🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): gzip renderer OTA CAS and keep r0 plus last-2 deltas (#18694)
Innei2fd9cfb970ba
diff --git a/.github/actions/desktop-publish-s3/action.yml b/.github/actions/desktop-publish-s3/action.ymlindex 48c31b87072..024da6a20a4 100644--- a/.github/actions/desktop-publish-s3/action.yml+++ b/.github/actions/desktop-publish-s3/action.yml@@ -199,5 +199,24 @@ runs:--arg version "$VERSION" \'{ cloudRef: $cloudRef, mainHash: $mainHash, version: $version }' \> /tmp/renderer-ota-base.json++ LATEST=$(find release/renderer-ota -name latest.json | head -n 1)+ SNAPSHOT=$(find release/renderer-ota -path '*/versions/r0.json' | head -n 1)+ if [ ! -d release/renderer-ota/files ] || [ -z "$LATEST" ] || [ -z "$SNAPSHOT" ]; then+ echo "Renderer OTA r0 artifacts are incomplete"+ exit 1+ fi++ aws s3 sync release/renderer-ota/files "s3://$S3_BUCKET/renderer/files" \+ --size-only \+ --content-encoding gzip \+ --content-type application/octet-stream \+ --cache-control public,max-age=31536000,immutable \+ $ENDPOINT_ARG+ aws s3 cp "$SNAPSHOT" "s3://$S3_BUCKET/renderer/$CHANNEL/$MAIN_HASH/versions/r0.json" \+ --cache-control no-store $ENDPOINT_ARG+ aws s3 cp "$LATEST" "s3://$S3_BUCKET/renderer/$CHANNEL/$MAIN_HASH/latest.json" \+ --cache-control no-store $ENDPOINT_ARGaws s3 cp /tmp/renderer-ota-base.json "s3://$S3_BUCKET/renderer/$CHANNEL/base.json" \--cache-control no-store $ENDPOINT_ARG+ echo "Published renderer OTA r0 for $CHANNEL/$MAIN_HASH"diff --git a/.github/actions/desktop-upload-artifacts/action.yml b/.github/actions/desktop-upload-artifacts/action.ymlindex 3b93c0bc483..8a9f5fc4f4f 100644--- a/.github/actions/desktop-upload-artifacts/action.yml+++ b/.github/actions/desktop-upload-artifacts/action.yml@@ -12,6 +12,14 @@ inputs:renderer-ota-public-key:description: Public key embedded in the packaged binaryrequired: true+ renderer-ota-private-key:+ description: Private key used to sign the r0 renderer OTA baseline+ required: false+ default: ''+ update-channel:+ description: Desktop update channel (canary, beta, stable)+ required: false+ default: ''runs:using: composite@@ -22,6 +30,22 @@ runs:RENDERER_OTA_PUBLIC_KEY: ${{ inputs.renderer-ota-public-key }}run: node apps/desktop/scripts/mainHash.mjs > apps/desktop/release/renderer-mainhash.txt+ - name: Sign renderer OTA r0 baseline+ if: runner.os == 'Linux' && inputs.renderer-ota-private-key != '' && inputs.update-channel != ''+ shell: bash+ env:+ RENDERER_OTA_PRIVATE_KEY: ${{ inputs.renderer-ota-private-key }}+ RENDERER_OTA_PUBLIC_KEY: ${{ inputs.renderer-ota-public-key }}+ run: |+ set -euo pipefail+ MAIN_HASH=$(cat apps/desktop/release/renderer-mainhash.txt)+ node apps/desktop/scripts/buildRendererManifest.mjs \+ --renderer=apps/desktop/dist/renderer \+ --out=apps/desktop/release/renderer-ota \+ --channel=${{ inputs.update-channel }} \+ --version=r0 \+ --mainHash="$MAIN_HASH"+- name: Rename macOS *-mac.yml for multi-architecture supportif: runner.os == 'macOS'shell: bash@@ -51,6 +75,7 @@ runs:uses: actions/upload-artifact@v6with:name: ${{ inputs.artifact-name }}+ if-no-files-found: warnpath: |apps/desktop/release/*.ymlapps/desktop/release/*.dmg*@@ -62,4 +87,5 @@ runs:apps/desktop/release/*.rpm*apps/desktop/release/*.tar.gz*apps/desktop/release/renderer-mainhash.txt+ apps/desktop/release/renderer-otaretention-days: ${{ inputs.retention-days }}diff --git a/.github/workflows/release-desktop-beta.yml b/.github/workflows/release-desktop-beta.ymlindex e00fe8b2cad..65dbb0489ff 100644--- a/.github/workflows/release-desktop-beta.yml+++ b/.github/workflows/release-desktop-beta.yml@@ -174,7 +174,9 @@ jobs:uses: ./.github/actions/desktop-upload-artifactswith:artifact-name: release-${{ matrix.os }}+ renderer-ota-private-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}+ update-channel: beta# 汇总门禁: test/build 完成后决定是否继续gate:diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.ymlindex 0e33959100c..f52b8093a1f 100644--- a/.github/workflows/release-desktop-canary.yml+++ b/.github/workflows/release-desktop-canary.yml@@ -338,8 +338,10 @@ jobs:uses: ./.github/actions/desktop-upload-artifactswith:artifact-name: release-${{ matrix.os }}+ renderer-ota-private-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}retention-days: 3+ update-channel: canary# ============================================# 合并 macOS 多架构 latest-mac.yml 文件diff --git a/.github/workflows/release-desktop-renderer-ota.yml b/.github/workflows/release-desktop-renderer-ota.ymlindex 1f931cffc37..326ff8a5cd9 100644--- a/.github/workflows/release-desktop-renderer-ota.yml+++ b/.github/workflows/release-desktop-renderer-ota.yml@@ -6,8 +6,10 @@ name: Release Desktop Renderer OTA# 前提: renderer/<channel>/base.json 由全量发版流程写入 (desktop-publish-s3)。# 门禁: HEAD 的 mainHash 必须等于该 marker —— main 变了只能走全量发版,# 此工作流会直接跳过。-# 产物: renderer/<channel>/<mainHash>/latest.json (签名 manifest)-# renderer/files/<sha256>.bin (内容寻址,增量上传)+# 产物: renderer/<channel>/<mainHash>/latest.json (签名 manifest + zstd tree delta)+# renderer/<channel>/<mainHash>/versions/rN.json (打下一版差分用的文件清单)+# renderer/files/<sha256>.bin (gzip CAS: 原文或 zstd --patch-from 补丁)+# delta: r0 + 最近 2 个 rN,客户端只下一份对得上的 fromVersion# ============================================on:@@ -124,13 +126,22 @@ jobs:if: steps.gate.outputs.allowed == 'true'env:RENDERER_OTA_PRIVATE_KEY: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}+ CHANNEL: ${{ inputs.channel }}+ MAIN_HASH: ${{ steps.gate.outputs.main_hash }}run: |+ set -euo pipefail+ sudo apt-get update -y+ sudo apt-get install -y zstd+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 }}+ --mainHash=${{ steps.gate.outputs.main_hash }} \+ --feed-url="$UPDATE_SERVER_URL/renderer/$CHANNEL/$MAIN_HASH" \+ --cas-base-url="$UPDATE_SERVER_URL/renderer/files"- name: Upload to S3if: steps.gate.outputs.allowed == 'true'@@ -151,9 +162,16 @@ jobs:# 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+ --size-only \+ --content-encoding gzip \+ --content-type application/octet-stream \+ --cache-control public,max-age=31536000,immutable \+ $ENDPOINT_ARGaws 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+ aws s3 cp "renderer-ota-out/$CHANNEL/$MAIN_HASH/versions/${{ steps.version.outputs.version }}.json" \+ "s3://$S3_BUCKET/renderer/$CHANNEL/$MAIN_HASH/versions/${{ steps.version.outputs.version }}.json" \+ --cache-control no-store $ENDPOINT_ARGecho "✅ 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.ymlindex ca5d5108602..b194445a303 100644--- a/.github/workflows/release-desktop-stable.yml+++ b/.github/workflows/release-desktop-stable.yml@@ -283,7 +283,9 @@ jobs:uses: ./.github/actions/desktop-upload-artifactswith:artifact-name: release-${{ matrix.name }}+ renderer-ota-private-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}+ update-channel: stable# ============================================# 合并 macOS 多架构文件diff --git a/apps/desktop/scripts/__tests__/mainHash.test.mjs b/apps/desktop/scripts/__tests__/mainHash.test.mjsindex a681efb164a..a374f73ca54 100644--- a/apps/desktop/scripts/__tests__/mainHash.test.mjs+++ b/apps/desktop/scripts/__tests__/mainHash.test.mjs@@ -62,7 +62,7 @@ describe('mainHash', () => {}});- it('shares a lineage across release versions but not verification keys', () => {+ it('starts a new lineage for each release version and verification key', () => {const packagePath = path.join(desktopRoot, 'package.json');const originalPackage = readFileSync(packagePath, 'utf8');const originalPublicKey = process.env.RENDERER_OTA_PUBLIC_KEY;@@ -70,14 +70,13 @@ describe('mainHash', () => {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);+ const nextRelease = computeMainHash();+ expect(nextRelease).not.toBe(before);process.env.RENDERER_OTA_PUBLIC_KEY = 'key-b';- expect(computeMainHash()).not.toBe(before);+ expect(computeMainHash()).not.toBe(nextRelease);} finally {writeFileSync(packagePath, originalPackage);if (originalPublicKey === undefined) delete process.env.RENDERER_OTA_PUBLIC_KEY;diff --git a/apps/desktop/scripts/__tests__/rendererDelta.test.mjs b/apps/desktop/scripts/__tests__/rendererDelta.test.mjsnew file mode 100644index 00000000000..d5b8b82e3d7--- /dev/null+++ b/apps/desktop/scripts/__tests__/rendererDelta.test.mjs@@ -0,0 +1,117 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import {+ candidateDeltaVersions,+ generateZstdPatch,+ logicalKey,+ MIN_PATCH_BYTES,+ pairRendererFiles,+} from '../rendererDelta.mjs';++const file = (filePath, sha256, size) => ({ path: filePath, sha256, size });++describe('logicalKey', () => {+ it('strips the Vite content hash so renamed chunks still pair', () => {+ expect(logicalKey('assets/es-DswPNUym.js')).toBe('assets/es.js');+ expect(logicalKey('i18n/i18n-zh-CN-BnM26YwX.js')).toBe('i18n/i18n-zh-CN.js');+ expect(logicalKey('apps/desktop/index.html')).toBe('apps/desktop/index.html');+ });+});++describe('candidateDeltaVersions', () => {+ it('lists r0 and the last two numbers below current', () => {+ expect(candidateDeltaVersions('r5')).toEqual(['r0', 'r3', 'r4']);+ expect(candidateDeltaVersions('r1')).toEqual(['r0']);+ expect(candidateDeltaVersions('r2')).toEqual(['r0', 'r1']);+ });+});++describe('pairRendererFiles', () => {+ it('copies identical hashes even when the Vite path changed', () => {+ const pairings = pairRendererFiles(+ [file('assets/entry-aaaaaaaa.js', 'aa'.repeat(32), 10)],+ [file('assets/entry-bbbbbbbb.js', 'aa'.repeat(32), 10)],+ );+ expect(pairings).toEqual([+ {+ from: file('assets/entry-aaaaaaaa.js', 'aa'.repeat(32), 10),+ kind: 'copy',+ to: file('assets/entry-bbbbbbbb.js', 'aa'.repeat(32), 10),+ },+ ]);+ });++ it('patches the same relative path when content changed', () => {+ const pairings = pairRendererFiles(+ [file('apps/desktop/index.html', 'aa'.repeat(32), 100)],+ [file('apps/desktop/index.html', 'bb'.repeat(32), 110)],+ );+ expect(pairings[0].kind).toBe('patch');+ expect(pairings[0].from.path).toBe('apps/desktop/index.html');+ });++ it('pairs Vite-renamed chunks with the closest size when hashes differ', () => {+ const pairings = pairRendererFiles(+ [+ file('assets/es-aaaaaaaa.js', '11'.repeat(32), 8_000_000),+ file('assets/es-bbbbbbbb.js', '22'.repeat(32), 2_000_000),+ ],+ [+ file('assets/es-cccccccc.js', '33'.repeat(32), 8_010_000),+ file('assets/es-dddddddd.js', '44'.repeat(32), 1_990_000),+ ],+ );+ const patches = pairings.filter((p) => p.kind === 'patch');+ expect(patches).toHaveLength(2);+ expect(patches.find((p) => p.to.size === 8_010_000).from.size).toBe(8_000_000);+ expect(patches.find((p) => p.to.size === 1_990_000).from.size).toBe(2_000_000);+ });++ it('falls back to a full download when nothing pairs', () => {+ const pairings = pairRendererFiles(+ [file('old.png', 'aa'.repeat(32), 10)],+ [file('brand-new.js', 'bb'.repeat(32), 10)],+ );+ expect(pairings).toEqual([{ kind: 'full', to: file('brand-new.js', 'bb'.repeat(32), 10) }]);+ });+});++const hasZstd = (() => {+ try {+ execFileSync('zstd', ['-V'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();++describe.skipIf(!hasZstd)('generateZstdPatch', () => {+ it('emits a tiny patch when a large file only changes a few bytes', async () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'delta-'));+ const oldPath = path.join(dir, 'old.bin');+ const newPath = path.join(dir, 'new.bin');+ const oldBuf = Buffer.alloc(MIN_PATCH_BYTES * 4, 7);+ const newBuf = Buffer.from(oldBuf);+ newBuf[100] = 9;+ writeFileSync(oldPath, oldBuf);+ writeFileSync(newPath, newBuf);++ const patch = await generateZstdPatch(oldPath, newPath, newBuf.byteLength);+ expect(patch).toBeInstanceOf(Buffer);+ expect(patch.byteLength).toBeLessThan(512);+ });++ it('skips patching files below the size floor', async () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'delta-'));+ const oldPath = path.join(dir, 'old.bin');+ const newPath = path.join(dir, 'new.bin');+ writeFileSync(oldPath, Buffer.from('old'));+ writeFileSync(newPath, Buffer.from('new'));+ await expect(generateZstdPatch(oldPath, newPath, 3)).resolves.toBeNull();+ });+});diff --git a/apps/desktop/scripts/buildRendererManifest.mjs b/apps/desktop/scripts/buildRendererManifest.mjsindex 7b341df0a94..b09817d70f5 100644--- a/apps/desktop/scripts/buildRendererManifest.mjs+++ b/apps/desktop/scripts/buildRendererManifest.mjs@@ -1,16 +1,13 @@import { createHash, generateKeyPairSync, sign } from 'node:crypto';-import {- copyFileSync,- mkdirSync,- readdirSync,- readFileSync,- statSync,- writeFileSync,-} from 'node:fs';+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import { mkdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';+import { gunzip, gzip } from 'node:zlib';import { computeMainHash } from './mainHash.mjs';+import { candidateDeltaVersions, generateZstdPatch, pairRendererFiles } from './rendererDelta.mjs';export function canonicalJson(value) {if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;@@ -54,13 +51,193 @@ export function signManifest(manifest, privateKeyPem) {return { ...manifest, signature };}-function main() {+const sha256Of = (content) => createHash('sha256').update(content).digest('hex');+const gzipAsync = promisify(gzip);+const gunzipAsync = promisify(gunzip);++const isGzipPayload = (buf) => buf.byteLength >= 2 && buf[0] === 0x1f && buf[1] === 0x8b;++const encodeCasPayload = async (raw) => Buffer.from(await gzipAsync(raw, { level: 9 }));++const decodeCasPayload = async (buf) =>+ isGzipPayload(buf) ? Buffer.from(await gunzipAsync(buf)) : buf;++const writeCasObject = async (casDir, sha256, raw) => {+ mkdirSync(casDir, { recursive: true });+ await writeFile(path.join(casDir, `${sha256}.bin`), await encodeCasPayload(raw));+};++const readTreeEntries = (dir) =>+ walk(dir)+ .map((full) => {+ const content = readFileSync(full);+ return {+ path: path.relative(dir, full).replaceAll('\\', '/'),+ sha256: sha256Of(content),+ size: content.byteLength,+ };+ })+ .sort((a, b) => (a.path < b.path ? -1 : 1));++export async function buildDelta({ fromFiles, fromVersion, resolveFromPath, toDir, toFiles }) {+ const pairings = pairRendererFiles(fromFiles, toFiles);++ const patches = new Map();+ const ops = [];++ for (const pairing of pairings) {+ if (pairing.kind === 'copy') {+ ops.push({ op: 'copy', path: pairing.to.path, sha256: pairing.to.sha256 });+ continue;+ }++ if (pairing.kind === 'full') {+ ops.push({+ op: 'full',+ path: pairing.to.path,+ sha256: pairing.to.sha256,+ size: pairing.to.size,+ });+ continue;+ }++ const oldFull = await resolveFromPath(pairing.from);+ const newFull = path.join(toDir, pairing.to.path);+ const patch = await generateZstdPatch(oldFull, newFull, pairing.to.size);+ if (!patch) {+ ops.push({+ op: 'full',+ path: pairing.to.path,+ sha256: pairing.to.sha256,+ size: pairing.to.size,+ });+ continue;+ }++ const patchSha256 = sha256Of(patch);+ patches.set(patchSha256, patch);+ ops.push({+ fromSha256: pairing.from.sha256,+ op: 'patch',+ patchSha256,+ patchSize: patch.byteLength,+ path: pairing.to.path,+ sha256: pairing.to.sha256,+ size: pairing.to.size,+ });+ }++ const downloadedBytes = ops.reduce((sum, op) => {+ if (op.op === 'patch') return sum + op.patchSize;+ if (op.op === 'full') return sum + op.size;+ return sum;+ }, 0);+ const fullBytes = toFiles.reduce((sum, file) => sum + file.size, 0);++ return {+ delta: { fromVersion, ops },+ downloadedBytes,+ fullBytes,+ patches,+ };+}++const fetchJson = async (url) => {+ const res = await fetch(url, { cache: 'no-store' });+ if (res.status === 404) return null;+ if (!res.ok) throw new Error(`fetch ${url} failed: ${res.status}`);+ return res.json();+};++const createCasResolver = (casBaseUrl, cacheDir) => {+ const base = casBaseUrl.replace(/\/$/, '');+ const cache = new Map();+ return async (file) => {+ const hit = cache.get(file.sha256);+ if (hit) return hit;+ const dest = path.join(cacheDir, `${file.sha256}.bin`);+ await mkdir(path.dirname(dest), { recursive: true });+ const res = await fetch(`${base}/${file.sha256}.bin`);+ if (!res.ok) throw new Error(`hydrate ${file.path} failed: ${res.status}`);+ await writeFile(dest, await decodeCasPayload(Buffer.from(await res.arrayBuffer())));+ cache.set(file.sha256, dest);+ return dest;+ };+};++export async function loadDeltaBases({+ casBaseUrl,+ feedUrl,+ fromDir,+ fromManifests,+ fromVersion,+ version,+}) {+ if (fromDir) {+ return {+ bases: [+ {+ files: readTreeEntries(fromDir),+ resolveFromPath: async (file) => path.join(fromDir, file.path),+ version: fromVersion ?? 'r0',+ },+ ],+ cacheDir: null,+ };+ }++ const snapshots = [];+ const seen = new Set();+ const add = (manifest) => {+ if (!manifest?.version || !Array.isArray(manifest.files) || seen.has(manifest.version)) return;+ seen.add(manifest.version);+ snapshots.push(manifest);+ };++ for (const filePath of fromManifests) {+ add(JSON.parse(readFileSync(path.resolve(filePath), 'utf8')));+ }++ if (feedUrl) {+ const feed = feedUrl.replace(/\/$/, '');+ add(await fetchJson(`${feed}/latest.json`));+ for (const target of candidateDeltaVersions(version)) {+ if (seen.has(target)) continue;+ add(await fetchJson(`${feed}/versions/${target}.json`));+ }+ }++ const selected = new Set(candidateDeltaVersions(version));+ const bases = snapshots.filter((manifest) => selected.has(manifest.version));+ if (bases.length === 0) return { bases: [], cacheDir: null };+ if (!casBaseUrl) {+ throw new Error('--cas-base-url is required to build deltas from manifests');+ }++ const { mkdtemp } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const cacheDir = await mkdtemp(path.join(tmpdir(), 'renderer-cas-'));+ const resolveFromPath = createCasResolver(casBaseUrl, cacheDir);++ return {+ bases: bases.map((manifest) => ({+ files: manifest.files,+ resolveFromPath,+ version: manifest.version,+ })),+ cacheDir,+ };+}++async function main() {+ const fromManifests = [];const args = Object.fromEntries(process.argv.slice(2).filter((a) => a.startsWith('--')).map((a) => {const [k, v] = a.slice(2).split('=');+ if (k === 'from-manifest' && v) fromManifests.push(v);return [k, v ?? true];}),);@@ -90,25 +267,62 @@ function main() {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 unsigned = buildManifest({ appVersion, mainHash, rendererDir, version });+ const { rm } = await import('node:fs/promises');++ const { bases, cacheDir } = await loadDeltaBases({+ casBaseUrl: args['cas-base-url'],+ feedUrl: args['feed-url'],+ fromDir: args['from-dir'] ? path.resolve(args['from-dir']) : null,+ fromManifests,+ fromVersion: args['from-version'],+ version,+ });++ if (bases.length > 0) {+ unsigned.deltas = [];+ const casDir = path.join(outDir, 'files');+ for (const base of bases) {+ const { delta, downloadedBytes, fullBytes, patches } = await buildDelta({+ fromFiles: base.files,+ fromVersion: base.version,+ resolveFromPath: base.resolveFromPath,+ toDir: rendererDir,+ toFiles: unsigned.files,+ });+ unsigned.deltas.push(delta);+ for (const [sha256, patch] of patches) {+ await writeCasObject(casDir, sha256, patch);+ }+ console.log(+ `renderer-ota delta ${base.version} -> ${version}: ${(downloadedBytes / 1048576).toFixed(2)} MB download vs ${(fullBytes / 1048576).toFixed(2)} MB full`,+ );+ }+ }++ if (cacheDir) await rm(cacheDir, { force: true, recursive: true });++ const manifest = signManifest(unsigned, 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);+ if (isGzipPayload(readFileSync(target))) continue;} catch {- copyFileSync(path.join(rendererDir, file.path), target);+ /* missing */}+ await writeCasObject(casDir, file.sha256, readFileSync(path.join(rendererDir, file.path)));}const feedDir = path.join(outDir, channel, mainHash);- mkdirSync(feedDir, { recursive: true });+ mkdirSync(path.join(feedDir, 'versions'), { recursive: true });writeFileSync(path.join(feedDir, 'latest.json'), JSON.stringify(manifest, null, 2));+ writeFileSync(+ path.join(feedDir, 'versions', `${version}.json`),+ JSON.stringify({ files: unsigned.files, version }, null, 2),+ );console.log(`renderer-ota manifest: ${channel}/${mainHash}/latest.json (${manifest.files.length} files, version ${version})`,@@ -116,5 +330,5 @@ function main() {}if (process.argv[1] === fileURLToPath(import.meta.url)) {- main();+ await main();}diff --git a/apps/desktop/scripts/mainHash.mjs b/apps/desktop/scripts/mainHash.mjsindex 0cfeeba652f..3f29b5bb1db 100644--- a/apps/desktop/scripts/mainHash.mjs+++ b/apps/desktop/scripts/mainHash.mjs@@ -103,7 +103,7 @@ export function computeMainHash() {const packageJson = JSON.parse(content.toString());delete packageJson.name;delete packageJson.productName;- delete packageJson.version;+ // Keep version: every full release must start a fresh renderer OTA lineage.content = Buffer.from(JSON.stringify(packageJson));}hash.update(path.relative(repoRoot, file).replaceAll('\\', '/'));diff --git a/apps/desktop/scripts/renderer-ota-test/README.md b/apps/desktop/scripts/renderer-ota-test/README.mdindex 9777b2105fa..acbf1289a95 100644--- a/apps/desktop/scripts/renderer-ota-test/README.md+++ b/apps/desktop/scripts/renderer-ota-test/README.md@@ -50,7 +50,7 @@ node scripts/renderer-ota-test/serveOta.mjs /tmp/ota-feed 8787- 等下一轮检查,或在 DevTools console 手动触发:`await window.electronAPI.invoke('rendererOta.checkNow')`-- serveOta 日志:只有 hash 变化的文件被拉取 (增量生效)+- serveOta 日志:未变文件 copy,改动走 zstd `--patch-from` 差分;原文 `.bin` 为 gzip- 应用左下角出现「新版本已就绪,刷新即可使用」toast- 点「立即刷新」: 窗口 reload (应用不重启), 改动的文案出现- `~/Library/Application Support/<dev userData>/renderer-ota/pointer.json`:diff --git a/apps/desktop/scripts/renderer-ota-test/serveOta.mjs b/apps/desktop/scripts/renderer-ota-test/serveOta.mjsindex c87c8be9d51..a0d95bf4d1f 100644--- a/apps/desktop/scripts/renderer-ota-test/serveOta.mjs+++ b/apps/desktop/scripts/renderer-ota-test/serveOta.mjs@@ -1,4 +1,4 @@-import { createReadStream, existsSync, statSync } from 'node:fs';+import { closeSync, createReadStream, existsSync, openSync, readSync, statSync } from 'node:fs';import http from 'node:http';import path from 'node:path';@@ -19,7 +19,15 @@ const server = http.createServer((req, res) => {return;}- res.writeHead(200, { 'cache-control': 'no-store' });+ const fd = openSync(file, 'r');+ const head = Buffer.alloc(2);+ const n = readSync(fd, head, 0, 2, 0);+ closeSync(fd);+ const gzip = n >= 2 && head[0] === 0x1f && head[1] === 0x8b;+ res.writeHead(200, {+ 'cache-control': 'no-store',+ ...(gzip ? { 'content-encoding': 'gzip' } : {}),+ });createReadStream(file).pipe(res);console.log(`200 ${url.pathname}`);});diff --git a/apps/desktop/scripts/rendererDelta.mjs b/apps/desktop/scripts/rendererDelta.mjsnew file mode 100644index 00000000000..9c5d9a2533b--- /dev/null+++ b/apps/desktop/scripts/rendererDelta.mjs@@ -0,0 +1,110 @@+import { execFile } from 'node:child_process';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++export const MIN_PATCH_BYTES = 16 * 1024;+const MAX_PATCH_RATIO = 0.5;+const RECENT_DELTA_KEEP = 2;++const VITE_CONTENT_HASH = /-[\w-]{8}(?=\.[^./]+$)/;++export const logicalKey = (filePath) => filePath.replace(VITE_CONTENT_HASH, '');++const versionNumber = (version) => Number(String(version).replace(/^r/, ''));++export const candidateDeltaVersions = (currentVersion) => {+ const current = versionNumber(currentVersion);+ if (!Number.isFinite(current) || current <= 0) return [];+ const nums = new Set([0]);+ for (let i = 1; i <= RECENT_DELTA_KEEP; i += 1) {+ const n = current - i;+ if (n > 0) nums.add(n);+ }+ return [...nums]+ .filter((n) => n < current)+ .sort((a, b) => a - b)+ .map((n) => `r${n}`);+};++export const pairRendererFiles = (fromFiles, toFiles) => {+ const usedFrom = new Set();+ const pairings = [];++ const fromByHash = new Map();+ for (const file of fromFiles) {+ if (!fromByHash.has(file.sha256)) fromByHash.set(file.sha256, file);+ }++ const unmatchedTo = [];+ for (const to of toFiles) {+ const from = fromByHash.get(to.sha256);+ if (from && !usedFrom.has(from.path)) {+ usedFrom.add(from.path);+ pairings.push({ from, kind: 'copy', to });+ } else {+ unmatchedTo.push(to);+ }+ }++ const remainingFrom = () => fromFiles.filter((file) => !usedFrom.has(file.path));++ const fromByPath = new Map(remainingFrom().map((file) => [file.path, file]));+ const afterPath = [];+ for (const to of unmatchedTo) {+ const from = fromByPath.get(to.path);+ if (from) {+ usedFrom.add(from.path);+ pairings.push({ from, kind: 'patch', to });+ } else {+ afterPath.push(to);+ }+ }++ const fromByKey = new Map();+ for (const file of remainingFrom()) {+ const key = logicalKey(file.path);+ const group = fromByKey.get(key) ?? [];+ group.push(file);+ fromByKey.set(key, group);+ }++ for (const to of afterPath) {+ const group = fromByKey.get(logicalKey(to.path));+ if (!group?.length) {+ pairings.push({ kind: 'full', to });+ continue;+ }+ group.sort((a, b) => Math.abs(a.size - to.size) - Math.abs(b.size - to.size));+ const from = group.shift();+ usedFrom.add(from.path);+ pairings.push({ from, kind: 'patch', to });+ }++ return pairings;+};++export const generateZstdPatch = async (oldPath, newPath, newSize) => {+ if (newSize < MIN_PATCH_BYTES) return null;++ const dir = await mkdtemp(path.join(tmpdir(), 'renderer-delta-'));+ const patchPath = path.join(dir, 'patch.zst');++ try {+ await execFileAsync(+ 'zstd',+ ['--patch-from', oldPath, '-19', '-q', '-f', newPath, '-o', patchPath],+ { timeout: 120_000 },+ );+ const patch = await readFile(patchPath);+ if (patch.byteLength === 0 || patch.byteLength >= newSize * MAX_PATCH_RATIO) return null;+ return patch;+ } catch {+ return null;+ } finally {+ await rm(dir, { force: true, recursive: true });+ }+};diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.tsindex ed04825c595..f3d1bbcfb74 100644--- a/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts@@ -16,16 +16,21 @@ import {import { createLogger } from '@/utils/logger';import type { App } from '../../App';+import { decodeCasPayload } from './casPayload';+import { canApplyDelta, indexLocalByHash, pickDelta } from './deltaFeed';import {diffManifest,findMissingEntryAssets,isValidManifestShape,patchNumber,+ type RendererDelta,type RendererManifest,+ type RendererManifestFile,sha256File,verifyManifestSignature,} from './manifest';import { emptyPointer, type OtaPointer, readPointer, writePointer } from './pointer';+import { applyZstdPatch } from './zstdPatch';const logger = createLogger('core:RendererUpdateManager');@@ -256,28 +261,20 @@ export class RendererUpdateManager {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);+ const localHashes = await this.hashLocalTree(otaDir, pointer);+ const byHash = indexLocalByHash(localHashes);+ const localVersion = pointer.current ?? 'r0';+ const delta = pickDelta(manifest, localVersion);++ if (delta && canApplyDelta(delta, byHash)) {+ logger.info(`Renderer ${manifest.version}: applying delta from ${delta.fromVersion}`);+ await this.stageDelta(delta, stagingDir, byHash);+ } else {+ const { missing, reusable } = diffManifest(manifest, localHashes);+ logger.info(+ `Renderer ${manifest.version}: ${reusable.length} files reused, ${missing.length} to download`,+ );+ await this.stageCas(stagingDir, missing, reusable);}for (const file of manifest.files) {@@ -303,6 +300,62 @@ export class RendererUpdateManager {rmSync(stagingRoot, { force: true, recursive: true });}+ private async stageCas(+ stagingDir: string,+ missing: RendererManifestFile[],+ reusable: Array<{ file: RendererManifestFile; localPath: string }>,+ ) {+ for (const { file, localPath } of reusable) {+ await this.placeLocalFile(localPath, path.join(stagingDir, file.path));+ }+ for (const file of missing) {+ await this.writeStaged(stagingDir, file.path, await this.fetchCas(file.sha256, file.path));+ }+ }++ private async stageDelta(delta: RendererDelta, stagingDir: string, byHash: Map<string, string>) {+ for (const op of delta.ops) {+ const target = path.join(stagingDir, op.path);+ if (op.op === 'copy') {+ const localPath = byHash.get(op.sha256);+ if (!localPath) throw new Error(`Delta copy missing local ${op.sha256}`);+ await this.placeLocalFile(localPath, target);+ continue;+ }+ if (op.op === 'full') {+ await this.writeStaged(stagingDir, op.path, await this.fetchCas(op.sha256, op.path));+ continue;+ }+ const localPath = byHash.get(op.fromSha256);+ if (!localPath) throw new Error(`Delta patch missing base ${op.fromSha256}`);+ const oldContent = await readFile(localPath);+ const patch = await this.fetchCas(op.patchSha256, op.path);+ const next = await applyZstdPatch(oldContent, patch);+ await this.writeStaged(stagingDir, op.path, next);+ }+ }++ private async placeLocalFile(localPath: string, target: string) {+ await mkdir(path.dirname(target), { recursive: true });+ try {+ await link(localPath, target);+ } catch {+ await copyFile(localPath, target);+ }+ }++ private async writeStaged(stagingDir: string, relPath: string, content: Buffer) {+ const target = path.join(stagingDir, relPath);+ await mkdir(path.dirname(target), { recursive: true });+ await writeFile(target, content);+ }++ private async fetchCas(sha256: string, label: string) {+ const res = await fetch(this.fileUrl(sha256));+ if (!res.ok) throw new Error(`Asset fetch failed (${res.status}): ${label}`);+ return decodeCasPayload(Buffer.from(await res.arrayBuffer()));+ }+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>();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.tsindex 1984438fe93..d4d0e287f17 100644--- 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@@ -1,7 +1,9 @@+import { execFileSync } from 'node:child_process';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 { gzipSync } from 'node:zlib';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -97,6 +99,15 @@ const stubFetch = ();};+const hasZstd = (() => {+ try {+ execFileSync('zstd', ['-V'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();+const loadManager = async (app: ReturnType<typeof makeApp>) => {vi.resetModules();process.env.MAIN_HASH = MAIN_HASH;@@ -173,6 +184,106 @@ describe('RendererUpdateManager full path', () => {expect(readPointer(otaDir, MAIN_HASH).staged).toBe('r2');});+ it.skipIf(!hasZstd)('downloads only zstd patches when a delta from r0 applies', async () => {+ const app = makeApp();+ const oldChunk = Buffer.alloc(32 * 1024, 7);+ writeFileSync(path.join(builtinDir, 'chunk.bin'), oldChunk);++ const newChunk = Buffer.from(oldChunk);+ newChunk[10] = 9;+ const dir = mkdtempSync(path.join(tmpdir(), 'ota-delta-'));+ const oldPath = path.join(dir, 'old.bin');+ const newPath = path.join(dir, 'new.bin');+ const patchPath = path.join(dir, 'patch.zst');+ writeFileSync(oldPath, oldChunk);+ writeFileSync(newPath, newChunk);+ execFileSync('zstd', ['--patch-from', oldPath, '-19', '-q', '-f', newPath, '-o', patchPath]);+ const patch = readFileSync(patchPath);++ const manager = await loadManager(app);+ manager.initialize();++ const feed = buildFeed('r1', {+ 'apps/desktop/index.html': entryHtml('v1'),+ 'assets/entry-e2e.js': 'console.log("v1")',+ 'chunk.bin': newChunk.toString('latin1'),+ 'shared.js': 'shared-content',+ });+ const chunkFile = feed.manifest.files.find((f) => f.path === 'chunk.bin');+ const sharedFile = feed.manifest.files.find((f) => f.path === 'shared.js');+ if (!chunkFile || !sharedFile) throw new Error('expected files');+ const patchSha = sha256File(patch);+ feed.cas.set(patchSha, patch);+ feed.cas.set(chunkFile.sha256, newChunk);+ const { signature: _ignored, ...unsigned } = feed.manifest;+ feed.manifest = signManifest({+ ...unsigned,+ deltas: [+ {+ fromVersion: 'r0',+ ops: [+ { op: 'copy', path: 'shared.js', sha256: sharedFile.sha256 },+ {+ fromSha256: sha256File(oldChunk),+ op: 'patch',+ patchSha256: patchSha,+ patchSize: patch.byteLength,+ path: 'chunk.bin',+ sha256: chunkFile.sha256,+ size: newChunk.byteLength,+ },+ ...feed.manifest.files+ .filter((f) => f.path !== 'shared.js' && f.path !== 'chunk.bin')+ .map((f) => ({ op: 'full' as const, path: f.path, sha256: f.sha256, size: f.size })),+ ],+ },+ ],+ });++ stubFetch(feed);+ await manager.checkForUpdates();++ 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).toContain(`${SERVER}/renderer/files/${patchSha}.bin`);+ expect(casFetches).not.toContain(`${SERVER}/renderer/files/${sharedFile.sha256}.bin`);+ expect(readPointer(channelDir(), MAIN_HASH).staged).toBe('r1');+ expect(readFileSync(path.join(channelDir(), 'versions', 'r1', 'chunk.bin'))).toEqual(newChunk);+ });++ it('accepts gzip-compressed CAS objects when Content-Encoding is missing', 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")',+ });+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (url: string) => {+ if (url === `${SERVER}/renderer/stable/${MAIN_HASH}/latest.json`) {+ 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(gzipSync(content)));+ return new Response('nope', { status: 404 });+ }),+ );++ await manager.checkForUpdates();++ expect(readPointer(channelDir(), MAIN_HASH).staged).toBe('r1');+ expect(+ readFileSync(+ path.join(channelDir(), 'versions', 'r1', 'apps', 'desktop', 'index.html'),+ 'utf8',+ ),+ ).toBe(entryHtml('v1'));+ });+it('rejects a manifest signed by a foreign key', async () => {const app = makeApp();const manager = await loadManager(app);diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/casPayload.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/casPayload.test.tsnew file mode 100644index 00000000000..6eb6f4f8fce--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/casPayload.test.ts@@ -0,0 +1,19 @@+import { gzipSync } from 'node:zlib';++import { describe, expect, it } from 'vitest';++import { decodeCasPayload } from '../casPayload';++describe('casPayload', () => {+ it('decodes gzip CAS objects back to the raw hash input', async () => {+ const raw = Buffer.from('export const x = 1;\n'.repeat(200));+ const encoded = gzipSync(raw, { level: 9 });+ expect(encoded.byteLength).toBeLessThan(raw.byteLength);+ await expect(decodeCasPayload(encoded)).resolves.toEqual(raw);+ });++ it('leaves uncompressed payloads untouched so old CAS objects still apply', async () => {+ const raw = Buffer.from('not-gzip');+ await expect(decodeCasPayload(raw)).resolves.toEqual(raw);+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/deltaFeed.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/deltaFeed.test.tsnew file mode 100644index 00000000000..73545cee0c3--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/deltaFeed.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { canApplyDelta, indexLocalByHash, pickDelta } from '../deltaFeed';+import type { RendererDelta, RendererManifest } from '../manifest';++const sha = (ch: string) => ch.repeat(64);++const manifest = (deltas?: RendererManifest['deltas']): RendererManifest => ({+ appVersion: '1.0.0',+ deltas,+ files: [{ path: 'a.js', sha256: sha('a'), size: 1 }],+ mainHash: sha('m'),+ signature: 'sig',+ version: 'r2',+});++const delta = (fromVersion: string, fromSha256: string): RendererDelta => ({+ fromVersion,+ ops: [+ {+ fromSha256,+ op: 'patch',+ patchSha256: sha('p'),+ patchSize: 10,+ path: 'a.js',+ sha256: sha('n'),+ size: 20,+ },+ ],+});++describe('pickDelta', () => {+ it('selects the delta that matches the local version', () => {+ const r0 = delta('r0', sha('o'));+ const r1 = delta('r1', sha('x'));+ expect(pickDelta(manifest([r0, r1]), 'r0')).toBe(r0);+ expect(pickDelta(manifest([r0, r1]), 'r3')).toBeUndefined();+ });+});++describe('canApplyDelta', () => {+ it('requires every copy/patch base hash to exist locally', () => {+ const d = delta('r0', sha('o'));+ expect(canApplyDelta(d, indexLocalByHash(new Map([['/old', sha('o')]])))).toBe(true);+ expect(canApplyDelta(d, indexLocalByHash(new Map([['/old', sha('z')]])))).toBe(false);+ });+});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.tsindex 87dff5163dc..5c84c6a1da7 100644--- a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts@@ -75,6 +75,28 @@ describe('isValidManifestShape', () => {it('rejects non r<N> versions', () => {expect(isValidManifestShape({ ...baseManifest(), version: '1.2.3' })).toBe(false);});++ it('accepts a signed tree delta', () => {+ const manifest = baseManifest();+ manifest.deltas = [+ {+ fromVersion: 'r0',+ ops: [+ { op: 'copy', path: 'apps/desktop/index.html', sha256: 'a'.repeat(64) },+ {+ fromSha256: 'b'.repeat(64),+ op: 'patch',+ patchSha256: 'c'.repeat(64),+ patchSize: 12,+ path: 'assets/entry-abc.js',+ sha256: 'd'.repeat(64),+ size: 20,+ },+ ],+ },+ ];+ expect(isValidManifestShape(manifest)).toBe(true);+ });});describe('diffManifest', () => {diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/zstdPatch.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/zstdPatch.test.tsnew file mode 100644index 00000000000..ec4e613a99a--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/zstdPatch.test.ts@@ -0,0 +1,35 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import { applyZstdPatch } from '../zstdPatch';++const hasZstd = (() => {+ try {+ execFileSync('zstd', ['-V'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();++describe.skipIf(!hasZstd)('applyZstdPatch', () => {+ it('reconstructs the new file from a zstd --patch-from blob', async () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'zstd-patch-'));+ const oldPath = path.join(dir, 'old.bin');+ const newPath = path.join(dir, 'new.bin');+ const patchPath = path.join(dir, 'patch.zst');+ const oldBuf = Buffer.alloc(64 * 1024, 3);+ const newBuf = Buffer.from(oldBuf);+ newBuf[200] = 42;+ writeFileSync(oldPath, oldBuf);+ writeFileSync(newPath, newBuf);+ execFileSync('zstd', ['--patch-from', oldPath, '-19', '-q', '-f', newPath, '-o', patchPath]);++ const rebuilt = await applyZstdPatch(oldBuf, readFileSync(patchPath));+ expect(Buffer.compare(rebuilt, newBuf)).toBe(0);+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/casPayload.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/casPayload.tsnew file mode 100644index 00000000000..d90ae45c77a--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/casPayload.ts@@ -0,0 +1,12 @@+import { promisify } from 'node:util';+import { gunzip } from 'node:zlib';++const gunzipAsync = promisify(gunzip);++const isGzipPayload = (buf: Buffer): boolean =>+ buf.byteLength >= 2 && buf[0] === 0x1f && buf[1] === 0x8b;++export const decodeCasPayload = async (buf: Buffer): Promise<Buffer> => {+ if (!isGzipPayload(buf)) return buf;+ return Buffer.from(await gunzipAsync(buf));+};diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/deltaFeed.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/deltaFeed.tsnew file mode 100644index 00000000000..aab4967afa3--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/deltaFeed.ts@@ -0,0 +1,22 @@+import type { RendererDelta, RendererManifest } from './manifest';++export const indexLocalByHash = (localHashes: Map<string, string>): Map<string, string> => {+ const byHash = new Map<string, string>();+ for (const [localPath, hash] of localHashes) {+ if (!byHash.has(hash)) byHash.set(hash, localPath);+ }+ return byHash;+};++export const pickDelta = (+ manifest: RendererManifest,+ localVersion: string,+): RendererDelta | undefined =>+ manifest.deltas?.find((delta) => delta.fromVersion === localVersion);++export const canApplyDelta = (delta: RendererDelta, byHash: Map<string, string>): boolean =>+ delta.ops.every((op) => {+ if (op.op === 'copy') return byHash.has(op.sha256);+ if (op.op === 'patch') return byHash.has(op.fromSha256);+ return true;+ });diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.tsindex 7e38a75bf33..2502dfb7136 100644--- a/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts@@ -2,14 +2,52 @@ import { createHash, verify as cryptoVerify } from 'node:crypto';import { z } from 'zod';+const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);+const relativePathSchema = z.string().refine((p) => !p.includes('..') && !p.startsWith('/'));+export const rendererManifestFileSchema = z.object({- path: z.string().refine((p) => !p.includes('..') && !p.startsWith('/')),- sha256: z.string().regex(/^[0-9a-f]{64}$/),+ path: relativePathSchema,+ sha256: sha256Schema,+ size: z.number(),+});++export const rendererDeltaCopyOpSchema = z.object({+ op: z.literal('copy'),+ path: relativePathSchema,+ sha256: sha256Schema,+});++export const rendererDeltaPatchOpSchema = z.object({+ fromSha256: sha256Schema,+ op: z.literal('patch'),+ patchSha256: sha256Schema,+ patchSize: z.number(),+ path: relativePathSchema,+ sha256: sha256Schema,size: z.number(),});+export const rendererDeltaFullOpSchema = z.object({+ op: z.literal('full'),+ path: relativePathSchema,+ sha256: sha256Schema,+ size: z.number(),+});++export const rendererDeltaOpSchema = z.discriminatedUnion('op', [+ rendererDeltaCopyOpSchema,+ rendererDeltaPatchOpSchema,+ rendererDeltaFullOpSchema,+]);++export const rendererDeltaSchema = z.object({+ fromVersion: z.string().regex(/^r\d+$/),+ ops: z.array(rendererDeltaOpSchema),+});+export const rendererManifestSchema = z.object({appVersion: z.string(),+ deltas: z.array(rendererDeltaSchema).optional(),files: z.array(rendererManifestFileSchema),mainHash: z.string(),signature: z.string(),@@ -17,6 +55,8 @@ export const rendererManifestSchema = z.object({});export type RendererManifestFile = z.infer<typeof rendererManifestFileSchema>;+export type RendererDeltaOp = z.infer<typeof rendererDeltaOpSchema>;+export type RendererDelta = z.infer<typeof rendererDeltaSchema>;export type RendererManifest = z.infer<typeof rendererManifestSchema>;export const canonicalJson = (value: unknown): string => {diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/zstdPatch.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/zstdPatch.tsnew file mode 100644index 00000000000..22bb1cd9b46--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/rendererOta/zstdPatch.ts@@ -0,0 +1,9 @@+import { promisify } from 'node:util';+import { zstdDecompress } from 'node:zlib';++const zstdDecompressAsync = promisify(zstdDecompress);++export const applyZstdPatch = async (oldContent: Buffer, patch: Buffer): Promise<Buffer> => {+ const out = await zstdDecompressAsync(patch, { dictionary: oldContent });+ return Buffer.from(out);+};