DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh): binary bootstrap with arm64 matrix, version pin, boot-HTML readiness, machine.events channel
Menghuan19187a675e54adea
diff --git a/packages/dsh-tauri-ssh/src/host/apply.test.ts b/packages/dsh-tauri-ssh/src/host/apply.test.tsindex 5068bdce..a0761587 100644--- a/packages/dsh-tauri-ssh/src/host/apply.test.ts+++ b/packages/dsh-tauri-ssh/src/host/apply.test.ts@@ -207,10 +207,10 @@ describe('ssh-remote plugin', () => {it('forwards installs to the manager', async () => {const { service } = boot()const install = vi.spyOn(service.manager, 'install')- .mockResolvedValue({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })+ .mockResolvedValue({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true })const result = await service.install(MachineId('a'))expect(install).toHaveBeenCalledWith(MachineId('a'), undefined)- expect(result).toEqual({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })+ expect(result).toEqual({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true })})it('saves a machine through the settings scope and refreshes the manager', async () => {diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.tsindex 20859c65..a839b824 100644--- a/packages/dsh-tauri-ssh/src/host/apply.ts+++ b/packages/dsh-tauri-ssh/src/host/apply.ts@@ -12,12 +12,13 @@ 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'-import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineStatus, SshTestResult } from './types/index.js'+import type { HostSettingsScope, MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineEventsPage, SshMachineStatus, SshTestResult } from './types/index.js'import { homedir } from 'node:os'import process from 'node:process'import { join } from 'pathe'import { SSH_API_PREFIX, SSH_PLUGIN_NAME } from '../shared/constants.js'import { createSshApiHandler } from './routes/index.js'+import { SshMachineEvents } from './service/events.js'import { KnownHostsStore } from './service/host-keys.js'import { profileView, SshManager } from './service/manager.js'import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config.js'@@ -41,6 +42,9 @@ export class SshRemoteService implements SshApiHost {/** The connection manager (transport, TOFU store, and per-machine state). */readonly manager: SshManager+ /** The machine event channel drained by the `/api-ssh` `machine.events` method. */+ readonly machineEvents: SshMachineEvents+/** The registered settings scope; the write path for machine CRUD. */private scope!: HostSettingsScope<MachinesValue>@@ -62,6 +66,7 @@ export class SshRemoteService implements SshApiHost {this.homeDir = homedir()this.sshDir = config.sshDir ?? join(this.homeDir, '.ssh')this.config = config+ this.machineEvents = new SshMachineEvents()this.manager = new SshManager({transport: new Ssh2Transport(config.connectTimeoutMs,@@ -71,6 +76,7 @@ export class SshRemoteService implements SshApiHost {),knownHosts,config,+ events: this.machineEvents,// v8 ignore next -- deliberately empty status hook: the settings page polls /api-sshemitStatus: () => {// The settings page polls status through /api-ssh; no live consumers.@@ -189,6 +195,10 @@ export class SshRemoteService implements SshApiHost {return this.manager.install(machineId, signal)}+ events(machineId: MachineId, sinceSeq?: number): SshMachineEventsPage {+ return this.machineEvents.since(machineId, sinceSeq)+ }+/*** Upsert one machine profile: merge the config row and any freshly typed* secrets into the stored profile (secrets omitted keep the stored value).diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts b/packages/dsh-tauri-ssh/src/host/routes/index.test.tsindex d4c9a075..bbbc8090 100644--- a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts+++ b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts@@ -4,6 +4,7 @@ import { Buffer } from 'node:buffer'import { IncomingMessage, ServerResponse } from 'node:http'import { Socket } from 'node:net'import { describe, expect, it, vi } from 'vitest'+import { SshMachineEvents } from '../service/events.js'import { MachineId, SshError } from '../types/index.js'import { createSshApiHandler, isLoopbackPeer } from './index.js'@@ -18,6 +19,12 @@ const view: MachineView = {remotePort: 3080,}+/** A seeded per-machine event log shared by the fake host. */+const log = new SshMachineEvents()+log.append(MachineId('m1'), 'probe', '探测远端平台 (uname -srm)')+log.append(MachineId('m1'), 'download', 'https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.gz')+log.append(MachineId('m1'), 'ready', '远端实例已就绪', { terminal: 'success' })+function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {return {profileViews: () => [view],@@ -26,7 +33,8 @@ function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {test: async (): Promise<SshTestResult> => ({ ok: true, banner: 'Linux alpha' }),connect: async () => ({ tunnelBaseUrl: 'http://127.0.0.1:45678' }),disconnect: async () => {},- install: async () => ({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }),+ install: async () => ({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true }),+ events: (machineId, sinceSeq) => log.since(machineId, sinceSeq),save: async () => {},remove: async () => {},...overrides,@@ -318,13 +326,13 @@ describe('/api-ssh handler', () => {})it('installs dsh on a machine and returns the outcome', async () => {- const install = vi.fn(async () => ({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }))+ const install = vi.fn(async () => ({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true }))const host = fakeHost({ install })const { status, body } = await call(host, JSON.stringify({ method: 'machine.install', payload: { machineId: 'm1' } }))expect(status).toBe(200)expect(body).toEqual({ok: true,- value: { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true },+ value: { installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true },})expect(install).toHaveBeenCalledWith(MachineId('m1'), expect.any(AbortSignal))})@@ -386,4 +394,42 @@ describe('/api-ssh handler', () => {expect(status).toBe(404)expect(body).toMatchObject({ ok: false, error: { code: 'unknown-method' } })})+ it('drains machine events from the beginning', async () => {+ const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'm1' } }))+ expect(response.status).toBe(200)+ expect(response.body).toEqual({+ ok: true,+ value: {+ events: [+ expect.objectContaining({ seq: 1, stage: 'probe' }),+ expect.objectContaining({ seq: 2, stage: 'download' }),+ expect.objectContaining({ seq: 3, stage: 'ready', terminal: 'success' }),+ ],+ nextSeq: 4,+ },+ })+ })++ it('drains machine events incrementally by sinceSeq', async () => {+ const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'm1', sinceSeq: 2 } }))+ expect(response.body).toMatchObject({+ ok: true,+ value: {+ events: [expect.objectContaining({ seq: 3 })],+ nextSeq: 4,+ },+ })+ })++ it('reports unknown event machines as an empty page anchored at seq 1', async () => {+ const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'ghost' } }))+ expect(response.body).toEqual({ ok: true, value: { events: [], nextSeq: 1 } })+ })++ it('rejects malformed event cursors', async () => {+ const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'm1', sinceSeq: -1 } }))+ expect(response.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid sinceSeq' } })+ const missing = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: {} }))+ expect(missing.body).toEqual({ ok: false, error: { code: 'internal', message: 'missing machineId' } })+ })})diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.ts b/packages/dsh-tauri-ssh/src/host/routes/index.tsindex d43387cf..77d8d651 100644--- a/packages/dsh-tauri-ssh/src/host/routes/index.ts+++ b/packages/dsh-tauri-ssh/src/host/routes/index.ts@@ -7,15 +7,17 @@* POST /api-ssh { "method": "machine.list", "payload": {} }* → 200 { "ok": true, "value": ... } | { "ok": false, "error": { "code", "message" } }*- * Machines are stored in the `ssh-machines` settings namespace; this API only- * serves the connection plane (list/test/connect/disconnect) and the CRUD- * writes (save/remove), which is exactly what the settings page cannot do- * through the settings domain.+ * Machines are stored in the `ssh-machines` settings namespace; this API+ * serves the connection plane (list/test/connect/disconnect/install), the+ * per-machine bootstrap event drain (`machine.events`: ring-buffered,+ * seq-cursored polling — no SSE/WebSocket), and the CRUD writes+ * (save/remove), which is exactly what the settings page cannot do through+ * the settings domain.* @module dsh-tauri-ssh/host/routes*/import type { IncomingMessage, ServerResponse } from 'node:http'-import type { MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshMachineStatus, SshTestResult } from '../types/index.js'+import type { MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshMachineEventsPage, SshMachineStatus, SshTestResult } from '../types/index.js'import { Buffer } from 'node:buffer'import { MachineId, SshError } from '../types/index.js'@@ -40,6 +42,7 @@ export type SshApiMethod| 'machine.connect'| 'machine.disconnect'| 'machine.install'+ | 'machine.events'| 'machine.save'| 'machine.remove'@@ -62,6 +65,8 @@ export interface SshApiHost {disconnect: (machineId: MachineId) => Promise<void>/** One-shot remote dsh install; a successful install auto-connects. */install: (machineId: MachineId, signal?: AbortSignal) => Promise<SshInstallResult>+ /** Drain one machine's bootstrap log/progress events after a seq cursor. */+ events: (machineId: MachineId, sinceSeq?: number) => SshMachineEventsPagesave: (machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite) => Promise<void>remove: (machineId: MachineId) => Promise<void>}@@ -153,6 +158,12 @@ export function createSshApiHandler(host: SshApiHost): (req: IncomingMessage, rerespond(200, { ok: true, value })return}+ case 'machine.events': {+ const machineId = machineIdOf(payload)+ const sinceSeq = sinceSeqOf(payload)+ respond(200, { ok: true, value: host.events(machineId, sinceSeq) })+ return+ }case 'machine.save': {const machineId = machineIdOf(payload)const row = saveRowOf(payload)@@ -185,6 +196,16 @@ function machineIdOf(payload: Record<string, unknown>): MachineId {return MachineId(payload.machineId)}+/** Read the optional event poll cursor; absent or non-numeric means "from the start". */+function sinceSeqOf(payload: Record<string, unknown>): number | undefined {+ if (payload.sinceSeq === undefined)+ return undefined+ if (typeof payload.sinceSeq !== 'number' || !Number.isInteger(payload.sinceSeq) || payload.sinceSeq < 0) {+ throw new Error('invalid sinceSeq')+ }+ return payload.sinceSeq+}+/** One list row: the redacted view plus its live status. */function listItemOf(host: SshApiHost, view: MachineView): SshMachineListItem {const status = host.status(view.id)diff --git a/packages/dsh-tauri-ssh/src/host/service/assets.test.ts b/packages/dsh-tauri-ssh/src/host/service/assets.test.tsnew file mode 100644index 00000000..c56649b6--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/assets.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest'+import {+ assetMatrixFor,+ dshNpmTarballUrls,+ dshZipDownloadUrls,+ nodeDownloadUrls,+ nodeFilenameFor,+ nodeShasumUrls,+ parsePlatform,+ pnpmDownloadUrls,+ UnsupportedRemotePlatformError,+} from './assets.js'++describe('parsePlatform', () => {+ it('maps uname output onto repo identifiers (amd64/aarch64 aliases included)', () => {+ expect(parsePlatform('Linux 6.8.0-45-generic x86_64\n')).toEqual({ os: 'linux', arch: 'x64' })+ expect(parsePlatform('Linux 5.15 aarch64')).toEqual({ os: 'linux', arch: 'arm64' })+ expect(parsePlatform('Linux 6.1 amd64')).toEqual({ os: 'linux', arch: 'x64' })+ expect(parsePlatform('Darwin host.local 24.0 x86_64')).toEqual({ os: 'macos', arch: 'x64' })+ })++ it('rejects unsupported systems and architectures with the detected pair', () => {+ const unsupported = (out: string): UnsupportedRemotePlatformError => {+ try {+ parsePlatform(out)+ }+ catch (error) {+ if (error instanceof UnsupportedRemotePlatformError)+ return error+ throw error+ }+ throw new Error('expected a rejection')+ }+ expect(unsupported('MINGW64_NT-10.0 x86_64').detected).toEqual({ system: 'MINGW64_NT-10.0', machine: 'x86_64' })+ expect(unsupported('Linux 6.8 riscv64').detected).toEqual({ system: 'Linux', machine: 'riscv64' })+ expect(unsupported('Darwin host.local 24.0 arm64').message).toContain('macOS arm64')+ expect(unsupported('').message).toContain('REMOTE_PLATFORM_UNSUPPORTED')+ })+})++describe('assetMatrixFor', () => {+ it('linux x64 installs the packaged zip', () => {+ const matrix = assetMatrixFor('linux', 'x64')+ expect(matrix.dshKind).toBe('pkg-zip')+ expect(matrix.dshZipName).toBe('deepseek-harness-pkg-linux.zip')+ expect(matrix.nodeFilename).toBe('node-v22.22.0-linux-x64.tar.gz')+ })++ it('linux arm64 installs the npm tarball (no packaged arm64 zip exists)', () => {+ const matrix = assetMatrixFor('linux', 'arm64')+ expect(matrix.dshKind).toBe('npm-tgz')+ expect(matrix.dshNpmPackage).toBe('@deepseek-ai/dsh')+ expect(matrix.nodeFilename).toBe('node-v22.22.0-linux-arm64.tar.gz')+ })++ it('macos x64 installs the packaged zip', () => {+ const matrix = assetMatrixFor('macos', 'x64')+ expect(matrix.dshKind).toBe('pkg-zip')+ expect(matrix.dshZipName).toBe('deepseek-harness-pkg-macos-x64.zip')+ expect(matrix.nodeFilename).toBe('node-v22.22.0-darwin-x64.tar.gz')+ })++ it('rejects macOS arm64 and other unsupported combinations', () => {+ expect(() => assetMatrixFor('macos', 'arm64')).toThrow(UnsupportedRemotePlatformError)+ // Windows remotes: v1 limitation carried forward.+ expect(() => assetMatrixFor('windows' as 'linux', 'x64')).toThrow(UnsupportedRemotePlatformError)+ // Unknown architectures carry no Node asset; the matrix surfaces the typed error.+ expect(nodeFilenameFor('linux', 'riscv64' as 'arm64')).toBeUndefined()+ })+})++describe('download URL builders', () => {+ it('pairs every asset with its official source and mirror, in order', () => {+ expect(nodeDownloadUrls('linux', 'x64')).toEqual([+ 'https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.gz',+ 'https://npmmirror.com/mirrors/node/v22.22.0/node-v22.22.0-linux-x64.tar.gz',+ ])+ expect(nodeDownloadUrls('linux', 'arm64')).toEqual([+ 'https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-arm64.tar.gz',+ 'https://npmmirror.com/mirrors/node/v22.22.0/node-v22.22.0-linux-arm64.tar.gz',+ ])+ expect(nodeDownloadUrls('macos', 'x64')).toEqual([+ 'https://nodejs.org/dist/v22.22.0/node-v22.22.0-darwin-x64.tar.gz',+ 'https://npmmirror.com/mirrors/node/v22.22.0/node-v22.22.0-darwin-x64.tar.gz',+ ])+ expect(nodeShasumUrls()[0]).toBe('https://nodejs.org/dist/v22.22.0/SHASUMS256.txt')+ expect(nodeShasumUrls()[1]).toContain('npmmirror.com')+ expect(pnpmDownloadUrls()).toEqual([+ 'https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz',+ 'https://registry.npmmirror.com/pnpm/-/pnpm-11.7.0.tgz',+ ])+ })++ it('builds the packaged zip URL pair (GitHub official → ghfast.top mirror)', () => {+ expect(dshZipDownloadUrls('dsh-tauri-desk/deepseek-harness-pkg', 'dsh-0.1.2-rc.1-1', 'deepseek-harness-pkg-linux.zip')).toEqual([+ 'https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-1/deepseek-harness-pkg-linux.zip',+ 'https://ghfast.top/https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-1/deepseek-harness-pkg-linux.zip',+ ])+ })++ it('builds the npm tarball URL pair for the arm64 kind', () => {+ expect(dshNpmTarballUrls('@deepseek-ai/dsh', '0.1.2-rc.1')).toEqual([+ 'https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz',+ 'https://registry.npmmirror.com/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz',+ ])+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/assets.ts b/packages/dsh-tauri-ssh/src/host/service/assets.tsnew file mode 100644index 00000000..2bd2c93e--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/assets.ts@@ -0,0 +1,189 @@+/**+ * The remote install asset matrix: `uname` output → platform identifiers, the+ * per-platform choice of the three install assets (Node runtime, DSH+ * distribution, pnpm), and their official → mirror download URL pairs. Pure+ * functions over injectable constants so the matrix is fully unit-testable+ * without touching the network.+ *+ * DSH ships two distribution kinds: the packaged zip (a `pnpm deploy` tree+ * with platform-pinned native modules — only linux x64 and macOS x64 assets+ * exist) and the npm tarball of `@deepseek-ai/dsh` (assembled on the remote+ * by `pnpm install`, which resolves the correct platform natives — the only+ * honest asset for linux arm64, where no packaged zip exists).+ * @module dsh-tauri-ssh/host/service/assets+ */++/** Remote platform identifiers the install matrix understands. */+export type RemoteOs = 'linux' | 'macos'++/** Remote CPU architectures the install matrix understands. */+export type RemoteArch = 'x64' | 'arm64'++/** How the DSH distribution is fetched and laid out for one platform. */+export type DshAssetKind = 'pkg-zip' | 'npm-tgz'++/** One supported matrix cell. */+export interface RemoteAssetMatrix {+ os: RemoteOs+ arch: RemoteArch+ /** The DSH distribution kind this platform installs. */+ dshKind: DshAssetKind+ /** Node.js distribution tarball file name (under `<base>/<version>/`). */+ nodeFilename: string+ /** The packaged DSH zip asset name, when `dshKind` is `pkg-zip`. */+ dshZipName?: string+ /** The npm package the `npm-tgz` kind installs. */+ dshNpmPackage?: string+}++/** Typed failure for a remote platform outside the install matrix. */+export class UnsupportedRemotePlatformError extends Error {+ /** The raw `uname -srm` parts as detected (first column, last column). */+ readonly detected: { system: string, machine: string }++ constructor(system: string, machine: string) {+ super(+ `REMOTE_PLATFORM_UNSUPPORTED: 不支持远端系统/架构 ${system}/${machine}`+ + '(支持矩阵:linux x64、linux arm64、macOS x64;远端 Windows 与 macOS arm64 明确不支持)',+ )+ this.name = 'UnsupportedRemotePlatformError'+ this.detected = { system, machine }+ }+}++/**+ * Parse `uname -srm` output into the platform identifiers. Output looks like+ * `Linux 6.8.0-45-generic x86_64` / `Darwin host.local 24.0 arm64`: the+ * system name is the first column, the machine architecture the last.+ * @param unameOut - the raw `uname -srm` stdout.+ * @returns the supported (os, arch) pair.+ * @throws {UnsupportedRemotePlatformError} for anything outside the matrix.+ */+export function parsePlatform(unameOut: string): { os: RemoteOs, arch: RemoteArch } {+ const parts = unameOut.trim().split(/\s+/u)+ const system = parts[0] ?? ''+ const machine = parts.length > 1 ? parts[parts.length - 1] ?? '' : ''+ const os: RemoteOs | undefined = system === 'Linux' ? 'linux' : system === 'Darwin' ? 'macos' : undefined+ const arch: RemoteArch | undefined = machine === 'x86_64' || machine === 'amd64'+ ? 'x64'+ : machine === 'aarch64' || machine === 'arm64' ? 'arm64' : undefined+ // macOS arm64 remotes are deliberately out of scope (spec S2): the matrix+ // stops at the three combinations the distribution actually covers.+ if (os === undefined || arch === undefined || (os === 'macos' && arch === 'arm64'))+ throw new UnsupportedRemotePlatformError(system, machine)+ return { os, arch }+}++/**+ * The asset matrix cell for one supported platform.+ * @param os - the remote operating system.+ * @param arch - the remote CPU architecture.+ * @returns the matrix entry (asset names; URLs are built by the dedicated+ * builders).+ * @throws {UnsupportedRemotePlatformError} for combinations outside the+ * matrix (Windows, macOS arm64, other architectures).+ */+export function assetMatrixFor(os: RemoteOs, arch: RemoteArch): RemoteAssetMatrix {+ const nodeFilename = nodeFilenameFor(os, arch)+ if (nodeFilename === undefined)+ throw new UnsupportedRemotePlatformError(os, arch)+ if (os === 'linux' && arch === 'x64') {+ return { os, arch, dshKind: 'pkg-zip', nodeFilename, dshZipName: 'deepseek-harness-pkg-linux.zip' }+ }+ if (os === 'linux' && arch === 'arm64') {+ // No packaged arm64 zip exists (the zips carry x64-pinned natives);+ // the npm tarball lets the remote resolve arm64 natives itself.+ return { os, arch, dshKind: 'npm-tgz', nodeFilename, dshNpmPackage: '@deepseek-ai/dsh' }+ }+ if (os === 'macos' && arch === 'x64') {+ return { os, arch, dshKind: 'pkg-zip', nodeFilename, dshZipName: 'deepseek-harness-pkg-macos-x64.zip' }+ }+ throw new UnsupportedRemotePlatformError(os, arch)+}++/** Bundled Node.js runtime line (satisfies DSH's `^22.19.0 || >=24` engine). */+export const NODE_VERSION = 'v22.22.0'++/** Node.js official distribution base. */+export const NODE_BASE_URL = 'https://nodejs.org/dist/'++/** Node.js mirror base (npmmirror; domestic fallback). */+export const NODE_MIRROR_BASE_URL = 'https://npmmirror.com/mirrors/node/'++/** pnpm version, aligned with the packaged distribution's `packageManager`. */+export const PNPM_VERSION = '11.7.0'++/** pnpm npm tarball SHA-256; must be updated together with the version. */+export const PNPM_SHA256 = 'deafa7ec98a1218b6a047289b92fbe2395c1e22d3495bb711653013218ee15ee'++/** pnpm official npm registry tarball base. */+export const PNPM_BASE_URL = 'https://registry.npmjs.org/pnpm/-/'++/** pnpm mirror (npmmirror registry) tarball base. */+export const PNPM_MIRROR_BASE_URL = 'https://registry.npmmirror.com/pnpm/-/'++/** npm registry bases for the `npm-tgz` DSH kind (official → mirror). */+export const NPM_REGISTRY_BASES = ['https://registry.npmjs.org', 'https://registry.npmmirror.com'] as const++/** The Node.js tarball file name for one platform, when supported. */+export function nodeFilenameFor(os: RemoteOs, arch: RemoteArch): string | undefined {+ if (os === 'linux' && arch === 'x64')+ return `node-${NODE_VERSION}-linux-x64.tar.gz`+ if (os === 'linux' && arch === 'arm64')+ return `node-${NODE_VERSION}-linux-arm64.tar.gz`+ if (os === 'macos' && arch === 'x64')+ return `node-${NODE_VERSION}-darwin-x64.tar.gz`+ return undefined+}+/**+ * The Node.js tarball download URLs (official → mirror), in fallback order.+ * @param os - the remote operating system.+ * @param arch - the remote CPU architecture.+ */+export function nodeDownloadUrls(os: RemoteOs, arch: RemoteArch): string[] {+ const filename = nodeFilenameFor(os, arch)+ if (filename === undefined)+ throw new UnsupportedRemotePlatformError(os, arch)+ return [+ `${NODE_BASE_URL}${NODE_VERSION}/${filename}`,+ `${NODE_MIRROR_BASE_URL}${NODE_VERSION}/${filename}`,+ ]+}++/** The Node.js `SHASUMS256.txt` URLs (official → mirror). */+export function nodeShasumUrls(): string[] {+ return [+ `${NODE_BASE_URL}${NODE_VERSION}/SHASUMS256.txt`,+ `${NODE_MIRROR_BASE_URL}${NODE_VERSION}/SHASUMS256.txt`,+ ]+}++/** The pnpm tarball download URLs (official registry → mirror). */+export function pnpmDownloadUrls(): string[] {+ return [+ `${PNPM_BASE_URL}pnpm-${PNPM_VERSION}.tgz`,+ `${PNPM_MIRROR_BASE_URL}pnpm-${PNPM_VERSION}.tgz`,+ ]+}++/**+ * The packaged DSH zip download URLs (GitHub official → ghfast.top mirror)+ * for one release tag.+ * @param repo - the GitHub `owner/name` hosting the packaged releases.+ * @param tag - the release tag.+ * @param assetName - the platform zip asset name.+ */+export function dshZipDownloadUrls(repo: string, tag: string, assetName: string): string[] {+ const official = `https://github.com/${repo}/releases/download/${tag}/${assetName}`+ return [official, `https://ghfast.top/${official}`]+}++/**+ * The `@deepseek-ai/dsh` npm tarball URLs (official registry → mirror) for+ * one version. The packument's `dist.tarball` URL shape is deterministic.+ * @param packageName - the scoped npm package name.+ * @param version - the resolved package version.+ */+export function dshNpmTarballUrls(packageName: string, version: string): string[] {+ return NPM_REGISTRY_BASES.map(base => `${base}/${packageName}/-/${packageName.split('/')[1]}-${version}.tgz`)+}diff --git a/packages/dsh-tauri-ssh/src/host/service/boot-html.test.ts b/packages/dsh-tauri-ssh/src/host/service/boot-html.test.tsnew file mode 100644index 00000000..0b2530f1--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/boot-html.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest'+import { clientUrlsFromBootHtml, decodeHtmlAttribute, isClientBundlePath, looksLikePluginBundle } from './boot-html.js'++/** A realistic rc-line boot page: combo preload script + entries graph. */+const BOOT_HTML = [+ '<!doctype html><html><head>',+ '<script src="/plugins/??@deepseek-ai/dsh-client-modules/client.js&rev=cddf5581d5d5"></script>',+ '</head><body><div id="root"></div><script>',+ 'globalThis["__DSH_BOOT__"] = {"entries":[{"url":"/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"},{"url":"/plugins/@deepseek-ai/dsh-client-modules/client.js"}]};',+ '</script></body></html>',+].join('')++describe('clientUrlsFromBootHtml', () => {+ it('parses a normal boot graph into sorted, deduped loopback bundle URLs', () => {+ const urls = clientUrlsFromBootHtml(3099, BOOT_HTML)+ expect(urls).toBeDefined()+ expect(urls).toEqual([+ 'http://127.0.0.1:3099/plugins/??@deepseek-ai/dsh-client-modules/client.js&rev=cddf5581d5d5',+ 'http://127.0.0.1:3099/plugins/@deepseek-ai/dsh-client-modules/client.js',+ 'http://127.0.0.1:3099/plugins/@deepseek-ai/dsh-client-ui-layout/client.js',+ ])+ })++ it('decodes the combo attribute URL before use (&rev= → &rev=)', () => {+ const html = '<script src="/plugins/??pkg/client.js&rev=1"></script><script>globalThis["__DSH_BOOT__"] = {"entries":[]}</script>'+ expect(clientUrlsFromBootHtml(3081, html)).toEqual([+ 'http://127.0.0.1:3081/plugins/??pkg/client.js&rev=1',+ ])+ })++ it('returns undefined when the marker is missing (not a dsh boot page)', () => {+ expect(clientUrlsFromBootHtml(3080, '<html><body>plain</body></html>')).toBeUndefined()+ expect(clientUrlsFromBootHtml(3080, '')).toBeUndefined()+ })++ it('returns undefined for malformed manifest JSON', () => {+ const html = '<script>globalThis["__DSH_BOOT__"] = {not json!;</script>'+ expect(clientUrlsFromBootHtml(3080, html)).toBeUndefined()+ const noEnd = '<script>globalThis["__DSH_BOOT__"] = {"entries":[]}'+ expect(clientUrlsFromBootHtml(3080, noEnd)).toBeUndefined()+ })++ it('returns undefined when entries is absent or every URL is foreign', () => {+ const noEntries = '<script>globalThis["__DSH_BOOT__"] = {}</script>'+ expect(clientUrlsFromBootHtml(3080, noEntries)).toBeUndefined()+ const foreign = '<script>globalThis["__DSH_BOOT__"] = {"entries":[{"url":"https://example.test/client.js"}]}</script>'+ expect(clientUrlsFromBootHtml(3080, foreign)).toBeUndefined()+ })++ it('accepts single-quoted marker assignments and a trailing semicolon', () => {+ const html = '<script>globalThis[\'__DSH_BOOT__\'] = {"entries":[{"url":"/plugins/x/client.js"}]} ;</script>'+ expect(clientUrlsFromBootHtml(3080, html)).toEqual(['http://127.0.0.1:3080/plugins/x/client.js'])+ })+})++describe('isClientBundlePath', () => {+ it('accepts same-origin plugin bundle paths, including the combo route', () => {+ expect(isClientBundlePath('/plugins/@scope/pkg/client.js')).toBe(true)+ expect(isClientBundlePath('/plugins/??@scope/pkg/client.js&rev=1')).toBe(true)+ })++ it('rejects foreign, protocol-relative, and non-bundle paths', () => {+ expect(isClientBundlePath('https://evil.test/client.js')).toBe(false)+ expect(isClientBundlePath('//evil.test/plugins/x/client.js')).toBe(false)+ expect(isClientBundlePath('/assets/index.js')).toBe(false)+ })+})++describe('looksLikePluginBundle', () => {+ it('rejects empty bodies and HTML (the SPA fallback answers 200 too)', () => {+ expect(looksLikePluginBundle(true, '')).toBe(false)+ expect(looksLikePluginBundle(true, ' \n ')).toBe(false)+ expect(looksLikePluginBundle(true, '<!doctype html><html>')).toBe(false)+ expect(looksLikePluginBundle(true, '<HTML lang="en">')).toBe(false)+ })++ it('accepts JavaScript bodies on successful exchanges only', () => {+ expect(looksLikePluginBundle(true, 'console.log(1)')).toBe(true)+ expect(looksLikePluginBundle(false, 'console.log(1)')).toBe(false)+ })+})++describe('decodeHtmlAttribute', () => {+ it('restores the limited named entities', () => {+ expect(decodeHtmlAttribute('&"'<>')).toBe('&"\'<>')+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/boot-html.ts b/packages/dsh-tauri-ssh/src/host/service/boot-html.tsnew file mode 100644index 00000000..dc5eefb6--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/boot-html.ts@@ -0,0 +1,110 @@+/**+ * Boot-HTML readiness parsing, ported from the retired Rust engine's+ * `client_urls_from_boot_html` (`service/workflow/utils.rs`): the remote+ * instance's readiness verdict comes from the `__DSH_BOOT__` client manifest+ * embedded in its served HTML — a real manifest proves the actual dsh web+ * server is up with its plugin bundles mounted, where a bare "some HTTP+ * server answered" probe (the legacy fallback) cannot.+ * @module dsh-tauri-ssh/host/service/boot-html+ */++/** The boot-manifest assignment marker inside the served HTML. */+const BOOT_MARKER = /globalThis\[(['"])__DSH_BOOT__\1\]\s*=\s*/u++/**+ * Extract the client-bundle URLs from one served boot HTML document. Both+ * collection axes of the blueprint are honored: the `entries[].url` graph of+ * the `__DSH_BOOT__` manifest and the `<script src>` attributes (the preload+ * script does not always repeat in entries), deduped and sorted.+ * @param port - the remote instance's loopback port.+ * @param html - the HTML the root probe received.+ * @returns the absolute loopback URLs, or undefined when the document is not+ * a dsh boot page (marker missing, malformed manifest JSON, no entries+ * array, or no same-origin client-bundle paths at all).+ */+export function clientUrlsFromBootHtml(port: number, html: string): string[] | undefined {+ const marker = BOOT_MARKER.exec(html)+ if (marker === null)+ return undefined+ const start = marker.index + marker[0].length+ const end = html.indexOf('</script>', start)+ if (end < 0)+ return undefined+ const json = html.slice(start, end).trim().replace(/;$/u, '').trim()+ let boot: unknown+ try {+ boot = JSON.parse(json)+ }+ catch {+ return undefined+ }+ const entries = (boot as { entries?: unknown }).entries+ if (!Array.isArray(entries))+ return undefined+ const paths: string[] = []+ for (const script of html.split('<script').slice(1)) {+ const srcStart = script.indexOf('src="')+ if (srcStart < 0)+ continue+ const rest = script.slice(srcStart + 5)+ const srcEnd = rest.indexOf('"')+ if (srcEnd < 0)+ continue+ const src = decodeHtmlAttribute(rest.slice(0, srcEnd))+ if (isClientBundlePath(src))+ paths.push(src)+ }+ for (const entry of entries) {+ const url = (entry as { url?: unknown }).url+ if (typeof url !== 'string')+ continue+ const decoded = decodeHtmlAttribute(url)+ if (isClientBundlePath(decoded))+ paths.push(decoded)+ }+ const unique = [...new Set(paths)].sort()+ if (unique.length === 0)+ return undefined+ return unique.map(path => `http://127.0.0.1:${port}${path}`)+}++/**+ * Whether a probe response body is a plugin bundle (not the SPA fallback):+ * unknown `/plugins/...` paths get rewritten to `index.html` with HTTP 200,+ * so an HTML-looking body must not count as a served bundle.+ * @param okStatus - whether the HTTP exchange itself succeeded (2xx).+ * @param body - the response body.+ */+export function looksLikePluginBundle(okStatus: boolean, body: string): boolean {+ if (!okStatus)+ return false+ const trimmed = body.trimStart()+ if (trimmed === '')+ return false+ const lower = trimmed.slice(0, 32).toLowerCase()+ return !lower.startsWith('<!doctype') && !lower.startsWith('<html')+}++/**+ * Restore the limited named entities boot HTML attributes/JSON carry (the+ * combo route's `&rev=` arrives as `&rev=`).+ * @param value - the raw attribute value.+ */+export function decodeHtmlAttribute(value: string): string {+ return value+ .replaceAll('&', '&')+ .replaceAll('"', '\"')+ .replaceAll(''', '\'')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+}++/**+ * Whether a path is a same-origin client-bundle path: under `/plugins/`,+ * naming `client.js` (the combo route's `/plugins/??<pkg>/client.js&rev=…`+ * included), and never protocol-relative.+ * @param path - the candidate path.+ */+export function isClientBundlePath(path: string): boolean {+ return path.startsWith('/plugins/') && path.includes('client.js') && !path.startsWith('//')+}diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.tsnew file mode 100644index 00000000..6f27ff83--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts@@ -0,0 +1,44 @@+/* eslint-disable no-console -- the run's console output IS the recorded evidence */+/**+ * arm64 substitute evidence (spec S2 acceptance 6): no arm64 machine exists,+ * so the dry run resolves the REAL linux/arm64 install plan against the live+ * npm registry and proves every download URL answers — without writing any+ * bytes to disk. Gated behind `DSH_SSH_ARM64_DRYRUN=1`:+ *+ * DSH_SSH_ARM64_DRYRUN=1 pnpm --filter dsh-tauri-ssh exec vitest run \+ * src/host/service/bootstrap.arm64-dryrun.test.ts+ * @module dsh-tauri-ssh/host/service/bootstrap.arm64-dryrun+ */++import { describe, expect, it } from 'vitest'+import { buildInstallScript, planRemoteInstall } from './bootstrap.js'++const RUN = process.env.DSH_SSH_ARM64_DRYRUN === '1'++describe.skipIf(!RUN)('arm64 install dry run (real metadata, no disk writes)', () => {+ it('resolves the live arm64 plan and verifies every URL answers a HEAD', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic aarch64', {})+ console.log('[arm64-dryrun] plan:', JSON.stringify({+ os: plan.os,+ arch: plan.arch,+ dshKind: plan.dsh.kind,+ dshVersion: plan.dshVersion,+ notes: plan.notes,+ }, null, 2))+ const urls = [+ ...plan.node.urls,+ ...plan.node.shasumUrls,+ ...plan.dsh.urls,+ ...plan.pnpm.urls,+ ]+ for (const url of urls) {+ const response = await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(30_000) })+ console.log(`[arm64-dryrun] HEAD ${response.status} ${url}`)+ expect(response.status, url).toBeLessThan(400)+ }+ // The generated script must carry the npm-kind assembly path.+ const script = buildInstallScript(plan)+ expect(script).toContain('install --prod --silent --registry')+ console.log('[arm64-dryrun] script bytes:', script.length)+ }, 120_000)+})diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.tsnew file mode 100644index 00000000..8e51f10b--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts@@ -0,0 +1,190 @@+/**+ * Real-machine E2E (linux x64): a fresh remote bootstrap through the REAL+ * transport, planner (live GitHub metadata), install script, launch, and+ * boot-HTML readiness, then a reconnect that skips the install. Gated behind+ * `DSH_SSH_E2E_HOST` so the ordinary test run never needs a remote:+ *+ * DSH_SSH_E2E_HOST=dev pnpm --filter dsh-tauri-ssh exec vitest run \+ * src/host/service/bootstrap.e2e.test.ts+ *+ * Shares the machine with parallel nodes: default layout (`~/.dsh-desktop`)+ * and the default port, leftover processes cleaned before and after, and the+ * installed tree deliberately left in place (the shared "already+ * initialized" state other nodes may reuse).+ * @module dsh-tauri-ssh/host/service/bootstrap.e2e+ */++/* eslint-disable no-console -- the run's console output IS the recorded evidence */+import type { MachineProfile, SshLink } from '../types/index.js'+import type { SshTransport } from './transport.js'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { MachineId } from '../types/index.js'+import { SshMachineEvents } from './events.js'+import { KnownHostsStore } from './host-keys.js'+import { SshManager } from './manager.js'+import { SshConfigResolver } from './ssh-config.js'+import { Ssh2Transport } from './transport.js'++/** The shared dev machine alias from `~/.ssh/config` (key auth). */+const HOST = process.env.DSH_SSH_E2E_HOST++/**+ * The remote instance port. Defaults to 3080; the shared dev machine's 3080+ * is held by caddy (shared infra, never touched), so runs there pass an+ * explicit free port (e.g. `DSH_SSH_E2E_PORT=3082`).+ */+const PORT = Number.parseInt(process.env.DSH_SSH_E2E_PORT ?? '3080', 10)++/** Generous budgets: real downloads (~90 MB) over SSH plus instance start. */+const E2E_CONFIG = {+ connectTimeoutMs: 30_000,+ healthCheckTimeoutMs: 5_000,+ healthPollIntervalMs: 1_000,+ healthPollAttempts: 90,+ installTimeoutMs: 1_800_000,+}++/** Kill only processes whose command line references the shared layout. */+const CLEANUP_COMMAND = [+ `if [ -f "$HOME/.dsh/.dsh-remote.pid" ]; then kill "$(cat "$HOME/.dsh/.dsh-remote.pid")" 2>/dev/null || true; rm -f "$HOME/.dsh/.dsh-remote.pid"; fi`,+ `pgrep -af '\\.dsh-desktop' | while IFS= read -r _pid _rest; do kill "$_pid" 2>/dev/null || true; done`,+ `sleep 1`,+ `pgrep -af '\\.dsh-desktop' || true`,+].join('\n')++const profile: MachineProfile = HOST === undefined+ ? {} as MachineProfile+ : {+ id: MachineId('e2e-dev'),+ name: 'dev-e2e',+ host: HOST,+ port: 22,+ user: '',+ remotePort: PORT,+ // The dev machine's home-level user patch pins the webserver row to+ // 3081 (held by its production instance behind caddy), which by design+ // overrides the CLI --port flag. The launch therefore goes through the+ // profile's startCommand override — the product's operator escape+ // hatch for exactly this — with a `--patch` overlay (applied after the+ // user layer, so it wins) restating the webserver row on our port.+ startCommand: `"$HOME/.dsh-desktop/runtime/bin/node" "$HOME/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js" --profile web --patch "$HOME/.dsh-e2e-port.yml" --host 127.0.0.1 --port ${PORT} --no-open`,+ }++/** The `--patch` overlay restating the webserver row on the E2E port. */+const PORT_PATCH_COMMAND = `cat > "$HOME/.dsh-e2e-port.yml" <<'EOF'+- id: webserver+ config:+ host: '127.0.0.1'+ port: ${PORT}+EOF+`++describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', () => {+ const roots: string[] = []+ let manager!: SshManager+ let events!: SshMachineEvents+ let transport!: SshTransport++ beforeAll(() => {+ const known = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-'))+ roots.push(known)+ events = new SshMachineEvents()+ transport = new Ssh2Transport(E2E_CONFIG.connectTimeoutMs, new SshConfigResolver(join(process.env.HOME ?? '', '.ssh'), process.env.HOME ?? ''))+ manager = new SshManager({+ transport,+ knownHosts: new KnownHostsStore(join(known, 'known-hosts.json')),+ config: E2E_CONFIG,+ events,+ emitStatus: () => {},+ })+ manager.refreshProfiles(new Map([[profile.id, profile]]))+ })++ afterAll(async () => {+ await manager.disconnect(profile.id).catch(() => undefined)+ await manager.dispose().catch(() => undefined)+ // Leave the installed tree for sibling nodes; stop only our processes.+ const session = await transport.connect(profile, () => true).catch(() => undefined)+ if (session !== undefined) {+ const leftovers = await session.exec(`${CLEANUP_COMMAND}\nrm -f "$HOME/.dsh-e2e-port.yml"`).catch(() => undefined)+ console.log('[e2e] remote cleanup done; remaining layout processes:', JSON.stringify(leftovers?.stdout.trim() ?? '(probe failed)'))+ await session.close().catch(() => undefined)+ }+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+ })++ it('bootstraps a fresh machine end to end (probe → download → verify → install → launch → ready)', async () => {+ // Fresh start: stop leftover shared-layout processes, wipe the tree, and+ // stage the port overlay the launch's --patch consumes.+ const cleaner = await transport.connect(profile, () => true)+ const wiped = await cleaner.exec(`${CLEANUP_COMMAND}\nrm -rf "$HOME/.dsh-desktop"\n${PORT_PATCH_COMMAND}\n[ -f "$HOME/.dsh-e2e-port.yml" ] && [ ! -e "$HOME/.dsh-desktop" ] && echo wiped`)+ await cleaner.close()+ expect(wiped.stdout).toContain('wiped')++ const startedAt = Date.now()+ let link: SshLink+ try {+ link = await manager.connect(profile.id)+ }+ catch (error) {+ // Surface everything the event channel captured before failing.+ console.log('[e2e] bootstrap FAILED; events:', JSON.stringify(events.since(profile.id), null, 2))+ throw error+ }+ const seconds = (Date.now() - startedAt) / 1000+ const page = events.since(profile.id)+ console.log(`[e2e] bootstrap to ready in ${seconds.toFixed(1)}s over ${page.events.length} events`)+ for (const event of page.events)+ console.log(`[e2e] #${event.seq} ${event.stage}${event.terminal === undefined ? '' : `(${event.terminal})`}: ${event.line.slice(0, 160)}`)++ expect(link.tunnelBaseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)+ const stages = page.events.map(event => event.stage)+ expect(stages).toContain('download')+ expect(stages).toContain('verify')+ expect(stages).toContain('install')+ expect(stages).toContain('launch')+ const ready = page.events.find(event => event.stage === 'ready')+ expect(ready?.terminal).toBe('success')+ // A fresh instance serves its auth fence on `/` (401, no boot page), so+ // readiness is judged by the legacy fallback — the designed behavior;+ // instances that serve the SPA manifest take the boot-HTML path instead.+ console.log(`[e2e] readiness judged by: ${ready?.line}`)+ expect(manager.status(profile.id).state).toBe('connected')+ }, 30 * 60_000)++ it('installs the shared default layout with working binaries', async () => {+ const session = await transport.connect(profile, () => true)+ const probe = await session.exec(+ `"$HOME/.dsh-desktop/runtime/bin/node" --version && ls "$HOME/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js" >/dev/null && echo entry-ok && ls "$HOME/.dsh-desktop/dependencies/pnpm/bin/pnpm.cjs" >/dev/null && echo pnpm-ok`,+ )+ await session.close()+ console.log('[e2e] layout probe:', JSON.stringify(probe.stdout.trim()), 'stderr:', JSON.stringify(probe.stderr.trim()))+ expect(probe.code).toBe(0)+ expect(probe.stdout).toMatch(/^v\d+\.\d+\.\d+/)+ expect(probe.stdout).toContain('entry-ok')+ expect(probe.stdout).toContain('pnpm-ok')+ })++ it('reconnects without reinstalling and returns to ready', async () => {+ await manager.disconnect(profile.id)+ const page0 = events.since(profile.id)+ const link = await manager.connect(profile.id)+ expect(link.tunnelBaseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)+ const page1 = events.since(profile.id)+ const fresh = page1.events.filter(event => event.seq > (page0.events.at(-1)?.seq ?? 0))+ for (const event of fresh)+ console.log(`[e2e] #${event.seq} ${event.stage}${event.terminal === undefined ? '' : `(${event.terminal})`}: ${event.line.slice(0, 160)}`)+ const stages = fresh.map(event => event.stage)+ // Already-initialized remote: no download/verify/install stages, and no+ // launch either when the detached instance survived the disconnect (the+ // still-running path judges readiness immediately).+ expect(stages).not.toContain('download')+ expect(stages).not.toContain('verify')+ expect(stages).not.toContain('install')+ const ready = fresh.find(event => event.stage === 'ready')+ expect(ready?.terminal).toBe('success')+ }, 10 * 60_000)+})diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.tsindex 95284974..b24b403b 100644--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts@@ -1,22 +1,28 @@import type { MachineProfile } from '../types/index.js'+import type { RemoteInstallPlan } from './bootstrap.js'import type { SshExecOptions, SshExecResult, SshSession } from './transport.js'-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { execFile } from 'node:child_process'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'+import { promisify } from 'node:util'import { join } from 'pathe'import { afterEach, describe, expect, it } from 'vitest'import { MachineId } from '../types/index.js'import {+ buildInstallScript,+ bundleProbeCommand,+ checkMissingCommand,credentialsCopyCommand,- defaultStartCommand,describeExecFailure,- DshMissingError,ensureRemoteInstance,firstLineOf,- healthCheckCommand,- installCommandFor,- OFFICIAL_INSTALL_REPO,- probeDshCommand,+ missingComponentsOf,+ parseBootstrapLine,+ planRemoteInstall,readEnvCredentials,+ REMOTE_ROOT,+ rootProbeCommand,+ splitBundleProbeStdout,startCommandFor,} from './bootstrap.js'@@ -29,8 +35,41 @@ const profile: MachineProfile = {remotePort: 3080,}-/** The dsh-path answer a remote probe would print. */-const RESOLVED_DSH = '/usr/local/bin/dsh'+/** A realistic newest-first release list matching the live pkg repository. */+const RELEASES = [+ { tag: 'dsh-0.2.0-preview.1-32490000001', prerelease: true },+ { tag: 'dsh-0.1.2-rc.1-33729514615', prerelease: false },+ { tag: 'dsh-0.1.1-rc.1-32342588166', prerelease: false },+]++const PKG_REPO = 'dsh-tauri-desk/deepseek-harness-pkg'++/** The GitHub assets the linux-x64 zip release carries. */+const LINUX_ASSETS = [+ {+ name: 'deepseek-harness-pkg-linux.zip',+ url: `https://github.com/${PKG_REPO}/releases/download/dsh-0.1.2-rc.1-33729514615/deepseek-harness-pkg-linux.zip`,+ digest: 'sha256:6b7ecfebe3b7d779b459262943b17777427860f1b96dbf3b6f16a5074b1119a7',+ },+]++/** The default injected fetchers (no network): a healthy metadata view. */+function healthyFetchers(overrides: Partial<{+ listReleases: () => Promise<typeof RELEASES>+ listAssets: () => Promise<typeof LINUX_ASSETS>+ npmDist: () => Promise<{ url: string, mirrorUrl: string, integrity?: string }>+}> = {}) {+ return {+ listReleases: () => Promise.resolve(RELEASES),+ listAssets: () => Promise.resolve(LINUX_ASSETS),+ npmDist: () => Promise.resolve({+ url: 'https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz',+ mirrorUrl: 'https://registry.npmmirror.com/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz',+ integrity: 'sha512-ZXhhZQ==',+ }),+ ...overrides,+ }+}class FakeSession implements SshSession {commands: string[] = []@@ -65,84 +104,271 @@ afterEach(() => {for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })})-describe('remote instance commands', () => {- it('builds the default start command from the profile port', () => {- expect(defaultStartCommand(profile)).toBe('dsh web --host 127.0.0.1 --port 3080')+describe('parseBootstrapLine', () => {+ it('splits stage-tagged markers and demotes untagged lines', () => {+ expect(parseBootstrapLine('::dsh download https://example.test/a')).toEqual({+ stage: 'download',+ line: 'https://example.test/a',+ })+ expect(parseBootstrapLine('::dsh failed checksum mismatch: x')).toEqual({+ stage: 'failed',+ line: 'checksum mismatch: x',+ })+ expect(parseBootstrapLine('random tool output')).toEqual({ stage: 'install', line: 'random tool output' })})+})- it('honors the profile startCommand override and ensures the log directory', () => {- const overridden: MachineProfile = { ...profile, startCommand: 'dsh web --port 4000' }- expect(startCommandFor(overridden))- .toBe('mkdir -p "$HOME/.dsh" && ( dsh web --port 4000 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+describe('planRemoteInstall', () => {+ it('pins the recommended release for linux x64 with its trusted digest', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())+ expect(plan.os).toBe('linux')+ expect(plan.arch).toBe('x64')+ expect(plan.dsh.kind).toBe('pkg-zip')+ if (plan.dsh.kind !== 'pkg-zip')+ throw new Error('expected pkg-zip')+ expect(plan.dsh.tag).toBe('dsh-0.1.2-rc.1-33729514615')+ expect(plan.dsh.digest).toBe(LINUX_ASSETS[0]?.digest)+ expect(plan.dsh.urls[0]).toBe(LINUX_ASSETS[0]?.url)+ expect(plan.dsh.urls[1]).toContain('ghfast.top/')+ expect(plan.dshEntry).toBe('node_modules/@deepseek-ai/dsh/lib/bin.js')+ expect(plan.dshVersion).toBe('0.1.2-rc.1')+ expect(plan.notes).toEqual([])})- it('builds the detached default start with log redirection', () => {- expect(startCommandFor(profile))- .toBe('mkdir -p "$HOME/.dsh" && ( dsh web --host 127.0.0.1 --port 3080 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+ it('resolves the arm64 npm asset with its packument integrity', async () => {+ const plan = await planRemoteInstall('Linux 5.15 aarch64', {}, healthyFetchers())+ expect(plan.dsh.kind).toBe('npm-tgz')+ if (plan.dsh.kind === 'npm-tgz') {+ expect(plan.dsh.urls).toEqual([+ 'https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz',+ 'https://registry.npmmirror.com/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz',+ ])+ expect(plan.dsh.integrity).toBe('sha512-ZXhhZQ==')+ }+ expect(plan.dshEntry).toBe('lib/bin.js')+ expect(plan.node.urls[0]).toBe('https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-arm64.tar.gz')})- it('substitutes a resolved dsh path into the default start command', () => {- expect(startCommandFor(profile, RESOLVED_DSH))- .toBe('mkdir -p "$HOME/.dsh" && ( /usr/local/bin/dsh web --host 127.0.0.1 --port 3080 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+ it('derives deterministic URLs and notes skipped verification when metadata fails', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers({+ listAssets: () => Promise.reject(new Error('rate limited')),+ }))+ expect(plan.dsh.kind).toBe('pkg-zip')+ expect(plan.notes.join('\n')).toContain('资产元数据获取失败')+ expect(plan.notes.join('\n')).toContain('跳过 SHA-256 校验')+ if (plan.dsh.kind === 'pkg-zip')+ expect(plan.dsh.urls[0]).toBe(LINUX_ASSETS[0]?.url)})- it('keeps the profile override untouched when a dsh path is known', () => {- const overridden: MachineProfile = { ...profile, startCommand: 'my-launcher web' }- expect(startCommandFor(overridden, RESOLVED_DSH)).toContain('my-launcher web')+ it('derives deterministic npm URLs when the registry view fails', async () => {+ const plan = await planRemoteInstall('Linux 5.15 aarch64', {}, healthyFetchers({+ npmDist: () => Promise.reject(new Error('offline')),+ }))+ expect(plan.dsh.kind).toBe('npm-tgz')+ if (plan.dsh.kind === 'npm-tgz')+ expect(plan.dsh.urls[0]).toBe('https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz')+ expect(plan.notes.join('\n')).toContain('未取得')})- it('builds a curl health probe with a bounded deadline', () => {- expect(healthCheckCommand(3080, 2500)).toBe('curl -s -o /dev/null -m 3 -w \'%{http_code}\' http://127.0.0.1:3080/')- expect(healthCheckCommand(4000, 100)).toBe('curl -s -o /dev/null -m 1 -w \'%{http_code}\' http://127.0.0.1:4000/')+ it('falls back to the known stable tag when the release listing fails', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers({+ listReleases: () => Promise.reject(new Error('offline')),+ }))+ if (plan.dsh.kind !== 'pkg-zip')+ throw new Error('expected pkg-zip')+ expect(plan.dsh.tag).toBe('dsh-0.1.2-rc.1-33729514615')+ expect(plan.notes.join('\n')).toContain('release 列表获取失败')})- it('summarizes a failed command for operators', () => {- expect(describeExecFailure(1, 'bash: dsh: command not found\n')).toBe('exit 1: bash: dsh: command not found')- expect(describeExecFailure(null, ' ')).toBe('exit ?')+ it('honors a configured pin and a custom release repository', async () => {+ const repos: string[] = []+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {+ installRepo: 'https://github.com/my-org/deepseek-harness-pkg.git',+ installRef: '0.1.1-rc.1',+ }, {+ listReleases: (repo) => {+ repos.push(repo)+ return Promise.resolve(RELEASES)+ },+ listAssets: () => Promise.resolve(LINUX_ASSETS),+ npmDist: () => Promise.reject(new Error('unused')),+ })+ expect(repos).toEqual(['my-org/deepseek-harness-pkg'])+ if (plan.dsh.kind !== 'pkg-zip')+ throw new Error('expected pkg-zip')+ expect(plan.dsh.tag).toBe('dsh-0.1.1-rc.1-32342588166')+ })++ it('rejects platforms outside the matrix before any network use', async () => {+ const fetchers = {+ listReleases: (): Promise<typeof RELEASES> => {+ throw new Error('must not be called')+ },+ listAssets: (): Promise<typeof LINUX_ASSETS> => {+ throw new Error('must not be called')+ },+ npmDist: (): Promise<never> => {+ throw new Error('must not be called')+ },+ }+ await expect(planRemoteInstall('MINGW64_NT-10.0-19045 x86_64', {}, fetchers)).rejects.toThrow(/REMOTE_PLATFORM_UNSUPPORTED/)})})-describe('dsh probe', () => {- it('checks PATH, then the installer links, and never fails', () => {- const command = probeDshCommand()- expect(command).toContain('command -v dsh')- expect(command).toContain('"$HOME/.local/bin/dsh"')- expect(command).toContain('"$HOME/.dsh/source/current/bin/dsh"')- expect(command).toContain('true')- // Each fallback is a braced group: a successful earlier arm must- // short-circuit the chain instead of firing the later && printf arms too.- expect(command).toMatch(/\{ test -x "\$HOME\/\.local\/bin\/dsh" && printf/)+describe('buildInstallScript', () => {+ it('embeds the plan: URLs, digests, entries, and the cleanup trap', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers())+ const script = buildInstallScript(plan)+ expect(script).toContain('https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.gz')+ expect(script).toContain('https://npmmirror.com/mirrors/node/v22.22.0/node-v22.22.0-linux-x64.tar.gz')+ expect(script).toContain('https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz')+ expect(script).toContain(LINUX_ASSETS[0]?.url ?? '')+ expect(script).toContain('sha256:6b7ecfebe3b7d779b459262943b17777427860f1b96dbf3b6f16a5074b1119a7')+ expect(script).toContain('trap cleanup EXIT')+ expect(script).toContain('checksum mismatch')+ expect(script).toContain('unzip -q -o')+ expect(script).not.toContain('pnpm install')})- it('takes the first non-empty line of a probe result', () => {- expect(firstLineOf('/usr/local/bin/dsh\n/other/bin/dsh\n')).toBe('/usr/local/bin/dsh')- expect(firstLineOf('\n \n/usr/local/bin/dsh')).toBe('/usr/local/bin/dsh')- expect(firstLineOf(' ')).toBe('')- expect(firstLineOf('')).toBe('')+ it('arm64: assembles node_modules on the remote with registry fallback', async () => {+ const plan = await planRemoteInstall('Linux 5.15 aarch64', {}, healthyFetchers())+ const script = buildInstallScript(plan)+ expect(script).toContain('https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz')+ expect(script).toContain('sha512-ZXhhZQ==')+ expect(script).toContain('install --prod --silent --registry')+ expect(script).toContain('"$ROOT/dependencies/pnpm/bin/pnpm.cjs"')+ expect(script).toContain('https://registry.npmmirror.com')+ // The tarball path extracts with tar; the zip helper stays uncalled.+ expect(script).not.toContain('extract_zip "$TMP/dsh')+ })+})++describe('install script execution (real POSIX sh)', () => {+ /**+ * Run one generated script under the real `sh` inside a sandboxed HOME,+ * with a fake `curl` first on PATH that "downloads" tampered bytes and a+ * SHASUMS256.txt pinning a digest those bytes cannot match.+ */+ function runScript(script: string, sandbox: string): Promise<{ code: number, stdout: string, stderr: string }> {+ const binDir = join(sandbox, 'fake-bin')+ mkdirSync(binDir, { recursive: true })+ const fakeCurl = join(binDir, 'curl')+ writeFileSync(fakeCurl, [+ '#!/bin/sh',+ 'dst=""',+ 'prev=""',+ 'for arg in "$@"; do',+ ' if [ "$prev" = "-o" ]; then dst="$arg"; fi',+ ' prev="$arg"',+ 'done',+ 'url=""',+ 'for arg in "$@"; do url="$arg"; done',+ 'case "$url" in',+ ' *SHASUMS256.txt)',+ ' printf \'%s %s\\n\' deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef node-v22.22.0-linux-x64.tar.gz > "$dst"',+ ' ;;',+ ' *)',+ ' printf \'tampered-download-bytes\' > "$dst"',+ ' ;;',+ 'esac',+ 'exit 0',+ ].join('\n'))+ chmodSync(fakeCurl, 0o755)+ const scriptPath = join(sandbox, 'install.sh')+ writeFileSync(scriptPath, script)+ const run = promisify(execFile)+ return run('sh', [scriptPath], {+ env: { ...process.env, HOME: sandbox, PATH: `${binDir}:${process.env.PATH ?? ''}` },+ }).then(+ ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),+ (error: { code?: number, stdout?: string, stderr?: string }) =>+ ({ code: error.code ?? -1, stdout: error.stdout ?? '', stderr: error.stderr ?? '' }),+ )+ }++ it('aborts and cleans half-products when the SHA-256 mismatches (tampered asset)', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers({+ listAssets: () => Promise.resolve(LINUX_ASSETS),+ }))+ const sandbox = tempDir()+ const outcome = await runScript(buildInstallScript(plan), sandbox)+ // The node tarball's digest cannot match the tampered download: the run+ // must abort before installing anything and the trap must clean up.+ expect(outcome.code).toBe(11)+ expect(outcome.stdout).toContain('::dsh failed checksum mismatch')+ expect(existsSync(join(sandbox, REMOTE_ROOT, 'runtime'))).toBe(false)+ expect(existsSync(join(sandbox, REMOTE_ROOT, 'tmp'))).toBe(false)+ expect(existsSync(join(sandbox, REMOTE_ROOT, 'runtime.new'))).toBe(false)+ expect(existsSync(join(sandbox, REMOTE_ROOT, 'dependencies', 'dsh'))).toBe(false)+ })++ it('skips every section when the three components are already installed', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers())+ const sandbox = tempDir()+ const root = join(sandbox, REMOTE_ROOT)+ mkdirSync(join(root, 'runtime', 'bin'), { recursive: true })+ writeFileSync(join(root, 'runtime', 'bin', 'node'), 'placeholder')+ chmodSync(join(root, 'runtime', 'bin', 'node'), 0o755)+ mkdirSync(join(root, 'dependencies', 'pnpm', 'bin'), { recursive: true })+ writeFileSync(join(root, 'dependencies', 'pnpm', 'bin', 'pnpm.cjs'), 'placeholder')+ mkdirSync(join(root, 'dependencies', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'lib'), { recursive: true })+ writeFileSync(join(root, 'dependencies', 'dsh', 'node_modules', '@deepseek-ai', 'dsh', 'lib', 'bin.js'), 'placeholder')+ const outcome = await runScript(buildInstallScript(plan), sandbox)+ expect(outcome.code).toBe(0)+ expect(outcome.stdout).toContain('node 已就绪')+ expect(outcome.stdout).toContain('pnpm 已就绪')+ expect(outcome.stdout).toContain('dsh 已就绪')+ expect(outcome.stdout).toContain('远端初始化完成')+ expect(outcome.stdout).not.toContain('::dsh download')+ expect(existsSync(join(root, 'tmp'))).toBe(false)})})-describe('install commands', () => {- it('builds the built-in install from the official repo default', () => {- const command = installCommandFor({})- expect(command).toContain(`git clone --depth 1 '${OFFICIAL_INSTALL_REPO}' "$HOME/.dsh/source/master"`)- expect(command).toContain('corepack enable pnpm')- expect(command).toContain('npm install -g pnpm')- expect(command).toContain('pnpm install')- expect(command).toContain('pnpm run build')- expect(command).toContain('ln -sfn "$HOME/.dsh/source/current/bin/dsh" "$HOME/.local/bin/dsh"')- expect(command).toContain('rm -rf "$HOME/.dsh/source/master" "$HOME/.dsh/source/current"')- expect(command).toContain('set -e')+describe('component probe and launch commands', () => {+ it('lists the missing components of the remote layout', () => {+ const command = checkMissingCommand()+ expect(command).toContain('.dsh-desktop')+ expect(command).toContain('"$ROOT/runtime/bin/node"')+ expect(command).toContain('"$ROOT/dependencies/pnpm/bin/pnpm.cjs"')+ expect(command).toContain('"$ROOT/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"')+ expect(missingComponentsOf('node\ndsh\n')).toEqual(['node', 'dsh'])+ expect(missingComponentsOf('')).toEqual([])+ expect(missingComponentsOf('node\njunk\npnpm\n')).toEqual(['node', 'pnpm'])})- it('clones a configured repo with an optional ref', () => {- const command = installCommandFor({ installRepo: 'https://git.example.com/team/dsh.git' })- expect(command).toContain(`git clone --depth 1 'https://git.example.com/team/dsh.git' "$HOME/.dsh/source/master"`)- const withRef = installCommandFor({- installRepo: '[email protected]:me/dsh.git',- installRef: 'snapshots/2026',- })- expect(withRef).toContain(`git clone --depth 1 --branch 'snapshots/2026' '[email protected]:me/dsh.git' "$HOME/.dsh/source/master"`)+ it('builds the layout launch: pinned port, pid file, detached, log redirect', async () => {+ const plan = await planRemoteInstall('Linux 6.8 x86_64', {}, healthyFetchers())+ const command = startCommandFor(profile, plan)+ expect(command).toContain('.dsh-desktop/runtime/bin/node')+ expect(command).toContain('.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js')+ expect(command).toContain('.dsh-remote.pid')+ expect(command).toContain('--host 127.0.0.1')+ expect(command).toContain(`--port "$4"`)+ expect(command).toContain('DSH_WEB_PORT=3080')+ expect(command).toContain('--no-open')+ expect(command).toContain('REMOTE_NOT_INSTALLED')+ expect(command).toContain('dsh-remote-web.log')+ })++ it('keeps the profile startCommand override untouched', () => {+ const overridden: MachineProfile = { ...profile, startCommand: 'my-launcher web --port 4000' }+ expect(startCommandFor(overridden))+ .toBe('mkdir -p "$HOME/.dsh" && ( my-launcher web --port 4000 >>"$HOME/.dsh/dsh-remote-web.log" 2>&1 < /dev/null & ) &')+ })+})++describe('health probes', () => {+ it('builds the root probe and the bundle probe', () => {+ expect(rootProbeCommand(3080, 2500)).toBe('curl -s -m 3 http://127.0.0.1:3080/')+ expect(bundleProbeCommand('http://127.0.0.1:3080/plugins/x/client.js', 2500))+ .toBe('curl -s -m 3 -w \'\\n%{http_code}\' \'http://127.0.0.1:3080/plugins/x/client.js\'')+ })++ it('splits a bundle probe answer into body and status', () => {+ expect(splitBundleProbeStdout('console.log(1)\n200')).toEqual({ body: 'console.log(1)', status: 200 })+ expect(splitBundleProbeStdout('404\n')).toEqual({ body: '', status: 404 })+ expect(splitBundleProbeStdout('<!doctype html>\n200')).toEqual({ body: '<!doctype html>', status: 200 })+ expect(splitBundleProbeStdout('garbage')).toEqual({ body: 'garbage', status: 0 })})})@@ -179,114 +405,204 @@ describe('credentials', () => {})})+/** A boot page the bundle probe answers with real JavaScript. */+const BOOT_HTML = [+ '<html><head>',+ '<script src="/plugins/??@deepseek-ai/dsh-client-modules/client.js&rev=1"></script>',+ '</head><body><script>globalThis["__DSH_BOOT__"] = {"entries":[{"url":"/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"}]};</script></body></html>',+].join('')++const BOOTSTRAP = {+ config: {},+ healthCheckTimeoutMs: 1000,+ healthPollIntervalMs: 5,+ healthPollAttempts: 3,+}++function plannerOf(plan: RemoteInstallPlan) {+ return async (): Promise<RemoteInstallPlan> => plan+}+describe('ensureRemoteInstance', () => {- it('skips start when the instance already answers', async () => {- const session = new FakeSession(() => ({ code: 0, stdout: '200', stderr: '' }))- await expect(ensureRemoteInstance(session, profile, 1000, 10, 3)).resolves.toBe('10.0.0.1:3080')- expect(session.commands).toHaveLength(1)- expect(session.commands[0]).toContain('curl')+ it('is satisfied immediately when the boot manifest answers with a real bundle', async () => {+ const session = new FakeSession((command) => {+ if (command.includes('-w'))+ return { code: 0, stdout: 'console.log(1)\n200', stderr: '' }+ return { code: 0, stdout: BOOT_HTML, stderr: '' }+ })+ const events: Array<{ stage: string, line: string, terminal?: string }> = []+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {+ onEvent: (stage, line, options) => events.push({ stage, line, ...options?.terminal === undefined ? {} : { terminal: options.terminal } }),+ })).resolves.toBe('10.0.0.1:3080')+ expect(session.commands).toHaveLength(2)+ expect(events).toEqual([{ stage: 'ready', line: expect.stringContaining('已就绪'), terminal: 'success' }])})- it('auto-starts when absent and reports the healthy address after polling', async () => {- const session = new FakeSession((_command, index) => {- // 1 = port probe (refused), 2 = dsh probe, 3 = start, 4 = post-start probe (healthy).- if (index === 1)- return { code: 0, stdout: RESOLVED_DSH, stderr: '' }- if (index === 2)- return { code: 0, stdout: '', stderr: '' }- if (index === 3)+ it('falls back to the legacy any-response verdict when the HTML carries no manifest', async () => {+ const session = new FakeSession((command) => {+ if (command.includes('/dev/null'))return { code: 0, stdout: '200', stderr: '' }- return { code: 7, stdout: '', stderr: 'refused' }+ return { code: 0, stdout: '<html>an old instance without a boot graph</html>', stderr: '' }})- await expect(ensureRemoteInstance(session, profile, 1000, 5, 3)).resolves.toBe('10.0.0.1:3080')- expect(session.commands[2]).toContain(`${RESOLVED_DSH} web --host 127.0.0.1 --port 3080`)+ const events: string[] = []+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {+ onEvent: (stage, line) => events.push(`${stage}: ${line}`),+ })).resolves.toBe('10.0.0.1:3080')+ expect(events[0]).toContain('旧探测兜底')+ expect(events[0]).toContain('root answered 200')})- it('reports the bootstrap phases through the progress callback', async () => {- const session = new FakeSession((_command, index) => {- // 1 = port probe (refused), 2 = dsh probe, 3 = start, 4 = post-start probe (healthy).- if (index === 1)- return { code: 0, stdout: RESOLVED_DSH, stderr: '' }- if (index === 2)- return { code: 0, stdout: '', stderr: '' }- if (index === 3)- return { code: 0, stdout: '200', stderr: '' }- return { code: 7, stdout: '', stderr: 'refused' }+ it('bootstraps a fresh machine end to end: probe → install → launch → ready', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())+ let started = false+ const session = new FakeSession((command) => {+ if (command === 'uname -srm')+ return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }+ if (command.includes('echo node'))+ return { code: 0, stdout: 'node\ndsh\npnpm\n', stderr: '' }+ if (command.includes('trap cleanup EXIT'))+ return { code: 0, stdout: '::dsh install 远端初始化完成', stderr: '' }+ if (command.includes('dsh-remote.pid')) {+ started = true+ return { code: 0, stdout: '远端实例已拉起', stderr: '' }+ }+ // Readiness probes: refused until the launch, manifest-healthy after.+ if (command.includes('-w'))+ return { code: 0, stdout: 'console.log(1)\n200', stderr: '' }+ return started+ ? { code: 0, stdout: BOOT_HTML, stderr: '' }+ : { code: 7, stdout: '', stderr: 'refused' }})+ const events: Array<{ stage: string, line: string, terminal?: string, reason?: string }> = []const phases: unknown[] = []- await ensureRemoteInstance(session, profile, 1000, 5, 3, progress => phases.push(progress))- expect(phases).toEqual([- { phase: 'starting' },- { phase: 'probing', attempt: 1, total: 3 },- ])+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {+ onProgress: progress => phases.push(progress),+ onEvent: (stage, line, options) => events.push({ stage, line, ...options ?? {} }),+ }, plannerOf(plan))).resolves.toBe('10.0.0.1:3080')+ const kinds = events.map(event => event.stage)+ expect(kinds).toEqual(['probe', 'probe', 'probe', 'launch', 'ready'])+ expect(events[0]?.line).toContain('探测远端平台')+ expect(events[1]?.line).toContain('linux/x64')+ expect(events[2]?.line).toContain('缺失组件: node, dsh, pnpm')+ expect(events[4]?.terminal).toBe('success')+ expect(phases).toEqual([{ phase: 'starting' }, { phase: 'probing', attempt: 1, total: 3 }])+ expect(session.commands.some(command => command.includes('https://nodejs.org/dist/'))).toBe(true)})- it('fails fast with DshMissingError when no dsh binary is reachable', async () => {+ it('skips the install when the three components are already present', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())+ let started = falseconst session = new FakeSession((command) => {- if (command.includes('curl'))- return { code: 7, stdout: '', stderr: '' }- return { code: 0, stdout: '', stderr: '' }+ if (command === 'uname -srm')+ return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }+ if (command.includes('echo node'))+ return { code: 0, stdout: '', stderr: '' }+ if (command.includes('dsh-remote.pid')) {+ started = true+ return { code: 0, stdout: '远端实例已拉起', stderr: '' }+ }+ if (command.includes('-w'))+ return { code: 0, stdout: 'console.log(1)\n200', stderr: '' }+ return started+ ? { code: 0, stdout: BOOT_HTML, stderr: '' }+ : { code: 7, stdout: '', stderr: '' }})- await expect(ensureRemoteInstance(session, profile, 1000, 5, 3)).rejects.toBeInstanceOf(DshMissingError)+ const events: string[] = []+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {+ onEvent: (stage, line) => events.push(`${stage}: ${line}`),+ }, plannerOf(plan))).resolves.toBe('10.0.0.1:3080')+ expect(events.some(entry => entry.includes('三件套已就绪,跳过安装'))).toBe(true)+ expect(session.commands.some(command => command.includes('trap cleanup EXIT'))).toBe(false)})- it('fails loud when the start command itself fails', async () => {- const session = new FakeSession((_command, index) => {- if (index === 1)- return { code: 0, stdout: RESOLVED_DSH, stderr: '' }- if (index === 2)- return { code: 127, stdout: '', stderr: 'sh: dsh: not found' }+ it('records the terminal failure and reason when the install script fails', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())+ const session = new FakeSession((command) => {+ if (command === 'uname -srm')+ return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }+ if (command.includes('echo node'))+ return { code: 0, stdout: 'node\n', stderr: '' }+ if (command.includes('trap cleanup EXIT'))+ return { code: 11, stdout: '::dsh failed checksum mismatch: node.tar.gz', stderr: '' }return { code: 7, stdout: '', stderr: '' }})- await expect(ensureRemoteInstance(session, profile, 1000, 5, 3)).rejects.toThrow(/start failed.*not found/)+ const failures: Array<{ line: string, terminal?: string, reason?: string }> = []+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {+ onEvent: (stage, line, options) => {+ if (stage === 'failed')+ failures.push({ line, ...options ?? {} })+ },+ }, plannerOf(plan))).rejects.toThrow(/install failed on remote/)+ expect(failures[0]?.terminal).toBe('failed')+ expect(failures[0]?.reason).toContain('checksum mismatch')})- it('fails loud when the instance never becomes reachable, with the log tail', async () => {+ it('reports unsupported platforms as a terminal failure', async () => {const session = new FakeSession((command) => {- if (command.includes('command -v dsh'))- return { code: 0, stdout: RESOLVED_DSH, stderr: '' }- if (command.includes('tail'))- return { code: 0, stdout: 'dsh: command not found\nline2\nline3\nline4\nline5\nline6', stderr: '' }- if (command.includes('curl'))- return { code: 7, stdout: '', stderr: '' }- return { code: 0, stdout: '', stderr: '' }+ if (command === 'uname -srm')+ return { code: 0, stdout: 'MINGW64_NT-10.0-19045 x86_64\n', stderr: '' }+ return { code: 7, stdout: '', stderr: '' }})- await expect(ensureRemoteInstance(session, profile, 1000, 5, 2)).rejects.toThrow(- /did not become reachable.*line2 \| line3 \| line4 \| line5 \| line6/,- )- expect(session.commands).toHaveLength(6)+ const failures: string[] = []+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {+ onEvent: (stage, line) => {+ if (stage === 'failed')+ failures.push(line)+ },+ })).rejects.toThrow(/REMOTE_PLATFORM_UNSUPPORTED/)+ expect(failures).toHaveLength(1)})- it('notes an empty remote log in the failure message', async () => {+ it('fails loud with fallback details when the instance never becomes ready', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())const session = new FakeSession((command) => {- if (command.includes('command -v dsh'))- return { code: 0, stdout: RESOLVED_DSH, stderr: '' }- if (command.includes('tail'))+ if (command === 'uname -srm')+ return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }+ if (command.includes('echo node'))return { code: 0, stdout: '', stderr: '' }- if (command.includes('curl'))- return { code: 7, stdout: '', stderr: '' }- return { code: 0, stdout: '', stderr: '' }+ if (command.includes('tail'))+ return { code: 0, stdout: 'err1\nerr2\nerr3\nerr4\nerr5\nerr6', stderr: '' }+ if (command.includes('dsh-remote.pid'))+ return { code: 0, stdout: '远端实例已拉起', stderr: '' }+ return { code: 7, stdout: '', stderr: '' }})- await expect(ensureRemoteInstance(session, profile, 1000, 5, 1)).rejects.toThrow(/log is empty/)+ const failures: Array<{ reason?: string, terminal?: string }> = []+ await expect(ensureRemoteInstance(session, profile, {+ ...BOOTSTRAP,+ healthPollAttempts: 2,+ }, {+ onEvent: (_stage, _line, options) => {+ if (options?.terminal === 'failed')+ failures.push({ terminal: options.terminal, ...options.reason === undefined ? {} : { reason: options.reason } })+ },+ }, plannerOf(plan))).rejects.toThrow(/did not become ready.*fallback probe: root no answer.*err2 \| err3 \| err4 \| err5 \| err6/)+ expect(failures[0]?.terminal).toBe('failed')})- it('notes an unreadable remote log in the failure message', async () => {+ it('surfaces REMOTE_NOT_INSTALLED when the launch finds an incomplete runtime', async () => {+ const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())const session = new FakeSession((command) => {- if (command.includes('command -v dsh'))- return { code: 0, stdout: RESOLVED_DSH, stderr: '' }- if (command.includes('tail'))- throw new Error('channel closed')- if (command.includes('curl'))- return { code: 7, stdout: '', stderr: '' }- return { code: 0, stdout: '', stderr: '' }+ if (command === 'uname -srm')+ return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }+ if (command.includes('echo node'))+ return { code: 0, stdout: '', stderr: '' }+ if (command.includes('dsh-remote.pid'))+ return { code: 1, stdout: 'REMOTE_NOT_INSTALLED: 远端三件套未安装完整', stderr: '' }+ return { code: 7, stdout: '', stderr: '' }})- await expect(ensureRemoteInstance(session, profile, 1000, 5, 1)).rejects.toThrow(/log unreadable/)+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {}, plannerOf(plan)))+ .rejects+ .toThrow(/REMOTE_NOT_INSTALLED/)})- it('propagates transport failures', async () => {- const session = new FakeSession(() => {- throw new Error('channel closed')- })- await expect(ensureRemoteInstance(session, profile, 1000, 5, 2)).rejects.toThrow()+ it('summarizes a failed command for operators', () => {+ expect(describeExecFailure(1, 'sh: dsh: not found\n')).toBe('exit 1: sh: dsh: not found')+ expect(describeExecFailure(null, ' ')).toBe('exit ?')+ })++ it('takes the first non-empty line of a probe result', () => {+ expect(firstLineOf('ok\nother\n')).toBe('ok')+ expect(firstLineOf('\n \nok')).toBe('ok')+ expect(firstLineOf('')).toBe('')})})diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.tsindex c3d566bf..ae122afc 100644--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts@@ -1,117 +1,437 @@/**- * Remote-instance assurance: probe the remote `dsh web` port, auto-start the- * instance when absent, and poll until it answers. Commands are pure- * functions of the profile so the manager can drive them through any- * transport; the polling loop owns the timing contract and reports its phase- * through a progress callback so the settings page can show live progress.- * Also the one-line dsh installer: probe for a `dsh` binary, run the official- * install script through the remote shell, and copy the local API credentials.+ * Remote-instance assurance, v2: binary distribution. Connect-time flow =+ * probe the remote platform (`uname -srm`), download/verify/install the+ * three-part runtime (Node + DSH + pnpm) under the remote-exclusive+ * `~/.dsh-desktop` layout when components are missing, launch the instance,+ * and judge readiness by parsing the served boot HTML's `__DSH_BOOT__`+ * client manifest (the legacy any-response port probe stays as fallback).+ * Ported from the retired Rust engine's `service/remote/bootstrap.rs`+ * (official → mirror download fallback, SHA verification, single-top-level+ * flattening, detached launch) with the stage-tagged event stream this spec+ * adds. Commands remain pure functions of the profile/plan so the manager+ * drives them through any transport.* @module dsh-tauri-ssh/host/service/bootstrap*/import type { Config } from '../storage/index.js'import type { MachineProfile, SshProgress } from '../types/index.js'+import type { RemoteArch, RemoteAssetMatrix, RemoteOs } from './assets.js'import type { SshSession } from './transport.js'import { readFileSync } from 'node:fs'+import { assetMatrixFor, dshNpmTarballUrls, dshZipDownloadUrls, nodeDownloadUrls, nodeFilenameFor, nodeShasumUrls, parsePlatform, PNPM_SHA256, PNPM_VERSION, pnpmDownloadUrls } from './assets.js'+import { clientUrlsFromBootHtml, looksLikePluginBundle } from './boot-html.js'import { shQuote } from './transport.js'+import { listGithubAssets, listGithubReleases, npmDistMetadata, pickReleaseTag, pkgRepoOf } from './version.js'/** Log file of the auto-started remote instance, under the remote home. */export const REMOTE_WEB_LOG = '.dsh/dsh-remote-web.log'-/** The installer's default clone source (its DSH_REPO default). */-export const OFFICIAL_INSTALL_REPO = 'https://github.com/deepseek-harness/deepseek-harness.git'+/** The remote-exclusive install root, relative to the remote home. */+export const REMOTE_ROOT = '.dsh-desktop'-/** The default remote-instance start command, parameterized by the profile's remote port. */-export function defaultStartCommand(profile: MachineProfile): string {- return `dsh web --host 127.0.0.1 --port ${profile.remotePort}`+/** The packaged-zip DSH entry, relative to the dsh install directory. */+const DSH_ZIP_ENTRY = 'node_modules/@deepseek-ai/dsh/lib/bin.js'++/** The npm-tarball DSH entry, relative to the dsh install directory. */+const DSH_NPM_ENTRY = 'lib/bin.js'++/** The pnpm entry, relative to the pnpm install directory. */+const PNPM_ENTRY = 'bin/pnpm.cjs'++/** Marker prefix the install script tags its stage lines with. */+export const BOOTSTRAP_LOG_PREFIX = '::dsh '++/** One parsed stage line of the install script's output stream. */+export interface BootstrapLogLine {+ stage: string+ line: string}/**- * The remote-instance start command: the profile override when present, else- * the default with the resolved `dsh` binary substituted for the bare name- * (the installer's `~/.local/bin` is rarely on a login shell's PATH). The- * log directory is ensured first (a missing `$HOME/.dsh` would otherwise- * swallow the redirection and every error with it), then the command runs- * detached in the background with output redirected to the log; the health- * probe judges the outcome, never the command. Deliberately no `nohup`: in an- * sshd exec session there is no controlling terminal to detach from, and- * macOS nohup then kills the child instead of protecting it — a plain- * backgrounded job survives both the exec channel and connection close (no- * pty was ever allocated).- * @param profile - the machine profile.- * @param dshPath - resolved remote `dsh` binary path, when known.- * @returns the shell command line that starts (or restarts) the instance.+ * Parse one output line of the install script into its stage tag; lines+ * without the marker are unexpected tool output and report stage `install`.+ * @param chunk - one raw output line.+ */+export function parseBootstrapLine(chunk: string): BootstrapLogLine {+ const match = /^::dsh (\w+) (.*)$/u.exec(chunk)+ if (match === null)+ return { stage: 'install', line: chunk }+ return { stage: match[1] ?? 'install', line: match[2] ?? '' }+}++/** The npm-registry DSH kind's resolved asset. */+interface DshNpmPlan {+ kind: 'npm-tgz'+ urls: string[]+ /** Trusted `sha512-…` integrity from the packument, when available. */+ integrity?: string+ packageName: string+ version: string+}++/** The packaged-zip DSH kind's resolved asset. */+interface DshZipPlan {+ kind: 'pkg-zip'+ urls: string[]+ /** Trusted `sha256:<hex>` digest from the GitHub release, when available. */+ digest?: string+ zipName: string+ tag: string+}++/** The fully resolved install plan for one remote. */+export interface RemoteInstallPlan {+ os: RemoteOs+ arch: RemoteArch+ matrix: RemoteAssetMatrix+ /** The GitHub `owner/name` the DSH asset downloads from. */+ repo: string+ /** The DSH entry path relative to `$HOME/.dsh-desktop/dependencies/dsh`. */+ dshEntry: string+ /** The resolved DSH semver (empty when the tag carries none). */+ dshVersion: string+ node: { urls: string[], shasumUrls: string[], filename: string, version: string }+ dsh: DshNpmPlan | DshZipPlan+ pnpm: { urls: string[], sha256: string, version: string }+ /** Resolution notes (fallbacks, skipped verification) worth surfacing. */+ notes: string[]+}++/**+ * Plan one remote's install: platform → asset matrix → pinned release tag →+ * per-asset URLs and trusted digests. Pure orchestration over the injectable+ * network functions, so tests cover every path without touching the network.+ * @param unameOut - the remote `uname -srm` output.+ * @param config - plugin config (source repository and version pin).+ * @param fetchers - network overrides for tests.+ * @param fetchers.listReleases - the packaged release list (newest first).+ * @param fetchers.listAssets - one tag's release assets.+ * @param fetchers.npmDist - the npm packument dist metadata.+ * @throws {UnsupportedRemotePlatformError} when the platform is outside the matrix.+ */+export async function planRemoteInstall(+ unameOut: string,+ config: Pick<Config, 'installRepo' | 'installRef'>,+ fetchers: {+ listReleases?: (repo: string) => Promise<{ tag: string, prerelease: boolean }[]>+ listAssets?: (repo: string, tag: string) => Promise<Array<{ name: string, url: string, digest?: string }>>+ npmDist?: (packageName: string, version: string) => Promise<{ url: string, mirrorUrl: string, integrity?: string }>+ } = {},+): Promise<RemoteInstallPlan> {+ const { os, arch } = parsePlatform(unameOut)+ const matrix = assetMatrixFor(os, arch)+ const repo = pkgRepoOf(config.installRepo)+ const notes: string[] = []+ const listReleases = fetchers.listReleases ?? listGithubReleases+ const listAssets = fetchers.listAssets ?? listGithubAssets+ const npmDist = fetchers.npmDist ?? npmDistMetadata+ let metas+ try {+ metas = await listReleases(repo)+ }+ catch (error) {+ notes.push(`release 列表获取失败(${describeError(error)})`)+ }+ const resolved = pickReleaseTag(metas, { ref: config.installRef })+ notes.push(...resolved.notes.map(note => `版本选择: ${note}`))+ const nodeFilename = nodeFilenameFor(os, arch)+ if (nodeFilename === undefined)+ throw new Error(`node asset missing for ${os}/${arch}`)+ const node = {+ urls: nodeDownloadUrls(os, arch),+ shasumUrls: nodeShasumUrls(),+ filename: nodeFilename,+ version: nodeFilename.split('-')[1] ?? '',+ }+ const pnpm = { urls: pnpmDownloadUrls(), sha256: PNPM_SHA256, version: PNPM_VERSION }+ if (matrix.dshKind === 'pkg-zip') {+ const zipName = matrix.dshZipName ?? ''+ let urls: string[] | undefined+ let digest: string | undefined+ try {+ const assets = await listAssets(repo, resolved.tag)+ const asset = assets.find(candidate => candidate.name === zipName)+ if (asset !== undefined) {+ urls = [asset.url, ...dshZipDownloadUrls(repo, resolved.tag, zipName).slice(1)]+ digest = asset.digest+ }+ }+ catch (error) {+ notes.push(`release 资产元数据获取失败(${describeError(error)})`)+ }+ if (digest === undefined)+ notes.push(`未取得 ${zipName} 的可信摘要,将跳过 SHA-256 校验`)+ return {+ os,+ arch,+ matrix,+ repo,+ dshEntry: DSH_ZIP_ENTRY,+ dshVersion: resolved.version,+ node,+ dsh: { kind: 'pkg-zip', urls: urls ?? dshZipDownloadUrls(repo, resolved.tag, zipName), ...digest === undefined ? {} : { digest }, zipName, tag: resolved.tag },+ pnpm,+ notes,+ }+ }+ const packageName = matrix.dshNpmPackage ?? '@deepseek-ai/dsh'+ if (resolved.version === '')+ throw new Error(`cannot resolve a DSH npm version from tag "${resolved.tag}"`)+ let urls: string[] | undefined+ let integrity: string | undefined+ try {+ const dist = await npmDist(packageName, resolved.version)+ urls = [dist.url, dist.mirrorUrl]+ integrity = dist.integrity+ }+ catch (error) {+ notes.push(`npm 元数据获取失败(${describeError(error)}),回退确定性 URL`)+ }+ if (integrity === undefined)+ notes.push(`未取得 ${packageName}@${resolved.version} 的完整性摘要,将跳过校验`)+ return {+ os,+ arch,+ matrix,+ repo,+ dshEntry: DSH_NPM_ENTRY,+ dshVersion: resolved.version,+ node,+ dsh: { kind: 'npm-tgz', urls: urls ?? dshNpmTarballUrls(packageName, resolved.version), ...integrity === undefined ? {} : { integrity }, packageName, version: resolved.version },+ pnpm,+ notes,+ }+}++/** The shell-quoted URL list for a fetch call. */+function quoteUrls(urls: string[]): string {+ return urls.map(shQuote).join(' ')+}++/**+ * Build the remote install script (POSIX sh) for one plan. Behavior: idempotent+ * (installed components are skipped), official → mirror download fallback with+ * both sources' errors reported on double failure, SHA-256/512 verification+ * with mismatch abort and partial cleanup (`trap`), single-top-level+ * flattening, and the `npm-tgz` kind's `pnpm install` (registry official →+ * mirror fallback). Progress reports through `::dsh <stage> <line>` markers.+ * @param plan - the resolved install plan.+ * @returns the full script text.*/-export function startCommandFor(profile: MachineProfile, dshPath?: string): string {- const base = profile.startCommand !== undefined- ? profile.startCommand- : dshPath === undefined- ? defaultStartCommand(profile)- : `${dshPath} web --host 127.0.0.1 --port ${profile.remotePort}`- // Detach through a double subshell: `( … & ) &` — the inner background job- // reparents (orphan) as soon as the wrapping subshell exits, so nothing- // holds the exec channel's stdin and sshd closes the channel immediately- // (a bare `… &` keeps the instance in the session: sshd holds the channel- // open and ssh2's exec never settles). Output goes to the log with stdin- // from /dev/null; no nohup (macOS nohup kills the child in this context).- return `mkdir -p "$HOME/.dsh" && ( ${base} >>"$HOME/${REMOTE_WEB_LOG}" 2>&1 < /dev/null & ) &`+export function buildInstallScript(plan: RemoteInstallPlan): string {+ const dshSection = plan.dsh.kind === 'pkg-zip'+ ? [+ `if [ -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ]; then`,+ ` log install "dsh 已就绪"`,+ `else`,+ ` log download "dsh ${plan.dsh.tag}"`,+ ` fetch "$TMP/dsh-pkg.zip" ${quoteUrls(plan.dsh.urls)}`,+ ` verify "$TMP/dsh-pkg.zip" "${plan.dsh.digest ?? ''}" "${plan.dsh.zipName}"`,+ ` extract_zip "$TMP/dsh-pkg.zip" "$ROOT/dependencies/dsh.new"`,+ ` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,+ ` log install "dsh 安装完成 (${plan.dsh.tag})"`,+ `fi`,+ ].join('\n')+ : [+ // The npm kind assembles node_modules on the remote: pnpm resolves+ // the platform-correct natives, official registry first, mirror fallback.+ `install_dsh_deps() {`,+ ` for _reg in ${quoteUrls(['https://registry.npmjs.org', 'https://registry.npmmirror.com'])}; do`,+ ` if "$ROOT/runtime/bin/node" "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" install --prod --silent --registry="$_reg" >"$TMP/pnpm.log" 2>&1; then`,+ ` log install "dsh 依赖安装完成 (registry $_reg)"`,+ ` return 0`,+ ` fi`,+ ` done`,+ ` log failed "pnpm install 失败: $(tail -n 5 "$TMP/pnpm.log" 2>/dev/null | tr '\n' ' ')"`,+ ` return 1`,+ `}`,+ `if [ -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then`,+ ` log install "dsh 已就绪"`,+ `else`,+ ` log download "dsh ${plan.dsh.packageName}@${plan.dsh.version} (npm)"`,+ ` fetch "$TMP/dsh.tgz" ${quoteUrls(plan.dsh.urls)}`,+ ` verify "$TMP/dsh.tgz" "${plan.dsh.integrity ?? ''}" "${plan.dsh.packageName}-${plan.dsh.version}.tgz"`,+ ` rm -rf "$ROOT/dependencies/dsh.new"`,+ ` mkdir -p "$ROOT/dependencies/dsh.new"`,+ ` tar -xzf "$TMP/dsh.tgz" -C "$ROOT/dependencies/dsh.new" --strip-components=1`,+ ` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,+ ` install_dsh_deps || exit 13`,+ ` log install "dsh 安装完成 (${plan.dsh.packageName}@${plan.dsh.version})"`,+ `fi`,+ ].join('\n')+ return [+ 'set -eu',+ 'ROOT="$HOME/.dsh-desktop"',+ 'TMP="$ROOT/tmp"',+ 'mkdir -p "$ROOT/dependencies" "$TMP"',+ // Half-finished products never outlive the run: the trap clears the+ // staging area and any *.new partial directory on every exit path.+ 'cleanup() { rm -rf "$TMP" "$ROOT/runtime.new" "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/dsh.new"; }',+ 'trap cleanup EXIT',+ `log() { printf '${BOOTSTRAP_LOG_PREFIX}%s %s\\n' "$1" "$2"; }`,+ 'fetch() {',+ ' _dst="$1"; shift',+ ' _errs=""',+ ' for _url in "$@"; do',+ ' if command -v curl >/dev/null 2>&1; then',+ ' log download "$_url"',+ ' if curl -fsSL --retry 3 --connect-timeout 15 -o "$_dst" "$_url" 2>"$TMP/fetch.err"; then return 0; fi',+ ' _errs="$_errs | $_url: $(head -n 1 "$TMP/fetch.err" 2>/dev/null || echo download failed)"',+ ' elif command -v wget >/dev/null 2>&1; then',+ ' log download "$_url"',+ ' if wget -q --tries=3 -O "$_dst" "$_url" 2>/dev/null; then return 0; fi',+ ' _errs="$_errs | $_url: wget download failed"',+ ' else',+ ' log failed "REMOTE_INSTALL_NO_DOWNLOADER: 远端缺少 curl 或 wget,请先安装其一"',+ ' exit 9',+ ' fi',+ ' done',+ ' log failed "所有下载源均失败:$_errs"',+ ' exit 10',+ '}',+ 'verify() {',+ ' _file="$1"; _want="$2"; _name="$3"',+ ' case "$_want" in',+ ' sha256:*) _algo=256; _hex="$(printf \'%s\' "$_want" | sed \'s/^sha256://\')" ;;',+ ' sha512:*) _algo=512; _hex="$(printf \'%s\' "$_want" | sed \'s/^sha512://\')" ;;',+ ' "") log verify "警告: 未取得可信摘要,跳过校验 $_name"; return 0 ;;',+ ' *) _algo=256; _hex="$_want" ;;',+ ' esac',+ ' _got=""',+ ` if [ "\$_algo" = 256 ]; then`,+ ' if command -v sha256sum >/dev/null 2>&1; then _got="$(sha256sum "$_file" | cut -d\' \' -f1)"',+ ' elif command -v shasum >/dev/null 2>&1; then _got="$(shasum -a 256 "$_file" | cut -d\' \' -f1)"',+ ' fi',+ ' else',+ ' if command -v sha512sum >/dev/null 2>&1; then _got="$(sha512sum "$_file" | cut -d\' \' -f1)"',+ ' elif command -v shasum >/dev/null 2>&1; then _got="$(shasum -a 512 "$_file" | cut -d\' \' -f1)"',+ ' fi',+ ' fi',+ ' if [ -z "$_got" ]; then',+ ' log verify "警告: 远端缺少摘要工具,跳过校验 $_name"',+ ' return 0',+ ' fi',+ ' if [ "$_got" != "$_hex" ]; then',+ ' log failed "checksum mismatch: $_name (want sha$_algo:$_hex, got $_got)"',+ ' exit 11',+ ' fi',+ ` log verify "$_name 校验通过 (sha$_algo)"`,+ '}',+ 'extract_zip() {',+ ' _zip="$1"; _dir="$2"',+ ' mkdir -p "$_dir"',+ ' if command -v unzip >/dev/null 2>&1; then unzip -q -o "$_zip" -d "$_dir"',+ ' elif command -v python3 >/dev/null 2>&1; then python3 -m zipfile -e "$_zip" "$_dir"',+ ' else',+ ' log failed "REMOTE_INSTALL_NO_UNZIP: 远端缺少 unzip 或 python3,无法解压发行包"',+ ' exit 12',+ ' fi',+ '}',+ 'flatten_move() {',+ ' _src="$1"; _dst="$2"',+ ' _count=0; _top=""',+ ' for _e in "$_src"/*; do',+ ' if [ -e "$_e" ]; then _count=$((_count + 1)); _top="$_e"; fi',+ ' done',+ ' rm -rf "$_dst"',+ ' if [ "$_count" -eq 1 ] && [ -d "$_top" ]; then',+ ' mkdir -p "$_dst"',+ ' for _e in "$_top"/* "$_top"/.[!.]* "$_top"/..?*; do',+ ' if [ -e "$_e" ]; then mv -f "$_e" "$_dst/"; fi',+ ' done',+ ' rmdir "$_top" 2>/dev/null || true',+ ' rmdir "$_src" 2>/dev/null || true',+ ' else',+ ' mv -f "$_src" "$_dst"',+ ' fi',+ '}',+ 'if [ -x "$ROOT/runtime/bin/node" ]; then',+ ' log install "node 已就绪: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo installed)"',+ 'else',+ ` log download "node ${plan.node.version}"`,+ ` fetch "$TMP/node.tar.gz" ${quoteUrls(plan.node.urls)}`,+ ` fetch "$TMP/SHASUMS256.txt" ${quoteUrls(plan.node.shasumUrls)}`,+ ` _want="$(grep " ${plan.node.filename}\$" "$TMP/SHASUMS256.txt" | head -n 1 | tr -d '\\r' | sed 's/^ *//' | cut -d' ' -f1)"`,+ ` verify "$TMP/node.tar.gz" "\$_want" "${plan.node.filename}"`,+ ' rm -rf "$ROOT/runtime.new"',+ ' mkdir -p "$ROOT/runtime.new"',+ ' tar -xzf "$TMP/node.tar.gz" -C "$ROOT/runtime.new" --strip-components=1',+ ' flatten_move "$ROOT/runtime.new" "$ROOT/runtime"',+ ` log install "node 安装完成: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo ok)"`,+ 'fi',+ `if [ -f "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" ]; then`,+ ' log install "pnpm 已就绪"',+ 'else',+ ` log download "pnpm ${plan.pnpm.version}"`,+ ` fetch "$TMP/pnpm.tgz" ${quoteUrls(plan.pnpm.urls)}`,+ ` verify "$TMP/pnpm.tgz" "sha256:${plan.pnpm.sha256}" "pnpm-${plan.pnpm.version}.tgz"`,+ ' rm -rf "$ROOT/dependencies/pnpm.new"',+ ' mkdir -p "$ROOT/dependencies/pnpm.new"',+ ' tar -xzf "$TMP/pnpm.tgz" -C "$ROOT/dependencies/pnpm.new" --strip-components=1',+ ' flatten_move "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/pnpm"',+ ` log install "pnpm 安装完成: ${plan.pnpm.version}"`,+ 'fi',+ dshSection,+ 'log install "远端初始化完成"',+ ].join('\n')}/**- * Probe for a remote `dsh` binary, in install order: the login shell's PATH,- * then the installer's `~/.local/bin` link, then the source checkout's- * launcher. Prints the resolved path (possibly `$HOME`-relative) or nothing.- * Each branch is a braced group so a successful `command -v` short-circuits- * the whole `||` chain without the later `&& printf` arms firing too.+ * The remote missing-components probe: prints one line per missing member of+ * the three-part runtime (nothing when fully installed).*/-export function probeDshCommand(): string {+export function checkMissingCommand(): string {return [- 'command -v dsh 2>/dev/null',- `{ test -x "$HOME/.local/bin/dsh" && printf '%s\\n' "$HOME/.local/bin/dsh"; }`,- `{ test -x "$HOME/.dsh/source/current/bin/dsh" && printf '%s\\n' "$HOME/.dsh/source/current/bin/dsh"; }`,+ `ROOT="$HOME/${REMOTE_ROOT}"`,+ `[ -x "$ROOT/runtime/bin/node" ] || echo node`,+ `[ -f "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" ] || echo pnpm`,+ `if [ ! -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ] && [ ! -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then echo dsh; fi`,'true',- ].join(' || ')+ ].join('\n')+}++/** Parse the check script's stdout into the missing component set. */+export function missingComponentsOf(stdout: string): string[] {+ return stdout.split('\n').map(line => line.trim()).filter(line => line !== '' && ['node', 'dsh', 'pnpm'].includes(line))}/**- * The one-line remote install, built in (no external script to curl — the- * "official" installer URL does not exist yet): clone the repository (the- * configured `installRepo`, default branch or `installRef`), install- * dependencies, build the web frontend, and link `dsh` into- * `~/.local/bin` (the path the probe resolves when the login PATH lacks it).- * A prior managed install under `~/.dsh/source` is replaced, so re-running- * reinstalls cleanly.- * @param config - plugin config (repo and ref overrides).- * @returns the full remote install command line.+ * The default remote-instance start command's entry resolution: the layout's+ * Node binary and DSH entry, always (the installer's `~/.local/bin` link no+ * longer exists in the binary layout).*/-export function installCommandFor(config: Pick<Config, 'installRepo' | 'installRef'>): string {- const repo = config.installRepo === undefined || config.installRepo === ''- ? OFFICIAL_INSTALL_REPO- : config.installRepo- const ref = config.installRef === undefined || config.installRef === ''- ? undefined- : config.installRef- const clone = ref === undefined- ? `git clone --depth 1 ${shQuote(repo)} "$HOME/.dsh/source/master"`- : `git clone --depth 1 --branch ${shQuote(ref)} ${shQuote(repo)} "$HOME/.dsh/source/master"`+export function layoutDshEntry(plan?: RemoteInstallPlan): string {+ return `$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan?.dshEntry ?? DSH_ZIP_ENTRY}`+}++/**+ * The remote-instance launch: the profile override when present, else the+ * layout's Node + DSH entry with the port pinned twice (`DSH_WEB_PORT` and+ * the flag). Detached through a double subshell so the exec channel settles+ * immediately; the pid lands in `~/.dsh/.dsh-remote.pid`; output redirects+ * to the log with stdin from /dev/null; no `nohup` (macOS kills the child).+ * @param profile - the machine profile (port + start command override).+ * @param plan - the resolved install plan (chooses the DSH entry).+ * @returns the shell command line that starts (or restarts) the instance.+ */+export function startCommandFor(profile: MachineProfile, plan?: RemoteInstallPlan): string {+ if (profile.startCommand !== undefined)+ return `mkdir -p "$HOME/.dsh" && ( ${profile.startCommand} >>"$HOME/${REMOTE_WEB_LOG}" 2>&1 < /dev/null & ) &`+ const node = `$HOME/${REMOTE_ROOT}/runtime/bin/node`+ const dshBin = layoutDshEntry(plan)return [- 'set -e',- `mkdir -p "$HOME/.dsh/source" "$HOME/.local/bin"`,- `rm -rf "$HOME/.dsh/source/master" "$HOME/.dsh/source/current"`,- `echo '==> cloning dsh source'`,- clone,- `ln -s "$HOME/.dsh/source/master" "$HOME/.dsh/source/current"`,- `echo '==> ensuring pnpm'`,- // pnpm may live outside the login PATH (nvm etc.): enable it via- // corepack (ships with Node), else install it globally with npm.- `(command -v pnpm >/dev/null 2>&1) || (corepack enable pnpm >/dev/null 2>&1) || npm install -g pnpm`,- `echo '==> installing dependencies (pnpm install)'`,- `(cd "$HOME/.dsh/source/current" && pnpm install)`,- `echo '==> building web UI'`,- `(cd "$HOME/.dsh/source/current" && pnpm run build)`,- `ln -sfn "$HOME/.dsh/source/current/bin/dsh" "$HOME/.local/bin/dsh"`,- `echo '==> dsh installed'`,- ].join(' && ')+ `ROOT="$HOME/${REMOTE_ROOT}"`,+ `NODE=${node}`,+ `DSH_BIN=${dshBin}`,+ `LOG_DIR="$HOME/.dsh"`,+ `LOG="$LOG_DIR/dsh-remote-web.log"`,+ `if [ ! -x "$NODE" ] || [ ! -f "$DSH_BIN" ]; then echo "REMOTE_NOT_INSTALLED: 远端三件套未安装完整"; exit 1; fi`,+ `mkdir -p "$LOG_DIR"`,+ `export PATH="$ROOT/runtime/bin:$PATH"`,+ `export DSH_TELEMETRY_DISABLED=1 NO_COLOR=1 DSH_WEB_PORT=${profile.remotePort}`,+ `( sh -c 'echo $$ > "$1/.dsh-remote.pid"; exec "$2" "$3" web --host 127.0.0.1 --port "$4" --no-open' dsh-remote "$LOG_DIR" "$NODE" "$DSH_BIN" ${profile.remotePort} </dev/null >>"$LOG" 2>&1 & )`,+ `echo "远端实例已拉起(日志: $LOG)"`,+ ].join('\n')}/** Credentials read from a local dsh `.env` document. */@@ -121,8 +441,7 @@ export interface EnvCredentials {}/**- * Read `DEEPSEEK_API_KEY`/`DEEPSEEK_BASE_URL` from a dsh `.env` document- * (the installer's own layout: `KEY=value` lines, no quoting).+ * Read `DEEPSEEK_API_KEY`/`DEEPSEEK_BASE_URL` from a dsh `.env` document.* @param path - the `.env` file path (the harness home's `.env`).* @returns the credentials present in the document.*/@@ -185,13 +504,43 @@ export function firstLineOf(stdout: string): string {}/**- * One health probe: curl the remote instance's web port. Any HTTP response- * (including 404 on the bare path) proves the webserver listens; a refused- * connection exits nonzero.+ * The root-page probe: fetch the instance's boot HTML. Any HTTP response+ * (including 404) exits 0 — the body decides; a refused connection exits+ * nonzero.+ * @param remotePort - the instance's loopback port.+ * @param timeoutMs - per-probe curl deadline.+ */+export function rootProbeCommand(remotePort: number, timeoutMs: number): string {+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))+ return `curl -s -m ${seconds} http://127.0.0.1:${remotePort}/`+}++/**+ * The client-bundle probe: fetch one boot-manifest URL, printing the body+ * followed by the numeric status code on its last line.+ * @param url - the absolute loopback URL to fetch.+ * @param timeoutMs - per-probe curl deadline.*/-export function healthCheckCommand(remotePort: number, timeoutMs: number): string {+export function bundleProbeCommand(url: string, timeoutMs: number): string {const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))- return `curl -s -o /dev/null -m ${seconds} -w '%{http_code}' http://127.0.0.1:${remotePort}/`+ return `curl -s -m ${seconds} -w '\\n%{http_code}' ${shQuote(url)}`+}++/**+ * Split a bundle probe's stdout into body and numeric status. Malformed+ * output (no trailing status line) reports status 0.+ * @param stdout - the raw probe stdout.+ */+export function splitBundleProbeStdout(stdout: string): { body: string, status: number } {+ const trimmed = stdout.replace(/\n$/u, '')+ const index = trimmed.lastIndexOf('\n')+ if (index < 0) {+ // A single-line answer is the bare status (an empty body).+ const status = Number.parseInt(trimmed, 10)+ return Number.isNaN(status) ? { body: trimmed, status: 0 } : { body: '', status }+ }+ const status = Number.parseInt(trimmed.slice(index + 1).trim(), 10)+ return Number.isNaN(status) ? { body: trimmed, status: 0 } : { body: trimmed.slice(0, index), status }}/** The tail command that recovers the remote instance's log for the error message. */@@ -199,71 +548,186 @@ export function logTailCommand(): string {return `tail -n 20 "$HOME/${REMOTE_WEB_LOG}" 2>/dev/null || true`}-/** The typed failure "the remote has no `dsh` binary" (offers the install path). */-export class DshMissingError extends Error {}+/** One operator-facing fragment for a failed remote command. */+export function describeExecFailure(code: number | null, stderr: string): string {+ const tail = stderr.trim().split('\n').slice(-3).join(' | ')+ return `exit ${code ?? '?'}${tail === '' ? '' : `: ${tail}`}`+}++/** One operator-facing fragment for an unknown-shape failure. */+export function describeError(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++/** Hooks the assurance flow reports through (both optional). */+export interface BootstrapHooks {+ /** Coarse UI progress (the settings page's live status line). */+ onProgress?: (progress: SshProgress) => void+ /** Machine event channel appends (stage-tagged, the spec's C-EVENT). */+ onEvent?: (stage: 'probe' | 'download' | 'verify' | 'install' | 'launch' | 'ready' | 'failed', line: string, options?: { terminal?: 'success' | 'failed', reason?: string }) => void+}++/** Timing + source configuration of the assurance flow. */+export interface BootstrapConfig {+ config: Pick<Config, 'installRepo' | 'installRef' | 'installTimeoutMs'>+ healthCheckTimeoutMs: number+ healthPollIntervalMs: number+ healthPollAttempts: number+}/**- * Ensure the remote instance answers on its port: probe once, auto-start when- * absent, then poll until healthy or the attempt budget is exhausted. The- * failure message carries the remote log's tail — a backgrounded start always- * exits 0 (even when the command itself fails), so the log is the only place- * the real error (command not found, port busy, …) is visible. When the- * default start command is in play (no profile override), the `dsh` binary is- * resolved first and its absence fails fast with {@link DshMissingError}.+ * Ensure the remote instance is ready: judge readiness from the served boot+ * HTML (client-bundle manifest), and when it is not, bootstrap the machine —+ * probe the platform, install missing runtime components from pinned binary+ * assets, launch the instance, and poll until the manifest answers. The+ * legacy any-response verdict stays as the fallback for instances whose HTML+ * carries no manifest.* @param session - the authenticated SSH session.- * @param profile - the machine profile (port + start command).- * @param timeoutMs - per-probe curl deadline.- * @param pollIntervalMs - pause between probes.- * @param pollAttempts - total probes after the initial one.- * @param onProgress - receives the live bootstrap phase (started/probing).- * @returns a short description of the healthy instance (host:port).- * @throws {DshMissingError} when no `dsh` binary is reachable.- * @throws {Error} with an operator-facing message when the instance never becomes reachable.+ * @param profile - the machine profile (port + start command override).+ * @param bootstrap - timing + source configuration.+ * @param hooks - progress and event reporting.+ * @param planner - the install-plan resolver (injectable for tests).+ * @returns a short description of the ready instance (host:port, plus how+ * readiness was judged).+ * @throws {Error} with an operator-facing message when the machine cannot be+ * bootstrapped (unsupported platform, install failure, never ready).*/export async function ensureRemoteInstance(session: SshSession,profile: MachineProfile,- timeoutMs: number,- pollIntervalMs: number,- pollAttempts: number,- onProgress?: (progress: SshProgress) => void,+ bootstrap: BootstrapConfig,+ hooks: BootstrapHooks = {},+ planner: (unameOut: string, config: Pick<Config, 'installRepo' | 'installRef'>) => Promise<RemoteInstallPlan> = (unameOut, config) => planRemoteInstall(unameOut, config),): Promise<string> {- const probe = async (): Promise<boolean> => {- const result = await session.exec(healthCheckCommand(profile.remotePort, timeoutMs))- return result.code === 0- }- if (await probe())- return `${profile.host}:${profile.remotePort}`- onProgress?.({ phase: 'starting' })- let dshPath: string | undefined- if (profile.startCommand === undefined) {- dshPath = firstLineOf((await session.exec(probeDshCommand())).stdout)- if (dshPath === '') {- throw new DshMissingError(- `dsh is not installed on "${profile.host}" (checked the login PATH, ~/.local/bin and ~/.dsh/source/current); `- + 'install it with the one-click install, or configure the machine\'s start command',- )+ const { onEvent, onProgress } = hooks+ const target = `${profile.host}:${profile.remotePort}`+ const readyFromHtml = await judgeReadiness(session, profile, bootstrap)+ if (readyFromHtml !== undefined) {+ if (readyFromHtml.startsWith('boot')) {+ onEvent?.('ready', `远端实例已就绪 (${target})`, { terminal: 'success' })+ }+ else {+ onEvent?.('ready', `远端实例已就绪(旧探测兜底: ${readyFromHtml})`, { terminal: 'success' })}+ return target+ }+ // The instance is not answering: bootstrap (probe → install → launch).+ onEvent?.('probe', '探测远端平台 (uname -srm)')+ const uname = await session.exec('uname -srm')+ if (uname.code !== 0) {+ return failBootstrap(onEvent, `无法探测远端平台: ${describeExecFailure(uname.code, uname.stderr)}`)+ }+ let plan: RemoteInstallPlan+ try {+ plan = await planner(uname.stdout, bootstrap.config)}- const started = await session.exec(startCommandFor(profile, dshPath))+ catch (error) {+ return failBootstrap(onEvent, describeError(error))+ }+ onEvent?.('probe', `远端平台 ${plan.os}/${plan.arch},安装源 ${plan.repo}${plan.dsh.kind === 'pkg-zip' ? ` tag ${plan.dsh.tag}` : ` npm ${plan.dsh.version}`}`)+ for (const note of plan.notes)+ onEvent?.('probe', note)+ const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)+ if (missing.length > 0) {+ onEvent?.('probe', `缺失组件: ${missing.join(', ')}`)+ await runInstallScript(session, plan, bootstrap, hooks)+ }+ else {+ onEvent?.('probe', '三件套已就绪,跳过安装')+ }+ onProgress?.({ phase: 'starting' })+ onEvent?.('launch', `拉起远端实例 (端口 ${profile.remotePort})`)+ const started = await session.exec(startCommandFor(profile, plan))if (started.code !== 0) {- throw new Error(- `remote instance start failed on "${profile.host}": ${describeExecFailure(started.code, started.stderr)}`,- )+ const message = started.stdout.includes('REMOTE_NOT_INSTALLED')+ ? `remote runtime incomplete on "${profile.host}" (REMOTE_NOT_INSTALLED)`+ : `remote instance start failed on "${profile.host}": ${describeExecFailure(started.code, started.stderr)}`+ return failBootstrap(onEvent, message)}- for (let attempt = 0; attempt < pollAttempts; attempt++) {- onProgress?.({ phase: 'probing', attempt: attempt + 1, total: pollAttempts })- await sleep(pollIntervalMs)- if (await probe())- return `${profile.host}:${profile.remotePort}`+ for (let attempt = 0; attempt < bootstrap.healthPollAttempts; attempt++) {+ onProgress?.({ phase: 'probing', attempt: attempt + 1, total: bootstrap.healthPollAttempts })+ await sleep(bootstrap.healthPollIntervalMs)+ const verdict = await judgeReadiness(session, profile, bootstrap)+ if (verdict !== undefined) {+ if (verdict.startsWith('boot')) {+ onEvent?.('ready', `远端实例已就绪 (${target})`, { terminal: 'success' })+ return target+ }+ onEvent?.('ready', `远端实例已就绪(旧探测兜底: ${verdict})`, { terminal: 'success' })+ return target+ }}const tail = await logTail(session)- throw new Error(- `remote dsh web did not become reachable on "${profile.host}:${profile.remotePort}" `- + `within ${pollAttempts} polls; remote log (${shQuote(`$HOME/${REMOTE_WEB_LOG}`)}) tail: ${tail}`,+ return failBootstrap(+ onEvent,+ `remote dsh web did not become ready on "${target}" within ${bootstrap.healthPollAttempts} polls; `+ + `fallback probe: root ${await legacyRootVerdict(session, profile, bootstrap)}; `+ + `remote log tail: ${tail}`,)}+/**+ * One readiness judgement: boot-HTML manifest (primary) or any-response+ * (legacy fallback). Returns `boot …` / `legacy …`, or undefined while not+ * ready.+ */+async function judgeReadiness(session: SshSession, profile: MachineProfile, bootstrap: BootstrapConfig): Promise<string | undefined> {+ const root = await session.exec(rootProbeCommand(profile.remotePort, bootstrap.healthCheckTimeoutMs))+ if (root.code !== 0)+ return undefined+ const urls = clientUrlsFromBootHtml(profile.remotePort, root.stdout)+ if (urls === undefined) {+ // No usable manifest: keep the legacy verdict — an answered port still+ // proves a webserver listens (the v1 behavior, demoted to fallback).+ return await legacyRootVerdict(session, profile, bootstrap)+ }+ const first = urls[0]+ if (first === undefined)+ return undefined+ const probe = await session.exec(bundleProbeCommand(first, bootstrap.healthCheckTimeoutMs))+ const { body, status } = splitBundleProbeStdout(probe.stdout)+ if (probe.code === 0 && status >= 200 && status < 300 && looksLikePluginBundle(true, body))+ return `boot manifest (${urls.length} bundles)`+ return undefined+}++/** The legacy any-response verdict, with the observed status code attached. */+async function legacyRootVerdict(session: SshSession, profile: MachineProfile, bootstrap: BootstrapConfig): Promise<string> {+ const probe = await session.exec(`curl -s -o /dev/null -m ${Math.max(1, Math.ceil(bootstrap.healthCheckTimeoutMs / 1000))} -w '%{http_code}' http://127.0.0.1:${profile.remotePort}/`)+ return probe.code === 0 ? `root answered ${probe.stdout.trim() || '?'}` : 'no answer'+}++/** Run the generated install script, streaming its stage-tagged output. */+async function runInstallScript(session: SshSession, plan: RemoteInstallPlan, bootstrap: BootstrapConfig, hooks: BootstrapHooks): Promise<void> {+ const { onEvent, onProgress } = hooks+ const installTimeoutMs = bootstrap.config.installTimeoutMs+ let log = ''+ const result = await session.exec(buildInstallScript(plan), {+ ...installTimeoutMs === undefined ? {} : { timeoutMs: installTimeoutMs },+ onData: (chunk) => {+ log = `${log}${chunk}`.slice(-2000)+ for (const line of chunk.split('\n').filter(line => line !== '')) {+ const parsed = parseBootstrapLine(line)+ onEvent?.(parsed.stage as 'probe' | 'download' | 'verify' | 'install' | 'launch' | 'ready' | 'failed', parsed.line)+ }+ onProgress?.({ phase: 'installing', log })+ },+ })+ if (result.code !== 0) {+ // Prefer the streamed log (the transport taps stdout live); transports+ // without the tap still surface the markers through the collected stdout.+ const stream = log.trim() === '' ? result.stdout.trim() : log.trim()+ const tail = stream === '' ? '(no output captured)' : stream.split('\n').slice(-5).join(' | ')+ failBootstrap(onEvent, `install failed on remote (exit ${result.code ?? '?'}): ${tail}`)+ }+}++/** Record the terminal failure and build the thrown error. */+function failBootstrap(onEvent: BootstrapHooks['onEvent'], reason: string): never {+ onEvent?.('failed', 'bootstrap 失败', { terminal: 'failed', reason })+ throw new Error(reason)+}+/** The remote instance log's tail, or a note when nothing was captured. */async function logTail(session: SshSession): Promise<string> {try {@@ -276,12 +740,6 @@ async function logTail(session: SshSession): Promise<string> {}}-/** One operator-facing fragment for a failed remote command. */-export function describeExecFailure(code: number | null, stderr: string): string {- const tail = stderr.trim().split('\n').slice(-3).join(' | ')- return `exit ${code ?? '?'}${tail === '' ? '' : `: ${tail}`}`-}-function sleep(ms: number): Promise<void> {return new Promise(resolve => setTimeout(resolve, ms))}diff --git a/packages/dsh-tauri-ssh/src/host/service/events.test.ts b/packages/dsh-tauri-ssh/src/host/service/events.test.tsnew file mode 100644index 00000000..9661d059--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/events.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest'+import { MachineId } from '../types/index.js'+import { EVENT_RING_CAPACITY, SshMachineEvents } from './events.js'++const m1 = MachineId('m1')+const m2 = MachineId('m2')++describe('sshMachineEvents', () => {+ it('assigns per-machine monotonic seqs starting at 1', () => {+ const log = new SshMachineEvents()+ log.append(m1, 'probe', 'one')+ log.append(m1, 'download', 'two')+ log.append(m2, 'probe', 'other machine')+ const page = log.since(m1)+ expect(page.events.map(event => event.seq)).toEqual([1, 2])+ expect(page.nextSeq).toBe(3)+ expect(log.since(m2).events).toHaveLength(1)+ })++ it('stamps ts and machineId on every event and carries terminal/reason only when present', () => {+ const log = new SshMachineEvents()+ const first = log.append(m1, 'probe', 'probing')+ expect(first.machineId).toBe(m1)+ expect(first.ts).toBeTruthy()+ expect('terminal' in first).toBe(false)+ const last = log.append(m1, 'failed', 'bootstrap 失败', { terminal: 'failed', reason: 'checksum mismatch' })+ expect(last.terminal).toBe('failed')+ expect(last.reason).toBe('checksum mismatch')+ const ready = log.append(m1, 'ready', '已就绪', { terminal: 'success' })+ expect(ready.terminal).toBe('success')+ expect('reason' in ready).toBe(false)+ })++ it('drains incrementally by sinceSeq', () => {+ const log = new SshMachineEvents()+ for (let i = 0; i < 5; i++)+ log.append(m1, 'install', `line ${i}`)+ const first = log.since(m1)+ expect(first.events).toHaveLength(5)+ const second = log.since(m1, first.events[2]?.seq)+ expect(second.events.map(event => event.line)).toEqual(['line 3', 'line 4'])+ expect(second.nextSeq).toBe(6)+ const caughtUp = log.since(m1, 4)+ expect(caughtUp.events).toHaveLength(1)+ })++ it('anchors unknown machines at an empty page', () => {+ const log = new SshMachineEvents()+ expect(log.since(MachineId('nope'))).toEqual({ events: [], nextSeq: 1 })+ })++ it('keeps only the newest events per machine (ring buffer)', () => {+ const log = new SshMachineEvents(3)+ for (let i = 0; i < 6; i++)+ log.append(m1, 'download', `url ${i}`)+ const page = log.since(m1)+ expect(page.events.map(event => event.line)).toEqual(['url 3', 'url 4', 'url 5'])+ expect(page.nextSeq).toBe(7)+ // A lagged consumer skipping past the dropped window sees only what survives.+ expect(log.since(m1, 1).events).toHaveLength(3)+ })++ it('uses the documented default capacity', () => {+ const log = new SshMachineEvents()+ for (let i = 0; i < EVENT_RING_CAPACITY + 25; i++)+ log.append(m1, 'install', `line ${i}`)+ expect(log.since(m1).events).toHaveLength(EVENT_RING_CAPACITY)+ })++ it('forgets a removed machine independently of its neighbors', () => {+ const log = new SshMachineEvents()+ log.append(m1, 'probe', 'one')+ log.append(m2, 'probe', 'two')+ log.forget(m1)+ expect(log.since(m1).events).toHaveLength(0)+ expect(log.since(m2).events).toHaveLength(1)+ // A re-created machine starts a fresh seq domain.+ expect(log.append(m1, 'probe', 'again').seq).toBe(1)+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/events.ts b/packages/dsh-tauri-ssh/src/host/service/events.tsnew file mode 100644index 00000000..0479b25c--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/events.ts@@ -0,0 +1,91 @@+/**+ * The machine-level log/progress event channel (`/api-ssh` method+ * `machine.events`): a per-machine ring buffer of bootstrap stages, drained+ * by polling (no SSE/WebSocket — the settings page polls `sinceSeq`+ * incrementally). Owned by this plugin's bootstrap plane; the connection+ * lifecycle stages (S3) extend the same stage union on this channel.+ * @module dsh-tauri-ssh/host/service/events+ */++import type { MachineId, SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal } from '../types/index.js'++export type { SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal }++/** Events kept per machine before the oldest are dropped. */+export const EVENT_RING_CAPACITY = 500++/**+ * The per-machine ring buffer. Appends are serialized through a monotonic+ * per-machine counter; reads never mutate. One instance is shared by the+ * manager and the `/api-ssh` route.+ */+export class SshMachineEvents {+ private readonly buffers = new Map<MachineId, { seq: number, events: SshMachineEvent[] }>()++ /**+ * @param capacity - events kept per machine (defaults to+ * {@link EVENT_RING_CAPACITY}).+ */+ constructor(private readonly capacity: number = EVENT_RING_CAPACITY) {}++ /**+ * Append one event.+ * @param machineId - the machine the event is about.+ * @param stage - the pipeline stage.+ * @param line - the displayable log line.+ * @param options - the terminal verdict and failure reason, when present.+ * @param options.terminal - the terminal verdict, when the event settles an operation.+ * @param options.reason - the failure reason, on `terminal: 'failed'`.+ * @returns the stored event (with its assigned `seq`).+ */+ append(machineId: MachineId, stage: SshMachineStage, line: string, options: { terminal?: SshMachineTerminal, reason?: string } = {}): SshMachineEvent {+ const buffer = this.ensure(machineId)+ buffer.seq += 1+ const event: SshMachineEvent = {+ seq: buffer.seq,+ ts: new Date().toISOString(),+ machineId,+ stage,+ line,+ ...options.terminal === undefined ? {} : { terminal: options.terminal },+ ...options.reason === undefined ? {} : { reason: options.reason },+ }+ buffer.events.push(event)+ if (buffer.events.length > this.capacity)+ buffer.events.splice(0, buffer.events.length - this.capacity)+ return event+ }++ /**+ * Drain one machine's events after `sinceSeq` (inclusive lower bound is+ * `sinceSeq + 1`; omit it to read from the beginning).+ * @param machineId - the machine to read.+ * @param sinceSeq - the last seq the caller already saw.+ * @returns the drained slice and the next poll cursor; unknown machines+ * report an empty page anchored at seq 0.+ */+ since(machineId: MachineId, sinceSeq?: number): SshMachineEventsPage {+ const buffer = this.buffers.get(machineId)+ if (buffer === undefined)+ return { events: [], nextSeq: 1 }+ const after = sinceSeq === undefined ? 0 : Math.max(0, sinceSeq)+ return {+ events: buffer.events.filter(event => event.seq > after),+ nextSeq: buffer.seq + 1,+ }+ }++ /** Forget one machine's buffer (profile removed). */+ forget(machineId: MachineId): void {+ this.buffers.delete(machineId)+ }++ private ensure(machineId: MachineId): { seq: number, events: SshMachineEvent[] } {+ let buffer = this.buffers.get(machineId)+ if (buffer === undefined) {+ buffer = { seq: 0, events: [] }+ this.buffers.set(machineId, buffer)+ }+ return buffer+ }+}diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/manager.test.tsindex b9dd1214..2f3c51ef 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts@@ -1,4 +1,5 @@import type { MachineProfile } from '../types/index.js'+import type { RemoteInstallPlan } from './bootstrap.js'import type { SshExecOptions, SshExecResult, SshSession, SshTransport, SshTunnelHandle } from './transport.js'import { Buffer } from 'node:buffer'import { mkdtempSync, rmSync } from 'node:fs'@@ -6,6 +7,7 @@ import { tmpdir } from 'node:os'import { join } from 'pathe'import { afterEach, describe, expect, it } from 'vitest'import { MachineId, SshError } from '../types/index.js'+import { SshMachineEvents } from './events.js'import { KnownHostsStore } from './host-keys.js'import { SshManager } from './manager.js'@@ -33,8 +35,38 @@ const config = {installTimeoutMs: 60000,}-/** The dsh-path answer a remote probe would print. */-const RESOLVED_DSH = '/usr/local/bin/dsh'+/** A boot page whose manifest the bundle probe confirms. */+const BOOT_HTML = '<html><body><script>globalThis["__DSH_BOOT__"] = {"entries":[{"url":"/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"}]};</script></body></html>'++/** The layout entry the v2 install resolves (see {@link fakePlan}). */+const ENTRY = '$HOME/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js'++/** A literal linux/x64 plan (no network): the recommended pin with digest. */+function fakePlan(): RemoteInstallPlan {+ return {+ os: 'linux',+ arch: 'x64',+ matrix: { os: 'linux', arch: 'x64', dshKind: 'pkg-zip', nodeFilename: 'node-v22.22.0-linux-x64.tar.gz', dshZipName: 'deepseek-harness-pkg-linux.zip' },+ repo: 'dsh-tauri-desk/deepseek-harness-pkg',+ dshEntry: 'node_modules/@deepseek-ai/dsh/lib/bin.js',+ dshVersion: '0.1.2-rc.1',+ node: {+ urls: ['https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.gz'],+ shasumUrls: ['https://nodejs.org/dist/v22.22.0/SHASUMS256.txt'],+ filename: 'node-v22.22.0-linux-x64.tar.gz',+ version: 'v22.22.0',+ },+ dsh: {+ kind: 'pkg-zip',+ urls: ['https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-33729514615/deepseek-harness-pkg-linux.zip'],+ digest: 'sha256:6b7ecfeb',+ zipName: 'deepseek-harness-pkg-linux.zip',+ tag: 'dsh-0.1.2-rc.1-33729514615',+ },+ pnpm: { urls: ['https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz'], sha256: 'deaf'.repeat(16), version: '11.7.0' },+ notes: [],+ }+}class FakeSession implements SshSession {commands: string[] = []@@ -48,8 +80,6 @@ class FakeSession implements SshSession {tunnelGate: Promise<void> | undefinedtunnelStarted: (() => void) | undefinedexecGate: ((command: string, index: number) => Promise<void> | undefined) | undefined- /** What the remote dsh probe answers; undefined = a binary is reachable. */- dshProbeResult: string | undefined = RESOLVED_DSHprivate closedCallbacks: Array<() => void> = []constructor(@@ -59,28 +89,57 @@ class FakeSession implements SshSession {public installError?: Error,) {}+ /** The uname answer the platform probe prints (default: linux x64). */+ unameResult = 'Linux 6.8.0-45-generic x86_64\n'+ /** The check-script answer: one missing component per line (default: none). */+ missingResult = ''+ /** Whether the launch answered REMOTE_NOT_INSTALLED instead of starting. */+ startNotInstalled = false+exec(command: string, options?: SshExecOptions): Promise<SshExecResult> {this.commands.push(command)this.options.push(options ?? {})const respond = (): SshExecResult => {if (this.connectError !== undefined)throw this.connectError- if (command.includes('command -v dsh')) {- return { code: 0, stdout: this.dshProbeResult ?? '', stderr: '' }+ if (command === 'uname -srm') {+ return { code: 0, stdout: this.unameResult, stderr: '' }+ }+ if (command.includes('echo node')) {+ return { code: 0, stdout: this.missingResult, stderr: '' }}- if (command.includes('git clone')) {+ if (command.includes('trap cleanup EXIT')) {+ // A successful script settles the missing set, like a real install.+ this.missingResult = this.installError !== undefined ? this.missingResult : ''if (this.installError !== undefined)- return { code: 1, stdout: '', stderr: this.installError.message }- return { code: 0, stdout: 'installing...', stderr: '' }+ return { code: 1, stdout: '::dsh install far', stderr: this.installError.message }+ return { code: 0, stdout: '::dsh install 远端初始化完成', stderr: '' }+ }+ if (command.includes('test -f ')) {+ return { code: 0, stdout: 'ok\n', stderr: '' }}if (command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')) {return { code: 0, stdout: this.credentialsAnswer, stderr: '' }}- if (command.includes('curl') && !this.healthHealthy(this.commands.length - 1)) {- return { code: 7, stdout: '', stderr: 'refused' }+ if (command.includes('dsh-remote.pid')) {+ if (this.startNotInstalled)+ return { code: 1, stdout: 'REMOTE_NOT_INSTALLED: 远端三件套未安装完整', stderr: '' }+ if (this.startError !== undefined)+ return { code: 127, stdout: '', stderr: this.startError.message }+ return { code: 0, stdout: '远端实例已拉起', stderr: '' }+ }+ const healthy = this.healthHealthy(this.commands.length - 1)+ if (command.includes('/dev/null')) {+ return healthy ? { code: 0, stdout: '200', stderr: '' } : { code: 7, stdout: '', stderr: 'refused' }}- if (command.includes('web --host') && this.startError !== undefined) {- return { code: 127, stdout: '', stderr: this.startError.message }+ if (command.includes('curl')) {+ if (!healthy)+ return { code: 7, stdout: '', stderr: 'refused' }+ // The bundle probe (status-suffixed) answers JavaScript; the root+ // probe answers the boot page.+ return command.includes('-w')+ ? { code: 0, stdout: 'console.log(1)\n200', stderr: '' }+ : { code: 0, stdout: BOOT_HTML, stderr: '' }}return { code: 0, stdout: '200', stderr: '' }}@@ -171,17 +230,21 @@ function boot(overrides: Partial<{const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))transport.rejectKeys = overrides.rejectKeys ?? falseconst emits: Array<{ id: MachineId, state: string, progress?: { phase: string } }> = []+ const events = new SshMachineEvents()+ const plan = fakePlan()const manager = new SshManager({transport,knownHosts: tempKnownHosts(),config: overrides.config ?? config,+ events,+ planInstall: () => Promise.resolve(plan),...overrides.readEnvCredentials === undefined ? {} : { readEnvCredentials: overrides.readEnvCredentials },emitStatus: (id, status) => {emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })},})manager.refreshProfiles(new Map([[profile.id, profile], [secondProfile.id, secondProfile]]))- return { manager, transport, emits }+ return { manager, transport, emits, events }}describe('sshManager', () => {@@ -239,8 +302,10 @@ describe('sshManager', () => {const { manager } = boot({ sessionFactory: () => session })await manager.connect(MachineId('m1'))expect(session.commands[0]).toContain('curl')- expect(session.commands[1]).toContain('command -v dsh')- expect(session.commands[2]).toContain(`${RESOLVED_DSH} web --host 127.0.0.1 --port 3080`)+ expect(session.commands[1]).toBe('uname -srm')+ expect(session.commands[2]).toContain('echo node')+ expect(session.commands[3]).toContain('dsh-remote.pid')+ expect(session.commands[3]).toContain('--host 127.0.0.1')expect(manager.status(MachineId('m1')).state).toBe('connected')})@@ -265,13 +330,13 @@ describe('sshManager', () => {releaseStart = resolve})const session = new FakeSession(index => index !== 0)- session.execGate = command => command.includes('web --host') ? startGate : undefined+ session.execGate = command => command.includes('dsh-remote.pid') ? startGate : undefinedconst { manager, emits } = boot({ sessionFactory: () => session })const pending = manager.connect(MachineId('m1'))// Wait until the start command is in flight, then supersede the attempt.await new Promise<void>((resolve) => {const timer = setInterval(() => {- if (session.commands.some(command => command.includes('web --host'))) {+ if (session.commands.some(command => command.includes('dsh-remote.pid'))) {clearInterval(timer)resolve()}@@ -462,7 +527,7 @@ describe('sshManager', () => {session.commands = []const { manager } = boot({ sessionFactory: () => session })const result = await manager.test(MachineId('m1'))- expect(result).toEqual({ ok: true, banner: '200' })+ expect(result).toEqual({ ok: true, banner: 'Linux 6.8.0-45-generic x86_64' })expect(session.commands).toEqual(['uname -srm'])expect(session.closed).toBe(true)})@@ -574,22 +639,22 @@ describe('sshManager', () => {expect(manager.status(MachineId('m2')).state).toBe('disconnected')})- it('marks dshMissing when the remote has no dsh binary', async () => {+ it('marks dshMissing when the launch reports the runtime incomplete', async () => {const session = new FakeSession(index => index !== 0)- session.dshProbeResult = ''+ session.startNotInstalled = trueconst { manager } = boot({ sessionFactory: () => session })- await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-dsh-missing' })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })const status = manager.status(MachineId('m1'))expect(status.dshMissing).toBe(true)expect(status.state).toBe('disconnected')- expect(status.lastError).toContain('dsh is not installed')+ expect(status.lastError).toContain('REMOTE_NOT_INSTALLED')})it('clears the dshMissing marker on disconnect', async () => {const session = new FakeSession(index => index !== 0)- session.dshProbeResult = ''+ session.startNotInstalled = trueconst { manager } = boot({ sessionFactory: () => session })- await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-dsh-missing' })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })await manager.disconnect(MachineId('m1'))expect(manager.status(MachineId('m1')).dshMissing).toBeUndefined()})@@ -607,54 +672,70 @@ describe('sshManager install', () => {}it('installs dsh end-to-end, copies credentials, and auto-connects', async () => {- // Session 1 = install (installer, dsh probe, credentials copy); session 2- // = the automatic connect (port probe refused, dsh probe, start, healthy).+ // Session 1 = install (platform probe, missing check, install script,+ // entry check, credentials copy); session 2 = the automatic connect+ // (root probe refused, platform probe, missing check, launch, healthy).let sessions = 0const factory = () => {sessions += 1- return new FakeSession(index => sessions === 2 && index === 3)+ const session = new FakeSession(index => sessions === 2 && index >= 4)+ if (sessions === 1)+ session.missingResult = 'node\ndsh\npnpm\n'+ return session}const { manager, transport } = boot({sessionFactory: factory,readEnvCredentials: () => ({ apiKey: 'sk-test', baseUrl: 'https://api.example.com' }),})const result = await manager.install(MachineId('m1'))- expect(result).toEqual({ dshPath: RESOLVED_DSH, credentialsCopied: true })+ expect(result).toEqual({+ installed: ['node', 'dsh', 'pnpm'],+ dshRef: 'dsh-0.1.2-rc.1-33729514615',+ dshVersion: '0.1.2-rc.1',+ dshPath: ENTRY,+ credentialsCopied: true,+ })const installSession = transport.sessions[0]!- expect(installSession.commands[0]).toContain('git clone')- expect(installSession.commands[0]).toContain('pnpm run build')- expect(installSession.commands[1]).toContain('command -v dsh')- expect(installSession.commands[2]).toContain('DEEPSEEK_API_KEY')- expect(installSession.options[0]!.timeoutMs).toBe(60000)- expect(typeof installSession.options[0]!.onData).toBe('function')+ expect(installSession.commands[0]).toBe('uname -srm')+ expect(installSession.commands[1]).toContain('echo node')+ expect(installSession.commands[2]).toContain('https://nodejs.org/dist/')+ expect(installSession.commands[3]).toContain('test -f')+ expect(installSession.commands[4]).toContain('DEEPSEEK_API_KEY')+ expect(installSession.options[2]!.timeoutMs).toBe(60000)+ expect(typeof installSession.options[2]!.onData).toBe('function')await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-connect')expect(transport.connectCalls).toBe(2)})it('publishes the installing phase with the streaming install log', async () => {const session = new FakeSession(() => false)+ session.missingResult = 'node\n'const { manager } = boot({ sessionFactory: () => session })const pending = manager.install(MachineId('m1'))expect(manager.status(MachineId('m1')).progress).toEqual({ phase: 'installing' })- // Wait until the install command is in flight, then feed the streaming tap.- await until(() => session.commands.length >= 1, 'install exec')- session.options[0]?.onData?.('==> Checking dependencies\n')- session.options[0]?.onData?.('git ... ok')+ // Wait until the install script is in flight, then feed the streaming tap.+ await until(() => session.commands.some(command => command.includes('trap cleanup EXIT')), 'install exec')+ const installIndex = session.commands.findIndex(command => command.includes('trap cleanup EXIT'))+ session.options[installIndex]?.onData?.('==> downloading node\n')+ session.options[installIndex]?.onData?.('::dsh verify ok')expect(manager.status(MachineId('m1')).progress).toEqual({phase: 'installing',- log: '==> Checking dependencies\ngit ... ok',+ log: '==> downloading node\n::dsh verify ok',})await pending})it('dedupes concurrent installs onto one attempt', async () => {- const { manager, transport } = boot({ readEnvCredentials: () => ({ apiKey: 'sk-test' }) })+ const session = new FakeSession(() => false)+ session.missingResult = 'node\n'+ const { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })const [a, b] = await Promise.all([manager.install(MachineId('m1')), manager.install(MachineId('m1'))])expect(a).toEqual(b)- // One install exec (the auto-connect session is separate).- const installRuns = transport.sessions+ // One install exec (the auto-connect reuses the same session instance,+ // so dedupe the transport's session list before counting commands).+ const installRuns = [...new Set(transport.sessions)].flatMap(session => session.commands)- .filter(command => command.includes('git clone'))+ .filter(command => command.includes('trap cleanup EXIT'))expect(installRuns).toHaveLength(1)})@@ -678,7 +759,7 @@ describe('sshManager install', () => {const session = new FakeSession(() => false)session.exec = (command, _options) => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')? Promise.resolve({ code: 1, stdout: '', stderr: 'disk full' })- : Promise.resolve({ code: 0, stdout: 'installed', stderr: '' })+ : Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? 'ok\n' : 'installed', stderr: '' })const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })const result = await manager.install(MachineId('m1'))expect(result.credentialsCopied).toBe(false)@@ -687,8 +768,9 @@ describe('sshManager install', () => {it('fails loud with machine-install-failed when the install command fails', async () => {const session = new FakeSession(() => false)+ session.missingResult = 'node\n'const original = session.exec.bind(session)- session.exec = (command, options) => command.includes('git clone')+ session.exec = (command, options) => command.includes('trap cleanup EXIT')? Promise.resolve({ code: 1, stdout: '', stderr: 'pnpm: not found' }): original(command, options)const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })@@ -704,20 +786,23 @@ describe('sshManager install', () => {it('carries the installer output tail in a failed-install error', async () => {const session = new FakeSession(() => false)+ session.missingResult = 'node\n'const original = session.exec.bind(session)session.exec = (command, options) => {- if (command.includes('git clone')) {+ if (command.includes('echo node'))+ return Promise.resolve({ code: 0, stdout: 'node\n', stderr: '' })+ if (command.includes('trap cleanup EXIT')) {// The transport streams installer output before failing.- options?.onData?.('==> cloning dsh source\n')- options?.onData?.('fatal: repository not found')- return Promise.resolve({ code: 1, stdout: '', stderr: 'clone failed' })+ options?.onData?.('==> downloading node\n')+ options?.onData?.('fatal: checksum mismatch')+ return Promise.resolve({ code: 11, stdout: '', stderr: 'verify failed' })}return original(command, options)}const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({code: 'machine-install-failed',- message: /installer output tail: ==> cloning dsh source \| fatal: repository not found/,+ message: /installer output tail: ==> downloading node \| fatal: checksum mismatch/,})})@@ -731,14 +816,16 @@ describe('sshManager install', () => {it('runs without an install timeout when the config omits it', async () => {const session = new FakeSession(() => false)+ session.missingResult = 'node\n'const { manager } = boot({sessionFactory: () => session,config: { ...config, installTimeoutMs: undefined as unknown as number },readEnvCredentials: () => ({ apiKey: 'sk-test' }),})await manager.install(MachineId('m1'))- expect(session.options[0]!.timeoutMs).toBeUndefined()- expect(typeof session.options[0]!.onData).toBe('function')+ const installIndex = session.commands.findIndex(command => command.includes('trap cleanup EXIT'))+ expect(session.options[installIndex]!.timeoutMs).toBeUndefined()+ expect(typeof session.options[installIndex]!.onData).toBe('function')})it('falls back to the local harness .env when no credentials reader is injected', async () => {@@ -747,7 +834,7 @@ describe('sshManager install', () => {// No readEnvCredentials injection: the manager reads the host's own// $DSH_HOME/.env — whatever it holds, the install still completes.const result = await manager.install(MachineId('m1'))- expect(result.dshPath).toBe(RESOLVED_DSH)+ expect(result.dshPath).toBe(ENTRY)expect(result.credentialsError).toBeUndefined()})@@ -787,7 +874,7 @@ describe('sshManager install', () => {// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection// eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers describeExecFailure's message tail? Promise.reject('disk full')- : Promise.resolve({ code: 0, stdout: 'installed', stderr: '' })+ : Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? 'ok\n' : 'installed', stderr: '' })const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })const result = await manager.install(MachineId('m1'))expect(result.credentialsCopied).toBe(false)@@ -800,12 +887,13 @@ describe('sshManager install', () => {releaseInstall = resolve})const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))- session.execGate = command => command.includes('git clone') ? installGate : undefined+ session.missingResult = 'node\n'+ session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefinedconst { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })const pending = manager.install(MachineId('m1'))await new Promise<void>((resolve) => {const timer = setInterval(() => {- if (session.commands.some(command => command.includes('git clone'))) {+ if (session.commands.some(command => command.includes('trap cleanup EXIT'))) {clearInterval(timer)resolve()}@@ -813,18 +901,24 @@ describe('sshManager install', () => {})await manager.disconnect(MachineId('m1'))releaseInstall!()- await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed', message: 'dsh install failed' })+ await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed', message: /dsh install failed/ })expect(manager.status(MachineId('m1')).lastError).toBeUndefined()expect(manager.status(MachineId('m1')).progress).toBeUndefined()})- it('fails loud when the install finished but no dsh binary is reachable', async () => {+ it('fails loud when the install finished but the entry is not present', async () => {const session = new FakeSession(() => false)- session.dshProbeResult = ''+ session.exec = (command, _options) => {+ if (command.includes('echo node'))+ return Promise.resolve({ code: 0, stdout: 'node\n', stderr: '' })+ if (command.includes('trap cleanup EXIT'))+ return Promise.resolve({ code: 0, stdout: '::dsh install 远端初始化完成', stderr: '' })+ return Promise.resolve({ code: 0, stdout: '', stderr: '' })+ }const { manager } = boot({ sessionFactory: () => session })await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({- code: 'machine-install-failed',- message: /no dsh binary is reachable/,+ code: 'machine-dsh-missing',+ message: /entry .* is not present/,})})@@ -832,20 +926,21 @@ describe('sshManager install', () => {let sessions = 0const factory = () => {sessions += 1- const session = new FakeSession(index => sessions >= 2 && index === 3)- // The first (failed) connect sees no dsh; the install and auto-connect do.+ const session = new FakeSession(index => sessions >= 2 && index >= 4)+ // The first (failed) connect finds the runtime incomplete; the install+ // and the auto-connect see it whole.if (sessions === 1)- session.dshProbeResult = ''+ session.startNotInstalled = truereturn session}const { manager, transport } = boot({sessionFactory: factory,readEnvCredentials: () => ({ apiKey: 'sk-test' }),})- await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-dsh-missing' })+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })expect(manager.status(MachineId('m1')).dshMissing).toBe(true)const result = await manager.install(MachineId('m1'))- expect(result.dshPath).toBe(RESOLVED_DSH)+ expect(result.dshPath).toBe('$HOME/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js')expect(manager.status(MachineId('m1')).dshMissing).toBeUndefined()await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-connect after install')// First (failed) connect + install + auto-connect.@@ -858,20 +953,22 @@ describe('sshManager install', () => {releaseInstall = resolve})const session = new FakeSession(() => false)- session.execGate = command => command.includes('git clone') ? installGate : undefined+ session.missingResult = 'node\n'+ session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefinedconst { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })const pending = manager.install(MachineId('m1'))- await new Promise<void>((resolve) => {+ const installIndex = await new Promise<number>((resolve) => {const timer = setInterval(() => {- if (session.commands.some(command => command.includes('git clone'))) {+ const index = session.commands.findIndex(command => command.includes('trap cleanup EXIT'))+ if (index >= 0) {clearInterval(timer)- resolve()+ resolve(index)}}, 1)})await manager.disconnect(MachineId('m1'))// Output arriving after the supersede must not touch the published log.- session.options[0]?.onData?.('stale output')+ session.options[installIndex]?.onData?.('stale output')expect(manager.status(MachineId('m1')).progress).toBeUndefined()releaseInstall!()await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed', message: /cancelled by disconnect/ })@@ -910,6 +1007,7 @@ describe('sshManager install', () => {it('swallows a close failure during a failed install', async () => {const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))+ session.missingResult = 'node\n'session.closeError = new Error('close refused')const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })@@ -936,11 +1034,16 @@ describe('sshManager install', () => {it('reports a non-Error install failure in the status', async () => {const session = new FakeSession(() => false)- session.exec = (command, _options) => command.includes('git clone')- // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection- // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers install failure normalization- ? Promise.reject('pnpm blew up')- : Promise.resolve({ code: 0, stdout: '', stderr: '' })+ session.missingResult = 'node\n'+ session.exec = (command, _options) => {+ if (command.includes('echo node'))+ return Promise.resolve({ code: 0, stdout: 'node\n', stderr: '' })+ if (command.includes('trap cleanup EXIT'))+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection+ // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers install failure normalization+ return Promise.reject('pnpm blew up')+ return Promise.resolve({ code: 0, stdout: '', stderr: '' })+ }const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })expect(manager.status(MachineId('m1')).lastError).toBe('pnpm blew up')diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.tsindex 3cd68920..a36bc41d 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts@@ -8,14 +8,15 @@ import type { Config } from '../storage/index.js'* @module dsh-tauri-ssh/host/service/manager*/-import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshTestResult } from '../types/index.js'+import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStage, SshMachineStatus, SshProgress, SshTestResult } from '../types/index.js'+import type { SshMachineEvents } from './events.js'import type { KnownHostsStore } from './host-keys.js'import type { SshSession, SshTransport, SshTunnelHandle } from './transport.js'import { homedir } from 'node:os'import process from 'node:process'import { join } from 'pathe'import { SshError } from '../types/index.js'-import { credentialsCopyCommand, describeExecFailure, DshMissingError, ensureRemoteInstance, firstLineOf, installCommandFor, probeDshCommand, readEnvCredentials } from './bootstrap.js'+import { buildInstallScript, checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, parseBootstrapLine, planRemoteInstall, readEnvCredentials, REMOTE_ROOT } from './bootstrap.js'import { fingerprintHostKey } from './host-keys.js'/** One machine's live connection state. */@@ -49,6 +50,10 @@ export interface SshManagerDeps {transport: SshTransportknownHosts: KnownHostsStoreconfig: Config+ /** The machine event channel (C-EVENT): bootstrap log/progress events. */+ events: SshMachineEvents+ /** The install-plan resolver (overridable so tests never touch the network). */+ planInstall?: (unameOut: string, config: Pick<Config, 'installRepo' | 'installRef'>) => Promise<import('./bootstrap.js').RemoteInstallPlan>/** Publish one machine's status change (the service emits the seam event). */emitStatus: (machineId: MachineId, status: SshMachineStatus) => void/** Local dsh `.env` credentials to copy after an install (defaults to the host's own). */@@ -84,8 +89,10 @@ export class SshManager {this.profiles.clear()for (const [id, profile] of profiles) this.profiles.set(id, profile)for (const id of this.states.keys()) {- if (!this.profiles.has(id))+ if (!this.profiles.has(id)) {+ this.deps.events.forget(id)void this.disconnect(id)+ }}}@@ -276,15 +283,24 @@ export class SshManager {await ensureRemoteInstance(session,profile,- this.deps.config.healthCheckTimeoutMs,- this.deps.config.healthPollIntervalMs,- this.deps.config.healthPollAttempts,- (progress) => {- if (generation === state.generation) {- state.progress = progress- this.emit(machineId)- }+ {+ config: this.deps.config,+ healthCheckTimeoutMs: this.deps.config.healthCheckTimeoutMs,+ healthPollIntervalMs: this.deps.config.healthPollIntervalMs,+ healthPollAttempts: this.deps.config.healthPollAttempts,},+ {+ onProgress: (progress) => {+ if (generation === state.generation) {+ state.progress = progress+ this.emit(machineId)+ }+ },+ onEvent: (stage, line, options) => {+ this.deps.events.append(machineId, stage, line, options)+ },+ },+ this.deps.planInstall,)const tunnel = await session.openTunnel(profile.remotePort)// A disconnect that landed anywhere above (bootstrap, tunnel opening)@@ -325,25 +341,25 @@ export class SshManager {}if (generation === state.generation) {delete state.progress- state.lastError = error instanceof Error ? error.message : String(error)- if (error instanceof DshMissingError)+ const message = error instanceof Error ? error.message : String(error)+ state.lastError = message+ // The start script's own "not installed" verdict keeps the UI's+ // install hint alive (the auto-bootstrap could not complete).+ if (message.includes('REMOTE_NOT_INSTALLED'))state.dshMissing = truestate.phase = 'disconnected'this.emit(machineId)}- throw new SshError(- error instanceof DshMissingError ? 'machine-dsh-missing' : 'machine-bootstrap-failed',- machineId,- state.lastError ?? 'remote instance bootstrap failed',- )+ throw new SshError('machine-bootstrap-failed', machineId, state.lastError ?? 'remote instance bootstrap failed')}}/**- * One-shot remote dsh install: authenticate, stream the official installer- * (clone + pnpm install + build), resolve the installed binary, copy the- * local API credentials into the remote `~/.dsh/.env`, then hand off to- * {@link connect} automatically. Idempotent while in flight.+ * One-shot remote dsh install (binary distribution): authenticate, probe+ * the platform, download/verify/install the missing runtime components+ * from the pinned release, copy the local API credentials into the remote+ * `~/.dsh/.env`, then hand off to {@link connect} automatically.+ * Idempotent while in flight.* @param machineId - the machine to install on.* @param signal - aborts the attempt.* @returns the install outcome.@@ -373,6 +389,7 @@ export class SshManager {private async performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {const state = this.ensureState(machineId)const generation = state.generation+ const events = this.deps.eventslet session: SshSessiontry {session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)@@ -388,33 +405,54 @@ export class SshManager {}try {const installTimeoutMs = this.deps.config.installTimeoutMs- const result = await session.exec(installCommandFor(this.deps.config), {- ...installTimeoutMs === undefined ? {} : { timeoutMs: installTimeoutMs },- onData: (chunk) => {- if (generation !== state.generation)- return- state.installLog = [...(state.installLog ?? []), chunk].slice(-40)- state.progress = {- phase: 'installing',- log: state.installLog.join('').slice(-2000),- }- },- })- if (result.code !== 0) {- const log = state.installLog?.join('').trim() ?? ''- const tail = log === '' ? '(no output captured)' : log.split('\n').slice(-5).join(' | ')- throw new Error(- `dsh install failed on "${profile.host}": ${describeExecFailure(result.code, result.stderr)}; `- + `installer output tail: ${tail}`,- )+ events.append(machineId, 'probe', '探测远端平台 (uname -srm)')+ const uname = await session.exec('uname -srm')+ if (uname.code !== 0) {+ throw new Error(`cannot probe remote platform: ${describeExecFailure(uname.code, uname.stderr)}`)}- if (generation !== state.generation)- throw new AttemptCancelled()- const dshPath = firstLineOf((await session.exec(probeDshCommand())).stdout)- if (dshPath === '') {- throw new Error(- `dsh install finished on "${profile.host}" but no dsh binary is reachable `- + '(checked the login PATH, ~/.local/bin and ~/.dsh/source/current)',+ const plan = await (this.deps.planInstall ?? planRemoteInstall)(uname.stdout, this.deps.config)+ events.append(machineId, 'probe', `远端平台 ${plan.os}/${plan.arch},安装源 ${plan.repo}${plan.dsh.kind === 'pkg-zip' ? ` tag ${plan.dsh.tag}` : ` npm ${plan.dsh.version}`}`)+ for (const note of plan.notes)+ events.append(machineId, 'probe', note)+ const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)+ if (missing.length > 0) {+ events.append(machineId, 'probe', `缺失组件: ${missing.join(', ')}`)+ let log = ''+ const result = await session.exec(buildInstallScript(plan), {+ ...installTimeoutMs === undefined ? {} : { timeoutMs: installTimeoutMs },+ onData: (chunk) => {+ if (generation !== state.generation)+ return+ log = `${log}${chunk}`.slice(-2000)+ for (const line of chunk.split('\n').filter(line => line !== '')) {+ const parsed = parseBootstrapLine(line)+ events.append(machineId, parsed.stage as SshMachineStage, parsed.line)+ }+ state.progress = { phase: 'installing', log }+ this.emit(machineId)+ },+ })+ if (result.code !== 0) {+ const tail = log.trim() === '' ? '(no output captured)' : log.trim().split('\n').slice(-5).join(' | ')+ events.append(machineId, 'failed', 'install failed', { terminal: 'failed', reason: tail })+ throw new Error(+ `dsh install failed on "${profile.host}": ${describeExecFailure(result.code, result.stderr)}; installer output tail: ${tail}`,+ )+ }+ if (generation !== state.generation)+ throw new AttemptCancelled()+ }+ else {+ events.append(machineId, 'probe', '三件套已就绪,跳过安装')+ }+ const dshPath = `$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan.dshEntry}`+ const entryCheck = await session.exec(`test -f ${dshPath} && printf 'ok\\n'`)+ const dshResolved = firstLineOf(entryCheck.stdout)+ if (dshResolved !== 'ok') {+ throw new SshError(+ 'machine-dsh-missing',+ machineId,+ `dsh install finished on "${profile.host}" but the entry ${dshPath} is not present`,)}let credentialsCopied = false@@ -438,6 +476,9 @@ export class SshManager {void this.connect(machineId).catch(() => undefined)}return {+ installed: missing,+ dshRef: plan.dsh.kind === 'pkg-zip' ? plan.dsh.tag : `npm:${plan.dsh.version}`,+ dshVersion: plan.dshVersion,dshPath,credentialsCopied,...credentialsError === undefined ? {} : { credentialsError },@@ -455,6 +496,8 @@ export class SshManager {state.phase = 'disconnected'this.emit(machineId)}+ if (error instanceof SshError)+ throw errorthrow new SshError('machine-install-failed', machineId, state.lastError ?? 'dsh install failed')}}diff --git a/packages/dsh-tauri-ssh/src/host/service/version.test.ts b/packages/dsh-tauri-ssh/src/host/service/version.test.tsnew file mode 100644index 00000000..32c5f52d--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/version.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest'+import {+ FALLBACK_DSH_TAG,+ isPreviewTag,+ OFFICIAL_INSTALL_REPO,+ OFFICIAL_PKG_REPO,+ parseGitHubRepo,+ parseVersionFromTag,+ pickReleaseTag,+ pkgRepoOf,+ RECOMMENDED_DSH_VERSION,+} from './version.js'++/** A realistic newest-first release list (test tags republishing included). */+const RELEASES = [+ { tag: 'dsh-0.2.0-preview.1-32490000001', prerelease: true },+ { tag: 'dsh-0.1.2-rc.1-33729514615', prerelease: false },+ { tag: 'dsh-0.1.1-rc.1-32342588166', prerelease: false },+ { tag: 'dsh-0.1.0-rc.8-32331963388', prerelease: false },+ { tag: 'dsh-0.1.0-rc.8-32342588167', prerelease: false },+ { tag: 'dsh-0.1.0-beta.1-32490000002', prerelease: false },+]++describe('parseVersionFromTag', () => {+ it('extracts the semver from build-id tags', () => {+ expect(parseVersionFromTag('dsh-0.1.2-rc.1-33729514615')).toBe('0.1.2-rc.1')+ expect(parseVersionFromTag('dsh-0.1.0-rc.8-32342588167')).toBe('0.1.0-rc.8')+ // Bare dsh-prefixed tags always lose their last dash segment (the build-id+ // convention) — matching the retired Rust parser exactly.+ expect(parseVersionFromTag('dsh-0.1.2-rc.1')).toBe('0.1.2')+ })++ it('handles src tags and rejects tags without a version', () => {+ expect(parseVersionFromTag('dsh-src-0.1.2-alpha.1-33260039971')).toBe('0.1.2-alpha.1')+ expect(parseVersionFromTag('src-0.1.2-alpha.1')).toBe('0.1.2-alpha.1')+ expect(parseVersionFromTag('v99')).toBeUndefined()+ expect(parseVersionFromTag('')).toBeUndefined()+ })+})++describe('isPreviewTag', () => {+ it('flags non-rc pre-release markers only', () => {+ expect(isPreviewTag('dsh-0.2.0-preview.1-1')).toBe(true)+ expect(isPreviewTag('dsh-0.1.0-beta.1-2')).toBe(true)+ expect(isPreviewTag('dsh-0.1.2-rc.1-33729514615')).toBe(false)+ expect(isPreviewTag('dsh-0.1.2-33729514615')).toBe(false)+ expect(isPreviewTag('not-a-tag')).toBe(false)+ })+})++describe('pickReleaseTag', () => {+ it('resolves the recommended version onto its release tag (recommended path)', () => {+ const resolved = pickReleaseTag(RELEASES)+ expect(resolved).toMatchObject({ tag: 'dsh-0.1.2-rc.1-33729514615', version: RECOMMENDED_DSH_VERSION, source: 'recommended' })+ expect(resolved.notes).toEqual([])+ })++ it('dedupes republished versions keeping the last-listed tag', () => {+ const resolved = pickReleaseTag(RELEASES, { recommended: '0.1.0-rc.8' })+ expect(resolved.tag).toBe('dsh-0.1.0-rc.8-32342588167')+ })++ it('honors an explicit tag pin, listed or not', () => {+ expect(pickReleaseTag(RELEASES, { ref: 'dsh-0.1.1-rc.1-32342588166' })).toMatchObject({+ tag: 'dsh-0.1.1-rc.1-32342588166',+ source: 'pin',+ })+ const unlisted = pickReleaseTag(RELEASES, { ref: 'dsh-0.1.1-rc.2-999' })+ expect(unlisted.source).toBe('pin')+ expect(unlisted.notes[0]).toContain('不在 release 列表')+ })++ it('honors an explicit version pin', () => {+ expect(pickReleaseTag(RELEASES, { ref: '0.1.1-rc.1' })).toMatchObject({+ tag: 'dsh-0.1.1-rc.1-32342588166',+ version: '0.1.1-rc.1',+ source: 'pin',+ })+ })++ it('falls back to the newest stable release when the recommended version is absent', () => {+ const resolved = pickReleaseTag(RELEASES, { recommended: '0.3.0' })+ expect(resolved.source).toBe('latest-stable')+ expect(resolved.tag).toBe('dsh-0.1.2-rc.1-33729514615')+ expect(resolved.notes[0]).toContain('回退最新稳定')+ })++ it('skips preview releases in the stable fallback', () => {+ const previewTop = [+ { tag: 'dsh-0.2.0-preview.1-1', prerelease: true },+ { tag: 'dsh-0.1.2-rc.1-33729514615', prerelease: false },+ ]+ expect(pickReleaseTag(previewTop, { recommended: '0.9.9' }).tag).toBe('dsh-0.1.2-rc.1-33729514615')+ })++ it('falls back to the known stable tag when the release list is unavailable', () => {+ const resolved = pickReleaseTag(undefined)+ expect(resolved).toMatchObject({ tag: FALLBACK_DSH_TAG, source: 'fallback' })+ expect(resolved.notes[0]).toContain('回退已知稳定 tag')+ })++ it('falls back when the list is empty or everything is a preview', () => {+ expect(pickReleaseTag([]).source).toBe('fallback')+ expect(pickReleaseTag([{ tag: 'dsh-0.2.0-preview.1-1', prerelease: true }]).source).toBe('fallback')+ })++ it('notes an unresolvable version pin before falling back', () => {+ const resolved = pickReleaseTag(RELEASES, { ref: '9.9.9' })+ expect(resolved.source).toBe('recommended')+ expect(resolved.notes[0]).toContain('回退推荐/最新稳定版')+ })+})++describe('install source repository mapping', () => {+ it('anchors the official repository at the verified org', () => {+ expect(OFFICIAL_INSTALL_REPO).toBe('https://github.com/deepseek-ai/deepseek-harness.git')+ expect(pkgRepoOf()).toBe(OFFICIAL_PKG_REPO)+ expect(pkgRepoOf('')).toBe(OFFICIAL_PKG_REPO)+ // The official anchor (and its legacy wrong-org spelling) map onto the packaging repo.+ expect(pkgRepoOf('https://github.com/deepseek-ai/deepseek-harness.git')).toBe(OFFICIAL_PKG_REPO)+ expect(pkgRepoOf('https://github.com/deepseek-harness/deepseek-harness.git')).toBe(OFFICIAL_PKG_REPO)+ })++ it('uses a configured fork or mirror as the release repository directly', () => {+ expect(pkgRepoOf('https://github.com/my-org/deepseek-harness-pkg')).toBe('my-org/deepseek-harness-pkg')+ expect(pkgRepoOf('https://github.com/my-org/deepseek-harness-pkg.git')).toBe('my-org/deepseek-harness-pkg')+ expect(pkgRepoOf('my-org/deepseek-harness-pkg')).toBe('my-org/deepseek-harness-pkg')+ })++ it('rejects unparseable repository strings onto the official source', () => {+ expect(pkgRepoOf('not a repo at all')).toBe(OFFICIAL_PKG_REPO)+ })++ it('parses GitHub URLs and bare owner/name pairs', () => {+ expect(parseGitHubRepo('https://github.com/a/b')).toBe('a/b')+ expect(parseGitHubRepo('http://github.com/a/b.git/')).toBe('a/b')+ expect(parseGitHubRepo('[email protected]:a/b')).toBeUndefined()+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/version.ts b/packages/dsh-tauri-ssh/src/host/service/version.tsnew file mode 100644index 00000000..4cc5aa8f--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/version.ts@@ -0,0 +1,263 @@+/**+ * DSH version selection and download-metadata pinning, ported from the+ * retired Rust engine's semantics (`service/download/github.rs` ++ * `config/version_recommend.rs`): never "latest 直下" — resolve the+ * recommended version onto a concrete release tag, pin that tag's asset URL+ * and trusted digest, and on resolution failure fall back to a known stable+ * tag while reporting why. Also owns the install-source repository mapping+ * (`installRepo` config → the GitHub repository hosting the packaged+ * releases).+ * @module dsh-tauri-ssh/host/service/version+ */++/** One packaged release as the GitHub API lists it. */+export interface DshPkgReleaseMeta {+ tag: string+ /** GitHub's Pre-release label for the tag. */+ prerelease: boolean+}++/** How a release tag was chosen. */+export type DshTagSource = 'pin' | 'recommended' | 'latest-stable' | 'fallback'++/** The outcome of release-tag resolution. */+export interface ResolvedDshTag {+ tag: string+ /** The parsed semver (empty when the tag carries none). */+ version: string+ source: DshTagSource+ /** Human-readable notes for every departure from the primary choice. */+ notes: string[]+}++/**+ * The recommended DSH version. Mirrors the desktop mainline's+ * `version-recommend.json` intent: installs pin this version instead of+ * following whatever "latest" happens to be.+ */+export const RECOMMENDED_DSH_VERSION = '0.1.2-rc.1'++/**+ * The last known-good packaged release tag, used when version resolution+ * fails (offline, rate-limited, or the recommended version vanished). A+ * concrete tag — never an unknown version.+ */+export const FALLBACK_DSH_TAG = 'dsh-0.1.2-rc.1-33729514615'++/** The official DSH project repository (org verified on GitHub). */+export const OFFICIAL_INSTALL_REPO = 'https://github.com/deepseek-ai/deepseek-harness.git'++/** The GitHub repository hosting the packaged DSH binary releases. */+export const OFFICIAL_PKG_REPO = 'dsh-tauri-desk/deepseek-harness-pkg'++/**+ * Map the `installRepo` config onto the GitHub `owner/name` repository whose+ * releases the binary install downloads from. The official anchor (and the+ * legacy wrong-org spelling it replaces) maps onto the official packaging+ * repository; any other configured repository is used as-is, so forks and+ * mirrors of the packaging repo work.+ * @param installRepo - the configured install repository (URL or `owner/name`).+ * @returns the `owner/name` release repository.+ */+export function pkgRepoOf(installRepo?: string): string {+ const configured = installRepo === undefined || installRepo.trim() === '' ? undefined : installRepo.trim()+ if (configured === undefined)+ return OFFICIAL_PKG_REPO+ const parsed = parseGitHubRepo(configured)+ if (parsed === undefined)+ return OFFICIAL_PKG_REPO+ if (parsed === 'deepseek-ai/deepseek-harness' || parsed === 'deepseek-harness/deepseek-harness')+ return OFFICIAL_PKG_REPO+ return parsed+}++/** The `owner/name` of a GitHub repository URL (`.git` suffix tolerated). */+export function parseGitHubRepo(value: string): string | undefined {+ const match = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/u.exec(value)+ if (match === null) {+ // A bare `owner/name` is accepted for local mirrors expressed concisely.+ const bare = /^([\w.-]+)\/([\w.-]+)$/u.exec(value)+ return bare === null ? undefined : `${bare[1]}/${bare[2]}`+ }+ return `${match[1] ?? ''}/${match[2] ?? ''}`+}++/**+ * Parse the DSH semver out of a packaged release tag: `dsh-0.1.2-rc.1-<build>`+ * (the trailing build id is dropped), `dsh-src-0.1.2-alpha.1-<build>`, and+ * bare `dsh-0.1.2-rc.1` all yield the version.+ * @param tag - the release tag.+ * @returns the version string, or undefined when the tag carries none.+ */+export function parseVersionFromTag(tag: string): string | undefined {+ const hasDshPrefix = tag.startsWith('dsh-')+ const stripped = hasDshPrefix ? tag.slice('dsh-'.length) : tag+ if (stripped.startsWith('src-')) {+ const rest = stripped.slice('src-'.length)+ // `dsh-src-<version>-<build>`: drop the build id; bare `src-<version>`: as-is.+ const version = hasDshPrefix ? rest.split('-').slice(0, -1).join('-') : rest+ return version === '' ? undefined : version+ }+ if (!hasDshPrefix)+ return undefined+ const version = stripped.split('-').slice(0, -1).join('-')+ return version === '' ? undefined : version+}++/** Pre-release markers that make a tag a preview (rc does not — rc ships). */+const PREVIEW_MARKERS = ['preview', 'beta', 'alpha', 'canary', 'next'] as const++/**+ * Whether a tag is a preview release (its version's pre-release segment+ * carries a non-rc preview marker). Preview releases never win the+ * "latest stable" fallback.+ * @param tag - the release tag.+ */+export function isPreviewTag(tag: string): boolean {+ const version = parseVersionFromTag(tag)+ if (version === undefined)+ return false+ const pre = version.split('-').slice(1).join('-')+ if (pre === '')+ return false+ return pre.split('.').some(id => PREVIEW_MARKERS.some(marker => id.startsWith(marker)))+}++/**+ * Resolve the install tag from the release list (pure — the network fetch is+ * injected). Resolution order: the configured pin (`ref`, a tag or version),+ * the {@link RECOMMENDED_DSH_VERSION} match, the newest stable release, and+ * finally the {@link FALLBACK_DSH_TAG} constant when no list was available.+ * Every departure from the primary choice carries a human-readable note.+ * @param metas - the packaged release list (newest first), or undefined when+ * the listing itself failed.+ * @param options - the pin (`ref`) and the recommended version override.+ * @param options.ref - the configured pin: a full release tag or a semver.+ * @param options.recommended - the recommended version (defaults to the constant).+ * @returns the resolved tag, its version, the resolution source, and notes.+ */+export function pickReleaseTag(+ metas: DshPkgReleaseMeta[] | undefined,+ options: { ref?: string | undefined, recommended?: string | undefined } = {},+): ResolvedDshTag {+ const recommended = options.recommended ?? RECOMMENDED_DSH_VERSION+ const notes: string[] = []+ const ref = options.ref === undefined || options.ref.trim() === '' ? undefined : options.ref.trim()+ if (ref !== undefined) {+ if (ref.startsWith('dsh-')) {+ const listed = metas?.some(meta => meta.tag === ref) ?? false+ if (!listed)+ notes.push(`pin tag ${ref} 不在 release 列表中(列表截断或来源异常),按 pin 直用`)+ const version = parseVersionFromTag(ref) ?? ''+ return { tag: ref, version, source: 'pin', notes }+ }+ const pinned = metas?.find(meta => parseVersionFromTag(meta.tag) === ref)+ if (pinned !== undefined)+ return { tag: pinned.tag, version: ref, source: 'pin', notes }+ notes.push(`版本 pin ${ref} 未找到匹配 release,回退推荐/最新稳定版`)+ }+ if (metas === undefined || metas.length === 0) {+ notes.push('release 列表不可用(网络/限流),回退已知稳定 tag')+ return { tag: FALLBACK_DSH_TAG, version: parseVersionFromTag(FALLBACK_DSH_TAG) ?? '', source: 'fallback', notes }+ }+ // Dedupe by version keeping the last tag (the packager republishes the+ // same version under test tags; the newest listing wins).+ const byVersion = new Map<string, DshPkgReleaseMeta>()+ for (const meta of metas) {+ const version = parseVersionFromTag(meta.tag)+ if (version === undefined)+ continue+ byVersion.set(version, meta)+ }+ const recommendedMeta = byVersion.get(recommended)+ if (recommendedMeta !== undefined)+ return { tag: recommendedMeta.tag, version: recommended, source: 'recommended', notes }+ const fallback = metas.find(meta => !meta.prerelease && !isPreviewTag(meta.tag))+ if (fallback === undefined) {+ notes.push('推荐版本不在 release 列表且无稳定 release,回退已知稳定 tag')+ return { tag: FALLBACK_DSH_TAG, version: parseVersionFromTag(FALLBACK_DSH_TAG) ?? '', source: 'fallback', notes }+ }+ notes.push(`推荐版本 ${recommended} 不在 release 列表,回退最新稳定 ${fallback.tag}`)+ return { tag: fallback.tag, version: parseVersionFromTag(fallback.tag) ?? '', source: 'latest-stable', notes }+}++/** One packaged release asset as GitHub reports it. */+export interface GithubAsset {+ name: string+ url: string+ /** Trusted digest (`sha256:<hex>`), when GitHub computed one. */+ digest?: string+}++/** Fetch JSON with a deadline; a non-2xx fails with the status. */+async function fetchJson(url: string, headers: Record<string, string>, timeoutMs: number): Promise<unknown> {+ const response = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) })+ if (!response.ok)+ throw new Error(`GET ${url} → HTTP ${response.status}`)+ return await response.json() as unknown+}++/** List the packaged releases (newest first) from the GitHub API. */+export async function listGithubReleases(repo: string, timeoutMs = 15_000): Promise<DshPkgReleaseMeta[]> {+ const json = await fetchJson(+ `https://api.github.com/repos/${repo}/releases?per_page=100`,+ { 'accept': 'application/vnd.github+json', 'user-agent': 'dsh-tauri-ssh' },+ timeoutMs,+ )+ if (!Array.isArray(json))+ throw new Error(`unexpected releases payload from ${repo}`)+ return json+ .filter((entry): entry is { tag_name: string, draft: boolean, prerelease: boolean } =>+ typeof entry === 'object' && entry !== null && typeof (entry as { tag_name?: unknown }).tag_name === 'string')+ .filter(entry => !entry.draft)+ .map(entry => ({ tag: entry.tag_name, prerelease: entry.prerelease }))+}++/** Fetch one tag's release assets from the GitHub API. */+export async function listGithubAssets(repo: string, tag: string, timeoutMs = 15_000): Promise<GithubAsset[]> {+ const json = await fetchJson(+ `https://api.github.com/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`,+ { 'accept': 'application/vnd.github+json', 'user-agent': 'dsh-tauri-ssh' },+ timeoutMs,+ )+ const assets = (json as { assets?: unknown }).assets+ if (!Array.isArray(assets))+ throw new Error(`unexpected release payload for ${tag}`)+ return assets+ .filter((asset): asset is { name: string, browser_download_url: string, digest?: unknown } =>+ typeof asset === 'object' && asset !== null && typeof (asset as { name?: unknown }).name === 'string')+ .map(asset => ({+ name: asset.name,+ url: asset.browser_download_url,+ ...typeof asset.digest === 'string' ? { digest: asset.digest } : {},+ }))+}++/**+ * Resolve the `npm-tgz` DSH asset metadata for one version from the npm+ * registry (official → npmmirror fallback): the deterministic tarball URL+ * pair and the packument's trusted integrity digest.+ * @param packageName - the scoped package name (`@deepseek-ai/dsh`).+ * @param version - the resolved version.+ * @param timeoutMs - per-request deadline.+ * @returns the tarball URL (official), its mirror, and the `sha512` integrity.+ */+export async function npmDistMetadata(+ packageName: string,+ version: string,+ timeoutMs = 15_000,+): Promise<{ url: string, mirrorUrl: string, integrity?: string }> {+ const headers = { accept: 'application/json' }+ const packument = await fetchJson(`https://registry.npmjs.org/${packageName}`, headers, timeoutMs)+ .catch(() => fetchJson(`https://registry.npmmirror.com/${packageName}`, headers, timeoutMs))+ const dist = (packument as { versions?: Record<string, { dist?: { tarball?: unknown, integrity?: unknown } }> })+ ?.versions?.[version]+ ?.dist+ if (dist === undefined || typeof dist.tarball !== 'string')+ throw new Error(`npm registry carries no ${packageName}@${version}`)+ return {+ url: dist.tarball,+ mirrorUrl: dist.tarball.replace('https://registry.npmjs.org/', 'https://registry.npmmirror.com/'),+ ...typeof dist.integrity === 'string' ? { integrity: dist.integrity } : {},+ }+}diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.tsindex 45c03aae..8bd21c12 100644--- a/packages/dsh-tauri-ssh/src/host/storage/index.ts+++ b/packages/dsh-tauri-ssh/src/host/storage/index.ts@@ -85,13 +85,19 @@ export interface Config {*/startCommand?: string/**- * Git repository URL the one-click install clones from. Defaults to the- * official GitHub repository; set your own fork, an internal mirror, or a- * private repository (a credential-bearing URL works). The clone happens on- * the remote machine, so the remote must be able to reach and read it.+ * The DSH install-source repository anchor. Defaults to the official DSH+ * repository (org verified: `deepseek-ai`); the binary install resolves its+ * download repository from it — the official anchor maps onto the official+ * packaging repository (`dsh-tauri-desk/deepseek-harness-pkg`), and any+ * other configured `owner/name` or GitHub URL is used directly as the+ * release repository, so forks/mirrors of the packaging repo keep working.*/installRepo?: string- /** Git ref (branch/tag) the one-click install checks out; defaults to the repository's default branch. */+ /**+ * DSH version pin for the binary install: a semver (`0.1.2-rc.1`) or a full+ * release tag (`dsh-0.1.2-rc.1-33729514615`). Defaults to the recommended+ * version; unresolvable pins fall back to the latest stable release.+ */installRef?: string/** Deadline for one remote dsh install (clone + pnpm install + build). */installTimeoutMs?: numberdiff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.tsindex cf3da833..51021666 100644--- a/packages/dsh-tauri-ssh/src/host/types/index.ts+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts@@ -137,9 +137,57 @@ export type SshTestResult= | { ok: true, banner: string }| { ok: false, message: string }+/** One bootstrap stage of the remote-instance assurance pipeline (S3 adds the connection-lifecycle stages on the same channel). */+export type SshMachineStage+ = | 'probe'+ | 'download'+ | 'verify'+ | 'install'+ | 'launch'+ | 'ready'+ | 'failed'++/** Terminal verdict of a machine event, when it settles an operation. */+export type SshMachineTerminal = 'success' | 'failed'++/**+ * One machine-scoped event of the `/api-ssh` `machine.events` channel: a+ * displayable log line tagged with its pipeline stage. `seq` is per-machine+ * and monotonically increasing; consumers poll with the last seen seq.+ */+export interface SshMachineEvent {+ /** Per-machine sequence number, starting at 1. */+ seq: number+ /** Wall-clock timestamp of the event (ISO-8601). */+ ts: string+ /** The machine the event is about. */+ machineId: MachineId+ /** The pipeline stage the line belongs to. */+ stage: SshMachineStage+ /** The displayable log line. */+ line: string+ /** Terminal verdict, present only on the settling event of an operation. */+ terminal?: SshMachineTerminal+ /** Failure reason, present on `terminal: 'failed'` events. */+ reason?: string+}++/** The `machine.events` response: the drained slice plus the poll cursor. */+export interface SshMachineEventsPage {+ events: SshMachineEvent[]+ /** The next event's seq; poll again with `sinceSeq = nextSeq - 1`. */+ nextSeq: number+}+/** Outcome of a one-shot remote dsh install. */export interface SshInstallResult {- /** Absolute path of the installed `dsh` binary as the remote sees it. */+ /** Components freshly installed this run (a subset of node/dsh/pnpm). */+ installed: string[]+ /** The pinned DSH release actually installed (`<tag>` or `npm:<version>`). */+ dshRef: string+ /** The resolved DSH semver. */+ dshVersion: string+ /** Absolute path of the installed `dsh` entry as the remote sees it. */dshPath: string/** Whether the local DEEPSEEK_API_KEY was copied to the remote `~/.dsh/.env`. */credentialsCopied: booleandiff --git a/packages/dsh-tauri-ssh/src/index.ts b/packages/dsh-tauri-ssh/src/index.tsindex ffb8f13d..939087fc 100644--- a/packages/dsh-tauri-ssh/src/index.ts+++ b/packages/dsh-tauri-ssh/src/index.ts@@ -17,4 +17,5 @@*/export { apply, Config, default, inject, name, SshRemoteService } from './host/apply.js'+export type { SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal } from './host/types/index.js'export { SSH_API_PREFIX } from './shared/constants.js'