Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): prefetch agent binaries before restart

MagicLizib9fe998e2ef8
diff --git a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
index 23fe0cdf35..5c3b0009a0 100644
--- a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
+++ b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
@@ -1,5 +1,6 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
+import type { StartupBinaryUpdateScope } from '../agent-binaries/startup-update';
// getBase() 按 kind 缓存 provisioner 实例:全部测试共享同一个 cdndProvisioner,
// 每测试重配它的行为(而不是 mockReturnValueOnce 换实例——缓存会让新实例永远不被使用)。
@@ -29,7 +30,7 @@ const {
findUsableLinuxRuntimeFallbackBinary: vi.fn(async (): Promise<string | null> => null),
prepareLinuxRuntimeFallback: vi.fn(),
probeBinaryVersion: vi.fn(),
- consumeStartupBinaryUpdateMarker: vi.fn(() => true),
+ consumeStartupBinaryUpdateMarker: vi.fn((): StartupBinaryUpdateScope => true),
};
});
@@ -91,7 +92,9 @@ beforeEach(async () => {
findDevBinary.mockReset().mockReturnValue(null);
findCachedLinuxRuntimeFallbackBinary.mockReturnValue(null);
findUsableLinuxRuntimeFallbackBinary.mockReset().mockResolvedValue(null);
- consumeStartupBinaryUpdateMarker.mockReturnValue(true);
+ // These CDN/fallback cases exercise the retained explicit harness-update path.
+ // Unscoped app-update markers are covered through real preparation in startup-policy.
+ consumeStartupBinaryUpdateMarker.mockReturnValue(['claude-code', 'codex', 'pi']);
probeBinaryVersion.mockReset().mockResolvedValue('1.0.0');
prepareLinuxRuntimeFallback.mockResolvedValue({
ready: true,
diff --git a/apps/desktop/src/main/__tests__/manifestService.test.ts b/apps/desktop/src/main/__tests__/manifestService.test.ts
index 0904fdf4e4..120051a8d7 100644
--- a/apps/desktop/src/main/__tests__/manifestService.test.ts
+++ b/apps/desktop/src/main/__tests__/manifestService.test.ts
@@ -93,6 +93,23 @@ describe('manifestService cache channel identity', () => {
clearCachedManifest();
});
+ // Optional binary preparation observes metadata; it cannot change the result
+ // of the application's update lookup, even if the observer fails. Tier: unit.
+ it('isolates optional metadata observers and honors unsubscribe', async () => {
+ const service = await import('../manifestService');
+ const observer = vi.fn(() => { throw new Error('optional prefetch failed'); });
+ const unsubscribe = service.onManifestFetched(observer);
+ try {
+ mockManifestResponse(RELEASE_MANIFEST);
+ await expect(service.fetchManifest()).resolves.toMatchObject({ app: { version: '0.0.65' } });
+ expect(observer).toHaveBeenCalledOnce();
+ unsubscribe();
+ mockManifestResponse(RELEASE_MANIFEST);
+ await expect(service.fetchManifest()).resolves.toMatchObject({ app: { version: '0.0.65' } });
+ expect(observer).toHaveBeenCalledOnce();
+ } finally { unsubscribe(); }
+ });
+
it('discards a cached release manifest after the shared channel switches to beta', async () => {
mockManifestResponse(RELEASE_MANIFEST);
const service = await import('../manifestService');
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index 89522cb08f..bdb85fcff6 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -34,6 +34,8 @@ const getBaseUrl = vi.fn(() => CDN_EXTERNAL_BASE_URL);
const isDev = vi.fn(() => false);
const syncWindowsVersionAfterUpdate = vi.fn(async () => undefined);
const download = vi.fn();
+const prefetchAgentBinary = vi.fn(async () => true);
+vi.mock('../agent-binaries/index.js', () => ({ prefetch: prefetchAgentBinary }));
const readAutoUpdateSettings = vi.fn(() => ({ autoRelaunchOnIdle: true }));
const spawnProcess = vi.fn(() => ({
unref: vi.fn(),
@@ -682,6 +684,7 @@ describe('agent-facing managed app update check', () => {
describe('binary version checks after an applied update', () => {
beforeEach(() => {
+ prefetchAgentBinary.mockReset().mockResolvedValue(true);
readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });
download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
@@ -690,6 +693,43 @@ describe('binary version checks after an applied update', () => {
});
});
+ // New local preparation IPC: deferred/failed binary downloads must leave a
+ // staged application patch ready and must not restart Cindy. Tier: unit.
+ it('keeps the application update ready while About prepares an engine, including preparation failure', async () => {
+ const service = await freshUpdateService('darwin');
+ service.initUpdateService();
+ try {
+ await service.checkForUpdate(updateManifest());
+ const manifest = { ...updateManifest(), codexPackage: { version: '9.0.0', file: 'codex-package/runtime.tar.gz', sha256: 'a'.repeat(64), size: 123 } };
+ fetchManifest.mockResolvedValue(manifest);
+ const preparation = Promise.withResolvers<boolean>();
+ prefetchAgentBinary.mockReturnValueOnce(preparation.promise);
+ const prepare = ipcHandlers.get('update-harness-prepare');
+ const result = prepare?.({ sender: { id: 1 } }, 'codex', '9.0.0');
+ await vi.waitFor(() => expect(prefetchAgentBinary).toHaveBeenCalled());
+ expect(service.getUpdateStatus()).toBe('ready');
+ expect(appRelaunch).not.toHaveBeenCalled();
+ preparation.resolve(false);
+ await expect(result).rejects.toThrow('could not prepare harness update');
+ expect(service.getUpdateStatus()).toBe('ready');
+ // A fresh user retry is allowed; a failed download cannot poison readiness.
+ await expect(prepare?.({ sender: { id: 1 } }, 'codex', '9.0.0')).resolves.toEqual({ ready: true });
+ expect(appRelaunch).not.toHaveBeenCalled();
+ expect(appQuit).not.toHaveBeenCalled();
+ } finally { service.stopUpdateService(); }
+ });
+
+ it('rejects a changed engine version before downloading or scheduling a restart', async () => {
+ const service = await freshUpdateService('darwin');
+ service.initUpdateService();
+ try {
+ fetchManifest.mockResolvedValue({ ...updateManifest(), codexPackage: { version: '9.1.0', file: 'runtime.tar.gz', sha256: 'a'.repeat(64), size: 123 } });
+ await expect(ipcHandlers.get('update-harness-prepare')?.({ sender: { id: 1 } }, 'codex', '9.0.0')).rejects.toThrow('harness update changed');
+ expect(prefetchAgentBinary).not.toHaveBeenCalled();
+ expect(appRelaunch).not.toHaveBeenCalled();
+ } finally { service.stopUpdateService(); }
+ });
+
it('schedules a one-time refresh of only the confirmed harness before a graceful relaunch', async () => {
const service = await freshUpdateService('darwin');
const { consumeStartupBinaryUpdateMarker } = await import('../agent-binaries/startup-update');
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/background-update.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/background-update.test.ts
new file mode 100644
index 0000000000..9e4d96d91b
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/__tests__/background-update.test.ts
@@ -0,0 +1,94 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Manifest } from '../../manifestService';
+
+const mocks = vi.hoisted(() => ({
+ packaged: true,
+ personal: false,
+ observe: undefined as ((manifest: Manifest) => void) | undefined,
+ unsubscribe: vi.fn(),
+ prefetch: vi.fn(),
+ once: vi.fn(),
+}));
+vi.mock('electron', () => ({ app: {
+ get isPackaged() { return mocks.packaged; },
+ once: mocks.once,
+ removeListener: vi.fn(),
+} }));
+vi.mock('../../cindy-make/versionRuntimeIdentity.js', () => ({ isCindyPersonalRuntime: () => mocks.personal }));
+vi.mock('../../manifestService.js', () => ({
+ getCachedManifest: () => ({ app: { version: '1.0.0' } }),
+ onManifestFetched: (callback: (manifest: Manifest) => void) => {
+ mocks.observe = callback;
+ return mocks.unsubscribe;
+ },
+}));
+vi.mock('../index.js', () => ({ prefetch: mocks.prefetch }));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+
+import { startBinaryBackgroundUpdates, stopBinaryBackgroundUpdates } from '../background-update';
+
+/*
+ * Production start/manifest observer/stop lifecycle. Existing installer tests do
+ * not exercise scheduling: prefetch must not gate startup or keep running after
+ * exit, and failures must retry on a later manifest. Minimal inputs are readiness
+ * plus one manifest or cancellation. Tier: unit; timers and network are fake.
+ */
+describe('binary background update lifecycle', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.packaged = true;
+ mocks.personal = false;
+ mocks.observe = undefined;
+ mocks.prefetch.mockReset().mockResolvedValue(true);
+ mocks.unsubscribe.mockClear();
+ mocks.once.mockClear();
+ });
+ afterEach(() => { stopBinaryBackgroundUpdates(); vi.useRealTimers(); });
+
+ it('starts once after readiness without blocking startup and uses the cached manifest', async () => {
+ expect(startBinaryBackgroundUpdates()).toBeUndefined();
+ startBinaryBackgroundUpdates();
+ expect(mocks.once).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(9_999);
+ expect(mocks.prefetch).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2);
+ expect(mocks.prefetch.mock.calls.map(([kind]) => kind)).toEqual(['claude-code', 'codex', 'pi']);
+ expect(mocks.prefetch.mock.calls[0][1].manifest.app.version).toBe('1.0.0');
+ });
+
+ it('retries failed preparation when the app next fetches fresh metadata, without a separate polling loop', async () => {
+ mocks.prefetch.mockResolvedValue(false);
+ startBinaryBackgroundUpdates();
+ await vi.advanceTimersByTimeAsync(10_001);
+ expect(mocks.prefetch).toHaveBeenCalledTimes(3);
+ const manifest = { app: { version: '2.0.0' } };
+ mocks.observe?.(manifest);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(mocks.prefetch).toHaveBeenCalledTimes(6);
+ expect(mocks.prefetch.mock.calls[3][1].manifest).toBe(manifest);
+ });
+
+ it('cancels in-flight work and removes the observer when quitting', async () => {
+ const preparation = Promise.withResolvers<boolean>();
+ mocks.prefetch.mockReturnValueOnce(preparation.promise);
+ startBinaryBackgroundUpdates();
+ await vi.advanceTimersByTimeAsync(10_001);
+ const signal = mocks.prefetch.mock.calls[0][1].signal as AbortSignal;
+ expect(signal.aborted).toBe(false);
+ stopBinaryBackgroundUpdates();
+ expect(signal.aborted).toBe(true);
+ expect(mocks.unsubscribe).toHaveBeenCalledOnce();
+ preparation.resolve(false);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(mocks.prefetch).toHaveBeenCalledOnce();
+ });
+
+ it.each(['development', 'personal'] as const)('leaves %s builds on their existing update policy', async mode => {
+ mocks.packaged = mode !== 'development';
+ mocks.personal = mode === 'personal';
+ startBinaryBackgroundUpdates();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.observe).toBeUndefined();
+ expect(mocks.prefetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts
index fee5821c99..e98674c3cf 100644
--- a/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts
+++ b/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts
@@ -14,6 +14,8 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { create as createTar } from 'tar';
+import { createHash, randomUUID } from 'node:crypto';
+import { app } from 'electron';
import type { VendorAsset } from '../manifest.js';
@@ -21,6 +23,7 @@ const FAKE_SHA = 'b'.repeat(64);
const mocks = vi.hoisted(() => ({
download: vi.fn(),
+ backgroundDownload: vi.fn(),
fetchManifest: vi.fn(async () => ({ app: {} })),
cachedManifest: { current: { app: {} } as { app: Record<string, never> } | null },
// 每个用例把要打包进 tar.gz 的源目录塞进来,download mock 现打包成归档落盘。
@@ -37,6 +40,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('../../downloader/index.js', () => ({
download: mocks.download,
+ createDownloader: () => mocks.backgroundDownload,
DownloadError: class DownloadError extends Error {
code: string;
constructor(code: string, message: string) {
@@ -118,6 +122,48 @@ beforeEach(() => {
});
describe('createBinaryProvisioner tar-gz-dir', () => {
+ // A cached Codex archive has a nested bin/codex entrypoint. Unlike download(),
+ // copying a local archive does not create its parent; retain real extraction
+ // and auxiliary files in this regression. Tier: unit, unique temporary files.
+ it('adopts a prefetched directory package with a nested entrypoint without downloading on startup', async () => {
+ const source = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-prefetch-'));
+ const binaryName = path.join('bin', process.platform === 'win32' ? 'codex.exe' : 'codex');
+ const installSubdir = 'prefetch-dist-' + randomUUID();
+ const installRoot = path.join(app.getPath('userData'), installSubdir);
+ let cacheDirectory: string | undefined;
+ try {
+ fs.mkdirSync(path.join(source, 'bin'));
+ fs.writeFileSync(path.join(source, binaryName), 'codex-runtime', { mode: 0o755 });
+ fs.writeFileSync(path.join(source, 'codex-package.json'), '{}');
+ const archivePath = path.join(source, 'payload.tar.gz');
+ await createTar({ gzip: true, cwd: source, file: archivePath }, ['bin', 'codex-package.json']);
+ const bytes = fs.readFileSync(archivePath);
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
+ mocks.asset.current = { version: '9.0.0', file: 'codex-package/9.0.0/darwin-arm64/dist.tar.gz', sha256, size: bytes.length };
+ cacheDirectory = path.join(app.getPath('userData'), 'agent-binary-downloads', 'codex', sha256);
+ mocks.backgroundDownload.mockImplementation(async ({ targetPath }: DownloadOpts) => {
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
+ fs.writeFileSync(targetPath, bytes);
+ return { path: targetPath, sha256, size: bytes.length };
+ });
+ const provisioner = createBinaryProvisioner({
+ vendorKey: 'codex', manifestField: 'codexPackage', installSubdir,
+ artifact: { kind: 'tar-gz-dir', binaryName },
+ });
+ await expect(provisioner.prefetch({ manifest: { app: { version: '1.0.0' } } })).resolves.toBe(true);
+ const result = await provisioner.prepare({ checkForUpdates: false });
+ expect(result).toEqual({ ready: true, binaryPath: path.join(installRoot, '9.0.0', binaryName) });
+ expect(fs.readFileSync(result.binaryPath, 'utf8')).toBe('codex-runtime');
+ expect(fs.readFileSync(path.join(installRoot, '9.0.0', 'codex-package.json'), 'utf8')).toBe('{}');
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(cacheDirectory)).toBe(false);
+ } finally {
+ fs.rmSync(source, { recursive: true, force: true });
+ fs.rmSync(installRoot, { recursive: true, force: true });
+ if (cacheDirectory) fs.rmSync(cacheDirectory, { recursive: true, force: true });
+ }
+ });
+
it('平铺归档:解压出完整目录、写 .verified、清理归档中间文件', async () => {
mocks.archiveState.srcDir = stageDist('flat');
mocks.download.mockImplementation(fulfillDownloadWithTarGz);
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/factory-startup-update.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/factory-startup-update.test.ts
index f5e56dc44a..8a86e37613 100644
--- a/apps/desktop/src/main/agent-binaries/__tests__/factory-startup-update.test.ts
+++ b/apps/desktop/src/main/agent-binaries/__tests__/factory-startup-update.test.ts
@@ -2,12 +2,15 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { gzipSync } from 'node:zlib';
+import { createHash } from 'node:crypto';
+import { withCrossProcessLock } from '../../device-link/crossProcessLock';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BinaryProvisionerConfig } from '../types';
const mocks = vi.hoisted(() => ({
userDataDir: '',
download: vi.fn(),
+ backgroundDownload: vi.fn(),
fetchManifest: vi.fn(),
getCachedManifest: vi.fn(),
getVendorAsset: vi.fn(),
@@ -26,16 +29,18 @@ vi.mock('../manifest.js', () => ({
}));
vi.mock('../../downloader/index.js', () => ({
download: mocks.download,
+ createDownloader: () => mocks.backgroundDownload,
DownloadError: class DownloadError extends Error {},
}));
import { createBinaryProvisioner } from '../factory';
+const archiveBytes = gzipSync(Buffer.from('runtime'));
const asset = {
version: '3.0.0',
file: 'claude-code/3.0.0/darwin-arm64/claude.gz',
- sha256: 'c'.repeat(64),
- size: 7,
+ sha256: createHash('sha256').update(archiveBytes).digest('hex'),
+ size: archiveBytes.length,
};
const config: BinaryProvisionerConfig = {
vendorKey: 'claude',
@@ -62,6 +67,7 @@ afterAll(() => {
});
beforeEach(() => {
fs.rmSync(path.join(mocks.userDataDir, config.installSubdir), { recursive: true, force: true });
+ fs.rmSync(path.join(mocks.userDataDir, 'agent-binary-downloads'), { recursive: true, force: true });
mocks.getCachedManifest.mockReset().mockReturnValue(null);
mocks.fetchManifest.mockReset().mockResolvedValue({ app: {} });
mocks.getVendorAsset.mockReset().mockReturnValue(asset);
@@ -70,6 +76,136 @@ beforeEach(() => {
fs.writeFileSync(targetPath, gzipSync(Buffer.from('runtime')));
return { path: targetPath, size: 7, sha256: asset.sha256, fromCache: false };
});
+ mocks.backgroundDownload.mockReset().mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
+ fs.writeFileSync(targetPath, archiveBytes);
+ return { path: targetPath, size: asset.size, sha256: asset.sha256 };
+ });
+});
+
+/*
+ * Production entry/result: prefetch -> prepare returns the new local path without
+ * HTTP; the running runtime remains usable until then. The former startup-only
+ * suite had no staged downloads. Minimal inputs are one old install plus one
+ * newer archive (or one failed/corrupt archive). Tier: unit, no external IO.
+ */
+describe('background downloads handed to the existing installer', () => {
+ it('keeps the running install during prefetch and installs the verified cache on restart without HTTP', async () => {
+ const oldPath = installLocal('1.0.0');
+ const provisioner = createBinaryProvisioner(config);
+ await provisioner.prepare({ checkForUpdates: false });
+ await expect(provisioner.prefetch({ manifest: { app: {} } as never })).resolves.toBe(true);
+ expect(fs.readFileSync(oldPath, 'utf8')).toBe('local');
+ await expect(provisioner.getState()).resolves.toMatchObject({ binaryPath: oldPath });
+ expect(fs.existsSync(path.join(mocks.userDataDir, config.installSubdir, asset.version, '.verified'))).toBe(false);
+
+ const restarted = createBinaryProvisioner(config);
+ const result = await restarted.prepare({ checkForUpdates: false });
+ expect(result).toEqual({ ready: true, binaryPath: path.join(mocks.userDataDir, config.installSubdir, asset.version, 'claude') });
+ expect(fs.readFileSync(result.binaryPath, 'utf8')).toBe('runtime');
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(mocks.userDataDir, 'agent-binary-downloads', 'claude', asset.sha256))).toBe(false);
+ expect(fs.existsSync(oldPath)).toBe(false);
+ });
+
+ it('shares a simultaneous background and manual prefetch of the same target', async () => {
+ let finish!: () => void;
+ const started = Promise.withResolvers<void>();
+ mocks.backgroundDownload.mockImplementationOnce(async ({ targetPath }: { targetPath: string }) => {
+ started.resolve();
+ await new Promise<void>(resolve => { finish = resolve; });
+ fs.writeFileSync(targetPath, archiveBytes);
+ return { path: targetPath, size: asset.size, sha256: asset.sha256 };
+ });
+ const one = createBinaryProvisioner(config).prefetch({ manifest: { app: {} } as never });
+ await started.promise;
+ const two = createBinaryProvisioner(config).prefetch({ manifest: { app: {} } as never });
+ finish();
+ expect(await Promise.all([one, two])).toEqual([true, true]);
+ expect(mocks.backgroundDownload).toHaveBeenCalledOnce();
+ });
+
+ it('keeps a usable old runtime after failed prefetch and permits a later successful retry', async () => {
+ const oldPath = installLocal('1.0.0');
+ mocks.backgroundDownload.mockRejectedValueOnce(new Error('CDN unavailable'));
+ const provisioner = createBinaryProvisioner(config);
+ await expect(provisioner.prefetch({ manifest: { app: {} } as never })).resolves.toBe(false);
+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toEqual({ ready: true, binaryPath: oldPath });
+ expect(mocks.download).not.toHaveBeenCalled();
+ await expect(provisioner.prefetch({ manifest: { app: {} } as never })).resolves.toBe(true);
+ expect((await provisioner.prepare({ checkForUpdates: false })).binaryPath).not.toBe(oldPath);
+ });
+
+ it('rejects a modified cache without a startup download or a false installed marker', async () => {
+ const oldPath = installLocal('1.0.0');
+ const provisioner = createBinaryProvisioner(config);
+ await provisioner.prefetch({ manifest: { app: {} } as never });
+ fs.writeFileSync(path.join(mocks.userDataDir, 'agent-binary-downloads', 'claude', asset.sha256, 'archive'), Buffer.alloc(asset.size));
+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toEqual({ ready: true, binaryPath: oldPath });
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(mocks.userDataDir, config.installSubdir, asset.version, '.verified'))).toBe(false);
+ });
+
+ it('keeps first-install retries on one installation instead of removing an in-flight directory', async () => {
+ const transfer = Promise.withResolvers<void>();
+ const writeArchive = mocks.download.getMockImplementation()!;
+ mocks.download.mockImplementationOnce(async (options) => { await transfer.promise; return writeArchive(options); });
+ const provisioner = createBinaryProvisioner(config);
+ const one = provisioner.prepare({ checkForUpdates: false });
+ const two = provisioner.prepare({ checkForUpdates: false });
+ transfer.resolve();
+ const [first, second] = await Promise.all([one, two]);
+ expect(first).toEqual(second);
+ expect(first.ready).toBe(true);
+ expect(fs.readFileSync(first.binaryPath, 'utf8')).toBe('runtime');
+ expect(mocks.download).toHaveBeenCalledOnce();
+ });
+
+ it('keeps an optional installed runtime if the downloaded update passes its hash but cannot be extracted', async () => {
+ const oldPath = installLocal('1.0.0');
+ const bytes = Buffer.from('not a gzip archive');
+ mocks.getVendorAsset.mockReturnValue({ ...asset, sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length });
+ mocks.backgroundDownload.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.writeFileSync(targetPath, bytes);
+ return { path: targetPath, size: bytes.length };
+ });
+ const provisioner = createBinaryProvisioner({ ...config, optionalAsset: true });
+ await expect(provisioner.prefetch({ manifest: { app: {} } as never })).resolves.toBe(true);
+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toEqual({ ready: true, binaryPath: oldPath });
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(mocks.userDataDir, config.installSubdir, asset.version))).toBe(false);
+ });
+
+ it('cleans superseded and expired partial downloads without removing the installed runtime', async () => {
+ const oldPath = installLocal('1.0.0');
+ const root = path.join(mocks.userDataDir, 'agent-binary-downloads', 'claude');
+ const obsolete = path.join(root, 'd'.repeat(64));
+ const candidate = path.join(root, asset.sha256);
+ for (const directory of [obsolete, candidate]) {
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(path.join(directory, 'archive.part'), 'abandoned');
+ const expired = new Date(Date.now() - 8 * 24 * 60 * 60_000);
+ fs.utimesSync(directory, expired, expired);
+ }
+ await expect(createBinaryProvisioner(config).prefetch({ manifest: { app: {} } as never })).resolves.toBe(true);
+ expect(fs.existsSync(obsolete)).toBe(false);
+ expect(fs.existsSync(path.join(candidate, 'archive.part'))).toBe(false);
+ expect(fs.readFileSync(oldPath, 'utf8')).toBe('local');
+ });
+
+ it('defers a download when another process owns the cache and remains retryable after it releases the lock', async () => {
+ const oldPath = installLocal('1.0.0');
+ const root = path.join(mocks.userDataDir, 'agent-binary-downloads', 'claude');
+ fs.mkdirSync(root, { recursive: true });
+ const provisioner = createBinaryProvisioner(config);
+ await withCrossProcessLock(path.join(root, 'download.lock'), { label: 'other-instance', waitMs: 0 }, async status => {
+ expect(status.held).toBe(true);
+ await expect(provisioner.prefetch({ manifest: { app: {} } as never })).resolves.toBe(false);
+ expect(mocks.backgroundDownload).not.toHaveBeenCalled();
+ expect(fs.readFileSync(oldPath, 'utf8')).toBe('local');
+ });
+ await expect(provisioner.prefetch({ manifest: { app: {} } as never })).resolves.toBe(true);
+ });
});
describe('startup binary version check policy', () => {
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts
index 2d18c28c6e..adbf6fc202 100644
--- a/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts
+++ b/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { gzipSync } from 'node:zlib';
+import { createHash } from 'node:crypto';
import { c as createTar } from 'tar';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Manifest } from '../../manifestService';
@@ -16,6 +17,7 @@ const mocks = vi.hoisted(() => ({
remoteManifest: null as Manifest | null,
fetchManifest: vi.fn(),
download: vi.fn(),
+ backgroundDownload: vi.fn(),
execFile: vi.fn(),
systemCommands: new Map<string, string>(),
}));
@@ -37,6 +39,7 @@ vi.mock('../../manifestService.js', () => ({
}));
vi.mock('../../downloader/index.js', () => ({
download: mocks.download,
+ createDownloader: () => mocks.backgroundDownload,
DownloadError: class DownloadError extends Error {},
}));
vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn() }) }));
@@ -117,6 +120,7 @@ beforeEach(async () => {
}
return { path: targetPath, size: 7 };
});
+ mocks.backgroundDownload.mockReset();
await reloadBinaries();
});
afterEach(() => {
@@ -126,6 +130,44 @@ afterEach(() => {
afterAll(() => { fs.rmSync(tempRoot, { recursive: true, force: true }); });
describe('shared startup policy through the real binary preparation chain', () => {
+ // Public index -> cache -> original installer. Windows has an .exe entrypoint;
+ // Linux can start from a system CLI. Existing tests had no background/next-start
+ // handoff. Tier: unit, real local archives with a fake network.
+ it.each(['darwin', 'win32', 'linux'] as const)('adopts a background Codex download on the next %s startup while keeping the running path unchanged', async platform => {
+ await reloadBinaries(platform);
+ const version = newerStableVersion(PINNED_CODEX_VERSION);
+ const source = fs.mkdtempSync(path.join(tempRoot, 'prefetch-package-'));
+ const binaryName = path.join('bin', platform === 'win32' ? 'codex.exe' : 'codex');
+ writeExecutable(path.join(source, binaryName), version);
+ fs.writeFileSync(path.join(source, 'codex-package.json'), '{}');
+ const archivePath = path.join(source, 'payload.tar.gz');
+ await createTar({ file: archivePath, cwd: source, gzip: true }, ['bin', 'codex-package.json']);
+ const bytes = fs.readFileSync(archivePath);
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
+ mocks.remoteManifest = { app: { version: '2.0.0' }, codexPackage: {
+ version, file: `codex-package/${version}/runtime.tar.gz`, sha256, size: bytes.length,
+ } };
+ const oldPath = platform === 'linux'
+ ? writeExecutable(path.join(tempRoot, 'system-prefetch-codex'), 'codex-cli ' + PINNED_CODEX_VERSION)
+ : installManaged('codex', PINNED_CODEX_VERSION);
+ if (platform === 'linux') mocks.systemCommands.set('codex', oldPath);
+ await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true, path: oldPath });
+ mocks.backgroundDownload.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.writeFileSync(targetPath, bytes);
+ return { path: targetPath, sha256, size: bytes.length };
+ });
+ await expect(binaries.prefetch('codex', { manifest: mocks.remoteManifest! })).resolves.toBe(true);
+ expect(binaries.getReadyBinaryPath('codex')).toBe(oldPath);
+ expect(fs.existsSync(oldPath)).toBe(true);
+ await reloadBinaries(platform);
+ const nextPath = path.join(mocks.userDataDir, 'codex-package', version, binaryName);
+ await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true, path: nextPath });
+ expect(fs.readFileSync(nextPath, 'utf8')).toBe(version);
+ expect(fs.readFileSync(path.join(mocks.userDataDir, 'codex-package', version, 'codex-package.json'), 'utf8')).toBe('{}');
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(mocks.userDataDir, 'agent-binary-downloads', 'codex', sha256))).toBe(false);
+ });
+
it.each(['darwin', 'win32', 'linux'] as const)('reuses managed runtimes by default on %s after fetching manifest', async (platform) => {
await reloadBinaries(platform);
for (const kind of ['claude-code', 'codex', 'pi'] as const) {
@@ -137,8 +179,8 @@ describe('shared startup policy through the real binary preparation chain', () =
expect(mocks.download).not.toHaveBeenCalled();
});
- it('consumes a matching marker once and retains the upgrade decision for retries and other vendors', async () => {
- writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');
+ it('consumes a legacy harness marker once and retains its repair decision for retries and other vendors', async () => {
+ writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0', ['pi', 'codex']);
installManaged('pi');
await expect(binaries.peekNeedsDownload('pi')).resolves.toBe(true);
expect(fs.existsSync(path.join(mocks.userDataDir, 'agent-binary-update-once.json'))).toBe(false);
@@ -154,6 +196,18 @@ describe('shared startup policy through the real binary preparation chain', () =
expect(mocks.download).toHaveBeenCalledTimes(2);
});
+ // Migration regression: older app updaters write an unscoped marker. With no
+ // prepared download, the next startup must keep usable runtimes, not fetch them.
+ it('consumes an old application-update marker without forcing any runtime download', async () => {
+ const paths = new Map((['claude-code', 'codex', 'pi'] as const).map(kind => [kind, installManaged(kind)]));
+ writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');
+ for (const [kind, binaryPath] of paths) {
+ await expect(binaries.prepare(kind, quiet)).resolves.toMatchObject({ ready: true, path: binaryPath });
+ }
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(mocks.userDataDir, 'agent-binary-update-once.json'))).toBe(false);
+ });
+
it('limits a harness-scoped marker to the confirmed harness', async () => {
writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0', ['codex']);
installManaged('claude-code');
@@ -165,7 +219,7 @@ describe('shared startup policy through the real binary preparation chain', () =
});
it.each([false, true])('Pi background recovery inherits checkForUpdates=%s without caller flags', async (allowUpdates) => {
- if (allowUpdates) writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');
+ if (allowUpdates) writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0', ['pi']);
const localPath = installManaged('pi');
mocks.remoteManifest = null;
const startup = await binaries.prepare('pi', quiet);
@@ -257,6 +311,10 @@ describe('Linux local discovery before any update download', () => {
expect(mocks.download).not.toHaveBeenCalled();
writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');
await reloadBinaries('linux');
+ await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true, path: systemPath });
+ expect(mocks.download).not.toHaveBeenCalled();
+ writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0', ['codex']);
+ await reloadBinaries('linux');
await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true });
expect(binaries.getReadyBinaryPath('codex')).not.toBe(systemPath);
diff --git a/apps/desktop/src/main/agent-binaries/background-update.ts b/apps/desktop/src/main/agent-binaries/background-update.ts
new file mode 100644
index 0000000000..d8a46b84ef
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/background-update.ts
@@ -0,0 +1,61 @@
+import { app } from 'electron';
+import { isCindyPersonalRuntime } from '../cindy-make/versionRuntimeIdentity.js';
+import { getCachedManifest, onManifestFetched, type Manifest } from '../manifestService.js';
+import { prefetch } from './index.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('agent-binaries/background-update');
+let unsubscribe: (() => void) | undefined;
+let timer: ReturnType<typeof setTimeout> | undefined;
+let controller: AbortController | undefined;
+let pending: Manifest | undefined;
+let running = false;
+
+/** Start after environment readiness. The app's existing checks supply fresh metadata. */
+export function startBinaryBackgroundUpdates(): void {
+ if (unsubscribe || !app.isPackaged || isCindyPersonalRuntime()) return;
+ controller = new AbortController();
+ const signal = controller.signal;
+ const queue = (manifest: Manifest): void => {
+ pending = manifest;
+ if (running || timer) return;
+ timer = setTimeout(() => { timer = undefined; void run(signal); }, 0);
+ timer.unref?.();
+ };
+ unsubscribe = onManifestFetched(queue);
+ // Let the main window finish opening; do not add any await to startup.
+ timer = setTimeout(() => {
+ timer = undefined;
+ const manifest = pending ?? getCachedManifest();
+ if (manifest) queue(manifest);
+ }, 10_000);
+ timer.unref?.();
+ app.once('will-quit', stopBinaryBackgroundUpdates);
+}
+
+async function run(signal: AbortSignal): Promise<void> {
+ running = true;
+ try {
+ while (pending && !signal.aborted) {
+ const manifest = pending;
+ pending = undefined;
+ for (const kind of ['claude-code', 'codex', 'pi'] as const) {
+ if (signal.aborted) break;
+ await prefetch(kind, { manifest, signal });
+ }
+ }
+ } catch {
+ log.warn('Binary prefetch stopped; a later update check will retry');
+ } finally { running = false; }
+}
+
+export function stopBinaryBackgroundUpdates(): void {
+ unsubscribe?.();
+ unsubscribe = undefined;
+ if (timer) clearTimeout(timer);
+ timer = undefined;
+ controller?.abort();
+ controller = undefined;
+ pending = undefined;
+ app.removeListener('will-quit', stopBinaryBackgroundUpdates);
+}
diff --git a/apps/desktop/src/main/agent-binaries/download-cache.ts b/apps/desktop/src/main/agent-binaries/download-cache.ts
new file mode 100644
index 0000000000..8ce630de9f
--- /dev/null
+++ b/apps/desktop/src/main/agent-binaries/download-cache.ts
@@ -0,0 +1,134 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { app } from 'electron';
+import { createDownloader, type DownloadOptions, type DownloadResult } from '../downloader/index.js';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import { getBaseUrl, getPlatformKey } from '../manifestService.js';
+import { createLogger } from '../logger.js';
+import type { VendorAsset } from './manifest.js';
+import type { VendorKey } from './types.js';
+
+const log = createLogger('agent-binaries/download-cache');
+const MAX_AGE_MS = 7 * 24 * 60 * 60_000;
+const inFlight = new Map<string, { identity: string; task: Promise<boolean> }>();
+let backgroundDownload: ((opts: DownloadOptions) => Promise<DownloadResult>) | undefined;
+
+function rootFor(vendor: VendorKey): string {
+ return path.join(app.getPath('userData'), 'agent-binary-downloads', vendor);
+}
+
+function identity(asset: VendorAsset): string {
+ return JSON.stringify({ source: getBaseUrl(), platform: getPlatformKey(), ...asset, sha256: asset.sha256.toLowerCase() });
+}
+
+function directoryFor(vendor: VendorKey, asset: VendorAsset): string | undefined {
+ if (!/^[a-f0-9]{64}$/i.test(asset.sha256) || !Number.isSafeInteger(asset.size) || asset.size <= 0) return;
+ return path.join(rootFor(vendor), asset.sha256.toLowerCase());
+}
+
+/** Metadata is only a hint; consumers hash the archive again before using it. */
+export function hasPreparedBinaryDownload(vendor: VendorKey, asset: VendorAsset): boolean {
+ const directory = directoryFor(vendor, asset);
+ if (!directory) return false;
+ try {
+ return fs.readFileSync(path.join(directory, 'ready.json'), 'utf8') === identity(asset)
+ && fs.statSync(path.join(directory, 'archive')).size === asset.size;
+ } catch { return false; }
+}
+
+/** Only our hash-named cache children are eligible; live installs are elsewhere. */
+function trim(root: string, keep?: string): void {
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
+ if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;
+ const directory = path.join(root, entry.name);
+ if (entry.name === keep && Date.now() - fs.statSync(directory).mtimeMs <= MAX_AGE_MS) continue;
+ try { fs.rmSync(directory, { recursive: true, force: true }); }
+ catch { log.warn('Could not remove an obsolete binary download; will retry later'); }
+ }
+}
+
+/**
+ * An independent, single-slot queue keeps these optional transfers out of the
+ * application's update queue. Same-target callers share a task, including About.
+ */
+export function prefetchBinaryDownload(vendor: VendorKey, asset: VendorAsset, signal?: AbortSignal): Promise<boolean> {
+ const directory = directoryFor(vendor, asset);
+ if (!directory) return Promise.resolve(false);
+ const expectedIdentity = identity(asset);
+ const key = rootFor(vendor);
+ const previous = inFlight.get(key);
+ if (previous?.identity === expectedIdentity) return previous.task;
+ // Serialize different candidates too; the next caller rechecks the cache.
+ const task = (async () => {
+ if (previous) await previous.task;
+ signal?.throwIfAborted();
+ fs.mkdirSync(key, { recursive: true });
+ return withCrossProcessLock(path.join(key, 'download.lock'), { label: 'agent-binary-download', waitMs: 0 }, async status => {
+ if (!status.held) return false;
+ trim(key, asset.sha256.toLowerCase());
+ fs.mkdirSync(directory, { recursive: true });
+ // No .verified marker or live-path mutation: this archive cannot be selected
+ // as an installed runtime by either this process or an older Cindy version.
+ backgroundDownload ??= createDownloader();
+ await backgroundDownload({
+ url: `${getBaseUrl()}/${asset.file}`,
+ targetPath: path.join(directory, 'archive'),
+ sha256: asset.sha256.toLowerCase(),
+ expectedSize: asset.size,
+ signal,
+ timeout: { totalMs: 180_000 },
+ retry: { maxAttempts: 3 },
+ });
+ signal?.throwIfAborted();
+ // A channel/endpoint change cannot publish the old source under a new identity.
+ if (identity(asset) !== expectedIdentity) return false;
+ fs.writeFileSync(path.join(directory, 'ready.json'), expectedIdentity);
+ const now = new Date();
+ fs.utimesSync(directory, now, now);
+ return true;
+ }, signal);
+ })().catch(() => {
+ log.warn('Background binary download did not finish; the installed runtime is unchanged');
+ return false;
+ });
+ inFlight.set(key, { identity: expectedIdentity, task });
+ void task.finally(() => { if (inFlight.get(key)?.task === task) inFlight.delete(key); });
+ return task;
+}
+
+/** Copy a verified cache hit into the existing installer, without network IO. */
+export async function copyPreparedBinaryDownload(
+ vendor: VendorKey, asset: VendorAsset, destination: string, signal?: AbortSignal,
+): Promise<boolean> {
+ if (!hasPreparedBinaryDownload(vendor, asset)) return false;
+ const root = rootFor(vendor);
+ const directory = directoryFor(vendor, asset)!;
+ return withCrossProcessLock(path.join(root, 'download.lock'), { label: 'agent-binary-download', waitMs: 0 }, async status => {
+ if (!status.held || !hasPreparedBinaryDownload(vendor, asset)) return false;
+ const archive = path.join(directory, 'archive');
+ const hash = createHash('sha256');
+ for await (const chunk of fs.createReadStream(archive)) {
+ signal?.throwIfAborted();
+ hash.update(chunk);
+ }
+ if (hash.digest('hex') !== asset.sha256.toLowerCase()) {
+ fs.rmSync(directory, { recursive: true, force: true });
+ return false;
+ }
+ await fs.promises.mkdir(path.dirname(destination), { recursive: true });
+ await fs.promises.copyFile(archive, destination);
+ // The installer now owns its copy and removes it after extraction, as before.
+ fs.rmSync(directory, { recursive: true, force: true });
+ return true;
+ }, signal);
+}
+
+/** Clean abandoned candidates even when the currently installed version is newer. */
+export async function clearPreparedBinaryDownloads(vendor: VendorKey): Promise<void> {
+ const root = rootFor(vendor);
+ if (!fs.existsSync(root)) return;
+ await withCrossProcessLock(path.join(root, 'download.lock'), { label: 'agent-binary-download', waitMs: 0 }, async status => {
+ if (status.held) trim(root);
+ });
+}
diff --git a/apps/desktop/src/main/agent-binaries/factory.ts b/apps/desktop/src/main/agent-binaries/factory.ts
index 7a0014cc6e..22b0d42c5e 100644
--- a/apps/desktop/src/main/agent-binaries/factory.ts
+++ b/apps/desktop/src/main/agent-binaries/factory.ts
@@ -31,6 +31,13 @@ import {
normalizeBinaryVersion,
} from './binary-version-probe.js';
import { getVendorAsset, resolveVendorAssetUrl, type VendorAsset } from './manifest.js';
+import {
+ clearPreparedBinaryDownloads,
+ copyPreparedBinaryDownload,
+ hasPreparedBinaryDownload,
+ prefetchBinaryDownload,
+} from './download-cache.js';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
import { download, DownloadError, type ProgressEvent } from '../downloader/index.js';
import {
fetchManifest,
@@ -233,6 +240,7 @@ async function extractTarGzDir(srcTarGz: string, destDir: string, binaryName: st
export function createBinaryProvisioner(config: BinaryProvisionerConfig): BinaryProvisioner {
let state: VendorRuntimeState = { status: 'not_installed' };
+ let preparing: ReturnType<BinaryProvisioner['prepare']> | undefined;
const localVersionCache = new Map<string, { mtimeMs: number; size: number; version: string }>();
async function resolveLocalVersion(
@@ -285,13 +293,67 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
: findLatestVerifiedBinary(config.installSubdir, deriveBinaryName());
}
+ function exclusivelyPrepare(
+ opts: Parameters<BinaryProvisioner['prepare']>[0],
+ install: () => ReturnType<BinaryProvisioner['prepare']>,
+ ): ReturnType<BinaryProvisioner['prepare']> {
+ if (preparing) return preparing;
+ // Startup retries and another Cindy sharing this profile cannot extract or
+ // clean each other's installation. Cache downloads use their own lock.
+ const task = withCrossProcessLock(
+ path.join(getInstallRoot(config.installSubdir), 'install.lock'),
+ { label: 'agent-binary-install', waitMs: 0 },
+ async status => {
+ if (status.held) return install();
+ const local = config.optionalAsset ? null : await findUsableLocalBinary(opts?.signal);
+ if (local) {
+ emit({ status: 'ready', installedVersion: local.version, binaryPath: local.binaryPath }, opts?.onProgress);
+ return { ready: true, binaryPath: local.binaryPath };
+ }
+ return { ready: false, binaryPath: '', error: 'install_busy' };
+ },
+ opts?.signal,
+ );
+ preparing = task;
+ const clear = () => { if (preparing === task) preparing = undefined; };
+ void task.then(clear, clear);
+ return task;
+ }
+
return {
+ async prefetch(opts) {
+ try {
+ const manifest = opts?.manifest ?? getCachedManifest();
+ if (!manifest) return false;
+ const asset = getVendorAsset(manifest, config.manifestField);
+ if (!asset) {
+ await clearPreparedBinaryDownloads(config.vendorKey);
+ return false;
+ }
+ const assetPlatform = asset.file.match(/\/(linux-x64|linux-arm64|darwin-arm64|darwin-x64|win32-x64|win32-arm64)\//)?.[1];
+ if (assetPlatform && assetPlatform !== getPlatformKey()) return false;
+ const preferred = await findPreferredLocalBinary(
+ config.installSubdir, deriveBinaryName(), asset.version,
+ config.localVersionResolver ? resolveLocalVersion : undefined, opts?.signal,
+ );
+ if (preferred || (!config.localVersionResolver && isInstalled(config.installSubdir, asset.version, deriveBinaryName()))) {
+ await clearPreparedBinaryDownloads(config.vendorKey);
+ return true;
+ }
+ return await prefetchBinaryDownload(config.vendorKey, asset, opts?.signal);
+ } catch {
+ return false;
+ }
+ },
+
async getState(): Promise<VendorRuntimeState> {
return { ...state };
},
- async prepare(opts) {
+ prepare: (opts) => exclusivelyPrepare(opts, async () => {
const onProgress = opts?.onProgress;
+ let failedInstallDirectory: string | undefined;
+ let preparedUpdateFallback: { version: string; binaryPath: string } | undefined;
try {
const binaryName = deriveBinaryName();
// 1. 拉 manifest(不带 dev fallback —— dev mode 归属在 Boss 2 包壳层)
@@ -345,13 +407,14 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
}
emit({ availableVersion: asset.version }, onProgress);
- if (opts?.checkForUpdates === false) {
- const local = await findUsableLocalBinary(opts.signal);
- if (local) {
- emit({ status: 'ready', installedVersion: local.version, binaryPath: local.binaryPath }, onProgress);
- return { ready: true, binaryPath: local.binaryPath };
- }
+ const usableLocal = opts?.checkForUpdates === false ? await findUsableLocalBinary(opts.signal) : null;
+ if (usableLocal && !hasPreparedBinaryDownload(config.vendorKey, asset)) {
+ emit({ status: 'ready', installedVersion: usableLocal.version, binaryPath: usableLocal.binaryPath }, onProgress);
+ return { ready: true, binaryPath: usableLocal.binaryPath };
}
+ // The current manifest still permits this runtime. A bad optional update
+ // must not disable an otherwise usable Pi installation on the next start.
+ if (usableLocal) preparedUpdateFallback = usableLocal;
// 3. 本地真实版本不低于 manifest:保留用户自更新结果,禁止降级与旧版清理。
const preferredLocal = await findPreferredLocalBinary(
@@ -387,6 +450,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
// 4. 准备目录
const versionDir = getVersionDir(config.installSubdir, asset.version);
+ if (!fs.existsSync(getVerifiedMarker(config.installSubdir, asset.version))) failedInstallDirectory = versionDir;
fs.mkdirSync(versionDir, { recursive: true });
// 5. 计算下载目标路径(gz 中间文件加 .gz 后缀,tar-gz-dir 落整包归档,
@@ -406,7 +470,16 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
// 命中时会闪一次 0→100 的假进度。'downloading' 状态与进度广播完全由
// 传输层真实的 onProgress 事件驱动(transport 在收到 HTTP response 后
// 才发首个事件 = 下载真正开始)。
- await download({
+ const prepared = await copyPreparedBinaryDownload(config.vendorKey, asset, downloadDest, opts?.signal);
+ if (!prepared && usableLocal) {
+ // Background prefetch is optional: a missing/corrupt/busy cache must
+ // never turn an application update into a blocking startup download.
+ emit({ status: 'ready', installedVersion: usableLocal.version, binaryPath: usableLocal.binaryPath }, onProgress);
+ if (failedInstallDirectory) fs.rmSync(failedInstallDirectory, { recursive: true, force: true });
+ return { ready: true, binaryPath: usableLocal.binaryPath };
+ }
+ if (!prepared && opts?.allowDownload === false) throw new Error('prepared_download_unavailable');
+ if (!prepared) await download({
url,
targetPath: downloadDest,
sha256: asset.sha256.toLowerCase(),
@@ -449,6 +522,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
try { fs.chmodSync(finalBinPath, 0o755); } catch { /* ignore */ }
}
fs.writeFileSync(getVerifiedMarker(config.installSubdir, asset.version), '', 'utf-8');
+ failedInstallDirectory = undefined;
// 9. cleanup 旧版本
cleanupOldVersions(config.installSubdir, asset.version);
@@ -462,6 +536,9 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
return { ready: true, binaryPath: finalBinPath };
} catch (err) {
+ if (failedInstallDirectory) {
+ try { fs.rmSync(failedInstallDirectory, { recursive: true, force: true }); } catch { /* retry on the next install */ }
+ }
const message = err instanceof Error ? err.message : String(err);
// NOT_IMPLEMENTED_* 必须 rethrow(让 Boss 4 / 未来消费者立即感知)
if (message === 'NOT_IMPLEMENTED_BOSS_4' || message === 'NOT_IMPLEMENTED') {
@@ -476,9 +553,9 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
// A proxy that permits manifest URLs but blocks CDN binaries would
// otherwise leave the user stuck even when a verified local version
// exists.
- const localFallback = config.optionalAsset
+ const localFallback = preparedUpdateFallback ?? (config.optionalAsset
? null
- : findLatestVerifiedBinary(config.installSubdir, config.artifact.binaryName);
+ : findLatestVerifiedBinary(config.installSubdir, config.artifact.binaryName));
if (localFallback) {
emit({
status: 'ready',
@@ -493,7 +570,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary
}, opts?.onProgress);
return { ready: false, binaryPath: '', error: code };
}
- },
+ }),
async peekNeedsDownload(opts): Promise<boolean> {
// 不发起任何下载——只读 manifest(cache 优先)+ 本地 isInstalled 检查。
diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.ts
index 73d7446e0c..8b64d38ee3 100644
--- a/apps/desktop/src/main/agent-binaries/index.ts
+++ b/apps/desktop/src/main/agent-binaries/index.ts
@@ -6,7 +6,8 @@ import { createPiKernelManager, type PiKernelManager } from './pi-kernel-manager
* 2026-08 起 pi 也走本模块(整目录 tar.gz 分发,可选资产,失败由 pi-host 降级)。
*
* 公开 API (全部走 (kind, ...) 形态, 调用方不再分 claude/codex 各导一份):
- * prepare(kind, opts?) — splash 下载入口, 真做 dev fallback / OSS 下载 / SHA256 校验 / IPC 进度广播
+ * prepare(kind, opts?) — 启动安装入口,优先复用后台下载;首装/修复保留网络兜底
+ * prefetch(kind, opts?) — 后台/About 共用的下载缓存,不切换当前运行路径
* getCachedBinaryStatus(kind) — 同步快查 (DropdownMenu 元 IPC 用), 不触发下载
* getReadyBinaryPath(kind) — 读 prepare() 成功后写入的 cache 路径 (maker-host 构造期同步注入)
* peekNeedsDownload(kind) — splash 顺序检查用
@@ -49,6 +50,7 @@ import {
import { ProgressNormalizer } from '../updateProgressNormalizer.js';
import { createLogger } from '../logger.js';
import { consumeStartupBinaryUpdateMarker, type StartupBinaryUpdateScope } from './startup-update.js';
+import { clearPreparedBinaryDownloads, hasPreparedBinaryDownload } from './download-cache.js';
let startupUpdateScope: StartupBinaryUpdateScope | undefined;
@@ -56,7 +58,10 @@ function resolveUpdateCheck(kind: AgentBinaryKind, checkForUpdates?: boolean): b
startupUpdateScope ??= app.isPackaged
&& consumeStartupBinaryUpdateMarker(app.getPath('userData'), app.getVersion());
if (checkForUpdates !== undefined) return checkForUpdates;
- return startupUpdateScope === true || (Array.isArray(startupUpdateScope) && startupUpdateScope.includes(kind));
+ // Legacy application-update markers must not force a network upgrade anymore.
+ // prepare() adopts a completed background download, otherwise keeps the usable
+ // local runtime. Scoped markers from older About flows retain their repair path.
+ return Array.isArray(startupUpdateScope) && startupUpdateScope.includes(kind);
}
/**
@@ -265,6 +270,20 @@ export function getReadyBinaryPath(kind: AgentBinaryKind): string | undefined {
return lastReadyPath.get(kind);
}
+/** Background/About share the cache, while the running process keeps its path. */
+export async function prefetch(
+ kind: AgentBinaryKind,
+ opts: { manifest?: Manifest; signal?: AbortSignal } = {},
+): Promise<boolean> {
+ if (!app.isPackaged) return false;
+ // An explicit Pi selection (including an intentional downgrade) is authoritative.
+ if (kind === 'pi' && getPiKernelManager().hasSelection()) {
+ await clearPreparedBinaryDownloads('pi').catch(() => undefined);
+ return true;
+ }
+ return getBase(kind).prefetch(opts);
+}
+
/**
* spawn/execFile 前的执行侧复核:candidate 必须与本模块此刻能解析出的受管二进制
* 路径完全一致。二进制路径本就只该出自本模块,这里再挡一层意外来源作为防御纵深
@@ -426,8 +445,15 @@ export async function prepare(
if (!hasLocalCdnRuntime) {
const localPath = await findUsableLinuxRuntimeFallbackBinary(kind, opts.signal);
if (localPath) {
- lastReadyPath.set(kind, localPath);
- return { ready: true, path: localPath, downloaded: false };
+ const manifest = getCachedManifest();
+ const asset = manifest && getVendorAsset(manifest, cfg.manifestField);
+ if (!asset || !hasPreparedBinaryDownload(cfg.vendorKey, asset)) {
+ lastReadyPath.set(kind, localPath);
+ return { ready: true, path: localPath, downloaded: false };
+ }
+ // Try the completed cache first. A corrupt or locked cache falls back
+ // to the working system/private runtime without starting network IO.
+ opts = { ...opts, allowDownload: false };
}
}
}
@@ -536,7 +562,7 @@ async function prepareViaCdn(
// ── 不广播 IPC 路径 (lazy 调用, 当前 desktop 不走) ────────────────────────
if (!broadcastProgress) {
- const result = await base.prepare({ signal: opts.signal, checkForUpdates: opts.checkForUpdates });
+ const result = await base.prepare({ signal: opts.signal, checkForUpdates: opts.checkForUpdates, allowDownload: opts.allowDownload });
if (result.ready) {
lastReadyPath.set(kind, result.binaryPath);
return { ready: true, path: result.binaryPath };
@@ -602,6 +628,7 @@ async function prepareViaCdn(
const result = await base.prepare({
signal: effectiveSignal,
checkForUpdates: opts.checkForUpdates,
+ allowDownload: opts.allowDownload,
onProgress: (p: VendorRuntimeState) => {
if (p.status === 'downloading') {
didDownload = true;
diff --git a/apps/desktop/src/main/agent-binaries/startup-update.ts b/apps/desktop/src/main/agent-binaries/startup-update.ts
index 32808e4f55..1319713bd6 100644
--- a/apps/desktop/src/main/agent-binaries/startup-update.ts
+++ b/apps/desktop/src/main/agent-binaries/startup-update.ts
@@ -9,8 +9,8 @@ const MARKER_FILE = 'agent-binary-update-once.json';
const MARKER_KINDS: readonly AgentBinaryKind[] = ['claude-code', 'codex', 'pi'];
/**
- * Which managed binaries the next startup may refresh: `true` = all (app update),
- * a list = only the harnesses the user confirmed, `false` = ordinary startup.
+ * Legacy startup intent: `true` = application update (now cache adoption only),
+ * a list = explicit harness update/repair, `false` = ordinary startup.
*/
export type StartupBinaryUpdateScope = boolean | readonly AgentBinaryKind[];
diff --git a/apps/desktop/src/main/agent-binaries/types.ts b/apps/desktop/src/main/agent-binaries/types.ts
index 7f662c7e3c..00b5ee5f39 100644
--- a/apps/desktop/src/main/agent-binaries/types.ts
+++ b/apps/desktop/src/main/agent-binaries/types.ts
@@ -1,3 +1,5 @@
+import type { Manifest } from '../manifestService.js';
+
/**
* apps/desktop/src/main/agent-binaries/types.ts
*
@@ -56,6 +58,9 @@ export interface VendorRuntimeState {
// ===== §5.2 BinaryProvisioner =====
/** @frozen v1.0 */
export interface BinaryProvisioner {
+ /** Download only; never selects a new runtime or removes the running version. */
+ prefetch(opts?: { manifest?: Manifest; signal?: AbortSignal }): Promise<boolean>;
+
/** 不触发下载,仅返回当前状态。Renderer 用来决定是否需要触发 prepare */
getState(): Promise<VendorRuntimeState>;
@@ -63,6 +68,8 @@ export interface BinaryProvisioner {
prepare(opts?: {
onProgress?: (p: VendorRuntimeState) => void;
checkForUpdates?: boolean;
+ /** false when a usable Linux fallback only needs an already downloaded update. */
+ allowDownload?: boolean;
/** 取消排队、下载或重试等待;已完成的本地命中不受影响。 */
signal?: AbortSignal;
}): Promise<{ ready: boolean; binaryPath: string; error?: string }>;
@@ -82,6 +89,8 @@ export interface BinaryProvisioner {
export interface PrepareOpts {
checkForUpdates?: boolean;
+ /** Internal cache adoption path; never prevents normal first-install repair. */
+ allowDownload?: boolean;
/** D 场景顺序下载阶段标记,会写进 IPC payload 给 splash 显示 (x/y) 文案。 */
step?: 1 | 2 | 3;
/** D 场景 = 本次需要下载的 vendor 数(2 或 3);B/C 场景缺省。 */
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index ac7ffdaf21..dec36d44da 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -978,6 +978,7 @@ import {
} from './maker-ipc/usage.js';
import { prewarmModelPricing } from './usage/modelPricing.js';
import { registerMakerBinaryVersionIpc } from './maker-ipc/binary-version.js';
+import { startBinaryBackgroundUpdates } from './agent-binaries/background-update.js';
import { registerCrossAgentConvertIpc } from './cross-agent-convert/ipc.js';
import { registerFileBrowserIpc } from './file-browser/index.js';
import { disposeHtmlPreviews } from './file-browser/html-preview-ipc.js';
@@ -6681,6 +6682,7 @@ const registerIpcHandlers = () => {
// 必装 binary 都 ready,现在才能安全构造 Maker 单例并挂 maker:* / 相关 IPC。
await registerMakerIpcsAfterSplash();
+ startBinaryBackgroundUpdates();
return {
claudeCode: { status: 'passed' as const, path: claudeRes.path },
diff --git a/apps/desktop/src/main/manifestService.ts b/apps/desktop/src/main/manifestService.ts
index 79a2c9dca8..1c8fd344d4 100644
--- a/apps/desktop/src/main/manifestService.ts
+++ b/apps/desktop/src/main/manifestService.ts
@@ -114,6 +114,13 @@ let cachedChannel: UpdateChannel | null = null;
* 不写缓存、返回 null,让调用方(agent prepare / 更新轮询)下次按新渠道重新 fetch。
*/
let manifestEpoch = 0;
+const manifestListeners = new Set<(manifest: Manifest) => void>();
+
+/** Observers cannot delay or fail application update checks. */
+export function onManifestFetched(listener: (manifest: Manifest) => void): () => void {
+ manifestListeners.add(listener);
+ return () => { manifestListeners.delete(listener); };
+}
function currentUpdateChannel(): UpdateChannel {
return resolveUpdateChannel(canaryFlagStore.read(), isBetaChannelEnabled());
@@ -243,6 +250,9 @@ export async function fetchManifest(
cachedChannel = channel;
log.info('Fetched OK: app.version=%s, hotfix=%s', json.app?.version, json.app?.hotfix?.file ?? 'none');
finish(json);
+ for (const listener of manifestListeners) {
+ try { listener(json); } catch { /* an optional observer cannot fail the update */ }
+ }
} catch (err) {
log.error('JSON parse failed:', err);
finish(null);
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index b63a61951a..e768c5d793 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -44,6 +44,8 @@ import { compareAppUpdateVersions } from './updateVersionPolicy';
import { CURRENT_APP_ID } from '../shared/brandRegion';
import { syncWindowsVersionAfterUpdate, windowsInstallKey } from './windowsInstallationVersion';
import { writeStartupBinaryUpdateMarker } from './agent-binaries/startup-update';
+import { prefetch as prefetchAgentBinary } from './agent-binaries/index.js';
+import { getVendorAsset } from './agent-binaries/manifest.js';
import { createLogger, maskPath } from './logger';
import {
@@ -2063,8 +2065,9 @@ async function executeRelaunchUnguarded(
maskPath(readyFilePath), fs.statSync(readyFilePath).size,
);
- // Every applied app update — manual, idle or startup auto-relaunch — checks
- // agent binaries once on the next launch; ordinary launches do not.
+ // Keep the legacy marker for rollback compatibility. New startups adopt only
+ // completed binary downloads and reuse usable local runtimes otherwise;
+ // application-update readiness never waits for optional binary preparation.
if (readyVersion) {
cancelStartupBinaryUpdateCheck = writeStartupBinaryUpdateMarker(app.getPath('userData'), readyVersion);
}
@@ -2466,6 +2469,26 @@ export function initUpdateService(): void {
app.quit();
});
+ // About downloads before showing the restart confirmation. A failed preparation
+ // leaves both the application update state and the running harness untouched.
+ ipcMain.handle('update-harness-prepare', async (event, kind: unknown, expectedVersion: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if ((kind !== 'claude-code' && kind !== 'codex') || typeof expectedVersion !== 'string'
+ || expectedVersion.length === 0 || expectedVersion.length > 128) {
+ throwIpcError('INVALID_PARAMS', 'kind and expectedVersion required');
+ }
+ const signal = AbortSignal.timeout(180_000);
+ const manifest = await fetchManifest(undefined, signal);
+ const asset = manifest && getVendorAsset(manifest, kind === 'claude-code' ? 'claudeCode' : 'codexPackage');
+ if (!manifest || !asset || asset.version !== expectedVersion) {
+ throwIpcError('INTERNAL', 'harness update changed or is unavailable; check again');
+ }
+ if (!await prefetchAgentBinary(kind, { manifest, signal })) {
+ throwIpcError('INTERNAL', 'could not prepare harness update; retry later');
+ }
+ return { ready: true };
+ });
+
// About → Agent version update: keep the same graceful app relaunch lifecycle,
// but ask the next startup to refresh managed harness binaries before they are
// exposed to Maker. The marker is consumed once by agent-binaries/prepare and
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index caa095930b..de07e9fc90 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2874,6 +2874,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
isCustomized?: boolean;
}> => ipcRenderer.invoke('update-channel-settings-reset'),
relaunchForChannelChange: (): Promise<void> => ipcRenderer.invoke('update-channel-relaunch'),
+ /** Cache the confirmed target before the user chooses to interrupt work and restart. */
+ prepareHarnessUpdate: (kind: 'claude-code' | 'codex', version: string): Promise<{ ready: true }> =>
+ ipcRenderer.invoke('update-harness-prepare', kind, version),
/** Restart once; the next startup refreshes only the confirmed managed harness first. */
relaunchForHarnessUpdate: (kind: 'claude-code' | 'codex'): Promise<{ accepted: true }> =>
ipcRenderer.invoke('update-harness-relaunch', kind),
diff --git a/apps/desktop/src/renderer/components/settings/AboutSection.tsx b/apps/desktop/src/renderer/components/settings/AboutSection.tsx
index eee3abdede..f34a314055 100644
--- a/apps/desktop/src/renderer/components/settings/AboutSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AboutSection.tsx
@@ -207,6 +207,13 @@ function AgentVersionRow({
}) {
const { t, i18n } = useTranslation();
const { confirm } = useConfirmDialog();
+ const [preparing, setPreparing] = useState(false);
+ const preparingRef = useRef(false);
+ const active = useRef(true);
+ useEffect(() => {
+ active.current = true;
+ return () => { active.current = false; };
+ }, []);
const stateRef = useRef(state);
stateRef.current = state;
const currentVersion = state.version ? extractSemver(state.version) : null;
@@ -218,7 +225,7 @@ function AgentVersionRow({
const canUpdate = () => {
const next = stateRef.current;
return Boolean(
- !next.checking &&
+ active.current && !next.checking &&
next.updateAvailable &&
next.version &&
next.latestVersion &&
@@ -226,7 +233,9 @@ function AgentVersionRow({
extractSemver(next.latestVersion),
);
};
- const status = state.checking
+ const status = preparing
+ ? t('settings.about.piKernel.download')
+ : state.checking
? t('settings.about.harnessChecking')
: state.checkFailed
? t('settings.about.harnessCheckFailed')
@@ -235,7 +244,21 @@ function AgentVersionRow({
: '';
const handleUpdate = async () => {
- if (!canUpdate() || !currentVersion || !latestVersion) return;
+ if (preparingRef.current || !canUpdate() || !currentVersion || !latestVersion) return;
+ const targetVersion = stateRef.current.latestVersion;
+ if (!targetVersion) return;
+ preparingRef.current = true;
+ setPreparing(true);
+ try {
+ await window.electronAPI.prepareHarnessUpdate(kind, targetVersion);
+ } catch {
+ toast.error(t('settings.about.harnessUpdateFailed'));
+ return;
+ } finally {
+ preparingRef.current = false;
+ if (active.current) setPreparing(false);
+ }
+ if (!canUpdate() || stateRef.current.latestVersion !== targetVersion) return;
const confirmed = await confirm({
title: t('settings.about.harnessUpdateTitle', { name }),
description: t('settings.about.harnessUpdateDescription', {
@@ -284,16 +307,16 @@ function AgentVersionRow({
manageLabel={t('settings.about.harnessManage', { name })}
version={renderVersion(state, t)}
status={status}
- pending={state.checking}
+ pending={state.checking || preparing}
>
<HarnessVersionMenuItem
label={t('settings.about.harnessUpdateButton', { name })}
version={latestVersion}
- disabled={!updateAvailable || state.checking}
+ disabled={!updateAvailable || state.checking || preparing}
onSelect={() => void handleUpdate()}
/>
<DropdownMenuSeparator />
- <DropdownMenuItem className={HARNESS_MENU_ITEM_CLASS} disabled={state.checking} onSelect={onCheck}>
+ <DropdownMenuItem className={HARNESS_MENU_ITEM_CLASS} disabled={state.checking || preparing} onSelect={onCheck}>
{state.checking ? t('settings.about.harnessChecking') : t('settings.about.harnessCheck')}
</DropdownMenuItem>
{state.checkedAt && (
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx
index 9611373c5b..7ea628bf98 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/AboutSection.binaryVersions.test.tsx
@@ -17,6 +17,7 @@ import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
const getBinaryVersion = vi.fn();
const getState = vi.fn();
const relaunchForHarnessUpdate = vi.fn();
+const prepareHarnessUpdate = vi.fn();
const anyActivityBlockingRelaunch = vi.fn();
type Online = { latestVersion: string; updateAvailable: boolean } | 'failed' | null;
@@ -52,11 +53,13 @@ describe('AboutSection agent binary versions', () => {
beforeEach(() => {
vi.clearAllMocks();
+ prepareHarnessUpdate.mockResolvedValue({ ready: true });
getState.mockResolvedValue({ currentVersion: '0.84.4', restartRequired: false, official: { release: null }, upstream: { release: null }, operation: null });
anyActivityBlockingRelaunch.mockResolvedValue(false);
HTMLElement.prototype.scrollIntoView = vi.fn();
(window as unknown as { electronAPI: unknown }).electronAPI = {
relaunchForHarnessUpdate,
+ prepareHarnessUpdate,
anyActivityBlockingRelaunch,
maker: {
piKernel: { getState },
@@ -224,7 +227,7 @@ describe('AboutSection agent binary versions', () => {
});
it('requires confirmation and relaunches only for the confirmed harness', async () => {
- mockOnline({ codex: CODEX_UPDATE });
+ mockOnline({ codex: { ...CODEX_UPDATE, latestVersion: 'v1.1.0' } });
relaunchForHarnessUpdate.mockResolvedValue({ accepted: true });
renderRows();
@@ -233,10 +236,48 @@ describe('AboutSection agent binary versions', () => {
fireEvent.click(screen.getByRole('menuitem', { name: /harnessUpdateButton Codex/ }));
await screen.findByText('settings.about.harnessUpdateDescription Codex');
expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
+ expect(prepareHarnessUpdate).toHaveBeenCalledExactlyOnceWith('codex', 'v1.1.0');
fireEvent.click(screen.getByRole('button', { name: 'settings.about.harnessUpdateConfirm Codex' }));
await waitFor(() => expect(relaunchForHarnessUpdate).toHaveBeenCalledExactlyOnceWith('codex'));
});
+ // Manual updates now prepare outside Splash. Keep restart confirmation after
+ // the transfer, and leave failed or abandoned requests safe to retry. Tier: unit.
+ it('shows preparation before asking to restart and permits a retry after download failure', async () => {
+ mockOnline({ codex: CODEX_UPDATE });
+ const preparation = Promise.withResolvers<{ ready: true }>();
+ prepareHarnessUpdate.mockReturnValueOnce(preparation.promise);
+ renderRows();
+ await openMenu('Codex');
+ fireEvent.click(screen.getByRole('menuitem', { name: /harnessUpdateButton Codex/ }));
+ await screen.findByText('settings.about.piKernel.download');
+ expect(screen.queryByText('settings.about.harnessUpdateDescription Codex')).toBeNull();
+ expect(anyActivityBlockingRelaunch).not.toHaveBeenCalled();
+ expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
+ preparation.reject(new Error('download failed'));
+ await waitFor(() => expect(screen.queryByText('settings.about.piKernel.download')).toBeNull());
+ expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
+ await openMenu('Codex');
+ fireEvent.click(screen.getByRole('menuitem', { name: /harnessUpdateButton Codex/ }));
+ await screen.findByText('settings.about.harnessUpdateDescription Codex');
+ expect(prepareHarnessUpdate).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not open a restart confirmation after the settings row was unmounted during preparation', async () => {
+ mockOnline({ codex: CODEX_UPDATE });
+ const preparation = Promise.withResolvers<{ ready: true }>();
+ prepareHarnessUpdate.mockReturnValueOnce(preparation.promise);
+ const rendered = renderRows();
+ await openMenu('Codex');
+ fireEvent.click(screen.getByRole('menuitem', { name: /harnessUpdateButton Codex/ }));
+ await screen.findByText('settings.about.piKernel.download');
+ rendered.unmount();
+ preparation.resolve({ ready: true });
+ await preparation.promise;
+ expect(anyActivityBlockingRelaunch).not.toHaveBeenCalled();
+ expect(relaunchForHarnessUpdate).not.toHaveBeenCalled();
+ });
+
it('asks again before a harness restart would interrupt in-flight work', async () => {
mockOnline({ codex: CODEX_UPDATE });
anyActivityBlockingRelaunch.mockResolvedValue(true);
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 241e8e9477..a124231eef 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4006,6 +4006,8 @@ interface ElectronAPI {
}>;
/** 用户主动重启,让 beta 通道切换在下次冷启动前生效。 */
relaunchForChannelChange: () => Promise<void>;
+ /** 下载并校验指定版本;完成前不重启、不切换当前引擎。 */
+ prepareHarnessUpdate: (kind: 'claude-code' | 'codex', version: string) => Promise<{ ready: true }>;
/** 用户确认后重启,下一次启动只更新所确认的受管 Harness(Pi 由内核管理单独处理)。 */
relaunchForHarnessUpdate: (kind: 'claude-code' | 'codex') => Promise<{ accepted: true }>;
/** 打开 beta 前预检:探测 beta manifest 是否可达(HTTP 200)。 */
diff --git a/docs/dev-rules/cindy-updater.md b/docs/dev-rules/cindy-updater.md
index 8176e2b3f6..8ac70d5f75 100644
--- a/docs/dev-rules/cindy-updater.md
+++ b/docs/dev-rules/cindy-updater.md
@@ -46,6 +46,27 @@ Agent 只能通过 `updateService.ts` 的 `applyConfirmedAppUpdateForAgent` 走
check → download → relaunch 状态机,且必须先经宿主确认卡;不得给 Agent 新开下载、替换或重启
路径。产品规则见 [`../product-rules/agent-app-update.md`](../product-rules/agent-app-update.md)。
+## 引擎二进制的后台下载
+
+主程序的检查、下载、ready、自动重启、替换和回滚条件不依赖引擎下载。环境就绪后,
+`agent-binaries/background-update.ts` 订阅现有更新检查取得的清单,在独立下载队列中缓存
+引擎归档;不更改当前引擎路径,也不删除正在使用的版本。
+
+下次启动仍由原安装器解压、校验安装与选定路径,优先消费已经校验的下载缓存。旧应用
+更新器留下的无范围一次性标记不再强制联网升级;缓存未准备好时复用本地可用版本。
+首次安装、本地版本不可用以及旧版设置入口留下的指定引擎修复标记保留原下载兜底。
+Linux 的可用系统/私有引擎也能消费缓存,缓存不可用时继续使用原引擎。
+
+设置中的 Claude Code/Codex 更新先调用本地 `update-harness-prepare`,复用后台缓存和锁,
+完成后再确认重启及中断运行中的工作;失败可重试,离开设置后不弹出迟到的重启确认。
+Pi 的显式版本选择沿用原内核管理器,不由后台更新覆盖。没有搬迁既有引擎目录、凭证
+或设置,也没有修改 Tauri 更新器;旧客户端忽略新的下载缓存。
+
+行为回归见 `factory-startup-update.test.ts`、`factory-dir-dist.test.ts`、`startup-policy.test.ts`、
+`background-update.test.ts`、`manifestService.test.ts`、`updateService.test.ts` 及
+`AboutSection.binaryVersions.test.tsx`;缓存生命周期见
+[`credentials-and-local-storage.md`](credentials-and-local-storage.md)。
+
## Review 要点
1. 改动是否触及更新器或更新服务?触及就必须先有 owner 确认,PR 说明写明。
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 7171897018..8b083c6ba2 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -196,6 +196,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复
| 数据性质 | 正确位置 |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 引擎二进制后台下载缓存 | `userData/agent-binary-downloads/<vendor>/<归档 SHA-256>/`,只有归档、续传碎片和绑定来源/平台/版本/哈希的就绪记录,不含凭证。每种引擎保留一个候选,切换候选时回收旧候选,超过 7 天的碎片在后续检查时重建。下载与消费共用跨进程缓存锁;启动前复验哈希,复制交给原安装器后回收缓存,解压后的中间包与旧版本仍由原安装器清理。回退旧客户端时这些缓存不会被识别成已安装引擎。见 `agent-binaries/download-cache.ts` |
| Codex 包内 shell 入口 | `<userData>/codex-package/<版本>/codex-path/codex`,打包版 macOS/Linux 在 `getMaker()` 选定实际运行的 Codex 后由主进程原子写入,转发到同包的 `bin/codex`;只更新带 Cindy 标记的旧脚本,不覆盖外来文件。随旧版本目录整体删除,不含凭证。实现见 `agent-binaries/codex-cli-launcher.ts` |
| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |
| 浏览器用户配方 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存配方定义及 active/suspended 状态,不保存试跑的 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。试跑凭证与单轮修复预算只在 MCP 会话内存中,暂停状态跨重启保留。 |
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7e81db2389..5a2da4bdcf 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,14 @@ Profile 版本)。它是显式接受模型的意图;宿主重新校验模型
返回成功视为完成恢复,必须读回版本及发送结果。现有 `update_teammate_profile` 显式提交
`modelChain` 时走同一接受入口,包括重复选择当前值;省略模型字段不改变恢复状态。
+## 设置中的引擎更新准备
+
+Desktop 新增本机 `update-harness-prepare` IPC(Claude Code/Codex、用户看到的目标版本),
+只供可信应用顶层 renderer 在重启确认前准备下载,不暴露到 device-link allowlist。
+原 `update-harness-relaunch` 参数与回复保持兼容,旧设置入口与旧的一次性修复标记仍可
+更新。应用更新 IPC、手机与设备间 wire protocol 不变;后台归档只放新缓存目录,旧客户端
+忽略它,不改变原安装目录、凭证、数据库或持久偏好。
+
## 任务链接保留所属电脑
任务查询返回可选 `sessionUrl`,沿用 `cindy://session/<id>?device=<deviceId>`。