DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
Revert "refactor(bundle): 离线包只随包压缩产物并优先本地解压"
Mao Mrd5f7236c7150
diff --git a/.github/actions/prepare-bundle-resources/action.yml b/.github/actions/prepare-bundle-resources/action.ymlindex da8a9d20..3d965bfb 100644--- a/.github/actions/prepare-bundle-resources/action.yml+++ b/.github/actions/prepare-bundle-resources/action.yml@@ -1,10 +1,9 @@name: Prepare offline bundle resourcesdescription: >-- Download and verify the Node.js runtime, the packaged dsh core and pnpm, then- stage them **as-is** (the upstream archives) under src-tauri/resources. The- application unpacks them into app data on first launch, so the installer ships- no expanded runtime tree and never has to write into its own install- directory.+ Download and unpack the Node.js runtime, the packaged dsh core and pnpm into+ src-tauri/resources, then rewrite manifest.jsonc so every bundled dependency+ resolves through `$Resources/...`. The resulting `tauri build` produces an+ installer that needs no download on first launch.inputs:platform:@@ -27,7 +26,7 @@ inputs:runs:using: compositesteps:- - name: Download and stage bundled archives+ - name: Download and unpack bundled runtimesshell: bashenv:PLATFORM: ${{ inputs.platform }}@@ -83,21 +82,46 @@ runs:echo "${label} SHA-256 verified"}- # 离线包只随包压缩包:按资产名原样落盘,运行期由- # `config::runtime::bundled_archive_filename` 按同一套常量推导出同一个文件名。- stage() {- local from="$1" name="$2"- mkdir -p src-tauri/resources- mv -f "$from" "src-tauri/resources/$name"+ extract() {+ local archive="$1" dest="$2"+ mkdir -p "$dest"+ case "$archive" in+ *.zip)+ # Windows 的 Git Bash 不一定带 unzip;Windows 10+ 自带的 bsdtar 能解 zip。+ if command -v unzip >/dev/null 2>&1; then+ (cd "$dest" && unzip -q "$archive")+ else+ (cd "$dest" && tar -xf "$archive")+ fi+ ;;+ *)+ (cd "$dest" && tar -xzf "$archive")+ ;;+ esac+ }++ # 与 Rust `download::utils::flatten_directory` 一致:解压结果只有唯一一层+ # 子目录时把内容上提,保证 resources/<name> 就是运行时目录本身。+ flatten() {+ local dir="$1" entries=()+ while IFS= read -r entry; do entries+=("$entry"); done < <(find "$dir" -mindepth 1 -maxdepth 1)+ if [ "${#entries[@]}" -eq 1 ] && [ -d "${entries[0]}" ]; then+ shopt -s dotglob+ mv "${entries[0]}"/* "$dir"/+ shopt -u dotglob+ rmdir "${entries[0]}"+ fi+ }++ install_tree() {+ local from="$1" to="$2"+ rm -rf "$to"+ mkdir -p "$to"+ cp -a "$from/." "$to/"}# 刻意不用关联数组:macOS runner 的 /bin/bash 是 3.2(`declare -A` 需要 bash 4),# 而 `shell: bash` 会解析到它,用了会让 macOS 离线包构建在下载前就失败。- # 资产表先落到变量再解析:`while ... < <(node ...)` 里脚本失败不会让步骤失败,- # 只会得到一张空表,最后以「变量未设置」这种看不出原因的报错收场。- assets="$(node scripts/bundle-metadata.mjs --assets --platform "$PLATFORM" --arch "$ARCH" $git_flag)"- [ -n "$assets" ] || { echo "::error::failed to resolve bundle assets"; exit 1; }-while IFS='|' read -r key name url sha sha_url; do[ -n "${key:-}" ] || continuecase "$key" in@@ -106,7 +130,7 @@ runs:pnpm) pnpm_name="$name"; pnpm_url="$url"; pnpm_sha="$sha" ;;git) git_name="$name"; git_url="$url"; git_sha="$sha" ;;esac- done <<< "$assets"+ done < <(node scripts/bundle-metadata.mjs --assets --platform "$PLATFORM" --arch "$ARCH" $git_flag)# Node.js 运行时:摘要取自官方 SHASUMS256.txt,与 assets 同源同版本。fetch "$node_url" "${workdir}/${node_name}"@@ -114,7 +138,9 @@ runs:verify "${workdir}/${node_name}" \"$(awk -v asset="${node_name}" '$2 == asset { print $1 }' "${workdir}/SHASUMS256.txt")" \"Node.js ${node_name}"- stage "${workdir}/${node_name}" "$node_name"+ extract "${workdir}/${node_name}" "${workdir}/node"+ flatten "${workdir}/node"+ install_tree "${workdir}/node" "src-tauri/resources/node"# dsh 内核:摘要来自同一 release 的 GitHub API,缺失即中止(无法校验完整性的# 内容不进离线包)。@@ -123,126 +149,58 @@ runs:--jq ".assets[] | select(.name == \"${dsh_name}\") | .digest" 2>/dev/null \| sed 's/^sha256://' | head -n 1)"verify "${workdir}/${dsh_name}" "$dsh_digest" "dsh core ${dsh_name}"- stage "${workdir}/${dsh_name}" "$dsh_name"+ extract "${workdir}/${dsh_name}" "${workdir}/dsh"+ flatten "${workdir}/dsh"+ install_tree "${workdir}/dsh" "src-tauri/resources/dsh"# pnpm:纯 JS 发行,摘要取自 constants.rs 的固定值。fetch "$pnpm_url" "${workdir}/${pnpm_name}"verify "${workdir}/${pnpm_name}" "$pnpm_sha" "pnpm ${pnpm_name}"- stage "${workdir}/${pnpm_name}" "$pnpm_name"+ extract "${workdir}/${pnpm_name}" "${workdir}/pnpm"+ flatten "${workdir}/pnpm"+ install_tree "${workdir}/pnpm" "src-tauri/resources/pnpm"# MinGit:默认不随包(`bundle-git: true` 才下载)。启动 dsh 不需要 Git,# 只有 git 托管的能力(worktree、`github:` 插件)依赖它。if [ -n "${git_name:-}" ]; thenfetch "$git_url" "${workdir}/${git_name}"verify "${workdir}/${git_name}" "$git_sha" "MinGit ${git_name}"- stage "${workdir}/${git_name}" "$git_name"+ extract "${workdir}/${git_name}" "${workdir}/git"+ flatten "${workdir}/git"+ install_tree "${workdir}/git" "src-tauri/resources/git"fi- - name: Verify staged archives+ node scripts/bundle-metadata.mjs --manifest --platform "$PLATFORM" --arch "$ARCH" $git_flag++ - name: Verify bundled entriesshell: bashenv:PLATFORM: ${{ inputs.platform }}- ARCH: ${{ inputs.arch }}- DSH_TAG: ${{ inputs.dsh-tag }}- BUNDLE_GIT: ${{ inputs.bundle-git }}run: |set -euo pipefail-- with_git=false- if [ "$PLATFORM" = "windows" ] && [ "$BUNDLE_GIT" = "true" ]; then- with_git=true+ # 入口路径必须与清单 `dependencies.<key>.entry` 一致:解压层级(flatten)+ # 或资产布局变化会让应用在启动时判定「依赖缺失」并转去联网下载。+ entries="pnpm/bin/pnpm.cjs dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"+ if [ "$PLATFORM" != "windows" ]; then+ entries="node/bin/node $entries"+ else+ entries="node/node.exe $entries"fi- git_flag=""- [ "$with_git" = "true" ] && git_flag="--with-git"-- workdir="$(mktemp -d)"- trap 'rm -rf "$workdir"' EXIT-- extract() {- # 归档先取绝对路径:解压要在目标目录里执行(`cd "$out"`),- # 相对路径在那之后就失效了。局部变量刻意不复用调用方的名字:- # bash 是动态作用域,被调用方 `read` 到同名变量会写回调用方的局部变量- # (`flatten` 里的 `read` 一旦 EOF 就会把它清空)。- local src out- src="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"- out="$2"- mkdir -p "$out"- case "$src" in- *.zip)- # Windows 的 Git Bash 不一定带 unzip;Windows 10+ 自带的 bsdtar 能解 zip。- if command -v unzip >/dev/null 2>&1; then- (cd "$out" && unzip -q "$src")- else- (cd "$out" && tar -xf "$src")- fi- ;;- *)- (cd "$out" && tar -xzf "$src")- ;;- esac- }-- # 与 Rust `download::utils::flatten_directory` 一致:解压结果只有唯一一层- # 子目录时把内容上提,保证运行时根就是预期的那一层。- flatten() {- local dir="$1" entries=() child- while IFS= read -r child; do entries+=("$child"); done < <(find "$dir" -mindepth 1 -maxdepth 1)- if [ "${#entries[@]}" -eq 1 ] && [ -d "${entries[0]}" ]; then- shopt -s dotglob- mv "${entries[0]}"/* "$dir"/- shopt -u dotglob- rmdir "${entries[0]}"- fi- }-- # 入口路径必须与清单 `dependencies.<key>.entry` 一致:解压层级或资产布局变化- # 会让应用在启动时判定「依赖缺失」并转去联网下载。校验在临时目录里解压完成,- # 安装包内只保留压缩包。- check_entry() {- local key="$1" archive="$2" entry="$3" dir="${workdir}/check-${1}"- rm -rf "$dir"- extract "$archive" "$dir"- flatten "$dir"- if [ ! -e "${dir}/${entry}" ]; then- echo "::error::bundled entry is missing after unpacking ${key}: ${entry}"- return 1- fi- echo "${key} archive unpacks to ${entry}"- }-- # 资产表先落到变量再解析(理由同第一步):脚本失败必须让步骤失败,- # 而不是解析出一张空表、一个入口都不检查就通过。- assets="$(node scripts/bundle-metadata.mjs --assets --platform "$PLATFORM" --arch "$ARCH" $git_flag)"- [ -n "$assets" ] || { echo "::error::failed to resolve bundle assets"; exit 1; }-- while IFS='|' read -r key name url sha sha_url; do- [ -n "${key:-}" ] || continue- archive="src-tauri/resources/${name}"- if [ ! -f "$archive" ]; then- echo "::error::bundled archive is missing: ${archive}"- exit 1- fi- case "$key" in- node) entry="bin/node"; [ "$PLATFORM" = "windows" ] && entry="node.exe" ;;- pnpm) entry="bin/pnpm.cjs" ;;- dsh) entry="node_modules/@deepseek-ai/dsh/lib/bin.js" ;;- git) entry="cmd/git.exe" ;;- *) echo "::error::unknown bundled key ${key}"; exit 1 ;;- esac- check_entry "$key" "$archive" "$entry"- done <<< "$assets"-- # 解压后的运行时树不得进安装包:那正是这次要消掉的体积。- for legacy in node pnpm dsh git; do- if [ -d "src-tauri/resources/$legacy" ]; then- echo "::error::extracted runtime tree must not be bundled: src-tauri/resources/$legacy"- exit 1+ # 清单没有指向 `$Resources/git` 时不能要求它存在(默认就不随包 MinGit)。+ if grep -q '"managedRoot": "$Resources/git"' src-tauri/resources/manifest.jsonc; then+ entries="$entries git/cmd/git.exe"+ fi+ missing=0+ for entry in $entries; do+ if [ ! -e "src-tauri/resources/${entry}" ]; then+ echo "::error::bundled entry is missing: src-tauri/resources/${entry}"+ missing=1fidone+ [ "$missing" -eq 0 ] || exit 1- # 托管根必须留在 AppData(已废弃的 `$Resources/...` 不再出现在清单里)- grep -q '"managedRoot": "\$AppData/' src-tauri/resources/manifest.jsonc- ! grep -q '"\$Resources/' src-tauri/resources/manifest.jsonc- echo "--- bundled archives ---"- du -sh src-tauri/resources/*.zip src-tauri/resources/*.tgz src-tauri/resources/*.tar.gz 2>/dev/null || true+ grep -q '"$Resources/' src-tauri/resources/manifest.jsonc+ echo "--- bundled resources ---"+ du -sh src-tauri/resources/node src-tauri/resources/dsh src-tauri/resources/pnpm 2>/dev/null || true+ [ -d src-tauri/resources/git ] && du -sh src-tauri/resources/git || truesed -n '/"dependencies"/,/^ }/p' src-tauri/resources/manifest.jsoncdiff --git a/.github/workflows/build-bundle-macos.yml b/.github/workflows/build-bundle-macos.ymlindex dc123d14..3a676459 100644--- a/.github/workflows/build-bundle-macos.yml+++ b/.github/workflows/build-bundle-macos.yml@@ -110,12 +110,12 @@ jobs:exit 1fi- # 离线包只把 Node 运行时 / 内核的**压缩包**随包分发(首次启动解压到 AppData),- # 因此 .app 的 `Contents/Resources/**` 里已不再有随包的 Mach-O 原生模块- # (sharp / koffi / node-pty 的 `.node`、`@img` 的 `.dylib` 都在压缩包里)。- # 这一遍签约保留为安全网:万一 resources/ 下仍有 Mach-O(例如内置插件带了原生- # 模块),Apple 的公证会要求它带 Developer ID 签名与安全时间戳,而 tauri 只签- # 自己产出的可执行文件(`--deep` 按 Apple 的定义会跳过 `Contents/Resources/**`)。+ # 离线包把 Node 运行时与原生模块(sharp / koffi / node-pty 的 `.node`、`@img` 的+ # `.dylib`)一起塞进了 .app。Apple 的公证要求包里**每一个** Mach-O 都带 Developer ID+ # 签名与安全时间戳,而 tauri 只签自己产出的可执行文件(`--deep` 按 Apple 的定义会+ # 跳过 `Contents/Resources/**`),于是公证会逐条报+ # 「The binary is not signed with a valid Developer ID certificate」。+ # 这里先把随包资源里的 Mach-O 全部签掉,再交给 tauri 打包与公证。- name: Sign bundled Mach-O binariesif: steps.check.outputs.should_run == 'true'shell: bash@@ -173,7 +173,7 @@ jobs:done < <(find src-tauri/resources -type f \\( -name '*.node' -o -name '*.dylib' -o -name '*.so' -o -perm -100 \) -print)echo "signed $signed Mach-O binaries under src-tauri/resources ($kept already Developer ID signed)"- # 离线包正常为 0:随包的运行时原生模块都在压缩包里,公证不会展开压缩包。+ [ "$signed" -gt 0 ] || { echo "::error::no unsigned Mach-O binaries found under src-tauri/resources"; exit 1; }# 必须同时产出 app:只给 `--bundles dmg` 时 tauri 会把 .app 当中间产物,打完 dmg# 就删掉它(日志里的 `Cleaning .../bundle/macos/<name>.app`),后面的签名/公证diff --git a/.github/workflows/release-bundle.yml b/.github/workflows/release-bundle.ymlindex 21c721c2..52015ffa 100644--- a/.github/workflows/release-bundle.yml+++ b/.github/workflows/release-bundle.yml@@ -1,9 +1,10 @@name: Build & Release (Offline Bundle)# 离线安装包:在普通发布流程(release.yml)成功后追加一次带资源构建。-# 产物把 Node.js 运行时、推荐 dsh 内核、pnpm 随安装包分发(安装目录里只放上游压缩包,-# 首次启动解压到 AppData),首次启动全程不联网。只随包启动 dsh 必需的资源:MinGit 默认-# 不携带(git 托管的能力在真正使用时才需要,`bundle_git` 可显式开启)。+# 产物把 Node.js 运行时、推荐 dsh 内核、pnpm 随安装包分发,并在构建期把+# `resources/manifest.jsonc` 的托管根改写成 `$Resources/...`,首次启动直接使用+# 随包资源,全程不联网。只随包启动 dsh 必需的资源:MinGit 默认不携带(git 托管的+# 能力在真正使用时才需要,`bundle_git` 可显式开启)。## 手动触发有两条路:# - 留空 `tag`:试跑。构建当前 ref,发一个 `test-<ref>-<run>` 测试预发布,不碰任何@@ -355,7 +356,7 @@ jobs:{echo "### Offline bundle assets"echo- echo "Bundled core: \`$DSH_TAG\` · archives staged in \`resources/\` (unpacked into app data on first launch)"+ echo "Bundled core: \`$DSH_TAG\` · resources mapped to \`\$Resources/{node,pnpm,dsh}\`"echofor asset in "${assets[@]}"; doecho "- \`$(basename "$asset")\`"diff --git a/.gitignore b/.gitignoreindex 419ff405..905f3ca8 100644--- a/.gitignore+++ b/.gitignore@@ -3,11 +3,10 @@ dist.build-plugins-tmpsrc-tauri/targetsrc-tauri/gen-# 离线包随包的运行时压缩包(构建产物,按上游资产名落盘)-src-tauri/resources/node-v*-src-tauri/resources/pnpm-*.tgz-src-tauri/resources/deepseek-harness-pkg-*.zip-src-tauri/resources/MinGit-*.zip+src-tauri/resources/node+src-tauri/resources/dsh+src-tauri/resources/pnpm+src-tauri/resources/gitsrc-tauri/resources/preset-plugins/src-tauri/resources/internal-plugins/*.logdiff --git a/scripts/bundle-metadata.d.mts b/scripts/bundle-metadata.d.mtsindex 70f42f82..fb6cab7c 100644--- a/scripts/bundle-metadata.d.mts+++ b/scripts/bundle-metadata.d.mts@@ -38,6 +38,7 @@ export interface BundleConstants {export type BundlePlatform = 'windows' | 'macos' | 'linux'export type BundleArch = 'x64' | 'arm64'+export const BUNDLED_DIRS: Record<string, string>export const DSH_PKG_REPO: stringexport function stripJsonc(raw: string): string@@ -63,12 +64,18 @@ export function bundleAssets(input: {arch: BundleArchconstants: BundleConstantsdshTag: string- /** 随包 MinGit(默认 false;Windows 且确实要随包 Git 时才需要) */+ /** 随包 MinGit(默认 false;Windows 且清单未被改写时才需要) */withGit?: boolean}): BundleAssetsexport function toAssetTable(assets: BundleAssets): string+export function applyBundleManifest(input: {+ repo?: string+ platform: BundlePlatform+ withGit?: boolean+}): { file: string, applied: string[] }+export function findReleaseTag(releases: unknown, version: string): stringexport function resolveDshTag(diff --git a/scripts/bundle-metadata.mjs b/scripts/bundle-metadata.mjsindex fae9e15e..6b0ac934 100644--- a/scripts/bundle-metadata.mjs+++ b/scripts/bundle-metadata.mjs@@ -1,4 +1,4 @@-import { appendFileSync, readFileSync } from 'node:fs'+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'import path from 'node:path'import process from 'node:process'import { pathToFileURL } from 'node:url'@@ -6,13 +6,13 @@ import { pathToFileURL } from 'node:url'// 离线安装包(offline bundle)构建元数据。版本号、资产名与下载前缀全部取自// `src-tauri/src/config/constants.rs` 与 `src-tauri/resources/manifest.jsonc`,// 不在 workflow 或本脚本里另抄一份常量。-//-// 资产名同时也是随包落盘名:`.github/actions/prepare-bundle-resources` 把下载到的-// 压缩包按原名放进 `src-tauri/resources/`,运行期由-// `config::runtime::bundled_archive_filename` 按同一套常量推导出同一个名字。const DSH_PKG_REPO = 'dsh-tauri-desk/deepseek-harness-pkg'const DSH_LATEST_DOWNLOAD_SEGMENT = 'releases/latest/download/'+const RESOURCES_TOKEN = '$Resources'++/** 随包资源目录名(= `src-tauri/resources/<dir>`,也是清单 `$Resources/<dir>` 的落点)。 */+const BUNDLED_DIRS = { node: 'node', pnpm: 'pnpm', dsh: 'dsh', git: 'git' }function bundleError(message, cause) {const error = new Error(`BUNDLE_METADATA: ${message}`)@@ -200,7 +200,7 @@ export function readBuildConstants(repo = process.cwd()) {** 默认只随包 Node / pnpm / 内核三项:MinGit 约 35 MiB,而绝大多数 Windows 机器已有* 可用的系统 Git,内网补装又必然失败(应用侧据「随包资源」构建放宽 Git 就绪判定,- * 见 `config::dependencies::bundled_core_dir`)。确有需要时用 `--with-git` 显式开启。+ * 见 `config::dependencies::is_bundled_install`)。确有需要时用 `--with-git` 显式开启。*/export function bundleTargets(platform, { withGit = false } = {}) {const keys = ['node', 'pnpm', 'dsh']@@ -239,7 +239,7 @@ export function bundleAssets({ platform, arch, constants, dshTag, withGit = falssha256Url: '',},}- if (bundleTargets(platform, { withGit }).includes('git')) {+ if (platform === 'windows' && withGit) {const name = mingitAssetName(arch, constants.mingitVersion)assets.git = {name,@@ -264,6 +264,45 @@ export function toAssetTable(assets) {.join('\n')}+/**+ * 把清单里的依赖托管根改写成 `$Resources/<dir>`。+ *+ * 离线包把运行时随安装包分发,`managedRoot` 必须指向安装包资源目录。+ *+ * `overridable` 按依赖区分:+ * - Node / pnpm(以及可选的 MinGit)置 false:它们固定随包,本机既有的+ * `dependencies.json` 记录(旧的非离线安装留下、可能已被删除)不该盖过随包资源;+ * - 内核保持 true:随包内核是核心面板里置顶的「本地」项,用户要能下载并切换到+ * AppData 里的其它版本,也能切回来——切换正是通过依赖映射表实现的。+ *+ * 改写结果直接写回 `src-tauri/resources/manifest.jsonc`(构建产物,不提交),+ * 因此注释与缩进按 JSON 重新序列化。未随包的依赖(默认的 MinGit)保持清单原值,+ * 不能指向并不存在的 `$Resources/git`。+ */+export function applyBundleManifest({ repo = process.cwd(), platform, withGit = false } = {}) {+ if (!['windows', 'macos', 'linux'].includes(platform))+ throw bundleError(`platform must be windows|macos|linux, got ${JSON.stringify(platform)}`)+ const manifest = readManifest(repo)+ const dependencies = manifest?.dependencies+ if (!dependencies || typeof dependencies !== 'object')+ throw bundleError('manifest.jsonc is missing the dependencies section')++ const applied = []+ for (const key of bundleTargets(platform, { withGit })) {+ const spec = dependencies[key]+ if (!spec || typeof spec !== 'object')+ throw bundleError(`manifest.jsonc is missing dependencies.${key}`)+ const managedRoot = `${RESOURCES_TOKEN}/${BUNDLED_DIRS[key]}`+ spec.managedRoot = managedRoot+ spec.overridable = key === 'dsh'+ applied.push(`${key} -> ${managedRoot} (overridable: ${spec.overridable})`)+ }++ const file = manifestPath(repo)+ writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')+ return { file, applied }+}+/** 解析 GitHub Release 响应中版本号命中推荐版本的 tag(与 Rust 侧版本解析同源)。 */export function findReleaseTag(releases, version) {if (!Array.isArray(releases))@@ -306,11 +345,13 @@ function appendOutputs(outputPath, values) {}function parseArgs(argv) {- const args = { assets: false, platform: '', arch: '', withGit: false }+ const args = { assets: false, manifest: false, platform: '', arch: '', withGit: false }for (let i = 0; i < argv.length; i += 1) {const arg = argv[i]if (arg === '--assets')args.assets = true+ else if (arg === '--manifest')+ args.manifest = trueelse if (arg === '--with-git')args.withGit = trueelse if (arg === '--platform')@@ -343,6 +384,13 @@ async function main() {return}+ if (args.manifest) {+ requirePlatformArch(args)+ const { file, applied } = applyBundleManifest({ repo, platform: args.platform, withGit: args.withGit })+ process.stdout.write(`${file}\n${applied.map(line => ` ${line}`).join('\n')}\n`)+ return+ }+const dshTag = await resolveDshTag(dshVersion)appendOutputs(process.env.GITHUB_OUTPUT, {node_version: constants.nodeVersion,@@ -366,5 +414,6 @@ if (entryPoint && import.meta.url === pathToFileURL(path.resolve(entryPoint)).hr}export {+ BUNDLED_DIRS,DSH_PKG_REPO,}diff --git a/src-tauri/resources/README.md b/src-tauri/resources/README.mdindex c4968c4b..119aece3 100644--- a/src-tauri/resources/README.md+++ b/src-tauri/resources/README.md@@ -63,20 +63,17 @@ mapping entry**.}```-`managedRoot` (and every recorded mapping value) accepts these forms:+`managedRoot` (and every recorded mapping value) accepts three forms:| Form | Resolves to || ---- | ----------- || `$AppData/...` | the app data directory (its `dev` sibling in debug builds) |+| `$Resources/...` (legacy spelling: `resources/...`) | the installed app's resource root, falling back to app data when it cannot be probed || absolute path (`C:/anywhere/dsh`, `/opt/dsh`) | used verbatim — how a local bundle build points at a checkout || any other relative path | app data directory |-The prefix is case-insensitive and requires the `/` boundary (`$appdatafoo` is a plain-relative path). The early `$Resources/...` token (legacy spelling `resources/...`), which-pointed a managed root into the installer's own resource directory, **is deprecated**: a-managed root never lives inside the installation directory. Old `dependencies.json`-entries carrying it now resolve to a non-existent relative path, so the dependency falls-back to `managedRoot` and is reinstalled under app data.+Prefixes are case-insensitive and require the `/` boundary (`$resourcesfoo` is a plain+relative path).| Section | Purpose || ------- | ------- |@@ -98,70 +95,80 @@ Which root is actually used is recorded per machine in{ "node": "C:/Users/you/AppData/Roaming/dsh-tauri/runtime", "pnpm": null, "dsh": "C:/Users/you/AppData/Roaming/dsh-tauri/dependencies/dsh" }```-* a path → that root is used (an absolute location anywhere on disk, or an- `$AppData/...` token as described above);+* a path → that root is used (an absolute location anywhere on disk, or a+ `$AppData/...` / `$Resources/...` token as described above);* `null` → the system environment satisfies this dependency; a managed copy isstill downloaded into `managedRoot` if one is ever needed (and the mapping isrewritten then);* a missing key → fall back to the manifest's `managedRoot` (under app data).-A recorded root that no longer exists — or that points inside the installation directory,-as old offline bundles did — is ignored as well, so an upgrade never pins the app to a-stale tree.+This is what makes a future "bundled core" build a manifest-only change:+point `managedRoot` (or the recorded root) at `$Resources/dsh` and no path logic+in `src-tauri` has to move.### Offline bundle`Build & Release (Offline Bundle)` (`.github/workflows/release-bundle.yml`) produces asecond set of installers that need no network on first launch. Its-`.github/actions/prepare-bundle-resources` step only **stages the upstream archives** in-`resources/`; nothing is unpacked at build time:--| Archive | Bundled contents |-| ------- | ---------------- |-| `resources/node-v<version>-<os>-<arch>.{zip,tar.gz}` | Node.js runtime (`node.exe` / `bin/node`) |-| `resources/pnpm-<version>.tgz` | pnpm distribution (`bin/pnpm.cjs`) |-| `resources/deepseek-harness-pkg-<platform>.zip` | packaged DeepSeek Harness core (`node_modules/@deepseek-ai/dsh/lib/bin.js`) |-| `resources/MinGit-<version>-<arch>.zip` | MinGit — **not** bundled by default (`bundle_git` opt-in) |--The file names are the upstream asset names, and the app derives them again from-`src-tauri/src/config/constants.rs` (`config::runtime::bundled_archive_filename`), so the-manifest needs no extra field and the installer carries no expanded runtime tree. On first-launch each archive with a matching file is preferred over the network: the install flow-skips the download phase, reads the archive and feeds it through the ordinary extraction-path (`download::ensure_extract` → `flatten_directory`), landing in the same app-data-managed roots a download would use.--An upgrade replaces those archives but leaves the app-data trees in place, so each-extraction also records a fingerprint of its archive (`<managed root>/.bundled-archive`,-name + byte size) and a mismatching fingerprint makes the dependency count as *not*-installed (see `config::dependencies::bundled_archive_is_stale`). A rebundled Node/pnpm/core-is therefore unpacked once on the next launch, while an unchanged archive is not touched-again. A core the user switched to a downloaded slot is exempt — re-unpacking the bundled-archive there would overwrite the selected version.+`.github/actions/prepare-bundle-resources` step unpacks the runtime into `resources/`:++| Directory | Bundled contents |+| --------- | ---------------- |+| `resources/node` | Node.js runtime (`node.exe` / `bin/node`) |+| `resources/pnpm` | pnpm distribution (`bin/pnpm.cjs`) |+| `resources/dsh` | packaged DeepSeek Harness core (`node_modules/@deepseek-ai/dsh/lib/bin.js`) |+| `resources/git` | MinGit — **not** bundled by default (`bundle_git` opt-in) |Only what running `dsh` itself needs is bundled. Git is deliberately left out: it is notrequired to start the harness, only git-backed features (worktree, `github:` plugins) are,and an air-gapped machine can never provision it later. A bundled build therefore stops-treating Git as a startup prerequisite (see `config::dependencies::bundled_core_dir`), so-the install screen is never entered for a download that cannot succeed. When MinGit *is*-bundled, that relaxation is suspended until the archive has been unpacked.--Every asset is SHA-256 verified at build time (Node against the official `SHASUMS256.txt`,-the core against its GitHub release digest, pnpm/MinGit against the pins in-`src-tauri/src/config/constants.rs`), and the staged archive is unpacks-checked against the-entry path the manifest declares. Versions and download prefixes are read from that same-file, and the core version from this manifest's `engines.dsh.recommend`, so the bundle-never drifts from what the app would otherwise download. The local archives are *not*-re-verified at runtime — an offline machine has no way to fetch the digests.--The bundled core is unpacked into `<app-data>/dependencies/dsh`, i.e. the ordinary managed-root, and is the core panel's pinned **本地** entry. Because it is no longer hosted in the-install directory, switching cores keeps working by pointing the `dsh` dependency root-elsewhere — either at a downloaded slot in `<app-data>/dependencies/<tag>` or back at the-managed root (see [`config::dependencies::bundled_core_dir`]). The install directory is-never written to, which also keeps the Linux deb under `/usr/lib/**` read-only-safe.-Community/preset plugins are still installed from the network; the offline bundle only-removes the *first-launch* dependency downloads.+treating Git as a startup prerequisite (see `config::dependencies::bundled_core_dir`),+so the install screen is never entered for a download that cannot succeed.++Every asset is SHA-256 verified before unpacking (Node against the official+`SHASUMS256.txt`, the core against its GitHub release digest, pnpm/MinGit against the+pins in `src-tauri/src/config/constants.rs`). Versions and download prefixes are read from+that same file, and the core version from this manifest's `engines.dsh.recommend`, so the+bundle never drifts from what the app would otherwise download.++The step then rewrites **this file** so every bundled dependency resolves through the+installer's own resources:++```jsonc+{+ "dependencies": {+ "node": { "entry": { "windows": "node.exe", "default": "bin/node" }, "managedRoot": "$Resources/node", "overridable": false },+ "dsh": { "entry": "node_modules/@deepseek-ai/dsh/lib/bin.js", "managedRoot": "$Resources/dsh", "overridable": true }+ }+}+```++The rewrite only ever touches the build output — the committed manifest keeps its+`$AppData/...` defaults. `overridable` is per dependency:++* `node` / `pnpm` (and MinGit, when bundled) are pinned (`false`): they ship with the+ installer, and a stale `<app-data>/dependencies.json` (written by an earlier,+ non-bundled install and possibly pointing at deleted directories) must not win over+ them. `config::dependencies::active_root` additionally ignores a recorded root whose+ path no longer exists.+* `dsh` stays overridable (`true`): the bundled core is the core panel's pinned **本地**+ entry, and switching cores works by pointing the `dsh` dependency root elsewhere —+ either at a downloaded slot in `<app-data>/dependencies/<tag>` or back at+ `$Resources/dsh`. Downloaded cores therefore keep landing in app data; the install+ directory is never written to and never loses its bundled core (unlike a directory+ swap, which would move `resources/dsh` into app data on every switch).++`resource_root()` strips the Windows `\\?\` verbatim prefix that Tauri's+`resource_dir()` carries (it canonicalizes the exe path). Without that, `$Resources/dsh`+resolves to a verbatim path, which is handed to node as its main module — and node's+`resolveMainPath` fails on it with `EISDIR: illegal operation on a directory, lstat 'C:'`,+so the bundled core could never start.++The bundled core is used in place, so the install directory must stay writable for the+desktop's startup patches and plugin entry links — true for the per-user NSIS install, not+for `/usr/lib/**` in the Linux deb (documented limitation). Community/preset plugins are+still installed from the network; the offline bundle only removes the *first-launch*+dependency downloads.### Preset plugins — `plugins.preset`diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex d5d2a3ed..e801f312 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -22,11 +22,10 @@"dependencies": {// 依赖映射规范:AppData 的 dependencies.json 只记录每个依赖的安装根// (null = 用系统环境);入口相对路径与默认托管根以本表为准。- // managedRoot / 映射值支持两种形态:+ // managedRoot / 映射值支持三种形态:// $AppData/... AppData 数据目录(debug 构建为 <base>/dev 的同级)+ // $Resources/... 安装包资源目录(`resources/...` 为等价旧写法)// 绝对路径 任意位置(如加载本地捆绑版内核)- // 随包资源(离线包)不再把解压产物放进安装目录:安装目录只留上游压缩包,- // 首次启动解压到本表声明的 AppData 托管根。"node": {"engine": ">=22.22.0","entry": {diff --git a/src-tauri/src/config/dependencies.rs b/src-tauri/src/config/dependencies.rsindex c0e833e9..e1251f7f 100644--- a/src-tauri/src/config/dependencies.rs+++ b/src-tauri/src/config/dependencies.rs@@ -3,15 +3,14 @@//! 桌面端不再假设 node/pnpm/dsh 一定装在固定的 AppData 路径下,而是把每个依赖//! 的**安装根**记在映射表里://!-//! - 路径 → 使用该根(任意绝对路径,或 `$AppData/...` 令牌,见+//! - 路径 → 使用该根(可为任意绝对路径,或 `resources/...` 令牌,见//! [`super::manifest::resolve_location`]);//! - `null` → 由系统环境满足,桌面端不托管该依赖;//! - 键缺失 → 尚未探测,按清单的 `managedRoot` 默认托管根解析。//!//! 入口相对路径由清单 `dependencies.<key>.entry` 决定,因此「装在哪」与「入口形状」-//! 各有一处真值。离线包(随包资源)只把压缩包放进安装目录,解压产物一律落在 AppData-//! 的托管根,因此路径解析逻辑与普通安装完全一致。写入单点收口到 [`record`],且内容-//! 不变时不落盘。+//! 各有一处真值。将来做本地捆绑版只需把清单(或映射表)指向 `resources/*`,路径解析+//! 逻辑无需改动。写入单点收口到 [`record`],且内容不变时不落盘。use serde::{Deserialize, Serialize};use std::collections::BTreeMap;@@ -178,8 +177,9 @@ pub fn managed_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {/// 当前生效的依赖根:映射指定的根优先,否则回落清单默认托管根////// 映射表里的值同样按 [`manifest::resolve_location`] 解析:绝对路径原样使用(任意-/// 位置),`$AppData/...` 指向数据目录。因此切换内核只需在映射表里写任意绝对路径,-/// 不必改动清单或重装。+/// 位置),`$AppData/...` / `$Resources/...` 指向数据目录 / 安装包资源根。因此本地+/// 捆绑 / 切换内核只需在映射表里写 `"dsh": "$Resources/dsh"` 或任意绝对路径,不必+/// 改动清单或重装。////// 清单把 `dependencies.<key>.overridable` 声明为 false 时,映射表记录的位置一律/// 被忽略(本地捆绑版内核固定随包,不允许被运行时改写)。@@ -193,11 +193,7 @@ pub fn active_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {if overridable {if let Some(Some(recorded)) = mapped(app, key) {let resolved = manifest::resolve_location(app, &recorded.to_string_lossy());- // 安装目录里的记录同样不采信:旧离线包把依赖根写在那里,而现在解压产物- // 一律落在 AppData,老记录只会把应用钉在旧树上。- let inside_install_dir =- manifest::resource_root(app).is_some_and(|root| resolved.starts_with(root));- if resolved.exists() && !inside_install_dir {+ if resolved.exists() {return resolved;}}@@ -205,82 +201,19 @@ pub fn active_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {managed_root(app, key)}-/// 随包资源压缩包(离线包在安装目录 `resources/` 下随包分发的原始资产名);不随包时为 None。-///-/// 文件名由 [`super::runtime::bundled_archive_filename`] 按同一套常量推导,与-/// `.github/actions/prepare-bundle-resources` 落盘的名字同源。-pub fn bundled_archive<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<PathBuf> {- let name = super::runtime::bundled_archive_filename(key)?;- let path = manifest::resource_root(app)?.join(name);- path.is_file().then_some(path)-}--/// 托管根里记录「这份产物解压自哪个随包压缩包」的指纹文件。-const BUNDLED_STAMP_FILE: &str = ".bundled-archive";--/// 随包压缩包指纹:文件名 + 字节数 + 修改时间。dsh 资产名不含版本-/// (`deepseek-harness-pkg-*.zip`),换版本只能靠体积与时间戳区分;升级安装必然重写该-/// 文件,三者合起来足以判定新旧。内容摘要要在每次就绪判定时整读压缩包(内核包 60MB+),-/// 代价远高于收益。-fn archive_fingerprint(archive: &Path) -> Option<String> {- let metadata = std::fs::metadata(archive).ok()?;- let name = archive.file_name()?.to_string_lossy();- let modified = metadata- .modified()- .ok()- .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())- .map(|elapsed| elapsed.as_nanos())- .unwrap_or(0);- Some(format!("{name}:{}:{modified}", metadata.len()))-}--/// 托管根与随包压缩包是否不同源(无记录、记录不匹配都算)。-fn archive_stamp_differs(root: &Path, archive: &Path) -> bool {- let Some(fingerprint) = archive_fingerprint(archive) else {- return false;- };- std::fs::read_to_string(root.join(BUNDLED_STAMP_FILE))- .map(|recorded| recorded.trim() != fingerprint)- .unwrap_or(true)-}--fn write_archive_stamp(root: &Path, archive: &Path) {- let Some(fingerprint) = archive_fingerprint(archive) else {- return;- };- let _ = std::fs::create_dir_all(root);- let _ = std::fs::write(root.join(BUNDLED_STAMP_FILE), fingerprint);-}--/// 随包压缩包是否比托管根里的产物新(没有随包压缩包时恒为 false)。-///-/// 离线包升级会替换安装目录里的压缩包,而 AppData 里的解压产物留在原地:不比对指纹-/// 就会一直用旧运行时。判定只在「托管根就是这份压缩包的解压目标」时有意义。-pub fn bundled_archive_is_stale<R: Runtime>(app: &AppHandle<R>, key: &str) -> bool {- match bundled_archive(app, key) {- Some(archive) => archive_stamp_differs(&managed_root(app, key), &archive),- None => false,- }-}--/// 解压落盘后记录指纹:下次启动据此判定「随包压缩包已换新版」而重新解压。-pub fn record_bundled_archive_stamp<R: Runtime>(app: &AppHandle<R>, key: &str) {- if let Some(archive) = bundled_archive(app, key) {- write_archive_stamp(&managed_root(app, key), &archive);- }-}--/// 随包资源构建的随包核心根(普通安装为 None)。+/// 随包资源构建的随包核心根(`$Resources/dsh`);非随包构建为 None。////// 这类安装的运行时全部随安装包分发(见 `.github/actions/prepare-bundle-resources`),/// 运行期下载在离线机器上必然失败:启动就绪判定据此放宽「补不上的依赖」,核心面板据此/// 把随包内核作为「本地」项置顶。///-/// 判定按**是否存在随包内核压缩包**,返回的却是托管根:离线包不再把解压产物放进安装目录,-/// 随包核心解压后就落在与普通安装相同的托管根上,因此「本地」标识与运行路径解耦。+/// 判定按**清单托管根**而不是当前生效根:随包核心始终是安装目录里那一份,与该依赖+/// 当前是否被映射到别处的槽位无关。pub fn bundled_core_dir<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {- bundled_archive(app, DEP_DSH)?;- Some(managed_root(app, DEP_DSH))+ let root = manifest::resource_root(app)?;+ let managed = managed_root(app, DEP_DSH);+ // 资源根自身不算:只有把核心托管到 `$Resources/<name>` 才是随包构建。+ (managed != root && managed.starts_with(&root)).then_some(managed)}/// 入口相对路径(相对依赖根):清单 `dependencies.<key>.entry`,未声明时用内置默认@@ -430,6 +363,7 @@ mod tests {let manifest = manifest::read_at(&path).expect("manifest should parse");// 清单声明的托管根可以是 `$AppData/...` 令牌,因此比较**解析后**的位置let base = PathBuf::from("C:/app-data");+ let resources = PathBuf::from("C:/app-resources");for (key, root, entry) in [(DEP_NODE, default_managed_root(DEP_NODE), default_entry(DEP_NODE)),(DEP_PNPM, default_managed_root(DEP_PNPM), default_entry(DEP_PNPM)),@@ -439,64 +373,11 @@ mod tests {let spec = manifest.dependencies.get(key).expect("spec should exist");let declared = spec.managed_root.as_deref().expect("managedRoot");assert_eq!(- manifest::resolve_location_from(&base, declared),+ manifest::resolve_location_from(&base, Some(&resources), declared),base.join(root),"{key}");assert_eq!(spec.entry.resolve(), Some(entry), "{key}");}}-- #[test]- fn shipped_manifest_never_points_into_the_installer_resources() {- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(manifest::MANIFEST_FILE);- let manifest = manifest::read_at(&path).expect("manifest should parse");- for (key, spec) in &manifest.dependencies {- let Some(declared) = spec.managed_root.as_deref() else {- continue;- };- // 解压产物一律落在 AppData:托管根不得再引用已废弃的 `$Resources` / `resources/`- assert!(- !declared.to_ascii_lowercase().starts_with("$resources")- && !declared- .replace('\\', "/")- .to_ascii_lowercase()- .starts_with("resources/"),- "{key}: {declared}"- );- }- }-- #[test]- fn archive_stamp_detects_a_repacked_bundle() {- let dir = temp_path("stamp");- let root = dir.join("root");- let archive = dir.join("pnpm-11.7.0.tgz");- std::fs::create_dir_all(&dir).unwrap();- std::fs::write(&archive, b"first").unwrap();-- // 没有指纹(首次安装)与换个压缩包都算「需要解压」- assert!(archive_stamp_differs(&root, &archive));- let fingerprint = archive_fingerprint(&archive).expect("fingerprint");- assert!(- fingerprint.starts_with("pnpm-11.7.0.tgz:5:"),- "{fingerprint}"- );- write_archive_stamp(&root, &archive);- assert!(!archive_stamp_differs(&root, &archive));-- // 同名换版本:字节数变化即重新解压- std::fs::write(&archive, b"second-revision").unwrap();- assert!(archive_stamp_differs(&root, &archive));-- // 文件名变化(dsh 之外的资产都带版本号)同样触发- let renamed = dir.join("pnpm-11.8.0.tgz");- std::fs::write(&renamed, b"second-revision").unwrap();- write_archive_stamp(&root, &archive);- assert!(archive_stamp_differs(&root, &renamed));-- let _ = std::fs::remove_dir_all(dir);- }}diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rsindex be7a8e59..1c07fccc 100644--- a/src-tauri/src/config/manifest.rs+++ b/src-tauri/src/config/manifest.rs@@ -265,7 +265,7 @@ pub struct PresetPetExt {pub struct DependencySpec {/// 入口相对路径(相对依赖根),按平台覆盖:`default` / `windows` / `macos` / `linux`pub entry: EntrySpec,- /// AppData 下的默认托管根(相对 AppData 基础目录)+ /// AppData 下的默认托管根(相对 AppData 基础目录,或 `resources/...`)pub managed_root: Option<String>,/// 是否允许运行期覆盖为任意位置pub overridable: bool,@@ -313,7 +313,7 @@ impl EntrySpec {}}-/// 安装包资源根:清单与随包资源压缩包的解析基准。+/// 安装包资源根:`resources/...` 位置令牌与入口路径的解析基准。////// Tauri 2 在 Windows 上 `resource_dir()` 恒等于 exe 所在目录,安装包与开发产物/// 都会把资源按 `resources/**` 前缀落盘到 `{resource_dir}/resources/` 子目录,@@ -321,11 +321,11 @@ impl EntrySpec {////// 返回前统一剥离 Windows 扩展长度前缀:`resource_dir()` 取自/// `tauri_utils::platform::current_exe()`(内部对 exe 路径做了 canonicalize),-/// 在 Windows 上带 `\\?\` verbatim 前缀。该前缀会随依赖托管根拼进入口路径,-/// 而已装内核的入口要交给 node 当主模块:node 的+/// 在 Windows 上带 `\\?\` verbatim 前缀。该前缀会随依赖托管根(`$Resources/dsh`+/// 等)拼进入口路径,而随包内核的入口要交给 node 当主模块:node 的/// `resolveMainPath` 解析 verbatim 路径会直接以-/// `EISDIR: illegal operation on a directory, lstat 'C:'` 退出(Node 25 实测)。-/// CLI shim 也会把这个前缀写进 `.cmd`,同样要归一化。+/// `EISDIR: illegal operation on a directory, lstat 'C:'` 退出(Node 25 实测),+/// 随包核心因此永远起不来。CLI shim 也会把这个前缀写进 `.cmd`,同样要归一化。pub fn resource_root<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {let dir = app.path().resource_dir().ok()?;Some(simplify_resource_root(pick_resource_root(&dir).unwrap_or(dir)))@@ -456,32 +456,43 @@ pub fn dependency_spec<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<Depewith_manifest(app, |manifest| manifest.dependencies.get(key).cloned())?}-/// 位置令牌解析:绝对路径原样返回,其余相对 AppData 基础目录——依赖可以托管在-/// AppData,也可以由用户指定到任意盘符。+/// 位置令牌解析:`resources/...` 相对安装包资源根,其余相对 AppData 基础目录,+/// 绝对路径原样返回——依赖可以位于任意位置(AppData 托管、安装目录捆绑、+/// 或用户指定的其它盘符)。pub fn resolve_location<R: Runtime>(app: &AppHandle<R>, raw: &str) -> PathBuf {- resolve_location_from(&super::runtime::get_base_dir(app), raw)+ resolve_location_from(+ &super::runtime::get_base_dir(app),+ resource_root(app).as_deref(),+ raw,+ )}-/// 位置令牌解析(依赖可位于任意位置:AppData 托管、或用户指定的其它盘符):+/// 位置令牌解析(依赖可位于任意位置:AppData 托管、安装目录捆绑、或用户指定的其它盘符):////// - 绝对路径(`C:/...`、`/opt/...`)原样返回;/// - `$AppData/...`(大小写不敏感)= AppData 基础目录,debug 构建即 `<base>/dev` 的同级;+/// - `$Resources/...` = 安装包资源根(`resources/` 为等价旧写法),探测不到时回落 AppData;/// - 其余相对路径 = 相对 AppData 基础目录。-///-/// 早期离线包曾用 `$Resources/...`(旧写法 `resources/...`)把依赖托管根指进安装包资源目录,-/// 该令牌已废弃:解压产物一律落在 AppData,安装包内只留压缩包。-pub fn resolve_location_from(base: &Path, raw: &str) -> PathBuf {+pub fn resolve_location_from(base: &Path, resource_root: Option<&Path>, raw: &str) -> PathBuf {let value = raw.trim();if PathBuf::from(value).is_absolute() {return PathBuf::from(value);}let normalized = value.replace('\\', "/");if let Some(rest) = normalized.strip_prefix("./") {- return resolve_location_from(base, rest);+ return resolve_location_from(base, resource_root, rest);}if let Some(rest) = strip_prefix_ci(&normalized, "$appdata") {return join_token(base, rest);}+ if let Some(rest) = strip_prefix_ci(&normalized, "$resources") {+ return join_token(resource_root.unwrap_or(base), rest);+ }+ if let Some(rest) = normalized.strip_prefix("resources/") {+ if let Some(root) = resource_root {+ return join_token(root, rest);+ }+ }base.join(value)}@@ -743,9 +754,10 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}- /// 用户可以把依赖托管根指向任意绝对路径(本地核心构建的常见做法)。`resource_dir()`- /// 在 Windows 上是 canonicalize 结果(带 `\\?\`),而 node 的 resolveMainPath 解析- /// verbatim 路径会直接以 `EISDIR: ... lstat 'C:'` 退出,因此资源根必须先归一化。+ /// 随包资源构建(离线包)会把核心托管根指向 `$Resources/dsh`,该路径会作为+ /// node 的主模块参数。`resource_dir()` 在 Windows 上是 canonicalize 结果(带+ /// `\\?\`),而 node 的 resolveMainPath 解析 verbatim 路径会直接以+ /// `EISDIR: ... lstat 'C:'` 退出,因此资源根必须先归一化。#[test]fn resource_root_simplifies_windows_verbatim_prefix() {let verbatim = PathBuf::from(r"\\?\C:\app\resources\dsh");@@ -762,6 +774,7 @@ mod tests {#[test]fn location_token_resolves_arbitrary_bases() {let base = PathBuf::from("C:/app/data");+ let resources = PathBuf::from("C:/app/resources");let absolute = if cfg!(windows) {"D:/anywhere"} else {@@ -769,15 +782,19 @@ mod tests {};assert_eq!(- resolve_location_from(&base, "dependencies/dsh"),+ resolve_location_from(&base, Some(&resources), "dependencies/dsh"),base.join("dependencies/dsh"));assert_eq!(- resolve_location_from(&base, r"dependencies\node"),- base.join(r"dependencies\node")+ resolve_location_from(&base, Some(&resources), "resources/dsh"),+ resources.join("dsh"));assert_eq!(- resolve_location_from(&base, absolute),+ resolve_location_from(&base, Some(&resources), r"resources\node"),+ resources.join("node")+ );+ assert_eq!(+ resolve_location_from(&base, Some(&resources), absolute),PathBuf::from(absolute));}@@ -785,6 +802,7 @@ mod tests {#[test]fn location_prefix_tokens_are_case_insensitive_and_typed() {let base = PathBuf::from("C:/app/data");+ let resources = PathBuf::from("C:/app/resources");for raw in ["$AppData/runtime",@@ -797,21 +815,29 @@ mod tests {} else {base.clone()};- assert_eq!(resolve_location_from(&base, raw), expected, "{raw}");+ assert_eq!(+ resolve_location_from(&base, Some(&resources), raw),+ expected,+ "{raw}"+ );}- // 已废弃的资源令牌按普通相对路径落到 AppData:旧安装包留下的- // `"dsh": "$Resources/dsh"` 记录因此不再命中旧安装目录,回落到托管根重装。for raw in ["$Resources/dsh", "$resources/dsh", r"$RESOURCES\dsh"] {- assert_eq!(resolve_location_from(&base, raw), base.join(raw), "{raw}");+ assert_eq!(+ resolve_location_from(&base, Some(&resources), raw),+ resources.join("dsh"),+ "{raw}"+ );}++ // 资源根探测不到时回落 AppData,而不是相对当前工作目录assert_eq!(- resolve_location_from(&base, "resources/dsh"),- base.join("resources/dsh")+ resolve_location_from(&base, None, "$Resources/dsh"),+ base.join("dsh"));// 前缀不完整(不是令牌)时按普通相对路径处理assert_eq!(- resolve_location_from(&base, "$resourcesfoo/dsh"),+ resolve_location_from(&base, Some(&resources), "$resourcesfoo/dsh"),base.join("$resourcesfoo/dsh"));}diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex 3b93bdb4..3f0bc501 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -358,22 +358,6 @@ pub fn get_mingit_download_url() -> Result<String, String> {))}-/// 随包资源压缩包文件名(相对安装包资源根)。-///-/// 离线包只把**压缩包**随安装包分发(解压产物一律落在 AppData),文件名就是上游资产名:-/// `.github/actions/prepare-bundle-resources` 直接按 `scripts/bundle-metadata.mjs --assets`-/// 的资产名落盘,这里按同一套常量重新推导,因此清单不必再记一份文件名,运行期也不必-/// 解析目录。-pub fn bundled_archive_filename(key: &str) -> Option<String> {- match key {- dependencies::DEP_NODE => node_pkg_filename(env::consts::OS, env::consts::ARCH).ok(),- dependencies::DEP_PNPM => Some(format!("pnpm-{PNPM_VERSION}.tgz")),- dependencies::DEP_DSH => dsh_pkg_asset_filename().ok(),- dependencies::DEP_GIT if cfg!(windows) => mingit_pkg_filename(env::consts::ARCH).ok(),- _ => None,- }-}-/// Windows MinGit 官方发行包固定 SHA-256。#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 MinGit 任务使用pub fn get_mingit_sha256() -> Result<&'static str, String> {@@ -467,13 +451,8 @@ pub fn get_git_cmd_dir<R: Runtime>(_app_handle: &AppHandle<R>) -> Option<PathBuf#[cfg(windows)]pub fn git_runtime_ready<R: Runtime>(app_handle: &AppHandle<R>) -> bool {find_system_git_binary().is_some()- // 随包 MinGit 换新版后同样要重解压:旧产物的指纹对不上就当未安装。- || (git_binary_works(&get_mingit_binary_path(app_handle))- && !dependencies::bundled_archive_is_stale(app_handle, dependencies::DEP_GIT))- // 随包构建放宽只在「没有随包 MinGit 压缩包」时成立:真随包了 MinGit,- // 就必须让它走解压流程,否则放宽会把该任务跳过、Git 永远装不上。- || (dependencies::bundled_core_dir(app_handle).is_some()- && dependencies::bundled_archive(app_handle, dependencies::DEP_GIT).is_none())+ || git_binary_works(&get_mingit_binary_path(app_handle))+ || dependencies::bundled_core_dir(app_handle).is_some()}/// 非 Windows 平台不属于本次空白 Windows 环境的自动配置范围。@@ -835,42 +814,4 @@ mod tests {);}}-- #[test]- fn bundled_archive_filenames_mirror_the_bundled_assets() {- // 必须与 `.github/actions/prepare-bundle-resources` 落盘的文件名一致- // (资产名来自 `scripts/bundle-metadata.mjs --assets`),否则运行期找不到随包压缩包。- let node = bundled_archive_filename(dependencies::DEP_NODE).expect("node archive");- assert!(node.starts_with(&format!("node-{NODE_VERSION}-")), "{node}");- assert_eq!(- bundled_archive_filename(dependencies::DEP_PNPM).expect("pnpm archive"),- format!("pnpm-{PNPM_VERSION}.tgz")- );- let dsh = bundled_archive_filename(dependencies::DEP_DSH).expect("dsh archive");- assert!(dsh.starts_with("deepseek-harness-pkg-"), "{dsh}");-- if cfg!(windows) {- assert_eq!(- bundled_archive_filename(dependencies::DEP_GIT).expect("mingit archive"),- mingit_pkg_filename(env::consts::ARCH).expect("supported arch")- );- } else {- // MinGit 只在 Windows 随包- assert!(bundled_archive_filename(dependencies::DEP_GIT).is_none());- }-- // 扩展名必须落在 `download::ensure_extract` 能识别的归档格式内- for key in [- dependencies::DEP_NODE,- dependencies::DEP_PNPM,- dependencies::DEP_DSH,- ] {- let name = bundled_archive_filename(key).expect("bundled archive name");- assert!(- name.ends_with(".zip") || name.ends_with(".tgz") || name.ends_with(".tar.gz"),- "{name}"- );- }- assert!(bundled_archive_filename("unknown").is_none());- }}diff --git a/src-tauri/src/service/core/source.rs b/src-tauri/src/service/core/source.rsindex ed3b6bb5..03fadf78 100644--- a/src-tauri/src/service/core/source.rs+++ b/src-tauri/src/service/core/source.rs@@ -67,8 +67,8 @@ pub struct HarnessCore {pub above_recommended: bool,/// 本地存在但远程 pkg 仓库已不再提供的历史槽位。pub orphaned: bool,- /// 是否随安装包分发(离线包在安装目录里随包内核压缩包,解压到 AppData 托管根):- /// 核心面板把它置顶并标记「本地」,且不提供卸载——它是内网/离线环境唯一的兜底内核。+ /// 是否随安装包分发(离线包把内核托管到 `$Resources/dsh`):核心面板把它置顶并+ /// 标记「本地」,且不提供卸载——它是内网/离线环境唯一的兜底内核。pub bundled: bool,/// 资源清单中的推荐版本,用于切换前风险提示。pub recommended_version: Option<String>,@@ -161,7 +161,7 @@ pub fn active_dsh_binary(app_handle: &AppHandle) -> PathBuf {}}-/// 当前生效的核心是否就是随安装包分发的那份(离线包随包压缩包解压到托管根)。+/// 当前生效的核心是否就是随安装包分发的那份(离线包把内核托管到 `$Resources/dsh`)。////// 判定「来源是 App **且** 生效根就是随包内核目录」:切到本地核心时映射被记为系统环境、/// 生效根回落到随包目录,此时不能再算作随包内核。diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex 9400fbb8..6ca06a61 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -4,10 +4,9 @@//! 历史版本存放在 `dependencies/<tag>` 槽位,切换/卸载依赖既有版本行。本地//! 核心的探测见 [`super::local`],来源判定与活动入口见 [`super::source`]。//!-//! 随包资源构建(离线包)不适用上面的目录互换:随包内核由安装目录里的压缩包解压而来,-//! 落在 `dependencies/dsh` 托管根上,在面板里作为固定置顶的「本地」行存在(见-//! [`config::dependencies::bundled_core_dir`]),切换只是把 `dsh` 依赖根指向目标槽位-//! 或指回随包内核。+//! 随包资源构建(离线包)不适用上面的目录互换:随包内核必须留在安装目录里+//! (`$Resources/dsh`,见 [`config::dependencies::bundled_core_dir`]),它在面板里+//! 作为固定置顶的「本地」行存在,切换只是把 `dsh` 依赖根指向目标槽位或指回随包内核。use crate::config;use crate::service::{download, fs_guard, workflow};@@ -25,9 +24,9 @@ const BUNDLED_CORE_ID: &str = "app-bundled";/// `dependencies` 目录(下载的核心槽位与普通安装的 `dsh` 激活目录的共同父级)。///-/// 恒落在应用数据目录之下:槽位是桌面端自己下载的产物,绝不能让下载产物写进安装目录-/// ——那里在 macOS `.app` 上是签名的只读内容、在 Linux deb 里属于 root,且会随应用-/// 升级被覆盖。+/// 恒落在应用数据目录之下:槽位是桌面端自己下载的产物,即使清单把激活核心托管到安装+/// 包资源(离线包 `$Resources/dsh`)也不能让下载产物写进安装目录——那里在 macOS `.app`+/// 上是签名的只读内容、在 Linux deb 里属于 root,且会随应用升级被覆盖。fn dependencies_dir(app_handle: &AppHandle) -> PathBuf {config::get_base_dir(app_handle).join("dependencies")}@@ -433,7 +432,7 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,// 映射表记录「该依赖由系统环境满足」(`null`),与清单的 `Path | null` 语义一致。config::dependencies::record(app_handle, config::dependencies::DEP_DSH, None);} else if id == BUNDLED_CORE_ID {- // 切回随包内核:它就是托管根上那份解压产物,只需把 dsh 依赖根指回去。+ // 切回随包内核:它始终在安装目录里,只需把 dsh 依赖根指回去。let Some(bundled) = config::dependencies::bundled_core_dir(app_handle) else {return Err("CORE_BUNDLED_NOT_FOUND: this install ships no bundled core".to_string());};@@ -507,10 +506,10 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Strlet target_dir = existing_slot_dir(app_handle, tag).ok_or_else(|| format!("CORE_VERSION_NOT_DOWNLOADED: {tag}"))?;- // 随包资源构建:随包内核解压在 AppData 托管根上,不能像普通安装那样把「激活目录 ↔- // 槽位目录」互换——那会把随包内核搬进槽位、也让应用升级后的新压缩包无处解压。- // 改为把 `dsh` 依赖根指向槽位本身:槽位本就在 AppData 里,切回随包内核只是把根指回- // 托管根(见 `set_active` 的 `app-bundled` 分支)。+ // 随包资源构建:随包内核必须留在安装目录(`$Resources/dsh`),不能像普通安装那样+ // 把「激活目录 ↔ 槽位目录」互换——那会把安装包资源搬进 AppData,也会让应用升级+ // 覆盖掉用户选中的版本。改为把 `dsh` 依赖根指向槽位本身:槽位本就在 AppData 里,+ // 切回随包内核只是把根指回去(见 `set_active` 的 `app-bundled` 分支)。if config::dependencies::bundled_core_dir(app_handle).is_some() {stop_harness_for_core_switch(app_handle).await?;let commit = match download::fetch_dsh_pkg_tags().await {diff --git a/src-tauri/src/service/download/installable.rs b/src-tauri/src/service/download/installable.rsindex 7a8ca6d2..9754469e 100644--- a/src-tauri/src/service/download/installable.rs+++ b/src-tauri/src/service/download/installable.rs@@ -81,11 +81,7 @@ impl Installable for Nodejs {// 用那个 ABI 不匹配的运行时启动。if config::prefer_bundled_node_runtime() {return config::bundled_node_binary(app).is_some()- && config::is_runtime_compatible(app)- && !config::dependencies::bundled_archive_is_stale(- app,- config::dependencies::DEP_NODE,- );+ && config::is_runtime_compatible(app);}if let Some(local_node) = config::get_local_node_path() {log::info!(@@ -94,9 +90,7 @@ impl Installable for Nodejs {);return true;}- config::get_node_binary_path(app).exists()- && config::is_runtime_compatible(app)- && !config::dependencies::bundled_archive_is_stale(app, config::dependencies::DEP_NODE)+ config::get_node_binary_path(app).exists() && config::is_runtime_compatible(app)}fn record_mapping(&self, app: &AppHandle) {let managed = config::get_node_install_path(app);@@ -129,15 +123,7 @@ impl Installable for Dsh {config::get_dsh_install_path(app)}fn check_installed(&self, app: &AppHandle) -> bool {- if !config::get_dsh_binary_path(app).exists() {- return false;- }- // 随包压缩包解压出的托管根要跟随新版安装包(升级只替换压缩包,AppData 里的- // 解压产物留在原地)。只有生效根就是托管根时才让陈旧的压缩包判成待重装:用户- // 自选的下载槽位不在此列,否则重解压会覆盖用户选定的版本。- let active = config::dependencies::active_root(app, config::dependencies::DEP_DSH);- active != config::dependencies::managed_root(app, config::dependencies::DEP_DSH)- || !config::dependencies::bundled_archive_is_stale(app, config::dependencies::DEP_DSH)+ config::get_dsh_binary_path(app).exists()}fn record_mapping(&self, app: &AppHandle) {// 记录**当前生效的根**而不是清单托管根:随包资源构建(离线包)里用户可以把内核@@ -176,7 +162,6 @@ impl Installable for Pnpm {return true;}config::get_pnpm_binary_path(app).exists()- && !config::dependencies::bundled_archive_is_stale(app, config::dependencies::DEP_PNPM)}fn record_mapping(&self, app: &AppHandle) {let managed = config::get_pnpm_install_path(app);diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rsindex d133ec7e..2de83140 100644--- a/src-tauri/src/service/workflow/install.rs+++ b/src-tauri/src/service/workflow/install.rs@@ -52,10 +52,7 @@ pub async fn install(// 必须在下载前解析 release 元数据:下载地址和摘要必须属于同一固定 tag。// 若先下载 latest、再因 API 限流从 Atom/HTML 解析 tag,latest 在两次请求间// 发生切换就会把另一份资产拿来匹配摘要,最终触发 INTEGRITY_CHECK_FAILED。- // 离线包(随包资源)把内核压缩包放进安装目录,此时无需任何联网元数据。- let bundled_dsh =- config::dependencies::bundled_archive(app_handle, config::dependencies::DEP_DSH);- let dsh_missing = !download::Dsh.check_installed(app_handle) && bundled_dsh.is_none();+ let dsh_missing = !download::Dsh.check_installed(app_handle);if dsh_latest.is_none() && dsh_missing {for attempt in 0..3 {let metadata = match config::recommended_dsh_version(app_handle) {@@ -97,15 +94,11 @@ pub async fn install(let kind = task.kind();log::debug!("Processing task {}/{}", index + 1, tasks.len());// 已安装但版本/commit 与最新 release 不一致时强制重新下载。- // 随包内核压缩包例外:本地压缩包就是权威版本,按 release 判定「过期」会把- // 随包旧核心每次启动都重解压一遍;安装包换了新版压缩包的情况由- // `bundled_archive_is_stale` 指纹判定(见 `Dsh::check_installed`)。// 版本优先(与 resolve_update 的判定完全一致):dsh 的 rc 发布会复用// 同一 git commit(record_commit 不变),只比 commit 会把 rc.8 之于// rc.7 误判为"已最新"而跳过下载——日志表现为"All installation tasks// completed"但实际什么都没下载,重启后仍是旧版,且前端丢掉更新提示。let outdated = kind == download::InstallKind::Dsh- && bundled_dsh.is_none()&& dsh_latest.as_ref().is_some_and(|info| {let installed_version = config::get_dsh_version(app_handle);let latest_version = download::parse_version_from_tag(&info.tag);@@ -139,91 +132,70 @@ pub async fn install(log::info!("Task {} not installed, starting installation", index + 1);- // 1. 下载:安装目录里随包了该依赖的压缩包时整段跳过,直接进入解压。- // 压缩包在构建期已校验过 SHA-256,且离线机器上取不到 SHASUMS256/release- // digest,因此本地包不做运行期摘要校验。- let bundled = config::dependencies::bundled_archive(app_handle, kind.dependency_key());- let (name, buffer) = match &bundled {- Some(path) => {- log::info!("Using bundled archive {}", path.display());- tracker.skip_phases(1);- let name = path- .file_name()- .map(|name| name.to_string_lossy().into_owned())- .unwrap_or_default();- let buffer = std::fs::read(path)- .map_err(|e| format!("BUNDLED_ARCHIVE_READ_FAILED: {}: {e}", path.display()))?;- (name, buffer)+ // 1. 下载+ tracker.start_phase(+ "download",+ &format!(+ "{} {}",+ config::i18n::t("install.downloading"),+ task.title()+ ),+ );+ // 下载 URL 对 dsh 也是完全确定可算的(DSH_CORE_URL + 平台文件名),+ // 无需依赖 GitHub API 元数据;api.github.com 限流/被代理拦截时+ // (mac 首次启动常见)仍能拿到真实下载地址,避免整次安装被瞬时失败卡死。+ // dsh 核心默认先走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底+ // (下载层会在界面上告知用户);其余任务保持单一官方源。+ let (urls, name) = if kind == download::InstallKind::Dsh {+ // 摘要与资产必须来自同一个 release。若前面已取得 release 元数据,+ // 必须使用其中的固定 asset URL;继续请求 `releases/latest` 会在 latest+ // 发布切换或 CDN 缓存不一致时下载另一份文件,最终表现为摘要 mismatch。+ let primary = dsh_latest+ .as_ref()+ .map(|info| info.asset_url.clone())+ .filter(|url| !url.is_empty())+ .unwrap_or(config::get_dsh_download_url()?);+ let name = primary.rsplit('/').next().unwrap_or("").to_string();+ let urls = vec![primary.clone(), config::mirror_download_url(&primary)];+ (urls, name)+ } else {+ let url = task.get_download_url()?;+ let name = url.rsplit('/').next().unwrap_or("").to_string();+ (vec![url], name)+ };+ // 取文件名用于解压类型判定;下载 URL 正常必含 '/',但这里不 panic,+ // 防御性兜底为空串(后续 ensure_extract 会因无法判定类型而报错返回,+ // 不再让进程崩溃)。+ log::debug!("Download URL: {}", urls.join(" -> "));+ log::debug!("File name: {}", name);+ let buffer = download::download_file_from_sources(&tracker, urls).await?;+ log::info!("Download completed, file size: {} bytes", buffer.len());+ let expected_digest = match kind {+ download::InstallKind::Node => {+ download::fetch_node_sha256(task.get_download_url()?.as_str()).await?+ }+ download::InstallKind::Dsh => {+ // 元数据已在安装任务开始前获取,确保下载地址与摘要来自同一 release。+ dsh_latest+ .as_ref()+ .and_then(|info| info.digest.clone())+ .ok_or_else(|| {+ "DSH_INTEGRITY_UNAVAILABLE: trusted release digest is required".to_string()+ })?}- None => {- tracker.start_phase(- "download",- &format!(- "{} {}",- config::i18n::t("install.downloading"),- task.title()- ),- );- // 下载 URL 对 dsh 也是完全确定可算的(DSH_CORE_URL + 平台文件名),- // 无需依赖 GitHub API 元数据;api.github.com 限流/被代理拦截时- // (mac 首次启动常见)仍能拿到真实下载地址,避免整次安装被瞬时失败卡死。- // dsh 核心默认先走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底- // (下载层会在界面上告知用户);其余任务保持单一官方源。- let (urls, name) = if kind == download::InstallKind::Dsh {- // 摘要与资产必须来自同一个 release。若前面已取得 release 元数据,- // 必须使用其中的固定 asset URL;继续请求 `releases/latest` 会在 latest- // 发布切换或 CDN 缓存不一致时下载另一份文件,最终表现为摘要 mismatch。- let primary = dsh_latest- .as_ref()- .map(|info| info.asset_url.clone())- .filter(|url| !url.is_empty())- .unwrap_or(config::get_dsh_download_url()?);- let name = primary.rsplit('/').next().unwrap_or("").to_string();- let urls = vec![primary.clone(), config::mirror_download_url(&primary)];- (urls, name)- } else {- let url = task.get_download_url()?;- let name = url.rsplit('/').next().unwrap_or("").to_string();- (vec![url], name)- };- // 取文件名用于解压类型判定;下载 URL 正常必含 '/',但这里不 panic,- // 防御性兜底为空串(后续 ensure_extract 会因无法判定类型而报错返回,- // 不再让进程崩溃)。- log::debug!("Download URL: {}", urls.join(" -> "));- log::debug!("File name: {}", name);- let buffer = download::download_file_from_sources(&tracker, urls).await?;- log::info!("Download completed, file size: {} bytes", buffer.len());- let expected_digest = match kind {- download::InstallKind::Node => {- download::fetch_node_sha256(task.get_download_url()?.as_str()).await?- }- download::InstallKind::Dsh => {- // 元数据已在安装任务开始前获取,确保下载地址与摘要来自同一 release。- dsh_latest- .as_ref()- .and_then(|info| info.digest.clone())- .ok_or_else(|| {- "DSH_INTEGRITY_UNAVAILABLE: trusted release digest is required"- .to_string()- })?- }- download::InstallKind::Pnpm => config::PNPM_SHA256.to_string(),- #[cfg(windows)]- download::InstallKind::Git => config::get_mingit_sha256()?.to_string(),- #[cfg(not(windows))]- download::InstallKind::Git => {- return Err(- "INSTALL_TASK_INVALID: Git task not supported on this platform"- .to_string(),- )- }- };- download::verify_sha256(&buffer, &expected_digest)?;- log::info!("Download integrity verified for task {}", index + 1);- tracker.end_phase();- (name, buffer)+ download::InstallKind::Pnpm => config::PNPM_SHA256.to_string(),+ #[cfg(windows)]+ download::InstallKind::Git => config::get_mingit_sha256()?.to_string(),+ #[cfg(not(windows))]+ download::InstallKind::Git => {+ return Err(+ "INSTALL_TASK_INVALID: Git task not supported on this platform".to_string(),+ )}};+ download::verify_sha256(&buffer, &expected_digest)?;+ log::info!("Download integrity verified for task {}", index + 1);+ tracker.end_phase();// 2. 解压tracker.start_phase(@@ -236,21 +208,14 @@ pub async fn install(log::info!("Extraction completed");// 解压落盘即建立该依赖的路径映射(新用户 / 缺少内核的场景)。task.record_mapping(app_handle);- // 随包压缩包记指纹:安装包升级换了新版压缩包时,下次启动据此重解压。- if bundled.is_some() {- config::dependencies::record_bundled_archive_stamp(app_handle, kind.dependency_key());- }tracker.end_phase();// 记录本次安装对应的 release tag 与 commit,供下次启动比对if kind == download::InstallKind::Dsh {dsh_updated = true;- // 随包压缩包装的不是 release 资产:不能把最新 release 的 tag/commit 记在它头上。- if bundled.is_none() {- if let Some(info) = &dsh_latest {- config::set_dsh_pkg_commit(app_handle, info.commit.clone());- config::set_dsh_pkg_tag(app_handle, info.tag.clone());- }+ if let Some(info) = &dsh_latest {+ config::set_dsh_pkg_commit(app_handle, info.commit.clone());+ config::set_dsh_pkg_tag(app_handle, info.tag.clone());}}}diff --git a/src/types/core.ts b/src/types/core.tsindex 20b071f4..e82755aa 100644--- a/src/types/core.ts+++ b/src/types/core.ts@@ -24,7 +24,7 @@ export interface HarnessCore {aboveRecommended: boolean/** 本地存在但 pkg 仓库已不再提供的历史槽位 */orphaned: boolean- /** 随安装包分发的内核(离线包随包压缩包解压到 AppData 托管根):面板置顶并标记「本地」,不可卸载 */+ /** 随安装包分发的内核(离线包 `$Resources/dsh`):面板置顶并标记「本地」,不可卸载 */bundled: booleanrecommendedVersion: string | nullerror?: string | nulldiff --git a/test/bundle-metadata.test.ts b/test/bundle-metadata.test.tsindex 7f4a7bbf..3f58624a 100644--- a/test/bundle-metadata.test.ts+++ b/test/bundle-metadata.test.ts@@ -1,3 +1,6 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'import { describe, expect, it } from 'vitest'import * as bundleMetadata from '../scripts/bundle-metadata.mjs'@@ -161,17 +164,106 @@ describe('jsonc stripping', () => {})})-describe('bundle archive staging', () => {- it('names the staged archives exactly like the downloaded assets', () => {- // 离线包把压缩包按资产名原样放进 `src-tauri/resources/`,- // 运行期由 `config::runtime::bundled_archive_filename` 按同一套常量重新推导。- const assets = assetsFor('windows', 'x64', { withGit: true })- expect(assets.node.name).toBe('node-v22.22.0-win-x64.zip')- expect(assets.pnpm.name).toBe('pnpm-11.7.0.tgz')- expect(assets.dsh.name).toBe('deepseek-harness-pkg-windows.zip')- expect(assets.git?.name).toBe('MinGit-2.53.0.2-64-bit.zip')- for (const name of Object.values(assets).map(asset => asset.name)) {- expect(name).not.toContain('/')+describe('bundle manifest rewrite', () => {+ const SHIPPED = `{+ // 依赖映射规范+ "engines": { "dsh": { "recommend": "0.1.5-rc.3", "minimum": "0.1.5-rc.1" } },+ "dependencies": {+ "node": { "entry": "node.exe", "managedRoot": "$AppData/runtime", "overridable": true },+ "pnpm": { "entry": "bin/pnpm.cjs", "managedRoot": "$AppData/dependencies/pnpm", "overridable": true },+ "dsh": { "entry": "node_modules/@deepseek-ai/dsh/lib/bin.js", "managedRoot": "$AppData/dependencies/dsh", "overridable": true },+ "git": { "entry": { "windows": "cmd/git.exe", "default": "bin/git" }, "managedRoot": "$AppData/dependencies/git", "overridable": true }+ }+}`++ function tempRepo() {+ const repo = mkdtempSync(path.join(tmpdir(), 'dsh-bundle-manifest-'))+ mkdirSync(path.join(repo, 'src-tauri', 'resources'), { recursive: true })+ writeFileSync(path.join(repo, 'src-tauri', 'resources', 'manifest.jsonc'), SHIPPED, 'utf8')+ return repo+ }++ it('points every bundled dependency at $Resources and disables overrides', () => {+ const repo = tempRepo()+ try {+ const result = bundleMetadata.applyBundleManifest({ repo, platform: 'windows' })+ expect(result.applied).toEqual([+ 'node -> $Resources/node (overridable: false)',+ 'pnpm -> $Resources/pnpm (overridable: false)',+ 'dsh -> $Resources/dsh (overridable: true)',+ ])++ const manifest = JSON.parse(readFileSync(result.file, 'utf8'))+ const shipped = JSON.parse(bundleMetadata.stripJsonc(SHIPPED))+ for (const [key, dir] of [['node', 'node'], ['pnpm', 'pnpm'], ['dsh', 'dsh']]) {+ expect(manifest.dependencies[key].managedRoot).toBe(`$Resources/${dir}`)+ // 内核保持可覆盖:核心面板要能把 dsh 根切到 AppData 里的其它版本再切回来。+ expect(manifest.dependencies[key].overridable).toBe(key === 'dsh')+ // 入口形状由清单声明,改写托管根不得动它。+ expect(manifest.dependencies[key].entry).toEqual(shipped.dependencies[key].entry)+ }+ expect(manifest.engines.dsh.recommend).toBe('0.1.5-rc.3')+ // 未随包的 git 保持清单原值:不能指向并不存在的 `$Resources/git`。+ expect(manifest.dependencies.git.managedRoot).toBe('$AppData/dependencies/git')+ expect(manifest.dependencies.git.overridable).toBe(true)+ }+ finally {+ rmSync(repo, { recursive: true, force: true })+ }+ })++ it('moves git to $Resources only when MinGit is bundled', () => {+ const repo = tempRepo()+ try {+ const { file, applied } = bundleMetadata.applyBundleManifest({ repo, platform: 'windows', withGit: true })+ expect(applied).toEqual([+ 'node -> $Resources/node (overridable: false)',+ 'pnpm -> $Resources/pnpm (overridable: false)',+ 'dsh -> $Resources/dsh (overridable: true)',+ 'git -> $Resources/git (overridable: false)',+ ])+ const manifest = JSON.parse(readFileSync(file, 'utf8'))+ expect(manifest.dependencies.git.managedRoot).toBe('$Resources/git')+ expect(manifest.dependencies.git.overridable).toBe(false)+ }+ finally {+ rmSync(repo, { recursive: true, force: true })+ }+ })++ it('leaves the non-Windows git mapping on app data', () => {+ const repo = tempRepo()+ try {+ const { file, applied } = bundleMetadata.applyBundleManifest({ repo, platform: 'macos' })+ expect(applied).toEqual([+ 'node -> $Resources/node (overridable: false)',+ 'pnpm -> $Resources/pnpm (overridable: false)',+ 'dsh -> $Resources/dsh (overridable: true)',+ ])+ const manifest = JSON.parse(readFileSync(file, 'utf8'))+ expect(manifest.dependencies.git.managedRoot).toBe('$AppData/dependencies/git')+ expect(manifest.dependencies.git.overridable).toBe(true)+ }+ finally {+ rmSync(repo, { recursive: true, force: true })+ }+ })++ it('is idempotent and fails loudly on unknown platforms', () => {+ const repo = tempRepo()+ try {+ bundleMetadata.applyBundleManifest({ repo, platform: 'linux' })+ const second = bundleMetadata.applyBundleManifest({ repo, platform: 'linux' })+ expect(second.applied).toEqual([+ 'node -> $Resources/node (overridable: false)',+ 'pnpm -> $Resources/pnpm (overridable: false)',+ 'dsh -> $Resources/dsh (overridable: true)',+ ])+ expect(() => bundleMetadata.applyBundleManifest({ repo, platform: 'freebsd' as BundlePlatform }))+ .toThrow(/^BUNDLE_METADATA:/)+ }+ finally {+ rmSync(repo, { recursive: true, force: true })}})})