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' 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: 'balanced' }, })) }) it('uses one task entry, Enter to run, Shift+Enter for a newline, and selected context only', async () => { vi.mocked(mockDesktopApi.aiComplete).mockResolvedValueOnce({ success: true, text: 'FINAL: 这是远端 Bash TMOUT 策略导致的自动退出。', model: 'test', redactedCount: 0, }) render( ({ 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.queryByRole('button', { name: '生成命令' })).not.toBeInTheDocument() expect(screen.getByText('自然语言驱动 SSH 自主排障与部署')).toBeVisible() const input = screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)') 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() }) 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 }) vi.mocked(mockDesktopApi.sshExec).mockResolvedValueOnce({ success: true, result: 'load average: 0.01', exitCode: 0, }) render( ({ selection: '', viewport: '' })} onClose={vi.fn()} connectionId="ssh-active-1" targetLabel="root@opsbase.cn" /> ) fireEvent.change(screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)'), { target: { value: '检查服务器负载' }, }) fireEvent.click(screen.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( ({ 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( ({ 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, text: '```bash\nrm -rf /\n```', model: 'test', redactedCount: 0, }) render( ({ selection: '', viewport: '' })} onClose={vi.fn()} connectionId="ssh-active-1" targetLabel="root@opsbase.cn" /> ) fireEvent.change(screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)'), { 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( ({ selection: '已有足够证据', viewport: '' })} onClose={vi.fn()} connectionId="ssh-active-1" targetLabel="root@opsbase.cn" /> ) fireEvent.change(screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)'), { 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 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 }) .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( ({ selection: '', viewport: '' })} onClose={vi.fn()} connectionId="ssh-active-1" targetLabel="root@opsbase.cn" /> ) fireEvent.change(screen.getByPlaceholderText('输入任务描述,回车发送(Shift+回车换行)'), { 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() }) })