fix(webui): recognize typed session handles as references (#6311)

* fix(webui): recognize typed session handles as references

Refs NAN-286

* refactor(webui): simplify session reference handling

* fix(webui): recognize mentions after punctuation

* docs(webui): focus topic references on usage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-20 01:05:11 +08:00
1 parent 1f8e49c70a
commit 909b277e7a
7 files changed
+369 -144

No files matched your search

+9 -5
View File
@@ -10,7 +10,11 @@ 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, type CapabilityMentionSegment } from "@/lib/composer-mention-text";
import {
composerMentionLabel,
isCapabilityMentionStart,
type CapabilityMentionSegment,
} from "@/lib/composer-mention-text";
// Paint-only weight keeps the native textarea's regular-width caret and wrapping in sync.
const COMPOSER_BRAND_NAME_CLASS = "[-webkit-text-stroke:0.4px_currentColor]";
@@ -64,19 +68,19 @@ export function splitCapabilityMentionSegments(
}
const segments: CapabilityMentionSegment[] = [];
const mentionRe = /(^|[\s([{])@([\p{L}\p{N}_-]+)(?=$|[^\p{L}\p{N}_-])/giu;
const mentionRe = /@([\p{L}\p{N}_-]+)(?=$|[^\p{L}\p{N}_-])/giu;
let cursor = 0;
let match: RegExpExecArray | null;
while ((match = mentionRe.exec(value)) !== null) {
const prefix = match[1] ?? "";
const name = match[2] ?? "";
if (!isCapabilityMentionStart(value, match.index)) continue;
const name = match[1] ?? "";
const key = name.toLowerCase();
const session = sessionsByName.get(key);
const app = session ? null : cliAppsByName.get(key);
const preset = session || app ? null : mcpPresetsByName.get(key);
if (!app && !preset && !session) continue;
const mentionStart = match.index + prefix.length;
const mentionStart = match.index;
const mentionEnd = mentionStart + name.length + 1;
if (mentionStart > cursor) {
segments.push({ kind: "text", text: value.slice(cursor, mentionStart) });
+61 -80
View File
@@ -45,7 +45,11 @@ import {
mcpPresetInitials,
splitCapabilityMentionSegments,
} from "@/components/CliAppMentionText";
import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";
import {
composerMentionText,
isCapabilityMentionStart,
type CapabilityMentionSegment,
} from "@/lib/composer-mention-text";
import { INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";
import {
ArrowUp,
@@ -138,7 +142,6 @@ import {
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { cn } from "@/lib/utils";
import { composerMentionText } from "@/lib/composer-mention-text";
import type { ComposerDraftStore } from "@/lib/composer-draft";
const VOICE_SHORTCUT_CODE = "KeyD";
@@ -430,7 +433,7 @@ function mentionInsertion(
const to = Math.min(Math.max(end, from), value.length);
const prefix = value.slice(0, from);
const suffix = value.slice(to);
const leadingSpace = prefix && !/\s$/.test(prefix) ? " " : "";
const leadingSpace = prefix && !isCapabilityMentionStart(value, from) ? " " : "";
const trailingSpace = /^\s/.test(suffix) ? "" : " ";
const tokenStart = prefix.length + leadingSpace.length;
const tokenEnd = tokenStart + name.length + 1;
@@ -1079,7 +1082,7 @@ export function ThreadComposer({
const [value, setValue] = useState(initialDraft?.text ?? "");
const [composerFocused, setComposerFocused] = useState(false);
const blurFrame = useRef<number | null>(null);
const [selectedSessionMentions, setSelectedSessionMentions] = useState<SessionMention[]>(
const [boundSessionMentions, setBoundSessionMentions] = useState<SessionMention[]>(
initialDraft?.sessionMentions ?? [],
);
const [sessionDragPreview, setSessionDragPreview] = useState<{
@@ -1447,12 +1450,12 @@ export function ThreadComposer({
if (interactionDisabled || cliAppMenuDismissed) return null;
const caret = Math.min(Math.max(cursorPosition, 0), value.length);
const beforeCaret = value.slice(0, caret);
const match = /(?:^|\s)@([\p{L}\p{N}_-]*)$/iu.exec(beforeCaret);
if (!match) return null;
const match = /@([\p{L}\p{N}_-]*)$/iu.exec(beforeCaret);
if (!match || !isCapabilityMentionStart(value, match.index)) return null;
const query = match[1].toLowerCase();
return {
query,
start: caret - query.length - 1,
start: match.index,
end: caret,
};
}, [cliAppMenuDismissed, cursorPosition, interactionDisabled, value]);
@@ -1466,9 +1469,13 @@ export function ThreadComposer({
() => sessionMentionOptions(sessions),
[sessions],
);
const sessionMentionCatalog = useMemo(
() => [...availableSessionMentions, ...boundSessionMentions],
[availableSessionMentions, boundSessionMentions],
);
const mentionSegments = useMemo(
() => splitCapabilityMentionSegments(value, cliApps, mcpPresets, selectedSessionMentions),
[cliApps, mcpPresets, selectedSessionMentions, value],
() => splitCapabilityMentionSegments(value, cliApps, mcpPresets, sessionMentionCatalog),
[cliApps, mcpPresets, sessionMentionCatalog, value],
);
const editMentionInput = useCallback((next: string, cursor: number) => {
secondEnterPromptIdRef.current = null;
@@ -1485,19 +1492,6 @@ export function ThreadComposer({
});
const { rawSelection, replace: replaceMentionInput } = mentionInput;
const draftText = composerMentionText(mentionInput.segments).raw;
useLayoutEffect(() => {
if (!draftKey || !draftStore || !draftAttachmentsReady) return;
if (!draftText && images.length === 0 && !quotedContext) {
draftStore.delete(draftKey);
return;
}
draftStore.set(draftKey, {
text: draftText,
files: images.map((image) => image.file),
sessionMentions: selectedSessionMentions,
quotedContext,
}, persistDraft);
}, [draftAttachmentsReady, draftKey, draftStore, images, persistDraft, quotedContext, selectedSessionMentions, draftText]);
const sessionDragInsertion = sessionDragPreview
? mentionInsertion(
value,
@@ -1511,7 +1505,7 @@ export function ThreadComposer({
sessionDragInsertion.value,
cliApps,
mcpPresets,
[...selectedSessionMentions, sessionDragPreview.mention],
sessionMentionCatalog,
)
: mentionInput.segments;
const activeSessionMentions = useMemo(() => {
@@ -1522,15 +1516,37 @@ export function ThreadComposer({
return [segment.mention];
});
}, [mentionSegments]);
useLayoutEffect(() => {
// Pin resolved identities so a catalog refresh cannot retarget an existing reference.
if (activeSessionMentions.length !== boundSessionMentions.length
|| activeSessionMentions.some((mention, index) => mention !== boundSessionMentions[index])) {
setBoundSessionMentions(activeSessionMentions);
}
}, [activeSessionMentions, boundSessionMentions]);
useLayoutEffect(() => {
if (!draftKey || !draftStore || !draftAttachmentsReady) return;
if (!draftText && images.length === 0 && !quotedContext) {
draftStore.delete(draftKey);
return;
}
draftStore.set(draftKey, {
text: draftText,
files: images.map((image) => image.file),
sessionMentions: activeSessionMentions,
quotedContext,
}, persistDraft);
}, [activeSessionMentions, draftAttachmentsReady, draftKey, draftStore, images, persistDraft, quotedContext, draftText]);
const insertableSessionMentions = useMemo(() => availableSessionMentions.filter((mention) => {
const bound = activeSessionMentions.find(
(active) => active.name.toLowerCase() === mention.name.toLowerCase(),
);
return (!bound || bound.session_key === mention.session_key)
&& (activeSessionMentions.length < SESSION_MENTIONS_LIMIT
|| activeSessionMentions.some((active) => active.session_key === mention.session_key));
}), [activeSessionMentions, availableSessionMentions]);
const filteredMentionCandidates = useMemo<MentionCandidate[]>(() => {
if (!cliAppMention) return [];
const sessionCandidates: MentionCandidate[] = availableSessionMentions
.filter((mention) => (
activeSessionMentions.length < SESSION_MENTIONS_LIMIT
|| activeSessionMentions.some(
(selected) => selected.session_key === mention.session_key,
)
))
const sessionCandidates: MentionCandidate[] = insertableSessionMentions
.filter((mention) => [
mention.name,
mention.title,
@@ -1542,7 +1558,7 @@ export function ThreadComposer({
mention,
}));
const sessionNames = new Set(
availableSessionMentions.map((mention) => mention.name.toLowerCase()),
sessionMentionCatalog.map((mention) => mention.name.toLowerCase()),
);
const cliCandidates: MentionCandidate[] = cliApps
.filter((app) => app.installed)
@@ -1603,7 +1619,7 @@ export function ThreadComposer({
remaining -= extra;
}
return groups.flatMap(({ candidates }, index) => candidates.slice(0, counts[index]));
}, [activeSessionMentions, availableSessionMentions, cliAppMention, cliApps, mcpPresets]);
}, [cliAppMention, cliApps, insertableSessionMentions, mcpPresets, sessionMentionCatalog]);
const showCliAppMenu = filteredMentionCandidates.length > 0;
const showAnyPalette = showSlashMenu || showCliAppMenu;
@@ -1741,7 +1757,6 @@ export function ThreadComposer({
previousPendingQueueKeyRef.current = pendingQueueKey;
secondEnterPromptIdRef.current = null;
setValue("");
setSelectedSessionMentions([]);
setInlineError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
@@ -1879,38 +1894,24 @@ export function ThreadComposer({
[handleStop, isStreaming, onStop, recentSlashCommands, replaceMentionInput, resizeTextarea, skillQuery, value],
);
const insertMentionCandidate = useCallback(
(candidate: MentionCandidate, start: number, end: number) => {
if (candidate.kind === "session") {
const alreadySelected = activeSessionMentions.some(
(mention) => mention.session_key === candidate.mention.session_key,
);
if (!alreadySelected && activeSessionMentions.length >= SESSION_MENTIONS_LIMIT) return;
const name = candidate.name.toLowerCase();
setSelectedSessionMentions([
...activeSessionMentions.filter((mention) => (
mention.name.toLowerCase() !== name
&& mention.session_key !== candidate.mention.session_key
)),
candidate.mention,
]);
}
const insertion = mentionInsertion(value, candidate.name, start, end);
const insertMention = useCallback(
(name: string, start: number, end: number) => {
const insertion = mentionInsertion(value, name, start, end);
replaceMentionInput(insertion.value, insertion.cursor);
setCliAppMenuDismissed(true);
setSlashMenuDismissed(false);
setInlineError(null);
resizeTextarea();
},
[activeSessionMentions, replaceMentionInput, resizeTextarea, value],
[replaceMentionInput, resizeTextarea, value],
);
const chooseMentionCandidate = useCallback(
(candidate: MentionCandidate) => {
if (!cliAppMention) return;
insertMentionCandidate(candidate, cliAppMention.start, cliAppMention.end);
insertMention(candidate.name, cliAppMention.start, cliAppMention.end);
},
[cliAppMention, insertMentionCandidate],
[cliAppMention, insertMention],
);
const handleSessionDrop = useCallback((event: React.DragEvent) => {
@@ -1921,30 +1922,14 @@ export function ThreadComposer({
setSessionDragPreview(null);
if (interactionDisabled) return true;
const sessionKey = readDraggedSession(event.dataTransfer);
const mention = availableSessionMentions.find(
const mention = insertableSessionMentions.find(
(candidate) => candidate.session_key === (sessionKey ?? preview?.mention.session_key),
);
if (!mention) return true;
const caret = preview?.start ?? rawSelection().start;
insertMentionCandidate(
{
kind: "session",
name: mention.name,
displayName: mention.title || mention.name,
mention,
},
caret,
preview?.end ?? rawSelection().end,
);
insertMention(mention.name, caret, preview?.end ?? rawSelection().end);
return true;
}, [
availableSessionMentions,
insertMentionCandidate,
interactionDisabled,
rawSelection,
sessionDragPreview,
value.length,
]);
}, [insertableSessionMentions, insertMention, interactionDisabled, rawSelection, sessionDragPreview]);
const previewSessionDrop = useCallback((event: React.DragEvent) => {
if (!hasDraggedSession(event.dataTransfer)) return false;
@@ -1954,13 +1939,10 @@ export function ThreadComposer({
return true;
}
const sessionKey = readDraggedSession(event.dataTransfer);
const mention = availableSessionMentions.find(
const mention = insertableSessionMentions.find(
(candidate) => candidate.session_key === sessionKey,
);
const alreadySelected = mention && activeSessionMentions.some(
(candidate) => candidate.session_key === mention.session_key,
);
if (!mention || (!alreadySelected && activeSessionMentions.length >= SESSION_MENTIONS_LIMIT)) {
if (!mention) {
event.dataTransfer.dropEffect = "none";
setSessionDragPreview(null);
return true;
@@ -1976,7 +1958,7 @@ export function ThreadComposer({
: { mention, start, end }
));
return true;
}, [activeSessionMentions, availableSessionMentions, interactionDisabled, rawSelection]);
}, [insertableSessionMentions, interactionDisabled, rawSelection]);
useEffect(() => {
if (!sessionDragPreview) return;
@@ -1990,7 +1972,6 @@ export function ThreadComposer({
const clearComposerText = useCallback((restoreFocus = true) => {
setValue("");
setSelectedSessionMentions([]);
setInlineError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
@@ -2056,7 +2037,7 @@ export function ThreadComposer({
secondEnterPromptIdRef.current = null;
setQueuedPrompt(null);
replaceMentionInput(prompt.text, prompt.text.length);
setSelectedSessionMentions(prompt.sessionMentions ?? []);
setBoundSessionMentions(prompt.sessionMentions ?? []);
setInlineError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
+6
View File
@@ -1,5 +1,11 @@
import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";
const MENTION_START_BOUNDARY = /[\s([{,,、;;::!?!?。]/u;
export function isCapabilityMentionStart(value: string, position: number): boolean {
return position === 0 || MENTION_START_BOUNDARY.test(value.charAt(position - 1));
}
export type CapabilityMentionSegment =
| { kind: "text"; text: string }
| { kind: "cli"; text: string; app: CliAppInfo }
+25
View File
@@ -653,6 +653,31 @@ describe("MessageBubble", () => {
);
});
it("preserves punctuation-separated session links and capability mentions in sent messages", () => {
const message: UIMessage = {
id: "u-punctuation-mentions",
role: "user",
content: "@bime、@luma,@luma;@zoom:@browserbase。",
sessionMentions: [
{ id: "handle_00000000000000000000000000000001", name: "bime", session_key: "websocket:pricing", title: "Pricing" },
{ id: "handle_00000000000000000000000000000002", name: "luma", session_key: "websocket:notes", title: "Notes" },
],
createdAt: Date.now(),
};
render(<MessageBubble message={message} cliApps={CLI_APPS} mcpPresets={MCP_PRESETS} />);
expect(screen.getByTestId("message-session-mention-bime").closest("a"))
.toHaveAttribute("href", "#/chat/websocket%3Apricing");
const repeated = screen.getAllByTestId("message-session-mention-luma");
expect(repeated).toHaveLength(2);
for (const token of repeated) {
expect(token.closest("a")).toHaveAttribute("href", "#/chat/websocket%3Anotes");
}
expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
expect(screen.getByTestId("message-mcp-mention-browserbase")).toHaveTextContent("@Browserbase");
});
it("renders installed CLI app mentions inside sent user messages", () => {
const message: UIMessage = {
id: "u-cli",
+261 -43
View File
@@ -151,7 +151,7 @@ const MCP_PRESETS: McpPresetInfo[] = [
},
];
function session(chatId: string, title: string, preview = ""): ChatSummary {
function session(chatId: string, title: string, preview = "", handleName = title): ChatSummary {
const key = `websocket:${chatId}`;
const handleId = Array.from(chatId)
.map((character) => character.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000")
@@ -168,7 +168,7 @@ function session(chatId: string, title: string, preview = ""): ChatSummary {
preview,
handle: {
id: `handle_${handleId}`,
name: title,
name: handleName,
},
};
}
@@ -2115,7 +2115,147 @@ describe("ThreadComposer", () => {
});
});
it("attaches persisted sessions only through the shared mention palette", () => {
it.each(["typed", "pasted"])("attaches %s session handles without selecting a candidate", async (entry) => {
const user = userEvent.setup();
const onSend = vi.fn();
const targets = [session("pricing", "Pricing", "", "bime"), session("notes", "Notes", "", "bari")];
render(<ThreadComposer onSend={onSend} sessions={targets} />);
const input = screen.getByLabelText("Message input");
const text = "参考 @bime @bime @BARI";
if (entry === "typed") await user.type(input, text);
else {
await user.click(input);
await user.paste(text);
}
expect(screen.getAllByTestId("composer-session-mention-bime")).toHaveLength(2);
expect(screen.getByTestId("composer-session-mention-bari")).toHaveTextContent("@BARI");
await user.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith(text, undefined, {
sessionMentions: targets.map((target) => ({
id: target.handle?.id,
name: target.handle?.name,
session_key: target.key,
title: target.title,
})),
});
});
it.each(["typed", "pasted"])("recognizes %s session handles separated by punctuation without spaces", async (entry) => {
const user = userEvent.setup();
const onSend = vi.fn();
const targets = [session("pricing", "Pricing", "", "bime"), session("notes", "Notes", "", "luma")];
render(<ThreadComposer onSend={onSend} sessions={targets} />);
const input = screen.getByLabelText("Message input");
const text = "@bime、@luma,@luma";
if (entry === "typed") await user.type(input, text);
else {
await user.click(input);
await user.paste(text);
}
expect(screen.getByTestId("composer-session-mention-bime")).toHaveTextContent("@bime");
expect(screen.getAllByTestId("composer-session-mention-luma")).toHaveLength(2);
await user.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith(text, undefined, {
sessionMentions: targets.map((target) => ({
id: target.handle?.id, name: target.handle?.name, session_key: target.key, title: target.title,
})),
});
});
it.each(["、", ",", ":"])("completes a session handle after %s without inserting a leading space", (separator) => {
const onSend = vi.fn();
const targets = [session("pricing", "Pricing", "", "bime"), session("notes", "Notes", "", "luma")];
render(<ThreadComposer onSend={onSend} sessions={targets} />);
const input = screen.getByLabelText("Message input");
const text = `@bime${separator}@lu`;
fireEvent.change(input, { target: { value: text, selectionStart: text.length } });
expect(screen.getByRole("option", { name: /@luma/i })).toBeInTheDocument();
fireEvent.keyDown(input, { key: "Tab" });
expect(input).toHaveValue(`@bime${separator}@luma `);
expect(screen.getByTestId("composer-session-mention-luma")).toHaveTextContent("@luma");
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith(`@bime${separator}@luma`, undefined, {
sessionMentions: targets.map((target) => ({
id: target.handle?.id, name: target.handle?.name, session_key: target.key, title: target.title,
})),
});
});
it("previews and drops a session after punctuation without changing the surrounding text", () => {
const onSend = vi.fn();
const targets = [session("pricing", "Pricing", "", "bime"), session("notes", "Notes", "", "luma")];
render(<ThreadComposer onSend={onSend} sessions={targets} />);
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
fireEvent.change(input, { target: { value: "@bime、", selectionStart: 6 } });
const dataTransfer = { types: [SESSION_DRAG_TYPE], files: [], getData: () => targets[1].key };
fireEvent.dragOver(input, { dataTransfer });
expect(screen.getByTestId("composer-session-drag-preview")).toHaveTextContent("@luma");
expect(input).toHaveValue("@bime、");
fireEvent.drop(input, { dataTransfer });
expect(input).toHaveValue("@bime、@luma ");
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("@bime、@luma", undefined, {
sessionMentions: targets.map((target) => ({
id: target.handle?.id, name: target.handle?.name, session_key: target.key, title: target.title,
})),
});
});
it("leaves unknown handles, partial names, titles and embedded email or path handles as plain text", () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} sessions={[session("pricing", "Pricing", "", "bime")]} />);
const text = "@missing @bi @bimex @Pricing mail@bime word@bime /tmp/@bime";
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: text, selectionStart: text.length } });
expect(screen.queryByTestId("composer-session-mention-bime")).not.toBeInTheDocument();
expect(screen.queryByRole("listbox", { name: "Mentions" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith(text, undefined, undefined);
});
it("updates session references when a typed handle is changed or removed", () => {
const onSend = vi.fn();
const target = session("notes", "Notes", "", "bari");
render(<ThreadComposer onSend={onSend} sessions={[session("pricing", "Pricing", "", "bime"), target]} />);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "@bime @bari" } });
expect(screen.getByTestId("composer-session-mention-bime")).toBeInTheDocument();
fireEvent.change(input, { target: { value: "@bim @bari" } });
expect(screen.queryByTestId("composer-session-mention-bime")).not.toBeInTheDocument();
expect(screen.getByTestId("composer-session-mention-bari")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("@bim @bari", undefined, {
sessionMentions: [{ id: target.handle?.id, name: "bari", session_key: target.key, title: "Notes" }],
});
});
it("gives typed session handles the same priority over App and MCP names as the palette", () => {
const onSend = vi.fn();
const targets = [session("image-notes", "Image notes", "", "gimp"), session("browser-notes", "Browser notes", "", "bari")];
render(<ThreadComposer onSend={onSend} sessions={targets} cliApps={CLI_APPS}
mcpPresets={[{ ...MCP_PRESETS[0], name: "bari" }]} />);
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "@gimp @bari" } });
expect(screen.getByTestId("composer-session-mention-gimp")).toBeInTheDocument();
expect(screen.getByTestId("composer-session-mention-bari")).toBeInTheDocument();
expect(screen.queryByTestId("composer-cli-mention-gimp")).not.toBeInTheDocument();
expect(screen.queryByTestId("composer-mcp-mention-bari")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("@gimp @bari", undefined, {
sessionMentions: targets.map((target) => ({
id: target.handle?.id, name: target.handle?.name, session_key: target.key, title: target.title,
})),
});
});
it("attaches persisted sessions through the shared mention palette", () => {
const onSend = vi.fn();
render(
<ThreadComposer
@@ -2126,13 +2266,6 @@ describe("ThreadComposer", () => {
);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, {
target: { value: "普通文字 @收费设计", selectionStart: 10 },
});
expect(screen.queryByTestId("composer-session-mention-收费设计")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenLastCalledWith("普通文字 @收费设计", undefined, undefined);
fireEvent.change(input, {
target: { value: "参考 @收费", selectionStart: 6 },
});
@@ -2236,40 +2369,59 @@ describe("ThreadComposer", () => {
expect(screen.queryByTestId("composer-session-drag-preview")).not.toBeInTheDocument();
});
it("releases the eight-session limit when a mention is removed", () => {
it.each([" ", "、"])("rejects more than eight typed session references separated by %j without silently dropping them", (separator) => {
const onSend = vi.fn();
render(
<ThreadComposer
onSend={onSend}
placeholder="Type your message..."
sessions={Array.from(
{ length: 9 },
(_, index) => session(`topic-${index}`, `Topic${index}`),
)}
/>,
);
const targets = Array.from({ length: 9 }, (_, index) => session(`topic-${index}`, `Topic${index}`));
render(<ThreadComposer onSend={onSend} sessions={targets} />);
const input = screen.getByLabelText("Message input");
const handles = targets.map((target) => `@${target.handle?.name}`);
fireEvent.change(input, { target: { value: handles.join(separator) } });
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
for (let index = 0; index < 8; index += 1) {
const value = `${input.value}${input.value ? " " : ""}@Topic${index}`;
fireEvent.change(input, { target: { value, selectionStart: value.length } });
fireEvent.keyDown(input, { key: "Tab" });
for (const target of targets) {
expect(screen.getByTestId(`composer-session-mention-${target.handle?.name}`)).toBeInTheDocument();
}
const replacement = `${input.value.replace("@Topic0 ", "")} @Topic8`;
fireEvent.change(input, {
target: { value: replacement, selectionStart: replacement.length },
});
fireEvent.keyDown(input, { key: "Tab" });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toHaveTextContent("A message can mention up to 8 chats");
const options = onSend.mock.calls[0]?.[2];
expect(options.sessionMentions).toHaveLength(8);
expect(options.sessionMentions.map((mention: { session_key: string }) => (
mention.session_key
))).toEqual(expect.arrayContaining(["websocket:topic-8"]));
fireEvent.change(input, { target: { value: handles.slice(1).join(separator) } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend.mock.calls[0]?.[2].sessionMentions.map((mention: { session_key: string }) => mention.session_key))
.toEqual(targets.slice(1).map((target) => target.key));
});
it("keeps a selected session stable across refreshes and queued guidance", () => {
it.each(["palette", "drop"])("releases the eight-session limit for %s insertion when a mention is removed", (entry) => {
const onSend = vi.fn();
const targets = Array.from({ length: 9 }, (_, index) => session(`topic-${index}`, `Topic${index}`, "", `ref${index}x`));
render(<ThreadComposer onSend={onSend} sessions={targets} />);
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
const text = `${targets.slice(0, 8).map((target) => `@${target.handle?.name}`).join(" ")} @ref8`;
fireEvent.change(input, { target: { value: text, selectionStart: text.length } });
expect(screen.queryByRole("option", { name: /@ref8x/i })).not.toBeInTheDocument();
const dataTransfer = { types: [SESSION_DRAG_TYPE], files: [], getData: () => targets[8].key };
if (entry === "drop") {
fireEvent.dragOver(input, { dataTransfer });
expect(screen.queryByTestId("composer-session-drag-preview")).not.toBeInTheDocument();
fireEvent.drop(input, { dataTransfer });
expect(input).toHaveValue(text);
}
const replacement = input.value.replace("@ref0x ", "");
fireEvent.change(input, { target: { value: replacement, selectionStart: replacement.length } });
expect(screen.getByRole("option", { name: /@ref8x/i })).toBeInTheDocument();
if (entry === "palette") fireEvent.keyDown(input, { key: "Tab" });
else {
input.setSelectionRange(replacement.lastIndexOf("@"), replacement.length);
fireEvent.dragOver(input, { dataTransfer });
expect(screen.getByTestId("composer-session-drag-preview")).toHaveTextContent("@ref8x");
fireEvent.drop(input, { dataTransfer });
}
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend.mock.calls[0]?.[2].sessionMentions.map((mention: { session_key: string }) => mention.session_key))
.toEqual(targets.slice(1).map((target) => target.key));
});
it.each(["typed", "selected"])("keeps a %s session stable across refreshes and queued guidance", (entry) => {
const onSend = vi.fn();
const target = session("z-target", "Plan", "Original plan");
const { rerender } = render(
@@ -2283,19 +2435,21 @@ describe("ThreadComposer", () => {
);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
fireEvent.keyDown(input, { key: "Tab" });
if (entry === "typed") fireEvent.change(input, { target: { value: "@Plan " } });
else {
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
fireEvent.keyDown(input, { key: "Tab" });
}
// The referenced chat was deleted and its handle reused by a new chat.
const replacement = session("a-new", "New plan", "", "Plan");
rerender(
<ThreadComposer
onSend={onSend}
onStop={vi.fn()}
isStreaming
placeholder="Type your message..."
sessions={[
{ ...target, title: "Renamed plan" },
session("a-new", "Plan", target.preview),
]}
sessions={[replacement]}
/>,
);
@@ -2314,6 +2468,46 @@ describe("ThreadComposer", () => {
});
});
it.each(["palette", "drop"])("prevents %s insertion from retargeting a draft when a handle is reused", (entry) => {
const onSend = vi.fn();
const original = session("original", "Original plan", "", "bime");
const replacement = session("replacement", "New plan", "", "bime");
const composer = (target: ChatSummary) => <ThreadComposer onSend={onSend} sessions={[target]} />;
const { rerender } = render(composer(original));
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
fireEvent.change(input, { target: { value: "@bime " } });
rerender(composer(replacement));
const dataTransfer = { types: [SESSION_DRAG_TYPE], files: [], getData: () => replacement.key };
if (entry === "palette") {
fireEvent.change(input, { target: { value: "@bime @bi", selectionStart: 9 } });
expect(screen.queryByRole("option", { name: /@bime/i })).not.toBeInTheDocument();
} else {
fireEvent.dragOver(input, { dataTransfer });
expect(screen.queryByTestId("composer-session-drag-preview")).not.toBeInTheDocument();
fireEvent.drop(input, { dataTransfer });
expect(input).toHaveValue("@bime ");
}
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend.mock.calls[0]?.[2].sessionMentions).toEqual([{
id: original.handle?.id, name: "bime", session_key: original.key, title: original.title,
}]);
if (entry === "palette") {
fireEvent.change(input, { target: { value: "@bi", selectionStart: 3 } });
expect(screen.getByRole("option", { name: /@bime/i })).toBeInTheDocument();
fireEvent.keyDown(input, { key: "Tab" });
} else {
fireEvent.dragOver(input, { dataTransfer });
expect(screen.getByTestId("composer-session-drag-preview")).toHaveTextContent("@bime");
fireEvent.drop(input, { dataTransfer });
}
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend.mock.calls[1]?.[2].sessionMentions).toEqual([{
id: replacement.handle?.id, name: "bime", session_key: replacement.key, title: replacement.title,
}]);
});
it("opens skills only from a $ reference and prioritizes the skill name", () => {
const skillName = "arxiv-intelligence-filter";
render(
@@ -3930,6 +4124,30 @@ describe("ThreadComposer", () => {
describe("session composer drafts", () => {
it("resolves typed draft handles when the catalog arrives and persists their identity", () => {
const draftStore = new ComposerDraftStore();
const onSend = vi.fn();
const target = session("pricing", "Pricing", "", "bime");
const composer = (sessions: ChatSummary[], store = draftStore) => (
<ThreadComposer draftKey="typed-handle" draftStore={store} persistDraft onSend={onSend} sessions={sessions} />
);
const view = render(composer([]));
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "参考 @bime" } });
expect(screen.queryByTestId("composer-session-mention-bime")).not.toBeInTheDocument();
view.rerender(composer([target]));
expect(screen.getByTestId("composer-session-mention-bime")).toBeInTheDocument();
view.unmount();
render(composer([], new ComposerDraftStore()));
expect(screen.getByLabelText("Message input")).toHaveValue("参考 @bime");
expect(screen.getByTestId("composer-session-mention-bime")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("参考 @bime", undefined, {
sessionMentions: [{ id: target.handle?.id, name: "bime", session_key: target.key, title: "Pricing" }],
});
});
it("restores independent drafts across session switches and remounts", () => {
const draftStore = new ComposerDraftStore();
const composer = (key: string) => (