mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(terminal): remove terminals that exit cleanly
A shell that exits with code 0 is now deleted and its tab removed, and the terminal panel closes when it was the last one. Non-zero exits keep their tab and output.
This commit is contained in:
1 parent
36b8c1b200
commit
8277ec253e
4 files changed
+160
-25
No files matched your search
@@ -33,7 +33,12 @@ vi.mock('@/components/source-control/RemoteSourceControlContent', () => ({
|
||||
),
|
||||
}))
|
||||
vi.mock('@/components/terminal/TerminalPanel', () => ({
|
||||
TerminalWorkspace: () => <div>terminal-tool</div>,
|
||||
TerminalWorkspace: ({ onLastTerminalExited }: { onLastTerminalExited?: () => void }) => (
|
||||
<div>
|
||||
terminal-tool
|
||||
<button type="button" onClick={onLastTerminalExited}>Exit last terminal</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
vi.mock('@/components/preview/PreviewPanel', () => ({ PreviewWorkspace: () => <div>preview-tool</div> }))
|
||||
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)
|
||||
|
||||
|
||||
@@ -211,7 +211,7 @@ export function ToolSidePanel({
|
||||
if (tool === 'activity') return <ActivityPanelBody />
|
||||
if (tool === 'terminal') {
|
||||
return terminalWorkspaceTarget
|
||||
? <TerminalWorkspace target={terminalWorkspaceTarget} directory={terminalDirectory ?? directory} isOpen />
|
||||
? <TerminalWorkspace target={terminalWorkspaceTarget} directory={terminalDirectory ?? directory} isOpen onLastTerminalExited={closePanel} />
|
||||
: null
|
||||
}
|
||||
if (tool === 'skills') {
|
||||
|
||||
@@ -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<unknown>,
|
||||
) {
|
||||
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(
|
||||
<MemoryRouter initialEntries={['/repos/1?dialog=terminal&terminal=t1']}>
|
||||
<TerminalPanel target={{ kind: 'repo', repoId: 1 }} directory="/repo" isOpen onClose={onClose} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
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])
|
||||
|
||||
|
||||
@@ -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<TerminalInfo | null>(null)
|
||||
const [dismissedTerminalIds, setDismissedTerminalIds] = useState<ReadonlySet<string>>(() => new Set())
|
||||
const viewHandlesRef = useRef(new Map<string, TerminalViewHandle>())
|
||||
const autoCreateCheckedDirectoryRef = useRef<string | null>(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)}
|
||||
/>
|
||||
))}
|
||||
</Suspense>
|
||||
@@ -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
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
<TerminalWorkspace target={target} directory={directory} isOpen={isOpen} />
|
||||
<TerminalWorkspace target={target} directory={directory} isOpen={isOpen} onLastTerminalExited={onClose} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user