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): Linux agent 二进制改为 CDN manifest 优先,官方源兜底 (#3333)

guyong-zapo1e165ea83c80
diff --git a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
index 8b0baed2c4..b1f8aa020a 100644
--- a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
+++ b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
@@ -1,16 +1,28 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+// getBase() 按 kind 缓存 provisioner 实例:全部测试共享同一个 cdndProvisioner,
+// 每测试重配它的行为(而不是 mockReturnValueOnce 换实例——缓存会让新实例永远不被使用)。
const {
appMock,
+ cdndProvisioner,
createBinaryProvisioner,
findCachedLinuxRuntimeFallbackBinary,
prepareLinuxRuntimeFallback,
-} = vi.hoisted(() => ({
- appMock: { isPackaged: true, getPath: vi.fn(() => '/tmp/xdt-userdata') },
- createBinaryProvisioner: vi.fn(),
- findCachedLinuxRuntimeFallbackBinary: vi.fn((): string | null => null),
- prepareLinuxRuntimeFallback: vi.fn(),
-}));
+} = vi.hoisted(() => {
+ const cdndProvisioner = {
+ prepare: vi.fn(),
+ peekNeedsDownload: vi.fn(),
+ getState: vi.fn(async () => ({ status: 'not_installed' })),
+ cleanup: vi.fn(),
+ };
+ return {
+ appMock: { isPackaged: true, getPath: vi.fn(() => '/tmp/xdt-userdata') },
+ cdndProvisioner,
+ createBinaryProvisioner: vi.fn(() => cdndProvisioner),
+ findCachedLinuxRuntimeFallbackBinary: vi.fn((): string | null => null),
+ prepareLinuxRuntimeFallback: vi.fn(),
+ };
+});
vi.mock('electron', () => ({
app: appMock,
@@ -22,7 +34,12 @@ vi.mock('../agent-binaries/linux-runtime-fallback.js', () => ({
findCachedLinuxRuntimeFallbackBinary,
prepareLinuxRuntimeFallback,
}));
-vi.mock('../manifestService.js', () => ({ getPlatformKey: () => 'linux-x64' }));
+// CDN manifest 缺省不可用(无缓存、拉取也拿不到)。CDN 命中用例单独 stub。
+vi.mock('../manifestService.js', () => ({
+ getPlatformKey: () => 'linux-x64',
+ getCachedManifest: vi.fn((): unknown => null),
+ fetchManifest: vi.fn(async (): Promise<unknown> => null),
+}));
vi.mock('../updateProgressNormalizer.js', () => ({
ProgressNormalizer: class {
handle(): void {}
@@ -33,15 +50,32 @@ vi.mock('../updateProgressNormalizer.js', () => ({
const originalPlatform = process.platform;
let binaries: typeof import('../agent-binaries/index');
+let manifestService: { getCachedManifest: ReturnType<typeof vi.fn>; fetchManifest: ReturnType<typeof vi.fn> };
beforeAll(async () => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
- binaries = await import('../agent-binaries/index');
});
-beforeEach(() => {
+// peek 的 manifest 探测是模块级 single-flight + 负缓存:每测试 resetModules +
+// 重新 import,否则前一个用例的探测结果(memo)会泄漏进下一个用例。
+async function reloadBinaries(): Promise<void> {
+ vi.resetModules();
+ manifestService = (await import('../manifestService.js')) as never;
+ binaries = await import('../agent-binaries/index');
+}
+
+beforeEach(async () => {
+ await reloadBinaries();
vi.clearAllMocks();
appMock.isPackaged = true;
+ // 默认:CDN 链失败(asset_missing)→ 回落 fallback;fallback 命中私有安装。
+ cdndProvisioner.prepare.mockReset().mockResolvedValue({ ready: false, binaryPath: '', error: 'asset_missing' });
+ cdndProvisioner.peekNeedsDownload.mockReset().mockResolvedValue(true);
+ // manifestService 是 reloadBinaries 刚重建的 mock(工厂默认实现仍在):
+ // getCachedManifest → null / fetchManifest → Promise<null>。用例里覆盖时用
+ // mockReturnValue/mockResolvedValue,别 mockReset(会连默认实现一起清掉)。
+ manifestService.getCachedManifest.mockReturnValue(null);
+ manifestService.fetchManifest.mockResolvedValue(null);
findCachedLinuxRuntimeFallbackBinary.mockReturnValue(null);
prepareLinuxRuntimeFallback.mockResolvedValue({
ready: true,
@@ -64,7 +98,7 @@ describe('packaged Linux agent binary prepare', () => {
expect(findCachedLinuxRuntimeFallbackBinary).toHaveBeenCalledWith('codex');
});
- it('reuses an existing runtime binary without private install or CDN work', async () => {
+ it('falls back to the runtime chain when the CDN chain reports asset_missing', async () => {
prepareLinuxRuntimeFallback.mockResolvedValueOnce({
ready: true,
binaryPath: '/usr/local/bin/claude',
@@ -79,14 +113,15 @@ describe('packaged Linux agent binary prepare', () => {
path: '/usr/local/bin/claude',
downloaded: false,
});
+ // CDN 链先试(manifest 无段 → asset_missing),失败后静默落到 fallback。
+ expect(cdndProvisioner.prepare).toHaveBeenCalled();
expect(prepareLinuxRuntimeFallback).toHaveBeenCalledWith('claude-code', {
signal: undefined,
onProgress: expect.any(Function),
});
- expect(createBinaryProvisioner).not.toHaveBeenCalled();
});
- it('goes directly to the runtime fallback without creating or probing the CDN provisioner', async () => {
+ it('propagates signal and returns fallback install result when CDN misses', async () => {
const controller = new AbortController();
const result = await binaries.prepare('claude-code');
@@ -104,13 +139,116 @@ describe('packaged Linux agent binary prepare', () => {
signal: controller.signal,
onProgress: expect.any(Function),
});
- expect(createBinaryProvisioner).not.toHaveBeenCalled();
});
- it('reports a local miss as a private install need without fetching a manifest', async () => {
+ it('prefers the CDN chain when the manifest publishes a linux asset, without touching the fallback', async () => {
+ manifestService.getCachedManifest.mockReturnValue({
+ app: { version: '0.1.59' },
+ claudeCode: {
+ version: '2.1.219',
+ file: 'claude-code/2.1.219/linux-x64/claude.gz',
+ sha256: 'a'.repeat(64),
+ size: 1234,
+ },
+ });
+ cdndProvisioner.prepare.mockResolvedValueOnce({
+ ready: true,
+ binaryPath: '/tmp/xdt-userdata/claude-code/2.1.219/claude',
+ });
+
+ const result = await binaries.prepare('claude-code');
+
+ expect(result.ready).toBe(true);
+ expect(result.path).toBe('/tmp/xdt-userdata/claude-code/2.1.219/claude');
+ expect(prepareLinuxRuntimeFallback).not.toHaveBeenCalled();
+ });
+
+ it('survives a throwing CDN chain and still resolves via the fallback', async () => {
+ cdndProvisioner.prepare.mockReset().mockRejectedValue(new Error('disk exploded'));
+
+ const result = await binaries.prepare('claude-code');
+
+ expect(result.ready).toBe(true);
+ expect(result.path).toBe('/tmp/xdt-userdata/agent-runtime/claude-code/bin/claude');
+ expect(prepareLinuxRuntimeFallback).toHaveBeenCalled();
+ });
+
+ it('peek pulls a manifest when none is cached and falls back to the fs check on a miss', async () => {
+ // 无缓存 → peek 拉一次 manifest(与 prepare 同判据);拉取失败/null → fs 快查。
await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
+ expect(manifestService.fetchManifest).toHaveBeenCalled();
expect(findCachedLinuxRuntimeFallbackBinary).toHaveBeenCalledWith('codex');
- expect(createBinaryProvisioner).not.toHaveBeenCalled();
+ expect(cdndProvisioner.peekNeedsDownload).not.toHaveBeenCalled();
+ });
+
+ it('peek probes the manifest once per splash round across vendors (single flight)', async () => {
+ // 同轮内:两个 vendor 的 peek 共享一次探测(第二个 peek 命中 memo)。
+ manifestService.fetchManifest.mockRejectedValue(new Error('offline'));
+ await expect(binaries.peekNeedsDownload('claude-code')).resolves.toBe(true);
+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
+ expect(manifestService.fetchManifest).toHaveBeenCalledTimes(1);
+ expect(findCachedLinuxRuntimeFallbackBinary).toHaveBeenCalledTimes(2);
+ });
+
+ it('prepare clears the probe memo so the next retry round re-probes the manifest', async () => {
+ // 模拟真实 retry 流程:peek(Phase 0)→ prepare(Phase 1)清 memo →
+ // 下一轮 peek 重新探测(网络恢复后进度标签与 prepare 行为对齐)。
+ manifestService.fetchManifest.mockRejectedValue(new Error('offline'));
+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
+ await expect(binaries.peekNeedsDownload('claude-code')).resolves.toBe(true);
+ expect(manifestService.fetchManifest).toHaveBeenCalledTimes(1);
+ // 本轮 prepare(默认 mock:CDN 失败 → fallback 成功)。
+ await expect(binaries.prepare('claude-code')).resolves.toMatchObject({ ready: true });
+ // 下一轮 peek:重新探测。
+ await expect(binaries.peekNeedsDownload('claude-code')).resolves.toBe(true);
+ expect(manifestService.fetchManifest).toHaveBeenCalledTimes(2);
+ });
+
+ it('skips the CDN leg when the round peek probe failed and goes straight to fallback', async () => {
+ // peek 失败 → 本轮 prepare 跳过 CDN 腿,直接 fallback(离线 + 本地已有
+ // runtime 的首启不再为两个 vendor 白等 2×30s manifest 拉取)。
+ manifestService.fetchManifest.mockRejectedValue(new Error('offline'));
+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
+ const result = await binaries.prepare('claude-code');
+ expect(result.ready).toBe(true);
+ expect(cdndProvisioner.prepare).not.toHaveBeenCalled();
+ expect(prepareLinuxRuntimeFallback).toHaveBeenCalled();
+ });
+
+ it('peek delegates to the CDN check when the manifest publishes a linux asset', async () => {
+ manifestService.getCachedManifest.mockReturnValue({
+ app: { version: '0.1.59' },
+ codex: {
+ version: '0.144.6',
+ file: 'codex/0.144.6/linux-x64/codex.gz',
+ sha256: 'b'.repeat(64),
+ size: 5678,
+ },
+ });
+
+ await expect(binaries.peekNeedsDownload('codex')).resolves.toBe(true);
+ expect(cdndProvisioner.peekNeedsDownload).toHaveBeenCalled();
+ expect(findCachedLinuxRuntimeFallbackBinary).not.toHaveBeenCalled();
+ });
+
+ it('gives the CDN leg its own signal and preserves the original one for the fallback', async () => {
+ const controller = new AbortController();
+ // CDN 腿失败(模拟拖满自身预算),fallback 必须收到原始未中止的 signal,
+ // 否则官方源兜底会在共享 deadline 被耗尽时名存实亡。
+ cdndProvisioner.prepare.mockReset().mockRejectedValue(new Error('cdn leg timed out'));
+
+ const result = await binaries.prepare('claude-code', { signal: controller.signal });
+
+ expect(result.ready).toBe(true);
+ // CDN 腿收到的是包装后的独立 signal,不是调用方原始 signal。
+ const cdnArgs = cdndProvisioner.prepare.mock.calls[0][0];
+ expect(cdnArgs.signal).toBeInstanceOf(AbortSignal);
+ expect(cdnArgs.signal).not.toBe(controller.signal);
+ // fallback 收到的是原始 signal(未被 CDN 腿污染)。
+ expect(prepareLinuxRuntimeFallback).toHaveBeenCalledWith(
+ 'claude-code',
+ expect.objectContaining({ signal: controller.signal }),
+ );
});
});
diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.ts
index 669200ac92..2767ab0ccc 100644
--- a/apps/desktop/src/main/agent-binaries/index.ts
+++ b/apps/desktop/src/main/agent-binaries/index.ts
@@ -19,8 +19,9 @@
* - 基础 BinaryProvisioner 实例懒加载 + 缓存 (createBinaryProvisioner 是工厂, 复用同一份 cached manifest)。
* - prepare(kind) 内部:
* dev: findDevBinary 短路, 缺失硬错 (开发者必须 git lfs pull / pnpm update:codex)
- * Linux packaged: PC 已装 CLI / 旧缓存 / userData 私有安装优先; miss 后
- * 直接下载带上游 SHA-256 的官方 pin 资产(不依赖系统 npm/curl/tar)
+ * Linux packaged: CDN manifest 段优先 (与 mac/win 同链, 国内可达); 资产缺失 /
+ * 拉取 / 下载失败时静默回落 runtime fallback (PC 已装 CLI / 旧缓存 / userData
+ * 私有安装 / 带上游 SHA-256 的官方 pin 资产, 不依赖系统 npm/curl/tar)
* other prod: createBinaryProvisioner.prepare() + ProgressNormalizer 节流 + 'binary-download-progress' IPC 广播
* opts.broadcastProgress=false 时不接 IPC (lazy 调用路径, 当前 desktop 全是 splash 路径所以默认 true)。
*/
@@ -35,8 +36,108 @@ import {
findCachedLinuxRuntimeFallbackBinary,
prepareLinuxRuntimeFallback,
} from './linux-runtime-fallback.js';
-import { getPlatformKey } from '../manifestService.js';
+import { getVendorAsset } from './manifest.js';
+import {
+ fetchManifest,
+ getCachedManifest,
+ getPlatformKey,
+ type Manifest,
+} from '../manifestService.js';
import { ProgressNormalizer } from '../updateProgressNormalizer.js';
+import { createLogger } from '../logger.js';
+
+/**
+ * CDN 腿预算上限(毫秒)。有进展的慢速下载给 3 分钟窗口(百 MB 级资产在慢网
+ * 也能下完),无进展(stall)由 downloader 自带 connect 10s / idle 30s 兜底;
+ * 共享 5 分钟启动预算给 fallback 留 1 分钟作最终判决。
+ */
+const LINUX_CDN_LEG_TIMEOUT_MS = 180_000;
+
+/** 与 bootstrap-electron.ts 的 LINUX_AGENT_INSTALL_STARTUP_DEADLINE_MS 保持一致。 */
+const LINUX_SHARED_STARTUP_DEADLINE_MS = 5 * 60_000;
+
+/** 每个 CDN 腿开始前,共享 deadline 里必须给 fallback 预留的最小预算。 */
+const LINUX_FALLBACK_RESERVE_MS = 60_000;
+
+/** peek 的 manifest 探测超时(毫秒):离线首启时不能为「猜进度标签」白等 30s×2。 */
+const LINUX_PEEK_MANIFEST_PROBE_TIMEOUT_MS = 3_000;
+
+/**
+ * peek 阶段跨 vendor 的单次 manifest 探测(single-flight,每轮 splash 一次)。
+ * 两个 vendor 的 peek 串行调用共享同一探测(3s 短超时);prepare 开始时
+ * 消费并清空——用户在同一进程内重试(新一轮 check-environment)会重新探测,
+ * 不会因旧的失败 memo 把 vendor 排除出下载清单(进度标签与 prepare 行为
+ * 对齐)。单轮离线成本上界 = 3s(两个 vendor 共享一次探测)。
+ */
+let peekManifestProbe: Promise<Manifest | null> | null = null;
+
+/**
+ * 本轮 peek 探测是否已失败(轮级信号,module 级)。探测失败(离线 / endpoint
+ * 不可达)→ true:本轮的 prepare 跳过 CDN 腿,直接走 fallback——离线且本地
+ * 已有 runtime 的首启不再为两个 vendor 白等 2×30s 的 manifest 拉取。
+ * 下一轮 peek 成功会置回 false,CDN 腿自动恢复。
+ */
+let skipCdnUntilNextProbeSuccess = false;
+
+/** 本轮(最新一次)首个 peek 探测的发起点:prepare 开始时会消费进
+ * per-signal 记录并清零,下一轮 peek 未探测(命中缓存)时自然为 0。 */
+let lastPeekProbeStartMs = 0;
+
+function probeManifestForPeek(): Promise<Manifest | null> {
+ if (peekManifestProbe) return peekManifestProbe;
+ // 新一轮的首个探测:记录轮次起点(共享 deadline 从 bootstrap 创建 signal
+ // 起就在流逝,peek 起点比 prepare 起点更接近 signal 创建时刻)。
+ lastPeekProbeStartMs = Date.now();
+ const probe = fetchManifest(LINUX_PEEK_MANIFEST_PROBE_TIMEOUT_MS).then(
+ (manifest) => {
+ skipCdnUntilNextProbeSuccess = manifest === null;
+ return manifest;
+ },
+ () => {
+ skipCdnUntilNextProbeSuccess = true;
+ return null;
+ },
+ );
+ peekManifestProbe = probe;
+ return probe;
+}
+
+/** 新一轮 check-environment 开始时清空 peek 探测 memo(peek 先于 prepare)。 */
+function resetPeekManifestProbe(): void {
+ peekManifestProbe = null;
+}
+
+/**
+ * 共享 signal → 该轮首个 prepare 的启动时刻。WeakMap 以 signal 对象为键:
+ * bootstrap 每次 check-environment 新建一个 AbortSignal.timeout,新一轮自然
+ * 拿到新键、老键随 signal 回收——无跨轮状态泄漏,也无需显式 reset。
+ */
+const linuxRoundStartBySignal = new WeakMap<object, number>();
+
+/**
+ * 计算本 vendor 的 CDN 腿预算:min(180s 上限, 共享 deadline 剩余 − 1 分钟
+ * fallback 预留)。前一 vendor 的慢 fallback 已消耗共享预算时,本 vendor 的
+ * CDN 腿相应缩短;剩余不足预留时返回 0(调用方跳过 CDN 腿,把剩余时间全部
+ * 留给 fallback 作最终判决)。
+ */
+function linuxCdnBudgetForSignal(sharedSignal: AbortSignal | undefined): number {
+ if (!sharedSignal) return LINUX_CDN_LEG_TIMEOUT_MS;
+ const now = Date.now();
+ let roundStart = linuxRoundStartBySignal.get(sharedSignal);
+ if (roundStart === undefined) {
+ // 轮次起点由 prepare 在入口消费本轮 peek 探测起点写入;直接 prepare
+ // (无 peek)或入口未写入时退回 now。
+ roundStart = now;
+ linuxRoundStartBySignal.set(sharedSignal, roundStart);
+ }
+ const elapsedMs = now - roundStart;
+ const remainingMs = LINUX_SHARED_STARTUP_DEADLINE_MS - elapsedMs;
+ if (remainingMs <= LINUX_FALLBACK_RESERVE_MS) return 0;
+ return Math.min(LINUX_CDN_LEG_TIMEOUT_MS, remainingMs - LINUX_FALLBACK_RESERVE_MS);
+}
+
+const log = createLogger('agent-binaries');
+
import type {
BinaryProvisioner,
BinaryDownloadProgressPayload,
@@ -231,13 +332,51 @@ export async function prepare(
return { ready: false, error: `${kind} dev binary not found for ${getPlatformKey()}`, downloaded: false };
}
- // ── packaged Linux runtime: 私有安装 / 旧缓存 / PC 已装 / 官方下载 ───────
- // Linux release manifest 明确不发布 Claude/Codex 资产。这里直接走 runtime
- // fallback,不能先调 base.prepare()/manifest:离线首装会让 peek + prepare
- // 重复等待 CDN 超时,fallback 尚未开始 splash 就已经卡住。
+ // ── packaged Linux: CDN manifest 段优先,失败静默回落 runtime fallback ─────
+ // 2026-08 起 Linux 与 mac/win 同链:scripts 侧发版把 claude/codex 资产上传
+ // 区域 CDN 并写进 manifest 段(国内可达)。CDN 链失败(manifest 无段——旧
+ // canary / 首发渠道、拉取失败、下载失败)是预期内的降级第一环,不向 splash
+ // 广播 failed,静默落到 runtime fallback(私有安装 / 旧缓存 / 系统 CLI /
+ // 官方下载)——fallback 才是最终判决。
// pi 例外:没有官方 CLI fallback 链,Linux 也走下方通用 manifest 路径
// (manifest 缺 pi 字段 → asset_missing 快速失败,由调用方降级)。
if (process.platform === 'linux' && app.isPackaged && kind !== 'pi') {
+ // 本轮轮次起点:优先消费本轮 peek 探测的发起点(含 Phase 0 探测耗时,
+ // 比 prepare 起点更接近 signal 创建时刻);本轮 peek 命中缓存未探测时
+ // lastPeekProbeStartMs 为 0,退回 now。消费后清零,防跨轮残留
+ // (下一轮 peek 未探测时,预算不能拿上一轮的旧起点计算)。
+ if (opts.signal && !linuxRoundStartBySignal.has(opts.signal)) {
+ linuxRoundStartBySignal.set(opts.signal, lastPeekProbeStartMs > 0 ? lastPeekProbeStartMs : Date.now());
+ }
+ lastPeekProbeStartMs = 0;
+ // 新一轮 check-environment 开始(Phase 0 peek 已全部完成):清空 peek
+ // 探测 memo,下一轮重试的 peek 会重新探测 manifest。
+ resetPeekManifestProbe();
+ // 本轮 peek 探测失败(离线 / endpoint 不可达)→ 跳过 CDN 腿,直接
+ // fallback:离线且本地已有 runtime 的首启不再为两个 vendor 白等
+ // 2×30s 的 manifest 拉取。下一轮 peek 成功自动恢复 CDN 腿。
+ // 例外:peek 与 prepare 之间缓存里已出现 manifest(并发启动 updater
+ // 可能已拉取并缓存)→ 清标记走 CDN,CDN 资产可用时不该被旧标记跳过。
+ if (getCachedManifest()) skipCdnUntilNextProbeSuccess = false;
+ const cdnSkipped = skipCdnUntilNextProbeSuccess;
+ // CDN 腿的信号与预算在 prepareViaCdn 内构造(预算从传输真正开始计起,
+ // 排队等待不计入,见该函数注释)。CDN 链任何异常(含磁盘错误级)都是降级
+ // 第一环的信号:吞掉走 fallback,绝不让 CDN 尝试本身变成 splash 失败原因。
+ let cdnResult: PrepareResult = { ready: false, error: 'cdn_skipped_probe_failed', downloaded: false };
+ if (!cdnSkipped) {
+ try {
+ cdnResult = await prepareViaCdn(kind, opts, {
+ broadcastProgress,
+ broadcastFailure: false,
+ linuxCdnBudget: true,
+ });
+ } catch (err) {
+ log.warn(`CDN chain failed, falling back to linux runtime fallback: ${String((err as Error)?.message ?? err)}`);
+ cdnResult = { ready: false, error: 'cdn_chain_error', downloaded: false };
+ }
+ }
+ if (cdnResult.ready) return cdnResult;
+
if (broadcastProgress) {
broadcastBinaryDownloadProgress({
progress: 0,
@@ -296,6 +435,31 @@ export async function prepare(
}
}
+ return prepareViaCdn(kind, opts, { broadcastProgress, broadcastFailure, linuxCdnBudget: false });
+}
+
+/**
+ * 通用 CDN 供给链(与 mac/win 同链):读 manifest 段 → 下载 → SHA-256 校验。
+ * Linux 上也作为首选链调用;失败由调用方决定是否回落 runtime fallback。
+ * broadcastFailure 允许调用方关掉失败广播(降级链的第一环不该让 splash
+ * 短暂闪烁失败态)。linuxCdnBudget 只在 packaged Linux 分支传 true——
+ * mac/win 没有 runtime fallback,不能让 180s 惰性预算中止它们的传输。
+ */
+async function prepareViaCdn(
+ kind: AgentBinaryKind,
+ opts: PrepareOpts,
+ {
+ broadcastProgress,
+ broadcastFailure,
+ linuxCdnBudget,
+ }: {
+ broadcastProgress: boolean;
+ broadcastFailure: boolean;
+ linuxCdnBudget: boolean;
+ },
+): Promise<PrepareResult> {
+ const cfg = CONFIG[kind];
+ const { step, totalSteps } = opts;
const base = getBase(kind);
// ── 不广播 IPC 路径 (lazy 调用, 当前 desktop 不走) ────────────────────────
@@ -314,6 +478,40 @@ export async function prepare(
let lastSpeed: string | undefined;
let didDownload = false;
+ // CDN 腿预算(仅 packaged Linux)从「传输真正开始」计起,排队等待不计入:
+ // 单槽 FIFO 下载器可能被启动期 app 更新(.deb,百 MB 级)占住,若预算从信号
+ // 创建起算,排队期间预算就在流逝,排到队首时可能已耗尽 → 没试 CDN 就被迫
+ // 回落官方源。factory 只在传输层首个 progress 事件才发 'downloading',
+ // 用它作为预算计时起点。mac/win 不启用(没有 runtime fallback,不能让
+ // 预算中止它们的传输)。
+ // 入口早退:此刻共享 deadline 剩余已不足预留 → 跳过 CDN 腿,把剩余时间
+ // 全部留给 fallback 作最终判决(不能先空跑一段 CDN 再把它烧掉)。
+ if (linuxCdnBudget && linuxCdnBudgetForSignal(opts.signal) <= 0) {
+ return { ready: false, error: 'cdn_budget_exhausted', downloaded: false };
+ }
+ const cdnBudget = linuxCdnBudget ? new AbortController() : null;
+ let budgetTimer: ReturnType<typeof setTimeout> | null = null;
+ const startCdnBudget = (): void => {
+ if (!cdnBudget || budgetTimer) return;
+ // 传输真正开始的时刻重新按共享 deadline 剩余计算:manifest 拉取与
+ // FIFO 排队期间共享 deadline 已在流逝,入口时的预算值已陈旧,固定值
+ // 会让 CDN 吃掉本应留给 fallback 的预留。剩余不足预留 → 立即中止。
+ const budgetMs = linuxCdnBudgetForSignal(opts.signal);
+ if (budgetMs <= 0) {
+ cdnBudget.abort();
+ return;
+ }
+ budgetTimer = setTimeout(() => cdnBudget.abort(), budgetMs);
+ };
+ // 共享启动 deadline(opts.signal)与 CDN 预算(Linux only)任一触发即中止:
+ // 共享 deadline 保证整段启动仍严格受 5 分钟预算约束;CDN 预算保证单段
+ // CDN 传输不吞掉全部共享预算(每段开始前重新计算,始终预留 1 分钟)。
+ const effectiveSignal = cdnBudget
+ ? opts.signal
+ ? AbortSignal.any([opts.signal, cdnBudget.signal])
+ : cdnBudget.signal
+ : opts.signal;
+
const normalizer = new ProgressNormalizer({
onIpc: (progress) => {
broadcastBinaryDownloadProgress({
@@ -328,63 +526,70 @@ export async function prepare(
},
});
- const result = await base.prepare({
- signal: opts.signal,
- onProgress: (p: VendorRuntimeState) => {
- if (p.status === 'downloading') didDownload = true;
- if (p.downloadProgress) {
- lastReceived = p.downloadProgress.received;
- lastTotal = p.downloadProgress.total;
- lastSpeed = p.downloadProgress.speedBps > 0
- ? `${formatBytes(p.downloadProgress.speedBps)}/s`
- : undefined;
- normalizer.handle({
- loaded: lastReceived,
- total: lastTotal > 0 ? lastTotal : null,
- percent: lastTotal > 0 ? (lastReceived / lastTotal) * 100 : null,
- speedBps: p.downloadProgress.speedBps,
- });
- }
- // 初始 0% 广播 (首次进入 downloading 状态时, lastReceived 还是 0)
- if (p.status === 'downloading' && lastReceived === 0) {
+ try {
+ const result = await base.prepare({
+ signal: effectiveSignal,
+ onProgress: (p: VendorRuntimeState) => {
+ if (p.status === 'downloading') {
+ didDownload = true;
+ startCdnBudget();
+ }
+ if (p.downloadProgress) {
+ lastReceived = p.downloadProgress.received;
+ lastTotal = p.downloadProgress.total;
+ lastSpeed = p.downloadProgress.speedBps > 0
+ ? `${formatBytes(p.downloadProgress.speedBps)}/s`
+ : undefined;
+ normalizer.handle({
+ loaded: lastReceived,
+ total: lastTotal > 0 ? lastTotal : null,
+ percent: lastTotal > 0 ? (lastReceived / lastTotal) * 100 : null,
+ speedBps: p.downloadProgress.speedBps,
+ });
+ }
+ // 初始 0% 广播 (首次进入 downloading 状态时, lastReceived 还是 0)
+ if (p.status === 'downloading' && lastReceived === 0) {
+ broadcastBinaryDownloadProgress({
+ progress: 0,
+ total: lastTotal > 0 ? formatBytes(lastTotal) : undefined,
+ step,
+ totalSteps,
+ vendor: cfg.vendorTag,
+ });
+ }
+ },
+ });
+
+ if (result.ready) {
+ if (didDownload) {
+ normalizer.flush();
broadcastBinaryDownloadProgress({
- progress: 0,
+ progress: 100,
+ downloaded: lastReceived > 0 ? formatBytes(lastReceived) : undefined,
total: lastTotal > 0 ? formatBytes(lastTotal) : undefined,
step,
totalSteps,
vendor: cfg.vendorTag,
});
}
- },
- });
+ lastReadyPath.set(kind, result.binaryPath);
+ return { ready: true, path: result.binaryPath, downloaded: didDownload };
+ }
- if (result.ready) {
- if (didDownload) {
- normalizer.flush();
+ if (broadcastFailure) {
broadcastBinaryDownloadProgress({
- progress: 100,
- downloaded: lastReceived > 0 ? formatBytes(lastReceived) : undefined,
- total: lastTotal > 0 ? formatBytes(lastTotal) : undefined,
+ progress: normalizer.getCurrent(),
+ failed: true,
+ error: result.error ?? 'unknown',
step,
totalSteps,
vendor: cfg.vendorTag,
});
}
- lastReadyPath.set(kind, result.binaryPath);
- return { ready: true, path: result.binaryPath, downloaded: didDownload };
- }
-
- if (broadcastFailure) {
- broadcastBinaryDownloadProgress({
- progress: normalizer.getCurrent(),
- failed: true,
- error: result.error ?? 'unknown',
- step,
- totalSteps,
- vendor: cfg.vendorTag,
- });
+ return { ready: false, error: result.error ?? 'unknown', downloaded: didDownload };
+ } finally {
+ if (budgetTimer) clearTimeout(budgetTimer);
}
- return { ready: false, error: result.error ?? 'unknown', downloaded: didDownload };
}
// ── splash 顺序检查 helpers ──────────────────────────────────────────────────
@@ -392,10 +597,25 @@ export async function prepare(
export async function peekNeedsDownload(kind: AgentBinaryKind): Promise<boolean> {
// dev 模式永不下载 (findDevBinary 命中 / 缺失都不走 OSS)
if (!app.isPackaged) return false;
- // Linux release 不发布 cc/codex manifest 资产。peek 只做已知私有路径的 fs 快查,
- // PATH 与版本探测统一留给可取消的 async prepare,避免 splash 前同步阻塞。
+ // Linux(cc/codex):manifest 有段 → 走通用 CDN peek(与 mac/win 同口径);
+ // 无段(旧 canary / 首发渠道)→ 只看私有 fallback 是否已就位(fs 快查)。
+ // peek 时 manifest 未缓存则做一次跨 vendor 的短超时探测(3s,single-flight +
+ // 失败负缓存),与 prepare 判据对齐又不拖慢离线首启:两个 vendor 的 peek
+ // 串行调用共享同一探测,offline 首启只损失 3s 而非 2×30s。
+ // PATH 与版本探测统一留给可取消的 async prepare。
// pi 各平台统一走 manifest peek(可选资产:manifest 缺字段 → false)。
if (process.platform === 'linux' && kind !== 'pi') {
+ let manifest = getCachedManifest();
+ if (manifest) {
+ // 缓存里已有 manifest(如并发启动 updater 已拉取并缓存):探测失败
+ // 标记立即作废——CDN 资产已可用,不能让 prepare 因旧标记跳过 CDN 腿。
+ skipCdnUntilNextProbeSuccess = false;
+ } else {
+ manifest = await probeManifestForPeek();
+ }
+ if (manifest && getVendorAsset(manifest, CONFIG[kind].manifestField)) {
+ return getBase(kind).peekNeedsDownload();
+ }
return findCachedLinuxRuntimeFallbackBinary(kind) === null;
}
return getBase(kind).peekNeedsDownload();