Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): stage startup binary update policy
Lizie6272f79ad5e
diff --git a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.tsindex 292fe0502a..23fe0cdf35 100644--- a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts+++ b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts@@ -9,7 +9,10 @@ const {createBinaryProvisioner,findDevBinary,findCachedLinuxRuntimeFallbackBinary,+ findUsableLinuxRuntimeFallbackBinary,prepareLinuxRuntimeFallback,+ probeBinaryVersion,+ consumeStartupBinaryUpdateMarker,} = vi.hoisted(() => {const cdndProvisioner = {prepare: vi.fn(),@@ -18,12 +21,15 @@ const {cleanup: vi.fn(),};return {- appMock: { isPackaged: true, getPath: vi.fn(() => '/tmp/xdt-userdata') },+ appMock: { isPackaged: true, getPath: vi.fn(() => '/tmp/xdt-userdata'), getVersion: () => '1.0.0' },cdndProvisioner,createBinaryProvisioner: vi.fn(() => cdndProvisioner),findDevBinary: vi.fn((): string | null => null),findCachedLinuxRuntimeFallbackBinary: vi.fn((): string | null => null),+ findUsableLinuxRuntimeFallbackBinary: vi.fn(async (): Promise<string | null> => null),prepareLinuxRuntimeFallback: vi.fn(),+ probeBinaryVersion: vi.fn(),+ consumeStartupBinaryUpdateMarker: vi.fn(() => true),};});@@ -33,8 +39,11 @@ vi.mock('electron', () => ({}));vi.mock('../agent-binaries/factory.js', () => ({ createBinaryProvisioner }));vi.mock('../agent-binaries/dev-fallback.js', () => ({ findDevBinary }));+vi.mock('../agent-binaries/binary-version-probe.js', () => ({ probeBinaryVersion }));+vi.mock('../agent-binaries/startup-update.js', () => ({ consumeStartupBinaryUpdateMarker }));vi.mock('../agent-binaries/linux-runtime-fallback.js', () => ({findCachedLinuxRuntimeFallbackBinary,+ findUsableLinuxRuntimeFallbackBinary,prepareLinuxRuntimeFallback,}));// CDN manifest 缺省不可用(无缓存、拉取也拿不到)。CDN 命中用例单独 stub。@@ -81,6 +90,9 @@ beforeEach(async () => {manifestService.fetchManifest.mockResolvedValue(null);findDevBinary.mockReset().mockReturnValue(null);findCachedLinuxRuntimeFallbackBinary.mockReturnValue(null);+ findUsableLinuxRuntimeFallbackBinary.mockReset().mockResolvedValue(null);+ consumeStartupBinaryUpdateMarker.mockReturnValue(true);+ probeBinaryVersion.mockReset().mockResolvedValue('1.0.0');prepareLinuxRuntimeFallback.mockResolvedValue({ready: true,binaryPath: '/tmp/xdt-userdata/agent-runtime/claude-code/bin/claude',@@ -89,6 +101,86 @@ beforeEach(async () => {});});+describe('startup binary update policy forwarding', () => {+ it.each([true, false])('passes checkForUpdates=false through prepare with broadcastProgress=%s', async (broadcastProgress) => {+ const binaryPath = path.join('/tmp/xdt-userdata', 'claude-code', '1.0.0', 'claude');+ manifestService.getCachedManifest.mockReturnValue({ app: {} });+ cdndProvisioner.prepare.mockResolvedValue({ ready: true, binaryPath });+ await expect(binaries.prepare('claude-code', { checkForUpdates: false, broadcastProgress }))+ .resolves.toMatchObject({ ready: true, path: binaryPath });+ expect(cdndProvisioner.prepare).toHaveBeenCalledWith(expect.objectContaining({ checkForUpdates: false }));+ expect(binaries.getReadyBinaryPath('claude-code')).toBe(binaryPath);+ });++ it('still probes the manifest but keeps a cached Linux fallback instead of downloading a newer CDN asset', async () => {+ const binaryPath = path.join('/tmp/xdt-userdata', 'agent-runtime', 'claude-code', 'bin', 'claude');+ findCachedLinuxRuntimeFallbackBinary.mockReturnValue(binaryPath);+ findUsableLinuxRuntimeFallbackBinary.mockResolvedValue(binaryPath);+ const options = { checkForUpdates: false };+ await expect(binaries.peekNeedsDownload('claude-code', options)).resolves.toBe(false);+ await expect(binaries.prepare('claude-code', options)).resolves.toEqual({ ready: true, path: binaryPath, downloaded: false });+ expect(manifestService.fetchManifest).toHaveBeenCalledOnce();+ expect(findUsableLinuxRuntimeFallbackBinary).toHaveBeenCalledWith('claude-code', undefined);+ expect(cdndProvisioner.prepare).not.toHaveBeenCalled();+ expect(prepareLinuxRuntimeFallback).not.toHaveBeenCalled();+ expect(binaries.getReadyBinaryPath('claude-code')).toBe(binaryPath);+ });++ it('does not skip the CDN version check after an update relaunch even with a local Linux fallback', async () => {+ findCachedLinuxRuntimeFallbackBinary.mockReturnValue(path.join('/tmp/xdt-userdata', 'old-claude'));+ const binaryPath = path.join('/tmp/xdt-userdata', 'new-claude');+ manifestService.getCachedManifest.mockReturnValue({ app: {} });+ cdndProvisioner.prepare.mockResolvedValue({ ready: true, binaryPath });+ await expect(binaries.prepare('claude-code', { checkForUpdates: true }))+ .resolves.toMatchObject({ ready: true, path: binaryPath });+ expect(cdndProvisioner.prepare).toHaveBeenCalledWith(expect.objectContaining({ checkForUpdates: true }));+ });++ it('repairs a cached Linux fallback that is present but cannot run', async () => {+ const brokenPath = path.join('/tmp/xdt-userdata', 'old-claude');+ const repairedPath = path.join('/tmp/xdt-userdata', 'new-claude');+ findCachedLinuxRuntimeFallbackBinary.mockReturnValue(brokenPath);+ probeBinaryVersion.mockResolvedValue(null);+ manifestService.getCachedManifest.mockReturnValue({ app: {} });+ cdndProvisioner.prepare.mockResolvedValue({ ready: true, binaryPath: repairedPath });+ await expect(binaries.prepare('claude-code', { checkForUpdates: false }))+ .resolves.toMatchObject({ ready: true, path: repairedPath });+ expect(findUsableLinuxRuntimeFallbackBinary).toHaveBeenCalledWith('claude-code', undefined);+ expect(cdndProvisioner.prepare).toHaveBeenCalledOnce();+ });++ it('keeps the managed CDN runtime ahead of an older Linux fallback on ordinary startup', async () => {+ findCachedLinuxRuntimeFallbackBinary.mockReturnValue(path.join('/tmp/xdt-userdata', 'old-claude'));+ findUsableLinuxRuntimeFallbackBinary.mockResolvedValue(path.join('/tmp/xdt-userdata', 'old-claude'));+ const binaryPath = path.join('/tmp/xdt-userdata', 'managed-claude');+ manifestService.getCachedManifest.mockReturnValue({ app: {} });+ cdndProvisioner.peekNeedsDownload.mockResolvedValue(false);+ cdndProvisioner.prepare.mockResolvedValue({ ready: true, binaryPath });+ await expect(binaries.prepare('claude-code', { checkForUpdates: false }))+ .resolves.toMatchObject({ ready: true, path: binaryPath });+ expect(cdndProvisioner.prepare).toHaveBeenCalledWith(expect.objectContaining({ checkForUpdates: false }));+ expect(findUsableLinuxRuntimeFallbackBinary).not.toHaveBeenCalled();+ });++ it('keeps first-install fallback working when update checks are disabled and the CDN is unavailable', async () => {+ await expect(binaries.prepare('claude-code', { checkForUpdates: false })).resolves.toMatchObject({ ready: true });+ expect(prepareLinuxRuntimeFallback).toHaveBeenCalledOnce();+ });++ it.each(['darwin', 'win32'] as const)('forwards the ordinary startup policy for %s', async (platform) => {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+ try {+ cdndProvisioner.prepare.mockResolvedValue({ ready: true, binaryPath: path.join('/tmp/xdt-userdata', 'claude') });+ await binaries.peekNeedsDownload('claude-code', { checkForUpdates: false });+ await binaries.prepare('claude-code', { checkForUpdates: false });+ expect(cdndProvisioner.peekNeedsDownload).toHaveBeenCalledWith({ checkForUpdates: false });+ expect(cdndProvisioner.prepare).toHaveBeenCalledWith(expect.objectContaining({ checkForUpdates: false }));+ } finally {+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });+ }+ });+});+describe('dev Codex package selection', () => {it('starts Codex from the complete local package entrypoint', async () => {appMock.isPackaged = false;diff --git a/apps/desktop/src/main/__tests__/piSubagentUpdateRelaunchGate.test.ts b/apps/desktop/src/main/__tests__/piSubagentUpdateRelaunchGate.test.tsindex 2d7600274a..dac4eecc43 100644--- a/apps/desktop/src/main/__tests__/piSubagentUpdateRelaunchGate.test.ts+++ b/apps/desktop/src/main/__tests__/piSubagentUpdateRelaunchGate.test.ts@@ -142,7 +142,7 @@ describe('PI Subagent reclaim before an update relaunch', () => {source.indexOf('async function executeRelaunch('),source.indexOf('async function executeRelaunchUnguarded('),);- expect(wrapper).toMatch(/try \{\s*await executeRelaunchUnguarded\(theme\);\s*\} catch/);+ expect(wrapper).toMatch(/try \{\s*await executeRelaunchUnguarded\(theme, checkForBinaryUpdates\);\s*\} catch/);expect(wrapper).toContain("handleApplyFailure('relaunch_failed')");// The gate and everything after it live in the guarded body.const guarded = source.slice(source.indexOf('async function executeRelaunchUnguarded('));@@ -153,9 +153,8 @@ describe('PI Subagent reclaim before an update relaunch', () => {it('keeps every relaunch entry point on the awaited path', () => {// `executeRelaunch` is now async; a forgotten `void` would silently drop// the gate's rejection handling.- expect([...source.matchAll(/(?<!void )executeRelaunch\(resolved\)/g)]).toHaveLength(0);- expect([...source.matchAll(/(?<!void )executeRelaunch\(theme\)/g)]).toHaveLength(0);- expect(source).toContain('void executeRelaunch(resolved);');+ expect([...source.matchAll(/(?<!void )executeRelaunch\((?:resolved|theme)(?:,[^)]*)?\)/g)]).toHaveLength(0);+ expect(source).toContain('void executeRelaunch(resolved, true);');expect(source).toContain('void executeRelaunch(theme);');});});diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.tsindex a1ac71a965..1bb113d1dd 100644--- a/apps/desktop/src/main/__tests__/updateService.test.ts+++ b/apps/desktop/src/main/__tests__/updateService.test.ts@@ -260,6 +260,118 @@ afterEach(() => {setArch(originalArch);});+describe('binary version checks after a user-requested update', () => {+ beforeEach(() => {+ readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });+ fs.writeFileSync(targetPath, 'update');+ return { path: targetPath, size: 123 };+ });+ });++ it('writes the target-version marker only when the user actually applies the update', async () => {+ const service = await freshUpdateService('darwin');+ const { consumeStartupBinaryUpdateMarker } = await import('../agent-binaries/startup-update');+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ service.initUpdateService();+ try {+ await expect(service.checkForUpdate(updateManifest())).resolves.toBe('ready');+ const markerPath = path.join(TEST_USER_DATA, 'agent-binary-update-once.json');+ expect(fs.existsSync(markerPath)).toBe(false);+ ipcListeners.get('update-relaunch')?.({}, 'dark');+ await vi.waitFor(() => { expect(spawnProcess).toHaveBeenCalledOnce(); });+ expect(JSON.parse(fs.readFileSync(markerPath, 'utf8'))).toMatchObject({ version: '0.0.65' });+ expect(consumeStartupBinaryUpdateMarker(TEST_USER_DATA, '0.0.65')).toBe(true);+ expect(fs.existsSync(markerPath)).toBe(false);+ expect(consumeStartupBinaryUpdateMarker(TEST_USER_DATA, '0.0.65')).toBe(false);+ } finally {+ service.stopUpdateService();+ exitSpy.mockRestore();+ }+ });++ it('does not write the marker for an automatic update relaunch', async () => {+ const service = await freshUpdateService('darwin');+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ service.initUpdateService();+ try {+ await service.checkForUpdate(updateManifest());+ await expect(ipcHandlers.get('update-relaunch-auto')?.({}, 'dark')).resolves.toMatchObject({ accepted: true });+ await vi.waitFor(() => { expect(spawnProcess).toHaveBeenCalledOnce(); });+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'agent-binary-update-once.json'))).toBe(false);+ } finally {+ service.stopUpdateService();+ exitSpy.mockRestore();+ }+ });++ it('does not write the marker when Windows updater prerequisites block applying', async () => {+ const service = await freshUpdateService('win32');+ checkWindowsUpdaterPrerequisites.mockReturnValue({ satisfied: false, missingFiles: ['vcruntime140.dll'] });+ service.initUpdateService();+ try {+ await service.checkForUpdate(updateManifest());+ ipcListeners.get('update-relaunch')?.({}, 'dark');+ expect(spawnProcess).not.toHaveBeenCalled();+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'agent-binary-update-once.json'))).toBe(false);+ } finally {+ service.stopUpdateService();+ }+ });++ it('clears the marker when the Windows updater reports an asynchronous spawn error', async () => {+ const service = await freshUpdateService('win32');+ const resourcesPath = path.join(TEST_ROOT, 'resources');+ fs.mkdirSync(resourcesPath, { recursive: true });+ fs.writeFileSync(path.join(resourcesPath, 'cindy-updater.exe'), 'updater');+ const resourcesDescriptor = Object.getOwnPropertyDescriptor(process, 'resourcesPath');+ Object.defineProperty(process, 'resourcesPath', { value: resourcesPath, configurable: true });+ const tmpdirSpy = vi.spyOn(os, 'tmpdir').mockReturnValue(TEST_ROOT);+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);+ const childListeners = new Map<string, (...args: unknown[]) => void>();+ spawnProcess.mockImplementationOnce(() => ({+ unref: vi.fn(),+ on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { childListeners.set(event, listener); }),+ }));+ service.initUpdateService();+ try {+ await service.checkForUpdate(updateManifest());+ ipcListeners.get('update-relaunch')?.({}, 'dark');+ await vi.waitFor(() => { expect(childListeners.has('error')).toBe(true); });+ const markerPath = path.join(TEST_USER_DATA, 'agent-binary-update-once.json');+ expect(fs.existsSync(markerPath)).toBe(true);+ childListeners.get('error')?.(Object.assign(new Error('spawn denied'), { code: 'EACCES' }));+ expect(fs.existsSync(markerPath)).toBe(false);+ expect(service.getUpdateStatus()).toBe('error');+ expect(exitSpy).not.toHaveBeenCalled();+ } finally {+ service.stopUpdateService();+ tmpdirSpy.mockRestore();+ exitSpy.mockRestore();+ if (resourcesDescriptor) Object.defineProperty(process, 'resourcesPath', resourcesDescriptor);+ else Reflect.deleteProperty(process, 'resourcesPath');+ }+ });++ it('removes the marker when spawning the updater fails', async () => {+ const service = await freshUpdateService('darwin');+ service.initUpdateService();+ try {+ await service.checkForUpdate(updateManifest());+ spawnProcess.mockImplementationOnce(() => {+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'agent-binary-update-once.json'))).toBe(true);+ throw new Error('updater spawn failed');+ });+ ipcListeners.get('update-relaunch')?.({}, 'dark');+ await vi.waitFor(() => { expect(service.getUpdateStatus()).toBe('error'); });+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'agent-binary-update-once.json'))).toBe(false);+ } finally {+ service.stopUpdateService();+ }+ });+});+function updateManifest(version = '0.0.65', hotfixFile?: string) {return {app: {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.tsnew file mode 100644index 0000000000..f5e56dc44a--- /dev/null+++ b/apps/desktop/src/main/agent-binaries/__tests__/factory-startup-update.test.ts@@ -0,0 +1,177 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { gzipSync } from 'node:zlib';+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import type { BinaryProvisionerConfig } from '../types';++const mocks = vi.hoisted(() => ({+ userDataDir: '',+ download: vi.fn(),+ fetchManifest: vi.fn(),+ getCachedManifest: vi.fn(),+ getVendorAsset: vi.fn(),+}));++vi.mock('electron', () => ({ app: { getPath: () => mocks.userDataDir } }));+vi.mock('../../manifestService.js', () => ({+ fetchManifest: mocks.fetchManifest,+ getCachedManifest: mocks.getCachedManifest,+ getBaseUrl: () => 'https://cdn.test',+ getPlatformKey: () => 'darwin-arm64',+}));+vi.mock('../manifest.js', () => ({+ getVendorAsset: mocks.getVendorAsset,+ resolveVendorAssetUrl: (base: string, asset: { file: string }) => base + '/' + asset.file,+}));+vi.mock('../../downloader/index.js', () => ({+ download: mocks.download,+ DownloadError: class DownloadError extends Error {},+}));++import { createBinaryProvisioner } from '../factory';++const asset = {+ version: '3.0.0',+ file: 'claude-code/3.0.0/darwin-arm64/claude.gz',+ sha256: 'c'.repeat(64),+ size: 7,+};+const config: BinaryProvisionerConfig = {+ vendorKey: 'claude',+ manifestField: 'claudeCode',+ installSubdir: 'runtime',+ artifact: { kind: 'gz', binaryName: 'claude' },+};++function installLocal(version: string, verified = true): string {+ const installDir = path.join(mocks.userDataDir, config.installSubdir, version);+ fs.mkdirSync(installDir, { recursive: true });+ const binaryPath = path.join(installDir, config.artifact.binaryName);+ fs.writeFileSync(binaryPath, 'local');+ fs.chmodSync(binaryPath, 0o755);+ if (verified) fs.writeFileSync(path.join(installDir, '.verified'), '');+ return binaryPath;+}++beforeAll(() => {+ mocks.userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'binary-startup-update-'));+});+afterAll(() => {+ fs.rmSync(mocks.userDataDir, { recursive: true, force: true });+});+beforeEach(() => {+ fs.rmSync(path.join(mocks.userDataDir, config.installSubdir), { recursive: true, force: true });+ mocks.getCachedManifest.mockReset().mockReturnValue(null);+ mocks.fetchManifest.mockReset().mockResolvedValue({ app: {} });+ mocks.getVendorAsset.mockReset().mockReturnValue(asset);+ mocks.download.mockReset().mockImplementation(async ({ targetPath }: { targetPath: string }) => {+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });+ fs.writeFileSync(targetPath, gzipSync(Buffer.from('runtime')));+ return { path: targetPath, size: 7, sha256: asset.sha256, fromCache: false };+ });+});++describe('startup binary version check policy', () => {+ it('still fetches the manifest but reuses a verified older binary on ordinary startup', async () => {+ const binaryPath = installLocal('1.0.0');+ const provisioner = createBinaryProvisioner(config);+ const options = { checkForUpdates: false };++ await expect(provisioner.peekNeedsDownload(options)).resolves.toBe(false);+ await expect(provisioner.prepare(options)).resolves.toEqual({ ready: true, binaryPath });+ expect(mocks.fetchManifest).toHaveBeenCalled();+ expect(mocks.download).not.toHaveBeenCalled();+ await expect(provisioner.getState()).resolves.toMatchObject({+ status: 'ready', installedVersion: '1.0.0', binaryPath,+ });+ });++ it.each([undefined, true])('retains the existing upgrade flow with checkForUpdates=%s', async (checkForUpdates) => {+ installLocal('1.0.0');+ const provisioner = createBinaryProvisioner(config);+ await expect(provisioner.peekNeedsDownload({ checkForUpdates })).resolves.toBe(true);+ await expect(provisioner.prepare({ checkForUpdates })).resolves.toMatchObject({ ready: true });+ expect(mocks.download).toHaveBeenCalledOnce();+ await expect(provisioner.getState()).resolves.toMatchObject({ installedVersion: asset.version });+ });++ it('downloads and verifies the first installation even when upgrade checks are disabled', async () => {+ const provisioner = createBinaryProvisioner(config);+ await expect(provisioner.peekNeedsDownload({ checkForUpdates: false })).resolves.toBe(true);+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toMatchObject({ ready: true });+ expect(mocks.download).toHaveBeenCalledOnce();+ expect(fs.existsSync(path.join(mocks.userDataDir, config.installSubdir, asset.version, '.verified'))).toBe(true);+ });++ it.each(['unverified', 'missing'])('repairs a %s local installation instead of falsely reporting ready', async (damage) => {+ const binaryPath = installLocal('1.0.0', damage !== 'unverified');+ if (damage === 'missing') fs.unlinkSync(binaryPath);+ const provisioner = createBinaryProvisioner(config);+ await expect(provisioner.peekNeedsDownload({ checkForUpdates: false })).resolves.toBe(true);+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toMatchObject({ ready: true });+ expect(mocks.download).toHaveBeenCalledOnce();+ });++ it('preserves the highest actual self-updated runtime rather than selecting by directory name', async () => {+ const selfUpdated = installLocal('1.0.0');+ const otherBinary = installLocal('2.0.0');+ const versions = new Map([[selfUpdated, '4.0.0'], [otherBinary, '2.0.0']]);+ const provisioner = createBinaryProvisioner({+ ...config,+ localVersionResolver: async (binaryPath) => versions.get(binaryPath) ?? null,+ });+ await expect(provisioner.peekNeedsDownload({ checkForUpdates: false })).resolves.toBe(false);+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toEqual({ ready: true, binaryPath: selfUpdated });+ expect(mocks.download).not.toHaveBeenCalled();+ expect(fs.existsSync(otherBinary)).toBe(true);+ });++ it('repairs a verified runtime whose executable no longer passes its local probe', async () => {+ installLocal(asset.version);+ const provisioner = createBinaryProvisioner({ ...config, localVersionResolver: async () => null });+ await expect(provisioner.peekNeedsDownload({ checkForUpdates: false })).resolves.toBe(true);+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toMatchObject({ ready: true });+ expect(mocks.download).toHaveBeenCalledOnce();+ });++ it('keeps the required-runtime offline fallback', async () => {+ const binaryPath = installLocal('1.0.0');+ mocks.fetchManifest.mockResolvedValue(null);+ await expect(createBinaryProvisioner(config).prepare({ checkForUpdates: false }))+ .resolves.toEqual({ ready: true, binaryPath });+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it('does not resurrect an optional runtime withdrawn from the manifest', async () => {+ installLocal('1.0.0');+ mocks.getCachedManifest.mockReturnValue({ app: {} });+ mocks.getVendorAsset.mockReturnValue(undefined);+ const provisioner = createBinaryProvisioner({ ...config, optionalAsset: true });+ await expect(provisioner.peekNeedsDownload({ checkForUpdates: false })).resolves.toBe(false);+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toMatchObject({ ready: false, error: 'asset_missing' });+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it('keeps optional runtimes unavailable when the manifest cannot be fetched', async () => {+ installLocal('1.0.0');+ mocks.fetchManifest.mockResolvedValue(null);+ await expect(createBinaryProvisioner({ ...config, optionalAsset: true }).prepare({ checkForUpdates: false }))+ .resolves.toMatchObject({ ready: false, error: 'manifest_failed' });+ });++ it('does not bypass manifest platform validation', async () => {+ installLocal('1.0.0');+ mocks.getVendorAsset.mockReturnValue({ ...asset, file: 'claude-code/3.0.0/win32-x64/claude.exe' });+ await expect(createBinaryProvisioner(config).prepare({ checkForUpdates: false }))+ .resolves.toMatchObject({ ready: false, error: 'asset_platform_mismatch' });+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it('surfaces a failed first download and allows a retry', async () => {+ mocks.download.mockRejectedValueOnce(new Error('network unavailable'));+ const provisioner = createBinaryProvisioner(config);+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toMatchObject({ ready: false });+ await expect(provisioner.prepare({ checkForUpdates: false })).resolves.toMatchObject({ ready: true });+ });+});diff --git a/apps/desktop/src/main/agent-binaries/__tests__/linuxRuntimeMigration.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/linuxRuntimeMigration.test.tsindex 3fd8ddce72..d8ebe3dcae 100644--- a/apps/desktop/src/main/agent-binaries/__tests__/linuxRuntimeMigration.test.ts+++ b/apps/desktop/src/main/agent-binaries/__tests__/linuxRuntimeMigration.test.ts@@ -62,6 +62,18 @@ afterAll(() => {});describe('legacy managed binary migration', () => {+ it('allows an older verified private runtime only when startup upgrade checks are disabled', () => {+ const binaryPath = fallback.privateBinaryPath(tempDir, 'claude-code');+ fs.mkdirSync(path.dirname(binaryPath), { recursive: true });+ fs.writeFileSync(binaryPath, 'local runtime', { mode: 0o755 });+ const versionMarker = path.join(fallback.runtimeInstallRoot(tempDir, 'claude-code'), '.version');+ fs.writeFileSync(versionMarker, olderStableVersion(PINNED_CLAUDE_VERSION));+ expect(fallback.findCachedLinuxRuntimeFallbackBinary('claude-code')).toBeNull();+ expect(fallback.findCachedLinuxRuntimeFallbackBinary('claude-code', false)).toBe(binaryPath);+ fs.unlinkSync(versionMarker);+ expect(fallback.findCachedLinuxRuntimeFallbackBinary('claude-code', false)).toBeNull();+ });+it('reuses and atomically migrates the exact pinned Claude cache without network access', async () => {const legacyPath = fallback.legacyManagedBinaryPath(tempDir, 'claude-code');fs.mkdirSync(path.dirname(legacyPath), { recursive: true });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.tsnew file mode 100644index 0000000000..ee1ee8569a--- /dev/null+++ b/apps/desktop/src/main/agent-binaries/__tests__/startup-policy.test.ts@@ -0,0 +1,242 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { gzipSync } from 'node:zlib';+import { c as createTar } from 'tar';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import type { Manifest } from '../../manifestService';+import { createPiRuntimeRecovery } from '../pi-runtime-recovery';+import { writeStartupBinaryUpdateMarker } from '../startup-update';+import { newerStableVersion, PINNED_CODEX_VERSION } from './runtimeVersionFixtures';++const mocks = vi.hoisted(() => ({+ userDataDir: '',+ isPackaged: true,+ cachedManifest: null as Manifest | null,+ remoteManifest: null as Manifest | null,+ fetchManifest: vi.fn(),+ download: vi.fn(),+ execFile: vi.fn(),+ systemCommands: new Map<string, string>(),+}));++vi.mock('electron', () => ({+ app: {+ get isPackaged() { return mocks.isPackaged; },+ getPath: () => mocks.userDataDir,+ getVersion: () => '2.0.0',+ },+ BrowserWindow: { getAllWindows: () => [] },+}));+vi.mock('node:child_process', () => ({ execFile: mocks.execFile }));+vi.mock('../../manifestService.js', () => ({+ getCachedManifest: () => mocks.cachedManifest,+ fetchManifest: mocks.fetchManifest,+ getPlatformKey: () => process.platform === 'win32' ? 'win32-x64' : process.platform === 'linux' ? 'linux-x64' : 'darwin-arm64',+ getBaseUrl: () => 'https://cdn.test',+}));+vi.mock('../../downloader/index.js', () => ({+ download: mocks.download,+ DownloadError: class DownloadError extends Error {},+}));+vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn() }) }));+vi.mock('../dev-fallback.js', () => ({ findDevBinary: () => null }));++const originalPlatform = process.platform;+const quiet = { broadcastProgress: false, broadcastFailure: false };+let tempRoot: string;+let binaries: typeof import('../index');++function writeExecutable(binaryPath: string, version: string): string {+ fs.mkdirSync(path.dirname(binaryPath), { recursive: true });+ fs.writeFileSync(binaryPath, version, { mode: 0o755 });+ return binaryPath;+}++function installManaged(kind: 'claude-code' | 'codex' | 'pi', version = '1.0.0'): string {+ const installDir = path.join(mocks.userDataDir, kind === 'codex' ? 'codex-package' : kind, version);+ const name = kind === 'claude-code' ? 'claude' : kind;+ const executable = process.platform === 'win32' ? name + '.exe' : name;+ const binaryPath = writeExecutable(path.join(installDir, kind === 'codex' ? 'bin' : '', executable), version);+ fs.writeFileSync(path.join(installDir, '.verified'), '');+ return binaryPath;+}++function releaseManifest(version = '2.0.0'): Manifest {+ const asset = (kind: string) => ({ version, file: kind + '/' + version + '/runtime', sha256: 'a'.repeat(64), size: 7 });+ return { app: {}, claudeCode: asset('claude'), codexPackage: asset('codex'), pi: asset('pi') } as unknown as Manifest;+}++async function reloadBinaries(platform: NodeJS.Platform = 'darwin') {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+ vi.resetModules();+ mocks.cachedManifest = null;+ binaries = await import('../index');+}++beforeAll(() => {+ tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-startup-policy-'));+});+beforeEach(async () => {+ mocks.userDataDir = path.join(tempRoot, 'user-data');+ mocks.isPackaged = true;+ mocks.systemCommands.clear();+ mocks.remoteManifest = releaseManifest();+ mocks.fetchManifest.mockReset().mockImplementation(async () => {+ mocks.cachedManifest = mocks.remoteManifest;+ return mocks.cachedManifest;+ });+ mocks.execFile.mockReset().mockImplementation((+ command: string, args: string[], options: { signal?: AbortSignal },+ callback: (error: Error | null, stdout: string, stderr: string) => void,+ ) => {+ if (options.signal?.aborted) {+ callback(new Error('aborted'), '', '');+ return;+ }+ if (command === '/bin/sh') {+ const commandName = [...mocks.systemCommands.keys()].find((name) => args.join(' ').includes(name));+ callback(null, commandName ? mocks.systemCommands.get(commandName)! : '', '');+ return;+ }+ try { callback(null, fs.readFileSync(command, 'utf8'), ''); }+ catch { callback(new Error('executable missing'), '', ''); }+ });+ mocks.download.mockReset().mockImplementation(async ({ targetPath, url }: { targetPath: string; url: string }) => {+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });+ const version = url.split('/').at(-2)!;+ if (targetPath.endsWith('.tar.gz')) {+ const executable = url.includes('/codex/') ? path.join('bin', 'codex') : 'pi';+ const payload = fs.mkdtempSync(path.join(tempRoot, 'payload-'));+ try {+ writeExecutable(path.join(payload, executable), version);+ await createTar({ file: targetPath, cwd: payload, gzip: true }, [executable]);+ } finally { fs.rmSync(payload, { recursive: true, force: true }); }+ } else {+ fs.writeFileSync(targetPath, gzipSync(Buffer.from(version)));+ }+ return { path: targetPath, size: 7 };+ });+ await reloadBinaries();+});+afterEach(() => {+ fs.rmSync(mocks.userDataDir, { recursive: true, force: true });+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });+});+afterAll(() => { fs.rmSync(tempRoot, { recursive: true, force: true }); });++describe('shared startup policy through the real binary preparation chain', () => {+ 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) {+ const binaryPath = installManaged(kind);+ await expect(binaries.peekNeedsDownload(kind)).resolves.toBe(false);+ await expect(binaries.prepare(kind, quiet)).resolves.toMatchObject({ ready: true, path: binaryPath });+ }+ expect(mocks.fetchManifest).toHaveBeenCalled();+ 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');+ installManaged('pi');+ await expect(binaries.peekNeedsDownload('pi')).resolves.toBe(true);+ expect(fs.existsSync(path.join(mocks.userDataDir, 'agent-binary-update-once.json'))).toBe(false);+ mocks.download.mockRejectedValueOnce(new Error('network unavailable'));+ await expect(binaries.prepare('pi', quiet)).resolves.toMatchObject({ ready: false });+ await expect(binaries.prepare('pi', quiet)).resolves.toMatchObject({ ready: true, path: path.join(mocks.userDataDir, 'pi', '2.0.0', 'pi') });+ installManaged('codex');+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);+ expect(mocks.download).toHaveBeenCalledTimes(2);+ await reloadBinaries();+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(false);+ await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true });+ expect(mocks.download).toHaveBeenCalledTimes(2);+ });++ it.each([false, true])('Pi background recovery inherits checkForUpdates=%s without caller flags', async (allowUpdates) => {+ if (allowUpdates) writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');+ const localPath = installManaged('pi');+ mocks.remoteManifest = null;+ const startup = await binaries.prepare('pi', quiet);+ expect(startup).toMatchObject({ ready: false, error: 'manifest_failed' });+ const recovery = createPiRuntimeRecovery({+ isOnline: () => true,+ prepare: () => binaries.prepare('pi', quiet),+ register: () => true,+ onRegistered: vi.fn(),+ });+ try {+ recovery.markUnavailable(startup.error);+ mocks.remoteManifest = releaseManifest();+ await expect(recovery.retryNow('window-focus')).resolves.toBe(true);+ expect(binaries.getReadyBinaryPath('pi')).toBe(allowUpdates ? path.join(mocks.userDataDir, 'pi', '2.0.0', 'pi') : localPath);+ expect(mocks.download).toHaveBeenCalledTimes(allowUpdates ? 1 : 0);+ } finally { recovery.dispose(); }+ });++ it('repairs the first installation and a broken managed executable without an update marker', async () => {+ await expect(binaries.prepare('pi', quiet)).resolves.toMatchObject({ ready: true });+ writeExecutable(path.join(mocks.userDataDir, 'pi', '2.0.0', 'pi'), 'broken executable');+ await expect(binaries.peekNeedsDownload('pi')).resolves.toBe(true);+ await expect(binaries.prepare('pi', quiet)).resolves.toMatchObject({ ready: true });+ expect(mocks.download).toHaveBeenCalledTimes(2);+ });++ it('allows an explicit update check without changing the default startup decision', async () => {+ installManaged('pi');+ installManaged('codex');+ await expect(binaries.prepare('pi', { ...quiet, checkForUpdates: true })).resolves.toMatchObject({ ready: true });+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(false);+ expect(mocks.download).toHaveBeenCalledOnce();+ });++ it('does not resurrect a withdrawn optional runtime through the shared policy', async () => {+ installManaged('pi');+ mocks.remoteManifest = { app: {} } as Manifest;+ await expect(binaries.prepare('pi', quiet)).resolves.toMatchObject({ ready: false, error: 'asset_missing' });+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it('does not consume the packaged marker during a development startup', async () => {+ writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');+ mocks.isPackaged = false;+ await binaries.peekNeedsDownload('pi');+ await binaries.prepare('pi', quiet);+ expect(fs.existsSync(path.join(mocks.userDataDir, 'agent-binary-update-once.json'))).toBe(true);+ expect(mocks.download).not.toHaveBeenCalled();+ });+});++describe('Linux local discovery before any update download', () => {+ it('keeps the previously used system Codex when a newer CDN release appears on the next startup', async () => {+ await reloadBinaries('linux');+ const systemPath = writeExecutable(path.join(tempRoot, 'system-codex'), 'codex-cli ' + PINNED_CODEX_VERSION);+ mocks.systemCommands.set('codex', systemPath);+ mocks.remoteManifest = { app: {} } as Manifest;+ await expect(binaries.prepare('codex', { ...quiet, checkForUpdates: true })).resolves.toMatchObject({ ready: true, path: systemPath });+ expect(mocks.download).not.toHaveBeenCalled();+ await reloadBinaries('linux');+ mocks.remoteManifest = releaseManifest(newerStableVersion(PINNED_CODEX_VERSION));+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(false);+ await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true, path: systemPath });+ expect(mocks.download).not.toHaveBeenCalled();+ writeStartupBinaryUpdateMarker(mocks.userDataDir, '2.0.0');+ 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);+ expect(mocks.download).toHaveBeenCalledOnce();+ });++ it.each([false, true])('only reuses a private cached runtime when it is executable (broken=%s)', async (broken) => {+ await reloadBinaries('linux');+ const runtimeRoot = path.join(mocks.userDataDir, 'agent-runtime', 'codex');+ const binaryPath = writeExecutable(path.join(runtimeRoot, 'bin', 'codex'), broken ? 'invalid output' : 'codex-cli ' + PINNED_CODEX_VERSION);+ fs.writeFileSync(path.join(runtimeRoot, '.version'), PINNED_CODEX_VERSION);+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(broken);+ await expect(binaries.prepare('codex', quiet)).resolves.toMatchObject({ ready: true });+ expect(binaries.getReadyBinaryPath('codex') === binaryPath).toBe(!broken);+ expect(mocks.download).toHaveBeenCalledTimes(broken ? 1 : 0);+ });+});diff --git a/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.tsnew file mode 100644index 0000000000..249633b64f--- /dev/null+++ b/apps/desktop/src/main/agent-binaries/__tests__/startup-update.test.ts@@ -0,0 +1,79 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { consumeStartupBinaryUpdateMarker, writeStartupBinaryUpdateMarker } from '../startup-update';++vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));++let userDataDir: string;+let markerPath: string;+beforeAll(() => {+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'binary-update-marker-'));+ markerPath = path.join(userDataDir, 'agent-binary-update-once.json');+});+beforeEach(() => {+ fs.rmSync(markerPath, { force: true });+});+afterEach(() => { vi.restoreAllMocks(); });+afterAll(() => { fs.rmSync(userDataDir, { recursive: true, force: true }); });++describe('one-time startup binary update marker', () => {+ it('does not request version checks on an ordinary startup', () => {+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '1.0.0')).toBe(false);+ });++ it('consumes the matching marker before checks run, while the caller can retain its decision for retries', () => {+ writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ const checkForUpdates = consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ expect(checkForUpdates).toBe(true);+ expect(fs.existsSync(markerPath)).toBe(false);+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBe(false);+ expect(checkForUpdates).toBe(true);+ });++ it.each(['1.0.0', '3.0.0'])('discards a stale marker when the actual app version is %s', (version) => {+ writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ expect(consumeStartupBinaryUpdateMarker(userDataDir, version)).toBe(false);+ expect(fs.existsSync(markerPath)).toBe(false);+ });++ it.each(['{', 'null', '{}', '{"version":123}'])('cleans up malformed marker %s without blocking startup', (contents) => {+ fs.writeFileSync(markerPath, contents);+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBe(false);+ expect(fs.existsSync(markerPath)).toBe(false);+ });++ it('cleans up a cancelled apply and tolerates repeated cleanup', () => {+ const cancel = writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ expect(cancel).toBeTypeOf('function');+ cancel?.();+ expect(fs.existsSync(markerPath)).toBe(false);+ expect(() => cancel?.()).not.toThrow();+ });++ it('does not let an older cancellation remove a newer attempt for the same version', () => {+ const cancelEarlier = writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ cancelEarlier?.();+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBe(true);+ });++ it('does not consume another userData directory marker', () => {+ writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ expect(consumeStartupBinaryUpdateMarker(path.join(userDataDir, 'other'), '2.0.0')).toBe(false);+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBe(true);+ });++ it('does not prevent applying an app update when marker writing fails', () => {+ vi.spyOn(fs, 'writeFileSync').mockImplementationOnce(() => { throw new Error('disk unavailable'); });+ expect(writeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBeUndefined();+ });++ it('does not report a consumed marker if deletion fails', () => {+ writeStartupBinaryUpdateMarker(userDataDir, '2.0.0');+ vi.spyOn(fs, 'unlinkSync').mockImplementationOnce(() => { throw new Error('file locked'); });+ expect(consumeStartupBinaryUpdateMarker(userDataDir, '2.0.0')).toBe(false);+ expect(fs.existsSync(markerPath)).toBe(true);+ });+});diff --git a/apps/desktop/src/main/agent-binaries/factory.ts b/apps/desktop/src/main/agent-binaries/factory.tsindex b51fda51f4..7a0014cc6e 100644--- a/apps/desktop/src/main/agent-binaries/factory.ts+++ b/apps/desktop/src/main/agent-binaries/factory.ts@@ -135,13 +135,13 @@ function findLatestVerifiedBinary(async function findPreferredLocalBinary(installSubdir: string,binaryName: string,- manifestVersion: string,+ manifestVersion: string | undefined,resolveVersion:((binaryPath: string, signal?: AbortSignal) => Promise<string | null>) | undefined,signal?: AbortSignal,): Promise<{ version: string; binaryPath: string } | null> {- const requiredVersion = normalizeBinaryVersion(manifestVersion);- if (!resolveVersion || !requiredVersion) return null;+ const requiredVersion = manifestVersion === undefined ? null : normalizeBinaryVersion(manifestVersion);+ if (!resolveVersion || (manifestVersion !== undefined && !requiredVersion)) return null;// Probe all completed installs concurrently so one broken candidate cannot hide// a self-updated runtime or multiply the bounded probe delay.@@ -157,7 +157,7 @@ async function findPreferredLocalBinary(}),);return resolved.reduce<{ version: string; binaryPath: string } | null>((preferred, candidate) => {- if (!candidate || !isBinaryVersionNotOlder(candidate.version, requiredVersion))+ if (!candidate || (requiredVersion !== null && !isBinaryVersionNotOlder(candidate.version, requiredVersion)))return preferred;return !preferred || isBinaryVersionNotOlder(candidate.version, preferred.version)? candidate@@ -273,6 +273,18 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binaryreturn config.artifact.binaryName;}+ async function findUsableLocalBinary(signal?: AbortSignal) {+ return config.localVersionResolver+ ? findPreferredLocalBinary(+ config.installSubdir,+ deriveBinaryName(),+ undefined,+ resolveLocalVersion,+ signal,+ )+ : findLatestVerifiedBinary(config.installSubdir, deriveBinaryName());+ }+return {async getState(): Promise<VendorRuntimeState> {return { ...state };@@ -333,6 +345,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 };+ }+ }+// 3. 本地真实版本不低于 manifest:保留用户自更新结果,禁止降级与旧版清理。const preferredLocal = await findPreferredLocalBinary(config.installSubdir,@@ -475,7 +495,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary}},- async peekNeedsDownload(): Promise<boolean> {+ async peekNeedsDownload(opts): Promise<boolean> {// 不发起任何下载——只读 manifest(cache 优先)+ 本地 isInstalled 检查。// 任何异常 / manifest 缺失 → 返回 true(保守地走 prepare(),让其内部的完整错误处理接管)。// optionalAsset vendor 例外:manifest 有但缺该字段 = 平台没发这个可选资产,@@ -490,6 +510,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binaryif (!manifest) return true;const asset = getVendorAsset(manifest, config.manifestField);if (!asset) return config.optionalAsset !== true;+ if (opts?.checkForUpdates === false) return await findUsableLocalBinary() === null;return !isInstalled(config.installSubdir, asset.version, deriveBinaryName());} catch {return true;diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.tsindex e2ddff02c5..3e6b451982 100644--- a/apps/desktop/src/main/agent-binaries/index.ts+++ b/apps/desktop/src/main/agent-binaries/index.ts@@ -35,6 +35,7 @@ import { probeBinaryVersion } from './binary-version-probe.js';import { findDevBinary } from './dev-fallback.js';import {findCachedLinuxRuntimeFallbackBinary,+ findUsableLinuxRuntimeFallbackBinary,prepareLinuxRuntimeFallback,} from './linux-runtime-fallback.js';import { getVendorAsset } from './manifest.js';@@ -46,6 +47,15 @@ import {} from '../manifestService.js';import { ProgressNormalizer } from '../updateProgressNormalizer.js';import { createLogger } from '../logger.js';+import { consumeStartupBinaryUpdateMarker } from './startup-update.js';++let startupCheckForUpdates: boolean | undefined;++function resolveUpdateCheck(checkForUpdates?: boolean): boolean {+ startupCheckForUpdates ??= app.isPackaged+ && consumeStartupBinaryUpdateMarker(app.getPath('userData'), app.getVersion());+ return checkForUpdates ?? startupCheckForUpdates;+}/*** CDN 腿预算上限(毫秒)。有进展的慢速下载给 3 分钟窗口(百 MB 级资产在慢网@@ -345,6 +355,8 @@ export async function prepare(return { ready: false, error: `${kind} dev binary not found for ${getPlatformKey()}`, downloaded: false };}+ opts = { ...opts, checkForUpdates: resolveUpdateCheck(opts.checkForUpdates) };+// ── packaged Linux: CDN manifest 段优先,失败静默回落 runtime fallback ─────// 2026-08 起 Linux 与 mac/win 同链:scripts 侧发版把 claude/codex 资产上传// 区域 CDN 并写进 manifest 段(国内可达)。CDN 链失败(manifest 无段——旧@@ -354,6 +366,7 @@ export async function prepare(// pi 例外:没有官方 CLI fallback 链,Linux 也走下方通用 manifest 路径// (manifest 缺 pi 字段 → asset_missing 快速失败,由调用方降级)。if (process.platform === 'linux' && app.isPackaged && kind !== 'pi') {+ if (opts.checkForUpdates === false && !getCachedManifest()) await probeManifestForPeek();// 本轮轮次起点:优先消费本轮 peek 探测的发起点(含 Phase 0 探测耗时,// 比 prepare 起点更接近 signal 创建时刻);本轮 peek 命中缓存未探测时// lastPeekProbeStartMs 为 0,退回 now。消费后清零,防跨轮残留@@ -372,6 +385,16 @@ export async function prepare(// 可能已拉取并缓存)→ 清标记走 CDN,CDN 资产可用时不该被旧标记跳过。if (getCachedManifest()) skipCdnUntilNextProbeSuccess = false;const cdnSkipped = skipCdnUntilNextProbeSuccess;+ if (opts.checkForUpdates === false) {+ const hasLocalCdnRuntime = getCachedManifest() && !await getBase(kind).peekNeedsDownload(opts);+ if (!hasLocalCdnRuntime) {+ const localPath = await findUsableLinuxRuntimeFallbackBinary(kind, opts.signal);+ if (localPath) {+ lastReadyPath.set(kind, localPath);+ return { ready: true, path: localPath, downloaded: false };+ }+ }+ }// CDN 腿的信号与预算在 prepareViaCdn 内构造(预算从传输真正开始计起,// 排队等待不计入,见该函数注释)。CDN 链任何异常(含磁盘错误级)都是降级// 第一环的信号:吞掉走 fallback,绝不让 CDN 尝试本身变成 splash 失败原因。@@ -477,7 +500,7 @@ async function prepareViaCdn(// ── 不广播 IPC 路径 (lazy 调用, 当前 desktop 不走) ────────────────────────if (!broadcastProgress) {- const result = await base.prepare({ signal: opts.signal });+ const result = await base.prepare({ signal: opts.signal, checkForUpdates: opts.checkForUpdates });if (result.ready) {lastReadyPath.set(kind, result.binaryPath);return { ready: true, path: result.binaryPath };@@ -542,6 +565,7 @@ async function prepareViaCdn(try {const result = await base.prepare({signal: effectiveSignal,+ checkForUpdates: opts.checkForUpdates,onProgress: (p: VendorRuntimeState) => {if (p.status === 'downloading') {didDownload = true;@@ -607,9 +631,13 @@ async function prepareViaCdn(// ── splash 顺序检查 helpers ──────────────────────────────────────────────────-export async function peekNeedsDownload(kind: AgentBinaryKind): Promise<boolean> {+export async function peekNeedsDownload(+ kind: AgentBinaryKind,+ opts: Pick<PrepareOpts, 'checkForUpdates'> = {},+): Promise<boolean> {// dev 模式永不下载 (findDevBinary 命中 / 缺失都不走 OSS)if (!app.isPackaged) return false;+ opts = { ...opts, checkForUpdates: resolveUpdateCheck(opts.checkForUpdates) };// Linux(cc/codex):manifest 有段 → 走通用 CDN peek(与 mac/win 同口径);// 无段(旧 canary / 首发渠道)→ 只看私有 fallback 是否已就位(fs 快查)。// peek 时 manifest 未缓存则做一次跨 vendor 的短超时探测(3s,single-flight +@@ -627,11 +655,13 @@ export async function peekNeedsDownload(kind: AgentBinaryKind): Promise<boolean>manifest = await probeManifestForPeek();}if (manifest && getVendorAsset(manifest, CONFIG[kind].manifestField)) {- return getBase(kind).peekNeedsDownload();+ const needsDownload = await getBase(kind).peekNeedsDownload(opts);+ if (!needsDownload || opts.checkForUpdates) return needsDownload;}+ if (opts.checkForUpdates === false) return await findUsableLinuxRuntimeFallbackBinary(kind) === null;return findCachedLinuxRuntimeFallbackBinary(kind) === null;}- return getBase(kind).peekNeedsDownload();+ return getBase(kind).peekNeedsDownload(opts);}export async function getInstallState(kind: AgentBinaryKind): Promise<VendorRuntimeState> {diff --git a/apps/desktop/src/main/agent-binaries/linux-runtime-fallback.ts b/apps/desktop/src/main/agent-binaries/linux-runtime-fallback.tsindex 5523fa8bf0..8ef8235b10 100644--- a/apps/desktop/src/main/agent-binaries/linux-runtime-fallback.ts+++ b/apps/desktop/src/main/agent-binaries/linux-runtime-fallback.ts@@ -16,6 +16,7 @@ import { app } from 'electron';import claudeLatest from '../../../../../tools/claude/latest.json';import codexLatest from '../../../../../tools/codex/latest.json';import { download, type ProgressEvent } from '../downloader/index.js';+import { parseBinaryVersionOutput } from './binary-version-probe.js';export type LinuxRuntimeFallbackKind = 'claude-code' | 'codex';@@ -355,10 +356,12 @@ async function migrateLegacyManagedBinary(*/export function findCachedLinuxRuntimeFallbackBinary(kind: LinuxRuntimeFallbackKind,+ checkForUpdates = true,): string | null {if (!app.isPackaged || process.platform !== 'linux') return null;const userDataPath = app.getPath('userData');- if (readText(runtimeVersionMarkerPath(userDataPath, kind)) === CONFIG[kind].version) {+ const installedVersion = readText(runtimeVersionMarkerPath(userDataPath, kind));+ if (installedVersion && (!checkForUpdates || installedVersion === CONFIG[kind].version)) {for (const candidate of privateBinaryCandidates(userDataPath, kind)) {try {fs.accessSync(candidate, fs.constants.X_OK);@@ -530,6 +533,19 @@ async function installCodexFromOfficialAsset(return binaryPath;}+export async function findUsableLinuxRuntimeFallbackBinary(+ kind: LinuxRuntimeFallbackKind,+ signal?: AbortSignal,+): Promise<string | null> {+ if (!app.isPackaged || process.platform !== 'linux') return null;+ const cachedPath = findCachedLinuxRuntimeFallbackBinary(kind, false);+ if (cachedPath) {+ const versionOutput = await readExecutableVersion(cachedPath, signal);+ if (versionOutput && parseBinaryVersionOutput(versionOutput, '')) return cachedPath;+ }+ return findSystemBinaryAsync(kind, signal);+}+export async function prepareLinuxRuntimeFallback(kind: LinuxRuntimeFallbackKind,options: { signal?: AbortSignal; onProgress?: (event: ProgressEvent) => void } = {},diff --git a/apps/desktop/src/main/agent-binaries/startup-update.ts b/apps/desktop/src/main/agent-binaries/startup-update.tsnew file mode 100644index 0000000000..4a3217b00a--- /dev/null+++ b/apps/desktop/src/main/agent-binaries/startup-update.ts@@ -0,0 +1,46 @@+import fs from 'node:fs';+import path from 'node:path';+import { randomUUID } from 'node:crypto';+import { createLogger } from '../logger';++const log = createLogger('agent-binaries/startup-update');+const MARKER_FILE = 'agent-binary-update-once.json';++export function writeStartupBinaryUpdateMarker(+ userDataDir: string,+ version: string,+): (() => void) | undefined {+ const markerPath = path.join(userDataDir, MARKER_FILE);+ const contents = JSON.stringify({ version, token: randomUUID() });+ try {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(markerPath, contents, { mode: 0o600 });+ } catch {+ log.warn('Could not record the binary update check for the next startup');+ return undefined;+ }+ return () => {+ try {+ if (fs.readFileSync(markerPath, 'utf8') === contents) fs.unlinkSync(markerPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn('Could not clear the cancelled startup binary update check');+ }+ }+ };+}++export function consumeStartupBinaryUpdateMarker(userDataDir: string, version: string): boolean {+ const markerPath = path.join(userDataDir, MARKER_FILE);+ try {+ const contents = fs.readFileSync(markerPath, 'utf8');+ fs.unlinkSync(markerPath);+ const marker: unknown = JSON.parse(contents);+ return !!marker && typeof marker === 'object' && 'version' in marker && marker.version === version;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn('Could not consume the startup binary update check');+ }+ return false;+ }+}diff --git a/apps/desktop/src/main/agent-binaries/types.ts b/apps/desktop/src/main/agent-binaries/types.tsindex 74d4886dd4..7f662c7e3c 100644--- a/apps/desktop/src/main/agent-binaries/types.ts+++ b/apps/desktop/src/main/agent-binaries/types.ts@@ -62,6 +62,7 @@ export interface BinaryProvisioner {/** 显式触发安装/升级流程;幂等:本地已有正确版本时立即返回 ready: true */prepare(opts?: {onProgress?: (p: VendorRuntimeState) => void;+ checkForUpdates?: boolean;/** 取消排队、下载或重试等待;已完成的本地命中不受影响。 */signal?: AbortSignal;}): Promise<{ ready: boolean; binaryPath: string; error?: string }>;@@ -71,7 +72,7 @@ export interface BinaryProvisioner {* 复用 cached manifest(splash phase 1 已 fetch)+ 本地 isInstalled+.verified 检查。* dev 模式下 host 包壳层应在调用前自行短路(dev 永不走 OSS)。*/- peekNeedsDownload(): Promise<boolean>;+ peekNeedsDownload(opts?: { checkForUpdates?: boolean }): Promise<boolean>;/** 清理旧版本 */cleanup(keepVersion: string): Promise<void>;@@ -80,6 +81,7 @@ export interface BinaryProvisioner {// ── 上层包壳类型 (供 prepare(kind, opts) 使用) ──────────────────────────────export interface PrepareOpts {+ checkForUpdates?: boolean;/** D 场景顺序下载阶段标记,会写进 IPC payload 给 splash 显示 (x/y) 文案。 */step?: 1 | 2 | 3;/** D 场景 = 本次需要下载的 vendor 数(2 或 3);B/C 场景缺省。 */diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.tsindex 9133218525..456971df97 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -40,6 +40,7 @@ import type { Manifest } from './manifestService';import { download, DownloadError } from './downloader/index';import { ProgressNormalizer } from './updateProgressNormalizer';import { compareAppUpdateVersions } from './updateVersionPolicy';+import { writeStartupBinaryUpdateMarker } from './agent-binaries/startup-update';import { createLogger, maskPath } from './logger';import {@@ -77,6 +78,7 @@ import {} from './windowsUpdaterPrerequisites';const log = createLogger('updateService');+let cancelStartupBinaryUpdateCheck: (() => void) | undefined;// ── Types ──────────────────────────────────────────────────────────────────@@ -1372,6 +1374,8 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<Che// ── Spawn failure handler ─────────────────────────────────────────────────function handleApplyFailure(reason: string): void {+ cancelStartupBinaryUpdateCheck?.();+ cancelStartupBinaryUpdateCheck = undefined;log.error('Update apply failed (reason=%s), clearing patch and notifying renderer', reason);removePatchInfo();readyVersion = undefined;@@ -1824,9 +1828,9 @@ function executeUpdateLinux(debPath: string): void {});}-async function executeRelaunch(theme: 'light' | 'dark'): Promise<void> {+async function executeRelaunch(theme: 'light' | 'dark', checkForBinaryUpdates = false): Promise<void> {try {- await executeRelaunchUnguarded(theme);+ await executeRelaunchUnguarded(theme, checkForBinaryUpdates);} catch (err) {log.error('executeRelaunch() failed: %s', err instanceof Error ? err.stack ?? err.message : String(err));try {@@ -1838,11 +1842,15 @@ async function executeRelaunch(theme: 'light' | 'dark'): Promise<void> {// Any return from here that is not `process.exit` means the relaunch did// not happen, so the fence must come down — including the early returns// inside the guarded body.- if (!isRelaunching) await clearSubagentLaunchFence();+ if (!isRelaunching) {+ cancelStartupBinaryUpdateCheck?.();+ cancelStartupBinaryUpdateCheck = undefined;+ await clearSubagentLaunchFence();+ }}}-async function executeRelaunchUnguarded(theme: 'light' | 'dark'): Promise<void> {+async function executeRelaunchUnguarded(theme: 'light' | 'dark', checkForBinaryUpdates: boolean): Promise<void> {if (isRelaunching) {log.info('executeRelaunch() skipped — already in progress');return;@@ -1932,6 +1940,10 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark'): Promise<void>maskPath(readyFilePath), fs.statSync(readyFilePath).size,);+ if (checkForBinaryUpdates && readyVersion) {+ cancelStartupBinaryUpdateCheck = writeStartupBinaryUpdateMarker(app.getPath('userData'), readyVersion);+ }+switch (process.platform) {case 'win32':executeUpdateWindows(readyFilePath, theme);@@ -1971,7 +1983,7 @@ export function initUpdateService(): void {// default and the .env'd-out look most users have.const resolved = theme === 'light' || theme === 'dark' ? theme : 'dark';resolvedRelaunchTheme = resolved;- void executeRelaunch(resolved);+ void executeRelaunch(resolved, true);});ipcMain.handle(diff --git a/docs/desktop-startup-binary-updates.md b/docs/desktop-startup-binary-updates.mdnew file mode 100644index 0000000000..62347298ba--- /dev/null+++ b/docs/desktop-startup-binary-updates.md@@ -0,0 +1,48 @@+# Desktop 启动时的 Agent 二进制检查++普通启动不再因为 manifest 发布了更新版本而升级已有的 Agent 运行时。清单拉取、资产与+平台校验保持原样;首次安装、缺失或无法通过已有本地探测的运行时仍走原有下载、校验和+重试流程。此改动不保证启动离线或不等待网络。++## 启动策略++- 普通启动:向二进制预检查与准备流程传入 `checkForUpdates: false`。本地存在可用运行时+ 时返回其真实路径;有本地版本探针的运行时按真实版本选择候选,保留用户自更新结果。+- 用户点击应用内热更重启:确认更新可以执行后,写入目标应用版本的一次性标记;新版本+ 启动时开启二进制版本检查,复用原有升级流程。+- 仅下载应用更新、后台自动更新重启、普通重启:不写该标记。+- Pi 的可选资产规则不变:清单撤回资产或无法取得清单时,不因本地残留而重新启用。+- Linux 已验证的私有运行时同样可以在普通启动时复用;更新检查开启时继续执行现有+ CDN 优先与运行时回退逻辑。+- 公共入口默认沿用本次启动的检查决定,包含 Pi 后台恢复;明确传入+ `checkForUpdates: true` 的修复或升级调用仍可检查更新,底层 provisioner 与开发模式不变。++## 一次性标记++标记位于 Electron userData 下的 `agent-binary-update-once.json`,包含目标版本与写入代次。+它不是用户偏好,不进入数据库或仓库,也不改变独立更新器的参数、协议与文件替换步骤。++首次进入二进制公共入口时读取并删除标记,仅目标版本与当前应用版本一致时开启检查。+检查模式保留在本次主进程的公共模块中,启动失败与 Pi 后台恢复的重试都不会丢失;随后普通启动不会+重复检查。版本不匹配或损坏的标记也会清理。开发模式不消费正式版的标记。++更新执行被拒绝时不写标记;写入后可观察到的执行失败会清理本次标记,旧执行的清理不+应删掉更新一代的标记。如果外部更新器失败并退出,下一次旧版启动会清除不匹配的标记。+标记文件写入失败只记录警告,不阻断既有应用更新;读取或删除失败时不开启本次版本检查。++## 代码入口与回退++- `apps/desktop/src/main/agent-binaries/index.ts`:统一决定本次启动的检查参数,启动与恢复调用无需传开关。+- `apps/desktop/src/main/agent-binaries/`:本地复用与一次性标记;Linux 在下载前查找可用的受管、私有和系统运行时。+- `apps/desktop/src/main/updateService.ts`:仅用户主动更新重启时写标记,执行失败时清理。++恢复每次启动检查,只需将公共入口的默认检查决定改为 `true`。移除整项功能+不需要迁移或删除用户已经安装的二进制。++## 验证++定向运行 `agent-binaries/__tests__`、`agentBinaryLinuxPrepare.test.ts` 和+`updateService.test.ts`;再运行根目录 `pnpm test:unit:related` 与+`pnpm --filter desktop run --if-present typecheck`。++单测不能替代 macOS、Windows、Linux 正式安装包的实际更新—替换—重启验证。