453 lines
18 KiB
TypeScript
453 lines
18 KiB
TypeScript
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
|
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'
|
|
|
|
const PLACEHOLDER = '任务或追问…(Enter 发送,Shift+Enter 换行)'
|
|
|
|
describe('terminal Agent CLI panel', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
useAiProviderStore.setState({
|
|
providers: [
|
|
{
|
|
id: 'local-test',
|
|
name: 'Local Test',
|
|
protocol: 'openai-chat',
|
|
authStyle: 'none',
|
|
baseUrl: 'http://127.0.0.1:11434/v1',
|
|
allowInsecureHttp: true,
|
|
models: [{ id: 'test', model: 'test', label: 'Test', capability: 'chat', billing: 'local' }],
|
|
defaultModelId: 'test',
|
|
enabled: true,
|
|
hasApiKey: true,
|
|
},
|
|
],
|
|
activeProviderId: 'local-test',
|
|
isLoaded: true,
|
|
catalogProviders: [],
|
|
catalogUpdatedAt: null,
|
|
})
|
|
useSettingsStore.setState((state) => ({
|
|
settings: { ...state.settings, agentSafetyMode: 'relaxed' },
|
|
}))
|
|
})
|
|
|
|
it('keeps a sticky composer and uses Enter to send with selected context only', async () => {
|
|
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({
|
|
success: true,
|
|
text: 'FINAL: 这是远端 Bash TMOUT 策略导致的自动退出。',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: 'timed out waiting for input: auto-logout', viewport: 'whole screen' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
|
|
expect(screen.queryByRole('button', { name: '解释' })).not.toBeInTheDocument()
|
|
expect(screen.queryByText('自然语言驱动 SSH 自主排障与部署')).not.toBeInTheDocument()
|
|
expect(screen.getByRole('button', { name: '发送' })).toBeVisible()
|
|
|
|
const input = screen.getByPlaceholderText(PLACEHOLDER)
|
|
fireEvent.change(input, { target: { value: '解释这个超时' } })
|
|
fireEvent.keyDown(input, { key: 'Enter', shiftKey: true })
|
|
expect(mockDesktopApi.aiComplete).not.toHaveBeenCalled()
|
|
fireEvent.keyDown(input, { key: 'Enter' })
|
|
|
|
await waitFor(() => expect(mockDesktopApi.aiComplete).toHaveBeenCalledTimes(1))
|
|
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[0][0].context).toContain('auto-logout')
|
|
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[0][0].context).not.toContain('whole screen')
|
|
expect(await screen.findByText('这是远端 Bash TMOUT 策略导致的自动退出。')).toBeVisible()
|
|
expect(screen.getByPlaceholderText(PLACEHOLDER)).toHaveValue('')
|
|
})
|
|
|
|
it('runs safe diagnostic commands automatically in the default relaxed 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 })
|
|
vi.mocked(mockDesktopApi.sshExec).mockResolvedValueOnce({
|
|
success: true,
|
|
result: 'load average: 0.01',
|
|
exitCode: 0,
|
|
})
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), {
|
|
target: { value: '检查服务器负载' },
|
|
})
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
await waitFor(() =>
|
|
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'uptime', { fromAgent: true })
|
|
)
|
|
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 relaxed 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(PLACEHOLDER), {
|
|
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('Always skips confirmation for the same command shape in the current panel session', async () => {
|
|
vi.mocked(mockDesktopApi.aiComplete)
|
|
.mockResolvedValueOnce({
|
|
success: true,
|
|
text: '```bash\nrm /tmp/tmp.AAA111\n```',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
.mockResolvedValueOnce({
|
|
success: true,
|
|
text: '```bash\nrm /tmp/tmp.BBB222\n```',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
.mockResolvedValueOnce({ success: true, text: 'FINAL: 清理完成。', model: 'test', redactedCount: 0 })
|
|
vi.mocked(mockDesktopApi.sshExec)
|
|
.mockResolvedValueOnce({ success: true, result: 'ok', exitCode: 0 })
|
|
.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(PLACEHOLDER), {
|
|
target: { value: '清理临时文件' },
|
|
})
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
const dialog = await screen.findByRole('dialog')
|
|
fireEvent.click(within(dialog).getByRole('button', { name: '本会话允许' }))
|
|
await waitFor(() =>
|
|
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'rm /tmp/tmp.AAA111', { fromAgent: true })
|
|
)
|
|
await waitFor(() =>
|
|
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'rm /tmp/tmp.BBB222', { fromAgent: true })
|
|
)
|
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
|
expect(await screen.findByText('清理完成。')).toBeVisible()
|
|
})
|
|
|
|
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(PLACEHOLDER), {
|
|
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,
|
|
text: '```bash\nrm -rf /\n```',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), {
|
|
target: { value: '删除整台主机' },
|
|
})
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
expect(await screen.findByRole('alert')).toHaveTextContent('破坏性操作硬红线')
|
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
|
expect(mockDesktopApi.sshExec).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('retries one malformed model response and then requires the explicit FINAL protocol', async () => {
|
|
vi.mocked(mockDesktopApi.aiComplete)
|
|
.mockResolvedValueOnce({ success: true, text: '我准备先检查一下。', model: 'test', redactedCount: 0 })
|
|
.mockResolvedValueOnce({
|
|
success: true,
|
|
text: 'FINAL: 已根据已有上下文完成分析。',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '已有足够证据', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), {
|
|
target: { value: '给出结论' },
|
|
})
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
expect(await screen.findByText('已根据已有上下文完成分析。')).toBeVisible()
|
|
expect(mockDesktopApi.aiComplete).toHaveBeenCalledTimes(2)
|
|
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[1][0].prompt).toContain('上一次回答没有遵循工具协议')
|
|
expect(mockDesktopApi.sshExec).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('automatically executes multiple read-only commands in the same relaxed 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 })
|
|
.mockResolvedValueOnce({ success: true, text: 'FINAL: 两项检查已完成。', model: 'test', redactedCount: 0 })
|
|
vi.mocked(mockDesktopApi.sshExec)
|
|
.mockResolvedValueOnce({ success: true, result: 'Thu Jul 30', exitCode: 0 })
|
|
.mockResolvedValueOnce({ success: true, result: 'Linux host', exitCode: 0 })
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), {
|
|
target: { value: '连续检查时间和系统' },
|
|
})
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledTimes(2))
|
|
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
|
expect(await screen.findByText('两项检查已完成。')).toBeVisible()
|
|
})
|
|
|
|
it('keeps follow-up turns in memory and can start a new topic', async () => {
|
|
vi.mocked(mockDesktopApi.aiComplete)
|
|
.mockResolvedValueOnce({ success: true, text: 'FINAL: 负载正常。', model: 'test', redactedCount: 0 })
|
|
.mockResolvedValueOnce({ success: true, text: 'FINAL: 内存也正常。', model: 'test', redactedCount: 0 })
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), { target: { value: '看负载' } })
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
expect(await screen.findByText('负载正常。')).toBeVisible()
|
|
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), { target: { value: '再看内存' } })
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
expect(await screen.findByText('内存也正常。')).toBeVisible()
|
|
expect(mockDesktopApi.aiComplete).toHaveBeenCalledTimes(2)
|
|
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[1][0].prompt).toContain('用户追问')
|
|
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[1][0].context).toContain('负载正常')
|
|
|
|
fireEvent.click(screen.getByRole('button', { name: '新话题' }))
|
|
expect(screen.queryByText('负载正常。')).not.toBeInTheDocument()
|
|
expect(screen.queryByText('内存也正常。')).not.toBeInTheDocument()
|
|
expect(screen.getByText(/可连续追问/)).toBeVisible()
|
|
})
|
|
|
|
it('renders markdown tables in FINAL conclusions', async () => {
|
|
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({
|
|
success: true,
|
|
text: [
|
|
'FINAL: 当前监听端口如下:',
|
|
'',
|
|
'| 端口 | 服务 |',
|
|
'|------|------|',
|
|
'| 22 | sshd |',
|
|
'| 80 | nginx |',
|
|
].join('\n'),
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), { target: { value: '列出端口' } })
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
expect(await screen.findByRole('table')).toBeVisible()
|
|
expect(screen.getByText('sshd')).toBeVisible()
|
|
expect(screen.getByText('nginx')).toBeVisible()
|
|
})
|
|
|
|
it('stops the agent and cancels the in-flight ssh_exec', async () => {
|
|
type ExecResult = { success: boolean; result?: string; exitCode?: number; error?: string }
|
|
const deferred: { resolve: (value: ExecResult) => void } = {
|
|
resolve: () => undefined,
|
|
}
|
|
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({
|
|
success: true,
|
|
text: '```bash\ndate\n```',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
vi.mocked(mockDesktopApi.sshExec).mockImplementationOnce(
|
|
() =>
|
|
new Promise<ExecResult>((resolve) => {
|
|
deferred.resolve = resolve
|
|
})
|
|
)
|
|
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), { target: { value: '查看时间' } })
|
|
fireEvent.click(screen.getByRole('button', { name: '发送' }))
|
|
|
|
await waitFor(() =>
|
|
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'date', { fromAgent: true })
|
|
)
|
|
fireEvent.click(screen.getByRole('button', { name: '停止' }))
|
|
|
|
expect(mockDesktopApi.sshExecCancel).toHaveBeenCalledWith('ssh-active-1')
|
|
expect(await screen.findByText('已终止。正在执行的远端命令已请求中断。')).toBeVisible()
|
|
deferred.resolve({ success: false, error: '命令已终止' })
|
|
await waitFor(() => expect(screen.getByRole('button', { name: '发送' })).toBeVisible())
|
|
expect(mockDesktopApi.aiComplete).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('splits model and SSH target in the header and hides extra chrome until needed', () => {
|
|
useAiProviderStore.setState({
|
|
providers: [
|
|
{
|
|
id: 'deepseek',
|
|
name: 'DeepSeek',
|
|
protocol: 'openai-chat',
|
|
authStyle: 'bearer',
|
|
baseUrl: 'https://api.deepseek.com',
|
|
models: [
|
|
{ id: 'v4', model: 'deepseek-v4-pro', label: 'DeepSeek V4 Pro', capability: 'chat', billing: 'payg' },
|
|
],
|
|
defaultModelId: 'v4',
|
|
enabled: true,
|
|
hasApiKey: true,
|
|
allowInsecureHttp: false,
|
|
},
|
|
],
|
|
activeProviderId: 'deepseek',
|
|
isLoaded: true,
|
|
catalogProviders: [],
|
|
catalogUpdatedAt: null,
|
|
})
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport: '' })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="pre-jenkins"
|
|
/>
|
|
)
|
|
expect(screen.getByText('DeepSeek V4 Pro')).toBeVisible()
|
|
expect(screen.getByText('SSH · pre-jenkins')).toBeVisible()
|
|
expect(screen.queryByRole('button', { name: '所有命令都需确认(只读白名单除外)' })).not.toBeInTheDocument()
|
|
expect(screen.queryByRole('button', { name: '新话题' })).not.toBeInTheDocument()
|
|
expect(screen.getByRole('button', { name: '关闭' })).toBeVisible()
|
|
})
|
|
|
|
it('compacts oversized terminal dumps before summarizing', async () => {
|
|
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({
|
|
success: true,
|
|
text: 'FINAL: 日志过长,已按摘要阅读。',
|
|
model: 'test',
|
|
redactedCount: 0,
|
|
})
|
|
const viewport = Array.from({ length: 200 }, (_, index) => `line-${index} ${'x'.repeat(48)}`).join('\n')
|
|
render(
|
|
<AiTerminalPanel
|
|
capture={() => ({ selection: '', viewport })}
|
|
onClose={vi.fn()}
|
|
connectionId="ssh-active-1"
|
|
targetLabel="root@opsbase.cn"
|
|
/>
|
|
)
|
|
fireEvent.click(screen.getByRole('button', { name: '总结输出' }))
|
|
await waitFor(() => expect(mockDesktopApi.aiComplete).toHaveBeenCalledTimes(1))
|
|
const context = String(vi.mocked(mockDesktopApi.aiComplete).mock.calls[0][0].context)
|
|
expect(context.length).toBeLessThan(viewport.length)
|
|
expect(context).toMatch(/总行数|已省略/)
|
|
})
|
|
})
|