DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(shell): SSH 远端体验重构——壳层管理面板 + 连接进度弹窗 + 行内双动作 + 切换器重做
Menghuan1918232218e38e20
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex a621dbb2..6a5eca69 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -367,5 +367,48 @@"remote.state.connecting": "Connecting","remote.state.connected": "Connected","remote.state.reconnecting": "Reconnecting",- "remote.state.given-up": "Failed"+ "remote.state.given-up": "Failed",+ "remote.section_local": "Current",+ "remote.section_machines": "Remote machines",+ "remote.section_actions": "Actions",+ "remote.current": "Current",+ "remote.open_new_window": "Open in new window",+ "remote.open_window_failed": "Failed to open the new window",+ "remote.step.handshake": "Handshake",+ "remote.step.installing": "Install",+ "remote.step.starting": "Start",+ "remote.step.probing": "Probe",+ "remote.connect.title": "Connecting to {{name}}",+ "remote.connect.working": "Connecting in progress; you may close this dialog and it continues in background.",+ "remote.connect.failed_title": "Connection failed",+ "remote.connect.retry": "Retry",+ "remote.form.host": "Host",+ "remote.form.name": "Name",+ "remote.form.id": "ID",+ "remote.form.port": "SSH port",+ "remote.form.user": "User",+ "remote.form.remote_port": "Remote web port",+ "remote.form.password": "Password",+ "remote.form.passphrase": "Key passphrase",+ "remote.form.color": "Color",+ "remote.form.tint_border": "Tint border",+ "remote.form.start_command": "Custom start command",+ "remote.form.start_command_hint": "Leave empty for the default",+ "remote.form.keep_blank": "blank = keep stored",+ "remote.form.host_required": "Host is required",+ "remote.form.id_invalid": "ID may only contain lowercase letters, digits and dashes, starting with a letter or digit",+ "remote.form.id_taken": "ID already taken",+ "remote.manager.title": "Remote machines",+ "remote.manager.subtitle": "Add, edit or remove SSH remote machines; changes apply immediately.",+ "remote.manager.add": "Add machine",+ "remote.manager.edit": "Edit {{name}}",+ "remote.manager.edit_action": "Edit",+ "remote.manager.remove_action": "Remove",+ "remote.manager.remove_title": "Remove this machine?",+ "remote.manager.remove_desc": "This removes \"{{name}}\" config and stored credentials; the remote environment is untouched.",+ "remote.manager.connect": "Connect",+ "remote.manager.disconnect": "Disconnect",+ "remote.manager.test": "Test",+ "remote.manager.empty": "No remote machines yet. Click \"Add machine\" to create one.",+ "buttons.close": "Close"}diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex 037e3b65..ad613fa2 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -367,5 +367,48 @@"remote.state.connecting": "连接中","remote.state.connected": "已连接","remote.state.reconnecting": "重连中",- "remote.state.given-up": "已放弃"+ "remote.state.given-up": "已放弃",+ "remote.section_local": "当前环境",+ "remote.section_machines": "远端机器",+ "remote.section_actions": "操作",+ "remote.current": "当前",+ "remote.open_new_window": "在新窗口中打开",+ "remote.open_window_failed": "打开新窗口失败",+ "remote.step.handshake": "握手",+ "remote.step.installing": "安装",+ "remote.step.starting": "启动",+ "remote.step.probing": "探测",+ "remote.connect.title": "正在连接 {{name}}",+ "remote.connect.working": "连接进行中,可关闭此窗口,连接会在后台继续。",+ "remote.connect.failed_title": "连接失败",+ "remote.connect.retry": "重试",+ "remote.form.host": "主机",+ "remote.form.name": "名称",+ "remote.form.id": "ID",+ "remote.form.port": "SSH 端口",+ "remote.form.user": "用户",+ "remote.form.remote_port": "远端 web 端口",+ "remote.form.password": "密码",+ "remote.form.passphrase": "密钥口令",+ "remote.form.color": "标识色",+ "remote.form.tint_border": "边框着色",+ "remote.form.start_command": "自定义启动命令",+ "remote.form.start_command_hint": "留空用默认启动命令",+ "remote.form.keep_blank": "留空 = 保留已存",+ "remote.form.host_required": "请填写主机",+ "remote.form.id_invalid": "ID 只能含小写字母、数字、连字符,且以字母或数字开头",+ "remote.form.id_taken": "ID 已被占用",+ "remote.manager.title": "远端机器",+ "remote.manager.subtitle": "新增、编辑或删除 SSH 远端机器;保存立即生效。",+ "remote.manager.add": "添加机器",+ "remote.manager.edit": "编辑 {{name}}",+ "remote.manager.edit_action": "编辑",+ "remote.manager.remove_action": "删除",+ "remote.manager.remove_title": "删除这台机器?",+ "remote.manager.remove_desc": "将删除「{{name}}」的配置与已存凭据,远端环境不受影响。",+ "remote.manager.connect": "连接",+ "remote.manager.disconnect": "断开",+ "remote.manager.test": "测试",+ "remote.manager.empty": "还没有远端机器,点「添加机器」创建第一台。",+ "buttons.close": "关闭"}diff --git a/src/layout/components/connect-dialog.test.tsx b/src/layout/components/connect-dialog.test.tsxnew file mode 100644index 00000000..6478a18b--- /dev/null+++ b/src/layout/components/connect-dialog.test.tsx@@ -0,0 +1,77 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { bindSshApiForTests, disposeRemoteForTests, remote } from '@/store/modules/remote'+import { ConnectDialog } from './connect-dialog'++// i18n 直通(key 即文案)+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string, params?: Record<string, unknown>) => params?.name !== undefined ? `${key}:${String(params.name)}` : key }),+}))++beforeEach(() => {+ disposeRemoteForTests()+})++afterEach(() => {+ cleanup()+ disposeRemoteForTests()+})++describe('connectDialog 连接进度弹窗', () => {+ it('pending 时打开:标题含机器名、步骤条只显示走过的阶段、日志尾呈现', async () => {+ remote.machines = [{ id: 'm1', name: 'alpha', state: 'connecting', progress: { phase: 'installing' } }]+ remote.pendingId = 'm1'+ remote.connectTrail = ['handshake', 'installing']+ remote.connectLog = ['[handshake] ssh ok', '[installing] download 42%']+ render(<ConnectDialog />)+ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())+ expect(screen.getByText('remote.connect.title:alpha')).toBeTruthy()+ const steps = screen.getByTestId('connect-steps')+ expect(steps.textContent).toContain('remote.step.handshake')+ expect(steps.textContent).toContain('remote.step.installing')+ // 未走过的阶段不出现+ expect(steps.textContent).not.toContain('remote.step.starting')+ expect(screen.getByText('[installing] download 42%')).toBeTruthy()+ expect(screen.getByText('remote.connect.working')).toBeTruthy()+ })++ it('无 pending 且无失败定格:不渲染弹窗', () => {+ render(<ConnectDialog />)+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('失败定格:直接原因 + 重试按钮(重试重新发起连接)', async () => {+ const connectSpy = vi.fn(() => new Promise<{ tunnelBaseUrl: string }>(() => {}))+ bindSshApiForTests({+ listMachines: vi.fn(async () => [{ id: 'm1', name: 'alpha', state: 'given-up' as const, lastError: 'boom' }]),+ connect: connectSpy,+ disconnect: vi.fn(async () => undefined),+ })+ remote.machines = [{ id: 'm1', name: 'alpha', state: 'given-up', lastError: 'boom' }]+ remote.connectFailed = { id: 'm1', error: 'dial tcp timeout' }+ remote.connectLog = ['[handshake] fail']+ render(<ConnectDialog />)+ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())+ expect(screen.getByText('remote.connect.failed_title')).toBeTruthy()+ expect(screen.getByText('dial tcp timeout')).toBeTruthy()+ fireEvent.click(screen.getByText('remote.connect.retry'))+ // 重试:失败定格清除并重新挂起连接+ await waitFor(() => expect(remote.connectFailed).toBeNull())+ expect(remote.pendingId).toBe('m1')+ await waitFor(() => expect(connectSpy).toHaveBeenCalledWith('m1'))+ })++ it('关闭(进行中):弹窗关闭、跟踪态清理,pending 语义不撤销', async () => {+ remote.machines = [{ id: 'm1', name: 'alpha', state: 'connecting' }]+ remote.pendingId = 'm1'+ remote.connectLog = ['[handshake] ssh ok']+ render(<ConnectDialog />)+ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ expect(remote.connectLog).toEqual([])+ // 关闭只是隐藏:连接挂起仍在(后台继续,就绪后自动切换)+ expect(remote.pendingId).toBe('m1')+ })+})diff --git a/src/layout/components/connect-dialog.tsx b/src/layout/components/connect-dialog.tsxnew file mode 100644index 00000000..b0441385--- /dev/null+++ b/src/layout/components/connect-dialog.tsx@@ -0,0 +1,98 @@+import { Button, Description, Modal, Spinner } from '@heroui/react'+import { useTranslation } from 'react-i18next'+import { If } from 'react-if-lite'+import { cn } from 'tailwind-variants'+import { useStore } from 'valtio-define'+import { Logs } from '@/components/logs'+import { store } from '@/store'++/**+ * 连接进度弹窗:点击未连接机器后实时呈现管线进度。+ *+ * 内容:阶段步骤条(只显示真实走过的阶段,当前阶段高亮)+ machine.events+ * 实时日志尾。成功即自动关闭(pendingId 清空);失败定格:直接原因 ++ * 已走阶段 + 日志全部保留,提供「重试 / 关闭」。进行中可关闭弹窗,+ * 连接在后台继续(不影响引擎侧)。+ */+export function ConnectDialog() {+ const { t } = useTranslation()+ const { machines, pendingId, connectFailed, connectTrail, connectLog, connectDismissed } = useStore(store.remote)++ const targetId = pendingId ?? connectFailed?.id ?? null+ const machine = targetId === null ? undefined : machines.find(item => item.id === targetId)+ // 进行中手动关过则隐藏到落定;失败定格始终可见+ const isOpen = connectFailed !== null || (pendingId !== null && !connectDismissed)+ const failed = connectFailed !== null+ // 当前阶段:列表行的 live progress(落定即消失,trail 最后一项兜底)+ const currentPhase = machine?.progress?.phase ?? (failed ? undefined : connectTrail[connectTrail.length - 1])++ function handleRetry() {+ if (connectFailed === null)+ return+ store.remote.dismissConnect()+ store.remote.switchTo(connectFailed.id)+ }++ return (+ <Modal+ isOpen={isOpen}+ onOpenChange={(open: boolean) => {+ if (!open)+ store.remote.dismissConnect()+ }}+ >+ <Modal.Backdrop>+ <Modal.Container size="sm">+ <Modal.Dialog>+ <Modal.CloseTrigger />+ <Modal.Header className="mb-2">+ <Modal.Heading>+ {failed ? t('remote.connect.failed_title') : t('remote.connect.title', { name: machine?.name ?? '' })}+ </Modal.Heading>+ </Modal.Header>+ <Modal.Body className="space-y-3">+ {/* 阶段步骤条:仅真实走过的阶段 */}+ <If cond={connectTrail.length > 0 || currentPhase !== undefined}>+ <div className="flex items-center gap-1.5" data-testid="connect-steps">+ {(connectTrail.length > 0 ? connectTrail : currentPhase !== undefined ? [currentPhase] : []).map((phase, index, all) => (+ // 阶段可能重复出现(重试),以序位区分 key+ // eslint-disable-next-line react/no-array-index-key+ <span+ key={`${phase}-${index}`}+ className={cn(+ 'rounded-md px-2 py-0.5 text-xs',+ index === all.length - 1 && !failed ? 'bg-accent/10 text-accent' : 'bg-panel2 text-muted',+ )}+ >+ {t(`remote.step.${phase}`)}+ </span>+ ))}+ </div>+ </If>+ <If cond={failed}>+ <Description className="text-danger break-all">{connectFailed?.error}</Description>+ </If>+ <Logs logs={connectLog} bodyClassName="max-h-[160px]" />+ <If cond={!failed}>+ <Description className="flex items-center gap-1.5">+ <Spinner className="size-3" />+ {t('remote.connect.working')}+ </Description>+ </If>+ </Modal.Body>+ <If cond={failed}>+ <Modal.Footer>+ <Button className="rounded-md" variant="tertiary" onPress={() => store.remote.dismissConnect()}>+ {t('buttons.close')}+ </Button>+ <Button className="rounded-md" variant="primary" onPress={handleRetry}>+ {t('remote.connect.retry')}+ </Button>+ </Modal.Footer>+ </If>+ </Modal.Dialog>+ </Modal.Container>+ </Modal.Backdrop>+ </Modal>+ )+}diff --git a/src/layout/components/remote-manager.test.tsx b/src/layout/components/remote-manager.test.tsxnew file mode 100644index 00000000..0859fb4f--- /dev/null+++ b/src/layout/components/remote-manager.test.tsx@@ -0,0 +1,153 @@+// @vitest-environment jsdom+import type { SshMachineRow } from '@/store/modules/remote'+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { bindSshApiForTests, disposeRemoteForTests, remote } from '@/store/modules/remote'+import { RemoteManager } from './remote-manager'++// jsdom 未实现 CSS.escape(react-aria 可选集合依赖)+if (typeof globalThis.CSS === 'undefined') {+ Object.assign(globalThis, {+ CSS: {+ escape: (value: string) => value.replace(/[^\w-]/g, c => `\\${c}`),+ },+ })+}++// i18n 直通(key 即文案,插值拼后缀便于断言)+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, params?: Record<string, unknown>) =>+ params?.name !== undefined ? `${key}:${String(params.name)}` : key,+ }),+}))+const toastSpy = vi.fn()+const invokeSpy = vi.fn(async (..._args: unknown[]) => undefined)+vi.mock('@/utils/toast', () => ({+ toast: (...args: unknown[]) => { toastSpy(...args) },+}))+vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => invokeSpy(...args),+}))++function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {+ return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }+}++let engineMachines: SshMachineRow[] = []+const saveSpy = vi.fn(async (..._args: unknown[]) => undefined)+const removeSpy = vi.fn(async () => undefined)+const testSpy = vi.fn(async () => ({ ok: true, banner: 'Linux alpha' }))++function bindEngine() {+ saveSpy.mockClear()+ removeSpy.mockClear()+ testSpy.mockClear()+ bindSshApiForTests({+ listMachines: vi.fn(async () => engineMachines),+ connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),+ disconnect: vi.fn(async () => undefined),+ save: saveSpy as never,+ remove: removeSpy,+ test: testSpy,+ })+}++beforeEach(() => {+ disposeRemoteForTests()+ toastSpy.mockClear()+ invokeSpy.mockClear()+ engineMachines = []+ bindEngine()+})++afterEach(() => {+ cleanup()+ disposeRemoteForTests()+})++function seed(machines: SshMachineRow[]) {+ engineMachines = machines+ remote.machines = machines+}++describe('remoteManager 壳层管理面板', () => {+ it('列表:名称 + user@host:port + 状态;未连接行有连接/编辑/删除动作', async () => {+ seed([machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1', port: 22, user: 'root' })])+ render(<RemoteManager isOpen={true} onClose={() => {}} />)+ await waitFor(() => expect(screen.getByTestId('manager-m1')).toBeTruthy())+ const row = screen.getByTestId('manager-m1')+ expect(row.textContent).toContain('alpha')+ expect(row.textContent).toContain('[email protected]:22')+ expect(row.textContent).toContain('remote.state.disconnected')+ expect(within(row).getByRole('button', { name: 'remote.manager.connect' })).toBeTruthy()+ expect(within(row).getByRole('button', { name: 'remote.manager.edit_action' })).toBeTruthy()+ expect(within(row).getByRole('button', { name: 'remote.manager.remove_action' })).toBeTruthy()+ })++ it('添加:主机派生 ID(撞名 -2 避让),手改 ID 后停止派生;主机空禁用保存', async () => {+ seed([machineOf({ id: 'dev', name: 'dev' })])+ render(<RemoteManager isOpen={true} onClose={() => {}} />)+ fireEvent.click(screen.getByText('remote.manager.add'))+ const form = await screen.findByTestId('machine-form')+ const hostInput = within(form).getByLabelText('remote.form.host')+ const idInput = within(form).getByLabelText('remote.form.id') as HTMLInputElement+ const saveButton = within(form).getByText('buttons.save').closest('button')!+ // 空主机:保存禁用 + 必填提示+ expect(saveButton.hasAttribute('disabled')).toBe(true)+ fireEvent.change(hostInput, { target: { value: 'ops@dev' } })+ expect(idInput.value).toBe('dev-2')+ expect(saveButton.hasAttribute('disabled')).toBe(false)+ // 手改 ID 后主机变更不再派生+ fireEvent.change(idInput, { target: { value: 'my-box' } })+ fireEvent.change(hostInput, { target: { value: '10.2.2.2' } })+ expect(idInput.value).toBe('my-box')+ // 提交:save 信封 + 名称回退主机+ fireEvent.click(saveButton)+ await waitFor(() => expect(saveSpy).toHaveBeenCalled())+ const [profile] = saveSpy.mock.calls[0] as [Record<string, unknown>]+ expect(profile).toMatchObject({ id: 'my-box', name: '10.2.2.2', host: '10.2.2.2' })+ // 保存成功表单收起+ await waitFor(() => expect(screen.queryByTestId('machine-form')).toBeNull())+ })++ it('编辑:表单回填已存字段,敏感值留空=不传(保留已存)', async () => {+ seed([machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1', port: 22, user: 'root', remotePort: 3081, color: '#123456', hasPassword: true })])+ render(<RemoteManager isOpen={true} onClose={() => {}} />)+ fireEvent.click(within(screen.getByTestId('manager-m1')).getByRole('button', { name: 'remote.manager.edit_action' }))+ const form = await screen.findByTestId('machine-form')+ expect((within(form).getByLabelText('remote.form.host') as HTMLInputElement).value).toBe('10.1.1.1')+ expect((within(form).getByLabelText('remote.form.user') as HTMLInputElement).value).toBe('root')+ // 已存密码:placeholder 提示留空保留+ expect((within(form).getByLabelText('remote.form.password') as HTMLInputElement).placeholder).toBe('remote.form.keep_blank')+ // 编辑态无 ID 字段+ expect(within(form).queryByLabelText('remote.form.id')).toBeNull()+ fireEvent.click(within(form).getByText('buttons.save'))+ await waitFor(() => expect(saveSpy).toHaveBeenCalled())+ const [profile, secrets] = saveSpy.mock.calls[0] as [Record<string, unknown>, Record<string, unknown>]+ expect(profile).toMatchObject({ id: 'm1', name: 'alpha', host: '10.1.1.1', port: 22, user: 'root', remotePort: 3081, color: '#123456' })+ expect(secrets).toEqual({})+ })++ it('删除:确认弹窗后才 remove,成功后行消失', async () => {+ seed([machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1' })])+ render(<RemoteManager isOpen={true} onClose={() => {}} />)+ fireEvent.click(within(screen.getByTestId('manager-m1')).getByRole('button', { name: 'remote.manager.remove_action' }))+ const dialog = await screen.findByRole('alertdialog')+ expect(dialog.textContent).toContain('remote.manager.remove_desc:alpha')+ expect(removeSpy).not.toHaveBeenCalled()+ fireEvent.click(within(dialog).getByText('buttons.confirm'))+ await waitFor(() => expect(removeSpy).toHaveBeenCalledWith('m1'))+ })++ it('已连接行:断开与新窗口动作;新窗口发 remote_open_window', async () => {+ seed([machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])+ render(<RemoteManager isOpen={true} onClose={() => {}} />)+ const row = await screen.findByTestId('manager-m1')+ expect(within(row).getByRole('button', { name: 'remote.manager.disconnect' })).toBeTruthy()+ fireEvent.click(within(row).getByRole('button', { name: 'remote.open_new_window' }))+ await waitFor(() => {+ expect(invokeSpy).toHaveBeenCalledWith('remote_open_window', { machineId: 'm1', url: 'http://127.0.0.1:4001' })+ })+ })+})diff --git a/src/layout/components/remote-manager.tsx b/src/layout/components/remote-manager.tsxnew file mode 100644index 00000000..c414e1de--- /dev/null+++ b/src/layout/components/remote-manager.tsx@@ -0,0 +1,398 @@+import type { SshMachineRow } from '@/store/modules/remote'+import { ArrowUpRightFromSquare, PencilToSquare, PlugConnection, Plus, Power, TrashBin } from '@gravity-ui/icons'+import { Button, Description, Input, Label, Modal, Switch } from '@heroui/react'+import { useOverlay } from '@overlastic/react'+import { invoke } from '@tauri-apps/api/core'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { If } from 'react-if-lite'+import { cn } from 'tailwind-variants'+import { useStore } from 'valtio-define'+import { Modal as ConfirmModal } from '@/components/modal'+import { store } from '@/store'+import { dotClassOf, dotStyleOf, sshApi } from '@/store/modules/remote'+import { toast } from '@/utils/toast'++/** ID 合法性:小写字母/数字/连字符,字母或数字开头(与 ssh-ui 同一规则)。 */+const ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/u++/** 从主机派生 ID:剥掉 user@ 前缀后取小写 slug;空结果兜底 'machine'。 */+function slugOf(host: string): string {+ const slug = host+ .trim()+ .toLowerCase()+ .replace(/^.*@/u, '')+ .replace(/[^a-z0-9-]+/gu, '-')+ .replace(/^-+|-+$/gu, '')+ return slug === '' ? 'machine' : slug+}++/** 占用避让:id 已存在时 -2/-3 递增。 */+function freeIdOf(base: string, taken: readonly string[]): string {+ if (!taken.includes(base))+ return base+ for (let index = 2; ; index += 1) {+ const candidate = `${base}-${index}`+ if (!taken.includes(candidate))+ return candidate+ }+}++interface FormState {+ id: string+ idTouched: boolean+ name: string+ host: string+ port: string+ user: string+ remotePort: string+ color: string+ tintBorder: boolean+ startCommand: string+ password: string+ passphrase: string+}++function formOf(machine?: SshMachineRow, taken: readonly string[] = []): FormState {+ const host = machine?.host ?? ''+ return {+ id: machine?.id ?? freeIdOf(slugOf(host), taken),+ idTouched: false,+ name: machine?.name ?? '',+ host,+ port: machine?.port !== undefined ? String(machine.port) : '',+ user: machine?.user ?? '',+ remotePort: machine?.remotePort !== undefined ? String(machine.remotePort) : '',+ color: machine?.color ?? '',+ tintBorder: machine?.tintBorder === true,+ startCommand: machine?.startCommand ?? '',+ password: '',+ passphrase: '',+ }+}++/** 表单校验:主机必填;新增时 ID 合法且不占用。返回 locale key 或 null。 */+function formErrorOf(form: FormState, isNew: boolean, taken: readonly string[]): string | null {+ if (form.host.trim() === '')+ return 'remote.form.host_required'+ if (isNew) {+ if (!ID_PATTERN.test(form.id))+ return 'remote.form.id_invalid'+ if (taken.includes(form.id))+ return 'remote.form.id_taken'+ }+ return null+}++/**+ * 壳层原生远端机器管理面板:切换器「管理机器…」直达。+ *+ * 列表即态:色点/名称/连接目标/连接状态 + 行内动作(连接或断开、新窗口、+ * 编辑、删除——删除经确认对话框且立即生效)。表单内联展开(顶部),新增时+ * ID 从主机自动派生(手改后停止);保存立即落盘(敏感值留空=保留已存),+ * 全部经 `/api-ssh` 数据面(sshApi),成功后远端列表随轮询刷新。+ */+export function RemoteManager({ isOpen, onClose }: { isOpen: boolean, onClose: () => void }) {+ const { t } = useTranslation()+ const { machines, activeId } = useStore(store.remote)+ const [dialogHolder, openConfirm] = useOverlay(ConfirmModal, { type: 'holder' })+ /** 'new' 或机器 id;null = 收起表单 */+ const [editing, setEditing] = useState<string | null>(null)+ const [form, setForm] = useState<FormState>(() => formOf())+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [testResult, setTestResult] = useState<string | null>(null)++ const isNew = editing === 'new'+ const editingRow = isNew ? undefined : machines.find(machine => machine.id === editing)+ const takenIds = machines.map(machine => machine.id)+ const formError = editing === null ? null : formErrorOf(form, isNew, takenIds)++ function openForm(target: 'new' | SshMachineRow) {+ setEditing(target === 'new' ? 'new' : target.id)+ setForm(formOf(target === 'new' ? undefined : target, takenIds))+ setError(null)+ setTestResult(null)+ }++ function patchForm(patch: Partial<FormState>) {+ setForm((previous) => {+ const next = { ...previous, ...patch }+ // 主机变更且未手改 ID:跟随派生+ if (patch.host !== undefined && !next.idTouched && isNew)+ next.id = freeIdOf(slugOf(patch.host), takenIds)+ return next+ })+ setTestResult(null)+ }++ async function handleSave() {+ if (editing === null || formError !== null)+ return+ setBusy(true)+ setError(null)+ try {+ await sshApi().save({+ id: form.id,+ name: form.name.trim() === '' ? form.host.trim() : form.name.trim(),+ host: form.host.trim(),+ ...form.port.trim() !== '' && Number(form.port) > 0 ? { port: Number(form.port) } : {},+ ...form.user.trim() !== '' ? { user: form.user.trim() } : {},+ ...form.remotePort.trim() !== '' && Number(form.remotePort) > 0 ? { remotePort: Number(form.remotePort) } : {},+ ...form.color.trim() !== '' ? { color: form.color.trim() } : {},+ ...form.tintBorder ? { tintBorder: true } : {},+ ...form.startCommand.trim() !== '' ? { startCommand: form.startCommand.trim() } : {},+ }, {+ ...form.password !== '' ? { password: form.password } : {},+ ...form.passphrase !== '' ? { passphrase: form.passphrase } : {},+ })+ setEditing(null)+ await store.remote.refresh()+ }+ catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ }+ finally {+ setBusy(false)+ }+ }++ async function handleTest() {+ if (editing === null)+ return+ setBusy(true)+ setTestResult(null)+ try {+ // 探测针对已存机器(新增需先保存)+ const result = await sshApi().test(form.id)+ setTestResult(result.ok ? (result.banner ?? 'ok') : 'failed')+ }+ catch (err) {+ setTestResult(err instanceof Error ? err.message : String(err))+ }+ finally {+ setBusy(false)+ }+ }++ async function handleRemove(machine: SshMachineRow) {+ try {+ await openConfirm({+ status: 'danger',+ title: t('remote.manager.remove_title'),+ description: <p>{t('remote.manager.remove_desc', { name: machine.name })}</p>,+ })+ }+ catch {+ return+ }+ try {+ await sshApi().remove(machine.id)+ if (editing === machine.id)+ setEditing(null)+ await store.remote.refresh()+ }+ catch (err) {+ toast(err instanceof Error ? err.message : String(err), {})+ }+ }++ function handleOpenWindow(machine: SshMachineRow) {+ if (machine.tunnelBaseUrl === undefined)+ return+ invoke('remote_open_window', { machineId: machine.id, url: machine.tunnelBaseUrl })+ .catch((err: unknown) => {+ toast(t('remote.open_window_failed'), {})+ console.warn('[remote] open window failed:', err)+ })+ }++ const fieldClass = 'h-8 rounded-md text-xs'++ return (+ <Modal+ isOpen={isOpen}+ onOpenChange={(open: boolean) => {+ if (!open)+ onClose()+ }}+ >+ {dialogHolder}+ <Modal.Backdrop>+ <Modal.Container size="lg">+ <Modal.Dialog>+ <Modal.CloseTrigger />+ <Modal.Header className="mb-3">+ <Modal.Heading>{t('remote.manager.title')}</Modal.Heading>+ </Modal.Header>+ <Modal.Body className="space-y-3">+ <div className="flex items-center justify-between">+ <Description>{t('remote.manager.subtitle')}</Description>+ <Button+ className="rounded-md"+ size="sm"+ variant="primary"+ isDisabled={editing !== null}+ onPress={() => openForm('new')}+ >+ <Plus className="size-3.5" />+ {t('remote.manager.add')}+ </Button>+ </div>++ {/* 内联表单:新增/编辑 */}+ <If cond={editing !== null}>+ <div className="space-y-2.5 rounded-lg border border-line bg-panel2/50 p-3" data-testid="machine-form">+ <Label className="text-xs font-medium text-ink">+ {isNew ? t('remote.manager.add') : t('remote.manager.edit', { name: editingRow?.name ?? '' })}+ </Label>+ <div className="grid grid-cols-2 gap-2.5">+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">+ {t('remote.form.host')}+ {' '}+ *+ </span>+ <Input variant="secondary" className={fieldClass} value={form.host} aria-label={t('remote.form.host')} onChange={e => patchForm({ host: e.target.value })} />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.name')}</span>+ <Input variant="secondary" className={fieldClass} value={form.name} aria-label={t('remote.form.name')} placeholder={form.host} onChange={e => patchForm({ name: e.target.value })} />+ </label>+ <If cond={isNew}>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.id')}</span>+ <Input variant="secondary" className={cn(fieldClass, 'font-mono')} value={form.id} aria-label={t('remote.form.id')} onChange={e => patchForm({ id: e.target.value, idTouched: true })} />+ </label>+ </If>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.port')}</span>+ <Input variant="secondary" type="number" className={cn(fieldClass, '[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none')} value={form.port} aria-label={t('remote.form.port')} placeholder="22" onChange={e => patchForm({ port: e.target.value })} />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.user')}</span>+ <Input variant="secondary" className={fieldClass} value={form.user} aria-label={t('remote.form.user')} onChange={e => patchForm({ user: e.target.value })} />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.remote_port')}</span>+ <Input variant="secondary" type="number" className={cn(fieldClass, '[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none')} value={form.remotePort} aria-label={t('remote.form.remote_port')} placeholder="3081" onChange={e => patchForm({ remotePort: e.target.value })} />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.password')}</span>+ <Input variant="secondary" type="password" className={fieldClass} value={form.password} aria-label={t('remote.form.password')} placeholder={!isNew && editingRow?.hasPassword === true ? t('remote.form.keep_blank') : ''} onChange={e => patchForm({ password: e.target.value })} />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.passphrase')}</span>+ <Input variant="secondary" type="password" className={fieldClass} value={form.passphrase} aria-label={t('remote.form.passphrase')} placeholder={!isNew && editingRow?.hasPassphrase === true ? t('remote.form.keep_blank') : ''} onChange={e => patchForm({ passphrase: e.target.value })} />+ </label>+ <label className="flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.color')}</span>+ <span className="flex items-center gap-1.5">+ <span aria-hidden="true" className="size-4 shrink-0 rounded-full border border-line" style={form.color !== '' ? { backgroundColor: form.color } : undefined} />+ <Input variant="secondary" className={cn(fieldClass, 'font-mono')} value={form.color} aria-label={t('remote.form.color')} placeholder="#7c5cff" onChange={e => patchForm({ color: e.target.value })} />+ </span>+ </label>+ <span className="flex items-end pb-1">+ <Switch isSelected={form.tintBorder} aria-label={t('remote.form.tint_border')} onChange={selected => patchForm({ tintBorder: selected })}>+ <Switch.Content>+ <Switch.Control>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Content>+ </Switch>+ <span className="ml-2 text-xs text-muted">{t('remote.form.tint_border')}</span>+ </span>+ <label className="col-span-2 flex flex-col gap-1">+ <span className="text-xs text-muted">{t('remote.form.start_command')}</span>+ <Input variant="secondary" className={cn(fieldClass, 'font-mono')} value={form.startCommand} aria-label={t('remote.form.start_command')} placeholder={t('remote.form.start_command_hint')} onChange={e => patchForm({ startCommand: e.target.value })} />+ </label>+ </div>+ <If cond={formError !== null}>+ <Description className="text-danger">{t(formError ?? '')}</Description>+ </If>+ <If cond={error !== null}>+ <Description className="text-danger break-all">{error}</Description>+ </If>+ <If cond={testResult !== null}>+ <Description className="break-all">{testResult}</Description>+ </If>+ <div className="flex items-center justify-end gap-2">+ <If cond={!isNew}>+ <Button className="rounded-md" size="sm" variant="ghost" isDisabled={busy} onPress={() => { void handleTest() }}>+ {t('remote.manager.test')}+ </Button>+ </If>+ <Button className="rounded-md" size="sm" variant="tertiary" isDisabled={busy} onPress={() => setEditing(null)}>+ {t('buttons.cancel')}+ </Button>+ <Button className="rounded-md" size="sm" variant="primary" isDisabled={busy || formError !== null} onPress={() => { void handleSave() }}>+ {t('buttons.save')}+ </Button>+ </div>+ </div>+ </If>++ {/* 机器列表 */}+ <If cond={machines.length === 0 && editing === null}>+ <Description className="py-4 text-center">{t('remote.manager.empty')}</Description>+ </If>+ <div className="flex flex-col gap-1.5">+ {machines.map(machine => (+ <div key={machine.id} className="flex items-center gap-2.5 rounded-lg border border-line px-3 py-2" data-testid={`manager-${machine.id}`}>+ <span+ aria-hidden="true"+ className={cn('size-2 shrink-0 rounded-full', machine.id === activeId ? 'bg-success' : dotClassOf(machine))}+ style={machine.id === activeId ? undefined : dotStyleOf(machine)}+ />+ <span className="flex min-w-0 flex-1 flex-col">+ <Label className="truncate text-sm">{machine.name}</Label>+ <Description className="truncate text-[11px] leading-4">+ {machine.host !== undefined ? `${machine.user !== undefined ? `${machine.user}@` : ''}${machine.host}${machine.port !== undefined ? `:${machine.port}` : ''}` : machine.id}+ </Description>+ </span>+ <Description className="shrink-0">{t(`remote.state.${machine.state}`)}</Description>+ <span className="flex shrink-0 items-center gap-1">+ <If+ cond={machine.state === 'connected'}+ else={(+ <Button+ isIconOnly+ aria-label={t('remote.manager.connect')}+ className="size-7 rounded-md"+ size="sm"+ variant="ghost"+ onPress={() => {+ store.remote.switchTo(machine.id)+ onClose()+ }}+ >+ <PlugConnection className="size-3.5" />+ </Button>+ )}+ >+ <Button isIconOnly aria-label={t('remote.manager.disconnect')} className="size-7 rounded-md" size="sm" variant="ghost" onPress={() => { void store.remote.disconnect(machine.id) }}>+ <Power className="size-3.5" />+ </Button>+ </If>+ <If cond={machine.state === 'connected' && machine.tunnelBaseUrl !== undefined}>+ <Button isIconOnly aria-label={t('remote.open_new_window')} className="size-7 rounded-md" size="sm" variant="ghost" onPress={() => handleOpenWindow(machine)}>+ <ArrowUpRightFromSquare className="size-3.5" />+ </Button>+ </If>+ <Button isIconOnly aria-label={t('remote.manager.edit_action')} className="size-7 rounded-md" size="sm" variant="ghost" onPress={() => openForm(machine)}>+ <PencilToSquare className="size-3.5" />+ </Button>+ <Button isIconOnly aria-label={t('remote.manager.remove_action')} className="size-7 rounded-md text-danger" size="sm" variant="ghost" onPress={() => { void handleRemove(machine) }}>+ <TrashBin className="size-3.5" />+ </Button>+ </span>+ </div>+ ))}+ </div>+ </Modal.Body>+ </Modal.Dialog>+ </Modal.Container>+ </Modal.Backdrop>+ </Modal>+ )+}diff --git a/src/layout/components/remote-switcher.test.tsx b/src/layout/components/remote-switcher.test.tsxindex 4e6da5c7..2418e0b1 100644--- a/src/layout/components/remote-switcher.test.tsx+++ b/src/layout/components/remote-switcher.test.tsx@@ -19,9 +19,14 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}))const toastSpy = vi.fn()+const manageSpy = vi.fn()+const invokeSpy = vi.fn(async (..._args: unknown[]) => undefined)vi.mock('@/utils/toast', () => ({toast: (...args: unknown[]) => { toastSpy(...args) },}))+vi.mock('@tauri-apps/api/core', () => ({+ invoke: (...args: unknown[]) => invokeSpy(...args),+}))function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }@@ -65,6 +70,8 @@ function seedMachines(machines: SshMachineRow[]) {beforeEach(() => {disposeRemoteForTests()toastSpy.mockClear()+ manageSpy.mockClear()+ invokeSpy.mockClear()engineMachines = []engineUnreachable = falsebindEngine()@@ -77,8 +84,8 @@ afterEach(() => {})describe('remoteSwitcher 渲染', () => {- it('空态:本地项 + 空态引导 + 管理入口(toast 引导到内嵌设置页)', async () => {- render(<RemoteSwitcher />)+ it('空态:本地项 + 空态引导 + 管理入口(打开壳层管理面板)', async () => {+ render(<RemoteSwitcher onManage={manageSpy} />)await openMenu()const menu = screen.getByRole('menu')expect(within(menu).getByText('remote.local')).toBeTruthy()@@ -86,7 +93,7 @@ describe('remoteSwitcher 渲染', () => {fireEvent.click(within(menu).getByText('remote.manage'))await waitFor(() => {- expect(toastSpy).toHaveBeenCalledWith('remote.manage_hint', {})+ expect(manageSpy).toHaveBeenCalled()})})@@ -97,20 +104,20 @@ describe('remoteSwitcher 渲染', () => {machineOf({ id: 'amber', name: 'amber', state: 'connecting' }),machineOf({ id: 'red', name: 'red', state: 'given-up', lastError: 'connect failed after 3 attempt(s): refused' }),])- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)await openMenu()- const colored = screen.getByText('colored').closest('[class*="flex"]')?.querySelector('span')+ const colored = screen.getByText('colored').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')expect(colored?.getAttribute('style')).toContain('rgb(255, 0, 255)')- const green = screen.getByText('green').closest('[class*="flex"]')?.querySelector('span')+ const green = screen.getByText('green').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')expect(green?.className).toContain('bg-success')expect(screen.getByText('remote.state.connected')).toBeTruthy()- const amber = screen.getByText('amber').closest('[class*="flex"]')?.querySelector('span')+ const amber = screen.getByText('amber').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')expect(amber?.className).toContain('bg-warning')- const red = screen.getByText('red').closest('[class*="flex"]')?.querySelector('span')+ const red = screen.getByText('red').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')expect(red?.className).toContain('bg-danger')// 放弃态的原因入口(title 提示)expect(screen.getByText('red').closest('[title]')?.getAttribute('title')).toContain('refused')@@ -120,7 +127,7 @@ describe('remoteSwitcher 渲染', () => {seedMachines([machineOf({ id: 'm1', name: 'alpha', color: '#123456', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])remote.activeId = 'm1'remote.activeTunnelUrl = 'http://127.0.0.1:4001'- const { unmount } = render(<RemoteSwitcher />)+ const { unmount } = render(<RemoteSwitcher onManage={manageSpy} />)const trigger = screen.getByRole('button', { name: 'remote.switcher' })expect(trigger.textContent).toContain('alpha')// jsdom 将内联色归一为 rgb()(#123456 → rgb(18, 52, 86))@@ -129,7 +136,7 @@ describe('remoteSwitcher 渲染', () => {remote.activeId = nullremote.activeTunnelUrl = ''- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')})})@@ -137,7 +144,7 @@ describe('remoteSwitcher 渲染', () => {describe('remoteSwitcher 交互与降级', () => {it('点击已连接机器项:切换视图(activeId/隧道 URL)', async () => {seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)const menu = await openMenu()fireEvent.click(within(menu).getByText('alpha'))await waitFor(() => {@@ -151,7 +158,7 @@ describe('remoteSwitcher 交互与降级', () => {remote.activeId = 'm1'remote.activeTunnelUrl = 'http://127.0.0.1:4001'remote.pendingId = 'm1'- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)const menu = await openMenu()fireEvent.click(within(menu).getByText('remote.local'))await waitFor(() => {@@ -164,7 +171,7 @@ describe('remoteSwitcher 交互与降级', () => {it('本地实例不可达:降级提示 + 远端项禁用(不弹错误风暴),恢复后自动复原', async () => {seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])engineUnreachable = true- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)// boot 首刷即不可达 → 降级await vi.waitFor(() => {expect(remote.available).toBe(false)@@ -191,10 +198,10 @@ describe('remoteSwitcher 增强(4.4)', () => {seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])remote.activeId = 'm1'remote.activeTunnelUrl = 'http://127.0.0.1:4001'- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)const menu = await openMenu()- const dot = within(menu).getByText('alpha').closest('[class*="flex"]')?.querySelector('span')+ const dot = within(menu).getByText('alpha').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')expect(dot?.className).toContain('bg-success')fireEvent.click(within(menu).getByText('remote.disconnect_active'))@@ -207,7 +214,7 @@ describe('remoteSwitcher 增强(4.4)', () => {it('无活动机器时不出现断开项', async () => {seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)const menu = await openMenu()expect(within(menu).queryByText('remote.disconnect_active')).toBeNull()})@@ -217,11 +224,39 @@ describe('remoteSwitcher 增强(4.4)', () => {machineOf({ id: 'm1', name: 'alpha', state: 'reconnecting', nextRetryAt: Date.now() + 42_000 }),machineOf({ id: 'm2', name: 'beta', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002', authMethod: 'key' }),])- render(<RemoteSwitcher />)+ render(<RemoteSwitcher onManage={manageSpy} />)const menu = await openMenu()- const alpha = within(menu).getByText('alpha').closest('[class*="flex"]')+ const alpha = within(menu).getByText('alpha').closest('[role="menuitem"]')expect(alpha?.textContent).toContain('remote.retry_in')- const beta = within(menu).getByText('beta').closest('[class*="flex"]')+ const beta = within(menu).getByText('beta').closest('[role="menuitem"]')expect(beta?.textContent).toContain('remote.auth.key')})})++describe('remoteSwitcher 行内双动作(当前窗口 vs 新窗口)', () => {+ it('已连接机器行尾出现新窗口按钮:点击只发 remote_open_window,不触发切换', async () => {+ seedMachines([+ machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' }),+ machineOf({ id: 'm2', name: 'beta', state: 'disconnected' }),+ ])+ render(<RemoteSwitcher onManage={manageSpy} />)+ const menu = await openMenu()+ // 仅已连接行有按钮(title/aria 语义键)+ const buttons = within(menu).getAllByRole('button', { name: 'remote.open_new_window' })+ expect(buttons.length).toBe(1)+ fireEvent.click(buttons[0]!)+ await waitFor(() => {+ expect(invokeSpy).toHaveBeenCalledWith('remote_open_window', { machineId: 'm1', url: 'http://127.0.0.1:4001' })+ })+ // 行本体语义未被连带触发:视图仍是本地+ expect(remote.activeId).toBeNull()+ expect(remote.pendingId).toBeNull()+ })++ it('机器行显示 user@host:port 副标题', async () => {+ seedMachines([machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1', port: 22, user: 'root', state: 'disconnected' })])+ render(<RemoteSwitcher onManage={manageSpy} />)+ const menu = await openMenu()+ expect(within(menu).getByText('[email protected]:22')).toBeTruthy()+ })+})diff --git a/src/layout/components/remote-switcher.tsx b/src/layout/components/remote-switcher.tsxindex ccb3b42f..9e7f4d68 100644--- a/src/layout/components/remote-switcher.tsx+++ b/src/layout/components/remote-switcher.tsx@@ -1,5 +1,7 @@-import { Globe } from '@gravity-ui/icons'+import type { SshMachineRow } from '@/store/modules/remote'+import { ArrowUpRightFromSquare, Gear, Globe, House, Power } from '@gravity-ui/icons'import { Button, Description, Dropdown, Label } from '@heroui/react'+import { invoke } from '@tauri-apps/api/core'import { useTranslation } from 'react-i18next'import { If } from 'react-if-lite'import { cn } from 'tailwind-variants'@@ -27,19 +29,35 @@ function stateTextOf(return text}+/** 行内副标题:`user@host:port`(信息不全时退化为已有字段)。 */+function subtitleOf(machine: SshMachineRow): string | undefined {+ if (machine.host === undefined)+ return undefined+ const target = `${machine.user !== undefined ? `${machine.user}@` : ''}${machine.host}${machine.port !== undefined ? `:${machine.port}` : ''}`+ return target+}++/** 新窗口打开远端(复用壳层 remote_open_window 命令;聚焦已有窗口)。 */+function openInNewWindow(machine: SshMachineRow, onError: (err: unknown) => void): void {+ if (machine.tunnelBaseUrl === undefined)+ return+ invoke('remote_open_window', { machineId: machine.id, url: machine.tunnelBaseUrl })+ .catch(onError)+}+/*** 导航栏远端机器切换器:本地实例 ↔ 各远端机器。** 数据面全部来自本地实例 `/api-ssh`(`useRemoteMachines` 启动秒级轮询 +- * 聚焦刷新);点击已连接机器直接切换视图,点击未连接机器发起连接、就绪后- * 自动切换;点击「本地」回到本地实例(不断开远端)。机器的增删改与断开- * 入口在内嵌 web 设置页的 SSH 面板(本组件只提供引导)。+ * 聚焦刷新);点击机器行=当前窗口切换(未连接则发起连接,进度弹窗实时+ * 呈现),行尾图标=新窗口打开(已连接机器可用)。管理入口在底部+ * 「管理机器…」(壳层原生面板)。** 色点语义(S3 词汇表):机器标识色优先 → 已连接绿 → 重连/进行中琥珀 →* 放弃红 → 其余中性灰;未连接行整体降不透明度。本地实例不可达时进入降级* 态:远端项禁用 + 顶部提示,恢复后自动复原(轮询静默重试,不弹错误)。*/-export function RemoteSwitcher() {+export function RemoteSwitcher({ onManage }: { onManage: () => void }) {const { t } = useTranslation()useRemoteMachines()const { machines, activeId, available, pendingId } = useStore(store.remote)@@ -47,10 +65,9 @@ export function RemoteSwitcher() {const activeMachine = machines.find(machine => machine.id === activeId)const activeColor = activeMachine?.color- function handleManage() {- // 机器管理唯一入口 = 内嵌 web 设置页的 SSH 面板(web 应用无 URL 路由,- // 壳层无法深链,给出路径引导)- toast(t('remote.manage_hint'), {})+ function handleOpenWindowError(err: unknown) {+ toast(t('remote.open_window_failed'), {})+ console.warn('[remote] open window failed:', err)}return (@@ -71,84 +88,120 @@ export function RemoteSwitcher() {/></If></Button>- <Dropdown.Popover className="rounded-md w-64!">+ <Dropdown.Popover className="rounded-lg w-72!"><Dropdown.Menu><If cond={!available}><Dropdown.Item className="rounded-md" id="remote-degraded" isDisabled textValue={t('remote.degraded')}><Description className="text-warning">{t('remote.degraded')}</Description></Dropdown.Item></If>- <Dropdown.Item- className="rounded-md"- id="remote-local"- textValue={t('remote.local')}- onAction={() => { store.remote.backToLocal() }}- >- <span className="flex w-full items-center gap-2">- <span- aria-hidden="true"- className={cn('size-1.5 rounded-full', activeMachine === undefined ? 'bg-success' : 'bg-line-strong')}- />- <Label>{t('remote.local')}</Label>- </span>- </Dropdown.Item>- <If cond={machines.length === 0}>- <Dropdown.Item className="rounded-md" id="remote-empty" isDisabled textValue={t('remote.empty')}>- <Description>{t('remote.empty')}</Description>- </Dropdown.Item>- </If>- {machines.map(machine => (+ <Dropdown.Section aria-label={t('remote.section_local')}><Dropdown.Item- key={machine.id}className="rounded-md"- id={`remote-${machine.id}`}- textValue={machine.name}- isDisabled={!available || pendingId !== null}- onAction={() => { store.remote.switchTo(machine.id) }}+ id="remote-local"+ textValue={t('remote.local')}+ onAction={() => { store.remote.backToLocal() }}>- <span- title={machine.lastError}- className={cn(- 'flex w-full items-center gap-2',- machine.state === 'connected' ? '' : 'opacity-60',- )}- >+ <span className="flex w-full items-center gap-2"><spanaria-hidden="true"- className={cn('size-1.5 shrink-0 rounded-full', machine.id === activeId ? 'bg-success' : dotClassOf(machine))}- style={machine.id === activeId ? undefined : dotStyleOf(machine)}+ className={cn('size-1.5 rounded-full', activeMachine === undefined ? 'bg-success' : 'bg-line-strong')}/>- <Label className="min-w-0 truncate">{machine.name}</Label>- {/* 待切换的机器在首轮轮询回报前尚无 connecting 状态:由- pendingId 立即给出「连接中」反馈,避免点了没反应 */}- <Description className={cn('ml-auto shrink-0', pendingId === machine.id && 'text-warning')}>- {stateTextOf(machine, pendingId === machine.id, t)}- </Description>+ <House className="size-3.5 text-muted" />+ <Label>{t('remote.local')}</Label>+ <If cond={activeId === null}>+ <Description className="ml-auto">{t('remote.current')}</Description>+ </If></span></Dropdown.Item>- ))}- {/* 活动远端连接的一键断开(视图先回本地,再向引擎发断开) */}- <If cond={activeId !== null}>+ </Dropdown.Section>+ <Dropdown.Section aria-label={t('remote.section_machines')}>+ <If cond={machines.length === 0}>+ <Dropdown.Item className="rounded-md" id="remote-empty" isDisabled textValue={t('remote.empty')}>+ <Description>{t('remote.empty')}</Description>+ </Dropdown.Item>+ </If>+ {machines.map((machine) => {+ const pending = pendingId === machine.id+ const connected = machine.state === 'connected' && machine.tunnelBaseUrl !== undefined+ return (+ <Dropdown.Item+ key={machine.id}+ className="rounded-md"+ id={`remote-${machine.id}`}+ textValue={machine.name}+ isDisabled={!available || pendingId !== null}+ onAction={() => { store.remote.switchTo(machine.id) }}+ >+ <span+ title={machine.lastError}+ className={cn(+ 'flex w-full items-center gap-2',+ connected ? '' : 'opacity-60',+ )}+ >+ <span+ aria-hidden="true"+ className={cn('size-1.5 shrink-0 rounded-full', machine.id === activeId ? 'bg-success' : dotClassOf(machine))}+ style={machine.id === activeId ? undefined : dotStyleOf(machine)}+ />+ <span className="flex min-w-0 flex-col">+ <Label className="truncate">{machine.name}</Label>+ <If cond={subtitleOf(machine) !== undefined}>+ <Description className="truncate text-[11px] leading-4">{subtitleOf(machine)}</Description>+ </If>+ </span>+ <Description className={cn('ml-auto shrink-0', pending && 'text-warning')}>+ {stateTextOf(machine, pending, t)}+ </Description>+ {/* 行尾双动作:行本体=当前窗口切换;图标=新窗口打开 */}+ <If cond={connected}>+ <Button+ isIconOnly+ aria-label={t('remote.open_new_window')}+ className="size-6 shrink-0 rounded-md text-muted hover:text-ink"+ size="sm"+ variant="ghost"+ onPress={() => { openInNewWindow(machine, handleOpenWindowError) }}+ >+ <ArrowUpRightFromSquare className="size-3.5" />+ </Button>+ </If>+ </span>+ </Dropdown.Item>+ )+ })}+ </Dropdown.Section>+ <Dropdown.Section aria-label={t('remote.section_actions')}>+ {/* 活动远端连接的一键断开(视图先回本地,再向引擎发断开) */}+ <If cond={activeId !== null}>+ <Dropdown.Item+ className="rounded-md"+ id="remote-disconnect-active"+ textValue={t('remote.disconnect_active')}+ onAction={() => {+ if (activeId !== null)+ void store.remote.disconnect(activeId)+ }}+ >+ <span className="flex w-full items-center gap-2 text-warning">+ <Power className="size-3.5" />+ <Label className="text-warning">{t('remote.disconnect_active')}</Label>+ </span>+ </Dropdown.Item>+ </If><Dropdown.ItemclassName="rounded-md"- id="remote-disconnect-active"- textValue={t('remote.disconnect_active')}- onAction={() => {- if (activeId !== null)- void store.remote.disconnect(activeId)- }}+ id="remote-manage"+ textValue={t('remote.manage')}+ onAction={onManage}>- <Label className="text-warning">{t('remote.disconnect_active')}</Label>+ <span className="flex w-full items-center gap-2">+ <Gear className="size-3.5 text-muted" />+ <Label>{t('remote.manage')}</Label>+ </span></Dropdown.Item>- </If>- <Dropdown.Item- className="rounded-md"- id="remote-manage"- textValue={t('remote.manage')}- onAction={handleManage}- >- <Label>{t('remote.manage')}</Label>- </Dropdown.Item>+ </Dropdown.Section></Dropdown.Menu></Dropdown.Popover></Dropdown>diff --git a/src/store/modules/remote/api.ts b/src/store/modules/remote/api.tsindex 826f760e..de38a87c 100644--- a/src/store/modules/remote/api.ts+++ b/src/store/modules/remote/api.ts@@ -5,13 +5,14 @@* POST /api-ssh { "method": "machine.list", "payload": {} }* → 200 { "ok": true, "value": ... } | { "ok": false, "error": {...} }*- * 壳层只用三个方法:`machine.list`(轮询)、`machine.connect`(切换到未连接- * 机器)、`machine.disconnect`(面板之外的断开入口,预留给后续壳层动作)。- * fetch 与基础 URL 均可注入,便于单测与复用。+ * 壳层消费:`machine.list`(轮询)、`machine.connect`/`machine.disconnect`+ * (切换与断开)、`machine.save`/`machine.remove`/`machine.test`(管理面板)、+ * `machine.events`(连接进度弹窗的实时日志)。fetch 与基础 URL 均可注入,+ * 便于单测与复用。* @module store/remote/api*/-import type { SshConnectionState, SshMachineListValue, SshMachineRow } from './types'+import type { SshConnectionState, SshEventEntry, SshMachineListValue, SshMachineProfile, SshMachineRow, SshProgress, SshSecrets } from './types'/** 一次请求信封。 */interface SshApiRequest {@@ -35,6 +36,14 @@ export interface SshApiClient {connect: (machineId: string) => Promise<{ tunnelBaseUrl: string }>/** `machine.disconnect`:主动断开(远端实例保持运行)。 */disconnect: (machineId: string) => Promise<void>+ /** `machine.save`:保存(新增/覆盖)手动机器;secrets 仅显式传入时更新。 */+ save: (machine: SshMachineProfile, secrets?: SshSecrets) => Promise<void>+ /** `machine.remove`:删除手动机器。 */+ remove: (machineId: string) => Promise<void>+ /** `machine.test`:快速 SSH 握手探测(不建隧道)。 */+ test: (machineId: string) => Promise<{ ok: boolean, banner?: string }>+ /** `machine.events`:增量事件日志(seq 游标)。 */+ events: (machineId: string, sinceSeq?: number) => Promise<{ items: SshEventEntry[] }>}/** 非法机器行兜底:缺 id/name/state 的行直接丢弃,不让坏数据进切换器。 */@@ -54,6 +63,13 @@ function machineRowOf(raw: unknown): SshMachineRow | undefined {name: value.name,...typeof value.color === 'string' && value.color !== '' ? { color: value.color } : {},...value.tintBorder === true ? { tintBorder: true } : {},+ ...typeof value.host === 'string' && value.host !== '' ? { host: value.host } : {},+ ...typeof value.port === 'number' ? { port: value.port } : {},+ ...typeof value.user === 'string' && value.user !== '' ? { user: value.user } : {},+ ...typeof value.remotePort === 'number' ? { remotePort: value.remotePort } : {},+ ...typeof value.startCommand === 'string' && value.startCommand !== '' ? { startCommand: value.startCommand } : {},+ ...value.hasPassword === true ? { hasPassword: true } : {},+ ...value.hasPassphrase === true ? { hasPassphrase: true } : {},state: value.state as SshConnectionState,...typeof value.tunnelBaseUrl === 'string' ? { tunnelBaseUrl: value.tunnelBaseUrl } : {},...typeof value.lastError === 'string' ? { lastError: value.lastError } : {},@@ -61,6 +77,25 @@ function machineRowOf(raw: unknown): SshMachineRow | undefined {...value.authMethod === 'agent' || value.authMethod === 'key' || value.authMethod === 'password'? { authMethod: value.authMethod }: {},+ ...progressOf(value.progress),+ }+}++/** progress 投影:phase 合法才保留,附带可选 attempt/total/log。 */+function progressOf(raw: unknown): { progress?: SshProgress } {+ if (typeof raw !== 'object' || raw === null)+ return {}+ const value = raw as Record<string, unknown>+ const PHASES: SshProgress['phase'][] = ['handshake', 'installing', 'starting', 'probing']+ if (!PHASES.includes(value.phase as SshProgress['phase']))+ return {}+ return {+ progress: {+ phase: value.phase as SshProgress['phase'],+ ...typeof value.attempt === 'number' ? { attempt: value.attempt } : {},+ ...typeof value.total === 'number' ? { total: value.total } : {},+ ...typeof value.log === 'string' ? { log: value.log } : {},+ },}}@@ -100,5 +135,16 @@ export function createSshApiClient(disconnect: async (machineId) => {await call<unknown>('machine.disconnect', { machineId })},+ /** 保存(新增/覆盖)一台手动机器;secrets 仅在显式传入时更新。 */+ save: async (machine: SshMachineProfile, secrets?: SshSecrets) => {+ await call<unknown>('machine.save', { machine, secrets })+ },+ remove: async (machineId) => {+ await call<unknown>('machine.remove', { machineId })+ },+ /** 快速 SSH 握手探测(不建隧道);失败时引擎错误消息即原因。 */+ test: machineId => call<{ ok: boolean, banner?: string }>('machine.test', { machineId }),+ /** 增量取事件日志(seq 游标;空数组 = 无新事件)。 */+ events: (machineId, sinceSeq = 0) => call<{ items: SshEventEntry[] }>('machine.events', { machineId, sinceSeq }),}}diff --git a/src/store/modules/remote/index.ts b/src/store/modules/remote/index.tsindex 9113e30b..18dce75c 100644--- a/src/store/modules/remote/index.ts+++ b/src/store/modules/remote/index.ts@@ -1,3 +1,3 @@export { borderTintOf, dotClassOf, dotStyleOf, reconcileSwitcher } from './logic'-export { bindSshApiForTests, disposeRemoteForTests, remote } from './store'-export type { SshMachineRow } from './types'+export { bindSshApiForTests, disposeRemoteForTests, remote, sshApi } from './store'+export type { SshMachineProfile, SshMachineRow, SshSecrets } from './types'diff --git a/src/store/modules/remote/store.test.ts b/src/store/modules/remote/store.test.tsindex 047cf86b..9c1f824c 100644--- a/src/store/modules/remote/store.test.ts+++ b/src/store/modules/remote/store.test.ts@@ -6,6 +6,16 @@ function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }}+/** 组一个按调用序返回快照序列的 listMachines mock(末张快照驻留)。 */+function bindListSequence(list: SshMachineRow[][]) {+ let call = 0+ return vi.fn(async () => {+ const snapshot = list[Math.min(call, list.length - 1)]+ call += 1+ return snapshot+ })+}+/** 注入可编程 mock 引擎:listMachines 按调用序返回快照序列。 */function bindEngine(options: {list: SshMachineRow[][]@@ -204,4 +214,53 @@ describe('remote store 切换语义', () => {expect(remote.activeTunnelUrl).toBe('')expect(remote.machines[0]?.state).toBe('disconnected')})++ it('连接进行中:累积走过的 progress 阶段 + 增量追加事件日志;成功自动复位', async () => {+ let release: () => void = () => {}+ bindSshApiForTests({+ listMachines: bindListSequence([+ [machineOf({ id: 'm1', state: 'disconnected' })],+ [machineOf({ id: 'm1', state: 'connecting', progress: { phase: 'installing' } })],+ [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })],+ ]),+ connect: vi.fn(() => new Promise<{ tunnelBaseUrl: string }>((resolve) => {+ release = () => resolve({ tunnelBaseUrl: 'http://127.0.0.1:4001' })+ })),+ disconnect: vi.fn(async () => undefined),+ events: vi.fn(async (_id: string, sinceSeq = 0) => ({+ items: sinceSeq === 0+ ? [{ seq: 0, line: '[handshake] ssh ok' }, { seq: 1, line: '[installing] download' }]+ : [],+ })),+ })+ await remote.refresh()+ remote.switchTo('m1')+ // 连接阻塞中:轮询 refresh 把 progress 阶段与事件增量累积进跟踪态+ await remote.refresh()+ expect(remote.connectTrail).toEqual(['installing'])+ expect(remote.connectLog).toEqual(['[handshake] ssh ok', '[installing] download'])+ // 就绪:切换完成,跟踪态自动复位(弹窗随 pendingId 清空关闭)+ release()+ await vi.waitFor(() => expect(remote.activeId).toBe('m1'))+ expect(remote.connectTrail).toEqual([])+ expect(remote.connectLog).toEqual([])+ expect(remote.connectFailed).toBeNull()+ })++ it('连接失败:定格目标与直接原因供进度弹窗呈现,dismissConnect 关闭清理', async () => {+ bindSshApiForTests({+ listMachines: vi.fn(async () => [machineOf({ id: 'm1', state: 'given-up', lastError: 'timeout' })]),+ connect: vi.fn(async () => { throw new Error('dial tcp timeout') }),+ disconnect: vi.fn(async () => undefined),+ events: vi.fn(async () => ({ items: [{ seq: 0, line: '[handshake] fail' }] })),+ })+ await remote.refresh()+ remote.switchTo('m1')+ await vi.waitFor(() => expect(remote.connectFailed).toEqual({ id: 'm1', error: 'dial tcp timeout' }))+ // 失败期间的事件日志保留在弹窗里(用户可见问题所在)+ await vi.waitFor(() => expect(remote.connectLog).toEqual(['[handshake] fail']))+ remote.dismissConnect()+ expect(remote.connectFailed).toBeNull()+ expect(remote.connectLog).toEqual([])+ })})diff --git a/src/store/modules/remote/store.ts b/src/store/modules/remote/store.tsindex 81f99388..a629e23c 100644--- a/src/store/modules/remote/store.ts+++ b/src/store/modules/remote/store.ts@@ -10,7 +10,8 @@* @module store/remote/store*/-import type { SshMachineRow } from './types'+import type { SshApiClient } from './api'+import type { SshMachineRow, SshProgressPhase } from './types'import { defineStore } from 'valtio-define'import { harness } from '../harness'import { createSshApiClient } from './api'@@ -19,6 +20,14 @@ import { reconcileSwitcher } from './logic'/** 轮询间隔(毫秒):秒级即可让切换器跟上连接/重连状态流转。 */const POLL_INTERVAL_MS = 2000+/** machine.events 增量游标(模块级,不属于 UI 状态)。 */+let eventSeq = 0++/** 引擎/网络错误的可读摘要(与 ssh-ui 的 messageOf 同语义)。 */+function messageOf(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}+/** 模块级轮询句柄(与 harness store 的定时器管理模式一致)。 */let pollTimer: ReturnType<typeof setInterval> | undefined@@ -28,13 +37,20 @@ let api = createSshApiClient(() => harness.$state.serviceUrl,)+/** 当前数据面客户端(管理面板复用同一实例;测试经 bindSshApiForTests 替换)。 */+export function sshApi(): SshApiClient {+ return api+}+/** 测试注入口:替换数据面客户端并复位切换状态(仅测试使用)。 */-export function bindSshApiForTests(client: {- listMachines: () => Promise<SshMachineRow[]>- connect: (machineId: string) => Promise<{ tunnelBaseUrl: string }>- disconnect: (machineId: string) => Promise<void>-}): void {- api = client+export function bindSshApiForTests(client: Partial<SshApiClient> & Pick<SshApiClient, 'listMachines' | 'connect' | 'disconnect'>): void {+ api = {+ save: async () => {},+ remove: async () => {},+ test: async () => ({ ok: true }),+ events: async () => ({ items: [] }),+ ...client,+ }}export const remote = defineStore({@@ -49,6 +65,14 @@ export const remote = defineStore({activeTunnelUrl: '',/** `/api-ssh` 是否可达;不可达时切换器降级(禁用远端项 + 提示)。 */available: true,+ /** 连接进度弹窗:本次连接实际走过的管线阶段(落定后保留供失败复盘)。 */+ connectTrail: [] as SshProgressPhase[],+ /** 连接进度弹窗:machine.events 实时日志尾(增量轮询追加)。 */+ connectLog: [] as string[],+ /** 连接失败定格:目标机器 + 直接原因(弹窗呈现与重试入口)。 */+ connectFailed: null as { id: string, error: string } | null,+ /** 进行中手动关了弹窗:隐藏到落定;失败时重新弹出(原因必须可见)。 */+ connectDismissed: false,/** 单飞标志:上一轮未完成时跳过本轮,避免请求堆积。 */refreshing: false,booted: false,@@ -85,6 +109,7 @@ export const remote = defineStore({this.pendingId = next.pendingIdthis.activeTunnelUrl = next.activeTunnelUrlthis.available = true+ await this.trackConnectProgress()}catch (err) {// 本地实例不可达(启动中/已停止):降级但保留既有列表,静默重试@@ -96,6 +121,37 @@ export const remote = defineStore({}},+ /** 连接进行中:累积实际走过的 progress 阶段 + 增量拉取事件日志。 */+ async trackConnectProgress() {+ const id = this.pendingId ?? this.connectFailed?.id+ if (id === undefined || id === null)+ return+ const machine = this.machines.find(item => item.id === id)+ const phase = machine?.progress?.phase+ if (phase !== undefined && this.connectTrail[this.connectTrail.length - 1] !== phase)+ this.connectTrail = [...this.connectTrail, phase]+ try {+ const { items } = await api.events(id, eventSeq)+ for (const item of items) {+ eventSeq = Math.max(eventSeq, item.seq + 1)+ this.connectLog = [...this.connectLog, item.line]+ }+ }+ catch {+ // 事件通道失败不阻断连接进度(列表轮询仍在推进)+ }+ },++ /** 关闭连接进度弹窗:清日志/阶段/失败定格(不影响进行中的连接)。 */+ dismissConnect() {+ this.connectTrail = []+ this.connectLog = []+ this.connectFailed = null+ // 仍在连接中:仅隐藏到落定(失败会重新弹出),成功/失败后自然复位+ if (this.pendingId !== null)+ this.connectDismissed = true+ },+/*** 切换视图:已连接直接切换;进行中(连接/重连)挂起等待;否则发起* 连接(阻塞到隧道就绪,见 S1 契约——不会指向空端口)。@@ -114,15 +170,26 @@ export const remote = defineStore({}if (machine.state === 'connecting' || machine.state === 'testing' || machine.state === 'reconnecting') {// 引擎已在推进(用户连接或自动重连):挂起等待,轮询 reconcile 接管- this.pendingId = machineId+ if (this.pendingId !== machineId)+ this.beginTracking(machineId)return}// disconnected / given-up:重新连接(given-up 可经再次 connect 退出)- this.pendingId = machineId+ this.beginTracking(machineId)void this.connectAndSwitch(machineId)},- /** 连接一台机器并在就绪后切换;失败留在本地(失败态由列表呈现)。 */+ /** 开始跟踪一台机器的连接:复位日志/阶段/游标并挂起。 */+ beginTracking(machineId: string) {+ this.pendingId = machineId+ this.connectFailed = null+ this.connectDismissed = false+ this.connectTrail = []+ this.connectLog = []+ eventSeq = 0+ },++ /** 连接一台机器并在就绪后切换;失败定格原因(进度弹窗呈现重试入口)。 */async connectAndSwitch(machineId: string) {try {const link = await api.connect(machineId)@@ -132,11 +199,17 @@ export const remote = defineStore({this.activeId = machineIdthis.activeTunnelUrl = machine.tunnelBaseUrl ?? link.tunnelBaseUrlthis.pendingId = null+ // 成功:弹窗随 pendingId 清空自动关闭,日志/阶段一并复位+ this.dismissConnect()+ this.connectDismissed = false}}catch (err) {console.warn('[remote] connect failed:', err)this.pendingId = null+ this.connectFailed = { id: machineId, error: messageOf(err) }+ // 失败必须可见:进行中手动关过弹窗也重新弹出+ this.connectDismissed = false// 拉取引擎落定的失败态(given-up + lastError)供切换器呈现void this.refresh()}@@ -181,4 +254,9 @@ export function disposeRemoteForTests(): void {remote.activeTunnelUrl = ''remote.available = trueremote.refreshing = false+ remote.connectTrail = []+ remote.connectLog = []+ remote.connectFailed = null+ remote.connectDismissed = false+ eventSeq = 0}diff --git a/src/store/modules/remote/types.ts b/src/store/modules/remote/types.tsindex b8f01c98..455aa8ea 100644--- a/src/store/modules/remote/types.ts+++ b/src/store/modules/remote/types.ts@@ -23,6 +23,17 @@ export interface SshMachineRow {color?: string/** 是否用标识色给内容区描边。 */tintBorder?: boolean+ /** 连接目标(管理面板表单回填与切换器副标题)。 */+ host?: string+ port?: number+ user?: string+ /** 远端 dsh web 端口。 */+ remotePort?: number+ /** 自定义启动命令(远端 home pin 端口时用)。 */+ startCommand?: string+ /** 是否已存密码/密钥口令(值本身永不过线;表单「留空=保留」提示用)。 */+ hasPassword?: boolean+ hasPassphrase?: booleanstate: SshConnectionState/** 隧道就绪时的本地回环 URL(`http://127.0.0.1:<port>`)。 */tunnelBaseUrl?: string@@ -32,6 +43,44 @@ export interface SshMachineRow {nextRetryAt?: number/** 当前(或最近一次成功)连接使用的凭据类型。 */authMethod?: 'agent' | 'key' | 'password'+ /** 进行中操作的实时阶段(连接/安装管线),落定即消失。 */+ progress?: SshProgress+}++/** 连接管线阶段(宿主 progress.phase 词汇;installing 含 bootstrap 安装段)。 */+export type SshProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing'++/** 进行中操作的实时进度(来自 machine.list 行的 progress 字段)。 */+export interface SshProgress {+ phase: SshProgressPhase+ attempt?: number+ total?: number+ log?: string+}++/** machine.save 的机器档案(与宿主 MachineProfile 契约对齐;敏感值走 secrets 另传)。 */+export interface SshMachineProfile {+ id: string+ name: string+ host: string+ port?: number+ user?: string+ remotePort?: number+ color?: string+ tintBorder?: boolean+ startCommand?: string+}++/** machine.save 的敏感字段:仅在保存时传输,任何状态不落库。 */+export interface SshSecrets {+ password?: string+ passphrase?: string+}++/** machine.events 返回的单条事件(seq 单调递增,增量轮询游标)。 */+export interface SshEventEntry {+ seq: number+ line: string}/** `machine.list` 的应答信封(items = 手动机器,discovered = ~/.ssh/config 别名)。 */