mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 5: Phase 5: Terminal panel, navigation and mobile key bar
This commit is contained in:
1 parent
dc7cd2382f
commit
c320e2ac7d
10 files changed
+678
-21
No files matched your search
@@ -14,7 +14,7 @@ describe('buildMoreItems', () => {
|
||||
|
||||
it('returns repo-specific items for /repos/:id', () => {
|
||||
const items = buildMoreItems('/repos/42')
|
||||
expect(items).toHaveLength(9)
|
||||
expect(items).toHaveLength(10)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[1].dialog).toBe('files')
|
||||
@@ -29,13 +29,15 @@ describe('buildMoreItems', () => {
|
||||
expect(items[5].to).toBe('/repos/42/schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[6].dialog).toBe('sourceControl')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('settings')
|
||||
expect(items[9].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
|
||||
const items = buildMoreItems('/repos/42/sessions/abc')
|
||||
expect(items).toHaveLength(9)
|
||||
expect(items).toHaveLength(10)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[2].key).toBe('mcp')
|
||||
@@ -44,13 +46,15 @@ describe('buildMoreItems', () => {
|
||||
expect(items[5].key).toBe('schedules')
|
||||
expect(items[5].to).toBe('/repos/42/schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('settings')
|
||||
expect(items[9].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns assistant workspace items for /repos/:id/assistant', () => {
|
||||
const items = buildMoreItems('/repos/42/assistant')
|
||||
expect(items).toHaveLength(9)
|
||||
expect(items).toHaveLength(10)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[1].dialog).toBe('files')
|
||||
@@ -59,8 +63,10 @@ describe('buildMoreItems', () => {
|
||||
expect(items[4].key).toBe('reset-permissions')
|
||||
expect(items[5].key).toBe('schedules')
|
||||
expect(items[6].key).toBe('source-control')
|
||||
expect(items[7].key).toBe('settings')
|
||||
expect(items[8].key).toBe('logout')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('settings')
|
||||
expect(items[9].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns only Home + Settings + Logout for /schedules', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Settings, LogOut, Bot, Folder, Home } from 'lucide-react'
|
||||
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home } from 'lucide-react'
|
||||
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
|
||||
|
||||
export interface MoreDrawerItem {
|
||||
@@ -58,6 +58,7 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
@@ -76,6 +77,7 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/schedules` },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
@@ -93,6 +95,7 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules' },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface TerminalKeyBarProps {
|
||||
onSend: (data: string) => void
|
||||
ctrlArmed: boolean
|
||||
onToggleCtrl: () => void
|
||||
}
|
||||
|
||||
interface SpecialKey {
|
||||
label: string
|
||||
data: string
|
||||
ariaLabel?: string
|
||||
}
|
||||
|
||||
const ESCAPE_KEY = '\x1b'
|
||||
const TAB_KEY = '\t'
|
||||
|
||||
const ARROW_KEYS: SpecialKey[] = [
|
||||
{ label: '↑', data: '\x1b[A', ariaLabel: 'Arrow up' },
|
||||
{ label: '↓', data: '\x1b[B', ariaLabel: 'Arrow down' },
|
||||
{ label: '←', data: '\x1b[D', ariaLabel: 'Arrow left' },
|
||||
{ label: '→', data: '\x1b[C', ariaLabel: 'Arrow right' },
|
||||
]
|
||||
|
||||
const SYMBOL_KEYS: SpecialKey[] = [
|
||||
{ label: '|', data: '|' },
|
||||
{ label: '~', data: '~' },
|
||||
{ label: '/', data: '/' },
|
||||
]
|
||||
|
||||
export function TerminalKeyBar({ onSend, ctrlArmed, onToggleCtrl }: TerminalKeyBarProps) {
|
||||
const renderKey = (key: SpecialKey) => (
|
||||
<Button
|
||||
key={key.label}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 min-w-8 flex-shrink-0 px-2 font-mono text-xs"
|
||||
aria-label={key.ariaLabel}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => onSend(key.data)}
|
||||
>
|
||||
{key.label}
|
||||
</Button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-card px-2 py-1.5"
|
||||
data-testid="terminal-key-bar"
|
||||
>
|
||||
{renderKey({ label: 'Esc', data: ESCAPE_KEY })}
|
||||
{renderKey({ label: 'Tab', data: TAB_KEY })}
|
||||
<Button
|
||||
type="button"
|
||||
variant={ctrlArmed ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
className={cn('h-8 min-w-8 flex-shrink-0 px-2 font-mono text-xs', ctrlArmed && 'bg-primary text-primary-foreground')}
|
||||
aria-pressed={ctrlArmed}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={onToggleCtrl}
|
||||
>
|
||||
Ctrl
|
||||
</Button>
|
||||
{ARROW_KEYS.map(renderKey)}
|
||||
{SYMBOL_KEYS.map(renderKey)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { TerminalPanel } from './TerminalPanel'
|
||||
|
||||
vi.mock('@/api/terminals', () => ({
|
||||
useTerminals: vi.fn(),
|
||||
useCreateTerminal: vi.fn(),
|
||||
useRemoveTerminal: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/hooks/useMobile')>('@/hooks/useMobile')
|
||||
return { ...actual, useMobile: vi.fn(() => false) }
|
||||
})
|
||||
|
||||
vi.mock('./TerminalView', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
TerminalView: React.forwardRef(function MockTerminalView(
|
||||
props: { ptyID: string; active: boolean },
|
||||
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),
|
||||
})
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const runningTerminal: TerminalInfo = {
|
||||
id: 't1',
|
||||
title: 'Terminal',
|
||||
kind: 'shell',
|
||||
cwd: '/repo',
|
||||
status: 'running',
|
||||
}
|
||||
|
||||
const exitedTerminal: TerminalInfo = {
|
||||
id: 't2',
|
||||
title: 'Build',
|
||||
kind: 'action',
|
||||
actionId: 'build',
|
||||
cwd: '/repo',
|
||||
status: 'exited',
|
||||
exitCode: 0,
|
||||
}
|
||||
|
||||
const createMutate = vi.fn()
|
||||
const removeMutate = vi.fn()
|
||||
const refetch = vi.fn()
|
||||
|
||||
function mockTerminalHooks(
|
||||
terminals: TerminalInfo[] | undefined,
|
||||
options: { isLoading?: boolean; isSuccess?: boolean } = {},
|
||||
) {
|
||||
vi.mocked(useTerminals).mockReturnValue({
|
||||
data: terminals,
|
||||
isLoading: options.isLoading ?? false,
|
||||
isSuccess: options.isSuccess ?? terminals !== undefined,
|
||||
refetch,
|
||||
} as unknown as ReturnType<typeof useTerminals>)
|
||||
vi.mocked(useCreateTerminal).mockReturnValue({
|
||||
mutate: createMutate,
|
||||
isPending: false,
|
||||
} as unknown as ReturnType<typeof useCreateTerminal>)
|
||||
vi.mocked(useRemoveTerminal).mockReturnValue({
|
||||
mutate: removeMutate,
|
||||
isPending: false,
|
||||
} as unknown as ReturnType<typeof useRemoveTerminal>)
|
||||
}
|
||||
|
||||
function renderPanel(initialEntry = '/repos/1?dialog=terminal', onClose = vi.fn()) {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={onClose} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('TerminalPanel', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(useMobile).mockReturnValue(false)
|
||||
mockTerminalHooks([])
|
||||
})
|
||||
|
||||
it('auto-creates a terminal when the directory has none', () => {
|
||||
mockTerminalHooks([])
|
||||
renderPanel()
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('does not auto-create while the list request is unresolved or failed', () => {
|
||||
mockTerminalHooks(undefined, { isSuccess: false })
|
||||
renderPanel()
|
||||
|
||||
expect(createMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-creates once the list resolves successfully empty', () => {
|
||||
mockTerminalHooks(undefined, { isSuccess: false })
|
||||
const { rerender } = renderPanel()
|
||||
expect(createMutate).not.toHaveBeenCalled()
|
||||
|
||||
mockTerminalHooks([], { isSuccess: true })
|
||||
rerender(
|
||||
<MemoryRouter initialEntries={['/repos/1?dialog=terminal']}>
|
||||
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={vi.fn()} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
expect(createMutate).toHaveBeenCalledTimes(1)
|
||||
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('exposes an accessible name for the mobile panel close control', () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const onClose = vi.fn()
|
||||
renderPanel('/repos/1?dialog=terminal', onClose)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close terminal panel' }))
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('activates the terminal referenced by the terminal URL param', () => {
|
||||
mockTerminalHooks([runningTerminal, exitedTerminal])
|
||||
renderPanel('/repos/1?dialog=terminal&terminal=t2')
|
||||
|
||||
const views = screen.getAllByTestId('terminal-view')
|
||||
const active = views.find((view) => view.getAttribute('data-pty-id') === 't2')
|
||||
const inactive = views.find((view) => view.getAttribute('data-pty-id') === 't1')
|
||||
|
||||
expect(active).toHaveAttribute('data-active', 'true')
|
||||
expect(inactive).toHaveAttribute('data-active', 'false')
|
||||
})
|
||||
|
||||
it('shows an exited badge with the exit code', () => {
|
||||
mockTerminalHooks([exitedTerminal])
|
||||
renderPanel()
|
||||
|
||||
expect(screen.getByText('exited (0)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('asks for confirmation before closing a running terminal', () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
renderPanel()
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Terminal'))
|
||||
|
||||
expect(screen.getByText('Stop the running process?')).toBeInTheDocument()
|
||||
expect(removeMutate).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Stop' }))
|
||||
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('removes an exited terminal without confirmation', () => {
|
||||
mockTerminalHooks([exitedTerminal])
|
||||
renderPanel()
|
||||
|
||||
fireEvent.click(screen.getByLabelText('Close Build'))
|
||||
|
||||
expect(screen.queryByText('Stop the running process?')).not.toBeInTheDocument()
|
||||
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object))
|
||||
})
|
||||
|
||||
it('renders the key bar only on mobile', () => {
|
||||
mockTerminalHooks([runningTerminal])
|
||||
|
||||
vi.mocked(useMobile).mockReturnValue(false)
|
||||
renderPanel()
|
||||
expect(screen.queryByTestId('terminal-key-bar')).not.toBeInTheDocument()
|
||||
|
||||
cleanup()
|
||||
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
renderPanel()
|
||||
expect(screen.getByTestId('terminal-key-bar')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,220 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import { Plus, SquareTerminal, X } from 'lucide-react'
|
||||
import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { TerminalKeyBar } from './TerminalKeyBar'
|
||||
import { TerminalView, type TerminalViewHandle } from './TerminalView'
|
||||
|
||||
interface TerminalPanelProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onOpenLink?: (uri: string) => void
|
||||
}
|
||||
|
||||
export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }: TerminalPanelProps) {
|
||||
const isMobile = useMobile()
|
||||
const { searchParams, updateParams } = useUrlParams()
|
||||
const { data, isLoading, isSuccess, refetch } = useTerminals(repoId, directory, {
|
||||
enabled: isOpen && !!directory,
|
||||
refetchInterval: isOpen ? 5000 : false,
|
||||
})
|
||||
const { mutate: createTerminal, isPending: isCreating } = useCreateTerminal(repoId)
|
||||
const { mutate: removeTerminal, isPending: isRemoving } = useRemoveTerminal(repoId)
|
||||
|
||||
const [ctrlArmed, setCtrlArmed] = useState(false)
|
||||
const [pendingClose, setPendingClose] = useState<TerminalInfo | null>(null)
|
||||
const viewHandlesRef = useRef(new Map<string, TerminalViewHandle>())
|
||||
const autoCreatedDirectoryRef = useRef<string | null>(null)
|
||||
|
||||
const terminals = useMemo(() => data ?? [], [data])
|
||||
|
||||
const selectTerminal = useCallback((id: string) => {
|
||||
updateParams((params) => {
|
||||
params.set('terminal', id)
|
||||
}, 'replace')
|
||||
}, [updateParams])
|
||||
|
||||
const requestedTerminalId = searchParams.get('terminal')
|
||||
const activeTerminalId = requestedTerminalId && terminals.some((terminal) => terminal.id === requestedTerminalId)
|
||||
? requestedTerminalId
|
||||
: terminals[0]?.id
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !directory) {
|
||||
autoCreatedDirectoryRef.current = null
|
||||
return
|
||||
}
|
||||
if (!isSuccess || terminals.length > 0) return
|
||||
if (autoCreatedDirectoryRef.current === directory) return
|
||||
autoCreatedDirectoryRef.current = directory
|
||||
createTerminal(
|
||||
{ directory },
|
||||
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
|
||||
)
|
||||
}, [isOpen, directory, isSuccess, terminals.length, createTerminal, selectTerminal])
|
||||
|
||||
const handleCreate = useCallback(() => {
|
||||
createTerminal(
|
||||
{ directory },
|
||||
{ onSuccess: (terminal) => selectTerminal(terminal.id) },
|
||||
)
|
||||
}, [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')
|
||||
},
|
||||
},
|
||||
)
|
||||
}, [removeTerminal, directory, updateParams])
|
||||
|
||||
const handleCloseTab = useCallback((terminal: TerminalInfo) => {
|
||||
if (terminal.status === 'running') {
|
||||
setPendingClose(terminal)
|
||||
return
|
||||
}
|
||||
performRemove(terminal)
|
||||
}, [performRemove])
|
||||
|
||||
const handleKeySend = useCallback((input: string) => {
|
||||
if (!activeTerminalId) return
|
||||
viewHandlesRef.current.get(activeTerminalId)?.send(input)
|
||||
}, [activeTerminalId])
|
||||
|
||||
const handleToggleCtrl = useCallback(() => setCtrlArmed((armed) => !armed), [])
|
||||
const handleCtrlConsumed = useCallback(() => setCtrlArmed(false), [])
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
hideCloseButton={isMobile}
|
||||
className={cn(
|
||||
'p-0 flex flex-col bg-card border-border gap-0',
|
||||
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-5xl h-[90vh] sm:pb-0',
|
||||
)}
|
||||
>
|
||||
<DialogHeader className={cn('px-4 py-2 border-b border-border flex-shrink-0', isMobile && 'relative')}>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<SquareTerminal className="w-5 h-5" />
|
||||
Terminal
|
||||
</DialogTitle>
|
||||
{isMobile && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
aria-label="Close terminal panel"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 h-10 w-10 p-0"
|
||||
>
|
||||
<X className="h-6 w-6" />
|
||||
</Button>
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-center gap-1 border-b border-border flex-shrink-0 overflow-x-auto px-1">
|
||||
{terminals.map((terminal) => (
|
||||
<div
|
||||
key={terminal.id}
|
||||
className={cn(
|
||||
'flex items-center gap-1 rounded-t-md border-b-2 px-2 py-1.5 text-sm transition-colors flex-shrink-0',
|
||||
terminal.id === activeTerminalId
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectTerminal(terminal.id)}
|
||||
className="flex max-w-[12rem] items-center gap-1.5"
|
||||
>
|
||||
<span className="truncate">{terminal.title}</span>
|
||||
{terminal.status === 'exited' && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
|
||||
{terminal.exitCode !== undefined ? `exited (${terminal.exitCode})` : 'exited'}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCloseTab(terminal)}
|
||||
aria-label={`Close ${terminal.title}`}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleCreate}
|
||||
disabled={!directory || isCreating}
|
||||
aria-label="New terminal"
|
||||
className="h-7 w-7 p-0 flex-shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="relative flex-1 min-h-0">
|
||||
{terminals.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
{isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
|
||||
</div>
|
||||
) : (
|
||||
terminals.map((terminal) => (
|
||||
<TerminalView
|
||||
key={terminal.id}
|
||||
ref={(handle) => {
|
||||
if (handle) viewHandlesRef.current.set(terminal.id, handle)
|
||||
else viewHandlesRef.current.delete(terminal.id)
|
||||
}}
|
||||
repoId={repoId}
|
||||
directory={directory}
|
||||
ptyID={terminal.id}
|
||||
active={terminal.id === activeTerminalId}
|
||||
ctrlArmed={ctrlArmed}
|
||||
onCtrlConsumed={handleCtrlConsumed}
|
||||
onOpenLink={onOpenLink}
|
||||
onExited={() => { void refetch() }}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isMobile && terminals.length > 0 && (
|
||||
<TerminalKeyBar onSend={handleKeySend} ctrlArmed={ctrlArmed} onToggleCtrl={handleToggleCtrl} />
|
||||
)}
|
||||
|
||||
<ConfirmDestructiveDialog
|
||||
open={pendingClose !== null}
|
||||
onOpenChange={(open) => { if (!open) setPendingClose(null) }}
|
||||
onConfirm={() => {
|
||||
if (pendingClose) performRemove(pendingClose)
|
||||
setPendingClose(null)
|
||||
}}
|
||||
onCancel={() => setPendingClose(null)}
|
||||
title="Close Terminal"
|
||||
description="Stop the running process?"
|
||||
confirmLabel="Stop"
|
||||
pendingLabel="Stopping..."
|
||||
isPending={isRemoving}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { createRef, type ComponentProps } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, render } from '@testing-library/react'
|
||||
import { TerminalView, type TerminalViewHandle } from './TerminalView'
|
||||
|
||||
const xterm = vi.hoisted(() => {
|
||||
const onDataHandlers: Array<(data: string) => void> = []
|
||||
return {
|
||||
onDataHandlers,
|
||||
write: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
dispose: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
const socket = vi.hoisted(() => ({ send: vi.fn() }))
|
||||
|
||||
vi.mock('@xterm/xterm', () => ({
|
||||
Terminal: vi.fn().mockImplementation(() => ({
|
||||
loadAddon: vi.fn(),
|
||||
open: vi.fn(),
|
||||
write: xterm.write,
|
||||
focus: xterm.focus,
|
||||
dispose: xterm.dispose,
|
||||
onData: (handler: (data: string) => void) => {
|
||||
xterm.onDataHandlers.push(handler)
|
||||
return { dispose: vi.fn() }
|
||||
},
|
||||
options: {},
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@xterm/addon-fit', () => ({
|
||||
FitAddon: vi.fn().mockImplementation(() => ({ fit: vi.fn() })),
|
||||
}))
|
||||
|
||||
vi.mock('@xterm/addon-web-links', () => ({
|
||||
WebLinksAddon: vi.fn().mockImplementation(() => ({})),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/terminals', () => ({
|
||||
resizeTerminal: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/terminal-theme', () => ({
|
||||
resolveTerminalTheme: vi.fn(() => ({})),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTerminalSocket', () => ({
|
||||
useTerminalSocket: () => ({ send: socket.send, status: 'open' }),
|
||||
}))
|
||||
|
||||
function renderView(overrides: Partial<ComponentProps<typeof TerminalView>> = {}) {
|
||||
const ref = createRef<TerminalViewHandle>()
|
||||
const onCtrlConsumed = vi.fn()
|
||||
const element = (
|
||||
<TerminalView
|
||||
ref={ref}
|
||||
repoId={1}
|
||||
directory="/repo"
|
||||
ptyID="t1"
|
||||
active
|
||||
ctrlArmed={false}
|
||||
onCtrlConsumed={onCtrlConsumed}
|
||||
onExited={vi.fn()}
|
||||
{...overrides}
|
||||
/>
|
||||
)
|
||||
const view = render(element)
|
||||
return { ref, onCtrlConsumed, view }
|
||||
}
|
||||
|
||||
describe('TerminalView input handling', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
xterm.onDataHandlers.length = 0
|
||||
})
|
||||
|
||||
it('applies the ctrl modifier and consumes it for imperative key-bar sends', () => {
|
||||
const { ref, onCtrlConsumed } = renderView({ ctrlArmed: true })
|
||||
|
||||
act(() => {
|
||||
ref.current?.send('c')
|
||||
})
|
||||
|
||||
expect(socket.send).toHaveBeenCalledWith('\x03')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('applies the ctrl modifier to keyboard input while armed', () => {
|
||||
const { onCtrlConsumed } = renderView({ ctrlArmed: true })
|
||||
|
||||
act(() => {
|
||||
xterm.onDataHandlers[0]('c')
|
||||
})
|
||||
|
||||
expect(socket.send).toHaveBeenCalledWith('\x03')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('consumes ctrl exactly once so subsequent keyboard input is unmodified', () => {
|
||||
const ref = createRef<TerminalViewHandle>()
|
||||
const onCtrlConsumed = vi.fn()
|
||||
const props: ComponentProps<typeof TerminalView> = {
|
||||
repoId: 1,
|
||||
directory: '/repo',
|
||||
ptyID: 't1',
|
||||
active: true,
|
||||
ctrlArmed: true,
|
||||
onCtrlConsumed,
|
||||
onExited: vi.fn(),
|
||||
}
|
||||
|
||||
const { rerender } = render(<TerminalView ref={ref} {...props} />)
|
||||
|
||||
act(() => {
|
||||
ref.current?.send('c')
|
||||
})
|
||||
expect(socket.send).toHaveBeenLastCalledWith('\x03')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(<TerminalView ref={ref} {...props} ctrlArmed={false} />)
|
||||
|
||||
act(() => {
|
||||
xterm.onDataHandlers[xterm.onDataHandlers.length - 1]('c')
|
||||
})
|
||||
|
||||
expect(socket.send).toHaveBeenLastCalledWith('c')
|
||||
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react'
|
||||
import { Terminal } from '@xterm/xterm'
|
||||
import { FitAddon } from '@xterm/addon-fit'
|
||||
import { WebLinksAddon } from '@xterm/addon-web-links'
|
||||
@@ -18,6 +18,10 @@ function defaultOpenLink(uri: string) {
|
||||
window.open(uri, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
export interface TerminalViewHandle {
|
||||
send: (data: string) => void
|
||||
}
|
||||
|
||||
export interface TerminalViewProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
@@ -29,7 +33,7 @@ export interface TerminalViewProps {
|
||||
onExited: () => void
|
||||
}
|
||||
|
||||
export function TerminalView({
|
||||
export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(function TerminalView({
|
||||
repoId,
|
||||
directory,
|
||||
ptyID,
|
||||
@@ -38,7 +42,7 @@ export function TerminalView({
|
||||
onCtrlConsumed,
|
||||
onOpenLink,
|
||||
onExited,
|
||||
}: TerminalViewProps) {
|
||||
}, ref) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const terminalRef = useRef<Terminal | null>(null)
|
||||
const fitAddonRef = useRef<FitAddon | null>(null)
|
||||
@@ -60,6 +64,15 @@ export function TerminalView({
|
||||
terminalRef.current?.write(text)
|
||||
}, [])
|
||||
|
||||
const handleInput = useCallback((data: string) => {
|
||||
if (ctrlArmedRef.current) {
|
||||
sendRef.current(applyCtrlModifier(data))
|
||||
onCtrlConsumedRef.current()
|
||||
return
|
||||
}
|
||||
sendRef.current(data)
|
||||
}, [])
|
||||
|
||||
const handleExit = useCallback(() => {
|
||||
terminalRef.current?.write('\r\n[process exited]\r\n')
|
||||
onExitedRef.current()
|
||||
@@ -75,6 +88,8 @@ export function TerminalView({
|
||||
})
|
||||
sendRef.current = send
|
||||
|
||||
useImperativeHandle(ref, () => ({ send: handleInput }), [handleInput])
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
@@ -100,12 +115,7 @@ export function TerminalView({
|
||||
fitAddonRef.current = fitAddon
|
||||
|
||||
const dataDisposable = terminal.onData((data) => {
|
||||
if (ctrlArmedRef.current) {
|
||||
sendRef.current(applyCtrlModifier(data))
|
||||
onCtrlConsumedRef.current()
|
||||
return
|
||||
}
|
||||
sendRef.current(data)
|
||||
handleInput(data)
|
||||
})
|
||||
|
||||
return () => {
|
||||
@@ -114,7 +124,7 @@ export function TerminalView({
|
||||
terminalRef.current = null
|
||||
fitAddonRef.current = null
|
||||
}
|
||||
}, [])
|
||||
}, [handleInput])
|
||||
|
||||
useEffect(() => {
|
||||
const terminal = terminalRef.current
|
||||
@@ -187,4 +197,6 @@ export function TerminalView({
|
||||
data-terminal-id={ptyID}
|
||||
/>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
TerminalView.displayName = 'TerminalView'
|
||||
@@ -12,6 +12,7 @@ import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"
|
||||
import { SourceControlPanel } from "@/components/source-control"
|
||||
import { TerminalPanel } from "@/components/terminal/TerminalPanel"
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
|
||||
import { Plus } from "lucide-react"
|
||||
@@ -23,6 +24,7 @@ export function AssistantRedirect() {
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp')
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills')
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl')
|
||||
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal')
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions')
|
||||
|
||||
const { data: repo, isLoading: repoLoading, error: repoError } = useQuery({
|
||||
@@ -92,6 +94,7 @@ export function AssistantRedirect() {
|
||||
/>
|
||||
)}
|
||||
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
|
||||
<TerminalPanel repoId={0} directory={assistantDirectory} isOpen={terminalOpen} onClose={() => setTerminalOpen(false)} />
|
||||
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Header } from "@/components/ui/header";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { SourceControlPanel } from "@/components/source-control";
|
||||
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
|
||||
import { useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useRepoActivity } from "@/hooks/useRepoActivity";
|
||||
import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings";
|
||||
@@ -33,6 +34,7 @@ export function RepoDetail() {
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
|
||||
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
|
||||
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
|
||||
@@ -291,6 +293,13 @@ export function RepoDetail() {
|
||||
repoName={repoName}
|
||||
/>
|
||||
|
||||
<TerminalPanel
|
||||
repoId={repoId}
|
||||
directory={composerDirectory}
|
||||
isOpen={terminalOpen}
|
||||
onClose={() => setTerminalOpen(false)}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
|
||||
@@ -50,6 +50,7 @@ import { FormPrompt } from "@/components/session/FormPrompt";
|
||||
import { MinimizedFormIndicator } from "@/components/session/MinimizedFormIndicator";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { SourceControlPanel } from "@/components/source-control";
|
||||
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
|
||||
import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner";
|
||||
import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
@@ -117,6 +118,7 @@ export function SessionDetail() {
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills');
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
|
||||
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
@@ -861,6 +863,13 @@ export function SessionDetail() {
|
||||
repoName={workspaceDisplayName}
|
||||
/>
|
||||
|
||||
<TerminalPanel
|
||||
repoId={repoId}
|
||||
directory={sessionDirectory}
|
||||
isOpen={terminalOpen}
|
||||
onClose={() => setTerminalOpen(false)}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
|
||||
Reference in new issue
Block a user