Skip to content

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

fix(ssh): reviewer round — arm64 install cwd + SRI digest, newest-first dedup, install terminal event, absolute dshPath

Menghuan1918b7f8a8a48c0e
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.ts
index 8e51f10b..bdda85ed 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
@@ -50,9 +50,17 @@ const E2E_CONFIG = {
/** 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`,
+ // No `IFS= read` here: an empty IFS disables word splitting, the whole
+ // pgrep line lands in the pid variable, and the kill silently no-ops
+ // (verified live — the leftover instance survived the old loop). pgrep
+ // without -a prints bare pids; this shell's own pid is skipped so the
+ // cleanup does not kill itself mid-script.
+ `for _pid in $(pgrep -f '\\.dsh-desktop'); do [ "$_pid" = "$$" ] && continue; kill "$_pid" 2>/dev/null || true; done`,
`sleep 1`,
- `pgrep -af '\\.dsh-desktop' || true`,
+ // Escalation pass: anything still alive after SIGTERM gets SIGKILL.
+ `for _pid in $(pgrep -f '\\.dsh-desktop'); do [ "$_pid" = "$$" ] && continue; kill -9 "$_pid" 2>/dev/null || true; done`,
+ `sleep 1`,
+ `pgrep -af '\\.dsh-desktop' | grep -v "^$$ " || true`,
].join('\n')
const profile: MachineProfile = HOST === undefined
@@ -110,7 +118,11 @@ describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', ()
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)'))
+ const remaining = (leftovers?.stdout ?? '(probe failed)').trim()
+ console.log('[e2e] remote cleanup done; remaining layout processes:', JSON.stringify(remaining))
+ // The cleanup must actually leave nothing behind — a leftover instance
+ // would hold the port and fake the next run's readiness.
+ expect(remaining).toBe('')
await session.close().catch(() => undefined)
}
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
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 b24b403b..b83d5102 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
@@ -1,8 +1,10 @@
import type { MachineProfile } from '../types/index.js'
import type { RemoteInstallPlan } from './bootstrap.js'
import type { SshExecOptions, SshExecResult, SshSession } from './transport.js'
+import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createHash } from 'node:crypto'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { promisify } from 'node:util'
import { join } from 'pathe'
@@ -12,16 +14,19 @@ import {
buildInstallScript,
bundleProbeCommand,
checkMissingCommand,
+ createBootstrapLineDispatcher,
credentialsCopyCommand,
describeExecFailure,
ensureRemoteInstance,
firstLineOf,
missingComponentsOf,
+ normalizeNpmIntegrity,
parseBootstrapLine,
planRemoteInstall,
readEnvCredentials,
REMOTE_ROOT,
rootProbeCommand,
+ skippedVerificationSummary,
splitBundleProbeStdout,
startCommandFor,
} from './bootstrap.js'
@@ -116,6 +121,66 @@ describe('parseBootstrapLine', () => {
})
expect(parseBootstrapLine('random tool output')).toEqual({ stage: 'install', line: 'random tool output' })
})
+
+ it('demotes unknown stage words instead of leaking them into the typed channel', () => {
+ expect(parseBootstrapLine('::dsh bogus hello')).toEqual({ stage: 'install', line: '::dsh bogus hello' })
+ expect(parseBootstrapLine('::dsh 123 numbers')).toEqual({ stage: 'install', line: '::dsh 123 numbers' })
+ })
+})
+
+describe('createBootstrapLineDispatcher', () => {
+ it('holds a half-received line back until its newline completes it', () => {
+ const lines: string[] = []
+ const dispatch = createBootstrapLineDispatcher(line => lines.push(line))
+ dispatch.push('::dsh verify 警告: 远端缺少摘要工具,跳过校')
+ expect(lines).toEqual([])
+ dispatch.push('验 node.tar.gz\n::dsh download https://a.test/x')
+ expect(lines).toEqual(['::dsh verify 警告: 远端缺少摘要工具,跳过校验 node.tar.gz'])
+ dispatch.push('\n')
+ expect(lines).toEqual(['::dsh verify 警告: 远端缺少摘要工具,跳过校验 node.tar.gz', '::dsh download https://a.test/x'])
+ })
+
+ it('flushes a trailing unterminated line and drops empty lines', () => {
+ const lines: string[] = []
+ const dispatch = createBootstrapLineDispatcher(line => lines.push(line))
+ dispatch.push('one\n\ntwo\n')
+ dispatch.push('tail without newline')
+ dispatch.flush()
+ dispatch.flush()
+ expect(lines).toEqual(['one', 'two', 'tail without newline'])
+ })
+})
+
+describe('normalizeNpmIntegrity', () => {
+ it('decodes SRI base64 digests into the script-verifiable hex form', () => {
+ expect(normalizeNpmIntegrity('sha512-dQw4w9WgXcQ=')).toBe(`sha512:${Buffer.from('dQw4w9WgXcQ=', 'base64').toString('hex')}`)
+ expect(normalizeNpmIntegrity('sha256-ZXhhZQ==')).toBe(`sha256:${Buffer.from('ZXhhZQ==', 'base64').toString('hex')}`)
+ })
+
+ it('passes colonformed digests through and drops unshaped ones', () => {
+ expect(normalizeNpmIntegrity('sha512:deadbeef')).toBe('sha512:deadbeef')
+ expect(normalizeNpmIntegrity(undefined)).toBeUndefined()
+ expect(normalizeNpmIntegrity('md5-xxxx')).toBeUndefined()
+ expect(normalizeNpmIntegrity('garbage')).toBeUndefined()
+ })
+})
+
+describe('skippedVerificationSummary', () => {
+ it('merges plan notes and streamed skip warnings, deduplicated', () => {
+ expect(skippedVerificationSummary(
+ ['未取得 @deepseek-ai/[email protected] 的完整性摘要,将跳过校验', 'release 列表获取失败(offline)'],
+ ['警告: 未取得可信摘要,跳过校验 dsh.tgz'],
+ )).toBe(';跳过校验项: 未取得 @deepseek-ai/[email protected] 的完整性摘要,将跳过校验;警告: 未取得可信摘要,跳过校验 dsh.tgz')
+ expect(skippedVerificationSummary(
+ ['警告: 远端缺少摘要工具,跳过校验 node.tar.gz'],
+ ['警告: 远端缺少摘要工具,跳过校验 node.tar.gz'],
+ )).toBe(';跳过校验项: 警告: 远端缺少摘要工具,跳过校验 node.tar.gz')
+ })
+
+ it('stays empty when everything was verified', () => {
+ expect(skippedVerificationSummary(['版本选择: pin 直用'], [])).toBe('')
+ expect(skippedVerificationSummary([], [])).toBe('')
+ })
})
describe('planRemoteInstall', () => {
@@ -143,7 +208,8 @@ describe('planRemoteInstall', () => {
'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==')
+ // The SRI digest arrives normalized into the script-verifiable hex form.
+ expect(plan.dsh.integrity).toBe(`sha512:${Buffer.from('ZXhhZQ==', 'base64').toString('hex')}`)
}
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')
@@ -234,13 +300,33 @@ describe('buildInstallScript', () => {
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(`sha512:${Buffer.from('ZXhhZQ==', 'base64').toString('hex')}`)
expect(script).toContain('install --prod --silent --registry')
expect(script).toContain('"$ROOT/dependencies/pnpm/bin/pnpm.cjs"')
expect(script).toContain('https://registry.npmmirror.com')
+ // pnpm must run inside the extracted package (SSH exec starts in $HOME,
+ // where pnpm aborts with ERR_PNPM_NO_PKG_MANIFEST).
+ expect(script).toContain('( cd "$ROOT/dependencies/dsh" && "$ROOT/runtime/bin/node"')
// The tarball path extracts with tar; the zip helper stays uncalled.
expect(script).not.toContain('extract_zip "$TMP/dsh')
})
+
+ it('notes an unparseable installRepo instead of silently installing official', async () => {
+ const plan = await planRemoteInstall('Linux 6.8 x86_64', { installRepo: 'not a repo at all' }, healthyFetchers())
+ expect(plan.repo).toBe(PKG_REPO)
+ expect(plan.notes.join('\n')).toContain('无法解析为 GitHub 仓库')
+ expect(plan.notes.join('\n')).toContain(PKG_REPO)
+ })
+
+ it('dedupes the npm tarball URL pair when the packument already carries the mirror', async () => {
+ const mirrorOnly = 'https://registry.npmmirror.com/@deepseek-ai/dsh/-/dsh-0.1.2-rc.1.tgz'
+ const plan = await planRemoteInstall('Linux 5.15 aarch64', {}, healthyFetchers({
+ npmDist: () => Promise.resolve({ url: mirrorOnly, mirrorUrl: mirrorOnly, integrity: 'sha512-ZXhhZQ==' }),
+ }))
+ if (plan.dsh.kind !== 'npm-tgz')
+ throw new Error('expected npm-tgz')
+ expect(plan.dsh.urls).toEqual([mirrorOnly])
+ })
})
describe('install script execution (real POSIX sh)', () => {
@@ -322,6 +408,123 @@ describe('install script execution (real POSIX sh)', () => {
expect(outcome.stdout).not.toContain('::dsh download')
expect(existsSync(join(root, 'tmp'))).toBe(false)
})
+
+ /**
+ * Run one generated script under the real `sh` inside a sandboxed HOME
+ * whose fake `curl` serves crafted artifacts from `servedDir` by URL
+ * basename. Used for the arm64 npm path, whose node/pnpm/dsh tarballs are
+ * sh shims standing in for the real binaries.
+ */
+ function runScriptServing(script: string, sandbox: string, servedDir: 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',
+ 'if [ -f "$SERVED/$(basename "$url")" ]; then cp "$SERVED/$(basename "$url")" "$dst"; exit 0; fi',
+ 'echo "fake curl: no artifact for $url" >&2',
+ 'exit 22',
+ ].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, SERVED: servedDir, 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 ?? '' }),
+ )
+ }
+
+ /**
+ * arm64 (npm-tgz) execution coverage: the whole script runs under real sh
+ * with crafted tarballs — node is an `exec sh` shim, pnpm.cjs a stand-in
+ * that REFUSES to run without a package.json in cwd (exactly the
+ * ERR_PNPM_NO_PKG_MANIFEST failure the missing `cd` would cause) and
+ * writes a marker into node_modules when it "installs".
+ */
+ it('arm64: pnpm install runs inside the extracted package (real POSIX sh)', async () => {
+ const work = tempDir()
+ const served = join(work, 'served')
+ mkdirSync(served, { recursive: true })
+
+ // node dist: bin/node = a sh shim standing in for the real binary, plus
+ // a second top-level entry so flatten_move sees the real multi-entry
+ // layout (a lone bin/ would flatten one level too many).
+ const nodeDir = join(work, 'node-v22.22.0-linux-arm64')
+ mkdirSync(join(nodeDir, 'bin'), { recursive: true })
+ mkdirSync(join(nodeDir, 'include'), { recursive: true })
+ writeFileSync(join(nodeDir, 'bin', 'node'), '#!/bin/sh\nexec sh "$@"\n')
+ chmodSync(join(nodeDir, 'bin', 'node'), 0o755)
+ writeFileSync(join(nodeDir, 'include', 'node'), 'headers\n')
+ const nodeTgz = join(served, 'node-v22.22.0-linux-arm64.tar.gz')
+ await promisify(execFile)('tar', ['-czf', nodeTgz, '-C', work, 'node-v22.22.0-linux-arm64'])
+
+ // pnpm dist: the cwd-gating stand-in, packed as package/{bin,lib}.
+ const pnpmStage = join(work, 'pnpm-stage')
+ mkdirSync(join(pnpmStage, 'package', 'bin'), { recursive: true })
+ mkdirSync(join(pnpmStage, 'package', 'lib'), { recursive: true })
+ writeFileSync(join(pnpmStage, 'package', 'bin', 'pnpm.cjs'), [
+ '#!/bin/sh',
+ 'if [ ! -f package.json ]; then',
+ ' echo "ERR_PNPM_NO_PKG_MANIFEST: no package.json in $PWD" >&2',
+ ' exit 1',
+ 'fi',
+ 'mkdir -p node_modules',
+ 'echo ok > node_modules/installed',
+ ].join('\n'))
+ writeFileSync(join(pnpmStage, 'package', 'lib', 'pnpm.js'), 'module.exports = {}\n')
+ const pnpmTgz = join(served, 'pnpm-11.7.0.tgz')
+ await promisify(execFile)('tar', ['-czf', pnpmTgz, '-C', pnpmStage, 'package'])
+
+ // dsh dist: the npm package layout (package.json + lib/bin.js).
+ const dshStage = join(work, 'dsh-stage')
+ mkdirSync(join(dshStage, 'package', 'lib'), { recursive: true })
+ writeFileSync(join(dshStage, 'package', 'package.json'), '{"name":"@deepseek-ai/dsh","version":"0.1.2-rc.1"}\n')
+ writeFileSync(join(dshStage, 'package', 'lib', 'bin.js'), '#!/usr/bin/env node\nvoid 0\n')
+ const dshTgz = join(served, 'dsh-0.1.2-rc.1.tgz')
+ await promisify(execFile)('tar', ['-czf', dshTgz, '-C', dshStage, 'package'])
+
+ const digest = (file: string, algorithm: 'sha256' | 'sha512', encoding: 'hex' | 'base64') =>
+ createHash(algorithm).update(readFileSync(file)).digest(encoding)
+ writeFileSync(join(served, 'SHASUMS256.txt'), `${digest(nodeTgz, 'sha256', 'hex')} node-v22.22.0-linux-arm64.tar.gz\n`)
+
+ const basePlan = await planRemoteInstall('Linux 5.15 aarch64', {}, healthyFetchers({
+ 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',
+ // The real SRI form npm serves; the planner normalizes it to hex.
+ integrity: `sha512-${digest(dshTgz, 'sha512', 'base64')}`,
+ }),
+ }))
+ // The pinned pnpm digest is the real release's; point it at the crafted
+ // tarball so the verify step passes against what the fake curl serves.
+ const plan: RemoteInstallPlan = { ...basePlan, pnpm: { ...basePlan.pnpm, sha256: digest(pnpmTgz, 'sha256', 'hex') } }
+
+ const sandbox = tempDir()
+ const outcome = await runScriptServing(buildInstallScript(plan), sandbox, served)
+ // Without the cd into dependencies/dsh, the pnpm stand-in aborts with
+ // ERR_PNPM_NO_PKG_MANIFEST on both registries and the script exits 13.
+ expect(outcome.stderr).toBe('')
+ expect(outcome.code).toBe(0)
+ expect(outcome.stdout).toContain('dsh 依赖安装完成 (registry https://registry.npmjs.org)')
+ expect(outcome.stdout).toContain('远端初始化完成')
+ const root = join(sandbox, REMOTE_ROOT)
+ expect(existsSync(join(root, 'dependencies', 'dsh', 'node_modules', 'installed'))).toBe(true)
+ expect(existsSync(join(root, 'dependencies', 'dsh', 'lib', 'bin.js'))).toBe(true)
+ expect(existsSync(join(root, 'runtime', 'bin', 'node'))).toBe(true)
+ expect(existsSync(join(root, 'dependencies', 'pnpm', 'bin', 'pnpm.cjs'))).toBe(true)
+ })
})
describe('component probe and launch commands', () => {
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
index ae122afc..a375bfc7 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
@@ -14,14 +14,15 @@
*/
import type { Config } from '../storage/index.js'
-import type { MachineProfile, SshProgress } from '../types/index.js'
+import type { MachineProfile, SshMachineStage, SshMachineTerminal, SshProgress } from '../types/index.js'
import type { RemoteArch, RemoteAssetMatrix, RemoteOs } from './assets.js'
import type { SshSession } from './transport.js'
+import { Buffer } from 'node:buffer'
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'
+import { listGithubAssets, listGithubReleases, npmDistMetadata, parseGitHubRepo, 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'
@@ -43,32 +44,116 @@ export const BOOTSTRAP_LOG_PREFIX = '::dsh '
/** One parsed stage line of the install script's output stream. */
export interface BootstrapLogLine {
- stage: string
+ stage: SshMachineStage
line: string
}
+/**
+ * The install script's stage vocabulary as a runtime set. Keyed by every
+ * {@link SshMachineStage} member so the compiler flags drift (S3 adds the
+ * connection-lifecycle stages here too).
+ */
+const BOOTSTRAP_STAGES: Record<SshMachineStage, true> = {
+ probe: true,
+ download: true,
+ verify: true,
+ install: true,
+ launch: true,
+ ready: true,
+ failed: true,
+}
+
+/** Whether a parsed marker word is one of the known stage tags. */
+function isBootstrapStage(value: string): value is SshMachineStage {
+ return (BOOTSTRAP_STAGES as Record<string, true | undefined>)[value] === true
+}
+
/**
* Parse one output line of the install script into its stage tag; lines
- * without the marker are unexpected tool output and report stage `install`.
+ * without a known marker are unexpected tool output and report stage
+ * `install` with the raw line kept.
* @param chunk - one raw output line.
*/
export function parseBootstrapLine(chunk: string): BootstrapLogLine {
const match = /^::dsh (\w+) (.*)$/u.exec(chunk)
- if (match === null)
+ const stage = match?.[1]
+ if (match === null || stage === undefined || !isBootstrapStage(stage))
return { stage: 'install', line: chunk }
- return { stage: match[1] ?? 'install', line: match[2] ?? '' }
+ return { stage, line: match[2] ?? '' }
+}
+
+/**
+ * Line-buffered dispatcher for a bootstrap script's streamed output: SSH
+ * data arrives in arbitrary chunk boundaries, so a half-received line is
+ * held back until its newline (or the final flush) completes it.
+ * @param onLine - one complete output line.
+ */
+export function createBootstrapLineDispatcher(onLine: (line: string) => void): { push: (chunk: string) => void, flush: () => void } {
+ let pending = ''
+ return {
+ push(chunk: string): void {
+ pending = `${pending}${chunk}`
+ const lines = pending.split('\n')
+ pending = lines.pop() ?? ''
+ for (const line of lines) {
+ if (line !== '')
+ onLine(line)
+ }
+ },
+ flush(): void {
+ const line = pending
+ pending = ''
+ if (line !== '')
+ onLine(line)
+ },
+ }
+}
+
+/**
+ * The skipped-verification summary terminal events carry: plan-level notes
+ * ("no trusted digest") plus the install script's live skip warnings,
+ * deduplicated. Empty when every artifact was actually verified — the
+ * fail-open skips stay impossible to miss on the settling event.
+ * @param notes - the install plan's resolution notes.
+ * @param skipLines - streamed verify lines that recorded a skipped check.
+ */
+export function skippedVerificationSummary(notes: string[], skipLines: string[]): string {
+ const items = [...new Set([...notes, ...skipLines].filter(item => item.includes('跳过')))]
+ return items.length === 0 ? '' : `;跳过校验项: ${items.join(';')}`
}
/** The npm-registry DSH kind's resolved asset. */
interface DshNpmPlan {
kind: 'npm-tgz'
urls: string[]
- /** Trusted `sha512-…` integrity from the packument, when available. */
+ /**
+ * Trusted digest in the install script's `sha512:<hex>` form (normalized
+ * from the packument's SRI `sha512-<base64>`), when available.
+ */
integrity?: string
packageName: string
version: string
}
+/**
+ * Normalize an npm packument integrity into the `shaNNN:<hex>` form the
+ * install script's `verify` understands. npm carries SRI (`sha512-<base64>`),
+ * which the script would otherwise compare against a hex digest — a
+ * guaranteed mismatch. Already-colonformed or unshaped values pass through
+ * unchanged (colon forms verify; unshaped ones mismatch loudly) — except
+ * unparseable ones, which report undefined so the plan notes the skip.
+ * @param integrity - the packument's `dist.integrity`, when present.
+ * @returns the `shaNNN:<hex>` digest, or undefined when unusable.
+ */
+export function normalizeNpmIntegrity(integrity: string | undefined): string | undefined {
+ if (integrity === undefined)
+ return undefined
+ const sri = /^sha(256|512)-([A-Za-z0-9+/]+={0,2})$/u.exec(integrity)
+ if (sri !== null)
+ return `sha${sri[1]}:${Buffer.from(sri[2] ?? '', 'base64').toString('hex')}`
+ return integrity.startsWith('sha256:') || integrity.startsWith('sha512:') ? integrity : undefined
+}
+
/** The packaged-zip DSH kind's resolved asset. */
interface DshZipPlan {
kind: 'pkg-zip'
@@ -122,6 +207,11 @@ export async function planRemoteInstall(
const matrix = assetMatrixFor(os, arch)
const repo = pkgRepoOf(config.installRepo)
const notes: string[] = []
+ // An unparseable configured repository falls back inside pkgRepoOf; note
+ // it so a config typo is visible instead of silently installing official.
+ const configuredRepo = config.installRepo?.trim()
+ if (configuredRepo !== undefined && configuredRepo !== '' && parseGitHubRepo(configuredRepo) === undefined)
+ notes.push(`installRepo "${configuredRepo}" 无法解析为 GitHub 仓库,回退官方发行仓 ${repo}`)
const listReleases = fetchers.listReleases ?? listGithubReleases
const listAssets = fetchers.listAssets ?? listGithubAssets
const npmDist = fetchers.npmDist ?? npmDistMetadata
@@ -181,14 +271,16 @@ export async function planRemoteInstall(
let integrity: string | undefined
try {
const dist = await npmDist(packageName, resolved.version)
- urls = [dist.url, dist.mirrorUrl]
- integrity = dist.integrity
+ // A packument served by the mirror already carries the mirror tarball
+ // URL — dedupe so the fallback list never repeats the same URL.
+ urls = [...new Set([dist.url, dist.mirrorUrl])]
+ integrity = normalizeNpmIntegrity(dist.integrity)
}
catch (error) {
notes.push(`npm 元数据获取失败(${describeError(error)}),回退确定性 URL`)
}
if (integrity === undefined)
- notes.push(`未取得 ${packageName}@${resolved.version} 的完整性摘要,将跳过校验`)
+ notes.push(`未取得 ${packageName}@${resolved.version} 的可校验完整性摘要,将跳过校验`)
return {
os,
arch,
@@ -234,10 +326,12 @@ export function buildInstallScript(plan: RemoteInstallPlan): string {
].join('\n')
: [
// The npm kind assembles node_modules on the remote: pnpm resolves
- // the platform-correct natives, official registry first, mirror fallback.
+ // the platform-correct natives, official registry first, mirror
+ // fallback. pnpm must run inside the extracted package (SSH exec
+ // starts in $HOME, where pnpm would abort with NO_PKG_MANIFEST).
`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`,
+ ` if ( cd "$ROOT/dependencies/dsh" && "$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`,
@@ -564,7 +658,7 @@ 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
+ onEvent?: (stage: SshMachineStage, line: string, options?: { terminal?: SshMachineTerminal, reason?: string }) => void
}
/** Timing + source configuration of the assurance flow. */
@@ -603,12 +697,7 @@ export async function ensureRemoteInstance(
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' })
- }
+ emitReady(onEvent, target, readyFromHtml)
return target
}
// The instance is not answering: bootstrap (probe → install → launch).
@@ -628,13 +717,17 @@ export async function ensureRemoteInstance(
for (const note of plan.notes)
onEvent?.('probe', note)
const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)
+ let skips: string[] = []
if (missing.length > 0) {
onEvent?.('probe', `缺失组件: ${missing.join(', ')}`)
- await runInstallScript(session, plan, bootstrap, hooks)
+ skips = await runInstallScript(session, plan, bootstrap, hooks)
}
else {
onEvent?.('probe', '三件套已就绪,跳过安装')
}
+ // The bootstrap's settling event carries the skipped-verification summary
+ // (plan notes + the script's live verify warnings), if any.
+ const skipSummary = skippedVerificationSummary(plan.notes, skips)
onProgress?.({ phase: 'starting' })
onEvent?.('launch', `拉起远端实例 (端口 ${profile.remotePort})`)
const started = await session.exec(startCommandFor(profile, plan))
@@ -649,11 +742,7 @@ export async function ensureRemoteInstance(
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' })
+ emitReady(onEvent, target, verdict, skipSummary)
return target
}
}
@@ -697,22 +786,31 @@ async function legacyRootVerdict(session: SshSession, profile: MachineProfile, b
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> {
+/**
+ * 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.
+ */
+async function runInstallScript(session: SshSession, plan: RemoteInstallPlan, bootstrap: BootstrapConfig, hooks: BootstrapHooks): Promise<string[]> {
const { onEvent, onProgress } = hooks
const installTimeoutMs = bootstrap.config.installTimeoutMs
let log = ''
+ const skips: string[] = []
+ const dispatch = createBootstrapLineDispatcher((line) => {
+ const parsed = parseBootstrapLine(line)
+ if (parsed.stage === 'verify' && parsed.line.includes('跳过'))
+ skips.push(parsed.line)
+ onEvent?.(parsed.stage, parsed.line)
+ })
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)
- }
+ dispatch.push(chunk)
onProgress?.({ phase: 'installing', log })
},
})
+ 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.
@@ -720,6 +818,23 @@ async function runInstallScript(session: SshSession, plan: RemoteInstallPlan, bo
const tail = stream === '' ? '(no output captured)' : stream.split('\n').slice(-5).join(' | ')
failBootstrap(onEvent, `install failed on remote (exit ${result.code ?? '?'}): ${tail}`)
}
+ return skips
+}
+
+/**
+ * The settling ready event: primary boot-manifest verdict, legacy-fallback
+ * note, and the skipped-verification summary when checks were skipped.
+ */
+function emitReady(
+ onEvent: BootstrapHooks['onEvent'],
+ target: string,
+ verdict: string,
+ skipSummary = '',
+): void {
+ const base = verdict.startsWith('boot')
+ ? `远端实例已就绪 (${target})`
+ : `远端实例已就绪(旧探测兜底: ${verdict})`
+ onEvent?.('ready', `${base}${skipSummary}`, { terminal: 'success' })
}
/** Record the terminal failure and build the thrown error. */
diff --git a/packages/dsh-tauri-ssh/src/host/service/events.ts b/packages/dsh-tauri-ssh/src/host/service/events.ts
index 0479b25c..02b71eae 100644
--- a/packages/dsh-tauri-ssh/src/host/service/events.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/events.ts
@@ -62,7 +62,7 @@ export class SshMachineEvents {
* @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.
+ * report an empty page anchored at `nextSeq: 1` (the first event's seq).
*/
since(machineId: MachineId, sinceSeq?: number): SshMachineEventsPage {
const buffer = this.buffers.get(machineId)
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 2f3c51ef..6915504d 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
@@ -38,8 +38,8 @@ const config = {
/** 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'
+/** The layout entry the v2 install resolves (see {@link fakePlan}): the remote shell expands $HOME (root user in the fake). */
+const ENTRY = '/root/.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 {
@@ -116,7 +116,8 @@ class FakeSession implements SshSession {
return { code: 0, stdout: '::dsh install 远端初始化完成', stderr: '' }
}
if (command.includes('test -f ')) {
- return { code: 0, stdout: 'ok\n', stderr: '' }
+ // The real command prints the $HOME-expanded absolute entry path.
+ return { code: 0, stdout: `${ENTRY}\n`, stderr: '' }
}
if (command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')) {
return { code: 0, stdout: this.credentialsAnswer, stderr: '' }
@@ -759,13 +760,45 @@ 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: command.includes('test -f ') ? 'ok\n' : 'installed', stderr: '' })
+ : Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? `${ENTRY}\n` : 'installed', stderr: '' })
const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(false)
expect(result.credentialsError).toContain('disk full')
})
+ it('settles the install with a terminal success event and line-buffered stream parsing', async () => {
+ let releaseInstall: (() => void) | undefined
+ const installGate = new Promise<void>((resolve) => {
+ releaseInstall = resolve
+ })
+ const session = new FakeSession(() => false)
+ session.missingResult = 'node\n'
+ session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
+ const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({}) })
+ const pending = manager.install(MachineId('m1'))
+ await until(() => session.commands.some(command => command.includes('trap cleanup EXIT')), 'install exec')
+ const installIndex = session.commands.findIndex(command => command.includes('trap cleanup EXIT'))
+ // A stage line split across two SSH chunks must surface as ONE event
+ // with the full line, never two mangled halves.
+ session.options[installIndex]?.onData?.('::dsh verify 警告: 远端缺少摘要工具,跳过校')
+ session.options[installIndex]?.onData?.('验 node.tar.gz\n::dsh download https://example.test/a\n')
+ releaseInstall!()
+ const result = await pending
+ expect(result.dshPath).toBe(ENTRY)
+ const page = events.since(MachineId('m1'))
+ const lines = page.events.map(event => `${event.stage}: ${event.line}`)
+ expect(lines).toContain('verify: 警告: 远端缺少摘要工具,跳过校验 node.tar.gz')
+ expect(lines).toContain('download: https://example.test/a')
+ // The install operation settles on its own terminal event — independent
+ // of the connect handoff — and carries the skipped-verification summary.
+ const terminals = page.events.filter(event => event.terminal !== undefined)
+ expect(terminals).toHaveLength(1)
+ expect(terminals[0]).toMatchObject({ stage: 'install', terminal: 'success' })
+ expect(terminals[0]?.line).toContain('dsh 安装成功')
+ expect(terminals[0]?.line).toContain('跳过校验项: 警告: 远端缺少摘要工具,跳过校验 node.tar.gz')
+ })
+
it('fails loud with machine-install-failed when the install command fails', async () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
@@ -874,7 +907,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: command.includes('test -f ') ? 'ok\n' : 'installed', stderr: '' })
+ : Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? `${ENTRY}\n` : 'installed', stderr: '' })
const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(false)
@@ -913,6 +946,9 @@ describe('sshManager install', () => {
return Promise.resolve({ code: 0, stdout: 'node\n', stderr: '' })
if (command.includes('trap cleanup EXIT'))
return Promise.resolve({ code: 0, stdout: '::dsh install 远端初始化完成', stderr: '' })
+ if (command.includes('test -f '))
+ // The remote `test -f` itself fails: the entry never landed.
+ return Promise.resolve({ code: 1, stdout: '', stderr: '' })
return Promise.resolve({ code: 0, stdout: '', stderr: '' })
}
const { manager } = boot({ sessionFactory: () => session })
@@ -940,7 +976,7 @@ describe('sshManager install', () => {
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('$HOME/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js')
+ expect(result.dshPath).toBe(ENTRY)
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.
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.ts
index a36bc41d..3aeb1feb 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts
@@ -8,7 +8,7 @@ import type { Config } from '../storage/index.js'
* @module dsh-tauri-ssh/host/service/manager
*/
-import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStage, SshMachineStatus, SshProgress, SshTestResult } from '../types/index.js'
+import type { MachineId, MachineProfile, MachineView, SshInstallResult, SshLink, 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'
@@ -16,7 +16,7 @@ import { homedir } from 'node:os'
import process from 'node:process'
import { join } from 'pathe'
import { SshError } from '../types/index.js'
-import { buildInstallScript, checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, parseBootstrapLine, planRemoteInstall, readEnvCredentials, REMOTE_ROOT } from './bootstrap.js'
+import { buildInstallScript, checkMissingCommand, createBootstrapLineDispatcher, credentialsCopyCommand, describeExecFailure, ensureRemoteInstance, firstLineOf, missingComponentsOf, parseBootstrapLine, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, skippedVerificationSummary } from './bootstrap.js'
import { fingerprintHostKey } from './host-keys.js'
/** One machine's live connection state. */
@@ -415,23 +415,28 @@ export class SshManager {
for (const note of plan.notes)
events.append(machineId, '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) => {
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)
- }
+ dispatch.push(chunk)
state.progress = { phase: 'installing', log }
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 })
@@ -445,14 +450,16 @@ export class SshManager {
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') {
+ // The entry check doubles as $HOME expansion: the shell prints the
+ // absolute path the type contract promises (never a literal `$HOME`).
+ const dshExpr = `"$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan.dshEntry}"`
+ const entryCheck = await session.exec(`test -f ${dshExpr} && printf '%s\\n' ${dshExpr}`)
+ const dshPath = firstLineOf(entryCheck.stdout)
+ if (entryCheck.code !== 0 || dshPath === '') {
throw new SshError(
'machine-dsh-missing',
machineId,
- `dsh install finished on "${profile.host}" but the entry ${dshPath} is not present`,
+ `dsh install finished on "${profile.host}" but the entry ${dshExpr} is not present`,
)
}
let credentialsCopied = false
@@ -463,6 +470,12 @@ export class SshManager {
catch (error) {
credentialsError = error instanceof Error ? error.message : String(error)
}
+ const dshRef = plan.dsh.kind === 'pkg-zip' ? plan.dsh.tag : `npm:${plan.dsh.version}`
+ // The install operation settles here regardless of the connect handoff
+ // 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' })
await session.close().catch(() => undefined)
if (generation === state.generation) {
delete state.progress
@@ -477,7 +490,7 @@ export class SshManager {
}
return {
installed: missing,
- dshRef: plan.dsh.kind === 'pkg-zip' ? plan.dsh.tag : `npm:${plan.dsh.version}`,
+ dshRef,
dshVersion: plan.dshVersion,
dshPath,
credentialsCopied,
diff --git a/packages/dsh-tauri-ssh/src/host/service/version.test.ts b/packages/dsh-tauri-ssh/src/host/service/version.test.ts
index 32c5f52d..296a534e 100644
--- a/packages/dsh-tauri-ssh/src/host/service/version.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/version.test.ts
@@ -16,8 +16,8 @@ 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-rc.8-32331963388', prerelease: false },
{ tag: 'dsh-0.1.0-beta.1-32490000002', prerelease: false },
]
@@ -55,11 +55,22 @@ describe('pickReleaseTag', () => {
expect(resolved.notes).toEqual([])
})
- it('dedupes republished versions keeping the last-listed tag', () => {
+ it('dedupes republished versions keeping the newest-listed tag', () => {
const resolved = pickReleaseTag(RELEASES, { recommended: '0.1.0-rc.8' })
expect(resolved.tag).toBe('dsh-0.1.0-rc.8-32342588167')
})
+ it('prefers the non-src republish of a version (newest-first listing)', () => {
+ // Mirrors the live pkg repo: `dsh-0.1.2-alpha.4` (newer) and the older
+ // `dsh-src-0.1.2-alpha.4` parse to the same version; newest-first order
+ // must keep the `dsh-` variant.
+ const srcPair = [
+ { tag: 'dsh-0.1.2-alpha.4-33260040123', prerelease: false },
+ { tag: 'dsh-src-0.1.2-alpha.4-33260039971', prerelease: false },
+ ]
+ expect(pickReleaseTag(srcPair, { recommended: '0.1.2-alpha.4' }).tag).toBe('dsh-0.1.2-alpha.4-33260040123')
+ })
+
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',
diff --git a/packages/dsh-tauri-ssh/src/host/service/version.ts b/packages/dsh-tauri-ssh/src/host/service/version.ts
index 4cc5aa8f..18171edb 100644
--- a/packages/dsh-tauri-ssh/src/host/service/version.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/version.ts
@@ -160,14 +160,17 @@ export function pickReleaseTag(
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).
+ // Dedupe by version keeping the first-listed tag: GitHub lists releases
+ // newest-first (created_at descending, verified against the pkg repo), so
+ // the first tag of a version is its newest republish — e.g. `dsh-…` wins
+ // over an older `dsh-src-…` that parses to the same version.
const byVersion = new Map<string, DshPkgReleaseMeta>()
for (const meta of metas) {
const version = parseVersionFromTag(meta.tag)
if (version === undefined)
continue
- byVersion.set(version, meta)
+ if (!byVersion.has(version))
+ byVersion.set(version, meta)
}
const recommendedMeta = byVersion.get(recommended)
if (recommendedMeta !== undefined)
diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.ts
index 8bd21c12..e001d597 100644
--- a/packages/dsh-tauri-ssh/src/host/storage/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/storage/index.ts
@@ -99,7 +99,7 @@ export interface Config {
* version; unresolvable pins fall back to the latest stable release.
*/
installRef?: string
- /** Deadline for one remote dsh install (clone + pnpm install + build). */
+ /** Deadline for one remote binary install (download + verify + extract + pnpm assembly). */
installTimeoutMs?: number
}