DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh-ui): 同步页重做——逐项进度、结果合并重试、装进机器自己的档案
Menghuan1918a27b9047f150
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 bee7beab..4db30a49 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@@ -441,6 +441,7 @@ const STEP_KEY_OF: Record<ProgressPhase, SshKey> = {installing: 'step.installing',starting: 'step.starting',probing: 'step.probing',+ syncing: 'step.syncing',}/** The step rail: the phases one operation actually walked, latest current. */@@ -497,6 +498,11 @@ function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => str.replace('{attempt}', String(progress.attempt ?? '?')).replace('{total}', String(progress.total ?? '?'))}+ if (progress?.phase === 'syncing') {+ return t('progress.syncing')+ .replace('{attempt}', String(progress.attempt ?? '?'))+ .replace('{total}', String(progress.total ?? '?'))+ }const base = status === undefined? t('status.disconnected'): t(STATUS_KEY_OF[status.state])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.tsxindex 5ba7a98b..c2966797 100644--- 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.tsx@@ -72,49 +72,72 @@ function connectedStore(fetchFn: FetchMock): MachinesStore {}describe('syncPanel', () => {- it('keeps every independently selected item (multi-select, not a radio group)', async () => {+ it('starts with every syncable item ticked and keeps independent tick state', 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')+ await waitFor(() => expect(screen.getByTestId('sync-row-dsh-market')).toBeTruthy())+ // 默认=全选可同步项(不可同步的 local-thing 恒不勾)+ expect(screen.getByTestId('sync-row-dsh-market').getAttribute('aria-checked')).toBe('true')+ expect(screen.getByTestId('sync-row-alpha').getAttribute('aria-checked')).toBe('true')+ expect(screen.getByTestId('sync-row-beta').getAttribute('aria-checked')).toBe('true')+ expect(screen.getByTestId('sync-row-local-thing').getAttribute('aria-checked')).toBe('false')+ expect(screen.getByTestId('sync-selected').textContent).toContain('1 plugins and 2 skills selected')++ // 取消一项不动其它项(多选而非单选)+ fireEvent.click(screen.getByTestId('sync-row-dsh-market'))+ expect(screen.getByTestId('sync-row-dsh-market').getAttribute('aria-checked')).toBe('false')+ expect(screen.getByTestId('sync-row-alpha').getAttribute('aria-checked')).toBe('true')+ expect(screen.getByTestId('sync-selected').textContent).toContain('0 plugins and 2 skills selected')++ // 清空 → 全选回来,计数复位+ fireEvent.click(screen.getByText('Clear'))+ expect(screen.getByTestId('sync-row-alpha').getAttribute('aria-checked')).toBe('false')+ fireEvent.click(screen.getByText('Select all'))+ expect(screen.getByTestId('sync-row-dsh-market').getAttribute('aria-checked')).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)+ await waitFor(() => expect(screen.getByTestId('sync-row-local-thing')).toBeTruthy())+ expect(screen.getByTestId('sync-row-local-thing').hasAttribute('disabled')).toBe(true)expect(screen.getByText(/local-path dependency/)).toBeTruthy()})- it('sends the whole multi-selection to sync.apply', async () => {+ it('sends the whole ticked 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' }],+ skills: [{ name: 'alpha', root: 'dsh' }, { name: 'beta', root: 'agents' }],})})- it('renders partial failures per item with reasons', async () => {- const store = connectedStore(routeFetch({}))+ it('shows per-item live progress while an apply runs', async () => {+ const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))+ store.store.update((state) => {+ state.sync.applying = true+ state.statuses = { a: { state: 'connected', progress: { phase: 'syncing', attempt: 3, total: 5, item: 'dsh-tauri-ssh-ui' } } }+ })+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-progress')).toBeTruthy())+ expect(screen.getByTestId('sync-progress').textContent).toContain('3/5')+ expect(screen.getByTestId('sync-progress').textContent).toContain('dsh-tauri-ssh-ui')+ // 3/5 起跑(已完成 2 项)→ 进度条 40%+ const fill = screen.getByTestId('sync-progress').querySelector('[class*="sync-bar-fill"]') as HTMLElement+ expect(fill.style.width).toBe('40%')+ expect(screen.getByTestId('sync-apply').textContent).toContain('Syncing')+ })++ it('renders partial failures per item with reasons and a retry that re-sends only them', async () => {+ const fetchFn = routeFetch({ 'sync.apply': { items: [] }, 'machine.list': { items: [] } })+ const store = connectedStore(fetchFn)store.store.update((state) => {state.sync.results = [{ kind: 'plugin', name: 'dsh-market', ok: true },@@ -128,7 +151,15 @@ describe('syncPanel', () => {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()+ expect(screen.getByText(/1 succeeded, 1 failed/)).toBeTruthy()++ fireEvent.click(screen.getByTestId('sync-retry'))+ await waitFor(() => expect(applyCalls(fetchFn)).toHaveLength(1))+ expect(applyCalls(fetchFn)[0]).toEqual({+ machineId: 'a',+ plugins: [],+ skills: [{ name: 'alpha', root: 'dsh' }],+ })})it('renders a complete failure with every reason visible', async () => {@@ -141,7 +172,7 @@ describe('syncPanel', () => {})render(<SyncPanel store={store} t={t} />)await waitFor(() => expect(screen.getByTestId('sync-results')).toBeTruthy())- expect(screen.getByText(/0\/2 items succeeded/)).toBeTruthy()+ expect(screen.getByText(/0 succeeded, 2 failed/)).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')})@@ -149,11 +180,45 @@ describe('syncPanel', () => {it('surfaces a request-level failure without swallowing previous results', async () => {const fetchFn = routeFetch({ 'sync.apply': { items: [] } }, ['sync.apply'])const store = connectedStore(fetchFn)+ store.store.update((state) => {+ state.sync.results = [{ kind: 'plugin', name: 'dsh-market', ok: true }]+ })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())+ expect(screen.getByTestId('sync-result-dsh-market')).toBeTruthy()+ })++ it('disables apply with an empty tick set', async () => {+ const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByText('Clear')).toBeTruthy())+ fireEvent.click(screen.getByText('Clear'))+ expect(screen.getByTestId('sync-apply').hasAttribute('disabled')).toBe(true)+ })++ it('loads the machine list itself and offers the connected machine as the target', async () => {+ // 本分区可以不经机器页直达:store 还没拉过列表时它必须自己拉一次,+ // 否则已连接的机器在这里看不见(回归:首版漏了这步,页面永远显示空态)。+ const fetchFn = routeFetch({+ 'machine.list': { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] },+ 'sync.preview': preview,+ })+ const store = new MachinesStore(fetchFn)+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-target-a')).toBeTruthy())+ expect(apiMethods(fetchFn)).toContain('machine.list')+ expect(screen.getByTestId('sync-apply').textContent).toContain('Sync to alpha')+ expect(screen.queryByTestId('sync-empty')).toBeNull()+ })++ it('points a remote-session instance back at the initiating machine', async () => {+ const store = new MachinesStore(routeFetch({ 'machine.list': { items: [] }, 'session.role': { remote: true, origin: 'ops' } }))+ render(<SyncPanel store={store} t={t} />)+ await waitFor(() => expect(screen.getByTestId('sync-remote-note')).toBeTruthy())+ expect(screen.getByTestId('sync-remote-note').textContent).toContain('Sync to remote')+ expect(screen.queryByTestId('sync-apply')).toBeNull()})it('shows the not-connected note when no machine is connected', async () => {@@ -165,7 +230,8 @@ describe('syncPanel', () => {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())+ await waitFor(() => expect(screen.getByTestId('sync-empty')).toBeTruthy())+ expect(screen.getByTestId('sync-empty').textContent).toContain('No connected machines')expect(screen.queryByTestId('sync-apply')).toBeNull()})@@ -180,6 +246,11 @@ describe('syncPanel', () => {})})+/** The /api-ssh methods the fake fetch received, in call order. */+function apiMethods(fetchFn: ReturnType<typeof vi.fn>): string[] {+ return fetchFn.mock.calls.map(call => (JSON.parse(String(call[1]?.body)) as { method: string }).method)+}+/** The sync.apply request bodies the fake fetch received. */function applyCalls(fetchFn: ReturnType<typeof vi.fn>): Array<Record<string, unknown>> {return fetchFn.mock.callsdiff --git a/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsxindex fc7272bc..de9f6b43 100644--- a/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx+++ b/packages/dsh-tauri-ssh-ui/src/client/components/sync-panel.tsx@@ -1,23 +1,24 @@'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.+ * The sync-to-remote page: pick a connected target, tick the local plugins and+ * user-level skills to move (all syncable items start ticked — the entry point+ * is called "sync to remote", so the default answer is "everything"), then+ * watch each item settle. Live progress comes from the target's machine status+ * (`phase: 'syncing'`), which the host publishes item by item; outcomes merge+ * across runs so a retry keeps the earlier batch visible. All domain state+ * lives in the injected {@link MachinesStore}; only the selection and the+ * target are local.* @module dsh-tauri-ssh-ui/client/components/sync-panel*/import type { ReactNode } from 'react'import type { SshKey } from '../locales/index'import type { MachineRow, MachinesStore } from '../store/index'-import type { SyncItemResult } from '../types/index'+import type { SyncItemResult, SyncPluginItem, SyncSkillItem } from '../types/index'import { Button, Pill, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'import { useEffect, useState, useSyncExternalStore } from 'react'-import { toggleSelection } from '../store/index'+import { pluginKeyOf, skillKeyOf, syncKeyOf, toggleSelection } from '../store/index'import { cls } from '../styles'/** The panel props: the framework `t` seat plus the injected store. */@@ -26,10 +27,22 @@ export interface SyncPanelProps {t: (key: SshKey) => string}-/** Render the sync panel over the store snapshot. */+/** One selectable row of either group (plugins and skills share the layout). */+interface SelectableRow {+ key: string+ name: string+ /** The muted right-hand metadata: the dependency spec, or the skill root. */+ meta: string+ syncable: boolean+ reason?: string+}++/** Render the sync page 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())+ // 选择态:null = 还没动过手,按「全选可同步项」派生(入口叫「同步到远端」,+ // 默认答案就是「都同步」);一旦勾选/清空/重试就以显式集合为准。+ const [touched, setTouched] = useState<ReadonlySet<string> | null>(null)const [targetId, setTargetId] = useState<string | null>(null)useEffect(() => {@@ -37,17 +50,59 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {void store.loadSyncPreview()}, [state.sync.status, store])+ // 目标候选来自 machine.list:本分区可以不经机器页直达,必须自己拉一次,+ // 否则已连接的机器在这里看不见(两页共用同一个 store 实例,各拉各的)。+ useEffect(() => {+ if (state.status === 'idle')+ void store.load()+ }, [state.status, store])++ const preview = state.sync.preview++ // 同步期间轮询机器状态:逐项进度就长在这条通道上(phase: 'syncing')。+ const applying = state.sync.applying+ useEffect(() => {+ if (!applying)+ return+ const timer = setInterval(() => void store.poll(), 1000)+ return () => clearInterval(timer)+ }, [applying, 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 pluginRows: SelectableRow[] = (preview?.plugins ?? []).map(plugin => ({+ key: pluginKeyOf(plugin),+ name: plugin.name,+ meta: plugin.spec,+ syncable: plugin.syncable,+ ...plugin.reason === undefined ? {} : { reason: plugin.reason },+ }))+ const skillRows: SelectableRow[] = (preview?.skills ?? []).map(skill => ({+ key: skillKeyOf(skill),+ name: skill.name,+ meta: skill.root,+ syncable: true,+ }))+ const selectableKeys = [...pluginRows, ...skillRows].filter(row => row.syncable).map(row => row.key)+ const selected = touched ?? new Set(selectableKeys)+ const plugins = (preview?.plugins ?? []).filter(plugin => selected.has(pluginKeyOf(plugin)))+ const skills = (preview?.skills ?? []).filter(skill => selected.has(skillKeyOf(skill)))+ const canApply = target !== undefined && !applying && (plugins.length > 0 || skills.length > 0)+ const progress = target === undefined ? undefined : state.statuses[target.id]?.progress+ const syncing = progress?.phase === 'syncing' ? progress : undefinedconst apply = (): void => {if (target === undefined)return- void store.applySync(target.id, selectedPlugins, selectedSkills)+ void store.applySync(target.id, plugins, skills)+ }++ const retryFailed = (): void => {+ if (target === undefined || preview === null)+ return+ const failed = failedRefsOf(state.sync.results ?? [], preview)+ setTouched(new Set(failed.keys))+ void store.applySync(target.id, failed.plugins, failed.skills)}return (@@ -57,90 +112,116 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {<h2 className={cls.title}>{t('sync.title')}</h2><p className={cls.intro}>{t('sync.desc')}</p></div>+ <div className={cls.chrome}>+ <Button+ variant="outline"+ size="sm"+ disabled={state.sync.status === 'loading' || applying}+ onClick={() => {+ // 刷新回到派生默认(新出现的可同步项自动纳入),再看一遍计数。+ setTouched(null)+ void store.loadSyncPreview()+ }}+ >+ {t('sync.refresh')}+ </Button>+ </div></div>- {connected.length === 0- ? <p className={cls.hint}>{t('sync.notConnectedHint')}</p>- : (- <>- <div className={cls.syncTargets}>- <span className={cls.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>- {state.sync.status === 'error'- ? null- : preview === null || state.sync.status === 'loading'+ {state.role?.remote === true+ ? <p className={cls.empty} data-testid="sync-remote-note">{t('sync.remoteSessionHint')}</p>+ : connected.length === 0+ ? <p className={cls.empty} data-testid="sync-empty">{t('sync.notConnectedHint')}</p>+ : (+ <>+ <div className={cls.syncTargets}>+ <span className={cls.fieldLabel}>{t('sync.target')}</span>+ {connected.map(machine => (+ <Pill+ key={machine.id}+ active={machine.id === target?.id}+ disabled={applying}+ aria-pressed={machine.id === target?.id}+ data-testid={`sync-target-${machine.id}`}+ onClick={() => setTargetId(machine.id)}+ >+ <span className={cls.syncChip}>+ <StateDot state="done" size={6} />+ {machine.name}+ </span>+ </Pill>+ ))}+ </div>+ {preview === null || state.sync.status === 'loading'? <p className={cls.hint}>{t('loading')}</p>- : (- <div className={cls.syncGroups}>- <div className={cls.syncGroup}>- <span className={cls.fieldLabel}>{t('sync.plugins')}</span>- {preview.plugins.length === 0- ? <p className={cls.hint}>{t('sync.noPlugins')}</p>- : (- <ul className={cls.syncItems}>- {preview.plugins.map(plugin => (- <li key={`plugin:${plugin.spec}`} className={cls.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={cls.syncReason}>{plugin.reason}</span>- : null}- </li>- ))}- </ul>- )}+ : (state.sync.status === 'ready'+ ? (+ <>+ <div className={cls.syncToolbar}>+ <span className={cls.syncCount} data-testid="sync-selected">+ {t('sync.selected')+ .replace('{plugins}', String(plugins.length))+ .replace('{skills}', String(skills.length))}+ </span>+ <Button+ variant="ghost"+ size="sm"+ disabled={applying || selected.size === selectableKeys.length}+ onClick={() => setTouched(new Set(selectableKeys))}+ >+ {t('sync.selectAll')}+ </Button>+ <Button variant="ghost" size="sm" disabled={applying || selected.size === 0} onClick={() => setTouched(new Set())}>+ {t('sync.clear')}+ </Button>+ </div>+ <SyncGroup+ empty={t('sync.noPlugins')}+ label={t('sync.plugins')}+ rows={pluginRows}+ selected={selected}+ t={t}+ onToggle={key => setTouched(toggleSelection(selected, key))}+ />+ <SyncGroup+ empty={t('sync.noSkills')}+ label={t('sync.skills')}+ rows={skillRows}+ selected={selected}+ t={t}+ onToggle={key => setTouched(toggleSelection(selected, key))}+ />+ </>+ )+ : null)}+ <div className={cls.syncActions}>+ <Button variant="primary" size="sm" disabled={!canApply} data-testid="sync-apply" onClick={apply}>+ {applying+ ? t('sync.applying')+ : target === undefined+ ? t('sync.apply')+ : t('sync.applyTo').replace('{name}', target.name)}+ </Button>+ {syncing !== undefined+ ? (+ <div className={cls.syncProgress} data-testid="sync-progress">+ <span className={cls.syncBar} aria-hidden="true">+ <span+ className={cls.syncBarFill}+ style={{ width: `${barPercentOf(syncing.attempt, syncing.total)}%` }}+ />+ </span>+ <span className={cls.syncProgressText}>+ {t('sync.progress')+ .replace('{done}', String(syncing.attempt ?? 0))+ .replace('{total}', String(syncing.total ?? 0))+ .replace('{item}', syncing.item ?? '')}+ </span></div>- <div className={cls.syncGroup}>- <span className={cls.fieldLabel}>{t('sync.skills')}</span>- {preview.skills.length === 0- ? <p className={cls.hint}>{t('sync.noSkills')}</p>- : (- <ul className={cls.syncItems}>- {preview.skills.map(skill => (- <li key={`skill:${skill.root}:${skill.name}`} className={cls.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={cls.syncRoot}>{skill.root}</span>- </Pill>- </li>- ))}- </ul>- )}- </div>- </div>- )}- <div className={cls.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>- </>- )}+ )+ : null}+ </div>+ </>+ )}{state.sync.status === 'error'? (<p className={cls.error} role="alert">@@ -158,22 +239,89 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {): null}{state.sync.results !== null- ? <SyncResults results={state.sync.results} t={t} />+ ? <SyncResults results={state.sync.results} applying={applying} t={t} onRetry={retryFailed} />: 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 {+/** One selection group: a counted header plus one checkbox row per item. */+function SyncGroup({ label, empty, rows, selected, t, onToggle }: {+ label: string+ empty: string+ rows: readonly SelectableRow[]+ selected: ReadonlySet<string>+ t: (key: SshKey) => string+ onToggle: (key: string) => void+}): ReactNode {+ // 计数只算「可同步」的条目:不可同步的行恒不勾,算进去会读出「2/15 已选」的假象。+ const syncable = rows.filter(row => row.syncable)+ const checked = syncable.filter(row => selected.has(row.key)).length+ return (+ <div className={cls.syncGroup}>+ <div className={cls.syncGroupHead}>+ <span className={cls.fieldLabel}>{label}</span>+ {rows.length === 0+ ? null+ : <span className={cls.syncCount}>{t('sync.groupCount').replace('{checked}', String(checked)).replace('{total}', String(syncable.length))}</span>}+ </div>+ {rows.length === 0+ ? <p className={cls.hint}>{empty}</p>+ : (+ <ul className={cls.syncItems}>+ {rows.map(row => (+ <li key={row.key} className={cls.syncItem}>+ <button+ type="button"+ role="checkbox"+ aria-checked={row.syncable && selected.has(row.key)}+ className={cls.syncRow}+ data-testid={`sync-row-${row.name}`}+ disabled={!row.syncable || undefined}+ title={row.reason}+ onClick={() => onToggle(row.key)}+ >+ <span className={cls.syncBox} aria-hidden="true">+ {row.syncable && selected.has(row.key)+ ? (+ <svg fill="none" height="10" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.4" viewBox="0 0 12 12" width="10">+ <path d="M2 6.5 4.6 9 10 3.5" />+ </svg>+ )+ : null}+ </span>+ <span className={cls.syncText}>+ <span className={cls.syncName}>{row.name}</span>+ {row.syncable ? null : <span className={cls.syncReason}>{row.reason ?? t('sync.notSyncable')}</span>}+ </span>+ <span className={cls.syncMeta}>{row.meta}</span>+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ )+}++/** The merged outcome list: every item this page attempted, with the tally. */+function SyncResults({ results, applying, t, onRetry }: {+ results: readonly SyncItemResult[]+ applying: boolean+ t: (key: SshKey) => string+ onRetry: () => void+}): ReactNode {const okCount = results.filter(item => item.ok).length+ const failed = results.length - okCountreturn (<div className={cls.syncResults} data-testid="sync-results">- <p className={cls.syncSummary}>{t('sync.done').replace('{ok}', String(okCount)).replace('{total}', String(results.length))}</p>+ <p className={cls.syncSummary}>+ {t('sync.summary').replace('{ok}', String(okCount)).replace('{failed}', String(failed))}+ </p><ul className={cls.syncItems}>{results.map(item => (<li- key={`${item.kind}:${item.root ?? ''}:${item.name}`}+ key={syncKeyOf(item)}className={cls.syncResult}data-testid={`sync-result-${item.name}`}data-ok={item.ok}@@ -181,7 +329,7 @@ function SyncResults({ results, t }: { results: SyncItemResult[], t: (key: SshKe<StateDot state={item.ok ? 'done' : 'error'} size={8} /><span className={cls.syncResultName}>{item.name}- {item.root !== undefined ? ` (${item.root})` : ''}+ {item.root === undefined ? '' : ` (${item.root})`}</span>{item.ok? <span className={cls.syncOk}>{t('sync.itemOk')}</span>@@ -194,10 +342,37 @@ function SyncResults({ results, t }: { results: SyncItemResult[], t: (key: SshKe</li>))}</ul>+ {failed > 0+ ? (+ <Button variant="outline" size="sm" disabled={applying} data-testid="sync-retry" onClick={onRetry}>+ {t('sync.retryFailed').replace('{count}', String(failed))}+ </Button>+ )+ : null}</div>)}+/** The failed items of the last runs, resolved back to selectable refs. */+function failedRefsOf(+ results: readonly SyncItemResult[],+ preview: { plugins: SyncPluginItem[], skills: SyncSkillItem[] },+): { keys: Set<string>, plugins: SyncPluginItem[], skills: SyncSkillItem[] } {+ const keys = new Set(results.filter(item => !item.ok).map(syncKeyOf))+ return {+ keys,+ plugins: preview.plugins.filter(plugin => keys.has(pluginKeyOf(plugin))),+ skills: preview.skills.filter(skill => keys.has(skillKeyOf(skill))),+ }+}++/** The determinate bar width; an unknown total reads as empty. */+function barPercentOf(attempt: number | undefined, total: number | undefined): number {+ if (total === undefined || total <= 0)+ return 0+ return Math.min(100, Math.round((Math.max(0, (attempt ?? 0) - 1) / total) * 100))+}+/** The connected machines, manual first then discovered, in list order. */function connectedMachinesOf(machines: readonly MachineRow[],diff --git a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts b/packages/dsh-tauri-ssh-ui/src/client/locales/index.tsindex ace8bd26..bf99371f 100644--- a/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/locales/index.ts@@ -33,7 +33,8 @@ export const zh = {'field.user': '用户(可选)','session.remoteTitle': '目前正在 SSH 中','sync.nav': '同步到远端',- 'sync.notConnectedHint': '还没有已连接的机器——先在「SSH 远程机器」里连接一台,即可把插件和 Skill 同步过去。',+ 'sync.notConnectedHint': '还没有已连接的机器——先到「SSH 机器」分区连接一台,再回来同步。',+ 'sync.remoteSessionHint': '本实例正通过 SSH 使用:插件与 Skill 的同步请在发起连接的机器上操作(那里选「同步到远端…」)。','session.remoteHintNamed': '此实例正通过 SSH 来自 {name} 的连接使用;机器的添加、编辑与连接都在发起端操作。','session.remoteHint': '此实例正通过 SSH 远程连接使用;机器的添加、编辑与连接都在发起端操作。','session.remoteSyncHint': '想把发起端的插件和 Skill 搬过来?回到发起连接的机器,在顶部切换器里选「同步到远端…」。',@@ -62,20 +63,29 @@ export const zh = {'remove.confirm.ok': '确认删除','bridge.error': '打开远端窗口失败:','sync.title': '同步到远端',- 'sync.desc': '把本机已安装的插件与用户级 skills 同步到已连接的机器:插件在远端执行 dsh plugin add;skills 经 tar 流式复制到远端 ~/.dsh/skills。可多选。',- 'sync.target': '目标机器:',+ 'sync.desc': '把本机档案里的插件与用户级 Skill 推到一台已连接的机器:插件在远端执行 dsh plugin add;Skill 经 tar 流式写入远端 ~/.dsh/skills。同步前可在下面勾选要带走的内容。',+ 'sync.target': '目标机器','sync.plugins': '插件',- 'sync.skills': 'Skills',- 'sync.noPlugins': '本机档案没有插件依赖。',- 'sync.noSkills': '没有用户级 skills。',+ 'sync.skills': 'Skill',+ 'sync.noPlugins': '本机档案没有可同步的插件依赖。',+ 'sync.noSkills': '没有用户级 Skill。',+ 'sync.selected': '已选 {plugins} 个插件、{skills} 个 Skill',+ 'sync.selectAll': '全选',+ 'sync.clear': '清空',+ 'sync.groupCount': '{checked}/{total}',+ 'sync.notSyncable': '不可同步','sync.apply': '同步所选',+ 'sync.applyTo': '同步到 {name}','sync.applying': '同步中…',+ 'sync.progress': '正在同步第 {done}/{total} 项:{item}','sync.refresh': '刷新列表','sync.loadFailed': '加载同步列表失败:','sync.applyFailed': '同步请求失败:',- 'sync.done': '同步完成:{ok}/{total} 项成功。',+ 'sync.summary': '同步结果:{ok} 项成功、{failed} 项失败。',+ 'sync.retryFailed': '重试失败项({count})','sync.itemOk': '已同步','sync.itemFailed': '失败',+ 'progress.syncing': '正在同步第 {attempt}/{total} 项…','progress.handshake': '正在建立 SSH 连接…','progress.starting': '正在启动远端实例…','progress.probing': '健康检查 {attempt}/{total}…',@@ -92,6 +102,7 @@ export const zh = {'step.installing': '安装','step.starting': '启动','step.probing': '探测',+ 'step.syncing': '同步','notice.probe_ok': '探测通过','notice.probe_failed': '探测失败','progress.installing': '正在安装 dsh(下载并校验官方打包运行时,通常 1–3 分钟)…',@@ -138,7 +149,8 @@ export const en = {'field.user': 'User (optional)','session.remoteTitle': 'Currently in an SSH session','sync.nav': 'Sync to remote',- 'sync.notConnectedHint': 'No connected machines yet — connect one under “SSH machines” first, then sync plugins and skills to it.',+ 'sync.notConnectedHint': 'No connected machines yet — connect one under “SSH machines” first, then come back here to sync.',+ 'sync.remoteSessionHint': 'This instance is in use over SSH: run the plugin/skill sync on the machine that started the session (pick “Sync to remote…” there).','session.remoteHintNamed': 'This instance is in use over SSH from {name}; add, edit and connect machines on the machine that started the session.','session.remoteHint': 'This instance is in use over an SSH session; add, edit and connect machines on the machine that started it.','session.remoteSyncHint': 'Want the plugins and skills from that side? On the machine that started the session, pick “Sync to remote…” in the top switcher.',@@ -167,20 +179,29 @@ export const en = {'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.target': 'Target machine: ',+ 'sync.desc': 'Push the plugins and user-level skills of this machine\'s profile to a connected machine: plugins install remotely via dsh plugin add; skills stream as a tar into the remote ~/.dsh/skills. Tick what should travel below.',+ 'sync.target': 'Target machine','sync.plugins': 'Plugins','sync.skills': 'Skills',- 'sync.noPlugins': 'No plugin dependencies in the local profile.',+ 'sync.noPlugins': 'No syncable plugin dependencies in the local profile.','sync.noSkills': 'No user-level skills.',+ 'sync.selected': '{plugins} plugins and {skills} skills selected',+ 'sync.selectAll': 'Select all',+ 'sync.clear': 'Clear',+ 'sync.groupCount': '{checked}/{total}',+ 'sync.notSyncable': 'not syncable','sync.apply': 'Sync selection',+ 'sync.applyTo': 'Sync to {name}','sync.applying': 'Syncing…',+ 'sync.progress': 'Syncing item {done}/{total}: {item}','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.summary': 'Sync result: {ok} succeeded, {failed} failed.',+ 'sync.retryFailed': 'Retry failed items ({count})','sync.itemOk': 'synced','sync.itemFailed': 'failed',+ 'progress.syncing': 'Syncing item {attempt}/{total}…','progress.handshake': 'Connecting over SSH…','progress.starting': 'Starting the remote instance…','progress.probing': 'Health check {attempt}/{total}…',@@ -197,6 +218,7 @@ export const en = {'step.installing': 'Install','step.starting': 'Start','step.probing': 'Probe',+ 'step.syncing': 'Sync','notice.probe_ok': 'Probe passed','notice.probe_failed': 'Probe failed','progress.installing': 'Installing dsh (downloading and verifying the official packaged runtime, usually 1–3 min)…',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 496937b9..90e2ba86 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'import { describe, expect, it, vi } from 'vitest'-import { machineEventsOf, machineRowOf, MachinesStore, savePayloadOf, toggleSelection } from './index'+import { machineEventsOf, machineRowOf, MachinesStore, mergeSyncResults, savePayloadOf, toggleSelection } from './index'type FetchMock = ReturnType<typeof vi.fn<FetchFn>>@@ -629,4 +629,43 @@ describe('sync state', () => {await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [])expect(store.getSnapshot().sync).toMatchObject({ applying: false, error: 'ssh down' })})++ it('merges a retry batch over its own entries and appends new ones', async () => {+ const fetchFn = syncFetch({+ 'sync.apply': { items: [+ { kind: 'plugin', name: 'p', ok: false, error: 'exit 1' },+ { kind: 'skill', name: 's', root: 'dsh', ok: true },+ ] },+ })+ const store = new MachinesStore(fetchFn)+ await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [{ name: 's', root: 'dsh' }])+ // 重试 p:成功,且 s 的既有结论不被抹掉+ fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { items: [{ kind: 'plugin', name: 'p', ok: true }] } }) } as unknown as Response)+ await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [])+ expect(store.getSnapshot().sync.results).toEqual([+ { kind: 'plugin', name: 'p', ok: true },+ { kind: 'skill', name: 's', root: 'dsh', ok: true },+ ])+ })+})++describe('mergeSyncResults', () => {+ const ok = (name: string): { kind: 'plugin', name: string, ok: boolean } => ({ kind: 'plugin', name, ok: true })++ it('keeps the first-seen order and replaces in place', () => {+ const merged = mergeSyncResults([ok('a'), ok('b')], [{ kind: 'plugin', name: 'b', ok: false, error: 'boom' }])+ expect(merged).toEqual([ok('a'), { kind: 'plugin', name: 'b', ok: false, error: 'boom' }])+ })++ it('appends unseen items and separates skills by root', () => {+ const merged = mergeSyncResults(+ [{ kind: 'skill', name: 'alpha', root: 'dsh', ok: true }],+ [{ kind: 'skill', name: 'alpha', root: 'agents', ok: false }, ok('c')],+ )+ expect(merged.map(item => `${item.kind}:${item.root ?? ''}:${item.name}`)).toEqual([+ 'skill:dsh:alpha',+ 'skill:agents:alpha',+ 'plugin::c',+ ])+ })})diff --git a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts b/packages/dsh-tauri-ssh-ui/src/client/store/index.tsindex 0302dd7c..fc1580a1 100644--- a/packages/dsh-tauri-ssh-ui/src/client/store/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/store/index.ts@@ -48,7 +48,7 @@ export interface SecretValues {}/** The pipeline phases one connection-plane operation walks through. */-export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing'+export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing' | 'syncing'/** Live transport status of one machine, from the /api-ssh list. */export interface MachineStatus {@@ -63,7 +63,7 @@ export interface MachineStatus {/** Whether the last failure was "dsh not installed on the remote" (offers install). */dshMissing?: boolean/** Live progress of the in-flight operation (phase codes translated by the UI). */- progress?: { phase: ProgressPhase, attempt?: number, total?: number, log?: string }+ progress?: { phase: ProgressPhase, attempt?: number, total?: number, item?: string, log?: string }}/** Outcome of a machine.install call (the host's install result). */@@ -89,7 +89,11 @@ export interface SyncPanelState {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. */+ /**+ * Apply outcomes keyed by item (kind:root:name); a retry overwrites its own+ * entries instead of dropping the earlier batch, so the list stays a running+ * record of this page. Null before the first apply.+ */results: SyncItemResult[] | null}@@ -263,6 +267,45 @@ export function toggleSelection(selected: ReadonlySet<string>, key: string): Setreturn next}+/**+ * The selection key of one preview plugin — identical in shape to the outcome+ * key {@link syncKeyOf} derives, so a selection and its result never drift.+ */+export function pluginKeyOf(plugin: { name: string }): string {+ return `plugin::${plugin.name}`+}++/** The selection key of one preview skill (same shape as the outcome key). */+export function skillKeyOf(skill: { name: string, root: string }): string {+ return `skill:${skill.root}:${skill.name}`+}++/** The outcome key of one settled sync item. */+export function syncKeyOf(item: SyncItemResult): string {+ return `${item.kind}:${item.root ?? ''}:${item.name}`+}++/**+ * Merge one apply batch into the running outcome list: an item that ran again+ * (a retry) replaces its own entry in place, a new item appends. Without this+ * a retry would wipe the earlier batch and hide which items had succeeded.+ */+export function mergeSyncResults(previous: readonly SyncItemResult[], incoming: readonly SyncItemResult[]): SyncItemResult[] {+ const merged = [...previous]+ const at = new Map(merged.map((item, index) => [syncKeyOf(item), index]))+ for (const item of incoming) {+ const index = at.get(syncKeyOf(item))+ if (index === undefined) {+ at.set(syncKeyOf(item), merged.length)+ merged.push(item)+ }+ else {+ merged[index] = item+ }+ }+ return merged+}+/** Parse one /api-ssh envelope; non-ok envelopes throw. */async function envelopeOf(response: Response): Promise<SshApiResponse> {return await response.json() as SshApiResponse@@ -735,7 +778,7 @@ export class MachinesStore {if (result === null)throw new Error('malformed sync.apply payload')this.store.update((state) => {- state.sync.results = result.items+ state.sync.results = mergeSyncResults(state.sync.results ?? [], result.items)})}catch (error) {diff --git a/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts b/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.tsindex 6f117743..6279b6b5 100644--- a/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/styles/index.cssr.ts@@ -502,16 +502,7 @@ export default c([color: 'var(--dsw-alias-label-tertiary)',}),- /* The sync panel (a section-level group under the machine list). */- c('.dshp-ssh-sync-panel', {- display: 'flex',- flexDirection: 'column',- gap: '10px',- marginTop: '12px',- paddingTop: '12px',- borderTop: '1px solid var(--dsw-alias-border-l2)',- }),-+ /* The sync page: target chips, selection rows, progress, outcomes. */c('.dshp-ssh-sync-targets', {display: 'flex',alignItems: 'center',@@ -519,10 +510,25 @@ export default c([flexWrap: 'wrap',}),- c('.dshp-ssh-sync-groups', {+ /* A target chip's inner line: connection dot + machine name. */+ c('.dshp-ssh-sync-chip', {+ display: 'inline-flex',+ alignItems: 'center',+ gap: '6px',+ }),++ c('.dshp-ssh-sync-toolbar', {display: 'flex',- flexDirection: 'column',- gap: '10px',+ alignItems: 'center',+ gap: '8px',+ flexWrap: 'wrap',+ paddingTop: '2px',+ }),++ c('.dshp-ssh-sync-count', {+ fontSize: '12px',+ lineHeight: '18px',+ color: 'var(--dsw-alias-label-secondary)',}),c('.dshp-ssh-sync-group', {@@ -531,13 +537,19 @@ export default c([gap: '6px',}),+ c('.dshp-ssh-sync-group-head', {+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }),+c('.dshp-ssh-sync-items', {listStyle: 'none',margin: 0,padding: 0,display: 'flex',flexDirection: 'column',- gap: '4px',+ gap: '2px',}),c('.dshp-ssh-sync-item', {@@ -547,30 +559,141 @@ export default c([flexWrap: 'wrap',}),- c('.dshp-ssh-sync-reason', {- fontSize: '12px',- lineHeight: '18px',- color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-tertiary))',+ /*+ * One selectable row: the whole line is the hit target (checkbox + name ++ * metadata), so ticking does not require hitting a 12px box. Hover/focus+ * reuse the interactive tokens the primitives use.+ */+ c('.dshp-ssh-sync-row', {+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ flex: 1,+ minWidth: 0,+ padding: '5px 8px',+ border: 0,+ borderRadius: '6px',+ background: 'transparent',+ color: 'inherit',+ font: 'inherit',+ textAlign: 'left',+ cursor: 'pointer',+ }),++ c('.dshp-ssh-sync-row:hover', {+ background: 'var(--dsw-alias-interactive-bg-hover)',}),- /* The root tag inside a skill pill. */- c('.dshp-ssh-sync-root', {- marginLeft: '6px',- fontSize: '10px',- lineHeight: '14px',+ c('.dshp-ssh-sync-row:disabled', {+ cursor: 'not-allowed',+ opacity: 0.6,+ }),++ c('.dshp-ssh-sync-box', {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ width: '14px',+ height: '14px',+ border: '1px solid var(--dsw-alias-border-l4)',+ borderRadius: '4px',+ color: 'var(--dsw-alias-label-primary-foreground)',+ }),++ c('.dshp-ssh-sync-row[aria-checked="true"] .dshp-ssh-sync-box', {+ borderColor: 'var(--dsw-alias-brand-primary)',+ background: 'var(--dsw-alias-brand-primary)',+ }),++ /* 名称与「为何不可同步」的两行文本列:原因收进行内,行宽才对得齐 */+ c('.dshp-ssh-sync-text', {+ display: 'flex',+ flexDirection: 'column',+ gap: '1px',+ flex: 1,+ minWidth: 0,+ }),++ c('.dshp-ssh-sync-name', {+ fontSize: '13px',+ lineHeight: '20px',+ color: 'var(--dsw-alias-label-primary)',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }),++ c('.dshp-ssh-sync-meta', {+ flexShrink: 0,+ marginLeft: 'auto',+ paddingLeft: '8px',+ maxWidth: '40%',+ fontSize: '11px',+ lineHeight: '16px',color: 'var(--dsw-alias-label-tertiary)',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }),++ c('.dshp-ssh-sync-reason', {+ fontSize: '11px',+ lineHeight: '16px',+ color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-tertiary))',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',}),c('.dshp-ssh-sync-actions', {+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ flexWrap: 'wrap',+ paddingTop: '2px',+ }),++ c('.dshp-ssh-sync-progress', {display: 'flex',alignItems: 'center',gap: '8px',+ flex: 1,+ minWidth: '220px',+ }),++ c('.dshp-ssh-sync-bar', {+ display: 'block',+ flex: 1,+ height: '4px',+ borderRadius: '2px',+ background: 'var(--dsw-alias-border-l2)',+ overflow: 'hidden',+ }),++ c('.dshp-ssh-sync-bar-fill', {+ display: 'block',+ height: '100%',+ borderRadius: '2px',+ background: 'var(--dsw-alias-brand-primary)',+ transition: 'width 200ms ease',+ }),++ c('.dshp-ssh-sync-progress-text', {+ flexShrink: 0,+ fontSize: '12px',+ lineHeight: '18px',+ color: 'var(--dsw-alias-label-secondary)',}),c('.dshp-ssh-sync-results', {display: 'flex',flexDirection: 'column',+ alignItems: 'flex-start',gap: '6px',+ marginTop: '4px',+ paddingTop: '12px',+ borderTop: '1px solid var(--dsw-alias-border-l2)',}),c('.dshp-ssh-sync-summary', {diff --git a/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts b/packages/dsh-tauri-ssh-ui/src/client/styles/index.tsindex 9f62cdc1..798c6d4e 100644--- a/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts+++ b/packages/dsh-tauri-ssh-ui/src/client/styles/index.ts@@ -70,15 +70,25 @@ export const cls = {remoteTitle: 'dshp-ssh-remote-title',remoteHint: 'dshp-ssh-remote-hint',remoteNote: 'dshp-ssh-remote-note',- syncPanel: 'dshp-ssh-sync-panel',syncTargets: 'dshp-ssh-sync-targets',- syncGroups: 'dshp-ssh-sync-groups',+ syncChip: 'dshp-ssh-sync-chip',+ syncToolbar: 'dshp-ssh-sync-toolbar',+ syncCount: 'dshp-ssh-sync-count',syncGroup: 'dshp-ssh-sync-group',+ syncGroupHead: 'dshp-ssh-sync-group-head',syncItems: 'dshp-ssh-sync-items',syncItem: 'dshp-ssh-sync-item',+ syncRow: 'dshp-ssh-sync-row',+ syncBox: 'dshp-ssh-sync-box',+ syncText: 'dshp-ssh-sync-text',+ syncName: 'dshp-ssh-sync-name',+ syncMeta: 'dshp-ssh-sync-meta',syncReason: 'dshp-ssh-sync-reason',- syncRoot: 'dshp-ssh-sync-root',syncActions: 'dshp-ssh-sync-actions',+ syncProgress: 'dshp-ssh-sync-progress',+ syncBar: 'dshp-ssh-sync-bar',+ syncBarFill: 'dshp-ssh-sync-bar-fill',+ syncProgressText: 'dshp-ssh-sync-progress-text',syncResults: 'dshp-ssh-sync-results',syncSummary: 'dshp-ssh-sync-summary',syncResult: 'dshp-ssh-sync-result',diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.tsindex f0ff98c1..3e9893db 100644--- a/packages/dsh-tauri-ssh/src/host/apply.ts+++ b/packages/dsh-tauri-ssh/src/host/apply.ts@@ -302,7 +302,19 @@ export class SshRemoteService implements SshApiHost {*/async syncApply(machineId: MachineId, plugins: SyncPluginRef[], skills: SyncSkillRef[]): Promise<SyncApplyResult> {await this.syncProfiles()- return await this.sync.apply(machineId, plugins, skills)+ try {+ // 逐条进度经机器状态发布:设置页只轮询 machine.status,同步是本服务里+ // 唯一「一条请求跑几分钟」的操作,不报进度就只能干等。+ return await this.sync.apply(machineId, plugins, skills, {+ // 装进这台机器真正在跑的档案:隧道只服务那一个 profile,装到别处+ // (历史上的硬编码 web)等于没同步。+ profileName: this.manager.profileName(machineId),+ onItem: (position, total, item) => this.manager.setProgress(machineId, { phase: 'syncing', attempt: position, total, item }),+ })+ }+ finally {+ this.manager.setProgress(machineId)+ }}}diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/manager.test.tsindex 9433f8f0..e23fba77 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts@@ -25,6 +25,7 @@ const secondProfile: MachineProfile = {...profile,id: MachineId('m2'),name: 'beta',+ profileName: 'work',}const config = {@@ -362,6 +363,26 @@ describe('sshManager', () => {expect(manager.status(MachineId('m1')).state).toBe('connected')})+ it('reports the profile a machine serves, defaulting when unset', () => {+ const { manager } = boot()+ // boot()'s m1 has no profileName; the second profile pins one.+ expect(manager.profileName(MachineId('m1'))).toBe('remote')+ expect(manager.profileName(MachineId('m2'))).toBe('work')+ expect(manager.profileName(MachineId('unknown'))).toBe('remote')+ })++ it('publishes and clears externally driven progress (the sync engine)', () => {+ const { manager, emits } = boot()+ manager.setProgress(MachineId('m1'), { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' })+ expect(manager.status(MachineId('m1')).progress).toEqual({ phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' })+ manager.setProgress(MachineId('m1'))+ expect(manager.status(MachineId('m1')).progress).toBeUndefined()+ expect(emits.map(entry => entry.progress)).toEqual([+ { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' },+ undefined,+ ])+ })+it('publishes live progress phases while connecting', async () => {const session = new FakeSession(index => index !== 0)const { manager, emits } = boot({ sessionFactory: () => session })diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.tsindex 37692acf..4886352a 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts@@ -141,6 +141,34 @@ export class SshManager {return [...this.profiles.keys()].map(id => this.status(id))}+ /**+ * The remote dsh profile this machine serves (its configured name, falling+ * back to the default). Callers that install plugins on the remote must+ * target it: the tunnel only ever serves this one profile.+ * @param machineId - the machine to look up.+ * @returns the shell-safe profile name.+ */+ profileName(machineId: MachineId): string {+ return safeProfileName(this.profiles.get(machineId)?.profileName)+ }++ /**+ * Publish (or clear, with no value) the live progress of an operation the+ * manager does not own a lifecycle for — the sync engine's item-by-item+ * pass. The status line is the only channel the settings page polls, so an+ * externally driven operation reports itself here to stay visible.+ * @param machineId - the machine the operation runs against.+ * @param progress - the progress to publish; omit to clear.+ */+ setProgress(machineId: MachineId, progress?: SshProgress): void {+ const state = this.ensureState(machineId)+ if (progress === undefined)+ delete state.progress+ else+ state.progress = progress+ this.emit(machineId)+ }+/** Transport status of one machine; unknown ids report `disconnected`. */status(machineId: MachineId): SshMachineStatus {const state = this.states.get(machineId)diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync.test.tsindex 124b9d39..50f477f1 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts@@ -1,7 +1,9 @@import type { SshExecResult, SshSession } from './transport'import { Buffer } from 'node:buffer'import { describe, expect, it, vi } from 'vitest'+import { DEFAULT_REMOTE_PROFILE } from '../storage/index'import { MachineId } from '../types/index'+import { layoutNodeBinary } from './bootstrap'import { buildPreview, classifySpec, pluginAddCommand, skillExtractCommand, SyncEngine } from './sync'/** A scripted SSH session: commands dispatched by order or by matcher. */@@ -77,9 +79,15 @@ describe('buildPreview', () => {describe('command builders', () => {it('runs the layout entry under the layout node, both quoted', () => {expect(pluginAddCommand('/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js', 'github:a/b'))- .toBe(`"$HOME/.dsh-desktop/runtime/bin/node" '/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js' plugin --profile web add 'github:a/b'`)+ .toBe(`"$HOME/.dsh-desktop/runtime/bin/node" '/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js' plugin --profile '${DEFAULT_REMOTE_PROFILE}' add 'github:a/b'`)expect(pluginAddCommand('/home/u/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', 'pkg@^1.0.0'))- .toBe(`"$HOME/.dsh-desktop/runtime/bin/node" '/home/u/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js' plugin --profile web add 'pkg@^1.0.0'`)+ .toBe(`${layoutNodeBinary()} '/home/u/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js' plugin --profile '${DEFAULT_REMOTE_PROFILE}' add 'pkg@^1.0.0'`)+ })++ it('installs into the machine profile it is handed, quoted', () => {+ // 隧道只服务这台机器自己的档案:装到别处(历史上的硬编码 web)等于没同步+ expect(pluginAddCommand('/x/bin.js', 'github:a/b', 'work'))+ .toBe(`${layoutNodeBinary()} '/x/bin.js' plugin --profile 'work' add 'github:a/b'`)})it('extracts the streamed tarball into the remote skill home', () => {@@ -220,4 +228,48 @@ describe('syncEngine.apply', () => {)expect(deduped.items).toHaveLength(2)})++ it('installs plugins into the profile the options name', async () => {+ const session = fakeSession((command) => {+ if (command.includes('printf'))+ return ok('/dsh\n')+ return ok()+ })+ const sync = new SyncEngine({+ profileDependencies: () => ({}),+ scanSkills: () => [],+ packSkills: async () => Buffer.alloc(0),+ openSession: async () => session,+ })+ await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'work' })+ const add = session.execSpy.mock.calls.map(([command]) => command).find(command => command.includes('plugin --profile'))+ expect(add).toContain('--profile \'work\' add')+ })++ it('announces each item before it runs, 1-based and deduped, skills batched by root', async () => {+ const session = fakeSession((command) => {+ if (command.includes('printf'))+ return ok('/dsh\n')+ return ok()+ })+ const sync = new SyncEngine({+ profileDependencies: () => ({}),+ scanSkills: () => [+ { root: 'dsh', dir: '/root/dsh-skills', names: ['alpha', 'beta'] },+ { root: 'agents', dir: '/root/agent-skills', names: ['gamma'] },+ ],+ packSkills: async () => Buffer.alloc(0),+ openSession: async () => session,+ })+ const seen: string[] = []+ await sync.apply(+ machine,+ [{ name: 'p1', spec: 'github:a/b' }, { name: 'p1 dup', spec: 'github:a/b' }, { name: 'p2', spec: '^1.0.0' }],+ [{ name: 'alpha', root: 'dsh' }, { name: 'beta', root: 'dsh' }, { name: 'ghost', root: 'dsh' }, { name: 'gamma', root: 'agents' }],+ { onItem: (position, total, name) => seen.push(`${position}/${total}:${name}`) },+ )+ // 去重后 2 插件 + 4 skill;ghost 在本地校验出局(不公告但照样结算),+ // 每个 root 的 skill 共用一份 tar,故只公告批首那条。+ expect(seen).toEqual(['1/6:p1', '2/6:p2', '4/6:alpha', '6/6:gamma'])+ })})diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-ssh/src/host/service/sync.tsindex 4648c60d..92163124 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync.ts@@ -15,11 +15,17 @@import type { Buffer } from 'node:buffer'import type { MachineId, SyncApplyResult, SyncItemResult, SyncPluginItem, SyncPluginRef, SyncPreview, SyncSkillItem, SyncSkillRef, SyncSkillRoot } from '../types/index'import type { SshSession } from './transport'+import { DEFAULT_REMOTE_PROFILE } from '../storage/index'import { dshEntryProbeCommand, firstLineOf, layoutNodeBinary } from './bootstrap'import { shQuote } from './transport'-/** The remote profile plugins are installed into (the web-serving one). */-export const REMOTE_PLUGIN_PROFILE = 'web'+/**+ * Fallback remote profile for plugin installs when the caller names none —+ * the same default the tunnel bootstrap serves ({@link DEFAULT_REMOTE_PROFILE}).+ * Callers that know the machine (the `/api-ssh` service) always pass the+ * machine's own profile, so plugins land where the tunnel actually looks.+ */+export const REMOTE_PLUGIN_PROFILE = DEFAULT_REMOTE_PROFILE/** How many output lines an item failure carries (the operator-facing tail). */const FAILURE_TAIL_LINES = 5@@ -75,10 +81,11 @@ export function buildPreview(dependencies: Record<string, string>, skillRoots: R* under the layout's Node binary (never a bare `dsh` from the login PATH).* @param dshEntry - the absolute entry path the layout probe resolved.* @param spec - the dependency spec to install.+ * @param profileName - the remote profile to install into.* @returns the shell command line.*/-export function pluginAddCommand(dshEntry: string, spec: string): string {- return `${layoutNodeBinary()} ${shQuote(dshEntry)} plugin --profile ${REMOTE_PLUGIN_PROFILE} add ${shQuote(spec)}`+export function pluginAddCommand(dshEntry: string, spec: string, profileName: string = REMOTE_PLUGIN_PROFILE): string {+ return `${layoutNodeBinary()} ${shQuote(dshEntry)} plugin --profile ${shQuote(profileName)} add ${shQuote(spec)}`}/** The remote skill-extract command; the tarball arrives on its stdin. */@@ -112,6 +119,23 @@ export interface SyncEngineDeps {commandTimeoutMs?: number}+/** One apply run's options. */+export interface SyncApplyOptions {+ /**+ * Live progress of the run: the item about to start (1-based position), the+ * deduped item count, and the item's display name. Called before every+ * remote command, so the UI can show progress instead of a silent+ * multi-minute wait.+ */+ onItem?: (position: number, total: number, name: string) => void+ /**+ * The remote dsh profile the plugins install into. The tunnel serves this+ * machine's configured profile (default {@link DEFAULT_REMOTE_PROFILE}), so+ * installing anywhere else would leave the synced plugins inert.+ */+ profileName?: string+}+/*** The sync engine: preview from local sources, apply over one SSH session.* Apply never throws for command-level failures — every requested item@@ -130,18 +154,27 @@ export class SyncEngine {* @param machineId - the target machine.* @param plugins - the plugin refs to install (name is display identity).* @param skills - the skill refs to copy (root picks the local source).+ * @param options - live progress and the install target profile.* @returns one outcome per requested item, in request order.*/- async apply(machineId: MachineId, plugins: readonly SyncPluginRef[], skills: readonly SyncSkillRef[]): Promise<SyncApplyResult> {+ async apply(+ machineId: MachineId,+ plugins: readonly SyncPluginRef[],+ skills: readonly SyncSkillRef[],+ options: SyncApplyOptions = {},+ ): Promise<SyncApplyResult> {const items: SyncItemResult[] = []const uniquePlugins = dedupeBy(plugins, ref => ref.spec)const uniqueSkills = dedupeBy(skills, ref => `${ref.root}:${ref.name}`)if (uniquePlugins.length === 0 && uniqueSkills.length === 0)return { items }+ // 进度只按「已结算的条目数」推进:公告的 position 恒为 settled + 1,UI 的+ // 「第 n/N 项」因此在任何失败路径下都不跳号(本地校验出局的条目也结算)。+ const progress: SyncProgress = { settled: 0, total: uniquePlugins.length + uniqueSkills.length }const session = await this.deps.openSession(machineId)try {- await this.applyPlugins(session, uniquePlugins, items)- await this.applySkills(session, uniqueSkills, items)+ await this.applyPlugins(session, uniquePlugins, items, progress, options)+ await this.applySkills(session, uniqueSkills, items, progress, options)}finally {await session.close().catch(() => undefined)@@ -150,11 +183,18 @@ export class SyncEngine {}/** Install each plugin spec in its own exec so outcomes stay per-item. */- private async applyPlugins(session: SshSession, plugins: readonly SyncPluginRef[], items: SyncItemResult[]): Promise<void> {+ private async applyPlugins(+ session: SshSession,+ plugins: readonly SyncPluginRef[],+ items: SyncItemResult[],+ progress: SyncProgress,+ options: SyncApplyOptions,+ ): Promise<void> {if (plugins.length === 0)returnconst dshEntry = firstLineOf((await session.exec(dshEntryProbeCommand())).stdout)for (const plugin of plugins) {+ announceItem(progress, options, plugin.name)if (dshEntry === '') {items.push({kind: 'plugin',@@ -164,7 +204,7 @@ export class SyncEngine {})continue}- const result = await session.exec(pluginAddCommand(dshEntry, plugin.spec), {+ const result = await session.exec(pluginAddCommand(dshEntry, plugin.spec, options.profileName), {...this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs },})items.push(@@ -172,11 +212,18 @@ export class SyncEngine {? { kind: 'plugin', name: plugin.name, ok: true }: { kind: 'plugin', name: plugin.name, ok: false, error: describeFailure(result.code, result.stdout, result.stderr) },)+ progress.settled += 1}}/** Copy skills per root: local validation per item, one tar stream per root. */- private async applySkills(session: SshSession, skills: readonly SyncSkillRef[], items: SyncItemResult[]): Promise<void> {+ private async applySkills(+ session: SshSession,+ skills: readonly SyncSkillRef[],+ items: SyncItemResult[],+ progress: SyncProgress,+ options: SyncApplyOptions,+ ): Promise<void> {if (skills.length === 0)returnconst roots = new Map(this.deps.scanSkills().map(entry => [entry.root as SyncSkillRoot, entry]))@@ -198,10 +245,13 @@ export class SyncEngine {ok: false,error: `not found under the local "${root}" skill root (it may have been removed)`,})+ progress.settled += 1}}if (transferable.length === 0)continue+ // 一个 root 的全部 skill 走同一份 tar:公告取批首那条,位置即批次起点。+ announceItem(progress, options, transferable[0]!.name)let tar: Buffertry {tar = await this.deps.packSkills(entry.dir, transferable.map(skill => skill.name))@@ -212,6 +262,7 @@ export class SyncEngine {for (const skill of transferable) {items.push({ kind: 'skill', name: skill.name, root, ok: false, error: message })}+ progress.settled += transferable.lengthcontinue}const result = await session.exec(skillExtractCommand(), {@@ -225,10 +276,24 @@ export class SyncEngine {: { kind: 'skill', name: skill.name, root, ok: false, error: describeFailure(result.code, result.stdout, result.stderr) },)}+ progress.settled += transferable.length}}}+/** The live progress bookkeeping of one apply run (see `SyncProgressHook`). */+interface SyncProgress {+ /** Items already settled (success or failure); the next item is `settled + 1`. */+ settled: number+ /** Deduped item count of the run. */+ total: number+}++/** Announce the item about to run; no-op when the caller passed no hook. */+function announceItem(progress: SyncProgress, options: SyncApplyOptions, name: string): void {+ options.onItem?.(progress.settled + 1, progress.total, name)+}+/** Keep the first occurrence of each keyed item, preserving request order. */function dedupeBy<T>(items: readonly T[], keyOf: (item: T) => string): T[] {const seen = new Set<string>()diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.tsindex 1243bc62..2f453779 100644--- a/packages/dsh-tauri-ssh/src/host/types/index.ts+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts@@ -129,15 +129,17 @@ export type SshConnectionStateexport type SshAuthMethod = 'agent' | 'key' | 'password'/** One progress phase of a connection-plane operation, shown live in the UI. */-export type SshProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing'+export type SshProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing' | 'syncing'/** Structured progress of an in-flight connection-plane operation. */export interface SshProgress {phase: SshProgressPhase- /** Progress position (e.g. health-probe attempt number). */+ /** Progress position (health-probe attempt, or the sync item's 1-based index). */attempt?: number- /** Progress total (e.g. health-probe attempt budget). */+ /** Progress total (health-probe attempt budget, or the sync item count). */total?: number+ /** Display label of the work in flight (the sync item's name). */+ item?: string/** Recent streaming output of the operation (the install log), newest last. */log?: string}