DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(ui): 机器管理统一到设置分区,壳层管理弹窗退役
Menghuan191810157ff71351
diff --git a/packages/dsh-tauri-ui/src/client/constants/index.ts b/packages/dsh-tauri-ui/src/client/constants/index.tsindex 68548d05..9ca41b61 100644--- a/packages/dsh-tauri-ui/src/client/constants/index.ts+++ b/packages/dsh-tauri-ui/src/client/constants/index.ts@@ -47,6 +47,7 @@ export const SEAT_EFFECT = `${PLUGIN_ID}: shell.overlay seat`export const SECTIONS_EFFECT = `${PLUGIN_ID}: settings sections projection`export const SETTINGS_EFFECT = `${PLUGIN_ID}: settings panel`export const OBSTRUCTIONS_EFFECT = `${PLUGIN_ID}: settings obstructions`+export const SETTINGS_OPEN_EFFECT = `${PLUGIN_ID}: settings deep-link`export const IM_PANEL_EFFECT = `${PLUGIN_ID}: im panel`export const HERO_WORKSPACE_EFFECT = `${PLUGIN_ID}: hero workspace picker`export const NEW_SESSION_EFFECT = `${PLUGIN_ID}: sidebar new session`diff --git a/packages/dsh-tauri-ui/src/client/index.ts b/packages/dsh-tauri-ui/src/client/index.tsindex 7ac5a5fd..0186a3ab 100644--- a/packages/dsh-tauri-ui/src/client/index.ts+++ b/packages/dsh-tauri-ui/src/client/index.ts@@ -1,7 +1,7 @@import type {} from '@deepseek-ai/dsh-client-ui-layout/client'import type { ClientContext } from 'dsh-tauri/client'import { PLUGIN_ID } from '../shared/constants'-import { HERO_WORKSPACE_EFFECT, IM_PANEL_EFFECT, LOCALE_EFFECT, NEW_SESSION_EFFECT, OBSTRUCTIONS_EFFECT, SEAT_EFFECT, SECTIONS_EFFECT, SETTINGS_EFFECT, STYLES_EFFECT } from './constants'+import { HERO_WORKSPACE_EFFECT, IM_PANEL_EFFECT, LOCALE_EFFECT, NEW_SESSION_EFFECT, OBSTRUCTIONS_EFFECT, SEAT_EFFECT, SECTIONS_EFFECT, SETTINGS_EFFECT, SETTINGS_OPEN_EFFECT, STYLES_EFFECT } from './constants'import { locale } from './locales'import { composerResumeFeature } from './register/composer-resume'import { heroWorkspaceFeature } from './register/hero-workspace'@@ -11,6 +11,7 @@ import { registerSettingsObstructions } from './register/obstructions'import { registerShellSeat } from './register/seat'import { registerSettingsSections } from './register/sections'import { registerSettings } from './register/settings'+import { registerSettingsOpen } from './register/settings-open'import { registerStyles } from './register/styles'export * from './components'@@ -40,6 +41,7 @@ export function apply(ctx: ClientContext): void {ctx.effect(registerSettingsObstructions, OBSTRUCTIONS_EFFECT)ctx.effect(heroWorkspaceFeature, HERO_WORKSPACE_EFFECT)ctx.effect(sidebarNewSessionFeature, NEW_SESSION_EFFECT)+ ctx.effect(registerSettingsOpen, SETTINGS_OPEN_EFFECT)ctx.effect(composerResumeFeature, COMPOSER_RESUME_EFFECT)ctx.effect(registerImPanel, IM_PANEL_EFFECT)}diff --git a/packages/dsh-tauri-ui/src/client/register/settings-open.test.ts b/packages/dsh-tauri-ui/src/client/register/settings-open.test.tsnew file mode 100644index 00000000..34717ac5--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/settings-open.test.ts@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { registerSettingsOpen, SETTINGS_OPEN_MESSAGE } from './settings-open'++const mocks = vi.hoisted(() => ({+ openAt: vi.fn(),+ listenParent: vi.fn(),+}))++vi.mock('dsh-tauri/client', () => ({+ defineRegister: (feature: (...args: never[]) => void) => feature,+ listenParent: mocks.listenParent,+}))++vi.mock('../store/modules/settings', () => ({+ settings: { openAt: mocks.openAt },+}))++describe('registerSettingsOpen', () => {+ beforeEach(() => {+ mocks.openAt.mockClear()+ mocks.listenParent.mockReset()+ })++ it('opens the settings overlay at the requested section on the host message', () => {+ mocks.listenParent.mockImplementation((handler: (message: unknown) => void, types: unknown) => {+ expect(types).toBe(SETTINGS_OPEN_MESSAGE)+ handler({ payload: { section: 'dsh-tauri-ssh' } })+ return () => {}+ })+ const controller = { add: vi.fn() }+ ;(registerSettingsOpen as (controller: unknown) => void)(controller)+ expect(mocks.listenParent).toHaveBeenCalledOnce()+ expect(mocks.openAt).toHaveBeenCalledWith('dsh-tauri-ssh')+ })++ it('ignores non-string sections and opens without a target', () => {+ mocks.listenParent.mockImplementation((handler: (message: unknown) => void) => {+ handler({ payload: { section: 42 } })+ handler({})+ return () => {}+ })+ ;(registerSettingsOpen as (controller: unknown) => void)({ add: vi.fn() })+ expect(mocks.openAt).toHaveBeenNthCalledWith(1, undefined)+ expect(mocks.openAt).toHaveBeenNthCalledWith(2, undefined)+ })+})diff --git a/packages/dsh-tauri-ui/src/client/register/settings-open.ts b/packages/dsh-tauri-ui/src/client/register/settings-open.tsnew file mode 100644index 00000000..305e0175--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/settings-open.ts@@ -0,0 +1,17 @@+import type { ClientContext } from 'dsh-tauri/client'+import { defineRegister, listenParent } from 'dsh-tauri/client'+import { settings } from '../store/modules/settings'++export const SETTINGS_OPEN_MESSAGE = 'dsh://settings:open'++/**+ * 壳层 deep-link:宿主窗口 postMessage `dsh://settings:open`(payload+ * `{ section }`,可省略)→ 打开设置浮层并定位到对应分区。桌面壳的+ * 「管理机器」等入口经此直达插件的设置分区,替代壳内重复管理面板。+ */+export const registerSettingsOpen = defineRegister<ClientContext>((controller) => {+ controller.add(listenParent((message) => {+ const section = (message.payload as { section?: unknown } | undefined)?.section+ settings.openAt(typeof section === 'string' && section !== '' ? section : undefined)+ }, SETTINGS_OPEN_MESSAGE))+})diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsxindex fb180751..f50bd85c 100644--- a/src/layout/components/navbar.tsx+++ b/src/layout/components/navbar.tsx@@ -27,7 +27,6 @@ import { DesktopUpdateDialog } from '@/ui/dialog/update'import { writeClipboardText } from '@/utils/clipboard'import { toast } from '@/utils/toast'import { ConnectDialog } from './connect-dialog'-import { RemoteManager } from './remote-manager'import { RemoteSwitcher } from './remote-switcher'/**@@ -152,12 +151,13 @@ export interface NavbarProps {onToggleSidebar?: () => void/** 新聊天:向 iframe 发 `dsh://session:new`(dsh 官方「新建会话」);传入时该项可用 */onNewChat?: () => void+ /** 管理机器:向 iframe 发 `dsh://settings:open` 定位 SSH 分区(统一到设置页) */+ onOpenMachineManager?: () => void/** 打开文件夹:向 iframe 发 `dsh://workspace:add`(dsh 官方「添加工作区」);传入时该项可用 */onOpenFolder?: () => void}-export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder }: NavbarProps) {- const [managerOpen, setManagerOpen] = useState(false)+export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenMachineManager }: NavbarProps) {const { t } = useTranslation()const isFullscreen = useMacOSFullscreen()// 只读取「dsh-tauri 插件是否已安装」;查询键与「插件」面板共用(同一份缓存),@@ -370,9 +370,8 @@ export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, o</Button></If><If cond={onToggleSidebar != null}>- <RemoteSwitcher onManage={() => setManagerOpen(true)} />+ <RemoteSwitcher onManage={onOpenMachineManager} /><ConnectDialog />- <RemoteManager isOpen={managerOpen} onClose={() => setManagerOpen(false)} /></If><If cond={!IS_MACOS}><div className="ml-1">diff --git a/src/layout/components/remote-manager.test.tsx b/src/layout/components/remote-manager.test.tsxdeleted file mode 100644index 0859fb4f..00000000--- a/src/layout/components/remote-manager.test.tsx+++ /dev/null@@ -1,153 +0,0 @@-// @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.tsxdeleted file mode 100644index c414e1de..00000000--- a/src/layout/components/remote-manager.tsx+++ /dev/null@@ -1,398 +0,0 @@-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.tsx b/src/layout/components/remote-switcher.tsxindex c0cc95f9..6767962d 100644--- a/src/layout/components/remote-switcher.tsx+++ b/src/layout/components/remote-switcher.tsx@@ -58,7 +58,7 @@ function openInNewWindow(machine: SshMachineRow, onError: (err: unknown) => void* 放弃红 → 其余中性灰;未连接行整体降不透明度。本地实例不可达时进入降级* 态:远端项禁用 + 顶部提示,恢复后自动复原(轮询静默重试,不弹错误)。*/-export function RemoteSwitcher({ onManage }: { onManage: () => void }) {+export function RemoteSwitcher({ onManage }: { onManage?: () => void }) {const { t } = useTranslation()useRemoteMachines()const { machines, activeId, available, pendingId } = useStore(store.remote)@@ -200,6 +200,7 @@ export function RemoteSwitcher({ onManage }: { onManage: () => void }) {<Dropdown.ItemclassName="rounded-md"id="remote-manage"+ isDisabled={onManage == null}textValue={t('remote.manage')}onAction={onManage}>