Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(ssh): 适配 0.1.7 内核并把远程设置合并为 Hero + Tabs

hairyfbb861a0a6f32
diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx
index 83cec33d..a55e7198 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx
+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.tsx
@@ -5,6 +5,7 @@ import type { MachineLifecycleState, RemoteBridge } from '../types/index'
import { Button, Input, Modal, StateDot } from 'dsh-tauri-ui/client'
import { useEffect, useState, useSyncExternalStore } from 'react'
import { cls } from '../styles/index'
+import { errorTextOf } from '../utils/error'
import { retrySecondsOf } from '../utils/retry'
/** New-machine form defaults (ssh-ui 既有默认:SSH 22 / 远端 web 3080)。 */
@@ -147,35 +148,37 @@ function EditPanel({ draft, t, secretSet, dirty, saving, onChange, onSecret, onS
const invalid = row.id === '' || row.name === '' || row.host === ''
return (
<div className={cls.editor} data-testid={`editor-${row.id}`}>
+ {/* 12 栅格显式分组:第 1 行 = ID / 名称 / 主机(3+4+5),
+ 第 2 行 = 端口 / 用户 / 远端端口 / 远端档案(3×4),启动命令独占整行 */}
<div className={cls.grid}>
- <Field label={t('field.id')}>
+ <Field label={t('field.id')} span={3}>
<Input className={cls.fieldInput} value={row.id} disabled />
</Field>
- <Field label={t('field.name')}>
+ <Field label={t('field.name')} span={4}>
<Input className={cls.fieldInput} value={row.name} disabled={saving} onChange={event => onChange(draft.key, { name: event.target.value })} />
</Field>
- <Field label={t('field.host')}>
+ <Field label={t('field.host')} span={5}>
<Input className={cls.fieldInput} value={row.host} disabled={saving} onChange={event => onChange(draft.key, { host: event.target.value })} />
</Field>
- <Field label={t('field.port')}>
+ <Field label={t('field.port')} span={3}>
<Input className={cls.fieldInput} type="number" value={row.port} disabled={saving} onChange={event => onChange(draft.key, { port: numberOf(event.target.value, DEFAULT_PORT) })} />
</Field>
- <Field label={t('field.user')}>
+ <Field label={t('field.user')} span={3}>
<Input className={cls.fieldInput} value={row.user} disabled={saving} onChange={event => onChange(draft.key, { user: event.target.value })} />
</Field>
- <Field label={t('field.remotePort')}>
+ <Field label={t('field.remotePort')} span={3}>
<Input className={cls.fieldInput} type="number" value={row.remotePort} disabled={saving} onChange={event => onChange(draft.key, { remotePort: numberOf(event.target.value, DEFAULT_REMOTE_PORT) })} />
</Field>
- <Field label={t('field.profileName')}>
+ <Field label={t('field.profileName')} span={3}>
<Input className={cls.fieldInput} value={row.profileName ?? ''} placeholder="remote" disabled={saving || (row.startCommand ?? '') !== ''} onChange={event => onChange(draft.key, { profileName: event.target.value })} />
</Field>
- <Field label={t('field.startCommand')}>
+ <Field label={t('field.startCommand')} span={12}>
<Input className={cls.fieldInput} value={row.startCommand ?? ''} disabled={saving} onChange={event => onChange(draft.key, { startCommand: event.target.value })} />
</Field>
</div>
<div className={cls.grid}>
- <SecretField field="password" label={t('field.password')} keyName={draft.key} secretSet={secretSet} t={t} value={dirty.password ?? ''} onValue={onSecret} />
- <SecretField field="passphrase" label={t('field.passphrase')} keyName={draft.key} secretSet={secretSet} t={t} value={dirty.passphrase ?? ''} onValue={onSecret} />
+ <SecretField field="password" span={6} label={t('field.password')} keyName={draft.key} secretSet={secretSet} t={t} value={dirty.password ?? ''} onValue={onSecret} />
+ <SecretField field="passphrase" span={6} label={t('field.passphrase')} keyName={draft.key} secretSet={secretSet} t={t} value={dirty.passphrase ?? ''} onValue={onSecret} />
</div>
<AppearanceEditor row={row} t={t} onChange={onChange} draftKey={draft.key} />
<div className={cls.editorActions}>
@@ -333,10 +336,23 @@ function installNoteOf(result: InstallResult, t: (key: SshKey) => string): strin
return result.credentialsCopied ? t('install.done.copied') : t('install.done.nokey')
}
+/** The grid spans the editor layout uses (12-column track). */
+export type FieldSpan = 3 | 4 | 5 | 6 | 8 | 12
+
+/** Span class per grid width (the 12-column editor track). */
+const SPAN_CLASS: Record<FieldSpan, string> = {
+ 3: cls.span3,
+ 4: cls.span4,
+ 5: cls.span5,
+ 6: cls.span6,
+ 8: cls.span8,
+ 12: cls.span12,
+}
+
/** One labeled field row. */
-function Field({ label, children }: { label: string, children: ReactNode }): ReactNode {
+function Field({ label, span = 6, children }: { label: string, span?: FieldSpan, children: ReactNode }): ReactNode {
return (
- <label className={cls.field}>
+ <label className={`${cls.field} ${SPAN_CLASS[span]}`}>
<span className={cls.fieldLabel}>{label}</span>
{children}
</label>
@@ -398,7 +414,7 @@ function AppearanceEditor({ row, t, onChange, draftKey }: {
}
/** One write-only secret input; the placeholder reports whether a value is stored. */
-export function SecretField({ field, label, keyName, secretSet, t, value, onValue }: {
+export function SecretField({ field, label, keyName, secretSet, t, value, onValue, span = 6 }: {
field: SecretFieldName
label: string
keyName: string
@@ -406,10 +422,11 @@ export function SecretField({ field, label, keyName, secretSet, t, value, onValu
t: (key: SshKey) => string
value: string
onValue: (key: string, field: SecretFieldName, value: string) => void
+ span?: FieldSpan
}): ReactNode {
const placeholder = secretSet[`${keyName}.${field}`] ? t('secret.set') : t('secret.unset')
return (
- <label className={cls.field}>
+ <label className={`${cls.field} ${SPAN_CLASS[span]}`}>
<span className={cls.fieldLabel}>{label}</span>
<Input
className={cls.fieldInput}
@@ -607,8 +624,10 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
</>
)}
>
+ {/* 新增表单同样按 12 栅格成组:主机 + 端口一行(8+4),
+ 名称 / ID / 用户一行(4×3),远端端口 + 远端档案一行(6+6) */}
<div className={cls.grid}>
- <Field label={t('field.host')}>
+ <Field label={t('field.host')} span={8}>
<Input
className={cls.fieldInput}
value={host}
@@ -617,10 +636,13 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
onChange={event => setHost(event.target.value)}
/>
</Field>
- <Field label={t('field.name')}>
+ <Field label={t('field.port')} span={4}>
+ <Input className={cls.fieldInput} value={port} disabled={saving} onChange={event => setPort(event.target.value)} />
+ </Field>
+ <Field label={t('field.name')} span={4}>
<Input className={cls.fieldInput} value={name} disabled={saving} onChange={event => setName(event.target.value)} />
</Field>
- <Field label={t('field.id')}>
+ <Field label={t('field.id')} span={4}>
<Input
className={cls.fieldInput}
value={idTouched ? id : effectiveId}
@@ -632,16 +654,13 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
}}
/>
</Field>
- <Field label={t('field.user')}>
+ <Field label={t('field.user')} span={4}>
<Input className={cls.fieldInput} value={user} disabled={saving} onChange={event => setUser(event.target.value)} />
</Field>
- <Field label={t('field.port')}>
- <Input className={cls.fieldInput} value={port} disabled={saving} onChange={event => setPort(event.target.value)} />
- </Field>
- <Field label={t('field.remotePort')}>
+ <Field label={t('field.remotePort')} span={6}>
<Input className={cls.fieldInput} value={remotePort} disabled={saving} onChange={event => setRemotePort(event.target.value)} />
</Field>
- <Field label={t('field.profileName')}>
+ <Field label={t('field.profileName')} span={6}>
<Input className={cls.fieldInput} value={profileName} placeholder="remote" disabled={saving} onChange={event => setProfileName(event.target.value)} />
</Field>
</div>
@@ -890,7 +909,7 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
? (
<p className={cls.error} role="alert">
{t('error.banner')}
- {state.error}
+ {errorTextOf(state.error, t)}
</p>
)
: null}
diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/ssh-section.test.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/ssh-section.test.tsx
new file mode 100644
index 00000000..85adae4b
--- /dev/null
+++ b/packages/dsh-tauri-ssh-ui/src/client/components/ssh-section.test.tsx
@@ -0,0 +1,138 @@
+// @vitest-environment jsdom
+import type { FetchFn } from '../store/index'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { MachinesStore } from '../store/index'
+import { SshSection } from './ssh-section'
+
+// dsh-tauri-ui/client 的 dist bundle 以 ModuleLoader 工厂包裹,脱离宿主加载器无法在
+// node 求值:通用控件用最小替身(本套用例只关心 Hero / Tabs 的取舍与定位),
+// listenParent 取真实源实现,好让 deep link 走一遍真实的消息过滤。
+vi.mock('dsh-tauri-ui/client', async () => {
+ const mod = await import('../../../../dsh-tauri-ui/src/client/utils/cssr.ts')
+ const React = await import('react')
+ const h = React.createElement
+ const passthrough = (props: { children?: unknown }) => h('div', null, props.children as never)
+ return {
+ cssr: mod.cssr,
+ Button: ({ variant: _variant, size: _size, onPress, ...rest }: { variant?: unknown, size?: unknown, onPress?: () => void } & Record<string, unknown>) =>
+ h('button', { type: 'button', ...rest, onClick: onPress ?? rest.onClick } as never, rest.children as never),
+ Globe: () => null,
+ Icon: () => null,
+ Input: () => null,
+ Modal: passthrough,
+ Pill: passthrough,
+ StateDot: () => null,
+ SegmentedControl: (props: { options: Array<{ value: string, label: string }>, value: string, onChange: (next: string) => void, id?: string }) =>
+ h('div', { role: 'tablist' }, props.options.map(option =>
+ h('button', {
+ 'key': option.value,
+ 'type': 'button',
+ 'role': 'tab',
+ 'aria-selected': option.value === props.value,
+ 'onClick': () => props.onChange(option.value),
+ }, option.label))),
+ }
+})
+
+vi.mock('dsh-tauri/client', async () => {
+ const mod = await import('../../../../dsh-tauri/src/client/service/listen-parent.ts')
+ return { listenParent: mod.listenParent }
+})
+
+/** A store whose /api-ssh answers the enable flow (off by default). */
+function bootStore(options: { enabled?: boolean } = {}) {
+ let enabled = options.enabled ?? false
+ const fetchFn = vi.fn<FetchFn>(async (_url, init) => {
+ const request = JSON.parse(String(init.body)) as { method: string }
+ if (request.method === 'settings.get')
+ return { json: async () => ({ ok: true, value: { enabled } }) } as unknown as Response
+ if (request.method === 'settings.set') {
+ enabled = true
+ return { json: async () => ({ ok: true, value: { enabled } }) } as unknown as Response
+ }
+ if (request.method === 'session.role')
+ return { json: async () => ({ ok: true, value: { remote: false } }) } as unknown as Response
+ return { json: async () => ({ ok: true, value: { enabled, items: [], discovered: [] } }) } as unknown as Response
+ })
+ return { store: new MachinesStore(fetchFn), fetchFn }
+}
+
+/** The bound dictionary lookup (key is the text, as elsewhere in this package). */
+const t = (key: string) => `t:${key}`
+
+afterEach(() => {
+ cleanup()
+})
+
+describe('sshSection', () => {
+ it('未启用时只渲染 Hero(图标 + 描述 + 开启按钮),不渲染 Tabs 内容', async () => {
+ const { store } = bootStore()
+ render(<SshSection t={t as never} store={store} />)
+
+ await waitFor(() => expect(screen.getByTestId('ssh-hero')).toBeTruthy())
+ expect(screen.getByText('t:hero.title')).toBeTruthy()
+ expect(screen.getByText('t:hero.desc')).toBeTruthy()
+ expect(screen.getByTestId('ssh-enable').textContent).toBe('t:hero.enable')
+ expect(screen.queryByTestId('ssh-tabs')).toBeNull()
+ expect(screen.queryByText('t:tabs.machines')).toBeNull()
+ })
+
+ it('点击开启:settings.set 落定后原位切换到 Tabs(SSH 机器 / 同步到远端)', async () => {
+ const { store, fetchFn } = bootStore()
+ render(<SshSection t={t as never} store={store} />)
+ await waitFor(() => expect(screen.getByTestId('ssh-enable')).toBeTruthy())
+
+ fireEvent.click(screen.getByTestId('ssh-enable'))
+ await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
+ expect(fetchFn.mock.calls.some(([, init]) => String(init?.body).includes('"settings.set"'))).toBe(true)
+ const tabs = screen.getAllByRole('tab')
+ expect(tabs.map(tab => tab.textContent)).toEqual(['t:tabs.machines', 't:tabs.sync'])
+ expect(screen.queryByTestId('ssh-hero')).toBeNull()
+ expect(screen.getByRole('tab', { selected: true }).textContent).toBe('t:tabs.machines')
+ })
+
+ it('已启用:Tabs 默认停在「SSH 机器」,切换后渲染同步面板且已访问面板保持挂载', async () => {
+ const { store } = bootStore({ enabled: true })
+ render(<SshSection t={t as never} store={store} />)
+ await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
+
+ const machinesPanel = document.getElementById('dsh-tauri-ssh-tabs-machines-panel')
+ expect(machinesPanel?.hasAttribute('hidden')).toBe(false)
+
+ fireEvent.click(screen.getByRole('tab', { name: 't:tabs.sync' }))
+ await waitFor(() => {
+ expect(document.getElementById('dsh-tauri-ssh-tabs-sync-panel')?.hasAttribute('hidden')).toBe(false)
+ })
+ expect(document.getElementById('dsh-tauri-ssh-tabs-machines-panel')?.hasAttribute('hidden')).toBe(true)
+ })
+
+ it('壳层 deep link:分区匹配时落到指定标签页,别的分区不动', async () => {
+ const { store } = bootStore({ enabled: true })
+ render(<SshSection t={t as never} store={store} />)
+ await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
+
+ window.dispatchEvent(new MessageEvent('message', {
+ data: { type: 'dsh://settings:open', section: 'dsh-tauri-ssh-sync', tab: 'sync' },
+ source: window,
+ }))
+ expect(screen.getByRole('tab', { selected: true }).textContent).toBe('t:tabs.machines')
+
+ window.dispatchEvent(new MessageEvent('message', {
+ data: { type: 'dsh://settings:open', section: 'dsh-tauri-ssh', tab: 'sync' },
+ source: window,
+ }))
+ await waitFor(() => {
+ expect(screen.getByRole('tab', { selected: true }).textContent).toBe('t:tabs.sync')
+ })
+ })
+
+ it('读取开关失败(插件未加载):Hero 呈现本地化的不可用提示而非原生解析异常', async () => {
+ const fetchFn = vi.fn<FetchFn>(async () => ({ ok: false, status: 405, json: async () => ({}) }) as unknown as Response)
+ const store = new MachinesStore(fetchFn)
+ render(<SshSection t={t as never} store={store} />)
+
+ await waitFor(() => expect(screen.getByTestId('ssh-hero-error')).toBeTruthy())
+ expect(screen.getByTestId('ssh-hero-error').textContent).toBe('t:error.unavailable')
+ })
+})
diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/ssh-section.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/ssh-section.tsx
new file mode 100644
index 00000000..abc7c395
--- /dev/null
+++ b/packages/dsh-tauri-ssh-ui/src/client/components/ssh-section.tsx
@@ -0,0 +1,140 @@
+/**
+ * The single `SSH` settings section: a feature switch in front of two tabs.
+ * While the SSH feature is off (the default on a fresh install) the section
+ * renders only the enable hero — no machine list, no sync surface, and no
+ * connection work on the host. Switching it on reveals the `SSH machines` and
+ * `Sync to remote` tabs; the desktop shell deep link picks the tab.
+ * @module dsh-tauri-ssh-ui/client/components/ssh-section
+ */
+
+import type { ReactNode } from 'react'
+import type { SshKey } from '../locales/index'
+import type { MachinesStore } from '../store/index'
+import type { RemoteBridge } from '../types/index'
+import { Button, Globe, Icon, SegmentedControl } from 'dsh-tauri-ui/client'
+import { listenParent } from 'dsh-tauri/client'
+import { useEffect, useState, useSyncExternalStore } from 'react'
+import { SETTINGS_OPEN_MESSAGE, SETTINGS_SECTION_ID, SSH_TAB_MACHINES, SSH_TAB_SYNC, SSH_TABS_ID } from '../constants'
+import { cls } from '../styles'
+import { errorTextOf } from '../utils/error'
+import { MachinesSection } from './machines-section'
+import { SyncPanel } from './sync-panel'
+
+/** The two tabs of the merged SSH section. */
+type SshTab = typeof SSH_TAB_MACHINES | typeof SSH_TAB_SYNC
+
+export interface SshSectionProps {
+ store: MachinesStore
+ /** Desktop bridge; absent (or unanswered probe) means pure web. */
+ bridge?: RemoteBridge
+ t: (key: SshKey) => string
+}
+
+/** The tabs of the section, in display order. */
+const TAB_KEYS: Record<SshTab, SshKey> = {
+ [SSH_TAB_MACHINES]: 'tabs.machines',
+ [SSH_TAB_SYNC]: 'tabs.sync',
+}
+
+/**
+ * Render the merged SSH settings section.
+ * @returns the enable hero while the feature is off, the tab surface once on.
+ */
+export function SshSection({ t, store, bridge }: SshSectionProps): ReactNode {
+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot)
+ const [tab, setTab] = useState<SshTab>(SSH_TAB_MACHINES)
+ const [visited, setVisited] = useState<ReadonlySet<SshTab>>(() => new Set<SshTab>([SSH_TAB_MACHINES]))
+
+ // 已访问的标签页保持挂载(切回来不丢选择态),与扩展面板的同款做法一致;
+ // 切换入口只有下面两个,visited 随选中一起推进,不必再挂一个同步 effect。
+ function openTab(next: SshTab): void {
+ setTab(next)
+ setVisited(previous => previous.has(next) ? previous : new Set<SshTab>([...previous, next]))
+ }
+
+ useEffect(() => {
+ if (store.getSnapshot().enabled === null)
+ void store.loadSettings()
+ }, [store])
+
+ // 壳层「管理机器…/同步到远端…」把分区与目标标签页一起发过来;本分区只认自己
+ // 的 section,其余交回 dsh-tauri-ui 的通用 deep-link 处理。
+ useEffect(() => {
+ return listenParent((message) => {
+ if (message.section !== SETTINGS_SECTION_ID)
+ return
+ if (message.tab === SSH_TAB_MACHINES || message.tab === SSH_TAB_SYNC)
+ openTab(message.tab)
+ }, SETTINGS_OPEN_MESSAGE)
+ }, [])
+
+ if (state.enabled === null) {
+ return (
+ <div className={cls.section} data-testid="ssh-section">
+ <p className={cls.hint}>{t('loading')}</p>
+ </div>
+ )
+ }
+
+ if (state.enabled === false) {
+ return (
+ <div className={cls.section} data-testid="ssh-section">
+ <div className={cls.hero} data-testid="ssh-hero">
+ <span className={cls.heroIcon} aria-hidden="true">
+ <Icon as={Globe} size={22} />
+ </span>
+ <h2 className={cls.heroTitle}>{t('hero.title')}</h2>
+ <p className={cls.heroHint}>{t('hero.desc')}</p>
+ {state.error !== null
+ ? <p className={cls.error} role="alert" data-testid="ssh-hero-error">{errorTextOf(state.error, t)}</p>
+ : null}
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={state.enabling}
+ data-testid="ssh-enable"
+ onClick={() => void store.enable()}
+ >
+ {state.enabling ? t('hero.enabling') : t('hero.enable')}
+ </Button>
+ </div>
+ </div>
+ )
+ }
+
+ const tabs: SshTab[] = [SSH_TAB_MACHINES, SSH_TAB_SYNC]
+
+ return (
+ <div className={cls.section} data-testid="ssh-section">
+ <div className={cls.tabs} data-testid="ssh-tabs">
+ <SegmentedControl
+ id={SSH_TABS_ID}
+ label={t('nav')}
+ value={tab}
+ options={tabs.map(value => ({ value, label: t(TAB_KEYS[value]) }))}
+ onChange={(next) => {
+ if (next === SSH_TAB_MACHINES || next === SSH_TAB_SYNC)
+ openTab(next)
+ }}
+ />
+ </div>
+ {tabs.filter(value => value === tab || visited.has(value)).map((value) => {
+ const selected = value === tab
+ return (
+ <div
+ key={value}
+ id={`${SSH_TABS_ID}-${value}-panel`}
+ className={cls.tabPanel}
+ role="tabpanel"
+ aria-labelledby={`${SSH_TABS_ID}-${value}`}
+ hidden={!selected}
+ >
+ {value === SSH_TAB_MACHINES
+ ? <MachinesSection t={t} store={store} bridge={bridge} />
+ : <SyncPanel t={t} store={store} />}
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx
index 74e28580..26f6b959 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx
+++ b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx
@@ -20,6 +20,7 @@ import { Button, Pill, StateDot } from 'dsh-tauri-ui/client'
import { useEffect, useState, useSyncExternalStore } from 'react'
import { pluginKeyOf, skillKeyOf, syncKeyOf, toggleSelection } from '../store/index'
import { cls } from '../styles'
+import { errorTextOf } from '../utils/error'
/** The panel props: the framework `t` seat plus the injected store. */
export interface SyncPanelProps {
@@ -226,7 +227,7 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
? (
<p className={cls.error} role="alert">
{t('sync.loadFailed')}
- {state.sync.error}
+ {errorTextOf(state.sync.error ?? '', t)}
</p>
)
: null}
@@ -234,7 +235,7 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
? (
<p className={cls.error} role="alert">
{t('sync.applyFailed')}
- {state.sync.error}
+ {errorTextOf(state.sync.error, t)}
</p>
)
: null}
diff --git a/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts b/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts
index ca0deb68..78c9f3b1 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts
@@ -11,21 +11,23 @@ export const SSH_LOCALE_NS = 'ssh'
/** The settings section slot this plugin registers into. */
export const SETTINGS_SECTION_SLOT = 'settings.section'
-/** Registration id of this plugin's settings section (the host plugin's id). */
+/** Registration id of this plugin's single settings section (the host plugin's id). */
export const SETTINGS_SECTION_ID = 'dsh-tauri-ssh'
/** Order of this plugin's settings section among the other sections. */
export const SETTINGS_SECTION_ORDER = 50
-/**
- * Registration id of the plugin/skill sync settings section — a sibling of
- * {@link SETTINGS_SECTION_ID}, so the desktop switcher can deep-link both
- * remote-machine surfaces at the same level (`dsh://settings:open` section).
- */
-export const SYNC_SECTION_ID = 'dsh-tauri-ssh-sync'
+/** The machines tab of the SSH section (shared with the shell deep link). */
+export const SSH_TAB_MACHINES = 'machines'
+
+/** The sync-to-remote tab of the SSH section (shared with the shell deep link). */
+export const SSH_TAB_SYNC = 'sync'
+
+/** DOM id base of the tab strip; each panel is `${SSH_TABS_ID}-${tab}-panel`. */
+export const SSH_TABS_ID = 'dsh-tauri-ssh-tabs'
-/** Order of the sync section, right behind the machines section. */
-export const SYNC_SECTION_ORDER = 51
+/** The shell → iframe settings deep link (the `tab` field picks the SSH tab). */
+export const SETTINGS_OPEN_MESSAGE = 'dsh://settings:open'
/** The /api-ssh route the host plugin mounts (same-origin POST envelope). */
export const SSH_API_PATH = '/api-ssh'
diff --git a/packages/dsh-tauri-ssh-ui/src/client/index.test.ts b/packages/dsh-tauri-ssh-ui/src/client/index.test.ts
index 3f8cc3f8..454cb328 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/index.test.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/index.test.ts
@@ -1,8 +1,7 @@
import type { UiContext } from './types/index'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { apply as hostApply } from '../index'
-import { MachinesSection } from './components/machines-section.tsx'
-import { SyncPanel } from './components/sync-panel.tsx'
+import { SshSection } from './components/ssh-section.tsx'
import { apply, inject } from './index'
import { en, zh } from './locales/index'
import { desktopBridge } from './service/bridge'
@@ -66,9 +65,10 @@ describe('ui-ssh client plugin', () => {
expect(locale.bind).toHaveBeenCalledWith('ssh')
})
- it('registers the settings section with a store-backed inject face', async () => {
+ it('registers the single SSH settings section with a store-backed inject face', async () => {
const { ctx, slots } = scriptedCtx()
apply(ctx)
+ expect(slots.inject).toHaveBeenCalledTimes(1)
expect(slots.inject).toHaveBeenCalledWith('settings.section', expect.any(Function))
const contribution = slots.inject.mock.calls[0]?.[1] as () => unknown
contribution()
@@ -88,36 +88,16 @@ describe('ui-ssh client plugin', () => {
const injected = options.inject()
expect(injected.store).toBeInstanceOf(MachinesStore)
expect(injected.bridge).toBe(desktopBridge)
- expect(slots.register.mock.calls[0]?.[1]).toBe(MachinesSection)
+ // 机器管理与同步合并在同一个分区内(组件内部用 Tabs 分页)
+ expect(slots.register.mock.calls[0]?.[1]).toBe(SshSection)
// Drive one store load so the window.fetch thunk the plugin installed
// actually executes (stubbed: no network in tests).
- const fetchMock = vi.fn(async () => ({ json: async () => ({ ok: true, value: { items: [] } }) }) as unknown as Response)
+ const fetchMock = vi.fn(async () => ({ json: async () => ({ ok: true, value: { enabled: true, items: [] } }) }) as unknown as Response)
vi.stubGlobal('fetch', fetchMock)
const store = injected.store as MachinesStore
await store.load()
expect(fetchMock).toHaveBeenCalledWith('/api-ssh', expect.objectContaining({ method: 'POST' }))
})
-
- it('registers the sync section as a sibling of the machines section', () => {
- const { ctx, slots } = scriptedCtx()
- apply(ctx)
- expect(slots.inject).toHaveBeenCalledTimes(2)
- const contribution = slots.inject.mock.calls[1]?.[1] as () => unknown
- contribution()
- const options = slots.register.mock.calls[0]?.[0] as {
- id: string
- order: number
- label: () => string
- locale: string
- inject: () => Record<string, unknown>
- }
- expect(options.id).toBe('dsh-tauri-ssh-sync')
- expect(options.order).toBe(51)
- expect(options.label()).toBe('t:sync.nav')
- expect(options.locale).toBe('ssh')
- expect(options.inject().store).toBeInstanceOf(MachinesStore)
- expect(slots.register.mock.calls[0]?.[1]).toBe(SyncPanel)
- })
})
afterEach(() => {
diff --git a/packages/dsh-tauri-ssh-ui/src/client/index.ts b/packages/dsh-tauri-ssh-ui/src/client/index.ts
index 195f4450..712ef485 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/index.ts
@@ -1,26 +1,23 @@
/**
* SSH-machines settings page, browser half. Registers the `ssh` dictionary
- * and two sibling `settings.section` entries — the machines page and the
- * plugin/skill sync page — so the desktop switcher can deep-link either of
- * them at the same level. The page state lives in the injected MachinesStore
- * (machine CRUD, the connection plane and the sync surface, all through the
- * host plugin's /api-ssh route). The css-render style tree mounts once here
- * via ctx.effect (unmounts with the plugin). Export discipline: thin apply,
- * everything else in feature modules.
+ * and the single `SSH` settings section that fronts the whole feature with an
+ * enable switch (off by default) and, once on, hosts the machines and the
+ * plugin/skill sync tabs. The page state lives in the injected MachinesStore
+ * (feature flag, machine CRUD, the connection plane and the sync surface, all
+ * through the host plugin's /api-ssh route). The css-render style tree mounts
+ * once here via ctx.effect (unmounts with the plugin). Export discipline: thin
+ * apply, everything else in feature modules.
* @module dsh-tauri-ssh-ui/client
*/
import type { UiContext } from './types'
import { mountStyle } from 'dsh-tauri-ui/client'
-import { MachinesSection } from './components/machines-section'
-import { SyncPanel } from './components/sync-panel'
+import { SshSection } from './components/ssh-section'
import {
SETTINGS_SECTION_ID,
SETTINGS_SECTION_ORDER,
SETTINGS_SECTION_SLOT,
SSH_LOCALE_NS,
- SYNC_SECTION_ID,
- SYNC_SECTION_ORDER,
} from './constants'
import { en, zh } from './locales'
import { desktopBridge } from './service/bridge'
@@ -31,8 +28,8 @@ import { SSH_STYLE_ID, sshStyle } from './styles'
export const inject = ['slots', 'locale']
/**
- * Register the `ssh` dictionaries and both settings sections, each once its
- * slot declaration is on the ledger.
+ * Register the `ssh` dictionary and the SSH settings section, once the slot
+ * declaration is on the ledger.
* @param ctx - client root context.
*/
export function apply(ctx: UiContext): void {
@@ -47,15 +44,7 @@ export function apply(ctx: UiContext): void {
label: () => t('nav'),
locale: SSH_LOCALE_NS,
inject: () => ({ store, bridge: desktopBridge }),
- }, MachinesSection))
- ctx.slots.inject(SETTINGS_SECTION_SLOT, () => ctx.slots.register({
- name: SETTINGS_SECTION_SLOT,
- id: SYNC_SECTION_ID,
- order: SYNC_SECTION_ORDER,
- label: () => t('sync.nav'),
- locale: SSH_LOCALE_NS,
- inject: () => ({ store }),
- }, SyncPanel))
+ }, SshSection))
}
/** The dictionary key union, re-exported for the section props. */
diff --git a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts
index c7fc9a29..4d7c65f5 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts
@@ -2,7 +2,15 @@
/** Simplified Chinese dictionary. */
export const zh = {
- 'nav': 'SSH 机器',
+ 'nav': '远程',
+ 'tabs.machines': 'SSH 机器',
+ 'tabs.sync': '同步到远端',
+ 'hero.title': '远程机器',
+ 'hero.desc': '把本机作为发起端,用 SSH 连接其他机器上的 dsh 实例:直连使用本机 ~/.ssh 的配置与密钥,可管理多台机器并一键切换、同步插件与 Skill。默认关闭,开启后才建立连接。',
+ 'hero.enable': '启用 SSH',
+ 'hero.enabling': '正在启用…',
+ 'hero.loadFailed': '无法读取 SSH 状态。',
+ 'error.unavailable': 'SSH 服务不可用:插件未加载或本地实例未就绪。',
'title': 'SSH 远程机器',
'intro': '连接直接使用本机 ~/.ssh 的配置与密钥:支持 config 别名、IdentityFile 与默认密钥;密码和私钥口令可选,仅在密钥不可用时作为回退。',
'loading': '加载中…',
@@ -32,8 +40,7 @@ export const zh = {
'field.port': '端口',
'field.user': '用户(可选)',
'session.remoteTitle': '目前正在 SSH 中',
- 'sync.nav': '同步到远端',
- 'sync.notConnectedHint': '还没有已连接的机器——先到「SSH 机器」分区连接一台,再回来同步。',
+ 'sync.notConnectedHint': '还没有已连接的机器——先到「SSH 机器」标签页连接一台,再回来同步。',
'sync.remoteSessionHint': '本实例正通过 SSH 使用:插件与 Skill 的同步请在发起连接的机器上操作(那里选「同步到远端…」)。',
'session.remoteHintNamed': '此实例正通过 SSH 来自 {name} 的连接使用;机器的添加、编辑与连接都在发起端操作。',
'session.remoteHint': '此实例正通过 SSH 远程连接使用;机器的添加、编辑与连接都在发起端操作。',
@@ -120,7 +127,15 @@ export type SshKey = keyof typeof zh
/** English dictionary, checked complete against the zh key set. */
export const en = {
- 'nav': 'SSH Machines',
+ 'nav': 'Remote',
+ 'tabs.machines': 'SSH machines',
+ 'tabs.sync': 'Sync to remote',
+ 'hero.title': 'Remote machines',
+ 'hero.desc': 'Drive other machines\' dsh instances from this one over SSH: connections use this machine\'s ~/.ssh directly, and you can keep several machines, switch between them, and sync plugins and skills. Off by default — nothing connects until you enable it.',
+ 'hero.enable': 'Enable SSH',
+ 'hero.enabling': 'Enabling…',
+ 'hero.loadFailed': 'Could not read the SSH state.',
+ 'error.unavailable': 'The SSH service is unavailable: the plugin is not loaded or the local instance is not ready.',
'title': 'SSH Remote Machines',
'intro': 'Connections use this machine\'s ~/.ssh directly: config aliases, IdentityFile, and the default keys are honored; password and passphrase are optional fallbacks.',
'loading': 'Loading…',
@@ -150,7 +165,6 @@ export const en = {
'field.port': 'Port',
'field.user': 'User (optional)',
'session.remoteTitle': 'Currently in an SSH session',
- 'sync.nav': 'Sync to remote',
'sync.notConnectedHint': 'No connected machines yet — connect one under “SSH machines” first, then come back here to sync.',
'sync.remoteSessionHint': 'This instance is in use over SSH: run the plugin/skill sync on the machine that started the session (pick “Sync to remote…” there).',
'session.remoteHintNamed': 'This instance is in use over SSH from {name}; add, edit and connect machines on the machine that started the session.',
diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.test.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.test.ts
index 90e2ba86..5bbbf377 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/store/index.test.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.test.ts
@@ -342,13 +342,17 @@ describe('machinesStore', () => {
fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'connect-failed', message: 'refused' } }) } as unknown as Response)
await store.connect('a')
expect(store.getSnapshot().error).toBe('refused')
+ // 解析不了的信封(空响应体 / 非 JSON)归到稳定错误码,不外泄原生解析异常
fetchFn.mockResolvedValueOnce({
json: async () => {
throw new Error('bad json')
},
} as unknown as Response)
await store.test('a')
- expect(store.getSnapshot().error).toBe('bad json')
+ expect(store.getSnapshot().error).toBe('SSH_API_EMPTY')
+ fetchFn.mockResolvedValueOnce({ ok: false, status: 405, json: async () => ({}) } as unknown as Response)
+ await store.test('a')
+ expect(store.getSnapshot().error).toBe('SSH_API_HTTP_405')
fetchFn.mockResolvedValueOnce({
json: async () => {
@@ -357,7 +361,40 @@ describe('machinesStore', () => {
},
} as unknown as Response)
await store.test('a')
- expect(store.getSnapshot().error).toBe('boom')
+ expect(store.getSnapshot().error).toBe('SSH_API_EMPTY')
+ })
+
+ it('reads the feature switch and enables the SSH service', async () => {
+ const { store, fetchFn } = boot({ ok: true, value: { enabled: false } })
+ await store.loadSettings()
+ expect(store.getSnapshot().enabled).toBe(false)
+
+ // 未启用:机器列表请求不发(分区只渲染开启 Hero)
+ await store.load()
+ expect(store.getSnapshot().status).toBe('idle')
+
+ fetchFn.mockImplementation(async (_url: string, init: RequestInit) => {
+ const request = JSON.parse(String(init.body)) as { method: string }
+ const envelope = request.method === 'settings.set'
+ ? { ok: true, value: { enabled: true } }
+ : request.method === 'session.role'
+ ? { ok: true, value: { remote: false } }
+ : { ok: true, value: { enabled: true, items: [{ ...machineA, state: 'disconnected' }], discovered: [] } }
+ return { json: async () => envelope } as unknown as Response
+ })
+ await store.enable()
+ const state = store.getSnapshot()
+ expect(state.enabled).toBe(true)
+ expect(state.enabling).toBe(false)
+ expect(state.machines.map(row => row.id)).toEqual(['a'])
+ })
+
+ it('treats an unavailable settings endpoint as switched off plus a transport code', async () => {
+ const { store, fetchFn } = boot()
+ fetchFn.mockResolvedValueOnce({ ok: false, status: 405, json: async () => ({}) } as unknown as Response)
+ await store.loadSettings()
+ expect(store.getSnapshot().enabled).toBe(false)
+ expect(store.getSnapshot().error).toBe('SSH_API_HTTP_405')
})
it('carries the dshMissing marker on list rows', async () => {
diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts
index d55b5002..16a25efd 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts
@@ -101,6 +101,10 @@ export interface SyncPanelState {
export interface MachinesPageState {
status: 'idle' | 'loading' | 'ready' | 'error'
error: string | null
+ /** Whether the SSH feature is switched on; null until settings.get answers. */
+ enabled: boolean | null
+ /** Whether a settings.set enable call is in flight. */
+ enabling: boolean
/** Redacted machine rows in settings order (the stored, editable set). */
machines: MachineRow[]
/** Read-only rows discovered from the host's ~/.ssh/config (aliases). */
@@ -307,9 +311,24 @@ export function mergeSyncResults(previous: readonly SyncItemResult[], incoming:
return merged
}
-/** Parse one /api-ssh envelope; non-ok envelopes throw. */
+/** Parse one /api-ssh envelope; a transport-level failure throws a stable code. */
async function envelopeOf(response: Response): Promise<SshApiResponse> {
- return await response.json() as SshApiResponse
+ // 非 2xx(路由未挂载 / 插件未启用时的 404、405)与空响应体都没有可解析的
+ // JSON:直接抛稳定错误码,绝不把 `Unexpected end of JSON input` 这类原生
+ // 解析异常泄漏到界面。
+ if (response.ok === false)
+ throw new Error(`SSH_API_HTTP_${response.status}`)
+ try {
+ return await response.json() as SshApiResponse
+ }
+ catch {
+ throw new Error('SSH_API_EMPTY')
+ }
+}
+
+/** Whether one failure text is a transport code rather than host-provided prose. */
+export function isTransportError(message: string): boolean {
+ return message.startsWith('SSH_API_')
}
/** Build a redacted machine row from one machine.list item. */
@@ -412,6 +431,8 @@ export class MachinesStore {
this.store = createSnapshotStore<MachinesPageState>({
status: 'idle',
error: null,
+ enabled: null,
+ enabling: false,
machines: [],
discovered: [],
statuses: {},
@@ -494,6 +515,8 @@ export class MachinesStore {
/** Refresh machines, secret flags, and live statuses from machine.list. */
async load(): Promise<void> {
+ if (this.store.getSnapshot().enabled === false)
+ return
this.store.update((state) => {
state.status = 'loading'
state.error = null
@@ -511,6 +534,53 @@ export class MachinesStore {
}
}
+ /**
+ * Read the feature switch (settings.get). A transport failure reads as
+ * "off" plus an error notice: the section then shows the enable surface
+ * instead of a raw parse error.
+ */
+ async loadSettings(): Promise<void> {
+ try {
+ const value = await this.callApi<{ enabled?: unknown }>('settings.get', {})
+ this.store.update((state) => {
+ state.enabled = value.enabled === true
+ state.error = null
+ })
+ }
+ catch (error) {
+ this.store.update((state) => {
+ state.enabled = false
+ state.error = messageOf(error)
+ })
+ }
+ }
+
+ /** Switch the SSH feature on (settings.set), then load the machine table. */
+ async enable(): Promise<void> {
+ this.store.update((state) => {
+ state.enabling = true
+ state.error = null
+ })
+ try {
+ const value = await this.callApi<{ enabled?: unknown }>('settings.set', { enabled: true })
+ this.store.update((state) => {
+ state.enabled = value.enabled !== false
+ })
+ if (this.store.getSnapshot().enabled === true)
+ await this.load()
+ }
+ catch (error) {
+ this.store.update((state) => {
+ state.error = messageOf(error)
+ })
+ }
+ finally {
+ this.store.update((state) => {
+ state.enabling = false
+ })
+ }
+ }
+
/** Load this instance's session role once (old hosts without the method keep null). */
async loadRole(): Promise<void> {
try {
diff --git a/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts b/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts
index f77e9c95..da3d4deb 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts
@@ -22,7 +22,8 @@ export default c([
display: 'flex',
flexDirection: 'column',
gap: '12px',
- maxWidth: '760px',
+ /* 与 dsh-tauri-ui 的 panel-page 同宽(960px):760px 在宽窗口下会挤成一条窄栏 */
+ maxWidth: '960px',
color: 'var(--dsw-alias-label-primary)',
}),
@@ -50,6 +51,66 @@ export default c([
flexWrap: 'wrap',
}),
+ /* 合并后的 SSH 分区:标签条 + 面板。面板自身带页头,标签条只负责切换。 */
+ c('.dshp-ssh-tabs', {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ flexWrap: 'wrap',
+ }),
+
+ c('.dshp-ssh-tab-panel', {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ minWidth: 0,
+ }, [
+ c('&[hidden]', {
+ display: 'none',
+ }),
+ ]),
+
+ /* 未启用时的 Hero:Icon / 描述 / 开启按钮,居中成一张卡。 */
+ c('.dshp-ssh-hero', {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: '12px',
+ marginTop: '4px',
+ padding: '40px 24px',
+ border: '0.5px solid var(--dsw-alias-border-l2)',
+ borderRadius: '12px',
+ background: 'var(--dsw-alias-bg-layer-1)',
+ textAlign: 'center',
+ }),
+
+ c('.dshp-ssh-hero-icon', {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '44px',
+ height: '44px',
+ borderRadius: '50%',
+ background: 'var(--dsw-alias-surface-tinted)',
+ color: 'var(--dsw-alias-brand-primary)',
+ }),
+
+ c('.dshp-ssh-hero-title', {
+ margin: 0,
+ fontSize: '22px',
+ lineHeight: '32px',
+ fontWeight: 600,
+ color: 'var(--dsw-alias-label-primary)',
+ }),
+
+ c('.dshp-ssh-hero-hint', {
+ margin: 0,
+ maxWidth: '460px',
+ fontSize: '13px',
+ lineHeight: '21px',
+ color: 'var(--dsw-alias-label-secondary)',
+ }),
+
/* The page chrome: refresh / add. */
c('.dshp-ssh-chrome', {
display: 'flex',
@@ -320,16 +381,45 @@ export default c([
}),
]),
+ /*
+ * The editor/add form track: 12 explicit columns so字段能按分组真正并排
+ * (原来的 auto-fit + minmax(170px) 会按可用宽度重新折行,8 个字段排出
+ * 锯齿状的对齐,也永远用不满宽窗口)。每个字段自带 span 类,窄窗口下由
+ * 下面的 media 查询降级为两列 / 单列。
+ */
c('.dshp-ssh-grid', {
display: 'grid',
- gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))',
- gap: '8px 12px',
- }),
+ gridTemplateColumns: 'repeat(12, minmax(0, 1fr))',
+ gap: '10px 12px',
+ }),
+
+ c('.dshp-ssh-span-3', { gridColumn: 'span 3' }),
+ c('.dshp-ssh-span-4', { gridColumn: 'span 4' }),
+ c('.dshp-ssh-span-5', { gridColumn: 'span 5' }),
+ c('.dshp-ssh-span-6', { gridColumn: 'span 6' }),
+ c('.dshp-ssh-span-8', { gridColumn: 'span 8' }),
+ c('.dshp-ssh-span-12', { gridColumn: 'span 12' }),
+
+ c('@media (max-width: 760px)', [
+ c('.dshp-ssh-grid', { gridTemplateColumns: 'repeat(6, minmax(0, 1fr))' }),
+ c('.dshp-ssh-span-3', { gridColumn: 'span 3' }),
+ c('.dshp-ssh-span-4', { gridColumn: 'span 3' }),
+ c('.dshp-ssh-span-5', { gridColumn: 'span 3' }),
+ c('.dshp-ssh-span-6', { gridColumn: 'span 3' }),
+ c('.dshp-ssh-span-8', { gridColumn: 'span 6' }),
+ c('.dshp-ssh-span-12', { gridColumn: 'span 6' }),
+ ]),
+
+ c('@media (max-width: 520px)', [
+ c('.dshp-ssh-field', { gridColumn: 'span 6' }),
+ ]),
c('.dshp-ssh-field', {
display: 'flex',
flexDirection: 'column',
gap: '6px',
+ /* grid 项默认 min-width:auto:长占位符/命令会把整列撑破,必须显式收紧 */
+ minWidth: 0,
}),
c('.dshp-ssh-field-label', {
diff --git a/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts b/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts
index 9b5e36c3..6a4d803a 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts
@@ -23,6 +23,12 @@ export const cls = {
section: 'dshp-ssh-section',
title: 'dshp-ssh-title',
intro: 'dshp-ssh-intro',
+ tabs: 'dshp-ssh-tabs',
+ tabPanel: 'dshp-ssh-tab-panel',
+ hero: 'dshp-ssh-hero',
+ heroIcon: 'dshp-ssh-hero-icon',
+ heroTitle: 'dshp-ssh-hero-title',
+ heroHint: 'dshp-ssh-hero-hint',
chrome: 'dshp-ssh-chrome',
dangerAction: 'dshp-ssh-danger-action',
sectionHead: 'dshp-ssh-section-head',
@@ -51,6 +57,12 @@ export const cls = {
rowActions: 'dshp-ssh-row-actions',
editor: 'dshp-ssh-editor',
grid: 'dshp-ssh-grid',
+ span3: 'dshp-ssh-span-3',
+ span4: 'dshp-ssh-span-4',
+ span5: 'dshp-ssh-span-5',
+ span6: 'dshp-ssh-span-6',
+ span8: 'dshp-ssh-span-8',
+ span12: 'dshp-ssh-span-12',
field: 'dshp-ssh-field',
fieldLabel: 'dshp-ssh-field-label',
fieldInput: 'dshp-ssh-field-input',
diff --git a/packages/dsh-tauri-ssh-ui/src/client/utils/error.ts b/packages/dsh-tauri-ssh-ui/src/client/utils/error.ts
new file mode 100644
index 00000000..7a35a11e
--- /dev/null
+++ b/packages/dsh-tauri-ssh-ui/src/client/utils/error.ts
@@ -0,0 +1,13 @@
+import type { SshKey } from '../locales/index'
+import { isTransportError } from '../store/index'
+
+/**
+ * One operator-facing failure line: a transport code (route missing, empty
+ * body) reads as the localized "service unavailable" notice instead of a raw
+ * `SSH_API_*` code; host-provided prose renders verbatim.
+ * @param message - the stored failure text.
+ * @param t - the bound dictionary lookup.
+ */
+export function errorTextOf(message: string, t: (key: SshKey) => string): string {
+ return isTransportError(message) ? t('error.unavailable') : message
+}
diff --git a/packages/dsh-tauri-ssh/src/host/apply.test.ts b/packages/dsh-tauri-ssh/src/host/apply.test.ts
index 602a6202..e2242498 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.test.ts
@@ -1,67 +1,12 @@
-import type z from 'schemastery'
import type { Config as SshRemoteConfig } from './storage/index'
import type { SshHostContext } from './types/index'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { apply, inject, name, SshRemoteService } from './apply'
-import { MACHINES_NAMESPACE } from './storage/index'
import { MachineId } from './types/index'
-/** Scripted settings scope double. */
-function scriptedSettings() {
- const doc: Record<string, unknown> = {}
- let lastNs = ''
- const watchers: Array<(next: unknown, prev: unknown) => void> = []
- const update = vi.fn(async (patch: Record<string, unknown>) => {
- doc[lastNs] = deepMerge((doc[lastNs] as Record<string, unknown> | undefined) ?? {}, patch)
- for (const watcher of watchers) watcher(doc, {})
- })
- const replace = vi.fn(async (section: Record<string, unknown>) => {
- doc[lastNs] = section
- for (const watcher of watchers) watcher(doc, {})
- })
- return {
- doc,
- update,
- replace,
- register: vi.fn((ns: string, _schema: z<unknown>, options?: { base?: unknown }) => {
- lastNs = ns
- const base = options?.base ?? {}
- const resolved = (): unknown => ({ ...(base as object), ...(doc[ns] as object | undefined) })
- return {
- get: () => resolved(),
- watch: (callback: (next: unknown, prev: unknown) => void) => {
- watchers.push(callback)
- return () => {}
- },
- update,
- replace,
- }
- }),
- set(ns: string, section: Record<string, unknown>): void {
- doc[ns] = section
- for (const watcher of watchers) watcher(doc, {})
- },
- }
-}
-
-/** Plain-object deep merge used by the scripted settings scope. */
-function deepMerge(target: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {
- const next: Record<string, unknown> = { ...target }
- for (const [key, value] of Object.entries(patch)) {
- if (typeof value === 'object' && value !== null && !Array.isArray(value)
- && typeof next[key] === 'object' && next[key] !== null && !Array.isArray(next[key])) {
- next[key] = deepMerge(next[key] as Record<string, unknown>, value as Record<string, unknown>)
- }
- else {
- next[key] = value
- }
- }
- return next
-}
-
function scriptedHttpServer() {
const routes: Array<{ kind: string, path: string, handler?: unknown }> = []
return {
@@ -86,12 +31,15 @@ const baseConfig: SshRemoteConfig = {
reconnectMaxAttempts: 2,
}
-// Every service construction points the credential/discovery layer at a
-// scratch ssh directory — the developer's real ~/.ssh is never read.
+// Every service construction points the credential/discovery layer and the
+// state document at a scratch directory — the developer's real ~/.ssh and
+// harness home are never touched.
let sshDir: string
+let statePath: string
beforeEach(() => {
sshDir = mkdtempSync(join(tmpdir(), 'ssh-index-'))
+ statePath = join(sshDir, 'machines.json')
})
afterEach(() => {
@@ -99,7 +47,7 @@ afterEach(() => {
})
/** One scripted context: cordis-shaped surface without real cordis types. */
-function scriptedCtx(settings: unknown, webServer: unknown): { ctx: SshHostContext, disposers: Array<() => void> } {
+function scriptedCtx(webServer: unknown): { ctx: SshHostContext, disposers: Array<() => void> } {
const disposers: Array<() => void> = []
const ctx = {
provide: vi.fn(),
@@ -108,34 +56,45 @@ function scriptedCtx(settings: unknown, webServer: unknown): { ctx: SshHostConte
if (typeof disposer === 'function')
disposers.push(disposer)
}),
- settings,
webServer,
} as unknown as SshHostContext
return { ctx, disposers }
}
-/** Construct the service on scripted settings/webServer doubles. */
+/** Persist one state document before construction. */
+function writeState(state: { enabled?: boolean, machines?: Record<string, unknown> }): void {
+ writeFileSync(statePath, `${JSON.stringify({ version: 1, enabled: state.enabled ?? false, machines: state.machines ?? {} }, null, 2)}\n`)
+}
+
+/** The stored state document as the service wrote it. */
+function readState(): { version: number, enabled: boolean, machines: Record<string, Record<string, unknown>> } {
+ return JSON.parse(readFileSync(statePath, 'utf8')) as { version: number, enabled: boolean, machines: Record<string, Record<string, unknown>> }
+}
+
+/** Construct the service on a scripted webServer double. */
function construct(config: SshRemoteConfig = baseConfig): { ctx: SshHostContext, service: SshRemoteService, disposers: Array<() => void> } {
- const { ctx, disposers } = scriptedCtx(scriptedSettings(), scriptedHttpServer())
- return { ctx, service: new SshRemoteService(ctx, { ...config, sshDir }), disposers }
+ const { ctx, disposers } = scriptedCtx(scriptedHttpServer())
+ return { ctx, service: new SshRemoteService(ctx, { ...config, sshDir, statePath }), disposers }
}
function boot(overrides: {
- settings?: ReturnType<typeof scriptedSettings>
+ state?: { enabled?: boolean, machines?: Record<string, unknown> }
webServer?: ReturnType<typeof scriptedHttpServer>
config?: Partial<SshRemoteConfig>
} = {}) {
- const settings = overrides.settings ?? scriptedSettings()
+ if (overrides.state !== undefined)
+ writeState(overrides.state)
const webServer = overrides.webServer ?? scriptedHttpServer()
- const { ctx } = scriptedCtx(settings, webServer)
+ const { ctx } = scriptedCtx(webServer)
const config = {
...baseConfig,
knownHostsPath: join(homedir(), '.dsh', 'ssh', 'known-hosts.json'),
sshDir,
+ statePath,
...overrides.config,
}
const service = new SshRemoteService(ctx, config)
- return { ctx, settings, webServer, service }
+ return { ctx, webServer, service }
}
function machine(id: string): Record<string, unknown> {
@@ -153,7 +112,7 @@ function machine(id: string): Record<string, unknown> {
describe('ssh-remote plugin', () => {
it('declares its plugin metadata', () => {
expect(name).toBe('dsh-tauri-ssh')
- expect(inject).toEqual(['settings', 'webServer'])
+ expect(inject).toEqual(['webServer'])
expect(apply).toEqual(expect.any(Function))
})
@@ -161,7 +120,7 @@ describe('ssh-remote plugin', () => {
const descriptor = (await import('./apply')).default
expect(descriptor).toMatchObject({
name: 'dsh-tauri-ssh',
- inject: ['settings', 'webServer'],
+ inject: ['webServer'],
Config: expect.anything(),
})
expect(descriptor.apply).toEqual(expect.any(Function))
@@ -170,36 +129,63 @@ describe('ssh-remote plugin', () => {
expect(descriptor.apply).toBe(apply)
})
- it('registers the namespace and mounts the /api-ssh route', () => {
- const { settings, webServer } = boot()
- expect(settings.register).toHaveBeenCalledWith(String(MACHINES_NAMESPACE), expect.anything(), { base: { machines: {} } })
+ it('mounts the /api-ssh route without any settings service', () => {
+ const { webServer } = boot()
expect(webServer.routes).toMatchObject([{ kind: 'prefix', path: '/api-ssh' }])
expect(webServer.routes[0]?.handler).toEqual(expect.any(Function))
})
- it('loads machine profiles from the settings namespace', () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })
- const { service } = boot({ settings })
+ it('starts switched off and persists the enable switch', async () => {
+ const { service } = boot()
+ expect(service.enabled()).toBe(false)
+ await service.setEnabled(true)
+ expect(service.enabled()).toBe(true)
+ expect(readState()).toMatchObject({ version: 1, enabled: true })
+ await service.setEnabled(false)
+ expect(readState()).toMatchObject({ enabled: false })
+ })
+
+ it('disconnects every machine when the feature is switched off', async () => {
+ const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } } })
+ const dispose = vi.spyOn(service.manager, 'dispose').mockResolvedValue(undefined)
+ await service.setEnabled(true)
+ expect(dispose).not.toHaveBeenCalled()
+ await service.setEnabled(false)
+ expect(dispose).toHaveBeenCalledTimes(1)
+ })
+
+ it('loads machine profiles from the state document', () => {
+ const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } } })
const views = service.profileViews()
expect(views.map(view => view.id)).toEqual(['a'])
expect(views[0]).toMatchObject({ name: 'machine-a', hasPassword: true })
expect(views[0]).not.toHaveProperty('password')
})
- it('refreshes the manager when the namespace changes', () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a'), b: machine('b') } })
- const { service } = boot({ settings })
- expect(service.profileViews()).toHaveLength(2)
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })
- expect(service.profileViews().map(view => view.id)).toEqual(['a'])
+ it('reads a corrupt or absent document as the default state', () => {
+ writeFileSync(statePath, '{ not json')
+ const corrupt = boot()
+ expect(corrupt.service.enabled()).toBe(false)
+ expect(corrupt.service.profileViews()).toEqual([])
+
+ rmSync(statePath, { force: true })
+ const absent = boot()
+ expect(absent.service.enabled()).toBe(false)
+ expect(absent.service.profileViews()).toEqual([])
})
- it('rejects a dict key that disagrees with the profile id', () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { b: machine('a') } })
- expect(() => boot({ settings })).toThrow(/dict key must equal the profile id/)
+ it('drops a stored row whose dict key disagrees with the profile id', () => {
+ const { service } = boot({ state: { enabled: true, machines: { b: machine('a') } } })
+ expect(service.profileViews()).toEqual([])
+ })
+
+ it('refreshes the manager when the stored machines change', async () => {
+ const { service } = boot()
+ await service.save('a' as never, { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 })
+ await service.save('b' as never, { name: 'beta', host: '10.0.0.2', port: 22, user: 'root', remotePort: 3080 })
+ expect(service.profileViews()).toHaveLength(2)
+ await service.remove('a' as never)
+ expect(service.profileViews().map(view => view.id)).toEqual(['b'])
})
it('exposes the manager connection plane', async () => {
@@ -218,8 +204,8 @@ describe('ssh-remote plugin', () => {
expect(result).toEqual({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true })
})
- it('saves a machine through the settings scope and refreshes the manager', async () => {
- const { service, settings } = boot()
+ it('saves a machine into the state document and refreshes the manager', async () => {
+ const { service } = boot()
await service.save('a' as never, {
name: 'alpha',
host: '10.0.0.1',
@@ -227,19 +213,15 @@ describe('ssh-remote plugin', () => {
user: 'root',
remotePort: 3080,
}, { password: 'sekrit', passphrase: 'PHRASE' })
- expect(settings.replace).toHaveBeenCalledWith({
- machines: {
- a: {
- id: 'a',
- name: 'alpha',
- host: '10.0.0.1',
- port: 22,
- user: 'root',
- remotePort: 3080,
- password: 'sekrit',
- passphrase: 'PHRASE',
- },
- },
+ expect(readState().machines.a).toEqual({
+ id: 'a',
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ remotePort: 3080,
+ password: 'sekrit',
+ passphrase: 'PHRASE',
})
const views = service.profileViews()
expect(views.map(view => view.id)).toEqual(['a'])
@@ -247,9 +229,7 @@ describe('ssh-remote plugin', () => {
})
it('keeps stored secrets on save unless rewritten', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })
- const { service } = boot({ settings })
+ const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } } })
await service.save('a' as never, {
name: 'alpha-2',
host: '10.0.0.1',
@@ -262,14 +242,15 @@ describe('ssh-remote plugin', () => {
})
it('clears optional appearance fields on save and keeps sibling machines intact', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), {
- machines: {
- a: { ...machine('a'), color: '#ff0000', tintBorder: true, startCommand: 'custom dsh web' },
- b: machine('b'),
+ const { service } = boot({
+ state: {
+ enabled: true,
+ machines: {
+ a: { ...machine('a'), color: '#ff0000', tintBorder: true, startCommand: 'custom dsh web' },
+ b: machine('b'),
+ },
},
})
- const { service } = boot({ settings })
await service.save('a' as never, {
name: 'alpha-3',
host: '10.0.0.1',
@@ -279,22 +260,18 @@ describe('ssh-remote plugin', () => {
})
const viewA = service.profileViews().find(view => view.id === 'a')
// 清除方向:color/tintBorder/startCommand 的空/关形态(row 缺位)必须真
- // 清除——save 走整节 replace 精确写;若退回 update 深合并,已存层会把
- // 这三个字段复活(回归守护)。
+ // 清除——save 写的是整份 profile,缺位字段不会从旧值复活(回归守护)。
expect(viewA).not.toHaveProperty('color')
expect(viewA).not.toHaveProperty('tintBorder')
expect(viewA).not.toHaveProperty('startCommand')
- expect(settings.update).not.toHaveBeenCalled()
- // 精确写重述全表:同表其他机器原样保留
+ // 同表其他机器原样保留
expect(service.profileViews().find(view => view.id === 'b')).toMatchObject({ name: 'machine-b', hasPassword: true })
})
it('keeps stored secrets on save and stores the start command', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), {
- machines: { a: { ...machine('a'), passphrase: 'OLD-PHRASE' } },
+ const { service } = boot({
+ state: { enabled: true, machines: { a: { ...machine('a'), passphrase: 'OLD-PHRASE' } } },
})
- const { service } = boot({ settings })
await service.save('a' as never, {
name: 'alpha',
host: '10.0.0.1',
@@ -313,9 +290,7 @@ describe('ssh-remote plugin', () => {
})
it('stores the remote profile name on save and clears it when the row omits it', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: { ...machine('a'), profileName: 'alpha' } } })
- const { service } = boot({ settings })
+ const { service } = boot({ state: { enabled: true, machines: { a: { ...machine('a'), profileName: 'alpha' } } } })
await service.save('a' as never, {
name: 'alpha',
host: '10.0.0.1',
@@ -338,11 +313,9 @@ describe('ssh-remote plugin', () => {
})
it('keeps whichever stored secrets exist and rewrites only typed ones', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), {
- machines: { a: { ...machine('a'), password: undefined, passphrase: 'OLD-PHRASE' } },
+ const { service } = boot({
+ state: { enabled: true, machines: { a: { ...machine('a'), password: undefined, passphrase: 'OLD-PHRASE' } } },
})
- const { service } = boot({ settings })
await service.save('a' as never, {
name: 'alpha',
host: '10.0.0.1',
@@ -352,9 +325,9 @@ describe('ssh-remote plugin', () => {
}, { password: 'NEW-PW' })
const views = service.profileViews()
expect(views[0]).toMatchObject({ name: 'alpha', hasPassword: true, hasPassphrase: true })
- const stored = settings.doc[String(MACHINES_NAMESPACE)] as { machines: Record<string, Record<string, unknown>> }
- expect(stored.machines.a?.password).toBe('NEW-PW')
- expect(stored.machines.a?.passphrase).toBe('OLD-PHRASE')
+ const stored = readState().machines.a
+ expect(stored?.password).toBe('NEW-PW')
+ expect(stored?.passphrase).toBe('OLD-PHRASE')
})
it('discovers ~/.ssh/config aliases as read-only machines', async () => {
@@ -391,9 +364,7 @@ describe('ssh-remote plugin', () => {
it('lets a manual machine shadow a config alias', async () => {
writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n')
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { dev: { ...machine('dev'), host: '10.1.1.1' } } })
- const { service } = boot({ settings })
+ const { service } = boot({ state: { enabled: true, machines: { dev: { ...machine('dev'), host: '10.1.1.1' } } } })
expect((await service.discoveredViews()).map(view => view.id)).toEqual([])
expect(service.profileViews().map(view => view.id)).toEqual(['dev'])
})
@@ -415,31 +386,27 @@ describe('ssh-remote plugin', () => {
})
it('applies the configured default start command to manual machines without their own', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a') } })
- const { service } = boot({ settings, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })
+ const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } }, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })
await service.disconnect('a' as never)
const views = service.manager.profileViews()
expect(views[0]).toMatchObject({ id: 'a', startCommand: 'dsh web --port 3080' })
})
it('keeps a manual start command over the configured default', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), {
- machines: { a: { ...machine('a'), startCommand: 'custom dsh web' } },
+ const { service } = boot({
+ state: { enabled: true, machines: { a: { ...machine('a'), startCommand: 'custom dsh web' } } },
+ config: { remotePort: 3080, startCommand: 'dsh web --port {port}' },
})
- const { service } = boot({ settings, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })
await service.disconnect('a' as never)
const views = service.manager.profileViews()
expect(views[0]).toMatchObject({ id: 'a', startCommand: 'custom dsh web' })
})
- it('removes a machine through the settings scope', async () => {
- const settings = scriptedSettings()
- settings.set(String(MACHINES_NAMESPACE), { machines: { a: machine('a'), b: machine('b') } })
- const { service } = boot({ settings })
+ it('removes a machine from the state document', async () => {
+ const { service } = boot({ state: { enabled: true, machines: { a: machine('a'), b: machine('b') } } })
await service.remove('a' as never)
expect(service.profileViews().map(view => view.id)).toEqual(['b'])
+ expect(readState().machines).not.toHaveProperty('a')
})
it('delegates test and connect to the manager', async () => {
@@ -448,18 +415,21 @@ describe('ssh-remote plugin', () => {
await expect(service.connect('ghost' as never)).rejects.toMatchObject({ code: 'machine-not-found' })
})
- it('defaults the known-hosts path from DSH_HOME or the home directory', () => {
+ it('defaults the state document and known-hosts path under DSH_HOME', async () => {
const previous = process.env.DSH_HOME
+ const home = join(sshDir, 'dsh-home')
try {
- process.env.DSH_HOME = '/tmp/dsh-home'
- expect(construct().service).toBeInstanceOf(SshRemoteService)
- delete process.env.DSH_HOME
- expect(construct().service).toBeInstanceOf(SshRemoteService)
+ process.env.DSH_HOME = home
+ const service = constructWithDefaults()
+ expect(service).toBeInstanceOf(SshRemoteService)
+ await service.setEnabled(true)
+ expect(JSON.parse(readFileSync(join(home, 'ssh', 'machines.json'), 'utf8'))).toMatchObject({ version: 1, enabled: true })
}
finally {
if (previous === undefined)
delete process.env.DSH_HOME
- else process.env.DSH_HOME = previous
+ else
+ process.env.DSH_HOME = previous
}
})
@@ -476,3 +446,9 @@ describe('ssh-remote plugin', () => {
expect(apply(ctx, baseConfig)).toBeInstanceOf(SshRemoteService)
})
})
+
+/** Construct on the config's path defaults (only `sshDir` is redirected). */
+function constructWithDefaults(): SshRemoteService {
+ const { ctx } = scriptedCtx(scriptedHttpServer())
+ return new SshRemoteService(ctx, { ...baseConfig, sshDir })
+}
diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.ts
index 243f7ccf..6a9f19ed 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.ts
@@ -1,18 +1,18 @@
/**
- * host/apply.ts — the DSH remote-machine host plugin assembly: registers the
- * `ssh-machines` settings namespace, owns the SSH connection manager (TOFU
- * host keys, remote `dsh web` auto-start, loopback tunnels), and mounts the
- * same-origin `/api-ssh` route on `ctx.webServer` for the settings page. No
- * upstream DSH source is touched: every integration is a documented cordis
- * extension point.
+ * host/apply.ts — the DSH remote-machine host plugin assembly: owns the
+ * plugin state document (`ssh/machines.json`: the enable switch and the manual
+ * machine table), the SSH connection manager (TOFU host keys, remote `dsh web`
+ * auto-start, loopback tunnels), and mounts the same-origin `/api-ssh` route on
+ * `ctx.webServer` for the settings page. No upstream DSH source is touched:
+ * every integration is a documented cordis extension point.
* @module dsh-tauri-ssh/host/apply
*/
import type z from 'schemastery'
import type { SshApiHost } from './routes/index'
import type { SshHostBlock } from './service/ssh-config'
-import type { MachinesValue, Config as SshRemoteConfig } from './storage/index'
-import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineEventsPage, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef } from './types/index'
+import type { Config as SshRemoteConfig } from './storage/index'
+import type { MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineEventsPage, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef } from './types/index'
import { homedir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
@@ -26,20 +26,32 @@ import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResol
import { SyncEngine } from './service/sync'
import { profileAllowlistReader, profileDependenciesReader, skillRootsScanner, tarPacker } from './service/sync-local'
import { Ssh2Transport } from './service/transport'
-import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MACHINES_NAMESPACE, machinesFromValue, MachinesSchema } from './storage/index'
+import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MachineStateStore } from './storage/index'
import { MachineId } from './types/index'
+/** The harness home every plugin-owned document lives under. */
+function harnessHome(): string {
+ return process.env.DSH_HOME ?? join(homedir(), '.dsh')
+}
+
/** Default location of the TOFU host-key document under the harness home. */
function defaultKnownHostsPath(): string {
- return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'ssh', 'known-hosts.json')
+ return join(harnessHome(), 'ssh', 'known-hosts.json')
+}
+
+/** Default location of the machine state document under the harness home. */
+function defaultStatePath(): string {
+ return join(harnessHome(), 'ssh', 'machines.json')
}
/**
* The plugin service: manager-backed connection plane plus the `/api-ssh`
- * handler face. Two machine sources feed the manager: the `ssh-machines`
- * settings namespace (manual machines, with secrets) and the host's own
- * `~/.ssh/config` (discovered Host aliases, read-only, no secrets) — a
- * manual machine with the same id as an alias shadows it.
+ * handler face. Two machine sources feed the manager: the plugin state
+ * document (manual machines, with secrets) and the host's own `~/.ssh/config`
+ * (discovered Host aliases, read-only, no secrets) — a manual machine with the
+ * same id as an alias shadows it. The SSH feature is off until the operator
+ * enables it from the settings page; while off the API serves the flag and
+ * refuses to enumerate machines.
*/
export class SshRemoteService implements SshApiHost {
/** The connection manager (transport, TOFU store, and per-machine state). */
@@ -48,8 +60,8 @@ export class SshRemoteService implements SshApiHost {
/** The machine event channel drained by the `/api-ssh` `machine.events` method. */
readonly machineEvents: SshMachineEvents
- /** The registered settings scope; the write path for machine CRUD. */
- private scope!: HostSettingsScope<MachinesValue>
+ /** The plugin state document (enable switch + manual machines). */
+ readonly store: MachineStateStore
/** The ssh directory the discovered aliases and credentials come from. */
private readonly sshDir: string
@@ -64,7 +76,7 @@ export class SshRemoteService implements SshApiHost {
private readonly sync: SyncEngine
/**
- * @param ctx - the plugin context (settings + webServer available through inject).
+ * @param ctx - the plugin context (webServer available through inject).
* @param config - the validated plugin config.
*/
constructor(ctx: SshHostContext, config: SshRemoteConfig) {
@@ -72,6 +84,7 @@ export class SshRemoteService implements SshApiHost {
this.homeDir = homedir()
this.sshDir = config.sshDir ?? join(this.homeDir, '.ssh')
this.config = config
+ this.store = new MachineStateStore(config.statePath ?? defaultStatePath())
this.machineEvents = new SshMachineEvents()
this.manager = new SshManager({
transport: new Ssh2Transport(
@@ -96,10 +109,6 @@ export class SshRemoteService implements SshApiHost {
// The settings page polls status through /api-ssh; no live consumers.
},
})
- const scope = ctx.settings.register<MachinesValue>(String(MACHINES_NAMESPACE), MachinesSchema, {
- base: { machines: {} },
- })
- this.scope = scope
// The sync engine: local profile/skill sources, remote commands over a
// dedicated session, the install-class deadline per remote command.
this.sync = new SyncEngine({
@@ -110,7 +119,7 @@ export class SshRemoteService implements SshApiHost {
...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },
})
this.manager.refreshProfiles(this.applyStartDefaults(this.manualProfiles()))
- scope.watch(() => {
+ this.store.subscribe(() => {
void this.syncProfiles()
})
// Mount the same-origin connection-plane API.
@@ -124,9 +133,21 @@ export class SshRemoteService implements SshApiHost {
})
}
- /** The manual profiles, read fresh from the settings scope. */
+ /** Whether the SSH feature is switched on. */
+ enabled(): boolean {
+ return this.store.enabled()
+ }
+
+ /** Flip the feature switch; switching off drops every live connection. */
+ async setEnabled(enabled: boolean): Promise<void> {
+ this.store.setEnabled(enabled)
+ if (!enabled)
+ await this.manager.dispose()
+ }
+
+ /** The manual profiles, read fresh from the state document. */
private manualProfiles(): Map<MachineId, MachineProfile> {
- return machinesFromValue(this.scope.get())
+ return this.store.machines()
}
/** The configured default start command, `{port}` substituted, or none. */
@@ -233,17 +254,16 @@ export class SshRemoteService implements SshApiHost {
/**
* Upsert one machine profile: merge the config row and any freshly typed
* secrets into the stored profile (secrets omitted keep the stored value).
- * Optional fields absent from the row are *cleared* — the write restates
- * the full machine table through `replace` (exact), because `update`'s
- * deep merge would resurrect cleared fields from the stored layer. The
- * watch refreshes the manager automatically.
+ * Optional fields absent from the row are *cleared* — the write restates the
+ * whole profile, so a cleared field cannot be resurrected from a previous
+ * layer (the former settings deep-merge did exactly that). The store
+ * subscription refreshes the manager automatically.
* @param machineId - the profile id (the settings dict key).
* @param row - the config fields as the settings page edited them.
* @param secrets - write-only secret values; absent fields keep stored ones.
*/
async save(machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite): Promise<void> {
- const machines = machinesFromValue(this.scope.get())
- const existing = machines.get(machineId)
+ const existing = this.store.machines().get(machineId)
const next: MachineProfile = {
id: machineId,
name: row.name,
@@ -272,23 +292,16 @@ export class SshRemoteService implements SshApiHost {
if (secrets.passphrase !== undefined && secrets.passphrase !== '')
next.passphrase = secrets.passphrase
}
- // 精确写:像 remove() 一样整节 replace 重述全量机器表。`update` 是深合
- // 并——被清除的可选字段(color/tintBorder/startCommand 的空/关形态在
- // next 中缺位)会从已存层复活,导致「清除」静默失效。
- machines.set(machineId, next)
- await this.scope.replace({ machines: Object.fromEntries(machines) })
+ this.store.saveMachine(next)
}
/**
- * Delete one machine profile. The owner scope's `replace` restates the full
- * section (in-process values include the stored secrets), so the removal is
- * exact and nothing else is touched.
- * @param machineId - the profile id to drop (idempotent for absent ids).
+ * Delete one machine profile (idempotent for absent ids); the store
+ * subscription refreshes the manager, which drops the machine's connection.
+ * @param machineId - the profile id to drop.
*/
async remove(machineId: MachineId): Promise<void> {
- const machines = machinesFromValue(this.scope.get())
- machines.delete(machineId)
- await this.scope.replace({ machines: Object.fromEntries(machines) })
+ this.store.removeMachine(machineId)
}
/** The local plugins and skills available to sync (the panel's selection list). */
@@ -333,8 +346,8 @@ export class SshRemoteService implements SshApiHost {
/** Cordis plugin name. */
export const name = SSH_PLUGIN_NAME
-/** Required services: the settings seam (namespace) and the webserver (route mount). */
-export const inject = ['settings', 'webServer']
+/** Required services: the webserver (route mount). */
+export const inject = ['webServer']
/** Validated plugin config; schemastery applies defaults before construction. */
export const Config: z<SshRemoteConfig> = ConfigSchema
@@ -353,7 +366,7 @@ export function apply(ctx: SshHostContext, config: SshRemoteConfig): SshRemoteSe
* The cordis plugin descriptor. The loader imports the module and reads
* `apply`/`Config`/`inject`/`name` from the **default export object** — a
* bare function default carries neither the schema nor the inject list, so
- * config defaults would never apply and the settings/webServer services
- * would not be injected.
+ * config defaults would never apply and the webServer service would not be
+ * injected.
*/
export default { apply, Config, inject, name }
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
index a8fed0c2..d7efe8f7 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
@@ -28,6 +28,8 @@ log.append(MachineId('m1'), 'ready', '远端实例已就绪', { terminal: 'succe
function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {
return {
sessionRole: () => ({ remote: false }),
+ enabled: () => true,
+ setEnabled: async () => {},
profileViews: () => [view],
discoveredViews: async () => [],
status: () => ({ machineId: MachineId('m1'), state: 'disconnected' }),
@@ -147,6 +149,37 @@ describe('/api-ssh handler', () => {
expect(remote.body).toEqual({ ok: true, value: { remote: true, origin: 'ops' } })
})
+ it('reads and writes the SSH feature switch', async () => {
+ const setEnabled = vi.fn(async () => {})
+ const off = fakeHost({ enabled: () => false, setEnabled })
+ expect((await call(off, JSON.stringify({ method: 'settings.get' }))).body)
+ .toEqual({ ok: true, value: { enabled: false } })
+
+ const written = await call(off, JSON.stringify({ method: 'settings.set', payload: { enabled: true } }))
+ expect(written.status).toBe(200)
+ expect(written.body).toEqual({ ok: true, value: { enabled: true } })
+ expect(setEnabled).toHaveBeenCalledWith(true)
+ })
+
+ it('refuses a settings.set without a boolean switch', async () => {
+ const setEnabled = vi.fn(async () => {})
+ const host = fakeHost({ setEnabled })
+ const { body } = await call(host, JSON.stringify({ method: 'settings.set', payload: {} }))
+ expect(body).toMatchObject({ ok: false, error: { message: 'missing enabled' } })
+ expect(setEnabled).not.toHaveBeenCalled()
+ })
+
+ it('serves no machines while the feature is off (keeps the flag visible)', async () => {
+ const host = fakeHost({
+ enabled: () => false,
+ profileViews: () => [view],
+ discoveredViews: async () => [view],
+ })
+ const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))
+ expect(status).toBe(200)
+ expect(body).toEqual({ ok: true, value: { enabled: false, items: [], discovered: [] } })
+ })
+
it('lists machines with live status', async () => {
const host = fakeHost({
status: () => ({ machineId: MachineId('m1'), state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1', lastError: 'boom' }),
@@ -156,6 +189,7 @@ describe('/api-ssh handler', () => {
expect(body).toEqual({
ok: true,
value: {
+ enabled: true,
items: [{
...view,
state: 'connected',
@@ -188,6 +222,7 @@ describe('/api-ssh handler', () => {
expect(body).toEqual({
ok: true,
value: {
+ enabled: true,
items: [{ ...view, state: 'disconnected' }],
discovered: [{
id: 'dev',
@@ -214,6 +249,7 @@ describe('/api-ssh handler', () => {
expect(body).toEqual({
ok: true,
value: {
+ enabled: true,
items: [{
...view,
state: 'connecting',
@@ -227,7 +263,7 @@ describe('/api-ssh handler', () => {
it('lists machines without link fields while disconnected', async () => {
const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }))
expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: { items: [{ ...view, state: 'disconnected' }], discovered: [] } })
+ expect(body).toEqual({ ok: true, value: { enabled: true, items: [{ ...view, state: 'disconnected' }], discovered: [] } })
})
it('rejects request bodies over the 64 KiB bound', async () => {
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.ts b/packages/dsh-tauri-ssh/src/host/routes/index.ts
index 415cd013..9170b762 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.ts
@@ -7,12 +7,12 @@
* POST /api-ssh { "method": "machine.list", "payload": {} }
* → 200 { "ok": true, "value": ... } | { "ok": false, "error": { "code", "message" } }
*
- * Machines are stored in the `ssh-machines` settings namespace; this API
- * serves the connection plane (list/test/connect/disconnect/install), the
- * per-machine bootstrap event drain (`machine.events`: ring-buffered,
- * seq-cursored polling — no SSE/WebSocket), and the CRUD writes
- * (save/remove), which is exactly what the settings page cannot do through
- * the settings domain.
+ * The plugin state lives in the plugin-owned state document; this API serves
+ * the feature switch (`settings.get`/`settings.set`), the connection plane
+ * (list/test/connect/disconnect/install), the per-machine bootstrap event
+ * drain (`machine.events`: ring-buffered, seq-cursored polling — no
+ * SSE/WebSocket), and the CRUD writes (save/remove), which is exactly what the
+ * settings page cannot do through the settings domain.
* @module dsh-tauri-ssh/host/routes
*/
@@ -33,9 +33,9 @@ export type SshApiResponse
| { ok: false, error: { code: string, message: string } }
/**
- * The connection-plane method set (CRUD lives here too: the settings RPC only
- * serves an upstream allowlist, so the page writes through this route), plus
- * the S4-owned `sync.*` surface (engine + execution + per-item results).
+ * The connection-plane method set (CRUD lives here too: the settings domain
+ * only serves an upstream allowlist, so the page writes through this route),
+ * the plugin state switch, plus the S4-owned `sync.*` surface.
*/
export type SshApiMethod
= | 'machine.list'
@@ -47,6 +47,8 @@ export type SshApiMethod
| 'machine.save'
| 'machine.remove'
| 'session.role'
+ | 'settings.get'
+ | 'settings.set'
| 'sync.preview'
| 'sync.apply'
@@ -68,6 +70,10 @@ export interface SshMachineListItem extends MachineView {
export interface SshApiHost {
/** Whether this host instance is itself a remote target of an SSH session. */
sessionRole: () => { remote: boolean, origin?: string }
+ /** Whether the SSH feature is switched on. */
+ enabled: () => boolean
+ /** Flip the feature switch. */
+ setEnabled: (enabled: boolean) => Promise<void>
profileViews: () => MachineView[]
/** The read-only `~/.ssh/config` alias machines (awaits the config read). */
discoveredViews: () => Promise<MachineView[]>
@@ -191,10 +197,26 @@ export function createSshApiHandler(host: SshApiHost): (req: IncomingMessage, re
respond(200, { ok: true, value: host.sessionRole() })
return
}
+ case 'settings.get': {
+ respond(200, { ok: true, value: { enabled: host.enabled() } })
+ return
+ }
+ case 'settings.set': {
+ const enabled = enabledOf(payload)
+ await host.setEnabled(enabled)
+ respond(200, { ok: true, value: { enabled } })
+ return
+ }
case 'machine.list': {
+ // 未启用:不枚举任何机器(不读 ~/.ssh/config,也不碰连接面),只回报开关,
+ // 壳层据此不渲染「本地」控件。
+ if (!host.enabled()) {
+ respond(200, { ok: true, value: { enabled: false, items: [], discovered: [] } })
+ return
+ }
const items: SshMachineListItem[] = host.profileViews().map(view => listItemOf(host, view))
const discovered: SshMachineListItem[] = (await host.discoveredViews()).map(view => listItemOf(host, view))
- respond(200, { ok: true, value: { items, discovered } })
+ respond(200, { ok: true, value: { enabled: true, items, discovered } })
return
}
case 'machine.test': {
@@ -265,6 +287,13 @@ function machineIdOf(payload: Record<string, unknown>): MachineId {
return MachineId(payload.machineId)
}
+/** Read the settings.set payload; a non-boolean switch fails loud. */
+function enabledOf(payload: Record<string, unknown>): boolean {
+ if (typeof payload.enabled !== 'boolean')
+ throw new Error('missing enabled')
+ return payload.enabled
+}
+
/** Read the optional event poll cursor; absent or non-numeric means "from the start". */
function sinceSeqOf(payload: Record<string, unknown>): number | undefined {
if (payload.sinceSeq === undefined)
diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.ts
index d242d6a0..e3ed5a80 100644
--- a/packages/dsh-tauri-ssh/src/host/storage/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/storage/index.ts
@@ -1,26 +1,18 @@
/**
- * Plugin config and the `ssh-machines` settings-namespace schema. The
- * namespace stores a dict of machine profiles keyed by machine id — a dict
- * (not an array) so a redacted client can add, edit, and delete one machine
- * through `settings.update` deep-merge and `settings.mutate` path-unset
- * without ever re-supplying (or deleting) secrets it never saw.
+ * Plugin config and the plugin-owned machine state document. 0.1.7 removed
+ * `ctx.settings.register` (namespaces are now plugin Config entries), so the
+ * machine table and the enable flag live in one JSON document under the
+ * harness home — the same shape of self-owned persistence the TOFU host-key
+ * store already uses, and therefore kernel-version agnostic.
* @module dsh-tauri-ssh/host/storage
*/
-import type { MachineProfile } from '../types/index'
+import type { MachineId, MachineProfile } from '../types/index'
+import { randomBytes } from 'node:crypto'
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname } from 'pathe'
import z from 'schemastery'
-import { MachineId } from '../types/index'
-
-/** One settings-namespace key (the harness brands these; the wire treats them as strings). */
-export type SettingsNamespace = string & { readonly __namespace: unique symbol }
-
-/** Brand a settings namespace key. */
-export function settingsNamespace(name: string): SettingsNamespace {
- return name as SettingsNamespace
-}
-
-/** Settings namespace key owning the machine profile dict. */
-export const MACHINES_NAMESPACE = settingsNamespace('ssh-machines')
+import { MachineId as brandMachineId } from '../types/index'
/** Default TCP port of the remote `dsh web` instance (loopback). */
export const DEFAULT_REMOTE_PORT = 3080
@@ -31,34 +23,12 @@ export const DEFAULT_SSH_PORT = 22
/** Default remote dsh profile name (`dsh --profile <name> web`). */
export const DEFAULT_REMOTE_PROFILE = 'remote'
-/**
- * One machine profile schema: the settings-namespace member shape. Credential
- * fields are `role('secret')` positions — redacted from every wire surface,
- * present in the owner scope's resolved value. Authentication itself runs on
- * the host's `~/.ssh`; the stored fields are only the optional fallbacks.
- */
-export const MachineSchema = z.object({
- id: z.string().required(),
- name: z.string().required(),
- host: z.string().required(),
- port: z.number().default(DEFAULT_SSH_PORT),
- user: z.string().required(),
- password: z.string().role('secret'),
- passphrase: z.string().role('secret'),
- remotePort: z.number().default(DEFAULT_REMOTE_PORT),
- profileName: z.string(),
- startCommand: z.string(),
- color: z.string(),
- tintBorder: z.boolean(),
-})
+/** Schema version of the state document. */
+export const STATE_VERSION = 1
-/** The whole `ssh-machines` namespace value: a dict of profiles by machine id. */
-export const MachinesSchema = z.object({
- machines: z.dict(MachineSchema).default({}),
-}) as unknown as z<MachinesValue>
-
-/** Resolved value shape of the `ssh-machines` namespace. */
-export interface MachinesValue {
+/** The persisted plugin state: the feature switch plus the manual machine dict. */
+export interface SshState {
+ enabled: boolean
machines: Record<string, MachineProfile>
}
@@ -77,6 +47,8 @@ export interface Config {
healthPollAttempts: number
/** Override for the TOFU known-hosts file (defaults under the harness home). */
knownHostsPath?: string
+ /** Override for the machine state document (defaults under the harness home). */
+ statePath?: string
/** Override for the `~/.ssh` directory the credentials resolve against. */
sshDir?: string
/** Default remote `dsh web` port for machines that do not override it. */
@@ -127,6 +99,7 @@ export const ConfigSchema: z<Config> = z.object({
healthPollIntervalMs: z.number().default(1_000),
healthPollAttempts: z.number().default(30),
knownHostsPath: z.string(),
+ statePath: z.string(),
sshDir: z.string(),
remotePort: z.number().default(DEFAULT_REMOTE_PORT),
startCommand: z.string(),
@@ -140,17 +113,142 @@ export const ConfigSchema: z<Config> = z.object({
reconnectMaxAttempts: z.number().default(6),
})
-/** Normalize a resolved namespace value into a machine profile map keyed by id. */
-export function machinesFromValue(value: MachinesValue): Map<MachineId, MachineProfile> {
+/** Project one stored record; malformed rows are dropped, never fatal. */
+export function machineProfileOf(raw: unknown): MachineProfile | undefined {
+ if (typeof raw !== 'object' || raw === null)
+ return undefined
+ const value = raw as Record<string, unknown>
+ if (typeof value.id !== 'string' || value.id === '')
+ return undefined
+ if (typeof value.name !== 'string')
+ return undefined
+ if (typeof value.host !== 'string' || value.host === '')
+ return undefined
+ if (typeof value.user !== 'string')
+ return undefined
+ return {
+ id: brandMachineId(value.id),
+ name: value.name,
+ host: value.host,
+ port: typeof value.port === 'number' ? value.port : DEFAULT_SSH_PORT,
+ user: value.user,
+ remotePort: typeof value.remotePort === 'number' ? value.remotePort : DEFAULT_REMOTE_PORT,
+ ...typeof value.password === 'string' && value.password !== '' ? { password: value.password } : {},
+ ...typeof value.passphrase === 'string' && value.passphrase !== '' ? { passphrase: value.passphrase } : {},
+ ...typeof value.profileName === 'string' && value.profileName !== '' ? { profileName: value.profileName } : {},
+ ...typeof value.startCommand === 'string' && value.startCommand !== '' ? { startCommand: value.startCommand } : {},
+ ...typeof value.color === 'string' && value.color !== '' ? { color: value.color } : {},
+ ...value.tintBorder === true ? { tintBorder: true } : {},
+ }
+}
+
+/** Project a stored dict into a profile map; a mismatched row is dropped. */
+export function machinesOf(value: unknown): Map<MachineId, MachineProfile> {
const profiles = new Map<MachineId, MachineProfile>()
- for (const [key, profile] of Object.entries(value.machines)) {
- const id = MachineId(key)
- if (profile.id !== key) {
- throw new Error(
- `ssh-machines: machine "${key}" carries id "${profile.id}"; the dict key must equal the profile id`,
- )
- }
- profiles.set(id, { ...profile, id })
+ if (typeof value !== 'object' || value === null)
+ return profiles
+ for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
+ const profile = machineProfileOf(raw)
+ if (profile === undefined || profile.id !== key)
+ continue
+ profiles.set(brandMachineId(key), profile)
}
return profiles
}
+
+/** Parse one state document; an absent or corrupt file reads as the default state. */
+function readState(file: string): SshState {
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
+ }
+ catch {
+ return { enabled: false, machines: {} }
+ }
+ if (typeof parsed !== 'object' || parsed === null)
+ return { enabled: false, machines: {} }
+ const record = parsed as { enabled?: unknown, machines?: unknown }
+ const machines: Record<string, MachineProfile> = {}
+ for (const [key, profile] of machinesOf(record.machines))
+ machines[key] = profile
+ return { enabled: record.enabled === true, machines }
+}
+
+/** Atomically replace `file` with `content` (same-directory rename, owner-only). */
+function writeStateFile(file: string, content: string): void {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ const temp = `${file}.${randomBytes(6).toString('hex')}.tmp`
+ try {
+ writeFileSync(temp, content, { mode: 0o600, flag: 'wx' })
+ renameSync(temp, file)
+ }
+ catch (error) {
+ rmSync(temp, { force: true })
+ throw error
+ }
+}
+
+/**
+ * File-backed machine state. The document is read once at construction (the
+ * manager needs the profile map synchronously) and every write is atomic and
+ * announces itself to the service, which refreshes the manager.
+ */
+export class MachineStateStore {
+ private state: SshState
+
+ private readonly listeners = new Set<() => void>()
+
+ /** @param file - absolute path of the state document. */
+ constructor(private readonly file: string) {
+ this.state = readState(file)
+ }
+
+ /** Whether the SSH feature is switched on. */
+ enabled(): boolean {
+ return this.state.enabled
+ }
+
+ /** The stored manual machines keyed by id. */
+ machines(): Map<MachineId, MachineProfile> {
+ const profiles = new Map<MachineId, MachineProfile>()
+ for (const [key, profile] of Object.entries(this.state.machines)) {
+ const id = brandMachineId(key)
+ profiles.set(id, { ...profile, id })
+ }
+ return profiles
+ }
+
+ /** Subscribe to in-process changes; returns the unsubscribe. */
+ subscribe(listener: () => void): () => void {
+ this.listeners.add(listener)
+ return () => this.listeners.delete(listener)
+ }
+
+ /** Flip the feature switch (idempotent). */
+ setEnabled(enabled: boolean): void {
+ if (this.state.enabled === enabled)
+ return
+ this.commit({ ...this.state, enabled })
+ }
+
+ /** Upsert one machine profile. */
+ saveMachine(profile: MachineProfile): void {
+ this.commit({ ...this.state, machines: { ...this.state.machines, [profile.id]: profile } })
+ }
+
+ /** Delete one machine profile (idempotent for absent ids). */
+ removeMachine(machineId: MachineId): void {
+ if (this.state.machines[machineId] === undefined)
+ return
+ const machines = { ...this.state.machines }
+ delete machines[machineId]
+ this.commit({ ...this.state, machines })
+ }
+
+ /** Persist the next state, adopt it, then notify subscribers. */
+ private commit(next: SshState): void {
+ writeStateFile(this.file, `${JSON.stringify({ version: STATE_VERSION, ...next }, null, 2)}\n`)
+ this.state = next
+ for (const listener of this.listeners) listener()
+ }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.ts
index a976fe5f..7426b90a 100644
--- a/packages/dsh-tauri-ssh/src/host/types/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts
@@ -8,7 +8,6 @@
*/
import type { IncomingMessage, ServerResponse } from 'node:http'
-import type z from 'schemastery'
/** Identifies one SSH machine profile. A generated uuid, never the host name: hosts are not unique. */
export type MachineId = string & { readonly __machineId: unique symbol }
@@ -24,12 +23,11 @@ export function MachineId(id: string): MachineId {
}
/**
- * One stored SSH machine profile: the `ssh-machines` settings-namespace
- * value shape. Credentials are deliberately sparse: authentication runs on
- * the host's own `~/.ssh` (config aliases, `IdentityFile`s, default keys),
- * so only the optional fallback secrets live here. Secret fields are
- * schema-declared `role('secret')` positions — they never ride a redacted
- * wire surface, only the owner scope's resolved in-process value.
+ * One stored SSH machine profile: the state document's machine value shape.
+ * Credentials are deliberately sparse: authentication runs on the host's own
+ * `~/.ssh` (config aliases, `IdentityFile`s, default keys), so only the
+ * optional fallback secrets live here — they never ride a redacted wire
+ * surface, only the plugin's in-process value.
*/
export interface MachineProfile {
/** Stable profile id (generated uuid). */
@@ -349,35 +347,17 @@ export interface HostWebRoute {
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>
}
-/** The settings namespace scope this plugin registers (a subset of dsh-settings' SettingsScope). */
-export interface HostSettingsScope<T> {
- /** The current resolved namespace value. */
- get: () => T
- /** Subscribe to value changes; returns an unsubscribe. */
- watch: (callback: (next: T, prev: T) => void) => () => void
- /** Merge a patch into the user section and persist (schema-validated). */
- update: (patch: object) => Promise<void>
- /** Replace the user section wholesale (absent keys re-inherit defaults). */
- replace: (section: object) => Promise<void>
-}
-
-/** The settings service surface this plugin needs. */
-export interface HostSettings {
- register: <T>(ns: string, schema: z<T>, options?: { base?: T, applies?: 'live' | 'restart' }) => HostSettingsScope<T>
-}
-
/** The webserver service surface this plugin needs. */
export interface HostWebServer {
register: (route: HostWebRoute) => () => void
}
/**
- * The host context this plugin's apply receives: the settings seam (namespace)
- * and the webserver (route mount), plus the teardown-effect seat. Structural —
- * the harness's real context duck-types onto it.
+ * The host context this plugin's apply receives: the webserver (route mount)
+ * plus the teardown-effect seat. Structural — the harness's real context
+ * duck-types onto it.
*/
export interface SshHostContext {
- settings: HostSettings
webServer: HostWebServer
/** Register a teardown effect (narrow cordis surface). */
effect: (execute: () => () => void, label?: string) => unknown
diff --git a/packages/dsh-tauri-ssh/src/index.ts b/packages/dsh-tauri-ssh/src/index.ts
index a4ceaf41..e5d19665 100644
--- a/packages/dsh-tauri-ssh/src/index.ts
+++ b/packages/dsh-tauri-ssh/src/index.ts
@@ -1,15 +1,16 @@
/**
- * The DSH remote-machine host plugin. Registers the `ssh-machines` settings
- * namespace, owns the SSH connection manager (TOFU host keys, remote `dsh
- * web` auto-start, loopback tunnels), and mounts the same-origin `/api-ssh`
- * route on `ctx.webServer` for the settings page. No upstream DSH source is
- * touched: every integration is a documented cordis extension point.
+ * The DSH remote-machine host plugin. Owns the plugin state document (the
+ * enable switch + the manual machine table), the SSH connection manager (TOFU
+ * host keys, remote `dsh web` auto-start, loopback tunnels), and mounts the
+ * same-origin `/api-ssh` route on `ctx.webServer` for the settings page. No
+ * upstream DSH source is touched: every integration is a documented cordis
+ * extension point.
*
* 三层目录(host / shared):
* - index.ts(本文件) public barrel(只保留导出面);
* - shared/constants 跨 half 协议常量(插件名 / API 前缀);
* - host/ Node half:routes(/api-ssh 路由)/ storage
- * (ssh-machines 命名空间 schema 与插件配置)/
+ * (状态文档读写与插件配置)/
* service(manager 状态机、bootstrap 远端保障、
* ssh-config 凭据解析、transport ssh2 传输、
* host-keys TOFU 存储)/ types / apply。
diff --git a/packages/dsh-tauri-ui/src/client/components/icons.tsx b/packages/dsh-tauri-ui/src/client/components/icons.tsx
index 19eab327..aa4ee1fa 100644
--- a/packages/dsh-tauri-ui/src/client/components/icons.tsx
+++ b/packages/dsh-tauri-ui/src/client/components/icons.tsx
@@ -28,6 +28,7 @@ export { default as FilePlus } from '@gravity-ui/icons/FilePlus'
export { default as Folder } from '@gravity-ui/icons/Folder'
export { default as FolderOpen } from '@gravity-ui/icons/FolderOpen'
export { default as Gear } from '@gravity-ui/icons/Gear'
+export { default as Globe } from '@gravity-ui/icons/Globe'
export { default as GraduationCap } from '@gravity-ui/icons/GraduationCap'
export { default as LogoGithub } from '@gravity-ui/icons/LogoGithub'
export { default as Magnifier } from '@gravity-ui/icons/Magnifier'
diff --git a/packages/dsh-tauri-ui/src/client/ui/nav-icon.tsx b/packages/dsh-tauri-ui/src/client/ui/nav-icon.tsx
index 8fa6a6b0..f43a3c9b 100644
--- a/packages/dsh-tauri-ui/src/client/ui/nav-icon.tsx
+++ b/packages/dsh-tauri-ui/src/client/ui/nav-icon.tsx
@@ -2,7 +2,7 @@ import type { ReactElement } from 'react'
import type { IconComponent } from '../components/icon'
import { get } from 'dsh-tauri/client'
import { Icon } from '../components/icon'
-import { Database, Gear, Person, Puzzle } from '../components/icons'
+import { Database, Gear, Globe, Person, Puzzle } from '../components/icons'
import { useMountStyle } from '../hooks/use-mount-style'
import settingsNavIconStyle from './nav-icon.cssr'
@@ -12,6 +12,8 @@ const NAV_ICONS: Record<string, IconComponent> = {
'models': Database,
'agent-presets': Person,
'plugins': Puzzle,
+ // 远程(dsh-tauri-ssh):网络图标,与壳层切换器的 Globe 同一语义
+ 'dsh-tauri-ssh': Globe,
}
export function SettingsNavIcon({ id }: { id: string }): ReactElement {
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 89182cb0..79c12a7f 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -363,13 +363,13 @@
"remote.local": "Local",
"remote.manage": "Manage machines",
"remote.sync": "Sync to remote",
- "remote.manage_hint": "Add or manage machines in the web app: open Settings → SSH Remote Machines.",
+ "remote.manage_hint": "Add or manage machines from Settings → Remote.",
"remote.disconnect_active": "Disconnect current remote",
"remote.retry_in": " (retry in {{seconds}}s)",
"remote.auth.agent": "agent",
"remote.auth.key": "key",
"remote.auth.password": "password",
- "remote.empty": "No machines yet — add one from the web Settings → SSH Remote Machines panel.",
+ "remote.empty": "No machines yet — add one from Settings → Remote.",
"remote.degraded": "Local instance unreachable — retrying",
"remote.state.disconnected": "Disconnected",
"remote.state.testing": "Testing",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 9856cd99..ded3f06f 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -363,13 +363,13 @@
"remote.local": "本地",
"remote.manage": "管理机器",
"remote.sync": "同步到远端",
- "remote.manage_hint": "在网页端「设置 → SSH 远端机器」面板中添加或管理机器。",
+ "remote.manage_hint": "在「设置 → 远程」面板中添加或管理机器。",
"remote.disconnect_active": "断开当前远端连接",
"remote.retry_in": "({{seconds}}s 后重试)",
"remote.auth.agent": "agent",
"remote.auth.key": "密钥",
"remote.auth.password": "密码",
- "remote.empty": "还没有机器——在网页端「设置 → SSH 远端机器」面板添加。",
+ "remote.empty": "还没有机器——在「设置 → 远程」面板添加。",
"remote.degraded": "本地实例不可达,正在重试",
"remote.state.disconnected": "未连接",
"remote.state.testing": "测试中",
diff --git a/src/layout/components/connect-dialog.test.tsx b/src/layout/components/connect-dialog.test.tsx
index 0e7a698f..941b415b 100644
--- a/src/layout/components/connect-dialog.test.tsx
+++ b/src/layout/components/connect-dialog.test.tsx
@@ -44,7 +44,7 @@ describe('connectDialog 连接进度弹窗', () => {
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' }]),
+ listMachines: vi.fn(async () => ({ enabled: true, machines: [{ id: 'm1', name: 'alpha', state: 'given-up' as const, lastError: 'boom' }] })),
connect: connectSpy,
disconnect: vi.fn(async () => undefined),
})
@@ -65,7 +65,7 @@ describe('connectDialog 连接进度弹窗', () => {
it('取消连接(进行中):中止引擎尝试并关闭弹窗,无失败定格', async () => {
const disconnectSpy = vi.fn(async () => undefined)
bindSshApiForTests({
- listMachines: vi.fn(async () => []),
+ listMachines: vi.fn(async () => ({ enabled: true, machines: [] })),
connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:1' })),
disconnect: disconnectSpy,
})
diff --git a/src/layout/components/nav-bridge.test.ts b/src/layout/components/nav-bridge.test.ts
index f3d088e5..6e35d0f6 100644
--- a/src/layout/components/nav-bridge.test.ts
+++ b/src/layout/components/nav-bridge.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { navBridgeOf, SSH_MACHINES_SECTION, SSH_SYNC_SECTION } from './nav-bridge'
+import { navBridgeOf, SSH_SECTION, SSH_TAB_MACHINES, SSH_TAB_SYNC } from './nav-bridge'
describe('navBridgeOf', () => {
it('sends no callbacks while the iframe is absent', () => {
@@ -21,8 +21,9 @@ describe('navBridgeOf', () => {
{ type: 'dsh://sidebar:toggle' },
{ type: 'dsh://session:new' },
{ type: 'dsh://workspace:add' },
- { type: 'dsh://settings:open', section: SSH_MACHINES_SECTION },
- { type: 'dsh://settings:open', section: SSH_SYNC_SECTION },
+ // 机器管理与同步同属 SSH 分区,靠 tab 落到对应标签页
+ { type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_MACHINES },
+ { type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_SYNC },
])
})
})
diff --git a/src/layout/components/nav-bridge.ts b/src/layout/components/nav-bridge.ts
index 8210fe45..1349201e 100644
--- a/src/layout/components/nav-bridge.ts
+++ b/src/layout/components/nav-bridge.ts
@@ -1,11 +1,14 @@
import type { NavbarProps } from './navbar'
import type { IframeOutboundMessage } from '@/hooks/use-iframe-post'
-/** 设置浮层分区 id:SSH 机器管理(dsh-tauri-ssh 插件注册)。 */
-export const SSH_MACHINES_SECTION = 'dsh-tauri-ssh'
+/** 设置浮层分区 id:SSH(dsh-tauri-ssh 插件注册的唯一分区,内部再用 Tabs 分页)。 */
+export const SSH_SECTION = 'dsh-tauri-ssh'
-/** 设置浮层分区 id:同步到远端(同一插件注册的第二个分区,与上者同级)。 */
-export const SSH_SYNC_SECTION = 'dsh-tauri-ssh-sync'
+/** SSH 分区内的标签页 id(与插件 `SSH_TAB_*` 约定一致)。 */
+export const SSH_TAB_MACHINES = 'machines'
+
+/** 同步到远端标签页 id。 */
+export const SSH_TAB_SYNC = 'sync'
/**
* 导航栏回调桥:把每个导航栏动作翻译成一条宿主 → iframe 协议消息。
@@ -25,7 +28,8 @@ export function navBridgeOf(post: (message: IframeOutboundMessage) => void, live
onToggleSidebar: () => post({ type: 'dsh://sidebar:toggle' }),
onNewChat: () => post({ type: 'dsh://session:new' }),
onOpenFolder: () => post({ type: 'dsh://workspace:add' }),
- onOpenMachineManager: () => post({ type: 'dsh://settings:open', section: SSH_MACHINES_SECTION }),
- onOpenSyncToRemote: () => post({ type: 'dsh://settings:open', section: SSH_SYNC_SECTION }),
+ // 机器管理与同步同属 SSH 分区:分区相同,靠 tab 字段落到对应标签页
+ onOpenMachineManager: () => post({ type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_MACHINES }),
+ onOpenSyncToRemote: () => post({ type: 'dsh://settings:open', section: SSH_SECTION, tab: SSH_TAB_SYNC }),
}
}
diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsx
index 5486cb8a..a4a78882 100644
--- a/src/layout/components/navbar.tsx
+++ b/src/layout/components/navbar.tsx
@@ -34,7 +34,7 @@ import { RemoteSwitcher } from './remote-switcher'
/**
* 壳层窗口顶部导航栏(44px,常驻):
*
- * [侧边栏(展开/收起)] [文件][运行][帮助] [ 空白拖拽区 ] [最小化][最大化][后台化(X)]
+ * [侧边栏(展开/收起)] [文件][运行][帮助] [ 空白拖拽区 ] [更新可用][本地/远端] [最小化][最大化][后台化(X)]
*
* - 侧边栏:经 postMessage 操控 iframe 内的 dsh 应用
* (`dsh://sidebar:toggle`,由 dsh-tauri 插件的 `client/register/sidebar.ts`
@@ -43,6 +43,8 @@ import { RemoteSwitcher } from './remote-switcher'
* 导航桥(收回报 + 发命令)在 `iframe.tsx` / `webview.tsx`,本组件只接收状态与回调:
* 左侧控件只在「dsh-tauri 插件已启用(已安装)」且传入 `onToggleSidebar` 时渲染,
* 原生桥缺席时控件没有可靠接收方,避免出现点了没反应的死按钮。
+ * - 本地 / 远端:`RemoteSwitcher` 固定在右侧「更新可用」旁边,SSH 功能未启用时
+ * 自身不渲染(见 `remote-switcher.tsx`)。
* - 文件:新建窗口(Tauri 再开一个 webview)/ 新聊天、打开文件夹(经协议调用 dsh 官方
* 「新建会话」「添加工作区」,接收方是 dsh-tauri 的 `client/register/navigation.ts`)/
* 关闭(隐藏到托盘)/ 退出(完整退出)。两条依赖 iframe 的项在回调缺席时禁用。
@@ -433,7 +435,6 @@ export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, o
</Button>
</If>
<If cond={onToggleSidebar != null}>
- <RemoteSwitcher onManage={onOpenMachineManager} onSync={onOpenSyncToRemote} />
<ConnectDialog />
</If>
<If cond={!IS_MACOS}>
@@ -651,6 +652,12 @@ export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, o
</Chip>
</If>
+ {/* 「本地」/ 远端机器切换器:SSH 功能启用后才出现(未启用时组件自身不渲染),
+ 位置固定在「更新可用」右侧,与左侧的文件/运行/帮助菜单分列两端。 */}
+ <If cond={onToggleSidebar != null}>
+ <RemoteSwitcher onManage={onOpenMachineManager} onSync={onOpenSyncToRemote} />
+ </If>
+
<If cond={!IS_MACOS}>
<Button
className="rounded-lg size-7"
diff --git a/src/layout/components/remote-switcher.test.tsx b/src/layout/components/remote-switcher.test.tsx
index 9aac2e24..c13a4e07 100644
--- a/src/layout/components/remote-switcher.test.tsx
+++ b/src/layout/components/remote-switcher.test.tsx
@@ -34,6 +34,8 @@ function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
/** 本轮引擎返回的机器列表(boot 的首次 refresh 会异步覆写 store,须同源)。 */
let engineMachines: SshMachineRow[] = []
+/** 本轮引擎回报的 SSH 开关(false = 插件未启用,壳层不渲染控件)。 */
+let engineEnabled = true
/** 是否模拟本地实例不可达(/api-ssh 抛错 → 降级态)。 */
let engineUnreachable = false
@@ -44,8 +46,8 @@ function bindEngine() {
bindSshApiForTests({
listMachines: vi.fn(async () => {
if (engineUnreachable)
- throw new Error('SSH_API_HTTP_503')
- return engineMachines
+ throw new TypeError('fetch failed')
+ return { enabled: engineEnabled, machines: engineMachines }
}),
connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
disconnect: disconnectSpy,
@@ -64,6 +66,8 @@ async function openMenu() {
/** 设定机器列表(store 与 mock 引擎同源,避免 boot 首刷覆写)。 */
function seedMachines(machines: SshMachineRow[]) {
engineMachines = machines
+ engineEnabled = true
+ remote.enabled = true
remote.machines = machines
}
@@ -73,6 +77,7 @@ beforeEach(() => {
manageSpy.mockClear()
invokeSpy.mockClear()
engineMachines = []
+ engineEnabled = true
engineUnreachable = false
bindEngine()
})
@@ -159,6 +164,24 @@ describe('remoteSwitcher 渲染', () => {
})
describe('remoteSwitcher 交互与降级', () => {
+ it('未启用(或插件未加载)时壳层不渲染「本地」控件;启用后随下一轮轮询出现', async () => {
+ engineEnabled = false
+ remote.enabled = false
+ render(<RemoteSwitcher onManage={manageSpy} />)
+ // boot 首刷回报未启用:整枚控件缺席(不是禁用的死按钮)
+ await vi.waitFor(() => {
+ expect(remote.available).toBe(true)
+ })
+ expect(screen.queryByRole('button', { name: 'remote.switcher' })).toBeNull()
+
+ // 用户在设置页启用后:聚焦触发的即时刷新让控件出现
+ engineEnabled = true
+ window.dispatchEvent(new Event('focus'))
+ await vi.waitFor(() => {
+ expect(screen.getByRole('button', { name: 'remote.switcher' })).toBeTruthy()
+ })
+ })
+
it('点击已连接机器项:切换视图(activeId/隧道 URL)', async () => {
seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
render(<RemoteSwitcher onManage={manageSpy} />)
diff --git a/src/layout/components/remote-switcher.tsx b/src/layout/components/remote-switcher.tsx
index 96923dbf..7092ff46 100644
--- a/src/layout/components/remote-switcher.tsx
+++ b/src/layout/components/remote-switcher.tsx
@@ -52,7 +52,10 @@ function openInNewWindow(machine: SshMachineRow, onError: (err: unknown) => void
* 数据面全部来自本地实例 `/api-ssh`(`useRemoteMachines` 启动秒级轮询 +
* 聚焦刷新);点击机器行=当前窗口切换(未连接则发起连接,进度弹窗实时
* 呈现),行尾图标=新窗口打开(已连接机器可用)。操作区两项同级:底部
- * 「管理机器…」与「同步到远端…」,各自直达 iframe 设置浮层的对应分区。
+ * 「管理机器…」与「同步到远端…」,各自直达 SSH 设置浮层的对应标签页。
+ *
+ * SSH 未启用(插件开关关闭,或本地实例没有该 API)时不渲染任何控件——「本地」
+ * 这一项本身就是 SSH 功能的一部分;轮询照常进行,启用后下一轮即出现。
*
* 色点语义(S3 词汇表):机器标识色优先 → 已连接绿 → 重连/进行中琥珀 →
* 放弃红 → 其余中性灰;未连接行整体降不透明度。本地实例不可达时进入降级
@@ -61,7 +64,7 @@ function openInNewWindow(machine: SshMachineRow, onError: (err: unknown) => void
export function RemoteSwitcher({ onManage, onSync }: { onManage?: () => void, onSync?: () => void }) {
const { t } = useTranslation()
useRemoteMachines()
- const { machines, activeId, available, pendingId } = useStore(store.remote)
+ const { machines, activeId, available, enabled, pendingId } = useStore(store.remote)
const activeMachine = machines.find(machine => machine.id === activeId)
const activeColor = activeMachine?.color
@@ -71,6 +74,9 @@ export function RemoteSwitcher({ onManage, onSync }: { onManage?: () => void, on
console.warn('[remote] open window failed:', err)
}
+ if (!enabled)
+ return null
+
return (
<Dropdown>
<Button
diff --git a/src/store/modules/remote/api.test.ts b/src/store/modules/remote/api.test.ts
index 78890e8f..6f2d4034 100644
--- a/src/store/modules/remote/api.test.ts
+++ b/src/store/modules/remote/api.test.ts
@@ -23,17 +23,19 @@ describe('createSshApiClient', () => {
const fetchFn = fakeFetch({
ok: true,
value: {
+ enabled: true,
items: [...listValue.items, { id: '', name: 'bad', state: 'connected' }, { id: 'x' }],
discovered: listValue.discovered,
},
})
const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
- const rows = await client.listMachines()
+ const { enabled, machines } = await client.listMachines()
+ expect(enabled).toBe(true)
// 按 name 排序:alias-host < alpha < beta
- expect(rows.map(row => row.id)).toEqual(['alias', 'a', 'b'])
- expect(rows[2]).toMatchObject({ color: '#123456', tintBorder: true, tunnelBaseUrl: 'http://127.0.0.1:4002' })
+ expect(machines.map(row => row.id)).toEqual(['alias', 'a', 'b'])
+ expect(machines[2]).toMatchObject({ color: '#123456', tintBorder: true, tunnelBaseUrl: 'http://127.0.0.1:4002' })
// 增量投影:authMethod 与 nextRetryAt 随行透出(切换器倒计时/凭据后缀用)
- expect(rows[1]).toMatchObject({ authMethod: 'key', nextRetryAt: 1725000000000 })
+ expect(machines[1]).toMatchObject({ authMethod: 'key', nextRetryAt: 1725000000000 })
// 请求形状:POST /api-ssh + machine.list 信封
expect(fetchFn).toHaveBeenCalledWith(
'http://127.0.0.1:3081/api-ssh',
@@ -41,6 +43,12 @@ describe('createSshApiClient', () => {
)
})
+ it('未启用时返回空列表与 enabled=false(壳层据此隐藏切换器)', async () => {
+ const fetchFn = fakeFetch({ ok: true, value: { enabled: false, items: [], discovered: [] } })
+ const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
+ await expect(client.listMachines()).resolves.toEqual({ enabled: false, machines: [] })
+ })
+
it('connect 透传 machineId 并返回隧道 URL', async () => {
const fetchFn = fakeFetch({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:4004' } })
const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
@@ -59,10 +67,25 @@ describe('createSshApiClient', () => {
await expect(client.connect('m1')).rejects.toThrow('machine is reconnecting')
})
- it('hTTP 非 200 与网络失败都抛错(本地实例不可达)', async () => {
+ it('hTTP 非 200、空响应体与网络失败都抛错(本地实例不可达 / 无 SSH API)', async () => {
const httpError = createSshApiClient(fakeFetch({ ok: true, value: {} }, 503), () => 'http://127.0.0.1:3081')
await expect(httpError.listMachines()).rejects.toThrow('SSH_API_HTTP_503')
+ // 405 是「插件未挂载」的实况(内核 fallback 只答状态码、正文为空):
+ // 必须是稳定的 HTTP 错误码,而不是原生 JSON 解析异常。
+ const routeMissing = createSshApiClient(
+ vi.fn(async () => ({ ok: false, status: 405, json: async () => { throw new SyntaxError('Unexpected end of JSON input') } }) as unknown as Response),
+ () => 'http://127.0.0.1:3081',
+ )
+ await expect(routeMissing.listMachines()).rejects.toThrow('SSH_API_HTTP_405')
+
+ // 200 但没有可解析正文:同样归到稳定错误码
+ const emptyBody = createSshApiClient(
+ vi.fn(async () => ({ ok: true, status: 200, json: async () => { throw new SyntaxError('Unexpected end of JSON input') } }) as unknown as Response),
+ () => 'http://127.0.0.1:3081',
+ )
+ await expect(emptyBody.listMachines()).rejects.toThrow('SSH_API_HTTP_200')
+
const networkError = createSshApiClient(
vi.fn(async () => { throw new TypeError('fetch failed') }) as unknown as SshFetchFn,
() => 'http://127.0.0.1:3081',
diff --git a/src/store/modules/remote/api.ts b/src/store/modules/remote/api.ts
index de38a87c..74b531a3 100644
--- a/src/store/modules/remote/api.ts
+++ b/src/store/modules/remote/api.ts
@@ -28,10 +28,30 @@ type SshApiResponse
/** fetch 函数形状(与全局 fetch 兼容,可注入 mock)。 */
export type SshFetchFn = (input: string, init?: RequestInit) => Promise<Response>
+/**
+ * 本地实例答了,但没有 SSH API:插件未加载 / 未启用(404、405 或非 JSON 响应)。
+ * 与网络失败区分——前者是「SSH 不可用」,后者才是「本地实例不可达」。
+ */
+export class SshApiHttpError extends Error {
+ readonly status: number
+
+ constructor(status: number) {
+ super(`SSH_API_HTTP_${status}`)
+ this.status = status
+ }
+}
+
+/** `machine.list` 的应答值:SSH 开关 + 机器行。 */
+export interface SshMachineList {
+ /** SSH 功能是否已启用;未启用时机器行为空,壳层不渲染切换器。 */
+ enabled: boolean
+ machines: SshMachineRow[]
+}
+
/** 本客户端面向壳层暴露的引擎动作。 */
export interface SshApiClient {
- /** `machine.list`:手动机器 + ~/.ssh/config 别名机器(已按名排序合并)。 */
- listMachines: () => Promise<SshMachineRow[]>
+ /** `machine.list`:SSH 开关 + 手动机器与 ~/.ssh/config 别名机器(已按名排序合并)。 */
+ listMachines: () => Promise<SshMachineList>
/** `machine.connect`:阻塞到隧道就绪,返回隧道 URL。 */
connect: (machineId: string) => Promise<{ tunnelBaseUrl: string }>
/** `machine.disconnect`:主动断开(远端实例保持运行)。 */
@@ -115,9 +135,17 @@ export function createSshApiClient(
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ method, payload: payload ?? {} } satisfies SshApiRequest),
})
+ // 非 2xx 与空/非 JSON 响应都不是信封:抛稳定的 HTTP 错误码,避免把
+ // `Unexpected end of JSON input` 这类原生解析异常泄漏到界面/降级提示。
if (!response.ok)
- throw new Error(`SSH_API_HTTP_${response.status}`)
- const envelope = await response.json() as SshApiResponse
+ throw new SshApiHttpError(response.status)
+ let envelope: SshApiResponse
+ try {
+ envelope = await response.json() as SshApiResponse
+ }
+ catch {
+ throw new SshApiHttpError(response.status)
+ }
if (!envelope.ok)
throw new Error(envelope.error?.message || envelope.error?.code || 'SSH_API_ERROR')
return envelope.value as T
@@ -129,7 +157,8 @@ export function createSshApiClient(
const items = (value?.items ?? []).map(machineRowOf).filter((row): row is SshMachineRow => row !== undefined)
const discovered = (value?.discovered ?? []).map(machineRowOf).filter((row): row is SshMachineRow => row !== undefined)
// 确定性排序(localeCompare 的 ICU 整序在不同环境不稳定)
- return [...items, ...discovered].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
+ const machines = [...items, ...discovered].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
+ return { enabled: value?.enabled === true, machines }
},
connect: machineId => call<{ tunnelBaseUrl: string }>('machine.connect', { machineId }),
disconnect: async (machineId) => {
diff --git a/src/store/modules/remote/store.test.ts b/src/store/modules/remote/store.test.ts
index 6e75547a..44e8952c 100644
--- a/src/store/modules/remote/store.test.ts
+++ b/src/store/modules/remote/store.test.ts
@@ -1,18 +1,25 @@
+import type { SshMachineList } from './api'
import type { SshMachineRow } from './types'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { SshApiHttpError } from './api'
import { bindSshApiForTests, disposeRemoteForTests, remote } from './store'
function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }
}
+/** SSH 已启用的 machine.list 应答。 */
+function listOf(machines: SshMachineRow[]): SshMachineList {
+ return { enabled: true, machines }
+}
+
/** 组一个按调用序返回快照序列的 listMachines mock(末张快照驻留)。 */
function bindListSequence(list: SshMachineRow[][]) {
let call = 0
return vi.fn(async () => {
- const snapshot = list[Math.min(call, list.length - 1)]
+ const snapshot = list[Math.min(call, list.length - 1)] ?? []
call += 1
- return snapshot
+ return listOf(snapshot)
})
}
@@ -23,9 +30,9 @@ function bindEngine(options: {
}) {
let call = 0
const listMachines = vi.fn(async () => {
- const snapshot = options.list[Math.min(call, options.list.length - 1)]
+ const snapshot = options.list[Math.min(call, options.list.length - 1)] ?? []
call += 1
- return snapshot
+ return listOf(snapshot)
})
const connect = options.connect ?? (vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })))
bindSshApiForTests({ listMachines, connect, disconnect: vi.fn(async () => undefined) })
@@ -41,15 +48,16 @@ afterEach(() => {
})
describe('remote store 轮询与降级', () => {
- it('refresh 成功更新机器列表;失败进入降级态并保留既有列表,恢复后复原', async () => {
+ it('refresh 成功更新机器列表;网络失败进入降级态并保留既有列表,恢复后复原', async () => {
bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
await remote.refresh()
expect(remote.machines.map(m => m.name)).toEqual(['alpha'])
+ expect(remote.enabled).toBe(true)
expect(remote.available).toBe(true)
// 本地实例不可达:fetch 抛错 → 降级但不清空列表(静默,不弹错误)
bindSshApiForTests({
- listMachines: vi.fn(async () => { throw new Error('SSH_API_HTTP_503') }),
+ listMachines: vi.fn(async () => { throw new TypeError('fetch failed') }),
connect: vi.fn(async () => { throw new Error('unreachable') }),
disconnect: vi.fn(async () => undefined),
})
@@ -63,6 +71,46 @@ describe('remote store 轮询与降级', () => {
expect(remote.available).toBe(true)
})
+ it('本地实例可达但没有 SSH API(404/405):不算不可达,按未启用处理并清空远端视图', async () => {
+ bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
+ await remote.refresh()
+ remote.activeId = 'm1'
+ remote.activeTunnelUrl = 'http://127.0.0.1:4001'
+
+ // 插件未加载 / 未启用:内核 fallback 只回 405、正文为空(0.1.7 的实况)
+ bindSshApiForTests({
+ listMachines: vi.fn(async () => { throw new SshApiHttpError(405) }),
+ connect: vi.fn(async () => { throw new Error('unreachable') }),
+ disconnect: vi.fn(async () => undefined),
+ })
+ await remote.refresh()
+ expect(remote.available).toBe(true)
+ expect(remote.enabled).toBe(false)
+ expect(remote.machines).toEqual([])
+ expect(remote.activeId).toBeNull()
+ expect(remote.activeTunnelUrl).toBe('')
+
+ // 用户在设置页启用插件后:下一轮轮询即恢复
+ bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
+ await remote.refresh()
+ expect(remote.enabled).toBe(true)
+ expect(remote.machines.map(m => m.name)).toEqual(['alpha'])
+ })
+
+ it('未启用(enabled=false)时清空列表且不推进切换', async () => {
+ remote.machines = [machineOf({ id: 'm1', name: 'alpha' })]
+ remote.activeId = 'm1'
+ bindSshApiForTests({
+ listMachines: vi.fn(async () => ({ enabled: false, machines: [] })),
+ connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
+ disconnect: vi.fn(async () => undefined),
+ })
+ await remote.refresh()
+ expect(remote.enabled).toBe(false)
+ expect(remote.machines).toEqual([])
+ expect(remote.activeId).toBeNull()
+ })
+
it('boot 幂等:只挂一个轮询定时器(fake timers 下按周期节奏发请求)', async () => {
vi.useFakeTimers()
try {
@@ -97,9 +145,9 @@ describe('remote store 远端弹窗启动寻址', () => {
// 首轮不可达(新窗口启动时实例健康检查常未就绪),恢复后轮询推进
bindEngine({ list: [] })
const engine = bindEngine({ list: [] })
- engine.listMachines.mockRejectedValueOnce(new Error('SSH_API_HTTP_503'))
+ engine.listMachines.mockRejectedValueOnce(new TypeError('fetch failed'))
engine.listMachines.mockImplementation(async () =>
- [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
+ listOf([machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]))
remote.openInitialMachine('m1')
await vi.waitFor(() => expect(remote.available).toBe(false))
expect(remote.activeId).toBeNull()
@@ -119,9 +167,9 @@ describe('remote store 远端弹窗启动寻址', () => {
}),
})
engine.listMachines.mockImplementation(async () =>
- [machineOf(connected
+ listOf([machineOf(connected
? { id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' }
- : { id: 'm1', state: 'disconnected' })])
+ : { id: 'm1', state: 'disconnected' })]))
remote.openInitialMachine('m1')
await vi.waitFor(() => expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001'))
expect(engine.connect).toHaveBeenCalledWith('m1')
@@ -162,9 +210,9 @@ describe('remote store 切换语义', () => {
}),
})
engine.listMachines.mockImplementation(async () =>
- [machineOf(connected
+ listOf([machineOf(connected
? { id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002' }
- : { id: 'm1', state: 'disconnected' })])
+ : { id: 'm1', state: 'disconnected' })]))
await remote.refresh()
remote.switchTo('m1')
@@ -247,7 +295,7 @@ describe('remote store 切换语义', () => {
it('降级态下 switchTo 直接忽略(远端项在切换器中已禁用)', async () => {
bindSshApiForTests({
- listMachines: vi.fn(async () => { throw new Error('SSH_API_HTTP_503') }),
+ listMachines: vi.fn(async () => { throw new TypeError('fetch failed') }),
connect: vi.fn(async () => { throw new Error('unreachable') }),
disconnect: vi.fn(async () => undefined),
})
@@ -260,11 +308,12 @@ describe('remote store 切换语义', () => {
it('disconnect:活动机器先回本地视图再向引擎发断开,随后 refresh 落定', async () => {
const disconnectSpy = vi.fn(async () => undefined)
bindSshApiForTests({
- listMachines: vi.fn(async () => [machineOf({ id: 'm1', state: 'disconnected' })]),
+ listMachines: vi.fn(async () => listOf([machineOf({ id: 'm1', state: 'disconnected' })])),
connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
disconnect: disconnectSpy,
})
remote.machines = [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ remote.enabled = true
remote.activeId = 'm1'
remote.activeTunnelUrl = 'http://127.0.0.1:4001'
await remote.disconnect('m1')
@@ -309,7 +358,7 @@ describe('remote store 切换语义', () => {
it('连接失败:定格目标与直接原因供进度弹窗呈现,dismissConnect 关闭清理', async () => {
bindSshApiForTests({
- listMachines: vi.fn(async () => [machineOf({ id: 'm1', state: 'given-up', lastError: 'timeout' })]),
+ listMachines: vi.fn(async () => listOf([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' }] })),
diff --git a/src/store/modules/remote/store.ts b/src/store/modules/remote/store.ts
index e6c070b3..62f1c9e8 100644
--- a/src/store/modules/remote/store.ts
+++ b/src/store/modules/remote/store.ts
@@ -5,8 +5,10 @@
*
* 节奏(KISS,无推送通道):秒级轮询 + 窗口聚焦触发刷新(监听在组件侧
* hook 装配);本地实例不可达时进入降级态(保留列表、静默重试,不弹错误
- * 风暴),恢复后自动复原。切换语义(断开回本地、重连粘性、就绪即切)由
- * 纯函数 `reconcileSwitcher` 承担(见 logic.ts)。
+ * 风暴),恢复后自动复原。插件侧 SSH 开关未启用(或本地实例没有该 API)时
+ * 清空远端视图并隐藏壳层切换器,而不是谎报「本地实例不可达」。切换语义
+ * (断开回本地、重连粘性、就绪即切)由纯函数 `reconcileSwitcher` 承担
+ * (见 logic.ts)。
* @module store/remote/store
*/
@@ -14,7 +16,7 @@ import type { SshApiClient } from './api'
import type { SshMachineRow, SshProgressPhase } from './types'
import { defineStore } from 'valtio-define'
import { harness } from '../harness'
-import { createSshApiClient } from './api'
+import { createSshApiClient, SshApiHttpError } from './api'
import { reconcileSwitcher } from './logic'
/** 轮询间隔(毫秒):秒级即可让切换器跟上连接/重连状态流转。 */
@@ -60,6 +62,8 @@ export const remote = defineStore({
state: () => ({
/** 全部机器(手动机器 + ~/.ssh/config 别名,按名排序)。 */
machines: [] as SshMachineRow[],
+ /** SSH 功能是否已启用(插件侧开关);未启用时壳层不渲染切换器。 */
+ enabled: false,
/** iframe 当前指向的远端机器(null = 本地实例)。 */
activeId: null as string | null,
/** 点击未连接机器后待切换的目标(连接就绪后升为 activeId)。 */
@@ -104,7 +108,18 @@ export const remote = defineStore({
return
this.refreshing = true
try {
- const machines = await api.listMachines()
+ const { enabled, machines } = await api.listMachines()
+ this.available = true
+ this.enabled = enabled
+ // 未启用:机器列表与远端视图一并清空(连接已由主机侧断开),壳层隐藏
+ // 切换器;挂起中的启动寻址保留,启用后随下一轮成功轮询兑现。
+ if (!enabled) {
+ this.machines = []
+ this.activeId = null
+ this.activeTunnelUrl = ''
+ this.pendingId = null
+ return
+ }
const next = reconcileSwitcher(
{ activeId: this.activeId, pendingId: this.pendingId, activeTunnelUrl: this.activeTunnelUrl },
machines,
@@ -113,7 +128,6 @@ export const remote = defineStore({
this.activeId = next.activeId
this.pendingId = next.pendingId
this.activeTunnelUrl = next.activeTunnelUrl
- this.available = true
// 启动寻址(远端弹窗 remote-<id>):实例就绪前 refresh 会连续失败,
// 一次性「拉一轮再切」抢跑必然落空——挂起目标随每次成功轮询推进,
// 机器一出现即切(已连接直切/未连接发起连接),用户手动操作则撤销
@@ -129,9 +143,21 @@ export const remote = defineStore({
await this.trackConnectProgress()
}
catch (err) {
- // 本地实例不可达(启动中/已停止):降级但保留既有列表,静默重试
- console.warn('[remote] /api-ssh unreachable:', err)
- this.available = false
+ // 本地实例可达但没有 SSH API(插件未加载 / 未启用):SSH 不可用,
+ // 不是「本地实例不可达」——静默隐藏切换器,不弹误导性的降级提示。
+ if (err instanceof SshApiHttpError) {
+ this.available = true
+ this.enabled = false
+ this.machines = []
+ this.activeId = null
+ this.activeTunnelUrl = ''
+ this.pendingId = null
+ }
+ else {
+ // 本地实例不可达(启动中/已停止):降级但保留既有列表,静默重试
+ console.warn('[remote] /api-ssh unreachable:', err)
+ this.available = false
+ }
}
finally {
this.refreshing = false
@@ -305,6 +331,7 @@ export function disposeRemoteForTests(): void {
}
remote.booted = false
remote.machines = []
+ remote.enabled = false
remote.activeId = null
remote.pendingId = null
remote.pendingBootMachineId = null
diff --git a/src/store/modules/remote/types.ts b/src/store/modules/remote/types.ts
index 455aa8ea..28f39c46 100644
--- a/src/store/modules/remote/types.ts
+++ b/src/store/modules/remote/types.ts
@@ -83,8 +83,12 @@ export interface SshEventEntry {
line: string
}
-/** `machine.list` 的应答信封(items = 手动机器,discovered = ~/.ssh/config 别名)。 */
+/**
+ * `machine.list` 的应答信封(items = 手动机器,discovered = ~/.ssh/config 别名)。
+ * `enabled` 为 SSH 功能开关:关闭时两侧机器行为空,壳层据此不渲染切换器。
+ */
export interface SshMachineListValue {
+ enabled?: boolean
items: SshMachineRow[]
discovered: SshMachineRow[]
}