Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): recognize typed session handles as references (#6311)
chengyongru909b277e7a5a
diff --git a/docs/webui.md b/docs/webui.mdindex bd5ecda9a..9dc302881 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -113,7 +113,7 @@ Open a topic's sidebar action menu and choose **Create group** to turn it into aUse **Pane layout** to choose columns, rows, a grid, BSP, or a main pane with a stack. Drag a divider to resize panes. Each pane has its own conversation; select one to direct the shared composer to that topic. Group membership and layout persist across refreshes. Grouping topics does not merge their histories.-To bring another topic's work into a conversation, select it from the `@` menu or drag it from the sidebar into the composer. The agent can read the selected session and exchange messages with other saved sessions. See [Composer](#composer) for the distinction between an attached reference and plain text.+To use work from another topic, mention it with `@` and tell nanobot what you need. See [Composer](#composer) for how to add a topic reference.### Activity and context usage@@ -205,13 +205,17 @@ In Restricted mode, ordinary file and shell work stays inside the selected projeWith voice transcription configured, the idle composer uses one button for voice input when empty and Send when text or attachments are present; speech is transcribed into the draft before sending.-The composer supports plain messages, image attachments, voice input when transcription is configured, slash commands, and `@` mentions for installed Apps, MCP presets, or persisted topics. Topics have short, pronounceable handles such as `@luma`; titles are display text rather than addresses. Select a topic from the menu, or drag it from the sidebar, to attach its structured reference. Typing the same text without selecting it remains plain text.+The composer supports plain messages, image attachments, voice input when transcription is configured, slash commands, and `@` mentions for installed Apps, MCP presets, or saved topics.++To reference another topic, type or paste its complete handle (such as `@luma`), choose it from the `@` menu, or drag it from the sidebar into the composer. Recognized handles are highlighted; unknown handles remain plain text. You can reference up to eight different topics in one message.++Ask nanobot to find, read, or send messages to other saved topics, including those in other projects. For example, “Summarize @luma” or “Send this update to @luma.” Mentioning a topic alone does not send a message to it.On touch-primary phones and tablets, **Enter** inserts a newline; tap the send arrow to submit. This also applies when a coarse-pointer tablet has a hardware keyboard attached. On desktop, **Enter** sends and **Shift+Enter** adds a newline. An open slash-command or mention menu takes precedence: Enter selects its item.While a response is running, desktop Enter adds your input to one waiting message. Further inputs append in order, separated by newlines, with their attachments and references retained. The complete message is sent once the current response finishes. Press Enter again with an empty input or choose **Send now** to insert it immediately as guidance for the active turn. The send arrow also includes any waiting content when submitting a new draft. Use **Edit message** to revise the complete message or **Delete message** to discard it. If an addition would exceed the message limits, it stays in the input so you can revise it. The primary button shows **Stop** when there is no sendable draft; stopping or a failed send keeps the waiting message for manual sending.-The agent can inspect an attached topic with `read_session`. It can discover other persisted topics with `list_sessions` and send asynchronous messages with `send_session_message`; topic messaging is not limited by workspace scope. The model badge shows the current model or preset and links to model settings when setup is incomplete.+The model badge shows the current model or preset and links to model settings when setup is incomplete.For image generation, configure an image provider first and then use the WebUI image mode from the composer. See [`image-generation.md`](./image-generation.md) for provider setup and output behavior.diff --git a/nanobot/webui/session_access.py b/nanobot/webui/session_access.pyindex b9de2a18b..934f54ccf 100644--- a/nanobot/webui/session_access.py+++ b/nanobot/webui/session_access.py@@ -38,19 +38,6 @@ class WebuiSessionAccess:self._sessions = sessionsself._handles = SessionHandleResolver(sessions)- def _metadata(- self,- session_key: str,- *,- exclude_session_key: str | None,- ) -> dict[str, Any] | None:- if session_key == exclude_session_key:- return None- payload = self._sessions.read_session_metadata(session_key)- if payload is None or not self._sessions.types.public_history(_session_metadata(payload)):- return None- return payload-async def normalize_mentions(self,raw: object,diff --git a/webui/src/components/CliAppMentionText.tsx b/webui/src/components/CliAppMentionText.tsxindex d55f104a2..40dac91bb 100644--- a/webui/src/components/CliAppMentionText.tsx+++ b/webui/src/components/CliAppMentionText.tsx@@ -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) });diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsxindex 5c48b0bee..81e4d2d2c 100644--- a/webui/src/components/thread/ThreadComposer.tsx+++ b/webui/src/components/thread/ThreadComposer.tsx@@ -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);diff --git a/webui/src/lib/composer-mention-text.ts b/webui/src/lib/composer-mention-text.tsindex 7802ef190..57d4c7d6e 100644--- a/webui/src/lib/composer-mention-text.ts+++ b/webui/src/lib/composer-mention-text.ts@@ -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 }diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsxindex 3d46beecf..8a9990c58 100644--- a/webui/src/tests/message-bubble.test.tsx+++ b/webui/src/tests/message-bubble.test.tsx@@ -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",diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsxindex 2b57ed319..c8cfd72af 100644--- a/webui/src/tests/thread-composer.test.tsx+++ b/webui/src/tests/thread-composer.test.tsx@@ -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");++ 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));+ });- 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"]));+ 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("keeps a selected session stable across refreshes and queued guidance", () => {+ 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(<ThreadComposeronSend={onSend}onStop={vi.fn()}isStreamingplaceholder="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) => (