Skip to content

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

feat(ssh): sync.* /api-ssh surface (engine + per-item results)

Menghuan1918d8e3533e490d
diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.ts
index a839b824..59e2be96 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.ts
@@ -12,7 +12,11 @@ import type z from 'schemastery'
import type { SshApiHost } from './routes/index.js'
import type { SshHostBlock } from './service/ssh-config.js'
import type { MachinesValue, Config as SshRemoteConfig } from './storage/index.js'
+<<<<<<< HEAD
import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineEventsPage, SshMachineStatus, SshTestResult } from './types/index.js'
+=======
+import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef } from './types/index.js'
+>>>>>>> a59eb500 (feat(ssh): sync.* /api-ssh surface (engine + per-item results))
import { homedir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
@@ -22,6 +26,8 @@ import { SshMachineEvents } from './service/events.js'
import { KnownHostsStore } from './service/host-keys.js'
import { profileView, SshManager } from './service/manager.js'
import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config.js'
+import { profileDependenciesReader, skillRootsScanner, tarPacker } from './service/sync-local.js'
+import { SyncEngine } from './service/sync.js'
import { Ssh2Transport } from './service/transport.js'
import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MACHINES_NAMESPACE, machinesFromValue, MachinesSchema } from './storage/index.js'
import { MachineId } from './types/index.js'
@@ -57,6 +63,9 @@ export class SshRemoteService implements SshApiHost {
/** The validated plugin config (defaults applied by schemastery). */
private readonly config: SshRemoteConfig
+ /** The plugin/skill sync engine (local sources → one remote machine). */
+ private readonly sync: SyncEngine
+
/**
* @param ctx - the plugin context (settings + webServer available through inject).
* @param config - the validated plugin config.
@@ -86,6 +95,15 @@ export class SshRemoteService implements SshApiHost {
base: { machines: {} },
})
this.scope = scope
+ // The sync engine: local profile/skill sources, remote commands over a
+ // dedicated session, the install-class deadline per remote command.
+ this.sync = new SyncEngine({
+ profileDependencies: profileDependenciesReader(),
+ scanSkills: skillRootsScanner(),
+ packSkills: tarPacker(),
+ openSession: (machineId) => this.manager.openSession(machineId),
+ ...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },
+ })
this.manager.refreshProfiles(this.applyStartDefaults(this.manualProfiles()))
scope.watch(() => {
void this.syncProfiles()
@@ -251,6 +269,25 @@ export class SshRemoteService implements SshApiHost {
machines.delete(machineId)
await this.scope.replace({ machines: Object.fromEntries(machines) })
}
+
+ /** The local plugins and skills available to sync (the panel's selection list). */
+ syncPreview(): SyncPreview {
+ return this.sync.preview()
+ }
+
+ /**
+ * Sync the selection to one machine over a dedicated authenticated session.
+ * Command-level failures settle per item in the result; only a session the
+ * engine cannot open at all escalates to an envelope error.
+ * @param machineId - the target machine.
+ * @param plugins - the plugin refs to install.
+ * @param skills - the skill refs to copy.
+ * @returns one outcome per requested item.
+ */
+ async syncApply(machineId: MachineId, plugins: SyncPluginRef[], skills: SyncSkillRef[]): Promise<SyncApplyResult> {
+ await this.syncProfiles()
+ return await this.sync.apply(machineId, plugins, skills)
+ }
}
/** Cordis plugin name. */
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
index bbbc8090..d49c4cbb 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
@@ -37,6 +37,8 @@ function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {
events: (machineId, sinceSeq) => log.since(machineId, sinceSeq),
save: async () => {},
remove: async () => {},
+ syncPreview: () => ({ plugins: [], skills: [] }),
+ syncApply: async () => ({ items: [] }),
...overrides,
}
}
@@ -389,6 +391,73 @@ describe('/api-ssh handler', () => {
expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'missing machineId' } })
})
+ it('serves the sync preview', async () => {
+ const preview = {
+ plugins: [{ name: 'dsh-market', spec: 'github:a/b', syncable: true }],
+ skills: [{ name: 'alpha', root: 'dsh' as const }],
+ }
+ const host = fakeHost({ syncPreview: () => preview })
+ const { status, body } = await call(host, JSON.stringify({ method: 'sync.preview' }))
+ expect(status).toBe(200)
+ expect(body).toEqual({ ok: true, value: preview })
+ })
+
+ it('applies a sync selection and returns per-item results', async () => {
+ const syncApply = vi.fn(async () => ({
+ items: [
+ { kind: 'plugin' as const, name: 'dsh-market', ok: true },
+ { kind: 'skill' as const, name: 'alpha', root: 'dsh' as const, ok: false, error: 'exit 1: read-only' },
+ ],
+ }))
+ const host = fakeHost({ syncApply })
+ const { status, body } = await call(host, JSON.stringify({
+ method: 'sync.apply',
+ payload: {
+ machineId: 'm1',
+ plugins: [{ name: 'dsh-market', spec: 'github:a/b' }],
+ skills: [{ name: 'alpha', root: 'dsh' }],
+ },
+ }))
+ expect(status).toBe(200)
+ expect(body).toMatchObject({ ok: true })
+ expect(syncApply).toHaveBeenCalledWith(
+ MachineId('m1'),
+ [{ name: 'dsh-market', spec: 'github:a/b' }],
+ [{ name: 'alpha', root: 'dsh' }],
+ )
+ const value = (body as { ok: true, value: { items: Array<Record<string, unknown>> } }).value
+ expect(value.items).toHaveLength(2)
+ expect(value.items[1]).toMatchObject({ ok: false, error: 'exit 1: read-only' })
+ })
+
+ it('defaults an absent sync selection to empty lists', async () => {
+ const syncApply = vi.fn(async () => ({ items: [] }))
+ const host = fakeHost({ syncApply })
+ const { body } = await call(host, JSON.stringify({ method: 'sync.apply', payload: { machineId: 'm1' } }))
+ expect(body).toMatchObject({ ok: true })
+ expect(syncApply).toHaveBeenCalledWith(MachineId('m1'), [], [])
+ })
+
+ it('rejects malformed sync selections', async () => {
+ const badPlugin = await call(fakeHost(), JSON.stringify({
+ method: 'sync.apply',
+ payload: { machineId: 'm1', plugins: [{ name: 'x' }] },
+ }))
+ expect(badPlugin.body).toMatchObject({ ok: false, error: { message: 'invalid plugin ref' } })
+
+ const badRoot = await call(fakeHost(), JSON.stringify({
+ method: 'sync.apply',
+ payload: { machineId: 'm1', skills: [{ name: 'x', root: 'elsewhere' }] },
+ }))
+ expect(badRoot.body).toMatchObject({ ok: false, error: { message: 'invalid skill ref: root' } })
+
+ const notArray = await call(fakeHost(), JSON.stringify({
+ method: 'sync.apply',
+ payload: { machineId: 'm1', plugins: 'nope' },
+ }))
+ expect(notArray.body).toMatchObject({ ok: false, error: { message: 'invalid plugins' } })
+ })
+
it('rejects unknown methods', async () => {
const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.warp' }))
expect(status).toBe(404)
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.ts
index d27fe122..cf1b2bb9 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts
@@ -191,6 +191,21 @@ export class SshManager {
return state.connecting
}
+ /**
+ * Open one dedicated authenticated session to the machine — handshake and
+ * TOFU gate only, no remote-instance bootstrap and no tunnel. Callers that
+ * drive plain remote commands (the sync engine) get an independent
+ * lifecycle: closing the returned session never touches a live link.
+ * @param machineId - the machine to reach.
+ * @param signal - aborts the handshake.
+ * @returns the authenticated session; the caller owns closing it.
+ * @throws {SshError} `machine-not-found` for an unknown id.
+ */
+ async openSession(machineId: MachineId, signal?: AbortSignal): Promise<SshSession> {
+ const profile = this.requireProfile(machineId)
+ return await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)
+ }
+
/**
* Tear down one machine's link, invalidating any in-flight connect.
* Idempotent for an absent link; unknown ids resolve without writing
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts b/packages/dsh-tauri-ssh/src/host/service/sync-local.ts
new file mode 100644
index 00000000..8cf047ac
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/sync-local.ts
@@ -0,0 +1,119 @@
+/**
+ * Local-source readers for the sync engine: the profile's package.json
+ * dependencies and the user-level skill roots, plus the local `tar` packer.
+ * These are the fs/process touchpoints the engine's seams abstract, kept
+ * apart from the pure engine so tests import neither.
+ * @module dsh-tauri-ssh/host/service/sync-local
+ */
+
+import type { SyncSkillRoot } from '../types/index.js'
+import { execFile } from 'node:child_process'
+import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
+import { homedir } from 'node:os'
+import process from 'node:process'
+import { join } from 'pathe'
+import { promisify } from 'node:util'
+
+const execFileAsync = promisify(execFile)
+
+/** The tar stream size budget (a skill folder can carry fixtures and assets). */
+const MAX_TAR_BYTES = 64 * 1024 * 1024
+
+/** Profile that boots this process: `--profile <name>` on the CLI invocation. */
+export function argvProfile(argv: readonly string[] = process.argv): string | undefined {
+ const flag = argv.indexOf('--profile')
+ const value = flag === -1 ? undefined : argv[flag + 1]
+ if (value !== undefined && !value.startsWith('-'))
+ return value
+ return undefined
+}
+
+/** The harness home: `$DSH_HOME`, else `~/.dsh`. */
+function dshHomeOf(override?: string): string {
+ return override ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
+}
+
+/**
+ * Read the local profile's plugin dependencies (`profiles/<name>/package.json`
+ * → `dependencies`). A missing or malformed manifest yields an empty map: "no
+ * plugins installed here" is a state to show, not a failure to raise.
+ * @param dshHome - harness-home override (tests).
+ * @returns the dependency-name → spec map.
+ */
+export function profileDependenciesReader(dshHome?: string): () => Record<string, string> {
+ return () => {
+ const profile = argvProfile() ?? 'web'
+ const manifestPath = join(dshHomeOf(dshHome), 'profiles', profile, 'package.json')
+ try {
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { dependencies?: Record<string, unknown> }
+ const out: Record<string, string> = {}
+ for (const [name, spec] of Object.entries(manifest.dependencies ?? {})) {
+ if (typeof spec === 'string')
+ out[name] = spec
+ }
+ return out
+ }
+ catch {
+ return {}
+ }
+ }
+}
+
+/**
+ * Scan the user-level skill roots (`<dsh-home>/skills`, `~/.agents/skills`)
+ * for SKILL.md-carrying directories. Absent roots simply contribute nothing.
+ * @param dshHome - harness-home override (tests).
+ * @param homeDir - user-home override (tests).
+ * @returns per root: the label, its directory, and its sorted skill names.
+ */
+export function skillRootsScanner(dshHome?: string, homeDir?: string): () => Array<{ root: SyncSkillRoot, dir: string, names: string[] }> {
+ return () => {
+ const roots: Array<{ root: SyncSkillRoot, dir: string }> = [
+ { root: 'dsh', dir: join(dshHomeOf(dshHome), 'skills') },
+ { root: 'agents', dir: join(homeDir ?? homedir(), '.agents', 'skills') },
+ ]
+ return roots.map(({ root, dir }) => ({
+ root,
+ dir,
+ names: skillNamesOf(dir),
+ }))
+ }
+}
+
+/** The SKILL.md directories under one root, sorted; absent roots stay empty. */
+function skillNamesOf(dir: string): string[] {
+ if (!existsSync(dir))
+ return []
+ const names: string[] = []
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (!entry.isDirectory())
+ continue
+ try {
+ if (statSync(join(dir, entry.name, 'SKILL.md')).isFile())
+ names.push(entry.name)
+ }
+ catch {
+ // A broken symlink or unreadable entry is not a skill; skip it.
+ }
+ }
+ return names.sort()
+}
+
+/**
+ * The local `tar` packer: one streamed archive (`tar -cf -`) of the selected
+ * skill directories under their root, exactly as the remote extract expects.
+ * @returns the tar bytes.
+ */
+export function tarPacker(): (dir: string, names: readonly string[]) => Promise<Buffer> {
+ return async (dir, names) => {
+ const { stdout, stderr } = await execFileAsync('tar', ['-cf', '-', '-C', dir, ...names], {
+ maxBuffer: MAX_TAR_BYTES,
+ windowsHide: true,
+ encoding: 'buffer',
+ })
+ if (stdout.length === 0) {
+ throw new Error(`packing skills produced no archive${stderr.length === 0 ? '' : `: ${stderr.toString('utf8').trim()}`}`)
+ }
+ return stdout
+ }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
new file mode 100644
index 00000000..617d6e54
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
@@ -0,0 +1,221 @@
+import type { SshExecResult, SshSession } from './transport.js'
+import { describe, expect, it, vi } from 'vitest'
+import { MachineId } from '../types/index.js'
+import { buildPreview, classifySpec, pluginAddCommand, skillExtractCommand, SyncEngine } from './sync.js'
+
+/** A scripted SSH session: commands dispatched by order or by matcher. */
+function fakeSession(respond: (command: string, options?: { stdinData?: Buffer }) => SshExecResult): SshSession & { execSpy: ReturnType<typeof vi.fn>, closed: () => boolean } {
+ let open = true
+ const execSpy = vi.fn(async (command: string, options?: { stdinData?: Buffer }) => respond(command, options))
+ return {
+ execSpy,
+ exec: execSpy as unknown as SshSession['exec'],
+ openTunnel: () => Promise.reject(new Error('not needed')),
+ onClosed: () => {},
+ close: async () => {
+ open = false
+ },
+ closed: () => !open,
+ }
+}
+
+const ok = (stdout = ''): SshExecResult => ({ code: 0, stdout, stderr: '' })
+const fail = (stderr: string): SshExecResult => ({ code: 1, stdout: '', stderr })
+
+describe('classifySpec', () => {
+ it('accepts remotely installable specs', () => {
+ expect(classifySpec('github:omdsh-dev/dsh-market').syncable).toBe(true)
+ expect(classifySpec('git+https://github.com/a/b.git').syncable).toBe(true)
+ expect(classifySpec('[email protected]:a/b.git').syncable).toBe(true)
+ expect(classifySpec('^0.3.0').syncable).toBe(true)
+ expect(classifySpec('0.16.0').syncable).toBe(true)
+ expect(classifySpec(' latest ').syncable).toBe(true)
+ })
+
+ it('rejects local-path and URL specs with reasons', () => {
+ const local = classifySpec('link:/path/to/plugin')
+ expect(local.syncable).toBe(false)
+ expect(local.reason).toContain('local-path')
+ expect(classifySpec('file:../local').reason).toContain('local-path')
+ const url = classifySpec('https://example.com/x.tgz')
+ expect(url.syncable).toBe(false)
+ expect(url.reason).toContain('URL')
+ expect(classifySpec('').reason).toContain('empty')
+ })
+})
+
+describe('buildPreview', () => {
+ it('lists profile dependencies minus core packages, each with a verdict', () => {
+ const preview = buildPreview(
+ {
+ 'zz-plugin': 'github:a/b',
+ 'aa-plugin': '^1.0.0',
+ '@deepseek-ai/dsh-client-runtime': '^0.1.0',
+ 'local-plugin': 'link:../local',
+ },
+ [],
+ )
+ expect(preview.plugins.map(plugin => plugin.name)).toEqual(['aa-plugin', 'local-plugin', 'zz-plugin'])
+ expect(preview.plugins[2]).toMatchObject({ syncable: true })
+ expect(preview.plugins[1]).toMatchObject({ syncable: false, reason: expect.stringContaining('local-path') })
+ })
+
+ it('lists skills per root in name order', () => {
+ const preview = buildPreview({}, [
+ { root: 'dsh', names: ['beta', 'alpha'] },
+ { root: 'agents', names: ['zeta'] },
+ ])
+ expect(preview.skills).toEqual([
+ { name: 'alpha', root: 'dsh' },
+ { name: 'beta', root: 'dsh' },
+ { name: 'zeta', root: 'agents' },
+ ])
+ })
+})
+
+describe('command builders', () => {
+ it('quotes the dsh path and the spec on the add command', () => {
+ expect(pluginAddCommand('/home/u/.local/bin/dsh', 'github:a/b'))
+ .toBe(`'/home/u/.local/bin/dsh' plugin --profile web add 'github:a/b'`)
+ expect(pluginAddCommand('dsh', 'pkg@^1.0.0'))
+ .toBe(`'dsh' plugin --profile web add 'pkg@^1.0.0'`)
+ })
+
+ it('extracts the streamed tarball into the remote skill home', () => {
+ expect(skillExtractCommand()).toBe(`mkdir -p "$HOME/.dsh/skills" && tar -xf - -C "$HOME/.dsh/skills"`)
+ })
+})
+
+describe('SyncEngine.apply', () => {
+ const machine = MachineId('m1')
+
+ it('returns per-item successes when everything lands', async () => {
+ const session = fakeSession((command) => {
+ if (command.includes('command -v dsh'))
+ return ok('/home/u/.local/bin/dsh\n')
+ return ok()
+ })
+ const packSkills = vi.fn(async () => Buffer.from('TARDATA'))
+ const openSession = vi.fn(async () => session)
+ const sync = new SyncEngine({
+ profileDependencies: () => ({}),
+ scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha'] }],
+ packSkills,
+ openSession,
+ })
+ const result = await sync.apply(machine, [{ name: 'p1', spec: 'github:a/b' }], [{ name: 'alpha', root: 'dsh' }])
+ expect(result.items).toEqual([
+ { kind: 'plugin', name: 'p1', ok: true },
+ { kind: 'skill', name: 'alpha', root: 'dsh', ok: true },
+ ])
+ // The tarball rode the command's stdin, never the command line.
+ const extract = session.execSpy.mock.calls.find(([command]) => command.includes('tar -xf')) as [string, { stdinData?: Buffer }]
+ expect(extract[1]?.stdinData?.toString()).toBe('TARDATA')
+ expect(extract[0]).not.toContain('TARDATA')
+ expect(packSkills).toHaveBeenCalledWith('/root/skills', ['alpha'])
+ expect(session.closed()).toBe(true)
+ })
+
+ it('reports partial plugin failures per item with the output tail', async () => {
+ const session = fakeSession((command) => {
+ if (command.includes('command -v dsh'))
+ return ok('/home/u/.local/bin/dsh\n')
+ return command.includes('bad-pkg') ? fail('ERR_PNPM_NO_MATCH') : ok()
+ })
+ const sync = new SyncEngine({
+ profileDependencies: () => ({}),
+ scanSkills: () => [],
+ packSkills: async () => Buffer.alloc(0),
+ openSession: async () => session,
+ })
+ const result = await sync.apply(
+ machine,
+ [
+ { name: 'good', spec: 'github:a/good' },
+ { name: 'bad', spec: 'npm:bad-pkg' },
+ ],
+ [],
+ )
+ expect(result.items[0]).toMatchObject({ kind: 'plugin', name: 'good', ok: true })
+ expect(result.items[1]).toMatchObject({ kind: 'plugin', name: 'bad', ok: false, error: expect.stringContaining('ERR_PNPM_NO_MATCH') })
+ expect(result.items[1]?.error).toContain('exit 1')
+ })
+
+ it('fails every plugin item when the remote has no dsh binary', async () => {
+ const session = fakeSession(() => ok('\n'))
+ const sync = new SyncEngine({
+ profileDependencies: () => ({}),
+ scanSkills: () => [],
+ packSkills: async () => Buffer.alloc(0),
+ openSession: async () => session,
+ })
+ const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [])
+ expect(result.items).toHaveLength(1)
+ expect(result.items[0]).toMatchObject({ ok: false, error: expect.stringContaining('no dsh binary') })
+ })
+
+ it('marks unknown skills and local pack failures without touching the remote', async () => {
+ const session = fakeSession(() => ok())
+ const packSkills = vi.fn(async () => {
+ throw new Error('tar failed: disk full')
+ })
+ const sync = new SyncEngine({
+ profileDependencies: () => ({}),
+ scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha'] }],
+ packSkills,
+ openSession: async () => session,
+ })
+ const result = await sync.apply(machine, [], [
+ { name: 'ghost', root: 'dsh' },
+ { name: 'alpha', root: 'dsh' },
+ ])
+ expect(result.items[0]).toMatchObject({ kind: 'skill', name: 'ghost', ok: false, error: expect.stringContaining('not found') })
+ expect(result.items[1]).toMatchObject({ kind: 'skill', name: 'alpha', ok: false, error: 'tar failed: disk full' })
+ // Nothing reached the remote: every extract carried no stdin payload failure path.
+ expect(session.execSpy.mock.calls.some(([command]) => command.includes('tar -xf'))).toBe(false)
+ })
+
+ it('reports a remote extract failure on every skill of that root', async () => {
+ const session = fakeSession((command) => {
+ if (command.includes('tar -xf'))
+ return fail('cannot write: read-only file system')
+ return ok()
+ })
+ const sync = new SyncEngine({
+ profileDependencies: () => ({}),
+ scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha', 'beta'] }],
+ packSkills: async () => Buffer.from('TAR'),
+ openSession: async () => session,
+ })
+ const result = await sync.apply(machine, [], [
+ { name: 'alpha', root: 'dsh' },
+ { name: 'beta', root: 'dsh' },
+ ])
+ expect(result.items).toHaveLength(2)
+ for (const item of result.items) {
+ expect(item.ok).toBe(false)
+ expect(item.error).toContain('read-only file system')
+ }
+ })
+
+ it('dedupes repeated selections and skips the session for an empty selection', async () => {
+ const session = fakeSession(() => ok('/dsh\n'))
+ const openSession = vi.fn(async () => session)
+ const sync = new SyncEngine({
+ profileDependencies: () => ({}),
+ scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha'] }],
+ packSkills: async () => Buffer.alloc(0),
+ openSession,
+ })
+ const empty = await sync.apply(machine, [], [])
+ expect(empty.items).toEqual([])
+ expect(openSession).not.toHaveBeenCalled()
+
+ const deduped = await sync.apply(
+ machine,
+ [{ name: 'p', spec: 'github:a/b' }, { name: 'p again', spec: 'github:a/b' }],
+ [{ name: 'alpha', root: 'dsh' }, { name: 'alpha', root: 'dsh' }],
+ )
+ expect(deduped.items).toHaveLength(2)
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-ssh/src/host/service/sync.ts
new file mode 100644
index 00000000..018a9188
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.ts
@@ -0,0 +1,236 @@
+/**
+ * Plugin & skill sync (local → one remote machine): the S4-owned `sync.*`
+ * surface behind `/api-ssh`. `preview` reads the local dsh profile's plugin
+ * dependencies and the user-level skill roots; `apply` installs the selected
+ * plugins on the remote (`<dsh> plugin --profile web add <spec>`, one exec
+ * per plugin so every item earns its own outcome) and streams the selected
+ * skills as a tarball over the command's stdin (`tar -xf -`). The apply
+ * result is deliberately per-item — a partial failure must never hide
+ * behind a batched error string (the defect this panel was rebuilt to fix).
+ * Command builders are pure functions; the engine's fs/ssh seams are
+ * injectable so tests never touch the network.
+ * @module dsh-tauri-ssh/host/service/sync
+ */
+
+import type { MachineId, SyncApplyResult, SyncItemResult, SyncPluginItem, SyncPluginRef, SyncPreview, SyncSkillItem, SyncSkillRef, SyncSkillRoot } from '../types/index.js'
+import type { SshSession } from './transport.js'
+import { firstLineOf, probeDshCommand } from './bootstrap.js'
+import { shQuote } from './transport.js'
+
+/** The remote profile plugins are installed into (the web-serving one). */
+export const REMOTE_PLUGIN_PROFILE = 'web'
+
+/** How many output lines an item failure carries (the operator-facing tail). */
+const FAILURE_TAIL_LINES = 5
+
+/** Classify one dependency spec: can a remote `dsh plugin add` resolve it? */
+export function classifySpec(spec: string): { syncable: boolean, reason?: string } {
+ const value = spec.trim()
+ if (value === '')
+ return { syncable: false, reason: 'empty dependency spec' }
+ if (/^(github:|git\+|git@)/u.test(value))
+ return { syncable: true }
+ 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' }
+ // Anything else is an npm version spec (^1.0.0, 0.16.0, latest, …).
+ return { syncable: true }
+}
+
+/**
+ * Build the preview from the local sources: profile dependencies minus the
+ * `@deepseek-ai/` core packages (the remote release ships those), and the
+ * scanned skill roots. Both halves sorted by name for a stable panel order.
+ * @param dependencies - the profile package.json dependency map.
+ * @param skillRoots - per root, the SKILL.md directory names found locally.
+ * @returns the preview payload.
+ */
+export function buildPreview(dependencies: Record<string, string>, skillRoots: ReadonlyArray<{ root: SyncSkillRoot, names: readonly string[] }>): SyncPreview {
+ const plugins: SyncPluginItem[] = Object.entries(dependencies)
+ .filter(([name]) => !name.startsWith('@deepseek-ai/'))
+ .map(([name, spec]) => {
+ const verdict = classifySpec(spec)
+ return {
+ name,
+ spec,
+ syncable: verdict.syncable,
+ ...verdict.reason === undefined ? {} : { reason: verdict.reason },
+ }
+ })
+ .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
+ const skills: SyncSkillItem[] = []
+ for (const entry of skillRoots) {
+ for (const name of [...entry.names].sort()) {
+ skills.push({ name, root: entry.root })
+ }
+ }
+ return { plugins, skills }
+}
+
+/** The remote plugin-install command for one spec (dsh add is pnpm-backed). */
+export function pluginAddCommand(dshPath: string, spec: string): string {
+ return `${shQuote(dshPath)} plugin --profile ${REMOTE_PLUGIN_PROFILE} add ${shQuote(spec)}`
+}
+
+/** The remote skill-extract command; the tarball arrives on its stdin. */
+export function skillExtractCommand(): string {
+ return `mkdir -p "$HOME/.dsh/skills" && tar -xf - -C "$HOME/.dsh/skills"`
+}
+
+/** The last few non-empty lines of a command's output, joined for an error message. */
+function tailOf(text: string): string {
+ const lines = text.split('\n').map(line => line.trim()).filter(line => line !== '')
+ return lines.slice(-FAILURE_TAIL_LINES).join(' | ')
+}
+
+/** One operator-facing failure for a finished remote command. */
+function describeFailure(code: number | null, stdout: string, stderr: string): string {
+ const tail = [tailOf(stdout), tailOf(stderr)].filter(part => part !== '').join(' | ')
+ return `exit ${code ?? '?'}${tail === '' ? '' : `: ${tail}`}`
+}
+
+/** Engine seams — the fs/ssh touchpoints, injectable for tests. */
+export interface SyncEngineDeps {
+ /** The local profile's package.json dependency map. */
+ profileDependencies: () => Record<string, string>
+ /** The local skill roots as scanned, with their directories. */
+ scanSkills: () => Array<{ root: SyncSkillRoot, dir: string, names: string[] }>
+ /** Pack skill directories into a tar stream (local `tar -cf -`). */
+ packSkills: (dir: string, names: readonly string[]) => Promise<Buffer>
+ /** Open one dedicated authenticated session; the engine closes it. */
+ openSession: (machineId: MachineId) => Promise<SshSession>
+ /** Per-remote-command deadline (plugin adds are install-class operations). */
+ commandTimeoutMs?: number
+}
+
+/**
+ * The sync engine: preview from local sources, apply over one SSH session.
+ * Apply never throws for command-level failures — every requested item
+ * settles into the returned list, so the panel can render each outcome.
+ */
+export class SyncEngine {
+ constructor(private readonly deps: SyncEngineDeps) {}
+
+ /** The selectable local plugins and skills. */
+ preview(): SyncPreview {
+ return buildPreview(this.deps.profileDependencies(), this.deps.scanSkills())
+ }
+
+ /**
+ * Sync the selected plugins and skills to one machine, item by item.
+ * @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).
+ * @returns one outcome per requested item, in request order.
+ */
+ async apply(machineId: MachineId, plugins: readonly SyncPluginRef[], skills: readonly SyncSkillRef[]): 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 }
+ const session = await this.deps.openSession(machineId)
+ try {
+ await this.applyPlugins(session, uniquePlugins, items)
+ await this.applySkills(session, uniqueSkills, items)
+ }
+ finally {
+ await session.close().catch(() => undefined)
+ }
+ return { items }
+ }
+
+ /** 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> {
+ if (plugins.length === 0)
+ return
+ const dshPath = firstLineOf((await session.exec(probeDshCommand())).stdout)
+ for (const plugin of plugins) {
+ if (dshPath === '') {
+ items.push({
+ kind: 'plugin',
+ name: plugin.name,
+ ok: false,
+ error: 'no dsh binary on the remote (checked the login PATH, ~/.local/bin and ~/.dsh/source/current); install dsh first',
+ })
+ continue
+ }
+ const result = await session.exec(pluginAddCommand(dshPath, plugin.spec), {
+ ...this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs },
+ })
+ items.push(
+ result.code === 0
+ ? { kind: 'plugin', name: plugin.name, ok: true }
+ : { kind: 'plugin', name: plugin.name, ok: false, error: describeFailure(result.code, result.stdout, result.stderr) },
+ )
+ }
+ }
+
+ /** 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> {
+ if (skills.length === 0)
+ return
+ const roots = new Map(this.deps.scanSkills().map(entry => [entry.root as SyncSkillRoot, entry]))
+ for (const [root, entry] of roots) {
+ const requested = skills.filter(skill => skill.root === root)
+ if (requested.length === 0)
+ continue
+ const known = new Set(entry.names)
+ const transferable: SyncSkillRef[] = []
+ for (const skill of requested) {
+ if (known.has(skill.name)) {
+ transferable.push(skill)
+ }
+ else {
+ items.push({
+ kind: 'skill',
+ name: skill.name,
+ root,
+ ok: false,
+ error: `not found under the local "${root}" skill root (it may have been removed)`,
+ })
+ }
+ }
+ if (transferable.length === 0)
+ continue
+ let tar: Buffer
+ try {
+ tar = await this.deps.packSkills(entry.dir, transferable.map(skill => skill.name))
+ }
+ catch (error) {
+ // The local pack failed: every transferable item carries the reason.
+ const message = error instanceof Error ? error.message : String(error)
+ for (const skill of transferable) {
+ items.push({ kind: 'skill', name: skill.name, root, ok: false, error: message })
+ }
+ continue
+ }
+ const result = await session.exec(skillExtractCommand(), {
+ stdinData: tar,
+ ...this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs },
+ })
+ for (const skill of transferable) {
+ items.push(
+ result.code === 0
+ ? { kind: 'skill', name: skill.name, root, ok: true }
+ : { kind: 'skill', name: skill.name, root, ok: false, error: describeFailure(result.code, result.stdout, result.stderr) },
+ )
+ }
+ }
+ }
+}
+
+/** 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>()
+ const out: T[] = []
+ for (const item of items) {
+ const key = keyOf(item)
+ if (seen.has(key))
+ continue
+ seen.add(key)
+ out.push(item)
+ }
+ return out
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-ssh/src/host/service/transport.ts
index 575545b8..b3f53b62 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.ts
@@ -27,12 +27,18 @@ export interface SshExecResult {
stderr: string
}
-/** Optional exec behavior: a deadline and/or a streaming stdout tap. */
+/** Optional exec behavior: a deadline, a streaming stdout tap, and stdin bytes. */
export interface SshExecOptions {
/** Abort the command after this many milliseconds (closes the connection). */
timeoutMs?: number
/** Receive stdout chunks as they arrive (long-running commands, logs). */
onData?: (chunk: string) => void
+ /**
+ * Bytes written to the command's stdin, then EOF. Used to stream payloads
+ * (a skill tarball) without landing them on the remote command line, whose
+ * single-argument length the kernel caps far below a real payload.
+ */
+ stdinData?: Buffer
}
/** A local loopback listener forwarding into the SSH tunnel. */
@@ -368,6 +374,12 @@ class Ssh2Session implements SshSession {
}
let stdout = ''
let stderr = ''
+ // Stdin payloads go out first (half-close semantics: EOF lets the
+ // remote `tar -xf -` finish while stdout keeps flowing back).
+ if (options?.stdinData !== undefined && options.stdinData.length > 0) {
+ stream.write(options.stdinData)
+ stream.end()
+ }
stream.on('data', (chunk: Buffer) => {
const text = chunk.toString('utf8')
stdout += text