fix(webui): unify app logos and brand mentions
This commit is contained in:
1 parent
bfb4f021ed
commit
b6122b9018
10 files changed
+752
-89
No files matched your search
@@ -10,6 +10,7 @@ import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import { sessionHandleColor } from "@/lib/session-handle";
|
||||
import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { composerMentionLabel } from "@/lib/composer-mention-text";
|
||||
|
||||
type CliAppMentionSegment =
|
||||
| { kind: "text"; text: string }
|
||||
@@ -185,7 +186,10 @@ function CliAppMentionToken({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const color = app.brand_color || INLINE_TOKEN_HIGHLIGHT_COLOR;
|
||||
const mentionName = label.startsWith("@") ? label.slice(1) : label;
|
||||
const displayName = app.display_name?.trim() || app.name;
|
||||
const mentionName = variant === "message"
|
||||
? displayName
|
||||
: composerMentionLabel({ kind: "cli", text: label, app }).slice(1);
|
||||
const logoUrls = useMemo(() => logoFallbackUrls(app.logo_url), [app.logo_url]);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
|
||||
const showLogo = Boolean(logoUrl);
|
||||
@@ -194,12 +198,20 @@ function CliAppMentionToken({
|
||||
return (
|
||||
<InlineTokenHighlight
|
||||
testId={`${testIdPrefix}-cli-mention-${app.name}`}
|
||||
title={t("thread.composer.mentions.cliTitle", { name: app.display_name || app.name })}
|
||||
title={t("thread.composer.mentions.cliTitle", {
|
||||
name: variant === "message" ? `${displayName} (${label})` : displayName,
|
||||
})}
|
||||
color={color}
|
||||
className={variant === "composer" ? "font-normal" : undefined}
|
||||
className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"}
|
||||
>
|
||||
<span
|
||||
className={cn("relative inline-block", showLogo && "text-transparent")}
|
||||
className={cn(
|
||||
"relative",
|
||||
variant === "composer" ? "inline" : "inline-block",
|
||||
variant === "message" && "shrink-0",
|
||||
showLogo && "text-transparent",
|
||||
showLogo && variant === "message" && "mr-1 w-[1.1em]",
|
||||
)}
|
||||
style={{ lineHeight: "inherit" }}
|
||||
>
|
||||
@
|
||||
@@ -207,9 +219,10 @@ function CliAppMentionToken({
|
||||
<span
|
||||
data-testid={`${testIdPrefix}-cli-mention-logo-${app.name}`}
|
||||
className={cn(
|
||||
"absolute left-1/2 top-1/2 grid place-items-center overflow-hidden rounded-mark",
|
||||
"-translate-x-1/2 -translate-y-1/2",
|
||||
isHero ? "h-[0.74em] w-[0.74em]" : "h-[0.72em] w-[0.72em]",
|
||||
"absolute left-0 top-1/2 grid -translate-y-1/2 place-items-center overflow-hidden rounded-[0.25em]",
|
||||
variant === "message"
|
||||
? "h-[1.1em] w-[1.1em]"
|
||||
: isHero ? "h-[0.92em] w-[0.92em]" : "h-[0.9em] w-[0.9em]",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
@@ -224,7 +237,7 @@ function CliAppMentionToken({
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
{mentionName}
|
||||
{variant === "message" ? <span className="min-w-0">{mentionName}</span> : mentionName}
|
||||
</InlineTokenHighlight>
|
||||
);
|
||||
}
|
||||
@@ -242,7 +255,10 @@ function McpPresetMentionToken({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const color = preset.brand_color || INLINE_TOKEN_HIGHLIGHT_COLOR;
|
||||
const mentionName = label.startsWith("@") ? label.slice(1) : label;
|
||||
const displayName = preset.display_name?.trim() || preset.name;
|
||||
const mentionName = variant === "message"
|
||||
? displayName
|
||||
: composerMentionLabel({ kind: "mcp", text: label, preset }).slice(1);
|
||||
const logoUrls = useMemo(() => logoFallbackUrls(preset.logo_url), [preset.logo_url]);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
|
||||
const showLogo = Boolean(logoUrl);
|
||||
@@ -251,12 +267,20 @@ function McpPresetMentionToken({
|
||||
return (
|
||||
<InlineTokenHighlight
|
||||
testId={`${testIdPrefix}-mcp-mention-${preset.name}`}
|
||||
title={t("thread.composer.mentions.mcpTitle", { name: preset.display_name || preset.name })}
|
||||
title={t("thread.composer.mentions.mcpTitle", {
|
||||
name: variant === "message" ? `${displayName} (${label})` : displayName,
|
||||
})}
|
||||
color={color}
|
||||
className={variant === "composer" ? "font-normal" : undefined}
|
||||
className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"}
|
||||
>
|
||||
<span
|
||||
className={cn("relative inline-block", showLogo && "text-transparent")}
|
||||
className={cn(
|
||||
"relative",
|
||||
variant === "composer" ? "inline" : "inline-block",
|
||||
variant === "message" && "shrink-0",
|
||||
showLogo && "text-transparent",
|
||||
showLogo && variant === "message" && "mr-1 w-[1.1em]",
|
||||
)}
|
||||
style={{ lineHeight: "inherit" }}
|
||||
>
|
||||
@
|
||||
@@ -264,9 +288,10 @@ function McpPresetMentionToken({
|
||||
<span
|
||||
data-testid={`${testIdPrefix}-mcp-mention-logo-${preset.name}`}
|
||||
className={cn(
|
||||
"absolute left-1/2 top-1/2 grid place-items-center overflow-hidden rounded-mark",
|
||||
"-translate-x-1/2 -translate-y-1/2",
|
||||
isHero ? "h-[0.74em] w-[0.74em]" : "h-[0.72em] w-[0.72em]",
|
||||
"absolute left-0 top-1/2 grid -translate-y-1/2 place-items-center overflow-hidden rounded-[0.25em]",
|
||||
variant === "message"
|
||||
? "h-[1.1em] w-[1.1em]"
|
||||
: isHero ? "h-[0.92em] w-[0.92em]" : "h-[0.9em] w-[0.9em]",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
@@ -281,7 +306,7 @@ function McpPresetMentionToken({
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
{mentionName}
|
||||
{variant === "message" ? <span className="min-w-0">{mentionName}</span> : mentionName}
|
||||
</InlineTokenHighlight>
|
||||
);
|
||||
}
|
||||
@@ -1342,8 +1342,8 @@ function McpPresetLogo({
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"grid shrink-0 place-items-center border border-border/45 bg-background",
|
||||
compact ? "h-10 w-10 rounded-control" : "h-11 w-11 rounded-compact",
|
||||
"grid shrink-0 place-items-center overflow-hidden",
|
||||
compact ? "h-10 w-10 rounded-control" : "h-9 w-9 rounded-[10px]",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
@@ -1351,7 +1351,7 @@ function McpPresetLogo({
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className={cn("object-contain", compact ? "h-[22px] w-[22px]" : "h-6 w-6")}
|
||||
className="h-full w-full object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
@@ -1364,7 +1364,7 @@ function McpPresetLogo({
|
||||
"grid shrink-0 place-items-center font-semibold text-white",
|
||||
compact
|
||||
? "h-10 w-10 rounded-control text-[12px]"
|
||||
: "h-11 w-11 rounded-compact text-[13px]",
|
||||
: "h-9 w-9 rounded-[10px] text-[12px]",
|
||||
)}
|
||||
style={{ backgroundColor: bg }}
|
||||
>
|
||||
@@ -1463,7 +1463,10 @@ function CliAppLogo({ app, showBrandLogos }: { app: CliAppInfo; showBrandLogos:
|
||||
|
||||
return (
|
||||
<span
|
||||
className="relative grid h-11 w-11 shrink-0 place-items-center overflow-hidden rounded-compact border border-border/45 bg-muted text-[13px] font-semibold"
|
||||
className={cn(
|
||||
"relative grid h-9 w-9 shrink-0 place-items-center overflow-hidden rounded-[10px] text-[12px] font-semibold",
|
||||
showRemoteLogo && logoLoaded ? "bg-transparent" : "bg-muted",
|
||||
)}
|
||||
style={{ color: app.brand_color || "hsl(var(--muted-foreground))" }}
|
||||
>
|
||||
<span
|
||||
@@ -1484,7 +1487,7 @@ function CliAppLogo({ app, showBrandLogos }: { app: CliAppInfo; showBrandLogos:
|
||||
referrerPolicy="no-referrer"
|
||||
draggable={false}
|
||||
className={cn(
|
||||
"absolute h-6 w-6 object-contain transition-opacity duration-150 motion-reduce:transition-none",
|
||||
"absolute h-full w-full object-contain transition-opacity duration-150 motion-reduce:transition-none",
|
||||
logoLoaded ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
onLoad={onLogoLoad}
|
||||
|
||||
@@ -86,6 +86,7 @@ import {
|
||||
type RestoredReadyImage,
|
||||
} from "@/hooks/useAttachedImages";
|
||||
import { useClipboardAndDrop } from "@/hooks/useClipboardAndDrop";
|
||||
import { useComposerMentionInput } from "@/hooks/useComposerMentionInput";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
|
||||
@@ -960,6 +961,7 @@ export function ThreadComposer({
|
||||
const [queuedPrompts, setQueuedPrompts] = useState<QueuedPrompt[]>([]);
|
||||
const hasTouchPrimaryPointer = useMediaQuery("(hover: none) and (pointer: coarse)");
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const mentionOverlayRef = useRef<HTMLDivElement>(null);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
@@ -1283,6 +1285,20 @@ export function ThreadComposer({
|
||||
() => splitCapabilityMentionSegments(value, cliApps, mcpPresets, selectedSessionMentions),
|
||||
[cliApps, mcpPresets, selectedSessionMentions, value],
|
||||
);
|
||||
const editMentionInput = useCallback((next: string, cursor: number) => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
setValue(next);
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setCursorPosition(cursor);
|
||||
}, []);
|
||||
const mentionInput = useComposerMentionInput({
|
||||
segments: mentionSegments,
|
||||
inputRef: textareaRef,
|
||||
onEdit: editMentionInput,
|
||||
resetKey: pendingQueueKey,
|
||||
});
|
||||
const { rawSelection, replace: replaceMentionInput } = mentionInput;
|
||||
const sessionDragInsertion = sessionDragPreview
|
||||
? mentionInsertion(
|
||||
value,
|
||||
@@ -1298,7 +1314,7 @@ export function ThreadComposer({
|
||||
mcpPresets,
|
||||
[...selectedSessionMentions, sessionDragPreview.mention],
|
||||
)
|
||||
: mentionSegments;
|
||||
: mentionInput.segments;
|
||||
const activeSessionMentions = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
return mentionSegments.flatMap((segment) => {
|
||||
@@ -1502,6 +1518,14 @@ export function ThreadComposer({
|
||||
});
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el || mentionInput.isComposing) return;
|
||||
el.style.height = "auto";
|
||||
el.style.height = `${Math.min(el.scrollHeight, 260)}px`;
|
||||
if (mentionOverlayRef.current) mentionOverlayRef.current.scrollTop = el.scrollTop;
|
||||
}, [mentionInput.isComposing, mentionInput.value]);
|
||||
|
||||
// Runs before paint so switching sessions never flashes stale draft text.
|
||||
useLayoutEffect(() => {
|
||||
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
|
||||
@@ -1628,14 +1652,7 @@ export function ThreadComposer({
|
||||
const inserted = `${command.command}${suffix.startsWith(" ") ? "" : " "}`;
|
||||
const next = `${value.slice(0, skillQuery.start)}${inserted}${suffix}`;
|
||||
const nextCursor = skillQuery.start + inserted.length;
|
||||
setValue(next);
|
||||
setCursorPosition(nextCursor);
|
||||
requestAnimationFrame(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(nextCursor, nextCursor);
|
||||
});
|
||||
replaceMentionInput(next, nextCursor);
|
||||
} else {
|
||||
setValue(command.argHint ? `${command.command} ` : command.command);
|
||||
}
|
||||
@@ -1644,7 +1661,7 @@ export function ThreadComposer({
|
||||
setInlineError(null);
|
||||
resizeTextarea();
|
||||
},
|
||||
[isStreaming, onStop, recentSlashCommands, resizeTextarea, skillQuery, value],
|
||||
[isStreaming, onStop, recentSlashCommands, replaceMentionInput, resizeTextarea, skillQuery, value],
|
||||
);
|
||||
|
||||
const insertMentionCandidate = useCallback(
|
||||
@@ -1664,20 +1681,13 @@ export function ThreadComposer({
|
||||
]);
|
||||
}
|
||||
const insertion = mentionInsertion(value, candidate.name, start, end);
|
||||
setValue(insertion.value);
|
||||
setCursorPosition(insertion.cursor);
|
||||
replaceMentionInput(insertion.value, insertion.cursor);
|
||||
setCliAppMenuDismissed(true);
|
||||
setSlashMenuDismissed(false);
|
||||
setInlineError(null);
|
||||
resizeTextarea();
|
||||
requestAnimationFrame(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(insertion.cursor, insertion.cursor);
|
||||
});
|
||||
},
|
||||
[activeSessionMentions, resizeTextarea, value],
|
||||
[activeSessionMentions, replaceMentionInput, resizeTextarea, value],
|
||||
);
|
||||
|
||||
const chooseMentionCandidate = useCallback(
|
||||
@@ -1700,7 +1710,7 @@ export function ThreadComposer({
|
||||
(candidate) => candidate.session_key === (sessionKey ?? preview?.mention.session_key),
|
||||
);
|
||||
if (!mention) return true;
|
||||
const caret = preview?.start ?? textareaRef.current?.selectionStart ?? value.length;
|
||||
const caret = preview?.start ?? rawSelection().start;
|
||||
insertMentionCandidate(
|
||||
{
|
||||
kind: "session",
|
||||
@@ -1709,13 +1719,14 @@ export function ThreadComposer({
|
||||
mention,
|
||||
},
|
||||
caret,
|
||||
preview?.end ?? textareaRef.current?.selectionEnd ?? caret,
|
||||
preview?.end ?? rawSelection().end,
|
||||
);
|
||||
return true;
|
||||
}, [
|
||||
availableSessionMentions,
|
||||
insertMentionCandidate,
|
||||
interactionDisabled,
|
||||
rawSelection,
|
||||
sessionDragPreview,
|
||||
value.length,
|
||||
]);
|
||||
@@ -1741,8 +1752,7 @@ export function ThreadComposer({
|
||||
}
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
const start = textareaRef.current?.selectionStart ?? value.length;
|
||||
const end = textareaRef.current?.selectionEnd ?? start;
|
||||
const { start, end } = rawSelection();
|
||||
setSessionDragPreview((current) => (
|
||||
current?.mention.session_key === mention.session_key
|
||||
&& current.start === start
|
||||
@@ -1751,7 +1761,7 @@ export function ThreadComposer({
|
||||
: { mention, start, end }
|
||||
));
|
||||
return true;
|
||||
}, [activeSessionMentions, availableSessionMentions, interactionDisabled, value.length]);
|
||||
}, [activeSessionMentions, availableSessionMentions, interactionDisabled, rawSelection]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionDragPreview) return;
|
||||
@@ -1821,12 +1831,11 @@ export function ThreadComposer({
|
||||
const editQueuedPrompt = useCallback((prompt: QueuedPrompt) => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
setQueuedPrompts((items) => items.filter((item) => item.id !== prompt.id));
|
||||
setValue(prompt.text);
|
||||
replaceMentionInput(prompt.text, prompt.text.length);
|
||||
setSelectedSessionMentions(prompt.sessionMentions ?? []);
|
||||
setInlineError(null);
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setCursorPosition(prompt.text.length);
|
||||
onQuotedContextChange?.(prompt.quotedContext ?? null);
|
||||
if (prompt.images?.length) {
|
||||
restoreReadyImages(prompt.images as RestoredReadyImage[]);
|
||||
@@ -1834,13 +1843,7 @@ export function ThreadComposer({
|
||||
clear();
|
||||
}
|
||||
resizeTextarea();
|
||||
requestAnimationFrame(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(prompt.text.length, prompt.text.length);
|
||||
});
|
||||
}, [clear, onQuotedContextChange, resizeTextarea, restoreReadyImages]);
|
||||
}, [clear, onQuotedContextChange, replaceMentionInput, resizeTextarea, restoreReadyImages]);
|
||||
|
||||
const moveQueuedPrompt = useCallback((dragId: string, targetId: string) => {
|
||||
if (dragId === targetId) return;
|
||||
@@ -2058,6 +2061,8 @@ export function ThreadComposer({
|
||||
]);
|
||||
|
||||
const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
|
||||
mentionInput.onKeyDown(e);
|
||||
if (e.defaultPrevented || e.nativeEvent.isComposing || mentionInput.isComposing) return;
|
||||
if (showCliAppMenu) {
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
@@ -2392,8 +2397,10 @@ export function ThreadComposer({
|
||||
<div className="thread-composer-input relative min-w-0">
|
||||
{hasMentionDecorations ? (
|
||||
<ComposerCliMentionOverlay
|
||||
overlayRef={mentionOverlayRef}
|
||||
segments={displayMentionSegments}
|
||||
isHero={isHero}
|
||||
isComposing={mentionInput.isComposing}
|
||||
className={inputTextClasses}
|
||||
ghostRange={sessionDragInsertion
|
||||
? { start: sessionDragInsertion.tokenStart, end: sessionDragInsertion.tokenEnd }
|
||||
@@ -2402,25 +2409,26 @@ export function ThreadComposer({
|
||||
) : null}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={value}
|
||||
value={mentionInput.value}
|
||||
onFocus={() => {
|
||||
if (compactWhenIdle) setComposerFocused(true);
|
||||
}}
|
||||
onChange={(e) => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
setValue(e.target.value);
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setCursorPosition(e.target.selectionStart ?? e.target.value.length);
|
||||
}}
|
||||
onChange={mentionInput.onChange}
|
||||
onCompositionStart={mentionInput.onCompositionStart}
|
||||
onCompositionEnd={mentionInput.onCompositionEnd}
|
||||
onBlur={() => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
}}
|
||||
onInput={onInput}
|
||||
onKeyDown={onKeyDown}
|
||||
onKeyUp={(e) => setCursorPosition(e.currentTarget.selectionStart ?? e.currentTarget.value.length)}
|
||||
onSelect={(e) => setCursorPosition(e.currentTarget.selectionStart ?? e.currentTarget.value.length)}
|
||||
onClick={(e) => setCursorPosition(e.currentTarget.selectionStart ?? e.currentTarget.value.length)}
|
||||
onKeyUp={() => setCursorPosition(rawSelection().start)}
|
||||
onSelect={() => setCursorPosition(rawSelection().start)}
|
||||
onClick={() => setCursorPosition(rawSelection().start)}
|
||||
onCopy={mentionInput.onCopy}
|
||||
onCut={mentionInput.onCut}
|
||||
onScroll={(e) => {
|
||||
if (mentionOverlayRef.current) mentionOverlayRef.current.scrollTop = e.currentTarget.scrollTop;
|
||||
}}
|
||||
onPaste={onPaste}
|
||||
rows={1}
|
||||
placeholder={sessionDragPreview ? "" : resolvedPlaceholder}
|
||||
@@ -2428,7 +2436,7 @@ export function ThreadComposer({
|
||||
aria-label={inputAriaLabel ?? t("thread.composer.inputAria")}
|
||||
className={cn(
|
||||
inputTextClasses,
|
||||
"relative z-10 caret-foreground placeholder:text-muted-foreground/70",
|
||||
"relative z-10 block caret-foreground placeholder:text-muted-foreground/70",
|
||||
"focus:outline-none focus-visible:outline-none",
|
||||
"disabled:cursor-not-allowed",
|
||||
hasMentionDecorations && "text-transparent selection:bg-primary/20",
|
||||
@@ -2830,23 +2838,31 @@ function QueuedPromptRow({
|
||||
}
|
||||
|
||||
function ComposerCliMentionOverlay({
|
||||
overlayRef,
|
||||
segments,
|
||||
isHero,
|
||||
isComposing,
|
||||
className,
|
||||
ghostRange,
|
||||
}: {
|
||||
overlayRef: Ref<HTMLDivElement>;
|
||||
segments: CapabilityMentionSegment[];
|
||||
isHero: boolean;
|
||||
isComposing: boolean;
|
||||
className: string;
|
||||
ghostRange?: { start: number; end: number } | null;
|
||||
}) {
|
||||
let offset = 0;
|
||||
const occurrences = new Map<string, number>();
|
||||
return (
|
||||
<div
|
||||
ref={overlayRef}
|
||||
aria-hidden
|
||||
className={cn(
|
||||
className,
|
||||
"pointer-events-none absolute inset-0 z-0 overflow-hidden whitespace-pre-wrap break-words text-foreground",
|
||||
// Native IME selection backgrounds can be opaque; keep the mirrored glyphs visible.
|
||||
isComposing && "z-20",
|
||||
)}
|
||||
>
|
||||
{segments.map((segment, index) => {
|
||||
@@ -2856,9 +2872,13 @@ function ComposerCliMentionOverlay({
|
||||
return <span key={`text-${index}`}>{segment.text}</span>;
|
||||
}
|
||||
const isGhost = ghostRange?.start === start && ghostRange.end === offset;
|
||||
const identity = `${segment.kind}-${segment.kind === "cli"
|
||||
? segment.app.name : segment.kind === "mcp" ? segment.preset.name : segment.mention.session_key}`;
|
||||
const occurrence = occurrences.get(identity) ?? 0;
|
||||
occurrences.set(identity, occurrence + 1);
|
||||
return (
|
||||
<span
|
||||
key={`${segment.kind}-${index}`}
|
||||
key={`${identity}-${occurrence}`}
|
||||
data-testid={isGhost ? "composer-session-drag-preview" : undefined}
|
||||
className={cn(isGhost && "opacity-45 transition-opacity duration-100")}
|
||||
>
|
||||
@@ -2870,6 +2890,7 @@ function ComposerCliMentionOverlay({
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{segments.at(-1)?.text.endsWith("\n") ? "\u200b" : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ChangeEvent, ClipboardEvent, KeyboardEvent, RefObject } from "react";
|
||||
|
||||
import type { CapabilityMentionSegment } from "@/components/CliAppMentionText";
|
||||
import { composerCompositionSegments, composerMentionText, editComposerMentionText, mentionTextOffset } from "@/lib/composer-mention-text";
|
||||
|
||||
type Snapshot = { value: string; start: number; end: number };
|
||||
const HISTORY_LIMIT = 100;
|
||||
|
||||
export function useComposerMentionInput({
|
||||
segments,
|
||||
inputRef,
|
||||
onEdit,
|
||||
resetKey,
|
||||
}: {
|
||||
segments: CapabilityMentionSegment[];
|
||||
inputRef: RefObject<HTMLTextAreaElement>;
|
||||
onEdit: (value: string, cursor: number) => void;
|
||||
resetKey?: string | null;
|
||||
}) {
|
||||
const text = useMemo(() => composerMentionText(segments), [segments]);
|
||||
const textRef = useRef(text);
|
||||
const pendingSelection = useRef<{ start: number; end: number } | null>(null);
|
||||
const history = useRef<{ undo: Snapshot[]; redo: Snapshot[] }>({ undo: [], redo: [] });
|
||||
const lastEdit = useRef({ type: "", at: 0, cursor: -1 });
|
||||
const composing = useRef(false);
|
||||
const [compositionValue, setCompositionValue] = useState<string | null>(null);
|
||||
const compositionStart = useRef(text);
|
||||
const compositionSegments = useRef(segments);
|
||||
const compositionSelection = useRef<{ start: number; end: number }>();
|
||||
const lastSelection = useRef({ start: 0, end: 0 });
|
||||
const previousResetKey = useRef(resetKey);
|
||||
|
||||
const rawSelection = useCallback(() => {
|
||||
const el = inputRef.current;
|
||||
const start = el?.selectionStart ?? textRef.current.display.length;
|
||||
const end = el?.selectionEnd ?? start;
|
||||
const selection = {
|
||||
start: mentionTextOffset(textRef.current, start, "toRaw", start === end ? "nearest" : "start"),
|
||||
end: mentionTextOffset(textRef.current, end, "toRaw", start === end ? "nearest" : "end"),
|
||||
};
|
||||
lastSelection.current = selection;
|
||||
return selection;
|
||||
}, [inputRef]);
|
||||
|
||||
const selectRaw = useCallback((start: number, end = start) => {
|
||||
inputRef.current?.setSelectionRange(
|
||||
mentionTextOffset(textRef.current, start, "toDisplay", "start"),
|
||||
mentionTextOffset(textRef.current, end, "toDisplay", "end"),
|
||||
);
|
||||
lastSelection.current = { start, end };
|
||||
}, [inputRef]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (previousResetKey.current !== resetKey) {
|
||||
previousResetKey.current = resetKey;
|
||||
history.current = { undo: [], redo: [] };
|
||||
pendingSelection.current = null;
|
||||
composing.current = false;
|
||||
setCompositionValue(null);
|
||||
lastEdit.current.type = "";
|
||||
}
|
||||
// Keep picker insertion undoable, but never restore a sent draft or another session's text.
|
||||
if (text.raw !== textRef.current.raw && !pendingSelection.current) {
|
||||
if (!text.raw) history.current = { undo: [], redo: [] };
|
||||
else {
|
||||
history.current.undo.push({ value: textRef.current.raw, ...lastSelection.current });
|
||||
if (history.current.undo.length > HISTORY_LIMIT) history.current.undo.shift();
|
||||
history.current.redo = [];
|
||||
}
|
||||
lastEdit.current.type = "";
|
||||
}
|
||||
textRef.current = text;
|
||||
if (!composing.current && pendingSelection.current) {
|
||||
const { start, end } = pendingSelection.current;
|
||||
selectRaw(start, end);
|
||||
pendingSelection.current = null;
|
||||
}
|
||||
});
|
||||
|
||||
const apply = useCallback((value: string, cursor: number, type = "", selection = rawSelection()) => {
|
||||
const previous = textRef.current;
|
||||
if (value !== previous.raw) {
|
||||
const now = Date.now();
|
||||
const coalesce = type && type === lastEdit.current.type && now - lastEdit.current.at < 750
|
||||
&& selection.start === selection.end && selection.start === lastEdit.current.cursor;
|
||||
if (!coalesce) {
|
||||
history.current.undo.push({ value: previous.raw, ...selection });
|
||||
if (history.current.undo.length > HISTORY_LIMIT) history.current.undo.shift();
|
||||
}
|
||||
history.current.redo = [];
|
||||
lastEdit.current = { type, at: now, cursor };
|
||||
}
|
||||
pendingSelection.current = value === previous.raw ? null : { start: cursor, end: cursor };
|
||||
onEdit(value, cursor);
|
||||
}, [onEdit, rawSelection]);
|
||||
|
||||
const beforeSelection = useRef<{ start: number; end: number; raw: { start: number; end: number } } | null>(null);
|
||||
const captureSelection = useCallback(() => {
|
||||
const el = inputRef.current;
|
||||
if (el) beforeSelection.current = { start: el.selectionStart, end: el.selectionEnd, raw: rawSelection() };
|
||||
}, [inputRef, rawSelection]);
|
||||
const onChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
|
||||
if (composing.current || (event.nativeEvent as InputEvent).isComposing) {
|
||||
if (!composing.current && compositionValue === null) {
|
||||
compositionSegments.current = segments;
|
||||
compositionSelection.current = beforeSelection.current ?? undefined;
|
||||
}
|
||||
setCompositionValue(event.target.value);
|
||||
return;
|
||||
}
|
||||
setCompositionValue(null);
|
||||
const edited = editComposerMentionText(textRef.current, event.target.value, event.target.selectionStart,
|
||||
beforeSelection.current ?? undefined);
|
||||
apply(edited.value, edited.cursor, (event.nativeEvent as InputEvent).inputType,
|
||||
beforeSelection.current?.raw);
|
||||
beforeSelection.current = null;
|
||||
};
|
||||
|
||||
const undo = useCallback((redo: boolean) => {
|
||||
const from = redo ? history.current.redo : history.current.undo;
|
||||
const to = redo ? history.current.undo : history.current.redo;
|
||||
const snapshot = from.pop();
|
||||
if (!snapshot) return;
|
||||
to.push({ value: textRef.current.raw, ...rawSelection() });
|
||||
pendingSelection.current = snapshot;
|
||||
lastEdit.current.type = "";
|
||||
onEdit(snapshot.value, snapshot.start);
|
||||
}, [onEdit, rawSelection]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = inputRef.current;
|
||||
if (!el) return;
|
||||
const beforeInput = (event: InputEvent) => {
|
||||
if (event.inputType === "historyUndo" || event.inputType === "historyRedo") {
|
||||
event.preventDefault();
|
||||
undo(event.inputType === "historyRedo");
|
||||
} else {
|
||||
captureSelection();
|
||||
}
|
||||
};
|
||||
el.addEventListener("beforeinput", beforeInput);
|
||||
return () => el.removeEventListener("beforeinput", beforeInput);
|
||||
}, [captureSelection, inputRef, undo]);
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (composing.current || event.nativeEvent.isComposing) return;
|
||||
const key = event.key.toLowerCase();
|
||||
if ((event.metaKey || event.ctrlKey) && !event.altKey && (key === "z" || key === "y")) {
|
||||
event.preventDefault();
|
||||
undo(key === "y" || event.shiftKey);
|
||||
}
|
||||
captureSelection();
|
||||
};
|
||||
|
||||
const copy = (event: ClipboardEvent<HTMLTextAreaElement>, cut: boolean) => {
|
||||
const selection = rawSelection();
|
||||
if (selection.start === selection.end) return;
|
||||
event.preventDefault();
|
||||
event.clipboardData.setData("text/plain", textRef.current.raw.slice(selection.start, selection.end));
|
||||
if (cut) apply(textRef.current.raw.slice(0, selection.start) + textRef.current.raw.slice(selection.end), selection.start);
|
||||
};
|
||||
|
||||
return {
|
||||
value: compositionValue ?? text.display,
|
||||
segments: compositionValue === null ? segments : composerCompositionSegments(
|
||||
compositionSegments.current, compositionValue, compositionSelection.current,
|
||||
),
|
||||
isComposing: compositionValue !== null,
|
||||
rawSelection,
|
||||
replace: apply,
|
||||
onChange,
|
||||
onKeyDown,
|
||||
onCopy: (event: ClipboardEvent<HTMLTextAreaElement>) => copy(event, false),
|
||||
onCut: (event: ClipboardEvent<HTMLTextAreaElement>) => copy(event, true),
|
||||
onCompositionStart: () => {
|
||||
composing.current = true;
|
||||
compositionStart.current = textRef.current;
|
||||
compositionSegments.current = segments;
|
||||
const el = inputRef.current;
|
||||
compositionSelection.current = el ? { start: el.selectionStart, end: el.selectionEnd } : undefined;
|
||||
setCompositionValue(inputRef.current?.value ?? textRef.current.display);
|
||||
},
|
||||
onCompositionEnd: () => {
|
||||
if (!composing.current) return;
|
||||
const el = inputRef.current;
|
||||
composing.current = false;
|
||||
setCompositionValue(null);
|
||||
if (!el) return;
|
||||
const edited = editComposerMentionText(compositionStart.current, el.value, el.selectionStart, compositionSelection.current);
|
||||
apply(edited.value, edited.cursor);
|
||||
beforeSelection.current = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { CapabilityMentionSegment } from "@/components/CliAppMentionText";
|
||||
|
||||
export function composerMentionLabel(segment: CapabilityMentionSegment): string {
|
||||
const app = segment.kind === "cli" ? segment.app : segment.kind === "mcp" ? segment.preset : null;
|
||||
if (!app) return segment.text;
|
||||
// A no-break space gives logos breathing room without separating them from the name.
|
||||
// Keep it in both the textarea and overlay, including while a logo is loading or unavailable.
|
||||
const gap = app.logo_url ? "\u00a0" : "";
|
||||
return `@${gap}${app.display_name?.trim().replace(/[\r\n\t]/g, " ") || app.name}`;
|
||||
}
|
||||
|
||||
type MentionRange = { start: number; end: number; displayStart: number; displayEnd: number };
|
||||
export interface ComposerMentionText {
|
||||
raw: string;
|
||||
display: string;
|
||||
mentions: MentionRange[];
|
||||
}
|
||||
|
||||
/** The textarea and its overlay share display text; only the draft uses invocation identifiers. */
|
||||
export function composerMentionText(segments: CapabilityMentionSegment[]): ComposerMentionText {
|
||||
let raw = "";
|
||||
let display = "";
|
||||
const mentions: MentionRange[] = [];
|
||||
for (const segment of segments) {
|
||||
const label = composerMentionLabel(segment);
|
||||
if (segment.kind === "cli" || segment.kind === "mcp") {
|
||||
mentions.push({
|
||||
start: raw.length,
|
||||
end: raw.length + segment.text.length,
|
||||
displayStart: display.length,
|
||||
displayEnd: display.length + label.length,
|
||||
});
|
||||
}
|
||||
raw += segment.text;
|
||||
display += label;
|
||||
}
|
||||
return { raw, display, mentions };
|
||||
}
|
||||
|
||||
/** Decorate only untouched mentions while mirroring the IME's exact, uncommitted text. */
|
||||
export function composerCompositionSegments(
|
||||
segments: CapabilityMentionSegment[],
|
||||
display: string,
|
||||
selection?: { start: number; end: number },
|
||||
): CapabilityMentionSegment[] {
|
||||
const previous = segments.map(composerMentionLabel).join("");
|
||||
if (previous === display) return segments;
|
||||
let start = 0;
|
||||
while (start < Math.min(previous.length, display.length, selection?.start ?? Infinity)
|
||||
&& previous[start] === display[start]) start++;
|
||||
let end = previous.length;
|
||||
let nextEnd = display.length;
|
||||
while (end > Math.max(start, selection?.end ?? 0) && nextEnd > start
|
||||
&& previous[end - 1] === display[nextEnd - 1]) {
|
||||
end--;
|
||||
nextEnd--;
|
||||
}
|
||||
|
||||
const result: CapabilityMentionSegment[] = [];
|
||||
let offset = 0;
|
||||
let cursor = 0;
|
||||
for (const segment of segments) {
|
||||
const label = composerMentionLabel(segment);
|
||||
const segmentStart = offset;
|
||||
offset += label.length;
|
||||
if (segment.kind === "text" || (offset > start && segmentStart < end)) continue;
|
||||
const shiftedStart = segmentStart >= end ? segmentStart + nextEnd - end : segmentStart;
|
||||
if (shiftedStart > cursor) result.push({ kind: "text", text: display.slice(cursor, shiftedStart) });
|
||||
result.push(segment);
|
||||
cursor = shiftedStart + label.length;
|
||||
}
|
||||
if (cursor < display.length) result.push({ kind: "text", text: display.slice(cursor) });
|
||||
return result;
|
||||
}
|
||||
|
||||
export function mentionTextOffset(
|
||||
text: ComposerMentionText,
|
||||
offset: number,
|
||||
direction: "toRaw" | "toDisplay",
|
||||
bias: "start" | "end" | "nearest" = "nearest",
|
||||
): number {
|
||||
offset = Math.max(0, Math.min(offset, direction === "toRaw" ? text.display.length : text.raw.length));
|
||||
let delta = 0;
|
||||
for (const mention of text.mentions) {
|
||||
const [start, end, targetStart, targetEnd] = direction === "toRaw"
|
||||
? [mention.displayStart, mention.displayEnd, mention.start, mention.end]
|
||||
: [mention.start, mention.end, mention.displayStart, mention.displayEnd];
|
||||
if (offset <= start) break;
|
||||
if (offset < end) {
|
||||
return bias === "start" || (bias === "nearest" && offset - start < end - offset)
|
||||
? targetStart : targetEnd;
|
||||
}
|
||||
delta = targetEnd - end;
|
||||
}
|
||||
return offset + delta;
|
||||
}
|
||||
|
||||
/** Apply a native textarea edit, retaining the identities of untouched mentions. */
|
||||
export function editComposerMentionText(
|
||||
text: ComposerMentionText,
|
||||
nextDisplay: string,
|
||||
caret: number,
|
||||
selection?: { start: number; end: number },
|
||||
): { value: string; cursor: number } {
|
||||
let start = 0;
|
||||
// The caret disambiguates repeated text (e.g. inserting a space before an existing space).
|
||||
while (start < Math.min(text.display.length, nextDisplay.length, caret, selection?.start ?? Infinity)
|
||||
&& text.display[start] === nextDisplay[start]) start++;
|
||||
let end = text.display.length;
|
||||
let nextEnd = nextDisplay.length;
|
||||
while (end > Math.max(start, selection?.end ?? 0) && nextEnd > Math.max(start, caret)
|
||||
&& text.display[end - 1] === nextDisplay[nextEnd - 1]) {
|
||||
end--;
|
||||
nextEnd--;
|
||||
}
|
||||
// A partial deletion/replacement removes the mention as a unit, never a broken identifier.
|
||||
const rawStart = mentionTextOffset(text, start, "toRaw", "start");
|
||||
const rawEnd = mentionTextOffset(text, end, "toRaw", "end");
|
||||
const inserted = nextDisplay.slice(start, nextEnd);
|
||||
const value = text.raw.slice(0, rawStart) + inserted + text.raw.slice(rawEnd);
|
||||
return { value, cursor: Math.min(value.length, rawStart + Math.max(0, caret - start)) };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { splitCapabilityMentionSegments } from "@/components/CliAppMentionText";
|
||||
import { composerCompositionSegments, composerMentionLabel, composerMentionText, editComposerMentionText, mentionTextOffset } from "@/lib/composer-mention-text";
|
||||
import type { CliAppInfo } from "@/lib/types";
|
||||
|
||||
const apps = [
|
||||
["linear", "Linear"], ["drawio", "Draw.io"], ["drive", "Google Drive"],
|
||||
["iterm2", "iTerm2"], ["gimp", "GIMP"], ["custom", "本地应用"],
|
||||
["blank", " "], ["first", "Same Name"], ["second", "Same Name"],
|
||||
].map(([name, display_name]) => ({ name, display_name, installed: true }) as CliAppInfo);
|
||||
const project = (raw: string) => composerMentionText(splitCapabilityMentionSegments(raw, apps));
|
||||
|
||||
describe("composer mention display text", () => {
|
||||
it.each([
|
||||
["n @Linear @Google Drive", 0, 0, ["linear", "drive"]],
|
||||
["@Linear n @Google Drive", 8, 8, ["linear", "drive"]],
|
||||
["@Linear @Google Drive n", 21, 21, ["linear", "drive"]],
|
||||
["@Lin中ear @Google Drive", 4, 4, ["drive"]],
|
||||
["中 @Google Drive", 0, 7, ["drive"]],
|
||||
])("keeps untouched mention identities during IME input: %s", (display, start, end, names) => {
|
||||
const original = splitCapabilityMentionSegments("@linear @drive", apps);
|
||||
const segments = composerCompositionSegments(original, display, { start, end });
|
||||
expect(segments.map(composerMentionLabel).join("")).toBe(display);
|
||||
expect(segments.flatMap(segment => segment.kind === "cli" ? [segment.app.name] : [])).toEqual(names);
|
||||
});
|
||||
|
||||
it("keeps duplicate display names tied to their own identities during composition", () => {
|
||||
const original = splitCapabilityMentionSegments("@first @second", apps);
|
||||
const segments = composerCompositionSegments(original, "中 @Same Name", { start: 0, end: 10 });
|
||||
expect(segments.map(composerMentionLabel).join("")).toBe("中 @Same Name");
|
||||
expect(segments.flatMap(segment => segment.kind === "cli" ? [segment.app.name] : [])).toEqual(["second"]);
|
||||
expect(composerCompositionSegments(original, "@Same Name @Same Name")).toBe(original);
|
||||
});
|
||||
|
||||
it("adds a non-breaking logo gap only to display text and maps editing around it", () => {
|
||||
const app = { ...apps[0], logo_url: "https://example.invalid/linear.svg" };
|
||||
const text = composerMentionText(splitCapabilityMentionSegments("@linear next", [app]));
|
||||
expect(text.display).toBe("@\u00a0Linear next");
|
||||
expect(text.raw).toBe("@linear next");
|
||||
expect(mentionTextOffset(text, 8, "toRaw")).toBe(7);
|
||||
expect(mentionTextOffset(text, 7, "toDisplay")).toBe(8);
|
||||
expect(editComposerMentionText(text, "@\u00a0Linear! next", 9, { start: 8, end: 8 }))
|
||||
.toEqual({ value: "@linear! next", cursor: 8 });
|
||||
});
|
||||
|
||||
it("preserves brand spelling without changing the raw identifiers", () => {
|
||||
const raw = "@linear @drawio @drive @iterm2 @gimp @custom @blank @unknown";
|
||||
const text = project(raw);
|
||||
expect(text.raw).toBe(raw);
|
||||
expect(text.display).toBe("@Linear @Draw.io @Google Drive @iTerm2 @GIMP @本地应用 @blank @unknown");
|
||||
});
|
||||
|
||||
it("maps both ends of every mention and all surrounding text positions", () => {
|
||||
const text = project("请用 @drive 和 @drawio 处理\n文件");
|
||||
for (let raw = 0; raw <= text.raw.length; raw++) {
|
||||
if (text.mentions.some((mention) => raw > mention.start && raw < mention.end)) continue;
|
||||
expect(mentionTextOffset(text, mentionTextOffset(text, raw, "toDisplay"), "toRaw")).toBe(raw);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["@drive", "@Google Drive hello", 19, "@drive hello"],
|
||||
["@drive done", "@Google Drive !done", 15, "@drive !done"],
|
||||
["@drive @drawio", "@Google Drive @Draw.io", 14, "@drive @drawio"],
|
||||
["@drive done", "@Google Driv done", 12, " done"],
|
||||
["@drive done", "@oogle Drive done", 1, " done"],
|
||||
["@drive done", "@Google XDrive done", 9, "X done"],
|
||||
["@drive @drawio", "@Google Drive\n@Draw.io", 14, "@drive\n@drawio"],
|
||||
["@first @second", "@Same Name @Same Name!", 21, "@first @second!"],
|
||||
])("applies %s → %s without rewriting untouched mentions", (raw, display, caret, expected) => {
|
||||
expect(editComposerMentionText(project(raw), display, caret as number).value).toBe(expected);
|
||||
});
|
||||
|
||||
it("replaces a selected mention without losing a shared @ prefix", () => {
|
||||
expect(editComposerMentionText(project("@drive"), "@linear", 7, { start: 0, end: 13 }))
|
||||
.toEqual({ value: "@linear", cursor: 7 });
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import * as clipboard from "@/lib/clipboard";
|
||||
import { fmtDateTime, formatMessageEndTime } from "@/lib/format";
|
||||
import type {
|
||||
CliAppInfo,
|
||||
@@ -394,7 +395,7 @@ describe("MessageBubble", () => {
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("message-slash-command")).toHaveTextContent("/goal");
|
||||
expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@zoom");
|
||||
expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
|
||||
});
|
||||
|
||||
it("highlights skill references without a live skill catalog", () => {
|
||||
@@ -422,8 +423,8 @@ describe("MessageBubble", () => {
|
||||
expect(skill.getAttribute("style")).not.toContain("text-shadow");
|
||||
expect(skill.getAttribute("style")).toContain("var(--inline-token-highlight)");
|
||||
expect(skill.className).not.toMatch(/(?:^|\s)(?:bg-|border|ring|rounded)/);
|
||||
expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@zoom");
|
||||
expect(skill.parentElement).toHaveTextContent("Ask github to review this with @zoom");
|
||||
expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
|
||||
expect(skill.parentElement).toHaveTextContent("Ask github to review this with @Zoom");
|
||||
});
|
||||
|
||||
it("highlights well-formed skill references and leaves a bare marker plain", () => {
|
||||
@@ -566,14 +567,16 @@ describe("MessageBubble", () => {
|
||||
render(<MessageBubble message={message} cliApps={CLI_APPS} />);
|
||||
|
||||
const token = screen.getByTestId("message-cli-mention-zoom");
|
||||
expect(token).toHaveTextContent("@zoom");
|
||||
expect(token).toHaveAttribute("title", "CLI app: Zoom");
|
||||
expect(token).toHaveTextContent("@Zoom");
|
||||
expect(token).toHaveAttribute("title", "CLI app: Zoom (@zoom)");
|
||||
expect(token).toHaveClass("font-[550]");
|
||||
expect(token.className).not.toContain("rounded");
|
||||
expect(token.className).not.toContain("px-");
|
||||
expect(token.getAttribute("style")).toContain("color: #0B5CFF");
|
||||
expect(token.getAttribute("style")).not.toContain("text-shadow");
|
||||
expect(screen.getByTestId("message-cli-mention-logo-zoom")).toBeInTheDocument();
|
||||
const logo = screen.getByTestId("message-cli-mention-logo-zoom");
|
||||
expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
|
||||
expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
|
||||
expect(screen.queryByTestId("message-cli-mention-krita")).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/not @krita/)).toBeInTheDocument();
|
||||
});
|
||||
@@ -632,7 +635,7 @@ describe("MessageBubble", () => {
|
||||
render(<MessageBubble message={message} cliApps={[]} />);
|
||||
|
||||
const token = screen.getByTestId("message-cli-mention-drawio");
|
||||
expect(token).toHaveTextContent("@drawio");
|
||||
expect(token).toHaveTextContent("@Draw.io");
|
||||
expect(token.className).not.toContain("rounded");
|
||||
expect(token.className).not.toContain("px-");
|
||||
expect(token.getAttribute("style")).toContain("color: #F08705");
|
||||
@@ -650,10 +653,61 @@ describe("MessageBubble", () => {
|
||||
render(<MessageBubble message={message} mcpPresets={MCP_PRESETS} />);
|
||||
|
||||
const token = screen.getByTestId("message-mcp-mention-browserbase");
|
||||
expect(token).toHaveTextContent("@browserbase");
|
||||
expect(token).toHaveAttribute("title", "MCP server: Browserbase");
|
||||
expect(token).toHaveTextContent("@Browserbase");
|
||||
expect(token).toHaveAttribute("title", "MCP server: Browserbase (@browserbase)");
|
||||
expect(token.getAttribute("style")).toContain("color: #111827");
|
||||
expect(screen.getByTestId("message-mcp-mention-logo-browserbase")).toBeInTheDocument();
|
||||
const logo = screen.getByTestId("message-mcp-mention-logo-browserbase");
|
||||
expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
|
||||
expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
|
||||
});
|
||||
|
||||
it.each((["cli", "mcp"] as const).flatMap((kind) => [
|
||||
["linear", "Linear", "Linear"],
|
||||
["iterm2", "iTerm2", "iTerm2"],
|
||||
["drawio", "Draw.io", "Draw.io"],
|
||||
["gimp", "GIMP", "GIMP"],
|
||||
["google-drive", "Google Drive", "Google Drive"],
|
||||
["1password-cli", "1Password CLI", "1Password CLI"],
|
||||
["feishu-cli", "Feishu/Lark CLI", "Feishu/Lark CLI"],
|
||||
["local-app", " 本地应用 ", "本地应用"],
|
||||
["fallback-app", " ", "fallback-app"],
|
||||
].map(([name, displayName, expected]) => ({ kind, name, displayName, expected }))))(
|
||||
"uses the saved display name for $kind $name without rewriting its identifier",
|
||||
({ kind, name, displayName, expected }) => {
|
||||
const message: UIMessage = {
|
||||
id: "saved-app-name",
|
||||
role: "user",
|
||||
content: `Use @${name} please`,
|
||||
...(kind === "cli" ? {
|
||||
cliApps: [{ name, display_name: displayName, category: "test", entry_point: name }],
|
||||
} : {
|
||||
mcpPresets: [{ name, display_name: displayName, category: "test", transport: "stdio" }],
|
||||
}),
|
||||
};
|
||||
render(<MessageBubble message={message} />);
|
||||
const token = screen.getByTestId(`message-${kind}-mention-${name}`);
|
||||
expect(token.textContent).toBe(`@${expected}`);
|
||||
expect(token).toHaveAttribute("title", `${kind === "cli" ? "CLI app" : "MCP server"}: ${expected} (@${name})`);
|
||||
expect(token).toHaveClass("inline-flex", "items-baseline", "max-w-full", "[overflow-wrap:anywhere]");
|
||||
expect(token.firstElementChild).toHaveClass("shrink-0");
|
||||
expect(token.lastElementChild).toHaveClass("min-w-0");
|
||||
expect(message.content).toBe(`Use @${name} please`);
|
||||
},
|
||||
);
|
||||
|
||||
it("copies the original mention identifiers rather than display names", async () => {
|
||||
const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);
|
||||
try {
|
||||
render(<MessageBubble message={{
|
||||
id: "copy-display-name", role: "user", content: "Please use @drawio",
|
||||
cliApps: [{ name: "drawio", display_name: "Draw.io", category: "diagram", entry_point: "drawio" }],
|
||||
}} />);
|
||||
expect(screen.getByTestId("message-cli-mention-drawio")).toHaveTextContent("@Draw.io");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy", exact: true }));
|
||||
await waitFor(() => expect(copy).toHaveBeenCalledWith("Please use @drawio"));
|
||||
} finally {
|
||||
copy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders persisted session mentions inside sent user messages", () => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { expect, it, vi } from "vitest";
|
||||
import { installedMcpPresetsFromPayload } from "@/lib/mcp-preset-events";
|
||||
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import { __clearLogoFallbackCacheForTests } from "@/hooks/useLogoFallback";
|
||||
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
|
||||
|
||||
|
||||
@@ -209,6 +210,51 @@ describe("Settings system domains", () => {
|
||||
expect(mcpTitle.nextElementSibling).toHaveTextContent("0");
|
||||
});
|
||||
|
||||
it.each(["cli", "mcp"] as const)(
|
||||
"fills the rounded %s app icon without an inset tile and preserves its fallback",
|
||||
async (kind) => {
|
||||
__clearLogoFallbackCacheForTests();
|
||||
const name = kind === "cli" ? "AnyGen" : "Linear";
|
||||
const logoUrl = `/test-${kind}-logo.svg`;
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url === "/api/settings") return jsonResponse(settingsPayload());
|
||||
if (url === "/api/settings/cli-apps") {
|
||||
return jsonResponse({ apps: [{ ...installedAnyGen, logo_url: logoUrl }], installed_count: 1 });
|
||||
}
|
||||
if (url === "/api/settings/mcp-presets") {
|
||||
return jsonResponse({ presets: [{
|
||||
...agentPlugin,
|
||||
name: "linear",
|
||||
display_name: "Linear",
|
||||
source: "builtin",
|
||||
enabled: true,
|
||||
logo_url: logoUrl,
|
||||
}], installed_count: 1 });
|
||||
}
|
||||
return jsonResponse({});
|
||||
}));
|
||||
renderSettingsView({ initialSection: "apps", initialSettings: settingsPayload() });
|
||||
await screen.findByText("AnyGen");
|
||||
if (kind === "mcp") fireEvent.click(screen.getByRole("button", { name: "MCP", exact: true }));
|
||||
const row = (await screen.findByText(name)).closest("article")!;
|
||||
const image = row.querySelector("img")!;
|
||||
expect(image).toHaveAttribute("src", logoUrl);
|
||||
expect(image).toHaveClass("h-full", "w-full", "object-contain");
|
||||
fireEvent.load(image);
|
||||
expect(image.parentElement).toHaveClass("h-9", "w-9", "overflow-hidden", "rounded-[10px]");
|
||||
for (const tileClass of ["border", "bg-background", "bg-muted"]) {
|
||||
expect(image.parentElement).not.toHaveClass(tileClass);
|
||||
}
|
||||
|
||||
fireEvent.error(image);
|
||||
expect(row.querySelector("img")).toBeNull();
|
||||
const fallback = within(row).getByText(name[0], { exact: true });
|
||||
expect(fallback).toBeVisible();
|
||||
expect(fallback.closest(".h-9")).toHaveClass("w-9", "rounded-[10px]");
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps skill group labels natural without changing grouping or filtering", () => {
|
||||
render(<ClientProvider client={{} as never} token="tok">
|
||||
<SkillsCatalogSettings skills={[
|
||||
|
||||
@@ -1707,8 +1707,8 @@ describe("ThreadComposer", () => {
|
||||
);
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
expect(input).toHaveValue("@blender ");
|
||||
expect(screen.getByTestId("composer-cli-mention-blender")).toHaveTextContent("@blender");
|
||||
expect(input).toHaveValue("@Blender ");
|
||||
expect(screen.getByTestId("composer-cli-mention-blender")).toHaveTextContent("@Blender");
|
||||
expect(screen.queryByTestId("composer-cli-app-tray")).not.toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole("listbox", { name: "Mentions" })).not.toBeInTheDocument();
|
||||
@@ -1789,8 +1789,8 @@ describe("ThreadComposer", () => {
|
||||
|
||||
fireEvent.keyDown(input, { key: "Tab" });
|
||||
|
||||
expect(input).toHaveValue("use @blender ");
|
||||
expect(screen.getByTestId("composer-cli-mention-blender")).toHaveTextContent("@blender");
|
||||
expect(input).toHaveValue("use @Blender ");
|
||||
expect(screen.getByTestId("composer-cli-mention-blender")).toHaveTextContent("@Blender");
|
||||
});
|
||||
|
||||
it("shows configured MCP presets in the mention palette and submits metadata", () => {
|
||||
@@ -1814,9 +1814,9 @@ describe("ThreadComposer", () => {
|
||||
|
||||
fireEvent.keyDown(input, { key: "Tab" });
|
||||
|
||||
expect(input).toHaveValue("use @browserbase ");
|
||||
expect(input).toHaveValue("use @\u00a0Browserbase ");
|
||||
const mention = screen.getByTestId("composer-mcp-mention-browserbase");
|
||||
expect(mention).toHaveTextContent("@browserbase");
|
||||
expect(mention.textContent).toBe("@\u00a0Browserbase");
|
||||
expect(mention).toHaveClass("font-normal");
|
||||
expect(mention).not.toHaveClass("font-[550]");
|
||||
|
||||
@@ -2201,7 +2201,7 @@ describe("ThreadComposer", () => {
|
||||
|
||||
fireEvent.keyDown(input, { key: "Tab" });
|
||||
|
||||
expect(input).toHaveValue("use @blender tonight");
|
||||
expect(input).toHaveValue("use @Blender tonight");
|
||||
});
|
||||
|
||||
it("renders a CLI app mention logo inline without moving the text cursor slot", () => {
|
||||
@@ -2218,9 +2218,9 @@ describe("ThreadComposer", () => {
|
||||
target: { value: "meeting in @gimp", selectionStart: 16 },
|
||||
});
|
||||
|
||||
expect(input).toHaveValue("meeting in @gimp");
|
||||
expect(input).toHaveValue("meeting in @\u00a0GIMP");
|
||||
const token = screen.getByTestId("composer-cli-mention-gimp");
|
||||
expect(token).toHaveTextContent("@gimp");
|
||||
expect(token.textContent).toBe("@\u00a0GIMP");
|
||||
expect(token).toHaveClass("font-normal");
|
||||
expect(token).not.toHaveClass("font-[550]");
|
||||
expect(token.className).not.toContain("zoom-in");
|
||||
@@ -2231,8 +2231,14 @@ describe("ThreadComposer", () => {
|
||||
expect(screen.queryByTestId("composer-cli-app-tray")).not.toBeInTheDocument();
|
||||
const logo = screen.getByTestId("composer-cli-mention-logo-gimp");
|
||||
expect(logo.className).toContain("top-1/2");
|
||||
expect(logo.className).toContain("left-1/2");
|
||||
expect(logo.className).toContain("left-0");
|
||||
expect(logo.className).not.toContain("-top-");
|
||||
expect(logo).toHaveClass("h-[0.9em]", "w-[0.9em]", "rounded-[0.25em]");
|
||||
// The shared text projection reserves the gap; no CSS margin may shift the caret.
|
||||
expect(logo.parentElement).toHaveTextContent("@");
|
||||
expect(logo.parentElement).toHaveClass("inline");
|
||||
expect(logo.parentElement).not.toHaveClass("inline-block");
|
||||
expect(logo.parentElement?.className).not.toMatch(/(?:^|\s)(?:w-|m[rlx]-|p[rlx]-)/);
|
||||
});
|
||||
|
||||
it("uses the shared accent when an installed CLI app has no brand metadata", () => {
|
||||
@@ -2271,6 +2277,117 @@ describe("ThreadComposer", () => {
|
||||
expect(token.getAttribute("style")).not.toContain("var(--primary)");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["linear", "Linear"], ["drawio", "Draw.io"], ["google-drive", "Google Drive"],
|
||||
["iterm2", "iTerm2"], ["gimp", "GIMP"], ["1password", "1Password"],
|
||||
["local", "本地应用"], ["fallback", " "],
|
||||
])("shows %s's brand in the input and sends its identifier", (name, displayName) => {
|
||||
const onSend = vi.fn();
|
||||
const app = { ...CLI_APPS[0], name, display_name: displayName };
|
||||
render(<ThreadComposer onSend={onSend} cliApps={[app]} />);
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: `请用 @${name} 帮我`, selectionStart: name.length + 5 } });
|
||||
const label = displayName.trim() || name;
|
||||
expect(input).toHaveValue(`请用 @\u00a0${label} 帮我`);
|
||||
expect(screen.getByTestId(`composer-cli-mention-${name}`).textContent).toBe(`@\u00a0${label}`);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onSend).toHaveBeenCalledWith(`请用 @${name} 帮我`, undefined, {
|
||||
cliApps: [expect.objectContaining({ name, display_name: displayName })],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps multiple long mentions intact while editing, copying, cutting and undoing", async () => {
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} cliApps={[
|
||||
{ ...CLI_APPS[0], name: "drive", display_name: "Google Drive" },
|
||||
{ ...CLI_APPS[1], name: "drawio", display_name: "Draw.io" },
|
||||
]} />);
|
||||
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
|
||||
fireEvent.change(input, { target: { value: "@drive @drawio" } });
|
||||
input.setSelectionRange(14, 14);
|
||||
await userEvent.type(input, " hello", { skipClick: true });
|
||||
expect(input).toHaveValue("@\u00a0Google Drive hello @Draw.io");
|
||||
input.setSelectionRange(0, 14);
|
||||
const setData = vi.fn();
|
||||
fireEvent.copy(input, { clipboardData: { setData } });
|
||||
expect(setData).toHaveBeenCalledWith("text/plain", "@drive");
|
||||
fireEvent.cut(input, { clipboardData: { setData } });
|
||||
expect(input).toHaveValue(" hello @Draw.io");
|
||||
fireEvent.keyDown(input, { key: "z", metaKey: true });
|
||||
expect(input).toHaveValue("@\u00a0Google Drive hello @Draw.io");
|
||||
fireEvent.keyDown(input, { key: "z", metaKey: true, shiftKey: true });
|
||||
expect(input).toHaveValue(" hello @Draw.io");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onSend).toHaveBeenCalledWith("hello @drawio", undefined, {
|
||||
cliApps: [expect.objectContaining({ name: "drawio" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes a brand mention as a unit and restores it on undo", async () => {
|
||||
render(<ThreadComposer onSend={vi.fn()} mcpPresets={[
|
||||
{ ...MCP_PRESETS[0], name: "drive", display_name: "Google Drive" },
|
||||
]} />);
|
||||
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
|
||||
fireEvent.change(input, { target: { value: "@drive!" } });
|
||||
input.setSelectionRange(14, 14);
|
||||
await userEvent.keyboard("{Backspace}");
|
||||
expect(input).toHaveValue("!");
|
||||
fireEvent.keyDown(input, { key: "z", ctrlKey: true });
|
||||
expect(input).toHaveValue("@\u00a0Google Drive!");
|
||||
});
|
||||
|
||||
it("does not interrupt Chinese composition or submit on an IME confirmation", () => {
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} cliApps={[
|
||||
{ ...CLI_APPS[0], name: "drive", display_name: "Google Drive" },
|
||||
]} />);
|
||||
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
|
||||
fireEvent.change(input, { target: { value: "@drive " } });
|
||||
const logo = screen.getByTestId("composer-cli-mention-logo-drive");
|
||||
fireEvent.compositionStart(input);
|
||||
expect(screen.getByTestId("composer-cli-mention-logo-drive")).toBe(logo);
|
||||
fireEvent.change(input, { target: { value: "@\u00a0Google Drive 中", selectionStart: 16 } });
|
||||
expect(input).toHaveValue("@\u00a0Google Drive 中");
|
||||
expect(input).toHaveClass("text-transparent");
|
||||
expect(input.previousElementSibling).toHaveClass("z-20");
|
||||
expect(screen.getByTestId("composer-cli-mention-logo-drive")).toBe(logo);
|
||||
expect(input.previousElementSibling?.textContent).toBe(input.value);
|
||||
fireEvent.keyDown(input, { key: "Enter", isComposing: true });
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
fireEvent.compositionEnd(input, { data: "中" });
|
||||
expect(input).toHaveValue("@\u00a0Google Drive 中");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onSend).toHaveBeenCalledWith("@drive 中", undefined, {
|
||||
cliApps: [expect.objectContaining({ name: "drive" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears mention editing and undo state when switching sessions during composition", () => {
|
||||
const props = { onSend: vi.fn(), cliApps: CLI_APPS };
|
||||
const { rerender } = render(<ThreadComposer {...props} pendingQueueKey="chat-a" />);
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "@gimp " } });
|
||||
fireEvent.compositionStart(input);
|
||||
fireEvent.change(input, { target: { value: "@\u00a0GIMP 草稿" } });
|
||||
rerender(<ThreadComposer {...props} pendingQueueKey="chat-b" />);
|
||||
expect(input).toHaveValue("");
|
||||
fireEvent.compositionEnd(input, { data: "草稿" });
|
||||
fireEvent.keyDown(input, { key: "z", metaKey: true });
|
||||
expect(input).toHaveValue("");
|
||||
});
|
||||
|
||||
it("mirrors the trailing empty line and scroll offset of a decorated textarea", () => {
|
||||
render(<ThreadComposer onSend={vi.fn()} cliApps={CLI_APPS} />);
|
||||
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
|
||||
fireEvent.change(input, { target: { value: "@gimp\n" } });
|
||||
const overlay = input.previousElementSibling as HTMLElement;
|
||||
expect(overlay.textContent).toBe("@\u00a0GIMP\n\u200b");
|
||||
expect(input).toHaveClass("block");
|
||||
input.scrollTop = 80;
|
||||
fireEvent.scroll(input);
|
||||
expect(overlay.scrollTop).toBe(80);
|
||||
});
|
||||
|
||||
it("opens the slash command palette downward when there is more room below", async () => {
|
||||
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue(
|
||||
rect({ top: 40, bottom: 160, width: 800, height: 120 }),
|
||||
|
||||
@@ -4459,8 +4459,9 @@ describe("ThreadShell", () => {
|
||||
|
||||
expect(screen.getByRole("option", { name: /@obsidian-agent-cli/i })).toBeInTheDocument();
|
||||
expect(screen.getByTestId("composer-cli-mention-obsidian-agent-cli")).toHaveTextContent(
|
||||
"@obsidian-agent-cli",
|
||||
"@Obsidian",
|
||||
);
|
||||
expect(input).toHaveValue("@Obsidian");
|
||||
});
|
||||
|
||||
it("offers sessions across projects in restricted mode", async () => {
|
||||
|
||||
Reference in new issue
Block a user