🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): package builtin core as ASAR and add range-based OTA packs (#20191)
Innei64e7fdc1163f
diff --git a/.github/actions/desktop-core-seq/action.yml b/.github/actions/desktop-core-seq/action.ymlindex 5be2adf6b26..7747691b46b 100644--- a/.github/actions/desktop-core-seq/action.yml+++ b/.github/actions/desktop-core-seq/action.yml@@ -1,7 +1,10 @@name: Desktop Core Seq-description: Resolve the next core seq (max over every platform's published latest.json + 1) so a new core always outranks published ones+description: Resolve the next core seq (max over every platform within one app version + 1) so a new core always outranks published onesinputs:+ app-version:+ description: Full application version owning the v4 OTA namespace+ required: truechannel:description: 'Update channel'required: true@@ -24,6 +27,7 @@ runs:id: seqshell: bashenv:+ APP_VERSION: ${{ inputs.app-version }}CHANNEL: ${{ inputs.channel }}UPDATE_SERVER_URL: ${{ inputs.update-server-url }}run: |@@ -32,16 +36,17 @@ runs:case "$BASE" in*/stable|*/nightly|*/canary|*/beta) BASE="${BASE%/*}" ;;esac+ [[ "$APP_VERSION" =~ ^[0-9A-Za-z][0-9A-Za-z.+-]*$ ]] || { echo "::error::valid app-version required"; exit 1; }MAX_SEQ=-1for p in darwin win32 linux; doHTTP_STATUS=$(curl -sS --connect-timeout 10 --max-time 30 \- -o "$RUNNER_TEMP/latest-$p.json" -w '%{http_code}' "$BASE/$CHANNEL/core/$p/latest.json")+ -o "$RUNNER_TEMP/latest-$p.json" -w '%{http_code}' "$BASE/$CHANNEL/$APP_VERSION/core-v4/$p/latest.json")case "$HTTP_STATUS" in200) SEQ=$(jq -er '.seq | select(type == "number")' "$RUNNER_TEMP/latest-$p.json") ;;404) SEQ=-1 ;;*) echo "::error::$p latest.json fetch failed: HTTP $HTTP_STATUS"; exit 1 ;;esac- echo "$p latest seq: $SEQ"+ echo "$APP_VERSION/core-v4/$p latest seq: $SEQ"if [ "$SEQ" -gt "$MAX_SEQ" ]; then MAX_SEQ=$SEQ; fidoneNEXT=$((MAX_SEQ + 1))diff --git a/.github/actions/desktop-ota-diagnostics/action.yml b/.github/actions/desktop-ota-diagnostics/action.ymlindex ea2033b4e12..5a70cb5fa1c 100644--- a/.github/actions/desktop-ota-diagnostics/action.yml+++ b/.github/actions/desktop-ota-diagnostics/action.yml@@ -52,8 +52,8 @@ runs:retention-days: 14path: |desktop-ota-diagnostics/- apps/desktop/release/core-ota/core/*/latest.json- release/core-ota/core/*/latest.json+ apps/desktop/release/core-ota/core*/*/latest.json+ release/core-ota/core*/*/latest.jsonrelease/shell.json${{ runner.temp }}/shell.json${{ runner.temp }}/previous-core.jsondiff --git a/.github/actions/desktop-publish-core-ota/action.yml b/.github/actions/desktop-publish-core-ota/action.ymlindex ed5dd50381a..efb1f05eec0 100644--- a/.github/actions/desktop-publish-core-ota/action.yml+++ b/.github/actions/desktop-publish-core-ota/action.yml@@ -1,7 +1,15 @@name: Desktop Publish Core OTA-description: Upload a buildCore.mjs output tree (cas + core/<platform>) to the update server+description: Upload core releases to their app-version namespace (legacy v3 layout retained)inputs:+ app-version:+ description: Full application version owning the v4 OTA namespace+ required: false+ default: ''+ core-dir:+ description: 'Protocol directory (core for v3, core-v4 for v4)'+ required: false+ default: corechannel:description: 'Update channel (stable, beta, canary)'required: true@@ -51,10 +59,18 @@ runs:S3_BUCKET: ${{ inputs.s3-bucket }}S3_ENDPOINT: ${{ inputs.s3-endpoint }}CHANNEL: ${{ inputs.channel }}+ APP_VERSION: ${{ inputs.app-version }}+ CORE_DIR: ${{ inputs.core-dir }}RELEASE_DIR: ${{ inputs.release-dir }}SHELL_JSON: ${{ inputs.shell-json }}run: |set -euo pipefail+ case "$CORE_DIR" in core|core-v4) ;; *) exit 1 ;; esac+ PREFIX="$CHANNEL"+ if [ "$CORE_DIR" = core-v4 ]; then+ [[ "$APP_VERSION" =~ ^[0-9A-Za-z][0-9A-Za-z.+-]*$ ]] || { echo "::error::valid app-version required for v4"; exit 1; }+ PREFIX="$CHANNEL/$APP_VERSION"+ fiecho "published=false" >> "$GITHUB_OUTPUT"echo "platforms=" >> "$GITHUB_OUTPUT"if [ -z "$S3_BUCKET" ]; then@@ -68,14 +84,14 @@ runs:IMMUTABLE=(--cache-control "public,max-age=31536000,immutable")# seq is allocated as max(published)+1 without a lock, so a concurrent publisher for the- # same channel may have landed first. Same seq + same version is a re-run and allowed.+ # same app version and channel may have landed first. Same seq + same version is a re-run and allowed.assert_not_behind() {local platform=$1- local key="$CHANNEL/core/$platform/latest.json"+ local key="$PREFIX/$CORE_DIR/$platform/latest.json"aws s3 ls "s3://$S3_BUCKET/$key" "${ENDPOINT_ARGS[@]}" >/dev/null 2>&1 || return 0local remote local_json remote_seq remote_version local_seq local_versionremote=$(aws s3 cp "s3://$S3_BUCKET/$key" - "${ENDPOINT_ARGS[@]}")- local_json="$RELEASE_DIR/core/$platform/latest.json"+ local_json="$RELEASE_DIR/$CORE_DIR/$platform/latest.json"remote_seq=$(jq -r '.seq // -1' <<<"$remote")remote_version=$(jq -r '.version' <<<"$remote")local_seq=$(jq -r '.seq' "$local_json")@@ -86,28 +102,45 @@ runs:fi}- for platform_dir in "$RELEASE_DIR"/core/*/; do+ for platform_dir in "$RELEASE_DIR"/"$CORE_DIR"/*/; do[ -d "$platform_dir" ] || continueassert_not_behind "$(basename "$platform_dir")"done# Order matters for clients mid-download: objects → packs → snapshot → shell.json → latest.json.- if [ -d "$RELEASE_DIR/cas" ]; then+ if [ "$CORE_DIR" = core ] && [ -d "$RELEASE_DIR/cas" ]; thenecho "📦 Syncing CAS objects"aws s3 sync "$RELEASE_DIR/cas" "s3://$S3_BUCKET/cas" --size-only \--content-type application/zstd "${IMMUTABLE[@]}" "${ENDPOINT_ARGS[@]}"fiPLATFORMS=""- for platform_dir in "$RELEASE_DIR"/core/*/; do+ for platform_dir in "$RELEASE_DIR"/"$CORE_DIR"/*/; do[ -d "$platform_dir" ] || continueplatform=$(basename "$platform_dir")- target="s3://$S3_BUCKET/$CHANNEL/core/$platform"+ target="s3://$S3_BUCKET/$PREFIX/$CORE_DIR/$platform"version=$(jq -r '.version' "$platform_dir/latest.json")echo "🚀 $platform: core $version → $target"+ PACK_TYPE=application/zip+ [ "$CORE_DIR" != core-v4 ] || PACK_TYPE=application/octet-streamif [ -d "$platform_dir/packs" ]; thenaws s3 sync "$platform_dir/packs" "$target/packs" --size-only \- --content-type application/zip "${IMMUTABLE[@]}" "${ENDPOINT_ARGS[@]}"+ --content-type "$PACK_TYPE" "${IMMUTABLE[@]}" "${ENDPOINT_ARGS[@]}"+ fi+ if [ "$CORE_DIR" = core-v4 ]; then+ # Verify uploaded bytes and a real S3 Range before exposing this version.+ while IFS=$'\t' read -r hash pack_path size offset length frame_hash; do+ key="$PREFIX/$CORE_DIR/$platform/$pack_path"+ actual=$(aws s3 cp "s3://$S3_BUCKET/$key" - "${ENDPOINT_ARGS[@]}" | sha256sum | cut -d ' ' -f1)+ [ "$actual" = "$hash" ] || { echo "::error::pack hash mismatch: $key"; exit 1; }+ range_file=$(mktemp)+ end=$((offset + length - 1))+ metadata=$(aws s3api get-object --bucket "$S3_BUCKET" --key "$key" --range "bytes=$offset-$end" "${ENDPOINT_ARGS[@]}" "$range_file")+ actual=$(sha256sum "$range_file" | cut -d ' ' -f1)+ rm "$range_file"+ [ "$actual" = "$frame_hash" ] && [ "$(jq -r '.ContentRange' <<<"$metadata")" = "bytes $offset-$end/$size" ] \+ || { echo "::error::pack Range verification failed: $key"; exit 1; }+ done < <(jq -r '. as $m | .packs[] | . as $p | ([$m.objects[], $m.patches[]] | map(select(.packSha256 == $p.sha256)) | first) as $f | [$p.sha256, $p.path, $p.size, $f.offset, $f.length, $f.compressedSha256] | @tsv' "$platform_dir/latest.json")fiaws s3 cp "$platform_dir/versions/$version.json" "$target/versions/$version.json" \--content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"@@ -115,6 +148,11 @@ runs:doneif [ -n "$SHELL_JSON" ]; then+ if [ "$CORE_DIR" = core-v4 ]; then+ [ "$(jq -r '.shellVersion' "$SHELL_JSON")" = "$APP_VERSION" ] || { echo "::error::shell version mismatch"; exit 1; }+ aws s3 cp "$SHELL_JSON" "s3://$S3_BUCKET/$PREFIX/shell.json" \+ --content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"+ fiecho "📋 Publishing $CHANNEL/shell.json: $(cat "$SHELL_JSON")"aws s3 cp "$SHELL_JSON" "s3://$S3_BUCKET/$CHANNEL/shell.json" \--content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"@@ -122,7 +160,7 @@ runs:for platform in $PLATFORMS; doassert_not_behind "$platform"- aws s3 cp "$RELEASE_DIR/core/$platform/latest.json" "s3://$S3_BUCKET/$CHANNEL/core/$platform/latest.json" \+ aws s3 cp "$RELEASE_DIR/$CORE_DIR/$platform/latest.json" "s3://$S3_BUCKET/$PREFIX/$CORE_DIR/$platform/latest.json" \--content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"donediff --git a/.github/actions/desktop-publish-s3/action.yml b/.github/actions/desktop-publish-s3/action.ymlindex edd77d71a30..22be5d9eafb 100644--- a/.github/actions/desktop-publish-s3/action.yml+++ b/.github/actions/desktop-publish-s3/action.yml@@ -71,21 +71,20 @@ runs:SHELL_ABI=""# Same-platform builds from different runners (mac arm64/x64) must produce identical trees.for dir in release/core-r0/*/; do- for latest in "$dir"core/*/latest.json; do+ for latest in "$dir"core-v4/*/latest.json; doplatform=$(basename "$(dirname "$latest")")[ "$(jq -r '.version' "$latest")" = "$VERSION" ] || { echo "::error::core version in $latest is not $VERSION"; exit 1; }abi=$(jq -er '.shellAbi' "$latest")[ -z "$SHELL_ABI" ] && SHELL_ABI="$abi"[ "$abi" = "$SHELL_ABI" ] || { echo "::error::shellAbi differs across platforms ($latest)"; exit 1; }- if [ -f "release/core-ota/core/$platform/latest.json" ]; then+ if [ -f "release/core-ota/core-v4/$platform/latest.json" ]; then# A mismatch only costs delta efficiency for some clients (they fall back to objects/full pack); keep the first tree.- diff <(jq -S '.tree' "release/core-ota/core/$platform/latest.json") <(jq -S '.tree' "$latest") \+ diff <(jq -S '.tree' "release/core-ota/core-v4/$platform/latest.json") <(jq -S '.tree' "$latest") \|| echo "::warning::$platform core trees differ between runners; keeping the first"continuefi- mkdir -p release/core-ota/cas release/core-ota/core- if [ -d "$dir"cas ]; then cp -R "$dir"cas/. release/core-ota/cas/; fi- cp -R "$dir"core/"$platform" release/core-ota/core/+ mkdir -p release/core-ota/core-v4+ cp -R "$dir"core-v4/"$platform" release/core-ota/core-v4/donedone[ -n "$SHELL_ABI" ] || { echo "::error::no r0 core artifacts found"; exit 1; }@@ -97,6 +96,8 @@ runs:id: baseuses: ./.github/actions/desktop-publish-core-otawith:+ core-dir: core-v4+ app-version: ${{ inputs.version }}channel: ${{ inputs.channel }}release-dir: release/core-otashell-json: release/shell.jsondiff --git a/.github/actions/desktop-upload-artifacts/action.yml b/.github/actions/desktop-upload-artifacts/action.ymlindex b56f14360ed..4e2c2344375 100644--- a/.github/actions/desktop-upload-artifacts/action.yml+++ b/.github/actions/desktop-upload-artifacts/action.yml@@ -78,7 +78,7 @@ runs:*/stable|*/nightly|*/canary|*/beta) BASE="${BASE%/*}" ;;esacread -r PLATFORM CHANNEL VERSION SEQ SHELL_ABI < <(node -p "const m=require('./core-dist/manifest.json');[m.platform,m.channel,m.version,m.seq,m.shellAbi].join(' ')")- node scripts/buildCore.mjs \+ node scripts/buildCore.mjs --protocol=4 \--core=core-dist \--platform="$PLATFORM" \--channel="$CHANNEL" \diff --git a/.github/scripts/desktop-pack-publish.test.mjs b/.github/scripts/desktop-pack-publish.test.mjsnew file mode 100644index 00000000000..f1f1154490a--- /dev/null+++ b/.github/scripts/desktop-pack-publish.test.mjs@@ -0,0 +1,170 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { test } from 'node:test';++import { parse } from 'yaml';++const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');++test('v4 publication verifies packs before advancing latest and never writes the v3 feed', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'pack-publish-'));+ try {+ const action = parse(+ await readFile(+ new URL('../actions/desktop-publish-core-ota/action.yml', import.meta.url),+ 'utf8',+ ),+ );+ const script = action.runs.steps[0].run;+ const dir = path.join(root, 'release/core-v4/darwin');+ await mkdir(path.join(dir, 'packs'), { recursive: true });+ await mkdir(path.join(dir, 'versions'), { recursive: true });+ const bytes = Buffer.from('compressed frame fixture');+ const sha256 = digest(bytes);+ const packPath = `packs/${sha256}.pack`;+ await writeFile(path.join(dir, packPath), bytes);+ const manifest = {+ version: '1',+ seq: 1,+ packs: [{ sha256, path: packPath, size: bytes.length }],+ objects: {+ [sha256]: { compressedSha256: sha256, length: bytes.length, offset: 0, packSha256: sha256 },+ },+ patches: [],+ };+ for (const file of ['latest.json', 'versions/1.json'])+ await writeFile(path.join(dir, file), JSON.stringify(manifest));+ await writeFile(+ path.join(root, 'aws'),+ `#!/usr/bin/env node+const fs=require('fs');+const args=process.argv.slice(2);+fs.appendFileSync(process.env.AWS_CALLS,JSON.stringify(args)+'\\n');+if(args[0]==='s3' && args[1]==='ls') process.exit(1);+if(args[0]==='s3' && args[1]==='cp' && args[3]==='-') {+ process.stdout.write(process.env.BAD_PACK==='1' ? 'corrupt' : fs.readFileSync(process.env.PACK_FILE));+}+if(args[0]==='s3api') {+ const bytes=fs.readFileSync(process.env.PACK_FILE);+ fs.writeFileSync(args.at(-1),bytes);+ process.stdout.write(JSON.stringify({ContentRange:'bytes 0-'+(bytes.length-1)+'/'+bytes.length}));+}+`,+ );+ await chmod(path.join(root, 'aws'), 0o755);+ for (const [appVersion, bad] of [+ ['1.0.0', '1'],+ ['1.0.0', '0'],+ ['2.0.0-canary.1', '0'],+ ]) {+ const log = path.join(root, `calls-${appVersion}-${bad}.jsonl`);+ const result = spawnSync('bash', ['-c', script], {+ encoding: 'utf8',+ env: {+ ...process.env,+ APP_VERSION: appVersion,+ AWS_CALLS: log,+ BAD_PACK: bad,+ CHANNEL: 'stable',+ CORE_DIR: 'core-v4',+ GITHUB_OUTPUT: path.join(root, 'output'),+ PACK_FILE: path.join(dir, packPath),+ PATH: `${root}:${process.env.PATH}`,+ RELEASE_DIR: path.join(root, 'release'),+ S3_BUCKET: 'fixture',+ S3_ENDPOINT: '',+ SHELL_JSON: '',+ },+ });+ const calls = (await readFile(log, 'utf8'))+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+ const expectedPrefix = `s3://fixture/stable/${appVersion}/core-v4/darwin/`;+ for (const args of calls) {+ for (const arg of args.filter((value) => value.startsWith('s3://')))+ assert(arg.startsWith(expectedPrefix), `Unexpected cross-version access: ${arg}`);+ if (args[0] === 's3api')+ assert(+ args[args.indexOf('--key') + 1].startsWith(`stable/${appVersion}/core-v4/darwin/`),+ );+ }+ const writes = calls.filter(+ (args) => args[0] === 's3' && args[1] === 'cp' && args[3].startsWith('s3://'),+ );+ assert.equal(+ writes.some((args) => args[3].includes('/stable/core/')),+ false,+ );+ assert.equal(+ writes.some((args) => args[3].endsWith('/latest.json')),+ bad === '0',+ result.stderr,+ );+ assert.equal(result.status === 0, bad === '0', result.stderr);+ console.log(+ JSON.stringify({+ scenario: bad === '1' ? 'corrupt-upload' : 'valid-upload',+ latestPublished: bad === '0',+ v3Untouched: true,+ }),+ );+ }+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test('v4 seq allocation only reads the owning app version across platforms', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'pack-seq-'));+ try {+ const action = parse(+ await readFile(new URL('../actions/desktop-core-seq/action.yml', import.meta.url), 'utf8'),+ );+ await writeFile(+ path.join(root, 'curl'),+ `#!/usr/bin/env node+const fs=require('fs');const args=process.argv.slice(2);const url=args.at(-1);+fs.appendFileSync(process.env.URL_LOG,url+'\\n');+const match=url.match(/\\/stable\\/([^/]+)\\/core-v4\\/(darwin|win32|linux)\\/latest.json$/);+if(!match) process.exit(2);+if(match[1]==='2.0.0'){process.stdout.write('404');process.exit(0);}+fs.writeFileSync(args[args.indexOf('-o')+1],JSON.stringify({seq:match[2]==='darwin'?7:3}));process.stdout.write('200');+`,+ );+ await chmod(path.join(root, 'curl'), 0o755);+ for (const [appVersion, expected] of [+ ['1.0.0', 8],+ ['2.0.0', 0],+ ]) {+ const output = path.join(root, `output-${appVersion}`);+ const log = path.join(root, `urls-${appVersion}`);+ const result = spawnSync('bash', ['-c', action.runs.steps[0].run], {+ encoding: 'utf8',+ env: {+ ...process.env,+ APP_VERSION: appVersion,+ CHANNEL: 'stable',+ UPDATE_SERVER_URL: 'https://updates.test/stable',+ RUNNER_TEMP: root,+ GITHUB_OUTPUT: output,+ URL_LOG: log,+ PATH: `${root}:${process.env.PATH}`,+ },+ });+ assert.equal(result.status, 0, result.stderr);+ assert.match(await readFile(output, 'utf8'), new RegExp(`seq=${expected}\\n`));+ const urls = (await readFile(log, 'utf8')).trim().split('\n');+ assert.equal(urls.length, 3);+ assert(+ urls.every((url) => url.startsWith(`https://updates.test/stable/${appVersion}/core-v4/`)),+ );+ }+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/.github/workflows/release-desktop-beta.yml b/.github/workflows/release-desktop-beta.ymlindex eed18cee9ba..ea8640dc5b7 100644--- a/.github/workflows/release-desktop-beta.yml+++ b/.github/workflows/release-desktop-beta.yml@@ -115,6 +115,7 @@ jobs:id: core_sequses: ./.github/actions/desktop-core-seqwith:+ app-version: ${{ needs.check-beta.outputs.version }}channel: betaupdate-server-url: ${{ secrets.UPDATE_SERVER_URL }}diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.ymlindex 1244ec57f04..c2d43a74951 100644--- a/.github/workflows/release-desktop-canary.yml+++ b/.github/workflows/release-desktop-canary.yml@@ -284,6 +284,7 @@ jobs:id: core_sequses: ./.github/actions/desktop-core-seqwith:+ app-version: ${{ needs.calculate-version.outputs.version }}channel: canaryupdate-server-url: ${{ secrets.UPDATE_SERVER_URL }}diff --git a/.github/workflows/release-desktop-core-ota.yml b/.github/workflows/release-desktop-core-ota.ymlindex 597ab69b109..f7549333ba8 100644--- a/.github/workflows/release-desktop-core-ota.yml+++ b/.github/workflows/release-desktop-core-ota.yml@@ -5,10 +5,9 @@ name: Release Desktop Core OTA# ============================================# 门禁: HEAD 的 shellAbi 必须等于 <channel>/shell.json 的 shellAbi,# 否则 requires_full_release=true,由调用方走全量发版。-# 产物: cas/objects/<sha>.zst, cas/patches/<from>-<to>.zst 跨平台共享,immutable-# <channel>/core/<platform>/packs/<sha>.zip 全量 zip(fallback)-# <channel>/core/<platform>/versions/<version>.json 签名快照-# <channel>/core/<platform>/latest.json 签名 manifest(no-store)+# 产物: <channel>/<appVersion>/core-v4/<platform>/packs/<sha>.pack 独立 Zstd 块+# <channel>/<appVersion>/core-v4/<platform>/versions/<version>.json 签名快照+# <channel>/<appVersion>/core-v4/<platform>/latest.json 签名 manifest# ============================================on:@@ -147,6 +146,7 @@ jobs:if: steps.gate.outputs.allowed == 'true'uses: ./.github/actions/desktop-core-seqwith:+ app-version: ${{ steps.base.outputs.app_version }}channel: ${{ inputs.channel }}update-server-url: ${{ secrets.UPDATE_SERVER_URL }}@@ -230,12 +230,13 @@ jobs:id: previousenv:CHANNEL: ${{ inputs.channel }}+ APP_VERSION: ${{ needs.gate.outputs.app_version }}FEED_BASE_URL: ${{ needs.gate.outputs.feed_base_url }}PLATFORM: ${{ matrix.platform }}run: |set -euo pipefailHTTP_STATUS=$(curl -sS --connect-timeout 10 --max-time 30 \- -o "$RUNNER_TEMP/previous-core.json" -w '%{http_code}' "$FEED_BASE_URL/$CHANNEL/core/$PLATFORM/latest.json")+ -o "$RUNNER_TEMP/previous-core.json" -w '%{http_code}' "$FEED_BASE_URL/$CHANNEL/$APP_VERSION/core-v4/$PLATFORM/latest.json")case "$HTTP_STATUS" in200)echo "Previous core: $(jq -er '.version' "$RUNNER_TEMP/previous-core.json")"@@ -254,6 +255,7 @@ jobs:env:RENDERER_OTA_PRIVATE_KEY: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}CHANNEL: ${{ inputs.channel }}+ APP_VERSION: ${{ needs.gate.outputs.app_version }}FEED_BASE_URL: ${{ needs.gate.outputs.feed_base_url }}PLATFORM: ${{ matrix.platform }}PREVIOUS_ARGS: ${{ steps.previous.outputs.args }}@@ -265,7 +267,7 @@ jobs:set -euo pipefailset +e# shellcheck disable=SC2086- node scripts/buildCore.mjs \+ node scripts/buildCore.mjs --protocol=4 \--core=core-dist \--platform="$PLATFORM" \--channel="$CHANNEL" \@@ -273,7 +275,7 @@ jobs:--seq="$SEQ" \--rollout="$ROLLOUT" \--shell-abi="$SHELL_ABI" \- --objects-base-url="$FEED_BASE_URL/cas" \+ --previous-base-url="$FEED_BASE_URL/$CHANNEL/$APP_VERSION/core-v4/$PLATFORM" \--out=release/core-ota \$PREVIOUS_ARGSSTATUS=$?@@ -327,8 +329,8 @@ jobs:id: collectrun: |set -euo pipefail- if [ -d release/core-ota/core ] && [ -n "$(ls -A release/core-ota/core)" ]; then- echo "Platforms: $(ls release/core-ota/core | tr '\n' ' ')"+ if [ -d release/core-ota/core-v4 ] && [ -n "$(ls -A release/core-ota/core-v4)" ]; then+ echo "Platforms: $(ls release/core-ota/core-v4 | tr '\n' ' ')"echo "skipped=false" >> "$GITHUB_OUTPUT"elseecho "::notice::every platform was unchanged; nothing to publish"@@ -340,6 +342,8 @@ jobs:if: steps.collect.outputs.skipped == 'false'uses: ./.github/actions/desktop-publish-core-otawith:+ core-dir: core-v4+ app-version: ${{ needs.gate.outputs.app_version }}channel: ${{ inputs.channel }}release-dir: release/core-otaaws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}diff --git a/.github/workflows/release-desktop-stable.yml b/.github/workflows/release-desktop-stable.ymlindex 23563bda6f3..59da291818c 100644--- a/.github/workflows/release-desktop-stable.yml+++ b/.github/workflows/release-desktop-stable.yml@@ -208,6 +208,7 @@ jobs:id: core_sequses: ./.github/actions/desktop-core-seqwith:+ app-version: ${{ needs.check-stable.outputs.version }}channel: stableupdate-server-url: ${{ secrets.UPDATE_SERVER_URL }}diff --git a/.gitignore b/.gitignoreindex 74c2cd94d2b..69d8b35e1de 100644--- a/.gitignore+++ b/.gitignore@@ -182,3 +182,7 @@ apps/desktop/core-dist# alint: local provider setup (holds the API key) and result cache.alint/.alintcache++# Packaged builtin desktop core+/apps/desktop/core.asar+/apps/desktop/core.asar.unpacked/diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex 37e75c599df..576bcc030b7 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -14,6 +14,7 @@ import {getAsarUnpackPatterns,getNativeModulesFilesConfig,} from './native-deps.config.mjs';+import { packBuiltinCore } from './scripts/packBuiltinCore.mjs';import { verifyFontListSignature } from './scripts/verifyFontListSigning.mjs';dotenv.config();@@ -178,6 +179,7 @@ const config = {`node scripts/buildCoreManifest.mjs --core=core-dist --platform=${corePlatform} --channel=${channel || 'stable'} --version=${packageJSON.version} --seq=${process.env.CORE_SEQ || 0} --shell-abi=${shellAbi}`,{ stdio: 'inherit', cwd: __dirname },);+ await packBuiltinCore(__dirname);},/*** AfterPack hook for copying Liquid Glass Assets.car on macOS 26+.@@ -343,9 +345,8 @@ const config = {extraResources: [{ from: 'resources/bin', to: 'bin' },- { from: 'core-dist', to: 'core' },- // electron-builder's copy filter drops a top-level `node_modules` dir from any `from`, so it needs its own entry- { from: 'core-dist/node_modules', to: 'core/node_modules' },+ { from: 'core.asar', to: 'core.asar' },+ { from: 'core.asar.unpacked', to: 'core.asar.unpacked' },// Local Sandbox helper binaries. The sandbox spawns these by path, so they// must be real files — not entries inside app.asar, and not something the// user is expected to install separately.diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex baecf9d7ae5..58f5a20f982 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -45,6 +45,7 @@"start:reuse": "electron .","stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix","test": "vitest --run",+ "test:core-ota": "vitest run --config scripts/core-ota-test/vitest.config.mjs","type-check": "tsgo --noEmit -p tsconfig.json","typecheck": "tsgo --noEmit -p tsconfig.json","update-server": "sh scripts/update-test/run-test.sh"diff --git a/apps/desktop/scripts/__tests__/assembleCore.test.mjs b/apps/desktop/scripts/__tests__/assembleCore.test.mjsindex 16b72fad462..47ae2b7a0d7 100644--- a/apps/desktop/scripts/__tests__/assembleCore.test.mjs+++ b/apps/desktop/scripts/__tests__/assembleCore.test.mjs@@ -1,3 +1,4 @@+import { execFileSync } from 'node:child_process';import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';@@ -67,7 +68,7 @@ describe('assembleCore', () => {assembleCore(options);expect(await listFiles(options.out)).toEqual([- 'cli/lobe-cli.js',+ 'cli/dist/index.js','cli/package.json','dist/main/chunk.js','dist/main/index.js',@@ -80,7 +81,7 @@ describe('assembleCore', () => {'resources/sounds/ping.mp3','resources/tray.png',]);- expect(await readFile(path.join(options.out, 'cli/lobe-cli.js'), 'utf8')).toBe('cli');+ expect(await readFile(path.join(options.out, 'cli/dist/index.js'), 'utf8')).toBe('cli');expect(JSON.parse(await readFile(path.join(options.out, 'package.json'), 'utf8'))).toEqual({type: 'commonjs',});@@ -91,6 +92,20 @@ describe('assembleCore', () => {});});+ it('keeps the CLI entry one directory below its package metadata', async () => {+ const options = await setup();+ await write(+ 'cli/dist/index.js',+ `import { createRequire } from 'node:module'; console.log(createRequire(import.meta.url)('../package.json').version);`,+ );+ assembleCore(options);+ expect(+ execFileSync(process.execPath, [path.join(options.out, 'cli/dist/index.js')], {+ encoding: 'utf8',+ }).trim(),+ ).toBe('1.2.3');+ });+it('throws when dist/main is missing', async () => {const options = await setup();await rm(path.join(options.desktopDir, 'dist/main'), { recursive: true });diff --git a/apps/desktop/scripts/__tests__/packBuiltinCore.test.mjs b/apps/desktop/scripts/__tests__/packBuiltinCore.test.mjsnew file mode 100644index 00000000000..b6b4ab5dda1--- /dev/null+++ b/apps/desktop/scripts/__tests__/packBuiltinCore.test.mjs@@ -0,0 +1,42 @@+import { execFileSync } from 'node:child_process';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { expect, it } from 'vitest';++import { packBuiltinCore } from '../packBuiltinCore.mjs';++const require = createRequire(import.meta.url);+const asar = createRequire(+ createRequire(require.resolve('electron-builder')).resolve('app-builder-lib'),+)('@electron/asar');++it('packs business files while keeping a runnable CLI and its metadata outside the archive', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'builtin-asar-'));+ try {+ await mkdir(path.join(dir, 'core-dist/cli/dist'), { recursive: true });+ await writeFile(path.join(dir, 'core-dist/main.js'), 'module.exports = 42;');+ await writeFile(+ path.join(dir, 'core-dist/cli/package.json'),+ JSON.stringify({ type: 'module', version: '1.2.3' }),+ );+ await writeFile(+ path.join(dir, 'core-dist/cli/dist/index.js'),+ "import { createRequire } from 'node:module'; console.log(createRequire(import.meta.url)('../package.json').version);",+ );+ await packBuiltinCore(dir);+ expect(asar.extractFile(path.join(dir, 'core.asar'), 'main.js').toString()).toBe(+ 'module.exports = 42;',+ );+ await expect(readFile(path.join(dir, 'core.asar.unpacked/main.js'))).rejects.toThrow();+ expect(+ execFileSync(process.execPath, [path.join(dir, 'core.asar.unpacked/cli/dist/index.js')], {+ encoding: 'utf8',+ }).trim(),+ ).toBe('1.2.3');+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/scripts/assembleCore.mjs b/apps/desktop/scripts/assembleCore.mjsindex 4a4651848f4..0607f05b311 100644--- a/apps/desktop/scripts/assembleCore.mjs+++ b/apps/desktop/scripts/assembleCore.mjs@@ -39,8 +39,8 @@ export function assembleCore({copy(inputs['node_modules/electron-log'], 'node_modules/electron-log');writeFileSync(path.join(out, 'package.json'), JSON.stringify({ type: 'commonjs' }));- mkdirSync(path.join(out, 'cli'), { recursive: true });- cpSync(inputs['apps/cli/dist/index.js'], path.join(out, 'cli/lobe-cli.js'));+ mkdirSync(path.join(out, 'cli/dist'), { recursive: true });+ cpSync(inputs['apps/cli/dist/index.js'], path.join(out, 'cli/dist/index.js'));const { name, version } = JSON.parse(readFileSync(path.join(cliDir, 'package.json'), 'utf8'));writeFileSync(path.join(out, 'cli/package.json'),diff --git a/apps/desktop/scripts/buildCore.mjs b/apps/desktop/scripts/buildCore.mjsindex be342e5f467..730abdd79de 100644--- a/apps/desktop/scripts/buildCore.mjs+++ b/apps/desktop/scripts/buildCore.mjs@@ -6,6 +6,7 @@ import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib';import {createCoreManifest,+ EmptyReleaseError,parseArgs,readCoreTree,readPrivateKey,@@ -18,11 +19,7 @@ const PATCH_SCOPE = /^(?:dist\/renderer|cli)\//;const RELOAD_SCOPE = 'dist/renderer/';const ZSTD_LEVEL = { params: { [constants.ZSTD_c_compressionLevel]: 19 } };-export class EmptyReleaseError extends Error {- constructor() {- super('empty release');- }-}+export { EmptyReleaseError } from './buildCoreManifest.mjs';const sha256Of = (content) => createHash('sha256').update(content).digest('hex');@@ -175,7 +172,10 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {const args = parseArgs(process.argv.slice(2));const started = Date.now();try {- const { manifest, stats } = await buildCore({+ const build =+ args.protocol === '4' ? (await import('./buildCoreV4.mjs')).buildCoreV4 : buildCore;+ const { manifest, stats } = await build({+ previousBaseUrl: args['previous-base-url'],channel: args.channel,coreDir: path.resolve(args.core ?? 'core-dist'),objectsBaseUrl: args['objects-base-url'],@@ -192,8 +192,8 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {});console.log(`core ${manifest.channel}/${manifest.platform} ${manifest.version} seq ${manifest.seq}: ` +- `${manifest.tree.length} files, ${stats.objects} objects (${stats.objectsWritten} new, ${(stats.objectBytes / 1048576).toFixed(2)} MB zst), ` +- `${stats.patches} patches, full ${(manifest.full.size / 1048576).toFixed(2)} MB, ` ++ `${manifest.tree.length} files, ${stats.objects ?? manifest.tree.length} objects (${stats.objectsWritten} new, ${(stats.objectBytes / 1048576).toFixed(2)} MB zst), ` ++ `${stats.patches} patches, full ${((manifest.full?.size ?? manifest.packs[0].size) / 1048576).toFixed(2)} MB, ` +`applyMode ${manifest.applyMode}, previous ${manifest.previous}, ${((Date.now() - started) / 1000).toFixed(1)}s`,);} catch (error) {diff --git a/apps/desktop/scripts/buildCoreManifest.mjs b/apps/desktop/scripts/buildCoreManifest.mjsindex 71e380b85b6..1579dbce2af 100644--- a/apps/desktop/scripts/buildCoreManifest.mjs+++ b/apps/desktop/scripts/buildCoreManifest.mjs@@ -135,3 +135,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {`core manifest: ${manifest.channel}/${manifest.platform} ${manifest.version} seq ${manifest.seq} (${manifest.tree.length} files, ${manifest.signature ? 'signed' : 'UNSIGNED'})`,);}++export class EmptyReleaseError extends Error {+ constructor() {+ super('empty release');+ }+}diff --git a/apps/desktop/scripts/buildCoreV4.mjs b/apps/desktop/scripts/buildCoreV4.mjsnew file mode 100644index 00000000000..f7aac7a1b3c--- /dev/null+++ b/apps/desktop/scripts/buildCoreV4.mjs@@ -0,0 +1,186 @@+import { createHash } from 'node:crypto';+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';+import { constants, zstdCompress, zstdDecompress } from 'node:zlib';++import { EmptyReleaseError, readCoreTree } from './buildCoreManifest.mjs';+import { signManifest } from './buildRendererManifest.mjs';+import { generateZstdPatch, pairRendererFiles } from './rendererDelta.mjs';++const compress = promisify(zstdCompress);+const decompress = promisify(zstdDecompress);+const hash = (content) => createHash('sha256').update(content).digest('hex');+const PATCH_SCOPE = /^(?:dist\/renderer|cli)\//;++export async function writeCorePack(entries, output) {+ const chunks = [];+ const index = {};+ let offset = 0;+ for (const [key, bytes] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {+ index[key] = { compressedSha256: hash(bytes), length: bytes.length, offset };+ chunks.push(bytes);+ offset += bytes.length;+ }+ const bytes = Buffer.concat(chunks);+ const sha256 = hash(bytes);+ const pack = { path: `packs/${sha256}.pack`, sha256, size: bytes.length };+ await mkdir(path.join(output, 'packs'), { recursive: true });+ await writeFile(path.join(output, pack.path), bytes);+ for (const frame of Object.values(index)) frame.packSha256 = sha256;+ return { index, pack };+}++async function boundedBody(response, limit) {+ const chunks = [];+ let size = 0;+ for await (const chunk of response.body) {+ size += chunk.length;+ if (size > limit) throw new Error('Previous content exceeds size limit');+ chunks.push(chunk);+ }+ return Buffer.concat(chunks);+}++async function previousContent(manifest, sha256, baseUrl, fetchImpl) {+ if (manifest.schemaVersion !== 4) {+ const response = await fetchImpl(`${manifest.objectsBaseUrl}/objects/${sha256}.zst`);+ if (!response.ok) throw new Error(`Previous object HTTP ${response.status}`);+ const bytes = await decompress(await boundedBody(response, 256 * 1024 ** 2), {+ maxOutputLength: 256 * 1024 ** 2,+ });+ if (hash(bytes) !== sha256) throw new Error('Previous object hash mismatch');+ return bytes;+ }+ const frame = manifest.objects[sha256];+ const pack = manifest.packs.find((entry) => entry.sha256 === frame.packSha256);+ const end = frame.offset + frame.length - 1;+ const response = await fetchImpl(`${baseUrl}/${pack.path}`, {+ headers: { Range: `bytes=${frame.offset}-${end}` },+ });+ if (+ response.status !== 206 ||+ response.headers.get('content-range') !== `bytes ${frame.offset}-${end}/${pack.size}`+ )+ throw new Error('Previous pack Range unsupported');+ const raw = await boundedBody(response, Math.min(frame.length, 256 * 1024 ** 2));+ if (raw.length !== frame.length || hash(raw) !== frame.compressedSha256)+ throw new Error('Previous frame mismatch');+ const bytes = await decompress(raw, { maxOutputLength: 256 * 1024 ** 2 });+ if (hash(bytes) !== sha256) throw new Error('Previous content mismatch');+ return bytes;+}++export async function buildCoreV4({+ channel,+ coreDir,+ outDir,+ platform,+ privateKeyPem,+ seq,+ shellAbi,+ version,+ previousManifest = null,+ previousBaseUrl,+ rollout = 1,+ fetchImpl = fetch,+}) {+ if (!privateKeyPem) throw new Error('private key required');+ if (+ !/^[\w.+-]{1,64}$/.test(version) ||+ version === '.' ||+ version === '..' ||+ !['darwin', 'win32', 'linux'].includes(platform) ||+ !['stable', 'beta', 'canary', 'nightly'].includes(channel) ||+ !/^[0-9a-f]{64}$/.test(shellAbi) ||+ !Number.isSafeInteger(seq) ||+ seq < 0 ||+ !Number.isFinite(rollout) ||+ rollout < 0 ||+ rollout > 1+ )+ throw new Error('Invalid core release metadata');+ const { objects, tree } = readCoreTree(coreDir);+ if (!tree.length || tree.some((file) => file.size > 256 * 1024 ** 2))+ throw new Error('Invalid core file size');+ const old = new Map(previousManifest?.tree.map((file) => [file.path, file.sha256]) ?? []);+ const next = new Map(tree.map((file) => [file.path, file.sha256]));+ const changed = [...new Set([...old.keys(), ...next.keys()])].filter(+ (key) => old.get(key) !== next.get(key),+ );+ if (previousManifest && changed.every((key) => key === 'package.json'))+ throw new EmptyReleaseError();+ const output = path.join(outDir, 'core-v4', platform);+ const encoded = new Map();+ for (const [sha256, bytes] of objects) {+ encoded.set(+ sha256,+ await compress(bytes, { params: { [constants.ZSTD_c_compressionLevel]: 19 } }),+ );+ }+ const { index, pack } = await writeCorePack(encoded, output);+ const patchBytes = new Map();+ if (previousManifest) {+ const pairs = pairRendererFiles(+ previousManifest.tree.filter((file) => PATCH_SCOPE.test(file.path)),+ tree.filter((file) => PATCH_SCOPE.test(file.path)),+ );+ for (const pair of pairs) {+ if (pair.kind !== 'patch') continue;+ const key = `${pair.from.sha256}-${pair.to.sha256}`;+ if (patchBytes.has(key)) continue;+ try {+ const base = await previousContent(+ previousManifest,+ pair.from.sha256,+ previousBaseUrl,+ fetchImpl,+ );+ const patch = await generateZstdPatch(base, objects.get(pair.to.sha256));+ if (patch && patch.length < index[pair.to.sha256].length) patchBytes.set(key, patch);+ } catch (error) {+ console.warn(`Skipping optional patch ${key}: ${error.message}`);+ }+ }+ }+ const packs = [pack];+ const patches = [];+ if (patchBytes.size) {+ const built = await writeCorePack(patchBytes, output);+ packs.push(built.pack);+ for (const [key, frame] of Object.entries(built.index)) {+ const [fromSha256, toSha256] = key.split('-');+ patches.push({ ...frame, fromSha256, toSha256 });+ }+ }+ const manifest = signManifest(+ {+ applyMode: previousManifest+ ? changed.every((key) => key.startsWith('dist/renderer/'))+ ? 'reload'+ : 'relaunch'+ : null,+ channel,+ objects: index,+ packs,+ patches,+ platform,+ previous: previousManifest?.version ?? null,+ rollout,+ schemaVersion: 4,+ seq,+ shellAbi,+ tree,+ version,+ },+ privateKeyPem,+ );+ await mkdir(path.join(output, 'versions'), { recursive: true });+ const json = JSON.stringify(manifest, null, 2);+ await writeFile(path.join(output, 'versions', `${version}.json`), json);+ await writeFile(path.join(output, 'latest.json'), json);+ return {+ manifest,+ stats: { objectBytes: pack.size, objectsWritten: objects.size, patches: patches.length },+ };+}diff --git a/apps/desktop/scripts/core-ota-test/README.md b/apps/desktop/scripts/core-ota-test/README.mdindex 7e46b22b74b..3ae2964f8f3 100644--- a/apps/desktop/scripts/core-ota-test/README.md+++ b/apps/desktop/scripts/core-ota-test/README.md@@ -1,12 +1,23 @@# Core OTA 本地 E2E(打包态)在本机打一个 arm64 的壳 + 内置 core(v1),再用本地 feed 依次发布 renderer-only(v2,reload)-和 main 变更(v3,relaunch),最后验证篡改拒绝和 boot 回滚。所有命令在 `apps/desktop/` 下执行。+和 main 变更(v3,relaunch),最后验证篡改拒绝和 boot 回滚。+这里的 v1–v4 是测试版本号,传输协议均为 schemaVersion 4,使用 `<channel>/<appVersion>/core-v4/<platform>` feed 和 HTTP Range;内置业务位于 `core.asar`,CLI 位于 `core.asar.unpacked/cli/dist/index.js`。所有命令在 `apps/desktop/` 下执行。产物都在 `release/core-ota-e2e/`:`priv.pem`/`pub.pem`、`app/`(打包结果)、`core-v1..v3/`、`feed/`。app 名固定为 `lobehub-core-ota-e2e`,userData 在 `~/Library/Application Support/lobehub-core-ota-e2e`,日志在 `~/Library/Logs/lobehub-core-ota-e2e/main.log`,与开发实例互不干扰。+## 手动 pack 集成验证++```bash+bun run test:core-ota+```++这组验证执行真实 zstd 压缩、打包和磁盘 staging,覆盖跨版本复用、401 个文件增量、Range、补丁和损坏拒绝。+仅在修改 OTA 协议或发布前手动运行,不纳入默认 `test` / PR CI;独立配置允许每项最多 30 秒。+它验证正确性,不测量性能指标,因此不作为 benchmark。+## 1. 构建 v1(一次,约 10 分钟)```bash@@ -67,8 +78,7 @@ node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.```bashR=release/core-ota-e2e/app/mac-arm64/lobehub-core-ota-e2e.app/Contents/Resources-cp $R/core/dist/main/index.js /tmp/core-main.js # 结束后拷回-sed -i '' '1s/^/throw new Error("e2e builtin boom");/' $R/core/dist/main/index.js+mv "$R/core.asar" "$R/core.asar.saved" # 仅限独立 E2E 应用,结束后移回# --dir 打包没有 app-update.yml,救援靠它拿 feed 地址printf 'provider: generic\nurl: http://127.0.0.1:8787/stable\n' > $R/app-update.yml```diff --git a/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs b/apps/desktop/scripts/core-ota-test/coreV4.integration.mjsnew file mode 100644index 00000000000..a97435efc98--- /dev/null+++ b/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs@@ -0,0 +1,219 @@+import { generateKeyPairSync, randomBytes } from 'node:crypto';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ coreManifestV4Schema,+ sha256File,+ verifyManifestSignature,+} from '../../src/main/core/infrastructure/coreOta/manifest';+import { planPackDownload } from '../../src/main/core/infrastructure/coreOta/pack';+import { CoreStore } from '../../src/main/core/infrastructure/coreOta/store';+import { buildCoreV4 } from '../buildCoreV4.mjs';++const keys = generateKeyPairSync('ed25519');+const privateKeyPem = keys.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();+const publicKeyPem = keys.publicKey.export({ format: 'pem', type: 'spki' }).toString();+const BASE = 'https://cdn.test/core-v4/darwin';+const entries = {+ 'dist/main/index.js': Buffer.from('main'),+ 'dist/renderer/apps/desktop/index.html': Buffer.from('<script src="/assets/index.js"></script>'),+ 'dist/renderer/apps/desktop/overlay.html': Buffer.from(+ '<script src="/assets/index.js"></script>',+ ),+ 'dist/renderer/apps/desktop/popup.html': Buffer.from('<script src="/assets/index.js"></script>'),+ 'dist/renderer/assets/index.js': Buffer.from('index'),+};+let root;+let files;+let responses;+let fetchImpl;+beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'core-v4-'));+ files = { ...entries, 'dist/renderer/assets/large.js': randomBytes(2 * 1024 ** 2) };+ responses = new Map();+ fetchImpl = vi.fn(async (url, init) => {+ const bytes = responses.get(url);+ if (!bytes) return new Response(null, { status: 404 });+ const range = new Headers(init?.headers).get('range');+ if (!range) return new Response(new Uint8Array(bytes));+ const match = /^bytes=(\d+)-(\d+)$/.exec(range);+ const start = Number(match[1]);+ const end = Number(match[2]);+ return new Response(new Uint8Array(bytes.subarray(start, end + 1)), {+ headers: { 'Content-Range': `bytes ${start}-${end}/${bytes.length}` },+ status: 206,+ });+ });+});+afterEach(async () => {+ await rm(root, { force: true, recursive: true });+});+const build = async (version, contents, previousManifest) => {+ const dir = path.join(root, version);+ for (const [file, bytes] of Object.entries(contents)) {+ await mkdir(path.dirname(path.join(dir, file)), { recursive: true });+ await writeFile(path.join(dir, file), bytes);+ }+ const { manifest: raw } = await buildCoreV4({+ channel: 'canary',+ coreDir: dir,+ fetchImpl,+ outDir: path.join(root, 'out'),+ platform: 'darwin',+ previousBaseUrl: BASE,+ previousManifest,+ privateKeyPem,+ seq: Number(version),+ shellAbi: 'a'.repeat(64),+ version,+ });+ const manifest = coreManifestV4Schema.parse(raw);+ for (const pack of manifest.packs)+ responses.set(+ `${BASE}/${pack.path}`,+ await readFile(path.join(root, 'out/core-v4/darwin', pack.path)),+ );+ return { dir, manifest };+};+const stage = async (builtin, remote) =>+ new CoreStore(path.join(root, 'ota'), fetchImpl).stage({+ builtin,+ current: null,+ packsBaseUrl: BASE,+ remote: remote.manifest,+ });+describe('v4 pack OTA', () => {+ it('builds deterministic signed packs and skips unchanged local bytes across versions', async () => {+ const v1 = await build('1', files);+ const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });+ const replay = await build('6', { ...files, 'cli/new.js': Buffer.from('new') });+ expect(replay.manifest.packs).toEqual(v5.manifest.packs);+ expect(verifyManifestSignature(v5.manifest, publicKeyPem)).toBe(true);+ const result = await stage(v1, v5);+ expect(result.downloaded.bytes).toBeLessThan(1000);+ expect(result.fallbackFull).toBe(false);+ expect(await readFile(path.join(result.dir, 'cli/new.js'), 'utf8')).toBe('new');+ expect(+ fetchImpl.mock.calls.every(([, init]) => !!new Headers(init?.headers).get('range')),+ ).toBe(true);+ expect(await readFile(path.join(result.dir, 'dist/renderer/assets/large.js'))).toEqual(+ files['dist/renderer/assets/large.js'],+ );+ });+ it('keeps 401 small missing files incremental and coalesces a fresh tree into one request', async () => {+ const v1 = await build('1', files);+ const next = { ...files };+ for (let i = 0; i < 401; i++) next[`cli/${i}.js`] = Buffer.from(`new ${i}`);+ const v5 = await build('5', next);+ const result = await stage(v1, v5);+ expect(result.fallbackFull).toBe(false);+ expect(result.downloaded.bytes).toBeLessThan(100_000);+ const plan = planPackDownload(v5.manifest, Object.keys(v5.manifest.objects), new Map());+ expect(plan.ranges.reduce((n, range) => n + range.end - range.offset, 0)).toBe(+ v5.manifest.packs[0].size,+ );+ expect(plan.ranges).toHaveLength(1);+ });+ it('repairs corrupted local files and cache entries instead of reusing them', async () => {+ const v1 = await build('1', files);+ const v5 = await build('5', files);+ await writeFile(path.join(v1.dir, 'dist/main/index.js'), 'bad');+ await mkdir(path.join(root, 'ota/store'), { recursive: true });+ await writeFile(+ path.join(root, 'ota/store', sha256File(files['dist/main/index.js'])),+ 'bad-cache',+ );+ const result = await stage(v1, v5);+ expect(await readFile(path.join(result.dir, 'dist/main/index.js'), 'utf8')).toBe('main');+ expect(result.downloaded.objects).toBe(1);+ });+ it('rejects wrong range offsets and never commits a version', async () => {+ const v1 = await build('1', files);+ const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });+ fetchImpl.mockImplementation(+ async () =>+ new Response(new Uint8Array(10), {+ headers: { 'Content-Range': 'bytes 0-9/10' },+ status: 206,+ }),+ );+ await expect(stage(v1, v5)).rejects.toThrow('Range');+ await expect(readFile(path.join(root, 'ota/cores/5/manifest.json'))).rejects.toThrow();+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ });+ it('cancels ignored ranges and downloads the full pack once', async () => {+ const v1 = await build('1', files);+ const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });+ fetchImpl.mockImplementation(async (url) => new Response(new Uint8Array(responses.get(url))));+ const result = await stage(v1, v5);+ expect(result.fallbackFull).toBe(true);+ expect(fetchImpl.mock.calls.filter(([, init]) => !init)).toHaveLength(1);+ expect(await readFile(path.join(result.dir, 'cli/new.js'), 'utf8')).toBe('new');+ });+ it('uses a matching file patch but can skip versions without its base', async () => {+ const text = Buffer.from(+ Array.from({ length: 10000 }, (_, i) => `line ${i}: something useful\n`).join(''),+ );+ const v1 = await build('1', { ...files, 'cli/lobe-cli.js': text });+ const updated = Buffer.from(text.toString().replace('line 30:', 'edited 30:'));+ const v5 = await build('5', { ...files, 'cli/lobe-cli.js': updated }, v1.manifest);+ expect(v5.manifest.patches).toHaveLength(1);+ fetchImpl.mockClear();+ const result = await stage(v1, v5);+ expect(result.downloaded.patches).toBe(1);+ const v0 = await build('0', files);+ await rm(path.join(root, 'ota'), { recursive: true, force: true });+ const skipped = await stage(v0, v5);+ expect(skipped.downloaded.patches).toBe(0);+ expect(await readFile(path.join(skipped.dir, 'cli/lobe-cli.js'))).toEqual(updated);+ });+ it('rejects malformed locations before downloading', async () => {+ const { manifest } = await build('1', files);+ const hash = Object.keys(manifest.objects)[0];+ expect(+ coreManifestV4Schema.safeParse({+ ...manifest,+ objects: {+ ...manifest.objects,+ [hash]: { ...manifest.objects[hash], offset: Number.MAX_SAFE_INTEGER },+ },+ }).success,+ ).toBe(false);+ expect(coreManifestV4Schema.safeParse({ ...manifest, objects: {} }).success).toBe(false);+ });+ it('falls back only the failed patch and rejects corrupt object frames', async () => {+ const text = Buffer.from(+ Array.from({ length: 10000 }, (_, i) => `line ${i}: useful content\n`).join(''),+ );+ const v1 = await build('1', { ...files, 'cli/lobe-cli.js': text });+ const updated = Buffer.from(text.toString().replace('line 30:', 'changed 30:'));+ const v5 = await build('5', { ...files, 'cli/lobe-cli.js': updated }, v1.manifest);+ const patch = v5.manifest.patches[0];+ const pack = v5.manifest.packs.find((p) => p.sha256 === patch.packSha256);+ responses.get(`${BASE}/${pack.path}`)[patch.offset] ^= 1;+ fetchImpl.mockClear();+ const result = await stage(v1, v5);+ expect(result.downloaded).toMatchObject({ objects: 1, patches: 0 });+ expect(result.fallbackFull).toBe(false);+ expect(await readFile(path.join(result.dir, 'cli/lobe-cli.js'))).toEqual(updated);+ await rm(path.join(root, 'ota'), { recursive: true, force: true });+ const frame = v5.manifest.objects[sha256File(updated)];+ const objectPack = v5.manifest.packs.find((p) => p.sha256 === frame.packSha256);+ responses.get(`${BASE}/${objectPack.path}`)[frame.offset] ^= 1;+ await expect(stage(v1, v5)).rejects.toThrow('hash mismatch');+ await expect(readFile(path.join(root, 'ota/cores/5/manifest.json'))).rejects.toThrow();+ });++ it('does not replace an existing corrupt version directory', async () => {+ const v1 = await build('1', files);+ const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });+ const result = await stage(v1, v5);+ await writeFile(path.join(result.dir, 'cli/new.js'), 'user-owned');+ await expect(stage(v1, v5)).rejects.toThrow('Existing core version is corrupt');+ expect(await readFile(path.join(result.dir, 'cli/new.js'), 'utf8')).toBe('user-owned');+ });+});diff --git a/apps/desktop/scripts/core-ota-test/run.mjs b/apps/desktop/scripts/core-ota-test/run.mjsindex 50da53038f9..f87a74924a5 100644--- a/apps/desktop/scripts/core-ota-test/run.mjs+++ b/apps/desktop/scripts/core-ota-test/run.mjs@@ -8,7 +8,6 @@ import {readdirSync,readFileSync,rmSync,- symlinkSync,writeFileSync,} from 'node:fs';import os from 'node:os';@@ -23,6 +22,7 @@ const CDP_PORT = 9333;const PRODUCT = 'lobehub-core-ota-e2e';const CHANNEL = 'stable';const APP_VERSION = '1.0.0';+const RELEASE = path.join(FEED, CHANNEL, APP_VERSION);const PLATFORM = 'darwin';const APP = path.join(WORK, 'app', 'mac-arm64', `${PRODUCT}.app`, 'Contents', 'MacOS', PRODUCT);const USER_DATA = path.join(os.homedir(), 'Library/Application Support', PRODUCT);@@ -43,14 +43,18 @@ const manifestOf = (tag) =>const publish = (tag, { version, seq, previous }) => {const { shellAbi } = manifestOf(previous ?? tag);const previousArg = previous- ? `--previous-manifest=${path.join(FEED, 'core', PLATFORM, 'versions', `${manifestOf(previous).version}.json`)}`+ ? `--previous-manifest=${path.join(RELEASE, 'core-v4', PLATFORM, 'versions', `${manifestOf(previous).version}.json`)}`: '';sh(- `node scripts/buildCore.mjs --core=${coreDir(tag)} --platform=${PLATFORM} --channel=${CHANNEL} ` ++ `node scripts/buildCore.mjs --protocol=4 --core=${coreDir(tag)} --platform=${PLATFORM} --channel=${CHANNEL} ` +`--version=${version} --seq=${seq} --shell-abi=${shellAbi} ` +- `--objects-base-url=http://127.0.0.1:${PORT}/cas --out=${FEED} ${previousArg}`,+ `--previous-base-url=http://127.0.0.1:${PORT}/${CHANNEL}/${APP_VERSION}/core-v4/${PLATFORM} --out=${RELEASE} ${previousArg}`,{ RENDERER_OTA_PRIVATE_KEY: keys().privateKey },);+ cpSync(+ path.join(RELEASE, 'core-v4', PLATFORM, 'versions', `${version}.json`),+ path.join(coreDir(tag), 'manifest.json'),+ );};const steps = {@@ -95,8 +99,6 @@ const steps = {cpSync(path.join(DESKTOP_DIR, 'core-dist'), coreDir('v1'), { recursive: true });rmSync(FEED, { force: true, recursive: true });publish('v1', { seq: manifestOf('v1').seq, version: manifestOf('v1').version });- // buildCore writes core/<platform>; the client reads <channel>/core/<platform> (S3 adds the channel prefix).- symlinkSync('.', path.join(FEED, CHANNEL));console.log(`v1 app: ${APP}`);},diff --git a/apps/desktop/scripts/core-ota-test/serve.mjs b/apps/desktop/scripts/core-ota-test/serve.mjsindex b39bb02148a..88ffa059519 100644--- a/apps/desktop/scripts/core-ota-test/serve.mjs+++ b/apps/desktop/scripts/core-ota-test/serve.mjs@@ -6,6 +6,7 @@ const root = path.resolve(process.argv[2] ?? 'release/core-ota');const port = Number(process.argv[3] ?? 8787);const contentType = (pathname) => {+ if (pathname.endsWith('.pack')) return 'application/octet-stream';if (pathname.endsWith('.zip')) return 'application/zip';if (pathname.endsWith('.zst')) return 'application/zstd';return 'application/json';@@ -20,13 +21,29 @@ const server = http.createServer((req, res) => {return;}const immutable = url.pathname.startsWith('/cas/') || url.pathname.includes('/packs/');- res.writeHead(200, {+ const size = statSync(file).size;+ let start = 0;+ let end = size - 1;+ let status = 200;+ if (req.headers.range) {+ const match = /^bytes=(\d+)-(\d+)$/.exec(req.headers.range);+ if (!match || Number(match[1]) > Number(match[2]) || Number(match[2]) >= size) {+ res.writeHead(416, { 'content-range': `bytes */${size}` }).end();+ return;+ }+ start = Number(match[1]);+ end = Number(match[2]);+ status = 206;+ }+ res.writeHead(status, {+ 'accept-ranges': 'bytes','cache-control': immutable ? 'public,max-age=31536000,immutable' : 'no-store',- 'content-length': statSync(file).size,+ 'content-length': end - start + 1,'content-type': contentType(url.pathname),+ ...(status === 206 ? { 'content-range': `bytes ${start}-${end}/${size}` } : {}),});- createReadStream(file).pipe(res);- console.log(`200 ${url.pathname}`);+ createReadStream(file, { start, end }).pipe(res);+ console.log(`${status} ${url.pathname} bytes=${start}-${end}/${size}`);});server.listen(port, '127.0.0.1', () => {diff --git a/apps/desktop/scripts/core-ota-test/vitest.config.mjs b/apps/desktop/scripts/core-ota-test/vitest.config.mjsnew file mode 100644index 00000000000..41a5dcd74db--- /dev/null+++ b/apps/desktop/scripts/core-ota-test/vitest.config.mjs@@ -0,0 +1,10 @@+import { mergeConfig } from 'vitest/config';++import desktopConfig from '../../vitest.config.mts';++export default mergeConfig(desktopConfig, {+ test: {+ include: ['scripts/core-ota-test/*.integration.mjs'],+ testTimeout: 30_000,+ },+});diff --git a/apps/desktop/scripts/packBuiltinCore.mjs b/apps/desktop/scripts/packBuiltinCore.mjsnew file mode 100644index 00000000000..f51f2f56fb1--- /dev/null+++ b/apps/desktop/scripts/packBuiltinCore.mjs@@ -0,0 +1,17 @@+import { createRequire } from 'node:module';+import path from 'node:path';++// Reuse electron-builder's installed ASAR implementation.+const require = createRequire(import.meta.url);+const builder = createRequire(+ createRequire(require.resolve('electron-builder')).resolve('app-builder-lib'),+);+const { createPackageWithOptions } = builder('@electron/asar');++export async function packBuiltinCore(desktopDir) {+ await createPackageWithOptions(+ path.join(desktopDir, 'core-dist'),+ path.join(desktopDir, 'core.asar'),+ { unpackDir: 'cli' },+ );+}diff --git a/apps/desktop/scripts/shellAbi.mjs b/apps/desktop/scripts/shellAbi.mjsindex 1daa8669a16..f9694b67ff2 100644--- a/apps/desktop/scripts/shellAbi.mjs+++ b/apps/desktop/scripts/shellAbi.mjs@@ -11,6 +11,8 @@ const TRACKED_INPUTS = ['apps/desktop/shell','apps/desktop/build','apps/desktop/electron-builder.mjs',+ 'apps/desktop/scripts/packBuiltinCore.mjs',+ 'apps/desktop/scripts/assembleCore.mjs','apps/desktop/native-deps.config.mjs','apps/desktop/module-deps.config.mjs','apps/desktop/external-runtime-deps.config.mjs',diff --git a/apps/desktop/shell/__tests__/rescue.test.mjs b/apps/desktop/shell/__tests__/rescue.test.mjsindex 92faa25e517..f6667e2d778 100644--- a/apps/desktop/shell/__tests__/rescue.test.mjs+++ b/apps/desktop/shell/__tests__/rescue.test.mjs@@ -154,7 +154,7 @@ describe('rescue config', () => {])('stored %s with builtin %s resolves to %s', (stored, built, expected) => {if (stored) writeJson(path.join(userData, 'lobehub-settings.json'), { updateChannel: stored });if (built)- writeJson(path.join(process.resourcesPath, 'core', 'manifest.json'), { channel: built });+ writeJson(path.join(process.resourcesPath, 'core.asar', 'manifest.json'), { channel: built });expect(resolveChannel({ resourcesPath: process.resourcesPath, userData })).toBe(expected);});@@ -191,6 +191,23 @@ describe('rescue config', () => {});describe('runRescue', () => {+ it('checks the packaged canary feed before an update-channel setting exists', async () => {+ writeJson(path.join(process.resourcesPath, 'core.asar', 'manifest.json'), {+ channel: 'canary',+ });+ const electron = fakeElectron({ response: 2 });+ const updater = fakeUpdater({ check: async () => ({ isUpdateAvailable: false }) });++ await run(electron, updater);++ expect(updater.channel).toBe('canary');+ expect(updater.setFeedURL).toHaveBeenCalledWith({+ provider: 'generic',+ url: 'https://releases.example.com/canary',+ });+ expect(updater.checkForUpdates).toHaveBeenCalledOnce();+ });+it('downloads and installs an available update', async () => {const electron = fakeElectron();const updater = fakeUpdater({diff --git a/apps/desktop/shell/main.js b/apps/desktop/shell/main.jsindex a0cea7d5722..5c0a9e16d1d 100644--- a/apps/desktop/shell/main.js+++ b/apps/desktop/shell/main.js@@ -48,7 +48,7 @@ try {const { installShellResolver, resolveCore } = require('./core-loader');const builtinDir = app.isPackaged- ? path.join(process.resourcesPath, 'core')+ ? path.join(process.resourcesPath, 'core.asar'): path.join(__dirname, '..');const loadAbi = () => {@@ -84,6 +84,7 @@ try {abi: abi.shellAbi,builtinDir,coreDir: core.dir,+ coreProtocol: 4,log: core.log,manifest: core.manifest,markHealthy: core.markHealthy ?? (() => {}),diff --git a/apps/desktop/shell/rescue/index.js b/apps/desktop/shell/rescue/index.jsindex 8e3986d978b..25a9b8bd206 100644--- a/apps/desktop/shell/rescue/index.js+++ b/apps/desktop/shell/rescue/index.js@@ -15,7 +15,7 @@ const readJson = (file) => {const resolveChannel = ({ resourcesPath, userData }) => {const stored = readJson(path.join(userData, 'lobehub-settings.json'))?.updateChannel;if (stored != null) return stored === 'canary' ? 'canary' : 'stable';- const built = readJson(path.join(resourcesPath, 'core', 'manifest.json'))?.channel;+ const built = readJson(path.join(resourcesPath, 'core.asar', 'manifest.json'))?.channel;return built === 'canary' || built === 'beta' ? 'canary' : 'stable';};diff --git a/apps/desktop/src/main/const/shell.ts b/apps/desktop/src/main/const/shell.tsindex 84d29dfbbaa..529b411a57c 100644--- a/apps/desktop/src/main/const/shell.ts+++ b/apps/desktop/src/main/const/shell.ts@@ -4,6 +4,7 @@ export interface ShellGlobal {readonly abi: string;readonly builtinDir: string;readonly coreDir: string;+ readonly coreProtocol?: 4;readonly log: string[];readonly manifest: CoreManifest | null;readonly markHealthy: () => void;diff --git a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.tsindex 3dcbd05a2f3..9475be2c882 100644--- a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts@@ -107,6 +107,7 @@ describe('AuthCtr', () => {let mockWindow: any;beforeEach(() => {+ vi.useFakeTimers();vi.clearAllMocks();ipcMainHandleMock.mockClear();randomBytesCounter = 0; // Reset counter for each test@@ -132,15 +133,13 @@ describe('AuthCtr', () => {});afterEach(() => {- // Clean up authCtr intervals (using real timers, not fake timers)+ // Stop polling before restoring the real clock.authCtr?.cleanup?.();- // Clean up any fake timers if usedvi.clearAllTimers();+ vi.useRealTimers();});describe('Basic functionality', () => {- // Use real timers for all tests since setInterval with async doesn't work well with fake timers-describe('requestAuthorization', () => {it('should generate PKCE parameters and open authorization URL', async () => {const config: DataSyncConfig = {@@ -186,7 +185,7 @@ describe('AuthCtr', () => {expect(result.success).toBe(true);// Wait a bit for polling to start- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);// Verify fetch was called for pollingconst pollingCalls = mockFetch.mock.calls.filter((call) =>@@ -250,7 +249,7 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for first poll- await new Promise((resolve) => setTimeout(resolve, 3100));+ await vi.advanceTimersByTimeAsync(3100);const firstCallCount = mockFetch.mock.calls.filter((call) =>(call[0] as string).includes('/oidc/handoff'),@@ -258,13 +257,13 @@ describe('AuthCtr', () => {expect(firstCallCount).toBeGreaterThanOrEqual(1);// Wait for second poll- await new Promise((resolve) => setTimeout(resolve, 3000));+ await vi.advanceTimersByTimeAsync(3000);const secondCallCount = mockFetch.mock.calls.filter((call) =>(call[0] as string).includes('/oidc/handoff'),).length;expect(secondCallCount).toBeGreaterThanOrEqual(2);- }, 10000);+ });it('should stop polling when credentials are received', async () => {const config: DataSyncConfig = {@@ -330,14 +329,14 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for polling to complete- await new Promise((resolve) => setTimeout(resolve, 10000));+ await vi.advanceTimersByTimeAsync(10000);const pollCountBefore = pollCount;// Wait more time and verify no more polling- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);expect(pollCount).toBe(pollCountBefore);- }, 15000);+ });it('should broadcast authorizationSuccessful when credentials are exchanged', async () => {const config: DataSyncConfig = {@@ -394,11 +393,11 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for polling to complete and token exchange- await new Promise((resolve) => setTimeout(resolve, 4000));+ await vi.advanceTimersByTimeAsync(4000);// Verify authorizationSuccessful was broadcastexpect(mockWindow.webContents.send).toHaveBeenCalledWith('authorizationSuccessful');- }, 6000);+ });it('should validate state parameter and reject mismatched state', async () => {const config: DataSyncConfig = {@@ -432,13 +431,13 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for polling and state validation- await new Promise((resolve) => setTimeout(resolve, 4000));+ await vi.advanceTimersByTimeAsync(4000);// Verify authorizationFailed was broadcast with state errorexpect(mockWindow.webContents.send).toHaveBeenCalledWith('authorizationFailed', {error: 'Invalid state parameter',});- }, 6000);+ });});describe('token refresh', () => {@@ -497,7 +496,7 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for polling and token exchange- await new Promise((resolve) => setTimeout(resolve, 4000));+ await vi.advanceTimersByTimeAsync(4000);// Verify saveTokens was calledexpect(mockRemoteServerConfigCtr.saveTokens).toHaveBeenCalledWith(@@ -510,13 +509,11 @@ describe('AuthCtr', () => {expect(mockRemoteServerConfigCtr.setRemoteServerConfig).toHaveBeenCalledWith({active: true,});- }, 6000);+ });});});describe('Scenario: Authorization Timeout and Retry', () => {- // All scenario tests use real timers-it('Step 1: User requests authorization but does not complete it within 5 minutes', async () => {const config: DataSyncConfig = {active: false,@@ -533,21 +530,21 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for some polling to happen- await new Promise((resolve) => setTimeout(resolve, 10000));+ await vi.advanceTimersByTimeAsync(10000);const handoffCallsBeforeTimeout = mockFetch.mock.calls.filter((call) =>(call[0] as string).includes('/oidc/handoff'),).length;expect(handoffCallsBeforeTimeout).toBeGreaterThan(0);- // Verify polling is active by checking calls increased- const callsBefore = handoffCallsBeforeTimeout;- await new Promise((resolve) => setTimeout(resolve, 3500));- const callsAfter = mockFetch.mock.calls.filter((call) =>- (call[0] as string).includes('/oidc/handoff'),- ).length;- expect(callsAfter).toBeGreaterThan(callsBefore);- }, 15000); // Increase test timeout+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(mockWindow.webContents.send).toHaveBeenCalledWith('authorizationFailed', {+ error: 'Authorization timed out',+ });+ const callsAtTimeout = mockFetch.mock.calls.length;+ await vi.advanceTimersByTimeAsync(6000);+ expect(mockFetch).toHaveBeenCalledTimes(callsAtTimeout);+ });it('Step 2: User clicks retry button after previous attempt', async () => {const config: DataSyncConfig = {@@ -562,7 +559,7 @@ describe('AuthCtr', () => {// First attemptawait authCtr.requestAuthorization(config);- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);// Reset mock to track retrymockFetch.mockClear();@@ -571,13 +568,13 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Verify: New polling started- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);const handoffCalls = mockFetch.mock.calls.filter((call) =>(call[0] as string).includes('/oidc/handoff'),);expect(handoffCalls.length).toBeGreaterThan(0);- }, 10000);+ });it('Step 3: Retry generates new state parameter (not reusing old state)', async () => {const config: DataSyncConfig = {@@ -598,7 +595,7 @@ describe('AuthCtr', () => {// First authorization attemptawait authCtr.requestAuthorization(config);- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);const firstState = capturedStates[0];// Clear for second attempt tracking@@ -607,7 +604,7 @@ describe('AuthCtr', () => {// Retry - should generate NEW stateawait authCtr.requestAuthorization(config);- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);const secondState = capturedStates[0];// CRITICAL: States must be different@@ -615,7 +612,7 @@ describe('AuthCtr', () => {expect(secondState).toBeDefined();expect(secondState).not.toBe(firstState);expect(firstAttemptStates).not.toContain(secondState);- }, 10000);+ });it('Step 4: User completes authorization on retry successfully', async () => {const config: DataSyncConfig = {@@ -626,7 +623,7 @@ describe('AuthCtr', () => {// First attempt - incompletemockFetch.mockResolvedValue({ status: 404, ok: false });await authCtr.requestAuthorization(config);- await new Promise((resolve) => setTimeout(resolve, 3500));+ await vi.advanceTimersByTimeAsync(3500);// Second attempt - user completes it this timemockFetch.mockImplementation((url: string) => {@@ -680,7 +677,7 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait longer for polling and token exchange- await new Promise((resolve) => setTimeout(resolve, 4000));+ await vi.advanceTimersByTimeAsync(4000);// Verify: Success message shownconst successCall = mockWindow.webContents.send.mock.calls.find(@@ -690,7 +687,7 @@ describe('AuthCtr', () => {// Verify: Tokens savedexpect(mockRemoteServerConfigCtr.saveTokens).toHaveBeenCalled();- }, 12000);+ });it('Edge case: Rapid retry clicks should not create multiple polling intervals', async () => {const config: DataSyncConfig = {@@ -706,17 +703,16 @@ describe('AuthCtr', () => {await authCtr.requestAuthorization(config);// Wait for some polling to happen- await new Promise((resolve) => setTimeout(resolve, 9000));+ await vi.advanceTimersByTimeAsync(9000);// Count handoff requestsconst handoffCalls = mockFetch.mock.calls.filter((call) =>(call[0] as string).includes('/oidc/handoff'),);- // Should have ~3 calls (one per 3-second interval), not ~9 (3 intervals running)- // Allow some tolerance for timing- expect(handoffCalls.length).toBeLessThanOrEqual(5);- }, 10000);+ // Exactly one active interval: one request per 3 seconds.+ expect(handoffCalls).toHaveLength(3);+ });});describe('Proactive Token Refresh', () => {@@ -823,7 +819,7 @@ describe('AuthCtr', () => {vi.mocked(mockRemoteServerConfigCtr.isTokenExpiringSoon).mockReturnValue(true);authCtr.afterAppReady();- await new Promise((resolve) => setTimeout(resolve, 100));+ await vi.advanceTimersByTimeAsync(100);expect(mockRemoteServerConfigCtr.refreshAccessToken).toHaveBeenCalled();});@@ -832,7 +828,7 @@ describe('AuthCtr', () => {vi.mocked(mockRemoteServerConfigCtr.isTokenExpiringSoon).mockReturnValue(false);authCtr.afterAppReady();- await new Promise((resolve) => setTimeout(resolve, 100));+ await vi.advanceTimersByTimeAsync(100);expect(mockRemoteServerConfigCtr.refreshAccessToken).not.toHaveBeenCalled();});@@ -841,7 +837,7 @@ describe('AuthCtr', () => {vi.mocked(mockRemoteServerConfigCtr.isTokenExpiringSoon).mockReturnValue(false);authCtr.afterAppReady();- await new Promise((resolve) => setTimeout(resolve, 100));+ await vi.advanceTimersByTimeAsync(100);const [buffer] = vi.mocked(mockRemoteServerConfigCtr.isTokenExpiringSoon).mock.calls[0];expect(buffer).toBeGreaterThan(0);@@ -853,7 +849,7 @@ describe('AuthCtr', () => {vi.mocked(mockRemoteServerConfigCtr.isTokenExpiringSoon).mockReturnValue(true);authCtr.afterAppReady();- await new Promise((resolve) => setTimeout(resolve, 100));+ await vi.advanceTimersByTimeAsync(100);expect(mockRemoteServerConfigCtr.refreshAccessToken).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 0b2e8707da1..91a375f4274 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -856,6 +856,7 @@ describe('HeterogeneousAgentCtr', () => {});afterEach(async () => {+ vi.useRealTimers();if (originalClaudeSdkLabEnv === undefined) delete process.env.LOBE_CLAUDE_CODE_SDK;else process.env.LOBE_CLAUDE_CODE_SDK = originalClaudeSdkLabEnv;if (originalCodexAppServerLabEnv === undefined) delete process.env.LOBE_CODEX_APP_SERVER;@@ -1345,6 +1346,11 @@ describe('HeterogeneousAgentCtr', () => {systemContext: string;}> = {},) => {+ // These argv/stream fixtures need no wall-clock session-completion grace.+ if (!vi.isFakeTimers()) {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ vi.setTimerTickMode('nextTimerAsync');+ }const { proc, writes } = createFakeProc({ stdoutLines });nextFakeProc = proc;@@ -2632,6 +2638,11 @@ describe('HeterogeneousAgentCtr', () => {}> = {},storeGet?: (key: string, defaultValue?: any) => any,) => {+ // These argv/stream fixtures need no wall-clock session-completion grace.+ if (!vi.isFakeTimers()) {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ vi.setTimerTickMode('nextTimerAsync');+ }const { proc, writes } = createFakeProc({ stdoutLines });nextFakeProc = proc;diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.tsindex 2fdcf83042f..b95017a25a3 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts@@ -1,8 +1,10 @@import { createHash } from 'node:crypto';import { existsSync, readFileSync, rmSync } from 'node:fs';+import { readFile } from 'node:fs/promises';import path from 'node:path';import type { UpdateChannel } from '@lobechat/electron-client-ipc';+import { readBlobWithLimit } from '@lobechat/utils/imageToBase64';import { app as electronApp, BrowserWindow, net } from 'electron';import { type ShellGlobal, shellInfo } from '@/const/shell';@@ -22,13 +24,7 @@ import {coreManifestSchema,verifyManifestSignature,} from './manifest';-import {- type CorePointer,- emptyPointer,- readPointer,- readPointerAbi,- writePointer,-} from './pointer';+import { type CorePointer, emptyPointer, readPointer, writePointer } from './pointer';import { cleanupLegacy, CoreStore } from './store';const logger = createLogger('core:CoreUpdateManager');@@ -101,8 +97,8 @@ export class CoreUpdateManager {options.fetchImpl ??((url, init) => net.fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT), ...init }));this.otaRoot = path.join(electronApp.getPath('userData'), 'core-ota');- this.store = new CoreStore(this.otaRoot, (url) =>- this.fetchImpl(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT) }),+ this.store = new CoreStore(this.otaRoot, (url, init) =>+ this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT) }),);this.builtinManifest = this.shell ? readBuiltinManifest(this.shell) : null;this.activeChannel = this.coreChannel(@@ -151,12 +147,11 @@ export class CoreUpdateManager {cleanupLegacy(electronApp.getPath('userData')).catch((error) =>logger.warn('Legacy renderer OTA cleanup failed:', error),);- const abiChanged = readPointerAbi(this.otaRoot) !== this.shell!.abi;const stored = readPointer(this.otaRoot, this.shell!.abi);this.pointer = { ...this.reconcilePointer(stored), channel: this.activeChannel };writePointer(this.otaRoot, this.pointer);logger.info('Core OTA boot state', this.pointer);- this.gc(abiChanged);+ this.gc();};private reconcilePointer(pointer: CorePointer): CorePointer {@@ -329,13 +324,27 @@ export class CoreUpdateManager {if (!this.inRollout(version, remote.rollout)) throw new SkipCheck('rollout-excluded');await this.gcTask;+ let current =+ this.shell!.source === 'external'+ ? { dir: this.shell!.coreDir, manifest: this.running }+ : null;+ if (this.pointer.current && this.pointer.current !== this.runningVersion) {+ try {+ const dir = this.coreDirOf(this.pointer.current);+ current = {+ dir,+ manifest: coreManifestSchema.parse(+ JSON.parse(await readFile(path.join(dir, 'manifest.json'), 'utf8')),+ ),+ };+ } catch (error) {+ logger.warn('Cannot reuse active renderer core', error);+ }+ }const staged = await this.store.stage({builtin: { dir: this.shell!.builtinDir, manifest: this.builtinManifest! },- current:- this.shell!.source === 'external'- ? { dir: this.shell!.coreDir, manifest: this.running }- : null,- objectsBaseUrl: remote.objectsBaseUrl,+ current,+ objectsBaseUrl: remote.schemaVersion === 3 ? remote.objectsBaseUrl : undefined,packsBaseUrl: feedUrl,remote,});@@ -384,9 +393,13 @@ export class CoreUpdateManager {const res = await this.fetchImpl(`${feedUrl}/latest.json`, { cache: 'no-store' });if (res.status === 404) throw new SkipCheck('feed-not-found');if (!res.ok) throw new Error(`Manifest fetch failed: ${res.status}`);- const parsed = coreManifestSchema.safeParse(await res.json());+ const parsed = coreManifestSchema.safeParse(+ JSON.parse(await (await readBlobWithLimit(res, 16 * 1024 ** 2)).text()),+ );if (!parsed.success) throw new Error('Manifest shape invalid');const remote = parsed.data;+ if (this.shell?.coreProtocol === 4 && remote.schemaVersion !== 4)+ throw new Error('Expected v4 manifest');if (!verifyManifestSignature(remote, this.shell!.publicKey)) {throw new Error('Manifest signature invalid');}@@ -409,7 +422,11 @@ export class CoreUpdateManager {}private feedUrl() {- return `${FEED_BASE_URL}/${this.activeChannel}/core/${process.platform}`;+ const prefix =+ this.shell?.coreProtocol === 4+ ? `${encodeURIComponent(this.shell.shellVersion)}/core-v4`+ : 'core';+ return `${FEED_BASE_URL}/${this.activeChannel}/${prefix}/${process.platform}`;}private coreDirOf(version: string) {@@ -519,9 +536,9 @@ export class CoreUpdateManager {});}- private gc(keepStore = false) {+ private gc() {this.gcTask = this.gcTask- .then(() => this.store.gc(this.keepVersions, { keepStore }))+ .then(() => this.store.gc(this.keepVersions)).catch((error) => logger.warn('Core OTA gc failed:', error));}}diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.tsindex 2db026262bf..322635b86a5 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts@@ -17,7 +17,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ShellGlobal } from '@/const/shell';-import { canonicalJson, type CoreManifest, sha256File } from '../manifest';+import { canonicalJson, type CoreManifestV3 as CoreManifest, sha256File } from '../manifest';import { readPointer, writePointer } from '../pointer';import { SAFE_VERSION } from '../store';@@ -266,15 +266,41 @@ describe('CoreUpdateManager initialize', () => {expect(existsSync(coreDir('0.9.0'))).toBe(false);});- it('keeps store objects across an abi reset', async () => {+ it('removes old OTA cache after a full release without touching app data', async () => {mkdirSync(storeDir(), { recursive: true });writeFileSync(path.join(storeDir(), 'f'.repeat(64)), 'blob');- pointerAt({ abi: 'b'.repeat(64) } as never);+ pointerAt({+ abi: 'b'.repeat(64),+ current: 'old',+ previous: 'older',+ staged: 'pending',+ } as never);+ for (const dir of [+ 'core-ota/cores/old',+ 'core-ota/cores/older',+ 'core-ota/cores/pending',+ 'core-ota/staging',+ 'renderer-ota',+ 'renderer-ota-v2',+ ]) {+ mkdirSync(path.join(userDataDir, dir), { recursive: true });+ writeFileSync(path.join(userDataDir, dir, 'old-file'), 'old OTA bytes');+ }+ writeFileSync(path.join(userDataDir, 'app-data.json'), 'keep app data');await loadManager();await flushGc();- expect(existsSync(path.join(storeDir(), 'f'.repeat(64)))).toBe(true);+ expect(existsSync(path.join(storeDir(), 'f'.repeat(64)))).toBe(false);+ expect(readdirSync(path.join(otaRoot(), 'cores'))).toEqual([]);+ for (const dir of ['core-ota/staging', 'renderer-ota', 'renderer-ota-v2'])+ expect(existsSync(path.join(userDataDir, dir))).toBe(false);+ expect(readPointer(otaRoot(), ABI)).toMatchObject({+ current: null,+ previous: null,+ staged: null,+ });+ expect(readFileSync(path.join(userDataDir, 'app-data.json'), 'utf8')).toBe('keep app data');});it('clears pointer.current when the shell fell back to builtin and the core dir is gone', async () => {@@ -454,6 +480,25 @@ describe('CoreUpdateManager initialize', () => {});describe('CoreUpdateManager checkForUpdates', () => {+ it.each(['1.0.0', '2.0.0-canary.1'])(+ 'isolates v4 feed by shell version %s even when an OTA core is running',+ async (shellVersion) => {+ const manifest = mainChanged('1.0.0-core.17', 17);+ // A shared or another application's feed must never be used as a fallback.+ served.set(`${SERVER}/stable/core-v4/${PLATFORM}/latest.json`, Buffer.from('{}'));+ const { manager } = await loadManager(+ makeApp(),+ makeShell({ coreProtocol: 4, manifest, shellVersion, source: 'external' }),+ );+ await manager.checkForUpdates();+ expect(fetchImpl).toHaveBeenCalledExactlyOnceWith(+ `${SERVER}/stable/${shellVersion}/core-v4/${PLATFORM}/latest.json`,+ { cache: 'no-store' },+ );+ expect(manager.getStatus().lastError).toBeNull();+ },+ );+it('is up-to-date when remote seq does not increase', async () => {serveLatest(rendererOnly('1.0.1', 0));const { app, manager } = await loadManager();@@ -558,6 +603,32 @@ describe('CoreUpdateManager checkForUpdates', () => {expect(reload).toHaveBeenCalledTimes(1);});+ it('reuses the active renderer version after a reload even without its object cache', async () => {+ serveLatest(rendererOnly('1.0.1', 1));+ const { manager } = await loadManager();+ await manager.checkForUpdates();+ manager.applyStagedNow();+ manager.handleBootPing('mounted');+ rmSync(storeDir(), { recursive: true, force: true });+ const reused = 'index-1.0.1';+ serveLatest(+ buildManifest('1.0.5', 5, {+ ...BASE_FILES,+ 'dist/renderer/assets/index.js': reused,+ 'dist/renderer/assets/extra.js': 'new',+ }),+ );+ fetchImpl.mockClear();+ await manager.checkForUpdates();+ expect(manager.getStatus().staged).toBe('1.0.5');+ expect(+ fetchImpl.mock.calls.some(([url]) => url.includes(sha256File(Buffer.from(reused)))),+ ).toBe(false);+ expect(readFileSync(path.join(coreDir('1.0.5'), 'dist/renderer/assets/index.js'), 'utf8')).toBe(+ reused,+ );+ });+it('re-announces an already staged core on a manual check', async () => {serveLatest(rendererOnly('1.0.1', 1));const { app, manager } = await loadManager();diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.tsindex 4b84b1d7714..732d73e7a57 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts@@ -8,7 +8,7 @@ import { constants, zstdCompressSync } from 'node:zlib';import { zipSync } from 'fflate';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { type CoreManifest, sha256File } from '../manifest';+import { type CoreManifestV3 as CoreManifest, sha256File } from '../manifest';import { cleanupLegacy, CoreStore, indexLocal, isSafeVersion } from '../store';vi.mock('node:fs/promises', async (importOriginal) => {diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.tsindex 359f55738aa..c8020abf857 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts@@ -49,7 +49,7 @@ export const corePatchSchema = z}).strict();-export const coreManifestSchema = z+export const coreManifestV3Schema = z.object({applyMode: z.enum(['reload', 'relaunch']).nullable(),channel: z.enum(['stable', 'beta', 'canary', 'nightly']),@@ -69,9 +69,87 @@ export const coreManifestSchema = z.strict();// The builtin manifest ships inside the code-signed app bundle, so it is built without the OTA key.-export const builtinManifestSchema = coreManifestSchema.extend({ signature: z.string() });+export const builtinManifestSchema = coreManifestV3Schema.extend({ signature: z.string() });-export type CoreManifest = z.infer<typeof coreManifestSchema>;+const packSchema = z+ .object({+ path: z.string().regex(/^packs\/[0-9a-f]{64}\.pack$/),+ sha256: sha256Schema,+ size: z+ .number()+ .int()+ .positive()+ .max(8 * 1024 ** 3),+ })+ .strict()+ .refine((pack) => pack.path === `packs/${pack.sha256}.pack`);++const frameSchema = z+ .object({+ compressedSha256: sha256Schema,+ length: z+ .number()+ .int()+ .positive()+ .max(256 * 1024 ** 2),+ offset: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),+ packSha256: sha256Schema,+ })+ .strict();++export const coreManifestV4Schema = coreManifestV3Schema+ .omit({+ full: true,+ objectsBaseUrl: true,+ patches: true,+ schemaVersion: true,+ })+ .extend({+ objects: z.record(sha256Schema, frameSchema),+ packs: z.array(packSchema).min(1).max(2),+ patches: z.array(frameSchema.extend({ fromSha256: sha256Schema, toSha256: sha256Schema })),+ schemaVersion: z.literal(4),+ })+ .strict()+ .superRefine((manifest, ctx) => {+ const bad = (message: string) => ctx.addIssue({ code: 'custom', message });+ const packs = new Map(manifest.packs.map((pack) => [pack.sha256, pack]));+ if (packs.size !== manifest.packs.length) bad('Duplicate pack');+ const sizes = new Map<string, number>();+ for (const file of manifest.tree) {+ if (!manifest.objects[file.sha256]) bad(`Missing object ${file.sha256}`);+ if (file.size > 256 * 1024 ** 2 || !Number.isSafeInteger(file.size)) bad('File too large');+ if (sizes.has(file.sha256) && sizes.get(file.sha256) !== file.size) bad('Conflicting sizes');+ sizes.set(file.sha256, file.size);+ }+ if (Object.keys(manifest.objects).some((hash) => !sizes.has(hash))) bad('Unreferenced object');+ if (new Set(Object.values(manifest.objects).map((frame) => frame.packSha256)).size !== 1)+ bad('Objects must share one pack');+ for (const patch of manifest.patches) {+ if (!sizes.has(patch.toSha256)) bad('Patch target missing');+ }+ const frames = [...Object.values(manifest.objects), ...manifest.patches].sort(+ (a, b) => a.packSha256.localeCompare(b.packSha256) || a.offset - b.offset,+ );+ let previous: (typeof frames)[number] | undefined;+ for (const frame of frames) {+ const pack = packs.get(frame.packSha256);+ const end = frame.offset + frame.length;+ if (!pack || !Number.isSafeInteger(end) || end > pack.size) bad('Frame outside pack');+ if (+ previous?.packSha256 === frame.packSha256 &&+ previous.offset + previous.length > frame.offset+ )+ bad('Overlapping frames');+ previous = frame;+ }+ });++export const coreManifestSchema = z.union([coreManifestV3Schema, coreManifestV4Schema]);+export type CoreManifestV3 = z.infer<typeof coreManifestV3Schema>;+export type CoreManifestV4 = z.infer<typeof coreManifestV4Schema>;+export type CoreManifest = CoreManifestV3 | CoreManifestV4;+export type PackFrame = z.infer<typeof frameSchema>;export type CorePatch = z.infer<typeof corePatchSchema>;export type RendererArtifact = z.infer<typeof rendererArtifactSchema>;export type RendererTreeFile = z.infer<typeof rendererTreeFileSchema>;diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/pack.ts b/apps/desktop/src/main/core/infrastructure/coreOta/pack.tsnew file mode 100644index 00000000000..d54f067e849--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/coreOta/pack.ts@@ -0,0 +1,301 @@+import { createHash } from 'node:crypto';+import { mkdtemp, open, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';+import { zstdDecompress } from 'node:zlib';++import type { CoreManifestV4, PackFrame } from './manifest';+import { sha256File } from './manifest';++const decompress = promisify(zstdDecompress);+const CONCURRENCY = 8;+const MAX_RANGE = 16 * 1024 ** 2;++interface Transfer extends PackFrame {+ fromSha256?: string;+ toSha256: string;+}+interface Range {+ end: number;+ frames: Transfer[];+ offset: number;+ packSha256: string;+}+interface Timing {+ bytesPerSecond: number;+ latency: number;+}+// ponytail: cold-start estimates, replace with measured defaults when deployment benchmarks exist.+const COLD_TIMING: Timing = { bytesPerSecond: 4 * 1024 ** 2, latency: 0.15 };++const cost = (ranges: Range[], timing: Timing) =>+ ranges.reduce((sum, range) => sum + range.end - range.offset, 0) / timing.bytesPerSecond ++ Math.ceil(ranges.length / CONCURRENCY) * timing.latency;++export function planPackDownload(+ manifest: CoreManifestV4,+ missing: string[],+ local: Map<string, string>,+ timing = COLD_TIMING,+): { full: boolean; ranges: Range[] } {+ if (!missing.length) return { full: false, ranges: [] };+ const objects = missing.map((toSha256) => ({ ...manifest.objects[toSha256], toSha256 }));+ const patches = new Map<string, Transfer>();+ for (const patch of manifest.patches) {+ if (+ local.has(patch.fromSha256) &&+ patch.length <+ (patches.get(patch.toSha256)?.length ?? manifest.objects[patch.toSha256].length)+ )+ patches.set(patch.toSha256, patch);+ }+ const merge = (frames: Transfer[]) => {+ const ranges: Range[] = [];+ for (const frame of frames.sort(+ (a, b) => a.packSha256.localeCompare(b.packSha256) || a.offset - b.offset,+ )) {+ const last = ranges.at(-1);+ const end = frame.offset + frame.length;+ const gap = last ? frame.offset - last.end : Infinity;+ if (+ last?.packSha256 === frame.packSha256 &&+ end - last.offset <= MAX_RANGE &&+ gap <= (timing.bytesPerSecond * timing.latency) / CONCURRENCY+ ) {+ last.end = end;+ last.frames.push(frame);+ } else+ ranges.push({ end, frames: [frame], offset: frame.offset, packSha256: frame.packSha256 });+ }+ return ranges;+ };+ const candidates = [+ { full: false, ranges: merge([...objects]) },+ { full: false, ranges: merge(objects.map((frame) => patches.get(frame.toSha256) ?? frame)) },+ {+ full: true,+ ranges: [+ {+ end: manifest.packs.find((pack) => pack.sha256 === objects[0].packSha256)!.size,+ frames: objects,+ offset: 0,+ packSha256: objects[0].packSha256,+ },+ ],+ },+ ];+ return candidates.sort(+ (a, b) => cost(a.ranges, timing) - cost(b.ranges, timing) || Number(b.full) - Number(a.full),+ )[0];+}++export type PackFetch = (url: string, init?: RequestInit) => Promise<Response>;++export class PackDownloader {+ private timing = COLD_TIMING;++ constructor(private readonly fetchImpl: PackFetch) {}++ async download(+ manifest: CoreManifestV4,+ missing: string[],+ local: Map<string, string>,+ baseUrl: string,+ put: (sha256: string, content: Buffer) => Promise<void>,+ ) {+ const plan = planPackDownload(manifest, missing, local, this.timing);+ const downloaded = { bytes: 0, objects: 0, patches: 0 };+ if (!missing.length) return { downloaded, fallbackFull: false };+ const temp = await mkdtemp(path.join(tmpdir(), 'core-pack-'));+ const packs = new Map(manifest.packs.map((pack) => [pack.sha256, pack]));+ const sizes = new Map(manifest.tree.map((file) => [file.sha256, file.size]));+ const fullDownloads = new Map<string, Promise<string>>();+ const failedPatches = new Set<string>();+ let serial = 0;+ let usedFull = plan.full;++ const save = async (response: Response, expected: number, packHash?: string) => {+ const filename = path.join(temp, String(serial++));+ const file = await open(filename, 'wx', 0o600);+ const digest = createHash('sha256');+ const reader = response.body?.getReader();+ let received = 0;+ try {+ if (!reader) throw new Error('Missing pack response body');+ const length = response.headers.get('content-length');+ if (length !== null && Number(length) !== expected)+ throw new Error('Pack Content-Length mismatch');+ if (+ response.headers.get('content-encoding') &&+ response.headers.get('content-encoding') !== 'identity'+ )+ throw new Error('Encoded pack response');+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ received += value.byteLength;+ downloaded.bytes += value.byteLength;+ if (received > expected) throw new Error('Oversized pack response');+ digest.update(value);+ let offset = 0;+ while (offset < value.length) {+ const { bytesWritten } = await file.write(value, offset, value.length - offset);+ if (!bytesWritten) throw new Error('Pack write stalled');+ offset += bytesWritten;+ }+ }+ if (received !== expected) throw new Error('Truncated pack response');+ if (packHash && digest.digest('hex') !== packHash) throw new Error('Pack hash mismatch');+ return filename;+ } finally {+ await reader?.cancel().catch(() => {});+ await file.close();+ }+ };+ const fetchRange = async (+ range: Range,+ full: boolean,+ ): Promise<{ file: string; start: number }> => {+ const pack = packs.get(range.packSha256)!;+ const url = `${baseUrl}/${pack.path}`;+ const getFull = () => {+ if (!fullDownloads.has(pack.sha256))+ fullDownloads.set(+ pack.sha256,+ (async () => {+ usedFull = true;+ const response = await this.fetchImpl(url);+ if (response.status !== 200) {+ await response.body?.cancel();+ throw new Error(`Pack HTTP ${response.status}`);+ }+ return save(response, pack.size, pack.sha256);+ })().catch((error) => {+ fullDownloads.delete(pack.sha256);+ throw error;+ }),+ );+ return fullDownloads.get(pack.sha256)!;+ };+ if (full) return { file: await getFull(), start: 0 };+ const started = performance.now();+ const response = await this.fetchImpl(url, {+ headers: { Range: `bytes=${range.offset}-${range.end - 1}` },+ });+ const latency = (performance.now() - started) / 1000;+ if (response.status === 200) {+ await response.body?.cancel();+ return { file: await getFull(), start: 0 };+ }+ if (+ response.status !== 206 ||+ response.headers.get('content-range') !==+ `bytes ${range.offset}-${range.end - 1}/${pack.size}`+ ) {+ await response.body?.cancel();+ throw new Error(`Invalid pack Range response (${response.status})`);+ }+ const file = await save(response, range.end - range.offset);+ const seconds = (performance.now() - started) / 1000 - latency;+ if (seconds > 0)+ this.timing = {+ bytesPerSecond: Math.max(1024, (range.end - range.offset) / seconds),+ latency: Math.max(0.001, latency),+ };+ return { file, start: range.offset };+ };+ const execute = async (range: Range, full: boolean) => {+ let result: Awaited<ReturnType<typeof fetchRange>> | undefined;+ try {+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ result = await fetchRange(range, full);+ break;+ } catch (error) {+ if (attempt === 1) throw error;+ }+ }+ } catch (error) {+ if (range.frames.every((frame) => frame.fromSha256)) {+ for (const frame of range.frames) failedPatches.add(frame.toSha256);+ return;+ }+ throw error;+ }+ const file = await open(result!.file, 'r');+ try {+ for (const frame of range.frames) {+ try {+ const raw = Buffer.alloc(frame.length);+ let offset = 0;+ while (offset < raw.length) {+ const { bytesRead } = await file.read(+ raw,+ offset,+ raw.length - offset,+ frame.offset - result!.start + offset,+ );+ if (!bytesRead) throw new Error('Truncated frame');+ offset += bytesRead;+ }+ if (sha256File(raw) !== frame.compressedSha256) throw new Error('Frame hash mismatch');+ const dictionary = frame.fromSha256+ ? await readFile(local.get(frame.fromSha256)!)+ : undefined;+ if (dictionary && sha256File(dictionary) !== frame.fromSha256)+ throw new Error('Patch base changed');+ const bytes = Buffer.from(+ await decompress(raw, {+ dictionary,+ maxOutputLength: Math.max(1, sizes.get(frame.toSha256)!),+ }),+ );+ if (bytes.length !== sizes.get(frame.toSha256) || sha256File(bytes) !== frame.toSha256)+ throw new Error('Content mismatch');+ await put(frame.toSha256, bytes);+ downloaded[frame.fromSha256 ? 'patches' : 'objects'] += 1;+ } catch (error) {+ if (!frame.fromSha256) throw error;+ failedPatches.add(frame.toSha256);+ }+ }+ } finally {+ await file.close();+ }+ };+ const run = async (ranges: Range[], full: boolean) => {+ let next = 0;+ let failed = false;+ const results = await Promise.allSettled(+ Array.from({ length: Math.min(CONCURRENCY, ranges.length) }, async () => {+ while (!failed && next < ranges.length) {+ try {+ await execute(ranges[next++], full);+ } catch (error) {+ failed = true;+ throw error;+ }+ }+ }),+ );+ const rejected = results.find((result) => result.status === 'rejected');+ if (rejected?.status === 'rejected') throw rejected.reason;+ };+ try {+ await run(plan.ranges, plan.full);+ if (failedPatches.size) {+ const retry = planPackDownload(+ { ...manifest, patches: [] },+ [...failedPatches],+ local,+ this.timing,+ );+ await run(retry.ranges, retry.full);+ }+ return { downloaded, fallbackFull: usedFull };+ } finally {+ await rm(temp, { force: true, recursive: true });+ }+ }+}diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/pointer.ts b/apps/desktop/src/main/core/infrastructure/coreOta/pointer.tsindex 43e79b54c48..f631a4965f9 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/pointer.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/pointer.ts@@ -32,11 +32,6 @@ const readRaw = (otaRoot: string) => {}};-export const readPointerAbi = (otaRoot: string): string | null => {- const abi = readRaw(otaRoot)?.abi;- return typeof abi === 'string' ? abi : null;-};-export const readPointer = (otaRoot: string, abi: string): CorePointer => {const raw = readRaw(otaRoot);if (raw?.abi === abi) {diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts b/apps/desktop/src/main/core/infrastructure/coreOta/store.tsindex cf3bf8760db..686a3139719 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/store.ts@@ -1,5 +1,15 @@import { existsSync } from 'node:fs';-import { copyFile, link, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';+import {+ copyFile,+ link,+ mkdir,+ readdir,+ readFile,+ rename,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';import { zstdDecompress } from 'node:zlib';@@ -9,16 +19,17 @@ import { unzip } from 'fflate';import { createLogger } from '@/utils/logger';import { type CoreManifest, findMissingEntryAssets, sha256File } from './manifest';+import { PackDownloader, type PackFetch } from './pack';import { applyZstdPatch } from './zstdPatch';const logger = createLogger('core:CoreStore');-type FetchImpl = (url: string) => Promise<Response>;+type FetchImpl = PackFetch;type LocalCore = { dir: string; manifest: CoreManifest };type StageInput = {builtin: LocalCore;current: LocalCore | null;- objectsBaseUrl: string;+ objectsBaseUrl?: string;packsBaseUrl: string;remote: CoreManifest;};@@ -118,6 +129,8 @@ export const cleanupLegacy = async (userData: string) => {};export class CoreStore {+ private active = false;+ private readonly packDownloader: PackDownloader;private readonly storeDir: string;private readonly coresDir: string;@@ -125,11 +138,22 @@ export class CoreStore {private readonly otaRoot: string,private readonly fetchImpl: FetchImpl,) {+ this.packDownloader = new PackDownloader(fetchImpl);this.storeDir = path.join(otaRoot, 'store');this.coresDir = path.join(otaRoot, 'cores');}- async stage({ builtin, current, objectsBaseUrl, packsBaseUrl, remote }: StageInput) {+ async stage(input: StageInput) {+ if (this.active) throw new Error('Core staging already active');+ this.active = true;+ try {+ return await this.stageCore(input);+ } finally {+ this.active = false;+ }+ }++ private async stageCore({ builtin, current, objectsBaseUrl, packsBaseUrl, remote }: StageInput) {if (!isSafeVersion(remote.version)) throw new Error(`Unsafe version: ${remote.version}`);await mkdir(this.storeDir, { mode: DIR_MODE, recursive: true });await mkdir(this.coresDir, { mode: DIR_MODE, recursive: true });@@ -138,6 +162,40 @@ export class CoreStore {...indexLocal(builtin.dir, builtin.manifest),...(current ? indexLocal(current.dir, current.manifest) : []),]);+ if (remote.schemaVersion === 4) {+ const expected = new Set([+ ...remote.tree.map((file) => file.sha256),+ ...remote.patches.map((patch) => patch.fromSha256),+ ]);+ await runPool([...expected], async (hash) => {+ const candidates = [byHash.get(hash), this.objectPath(hash)].filter(+ (file): file is string => !!file,+ );+ byHash.delete(hash);+ for (const source of candidates) {+ try {+ if ((await stat(source)).size > 256 * 1024 ** 2) continue;+ if (sha256File(await readFile(source)) === hash) {+ byHash.set(hash, source);+ break;+ }+ } catch {+ /* Missing local content is fetched from the target pack. */+ }+ }+ });+ const missing = [...new Set(remote.tree.map((file) => file.sha256))].filter(+ (hash) => !byHash.has(hash),+ );+ const result = await this.packDownloader.download(+ remote,+ missing,+ byHash,+ packsBaseUrl,+ (hash, bytes) => this.putObject(hash, bytes),+ );+ return { ...result, dir: await this.assemble(remote, byHash) } satisfies StageResult;+ }const missing = [...new Set(remote.tree.map((file) => file.sha256))].filter((sha256) => !byHash.has(sha256) && !existsSync(this.objectPath(sha256)),);@@ -193,7 +251,8 @@ export class CoreStore {return { dir, downloaded, fallbackFull } satisfies StageResult;}- async gc(keep: string[], { keepStore = false } = {}) {+ async gc(keep: string[]) {+ if (this.active) return;await rm(path.join(this.otaRoot, 'staging'), { force: true, recursive: true });const referenced = new Set<string>();for (const name of await readDirNames(this.coresDir)) {@@ -205,7 +264,6 @@ export class CoreStore {const manifest = await this.readManifest(dir);for (const file of manifest?.tree ?? []) referenced.add(file.sha256);}- if (keepStore) return;const unreferenced = (await readDirNames(this.storeDir)).filter((name) => !referenced.has(name),);@@ -247,11 +305,16 @@ export class CoreStore {const target = resolveInside(tmpDir, file.path);await mkdir(path.dirname(target), { mode: DIR_MODE, recursive: true });const source = byHash.get(file.sha256) ?? this.objectPath(file.sha256);- try {- await link(source, target);- } catch {- await copyFile(source, target);- }+ if (/\.asar[/\\]/.test(source)) {+ await writeFile(target, await readFile(source));+ } else+ try {+ await link(source, target);+ } catch {+ await copyFile(source, target);+ }+ if (remote.schemaVersion === 4 && sha256File(await readFile(target)) !== file.sha256)+ throw new Error(`Assembled file mismatch: ${file.path}`);});await writeFile(path.join(tmpDir, 'manifest.json'), JSON.stringify(remote));const rendererDir = path.join(tmpDir, RENDERER_ROOT);@@ -264,7 +327,17 @@ export class CoreStore {throw new Error(`Entry integrity check failed (${entry}): ${missing.join(', ')}`);}}- await rm(finalDir, { force: true, recursive: true });+ if (existsSync(finalDir)) {+ const existing = await this.readManifest(finalDir);+ if (JSON.stringify(existing) !== JSON.stringify(remote))+ throw new Error('Existing core version differs');+ for (const file of remote.tree) {+ if (sha256File(await readFile(resolveInside(finalDir, file.path))) !== file.sha256)+ throw new Error('Existing core version is corrupt');+ }+ await rm(tmpDir, { force: true, recursive: true });+ return finalDir;+ }await rename(tmpDir, finalDir);return finalDir;} catch (error) {diff --git a/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts b/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.tsindex e5f163b9912..c34b14651b0 100644--- a/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts+++ b/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts@@ -25,9 +25,13 @@ function resolveElectronBinary(): string {export function resolveCliScript(): string {if (app.isPackaged) {return path.join(- globalThis.__SHELL__?.coreDir ?? path.join(process.resourcesPath, 'core'),+ (globalThis.__SHELL__?.coreDir ?? path.join(process.resourcesPath, 'core.asar')).replace(+ /\.asar$/,+ '.asar.unpacked',+ ),'cli',- 'lobe-cli.js',+ 'dist',+ 'index.js',);}// Dev mode: app.getAppPath() points to apps/desktop/, go up to apps/cli/diff --git a/docs/development/desktop-core-asar-pack-ota-spec.md b/docs/development/desktop-core-asar-pack-ota-spec.mdnew file mode 100644index 00000000000..186f3eed6e0--- /dev/null+++ b/docs/development/desktop-core-asar-pack-ota-spec.md@@ -0,0 +1,261 @@+# Desktop 内置 ASAR 与 Pack Range OTA Spec++状态:已实现,本地打包态与真实 R2 测试桶验证通过;发布前待自定义域名 CDN、完整安装包与安装性能验收。v4 使用独立 feed;旧 v3 协议保留。++## 1. 目标与决策++将安装分发格式和 OTA 传输协议分开:++- 安装包内用小型 `app.asar` 引导器和 `core.asar` 业务归档,减少安装时的小文件创建。+- OTA 继续按文件内容哈希复用,保留已有文件级 Zstd 字典补丁能力。+- R2 使用不可变 `.pack`:将独立 Zstd frame 原样拼接,通过签名 manifest 记录偏移和长度。+- 客户端只下载缺失内容对应的 Range,在用户数据目录组装完整散文件版本。+- 不使用 ZIP,不对整个 ASAR 做二进制差分,不对整个 pack 再整体压缩。+- 跳级直接构建目标版本,不依赖中间版本或连续补丁链。+- 取消 “缺失对象超过 400 个就全量下载”;依据传输大小与合并后的请求数选择下载计划。++不在本次范围:运行时将 ASAR 与增量文件叠加为虚拟文件系统、修改正在使用的归档、跨版本全局 pack 去重服务、自定义归档压缩算法。++## 2. 改造前实现与问题++相关入口:++| 入口 | 当前行为 |+| ----------------------------------------------------- | --------------------------------------------------------------- |+| `apps/desktop/electron-builder.mjs` | `core-dist` 通过 `extraResources` 作为散文件进入安装包 |+| `apps/desktop/shell/main.js`、`core-loader.js` | 选择内置或外部 core,处理启动健康检查与回退 |+| `apps/desktop/scripts/buildCore.mjs` | 生成独立 `.zst` 对象、文件补丁和 ZIP 全量包 |+| `apps/desktop/scripts/buildCoreManifest.mjs` | 生成文件树及签名 manifest |+| `.github/actions/desktop-publish-core-ota/action.yml` | 用 `aws s3 sync --size-only` 上传 CAS 和全量包,最后发布 latest |+| `coreOta/manifest.ts` | schemaVersion 3,严格 schema |+| `coreOta/store.ts` | 按哈希复用,8 路并发,缺失超过 400 或下载失败时回退 ZIP |+| `coreOta/zstdPatch.ts` | 以旧文件为字典解压补丁 |+| `coreOta/CoreUpdateManager.ts` | 校验更新条件、ABI、灰度,决定 reload 或 relaunch |++上述 `coreOta/` 位于 `apps/desktop/src/main/core/infrastructure/`。++400 是请求数量兜底,不反映实际传输成本:401 个很小的文件也会触发全量下载。独立对象便于复用,但增加对象数量和发布请求开销。当前 sync 支持并发和跳过已有对象,不能将其描述为每次串行重传所有文件。++## 3. 安装与运行布局++```text+安装目录 / Resources+├── app.asar 引导器及其依赖+├── core.asar 内置业务 core 和 manifest+└── 外置运行资源 原生模块、CLI 或需真实路径的资源++用户数据目录 / core-ota+├── store/<sha256> 已校验、解压后的文件内容+├── cores/<version>/ 完整外部版本,散文件布局+├── pointer.json current / previous / staged+└── boot.json 启动健康状态+```++内置 manifest 的逻辑文件路径不因 ASAR 包装而变化。内置 core 的读取根改为 `core.asar`,Electron 通过 ASAR-aware 文件 API 读取内容。首次安装启动不先展开整个 core。++不能假设所有消费者都支持 ASAR。实施前必须核对主进程入口、preload、renderer 自定义协议、CLI wrapper、独立 Node 进程和子进程 `cwd`。需真实路径的资源保留外置,并显式定义其读取位置;不得把 CLI 或原生运行能力藏在首次启动全量解包中。++安装布局变化属于 shell 能力变化,通过完整应用发布交付,并纳入 shell ABI 输入。新的 shell 必须能验证 v4 manifest;旧 shell 不应被切换到无法理解的外部 core。++完整升级首次启动时,旧 ABI 的 OTA 指针失效,应用使用新的内置 core。启动 GC 删除旧 core 版本目录、staging 和未被保留版本引用的对象缓存;不再跨 ABI 保留缓存。已有 `renderer-ota` / `renderer-ota-v2` 目录也会清理。正在运行的外部 core 及 `current`、`previous`、`staged` 引用仍受保护,应用设置和业务数据不属于清理范围。++## 4. Pack 格式和 manifest v4++### 4.1 Pack 字节布局++```text+┌────────────────┬────────────────┬────────────────┐+│ 独立 Zstd A │ 独立 Zstd B │ 独立 Zstd C │+└────────────────┴────────────────┴────────────────┘+0 offset B offset C+```++pack 是字节容器,不内嵌文件系统,不要求客户端扫描 frame 边界。位置只由签名索引确定。每个 frame 可独立解码;文件补丁 frame 则要求精确的旧文件字典。++首版每个目标版本、平台提供一个包含全部唯一文件内容的 objects pack,按内容 SHA-256 排序。可选的 patches pack 按 `(fromSha256, toSha256)` 排序。固定压缩参数,不包含时间戳,保证相同输入可复现。++pack 使用自身完整字节的 SHA-256 命名,例如 `packs/<sha256>.pack`,不可原地覆盖。首版每次发布上传完整目标 objects pack:减少上传对象数量,但不承诺减少上传字节或跨版本远端存储量。不同版本的相同文件仍可能重复存储;客户端本地哈希复用不受影响。++### 4.2 签名数据++保留版本、channel、platform、seq、shellAbi、rollout、applyMode、tree 等语义,新增 v4 传输描述,替换 v3 的 ZIP `full` 和独立对象定位约定。++| 字段 | 内容 |+| --------------- | ------------------------------------------------------------------------------ |+| `schemaVersion` | `4` |+| `packs` | pack 描述列表:`sha256`、相对 `path`、完整 `size` |+| `objects` | 按内容哈希索引:`packSha256`、`offset`、`length`、`compressedSha256` |+| `patches` | `fromSha256`、`toSha256`、`packSha256`、`offset`、`length`、`compressedSha256` |+| `tree` | 每个逻辑文件的 `path`、解压后 `sha256`、解压后 `size` |++v4 中 objects 的编码固定为独立 Zstd,patches 固定为当前 Zstd 字典补丁,不增加不需要的可插拔编码机制。索引直接放在 manifest 中,并随所有定位信息一起参与现有 canonical JSON 签名。++必须满足:++- 每个 tree 内容哈希都有完整 object 描述;补丁只是优化,不能成为获取目标内容的唯一方式。+- 相同内容哈希只有一个 object frame,多个目标路径可以共享它。+- offset、length、size 为安全整数;offset 非负,length 为正,范围不可溢出或越过 pack。+- pack 引用必须存在,路径必须符合受限的相对路径格式;沿用可信更新源策略,不从未验证数据任意构造下载地址。+- frame 范围不重叠,解压后大小与 tree 声明一致;重复路径、非法路径、大小矛盾必须拒绝。+- 部分下载验证 `compressedSha256`,解码后验证内容 SHA-256 和大小。不能用完整 pack 哈希冒充片段校验。+- 完整下载额外验证 pack SHA-256。限制 manifest、响应、解压输出的资源消耗,不能先无限分配再检查大小。++## 5. 更新和跳级流程++```text+┌─────────────────────────────────┐+│ 验证目标 manifest、ABI、更新条件 │+└────────────────┬────────────────┘+ ▼+┌─────────────────────────────────┐+│ 建立内置 ASAR + 当前 core + 缓存 │+│ 的可复用内容索引 │+└────────────────┬────────────────┘+ ▼+┌─────────────────────────────────┐+│ 找出缺失内容,选择补丁或完整块 │+└────────────────┬────────────────┘+ ▼+┌─────────────────────────────────┐+│ 规划 Range / 全包下载并校验 │+└────────────────┬────────────────┘+ ▼+┌─────────────────────────────────┐+│ 组装临时目录,校验并标记 staged │+└────────────────┬────────────────┘+ ▼+┌─────────────────────────────────┐+│ 按现有 reload / relaunch 应用 │+│ 健康检查失败则回退 │+└─────────────────────────────────┘+```++以 v1 直接升级 v5 为例:++1. 只读取 v5 目标清单,不遍历 v2、v3、v4。+2. v5 文件哈希在 v1 内置 ASAR、当前外部版本或缓存中存在时直接复用。+3. 本地存在精确 `fromSha256`,且目标 manifest 提供适用补丁时,补丁参与下载计划;没有匹配字典则选择目标完整 object。+4. 所需完整 object 都能从 v5 objects pack 获得,因此缺少历史版本不会阻断更新。+5. 目标清单中已删除的路径不进入新目录;重命名但内容相同的文件不需下载。++不追逐补丁链。跳级可能降低补丁命中率、增加下载量,但不改变可达性。shellAbi 不兼容仍需完整应用更新。++本地对象只有通过内容校验才可作为有效复用来源;缓存存在不等于内容正确。发现损坏后重新获取目标内容,不能循环复用坏缓存。++## 6. 下载计划:替换 400 阈值++不再通过文件数量直接触发全量下载。++1. 剔除已验证的本地内容,按哈希去重。+2. 对缺失内容生成完整 object 计划;另生成包含可用、较小补丁的候选计划。+3. 按 pack 和 offset 排序,将重叠、连续范围合并。+4. 非连续范围仅在多下载间隙字节的成本小于节省请求的收益时合并,且不得超过单次请求的内存 / 流式处理预算。+5. 比较完整 object Range、补丁混合 Range、完整 objects pack 三类可行计划,选择估计成本最低者。全包候选只下载 objects pack,不必下载 patches pack。++使用可测试的估算:++```text+预计下载耗时 ≈ 传输字节数 / 估计吞吐量+ + ceil(请求数 / 并发数) × 估计请求延迟+```++这是启发式估算,不是 SLA。复用本次会话已完成请求的观测值;冷启动用明确的内部默认值。实施时根据目标网络基准确定默认值并记录,不引入长期遥测服务或用户配置项。并发初始沿用现有 8 路。下载大小必须使用压缩片段大小,并包含合并间隙;不能用 tree 的解压大小替代。++单个 Range 失败只重试该范围,有限重试后报告失败;补丁获取或应用失败时可改取对应完整 object。不得因一个失败请求直接隐式下载全量包。重新规划只针对尚缺内容。++## 7. HTTP Range 与错误处理++- 每次请求一个连续范围:`Range: bytes=<offset>-<offset+length-1>`;不依赖 multipart multi-range。+- pack 使用二进制 Content-Type,不设置整体 gzip/br Content-Encoding;下载端和 CDN 必须保持索引所指向的原始字节表示。+- 对部分请求要求正确的 `206`、`Content-Range`、返回长度及总对象大小;错误、截断、越界响应不得进入对象缓存。+- 对 Range 返回 `200` 时,不把响应当片段解码。停止未受控的全包消费,明确重新规划一次受大小限制的全包下载;不能每个 Range 都重复接收整包。+- `416`、错误总长度或压缩块哈希不匹配按协议 / 完整性失败处理,不自动接受新的偏移或对象内容。+- 全量下载以流式方式写临时文件或有界解析,验证后再使用;不把整个 pack 与所有解压文件同时堆在内存中。+- 对象写入临时路径,校验通过后原子提交。应用退出或网络中断后可复用已提交对象,未校验片段可丢弃;首版不要求持久化 Range 断点续传。++上线前必须在真实分发域名验证冷缓存与热缓存 Range 行为。客户端收到片段不代表 CDN 也只回源该片段,必须分别记录客户端传输量与可观测的回源情况。++## 8. 本地组装、应用和回退++外部版本仍是完整目录,不是只包含修改文件的覆盖层:++- 内置 ASAR 中的复用文件必须读取并写出,不能硬链接归档内的虚拟路径。+- 当前外部版本、对象缓存的文件可优先硬链接,失败时复制;共享 inode 的已提交内容不得原地修改。+- 在新临时目录组装并检查入口资源及全部目标内容,再提交为版本目录和 staged 指针。+- 不删除或覆盖正在运行的 current/previous。相同版本已存在时验证后复用,损坏且被使用时拒绝危险替换。+- 保留现有 renderer-only reload 与业务主进程变更 relaunch 行为,校验各入口均切换到同一目标资源版本。+- 应用失败回退 previous,必要时回退内置 core;内置 ASAR 始终保持不变。+- GC 不得删除被 current、previous、staged 或正在下载 / 组装任务引用的内容。++首次 OTA 会将所需内置内容写成散文件,因此网络增量不等于磁盘增量。需评估内置 ASAR、外部版本、缓存、下载临时文件共同产生的峰值空间;磁盘不足必须安全失败,保留当前可运行版本。++## 9. 发布与兼容迁移++v3 为严格 schema,不能直接向原 `latest.json` 塞入 v4 字段。++- 旧客户端继续使用现有 v3 feed、独立 CAS 对象、补丁和 ZIP 全量包。ZIP 仅为旧协议兼容保留,不用于 v4。+- v4 使用单独路径,例如 `<channel>/<appVersion>/core-v4/<platform>/latest.json` 和 `versions/<version>.json`;pack 位于该协议空间下的 `packs/<sha256>.pack`。+- 第一版通过完整应用发布交付 ASAR 布局、新 loader 和 v4 客户端。旧客户端通过原完整应用更新链路迁移;不要求旧 loader 直接启动 v4 core。+- 兼容期同一业务构建可同时生成 v3/v4 产物,分别使用其适用的 ABI 和 manifest,不混用严格 schema。+- 发布顺序:全部 pack → 不可变版本 manifest → latest。保留现有 seq 防倒退、发布互斥与 channel/platform 隔离。+- 发布前验证所有引用的 pack 已完整可读,Range 与哈希正确;上传失败不得推进 latest。+- 停止 v3 发布及删除对象必须有明确的支持周期决策,不以新版本上线为删除依据。+- 新构建生成补丁时,旧内容获取也必须支持上一版 v4 索引和 Range,不能继续依赖已停止上传的 `/cas/objects/<sha>.zst`。+- pack 保留按仍受支持的版本 manifest 引用决定,保证下载中的版本及可回退版本不因清理失效。++## 10. 实施顺序++1. 实现 v4 schema、确定性 pack 构建、索引与签名,保留 v3 发布能力。+2. 实现 Range 获取、校验、有界解码、下载计划与逐文件失败处理;复用现有对象缓存和 Zstd 补丁。+3. 接入 ASAR 内置布局及各真实路径消费者,更新 loader 和 ABI 输入。+4. 接入 v4 发布与完整应用迁移,验证真实 R2/CDN 链路。+5. 完成性能对比与产品验收后灰度启用;旧协议退役单独决策。++## 11. 验收条件++行为测试必须验证结果与边界,不以静态索引快照替代:++| 场景 | 必须满足 |+| -------------------- | ---------------------------------------------------------- |+| 确定性构建 | 相同内容生成相同 pack 字节及偏移,所有 frame 可独立还原 |+| 部分更新 | 本地内容有效时不下载相应 frame;新目录与目标 tree 完全一致 |+| 跳级 v1 → v5 | 不请求中间 manifest;无适用补丁仍可通过目标完整块完成 |+| 补丁 | 正确字典成功,错误字典或损坏补丁只回退对应 object |+| 大量小文件 | 超过 400 个缺失但 Range 估算更便宜时仍选择 Range |+| 接近全量 | 全包估算更便宜时选择 objects pack,不额外下载补丁包 |+| Range 合并 | 多余字节计入成本,按索引准确拆出各 frame |+| HTTP 异常 | 200/416、截断、错位、错误总长度和哈希失败不污染缓存 |+| 不可信索引 | 签名错误、越界、重复路径、输出超限均被拒绝 |+| 损坏本地内容 | 坏缓存 / 复用文件被识别,重新获取后能完成更新 |+| 中断与空间不足 | 当前版本保持可用,重试复用已验证对象 |+| 首次 ASAR → 外部版本 | 不下载未变内容,真实完成虚拟路径读取与散文件写出 |+| 外部版本 → 外部版本 | 复用不修改旧 inode;回退版本仍完整 |+| 兼容 | v3 继续读取原 feed;v4 不要求旧客户端理解新格式 |+| 发布失败 | pack 不完整或校验失败时 latest 不前移 |++性能与产品证据:++- 使用相同业务产物对比散文件安装与内置 ASAR 安装;Windows 启用默认安全软件,macOS 使用真实分发包。+- 分别测安装 / 拷贝时间、首次可交互时间,不能把后台展开延迟隐藏到首次启动。+- 至少覆盖连续版本、跨多个版本、401+ 小文件变更、接近全量变更四种更新数据集。+- 记录发布对象数、上传字节、上传耗时;客户端请求数、补丁命中、下载字节、下载耗时、组装耗时、峰值内存和磁盘空间。+- 真实域名冷 / 热缓存验证 206 与字节边界;不以本地 mock 代替 R2/CDN 验收。+- 实际打开更新后的主窗口及相关入口,完成至少一次 relaunch、renderer reload 和失败回退验证。+- 不预先承诺性能倍数。默认计划参数和发布结论必须附真实测量依据。++本文为文档交付,不改产品行为,不要求本次运行产品 acceptance;实施交付时按仓库 acceptance 流程完成上述产品验证。++## 12. 协议参考++- [Electron ASAR 文件读取与限制](https://www.electronjs.org/docs/latest/tutorial/asar-archives)+- [R2 S3 API 与 Range 支持](https://developers.cloudflare.com/r2/api/s3/api/)+- [R2 Workers API range 参数](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/)+- [Cloudflare Range 请求与缓存行为](https://developers.cloudflare.com/cache/reference/range-requests/)++### R2 发布目录与清理边界++- 安装包与 OTA 统一归属于 `<channel>/<appVersion>/`。`appVersion` 是壳的 `shellVersion`,不是 OTA 的 `<appVersion>-core.<seq>`。客户端即使运行外置 core,也始终使用壳版本定位 feed。+- 每个 App 版本的 `core-v4/<platform>/` 下保存 `latest.json`、`versions/<otaVersion>.json`、`packs/<sha256>.pack`;补丁只使用同一 App 版本的前序 manifest,seq 也仅在该版本所有平台中递增。pack 路径保持相对 feed,不跨 App 版本引用。+- `<channel>/shell.json` 与完整安装包 updater manifest 是发现最新完整版本的固定入口,继续放在渠道根目录;`shell.json` 另存一份至 `<channel>/<appVersion>/shell.json`。v3 旧路径仅为已安装旧客户端保留,v4 不再向渠道根级 core 或全局 CAS 写入。+- 本次上线不自动删除线上历史对象。完整版本上线并确认新客户端使用版本目录后,再盘点渠道根级旧 `core/`、`core-v4/`、历史 renderer OTA、全局 `cas/` 等引用;明确保留版本、回滚窗口和下载宽限期后单独执行清理。仍受支持的旧客户端所需对象不得仅因层级过时删除。+- 淘汰某个 App 版本可整体删除 `<channel>/<appVersion>/`,同时检查渠道根级入口不再指向它。当前 App 版本内的 pack 不能按单个 OTA manifest 随意删除,需保留仍被支持快照引用的 pack。