import { act, createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, describe, expect, it, vi } from "vitest"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover"; import { ComposerDraftStore } from "@/lib/composer-draft"; import { encodeImage } from "@/lib/imageEncode"; import { SESSION_DRAG_TYPE } from "@/lib/session-drag"; import type { ChatSummary, CliAppInfo, McpPresetInfo, SlashCommand, WorkspaceScopePayload } from "@/lib/types"; function workspacePickerProps(scope: WorkspaceScopePayload) { const resolvePath = (path: string) => path.startsWith("~/") ? `/Users/test/${path.slice(2)}` : path; return { onLoadWorkspaceProjects: async () => ({ schema_version: 1, default_access_mode: "default" as const, default_scope: scope, recent_projects: [], favorite_projects: [], controls: { can_change_project: true }, }), onBrowseWorkspaceDirectories: async (path: string) => ({ path: resolvePath(path), parent: null, entries: [], partial: false, truncated: false, host: "test-host", platform: "Linux", }), onResolveWorkspaceProject: async (path: string) => ({ path: resolvePath(path), name: path.replace(/\\/g, "/").split("/").filter(Boolean).pop() || path, }), onFavoriteWorkspaceProject: async () => [], }; } vi.mock("@/lib/imageEncode", () => ({ encodeImage: vi.fn(async (file: File) => ({ ok: true, dataUrl: `data:${file.type || "image/png"};base64,aW1hZ2U=`, bytes: Math.max(1, file.size), normalized: false, })), })); const COMMANDS: SlashCommand[] = [ { command: "/stop", title: "Stop current task", description: "Cancel the active agent turn.", icon: "square", lifecycle: "stop_active_turn", acceptsArgs: false, }, { command: "/history", title: "Show conversation history", description: "Print the last N persisted messages.", icon: "history", argHint: "[n]", lifecycle: "side_channel", acceptsArgs: true, }, ]; const CLI_APPS: CliAppInfo[] = [ { name: "gimp", display_name: "GIMP", category: "image", description: "Image editing", requires: "", source: "harness", entry_point: "cli-anything-gimp", install_supported: true, installed: true, available: true, status: "installed", logo_url: "https://example.invalid/gimp.svg", brand_color: "#5C5543", skill_installed: true, }, { name: "blender", display_name: "Blender", category: "3d", description: "3D creation", requires: "", source: "harness", entry_point: "cli-anything-blender", install_supported: true, installed: true, available: true, status: "installed", logo_url: null, brand_color: "#E87D0D", skill_installed: true, }, { name: "krita", display_name: "Krita", category: "image", description: "Painting", requires: "", source: "harness", entry_point: "cli-anything-krita", install_supported: true, installed: false, available: false, status: "not_installed", logo_url: null, brand_color: "#3BABFF", skill_installed: false, }, ]; const MCP_PRESETS: McpPresetInfo[] = [ { name: "browserbase", display_name: "Browserbase", category: "browser", description: "Cloud browser automation", docs_url: "https://docs.browserbase.com", transport: "streamableHttp", requires: "Browserbase API key", note: "", install_supported: true, installed: true, configured: true, available: true, status: "configured", logo_url: "https://example.invalid/browserbase.svg", brand_color: "#111827", required_fields: [], connection_summary: "https://mcp.browserbase.com/mcp", }, { name: "figma", display_name: "Figma", category: "design", description: "Design context", docs_url: "https://figma.com", transport: "streamableHttp", requires: "Figma local app", note: "", install_supported: true, installed: true, configured: false, available: false, status: "missing_credentials", logo_url: null, brand_color: "#F24E1E", required_fields: [], connection_summary: "", }, ]; 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") .join("") .padEnd(32, "0") .slice(0, 32); return { key, channel: "websocket", chatId, createdAt: null, updatedAt: null, title, preview, handle: { id: `handle_${handleId}`, name: handleName, }, }; } const ORIGINAL_INNER_HEIGHT = window.innerHeight; const ORIGINAL_MEDIA_DEVICES = navigator.mediaDevices; function mockBlobUrls() { Object.defineProperty(URL, "createObjectURL", { configurable: true, value: vi.fn(() => "blob:composer-test"), }); Object.defineProperty(URL, "revokeObjectURL", { configurable: true, value: vi.fn(), }); } function stubVisualViewport({ height, offsetTop = 0, }: { height: number; offsetTop?: number; }) { const target = new EventTarget(); vi.stubGlobal("visualViewport", { width: 390, height, offsetTop, offsetLeft: 0, pageTop: offsetTop, pageLeft: 0, scale: 1, addEventListener: target.addEventListener.bind(target), removeEventListener: target.removeEventListener.bind(target), dispatchEvent: target.dispatchEvent.bind(target), } as unknown as VisualViewport); } afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers(); Reflect.deleteProperty(window, "nanobotHost"); if (ORIGINAL_MEDIA_DEVICES) { Object.defineProperty(navigator, "mediaDevices", { configurable: true, value: ORIGINAL_MEDIA_DEVICES, }); } else { Reflect.deleteProperty(navigator, "mediaDevices"); } window.localStorage.clear(); Object.defineProperty(window, "innerHeight", { value: ORIGINAL_INNER_HEIGHT, configurable: true, }); }); function rect(init: Partial): DOMRect { const top = init.top ?? 0; const left = init.left ?? 0; const width = init.width ?? 0; const height = init.height ?? 0; return { x: init.x ?? left, y: init.y ?? top, top, left, width, height, right: init.right ?? left + width, bottom: init.bottom ?? top + height, toJSON: () => ({}), }; } function mockVoiceRecorder(blob = new Blob(["voice"], { type: "audio/webm" })) { const stopTrack = vi.fn(); const getUserMedia = vi.fn(async () => ({ getTracks: () => [{ stop: stopTrack }], })); Object.defineProperty(navigator, "mediaDevices", { configurable: true, value: { getUserMedia }, }); class FakeMediaRecorder { static isTypeSupported = vi.fn((type: string) => type === "audio/webm"); state: RecordingState = "inactive"; mimeType = blob.type; ondataavailable: ((event: BlobEvent) => void) | null = null; onstop: (() => void) | null = null; start() { this.state = "recording"; } stop() { this.state = "inactive"; this.ondataavailable?.({ data: blob } as BlobEvent); this.onstop?.(); } } vi.stubGlobal("MediaRecorder", FakeMediaRecorder); return { getUserMedia, stopTrack }; } function mockVoiceAudioInput( sample = 128, state: AudioContextState = "running", decodedChannels?: Float32Array[], ) { const decodeAudioDataMock = vi.fn(async () => { if (!decodedChannels) throw new Error("decodeAudioData not mocked"); return { numberOfChannels: decodedChannels.length, sampleRate: 16_000, getChannelData: (channel: number) => decodedChannels[channel], } as AudioBuffer; }); class FakeAudioContext { state = state; createMediaStreamSource() { return { connect: vi.fn(), disconnect: vi.fn() }; } createAnalyser() { return { fftSize: 256, smoothingTimeConstant: 0, disconnect: vi.fn(), getByteTimeDomainData: (data: Uint8Array) => data.fill(sample), }; } close = vi.fn(async () => undefined); decodeAudioData = decodeAudioDataMock; resume = vi.fn(async () => undefined); } vi.stubGlobal("AudioContext", FakeAudioContext); vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => window.setTimeout(() => callback(performance.now()), 16) as unknown as number ); vi.spyOn(window, "cancelAnimationFrame").mockImplementation((id) => window.clearTimeout(id as unknown as number) ); return { decodeAudioData: decodeAudioDataMock }; } async function waitForVoiceCapture(): Promise { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 700)); }); } function bytesFromDataUrl(dataUrl: string): Uint8Array { const [, base64 = ""] = dataUrl.split(","); return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)); } function ascii(bytes: Uint8Array, offset: number, length: number): string { return String.fromCharCode(...bytes.slice(offset, offset + length)); } const MODEL_PRESETS = [ { name: "kimi", model: "moonshot/kimi-k2.5", provider: "moonshot" }, { name: "dflash", model: "deepseek/deepseek-v4-flash", provider: "deepseek" }, { name: "dspro", model: "deepseek/deepseek-v4-pro", provider: "deepseek" }, ]; function renderPresetComposer( variant: "thread" | "hero" = "thread", onManageModels?: () => void, ) { const onPresetChange = vi.fn(); render( , ); return { badge: screen.getByRole("button", { name: "kimi" }), onPresetChange, }; } function stubCoarsePointer(): void { vi.stubGlobal("matchMedia", vi.fn((query: string) => ({ matches: query.includes("pointer: coarse"), media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), }))); } describe("ThreadComposer", () => { it("locks an async send and keeps the draft when it is rejected", async () => { let resolveSend!: (accepted: boolean) => void; const onSend = vi.fn(() => new Promise((resolve) => { resolveSend = resolve; })); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "keep this pending draft" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(input).toBeDisabled(); expect(screen.getByRole("button", { name: "Send message" })).toBeDisabled(); await act(async () => resolveSend(false)); await waitFor(() => expect(input).toBeEnabled()); expect(input).toHaveValue("keep this pending draft"); }); it("dismisses the touch keyboard after a successful send", async () => { vi.stubGlobal("matchMedia", vi.fn((query: string) => ({ matches: query === "(hover: none) and (pointer: coarse)", media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), }))); const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); await act(async () => { await new Promise((resolve) => requestAnimationFrame(() => resolve())); }); expect(input).not.toHaveFocus(); input.focus(); expect(input).toHaveFocus(); fireEvent.change(input, { target: { value: "hello from mobile" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); await act(async () => { await new Promise((resolve) => requestAnimationFrame(() => resolve())); }); expect(onSend).toHaveBeenCalledWith("hello from mobile", undefined, undefined); expect(input).toHaveValue(""); expect(input).not.toHaveFocus(); }); it("inserts a newline instead of sending on Enter on coarse-pointer devices", () => { stubCoarsePointer(); const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "line one" } }); const keyEvent = createEvent.keyDown(input, { key: "Enter" }); fireEvent(input, keyEvent); expect(keyEvent.defaultPrevented).toBe(false); expect(onSend).not.toHaveBeenCalled(); }); it("keeps sending on Enter on precision-pointer devices", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "desktop message" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledWith("desktop message", undefined, undefined); }); it("still selects a slash command with Enter on coarse-pointer devices", () => { stubCoarsePointer(); const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/" } }); expect(screen.getByRole("option", { name: /\/history/i })).toHaveAttribute( "aria-selected", "true", ); fireEvent.keyDown(input, { key: "Enter" }); expect(input).toHaveValue("/history "); expect(onSend).not.toHaveBeenCalled(); }); it("labels the keyboard action as enter on coarse-pointer devices", () => { stubCoarsePointer(); render( , ); expect(screen.getByLabelText("Message input")).toHaveAttribute("enterkeyhint", "enter"); }); it("does not set enterkeyhint on precision-pointer devices", () => { render( , ); expect(screen.getByLabelText("Message input")).not.toHaveAttribute("enterkeyhint"); }); it("focuses and sends a removable quoted answer excerpt", async () => { const onSend = vi.fn(); const onQuotedContextChange = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); await waitFor(() => expect(input).toHaveFocus()); expect(screen.getByLabelText("Quoted context")).toHaveTextContent("selected answer excerpt"); fireEvent.change(input, { target: { value: "What does this mean?" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("What does this mean?", undefined, { quotedContext: "selected answer excerpt", }); expect(onQuotedContextChange).toHaveBeenCalledWith(null); }); it("removes quoted context without clearing the draft", () => { const onQuotedContextChange = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "keep this draft" } }); fireEvent.click(screen.getByRole("button", { name: "Remove quote" })); expect(onQuotedContextChange).toHaveBeenCalledWith(null); expect(input).toHaveValue("keep this draft"); }); it("renders a readonly hero model composer when provided", () => { render( , ); expect(screen.getByText("claude-opus-4-5")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Search" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Thinking" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Deep research" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument(); const input = screen.getByPlaceholderText("Ask anything..."); expect(input).toBeInTheDocument(); expect(input.className).toContain("min-h-[78px]"); expect(input.className).toContain("text-composer"); expect(input.className).toContain("pt-[27px]"); fireEvent.change(input, { target: { value: "1" } }); expect(input.className).toContain("pt-[27px]"); expect(input.parentElement?.parentElement?.className).toContain("max-w-[var(--composer-content-width,58rem)]"); }); it("defers textarea autosizing until IME composition commits", () => { render( , ); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; Object.defineProperty(input, "scrollHeight", { configurable: true, value: 120, }); input.style.height = "50px"; fireEvent.input(input, { target: { value: "zhongwen" }, isComposing: true, }); expect(input.style.height).toBe("50px"); fireEvent.input(input, { target: { value: "中文" }, isComposing: false, }); expect(input.style.height).toBe("120px"); }); it("lets long model preset labels use their intrinsic width", () => { render( , ); const badge = screen.getByRole("button", { name: "gpt-5.6-sol" }); expect(badge).toHaveClass("w-fit", "max-w-[min(18rem,44vw)]"); expect(badge).not.toHaveClass("w-[5.75rem]"); expect(screen.getByText("gpt-5.6-sol")).toBeInTheDocument(); }); it("shows a compact context meter beside the model selector", async () => { render( {(renderContextUsage) => } , ); const context = screen.getByTestId("composer-context-usage"); expect(context).toHaveClass("size-5", "rounded-full"); expect(context).not.toHaveTextContent("Context 74.9K / 1M"); expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument(); expect(context).toHaveAccessibleName( "Context 7%. Open context usage", ); fireEvent.focus(context); const tooltip = await screen.findByRole("tooltip"); expect(tooltip).toHaveTextContent("Context 7%"); expect(tooltip.parentElement).not.toHaveTextContent("Available"); }); it("opens the current graph and replays its request snapshots from the beginning", async () => { // Happy DOM has no canvas renderer; supply the operations used by graph paint // so replay can receive the same painted-frame acknowledgement as a browser. vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ setTransform: vi.fn(), clearRect: vi.fn(), setLineDash: vi.fn(), beginPath: vi.fn(), moveTo: vi.fn(), lineTo: vi.fn(), stroke: vi.fn(), arc: vi.fn(), fill: vi.fn(), roundRect: vi.fn(), fillText: vi.fn(), measureText: (text: string) => ({ width: text.length * 6 }), } as unknown as CanvasRenderingContext2D); render( {(renderContextUsage) => } ); fireEvent.click(screen.getByTestId("composer-context-usage")); expect(await screen.findByRole("button", { name: "b.md" })).toBeInTheDocument(); expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20"); const replay = screen.getByRole("button", { name: "Play context history" }); fireEvent.click(replay); expect(replay).toBeDisabled(); expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "10"); expect(await screen.findByRole("button", { name: "a.md" })).toBeInTheDocument(); await waitFor(() => expect(replay).toBeEnabled(), { timeout: 2500 }); expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20"); }); it("shows the latest round cache metrics when inspecting legacy history", () => { render( {(renderContextUsage) => } ); fireEvent.click(screen.getByTestId("composer-context-usage")); const meter = screen.getByRole("progressbar", { name: "Context" }); fireEvent.pointerEnter(meter.parentElement!.parentElement!); expect(screen.getByText("Cache hit rate")).toBeInTheDocument(); expect(screen.getByText("89%")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled(); }); it("keeps context usage visible when the provider omits cache metrics", () => { render( {(renderContextUsage) => } ); fireEvent.click(screen.getByTestId("composer-context-usage")); const meter = screen.getByRole("progressbar", { name: "Context" }); expect(meter).toHaveAttribute("aria-valuenow", "7"); fireEvent.pointerEnter(meter.parentElement!.parentElement!); expect(screen.queryByText("Cache hit rate")).not.toBeInTheDocument(); }); it("keeps the thread composer compact while matching the hero style", () => { render( , ); expect(screen.getByText("gpt-4o")).toBeInTheDocument(); const modelPill = screen.getByText("gpt-4o").closest(".composer-model-pill"); expect(modelPill).toHaveClass("font-medium", "text-foreground/70"); expect(modelPill).not.toHaveClass("font-semibold"); const providerLogo = screen.getByTestId("composer-model-logo-openai"); expect(providerLogo).toBeInTheDocument(); for (const className of ["border", "bg-background"]) { expect(providerLogo).not.toHaveClass(className); } const input = screen.getByPlaceholderText("Type your message..."); expect(input.className).toContain("min-h-[50px]"); expect(input.className).toContain("text-composer"); expect(input.parentElement?.parentElement?.className).toContain("max-w-[var(--composer-content-width,49.5rem)]"); expect(input.parentElement?.parentElement?.className).toContain("rounded-panel"); expect(input.parentElement?.parentElement?.className).not.toContain("shadow-"); expect(screen.getByRole("button", { name: "Send message" }).className).toContain("bg-foreground"); expect(screen.queryByText(/Enter to send/)).not.toBeInTheDocument(); }); it("opens a model picker and switches presets with one click", async () => { const { badge, onPresetChange } = renderPresetComposer(); expect(badge).toHaveClass("h-9"); expect(badge).toHaveClass("w-fit"); fireEvent.click(badge); const picker = screen.getByRole("dialog", { name: "Switch model" }); expect(picker).toHaveClass("w-[min(18rem,calc(100vw-2rem))]"); expect(badge).toHaveClass("w-fit"); expect(badge.querySelector(".composer-model-pill")).not.toHaveClass("w-full"); expect(within(picker).getAllByRole("option")).toHaveLength(3); expect(within(picker).getByRole("option", { name: "dflash" })).toHaveTextContent( /dflash\s*deepseek-v4-flash/, ); expect(within(picker).getByRole("option", { name: "kimi" })).toHaveAttribute( "aria-selected", "true", ); expect(document.activeElement).toBe(within(picker).getByRole("option", { name: "kimi" })); fireEvent.click(within(picker).getByRole("option", { name: "dspro" })); expect(onPresetChange).toHaveBeenCalledWith("dspro"); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); expect(badge).toHaveClass("w-fit"); }); it("opens model settings from the picker footer", async () => { const onManageModels = vi.fn(); const { badge } = renderPresetComposer("thread", onManageModels); fireEvent.click(badge); const picker = screen.getByRole("dialog", { name: "Switch model" }); fireEvent.click(within(picker).getByRole("button", { name: "Manage presets" })); expect(onManageModels).toHaveBeenCalledTimes(1); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); }); it("keeps long-press drag switching alongside the click picker", () => { vi.useFakeTimers(); const { badge, onPresetChange } = renderPresetComposer(); fireEvent.pointerDown(badge, { pointerId: 1, pointerType: "touch", clientY: 100 }); act(() => vi.advanceTimersByTime(400)); expect(screen.getByTestId("composer-model-pill-viewport")).toBeInTheDocument(); expect(screen.getByTestId("composer-model-pill-layout")).toHaveClass("invisible"); expect(screen.getByTestId("composer-model-pill-track")).not.toHaveClass("transition-transform"); fireEvent.pointerMove(badge, { pointerId: 1, pointerType: "touch", clientY: 56 }); fireEvent.pointerUp(badge, { pointerId: 1, pointerType: "touch", clientY: 56 }); expect(onPresetChange).toHaveBeenCalledWith("dflash"); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); vi.useRealTimers(); }); it("uses the same click picker in hero mode", () => { const { badge, onPresetChange } = renderPresetComposer("hero"); expect(badge).toHaveClass("h-8"); fireEvent.click(badge); fireEvent.click(screen.getByRole("option", { name: "dflash" })); expect(onPresetChange).toHaveBeenCalledWith("dflash"); }); it("switches the same primary button between voice and send as the draft changes", () => { const onSend = vi.fn(); render( "voice")} />); const input = screen.getByRole("textbox"); const action = screen.getByRole("button", { name: "Voice input" }); expect(screen.queryByRole("button", { name: "Send message" })).not.toBeInTheDocument(); fireEvent.change(input, { target: { value: " " } }); expect(screen.getByRole("button", { name: "Voice input" })).toBe(action); fireEvent.change(input, { target: { value: "send this" } }); expect(screen.getByRole("button", { name: "Send message" })).toBe(action); expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument(); fireEvent.click(action); expect(onSend).toHaveBeenCalledWith("send this", undefined, undefined); expect(screen.getByRole("button", { name: "Voice input" })).toBe(action); }); it("uses send for an attachment-only draft and restores voice after removal", async () => { mockBlobUrls(); const { container } = render( "voice")} />); fireEvent.change(container.querySelector('input[type="file"]')!, { target: { files: [new File(["image"], "photo.png", { type: "image/png" })] }, }); await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled()); expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Remove attachment" })); expect(screen.getByRole("button", { name: "Voice input" })).toBeInTheDocument(); }); it("transcribes voice input into the composer without sending", async () => { mockVoiceRecorder(); const onSend = vi.fn(); const onTranscribeAudio = vi.fn(async () => "hello voice"); render( , ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledWith( expect.stringMatching(/^data:audio\/webm;base64,/), expect.objectContaining({ durationMs: expect.any(Number) }), )); await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("hello voice")); expect(onSend).not.toHaveBeenCalled(); }); it("explains the HTTPS requirement for voice input on an insecure origin", async () => { const { getUserMedia } = mockVoiceRecorder(); vi.stubGlobal("isSecureContext", false); render( "unused")} placeholder="Type your message..." />, ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); expect( await screen.findByText( "Chrome and other browsers block microphone access on remote HTTP pages for security. " + "Open this WebUI over HTTPS to use voice input.", ), ).toBeInTheDocument(); expect(screen.getByRole("alert")).toHaveClass("max-h-24"); expect(getUserMedia).not.toHaveBeenCalled(); }); it("keeps the unsupported-browser error for secure origins without recording support", async () => { const { getUserMedia } = mockVoiceRecorder(); vi.stubGlobal("isSecureContext", true); vi.stubGlobal("MediaRecorder", undefined); render( "unused")} placeholder="Type your message..." />, ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); expect( await screen.findByText("Voice input is not supported in this browser."), ).toBeInTheDocument(); expect(getUserMedia).not.toHaveBeenCalled(); }); it("converts voice recordings to wav for Xiaomi MiMo transcription", async () => { mockVoiceRecorder(new Blob([new Uint8Array([1, 2, 3, 4])], { type: "audio/webm" })); const { decodeAudioData } = mockVoiceAudioInput( 180, "running", [new Float32Array([0, 0.5, -0.5])], ); const onTranscribeAudio = vi.fn["onTranscribeAudio"]>>( async () => "mimo voice", ); render( , ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledTimes(1)); const [dataUrl, options] = onTranscribeAudio.mock.calls[0]; expect(dataUrl).toMatch(/^data:audio\/wav;base64,/); expect(options).toEqual(expect.objectContaining({ durationMs: expect.any(Number) })); expect(decodeAudioData).toHaveBeenCalledTimes(1); const bytes = bytesFromDataUrl(dataUrl); const view = new DataView(bytes.buffer); expect(ascii(bytes, 0, 4)).toBe("RIFF"); expect(ascii(bytes, 8, 4)).toBe("WAVE"); expect(ascii(bytes, 12, 4)).toBe("fmt "); expect(view.getUint16(20, true)).toBe(1); expect(view.getUint16(22, true)).toBe(1); expect(view.getUint32(24, true)).toBe(16_000); expect(view.getUint16(34, true)).toBe(16); expect(ascii(bytes, 36, 4)).toBe("data"); await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("mimo voice")); }); it("does not start duplicate voice recordings while microphone access is pending", async () => { const { getUserMedia, stopTrack } = mockVoiceRecorder(); let resolveStream: ((stream: Awaited>) => void) | undefined; getUserMedia.mockImplementation(() => new Promise((resolve) => { resolveStream = resolve; })); const onTranscribeAudio = vi.fn(async () => "one recording"); render( , ); const voiceButton = screen.getByRole("button", { name: "Voice input" }); fireEvent.click(voiceButton); fireEvent.click(voiceButton); expect(getUserMedia).toHaveBeenCalledTimes(1); await act(async () => { resolveStream?.({ getTracks: () => [{ stop: stopTrack }] }); }); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledTimes(1)); await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("one recording")); }); it("distinguishes a missing microphone from a blocked permission", async () => { const { getUserMedia } = mockVoiceRecorder(); getUserMedia.mockRejectedValue(Object.assign(new Error("no microphone"), { name: "NotFoundError", })); render( "unused")} placeholder="Type your message..." />, ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); await waitFor(() => { expect(screen.getByText("No microphone was found. Connect a microphone and try again.")).toBeInTheDocument(); }); }); it("clears a previous voice error when retrying microphone access", async () => { const { getUserMedia } = mockVoiceRecorder(); getUserMedia.mockRejectedValueOnce(new Error("permission denied")); const onTranscribeAudio = vi.fn(async () => "voice retry"); render( , ); const voiceButton = screen.getByRole("button", { name: "Voice input" }); fireEvent.click(voiceButton); await waitFor(() => expect(screen.getByText("Allow microphone access in the address bar, then retry.")).toBeInTheDocument()); fireEvent.click(voiceButton); await waitFor(() => expect(screen.queryByText("Allow microphone access in the address bar, then retry.")).not.toBeInTheDocument()); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); }); it("supports press-and-hold voice recording", async () => { mockVoiceRecorder(); const onSend = vi.fn(); const onTranscribeAudio = vi.fn(async () => "held voice"); render( , ); const voiceButton = screen.getByRole("button", { name: "Voice input" }); fireEvent.pointerDown(voiceButton, { button: 0, pointerId: 1, pointerType: "touch" }); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 180)); }); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.pointerUp(screen.getByRole("button", { name: "Stop recording" }), { pointerId: 1, pointerType: "touch", }); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalled()); await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("held voice")); expect(onSend).not.toHaveBeenCalled(); }); it("supports keyboard hold voice recording", async () => { mockVoiceRecorder(); const onSend = vi.fn(); const onTranscribeAudio = vi.fn(async () => "shortcut voice"); render( , ); const voiceButton = screen.getByRole("button", { name: "Voice input" }); expect(voiceButton).not.toHaveAttribute("title"); expect(voiceButton).toHaveAttribute("aria-keyshortcuts", "Control+Shift+D"); fireEvent.keyDown(window, { code: "KeyD", ctrlKey: true, key: "D", shiftKey: true }); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.keyUp(window, { code: "KeyD", ctrlKey: true, key: "D", shiftKey: true }); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalled()); await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("shortcut voice")); expect(onSend).not.toHaveBeenCalled(); }); it("ignores the delayed click emitted after a long-press voice recording", async () => { const { getUserMedia } = mockVoiceRecorder(); const onSend = vi.fn(); const onTranscribeAudio = vi.fn(async () => "held once"); render( , ); const voiceButton = screen.getByRole("button", { name: "Voice input" }); fireEvent.pointerDown(voiceButton, { button: 0, pointerId: 1, pointerType: "touch" }); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 180)); }); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.pointerUp(screen.getByRole("button", { name: "Stop recording" }), { pointerId: 1, pointerType: "touch", }); await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("held once")); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).not.toHaveBeenCalled(); expect(getUserMedia).toHaveBeenCalledTimes(1); expect(onTranscribeAudio).toHaveBeenCalledTimes(1); }); it("keeps existing text when voice transcription fails", async () => { mockVoiceRecorder(); const onSend = vi.fn(); const onTranscribeAudio = vi.fn(async () => { throw new Error("not_configured"); }); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "draft" } }); fireEvent.keyDown(window, { key: "D", code: "KeyD", ctrlKey: true, shiftKey: true }); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => { expect(screen.getByText("Configure a transcription provider first.")).toBeInTheDocument(); }); expect(input).toHaveValue("draft"); expect(onSend).not.toHaveBeenCalled(); }); it("does not transcribe recordings that are too short", async () => { mockVoiceRecorder(); const onTranscribeAudio = vi.fn(async () => "should not appear"); render( , ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => { expect(screen.getByText("Hold a little longer to record voice.")).toBeInTheDocument(); }); expect(onTranscribeAudio).not.toHaveBeenCalled(); }); it("transcribes recorded audio even when waveform samples are silent", async () => { mockVoiceRecorder(); mockVoiceAudioInput(); const onTranscribeAudio = vi.fn(async () => "quiet voice"); render( , ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 1_150)); }); expect(screen.queryByText("No microphone input detected.")).not.toBeInTheDocument(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledTimes(1)); expect(screen.getByDisplayValue("quiet voice")).toBeInTheDocument(); }); it("does not treat unavailable microphone levels as silence", async () => { mockVoiceRecorder(); mockVoiceAudioInput(128, "suspended"); const onTranscribeAudio = vi.fn(async () => "voice text"); render( , ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 1_150)); }); expect(screen.queryByText("No microphone input detected.")).not.toBeInTheDocument(); fireEvent.click(await screen.findByRole("button", { name: "Stop recording" })); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalledTimes(1)); expect(screen.getByDisplayValue("voice text")).toBeInTheDocument(); }); it.each(["thread", "hero"] as const)("keeps narrow %s permissions inline and usage below without losing the draft", async (variant) => { let width = 390; vi.stubGlobal("innerWidth", width); vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation( () => rect({ width, height: 160 }), ); const onSend = vi.fn(); const onWorkspaceScopeChange = vi.fn(); const { container } = render( {(renderContextUsage) => } , ); const form = container.querySelector("form")!; const input = screen.getByRole("textbox"); const access = screen.getByRole("button", { name: "Workspace access mode: Full Access" }); const meta = container.querySelector(".thread-composer-meta")!; const primary = container.querySelector(".thread-composer-footer-primary")!; expect(form).toHaveAttribute("data-compact-controls", "true"); expect(container.querySelector(".thread-composer-surface")).not.toHaveAttribute("data-compact"); expect(primary).toContainElement(access); expect(meta).toContainElement(screen.getByTestId("composer-context-usage")); expect(within(meta as HTMLElement).getByText("Context 50%")).toBeVisible(); expect(container.querySelector(".thread-composer-footer-actions")).toContainElement(screen.getByLabelText("codex")); fireEvent.change(input, { target: { value: "keep this draft" } }); // A narrow desktop panel uses the same layout; resizing must not replace the textarea. width = 800; vi.stubGlobal("innerWidth", width); fireEvent(window, new Event("resize")); expect(form).not.toHaveAttribute("data-compact-controls"); expect(primary).toContainElement(access); expect(screen.getByRole("textbox")).toBe(input); expect(input).toHaveValue("keep this draft"); expect(container.querySelector(".thread-composer-footer-actions")).toContainElement(screen.getByLabelText("codex")); expect(screen.getAllByRole("button", { name: "Workspace access mode: Full Access" })).toHaveLength(1); width = 320; fireEvent(window, new Event("resize")); expect(form).toHaveAttribute("data-compact-controls", "true"); expect(input).toHaveValue("keep this draft"); fireEvent.click(screen.getByRole("button", { name: "Send message" })); await waitFor(() => expect(onSend).toHaveBeenCalledWith("keep this draft", undefined, undefined)); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); }); it.each(["thread", "hero"] as const)("places %s mobile permission opposite workspace below the composer", async (variant) => { vi.stubGlobal("matchMedia", vi.fn((query: string) => ({ matches: query === "(max-width: 639px)" || query.includes("pointer: coarse"), media: query, addEventListener: vi.fn(), removeEventListener: vi.fn(), }))); vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue(rect({ width: 320, height: 160 })); const scope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const }; const onWorkspaceScopeChange = vi.fn(); const { container } = render( {(renderContextUsage) => } ); const meta = container.querySelector(".thread-composer-meta")!; const workspace = screen.getByRole("button", { name: "Switch directory" }); const access = screen.getByRole("button", { name: "Workspace access mode: Full Access" }); expect(container.querySelector(".thread-composer-surface")!.nextElementSibling).toBe(meta); expect(meta.querySelector(".thread-composer-workspace-group")).toContainElement(workspace); expect(meta).toContainElement(access); const usage = screen.getByTestId("composer-context-usage"); expect(meta).toContainElement(usage); expect(usage).toHaveTextContent(/^50%$/); expect(usage).toHaveAccessibleName("Context 50%. Open context usage"); expect(access.closest(".thread-composer-footer-primary")).toBeNull(); const user = userEvent.setup(); await user.click(access); await user.click(screen.getByRole("menuitemradio", { name: "Default Permission" })); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ access_mode: "restricted" })); }); it.each(["handle tap", "Escape"])("opens narrow context usage as a bottom sheet and restores interaction after %s", async (dismissal) => { vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue( rect({ width: 390, height: 160 }), ); vi.stubGlobal("innerWidth", 390); const user = userEvent.setup(); const onSend = vi.fn(); render( {(renderContextUsage) => } , ); const trigger = screen.getByTestId("composer-context-usage"); await user.click(trigger); const sheet = screen.getByRole("dialog", { name: "Context usage" }); expect(sheet).toHaveClass("mt-auto", "h-[85%]"); expect(sheet.contains(document.activeElement)).toBe(true); expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeInTheDocument(); expect(within(sheet).getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "5"); expect(within(sheet).getByRole("button", { name: "Play context history" })).toBeDisabled(); expect(document.body).toHaveStyle({ pointerEvents: "none" }); if (dismissal === "Escape") await user.keyboard("{Escape}"); else await user.click(within(sheet).getByRole("button", { name: "Close" })); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); expect(document.body).not.toHaveStyle({ pointerEvents: "none" }); expect(trigger).toHaveFocus(); await user.type(screen.getByRole("textbox"), "still works"); await user.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("still works", undefined, undefined); }); it("releases the mobile modal lock when resizing and keeps the desktop sidebar open", async () => { let width = 390; vi.stubGlobal("innerWidth", width); vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation( () => rect({ width, height: 160 }), ); const user = userEvent.setup(); render( {(renderContextUsage) => } ); await user.click(screen.getByTestId("composer-context-usage")); expect(screen.getByRole("dialog")).toHaveClass("mt-auto"); width = 800; vi.stubGlobal("innerWidth", width); fireEvent(window, new Event("resize")); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); expect(document.body).not.toHaveStyle({ pointerEvents: "none" }); expect(screen.getByRole("complementary", { name: "Context usage" })).toBeInTheDocument(); expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "50"); }); it.each([ ["restricted", "Default Permission", "Read files, edit files, and run commands only inside the working directory."], ["full", "Full Access", "Allow file access and commands outside the working directory."], ] as const)("explains the current %s permission on hover", async (mode, label, description) => { const user = userEvent.setup(); render(); const access = screen.getByRole("button", { name: `Workspace access mode: ${label}` }); expect(access).toHaveTextContent(label); expect(document.getElementById(access.getAttribute("aria-describedby")!)).toHaveTextContent(description); await user.hover(access); expect(await screen.findByRole("tooltip")).toHaveTextContent(description); }); it("changes access only after selecting a different menu option and preserves the project", async () => { const user = userEvent.setup(); const onWorkspaceScopeChange = vi.fn(); const restricted: WorkspaceScopePayload = { project_path: "/tmp/project", project_name: "project", access_mode: "restricted", restrict_to_workspace: true, }; const composer = (workspaceScope: WorkspaceScopePayload, disabled = false) => ( ); const { rerender } = render(composer(restricted)); const access = screen.getByRole("button", { name: "Workspace access mode: Default Permission" }); const full = { ...restricted, access_mode: "full" as const, restrict_to_workspace: false }; await user.click(access); expect(screen.getByRole("menuitemradio", { name: "Default Permission" })).toHaveAttribute("aria-checked", "true"); expect(screen.getByRole("menuitemradio", { name: "Full Access" })).toHaveAttribute("aria-checked", "false"); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); await user.click(screen.getByRole("menuitemradio", { name: "Default Permission" })); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); await user.click(access); await user.click(screen.getByRole("menuitemradio", { name: "Full Access" })); expect(onWorkspaceScopeChange).toHaveBeenCalledTimes(1); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(full); expect(screen.queryByRole("menu")).not.toBeInTheDocument(); rerender(composer(full)); expect(access).toHaveAccessibleName("Workspace access mode: Full Access"); await user.click(access); expect(screen.getByRole("menuitemradio", { name: "Full Access" })).toHaveAttribute("aria-checked", "true"); await user.keyboard("{Escape}"); expect(screen.queryByRole("menu")).not.toBeInTheDocument(); expect(onWorkspaceScopeChange).toHaveBeenCalledTimes(1); await waitFor(() => expect(access).toHaveFocus()); await user.keyboard("{Enter}{Home}{Enter}"); expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(restricted); rerender(composer(full, true)); expect(access).toBeDisabled(); await user.click(access); expect(screen.queryByRole("menu")).not.toBeInTheDocument(); expect(onWorkspaceScopeChange).toHaveBeenCalledTimes(2); }); it("opens project selection in a searchable dialog", async () => { const user = userEvent.setup(); const onWorkspaceScopeChange = vi.fn(); const defaultScope = { project_path: "/Users/test/.nanobot/workspace", project_name: "workspace", access_mode: "restricted" as const, restrict_to_workspace: true, }; render( , ); await user.click(screen.getByRole("button", { name: "Switch directory" })); expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument(); expect(screen.getByRole("dialog")).toBeInTheDocument(); await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); fireEvent.change(input, { target: { value: "relative/project" } }); expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument(); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } }); await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/Users/test/project-alpha", project_name: "project-alpha", access_mode: "full", restrict_to_workspace: false, })); await user.click(screen.getByRole("button", { name: "Switch directory" })); await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const reopenedInput = await screen.findByRole("combobox"); fireEvent.change(reopenedInput, { target: { value: "~/Pictures/Photos" } }); await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({ project_path: "/Users/test/Pictures/Photos", project_name: "Photos", access_mode: "full", restrict_to_workspace: false, })); }); it.each([ ["Windows", "D:\\Users\\test\\.nanobot\\workspace", "D:\\path\\to\\project"], ["Windows UNC", "\\\\server\\share\\workspace", "\\\\server\\share\\project"], ["macOS", "/Users/test/.nanobot/workspace", "/Users/name/project"], ["Linux", "/home/test/.nanobot/workspace", "/home/name/project"], ])("accepts a %s project path", async (_, projectPath, selectedPath) => { const user = userEvent.setup(); const onWorkspaceScopeChange = vi.fn(); const defaultScope = { project_path: projectPath, project_name: "workspace", access_mode: "restricted" as const, restrict_to_workspace: true, }; render( , ); await user.click(screen.getByRole("button", { name: "Switch directory" })); fireEvent.change(await screen.findByRole("combobox"), { target: { value: selectedPath } }); await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); fireEvent.keyDown(screen.getByRole("combobox"), { key: "Enter" }); await waitFor(() => expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath }))); }); it("locks project selection independently of the editable permission menu", async () => { const user = userEvent.setup(); const onWorkspaceScopeChange = vi.fn(); const defaultScope = { project_path: "/Users/test/.nanobot/workspace", project_name: "workspace", access_mode: "full" as const, restrict_to_workspace: false, }; const composer = (workspaceControlsHidden: boolean, variant: "hero" | "thread" = "hero", workspaceProjectLocked = false) => ( ); const { container, rerender } = render(composer(false)); const trigger = screen.getByRole("button", { name: "Switch directory" }); expect(trigger).toHaveTextContent("workspace"); const access = screen.getByRole("button", { name: "Workspace access mode: Full Access" }); const footer = container.querySelector(".thread-composer-footer-primary")!; expect(Array.from(footer.querySelectorAll("button"))).toEqual([ screen.getByRole("button", { name: "Attach files" }), access, ]); const meta = container.querySelector(".thread-composer-meta")!; expect(meta).toContainElement(trigger); expect(container.querySelector(".thread-composer-surface")!.nextElementSibling).toBe(meta); rerender(composer(true)); expect(screen.queryByRole("button", { name: "Switch directory" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Workspace access mode: Full Access" })).not.toBeInTheDocument(); rerender(composer(false)); expect(screen.getByRole("button", { name: "Switch directory" })).toBeEnabled(); rerender(composer(false, "thread")); expect(screen.getByRole("button", { name: "Switch directory" })).toBeEnabled(); rerender(composer(false, "thread", true)); expect(screen.queryByRole("button", { name: "Switch directory" })).not.toBeInTheDocument(); expect(container.querySelector(".thread-composer-workspace-label")).not.toBeInTheDocument(); const accessAfterLock = screen.getByRole("button", { name: "Workspace access mode: Full Access" }); await user.click(accessAfterLock); await user.click(screen.getByRole("menuitemradio", { name: "Default Permission" })); expect(onWorkspaceScopeChange).toHaveBeenCalledWith({ ...defaultScope, access_mode: "restricted", restrict_to_workspace: true, }); rerender(composer(true, "thread", true)); expect(screen.queryByText("workspace")).not.toBeInTheDocument(); }); it("keeps the inline permission menu and directory picker mounted across composer widths", () => { let width = 390; vi.stubGlobal("innerWidth", width); vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 })); const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const }; const { container } = render(); const input = screen.getByRole("textbox"); const row = container.querySelector(".thread-composer-meta")!; const trigger = screen.getByRole("button", { name: "Switch directory" }); const access = screen.getByRole("button", { name: "Workspace access mode: Full Access" }); expect(row.querySelector(".thread-composer-workspace-group")).toContainElement(trigger); expect(container.querySelector(".thread-composer-footer-primary")).toContainElement(access); width = 800; vi.stubGlobal("innerWidth", width); fireEvent(window, new Event("resize")); expect(container.querySelector(".thread-composer-meta")).toBe(row); expect(screen.getByRole("button", { name: "Switch directory" })).toBe(trigger); expect(screen.getByRole("button", { name: "Workspace access mode: Full Access" })).toBe(access); expect(screen.getByRole("textbox")).toBe(input); }); it("browses and selects the connected host's project in one dialog on a native client", async () => { const user = userEvent.setup(); const onWorkspaceScopeChange = vi.fn(); const defaultScope = { project_path: "/Users/test/.nanobot/workspace", project_name: "workspace", access_mode: "full" as const, restrict_to_workspace: false, }; const project = { path: `${defaultScope.project_path}/project`, name: "project" }; const onBrowseWorkspaceDirectories = vi.fn((rawPath: string) => { const path = rawPath.replace(/\/$/, ""); return Promise.resolve({ path, parent: path === defaultScope.project_path ? "/Users/test/.nanobot" : defaultScope.project_path, entries: path === defaultScope.project_path ? [project] : [], truncated: false, host: "dev-mac", platform: "Darwin", }); }); const onResolveWorkspaceProject = vi.fn().mockResolvedValue(project); Object.defineProperty(window, "nanobotHost", { configurable: true, value: { getRuntimeInfo: vi.fn(), restartEngine: vi.fn(), openLogs: vi.fn(), exportDiagnostics: vi.fn(), }, }); render( , ); await user.click(screen.getByRole("button", { name: "Switch directory" })); expect(screen.getByRole("dialog", { name: "Choose directory" })).toBeInTheDocument(); await user.click(await screen.findByRole("option", { name: project.path })); await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); await user.click(screen.getByRole("button", { name: "Confirm" })); await waitFor(() => expect(screen.queryByRole("dialog", { name: "Choose directory" })).not.toBeInTheDocument()); expect(onResolveWorkspaceProject).toHaveBeenCalledWith(project.path); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: project.path, project_name: project.name, access_mode: "full", restrict_to_workspace: false, })); }); it("preserves Full Access when selecting an entered host path", async () => { const user = userEvent.setup(); const onWorkspaceScopeChange = vi.fn(); const defaultScope = { project_path: "/srv/nanobot/workspace", project_name: "workspace", access_mode: "full" as const, restrict_to_workspace: false, }; render( , ); await user.click(screen.getByRole("button", { name: "Switch directory" })); expect(await screen.findByRole("combobox")).toBeInTheDocument(); fireEvent.change(screen.getByRole("combobox"), { target: { value: "/srv/nas-project" }, }); await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/nas-project", access_mode: "full", restrict_to_workspace: false, })); }); it("opens a slash command palette and inserts the selected command", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/" } }); const palette = screen.getByRole("listbox", { name: "Slash commands" }); expect(palette).toBeInTheDocument(); expect(palette).toHaveStyle({ maxHeight: "288px" }); expect(screen.queryByRole("option", { name: /\/stop/i })).not.toBeInTheDocument(); expect(screen.getByRole("option", { name: /\/history/i })).toHaveAttribute( "aria-selected", "true", ); fireEvent.keyDown(input, { key: "Enter" }); expect(input).toHaveValue("/history "); expect(screen.getByTestId("composer-slash-command")).toHaveTextContent("/history"); expect(input.previousElementSibling?.textContent).toBe("/history "); expect(onSend).not.toHaveBeenCalled(); expect(screen.queryByRole("listbox", { name: "Slash commands" })).not.toBeInTheDocument(); }); it("offers stop autocomplete once the user starts typing it", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/sto" } }); expect(screen.getByRole("option", { name: /\/stop/i })).toHaveAttribute( "aria-selected", "true", ); fireEvent.keyDown(input, { key: "Enter" }); expect(input).toHaveValue("/stop"); expect(onSend).not.toHaveBeenCalled(); }); it("renders slash commands as direct actions with current status", () => { render( , ); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "/" }, }); expect(screen.getByRole("option", { name: /Model deepseek-v4-pro/i })).toBeInTheDocument(); expect(screen.getByText("Current")).toBeInTheDocument(); expect(screen.getByText("/model [preset]")).toBeInTheDocument(); }); it("prioritizes stop as an immediate slash action while streaming", () => { const onStop = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/" } }); expect(screen.getByRole("option", { name: /Stop task/i })).toHaveAttribute( "aria-selected", "true", ); fireEvent.keyDown(input, { key: "Enter" }); expect(onStop).toHaveBeenCalledTimes(1); expect(input).toHaveValue(""); expect(window.localStorage.getItem("nanobot.webui.slashCommandRecents")).toBeNull(); }); it("orders recent slash commands first for the blank slash menu", () => { window.localStorage.setItem("nanobot.webui.slashCommandRecents", JSON.stringify(["/history"])); render( , ); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "/" }, }); expect(screen.getByRole("option", { name: /\/history/i })).toHaveAttribute( "aria-selected", "true", ); expect(screen.getByText("Recent")).toBeInTheDocument(); }); it("keeps keyboard-selected slash options visible while navigating", () => { const scrollIntoView = vi.fn(); const originalScrollIntoView = HTMLElement.prototype.scrollIntoView; HTMLElement.prototype.scrollIntoView = scrollIntoView; try { render( ({ command: `/cmd-${index}`, title: `Command ${index}`, description: `Description ${index}`, icon: "activity", lifecycle: "side_channel", acceptsArgs: false, }))} />, ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/" } }); scrollIntoView.mockClear(); fireEvent.keyDown(input, { key: "ArrowDown" }); fireEvent.keyDown(input, { key: "ArrowDown" }); expect(screen.getByRole("option", { name: /\/cmd-2/i })).toHaveAttribute( "aria-selected", "true", ); expect(scrollIntoView).toHaveBeenLastCalledWith({ block: "nearest" }); } finally { HTMLElement.prototype.scrollIntoView = originalScrollIntoView; } }); it("opens the CLI app mention palette and inserts the selected app", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@", selectionStart: 1 } }); const palette = screen.getByRole("listbox", { name: "Mentions" }); expect(palette).toBeInTheDocument(); expect(screen.getByRole("option", { name: /@gimp/i })).toHaveAttribute( "aria-selected", "true", ); expect(screen.queryByRole("option", { name: /@krita/i })).not.toBeInTheDocument(); fireEvent.keyDown(input, { key: "ArrowDown" }); expect(screen.getByRole("option", { name: /@blender/i })).toHaveAttribute( "aria-selected", "true", ); fireEvent.keyDown(input, { key: "Enter" }); 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(); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("@blender", undefined, { cliApps: [{ name: "blender", display_name: "Blender", category: "3d", entry_point: "cli-anything-blender", logo_url: null, brand_color: "#E87D0D", }], }); }); it("keeps keyboard-selected mention options visible while navigating", () => { const scrollIntoView = vi.fn(); const originalScrollIntoView = HTMLElement.prototype.scrollIntoView; HTMLElement.prototype.scrollIntoView = scrollIntoView; try { render( ({ name: `app-${index}`, display_name: `App ${index}`, category: "test", description: "Test app", requires: "", source: "harness", entry_point: `app-${index}`, install_supported: true, installed: true, available: true, status: "installed", logo_url: null, brand_color: "#111827", skill_installed: true, }))} />, ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@", selectionStart: 1 } }); scrollIntoView.mockClear(); fireEvent.keyDown(input, { key: "ArrowDown" }); fireEvent.keyDown(input, { key: "ArrowDown" }); expect(screen.getByRole("option", { name: /@app-2/i })).toHaveAttribute( "aria-selected", "true", ); expect(scrollIntoView).toHaveBeenLastCalledWith({ block: "nearest" }); } finally { HTMLElement.prototype.scrollIntoView = originalScrollIntoView; } }); it("completes a CLI app mention with Tab and adds exactly one trailing space", () => { render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "use @ble", selectionStart: 8 }, }); fireEvent.keyDown(input, { key: "Tab" }); 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", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "use @bro", selectionStart: 8 }, }); expect(screen.getByRole("option", { name: /@browserbase/i })).toBeInTheDocument(); expect(screen.queryByRole("option", { name: /@figma/i })).not.toBeInTheDocument(); fireEvent.keyDown(input, { key: "Tab" }); expect(input).toHaveValue("use @\u00a0Browserbase "); const mention = screen.getByTestId("composer-mcp-mention-browserbase"); expect(mention.textContent).toBe("@\u00a0Browserbase"); expect(mention).toHaveClass("font-normal"); expect(mention).not.toHaveClass("font-[550]"); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("use @browserbase", undefined, { mcpPresets: [{ name: "browserbase", display_name: "Browserbase", category: "browser", transport: "streamableHttp", status: "configured", configured: true, logo_url: "https://example.invalid/browserbase.svg", brand_color: "#111827", }], }); }); 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(); 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(); 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(); 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(); 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(); 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(); 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(); 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( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "参考 @收费", selectionStart: 6 }, }); expect(screen.getByRole("group", { name: "Nanobot conversations" })).toBeInTheDocument(); expect(screen.getByRole("option", { name: /@收费设计/i })).toBeInTheDocument(); fireEvent.keyDown(input, { key: "Tab" }); expect(input).toHaveValue("参考 @收费设计 "); const mention = screen.getByTestId("composer-session-mention-收费设计"); expect(mention).toHaveTextContent("@收费设计"); expect(mention).toHaveClass("font-normal"); expect(mention).not.toHaveClass("font-[550]"); expect(mention.closest("a")).toBeNull(); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("参考 @收费设计", undefined, { sessionMentions: [{ id: session("pricing", "收费设计").handle?.id, name: "收费设计", session_key: "websocket:pricing", title: "收费设计", }], }); }); it("turns a dropped sidebar session into the shared structured mention", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; fireEvent.change(input, { target: { value: "Compare notes" } }); input.setSelectionRange(7, 7); const dataTransfer = { types: [SESSION_DRAG_TYPE], effectAllowed: "copy", dropEffect: "none", files: [], getData: (type: string) => ( type === SESSION_DRAG_TYPE ? "websocket:pricing" : "" ), }; fireEvent.dragEnter(input, { dataTransfer }); fireEvent.dragOver(input, { dataTransfer }); expect(input).toHaveValue("Compare notes"); expect(screen.getByTestId("composer-session-drag-preview")) .toHaveTextContent("@收费设计"); fireEvent.dragEnd(document); expect(screen.queryByTestId("composer-session-drag-preview")).not.toBeInTheDocument(); fireEvent.dragEnter(input, { dataTransfer }); fireEvent.dragOver(input, { dataTransfer }); fireEvent.drop(input, { dataTransfer }); expect(input).toHaveValue("Compare @收费设计 notes"); expect(screen.queryByTestId("composer-session-drag-preview")).not.toBeInTheDocument(); expect(screen.getByTestId("composer-session-mention-收费设计")) .toHaveTextContent("@收费设计"); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("Compare @收费设计 notes", undefined, { sessionMentions: [{ id: session("pricing", "收费设计").handle?.id, name: "收费设计", session_key: "websocket:pricing", title: "收费设计", }], }); }); it("rejects self-session drops that are unavailable to the composer", () => { render( , ); const input = screen.getByLabelText("Message input"); const dataTransfer = { types: [SESSION_DRAG_TYPE], effectAllowed: "copyMove", dropEffect: "copy", files: [], getData: () => "websocket:current", }; expect(fireEvent.dragEnter(input, { dataTransfer })).toBe(true); expect(fireEvent.dragOver(input, { dataTransfer })).toBe(true); expect(screen.queryByTestId("composer-session-drag-preview")).not.toBeInTheDocument(); }); it.each([" ", "、"])("rejects more than eight typed session references separated by %j without silently dropping them", (separator) => { const onSend = vi.fn(); const targets = Array.from({ length: 9 }, (_, index) => session(`topic-${index}`, `Topic${index}`)); render(); const input = screen.getByLabelText("Message input"); const handles = targets.map((target) => `@${target.handle?.name}`); fireEvent.change(input, { target: { value: handles.join(separator) } }); for (const target of targets) { expect(screen.getByTestId(`composer-session-mention-${target.handle?.name}`)).toBeInTheDocument(); } 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)); }); 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(); 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( , ); const input = screen.getByLabelText("Message input"); 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( , ); expect(screen.getByTestId("composer-session-mention-Plan")).toHaveTextContent("@Plan"); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.click(screen.getByRole("button", { name: "Send now" })); expect(onSend).toHaveBeenCalledWith("@Plan", undefined, { sessionMentions: [{ id: session("z-target", "Plan").handle?.id, name: "Plan", session_key: "websocket:z-target", title: "Plan", }], continueActiveTurn: true, }); }); 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) => ; 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("highlights slash commands alongside skills without changing native edits or sending", () => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; const text = "/history $workflow 中文 English"; fireEvent.change(input, { target: { value: text, selectionStart: text.length } }); const command = screen.getByTestId("composer-slash-command"); const skill = screen.getByTestId("composer-skill-reference-workflow"); expect(command).toHaveTextContent("/history"); expect(command.className).toBe(skill.className); expect(command.getAttribute("style")).toBe(skill.getAttribute("style")); expect(input.previousElementSibling).toHaveAttribute("aria-hidden", "true"); expect(input.previousElementSibling?.textContent).toBe(text); input.setSelectionRange(1, 4); const setData = vi.fn(); fireEvent.copy(input, { clipboardData: { setData } }); expect(setData).toHaveBeenCalledWith("text/plain", "his"); fireEvent.cut(input, { clipboardData: { setData } }); expect(input).toHaveValue("/tory $workflow 中文 English"); expect(screen.queryByTestId("composer-slash-command")).not.toBeInTheDocument(); fireEvent.keyDown(input, { key: "z", ctrlKey: true }); expect(input).toHaveValue(text); expect(input.selectionStart).toBe(1); expect(input.selectionEnd).toBe(4); expect(screen.getByTestId("composer-slash-command")).toHaveTextContent("/history"); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith(text, undefined, { sideChannel: true }); }); it("highlights literal skill references while preserving partial edits, clipboard text and sending", () => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; const text = "like $workflow 与 $skill-creator,$"; fireEvent.change(input, { target: { value: text, selectionStart: text.length } }); expect(screen.getByTestId("composer-skill-reference-workflow")).toHaveTextContent(/^\$workflow$/); expect(screen.getByTestId("composer-skill-reference-skill-creator")).toHaveTextContent(/^\$skill-creator$/); expect(input).toHaveValue(text); expect(input.previousElementSibling).toHaveAttribute("aria-hidden", "true"); expect(input.previousElementSibling?.textContent).toBe(text); const start = text.indexOf("workflow") + 1; const end = start + 4; input.setSelectionRange(start, end); const setData = vi.fn(); fireEvent.copy(input, { clipboardData: { setData } }); expect(setData).toHaveBeenCalledWith("text/plain", text.slice(start, end)); fireEvent.cut(input, { clipboardData: { setData } }); expect(input).toHaveValue(text.slice(0, start) + text.slice(end)); fireEvent.keyDown(input, { key: "z", ctrlKey: true }); expect(input).toHaveValue(text); expect(input.selectionStart).toBe(start); expect(input.selectionEnd).toBe(end); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith(text, undefined, undefined); }); it("highlights only the leading bang with the skill-reference color and preserves literal command text", () => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; fireEvent.change(input, { target: { value: "$workflow " } }); const referenceColor = screen.getByTestId("composer-skill-reference-workflow").style.color; const command = ' !echo "hello! $workflow @typography"\nWrite-Output done'; fireEvent.change(input, { target: { value: command } }); const bang = screen.getByTestId("composer-shell-prefix"); expect(bang).toHaveTextContent(/^!$/); expect(bang.style.color).toBe(referenceColor); expect(input.previousElementSibling).toHaveAttribute("aria-hidden", "true"); expect(input.previousElementSibling?.textContent).toBe(command); expect(input).toHaveValue(command); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledWith(command.trim(), undefined, { sideChannel: true, userShell: true }); }); it.each(["", "/history "])("mirrors inline references during composition without submitting the IME confirmation: %s", (prefix) => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; fireEvent.change(input, { target: { value: `${prefix}$workflow ` } }); fireEvent.compositionStart(input); fireEvent.change(input, { target: { value: `${prefix}$workflow zhong` } }); if (prefix) expect(screen.getByTestId("composer-slash-command")).toHaveTextContent("/history"); expect(screen.getByTestId("composer-skill-reference-workflow")).toHaveTextContent(/^\$workflow$/); expect(input.previousElementSibling?.textContent).toBe(input.value); expect(input.previousElementSibling).toHaveClass("z-20"); fireEvent.keyDown(input, { key: "Enter", isComposing: true }); expect(onSend).not.toHaveBeenCalled(); fireEvent.change(input, { target: { value: `${prefix}$workflow 中` } }); fireEvent.compositionEnd(input, { data: "中" }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith(`${prefix}$workflow 中`, undefined, prefix ? { sideChannel: true } : undefined); }); it("opens skills only from a $ reference and prioritizes the skill name", () => { const skillName = "arxiv-intelligence-filter"; render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/git", selectionStart: 4 } }); expect(screen.queryByRole("listbox", { name: "Slash commands" })).not.toBeInTheDocument(); fireEvent.change(input, { target: { value: "please use $arxiv", selectionStart: 17 } }); const palette = screen.getByRole("listbox", { name: "Slash commands" }); const option = within(palette).getByRole("option", { name: new RegExp(skillName, "i") }); const name = within(option).getByText(skillName); expect(name).not.toHaveClass("truncate"); expect(within(option).queryByText(`$${skillName}`)).not.toBeInTheDocument(); expect(within(palette).queryByText("arxiv-disabled")).not.toBeInTheDocument(); expect(within(palette).queryByText("arxiv-unavailable")).not.toBeInTheDocument(); expect(within(palette).queryByText("/model")).not.toBeInTheDocument(); fireEvent.keyDown(input, { key: "Tab" }); expect(input).toHaveValue(`please use $${skillName} `); expect(screen.getByTestId(`composer-skill-reference-${skillName}`)) .toHaveTextContent(`$${skillName}`); }); it("ranks skill name matches ahead of earlier description matches", () => { render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "$up", selectionStart: 3 } }); const options = within(screen.getByRole("listbox", { name: "Slash commands" })) .getAllByRole("option"); expect(options.map((option) => option.textContent)).toEqual([ "upExact match", "upload-filesTransfer local files", "setup-updateConfigure upgrades", "skill-creatorCreate or update AgentSkills", ]); }); it("keeps a recently selected skill visible at the top of the blank skill menu", () => { const skills = Array.from({ length: 9 }, (_, index) => ({ name: `skill-${index}`, description: `Skill ${index}`, source: "builtin", available: true, })); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "$skill-8", selectionStart: 8 } }); fireEvent.keyDown(input, { key: "Tab" }); fireEvent.change(input, { target: { value: "$", selectionStart: 1 } }); const options = within(screen.getByRole("listbox", { name: "Slash commands" })) .getAllByRole("option"); expect(options).toHaveLength(8); expect(options[0]).toHaveTextContent("skill-8"); expect(options[0]).toHaveTextContent("Recent"); }); it("shows session handles without an icon and preserves app icons after their identifiers", () => { render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@", selectionStart: 1 } }); const conversation = screen.getByRole("option", { name: /@bime Pricing/i }); const app = screen.getByRole("option", { name: /@gimp GIMP/i }); const mcp = screen.getByRole("option", { name: /@browserbase Browserbase/i }); expect(conversation.children[0]).toHaveTextContent("@bime"); expect(conversation.children[1]).toHaveTextContent("Pricing"); expect(conversation.querySelector('[data-product-icon="conversation"]')).not.toBeInTheDocument(); expect(app.children[0]).toHaveTextContent("@gimp"); expect(app.children[1].querySelector("img")).toHaveAttribute("src", CLI_APPS[0].logo_url); expect(app.children[1]).toHaveTextContent("GIMP"); expect(mcp.children[0]).toHaveTextContent("@browserbase"); expect(mcp.children[1].querySelector("img")).toHaveAttribute("src", MCP_PRESETS[0].logo_url); expect(mcp.children[1]).toHaveTextContent("Browserbase"); }); it("shows right-side source badges so users can distinguish CLI apps from MCP servers", () => { render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@", selectionStart: 1 } }); expect(screen.queryByText("CLI Apps")).not.toBeInTheDocument(); expect(screen.queryByText("MCP servers")).not.toBeInTheDocument(); const gimp = screen.getByRole("option", { name: /@gimp GIMP .* CLI/i }); const browserbase = screen.getByRole("option", { name: /@browserbase Browserbase .* MCP/i }); expect(gimp).toHaveClass("touch-target"); expect(browserbase).toHaveClass("touch-target"); expect(within(gimp).getByText("CLI")).toBeInTheDocument(); expect(within(browserbase).getByText("MCP")).toBeInTheDocument(); expect(within(gimp).getByText("@gimp")).toBeInTheDocument(); expect(within(browserbase).getByText("@browserbase")).toBeInTheDocument(); }); it("does not duplicate the next word separator when completing a CLI app mention", () => { render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "use @ble tonight", selectionStart: 8 }, }); fireEvent.keyDown(input, { key: "Tab" }); expect(input).toHaveValue("use @Blender tonight"); }); it("keeps literal mixed-script spacing in both composer input layers", () => { render(); const input = screen.getByLabelText("Message input"); const value = "定位原因, 提 @gimp issue, i并提 $workflow"; fireEvent.change(input, { target: { value, selectionStart: value.length } }); const display = "定位原因, 提 @\u00a0GIMP issue, i并提 $workflow"; const overlay = input.previousElementSibling; expect(input).toHaveValue(display); expect(overlay).toHaveAttribute("aria-hidden", "true"); expect(overlay?.textContent).toBe(display); expect(input).toHaveClass("[text-autospace:no-autospace]"); expect(overlay).toHaveClass("[text-autospace:no-autospace]"); expect(screen.getByTestId("composer-skill-reference-workflow")).toHaveTextContent("$workflow"); }); it("renders a CLI app mention logo inline without moving the text cursor slot", () => { render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "meeting in @gimp", selectionStart: 16 }, }); expect(input).toHaveValue("meeting in @\u00a0GIMP"); const token = screen.getByTestId("composer-cli-mention-gimp"); expect(token.textContent).toBe("@\u00a0GIMP"); expect(token).toHaveClass("font-normal"); expect(token).not.toHaveClass("font-[550]"); expect(token.className).not.toContain("zoom-in"); expect(token.className).not.toContain("px-"); expect(token.className).not.toContain("mx-"); expect(token).toHaveClass("text-foreground"); expect(token.style.textShadow).toBe(""); 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-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.each(["cli", "mcp"] as const)("emphasizes the %s brand without changing composer text metrics", (kind) => { render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@linear 帮我查看", selectionStart: 12 } }); const token = screen.getByTestId(`composer-${kind}-mention-linear`); const name = token.lastElementChild!; expect(name).toHaveTextContent("Linear"); expect(name).toHaveClass("[-webkit-text-stroke:0.4px_currentColor]"); expect(token).toHaveClass("font-normal"); expect(token.firstElementChild).not.toHaveClass("[-webkit-text-stroke:0.4px_currentColor]"); expect(input).toHaveValue("@\u00a0Linear 帮我查看"); expect(input).not.toHaveClass("font-semibold"); fireEvent.compositionStart(input); fireEvent.change(input, { target: { value: "@\u00a0Linear 帮我查看n" } }); expect(token.lastElementChild).toBe(name); expect(name).toHaveClass("[-webkit-text-stroke:0.4px_currentColor]"); }); it("uses the theme foreground when an installed CLI app has no brand metadata", () => { const mention = "@obsidian-agent-cli"; const app: CliAppInfo = { name: "obsidian-agent-cli", display_name: "Obsidian CLI", category: "productivity", description: "Obsidian automation", requires: "", source: "local", entry_point: "obsidian-agent", install_supported: true, installed: true, available: true, status: "installed", logo_url: null, brand_color: null, skill_installed: true, }; render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: mention, selectionStart: mention.length }, }); const token = screen.getByTestId("composer-cli-mention-obsidian-agent-cli"); expect(token).toHaveClass("text-foreground"); }); 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(); 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(); 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(); 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(); 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("does not remove a mention when composition is canceled inside its label", () => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input") as HTMLTextAreaElement; fireEvent.change(input, { target: { value: "@drive next" } }); input.setSelectionRange(4, 4); fireEvent.compositionStart(input); fireEvent.change(input, { target: { value: "@\u00a0Gonogle Drive next", selectionStart: 5 } }); fireEvent.change(input, { target: { value: "@\u00a0Google Drive next", selectionStart: 4 } }); fireEvent.compositionEnd(input, { data: "" }); expect(input).toHaveValue("@\u00a0Google Drive next"); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("@drive next", undefined, { mcpPresets: [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(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@gimp " } }); fireEvent.compositionStart(input); fireEvent.change(input, { target: { value: "@\u00a0GIMP 草稿" } }); rerender(); 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(); 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 }), ); Object.defineProperty(window, "innerHeight", { value: 330, configurable: true, }); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/" } }); await waitFor(() => { const palette = screen.getByRole("listbox", { name: "Slash commands" }); expect(palette.className).toContain("top-full"); expect(palette).toHaveStyle({ maxHeight: "162px" }); }); }); it("keeps the slash command palette above a keyboard-constrained visual viewport", async () => { vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue( rect({ top: 120, bottom: 220, width: 390, height: 100 }), ); Object.defineProperty(window, "innerHeight", { value: 800, configurable: true, }); stubVisualViewport({ height: 300 }); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/" } }); await waitFor(() => { const palette = screen.getByRole("listbox", { name: "Slash commands" }); expect(palette.className).toContain("bottom-full"); expect(palette).toHaveStyle({ maxHeight: "112px" }); }); }); it.each(["/", "@"]) ("fits %s suggestions in the app frame while iOS pans the keyboard", (trigger) => { stubVisualViewport({ height: 396, offsetTop: 350 }); let formTop = 274; let frameHeight = 396; vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation( () => rect({ top: formTop, width: 388, height: 112 }), ); vi.spyOn(HTMLDivElement.prototype, "getBoundingClientRect").mockImplementation( () => rect({ top: 0, width: 420, height: frameHeight }), ); render(
, ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: trigger, selectionStart: 1 } }); const palette = screen.getByRole("listbox"); expect(palette).toHaveClass("bottom-full"); expect(palette).toHaveStyle({ maxHeight: "266px" }); // Keyboard dismissal moves the composer; keep measuring the same frame. formTop = 620; frameHeight = 746; Object.assign(window.visualViewport!, { height: 746, offsetTop: 0 }); act(() => window.visualViewport!.dispatchEvent(new Event("resize"))); expect(palette).toHaveStyle({ maxHeight: "288px" }); fireEvent.keyDown(input, { key: "Enter" }); expect(screen.queryByRole("listbox")).not.toBeInTheDocument(); expect(input).not.toHaveValue(trigger); }); it.each(["/", "@"]) ("keeps %s selectable beside the input in a short landscape frame", (trigger) => { stubVisualViewport({ height: 128, offsetTop: 208 }); let landscape = true; vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation( () => rect({ top: landscape ? 44 : 274, width: landscape ? 744 : 388, height: 112 }), ); vi.spyOn(HTMLDivElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLDivElement) { return this.id === "root" ? rect({ top: 0, width: landscape ? 776 : 420, height: landscape ? 128 : 396 }) : rect({ top: landscape ? 44 : 0, width: landscape ? 776 : 420, height: landscape ? 84 : 396 }); }); const onSend = vi.fn(); render(
, ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: trigger, selectionStart: 1 } }); const palette = screen.getByRole("listbox"); expect(palette).toHaveClass("col-start-2"); expect(palette).not.toHaveClass("absolute"); expect(palette).toHaveStyle({ maxHeight: "84px" }); expect(input.closest("form")).toHaveAttribute("data-palette-beside", "true"); landscape = false; document.getElementById("root")!.classList.remove("short-visual-viewport"); Object.assign(window.visualViewport!, { height: 396, offsetTop: 350 }); act(() => window.visualViewport!.dispatchEvent(new Event("resize"))); expect(palette).toHaveClass("bottom-full"); expect(palette).toHaveStyle({ maxHeight: "266px" }); expect(input).toHaveValue(trigger); fireEvent.mouseDown(screen.getAllByRole("option")[0]!); expect(screen.queryByRole("listbox")).not.toBeInTheDocument(); expect(input.closest("form")).not.toHaveAttribute("data-palette-beside"); expect(onSend).not.toHaveBeenCalled(); }); it.each([false, true])("uses visual bounds outside fitting (pinch zoom: %s)", (zoomed) => { stubVisualViewport({ height: 300, offsetTop: 100 }); if (zoomed) Object.assign(window.visualViewport!, { scale: 2 }); vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue( rect({ top: 220, width: 390, height: 100 }), ); render(
, ); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "/" } }); expect(screen.getByRole("listbox")).toHaveStyle({ maxHeight: "112px" }); expect(screen.getByRole("listbox")).toHaveClass("bottom-full"); }); it("dismisses the slash command palette on outside click", () => { render(
, ); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "/" }, }); expect(screen.getByRole("listbox", { name: "Slash commands" })).toBeInTheDocument(); fireEvent.pointerDown(screen.getByRole("button", { name: "outside" })); expect(screen.queryByRole("listbox", { name: "Slash commands" })).not.toBeInTheDocument(); }); it("keeps image generation mode out of the composer chrome", () => { const onSend = vi.fn(); render( , ); expect(screen.queryByRole("button", { name: "Image mode" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Image aspect ratio" })).not.toBeInTheDocument(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "Draw a friendly robot" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("Draw a friendly robot", undefined, undefined); }); it.each(["!pwd", " ! pwd ", "!Write-Output first\nWrite-Output second", "!"])("runs bang input directly without a configured model: %s", (command) => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: command } }); fireEvent.click(screen.getByRole("button", { name: "Run Shell command" })); expect(onSend).toHaveBeenCalledWith(command.trim(), undefined, { sideChannel: true, userShell: true }); expect(input).toHaveValue(""); }); it("keeps bang commands separate from pending guidance and the active turn", async () => { const onSend = vi.fn(); const onStop = vi.fn(); const { rerender } = render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "waiting guidance" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.change(input, { target: { value: "!pwd" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledOnce(); expect(onSend).toHaveBeenCalledWith("!pwd", undefined, { sideChannel: true, userShell: true }); expect(within(screen.getByRole("group", { name: "Waiting to send" })).getByText("waiting guidance")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); expect(onStop).not.toHaveBeenCalled(); rerender(); await waitFor(() => expect(onSend).toHaveBeenCalledTimes(2)); expect(onSend).toHaveBeenLastCalledWith("waiting guidance"); }); it.each(["!echo @gimp", "!echo $weather"])("keeps bang arguments literal instead of opening a mention or skill menu: %s", (command) => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: command, selectionStart: command.length } }); expect(input).toHaveValue(command); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledWith(command, undefined, { sideChannel: true, userShell: true }); }); it("keeps exclamation marks inside ordinary messages on the chat path", () => { const onSend = vi.fn(); render(); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "Please explain !pwd" } }); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" }); expect(onSend).toHaveBeenCalledWith("Please explain !pwd", undefined, undefined); }); it("retains a bang draft when delivery is rejected without retrying it", async () => { const onSend = vi.fn().mockRejectedValue(new Error("Shell send rejected")); const { rerender } = render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "!pwd" } }); fireEvent.keyDown(input, { key: "Enter" }); await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Shell send rejected")); expect(input).toHaveValue("!pwd"); rerender(); expect(onSend).toHaveBeenCalledOnce(); expect(onSend).toHaveBeenCalledWith("!pwd", undefined, { sideChannel: true, userShell: true }); }); it("rejects attachments on bang input without losing the draft or attachment", async () => { const onSend = vi.fn(); const { container } = render(); fireEvent.change(container.querySelector('input[type="file"]')!, { target: { files: [new File(["image"], "photo.png", { type: "image/png" })] }, }); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "!pwd" } }); await waitFor(() => expect(screen.getByRole("button", { name: "Run Shell command" })).toBeEnabled()); fireEvent.keyDown(input, { key: "Enter" }); expect(screen.getByRole("alert")).toHaveTextContent("Remove attachments and quoted text before running a command."); expect(onSend).not.toHaveBeenCalled(); expect(input).toHaveValue("!pwd"); expect(screen.getByRole("button", { name: "Remove attachment" })).toHaveAttribute("aria-description", "photo.png"); }); it("rejects quoted context on bang input without clearing it", () => { const onSend = vi.fn(); const onQuotedContextChange = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "!pwd" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(screen.getByRole("alert")).toHaveTextContent("Remove attachments and quoted text before running a command."); expect(input).toHaveValue("!pwd"); expect(onSend).not.toHaveBeenCalled(); expect(onQuotedContextChange).not.toHaveBeenCalled(); }); it("marks known slash commands as side-channel sends", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/history" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("/history", undefined, { sideChannel: true }); }); it("does not infer side-channel behavior before command metadata loads", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/status" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("/status", undefined, undefined); }); it("sends a possible stop command without waiting when command metadata is unavailable", () => { const onSend = vi.fn(); const onStop = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/stop" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledWith("/stop", undefined, { continueActiveTurn: true }); expect(onStop).not.toHaveBeenCalled(); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }); it("marks new chat commands as side-channel sends that finalize the active turn", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/new" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith( "/new", undefined, { sideChannel: true, finalizeActiveTurn: true }, ); }); it("does not classify exact-only slash commands with arguments", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/new with a title" } }); expect(screen.queryByTestId("composer-slash-command")).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("/new with a title", undefined, undefined); }); it("routes a manually submitted stop command through the stop handler", () => { const onSend = vi.fn(); const onStop = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/stop" } }); fireEvent.keyDown(input, { key: "Escape" }); fireEvent.keyDown(input, { key: "Enter" }); expect(onStop).toHaveBeenCalledTimes(1); expect(onSend).not.toHaveBeenCalled(); }); it("keeps goal task commands on the normal agent turn path", () => { const onSend = vi.fn(); render( ", lifecycle: "agent_turn_with_args", acceptsArgs: true, }, ]} />, ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/goal fix the release blocker" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith( "/goal fix the release blocker", undefined, undefined, ); }); it("keeps goal usage commands on the side-channel path", () => { const onSend = vi.fn(); render( ", lifecycle: "agent_turn_with_args", acceptsArgs: true, }, ]} />, ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "/goal" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("/goal", undefined, { sideChannel: true }); }); it("shows a stop button while streaming", () => { const onStop = vi.fn(); render( , ); fireEvent.click(screen.getByRole("button", { name: "Stop response" })); expect(onStop).toHaveBeenCalledTimes(1); expect(screen.queryByRole("button", { name: "Send message" })).not.toBeInTheDocument(); }); it("switches the primary action from Stop to Send while streaming once the user types", () => { const onSend = vi.fn(); const onStop = vi.fn(); render( , ); expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "one more thing: " } }); expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onStop).not.toHaveBeenCalled(); expect(onSend).toHaveBeenCalledWith("one more thing:", undefined, { continueActiveTurn: true, }); }); it("interjects with the send button on coarse-pointer devices while streaming", () => { stubCoarsePointer(); const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "hold on, actually…" } }); const keyEvent = createEvent.keyDown(input, { key: "Enter" }); fireEvent(input, keyEvent); expect(keyEvent.defaultPrevented).toBe(false); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByRole("button", { name: "Send message" })).toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("hold on, actually…", undefined, { continueActiveTurn: true, }); }); it("includes waiting guidance when the send button submits a newer draft", () => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "waiting guidance" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.change(input, { target: { value: "send this now" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("waiting guidance\nsend this now", undefined, { continueActiveTurn: true }); expect(onSend).toHaveBeenCalledTimes(1); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }); it("does not mark side-channel commands as guidance during an active turn", () => { const onSend = vi.fn(); render(); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "/history 5" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("/history 5", undefined, { sideChannel: true }); }); it("keeps Stop available while a draft attachment is encoding", () => { vi.mocked(encodeImage).mockReturnValueOnce(new Promise(() => {})); const onStop = vi.fn(); const { container } = render(); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "unfinished draft" } }); fireEvent.change(container.querySelector('input[type="file"]')!, { target: { files: [new File(["image"], "photo.png", { type: "image/png" })] }, }); fireEvent.click(screen.getByRole("button", { name: "Stop response" })); expect(onStop).toHaveBeenCalledOnce(); expect(screen.getByLabelText("Message input")).toHaveValue("unfinished draft"); }); it("queues plain guidance while a task is running", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); expect(input).toHaveAttribute("placeholder", "Type your message..."); fireEvent.change(input, { target: { value: "keep the UI minimal" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).not.toHaveBeenCalled(); expect(input).toHaveValue(""); expect(screen.getByText("keep the UI minimal")).toBeInTheDocument(); expect(screen.getByText("Waiting to send")).toBeInTheDocument(); expect(screen.queryByText( "Send now, or wait for the current response to finish.", )).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Send now" })); expect(onSend).toHaveBeenCalledWith( "keep the UI minimal", undefined, { continueActiveTurn: true }, ); expect(screen.queryByText("keep the UI minimal")).not.toBeInTheDocument(); }); it.each(["/tmp", "/home/user/project", "/stop/config.json", "/neaw"])( "queues ordinary slash-prefixed text %s until the response finishes", (content) => { const onSend = vi.fn(); const composer = (isStreaming: boolean) => ( ); const { rerender } = render(composer(true)); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: content } }); expect(screen.queryByTestId("composer-slash-command")).not.toBeInTheDocument(); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent(content); rerender(composer(false)); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith(content); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }, ); it.each(["/history 5", "/stop now", "/STOP@nanobot now"])( "sends registered command %s to the gateway without queuing it", (content) => { const onSend = vi.fn(); render(); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: content } }); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" }); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend.mock.calls[0][0]).toBe(content); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }, ); it("guides queued guidance when Enter is pressed again", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "send this guidance now" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).not.toHaveBeenCalled(); expect(input).toHaveValue(""); expect(screen.getByText("send this guidance now")).toBeInTheDocument(); fireEvent.keyDown(input, { key: "Enter", repeat: true }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByText("send this guidance now")).toBeInTheDocument(); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledWith( "send this guidance now", undefined, { continueActiveTurn: true }, ); expect(onSend).toHaveBeenCalledTimes(1); expect(screen.queryByText("send this guidance now")).not.toBeInTheDocument(); }); it("does not send waiting guidance during keyboard recording or transcription", async () => { mockVoiceRecorder(); const onSend = vi.fn(); let finishTranscription!: (text: string) => void; const onTranscribeAudio = vi.fn(() => new Promise((resolve) => { finishTranscription = resolve; })); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "keep this queued" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.keyDown(window, { code: "KeyD", ctrlKey: true, key: "D", shiftKey: true }); expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument(); expect(input).toHaveFocus(); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByText("keep this queued")).toBeInTheDocument(); await waitForVoiceCapture(); fireEvent.keyUp(window, { code: "KeyD", ctrlKey: true, key: "D", shiftKey: true }); await waitFor(() => expect(onTranscribeAudio).toHaveBeenCalled()); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("keep this queued"); await act(async () => { finishTranscription("voice guidance"); }); expect(input).toHaveValue("voice guidance"); }); it("keeps stopped guidance paused until an explicit Enter", () => { const onSend = vi.fn(); const onStop = vi.fn(); const { rerender } = render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "keep this queued" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.click(screen.getByRole("button", { name: "Stop response" })); expect(onStop).toHaveBeenCalledTimes(1); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByText("keep this queued")).toBeInTheDocument(); rerender( , ); rerender( , ); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByText("keep this queued")).toBeInTheDocument(); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" }); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith( "keep this queued", undefined, { continueActiveTurn: true }, ); }); it.each(["refocusing", "clearing edits"])("sends waiting guidance with Enter after %s", (interaction) => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "leave this queued" } }); fireEvent.keyDown(input, { key: "Enter" }); if (interaction === "refocusing") { fireEvent.blur(input); fireEvent.focus(input); } else { fireEvent.change(input, { target: { value: "x" } }); fireEvent.change(input, { target: { value: "" } }); } expect(onSend).not.toHaveBeenCalled(); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith( "leave this queued", undefined, { continueActiveTurn: true }, ); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }); it.each(["shiftKey", "altKey", "ctrlKey", "metaKey"])("keeps waiting guidance on modified Enter (%s)", (modifier) => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "waiting guidance" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.keyDown(input, { key: "Enter", [modifier]: true }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("waiting guidance"); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith("waiting guidance", undefined, { continueActiveTurn: true }); }); it("keeps waiting guidance during IME confirmation and sends after composition ends", () => { const onSend = vi.fn(); render(); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "waiting guidance" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.compositionStart(input); fireEvent.keyDown(input, { key: "Enter", isComposing: true }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("waiting guidance"); fireEvent.compositionEnd(input, { data: "" }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith( "waiting guidance", undefined, { continueActiveTurn: true }, ); }); it("merges consecutive queued inputs and interjects the whole message on a second Enter", () => { const onSend = vi.fn(); render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "older guidance" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.change(input, { target: { value: "guide this one now" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).toHaveBeenCalledWith( "older guidance\nguide this one now", undefined, { continueActiveTurn: true }, ); expect(onSend).toHaveBeenCalledTimes(1); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }); it("shows one pending message and sends all consecutive inputs once after completion", async () => { const onSend = vi.fn(); const { rerender } = render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "first follow-up" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.change(input, { target: { value: "second follow-up" } }); fireEvent.keyDown(input, { key: "Enter" }); const queue = screen.getByRole("group", { name: "Waiting to send" }); expect(queue).toHaveClass("composer-status-strip"); expect(queue).toHaveClass("mx-3"); expect(queue.parentElement?.className).toContain("group/composer"); expect(within(queue).getByText("first follow-up second follow-up")).toHaveTextContent("first follow-up second follow-up"); expect(within(queue).getAllByRole("button", { name: "Edit message" })).toHaveLength(1); expect(within(queue).getAllByRole("button", { name: "Send now" })).toHaveLength(1); rerender( , ); await waitFor(() => { expect(onSend).toHaveBeenCalledWith("first follow-up\nsecond follow-up"); }); expect(onSend).toHaveBeenCalledTimes(1); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); rerender( , ); rerender( , ); expect(onSend).toHaveBeenCalledTimes(1); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }); it("lets users edit queued guidance before it is sent", async () => { const onSend = vi.fn(); const { rerender } = render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "rough follow-up" } }); fireEvent.keyDown(input, { key: "Enter" }); const editButton = screen.getByRole("button", { name: "Edit message" }); const textarea = input as HTMLTextAreaElement; const setSelection = textarea.setSelectionRange.bind(textarea); const focusedSelections: boolean[] = []; vi.spyOn(textarea, "setSelectionRange").mockImplementation((start, end, direction) => { focusedSelections.push(document.activeElement === textarea); setSelection(start, end, direction); }); await userEvent.click(editButton); await waitFor(() => { expect(input).toHaveFocus(); }); expect(focusedSelections).toEqual([true]); expect(textarea.selectionStart).toBe("rough follow-up".length); expect(input).toHaveValue("rough follow-up"); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); fireEvent.change(input, { target: { value: "polished follow-up" } }); fireEvent.keyDown(input, { key: "Enter" }); rerender( , ); await waitFor(() => { expect(onSend).toHaveBeenCalledWith("polished follow-up"); }); }); it("edits the complete pending message without overwriting a newer draft", () => { const onSend = vi.fn(); const { rerender } = render(); const input = screen.getByLabelText("Message input"); for (const text of ["first follow-up", "second follow-up"]) { fireEvent.change(input, { target: { value: text } }); fireEvent.keyDown(input, { key: "Enter" }); } fireEvent.change(input, { target: { value: "third follow-up" } }); fireEvent.click(screen.getByRole("button", { name: "Edit message" })); expect(input).toHaveValue("first follow-up\nsecond follow-up\nthird follow-up"); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); fireEvent.change(input, { target: { value: "edited complete message" } }); fireEvent.keyDown(input, { key: "Enter" }); rerender(); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith("edited complete message"); }); it("queues image guidance while running and restores it for editing", async () => { mockBlobUrls(); const onSend = vi.fn(); const { container, rerender } = render( , ); const input = screen.getByLabelText("Message input"); const fileInput = container.querySelector('input[type="file"]'); expect(fileInput).toBeTruthy(); const file = new File(["image"], "draft.png", { type: "image/png" }); fireEvent.change(fileInput!, { target: { files: [file] } }); await screen.findByRole("img", { name: "draft.png" }); fireEvent.change(input, { target: { value: "look at this" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(onSend).not.toHaveBeenCalled(); expect(screen.getByRole("group", { name: "Waiting to send" })).toBeInTheDocument(); expect(screen.getByText("look at this")).toBeInTheDocument(); expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Edit message" })); expect(input).toHaveValue("look at this"); expect(screen.getByRole("img", { name: "draft.png" })).toBeInTheDocument(); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); fireEvent.keyDown(input, { key: "Enter" }); rerender( , ); await waitFor(() => { expect(onSend).toHaveBeenCalledWith( "look at this", [expect.objectContaining({ media: expect.objectContaining({ data_url: "data:image/png;base64,aW1hZ2U=", name: "draft.png", }), })], ); }); }); it("deletes the complete pending message across remounts", () => { const onSend = vi.fn(); const first = render(); const input = screen.getByLabelText("Message input"); for (const text of ["1", "2"]) { fireEvent.change(input, { target: { value: text } }); fireEvent.keyDown(input, { key: "Enter" }); } fireEvent.click(screen.getByRole("button", { name: "Delete message" })); first.unmount(); render(); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); expect(onSend).not.toHaveBeenCalled(); }); it("keeps queued guidance in its session when switching from running to idle", () => { const sendA = vi.fn(); const sendB = vi.fn(); const view = render( , ); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "follow-up for A" }, }); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" }); expect(screen.getByText("follow-up for A")).toBeInTheDocument(); expect(sendA).not.toHaveBeenCalled(); view.rerender( , ); expect(sendB).not.toHaveBeenCalled(); expect(screen.queryByText("follow-up for A")).not.toBeInTheDocument(); view.rerender( , ); expect(screen.getByText("follow-up for A")).toBeInTheDocument(); expect(sendA).not.toHaveBeenCalled(); view.rerender( , ); expect(sendA).toHaveBeenCalledTimes(1); expect(sendA).toHaveBeenCalledWith("follow-up for A"); expect(sendB).not.toHaveBeenCalled(); expect(screen.queryByText("follow-up for A")).not.toBeInTheDocument(); }); it("persists queued guidance per chat across remounts", async () => { const onSend = vi.fn(); const { rerender, unmount } = render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "remember this follow-up" } }); fireEvent.keyDown(input, { key: "Enter" }); fireEvent.click(screen.getByRole("button", { name: "Edit message" })); fireEvent.change(input, { target: { value: "remember this edited follow-up" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(screen.getByText("remember this edited follow-up")).toBeInTheDocument(); rerender( , ); await waitFor(() => { expect(screen.queryByText("remember this edited follow-up")).not.toBeInTheDocument(); }); rerender( , ); expect(await screen.findByText("remember this edited follow-up")).toBeInTheDocument(); expect(onSend).not.toHaveBeenCalled(); unmount(); const remount = render( , ); expect(await screen.findByText("remember this edited follow-up")).toBeInTheDocument(); expect(onSend).not.toHaveBeenCalled(); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" }); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith( "remember this edited follow-up", undefined, { continueActiveTurn: true }, ); remount.unmount(); render( , ); await waitFor(() => { expect(screen.queryByText("remember this edited follow-up")).not.toBeInTheDocument(); }); }); it("resumes a restored queue only after its waiting turn is confirmed complete", async () => { let acceptDelivery!: (accepted: boolean) => void; const delivery = new Promise((resolve) => { acceptDelivery = resolve; }); const onSend = vi.fn().mockReturnValueOnce(delivery); const first = render( , ); const input = screen.getByLabelText("Message input"); for (const text of ["first follow-up", "second follow-up"]) { fireEvent.change(input, { target: { value: text } }); fireEvent.keyDown(input, { key: "Enter" }); } first.unmount(); const otherSend = vi.fn(); const other = render( , ); expect(otherSend).not.toHaveBeenCalled(); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); other.unmount(); const returned = render( , ); expect(screen.getByText("first follow-up second follow-up")).toBeInTheDocument(); expect(onSend).not.toHaveBeenCalled(); returned.rerender( , ); expect(onSend).not.toHaveBeenCalled(); returned.rerender( , ); await waitFor(() => expect(onSend).toHaveBeenCalledWith("first follow-up\nsecond follow-up")); for (let update = 0; update < 3; update += 1) { returned.rerender( onSend(...args)} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />, ); } expect(onSend).toHaveBeenCalledTimes(1); expect(screen.getByRole("button", { name: "Send now" })).toBeDisabled(); await act(async () => { acceptDelivery(true); await delivery; }); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); returned.rerender( , ); returned.rerender( , ); expect(onSend).toHaveBeenCalledTimes(1); returned.unmount(); render( , ); expect(onSend).toHaveBeenCalledTimes(1); expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument(); }); it.each(["button", "palette"])("keeps queued messages manual after stopping through %s and remounting", (entrypoint) => { const onSend = vi.fn(); const onStop = vi.fn(); const view = render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "keep for later" } }); fireEvent.keyDown(input, { key: "Enter" }); if (entrypoint === "button") fireEvent.click(screen.getByRole("button", { name: "Stop response" })); else { fireEvent.change(input, { target: { value: "/sto" } }); fireEvent.mouseDown(screen.getByRole("option", { name: /\/stop/i })); } expect(onStop).toHaveBeenCalledTimes(1); view.unmount(); const returned = render( , ); expect(screen.getByText("keep for later")).toBeInTheDocument(); expect(onSend).not.toHaveBeenCalled(); // A run started in another pane must not re-arm a queue the user stopped. returned.rerender( , ); returned.rerender( , ); expect(onSend).not.toHaveBeenCalled(); fireEvent.click(screen.getByRole("button", { name: "Send now" })); expect(onSend).toHaveBeenCalledTimes(1); expect(onSend).toHaveBeenCalledWith("keep for later"); }); it("retains a rejected queued attachment for manual retry after remounting", async () => { mockBlobUrls(); let rejectDelivery!: (error: Error) => void; const delivery = new Promise((_resolve, reject) => { rejectDelivery = reject; }); const onSend = vi.fn().mockReturnValue(delivery); const first = render( , ); fireEvent.change(first.container.querySelector('input[type="file"]')!, { target: { files: [new File(["image"], "queued.png", { type: "image/png" })] }, }); await screen.findByRole("img", { name: "queued.png" }); for (const text of ["queued attachment", "more guidance"]) { fireEvent.change(screen.getByLabelText("Message input"), { target: { value: text } }); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" }); } first.unmount(); const returned = render( , ); await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1)); await act(async () => { rejectDelivery(new Error("Attachment upload interrupted")); }); expect(screen.getByText("queued attachment more guidance")).toBeInTheDocument(); expect(onSend).toHaveBeenCalledTimes(1); returned.unmount(); render( , ); expect(screen.getByText("queued attachment more guidance")).toBeInTheDocument(); expect(onSend).toHaveBeenCalledTimes(1); onSend.mockReturnValue(true); fireEvent.click(screen.getByRole("button", { name: "Send now" })); expect(onSend).toHaveBeenCalledTimes(2); expect(onSend.mock.calls[1][0]).toBe("queued attachment\nmore guidance"); expect(onSend.mock.calls[1][1]).toEqual([expect.objectContaining({ media: expect.objectContaining({ name: "queued.png" }) })]); }); it("retains legacy queued drafts for manual sending when mounted idle", () => { window.localStorage.setItem("nanobot.webui.composerQueuedGuidance.v1:chat-a", JSON.stringify([ { id: "legacy-draft", text: "legacy follow-up" }, ])); const onSend = vi.fn(); render(); expect(screen.getByText("legacy follow-up")).toBeInTheDocument(); expect(onSend).not.toHaveBeenCalled(); fireEvent.click(screen.getByRole("button", { name: "Send now" })); expect(onSend).toHaveBeenCalledWith("legacy follow-up"); }); it("keeps temporary chat guidance in memory only", async () => { const setItem = vi.spyOn(window.localStorage, "setItem"); const onSend = vi.fn(); const view = render( , ); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "do not persist this" } }); fireEvent.keyDown(input, { key: "Enter" }); expect(await screen.findByText("do not persist this")).toBeInTheDocument(); expect(setItem).not.toHaveBeenCalled(); view.unmount(); render( , ); await waitFor(() => { expect(screen.queryByText("do not persist this")).not.toBeInTheDocument(); }); expect(setItem).not.toHaveBeenCalled(); }); }); 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) => ( ); 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) => ( ); const view = render(composer("chat-a")); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: " draft A\nnext line" } }); view.rerender(composer("chat-b")); expect(screen.getByLabelText("Message input")).toHaveValue(""); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "draft B" } }); view.rerender(composer("chat-a")); expect(screen.getByLabelText("Message input")).toHaveValue(" draft A\nnext line"); fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "z", ctrlKey: true }); expect(screen.getByLabelText("Message input")).toHaveValue(" draft A\nnext line"); view.unmount(); render(composer("chat-b")); expect(screen.getByLabelText("Message input")).toHaveValue("draft B"); }); it("retains in-progress IME text without carrying composition into another chat", () => { const draftStore = new ComposerDraftStore(); const composer = (key: string) => ( ); const view = render(composer("chat-a")); const input = screen.getByLabelText("Message input"); fireEvent.change(input, { target: { value: "@gimp " } }); fireEvent.compositionStart(input); fireEvent.change(input, { target: { value: "@\u00a0GIMP 草稿" } }); view.rerender(composer("chat-b")); expect(screen.getByLabelText("Message input")).toHaveValue(""); view.rerender(composer("chat-a")); expect(screen.getByLabelText("Message input")).toHaveValue("@\u00a0GIMP 草稿"); }); it.each([true, false])("clears only accepted sends (accepted=%s)", (accepted) => { const draftStore = new ComposerDraftStore(); const composer = (key: string) => ( accepted} /> ); const view = render(composer("chat-a")); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "send me" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); view.rerender(composer("chat-b")); view.rerender(composer("chat-a")); expect(screen.getByLabelText("Message input")).toHaveValue(accepted ? "" : "send me"); }); it.each([false, true])("clears an accepted draft after restoring it unchanged (attachment=%s)", async (attachment) => { mockBlobUrls(); const draftStore = new ComposerDraftStore(); let resolveSend!: (accepted: boolean) => void; const onSend = vi.fn(() => new Promise((resolve) => { resolveSend = resolve; })); const composer = (key: string) => ( ); const view = render(composer("unchanged-draft")); fireEvent.change(screen.getByRole("textbox"), { target: { value: "send once" } }); if (attachment) { const file = new File(["image"], "draft.png", { type: "image/png" }); fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [file] } }); await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled()); } fireEvent.click(screen.getByRole("button", { name: "Send message" })); view.rerender(composer("other-draft")); view.rerender(composer("unchanged-draft")); expect(screen.getByRole("textbox")).toHaveValue("send once"); if (attachment) await screen.findByRole("img", { name: "draft.png" }); fireEvent.click(screen.getByRole("textbox")); await act(async () => resolveSend(true)); view.unmount(); expect(new ComposerDraftStore().get("unchanged-draft", true)).toBeUndefined(); }); it("does not delete a newer draft when an earlier async send completes", async () => { const draftStore = new ComposerDraftStore(); let resolveSend!: (accepted: boolean) => void; const onSend = vi.fn(() => new Promise((resolve) => { resolveSend = resolve; })); const composer = (key: string) => ( ); const view = render(composer("chat-a")); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "first" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); view.rerender(composer("chat-b")); view.rerender(composer("chat-a")); fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "newer draft" } }); await act(async () => resolveSend(true)); view.rerender(composer("chat-b")); view.rerender(composer("chat-a")); expect(screen.getByLabelText("Message input")).toHaveValue("newer draft"); }); it("restores attachments and quoted context with their original session", async () => { mockBlobUrls(); const draftStore = new ComposerDraftStore(); const onSend = vi.fn(); const composer = (key: string, quote = draftStore.get(key)?.quotedContext) => ( ); const view = render(composer("chat-a", "quoted answer")); const file = new File(["image"], "draft.png", { type: "image/png" }); fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [file] } }); view.rerender(composer("chat-b")); expect(screen.queryByRole("img", { name: "draft.png" })).not.toBeInTheDocument(); expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument(); view.rerender(composer("chat-a")); expect(await screen.findByRole("img", { name: "draft.png" })).toBeInTheDocument(); expect(screen.getByLabelText("Quoted context")).toHaveTextContent("quoted answer"); await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled()); fireEvent.click(screen.getByRole("button", { name: "Send message" })); expect(onSend).toHaveBeenCalledWith("", [expect.objectContaining({ media: expect.objectContaining({ name: "draft.png" }), })], { quotedContext: "quoted answer" }); }); });