Skip to content

🤯 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.

✨ feat(desktop): renderer OTA hot update without app restart (#18648)

Innei19f910750c49
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 058b2d3ae10..d9a6f0f797f 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -757,3 +757,19 @@ numerically (alpha at the corners vs the subject, encoded format signature, dime
and where the property is compositional, show the artifact over a contrasting surface.
When the model cannot deliver the property, produce it in code after generation rather
than re-wording the prompt.
+
+### L-S15 — Trusting a lockfile-false workspace's node\_modules to track current specs
+
+**Wrong approach:** debug a "missing export" build failure in a workspace with
+`lockfile: false` by bumping package.json specs or running `pnpm up`, assuming the
+next install re-resolves.
+
+**Why it fails:** pnpm keeps a hidden `node_modules/.pnpm/lock.yaml` that freezes
+prior resolutions even with `lockfile: false`; `pnpm install` and `pnpm up` can
+report success while every symlink stays on the stale version. CI never hits this
+because it installs from scratch.
+
+**Correct approach:** when installed versions contradict fresh-resolution
+expectations, delete the hidden `node_modules/.pnpm/lock.yaml` (or the whole
+node\_modules) in the affected workspace root and reinstall, then re-verify the
+actual resolved version via the importing package's symlink.
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 277044554fa..5576be8a5ae 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -1422,6 +1422,22 @@ pool instance along the way (the log shows
`GPU process exited unexpectedly: exit_code=15`), so the order is: fix the port and
start the server first, then start Electron.
+### Renderer OTA: creating a real download delta in dev
+
+**Situation:** verifying renderer OTA incremental download in dev, where the
+"builtin" renderer (`apps/desktop/dist/renderer`) is the same directory the build
+writes to.
+
+**Doesn't work:** rebuild + publish the manifest from `dist/renderer`, then
+trigger a check — the manager diffs against the builtin tree, which now equals
+the manifest tree, so every file is hardlink-reused and 0 files download.
+
+**Works:** snapshot `dist/renderer` before the new build; publish the manifest
+from the fresh build output; then restore the snapshot over `dist/renderer` so
+the local tree differs from the manifest. The check then downloads only the real
+delta. Also: read the feed server's 404 line after boot to learn the exact
+`<channel>/<mainHash>` path the running app expects instead of recomputing it.
+
### Dev server, install, and ports
#### A backgrounded `init-dev-env.sh dev` looks dead while the server is alive on a dynamic port
diff --git a/.github/actions/desktop-build-setup/action.yml b/.github/actions/desktop-build-setup/action.yml
index 259c7eacb1c..f8f1d12c7a4 100644
--- a/.github/actions/desktop-build-setup/action.yml
+++ b/.github/actions/desktop-build-setup/action.yml
@@ -43,12 +43,16 @@ runs:
rm -rf "$cloud_checkout"
- clone_args=(--depth 1)
+ git clone --depth 1 --no-checkout "https://x-access-token:${CLOUD_TOKEN}@github.com/${CLOUD_REPOSITORY}.git" "$cloud_checkout"
if [ -n "$CLOUD_REF" ]; then
- clone_args+=(--branch "$CLOUD_REF")
+ git -C "$cloud_checkout" fetch --depth 1 origin "$CLOUD_REF"
+ git -C "$cloud_checkout" checkout --detach FETCH_HEAD
+ else
+ git -C "$cloud_checkout" checkout --detach
fi
- git clone "${clone_args[@]}" "https://x-access-token:${CLOUD_TOKEN}@github.com/${CLOUD_REPOSITORY}.git" "$cloud_checkout"
+ resolved_cloud_ref="$(git -C "$cloud_checkout" rev-parse HEAD)"
+ echo "CLOUD_REF=$resolved_cloud_ref" >> "$GITHUB_ENV"
node <<'NODE'
const fs = require('node:fs');
@@ -87,7 +91,7 @@ runs:
NODE
echo "CLOUD_DESKTOP=1" >> "$GITHUB_ENV"
- echo "✅ Cloud repository overlaid at $cloud_root"
+ echo "✅ Cloud repository $resolved_cloud_ref overlaid at $cloud_root"
- name: Install dependencies
shell: bash
diff --git a/.github/actions/desktop-publish-s3/action.yml b/.github/actions/desktop-publish-s3/action.yml
index cfebe7201c3..48c31b87072 100644
--- a/.github/actions/desktop-publish-s3/action.yml
+++ b/.github/actions/desktop-publish-s3/action.yml
@@ -8,6 +8,9 @@ inputs:
version:
description: 'Release version (e.g., 2.1.29-canary.1)'
required: true
+ cloud-ref:
+ description: 'Cloud repository commit used by the packaged binaries'
+ required: true
aws-access-key-id:
description: 'AWS access key ID'
required: true
@@ -25,6 +28,10 @@ inputs:
description: 'Custom S3 endpoint (for R2/MinIO etc.)'
required: false
default: ''
+ upload-release-files:
+ description: Upload installers and electron-updater manifests
+ required: false
+ default: 'true'
runs:
using: composite
@@ -47,6 +54,7 @@ runs:
echo "📋 Version: ${{ inputs.version }}, Channel: ${{ inputs.channel }}"
- name: Upload to S3
+ if: inputs.upload-release-files == 'true'
shell: bash
env:
AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
@@ -153,3 +161,43 @@ runs:
echo ""
echo "📋 Files in s3://$S3_BUCKET/$CHANNEL/$VERSION/:"
aws s3 ls "s3://$S3_BUCKET/$CHANNEL/$VERSION/" $ENDPOINT_ARG || true
+
+ - name: Publish renderer OTA base marker
+ shell: bash
+ env:
+ AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
+ AWS_SECRET_ACCESS_KEY: ${{ inputs.aws-secret-access-key }}
+ AWS_REGION: ${{ inputs.s3-region }}
+ S3_BUCKET: ${{ inputs.s3-bucket }}
+ S3_ENDPOINT: ${{ inputs.s3-endpoint }}
+ CHANNEL: ${{ inputs.channel }}
+ CLOUD_REF: ${{ inputs.cloud-ref }}
+ VERSION: ${{ inputs.version }}
+ run: |
+ set -euo pipefail
+
+ if [ -z "$S3_BUCKET" ]; then
+ echo "S3 bucket not configured, skipping renderer OTA marker"
+ exit 0
+ fi
+
+ ENDPOINT_ARG=""
+ if [ -n "$S3_ENDPOINT" ]; then
+ ENDPOINT_ARG="--endpoint-url $S3_ENDPOINT"
+ fi
+
+ MAIN_HASH=$(cat release/renderer-mainhash.txt)
+ if [[ ! "$MAIN_HASH" =~ ^[0-9a-f]{64}$ ]] || [[ ! "$CLOUD_REF" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Invalid renderer OTA base metadata"
+ exit 1
+ fi
+
+ echo "renderer OTA base mainHash: $MAIN_HASH"
+ jq -n \
+ --arg cloudRef "$CLOUD_REF" \
+ --arg mainHash "$MAIN_HASH" \
+ --arg version "$VERSION" \
+ '{ cloudRef: $cloudRef, mainHash: $mainHash, version: $version }' \
+ > /tmp/renderer-ota-base.json
+ aws s3 cp /tmp/renderer-ota-base.json "s3://$S3_BUCKET/renderer/$CHANNEL/base.json" \
+ --cache-control no-store $ENDPOINT_ARG
diff --git a/.github/actions/desktop-upload-artifacts/action.yml b/.github/actions/desktop-upload-artifacts/action.yml
index e4fce923101..3b93c0bc483 100644
--- a/.github/actions/desktop-upload-artifacts/action.yml
+++ b/.github/actions/desktop-upload-artifacts/action.yml
@@ -9,10 +9,19 @@ inputs:
description: Number of days to retain artifacts
required: false
default: '5'
+ renderer-ota-public-key:
+ description: Public key embedded in the packaged binary
+ required: true
runs:
using: composite
steps:
+ - name: Export renderer OTA base hash
+ shell: bash
+ env:
+ RENDERER_OTA_PUBLIC_KEY: ${{ inputs.renderer-ota-public-key }}
+ run: node apps/desktop/scripts/mainHash.mjs > apps/desktop/release/renderer-mainhash.txt
+
- name: Rename macOS *-mac.yml for multi-architecture support
if: runner.os == 'macOS'
shell: bash
@@ -52,4 +61,5 @@ runs:
apps/desktop/release/*.snap*
apps/desktop/release/*.rpm*
apps/desktop/release/*.tar.gz*
+ apps/desktop/release/renderer-mainhash.txt
retention-days: ${{ inputs.retention-days }}
diff --git a/.github/workflows/release-desktop-beta.yml b/.github/workflows/release-desktop-beta.yml
index 9512226eb39..866eaa4a115 100644
--- a/.github/workflows/release-desktop-beta.yml
+++ b/.github/workflows/release-desktop-beta.yml
@@ -31,6 +31,7 @@ jobs:
name: Check if Beta Release
runs-on: ubuntu-latest
outputs:
+ cloud_ref: ${{ steps.cloud-ref.outputs.cloud_ref }}
is_beta: ${{ steps.check.outputs.is_beta }}
version: ${{ steps.check.outputs.version }}
steps:
@@ -53,6 +54,20 @@ jobs:
echo "⏭️ Skipping: $version is a stable release (handled by release-desktop-stable.yml)"
fi
+ - name: Resolve Cloud revision
+ id: cloud-ref
+ if: steps.check.outputs.is_beta == 'true'
+ env:
+ CLOUD_TOKEN: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
+ run: |
+ set -euo pipefail
+ cloud_ref=$(git ls-remote "https://x-access-token:${CLOUD_TOKEN}@github.com/lobehub/lobehub-cloud.git" HEAD | cut -f1)
+ if [[ ! "$cloud_ref" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Unable to resolve Cloud revision"
+ exit 1
+ fi
+ echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"
+
test:
name: Code quality check
needs: [check-beta]
@@ -87,6 +102,7 @@ jobs:
- name: Setup build environment
uses: ./.github/actions/desktop-build-setup
with:
+ cloud-ref: ${{ needs.check-beta.outputs.cloud_ref }}
cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
node-version: ${{ env.NODE_VERSION }}
@@ -109,6 +125,8 @@ jobs:
run: npm run desktop:package:app
env:
UPDATE_CHANNEL: beta
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
@@ -127,6 +145,8 @@ jobs:
run: npm run desktop:package:app
env:
UPDATE_CHANNEL: beta
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
@@ -141,6 +161,8 @@ jobs:
run: npm run desktop:package:app
env:
UPDATE_CHANNEL: beta
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
@@ -151,6 +173,7 @@ jobs:
uses: ./.github/actions/desktop-upload-artifacts
with:
artifact-name: release-${{ matrix.os }}
+ renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
# 汇总门禁: test/build 完成后决定是否继续
gate:
@@ -246,3 +269,21 @@ jobs:
release/*.tar.gz*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ publish-renderer-base:
+ needs: [check-beta, merge-mac-files]
+ name: Publish Beta Renderer Base
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+ - uses: ./.github/actions/desktop-publish-s3
+ with:
+ channel: beta
+ cloud-ref: ${{ needs.check-beta.outputs.cloud_ref }}
+ version: ${{ needs.check-beta.outputs.version }}
+ upload-release-files: false
+ aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
+ aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
+ s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
+ s3-region: ${{ secrets.UPDATE_S3_REGION }}
+ s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.yml
index 37e3da74d31..ecf5c4b577a 100644
--- a/.github/workflows/release-desktop-canary.yml
+++ b/.github/workflows/release-desktop-canary.yml
@@ -45,6 +45,7 @@ jobs:
name: Calculate Canary Version
runs-on: ubuntu-latest
outputs:
+ cloud_ref: ${{ steps.cloud-ref.outputs.cloud_ref }}
release_notes: ${{ steps.release-notes.outputs.release_notes }}
version: ${{ steps.version.outputs.version }}
tag: ${{ steps.version.outputs.tag }}
@@ -122,6 +123,20 @@ jobs:
echo "✅ Canary version: ${version}"
echo "🏷️ Tag: ${tag}"
+ - name: Resolve Cloud revision
+ id: cloud-ref
+ if: steps.check.outputs.should_build == 'true'
+ env:
+ CLOUD_TOKEN: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
+ run: |
+ set -euo pipefail
+ cloud_ref=$(git ls-remote "https://x-access-token:${CLOUD_TOKEN}@github.com/lobehub/lobehub-cloud.git" HEAD | cut -f1)
+ if [[ ! "$cloud_ref" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Unable to resolve Cloud revision"
+ exit 1
+ fi
+ echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"
+
- name: Generate canary release notes
if: steps.check.outputs.should_build == 'true'
id: release-notes
@@ -223,6 +238,7 @@ jobs:
- name: Setup build environment
uses: ./.github/actions/desktop-build-setup
with:
+ cloud-ref: ${{ needs.calculate-version.outputs.cloud_ref }}
cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
node-version: ${{ env.NODE_VERSION }}
@@ -254,6 +270,7 @@ jobs:
env:
UPDATE_CHANNEL: canary
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -274,6 +291,7 @@ jobs:
env:
UPDATE_CHANNEL: canary
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -290,6 +308,7 @@ jobs:
env:
UPDATE_CHANNEL: canary
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -318,6 +337,7 @@ jobs:
uses: ./.github/actions/desktop-upload-artifacts
with:
artifact-name: release-${{ matrix.os }}
+ renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
retention-days: 3
# ============================================
@@ -417,6 +437,7 @@ jobs:
- uses: ./.github/actions/desktop-publish-s3
with:
channel: canary
+ cloud-ref: ${{ needs.calculate-version.outputs.cloud_ref }}
version: ${{ needs.calculate-version.outputs.version }}
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
diff --git a/.github/workflows/release-desktop-renderer-ota.yml b/.github/workflows/release-desktop-renderer-ota.yml
new file mode 100644
index 00000000000..1f931cffc37
--- /dev/null
+++ b/.github/workflows/release-desktop-renderer-ota.yml
@@ -0,0 +1,159 @@
+name: Release Desktop Renderer OTA
+
+# ============================================
+# Renderer 热更 patch 发布
+# ============================================
+# 前提: renderer/<channel>/base.json 由全量发版流程写入 (desktop-publish-s3)。
+# 门禁: HEAD 的 mainHash 必须等于该 marker —— main 变了只能走全量发版,
+# 此工作流会直接跳过。
+# 产物: renderer/<channel>/<mainHash>/latest.json (签名 manifest)
+# renderer/files/<sha256>.bin (内容寻址,增量上传)
+# ============================================
+
+on:
+ workflow_dispatch:
+ inputs:
+ channel:
+ description: 'Update channel'
+ required: true
+ type: choice
+ options:
+ - canary
+ - stable
+ - beta
+ default: canary
+
+concurrency:
+ group: ${{ github.workflow }}-${{ inputs.channel }}
+ cancel-in-progress: true
+
+permissions: read-all
+
+env:
+ NODE_VERSION: '24.11.1'
+
+jobs:
+ publish-renderer-patch:
+ name: Publish Renderer Patch (${{ inputs.channel }})
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Load shipped base
+ id: base
+ env:
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ CHANNEL: ${{ inputs.channel }}
+ run: |
+ set -euo pipefail
+ BASE=$(curl -sf "$UPDATE_SERVER_URL/renderer/$CHANNEL/base.json" || true)
+ if [ -z "$BASE" ]; then
+ echo "::warning::no renderer OTA base metadata found; run a full release first"
+ echo "found=false" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+
+ MAIN_HASH=$(jq -er '.mainHash | select(type == "string" and test("^[0-9a-f]{64}$"))' <<< "$BASE")
+ CLOUD_REF=$(jq -er '.cloudRef | select(type == "string" and test("^[0-9a-f]{40}$"))' <<< "$BASE")
+ APP_VERSION=$(jq -er '.version | select(type == "string" and test("^[0-9A-Za-z.+-]+$"))' <<< "$BASE")
+ echo "app_version=$APP_VERSION" >> "$GITHUB_OUTPUT"
+ echo "cloud_ref=$CLOUD_REF" >> "$GITHUB_OUTPUT"
+ echo "found=true" >> "$GITHUB_OUTPUT"
+ echo "main_hash=$MAIN_HASH" >> "$GITHUB_OUTPUT"
+
+ - name: Setup build environment
+ if: steps.base.outputs.found == 'true'
+ uses: ./.github/actions/desktop-build-setup
+ with:
+ cloud-ref: ${{ steps.base.outputs.cloud_ref }}
+ cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
+ node-version: ${{ env.NODE_VERSION }}
+
+ - name: Set package version
+ if: steps.base.outputs.found == 'true'
+ run: npm run workflow:set-desktop-version ${{ steps.base.outputs.app_version }} ${{ inputs.channel }}
+
+ - name: Gate on mainHash
+ id: gate
+ if: steps.base.outputs.found == 'true'
+ env:
+ BASE_MAIN_HASH: ${{ steps.base.outputs.main_hash }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ run: |
+ MAIN_HASH=$(node apps/desktop/scripts/mainHash.mjs)
+ echo "main_hash=$MAIN_HASH" >> "$GITHUB_OUTPUT"
+ echo "HEAD mainHash: $MAIN_HASH"
+ echo "Shipped base mainHash: $BASE_MAIN_HASH"
+
+ if [ "$MAIN_HASH" != "$BASE_MAIN_HASH" ]; then
+ echo "::warning::main changed since last full release — renderer patch is not allowed, run a full release instead"
+ echo "allowed=false" >> "$GITHUB_OUTPUT"
+ else
+ echo "allowed=true" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Determine patch version
+ id: version
+ if: steps.gate.outputs.allowed == 'true'
+ env:
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ CHANNEL: ${{ inputs.channel }}
+ MAIN_HASH: ${{ steps.gate.outputs.main_hash }}
+ run: |
+ CURRENT=$(curl -sf "$UPDATE_SERVER_URL/renderer/$CHANNEL/$MAIN_HASH/latest.json" | node -e "
+ let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{
+ try { console.log(JSON.parse(d).version) } catch { console.log('r0') }
+ })" || echo "r0")
+ NEXT="r$(( ${CURRENT#r} + 1 ))"
+ echo "Current patch: $CURRENT -> next: $NEXT"
+ echo "version=$NEXT" >> "$GITHUB_OUTPUT"
+
+ - name: Build renderer
+ if: steps.gate.outputs.allowed == 'true'
+ run: npm run build:renderer --prefix=./apps/desktop
+ env:
+ UPDATE_CHANNEL: ${{ inputs.channel }}
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ APP_URL: http://localhost:3015
+ DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
+ KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
+ NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_PROJECT_ID || secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
+ NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_BASE_URL || secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
+
+ - name: Build and sign manifest
+ if: steps.gate.outputs.allowed == 'true'
+ env:
+ RENDERER_OTA_PRIVATE_KEY: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
+ run: |
+ node apps/desktop/scripts/buildRendererManifest.mjs \
+ --renderer=apps/desktop/dist/renderer \
+ --out=renderer-ota-out \
+ --channel=${{ inputs.channel }} \
+ --version=${{ steps.version.outputs.version }} \
+ --mainHash=${{ steps.gate.outputs.main_hash }}
+
+ - name: Upload to S3
+ if: steps.gate.outputs.allowed == 'true'
+ env:
+ AWS_ACCESS_KEY_ID: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
+ AWS_REGION: ${{ secrets.UPDATE_S3_REGION }}
+ S3_BUCKET: ${{ secrets.UPDATE_S3_BUCKET }}
+ S3_ENDPOINT: ${{ secrets.UPDATE_S3_ENDPOINT }}
+ CHANNEL: ${{ inputs.channel }}
+ MAIN_HASH: ${{ steps.gate.outputs.main_hash }}
+ run: |
+ ENDPOINT_ARG=""
+ if [ -n "$S3_ENDPOINT" ]; then
+ ENDPOINT_ARG="--endpoint-url $S3_ENDPOINT"
+ fi
+
+ # CAS objects first (immutable, skip existing), manifest last so a
+ # client never sees a manifest whose files are not yet uploaded.
+ aws s3 sync renderer-ota-out/files "s3://$S3_BUCKET/renderer/files" \
+ --size-only $ENDPOINT_ARG
+ aws s3 cp "renderer-ota-out/$CHANNEL/$MAIN_HASH/latest.json" \
+ "s3://$S3_BUCKET/renderer/$CHANNEL/$MAIN_HASH/latest.json" \
+ --cache-control no-store $ENDPOINT_ARG
+
+ echo "✅ Published renderer patch ${{ steps.version.outputs.version }} for $CHANNEL/$MAIN_HASH"
diff --git a/.github/workflows/release-desktop-stable.yml b/.github/workflows/release-desktop-stable.yml
index a61155bf79b..6aaee8383d8 100644
--- a/.github/workflows/release-desktop-stable.yml
+++ b/.github/workflows/release-desktop-stable.yml
@@ -77,6 +77,7 @@ jobs:
name: Check Release Version
runs-on: ubuntu-latest
outputs:
+ cloud_ref: ${{ steps.cloud-ref.outputs.cloud_ref }}
is_stable: ${{ steps.check.outputs.is_stable }}
version: ${{ steps.check.outputs.version }}
is_manual: ${{ steps.check.outputs.is_manual }}
@@ -119,6 +120,20 @@ jobs:
echo "✅ Stable release detected: $version"
fi
+ - name: Resolve Cloud revision
+ id: cloud-ref
+ if: steps.check.outputs.is_stable == 'true'
+ env:
+ CLOUD_TOKEN: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
+ run: |
+ set -euo pipefail
+ cloud_ref=$(git ls-remote "https://x-access-token:${CLOUD_TOKEN}@github.com/lobehub/lobehub-cloud.git" HEAD | cut -f1)
+ if [[ ! "$cloud_ref" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Unable to resolve Cloud revision"
+ exit 1
+ fi
+ echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"
+
# ============================================
# 配置构建矩阵 (检查自托管 Runner)
# ============================================
@@ -180,6 +195,7 @@ jobs:
- name: Setup build environment
uses: ./.github/actions/desktop-build-setup
with:
+ cloud-ref: ${{ needs.check-stable.outputs.cloud_ref }}
cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
node-version: ${{ env.NODE_VERSION }}
@@ -211,6 +227,7 @@ jobs:
env:
UPDATE_CHANNEL: stable
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
RELEASE_NOTES: ${{ needs.check-stable.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -233,6 +250,7 @@ jobs:
env:
UPDATE_CHANNEL: stable
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
RELEASE_NOTES: ${{ needs.check-stable.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -252,6 +270,7 @@ jobs:
env:
UPDATE_CHANNEL: stable
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
RELEASE_NOTES: ${{ needs.check-stable.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -263,6 +282,7 @@ jobs:
uses: ./.github/actions/desktop-upload-artifacts
with:
artifact-name: release-${{ matrix.name }}
+ renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
# ============================================
# 合并 macOS 多架构文件
@@ -366,6 +386,7 @@ jobs:
- uses: ./.github/actions/desktop-publish-s3
with:
channel: stable
+ cloud-ref: ${{ needs.check-stable.outputs.cloud_ref }}
version: ${{ needs.check-stable.outputs.version }}
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
diff --git a/apps/desktop/.npmrc b/apps/desktop/.npmrc
index 6245cc65270..b95c6a571b8 100644
--- a/apps/desktop/.npmrc
+++ b/apps/desktop/.npmrc
@@ -1,4 +1,4 @@
-lockfile=false
+lockfile=true
shamefully-hoist=true
ignore-workspace-root-check=true
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 9abab35f91f..628e73e21a1 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -14,6 +14,7 @@
"build:cli": "cd ../cli && cross-env MINIFY=1 bun run build",
"build:main": "cross-env NODE_OPTIONS=--max-old-space-size=8192 npm run build:main:raw",
"build:main:raw": "vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.renderer.config.ts",
+ "build:renderer": "cross-env NODE_OPTIONS=--max-old-space-size=8192 vite build --config vite.renderer.config.ts",
"build:run-unpack": "electron .",
"db:generate:local": "drizzle-kit generate --config drizzle.local.config.ts",
"dev": "node scripts/dev.mjs",
@@ -122,7 +123,8 @@
"uuid": "^14.0.1",
"vite": "8.0.14",
"vitest": "3.2.6",
- "zod": "^4.4.3"
+ "zod": "^4.4.3",
+ "zod-compiler": "^1.28.0"
},
"optionalDependencies": {
"node-mac-permissions": "^2.5.0"
diff --git a/apps/desktop/scripts/__tests__/mainHash.test.mjs b/apps/desktop/scripts/__tests__/mainHash.test.mjs
new file mode 100644
index 00000000000..a681efb164a
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/mainHash.test.mjs
@@ -0,0 +1,87 @@
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { readFileSync, rmSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+import { computeMainHash, STANDALONE_FILES } from '../mainHash.mjs';
+
+const desktopRoot = path.dirname(path.dirname(path.dirname(fileURLToPath(import.meta.url))));
+const repoRoot = path.dirname(path.dirname(desktopRoot));
+
+describe('mainHash', () => {
+ it('only hashes git-tracked standalone files so CI fresh checkouts reproduce the hash', () => {
+ for (const file of STANDALONE_FILES) {
+ const abs = path.join(desktopRoot, file);
+ expect(
+ () => execFileSync('git', ['ls-files', '--error-unmatch', abs], { cwd: repoRoot }),
+ `${file} must be committed — untracked inputs are silently skipped on fresh checkouts`,
+ ).not.toThrow();
+ }
+ });
+
+ it('changes when a file under src/common changes', () => {
+ const probe = path.join(desktopRoot, 'src', 'common', `__mainhash-probe-${randomUUID()}.ts`);
+ const before = computeMainHash();
+ writeFileSync(probe, 'export const probe = 1;\n');
+ try {
+ expect(computeMainHash()).not.toBe(before);
+ } finally {
+ rmSync(probe, { force: true });
+ }
+ });
+
+ it('changes when a main-process locale resource changes', () => {
+ const probe = path.join(
+ desktopRoot,
+ 'resources',
+ 'locales',
+ `__mainhash-probe-${randomUUID()}.json`,
+ );
+ const before = computeMainHash();
+ writeFileSync(probe, '{}\n');
+ try {
+ expect(computeMainHash()).not.toBe(before);
+ } finally {
+ rmSync(probe, { force: true });
+ }
+ });
+
+ it('changes when the Cloud build revision changes', () => {
+ const originalCloudRef = process.env.CLOUD_REF;
+ try {
+ process.env.CLOUD_REF = 'a'.repeat(40);
+ const before = computeMainHash();
+ process.env.CLOUD_REF = 'b'.repeat(40);
+ expect(computeMainHash()).not.toBe(before);
+ } finally {
+ if (originalCloudRef === undefined) delete process.env.CLOUD_REF;
+ else process.env.CLOUD_REF = originalCloudRef;
+ }
+ });
+
+ it('shares a lineage across release versions but not verification keys', () => {
+ const packagePath = path.join(desktopRoot, 'package.json');
+ const originalPackage = readFileSync(packagePath, 'utf8');
+ const originalPublicKey = process.env.RENDERER_OTA_PUBLIC_KEY;
+ try {
+ process.env.RENDERER_OTA_PUBLIC_KEY = 'key-a';
+ const before = computeMainHash();
+ const packageJson = JSON.parse(originalPackage);
+ packageJson.name = 'lobehub-desktop-beta';
+ packageJson.productName = 'LobeHub-Beta';
+ packageJson.version = '99.0.0-beta.1';
+ writeFileSync(packagePath, JSON.stringify(packageJson, null, 2));
+ expect(computeMainHash()).toBe(before);
+
+ process.env.RENDERER_OTA_PUBLIC_KEY = 'key-b';
+ expect(computeMainHash()).not.toBe(before);
+ } finally {
+ writeFileSync(packagePath, originalPackage);
+ if (originalPublicKey === undefined) delete process.env.RENDERER_OTA_PUBLIC_KEY;
+ else process.env.RENDERER_OTA_PUBLIC_KEY = originalPublicKey;
+ }
+ });
+});
diff --git a/apps/desktop/scripts/buildRendererManifest.mjs b/apps/desktop/scripts/buildRendererManifest.mjs
new file mode 100644
index 00000000000..7b341df0a94
--- /dev/null
+++ b/apps/desktop/scripts/buildRendererManifest.mjs
@@ -0,0 +1,120 @@
+import { createHash, generateKeyPairSync, sign } from 'node:crypto';
+import {
+ copyFileSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { computeMainHash } from './mainHash.mjs';
+
+export function canonicalJson(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const entries = Object.keys(value)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`);
+ return `{${entries.join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+function walk(dir, files = []) {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(full, files);
+ else files.push(full);
+ }
+ return files;
+}
+
+export function buildManifest({ rendererDir, version, appVersion, mainHash }) {
+ const files = walk(rendererDir)
+ .map((full) => {
+ const content = readFileSync(full);
+ return {
+ path: path.relative(rendererDir, full).replaceAll('\\', '/'),
+ sha256: createHash('sha256').update(content).digest('hex'),
+ size: content.byteLength,
+ };
+ })
+ .sort((a, b) => (a.path < b.path ? -1 : 1));
+
+ return { appVersion, files, mainHash, version };
+}
+
+export function signManifest(manifest, privateKeyPem) {
+ const signature = sign(null, Buffer.from(canonicalJson(manifest)), privateKeyPem).toString(
+ 'base64',
+ );
+ return { ...manifest, signature };
+}
+
+function main() {
+ const args = Object.fromEntries(
+ process.argv
+ .slice(2)
+ .filter((a) => a.startsWith('--'))
+ .map((a) => {
+ const [k, v] = a.slice(2).split('=');
+ return [k, v ?? true];
+ }),
+ );
+
+ if (args['gen-key']) {
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+ console.log(privateKey.export({ format: 'pem', type: 'pkcs8' }).toString());
+ console.log(publicKey.export({ format: 'pem', type: 'spki' }).toString());
+ return;
+ }
+
+ const rendererDir = path.resolve(args.renderer ?? 'dist/renderer');
+ const outDir = path.resolve(args.out ?? 'release/renderer-ota');
+ const channel = args.channel ?? process.env.UPDATE_CHANNEL ?? 'nightly';
+ const version = args.version;
+ const appVersion =
+ args.appVersion ??
+ JSON.parse(
+ readFileSync(
+ path.join(path.dirname(path.dirname(fileURLToPath(import.meta.url))), 'package.json'),
+ 'utf8',
+ ),
+ ).version;
+ const privateKeyPem = process.env.RENDERER_OTA_PRIVATE_KEY;
+
+ if (!version) throw new Error('--version=r<N> is required');
+ if (!privateKeyPem) throw new Error('RENDERER_OTA_PRIVATE_KEY env is required');
+
+ const mainHash = args.mainHash ?? computeMainHash();
+ const manifest = signManifest(
+ buildManifest({ appVersion, mainHash, rendererDir, version }),
+ privateKeyPem,
+ );
+
+ const casDir = path.join(outDir, 'files');
+ mkdirSync(casDir, { recursive: true });
+ for (const file of manifest.files) {
+ const target = path.join(casDir, `${file.sha256}.bin`);
+ try {
+ statSync(target);
+ } catch {
+ copyFileSync(path.join(rendererDir, file.path), target);
+ }
+ }
+
+ const feedDir = path.join(outDir, channel, mainHash);
+ mkdirSync(feedDir, { recursive: true });
+ writeFileSync(path.join(feedDir, 'latest.json'), JSON.stringify(manifest, null, 2));
+
+ console.log(
+ `renderer-ota manifest: ${channel}/${mainHash}/latest.json (${manifest.files.length} files, version ${version})`,
+ );
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ main();
+}
diff --git a/apps/desktop/scripts/mainHash.mjs b/apps/desktop/scripts/mainHash.mjs
new file mode 100644
index 00000000000..0cfeeba652f
--- /dev/null
+++ b/apps/desktop/scripts/mainHash.mjs
@@ -0,0 +1,129 @@
+import { createHash } from 'node:crypto';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const desktopRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const repoRoot = path.dirname(path.dirname(desktopRoot));
+
+// Only committed files: this hash must be reproducible from a fresh checkout
+// (CI gate/marker jobs) — never include generated files like pnpm-lock.yaml,
+// which only exists after install-isolated and would silently be skipped.
+export const STANDALONE_FILES = [
+ 'vite.main.config.ts',
+ 'vite.preload.config.ts',
+ 'vite.shared.ts',
+ 'native-deps.config.mjs',
+ 'external-runtime-deps.config.mjs',
+ 'module-deps.config.mjs',
+ 'electron-builder.mjs',
+ 'package.json',
+];
+
+const IGNORED_DIRS = new Set(['__tests__', '__mocks__', 'node_modules', 'dist']);
+const IGNORED_FILE_RE = /\.(?:test|spec)\.[cm]?tsx?$|\.md$|\.snap$/;
+
+function walk(dir, files = []) {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return files;
+ }
+ for (const entry of entries) {
+ if (entry.isDirectory()) {
+ if (!IGNORED_DIRS.has(entry.name)) walk(path.join(dir, entry.name), files);
+ } else if (!IGNORED_FILE_RE.test(entry.name)) {
+ files.push(path.join(dir, entry.name));
+ }
+ }
+ return files;
+}
+
+function collectWorkspaceImports(files) {
+ const packages = new Set();
+ const importRe = /(?:from\s+|import\s*\(\s*|^\s*import\s+)['"]@lobechat\/([\w-]+)/gm;
+ for (const file of files) {
+ if (!/\.[cm]?tsx?$/.test(file)) continue;
+ const content = readFileSync(file, 'utf8');
+ for (const match of content.matchAll(importRe)) packages.add(match[1]);
+ }
+ return packages;
+}
+
+function resolveWorkspaceClosure(seedFiles) {
+ const resolved = new Set();
+ let pending = collectWorkspaceImports(seedFiles);
+ while (pending.size > 0) {
+ const next = new Set();
+ for (const pkg of pending) {
+ if (resolved.has(pkg)) continue;
+ resolved.add(pkg);
+ const srcDir = path.join(repoRoot, 'packages', pkg, 'src');
+ try {
+ statSync(srcDir);
+ } catch {
+ continue;
+ }
+ for (const dep of collectWorkspaceImports(walk(srcDir))) {
+ if (!resolved.has(dep)) next.add(dep);
+ }
+ }
+ pending = next;
+ }
+ return [...resolved].sort();
+}
+
+export function computeMainHash() {
+ const seedFiles = [
+ ...walk(path.join(desktopRoot, 'src', 'main')),
+ ...walk(path.join(desktopRoot, 'src', 'preload')),
+ ...walk(path.join(desktopRoot, 'src', 'common')),
+ ...walk(path.join(desktopRoot, 'resources', 'locales')),
+ ];
+
+ const files = [...seedFiles, ...STANDALONE_FILES.map((f) => path.join(desktopRoot, f))];
+
+ for (const pkg of resolveWorkspaceClosure(seedFiles)) {
+ files.push(
+ ...walk(path.join(repoRoot, 'packages', pkg, 'src')),
+ path.join(repoRoot, 'packages', pkg, 'package.json'),
+ );
+ }
+
+ const hash = createHash('sha256');
+ for (const file of [...new Set(files)].sort()) {
+ let content;
+ try {
+ content = readFileSync(file);
+ } catch {
+ continue;
+ }
+ if (file === path.join(desktopRoot, 'package.json')) {
+ const packageJson = JSON.parse(content.toString());
+ delete packageJson.name;
+ delete packageJson.productName;
+ delete packageJson.version;
+ content = Buffer.from(JSON.stringify(packageJson));
+ }
+ hash.update(path.relative(repoRoot, file).replaceAll('\\', '/'));
+ hash.update('\0');
+ hash.update(content);
+ hash.update('\0');
+ }
+ if (process.env.CLOUD_REF) {
+ hash.update('cloud-ref\0');
+ hash.update(process.env.CLOUD_REF);
+ hash.update('\0');
+ }
+ if (process.env.RENDERER_OTA_PUBLIC_KEY) {
+ hash.update('renderer-ota-public-key\0');
+ hash.update(process.env.RENDERER_OTA_PUBLIC_KEY);
+ hash.update('\0');
+ }
+ return hash.digest('hex');
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ console.log(computeMainHash());
+}
diff --git a/apps/desktop/scripts/renderer-ota-test/README.md b/apps/desktop/scripts/renderer-ota-test/README.md
new file mode 100644
index 00000000000..9777b2105fa
--- /dev/null
+++ b/apps/desktop/scripts/renderer-ota-test/README.md
@@ -0,0 +1,83 @@
+# Renderer OTA 本地 E2E 测试
+
+在本地完整走通:检查 → 增量下载 → staged toast → 刷新应用 → boot ping 提交,以及坏包自动回退。全程 dev 模式,不需要打包。
+
+所有命令在 `apps/desktop/` 下执行。
+
+## 0. 生成测试密钥 (一次)
+
+```bash
+node scripts/buildRendererManifest.mjs --gen-key > /tmp/ota-keys.pem
+# 拆成两个文件:第一段 PRIVATE KEY 存 /tmp/ota-priv.pem,第二段 PUBLIC KEY 存 /tmp/ota-pub.pem
+```
+
+## 1. 构建 v0 renderer (内置基线)
+
+```bash
+npm run build:renderer
+```
+
+## 2. 以「生产形态」启动 dev 应用
+
+静态 renderer (不走 Vite 代理)+ 强制启用 OTA + 5 秒后首查:
+
+```bash
+DESKTOP_RENDERER_STATIC=1 \
+ RENDERER_OTA_FORCE=1 \
+ RENDERER_OTA_CHECK_DELAY=5000 \
+ RENDERER_OTA_PUBLIC_KEY="$(cat /tmp/ota-pub.pem)" \
+ UPDATE_SERVER_URL=http://127.0.0.1:8787 \
+ npm run dev
+```
+
+此时 feed 还没起,日志应出现 `Renderer OTA check failed`(fetch 拒连) 或 404 —— 属预期。
+
+## 3. 做一个肉眼可见的 renderer 改动并发布 r1
+
+改任意 renderer 侧文案 (例如 `src/features/` 下某个标题), 然后:
+
+```bash
+npm run build:renderer
+RENDERER_OTA_PRIVATE_KEY="$(cat /tmp/ota-priv.pem)" \
+ node scripts/buildRendererManifest.mjs \
+ --renderer=dist/renderer --out=/tmp/ota-feed --channel=stable --version=r1
+node scripts/renderer-ota-test/serveOta.mjs /tmp/ota-feed 8787
+```
+
+注意 `--channel` 要和应用实际渠道一致 (dev 默认 stable; 日志 `feedUrl` 可确认)。
+
+## 4. 验收 happy path
+
+- 等下一轮检查,或在 DevTools console 手动触发:
+ `await window.electronAPI.invoke('rendererOta.checkNow')`
+- serveOta 日志:只有 hash 变化的文件被拉取 (增量生效)
+- 应用左下角出现「新版本已就绪,刷新即可使用」toast
+- 点「立即刷新」: 窗口 reload (应用不重启), 改动的文案出现
+- `~/Library/Application Support/<dev userData>/renderer-ota/pointer.json`:
+ `current: "r1"`, 收到 boot ping 后 `pendingBootCheck: false`
+- `versions/` 只留 current (+previous)
+
+## 5. 验收回退路径
+
+发布一个必挂的 r2: 构建后把 `dist/renderer/assets/entry-*.js` 的内容整体替换为
+`throw new Error('boom')`(bundle 求值即抛 → 发不出 loaded ping; 注意不能删
+script 引用 —— 没有 script 的 index.html 会被 staging 期完整性检查直接拒掉),
+再按步骤 3 发布 `--version=r2`。
+
+- `checkNow` → toast → 刷新:白屏 / 报错页
+- **约 3 秒**自动回退 (loaded ping 未到); 若 bundle 能求值但挂不上,则 15 秒兜底
+- `pointer.json`:`current: "r1"`,`blacklist: ["r2"]`
+- 再次 `checkNow`:r2 被拉黑,不再下载
+
+## 6. 验收 mainHash 门禁
+
+改一行 `src/main/` 下的代码 (不重启应用), 重新按步骤 3 发布 r3:
+manifest 的 mainHash 会与运行中应用注入的不一致 → 日志
+`Manifest mainHash mismatch`, 拒绝更新。
+
+## 已知差异 (dev vs 打包)
+
+- dev 的 `MAIN_HASH` 在 vite 启动时计算;启动后改 main 源码不会让运行中的
+ 应用变 hash (打包产物没有这个问题)。
+- `RENDERER_OTA_FORCE` / `RENDERER_OTA_CHECK_DELAY` 是运行时 env, 打包产物
+ 不设置即无效,不影响生产行为。
diff --git a/apps/desktop/scripts/renderer-ota-test/serveOta.mjs b/apps/desktop/scripts/renderer-ota-test/serveOta.mjs
new file mode 100644
index 00000000000..c87c8be9d51
--- /dev/null
+++ b/apps/desktop/scripts/renderer-ota-test/serveOta.mjs
@@ -0,0 +1,29 @@
+import { createReadStream, existsSync, statSync } from 'node:fs';
+import http from 'node:http';
+import path from 'node:path';
+
+const root = path.resolve(process.argv[2] ?? 'release/renderer-ota');
+const port = Number(process.argv[3] ?? 8787);
+
+const server = http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ if (!url.pathname.startsWith('/renderer/')) {
+ res.writeHead(404).end('not an ota path');
+ return;
+ }
+
+ const file = path.join(root, url.pathname.slice('/renderer/'.length));
+ if (!file.startsWith(root) || !existsSync(file) || !statSync(file).isFile()) {
+ res.writeHead(404).end('not found');
+ console.log(`404 ${url.pathname}`);
+ return;
+ }
+
+ res.writeHead(200, { 'cache-control': 'no-store' });
+ createReadStream(file).pipe(res);
+ console.log(`200 ${url.pathname}`);
+});
+
+server.listen(port, () => {
+ console.log(`renderer OTA feed: http://127.0.0.1:${port}/renderer/ -> ${root}`);
+});
diff --git a/apps/desktop/src/main/controllers/RendererOtaCtr.ts b/apps/desktop/src/main/controllers/RendererOtaCtr.ts
new file mode 100644
index 00000000000..cee0dad9c5d
--- /dev/null
+++ b/apps/desktop/src/main/controllers/RendererOtaCtr.ts
@@ -0,0 +1,26 @@
+import { ControllerModule, IpcMethod } from './index';
+
+export default class RendererOtaCtr extends ControllerModule {
+ static override readonly groupName = 'rendererOta';
+
+ @IpcMethod()
+ async bootPing(stage?: 'loaded' | 'mounted') {
+ this.app.rendererUpdateManager.handleBootPing(stage);
+ }
+
+ @IpcMethod()
+ async applyNow(): Promise<boolean> {
+ return this.app.rendererUpdateManager.applyStagedNow();
+ }
+
+ @IpcMethod()
+ async getStatus() {
+ return this.app.rendererUpdateManager.getStatus();
+ }
+
+ @IpcMethod()
+ async checkNow() {
+ await this.app.rendererUpdateManager.checkForUpdates();
+ return this.app.rendererUpdateManager.getStatus();
+ }
+}
diff --git a/apps/desktop/src/main/controllers/UpdaterCtr.ts b/apps/desktop/src/main/controllers/UpdaterCtr.ts
index 01d136ba513..5a60d51b5b4 100644
--- a/apps/desktop/src/main/controllers/UpdaterCtr.ts
+++ b/apps/desktop/src/main/controllers/UpdaterCtr.ts
@@ -77,6 +77,7 @@ export default class UpdaterCtr extends ControllerModule {
logger.info(`Set update channel requested: ${channel}`);
this.app.storeManager.set('updateChannel', channel);
+ this.app.rendererUpdateManager.switchChannel(channel);
(await this.getUpdaterManager()).switchChannel(channel);
}
diff --git a/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
index 83c97c1d537..721d3f54532 100644
--- a/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
@@ -32,11 +32,15 @@ const mockDownloadUpdate = vi.fn();
const mockInstallNow = vi.fn();
const mockInstallLater = vi.fn();
const mockGetUpdaterState = vi.fn();
+const mockRendererSwitchChannel = vi.fn();
const mockSwitchChannel = vi.fn();
const mockStoreGet = vi.fn();
const mockStoreSet = vi.fn();
const mockApp = {
+ rendererUpdateManager: {
+ switchChannel: mockRendererSwitchChannel,
+ },
storeManager: {
get: mockStoreGet,
set: mockStoreSet,
@@ -107,6 +111,7 @@ describe('UpdaterCtr', () => {
await updaterCtr.setUpdateChannel('canary');
expect(mockStoreSet).toHaveBeenCalledWith('updateChannel', 'canary');
+ expect(mockRendererSwitchChannel).toHaveBeenCalledWith('canary');
expect(mockSwitchChannel).toHaveBeenCalledWith('canary');
});
@@ -116,6 +121,7 @@ describe('UpdaterCtr', () => {
);
expect(mockStoreSet).not.toHaveBeenCalled();
+ expect(mockRendererSwitchChannel).not.toHaveBeenCalled();
expect(mockSwitchChannel).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.ts
index 8fad5959ccd..5819e31fa8b 100644
--- a/apps/desktop/src/main/controllers/registry.ts
+++ b/apps/desktop/src/main/controllers/registry.ts
@@ -21,6 +21,7 @@ import NotificationCtr from './NotificationCtr';
import OpenInAppCtr from './OpenInAppCtr';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
import RemoteServerSyncCtr from './RemoteServerSyncCtr';
+import RendererOtaCtr from './RendererOtaCtr';
import ScreenCaptureCtr from './ScreenCaptureCtr';
import ShellCommandCtr from './ShellCommandCtr';
import ShortcutController from './ShortcutCtr';
@@ -48,6 +49,7 @@ export const controllerIpcConstructors = [
MenuController,
NetworkProxyCtr,
NotificationCtr,
+ RendererOtaCtr,
OpenInAppCtr,
RemoteServerConfigCtr,
RemoteServerSyncCtr,
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index c2660da563b..6dd935f0a76 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -37,6 +37,7 @@ import { I18nManager } from './infrastructure/I18nManager';
import { IoCContainer } from './infrastructure/IoCContainer';
import { LocalFileProtocolManager } from './infrastructure/LocalFileProtocolManager';
import { ProtocolManager } from './infrastructure/ProtocolManager';
+import { RendererUpdateManager } from './infrastructure/rendererOta/RendererUpdateManager';
import { RendererUrlManager } from './infrastructure/RendererUrlManager';
import { StaticFileServerManager } from './infrastructure/StaticFileServerManager';
import { StoreManager } from './infrastructure/StoreManager';
@@ -67,6 +68,7 @@ export class App {
staticFileServerManager: StaticFileServerManager;
protocolManager: ProtocolManager;
rendererUrlManager: RendererUrlManager;
+ rendererUpdateManager: RendererUpdateManager;
localFileProtocolManager: LocalFileProtocolManager;
binaryManager: BinaryManager;
screenCaptureManager: ScreenCaptureManager;
@@ -155,6 +157,16 @@ export class App {
this.binaryManager = new BinaryManager(this);
this.screenCaptureManager = new ScreenCaptureManager(this);
+ // Resolve the renderer OTA pointer and set the app:// serving root before
+ // any window starts loading.
+ this.rendererUpdateManager = new RendererUpdateManager(this);
+ this.rendererUpdateManager.initialize();
+ app.on('web-contents-created', (_event, webContents) => {
+ webContents.on('render-process-gone', () => {
+ this.rendererUpdateManager.handleRendererCrash();
+ });
+ });
+
// Register built-in binary specs
this.registerBuiltinBinarySpecs();
@@ -329,6 +341,7 @@ export class App {
// Initialize updater manager
await this.updaterManager.initialize();
+ this.rendererUpdateManager.startScheduledChecks();
this.screenCaptureManager.prewarmPermissionCheck();
logger.info('Post-first-frame initialization completed');
diff --git a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
index 555256588ff..dfae15a65f8 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
@@ -17,14 +17,15 @@ const logger = createLogger('core:RendererUrlManager');
// Vite build with root=monorepo preserves input path structure,
// so index.html / overlay.html / popup.html end up under apps/desktop/ in outDir.
-const SPA_ENTRY_HTML = path.join(rendererDir, 'apps', 'desktop', 'index.html');
-const OVERLAY_ENTRY_HTML = path.join(rendererDir, 'apps', 'desktop', 'overlay.html');
-const POPUP_ENTRY_HTML = path.join(rendererDir, 'apps', 'desktop', 'popup.html');
+const SPA_ENTRY_HTML = path.join('apps', 'desktop', 'index.html');
+const OVERLAY_ENTRY_HTML = path.join('apps', 'desktop', 'overlay.html');
+const POPUP_ENTRY_HTML = path.join('apps', 'desktop', 'popup.html');
export class RendererUrlManager {
private readonly rendererProtocolManager: RendererProtocolManager;
private readonly rendererStaticOverride = getDesktopEnv().DESKTOP_RENDERER_STATIC;
private readonly rendererLoadedUrl: string;
+ private activeRendererDir = rendererDir;
constructor() {
this.rendererProtocolManager = new RendererProtocolManager({
@@ -42,6 +43,26 @@ export class RendererUrlManager {
this.rendererProtocolManager.addRequestInterceptor(interceptor);
}
+ /**
+ * Point the static renderer at an OTA version dir (or back to the builtin
+ * bundle with `null`). Only takes effect between window reloads — requests
+ * read the field per resolution, no in-flight swap.
+ */
+ setActiveRendererDir(dir: string | null) {
+ const next = dir ?? rendererDir;
+ if (next !== rendererDir && !existsSync(path.join(next, SPA_ENTRY_HTML))) {
+ logger.warn(`OTA renderer dir missing entry html, falling back to builtin: ${next}`);
+ this.activeRendererDir = rendererDir;
+ return;
+ }
+ logger.info(`Renderer serving root: ${next}`);
+ this.activeRendererDir = next;
+ }
+
+ getActiveRendererDir() {
+ return this.activeRendererDir;
+ }
+
/**
* Register the `app://` protocol handler. Idempotent — safe to call after
* interceptors are wired.
@@ -72,25 +93,26 @@ export class RendererUrlManager {
*/
resolveRendererFilePath = async (url: URL): Promise<string | null> => {
const pathname = url.pathname;
+ const root = this.activeRendererDir;
// Static assets: direct file mapping
if (pathname.startsWith('/assets/') || path.extname(pathname)) {
- const filePath = path.join(rendererDir, pathname);
+ const filePath = path.join(root, pathname);
return existsSync(filePath) ? filePath : null;
}
// Overlay entry (separate MPA page)
if (pathname === '/overlay' || pathname === '/overlay.html') {
- return OVERLAY_ENTRY_HTML;
+ return path.join(root, OVERLAY_ENTRY_HTML);
}
// Topic popup window has its own SPA bundle.
if (pathname === '/popup' || pathname.startsWith('/popup/')) {
- return POPUP_ENTRY_HTML;
+ return path.join(root, POPUP_ENTRY_HTML);
}
// All other routes fallback to index.html (SPA)
- return SPA_ENTRY_HTML;
+ return path.join(root, SPA_ENTRY_HTML);
};
private pickFallback() {
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts
new file mode 100644
index 00000000000..ed04825c595
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts
@@ -0,0 +1,437 @@
+import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'node:fs';
+import { copyFile, link, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { UpdateChannel } from '@lobechat/electron-client-ipc';
+import { app as electronApp } from 'electron';
+
+import { rendererDir } from '@/const/dir';
+import { isDev } from '@/const/env';
+import {
+ BUILD_CHANNEL,
+ coerceStoredUpdateChannel,
+ UPDATE_CHANNEL,
+ UPDATE_SERVER_URL,
+} from '@/modules/updater/configs';
+import { createLogger } from '@/utils/logger';
+
+import type { App } from '../../App';
+import {
+ diffManifest,
+ findMissingEntryAssets,
+ isValidManifestShape,
+ patchNumber,
+ type RendererManifest,
+ sha256File,
+ verifyManifestSignature,
+} from './manifest';
+import { emptyPointer, type OtaPointer, readPointer, writePointer } from './pointer';
+
+const logger = createLogger('core:RendererUpdateManager');
+
+const BOOT_CHECK_TIMEOUT = 15_000;
+const LOAD_PING_TIMEOUT = 3000;
+const MAX_BOOT_CRASHES = 2;
+const CHECK_INTERVAL = 60 * 60 * 1000;
+
+const MAIN_HASH = process.env.MAIN_HASH || '';
+const PUBLIC_KEY = process.env.RENDERER_OTA_PUBLIC_KEY || '';
+// Local e2e escape hatches (never set in packaged builds): force-enable in
+// dev and shorten the first scheduled check.
+const FORCE_IN_DEV = process.env['RENDERER_OTA_FORCE'] === '1';
+const FIRST_CHECK_DELAY = Number(process.env['RENDERER_OTA_CHECK_DELAY']) || 90 * 1000;
+
+type OtaState = 'idle' | 'checking' | 'downloading' | 'staged';
+type RendererOtaChannel = UpdateChannel | 'beta';
+
+export class RendererUpdateManager {
+ private readonly app: App;
+ private readonly otaRootDir: string;
+ private activeChannel: RendererOtaChannel;
+ private pointer: OtaPointer;
+ private state: OtaState = 'idle';
+ private stagedManifest: RendererManifest | null = null;
+ private bootCheckTimer: NodeJS.Timeout | null = null;
+ private loadPingTimer: NodeJS.Timeout | null = null;
+ private bootCrashCount = 0;
+ private checkTimer: NodeJS.Timeout | null = null;
+ private checkGeneration = 0;
+
+ constructor(app: App) {
+ this.app = app;
+ this.otaRootDir = path.join(electronApp.getPath('userData'), 'renderer-ota');
+ this.activeChannel = this.rendererChannel(
+ coerceStoredUpdateChannel(this.app.storeManager.get('updateChannel') as string | undefined) ||
+ UPDATE_CHANNEL,
+ );
+ this.pointer = emptyPointer(MAIN_HASH);
+ }
+
+ private get otaDir() {
+ return path.join(this.otaRootDir, this.activeChannel);
+ }
+
+ get enabled() {
+ return (!isDev || FORCE_IN_DEV) && !!MAIN_HASH && !!PUBLIC_KEY && !!UPDATE_SERVER_URL;
+ }
+
+ /**
+ * Must run before the first window loads: resolves the pointer, applies a
+ * restart-pending staged version, garbage-collects, and sets the app://
+ * serving root.
+ */
+ initialize = () => {
+ if (!this.enabled) {
+ logger.info('Renderer OTA disabled (dev build or missing MAIN_HASH/key/server url)');
+ return;
+ }
+
+ mkdirSync(path.join(this.otaDir, 'versions'), { recursive: true });
+ this.pointer = readPointer(this.otaDir, MAIN_HASH);
+
+ if (this.pointer.staged && this.versionDirValid(this.pointer.staged)) {
+ logger.info(`Applying staged renderer ${this.pointer.staged} on boot`);
+ this.promoteToCurrent(this.pointer.staged);
+ } else if (this.pointer.pendingBootCheck && this.pointer.current) {
+ // Previous session died before the boot check passed — treat as a failed boot.
+ logger.warn(`Renderer ${this.pointer.current} never passed boot check, rolling back`);
+ this.rollback();
+ }
+
+ this.gc();
+ writePointer(this.otaDir, this.pointer);
+ this.applyServingRoot();
+
+ if (this.pointer.pendingBootCheck) this.armBootCheck();
+ };
+
+ startScheduledChecks = () => {
+ if (!this.enabled) return;
+ this.checkTimer = setTimeout(() => this.checkForUpdates(), FIRST_CHECK_DELAY);
+ setInterval(() => this.checkForUpdates(), CHECK_INTERVAL);
+ };
+
+ switchChannel = (channel: UpdateChannel) => {
+ const nextChannel = this.rendererChannel(channel);
+ if (nextChannel === this.activeChannel) return;
+
+ if (!this.enabled) {
+ this.activeChannel = nextChannel;
+ return;
+ }
+
+ this.checkGeneration += 1;
+ this.clearBootTimers();
+ this.state = 'idle';
+ this.stagedManifest = null;
+ this.activeChannel = nextChannel;
+
+ mkdirSync(path.join(this.otaDir, 'versions'), { recursive: true });
+ this.pointer = readPointer(this.otaDir, MAIN_HASH);
+ if (this.pointer.pendingBootCheck) this.rollback();
+ this.state = this.pointer.staged ? 'staged' : 'idle';
+ this.gc();
+ writePointer(this.otaDir, this.pointer);
+ this.applyServingRoot();
+ this.reloadAllWindows();
+ };
+
+ handleBootPing = (stage?: 'loaded' | 'mounted') => {
+ if (!this.pointer.pendingBootCheck) return;
+
+ if (stage === 'loaded') {
+ logger.info(`Renderer ${this.pointer.current} bundle evaluated (load ping)`);
+ this.clearLoadPingTimer();
+ return;
+ }
+
+ logger.info(`Renderer ${this.pointer.current} boot check passed`);
+ this.clearBootTimers();
+ this.bootCrashCount = 0;
+ this.pointer = { ...this.pointer, pendingBootCheck: false };
+ writePointer(this.otaDir, this.pointer);
+ this.gc();
+ };
+
+ handleRendererCrash = () => {
+ if (!this.pointer.pendingBootCheck) return;
+ this.bootCrashCount += 1;
+ logger.warn(`Renderer crashed during boot check (${this.bootCrashCount}/${MAX_BOOT_CRASHES})`);
+ if (this.bootCrashCount >= MAX_BOOT_CRASHES) this.failBootCheck();
+ };
+
+ applyStagedNow = () => {
+ if (!this.pointer.staged || !this.versionDirValid(this.pointer.staged)) return false;
+ logger.info(`Applying staged renderer ${this.pointer.staged} now`);
+ this.promoteToCurrent(this.pointer.staged);
+ this.stagedManifest = null;
+ this.state = 'idle';
+ this.applyServingRoot();
+ this.reloadAllWindows();
+ // Hot apply is an in-place reload from local disk: the bundle must
+ // evaluate within seconds, so a missing load ping fails fast. Cold-boot
+ // arming (initialize) keeps only the long mount timeout.
+ this.armBootCheck({ expectFastLoad: true });
+ return true;
+ };
+
+ getStatus = () => ({
+ current: this.pointer.current,
+ enabled: this.enabled,
+ staged: this.pointer.staged,
+ state: this.state,
+ });
+
+ checkForUpdates = async () => {
+ if (!this.enabled || this.state !== 'idle') return;
+ const generation = this.checkGeneration;
+ const channel = this.activeChannel;
+ const otaDir = this.otaDir;
+ const pointer = this.pointer;
+ this.state = 'checking';
+
+ try {
+ const manifest = await this.fetchManifest(channel);
+ if (!manifest || generation !== this.checkGeneration) return;
+
+ const currentN = pointer.current ? patchNumber(pointer.current) : 0;
+ if (
+ patchNumber(manifest.version) <= currentN ||
+ pointer.blacklist.includes(manifest.version) ||
+ pointer.staged === manifest.version
+ ) {
+ return;
+ }
+
+ this.state = 'downloading';
+ await this.downloadAndStage(manifest, otaDir, pointer);
+ if (generation !== this.checkGeneration) return;
+
+ this.stagedManifest = manifest;
+ this.pointer = { ...this.pointer, staged: manifest.version };
+ writePointer(otaDir, this.pointer);
+ this.state = 'staged';
+
+ logger.info(`Renderer ${manifest.version} staged (app ${manifest.appVersion})`);
+ this.app.browserManager.broadcastToAllWindows('rendererUpdateReady', {
+ appVersion: manifest.appVersion,
+ version: manifest.version,
+ });
+ return;
+ } catch (error) {
+ if (generation === this.checkGeneration) logger.error('Renderer OTA check failed:', error);
+ rmSync(path.join(otaDir, 'staging'), { force: true, recursive: true });
+ } finally {
+ if (generation === this.checkGeneration && this.state !== 'staged') this.state = 'idle';
+ }
+ };
+
+ private rendererChannel(channel: UpdateChannel): RendererOtaChannel {
+ return BUILD_CHANNEL === 'beta' && channel === 'canary' ? 'beta' : channel;
+ }
+
+ private feedUrl(channel: RendererOtaChannel) {
+ return `${UPDATE_SERVER_URL}/renderer/${channel}/${MAIN_HASH}/latest.json`;
+ }
+
+ private fileUrl(sha256: string) {
+ return `${UPDATE_SERVER_URL}/renderer/files/${sha256}.bin`;
+ }
+
+ private async fetchManifest(channel: RendererOtaChannel): Promise<RendererManifest | null> {
+ const res = await fetch(this.feedUrl(channel), { cache: 'no-store' });
+ if (res.status === 404) return null;
+ if (!res.ok) throw new Error(`Manifest fetch failed: ${res.status}`);
+
+ const raw = await res.json();
+ if (!isValidManifestShape(raw)) throw new Error('Manifest shape invalid');
+ if (raw.mainHash !== MAIN_HASH) throw new Error('Manifest mainHash mismatch');
+ if (!verifyManifestSignature(raw, PUBLIC_KEY)) throw new Error('Manifest signature invalid');
+ return raw;
+ }
+
+ private async downloadAndStage(manifest: RendererManifest, otaDir: string, pointer: OtaPointer) {
+ const stagingRoot = path.join(otaDir, 'staging');
+ rmSync(stagingRoot, { force: true, recursive: true });
+ const stagingDir = path.join(stagingRoot, manifest.version);
+ mkdirSync(stagingDir, { recursive: true });
+
+ const { missing, reusable } = diffManifest(manifest, await this.hashLocalTree(otaDir, pointer));
+ logger.info(
+ `Renderer ${manifest.version}: ${reusable.length} files reused, ${missing.length} to download`,
+ );
+
+ for (const { file, localPath } of reusable) {
+ const target = path.join(stagingDir, file.path);
+ await mkdir(path.dirname(target), { recursive: true });
+ try {
+ await link(localPath, target);
+ } catch {
+ await copyFile(localPath, target);
+ }
+ }
+
+ for (const file of missing) {
+ const res = await fetch(this.fileUrl(file.sha256));
+ if (!res.ok) throw new Error(`Asset fetch failed (${res.status}): ${file.path}`);
+ const content = Buffer.from(await res.arrayBuffer());
+ const target = path.join(stagingDir, file.path);
+ await mkdir(path.dirname(target), { recursive: true });
+ await writeFile(target, content);
+ }
+
+ for (const file of manifest.files) {
+ const content = await readFile(path.join(stagingDir, file.path));
+ if (sha256File(content) !== file.sha256) {
+ throw new Error(`Hash mismatch after staging: ${file.path}`);
+ }
+ }
+
+ for (const entry of ['index.html', 'popup.html', 'overlay.html']) {
+ const entryHtml = await readFile(path.join(stagingDir, 'apps', 'desktop', entry), 'utf8');
+ const missingAssets = findMissingEntryAssets(entryHtml, (relPath) =>
+ existsSync(path.join(stagingDir, relPath)),
+ );
+ if (missingAssets.length > 0) {
+ throw new Error(`Entry integrity check failed (${entry}): ${missingAssets.join(', ')}`);
+ }
+ }
+
+ const finalDir = path.join(otaDir, 'versions', manifest.version);
+ rmSync(finalDir, { force: true, recursive: true });
+ renameSync(stagingDir, finalDir);
+ rmSync(stagingRoot, { force: true, recursive: true });
+ }
+
+ private async hashLocalTree(otaDir: string, pointer: OtaPointer): Promise<Map<string, string>> {
+ const root = pointer.current ? path.join(otaDir, 'versions', pointer.current) : rendererDir;
+ const hashes = new Map<string, string>();
+
+ const walk = async (dir: string) => {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) await walk(full);
+ else hashes.set(full, sha256File(await readFile(full)));
+ }
+ };
+ await walk(root);
+ return hashes;
+ }
+
+ private versionDirValid(version: string) {
+ return existsSync(path.join(this.otaDir, 'versions', version, 'apps', 'desktop', 'index.html'));
+ }
+
+ private promoteToCurrent(version: string) {
+ this.pointer = {
+ ...this.pointer,
+ current: version,
+ pendingBootCheck: true,
+ previous: this.pointer.current,
+ staged: this.pointer.staged === version ? null : this.pointer.staged,
+ };
+ writePointer(this.otaDir, this.pointer);
+ }
+
+ private rollback() {
+ const bad = this.pointer.current;
+ const fallback =
+ this.pointer.previous && this.versionDirValid(this.pointer.previous)
+ ? this.pointer.previous
+ : null;
+
+ this.pointer = {
+ ...this.pointer,
+ blacklist: bad ? [...new Set([...this.pointer.blacklist, bad])] : this.pointer.blacklist,
+ current: fallback,
+ pendingBootCheck: false,
+ previous: null,
+ };
+ writePointer(this.otaDir, this.pointer);
+ logger.warn(`Rolled back renderer to ${fallback ?? 'builtin bundle'} (blacklisted ${bad})`);
+ this.gc();
+ }
+
+ private failBootCheck() {
+ this.clearBootTimers();
+ this.rollback();
+ this.applyServingRoot();
+ this.reloadAllWindows();
+ }
+
+ private clearLoadPingTimer() {
+ if (this.loadPingTimer) clearTimeout(this.loadPingTimer);
+ this.loadPingTimer = null;
+ }
+
+ private clearBootTimers() {
+ this.clearLoadPingTimer();
+ if (this.bootCheckTimer) clearTimeout(this.bootCheckTimer);
+ this.bootCheckTimer = null;
+ }
+
+ private armBootCheck(options?: { expectFastLoad?: boolean }) {
+ this.bootCrashCount = 0;
+ this.clearBootTimers();
+
+ if (options?.expectFastLoad) {
+ this.loadPingTimer = setTimeout(() => {
+ logger.warn(`No load ping within ${LOAD_PING_TIMEOUT}ms`);
+ this.failBootCheck();
+ }, LOAD_PING_TIMEOUT);
+ this.loadPingTimer.unref?.();
+ }
+
+ this.bootCheckTimer = setTimeout(() => {
+ logger.warn(`No boot ping within ${BOOT_CHECK_TIMEOUT}ms`);
+ this.failBootCheck();
+ }, BOOT_CHECK_TIMEOUT);
+ this.bootCheckTimer.unref?.();
+ }
+
+ private applyServingRoot() {
+ const dir =
+ this.pointer.current && this.versionDirValid(this.pointer.current)
+ ? path.join(this.otaDir, 'versions', this.pointer.current)
+ : null;
+ this.app.rendererUrlManager.setActiveRendererDir(dir);
+ }
+
+ private reloadAllWindows() {
+ this.app.browserManager.browsers.forEach((browser) => {
+ try {
+ browser.browserWindow.webContents.reload();
+ } catch {
+ /* window may be destroyed */
+ }
+ });
+ }
+
+ private gc() {
+ const versionsDir = path.join(this.otaDir, 'versions');
+ const keep = new Set(
+ [this.pointer.current, this.pointer.previous, this.pointer.staged].filter(Boolean),
+ );
+
+ rmSync(path.join(this.otaDir, 'staging'), { force: true, recursive: true });
+
+ let entries;
+ try {
+ entries = readdirSync(versionsDir);
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (!keep.has(entry)) {
+ logger.debug(`GC renderer version ${entry}`);
+ rmSync(path.join(versionsDir, entry), { force: true, recursive: true });
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/RendererUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/RendererUpdateManager.int.test.ts
new file mode 100644
index 00000000000..1984438fe93
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/RendererUpdateManager.int.test.ts
@@ -0,0 +1,407 @@
+import { generateKeyPairSync, sign } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { canonicalJson, type RendererManifest, sha256File } from '../manifest';
+import { readPointer } from '../pointer';
+
+const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+const PUBLIC_KEY_PEM = publicKey.export({ format: 'pem', type: 'spki' }).toString();
+const MAIN_HASH = 'a'.repeat(64);
+const SERVER = 'https://updates.test';
+
+let userDataDir: string;
+let builtinDir: string;
+const { updaterConfigMock } = vi.hoisted(() => ({
+ updaterConfigMock: { buildChannel: 'stable' },
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: () => userDataDir },
+}));
+vi.mock('@/const/dir', () => ({
+ get rendererDir() {
+ return builtinDir;
+ },
+}));
+vi.mock('@/const/env', () => ({ isDev: false }));
+vi.mock('@/modules/updater/configs', () => ({
+ get BUILD_CHANNEL() {
+ return updaterConfigMock.buildChannel;
+ },
+ UPDATE_CHANNEL: 'stable',
+ UPDATE_SERVER_URL: 'https://updates.test',
+ coerceStoredUpdateChannel: (channel?: string) => (channel === 'canary' ? 'canary' : 'stable'),
+}));
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+}));
+
+const makeApp = () => ({
+ browserManager: { broadcastToAllWindows: vi.fn(), browsers: new Map() },
+ rendererUrlManager: { setActiveRendererDir: vi.fn() },
+ storeManager: { get: vi.fn(() => 'stable') },
+});
+
+const channelDir = (channel = 'stable') => path.join(userDataDir, 'renderer-ota', channel);
+
+const signManifest = (unsigned: Omit<RendererManifest, 'signature'>): RendererManifest => ({
+ ...unsigned,
+ signature: sign(null, Buffer.from(canonicalJson(unsigned)), privateKey).toString('base64'),
+});
+
+const entryHtml = (marker: string) =>
+ `<html><head><script type="module" src="/assets/entry-e2e.js"></script></head><body>${marker}</body></html>`;
+
+const buildFeed = (version: string, files: Record<string, string>) => {
+ const withEntries = {
+ 'apps/desktop/overlay.html': entryHtml(`${version}-overlay`),
+ 'apps/desktop/popup.html': entryHtml(`${version}-popup`),
+ ...files,
+ };
+ const cas = new Map<string, Buffer>();
+ const manifestFiles = Object.entries(withEntries).map(([filePath, text]) => {
+ const content = Buffer.from(text);
+ const sha256 = sha256File(content);
+ cas.set(sha256, content);
+ return { path: filePath, sha256, size: content.byteLength };
+ });
+ const manifest = signManifest({
+ appVersion: '1.0.0',
+ files: manifestFiles,
+ mainHash: MAIN_HASH,
+ version,
+ });
+ return { cas, manifest };
+};
+
+const stubFetch = (
+ feed: { cas: Map<string, Buffer>; manifest: RendererManifest } | null,
+ channel = 'stable',
+) => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string) => {
+ if (url === `${SERVER}/renderer/${channel}/${MAIN_HASH}/latest.json`) {
+ if (!feed) return new Response('nope', { status: 404 });
+ return Response.json(feed.manifest);
+ }
+ const match = /\/renderer\/files\/([0-9a-f]{64})\.bin$/.exec(url);
+ const content = match && feed?.cas.get(match[1]);
+ if (content) return new Response(new Uint8Array(content));
+ return new Response('nope', { status: 404 });
+ }),
+ );
+};
+
+const loadManager = async (app: ReturnType<typeof makeApp>) => {
+ vi.resetModules();
+ process.env.MAIN_HASH = MAIN_HASH;
+ process.env.RENDERER_OTA_PUBLIC_KEY = PUBLIC_KEY_PEM;
+ const { RendererUpdateManager } = await import('../RendererUpdateManager');
+ return new RendererUpdateManager(app as never);
+};
+
+beforeEach(() => {
+ updaterConfigMock.buildChannel = 'stable';
+ userDataDir = mkdtempSync(path.join(tmpdir(), 'ota-user-'));
+ builtinDir = mkdtempSync(path.join(tmpdir(), 'ota-builtin-'));
+ mkdirSync(path.join(builtinDir, 'apps', 'desktop'), { recursive: true });
+ writeFileSync(path.join(builtinDir, 'apps', 'desktop', 'index.html'), '<html>builtin</html>');
+ writeFileSync(path.join(builtinDir, 'shared.js'), 'shared-content');
+});
+
+afterEach(() => {
+ rmSync(userDataDir, { force: true, recursive: true });
+ rmSync(builtinDir, { force: true, recursive: true });
+ vi.unstubAllGlobals();
+ delete process.env.MAIN_HASH;
+ delete process.env.RENDERER_OTA_PUBLIC_KEY;
+});
+
+describe('RendererUpdateManager full path', () => {
+ it('check → incremental download → stage → apply → boot ping → gc', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ const feed = buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'assets/entry-e2e.js': 'console.log("v1")',
+ 'shared.js': 'shared-content',
+ });
+ stubFetch(feed);
+
+ await manager.checkForUpdates();
+
+ const otaDir = channelDir();
+ expect(readPointer(otaDir, MAIN_HASH).staged).toBe('r1');
+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('rendererUpdateReady', {
+ appVersion: '1.0.0',
+ version: 'r1',
+ });
+
+ const fetchedUrls = (fetch as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0]);
+ const casFetches = fetchedUrls.filter((u: string) => u.includes('/renderer/files/'));
+ expect(casFetches).toHaveLength(4);
+
+ expect(manager.applyStagedNow()).toBe(true);
+ expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenLastCalledWith(
+ path.join(otaDir, 'versions', 'r1'),
+ );
+ expect(
+ readFileSync(path.join(otaDir, 'versions', 'r1', 'apps', 'desktop', 'index.html'), 'utf8'),
+ ).toBe(entryHtml('v1'));
+ expect(readPointer(otaDir, MAIN_HASH).pendingBootCheck).toBe(true);
+
+ manager.handleBootPing();
+ const committed = readPointer(otaDir, MAIN_HASH);
+ expect(committed.pendingBootCheck).toBe(false);
+ expect(committed.current).toBe('r1');
+
+ expect(manager.getStatus().state).toBe('idle');
+ stubFetch(
+ buildFeed('r2', {
+ 'apps/desktop/index.html': entryHtml('v2'),
+ 'assets/entry-e2e.js': 'console.log("v2")',
+ }),
+ );
+ await manager.checkForUpdates();
+ expect(readPointer(otaDir, MAIN_HASH).staged).toBe('r2');
+ });
+
+ it('rejects a manifest signed by a foreign key', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ const feed = buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('evil'),
+ 'assets/entry-e2e.js': 'evil',
+ });
+ const foreign = generateKeyPairSync('ed25519').privateKey;
+ const { signature: _sig, ...unsigned } = feed.manifest;
+ feed.manifest = {
+ ...unsigned,
+ signature: sign(null, Buffer.from(canonicalJson(unsigned)), foreign).toString('base64'),
+ };
+ stubFetch(feed);
+
+ await manager.checkForUpdates();
+
+ expect(readPointer(channelDir(), MAIN_HASH).staged).toBeNull();
+ expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalled();
+ });
+
+ it('discards staging when a downloaded file is tampered', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ const feed = buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'assets/entry-e2e.js': 'console.log("v1")',
+ });
+ const [sha] = feed.cas.keys();
+ feed.cas.set(sha, Buffer.from('tampered-on-cdn'));
+ stubFetch(feed);
+
+ await manager.checkForUpdates();
+
+ const otaDir = channelDir();
+ expect(readPointer(otaDir, MAIN_HASH).staged).toBeNull();
+ expect(existsSync(path.join(otaDir, 'staging'))).toBe(false);
+ });
+
+ it('rewrites the pointer on disk when mainHash changed (new full release)', async () => {
+ const otaDir = channelDir();
+ mkdirSync(otaDir, { recursive: true });
+ writeFileSync(
+ path.join(otaDir, 'pointer.json'),
+ JSON.stringify({
+ blacklist: ['r9'],
+ current: 'r9',
+ mainHash: 'b'.repeat(64),
+ pendingBootCheck: false,
+ previous: null,
+ staged: null,
+ }),
+ );
+
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ const onDisk = JSON.parse(readFileSync(path.join(otaDir, 'pointer.json'), 'utf8'));
+ expect(onDisk.mainHash).toBe(MAIN_HASH);
+ expect(onDisk.current).toBeNull();
+ expect(onDisk.blacklist).toEqual([]);
+ expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenLastCalledWith(null);
+ });
+
+ it('rolls back and blacklists when the previous session never passed boot check', async () => {
+ const app = makeApp();
+ let manager = await loadManager(app);
+ manager.initialize();
+
+ const feed = buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'assets/entry-e2e.js': 'console.log("v1")',
+ });
+ stubFetch(feed);
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+
+ const app2 = makeApp();
+ manager = await loadManager(app2);
+ manager.initialize();
+
+ const pointer = readPointer(channelDir(), MAIN_HASH);
+ expect(pointer.current).toBeNull();
+ expect(pointer.blacklist).toContain('r1');
+ expect(app2.rendererUrlManager.setActiveRendererDir).toHaveBeenLastCalledWith(null);
+
+ await manager.checkForUpdates();
+ expect(readPointer(channelDir(), MAIN_HASH).staged).toBeNull();
+ });
+
+ it('rejects a staged tree whose entry html references a missing chunk', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ stubFetch(
+ buildFeed('r1', {
+ 'apps/desktop/index.html':
+ '<html><script type="module" src="/assets/gone.js"></script></html>',
+ }),
+ );
+
+ await manager.checkForUpdates();
+
+ const otaDir = channelDir();
+ expect(readPointer(otaDir, MAIN_HASH).staged).toBeNull();
+ expect(existsSync(path.join(otaDir, 'staging'))).toBe(false);
+ });
+
+ it('rejects a staged tree whose popup entry references a missing chunk', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ stubFetch(
+ buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'apps/desktop/popup.html':
+ '<html><script type="module" src="/assets/gone.js"></script></html>',
+ 'assets/entry-e2e.js': 'console.log("v1")',
+ }),
+ );
+
+ await manager.checkForUpdates();
+
+ const otaDir = channelDir();
+ expect(readPointer(otaDir, MAIN_HASH).staged).toBeNull();
+ expect(existsSync(path.join(otaDir, 'staging'))).toBe(false);
+ });
+
+ it('rolls back within seconds when the load ping never arrives after hot apply', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ stubFetch(
+ buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'assets/entry-e2e.js': 'throw new Error("boom")',
+ }),
+ );
+ await manager.checkForUpdates();
+
+ vi.useFakeTimers();
+ try {
+ manager.applyStagedNow();
+ vi.advanceTimersByTime(3100);
+ } finally {
+ vi.useRealTimers();
+ }
+
+ const pointer = readPointer(channelDir(), MAIN_HASH);
+ expect(pointer.current).toBeNull();
+ expect(pointer.blacklist).toContain('r1');
+ });
+
+ it('load ping defers the verdict to the mount-stage timeout', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ stubFetch(
+ buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'assets/entry-e2e.js': 'console.log("v1")',
+ }),
+ );
+ await manager.checkForUpdates();
+
+ const otaDir = channelDir();
+ vi.useFakeTimers();
+ try {
+ manager.applyStagedNow();
+ manager.handleBootPing('loaded');
+ vi.advanceTimersByTime(5000);
+ expect(readPointer(otaDir, MAIN_HASH).current).toBe('r1');
+
+ vi.advanceTimersByTime(11_000);
+ } finally {
+ vi.useRealTimers();
+ }
+
+ const pointer = readPointer(otaDir, MAIN_HASH);
+ expect(pointer.current).toBeNull();
+ expect(pointer.blacklist).toContain('r1');
+ });
+
+ it('keeps patch versions independent when the update channel changes', async () => {
+ const app = makeApp();
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ const feed = buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('v1'),
+ 'assets/entry-e2e.js': 'console.log("v1")',
+ });
+ stubFetch(feed);
+ await manager.checkForUpdates();
+ expect(readPointer(channelDir(), MAIN_HASH).staged).toBe('r1');
+
+ manager.switchChannel('canary');
+ expect(readPointer(channelDir('canary'), MAIN_HASH).staged).toBeNull();
+ expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenLastCalledWith(null);
+
+ stubFetch(feed, 'canary');
+ await manager.checkForUpdates();
+ expect(readPointer(channelDir('canary'), MAIN_HASH).staged).toBe('r1');
+ expect(readPointer(channelDir(), MAIN_HASH).staged).toBe('r1');
+ });
+
+ it('uses a dedicated beta feed for beta binaries', async () => {
+ updaterConfigMock.buildChannel = 'beta';
+ const app = makeApp();
+ app.storeManager.get.mockReturnValue('canary');
+ const manager = await loadManager(app);
+ manager.initialize();
+
+ const feed = buildFeed('r1', {
+ 'apps/desktop/index.html': entryHtml('beta'),
+ 'assets/entry-e2e.js': 'console.log("beta")',
+ });
+ stubFetch(feed, 'beta');
+ await manager.checkForUpdates();
+
+ expect(readPointer(channelDir('beta'), MAIN_HASH).staged).toBe('r1');
+ });
+});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts
new file mode 100644
index 00000000000..87dff5163dc
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts
@@ -0,0 +1,108 @@
+import { generateKeyPairSync, sign } from 'node:crypto';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ canonicalJson,
+ diffManifest,
+ isValidManifestShape,
+ patchNumber,
+ type RendererManifest,
+ verifyManifestSignature,
+} from '../manifest';
+
+const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+const publicKeyPem = publicKey.export({ format: 'pem', type: 'spki' }).toString();
+
+const signManifest = (unsigned: Omit<RendererManifest, 'signature'>): RendererManifest => ({
+ ...unsigned,
+ signature: sign(null, Buffer.from(canonicalJson(unsigned)), privateKey).toString('base64'),
+});
+
+const baseManifest = (): RendererManifest =>
+ signManifest({
+ appVersion: '1.147.0',
+ files: [
+ { path: 'apps/desktop/index.html', sha256: 'a'.repeat(64), size: 10 },
+ { path: 'assets/entry-abc.js', sha256: 'b'.repeat(64), size: 20 },
+ ],
+ mainHash: 'f'.repeat(64),
+ version: 'r3',
+ });
+
+describe('canonicalJson', () => {
+ it('sorts keys deterministically', () => {
+ expect(canonicalJson({ b: 1, a: [{ d: 2, c: 3 }] })).toBe('{"a":[{"c":3,"d":2}],"b":1}');
+ });
+});
+
+describe('verifyManifestSignature', () => {
+ it('accepts a valid signature', () => {
+ expect(verifyManifestSignature(baseManifest(), publicKeyPem)).toBe(true);
+ });
+
+ it('rejects a tampered manifest', () => {
+ const manifest = baseManifest();
+ manifest.files[0].sha256 = 'c'.repeat(64);
+ expect(verifyManifestSignature(manifest, publicKeyPem)).toBe(false);
+ });
+
+ it('rejects a foreign key', () => {
+ const other = generateKeyPairSync('ed25519')
+ .publicKey.export({ format: 'pem', type: 'spki' })
+ .toString();
+ expect(verifyManifestSignature(baseManifest(), other)).toBe(false);
+ });
+});
+
+describe('isValidManifestShape', () => {
+ it('accepts a well-formed manifest', () => {
+ expect(isValidManifestShape(baseManifest())).toBe(true);
+ });
+
+ it('rejects path traversal', () => {
+ const manifest = baseManifest();
+ manifest.files[0].path = '../evil.js';
+ expect(isValidManifestShape(manifest)).toBe(false);
+ });
+
+ it('rejects absolute paths', () => {
+ const manifest = baseManifest();
+ manifest.files[0].path = '/etc/passwd';
+ expect(isValidManifestShape(manifest)).toBe(false);
+ });
+
+ it('rejects non r<N> versions', () => {
+ expect(isValidManifestShape({ ...baseManifest(), version: '1.2.3' })).toBe(false);
+ });
+});
+
+describe('diffManifest', () => {
+ it('splits files into reusable and missing by content hash', () => {
+ const manifest = baseManifest();
+ const local = new Map([['/old/apps/desktop/index.html', 'a'.repeat(64)]]);
+
+ const { missing, reusable } = diffManifest(manifest, local);
+
+ expect(reusable).toEqual([
+ { file: manifest.files[0], localPath: '/old/apps/desktop/index.html' },
+ ]);
+ expect(missing).toEqual([manifest.files[1]]);
+ });
+
+ it('reuses by hash regardless of local path', () => {
+ const manifest = baseManifest();
+ const local = new Map([['/anywhere/renamed.js', 'b'.repeat(64)]]);
+
+ const { missing, reusable } = diffManifest(manifest, local);
+
+ expect(reusable[0].file.path).toBe('assets/entry-abc.js');
+ expect(missing).toEqual([manifest.files[0]]);
+ });
+});
+
+describe('patchNumber', () => {
+ it('parses r<N>', () => {
+ expect(patchNumber('r12')).toBe(12);
+ });
+});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pointer.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pointer.test.ts
new file mode 100644
index 00000000000..a3864ac46ca
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pointer.test.ts
@@ -0,0 +1,65 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { emptyPointer, readPointer, writePointer } from '../pointer';
+
+const HASH_A = 'a'.repeat(64);
+const HASH_B = 'b'.repeat(64);
+
+let dirs: string[] = [];
+const makeDir = () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'renderer-ota-'));
+ dirs.push(dir);
+ return dir;
+};
+
+afterEach(() => {
+ for (const dir of dirs) rmSync(dir, { force: true, recursive: true });
+ dirs = [];
+});
+
+describe('pointer', () => {
+ it('round-trips through write/read', () => {
+ const dir = makeDir();
+ const pointer = {
+ ...emptyPointer(HASH_A),
+ current: 'r2',
+ pendingBootCheck: true,
+ previous: 'r1',
+ staged: 'r3',
+ };
+
+ writePointer(dir, pointer);
+
+ expect(readPointer(dir, HASH_A)).toEqual(pointer);
+ });
+
+ it('returns an empty pointer when the file is missing', () => {
+ expect(readPointer(makeDir(), HASH_A)).toEqual(emptyPointer(HASH_A));
+ });
+
+ it('resets the lineage when mainHash changed (full release installed)', () => {
+ const dir = makeDir();
+ writePointer(dir, { ...emptyPointer(HASH_A), current: 'r5' });
+
+ expect(readPointer(dir, HASH_B)).toEqual(emptyPointer(HASH_B));
+ });
+
+ it('survives a corrupt pointer file', () => {
+ const dir = makeDir();
+ writeFileSync(path.join(dir, 'pointer.json'), '{not json');
+
+ expect(readPointer(dir, HASH_A)).toEqual(emptyPointer(HASH_A));
+ });
+
+ it('writes atomically via temp+rename', () => {
+ const dir = makeDir();
+ writePointer(dir, emptyPointer(HASH_A));
+
+ const raw = JSON.parse(readFileSync(path.join(dir, 'pointer.json'), 'utf8'));
+ expect(raw.mainHash).toBe(HASH_A);
+ });
+});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts
new file mode 100644
index 00000000000..7e38a75bf33
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts
@@ -0,0 +1,98 @@
+import { createHash, verify as cryptoVerify } from 'node:crypto';
+
+import { z } from 'zod';
+
+export const rendererManifestFileSchema = z.object({
+ path: z.string().refine((p) => !p.includes('..') && !p.startsWith('/')),
+ sha256: z.string().regex(/^[0-9a-f]{64}$/),
+ size: z.number(),
+});
+
+export const rendererManifestSchema = z.object({
+ appVersion: z.string(),
+ files: z.array(rendererManifestFileSchema),
+ mainHash: z.string(),
+ signature: z.string(),
+ version: z.string().regex(/^r\d+$/),
+});
+
+export type RendererManifestFile = z.infer<typeof rendererManifestFileSchema>;
+export type RendererManifest = z.infer<typeof rendererManifestSchema>;
+
+export const canonicalJson = (value: unknown): string => {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const entries = Object.keys(value as Record<string, unknown>)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson((value as Record<string, unknown>)[k])}`);
+ return `{${entries.join(',')}}`;
+ }
+ return JSON.stringify(value);
+};
+
+export const verifyManifestSignature = (
+ manifest: RendererManifest,
+ publicKeyPem: string,
+): boolean => {
+ const { signature, ...unsigned } = manifest;
+ if (!signature) return false;
+ try {
+ return cryptoVerify(
+ null,
+ Buffer.from(canonicalJson(unsigned)),
+ publicKeyPem,
+ Buffer.from(signature, 'base64'),
+ );
+ } catch {
+ return false;
+ }
+};
+
+export const isValidManifestShape = (value: unknown): value is RendererManifest =>
+ rendererManifestSchema.safeParse(value).success;
+
+export const patchNumber = (version: string): number => Number(version.slice(1));
+
+export const sha256File = (content: Buffer): string =>
+ createHash('sha256').update(content).digest('hex');
+
+/**
+ * Static integrity check on a staged tree's entry html: every referenced local
+ * js/css must exist, and at least one script must be referenced — a bundle
+ * whose entry chunk is missing would otherwise only surface as a boot-check
+ * timeout after the swap.
+ */
+export const findMissingEntryAssets = (
+ html: string,
+ exists: (relPath: string) => boolean,
+): string[] => {
+ const refs = [...html.matchAll(/(?:src|href)="\.?\/([^"]+\.(?:m?js|css))"/g)].map((m) => m[1]);
+ const missing = refs.filter((ref) => !exists(ref));
+ if (!refs.some((ref) => /\.m?js$/.test(ref))) missing.push('<no script referenced>');
+ return missing;
+};
+
+/** Split manifest files into reusable-from-local (by hash) and missing (to download). */
+export const diffManifest = (
+ manifest: RendererManifest,
+ localHashes: Map<string, string>,
+): {
+ missing: RendererManifestFile[];
+ reusable: Array<{ file: RendererManifestFile; localPath: string }>;
+} => {
+ const missing: RendererManifestFile[] = [];
+ const reusable: Array<{ file: RendererManifestFile; localPath: string }> = [];
+
+ const byHash = new Map<string, string>();
+ for (const [localPath, hash] of localHashes) {
+ if (!byHash.has(hash)) byHash.set(hash, localPath);
+ }
+
+ for (const file of manifest.files) {
+ const localPath = byHash.get(file.sha256);
+ if (localPath) reusable.push({ file, localPath });
+ else missing.push(file);
+ }
+
+ return { missing, reusable };
+};
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/pointer.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/pointer.ts
new file mode 100644
index 00000000000..c7534568c07
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/pointer.ts
@@ -0,0 +1,50 @@
+import { readFileSync, renameSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+export interface OtaPointer {
+ blacklist: string[];
+ current: string | null;
+ mainHash: string;
+ pendingBootCheck: boolean;
+ previous: string | null;
+ staged: string | null;
+}
+
+export const emptyPointer = (mainHash: string): OtaPointer => ({
+ blacklist: [],
+ current: null,
+ mainHash,
+ pendingBootCheck: false,
+ previous: null,
+ staged: null,
+});
+
+export const readPointer = (otaDir: string, mainHash: string): OtaPointer => {
+ try {
+ const raw = JSON.parse(readFileSync(path.join(otaDir, 'pointer.json'), 'utf8'));
+ if (
+ raw?.mainHash === mainHash &&
+ Array.isArray(raw.blacklist) &&
+ (raw.current === null || typeof raw.current === 'string')
+ ) {
+ return {
+ blacklist: raw.blacklist,
+ current: raw.current,
+ mainHash: raw.mainHash,
+ pendingBootCheck: !!raw.pendingBootCheck,
+ previous: typeof raw.previous === 'string' ? raw.previous : null,
+ staged: typeof raw.staged === 'string' ? raw.staged : null,
+ };
+ }
+ } catch {
+ /* missing or corrupt -> fresh pointer */
+ }
+ return emptyPointer(mainHash);
+};
+
+export const writePointer = (otaDir: string, pointer: OtaPointer): void => {
+ const target = path.join(otaDir, 'pointer.json');
+ const tmp = `${target}.tmp`;
+ writeFileSync(tmp, JSON.stringify(pointer, null, 2));
+ renameSync(tmp, target);
+};
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index d722c57f8d4..52d85b6eaca 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -1,10 +1,12 @@
import path from 'node:path';
import { defineConfig, type UserConfig } from 'vite';
+import zodCompiler from 'zod-compiler/vite';
import { viteOsPlatformResolve } from '../../plugins/vite/osPlatformResolve';
import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
import { getNativeExternalDependencies } from './native-deps.config.mjs';
+import { computeMainHash } from './scripts/mainHash.mjs';
import {
applyDesktopViteConfigExtension,
isCloudDesktopBuild,
@@ -110,10 +112,12 @@ export default defineConfig(async (env) => {
define: {
...processEnvDefine,
'process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS': JSON.stringify(externalNavigationHosts),
+ 'process.env.MAIN_HASH': JSON.stringify(computeMainHash()),
+ 'process.env.RENDERER_OTA_PUBLIC_KEY': JSON.stringify(process.env.RENDERER_OTA_PUBLIC_KEY),
'process.env.UPDATE_CHANNEL': JSON.stringify(process.env.UPDATE_CHANNEL),
'process.env.UPDATE_SERVER_URL': JSON.stringify(process.env.UPDATE_SERVER_URL),
},
- plugins: [viteOsPlatformResolve()],
+ plugins: [viteOsPlatformResolve(), zodCompiler()],
publicDir: false,
resolve: {
alias: mainProcessAlias,
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index c92143fc39c..83dfdfc558c 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -146,6 +146,8 @@
"updater.later": "Later",
"updater.newVersionAvailable": "New version available",
"updater.newVersionAvailableDesc": "A new version {{version}} has been found, would you like to download it now?",
+ "updater.refreshToApply": "Refresh now",
+ "updater.rendererUpdateReady": "A new version is ready — refresh to apply",
"updater.restartAndInstall": "Install updates and restart",
"updater.updateError": "Update error",
"updater.updateReady": "A new version is available",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 1c0d8ed385d..9f9861ef1c4 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -146,6 +146,8 @@
"updater.later": "稍后",
"updater.newVersionAvailable": "新版本可用",
"updater.newVersionAvailableDesc": "发现新版本 {{version}},是否立即下载?",
+ "updater.refreshToApply": "立即刷新",
+ "updater.rendererUpdateReady": "新版本已就绪,刷新即可使用",
"updater.restartAndInstall": "安装更新并重启",
"updater.updateError": "更新错误",
"updater.updateReady": "有新版本可用",
diff --git a/packages/electron-client-ipc/src/events/index.ts b/packages/electron-client-ipc/src/events/index.ts
index c108164d132..19a84fb5393 100644
--- a/packages/electron-client-ipc/src/events/index.ts
+++ b/packages/electron-client-ipc/src/events/index.ts
@@ -5,6 +5,7 @@ import type { HeterogeneousAgentBroadcastEvents } from './heterogeneousAgent';
import type { NavigationBroadcastEvents } from './navigation';
import type { ProtocolBroadcastEvents } from './protocol';
import type { RemoteServerBroadcastEvents } from './remoteServer';
+import type { RendererOtaBroadcastEvents } from './rendererOta';
import type { ScreenCaptureBroadcastEvents } from './screenCapture';
import type { SystemBroadcastEvents } from './system';
import type { TerminalBroadcastEvents } from './terminal';
@@ -25,6 +26,7 @@ export interface MainBroadcastEvents
HeterogeneousAgentBroadcastEvents,
NavigationBroadcastEvents,
RemoteServerBroadcastEvents,
+ RendererOtaBroadcastEvents,
ScreenCaptureBroadcastEvents,
SystemBroadcastEvents,
TerminalBroadcastEvents,
@@ -51,5 +53,6 @@ export type {
AuthorizationProgress,
MarketAuthorizationParams,
} from './remoteServer';
+export type { RendererOtaUpdateInfo } from './rendererOta';
export type { OverlayDispatchMessagePayload } from './screenCapture';
export type { OpenSettingsWindowOptions } from './windows';
diff --git a/packages/electron-client-ipc/src/events/rendererOta.ts b/packages/electron-client-ipc/src/events/rendererOta.ts
new file mode 100644
index 00000000000..eac5e1280ea
--- /dev/null
+++ b/packages/electron-client-ipc/src/events/rendererOta.ts
@@ -0,0 +1,8 @@
+export interface RendererOtaUpdateInfo {
+ appVersion: string;
+ version: string;
+}
+
+export interface RendererOtaBroadcastEvents {
+ rendererUpdateReady: (info: RendererOtaUpdateInfo) => void;
+}
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 55ce4bbe8df..59c9a6c271e 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -149,6 +149,8 @@ export default {
'updater.newVersionAvailable': 'New version available',
'updater.newVersionAvailableDesc':
'A new version {{version}} has been found, would you like to download it now?',
+ 'updater.refreshToApply': 'Refresh now',
+ 'updater.rendererUpdateReady': 'A new version is ready — refresh to apply',
'updater.restartAndInstall': 'Install updates and restart',
'updater.updateError': 'Update error',
'updater.updateReady': 'A new version is available',
diff --git a/src/features/Electron/updater/UpdateNotification.tsx b/src/features/Electron/updater/UpdateNotification.tsx
index fae260d97e3..d984e4ceb23 100644
--- a/src/features/Electron/updater/UpdateNotification.tsx
+++ b/src/features/Electron/updater/UpdateNotification.tsx
@@ -9,6 +9,7 @@ import React, { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { autoUpdateService } from '@/services/electron/autoUpdate';
+import { rendererOtaService } from '@/services/electron/rendererOta';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -144,6 +145,7 @@ export const UpdateNotification: React.FC = () => {
'unconfirm' | 'installLater' | 'installNow' | null
>('unconfirm');
const [isInstalling, setIsInstalling] = useState(false);
+ const [rendererUpdateReady, setRendererUpdateReady] = useState(false);
useWatchBroadcast('updateDownloaded', (info: UpdateInfo) => {
setUpdateInfo(info);
@@ -158,6 +160,35 @@ export const UpdateNotification: React.FC = () => {
setTimeout(() => setInstallConfirmMode(null), 5000);
});
+ useWatchBroadcast('rendererUpdateReady', () => {
+ setRendererUpdateReady(true);
+ });
+
+ if (rendererUpdateReady && !updateDownloaded && !updateAvailable) {
+ return (
+ <div className={styles.installLaterToast}>
+ {tElectron('updater.rendererUpdateReady')}
+ <BaseButton
+ size={'small'}
+ type={'primary'}
+ onClick={() => {
+ rendererOtaService.applyNow().catch(() => {});
+ }}
+ >
+ {tElectron('updater.refreshToApply')}
+ </BaseButton>
+ <button
+ aria-label="Close"
+ className={styles.installLaterCloseButton}
+ type="button"
+ onClick={() => setRendererUpdateReady(false)}
+ >
+ <Icon icon={X} style={{ fontSize: 14 }} />
+ </button>
+ </div>
+ );
+ }
+
if (!updateDownloaded && !updateAvailable) return null;
if (installConfirmMode === 'installLater') {
diff --git a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
index 41566ed49ca..00b745990d3 100644
--- a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
+++ b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
@@ -1,7 +1,9 @@
'use client';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
+import { useEffect } from 'react';
+import { rendererOtaService } from '@/services/electron/rendererOta';
import { useElectronStore } from '@/store/electron';
/**
@@ -23,6 +25,12 @@ const ElectronAppStateSync = () => {
useInitElectronAppState();
+ useEffect(() => {
+ // Renderer OTA boot check: main rolls back the hot-updated bundle if this
+ // ping never arrives after a swap.
+ rendererOtaService.bootPing('mounted').catch(() => {});
+ }, []);
+
useWatchBroadcast('appStateUpdated', (state) => {
updateElectronAppState(state);
});
diff --git a/src/services/electron/rendererOta.ts b/src/services/electron/rendererOta.ts
new file mode 100644
index 00000000000..d9e1c6a14dc
--- /dev/null
+++ b/src/services/electron/rendererOta.ts
@@ -0,0 +1,17 @@
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+class RendererOtaService {
+ bootPing = async (stage?: 'loaded' | 'mounted') => {
+ return ensureElectronIpc().rendererOta.bootPing(stage);
+ };
+
+ applyNow = async (): Promise<boolean> => {
+ return ensureElectronIpc().rendererOta.applyNow();
+ };
+
+ getStatus = async () => {
+ return ensureElectronIpc().rendererOta.getStatus();
+ };
+}
+
+export const rendererOtaService = new RendererOtaService();
diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsx
index 0a58fe99935..f0fe3d0e9ca 100644
--- a/src/spa/entry.desktop.tsx
+++ b/src/spa/entry.desktop.tsx
@@ -6,6 +6,7 @@ import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
import { bootTiming } from '@/libs/bootTiming';
import { registerLocalDatabaseAdapter } from '@/libs/localDatabase';
import { createElectronLocalDatabaseAdapter } from '@/libs/localDatabase/electronAdapter';
+import { rendererOtaService } from '@/services/electron/rendererOta';
import { createAppRouter } from '@/utils/router';
import BootShell from './BootShell';
@@ -15,6 +16,11 @@ import { applyDesktopBootstrapIdentity } from './initialize/desktopIdentity';
import { desktopRoutes } from './router/desktopRouter.config';
import { createSPARoot } from './runtime';
+// OTA fast-fail signal: this line running proves the whole bundle graph
+// loaded and evaluated — a broken patch never reaches it, and main rolls back
+// within seconds instead of waiting for the mount-stage timeout.
+rendererOtaService.bootPing('loaded').catch(() => {});
+
registerLocalDatabaseAdapter(createElectronLocalDatabaseAdapter());
// Must stay synchronous and ahead of the first render: `useCacheScope` reads
// `isIdentityResolved` to pick the cache partition, and on desktop preload is