Skip to content

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

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

hairyf3e257103339a
diff --git a/.github/actions/prepare-bundle-resources/action.yml b/.github/actions/prepare-bundle-resources/action.yml
new file mode 100644
index 00000000..11ec31e6
--- /dev/null
+++ b/.github/actions/prepare-bundle-resources/action.yml
@@ -0,0 +1,152 @@
+name: Prepare offline bundle resources
+description: >-
+ Download and unpack the Node.js runtime, the packaged dsh core and pnpm into
+ src-tauri/resources so `tauri build` produces an offline 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
+ dsh-commit:
+ description: Commit / build id recorded for the bundled core
+ required: false
+ default: ''
+
+runs:
+ using: composite
+ steps:
+ - name: Download and unpack bundled runtimes
+ shell: bash
+ env:
+ PLATFORM: ${{ inputs.platform }}
+ ARCH: ${{ inputs.arch }}
+ DSH_TAG: ${{ inputs.dsh-tag }}
+ DSH_COMMIT: ${{ inputs.dsh-commit }}
+ 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 3600 -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)
+ 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/"
+ }
+
+ declare -A ASSET_NAME ASSET_URL ASSET_SHA ASSET_SHA_URL
+ while IFS='|' read -r key name url sha sha_url; do
+ [ -n "${key:-}" ] || continue
+ ASSET_NAME["$key"]="$name"
+ ASSET_URL["$key"]="$url"
+ ASSET_SHA["$key"]="$sha"
+ ASSET_SHA_URL["$key"]="$sha_url"
+ done < <(node scripts/bundle-metadata.mjs --assets --platform "$PLATFORM" --arch "$ARCH")
+
+ # Node.js 运行时:摘要取自官方 SHASUMS256.txt,与 assets 同源同版本。
+ fetch "${ASSET_URL[node]}" "${workdir}/${ASSET_NAME[node]}"
+ fetch "${ASSET_SHA_URL[node]}" "${workdir}/SHASUMS256.txt"
+ verify "${workdir}/${ASSET_NAME[node]}" \
+ "$(awk -v asset="${ASSET_NAME[node]}" '$2 == asset { print $1 }' "${workdir}/SHASUMS256.txt")" \
+ "Node.js ${ASSET_NAME[node]}"
+ extract "${workdir}/${ASSET_NAME[node]}" "${workdir}/node"
+ flatten "${workdir}/node"
+ install_tree "${workdir}/node" "src-tauri/resources/node"
+
+ # dsh 内核:摘要来自同一 release 的 GitHub API,缺失即中止(无法校验完整性的
+ # 内容不进离线包)。
+ fetch "${ASSET_URL[dsh]}" "${workdir}/${ASSET_NAME[dsh]}"
+ dsh_digest="$(gh api "repos/dsh-tauri-desk/deepseek-harness-pkg/releases/tags/${DSH_TAG}" \
+ --jq ".assets[] | select(.name == \"${ASSET_NAME[dsh]}\") | .digest" 2>/dev/null \
+ | sed 's/^sha256://' | head -n 1)"
+ verify "${workdir}/${ASSET_NAME[dsh]}" "$dsh_digest" "dsh core ${ASSET_NAME[dsh]}"
+ extract "${workdir}/${ASSET_NAME[dsh]}" "${workdir}/dsh"
+ flatten "${workdir}/dsh"
+ install_tree "${workdir}/dsh" "src-tauri/resources/dsh"
+
+ # pnpm:纯 JS 发行,摘要取自 constants.rs 的固定值。
+ fetch "${ASSET_URL[pnpm]}" "${workdir}/${ASSET_NAME[pnpm]}"
+ verify "${workdir}/${ASSET_NAME[pnpm]}" "${ASSET_SHA[pnpm]}" "pnpm ${ASSET_NAME[pnpm]}"
+ extract "${workdir}/${ASSET_NAME[pnpm]}" "${workdir}/pnpm"
+ flatten "${workdir}/pnpm"
+ install_tree "${workdir}/pnpm" "src-tauri/resources/pnpm"
+
+ node scripts/bundle-metadata.mjs --manifest --platform "$PLATFORM" --arch "$ARCH"
+
+ echo "--- bundled resources ---"
+ du -sh src-tauri/resources/node src-tauri/resources/dsh src-tauri/resources/pnpm
+ cat src-tauri/resources/bundle.json
diff --git a/.github/workflows/build-bundle-linux.yml b/.github/workflows/build-bundle-linux.yml
new file mode 100644
index 00000000..90738560
--- /dev/null
+++ b/.github/workflows/build-bundle-linux.yml
@@ -0,0 +1,90 @@
+name: Reusable Linux Offline Bundle Build
+
+on:
+ workflow_call:
+ inputs:
+ source_ref:
+ required: true
+ type: string
+ dsh_tag:
+ required: true
+ type: string
+ dsh_commit:
+ required: false
+ type: string
+ default: ''
+ 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 }}
+ dsh-commit: ${{ inputs.dsh_commit }}
+
+ - 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 appimage,deb
+
+ - name: Upload build outputs
+ uses: actions/upload-artifact@v6
+ with:
+ name: release-bundle-linux
+ path: |
+ src-tauri/target/release/bundle/appimage/*.AppImage
+ 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..688c7234
--- /dev/null
+++ b/.github/workflows/build-bundle-macos.yml
@@ -0,0 +1,150 @@
+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
+ dsh_commit:
+ required: false
+ type: string
+ default: ''
+ 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 }}
+ dsh-commit: ${{ inputs.dsh_commit }}
+
+ - 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
+
+ - 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 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"
+
+ - 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..4f0a29e3
--- /dev/null
+++ b/.github/workflows/build-bundle-windows.yml
@@ -0,0 +1,70 @@
+name: Reusable Windows Offline Bundle Build
+
+on:
+ workflow_call:
+ inputs:
+ source_ref:
+ required: true
+ type: string
+ dsh_tag:
+ required: true
+ type: string
+ dsh_commit:
+ required: false
+ type: string
+ default: ''
+ 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 }}
+ dsh-commit: ${{ inputs.dsh_commit }}
+
+ # 只出 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
+
+ - 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..759f0e12
--- /dev/null
+++ b/.github/workflows/release-bundle.yml
@@ -0,0 +1,231 @@
+name: Build & Release (Offline Bundle)
+
+# 离线安装包:在普通发布流程(release.yml)成功后追加一次带资源构建。
+# 产物把 Node.js 运行时、推荐 dsh 内核、pnpm(Windows 还有 MinGit)随安装包分发,
+# 首次启动直接落地到应用数据目录,全程不联网。
+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(留空则按 package.json 版本推导 v<version>)
+ required: false
+ default: ''
+ type: string
+
+permissions:
+ contents: write
+
+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 的每一次结束(含失败/取消)触发,只有成功才继续。
+ if: >-
+ github.event_name == 'workflow_dispatch' ||
+ github.event.workflow_run.conclusion == 'success'
+ runs-on: ubuntu-latest
+ outputs:
+ should_build: ${{ steps.release.outputs.should_build }}
+ tag: ${{ steps.release.outputs.tag }}
+ version: ${{ steps.release.outputs.version }}
+ source_ref: ${{ steps.release.outputs.source_ref }}
+ dsh_tag: ${{ steps.meta.outputs.dsh_tag }}
+ dsh_commit: ${{ steps.meta.outputs.dsh_commit }}
+ steps:
+ - name: Checkout release commit
+ uses: actions/checkout@v7
+ with:
+ # workflow_run 用触发运行时的 head_sha(即 release.yml 真正构建的提交),
+ # 手动触发用当前 ref。
+ ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}
+ fetch-depth: 0
+
+ - 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 }}
+ 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"
+ if [ -z "$tag" ] && [[ "$RUN_HEAD_BRANCH" == v* ]]; then
+ tag="$RUN_HEAD_BRANCH"
+ fi
+ if [ -z "$tag" ]; then
+ tag="v$version"
+ fi
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+ echo "source_ref=$SOURCE_REF" >> "$GITHUB_OUTPUT"
+ if gh release view "$tag" >/dev/null 2>&1; then
+ echo "should_build=true" >> "$GITHUB_OUTPUT"
+ echo "offline bundle target release: $tag ($version)"
+ else
+ echo "should_build=false" >> "$GITHUB_OUTPUT"
+ echo "::warning::release $tag does not exist yet, skipping the offline bundle build"
+ fi
+
+ - name: Resolve bundle metadata
+ 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 }}
+ dsh_commit: ${{ needs.prepare.outputs.dsh_commit }}
+ 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 }}
+ dsh_commit: ${{ needs.prepare.outputs.dsh_commit }}
+ 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 }}
+ dsh_commit: ${{ needs.prepare.outputs.dsh_commit }}
+ 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
+ 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 }}
+ run: |
+ set -euo pipefail
+ mapfile -d '' assets < <(find upload -type f -print0)
+ gh release upload "$RELEASE_TAG" "${assets[@]}" --clobber
+ {
+ echo "### Offline bundle assets"
+ for asset in "${assets[@]}"; do
+ echo "- \`$(basename "$asset")\`"
+ done
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/.gitignore b/.gitignore
index 2060fb93..44e82a72 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/bundle.json
src-tauri/resources/preset-plugins/
src-tauri/resources/internal-plugins/
*.log
diff --git a/scripts/bundle-metadata.mjs b/scripts/bundle-metadata.mjs
new file mode 100644
index 00000000..bb8dd210
--- /dev/null
+++ b/scripts/bundle-metadata.mjs
@@ -0,0 +1,293 @@
+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
+import path from 'node:path'
+import process from 'node:process'
+import { pathToFileURL } from 'node:url'
+
+// 离线安装包(offline bundle)构建元数据:版本号与资产名必须与 Rust 侧
+// (src-tauri/src/config/constants.rs、config::runtime 的资产命名)保持同源,
+// 因此这里直接解析 constants.rs,而不是在 workflow 里再抄一份常量。
+
+const DSH_PKG_REPO = 'dsh-tauri-desk/deepseek-harness-pkg'
+const DSH_PKG_RELEASE_BASE = `https://github.com/${DSH_PKG_REPO}/releases/download`
+const NODE_BASE_URL = 'https://nodejs.org/dist'
+const PNPM_BASE_URL = 'https://registry.npmjs.org/pnpm/-/'
+
+function bundleError(message, cause) {
+ const error = new Error(`BUNDLE_METADATA: ${message}`)
+ if (cause !== undefined)
+ error.cause = cause
+ return error
+}
+
+/** 解析 `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]
+}
+
+/** 从 release tag 解析版本号,与 Rust `download::parse_version_from_tag` 等价。 */
+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` 一致)。 */
+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` 一致)。 */
+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'
+}
+
+/** 收集仓库内的构建常量(Node / pnpm)。 */
+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/, ''),
+ pnpmVersion: readRustStringConst(source, 'PNPM_VERSION'),
+ pnpmSha256: readRustStringConst(source, 'PNPM_SHA256'),
+ }
+}
+
+/** 读取应用资源中的推荐核心版本。 */
+function readRecommendedDshVersion(repo = process.cwd()) {
+ const file = path.join(repo, 'src-tauri', 'resources', 'version-recommend.json')
+ let parsed
+ try {
+ parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
+ }
+ catch (error) {
+ throw bundleError(`cannot read ${file}`, error)
+ }
+ const version = typeof parsed?.dsh === 'string' ? parsed.dsh.trim() : ''
+ if (!version)
+ throw bundleError('version-recommend.json is missing a dsh version')
+ return version
+}
+
+/**
+ * 按平台/架构列出离线包需要下载的全部资产。
+ *
+ * `sha256Url` 为可选的“摘要来源”:Node 走官方 SHASUMS256.txt,pnpm 走
+ * constants.rs 中固定的摘要;dsh 发行版的摘要在构建期通过 GitHub Release API
+ * 读取(见 workflow 中的校验步骤)。MinGit 刻意不随包分发(见
+ * `src-tauri/src/service/bundle`),因此不在资产列表内。
+ */
+function bundleAssets({ platform, arch, constants, dshVersion, dshTag }) {
+ const nodeName = nodeAssetName(platform, arch, constants.nodeVersion)
+ const dshName = dshAssetName(platform, arch)
+ return {
+ node: {
+ name: nodeName,
+ url: `${NODE_BASE_URL}/v${constants.nodeVersion}/${nodeName}`,
+ sha256Url: `${NODE_BASE_URL}/v${constants.nodeVersion}/SHASUMS256.txt`,
+ },
+ dsh: {
+ name: dshName,
+ url: `${DSH_PKG_RELEASE_BASE}/${dshTag}/${dshName}`,
+ version: dshVersion,
+ tag: dshTag,
+ },
+ pnpm: {
+ name: `pnpm-${constants.pnpmVersion}.tgz`,
+ url: `${PNPM_BASE_URL}pnpm-${constants.pnpmVersion}.tgz`,
+ sha256: constants.pnpmSha256,
+ },
+ }
+}
+
+/**
+ * 把资产表渲染成逐行 `|` 分隔的文本供 composite action 解析。
+ *
+ * 刻意不用 TAB:bash 的 `read` 在 IFS 只含空白字符时会把连续分隔符折叠成一个、
+ * 并剥掉首尾分隔符,空字段(dsh 没有 sha256/sha256Url)会串位。`|` 不属于空白
+ * 字符,空字段因此能被如实保留。资产名与 URL 都不会包含 `|`。
+ */
+function toAssetTable(assets) {
+ return ['node', 'dsh', 'pnpm']
+ .map((key) => {
+ const asset = assets[key]
+ return [key, asset.name, asset.url, asset.sha256 ?? '', asset.sha256Url ?? ''].join('|')
+ })
+ .join('\n')
+}
+
+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')
+}
+
+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 与提交标识。 */
+async function resolveDshRelease(version, fetchJson = githubJson) {
+ const releases = await fetchJson(
+ `https://api.github.com/repos/${DSH_PKG_REPO}/releases?per_page=100`,
+ )
+ 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}`)
+ const commitish = typeof release.target_commitish === 'string' ? release.target_commitish : ''
+ const commit = /^[0-9a-f]{40}$/i.test(commitish)
+ ? commitish.toLowerCase()
+ : (release.tag_name.match(/-(\d+)$/)?.[1] ?? '')
+ return { tag: release.tag_name, commit }
+}
+
+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)}`)
+}
+
+function requireDshTag() {
+ const tag = process.env.DSH_TAG || ''
+ if (!tag)
+ throw bundleError('DSH_TAG environment variable is required')
+ return tag
+}
+
+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 = requireDshTag()
+ const assets = bundleAssets({ platform: args.platform, arch: args.arch, constants, dshVersion, dshTag })
+ process.stdout.write(`${toAssetTable(assets)}\n`)
+ return
+ }
+
+ if (args.manifest) {
+ requirePlatformArch(args)
+ const dshTag = requireDshTag()
+ const manifest = {
+ node: constants.nodeVersion,
+ pnpm: constants.pnpmVersion,
+ platform: args.platform,
+ arch: args.arch,
+ dsh: {
+ version: dshVersion,
+ tag: dshTag,
+ commit: process.env.DSH_COMMIT || null,
+ },
+ }
+ const target = path.join(repo, 'src-tauri', 'resources', 'bundle.json')
+ writeFileSync(target, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
+ process.stdout.write(`${target}\n`)
+ return
+ }
+
+ const release = await resolveDshRelease(dshVersion)
+ await appendOutputs(process.env.GITHUB_OUTPUT, {
+ node_version: constants.nodeVersion,
+ pnpm_version: constants.pnpmVersion,
+ pnpm_sha256: constants.pnpmSha256,
+ mingit_version: constants.mingitVersion,
+ dsh_version: dshVersion,
+ dsh_tag: release.tag,
+ dsh_commit: release.commit,
+ })
+}
+
+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 {
+ bundleAssets,
+ dshAssetName,
+ nodeAssetName,
+ parseVersionFromTag,
+ readBuildConstants,
+ readRecommendedDshVersion,
+ resolveDshRelease,
+ toAssetTable,
+}
diff --git a/src-tauri/resources/README.md b/src-tauri/resources/README.md
index 01054db8..29836dc9 100644
--- a/src-tauri/resources/README.md
+++ b/src-tauri/resources/README.md
@@ -15,6 +15,64 @@ directory (the Tauri app-data dir for identifier
No manual Node.js or pnpm installation is required.
+## Offline bundle resources
+
+Alongside the regular installers, `.github/workflows/release-bundle.yml` publishes
+an **offline** build (`Deepseek.Harness.Desktop_Bundle_<version>.<ext>`) for
+machines without internet access. That build ships the runtime pieces the regular
+installer would otherwise download, under this same directory:
+
+- `node/` — the extracted Node.js distribution (`v22.22.0` and friends, see
+ `NODE_VERSION` in `src-tauri/src/config/constants.rs`)
+- `dsh/` — the extracted recommended dsh core, i.e. the built-in engine
+ (`resources/version-recommend.json`)
+- `pnpm/` — the extracted pnpm distribution
+- `bundle.json` — build-time manifest (`node`, `pnpm`, `dsh.version`,
+ `dsh.tag`, `dsh.commit`)
+
+They are produced by `.github/actions/prepare-bundle-resources` and are **not**
+committed (see `.gitignore`). Detecting `bundle.json` switches the app into
+offline mode (`src-tauri/src/config/bundle.rs`):
+
+- **Node and pnpm are used in place** — `resources/node` and `resources/pnpm`
+ directly, skipping the local PATH install and the app-data copies. Both are
+ read-only consumers, so nothing is copied.
+- **The dsh core is materialized into `dependencies/dsh` with no bulk copy**
+ (`src-tauri/src/service/bundle`), in one of two modes, re-decided on every launch
+ by probing whether the bundled core directory is writable:
+
+ - **Link** (writable — a Windows per-user install lands in `%LOCALAPPDATA%`):
+ `dependencies/dsh` *is* a directory link to `resources/dsh`. The patch layer
+ writes straight through into `resources/dsh`, so the file that gets loaded is
+ the very file that was rewritten — zero extra disk, no patched-copy/core skew.
+ - **Layer** (read-only — macOS `.app`, Linux AppImage/deb): a link layer whose
+ patched subtrees are real copies and whose remaining directories are links.
+
+ `src-tauri/src/service/patch::patched_paths()` is the single source of truth for
+ what must be writable: `service::bundle::real_dirs()` derives the Layer's real
+ directories from it, and both modes are verified right after materialization — if
+ any patch target ends up behind a directory link, or cannot be opened for
+ writing, materialization fails loudly instead of letting patches silently no-op.
+ Layer mode costs ~1.4 MiB on top of `resources/dsh`; Link mode costs nothing.
+
+ Core switching (`dependencies/dsh` ↔ `dependencies/<tag>`) is untouched — both
+ forms rename fine. A user-downloaded core is never overwritten: when the active
+ slot already holds a real core, the bundled one lands in its own tag slot as a
+ normal switchable version instead.
+- **The Node and pnpm directories are linked whole** (`{app_data}/runtime`,
+ `{app_data}/dependencies/pnpm`): both are read-only consumers (pnpm keeps its
+ store in `$DSH_HOME`), so one link each satisfies every existing convention —
+ including the paths hardcoded in the generated CLI shims.
+
+Windows MinGit is deliberately **not** bundled: the offline build treats the Git
+dependency as satisfied and never tries to fetch it (`config::is_offline_bundle`),
+so a machine without Git still boots normally — only plugin installs from
+`github:`/`git+ssh:` specs fail, at the point of use, instead of blocking startup.
+
+`bundle.json` also drives the core panel: the version it names is pinned to the
+top of the「核心引擎」list with a **内置核心 / Built-in** chip and cannot be
+uninstalled, so an offline machine always keeps a usable engine.
+
## `$DSH_HOME` — shared with the official Node.js install
The user data directory (`$DSH_HOME`) used by the running `dsh` process follows
diff --git a/src-tauri/src/bridge/lifecycle.rs b/src-tauri/src/bridge/lifecycle.rs
index 0b2ea1f4..e7f9e64a 100644
--- a/src-tauri/src/bridge/lifecycle.rs
+++ b/src-tauri/src/bridge/lifecycle.rs
@@ -41,6 +41,40 @@ fn install_lock() -> &'static tokio::sync::Mutex<()> {
INSTALL_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}
+/// 离线安装包内置核心落位互斥:`runtime_ready` 与 `install_dependencies` 会在启动
+/// 路径上先后调用,避免两路并发重建同一份链接层。
+static BUNDLE_LINK_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
+
+/// 把离线安装包随带的内置核心以零拷贝链接层落位到应用数据目录。
+///
+/// 幂等:普通安装包没有 `resources/bundle.json`,直接空转;离线包只在首次启动或
+/// 安装包升级(内置核心版本变化)时真正重建。失败只告警不阻断——后续
+/// `Installable::check_installed` 仍为 false,会走原有下载路径。
+async fn materialize_bundled_core(app_handle: &AppHandle) {
+ let lock = BUNDLE_LINK_LOCK.get_or_init(|| tokio::sync::Mutex::new(()));
+ let _guard = lock.lock().await;
+ let handle = app_handle.clone();
+ let result = tauri::async_runtime::spawn_blocking(move || {
+ crate::service::bundle::materialize(&handle)
+ })
+ .await;
+ match result {
+ Ok(Ok(true)) => log::info!("bundled core link layer materialized"),
+ Ok(Ok(false)) => {}
+ Ok(Err(e)) => log::warn!("bundled core materialization failed: {e}"),
+ Err(e) => log::warn!("bundled core materialization task failed: {e}"),
+ }
+}
+
+/// Git 依赖是否已满足。
+///
+/// 离线安装包**不随包分发 MinGit**:内网环境补装必然失败,把 Git 判定为「已满足」
+/// 以免用户卡在启动安装界面(`workflow::install` 对离线包也不再加入 Git 任务)。
+/// git 托管的插件安装会在真正使用时给出明确失败,而不是让应用起不来。
+fn git_dependency_ready(app_handle: &AppHandle) -> bool {
+ config::git_runtime_ready(app_handle) || config::is_offline_bundle(app_handle)
+}
+
/// 安装失败后把状态从 Installing 复位,避免后续调用被“正在安装”卡死。
/// 仅在失败路径调用;成功路径保持原有状态语义(由前端随后 launch 续接)。
fn reset_install_status(app_handle: &AppHandle) {
@@ -81,6 +115,10 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>
return Ok(false);
};
+ // 离线安装包:先把内置核心以零拷贝链接层落位,再判定「已就绪」。命中后下面的
+ // node/dsh/pnpm 检查全部为 true,启动路径不会产生任何下载。
+ materialize_bundled_core(&app_handle).await;
+
// 以实际安装状态为准:本地安装与 GitHub 最新 release 的 commit hash
// 不一致时,说明上游 pkg 有更新/修复,需要自动重新下载。
let node_ok = download::Nodejs.check_installed(&app_handle);
@@ -90,8 +128,8 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>
// 需一并纳入"已就绪"判定,缺失时由 workflow::install 按任务补齐。
let pnpm_ok = download::Pnpm.check_installed(&app_handle);
// Windows 空白环境还必须有可执行的 Git,才能安装 github:/git+ssh: 插件。
- // 非 Windows 返回 true,保持原有依赖集合不变。
- let git_ok = config::git_runtime_ready(&app_handle);
+ // 非 Windows 与离线包返回 true,保持原有依赖集合不变(见 git_dependency_ready)。
+ let git_ok = git_dependency_ready(&app_handle);
// 启动自愈捷径:记录显示未安装、但运行时文件已全部在盘。常见于桌面端自更新
// 安装器强杀进程,或上次启动时核心文件短暂缺失被 workflow::start 复位
@@ -405,12 +443,17 @@ pub fn get_dsh_status() -> workflow::status::Status {
/// (MSI 强杀进程)后 store 可能被复位或损坏显示「未安装」,但运行时文件其实
/// 已就绪——此时前端跳过安装/下载界面,交给 install_dependencies 内部自愈
/// 补记 installed 后直接启动,避免自动重开时闪现误导用户的安装界面。
+///
+/// 离线安装包(`resources/bundle.json`)在这里先把内置核心以零拷贝链接层落位到
+/// 应用数据目录:前端启动路径第一件事就是本命令,落位完成后即返回 true,用户直接
+/// 进入页面、看不到下载流程。
#[tauri::command]
-pub fn runtime_ready(app_handle: AppHandle) -> bool {
+pub async fn runtime_ready(app_handle: AppHandle) -> bool {
+ materialize_bundled_core(&app_handle).await;
download::Nodejs.check_installed(&app_handle)
&& download::Dsh.check_installed(&app_handle)
&& download::Pnpm.check_installed(&app_handle)
- && config::git_runtime_ready(&app_handle)
+ && git_dependency_ready(&app_handle)
}
#[cfg(test)]
diff --git a/src-tauri/src/config/bundle.rs b/src-tauri/src/config/bundle.rs
new file mode 100644
index 00000000..08b1944a
--- /dev/null
+++ b/src-tauri/src/config/bundle.rs
@@ -0,0 +1,164 @@
+//! 离线安装包(`resources/bundle.json`)识别与随包资源路径。
+//!
+//! 离线包构建(见 `.github/workflows/release-bundle.yml`)把 Node.js 运行时、推荐
+//! dsh 内核与 pnpm 预解压进 `resources/{node,dsh,pnpm}`,并写一份
+//! `resources/bundle.json`。检测到该清单即视为离线包:
+//!
+//! - **Node / pnpm 直接使用**随包目录,跳过 PATH 上的本地安装与应用数据目录副本
+//! (两者都只读使用,不需要可写);
+//! - **dsh 内核零拷贝落位**到应用数据目录的 `dependencies/dsh`(见 `service::bundle`):
+//! 顶层条目与 `node_modules` 的绝大多数条目都是指向 `resources/dsh` 的目录链接,
+//! 只有补丁目标 `node_modules/@deepseek-ai` 复制为真实文件——桌面端每次启动都会
+//! 改写其中的 8 个文件(见 `service::patch`),链接无法承载写入。
+
+use serde::Deserialize;
+use std::path::PathBuf;
+use tauri::{AppHandle, Manager, Runtime};
+
+/// 随包清单文件名(只有离线包构建会写入)
+const MANIFEST_FILE: &str = "bundle.json";
+/// 随包 Node.js 运行时目录名
+pub const BUNDLE_NODE_DIR: &str = "node";
+/// 随包 Harness 发行版目录名
+pub const BUNDLE_DSH_DIR: &str = "dsh";
+/// 随包 pnpm 目录名
+pub const BUNDLE_PNPM_DIR: &str = "pnpm";
+
+/// 随包清单 `resources/bundle.json`:只有 `dsh` 是运行时需要的字段
+/// (内置核心的版本 / tag / 提交标识),Node、pnpm、平台等仅作构建期记录。
+#[derive(Debug, Clone, Deserialize)]
+pub struct BundleManifest {
+ #[serde(default)]
+ pub dsh: Option<BundleDsh>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct BundleDsh {
+ pub version: String,
+ #[serde(default)]
+ pub tag: Option<String>,
+ #[serde(default)]
+ pub commit: Option<String>,
+}
+
+/// 安装包资源根下的候选位置。
+///
+/// Tauri 2 在 Windows 上 `resource_dir()` 恒等于 exe 所在目录,而资源实际按
+/// `resources/**` 前缀落盘到 `{resource_dir}/resources/`,因此两个位置都要探测
+/// (与 `plugin::preset` 的查找策略一致)。
+fn resource_candidates<R: Runtime>(app_handle: &AppHandle<R>, name: &str) -> Vec<PathBuf> {
+ let mut paths = Vec::new();
+ if let Ok(dir) = app_handle.path().resource_dir() {
+ paths.push(dir.join(name));
+ paths.push(dir.join("resources").join(name));
+ }
+ paths
+}
+
+fn find_resource<R: Runtime>(app_handle: &AppHandle<R>, name: &str) -> Option<PathBuf> {
+ resource_candidates(app_handle, name)
+ .into_iter()
+ .find(|path| path.exists())
+}
+
+/// 本次安装是否由离线包构建产出(`resources/bundle.json` 是唯一判据)。
+pub fn is_offline_bundle<R: Runtime>(app_handle: &AppHandle<R>) -> bool {
+ resource_candidates(app_handle, MANIFEST_FILE)
+ .into_iter()
+ .any(|path| path.is_file())
+}
+
+/// 读取随包清单(缺失/损坏时返回 None)。
+pub fn bundle_manifest<R: Runtime>(app_handle: &AppHandle<R>) -> Option<BundleManifest> {
+ let path = resource_candidates(app_handle, MANIFEST_FILE)
+ .into_iter()
+ .find(|path| path.is_file())?;
+ serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
+}
+
+/// 随包 Node.js 运行时目录
+pub fn bundled_node_dir<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
+ find_resource(app_handle, BUNDLE_NODE_DIR).filter(|path| path.is_dir())
+}
+
+/// 随包 Harness 发行版目录
+pub fn bundled_dsh_dir<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
+ find_resource(app_handle, BUNDLE_DSH_DIR).filter(|path| path.is_dir())
+}
+
+/// 随包 pnpm 目录
+pub fn bundled_pnpm_dir<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
+ find_resource(app_handle, BUNDLE_PNPM_DIR).filter(|path| path.is_dir())
+}
+
+/// 随包 Node.js 可执行文件(未随包分发或文件缺失时返回 None)。
+pub fn bundled_node_binary<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
+ let dir = bundled_node_dir(app_handle)?;
+ let binary = if cfg!(windows) {
+ dir.join("node.exe")
+ } else {
+ dir.join("bin").join("node")
+ };
+ binary.is_file().then_some(binary)
+}
+
+/// 随包 pnpm CLI 入口(纯 JS 发行,用 node 运行)。
+pub fn bundled_pnpm_binary<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
+ let binary = bundled_pnpm_dir(app_handle)?.join(crate::config::PNPM_ENTRY_RELATIVE);
+ binary.is_file().then_some(binary)
+}
+
+/// 随包核心的 dsh 入口。
+pub fn bundled_dsh_binary<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
+ let binary = bundled_dsh_dir(app_handle)?.join(crate::config::DSH_ENTRY_RELATIVE);
+ binary.is_file().then_some(binary)
+}
+
+/// 读取发行版目录 `package.json` 中 `@deepseek-ai/dsh` 依赖版本。
+fn read_manifest_dsh_version(dir: &std::path::Path) -> Option<String> {
+ let value: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(dir.join("package.json")).ok()?).ok()?;
+ value
+ .get("dependencies")?
+ .get("@deepseek-ai/dsh")?
+ .as_str()
+ .map(|version| version.trim_start_matches(['^', '~', '=', '>', '<']).to_string())
+}
+
+/// 内置核心版本号:随包清单优先,清单缺失时读 `resources/dsh/package.json`。
+pub fn bundled_dsh_version<R: Runtime>(app_handle: &AppHandle<R>) -> Option<String> {
+ if let Some(version) = bundle_manifest(app_handle)
+ .and_then(|manifest| manifest.dsh)
+ .map(|dsh| dsh.version)
+ .filter(|version| !version.is_empty())
+ {
+ return Some(version);
+ }
+ bundled_dsh_dir(app_handle).and_then(|dir| read_manifest_dsh_version(&dir))
+}
+
+/// 内置核心对应的 release tag:清单优先,缺失时按版本号合成一个可被
+/// `download::parse_version_from_tag` 解析的 tag(槽位目录名即 tag)。
+pub fn bundled_core_tag<R: Runtime>(app_handle: &AppHandle<R>) -> Option<String> {
+ if let Some(tag) = bundle_manifest(app_handle)
+ .and_then(|manifest| manifest.dsh)
+ .and_then(|dsh| dsh.tag)
+ .filter(|tag| !tag.is_empty())
+ {
+ return Some(tag);
+ }
+ bundled_dsh_version(app_handle).map(|version| format!("dsh-{version}-bundled"))
+}
+
+/// 内置核心对应的提交标识(清单未记录时为空)。
+pub fn bundled_core_commit<R: Runtime>(app_handle: &AppHandle<R>) -> Option<String> {
+ bundle_manifest(app_handle)
+ .and_then(|manifest| manifest.dsh)
+ .and_then(|dsh| dsh.commit)
+ .filter(|commit| !commit.is_empty())
+}
+
+/// 版本是否为内置核心版本(核心列表据此标注「内置核心」并禁止卸载)。
+pub fn is_bundled_core_version<R: Runtime>(app_handle: &AppHandle<R>, version: &str) -> bool {
+ !version.is_empty() && bundled_dsh_version(app_handle).as_deref() == Some(version)
+}
diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs
index ed4dbfce..a5e79923 100644
--- a/src-tauri/src/config/mod.rs
+++ b/src-tauri/src/config/mod.rs
@@ -1,3 +1,4 @@
+mod bundle;
mod constants;
mod format;
pub mod i18n;
@@ -9,6 +10,7 @@ mod utils;
mod version_recommend;
mod window_state;
+pub use bundle::*;
pub use constants::*;
pub use format::*;
pub use region::*;
diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs
index 4fffa569..d49e3a98 100644
--- a/src-tauri/src/config/runtime.rs
+++ b/src-tauri/src/config/runtime.rs
@@ -5,6 +5,7 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::{AppHandle, Manager, Runtime};
+use super::bundle::{bundled_node_binary, bundled_pnpm_dir};
use super::constants::*;
use super::format::get_dsh_service_url;
use super::utils::search_node_binary;
@@ -218,8 +219,8 @@ pub fn set_prefer_bundled_node_runtime(prefer: bool) {
PREFER_BUNDLED_NODE_RUNTIME.store(prefer, Ordering::Relaxed);
}
-/// 已安装的捆绑运行时 node 二进制(未安装时返回 None)
-pub fn bundled_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {
+/// 已下载到应用数据目录的捆绑运行时 node 二进制(未安装时返回 None)
+pub fn runtime_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {
let runtime_dir = get_node_install_path(app_handle);
// 使用 cfg 宏在编译时确定文件名
let (rel_path, bin_name) = if cfg!(windows) {
@@ -238,8 +239,9 @@ pub fn bundled_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {
/// Node.js 二进制路径
///
-/// 优先级:ABI 探测要求捆绑运行时(原生模块不匹配时的兜底)> 本地版本兼容的
-/// Node.js 环境 > 已安装的捆绑运行时
+/// 优先级:离线安装包的随包运行时(唯一来源,见 [`bundled_node_binary`])>
+/// ABI 探测要求捆绑运行时(原生模块不匹配时的兜底)> 本地版本兼容的
+/// Node.js 环境 > 应用数据目录中已下载的捆绑运行时
pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {
let runtime_dir = get_node_install_path(app_handle);
let (rel_path, bin_name) = if cfg!(windows) {
@@ -247,7 +249,15 @@ pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {
} else {
("bin", "node")
};
- let bundled = bundled_node_binary(app_handle);
+
+ // 离线安装包:随包运行时与随包核心由同一次构建产出、ABI 天然对齐,直接使用并
+ // 完全跳过本地 node 与 AppData 副本,避免版本选择引入不必要的分支。
+ if let Some(bundled) = bundled_node_binary(app_handle) {
+ log::debug!("Using bundled Node.js runtime: {}", bundled.display());
+ return bundled;
+ }
+
+ let bundled = runtime_node_binary(app_handle);
if prefer_bundled_node_runtime() {
if let Some(bundled) = bundled.clone() {
@@ -286,16 +296,23 @@ pub fn get_dsh_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {
get_dsh_install_path(app_handle).join(DSH_ENTRY_RELATIVE)
}
-/// pnpm 安装目录
+/// pnpm 安装目录(应用数据目录中已下载的捆绑 pnpm)
pub fn get_pnpm_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {
get_base_dir(app_handle)
.join("dependencies")
.join(PNPM_CORE_DIR)
}
-/// 捆绑 pnpm CLI 入口(纯 JS 发行,用 node 运行)
+/// 当前使用的 pnpm 目录:离线安装包的随包 pnpm 优先,其次应用数据目录。
+pub fn get_pnpm_runtime_dir<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {
+ bundled_pnpm_dir(app_handle).unwrap_or_else(|| get_pnpm_install_path(app_handle))
+}
+
+/// 当前使用的 pnpm CLI 入口(纯 JS 发行,用 node 运行)。
+///
+/// 离线安装包直接使用 `resources/pnpm`,完全跳过本地 pnpm 与 AppData 副本。
pub fn get_pnpm_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {
- get_pnpm_install_path(app_handle).join(PNPM_ENTRY_RELATIVE)
+ get_pnpm_runtime_dir(app_handle).join(PNPM_ENTRY_RELATIVE)
}
/// pnpm 官方/镜像下载前缀:国内走 npmmirror registry,其他直连 npmjs.org
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index c81afe37..8247f8da 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -44,7 +44,8 @@ pub struct Setting {
#[serde(default)]
pub desktop_profile_ready: bool,
/// 活动核心的显式选择:`Some("local")` = 用户 CLI 安装的本地核心,
- /// `Some("app")` = 桌面端预打包核心;`None` = 自动(本地核心存在时优先)。
+ /// `Some("app")` = 桌面端预打包核心;`None` = 自动(离线包用内置核心,
+ /// 否则本地核心存在时优先)。
#[serde(default)]
pub active_core: Option<String>,
/// 用户手动设置的服务端口(设置页「端口」输入,见 bridge::config)。
diff --git a/src-tauri/src/service/bundle/mod.rs b/src-tauri/src/service/bundle/mod.rs
new file mode 100644
index 00000000..bbbca514
--- /dev/null
+++ b/src-tauri/src/service/bundle/mod.rs
@@ -0,0 +1,827 @@
+//! 离线安装包随包资源的**零拷贝落位**。
+//!
+//! 离线包把 Node.js 运行时、推荐 dsh 内核与 pnpm 预解压进 `resources/{node,dsh,pnpm}`
+//! (内核 127 MiB / 一万余文件)。直接使用这些目录是不行的:桌面端每次启动都会往里
+//! 写东西——`service::patch` 会改写 `node_modules/@deepseek-ai` 下的 8 个文件(其中
+//! `alpha_auth` 决定要不要给服务传 `--skip-auth`),`prepare_active_runtime` 要在核心
+//! 的 `node_modules` 下建内置插件与 profile 插件的入口链接。而 macOS 的 `.app`、
+//! Linux 的 AppImage/deb 里的 `resources/` 都是只读的。
+//!
+//! 落位分三块,都不复制大块内容:
+//!
+//! 1. **Node / pnpm**:整目录链接到既有路径约定(`{app_data}/runtime`、
+//! `{app_data}/dependencies/pnpm`)。两者全程只读使用(pnpm 的 store 在
+//! `$DSH_HOME`),一个链接即可满足 `config::get_node_install_path`、CLI shim 里
+//! 写死的 `%APP_DIR%\runtime\node.exe` 等全部既有约定。
+//! 2. **dsh 内核**:在 `dependencies/dsh` 落位,方式按随包核心目录**是否可写**每次
+//! 启动重新判定([`core_writable`]):
+//!
+//! - [`LinkMode::Link`](可写,Windows 每用户安装即如此):`dependencies/dsh`
+//! 就是 `resources/dsh` 的目录链接。补丁直接写穿到随包资源上——**被加载的就是
+//! 被改写的同一份文件**,零额外磁盘占用,不存在"补丁副本与核心不同步"。
+//! - [`LinkMode::Layer`](只读):建一层链接层,只把补丁目标的祖先目录复制成真实
+//! 文件,其余目录建链接。补丁写入落在应用数据目录。
+//!
+//! 链接层哪些目录必须真实,由补丁层自己声明([`real_dirs`] 读
+//! `service::patch::patched_paths()`):补丁写不穿目录链接,写在只读资源上必然
+//! 失败,而 `patch_dsh` 对失败只记日志——`alpha_auth` 的补丁落不了地,
+//! `--skip-auth` 就不会下发,内嵌页面会要求登录。新增补丁只要登记进声明,两种
+//! 模式都自动跟随;落位后逐项自检(链路真实 + 可写),把脱节变成硬错误而不是
+//! 运行时静默降级。
+//! 3. **核心切换照旧**:`dependencies/dsh` ↔ `dependencies/<tag>` 仍是目录互换,
+//! 链接/链接层都能被重命名。用户下载的真实核心绝不覆盖——活动槽位被真实核心占用
+//! 时,内置核心退到自己的 tag 槽位,作为可切换的普通版本存在。
+
+use crate::config;
+use crate::service::core::create_directory_link;
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use std::fs;
+use std::path::{Path, PathBuf};
+use tauri::AppHandle;
+
+/// 链接层标记文件(只用于 [`LinkMode::Layer`]:链接层是真实目录,可以放标记)。
+///
+/// `Link` 模式不放标记:核心目录本身是指向随包资源的链接,标记会写进安装包资源;
+/// 该模式的归属由"它是指向当前随包核心的链接"直接判定。
+const MARKER_FILE: &str = ".bundle-links.json";
+
+/// 内置核心落位方式。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum LinkMode {
+ /// 随包核心目录可写:`dependencies/dsh` 就是它的目录链接,补丁写穿到
+ /// `resources/dsh`。
+ Link,
+ /// 随包核心目录只读:链接层,补丁目标复制为真实文件。
+ Layer,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+struct LinkMarker {
+ /// 链接层指向的随包核心目录(绝对路径)
+ source: String,
+ /// 生成链接层时的内置核心版本
+ version: String,
+}
+
+fn read_marker(dir: &Path) -> Option<LinkMarker> {
+ let content = fs::read_to_string(dir.join(MARKER_FILE)).ok()?;
+ serde_json::from_str(&content).ok()
+}
+
+/// 必须以**真实文件**落地的目录(相对核心根)。
+///
+/// 来自 `service::patch::patched_paths()` 的声明——补丁的写入目标及其全部祖先目录。
+/// 这些目录一旦是链接,写入就会透传到只读的随包资源上;`patch_dsh` 对失败只记日志,
+/// 表现为补丁静默失效。`node_modules` 本身始终真实:`prepare_active_runtime` 要在
+/// 这里建内置插件与 profile 插件的入口链接。
+///
+/// 刻意不做成"复制某个 scope":那样既多复制几十 MB,又把补丁目标与落位逻辑的耦合
+/// 写死在两个地方——新增补丁落在别的包里就会静默失效。
+fn real_dirs() -> HashSet<PathBuf> {
+ let mut dirs = HashSet::from([PathBuf::from("node_modules")]);
+ for target in crate::service::patch::patched_paths() {
+ let mut parent = Path::new(target).parent();
+ while let Some(dir) = parent {
+ if dir.as_os_str().is_empty() {
+ break;
+ }
+ dirs.insert(dir.to_path_buf());
+ parent = dir.parent();
+ }
+ }
+ dirs
+}
+
+/// 随包核心目录是否可写:能否在里面创建并删除一个探针文件。
+///
+/// 决定用 [`LinkMode::Link`] 还是 [`LinkMode::Layer`]。每次启动重新探测:权限/挂载
+/// 方式变了会自动切换模式,而不是留下一个补丁写不进去的核心。
+fn core_writable(dir: &Path) -> bool {
+ let probe = dir.join(format!(".dsh-write-probe-{}", std::process::id()));
+ if fs::write(&probe, b"").is_err() {
+ return false;
+ }
+ let _ = fs::remove_file(&probe);
+ true
+}
+
+fn is_link(path: &Path) -> Result<bool, String> {
+ Ok(fs::symlink_metadata(path)
+ .map_err(|e| format!("BUNDLE_LINKS_STAT_FAILED: {}: {e}", path.display()))?
+ .file_type()
+ .is_symlink())
+}
+
+/// 判定某个目录是否已经是当前随包核心的落位产物,以及用的哪种方式。
+fn materialized_mode(dir: &Path, source: &Path, version: &str) -> Option<LinkMode> {
+ let metadata = fs::symlink_metadata(dir).ok()?;
+ if metadata.file_type().is_symlink() {
+ let target = fs::read_link(dir).ok()?;
+ let target = if target.is_absolute() {
+ target
+ } else {
+ dir.parent()?.join(target)
+ };
+ // 链接指向当前随包核心即可:资源被新安装包替换后链接自动指向新版本,
+ // 不需要重建(补丁会在启动时按新内容重新判定)。
+ let resolved = fs::canonicalize(target).ok()?;
+ return (resolved == fs::canonicalize(source).ok()?).then_some(LinkMode::Link);
+ }
+ if !metadata.is_dir() {
+ return None;
+ }
+ let marker = read_marker(dir)?;
+ (marker.source == source.to_string_lossy() && marker.version == version)
+ .then_some(LinkMode::Layer)
+}
+
+/// 内置核心是否需要(重新)落位;`None` 表示已就绪或让位给用户自己的核心。
+fn plan(app_handle: &AppHandle, source: &Path, version: &str, tag: &str, mode: LinkMode) -> Option<PathBuf> {
+ let active = config::get_dsh_install_path(app_handle);
+ if let Some(current) = materialized_mode(&active, source, version) {
+ return if current == mode && verify_patch_targets(&active, false).is_ok() {
+ None
+ } else {
+ Some(active)
+ };
+ }
+ // 不存在,或是我们自己留下的链接(含悬垂链接):直接落位为活动核心
+ if !active.exists() || is_link(&active).unwrap_or(false) {
+ return Some(active);
+ }
+
+ // 活动槽位是用户自己的真实核心:内置核心退到自己的 tag 槽位
+ let slot = active
+ .parent()
+ .map(|deps| deps.join(tag))
+ .unwrap_or_else(|| active.clone());
+ if let Some(current) = materialized_mode(&slot, source, version) {
+ return if current == mode && verify_patch_targets(&slot, false).is_ok() {
+ None
+ } else {
+ Some(slot)
+ };
+ }
+ if !slot.exists() || is_link(&slot).unwrap_or(false) {
+ return Some(slot);
+ }
+ log::info!(
+ "BUNDLE_LINKS_SKIP: {} is occupied by a downloaded core, keeping it untouched",
+ slot.display()
+ );
+ None
+}
+
+/// 把随包内置核心落位到应用数据目录(幂等)。
+///
+/// 返回是否真正(重新)落位。普通安装包(无 `resources/bundle.json`)直接空转。
+pub fn materialize(app_handle: &AppHandle) -> Result<bool, String> {
+ if !config::is_offline_bundle(app_handle) {
+ return Ok(false);
+ }
+ // Node / pnpm 的链接与内核落位互不依赖:任一项失败都不应连带跳过另一项。
+ link_runtime_dirs(app_handle);
+ materialize_core(app_handle)
+}
+
+/// 随包 Node 运行时与 pnpm 以整目录链接落到既有路径约定上。
+///
+/// 两者全程只读使用(pnpm 的 store 在 `$DSH_HOME`,Node 只被启动/调用),因此一个
+/// 目录链接即可零拷贝满足全部既有约定:`config::get_node_install_path` 的
+/// `runtime/`、`dependencies/pnpm`,以及 CLI shim 里写死的
+/// `%APP_DIR%\runtime\node.exe` 与 `%APP_DIR%\dependencies\pnpm\bin\pnpm.cjs`。
+/// 已有真实运行时(用户下载过)时不覆盖。
+fn link_runtime_dirs(app_handle: &AppHandle) {
+ // 逐项独立:Node 链接失败不应连带跳过 pnpm(反之亦然),失败项由
+ // `Installable::check_installed` 走原有下载路径兜底。
+ if let Some(node) = config::bundled_node_dir(app_handle) {
+ if let Err(e) = link_runtime_dir(&node, &config::get_node_install_path(app_handle), "node") {
+ log::warn!("{e}");
+ }
+ }
+ if let Some(pnpm) = config::bundled_pnpm_dir(app_handle) {
+ if let Err(e) = link_runtime_dir(&pnpm, &config::get_pnpm_install_path(app_handle), "pnpm") {
+ log::warn!("{e}");
+ }
+ }
+}
+
+fn link_runtime_dir(source: &Path, dest: &Path, label: &str) -> Result<(), String> {
+ match fs::symlink_metadata(dest) {
+ // 悬垂链接(随包资源被移动/删除):先移除再重建,避免永久失效
+ Ok(meta) if meta.file_type().is_symlink() && !dest.exists() => remove_link(dest)?,
+ Ok(_) => return Ok(()),
+ Err(_) => {}
+ }
+ if let Some(parent) = dest.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("BUNDLE_LINKS_RUNTIME_FAILED: {}: {e}", parent.display()))?;
+ }
+ let absolute = fs::canonicalize(source)
+ .map_err(|e| format!("BUNDLE_LINKS_RUNTIME_FAILED: {}: {e}", source.display()))?;
+ create_directory_link(&absolute, dest).map_err(|e| {
+ format!(
+ "BUNDLE_LINKS_RUNTIME_FAILED: {label}: {} -> {}: {e}",
+ dest.display(),
+ absolute.display()
+ )
+ })
+}
+
+/// 内置核心落位:见模块头。
+fn materialize_core(app_handle: &AppHandle) -> Result<bool, String> {
+ let Some(source) = config::bundled_dsh_dir(app_handle) else {
+ return Ok(false);
+ };
+ // 随包目录不完整(构建缺陷)时不做落位:让原有下载路径兜底。
+ if config::bundled_dsh_binary(app_handle).is_none() {
+ log::warn!(
+ "BUNDLE_LINKS_INCOMPLETE: bundled core entry is missing under {}",
+ source.display()
+ );
+ return Ok(false);
+ }
+ let Some(version) = config::bundled_dsh_version(app_handle) else {
+ return Ok(false);
+ };
+ let tag = config::bundled_core_tag(app_handle)
+ .unwrap_or_else(|| format!("dsh-{version}-bundled"));
+ let mode = if core_writable(&source) {
+ LinkMode::Link
+ } else {
+ LinkMode::Layer
+ };
+
+ let Some(target) = plan(app_handle, &source, &version, &tag, mode) else {
+ return Ok(false);
+ };
+
+ materialize_into(&source, &target, &version, mode)?;
+ log::info!(
+ "BUNDLE_LINKS: materialized bundled core {version} at {} ({mode:?}, source {})",
+ target.display(),
+ source.display()
+ );
+
+ // 内置核心的记录 tag/commit:核心列表据此标注「内置核心」,切换时也据此命名
+ // 备份槽位。只在活动槽位就是内置核心时写入,避免覆盖用户所选核心的记录。
+ if target == config::get_dsh_install_path(app_handle) {
+ let commit = config::bundled_core_commit(app_handle);
+ config::update_store_dat_setting(app_handle, |setting| {
+ setting.dsh_pkg_tag = Some(tag);
+ if commit.is_some() {
+ setting.dsh_pkg_commit = commit;
+ }
+ });
+ }
+ Ok(true)
+}
+
+fn materialize_into(source: &Path, target: &Path, version: &str, mode: LinkMode) -> Result<(), String> {
+ remove_materialized(target)?;
+ match mode {
+ LinkMode::Link => {
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("BUNDLE_LINKS_CREATE_FAILED: {}: {e}", parent.display()))?;
+ }
+ let absolute = fs::canonicalize(source)
+ .map_err(|e| format!("BUNDLE_LINKS_CREATE_FAILED: {}: {e}", source.display()))?;
+ create_directory_link(&absolute, target).map_err(|e| {
+ format!(
+ "BUNDLE_LINKS_LINK_FAILED: {} -> {}: {e}",
+ target.display(),
+ absolute.display()
+ )
+ })?;
+ }
+ LinkMode::Layer => build_link_layer(source, target, version)?,
+ }
+ // 落位完立即自检:补丁目标必须真实可写。这里失败说明落位方式与补丁声明脱节,
+ // 属于必须修的缺陷,不能等补丁在运行时静默失效。
+ verify_patch_targets(target, true)
+}
+
+/// 删除上一次的落位产物:链接只删入口,链接层只删链接与它自己复制的内容。
+///
+/// 调用方([`plan`])已确认目标属于内置核心;真实核心绝不会走到这里。
+fn remove_materialized(target: &Path) -> Result<(), String> {
+ match fs::symlink_metadata(target) {
+ Err(_) => Ok(()),
+ Ok(meta) if meta.file_type().is_symlink() => remove_link(target),
+ Ok(_) => remove_link_layer(target),
+ }
+}
+
+/// 建链接层:只有补丁目标的祖先目录与 `node_modules` 复制为真实内容,其余目录建
+/// 链接,文件一律复制(文件链接在 Windows 上需要特权)。
+fn build_link_layer(source: &Path, dest: &Path, version: &str) -> Result<(), String> {
+ let real = real_dirs();
+ build_tree(source, dest, Path::new(""), &real)?;
+
+ let marker = LinkMarker {
+ source: source.to_string_lossy().into_owned(),
+ version: version.to_string(),
+ };
+ let payload = serde_json::to_string_pretty(&marker)
+ .map_err(|e| format!("BUNDLE_LINKS_MARKER_FAILED: {e}"))?;
+ fs::write(dest.join(MARKER_FILE), payload)
+ .map_err(|e| format!("BUNDLE_LINKS_MARKER_FAILED: {}: {e}", dest.display()))?;
+ Ok(())
+}
+
+/// 递归建树:`real` 里的目录(补丁目标的祖先 + `node_modules`)复制为真实目录,
+/// 其余目录建链接,文件一律复制。
+fn build_tree(src: &Path, dest: &Path, rel: &Path, real: &HashSet<PathBuf>) -> Result<(), String> {
+ fs::create_dir_all(dest)
+ .map_err(|e| format!("BUNDLE_LINKS_CREATE_FAILED: {}: {e}", dest.display()))?;
+ for entry in read_dir(src)? {
+ let from = entry.path();
+ let name = entry.file_name();
+ let to = dest.join(&name);
+ let rel_child = rel.join(&name);
+ let metadata = fs::symlink_metadata(&from)
+ .map_err(|e| format!("BUNDLE_LINKS_ENTRY_FAILED: {}: {e}", from.display()))?;
+ if metadata.is_dir() && !metadata.file_type().is_symlink() {
+ if real.contains(&rel_child) {
+ build_tree(&from, &to, &rel_child, real)?;
+ } else {
+ link_entry(&from, &to)?;
+ }
+ } else {
+ copy_tree(&from, &to)?;
+ }
+ }
+ Ok(())
+}
+
+/// 校验所有补丁目标从核心根**之下**到文件的整条链路都是真实目录。
+///
+/// 只检查文件本身是不是链接是不够的:`node_modules/@deepseek-ai` 是链接时,其下的
+/// `dsh-web-app/lib/startup.js` 在 `symlink_metadata` 眼里仍是普通文件,写入却会
+/// 透传到只读的随包资源。因此逐级上溯,任何一级是链接即判定失败。
+///
+/// 核心根自身不计入:[`LinkMode::Link`] 下它本来就是链接,而链接目标的可写性由
+/// [`core_writable`] 单独保证(每次启动重新探测)。
+///
+/// `probe_writes` 为真时额外尝试以写模式打开:只读挂载/权限异常下补丁会静默失败,
+/// 落位阶段就要暴露出来(启动路径上的常规校验不做写探测,避免与运行中的进程抢锁)。
+fn verify_patch_targets(dir: &Path, probe_writes: bool) -> Result<(), String> {
+ for target in crate::service::patch::patched_paths() {
+ let path = dir.join(target);
+ if !path.exists() {
+ // 该核心版本没有这个文件:补丁本来就会安全跳过。
+ continue;
+ }
+ let mut node = Some(path.as_path());
+ while let Some(current) = node {
+ if !current.starts_with(dir) || current == dir {
+ break;
+ }
+ if is_link(current)? {
+ return Err(format!(
+ "BUNDLE_LINKS_PATCH_TARGET_LINKED: {target} is behind a directory link ({}), patches cannot be written",
+ current.display()
+ ));
+ }
+ node = current.parent();
+ }
+ if probe_writes {
+ fs::OpenOptions::new()
+ .write(true)
+ .open(&path)
+ .map_err(|e| format!("BUNDLE_LINKS_PATCH_TARGET_READONLY: {target}: {e}"))?;
+ }
+ }
+ Ok(())
+}
+
+fn read_dir(dir: &Path) -> Result<Vec<fs::DirEntry>, String> {
+ let entries = fs::read_dir(dir)
+ .map_err(|e| format!("BUNDLE_LINKS_READ_FAILED: {}: {e}", dir.display()))?;
+ entries
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| format!("BUNDLE_LINKS_READ_FAILED: {}: {e}", dir.display()))
+}
+
+/// 目录建链接,文件直接复制。
+///
+/// 文件不做链接:Windows 的文件符号链接同样需要 SeCreateSymbolicLinkPrivilege,而
+/// junction 回退只适用于目录;顶层只有 `package.json` / `package-lock.json` 两个
+/// 小文件,复制代价可忽略。链接失败(文件系统不支持)时退回整目录复制。
+fn link_entry(from: &Path, to: &Path) -> Result<(), String> {
+ let metadata = fs::symlink_metadata(from)
+ .map_err(|e| format!("BUNDLE_LINKS_ENTRY_FAILED: {}: {e}", from.display()))?;
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
+ return copy_tree(from, to);
+ }
+ // 链接目标必须是绝对路径:junction 记录的是字面目标,相对路径会在应用数据
+ // 目录下解析到错误位置。
+ let absolute = fs::canonicalize(from)
+ .map_err(|e| format!("BUNDLE_LINKS_ENTRY_FAILED: {}: {e}", from.display()))?;
+ match create_directory_link(&absolute, to) {
+ Ok(()) => Ok(()),
+ Err(e) => {
+ log::warn!(
+ "BUNDLE_LINKS_FALLBACK_COPY: cannot link {} -> {} ({e}), copying instead",
+ to.display(),
+ absolute.display()
+ );
+ copy_tree(from, to)
+ }
+ }
+}
+
+/// 递归复制目录/文件(Unix 上原样重建符号链接)。
+fn copy_tree(src: &Path, dest: &Path) -> Result<(), String> {
+ let metadata = fs::symlink_metadata(src)
+ .map_err(|e| format!("BUNDLE_LINKS_COPY_FAILED: {}: {e}", src.display()))?;
+ if metadata.file_type().is_symlink() {
+ return copy_symlink(src, dest);
+ }
+ if metadata.is_dir() {
+ fs::create_dir_all(dest)
+ .map_err(|e| format!("BUNDLE_LINKS_COPY_FAILED: {}: {e}", dest.display()))?;
+ for entry in read_dir(src)? {
+ copy_tree(&entry.path(), &dest.join(entry.file_name()))?;
+ }
+ return Ok(());
+ }
+ if let Some(parent) = dest.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("BUNDLE_LINKS_COPY_FAILED: {}: {e}", parent.display()))?;
+ }
+ fs::copy(src, dest).map_err(|e| {
+ format!(
+ "BUNDLE_LINKS_COPY_FAILED: {} -> {}: {e}",
+ src.display(),
+ dest.display()
+ )
+ })?;
+ Ok(())
+}
+
+#[cfg(unix)]
+fn copy_symlink(src: &Path, dest: &Path) -> Result<(), String> {
+ let target = fs::read_link(src)
+ .map_err(|e| format!("BUNDLE_LINKS_COPY_FAILED: {}: {e}", src.display()))?;
+ if let Some(parent) = dest.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("BUNDLE_LINKS_COPY_FAILED: {}: {e}", parent.display()))?;
+ }
+ std::os::unix::fs::symlink(&target, dest).map_err(|e| {
+ format!(
+ "BUNDLE_LINKS_COPY_FAILED: {} -> {}: {e}",
+ src.display(),
+ dest.display()
+ )
+ })
+}
+
+#[cfg(not(unix))]
+fn copy_symlink(src: &Path, dest: &Path) -> Result<(), String> {
+ let resolved = fs::canonicalize(src)
+ .map_err(|e| format!("BUNDLE_LINKS_COPY_FAILED: {}: {e}", src.display()))?;
+ copy_tree(&resolved, dest)
+}
+
+/// 删除链接层:只移除链接本身,绝不递归进入链接目标(否则会删掉随包资源)。
+fn remove_link_layer(dest: &Path) -> Result<(), String> {
+ for entry in read_dir(dest)? {
+ let path = entry.path();
+ let metadata = fs::symlink_metadata(&path)
+ .map_err(|e| format!("BUNDLE_LINKS_REMOVE_FAILED: {}: {e}", path.display()))?;
+ if metadata.file_type().is_symlink() {
+ remove_link(&path)?;
+ } else if metadata.is_dir() {
+ fs::remove_dir_all(&path)
+ .map_err(|e| format!("BUNDLE_LINKS_REMOVE_FAILED: {}: {e}", path.display()))?;
+ } else {
+ fs::remove_file(&path)
+ .map_err(|e| format!("BUNDLE_LINKS_REMOVE_FAILED: {}: {e}", path.display()))?;
+ }
+ }
+ fs::remove_dir(dest)
+ .map_err(|e| format!("BUNDLE_LINKS_REMOVE_FAILED: {}: {e}", dest.display()))
+}
+
+/// 只删除链接入口本身。Windows 的 junction 是目录重解析点,用 `remove_dir` 移除。
+fn remove_link(path: &Path) -> Result<(), String> {
+ #[cfg(windows)]
+ let result = fs::remove_dir(path).or_else(|_| fs::remove_file(path));
+ #[cfg(not(windows))]
+ let result = fs::remove_file(path);
+ result.map_err(|e| format!("BUNDLE_LINKS_REMOVE_FAILED: {}: {e}", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp_dir(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("dsh-bundle-links-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ dir
+ }
+
+ /// 造一个最小内核:按**真实补丁声明**生成补丁目标,再放一个同 scope 下的非补丁包
+ /// 与一个顶层包——后两者在链接层里必须保持链接。
+ fn fake_core(root: &Path) {
+ for target in crate::service::patch::patched_paths() {
+ let path = root.join(target);
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(&path, b"original").unwrap();
+ }
+ let untouched = root.join("node_modules/@deepseek-ai/dsh-web-frontend");
+ fs::create_dir_all(&untouched).unwrap();
+ fs::write(untouched.join("index.js"), b"frontend").unwrap();
+ let plain = root.join("node_modules/node-pty");
+ fs::create_dir_all(&plain).unwrap();
+ fs::write(plain.join("index.js"), b"pty").unwrap();
+ fs::write(
+ root.join("package.json"),
+ br#"{"dependencies":{"@deepseek-ai/dsh":"0.1.5-rc.2"}}"#,
+ )
+ .unwrap();
+ fs::write(root.join("package-lock.json"), b"{}").unwrap();
+ }
+
+ fn first_patch_target() -> &'static str {
+ crate::service::patch::patched_paths()[0]
+ }
+
+ /// `Link` 模式:核心目录就是随包资源的链接,补丁**直接写进 resources/dsh**。
+ #[test]
+ fn link_mode_patches_resources_in_place() {
+ let root = temp_dir("link-mode");
+ let source = root.join("resources").join("dsh");
+ let target = root.join("dependencies").join("dsh");
+ fake_core(&source);
+
+ assert!(core_writable(&source));
+ materialize_into(&source, &target, "0.1.5-rc.2", LinkMode::Link).unwrap();
+
+ assert!(fs::symlink_metadata(&target).unwrap().file_type().is_symlink());
+ assert_eq!(
+ materialized_mode(&target, &source, "0.1.5-rc.2"),
+ Some(LinkMode::Link)
+ );
+
+ // 通过活动核心目录写入 = 写进随包资源本身(加载的与改写的是同一份文件)
+ for patch_target in crate::service::patch::patched_paths() {
+ let path = target.join(patch_target);
+ fs::write(&path, b"patched").unwrap();
+ assert_eq!(
+ fs::read(source.join(patch_target)).unwrap().as_slice(),
+ b"patched",
+ "Link 模式下补丁应落在随包资源上: {patch_target}"
+ );
+ }
+
+ // 删除只移除链接入口,随包资源保持不动
+ remove_materialized(&target).unwrap();
+ assert!(!target.exists());
+ assert!(source.join(first_patch_target()).is_file());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// `Layer` 模式:补丁目标复制为真实文件,写入不穿透到只读的随包资源。
+ #[test]
+ fn layer_mode_makes_exactly_the_patch_targets_real() {
+ let root = temp_dir("layer-mode");
+ let source = root.join("resources").join("dsh");
+ let target = root.join("dependencies").join("dsh");
+ fake_core(&source);
+
+ materialize_into(&source, &target, "0.1.5-rc.2", LinkMode::Layer).unwrap();
+
+ assert!(!fs::symlink_metadata(&target).unwrap().file_type().is_symlink());
+ assert_eq!(
+ materialized_mode(&target, &source, "0.1.5-rc.2"),
+ Some(LinkMode::Layer)
+ );
+
+ for patch_target in crate::service::patch::patched_paths() {
+ let patched = target.join(patch_target);
+ assert!(
+ !fs::symlink_metadata(&patched).unwrap().file_type().is_symlink(),
+ "补丁目标必须是真实文件: {patch_target}"
+ );
+ fs::write(&patched, b"patched").unwrap();
+ assert_eq!(
+ fs::read(source.join(patch_target)).unwrap().as_slice(),
+ b"original",
+ "补丁不得写进随包资源: {patch_target}"
+ );
+ }
+
+ // 无补丁的包保持链接,且 node_modules 本身是可写真实目录
+ for linked in [
+ "node_modules/@deepseek-ai/dsh-web-frontend",
+ "node_modules/node-pty",
+ ] {
+ let path = target.join(linked);
+ assert!(
+ fs::symlink_metadata(&path).unwrap().file_type().is_symlink(),
+ "无补丁的包必须保持链接: {linked}"
+ );
+ }
+ assert_eq!(
+ fs::read(target.join("node_modules/node-pty/index.js")).unwrap().as_slice(),
+ b"pty"
+ );
+ fs::create_dir(target.join("node_modules/dsh-tauri")).unwrap();
+
+ // 顶层文件复制为真实文件
+ assert!(!fs::symlink_metadata(target.join("package.json")).unwrap().file_type().is_symlink());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// 模式切换:可写→只读(或反之)时必须重建,而不是留下一个补丁写不进去的核心。
+ #[test]
+ fn mode_change_triggers_a_rebuild() {
+ let root = temp_dir("mode-switch");
+ let source = root.join("resources").join("dsh");
+ let target = root.join("dependencies").join("dsh");
+ fake_core(&source);
+
+ materialize_into(&source, &target, "0.1.5-rc.2", LinkMode::Link).unwrap();
+ assert_eq!(
+ materialized_mode(&target, &source, "0.1.5-rc.2"),
+ Some(LinkMode::Link)
+ );
+
+ materialize_into(&source, &target, "0.1.5-rc.2", LinkMode::Layer).unwrap();
+ assert_eq!(
+ materialized_mode(&target, &source, "0.1.5-rc.2"),
+ Some(LinkMode::Layer)
+ );
+ assert!(!fs::symlink_metadata(&target).unwrap().file_type().is_symlink());
+ // 切换后补丁不再写进随包资源
+ fs::write(target.join(first_patch_target()), b"patched").unwrap();
+ assert_eq!(
+ fs::read(source.join(first_patch_target())).unwrap().as_slice(),
+ b"original"
+ );
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// `real_dirs()` 必须覆盖每个补丁目标的全部祖先目录,否则那个目标会落在链接后面。
+ #[test]
+ fn real_dirs_cover_every_patch_ancestor() {
+ let real = real_dirs();
+ assert!(real.contains(&PathBuf::from("node_modules")));
+ for target in crate::service::patch::patched_paths() {
+ let mut parent = Path::new(target).parent();
+ while let Some(dir) = parent {
+ if dir.as_os_str().is_empty() {
+ break;
+ }
+ assert!(real.contains(dir), "缺少祖先目录 {dir:?}(目标 {target})");
+ parent = dir.parent();
+ }
+ }
+ }
+
+ /// 补丁目标被留在链接后面时必须**报错**,不能静默产出一个补丁写不进去的落位。
+ #[test]
+ fn patch_target_behind_a_link_fails_verification() {
+ let root = temp_dir("verify");
+ let source = root.join("resources").join("dsh");
+ fake_core(&source);
+ let target = root.join("dependencies").join("dsh");
+
+ // 造一个"整包链接"的错误布局:把补丁目标所在包直接链接过去
+ fs::create_dir_all(target.join("node_modules")).unwrap();
+ let patch_target = first_patch_target();
+ let package = Path::new(patch_target).parent().unwrap().parent().unwrap();
+ fs::create_dir_all(target.join(package).parent().unwrap()).unwrap();
+ let absolute = fs::canonicalize(source.join(package)).unwrap();
+ create_directory_link(&absolute, &target.join(package)).unwrap();
+
+ let error = verify_patch_targets(&target, false).expect_err("必须报错");
+ assert!(
+ error.starts_with("BUNDLE_LINKS_PATCH_TARGET_LINKED:"),
+ "unexpected error: {error}"
+ );
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// 目标文件不存在(该核心版本没有这个补丁点)时不算失败:补丁本来就会安全跳过。
+ #[test]
+ fn verification_passes_when_patch_targets_are_absent() {
+ let root = temp_dir("verify-absent");
+ let target = root.join("dependencies").join("dsh");
+ fs::create_dir_all(&target).unwrap();
+ assert!(verify_patch_targets(&target, false).is_ok());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// 用户自己下载的真实核心(无标记、非链接)绝不被认领、绝不删除。
+ #[test]
+ fn real_core_is_never_claimed_or_replaced() {
+ let root = temp_dir("occupied");
+ let source = root.join("resources").join("dsh");
+ fake_core(&source);
+ let real = root.join("dependencies").join("dsh");
+ fake_core(&real);
+
+ assert_eq!(materialized_mode(&real, &source, "0.1.5-rc.2"), None);
+ assert!(plan_free(&real, &source, "0.1.5-rc.2").is_none());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// `plan` 的"目标是否可用"判定:不存在或属于内置核心才可落位。
+ fn plan_free(dir: &Path, source: &Path, version: &str) -> Option<PathBuf> {
+ if let Some(_mode) = materialized_mode(dir, source, version) {
+ return Some(dir.to_path_buf());
+ }
+ if !dir.exists() || is_link(dir).unwrap_or(false) {
+ return Some(dir.to_path_buf());
+ }
+ None
+ }
+
+ /// 链接层重建时必须清掉上一次的残留(例如已卸载插件的入口链接)。
+ #[test]
+ fn rebuild_replaces_a_stale_layer() {
+ let root = temp_dir("rebuild");
+ let source = root.join("resources").join("dsh");
+ let target = root.join("dependencies").join("dsh");
+ fake_core(&source);
+ materialize_into(&source, &target, "0.1.5-rc.2", LinkMode::Layer).unwrap();
+ fs::create_dir(target.join("node_modules").join("stale-plugin")).unwrap();
+
+ materialize_into(&source, &target, "0.1.6-rc.1", LinkMode::Layer).unwrap();
+
+ assert!(!target.join("node_modules").join("stale-plugin").exists());
+ assert_eq!(read_marker(&target).unwrap().version, "0.1.6-rc.1");
+ assert!(source.join("node_modules/node-pty/index.js").is_file());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// 运行时整目录链接:建一次、幂等、已有真实运行时绝不覆盖。
+ #[test]
+ fn runtime_dir_link_is_idempotent_and_never_replaces_real_dirs() {
+ let root = temp_dir("runtime-link");
+ let source = root.join("resources").join("node");
+ fs::create_dir_all(&source).unwrap();
+ fs::write(source.join(if cfg!(windows) { "node.exe" } else { "node" }), b"node").unwrap();
+
+ let dest = root.join("runtime");
+ link_runtime_dir(&source, &dest, "node").unwrap();
+ assert!(fs::symlink_metadata(&dest).unwrap().file_type().is_symlink());
+ assert!(dest.join(if cfg!(windows) { "node.exe" } else { "node" }).is_file());
+
+ // 幂等:重复调用不报错也不重建
+ link_runtime_dir(&source, &dest, "node").unwrap();
+
+ // 已有真实运行时(用户下载过)时保持原样
+ let real = root.join("real-runtime");
+ fs::create_dir_all(&real).unwrap();
+ fs::write(real.join("marker"), b"downloaded").unwrap();
+ link_runtime_dir(&source, &real, "node").unwrap();
+ assert!(real.join("marker").is_file());
+ assert!(!fs::symlink_metadata(&real).unwrap().file_type().is_symlink());
+
+ let _ = fs::remove_dir_all(root);
+ }
+
+ /// `runtime/` 是指向随包运行时的链接时,下载路径的 `fs::remove_dir_all` 必须
+ /// 只删链接本身——否则一次「重装 Node」就会把 `resources/node` 整个删掉。
+ #[test]
+ fn remove_dir_all_does_not_follow_directory_links() {
+ let root = temp_dir("remove-all-link");
+ let source = root.join("resources").join("node");
+ fs::create_dir_all(&source).unwrap();
+ fs::write(source.join("node.exe"), b"node").unwrap();
+
+ let link = root.join("runtime");
+ link_runtime_dir(&source, &link, "node").unwrap();
+ assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
+
+ fs::remove_dir_all(&link).unwrap();
+
+ assert!(!link.exists(), "link entry must be gone");
+ assert!(
+ source.join("node.exe").is_file(),
+ "link target must survive remove_dir_all"
+ );
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn copy_tree_mirrors_directory_layout() {
+ let root = temp_dir("copy");
+ let src = root.join("src");
+ fs::create_dir_all(src.join("bin")).unwrap();
+ fs::write(src.join("bin/node"), b"binary").unwrap();
+
+ let dest = root.join("dest");
+ copy_tree(&src, &dest).unwrap();
+
+ assert_eq!(fs::read(dest.join("bin/node")).unwrap(), b"binary");
+ let _ = fs::remove_dir_all(root);
+ }
+}
diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rs
index 99d3c45d..239e75d4 100644
--- a/src-tauri/src/service/core/runtime.rs
+++ b/src-tauri/src/service/core/runtime.rs
@@ -257,7 +257,7 @@ impl NativeProbe {
// pkg 在固定 Node 大版本下构建,捆绑运行时与之对齐,因此先验证捆绑运行时;
// 探测通过则本进程内固定使用它(config::set_prefer_bundled_node_runtime)。
if probe.has_abi_mismatch() && !is_bundled_runtime_node(&node, app_handle) {
- if let Some(bundled) = crate::config::bundled_node_binary(app_handle) {
+ if let Some(bundled) = crate::config::runtime_node_binary(app_handle) {
if probe_native_modules(&bundled, &core_root).await.is_ready() {
log::warn!(
"CORE_NATIVE_ABI_MISMATCH: {:?} cannot load under {}; switching to the bundled Node.js runtime {}",
@@ -788,7 +788,7 @@ fn parse_native_probe_failures(stdout: &str) -> Option<Vec<NativeProbeFailure>>
/// 当前 node 是否就是捆绑运行时(用于避免重复尝试同一个运行时)
fn is_bundled_runtime_node(node: &Path, app_handle: &AppHandle) -> bool {
- crate::config::bundled_node_binary(app_handle).is_some_and(|bundled| {
+ crate::config::runtime_node_binary(app_handle).is_some_and(|bundled| {
bundled == node
|| bundled
.to_string_lossy()
diff --git a/src-tauri/src/service/core/source.rs b/src-tauri/src/service/core/source.rs
index 6666e358..8fcf000f 100644
--- a/src-tauri/src/service/core/source.rs
+++ b/src-tauri/src/service/core/source.rs
@@ -67,6 +67,10 @@ pub struct HarnessCore {
pub above_recommended: bool,
/// 本地存在但远程 pkg 仓库已不再提供的历史槽位。
pub orphaned: bool,
+ /// 是否为离线安装包随包分发的内置核心(`resources/dsh`,版本取自
+ /// `resources/bundle.json`):核心面板把它固定置顶、标注「内置核心」,
+ /// 且不允许卸载(见 `service::bundle`)。
+ pub bundled: bool,
/// 资源清单中的推荐版本,用于切换前风险提示。
pub recommended_version: Option<String>,
pub error: Option<String>,
@@ -115,6 +119,10 @@ fn warn_unsupported_local_core(app_handle: &AppHandle, version: &str) {
/// 本地核心低于内置插件基线时不参与优先,一律回退预打包核心:内置插件是桌面壳的
/// 组成部分,装上也无法加载,只会把启动卡在插件阶段(issue #596)。持久化的
/// `active_core` 设置不改写——用户升级本地核心后自动恢复「本地优先」。
+///
+/// 离线安装包(`resources/bundle.json`)在自动模式下改为**内置核心优先**:随包
+/// 内核与随包 Node 由同一次构建产出、版本匹配有保证,而内网机器上的本地 dsh 往往
+/// 是任意版本,没有理由让它盖过随包内核。用户显式选择的来源仍然照旧生效。
pub fn active_source(app_handle: &AppHandle) -> CoreSource {
let setting = config::get_store_dat_setting(app_handle);
let local = local_core(app_handle);
@@ -134,9 +142,11 @@ pub fn active_source(app_handle: &AppHandle) -> CoreSource {
Some(CoreSource::App) => CoreSource::App,
// 显式选择本地但本地已失效/低于基线 → 回退预打包
Some(CoreSource::Local) if local_usable => CoreSource::Local,
- // 未设置(自动)或显式本地不可用:本地可用时优先
+ // 未设置(自动)或显式本地不可用:离线包用内置核心,否则本地可用时优先
_ => {
- if local_usable {
+ if config::is_offline_bundle(app_handle) {
+ CoreSource::App
+ } else if local_usable {
CoreSource::Local
} else {
CoreSource::App
diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rs
index a61c3dea..1176f84d 100644
--- a/src-tauri/src/service/core/version.rs
+++ b/src-tauri/src/service/core/version.rs
@@ -71,6 +71,12 @@ fn read_manifest_dsh_version(dir: &Path) -> Option<String> {
pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {
let source = active_source(app_handle);
let local = local_core(app_handle);
+ // 离线安装包的内置核心版本:列表据此把对应版本行标注为「内置核心」。
+ // 普通安装包没有随包清单,`None` 时所有行 `bundled = false`。
+ let bundled_version = config::bundled_dsh_version(app_handle);
+ let is_bundled = |version: &str| {
+ !version.is_empty() && bundled_version.as_deref() == Some(version)
+ };
let local_bin = local
.as_ref()
.map(|c| c.bin.to_string_lossy().into_owned())
@@ -96,6 +102,7 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {
.as_ref()
.is_some_and(|c| config::is_dsh_version_above_recommended(app_handle, &c.version)),
orphaned: false,
+ bundled: false,
recommended_version: config::recommended_dsh_version(app_handle),
error: None,
}];
@@ -211,6 +218,7 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {
preview: *preview,
above_recommended: config::is_dsh_version_above_recommended(app_handle, version),
orphaned: false,
+ bundled: is_bundled(version),
recommended_version: config::recommended_dsh_version(app_handle),
error: None,
});
@@ -238,6 +246,7 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {
above_recommended: installed_version
.as_deref()
.is_some_and(|v| config::is_dsh_version_above_recommended(app_handle, v)),
+ bundled: installed_version.as_deref().is_some_and(is_bundled),
recommended_version: config::recommended_dsh_version(app_handle),
error: None,
});
@@ -296,6 +305,7 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {
preview: download::is_preview_tag(&tag),
above_recommended: config::is_dsh_version_above_recommended(app_handle, &version),
orphaned,
+ bundled: is_bundled(&version),
recommended_version: config::recommended_dsh_version(app_handle),
error: None,
});
@@ -563,6 +573,17 @@ pub async fn remove_version(app_handle: &AppHandle, id: &str) -> Result<(), Stri
let dir = existing_slot_dir(app_handle, tag)
.ok_or_else(|| format!("CORE_VERSION_NOT_FOUND: {tag}"))?;
+ // 离线安装包的内置核心不允许卸载:它是随包分发的兜底内核,删掉后内网/离线
+ // 环境将再无可用核心(重装应用才能恢复)。核心面板同样不渲染卸载入口。
+ let version = read_manifest_dsh_version(&dir)
+ .or_else(|| download::parse_version_from_tag(tag))
+ .unwrap_or_default();
+ if config::is_bundled_core_version(app_handle, &version) {
+ return Err(format!(
+ "CORE_BUNDLED_PROTECTED: bundled core {version} cannot be removed"
+ ));
+ }
+
// 停止服务避免句柄锁定(被删目录可能是上一份激活副本,句柄未释放)
if workflow::has_owned_process() {
if let Err(e) = workflow::stop(app_handle.clone()).await {
@@ -594,11 +615,13 @@ fn active_app_version(
fn row_for_tag(app_handle: &AppHandle, tag: &str, dir: &Path) -> HarnessCore {
let active = config::get_dsh_pkg_tag(app_handle).as_deref() == Some(tag)
&& active_source(app_handle) == CoreSource::App;
+ let version = download::parse_version_from_tag(tag).unwrap_or_default();
let dir_str = dir.to_string_lossy().into_owned();
HarnessCore {
id: format!("app-{tag}"),
source: CoreSource::App,
- version: download::parse_version_from_tag(tag).unwrap_or_default(),
+ bundled: config::is_bundled_core_version(app_handle, &version),
+ version,
tag: tag.to_string(),
path: dir_str.clone(),
dir: dir_str,
diff --git a/src-tauri/src/service/download/installable.rs b/src-tauri/src/service/download/installable.rs
index d90401e1..dcd0cb1a 100644
--- a/src-tauri/src/service/download/installable.rs
+++ b/src-tauri/src/service/download/installable.rs
@@ -42,11 +42,15 @@ impl Installable for Nodejs {
config::get_node_install_path(app)
}
fn check_installed(&self, app: &AppHandle) -> bool {
+ // 离线安装包:随包运行时就是唯一来源,直接可用即视为已安装。
+ if config::bundled_node_binary(app).is_some() {
+ return config::is_runtime_compatible(app);
+ }
// 原生模块 ABI 探测已判定本地 node 无法加载核心的原生模块(issue #441):
// 此时不能再以"本机有版本兼容的 node"为由跳过捆绑运行时,否则服务进程仍会
// 用那个 ABI 不匹配的运行时启动。
if config::prefer_bundled_node_runtime() {
- return config::bundled_node_binary(app).is_some() && config::is_runtime_compatible(app);
+ return config::runtime_node_binary(app).is_some() && config::is_runtime_compatible(app);
}
if let Some(local_node) = config::get_local_node_path() {
log::info!(
@@ -99,6 +103,10 @@ impl Installable for Pnpm {
config::get_pnpm_install_path(app)
}
fn check_installed(&self, app: &AppHandle) -> bool {
+ // 离线安装包:直接使用随包 pnpm,完全跳过本地 pnpm 探测。
+ if config::bundled_pnpm_binary(app).is_some() {
+ return true;
+ }
// "有则跳过":用户 PATH 中已有 pnpm 时不再安装捆绑版
if crate::service::cli::find_user_pnpm(app).is_some() {
log::info!("Detected user-installed pnpm, skipping bundled pnpm");
diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rs
index dc0db049..e4628311 100644
--- a/src-tauri/src/service/mod.rs
+++ b/src-tauri/src/service/mod.rs
@@ -1,4 +1,5 @@
pub mod backup;
+pub mod bundle;
pub mod cli;
pub mod core;
pub mod download;
diff --git a/src-tauri/src/service/patch/alpha_auth.rs b/src-tauri/src/service/patch/alpha_auth.rs
index 0798cc59..a5c8d3b2 100644
--- a/src-tauri/src/service/patch/alpha_auth.rs
+++ b/src-tauri/src/service/patch/alpha_auth.rs
@@ -30,7 +30,7 @@ use crate::utils::{dsh_rel_contains, patch_dsh, PatchOutcome};
const PATCH_MARKER: &str = "dsh-tauri-desktop: alpha embedded auth --skip-auth flag";
// ── dsh-web-app/lib/startup.js ────────────────────────────────────────────────
-const WEB_STARTUP_REL: &str = "node_modules/@deepseek-ai/dsh-web-app/lib/startup.js";
+pub(super) const WEB_STARTUP_REL: &str = "node_modules/@deepseek-ai/dsh-web-app/lib/startup.js";
const STARTUP_OPTION_ANCHOR: &str =
".option(\"--no-open\", \"do not open the Web UI in the default browser\")";
const STARTUP_OPTION_REPLACEMENT: &str = ".option(\"--no-open\", \"do not open the Web UI in the default browser\")\n\t\t.option(\"--skip-auth\", \"skip the browser-session token/cookie exchange; keeps the Host/Origin trust fence (for embedded UIs)\")";
@@ -38,7 +38,7 @@ const STARTUP_ACTION_ANCHOR: &str = "\t\tconst options = program.opts();";
const STARTUP_ACTION_REPLACEMENT: &str = "\t\tconst options = program.opts();\n\t\t/* dsh-tauri-desktop: alpha embedded auth --skip-auth flag */\n\t\tif (options.skipAuth) process.env.DSH_SKIP_AUTH = \"1\";";
// ── dsh-client-connection/lib/index.js ────────────────────────────────────────
-const CONNECTION_INDEX_JS: &str =
+pub(super) const CONNECTION_INDEX_JS: &str =
"node_modules/@deepseek-ai/dsh-client-connection/lib/index.js";
const REJECTION_ANCHOR: &str = "\trequestRejection(request) {\n\t\tif (!isTrustedApiRequest(request, this.trustedHosts)) return 403;\n\t\treturn this.browserAuth.isAuthenticated(request) ? void 0 : 401;\n\t}";
const REJECTION_PATCHED: &str = "\trequestRejection(request) {\n\t\tif (!isTrustedApiRequest(request, this.trustedHosts)) return 403;\n\t\tif (process.env.DSH_SKIP_AUTH === \"1\") return void 0;\n\t\treturn this.browserAuth.isAuthenticated(request) ? void 0 : 401;\n\t} /* dsh-tauri-desktop: alpha embedded auth --skip-auth flag */";
diff --git a/src-tauri/src/service/patch/client_hmr.rs b/src-tauri/src/service/patch/client_hmr.rs
index 0020d37f..dae2b8bf 100644
--- a/src-tauri/src/service/patch/client_hmr.rs
+++ b/src-tauri/src/service/patch/client_hmr.rs
@@ -25,7 +25,7 @@ const UPSTREAM_INVALIDATE: &str = "modLoader.invalidate(id, rev);";
const UPSTREAM_PREFETCH: &str = "await modLoader.prefetch(id);";
/// 相对活动核心安装目录的 client-hmr `lib/client.js` 包内路径。
-const CLIENT_HMR_CLIENT_JS: &str = "node_modules/@deepseek-ai/dsh-client-hmr/lib/client.js";
+pub(super) const CLIENT_HMR_CLIENT_JS: &str = "node_modules/@deepseek-ai/dsh-client-hmr/lib/client.js";
fn patch_source(source: &str) -> PatchOutcome {
if source.contains(PATCH_MARKER) {
diff --git a/src-tauri/src/service/patch/llm_session.rs b/src-tauri/src/service/patch/llm_session.rs
index 77b8ea17..e8bdef53 100644
--- a/src-tauri/src/service/patch/llm_session.rs
+++ b/src-tauri/src/service/patch/llm_session.rs
@@ -24,7 +24,7 @@ use crate::utils::{patch_dsh, PatchOutcome};
const PATCH_MARKER: &str = "dsh-tauri-desktop: OpenCode Go session header";
/// 相对活动核心安装目录的 pi-ai 适配器包内路径。
-const PI_AI_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-llm-pi-ai/lib/index.js";
+pub(super) const PI_AI_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-llm-pi-ai/lib/index.js";
/// 原始 `requestHeaders` 定义:单参数、直接取 attribution。
const HEADERS_ANCHOR: &str =
diff --git a/src-tauri/src/service/patch/mod.rs b/src-tauri/src/service/patch/mod.rs
index 4cd9a98f..c35d4a4c 100644
--- a/src-tauri/src/service/patch/mod.rs
+++ b/src-tauri/src/service/patch/mod.rs
@@ -7,6 +7,10 @@
//!
//! 命名约定:子模块名不带 `_patch` 后缀(`renderer` / `session` / `workspace` /
//! `client_hmr`),挂点统一为 `service::workflow::launch`,均为最佳努力、失败仅告警。
+//!
+//! [`patched_paths`] 是补丁写入目标的**唯一声明**:离线安装包的链接层据此决定哪些
+//! 目录必须是真实文件(补丁写不穿目录链接,见 `service::bundle`),并逐项校验。
+//! 新增补丁时只要把常量登记进去,链接层自动跟随——绝不能在链接层里另抄一份清单。
pub(crate) mod alpha_auth;
pub(crate) mod client_hmr;
@@ -15,3 +19,49 @@ pub(crate) mod renderer;
pub(crate) mod session;
pub(crate) mod workspace;
pub(crate) mod workspace_view;
+
+/// 桌面端会改写的核心内相对路径(相对活动核心目录,形如
+/// `node_modules/<包>/lib/index.js`)。
+///
+/// 这些路径在离线安装包里必须是**真实可写文件**:补丁通过目录链接写入时,写入会
+/// 透传到只读的随包资源上(macOS `.app` / Linux AppImage·deb),而 `patch_dsh` 对
+/// 失败只记日志——`alpha_auth` 的补丁落不了地,`--skip-auth` 就不会下发,内嵌页面
+/// 会要求登录。因此链接层必须按这份声明把这些目录复制成真实内容。
+pub(crate) fn patched_paths() -> Vec<&'static str> {
+ let mut paths = vec![
+ alpha_auth::WEB_STARTUP_REL,
+ alpha_auth::CONNECTION_INDEX_JS,
+ client_hmr::CLIENT_HMR_CLIENT_JS,
+ llm_session::PI_AI_INDEX_JS,
+ renderer::RENDERER_CLIENT_JS,
+ session::SESSION_INDEX_JS,
+ workspace::WORKSPACE_INDEX_JS,
+ workspace_view::WORKSPACE_CLIENT_JS,
+ ];
+ paths.sort_unstable();
+ paths.dedup();
+ paths
+}
+
+#[cfg(test)]
+mod tests {
+ use super::patched_paths;
+ use std::collections::HashSet;
+
+ /// 声明必须覆盖每个补丁模块实际使用的常量:常量改名/新增补丁而漏登记时,
+ /// 离线包的链接层会把补丁目标留在只读链接后面,补丁静默失效。
+ #[test]
+ fn patched_paths_are_core_relative_and_unique() {
+ let paths = patched_paths();
+ assert_eq!(paths.len(), 8, "每个补丁常量都必须在声明里出现一次");
+ assert_eq!(paths.iter().collect::<HashSet<_>>().len(), paths.len());
+
+ for path in paths {
+ assert!(
+ path.starts_with("node_modules/") && path.ends_with(".js"),
+ "补丁目标必须是核心内的 JS 文件: {path}"
+ );
+ assert!(!path.contains(".."), "补丁目标不得越出核心目录: {path}");
+ }
+ }
+}
diff --git a/src-tauri/src/service/patch/renderer.rs b/src-tauri/src/service/patch/renderer.rs
index bf19916d..0928142e 100644
--- a/src-tauri/src/service/patch/renderer.rs
+++ b/src-tauri/src/service/patch/renderer.rs
@@ -25,7 +25,7 @@ use crate::utils::{patch_dsh, PatchOutcome};
const ANCHOR_KEYWORD: &str = "return module.exports;";
/// 相对活动核心安装目录的 renderer `lib/client.js` 包内路径。
-const RENDERER_CLIENT_JS: &str = "node_modules/@deepseek-ai/dsh-client-ui-renderer/lib/client.js";
+pub(super) const RENDERER_CLIENT_JS: &str = "node_modules/@deepseek-ai/dsh-client-ui-renderer/lib/client.js";
/// 幂等补丁逻辑的纯函数部分(便于单测,不触碰文件系统)。
///
diff --git a/src-tauri/src/service/patch/session.rs b/src-tauri/src/service/patch/session.rs
index 230659fe..6b2e076c 100644
--- a/src-tauri/src/service/patch/session.rs
+++ b/src-tauri/src/service/patch/session.rs
@@ -19,7 +19,7 @@ const INSERTION: &str = r#"/** Remove one live session by id and run its officia
/** Remove one exact entered session and emit its paired disposal when announced. */"#;
/// 相对活动核心安装目录的 session `lib/index.js` 包内路径。
-const SESSION_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-session/lib/index.js";
+pub(super) const SESSION_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-session/lib/index.js";
fn patch_source(source: &str) -> PatchOutcome {
if source.contains(PATCH_MARKER) {
diff --git a/src-tauri/src/service/patch/workspace.rs b/src-tauri/src/service/patch/workspace.rs
index a0e137b3..455fbb08 100644
--- a/src-tauri/src/service/patch/workspace.rs
+++ b/src-tauri/src/service/patch/workspace.rs
@@ -18,7 +18,7 @@ const MUTATE_ORIGINAL: &str = "const sessionIds = changed.sessionIds.filter((id)
const MUTATE_PATCHED: &str = "const sessionIds = changed.sessionIds; /* dsh-tauri-worktree: relaxed explicit workspace membership */";
/// 相对活动核心安装目录的 workspace `lib/index.js` 包内路径。
-const WORKSPACE_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-workspace/lib/index.js";
+pub(super) const WORKSPACE_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-workspace/lib/index.js";
fn patch_source(source: &str) -> PatchOutcome {
if source.contains(PATCH_MARKER) {
diff --git a/src-tauri/src/service/patch/workspace_view.rs b/src-tauri/src/service/patch/workspace_view.rs
index 6abb3c1b..f4c807df 100644
--- a/src-tauri/src/service/patch/workspace_view.rs
+++ b/src-tauri/src/service/patch/workspace_view.rs
@@ -40,7 +40,7 @@ const SESSION_UPDATED_AT_PATCHED: &str =
"d.sessionUpdatedAtByAccount = Object.fromEntries(Object.entries(d.sessionUpdatedAtByAccount ?? {}).filter(([key]) => retained.has(key))); /* dsh-tauri: tolerate workspace view state written by a newer core */";
/// 相对活动核心安装目录的 workspace 客户端 `lib/client.js` 包内路径。
-const WORKSPACE_CLIENT_JS: &str =
+pub(super) const WORKSPACE_CLIENT_JS: &str =
"node_modules/@deepseek-ai/dsh-client-ui-workspace/lib/client.js";
fn patch_source(source: &str) -> PatchOutcome {
diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rs
index 1f15c502..2a452074 100644
--- a/src-tauri/src/service/plugin/install/pnpm.rs
+++ b/src-tauri/src/service/plugin/install/pnpm.rs
@@ -739,12 +739,12 @@ fn parse_store_major_from_modules_yaml(content: &str) -> Option<u32> {
major.parse().ok()
}
-/// 捆绑版 pnpm 的主版本(读 `dependencies/pnpm/package.json` 的 version 字段);
-/// 未安装或清单缺失返回 None。
+/// 捆绑版 pnpm 的主版本(读 pnpm 目录 `package.json` 的 version 字段,离线安装包
+/// 为随包 `resources/pnpm`);未安装或清单缺失返回 None。
///
/// 供 [`ensure_pnpm`] 选版与 [`crate::service::plugin::verify`] 的修复选版共用(store 主版本匹配)。
pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {
- let manifest = config::get_pnpm_install_path(app_handle).join("package.json");
+ let manifest = config::get_pnpm_runtime_dir(app_handle).join("package.json");
let content = std::fs::read_to_string(manifest).ok()?;
let value: serde_json::Value = serde_json::from_str(&content).ok()?;
value
diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rs
index 45e1d4ae..e0eda5e5 100644
--- a/src-tauri/src/service/workflow/install.rs
+++ b/src-tauri/src/service/workflow/install.rs
@@ -92,8 +92,12 @@ pub async fn install(
}
// Windows Sandbox 等空白环境没有 Git;仅 Windows 加入第 4 项,若系统 Git
// 可真实执行则 Installable 会跳过,不重复下载也不修改系统 PATH。
+ // 离线安装包不随包分发 MinGit,也不加入该任务:内网补装必然失败,只会把整个
+ // 安装流程拖到超时(Git 依赖判定见 bridge::lifecycle::git_dependency_ready)。
#[cfg(windows)]
- tasks.push(Box::new(download::Git));
+ if !crate::config::is_offline_bundle(app_handle) {
+ tasks.push(Box::new(download::Git));
+ }
// 每项均有下载/解压两个阶段,按实际平台任务数计算,避免进度提前到 100%。
let mut tracker = download::ProgressTracker::new(&window, tasks.len() * 2);
log::info!("Task list created, {} tasks total", tasks.len());
diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs
index f9a84622..0e41dce1 100644
--- a/src-tauri/src/utils/mod.rs
+++ b/src-tauri/src/utils/mod.rs
@@ -38,6 +38,12 @@ fn active_core_install_dir(app_handle: &tauri::AppHandle) -> PathBuf {
/// 统一处理「定位文件 → 读取 → 打补丁 → 写回」与对应的日志。文件缺失、已打过、
/// 锚点变更均静默跳过并返回 Ok;只有真实读/写失败才返回 Err(不阻断启动的调用方
/// 据此仅告警)。活动核心的判定与 [`active_core_install_dir`] 一致。
+///
+/// **离线安装包**:活动核心目录是随包内核的落位产物,写入落在哪里由落位方式决定
+/// (见 `service::bundle`)——随包目录可写时是它的目录链接,补丁直接改写
+/// `resources/dsh` 里**被加载的那份文件**;只读时才落到应用数据目录的真实副本。
+/// 补丁自身不需要关心这件事,只需保证 [`crate::service::patch::patched_paths`] 里
+/// 登记了目标路径。
pub fn patch_dsh(
app_handle: &tauri::AppHandle,
rel_path: &str,
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 28d12d7e..b4bb09d6 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -282,6 +282,7 @@
"core.remove_confirm_title": "Uninstall version",
"core.remove_confirm_desc": "Uninstall {{version}}? The engine copy will be removed from this device (other copies are unaffected).",
"core.app": "Bundled",
+ "core.bundled": "Built-in",
"core.orphaned_title": "Local packages no longer in the repository",
"core.orphaned": "Orphaned",
"core.preview": "Preview",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index d82319ed..c7ba0b87 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -282,6 +282,7 @@
"core.remove_confirm_title": "卸载版本",
"core.remove_confirm_desc": "确定卸载 {{version}} 吗?将移除本机的该引擎副本(其余副本不受影响)。",
"core.app": "预打包",
+ "core.bundled": "内置核心",
"core.orphaned_title": "本地已废弃的 pkg",
"core.orphaned": "已废弃",
"core.preview": "预览版",
diff --git a/src/types/core.ts b/src/types/core.ts
index cc3566d0..e7c3447c 100644
--- a/src/types/core.ts
+++ b/src/types/core.ts
@@ -24,6 +24,8 @@ export interface HarnessCore {
aboveRecommended: boolean
/** 本地存在但 pkg 仓库已不再提供的历史槽位 */
orphaned: boolean
+ /** 离线安装包随包分发的内置核心(resources/dsh):固定置顶、标注「内置核心」且不可卸载 */
+ bundled: boolean
recommendedVersion: string | null
error?: string | null
}
diff --git a/src/ui/config/core.tsx b/src/ui/config/core.tsx
index 206cd866..a91f3622 100644
--- a/src/ui/config/core.tsx
+++ b/src/ui/config/core.tsx
@@ -30,6 +30,8 @@ import { toast } from '@/utils/toast'
* `app-<tag>` = deepseek-harness-pkg 各发布版本(GitHub releases 拉取失败时
* 降级为 git tags / 磁盘扫描,仅显示已下载版本)。预览版(Pre-release label
* 或 tag 命名)照常列出、可下载安装,但带「预览版」标签、不参与更新提示。
+ * 离线安装包随包分发的内置核心(`bundled`,版本来自 `resources/bundle.json`)
+ * 固定置顶、标注「内置核心」且不提供卸载入口。
* - 切换核心:持久化后**自动重启**服务(需求 5),重启走 harness store 的
* restart 流程(停止 → 重新启动 → 健康检查)。
* - 下载版本:拉指定 tag 的发布资产到历史槽位(不激活),随后可切换;
@@ -88,10 +90,12 @@ export function ConfigCore() {
// 本地核心未检测到时不渲染 local 行(保留 local_missing_hint 提示)
// 后端列表在部分缓存/旧版本返回路径中可能仍保持远程顺序,前端统一按版本从高到低排序。
- // 本地核心固定放在版本列表前,预打包核心按 SemVer 排序。
+ // 离线安装包的内置核心固定在最顶部(`bundled`),随后是本地核心,最后是预打包版本。
const rows = cores
.filter(core => !(core.source === 'local' && !core.present))
.sort((a, b) => {
+ if (a.bundled !== b.bundled)
+ return a.bundled ? -1 : 1
if (a.source !== b.source)
return a.source === 'local' ? -1 : 1
if (a.source === 'local')
@@ -101,8 +105,9 @@ export function ConfigCore() {
return -compareVersions(a.version || a.tag, b.version || b.tag)
})
const localCore = cores.find(c => c.source === 'local')
- const currentRows = rows.filter(core => !core.orphaned)
- const orphanRows = rows.filter(core => core.orphaned)
+ // 内置核心即使不在远程发布列表里也保持在主列表(不被归入「已废弃」分区)。
+ const currentRows = rows.filter(core => !core.orphaned || core.bundled)
+ const orphanRows = rows.filter(core => core.orphaned && !core.bundled)
const displayRows = [...currentRows, ...orphanRows]
// 本地核心是否有新版可更新:仅当存在更新的预打包发布时才显示「更新本地核心」。
@@ -334,12 +339,18 @@ export function ConfigCore() {
{t('core.local')}
</Chip>
</If>
- <If cond={core.source === 'app'}>
+ {/* 离线安装包的内置核心:随包分发、固定置顶、不可卸载 */}
+ <If cond={core.bundled}>
+ <Chip size="sm" variant="soft" color="success" className="shrink-0 font-medium">
+ {t('core.bundled')}
+ </Chip>
+ </If>
+ <If cond={core.source === 'app' && !core.bundled}>
<Chip size="sm" variant="soft" color="default" className="shrink-0 font-medium">
{t('core.app')}
</Chip>
</If>
- <If cond={core.orphaned}>
+ <If cond={core.orphaned && !core.bundled}>
<Chip size="sm" variant="soft" color="warning" className="shrink-0 font-medium">
{t('core.orphaned')}
</Chip>
@@ -413,8 +424,9 @@ export function ConfigCore() {
{t('core.download')}
</Button>
</If>
- {/* 已下载且非激活(app 版本):卸载入口 */}
- <If cond={core.present && !core.active && core.source === 'app'}>
+ {/* 已下载且非激活(app 版本):卸载入口。内置核心随包分发、
+ 删掉后离线环境将再无可用核心,因此不提供卸载。 */}
+ <If cond={core.present && !core.active && core.source === 'app' && !core.bundled}>
<Button
size="sm"
variant="tertiary"
diff --git a/test/bundle-metadata.test.ts b/test/bundle-metadata.test.ts
new file mode 100644
index 00000000..3afd2dec
--- /dev/null
+++ b/test/bundle-metadata.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it } from 'vitest'
+import * as bundleMetadataModule from '../scripts/bundle-metadata.mjs'
+
+interface BundleAsset {
+ name: string
+ url: string
+ sha256?: string
+ sha256Url?: string
+ version?: string
+ tag?: string
+}
+
+interface BundleAssets {
+ node: BundleAsset
+ dsh: BundleAsset
+ pnpm: BundleAsset
+}
+
+interface BundleConstants {
+ nodeVersion: string
+ pnpmVersion: string
+ pnpmSha256: string
+}
+
+interface BundleMetadataModule {
+ parseVersionFromTag: (tag: unknown) => string | null
+ nodeAssetName: (platform: string, arch: string, version: string) => string
+ dshAssetName: (platform: string, arch: string) => string
+ bundleAssets: (input: {
+ platform: string
+ arch: string
+ constants: BundleConstants
+ dshVersion: string
+ dshTag: string
+ }) => BundleAssets
+ toAssetTable: (assets: BundleAssets) => string
+ readBuildConstants: (repo?: string) => BundleConstants
+ readRecommendedDshVersion: (repo?: string) => string
+ resolveDshRelease: (
+ version: string,
+ fetchJson?: (url: string) => Promise<unknown>,
+ ) => Promise<{ tag: string, commit: string }>
+}
+
+const bundleMetadata = bundleMetadataModule as unknown as BundleMetadataModule
+
+const constants: BundleConstants = {
+ nodeVersion: '22.22.0',
+ pnpmVersion: '11.7.0',
+ pnpmSha256: 'a'.repeat(64),
+}
+
+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')
+ })
+})
+
+describe('bundle asset resolution', () => {
+ it('pins every windows asset to a downloadable url', () => {
+ const assets = bundleMetadata.bundleAssets({
+ platform: 'windows',
+ arch: 'x64',
+ constants,
+ dshVersion: '0.1.5-rc.2',
+ dshTag: 'dsh-0.1.5-rc.2-123',
+ })
+
+ 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-0.1.5-rc.2-123/deepseek-harness-pkg-windows.zip',
+ )
+ expect(assets.pnpm.url).toBe('https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz')
+ })
+
+ // MinGit 不随离线包分发:资产列表必须始终只有 node / dsh / pnpm 三项。
+ it.each([
+ ['windows', 'x64'],
+ ['macos', 'arm64'],
+ ['macos', 'x64'],
+ ['linux', 'x64'],
+ ])('bundles exactly node, dsh and pnpm for %s/%s', (platform, arch) => {
+ const assets = bundleMetadata.bundleAssets({
+ platform,
+ arch,
+ constants,
+ dshVersion: '0.1.5-rc.2',
+ dshTag: 'dsh-0.1.5-rc.2-123',
+ })
+ expect(Object.keys(assets).sort()).toEqual(['dsh', 'node', 'pnpm'])
+ const rows = bundleMetadata.toAssetTable(assets).split('\n')
+ expect(rows.map(row => row.split('|')[0])).toEqual(['node', 'dsh', 'pnpm'])
+ // 空字段必须如实保留(bash `read` 用 `|` 而不是 TAB 作为分隔符的原因)。
+ expect(rows[0].split('|')[3]).toBe('')
+ expect(rows[0].split('|')[4]).toBe(assets.node.sha256Url)
+ expect(rows[2].split('|')[3]).toBe(constants.pnpmSha256)
+ expect(rows[2].split('|')[4]).toBe('')
+ })
+})
+
+describe('bundle release resolution', () => {
+ it('picks the release whose tag parses to the recommended version', async () => {
+ const release = await bundleMetadata.resolveDshRelease('0.1.5-rc.2', async () => [
+ { tag_name: 'dsh-0.1.6-rc.1-200', target_commitish: 'main' },
+ { tag_name: 'dsh-0.1.5-rc.2-123', target_commitish: '2'.repeat(40) },
+ ])
+ expect(release).toEqual({ tag: 'dsh-0.1.5-rc.2-123', commit: '2'.repeat(40) })
+ })
+
+ it('falls back to the tag build id when target_commitish is not a sha', async () => {
+ const release = await bundleMetadata.resolveDshRelease('0.1.5-rc.2', async () => [
+ { tag_name: 'dsh-0.1.5-rc.2-123', target_commitish: 'main' },
+ ])
+ expect(release).toEqual({ tag: 'dsh-0.1.5-rc.2-123', commit: '123' })
+ })
+
+ it('fails loudly when no release matches', async () => {
+ await expect(bundleMetadata.resolveDshRelease('9.9.9', async () => [])).rejects.toThrow(
+ /^BUNDLE_METADATA:/,
+ )
+ })
+})
+
+describe('bundle build constants', () => {
+ it('reads node/pnpm pins from the checked out repository', () => {
+ const parsed = bundleMetadata.readBuildConstants(process.cwd())
+ expect(parsed.nodeVersion).toMatch(/^\d+\.\d+\.\d+$/)
+ expect(parsed.pnpmVersion).toMatch(/^\d+\.\d+\.\d+/)
+ expect(parsed.pnpmSha256).toHaveLength(64)
+ expect(bundleMetadata.readRecommendedDshVersion(process.cwd())).toMatch(/^\d+\.\d+\.\d+/)
+ })
+})
diff --git a/vitest.config.ts b/vitest.config.ts
index 1516d2b0..c69f92d2 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -34,6 +34,8 @@ export default defineConfig({
'test/compat-iterator.test.ts',
// issue #596:本地核心低于内置插件基线导致启动失败,核心面板与后端共用的版本判定回归。
'test/core-version.test.ts',
+ // 离线安装包(issue #344):构建期资源清单与 Rust 侧资产命名/版本解析保持同源。
+ 'test/bundle-metadata.test.ts',
// v0.2.0:气泡托管给 dsh-pet-component,宿主侧只剩「会话快照 → pet.bubble」的映射。
'src/pet/hooks/use-bubble-tracker.test.ts',
// 桌宠素材响应头:GitHub 对中文动画名回 `content-disposition`,插件版 fetch 会因