Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Pi 不再进正式安装包,公证失败直接暴露 Apple 原因
Lizi6ef0db1d0b97
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 423f699eaa..6e7acf9269 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -618,9 +618,6 @@ function signPackagedExes(buildPath: string): void {// 未签名第三方 exe,会被运行时 spawn(项目内 grep/search),未签同样被严格策略 /// EDR 拦。扩到整个 tools/ 一次覆盖,新增工具免维护。...collectExeFilesRecursively(path.join(buildPath, 'resources', 'tools')),- // Pi 是目录分发;Windows 主程序 pi.exe 位于 resources/pi/<platform>/,- // 不在 tools/ 下,必须一并签名,否则 Smart App Control 会拦截 agent 启动。- ...collectExeFilesRecursively(path.join(buildPath, 'resources', 'pi')),);for (const exe of exes) {@@ -709,45 +706,6 @@ function ripgrepBinaryName(targetPlatform: string): string {return targetPlatform === 'win32' ? 'rg.exe' : 'rg';}-function piBinaryName(targetPlatform: string): string {- return targetPlatform === 'win32' ? 'pi.exe' : 'pi';-}--/**- * 把目标平台的完整 Pi 目录分发加入安装包。Pi 与单文件 agent 不同,运行时还依赖- * themes/examples/native prebuilds;只复制 pi(.exe) 会在 RPC 启动期崩溃。- */-function stagePi(targetPlatform: string, targetArch: string): void {- const key = targetPlatformKey(targetPlatform, targetArch);- const file = piBinaryName(targetPlatform);- const srcDir = path.join(__dirname, '..', 'pi-bin', key);- const src = path.join(srcDir, file);- const stagingRoot = path.join(__dirname, 'resources', 'pi');- const destDir = path.join(stagingRoot, key);- const ensureScript = path.join(__dirname, '..', '..', 'scripts', 'ensure-agent-binaries.mjs');-- console.log(`[forge:prePackage] ensuring pinned pi ${key} via ${ensureScript}...`);- const result = spawnSync(process.execPath, [ensureScript, '--kinds=pi', `--platform=${key}`], {- stdio: 'inherit',- });- if (result.status !== 0) {- throw new Error(`[forge] failed to ensure pinned pi ${key}; run "pnpm update:pi -- --platform=${key}" before packaging`);- }- if (!fs.existsSync(src)) {- throw new Error(`[forge] pi distribution missing main executable at ${src} after ensure`);- }-- // Forge 的 extraResource 会复制整个 resources/pi;连续构建其它 target 时必须- // 清掉上一轮暂存,避免单个平台安装包误带六个平台的完整分发。- fs.rmSync(stagingRoot, { recursive: true, force: true });- fs.mkdirSync(destDir, { recursive: true });- fs.cpSync(srcDir, destDir, { recursive: true });- const dest = path.join(destDir, file);- if (targetPlatform !== 'win32') fs.chmodSync(dest, 0o755);- const sizeMb = (fs.statSync(dest).size / (1024 * 1024)).toFixed(2);- console.log(`[forge:prePackage] pi ${key} -> ${destDir} (main ${sizeMb} MB)`);-}-function stageRipgrep(targetPlatform: string, targetArch: string): void {const key = targetPlatformKey(targetPlatform, targetArch);const file = ripgrepBinaryName(targetPlatform);@@ -789,8 +747,6 @@ function extraResourcesForTarget(targetPlatform: string): string[] {'resources/cc-manager','resources/anthropic-compat-proxy','resources/remote-file-service',- // 目标平台完整 Pi 目录分发,由 prePackage/stagePi 写入。- 'resources/pi',// .cindy 发布者/审核 Ed25519 公钥信任表(私钥永不进客户端)。'resources/ghost-trust.json',// 第三方开源声明,由 scripts/generate-third-party-notices.mjs 生成@@ -1343,7 +1299,6 @@ const config: ForgeConfig = {buildCindyUpdater();}stageRipgrep(targetPlatform, targetArch);- stagePi(targetPlatform, targetArch);stageAndroidPlatformTools(targetPlatform, targetArch);buildMacVoiceInputTextInsertionHelper(platform, arch);buildMacVoiceInputModifierShortcutListener(platform, arch);diff --git a/apps/desktop/help-knowledge/updates-and-about.md b/apps/desktop/help-knowledge/updates-and-about.mdindex 69bc62b04f..6ff4a2d5ae 100644--- a/apps/desktop/help-knowledge/updates-and-about.md+++ b/apps/desktop/help-knowledge/updates-and-about.md@@ -9,7 +9,7 @@ Cindy checks for updates automatically and downloads them in the background. Whe**Settings > About:**- **App version** — the desktop app's release.-- **Claude Code version** / **Codex version** — the bundled agent CLIs the app ships with (these update with the app, not separately).+- **Claude Code version** / **Codex version** — the agent CLIs Cindy manages and downloads at runtime into your user data (they update separately from the app).- **Auto-relaunch when idle** — an optional toggle that lets a downloaded update apply itself during idle time instead of waiting for you to click relaunch.- **Debug log toggle** — turn on more verbose logging when reproducing a problem. Leave it off for normal use.- **Open logs folder** — opens the logs directory in your OS file browser, useful when you need to attach logs to a bug report.@@ -19,4 +19,4 @@ Cindy checks for updates automatically and downloads them in the background. Whe- By default, a downloaded update only triggers a relaunch prompt — it won't restart you unexpectedly. If you enable **Auto-relaunch when idle**, Cindy will restart itself automatically once the idle and busy gates pass, without an additional prompt.- If you want to skip auto-update temporarily, you can dismiss the relaunch prompt; the update applies next time you start the app.-- The Claude Code / Codex versions you see here are what the **app's bundled agents** run as — they're independent from any Claude / Codex CLI you have installed globally on your shell.+- The Claude Code / Codex versions you see here are what Cindy's **managed agents** run as — they're independent from any Claude / Codex CLI you have installed globally on your shell.diff --git a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt b/apps/desktop/resources/THIRD-PARTY-NOTICES.txtindex 02a911a8fc..70166341bd 100644--- a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt+++ b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt@@ -19,7 +19,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------@@ -3432,7 +3432,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------OpenAI Codex CLI (bundled binary) 0.145.0+OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0Source: https://github.com/openai/codex------------------------------------------------------------------------------@@ -3668,7 +3668,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-------------------------------------------------------------------------------pi coding agent (bundled binary) 0.83.0+pi coding agent (runtime-downloaded binary) 0.83.0License: MITSource: https://github.com/earendil-works/pi------------------------------------------------------------------------------diff --git a/apps/desktop/scripts/ci/lib.mjs b/apps/desktop/scripts/ci/lib.mjsindex e900113362..8b289e27d2 100644--- a/apps/desktop/scripts/ci/lib.mjs+++ b/apps/desktop/scripts/ci/lib.mjs@@ -632,17 +632,168 @@ export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEntiverifyMacContactsPermissions(appPath);}+const NOTARYTOOL_TIMEOUT_MS = 1800000;++function spawnOutputText(value) {+ if (Buffer.isBuffer(value)) return value.toString('utf8');+ return value == null ? '' : String(value);+}++function redactApplePassword(value, applePassword) {+ const text = spawnOutputText(value);+ return applePassword ? text.split(applePassword).join('****') : text;+}++function logCapturedNotarytoolOutput(result, operation, identity, logger) {+ const output = [result.stdout, result.stderr]+ .map((value) => redactApplePassword(value, identity.applePassword).trim())+ .filter(Boolean)+ .join('\n');+ if (output) {+ logger.error(` notarytool ${operation} output:`);+ logger.error(output);+ }+}++/**+ * 把 notarytool 的原始输出挂到 error 上。notarytool 对 Invalid 提交的 exit code 随+ * Xcode 版本变化(有的 0、有的非 0);非 0 那条路径也必须能从 stdout 里救回+ * submission id,否则拿不到 Apple 的详细失败原因。+ */+function attachNotarytoolOutput(error, result) {+ error.notarytoolStdout = spawnOutputText(result?.stdout);+ error.notarytoolStderr = spawnOutputText(result?.stderr);+ return error;+}++function runNotarytool(operation, args, identity, { spawnCommand, logger }) {+ let result;+ try {+ result = spawnCommand('/usr/bin/xcrun', args, {+ encoding: 'utf8',+ timeout: NOTARYTOOL_TIMEOUT_MS,+ });+ } catch (error) {+ const message = redactApplePassword(error?.message ?? error, identity.applePassword);+ throw new Error(`notarytool ${operation} 无法执行:${message}`);+ }++ if (result.error || result.signal || result.status !== 0) {+ logCapturedNotarytoolOutput(result, operation, identity, logger);+ }+ if (result.error) {+ const message = redactApplePassword(result.error.message, identity.applePassword);+ throw new Error(`notarytool ${operation} 无法执行:${message}`);+ }+ if (result.signal) {+ throw attachNotarytoolOutput(+ new Error(+ `notarytool ${operation} 被信号 ${result.signal} 终止(可能公证超时);公证未通过。`,+ ),+ result,+ );+ }+ if (result.status !== 0) {+ throw attachNotarytoolOutput(+ new Error(`notarytool ${operation} 失败(exit ${result.status});公证未通过。`),+ result,+ );+ }+ return {+ stdout: spawnOutputText(result.stdout),+ stderr: spawnOutputText(result.stderr),+ };+}++function parseNotarytoolSubmitResponse(stdout) {+ let response;+ try {+ response = JSON.parse(stdout);+ } catch {+ throw new Error('notarytool submit 未返回有效 JSON;公证结果无法确认。');+ }+ if (!response || typeof response !== 'object' || Array.isArray(response)) {+ throw new Error('notarytool submit JSON 结构无效;公证结果无法确认。');+ }+ const status = typeof response.status === 'string' ? response.status.trim() : '';+ const id = typeof response.id === 'string' ? response.id.trim() : '';+ if (!status) {+ throw new Error('notarytool submit JSON 缺少 status;公证结果无法确认。');+ }+ return { id, status };+}++/** 解析失败时返回 null(救援路径用):此时 exit code 已经说明公证没过。 */+function tryParseNotarytoolSubmitResponse(stdout) {+ try {+ return parseNotarytoolSubmitResponse(stdout);+ } catch {+ return null;+ }+}++function printNotarizationFailureLog(submissionId, status, identity, dependencies) {+ const { logger } = dependencies;+ if (!submissionId) {+ logger.error(+ ` Apple 公证返回 ${status},但响应缺少 submission id,无法拉取详细日志。`,+ );+ return;+ }++ const logArgs = [+ 'notarytool',+ 'log',+ submissionId,+ '--apple-id',+ identity.appleId,+ '--password',+ identity.applePassword,+ '--team-id',+ identity.teamId,+ ];+ logger.log(+ ` $ /usr/bin/xcrun notarytool log ${JSON.stringify(submissionId)} ` ++ `--apple-id ${JSON.stringify(identity.appleId)} --password "****" ` ++ `--team-id ${JSON.stringify(identity.teamId)}`,+ );+ try {+ const result = runNotarytool('log', logArgs, identity, dependencies);+ const output = [result.stdout, result.stderr]+ .map((value) => redactApplePassword(value, identity.applePassword).trim())+ .filter(Boolean)+ .join('\n');+ logger.error(' Apple notarization log:');+ logger.error(output || '(empty log)');+ } catch (error) {+ const message = redactApplePassword(error?.message ?? error, identity.applePassword);+ logger.error(` WARN: 无法获取 Apple notarization log: ${message}`);+ }+}+/*** Apple notarytool 公证 + staple。* @param {{ appleId: string, teamId: string, applePassword: string }} identity+ * @param {{+ * execCommand?: typeof exec,+ * spawnCommand?: typeof spawnSync,+ * unlinkFile?: typeof fs.unlinkSync,+ * logger?: Console,+ * }} dependencies*/-export function notarizeMacApp(appPath, identity) {+export function notarizeMacApp(appPath, identity, {+ execCommand = exec,+ spawnCommand = spawnSync,+ unlinkFile = fs.unlinkSync,+ logger = console,+} = {}) {const zipPath = appPath + '.zip';+ const dependencies = { spawnCommand, logger };- console.log(' Compressing for notarization...');- exec(`/usr/bin/ditto -c -k --keepParent "${appPath}" "${zipPath}"`);+ logger.log(' Compressing for notarization...');+ execCommand(`/usr/bin/ditto -c -k --keepParent "${appPath}" "${zipPath}"`);- console.log(' Submitting to Apple notarization service (this may take a few minutes)...');+ logger.log(' Submitting to Apple notarization service (this may take a few minutes)...');// 密码作为 --password 值直接传给 notarytool——不再用 --password @env:VAR 间接:// 旧版 notarytool 不认 @env: 前缀,会把字面量 "@env:..." 当密码本身发出去而 401。// 走 spawnSync 参数数组:避免 shell 参与(无插值/无注入面),且日志回显时对密码@@ -661,31 +812,51 @@ export function notarizeMacApp(appPath, identity) {'--team-id',identity.teamId,'--wait',+ '--output-format',+ 'json',];- console.log(- ` $ /usr/bin/xcrun notarytool submit "${zipPath}" ` +- `--apple-id "${identity.appleId}" --password "****" --team-id "${identity.teamId}" --wait`,+ logger.log(+ ` $ /usr/bin/xcrun notarytool submit ${JSON.stringify(zipPath)} ` ++ `--apple-id ${JSON.stringify(identity.appleId)} --password "****" ` ++ `--team-id ${JSON.stringify(identity.teamId)} --wait --output-format json`,);- const submitResult = spawnSync('/usr/bin/xcrun', submitArgs, {- stdio: 'inherit',- timeout: 1800000, // 30 min- });- if (submitResult.error) {- throw new Error(`notarytool submit 无法执行:${submitResult.error.message}`);+ let submitResult;+ try {+ submitResult = runNotarytool('submit', submitArgs, identity, dependencies);+ } catch (error) {+ // notarytool 自己以非 0 退出:原始输出已由 runNotarytool 打过一遍,这里再尽力从+ // stdout 里救出 submission id 去拉 Apple 的详细失败原因。zip 保留不删。+ const salvaged = tryParseNotarytoolSubmitResponse(error?.notarytoolStdout ?? '');+ if (salvaged && salvaged.status !== 'Accepted') {+ printNotarizationFailureLog(salvaged.id, salvaged.status, identity, dependencies);+ }+ throw error;}- if (submitResult.signal) {- // 被信号终止(如 30min 超时 kill → SIGTERM):status 为 null,单看 exit 会显示- // "exit null",这里显式报出 signal 便于定位。- throw new Error(`notarytool submit 被信号 ${submitResult.signal} 终止(可能公证超时);公证未通过。`);+ let submission;+ try {+ submission = parseNotarytoolSubmitResponse(submitResult.stdout);+ } catch (error) {+ logCapturedNotarytoolOutput(submitResult, 'submit', identity, logger);+ throw error;}- if (submitResult.status !== 0) {- throw new Error(`notarytool submit 失败(exit ${submitResult.status});公证未通过。`);+ logger.log(+ ` Apple notarization status: ${submission.status}` ++ (submission.id ? ` (${submission.id})` : ''),+ );++ if (submission.status !== 'Accepted') {+ printNotarizationFailureLog(submission.id, submission.status, identity, dependencies);+ throw new Error(+ `Apple 公证未通过: status=${submission.status}` ++ (submission.id ? `, submission=${submission.id}` : '') ++ '。',+ );}- fs.unlinkSync(zipPath);+ unlinkFile(zipPath);- console.log(' Stapling notarization ticket...');- exec(`/usr/bin/xcrun stapler staple "${appPath}"`);+ logger.log(' Stapling notarization ticket...');+ execCommand(`/usr/bin/xcrun stapler staple "${appPath}"`);}// ── DMG 安装界面(dmgbuild)─────────────────────────────────────────────────diff --git a/apps/desktop/scripts/package-desktop.mjs b/apps/desktop/scripts/package-desktop.mjsindex f0ab9b4615..faad729712 100644--- a/apps/desktop/scripts/package-desktop.mjs+++ b/apps/desktop/scripts/package-desktop.mjs@@ -437,9 +437,10 @@ async function main() {console.log(` version: ${versionless ? `(版本无关,占位 ${version},不参与热更新)` : version}`);console.log('='.repeat(60));- // Linux 只校验 sqlite-vec 等原生运行资产。Claude/Codex 各平台都不进安装包+ // Linux 只校验 sqlite-vec 等原生运行资产。Claude/Codex/Pi 各平台都不进安装包// (forge extraResource 不含它们),由 packaged runtime 首启时复用系统 CLI 或- // 安装到 userData/agent-runtime,打包阶段无需预下载。ripgrep 是唯一进包的+ // 从 CDN 安装到 userData(仅 Linux 的 Claude/Codex 另有系统 CLI / 官方下载+ // fallback),打包阶段无需预下载。ripgrep 是唯一进包的// agent 二进制,这里按 pin 预 ensure(缓存命中即跳过),在昂贵的 forge make// 之前尽早失败;forge prePackage 的 stageRipgrep 仍会兜底校验。if (platform === 'linux') {diff --git a/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.tsindex 3cf3a67d59..5e8e235c48 100644--- a/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts+++ b/apps/desktop/src/main/agent-binaries/__tests__/factory-dir-dist.test.ts@@ -21,6 +21,8 @@ const FAKE_SHA = 'b'.repeat(64);const mocks = vi.hoisted(() => ({download: vi.fn(),+ fetchManifest: vi.fn(async () => ({ app: {} })),+ cachedManifest: { current: { app: {} } as { app: Record<string, never> } | null },// 每个用例把要打包进 tar.gz 的源目录塞进来,download mock 现打包成归档落盘。archiveState: { srcDir: '' },asset: {@@ -45,8 +47,8 @@ vi.mock('../../downloader/index.js', () => ({}));vi.mock('../../manifestService.js', () => ({- fetchManifest: vi.fn(async () => null),- getCachedManifest: vi.fn(() => ({ app: {} })),+ fetchManifest: mocks.fetchManifest,+ getCachedManifest: vi.fn(() => mocks.cachedManifest.current),getBaseUrl: () => 'https://cdn.test',getPlatformKey: () => 'darwin-arm64',}));@@ -60,7 +62,7 @@ import { createBinaryProvisioner } from '../factory.js';const BIN_NAME = 'pi-test-bin';-interface DownloadOpts { targetPath: string }+interface DownloadOpts { targetPath: string; signal?: AbortSignal }/** download mock 成功实现:把 archiveState.srcDir 打成真实 tar.gz 落到 targetPath。 */async function fulfillDownloadWithTarGz(opts: DownloadOpts) {@@ -103,6 +105,9 @@ function stageDist(layout: 'flat' | 'nested', withBinary = true): string {beforeEach(() => {mocks.download.mockReset();+ mocks.fetchManifest.mockReset();+ mocks.fetchManifest.mockResolvedValue({ app: {} });+ mocks.cachedManifest.current = { app: {} };mocks.asset.current = {version: '9.9.9-test',file: 'pi/9.9.9-test/darwin-arm64/pi.dist.tar.gz',@@ -158,6 +163,20 @@ describe('createBinaryProvisioner tar-gz-dir', () => {expect(state.status).toBe('failed');});+ it('拒绝 win32-arm64 资产被错误地用于当前平台', async () => {+ mocks.asset.current = {+ version: '9.9.9-test',+ file: 'pi/9.9.9-test/win32-arm64/pi.dist.tar.gz',+ sha256: FAKE_SHA,+ size: 128,+ };++ const result = await makeProvisioner({ optionalAsset: true }).prepare();++ expect(result).toEqual({ ready: false, binaryPath: '', error: 'asset_platform_mismatch' });+ expect(mocks.download).not.toHaveBeenCalled();+ });+it('二次 prepare 命中已安装版本,不再下载', async () => {mocks.archiveState.srcDir = stageDist('flat');mocks.download.mockImplementation(fulfillDownloadWithTarGz);@@ -173,6 +192,26 @@ describe('createBinaryProvisioner tar-gz-dir', () => {expect(mocks.download).toHaveBeenCalledTimes(1);});+ it('把宿主的启动取消信号传给统一下载器', async () => {+ mocks.archiveState.srcDir = stageDist('flat');+ mocks.download.mockImplementation(fulfillDownloadWithTarGz);+ const controller = new AbortController();++ mocks.cachedManifest.current = null;+ const result = await makeProvisioner({ optionalAsset: true }).prepare({+ signal: controller.signal,+ });++ expect(result.ready).toBe(true);+ expect(mocks.fetchManifest).toHaveBeenCalledWith(undefined, controller.signal);+ expect(mocks.download).toHaveBeenCalledWith(+ expect.objectContaining({+ signal: controller.signal,+ retry: { maxAttempts: 1 },+ }),+ );+ });+it('optionalAsset: manifest 缺字段 → peekNeedsDownload false;非 optional 保守 true', async () => {mocks.asset.current = undefined;expect(await makeProvisioner({ optionalAsset: true }).peekNeedsDownload()).toBe(false);diff --git a/apps/desktop/src/main/agent-binaries/factory.ts b/apps/desktop/src/main/agent-binaries/factory.tsindex d701b8b804..b0240fa40d 100644--- a/apps/desktop/src/main/agent-binaries/factory.ts+++ b/apps/desktop/src/main/agent-binaries/factory.ts@@ -144,7 +144,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binarytry {// 1. 拉 manifest(不带 dev fallback —— dev mode 归属在 Boss 2 包壳层)let manifest = getCachedManifest();- if (!manifest) manifest = await fetchManifest();+ if (!manifest) manifest = await fetchManifest(undefined, opts?.signal);if (!manifest) {emit({status: 'failed',@@ -168,7 +168,7 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary// Reject a manifest asset explicitly scoped to another platform, while// keeping compatibility with older manifests whose file path had no// platform segment at all.- const assetPlatform = asset.file.match(/\/(linux-x64|linux-arm64|darwin-arm64|darwin-x64|win32-x64)\//)?.[1];+ const assetPlatform = asset.file.match(/\/(linux-x64|linux-arm64|darwin-arm64|darwin-x64|win32-x64|win32-arm64)\//)?.[1];if (assetPlatform && assetPlatform !== getPlatformKey()) {emit({status: 'failed',@@ -219,6 +219,10 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): BinarytargetPath: downloadDest,sha256: asset.sha256.toLowerCase(),expectedSize: asset.size,+ signal: opts?.signal,+ // 可选 Pi 不该在 CDN 故障时做六轮重试拖住启动;一次连接失败就降级,+ // 持续有进度的正常下载仍可在宿主总 deadline 内完成。+ retry: config.optionalAsset ? { maxAttempts: 1 } : undefined,onProgress: (e: ProgressEvent) => {emit({status: 'downloading',@@ -292,6 +296,9 @@ export function createBinaryProvisioner(config: BinaryProvisionerConfig): Binary// asset_missing 快速失败交调用方降级)。try {let manifest = getCachedManifest();+ // 可选资产的 peek 只用于 splash 步数提示,不能为了“猜要不要下载”额外+ // 发一次可能卡住启动的网络请求;真正 prepare 会带宿主 deadline 拉清单。+ if (!manifest && config.optionalAsset) return true;if (!manifest) manifest = await fetchManifest();if (!manifest) return true;const asset = getVendorAsset(manifest, config.manifestField);diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.tsindex a88429d84d..669200ac92 100644--- a/apps/desktop/src/main/agent-binaries/index.ts+++ b/apps/desktop/src/main/agent-binaries/index.ts@@ -59,8 +59,7 @@ import type {// 只装主二进制会在 RPC 启动期崩溃), CDN 资产是整包 tar.gz, 归档根即完整目录// (与 apps/pi-bin/<platform>/ 同布局)。// - optionalAsset: pi 是可选实验 agent。manifest 缺 pi 字段 / 下载失败都不阻塞-// 启动 —— check-environment 的 pi 段静默降级, pi-host 回退安装包自带分发-// (resources/pi/<platform>), 再缺失则本次不注册 pi。+// 启动 —— check-environment 的 pi 段静默降级,本次不注册 pi。export type AgentBinaryKind = 'claude-code' | 'codex' | 'pi';@@ -184,7 +183,7 @@ export function getCachedBinaryStatus(kind: AgentBinaryKind): CachedBinaryStatus// packaged Linux 同步快查只看已知私有路径;不能在 renderer-facing 路径// 里执行 CLI --version 或 PATH shell lookup。系统 CLI 由 async prepare 发现。// pi 不走 Linux runtime fallback(那条链是 cc/codex 官方 CLI 专用),Linux 上的- // pi 与其它平台一致:manifest 下载 miss 后由 pi-host 回退安装包自带分发。+ // pi 与其它平台一致:只使用 manifest 管理的 CDN 资产。if (kind !== 'pi') {const linuxFallbackPath = findCachedLinuxRuntimeFallbackBinary(kind);if (linuxFallbackPath) return { binaryReady: true, binaryPath: linuxFallbackPath };@@ -301,7 +300,7 @@ export async function prepare(// ── 不广播 IPC 路径 (lazy 调用, 当前 desktop 不走) ────────────────────────if (!broadcastProgress) {- const result = await base.prepare();+ const result = await base.prepare({ signal: opts.signal });if (result.ready) {lastReadyPath.set(kind, result.binaryPath);return { ready: true, path: result.binaryPath };@@ -330,6 +329,7 @@ export async function prepare(});const result = await base.prepare({+ signal: opts.signal,onProgress: (p: VendorRuntimeState) => {if (p.status === 'downloading') didDownload = true;if (p.downloadProgress) {diff --git a/apps/desktop/src/main/agent-binaries/types.ts b/apps/desktop/src/main/agent-binaries/types.tsindex f044b80662..bdd7704205 100644--- a/apps/desktop/src/main/agent-binaries/types.ts+++ b/apps/desktop/src/main/agent-binaries/types.ts@@ -56,6 +56,8 @@ export interface BinaryProvisioner {/** 显式触发安装/升级流程;幂等:本地已有正确版本时立即返回 ready: true */prepare(opts?: {onProgress?: (p: VendorRuntimeState) => void;+ /** 取消排队、下载或重试等待;已完成的本地命中不受影响。 */+ signal?: AbortSignal;}): Promise<{ ready: boolean; binaryPath: string; error?: string }>;/**@@ -80,11 +82,11 @@ export interface PrepareOpts {broadcastProgress?: boolean;/*** false 时失败不广播 failed payload(splash 收到 failed 会立即进失败态)。- * 供可选 vendor(pi)使用:下载失败静默降级到安装包自带分发,不打断启动。+ * 供可选 vendor(pi)使用:下载失败时本次禁用 pi,不打断启动。* 缺省 true(cc/codex 必装,失败要让 splash 显示重试)。*/broadcastFailure?: boolean;- /** 允许宿主在退出或启动 deadline 到期时取消 Linux 私有安装子进程。 */+ /** 允许宿主在退出或启动 deadline 到期时取消受管下载或 Linux 私有安装。 */signal?: AbortSignal;}diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex ee334954d2..40e392f767 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -43,6 +43,9 @@ const PROCESS_STARTED_AT_MS = Date.now();// both downloads, but allow normal consumer connections to finish while the// splash displays real byte progress.const LINUX_AGENT_INSTALL_STARTUP_DEADLINE_MS = 5 * 60_000;+// Pi 是可选能力。首启可以给它一小段时间从 CDN 准备,但网络异常时不能让+// 整个 Cindy 一直停在启动页;到期后取消本次下载并禁用本次 Pi。+const PI_AGENT_INSTALL_STARTUP_DEADLINE_MS = 60_000;if (process.platform === 'linux' &&@@ -3835,6 +3838,9 @@ const registerIpcHandlers = () => {// getMaker() 在构造期就读 binary path, 早于 splash 调用会抛错; 第一次 splash 成功后置 true,// 后续 retry 走 check-environment 不重复注册 (重复 ipcMain.handle 会覆盖同名 handler)。let makerIpcsRegistered = false;+ // Pi 是“本次启动可选”的能力:一旦首次准备失败,就算后续清单/CDN恢复,+ // 也不再把 Pi 动态塞回已经构造好的 Maker,避免返回状态与实际能力不一致。+ let piDisabledForLaunch = false;const registerMakerIpcsAfterSplash = async (): Promise<void> => {if (makerIpcsRegistered) return;// 模型供应商目录(providers.json)按「OSS 真源 / bundled 兜底」加载一次存内存:必须在第一次@@ -4041,7 +4047,7 @@ const registerIpcHandlers = () => {// 提前 peekNeedsDownload 决定 (x/y) 标签:两个及以上需要下载时给 step/totalSteps,// 否则不带标签(splash 显示单一 "唤醒 Cindy 中..." 文案)。// pi 是可选实验 agent:清单无资产 / 下载失败都不算环境检查失败(失败不广播- // failed payload),pi-host 会回退安装包自带分发,再缺失则本次不注册 pi。+ // failed payload),本次不注册 pi。ipcMain.handle('check-environment', async () => {// splash 首个 invoke = renderer 存活的强信号(与 renderer:log 双保险)。rendererBootGuard?.markAlive();@@ -4143,28 +4149,41 @@ const registerIpcHandlers = () => {}// ── Phase 3: pi 段(可选,失败不阻塞启动)──────────────────────────────────- // broadcastFailure: false —— pi 下载失败不能把 splash 打进失败态;静默降级,- // buildPiAgent 会依次回退 userData 已装版本 → 安装包自带分发(resources/pi)。+ // broadcastFailure: false —— pi 下载失败不能把 splash 打进失败态;静默禁用+ // 本次 pi 注册,Claude Code / Codex 与 Cindy 本身仍照常可用。+ // 只从 Pi 阶段开始计时,不能让前面的必需 binary 下载吃掉 Pi 自己的预算。+ const piInstallSignal = app.isPackaged+ ? AbortSignal.timeout(PI_AGENT_INSTALL_STARTUP_DEADLINE_MS)+ : undefined;resetBeforeSegment('pi', claudeRes.downloaded === true || codexRes.downloaded === true);let piInfo: { status: 'passed' | 'failed'; path?: string; error?: string };- try {- const piRes = await binaryPrepare('pi', {- ...stepOptsFor('pi'),- broadcastFailure: false,- });- piInfo = piRes.ready && piRes.path- ? { status: 'passed' as const, path: piRes.path }- : { status: 'failed' as const, error: piRes.error ?? 'pi binary not available' };- } catch (err: unknown) {+ if (piDisabledForLaunch) {piInfo = {status: 'failed' as const,- error: err instanceof Error ? err.message : String(err),+ error: 'pi disabled for this launch after an earlier prepare failure',};+ } else {+ try {+ const piRes = await binaryPrepare('pi', {+ ...stepOptsFor('pi'),+ broadcastFailure: false,+ signal: piInstallSignal,+ });+ piInfo = piRes.ready && piRes.path+ ? { status: 'passed' as const, path: piRes.path }+ : { status: 'failed' as const, error: piRes.error ?? 'pi binary not available' };+ } catch (err: unknown) {+ piInfo = {+ status: 'failed' as const,+ error: err instanceof Error ? err.message : String(err),+ };+ }}if (piInfo.status === 'failed') {+ piDisabledForLaunch = true;console.warn(- `[bootstrap-electron] pi binary prepare failed (non-fatal, falling back to bundled dist): ${piInfo.error}`,+ `[bootstrap-electron] pi binary prepare failed (non-fatal, pi disabled for this launch): ${piInfo.error}`,);}diff --git a/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts b/apps/desktop/src/main/downloader/__tests__/scheduler.test.tsnew file mode 100644index 0000000000..0dcb78ee4b--- /dev/null+++ b/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ computeHash: vi.fn(),+ executeOnce: vi.fn(),+ withRetry: vi.fn(),+}));++vi.mock('../integrity', () => ({ computeHash: mocks.computeHash }));+vi.mock('../transport', () => ({ executeOnce: mocks.executeOnce }));+vi.mock('../retry', () => ({ withRetry: mocks.withRetry }));+vi.mock('../resume', () => ({ deletePart: vi.fn(), deleteMeta: vi.fn() }));+vi.mock('../../logger', () => ({+ createLogger: () => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn() }),+}));++import { Scheduler } from '../scheduler';++const HASH_A = 'a'.repeat(64);+const HASH_B = 'b'.repeat(64);++function options(url: string, targetPath: string, sha256: string, signal?: AbortSignal) {+ return { url, targetPath, sha256, signal };+}++describe('downloader scheduler queued cancellation', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.computeHash.mockResolvedValue('not-the-expected-hash');+ mocks.withRetry.mockImplementation(async (run: () => Promise<unknown>) => run());+ });++ it('rejects an aborted queued task immediately instead of waiting behind an active download', async () => {+ let releaseFirst!: () => void;+ const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });+ let executeCount = 0;+ mocks.executeOnce.mockImplementation(async (ctx: { opts: { sha256: string } }) => {+ executeCount += 1;+ if (executeCount === 1) await firstGate;+ return { size: 1, sha256: ctx.opts.sha256 };+ });++ const scheduler = new Scheduler({ maxConcurrent: 1 });+ const first = scheduler.enqueue(options('https://first.invalid', '/tmp/cindy-first', HASH_A));+ await vi.waitFor(() => expect(mocks.executeOnce).toHaveBeenCalledTimes(1));++ const controller = new AbortController();+ const second = scheduler.enqueue(+ options('https://second.invalid', '/tmp/cindy-second', HASH_B, controller.signal),+ );+ controller.abort();++ await expect(second).rejects.toMatchObject({ code: 'ABORTED' });+ expect(mocks.executeOnce).toHaveBeenCalledTimes(1);++ releaseFirst();+ await expect(first).resolves.toMatchObject({ sha256: HASH_A });+ });+});diff --git a/apps/desktop/src/main/downloader/scheduler.ts b/apps/desktop/src/main/downloader/scheduler.tsindex 0ef1fbbd89..89daeac5a4 100644--- a/apps/desktop/src/main/downloader/scheduler.ts+++ b/apps/desktop/src/main/downloader/scheduler.ts@@ -38,6 +38,7 @@ interface QueuedTask {opts: DownloadOptions;resolve: (r: DownloadResult) => void;reject: (e: Error) => void;+ onAbort?: () => void;}export interface SchedulerOptions {@@ -68,11 +69,19 @@ export class Scheduler {if (existing !== undefined) return existing;const promise = new Promise<DownloadResult>((resolve, reject) => {- this.queue.push({ key, opts, resolve, reject });+ const task: QueuedTask = { key, opts, resolve, reject };+ task.onAbort = () => this.abortQueuedTask(task);+ opts.signal?.addEventListener('abort', task.onAbort, { once: true });+ this.queue.push(task);this.tryStart();});this.inflight.set(key, promise);- promise.finally(() => this.inflight.delete(key));+ // 用双分支 then 做清理,避免 finally 返回的 rejected Promise 在调用方+ // 尚未来得及接住时触发 unhandledRejection。+ void promise.then(+ () => this.inflight.delete(key),+ () => this.inflight.delete(key),+ );return promise;}@@ -98,6 +107,11 @@ export class Scheduler {const task = this.queue.shift();if (task === undefined) return;+ if (task.onAbort) {+ task.opts.signal?.removeEventListener('abort', task.onAbort);+ task.onAbort = undefined;+ }+// Aborted while queued.if (task.opts.signal?.aborted === true) {task.reject(new DownloadError('ABORTED', 'aborted while queued'));@@ -108,6 +122,17 @@ export class Scheduler {}}+ private abortQueuedTask(task: QueuedTask): void {+ const index = this.queue.indexOf(task);+ if (index < 0) return;+ this.queue.splice(index, 1);+ task.onAbort = undefined;+ task.reject(new DownloadError('ABORTED', 'aborted while queued'));+ // The aborted task did not consume an active slot, but another queued task+ // may now be startable when this callback races with a slot becoming free.+ this.tryStart();+ }+private async run(task: QueuedTask): Promise<void> {const startedAt = Date.now();const logger: Logger = task.opts.logger ?? defaultLogger;diff --git a/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts b/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.tsnew file mode 100644index 0000000000..7a2906fa19--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/piBinaryDistribution.test.ts@@ -0,0 +1,65 @@+/** Pi 正式版二进制必须与 Claude Code / Codex 一样只走 CDN,不能重新塞回安装包。 */++import fs from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const desktopRoot = path.resolve(process.cwd());++describe('Pi binary distribution contract', () => {+ it('does not stage or copy Pi into packaged resources', () => {+ const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');++ expect(forge).not.toContain('function stagePi(');+ expect(forge).not.toContain("'resources/pi'");+ expect(forge).not.toContain('stagePi(targetPlatform');+ });++ it('resolves Pi only through the managed CDN/dev binary chain', () => {+ const host = fs.readFileSync(+ path.join(desktopRoot, 'src/main/maker-host/pi-host.ts'),+ 'utf8',+ );++ expect(host).toContain("getReadyBinaryPath('pi')");+ expect(host).not.toContain("getCachedBinaryStatus('pi')");+ expect(host).not.toContain("path.join(process.resourcesPath, 'pi'");+ expect(host).not.toContain('安装包自带');+ });++ it('bounds optional Pi preparation so CDN trouble cannot hold the startup page', () => {+ const bootstrap = fs.readFileSync(+ path.join(desktopRoot, 'src/main/bootstrap-electron.ts'),+ 'utf8',+ );+ const binaries = fs.readFileSync(+ path.join(desktopRoot, 'src/main/agent-binaries/index.ts'),+ 'utf8',+ );++ expect(bootstrap).toContain('PI_AGENT_INSTALL_STARTUP_DEADLINE_MS = 60_000');+ expect(bootstrap).toContain('signal: piInstallSignal');+ expect(binaries).toContain('signal: opts.signal');+ });++ it('does not expose an old Pi cache through the binary-version IPC', () => {+ const binaryVersion = fs.readFileSync(+ path.join(desktopRoot, 'src/main/maker-ipc/binary-version.ts'),+ 'utf8',+ );++ expect(binaryVersion).toContain("if (kind === 'pi') return null;");+ });++ it('keeps a failed Pi disabled when check-environment is retried', () => {+ const bootstrap = fs.readFileSync(+ path.join(desktopRoot, 'src/main/bootstrap-electron.ts'),+ 'utf8',+ );++ expect(bootstrap).toContain('let piDisabledForLaunch = false;');+ expect(bootstrap).toContain('if (piDisabledForLaunch)');+ expect(bootstrap).toContain('piDisabledForLaunch = true;');+ });+});diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 9f39c5a403..89e15558f4 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -11,14 +11,12 @@* Responses bridge 翻译,Claude / Cindy AI 走透明 Anthropic 路由。* - 二进制:与 cc/codex 同链 —— splash prepare 经 agent-binaries 按 CDN manifest* 的 pi 字段下载整目录 tar.gz 到 userData/pi/<version>/(SHA256 校验,清单一变- * 下次启动即换新)。解析优先级:受管下载版(含 dev 期 apps/pi-bin,- * pnpm install:pi 产物)→ 安装包自带分发 resources/pi/<platform>(清单未发- * pi 资产或下载失败的兜底)。全部缺失 → buildPiAgent 返回 null,pi 不注册,- * 对既有环境零影响。+ * 下次启动即换新)。dev 期使用 apps/pi-bin 中 pnpm install:pi 的产物;正式版+ * 不内置 Pi,清单缺失或下载失败时 buildPiAgent 返回 null,本次不注册 pi,+ * 对 Cindy 启动零影响。*/import path from 'node:path';-import fs from 'node:fs';import { app } from 'electron';import { PiAgent, type AgentDeps, type AuthAdapter, type AuthState } from '@cindy/maker-core';@@ -31,7 +29,7 @@ import type {} from '@cindy/maker-core';import type { ProviderWireProtocol } from '@cindy/model-providers';-import { getCachedBinaryStatus } from '../agent-binaries/index.js';+import { getReadyBinaryPath } from '../agent-binaries/index.js';import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';import { listCustomProvidersWithSecureHeaders } from './custom-provider-header-secrets.js';import { readCustomProviderKey } from '../secrets/providerSecretStore.js';@@ -58,49 +56,14 @@ const PI_PROVIDER_AUTH_PLACEHOLDER_KEY = 'cindy-pi-provider-auth-placeholder';*/const PI_OAUTH_SUBSCRIPTION_PROVIDERS = new Set(['anthropic', 'openai', 'xai']);-// ── 二进制解析(dev 短路)────────────────────────────────────────────────────--function platformKey(): string {- return `${process.platform}-${process.arch}`;-}--function piBinaryName(): string {- return process.platform === 'win32' ? 'pi.exe' : 'pi';-}-/*** 解析 pi 主执行文件绝对路径;找不到返回 null(pi 为可选实验 agent,不阻塞启动)。* pi 产物是目录形态(主二进制 + theme/ 等运行时资产),路径指向其中的可执行文件。- *- * 优先级:- * 1. agent-binaries 受管链 —— splash prepare 下载的 userData/pi/<version>/- * (packaged;清单一变下次启动自动换新),dev 期为 apps/pi-bin/<platform>/- * (pnpm install:pi 产物,经 dev-fallback 命中)。- * 2. 安装包自带整目录分发 resources/pi/<platform> —— CDN 清单未发 pi 资产或- * 下载失败时的兜底(离线首启也可用)。+ * 路径只来自 agent-binaries 受管链:正式版是 CDN 下载到 userData/pi/<version>/+ * 的已校验目录,dev 是 apps/pi-bin/<platform>/ 中 pnpm install:pi 的产物。*/export function resolvePiBinaryPath(): string | null {- const managed = getCachedBinaryStatus('pi');- if (managed.binaryReady && managed.binaryPath) return managed.binaryPath;-- const key = platformKey();- const file = piBinaryName();- const candidates = app.isPackaged- ? [path.join(process.resourcesPath, 'pi', key)]- : [- path.join(app.getAppPath(), '..', '..', 'apps', 'pi-bin', key),- path.join(process.cwd(), 'apps', 'pi-bin', key),- path.join(process.cwd(), '..', 'pi-bin', key),- ];- for (const dir of candidates) {- const bin = path.join(dir, file);- if (!fs.existsSync(bin)) continue;- if (process.platform !== 'win32') {- try { fs.chmodSync(bin, 0o755); } catch { /* ignore */ }- }- return bin;- }- return null;+ return getReadyBinaryPath('pi') ?? null;}// ── AuthAdapter(XD 网关 key)─────────────────────────────────────────────────@@ -352,7 +315,7 @@ async function resolvePiNativeProviders(): Promise<PiNativeProvidersResult> {export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {const binaryPath = resolvePiBinaryPath();if (!binaryPath) {- log.warn('pi binary not found (run `pnpm install:pi`); pi agent disabled for this launch');+ log.warn('pi binary unavailable after managed prepare; pi agent disabled for this launch');return null;}log.info('pi agent enabled', { binaryPath });diff --git a/apps/desktop/src/main/maker-ipc/binary-version.ts b/apps/desktop/src/main/maker-ipc/binary-version.tsindex 30e62d703f..2310cbf313 100644--- a/apps/desktop/src/main/maker-ipc/binary-version.ts+++ b/apps/desktop/src/main/maker-ipc/binary-version.ts@@ -5,7 +5,8 @@* 把首行输出回给 renderer 的 About 面板。** 设计:- * - 路径来源: getReadyBinaryPath() (prepare 成功后写入), 拿不到再退到 getCachedBinaryStatus()。+ * - Claude/Codex 在 prepare 成功后优先读 getReadyBinaryPath(),必要时可读受管缓存;+ * Pi 是可选资产,只允许使用本次 prepare 成功的路径,失败时不能复用旧缓存。* - 进程内按 binaryPath 缓存结果, 同一 binary 只 spawn 一次。* - 5s 超时, 失败时返回 { error }。*/@@ -42,6 +43,7 @@ function isAgentBinaryKind(value: unknown): value is AgentBinaryKind {function resolveBinaryPath(kind: AgentBinaryKind): string | null {const ready = getReadyBinaryPath(kind);if (ready) return ready;+ if (kind === 'pi') return null;const cached = getCachedBinaryStatus(kind);return cached.binaryReady && cached.binaryPath ? cached.binaryPath : null;}diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex 122e73f0da..57cbbadee4 100644--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts@@ -151,7 +151,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [title: "App updates, version and logs",summary: "How auto-updates apply; where to find the app and agent versions, the debug-log toggle, and the logs folder.",tab: "about",- content: "Cindy checks for updates automatically and downloads them in the background. When an update is ready, you're prompted to **relaunch** the app to apply it.\n\n**Settings > About:**\n\n- **App version** — the desktop app's release.\n- **Claude Code version** / **Codex version** — the bundled agent CLIs the app ships with (these update with the app, not separately).\n- **Auto-relaunch when idle** — an optional toggle that lets a downloaded update apply itself during idle time instead of waiting for you to click relaunch.\n- **Debug log toggle** — turn on more verbose logging when reproducing a problem. Leave it off for normal use.\n- **Open logs folder** — opens the logs directory in your OS file browser, useful when you need to attach logs to a bug report.\n- **Storage** — a storage-management card for reviewing / clearing local app data.\n\n**Notes:**\n\n- By default, a downloaded update only triggers a relaunch prompt — it won't restart you unexpectedly. If you enable **Auto-relaunch when idle**, Cindy will restart itself automatically once the idle and busy gates pass, without an additional prompt.\n- If you want to skip auto-update temporarily, you can dismiss the relaunch prompt; the update applies next time you start the app.\n- The Claude Code / Codex versions you see here are what the **app's bundled agents** run as — they're independent from any Claude / Codex CLI you have installed globally on your shell.",+ content: "Cindy checks for updates automatically and downloads them in the background. When an update is ready, you're prompted to **relaunch** the app to apply it.\n\n**Settings > About:**\n\n- **App version** — the desktop app's release.\n- **Claude Code version** / **Codex version** — the agent CLIs Cindy manages and downloads at runtime into your user data (they update separately from the app).\n- **Auto-relaunch when idle** — an optional toggle that lets a downloaded update apply itself during idle time instead of waiting for you to click relaunch.\n- **Debug log toggle** — turn on more verbose logging when reproducing a problem. Leave it off for normal use.\n- **Open logs folder** — opens the logs directory in your OS file browser, useful when you need to attach logs to a bug report.\n- **Storage** — a storage-management card for reviewing / clearing local app data.\n\n**Notes:**\n\n- By default, a downloaded update only triggers a relaunch prompt — it won't restart you unexpectedly. If you enable **Auto-relaunch when idle**, Cindy will restart itself automatically once the idle and busy gates pass, without an additional prompt.\n- If you want to skip auto-update temporarily, you can dismiss the relaunch prompt; the update applies next time you start the app.\n- The Claude Code / Codex versions you see here are what Cindy's **managed agents** run as — they're independent from any Claude / Codex CLI you have installed globally on your shell.",},{id: "voice-input",diff --git a/apps/desktop/src/main/manifestService.ts b/apps/desktop/src/main/manifestService.tsindex 1c554b0ce8..5f077fb8f1 100644--- a/apps/desktop/src/main/manifestService.ts+++ b/apps/desktop/src/main/manifestService.ts@@ -73,7 +73,7 @@ export interface RipgrepManifest {/*** pi 是整目录分发:`file` 指向整包 tar.gz(归档根即完整运行时目录,主二进制 +* theme/ 等旁侧资产,与 apps/pi-bin/<platform>/ 同布局),`sha256`/`size` 是该- * tar.gz 的。可选字段:清单未发 pi 资产时客户端回退安装包自带分发(resources/pi)。+ * tar.gz 的。可选字段:清单未发 pi 资产或下载失败时,本次不注册 pi,但不阻塞启动。*/export interface PiManifest {version: string;@@ -138,8 +138,12 @@ export function isDev(): boolean {* to stable — that would silently downgrade canary users to whatever stale* version is sitting on the stable channel.*/-export async function fetchManifest(timeoutMs?: number): Promise<Manifest | null> {+export async function fetchManifest(+ timeoutMs?: number,+ signal?: AbortSignal,+): Promise<Manifest | null> {if (isDev()) return null;+ if (signal?.aborted) return null;const isCanary = canaryFlagStore.read();const channelSuffix = isCanary ? '-canary' : '';@@ -152,21 +156,25 @@ export async function fetchManifest(timeoutMs?: number): Promise<Manifest | nullconst request = net.request(url);let body = '';let settled = false;+ let timeout: ReturnType<typeof setTimeout> | undefined;- const timeout = setTimeout(() => {- if (!settled) {- settled = true;- request.abort();- resolve(null);- }- }, timeoutMs ?? REQUEST_TIMEOUT_MS);+ const finish = (value: Manifest | null, abortRequest = false): void => {+ if (settled) return;+ settled = true;+ if (timeout) clearTimeout(timeout);+ signal?.removeEventListener('abort', onAbort);+ if (abortRequest) request.abort();+ resolve(value);+ };+ const onAbort = (): void => finish(null, true);+ signal?.addEventListener('abort', onAbort, { once: true });++ timeout = setTimeout(() => finish(null, true), timeoutMs ?? REQUEST_TIMEOUT_MS);request.on('response', (response) => {if (response.statusCode !== 200) {log.info('HTTP %d for %s', response.statusCode, url);- clearTimeout(timeout);- settled = true;- resolve(null);+ finish(null);return;}@@ -174,37 +182,27 @@ export async function fetchManifest(timeoutMs?: number): Promise<Manifest | nullbody += chunk.toString();});response.on('end', () => {- clearTimeout(timeout);if (settled) return;- settled = true;try {const json = JSON.parse(body) as Manifest;cached = json;log.info('Fetched OK: app.version=%s, hotfix=%s', json.app?.version, json.app?.hotfix?.file ?? 'none');- resolve(json);+ finish(json);} catch (err) {log.error('JSON parse failed:', err);- resolve(null);- }- });- response.on('error', () => {- clearTimeout(timeout);- if (!settled) {- settled = true;- resolve(null);+ finish(null);}});+ response.on('error', () => finish(null));});- request.on('error', () => {- clearTimeout(timeout);- if (!settled) {- settled = true;- resolve(null);- }- });+ request.on('error', () => finish(null));- request.end();+ try {+ request.end();+ } catch {+ finish(null, true);+ }} catch {resolve(null);}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 5836437783..f1b39ff4b9 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -47,7 +47,7 @@ type RemotePrecreatedWorktreeLedgerSnapshot =interface EnvCheckResult {claudeCode: { status: 'passed' | 'failed'; path?: string; error?: string };codex: { status: 'passed' | 'failed' | 'skipped'; path?: string; error?: string };- /** pi 可选实验 agent:failed 不影响 allPassed(主进程会降级到安装包自带分发)。 */+ /** pi 可选实验 agent:failed 不影响 allPassed;本次启动会禁用 pi。 */pi?: { status: 'passed' | 'failed' | 'skipped'; path?: string; error?: string };allPassed: boolean;platform: 'darwin' | 'win32' | 'linux';diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 08f74a0b18..0b6e8091ff 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -88,17 +88,13 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、- [x] **平台分发**:pin 已升级到 Pi `v0.83.0`,darwin arm64/x64、linux arm64/x64、win32 arm64/x64 六份官方资产都进入 digest pin;下载器兼容 Unix `pi/` 嵌套包与- Windows 根目录平铺 zip。Forge 按目标平台下载、校验并把**完整目录分发**打进- `resources/pi/<platform>`,Windows `pi.exe` 进入签名扫描。当前 Mac 已完成六资产- SHA-256 下载验收;非本机 OS 的最终启动 smoke 仍由对应发布 runner 执行。- 2026-08 起 pi 接入与 cc/codex 相同的 CDN 运行时分发链(`agent-binaries` +- splash prepare):CDN manifest 新增可选 `pi` 字段(整包 tar.gz,归档根即完整- 目录分发,SHA256 为 tar.gz 的),启动时按 manifest 版本下载到- `userData/pi/<version>/` 并清旧版。pi 是可选资产:manifest 缺字段/下载失败- **不阻塞启动**(splash 不进失败态),`pi-host.resolvePiBinaryPath` 依次回退- 受管下载版 → `resources/pi/<platform>` 安装包自带分发。发布侧需把整包- tar.gz 上传 CDN 并写 manifest `pi` 字段后,该链路才对 packaged 用户生效;- 在那之前行为与旧版一致(只用安装包自带分发)。发布入口**不在本仓**:+ Windows 根目录平铺 zip。当前 Mac 已完成六资产 SHA-256 下载验收;非本机 OS 的+ 最终启动 smoke 仍由对应发布 runner 执行。2026-08 起 pi 与 cc/codex 一样只走+ CDN 运行时分发链(`agent-binaries` + splash prepare):CDN manifest 的可选 `pi`+ 字段指向整包 tar.gz(归档根即完整目录分发,SHA256 为 tar.gz 的),启动时按+ manifest 版本下载到 `userData/pi/<version>/` 并清旧版。正式安装包不内置 Pi;+ manifest 缺字段或下载失败时**不阻塞启动**(splash 不进失败态),本次不注册 pi。+ 发布入口**不在本仓**:二进制发布统一走 cindy 同级目录的独立工程 `cindy-binary-release`(`pnpm release:pi -- --region cn|global`,默认 canary 通道;配置与安全机制见该工程 README)。本仓只保留版本 pin 与暂存(`pnpm update:pi` / `install:pi`)。diff --git a/docs/legal/notices/README.md b/docs/legal/notices/README.mdindex ab0384701c..1585169660 100644--- a/docs/legal/notices/README.md+++ b/docs/legal/notices/README.md@@ -3,9 +3,11 @@本目录位于 `docs/legal/notices/`。`pnpm licenses:generate` 根据锁定依赖生成以下合规产物:-- `desktop-win.txt`:Windows x64 桌面安装包,包含 Rust updater 与 ADB。-- `desktop-macos.txt`:macOS x64/arm64 桌面安装包。-- `desktop-linux.txt`:Linux x64 glibc 桌面安装包。+- `desktop-win.txt`:Windows x64 桌面分发,包含安装包内的 Rust updater 与 ADB。+- `desktop-macos.txt`:macOS x64/arm64 桌面分发。+- `desktop-linux.txt`:Linux x64/arm64 glibc 桌面分发。+ 三份桌面声明也覆盖启动后受管下载的 agent CLI;Claude Code、Codex 与 Pi+ 不包含在安装包内,而是下载到用户数据目录。- `mobile-ios.txt` / `mobile-android.txt`:移动端 JS 生产依赖与仓库显式声明的原生 SDK。按 app 实际分发到的设备过滤,不含只在开发机构建期使用的平台可选原生包(这些包的JS 主包本身仍在声明内,只是其 `darwin`/`linux`/`win32` 预编译二进制不随 app 分发)。diff --git a/docs/legal/notices/THIRD-PARTY-NOTICES.txt b/docs/legal/notices/THIRD-PARTY-NOTICES.txtindex 4570c313c9..62c1298af1 100644--- a/docs/legal/notices/THIRD-PARTY-NOTICES.txt+++ b/docs/legal/notices/THIRD-PARTY-NOTICES.txt@@ -19,7 +19,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------@@ -3738,7 +3738,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------OpenAI Codex CLI (bundled binary) 0.145.0+OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0Source: https://github.com/openai/codex------------------------------------------------------------------------------@@ -3974,7 +3974,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-------------------------------------------------------------------------------pi coding agent (bundled binary) 0.83.0+pi coding agent (runtime-downloaded binary) 0.83.0License: MITSource: https://github.com/earendil-works/pi------------------------------------------------------------------------------diff --git a/docs/legal/notices/desktop-linux.txt b/docs/legal/notices/desktop-linux.txtindex c258e395be..f746e6badd 100644--- a/docs/legal/notices/desktop-linux.txt+++ b/docs/legal/notices/desktop-linux.txt@@ -19,7 +19,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------@@ -50,7 +50,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------OpenAI Codex CLI (bundled binary) 0.145.0+OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0Source: https://github.com/openai/codex------------------------------------------------------------------------------@@ -259,7 +259,7 @@ Apache LicenseCopyright (c) OpenAI-------------------------------------------------------------------------------pi coding agent (bundled binary) 0.83.0+pi coding agent (runtime-downloaded binary) 0.83.0License: MITSource: https://github.com/earendil-works/pi------------------------------------------------------------------------------diff --git a/docs/legal/notices/desktop-macos.txt b/docs/legal/notices/desktop-macos.txtindex 46ac15c030..740f3c190e 100644--- a/docs/legal/notices/desktop-macos.txt+++ b/docs/legal/notices/desktop-macos.txt@@ -19,7 +19,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------@@ -50,7 +50,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------OpenAI Codex CLI (bundled binary) 0.145.0+OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0Source: https://github.com/openai/codex------------------------------------------------------------------------------@@ -259,7 +259,7 @@ Apache LicenseCopyright (c) OpenAI-------------------------------------------------------------------------------pi coding agent (bundled binary) 0.83.0+pi coding agent (runtime-downloaded binary) 0.83.0License: MITSource: https://github.com/earendil-works/pi------------------------------------------------------------------------------diff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txtindex e629151f63..01bd81bc5f 100644--- a/docs/legal/notices/desktop-win.txt+++ b/docs/legal/notices/desktop-win.txt@@ -19,7 +19,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------@@ -50,7 +50,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.-------------------------------------------------------------------------------OpenAI Codex CLI (bundled binary) 0.145.0+OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0Source: https://github.com/openai/codex------------------------------------------------------------------------------@@ -259,7 +259,7 @@ Apache LicenseCopyright (c) OpenAI-------------------------------------------------------------------------------pi coding agent (bundled binary) 0.83.0+pi coding agent (runtime-downloaded binary) 0.83.0License: MITSource: https://github.com/earendil-works/pi------------------------------------------------------------------------------diff --git a/docs/legal/notices/mobile-android.txt b/docs/legal/notices/mobile-android.txtindex 1b96db6ce9..0f0617ae8f 100644--- a/docs/legal/notices/mobile-android.txt+++ b/docs/legal/notices/mobile-android.txt@@ -20,7 +20,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------diff --git a/docs/legal/notices/mobile-ios.txt b/docs/legal/notices/mobile-ios.txtindex ab90651a97..ed92052d92 100644--- a/docs/legal/notices/mobile-ios.txt+++ b/docs/legal/notices/mobile-ios.txt@@ -20,7 +20,7 @@ SCOPE NOTES:Restricted or proprietary components are disclosed in the companion file.==============================================================================-SECTION 1: Bundled components (non-npm)+SECTION 1: Non-npm components==============================================================================------------------------------------------------------------------------------diff --git a/docs/legal/notices/sbom/desktop-linux.spdx.json b/docs/legal/notices/sbom/desktop-linux.spdx.jsonindex fabfe9843d..b79463b702 100644--- a/docs/legal/notices/sbom/desktop-linux.spdx.json+++ b/docs/legal/notices/sbom/desktop-linux.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-linux",- "documentNamespace": "https://cindy.app/spdx/desktop-linux/79dc59f14f6dce4df3cb4fc99abf194a2bb7eb87e6061b760fa456a9991770b4",+ "documentNamespace": "https://cindy.app/spdx/desktop-linux/156d44a61ecf03e9226484f8e891de84ed099853480e30fba697a651bf84af24","creationInfo": {- "created": "2026-08-01T10:11:54Z",+ "created": "2026-08-02T09:08:05Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -72,8 +72,8 @@"copyrightText": "NOASSERTION"},{- "name": "OpenAI Codex CLI (bundled binary)",- "SPDXID": "SPDXRef-Package-2533cecb0b1ad2d4",+ "name": "OpenAI Codex CLI (runtime-downloaded binary)",+ "SPDXID": "SPDXRef-Package-4f22132a77577bcb","versionInfo": "0.145.0","downloadLocation": "https://github.com/openai/codex","filesAnalyzed": false,@@ -92,8 +92,8 @@"copyrightText": "NOASSERTION"},{- "name": "pi coding agent (bundled binary)",- "SPDXID": "SPDXRef-Package-47bf96d7e756f6b6",+ "name": "pi coding agent (runtime-downloaded binary)",+ "SPDXID": "SPDXRef-Package-04c1add3e48a9e5c","versionInfo": "0.83.0","downloadLocation": "https://github.com/earendil-works/pi","filesAnalyzed": false,@@ -13684,7 +13684,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-2533cecb0b1ad2d4"+ "relatedSpdxElement": "SPDXRef-Package-4f22132a77577bcb"},{"spdxElementId": "SPDXRef-DOCUMENT",@@ -13694,7 +13694,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-47bf96d7e756f6b6"+ "relatedSpdxElement": "SPDXRef-Package-04c1add3e48a9e5c"},{"spdxElementId": "SPDXRef-DOCUMENT",diff --git a/docs/legal/notices/sbom/desktop-macos.spdx.json b/docs/legal/notices/sbom/desktop-macos.spdx.jsonindex f19092c749..895c60a362 100644--- a/docs/legal/notices/sbom/desktop-macos.spdx.json+++ b/docs/legal/notices/sbom/desktop-macos.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-macos",- "documentNamespace": "https://cindy.app/spdx/desktop-macos/e4b94a7831c16c0a5dbc25aa2dbb5e81375a4510170b73f063ce50eec31456f7",+ "documentNamespace": "https://cindy.app/spdx/desktop-macos/1668c13954a47a76830fdbc5ec00a56b0bf2d6ea47c88c057d140572c73fb28b","creationInfo": {- "created": "2026-08-01T10:11:54Z",+ "created": "2026-08-02T09:08:05Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -82,8 +82,8 @@"copyrightText": "NOASSERTION"},{- "name": "OpenAI Codex CLI (bundled binary)",- "SPDXID": "SPDXRef-Package-2533cecb0b1ad2d4",+ "name": "OpenAI Codex CLI (runtime-downloaded binary)",+ "SPDXID": "SPDXRef-Package-4f22132a77577bcb","versionInfo": "0.145.0","downloadLocation": "https://github.com/openai/codex","filesAnalyzed": false,@@ -102,8 +102,8 @@"copyrightText": "NOASSERTION"},{- "name": "pi coding agent (bundled binary)",- "SPDXID": "SPDXRef-Package-47bf96d7e756f6b6",+ "name": "pi coding agent (runtime-downloaded binary)",+ "SPDXID": "SPDXRef-Package-04c1add3e48a9e5c","versionInfo": "0.83.0","downloadLocation": "https://github.com/earendil-works/pi","filesAnalyzed": false,@@ -13699,7 +13699,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-2533cecb0b1ad2d4"+ "relatedSpdxElement": "SPDXRef-Package-4f22132a77577bcb"},{"spdxElementId": "SPDXRef-DOCUMENT",@@ -13709,7 +13709,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-47bf96d7e756f6b6"+ "relatedSpdxElement": "SPDXRef-Package-04c1add3e48a9e5c"},{"spdxElementId": "SPDXRef-DOCUMENT",diff --git a/docs/legal/notices/sbom/desktop-win.spdx.json b/docs/legal/notices/sbom/desktop-win.spdx.jsonindex f385cc9495..0bb70886c9 100644--- a/docs/legal/notices/sbom/desktop-win.spdx.json+++ b/docs/legal/notices/sbom/desktop-win.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-win",- "documentNamespace": "https://cindy.app/spdx/desktop-win/c53da8f0bda75462bf53132753780390aeaf4d983f66392816b195a81311814b",+ "documentNamespace": "https://cindy.app/spdx/desktop-win/13eefb05658bb33ea52ade0679664ceaf1ace05c2f2a30ad4ee7562116a4903c","creationInfo": {- "created": "2026-08-01T10:11:54Z",+ "created": "2026-08-02T09:08:05Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -72,8 +72,8 @@"copyrightText": "NOASSERTION"},{- "name": "OpenAI Codex CLI (bundled binary)",- "SPDXID": "SPDXRef-Package-2533cecb0b1ad2d4",+ "name": "OpenAI Codex CLI (runtime-downloaded binary)",+ "SPDXID": "SPDXRef-Package-4f22132a77577bcb","versionInfo": "0.145.0","downloadLocation": "https://github.com/openai/codex","filesAnalyzed": false,@@ -92,8 +92,8 @@"copyrightText": "NOASSERTION"},{- "name": "pi coding agent (bundled binary)",- "SPDXID": "SPDXRef-Package-47bf96d7e756f6b6",+ "name": "pi coding agent (runtime-downloaded binary)",+ "SPDXID": "SPDXRef-Package-04c1add3e48a9e5c","versionInfo": "0.83.0","downloadLocation": "https://github.com/earendil-works/pi","filesAnalyzed": false,@@ -18053,7 +18053,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-2533cecb0b1ad2d4"+ "relatedSpdxElement": "SPDXRef-Package-4f22132a77577bcb"},{"spdxElementId": "SPDXRef-DOCUMENT",@@ -18063,7 +18063,7 @@{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",- "relatedSpdxElement": "SPDXRef-Package-47bf96d7e756f6b6"+ "relatedSpdxElement": "SPDXRef-Package-04c1add3e48a9e5c"},{"spdxElementId": "SPDXRef-DOCUMENT",diff --git a/docs/legal/notices/sbom/mobile-android.spdx.json b/docs/legal/notices/sbom/mobile-android.spdx.jsonindex a5a42b71d3..665ef17ca0 100644--- a/docs/legal/notices/sbom/mobile-android.spdx.json+++ b/docs/legal/notices/sbom/mobile-android.spdx.json@@ -5,7 +5,7 @@"name": "cindy-mobile-android","documentNamespace": "https://cindy.app/spdx/mobile-android/05efd357f74ac207a075699dbbd457afe65ed99fd574ee594be1d4bb651dc49a","creationInfo": {- "created": "2026-08-01T10:11:54Z",+ "created": "2026-08-02T09:08:05Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]diff --git a/docs/legal/notices/sbom/mobile-ios.spdx.json b/docs/legal/notices/sbom/mobile-ios.spdx.jsonindex 7c04eab56d..31eae9c22c 100644--- a/docs/legal/notices/sbom/mobile-ios.spdx.json+++ b/docs/legal/notices/sbom/mobile-ios.spdx.json@@ -5,7 +5,7 @@"name": "cindy-mobile-ios","documentNamespace": "https://cindy.app/spdx/mobile-ios/9cae3d29bee1df233432e6dd0978265ea2d61b380b2e50bf92a64c3516a1cccf","creationInfo": {- "created": "2026-08-01T10:11:54Z",+ "created": "2026-08-02T09:08:05Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]diff --git a/package.json b/package.jsonindex b9a59849f4..c94d33b7d6 100644--- a/package.json+++ b/package.json@@ -115,7 +115,7 @@"licenses:generate": "node scripts/generate-third-party-notices.mjs","lint": "pnpm -r lint","format": "pnpm -r format",- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/glossary-rules.test.mjs",+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs","test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit","test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all","test:git-integration": "pnpm test:runner && node scripts/test-workspaces.mjs --tier git-integration",diff --git a/scripts/__tests__/notarize-mac-app.test.mjs b/scripts/__tests__/notarize-mac-app.test.mjsnew file mode 100644index 0000000000..7ed5700668--- /dev/null+++ b/scripts/__tests__/notarize-mac-app.test.mjs@@ -0,0 +1,244 @@+// macOS 公证编排回归测试。所有命令与文件操作都通过依赖注入模拟,+// 不连接 Apple 服务、不读取真实凭证,也不创建打包产物。+import { test } from 'node:test';+import assert from 'node:assert/strict';++import { notarizeMacApp } from '../../apps/desktop/scripts/ci/lib.mjs';++const APP_PATH = '/tmp/Cindy.app';+const ZIP_PATH = `${APP_PATH}.zip`;+const IDENTITY = Object.freeze({+ appleId: '[email protected]',+ teamId: 'TEAM123456',+ applePassword: 'test-app-password',+});++function createHarness(results) {+ const queue = [...results];+ const execCommands = [];+ const spawnCalls = [];+ const deletedFiles = [];+ const output = [];+ const logger = {+ log(...args) {+ output.push(args.join(' '));+ },+ error(...args) {+ output.push(args.join(' '));+ },+ };+ const dependencies = {+ execCommand(command) {+ execCommands.push(command);+ },+ spawnCommand(command, args, options) {+ spawnCalls.push({ command, args, options });+ assert.ok(queue.length > 0, `unexpected spawn: ${command} ${args.join(' ')}`);+ const result = queue.shift();+ if (result instanceof Error) throw result;+ return result;+ },+ unlinkFile(filePath) {+ deletedFiles.push(filePath);+ },+ logger,+ };+ return {+ dependencies,+ execCommands,+ spawnCalls,+ deletedFiles,+ output,+ assertQueueDrained() {+ assert.equal(queue.length, 0, 'all mocked command results should be consumed');+ },+ };+}++test('notarizeMacApp: Accepted 后才删除 zip 并 staple', () => {+ const harness = createHarness([{+ status: 0,+ signal: null,+ stdout: JSON.stringify({ id: 'accepted-id', status: 'Accepted' }),+ stderr: '',+ }]);++ notarizeMacApp(APP_PATH, IDENTITY, harness.dependencies);++ assert.deepEqual(harness.deletedFiles, [ZIP_PATH]);+ assert.deepEqual(harness.execCommands, [+ `/usr/bin/ditto -c -k --keepParent "${APP_PATH}" "${ZIP_PATH}"`,+ `/usr/bin/xcrun stapler staple "${APP_PATH}"`,+ ]);+ assert.equal(harness.spawnCalls.length, 1);+ assert.deepEqual(harness.spawnCalls[0], {+ command: '/usr/bin/xcrun',+ args: [+ 'notarytool',+ 'submit',+ ZIP_PATH,+ '--apple-id',+ IDENTITY.appleId,+ '--password',+ IDENTITY.applePassword,+ '--team-id',+ IDENTITY.teamId,+ '--wait',+ '--output-format',+ 'json',+ ],+ options: { encoding: 'utf8', timeout: 1800000 },+ });+ assert.match(harness.output.join('\n'), /Apple notarization status: Accepted/);+ assert.doesNotMatch(harness.output.join('\n'), new RegExp(IDENTITY.applePassword));+ harness.assertQueueDrained();+});++test('notarizeMacApp: Invalid 时拉取详细日志且不删除或 staple', () => {+ const harness = createHarness([+ {+ status: 0,+ signal: null,+ stdout: JSON.stringify({ id: 'invalid-id', status: 'Invalid' }),+ stderr: '',+ },+ {+ status: 0,+ signal: null,+ stdout: JSON.stringify({+ statusCode: 4000,+ issues: [{ path: 'Cindy.app/Contents/MacOS/pi', message: IDENTITY.applePassword }],+ }),+ stderr: '',+ },+ ]);++ assert.throws(+ () => notarizeMacApp(APP_PATH, IDENTITY, harness.dependencies),+ /Apple 公证未通过: status=Invalid, submission=invalid-id/,+ );++ assert.deepEqual(harness.deletedFiles, []);+ assert.deepEqual(harness.execCommands, [+ `/usr/bin/ditto -c -k --keepParent "${APP_PATH}" "${ZIP_PATH}"`,+ ]);+ assert.equal(harness.spawnCalls.length, 2);+ assert.deepEqual(harness.spawnCalls[1].args, [+ 'notarytool',+ 'log',+ 'invalid-id',+ '--apple-id',+ IDENTITY.appleId,+ '--password',+ IDENTITY.applePassword,+ '--team-id',+ IDENTITY.teamId,+ ]);+ const output = harness.output.join('\n');+ assert.match(output, /Apple notarization log:/);+ assert.match(output, /Cindy\.app\/Contents\/MacOS\/pi/);+ assert.match(output, /\*\*\*\*/);+ assert.doesNotMatch(output, new RegExp(IDENTITY.applePassword));+ harness.assertQueueDrained();+});++test('notarizeMacApp: submit 命令失败时保留 zip 且输出脱敏诊断', () => {+ const harness = createHarness([{+ status: 1,+ signal: null,+ stdout: '',+ stderr: `authentication rejected: ${IDENTITY.applePassword}`,+ }]);++ assert.throws(+ () => notarizeMacApp(APP_PATH, IDENTITY, harness.dependencies),+ /notarytool submit 失败\(exit 1\);公证未通过/,+ );++ assert.deepEqual(harness.deletedFiles, []);+ assert.equal(harness.execCommands.length, 1);+ assert.equal(harness.spawnCalls.length, 1);+ const output = harness.output.join('\n');+ assert.match(output, /authentication rejected: \*\*\*\*/);+ assert.doesNotMatch(output, new RegExp(IDENTITY.applePassword));+ harness.assertQueueDrained();+});++// notarytool 对 Invalid 提交的 exit code 随 Xcode 版本变化;非 0 退出这条路径同样+// 必须从 stdout 里救出 submission id 去拉 Apple 的详细原因,否则发布失败无从定位。+test('notarizeMacApp: submit 非 0 退出但 stdout 带 Invalid 时仍拉取详细日志', () => {+ const harness = createHarness([+ {+ status: 2,+ signal: null,+ stdout: JSON.stringify({ id: 'nonzero-invalid-id', status: 'Invalid' }),+ stderr: '',+ },+ {+ status: 0,+ signal: null,+ stdout: JSON.stringify({+ statusCode: 4000,+ issues: [{ path: 'Cindy.app/Contents/MacOS/cindy', message: 'not signed' }],+ }),+ stderr: '',+ },+ ]);++ assert.throws(+ () => notarizeMacApp(APP_PATH, IDENTITY, harness.dependencies),+ /notarytool submit 失败\(exit 2\);公证未通过/,+ );++ assert.deepEqual(harness.deletedFiles, []);+ assert.deepEqual(harness.execCommands, [+ `/usr/bin/ditto -c -k --keepParent "${APP_PATH}" "${ZIP_PATH}"`,+ ]);+ assert.equal(harness.spawnCalls.length, 2);+ assert.deepEqual(harness.spawnCalls[1].args, [+ 'notarytool',+ 'log',+ 'nonzero-invalid-id',+ '--apple-id',+ IDENTITY.appleId,+ '--password',+ IDENTITY.applePassword,+ '--team-id',+ IDENTITY.teamId,+ ]);+ const output = harness.output.join('\n');+ assert.match(output, /Apple notarization log:/);+ assert.match(output, /not signed/);+ assert.doesNotMatch(output, new RegExp(IDENTITY.applePassword));+ harness.assertQueueDrained();+});++test('notarizeMacApp: Invalid 的日志命令失败仍直接报告公证失败', () => {+ const harness = createHarness([+ {+ status: 0,+ signal: null,+ stdout: JSON.stringify({ id: 'invalid-log-failure', status: 'Invalid' }),+ stderr: '',+ },+ {+ status: 69,+ signal: null,+ stdout: '',+ stderr: `log authentication failed: ${IDENTITY.applePassword}`,+ },+ ]);++ assert.throws(+ () => notarizeMacApp(APP_PATH, IDENTITY, harness.dependencies),+ /Apple 公证未通过: status=Invalid, submission=invalid-log-failure/,+ );++ assert.deepEqual(harness.deletedFiles, []);+ assert.equal(harness.execCommands.length, 1);+ const output = harness.output.join('\n');+ assert.match(output, /WARN: 无法获取 Apple notarization log/);+ assert.match(output, /log authentication failed: \*\*\*\*/);+ assert.doesNotMatch(output, new RegExp(IDENTITY.applePassword));+ harness.assertQueueDrained();+});diff --git a/scripts/__tests__/third-party-notices.test.mjs b/scripts/__tests__/third-party-notices.test.mjsindex 1693252018..2f5d1ecdcd 100644--- a/scripts/__tests__/third-party-notices.test.mjs+++ b/scripts/__tests__/third-party-notices.test.mjs@@ -40,10 +40,10 @@ test("generated artifact notices are platform-scoped and disclose restricted comassert.doesNotMatch(windows, /@img\/sharp-darwin-/);assert.match(windows, /SECTION \d+: cargo packages/);assert.match(windows, /Android SDK Platform-Tools/);- // 随包分发的 agent 二进制必须出现在全部三个桌面平台的开源声明里。+ // 安装包内资产和运行时受管下载的 agent 二进制,都必须出现在三个桌面平台声明里。for (const notice of [windows, macos, linux]) {- assert.match(notice, /OpenAI Codex CLI \(bundled binary\) \d/);- assert.match(notice, /pi coding agent \(bundled binary\) \d/);+ assert.match(notice, /OpenAI Codex CLI \(runtime-downloaded binary\) \d/);+ assert.match(notice, /pi coding agent \(runtime-downloaded binary\) \d/);assert.match(notice, /ripgrep \(bundled binary\) \d/);}assert.match(macos, /@img\/sharp-darwin-/);diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjsindex b1f4c2da18..8dfca14e74 100644--- a/scripts/generate-third-party-notices.mjs+++ b/scripts/generate-third-party-notices.mjs@@ -5,8 +5,9 @@* 生成全工程及桌面端分发产物的第三方开源声明文件 THIRD-PARTY-NOTICES.txt。** 范围:根目录及所有 pnpm workspace 包的生产依赖闭包(dependencies +- * optionalDependencies,递归;workspace 内部包只穿透不收录),外加随安装包- * 分发的非 npm 资产(ripgrep / Codex CLI / pi coding agent / Electron /+ * optionalDependencies,递归;workspace 内部包只穿透不收录),外加产品分发的+ * 非 npm 资产(安装包内的 ripgrep / Electron,以及运行时下载的 Codex CLI /+ * pi coding agent,另含* Android Platform-Tools / vendored 代码)的手工条目。** 输出(均应提交进仓库,但依赖范围不同):@@ -612,7 +613,7 @@ function readBundledLicense(relativePath) {}/**- * 桌面三平台共有的随包分发组件声明。+ * 桌面三平台共有的非 npm 分发组件声明(含安装包内资产与运行时受管下载资产)。** @param sharpPackageNames sharp 预编译包名,可传单个或数组。该包的 README 与* versions.json 是 per-arch 的(见下方 sharp 段),所以一个平台声明覆盖多个架构时@@ -635,10 +636,10 @@ function buildDesktopCommonEntries(apacheText, sharpPackageNames) {}),);- // OpenAI Codex CLI — 随包分发的 agent 二进制+ // OpenAI Codex CLI — 运行时从 CDN 下载到 userData,不进入安装包entries.push(bundledComponent({- name: "OpenAI Codex CLI (bundled binary)",+ name: "OpenAI Codex CLI (runtime-downloaded binary)",version: readToolVersion("codex"),license: "Apache-2.0",url: "https://github.com/openai/codex",@@ -649,10 +650,10 @@ function buildDesktopCommonEntries(apacheText, sharpPackageNames) {}),);- // pi coding agent — 随包分发的 agent 二进制(@earendil-works/pi-coding-agent)+ // pi coding agent — 运行时从 CDN 下载到 userData,不进入安装包entries.push(bundledComponent({- name: "pi coding agent (bundled binary)",+ name: "pi coding agent (runtime-downloaded binary)",version: readToolVersion("pi"),license: "MIT",url: "https://github.com/earendil-works/pi",@@ -932,7 +933,7 @@ function buildOutput({// —— Section 1: 非 npm 组件 ——push("=".repeat(78));- push("SECTION 1: Bundled components (non-npm)");+ push("SECTION 1: Non-npm components");push("=".repeat(78));for (const e of manualEntries) {const versionSuffix = `(${e.version})`;@@ -1229,7 +1230,7 @@ function auditArtifact(label, closure, manualEntries) {throw new Error(lines.join("\n"));}console.log(- `${label}: ${closure.packages.length} package dependencies + ${manualEntries.length} bundled components`,+ `${label}: ${closure.packages.length} package dependencies + ${manualEntries.length} non-npm components`,);}diff --git a/tools/shared/dir-dist-manifest.mjs b/tools/shared/dir-dist-manifest.mjsindex bf32ebf809..bfa385dc84 100644--- a/tools/shared/dir-dist-manifest.mjs+++ b/tools/shared/dir-dist-manifest.mjs@@ -86,7 +86,7 @@ export function verifyDirDistManifest(destDir) {}// 反向精确匹配:目录里不得有清单之外的条目。逐文件哈希只覆盖清单内条目,清单外的// 字节(旧构建残留 / 本地污染)完全不参与校验,却会被 ensure-agent-binaries 跳过刷新、- // 被 stagePi 原样打进安装包 —— 成为未验证资产(codex review P1)。故递归枚举实际集合,+ // 随后进入 CDN 目录归档 —— 成为未验证资产(codex review P1)。故递归枚举实际集合,// 要求与清单精确一致:多出普通文件、或出现任何 symlink/非普通文件(污染向量)即 false。const manifestPaths = new Set(files.map((entry) => entry.path));const actualPaths = [];