feat: add terminal broadcast, context menu, and shell close

Complete multi-pane broadcast, standard terminal right-click actions, batch host selection with progress, and native ssh_close_shell so closing a pane tears down the remote shell.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Logan.LiandCursor committed 2026-08-05 19:53:39 +08:00
1 parent 494ef6b9d0
commit 9ce71795b8
38 files changed
+1437 -186

No files matched your search

+61 -17
View File
@@ -2,6 +2,7 @@ import { fireEvent, render, screen, waitFor, within } from '@testing-library/rea
import { beforeEach, describe, expect, it, vi } from 'vitest'
import AiTerminalPanel from '../../src/components/ai/AiTerminalPanel'
import { useAiProviderStore } from '../../src/stores/aiProviderStore'
import { useSettingsStore } from '../../src/stores/settingsStore'
import { mockDesktopApi } from '../setup'
describe('terminal Agent CLI panel', () => {
@@ -27,6 +28,9 @@ describe('terminal Agent CLI panel', () => {
catalogProviders: [],
catalogUpdatedAt: null,
})
useSettingsStore.setState((state) => ({
settings: { ...state.settings, agentSafetyMode: 'balanced' },
}))
})
it('uses one task entry, Enter to run, Shift+Enter for a newline, and selected context only', async () => {
@@ -61,7 +65,7 @@ describe('terminal Agent CLI panel', () => {
expect(await screen.findByText('这是远端 Bash TMOUT 策略导致的自动退出。')).toBeVisible()
})
it('runs a bounded observe loop on the active SSH connection with confirmation before every command', async () => {
it('runs safe diagnostic commands automatically in the default balanced mode', async () => {
vi.mocked(mockDesktopApi.aiComplete)
.mockResolvedValueOnce({ success: true, text: '```bash\nuptime\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({ success: true, text: 'FINAL: 负载正常,任务完成。', model: 'test', redactedCount: 0 })
@@ -85,19 +89,67 @@ describe('terminal Agent CLI panel', () => {
})
fireEvent.click(screen.getByRole('button', { name: '执行' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/root@opsbase.cn/)).toBeVisible()
expect(within(dialog).getByText(/uptime/)).toBeVisible()
expect(mockDesktopApi.sshExec).not.toHaveBeenCalled()
fireEvent.click(within(dialog).getByRole('button', { name: '执行' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'uptime'))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(await screen.findByText('load average: 0.01')).toBeVisible()
expect(await screen.findByText('负载正常,任务完成。')).toBeVisible()
expect(mockDesktopApi.aiComplete).toHaveBeenCalledTimes(2)
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[1][0].context).toContain('[exit_code=0]')
})
it('asks for confirmation for high-risk commands in the default balanced mode', async () => {
vi.mocked(mockDesktopApi.aiComplete)
.mockResolvedValueOnce({ success: true, text: '```bash\nsystemctl restart nginx\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({ success: true, text: 'FINAL: nginx 已重启。', model: 'test', redactedCount: 0 })
vi.mocked(mockDesktopApi.sshExec).mockResolvedValueOnce({ success: true, result: 'ok', exitCode: 0 })
render(
<AiTerminalPanel
capture={() => ({ selection: '', viewport: '' })}
onClose={vi.fn()}
connectionId="ssh-active-1"
targetLabel="root@opsbase.cn"
/>
)
fireEvent.change(screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)'), {
target: { value: '重启 nginx' },
})
fireEvent.click(screen.getByRole('button', { name: '执行' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/均衡/)).toBeVisible()
expect(within(dialog).getByText(/systemctl restart nginx/)).toBeVisible()
expect(mockDesktopApi.sshExec).not.toHaveBeenCalled()
fireEvent.click(within(dialog).getByRole('button', { name: '确认风险并执行' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledTimes(1))
})
it('lets strict mode require confirmation from medium risk upward', async () => {
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({
success: true,
text: '```bash\ntouch /tmp/opsxshell-agent-test\n```',
model: 'test',
redactedCount: 0,
})
render(
<AiTerminalPanel
capture={() => ({ selection: '', viewport: '' })}
onClose={vi.fn()}
connectionId="ssh-active-1"
targetLabel="root@opsbase.cn"
/>
)
fireEvent.click(screen.getByRole('radio', { name: '严格' }))
fireEvent.change(screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)'), {
target: { value: '创建临时文件' },
})
fireEvent.click(screen.getByRole('button', { name: '执行' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/touch \/tmp\/opsxshell-agent-test/)).toBeVisible()
expect(mockDesktopApi.sshExec).not.toHaveBeenCalled()
})
it('hard-denies critical destructive commands without offering confirmation', async () => {
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({
success: true,
@@ -153,7 +205,7 @@ describe('terminal Agent CLI panel', () => {
expect(mockDesktopApi.sshExec).not.toHaveBeenCalled()
})
it('asks again before a second command in the same task', async () => {
it('automatically executes multiple read-only commands in the same balanced task', async () => {
vi.mocked(mockDesktopApi.aiComplete)
.mockResolvedValueOnce({ success: true, text: '```bash\ndate\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({ success: true, text: '```bash\nuname -a\n```', model: 'test', redactedCount: 0 })
@@ -175,16 +227,8 @@ describe('terminal Agent CLI panel', () => {
})
fireEvent.click(screen.getByRole('button', { name: '执行' }))
let dialog = await screen.findByRole('dialog')
fireEvent.click(within(dialog).getByRole('button', { name: '执行' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledTimes(1))
dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/uname -a/)).toBeVisible()
expect(mockDesktopApi.sshExec).toHaveBeenCalledTimes(1)
fireEvent.click(within(dialog).getByRole('button', { name: '执行' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledTimes(2))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(await screen.findByText('两项检查已完成。')).toBeVisible()
})
})
+38 -1
View File
@@ -33,7 +33,7 @@ describe('BatchCommandDialog', () => {
render(<BatchCommandDialog isOpen sessions={sessions} onClose={vi.fn()} />)
await user.type(screen.getByLabelText('远程命令'), 'date')
await user.click(screen.getByRole('button', { name: '执行命令' }))
await user.click(screen.getByRole('button', { name: '执行到 2 台' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledTimes(2))
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('connection-10.0.0.1', 'date')
@@ -43,4 +43,41 @@ describe('BatchCommandDialog', () => {
expect(screen.getByText('connection-10.0.0.1: date')).toBeVisible()
expect(screen.getByText('connection-10.0.0.2: date')).toBeVisible()
})
it('starts with the sidebar selection and lets the user adjust targets in the dialog', async () => {
const user = userEvent.setup()
render(
<BatchCommandDialog
isOpen
sessions={sessions}
initialSelectedIds={['host-a']}
onClose={vi.fn()}
/>
)
expect(screen.getByRole('checkbox', { name: /Host A/ })).toHaveAttribute('aria-checked', 'true')
expect(screen.getByRole('checkbox', { name: /Host B/ })).toHaveAttribute('aria-checked', 'false')
await user.click(screen.getByRole('checkbox', { name: /Host B/ }))
expect(screen.getByRole('button', { name: '执行到 2 台' })).toBeVisible()
await user.type(screen.getByLabelText('筛选主机'), '10.0.0.1')
expect(screen.getByRole('checkbox', { name: /Host A/ })).toBeVisible()
expect(screen.queryByRole('checkbox', { name: /Host B/ })).not.toBeInTheDocument()
})
it('clears the command when reopened so sensitive input is not retained', async () => {
const user = userEvent.setup()
const { rerender } = render(
<BatchCommandDialog isOpen sessions={sessions} onClose={vi.fn()} />
)
const command = screen.getByLabelText('远程命令')
await user.type(command, 'cat /etc/shadow')
expect(command).toHaveValue('cat /etc/shadow')
rerender(<BatchCommandDialog isOpen={false} sessions={sessions} onClose={vi.fn()} />)
rerender(<BatchCommandDialog isOpen sessions={sessions} onClose={vi.fn()} />)
expect(screen.getByLabelText('远程命令')).toHaveValue('')
})
})
@@ -205,4 +205,18 @@ describe('Session workflow acceptance', () => {
expect(sessionTarget).toHaveValue('admin@example.com:2200')
expect(screen.getByLabelText('端口')).toHaveValue(2200)
})
it('clears quick-connect credentials whenever the dialog is reopened', async () => {
const user = userEvent.setup()
const { rerender } = render(<QuickConnectDialog isOpen onClose={vi.fn()} />)
await user.type(screen.getByPlaceholderText('root@192.168.1.10:22'), 'root@example.com')
await user.type(screen.getByPlaceholderText('••••••••'), 'temporary-secret')
rerender(<QuickConnectDialog isOpen={false} onClose={vi.fn()} />)
rerender(<QuickConnectDialog isOpen onClose={vi.fn()} />)
expect(screen.getByPlaceholderText('root@192.168.1.10:22')).toHaveValue('')
expect(screen.getByPlaceholderText('••••••••')).toHaveValue('')
})
})
@@ -0,0 +1,48 @@
import { fireEvent, render, screen } from '@testing-library/react'
import type { ComponentProps } from 'react'
import { describe, expect, it, vi } from 'vitest'
import TerminalContextMenu from '../../src/components/terminal/TerminalContextMenu'
function renderMenu(overrides: Partial<ComponentProps<typeof TerminalContextMenu>> = {}) {
const props: ComponentProps<typeof TerminalContextMenu> = {
position: { x: 20, y: 20 },
hasSelection: false,
canSplit: true,
canClosePane: true,
canCloseTerminal: true,
closeLabel: '关闭当前分屏',
maximized: false,
onClose: vi.fn(),
onCopy: vi.fn(),
onPaste: vi.fn(),
onSelectAll: vi.fn(),
onClear: vi.fn(),
onSplitRight: vi.fn(),
onSplitDown: vi.fn(),
onToggleMaximize: vi.fn(),
onClosePane: vi.fn(),
...overrides,
}
render(<TerminalContextMenu {...props} />)
return props
}
describe('TerminalContextMenu', () => {
it('provides standard clipboard and pane actions without browser debug entries', () => {
const props = renderMenu()
expect(screen.getByRole('menuitem', { name: '复制' })).toBeDisabled()
fireEvent.click(screen.getByRole('menuitem', { name: '粘贴' }))
expect(props.onPaste).toHaveBeenCalled()
expect(screen.queryByText('Reload')).not.toBeInTheDocument()
expect(screen.queryByText('Inspect Element')).not.toBeInTheDocument()
})
it('exposes right/down split and the context-aware close action', () => {
const props = renderMenu({ hasSelection: true, closeLabel: '关闭当前终端标签' })
fireEvent.click(screen.getByRole('menuitem', { name: '向右分屏' }))
expect(props.onSplitRight).toHaveBeenCalled()
renderMenu({ closeLabel: '关闭当前终端标签' })
expect(screen.getAllByRole('menuitem', { name: '关闭当前终端标签' })[0]).toBeEnabled()
})
})
+1
View File
@@ -26,6 +26,7 @@ export const mockDesktopApi: DesktopApiContract = {
sshCreateShell: vi.fn().mockResolvedValue({ success: true, shellId: 'test-shell-1' }),
sshShellWrite: vi.fn().mockResolvedValue({ success: true }),
sshShellResize: vi.fn().mockResolvedValue({ success: true }),
sshCloseShell: vi.fn().mockResolvedValue({ success: true }),
sshForwardLocal: vi.fn().mockResolvedValue({ success: true }),
sshForwardRemote: vi.fn().mockResolvedValue({ success: true }),
sshForwardDynamic: vi.fn().mockResolvedValue({ success: true }),
@@ -0,0 +1,48 @@
import { beforeEach, describe, expect, it } from 'vitest'
import {
getTerminalBroadcastTargets,
terminalBroadcastTargetCount,
useTerminalBroadcastStore,
} from '../../src/stores/terminalBroadcastStore'
describe('terminal broadcast store', () => {
beforeEach(() => useTerminalBroadcastStore.getState().reset())
it('collects ready shells from every open terminal workspace and removes closed tabs', () => {
const store = useTerminalBroadcastStore.getState()
store.registerWorkspace({
tabId: 'tab-a',
targets: [
{ tabId: 'tab-a', paneId: 'left', shellId: 'shell-a', connectionId: 'conn-a', label: 'Host A' },
{ tabId: 'tab-a', paneId: 'right', shellId: 'shell-b', connectionId: 'conn-a', label: 'Host A' },
],
})
store.registerWorkspace({
tabId: 'tab-b',
targets: [
{ tabId: 'tab-b', paneId: 'main', shellId: 'shell-c', connectionId: 'conn-b', label: 'Host B' },
],
})
expect(getTerminalBroadcastTargets().map((target) => target.shellId)).toEqual([
'shell-a',
'shell-b',
'shell-c',
])
expect(terminalBroadcastTargetCount(useTerminalBroadcastStore.getState())).toBe(3)
useTerminalBroadcastStore.getState().unregisterWorkspace('tab-a')
expect(getTerminalBroadcastTargets().map((target) => target.shellId)).toEqual(['shell-c'])
})
it('deduplicates a shell defensively', () => {
useTerminalBroadcastStore.getState().registerWorkspace({
tabId: 'tab-a',
targets: [
{ tabId: 'tab-a', paneId: 'a', shellId: 'shared', connectionId: 'conn-a', label: 'A' },
{ tabId: 'tab-a', paneId: 'b', shellId: 'shared', connectionId: 'conn-a', label: 'A' },
],
})
expect(getTerminalBroadcastTargets()).toHaveLength(1)
})
})
+13 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
import { analyzeAgentOutput } from '../../src/utils/agentOutput'
import { assessAgentCommandRisk } from '../../src/utils/agentCommandRisk'
import {
agentCommandNeedsConfirmation,
assessAgentCommandRisk,
} from '../../src/utils/agentCommandRisk'
describe('Agent command guardrail', () => {
it.each([
@@ -17,6 +20,15 @@ describe('Agent command guardrail', () => {
])('classifies %s as %s', (command, expected) => {
expect(assessAgentCommandRisk(command)).toBe(expected)
})
it('uses strict, balanced and permissive confirmation thresholds', () => {
expect(agentCommandNeedsConfirmation('safe', 'strict')).toBe(false)
expect(agentCommandNeedsConfirmation('medium', 'strict')).toBe(true)
expect(agentCommandNeedsConfirmation('medium', 'balanced')).toBe(false)
expect(agentCommandNeedsConfirmation('high', 'balanced')).toBe(true)
expect(agentCommandNeedsConfirmation('high', 'permissive')).toBe(false)
expect(agentCommandNeedsConfirmation('critical', 'permissive')).toBe(false)
})
})
describe('Agent analyze_output tool', () => {
+11 -1
View File
@@ -1,5 +1,8 @@
import { describe, expect, it } from 'vitest'
import { resolveTerminalInputTargets } from '../../src/utils/terminalPanes'
import {
resolveTerminalInputTargets,
shouldBroadcastTerminalInput,
} from '../../src/utils/terminalPanes'
const panes = [
{ id: 'left', shellId: 'shell-1' },
@@ -23,4 +26,11 @@ describe('terminal pane input routing', () => {
expect(resolveTerminalInputTargets(panes, 'starting', false)).toEqual([])
expect(resolveTerminalInputTargets(panes, 'missing', false)).toEqual([])
})
it('never broadcasts input originating from a local terminal', () => {
expect(shouldBroadcastTerminalInput(true, true, 'local')).toBe(false)
expect(shouldBroadcastTerminalInput(true, true, 'ssh-connection')).toBe(false)
expect(shouldBroadcastTerminalInput(true, false, 'ssh-connection')).toBe(true)
expect(shouldBroadcastTerminalInput(true, false, null)).toBe(false)
})
})