feat: release OpsXShell 2.1.1

This commit is contained in:
Logan.Li committed 2026-07-31 01:37:01 +08:00
1 parent a3dba0c6ed
commit 494ef6b9d0
37 files changed
+2039 -370

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import SettingsView from '../../src/components/settings/SettingsView'
import TerminalWorkspace from '../../src/components/terminal/TerminalWorkspace'
import { useAiProviderStore } from '../../src/stores/aiProviderStore'
import { useSettingsStore } from '../../src/stores/settingsStore'
import { useTabStore } from '../../src/stores/tabStore'
describe('AI entry points', () => {
beforeEach(() => {
vi.clearAllMocks()
useSettingsStore.setState({ isLoaded: true })
useAiProviderStore.setState({
providers: [],
activeProviderId: '',
isLoaded: true,
catalogProviders: [],
catalogUpdatedAt: null,
})
})
it('keeps the model configuration visible in settings navigation', () => {
render(<SettingsView />)
const entry = screen.getByTestId('settings-tab-ai')
expect(entry).toBeVisible()
expect(entry).toHaveTextContent('大模型')
expect(entry).toHaveTextContent('Provider、模型与测试')
fireEvent.click(entry)
expect(screen.getByRole('heading', { name: '大模型' })).toBeVisible()
expect(screen.getByRole('button', { name: '添加' })).toBeVisible()
})
it('keeps a prominent AI assistant control wired into every terminal workspace', () => {
useTabStore.setState({
tabs: [
{
id: 'terminal-ai-test',
title: 'root@example.com',
type: 'terminal',
isActive: false,
sessionId: 'session-ai-test',
},
],
activeTabId: null,
})
render(<TerminalWorkspace tabId="terminal-ai-test" isActive={false} />)
const entry = screen.getByTestId('terminal-ai-button')
expect(entry).toBeVisible()
expect(entry).toHaveTextContent('AI 助手')
expect(entry).toHaveAttribute('aria-label', '打开终端 AI 助手')
fireEvent.click(entry)
expect(entry).toHaveAttribute('aria-label', '关闭终端 AI 助手')
})
})
+139 -40
View File
@@ -4,7 +4,7 @@ import AiTerminalPanel from '../../src/components/ai/AiTerminalPanel'
import { useAiProviderStore } from '../../src/stores/aiProviderStore'
import { mockDesktopApi } from '../setup'
describe('terminal AI panel', () => {
describe('terminal Agent CLI panel', () => {
beforeEach(() => {
vi.clearAllMocks()
useAiProviderStore.setState({
@@ -27,65 +27,164 @@ describe('terminal AI panel', () => {
catalogProviders: [],
catalogUpdatedAt: null,
})
vi.mocked(mockDesktopApi.aiComplete).mockResolvedValue({
})
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: '建议:\n```bash\ndate\n```',
text: 'FINAL: 这是远端 Bash TMOUT 策略导致的自动退出。',
model: 'test',
redactedCount: 0,
})
})
it('prefers selection and fills one line without pressing enter', async () => {
const insert = vi.fn()
render(
<AiTerminalPanel
capture={() => ({ selection: 'selected error', viewport: 'whole screen' })}
insert={insert}
onClose={vi.fn()}
/>
)
fireEvent.change(screen.getByPlaceholderText('例如:分析这段报错,并给出最少的只读检查命令'), {
target: { value: '怎么排查' },
})
fireEvent.click(screen.getByRole('button', { name: '生成建议' }))
await waitFor(() => expect(mockDesktopApi.aiComplete).toHaveBeenCalled())
expect(vi.mocked(mockDesktopApi.aiComplete).mock.calls[0][0].context).toBe('selected error')
fireEvent.click(await screen.findByRole('button', { name: '填入终端' }))
expect(insert).toHaveBeenCalledWith('date')
})
it('executes one confirmed command through the current SSH connection and analyzes real output', async () => {
vi.mocked(mockDesktopApi.aiComplete)
.mockResolvedValueOnce({ success: true, text: '```bash\nuptime\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({ success: true, text: '负载正常。', model: 'test', redactedCount: 0 })
vi.mocked(mockDesktopApi.sshExec).mockResolvedValueOnce({ success: true, result: 'load average: 0.01' })
render(
<AiTerminalPanel
capture={() => ({ selection: '', viewport: '' })}
insert={vi.fn()}
capture={() => ({ selection: 'timed out waiting for input: auto-logout', viewport: 'whole screen' })}
onClose={vi.fn()}
connectionId="ssh-active-1"
targetLabel="root@opsbase.cn"
/>
)
fireEvent.click(screen.getByRole('button', { name: '执行任务' }))
fireEvent.change(screen.getByPlaceholderText('例如:分析这段报错,并给出最少的只读检查命令'), {
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 a bounded observe loop on the active SSH connection with confirmation before every command', 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('输入任务描述,回车发送(Shift+回车换行)'), {
target: { value: '检查服务器负载' },
})
fireEvent.click(screen.getByRole('button', { name: '准备执行方案' }))
fireEvent.click(await screen.findByRole('button', { name: '执行一次' }))
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: '执行一次' }))
fireEvent.click(within(dialog).getByRole('button', { name: '执行' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'uptime'))
expect(await screen.findByText('load average: 0.01')).toBeVisible()
expect(await screen.findByText('负载正常。')).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('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('输入任务描述,回车发送(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(
<AiTerminalPanel
capture={() => ({ 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('asks again before a second command in the same 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('输入任务描述,回车发送(Shift+回车换行)'), {
target: { value: '连续检查时间和系统' },
})
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(await screen.findByText('两项检查已完成。')).toBeVisible()
})
})
@@ -0,0 +1,15 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { ShellClosedOverlay } from '../../src/components/terminal/TerminalOverlay'
describe('remote shell close recovery', () => {
it('explains remote TMOUT without claiming the pooled SSH connection is dead', () => {
const reopen = vi.fn()
render(<ShellClosedOverlay reason="远端 Shell 因空闲策略(TMOUT)自动退出" idleTimeout onReopen={reopen} />)
expect(screen.getByText('空闲超时,Shell 已退出')).toBeVisible()
expect(screen.getByText(/SSH 连接仍可用/)).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '重新打开 Shell' }))
expect(reopen).toHaveBeenCalledTimes(1)
})
})
+26
View File
@@ -19,6 +19,32 @@ function deferred<T>() {
}
describe('Tauri event subscriptions', () => {
it('maps a shell close event without treating the pooled connection as closed', async () => {
const unlisten = vi.fn()
let dispatch: ((event: { payload: unknown }) => void) | undefined
listenMock.mockImplementationOnce(async (_channel, callback) => {
dispatch = callback
return unlisten
})
const listener = vi.fn()
desktopApi.onShellClosed(listener)
await Promise.resolve()
dispatch?.({
payload: {
connectionId: 'connection-1',
shellId: 'shell-2',
reason: '远端 Shell 因空闲策略(TMOUT)自动退出',
idleTimeout: true,
},
})
expect(listener).toHaveBeenCalledWith({}, 'connection-1', 'shell-2', {
reason: '远端 Shell 因空闲策略(TMOUT)自动退出',
idleTimeout: true,
})
})
it('safely unregisters when React cleans up before listen resolves', async () => {
const pending = deferred<() => void>()
const unlisten = vi.fn()
+5 -2
View File
@@ -21,7 +21,7 @@ export const mockDesktopApi: DesktopApiContract = {
// SSH
sshConnect: vi.fn().mockResolvedValue({ success: true, connectionId: 'test-conn-1' }),
sshDisconnect: vi.fn().mockResolvedValue({ success: true }),
sshExec: vi.fn().mockResolvedValue({ success: true, stdout: '', stderr: '' }),
sshExec: vi.fn().mockResolvedValue({ success: true, result: '', exitCode: 0 }),
sshKeepalive: vi.fn().mockResolvedValue({ success: true }),
sshCreateShell: vi.fn().mockResolvedValue({ success: true, shellId: 'test-shell-1' }),
sshShellWrite: vi.fn().mockResolvedValue({ success: true }),
@@ -67,7 +67,9 @@ export const mockDesktopApi: DesktopApiContract = {
aiProviderDeleteKey: vi.fn().mockResolvedValue({ success: true }),
aiListModels: vi.fn().mockResolvedValue({ success: true, models: [] }),
aiComplete: vi.fn().mockResolvedValue({ success: true, text: '建议', model: 'test-model', redactedCount: 0 }),
aiTestProvider: vi.fn().mockResolvedValue({ success: true, status: 200, model: 'test-model', latencyMs: 88, answer: 'OK' }),
aiTestProvider: vi
.fn()
.mockResolvedValue({ success: true, status: 200, model: 'test-model', latencyMs: 88, answer: 'OK' }),
aiCatalogFetch: vi.fn().mockResolvedValue({ success: false, documents: [], errors: ['offline'] }),
// Dialog
@@ -113,6 +115,7 @@ export const mockDesktopApi: DesktopApiContract = {
// Event listeners
onShellData: vi.fn(),
onShellClosed: vi.fn(),
onConnectionClosed: vi.fn(),
onHostKeyPrompt: vi.fn(),
onMenuNewSession: vi.fn(),
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest'
import { analyzeAgentOutput } from '../../src/utils/agentOutput'
import { assessAgentCommandRisk } from '../../src/utils/agentCommandRisk'
describe('Agent command guardrail', () => {
it.each([
['df -h', 'safe'],
['journalctl -u nginx -n 100', 'safe'],
['custom-health-check --json', 'low'],
['sudo cp /tmp/a /etc/a', 'high'],
['systemctl restart nginx', 'high'],
['rm -rf /', 'critical'],
['sudo rm -r -f -- /', 'critical'],
['dd if=/dev/zero of=/dev/sda', 'critical'],
['find /tmp -delete', 'high'],
['cat /etc/os-release && systemctl restart nginx', 'high'],
])('classifies %s as %s', (command, expected) => {
expect(assessAgentCommandRisk(command)).toBe(expected)
})
})
describe('Agent analyze_output tool', () => {
it('keeps error evidence while bounding long output by line count', () => {
const lines = Array.from({ length: 160 }, (_, index) =>
index === 150 ? 'FATAL connection refused' : `normal line ${index}`
)
const result = analyzeAgentOutput(lines.join('\n'))
expect(result.totalLines).toBe(160)
expect(result.truncated).toBe(true)
expect(result.errorLines).toBe(1)
expect(result.text).toContain('FATAL connection refused')
expect(result.text).toContain('已省略 80 行')
})
})