🤯 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): serve OTA renderer from the builtin core and object store instead of expanding it (#20214)
Innei1bab92a9deaf
diff --git a/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs b/apps/desktop/scripts/core-ota-test/coreV4.integration.mjsindex a97435efc98..69c679882d3 100644--- a/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs+++ b/apps/desktop/scripts/core-ota-test/coreV4.integration.mjs@@ -79,14 +79,24 @@ const build = async (version, contents, previousManifest) => {);return { dir, manifest };};-const stage = async (builtin, remote) =>+const stage = async (builtin, remote, current = null) =>new CoreStore(path.join(root, 'ota'), fetchImpl).stage({builtin,- current: null,+ current,packsBaseUrl: BASE,remote: remote.manifest,});describe('v4 pack OTA', () => {+ it('reuses builtin renderer content when the current version is an overlay', async () => {+ const v1 = await build('1', files);+ const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });+ const staged = await stage(v1, v5);+ const v6 = await build('6', { ...files, 'cli/new.js': Buffer.from('newer') });+ const result = await stage(v1, v6, { dir: staged.dir, manifest: v5.manifest });+ expect(result.downloaded.bytes).toBeLessThan(1000);+ expect(result.fallbackFull).toBe(false);+ });+it('builds deterministic signed packs and skips unchanged local bytes across versions', async () => {const v1 = await build('1', files);const v5 = await build('5', { ...files, 'cli/new.js': Buffer.from('new') });@@ -100,9 +110,9 @@ describe('v4 pack OTA', () => {expect(fetchImpl.mock.calls.every(([, init]) => !!new Headers(init?.headers).get('range')),).toBe(true);- expect(await readFile(path.join(result.dir, 'dist/renderer/assets/large.js'))).toEqual(- files['dist/renderer/assets/large.js'],- );+ await expect(+ readFile(path.join(result.dir, 'dist/renderer/assets/large.js')),+ ).rejects.toThrow();});it('keeps 401 small missing files incremental and coalesces a fresh tree into one request', async () => {const v1 = await build('1', files);diff --git a/apps/desktop/shell/__tests__/core-loader.test.mjs b/apps/desktop/shell/__tests__/core-loader.test.mjsindex e6f4cd95553..ac77af80c1a 100644--- a/apps/desktop/shell/__tests__/core-loader.test.mjs+++ b/apps/desktop/shell/__tests__/core-loader.test.mjs@@ -14,6 +14,9 @@ const privateKeyPem = privateKey.export({ format: 'pem', type: 'pkcs8' });const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');+const unsignedOf = (manifest) =>+ Object.fromEntries(Object.entries(manifest).filter(([key]) => key !== 'signature'));+const signManifest = (manifest) => ({...manifest,signature: sign(null, Buffer.from(canonicalJson(manifest)), privateKeyPem).toString('base64'),@@ -142,17 +145,17 @@ describe('resolveCore', () => {it('rejects a core with a missing tree file', () => {writeExternal('1.1.0', {- mutate: (dir) => fs.rmSync(path.join(dir, 'dist/renderer/index.html')),+ mutate: (dir) => fs.rmSync(path.join(dir, 'cli/lobe-cli.js')),});writePointer({ current: '1.1.0' });const core = resolve();expect(core.source).toBe('builtin');- expect(core.log.join('\n')).toContain('missing dist/renderer/index.html');+ expect(core.log.join('\n')).toContain('missing cli/lobe-cli.js');});it('accepts same-size local edits because content is hashed only while staging', () => {writeExternal('1.1.0', {- mutate: (dir) => fs.writeFileSync(path.join(dir, 'dist/renderer/index.html'), 'changed'),+ mutate: (dir) => fs.writeFileSync(path.join(dir, 'package.json'), '{"type":"commonjz"}'),});writePointer({ current: '1.1.0' });const core = resolve();@@ -160,6 +163,57 @@ describe('resolveCore', () => {expect(core.manifest.version).toBe('1.1.0');});+ describe('renderer overlay', () => {+ const storeObject = (content) => {+ const file = path.join(otaRoot(), 'store', sha256(content));+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ return file;+ };+ const overlayExternal = (renderer) =>+ writeExternal('1.1.0', {+ mutate: (dir, manifest) => {+ fs.rmSync(path.join(dir, 'dist/renderer'), { force: true, recursive: true });+ if (renderer === undefined) return;+ const entry = manifest.tree.find((file) => file.path === 'dist/renderer/index.html');+ Object.assign(entry, { sha256: sha256(renderer), size: renderer.length });+ Object.assign(manifest, signManifest(unsignedOf(manifest)));+ },+ });++ it('accepts renderer content served from the builtin core', () => {+ overlayExternal();+ writePointer({ current: '1.1.0' });+ const core = resolve();+ expect(core.source).toBe('external');+ expect(core.manifest.version).toBe('1.1.0');+ });++ it('accepts changed renderer content served from the object store', () => {+ overlayExternal('<html>new</html>');+ storeObject('<html>new</html>');+ writePointer({ current: '1.1.0' });+ expect(resolve().source).toBe('external');+ });++ it('rejects changed renderer content missing from the object store', () => {+ overlayExternal('<html>new</html>');+ writePointer({ current: '1.1.0' });+ const core = resolve();+ expect(core.source).toBe('builtin');+ expect(core.log.join('\n')).toContain('missing dist/renderer/index.html');+ });++ it('rejects a truncated object in the store', () => {+ overlayExternal('<html>new</html>');+ fs.truncateSync(storeObject('<html>new</html>'), 3);+ writePointer({ current: '1.1.0' });+ const core = resolve();+ expect(core.source).toBe('builtin');+ expect(core.log.join('\n')).toContain('size mismatch dist/renderer/index.html');+ });+ });+it.each(['../x', 'dist/main/../x', './x', '/x', 'dist\\main\\x'])('rejects a signed manifest whose tree contains %s',(unsafe) => {diff --git a/apps/desktop/shell/core-loader.js b/apps/desktop/shell/core-loader.jsindex 72bb19bac8c..e90b2f2cd24 100644--- a/apps/desktop/shell/core-loader.js+++ b/apps/desktop/shell/core-loader.js@@ -7,6 +7,7 @@ const MAX_BOOT_FAILURES = 3;const VERSION_NAME = /^[\w.+-]{1,64}$/;const UNSAFE_SEGMENT = /^\.\.?$/;const MAIN_ENTRY = 'dist/main/index.js';+const RENDERER_PREFIX = 'dist/renderer/';const canonicalJson = (value) => {if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;@@ -46,7 +47,7 @@ const writeJson = (file, value) => {fs.renameSync(`${file}.tmp`, file);};-const verifyCandidate = (dir, { abi, publicKey }) => {+const verifyCandidate = (dir, { abi, builtinHashes, publicKey, storeDir }) => {const manifest = readJson(path.join(dir, 'manifest.json'));if (!manifest) throw new Error('manifest missing or unreadable');if (!verifyManifestSignature(manifest, publicKey)) throw new Error('bad signature');@@ -65,7 +66,12 @@ const verifyCandidate = (dir, { abi, publicKey }) => {// Content hashes are verified once while staging; hashing ~110 MB here cost ~600 ms on a// cold Windows boot. Sizes still catch truncated, deleted or quarantined files.for (const file of manifest.tree) {- const stat = fs.statSync(path.join(dir, file.path), { throwIfNoEntry: false });+ const overlaid = file.path.startsWith(RENDERER_PREFIX);+ // Renderer content is never materialized: the core serves it by hash from the builtin+ // archive or the OTA object store.+ if (overlaid && builtinHashes.has(file.sha256)) continue;+ const source = overlaid ? path.join(storeDir, file.sha256) : path.join(dir, file.path);+ const stat = fs.statSync(source, { throwIfNoEntry: false });if (!stat) throw new Error(`missing ${file.path}`);if (stat.size !== file.size) throw new Error(`size mismatch ${file.path}`);}@@ -101,6 +107,10 @@ function resolveCore({ userData, builtinDir, abi, publicKey }) {const builtinManifest = readJson(path.join(builtinDir, 'manifest.json')) ?? null;const builtinSeq = typeof builtinManifest?.seq === 'number' ? builtinManifest.seq : null;+ const builtinHashes = new Set(+ Array.isArray(builtinManifest?.tree) ? builtinManifest.tree.map((file) => file.sha256) : [],+ );+ const storeDir = path.join(otaRoot, 'store');const channel = typeof pointer.channel === 'string' ? pointer.channel : builtinManifest?.channel;// seq counters are per channel: a full release ships a builtin core with a seq above every// published core of its own channel, so older external cores of that channel must not outlive it.@@ -137,7 +147,8 @@ function resolveCore({ userData, builtinDir, abi, publicKey }) {throw new Error(`invalid core version name ${JSON.stringify(version)}`);if (blacklist.includes(version)) throw new Error('blacklisted');const dir = path.join(otaRoot, 'cores', version);- if (!verified.has(version)) verified.set(version, verifyCandidate(dir, { abi, publicKey }));+ if (!verified.has(version))+ verified.set(version, verifyCandidate(dir, { abi, builtinHashes, publicKey, storeDir }));return { dir, manifest: verified.get(version) };};const verifies = (version) => {diff --git a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.tsindex 6da550f7911..8cdefc38b91 100644--- a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts@@ -1,4 +1,3 @@-import { existsSync } from 'node:fs';import { readFile, stat } from 'node:fs/promises';import path from 'node:path';@@ -7,7 +6,9 @@ import { app, protocol } from 'electron';import { createLogger } from '@/utils/logger';-type ResolveRendererFilePath = (url: URL) => Promise<string | null>;+export type RendererFile = { filePath: string; name: string };++type ResolveRendererFilePath = (url: URL) => Promise<RendererFile | null>;/*** Request interceptor: inspects an `app://` request and either produces a Response@@ -118,17 +119,11 @@ export class RendererProtocolManager {* unknown routes, and supports HTTP `Range` requests for media playback.*/export class StaticRendererFallback implements RendererFallbackStrategy {- private readonly rendererDir: string;private readonly resolveRendererFilePath: ResolveRendererFilePath;private readonly logger = createLogger('core:StaticRendererFallback');- constructor(rendererDir: string, resolveRendererFilePath: ResolveRendererFilePath) {- this.rendererDir = rendererDir;+ constructor(resolveRendererFilePath: ResolveRendererFilePath) {this.resolveRendererFilePath = resolveRendererFilePath;-- if (!existsSync(this.rendererDir)) {- this.logger.warn(`Renderer directory not found: ${this.rendererDir}`);- }}async handle(request: Request, url: URL): Promise<Response> {@@ -136,30 +131,30 @@ export class StaticRendererFallback implements RendererFallbackStrategy {const isAssetRequest = this.isAssetRequest(pathname);const isExplicit404HtmlRequest = pathname.endsWith('/404.html');- let filePath = await this.resolveRendererFilePath(url);+ let file = await this.resolveRendererFilePath(url);- if (filePath && this.is404Html(filePath) && !isExplicit404HtmlRequest) {- filePath = null;+ if (file && this.is404Html(file) && !isExplicit404HtmlRequest) {+ file = null;}- if (!filePath) {+ if (!file) {if (isAssetRequest) {return new Response('File Not Found', { status: 404 });}- filePath = await this.resolveEntryFilePath(url);- if (!filePath || this.is404Html(filePath)) {+ file = await this.resolveEntryFilePath(url);+ if (!file || this.is404Html(file)) {return new Response('Render file Not Found', { status: 404 });}}try {- return await this.buildFileResponse(request, filePath);+ return await this.buildFileResponse(request, file);} catch (error) {const code = (error as NodeJS.ErrnoException).code;if (code === 'ENOENT') {- this.logger.warn(`Export asset missing on disk ${filePath}, falling back`, error);+ this.logger.warn(`Export asset missing on disk ${file.filePath}, falling back`, error);if (isAssetRequest) {return new Response('File Not Found', { status: 404 });@@ -173,12 +168,15 @@ export class StaticRendererFallback implements RendererFallbackStrategy {try {return await this.buildFileResponse(request, fallbackPath);} catch (fallbackError) {- this.logger.error(`Failed to serve fallback entry ${fallbackPath}:`, fallbackError);+ this.logger.error(+ `Failed to serve fallback entry ${fallbackPath.filePath}:`,+ fallbackError,+ );return new Response('Internal Server Error', { status: 500 });}}- this.logger.error(`Failed to serve export asset ${filePath}:`, error);+ this.logger.error(`Failed to serve export asset ${file.filePath}:`, error);return new Response('Internal Server Error', { status: 500 });}}@@ -187,13 +185,13 @@ export class StaticRendererFallback implements RendererFallbackStrategy {return this.resolveRendererFilePath(new URL(`${url.protocol}//${url.host}/`));}- private async buildFileResponse(request: Request, targetPath: string): Promise<Response> {- const fileStat = await stat(targetPath);+ private async buildFileResponse(request: Request, file: RendererFile): Promise<Response> {+ const fileStat = await stat(file.filePath);const totalSize = fileStat.size;- const buffer = await readFile(targetPath);+ const buffer = await readFile(file.filePath);const headers = new Headers();- const mimeType = tryGetMimeType(targetPath);+ const mimeType = tryGetMimeType(file.name);if (mimeType) headers.set('Content-Type', mimeType);@@ -280,8 +278,8 @@ export class StaticRendererFallback implements RendererFallbackStrategy {);}- private is404Html(filePath: string) {- return path.basename(filePath) === '404.html';+ private is404Html(file: RendererFile) {+ return file.name === '404.html';}}diff --git a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.tsindex 18f24fdc9a5..a100fbd712b 100644--- a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts+++ b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts@@ -1,12 +1,21 @@-import { existsSync } from 'node:fs';import path from 'node:path';+import { app } from 'electron';+import { rendererDir } from '@/const/dir';import { isDev } from '@/const/env';+import { type ShellGlobal, shellInfo } from '@/const/shell';import { getDesktopEnv } from '@/env';import { createLogger } from '@/utils/logger';+import { readBuiltinManifest } from './coreOta/manifest';+import {+ dirRendererSource,+ type RendererSource,+ treeRendererSource,+} from './coreOta/rendererSource';import {+ type RendererFile,RendererProtocolManager,type RendererRequestInterceptor,StaticRendererFallback,@@ -17,16 +26,29 @@ 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('apps', 'desktop', 'index.html');-const OVERLAY_ENTRY_HTML = path.join('apps', 'desktop', 'overlay.html');-const POPUP_ENTRY_HTML = path.join('apps', 'desktop', 'popup.html');+const SPA_ENTRY_HTML = 'apps/desktop/index.html';+const OVERLAY_ENTRY_HTML = 'apps/desktop/overlay.html';+const POPUP_ENTRY_HTML = 'apps/desktop/popup.html';++// An external core ships no renderer files; its tree resolves against the builtin archive and+// the OTA object store.+const shellRendererSource = (shell: ShellGlobal | undefined = shellInfo): RendererSource => {+ if (shell?.source !== 'external' || !shell.manifest) return dirRendererSource(rendererDir);+ return treeRendererSource({+ builtinDir: shell.builtinDir,+ builtinTree: readBuiltinManifest(shell)?.tree ?? [],+ storeDir: path.join(app.getPath('userData'), 'core-ota', 'store'),+ tree: shell.manifest.tree,+ });+};export class RendererUrlManager {private readonly rendererProtocolManager: RendererProtocolManager;private readonly rendererStaticOverride = getDesktopEnv().DESKTOP_RENDERER_STATIC;private readonly rendererLoadedUrl: string;- private activeRendererDir = rendererDir;- private previousRendererDir: string | null = null;+ private readonly runningRenderer = shellRendererSource();+ private activeRenderer = this.runningRenderer;+ private previousRenderer: RendererSource | null = null;constructor() {this.rendererProtocolManager = new RendererProtocolManager({@@ -45,24 +67,23 @@ export class RendererUrlManager {}/**- * Point the static renderer at an OTA version dir (or back to the builtin- * bundle with `null`). Only takes effect between window reloads — requests+ * Point the static renderer at an OTA version (or back to the running core's+ * renderer 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;+ setActiveRenderer(source: RendererSource | null) {+ const next = source ?? this.runningRenderer;+ if (next !== this.runningRenderer && !next.resolve(SPA_ENTRY_HTML)) {+ logger.warn('OTA renderer missing entry html, falling back to the running renderer');+ this.activeRenderer = this.runningRenderer;return;}- logger.info(`Renderer serving root: ${next}`);- if (next !== this.activeRendererDir) this.previousRendererDir = this.activeRendererDir;- this.activeRendererDir = next;+ if (next !== this.activeRenderer) this.previousRenderer = this.activeRenderer;+ this.activeRenderer = next;}- getActiveRendererDir() {- return this.activeRendererDir;+ getActiveRenderer() {+ return this.activeRenderer;}/**@@ -93,34 +114,39 @@ export class RendererUrlManager {* Static assets map directly; /overlay routes fall back to overlay.html;* popup routes go to popup.html; all other routes fall back to index.html (SPA).*/- resolveRendererFilePath = async (url: URL): Promise<string | null> => {+ resolveRendererFilePath = async (url: URL): Promise<RendererFile | null> => {const pathname = url.pathname;- const root = this.activeRendererDir;// Static assets: direct file mappingif (pathname.startsWith('/assets/') || path.extname(pathname)) {- const filePath = path.join(root, pathname);- if (existsSync(filePath)) return filePath;+ const relPath = pathname.slice(1);// Windows that cancelled the OTA reload via beforeunload still lazy-load// hash-named chunks from the previous tree.- const previous = this.previousRendererDir && path.join(this.previousRendererDir, pathname);- return previous && pathname.startsWith('/assets/') && existsSync(previous) ? previous : null;+ const filePath =+ this.activeRenderer.resolve(relPath) ??+ (pathname.startsWith('/assets/') ? this.previousRenderer?.resolve(relPath) : null);+ return filePath ? { filePath, name: path.basename(pathname) } : null;}// Overlay entry (separate MPA page)if (pathname === '/overlay' || pathname === '/overlay.html') {- return path.join(root, OVERLAY_ENTRY_HTML);+ return this.resolveEntry(OVERLAY_ENTRY_HTML);}// Topic popup window has its own SPA bundle.if (pathname === '/popup' || pathname.startsWith('/popup/')) {- return path.join(root, POPUP_ENTRY_HTML);+ return this.resolveEntry(POPUP_ENTRY_HTML);}// All other routes fallback to index.html (SPA)- return path.join(root, SPA_ENTRY_HTML);+ return this.resolveEntry(SPA_ENTRY_HTML);};+ private resolveEntry(relPath: string): RendererFile | null {+ const filePath = this.activeRenderer.resolve(relPath);+ return filePath ? { filePath, name: path.basename(relPath) } : null;+ }+private pickFallback() {const electronRendererUrl = process.env['ELECTRON_RENDERER_URL'];@@ -141,6 +167,6 @@ export class RendererUrlManager {logger.warn('Dev mode: DESKTOP_RENDERER_STATIC enabled, using static renderer handler');}- return new StaticRendererFallback(rendererDir, this.resolveRendererFilePath);+ return new StaticRendererFallback(this.resolveRendererFilePath);}}diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.tsindex 8ff91736eda..29c6534e8ec 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {+ type RendererFile,RendererProtocolManager,StaticRendererFallback,ViteRendererFallback,@@ -64,8 +65,10 @@ describe('RendererProtocolManager + StaticRendererFallback', () => {protocolHandlerRef.current = null;});- const buildStaticManager = (resolve: (url: URL) => Promise<string | null>) => {- const fallback = new StaticRendererFallback('/export', resolve);+ const file = (filePath: string) => ({ filePath, name: filePath.split('/').pop()! });++ const buildStaticManager = (resolve: (url: URL) => Promise<RendererFile | null>) => {+ const fallback = new StaticRendererFallback(resolve);const manager = new RendererProtocolManager({ fallback });manager.registerHandler();return manager;@@ -73,8 +76,8 @@ describe('RendererProtocolManager + StaticRendererFallback', () => {it('falls back to entry HTML when resolve returns 404.html for non-asset routes', async () => {const resolveRendererFilePath = vi.fn(async (url: URL) => {- if (url.pathname === '/missing') return '/export/404.html';- if (url.pathname === '/') return '/export/index.html';+ if (url.pathname === '/missing') return file('/export/404.html');+ if (url.pathname === '/') return file('/export/index.html');return null;});mockReadFile.mockImplementation(async (path: string) => Buffer.from(`content:${path}`));@@ -101,8 +104,8 @@ describe('RendererProtocolManager + StaticRendererFallback', () => {it('serves 404.html when explicitly requested', async () => {const resolveRendererFilePath = vi.fn(async (url: URL) => {- if (url.pathname === '/404.html') return '/export/404.html';- if (url.pathname === '/') return '/export/index.html';+ if (url.pathname === '/404.html') return file('/export/404.html');+ if (url.pathname === '/') return file('/export/index.html');return null;});mockReadFile.mockImplementation(async (path: string) => Buffer.from(`content:${path}`));@@ -138,7 +141,7 @@ describe('RendererProtocolManager + StaticRendererFallback', () => {});it('supports Range requests for media assets', async () => {- const resolveRendererFilePath = vi.fn(async (_url: URL) => '/export/intro-video.mp4');+ const resolveRendererFilePath = vi.fn(async (_url: URL) => file('/export/intro-video.mp4'));const payload = Buffer.from('0123456789');mockStat.mockImplementation(async () => ({ size: payload.length }));@@ -163,11 +166,32 @@ describe('RendererProtocolManager + StaticRendererFallback', () => {expect(buf.toString()).toBe('01');});+ it('derives Content-Type from the logical name when the stored file has no extension', async () => {+ const resolveRendererFilePath = vi.fn(async () => ({+ filePath: '/core-ota/store/abc123',+ name: 'chunk.js',+ }));+ mockReadFile.mockImplementation(async () => Buffer.from('export {}'));++ buildStaticManager(resolveRendererFilePath);+ const handler = protocolHandlerRef.current;++ const response = await handler({+ headers: new Headers(),+ method: 'GET',+ url: 'app://renderer/assets/chunk.js',+ } as any);++ expect(response.status).toBe(200);+ expect(mockReadFile).toHaveBeenCalledWith('/core-ota/store/abc123');+ expect(response.headers.get('Content-Type')).toMatch(/javascript/);+ });+it('runs interceptors before the fallback and short-circuits on first non-null Response', async () => {- const resolveRendererFilePath = vi.fn(async () => '/export/index.html');+ const resolveRendererFilePath = vi.fn(async () => file('/export/index.html'));mockReadFile.mockImplementation(async () => Buffer.from('static'));- const fallback = new StaticRendererFallback('/export', resolveRendererFilePath);+ const fallback = new StaticRendererFallback(resolveRendererFilePath);const manager = new RendererProtocolManager({ fallback });manager.addRequestInterceptor(async () => null);@@ -199,7 +223,7 @@ describe('RendererProtocolManager + StaticRendererFallback', () => {});it('returns 404 for cross-host requests', async () => {- const resolveRendererFilePath = vi.fn(async () => '/export/index.html');+ const resolveRendererFilePath = vi.fn(async () => file('/export/index.html'));buildStaticManager(resolveRendererFilePath);const handler = protocolHandlerRef.current;diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.tsindex b07d4a1f975..ba1a169e981 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts@@ -58,7 +58,10 @@ describe('RendererUrlManager', () => {new URL('app://renderer/en-US__0__light.txt'),);- expect(resolved).toBe('/mock/export/out/en-US__0__light.txt');+ expect(resolved).toEqual({+ filePath: '/mock/export/out/en-US__0__light.txt',+ name: 'en-US__0__light.txt',+ });});it('should fall back to index.html for app routes', async () => {@@ -71,7 +74,58 @@ describe('RendererUrlManager', () => {const resolved = await manager.resolveRendererFilePath(new URL('app://renderer/settings'));- expect(resolved).toBe('/mock/export/out/apps/desktop/index.html');+ expect(resolved).toEqual({+ filePath: '/mock/export/out/apps/desktop/index.html',+ name: 'index.html',+ });+ });+ });++ describe('setActiveRenderer', () => {+ const otaSource = {+ resolve: (relPath: string) =>+ ['apps/desktop/index.html', 'assets/new.js'].includes(relPath) ? `/ota/${relPath}` : null,+ };++ it('serves an OTA source and keeps old chunks reachable from the previous source', async () => {+ const { RendererUrlManager } = await import('../RendererUrlManager');+ const manager = new RendererUrlManager();+ mockPathExistsSync.mockImplementation((p: string) => p === '/mock/export/out/assets/old.js');++ manager.setActiveRenderer(otaSource);++ expect(manager.getActiveRenderer()).toBe(otaSource);+ expect(await manager.resolveRendererFilePath(new URL('app://renderer/settings'))).toEqual({+ filePath: '/ota/apps/desktop/index.html',+ name: 'index.html',+ });+ expect(+ await manager.resolveRendererFilePath(new URL('app://renderer/assets/new.js')),+ ).toEqual({ filePath: '/ota/assets/new.js', name: 'new.js' });+ expect(+ await manager.resolveRendererFilePath(new URL('app://renderer/assets/old.js')),+ ).toEqual({ filePath: '/mock/export/out/assets/old.js', name: 'old.js' });+ });++ it('keeps the running renderer when the source has no entry HTML', async () => {+ const { RendererUrlManager } = await import('../RendererUrlManager');+ const manager = new RendererUrlManager();+ const running = manager.getActiveRenderer();++ manager.setActiveRenderer({ resolve: () => null });++ expect(manager.getActiveRenderer()).toBe(running);+ });++ it('returns to the running renderer for null', async () => {+ const { RendererUrlManager } = await import('../RendererUrlManager');+ const manager = new RendererUrlManager();+ const running = manager.getActiveRenderer();++ manager.setActiveRenderer(otaSource);+ manager.setActiveRenderer(null);++ expect(manager.getActiveRenderer()).toBe(running);});});diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.tsindex b95017a25a3..e724af5827f 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts@@ -19,12 +19,13 @@ import { createLogger } from '@/utils/logger';import type { App } from '../../App';import { type ApplyMode, computeApplyMode } from './applyMode';import {- builtinManifestSchema,type CoreManifest,coreManifestSchema,+ readBuiltinManifest,verifyManifestSignature,} from './manifest';import { type CorePointer, emptyPointer, readPointer, writePointer } from './pointer';+import { type RendererSource, treeRendererSource } from './rendererSource';import { cleanupLegacy, CoreStore } from './store';const logger = createLogger('core:CoreUpdateManager');@@ -38,7 +39,6 @@ const MAX_BOOT_CRASHES = 2;const CHECK_INTERVAL = 60 * 60 * 1000;const FIRST_CHECK_DELAY = Number(process.env['RENDERER_OTA_CHECK_DELAY']) || 0;const IDLE_APPLY_DELAY = 5 * 60 * 1000;-const RENDERER_ROOT = 'dist/renderer';const FEED_BASE_URL =UPDATE_SERVER_URL?.replace(/\/(stable|nightly|canary|beta)\/?$/, '').replace(/\/$/, '') || '';@@ -47,16 +47,6 @@ type CoreChannel = CoreManifest['channel'];type Staged = { applyMode: ApplyMode; version: string };type Options = { fetchImpl?: FetchImpl; shell?: ShellGlobal };-const readBuiltinManifest = (shell: ShellGlobal): CoreManifest | null => {- if (shell.source === 'builtin') return shell.manifest;- try {- const raw = JSON.parse(readFileSync(path.join(shell.builtinDir, 'manifest.json'), 'utf8'));- return builtinManifestSchema.parse(raw);- } catch {- return null;- }-};-class SkipCheck extends Error {}export class CoreUpdateManager {@@ -76,7 +66,7 @@ export class CoreUpdateManager {private lastError: string | null = null;private needsFullRelease = false;private unloadPrevented = false;- private rollbackRendererDir: string | null = null;+ private rollbackRenderer: RendererSource | null = null;private pendingBootCheck = false;private coldBootCheck = false;private deferredColdBootCheck = false;@@ -225,7 +215,7 @@ export class CoreUpdateManager {this.pendingBootCheck = false;this.deferredColdBootCheck = false;this.bootCrashCount = 0;- this.rollbackRendererDir = null;+ this.rollbackRenderer = null;this.gc();if (shouldRunDeferredCheck) this.checkForUpdates();};@@ -243,7 +233,7 @@ export class CoreUpdateManager {logger.info('Reload cancelled by renderer, cancelling boot check');this.clearBootTimers();this.pendingBootCheck = false;- this.rollbackRendererDir = null;+ this.rollbackRenderer = null;};applyStagedNow = () => {@@ -254,13 +244,13 @@ export class CoreUpdateManager {}const { version } = this.staged;logger.info(`Applying core ${version} renderer now`);- const rendererDir = this.rendererDirOf(version);- this.rollbackRendererDir = this.app.rendererUrlManager.getActiveRendererDir();- this.app.rendererUrlManager.setActiveRendererDir(rendererDir);- if (this.app.rendererUrlManager.getActiveRendererDir() !== rendererDir) {- logger.warn('Core OTA staged apply rejected', { reason: 'renderer-dir-unusable', version });- this.app.rendererUrlManager.setActiveRendererDir(this.rollbackRendererDir);- this.rollbackRendererDir = null;+ const renderer = this.rendererSourceOf(version);+ this.rollbackRenderer = this.app.rendererUrlManager.getActiveRenderer();+ if (renderer) this.app.rendererUrlManager.setActiveRenderer(renderer);+ if (!renderer || this.app.rendererUrlManager.getActiveRenderer() !== renderer) {+ logger.warn('Core OTA staged apply rejected', { reason: 'renderer-unusable', version });+ this.app.rendererUrlManager.setActiveRenderer(this.rollbackRenderer);+ this.rollbackRenderer = null;this.savePointer({blacklist: [...new Set([...this.pointer.blacklist, version])],staged: null,@@ -433,8 +423,21 @@ export class CoreUpdateManager {return path.join(this.otaRoot, 'cores', version);}- private rendererDirOf(version: string) {- return path.join(this.coreDirOf(version), RENDERER_ROOT);+ private rendererSourceOf(version: string): RendererSource | null {+ try {+ const manifest = coreManifestSchema.parse(+ JSON.parse(readFileSync(path.join(this.coreDirOf(version), 'manifest.json'), 'utf8')),+ );+ return treeRendererSource({+ builtinDir: this.shell!.builtinDir,+ builtinTree: this.builtinManifest!.tree,+ storeDir: path.join(this.otaRoot, 'store'),+ tree: manifest.tree,+ });+ } catch (error) {+ logger.warn(`Cannot read core ${version} manifest`, error);+ return null;+ }}private savePointer(patch: Partial<CorePointer>) {@@ -494,8 +497,8 @@ export class CoreUpdateManager {this.relaunchIntoCore();return;}- this.app.rendererUrlManager.setActiveRendererDir(this.rollbackRendererDir);- this.rollbackRendererDir = null;+ this.app.rendererUrlManager.setActiveRenderer(this.rollbackRenderer);+ this.rollbackRenderer = null;this.gc();this.reloadAllWindows();}diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.tsindex 322635b86a5..5f81b53f8ae 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts@@ -19,6 +19,7 @@ import type { ShellGlobal } from '@/const/shell';import { canonicalJson, type CoreManifestV3 as CoreManifest, sha256File } from '../manifest';import { readPointer, writePointer } from '../pointer';+import type { RendererSource } from '../rendererSource';import { SAFE_VERSION } from '../store';const { privateKey, publicKey } = generateKeyPairSync('ed25519');@@ -76,12 +77,15 @@ const makeApp = () => ({},isQuiting: false,rendererUrlManager: {- activeDir: null as string | null,- getActiveRendererDir() {- return this.activeDir;+ activeRenderer: null as RendererSource | null,+ getActiveRenderer() {+ return this.activeRenderer;},- setActiveRendererDir: vi.fn(function (this: { activeDir: string | null }, dir: string | null) {- this.activeDir = dir;+ setActiveRenderer: vi.fn(function (+ this: { activeRenderer: RendererSource | null },+ source: RendererSource | null,+ ) {+ this.activeRenderer = source;}),},storeManager: { get: vi.fn(() => 'stable') },@@ -187,6 +191,12 @@ const loadManager = async (app = makeApp(), shell: ShellGlobal | null = makeShelreturn { app, manager };};+const expectAppliedRenderer = (app: ReturnType<typeof makeApp>, indexContent: string) => {+ const renderer = app.rendererUrlManager.setActiveRenderer.mock.calls.at(-1)?.[0];+ expect(readFileSync(renderer!.resolve('assets/index.js')!, 'utf8')).toBe(indexContent);+ expect(readFileSync(renderer!.resolve('assets/popup.js')!, 'utf8')).toBe('popup');+};+const flushGc = () => new Promise((resolve) => setTimeout(resolve, 20));let builtinManifest: CoreManifest;@@ -390,7 +400,7 @@ describe('CoreUpdateManager initialize', () => {expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: ['1.0.1'], current: null });expect(electronMock.app.relaunch).toHaveBeenCalled();- expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();+ expect(app.rendererUrlManager.setActiveRenderer).not.toHaveBeenCalled();} finally {vi.useRealTimers();}@@ -575,7 +585,7 @@ describe('CoreUpdateManager checkForUpdates', () => {const remote = rendererOnly('1.0.1', 1);serveLatest(remote);const { app, manager } = await loadManager();- app.rendererUrlManager.activeDir = path.join(builtinDir, 'dist/renderer');+ app.rendererUrlManager.activeRenderer = { resolve: () => null };await manager.checkForUpdates();@@ -585,13 +595,14 @@ describe('CoreUpdateManager checkForUpdates', () => {version: '1.0.1',});expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: null, staged: '1.0.1' });- expect(existsSync(path.join(coreDir('1.0.1'), 'dist/renderer/assets/index.js'))).toBe(true);+ expect(existsSync(path.join(coreDir('1.0.1'), 'dist/renderer'))).toBe(false);+ expect(+ readFileSync(path.join(storeDir(), sha256File(Buffer.from('index-1.0.1'))), 'utf8'),+ ).toBe('index-1.0.1');expect(manager.applyStagedNow()).toBe(true);- expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenCalledWith(- path.join(coreDir('1.0.1'), 'dist/renderer'),- );+ expectAppliedRenderer(app, 'index-1.0.1');expect(readPointer(otaRoot(), ABI)).toMatchObject({current: '1.0.1',previous: null,@@ -603,13 +614,13 @@ describe('CoreUpdateManager checkForUpdates', () => {expect(reload).toHaveBeenCalledTimes(1);});- it('reuses the active renderer version after a reload even without its object cache', async () => {+ it('reuses the active renderer version content after a reload without downloading it', async () => {serveLatest(rendererOnly('1.0.1', 1));const { manager } = await loadManager();await manager.checkForUpdates();manager.applyStagedNow();manager.handleBootPing('mounted');- rmSync(storeDir(), { recursive: true, force: true });+ await flushGc();const reused = 'index-1.0.1';serveLatest(buildManifest('1.0.5', 5, {@@ -624,7 +635,7 @@ describe('CoreUpdateManager checkForUpdates', () => {expect(fetchImpl.mock.calls.some(([url]) => url.includes(sha256File(Buffer.from(reused)))),).toBe(false);- expect(readFileSync(path.join(coreDir('1.0.5'), 'dist/renderer/assets/index.js'), 'utf8')).toBe(+ expect(readFileSync(path.join(storeDir(), sha256File(Buffer.from(reused))), 'utf8')).toBe(reused,);});@@ -669,21 +680,21 @@ describe('CoreUpdateManager checkForUpdates', () => {expect(electronMock.app.releaseSingleInstanceLock).toHaveBeenCalled();expect(electronMock.app.relaunch).toHaveBeenCalled();expect(electronMock.app.quit).toHaveBeenCalled();- expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();+ expect(app.rendererUrlManager.setActiveRenderer).not.toHaveBeenCalled();});it('rolls back and blacklists the version when the boot check fails', async () => {serveLatest(rendererOnly('1.0.1', 1));const { app, manager } = await loadManager();- const builtinRenderer = path.join(builtinDir, 'dist/renderer');- app.rendererUrlManager.activeDir = builtinRenderer;+ const builtinRenderer = { resolve: () => null };+ app.rendererUrlManager.activeRenderer = builtinRenderer;await manager.checkForUpdates();manager.applyStagedNow();manager.handleRendererCrash();manager.handleRendererCrash();- expect(app.rendererUrlManager.activeDir).toBe(builtinRenderer);+ expect(app.rendererUrlManager.activeRenderer).toBe(builtinRenderer);expect(readPointer(otaRoot(), ABI)).toMatchObject({blacklist: ['1.0.1'],current: null,@@ -790,20 +801,16 @@ describe('CoreUpdateManager checkForUpdates', () => {}});- it('refuses to apply when the staged renderer dir is unusable', async () => {+ it('refuses to apply when the staged core manifest is unreadable', async () => {serveLatest(rendererOnly('1.0.1', 1));const { app, manager } = await loadManager();await manager.checkForUpdates();- rmSync(path.join(coreDir('1.0.1'), 'dist/renderer/apps/desktop/index.html'));- app.rendererUrlManager.setActiveRendererDir = vi.fn(function (- this: { activeDir: string | null },- dir,- ) {- this.activeDir = dir && existsSync(path.join(dir, 'apps/desktop/index.html')) ? dir : null;- });+ rmSync(path.join(coreDir('1.0.1'), 'manifest.json'));expect(manager.applyStagedNow()).toBe(false);+ expect(app.rendererUrlManager.getActiveRenderer()).toBeNull();+expect(readPointer(otaRoot(), ABI)).toMatchObject({blacklist: ['1.0.1'],current: null,@@ -834,12 +841,10 @@ describe('CoreUpdateManager checkForUpdates', () => {await manager.checkForUpdates();vi.advanceTimersByTime(5 * 60 * 1000 - 1);- expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();+ expect(app.rendererUrlManager.setActiveRenderer).not.toHaveBeenCalled();vi.advanceTimersByTime(1);- expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenCalledWith(- path.join(coreDir('1.0.1'), 'dist/renderer'),- );+ expectAppliedRenderer(app, 'index-1.0.1');} finally {vi.useRealTimers();}@@ -861,12 +866,12 @@ describe('CoreUpdateManager checkForUpdates', () => {focus();vi.advanceTimersByTime(6 * 60 * 1000);- expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();+ expect(app.rendererUrlManager.setActiveRenderer).not.toHaveBeenCalled();manager.handleUnloadPrevented();blur();vi.advanceTimersByTime(6 * 60 * 1000);- expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();+ expect(app.rendererUrlManager.setActiveRenderer).not.toHaveBeenCalled();} finally {vi.useRealTimers();}@@ -883,9 +888,7 @@ describe('CoreUpdateManager checkForUpdates', () => {vi.advanceTimersByTime(5 * 60 * 1000);- expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenCalledWith(- path.join(coreDir('1.0.1'), 'dist/renderer'),- );+ expectAppliedRenderer(app, 'index-1.0.1');} finally {vi.useRealTimers();}diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/rendererSource.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/rendererSource.test.tsnew file mode 100644index 00000000000..d25dabbcdff--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/rendererSource.test.ts@@ -0,0 +1,76 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { dirRendererSource, treeRendererSource } from '../rendererSource';++const entry = (filePath: string, sha: string) => ({ path: filePath, sha256: sha, size: 1 });++describe('treeRendererSource', () => {+ const source = treeRendererSource({+ builtinDir: '/app/core.asar',+ builtinTree: [+ entry('dist/renderer/assets/same.js', 'a'.repeat(64)),+ entry('dist/renderer/assets/old-name.js', 'b'.repeat(64)),+ entry('dist/main/index.js', 'm'.repeat(64)),+ ],+ storeDir: '/ota/store',+ tree: [+ entry('dist/renderer/assets/same.js', 'a'.repeat(64)),+ entry('dist/renderer/assets/renamed.js', 'b'.repeat(64)),+ entry('dist/renderer/assets/changed.js', 'c'.repeat(64)),+ entry('dist/renderer/assets/(home)-x.js', 'd'.repeat(64)),+ entry('dist/renderer/apps/desktop/index.html', 'e'.repeat(64)),+ entry('dist/main/index.js', 'f'.repeat(64)),+ ],+ });++ it('reads unchanged content from the builtin archive', () => {+ expect(source.resolve('assets/same.js')).toBe(+ path.join('/app/core.asar', 'dist/renderer/assets/same.js'),+ );+ });++ it('matches builtin content by hash even when the path moved', () => {+ expect(source.resolve('assets/renamed.js')).toBe(+ path.join('/app/core.asar', 'dist/renderer/assets/old-name.js'),+ );+ });++ it('reads changed content from the object store', () => {+ expect(source.resolve('assets/changed.js')).toBe(path.join('/ota/store', 'c'.repeat(64)));+ });++ it('accepts URL-encoded and Windows-style relative paths', () => {+ expect(source.resolve('assets/%28home%29-x.js')).toBe(path.join('/ota/store', 'd'.repeat(64)));+ expect(source.resolve('apps\\desktop\\index.html')).toBe(+ path.join('/ota/store', 'e'.repeat(64)),+ );+ });++ it('only serves renderer entries of the tree', () => {+ expect(source.resolve('../main/index.js')).toBeNull();+ expect(source.resolve('assets/unknown.js')).toBeNull();+ expect(source.resolve('assets/%E0%A4%A.js')).toBeNull();+ });+});++describe('dirRendererSource', () => {+ let root: string;++ beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'renderer-source-'));+ mkdirSync(path.join(root, 'assets'));+ writeFileSync(path.join(root, 'assets', 'a.js'), 'a');+ });++ afterEach(() => rmSync(root, { force: true, recursive: true }));++ it('resolves existing files under the root', () => {+ const source = dirRendererSource(root);+ expect(source.resolve('assets/a.js')).toBe(path.join(root, 'assets', 'a.js'));+ expect(source.resolve('assets/missing.js')).toBeNull();+ });+});diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.tsindex 732d73e7a57..9f85b89ee06 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts@@ -9,6 +9,7 @@ import { zipSync } from 'fflate';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { type CoreManifestV3 as CoreManifest, sha256File } from '../manifest';+import { treeRendererSource } from '../rendererSource';import { cleanupLegacy, CoreStore, indexLocal, isSafeVersion } from '../store';vi.mock('node:fs/promises', async (importOriginal) => {@@ -91,6 +92,24 @@ const readTree = (dir: string) =>}),);+const readVersion = (dir: string, builtin: { dir: string; manifest: CoreManifest }) => {+ const manifest: CoreManifest = JSON.parse(readFileSync(path.join(dir, 'manifest.json'), 'utf8'));+ const renderer = treeRendererSource({+ builtinDir: builtin.dir,+ builtinTree: builtin.manifest.tree,+ storeDir: path.join(root, 'ota/store'),+ tree: manifest.tree,+ });+ return Object.fromEntries(+ manifest.tree.map((file) => {+ const source = file.path.startsWith('dist/renderer/')+ ? renderer.resolve(file.path.slice('dist/renderer/'.length))!+ : path.join(dir, file.path);+ return [file.path, readFileSync(source, 'utf8')];+ }),+ );+};+beforeEach(() => {root = mkdtempSync(path.join(tmpdir(), 'core-store-'));served = new Map();@@ -134,7 +153,7 @@ describe('CoreStore.stage', () => {expect(result.fallbackFull).toBe(false);expect(result.downloaded).toMatchObject({ objects: 7, patches: 0 });expect(result.downloaded.bytes).toBeGreaterThan(0);- expect(readTree(result.dir)).toEqual(files);+ expect(readVersion(result.dir, builtin)).toEqual(files);expect(JSON.parse(readFileSync(path.join(result.dir, 'manifest.json'), 'utf8'))).toEqual(remote,);@@ -152,7 +171,7 @@ describe('CoreStore.stage', () => {expect(fetchImpl).not.toHaveBeenCalled();expect(result.downloaded).toEqual({ bytes: 0, objects: 0, patches: 0 });- expect(readTree(result.dir)).toEqual(ENTRY_FILES);+ expect(readVersion(result.dir, builtin)).toEqual(ENTRY_FILES);});it('prefers a patch when the base sha is local', async () => {@@ -213,7 +232,7 @@ describe('CoreStore.stage', () => {expect(result.fallbackFull).toBe(true);expect(fetchImpl).toHaveBeenCalledTimes(1);- expect(readTree(result.dir)).toEqual(files);+ expect(readVersion(result.dir, builtin)).toEqual(files);});it('never lands a sha-mismatched object in the store', async () => {@@ -255,13 +274,69 @@ describe('CoreStore.stage', () => {expect(existsSync(path.join(root, 'ota/cores'))).toBe(false);});+ it('keeps renderer files out of the version dir and reads unchanged ones from the builtin core', async () => {+ const builtin = await localCore('builtin', ENTRY_FILES);+ const remote = manifestFor('1.1.0', {+ ...ENTRY_FILES,+ 'cli/x.js': 'new',+ 'dist/renderer/assets/index.js': 'index-new',+ });++ const result = await stage(remote, null, builtin);++ expect(readTree(result.dir)).toEqual({ 'cli/x.js': 'new' });+ expect(readdirSync(path.join(root, 'ota/store')).sort()).toEqual(+ [sha256File(Buffer.from('new')), sha256File(Buffer.from('index-new'))].sort(),+ );+ expect(readVersion(result.dir, builtin)).toMatchObject({+ 'dist/renderer/assets/index.js': 'index-new',+ 'dist/renderer/assets/popup.js': 'popup',+ });+ });++ it('ignores renderer paths of the current version, which is never materialized', async () => {+ const builtin = await localCore('builtin', ENTRY_FILES);+ const current = await localCore('current', { 'cli/x.js': 'new' });+ const currentManifest = manifestFor('current', { ...ENTRY_FILES, 'cli/x.js': 'new' });++ const result = await stage(+ manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' }),+ { dir: current.dir, manifest: currentManifest },+ builtin,+ );++ expect(fetchImpl).not.toHaveBeenCalled();+ expect(readVersion(result.dir, builtin)).toEqual({ ...ENTRY_FILES, 'cli/x.js': 'new' });+ });++ it('rejects a tree whose entry html references a missing asset', async () => {+ const builtin = await localCore('builtin', ENTRY_FILES);+ const remote = manifestFor('1.1.0', {+ ...ENTRY_FILES,+ 'dist/renderer/apps/desktop/index.html': '<script src="/assets/missing.js"></script>',+ });++ await expect(stage(remote, null, builtin)).rejects.toThrow('Entry integrity check failed');+ expect(existsSync(path.join(root, 'ota/cores/1.1.0'))).toBe(false);+ });++ it('reuses an already assembled version', async () => {+ const builtin = await localCore('builtin', ENTRY_FILES);+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });++ const first = await stage(remote, null, builtin);+ const second = await stage(remote, null, builtin);++ expect(second.dir).toBe(first.dir);+ expect(readVersion(second.dir, builtin)).toEqual({ ...ENTRY_FILES, 'cli/x.js': 'new' });+ });+it('hard-links assembled files and copies when link fails', async () => {const builtin = await localCore('builtin', ENTRY_FILES);const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });const linked = await stage(remote, null, builtin);expect(statSync(path.join(linked.dir, 'cli/x.js')).nlink).toBe(2);- expect(statSync(path.join(linked.dir, 'dist/renderer/assets/index.js')).nlink).toBe(2);vi.mocked(link).mockRejectedValue(Object.assign(new Error('EXDEV'), { code: 'EXDEV' }));const copied = await stage(@@ -270,7 +345,7 @@ describe('CoreStore.stage', () => {builtin,);expect(statSync(path.join(copied.dir, 'cli/x.js')).nlink).toBe(1);- expect(readTree(copied.dir)).toEqual({ ...ENTRY_FILES, 'cli/x.js': 'new' });+ expect(readVersion(copied.dir, builtin)).toEqual({ ...ENTRY_FILES, 'cli/x.js': 'new' });vi.mocked(link).mockReset();});});@@ -292,7 +367,7 @@ describe('CoreStore.gc', () => {expect(readdirSync(path.join(ota, 'cores'))).toEqual(['1.1.0']);expect(existsSync(path.join(ota, 'staging'))).toBe(false);- expect(readTree(keep.dir)).toEqual({ ...ENTRY_FILES, 'cli/a.js': 'keep' });+ expect(readVersion(keep.dir, builtin)).toEqual({ ...ENTRY_FILES, 'cli/a.js': 'keep' });expect(readdirSync(path.join(ota, 'store')).sort()).toEqual([...new Set(kept.tree.map((file) => file.sha256))].sort(),);diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.tsindex c8020abf857..3726b132449 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts@@ -1,7 +1,11 @@import { createHash, verify as cryptoVerify } from 'node:crypto';+import { readFileSync } from 'node:fs';+import path from 'node:path';import * as z from 'zod/v4';+import type { ShellGlobal } from '@/const/shell';+const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);const packPathSchema = z.string().regex(/^packs\/[0-9a-f]{64}\.zip$/);const relativePathSchema = z.string().refine((value) => {@@ -201,3 +205,13 @@ export const findMissingEntryAssets = (if (!refs.some((ref) => /\.m?js$/.test(ref))) missing.push('<no script referenced>');return missing;};++export const readBuiltinManifest = (shell: ShellGlobal): CoreManifest | null => {+ if (shell.source === 'builtin') return shell.manifest;+ try {+ const raw = JSON.parse(readFileSync(path.join(shell.builtinDir, 'manifest.json'), 'utf8'));+ return builtinManifestSchema.parse(raw);+ } catch {+ return null;+ }+};diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/rendererSource.ts b/apps/desktop/src/main/core/infrastructure/coreOta/rendererSource.tsnew file mode 100644index 00000000000..e481688945d--- /dev/null+++ b/apps/desktop/src/main/core/infrastructure/coreOta/rendererSource.ts@@ -0,0 +1,59 @@+import { existsSync } from 'node:fs';+import path from 'node:path';++import type { RendererTreeFile } from './manifest';++export const RENDERER_ROOT = 'dist/renderer';+const RENDERER_PREFIX = `${RENDERER_ROOT}/`;++export const isRendererPath = (treePath: string) => treePath.startsWith(RENDERER_PREFIX);++export interface RendererSource {+ resolve: (relPath: string) => string | null;+}++type TreeSourceOptions = {+ builtinDir: string;+ builtinTree: RendererTreeFile[];+ storeDir: string;+ tree: RendererTreeFile[];+};++export const dirRendererSource = (root: string): RendererSource => ({+ resolve: (relPath) => {+ const file = path.join(root, relPath);+ return existsSync(file) ? file : null;+ },+});++const toTreePath = (relPath: string) => {+ try {+ return decodeURIComponent(relPath).replaceAll('\\', '/').replace(/^\/+/, '');+ } catch {+ return null;+ }+};++export const treeRendererSource = ({+ builtinDir,+ builtinTree,+ storeDir,+ tree,+}: TreeSourceOptions): RendererSource => {+ const builtinByHash = new Map(+ builtinTree.map((file) => [file.sha256, path.join(builtinDir, file.path)]),+ );+ const hashByPath = new Map(+ tree+ .filter((file) => isRendererPath(file.path))+ .map((file) => [file.path.slice(RENDERER_PREFIX.length), file.sha256]),+ );+ return {+ resolve: (relPath) => {+ const treePath = toTreePath(relPath);+ const sha256 = treePath === null ? undefined : hashByPath.get(treePath);+ if (!sha256) return null;+ return builtinByHash.get(sha256) ?? path.join(storeDir, sha256);+ },+ };+};diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts b/apps/desktop/src/main/core/infrastructure/coreOta/store.tsindex 686a3139719..509ae769758 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/store.ts@@ -20,6 +20,7 @@ import { createLogger } from '@/utils/logger';import { type CoreManifest, findMissingEntryAssets, sha256File } from './manifest';import { PackDownloader, type PackFetch } from './pack';+import { isRendererPath, treeRendererSource } from './rendererSource';import { applyZstdPatch } from './zstdPatch';const logger = createLogger('core:CoreStore');@@ -39,9 +40,8 @@ type StageResult = {fallbackFull: boolean;};-const RENDERER_ROOT = 'dist/renderer';-const ENTRY_HTMLS = ['index.html', 'overlay.html', 'popup.html'].map((name) =>- path.join(RENDERER_ROOT, 'apps', 'desktop', name),+const ENTRY_HTMLS = ['index.html', 'overlay.html', 'popup.html'].map(+ (name) => `apps/desktop/${name}`,);const FULL_FALLBACK_THRESHOLD = 400;const CONCURRENCY = 8;@@ -102,8 +102,17 @@ const readDirNames = async (dir: string): Promise<string[]> => {export const isSafeVersion = (version: string): boolean =>SAFE_VERSION.test(version) && version !== '.' && version !== '..';-export const indexLocal = (coreDir: string, manifest: CoreManifest): Map<string, string> =>- new Map(manifest.tree.map((file) => [file.sha256, path.join(coreDir, file.path)]));+// An OTA version dir holds no renderer files, so indexing them would shadow the builtin copies.+export const indexLocal = (+ coreDir: string,+ manifest: CoreManifest,+ { skipRenderer = false } = {},+): Map<string, string> =>+ new Map(+ manifest.tree+ .filter((file) => !skipRenderer || !isRendererPath(file.path))+ .map((file) => [file.sha256, path.join(coreDir, file.path)]),+ );export const decodeCorePack = (content: Buffer): Promise<Map<string, Buffer>> =>new Promise((resolve, reject) => {@@ -160,7 +169,7 @@ export class CoreStore {const byHash = new Map([...indexLocal(builtin.dir, builtin.manifest),- ...(current ? indexLocal(current.dir, current.manifest) : []),+ ...(current ? indexLocal(current.dir, current.manifest, { skipRenderer: true }) : []),]);if (remote.schemaVersion === 4) {const expected = new Set([@@ -194,7 +203,7 @@ export class CoreStore {packsBaseUrl,(hash, bytes) => this.putObject(hash, bytes),);- return { ...result, dir: await this.assemble(remote, byHash) } satisfies StageResult;+ return { ...result, dir: await this.assemble(remote, byHash, builtin) } satisfies StageResult;}const missing = [...new Set(remote.tree.map((file) => file.sha256))].filter((sha256) => !byHash.has(sha256) && !existsSync(this.objectPath(sha256)),@@ -247,7 +256,7 @@ export class CoreStore {}}- const dir = await this.assemble(remote, byHash);+ const dir = await this.assemble(remote, byHash, builtin);return { dir, downloaded, fallbackFull } satisfies StageResult;}@@ -287,6 +296,20 @@ export class CoreStore {await rename(`${target}.tmp`, target);}+ // Renderer content is served by hash from the builtin archive or the object store, so it is+ // never materialized into the version dir.+ private async keepRendererContent(+ file: CoreManifest['tree'][number],+ byHash: Map<string, string>,+ builtinHashes: Set<string>,+ ) {+ if (existsSync(this.objectPath(file.sha256))) return;+ const source = byHash.get(file.sha256);+ if (!source) throw new Error(`Missing renderer content: ${file.path}`);+ if (builtinHashes.has(file.sha256)) return;+ await this.putObject(file.sha256, await readFile(source));+ }+private async readManifest(dir: string): Promise<CoreManifest | null> {try {return JSON.parse(await readFile(path.join(dir, 'manifest.json'), 'utf8'));@@ -295,13 +318,19 @@ export class CoreStore {}}- private async assemble(remote: CoreManifest, byHash: Map<string, string>): Promise<string> {+ private async assemble(+ remote: CoreManifest,+ byHash: Map<string, string>,+ builtin: LocalCore,+ ): Promise<string> {const finalDir = resolveInside(this.coresDir, remote.version);const tmpDir = `${finalDir}.tmp`;+ const builtinHashes = new Set(builtin.manifest.tree.map((file) => file.sha256));await rm(tmpDir, { force: true, recursive: true });await mkdir(tmpDir, { mode: DIR_MODE, recursive: true });try {await runPool(remote.tree, async (file) => {+ if (isRendererPath(file.path)) return this.keepRendererContent(file, byHash, builtinHashes);const target = resolveInside(tmpDir, file.path);await mkdir(path.dirname(target), { mode: DIR_MODE, recursive: true });const source = byHash.get(file.sha256) ?? this.objectPath(file.sha256);@@ -317,12 +346,19 @@ export class CoreStore {throw new Error(`Assembled file mismatch: ${file.path}`);});await writeFile(path.join(tmpDir, 'manifest.json'), JSON.stringify(remote));- const rendererDir = path.join(tmpDir, RENDERER_ROOT);+ const renderer = treeRendererSource({+ builtinDir: builtin.dir,+ builtinTree: builtin.manifest.tree,+ storeDir: this.storeDir,+ tree: remote.tree,+ });for (const entry of ENTRY_HTMLS) {- const missing = findMissingEntryAssets(- await readFile(path.join(tmpDir, entry), 'utf8'),- (relPath) => existsSync(path.join(rendererDir, relPath)),- );+ const entryFile = renderer.resolve(entry);+ const missing = entryFile+ ? findMissingEntryAssets(await readFile(entryFile, 'utf8'), (relPath) =>+ Boolean(renderer.resolve(relPath)),+ )+ : ['<entry html>'];if (missing.length > 0) {throw new Error(`Entry integrity check failed (${entry}): ${missing.join(', ')}`);}@@ -332,6 +368,7 @@ export class CoreStore {if (JSON.stringify(existing) !== JSON.stringify(remote))throw new Error('Existing core version differs');for (const file of remote.tree) {+ if (isRendererPath(file.path)) continue;if (sha256File(await readFile(resolveInside(finalDir, file.path))) !== file.sha256)throw new Error('Existing core version is corrupt');}diff --git a/docs/development/desktop-core-renderer-overlay-spec.md b/docs/development/desktop-core-renderer-overlay-spec.mdnew file mode 100644index 00000000000..0077398fc67--- /dev/null+++ b/docs/development/desktop-core-renderer-overlay-spec.md@@ -0,0 +1,109 @@+# Desktop OTA Renderer Overlay Spec++状态:设计待评审。依赖 #20211(启动时按大小校验),两者都修改 `verifyCandidate`,本改动叠在其分支上。++## 1. 目标与决策++OTA 版本不再在用户数据目录里展开完整的 renderer。renderer 的每个文件按内容哈希解析:未变化的内容直接从内置 `core.asar` 读取,变化的内容从已校验的对象缓存 `store/<sha256>` 读取。++- 只对 `dist/renderer/` 做 overlay。主进程、preload、CLI、`node_modules`、`resources` 仍按现有方式组装为真实文件,`require()`、CLI 和子进程不受影响。+- 不 hook Node 模块解析,不引入虚拟文件系统,不修改 `core.asar`。+- v4 manifest、pack、发布流程不变;服务端无改动。+- shell 目录属于 shellAbi 输入,本改动随完整安装包发布。++不在本次范围:主进程 overlay、跨版本 pack 去重、ASAR 形式的 OTA 版本。++## 2. 现状与数据++`CoreStore.assemble` 把目标 tree 的每个文件写入 `core-ota/cores/<version>/`:来自内置 `core.asar` 的文件整份复制,来自对象缓存或当前外部版本的文件优先硬链接。硬链接无法指向 ASAR 内部,所以装机后的首次 OTA 会把几乎所有内容从 `core.asar` 复制出来。++以 canary `2.2.19-canary.33-core.2` 为例(1,706 个文件,111.6 MB):++| 部分 | 文件数 | 大小 |+| ----------------------------------------------------------------- | ------ | ------- |+| `dist/renderer` | 1,609 | 95.5 MB |+| 其余(main、preload、CLI、node_modules、resources、package.json) | 97 | 16.1 MB |++实测:Windows(i5-13600KF、NVMe、Defender 关闭)一次首次 OTA,下载 10.3 MB(635 个对象)并组装 1,707 个文件,端到端 4.19 s。macOS 冷缓存下首次 OTA 组装 1.8–3.3 s。++## 3. 布局++```text+core-ota/+├── store/<sha256> 已校验的下载内容(含变化的 renderer 文件)+├── cores/<version>/ manifest.json + 非 renderer 文件(真实文件)+├── pointer.json+└── boot.json+```++`cores/<version>/dist/renderer/` 不再存在。版本的 renderer 由该版本 manifest 的 tree 定义,按哈希在内置 `core.asar` 或 `store/` 中找到内容。++## 4. Renderer 解析++新增 renderer 来源(source)的概念,替代 `RendererUrlManager` 里的目录字段:++- 目录来源:现有行为,用于内置 core 和开发模式,根目录为 `rendererDir`。+- tree 来源:由 manifest tree、`store/` 路径、内置 `core.asar` 路径及内置 manifest 构建。+ - 建立 `dist/renderer/` 下逻辑路径 → sha256 的映射,以及内置 manifest 的 sha256 → `core.asar` 内路径的映射。+ - 解析顺序:内置 `core.asar` 中相同哈希的文件优先(安装包内容,不受杀毒软件隔离影响),否则 `store/<sha256>`。+ - 不在 tree 中的路径返回空,保持现有 404 与 SPA 入口回退行为。++`ResolveRendererFilePath` 改为返回 `{ filePath, name }`:`filePath` 用于读取,`name` 为逻辑文件名,用于 MIME 推断和 `404.html` 判断。`store/<sha256>` 没有扩展名,不能再按读取路径推断 MIME。++启动时 `RendererUrlManager` 的默认来源:内置启动用目录来源;外部启动用 `__SHELL__.manifest` 构建的 tree 来源。`rendererDir` 在外部启动时指向不存在的目录,不再作为外部版本的读取根。++reload 应用、回滚和 “取消卸载的窗口继续加载上一版本 chunk” 的逻辑保持不变,只是把 `activeRendererDir` / `previousRendererDir` 换成来源对象。应用前的入口检查改为:三个入口 HTML 在该来源中都能解析。++## 5. 暂存(staging)++`CoreStore.stageCore` 的下载计划不变:缺失内容写入 `store/`,写入前已校验哈希。++`assemble` 调整:++- `dist/renderer/` 条目不写入版本目录;每个条目的哈希必须在 `store/` 中存在或在内置 manifest 中出现,否则暂存失败。+- 其余条目按现有方式硬链接或复制,并逐个校验 sha256。+- 入口资源检查改为:入口 HTML 引用的资源在 tree 中存在且可解析。+- `indexLocal(current)` 跳过 `dist/renderer/` 条目;这些内容由 `store/` 或内置索引提供。++对象缓存中 renderer 内容的完整性在写入 `store/` 时校验;复用内置内容前沿用现有的读取并校验。++## 6. 启动校验(shell)++`verifyCandidate` 在 #20211 的基础上区分两类条目:++- 非 renderer 条目:版本目录中的真实文件,检查存在且大小一致(#20211 现状)。+- renderer 条目:内置 manifest 中存在相同 sha256 即通过;否则 `store/<sha256>` 必须存在且大小一致。++内置 manifest 已由 `resolveCore` 读取。签名、shellAbi、路径安全、主入口检查不变。++## 7. GC、回滚与兼容++- GC 不变:保留 current、previous、staged、运行版本 manifest 引用的全部 `store/` 对象,renderer 内容随之保留。+- 回滚不变:previous 的 manifest 仍引用其 renderer 对象;回退到内置 core 使用目录来源。+- 完整安装包升级会替换 `core.asar`。新 shell 的 ABI 不同,旧指针失效;同一渠道内完整发布的 seq 高于已发布的 OTA,旧 OTA 版本也会被拒绝。即使两者都未触发,第 6 节的启动校验也会因为内置 manifest 中找不到哈希、且 store 中没有对象而拒绝该版本。+- 旧 shell 展开的完整版本目录不会被新 shell 使用(ABI 变化后指针失效,GC 清理)。++## 8. 风险++| 风险 | 处理 |+| -------------------------------------- | ---------------------------------------------------------------------------------------------- |+| 主进程其他代码直接读取 `dist/renderer` | 已排查:只有 `RendererUrlManager`、`CoreUpdateManager` 和 `CoreStore` 读取,均在本次改动范围内 |+| 从 `core.asar` 读取 renderer 文件失败 | 内置 renderer 当前已从 `core.asar` 提供,读取路径相同 |+| MIME 或 404 判断错误 | 使用逻辑文件名,单测覆盖 |+| `store/` 对象被外部删除 | 启动校验拒绝该版本并回退;运行中缺失的资源返回 404,与当前缺文件行为一致 |+| reload 后旧窗口加载旧 chunk | 保留上一来源回退逻辑 |++## 9. 测试与验收++单测:++- tree 来源:内置优先、store 回退、tree 外路径、MIME 使用逻辑文件名。+- `assemble`:不写 renderer 条目;缺少内容时失败;入口资源检查。+- `verifyCandidate`:renderer 条目在内置 manifest 或 store 中通过;两者都没有时拒绝;store 对象大小不符时拒绝。+- `CoreUpdateManager`:reload 应用和回滚切换来源。++产品验收(打包态,macOS 和 Windows):++- 装机后首次 OTA(reload 与 relaunch 各一次),主窗口、overlay、popup 均正常显示新内容。+- 连续 OTA、跳级 OTA、坏版本回滚到 previous 和内置 core。+- 记录改动前后:首次 OTA 写入文件数、写入字节、组装耗时、`core-ota` 磁盘占用,以及启动时 `resolveCore` 耗时。