diff --git a/frontend/src/components/navigation/ToolSidePanel.test.tsx b/frontend/src/components/navigation/ToolSidePanel.test.tsx index 32ec9584..221c86ac 100644 --- a/frontend/src/components/navigation/ToolSidePanel.test.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.test.tsx @@ -33,7 +33,12 @@ vi.mock('@/components/source-control/RemoteSourceControlContent', () => ({ ), })) vi.mock('@/components/terminal/TerminalPanel', () => ({ - TerminalWorkspace: () =>
terminal-tool
, + TerminalWorkspace: ({ onLastTerminalExited }: { onLastTerminalExited?: () => void }) => ( +
+ terminal-tool + +
+ ), })) vi.mock('@/components/preview/PreviewPanel', () => ({ PreviewWorkspace: () =>
preview-tool
})) vi.mock('@/components/schedules/RepoSchedulesContent', () => ({ @@ -322,6 +327,16 @@ describe('ToolSidePanel', () => { expect(search().has('terminal')).toBe(false) }) + it('closes the docked terminal panel when the last terminal exits', async () => { + const user = userEvent.setup() + renderAt('?panel=terminal&terminal=pty-1') + + await user.click(await screen.findByRole('button', { name: 'Exit last terminal' })) + + await waitFor(() => expect(search().has('panel')).toBe(false)) + expect(search().has('terminal')).toBe(false) + }) + it('falls back to the dialog when not docked', async () => { renderAt('?panel=sourceControl', false) diff --git a/frontend/src/components/navigation/ToolSidePanel.tsx b/frontend/src/components/navigation/ToolSidePanel.tsx index 13bd9ba4..930571d4 100644 --- a/frontend/src/components/navigation/ToolSidePanel.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.tsx @@ -211,7 +211,7 @@ export function ToolSidePanel({ if (tool === 'activity') return if (tool === 'terminal') { return terminalWorkspaceTarget - ? + ? : null } if (tool === 'skills') { diff --git a/frontend/src/components/terminal/TerminalPanel.test.tsx b/frontend/src/components/terminal/TerminalPanel.test.tsx index 962ab58a..b226c96b 100644 --- a/frontend/src/components/terminal/TerminalPanel.test.tsx +++ b/frontend/src/components/terminal/TerminalPanel.test.tsx @@ -22,15 +22,23 @@ vi.mock('./TerminalView', async () => { const React = await import('react') return { TerminalView: React.forwardRef(function MockTerminalView( - props: { ptyID: string; active: boolean }, + props: { ptyID: string; active: boolean; onExited: () => void }, ref: React.Ref, ) { React.useImperativeHandle(ref, () => ({ send: vi.fn() })) - return React.createElement('div', { - 'data-testid': 'terminal-view', - 'data-pty-id': props.ptyID, - 'data-active': String(props.active), - }) + return React.createElement( + 'div', + { + 'data-testid': 'terminal-view', + 'data-pty-id': props.ptyID, + 'data-active': String(props.active), + }, + React.createElement( + 'button', + { type: 'button', 'aria-label': `exit ${props.ptyID}`, onClick: props.onExited }, + 'exit', + ), + ) }), } }) @@ -88,6 +96,10 @@ function renderPanel(initialEntry = '/repos/1?dialog=terminal', onClose = vi.fn( describe('TerminalPanel', () => { beforeEach(() => { vi.clearAllMocks() + createMutate.mockReset() + removeMutate.mockReset() + refetch.mockReset() + refetch.mockResolvedValue({ data: [] }) vi.mocked(useMobile).mockReturnValue(false) mockTerminalHooks([]) }) @@ -267,6 +279,73 @@ describe('TerminalPanel', () => { expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object)) }) + it('removes a cleanly exited terminal, closes the panel when it was the last, and does not respawn', async () => { + mockTerminalHooks([runningTerminal]) + refetch.mockResolvedValue({ data: [{ ...runningTerminal, status: 'exited', exitCode: 0 }] }) + removeMutate.mockImplementation((_variables: unknown, options: { onSuccess?: () => void }) => { + options.onSuccess?.() + }) + const onClose = vi.fn() + renderPanel('/repos/1?dialog=terminal&terminal=t1', onClose) + await screen.findAllByTestId('terminal-view') + + fireEvent.click(screen.getByLabelText('exit t1')) + + await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)) + expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object)) + expect(screen.queryByLabelText('Close Terminal')).not.toBeInTheDocument() + expect(createMutate).not.toHaveBeenCalled() + }) + + it('keeps a terminal that exited with a non-zero code so the failure stays inspectable', async () => { + mockTerminalHooks([runningTerminal]) + refetch.mockResolvedValue({ data: [{ ...runningTerminal, status: 'exited', exitCode: 2 }] }) + const onClose = vi.fn() + const { rerender } = renderPanel('/repos/1?dialog=terminal&terminal=t1', onClose) + await screen.findAllByTestId('terminal-view') + + fireEvent.click(screen.getByLabelText('exit t1')) + + await waitFor(() => expect(refetch).toHaveBeenCalledTimes(1)) + expect(removeMutate).not.toHaveBeenCalled() + expect(onClose).not.toHaveBeenCalled() + expect(screen.getByLabelText('Close Terminal')).toBeInTheDocument() + + mockTerminalHooks([{ ...runningTerminal, status: 'exited', exitCode: 2 }]) + rerender( + + + , + ) + + expect(await screen.findByText('exited (2)')).toBeInTheDocument() + }) + + it('keeps the panel open and selects another running terminal when one exits cleanly', async () => { + const otherTerminal: TerminalInfo = { ...runningTerminal, id: 't3', title: 'Shell' } + mockTerminalHooks([runningTerminal, otherTerminal]) + refetch.mockResolvedValue({ + data: [runningTerminal, { ...otherTerminal, status: 'exited', exitCode: 0 }], + }) + removeMutate.mockImplementation((_variables: unknown, options: { onSuccess?: () => void }) => { + options.onSuccess?.() + }) + const onClose = vi.fn() + renderPanel('/repos/1?dialog=terminal&terminal=t3', onClose) + + const views = await screen.findAllByTestId('terminal-view') + expect(views.find((view) => view.getAttribute('data-pty-id') === 't3')).toHaveAttribute('data-active', 'true') + + fireEvent.click(screen.getByLabelText('exit t3')) + + await waitFor(() => expect(screen.queryByLabelText('Close Shell')).not.toBeInTheDocument()) + expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't3', directory: '/repo' }, expect.any(Object)) + expect(onClose).not.toHaveBeenCalled() + expect(screen.getByTestId('terminal-view')).toHaveAttribute('data-pty-id', 't1') + expect(screen.getByTestId('terminal-view')).toHaveAttribute('data-active', 'true') + expect(createMutate).not.toHaveBeenCalled() + }) + it('renders the key bar only on mobile', async () => { mockTerminalHooks([runningTerminal]) diff --git a/frontend/src/components/terminal/TerminalPanel.tsx b/frontend/src/components/terminal/TerminalPanel.tsx index d1a3fef8..00dbcc15 100644 --- a/frontend/src/components/terminal/TerminalPanel.tsx +++ b/frontend/src/components/terminal/TerminalPanel.tsx @@ -29,9 +29,10 @@ interface TerminalWorkspaceProps { target: TerminalTarget directory: string | undefined isOpen: boolean + onLastTerminalExited?: () => void } -export function TerminalWorkspace({ target, directory, isOpen }: TerminalWorkspaceProps) { +export function TerminalWorkspace({ target, directory, isOpen, onLastTerminalExited }: TerminalWorkspaceProps) { const isMobile = useMobile() const { searchParams, updateParams } = useUrlParams() const openPreview = useOpenPreview() @@ -44,10 +45,14 @@ export function TerminalWorkspace({ target, directory, isOpen }: TerminalWorkspa const [ctrlArmed, setCtrlArmed] = useState(false) const [pendingClose, setPendingClose] = useState(null) + const [dismissedTerminalIds, setDismissedTerminalIds] = useState>(() => new Set()) const viewHandlesRef = useRef(new Map()) const autoCreateCheckedDirectoryRef = useRef(null) - const terminals = useMemo(() => data ?? [], [data]) + const terminals = useMemo( + () => (data ?? []).filter((terminal) => !dismissedTerminalIds.has(terminal.id)), + [data, dismissedTerminalIds], + ) const selectTerminal = useCallback((id: string) => { updateParams((params) => { @@ -83,27 +88,63 @@ export function TerminalWorkspace({ target, directory, isOpen }: TerminalWorkspa ) }, [createTerminal, directory, selectTerminal]) - const performRemove = useCallback((terminal: TerminalInfo) => { - removeTerminal( - { ptyID: terminal.id, directory }, - { - onSuccess: () => { - updateParams((params) => { - if (params.get('terminal') === terminal.id) params.delete('terminal') - }, 'replace') + const performRemove = useCallback( + ( + terminalId: string, + options: { onRemoved?: () => void; onError?: () => void } = {}, + ) => { + removeTerminal( + { ptyID: terminalId, directory }, + { + onSuccess: () => { + updateParams((params) => { + if (params.get('terminal') === terminalId) params.delete('terminal') + }, 'replace') + options.onRemoved?.() + }, + onError: options.onError, }, - }, - ) - }, [removeTerminal, directory, updateParams]) + ) + }, + [removeTerminal, directory, updateParams], + ) const handleCloseTab = useCallback((terminal: TerminalInfo) => { if (terminal.status === 'running') { setPendingClose(terminal) return } - performRemove(terminal) + performRemove(terminal.id) }, [performRemove]) + const handleTerminalExited = useCallback((terminalId: string) => { + const settleExit = async () => { + let latestTerminals: TerminalInfo[] + try { + const result = await refetch() + latestTerminals = result.data ?? [] + } catch { + return + } + const exitCode = latestTerminals.find((terminal) => terminal.id === terminalId)?.exitCode + if (exitCode !== undefined && exitCode !== 0) return + setDismissedTerminalIds((ids) => new Set(ids).add(terminalId)) + performRemove(terminalId, { + onRemoved: () => { + if (latestTerminals.every((terminal) => terminal.id === terminalId)) onLastTerminalExited?.() + }, + onError: () => { + setDismissedTerminalIds((ids) => { + const next = new Set(ids) + next.delete(terminalId) + return next + }) + }, + }) + } + void settleExit() + }, [refetch, performRemove, onLastTerminalExited]) + const handleKeySend = useCallback((input: string) => { if (!activeTerminalId) return viewHandlesRef.current.get(activeTerminalId)?.send(input) @@ -190,7 +231,7 @@ export function TerminalWorkspace({ target, directory, isOpen }: TerminalWorkspa ctrlArmed={ctrlArmed} onCtrlConsumed={handleCtrlConsumed} onOpenLink={handleOpenLink} - onExited={() => { void refetch() }} + onExited={() => handleTerminalExited(terminal.id)} /> ))} @@ -205,7 +246,7 @@ export function TerminalWorkspace({ target, directory, isOpen }: TerminalWorkspa open={pendingClose !== null} onOpenChange={(open) => { if (!open) setPendingClose(null) }} onConfirm={() => { - if (pendingClose) performRemove(pendingClose) + if (pendingClose) performRemove(pendingClose.id) setPendingClose(null) }} onCancel={() => setPendingClose(null)} @@ -251,7 +292,7 @@ export function TerminalPanel({ target, directory, isOpen, onClose }: TerminalPa )} - + )