import { describe, it, expect, vi, beforeEach } from 'vitest' import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { MemoryRouter } from 'react-router-dom' import type { PermissionRequest, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode' import { ToolCallPart } from './ToolCallPart' import { useUserBash } from '@/stores/userBashStore' import { useSessionStatus } from '@/stores/sessionStatusStore' const mocks = vi.hoisted(() => ({ useSettings: vi.fn(), useToolCallPermission: vi.fn(), })) vi.mock('@/hooks/useSettings', () => ({ useSettings: mocks.useSettings, })) vi.mock('@/contexts/EventContext', () => ({ useToolCallPermission: mocks.useToolCallPermission, })) vi.mock('@/api/opencode', async (importOriginal) => ({ ...(await importOriginal()), getSession: () => new Promise(() => {}), listShells: () => Promise.resolve([]), })) const renderWithProviders = (ui: React.ReactElement, queryClient = new QueryClient()) => { return render( {ui} , ) } const runningShell = (): SessionMessageAssistantTool => ({ type: 'tool', id: 'call_1', name: 'shell', time: { created: 1, ran: 2 }, state: { status: 'running', input: { command: 'git status' }, metadata: {} }, }) const permissionFor = (source: PermissionRequest['source']): PermissionRequest => ({ id: 'permission_1', sessionID: 'ses_1', action: 'shell', resources: ['git status'], source, }) describe('ToolCallPart permission indicator', () => { beforeEach(() => { vi.clearAllMocks() mocks.useSettings.mockReturnValue({ preferences: { expandToolCalls: true }, isLoading: false, updateSettings: vi.fn(), isUpdating: false, }) mocks.useToolCallPermission.mockReturnValue(null) }) it('shows the waiting permission state for a matching tool call', () => { mocks.useToolCallPermission.mockReturnValue( permissionFor({ type: 'tool', messageID: 'msg_1', id: 'call_1' }), ) renderWithProviders() expect(mocks.useToolCallPermission).toHaveBeenCalledWith('call_1', 'msg_1') expect(screen.getByText('awaiting permission')).toBeInTheDocument() expect(screen.getByText('Waiting for permission...')).toBeInTheDocument() }) it('does not show the waiting permission state without a pending permission', () => { renderWithProviders() expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument() expect(screen.queryByText('Waiting for permission...')).not.toBeInTheDocument() expect(screen.getByText('running')).toBeInTheDocument() }) it('ignores a permission whose source belongs to another tool call or message', () => { mocks.useToolCallPermission.mockReturnValue(null) renderWithProviders() expect(mocks.useToolCallPermission).toHaveBeenCalledWith('call_1', 'msg_1') expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument() }) it('does not show the waiting permission state while the tool call is still streaming', () => { mocks.useToolCallPermission.mockReturnValue( permissionFor({ type: 'tool', messageID: 'msg_1', id: 'call_1' }), ) renderWithProviders( , ) expect(screen.queryByText('awaiting permission')).not.toBeInTheDocument() }) }) describe('ToolCallPart background indicator', () => { beforeEach(() => { vi.clearAllMocks() mocks.useSettings.mockReturnValue({ preferences: { expandToolCalls: false }, isLoading: false, updateSettings: vi.fn(), isUpdating: false, }) mocks.useToolCallPermission.mockReturnValue(null) useUserBash.setState({ userBashCommands: new Map() }) useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), revision: 0, }) }) const completedShell = (metadata: Record): SessionMessageAssistantTool => ({ type: 'tool', id: 'call_2', name: 'shell', time: { created: 1, ran: 2, completed: 3 }, state: { status: 'completed', input: { command: 'npm run dev' }, content: [{ type: 'text', text: 'Command moved to the background (shell ID: sh_1).' }], metadata, }, }) const completedSubagent = (metadata: Record): SessionMessageAssistantTool => ({ type: 'tool', id: 'call_3', name: 'subagent', time: { created: 1, ran: 2, completed: 3 }, state: { status: 'completed', input: { description: 'Explore' }, content: [{ type: 'text', text: 'Task moved to the background (session ID: ses_child).' }], metadata, }, }) it('marks a shell call that returned while its command keeps running', () => { renderWithProviders() expect(screen.getByText('background')).toBeInTheDocument() }) it('does not mark a shell call that finished normally', () => { renderWithProviders() expect(screen.queryByText('background')).not.toBeInTheDocument() }) it('marks a backgrounded user-bash command with a background indicator', () => { useUserBash.setState({ userBashCommands: new Map([['npm run dev', Date.now()]]) }) renderWithProviders() expect(screen.getByText('background')).toBeInTheDocument() expect(screen.queryByText('✓')).not.toBeInTheDocument() }) it('clears the background badge once the live shell completes', async () => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) queryClient.setQueryData(['opencode', 'shells', '/repo'], [ { id: 'sh_1', status: 'exited', exit: 0, command: 'npm run dev', cwd: '/repo', shell: 'zsh', file: '/tmp/sh_1.log', metadata: { sessionID: 'ses_1' }, time: { started: 1, completed: 2 }, }, ]) renderWithProviders( , queryClient, ) await waitFor(() => expect(screen.queryByText('background')).not.toBeInTheDocument()) expect(screen.getByText('completed')).toBeInTheDocument() }) it('shows a background shell missing from a loaded list as a non-spinning unavailable icon', async () => { const { container } = renderWithProviders( , ) await waitFor(() => expect(screen.getByText('unavailable')).toBeInTheDocument()) expect(screen.queryByText('background')).not.toBeInTheDocument() expect(container.querySelector('.animate-spin')).toBeNull() }) it('completes a background shell missing from the list from its notice', async () => { const { container } = renderWithProviders( , ) await waitFor(() => expect(screen.getByText('completed')).toBeInTheDocument()) expect(screen.queryByText('background')).not.toBeInTheDocument() expect(container.querySelector('.animate-spin')).toBeNull() }) it('fails a background shell missing from the list from its notice', async () => { renderWithProviders( , ) await waitFor(() => expect(screen.getByText('failed')).toBeInTheDocument()) expect(screen.queryByText('background')).not.toBeInTheDocument() }) it('treats an unknown child session as running, not finished', () => { renderWithProviders( , ) expect(screen.getByText('background')).toBeInTheDocument() expect(screen.queryByText('✓')).not.toBeInTheDocument() }) it('completes a backgrounded subagent when the child session is known idle', async () => { act(() => { useSessionStatus.getState().setStatus('child-1', { type: 'idle' }) }) renderWithProviders( , ) await waitFor(() => expect(screen.getByText('✓')).toBeInTheDocument()) expect(screen.queryByText('background')).not.toBeInTheDocument() }) }) describe('ToolCallPart open walkthrough action', () => { beforeEach(() => { vi.clearAllMocks() mocks.useSettings.mockReturnValue({ preferences: { expandToolCalls: false }, isLoading: false, updateSettings: vi.fn(), isUpdating: false, }) mocks.useToolCallPermission.mockReturnValue(null) }) const openWalkthrough = (status: 'running' | 'completed'): SessionMessageAssistantTool => ({ type: 'tool', id: 'call_ocm', name: 'ocm', time: status === 'completed' ? { created: 1, ran: 2, completed: 3 } : { created: 1, ran: 2 }, state: status === 'completed' ? { status: 'completed', input: { action: 'open_walkthrough', params: {} }, content: [{ type: 'text', text: 'Walkthrough opened' }], } : { status: 'running', input: { action: 'open_walkthrough', params: {} }, metadata: {}, }, }) it('renders an Open walkthrough button and calls the opener', () => { const onOpenWalkthrough = vi.fn() renderWithProviders( , ) fireEvent.click(screen.getByRole('button', { name: 'Open walkthrough' })) expect(onOpenWalkthrough).toHaveBeenCalledTimes(1) }) it('passes the requested source to the opener', () => { const onOpenWalkthrough = vi.fn() const part: SessionMessageAssistantTool = { type: 'tool', id: 'call_ocm', name: 'ocm', time: { created: 1, ran: 2, completed: 3 }, state: { status: 'completed', input: { action: 'open_walkthrough', params: { source: { kind: 'staged' } } }, content: [{ type: 'text', text: 'Walkthrough opened' }], }, } renderWithProviders( , ) fireEvent.click(screen.getByRole('button', { name: 'Open walkthrough' })) expect(onOpenWalkthrough).toHaveBeenCalledWith({ kind: 'staged' }) }) it('passes no source when the call invalidates one', () => { const onOpenWalkthrough = vi.fn() const part: SessionMessageAssistantTool = { type: 'tool', id: 'call_ocm', name: 'ocm', time: { created: 1, ran: 2, completed: 3 }, state: { status: 'completed', input: { action: 'open_walkthrough', params: { source: { kind: 'nonsense' } } }, content: [{ type: 'text', text: 'Walkthrough opened' }], }, } renderWithProviders( , ) fireEvent.click(screen.getByRole('button', { name: 'Open walkthrough' })) expect(onOpenWalkthrough).toHaveBeenCalledWith(undefined) }) it('does not render the button while the call is still running', () => { renderWithProviders( , ) expect(screen.queryByRole('button', { name: 'Open walkthrough' })).not.toBeInTheDocument() }) it('does not render the button for another ocm action', () => { const otherAction: SessionMessageAssistantTool = { type: 'tool', id: 'call_ocm', name: 'ocm', time: { created: 1, ran: 2, completed: 3 }, state: { status: 'completed', input: { action: 'something_else' }, content: [{ type: 'text', text: 'ok' }], }, } renderWithProviders() expect(screen.queryByRole('button', { name: 'Open walkthrough' })).not.toBeInTheDocument() }) })