π OpenHands: AI-Driven Development
test: strengthen chat composer behavior (#17359)
aivong-openhands58ca06ced012
diff --git a/__tests__/components/features/chat/uploaded-image-preview.test.tsx b/__tests__/components/features/chat/uploaded-image-preview.test.tsxnew file mode 100644index 0000000000..1a76a3aa9c--- /dev/null+++ b/__tests__/components/features/chat/uploaded-image-preview.test.tsx@@ -0,0 +1,198 @@+import { cleanup, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { renderToString } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";+import { UploadedImage } from "#/components/features/chat/uploaded-image";++vi.mock("lucide-react", () => ({+ LoaderCircle: ({+ className,+ color,+ }: {+ className?: string;+ color?: string;+ }) => (+ <div data-testid="image-loader" data-color={color} className={className} />+ ),+}));++vi.mock("#/components/features/chat/remove-file-button", () => ({+ RemoveFileButton: ({ onClick }: { onClick: () => void }) => (+ <button type="button" data-testid="remove-image" onClick={onClick}>+ Remove image+ </button>+ ),+}));++vi.mock(+ "#/components/features/chat/pasted-image-upload-as-file-button",+ () => ({+ PastedImageUploadAsFileButton: ({+ active,+ onToggle,+ }: {+ active: boolean;+ onToggle: () => void;+ }) => (+ <button+ type="button"+ data-testid="upload-image-as-file"+ aria-pressed={active}+ onClick={onToggle}+ >+ Toggle upload as file+ </button>+ ),+ }),+);++function createImage(name = "diagram.png"): File {+ return new File(["image bytes"], name, { type: "image/png" });+}++function installObjectUrlMocks() {+ const createObjectURL = vi.fn((file: File) => `blob:preview/${file.name}`);+ const revokeObjectURL = vi.fn();++ vi.stubGlobal("URL", {+ createObjectURL,+ revokeObjectURL,+ });++ return { createObjectURL, revokeObjectURL };+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("uploaded image preview", () => {+ it("shows the image and supports removal with default options", async () => {+ const user = userEvent.setup();+ const { createObjectURL, revokeObjectURL } = installObjectUrlMocks();+ const image = createImage();+ const onRemove = vi.fn();+ const { unmount } = render(+ <UploadedImage+ image={image}+ onRemove={onRemove}+ onToggleUploadAsFile={vi.fn()}+ />,+ );++ const preview = screen.getByRole("img", { name: "diagram.png" });+ expect(preview).toHaveAttribute("src", "blob:preview/diagram.png");+ expect(createObjectURL).toHaveBeenCalledWith(image);+ expect(screen.queryByTestId("image-loader")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("upload-image-as-file"),+ ).not.toBeInTheDocument();++ await user.click(screen.getByTestId("remove-image"));+ expect(onRemove).toHaveBeenCalledOnce();++ unmount();+ expect(revokeObjectURL).toHaveBeenCalledWith("blob:preview/diagram.png");+ });++ it("renders no image before an object URL is available", () => {+ const initialMarkup = renderToString(+ <UploadedImage image={createImage()} onRemove={vi.fn()} />,+ );++ expect(initialMarkup).not.toContain("<img");+ });++ it("starts the upload-as-file control inactive when it is enabled", () => {+ installObjectUrlMocks();++ render(+ <UploadedImage+ image={createImage()}+ onRemove={vi.fn()}+ showUploadAsFileToggle+ onToggleUploadAsFile={vi.fn()}+ />,+ );++ expect(screen.getByTestId("upload-image-as-file")).toHaveAttribute(+ "aria-pressed",+ "false",+ );+ });++ it("shows a loader and forwards an active upload-as-file toggle", async () => {+ const user = userEvent.setup();+ const { revokeObjectURL } = installObjectUrlMocks();+ const onToggleUploadAsFile = vi.fn();+ const { unmount } = render(+ <UploadedImage+ image={createImage("large-image.png")}+ onRemove={vi.fn()}+ isLoading+ showUploadAsFileToggle+ uploadAsFileActive+ onToggleUploadAsFile={onToggleUploadAsFile}+ />,+ );++ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ expect(screen.getByTestId("image-loader")).toHaveClass("animate-spin");+ expect(screen.getByTestId("image-loader")).toHaveAttribute(+ "data-color",+ "white",+ );+ const toggle = screen.getByTestId("upload-image-as-file");+ expect(toggle).toHaveAttribute("aria-pressed", "true");++ await user.click(toggle);+ expect(onToggleUploadAsFile).toHaveBeenCalledOnce();++ unmount();+ expect(revokeObjectURL).toHaveBeenCalledWith(+ "blob:preview/large-image.png",+ );+ });++ it("refreshes the object URL for a new image and hides an unusable toggle", () => {+ const { createObjectURL, revokeObjectURL } = installObjectUrlMocks();+ const firstImage = createImage("first.png");+ const secondImage = createImage("second.png");+ const onRemove = vi.fn();+ const { rerender, unmount } = render(+ <UploadedImage+ image={firstImage}+ onRemove={onRemove}+ showUploadAsFileToggle+ />,+ );++ expect(screen.getByRole("img", { name: "first.png" })).toHaveAttribute(+ "src",+ "blob:preview/first.png",+ );+ expect(+ screen.queryByTestId("upload-image-as-file"),+ ).not.toBeInTheDocument();++ rerender(+ <UploadedImage+ image={secondImage}+ onRemove={onRemove}+ showUploadAsFileToggle+ />,+ );++ expect(screen.getByRole("img", { name: "second.png" })).toHaveAttribute(+ "src",+ "blob:preview/second.png",+ );+ expect(createObjectURL).toHaveBeenNthCalledWith(1, firstImage);+ expect(createObjectURL).toHaveBeenNthCalledWith(2, secondImage);+ expect(revokeObjectURL).toHaveBeenCalledWith("blob:preview/first.png");++ unmount();+ expect(revokeObjectURL).toHaveBeenCalledWith("blob:preview/second.png");+ });+});diff --git a/__tests__/hooks/chat/use-slash-command.test.ts b/__tests__/hooks/chat/use-slash-command.test.tsindex 1062ea08b0..e13cf1d80b 100644--- a/__tests__/hooks/chat/use-slash-command.test.ts+++ b/__tests__/hooks/chat/use-slash-command.test.ts@@ -1,7 +1,10 @@import React from "react";import { act, renderHook } from "@testing-library/react";-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";-import { useSlashCommand } from "#/hooks/chat/use-slash-command";+import { describe, it, expect, vi, afterEach } from "vitest";+import {+ type SlashCommandItem,+ useSlashCommand,+} from "#/hooks/chat/use-slash-command";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import {__resetActiveStoreForTests,@@ -55,30 +58,70 @@ function makeSkill(name: string,triggers: string[] = [],type: "agentskills" | "knowledge" = "agentskills",+ content: string | undefined = `Description of ${name}`,) {- return { name, type, content: `Description of ${name}`, triggers };+ return { name, type, source: null, content, triggers };+}++function makeProfile(+ name: string,+ model: string | null,+): NonNullable<typeof mockLlmProfiles.data>["profiles"][number] {+ return {+ name,+ model,+ base_url: null,+ api_key_set: true,+ };}function makeChatInputRef() {- return { current: document.createElement("div") };+ const current = document.createElement("div");+ current.tabIndex = 0;+ return { current };}-function setInputText(element: HTMLDivElement, text: string) {- element.textContent = text;- element.innerText = text;- document.body.appendChild(element);+function setInputText(+ element: HTMLDivElement,+ text: string,+ cursorOffset = text.length,+) {+ Object.assign(element, { textContent: text, innerText: text });+ if (!element.isConnected) document.body.appendChild(element);const textNode = element.firstChild;if (!textNode) return;const range = document.createRange();const selection = window.getSelection();- range.setStart(textNode, text.length);+ range.setStart(textNode, cursorOffset);range.collapse(true);selection?.removeAllRanges();selection?.addRange(range);}+function makeKeyboardEvent(key: string) {+ return {+ key,+ preventDefault: vi.fn(),+ } as unknown as React.KeyboardEvent;+}++function getSelectedCharacterOffset(element: HTMLElement) {+ const selection = window.getSelection();+ expect(selection?.rangeCount).toBe(1);+ const range = selection!.getRangeAt(0);+ const beforeCursor = range.cloneRange();+ beforeCursor.selectNodeContents(element);+ beforeCursor.setEnd(range.startContainer, range.startOffset);+ return beforeCursor.toString().length;+}++const fallbackItem: SlashCommandItem = {+ command: "/fallback",+ skill: makeSkill("fallback", ["/fallback"]),+};+const cloudBackend: Backend = {id: "prod",name: "Production",@@ -88,20 +131,14 @@ const cloudBackend: Backend = {};describe("useSlashCommand", () => {- beforeEach(() => {+ afterEach(() => {+ useFreeModelsStore.getState().resetFlags();vi.clearAllMocks();mockSkills.data = undefined;mockSkills.isLoading = false;mockLlmProfiles.data = undefined;mockLlmProfiles.isLoading = false;mockConversation.data = undefined;- useFreeModelsStore.getState().setFlags({- freeModels: new Set(),- defaultModel: null,- });- });-- afterEach(() => {document.body.innerHTML = "";window.localStorage.clear?.();__resetActiveStoreForTests();@@ -145,30 +182,10 @@ describe("useSlashCommand", () => {// The active backend store is reset before each test, which restores the default local backend.mockSkills.data = [];- useFreeModelsStore.getState().setFlags({- freeModels: new Set(["openhands/glm-5.2"]),- defaultModel: "openhands/glm-5.2",- });mockLlmProfiles.data = {profiles: [- {- name: "haiku",- model: "anthropic/claude-haiku-4-5",- base_url: null,- api_key_set: true,- },- {- name: "gpt",- model: "openai/gpt-5.1",- base_url: null,- api_key_set: true,- },- {- name: "free",- model: "openhands/glm-5.2",- base_url: null,- api_key_set: true,- },+ makeProfile("haiku", "anthropic/claude-haiku-4-5"),+ makeProfile("gpt", "openai/gpt-5.1"),],active_profile: "haiku",};@@ -184,30 +201,31 @@ describe("useSlashCommand", () => {expect(result.current.filteredItems.map((i) => i.command)).toEqual(["/model haiku","/model gpt",- "/model free",]);- expect(- result.current.filteredItems.find((i) => i.command === "/model free")- ?.skill.content,- ).toBe("Switch to openhands/glm-5.2 (free)");+ expect(result.current.filteredItems[0].skill.content).toBe(+ "Switch to anthropic/claude-haiku-4-5",+ );+ act(() => {+ useFreeModelsStore.getState().setFlags({+ freeModels: new Set(["anthropic/claude-haiku-4-5"]),+ defaultModel: null,+ });+ });+ expect(result.current.filteredItems[0].skill.content).toBe(+ "Switch to anthropic/claude-haiku-4-5 (free)",+ );+ act(() => useFreeModelsStore.getState().resetFlags());+ expect(result.current.filteredItems[0].skill.content).toBe(+ "Switch to anthropic/claude-haiku-4-5",+ );});it("filters saved LLM profile suggestions by profile name or model", () => {mockSkills.data = [];mockLlmProfiles.data = {profiles: [- {- name: "haiku",- model: "anthropic/claude-haiku-4-5",- base_url: null,- api_key_set: true,- },- {- name: "gpt",- model: "openai/gpt-5.1",- base_url: null,- api_key_set: true,- },+ makeProfile("haiku", "anthropic/claude-haiku-4-5"),+ makeProfile("gpt", "openai/gpt-5.1"),],active_profile: null,};@@ -223,4 +241,615 @@ describe("useSlashCommand", () => {"/model haiku",]);});++ it("keeps built-in commands stable while skills load or have no data", () => {+ mockSkills.isLoading = true;+ mockSkills.data = [makeSkill("hidden-until-loaded", ["/hidden"])];++ const ref = makeChatInputRef();+ const { result, rerender } = renderHook(() => useSlashCommand(ref));++ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/btw",+ "/model",+ "/goal",+ "/plan",+ "/code",+ ]);++ mockSkills.isLoading = false;+ mockSkills.data = undefined;+ rerender();++ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/btw",+ "/model",+ "/goal",+ "/plan",+ "/code",+ ]);+ });++ it("adds newly loaded skills after the hook has rendered", () => {+ mockSkills.data = [];+ const ref = makeChatInputRef();+ const { result, rerender } = renderHook(() => useSlashCommand(ref));+ expect(+ result.current.filteredItems.map((item) => item.command),+ ).not.toContain("/late-arrival");++ mockSkills.data = [makeSkill("late-arrival", ["/late-arrival"])];+ rerender();++ expect(result.current.filteredItems.map((item) => item.command)).toContain(+ "/late-arrival",+ );+ });++ it("builds commands from explicit triggers and agent skill names", () => {+ mockSkills.data = [+ makeSkill("explicit", ["task", "/explicit", "/alias"]),+ makeSkill("derived", ["task"]),+ { ...makeSkill("missing-triggers"), triggers: undefined },+ makeSkill("knowledge-hidden", [], "knowledge"),+ makeSkill("knowledge-explicit", ["/reference"], "knowledge"),+ ];++ const ref = makeChatInputRef();+ const { result } = renderHook(() => useSlashCommand(ref));++ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/btw",+ "/model",+ "/goal",+ "/plan",+ "/code",+ "/explicit",+ "/alias",+ "/derived",+ "/missing-triggers",+ "/reference",+ ]);+ });++ it("describes a profile without a model and filters it by name", () => {+ mockSkills.data = [];+ mockLlmProfiles.data = {+ profiles: [makeProfile("Default Profile", null)],+ active_profile: null,+ };+ const ref = makeChatInputRef();+ setInputText(ref.current, "/model DEFAULT");++ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());++ expect(result.current.filteredItems).toEqual([+ {+ command: "/model Default Profile",+ skill: {+ name: "Default Profile",+ type: "agentskills",+ source: null,+ content: "Switch to this LLM profile",+ triggers: ["/model Default Profile"],+ },+ },+ ]);+ });++ it.each([+ ["command", "/PLO", "/deploy"],+ ["skill name", "/nostic", "/inspect"],+ ["description", "/INCIDENT", "/respond"],+ ])(+ "filters skill suggestions by %s case-insensitively",+ (_field, input, command) => {+ mockSkills.data = [+ makeSkill("ship", ["/deploy"], "agentskills", "Release software"),+ makeSkill("diagnostics", ["/inspect"], "agentskills", "Check health"),+ makeSkill(+ "on-call",+ ["/respond"],+ "agentskills",+ "Fix production incidents",+ ),+ makeSkill("undocumented", ["/quiet"], "agentskills", undefined),+ ];+ const ref = makeChatInputRef();+ setInputText(ref.current, input);++ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());++ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ command,+ ]);+ },+ );++ it("filters skills without descriptions without throwing", () => {+ mockSkills.data = [+ { ...makeSkill("undocumented", ["/quiet"]), content: undefined },+ ];+ const ref = makeChatInputRef();+ setInputText(ref.current, "/absent");+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());++ expect(result.current.isMenuOpen).toBe(true);+ expect(result.current.filteredItems).toEqual([]);+ });++ it("recognizes a slash command after an internal newline", () => {+ mockSkills.data = [makeSkill("deploy", ["/deploy"])];+ const ref = makeChatInputRef();+ setInputText(ref.current, "context\n/dep");+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());++ expect(result.current.isMenuOpen).toBe(true);+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/deploy",+ ]);+ });++ it("ignores repeated trailing newlines while detecting and replacing a command", () => {+ mockSkills.data = [makeSkill("hello", ["/hello"])];+ const ref = makeChatInputRef();+ setInputText(ref.current, "/hel\n\r");+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/hello",+ ]);++ act(() => result.current.selectItem(result.current.filteredItems[0]));+ expect(ref.current.textContent).toBe("/hello ");+ });++ it("removes generated trailing newlines that sit after the cursor", () => {+ mockSkills.data = [makeSkill("hello", ["/hello"])];+ const ref = makeChatInputRef();+ setInputText(ref.current, "/hel\n\r", "/hel".length);+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ act(() => result.current.selectItem(result.current.filteredItems[0]));++ expect(ref.current.textContent).toBe("/hello ");+ });++ it("closes the menu when the input has no active slash word", () => {+ mockSkills.data = [makeSkill("deploy", ["/deploy"])];+ const ref = makeChatInputRef();+ setInputText(ref.current, "/dep");+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ expect(result.current.isMenuOpen).toBe(true);++ setInputText(ref.current, "/deploy ");+ act(() => result.current.updateSlashMenu());++ expect(result.current.isMenuOpen).toBe(false);+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/btw",+ "/model",+ "/goal",+ "/plan",+ "/code",+ "/deploy",+ ]);+ });++ it("does not open without a chat input or a cursor selection", () => {+ const missingRef: React.RefObject<HTMLDivElement | null> = {+ current: null,+ };+ const missing = renderHook(() => useSlashCommand(missingRef));++ act(() => {+ missing.result.current.updateSlashMenu();+ missing.result.current.selectItem(fallbackItem);+ });+ expect(missing.result.current.isMenuOpen).toBe(false);++ const ref = makeChatInputRef();+ setInputText(ref.current, "/btw");+ window.getSelection()?.removeAllRanges();+ const withoutSelection = renderHook(() => useSlashCommand(ref));++ act(() => withoutSelection.result.current.updateSlashMenu());+ expect(withoutSelection.result.current.isMenuOpen).toBe(false);+ });++ it("keeps model completion open while profiles load and closes when none exist", () => {+ mockSkills.data = [];+ mockLlmProfiles.isLoading = true;+ const ref = makeChatInputRef();+ setInputText(ref.current, "/model");+ const { result, rerender } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ expect(result.current.isMenuOpen).toBe(true);+ expect(result.current.filteredItems).toEqual([]);++ mockLlmProfiles.isLoading = false;+ rerender();+ act(() => result.current.updateSlashMenu());++ expect(result.current.isMenuOpen).toBe(false);+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/btw",+ "/model",+ "/goal",+ "/plan",+ "/code",+ ]);+ });++ it("does not treat extra model arguments as a profile completion", () => {+ mockLlmProfiles.data = {+ profiles: [makeProfile("haiku", "anthropic/claude-haiku")],+ active_profile: null,+ };+ const ref = makeChatInputRef();+ setInputText(ref.current, "/model haiku extra");+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());++ expect(result.current.isMenuOpen).toBe(false);+ });++ it("supports multiple spaces before a model profile filter", () => {+ mockLlmProfiles.data = {+ profiles: [+ makeProfile("haiku", "anthropic/claude-haiku"),+ makeProfile("gpt", "openai/gpt"),+ ],+ active_profile: null,+ };+ const ref = makeChatInputRef();+ setInputText(ref.current, "/model hai");+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());++ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/model haiku",+ ]);+ });++ it("replaces the entire input when selection happens without a tracked slash range", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "draft text\n");+ const inputListener = vi.fn<(event: InputEvent) => void>();+ document.body.addEventListener("input", inputListener);+ const focus = vi.spyOn(ref.current, "focus").mockImplementation(() => {});+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.selectItem(fallbackItem));++ expect(ref.current.textContent).toBe("/fallback ");+ expect(inputListener).toHaveBeenCalledOnce();+ expect(inputListener.mock.calls[0][0].bubbles).toBe(true);+ expect(focus).toHaveBeenCalledOnce();+ expect(getSelectedCharacterOffset(ref.current)).toBe("/fallback ".length);+ expect(result.current.isMenuOpen).toBe(false);+ expect(result.current.selectedIndex).toBe(0);+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/btw",+ "/model",+ "/goal",+ "/plan",+ "/code",+ ]);+ });++ it("supports selecting a command from an empty editor", () => {+ const ref = makeChatInputRef();+ ref.current.innerText = "";+ ref.current.textContent = "";+ document.body.appendChild(ref.current);+ const range = document.createRange();+ range.setStart(ref.current, 0);+ range.collapse(true);+ window.getSelection()?.removeAllRanges();+ window.getSelection()?.addRange(range);+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ expect(result.current.isMenuOpen).toBe(false);++ act(() => result.current.selectItem(fallbackItem));+ expect(ref.current.textContent).toBe("/fallback ");+ });++ it("does not restore cleared text when selecting a previously tracked command", () => {+ mockSkills.data = [makeSkill("fallback", ["/fallback"])];+ const ref = makeChatInputRef();+ setInputText(ref.current, "/fall");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());++ ref.current.innerText = "";+ ref.current.textContent = "";+ act(() => result.current.selectItem(result.current.filteredItems[0]));++ expect(ref.current.textContent).toBe("/fallback ");+ });++ it("replaces only the slash word when the cursor is in its middle", () => {+ mockSkills.data = [makeSkill("hello", ["/hello"])];+ const ref = makeChatInputRef();+ const input = "prefix\n/helXYZ suffix";+ setInputText(ref.current, input, input.indexOf("/hel") + 4);+ const inputListener = vi.fn();+ ref.current.addEventListener("input", inputListener);+ const focus = vi.spyOn(ref.current, "focus").mockImplementation(() => {});+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/hello",+ ]);++ act(() => result.current.selectItem(result.current.filteredItems[0]));++ expect(ref.current.textContent).toBe("prefix\n/hello suffix");+ expect(inputListener).toHaveBeenCalledOnce();+ expect(focus).toHaveBeenCalledOnce();+ expect(getSelectedCharacterOffset(ref.current)).toBe(+ "prefix\n".length + "/hello ".length,+ );+ expect(result.current.isMenuOpen).toBe(false);+ });++ it("replaces a model profile token through its trailing characters", () => {+ mockSkills.data = [];+ mockLlmProfiles.data = {+ profiles: [makeProfile("haiku", "anthropic/claude-haiku")],+ active_profile: null,+ };+ const ref = makeChatInputRef();+ const input = "question /model haiXYZ later";+ setInputText(ref.current, input, input.indexOf("hai") + 3);+ const { result } = renderHook(() => useSlashCommand(ref));++ act(() => result.current.updateSlashMenu());+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/model haiku",+ ]);++ act(() => result.current.selectItem(result.current.filteredItems[0]));+ expect(ref.current.textContent).toBe("question /model haiku later");+ });++ it("uses the latest input ref for direct selection after rerendering", () => {+ mockSkills.data = [makeSkill("fallback", ["/fallback"])];+ const firstRef = makeChatInputRef();+ setInputText(firstRef.current, "first draft");+ const secondRef = makeChatInputRef();+ setInputText(secondRef.current, "/fall");+ const { result, rerender } = renderHook(+ ({ inputRef }) => useSlashCommand(inputRef),+ { initialProps: { inputRef: firstRef } },+ );++ rerender({ inputRef: secondRef });+ act(() => result.current.updateSlashMenu());+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/fallback",+ ]);++ act(() => result.current.selectItem(result.current.filteredItems[0]));+ expect(secondRef.current.textContent).toBe("/fallback ");+ expect(firstRef.current.textContent).toBe("first draft");+ });++ it("uses the latest selection callback for keyboard completion after rerendering", () => {+ mockSkills.data = [makeSkill("fallback", ["/fallback"])];+ const firstRef = makeChatInputRef();+ setInputText(firstRef.current, "first draft");+ const secondRef = makeChatInputRef();+ setInputText(secondRef.current, "/fall");+ const { result, rerender } = renderHook(+ ({ inputRef }) => useSlashCommand(inputRef),+ { initialProps: { inputRef: firstRef } },+ );++ rerender({ inputRef: secondRef });+ act(() => result.current.updateSlashMenu());+ act(() => result.current.handleSlashKeyDown(makeKeyboardEvent("Enter")));++ expect(secondRef.current.textContent).toBe("/fallback ");+ expect(firstRef.current.textContent).toBe("first draft");+ });++ it("still replaces text when the browser has no active Selection object", () => {+ mockSkills.data = [makeSkill("fallback", ["/fallback"])];+ const trackedRef = makeChatInputRef();+ setInputText(trackedRef.current, "/fall");+ const tracked = renderHook(() => useSlashCommand(trackedRef));+ act(() => tracked.result.current.updateSlashMenu());++ const trackedSelection = vi+ .spyOn(window, "getSelection")+ .mockReturnValue(null);+ act(() =>+ tracked.result.current.selectItem(+ tracked.result.current.filteredItems[0],+ ),+ );+ expect(trackedRef.current.textContent).toBe("/fallback ");+ trackedSelection.mockRestore();++ const fallbackRef = makeChatInputRef();+ setInputText(fallbackRef.current, "draft");+ const fallback = renderHook(() => useSlashCommand(fallbackRef));+ const fallbackSelection = vi+ .spyOn(window, "getSelection")+ .mockReturnValue(null);+ act(() => fallback.result.current.selectItem(fallbackItem));+ expect(fallbackRef.current.textContent).toBe("/fallback ");+ fallbackSelection.mockRestore();+ });++ it("resets keyboard selection when the slash filter changes", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());++ const down = makeKeyboardEvent("ArrowDown");+ act(() => result.current.handleSlashKeyDown(down));+ expect(result.current.selectedIndex).toBe(1);++ setInputText(ref.current, "/go");+ act(() => result.current.updateSlashMenu());+ expect(result.current.selectedIndex).toBe(0);+ expect(result.current.filteredItems.map((item) => item.command)).toEqual([+ "/goal",+ ]);+ });++ it("wraps keyboard selection in both directions", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());++ for (const expected of [1, 2, 3, 4, 0]) {+ const event = makeKeyboardEvent("ArrowDown");+ act(() => expect(result.current.handleSlashKeyDown(event)).toBe(true));+ expect(event.preventDefault).toHaveBeenCalledOnce();+ expect(result.current.selectedIndex).toBe(expected);+ }++ for (const expected of [4, 3]) {+ const event = makeKeyboardEvent("ArrowUp");+ act(() => expect(result.current.handleSlashKeyDown(event)).toBe(true));+ expect(event.preventDefault).toHaveBeenCalledOnce();+ expect(result.current.selectedIndex).toBe(expected);+ }+ });++ it.each([+ ["Enter", "/btw "],+ ["Tab", "/btw "],+ ])("selects the highlighted command with %s", (key, replacement) => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());+ const event = makeKeyboardEvent(key);++ act(() => expect(result.current.handleSlashKeyDown(event)).toBe(true));++ expect(event.preventDefault).toHaveBeenCalledOnce();+ expect(ref.current.textContent).toBe(replacement);+ expect(result.current.isMenuOpen).toBe(false);+ });++ it("does not consume selection when a changing profile list invalidates the index", () => {+ mockLlmProfiles.data = {+ profiles: [+ makeProfile("one", "model-1"),+ makeProfile("two", "model-2"),+ makeProfile("three", "model-3"),+ ],+ active_profile: null,+ };+ const ref = makeChatInputRef();+ setInputText(ref.current, "/model");+ const { result, rerender } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());+ act(() => result.current.handleSlashKeyDown(makeKeyboardEvent("ArrowUp")));+ expect(result.current.selectedIndex).toBe(2);++ mockLlmProfiles.data = {+ profiles: [makeProfile("one", "model-1")],+ active_profile: null,+ };+ rerender();+ const enter = makeKeyboardEvent("Enter");++ act(() => expect(result.current.handleSlashKeyDown(enter)).toBe(false));+ expect(enter.preventDefault).not.toHaveBeenCalled();+ expect(ref.current.textContent).toBe("/model");+ });++ it("ignores keyboard input while closed or while filtering has no results", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ const closed = makeKeyboardEvent("ArrowDown");+ expect(result.current.handleSlashKeyDown(closed)).toBe(false);+ expect(closed.preventDefault).not.toHaveBeenCalled();++ setInputText(ref.current, "/nothing-matches");+ act(() => result.current.updateSlashMenu());+ expect(result.current.isMenuOpen).toBe(true);+ expect(result.current.filteredItems).toEqual([]);+ const empty = makeKeyboardEvent("ArrowDown");+ expect(result.current.handleSlashKeyDown(empty)).toBe(false);+ expect(empty.preventDefault).not.toHaveBeenCalled();+ });++ it("closes and consumes Escape", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());+ const escape = makeKeyboardEvent("Escape");++ act(() => expect(result.current.handleSlashKeyDown(escape)).toBe(true));++ expect(escape.preventDefault).toHaveBeenCalledOnce();+ expect(result.current.isMenuOpen).toBe(false);+ });++ it.each(["ArrowLeft", "ArrowRight", "Home", "End"])(+ "closes without consuming %s",+ (key) => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());+ const event = makeKeyboardEvent(key);++ act(() => expect(result.current.handleSlashKeyDown(event)).toBe(false));++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(result.current.isMenuOpen).toBe(false);+ },+ );++ it("leaves the menu open for an unrelated key", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());+ const event = makeKeyboardEvent("Shift");++ expect(result.current.handleSlashKeyDown(event)).toBe(false);+ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(result.current.isMenuOpen).toBe(true);+ });++ it("allows callers to close the menu", () => {+ const ref = makeChatInputRef();+ setInputText(ref.current, "/");+ const { result } = renderHook(() => useSlashCommand(ref));+ act(() => result.current.updateSlashMenu());++ act(() => result.current.closeMenu());++ expect(result.current.isMenuOpen).toBe(false);+ });});diff --git a/__tests__/hooks/send-message.test.tsx b/__tests__/hooks/send-message.test.tsxnew file mode 100644index 0000000000..5bb0c60b92--- /dev/null+++ b/__tests__/hooks/send-message.test.tsx@@ -0,0 +1,192 @@+import { renderHook } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useSendMessage } from "#/hooks/use-send-message";++const { useConversationWebSocketMock, useOptionalConversationIdMock } =+ vi.hoisted(() => ({+ useConversationWebSocketMock: vi.fn(),+ useOptionalConversationIdMock: vi.fn(),+ }));++vi.mock("#/contexts/conversation-websocket-context", () => ({+ useConversationWebSocket: () => useConversationWebSocketMock(),+}));++vi.mock("#/hooks/use-conversation-id", () => ({+ useOptionalConversationId: () => useOptionalConversationIdMock(),+}));++interface HookOptions {+ sendMessage?: ReturnType<typeof vi.fn> | null;+}++function renderSendMessageHook({+ sendMessage = vi.fn().mockResolvedValue({ queued: false }),+}: HookOptions = {}) {+ useOptionalConversationIdMock.mockReturnValue({+ conversationId: "conversation-1",+ });+ useConversationWebSocketMock.mockReturnValue(+ sendMessage+ ? {+ sendMessage,+ }+ : null,+ );++ return {+ ...renderHook(() => useSendMessage()),+ sendMessage,+ };+}++afterEach(() => {+ vi.clearAllMocks();+});++describe("sending chat messages", () => {+ it("is a safe no-op outside a conversation provider", async () => {+ const { result } = renderSendMessageHook({+ sendMessage: null,+ });++ await expect(+ result.current.send({+ action: "message",+ args: { content: "Hello" },+ }),+ ).resolves.toEqual({ queued: false });+ });++ it("ignores events that are not user messages", async () => {+ const sendMessage = vi.fn();+ const { result } = renderSendMessageHook({ sendMessage });++ await expect(+ result.current.send({+ action: "change_agent_state",+ args: { content: "This is not a chat message" },+ }),+ ).resolves.toEqual({ queued: false });+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it.each([+ ["missing arguments", { action: "message" }],+ ["missing content", { action: "message", args: {} }],+ ["empty content", { action: "message", args: { content: "" } }],+ ])("ignores a message with %s", async (_description, event) => {+ const sendMessage = vi.fn();+ const { result } = renderSendMessageHook({ sendMessage });++ await expect(result.current.send(event)).resolves.toEqual({+ queued: false,+ });+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it("converts text chat input into a user WebSocket message", async () => {+ const sendMessage = vi.fn().mockResolvedValue({ queued: true });+ const { result } = renderSendMessageHook({ sendMessage });++ await expect(+ result.current.send({+ action: "message",+ args: {+ content: "Explain this code",+ file_urls: ["file:///workspace/example.ts"],+ timestamp: "2026-07-13T00:00:00.000Z",+ },+ }),+ ).resolves.toEqual({ queued: true });+ expect(sendMessage).toHaveBeenCalledOnce();+ expect(sendMessage).toHaveBeenCalledWith({+ role: "user",+ content: [{ type: "text", text: "Explain this code" }],+ });+ });++ it("does not add an image block for an empty image list", async () => {+ const sendMessage = vi.fn().mockResolvedValue({ queued: false });+ const { result } = renderSendMessageHook({ sendMessage });++ await result.current.send({+ action: "message",+ args: { content: "No images", image_urls: [] },+ });++ expect(sendMessage).toHaveBeenCalledWith({+ role: "user",+ content: [{ type: "text", text: "No images" }],+ });+ });++ it("appends image URLs after the text content", async () => {+ const imageUrls = [+ "data:image/png;base64,first",+ "data:image/png;base64,second",+ ];+ const sendMessage = vi.fn().mockResolvedValue({ queued: false });+ const { result } = renderSendMessageHook({ sendMessage });++ await expect(+ result.current.send({+ action: "message",+ args: { content: "Compare these", image_urls: imageUrls },+ }),+ ).resolves.toEqual({ queued: false });+ expect(sendMessage).toHaveBeenCalledWith({+ role: "user",+ content: [+ { type: "text", text: "Compare these" },+ { type: "image", image_urls: imageUrls },+ ],+ });+ });++ it("uses the replacement WebSocket after the active conversation changes", async () => {+ const firstSendMessage = vi.fn().mockResolvedValue({ queued: false });+ const secondSendMessage = vi.fn().mockResolvedValue({ queued: true });+ const { result, rerender } = renderSendMessageHook({+ sendMessage: firstSendMessage,+ });++ await result.current.send({+ action: "message",+ args: { content: "First conversation" },+ });++ useOptionalConversationIdMock.mockReturnValue({+ conversationId: "conversation-2",+ });+ useConversationWebSocketMock.mockReturnValue({+ sendMessage: secondSendMessage,+ });+ rerender();++ await expect(+ result.current.send({+ action: "message",+ args: { content: "Second conversation" },+ }),+ ).resolves.toEqual({ queued: true });+ expect(firstSendMessage).toHaveBeenCalledOnce();+ expect(secondSendMessage).toHaveBeenCalledWith({+ role: "user",+ content: [{ type: "text", text: "Second conversation" }],+ });+ });++ it("propagates a WebSocket delivery failure", async () => {+ const deliveryError = new Error("WebSocket closed");+ const sendMessage = vi.fn().mockRejectedValue(deliveryError);+ const { result } = renderSendMessageHook({ sendMessage });++ await expect(+ result.current.send({+ action: "message",+ args: { content: "Please deliver this" },+ }),+ ).rejects.toBe(deliveryError);+ });+});diff --git a/src/components/features/chat/uploaded-files.test.tsx b/src/components/features/chat/uploaded-files.test.tsxnew file mode 100644index 0000000000..e390c947fd--- /dev/null+++ b/src/components/features/chat/uploaded-files.test.tsx@@ -0,0 +1,244 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { UploadedFiles } from "./uploaded-files";++const mockUseConversationStore = vi.hoisted(() => vi.fn());++vi.mock("#/stores/conversation-store", () => ({+ useConversationStore: mockUseConversationStore,+}));++vi.mock("./uploaded-file", () => ({+ UploadedFile: ({+ file,+ onRemove,+ isLoading,+ }: {+ file: File;+ onRemove: () => void;+ isLoading: boolean;+ }) => (+ <button+ type="button"+ data-testid="uploaded-file"+ data-name={file.name}+ data-loading={String(isLoading)}+ data-size={String(file.size)}+ onClick={onRemove}+ >+ {file.name}+ </button>+ ),+}));++vi.mock("./uploaded-image", () => ({+ UploadedImage: ({+ image,+ onRemove,+ isLoading,+ showUploadAsFileToggle,+ uploadAsFileActive,+ onToggleUploadAsFile,+ }: {+ image: File;+ onRemove: () => void;+ isLoading: boolean;+ showUploadAsFileToggle: boolean;+ uploadAsFileActive: boolean;+ onToggleUploadAsFile: () => void;+ }) => (+ <section+ data-testid="uploaded-image"+ data-name={image.name}+ data-loading={String(isLoading)}+ data-size={String(image.size)}+ data-show-toggle={String(showUploadAsFileToggle)}+ data-upload-as-file={String(uploadAsFileActive)}+ >+ {/* eslint-disable-next-line i18next/no-literal-string */}+ <button type="button" onClick={onRemove}>+ remove {image.name}+ </button>+ {/* eslint-disable-next-line i18next/no-literal-string */}+ <button type="button" onClick={onToggleUploadAsFile}>+ toggle {image.name}+ </button>+ </section>+ ),+}));++const removeFile = vi.fn();+const removeImage = vi.fn();+const toggleImageUploadAsFile = vi.fn();++function setStore(+ overrides: Partial<{+ images: File[];+ files: File[];+ loadingFiles: string[];+ loadingImages: string[];+ imagesMarkedUploadAsFile: string[];+ }> = {},+) {+ mockUseConversationStore.mockReturnValue({+ images: [],+ files: [],+ loadingFiles: [],+ loadingImages: [],+ imagesMarkedUploadAsFile: [],+ removeFile,+ removeImage,+ toggleImageUploadAsFile,+ ...overrides,+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ setStore();+});++describe("UploadedFiles", () => {+ it("renders nothing while there are no uploaded or loading items", () => {+ const { container } = render(<UploadedFiles />);++ expect(container).toBeEmptyDOMElement();+ });++ it.each([+ [+ "an uploaded image",+ () => setStore({ images: [new File([], "image.png")] }),+ "uploaded-image",+ ],+ [+ "an uploaded file",+ () => setStore({ files: [new File([], "notes.txt")] }),+ "uploaded-file",+ ],+ [+ "a loading file",+ () => setStore({ loadingFiles: ["processing.txt"] }),+ "uploaded-file",+ ],+ [+ "a loading image",+ () => setStore({ loadingImages: ["generating.png"] }),+ "uploaded-image",+ ],+ ])("renders when its only item is %s", (_label, arrange, testId) => {+ arrange();++ render(<UploadedFiles />);++ expect(screen.getByTestId(testId)).toBeInTheDocument();+ });++ it("renders regular and loading files with their exact loading state", () => {+ setStore({+ files: [new File(["ready"], "ready.txt"), new File([], "pending.txt")],+ loadingFiles: ["pending.txt", "processing.txt"],+ });++ render(<UploadedFiles />);++ expect(screen.getAllByTestId("uploaded-file")).toHaveLength(4);+ expect(screen.getByText("ready.txt")).toHaveAttribute(+ "data-loading",+ "false",+ );+ expect(screen.getAllByText("pending.txt")[0]).toHaveAttribute(+ "data-loading",+ "true",+ );+ expect(screen.getByText("processing.txt")).toHaveAttribute(+ "data-loading",+ "true",+ );+ expect(screen.getByText("processing.txt")).toHaveAttribute(+ "data-size",+ "0",+ );+ });++ it("removes uploaded files by index but keeps loading placeholders inert", () => {+ setStore({+ files: [new File([], "first.txt"), new File([], "second.txt")],+ loadingFiles: ["processing.txt"],+ });++ render(<UploadedFiles />);+ fireEvent.click(screen.getByText("first.txt"));+ fireEvent.click(screen.getByText("second.txt"));+ fireEvent.click(screen.getByText("processing.txt"));++ expect(removeFile).toHaveBeenNthCalledWith(1, 0);+ expect(removeFile).toHaveBeenNthCalledWith(2, 1);+ expect(removeFile).toHaveBeenCalledTimes(2);+ });++ it("renders image status and forwards remove and toggle actions", () => {+ setStore({+ images: [new File([], "diagram.png"), new File([], "photo.jpg")],+ loadingImages: ["photo.jpg", "generating.png"],+ imagesMarkedUploadAsFile: ["diagram.png", "generating.png"],+ });++ render(<UploadedFiles />);++ const images = screen.getAllByTestId("uploaded-image");+ expect(images).toHaveLength(4);+ expect(images[0]).toHaveAttribute("data-name", "diagram.png");+ expect(images[0]).toHaveAttribute("data-loading", "false");+ expect(images[0]).toHaveAttribute("data-show-toggle", "true");+ expect(images[0]).toHaveAttribute("data-upload-as-file", "true");+ expect(images[1]).toHaveAttribute("data-name", "photo.jpg");+ expect(images[1]).toHaveAttribute("data-loading", "true");+ expect(images[1]).toHaveAttribute("data-upload-as-file", "false");+ expect(images[3]).toHaveAttribute("data-name", "generating.png");+ expect(images[3]).toHaveAttribute("data-loading", "true");+ expect(images[3]).toHaveAttribute("data-size", "0");+ expect(images[3]).toHaveAttribute("data-upload-as-file", "true");++ fireEvent.click(screen.getByRole("button", { name: "remove diagram.png" }));+ fireEvent.click(+ screen.getAllByRole("button", { name: "remove photo.jpg" })[0],+ );+ fireEvent.click(+ screen.getByRole("button", { name: "remove generating.png" }),+ );+ fireEvent.click(screen.getByRole("button", { name: "toggle diagram.png" }));+ fireEvent.click(+ screen.getByRole("button", { name: "toggle generating.png" }),+ );++ expect(removeImage).toHaveBeenNthCalledWith(1, 0);+ expect(removeImage).toHaveBeenNthCalledWith(2, 1);+ expect(removeImage).toHaveBeenCalledTimes(2);+ expect(toggleImageUploadAsFile).toHaveBeenNthCalledWith(1, "diagram.png");+ expect(toggleImageUploadAsFile).toHaveBeenNthCalledWith(+ 2,+ "generating.png",+ );+ });++ it("renders every collection without React key collisions", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ setStore({+ files: [new File([], "first.txt"), new File([], "second.txt")],+ loadingFiles: ["loading-one.txt", "loading-two.txt"],+ images: [new File([], "first.png"), new File([], "second.png")],+ loadingImages: ["loading-one.png", "loading-two.png"],+ });++ try {+ render(<UploadedFiles />);++ expect(screen.getAllByTestId("uploaded-file")).toHaveLength(4);+ expect(screen.getAllByTestId("uploaded-image")).toHaveLength(4);+ expect(errorSpy).not.toHaveBeenCalled();+ } finally {+ errorSpy.mockRestore();+ }+ });+});