DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(bundle): 离线包只随包压缩产物并优先本地解压
hairyf8f716b7709e2
diff --git a/.github/actions/prepare-bundle-resources/action.yml b/.github/actions/prepare-bundle-resources/action.ymlindex 3d965bfb..c2ada844 100644--- a/.github/actions/prepare-bundle-resources/action.yml+++ b/.github/actions/prepare-bundle-resources/action.yml@@ -1,9 +1,10 @@name: Prepare offline bundle resourcesdescription: >-- 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.+ 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.inputs:platform:@@ -26,7 +27,7 @@ inputs:runs:using: compositesteps:- - name: Download and unpack bundled runtimes+ - name: Download and stage bundled archivesshell: bashenv:PLATFORM: ${{ inputs.platform }}@@ -82,42 +83,12 @@ runs:echo "${label} SHA-256 verified"}- 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/"+ # 离线包只随包压缩包:按资产名原样落盘,运行期由+ # `config::runtime::bundled_archive_filename` 按同一套常量推导出同一个文件名。+ stage() {+ local from="$1" name="$2"+ mkdir -p src-tauri/resources+ mv -f "$from" "src-tauri/resources/$name"}# 刻意不用关联数组:macOS runner 的 /bin/bash 是 3.2(`declare -A` 需要 bash 4),@@ -138,9 +109,7 @@ runs:verify "${workdir}/${node_name}" \"$(awk -v asset="${node_name}" '$2 == asset { print $1 }' "${workdir}/SHASUMS256.txt")" \"Node.js ${node_name}"- extract "${workdir}/${node_name}" "${workdir}/node"- flatten "${workdir}/node"- install_tree "${workdir}/node" "src-tauri/resources/node"+ stage "${workdir}/${node_name}" "$node_name"# dsh 内核:摘要来自同一 release 的 GitHub API,缺失即中止(无法校验完整性的# 内容不进离线包)。@@ -149,58 +118,115 @@ 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}"- extract "${workdir}/${dsh_name}" "${workdir}/dsh"- flatten "${workdir}/dsh"- install_tree "${workdir}/dsh" "src-tauri/resources/dsh"+ stage "${workdir}/${dsh_name}" "$dsh_name"# pnpm:纯 JS 发行,摘要取自 constants.rs 的固定值。fetch "$pnpm_url" "${workdir}/${pnpm_name}"verify "${workdir}/${pnpm_name}" "$pnpm_sha" "pnpm ${pnpm_name}"- extract "${workdir}/${pnpm_name}" "${workdir}/pnpm"- flatten "${workdir}/pnpm"- install_tree "${workdir}/pnpm" "src-tauri/resources/pnpm"+ stage "${workdir}/${pnpm_name}" "$pnpm_name"# 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}"- extract "${workdir}/${git_name}" "${workdir}/git"- flatten "${workdir}/git"- install_tree "${workdir}/git" "src-tauri/resources/git"+ stage "${workdir}/${git_name}" "$git_name"fi- node scripts/bundle-metadata.mjs --manifest --platform "$PLATFORM" --arch "$ARCH" $git_flag-- - name: Verify bundled entries+ - name: Verify staged archivesshell: bashenv:PLATFORM: ${{ inputs.platform }}+ ARCH: ${{ inputs.arch }}+ DSH_TAG: ${{ inputs.dsh-tag }}+ BUNDLE_GIT: ${{ inputs.bundle-git }}run: |set -euo pipefail- # 入口路径必须与清单 `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- # 清单没有指向 `$Resources/git` 时不能要求它存在(默认就不随包 MinGit)。- if grep -q '"managedRoot": "$Resources/git"' src-tauri/resources/manifest.jsonc; then- entries="$entries git/cmd/git.exe"++ with_git=false+ if [ "$PLATFORM" = "windows" ] && [ "$BUNDLE_GIT" = "true" ]; then+ with_git=truefi- 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=1+ git_flag=""+ [ "$with_git" = "true" ] && git_flag="--with-git"++ workdir="$(mktemp -d)"+ trap 'rm -rf "$workdir"' EXIT++ 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` 一致:解压结果只有唯一一层+ # 子目录时把内容上提,保证运行时根就是预期的那一层。+ 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+ }++ # 入口路径必须与清单 `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}"+ }++ 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 < <(node scripts/bundle-metadata.mjs --assets --platform "$PLATFORM" --arch "$ARCH" $git_flag)++ # 解压后的运行时树不得进安装包:那正是这次要消掉的体积。+ 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 1fidone- [ "$missing" -eq 0 ] || exit 1- 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 || true+ # 托管根必须留在 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 || truesed -n '/"dependencies"/,/^ }/p' src-tauri/resources/manifest.jsoncdiff --git a/.github/workflows/build-bundle-macos.yml b/.github/workflows/build-bundle-macos.ymlindex 3a676459..dc123d14 100644--- a/.github/workflows/build-bundle-macos.yml+++ b/.github/workflows/build-bundle-macos.yml@@ -110,12 +110,12 @@ jobs:exit 1fi- # 离线包把 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 打包与公证。+ # 离线包只把 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/**`)。- 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)"- [ "$signed" -gt 0 ] || { echo "::error::no unsigned Mach-O binaries found under src-tauri/resources"; exit 1; }+ # 离线包正常为 0:随包的运行时原生模块都在压缩包里,公证不会展开压缩包。# 必须同时产出 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 4d7b937d..496ec8c9 100644--- a/.github/workflows/release-bundle.yml+++ b/.github/workflows/release-bundle.yml@@ -1,10 +1,9 @@name: Build & Release (Offline Bundle)# 离线安装包:在普通发布流程(release.yml)成功后追加一次带资源构建。-# 产物把 Node.js 运行时、推荐 dsh 内核、pnpm 随安装包分发,并在构建期把-# `resources/manifest.jsonc` 的托管根改写成 `$Resources/...`,首次启动直接使用-# 随包资源,全程不联网。只随包启动 dsh 必需的资源:MinGit 默认不携带(git 托管的-# 能力在真正使用时才需要,`bundle_git` 可显式开启)。+# 产物把 Node.js 运行时、推荐 dsh 内核、pnpm 随安装包分发(安装目录里只放上游压缩包,+# 首次启动解压到 AppData),首次启动全程不联网。只随包启动 dsh 必需的资源:MinGit 默认+# 不携带(git 托管的能力在真正使用时才需要,`bundle_git` 可显式开启)。## 手动触发有两条路:# - 留空 `tag`:试跑。构建当前 ref,发一个 `test-<ref>-<run>` 测试预发布,不碰任何@@ -319,7 +318,7 @@ jobs:{echo "### Offline bundle assets"echo- echo "Bundled core: \`$DSH_TAG\` · resources mapped to \`\$Resources/{node,pnpm,dsh}\`"+ echo "Bundled core: \`$DSH_TAG\` · archives staged in \`resources/\` (unpacked into app data on first launch)"echofor asset in "${assets[@]}"; doecho "- \`$(basename "$asset")\`"diff --git a/.gitignore b/.gitignoreindex 905f3ca8..419ff405 100644--- a/.gitignore+++ b/.gitignore@@ -3,10 +3,11 @@ dist.build-plugins-tmpsrc-tauri/targetsrc-tauri/gen-src-tauri/resources/node-src-tauri/resources/dsh-src-tauri/resources/pnpm-src-tauri/resources/git+# 离线包随包的运行时压缩包(构建产物,按上游资产名落盘)+src-tauri/resources/node-v*+src-tauri/resources/pnpm-*.tgz+src-tauri/resources/deepseek-harness-pkg-*.zip+src-tauri/resources/MinGit-*.zipsrc-tauri/resources/preset-plugins/src-tauri/resources/internal-plugins/*.logdiff --git a/scripts/bundle-metadata.d.mts b/scripts/bundle-metadata.d.mtsindex fb6cab7c..70f42f82 100644--- a/scripts/bundle-metadata.d.mts+++ b/scripts/bundle-metadata.d.mts@@ -38,7 +38,6 @@ 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@@ -64,18 +63,12 @@ export function bundleAssets(input: {arch: BundleArchconstants: BundleConstantsdshTag: string- /** 随包 MinGit(默认 false;Windows 且清单未被改写时才需要) */+ /** 随包 MinGit(默认 false;Windows 且确实要随包 Git 时才需要) */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 6b0ac934..42176caa 100644--- a/scripts/bundle-metadata.mjs+++ b/scripts/bundle-metadata.mjs@@ -1,4 +1,4 @@-import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'+import { appendFileSync, readFileSync } 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::is_bundled_install`)。确有需要时用 `--with-git` 显式开启。+ * 见 `config::dependencies::bundled_core_dir`)。确有需要时用 `--with-git` 显式开启。*/export function bundleTargets(platform, { withGit = false } = {}) {const keys = ['node', 'pnpm', 'dsh']@@ -264,45 +264,6 @@ 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))@@ -345,13 +306,11 @@ function appendOutputs(outputPath, values) {}function parseArgs(argv) {- const args = { assets: false, manifest: false, platform: '', arch: '', withGit: false }+ const args = { assets: 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')@@ -384,13 +343,6 @@ 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,@@ -414,6 +366,5 @@ 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 119aece3..6a4ed141 100644--- a/src-tauri/resources/README.md+++ b/src-tauri/resources/README.md@@ -63,17 +63,20 @@ mapping entry**.}```-`managedRoot` (and every recorded mapping value) accepts three forms:+`managedRoot` (and every recorded mapping value) accepts these 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 |-Prefixes are case-insensitive and require the `/` boundary (`$resourcesfoo` is a plain-relative path).+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.| Section | Purpose || ------- | ------- |@@ -95,80 +98,62 @@ 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 a- `$AppData/...` / `$Resources/...` token as described above);+* a path → that root is used (an absolute location anywhere on disk, or an+ `$AppData/...` 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).-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.+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.### 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 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) |+`.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.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.--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.+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.### Preset plugins — `plugins.preset`diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex e801f312..d5d2a3ed 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -22,10 +22,11 @@"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 e1251f7f..ae99695f 100644--- a/src-tauri/src/config/dependencies.rs+++ b/src-tauri/src/config/dependencies.rs@@ -3,14 +3,15 @@//! 桌面端不再假设 node/pnpm/dsh 一定装在固定的 AppData 路径下,而是把每个依赖//! 的**安装根**记在映射表里://!-//! - 路径 → 使用该根(可为任意绝对路径,或 `resources/...` 令牌,见+//! - 路径 → 使用该根(任意绝对路径,或 `$AppData/...` 令牌,见//! [`super::manifest::resolve_location`]);//! - `null` → 由系统环境满足,桌面端不托管该依赖;//! - 键缺失 → 尚未探测,按清单的 `managedRoot` 默认托管根解析。//!//! 入口相对路径由清单 `dependencies.<key>.entry` 决定,因此「装在哪」与「入口形状」-//! 各有一处真值。将来做本地捆绑版只需把清单(或映射表)指向 `resources/*`,路径解析-//! 逻辑无需改动。写入单点收口到 [`record`],且内容不变时不落盘。+//! 各有一处真值。离线包(随包资源)只把压缩包放进安装目录,解压产物一律落在 AppData+//! 的托管根,因此路径解析逻辑与普通安装完全一致。写入单点收口到 [`record`],且内容+//! 不变时不落盘。use serde::{Deserialize, Serialize};use std::collections::BTreeMap;@@ -177,9 +178,8 @@ pub fn managed_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {/// 当前生效的依赖根:映射指定的根优先,否则回落清单默认托管根////// 映射表里的值同样按 [`manifest::resolve_location`] 解析:绝对路径原样使用(任意-/// 位置),`$AppData/...` / `$Resources/...` 指向数据目录 / 安装包资源根。因此本地-/// 捆绑 / 切换内核只需在映射表里写 `"dsh": "$Resources/dsh"` 或任意绝对路径,不必-/// 改动清单或重装。+/// 位置),`$AppData/...` 指向数据目录。因此切换内核只需在映射表里写任意绝对路径,+/// 不必改动清单或重装。////// 清单把 `dependencies.<key>.overridable` 声明为 false 时,映射表记录的位置一律/// 被忽略(本地捆绑版内核固定随包,不允许被运行时改写)。@@ -188,12 +188,15 @@ pub fn managed_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {/// 删除下载的核心目录都会留下悬空记录,继续采信会让就绪判定把可用资源判成缺失,/// 进而转去联网下载。此时回落到清单托管根——普通安装的托管根与记录值本就同路,/// 悬空回落不影响既有行为。+///+/// 落在**安装目录**里的记录同样不采信:随包资源版本(旧离线包)曾把依赖根写在+/// `resources/` 下,而现在解压产物一律落在 AppData,老记录只会把应用钉在旧树上。pub fn active_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {let overridable = manifest::dependency_spec(app, key).is_none_or(|spec| spec.overridable);if overridable {if let Some(Some(recorded)) = mapped(app, key) {let resolved = manifest::resolve_location(app, &recorded.to_string_lossy());- if resolved.exists() {+ if resolved.exists() && !is_inside_resource_root(app, &resolved) {return resolved;}}@@ -201,19 +204,32 @@ pub fn active_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {managed_root(app, key)}-/// 随包资源构建的随包核心根(`$Resources/dsh`);非随包构建为 None。+/// 路径是否落在安装包资源根之下(旧离线包把解压产物放在那里的历史遗留)+fn is_inside_resource_root<R: Runtime>(app: &AppHandle<R>, path: &Path) -> bool {+ manifest::resource_root(app).is_some_and(|root| path.starts_with(root))+}++/// 随包资源压缩包(离线包在安装目录 `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)+}++/// 随包资源构建的随包核心根(普通安装为 None)。////// 这类安装的运行时全部随安装包分发(见 `.github/actions/prepare-bundle-resources`),/// 运行期下载在离线机器上必然失败:启动就绪判定据此放宽「补不上的依赖」,核心面板据此/// 把随包内核作为「本地」项置顶。///-/// 判定按**清单托管根**而不是当前生效根:随包核心始终是安装目录里那一份,与该依赖-/// 当前是否被映射到别处的槽位无关。+/// 判定按**是否存在随包内核压缩包**,返回的却是托管根:离线包不再把解压产物放进安装目录,+/// 随包核心解压后就落在与普通安装相同的托管根上,因此「本地」标识与运行路径解耦。pub fn bundled_core_dir<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {- let root = manifest::resource_root(app)?;- let managed = managed_root(app, DEP_DSH);- // 资源根自身不算:只有把核心托管到 `$Resources/<name>` 才是随包构建。- (managed != root && managed.starts_with(&root)).then_some(managed)+ bundled_archive(app, DEP_DSH)?;+ Some(managed_root(app, DEP_DSH))}/// 入口相对路径(相对依赖根):清单 `dependencies.<key>.entry`,未声明时用内置默认@@ -363,7 +379,6 @@ 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)),@@ -373,11 +388,33 @@ 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, Some(&resources), declared),+ manifest::resolve_location_from(&base, 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}"+ );+ }+ }}diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rsindex 1c07fccc..be7a8e59 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 基础目录,或 `resources/...`)+ /// AppData 下的默认托管根(相对 AppData 基础目录)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 前缀。该前缀会随依赖托管根(`$Resources/dsh`-/// 等)拼进入口路径,而随包内核的入口要交给 node 当主模块:node 的+/// 在 Windows 上带 `\\?\` verbatim 前缀。该前缀会随依赖托管根拼进入口路径,+/// 而已装内核的入口要交给 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,43 +456,32 @@ pub fn dependency_spec<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<Depewith_manifest(app, |manifest| manifest.dependencies.get(key).cloned())?}-/// 位置令牌解析:`resources/...` 相对安装包资源根,其余相对 AppData 基础目录,-/// 绝对路径原样返回——依赖可以位于任意位置(AppData 托管、安装目录捆绑、-/// 或用户指定的其它盘符)。+/// 位置令牌解析:绝对路径原样返回,其余相对 AppData 基础目录——依赖可以托管在+/// AppData,也可以由用户指定到任意盘符。pub fn resolve_location<R: Runtime>(app: &AppHandle<R>, raw: &str) -> PathBuf {- resolve_location_from(- &super::runtime::get_base_dir(app),- resource_root(app).as_deref(),- raw,- )+ resolve_location_from(&super::runtime::get_base_dir(app), raw)}-/// 位置令牌解析(依赖可位于任意位置:AppData 托管、安装目录捆绑、或用户指定的其它盘符):+/// 位置令牌解析(依赖可位于任意位置:AppData 托管、或用户指定的其它盘符):////// - 绝对路径(`C:/...`、`/opt/...`)原样返回;/// - `$AppData/...`(大小写不敏感)= AppData 基础目录,debug 构建即 `<base>/dev` 的同级;-/// - `$Resources/...` = 安装包资源根(`resources/` 为等价旧写法),探测不到时回落 AppData;/// - 其余相对路径 = 相对 AppData 基础目录。-pub fn resolve_location_from(base: &Path, resource_root: Option<&Path>, raw: &str) -> PathBuf {+///+/// 早期离线包曾用 `$Resources/...`(旧写法 `resources/...`)把依赖托管根指进安装包资源目录,+/// 该令牌已废弃:解压产物一律落在 AppData,安装包内只留压缩包。+pub fn resolve_location_from(base: &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, resource_root, rest);+ return resolve_location_from(base, 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)}@@ -754,10 +743,9 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}- /// 随包资源构建(离线包)会把核心托管根指向 `$Resources/dsh`,该路径会作为- /// node 的主模块参数。`resource_dir()` 在 Windows 上是 canonicalize 结果(带- /// `\\?\`),而 node 的 resolveMainPath 解析 verbatim 路径会直接以- /// `EISDIR: ... lstat 'C:'` 退出,因此资源根必须先归一化。+ /// 用户可以把依赖托管根指向任意绝对路径(本地核心构建的常见做法)。`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");@@ -774,7 +762,6 @@ 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 {@@ -782,19 +769,15 @@ mod tests {};assert_eq!(- resolve_location_from(&base, Some(&resources), "dependencies/dsh"),+ resolve_location_from(&base, "dependencies/dsh"),base.join("dependencies/dsh"));assert_eq!(- resolve_location_from(&base, Some(&resources), "resources/dsh"),- resources.join("dsh")+ resolve_location_from(&base, r"dependencies\node"),+ base.join(r"dependencies\node"));assert_eq!(- resolve_location_from(&base, Some(&resources), r"resources\node"),- resources.join("node")- );- assert_eq!(- resolve_location_from(&base, Some(&resources), absolute),+ resolve_location_from(&base, absolute),PathBuf::from(absolute));}@@ -802,7 +785,6 @@ 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",@@ -815,29 +797,21 @@ mod tests {} else {base.clone()};- assert_eq!(- resolve_location_from(&base, Some(&resources), raw),- expected,- "{raw}"- );+ assert_eq!(resolve_location_from(&base, raw), expected, "{raw}");}+ // 已废弃的资源令牌按普通相对路径落到 AppData:旧安装包留下的+ // `"dsh": "$Resources/dsh"` 记录因此不再命中旧安装目录,回落到托管根重装。for raw in ["$Resources/dsh", "$resources/dsh", r"$RESOURCES\dsh"] {- assert_eq!(- resolve_location_from(&base, Some(&resources), raw),- resources.join("dsh"),- "{raw}"- );+ assert_eq!(resolve_location_from(&base, raw), base.join(raw), "{raw}");}-- // 资源根探测不到时回落 AppData,而不是相对当前工作目录assert_eq!(- resolve_location_from(&base, None, "$Resources/dsh"),- base.join("dsh")+ resolve_location_from(&base, "resources/dsh"),+ base.join("resources/dsh"));// 前缀不完整(不是令牌)时按普通相对路径处理assert_eq!(- resolve_location_from(&base, Some(&resources), "$resourcesfoo/dsh"),+ resolve_location_from(&base, "$resourcesfoo/dsh"),base.join("$resourcesfoo/dsh"));}diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex 3f0bc501..0c84cbaf 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -358,6 +358,22 @@ 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> {@@ -452,7 +468,10 @@ pub fn get_git_cmd_dir<R: Runtime>(_app_handle: &AppHandle<R>) -> Option<PathBufpub fn git_runtime_ready<R: Runtime>(app_handle: &AppHandle<R>) -> bool {find_system_git_binary().is_some()|| git_binary_works(&get_mingit_binary_path(app_handle))- || dependencies::bundled_core_dir(app_handle).is_some()+ // 随包构建放宽只在「没有随包 MinGit 压缩包」时成立:真随包了 MinGit,+ // 就必须让它走解压流程,否则放宽会把该任务跳过、Git 永远装不上。+ || (dependencies::bundled_core_dir(app_handle).is_some()+ && dependencies::bundled_archive(app_handle, dependencies::DEP_GIT).is_none())}/// 非 Windows 平台不属于本次空白 Windows 环境的自动配置范围。@@ -814,4 +833,42 @@ 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 03fadf78..ed3b6bb5 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,- /// 是否随安装包分发(离线包把内核托管到 `$Resources/dsh`):核心面板把它置顶并- /// 标记「本地」,且不提供卸载——它是内网/离线环境唯一的兜底内核。+ /// 是否随安装包分发(离线包在安装目录里随包内核压缩包,解压到 AppData 托管根):+ /// 核心面板把它置顶并标记「本地」,且不提供卸载——它是内网/离线环境唯一的兜底内核。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 6ca06a61..9400fbb8 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -4,9 +4,10 @@//! 历史版本存放在 `dependencies/<tag>` 槽位,切换/卸载依赖既有版本行。本地//! 核心的探测见 [`super::local`],来源判定与活动入口见 [`super::source`]。//!-//! 随包资源构建(离线包)不适用上面的目录互换:随包内核必须留在安装目录里-//! (`$Resources/dsh`,见 [`config::dependencies::bundled_core_dir`]),它在面板里-//! 作为固定置顶的「本地」行存在,切换只是把 `dsh` 依赖根指向目标槽位或指回随包内核。+//! 随包资源构建(离线包)不适用上面的目录互换:随包内核由安装目录里的压缩包解压而来,+//! 落在 `dependencies/dsh` 托管根上,在面板里作为固定置顶的「本地」行存在(见+//! [`config::dependencies::bundled_core_dir`]),切换只是把 `dsh` 依赖根指向目标槽位+//! 或指回随包内核。use crate::config;use crate::service::{download, fs_guard, workflow};@@ -24,9 +25,9 @@ const BUNDLED_CORE_ID: &str = "app-bundled";/// `dependencies` 目录(下载的核心槽位与普通安装的 `dsh` 激活目录的共同父级)。///-/// 恒落在应用数据目录之下:槽位是桌面端自己下载的产物,即使清单把激活核心托管到安装-/// 包资源(离线包 `$Resources/dsh`)也不能让下载产物写进安装目录——那里在 macOS `.app`-/// 上是签名的只读内容、在 Linux deb 里属于 root,且会随应用升级被覆盖。+/// 恒落在应用数据目录之下:槽位是桌面端自己下载的产物,绝不能让下载产物写进安装目录+/// ——那里在 macOS `.app` 上是签名的只读内容、在 Linux deb 里属于 root,且会随应用+/// 升级被覆盖。fn dependencies_dir(app_handle: &AppHandle) -> PathBuf {config::get_base_dir(app_handle).join("dependencies")}@@ -432,7 +433,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());};@@ -506,10 +507,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}"))?;- // 随包资源构建:随包内核必须留在安装目录(`$Resources/dsh`),不能像普通安装那样- // 把「激活目录 ↔ 槽位目录」互换——那会把安装包资源搬进 AppData,也会让应用升级- // 覆盖掉用户选中的版本。改为把 `dsh` 依赖根指向槽位本身:槽位本就在 AppData 里,- // 切回随包内核只是把根指回去(见 `set_active` 的 `app-bundled` 分支)。+ // 随包资源构建:随包内核解压在 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/workflow/install.rs b/src-tauri/src/service/workflow/install.rsindex 2de83140..6ddf5192 100644--- a/src-tauri/src/service/workflow/install.rs+++ b/src-tauri/src/service/workflow/install.rs@@ -52,7 +52,10 @@ pub async fn install(// 必须在下载前解析 release 元数据:下载地址和摘要必须属于同一固定 tag。// 若先下载 latest、再因 API 限流从 Atom/HTML 解析 tag,latest 在两次请求间// 发生切换就会把另一份资产拿来匹配摘要,最终触发 INTEGRITY_CHECK_FAILED。- let dsh_missing = !download::Dsh.check_installed(app_handle);+ // 离线包(随包资源)把内核压缩包放进安装目录,此时无需任何联网元数据。+ 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();if dsh_latest.is_none() && dsh_missing {for attempt in 0..3 {let metadata = match config::recommended_dsh_version(app_handle) {@@ -94,11 +97,14 @@ pub async fn install(let kind = task.kind();log::debug!("Processing task {}/{}", index + 1, tasks.len());// 已安装但版本/commit 与最新 release 不一致时强制重新下载。+ // 随包内核压缩包例外:本地压缩包就是权威版本,按 release 判定「过期」会把+ // 随包旧核心每次启动都重解压一遍。// 版本优先(与 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);@@ -132,70 +138,91 @@ pub async fn install(log::info!("Task {} not installed, starting installation", index + 1);- // 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?+ // 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)}- 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(),- )+ 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::verify_sha256(&buffer, &expected_digest)?;- log::info!("Download integrity verified for task {}", index + 1);- tracker.end_phase();// 2. 解压tracker.start_phase(@@ -213,9 +240,12 @@ pub async fn install(// 记录本次安装对应的 release tag 与 commit,供下次启动比对if kind == download::InstallKind::Dsh {dsh_updated = true;- 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());+ // 随包压缩包装的不是 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());+ }}}}diff --git a/src/types/core.ts b/src/types/core.tsindex e82755aa..20b071f4 100644--- a/src/types/core.ts+++ b/src/types/core.ts@@ -24,7 +24,7 @@ export interface HarnessCore {aboveRecommended: boolean/** 本地存在但 pkg 仓库已不再提供的历史槽位 */orphaned: boolean- /** 随安装包分发的内核(离线包 `$Resources/dsh`):面板置顶并标记「本地」,不可卸载 */+ /** 随安装包分发的内核(离线包随包压缩包解压到 AppData 托管根):面板置顶并标记「本地」,不可卸载 */bundled: booleanrecommendedVersion: string | nullerror?: string | nulldiff --git a/test/bundle-metadata.test.ts b/test/bundle-metadata.test.tsindex 3f58624a..7f4a7bbf 100644--- a/test/bundle-metadata.test.ts+++ b/test/bundle-metadata.test.ts@@ -1,6 +1,3 @@-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'@@ -164,106 +161,17 @@ describe('jsonc stripping', () => {})})-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 })+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('/')}})})