Skip to content

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

fix(rebase): 恢复重放中被 ours 策略误伤的本方文件与 i18n 键

Menghuan1918b99b03bdd814
diff --git a/packages/dsh-tauri-ssh-ui/package.json b/packages/dsh-tauri-ssh-ui/package.json
index 5889758b..91b79366 100644
--- a/packages/dsh-tauri-ssh-ui/package.json
+++ b/packages/dsh-tauri-ssh-ui/package.json
@@ -74,10 +74,12 @@
"@types/node": "catalog:types",
"@types/react": "catalog:types",
"@types/react-dom": "catalog:types",
+ "anser": "catalog:",
"dsh-tauri-tsdown": "workspace:*",
"jsdom": "catalog:testing",
"react": "catalog:runtime",
"react-dom": "catalog:runtime",
+ "shiki": "catalog:",
"tsdown": "catalog:cli",
"typescript": "catalog:cli",
"vitest": "catalog:testing"
diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx
index bcc749ee..a22cbdb7 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx
+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.test.tsx
@@ -249,12 +249,18 @@ describe('machinesSection', () => {
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Testing'))
cleanup()
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'reconnecting', nextRetryHint: 'in 8s' }] } } })
+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: Date.now() + 8_000 }] } } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Reconnecting'))
expect(screen.getByTestId('status-a').textContent).toContain('next retry: in 8s')
expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(true)
})
+ it('renders a due retry as now instead of a negative countdown', async () => {
+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: Date.now() - 2_000 }] } } })
+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Reconnecting'))
+ expect(screen.getByTestId('status-a').textContent).toContain('next retry: now')
+ })
+
it('renders the given-up state and lets the operator retry the connect', async () => {
mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'given-up', lastError: 'auth failed after 10 tries' }] } } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Given up'))
@@ -426,7 +432,7 @@ describe('machinesSection', () => {
it('polls the host while an operation is in flight and stops when idle', async () => {
vi.useFakeTimers()
try {
- const fetchFn = fakeFetch({ ok: true, value: { items: [] } })
+ const fetchFn = fakeFetch({ ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } })
const store = new MachinesStore(fetchFn)
store.store.update((state) => {
state.status = 'ready'
@@ -436,15 +442,20 @@ describe('machinesSection', () => {
render(<MachinesSection store={store} t={t} />)
const before = fetchFn.mock.calls.length
await act(async () => vi.advanceTimersByTime(1600))
- // One poll = machine.list + machine.events (the S2 channel ride-along).
+ // One poll = machine.list + machine.events for the one known machine.
expect(fetchFn.mock.calls.length).toBe(before + 2)
- // Idle machines stop the polling loop.
- store.store.update((state) => {
- state.statuses = { a: { state: 'disconnected' } }
- state.busy = {}
+ // Idle machines stop the polling loop. The flip runs inside act so the
+ // interval effect cleans up before the clock advances again; every
+ // further call would prove the loop leaked.
+ act(() => {
+ store.store.update((state) => {
+ state.statuses = { a: { state: 'disconnected' } }
+ state.busy = {}
+ })
})
+ const idle = fetchFn.mock.calls.length
await act(async () => vi.advanceTimersByTime(3200))
- expect(fetchFn.mock.calls.length).toBe(before + 2)
+ expect(fetchFn.mock.calls.length).toBe(idle)
}
finally {
vi.useRealTimers()
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 9281098c..6311dff1 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
@@ -1,71 +1,70 @@
-'use no memo'
-
-/**
- * The SSH-machines settings section, redrawn on the official UI primitives
- * (Button / Input / StateDot / Modal / Pill — the same atoms the DSH settings
- * pages use), with CSS Modules keeping only layout and token alignment. One
- * card per machine: the config form (secrets write-only, presence-flagged),
- * the connection plane (test/connect/open/disconnect) over the C-STATE
- * vocabulary (reconnecting and given-up included, with the next-retry hint),
- * the streaming log (the S2 machine.events channel, falling back to the
- * status progress log), and a delete confirmation modal. The open-in-window
- * affordance only exists where the desktop iframe bridge answers
- * (remote_bridge_ping); a bridge failure surfaces as a visible error. All
- * state lives in the injected {@link MachinesStore}; the component is a thin
- * renderer over its snapshot.
- * @module dsh-tauri-ssh-ui/client/components/machines-section
- */
-
import type { CSSProperties, ReactNode } from 'react'
-import type { SshKey } from '../locales/index.js'
-import type { InstallResult, MachineRow, MachinesStore, MachineStatus, SecretValues } from '../store/index.js'
-import type { MachineLifecycleState, RemoteBridge } from '../types/index.js'
+import type { SshKey } from '../locales/index'
+import type { InstallResult, MachineRow, MachinesNotice, MachinesStore, MachineStatus, ProgressPhase, SecretValues } from '../store/index'
+import type { MachineLifecycleState, RemoteBridge } from '../types/index'
import { Button, Input, Modal, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'
import { useEffect, useState, useSyncExternalStore } from 'react'
-import css from './machines-section.module.css'
-import { SyncPanel } from './sync-panel.js'
+import { cls } from '../styles/index'
+import { retrySecondsOf } from '../utils/retry'
+import { SyncPanel } from './sync-panel'
-/** A secret field name. */
-export type SecretFieldName = 'password' | 'passphrase'
+/** New-machine form defaults (ssh-ui 既有默认:SSH 22 / 远端 web 3080)。 */
+const DEFAULT_PORT = 22
+const DEFAULT_REMOTE_PORT = 3080
-/** Registrant-owned dependencies of the section. */
-export interface MachinesSectionInjected {
- store: MachinesStore
- /** The desktop iframe bridge (defaults to the real one at registration). */
- bridge?: RemoteBridge
-}
+/** The StateDot vocabulary the connection states map onto ('idle' is hollow). */
+type DotState = 'done' | 'ongoing' | 'error' | 'idle'
-/** Full section props: the framework `t` seat plus the injected store. */
-export interface MachinesSectionProps extends MachinesSectionInjected {
- t: (key: SshKey) => string
-}
+/** The identity-color palette (fits the DSH status hue family). */
+const COLOR_CHOICES = [
+ '#4176E6',
+ '#0EA5E9',
+ '#14B8A6',
+ '#22C55E',
+ '#F59E0B',
+ '#F97316',
+ '#EF4444',
+ '#A855F7',
+]
-/** One editable draft row (key is the machine id; rows always mirror saved machines). */
+/** One in-edit draft of a manual machine row (keyed by row id). */
interface Draft {
key: string
row: MachineRow
}
-/** The dirty-secret map the form carries: machine key → typed secret values. */
+/** Per-row typed secrets the editor holds (write-only; keyed by row id). */
type DirtySecrets = Record<string, SecretValues>
-/** The StateDot vocabulary the connection states map onto ('idle' is hollow). */
-type DotState = 'done' | 'ongoing' | 'error' | 'idle'
+/** Which secret fields exist (the write-only sidecar keys). */
+export type SecretFieldName = 'password' | 'passphrase'
-/** The desktop-context verdict of the bridge probe. */
-type BridgeAvailability = 'unknown' | 'desktop' | 'web'
+/** Injected dependencies (the app binds the real store/bridge; tests pass fakes). */
+export interface MachinesSectionInjected {
+ store: MachinesStore
+ /** Desktop bridge; absent (or unanswered probe) means pure web. */
+ bridge?: RemoteBridge
+}
-/** One pending delete, driving the confirmation modal. */
+export interface MachinesSectionProps extends MachinesSectionInjected {
+ t: (key: SshKey) => string
+}
+
+/** The remove-confirm target: which row is about to be deleted. */
interface RemoveTarget {
key: string
id: string
name: string
}
-const DEFAULT_PORT = 22
-const DEFAULT_REMOTE_PORT = 3080
+/** The id charset mirrors the host-side MachineId guard. */
+const ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/u
-/** Derive the machine id from a host: lowercase alnum-dash slug of the first label. */
+/**
+ * Derive the machine id from a host: lowercase alnum-dash slug of the part
+ * after the last `@` (so `[email protected]` → `10.1.1.1` → `10-1-1-1`); empty
+ * when the host has no usable characters.
+ */
function slugOf(host: string): string {
return host
.trim()
@@ -75,281 +74,205 @@ function slugOf(host: string): string {
.replace(/^-+|-+$/gu, '')
}
-/** The first free id: the slug itself, else slug-2, slug-3, … */
+/** Pick the first free id: the slug itself, else slug-2, slug-3, … */
function freeIdOf(base: string, taken: ReadonlySet<string>): string {
- if (base !== '' && !taken.has(base))
+ if (!taken.has(base))
return base
- const stem = base === '' ? 'machine' : base
- for (let n = 2;; n += 1) {
- const candidate = `${stem}-${n}`
+ for (let index = 2; ; index += 1) {
+ const candidate = `${base}-${index}`
if (!taken.has(candidate))
return candidate
}
}
-/** The id vocabulary (starts lowercase alnum; dashes allowed inside). */
-const ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/u
-
-/** The identity-color palette (fits the DSH status hue family). */
-const COLOR_CHOICES = [
- '#4176E6',
- '#0EA5E9',
- '#14B8A6',
- '#22C55E',
- '#F59E0B',
- '#F97316',
- '#EF4444',
- '#A855F7',
-]
-
-/** One machine's editable config card. */
-export function MachineCard(
- { draft, t, secretSet, status, busy, dirty, logLines, bridgeOpen, bridgeError, onChange, onSecret, onRemove, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {
- draft: Draft
- t: (key: SshKey) => string
- secretSet: Record<string, boolean>
- status: MachineStatus | undefined
- busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined
- dirty: SecretValues
- logLines: readonly string[]
- /** Whether the desktop bridge answers (the Open button only exists then). */
- bridgeOpen: boolean
- /** The visible error of a failed bridge open call, if any. */
- bridgeError: string | undefined
- onChange: (key: string, patch: Partial<MachineRow>) => void
- onSecret: (key: string, field: SecretFieldName, value: string) => void
- onRemove: (target: RemoveTarget) => void
- onTest: (id: string) => void
- onConnect: (id: string) => void
- onDisconnect: (id: string) => void
- onOpen: (id: string) => void
- onInstall: (id: string) => void
- installResult: InstallResult | undefined
- },
-): ReactNode {
- const { row } = draft
- const connected = status?.state === 'connected'
- const held = status?.state === 'connecting' || status?.state === 'testing' || status?.state === 'reconnecting'
- const id = row.id
- const color = colorOf(row)
+/**
+ * The shared machine row shell: identity (state dot + optional color pip +
+ * name + host tag), live status text with the step rail, and the trailing
+ * action cluster. Manual and discovered rows differ only in their action
+ * set and whether an editor can expand below.
+ */
+function RowShell({ id, name, tag, tintColor, tintBorder, status, trail, actions, t, children }: {
+ id: string
+ name: string
+ /** The muted identity suffix (host for manual rows, the config tag for discovered). */
+ tag: string
+ tintColor: string | undefined
+ tintBorder: boolean
+ status: MachineStatus | undefined
+ trail: readonly ProgressPhase[]
+ actions: ReactNode
+ t: (key: SshKey) => string
+ children?: ReactNode
+}): ReactNode {
return (
<li
- className={css.rowCard}
+ className={cls.rowCard}
data-testid={`machine-${id}`}
- style={row.tintBorder === true && color !== undefined ? { borderColor: color } : undefined}
+ style={tintBorder && tintColor !== undefined ? { borderLeftColor: tintColor } : undefined}
>
- <div className={css.rowHead}>
- <span className={css.rowIdentity}>
+ <div className={cls.rowHead}>
+ <span className={cls.rowIdentity}>
<StateDotOf status={status} />
- {color !== undefined
- ? <span className={css.colorPip} style={{ background: color }} aria-hidden="true" />
+ {tintColor !== undefined
+ ? <span className={cls.colorPip} style={{ background: tintColor }} aria-hidden="true" />
: null}
- <span className={css.rowName}>{row.name === '' ? row.id : row.name}</span>
- <span className={css.rowTag}>{row.host}</span>
- <span className={css.status} data-testid={`status-${id}`}>{statusTextOf(status, t)}</span>
- </span>
- <span className={css.rowActions}>
- <Button variant="outline" size="sm" disabled={busy !== undefined || held} onClick={() => onTest(id)}>
- {t('test')}
- </Button>
- {connected
- ? (
- <>
- {bridgeOpen
- ? (
- <Button variant="primary" size="sm" disabled={busy !== undefined} title={t('open.tip')} onClick={() => onOpen(id)}>
- {t('open')}
- </Button>
- )
- : null}
- <Button variant="outline" size="sm" disabled={busy !== undefined} onClick={() => onDisconnect(id)}>
- {t('disconnect')}
- </Button>
- </>
- )
- : (
- <Button variant="primary" size="sm" disabled={busy !== undefined || held} onClick={() => onConnect(id)}>
- {t('connect')}
- </Button>
- )}
- <Button variant="ghost" size="sm" className={moduleClass(css.dangerAction)} disabled={busy !== undefined} onClick={() => onRemove({ key: draft.key, id, name: row.name === '' ? id : row.name })}>
- {t('remove')}
- </Button>
+ <span className={cls.rowName}>{name}</span>
+ <span className={cls.rowTag}>{tag}</span>
+ <span className={cls.status} data-testid={`status-${id}`}>{statusTextOf(status, t)}</span>
+ <StepRail trail={trail} t={t} />
</span>
+ <span className={cls.rowActions}>{actions}</span>
</div>
- <div className={css.editor}>
- <div className={css.grid}>
- <Field label={t('field.id')}>
- <Input
- className={moduleClass(css.fieldInput)}
- value={row.id}
- disabled
- onChange={event => onChange(draft.key, { id: event.target.value })}
- />
- </Field>
- <Field label={t('field.name')}>
- <Input
- className={moduleClass(css.fieldInput)}
- value={row.name}
- onChange={event => onChange(draft.key, { name: event.target.value })}
- />
- </Field>
- <Field label={t('field.host')}>
- <Input
- className={moduleClass(css.fieldInput)}
- value={row.host}
- onChange={event => onChange(draft.key, { host: event.target.value })}
- />
- </Field>
- <Field label={t('field.port')}>
- <Input
- className={moduleClass(css.fieldInput)}
- type="number"
- value={row.port}
- onChange={event => onChange(draft.key, { port: numberOf(event.target.value, DEFAULT_PORT) })}
- />
- </Field>
- <Field label={t('field.user')}>
- <Input
- className={moduleClass(css.fieldInput)}
- value={row.user}
- onChange={event => onChange(draft.key, { user: event.target.value })}
- />
- </Field>
- <Field label={t('field.remotePort')}>
- <Input
- className={moduleClass(css.fieldInput)}
- type="number"
- value={row.remotePort}
- onChange={event => onChange(draft.key, { remotePort: numberOf(event.target.value, DEFAULT_REMOTE_PORT) })}
- />
- </Field>
- <Field label={t('field.startCommand')}>
- <Input
- className={moduleClass(css.fieldInput)}
- value={row.startCommand ?? ''}
- onChange={event => onChange(draft.key, { startCommand: event.target.value })}
- />
- </Field>
- </div>
- <div className={css.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}
- />
- </div>
- <AppearanceEditor row={row} t={t} onChange={onChange} draftKey={draft.key} />
- </div>
- {status?.dshMissing === true
- ? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(id)} />
- : null}
- {status?.lastError !== undefined ? <p className={css.statusError} role="alert">{status.lastError}</p> : null}
- {bridgeError !== undefined
- ? (
- <p className={css.statusError} role="alert" data-testid={`bridge-error-${id}`}>
- {t('bridge.error')}
- {bridgeError}
- </p>
- )
- : null}
- {status?.tunnelBaseUrl !== undefined ? <p className={css.link}>{status.tunnelBaseUrl}</p> : null}
- <LogStream id={id} lines={logLines} fallback={status?.progress?.log} />
- {installResult !== undefined
- ? <p className={css.installNote} data-testid={`install-note-${id}`}>{installNoteOf(installResult, t)}</p>
- : null}
+ {children}
</li>
)
}
/**
- * One read-only machine card from ~/.ssh/config: identity, status, and the
- * connection plane only — nothing here is stored or editable (no password,
- * no color, no delete).
+ * The inline editor of one manual machine: connection fields, write-only
+ * secrets and the appearance row. Saving applies immediately for this row
+ * alone (other rows are untouched); cancel discards the buffer.
*/
-function DiscoveredCard({ row, t, status, busy, logLines, bridgeOpen, bridgeError, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {
- row: MachineRow
+function EditPanel({ draft, t, secretSet, dirty, saving, onChange, onSecret, onSave, onCancel }: {
+ draft: Draft
+ t: (key: SshKey) => string
+ secretSet: Record<string, boolean>
+ dirty: SecretValues
+ saving: boolean
+ onChange: (key: string, patch: Partial<MachineRow>) => void
+ onSecret: (key: string, field: SecretFieldName, value: string) => void
+ onSave: (key: string) => void
+ onCancel: (key: string) => void
+}): ReactNode {
+ const { row } = draft
+ const invalid = row.id === '' || row.name === '' || row.host === ''
+ return (
+ <div className={cls.editor} data-testid={`editor-${row.id}`}>
+ <div className={cls.grid}>
+ <Field label={t('field.id')}>
+ <Input className={cls.fieldInput} value={row.id} disabled />
+ </Field>
+ <Field label={t('field.name')}>
+ <Input className={cls.fieldInput} value={row.name} disabled={saving} onChange={event => onChange(draft.key, { name: event.target.value })} />
+ </Field>
+ <Field label={t('field.host')}>
+ <Input className={cls.fieldInput} value={row.host} disabled={saving} onChange={event => onChange(draft.key, { host: event.target.value })} />
+ </Field>
+ <Field label={t('field.port')}>
+ <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')}>
+ <Input className={cls.fieldInput} value={row.user} disabled={saving} onChange={event => onChange(draft.key, { user: event.target.value })} />
+ </Field>
+ <Field label={t('field.remotePort')}>
+ <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.startCommand')}>
+ <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} />
+ </div>
+ <AppearanceEditor row={row} t={t} onChange={onChange} draftKey={draft.key} />
+ <div className={cls.editorActions}>
+ {invalid ? <p className={cls.hint}>{t('saveHint')}</p> : null}
+ <Button variant="ghost" size="sm" disabled={saving} onClick={() => onCancel(draft.key)}>
+ {t('add.cancel')}
+ </Button>
+ <Button variant="primary" size="sm" disabled={saving || invalid} onClick={() => onSave(draft.key)}>
+ {t('save')}
+ </Button>
+ </div>
+ </div>
+ )
+}
+
+/** The shared trailing action cluster of one row (test/connect/open/disconnect + row-specific extras). */
+function RowActions({ id, t, status, busy, bridgeOpen, bridgePending, opening, onTest, onConnect, onDisconnect, onOpen, extras }: {
+ id: string
t: (key: SshKey) => string
status: MachineStatus | undefined
busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined
- logLines: readonly string[]
bridgeOpen: boolean
- bridgeError: string | undefined
+ bridgePending?: boolean
+ opening?: boolean
onTest: (id: string) => void
onConnect: (id: string) => void
onDisconnect: (id: string) => void
onOpen: (id: string) => void
- onInstall: (id: string) => void
- installResult: InstallResult | undefined
+ extras?: ReactNode
}): ReactNode {
const connected = status?.state === 'connected'
const held = status?.state === 'connecting' || status?.state === 'testing' || status?.state === 'reconnecting'
return (
- <li className={css.rowCard} data-testid={`machine-${row.id}`}>
- <div className={css.rowHead}>
- <span className={css.rowIdentity}>
- <StateDotOf status={status} />
- <span className={css.rowName}>{row.name}</span>
- <span className={css.rowTag}>{t('configTag')}</span>
- <span className={css.status} data-testid={`status-${row.id}`}>{statusTextOf(status, t)}</span>
- </span>
- <span className={css.rowActions}>
- <Button variant="outline" size="sm" disabled={busy !== undefined || held} onClick={() => onTest(row.id)}>
- {t('test')}
- </Button>
- {connected
- ? (
- <>
- {bridgeOpen
- ? (
- <Button variant="primary" size="sm" disabled={busy !== undefined} title={t('open.tip')} onClick={() => onOpen(row.id)}>
- {t('open')}
- </Button>
- )
- : null}
- <Button variant="outline" size="sm" disabled={busy !== undefined} onClick={() => onDisconnect(row.id)}>
- {t('disconnect')}
- </Button>
- </>
- )
- : (
- <Button variant="primary" size="sm" disabled={busy !== undefined || held} onClick={() => onConnect(row.id)}>
- {t('connect')}
- </Button>
- )}
- </span>
- </div>
+ <>
+ <Button variant="outline" size="sm" disabled={busy !== undefined || held} onClick={() => onTest(id)}>
+ {t('test')}
+ </Button>
+ {connected
+ ? (
+ <>
+ {bridgeOpen
+ ? (
+ <Button variant="primary" size="sm" disabled={busy !== undefined || opening === true} title={t('open.tip')} onClick={() => onOpen(id)}>
+ {opening === true ? t('open.opening') : t('open')}
+ </Button>
+ )
+ : bridgePending === true
+ ? (
+ <Button variant="primary" size="sm" disabled title={t('open.probing')}>
+ {t('open')}
+ </Button>
+ )
+ : null}
+ <Button variant="outline" size="sm" disabled={busy !== undefined} onClick={() => onDisconnect(id)}>
+ {t('disconnect')}
+ </Button>
+ </>
+ )
+ : (
+ <Button variant="primary" size="sm" disabled={busy !== undefined || held} onClick={() => onConnect(id)}>
+ {t('connect')}
+ </Button>
+ )}
+ {extras}
+ </>
+ )
+}
+
+/** The detail block under a row: install surface, errors, tunnel link, live log. */
+function RowDetails({ id, status, busy, logLines, bridgeError, installResult, t, onInstall }: {
+ id: string
+ status: MachineStatus | undefined
+ busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined
+ logLines: readonly string[]
+ bridgeError: string | undefined
+ installResult: InstallResult | undefined
+ t: (key: SshKey) => string
+ onInstall: (id: string) => void
+}): ReactNode {
+ return (
+ <>
{status?.dshMissing === true
- ? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(row.id)} />
+ ? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(id)} />
: null}
- {status?.lastError !== undefined ? <p className={css.statusError} role="alert">{status.lastError}</p> : null}
+ {status?.lastError !== undefined ? <p className={cls.statusError} role="alert">{status.lastError}</p> : null}
{bridgeError !== undefined
? (
- <p className={css.statusError} role="alert" data-testid={`bridge-error-${row.id}`}>
+ <p className={cls.statusError} role="alert" data-testid={`bridge-error-${id}`}>
{t('bridge.error')}
{bridgeError}
</p>
)
: null}
- {status?.tunnelBaseUrl !== undefined ? <p className={css.link}>{status.tunnelBaseUrl}</p> : null}
- <LogStream id={row.id} lines={logLines} fallback={status?.progress?.log} />
+ {status?.tunnelBaseUrl !== undefined ? <p className={cls.link}>{status.tunnelBaseUrl}</p> : null}
+ <LogStream id={id} lines={logLines} fallback={status?.progress?.log} />
{installResult !== undefined
- ? <p className={css.installNote} data-testid={`install-note-${row.id}`}>{installNoteOf(installResult, t)}</p>
+ ? <p className={cls.installNote} data-testid={`install-note-${id}`}>{installNoteOf(installResult, t)}</p>
: null}
- </li>
+ </>
)
}
@@ -357,7 +280,7 @@ function DiscoveredCard({ row, t, status, busy, logLines, bridgeOpen, bridgeErro
function StateDotOf({ status }: { status: MachineStatus | undefined }): ReactNode {
const state = dotStateOf(status)
if (state === 'idle')
- return <span className={css.stateDot} data-state="idle" aria-hidden="true" />
+ return <span className={cls.stateDot} data-state="idle" aria-hidden="true" />
return <StateDot state={state} size={8} />
}
@@ -369,7 +292,7 @@ function LogStream({ id, lines, fallback }: { id: string, lines: readonly string
if (output === '')
return null
return (
- <pre className={css.logStream} data-testid={`machine-log-${id}`}>
+ <pre className={cls.logStream} data-testid={`machine-log-${id}`}>
{output}
</pre>
)
@@ -385,14 +308,14 @@ function InstallPanel({ status, busy, t, onInstall }: {
const installing = busy === 'install' || status.progress?.phase === 'installing'
if (installing) {
return (
- <div className={css.installBox}>
- <p className={css.installHint}>{t('progress.installing')}</p>
+ <div className={cls.installBox}>
+ <p className={cls.installHint}>{t('progress.installing')}</p>
</div>
)
}
return (
- <div className={css.installBox}>
- <p className={css.installHint}>{t('install.hint')}</p>
+ <div className={cls.installBox}>
+ <p className={cls.installHint}>{t('install.hint')}</p>
<Button variant="primary" size="sm" disabled={busy !== undefined} onClick={onInstall}>
{t('install.action')}
</Button>
@@ -411,15 +334,15 @@ function installNoteOf(result: InstallResult, t: (key: SshKey) => string): strin
/** One labeled field row. */
function Field({ label, children }: { label: string, children: ReactNode }): ReactNode {
return (
- <label className={css.field}>
- <span className={css.fieldLabel}>{label}</span>
+ <label className={cls.field}>
+ <span className={cls.fieldLabel}>{label}</span>
{children}
</label>
)
}
/**
- * The appearance row of one machine card: an identity-color swatch set
+ * The appearance row of one machine editor: an identity-color swatch set
* (plus a "default" reset) and the tint-the-border switch, which is only
* meaningful while a color is chosen. Clearing writes the empty-string
* (off) form — the save path drops it.
@@ -432,14 +355,14 @@ function AppearanceEditor({ row, t, onChange, draftKey }: {
}): ReactNode {
const color = colorOf(row)
return (
- <div className={css.appearance}>
- <span className={css.fieldLabel}>{t('field.color')}</span>
- <div className={css.swatches}>
+ <div className={cls.appearance}>
+ <span className={cls.fieldLabel}>{t('field.color')}</span>
+ <div className={cls.swatches}>
{COLOR_CHOICES.map(choice => (
<button
key={choice}
type="button"
- className={css.swatch}
+ className={cls.swatch}
data-selected={color === choice}
style={{ '--swatch-color': choice } as CSSProperties}
aria-label={`${t('field.color')}: ${choice}`}
@@ -449,23 +372,23 @@ function AppearanceEditor({ row, t, onChange, draftKey }: {
))}
<button
type="button"
- className={`${css.swatch} ${css.swatchNone}`}
+ className={`${cls.swatch} ${cls.swatchNone}`}
data-selected={color === undefined}
aria-label={t('color.none')}
aria-pressed={color === undefined}
title={t('color.none')}
onClick={() => onChange(draftKey, { color: '', tintBorder: false })}
/>
- <span className={css.switchRow}>
+ <span className={cls.switchRow}>
<button
type="button"
role="switch"
aria-checked={row.tintBorder === true}
- className={css.switch}
+ className={cls.switch}
disabled={color === undefined}
onClick={() => onChange(draftKey, { tintBorder: row.tintBorder !== true })}
/>
- <span className={css.fieldLabel}>{t('field.tintBorder')}</span>
+ <span className={cls.fieldLabel}>{t('field.tintBorder')}</span>
</span>
</div>
</div>
@@ -484,10 +407,10 @@ export function SecretField({ field, label, keyName, secretSet, t, value, onValu
}): ReactNode {
const placeholder = secretSet[`${keyName}.${field}`] ? t('secret.set') : t('secret.unset')
return (
- <label className={css.field}>
- <span className={css.fieldLabel}>{label}</span>
+ <label className={cls.field}>
+ <span className={cls.fieldLabel}>{label}</span>
<Input
- className={moduleClass(css.fieldInput)}
+ className={cls.fieldInput}
type="password"
value={value}
placeholder={placeholder}
@@ -510,6 +433,33 @@ function colorOf(row: MachineRow): string | undefined {
return row.color === undefined || row.color === '' ? undefined : row.color
}
+/** Short step labels of each pipeline phase (the long progress.* text stays in the status line). */
+const STEP_KEY_OF: Record<ProgressPhase, SshKey> = {
+ handshake: 'step.handshake',
+ installing: 'step.installing',
+ starting: 'step.starting',
+ probing: 'step.probing',
+}
+
+/** The step rail: the phases one operation actually walked, latest current. */
+function StepRail({ trail, t }: { trail: readonly ProgressPhase[], t: (key: SshKey) => string }): ReactNode {
+ if (trail.length === 0)
+ return null
+ const current = trail[trail.length - 1]
+ return (
+ <ol className={cls.stepRail} data-testid="step-rail">
+ {trail.map(phase => (
+ <li
+ key={phase}
+ className={phase === current ? cls.stepCurrent : cls.stepDone}
+ >
+ {t(STEP_KEY_OF[phase])}
+ </li>
+ ))}
+ </ol>
+ )
+}
+
/** The connection-state dot vocabulary (StateDot states; idle renders hollow). */
function dotStateOf(status: MachineStatus | undefined): DotState {
if (status?.state === 'connected')
@@ -548,33 +498,43 @@ function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => str
const base = status === undefined
? t('status.disconnected')
: t(STATUS_KEY_OF[status.state])
- if (status?.state === 'reconnecting' && status.nextRetryHint !== undefined && status.nextRetryHint !== '') {
- return base + t('status.nextRetry').replace('{hint}', status.nextRetryHint)
+ if (status?.state === 'reconnecting' && status.nextRetryAt !== undefined) {
+ return base + t('status.nextRetry').replace('{hint}', retryHintOf(status.nextRetryAt, Date.now(), t))
}
return base
}
+/**
+ * The relative-time hint for a scheduled retry: "now" once the instant is
+ * due, else "in Xs". The clock is read per render; the polling loop keeps
+ * reconnecting machines re-rendering, so the hint stays current.
+ */
+function retryHintOf(nextRetryAt: number, nowMs: number, t: (key: SshKey) => string): string {
+ const seconds = retrySecondsOf(nextRetryAt, nowMs)
+ return seconds <= 0 ? t('retry.now') : t('retry.inSeconds').replace('{seconds}', String(seconds))
+}
+
/** Parse a number input; non-numbers fall back to the default. */
function numberOf(raw: string, fallback: number): number {
const parsed = Number(raw)
return raw !== '' && Number.isFinite(parsed) ? parsed : fallback
}
-/**
- * Resolve one (possibly absent) CSS-module class for a primitive's optional
- * className seat: the module map reads as `string | undefined`, and
- * exactOptionalPropertyTypes forbids passing undefined where the prop is
- * merely optional.
- */
-function moduleClass(name: string | undefined): string {
- return name ?? ''
-}
-
/** One operator-facing description of a bridge failure. */
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
+/** Render one notice: host words verbatim, store literals through the locale table. */
+function noticeTextOf(notice: MachinesNotice, t: (key: SshKey) => string): string {
+ if (notice.kind === 'text')
+ return notice.text
+ let text = t(notice.key)
+ for (const [name, value] of Object.entries(notice.params ?? {}))
+ text = text.replace(`{${name}}`, value)
+ return text
+}
+
/**
* The add-machine dialog: one focused form, saved immediately on submit
* (the parent appends the row to the store). The id auto-derives from the
@@ -601,10 +561,13 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
const effectiveId = idTouched ? id.trim() : (slug === '' ? '' : freeIdOf(slug, takenIds))
const trimmedHost = host.trim()
const errorKey: SshKey | null
- = trimmedHost === '' ? 'add.host_required'
- : !ID_PATTERN.test(effectiveId) ? 'add.id_invalid'
- : takenIds.has(effectiveId) ? 'add.id_taken'
- : null
+ = trimmedHost === ''
+ ? 'add.host_required'
+ : !ID_PATTERN.test(effectiveId)
+ ? 'add.id_invalid'
+ : takenIds.has(effectiveId)
+ ? 'add.id_taken'
+ : null
function submit(): void {
if (errorKey !== null || saving)
@@ -671,24 +634,33 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
</div>
{errorKey === null
? <p className={cls.hint}>{t('add.id_auto')}</p>
- : <p className={cls.error} role="alert">{t(errorKey)}</p>}
+ : <p className={cls.error} role="alert">{errorKey === null ? '' : t(errorKey)}</p>}
</Modal>
)
}
/**
* Render the SSH-machines settings page.
+ *
+ * Rows are display-first: identity + live status + actions. Editing a manual
+ * machine expands an inline editor whose save applies to that row alone and
+ * immediately (no page-level staging); add is a focused modal; remove is
+ * confirmed then applied at once.
* @returns the page element tree.
*/
export function MachinesSection({ t, store, bridge }: MachinesSectionProps): ReactNode {
const state = useSyncExternalStore(store.subscribe, store.getSnapshot)
const [drafts, setDrafts] = useState<Record<string, Draft>>({})
const [dirty, setDirty] = useState<DirtySecrets>({})
+ /** The one row whose inline editor is open (null = all collapsed). */
+ const [editingId, setEditingId] = useState<string | null>(null)
+ const [savingId, setSavingId] = useState<string | null>(null)
const [addOpen, setAddOpen] = useState(false)
const [addSaving, setAddSaving] = useState(false)
const [initialized, setInitialized] = useState(false)
- const [availability, setAvailability] = useState<BridgeAvailability>(() => bridge?.probe === undefined ? 'web' : 'unknown')
+ const [availability, setAvailability] = useState<'desktop' | 'web' | 'unknown'>(() => bridge?.probe === undefined ? 'web' : 'unknown')
const [bridgeErrors, setBridgeErrors] = useState<Record<string, string>>({})
+ const [openingId, setOpeningId] = useState<string | null>(null)
const [removeTarget, setRemoveTarget] = useState<RemoveTarget | null>(null)
useEffect(() => {
@@ -731,12 +703,12 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
return () => clearInterval(timer)
}, [anyInFlight, store])
- // Initialize the draft buffer once the first load lands; later loads keep
- // the operator's in-progress edits (the buffer is the source until save).
+ // Initialize the draft buffer once the first load lands; the buffer only
+ // exists while a row editor is open (opened editors re-seed from the row).
useEffect(() => {
if (initialized || state.status !== 'ready')
return
- // eslint-disable-next-line react/set-state-in-effect -- load-once hydration: the draft buffer cannot exist before the first machine.list lands, and must not reset on later loads
+ // eslint-disable-next-line react/set-state-in-effect -- load-once hydration: the draft buffer cannot exist before the first machine.list lands
setInitialized(true)
// eslint-disable-next-line react/set-state-in-effect -- same hydrate-once guard as setInitialized above
setDrafts(Object.fromEntries(state.machines.map(row => [row.id, { key: row.id, row: { ...row } }])))
@@ -753,12 +725,48 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
setDirty(previous => ({ ...previous, [key]: { ...previous[key], [field]: value } }))
}
- const addMachine = (): void => {
- setAddOpen(true)
+ /** Open a row's editor, re-seeding its buffer from the latest saved row. */
+ const openEditor = (row: MachineRow): void => {
+ setDrafts(previous => ({ ...previous, [row.id]: { key: row.id, row: { ...row } } }))
+ setEditingId(row.id)
+ }
+
+ /** Discard a row's buffer and collapse its editor. */
+ const closeEditor = (key: string): void => {
+ const saved = state.machines.find(row => row.id === key)
+ if (saved !== undefined)
+ setDrafts(previous => ({ ...previous, [key]: { key, row: { ...saved } } }))
+ setDirty((previous) => {
+ const next = { ...previous }
+ delete next[key]
+ return next
+ })
+ setEditingId(null)
+ }
+
+ /** Save one row: persist the stored set with this row's buffer substituted. */
+ const saveRow = async (key: string): Promise<void> => {
+ const draft = drafts[key]
+ if (draft === undefined)
+ return
+ setSavingId(key)
+ const secrets = dirty[key] ?? {}
+ const rows = store.getSnapshot().machines.map(row => row.id === draft.row.id ? draft.row : row)
+ const ok = await store.persist(rows, { [key]: secrets })
+ setSavingId(null)
+ if (!ok)
+ return
+ setDirty((previous) => {
+ const next = { ...previous }
+ delete next[key]
+ return next
+ })
+ setEditingId(null)
}
- /** Add = create-and-save now: persist the saved set plus the new row; other
- * staged edits stay staged (we pass state.machines, not the drafts). */
+ /**
+ * Add = create-and-save now: persist the saved set plus the new row.
+ */
const submitAdd = async (row: MachineRow): Promise<void> => {
setAddSaving(true)
const ok = await store.persist([...store.getSnapshot().machines, row], {})
@@ -788,14 +796,20 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
delete next[key]
return next
})
+ if (editingId === id)
+ setEditingId(null)
})
}
- /** Ask the desktop shell for the remote window; failures surface per machine. */
+ /**
+ * Ask the desktop shell for the remote window; failures surface per machine.
+ * While the call is in flight the Open button shows an opening label.
+ */
const openRemoteWindow = (id: string): void => {
const url = state.statuses[id]?.tunnelBaseUrl
- if (url === undefined || bridge === undefined)
+ if (url === undefined || bridge === undefined || openingId !== null)
return
+ setOpeningId(id)
bridge.openWindow(id, url).then(
() => {
setBridgeErrors((previous) => {
@@ -809,117 +823,178 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
(error: unknown) => {
setBridgeErrors(previous => ({ ...previous, [id]: messageOf(error) }))
},
- )
- }
-
- const invalid = Object.values(drafts).some(draft =>
- draft.row.id === '' || draft.row.name === '' || draft.row.host === '')
-
- const save = (): void => {
- void store.persist(Object.values(drafts).map(draft => draft.row), dirty)
+ ).finally(() => setOpeningId(null))
}
const bridgeOpen = availability === 'desktop'
+ // 桌面桥探测未落定前给「新窗口打开」留禁用占位:落定后桌面端原位点亮、
+ // 纯 Web 端移除,避免按钮闪现造成布局跳动。
+ const bridgePending = availability === 'unknown'
return (
- <div className={css.section}>
- <h2 className={css.title}>{t('title')}</h2>
- <p className={css.intro}>{t('intro')}</p>
- <div className={css.chrome}>
- <Button variant="outline" disabled={state.status === 'loading'} onClick={() => void store.load()}>
- {t('refresh')}
- </Button>
- <Button variant="outline" className={moduleClass(css.addAction)} disabled={state.status === 'loading'} onClick={addMachine}>
- {t('addMachine')}
- </Button>
- <Button variant="primary" disabled={invalid || state.status === 'loading'} onClick={save}>
- {t('save')}
- </Button>
+ <div className={cls.section}>
+ <div className={cls.sectionHead}>
+ <div>
+ <h2 className={cls.title}>{t('title')}</h2>
+ <p className={cls.intro}>{t('intro')}</p>
+ </div>
+ <div className={cls.chrome}>
+ <Button variant="outline" size="sm" disabled={state.status === 'loading'} onClick={() => void store.load()}>
+ {t('refresh')}
+ </Button>
+ <Button variant="primary" size="sm" disabled={state.status === 'loading'} onClick={() => setAddOpen(true)}>
+ {t('addMachine')}
+ </Button>
+ </div>
</div>
- {state.notice !== null ? <p className={css.notice} data-testid="notice">{state.notice}</p> : null}
+ {state.notice !== null ? <p className={cls.notice} data-testid="notice">{noticeTextOf(state.notice, t)}</p> : null}
{state.error !== null
? (
- <p className={css.error} role="alert">
+ <p className={cls.error} role="alert">
{t('error.banner')}
{state.error}
</p>
)
: null}
- {invalid ? <p className={css.hint}>{t('saveHint')}</p> : null}
- {state.status === 'loading' ? <p className={css.hint}>{t('loading')}</p> : null}
+ {state.status === 'loading' ? <p className={cls.hint}>{t('loading')}</p> : null}
{state.status === 'error'
? (
- <div className={css.emptyBlock}>
- <p className={css.empty}>{t('loadFailed')}</p>
+ <div className={cls.emptyBlock}>
+ <p className={cls.empty}>{t('loadFailed')}</p>
<Button variant="outline" size="sm" onClick={() => void store.load()}>{t('refresh')}</Button>
</div>
)
: null}
- {state.status === 'ready' && Object.keys(drafts).length === 0 && state.discovered.length === 0
- ? <p className={css.empty}>{t('empty')}</p>
+ {state.status === 'ready' && state.machines.length === 0 && state.discovered.length === 0
+ ? <p className={cls.empty}>{t('empty')}</p>
: null}
+ <ul className={cls.rows}>
+ {state.machines.map((row) => {
+ const draft = drafts[row.id] ?? { key: row.id, row }
+ return (
+ <RowShell
+ key={row.id}
+ id={row.id}
+ name={row.name === '' ? row.id : row.name}
+ tag={row.host}
+ tintColor={colorOf(row)}
+ tintBorder={row.tintBorder === true}
+ status={state.statuses[row.id]}
+ trail={state.trails[row.id] ?? []}
+ t={t}
+ actions={(
+ <RowActions
+ id={row.id}
+ t={t}
+ status={state.statuses[row.id]}
+ busy={state.busy[row.id]}
+ bridgeOpen={bridgeOpen}
+ bridgePending={bridgePending}
+ opening={openingId === row.id}
+ onTest={id => void store.test(id)}
+ onConnect={id => void store.connect(id)}
+ onDisconnect={id => void store.disconnect(id)}
+ onOpen={openRemoteWindow}
+ extras={(
+ <>
+ <Button variant="outline" size="sm" disabled={editingId !== null && editingId !== row.id} onClick={() => editingId === row.id ? closeEditor(row.id) : openEditor(row)}>
+ {t('edit')}
+ </Button>
+ <Button variant="ghost" size="sm" className={cls.dangerAction} disabled={state.busy[row.id] !== undefined} onClick={() => setRemoveTarget({ key: row.id, id: row.id, name: row.name === '' ? row.id : row.name })}>
+ {t('remove')}
+ </Button>
+ </>
+ )}
+ />
+ )}
+ >
+ {editingId === row.id
+ ? (
+ <EditPanel
+ draft={draft}
+ t={t}
+ secretSet={secretFlagsOf(row)}
+ dirty={dirty[row.id] ?? {}}
+ saving={savingId === row.id}
+ onChange={patchDraft}
+ onSecret={patchDirty}
+ onSave={key => void saveRow(key)}
+ onCancel={closeEditor}
+ />
+ )
+ : null}
+ <RowDetails
+ id={row.id}
+ status={state.statuses[row.id]}
+ busy={state.busy[row.id]}
+ logLines={state.logs[row.id] ?? []}
+ bridgeError={bridgeErrors[row.id]}
+ installResult={state.installResults[row.id]}
+ t={t}
+ onInstall={id => void store.install(id)}
+ />
+ </RowShell>
+ )
+ })}
+ </ul>
{state.discovered.length > 0
? (
<>
- <div className={css.group}>
- <h3 className={css.groupTitle}>{t('configHosts')}</h3>
- <p className={css.groupHint}>{t('configHostsHint')}</p>
+ <div className={cls.group}>
+ <h3 className={cls.groupTitle}>{t('configHosts')}</h3>
+ <p className={cls.groupHint}>{t('configHostsHint')}</p>
</div>
- <ul className={css.rows}>
+ <ul className={cls.rows}>
{state.discovered.map(row => (
- <DiscoveredCard
+ <RowShell
key={row.id}
- row={row}
- t={t}
+ id={row.id}
+ name={row.name}
+ tag={t('configTag')}
+ tintColor={undefined}
+ tintBorder={false}
status={state.statuses[row.id]}
- busy={state.busy[row.id]}
- logLines={state.logs[row.id] ?? []}
- bridgeOpen={bridgeOpen}
- bridgeError={bridgeErrors[row.id]}
- installResult={state.installResults[row.id]}
- onTest={id => void store.test(id)}
- onConnect={id => void store.connect(id)}
- onDisconnect={id => void store.disconnect(id)}
- onInstall={id => void store.install(id)}
- onOpen={openRemoteWindow}
- />
+ trail={state.trails[row.id] ?? []}
+ t={t}
+ actions={(
+ <RowActions
+ id={row.id}
+ t={t}
+ status={state.statuses[row.id]}
+ busy={state.busy[row.id]}
+ bridgeOpen={bridgeOpen}
+ bridgePending={bridgePending}
+ opening={openingId === row.id}
+ onTest={id => void store.test(id)}
+ onConnect={id => void store.connect(id)}
+ onDisconnect={id => void store.disconnect(id)}
+ onOpen={openRemoteWindow}
+ />
+ )}
+ >
+ <RowDetails
+ id={row.id}
+ status={state.statuses[row.id]}
+ busy={state.busy[row.id]}
+ logLines={state.logs[row.id] ?? []}
+ bridgeError={bridgeErrors[row.id]}
+ installResult={state.installResults[row.id]}
+ t={t}
+ onInstall={id => void store.install(id)}
+ />
+ </RowShell>
))}
</ul>
</>
)
: null}
- <ul className={css.rows}>
- {Object.values(drafts).map(draft => (
- <MachineCard
- key={draft.key}
- draft={draft}
- t={t}
- secretSet={secretFlagsOf(draft.row)}
- status={state.statuses[draft.row.id]}
- busy={state.busy[draft.row.id]}
- logLines={state.logs[draft.row.id] ?? []}
- bridgeOpen={bridgeOpen}
- bridgeError={bridgeErrors[draft.row.id]}
- installResult={state.installResults[draft.row.id]}
- dirty={dirty[draft.key] ?? {}}
- onChange={patchDraft}
- onSecret={patchDirty}
- onRemove={setRemoveTarget}
- onTest={id => void store.test(id)}
- onConnect={id => void store.connect(id)}
- onDisconnect={id => void store.disconnect(id)}
- onInstall={id => void store.install(id)}
- onOpen={openRemoteWindow}
- />
- ))}
- </ul>
<SyncPanel store={store} t={t} />
{addOpen
? (
<AddMachineDialog
t={t}
saving={addSaving}
- takenIds={new Set([...state.machines.map(row => row.id), ...Object.values(drafts).map(draft => draft.row.id)])}
+ takenIds={new Set(state.machines.map(row => row.id))}
onSubmit={row => void submitAdd(row)}
onClose={() => {
if (!addSaving)
@@ -937,7 +1012,7 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
footer={(
<>
<Button variant="ghost" onClick={() => setRemoveTarget(null)}>{t('remove.confirm.cancel')}</Button>
- <Button variant="primary" className={moduleClass(css.dangerAction)} onClick={confirmRemove}>{t('remove.confirm.ok')}</Button>
+ <Button variant="primary" className={cls.dangerAction} onClick={confirmRemove}>{t('remove.confirm.ok')}</Button>
</>
)}
/>
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 9d8ec901..a9a470a9 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts
@@ -46,6 +46,8 @@ export const zh = {
'status.reconnecting': '重连中…',
'status.givenUp': '已放弃连接',
'status.nextRetry': '(下次重试:{hint})',
+ 'retry.now': '即刻',
+ 'retry.inSeconds': '{seconds}s 后',
'log.title': '日志',
'remove.confirm.title': '删除机器',
'remove.confirm.description': '将删除「{name}」的机器配置;已保存的密码/口令会一并删除。',
@@ -143,6 +145,8 @@ export const en = {
'status.reconnecting': 'Reconnecting…',
'status.givenUp': 'Given up',
'status.nextRetry': ' (next retry: {hint})',
+ 'retry.now': 'now',
+ 'retry.inSeconds': 'in {seconds}s',
'log.title': 'Log',
'remove.confirm.title': 'Remove machine',
'remove.confirm.description': 'This removes the "{name}" machine profile; any stored password or passphrase goes with it.',
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 3d5e11a4..5b984596 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
@@ -119,6 +119,32 @@ describe('machinesStore', () => {
.toEqual({ state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } })
})
+ it('accumulates the observed phase trail and clears it when the operation settles', async () => {
+ const { store, fetchFn } = boot({
+ ok: true,
+ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] },
+ })
+ await store.load()
+ expect(store.getSnapshot().trails.a).toEqual(['handshake'])
+ fetchFn.mockResolvedValueOnce({
+ json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } }),
+ } as unknown as Response)
+ await store.poll()
+ expect(store.getSnapshot().trails.a).toEqual(['handshake', 'starting'])
+ // 同阶段重复不重复入轨
+ fetchFn.mockResolvedValueOnce({
+ json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } }),
+ } as unknown as Response)
+ await store.poll()
+ expect(store.getSnapshot().trails.a).toEqual(['handshake', 'starting'])
+ // 操作落定(progress 消失)清轨
+ fetchFn.mockResolvedValueOnce({
+ json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } }),
+ } as unknown as Response)
+ await store.poll()
+ expect(store.getSnapshot().trails.a).toBeUndefined()
+ })
+
it('polls without flipping the loading banner', async () => {
const { store, fetchFn } = boot({
ok: true,
@@ -380,13 +406,17 @@ describe('machinesStore', () => {
})
describe('connection-state vocabulary', () => {
- it('reads the C-STATE states and the next-retry hint', async () => {
+ it('reads the C-STATE states, the retry instant, and the auth method', async () => {
const { store } = boot({
ok: true,
- value: { items: [{ ...machineA, state: 'reconnecting', nextRetryHint: 'in 8s' }] },
+ value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: 1_700_000_008_000, authMethod: 'key' }] },
})
await store.load()
- expect(store.getSnapshot().statuses.a).toMatchObject({ state: 'reconnecting', nextRetryHint: 'in 8s' })
+ expect(store.getSnapshot().statuses.a).toMatchObject({
+ state: 'reconnecting',
+ nextRetryAt: 1_700_000_008_000,
+ authMethod: 'key',
+ })
})
it('reads unknown wire states as disconnected', async () => {
@@ -402,55 +432,107 @@ describe('connection-state vocabulary', () => {
describe('machineEventsOf', () => {
it('parses well-formed events and drops malformed ones', () => {
expect(machineEventsOf({ events: [
- { seq: 2, ts: 1700000001, machineId: 'a', stage: 'bootstrap:clone', line: 'cloning' },
- { seq: 3, ts: 1700000002, machineId: 'a', stage: 'bootstrap:install', line: 'pnpm install', terminal: false },
- { seq: 4, ts: 1700000003, machineId: 'a', stage: 'connect:failed', line: 'gave up', terminal: true, reason: 'auth failed' },
+ { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'probing' },
+ { seq: 3, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'install', line: 'pnpm install', terminal: 'success' },
+ { seq: 4, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'auth', line: 'gave up', terminal: 'failed', reason: 'auth failed' },
] })).toEqual([
- { seq: 2, ts: 1700000001, machineId: 'a', stage: 'bootstrap:clone', line: 'cloning' },
- { seq: 3, ts: 1700000002, machineId: 'a', stage: 'bootstrap:install', line: 'pnpm install' },
- { seq: 4, ts: 1700000003, machineId: 'a', stage: 'connect:failed', line: 'gave up', terminal: true, reason: 'auth failed' },
+ { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'probing' },
+ { seq: 3, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'install', line: 'pnpm install', terminal: 'success' },
+ { seq: 4, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'auth', line: 'gave up', terminal: 'failed', reason: 'auth failed' },
])
expect(machineEventsOf(undefined)).toEqual([])
expect(machineEventsOf({ events: 'nope' })).toEqual([])
expect(machineEventsOf({ events: [{ machineId: 'a', line: 'x' }, 'junk'] })).toEqual([])
+ // A numeric ts or boolean terminal (the draft shapes) is malformed now.
+ expect(machineEventsOf({ events: [{ seq: 1, ts: 1_700_000_000, machineId: 'a', line: 'x' }] })).toEqual([])
+ expect(machineEventsOf({ events: [{ seq: 1, ts: '2025-09-01T00:00:00.000Z', machineId: 'a', line: 'x', terminal: true }] })[0]).not.toHaveProperty('terminal')
})
})
describe('event polling', () => {
- /** A fetch mock that answers machine.list and sequential machine.events payloads. */
- function eventsFetch(eventBatches: unknown[][]): FetchMock {
- let batch = 0
+ it('synthesizes a marker line for terminal events with an empty line', async () => {
+ const fetchFn = eventsFetch({
+ a: [[
+ { seq: 1, ts: '2025-09-01T00:00:00.000Z', machineId: 'a', stage: 'launch', line: '' },
+ { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'launch', line: '', terminal: 'failed', reason: 'port busy' },
+ ]],
+ })
+ const store = new MachinesStore(fetchFn)
+ await store.load()
+ await store.poll()
+ // 无 terminal 的空行丢弃;带 terminal 的收尾事件落成可见标记行
+ expect(store.getSnapshot().logs.a).toEqual(['[failed] port busy'])
+ })
+ /**
+ * A fetch mock that answers machine.list (one machine per id) and
+ * per-machine machine.events payloads, keyed by the polled machineId.
+ */
+ function eventsFetch(pagesByMachine: Record<string, unknown[][]>, listItems: MachineRow[] = [machineA]): FetchMock {
+ const batchByMachine = new Map<string, number>()
return vi.fn<FetchFn>(async (_url, init) => {
- const body = JSON.parse(String(init.body)) as { method: string }
+ const body = JSON.parse(String(init.body)) as { method: string, payload?: { machineId?: string } }
if (body.method === 'machine.events') {
- const events = eventBatches[Math.min(batch, eventBatches.length - 1)] ?? []
- batch += 1
+ const machineId = body.payload?.machineId ?? ''
+ const pages = pagesByMachine[machineId] ?? []
+ const batch = batchByMachine.get(machineId) ?? 0
+ batchByMachine.set(machineId, batch + 1)
+ const events = pages[Math.min(batch, pages.length - 1)] ?? []
return { json: async () => ({ ok: true, value: { events } }) } as unknown as Response
}
- return { json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } }) } as unknown as Response
+ return { json: async () => ({ ok: true, value: { items: listItems.map(row => ({ ...row, state: 'connecting' })) } }) } as unknown as Response
})
}
- it('folds event lines into the per-machine log tail past the cursor', async () => {
- const fetchFn = eventsFetch([
- [
- { seq: 1, ts: 1, machineId: 'a', stage: 'bootstrap:clone', line: 'line 1' },
- { seq: 2, ts: 2, machineId: 'a', stage: 'bootstrap:clone', line: 'line 2' },
- ],
- [
- { seq: 3, ts: 3, machineId: 'a', stage: 'bootstrap:install', line: 'line 3' },
+ /** The machine.events calls a fetch mock saw, as parsed payloads. */
+ function eventCallsOf(fetchFn: FetchMock): Array<{ machineId?: string, sinceSeq?: number }> {
+ return fetchFn.mock.calls
+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload?: { machineId?: string, sinceSeq?: number } })
+ .filter(call => call.method === 'machine.events')
+ .map(call => call.payload ?? {})
+ }
+
+ it('folds event lines into the per-machine log tail past the per-machine cursor', async () => {
+ const fetchFn = eventsFetch({
+ a: [
+ [
+ { seq: 1, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'line 1' },
+ { seq: 2, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'probe', line: 'line 2' },
+ ],
+ [
+ { seq: 3, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'ready', line: 'line 3', terminal: 'success' },
+ ],
],
- ])
+ })
const store = new MachinesStore(fetchFn)
await store.poll()
expect(store.getSnapshot().logs.a).toEqual(['line 1', 'line 2'])
await store.poll()
expect(store.getSnapshot().logs.a).toEqual(['line 1', 'line 2', 'line 3'])
- // The cursor rode along: the second call asked for events after seq 2.
- const eventsCalls = fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload?: { after?: number } })
- .filter(call => call.method === 'machine.events')
- expect(eventsCalls[1]?.payload).toEqual({ after: 2 })
+ // The cursor rode along per machine: the second poll of machine a asked
+ // for events after its own seq 2 (the first poll omitted sinceSeq).
+ const calls = eventCallsOf(fetchFn)
+ expect(calls[0]).toEqual({ machineId: 'a' })
+ expect(calls[1]).toEqual({ machineId: 'a', sinceSeq: 2 })
+ })
+
+ it('advances each machine cursor in its own seq space', async () => {
+ const fetchFn = eventsFetch({
+ a: [[{ seq: 10, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'a line' }]],
+ b: [[{ seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'b', stage: 'auth', line: 'b line' }]],
+ }, [machineA, machineB])
+ const store = new MachinesStore(fetchFn)
+ await store.poll()
+ expect(store.getSnapshot().logs.a).toEqual(['a line'])
+ expect(store.getSnapshot().logs.b).toEqual(['b line'])
+ // Both machines polled from the start on the first round; machine a's
+ // high seq must not starve machine b's lower seq space.
+ const firstRound = eventCallsOf(fetchFn)
+ expect(firstRound).toContainEqual({ machineId: 'a' })
+ expect(firstRound).toContainEqual({ machineId: 'b' })
+ await store.poll()
+ const secondRound = eventCallsOf(fetchFn).slice(firstRound.length)
+ expect(secondRound).toContainEqual({ machineId: 'a', sinceSeq: 10 })
+ expect(secondRound).toContainEqual({ machineId: 'b', sinceSeq: 2 })
})
it('turns the channel off after the host refuses it once', async () => {
@@ -459,7 +541,7 @@ describe('event polling', () => {
if (body.method === 'machine.events') {
return { json: async () => ({ ok: false, error: { code: 'unknown-method', message: 'unknown method "machine.events"' } }) } as unknown as Response
}
- return { json: async () => ({ ok: true, value: { items: [] } }) } as unknown as Response
+ return { json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } }) } as unknown as Response
})
const store = new MachinesStore(fetchFn)
await store.poll()
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 ee1c56f2..68c7341b 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts
@@ -46,18 +46,23 @@ export interface SecretValues {
passphrase?: string
}
+/** The pipeline phases one connection-plane operation walks through. */
+export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing'
+
/** Live transport status of one machine, from the /api-ssh list. */
export interface MachineStatus {
/** The C-STATE vocabulary (S3-owned); unknown wire values read as disconnected. */
state: MachineLifecycleState
- /** While reconnecting: when the next retry fires (S3's optional hint). */
- nextRetryHint?: string
+ /** While reconnecting: epoch ms of the next scheduled retry (S3-owned field). */
+ nextRetryAt?: number
+ /** Which credential the live (or last successful) connection used; registered, not rendered. */
+ authMethod?: 'agent' | 'key' | 'password'
tunnelBaseUrl?: string
lastError?: string
/** Whether the last failure was "dsh not installed on the remote" (offers install). */
dshMissing?: boolean
/** Live progress of the in-flight operation (phase codes translated by the UI). */
- progress?: { phase: 'handshake' | 'starting' | 'probing' | 'installing', attempt?: number, total?: number, log?: string }
+ progress?: { phase: ProgressPhase, attempt?: number, total?: number, log?: string }
}
/** Outcome of a machine.install call (the host's install result). */
@@ -99,6 +104,8 @@ export interface MachinesPageState {
statuses: Record<string, MachineStatus>
/** Streaming log lines per machine id (the S2 event channel; capped tail). */
logs: Record<string, string[]>
+ /** Observed progress-phase sequence per machine id (the step rail's truth). */
+ trails: Record<string, ProgressPhase[]>
/** One in-flight connection-plane op per machine id. */
busy: Record<string, 'test' | 'connect' | 'disconnect' | 'install'>
/** The latest connection-plane outcome, shown in the banner. */
@@ -164,17 +171,17 @@ export function machineEventsOf(value: unknown): SshMachineEvent[] {
const event = entry as Record<string, unknown>
if (typeof event.seq !== 'number' || typeof event.machineId !== 'string' || typeof event.line !== 'string')
continue
- if (event.ts !== undefined && typeof event.ts !== 'number')
+ if (event.ts !== undefined && typeof event.ts !== 'string')
continue
if (event.stage !== undefined && typeof event.stage !== 'string')
continue
out.push({
seq: event.seq,
- ts: typeof event.ts === 'number' ? event.ts : 0,
+ ts: typeof event.ts === 'string' ? event.ts : '',
machineId: event.machineId,
stage: typeof event.stage === 'string' ? event.stage : '',
line: event.line,
- ...event.terminal === true ? { terminal: true } : {},
+ ...(event.terminal === 'success' || event.terminal === 'failed') ? { terminal: event.terminal } : {},
...typeof event.reason === 'string' ? { reason: event.reason } : {},
})
}
@@ -336,8 +343,12 @@ export class MachinesStore {
/** The published page state. */
readonly store: SnapshotStore<MachinesPageState> & { update: (mutator: (state: MachinesPageState) => void) => void }
- /** The consumed event cursor (machine.events seq high-water mark). */
- private lastEventSeq = 0
+ /**
+ * The consumed event cursor per machine id (the last `seq` seen for that
+ * machine). `seq` is a per-machine space — a global high-water mark would
+ * mix counters and starve machines with lower sequence numbers.
+ */
+ private readonly lastEventSeqByMachine = new Map<string, number>()
/** Whether the host still gets asked for machine.events (off after first refusal). */
private eventsSupported = true
@@ -353,6 +364,7 @@ export class MachinesStore {
discovered: [],
statuses: {},
logs: {},
+ trails: {},
busy: {},
notice: null,
installResults: {},
@@ -386,8 +398,10 @@ export class MachinesStore {
const statuses: Record<string, MachineStatus> = {}
for (const item of [...(list.items ?? []), ...(list.discovered ?? [])]) {
const status: MachineStatus = { state: lifecycleStateOf(item.state) }
- if (typeof item.nextRetryHint === 'string' && item.nextRetryHint !== '')
- status.nextRetryHint = item.nextRetryHint
+ if (typeof item.nextRetryAt === 'number' && Number.isFinite(item.nextRetryAt))
+ status.nextRetryAt = item.nextRetryAt
+ if (item.authMethod === 'agent' || item.authMethod === 'key' || item.authMethod === 'password')
+ status.authMethod = item.authMethod
if (item.tunnelBaseUrl !== undefined)
status.tunnelBaseUrl = item.tunnelBaseUrl
if (item.lastError !== undefined)
@@ -404,6 +418,24 @@ export class MachinesStore {
state.machines = machines
state.discovered = discovered
state.statuses = statuses
+ // 阶段轨迹:操作期间把实际出现的 progress.phase 依次入轨(步骤条的
+ // 真值——装没装过 install 阶段由轨迹说话);progress 消失即操作结束,
+ // 清轨让步骤条收起。被删除的机器顺带清轨。
+ for (const [id, status] of Object.entries(statuses)) {
+ const phase = status.progress?.phase
+ if (phase !== undefined) {
+ const trail = state.trails[id] ?? []
+ if (trail[trail.length - 1] !== phase)
+ state.trails[id] = [...trail, phase]
+ }
+ else {
+ delete state.trails[id]
+ }
+ }
+ for (const id of Object.keys(state.trails)) {
+ if (statuses[id] === undefined)
+ delete state.trails[id]
+ }
})
}
@@ -438,33 +470,53 @@ export class MachinesStore {
}
/**
- * Pull machine.events past the cursor and fold the lines into the per-machine
- * logs. A host without the S2 channel (or any refusal) turns the channel off
- * for good — the panel then lives on the status progress fields alone, and
- * the polling loop never fails the page for it.
+ * Pull machine.events for every known machine and fold the lines into the
+ * per-machine logs. The channel is per-machine: `seq` counts inside one
+ * machine's buffer only, so the cursor lives per machine id and each poll
+ * sends `{ machineId, sinceSeq }` per machine (the cursor is omitted on a
+ * machine's first poll). A host without the S2 channel (or any refusal)
+ * turns the channel off for good — the panel then lives on the status
+ * progress fields alone, and the polling loop never fails the page for it.
*/
private async pollEvents(): Promise<void> {
if (!this.eventsSupported)
return
- let events: SshMachineEvent[]
+ const snapshot = this.store.getSnapshot()
+ const known = new Set([...snapshot.machines, ...snapshot.discovered].map(row => row.id))
+ // Removed machines leave their cursors behind; drop them so the map
+ // tracks the live machine set only.
+ for (const id of this.lastEventSeqByMachine.keys()) {
+ if (!known.has(id))
+ this.lastEventSeqByMachine.delete(id)
+ }
+ const byMachine = new Map<string, string[]>()
try {
- events = machineEventsOf(await this.callApi<unknown>('machine.events', {
- ...this.lastEventSeq === 0 ? {} : { after: this.lastEventSeq },
- }))
+ for (const machineId of known) {
+ const cursor = this.lastEventSeqByMachine.get(machineId)
+ const events = machineEventsOf(await this.callApi<unknown>('machine.events', {
+ machineId,
+ ...cursor === undefined ? {} : { sinceSeq: cursor },
+ }))
+ if (events.length === 0)
+ continue
+ this.lastEventSeqByMachine.set(machineId, Math.max(...events.map(event => event.seq)))
+ for (const event of events) {
+ // 空行的收尾事件(terminal/reason)合成一行标记,不再静默丢弃
+ const line = event.line !== ''
+ ? event.line
+ : event.terminal === undefined
+ ? ''
+ : `[${event.terminal}]${event.reason === undefined ? '' : ` ${event.reason}`}`
+ if (line === '')
+ continue
+ byMachine.set(event.machineId, [...(byMachine.get(event.machineId) ?? []), line])
+ }
+ }
}
catch {
this.eventsSupported = false
return
}
- if (events.length === 0)
- return
- this.lastEventSeq = Math.max(this.lastEventSeq, ...events.map(event => event.seq))
- const byMachine = new Map<string, string[]>()
- for (const event of events) {
- if (event.line === '')
- continue
- byMachine.set(event.machineId, [...(byMachine.get(event.machineId) ?? []), event.line])
- }
if (byMachine.size === 0)
return
this.store.update((state) => {
diff --git a/packages/dsh-tauri-ssh-ui/src/client/types/sync.ts b/packages/dsh-tauri-ssh-ui/src/client/types/sync.ts
index b2f57a1d..789d3a33 100644
--- a/packages/dsh-tauri-ssh-ui/src/client/types/sync.ts
+++ b/packages/dsh-tauri-ssh-ui/src/client/types/sync.ts
@@ -8,8 +8,8 @@
/**
* The connection-state vocabulary (C-STATE, S3-owned): the six lifecycle
- * states a machine row can report, plus the optional next-retry hint that
- * rides a `reconnecting` status.
+ * states a machine row can report. A `reconnecting` row also carries the
+ * optional `nextRetryAt` epoch-ms field (the retry-hint source).
*/
export type MachineLifecycleState
= | 'disconnected'
@@ -29,14 +29,22 @@ export function isLifecycleState(value: unknown): value is MachineLifecycleState
|| value === 'given-up'
}
-/** One machine event from the polled `machine.events` channel (C-EVENT, S2-owned). */
+/**
+ * One machine event from the polled `machine.events` channel (C-EVENT,
+ * S2-owned): a displayable log line tagged with its pipeline stage. `seq` is
+ * a per-machine space (the poll cursor is kept per machine, never mixed).
+ */
export interface SshMachineEvent {
+ /** Per-machine sequence number. */
seq: number
- ts: number
+ /** Wall-clock timestamp (ISO-8601), passed through as the host spelled it. */
+ ts: string
machineId: string
+ /** Pipeline stage; passed through unclassified (auth/reconnect need no special case). */
stage: string
line: string
- terminal?: boolean
+ /** Terminal verdict, present only on the settling event of an operation. */
+ terminal?: 'success' | 'failed'
reason?: string
}
diff --git a/packages/dsh-tauri-ssh-ui/src/client/utils/retry.ts b/packages/dsh-tauri-ssh-ui/src/client/utils/retry.ts
new file mode 100644
index 00000000..5c420b7d
--- /dev/null
+++ b/packages/dsh-tauri-ssh-ui/src/client/utils/retry.ts
@@ -0,0 +1,19 @@
+/**
+ * Pure time helpers for the machine-status line. The host reports the next
+ * reconnect retry as an epoch-ms instant (`nextRetryAt`, S3-owned); the UI
+ * renders it as a short relative hint, so the clock math lives here as a
+ * pure function (testable without React or a store).
+ * @module dsh-tauri-ssh-ui/client/utils/retry
+ */
+
+/**
+ * Whole seconds until the scheduled retry, rounded up so a partial second
+ * still reads as a full one (a "0s" hint would look like a bug while the
+ * retry has not fired yet).
+ * @param nextRetryAt - the epoch-ms instant the retry fires.
+ * @param nowMs - the reference clock (injected; tests pin it).
+ * @returns the remaining seconds; `0` means the retry is due now or overdue.
+ */
+export function retrySecondsOf(nextRetryAt: number, nowMs: number): number {
+ return Math.max(0, Math.ceil((nextRetryAt - nowMs) / 1000))
+}
diff --git a/packages/dsh-tauri-ssh/e2e/helpers.ts b/packages/dsh-tauri-ssh/e2e/helpers.ts
index 8a4480a0..aa9334f8 100644
--- a/packages/dsh-tauri-ssh/e2e/helpers.ts
+++ b/packages/dsh-tauri-ssh/e2e/helpers.ts
@@ -5,16 +5,33 @@
* @module dsh-tauri-ssh/e2e/helpers
*/
-import type { SshMachineEvent } from '../src/host/types/index.js'
+import type { SshMachineStage, SshMachineTerminal } from '../src/host/types/index'
import { generateKeyPairSync } from 'node:crypto'
import { mkdtempSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { join } from 'pathe'
-import { KnownHostsStore } from '../src/host/service/host-keys.js'
-import { SshManager } from '../src/host/service/manager.js'
-import { SshConfigResolver } from '../src/host/service/ssh-config.js'
-import { Ssh2Transport } from '../src/host/service/transport.js'
-import { MachineId } from '../src/host/types/index.js'
+import { SshMachineEvents } from '../src/host/service/events'
+import { KnownHostsStore } from '../src/host/service/host-keys'
+import { SshManager } from '../src/host/service/manager'
+import { SshConfigResolver } from '../src/host/service/ssh-config'
+import { Ssh2Transport } from '../src/host/service/transport'
+import { MachineId } from '../src/host/types/index'
+
+/**
+ * The machine event channel with evidence logging: every appended line is
+ * echoed into the harness log (`event <stage>[/<terminal>]: <line>`) before
+ * it lands in the ring buffer, so spec files can grep the emitted stream.
+ */
+class LoggingMachineEvents extends SshMachineEvents {
+ constructor(private readonly log: (text: string) => void) {
+ super()
+ }
+
+ override append(machineId: MachineId, stage: SshMachineStage, line: string, options: { terminal?: SshMachineTerminal, reason?: string } = {}) {
+ this.log(`event ${stage}${options.terminal === undefined ? '' : `/${options.terminal}`}: ${line}`)
+ return super.append(machineId, stage, line, options)
+ }
+}
/** One timestamped evidence line. */
export interface EvidenceLine {
@@ -89,7 +106,7 @@ export function bootHarness(options: {
reconnectMaxDelayMs: options.reconnectMaxDelayMs ?? 5_000,
reconnectMaxAttempts: options.reconnectMaxAttempts ?? 6,
},
- eventSink: { emit: (event: SshMachineEvent) => { log(`event ${event.stage}${event.outcome === undefined ? '' : `/${event.outcome}`}: ${event.text}`) } },
+ events: new LoggingMachineEvents(log),
emitStatus: (id, status) => {
const hints = [
status.state,
diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.ts
index d709d746..3821b8d3 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.ts
@@ -9,28 +9,24 @@
*/
import type z from 'schemastery'
-import type { SshApiHost } from './routes/index.js'
-import type { SshHostBlock } from './service/ssh-config.js'
-import type { MachinesValue, Config as SshRemoteConfig } from './storage/index.js'
-<<<<<<< HEAD
-import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineEventsPage, SshMachineStatus, SshTestResult } from './types/index.js'
-=======
-import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef } from './types/index.js'
->>>>>>> a59eb500 (feat(ssh): sync.* /api-ssh surface (engine + per-item results))
+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 { homedir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
-import { SSH_API_PREFIX, SSH_PLUGIN_NAME } from '../shared/constants.js'
-import { createSshApiHandler } from './routes/index.js'
-import { SshMachineEvents } from './service/events.js'
-import { KnownHostsStore } from './service/host-keys.js'
-import { profileView, SshManager } from './service/manager.js'
-import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config.js'
-import { profileDependenciesReader, skillRootsScanner, tarPacker } from './service/sync-local.js'
-import { SyncEngine } from './service/sync.js'
-import { Ssh2Transport } from './service/transport.js'
-import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MACHINES_NAMESPACE, machinesFromValue, MachinesSchema } from './storage/index.js'
-import { MachineId } from './types/index.js'
+import { SSH_API_PREFIX, SSH_PLUGIN_NAME } from '../shared/constants'
+import { createSshApiHandler } from './routes/index'
+import { SshMachineEvents } from './service/events'
+import { KnownHostsStore } from './service/host-keys'
+import { profileView, SshManager } from './service/manager'
+import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config'
+import { SyncEngine } from './service/sync'
+import { 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 { MachineId } from './types/index'
/** Default location of the TOFU host-key document under the harness home. */
function defaultKnownHostsPath(): string {
@@ -80,8 +76,14 @@ export class SshRemoteService implements SshApiHost {
transport: new Ssh2Transport(
config.connectTimeoutMs,
// Credentials come from the host's own ~/.ssh (config + identity
- // files), exactly like a local `ssh` invocation.
+ // files), exactly like a local `ssh` invocation; the auth chain is
+ // ssh-agent → private keys → stored password, and the keepalive
+ // watchdog timing is the plugin config's.
new SshConfigResolver(this.sshDir, this.homeDir),
+ {
+ keepaliveIntervalMs: config.keepaliveIntervalMs,
+ keepaliveCountMax: config.keepaliveCountMax,
+ },
),
knownHosts,
config,
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.ts b/packages/dsh-tauri-ssh/src/host/routes/index.ts
index f06e258e..14934521 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.ts
@@ -17,9 +17,9 @@
*/
import type { IncomingMessage, ServerResponse } from 'node:http'
-import type { MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshMachineEventsPage, SshMachineStatus, SshTestResult } from '../types/index.js'
+import type { MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshMachineEventsPage, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef, SyncSkillRoot } from '../types/index'
import { Buffer } from 'node:buffer'
-import { MachineId, SshError } from '../types/index.js'
+import { MachineId, SshError } from '../types/index'
/** One request envelope. */
export interface SshApiRequest {
@@ -34,7 +34,8 @@ export type SshApiResponse
/**
* The connection-plane method set (CRUD lives here too: the settings RPC only
- * serves an upstream allowlist, so the page writes through this route).
+ * serves an upstream allowlist, so the page writes through this route), plus
+ * the S4-owned `sync.*` surface (engine + execution + per-item results).
*/
export type SshApiMethod
= | 'machine.list'
@@ -45,6 +46,8 @@ export type SshApiMethod
| 'machine.events'
| 'machine.save'
| 'machine.remove'
+ | 'sync.preview'
+ | 'sync.apply'
/** A machine list row: the redacted profile plus its live status. */
export interface SshMachineListItem extends MachineView {
@@ -73,6 +76,10 @@ export interface SshApiHost {
events: (machineId: MachineId, sinceSeq?: number) => SshMachineEventsPage
save: (machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite) => Promise<void>
remove: (machineId: MachineId) => Promise<void>
+ /** The local plugins and skills available to sync (the selection list). */
+ syncPreview: () => SyncPreview
+ /** Sync the selection to one machine; every item settles in the result. */
+ syncApply: (machineId: MachineId, plugins: SyncPluginRef[], skills: SyncSkillRef[]) => Promise<SyncApplyResult>
}
/** Whether a socket peer is loopback (the only allowed caller of this API). */
@@ -221,6 +228,16 @@ export function createSshApiHandler(host: SshApiHost): (req: IncomingMessage, re
respond(200, { ok: true, value: {} })
return
}
+ case 'sync.preview': {
+ respond(200, { ok: true, value: host.syncPreview() })
+ return
+ }
+ case 'sync.apply': {
+ const machineId = machineIdOf(payload)
+ const value = await host.syncApply(machineId, pluginRefsOf(payload), skillRefsOf(payload))
+ respond(200, { ok: true, value })
+ return
+ }
default:
respond(404, { ok: false, error: { code: 'unknown-method', message: `unknown method "${request.method}"` } })
}
@@ -309,3 +326,39 @@ function secretsOf(payload: Record<string, unknown>): MachineSecretWrite | undef
out.passphrase = value.passphrase
return out
}
+
+/** Validate the sync.apply plugin refs; the panel sends its display names along. */
+function pluginRefsOf(payload: Record<string, unknown>): SyncPluginRef[] {
+ const list = payload.plugins
+ if (list === undefined)
+ return []
+ if (!Array.isArray(list))
+ throw new Error('invalid plugins')
+ return list.map((entry) => {
+ if (typeof entry !== 'object' || entry === null)
+ throw new Error('invalid plugin ref')
+ const ref = entry as Record<string, unknown>
+ if (typeof ref.name !== 'string' || typeof ref.spec !== 'string' || ref.spec === '')
+ throw new Error('invalid plugin ref')
+ return { name: ref.name, spec: ref.spec }
+ })
+}
+
+/** Validate the sync.apply skill refs; the root picks the local source tree. */
+function skillRefsOf(payload: Record<string, unknown>): SyncSkillRef[] {
+ const list = payload.skills
+ if (list === undefined)
+ return []
+ if (!Array.isArray(list))
+ throw new Error('invalid skills')
+ return list.map((entry) => {
+ if (typeof entry !== 'object' || entry === null)
+ throw new Error('invalid skill ref')
+ const ref = entry as Record<string, unknown>
+ if (typeof ref.name !== 'string' || ref.name === '')
+ throw new Error('invalid skill ref')
+ if (ref.root !== 'dsh' && ref.root !== 'agents')
+ throw new Error('invalid skill ref: root')
+ return { name: ref.name, root: ref.root as SyncSkillRoot }
+ })
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
index 918a988c..bc799450 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
@@ -45,6 +45,11 @@ const E2E_CONFIG = {
healthPollIntervalMs: 1_000,
healthPollAttempts: 90,
installTimeoutMs: 1_800_000,
+ keepaliveIntervalMs: 10_000,
+ keepaliveCountMax: 3,
+ reconnectInitialDelayMs: 1_000,
+ reconnectMaxDelayMs: 5_000,
+ reconnectMaxAttempts: 6,
}
/** Kill only processes whose command line references the shared layout. */
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
index 42329329..22cf7fde 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
@@ -61,6 +61,8 @@ const BOOTSTRAP_STAGES: Record<SshMachineStage, true> = {
launch: true,
ready: true,
failed: true,
+ auth: true,
+ reconnect: true,
}
/** Whether a parsed marker word is one of the known stage tags. */
@@ -498,6 +500,29 @@ export function layoutDshEntry(plan?: RemoteInstallPlan): string {
return `$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan?.dshEntry ?? DSH_ZIP_ENTRY}`
}
+/** The layout's Node binary, double-quoted so `$HOME` still expands under `sh -lc`. */
+export function layoutNodeBinary(): string {
+ return `"$HOME/${REMOTE_ROOT}/runtime/bin/node"`
+}
+
+/**
+ * The installed dsh-entry probe for command-driving callers (the sync
+ * engine): prints the first entry the binary layout actually holds — zip
+ * layout first, npm layout second, the same precedence as
+ * {@link checkMissingCommand} — or nothing when neither is installed.
+ * Unlike the instance launch the plan is unknown here, so the probe resolves
+ * it remotely; the printed path is absolute (`$HOME` already expanded).
+ */
+export function dshEntryProbeCommand(): string {
+ return [
+ `ROOT="$HOME/${REMOTE_ROOT}"`,
+ `if [ -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ]; then printf '%s\\n' "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}"`,
+ `elif [ -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then printf '%s\\n' "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}"`,
+ 'fi',
+ 'true',
+ ].join('\n')
+}
+
/**
* The remote-instance launch: the profile override when present, else the
* layout's Node + DSH entry with the port pinned twice (`DSH_WEB_PORT` and
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
index a8fcae19..c3b16744 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
@@ -1,15 +1,15 @@
-import type { MachineProfile, SshMachineEvent } from '../types/index.js'
-import type { RemoteInstallPlan } from './bootstrap.js'
-import type { SshExecOptions, SshExecResult, SshSession, SshTransport, SshTunnelHandle } from './transport.js'
+import type { MachineProfile, SshMachineEvent } from '../types/index'
+import type { RemoteInstallPlan } from './bootstrap'
+import type { SshExecOptions, SshExecResult, SshSession, SshTransport, SshTunnelHandle } from './transport'
import { Buffer } from 'node:buffer'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
-import { afterEach, describe, expect, it } from 'vitest'
-import { MachineId, SshError } from '../types/index.js'
-import { SshMachineEvents } from './events.js'
-import { KnownHostsStore } from './host-keys.js'
-import { SshManager } from './manager.js'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { MachineId, SshError } from '../types/index'
+import { SshMachineEvents } from './events'
+import { KnownHostsStore } from './host-keys'
+import { SshManager } from './manager'
const profile: MachineProfile = {
id: MachineId('m1'),
@@ -33,6 +33,11 @@ const config = {
healthPollIntervalMs: 5,
healthPollAttempts: 3,
installTimeoutMs: 60000,
+ keepaliveIntervalMs: 10000,
+ keepaliveCountMax: 3,
+ reconnectInitialDelayMs: 1,
+ reconnectMaxDelayMs: 2,
+ reconnectMaxAttempts: 2,
}
/** A boot page whose manifest the bundle probe confirms. */
@@ -80,6 +85,9 @@ class FakeSession implements SshSession {
tunnelGate: Promise<void> | undefined
tunnelStarted: (() => void) | undefined
execGate: ((command: string, index: number) => Promise<void> | undefined) | undefined
+ /** The preferred local port the last openTunnel call received. */
+ preferredTunnelPort: number | undefined
+ authMethod: SshSession['authMethod'] = 'key'
private closedCallbacks: Array<() => void> = []
constructor(
@@ -95,6 +103,8 @@ class FakeSession implements SshSession {
missingResult = ''
/** Whether the launch answered REMOTE_NOT_INSTALLED instead of starting. */
startNotInstalled = false
+ /** The web-log token grep answer (default: no token → bare tunnel URL). */
+ webTokenResult = ''
exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {
this.commands.push(command)
@@ -122,6 +132,10 @@ class FakeSession implements SshSession {
if (command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')) {
return { code: 0, stdout: this.credentialsAnswer, stderr: '' }
}
+ // 注意用命令头识别:launch 命令行里也含日志路径(重定向目标)
+ if (command.startsWith('grep -oE \'token=')) {
+ return { code: 0, stdout: this.webTokenResult, stderr: '' }
+ }
if (command.includes('dsh-remote.pid')) {
if (this.startNotInstalled)
return { code: 1, stdout: 'REMOTE_NOT_INSTALLED: 远端三件套未安装完整', stderr: '' }
@@ -153,7 +167,12 @@ class FakeSession implements SshSession {
/** The stdout the credentials-copy command answers (default: copied). */
credentialsAnswer = 'copied'
- async openTunnel(): Promise<SshTunnelHandle> {
+ /** The injection slot the last openTunnel call received. */
+ tunnelInjection: { cookie: string | undefined } | undefined
+
+ async openTunnel(_remotePort: number, preferredLocalPort?: number, injection?: { cookie: string | undefined }): Promise<SshTunnelHandle> {
+ this.tunnelInjection = injection
+ this.preferredTunnelPort = preferredLocalPort
this.tunnelStarted?.()
if (this.tunnelGate !== undefined)
await this.tunnelGate
@@ -190,14 +209,17 @@ class FakeTransport implements SshTransport {
connectCalls = 0
hostKeys: Array<{ key: Buffer, accepted: boolean }> = []
rejectKeys = false
+ /** The profile each connect call received (the loop must re-read edits). */
+ profiles: MachineProfile[] = []
constructor(private readonly sessionFactory: () => FakeSession) {}
async connect(
- _profile: MachineProfile,
- hostKeyVerifier: (key: Buffer) => boolean | Promise<boolean>,
+ profile: MachineProfile,
+ hostKeyVerifier: (label: string, key: Buffer) => boolean | Promise<boolean>,
): Promise<SshSession> {
this.connectCalls += 1
+ this.profiles.push(profile)
const session = this.sessionFactory()
this.sessions.push(session)
if (this.rejectKeys)
@@ -205,7 +227,7 @@ class FakeTransport implements SshTransport {
if (session.connectError !== undefined)
throw session.connectError
const key = Buffer.from('host-key')
- this.hostKeys.push({ key, accepted: await hostKeyVerifier(key) })
+ this.hostKeys.push({ key, accepted: await hostKeyVerifier(String(profile.id), key) })
return session
}
}
@@ -222,12 +244,32 @@ afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
+/** Wait until the predicate holds (background reconnect races). */
+async function until(predicate: () => boolean, label: string): Promise<void> {
+ const deadline = Date.now() + 2000
+ while (!predicate()) {
+ if (Date.now() > deadline)
+ throw new Error(`timed out waiting for ${label}`)
+ await new Promise(resolve => setTimeout(resolve, 5))
+ }
+}
+
+/** Wait until one machine settles into its terminal state after a failure. */
+async function untilSettled(manager: SshManager, machineId: MachineId = MachineId('m1')): Promise<void> {
+ await until(() => {
+ const state = manager.status(machineId).state
+ return state === 'given-up' || state === 'connected' || state === 'disconnected'
+ }, 'terminal state')
+}
+
function boot(overrides: Partial<{
sessionFactory: () => FakeSession
rejectKeys: boolean
readEnvCredentials: () => { apiKey?: string, baseUrl?: string }
config: typeof config
planInstall: () => Promise<RemoteInstallPlan>
+ mintCookie: (authenticatedUrl: string) => Promise<string | undefined>
+ syncPlugins: (session: import('./transport').SshSession, hooks: { onEvent?: (stage: import('../types/index').SshMachineStage, line: string) => void }) => Promise<boolean>
}> = {}) {
const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))
transport.rejectKeys = overrides.rejectKeys ?? false
@@ -240,6 +282,10 @@ function boot(overrides: Partial<{
config: overrides.config ?? config,
events,
planInstall: overrides.planInstall ?? (() => Promise.resolve(plan)),
+ // 默认离线 mint:不走真实 HTTP;个别用例经 overrides 覆盖
+ mintCookie: overrides.mintCookie ?? (() => Promise.resolve(undefined)),
+ // 默认离线插件同步:不打本地 tar;个别用例经 overrides 覆盖
+ syncPlugins: overrides.syncPlugins ?? (() => Promise.resolve(false)),
...overrides.readEnvCredentials === undefined ? {} : { readEnvCredentials: overrides.readEnvCredentials },
emitStatus: (id, status) => {
emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })
@@ -362,25 +408,29 @@ describe('sshManager', () => {
it('clears progress and reports the failure when connect fails', async () => {
const { manager } = boot({ rejectKeys: true })
await expect(manager.connect(MachineId('m1'))).rejects.toThrow()
+ await untilSettled(manager)
const status = manager.status(MachineId('m1'))
- expect(status.state).toBe('disconnected')
+ expect(status.state).toBe('given-up')
expect(status.progress).toBeUndefined()
- expect(status.lastError).toBe('auth failed')
+ expect(status.lastError).toBe('connect failed after 3 attempt(s): auth failed')
+ expect(status.nextRetryAt).toBeUndefined()
})
it('fails loud with machine-connect-failed on transport errors', async () => {
const { manager } = boot({ rejectKeys: true })
await expect(manager.connect(MachineId('m1'))).rejects.toThrow(SshError)
- await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-reconnecting' })
+ await untilSettled(manager)
const status = manager.status(MachineId('m1'))
- expect(status.state).toBe('disconnected')
- expect(status.lastError).toBe('auth failed')
+ expect(status.state).toBe('given-up')
+ expect(status.lastError).toBe('connect failed after 3 attempt(s): auth failed')
})
it('fails loud with machine-bootstrap-failed when the instance never answers', async () => {
const { manager } = boot({ sessionFactory: () => new FakeSession(() => false) })
await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
- expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ await untilSettled(manager)
+ expect(manager.status(MachineId('m1')).state).toBe('given-up')
})
it('fails loud with machine-bootstrap-failed when the start command fails', async () => {
@@ -388,6 +438,8 @@ describe('sshManager', () => {
sessionFactory: () => new FakeSession(() => false, undefined, new Error('dsh: not found')),
})
await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
+ await untilSettled(manager)
+ expect(manager.status(MachineId('m1')).state).toBe('given-up')
})
it('settles the bootstrap stream when a transport exception bypasses the bootstrap failure path', async () => {
@@ -525,15 +577,41 @@ describe('sshManager', () => {
expect(emits.map(entry => entry.state)).toEqual(['connecting', 'disconnected'])
})
- it('marks the machine disconnected when the SSH session drops', async () => {
- const { manager, transport } = boot()
- await manager.connect(MachineId('m1'))
+ it('marks the machine disconnected when the SSH session drops and reconnects it', async () => {
+ const { manager, transport, emits, events } = boot()
+ const first = await manager.connect(MachineId('m1'))
const session = transport.sessions[0]!
session.drop()
+ // The drop hands the machine to the reconnect loop; the retry (1 ms in
+ // the test config) succeeds against the fresh session.
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-reconnect')
const status = manager.status(MachineId('m1'))
- expect(status.state).toBe('disconnected')
- expect(status.lastError).toBe('SSH connection closed')
- expect(manager.link(MachineId('m1'))).toBeUndefined()
+ expect(status.state).toBe('connected')
+ expect(status.tunnelBaseUrl).toBe(first.tunnelBaseUrl)
+ expect(manager.link(MachineId('m1'))).toBeDefined()
+ expect(transport.connectCalls).toBe(2)
+ // One publish for the schedule, one for the in-flight retry's progress.
+ expect(emits.map(entry => entry.state)).toEqual(['connecting', 'connected', 'reconnecting', 'reconnecting', 'connected'])
+ expect(events.since(MachineId('m1')).events.some(event => event.stage === 'reconnect' && event.terminal === 'success')).toBe(true)
+ })
+
+ it('re-binds the same tunnel port across a drop reconnect', async () => {
+ const { manager, transport } = boot()
+ await manager.connect(MachineId('m1'))
+ transport.sessions[0]!.drop()
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-reconnect')
+ expect(transport.sessions[1]!.preferredTunnelPort).toBe(49152)
+ })
+
+ it('reports the next retry hint while reconnecting', async () => {
+ const { manager } = boot({
+ sessionFactory: () => new FakeSession(() => true, new Error('connect ECONNREFUSED')),
+ })
+ await expect(manager.connect(MachineId('m1'))).rejects.toThrow()
+ expect(manager.status(MachineId('m1')).state).toBe('reconnecting')
+ expect(manager.status(MachineId('m1')).nextRetryAt).toBeGreaterThan(Date.now() - 1)
+ await untilSettled(manager)
+ expect(manager.status(MachineId('m1')).nextRetryAt).toBeUndefined()
})
it('ignores session-close callbacks that no longer own the state', async () => {
@@ -552,7 +630,8 @@ describe('sshManager', () => {
const session = transport.sessions[0]!
session.tunnelCloseError = new Error('listener busy')
session.drop()
- expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-reconnect')
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
})
it('probes a machine with a remote banner', async () => {
@@ -635,8 +714,8 @@ describe('sshManager', () => {
it('rejects a mismatched host key (TOFU conflict)', async () => {
const { manager, transport } = boot()
await manager.connect(MachineId('m1'))
- transport.connect = async function (this: FakeTransport, _p: MachineProfile, verifier: (key: Buffer) => boolean | Promise<boolean>): Promise<SshSession> {
- const accepted = await verifier(Buffer.from('other-key'))
+ transport.connect = async function (this: FakeTransport, p: MachineProfile, verifier: (label: string, key: Buffer) => boolean | Promise<boolean>): Promise<SshSession> {
+ const accepted = await verifier(String(p.id), Buffer.from('other-key'))
if (!accepted)
throw new Error('Host key verification failed')
const session = new FakeSession(() => true)
@@ -679,7 +758,9 @@ describe('sshManager', () => {
await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
const status = manager.status(MachineId('m1'))
expect(status.dshMissing).toBe(true)
- expect(status.state).toBe('disconnected')
+ // A missing runtime is persistent: the machine lands in given-up (not
+ // the reconnect loop), freeing it for the install flow.
+ expect(status.state).toBe('given-up')
expect(status.lastError).toContain('REMOTE_NOT_INSTALLED')
})
@@ -694,16 +775,6 @@ describe('sshManager', () => {
})
describe('sshManager install', () => {
- /** Wait until the published state satisfies the predicate (auto-connect races). */
- async function until(predicate: () => boolean, label: string): Promise<void> {
- const deadline = Date.now() + 2000
- while (!predicate()) {
- if (Date.now() > deadline)
- throw new Error(`timed out waiting for ${label}`)
- await new Promise(resolve => setTimeout(resolve, 5))
- }
- }
-
it('installs dsh end-to-end, copies credentials, and auto-connects', async () => {
// Session 1 = install (platform probe, missing check, install script,
// entry check, credentials copy); session 2 = the automatic connect
@@ -957,9 +1028,10 @@ describe('sshManager install', () => {
it('fails loud with machine-connect-failed when the install connection fails', async () => {
const { manager } = boot({ rejectKeys: true })
await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ await untilSettled(manager)
const status = manager.status(MachineId('m1'))
- expect(status.state).toBe('disconnected')
- expect(status.lastError).toBe('auth failed')
+ expect(status.state).toBe('given-up')
+ expect(status.lastError).toBe('connect failed after 3 attempt(s): auth failed')
})
it('runs without an install timeout when the config omits it', async () => {
@@ -1193,10 +1265,12 @@ describe('sshManager install', () => {
const { manager, transport } = boot({ sessionFactory: factory, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(true)
- await until(() => transport.connectCalls === 2, 'auto-connect attempt')
+ // The auto-connect fails auth and its reconnect retries also fail: the
+ // machine settles in the given-up terminal state with the auth reason.
+ await until(() => manager.status(MachineId('m1')).state === 'given-up', 'auto-connect give-up')
const status = manager.status(MachineId('m1'))
- expect(status.state).toBe('disconnected')
- expect(status.lastError).toBe('auth failed')
+ expect(status.lastError).toContain('auth failed')
+ expect(transport.connectCalls).toBeGreaterThan(2)
})
it('reports a non-Error install failure in the status', async () => {
@@ -1216,3 +1290,268 @@ describe('sshManager install', () => {
expect(manager.status(MachineId('m1')).lastError).toBe('pnpm blew up')
})
})
+
+describe('sshManager reconnect', () => {
+ /** Retry budget with distinguishable, fake-timer-friendly delays. */
+ const fastRetry = { ...config, reconnectInitialDelayMs: 100, reconnectMaxDelayMs: 400, reconnectMaxAttempts: 3 }
+
+ /** Sessions whose transport connect always fails with ECONNREFUSED. */
+ const refused = (): FakeSession => new FakeSession(() => true, new Error('connect ECONNREFUSED 10.0.0.1:22'))
+
+ it('backs off exponentially, caps the delay, and gives up after the budget', async () => {
+ vi.useFakeTimers()
+ try {
+ const { manager, transport } = boot({ sessionFactory: refused, config: fastRetry })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ expect(manager.status(MachineId('m1')).state).toBe('reconnecting')
+ expect(transport.connectCalls).toBe(1)
+ // Retry 1 fires after the 100 ms initial delay — not before.
+ await vi.advanceTimersByTimeAsync(99)
+ expect(transport.connectCalls).toBe(1)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(transport.connectCalls).toBe(2)
+ // Retry 2 doubles to 200 ms.
+ await vi.advanceTimersByTimeAsync(199)
+ expect(transport.connectCalls).toBe(2)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(transport.connectCalls).toBe(3)
+ // Retry 3 caps at 400 ms.
+ await vi.advanceTimersByTimeAsync(399)
+ expect(transport.connectCalls).toBe(3)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(transport.connectCalls).toBe(4)
+ // Budget spent: the terminal given-up state with the summarized reason.
+ const status = manager.status(MachineId('m1'))
+ expect(status.state).toBe('given-up')
+ expect(status.lastError).toBe('connect failed after 4 attempt(s): connect ECONNREFUSED 10.0.0.1:22')
+ expect(status.nextRetryAt).toBeUndefined()
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('stops retrying after a manual disconnect', async () => {
+ vi.useFakeTimers()
+ try {
+ const { manager, transport } = boot({ sessionFactory: refused, config: fastRetry })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ await manager.disconnect(MachineId('m1'))
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(transport.connectCalls).toBe(1)
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('stops retrying when the machine profile vanishes', async () => {
+ vi.useFakeTimers()
+ try {
+ const { manager, transport } = boot({ sessionFactory: refused, config: fastRetry })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ manager.refreshProfiles(new Map())
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(transport.connectCalls).toBe(1)
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('refuses connect and install while reconnecting with a distinct code', async () => {
+ vi.useFakeTimers()
+ try {
+ const { manager } = boot({ sessionFactory: refused, config: fastRetry })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-reconnecting' })
+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-reconnecting' })
+ // 专用会话(sync 引擎入口)同样拒绝——与 connect/install 的在途一致
+ // 性语义对称,不并行建连。
+ await expect(manager.openSession(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-reconnecting' })
+ }
+ finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('uses the edited profile on the next retry', async () => {
+ // Real timers: the retry goes through TOFU file I/O, which the fake
+ // clock would not wait for.
+ let calls = 0
+ const factory = (): FakeSession => {
+ calls += 1
+ // The first connect fails; retries (after the profile edit) succeed.
+ return calls === 1 ? refused() : new FakeSession(() => true)
+ }
+ const { manager, transport } = boot({
+ sessionFactory: factory,
+ config: { ...config, reconnectInitialDelayMs: 5, reconnectMaxDelayMs: 10, reconnectMaxAttempts: 3 },
+ })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ // The operator fixes the profile mid-outage (e.g. a new password).
+ manager.refreshProfiles(new Map([[MachineId('m1'), { ...profile, host: '10.0.0.9' }], [secondProfile.id, secondProfile]]))
+ await until(() => manager.status(MachineId('m1')).state === 'connected', 'retry with edited profile')
+ expect(transport.profiles[1]?.host).toBe('10.0.0.9')
+ })
+
+ it('gives up without retrying when dsh is missing', async () => {
+ // The launch verdict REMOTE_NOT_INSTALLED is the merged flow's
+ // dsh-missing signal (the auto-bootstrap could not complete).
+ const session = new FakeSession(index => index !== 0)
+ session.startNotInstalled = true
+ const { manager, transport } = boot({ sessionFactory: () => session })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
+ expect(manager.status(MachineId('m1')).state).toBe('given-up')
+ expect(manager.status(MachineId('m1')).dshMissing).toBe(true)
+ expect(transport.connectCalls).toBe(1)
+ })
+
+ it('publishes the tunnel URL with the launch token when the remote log has one', async () => {
+ // 远端 web 日志带 token:隧道 URL 附带 ?token=(首次加载 mint 鉴权 cookie)
+ const { manager } = boot({
+ sessionFactory: () => {
+ const session = new FakeSession(() => true)
+ session.webTokenResult = 'tok-abc-123\n'
+ return session
+ },
+ })
+ const link = await manager.connect(MachineId('m1'))
+ expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
+ expect(manager.status(MachineId('m1')).tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
+ })
+
+ it('syncs bundled plugins before ensuring the instance (failure degrades, never blocks)', async () => {
+ const calls: string[] = []
+ const { manager } = boot({
+ syncPlugins: () => {
+ calls.push('sync')
+ return Promise.resolve(true)
+ },
+ })
+ const link = await manager.connect(MachineId('m1'))
+ expect(link.tunnelBaseUrl).toContain('http://127.0.0.1:')
+ expect(calls).toEqual(['sync'])
+ })
+
+ it('a plugin-sync failure degrades to the stock remote UI without failing the connect', async () => {
+ const { manager, events } = boot({
+ syncPlugins: () => Promise.reject(new Error('upload broke')),
+ })
+ const link = await manager.connect(MachineId('m1'))
+ expect(link.tunnelBaseUrl).toContain('http://127.0.0.1:')
+ const lines = events.since(MachineId('m1')).events.map(event => event.line)
+ expect(lines.some(line => line.includes('捆绑插件同步失败'))).toBe(true)
+ })
+
+ it('stamps the tunnel with the minted session cookie once the launch token resolves', async () => {
+ let mintedUrl = ''
+ const { manager, transport } = boot({
+ sessionFactory: () => {
+ const session = new FakeSession(() => true)
+ session.webTokenResult = 'tok-abc-123\n'
+ return session
+ },
+ mintCookie: (url) => {
+ mintedUrl = url
+ return Promise.resolve('dsh-auth-x=v1.signed')
+ },
+ })
+ const link = await manager.connect(MachineId('m1'))
+ // mint 走隧道自身的带 token URL;注入槽随后携带 Cookie(iframe 免登录)
+ expect(mintedUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
+ expect(transport.sessions[0]?.tunnelInjection?.cookie).toBe('dsh-auth-x=v1.signed')
+ expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
+ })
+
+ it('exits given-up on a fresh connect', async () => {
+ let fail = true
+ const factory = (): FakeSession => fail ? refused() : new FakeSession(() => true)
+ const { manager } = boot({ sessionFactory: factory })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-connect-failed' })
+ await untilSettled(manager)
+ expect(manager.status(MachineId('m1')).state).toBe('given-up')
+ fail = false
+ const link = await manager.connect(MachineId('m1'))
+ expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152')
+ expect(manager.status(MachineId('m1')).state).toBe('connected')
+ })
+
+ it('scrubs stored secrets from lastError, statuses, and events', async () => {
+ const leaky = (): FakeSession => new FakeSession(() => true, new Error('auth failed for password "sekrit"'))
+ const { manager, emits, events } = boot({ sessionFactory: leaky })
+ await expect(manager.connect(MachineId('m1'))).rejects.toThrow()
+ await untilSettled(manager)
+ expect(manager.status(MachineId('m1')).lastError).not.toContain('sekrit')
+ expect(manager.status(MachineId('m1')).lastError).toContain('***')
+ expect(JSON.stringify(manager.statuses())).not.toContain('sekrit')
+ expect(JSON.stringify(emits)).not.toContain('sekrit')
+ expect(JSON.stringify(events.since(MachineId('m1')))).not.toContain('sekrit')
+ })
+
+ it('emits auth and reconnect stage events across the give-up run', async () => {
+ const { manager, events } = boot({ sessionFactory: refused })
+ await expect(manager.connect(MachineId('m1'))).rejects.toThrow()
+ await untilSettled(manager)
+ const page = events.since(MachineId('m1'))
+ const stages = page.events.map(event => `${event.stage}${event.terminal === undefined ? '' : `:${event.terminal}`}`)
+ expect(stages.filter(stage => stage === 'auth')).toHaveLength(3)
+ expect(stages).toContain('reconnect:failed')
+ expect(page.events.at(-1)?.line).toContain('connect failed after 3 attempt(s)')
+ })
+
+ it('publishes the transient testing state around a probe', async () => {
+ const session = new FakeSession(() => true)
+ let markProbeStarted: (() => void) | undefined
+ const probeStarted = new Promise<void>((resolve) => {
+ markProbeStarted = resolve
+ })
+ session.exec = () => {
+ markProbeStarted?.()
+ return new Promise(resolve => setTimeout(resolve, 10, { code: 0, stdout: 'Linux x86_64', stderr: '' }))
+ }
+ const { manager } = boot({ sessionFactory: () => session })
+ const pending = manager.test(MachineId('m1'))
+ await probeStarted
+ expect(manager.status(MachineId('m1')).state).toBe('testing')
+ const result = await pending
+ expect(result).toEqual({ ok: true, banner: 'Linux x86_64' })
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ })
+
+ it('restores the given-up phase after a probe', async () => {
+ let fail = true
+ const factory = (): FakeSession => fail ? refused() : new FakeSession(() => true)
+ const { manager } = boot({ sessionFactory: factory })
+ await expect(manager.connect(MachineId('m1'))).rejects.toThrow()
+ await untilSettled(manager)
+ expect(manager.status(MachineId('m1')).state).toBe('given-up')
+ fail = false
+ const result = await manager.test(MachineId('m1'))
+ expect(result.ok).toBe(true)
+ expect(manager.status(MachineId('m1')).state).toBe('given-up')
+ })
+
+ it('does not let a probe restore a phase that changed underneath it', async () => {
+ const session = new FakeSession(() => true)
+ let releaseProbe: (() => void) | undefined
+ let markProbeStarted: (() => void) | undefined
+ const probeStarted = new Promise<void>((resolve) => {
+ markProbeStarted = resolve
+ })
+ session.exec = () => new Promise((resolve) => {
+ markProbeStarted?.()
+ releaseProbe = () => resolve({ code: 0, stdout: 'Linux x86_64', stderr: '' })
+ })
+ const { manager } = boot({ sessionFactory: () => session })
+ const pending = manager.test(MachineId('m1'))
+ await probeStarted
+ // A disconnect takes ownership while the probe still runs.
+ await manager.disconnect(MachineId('m1'))
+ releaseProbe!()
+ await pending
+ expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.ts
index b5ac7a26..2e9cf000 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts
@@ -1,24 +1,27 @@
import type { Buffer } from 'node:buffer'
import type { Config } from '../storage/index'
/**
- * Per-machine connection manager: profile map, the disconnected/connecting/
- * connected state machine, TOFU host-key gating, remote-instance assurance,
- * and the tunnel lifecycle. Transport-agnostic — tests inject a fake
- * transport and never touch the network.
+ * Per-machine connection manager: profile map, the connection state machine
+ * (disconnected/testing/connecting/connected/reconnecting/given-up), TOFU
+ * host-key gating, remote-instance assurance, the tunnel lifecycle, and the
+ * watchdog-driven reconnect loop (exponential backoff, tunnel rebuild).
+ * Transport-agnostic — tests inject a fake transport and never touch the
+ * network.
* @module dsh-tauri-ssh/host/service/manager
*/
-import type { MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshTestResult } from '../types/index'
+import type { MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStage, SshMachineStatus, SshProgress, SshTestResult } from '../types/index'
import type { BootstrapHooks } from './bootstrap'
import type { SshMachineEvents } from './events'
import type { KnownHostsStore } from './host-keys'
-import type { SshSession, SshTransport, SshTunnelHandle } from './transport'
+import type { SshSession, SshTransport, SshTunnelHandle, TunnelHeaderInjection } from './transport'
import { homedir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
import { MachineId, SshError } from '../types/index'
-import { checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, remoteWebTokenCommand, runInstallScript, skippedVerificationSummary } from './bootstrap'
+import { checkMissingCommand, credentialsCopyCommand, describeError, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, remoteWebTokenCommand, runInstallScript, skippedVerificationSummary } from './bootstrap'
import { fingerprintHostKey } from './host-keys'
+import { syncBundledPlugins } from './plugins-sync'
import { mintTunnelCookie } from './transport'
/** One machine's live connection state. */
@@ -26,7 +29,7 @@ interface MachineState {
/** Monotonic attempt counter; a disconnect invalidates in-flight connects. */
generation: number
/** Published connection phase; the status source of truth. */
- phase: 'disconnected' | 'connecting' | 'connected'
+ phase: 'disconnected' | 'testing' | 'connecting' | 'connected' | 'reconnecting' | 'given-up'
/** In-flight connect promise; concurrent connects share it. */
connecting?: Promise<SshLink>
/** In-flight install promise; concurrent installs share it. */
@@ -43,6 +46,26 @@ interface MachineState {
dshMissing?: boolean
/** Live progress of the in-flight operation. */
progress?: SshProgress
+ /** The active reconnect loop, while one owns the machine. */
+ reconnect?: ReconnectState
+ /** Local port to prefer when (re)binding the tunnel, keeping the URL stable. */
+ preferredTunnelPort?: number
+ /** Which credential the live (or last successful) connection used. */
+ authMethod?: SshSession['authMethod']
+}
+
+/** The background reconnect loop's bookkeeping. */
+interface ReconnectState {
+ /** Generation this loop belongs to; a disconnect invalidates it. */
+ generation: number
+ /** Number of the retry that runs next, 1-based; exceeds the budget → give up. */
+ attempt: number
+ /** Epoch ms when the scheduled retry fires; absent while a retry is in flight. */
+ nextRetryAt?: number
+ /** The pending retry timer; a disconnect clears it. */
+ timer?: NodeJS.Timeout
+ /** Redacted reason of every failed attempt so far, first attempt included. */
+ reasons: string[]
}
/** Manager dependencies (all transport seams injectable for tests). */
@@ -58,6 +81,18 @@ export interface SshManagerDeps {
emitStatus: (machineId: MachineId, status: SshMachineStatus) => void
/** Local dsh `.env` credentials to copy after an install (defaults to the host's own). */
readEnvCredentials?: () => ReturnType<typeof readEnvCredentials>
+ /**
+ * Mint the tunnel's session cookie: one local GET of the authenticated URL
+ * (no redirect follow), resolving the `name=value` pair from `set-cookie`.
+ * Defaults to the node:http implementation; tests stub it to stay offline.
+ */
+ mintCookie?: (authenticatedUrl: string) => Promise<string | undefined>
+ /**
+ * Sync the desktop-bundled plugins to the remote (defaults to the real
+ * tarball pipeline; tests stub it to stay offline). Returns whether the
+ * remote was modified (a running instance gets restarted by the sync).
+ */
+ syncPlugins?: (session: SshSession, hooks: { onEvent?: (stage: SshMachineStage, line: string) => void }) => Promise<boolean>
}
/** The sentinel rethrown when an in-flight attempt loses to a disconnect. */
@@ -111,6 +146,8 @@ export class SshManager {
const state = this.states.get(machineId)
const lastError = state?.lastError
const progress = state?.progress
+ const nextRetryAt = state?.reconnect?.nextRetryAt
+ const authMethod = state?.authMethod
return {
machineId,
state: state?.phase ?? 'disconnected',
@@ -118,6 +155,8 @@ export class SshManager {
...lastError === undefined ? {} : { lastError },
...state?.dshMissing === true ? { dshMissing: true } : {},
...progress === undefined ? {} : { progress },
+ ...nextRetryAt === undefined ? {} : { nextRetryAt },
+ ...authMethod === undefined ? {} : { authMethod },
}
}
@@ -128,7 +167,10 @@ export class SshManager {
/**
* One-shot probe: authenticate, run `uname -srm`, close. Never starts the
- * remote instance and never leaves a connection behind.
+ * remote instance and never leaves a connection behind. Publishes the
+ * transient `testing` state for the probe's duration, then restores the
+ * phase it found (unless something else transitioned the machine in the
+ * meantime — reconnects and disconnects own their transitions).
* @param machineId - the machine to probe.
* @param signal - aborts the probe.
* @returns the probe outcome.
@@ -137,19 +179,28 @@ export class SshManager {
async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {
const profile = this.requireProfile(machineId)
const state = this.ensureState(machineId)
+ const previousPhase = state.phase
+ state.phase = 'testing'
state.progress = { phase: 'handshake' }
this.emit(machineId)
+ const restore = (): void => {
+ const current = this.states.get(machineId)
+ // Only test() ever sets `testing`, so a different phase means another
+ // transition (drop, reconnect, disconnect) took ownership meanwhile.
+ if (current === state && current.phase === 'testing') {
+ current.phase = previousPhase === 'testing' ? 'disconnected' : previousPhase
+ delete current.progress
+ }
+ this.emit(machineId)
+ }
let session: SshSession
try {
session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
}
catch (error) {
- delete state.progress
- this.emit(machineId)
- return { ok: false, message: describeSshFailure(error) }
+ restore()
+ return { ok: false, message: this.redacted(machineId, describeSshFailure(error)) }
}
- delete state.progress
- this.emit(machineId)
try {
const result = await session.exec('uname -srm')
if (result.code !== 0) {
@@ -158,36 +209,58 @@ export class SshManager {
return { ok: true, banner: result.stdout.trim() }
}
catch (error) {
- return { ok: false, message: describeSshFailure(error) }
+ return { ok: false, message: this.redacted(machineId, describeSshFailure(error)) }
}
finally {
+ restore()
await session.close()
}
}
/**
* Establish (or reuse) the machine link: SSH connection, remote-instance
- * assurance, and the local tunnel. Idempotent.
+ * assurance, and the local tunnel. Idempotent. A failed attempt hands the
+ * machine to the background reconnect loop (the caller sees the failure;
+ * the loop keeps retrying with exponential backoff and either reconnects
+ * or lands in the `given-up` terminal state).
* @param machineId - the machine to connect.
* @param signal - aborts the connection attempt.
* @returns the live link.
- * @throws {SshError} on any failure.
+ * @throws {SshError} on any failure, or `machine-reconnecting` while the
+ * reconnect loop owns the machine.
*/
async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {
const profile = this.requireProfile(machineId)
const state = this.ensureState(machineId)
if (state.link !== undefined)
return state.link
+ this.refuseWhileReconnecting(machineId, state)
if (state.connecting === undefined) {
state.phase = 'connecting'
+ delete state.lastError
+ delete state.dshMissing
state.progress = { phase: 'handshake' }
this.emit(machineId)
+ const generation = state.generation
const attempt = this.performConnect(machineId, profile, signal)
state.connecting = attempt.finally(() => {
// The slot is only ever replaced while undefined, so the settling
// attempt always owns it at this point.
delete this.states.get(machineId)?.connecting
})
+ // The caller sees the first failure; the reconnect loop keeps trying
+ // in the background (unless the failure is persistent dsh-missing or
+ // a disconnect superseded the attempt).
+ void attempt.catch((error) => {
+ const current = this.states.get(machineId)
+ if (current === undefined || current.generation !== generation)
+ return
+ if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
+ this.giveUp(machineId, current)
+ return
+ }
+ this.beginReconnect(machineId)
+ })
}
return state.connecting
}
@@ -213,9 +286,9 @@ export class SshManager {
}
/**
- * Tear down one machine's link, invalidating any in-flight connect.
- * Idempotent for an absent link; unknown ids resolve without writing
- * anything.
+ * Tear down one machine's link, invalidating any in-flight connect and any
+ * running reconnect loop. Idempotent for an absent link; unknown ids
+ * resolve without writing anything.
* @param machineId - the machine to disconnect.
*/
async disconnect(machineId: MachineId): Promise<void> {
@@ -223,6 +296,7 @@ export class SshManager {
if (state === undefined)
return
state.generation += 1
+ this.stopReconnect(state)
delete state.lastError
delete state.dshMissing
delete state.progress
@@ -301,7 +375,9 @@ export class SshManager {
* The bootstrap event stream likewise settles on every failure (its own
* settling events, or the catch for transport exceptions that bypass
* them), except a superseded attempt: cancellation by an explicit
- * disconnect is the documented no-terminal case.
+ * disconnect is the documented no-terminal case. Failures record the
+ * (redacted, auth-stage) reason — the caller decides whether the reconnect
+ * loop takes over.
*/
private async performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshLink> {
const state = this.ensureState(machineId)
@@ -322,13 +398,29 @@ export class SshManager {
session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
}
catch (error) {
+ // The locally captured, redacted message: a superseded attempt must
+ // not read state.lastError back — that slot may already belong to a
+ // newer try.
+ const message = this.redacted(machineId, describeSshFailure(error))
if (generation === state.generation) {
delete state.progress
- state.lastError = describeSshFailure(error)
- state.phase = 'disconnected'
- this.emit(machineId)
+ this.noteConnectFailure(machineId, message)
}
- throw new SshError('machine-connect-failed', machineId, describeSshFailure(error))
+ throw new SshError('machine-connect-failed', machineId, message)
+ }
+ // 桌面捆绑插件随远端实例走(远端窗口与本体唯一区别=后端):树变化时
+ // 上传并重启实例,随后的 ensure 按新 profile 拉起。best-effort:同步
+ // 失败降级为原生远端 UI,连接本身不受影响。
+ try {
+ await (this.deps.syncPlugins ?? syncBundledPlugins)(session, {
+ onEvent: (stage, line) => {
+ if (generation === state.generation)
+ this.deps.events.append(machineId, stage, line)
+ },
+ })
+ }
+ catch (error) {
+ this.deps.events.append(machineId, 'install', `捆绑插件同步失败(降级原生 UI): ${describeError(error)}`)
}
try {
await ensureRemoteInstance(
@@ -351,7 +443,12 @@ export class SshManager {
},
this.deps.planInstall,
)
- const tunnel = await session.openTunnel(profile.remotePort)
+ // Prefer the previously published tunnel port so a reconnect keeps
+ // the machine's URL stable for consumers (falls back to ephemeral).
+ // Cookie 注入槽先挂上:隧道一旦发布即可服务;mint 落定后每条连接
+ // 自动带 Cookie( mint 前的纯裸管阶段只发生在发布前,外部不可见)。
+ const injection: TunnelHeaderInjection = { cookie: undefined }
+ const tunnel = await session.openTunnel(profile.remotePort, state.preferredTunnelPort, injection)
// A disconnect that landed anywhere above (bootstrap, tunnel opening)
// must not publish a link; tear the tunnel down and abort the attempt.
if (generation !== state.generation) {
@@ -362,29 +459,56 @@ export class SshManager {
// 该 authority 的鉴权 cookie(303 → /),壳层 iframe 与新窗口免登录;
// 读不到(实例非本插件拉起/日志无记录)退化为裸 URL(401 页自行呈现)。
const webToken = await this.readRemoteWebToken(session)
+ // 会话 cookie 是 SameSite=Strict:iframe 第三方上下文存不下也发不出
+ // (壳层内嵌 401 的根因)——隧道自注 Cookie 才是不挑嵌入上下文的解法;
+ // URL 同时保留 ?token=(顶层导航的新窗口/浏览器自举用)。
+ if (webToken !== undefined) {
+ const mint = this.deps.mintCookie ?? mintTunnelCookie
+ injection.cookie = await mint(`http://127.0.0.1:${tunnel.localPort}/?token=${webToken}`)
+ }
const link: SshLink = {
machineId,
tunnelBaseUrl: `http://127.0.0.1:${tunnel.localPort}${webToken === undefined ? '' : `/?token=${webToken}`}`,
}
+ const reconnected = state.reconnect !== undefined ? state.reconnect.reasons.length : undefined
state.session = session
state.tunnel = tunnel
state.link = link
+ state.preferredTunnelPort = tunnel.localPort
+ state.authMethod = session.authMethod
delete state.progress
+ this.stopReconnect(state)
state.phase = 'connected'
session.onClosed(() => {
const current = this.states.get(machineId)
if (current?.session !== session)
return
- current.lastError = 'SSH connection closed'
+ // The established connection dropped (server went away, network,
+ // keepalive watchdog): hand the machine to the reconnect loop.
const tunnel = current.tunnel
delete current.session
delete current.tunnel
delete current.link
- current.phase = 'disconnected'
+ delete current.progress
void tunnel?.close().catch(() => undefined)
- this.emit(machineId)
+ current.lastError = 'SSH connection closed'
+ this.beginReconnect(machineId)
})
this.emit(machineId)
+ this.deps.events.append(
+ machineId,
+ 'auth',
+ this.redacted(machineId, `connected to ${profile.host}${session.authMethod === undefined ? '' : ` (auth: ${session.authMethod})`}`),
+ { terminal: 'success' },
+ )
+ if (reconnected !== undefined) {
+ this.deps.events.append(
+ machineId,
+ 'reconnect',
+ this.redacted(machineId, `reconnected to ${profile.host} after ${reconnected} failed attempt(s)`),
+ { terminal: 'success' },
+ )
+ }
return link
}
catch (error) {
@@ -396,36 +520,192 @@ export class SshManager {
// state.lastError back — that slot may already belong to a newer try.
const message = error instanceof Error ? error.message : String(error)
if (generation === state.generation && !bootstrapSettled) {
- onEvent('failed', 'bootstrap 失败', { terminal: 'failed', reason: message })
+ onEvent('failed', 'bootstrap 失败', { terminal: 'failed', reason: this.redacted(machineId, message) })
}
if (generation === state.generation) {
delete state.progress
- state.lastError = message
- // The start script's own "not installed" verdict keeps the UI's
- // install hint alive (the auto-bootstrap could not complete).
- if (message.includes('REMOTE_NOT_INSTALLED'))
- state.dshMissing = true
+ this.noteConnectFailure(machineId, message)
state.phase = 'disconnected'
this.emit(machineId)
}
- throw new SshError('machine-bootstrap-failed', machineId, message)
+ throw new SshError('machine-bootstrap-failed', machineId, this.redacted(machineId, message))
+ }
+ }
+
+ /**
+ * Record one failed connection attempt: redacted `lastError`, the
+ * dsh-missing marker, and an `auth`-stage event line on the machine event
+ * channel. Never publishes the phase — the caller owns that transition.
+ */
+ private noteConnectFailure(machineId: MachineId, message: string): void {
+ const state = this.states.get(machineId)
+ if (state === undefined)
+ return
+ const redactedMessage = this.redacted(machineId, message)
+ state.lastError = redactedMessage
+ // The start script's own "not installed" verdict keeps the UI's install
+ // hint alive (the auto-bootstrap could not complete).
+ if (message.includes('REMOTE_NOT_INSTALLED'))
+ state.dshMissing = true
+ this.deps.events.append(machineId, 'auth', redactedMessage)
+ }
+
+ /**
+ * Hand one machine to the reconnect loop after its first failed attempt
+ * (user connect, install connect, or a dropped established connection).
+ * Idempotent — a machine already owned by a loop stays on its schedule.
+ */
+ private beginReconnect(machineId: MachineId): void {
+ const state = this.ensureState(machineId)
+ if (state.reconnect !== undefined)
+ return
+ state.reconnect = {
+ generation: state.generation,
+ attempt: 0,
+ reasons: [state.lastError ?? 'connection failed'],
+ }
+ this.scheduleReconnect(machineId)
+ }
+
+ /**
+ * Schedule the loop's next retry (or give up when the budget is spent):
+ * exponential backoff from the configured initial delay, capped at the
+ * configured ceiling. Publishes the `reconnecting` phase with the retry
+ * hint each time the schedule changes.
+ */
+ private scheduleReconnect(machineId: MachineId): void {
+ const state = this.states.get(machineId)
+ const rec = state?.reconnect
+ if (state === undefined || rec === undefined)
+ return
+ rec.attempt += 1
+ if (rec.attempt > this.deps.config.reconnectMaxAttempts) {
+ this.giveUp(machineId, state)
+ return
+ }
+ const base = this.deps.config.reconnectInitialDelayMs
+ const ceiling = this.deps.config.reconnectMaxDelayMs
+ const delay = Math.min(base * 2 ** (rec.attempt - 1), ceiling)
+ rec.nextRetryAt = Date.now() + delay
+ state.phase = 'reconnecting'
+ delete state.progress
+ this.emit(machineId)
+ this.deps.events.append(
+ machineId,
+ 'reconnect',
+ this.redacted(machineId, `retrying in ${Math.round(delay / 100) / 10} s (attempt ${rec.attempt} of ${this.deps.config.reconnectMaxAttempts})`),
+ )
+ rec.timer = setTimeout(() => {
+ void this.attemptReconnect(machineId)
+ }, delay)
+ // A pending retry must never hold the host process open on its own.
+ rec.timer.unref?.()
+ }
+
+ /**
+ * One background reconnect attempt: re-reads the live profile (an edit
+ * during the outage — e.g. a fixed password — applies on the next retry)
+ * and stops silently when a disconnect superseded the loop.
+ */
+ private async attemptReconnect(machineId: MachineId): Promise<void> {
+ const state = this.states.get(machineId)
+ const rec = state?.reconnect
+ if (state === undefined || rec === undefined || rec.generation !== state.generation)
+ return
+ const profile = this.profiles.get(machineId)
+ if (profile === undefined)
+ return
+ delete rec.nextRetryAt
+ state.progress = { phase: 'handshake' }
+ this.emit(machineId)
+ try {
+ await this.performConnect(machineId, profile)
+ // performConnect published `connected`, cleared the loop, and emitted
+ // the success events.
+ }
+ catch (error) {
+ if (error instanceof AttemptCancelled)
+ return
+ const current = this.states.get(machineId)
+ const loop = current?.reconnect
+ if (current === undefined || loop === undefined || loop.generation !== current.generation)
+ return
+ if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
+ // A missing dsh runtime is persistent — retrying cannot fix it, and
+ // the given-up state frees the machine for the install flow.
+ this.giveUp(machineId, current)
+ return
+ }
+ loop.reasons.push(current.lastError ?? describeSshFailure(error))
+ this.scheduleReconnect(machineId)
}
}
+ /**
+ * Land one machine in the `given-up` terminal state: summarized failure
+ * reason, loop cleared, terminal event emitted. A fresh `connect` exits it.
+ */
+ private giveUp(machineId: MachineId, state: MachineState): void {
+ const rec = state.reconnect
+ this.stopReconnect(state)
+ delete state.progress
+ state.phase = 'given-up'
+ const last = rec?.reasons[rec.reasons.length - 1] ?? state.lastError ?? 'connection failed'
+ state.lastError = rec === undefined
+ ? this.redacted(machineId, last)
+ : this.redacted(machineId, `connect failed after ${rec.reasons.length} attempt(s): ${last}`)
+ this.emit(machineId)
+ this.deps.events.append(machineId, 'reconnect', state.lastError, { terminal: 'failed', reason: state.lastError })
+ }
+
+ /** Clear one machine's reconnect loop (timer and bookkeeping). */
+ private stopReconnect(state: MachineState): void {
+ if (state.reconnect?.timer !== undefined)
+ clearTimeout(state.reconnect.timer)
+ delete state.reconnect
+ }
+
+ /** @throws {SshError} `machine-reconnecting` while the reconnect loop owns the machine. */
+ private refuseWhileReconnecting(machineId: MachineId, state: MachineState): void {
+ const rec = state.reconnect
+ if (rec === undefined)
+ return
+ throw new SshError(
+ 'machine-reconnecting',
+ machineId,
+ `machine is reconnecting (attempt ${rec.attempt} of ${this.deps.config.reconnectMaxAttempts}); `
+ + 'wait for the automatic retry or disconnect first',
+ )
+ }
+
+ /** Scrub the profile's secret values out of any operator-facing text. */
+ private redacted(machineId: MachineId, text: string): string {
+ const profile = this.profiles.get(machineId)
+ let out = text
+ for (const secret of [profile?.password, profile?.passphrase]) {
+ if (secret !== undefined && secret !== '')
+ out = out.replaceAll(secret, '***')
+ }
+ return out
+ }
+
/**
* One-shot remote dsh install (binary distribution): authenticate, probe
* the platform, download/verify/install the missing runtime components
* from the pinned release, copy the local API credentials into the remote
* `~/.dsh/.env`, then hand off to {@link connect} automatically.
- * Idempotent while in flight.
+ * Idempotent while in flight. Refused while the reconnect loop owns the
+ * machine.
* @param machineId - the machine to install on.
* @param signal - aborts the attempt.
* @returns the install outcome.
- * @throws {SshError} on any failure (connect, install, or probe).
+ * @throws {SshError} on any failure (connect, install, or probe), or
+ * `machine-reconnecting` while reconnecting.
*/
async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {
const profile = this.requireProfile(machineId)
const state = this.ensureState(machineId)
+ this.refuseWhileReconnecting(machineId, state)
if (state.installing === undefined) {
state.progress = { phase: 'installing' }
this.emit(machineId)
@@ -447,7 +727,8 @@ export class SshManager {
* terminal event, or the catch for exception failures (probe, planner,
* transport rejects, missing entry) that bypass it. A superseded attempt
* (cancellation by an explicit disconnect) is the documented no-terminal
- * case.
+ * case. A failed install connection hands the machine to the reconnect
+ * loop, like a failed connect.
*/
private async performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {
const state = this.ensureState(machineId)
@@ -467,13 +748,16 @@ export class SshManager {
session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
}
catch (error) {
+ // The locally captured, redacted message: a superseded attempt must
+ // not read state.lastError back — that slot may already belong to a
+ // newer try.
+ const message = this.redacted(machineId, describeSshFailure(error))
if (generation === state.generation) {
delete state.progress
- state.lastError = describeSshFailure(error)
- state.phase = 'disconnected'
- this.emit(machineId)
+ this.noteConnectFailure(machineId, message)
+ this.beginReconnect(machineId)
}
- throw new SshError('machine-connect-failed', machineId, describeSshFailure(error))
+ throw new SshError('machine-connect-failed', machineId, message)
}
try {
const installTimeoutMs = this.deps.config.installTimeoutMs
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
index fcb4e10c..124b9d39 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
@@ -75,11 +75,11 @@ describe('buildPreview', () => {
})
describe('command builders', () => {
- it('quotes the dsh path and the spec on the add command', () => {
- expect(pluginAddCommand('/home/u/.local/bin/dsh', 'github:a/b'))
- .toBe(`'/home/u/.local/bin/dsh' plugin --profile web add 'github:a/b'`)
- expect(pluginAddCommand('dsh', 'pkg@^1.0.0'))
- .toBe(`'dsh' plugin --profile web add 'pkg@^1.0.0'`)
+ it('runs the layout entry under the layout node, both quoted', () => {
+ expect(pluginAddCommand('/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js', 'github:a/b'))
+ .toBe(`"$HOME/.dsh-desktop/runtime/bin/node" '/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js' plugin --profile web add 'github:a/b'`)
+ expect(pluginAddCommand('/home/u/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', 'pkg@^1.0.0'))
+ .toBe(`"$HOME/.dsh-desktop/runtime/bin/node" '/home/u/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js' plugin --profile web add 'pkg@^1.0.0'`)
})
it('extracts the streamed tarball into the remote skill home', () => {
@@ -92,8 +92,9 @@ describe('syncEngine.apply', () => {
it('returns per-item successes when everything lands', async () => {
const session = fakeSession((command) => {
- if (command.includes('command -v dsh'))
- return ok('/home/u/.local/bin/dsh\n')
+ // The entry probe is the only command carrying a printf.
+ if (command.includes('printf'))
+ return ok('/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js\n')
return ok()
})
const packSkills = vi.fn(async () => Buffer.from('TARDATA'))
@@ -119,8 +120,8 @@ describe('syncEngine.apply', () => {
it('reports partial plugin failures per item with the output tail', async () => {
const session = fakeSession((command) => {
- if (command.includes('command -v dsh'))
- return ok('/home/u/.local/bin/dsh\n')
+ if (command.includes('printf'))
+ return ok('/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js\n')
return command.includes('bad-pkg') ? fail('ERR_PNPM_NO_MATCH') : ok()
})
const sync = new SyncEngine({
@@ -142,7 +143,7 @@ describe('syncEngine.apply', () => {
expect(result.items[1]?.error).toContain('exit 1')
})
- it('fails every plugin item when the remote has no dsh binary', async () => {
+ it('fails every plugin item when the remote has no dsh entry', async () => {
const session = fakeSession(() => ok('\n'))
const sync = new SyncEngine({
profileDependencies: () => ({}),
@@ -152,7 +153,7 @@ describe('syncEngine.apply', () => {
})
const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [])
expect(result.items).toHaveLength(1)
- expect(result.items[0]).toMatchObject({ ok: false, error: expect.stringContaining('no dsh binary') })
+ expect(result.items[0]).toMatchObject({ ok: false, error: expect.stringContaining('no dsh entry') })
})
it('marks unknown skills and local pack failures without touching the remote', async () => {
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-ssh/src/host/service/sync.ts
index b86e0a31..4648c60d 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.ts
@@ -13,10 +13,10 @@
*/
import type { Buffer } from 'node:buffer'
-import type { MachineId, SyncApplyResult, SyncItemResult, SyncPluginItem, SyncPluginRef, SyncPreview, SyncSkillItem, SyncSkillRef, SyncSkillRoot } from '../types/index.js'
-import type { SshSession } from './transport.js'
-import { firstLineOf, probeDshCommand } from './bootstrap.js'
-import { shQuote } from './transport.js'
+import type { MachineId, SyncApplyResult, SyncItemResult, SyncPluginItem, SyncPluginRef, SyncPreview, SyncSkillItem, SyncSkillRef, SyncSkillRoot } from '../types/index'
+import type { SshSession } from './transport'
+import { dshEntryProbeCommand, firstLineOf, layoutNodeBinary } from './bootstrap'
+import { shQuote } from './transport'
/** The remote profile plugins are installed into (the web-serving one). */
export const REMOTE_PLUGIN_PROFILE = 'web'
@@ -69,9 +69,16 @@ export function buildPreview(dependencies: Record<string, string>, skillRoots: R
return { plugins, skills }
}
-/** The remote plugin-install command for one spec (dsh add is pnpm-backed). */
-export function pluginAddCommand(dshPath: string, spec: string): string {
- return `${shQuote(dshPath)} plugin --profile ${REMOTE_PLUGIN_PROFILE} add ${shQuote(spec)}`
+/**
+ * The remote plugin-install command for one spec (dsh add is pnpm-backed).
+ * The dsh entry is a Node script in the binary layout, so it always runs
+ * under the layout's Node binary (never a bare `dsh` from the login PATH).
+ * @param dshEntry - the absolute entry path the layout probe resolved.
+ * @param spec - the dependency spec to install.
+ * @returns the shell command line.
+ */
+export function pluginAddCommand(dshEntry: string, spec: string): string {
+ return `${layoutNodeBinary()} ${shQuote(dshEntry)} plugin --profile ${REMOTE_PLUGIN_PROFILE} add ${shQuote(spec)}`
}
/** The remote skill-extract command; the tarball arrives on its stdin. */
@@ -146,18 +153,18 @@ export class SyncEngine {
private async applyPlugins(session: SshSession, plugins: readonly SyncPluginRef[], items: SyncItemResult[]): Promise<void> {
if (plugins.length === 0)
return
- const dshPath = firstLineOf((await session.exec(probeDshCommand())).stdout)
+ const dshEntry = firstLineOf((await session.exec(dshEntryProbeCommand())).stdout)
for (const plugin of plugins) {
- if (dshPath === '') {
+ if (dshEntry === '') {
items.push({
kind: 'plugin',
name: plugin.name,
ok: false,
- error: 'no dsh binary on the remote (checked the login PATH, ~/.local/bin and ~/.dsh/source/current); install dsh first',
+ error: 'no dsh entry under the remote ~/.dsh-desktop install layout; run the machine install first',
})
continue
}
- const result = await session.exec(pluginAddCommand(dshPath, plugin.spec), {
+ const result = await session.exec(pluginAddCommand(dshEntry, plugin.spec), {
...this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs },
})
items.push(
diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.ts
index c93bfaaf..9d293d68 100644
--- a/packages/dsh-tauri-ssh/src/host/types/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts
@@ -165,7 +165,11 @@ export type SshTestResult
= | { ok: true, banner: string }
| { ok: false, message: string }
-/** One bootstrap stage of the remote-instance assurance pipeline (S3 adds the connection-lifecycle stages on the same channel). */
+/**
+ * One stage of the machine event channel: S2's bootstrap pipeline stages
+ * plus S3's connection-lifecycle stages (`auth`/`reconnect`, declared by
+ * {@link SSH_CONNECTION_EVENT_STAGES} on the same channel).
+ */
export type SshMachineStage
= | 'probe'
| 'download'
@@ -174,6 +178,8 @@ export type SshMachineStage
| 'launch'
| 'ready'
| 'failed'
+ | 'auth'
+ | 'reconnect'
/** Terminal verdict of a machine event, when it settles an operation. */
export type SshMachineTerminal = 'success' | 'failed'
@@ -232,38 +238,75 @@ export type SshErrorCode
| 'machine-install-failed'
| 'machine-ssh-error'
| 'machine-reconnecting'
+ | 'machine-sync-failed'
/**
* Connection-lifecycle stages this plugin feeds into the machine-level event
* channel (C-EVENT). The channel itself — `/api-ssh` `machine.events` — is
- * owned by S2; these are the stages S3 appends to its stage enum, so the
- * merged vocabulary is S2's bootstrap stages plus `auth` and `reconnect`.
+ * owned by S2; this constant declares S3's augmentation of
+ * {@link SshMachineStage}, and the `satisfies` clause keeps it checked
+ * against the merged union (adding a stage here requires it on the union).
*/
-export const SSH_CONNECTION_EVENT_STAGES = ['auth', 'reconnect'] as const
+export const SSH_CONNECTION_EVENT_STAGES = ['auth', 'reconnect'] as const satisfies readonly SshMachineStage[]
/** One connection-lifecycle stage of the machine event channel (S3's slice). */
export type SshConnectionEventStage = typeof SSH_CONNECTION_EVENT_STAGES[number]
-/**
- * One machine event: a displayable, secret-free line on the machine's log
- * stream. `outcome` marks the line that closes a lifecycle run.
- */
-export interface SshMachineEvent {
- machineId: MachineId
- stage: SshConnectionEventStage
- /** Operator-facing text line; never carries secret values. */
- text: string
- /** Terminal outcome, present on the line that closes a run. */
- outcome?: 'success' | 'failure'
+/** Label of one local user-level skill root the sync scans. */
+export type SyncSkillRoot = 'dsh' | 'agents'
+
+/** One plugin sync candidate: a dependency of the local dsh profile. */
+export interface SyncPluginItem {
+ /** Package name as the profile's package.json spells it. */
+ name: string
+ /** The dependency spec to install on the remote (e.g. `github:org/repo`, `^1.2.0`). */
+ spec: string
+ /** Whether the spec can be installed on a remote at all. */
+ syncable: boolean
+ /** Operator-facing reason a non-syncable spec is excluded. */
+ reason?: string
}
-/**
- * Pluggable sink for {@link SshMachineEvent}s — the seam where the event
- * routing lands. Today the default sink is a no-op; when S2's `machine.events`
- * channel merges, the plugin assembly wires a sink that forwards into it.
- */
-export interface SshMachineEventSink {
- emit: (event: SshMachineEvent) => void
+/** One skill sync candidate: a SKILL.md directory under a user-level root. */
+export interface SyncSkillItem {
+ name: string
+ /** The local root the skill was found under. */
+ root: SyncSkillRoot
+}
+
+/** The `sync.preview` value: what the panel offers for selection. */
+export interface SyncPreview {
+ plugins: SyncPluginItem[]
+ skills: SyncSkillItem[]
+}
+
+/** One plugin the panel asked to sync, as `sync.apply` receives it. */
+export interface SyncPluginRef {
+ name: string
+ spec: string
+}
+
+/** One skill the panel asked to sync, as `sync.apply` receives it. */
+export interface SyncSkillRef {
+ name: string
+ root: SyncSkillRoot
+}
+
+/** Outcome of exactly one synced item — the per-item failure surface. */
+export interface SyncItemResult {
+ kind: 'plugin' | 'skill'
+ /** Display identity, matching the ref the panel sent. */
+ name: string
+ /** Skill root; plugins carry none. */
+ root?: SyncSkillRoot
+ ok: boolean
+ /** Operator-facing failure description; absent on success. */
+ error?: string
+}
+
+/** The `sync.apply` value: every requested item, success and failure alike. */
+export interface SyncApplyResult {
+ items: SyncItemResult[]
}
/** Typed failure thrown by ssh primitives so consumers map business codes without string matching. */
diff --git a/src/hooks/use-remote-machines.ts b/src/hooks/use-remote-machines.ts
index 8267668b..c5a135df 100644
--- a/src/hooks/use-remote-machines.ts
+++ b/src/hooks/use-remote-machines.ts
@@ -1,5 +1,6 @@
import { useEventListener, useMount } from '@reause/core'
import { getCurrentWindow } from '@tauri-apps/api/window'
+import { useRef } from 'react'
import { store } from '@/store'
/** 远端弹窗 label 前缀(与 rust remote_open_window 的窗口命名一致)。 */
@@ -37,5 +38,5 @@ export function useRemoteMachines(): void {
}
useEventListener('focus', refreshNow)
- useEventListener(document, 'visibilitychange', refreshNow)
+ useEventListener(useRef(document), 'visibilitychange', refreshNow)
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 646329b6..6ed5e7cd 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -411,5 +411,6 @@
"remote.manager.disconnect": "Disconnect",
"remote.manager.test": "Test",
"remote.manager.empty": "No remote machines yet. Click \"Add machine\" to create one.",
- "buttons.close": "Close"
+ "buttons.close": "Close",
+ "remote.loading": "Loading remote interface…"
}
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 9805afc8..75088184 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -411,5 +411,6 @@
"remote.manager.disconnect": "断开",
"remote.manager.test": "测试",
"remote.manager.empty": "还没有远端机器,点「添加机器」创建第一台。",
- "buttons.close": "关闭"
+ "buttons.close": "关闭",
+ "remote.loading": "正在加载远端界面…"
}