Skip to content

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

fix(ssh): reviewer round 2 — terminal events on failure paths, wget readiness fallback, unified install executor, merge credentials

Menghuan19187e1f205bb4f4
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
index b83d5102..23e86077 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
@@ -4,7 +4,7 @@ import type { SshExecOptions, SshExecResult, SshSession } from './transport.js'
import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { promisify } from 'node:util'
import { join } from 'pathe'
@@ -19,11 +19,13 @@ import {
describeExecFailure,
ensureRemoteInstance,
firstLineOf,
+ legacyProbeCommand,
missingComponentsOf,
normalizeNpmIntegrity,
parseBootstrapLine,
planRemoteInstall,
readEnvCredentials,
+ REMOTE_PROBE_NO_DOWNLOADER,
REMOTE_ROOT,
rootProbeCommand,
skippedVerificationSummary,
@@ -561,10 +563,17 @@ describe('component probe and launch commands', () => {
})
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('builds the root probe and the bundle probe with the wget fallback', () => {
+ expect(rootProbeCommand(3080, 2500)).toBe(
+ 'if [ -n "$(command -v curl)" ]; then curl -s -m 3 http://127.0.0.1:3080/; '
+ + 'elif [ -n "$(command -v wget)" ]; then wget -q -T 3 -O - http://127.0.0.1:3080/; case $? in 0|6|8) ;; *) exit 1 ;; esac; '
+ + 'else echo "REMOTE_PROBE_NO_DOWNLOADER: 远端缺少 curl 与 wget,无法探测就绪状态" >&2; exit 1; fi',
+ )
+ expect(bundleProbeCommand('http://127.0.0.1:3080/plugins/x/client.js', 2500)).toBe(
+ 'if [ -n "$(command -v curl)" ]; then curl -s -m 3 -w \'\\n%{http_code}\' \'http://127.0.0.1:3080/plugins/x/client.js\'; '
+ + 'elif [ -n "$(command -v wget)" ]; then wget -q -T 3 -O - \'http://127.0.0.1:3080/plugins/x/client.js\' && printf \'\\n200\\n\' || printf \'\\n0\\n\'; '
+ + 'else echo "REMOTE_PROBE_NO_DOWNLOADER: 远端缺少 curl 与 wget,无法探测就绪状态" >&2; exit 1; fi',
+ )
})
it('splits a bundle probe answer into body and status', () => {
@@ -575,6 +584,104 @@ describe('health probes', () => {
})
})
+describe('probe execution (real POSIX sh)', () => {
+ /**
+ * Run one generated probe under the real `sh` with a curated tool PATH:
+ * the downloader selection must actually work, not just look right.
+ */
+ function runProbe(command: string, sandbox: string, tools: Record<string, string>): Promise<{ code: number, stdout: string, stderr: string }> {
+ const binDir = join(sandbox, 'bin')
+ mkdirSync(binDir, { recursive: true })
+ for (const [name, body] of Object.entries(tools)) {
+ writeFileSync(join(binDir, name), body)
+ chmodSync(join(binDir, name), 0o755)
+ }
+ const scriptPath = join(sandbox, 'probe.sh')
+ writeFileSync(scriptPath, command)
+ // /bin/sh by absolute path: PATH holds only the sandbox bin dir, so
+ // `command -v` sees exactly the fakes this case installs (the probe
+ // itself needs nothing but shell builtins besides the downloader).
+ const run = promisify(execFile)
+ return run('/bin/sh', [scriptPath], { env: { ...process.env, HOME: sandbox, PATH: binDir } }).then(
+ ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),
+ (error: { code?: number, stdout?: string, stderr?: string }) =>
+ ({ code: error.code ?? -1, stdout: error.stdout ?? '', stderr: error.stderr ?? '' }),
+ )
+ }
+
+ // The fake curl serves a fixed body and honors `-w` (expanded to the
+ // emulated status) like the real one, so the bundle probe parses cleanly.
+ const CURL = [
+ '#!/bin/sh',
+ 'printf \'curl-body\'',
+ 'prev=""',
+ 'for arg in "$@"; do',
+ ' if [ "$prev" = "-w" ]; then printf \'\\n200\\n\'; fi',
+ ' prev="$arg"',
+ 'done',
+ ].join('\n')
+ const WGET = '#!/bin/sh\nprintf \'wget-body\'\n'
+ // Real GNU wget semantics (verified live on GNU Wget 1.21.2): a 401 auth
+ // challenge exits 6, a 404/5xx server error exits 8, a connection-level
+ // failure (refused/timeout) exits 4.
+ const WGET_AUTH_CHALLENGE = '#!/bin/sh\nexit 6\n'
+ const WGET_SERVER_ERROR = '#!/bin/sh\nexit 8\n'
+ const WGET_REFUSED = '#!/bin/sh\nexit 4\n'
+
+ it('root probe answers from curl and falls back to wget when curl is absent', async () => {
+ const withCurl = await runProbe(rootProbeCommand(3080, 2500), tempDir(), { curl: CURL, wget: WGET })
+ expect(withCurl).toMatchObject({ code: 0, stdout: 'curl-body' })
+ const withWgetOnly = await runProbe(rootProbeCommand(3080, 2500), tempDir(), { wget: WGET })
+ expect(withWgetOnly).toMatchObject({ code: 0, stdout: 'wget-body' })
+ })
+
+ it('root probe counts wget server answers (401→6, 404→8) as answered, a refused connection as not ready', async () => {
+ // curl exits 0 on any HTTP response; wget answers with 6/8 there. The
+ // probe must normalize, or an auth-fence instance never becomes ready
+ // on wget-only remotes (verified live against a real 401 instance).
+ for (const fake of [WGET_AUTH_CHALLENGE, WGET_SERVER_ERROR]) {
+ const answered = await runProbe(rootProbeCommand(3080, 2500), tempDir(), { wget: fake })
+ expect(answered.code).toBe(0)
+ expect(answered.stdout).toBe('')
+ }
+ const refused = await runProbe(rootProbeCommand(3080, 2500), tempDir(), { wget: WGET_REFUSED })
+ expect(refused.code).not.toBe(0)
+ })
+
+ it('root probe fails loud with the marker when neither downloader exists', async () => {
+ const neither = await runProbe(rootProbeCommand(3080, 2500), tempDir(), {})
+ expect(neither.code).not.toBe(0)
+ expect(neither.stderr).toContain('REMOTE_PROBE_NO_DOWNLOADER')
+ })
+
+ it('bundle probe appends the real status under curl and synthesizes 200/0 under wget', async () => {
+ const url = 'http://127.0.0.1:3080/plugins/x/client.js'
+ const withCurl = await runProbe(bundleProbeCommand(url, 2500), tempDir(), { curl: CURL })
+ expect(withCurl.code).toBe(0)
+ expect(splitBundleProbeStdout(withCurl.stdout)).toEqual({ body: 'curl-body', status: 200 })
+ const withWget = await runProbe(bundleProbeCommand(url, 2500), tempDir(), { wget: WGET })
+ expect(withWget.code).toBe(0)
+ expect(splitBundleProbeStdout(withWget.stdout)).toEqual({ body: 'wget-body', status: 200 })
+ // Server answers (6/8) and connection failures (4) all report status 0
+ // — never a healthy manifest.
+ for (const fake of [WGET_AUTH_CHALLENGE, WGET_SERVER_ERROR, WGET_REFUSED]) {
+ const failing = await runProbe(bundleProbeCommand(url, 2500), tempDir(), { wget: fake })
+ expect(splitBundleProbeStdout(failing.stdout)).toEqual({ body: '', status: 0 })
+ }
+ })
+
+ it('legacy verdict probe: wget 6/8 answer 4xx/5xx, exit 4 is no answer', async () => {
+ for (const fake of [WGET_AUTH_CHALLENGE, WGET_SERVER_ERROR]) {
+ const answered = await runProbe(legacyProbeCommand(3080, 2500), tempDir(), { wget: fake })
+ expect(answered).toMatchObject({ code: 0, stdout: '4xx/5xx\n' })
+ }
+ const refused = await runProbe(legacyProbeCommand(3080, 2500), tempDir(), { wget: WGET_REFUSED })
+ expect(refused.code).not.toBe(0)
+ const healthy = await runProbe(legacyProbeCommand(3080, 2500), tempDir(), { wget: '#!/bin/sh\nexit 0\n' })
+ expect(healthy).toMatchObject({ code: 0, stdout: '200\n' })
+ })
+})
+
describe('credentials', () => {
it('reads the DEEPSEEK keys from a dsh .env document', () => {
const dir = tempDir()
@@ -605,6 +712,73 @@ describe('credentials', () => {
expect(command).toContain('echo copied')
expect(command).toContain('echo existing')
expect(command).toContain('umask 077')
+ // The write merges: only the keys being written are filtered out of an
+ // existing document, and it lands through the temp file + mv.
+ expect(command).toContain(`grep -v -E '^DEEPSEEK_API_KEY=|^DEEPSEEK_BASE_URL='`)
+ expect(command).toContain('"$HOME/.dsh/.env.new"')
+ expect(command).toContain('mv -f "$HOME/.dsh/.env.new" "$HOME/.dsh/.env"')
+ })
+})
+
+describe('credentials copy execution (real POSIX sh)', () => {
+ /** Run one generated command under the real `sh` inside a sandboxed HOME. */
+ function runCommand(command: string, sandbox: string): Promise<{ code: number, stdout: string, stderr: string }> {
+ const scriptPath = join(sandbox, 'cmd.sh')
+ writeFileSync(scriptPath, command)
+ const run = promisify(execFile)
+ return run('sh', [scriptPath], { env: { ...process.env, HOME: sandbox } }).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('merges into an existing remote .env, keeping unrelated variables and replacing managed keys', async () => {
+ const sandbox = tempDir()
+ mkdirSync(join(sandbox, '.dsh'), { recursive: true })
+ writeFileSync(join(sandbox, '.dsh', '.env'), 'OTHER_TOOL=1\nDEEPSEEK_BASE_URL=https://remote.example.com\n')
+ const outcome = await runCommand(credentialsCopyCommand({ apiKey: 'sk-new', baseUrl: 'https://local.example.com' }), sandbox)
+ expect(outcome.code).toBe(0)
+ expect(outcome.stdout.trim()).toBe('copied')
+ const env = readFileSync(join(sandbox, '.dsh', '.env'), 'utf8')
+ expect(env).toContain('OTHER_TOOL=1')
+ expect(env).toContain('DEEPSEEK_API_KEY=sk-new')
+ expect(env).toContain('DEEPSEEK_BASE_URL=https://local.example.com')
+ expect(env).not.toContain('remote.example.com')
+ // umask 077 → the merged document stays owner-only; no temp file leaks.
+ expect(statSync(join(sandbox, '.dsh', '.env')).mode & 0o777).toBe(0o600)
+ expect(existsSync(join(sandbox, '.dsh', '.env.new'))).toBe(false)
+ })
+
+ it('keeps a remote-set DEEPSEEK_BASE_URL when the local env carries none', async () => {
+ const sandbox = tempDir()
+ mkdirSync(join(sandbox, '.dsh'), { recursive: true })
+ writeFileSync(join(sandbox, '.dsh', '.env'), 'DEEPSEEK_BASE_URL=https://remote.example.com\nOTHER=2\n')
+ const outcome = await runCommand(credentialsCopyCommand({ apiKey: 'sk-new' }), sandbox)
+ expect(outcome.code).toBe(0)
+ const env = readFileSync(join(sandbox, '.dsh', '.env'), 'utf8')
+ expect(env).toContain('DEEPSEEK_API_KEY=sk-new')
+ expect(env).toContain('DEEPSEEK_BASE_URL=https://remote.example.com')
+ expect(env).toContain('OTHER=2')
+ })
+
+ it('creates the document from nothing when the remote has no .env yet', async () => {
+ const sandbox = tempDir()
+ const outcome = await runCommand(credentialsCopyCommand({ apiKey: 'sk-fresh' }), sandbox)
+ expect(outcome.code).toBe(0)
+ expect(outcome.stdout.trim()).toBe('copied')
+ expect(readFileSync(join(sandbox, '.dsh', '.env'), 'utf8')).toBe('DEEPSEEK_API_KEY=sk-fresh\n')
+ })
+
+ it('reports existing and leaves the document untouched when the remote already has a key', async () => {
+ const sandbox = tempDir()
+ mkdirSync(join(sandbox, '.dsh'), { recursive: true })
+ const before = 'DEEPSEEK_API_KEY=sk-remote\nOTHER=7\n'
+ writeFileSync(join(sandbox, '.dsh', '.env'), before)
+ const outcome = await runCommand(credentialsCopyCommand({ apiKey: 'sk-new' }), sandbox)
+ expect(outcome.code).toBe(0)
+ expect(outcome.stdout.trim()).toBe('existing')
+ expect(readFileSync(join(sandbox, '.dsh', '.env'), 'utf8')).toBe(before)
})
})
@@ -782,6 +956,37 @@ describe('ensureRemoteInstance', () => {
expect(failures[0]?.terminal).toBe('failed')
})
+ it('says the remote has no downloader instead of a misleading not-ready', 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: '', stderr: '' }
+ if (command.includes('dsh-remote.pid'))
+ return { code: 0, stdout: '远端实例已拉起', stderr: '' }
+ if (command.includes('tail'))
+ return { code: 0, stdout: 'instance log line\n', stderr: '' }
+ if (command.includes('/dev/null'))
+ // The legacy verdict probe: this remote has neither curl nor wget,
+ // so its else-arm prints the marker on stdout.
+ return { code: 0, stdout: REMOTE_PROBE_NO_DOWNLOADER, stderr: '' }
+ // The root/bundle probes fail (their else-arm exits 1) — not ready.
+ return { code: 1, stdout: '', stderr: '' }
+ })
+ const failures: string[] = []
+ await expect(ensureRemoteInstance(session, profile, {
+ ...BOOTSTRAP,
+ healthPollAttempts: 1,
+ }, {
+ onEvent: (_stage, _line, options) => {
+ if (options?.terminal === 'failed')
+ failures.push(options.reason ?? '')
+ },
+ }, plannerOf(plan))).rejects.toThrow(/no downloader/)
+ expect(failures[0]).toContain('REMOTE_PROBE_NO_DOWNLOADER')
+ })
+
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) => {
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
index a375bfc7..62600bc1 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
@@ -559,20 +559,26 @@ export function readEnvCredentials(path: string): EnvCredentials {
}
/**
- * Write credentials into the remote `~/.dsh/.env` without clobbering an
- * existing key: print `copied` when the write happened, `existing` when the
- * remote already carries a key (kept untouched).
+ * Write credentials into the remote `~/.dsh/.env`: print `copied` when the
+ * write happened, `existing` when the remote already carries a key (kept
+ * untouched). The write merges instead of replacing — only the keys being
+ * written are filtered out of an existing document, so remote-set variables
+ * (including a remote `DEEPSEEK_BASE_URL` when the local env carries none)
+ * survive — and it lands through a temp file + `mv`, so a failed write can
+ * never truncate the existing document.
* @param credentials - the credentials to write (apiKey required).
* @returns the shell command line.
*/
export function credentialsCopyCommand(credentials: EnvCredentials & { apiKey: string }): string {
- const lines = [`printf 'DEEPSEEK_API_KEY=%s\\n' ${shQuote(credentials.apiKey)}`]
- if (credentials.baseUrl !== undefined) {
- lines.push(`printf 'DEEPSEEK_BASE_URL=%s\\n' ${shQuote(credentials.baseUrl)}`)
- }
+ // Only the keys this write owns are filtered from the existing document.
+ const managed = ['DEEPSEEK_API_KEY', ...(credentials.baseUrl === undefined ? [] : ['DEEPSEEK_BASE_URL'])]
+ const writes = [`printf 'DEEPSEEK_API_KEY=%s\\n' ${shQuote(credentials.apiKey)}`]
+ if (credentials.baseUrl !== undefined)
+ writes.push(`printf 'DEEPSEEK_BASE_URL=%s\\n' ${shQuote(credentials.baseUrl)}`)
+ const filter = managed.map(key => `^${key}=`).join('|')
return [
`mkdir -p "$HOME/.dsh"`,
- `if grep -q '^DEEPSEEK_API_KEY=' "$HOME/.dsh/.env" 2>/dev/null; then echo existing; else umask 077 && { ${lines.join('; ')}; } > "$HOME/.dsh/.env" && echo copied; fi`,
+ `if grep -q '^DEEPSEEK_API_KEY=' "$HOME/.dsh/.env" 2>/dev/null; then echo existing; else umask 077 && { grep -v -E '${filter}' "$HOME/.dsh/.env" 2>/dev/null || true; ${writes.join('; ')}; } > "$HOME/.dsh/.env.new" && mv -f "$HOME/.dsh/.env.new" "$HOME/.dsh/.env" && echo copied; fi`,
].join(' && ')
}
@@ -597,27 +603,63 @@ export function firstLineOf(stdout: string): string {
return ''
}
+/** Marker the readiness probes report when the remote has neither curl nor wget. */
+export const REMOTE_PROBE_NO_DOWNLOADER = 'REMOTE_PROBE_NO_DOWNLOADER'
+
+/**
+ * Wrap one probe's fetch arms with the downloader selection the install
+ * script's `fetch()` uses: curl when present, wget next, and a loud
+ * `REMOTE_PROBE_NO_DOWNLOADER` marker (exit 1) when neither exists — a
+ * wget-only remote must not install fine and then fail readiness forever.
+ * `command -v` runs inside a command substitution so the probes never
+ * contain a `/dev/null` redirect (the legacy verdict probe is told apart
+ * by exactly that token).
+ * @param curlArm - the curl invocation.
+ * @param wgetArm - the wget invocation.
+ */
+function withDownloaderFallback(curlArm: string, wgetArm: string): string {
+ return [
+ `if [ -n "$(command -v curl)" ]; then ${curlArm}`,
+ `elif [ -n "$(command -v wget)" ]; then ${wgetArm}`,
+ `else echo "${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态" >&2; exit 1; fi`,
+ ].join('; ')
+}
+
/**
* 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.
+ * (including 401/404) exits 0 — the body decides; a connection-level
+ * failure exits nonzero. The wget arm normalizes GNU wget's exit codes to
+ * curl's any-response-answers semantics: 6 is an authentication challenge
+ * (the auth fence's 401), 8 a server error status — both are answers
+ * (verified live: GNU Wget 1.21.2 gives 6 on 401, 8 on 404, 4 on refused).
+ * busybox wget collapses every failure to 1 and lands on the not-ready
+ * side of that split.
* @param remotePort - the instance's loopback port.
- * @param timeoutMs - per-probe curl deadline.
+ * @param timeoutMs - per-probe downloader 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}/`
+ return withDownloaderFallback(
+ `curl -s -m ${seconds} http://127.0.0.1:${remotePort}/`,
+ `wget -q -T ${seconds} -O - http://127.0.0.1:${remotePort}/; case $? in 0|6|8) ;; *) exit 1 ;; esac`,
+ )
}
/**
* The client-bundle probe: fetch one boot-manifest URL, printing the body
- * followed by the numeric status code on its last line.
+ * followed by the numeric status code on its last line. wget cannot append
+ * a status line, so its arm synthesizes one: a completed fetch (exit 0) IS
+ * a 2xx answer; anything else — connection failure or a server error
+ * status (exit 8) — reports status 0, which never passes readiness.
* @param url - the absolute loopback URL to fetch.
- * @param timeoutMs - per-probe curl deadline.
+ * @param timeoutMs - per-probe downloader deadline.
*/
export function bundleProbeCommand(url: string, timeoutMs: number): string {
const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
- return `curl -s -m ${seconds} -w '\\n%{http_code}' ${shQuote(url)}`
+ return withDownloaderFallback(
+ `curl -s -m ${seconds} -w '\\n%{http_code}' ${shQuote(url)}`,
+ `wget -q -T ${seconds} -O - ${shQuote(url)} && printf '\\n200\\n' || printf '\\n0\\n'`,
+ )
}
/**
@@ -720,7 +762,7 @@ export async function ensureRemoteInstance(
let skips: string[] = []
if (missing.length > 0) {
onEvent?.('probe', `缺失组件: ${missing.join(', ')}`)
- skips = await runInstallScript(session, plan, bootstrap, hooks)
+ skips = await runInstallScript(session, plan, bootstrap.config.installTimeoutMs, hooks)
}
else {
onEvent?.('probe', '三件套已就绪,跳过安装')
@@ -780,9 +822,31 @@ async function judgeReadiness(session: SshSession, profile: MachineProfile, boot
return undefined
}
+/**
+ * The legacy any-response probe command: the status code on stdout, exit
+ * nonzero only when nothing answered. curl prints the real code; the wget
+ * arm normalizes GNU wget's exit codes — 0 is a 2xx answer, 6/8 are server
+ * answers (auth challenge / error status, code unknown → `4xx/5xx`), and
+ * the rest are connection-level failures. The no-downloader marker rides
+ * stdout so the failure message says why instead of a misleading "no
+ * answer".
+ * @param remotePort - the instance's loopback port.
+ * @param timeoutMs - per-probe downloader deadline.
+ */
+export function legacyProbeCommand(remotePort: number, timeoutMs: number): string {
+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
+ return [
+ `if [ -n "$(command -v curl)" ]; then curl -s -o /dev/null -m ${seconds} -w '%{http_code}' http://127.0.0.1:${remotePort}/`,
+ `elif [ -n "$(command -v wget)" ]; then wget -q -T ${seconds} -O /dev/null http://127.0.0.1:${remotePort}/; case $? in 0) echo 200 ;; 6|8) echo 4xx/5xx ;; *) exit 1 ;; esac`,
+ `else echo ${REMOTE_PROBE_NO_DOWNLOADER}; fi`,
+ ].join('; ')
+}
+
/** 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}/`)
+ const probe = await session.exec(legacyProbeCommand(profile.remotePort, bootstrap.healthCheckTimeoutMs))
+ if (probe.stdout.includes(REMOTE_PROBE_NO_DOWNLOADER))
+ return `no downloader (${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态)`
return probe.code === 0 ? `root answered ${probe.stdout.trim() || '?'}` : 'no answer'
}
@@ -790,10 +854,25 @@ async function legacyRootVerdict(session: SshSession, profile: MachineProfile, b
* Run the generated install script, streaming its stage-tagged output
* line-buffered (SSH chunks may split mid-line). Returns the verify-stage
* lines that recorded a skipped check, for the settling event's summary.
+ * The single install executor for both the connect-time bootstrap and the
+ * manager's install operation — the caller injects its event adapter
+ * through {@link BootstrapHooks.onEvent}, so the two flows can never drift.
+ * @param session - the authenticated session.
+ * @param plan - the resolved install plan.
+ * @param installTimeoutMs - the install exec deadline, when configured.
+ * @param hooks - progress and event reporting.
+ * @param failureLine - the settling failure event's display line.
+ * @returns the verify-stage lines that recorded a skipped check.
+ * @throws {Error} with the output tail when the script exits nonzero.
*/
-async function runInstallScript(session: SshSession, plan: RemoteInstallPlan, bootstrap: BootstrapConfig, hooks: BootstrapHooks): Promise<string[]> {
+export async function runInstallScript(
+ session: SshSession,
+ plan: RemoteInstallPlan,
+ installTimeoutMs: number | undefined,
+ hooks: BootstrapHooks,
+ failureLine = 'bootstrap 失败',
+): Promise<string[]> {
const { onEvent, onProgress } = hooks
- const installTimeoutMs = bootstrap.config.installTimeoutMs
let log = ''
const skips: string[] = []
const dispatch = createBootstrapLineDispatcher((line) => {
@@ -813,10 +892,13 @@ async function runInstallScript(session: SshSession, plan: RemoteInstallPlan, bo
dispatch.flush()
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()
+ // without the tap still surface the markers through the collected
+ // stdout, and a totally silent failure keeps its exit stderr.
+ const streamed = log.trim()
+ const collected = streamed !== '' ? streamed : result.stdout.trim()
+ const stream = collected !== '' ? collected : result.stderr.trim()
const tail = stream === '' ? '(no output captured)' : stream.split('\n').slice(-5).join(' | ')
- failBootstrap(onEvent, `install failed on remote (exit ${result.code ?? '?'}): ${tail}`)
+ failBootstrap(onEvent, `install failed on remote (exit ${result.code ?? '?'}): ${tail}`, failureLine)
}
return skips
}
@@ -837,9 +919,15 @@ function emitReady(
onEvent?.('ready', `${base}${skipSummary}`, { terminal: 'success' })
}
-/** Record the terminal failure and build the thrown error. */
-function failBootstrap(onEvent: BootstrapHooks['onEvent'], reason: string): never {
- onEvent?.('failed', 'bootstrap 失败', { terminal: 'failed', reason })
+/**
+ * Record the terminal failure and build the thrown error.
+ * @param onEvent - the event hook receiving the settling event.
+ * @param reason - the operator-facing failure reason.
+ * @param line - the settling event's display line (the install operation
+ * passes its own wording; the default matches the connect-time bootstrap).
+ */
+function failBootstrap(onEvent: BootstrapHooks['onEvent'], reason: string, line = 'bootstrap 失败'): never {
+ onEvent?.('failed', line, { terminal: 'failed', reason })
throw new Error(reason)
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
index 6915504d..a8fcae19 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,4 @@
-import type { MachineProfile } from '../types/index.js'
+import type { MachineProfile, SshMachineEvent } from '../types/index.js'
import type { RemoteInstallPlan } from './bootstrap.js'
import type { SshExecOptions, SshExecResult, SshSession, SshTransport, SshTunnelHandle } from './transport.js'
import { Buffer } from 'node:buffer'
@@ -227,6 +227,7 @@ function boot(overrides: Partial<{
rejectKeys: boolean
readEnvCredentials: () => { apiKey?: string, baseUrl?: string }
config: typeof config
+ planInstall: () => Promise<RemoteInstallPlan>
}> = {}) {
const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))
transport.rejectKeys = overrides.rejectKeys ?? false
@@ -238,7 +239,7 @@ function boot(overrides: Partial<{
knownHosts: tempKnownHosts(),
config: overrides.config ?? config,
events,
- planInstall: () => Promise.resolve(plan),
+ planInstall: overrides.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 } })
@@ -248,6 +249,11 @@ function boot(overrides: Partial<{
return { manager, transport, emits, events }
}
+/** The terminal (settling) events one machine's channel recorded. */
+function terminalsOf(events: SshMachineEvents): SshMachineEvent[] {
+ return events.since(MachineId('m1')).events.filter(event => event.terminal !== undefined)
+}
+
describe('sshManager', () => {
it('lists redacted profile views in settings order', () => {
const { manager } = boot()
@@ -384,6 +390,27 @@ describe('sshManager', () => {
await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
})
+ it('settles the bootstrap stream when a transport exception bypasses the bootstrap failure path', async () => {
+ const session = new FakeSession(() => false)
+ session.exec = () => Promise.reject(new Error('channel reset during probe'))
+ const { manager, events } = boot({ sessionFactory: () => session })
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'failed', terminal: 'failed', line: 'bootstrap 失败' })
+ expect(terminals[0]?.reason).toContain('channel reset')
+ })
+
+ it('never double-settles a bootstrap failure the bootstrap itself already recorded', async () => {
+ const { manager, events } = boot({ sessionFactory: () => new FakeSession(() => false) })
+ // The never-ready path settles through its own terminal event; the
+ // manager's catch must not append a second one.
+ await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]?.reason).toContain('did not become ready')
+ })
+
it('rejects unknown machine ids with machine-not-found', async () => {
const { manager, transport } = boot()
await expect(manager.connect(MachineId('ghost'))).rejects.toMatchObject({ code: 'machine-not-found' })
@@ -441,13 +468,18 @@ describe('sshManager', () => {
markProbeStarted?.()
return gate.then(() => ({ code: 0, stdout: '200', stderr: '' }))
}
- const { manager } = boot({ sessionFactory: () => session })
+ const { manager, events } = boot({ sessionFactory: () => session })
const pending = manager.connect(MachineId('m1'))
await probeStarted
await manager.disconnect(MachineId('m1'))
releaseProbe!()
await expect(pending).rejects.toMatchObject({ code: 'machine-connect-failed', message: /cancelled by disconnect/ })
expect(manager.status(MachineId('m1')).state).toBe('disconnected')
+ // The bootstrap itself had settled ready (its own success terminal);
+ // the cancelled connect adds no failure terminal afterwards.
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'ready', terminal: 'success' })
})
it('cancels an in-flight connect that disconnects during tunnel opening', async () => {
@@ -806,15 +838,25 @@ describe('sshManager install', () => {
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' }) })
- await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({
- code: 'machine-install-failed',
- message: /pnpm: not found/,
- })
+ const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ // Capture the rejection: toMatchObject silently ignores message regexes,
+ // so the message is asserted on the caught error directly.
+ const failure = await manager.install(MachineId('m1')).then(
+ () => { throw new Error('expected a rejection') },
+ error => error as SshError,
+ )
+ expect(failure.code).toBe('machine-install-failed')
+ // No streaming tap answered, so the failure keeps the exit stderr.
+ expect(failure.message).toMatch(/install failed on remote \(exit 1\): pnpm: not found/)
const status = manager.status(MachineId('m1'))
expect(status.state).toBe('disconnected')
expect(status.progress).toBeUndefined()
expect(session.closed).toBe(true)
+ // The script's own failure settles the stream exactly once.
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'failed', terminal: 'failed', line: 'install 失败' })
+ expect(terminals[0]?.reason).toContain('pnpm: not found')
})
it('carries the installer output tail in a failed-install error', async () => {
@@ -832,11 +874,84 @@ describe('sshManager install', () => {
}
return original(command, options)
}
+ const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const failure = await manager.install(MachineId('m1')).then(
+ () => { throw new Error('expected a rejection') },
+ error => error as SshError,
+ )
+ expect(failure.code).toBe('machine-install-failed')
+ // The streamed log wins over the collected stdout/stderr.
+ expect(failure.message).toMatch(/install failed on remote \(exit 11\): ==> downloading node \| fatal: checksum mismatch/)
+ expect(terminalsOf(events)).toHaveLength(1)
+ })
+
+ it('keeps the collected stdout tail when the transport has no streaming tap', async () => {
+ const session = new FakeSession(() => false)
+ session.missingResult = 'node\n'
+ const original = session.exec.bind(session)
+ session.exec = (command, _options) => command.includes('trap cleanup EXIT')
+ // A tap-less transport: markers only in the collected stdout.
+ ? Promise.resolve({ code: 10, stdout: '::dsh failed 所有下载源均失败: node.tar.gz', stderr: '' })
+ : original(command, undefined)
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: ==> downloading node \| fatal: checksum mismatch/,
+ const failure = await manager.install(MachineId('m1')).then(
+ () => { throw new Error('expected a rejection') },
+ error => error as SshError,
+ )
+ expect(failure.message).toMatch(/install failed on remote \(exit 10\): .*所有下载源均失败/)
+ })
+
+ it('settles the install stream when the platform probe fails', async () => {
+ const session = new FakeSession(() => false)
+ const original = session.exec.bind(session)
+ session.exec = (command, options) => command === 'uname -srm'
+ ? Promise.resolve({ code: 1, stdout: '', stderr: 'denied' })
+ : original(command, options)
+ const { manager, events } = boot({ sessionFactory: () => session })
+ const failure = await manager.install(MachineId('m1')).then(
+ () => { throw new Error('expected a rejection') },
+ error => error as SshError,
+ )
+ expect(failure.code).toBe('machine-install-failed')
+ expect(failure.message).toContain('cannot probe remote platform')
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'failed', terminal: 'failed' })
+ expect(terminals[0]?.reason).toContain('cannot probe remote platform')
+ })
+
+ it('settles the install stream when the planner rejects the platform', async () => {
+ const session = new FakeSession(() => false)
+ const { manager, events } = boot({
+ sessionFactory: () => session,
+ planInstall: () => Promise.reject(new Error('REMOTE_PLATFORM_UNSUPPORTED: mingw/x64 outside the asset matrix')),
})
+ await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]?.reason).toContain('REMOTE_PLATFORM_UNSUPPORTED')
+ })
+
+ it('settles the install stream when the install exec rejects (transport timeout)', async () => {
+ const session = new FakeSession(() => false)
+ session.missingResult = 'node\n'
+ const original = session.exec.bind(session)
+ session.exec = (command, options) => command.includes('trap cleanup EXIT')
+ ? Promise.reject(new Error('install exec timed out after 60000ms'))
+ : original(command, options)
+ const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const failure = await manager.install(MachineId('m1')).then(
+ () => { throw new Error('expected a rejection') },
+ error => error as SshError,
+ )
+ expect(failure.code).toBe('machine-install-failed')
+ expect(failure.message).toContain('timed out')
+ // The timeout bypasses the script's own settling path — the catch must
+ // close the stream so S4 sees the install as failed, not still running.
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'failed', terminal: 'failed', line: 'install 失败' })
+ expect(terminals[0]?.reason).toContain('timed out')
})
it('fails loud with machine-connect-failed when the install connection fails', async () => {
@@ -922,7 +1037,7 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))
session.missingResult = 'node\n'
session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
const pending = manager.install(MachineId('m1'))
await new Promise<void>((resolve) => {
const timer = setInterval(() => {
@@ -934,9 +1049,17 @@ describe('sshManager install', () => {
})
await manager.disconnect(MachineId('m1'))
releaseInstall!()
- await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed', message: /dsh install failed/ })
+ const failure = await pending.then(
+ () => { throw new Error('expected a rejection') },
+ error => error as SshError,
+ )
+ expect(failure.code).toBe('machine-install-failed')
+ expect(failure.message).toMatch(/install failed on remote/)
expect(manager.status(MachineId('m1')).lastError).toBeUndefined()
expect(manager.status(MachineId('m1')).progress).toBeUndefined()
+ // The script's own settling event fired inside the shared executor
+ // before the supersede was noticed; the catch must not add a second.
+ expect(terminalsOf(events)).toHaveLength(1)
})
it('fails loud when the install finished but the entry is not present', async () => {
@@ -951,11 +1074,16 @@ describe('sshManager install', () => {
return Promise.resolve({ code: 1, stdout: '', stderr: '' })
return Promise.resolve({ code: 0, stdout: '', stderr: '' })
}
- const { manager } = boot({ sessionFactory: () => session })
+ const { manager, events } = boot({ sessionFactory: () => session })
await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({
code: 'machine-dsh-missing',
message: /entry .* is not present/,
})
+ // The exception path (SshError, not a script exit) settles the stream too.
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'failed', terminal: 'failed' })
+ expect(terminals[0]?.reason).toContain('is not present')
})
it('clears dshMissing after a successful install and reconnects', async () => {
@@ -991,7 +1119,7 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
- const { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, transport, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
const pending = manager.install(MachineId('m1'))
const installIndex = await new Promise<number>((resolve) => {
const timer = setInterval(() => {
@@ -1011,6 +1139,9 @@ describe('sshManager install', () => {
await new Promise(resolve => setTimeout(resolve, 20))
expect(transport.connectCalls).toBe(1)
expect(manager.status(MachineId('m1')).progress).toBeUndefined()
+ // Cancellation by an explicit disconnect is the documented no-terminal
+ // case: the superseded attempt never publishes, not even a settle.
+ expect(terminalsOf(events)).toHaveLength(0)
})
it('returns the install result without connecting once a disconnect superseded the finish', async () => {
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.ts
index 3aeb1feb..d27fe122 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts
@@ -9,6 +9,7 @@ import type { Config } from '../storage/index.js'
*/
import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshTestResult } from '../types/index.js'
+import type { BootstrapHooks } from './bootstrap.js'
import type { SshMachineEvents } from './events.js'
import type { KnownHostsStore } from './host-keys.js'
import type { SshSession, SshTransport, SshTunnelHandle } from './transport.js'
@@ -16,7 +17,7 @@ import { homedir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
import { SshError } from '../types/index.js'
-import { buildInstallScript, checkMissingCommand, createBootstrapLineDispatcher, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, parseBootstrapLine, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, skippedVerificationSummary } from './bootstrap.js'
+import { checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, runInstallScript, skippedVerificationSummary } from './bootstrap.js'
import { fingerprintHostKey } from './host-keys.js'
/** One machine's live connection state. */
@@ -41,8 +42,6 @@ interface MachineState {
dshMissing?: boolean
/** Live progress of the in-flight operation. */
progress?: SshProgress
- /** Ring buffer of the in-flight install's streaming output (newest last). */
- installLog?: string[]
}
/** Manager dependencies (all transport seams injectable for tests). */
@@ -206,7 +205,6 @@ export class SshManager {
delete state.lastError
delete state.dshMissing
delete state.progress
- delete state.installLog
const tunnel = state.tunnel
const session = state.session
delete state.tunnel
@@ -262,10 +260,25 @@ export class SshManager {
* One full connection attempt. Publishes exactly one terminal transition
* (connected or disconnected) unless a disconnect superseded the attempt —
* a superseded attempt closes its session and throws without publishing.
+ * The bootstrap event stream likewise settles on every failure (its own
+ * settling events, or the catch for transport exceptions that bypass
+ * them), except a superseded attempt: cancellation by an explicit
+ * disconnect is the documented no-terminal case.
*/
private async performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshLink> {
const state = this.ensureState(machineId)
const generation = state.generation
+ // The settling guard: remembers whether this attempt's bootstrap already
+ // settled the event stream (failBootstrap/emitReady fire their own
+ // terminal events), so the catch below settles only the gaps — transport
+ // exceptions such as exec timeouts or a dropped session, which bypass
+ // the bootstrap's own failure reporting.
+ let bootstrapSettled = false
+ const onEvent: NonNullable<BootstrapHooks['onEvent']> = (stage, line, options) => {
+ if (options?.terminal !== undefined)
+ bootstrapSettled = true
+ this.deps.events.append(machineId, stage, line, options)
+ }
let session: SshSession
try {
session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)
@@ -296,9 +309,7 @@ export class SshManager {
this.emit(machineId)
}
},
- onEvent: (stage, line, options) => {
- this.deps.events.append(machineId, stage, line, options)
- },
+ onEvent,
},
this.deps.planInstall,
)
@@ -339,9 +350,14 @@ export class SshManager {
if (error instanceof AttemptCancelled) {
throw new SshError('machine-connect-failed', machineId, 'connection cancelled by disconnect')
}
+ // The locally captured message: a superseded attempt must not read
+ // state.lastError back — that slot may already belong to a newer try.
+ const message = error instanceof Error ? error.message : String(error)
+ if (generation === state.generation && !bootstrapSettled) {
+ onEvent('failed', 'bootstrap 失败', { terminal: 'failed', reason: message })
+ }
if (generation === state.generation) {
delete state.progress
- 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).
@@ -350,7 +366,7 @@ export class SshManager {
state.phase = 'disconnected'
this.emit(machineId)
}
- throw new SshError('machine-bootstrap-failed', machineId, state.lastError ?? 'remote instance bootstrap failed')
+ throw new SshError('machine-bootstrap-failed', machineId, message)
}
}
@@ -385,11 +401,25 @@ export class SshManager {
* One full install attempt. Publishes the terminal transition unless a
* disconnect superseded the attempt; a successful install hands off to
* {@link connect} (fire-and-forget — its outcome lands in the status).
+ * The event stream settles on every failure — the install script's own
+ * terminal event, or the catch for exception failures (probe, planner,
+ * transport rejects, missing entry) that bypass it. A superseded attempt
+ * (cancellation by an explicit disconnect) is the documented no-terminal
+ * case.
*/
private async performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {
const state = this.ensureState(machineId)
const generation = state.generation
const events = this.deps.events
+ // The settling guard mirrors the connect path: the install script's own
+ // failure path (and the success line below) settle the stream exactly
+ // once; the catch below covers the exception failures that bypass them.
+ let settled = false
+ const onEvent: NonNullable<BootstrapHooks['onEvent']> = (stage, line, options) => {
+ if (options?.terminal !== undefined)
+ settled = true
+ events.append(machineId, stage, line, options)
+ }
let session: SshSession
try {
session = await this.deps.transport.connect(profile, key => this.checkHostKey(machineId, key), signal)
@@ -405,50 +435,36 @@ export class SshManager {
}
try {
const installTimeoutMs = this.deps.config.installTimeoutMs
- events.append(machineId, 'probe', '探测远端平台 (uname -srm)')
+ onEvent('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)}`)
}
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}`}`)
+ 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)
- events.append(machineId, 'probe', note)
+ onEvent('probe', note)
const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)
const skips: string[] = []
if (missing.length > 0) {
- events.append(machineId, 'probe', `缺失组件: ${missing.join(', ')}`)
- let log = ''
- const dispatch = createBootstrapLineDispatcher((line) => {
- const parsed = parseBootstrapLine(line)
- if (parsed.stage === 'verify' && parsed.line.includes('跳过'))
- skips.push(parsed.line)
- events.append(machineId, parsed.stage, parsed.line)
- })
- const result = await session.exec(buildInstallScript(plan), {
- ...installTimeoutMs === undefined ? {} : { timeoutMs: installTimeoutMs },
- onData: (chunk) => {
+ onEvent('probe', `缺失组件: ${missing.join(', ')}`)
+ // The single install executor (shared with the connect-time
+ // bootstrap): line-buffered stage streaming, the collected-stdout
+ // fallback for tap-less transports, and its own settling failure.
+ skips.push(...await runInstallScript(session, plan, installTimeoutMs, {
+ onEvent,
+ onProgress: (progress) => {
if (generation !== state.generation)
return
- log = `${log}${chunk}`.slice(-2000)
- dispatch.push(chunk)
- state.progress = { phase: 'installing', log }
+ state.progress = progress
this.emit(machineId)
},
- })
- dispatch.flush()
- 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}`,
- )
- }
+ }, 'install 失败'))
if (generation !== state.generation)
throw new AttemptCancelled()
}
else {
- events.append(machineId, 'probe', '三件套已就绪,跳过安装')
+ onEvent('probe', '三件套已就绪,跳过安装')
}
// The entry check doubles as $HOME expansion: the shell prints the
// absolute path the type contract promises (never a literal `$HOME`).
@@ -475,12 +491,11 @@ export class SshManager {
// that follows: S4 can tell "installed, connect pending" from a failed
// install purely from the channel's terminal event. Skipped
// verifications (fail-open checks) ride the settling line.
- events.append(machineId, 'install', `dsh 安装成功 (${dshRef})${skippedVerificationSummary(plan.notes, skips)}`, { terminal: 'success' })
+ onEvent('install', `dsh 安装成功 (${dshRef})${skippedVerificationSummary(plan.notes, skips)}`, { terminal: 'success' })
await session.close().catch(() => undefined)
if (generation === state.generation) {
delete state.progress
delete state.dshMissing
- delete state.installLog
delete state.lastError
state.phase = 'disconnected'
this.emit(machineId)
@@ -502,16 +517,26 @@ export class SshManager {
if (error instanceof AttemptCancelled) {
throw new SshError('machine-install-failed', machineId, 'install cancelled by disconnect')
}
+ // The locally captured message: a superseded attempt must not read
+ // state.lastError back — that slot may already belong to a newer try.
+ const message = error instanceof Error ? error.message : String(error)
+ // Exception failures (platform probe, planner rejects such as
+ // REMOTE_PLATFORM_UNSUPPORTED, transport exec rejects including the
+ // install timeout, the missing entry) never reach the script's own
+ // settling path: settle the channel here so S4 can tell a failed
+ // install from a still-running one purely from the stream.
+ if (generation === state.generation && !settled) {
+ onEvent('failed', 'install 失败', { terminal: 'failed', reason: message })
+ }
if (generation === state.generation) {
delete state.progress
- delete state.installLog
- state.lastError = error instanceof Error ? error.message : String(error)
+ state.lastError = message
state.phase = 'disconnected'
this.emit(machineId)
}
if (error instanceof SshError)
throw error
- throw new SshError('machine-install-failed', machineId, state.lastError ?? 'dsh install failed')
+ throw new SshError('machine-install-failed', machineId, message)
}
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/version.ts b/packages/dsh-tauri-ssh/src/host/service/version.ts
index 18171edb..186d1716 100644
--- a/packages/dsh-tauri-ssh/src/host/service/version.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/version.ts
@@ -84,8 +84,12 @@ export function parseGitHubRepo(value: string): string | undefined {
/**
* 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.
+ * (the trailing build id is dropped) and `dsh-src-0.1.2-alpha.1-<build>`
+ * yield the version with its prerelease segment intact. A bare dsh-prefixed
+ * tag still loses its last dash segment — the build-id convention applied
+ * unconditionally, matching the retired Rust parser — so bare
+ * `dsh-0.1.2-rc.1` yields `0.1.2` (the `rc.1` segment is dropped); only a
+ * bare `src-<version>` tag passes through as-is.
* @param tag - the release tag.
* @returns the version string, or undefined when the tag carries none.
*/