import { providerIdentifiers } from "@roo-code/types" import { defaultModeSlug } from "@roo/modes" import { render, fireEvent, screen, act } from "@src/utils/test-utils" import { useExtensionState } from "@src/context/ExtensionStateContext" import { vscode } from "@src/utils/vscode" import * as pathMentions from "@src/utils/path-mentions" import { ContextMenuOptionType } from "@src/utils/context-mentions" import { ChatTextArea } from "../ChatTextArea" vi.mock("@src/utils/vscode", () => ({ vscode: { postMessage: vi.fn(), }, })) vi.mock("@src/components/common/CodeBlock") vi.mock("@src/components/common/MarkdownBlock") // Capture the ContextMenu's onSelect so tests can invoke menu selections // directly. The real ContextMenu only renders option rows; stubbing it keeps // the ChatTextArea signal tests focused on what a selection does. const contextMenuHarness = vi.hoisted(() => ({ onSelect: undefined as ((type: string, value?: string) => void) | undefined, })) vi.mock("../ContextMenu", () => ({ default: (props: { onSelect: (type: string, value?: string) => void }) => { contextMenuHarness.onSelect = props.onSelect return null }, })) vi.mock("@src/utils/path-mentions", () => ({ convertToMentionPath: vi.fn((path, cwd) => { // Simple mock implementation that mimics the real function's behavior if (cwd && path.toLowerCase().startsWith(cwd.toLowerCase())) { const relativePath = path.substring(cwd.length) return "@" + (relativePath.startsWith("/") ? relativePath : "/" + relativePath) } return path }), })) // Get the mocked postMessage function const mockPostMessage = vscode.postMessage as ReturnType const mockConvertToMentionPath = pathMentions.convertToMentionPath as ReturnType // Mock ExtensionStateContext vi.mock("@src/context/ExtensionStateContext") // Custom query function to get the enhance prompt button const getEnhancePromptButton = () => { return screen.getByRole("button", { name: (_, element) => { // Find the button with the wand sparkles icon (Lucide React) return element.querySelector(".lucide-wand-sparkles") !== null }, }) } describe("ChatTextArea", () => { const defaultProps = { inputValue: "", setInputValue: vi.fn(), onSend: vi.fn(), sendingDisabled: false, selectApiConfigDisabled: false, onSelectImages: vi.fn(), shouldDisableImages: false, placeholderText: "Type a message...", selectedImages: [], setSelectedImages: vi.fn(), onHeightChange: vi.fn(), mode: defaultModeSlug, setMode: vi.fn(), modeShortcutText: "(⌘. for next mode)", } beforeEach(() => { vi.clearAllMocks() // Default mock implementation for useExtensionState ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], cwd: "/test/workspace", }) }) it.each([false, true])("only autofocuses the mounted input when this document has focus=%s", (hasFocus) => { const documentFocus = vi.spyOn(document, "hasFocus").mockReturnValue(hasFocus) const focusedElements: HTMLElement[] = [] const originalFocus = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "focus") if (!originalFocus) { throw new Error("Expected the test setup to define HTMLElement.focus") } // The shared setup replaces focus with an accessor, so restore its descriptor after the test. Object.defineProperty(HTMLElement.prototype, "focus", { configurable: true, get: () => function (this: HTMLElement) { focusedElements.push(this) }, }) const outsideInput = document.createElement("input") document.body.append(outsideInput) outsideInput.focus() try { render() expect(focusedElements[0]).toBe(outsideInput) expect(focusedElements).toHaveLength(hasFocus ? 2 : 1) if (hasFocus) { expect(focusedElements[1]).toBeInstanceOf(HTMLTextAreaElement) } } finally { documentFocus.mockRestore() Object.defineProperty(HTMLElement.prototype, "focus", originalFocus) outsideInput.remove() } }) describe("enhance prompt button", () => { it("should be enabled even when sendingDisabled is true (for message queueing)", () => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], cwd: "/test/workspace", }) render() const enhanceButton = getEnhancePromptButton() expect(enhanceButton).toHaveClass("cursor-pointer") }) }) describe("handleEnhancePrompt", () => { it("should send message with correct configuration when clicked", () => { const apiConfiguration = { apiProvider: providerIdentifiers.openrouter, apiKey: "test-key", } ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration, taskHistory: [], cwd: "/test/workspace", }) render() const enhanceButton = getEnhancePromptButton() fireEvent.click(enhanceButton) expect(mockPostMessage).toHaveBeenCalledWith({ type: "enhancePrompt", text: "Test prompt", }) }) it("should not send message when input is empty", () => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, taskHistory: [], cwd: "/test/workspace", }) render() // Clear any calls from component initialization (e.g., IndexingStatusBadge) mockPostMessage.mockClear() const enhanceButton = getEnhancePromptButton() fireEvent.click(enhanceButton) expect(mockPostMessage).not.toHaveBeenCalled() }) it("should show loading state while enhancing", () => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.openrouter, }, taskHistory: [], cwd: "/test/workspace", }) render() const enhanceButton = getEnhancePromptButton() fireEvent.click(enhanceButton) // Check if the WandSparkles icon has the animate-spin class const animatingIcon = enhanceButton.querySelector(".animate-spin") expect(animatingIcon).toBeInTheDocument() }) }) describe("effect dependencies", () => { it("should update when apiConfiguration changes", () => { const { rerender } = render() // Update apiConfiguration ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.openrouter, newSetting: "test", }, taskHistory: [], cwd: "/test/workspace", }) rerender() // Verify the enhance button appears after apiConfiguration changes expect(getEnhancePromptButton()).toBeInTheDocument() }) }) describe("enhanced prompt response", () => { it("should update input value using native browser methods when receiving enhanced prompt", () => { const setInputValue = vi.fn() // Mock document.execCommand const mockExecCommand = vi.fn().mockReturnValue(true) Object.defineProperty(document, "execCommand", { value: mockExecCommand, writable: true, }) const { container } = render( , ) const textarea = container.querySelector("textarea")! // Mock textarea methods const mockSelect = vi.fn() const mockFocus = vi.fn() textarea.select = mockSelect textarea.focus = mockFocus // Simulate receiving enhanced prompt message window.dispatchEvent( new MessageEvent("message", { data: { type: "enhancedPrompt", text: "Enhanced test prompt", }, }), ) // Verify native browser methods were used expect(mockFocus).toHaveBeenCalled() expect(mockSelect).toHaveBeenCalled() expect(mockExecCommand).toHaveBeenCalledWith("insertText", false, "Enhanced test prompt") }) it("should fallback to setInputValue when execCommand is not available", () => { const setInputValue = vi.fn() // Mock document.execCommand to be undefined (not available) Object.defineProperty(document, "execCommand", { value: undefined, writable: true, }) render() // Simulate receiving enhanced prompt message window.dispatchEvent( new MessageEvent("message", { data: { type: "enhancedPrompt", text: "Enhanced test prompt", }, }), ) // Verify fallback to setInputValue was used expect(setInputValue).toHaveBeenCalledWith("Enhanced test prompt") }) it("routes the enhanced prompt through the generated-text setter when provided", () => { const setInputValue = vi.fn() const setInputValueGenerated = vi.fn() Object.defineProperty(document, "execCommand", { value: undefined, writable: true }) render( , ) window.dispatchEvent( new MessageEvent("message", { data: { type: "enhancedPrompt", text: "Enhanced test prompt" } }), ) expect(setInputValueGenerated).toHaveBeenCalledWith("Enhanced test prompt") expect(setInputValue).not.toHaveBeenCalled() }) it("routes the native enhanced-prompt input event through the generated-text setter, then manual edits through setInputValue", () => { const setInputValue = vi.fn() const setInputValueGenerated = vi.fn() // Mimic the browser: execCommand fires an input event on the textarea. const target: { el?: HTMLTextAreaElement } = {} Object.defineProperty(document, "execCommand", { value: vi.fn((_cmd: string, _ui: boolean, value: string) => { if (target.el) { fireEvent.input(target.el, { target: { value } }) } return true }), writable: true, }) const { container } = render( , ) const textarea = container.querySelector("textarea")! target.el = textarea act(() => { window.dispatchEvent( new MessageEvent("message", { data: { type: "enhancedPrompt", text: "Enhanced test prompt" } }), ) }) expect(setInputValueGenerated).toHaveBeenCalledWith("Enhanced test prompt") expect(setInputValue).not.toHaveBeenCalled() fireEvent.change(textarea, { target: { value: "typed by hand" } }) expect(setInputValue).toHaveBeenCalledWith("typed by hand") }) it("should not crash when textarea ref is not available", () => { const setInputValue = vi.fn() render() // Simulate receiving enhanced prompt message when textarea ref might not be ready expect(() => { window.dispatchEvent( new MessageEvent("message", { data: { type: "enhancedPrompt", text: "Enhanced test prompt", }, }), ) }).not.toThrow() }) }) describe("multi-file drag and drop", () => { const mockCwd = "/Users/test/project" beforeEach(() => { vi.clearAllMocks() ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, cwd: mockCwd, }) mockConvertToMentionPath.mockClear() }) it("should process multiple file paths separated by newlines", () => { const setInputValue = vi.fn() const { container } = render( , ) // Create a mock dataTransfer object with text data containing multiple file paths const dataTransfer = { getData: vi.fn().mockReturnValue("/Users/test/project/file1.js\n/Users/test/project/file2.js"), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // Verify convertToMentionPath was called for each file path expect(mockConvertToMentionPath).toHaveBeenCalledTimes(2) expect(mockConvertToMentionPath).toHaveBeenCalledWith("/Users/test/project/file1.js", mockCwd) expect(mockConvertToMentionPath).toHaveBeenCalledWith("/Users/test/project/file2.js", mockCwd) // Verify setInputValue was called with the correct value // The mock implementation of convertToMentionPath will convert the paths to @/file1.js and @/file2.js expect(setInputValue).toHaveBeenCalledWith("@/file1.js @/file2.js Initial text") }) it("should filter out empty lines in the dragged text", () => { const setInputValue = vi.fn() const { container } = render( , ) // Create a mock dataTransfer object with text data containing empty lines const dataTransfer = { getData: vi.fn().mockReturnValue("/Users/test/project/file1.js\n\n/Users/test/project/file2.js\n\n"), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // Verify convertToMentionPath was called only for non-empty lines expect(mockConvertToMentionPath).toHaveBeenCalledTimes(2) // Verify setInputValue was called with the correct value expect(setInputValue).toHaveBeenCalledWith("@/file1.js @/file2.js Initial text") }) it("should correctly update cursor position after adding multiple mentions", () => { const setInputValue = vi.fn() const initialCursorPosition = 5 const { container } = render( , ) // Set the cursor position manually const textArea = container.querySelector("textarea") if (textArea) { textArea.selectionStart = initialCursorPosition textArea.selectionEnd = initialCursorPosition } // Create a mock dataTransfer object with text data const dataTransfer = { getData: vi.fn().mockReturnValue("/Users/test/project/file1.js\n/Users/test/project/file2.js"), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // The cursor position should be updated based on the implementation in the component expect(setInputValue).toHaveBeenCalledWith("@/file1.js @/file2.js Hello world") }) it("should handle very long file paths correctly", () => { const setInputValue = vi.fn() const { container } = render() // Create a very long file path const longPath = "/Users/test/project/very/long/path/with/many/nested/directories/and/a/very/long/filename/with/extension.typescript" // Create a mock dataTransfer object with the long path const dataTransfer = { getData: vi.fn().mockReturnValue(longPath), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // Verify convertToMentionPath was called with the long path expect(mockConvertToMentionPath).toHaveBeenCalledWith(longPath, mockCwd) // The mock implementation will convert it to @/very/long/path/... expect(setInputValue).toHaveBeenCalledWith( "@/very/long/path/with/many/nested/directories/and/a/very/long/filename/with/extension.typescript ", ) }) it("should handle paths with special characters correctly", () => { const setInputValue = vi.fn() const { container } = render() // Create paths with special characters const specialPath1 = "/Users/test/project/file with spaces.js" const specialPath2 = "/Users/test/project/file-with-dashes.js" const specialPath3 = "/Users/test/project/file_with_underscores.js" const specialPath4 = "/Users/test/project/file.with.dots.js" // Create a mock dataTransfer object with the special paths const dataTransfer = { getData: vi.fn().mockReturnValue(`${specialPath1}\n${specialPath2}\n${specialPath3}\n${specialPath4}`), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // Verify convertToMentionPath was called for each path expect(mockConvertToMentionPath).toHaveBeenCalledTimes(4) expect(mockConvertToMentionPath).toHaveBeenCalledWith(specialPath1, mockCwd) expect(mockConvertToMentionPath).toHaveBeenCalledWith(specialPath2, mockCwd) expect(mockConvertToMentionPath).toHaveBeenCalledWith(specialPath3, mockCwd) expect(mockConvertToMentionPath).toHaveBeenCalledWith(specialPath4, mockCwd) // Verify setInputValue was called with the correct value expect(setInputValue).toHaveBeenCalledWith( "@/file with spaces.js @/file-with-dashes.js @/file_with_underscores.js @/file.with.dots.js ", ) }) it("should handle paths outside the current working directory", () => { const setInputValue = vi.fn() const { container } = render() // Create paths outside the current working directory const outsidePath = "/Users/other/project/file.js" // Mock the convertToMentionPath function to return the original path for paths outside cwd mockConvertToMentionPath.mockImplementationOnce((path, _cwd) => { return path // Return original path for this test }) // Create a mock dataTransfer object with the outside path const dataTransfer = { getData: vi.fn().mockReturnValue(outsidePath), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // Verify convertToMentionPath was called with the outside path expect(mockConvertToMentionPath).toHaveBeenCalledWith(outsidePath, mockCwd) // Verify setInputValue was called with the original path expect(setInputValue).toHaveBeenCalledWith("/Users/other/project/file.js ") }) it("should do nothing when dropped text is empty", () => { const setInputValue = vi.fn() const { container } = render( , ) // Create a mock dataTransfer object with empty text const dataTransfer = { getData: vi.fn().mockReturnValue(""), files: [], } // Simulate drop event fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer, preventDefault: vi.fn(), }) // Verify convertToMentionPath was not called expect(mockConvertToMentionPath).not.toHaveBeenCalled() // Verify setInputValue was not called expect(setInputValue).not.toHaveBeenCalled() }) describe("dragover acceptance", () => { // jsdom has no DragEvent constructor, so build a plain cancelable // Event and attach the drag payload the React handler expects. const fireDragOver = (element: Element, types: string[], shiftKey = false) => { const event = new Event("dragover", { bubbles: true, cancelable: true }) const dataTransfer = { types, files: [], dropEffect: "none" } Object.defineProperty(event, "dataTransfer", { value: dataTransfer }) Object.defineProperty(event, "shiftKey", { value: shiftKey }) fireEvent(element, event) return { event, dataTransfer } } it.each([ "Files", "resourceurls", "codeeditors", "codefiles", "application/vnd.code.uri-list", "RESOURCEURLS", ])("accepts %s drags without Shift", (type) => { const { container } = render() const { event, dataTransfer } = fireDragOver(container.querySelector(".chat-text-area")!, [type]) expect(event.defaultPrevented).toBe(true) expect(dataTransfer.dropEffect).toBe("copy") expect(container.querySelector(".border-dashed")).not.toBeNull() }) it.each([["text/plain"], ["text/uri-list"], ["text/plain", "text/uri-list"]])( "keeps native behavior and clears the highlight for drag types %j without Shift", (...types) => { const { container } = render() const target = container.querySelector(".chat-text-area")! fireDragOver(target, ["Files"]) expect(container.querySelector(".border-dashed")).not.toBeNull() const { event, dataTransfer } = fireDragOver(target, types) expect(event.defaultPrevented).toBe(false) expect(dataTransfer.dropEffect).toBe("none") expect(container.querySelector(".border-dashed")).toBeNull() }, ) it("still accepts plain text drags when Shift is held", () => { const { container } = render() const { event, dataTransfer } = fireDragOver( container.querySelector(".chat-text-area")!, ["text/plain"], true, ) expect(event.defaultPrevented).toBe(true) expect(dataTransfer.dropEffect).toBe("copy") expect(container.querySelector(".border-dashed")).not.toBeNull() }) }) describe("prompt history navigation", () => { const mockClineMessages = [ { type: "say", say: "user_feedback", text: "First prompt", ts: 1000 }, { type: "say", say: "user_feedback", text: "Second prompt", ts: 2000 }, { type: "say", say: "user_feedback", text: "Third prompt", ts: 3000 }, ] beforeEach(() => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], clineMessages: mockClineMessages, cwd: "/test/workspace", }) }) it("should navigate to previous prompt on arrow up when cursor is at beginning", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Ensure cursor is at the beginning textarea.setSelectionRange(0, 0) // Simulate arrow up key press fireEvent.keyDown(textarea, { key: "ArrowUp" }) // Should set the newest conversation message (first in reversed array) expect(setInputValue).toHaveBeenCalledWith("Third prompt") }) it("restores the draft with its segments after history navigation", () => { const draft = [{ text: "ctx @/a", source: "generated" as const }] const setInputValueWithSegments = vi.fn() const { container } = render( draft} setInputValueWithSegments={setInputValueWithSegments} />, ) const textarea = container.querySelector("textarea")! textarea.setSelectionRange(0, 0) fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValueWithSegments).toHaveBeenLastCalledWith("Third prompt", [ { text: "Third prompt", source: "generated" }, ]) fireEvent.keyDown(textarea, { key: "ArrowDown" }) expect(setInputValueWithSegments).toHaveBeenLastCalledWith("ctx @/a", draft) }) it.each([ { inputType: "historyUndo", generated: true }, { inputType: "historyRedo", generated: true }, { inputType: "insertText", generated: false }, ])("marks the draft generated only for $inputType: $generated", ({ inputType, generated }) => { const setInputValue = vi.fn() const setInputValueWithSegments = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! fireEvent.input(textarea, { target: { value: "ctx @/secret" }, inputType }) if (generated) { expect(setInputValueWithSegments).toHaveBeenCalledWith("ctx @/secret", [ { text: "ctx @/secret", source: "generated" }, ]) expect(setInputValue).not.toHaveBeenCalled() } else { expect(setInputValue).toHaveBeenCalledWith("ctx @/secret") expect(setInputValueWithSegments).not.toHaveBeenCalled() } }) it("should navigate through history with multiple arrow up presses", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // First arrow up - newest conversation message fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Third prompt") // Update input value to simulate the state change setInputValue.mockClear() // Second arrow up - previous conversation message fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Second prompt") }) it("should navigate forward with arrow down", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Go back in history first (index 0 -> "Third prompt", then index 1 -> "Second prompt") fireEvent.keyDown(textarea, { key: "ArrowUp" }) fireEvent.keyDown(textarea, { key: "ArrowUp" }) setInputValue.mockClear() // Navigate forward (from index 1 back to index 0) fireEvent.keyDown(textarea, { key: "ArrowDown" }) expect(setInputValue).toHaveBeenCalledWith("Third prompt") }) it("should preserve current input when starting navigation", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Navigate to history fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Third prompt") setInputValue.mockClear() // Navigate back to current input fireEvent.keyDown(textarea, { key: "ArrowDown" }) expect(setInputValue).toHaveBeenCalledWith("Current input") }) it("should reset history navigation when user types", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Navigate to history fireEvent.keyDown(textarea, { key: "ArrowUp" }) setInputValue.mockClear() // Type something fireEvent.change(textarea, { target: { value: "New input", selectionStart: 9 } }) // Should reset history navigation expect(setInputValue).toHaveBeenCalledWith("New input") }) it("should reset history navigation when sending message", () => { const onSend = vi.fn() const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Navigate to history first fireEvent.keyDown(textarea, { key: "ArrowUp" }) setInputValue.mockClear() // Send message fireEvent.keyDown(textarea, { key: "Enter" }) expect(onSend).toHaveBeenCalled() }) it("should navigate history when cursor is at first line", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Clear any calls from initial render setInputValue.mockClear() // With empty input, cursor is at first line by default // Arrow up should navigate history fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Third prompt") }) it("should filter history by current workspace", () => { const mixedClineMessages = [ { type: "say", say: "user_feedback", text: "Workspace 1 prompt", ts: 1000 }, { type: "say", say: "user_feedback", text: "Other workspace prompt", ts: 2000 }, { type: "say", say: "user_feedback", text: "Workspace 1 prompt 2", ts: 3000 }, ] ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], clineMessages: mixedClineMessages, cwd: "/test/workspace", }) const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Should show conversation messages newest first (after reverse) fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Workspace 1 prompt 2") setInputValue.mockClear() fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Other workspace prompt") }) it("should handle empty conversation history gracefully", () => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], clineMessages: [], cwd: "/test/workspace", }) const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Should not crash or call setInputValue fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).not.toHaveBeenCalled() }) it("should ignore empty or whitespace-only messages", () => { const clineMessagesWithEmpty = [ { type: "say", say: "user_feedback", text: "Valid prompt", ts: 1000 }, { type: "say", say: "user_feedback", text: "", ts: 2000 }, { type: "say", say: "user_feedback", text: " ", ts: 3000 }, { type: "say", say: "user_feedback", text: "Another valid prompt", ts: 4000 }, ] ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], clineMessages: clineMessagesWithEmpty, cwd: "/test/workspace", }) const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Should skip empty messages, newest first for conversation fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Another valid prompt") setInputValue.mockClear() fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Valid prompt") }) it("should use task history (oldest first) when no conversation messages exist", () => { const mockTaskHistory = [ { task: "First task", workspace: "/test/workspace" }, { task: "Second task", workspace: "/test/workspace" }, { task: "Third task", workspace: "/test/workspace" }, ] ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: mockTaskHistory, clineMessages: [], // No conversation messages cwd: "/test/workspace", }) const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Should show task history oldest first (chronological order) fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("First task") setInputValue.mockClear() fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Second task") }) it("should reset navigation position when switching between history sources", () => { const setInputValue = vi.fn() const { rerender } = render( , ) // Start with task history ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [ { task: "Task 1", workspace: "/test/workspace" }, { task: "Task 2", workspace: "/test/workspace" }, ], clineMessages: [], cwd: "/test/workspace", }) rerender() const textarea = document.querySelector("textarea")! // Navigate in task history fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Task 1") // Switch to conversation messages ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], clineMessages: [ { type: "say", say: "user_feedback", text: "Message 1", ts: 1000 }, { type: "say", say: "user_feedback", text: "Message 2", ts: 2000 }, ], cwd: "/test/workspace", }) setInputValue.mockClear() rerender() // Should start from beginning of conversation history (newest first) fireEvent.keyDown(textarea, { key: "ArrowUp" }) expect(setInputValue).toHaveBeenCalledWith("Message 2") }) it("should not navigate history with arrow up when cursor is not at beginning", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Set cursor to middle of text (not at beginning) textarea.setSelectionRange(5, 5) // Clear any calls from initial render setInputValue.mockClear() // Simulate arrow up key press fireEvent.keyDown(textarea, { key: "ArrowUp" }) // Should not navigate history, allowing default behavior (move cursor to start) expect(setInputValue).not.toHaveBeenCalled() }) it("should navigate history with arrow up when cursor is at beginning", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Set cursor to beginning of text textarea.setSelectionRange(0, 0) // Clear any calls from initial render setInputValue.mockClear() // Simulate arrow up key press fireEvent.keyDown(textarea, { key: "ArrowUp" }) // Should navigate to history since cursor is at beginning expect(setInputValue).toHaveBeenCalledWith("Third prompt") }) it("should navigate history with Command+Up when cursor is at beginning", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Set cursor to beginning of text textarea.setSelectionRange(0, 0) // Clear any calls from initial render setInputValue.mockClear() // Simulate Command+Up key press fireEvent.keyDown(textarea, { key: "ArrowUp", metaKey: true }) // Should navigate to history since cursor is at beginning (same as regular Up) expect(setInputValue).toHaveBeenCalledWith("Third prompt") }) it("should not navigate history with Command+Up when cursor is not at beginning", () => { const setInputValue = vi.fn() const { container } = render( , ) const textarea = container.querySelector("textarea")! // Set cursor to middle of text (not at beginning) textarea.setSelectionRange(5, 5) // Clear any calls from initial render setInputValue.mockClear() // Simulate Command+Up key press fireEvent.keyDown(textarea, { key: "ArrowUp", metaKey: true }) // Should not navigate history, allowing default behavior (same as regular Up) expect(setInputValue).not.toHaveBeenCalled() }) }) }) describe("slash command highlighting", () => { const mockCommands = [ { name: "setup", source: "project", description: "Setup the project" }, { name: "deploy", source: "global", description: "Deploy the application" }, { name: "test-command", source: "project", description: "Test command with dash" }, ] beforeEach(() => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], cwd: "/test/workspace", commands: mockCommands, }) }) it("should highlight valid slash commands", () => { const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // The highlighting is applied via innerHTML, so we need to check the content // The valid command "/setup" should be highlighted expect(highlightLayer.innerHTML).toContain('/setup') }) it("should not highlight invalid slash commands", () => { const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // The invalid command "/invalid" should not be highlighted expect(highlightLayer.innerHTML).not.toContain( '/invalid', ) // But it should still contain the text without highlighting expect(highlightLayer.innerHTML).toContain("/invalid") }) it("should highlight only the command portion, not arguments", () => { const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // Only "/deploy" should be highlighted, not "to production" expect(highlightLayer.innerHTML).toContain( '/deploy', ) expect(highlightLayer.innerHTML).not.toContain( '/deploy to production', ) }) it("should handle commands with dashes and underscores", () => { const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // The command with dash should be highlighted expect(highlightLayer.innerHTML).toContain( '/test-command', ) }) it("should be case-sensitive when matching commands", () => { const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // "/Setup" (capital S) should not be highlighted since the command is "setup" (lowercase) expect(highlightLayer.innerHTML).not.toContain( '/Setup', ) expect(highlightLayer.innerHTML).toContain("/Setup") }) it("should highlight multiple valid commands in the same text", () => { const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // Both valid commands should be highlighted expect(highlightLayer.innerHTML).toContain('/setup') expect(highlightLayer.innerHTML).toContain( '/deploy', ) }) it("should handle mixed valid and invalid commands", () => { const { getByTestId } = render( , ) const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // Valid commands should be highlighted expect(highlightLayer.innerHTML).toContain('/setup') expect(highlightLayer.innerHTML).toContain( '/deploy', ) // Invalid command should not be highlighted expect(highlightLayer.innerHTML).not.toContain( '/invalid', ) expect(highlightLayer.innerHTML).toContain("/invalid") }) it("should work when no commands are available", () => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], cwd: "/test/workspace", commands: undefined, }) const { getByTestId } = render() const highlightLayer = getByTestId("highlight-layer") expect(highlightLayer).toBeInTheDocument() // No commands should be highlighted when commands array is undefined expect(highlightLayer.innerHTML).not.toContain( '/setup', ) expect(highlightLayer.innerHTML).toContain("/setup") }) }) describe("selectApiConfig", () => { // Helper function to get the API config dropdown const getApiConfigDropdown = () => { return screen.getByTestId("dropdown-trigger") } it("should be enabled independently of sendingDisabled", () => { render() const apiConfigDropdown = getApiConfigDropdown() expect(apiConfigDropdown).not.toHaveAttribute("disabled") }) it("should be disabled when selectApiConfigDisabled is true", () => { render() const apiConfigDropdown = getApiConfigDropdown() expect(apiConfigDropdown).toHaveAttribute("disabled") }) describe("enter key behavior", () => { it("should send on Enter and allow newline on Shift+Enter in default mode", () => { const onSend = vi.fn() ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], cwd: "/test/workspace", }) const { container } = render() const textarea = container.querySelector("textarea")! fireEvent.keyDown(textarea, { key: "Enter" }) expect(onSend).toHaveBeenCalledTimes(1) const shiftEnterEvent = new KeyboardEvent("keydown", { key: "Enter", shiftKey: true, bubbles: true }) fireEvent(textarea, shiftEnterEvent) expect(onSend).toHaveBeenCalledTimes(1) expect(shiftEnterEvent.defaultPrevented).toBe(false) }) it("should send only on Ctrl/Cmd+Enter and allow Shift+Enter in newline mode", () => { const onSend = vi.fn() ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic, }, taskHistory: [], cwd: "/test/workspace", enterBehavior: "newline", }) const { container } = render() const textarea = container.querySelector("textarea")! const plainEnterEvent = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }) fireEvent(textarea, plainEnterEvent) expect(onSend).not.toHaveBeenCalled() expect(plainEnterEvent.defaultPrevented).toBe(false) const ctrlEnterEvent = new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true, bubbles: true, cancelable: true, }) fireEvent(textarea, ctrlEnterEvent) expect(onSend).toHaveBeenCalledTimes(1) expect(ctrlEnterEvent.defaultPrevented).toBe(true) const shiftEnterEvent = new KeyboardEvent("keydown", { key: "Enter", shiftKey: true, bubbles: true, cancelable: true, }) fireEvent(textarea, shiftEnterEvent) expect(onSend).toHaveBeenCalledTimes(1) expect(shiftEnterEvent.defaultPrevented).toBe(false) }) }) }) describe("send button visibility", () => { it("should show send button when there are images but no text", () => { const { container } = render( , ) // Find the send button by looking for the button with SendHorizontal icon const buttons = container.querySelectorAll("button") const sendButton = Array.from(buttons).find( (button) => button.querySelector(".lucide-send-horizontal") !== null, ) expect(sendButton).toBeInTheDocument() // Check that the button is visible (has opacity-100 class when content exists) expect(sendButton).toHaveClass("opacity-100") expect(sendButton).toHaveClass("pointer-events-auto") expect(sendButton).not.toHaveClass("opacity-0") expect(sendButton).not.toHaveClass("pointer-events-none") }) it("should hide send button when there is no text and no images", () => { const { container } = render() // Find the send button by looking for the button with SendHorizontal icon const buttons = container.querySelectorAll("button") const sendButton = Array.from(buttons).find( (button) => button.querySelector(".lucide-send-horizontal") !== null, ) expect(sendButton).toBeInTheDocument() // Check that the button is hidden (has opacity-0 class when no content) expect(sendButton).toHaveClass("opacity-0") expect(sendButton).toHaveClass("pointer-events-none") expect(sendButton).not.toHaveClass("opacity-100") expect(sendButton).not.toHaveClass("pointer-events-auto") }) it("should show send button when there is text but no images", () => { const { container } = render() // Find the send button by looking for the button with SendHorizontal icon const buttons = container.querySelectorAll("button") const sendButton = Array.from(buttons).find( (button) => button.querySelector(".lucide-send-horizontal") !== null, ) expect(sendButton).toBeInTheDocument() // Check that the button is visible expect(sendButton).toHaveClass("opacity-100") expect(sendButton).toHaveClass("pointer-events-auto") }) it("should show send button when there is both text and images", () => { const { container } = render( , ) // Find the send button by looking for the button with SendHorizontal icon const buttons = container.querySelectorAll("button") const sendButton = Array.from(buttons).find( (button) => button.querySelector(".lucide-send-horizontal") !== null, ) expect(sendButton).toBeInTheDocument() // Check that the button is visible expect(sendButton).toHaveClass("opacity-100") expect(sendButton).toHaveClass("pointer-events-auto") }) }) describe("blank suggestion copy crash (issue #1226)", () => { const getSendButton = (container: HTMLElement) => { const buttons = container.querySelectorAll("button") return Array.from(buttons).find((button) => button.querySelector(".lucide-send-horizontal") !== null) } it("renders without crashing and treats an undefined inputValue as empty", () => { // Intentionally pass the malformed value that #1226 produced at runtime: // clicking "Copy to input" on an empty follow-up suggestion pushed // `undefined` into the input state. const undefinedInput = { ...defaultProps, inputValue: undefined } as unknown as typeof defaultProps const { container } = render() // Before the #1226 fix, mounting with an undefined inputValue threw // "Cannot read properties of undefined (reading 'trim')" in the // hasInputContent memo. It should render normally instead. // The normalized value drives the textarea: a malformed input renders as empty. const textarea = container.querySelector("textarea") expect(textarea).toBeInTheDocument() expect(textarea).toHaveValue("") // Clicking "Enhance prompt" with an undefined input must not crash either: // the undefined input behaves like an empty one, so nothing is sent. mockPostMessage.mockClear() fireEvent.click(getEnhancePromptButton()) expect(mockPostMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "enhancePrompt" })) // An undefined input behaves like an empty input: no content to send. const sendButton = getSendButton(container) expect(sendButton).toBeInTheDocument() expect(sendButton).toHaveClass("opacity-0") expect(sendButton).toHaveClass("pointer-events-none") }) it.each([0, false, { answer: "nope" }])("treats a non-string inputValue of %p as empty", (value) => { // Only nullish values were normalized before the #1226 follow-up fix; // any other non-string value must be treated as empty, not crash. const badInput = { ...defaultProps, inputValue: value } as unknown as typeof defaultProps const { container } = render() // The normalized value drives the textarea: a non-string input renders as empty. const textarea = container.querySelector("textarea") expect(textarea).toBeInTheDocument() expect(textarea).toHaveValue("") mockPostMessage.mockClear() fireEvent.click(getEnhancePromptButton()) expect(mockPostMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "enhancePrompt" })) const sendButton = getSendButton(container) expect(sendButton).toBeInTheDocument() expect(sendButton).toHaveClass("opacity-0") expect(sendButton).toHaveClass("pointer-events-none") }) }) describe("string operations on the normalized input (issue #1226)", () => { const getTextarea = (container: HTMLElement) => { const textarea = container.querySelector("textarea") if (!textarea) { throw new Error("expected the chat textarea to be rendered") } return textarea } it("inserts command text at the cursor via the insertTextIntoTextarea message", () => { render() act(() => { window.dispatchEvent( new MessageEvent("message", { data: { type: "insertTextIntoTextarea", text: "/command" } }), ) }) // The cursor starts at 0, so the command is prepended with a trailing space. expect(defaultProps.setInputValue).toHaveBeenCalledWith("/command hello ") }) it("inspects the characters around the cursor on Backspace without crashing", () => { const { container } = render() const textarea = getTextarea(container) fireEvent.keyDown(textarea, { key: "Backspace" }) // Plain text: no mention manipulation, so the input is untouched. expect(defaultProps.setInputValue).not.toHaveBeenCalled() }) it("removes a mention on the second Backspace after deleting the space after it", () => { const { container } = render() const textarea = getTextarea(container) // Position the cursor after the trailing space and tell the component about it. textarea.setSelectionRange(16, 16) fireEvent.mouseUp(textarea) // First Backspace: drops the space after the mention and arms the pending flag. fireEvent.keyDown(textarea, { key: "Backspace" }) // Second Backspace: removes the mention itself. fireEvent.keyDown(textarea, { key: "Backspace" }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("hello ") }) it("resets the pending mention flag without changing the input when the cursor is not after a mention", () => { const { container } = render() const textarea = getTextarea(container) // Arm the pending flag with the first Backspace right after the mention. textarea.setSelectionRange(16, 16) fireEvent.mouseUp(textarea) fireEvent.keyDown(textarea, { key: "Backspace" }) // Move the cursor away from the mention before the next Backspace. textarea.setSelectionRange(2, 2) fireEvent.mouseUp(textarea) fireEvent.keyDown(textarea, { key: "Backspace" }) // removeMention finds no mention at the cursor, so the input is untouched. expect(defaultProps.setInputValue).not.toHaveBeenCalled() }) it("adds a trailing space after a pasted URL", () => { const { container } = render() const textarea = getTextarea(container) const pasteEvent = new window.Event("paste", { bubbles: true, cancelable: true }) Object.defineProperty(pasteEvent, "clipboardData", { value: { items: [], getData: () => "https://example.com" }, }) act(() => { textarea.dispatchEvent(pasteEvent) }) // The URL is inserted at cursor position 0, followed by a space. expect(defaultProps.setInputValue).toHaveBeenCalledWith("https://example.com visit ") }) it("uses the re-rendered input when inserting command text", () => { const { container, rerender } = render() rerender() // Reset the DOM cursor: JSDOM moves the selection to the end of a // re-rendered value, so anchor the insertion at position 0 explicitly. getTextarea(container).setSelectionRange(0, 0) act(() => { window.dispatchEvent( new MessageEvent("message", { data: { type: "insertTextIntoTextarea", text: "/command" } }), ) }) // A stale effect would still insert into the original "hello " value. expect(defaultProps.setInputValue).toHaveBeenCalledWith("/command updated ") }) it("posts the trimmed input on enhance and follows a re-rendered value", () => { const { rerender } = render() fireEvent.click(getEnhancePromptButton()) // Surrounding whitespace must not reach the extension. expect(mockPostMessage).toHaveBeenCalledWith({ type: "enhancePrompt", text: "Test prompt" }) rerender() fireEvent.click(getEnhancePromptButton()) // A stale handler would re-post the original "Test prompt" value. expect(mockPostMessage).toHaveBeenLastCalledWith({ type: "enhancePrompt", text: "updated" }) }) it("keeps whitespace-only input hidden from the send button and placeholder", () => { const getSendButton = (container: HTMLElement) => Array.from(container.querySelectorAll("button")).find((b) => b.querySelector(".lucide-send-horizontal")) const { container, rerender } = render() // Whitespace-only input has no sendable content, and the placeholder only // renders for a truly empty value. expect(getSendButton(container)).toHaveClass("opacity-0") expect(container.querySelector(".left-2.z-30")).toBeNull() // A stale content memo would keep the send button hidden for real text. rerender() expect(getSendButton(container)).toHaveClass("opacity-100") }) it("moves the cursor to the end of the mention on Backspace at the end of the input", () => { const { container } = render() const textarea = getTextarea(container) textarea.setSelectionRange(16, 16) fireEvent.mouseUp(textarea) fireEvent.keyDown(textarea, { key: "Backspace" }) // Nothing follows the trailing space, so the space is not deleted; the // cursor moves to the end of the mention instead. expect(textarea.selectionStart).toBe(15) expect(defaultProps.setInputValue).not.toHaveBeenCalled() }) it("does not intercept Backspace when a word follows the mention", () => { const { container } = render() const textarea = getTextarea(container) textarea.setSelectionRange(15, 15) fireEvent.mouseUp(textarea) fireEvent.keyDown(textarea, { key: "Backspace" }) // The mention is not at the end of the inspected prefix, so the // selection is untouched. expect(textarea.selectionStart).toBe(15) expect(defaultProps.setInputValue).not.toHaveBeenCalled() }) it("applies the pending cursor once the pasted value commits", () => { const { container, rerender } = render() const textarea = getTextarea(container) const pasteEvent = new window.Event("paste", { bubbles: true, cancelable: true }) Object.defineProperty(pasteEvent, "clipboardData", { value: { items: [], getData: () => "https://example.com" }, }) act(() => { textarea.dispatchEvent(pasteEvent) // Commit the value the paste handler produced so the pending cursor // (0 + 19 + 1 = 20) is applied against the full 26-char value. rerender() }) // A stale effect would never re-apply the intended cursor position. expect(defaultProps.setInputValue).toHaveBeenLastCalledWith("https://example.com visit ") expect(textarea.selectionStart).toBe(20) }) it("inserts a pasted URL at the cursor and tracks re-rendered input", () => { const { container, rerender } = render() const textarea = getTextarea(container) textarea.setSelectionRange(6, 6) fireEvent.mouseUp(textarea) const pasteEvent = new window.Event("paste", { bubbles: true, cancelable: true }) Object.defineProperty(pasteEvent, "clipboardData", { value: { items: [], getData: () => "https://example.com" }, }) act(() => { textarea.dispatchEvent(pasteEvent) }) // The URL splits "visit this" at the cursor instead of reusing the whole // value for the tail. expect(defaultProps.setInputValue).toHaveBeenLastCalledWith("visit https://example.com this") rerender() textarea.setSelectionRange(0, 0) fireEvent.mouseUp(textarea) act(() => { textarea.dispatchEvent(pasteEvent) }) // A stale paste handler would repeat the original "visit this" value. expect(defaultProps.setInputValue).toHaveBeenLastCalledWith("https://example.com changed ") }) it("re-highlights mentions after the input changes", () => { const { container, rerender } = render() rerender() // A stale highlight effect would keep the empty highlight from the // initial render. expect(container.querySelector('[data-testid="highlight-layer"]')?.innerHTML).toContain(" { const { container } = render() const textarea = getTextarea(container) textarea.setSelectionRange(3, 3) fireEvent.mouseUp(textarea) fireEvent.drop(container.querySelector(".chat-text-area")!, { dataTransfer: { getData: () => "/some/path", files: [] }, preventDefault: vi.fn(), }) // The remainder after the cursor ("def") is preserved. expect(defaultProps.setInputValue).toHaveBeenCalledWith("abc/some/path def") }) }) describe("idle condense reset signal", () => { const getTextarea = (container: HTMLElement) => { const textarea = container.querySelector("textarea") if (!textarea) { throw new Error("expected the chat textarea to be rendered") } return textarea } const idleSignals = () => mockPostMessage.mock.calls.filter(([message]) => message?.type === "idleCondenseReset") it("posts idleCondenseReset when the user types", () => { const { container } = render() const textarea = getTextarea(container) fireEvent.change(textarea, { target: { value: "h", selectionStart: 1 } }) expect(idleSignals()).toHaveLength(1) }) it("signals on every edit, including edits within the former throttle window", () => { const { container } = render() const textarea = getTextarea(container) fireEvent.change(textarea, { target: { value: "h", selectionStart: 1 } }) expect(idleSignals()).toHaveLength(1) // Every keystroke must restart the idle countdown. A keystroke // suppressed by the old one-second throttle could let condensing // start less than one idle window after the user last typed. fireEvent.change(textarea, { target: { value: "he", selectionStart: 2 } }) fireEvent.change(textarea, { target: { value: "hel", selectionStart: 3 } }) expect(idleSignals()).toHaveLength(3) }) it("posts idleCondenseReset when a URL paste rewrites the prompt", () => { // A URL paste preventDefaults the native paste and sets the input // programmatically, so no onChange fires; the mutation itself must // restart the armed idle countdown. const { container } = render() const textarea = getTextarea(container) const pasteEvent = new window.Event("paste", { bubbles: true, cancelable: true }) Object.defineProperty(pasteEvent, "clipboardData", { value: { items: [], getData: () => "https://example.com" }, }) act(() => { textarea.dispatchEvent(pasteEvent) }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("https://example.com visit ") expect(idleSignals()).toHaveLength(1) }) it("posts idleCondenseReset when a dropped path rewrites the prompt", () => { const { container } = render() const textarea = getTextarea(container) textarea.setSelectionRange(3, 3) fireEvent.mouseUp(textarea) fireEvent.drop(container.querySelector(".chat-text-area") as HTMLElement, { dataTransfer: { getData: () => "/some/path", files: [] }, preventDefault: vi.fn(), }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("abc/some/path def") expect(idleSignals()).toHaveLength(1) }) it("posts idleCondenseReset when history navigation recalls a prompt", () => { ;(useExtensionState as ReturnType).mockReturnValue({ filePaths: [], openedTabs: [], apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, taskHistory: [], clineMessages: [{ type: "say", say: "user_feedback", text: "First prompt", ts: 1000 }], cwd: "/test/workspace", }) const { container } = render() const textarea = getTextarea(container) textarea.setSelectionRange(0, 0) fireEvent.keyDown(textarea, { key: "ArrowUp" }) // Recalling a prompt replaces the input without an onChange event. expect(defaultProps.setInputValue).toHaveBeenCalledWith("First prompt") expect(idleSignals()).toHaveLength(1) }) it("posts idleCondenseReset when an enhanced prompt replaces the input", () => { // The enhancedPrompt response rewrites the input programmatically; // in jsdom there is no execCommand, so the setInputValue fallback // runs and never fires the textarea onChange. The handler must // signal unconditionally. Pin execCommand absent because an earlier // test mocks it and the mock persists on the document. Object.defineProperty(document, "execCommand", { value: undefined, writable: true }) const { container } = render() const textarea = getTextarea(container) // The typing signal proves the baseline before the enhancement lands. fireEvent.change(textarea, { target: { value: "write unit tests", selectionStart: 16 } }) expect(idleSignals()).toHaveLength(1) act(() => { window.dispatchEvent( new MessageEvent("message", { data: { type: "enhancedPrompt", text: "improved prompt" } }), ) }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("improved prompt") expect(idleSignals()).toHaveLength(2) }) it("posts idleCondenseReset when a command is selected from the context menu", () => { const { container } = render() const textarea = getTextarea(container) // Typing "/" opens the slash-command context menu and signals once. fireEvent.change(textarea, { target: { value: "/", selectionStart: 1 } }) expect(contextMenuHarness.onSelect).toBeDefined() // Selecting a command rewrites the input programmatically (no // onChange), so the selection itself must restart the countdown. act(() => { contextMenuHarness.onSelect!(ContextMenuOptionType.Command, "test-command") }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("/test-command ") expect(idleSignals()).toHaveLength(2) }) it("posts idleCondenseReset when a mode is selected from the context menu", () => { const { container } = render() const textarea = getTextarea(container) fireEvent.change(textarea, { target: { value: "/", selectionStart: 1 } }) expect(idleSignals()).toHaveLength(1) act(() => { contextMenuHarness.onSelect!(ContextMenuOptionType.Mode, "architect") }) // A mode selection clears the input and switches modes without an // onChange event. expect(defaultProps.setMode).toHaveBeenCalledWith("architect") expect(idleSignals()).toHaveLength(2) }) it("posts idleCondenseReset when a mention is inserted from the context menu", () => { const { container } = render() const textarea = getTextarea(container) // Typing "@" opens the mention context menu and signals once. fireEvent.change(textarea, { target: { value: "@", selectionStart: 1 } }) expect(contextMenuHarness.onSelect).toBeDefined() act(() => { contextMenuHarness.onSelect!(ContextMenuOptionType.Problems) }) // The generic insertMention path rewrites the input programmatically. expect(defaultProps.setInputValue).toHaveBeenCalled() expect(idleSignals()).toHaveLength(2) }) it("posts idleCondenseReset when a slash command inserts text into the input", () => { // The insertTextIntoTextarea message rewrites the input // programmatically (no onChange), so the handler itself must // restart the armed idle countdown. render() act(() => { window.dispatchEvent( new MessageEvent("message", { data: { type: "insertTextIntoTextarea", text: "/command" } }), ) }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("/command hello ") expect(idleSignals()).toHaveLength(1) }) it("posts idleCondenseReset when Backspace programmatically removes a mention", () => { const { container } = render() const textarea = getTextarea(container) // Position the cursor after the trailing space and tell the component about it. textarea.setSelectionRange(16, 16) fireEvent.mouseUp(textarea) // First Backspace: drops the space after the mention and arms the // pending flag without rewriting the input, so no signal yet. fireEvent.keyDown(textarea, { key: "Backspace" }) expect(idleSignals()).toHaveLength(0) // Second Backspace: removes the mention itself via setInputValue, // a programmatic rewrite that never fires the textarea onChange. fireEvent.keyDown(textarea, { key: "Backspace" }) expect(defaultProps.setInputValue).toHaveBeenCalledWith("hello ") expect(idleSignals()).toHaveLength(1) }) }) })