import { createRef } from 'react' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { render, screen, fireEvent, act, waitFor } from '@testing-library/react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { PromptInput, type PromptInputHandle } from './PromptInput' import { useComposerDraftStore } from '@/stores/composerDraftStore' import { BUILTIN_COMMANDS } from '@/lib/builtinCommands' import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils' const mocks = vi.hoisted(() => ({ runCommand: vi.fn(), switchSessionModel: vi.fn(), switchSessionAgent: vi.fn(), agents: [] as Array<{ id: string; name: string; description?: string; mode?: string; hidden?: boolean }>, skills: [] as Array<{ id: string; name: string; description?: string }>, setAgent: vi.fn(), cycleVariant: vi.fn(), showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn(), promise: vi.fn(), dismiss: vi.fn(), }, useSTT: vi.fn(), useVoiceConversation: vi.fn(), useMobile: vi.fn(), useCommands: vi.fn(), useFileSearch: vi.fn(), useModelSelection: vi.fn(), useVariants: vi.fn(), useSessionAgent: vi.fn(), useUserBash: vi.fn(), useSessionAgentStore: vi.fn(), useSendErrorStore: vi.fn(), useHasBackgroundActivity: vi.fn(), })) const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0 })) vi.mock('@/api/opencode', async () => { const actual = await vi.importActual('@/api/opencode') return { ...actual, runCommand: mocks.runCommand, switchSessionModel: mocks.switchSessionModel, switchSessionAgent: mocks.switchSessionAgent, } }) vi.mock('@/hooks/useOpenCode', async () => { const actual = await vi.importActual('@/hooks/useOpenCode') return { ...actual, useAgents: () => ({ data: mocks.agents }), useSkills: () => ({ data: mocks.skills }), useSession: () => ({ data: undefined }), } }) vi.mock('@/hooks/useSTT', () => ({ useSTT: mocks.useSTT, useSttAvailability: () => ({ isEnabled: true, isSupported: true }), })) vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation })) vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile })) vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands })) vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch })) vi.mock('@/hooks/useModelSelection', () => ({ useModelSelection: mocks.useModelSelection })) vi.mock('@/hooks/useVariants', () => ({ useVariants: mocks.useVariants })) vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAgent })) vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash })) vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore })) vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore })) vi.mock('@/stores/sessionStatusStore', async (importOriginal) => { const actual = await importOriginal() return { ...actual, useHasBackgroundActivity: mocks.useHasBackgroundActivity } }) vi.mock('@/lib/toast', () => ({ showToast: mocks.showToast })) vi.mock('@/contexts/EventContext', () => ({ usePermissions: () => ({ hasForSession: vi.fn().mockReturnValue(false), setShowDialog: vi.fn(), }), })) vi.mock('@/components/agent/AgentQuickSelect', () => ({ AgentQuickSelect: ({ children }: { children: React.ReactNode }) =>
{children}
, })) vi.mock('@/components/model/ModelQuickSelect', () => ({ ModelQuickSelect: ({ children, open }: { children?: React.ReactNode; open?: boolean }) => (
{children}
), })) vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: () => null, })) vi.mock('@/hooks/useSessionGoals', () => ({ useSessionGoal: () => ({ data: undefined }), useSessionGoalCommand: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }), })) vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: () => ({ data: undefined }), })) vi.mock('./ComposerToolsMenu', () => ({ ComposerToolsMenu: () => null, })) vi.mock('@/components/session/SessionSandboxMenu', () => ({ SessionSandboxMenu: () => null, })) vi.mock('./PromptSuggestions', () => ({ PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => { if (props.isOpen) { suggestionProps.isOpen = true suggestionProps.selectedIndex = props.selectedIndex } return null }, })) const createTestQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false }, }, }) const sessionInfo = (overrides: Record = {}) => ({ id: 'test-session', projectID: 'proj_1', time: { created: 1000, updated: 1000 }, location: { directory: '/test' }, agent: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' }, ...overrides, }) describe('PromptInput command submission', () => { const defaultProps = { directory: '/test', sessionID: 'test-session', isSessionActive: false, isStreamingResponse: false, onScrollToBottom: vi.fn(), commandActions: createCommandActionsMock(), onPromptChange: vi.fn(), } const renderComponent = () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo()) return render( ) } const attachImage = async (container: HTMLElement) => { const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement const image = new File(['img'], 'pic.png', { type: 'image/png' }) fireEvent.change(fileInput, { target: { files: [image] } }) await screen.findByText('pic.png') } beforeEach(() => { vi.clearAllMocks() useComposerDraftStore.setState({ drafts: {} }) mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock()) mocks.runCommand.mockResolvedValue(undefined) mocks.switchSessionModel.mockResolvedValue(undefined) mocks.switchSessionAgent.mockResolvedValue(undefined) mocks.agents = [{ id: 'reviewer', name: 'reviewer', description: 'Reviewer', mode: 'primary' }] mocks.useMobile.mockReturnValue(false) mocks.useSTT.mockReturnValue({ isRecording: false, isProcessing: false, isSupported: false, isEnabled: false, interimTranscript: '', transcript: '', startRecording: vi.fn(), stopRecording: vi.fn(), abortRecording: vi.fn(), reset: vi.fn(), clear: vi.fn(), }) mocks.useCommands.mockReturnValue({ searchCommands: () => [], findCommand: (name: string) => { if (name === 'review') return { name: 'review', description: 'Review' } return BUILTIN_COMMANDS.find((command) => command.name === name) }, recentNames: [], }) mocks.useFileSearch.mockReturnValue({ files: [] }) mocks.useModelSelection.mockReturnValue({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' }, modelString: 'anthropic/claude-sonnet-4', setModel: vi.fn(), setActiveAgent: vi.fn(), recentModels: [], favoriteModels: [], toggleFavorite: vi.fn(), isModelReady: true, }) mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant }) mocks.useSessionAgent.mockReturnValue({ agent: 'build' }) mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() })) mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: mocks.setAgent })) mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} })) mocks.useHasBackgroundActivity.mockReturnValue(false) suggestionProps.isOpen = false suggestionProps.selectedIndex = 0 }) afterEach(() => { Reflect.deleteProperty(window, 'matchMedia') }) it('focuses the prompt on open with a fine pointer', async () => { stubMatchMedia(true) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') expect(input).toHaveFocus() }) it('does not focus the prompt on open on touch devices', async () => { stubMatchMedia(false) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') expect(input).not.toHaveFocus() }) it('does not take focus from an element that already has it', async () => { stubMatchMedia(true) const other = document.createElement('button') document.body.appendChild(other) other.focus() renderComponent() await screen.findByPlaceholderText('Send a message...') expect(other).toHaveFocus() other.remove() }) it('announces session activity changes to screen readers', async () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo()) const buildPrompt = (props: { isSessionActive?: boolean }) => ( ) const { rerender } = render(buildPrompt({})) await screen.findByPlaceholderText('Send a message...') expect(screen.getByRole('status').textContent).toBe('') rerender(buildPrompt({ isSessionActive: true })) expect(screen.getByRole('status')).toHaveTextContent('Session working') mocks.useHasBackgroundActivity.mockReturnValue(true) rerender(buildPrompt({})) expect(screen.getByRole('status')).toHaveTextContent('Background tasks running') }) it('keeps the model picker visible while the session is active', async () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo()) const buildPrompt = (props: { isSessionActive?: boolean }) => ( ) const { rerender } = render(buildPrompt({})) await screen.findByPlaceholderText('Send a message...') expect(screen.getByTestId('model-quick-select').querySelector('button')).not.toBeNull() rerender(buildPrompt({ isSessionActive: true })) expect(screen.getByTestId('model-quick-select').querySelector('button')).not.toBeNull() }) it('disables submit and does not run a command while the model is not ready', async () => { mocks.useModelSelection.mockReturnValue({ model: null, modelString: null, setModel: vi.fn(), setActiveAgent: vi.fn(), recentModels: [], favoriteModels: [], toggleFavorite: vi.fn(), isModelReady: false, }) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/review' } }) const sendButton = screen.getByTitle('Send') expect(sendButton).toBeDisabled() fireEvent.click(sendButton) expect(mocks.runCommand).not.toHaveBeenCalled() }) it('sends parsed command attachments and offsets to runCommand without injecting the selected agent', async () => { mocks.useFileSearch.mockReturnValue({ files: ['src/App.tsx'] }) const { container } = renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '@App' } }) await waitFor(() => expect(suggestionProps.isOpen).toBe(true)) fireEvent.keyDown(input, { key: 'Enter' }) await waitFor(() => expect(input).toHaveValue('@App.tsx ')) await attachImage(container) fireEvent.change(input, { target: { value: '/review @App.tsx @reviewer' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled()) const call = mocks.runCommand.mock.calls[0][0] as { sessionID: string name: string text: string files: Array<{ uri: string; name?: string; mention?: { start: number; end: number; text: string } }> agents: Array<{ name: string; mention?: { start: number; end: number; text: string } }> skills: unknown[] } expect(call.sessionID).toBe('test-session') expect(call.name).toBe('review') expect(call.text).toBe('@App.tsx @reviewer') expect(call.files).toEqual(expect.arrayContaining([ { uri: 'file:///test/src/App.tsx', name: 'App.tsx', mention: { start: 0, end: 8, text: '@App.tsx' } }, expect.objectContaining({ name: 'pic.png', uri: expect.stringMatching(/^data:image\/png/) }), ])) expect(call.agents).toEqual([ { name: 'reviewer', mention: { start: 9, end: 18, text: '@reviewer' } }, ]) expect(call.skills).toEqual([]) }) it('runs a command whose arguments span multiple lines', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/review first line\nsecond line' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled()) expect(mocks.runCommand.mock.calls[0][0]).toMatchObject({ name: 'review', text: 'first line\nsecond line', }) }) it('submits on plain Enter when the prompt is a known command', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/btw first line\nsecond line' } }) fireEvent.keyDown(input, { key: 'Enter' }) await waitFor(() => expect(defaultProps.commandActions.askSideQuestion).toHaveBeenCalledWith('first line\nsecond line')) }) it('does not submit a known command on Shift+Enter', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/btw hi' } }) fireEvent.keyDown(input, { key: 'Enter', shiftKey: true }) expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled() expect(input).toHaveValue('/btw hi') }) it.each(['hello there', '/bt hi', '/unknown hi'])('does not submit %j on plain Enter', async (value) => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value } }) fireEvent.keyDown(input, { key: 'Enter' }) expect(input).toHaveValue(value) expect(mocks.runCommand).not.toHaveBeenCalled() expect(defaultProps.commandActions.askSideQuestion).not.toHaveBeenCalled() }) it('preserves the submitted command text when the command submission fails', async () => { mocks.runCommand.mockRejectedValueOnce(new Error('command failed')) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/review' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.runCommand).toHaveBeenCalled()) expect(input).toHaveValue('/review') }) it('switches to the next primary agent for /agent without invoking runCommand', async () => { mocks.agents = [ { id: 'build', name: 'build', mode: 'primary' }, { id: 'plan', name: 'plan', mode: 'primary' }, ] renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/agent' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.setAgent).toHaveBeenCalledWith('test-session', 'plan')) expect(mocks.runCommand).not.toHaveBeenCalled() }) it('reports when /variants is used with a model that has no variants', async () => { mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant }) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/variants' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.showToast.info).toHaveBeenCalledWith('The selected model has no variants')) expect(mocks.cycleVariant).not.toHaveBeenCalled() }) it('cycles variants for /variants when the model has them', async () => { mocks.useVariants.mockReturnValue({ hasVariants: true, currentVariant: 'high', cycleVariant: mocks.cycleVariant }) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/variants' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.cycleVariant).toHaveBeenCalled()) expect(mocks.showToast.info).not.toHaveBeenCalled() }) it('opens the model picker through the imperative handle while the session is active', () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo()) const ref = createRef() render( ) expect(screen.getByTestId('model-quick-select')).toHaveAttribute('data-open', 'false') act(() => { ref.current?.openModelPicker() }) expect(screen.getByTestId('model-quick-select')).toHaveAttribute('data-open', 'true') }) it('resets bash mode through the imperative clearPrompt', async () => { const queryClient = createTestQueryClient() queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo()) const ref = createRef() render( ) const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '!' } }) expect(input).toHaveValue('!') expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH') act(() => { ref.current?.clearPrompt() }) expect(input).toHaveValue('') expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument() }) it('exits bash mode on Escape while idle and keeps the attachments', async () => { const { container } = renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '!' } }) expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH') await attachImage(container) expect(screen.getByText('pic.png')).toBeInTheDocument() fireEvent.keyDown(input, { key: 'Escape' }) expect(input).toHaveValue('') expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument() expect(screen.getByText('pic.png')).toBeInTheDocument() }) it('keeps attachments and clears only the text when a built-in command is submitted', async () => { const { container } = renderComponent() const input = await screen.findByPlaceholderText('Send a message...') await attachImage(container) fireEvent.change(input, { target: { value: '/btw hi' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(mocks.showToast.info).toHaveBeenCalledWith('Built-in commands do not use attachments; they were kept')) expect(input).toHaveValue('') expect(screen.getByText('pic.png')).toBeInTheDocument() }) it('clears the prompt for a built-in command without attachments', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/btw hi' } }) fireEvent.click(screen.getByTitle('Send')) await waitFor(() => expect(input).toHaveValue('')) expect(mocks.showToast.info).not.toHaveBeenCalled() }) const commandSuggestions = () => ({ searchCommands: () => [ { item: { name: 'alpha', description: 'Alpha' }, ranges: [] }, { item: { name: 'beta', description: 'Beta' }, ranges: [] }, { item: { name: 'gamma', description: 'Gamma' }, ranges: [] }, ], findCommand: () => undefined, recentNames: [], }) it('moves the command selection in the visual direction of the arrow on mobile', async () => { mocks.useMobile.mockReturnValue(true) mocks.useCommands.mockReturnValue(commandSuggestions()) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/', selectionStart: 1 } }) await waitFor(() => expect(suggestionProps.isOpen).toBe(true)) expect(suggestionProps.selectedIndex).toBe(0) fireEvent.keyDown(input, { key: 'ArrowUp' }) await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1)) fireEvent.keyDown(input, { key: 'ArrowDown' }) await waitFor(() => expect(suggestionProps.selectedIndex).toBe(0)) }) it('keeps the desktop command arrow direction unchanged', async () => { mocks.useCommands.mockReturnValue(commandSuggestions()) renderComponent() const input = await screen.findByPlaceholderText('Send a message...') fireEvent.change(input, { target: { value: '/', selectionStart: 1 } }) await waitFor(() => expect(suggestionProps.isOpen).toBe(true)) expect(suggestionProps.selectedIndex).toBe(0) fireEvent.keyDown(input, { key: 'ArrowDown' }) await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1)) fireEvent.keyDown(input, { key: 'ArrowUp' }) await waitFor(() => expect(suggestionProps.selectedIndex).toBe(0)) }) it('keeps the composer frame out of a compositing layer so the iOS caret stays aligned', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') const frame = input.closest('.isolate') as HTMLElement const tokens = frame.className.split(/\s+/) expect(tokens).not.toContain('transition-all') expect(tokens.some((token) => token.startsWith('backdrop-blur'))).toBe(false) expect(tokens.some((token) => token.startsWith('opacity-'))).toBe(false) expect(tokens).toContain('before:backdrop-blur-md') }) describe('mobile keybar', () => { beforeEach(() => { mocks.useMobile.mockReturnValue(true) }) it('shows only while the prompt is focused on mobile', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') expect(screen.queryByRole('toolbar', { name: 'Insert' })).not.toBeInTheDocument() fireEvent.focus(input) expect(screen.getByRole('toolbar', { name: 'Insert' })).toBeInTheDocument() }) it('is not shown on desktop', async () => { mocks.useMobile.mockReturnValue(false) renderComponent() fireEvent.focus(await screen.findByPlaceholderText('Send a message...')) expect(screen.queryByRole('toolbar', { name: 'Insert' })).not.toBeInTheDocument() }) it('inserts a separated trigger at the cursor', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') as HTMLTextAreaElement fireEvent.change(input, { target: { value: 'hello world' } }) fireEvent.focus(input) input.setSelectionRange(5, 5) fireEvent.click(screen.getByRole('button', { name: 'mention @' })) expect(input).toHaveValue('hello @ world') fireEvent.change(input, { target: { value: 'hello' } }) input.setSelectionRange(5, 5) fireEvent.click(screen.getByRole('button', { name: 'cmd /' })) expect(input).toHaveValue('hello /') }) it('enables bash only for an empty prompt and toggles bash mode', async () => { renderComponent() const input = await screen.findByPlaceholderText('Send a message...') expect(input).toHaveAttribute('autocomplete', 'off') expect(input).toHaveAttribute('autocorrect', 'off') expect(input).toHaveAttribute('autocapitalize', 'off') expect(input).toHaveAttribute('spellcheck', 'false') fireEvent.focus(input) fireEvent.change(input, { target: { value: 'text' } }) expect(screen.getByRole('button', { name: 'bash !' })).toBeDisabled() fireEvent.change(input, { target: { value: '' } }) const bashKey = screen.getByRole('button', { name: 'bash !' }) expect(bashKey).toBeEnabled() fireEvent.click(bashKey) expect(input).toHaveValue('!') expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH') expect(screen.getByRole('button', { name: 'cmd /' })).toBeDisabled() expect(input).toHaveAttribute('autocorrect', 'off') expect(input).toHaveAttribute('autocapitalize', 'off') expect(input).toHaveAttribute('spellcheck', 'false') fireEvent.click(screen.getByRole('button', { name: 'bash !' })) expect(input).toHaveValue('') expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument() }) }) })