Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(startup): allow offline launch with locally verified runtimes (#3076)
Battleplusd88f683a6302
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/factory.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/factory.test.tsindex bd76b56a01..119493b376 100644--- a/apps/desktop/src/main/agent-binaries/__tests__/factory.test.ts+++ b/apps/desktop/src/main/agent-binaries/__tests__/factory.test.ts@@ -125,3 +125,188 @@ describe('createBinaryProvisioner emit 时序', () => {expect(statuses[statuses.length - 1]).toBe('ready');});});+++describe('离线启动 fallback', () => {+ async function mountVerifiedBinary(+ installSubdir: string,+ version: string,+ binaryName: string,+ ): Promise<{ binPath: string; cleanup: () => void }> {+ const { app } = await import('electron');+ const installRoot = path.join(app.getPath('userData'), installSubdir);+ const versionDir = path.join(installRoot, version);+ fs.mkdirSync(versionDir, { recursive: true });+ const binPath = path.join(versionDir, binaryName);+ fs.writeFileSync(binPath, 'fake binary');+ fs.chmodSync(binPath, 0o755);+ fs.writeFileSync(path.join(versionDir, '.verified'), '');+ return {+ binPath,+ cleanup: () => fs.rmSync(installRoot, { recursive: true, force: true }),+ };+ }++ it('本地有已验证版本时:manifest fetch 失败仍返回 ready', async () => {+ const installSubdir = `offline-fallback-test-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ const version = '1.2.3-verified';+ const binaryName = 'test-binary';+ const local = await mountVerifiedBinary(installSubdir, version, binaryName);++ try {+ // 让 manifest 和 cache 都返回 null(模拟 CDN 不可达)+ const { getCachedManifest, fetchManifest } = await import('../../manifestService.js');+ vi.mocked(getCachedManifest).mockReturnValue(null as any);+ vi.mocked(fetchManifest).mockResolvedValue(null as any);++ const provisioner = createBinaryProvisioner({+ vendorKey: 'claude',+ manifestField: 'testField',+ installSubdir,+ artifact: { kind: 'raw', binaryName },+ });++ const result = await provisioner.prepare();++ expect(result.ready).toBe(true);+ expect(result.binaryPath).toBe(local.binPath);+ } finally {+ local.cleanup();+ }+ });++ it('download 失败时:本地有已验证版本仍返回 ready', async () => {+ const installSubdir = `download-fallback-test-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ const version = '2.0.0-verified';+ const binaryName = 'test-binary';+ const local = await mountVerifiedBinary(installSubdir, version, binaryName);++ try {+ // manifest 返回成功,但 download 会抛错(模拟 CDN 拦截)+ const { getCachedManifest, fetchManifest } = await import('../../manifestService.js');+ vi.mocked(getCachedManifest).mockReturnValue(null as any);+ vi.mocked(fetchManifest).mockResolvedValue({+ version: '2.0.0',+ claude: { file: '/linux-x64/claude.bin', sha256: 'abc', size: 100 },+ } as any);++ // Mock download to throw+ const downloader = await import('../../downloader/index.js');+ vi.mocked(downloader.download).mockRejectedValue(new Error('CDN blocked'));++ const provisioner = createBinaryProvisioner({+ vendorKey: 'claude',+ manifestField: 'claude',+ installSubdir,+ artifact: { kind: 'raw', binaryName },+ });++ const result = await provisioner.prepare();++ expect(result.ready).toBe(true);+ expect(result.binaryPath).toBe(local.binPath);+ } finally {+ local.cleanup();+ }+ });++ it('解压失败时:本地有已验证版本仍返回 ready', async () => {+ const installSubdir = `extract-fallback-test-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ const version = '3.0.0-verified';+ const binaryName = 'claude-test-bin';+ const local = await mountVerifiedBinary(installSubdir, version, binaryName);++ try {+ const { getCachedManifest, fetchManifest } = await import('../../manifestService.js');+ vi.mocked(getCachedManifest).mockReturnValue(null as any);+ vi.mocked(fetchManifest).mockResolvedValue({+ version: '3.0.0',+ claudeCode: { file: 'claude/claude-3.0.0.gz', sha256: FAKE_SHA, size: 3 },+ } as any);+ // A successful download followed by invalid gzip exercises the catch path+ // for extraction/verification failures, not just network failures.+ mocks.download.mockImplementation(async (opts: DownloadOpts) => {+ fs.mkdirSync(path.dirname(opts.targetPath), { recursive: true });+ fs.writeFileSync(opts.targetPath, 'not gzip');+ return {+ path: opts.targetPath,+ size: 8,+ sha256: FAKE_SHA,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ });++ const provisioner = createBinaryProvisioner({+ vendorKey: 'claude',+ manifestField: 'claudeCode',+ installSubdir,+ artifact: { kind: 'gz', binaryName },+ });++ const result = await provisioner.prepare();++ expect(result.ready).toBe(true);+ expect(result.binaryPath).toBe(local.binPath);+ } finally {+ local.cleanup();+ }+ });++ it('可选 runtime 在 manifest 失败时不复用旧版本', async () => {+ const installSubdir = `optional-manifest-failure-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ const local = await mountVerifiedBinary(installSubdir, '4.0.0-verified', 'pi');++ try {+ const { getCachedManifest, fetchManifest } = await import('../../manifestService.js');+ vi.mocked(getCachedManifest).mockReturnValue(null as any);+ vi.mocked(fetchManifest).mockResolvedValue(null as any);++ const provisioner = createBinaryProvisioner({+ vendorKey: 'pi',+ manifestField: 'pi',+ installSubdir,+ optionalAsset: true,+ artifact: { kind: 'raw', binaryName: 'pi' },+ });++ const result = await provisioner.prepare();++ expect(result.ready).toBe(false);+ expect(result.error).toBe('manifest_failed');+ } finally {+ local.cleanup();+ }+ });++ it('可选 runtime 在下载失败时不复用旧版本', async () => {+ const installSubdir = `optional-download-failure-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ const local = await mountVerifiedBinary(installSubdir, '5.0.0-verified', 'pi');++ try {+ const { getCachedManifest, fetchManifest } = await import('../../manifestService.js');+ vi.mocked(getCachedManifest).mockReturnValue(null as any);+ vi.mocked(fetchManifest).mockResolvedValue({+ version: '5.0.0',+ pi: { file: 'pi/pi-5.0.0.gz', sha256: FAKE_SHA, size: 3 },+ } as any);+ mocks.download.mockRejectedValue(new Error('CDN blocked'));++ const provisioner = createBinaryProvisioner({+ vendorKey: 'pi',+ manifestField: 'pi',+ installSubdir,+ optionalAsset: true,+ artifact: { kind: 'gz', binaryName: 'pi' },+ });++ const result = await provisioner.prepare();++ expect(result.ready).toBe(false);+ expect(result.error).toBe('unknown');+ } finally {+ local.cleanup();+ }+ });+});diff --git a/apps/desktop/src/main/agent-binaries/factory.ts b/apps/desktop/src/main/agent-binaries/factory.tsindex b0240fa40d..f3eaa90b33 100644--- a/apps/desktop/src/main/agent-binaries/factory.ts+++ b/apps/desktop/src/main/agent-binaries/factory.ts@@ -55,6 +55,41 @@ function getVerifiedMarker(installSubdir: string, version: string): string {return path.join(getVersionDir(installSubdir, version), '.verified');}+/**+ * Find the latest locally installed and verified version.+ * Scans the install root for directories containing a .verified marker file,+ * then checks that the binary exists and is executable.+ * Returns the binary path if found, null otherwise.+ */+function findLatestVerifiedBinary(+ installSubdir: string,+ binaryName: string,+): { version: string; binaryPath: string } | null {+ try {+ const root = getInstallRoot(installSubdir);+ const entries = fs.readdirSync(root, { withFileTypes: true });+ const verified: string[] = [];+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ try {+ fs.accessSync(getVerifiedMarker(installSubdir, entry.name));+ verified.push(entry.name);+ } catch { /* no .verified marker */ }+ }+ if (verified.length === 0) return null;+ // Sort descending by version string (semver-like: higher = later)+ verified.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));+ for (const v of verified) {+ const binPath = getFinalBinPath(installSubdir, v, binaryName);+ try {+ fs.accessSync(binPath, fs.constants.X_OK);+ return { version: v, binaryPath: binPath };+ } catch { /* binary missing or not executable */ }+ }+ } catch { /* install root doesn't exist or unreadable */ }+ return null;+}+function isInstalled(installSubdir: string, version: string, binaryName: string): boolean {try {fs.accessSync(getFinalBinPath(installSubdir, version, binaryName), fs.constants.X_OK);@@ -142,10 +177,23 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binaryasync prepare(opts) {const onProgress = opts?.onProgress;try {+ const binaryName = deriveBinaryName();// 1. 拉 manifest(不带 dev fallback —— dev mode 归属在 Boss 2 包壳层)let manifest = getCachedManifest();if (!manifest) manifest = await fetchManifest(undefined, opts?.signal);++ // 2. manifest 获取失败时,检查本地已验证版本(离线 fallback)if (!manifest) {+ // Optional assets (currently Pi) must remain disabled when the+ // manifest is unavailable; a stale local install may have been+ // withdrawn for this platform/channel and must not be resurrected.+ const local = config.optionalAsset+ ? null+ : findLatestVerifiedBinary(config.installSubdir, binaryName);+ if (local) {+ emit({ status: 'ready', installedVersion: local.version, binaryPath: local.binaryPath }, onProgress);+ return { ready: true, binaryPath: local.binaryPath };+ }emit({status: 'failed',error: { code: 'manifest_failed', message: 'Failed to fetch manifest from CDN' },@@ -153,7 +201,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binaryreturn { ready: false, binaryPath: '', error: 'manifest_failed' };}- // 2. 取 vendor asset+ // 3. 取 vendor assetconst asset: VendorAsset | undefined = getVendorAsset(manifest, config.manifestField);if (!asset) {emit({@@ -182,7 +230,6 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binaryemit({ availableVersion: asset.version }, onProgress);// 3. 已安装命中- const binaryName = deriveBinaryName();const finalBinPath = getFinalBinPath(config.installSubdir, asset.version, binaryName);if (isInstalled(config.installSubdir, asset.version, binaryName)) {emit({@@ -280,6 +327,21 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binarythrow err;}const code = err instanceof DownloadError ? err.code : 'unknown';+ // P1 fix: download/extract failures should also try local fallback.+ // 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+ ? null+ : findLatestVerifiedBinary(config.installSubdir, config.artifact.binaryName);+ if (localFallback) {+ emit({+ status: 'ready',+ installedVersion: localFallback.version,+ binaryPath: localFallback.binaryPath,+ }, opts?.onProgress);+ return { ready: true, binaryPath: localFallback.binaryPath };+ }emit({status: 'failed',error: { code, message },