Skip to content

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

feat(bundle): 离线安装包:随包分发 Node / dsh / pnpm / MinGit 资源

hairyf3a1e6048b12b
diff --git a/.github/actions/prepare-bundle-resources/action.yml b/.github/actions/prepare-bundle-resources/action.yml
new file mode 100644
index 00000000..6ddce523
--- /dev/null
+++ b/.github/actions/prepare-bundle-resources/action.yml
@@ -0,0 +1,187 @@
+name: Prepare offline bundle resources
+description: >-
+ Download and unpack the Node.js runtime, the packaged dsh core, pnpm (and MinGit
+ on Windows) 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:
+ description: Target platform (windows | macos | linux)
+ required: true
+ arch:
+ description: Target architecture (x64 | arm64)
+ required: true
+ dsh-tag:
+ description: deepseek-harness-pkg release tag bundled as the built-in core
+ required: true
+
+runs:
+ using: composite
+ steps:
+ - name: Download and unpack bundled runtimes
+ shell: bash
+ env:
+ PLATFORM: ${{ inputs.platform }}
+ ARCH: ${{ inputs.arch }}
+ DSH_TAG: ${{ inputs.dsh-tag }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+
+ workdir="$(mktemp -d)"
+ trap 'rm -rf "$workdir"' EXIT
+
+ sha256_of() {
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "$1" | awk '{print $1}'
+ else
+ shasum -a 256 "$1" | awk '{print $1}'
+ fi
+ }
+
+ fetch() {
+ local url="$1" out="$2" attempt
+ for attempt in 1 2 3 4; do
+ if curl -fL --retry 3 --retry-delay 3 --connect-timeout 30 --max-time 7200 -o "$out" "$url"; then
+ return 0
+ fi
+ echo "download failed (attempt ${attempt}/4): ${url}"
+ sleep 10
+ done
+ echo "::error::failed to download ${url}"
+ return 1
+ }
+
+ verify() {
+ local file="$1" expected="$2" label="$3" actual
+ if [ -z "$expected" ]; then
+ echo "::error::no trusted SHA-256 available for ${label}"
+ return 1
+ fi
+ actual="$(sha256_of "$file")"
+ if [ "$actual" != "$expected" ]; then
+ echo "::error::${label} SHA-256 mismatch: expected ${expected}, got ${actual}"
+ return 1
+ fi
+ 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/"
+ }
+
+ # 刻意不用关联数组:macOS runner 的 /bin/bash 是 3.2(`declare -A` 需要 bash 4),
+ # 而 `shell: bash` 会解析到它,用了会让 macOS 离线包构建在下载前就失败。
+ while IFS='|' read -r key name url sha sha_url; do
+ [ -n "${key:-}" ] || continue
+ case "$key" in
+ node) node_name="$name"; node_url="$url"; node_sha_url="$sha_url" ;;
+ dsh) dsh_name="$name"; dsh_url="$url" ;;
+ pnpm) pnpm_name="$name"; pnpm_url="$url"; pnpm_sha="$sha" ;;
+ git) git_name="$name"; git_url="$url"; git_sha="$sha" ;;
+ esac
+ done < <(node scripts/bundle-metadata.mjs --assets --platform "$PLATFORM" --arch "$ARCH")
+
+ # Node.js 运行时:摘要取自官方 SHASUMS256.txt,与 assets 同源同版本。
+ fetch "$node_url" "${workdir}/${node_name}"
+ fetch "$node_sha_url" "${workdir}/SHASUMS256.txt"
+ 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"
+
+ # dsh 内核:摘要来自同一 release 的 GitHub API,缺失即中止(无法校验完整性的
+ # 内容不进离线包)。
+ fetch "$dsh_url" "${workdir}/${dsh_name}"
+ dsh_digest="$(gh api "repos/dsh-tauri-desk/deepseek-harness-pkg/releases/tags/${DSH_TAG}" \
+ --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"
+
+ # 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"
+
+ # MinGit:仅 Windows 随包,摘要取自 constants.rs(内网环境补装必然失败,
+ # 系统 Git 缺失时它就是唯一可用的 Git)。
+ if [ -n "${git_name:-}" ]; then
+ fetch "$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"
+ fi
+
+ node scripts/bundle-metadata.mjs --manifest --platform "$PLATFORM" --arch "$ARCH"
+
+ - name: Verify bundled entries
+ shell: bash
+ env:
+ PLATFORM: ${{ inputs.platform }}
+ run: |
+ set -euo pipefail
+ # 入口路径必须与清单 `dependencies.<key>.entry` 一致:解压层级(flatten)
+ # 或资产布局变化会让应用在启动时判定「依赖缺失」并转去联网下载。
+ entries="node/node.exe pnpm/bin/pnpm.cjs dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"
+ if [ "$PLATFORM" != "windows" ]; then
+ entries="node/bin/node pnpm/bin/pnpm.cjs dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"
+ else
+ 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=1
+ fi
+ done
+ [ "$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
+ sed -n '/"dependencies"/,/^ }/p' src-tauri/resources/manifest.jsonc
diff --git a/.github/workflows/build-bundle-linux.yml b/.github/workflows/build-bundle-linux.yml
new file mode 100644
index 00000000..ead5fd6d
--- /dev/null
+++ b/.github/workflows/build-bundle-linux.yml
@@ -0,0 +1,91 @@
+name: Reusable Linux Offline Bundle Build
+
+on:
+ workflow_call:
+ inputs:
+ source_ref:
+ required: true
+ type: string
+ dsh_tag:
+ required: true
+ type: string
+ secrets:
+ TAURI_SIGNING_PRIVATE_KEY:
+ required: false
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD:
+ required: false
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Build offline bundle (linux)
+ # 22.04 的 glibc/WebKitGTK 产物兼容 Ubuntu 22.04 及更新版本。
+ runs-on: ubuntu-22.04
+ timeout-minutes: 180
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v7
+ with:
+ ref: ${{ inputs.source_ref }}
+ persist-credentials: false
+
+ - name: Setup Node.js and pnpm
+ uses: ./.github/actions/setup-node-pnpm
+
+ - name: Install Rust stable
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+
+ - name: Install system dependencies
+ shell: bash
+ run: |
+ apt_ok=0
+ for i in {1..3}; do
+ if timeout 180 sudo apt-get update \
+ -o Acquire::Retries=5 \
+ -o Acquire::http::Timeout=60 \
+ -o Acquire::https::Timeout=60 \
+ -o Acquire::ftp::Timeout=60; then
+ apt_ok=1
+ break
+ fi
+ echo "apt-get update 失败,准备重试 ($i/3)..."
+ sleep 10
+ done
+ [ "$apt_ok" = "1" ] || { echo "apt-get update 连续 3 次失败,中止"; exit 1; }
+ sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf unzip
+
+ - name: Install frontend dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Prepare bundled resources
+ uses: ./.github/actions/prepare-bundle-resources
+ with:
+ platform: linux
+ arch: x64
+ dsh-tag: ${{ inputs.dsh_tag }}
+
+ # 只出 deb:AppImage 由 linuxdeploy 打包,而离线包往 AppDir 里塞了 300 MiB /
+ # 一万余文件,linuxdeploy 在这种规模的 AppDir 上直接失败(普通安装包没有这份
+ # 资源所以不受影响)。内网离线部署本来也以 deb 为主;AppImage 留作后续单独排查。
+ #
+ # 已知限制:deb 把资源装到 /usr/lib/<product>/(root 所有),随包 dsh 内核因此
+ # 只读。桌面端每次启动会往内核目录写插件入口链接与 JS 补丁(见
+ # `service::core::runtime::link_required_plugins`),非 root 用户运行时会失败。
+ # 需要 root 安装后补齐目录权限,或改用 Windows/macOS 产物。
+ - name: Build offline packages
+ env:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+ run: pnpm tauri build --bundles deb
+
+ - name: Upload build outputs
+ uses: actions/upload-artifact@v6
+ with:
+ name: release-bundle-linux
+ path: src-tauri/target/release/bundle/deb/*.deb
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/build-bundle-macos.yml b/.github/workflows/build-bundle-macos.yml
new file mode 100644
index 00000000..3a676459
--- /dev/null
+++ b/.github/workflows/build-bundle-macos.yml
@@ -0,0 +1,216 @@
+name: Reusable macOS Offline Bundle Build
+
+on:
+ workflow_call:
+ inputs:
+ platform_filter:
+ required: false
+ type: string
+ default: all
+ source_ref:
+ required: true
+ type: string
+ dsh_tag:
+ required: true
+ type: string
+ secrets:
+ TAURI_SIGNING_PRIVATE_KEY:
+ required: false
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD:
+ required: false
+ APPLE_CERTIFICATE:
+ required: true
+ APPLE_CERTIFICATE_PASSWORD:
+ required: true
+ APPLE_ID:
+ required: true
+ APPLE_PASSWORD:
+ required: true
+ APPLE_TEAM_ID:
+ required: true
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Build offline bundle (${{ matrix.id }})
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - id: macos-aarch64
+ target: aarch64-apple-darwin
+ arch: arm64
+ - id: macos-x86_64
+ target: x86_64-apple-darwin
+ arch: x64
+ runs-on: macos-latest
+ timeout-minutes: 180
+ steps:
+ - name: Filter target architecture
+ id: check
+ shell: bash
+ env:
+ PLATFORM_FILTER: ${{ inputs.platform_filter }}
+ PLATFORM_ID: ${{ matrix.id }}
+ run: |
+ should_run=true
+ if [ "$PLATFORM_FILTER" != "all" ] && [ "$PLATFORM_FILTER" != "$PLATFORM_ID" ]; then
+ should_run=false
+ fi
+ echo "should_run=$should_run" >> "$GITHUB_OUTPUT"
+
+ - name: Checkout repository
+ if: steps.check.outputs.should_run == 'true'
+ uses: actions/checkout@v7
+ with:
+ ref: ${{ inputs.source_ref }}
+ persist-credentials: false
+
+ - name: Setup Node.js and pnpm
+ if: steps.check.outputs.should_run == 'true'
+ uses: ./.github/actions/setup-node-pnpm
+
+ - name: Install Rust stable
+ if: steps.check.outputs.should_run == 'true'
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+ targets: ${{ matrix.target }}
+
+ - name: Install frontend dependencies
+ if: steps.check.outputs.should_run == 'true'
+ run: pnpm install --frozen-lockfile
+
+ - name: Prepare bundled resources
+ if: steps.check.outputs.should_run == 'true'
+ uses: ./.github/actions/prepare-bundle-resources
+ with:
+ platform: macos
+ arch: ${{ matrix.arch }}
+ dsh-tag: ${{ inputs.dsh_tag }}
+
+ - name: Validate signing secrets
+ if: steps.check.outputs.should_run == 'true'
+ shell: bash
+ env:
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ run: |
+ missing=()
+ for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID; do
+ [ -z "${!name}" ] && missing+=("$name")
+ done
+ if [ "${#missing[@]}" -ne 0 ]; then
+ echo "::error::Missing macOS signing secrets: ${missing[*]}"
+ exit 1
+ fi
+
+ # 离线包把 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 binaries
+ if: steps.check.outputs.should_run == 'true'
+ shell: bash
+ env:
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ run: |
+ set -euo pipefail
+ keychain="$RUNNER_TEMP/bundle-signing.keychain-db"
+ keychain_password="$(openssl rand -base64 32)"
+ echo "$APPLE_CERTIFICATE" | base64 --decode > "$RUNNER_TEMP/bundle-cert.p12"
+
+ security create-keychain -p "$keychain_password" "$keychain"
+ security set-keychain-settings -lut 3600 "$keychain"
+ security unlock-keychain -p "$keychain_password" "$keychain"
+ security import "$RUNNER_TEMP/bundle-cert.p12" -k "$keychain" \
+ -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
+ security set-key-partition-list -S apple-tool:,apple: -k "$keychain_password" "$keychain" >/dev/null
+ security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"')
+
+ identity="$(security find-identity -v -p codesigning "$keychain" \
+ | awk -F'"' '/Developer ID Application/{print $2; exit}')"
+ if [ -z "$identity" ]; then
+ echo "::error::no Developer ID Application identity found in the imported certificate"
+ exit 1
+ fi
+
+ # 只挑可能是 Mach-O 的候选(可执行位或已知扩展名)再用 file 确认,避免对上万个
+ # 文件逐个调用 file。
+ #
+ # 已经是 Developer ID 签名的(nodejs.org 的 node 二进制自带签名与 JIT 相关
+ # entitlement)原样保留:重签会丢掉 entitlement,节点进程在 hardened runtime
+ # 下会因 JIT 被拒直接崩。其余 ad-hoc / 未签名的才补签,并在存在 entitlement 时
+ # 一并保留。
+ signed=0
+ kept=0
+ while IFS= read -r file; do
+ [ -n "$file" ] || continue
+ case "$(file -b "$file")" in
+ *Mach-O*) ;;
+ *) continue ;;
+ esac
+ authority="$(codesign -dv --verbose=2 "$file" 2>&1 | awk -F= '/^Authority=/{print $2; exit}' || true)"
+ if [ "${authority#Developer ID Application}" != "$authority" ]; then
+ kept=$((kept + 1))
+ continue
+ fi
+ preserve=""
+ if codesign -d --entitlements - "$file" 2>/dev/null | grep -q '<key>'; then
+ preserve="--preserve-metadata=entitlements"
+ fi
+ codesign --force --options runtime --timestamp $preserve \
+ --keychain "$keychain" --sign "$identity" "$file"
+ signed=$((signed + 1))
+ 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; }
+
+ # 必须同时产出 app:只给 `--bundles dmg` 时 tauri 会把 .app 当中间产物,打完 dmg
+ # 就删掉它(日志里的 `Cleaning .../bundle/macos/<name>.app`),后面的签名/公证
+ # 校验步骤便找不到目标。普通安装包不带 --bundles、走 targets: all,两者都产出。
+ - name: Build offline package
+ if: steps.check.outputs.should_run == 'true'
+ env:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ run: pnpm tauri build --target ${{ matrix.target }} --bundles app,dmg
+
+ - name: Verify signature and notarization
+ if: steps.check.outputs.should_run == 'true'
+ shell: bash
+ run: |
+ app_path="$(find "src-tauri/target/${{ matrix.target }}/release/bundle/macos" -type d -name '*.app' -print -quit)"
+ if [ -z "$app_path" ]; then
+ echo '::error::Built macOS app bundle was not found'
+ exit 1
+ fi
+ codesign --verify --deep --strict --verbose=2 "$app_path"
+ xcrun stapler validate "$app_path"
+ spctl --assess --type execute --verbose=4 "$app_path"
+
+ # 已知限制:.app 若被拖进 /Applications 且不属于当前用户(或来自下载的只读卷),
+ # 随包 dsh 内核同样不可写,桌面端启动时的插件入口链接会失败。用户目录自持的
+ # .app 不受影响。
+ - name: Upload build output
+ if: steps.check.outputs.should_run == 'true'
+ uses: actions/upload-artifact@v6
+ with:
+ name: release-bundle-${{ matrix.id }}
+ path: src-tauri/target/${{ matrix.target }}/release/bundle/dmg/*.dmg
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/build-bundle-windows.yml b/.github/workflows/build-bundle-windows.yml
new file mode 100644
index 00000000..ac080407
--- /dev/null
+++ b/.github/workflows/build-bundle-windows.yml
@@ -0,0 +1,81 @@
+name: Reusable Windows Offline Bundle Build
+
+on:
+ workflow_call:
+ inputs:
+ source_ref:
+ required: true
+ type: string
+ dsh_tag:
+ required: true
+ type: string
+ secrets:
+ TAURI_SIGNING_PRIVATE_KEY:
+ required: false
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD:
+ required: false
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Build offline bundle (windows)
+ runs-on: windows-latest
+ # 离线包要下载 Node/dsh/MinGit 并压缩数百 MB 资源,远慢于普通构建。
+ timeout-minutes: 180
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v7
+ with:
+ ref: ${{ inputs.source_ref }}
+ persist-credentials: false
+
+ - name: Setup Node.js and pnpm
+ uses: ./.github/actions/setup-node-pnpm
+
+ - name: Install Rust stable
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+
+ - name: Install frontend dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Prepare bundled resources
+ uses: ./.github/actions/prepare-bundle-resources
+ with:
+ platform: windows
+ arch: x64
+ dsh-tag: ${{ inputs.dsh_tag }}
+
+ # 内网机器上的 WebView2 只能靠安装包自带:默认的 downloadBootstrapper 会在
+ # 安装时去微软下载运行时,白名单环境里直接失败。offlineInstaller 把完整的
+ # WebView2 安装器打进 exe(约 +130 MB),安装全程不联网。
+ - name: Prepare offline WebView2 config
+ shell: bash
+ run: |
+ cat > offline-webview2.tmp.json <<'EOF'
+ {
+ "bundle": {
+ "windows": {
+ "webviewInstallMode": { "type": "offlineInstaller", "silent": true }
+ }
+ }
+ }
+ EOF
+
+ # 只出 NSIS:离线包资源有数万个文件,WiX/MSI 既慢又受 2 GB cab 上限约束。
+ - name: Build offline installer
+ env:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+ run: pnpm tauri build --bundles nsis --config offline-webview2.tmp.json
+
+ - name: Upload build outputs
+ uses: actions/upload-artifact@v6
+ with:
+ name: release-bundle-windows
+ path: src-tauri/target/release/bundle/nsis/*.exe
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/release-bundle.yml b/.github/workflows/release-bundle.yml
new file mode 100644
index 00000000..0518565f
--- /dev/null
+++ b/.github/workflows/release-bundle.yml
@@ -0,0 +1,308 @@
+name: Build & Release (Offline Bundle)
+
+# 离线安装包:在普通发布流程(release.yml)成功后追加一次带资源构建。
+# 产物把 Node.js 运行时、推荐 dsh 内核、pnpm(Windows 另含 MinGit)随安装包分发,
+# 并在构建期把 `resources/manifest.jsonc` 的托管根改写成 `$Resources/...`,首次
+# 启动直接使用随包资源,全程不联网。
+#
+# 手动触发有两条路:
+# - 留空 `tag`:试跑。构建当前 ref,发一个 `test-<ref>-<run>` 测试预发布,不碰任何
+# 已发布的 release(与 release.yml 的手动触发约定一致)。
+# - 指定 `tag`:为已有 release 补构建。必须**从该 tag 指向的提交**触发(ref 选对应
+# tag),因为构建源恒为触发提交,而产物是 `--clobber` 上传的。
+on:
+ workflow_run:
+ workflows: ['Build & Release']
+ types: [completed]
+ workflow_dispatch:
+ inputs:
+ platform_filter:
+ description: 选择需要打包的平台
+ required: true
+ default: all
+ type: choice
+ options:
+ - all
+ - macos-aarch64
+ - macos-x86_64
+ - windows
+ - linux
+ tag:
+ description: 目标 release tag(留空 = 发测试预发布;指定时需从该 tag 的提交触发)
+ required: false
+ default: ''
+ type: string
+
+permissions:
+ # 写权限只给真正上传产物的 finalize;prepare 与三个可复用构建只需要读。
+ contents: read
+
+concurrency:
+ group: release-bundle-${{ github.event.workflow_run.head_branch || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ prepare:
+ name: Prepare Offline Bundle
+ # workflow_run 会为 release.yml 的每一次结束(含失败/取消/全部 job 被跳过)触发。
+ # 被跳过的 job 报告的是 success,因此只看 conclusion 会接受「fork PR 被关闭但未合并」
+ # 那种整轮全跳过的运行——那样下面就会 checkout 到 fork 的 head_sha,并在带写权限与
+ # 签名密钥的构建里执行它。必须同时要求触发运行来自本仓库。
+ if: >-
+ github.event_name == 'workflow_dispatch' ||
+ (github.event.workflow_run.conclusion == 'success' &&
+ github.event.workflow_run.head_repository.full_name == github.repository)
+ runs-on: ubuntu-latest
+ outputs:
+ should_build: ${{ steps.release.outputs.should_build }}
+ tag: ${{ steps.release.outputs.tag }}
+ prerelease: ${{ steps.release.outputs.prerelease }}
+ version: ${{ steps.release.outputs.version }}
+ source_ref: ${{ steps.release.outputs.source_ref }}
+ dsh_tag: ${{ steps.meta.outputs.dsh_tag }}
+ steps:
+ - name: Checkout triggering commit
+ uses: actions/checkout@v7
+ with:
+ # 构建源恒为触发提交:workflow_run 用触发运行时的 head_sha(release.yml 真正
+ # 构建的提交),手动触发用所选 ref。真实发布路径下 tag 必须指向同一个提交
+ # (见 Resolve release tag),因此工作区、元数据、产物版本天然同源。
+ ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}
+ fetch-depth: 0
+ # 不把仓库写令牌留在 .git/config 里(后续步骤不需要 push)。
+ persist-credentials: false
+
+ - name: Setup Node.js and pnpm
+ uses: ./.github/actions/setup-node-pnpm
+
+ - name: Resolve release tag
+ id: release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPO: ${{ github.repository }}
+ EVENT_NAME: ${{ github.event_name }}
+ RUN_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
+ TAG_INPUT: ${{ inputs.tag }}
+ REF_NAME: ${{ github.ref_name }}
+ RUN_NUMBER: ${{ github.run_number }}
+ SOURCE_REF: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}
+ run: |
+ set -euo pipefail
+ version="$(node -p "require('./package.json').version")"
+ tag="$TAG_INPUT"
+ prerelease=false
+ manual=false
+ [ "$EVENT_NAME" = "workflow_dispatch" ] && manual=true
+
+ emit() {
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "prerelease=$prerelease" >> "$GITHUB_OUTPUT"
+ echo "source_ref=$SOURCE_REF" >> "$GITHUB_OUTPUT"
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+ }
+ # 自动路径(workflow_run 为每一次成功运行都触发,含测试发布)只跳过并告警;
+ # 手动指定了 tag 说明用户有明确目标,静默跳过会让人以为构建成功。
+ skip() {
+ emit
+ echo "should_build=false" >> "$GITHUB_OUTPUT"
+ echo "::warning::$1"
+ exit 0
+ }
+ reject() {
+ echo "::error::$1"
+ exit 1
+ }
+
+ if [ "$manual" = true ] && [ -z "$tag" ]; then
+ # 手动触发且未指定 tag = 试跑:不碰任何已发布的 release,按 release.yml
+ # 的手动触发约定发一个测试预发布。
+ tag="test-${REF_NAME}-${RUN_NUMBER}"
+ prerelease=true
+ emit
+ echo "should_build=true" >> "$GITHUB_OUTPUT"
+ echo "offline bundle test release: $tag ($version) from $SOURCE_REF"
+ exit 0
+ fi
+
+ if [ -z "$tag" ] && [[ "$RUN_HEAD_BRANCH" == v* ]]; then
+ tag="$RUN_HEAD_BRANCH"
+ fi
+ if [ -z "$tag" ]; then
+ tag="v$version"
+ fi
+
+ gh release view "$tag" >/dev/null 2>&1 \
+ || skip "release $tag does not exist, skipping the offline bundle build"
+
+ # 构建源恒为触发提交,而 finalize 是 `gh release upload --clobber`:必须确认
+ # 目标 release 的 tag 正好指向这个提交,否则就会用别的提交构建的产物覆盖该版本
+ # 已发布的离线包。tag 解析不到也算不安全——GitHub 会在 tag ref 被删除后保留
+ # release 记录,那时 `gh release view` 成功而 `git rev-parse` 失败。
+ tag_commit="$(git rev-parse --verify --quiet "${tag}^{commit}" || true)"
+ if [ -z "$tag_commit" ]; then
+ hint="cannot resolve tag $tag locally"
+ elif [ "$tag_commit" != "$SOURCE_REF" ]; then
+ hint="tag $tag points at $tag_commit but this run builds $SOURCE_REF"
+ else
+ emit
+ echo "should_build=true" >> "$GITHUB_OUTPUT"
+ echo "offline bundle target release: $tag ($version) from $SOURCE_REF"
+ exit 0
+ fi
+
+ if [ "$manual" = true ]; then
+ reject "$hint; dispatch this workflow from the release commit (pick the $tag tag as the ref), or clear the tag input to publish a test prerelease instead"
+ fi
+ skip "$hint; skipping the offline bundle build"
+
+ - name: Resolve bundled core tag
+ id: meta
+ if: steps.release.outputs.should_build == 'true'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: node scripts/bundle-metadata.mjs
+
+ build-macos:
+ name: Build macOS Offline Bundle
+ needs: prepare
+ if: >-
+ needs.prepare.result == 'success' &&
+ needs.prepare.outputs.should_build == 'true' &&
+ (github.event_name != 'workflow_dispatch' ||
+ inputs.platform_filter == 'all' ||
+ startsWith(inputs.platform_filter, 'macos-'))
+ uses: ./.github/workflows/build-bundle-macos.yml
+ with:
+ platform_filter: ${{ github.event_name == 'workflow_dispatch' && inputs.platform_filter || 'all' }}
+ source_ref: ${{ needs.prepare.outputs.source_ref }}
+ dsh_tag: ${{ needs.prepare.outputs.dsh_tag }}
+ secrets:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+ APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+ APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+
+ build-windows:
+ name: Build Windows Offline Bundle
+ needs: prepare
+ if: >-
+ needs.prepare.result == 'success' &&
+ needs.prepare.outputs.should_build == 'true' &&
+ (github.event_name != 'workflow_dispatch' ||
+ inputs.platform_filter == 'all' ||
+ inputs.platform_filter == 'windows')
+ uses: ./.github/workflows/build-bundle-windows.yml
+ with:
+ source_ref: ${{ needs.prepare.outputs.source_ref }}
+ dsh_tag: ${{ needs.prepare.outputs.dsh_tag }}
+ secrets:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+
+ build-linux:
+ name: Build Linux Offline Bundle
+ needs: prepare
+ if: >-
+ needs.prepare.result == 'success' &&
+ needs.prepare.outputs.should_build == 'true' &&
+ (github.event_name != 'workflow_dispatch' ||
+ inputs.platform_filter == 'all' ||
+ inputs.platform_filter == 'linux')
+ uses: ./.github/workflows/build-bundle-linux.yml
+ with:
+ source_ref: ${{ needs.prepare.outputs.source_ref }}
+ dsh_tag: ${{ needs.prepare.outputs.dsh_tag }}
+ secrets:
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+
+ finalize:
+ name: Publish Offline Installers
+ needs: [prepare, build-macos, build-windows, build-linux]
+ if: >-
+ always() && needs.prepare.result == 'success' &&
+ needs.prepare.outputs.should_build == 'true' &&
+ ((github.event_name != 'workflow_dispatch' &&
+ needs.build-macos.result == 'success' &&
+ needs.build-windows.result == 'success' &&
+ needs.build-linux.result == 'success') ||
+ (github.event_name == 'workflow_dispatch' &&
+ (needs.build-macos.result == 'success' || needs.build-macos.result == 'skipped') &&
+ (needs.build-windows.result == 'success' || needs.build-windows.result == 'skipped') &&
+ (needs.build-linux.result == 'success' || needs.build-linux.result == 'skipped')))
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - name: Download build outputs
+ uses: actions/download-artifact@v7
+ with:
+ pattern: release-bundle-*
+ path: release-assets
+
+ # 统一命名为 Deepseek.Harness.Desktop_Bundle_<version>.<ext>:与普通安装包
+ # (Tauri 默认名)区分,且同一 release 内不会重名。macOS 两个架构的产物
+ # 扩展名相同,必须带架构后缀才不会互相覆盖。
+ - name: Rename offline installers
+ env:
+ VERSION: ${{ needs.prepare.outputs.version }}
+ run: |
+ set -euo pipefail
+ mkdir -p upload
+ shopt -s nullglob
+ for dir in release-assets/*/; do
+ artifact="$(basename "$dir")"
+ suffix=""
+ case "$artifact" in
+ *macos-aarch64*) suffix="_aarch64" ;;
+ *macos-x86_64*) suffix="_x64" ;;
+ esac
+ for file in "$dir"*; do
+ [ -f "$file" ] || continue
+ base="$(basename "$file")"
+ ext="${base##*.}"
+ cp "$file" "upload/Deepseek.Harness.Desktop_Bundle_${VERSION}${suffix}.${ext}"
+ done
+ done
+ find upload -type f -print | sort
+
+ - name: Verify offline installers
+ run: |
+ set -euo pipefail
+ [ -n "$(find upload -type f -print -quit)" ] || {
+ echo '::error::No offline installers were produced'
+ exit 1
+ }
+
+ - name: Upload assets to release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ # finalize 未 checkout,gh 无法从 .git 推断仓库,需显式指定。
+ GH_REPO: ${{ github.repository }}
+ RELEASE_TAG: ${{ needs.prepare.outputs.tag }}
+ PRERELEASE: ${{ needs.prepare.outputs.prerelease }}
+ DSH_TAG: ${{ needs.prepare.outputs.dsh_tag }}
+ run: |
+ set -euo pipefail
+ # 试跑路径的 test-* release 还不存在,按 release.yml 的手动触发约定新建;
+ # 真实发布路径的 release 由 release.yml 的 finalize 建好,这里只上传。
+ if ! gh release view "$RELEASE_TAG" >/dev/null 2>&1; then
+ gh release create "$RELEASE_TAG" --draft --title "Deepseek Harness Desktop $RELEASE_TAG"
+ fi
+ mapfile -d '' assets < <(find upload -type f -print0)
+ gh release upload "$RELEASE_TAG" "${assets[@]}" --clobber
+ if [ "$PRERELEASE" = "true" ]; then
+ gh release edit "$RELEASE_TAG" --draft=false --prerelease --latest=false
+ fi
+ {
+ echo "### Offline bundle assets"
+ echo
+ echo "Bundled core: \`$DSH_TAG\` · resources mapped to \`\$Resources/{node,pnpm,dsh}\` (Windows also \`git\`)"
+ echo
+ for asset in "${assets[@]}"; do
+ echo "- \`$(basename "$asset")\`"
+ done
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/.gitignore b/.gitignore
index 81e5fc4e..905f3ca8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,9 @@ dist
src-tauri/target
src-tauri/gen
src-tauri/resources/node
+src-tauri/resources/dsh
+src-tauri/resources/pnpm
+src-tauri/resources/git
src-tauri/resources/preset-plugins/
src-tauri/resources/internal-plugins/
*.log
diff --git a/scripts/bundle-metadata.d.mts b/scripts/bundle-metadata.d.mts
new file mode 100644
index 00000000..1b81b732
--- /dev/null
+++ b/scripts/bundle-metadata.d.mts
@@ -0,0 +1,81 @@
+/**
+ * `scripts/bundle-metadata.mjs` 的类型声明。
+ *
+ * 该脚本是给 CI 直接调用的纯 ESM,本身不带类型;这里声明它导出的函数与常量,
+ * 让 `test/bundle-metadata.test.ts` 的导入在 `pnpm typecheck` 下可解析。
+ */
+
+export interface BundleAsset {
+ name: string
+ url: string
+ /** 构建期已知的固定摘要;需要单独下载摘要文件时为空字符串 */
+ sha256: string
+ /** 摘要文件地址(Node 官方 SHASUMS256.txt);有固定摘要时为空字符串 */
+ sha256Url: string
+}
+
+export interface BundleAssets {
+ node: BundleAsset
+ pnpm: BundleAsset
+ dsh: BundleAsset
+ /** 仅 Windows 随包(MinGit) */
+ git?: BundleAsset
+}
+
+export interface BundleConstants {
+ nodeVersion: string
+ nodeBaseUrl: string
+ pnpmVersion: string
+ pnpmBaseUrl: string
+ pnpmSha256: string
+ mingitVersion: string
+ mingitBaseUrl: string
+ mingitX64Sha256: string
+ mingitArm64Sha256: string
+ dshCoreUrl: string
+}
+
+export type BundlePlatform = 'windows' | 'macos' | 'linux'
+export type BundleArch = 'x64' | 'arm64'
+
+export const BUNDLED_DIRS: Record<string, string>
+export const DSH_PKG_REPO: string
+
+export function stripJsonc(raw: string): string
+
+export function readManifest(repo?: string): Record<string, unknown>
+
+export function readRecommendedDshVersion(repo?: string): string
+
+export function parseVersionFromTag(tag: unknown): string | null
+
+export function nodeAssetName(platform: BundlePlatform, arch: BundleArch, version: string): string
+
+export function dshAssetName(platform: BundlePlatform, arch: BundleArch): string
+
+export function mingitAssetName(arch: BundleArch, version: string): string
+
+export function readBuildConstants(repo?: string): BundleConstants
+
+export function bundleTargets(platform: BundlePlatform): string[]
+
+export function bundleAssets(input: {
+ platform: BundlePlatform
+ arch: BundleArch
+ constants: BundleConstants
+ dshTag: string
+}): BundleAssets
+
+export function toAssetTable(assets: BundleAssets): string
+
+export function applyBundleManifest(input: {
+ repo?: string
+ platform: BundlePlatform
+}): { file: string, applied: string[] }
+
+export function findReleaseTag(releases: unknown, version: string): string
+
+export function resolveDshTag(
+ version: string,
+ fetchJson?: (url: string) => Promise<unknown>,
+): Promise<string>
diff --git a/scripts/bundle-metadata.mjs b/scripts/bundle-metadata.mjs
new file mode 100644
index 00000000..b26a9114
--- /dev/null
+++ b/scripts/bundle-metadata.mjs
@@ -0,0 +1,406 @@
+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
+import path from 'node:path'
+import process from 'node:process'
+import { pathToFileURL } from 'node:url'
+
+// 离线安装包(offline bundle)构建元数据。版本号、资产名与下载前缀全部取自
+// `src-tauri/src/config/constants.rs` 与 `src-tauri/resources/manifest.jsonc`,
+// 不在 workflow 或本脚本里另抄一份常量。
+
+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}`)
+ if (cause !== undefined)
+ error.cause = cause
+ return error
+}
+
+function requireString(value, label) {
+ if (typeof value !== 'string' || value.length === 0)
+ throw bundleError(`${label} must be a non-empty string`)
+ return value
+}
+
+/** 解析 `constants.rs` 里的字符串常量(`pub const NAME: &str = "value";`)。 */
+function readRustStringConst(source, name) {
+ const pattern = new RegExp(`pub const ${name}:\\s*&str\\s*=\\s*"([^"]*)"`)
+ const match = pattern.exec(source)
+ if (!match)
+ throw bundleError(`constants.rs is missing string const ${name}`)
+ return match[1]
+}
+
+/**
+ * 去 JSONC 注释与尾逗号(与 `config::manifest::strip_jsonc` 等价)。
+ *
+ * 引号内的 `//`、`/*` 原样保留,转义字符不参与判定。
+ */
+export function stripJsonc(raw) {
+ let out = ''
+ let inString = false
+ for (let i = 0; i < raw.length; i += 1) {
+ const char = raw[i]
+ if (inString) {
+ out += char
+ if (char === '\\') {
+ out += raw[i + 1] ?? ''
+ i += 1
+ }
+ else if (char === '"') {
+ inString = false
+ }
+ continue
+ }
+ if (char === '"') {
+ inString = true
+ out += char
+ continue
+ }
+ if (char === '/' && raw[i + 1] === '/') {
+ while (i < raw.length && raw[i] !== '\n')
+ i += 1
+ continue
+ }
+ if (char === '/' && raw[i + 1] === '*') {
+ i += 2
+ while (i + 1 < raw.length && !(raw[i] === '*' && raw[i + 1] === '/'))
+ i += 1
+ i += 1
+ continue
+ }
+ if (char === ',') {
+ let next = i + 1
+ while (next < raw.length && /\s/.test(raw[next]))
+ next += 1
+ if (raw[next] === '}' || raw[next] === ']')
+ continue
+ }
+ out += char
+ }
+ return out
+}
+
+function manifestPath(repo) {
+ return path.join(repo, 'src-tauri', 'resources', 'manifest.jsonc')
+}
+
+/** 读取并解析资源清单(JSONC)。 */
+export function readManifest(repo = process.cwd()) {
+ const file = manifestPath(repo)
+ let raw
+ try {
+ raw = readFileSync(file, 'utf8')
+ }
+ catch (error) {
+ throw bundleError(`cannot read ${file}`, error)
+ }
+ try {
+ return JSON.parse(stripJsonc(raw.replace(/^\uFEFF/, '')))
+ }
+ catch (error) {
+ throw bundleError(`cannot parse ${file}`, error)
+ }
+}
+
+/** 资源清单中的推荐核心版本(`engines.dsh.recommend`)。 */
+export function readRecommendedDshVersion(repo = process.cwd()) {
+ const manifest = readManifest(repo)
+ const version = typeof manifest?.engines?.dsh?.recommend === 'string'
+ ? manifest.engines.dsh.recommend.trim()
+ : ''
+ if (!version)
+ throw bundleError('manifest.jsonc is missing engines.dsh.recommend')
+ return version
+}
+
+/** 从 release tag 解析版本号,与 Rust `download::parse_version_from_tag` 等价。 */
+export function parseVersionFromTag(tag) {
+ if (typeof tag !== 'string')
+ return null
+ const hasDshPrefix = tag.startsWith('dsh-')
+ let rest = hasDshPrefix ? tag.slice(4) : tag
+ if (rest.startsWith('src-')) {
+ rest = rest.slice(4)
+ if (hasDshPrefix) {
+ const cut = rest.lastIndexOf('-')
+ if (cut < 0)
+ return null
+ rest = rest.slice(0, cut)
+ }
+ return rest.length > 0 ? rest : null
+ }
+ if (!hasDshPrefix)
+ return null
+ const cut = rest.lastIndexOf('-')
+ if (cut < 0)
+ return null
+ rest = rest.slice(0, cut)
+ return rest.length > 0 ? rest : null
+}
+
+/** Node.js 官方发行包资产名(与 `config::runtime::node_pkg_filename` 一致)。 */
+export function nodeAssetName(platform, arch, version) {
+ const os = platform === 'macos' ? 'darwin' : platform === 'windows' ? 'win' : 'linux'
+ // 与 Rust 一致:Windows 只提供 x64 发行包(arm64 主机走 x64 模拟)。
+ const cpu = platform === 'windows' ? 'x64' : arch
+ const ext = platform === 'windows' ? 'zip' : 'tar.gz'
+ return `node-v${version}-${os}-${cpu}.${ext}`
+}
+
+/** deepseek-harness-pkg 发行资产名(与 `config::runtime::dsh_pkg_asset_filename` 一致)。 */
+export function dshAssetName(platform, arch) {
+ if (platform === 'windows')
+ return 'deepseek-harness-pkg-windows.zip'
+ if (platform === 'linux')
+ return 'deepseek-harness-pkg-linux.zip'
+ return arch === 'arm64' ? 'deepseek-harness-pkg-macos-arm64.zip' : 'deepseek-harness-pkg-macos-x64.zip'
+}
+
+/** MinGit 免安装发行包资产名(与 `config::runtime::mingit_pkg_filename` 一致)。 */
+export function mingitAssetName(arch, version) {
+ if (arch === 'arm64')
+ return `MinGit-${version}-arm64.zip`
+ if (arch === 'x64')
+ return `MinGit-${version}-64-bit.zip`
+ throw bundleError(`MinGit is not available for windows ${arch}`)
+}
+
+/** 收集仓库内的构建常量(Node / pnpm / MinGit 与各自的下载前缀)。 */
+export function readBuildConstants(repo = process.cwd()) {
+ const constantsPath = path.join(repo, 'src-tauri', 'src', 'config', 'constants.rs')
+ let source
+ try {
+ source = readFileSync(constantsPath, 'utf8')
+ }
+ catch (error) {
+ throw bundleError(`cannot read ${constantsPath}`, error)
+ }
+ return {
+ nodeVersion: readRustStringConst(source, 'NODE_VERSION').replace(/^v/, ''),
+ nodeBaseUrl: readRustStringConst(source, 'NODE_BASE_URL'),
+ pnpmVersion: readRustStringConst(source, 'PNPM_VERSION'),
+ pnpmBaseUrl: readRustStringConst(source, 'PNPM_BASE_URL'),
+ pnpmSha256: readRustStringConst(source, 'PNPM_SHA256'),
+ mingitVersion: readRustStringConst(source, 'MINGIT_VERSION'),
+ mingitBaseUrl: readRustStringConst(source, 'MINGIT_BASE_URL'),
+ mingitX64Sha256: readRustStringConst(source, 'MINGIT_X64_SHA256'),
+ mingitArm64Sha256: readRustStringConst(source, 'MINGIT_ARM64_SHA256'),
+ dshCoreUrl: readRustStringConst(source, 'DSH_CORE_URL'),
+ }
+}
+
+/** 随包依赖键(Windows 额外随包 MinGit,离线包不依赖系统 Git)。 */
+export function bundleTargets(platform) {
+ const keys = ['node', 'pnpm', 'dsh']
+ if (platform === 'windows')
+ keys.push('git')
+ return keys
+}
+
+/**
+ * 按平台/架构列出离线包需要下载的全部资产。
+ *
+ * `sha256` 为构建期已知的固定摘要(pnpm / MinGit,取自 constants.rs),`sha256Url`
+ * 为需要单独下载的摘要来源(Node 官方 SHASUMS256.txt);dsh 的摘要在下载后经
+ * GitHub Release API 读取(见 workflow)。
+ */
+export function bundleAssets({ platform, arch, constants, dshTag }) {
+ const nodeName = nodeAssetName(platform, arch, constants.nodeVersion)
+ const dshName = dshAssetName(platform, arch)
+ const assets = {
+ node: {
+ name: nodeName,
+ url: `${constants.nodeBaseUrl}v${constants.nodeVersion}/${nodeName}`,
+ sha256: '',
+ sha256Url: `${constants.nodeBaseUrl}v${constants.nodeVersion}/SHASUMS256.txt`,
+ },
+ pnpm: {
+ name: `pnpm-${constants.pnpmVersion}.tgz`,
+ url: `${constants.pnpmBaseUrl}pnpm-${constants.pnpmVersion}.tgz`,
+ sha256: constants.pnpmSha256,
+ sha256Url: '',
+ },
+ dsh: {
+ name: dshName,
+ url: `${constants.dshCoreUrl.replace(DSH_LATEST_DOWNLOAD_SEGMENT, `releases/download/${dshTag}/`)}${dshName}`,
+ sha256: '',
+ sha256Url: '',
+ },
+ }
+ if (platform === 'windows') {
+ const name = mingitAssetName(arch, constants.mingitVersion)
+ assets.git = {
+ name,
+ url: `${constants.mingitBaseUrl}${name}`,
+ sha256: arch === 'arm64' ? constants.mingitArm64Sha256 : constants.mingitX64Sha256,
+ sha256Url: '',
+ }
+ }
+ return assets
+}
+
+/**
+ * 把资产表渲染成逐行 `|` 分隔的文本供 composite action 解析。
+ *
+ * 刻意不用 TAB:bash 的 `read` 在 IFS 只含空白字符时会把连续分隔符折叠成一个、
+ * 并剥掉首尾分隔符,空字段(如 Node 没有固定 sha256)会串位。`|` 不属于空白
+ * 字符,空字段因此能被如实保留。资产名与 URL 都不会包含 `|`。
+ */
+export function toAssetTable(assets) {
+ return Object.entries(assets)
+ .map(([key, asset]) => [key, asset.name, asset.url, asset.sha256 ?? '', asset.sha256Url ?? ''].join('|'))
+ .join('\n')
+}
+
+/**
+ * 把清单里的依赖托管根改写成 `$Resources/<dir>` 并关闭运行期覆盖。
+ *
+ * 离线包把运行时随安装包分发,`managedRoot` 必须指向安装包资源目录;同时把
+ * `overridable` 置为 false,让本机既有的 `dependencies.json` 记录(旧的非离线
+ * 安装留下的 AppData 路径,可能已被删除)不能盖过随包资源。
+ *
+ * 改写结果直接写回 `src-tauri/resources/manifest.jsonc`(构建产物,不提交),
+ * 因此注释与缩进按 JSON 重新序列化。
+ */
+export function applyBundleManifest({ repo = process.cwd(), platform } = {}) {
+ 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)) {
+ 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 = false
+ applied.push(`${key} -> ${managedRoot}`)
+ }
+
+ 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))
+ throw bundleError('GitHub releases response is not an array')
+ const release = releases.find(item => parseVersionFromTag(item?.tag_name) === version)
+ if (!release)
+ throw bundleError(`no ${DSH_PKG_REPO} release found for version ${version}`)
+ return requireString(release.tag_name, 'release tag_name')
+}
+
+async function githubJson(url) {
+ const headers = {
+ 'accept': 'application/vnd.github+json',
+ 'user-agent': 'deepseek-harness-desktop-bundle',
+ }
+ const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN
+ if (token)
+ headers.authorization = `Bearer ${token}`
+ const response = await fetch(url, { headers })
+ if (!response.ok)
+ throw bundleError(`GitHub API ${url} responded ${response.status}`)
+ return response.json()
+}
+
+/** 按推荐版本反查 pkg 仓库的固定 tag。 */
+export async function resolveDshTag(version, fetchJson = githubJson) {
+ const releases = await fetchJson(
+ `https://api.github.com/repos/${DSH_PKG_REPO}/releases?per_page=100`,
+ )
+ return findReleaseTag(releases, version)
+}
+
+function appendOutputs(outputPath, values) {
+ if (!outputPath)
+ throw bundleError('GITHUB_OUTPUT is missing')
+ const lines = Object.entries(values)
+ .filter(([, value]) => value !== undefined && value !== null)
+ .map(([key, value]) => `${key}=${value}`)
+ appendFileSync(outputPath, `${lines.join('\n')}\n`, 'utf8')
+}
+
+function parseArgs(argv) {
+ const args = { assets: false, manifest: false, platform: '', arch: '' }
+ 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 = true
+ else if (arg === '--platform')
+ args.platform = argv[++i] ?? ''
+ else if (arg === '--arch')
+ args.arch = argv[++i] ?? ''
+ else
+ throw bundleError(`unknown argument ${arg}`)
+ }
+ return args
+}
+
+function requirePlatformArch(args) {
+ if (!['windows', 'macos', 'linux'].includes(args.platform))
+ throw bundleError(`--platform must be windows|macos|linux, got ${JSON.stringify(args.platform)}`)
+ if (!['x64', 'arm64'].includes(args.arch))
+ throw bundleError(`--arch must be x64|arm64, got ${JSON.stringify(args.arch)}`)
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2))
+ const repo = process.env.GITHUB_WORKSPACE || process.cwd()
+ const constants = readBuildConstants(repo)
+ const dshVersion = readRecommendedDshVersion(repo)
+
+ if (args.assets) {
+ requirePlatformArch(args)
+ const dshTag = requireString(process.env.DSH_TAG || '', 'DSH_TAG environment variable')
+ process.stdout.write(`${toAssetTable(bundleAssets({ platform: args.platform, arch: args.arch, constants, dshTag }))}\n`)
+ return
+ }
+
+ if (args.manifest) {
+ requirePlatformArch(args)
+ const { file, applied } = applyBundleManifest({ repo, platform: args.platform })
+ 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,
+ pnpm_version: constants.pnpmVersion,
+ mingit_version: constants.mingitVersion,
+ dsh_version: dshVersion,
+ dsh_tag: dshTag,
+ })
+}
+
+const entryPoint = process.argv[1]
+if (entryPoint && import.meta.url === pathToFileURL(path.resolve(entryPoint)).href) {
+ try {
+ await main()
+ }
+ catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ console.error(message.startsWith('BUNDLE_METADATA:') ? message : `BUNDLE_METADATA: ${message}`)
+ process.exitCode = 1
+ }
+}
+
+export {
+ BUNDLED_DIRS,
+ DSH_PKG_REPO,
+}
diff --git a/src-tauri/resources/README.md b/src-tauri/resources/README.md
index e8745de0..4088d5c0 100644
--- a/src-tauri/resources/README.md
+++ b/src-tauri/resources/README.md
@@ -106,6 +106,43 @@ 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 a
+second 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 — Windows only, so a blank machine needs no Git install |
+
+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
+"dsh": { "entry": "node_modules/@deepseek-ai/dsh/lib/bin.js", "managedRoot": "$Resources/dsh", "overridable": false }
+```
+
+The rewrite only ever touches the build output — the committed manifest keeps its
+`$AppData/...` defaults. `overridable: false` is what stops a stale
+`<app-data>/dependencies.json` (written by an earlier, non-bundled install and possibly
+pointing at deleted directories) from winning over the bundled copy.
+
+No Rust code is involved: node/pnpm/git are only ever read, and the 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`
To propose a new preset plugin, open a PR that adds one entry:
diff --git a/test/bundle-metadata.test.ts b/test/bundle-metadata.test.ts
new file mode 100644
index 00000000..0cc94eb7
--- /dev/null
+++ b/test/bundle-metadata.test.ts
@@ -0,0 +1,284 @@
+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 bundleMetadataModule from '../scripts/bundle-metadata.mjs'
+
+interface BundleAsset {
+ name: string
+ url: string
+ sha256: string
+ sha256Url: string
+}
+
+interface BundleAssets {
+ node: BundleAsset
+ dsh: BundleAsset
+ pnpm: BundleAsset
+ git?: BundleAsset
+}
+
+interface BundleConstants {
+ nodeVersion: string
+ nodeBaseUrl: string
+ pnpmVersion: string
+ pnpmBaseUrl: string
+ pnpmSha256: string
+ mingitVersion: string
+ mingitBaseUrl: string
+ mingitX64Sha256: string
+ mingitArm64Sha256: string
+ dshCoreUrl: string
+}
+
+interface BundleMetadataModule {
+ parseVersionFromTag: (tag: unknown) => string | null
+ nodeAssetName: (platform: string, arch: string, version: string) => string
+ dshAssetName: (platform: string, arch: string) => string
+ mingitAssetName: (arch: string, version: string) => string
+ bundleTargets: (platform: string) => string[]
+ bundleAssets: (input: {
+ platform: string
+ arch: string
+ constants: BundleConstants
+ dshTag: string
+ }) => BundleAssets
+ toAssetTable: (assets: BundleAssets) => string
+ stripJsonc: (raw: string) => string
+ readManifest: (repo?: string) => Record<string, any>
+ readBuildConstants: (repo?: string) => BundleConstants
+ readRecommendedDshVersion: (repo?: string) => string
+ applyBundleManifest: (input: { repo?: string, platform: string }) => {
+ file: string
+ applied: string[]
+ }
+ findReleaseTag: (releases: unknown, version: string) => string
+ resolveDshTag: (version: string, fetchJson?: (url: string) => Promise<unknown>) => Promise<string>
+}
+
+const bundleMetadata = bundleMetadataModule as unknown as BundleMetadataModule
+
+const constants: BundleConstants = {
+ nodeVersion: '22.22.0',
+ nodeBaseUrl: 'https://nodejs.org/dist/',
+ pnpmVersion: '11.7.0',
+ pnpmBaseUrl: 'https://registry.npmjs.org/pnpm/-/',
+ pnpmSha256: 'a'.repeat(64),
+ mingitVersion: '2.53.0.2',
+ mingitBaseUrl: 'https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.2/',
+ mingitX64Sha256: 'b'.repeat(64),
+ mingitArm64Sha256: 'c'.repeat(64),
+ dshCoreUrl: 'https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/latest/download/',
+}
+
+const DSH_TAG = 'dsh-0.1.5-rc.3-12345678901'
+
+function assetsFor(platform: string, arch: string) {
+ return bundleMetadata.bundleAssets({ platform, arch, constants, dshTag: DSH_TAG })
+}
+
+describe('bundle metadata tag parsing', () => {
+ it.each([
+ ['dsh-0.1.0-rc.7-32054485373', '0.1.0-rc.7'],
+ ['dsh-0.1.1-rc.2-32485170079', '0.1.1-rc.2'],
+ ['src-0.1.2-alpha.1', '0.1.2-alpha.1'],
+ ['dsh-src-0.1.2-alpha.1-33260039971', '0.1.2-alpha.1'],
+ ])('parses %s', (tag, version) => {
+ expect(bundleMetadata.parseVersionFromTag(tag)).toBe(version)
+ })
+
+ it.each(['dsh-0.2.0', '0.1.0-rc.7-abc', '', 'dsh-'])('rejects %s', (tag) => {
+ expect(bundleMetadata.parseVersionFromTag(tag)).toBeNull()
+ })
+})
+
+describe('bundle asset names', () => {
+ it('mirrors the runtime node distribution layout', () => {
+ expect(bundleMetadata.nodeAssetName('windows', 'x64', '22.22.0')).toBe('node-v22.22.0-win-x64.zip')
+ expect(bundleMetadata.nodeAssetName('windows', 'arm64', '22.22.0')).toBe('node-v22.22.0-win-x64.zip')
+ expect(bundleMetadata.nodeAssetName('macos', 'arm64', '22.22.0')).toBe('node-v22.22.0-darwin-arm64.tar.gz')
+ expect(bundleMetadata.nodeAssetName('macos', 'x64', '22.22.0')).toBe('node-v22.22.0-darwin-x64.tar.gz')
+ expect(bundleMetadata.nodeAssetName('linux', 'x64', '22.22.0')).toBe('node-v22.22.0-linux-x64.tar.gz')
+ expect(bundleMetadata.nodeAssetName('linux', 'arm64', '22.22.0')).toBe('node-v22.22.0-linux-arm64.tar.gz')
+ })
+
+ it('mirrors the packaged core asset layout', () => {
+ expect(bundleMetadata.dshAssetName('windows', 'x64')).toBe('deepseek-harness-pkg-windows.zip')
+ expect(bundleMetadata.dshAssetName('linux', 'arm64')).toBe('deepseek-harness-pkg-linux.zip')
+ expect(bundleMetadata.dshAssetName('macos', 'arm64')).toBe('deepseek-harness-pkg-macos-arm64.zip')
+ expect(bundleMetadata.dshAssetName('macos', 'x64')).toBe('deepseek-harness-pkg-macos-x64.zip')
+ })
+
+ it('mirrors the MinGit asset layout and rejects unknown architectures', () => {
+ expect(bundleMetadata.mingitAssetName('x64', '2.53.0.2')).toBe('MinGit-2.53.0.2-64-bit.zip')
+ expect(bundleMetadata.mingitAssetName('arm64', '2.53.0.2')).toBe('MinGit-2.53.0.2-arm64.zip')
+ expect(() => bundleMetadata.mingitAssetName('ia32', '2.53.0.2')).toThrow(/^BUNDLE_METADATA:/)
+ })
+})
+
+describe('bundle asset resolution', () => {
+ it('pins every windows asset to a downloadable url', () => {
+ const assets = assetsFor('windows', 'x64')
+
+ expect(assets.node.url).toBe('https://nodejs.org/dist/v22.22.0/node-v22.22.0-win-x64.zip')
+ expect(assets.node.sha256Url).toBe('https://nodejs.org/dist/v22.22.0/SHASUMS256.txt')
+ expect(assets.dsh.url).toBe(
+ `https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/${DSH_TAG}/deepseek-harness-pkg-windows.zip`,
+ )
+ expect(assets.pnpm.url).toBe('https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz')
+ // 离线包不依赖系统 Git:Windows 随包 MinGit,摘要取自 constants.rs。
+ expect(assets.git?.url).toBe(
+ 'https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.2/MinGit-2.53.0.2-64-bit.zip',
+ )
+ expect(assets.git?.sha256).toBe(constants.mingitX64Sha256)
+ })
+
+ it('bundles MinGit on windows only', () => {
+ expect(bundleMetadata.bundleTargets('windows')).toEqual(['node', 'pnpm', 'dsh', 'git'])
+ expect(bundleMetadata.bundleTargets('macos')).toEqual(['node', 'pnpm', 'dsh'])
+ expect(Object.keys(assetsFor('macos', 'arm64')).sort()).toEqual(['dsh', 'node', 'pnpm'])
+ })
+
+ it('keeps empty sha256 fields in the asset table', () => {
+ const assets = assetsFor('linux', 'x64')
+ const rows = bundleMetadata.toAssetTable(assets).split('\n')
+ expect(rows.map(row => row.split('|')[0])).toEqual(['node', 'pnpm', 'dsh'])
+ const field = (key: string, index: number) =>
+ rows.find(row => row.startsWith(`${key}|`))!.split('|')[index]
+ // 空字段必须如实保留(bash `read` 用 `|` 而不是 TAB 作为分隔符的原因)。
+ expect(field('node', 3)).toBe('')
+ expect(field('node', 4)).toBe(assets.node.sha256Url)
+ expect(field('pnpm', 3)).toBe(constants.pnpmSha256)
+ expect(field('pnpm', 4)).toBe('')
+ expect(field('dsh', 3)).toBe('')
+ expect(field('dsh', 4)).toBe('')
+ })
+})
+
+describe('bundle release resolution', () => {
+ it('picks the release whose tag parses to the recommended version', () => {
+ expect(bundleMetadata.findReleaseTag([
+ { tag_name: 'dsh-0.1.6-rc.1-200' },
+ { tag_name: DSH_TAG },
+ ], '0.1.5-rc.3')).toBe(DSH_TAG)
+ })
+
+ it('fails loudly when no release matches', () => {
+ expect(() => bundleMetadata.findReleaseTag([], '9.9.9')).toThrow(/^BUNDLE_METADATA:/)
+ })
+
+ it('resolves the tag through the GitHub releases API', async () => {
+ const tag = await bundleMetadata.resolveDshTag('0.1.5-rc.3', async () => [
+ { tag_name: 'dsh-0.1.7-rc.1-35871708301' },
+ { tag_name: DSH_TAG },
+ ])
+ expect(tag).toBe(DSH_TAG)
+ })
+})
+
+describe('bundle build constants', () => {
+ it('reads the node/pnpm/MinGit pins and the recommended core from the checkout', () => {
+ const parsed = bundleMetadata.readBuildConstants(process.cwd())
+ expect(parsed.nodeVersion).toMatch(/^\d+\.\d+\.\d+$/)
+ expect(parsed.nodeBaseUrl).toMatch(/^https:\/\//)
+ expect(parsed.pnpmVersion).toMatch(/^\d+\.\d+\.\d+/)
+ expect(parsed.pnpmSha256).toHaveLength(64)
+ expect(parsed.mingitX64Sha256).toHaveLength(64)
+ expect(parsed.dshCoreUrl).toContain('deepseek-harness-pkg')
+ expect(bundleMetadata.readRecommendedDshVersion(process.cwd())).toMatch(/^\d+\.\d+\.\d+/)
+ })
+})
+
+describe('jsonc stripping', () => {
+ it('tolerates comments and trailing commas without touching string content', () => {
+ const raw = `{
+ // 行注释
+ "id": "a//b/*c*/",
+ /* 块注释
+ 跨行 */
+ "list": [1, 2,],
+ }`
+ expect(JSON.parse(bundleMetadata.stripJsonc(raw))).toEqual({
+ id: 'a//b/*c*/',
+ list: [1, 2],
+ })
+ })
+})
+
+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',
+ 'pnpm -> $Resources/pnpm',
+ 'dsh -> $Resources/dsh',
+ 'git -> $Resources/git',
+ ])
+
+ 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'], ['git', 'git']]) {
+ expect(manifest.dependencies[key].managedRoot).toBe(`$Resources/${dir}`)
+ expect(manifest.dependencies[key].overridable).toBe(false)
+ // 入口形状由清单声明,改写托管根不得动它。
+ expect(manifest.dependencies[key].entry).toEqual(shipped.dependencies[key].entry)
+ }
+ expect(manifest.engines.dsh.recommend).toBe('0.1.5-rc.3')
+ }
+ 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).not.toContain('git -> $Resources/git')
+ 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',
+ 'pnpm -> $Resources/pnpm',
+ 'dsh -> $Resources/dsh',
+ ])
+ expect(() => bundleMetadata.applyBundleManifest({ repo, platform: 'freebsd' }))
+ .toThrow(/^BUNDLE_METADATA:/)
+ }
+ finally {
+ rmSync(repo, { recursive: true, force: true })
+ }
+ })
+})