DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh-ui): primitives redraw, sync panel, desktop-bridge gating
Menghuan1918348ced5fa31d
diff --git a/packages/dsh-tauri-ssh-ui/package.json b/packages/dsh-tauri-ssh-ui/package.jsonindex 3dd0742e..cb023e5d 100644--- a/packages/dsh-tauri-ssh-ui/package.json+++ b/packages/dsh-tauri-ssh-ui/package.json@@ -43,7 +43,8 @@"inject": ["@deepseek-ai/dsh-client-ui-renderer","@deepseek-ai/dsh-client-ui-settings",- "@deepseek-ai/dsh-client-locale"+ "@deepseek-ai/dsh-client-locale",+ "dsh-tauri"],"platform": "web"},@@ -59,6 +60,7 @@"typecheck": "tsc"},"devDependencies": {+ "@deepseek-ai/dsh-client-ui-primitives": "catalog:dsh","@testing-library/dom": "catalog:testing","@testing-library/react": "catalog:testing","@types/node": "catalog:types",diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.css b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.cssindex bfbb127f..ea917231 100644--- a/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.css+++ b/packages/dsh-tauri-ssh-ui/src/client/components/machines-section.module.css@@ -1,8 +1,10 @@-/* SSH-machines settings section, in the DSH settings-panel design language- * (the vocabulary of ModelsSection.module.css): 14/22 body, 12/18 caption,- * capsule controls (h36 r18; h28 r14 where a row is dense), 32px fields,- * hairline `border-l2` cards. Every color resolves through a `--dsw-alias-*`- * token, so light and dark themes both work without literals. */+/* SSH-machines settings section, on the official UI primitives (Button /+ * Input / StateDot / Modal / Pill draw the controls); this sheet keeps only+ * layout and token alignment: 14/22 body, 12/18 caption, hairline+ * `border-l2` cards, and the few custom visuals the primitives do not own+ * (the hollow idle dot, the color swatches, the tint switch). Every color+ * resolves through a `--dsw-alias-*` token, so light and dark themes both+ * work without literals. */.section {display: flex;@@ -35,73 +37,14 @@flex-wrap: wrap;}-/* Capsule button base (Button primitive geometry). */-.button {- box-sizing: border-box;- display: inline-flex;- align-items: center;- justify-content: center;- gap: 4px;- height: 36px;- padding: 0 14px;- border: none;- border-radius: 18px;- background: transparent;- color: var(--dsw-alias-label-primary);- font: inherit;- font-size: 14px;- line-height: 22px;- cursor: pointer;-}--.button:disabled {- cursor: default;- opacity: 0.4;-}--/* Dense capsule for row actions. */-.sm {- height: 28px;- padding: 0 10px;- border-radius: 14px;- font-size: 12px;- line-height: 18px;-}--.primary {- background: var(--dsw-alias-button-primary-fill);- color: var(--dsw-alias-label-primary-foreground);-}--.primary:hover:not(:disabled) {- background: var(--dsw-alias-button-primary-hover);-}--.secondary {- border: 1px solid var(--dsw-alias-border-l2);- background: transparent;-}--.secondary:hover:not(:disabled) {- background: var(--dsw-alias-interactive-bg-hover);-}--.danger {+/* The danger seat of an otherwise primitive button (token-aligned color). */+.dangerAction {color: var(--dsw-alias-state-error-primary);}-.danger:hover:not(:disabled) {- background: var(--dsw-alias-interactive-bg-hover-danger);-}--/* "Add machine": a dashed place, like every other empty-list affordance. */-.add {- border: 1px dashed var(--dsw-alias-border-l3);- background: transparent;-}--.add:hover:not(:disabled) {- background: var(--dsw-alias-interactive-bg-hover);+/* "Add machine" keeps the dashed affordance of every other empty-list entry. */+.addAction {+ border-style: dashed;}/* The machine list: one hairline card per machine. */@@ -179,13 +122,14 @@color: var(--dsw-alias-label-secondary);}-/* Connection state: dot (StateDot vocabulary) + caption text. */+/* Connection state caption text (the dot itself is StateDot). */.status {font-size: 12px;line-height: 18px;color: var(--dsw-alias-label-tertiary);}+/* The hollow idle dot: the one connection state StateDot has no glyph for. */.stateDot {position: relative;display: inline-block;@@ -197,16 +141,7 @@color: var(--dsw-alias-label-caption);}-.stateDot[data-state='done'] {- color: var(--dsw-alias-state-success-primary);-}--.stateDot[data-state='ongoing'] {- color: var(--dsw-static-deepseek-450);- animation: dsh-ssh-pulse 1.2s var(--ds-ease-in-out) infinite;-}--.stateDot[data-state='idle']::after {+.stateDot::after {content: '';position: absolute;inset: 25%;@@ -214,11 +149,6 @@background: currentColor;}-@keyframes dsh-ssh-pulse {- 0%, 100% { opacity: 1; }- 50% { opacity: 0.35; }-}-/* Identity color pip next to the machine name. */.colorPip {display: inline-block;@@ -356,32 +286,9 @@color: var(--dsw-alias-label-secondary);}-.input {- box-sizing: border-box;+/* The Input primitive draws the box; the field makes it fill the grid cell. */+.fieldInput {width: 100%;- height: 32px;- padding: 0 10px;- border: 1px solid var(--dsw-alias-border-l2);- border-radius: 8px;- font: inherit;- font-size: 14px;- line-height: 22px;- background: var(--dsw-alias-bg-layer-1);- color: var(--dsw-alias-label-primary);-}--.input:focus {- outline: none;- border-color: var(--dsw-alias-brand-primary);-}--.input::placeholder {- color: var(--dsw-alias-label-dimmed);-}--.input:disabled {- opacity: 0.6;- cursor: default;}/* Per-machine status lines. */@@ -401,6 +308,19 @@overflow-wrap: anywhere;}+/* The streaming log surface (machine.events lines, or the progress log). */+.logStream {+ margin: 0;+ max-height: 160px;+ overflow: auto;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ font-family: var(--ds-font-family-code);+ font-size: 11px;+ line-height: 16px;+ color: var(--dsw-alias-label-tertiary);+}+/* The one-click install surface (dsh missing on the remote). */.installBox {display: flex;@@ -419,18 +339,6 @@color: var(--dsw-alias-label-secondary);}-.installLog {- margin: 0;- max-height: 140px;- overflow: auto;- white-space: pre-wrap;- overflow-wrap: anywhere;- font-family: var(--ds-font-family-code);- font-size: 11px;- line-height: 16px;- color: var(--dsw-alias-label-tertiary);-}-.installNote {margin: 0;font-size: 12px;@@ -471,9 +379,108 @@color: var(--dsw-alias-label-tertiary);}-@media (prefers-reduced-motion: reduce) {- .stateDot[data-state='ongoing'] {- animation: none;- opacity: 0.6;- }+/* The load-failure block: empty state plus the retry affordance. */+.emptyBlock {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 8px;+}++/* The sync panel (a section-level group under the machine list). */+.syncPanel {+ display: flex;+ flex-direction: column;+ gap: 10px;+ margin-top: 12px;+ padding-top: 12px;+ border-top: 1px solid var(--dsw-alias-border-l2);+}++.syncTargets {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+}++.syncGroups {+ display: flex;+ flex-direction: column;+ gap: 10px;+}++.syncGroup {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.syncItems {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.syncItem {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++.syncReason {+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-tertiary));+}++/* The root tag inside a skill pill. */+.syncRoot {+ margin-left: 6px;+ font-size: 10px;+ line-height: 14px;+ color: var(--dsw-alias-label-tertiary);+}++.syncActions {+ display: flex;+ align-items: center;+ gap: 8px;+}++.syncResults {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.syncSummary {+ margin: 0;+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-label-secondary);+}++.syncResult {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++.syncResultName {+ font-size: 12px;+ line-height: 18px;+ font-weight: 500;+ color: var(--dsw-alias-label-primary);+}++.syncOk {+ font-size: 12px;+ line-height: 18px;+ color: var(--dsw-alias-state-success-primary);}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.tsxindex 3c4d6ba0..5440c43d 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@@ -1,12 +1,13 @@import type { SshKey } from '../locales/index.js'import type { FetchFn, MachineRow, SshApiResponse } from '../store/index.js'+import type { RemoteBridge } from '../types/index.js'import { fireEvent, screen, waitFor, within } from '@testing-library/dom'import { act, cleanup, render } from '@testing-library/react'// @vitest-environment jsdomimport { afterEach, describe, expect, it, vi } from 'vitest'import { en } from '../locales/index.js'import { MachinesStore } from '../store/index.js'-import { MachinesSection, OPEN_WINDOW_FEATURES } from './machines-section.js'+import { MachinesSection } from './machines-section.js'afterEach(() => {cleanup()@@ -21,6 +22,17 @@ function fakeFetch(envelope: SshApiResponse): FetchMock {return vi.fn<FetchFn>(async () => ({ json: async () => envelope }) as unknown as Response)}+/** A bridge whose ping never answers (the pure-web environment). */+const unreachableBridge: RemoteBridge = {+ probe: () => Promise.reject(new Error('NODE_NOT_ANSWERED: invoke remote_bridge_ping timed out')),+ openWindow: () => Promise.reject(new Error('no bridge')),+}++/** A bridge whose ping answers; `openWindow` is a spy. */+function desktopBridge(openWindow: RemoteBridge['openWindow'] = vi.fn(async () => undefined)): RemoteBridge {+ return { probe: async () => true, openWindow }+}+const machineA: MachineRow = {id: 'a',name: 'alpha',@@ -32,10 +44,12 @@ const machineA: MachineRow = {remotePort: 3080,}-function mount(overrides: { envelope?: SshApiResponse } = {}) {+function mount(overrides: { envelope?: SshApiResponse, bridge?: RemoteBridge } = {}) {const fetchFn = fakeFetch(overrides.envelope ?? { ok: true, value: { items: [] } })const store = new MachinesStore(fetchFn)- const view = render(<MachinesSection store={store} t={t} />)+ const view = render(+ <MachinesSection store={store} t={t} {...overrides.bridge === undefined ? {} : { bridge: overrides.bridge }} />,+ )return { view, store, fetchFn }}@@ -85,7 +99,7 @@ describe('machinesSection', () => {expect(payload.secrets).toMatchObject({ password: 'sekrit' })})- it('removes a draft and removes the machine on save', async () => {+ it('removes a draft through the confirmation modal and removes the machine on save', async () => {const { fetchFn } = mount({envelope: {ok: true,@@ -95,20 +109,28 @@ describe('machinesSection', () => {await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())const betaCard = screen.getByTestId('machine-b')fireEvent.click(withinButton(betaCard, 'Remove'))+ // The modal states what is about to be removed; cancel first keeps the row.+ await waitFor(() => expect(screen.getByText(/This removes the "beta" machine profile/)).toBeTruthy())+ fireEvent.click(screen.getByText('Cancel'))+ expect(screen.getByTestId('machine-b')).toBeTruthy()+ fireEvent.click(withinButton(betaCard, 'Remove'))+ await waitFor(() => expect(screen.getByText('Remove it')).toBeTruthy())+ fireEvent.click(screen.getByText('Remove it'))+ await waitFor(() => expect(screen.queryByTestId('machine-b')).toBeNull())fireEvent.click(screen.getByText('Save'))await waitFor(() => expect(removeCalls(fetchFn)).toHaveLength(1))expect(removeCalls(fetchFn)[0]).toEqual({ method: 'machine.remove', payload: { machineId: 'b' } })})- it('tests, connects, opens, and disconnects a machine', async () => {+ it('tests, connects, opens through the desktop bridge, and disconnects a machine', async () => {+ const openWindow = vi.fn(async () => undefined)const fetchFn = fakeFetch({ ok: true, value: { items: [] } })const store = new MachinesStore(fetchFn)store.store.update((state) => {state.status = 'ready'state.machines = [machineA]})- const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)- render(<MachinesSection store={store} t={t} />)+ render(<MachinesSection store={store} t={t} bridge={desktopBridge(openWindow)} />)await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux alpha' } }) } as unknown as Response)@@ -119,13 +141,36 @@ describe('machinesSection', () => {fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Connect'))await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Open')).toBeTruthy())fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Open'))- expect(openSpy).toHaveBeenCalledWith('http://127.0.0.1:49152', '_blank', OPEN_WINDOW_FEATURES)+ await waitFor(() => expect(openWindow).toHaveBeenCalledWith('a', 'http://127.0.0.1:49152'))+ expect(screen.queryByTestId('bridge-error-a')).toBeNull()fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Disconnect'))await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Connect')).toBeTruthy())})+ it('hides the open button entirely in the pure-web environment', async () => {+ const openWindow = vi.fn(async () => undefined)+ mount({+ bridge: unreachableBridge,+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },+ })+ // The rejected probe settles: pure web never shows the popup affordance.+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Connected'))+ await waitFor(() => expect(screen.queryByText('Open')).toBeNull())+ expect(openWindow).not.toHaveBeenCalled()+ })++ it('surfaces a failed bridge open call as a visible error', async () => {+ const openWindow = vi.fn(() => Promise.reject(new Error('window refused')))+ mount({+ bridge: desktopBridge(openWindow),+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },+ })+ fireEvent.click(await screen.findByText('Open'))+ await waitFor(() => expect(screen.getByTestId('bridge-error-a').textContent).toContain('window refused'))+ })+it('renders the connecting state with the connect action disabled', async () => {mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } } })await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())@@ -133,6 +178,24 @@ describe('machinesSection', () => {expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(true)})+ it('renders the testing and reconnecting states with the retry hint', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'testing' }] } } })+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Testing'))++ cleanup()+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'reconnecting', nextRetryHint: 'in 8s' }] } } })+ 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 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'))+ expect(screen.getByText('auth failed after 10 tries')).toBeTruthy()+ expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(false)+ })+it('edits every config field and falls back on malformed numbers', async () => {const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())@@ -151,12 +214,26 @@ describe('machinesSection', () => {expect(payload.secrets).toMatchObject({ passphrase: 'phrase' })})+ it('masks the secret inputs and keeps the write-only direction', async () => {+ mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ const password = screen.getByLabelText('Password (optional)')+ const passphrase = screen.getByLabelText('Key passphrase (optional)')+ expect(password.getAttribute('type')).toBe('password')+ expect(passphrase.getAttribute('type')).toBe('password')+ // Presence flags only: the placeholders report set/unset, never values.+ expect(password.getAttribute('placeholder')).toBe('set')+ expect(passphrase.getAttribute('placeholder')).toBe('not set')+ })+it('opens nothing when a connected machine has no tunnel url', async () => {- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected' }] } } })- const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)- await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Open')).toBeTruthy())- fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Open'))- expect(openSpy).not.toHaveBeenCalled()+ const openWindow = vi.fn(async () => undefined)+ mount({+ bridge: desktopBridge(openWindow),+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected' }] } },+ })+ fireEvent.click(await screen.findByText('Open'))+ expect(openWindow).not.toHaveBeenCalled()})it('persists the identity color and the border tint switch', async () => {@@ -207,6 +284,44 @@ describe('machinesSection', () => {await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Starting the remote instance'))})+ it('streams the install log through the unified log surface', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ act(() => {+ store.store.update((state) => {+ state.busy.a = 'install'+ state.statuses.a = {+ state: 'disconnected',+ dshMissing: true,+ progress: { phase: 'installing', log: '==> Checking dependencies\ngit ... ok' },+ }+ })+ })+ expect(screen.getAllByText(/Installing dsh/).length).toBeGreaterThan(0)+ const log = screen.getByTestId('machine-log-a')+ expect(log.textContent).toContain('==> Checking dependencies')+ expect(log.textContent).toContain('git ... ok')+ })++ it('prefers the machine.events lines over the progress log', async () => {+ const { store } = mount({+ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } },+ })+ await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())+ act(() => {+ store.store.update((state) => {+ state.logs.a = ['[bootstrap] cloning dsh source', '[bootstrap] pnpm install']+ state.statuses.a = { state: 'connecting', progress: { phase: 'starting', log: 'old progress text' } }+ })+ })+ const log = screen.getByTestId('machine-log-a')+ expect(log.textContent).toContain('[bootstrap] cloning dsh source')+ expect(log.textContent).toContain('[bootstrap] pnpm install')+ expect(log.textContent).not.toContain('old progress text')+ })+it('polls the host while an operation is in flight and stops when idle', async () => {vi.useFakeTimers()try {@@ -220,14 +335,15 @@ describe('machinesSection', () => {render(<MachinesSection store={store} t={t} />)const before = fetchFn.mock.calls.lengthawait act(async () => vi.advanceTimersByTime(1600))- expect(fetchFn.mock.calls.length).toBe(before + 1)+ // One poll = machine.list + machine.events (the S2 channel ride-along).+ 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 = {}})await act(async () => vi.advanceTimersByTime(3200))- expect(fetchFn.mock.calls.length).toBe(before + 1)+ expect(fetchFn.mock.calls.length).toBe(before + 2)}finally {vi.useRealTimers()@@ -245,6 +361,14 @@ describe('machinesSection', () => {await waitFor(() => expect(screen.getByText(/Error: boom/)).toBeTruthy())})+ it('renders the load-failure state with a retry affordance instead of a blank page', async () => {+ const fetchFn = vi.fn<FetchFn>(async () => ({ json: async () => ({ ok: false, error: { code: 'internal', message: 'route down' } }) }) as unknown as Response)+ const store = new MachinesStore(fetchFn)+ render(<MachinesSection store={store} t={t} />)+ await waitFor(() => expect(screen.getByText('The panel failed to load.')).toBeTruthy())+ expect(screen.getAllByText('Refresh').length).toBeGreaterThan(0)+ })+it('renders discovered config aliases as read-only cards with working actions', async () => {const fetchFn = fakeFetch({ok: true,@@ -258,7 +382,7 @@ describe('machinesSection', () => {await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())expect(screen.getByText('Hosts from ~/.ssh/config')).toBeTruthy()const card = screen.getByTestId('machine-dev')- // Read-only: no editable fields, no Remove button.+ // Read-only: no editable fields, no Remove button, no secrets.expect(within(card).queryByLabelText('ID')).toBeNull()expect(within(card).queryByText('Remove')).toBeNull()fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux dev' } }) } as unknown as Response)@@ -266,7 +390,8 @@ describe('machinesSection', () => {await waitFor(() => expect(screen.getByTestId('notice').textContent).toContain('Linux dev'))})- it('connects and opens a discovered config alias', async () => {+ it('connects and opens a discovered config alias through the bridge', async () => {+ const openWindow = vi.fn(async () => undefined)const fetchFn = fakeFetch({ok: true,value: {@@ -275,25 +400,28 @@ describe('machinesSection', () => {},})const store = new MachinesStore(fetchFn)- const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)- render(<MachinesSection store={store} t={t} />)+ render(<MachinesSection store={store} t={t} bridge={desktopBridge(openWindow)} />)await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Connect'))await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Open')).toBeTruthy())fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Open'))- expect(openSpy).toHaveBeenCalledWith('http://127.0.0.1:49152', '_blank', OPEN_WINDOW_FEATURES)+ await waitFor(() => expect(openWindow).toHaveBeenCalledWith('dev', 'http://127.0.0.1:49152'))fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Disconnect'))await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Connect')).toBeTruthy())})it('opens nothing for a discovered card without a tunnel url', async () => {- mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connected' }] } } })- const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)- await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Open')).toBeTruthy())- fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Open'))- expect(openSpy).not.toHaveBeenCalled()+ const openWindow = vi.fn(async () => undefined)+ const fetchFn = fakeFetch({+ ok: true,+ value: { items: [], discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connected' }] },+ })+ const store = new MachinesStore(fetchFn)+ render(<MachinesSection store={store} t={t} bridge={desktopBridge(openWindow)} />)+ fireEvent.click(await screen.findByText('Open'))+ expect(openWindow).not.toHaveBeenCalled()})it('disables connect while a discovered alias is connecting', async () => {@@ -338,27 +466,6 @@ describe('machinesSection', () => {})})- it('shows the installing phase with the live streaming log', async () => {- const { store } = mount({- envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },- })- await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())- act(() => {- store.store.update((state) => {- state.busy.a = 'install'- state.statuses.a = {- state: 'disconnected',- dshMissing: true,- progress: { phase: 'installing', log: '==> Checking dependencies\ngit ... ok' },- }- })- })- expect(screen.getAllByText(/Installing dsh/).length).toBeGreaterThan(0)- const log = screen.getByTestId('install-log')- expect(log.textContent).toContain('==> Checking dependencies')- expect(log.textContent).toContain('git ... ok')- })-it('shows the install outcome note under the card', async () => {const { store } = mount({envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } },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.tsxindex 0f1f3e59..eca9941a 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,12 +1,17 @@'use no memo'/**- * The SSH-machines settings section, in the DSH settings design language- * (see packages/client/ui-models ModelsSection.module.css): token-resolved- * colors, 32px fields, capsule controls, hairline row cards. One card per- * machine with the config form (secrets write-only), the connection plane- * (test/connect/open/disconnect), and the save/refresh chrome. All state- * lives in the injected {@link MachinesStore}; the component is a thin+ * 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*/@@ -14,12 +19,20 @@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 { 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'++/** A secret field name. */+export type SecretFieldName = 'password' | 'passphrase'/** Registrant-owned dependencies of the section. */export interface MachinesSectionInjected {store: MachinesStore+ /** The desktop iframe bridge (defaults to the real one at registration). */+ bridge?: RemoteBridge}/** Full section props: the framework `t` seat plus the injected store. */@@ -36,18 +49,22 @@ interface Draft {/** The dirty-secret map the form carries: machine key → typed secret values. */type DirtySecrets = Record<string, SecretValues>-/** A secret field name. */-export type SecretFieldName = 'password' | 'passphrase'+/** The StateDot vocabulary the connection states map onto ('idle' is hollow). */+type DotState = 'done' | 'ongoing' | 'error' | 'idle'++/** The desktop-context verdict of the bridge probe. */+type BridgeAvailability = 'unknown' | 'desktop' | 'web'-/** The connection-state dot data attribute (the StateDot vocabulary). */-type DotState = 'done' | 'ongoing' | 'idle'+/** One pending delete, driving the confirmation modal. */+interface RemoveTarget {+ key: string+ id: string+ name: string+}const DEFAULT_PORT = 22const DEFAULT_REMOTE_PORT = 3080-/** window.open features for the Open action: a real popup window, not a tab. */-export const OPEN_WINDOW_FEATURES = 'width=1280,height=860,noopener'-/** The identity-color palette (fits the DSH status hue family). */const COLOR_CHOICES = ['#4176E6',@@ -62,16 +79,21 @@ const COLOR_CHOICES = [/** One machine's editable config card. */export function MachineCard(- { draft, t, secretSet, status, busy, dirty, onChange, onSecret, onRemove, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {+ { draft, t, secretSet, status, busy, dirty, logLines, bridgeOpen, bridgeError, onChange, onSecret, onRemove, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {draft: Draftt: (key: SshKey) => stringsecretSet: Record<string, boolean>status: MachineStatus | undefinedbusy: 'test' | 'connect' | 'disconnect' | 'install' | undefineddirty: 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 | undefinedonChange: (key: string, patch: Partial<MachineRow>) => voidonSecret: (key: string, field: SecretFieldName, value: string) => void- onRemove: (key: string) => void+ onRemove: (target: RemoveTarget) => voidonTest: (id: string) => voidonConnect: (id: string) => voidonDisconnect: (id: string) => void@@ -82,7 +104,7 @@ export function MachineCard(): ReactNode {const { row } = draftconst connected = status?.state === 'connected'- const connecting = status?.state === 'connecting'+ const held = status?.state === 'connecting' || status?.state === 'testing' || status?.state === 'reconnecting'const id = row.idconst color = colorOf(row)return (@@ -93,7 +115,7 @@ export function MachineCard(><div className={css.rowHead}><span className={css.rowIdentity}>- <span className={css.stateDot} data-state={dotStateOf(status)} aria-hidden="true" />+ <StateDotOf status={status} />{color !== undefined? <span className={css.colorPip} style={{ background: color }} aria-hidden="true" />: null}@@ -102,106 +124,84 @@ export function MachineCard(<span className={css.status} data-testid={`status-${id}`}>{statusTextOf(status, t)}</span></span><span className={css.rowActions}>- <button- type="button"- className={`${css.button} ${css.secondary} ${css.sm}`}- disabled={busy !== undefined || connecting}- onClick={() => onTest(id)}- >+ <Button variant="outline" size="sm" disabled={busy !== undefined || held} onClick={() => onTest(id)}>{t('test')}- </button>+ </Button>{connected? (<>- <button- type="button"- className={`${css.button} ${css.primary} ${css.sm}`}- disabled={busy !== undefined}- title={t('open.tip')}- onClick={() => onOpen(id)}- >- {t('open')}- </button>- <button- type="button"- className={`${css.button} ${css.secondary} ${css.sm}`}- disabled={busy !== undefined}- onClick={() => onDisconnect(id)}- >+ {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></>): (- <button- type="button"- className={`${css.button} ${css.primary} ${css.sm}`}- disabled={busy !== undefined || connecting}- onClick={() => onConnect(id)}- >+ <Button variant="primary" size="sm" disabled={busy !== undefined || held} onClick={() => onConnect(id)}>{t('connect')}- </button>+ </Button>)}- <button- type="button"- className={`${css.button} ${css.danger} ${css.sm}`}- disabled={busy !== undefined}- onClick={() => onRemove(draft.key)}- >+ <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>+ </Button></span></div><div className={css.editor}><div className={css.grid}><Field label={t('field.id')}>- <input- className={css.input}+ <Input+ className={moduleClass(css.fieldInput)}value={row.id}disabled={!draft.key.startsWith('new-')}onChange={event => onChange(draft.key, { id: event.target.value })}/></Field><Field label={t('field.name')}>- <input- className={css.input}+ <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={css.input}+ <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={css.input}+ <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={css.input}+ <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={css.input}+ <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={css.input}+ <Input+ className={moduleClass(css.fieldInput)}value={row.startCommand ?? ''}onChange={event => onChange(draft.key, { startCommand: event.target.value })}/>@@ -233,7 +233,16 @@ export function MachineCard(? <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}@@ -243,13 +252,17 @@ export function MachineCard(/*** One read-only machine card from ~/.ssh/config: identity, status, and the- * connection plane only — nothing here is stored or editable.+ * connection plane only — nothing here is stored or editable (no password,+ * no color, no delete).*/-function DiscoveredCard({ row, t, status, busy, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {+function DiscoveredCard({ row, t, status, busy, logLines, bridgeOpen, bridgeError, onTest, onConnect, onDisconnect, onOpen, onInstall, installResult }: {row: MachineRowt: (key: SshKey) => stringstatus: MachineStatus | undefinedbusy: 'test' | 'connect' | 'disconnect' | 'install' | undefined+ logLines: readonly string[]+ bridgeOpen: boolean+ bridgeError: string | undefinedonTest: (id: string) => voidonConnect: (id: string) => voidonDisconnect: (id: string) => void@@ -258,56 +271,39 @@ function DiscoveredCard({ row, t, status, busy, onTest, onConnect, onDisconnect,installResult: InstallResult | undefined}): ReactNode {const connected = status?.state === 'connected'- const connecting = status?.state === 'connecting'+ 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}>- <span className={css.stateDot} data-state={dotStateOf(status)} aria-hidden="true" />+ <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- type="button"- className={`${css.button} ${css.secondary} ${css.sm}`}- disabled={busy !== undefined || connecting}- onClick={() => onTest(row.id)}- >+ <Button variant="outline" size="sm" disabled={busy !== undefined || held} onClick={() => onTest(row.id)}>{t('test')}- </button>+ </Button>{connected? (<>- <button- type="button"- className={`${css.button} ${css.primary} ${css.sm}`}- disabled={busy !== undefined}- title={t('open.tip')}- onClick={() => onOpen(row.id)}- >- {t('open')}- </button>- <button- type="button"- className={`${css.button} ${css.secondary} ${css.sm}`}- disabled={busy !== undefined}- onClick={() => onDisconnect(row.id)}- >+ {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></>): (- <button- type="button"- className={`${css.button} ${css.primary} ${css.sm}`}- disabled={busy !== undefined || connecting}- onClick={() => onConnect(row.id)}- >+ <Button variant="primary" size="sm" disabled={busy !== undefined || held} onClick={() => onConnect(row.id)}>{t('connect')}- </button>+ </Button>)}</span></div>@@ -315,7 +311,16 @@ function DiscoveredCard({ row, t, status, busy, onTest, onConnect, onDisconnect,? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(row.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-${row.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} />{installResult !== undefined? <p className={css.installNote} data-testid={`install-note-${row.id}`}>{installNoteOf(installResult, t)}</p>: null}@@ -323,7 +328,29 @@ function DiscoveredCard({ row, t, status, busy, onTest, onConnect, onDisconnect,)}-/** The dsh-missing install surface: a one-click install, or the live log while it runs. */+/** The state dot: a primitive StateDot for live states, hollow CSS for idle. */+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 <StateDot state={state} size={8} />+}++/** The streaming log: the S2 event lines when present, else the progress log. */+function LogStream({ id, lines, fallback }: { id: string, lines: readonly string[], fallback: string | undefined }): ReactNode {+ const output = lines.length > 0+ ? lines.join('\n')+ : (fallback ?? '')+ if (output === '')+ return null+ return (+ <pre className={css.logStream} data-testid={`machine-log-${id}`}>+ {output}+ </pre>+ )+}++/** The dsh-missing install surface: a one-click install (the log lives in the card stream). */function InstallPanel({ status, busy, t, onInstall }: {status: MachineStatusbusy: 'test' | 'connect' | 'disconnect' | 'install' | undefined@@ -335,21 +362,15 @@ function InstallPanel({ status, busy, t, onInstall }: {return (<div className={css.installBox}><p className={css.installHint}>{t('progress.installing')}</p>- <pre className={css.installLog} data-testid="install-log">{status.progress?.log ?? ''}</pre></div>)}return (<div className={css.installBox}><p className={css.installHint}>{t('install.hint')}</p>- <button- type="button"- className={`${css.button} ${css.primary} ${css.sm}`}- disabled={busy !== undefined}- onClick={onInstall}- >+ <Button variant="primary" size="sm" disabled={busy !== undefined} onClick={onInstall}>{t('install.action')}- </button>+ </Button></div>)}@@ -440,8 +461,8 @@ export function SecretField({ field, label, keyName, secretSet, t, value, onValureturn (<label className={css.field}><span className={css.fieldLabel}>{label}</span>- <input- className={css.input}+ <Input+ className={moduleClass(css.fieldInput)}type="password"value={value}placeholder={placeholder}@@ -464,15 +485,27 @@ function colorOf(row: MachineRow): string | undefined {return row.color === undefined || row.color === '' ? undefined : row.color}-/** The connection-state dot color vocabulary. */+/** The connection-state dot vocabulary (StateDot states; idle renders hollow). */function dotStateOf(status: MachineStatus | undefined): DotState {if (status?.state === 'connected')return 'done'- if (status?.state === 'connecting')+ if (status?.state === 'connecting' || status?.state === 'testing' || status?.state === 'reconnecting')return 'ongoing'+ if (status?.state === 'given-up')+ return 'error'return 'idle'}+/** The status-label key of each lifecycle state (the hyphenated state maps to camelCase keys). */+const STATUS_KEY_OF: Record<MachineLifecycleState, SshKey> = {+ 'disconnected': 'status.disconnected',+ 'testing': 'status.testing',+ 'connecting': 'status.connecting',+ 'connected': 'status.connected',+ 'reconnecting': 'status.reconnecting',+ 'given-up': 'status.givenUp',+}+/** The status line: live progress text while an operation is in flight, else the state label. */function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => string): string {const progress = status?.progress@@ -487,11 +520,13 @@ function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => str.replace('{attempt}', String(progress.attempt ?? '?')).replace('{total}', String(progress.total ?? '?'))}- if (status?.state === 'connected')- return t('status.connected')- if (status?.state === 'connecting')- return t('status.connecting')- return t('status.disconnected')+ 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)+ }+ return base}/** Parse a number input; non-numbers fall back to the default. */@@ -500,25 +535,68 @@ function numberOf(raw: string, fallback: number): number {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 the SSH-machines settings page.* @returns the page element tree.*/-export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {+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>({})const [addCounter, setAddCounter] = useState(0)const [initialized, setInitialized] = useState(false)+ const [availability, setAvailability] = useState<BridgeAvailability>(() => bridge?.probe === undefined ? 'web' : 'unknown')+ const [bridgeErrors, setBridgeErrors] = useState<Record<string, string>>({})+ const [removeTarget, setRemoveTarget] = useState<RemoveTarget | null>(null)useEffect(() => {void store.load()}, [store])+ // Probe the desktop bridge once: an answer means the popup affordance+ // exists; a timeout or rejection means pure web, where it never shows.+ // (No bridge at all settled synchronously in the initial state.)+ useEffect(() => {+ const probe = bridge?.probe+ if (probe === undefined)+ return+ let current = true+ probe().then(+ () => {+ if (current)+ setAvailability('desktop')+ },+ () => {+ if (current)+ setAvailability('web')+ },+ )+ return () => {+ current = false+ }+ }, [bridge])+// While any machine has an operation in flight, poll the host every 1.5 s- // so the live progress (handshake / starting / probing) stays current.+ // so the live progress (handshake / starting / probing) and the event log+ // stay current.const anyInFlight = Object.keys(state.busy).length > 0- || Object.values(state.statuses).some(status => status.state === 'connecting')+ || Object.values(state.statuses).some(status =>+ status.state === 'connecting' || status.state === 'reconnecting' || status.state === 'testing')useEffect(() => {if (!anyInFlight)return@@ -569,7 +647,11 @@ export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {}))}- const removeDraft = (key: string): void => {+ const confirmRemove = (): void => {+ if (removeTarget === null)+ return+ const key = removeTarget.key+ setRemoveTarget(null)setDrafts((previous) => {const next = { ...previous }delete next[key]@@ -577,6 +659,27 @@ export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {})}+ /** Ask the desktop shell for the remote window; failures surface per machine. */+ const openRemoteWindow = (id: string): void => {+ const url = state.statuses[id]?.tunnelBaseUrl+ if (url === undefined || bridge === undefined)+ return+ bridge.openWindow(id, url).then(+ () => {+ setBridgeErrors((previous) => {+ if (previous[id] === undefined)+ return previous+ const next = { ...previous }+ delete next[id]+ return next+ })+ },+ (error: unknown) => {+ setBridgeErrors(previous => ({ ...previous, [id]: messageOf(error) }))+ },+ )+ }+const invalid = Object.values(drafts).some(draft =>draft.row.id === '' || draft.row.name === '' || draft.row.host === '')@@ -584,35 +687,22 @@ export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {void store.persist(Object.values(drafts).map(draft => draft.row), dirty)}+ const bridgeOpen = availability === 'desktop'+return (<div className={css.section}><h2 className={css.title}>{t('title')}</h2><p className={css.intro}>{t('intro')}</p><div className={css.chrome}>- <button- type="button"- className={`${css.button} ${css.secondary}`}- disabled={state.status === 'loading'}- onClick={() => void store.load()}- >+ <Button variant="outline" disabled={state.status === 'loading'} onClick={() => void store.load()}>{t('refresh')}- </button>- <button- type="button"- className={`${css.button} ${css.add}`}- disabled={state.status === 'loading'}- onClick={addMachine}- >+ </Button>+ <Button variant="outline" className={moduleClass(css.addAction)} disabled={state.status === 'loading'} onClick={addMachine}>{t('addMachine')}- </button>- <button- type="button"- className={`${css.button} ${css.primary}`}- disabled={invalid || state.status === 'loading'}- onClick={save}- >+ </Button>+ <Button variant="primary" disabled={invalid || state.status === 'loading'} onClick={save}>{t('save')}- </button>+ </Button></div>{state.notice !== null ? <p className={css.notice} data-testid="notice">{state.notice}</p> : null}{state.error !== null@@ -625,6 +715,14 @@ export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {: null}{invalid ? <p className={css.hint}>{t('saveHint')}</p> : null}{state.status === 'loading' ? <p className={css.hint}>{t('loading')}</p> : null}+ {state.status === 'error'+ ? (+ <div className={css.emptyBlock}>+ <p className={css.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>: null}@@ -643,16 +741,15 @@ export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {t={t}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={(id) => {- const tunnelBaseUrl = state.statuses[id]?.tunnelBaseUrl- if (tunnelBaseUrl !== undefined)- window.open(tunnelBaseUrl, '_blank', OPEN_WINDOW_FEATURES)- }}+ onOpen={openRemoteWindow}/>))}</ul>@@ -668,23 +765,36 @@ export function MachinesSection({ t, store }: MachinesSectionProps): ReactNode {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={removeDraft}+ 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={(id) => {- const tunnelBaseUrl = state.statuses[id]?.tunnelBaseUrl- if (tunnelBaseUrl !== undefined)- window.open(tunnelBaseUrl, '_blank', OPEN_WINDOW_FEATURES)- }}+ onOpen={openRemoteWindow}/>))}</ul>+ <SyncPanel store={store} t={t} />+ <Modal+ open={removeTarget !== null}+ onClose={() => setRemoveTarget(null)}+ title={t('remove.confirm.title')}+ closeLabel={t('remove.confirm.cancel')}+ description={removeTarget === null ? '' : t('remove.confirm.description').replace('{name}', removeTarget.name)}+ 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>+ </>+ )}+ /></div>)}diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.test.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.test.tsxnew file mode 100644index 00000000..635ef013--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.test.tsx@@ -0,0 +1,181 @@+import type { SshKey } from '../locales/index.js'+import type { FetchFn, MachineRow } from '../store/index.js'+import { fireEvent, screen, waitFor } from '@testing-library/dom'+import { cleanup, render } from '@testing-library/react'+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { en } from '../locales/index.js'+import { MachinesStore } from '../store/index.js'+import { SyncPanel } from './sync-panel.js'++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+})++const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: SshKey) => string++type FetchMock = ReturnType<typeof vi.fn<FetchFn>>++/** A fetch mock dispatching by /api-ssh method name. */+function routeFetch(routes: Record<string, unknown>, failures: string[] = []): FetchMock {+ return vi.fn<FetchFn>(async (_url, init) => {+ const body = JSON.parse(String(init.body)) as { method: string }+ if (failures.includes(body.method)) {+ return { json: async () => ({ ok: false, error: { code: 'internal', message: `${body.method} broke` } }) } as unknown as Response+ }+ const value = routes[body.method] ?? {}+ return { json: async () => ({ ok: true, value }) } as unknown as Response+ })+}++const preview = {+ plugins: [+ { name: 'dsh-market', spec: 'github:omdsh/dsh-market', syncable: true },+ { name: 'local-thing', spec: 'link:../local', syncable: false, reason: 'local-path dependency; it cannot be resolved on the remote' },+ ],+ skills: [+ { name: 'alpha', root: 'dsh' },+ { name: 'beta', root: 'agents' },+ ],+}++const machineA: MachineRow = {+ id: 'a',+ name: 'alpha',+ host: '10.0.0.1',+ port: 22,+ user: 'root',+ hasPassword: false,+ hasPassphrase: false,+ remotePort: 3080,+}++/** A store preloaded with one connected machine and a landed sync preview. */+function connectedStore(fetchFn: FetchMock): MachinesStore {+ const store = new MachinesStore(fetchFn)+ store.store.update((state) => {+ state.status = 'ready'+ state.machines = [machineA]+ state.statuses = { a: { state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' } }+ state.sync = { status: 'ready', error: null, preview, applying: false, results: null }+ })+ return store+}++describe('syncPanel', () => {+ it('keeps every independently selected item (multi-select, not a radio group)', async () => {+ const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-plugin-dsh-market')).toBeTruthy())+ const plugin = screen.getByTestId('sync-plugin-dsh-market')+ const skill = screen.getByTestId('sync-skill-dsh-alpha')+ expect(plugin.getAttribute('aria-pressed')).toBe('false')+ fireEvent.click(plugin)+ fireEvent.click(skill)+ expect(screen.getByTestId('sync-plugin-dsh-market').getAttribute('aria-pressed')).toBe('true')+ expect(screen.getByTestId('sync-skill-dsh-alpha').getAttribute('aria-pressed')).toBe('true')+ // Deselecting one leaves the others selected — the chip defect fix.+ fireEvent.click(screen.getByTestId('sync-plugin-dsh-market'))+ expect(screen.getByTestId('sync-plugin-dsh-market').getAttribute('aria-pressed')).toBe('false')+ expect(screen.getByTestId('sync-skill-dsh-alpha').getAttribute('aria-pressed')).toBe('true')+ })++ it('disables unsyncable plugins and shows their reason', async () => {+ const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-plugin-local-thing')).toBeTruthy())+ expect(screen.getByTestId('sync-plugin-local-thing').hasAttribute('disabled')).toBe(true)+ expect(screen.getByText(/local-path dependency/)).toBeTruthy()+ })++ it('sends the whole multi-selection to sync.apply', async () => {+ const fetchFn = routeFetch({ 'sync.apply': { items: [] } })+ const store = connectedStore(fetchFn)+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-apply')).toBeTruthy())+ fireEvent.click(screen.getByTestId('sync-plugin-dsh-market'))+ fireEvent.click(screen.getByTestId('sync-skill-agents-beta'))+ fireEvent.click(screen.getByTestId('sync-apply'))+ await waitFor(() => expect(applyCalls(fetchFn)).toHaveLength(1))+ expect(applyCalls(fetchFn)[0]).toEqual({+ machineId: 'a',+ plugins: [{ name: 'dsh-market', spec: 'github:omdsh/dsh-market' }],+ skills: [{ name: 'beta', root: 'agents' }],+ })+ })++ it('renders partial failures per item with reasons', async () => {+ const store = connectedStore(routeFetch({}))+ store.store.update((state) => {+ state.sync.results = [+ { kind: 'plugin', name: 'dsh-market', ok: true },+ { kind: 'skill', name: 'alpha', root: 'dsh', ok: false, error: 'exit 1: read-only file system' },+ ]+ })+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-results')).toBeTruthy())+ expect(screen.getByTestId('sync-result-dsh-market').dataset.ok).toBe('true')+ const failed = screen.getByTestId('sync-result-alpha')+ expect(failed.dataset.ok).toBe('false')+ expect(failed.textContent).toContain('read-only file system')+ expect(failed.textContent).toContain('(dsh)')+ expect(screen.getByText(/1\/2 items succeeded/)).toBeTruthy()+ })++ it('renders a complete failure with every reason visible', async () => {+ const store = connectedStore(routeFetch({}))+ store.store.update((state) => {+ state.sync.results = [+ { kind: 'plugin', name: 'dsh-market', ok: false, error: 'exit 1: ERR_PNPM_NO_MATCH' },+ { kind: 'skill', name: 'alpha', root: 'dsh', ok: false, error: 'exit 1: read-only file system' },+ ]+ })+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-results')).toBeTruthy())+ expect(screen.getByText(/0\/2 items succeeded/)).toBeTruthy()+ expect(screen.getByTestId('sync-result-dsh-market').textContent).toContain('ERR_PNPM_NO_MATCH')+ expect(screen.getByTestId('sync-result-alpha').textContent).toContain('read-only file system')+ })++ it('surfaces a request-level failure without swallowing previous results', async () => {+ const fetchFn = routeFetch({ 'sync.apply': { items: [] } }, ['sync.apply'])+ const store = connectedStore(fetchFn)+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-apply')).toBeTruthy())+ fireEvent.click(screen.getByTestId('sync-plugin-dsh-market'))+ fireEvent.click(screen.getByTestId('sync-apply'))+ await waitFor(() => expect(screen.getByText(/The sync request failed: sync.apply broke/)).toBeTruthy())+ })++ it('shows the not-connected note when no machine is connected', async () => {+ const store = new MachinesStore(routeFetch({}))+ store.store.update((state) => {+ state.status = 'ready'+ state.machines = [machineA]+ state.statuses = { a: { state: 'disconnected' } }+ state.sync = { status: 'ready', error: null, preview, applying: false, results: null }+ })+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByText(/No connected machines/)).toBeTruthy())+ expect(screen.queryByTestId('sync-apply')).toBeNull()+ })++ it('shows the preview load failure with the reason', async () => {+ const fetchFn = routeFetch({}, ['sync.preview'])+ const store = new MachinesStore(fetchFn)+ store.store.update((state) => {+ state.status = 'ready'+ })+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByText(/Failed to load the sync list: sync.preview broke/)).toBeTruthy())+ })+})++/** The sync.apply request bodies the fake fetch received. */+function applyCalls(fetchFn: ReturnType<typeof vi.fn>): Array<Record<string, unknown>> {+ return fetchFn.mock.calls+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })+ .filter(call => call.method === 'sync.apply')+ .map(call => call.payload)+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsxnew file mode 100644index 00000000..04a9d8c3--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx@@ -0,0 +1,202 @@+'use no memo'++/**+ * The sync-to-remote panel: pick a connected target machine, multi-select+ * local plugins and user-level skills (independent Set semantics — the old+ * desktop panel behaved like a radio group over its chips, silently dropping+ * every earlier pick), then sync. Every requested item settles into a+ * per-item outcome row — partial failures render with their reasons instead+ * of vanishing into a success toast. All domain state lives in the injected+ * {@link MachinesStore}; only the selection is local.+ * @module dsh-tauri-ssh-ui/client/components/sync-panel+ */++import type { ReactNode } from 'react'+import type { SshKey } from '../locales/index.js'+import type { MachineRow, MachinesStore } from '../store/index.js'+import type { SyncItemResult } from '../types/index.js'+import { Button, Pill, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'+import { useEffect, useState, useSyncExternalStore } from 'react'+import { toggleSelection } from '../store/index.js'+import css from './machines-section.module.css'++/** The panel props: the framework `t` seat plus the injected store. */+export interface SyncPanelProps {+ store: MachinesStore+ t: (key: SshKey) => string+}++/** Render the sync panel over the store snapshot. */+export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot)+ const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set())+ const [targetId, setTargetId] = useState<string | null>(null)++ useEffect(() => {+ if (state.sync.status === 'idle')+ void store.loadSyncPreview()+ }, [state.sync.status, store])++ const connected = connectedMachinesOf(state.machines, state.discovered, state.statuses)+ const target = connected.find(machine => machine.id === (targetId ?? connected[0]?.id))+ const preview = state.sync.preview+ const selectedPlugins = preview?.plugins.filter(plugin => selected.has(`plugin:${plugin.spec}`)) ?? []+ const selectedSkills = preview?.skills.filter(skill => selected.has(`skill:${skill.root}:${skill.name}`)) ?? []+ const canApply = target !== undefined && !state.sync.applying && (selectedPlugins.length > 0 || selectedSkills.length > 0)++ const apply = (): void => {+ if (target === undefined)+ return+ void store.applySync(target.id, selectedPlugins, selectedSkills)+ }++ return (+ <section className={css.syncPanel} data-testid="sync-panel">+ <h3 className={css.groupTitle}>{t('sync.title')}</h3>+ <p className={css.groupHint}>{t('sync.desc')}</p>+ {connected.length === 0+ ? <p className={css.hint}>{t('sync.notConnected')}</p>+ : (+ <>+ <div className={css.syncTargets}>+ <span className={css.fieldLabel}>{t('sync.target')}</span>+ {connected.map(machine => (+ <Pill+ key={machine.id}+ active={machine.id === target?.id}+ onClick={() => setTargetId(machine.id)}+ aria-pressed={machine.id === target?.id}+ >+ {machine.name}+ </Pill>+ ))}+ </div>+ {preview === null || state.sync.status === 'loading'+ ? <p className={css.hint}>{t('loading')}</p>+ : (+ <div className={css.syncGroups}>+ <div className={css.syncGroup}>+ <span className={css.fieldLabel}>{t('sync.plugins')}</span>+ {preview.plugins.length === 0+ ? <p className={css.hint}>{t('sync.noPlugins')}</p>+ : (+ <ul className={css.syncItems}>+ {preview.plugins.map(plugin => (+ <li key={`plugin:${plugin.spec}`} className={css.syncItem}>+ <Pill+ active={selected.has(`plugin:${plugin.spec}`)}+ disabled={!plugin.syncable}+ title={plugin.syncable ? undefined : plugin.reason}+ aria-pressed={selected.has(`plugin:${plugin.spec}`)}+ data-testid={`sync-plugin-${plugin.name}`}+ onClick={() => setSelected(current => toggleSelection(current, `plugin:${plugin.spec}`))}+ >+ {plugin.name}+ </Pill>+ {!plugin.syncable && plugin.reason !== undefined+ ? <span className={css.syncReason}>{plugin.reason}</span>+ : null}+ </li>+ ))}+ </ul>+ )}+ </div>+ <div className={css.syncGroup}>+ <span className={css.fieldLabel}>{t('sync.skills')}</span>+ {preview.skills.length === 0+ ? <p className={css.hint}>{t('sync.noSkills')}</p>+ : (+ <ul className={css.syncItems}>+ {preview.skills.map(skill => (+ <li key={`skill:${skill.root}:${skill.name}`} className={css.syncItem}>+ <Pill+ active={selected.has(`skill:${skill.root}:${skill.name}`)}+ aria-pressed={selected.has(`skill:${skill.root}:${skill.name}`)}+ data-testid={`sync-skill-${skill.root}-${skill.name}`}+ onClick={() => setSelected(current => toggleSelection(current, `skill:${skill.root}:${skill.name}`))}+ >+ {skill.name}+ <span className={css.syncRoot}>{skill.root}</span>+ </Pill>+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ )}+ <div className={css.syncActions}>+ <Button variant="primary" size="sm" disabled={!canApply} data-testid="sync-apply" onClick={apply}>+ {state.sync.applying ? t('sync.applying') : t('sync.apply')}+ </Button>+ <Button variant="outline" size="sm" disabled={state.sync.status === 'loading'} onClick={() => void store.loadSyncPreview()}>+ {t('sync.refresh')}+ </Button>+ </div>+ </>+ )}+ {state.sync.status === 'error'+ ? (+ <p className={css.error} role="alert">+ {t('sync.loadFailed')}+ {state.sync.error}+ </p>+ )+ : null}+ {state.sync.error !== null && state.sync.status !== 'error'+ ? (+ <p className={css.error} role="alert">+ {t('sync.applyFailed')}+ {state.sync.error}+ </p>+ )+ : null}+ {state.sync.results !== null+ ? <SyncResults results={state.sync.results} t={t} />+ : null}+ </section>+ )+}++/** The per-item outcome list: every requested item, success and failure alike. */+function SyncResults({ results, t }: { results: SyncItemResult[], t: (key: SshKey) => string }): ReactNode {+ const okCount = results.filter(item => item.ok).length+ return (+ <div className={css.syncResults} data-testid="sync-results">+ <p className={css.syncSummary}>{t('sync.done').replace('{ok}', String(okCount)).replace('{total}', String(results.length))}</p>+ <ul className={css.syncItems}>+ {results.map(item => (+ <li+ key={`${item.kind}:${item.root ?? ''}:${item.name}`}+ className={css.syncResult}+ data-testid={`sync-result-${item.name}`}+ data-ok={item.ok}+ >+ <StateDot state={item.ok ? 'done' : 'error'} size={8} />+ <span className={css.syncResultName}>+ {item.name}+ {item.root !== undefined ? ` (${item.root})` : ''}+ </span>+ {item.ok+ ? <span className={css.syncOk}>{t('sync.itemOk')}</span>+ : (+ <span className={css.statusError} role="alert">+ {t('sync.itemFailed')}+ {item.error === undefined ? '' : `:${item.error}`}+ </span>+ )}+ </li>+ ))}+ </ul>+ </div>+ )+}++/** The connected machines, manual first then discovered, in list order. */+function connectedMachinesOf(+ machines: readonly MachineRow[],+ discovered: readonly MachineRow[],+ statuses: Record<string, { state: string }>,+): MachineRow[] {+ return [...machines, ...discovered].filter(machine => statuses[machine.id]?.state === 'connected')+}diff --git a/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts b/packages/dsh-tauri-ssh-ui/src/client/constants/index.tsindex 399382d4..aa01647d 100644--- a/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/constants/index.ts@@ -19,3 +19,14 @@ export const SETTINGS_SECTION_ORDER = 50/** The /api-ssh route the host plugin mounts (same-origin POST envelope). */export const SSH_API_PATH = '/api-ssh'++/**+ * C-BRIDGE (S5-owned): the desktop iframe invoke commands the panel talks to+ * through `invokeBridgedTauri`. A timeout or rejection on the ping means the+ * page runs outside the desktop shell (pure web) and the popup affordance+ * hides itself.+ */+export const REMOTE_BRIDGE_PING_COMMAND = 'remote_bridge_ping'++/** Open (or focus) the `remote-<machineId>` window for a tunnel URL. */+export const REMOTE_OPEN_WINDOW_COMMAND = 'remote_open_window'diff --git a/packages/dsh-tauri-ssh-ui/src/client/index.test.ts b/packages/dsh-tauri-ssh-ui/src/client/index.test.tsindex 86b8557c..b63d8842 100644--- a/packages/dsh-tauri-ssh-ui/src/client/index.test.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/index.test.ts@@ -4,8 +4,14 @@ import { apply as hostApply } from '../index.js'import { MachinesSection } from './components/machines-section.tsx'import { apply, inject } from './index.js'import { en, zh } from './locales/index.js'+import { desktopBridge } from './service/bridge.js'import { MachinesStore } from './store/index.js'+// The desktop invoke bridge resolves through the runtime module table, which+// does not exist under vitest; the registrant tests only need its shape.+// (vitest hoists vi.mock above the imports, so placement here is safe.)+vi.mock('dsh-tauri/client', () => ({ invokeBridgedTauri: vi.fn(async () => undefined) }))+function scriptedCtx(): {ctx: UiContextlocale: { register: ReturnType<typeof vi.fn>, bind: ReturnType<typeof vi.fn> }@@ -69,6 +75,7 @@ describe('ui-ssh client plugin', () => {expect(options.locale).toBe('ssh')const injected = options.inject()expect(injected.store).toBeInstanceOf(MachinesStore)+ expect(injected.bridge).toBe(desktopBridge)expect(slots.register.mock.calls[0]?.[1]).toBe(MachinesSection)// Drive one store load so the window.fetch thunk the plugin installed// actually executes (stubbed: no network in tests).diff --git a/packages/dsh-tauri-ssh-ui/src/client/index.ts b/packages/dsh-tauri-ssh-ui/src/client/index.tsindex 43b8199e..01769b0e 100644--- a/packages/dsh-tauri-ssh-ui/src/client/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/index.ts@@ -11,6 +11,7 @@ import type { UiContext } from './types/index.js'import { MachinesSection } from './components/machines-section.js'import { SETTINGS_SECTION_ID, SETTINGS_SECTION_ORDER, SETTINGS_SECTION_SLOT, SSH_LOCALE_NS } from './constants/index.js'import { en, zh } from './locales/index.js'+import { desktopBridge } from './service/bridge.js'import { MachinesStore } from './store/index.js'/** Required services: the settings slot seam and the locale seat. */@@ -31,7 +32,7 @@ export function apply(ctx: UiContext): void {order: SETTINGS_SECTION_ORDER,label: () => t('nav'),locale: SSH_LOCALE_NS,- inject: () => ({ store }),+ inject: () => ({ store, bridge: desktopBridge }),}, MachinesSection))}diff --git a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts b/packages/dsh-tauri-ssh-ui/src/client/locales/index.tsindex 8047bc5c..99ce246a 100644--- a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts@@ -22,6 +22,7 @@ export const zh = {'secret.set': '已设置','secret.unset': '未设置','error.banner': '错误:',+ 'loadFailed': '面板数据加载失败。','notice.testOk': '连接正常:','notice.disconnected': '已断开。','notice.connected': '已连接:',@@ -39,8 +40,34 @@ export const zh = {'field.tintBorder': '同时着色边框','open.tip': '在新窗口中打开远端实例','status.disconnected': '未连接',+ 'status.testing': '测试中…','status.connecting': '连接中…','status.connected': '已连接',+ 'status.reconnecting': '重连中…',+ 'status.givenUp': '已放弃连接',+ 'status.nextRetry': '(下次重试:{hint})',+ 'log.title': '日志',+ 'remove.confirm.title': '删除机器',+ 'remove.confirm.description': '将删除「{name}」的机器配置;已保存的密码/口令会一并删除。',+ 'remove.confirm.cancel': '取消',+ 'remove.confirm.ok': '确认删除',+ 'bridge.error': '打开远端窗口失败:',+ 'sync.title': '同步到远端',+ 'sync.desc': '把本机已安装的插件与用户级 skills 同步到已连接的机器:插件在远端执行 dsh plugin add;skills 经 tar 流式复制到远端 ~/.dsh/skills。可多选。',+ 'sync.notConnected': '没有已连接的机器。先连接一台,再回来同步。',+ 'sync.target': '目标机器:',+ 'sync.plugins': '插件',+ 'sync.skills': 'Skills',+ 'sync.noPlugins': '本机档案没有插件依赖。',+ 'sync.noSkills': '没有用户级 skills。',+ 'sync.apply': '同步所选',+ 'sync.applying': '同步中…',+ 'sync.refresh': '刷新列表',+ 'sync.loadFailed': '加载同步列表失败:',+ 'sync.applyFailed': '同步请求失败:',+ 'sync.done': '同步完成:{ok}/{total} 项成功。',+ 'sync.itemOk': '已同步',+ 'sync.itemFailed': '失败','progress.handshake': '正在建立 SSH 连接…','progress.starting': '正在启动远端实例…','progress.probing': '健康检查 {attempt}/{total}…',@@ -77,6 +104,7 @@ export const en = {'secret.set': 'set','secret.unset': 'not set','error.banner': 'Error: ',+ 'loadFailed': 'The panel failed to load.','notice.testOk': 'Probe ok: ','notice.disconnected': 'Disconnected.','notice.connected': 'Connected: ',@@ -94,8 +122,34 @@ export const en = {'field.tintBorder': 'Also tint the border','open.tip': 'Open the remote instance in a new window','status.disconnected': 'Disconnected',+ 'status.testing': 'Testing…','status.connecting': 'Connecting…','status.connected': 'Connected',+ 'status.reconnecting': 'Reconnecting…',+ 'status.givenUp': 'Given up',+ 'status.nextRetry': ' (next retry: {hint})',+ '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.',+ 'remove.confirm.cancel': 'Cancel',+ 'remove.confirm.ok': 'Remove it',+ 'bridge.error': 'Failed to open the remote window: ',+ 'sync.title': 'Sync to remote',+ 'sync.desc': 'Copy this machine\'s installed plugins and user-level skills to a connected machine: plugins install remotely via dsh plugin add; skills stream as a tar into the remote ~/.dsh/skills. Multi-select.',+ 'sync.notConnected': 'No connected machines. Connect one first, then come back to sync.',+ 'sync.target': 'Target machine: ',+ 'sync.plugins': 'Plugins',+ 'sync.skills': 'Skills',+ 'sync.noPlugins': 'No plugin dependencies in the local profile.',+ 'sync.noSkills': 'No user-level skills.',+ 'sync.apply': 'Sync selection',+ 'sync.applying': 'Syncing…',+ 'sync.refresh': 'Refresh list',+ 'sync.loadFailed': 'Failed to load the sync list: ',+ 'sync.applyFailed': 'The sync request failed: ',+ 'sync.done': 'Sync finished: {ok}/{total} items succeeded.',+ 'sync.itemOk': 'synced',+ 'sync.itemFailed': 'failed','progress.handshake': 'Connecting over SSH…','progress.starting': 'Starting the remote instance…','progress.probing': 'Health check {attempt}/{total}…',diff --git a/packages/dsh-tauri-ssh-ui/src/client/service/bridge.ts b/packages/dsh-tauri-ssh-ui/src/client/service/bridge.tsnew file mode 100644index 00000000..05960cc6--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/service/bridge.ts@@ -0,0 +1,18 @@+/**+ * The desktop-bridge face (C-BRIDGE, S5 owns the shell commands): probing+ * whether this page sits inside the desktop's iframe invoke bridge, and+ * asking the shell to open (or focus) a machine's remote window. Both rides+ * go through `invokeBridgedTauri` — a timeout or rejection on the ping means+ * pure web, where the popup affordance simply never shows.+ * @module dsh-tauri-ssh-ui/client/service/bridge+ */++import type { RemoteBridge } from '../types/index.js'+import { invokeBridgedTauri } from 'dsh-tauri/client'+import { REMOTE_BRIDGE_PING_COMMAND, REMOTE_OPEN_WINDOW_COMMAND } from '../constants/index.js'++/** The real desktop bridge: Tauri commands over the iframe postMessage relay. */+export const desktopBridge: RemoteBridge = {+ probe: () => invokeBridgedTauri(REMOTE_BRIDGE_PING_COMMAND),+ openWindow: (machineId, url) => invokeBridgedTauri(REMOTE_OPEN_WINDOW_COMMAND, { machineId, url }),+}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.tsindex b69314a3..84e53f68 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@@ -1,6 +1,6 @@import type { FetchFn, MachineRow, SshApiResponse } from './index.js'import { describe, expect, it, vi } from 'vitest'-import { machineRowOf, MachinesStore, savePayloadOf } from './index.js'+import { machineEventsOf, machineRowOf, MachinesStore, savePayloadOf, toggleSelection } from './index.js'type FetchMock = ReturnType<typeof vi.fn<FetchFn>>@@ -361,3 +361,171 @@ describe('machinesStore', () => {expect(store.getSnapshot()).toBe(store.store.getSnapshot())})})++describe('connection-state vocabulary', () => {+ it('reads the C-STATE states and the next-retry hint', async () => {+ const { store } = boot({+ ok: true,+ value: { items: [{ ...machineA, state: 'reconnecting', nextRetryHint: 'in 8s' }] },+ })+ await store.load()+ expect(store.getSnapshot().statuses.a).toMatchObject({ state: 'reconnecting', nextRetryHint: 'in 8s' })+ })++ it('reads unknown wire states as disconnected', async () => {+ const { store } = boot({+ ok: true,+ value: { items: [{ ...machineA, state: 'warping' }] },+ })+ await store.load()+ expect(store.getSnapshot().statuses.a?.state).toBe('disconnected')+ })+})++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' },+ ] })).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' },+ ])+ expect(machineEventsOf(undefined)).toEqual([])+ expect(machineEventsOf({ events: 'nope' })).toEqual([])+ expect(machineEventsOf({ events: [{ machineId: 'a', line: 'x' }, 'junk'] })).toEqual([])+ })+})++describe('event polling', () => {+ /** A fetch mock that answers machine.list and sequential machine.events payloads. */+ function eventsFetch(eventBatches: unknown[][]): FetchMock {+ let batch = 0+ return vi.fn<FetchFn>(async (_url, init) => {+ const body = JSON.parse(String(init.body)) as { method: string }+ if (body.method === 'machine.events') {+ const events = eventBatches[Math.min(batch, eventBatches.length - 1)] ?? []+ batch += 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+ })+ }++ 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' },+ ],+ ])+ 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 })+ })++ it('turns the channel off after the host refuses it once', async () => {+ const fetchFn = vi.fn<FetchFn>(async (_url, init) => {+ const body = JSON.parse(String(init.body)) as { method: string }+ 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+ })+ const store = new MachinesStore(fetchFn)+ await store.poll()+ await store.poll()+ await store.poll()+ const eventsCalls = fetchFn.mock.calls+ .filter(call => (JSON.parse(String(call[1]?.body)) as { method: string }).method === 'machine.events')+ expect(eventsCalls).toHaveLength(1)+ // The refusal never fails the page.+ expect(store.getSnapshot().error).toBeNull()+ })+})++describe('toggleSelection', () => {+ it('toggles membership independently per key', () => {+ let selected = toggleSelection(new Set(), 'a')+ selected = toggleSelection(selected, 'b')+ expect([...selected].sort()).toEqual(['a', 'b'])+ selected = toggleSelection(selected, 'a')+ expect([...selected].sort()).toEqual(['b'])+ })+})++describe('sync state', () => {+ /** A fetch mock answering per method. */+ function syncFetch(routes: Record<string, unknown>): FetchMock {+ return vi.fn<FetchFn>(async (_url, init) => {+ const body = JSON.parse(String(init.body)) as { method: string }+ return { json: async () => ({ ok: true, value: routes[body.method] ?? {} }) } as unknown as Response+ })+ }++ it('loads the preview into the sync slice', async () => {+ const store = new MachinesStore(syncFetch({+ 'sync.preview': { plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }], skills: [{ name: 's', root: 'dsh' }] },+ }))+ await store.loadSyncPreview()+ expect(store.getSnapshot().sync).toMatchObject({+ status: 'ready',+ preview: {+ plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }],+ skills: [{ name: 's', root: 'dsh' }],+ },+ })+ })++ it('settles a preview failure as the sync error state', async () => {+ const fetchFn = vi.fn<FetchFn>(async () => ({ json: async () => ({ ok: false, error: { code: 'internal', message: 'nope' } }) }) as unknown as Response)+ const store = new MachinesStore(fetchFn)+ await store.loadSyncPreview()+ expect(store.getSnapshot().sync).toMatchObject({ status: 'error', error: 'nope' })+ })++ it('applies a selection and lands the per-item results', async () => {+ const fetchFn = syncFetch({+ 'sync.apply': { items: [+ { kind: 'plugin', name: 'p', ok: true },+ { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1' },+ ] },+ })+ const store = new MachinesStore(fetchFn)+ await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [{ name: 's', root: 'dsh' }])+ const sync = store.getSnapshot().sync+ expect(sync.applying).toBe(false)+ expect(sync.error).toBeNull()+ expect(sync.results).toEqual([+ { kind: 'plugin', name: 'p', ok: true },+ { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1' },+ ])+ const applyCall = fetchFn.mock.calls+ .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })+ .find(call => call.method === 'sync.apply')+ expect(applyCall?.payload).toEqual({+ machineId: 'a',+ plugins: [{ name: 'p', spec: 'github:a/b' }],+ skills: [{ name: 's', root: 'dsh' }],+ })+ })++ it('settles an apply failure as the sync error without losing applying=false', async () => {+ const fetchFn = vi.fn<FetchFn>(async () => ({ json: async () => ({ ok: false, error: { code: 'machine-sync-failed', message: 'ssh down' } }) }) as unknown as Response)+ const store = new MachinesStore(fetchFn)+ await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [])+ expect(store.getSnapshot().sync).toMatchObject({ applying: false, error: 'ssh down' })+ })+})diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.tsindex 04263c76..546c347a 100644--- a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts@@ -9,7 +9,9 @@* @module dsh-tauri-ssh-ui/client/store*/+import type { MachineLifecycleState, SshMachineEvent, SyncApplyResult, SyncItemResult, SyncPreview } from '../types/index.js'import { SSH_API_PATH } from '../constants/index.js'+import { isLifecycleState } from '../types/index.js'/** One redacted machine row (secret fields live only in the form). */export interface MachineRow {@@ -36,7 +38,10 @@ export interface SecretValues {/** Live transport status of one machine, from the /api-ssh list. */export interface MachineStatus {- state: 'disconnected' | 'connecting' | 'connected'+ /** 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?: stringtunnelBaseUrl?: stringlastError?: string/** Whether the last failure was "dsh not installed on the remote" (offers install). */@@ -60,6 +65,18 @@ export type SshApiResponse= | { ok: true, value: unknown }| { ok: false, error: { code: string, message: string } }+/** The sync panel's slice of the page state. */+export interface SyncPanelState {+ status: 'idle' | 'loading' | 'ready' | 'error'+ error: string | null+ /** The selectable plugins and skills (null until a preview lands). */+ preview: SyncPreview | null+ /** Whether a sync.apply is in flight. */+ applying: boolean+ /** The latest apply outcome, one entry per requested item; null before the first. */+ results: SyncItemResult[] | null+}+/** Page state published to the component through the snapshot seam. */export interface MachinesPageState {status: 'idle' | 'loading' | 'ready' | 'error'@@ -70,12 +87,16 @@ export interface MachinesPageState {discovered: MachineRow[]/** Live status per machine id. */statuses: Record<string, MachineStatus>+ /** Streaming log lines per machine id (the S2 event channel; capped tail). */+ logs: Record<string, string[]>/** 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. */notice: string | null/** The latest install outcome per machine id (shown under the card). */installResults: Record<string, InstallResult>+ /** The sync-to-remote panel state. */+ sync: SyncPanelState}/** The fetch seam (window.fetch in the browser, fakes in tests). */@@ -111,6 +132,117 @@ function messageOf(error: unknown): string {return error instanceof Error ? error.message : String(error)}+/** Read one wire state through the C-STATE vocabulary; unknowns read as disconnected. */+function lifecycleStateOf(raw: unknown): MachineLifecycleState {+ return isLifecycleState(raw) ? raw : 'disconnected'+}++/** How many log lines one machine keeps (the streaming tail). */+const LOG_TAIL_LINES = 300++/** Parse one machine.events value; malformed entries are dropped, not fatal. */+export function machineEventsOf(value: unknown): SshMachineEvent[] {+ if (typeof value !== 'object' || value === null)+ return []+ const events = (value as { events?: unknown }).events+ if (!Array.isArray(events))+ return []+ const out: SshMachineEvent[] = []+ for (const entry of events) {+ if (typeof entry !== 'object' || entry === null)+ continue+ 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')+ continue+ if (event.stage !== undefined && typeof event.stage !== 'string')+ continue+ out.push({+ seq: event.seq,+ ts: typeof event.ts === 'number' ? event.ts : 0,+ machineId: event.machineId,+ stage: typeof event.stage === 'string' ? event.stage : '',+ line: event.line,+ ...event.terminal === true ? { terminal: true } : {},+ ...typeof event.reason === 'string' ? { reason: event.reason } : {},+ })+ }+ return out+}++/** Parse one sync.preview value; null when the shape is wrong. */+export function syncPreviewOf(value: unknown): SyncPreview | null {+ if (typeof value !== 'object' || value === null)+ return null+ const raw = value as { plugins?: unknown, skills?: unknown }+ if (!Array.isArray(raw.plugins) || !Array.isArray(raw.skills))+ return null+ const plugins = raw.plugins.flatMap((entry): SyncPreview['plugins'] => {+ if (typeof entry !== 'object' || entry === null)+ return []+ const item = entry as Record<string, unknown>+ if (typeof item.name !== 'string' || typeof item.spec !== 'string')+ return []+ return [{+ name: item.name,+ spec: item.spec,+ syncable: item.syncable === true,+ ...typeof item.reason === 'string' ? { reason: item.reason } : {},+ }]+ })+ const skills = raw.skills.flatMap((entry): SyncPreview['skills'] => {+ if (typeof entry !== 'object' || entry === null)+ return []+ const item = entry as Record<string, unknown>+ if (typeof item.name !== 'string' || typeof item.root !== 'string')+ return []+ return [{ name: item.name, root: item.root }]+ })+ return { plugins, skills }+}++/** Parse one sync.apply value; null when the shape is wrong. */+export function syncApplyResultOf(value: unknown): SyncApplyResult | null {+ if (typeof value !== 'object' || value === null)+ return null+ const items = (value as { items?: unknown }).items+ if (!Array.isArray(items))+ return null+ const out: SyncItemResult[] = []+ for (const entry of items) {+ if (typeof entry !== 'object' || entry === null)+ continue+ const item = entry as Record<string, unknown>+ if (typeof item.name !== 'string' || typeof item.ok !== 'boolean')+ continue+ if (item.kind !== 'plugin' && item.kind !== 'skill')+ continue+ out.push({+ kind: item.kind,+ name: item.name,+ ...typeof item.root === 'string' ? { root: item.root } : {},+ ok: item.ok,+ ...typeof item.error === 'string' ? { error: item.error } : {},+ })+ }+ return { items: out }+}++/**+ * The multi-select toggle: independent Set membership per key. This is the+ * semantic the sync items needed (the old panel behaved like a radio group —+ * picking one item silently dropped the others).+ */+export function toggleSelection(selected: ReadonlySet<string>, key: string): Set<string> {+ const next = new Set(selected)+ if (next.has(key))+ next.delete(key)+ else+ next.add(key)+ return next+}+/** Parse one /api-ssh envelope; non-ok envelopes throw. */async function envelopeOf(response: Response): Promise<SshApiResponse> {return await response.json() as SshApiResponse@@ -194,6 +326,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++ /** Whether the host still gets asked for machine.events (off after first refusal). */+ private eventsSupported = true+/*** @param fetchFn - the /api-ssh transport (window.fetch in the browser).*/@@ -204,9 +342,11 @@ export class MachinesStore {machines: [],discovered: [],statuses: {},+ logs: {},busy: {},notice: null,installResults: {},+ sync: { status: 'idle', error: null, preview: null, applying: false, results: null },})}@@ -235,7 +375,9 @@ export class MachinesStore {const discovered = (list.discovered ?? []).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)const statuses: Record<string, MachineStatus> = {}for (const item of [...(list.items ?? []), ...(list.discovered ?? [])]) {- const status: MachineStatus = { state: item.state }+ const status: MachineStatus = { state: lifecycleStateOf(item.state) }+ if (typeof item.nextRetryHint === 'string' && item.nextRetryHint !== '')+ status.nextRetryHint = item.nextRetryHintif (item.tunnelBaseUrl !== undefined)status.tunnelBaseUrl = item.tunnelBaseUrlif (item.lastError !== undefined)@@ -276,6 +418,7 @@ export class MachinesStore {async poll(): Promise<void> {try {this.applyList(await this.callApi<{ items?: MachineListItem[], discovered?: MachineListItem[] }>('machine.list', {}))+ await this.pollEvents()}catch (error) {this.store.update((state) => {@@ -284,6 +427,43 @@ 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.+ */+ private async pollEvents(): Promise<void> {+ if (!this.eventsSupported)+ return+ let events: SshMachineEvent[]+ try {+ events = machineEventsOf(await this.callApi<unknown>('machine.events', {+ ...this.lastEventSeq === 0 ? {} : { after: this.lastEventSeq },+ }))+ }+ 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) => {+ for (const [machineId, lines] of byMachine) {+ state.logs[machineId] = [...(state.logs[machineId] ?? []), ...lines].slice(-LOG_TAIL_LINES)+ }+ })+ }+/*** Persist the form: machine.save per row (write-only secrets; absent fields* keep the stored value) and machine.remove for ids that vanished.@@ -391,4 +571,64 @@ export class MachinesStore {await this.load()})}++ /** Load the sync selection list (local plugins and skills) from sync.preview. */+ async loadSyncPreview(): Promise<void> {+ this.store.update((state) => {+ state.sync.status = 'loading'+ state.sync.error = null+ })+ try {+ const preview = syncPreviewOf(await this.callApi<unknown>('sync.preview', {}))+ if (preview === null)+ throw new Error('malformed sync.preview payload')+ this.store.update((state) => {+ state.sync.status = 'ready'+ state.sync.preview = preview+ })+ }+ catch (error) {+ this.store.update((state) => {+ state.sync.status = 'error'+ state.sync.error = messageOf(error)+ })+ }+ }++ /**+ * Sync one selection to a machine. The per-item outcomes land in+ * `state.sync.results` even on partial failure — a request-level failure+ * (session unreachable) surfaces as `state.sync.error`.+ * @param machineId - the connected target machine.+ * @param plugins - the selected plugin refs.+ * @param skills - the selected skill refs.+ */+ async applySync(machineId: string, plugins: SyncPreview['plugins'], skills: SyncPreview['skills']): Promise<void> {+ this.store.update((state) => {+ state.sync.applying = true+ state.sync.error = null+ })+ try {+ const result = syncApplyResultOf(await this.callApi<unknown>('sync.apply', {+ machineId,+ plugins: plugins.map(plugin => ({ name: plugin.name, spec: plugin.spec })),+ skills: skills.map(skill => ({ name: skill.name, root: skill.root })),+ }))+ if (result === null)+ throw new Error('malformed sync.apply payload')+ this.store.update((state) => {+ state.sync.results = result.items+ })+ }+ catch (error) {+ this.store.update((state) => {+ state.sync.error = messageOf(error)+ })+ }+ finally {+ this.store.update((state) => {+ state.sync.applying = false+ })+ }+ }}diff --git a/packages/dsh-tauri-ssh-ui/src/client/types/index.ts b/packages/dsh-tauri-ssh-ui/src/client/types/index.tsindex 225cc53d..f585fa29 100644--- a/packages/dsh-tauri-ssh-ui/src/client/types/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/types/index.ts@@ -38,3 +38,15 @@ export interface UiContext {slots: SlotsServicelocale: LocaleService}++export type {+ MachineLifecycleState,+ RemoteBridge,+ SshMachineEvent,+ SyncApplyResult,+ SyncItemResult,+ SyncPluginItem,+ SyncPreview,+ SyncSkillItem,+} from './sync.js'+export { isLifecycleState } from './sync.js'diff --git a/packages/dsh-tauri-ssh-ui/src/client/types/sync.ts b/packages/dsh-tauri-ssh-ui/src/client/types/sync.tsnew file mode 100644index 00000000..b2f57a1d--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/client/types/sync.ts@@ -0,0 +1,83 @@+/**+ * Client-side mirrors of the S4-owned sync vocabulary, the S2-owned machine+ * event channel, and the S3-owned connection-state vocabulary this panel+ * consumes (the contracts are drafted by their owners; these shapes are the+ * panel's tolerant readers of them).+ * @module dsh-tauri-ssh-ui/client/types/sync+ */++/**+ * 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.+ */+export type MachineLifecycleState+ = | 'disconnected'+ | 'testing'+ | 'connecting'+ | 'connected'+ | 'reconnecting'+ | 'given-up'++/** Whether a raw value is one of the lifecycle states. */+export function isLifecycleState(value: unknown): value is MachineLifecycleState {+ return value === 'disconnected'+ || value === 'testing'+ || value === 'connecting'+ || value === 'connected'+ || value === 'reconnecting'+ || value === 'given-up'+}++/** One machine event from the polled `machine.events` channel (C-EVENT, S2-owned). */+export interface SshMachineEvent {+ seq: number+ ts: number+ machineId: string+ stage: string+ line: string+ terminal?: boolean+ reason?: string+}++/** One plugin sync candidate (the `sync.preview` plugins list member). */+export interface SyncPluginItem {+ name: string+ spec: string+ syncable: boolean+ reason?: string+}++/** One skill sync candidate (the `sync.preview` skills list member). */+export interface SyncSkillItem {+ name: string+ root: string+}++/** The `sync.preview` value. */+export interface SyncPreview {+ plugins: SyncPluginItem[]+ skills: SyncSkillItem[]+}++/** Outcome of exactly one synced item (the `sync.apply` items member). */+export interface SyncItemResult {+ kind: 'plugin' | 'skill'+ name: string+ root?: string+ ok: boolean+ error?: string+}++/** The `sync.apply` value. */+export interface SyncApplyResult {+ items: SyncItemResult[]+}++/** The desktop iframe bridge face (C-BRIDGE, S5-owned commands). */+export interface RemoteBridge {+ /** Probe whether the desktop invoke bridge answers (timeout/rejection = pure web). */+ probe: () => Promise<unknown>+ /** Ask the desktop shell to open (or focus) the machine's remote window. */+ openWindow: (machineId: string, url: string) => Promise<unknown>+}diff --git a/packages/dsh-tauri-ssh-ui/src/types/dsh.d.ts b/packages/dsh-tauri-ssh-ui/src/types/dsh.d.tsnew file mode 100644index 00000000..77aad9a6--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/src/types/dsh.d.ts@@ -0,0 +1,20 @@+/**+ * Host-runtime compile-time declarations for the modules this plugin's client+ * bundle requires through the DSH module table (the scheduler-plugin+ * precedent): the desktop invoke bridge re-exported by `dsh-tauri/client`.+ * No runtime dependency is declared — the loader resolves the specifier+ * against the module table (see the `dsh-tauri` inject entry in+ * package.json), so these mirrors exist purely for `tsc`.+ */++declare module 'dsh-tauri/client' {+ /**+ * Call one Tauri command through the desktop iframe invoke bridge; the+ * promise rejects on a command error or when the host never answers+ * (timeout — i.e. this page is not embedded in the desktop shell).+ */+ export function invokeBridgedTauri<T>(+ cmd: string,+ args?: Record<string, unknown>,+ ): Promise<T>+}diff --git a/packages/dsh-tauri-ssh-ui/vitest.config.ts b/packages/dsh-tauri-ssh-ui/vitest.config.tsnew file mode 100644index 00000000..1a826970--- /dev/null+++ b/packages/dsh-tauri-ssh-ui/vitest.config.ts@@ -0,0 +1,31 @@+import { fileURLToPath } from 'node:url'+import { defineConfig } from 'vitest/config'++/**+ * The section components render the official UI primitives, whose package+ * ships real `.module.css` sidecars and (under pnpm) a nested react@18 —+ * while this package develops against the workspace react. In the deployed+ * ModuleLoader there is exactly one platform react for both; these test-time+ * settings recreate that: the primitives package is inlined so Vite can+ * process its CSS imports, and every react specifier is pinned to the+ * workspace copy so jsdom mounts one renderer, not two.+ */+const reactRoot = fileURLToPath(new URL('../../node_modules/react', import.meta.url))++export default defineConfig({+ resolve: {+ alias: [+ { find: /^react$/, replacement: reactRoot },+ { find: /^react\/jsx-runtime$/, replacement: `${reactRoot}/jsx-runtime.js` },+ { find: /^react\/jsx-dev-runtime$/, replacement: `${reactRoot}/jsx-dev-runtime.js` },+ ],+ },+ test: {+ css: true,+ server: {+ deps: {+ inline: [/@deepseek-ai\/dsh-client-ui-primitives/],+ },+ },+ },+})diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.tsindex 59e2be96..9d15d97a 100644--- a/packages/dsh-tauri-ssh/src/host/apply.ts+++ b/packages/dsh-tauri-ssh/src/host/apply.ts@@ -101,7 +101,7 @@ export class SshRemoteService implements SshApiHost {profileDependencies: profileDependenciesReader(),scanSkills: skillRootsScanner(),packSkills: tarPacker(),- openSession: (machineId) => this.manager.openSession(machineId),+ openSession: machineId => this.manager.openSession(machineId),...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },})this.manager.refreshProfiles(this.applyStartDefaults(this.manualProfiles()))diff --git a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts b/packages/dsh-tauri-ssh/src/host/service/sync-local.tsindex 8cf047ac..64ee5d24 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync-local.ts@@ -6,13 +6,14 @@* @module dsh-tauri-ssh/host/service/sync-local*/+import type { Buffer } from 'node:buffer'import type { SyncSkillRoot } from '../types/index.js'import { execFile } from 'node:child_process'-import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'import { homedir } from 'node:os'import process from 'node:process'-import { join } from 'pathe'import { promisify } from 'node:util'+import { join } from 'pathe'const execFileAsync = promisify(execFile)diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync.test.tsindex 617d6e54..a2bd9c67 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts@@ -1,4 +1,5 @@import type { SshExecResult, SshSession } from './transport.js'+import { Buffer } from 'node:buffer'import { describe, expect, it, vi } from 'vitest'import { MachineId } from '../types/index.js'import { buildPreview, classifySpec, pluginAddCommand, skillExtractCommand, SyncEngine } from './sync.js'@@ -86,7 +87,7 @@ describe('command builders', () => {})})-describe('SyncEngine.apply', () => {+describe('syncEngine.apply', () => {const machine = MachineId('m1')it('returns per-item successes when everything lands', async () => {diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-ssh/src/host/service/sync.tsindex 018a9188..b86e0a31 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync.ts@@ -12,6 +12,7 @@* @module dsh-tauri-ssh/host/service/sync*/+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'@@ -28,9 +29,9 @@ export function classifySpec(spec: string): { syncable: boolean, reason?: stringconst value = spec.trim()if (value === '')return { syncable: false, reason: 'empty dependency spec' }- if (/^(github:|git\+|git@)/u.test(value))+ if (/^(?:github:|git\+|git@)/u.test(value))return { syncable: true }- if (/^(file:|link:|workspace:)/u.test(value))+ if (/^(?:file:|link:|workspace:)/u.test(value))return { syncable: false, reason: 'local-path dependency; it cannot be resolved on the remote' }if (/^https?:\/\//u.test(value))return { syncable: false, reason: 'URL dependencies are not supported' }