Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): lazify bundled ripgrep probe in runtime-configs (#1956) (#1989)
yan592051df5855
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 0552eb46d7..015e54d6af 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -404,6 +404,7 @@ import {waitForInitialCustomMcpRefresh,} from './maker-host/index.js';import { createDynamicMaker } from './maker-host/dynamic-maker.js';+import { ensureBundledRipgrepReady } from './maker-host/runtime-configs.js';import {ensureActiveCatalogLoaded,refreshCustomProvidersIntoCatalog,@@ -4359,6 +4360,29 @@ const registerIpcHandlers = () => {};}+ // ── Phase 2.5: bundled ripgrep(必需,codex spawn env 与 file-browser 搜索的+ // 硬依赖)──────────────────────────────────────────────────────────────+ // 探测已惰性化(import 不再触发,issue #1956),启动期 fail-fast 落在 splash+ // 这里:缺失时与 claude/codex binary 缺失同一体验(splash failed + 可重试,+ // dev 补跑 pnpm install:ripgrep 后重试即过),而不是 import 期硬崩、也不是+ // maker:* IPC 静默不注册的降级启动。memoize 后此处探测近零成本。+ try {+ ensureBundledRipgrepReady();+ } catch (err: unknown) {+ const message = err instanceof Error ? err.message : String(err);+ // splash 失败态 UI 不渲染 error 字段,这行日志是缺 rg 时唯一的诊断出口+ // (补装指引在 message 里);与下方 pi 失败的 console.warn 同一既有惯例。+ console.error('[bootstrap-electron] bundled ripgrep check failed:', message);+ return {+ claudeCode: { status: 'passed' as const, path: claudeRes.path },+ codex: { status: 'passed' as const, path: codexRes.path },+ pi: { status: 'skipped' as const },+ ripgrep: { status: 'failed' as const, error: message },+ allPassed: false,+ platform,+ };+ }+// ── Phase 3: pi 段(可选,失败不阻塞启动)──────────────────────────────────// broadcastFailure: false —— pi 下载失败不能把 splash 打进失败态;静默禁用// 本次 pi 注册,Claude Code / Codex 与 Cindy 本身仍照常可用。@@ -4406,6 +4430,7 @@ const registerIpcHandlers = () => {claudeCode: { status: 'passed' as const, path: claudeRes.path },codex: { status: 'passed' as const, path: codexRes.path },pi: piInfo,+ ripgrep: { status: 'passed' as const },allPassed: true,platform,};diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.tsindex 801217453f..b8fd38eb66 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts@@ -28,10 +28,8 @@ const h = vi.hoisted(() => ({vi.mock('electron', () => ({app: {getPath: () => '/tmp/xdt-test-userdata-nonexistent',- getAppPath: () => '/tmp/xdt-test-userdata-nonexistent',- // isPackaged=false:runtime-configs 模块级的 bundledRipgrepDir 在 packaged 分支- // 依赖 process.resourcesPath(测试进程为 undefined,直接抛)——走 dev 分支绕开。- isPackaged: false,+ // ripgrep 探测已惰性化(issue #1956):runtime-configs import 期不再读+ // getAppPath / isPackaged,这里无需再补。},safeStorage: { isEncryptionAvailable: () => h.encryptionAvailable },}));diff --git a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigsRipgrep.test.ts b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigsRipgrep.test.tsnew file mode 100644index 0000000000..43929a4439--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigsRipgrep.test.ts@@ -0,0 +1,121 @@+/**+ * runtimeConfigsRipgrep.test.ts —— issue #1956 回归守卫:+ * runtime-configs 的 bundled ripgrep 探测必须**惰性化**。+ *+ * 固化三条契约:+ * 1. import 零探测:electron mock 故意不提供 getAppPath / isPackaged,+ * import runtime-configs 不得炸(纯 node / vitest 收集期安全)。+ * 2. 惰性 fail-fast:pathPrepends / getRipgrepBinaryPath /+ * ensureBundledRipgrepReady 在 rg 缺失时**访问才** throw,且失败不缓存+ * (补装 rg 后同进程重试即可成功)。+ * 3. 成功结果 memoize:pathPrepends 每次 codex spawn 都读、+ * getRipgrepBinaryPath 每次 file-browser 搜索都调,命中后不得重复 fs 探测。+ */+import path from 'node:path';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ existsSync: vi.fn<(p: string) => boolean>(() => false),+ chmodSync: vi.fn(),+ getAppPath: vi.fn(() => '/xdt-lazy-rg/app'),+}));++function mockElectronApp(app: Record<string, unknown>): void {+ vi.doMock('electron', () => ({ app }));+}++function mockFsProbe(): void {+ vi.doMock('node:fs', async () => {+ const actual = await vi.importActual<typeof import('node:fs')>('node:fs');+ return {+ ...actual,+ existsSync: h.existsSync,+ chmodSync: h.chmodSync,+ default: { ...actual, existsSync: h.existsSync, chmodSync: h.chmodSync },+ };+ });+}++// 同 runtimeConfigs.test.ts:剪断 model-access 凭证链的文件 IO,本测试不断言 endpoint。+function mockEffectiveEndpoint(): void {+ vi.doMock('../../model-access/effectiveEndpoint.js', () => ({+ effectiveXdGatewayBaseUrl: () => 'http://127.0.0.1:0',+ }));+}++const platformKey = `${process.platform}-${process.arch}`;+const rgBinaryName = process.platform === 'win32' ? 'rg.exe' : 'rg';+// dev 分支第一个候选:与 runtime-configs 内 path.join 同式构造(宿主路径断言走 path API)。+const expectedDevDir = path.join('/xdt-lazy-rg/app', '..', '..', 'apps', 'ripgrep-bin', platformKey);++beforeEach(() => {+ vi.resetModules();+ h.existsSync.mockClear().mockReturnValue(false);+ h.chmodSync.mockClear();+ h.getAppPath.mockClear();+});++describe('runtime-configs bundled ripgrep laziness (#1956)', () => {+ it('import 不探测 ripgrep:electron mock 无 getAppPath / isPackaged 也能加载', async () => {+ // 只有 getPath:desktopCodexRuntimeConfig.userDataPath 仍在模块期读 userData。+ // getAppPath / isPackaged 缺席 —— 若模块顶层恢复探测,这里收集期即 TypeError。+ mockElectronApp({ getPath: () => '/xdt-lazy-rg/user-data' });+ mockFsProbe();+ mockEffectiveEndpoint();++ const mod = await import('../runtime-configs.js');++ expect(mod.desktopCodexRuntimeConfig.userDataPath).toBe('/xdt-lazy-rg/user-data');+ expect(typeof mod.getRipgrepBinaryPath).toBe('function');+ expect(typeof mod.ensureBundledRipgrepReady).toBe('function');+ expect(h.existsSync).not.toHaveBeenCalled();+ });++ it('pathPrepends 访问期才探测:rg 缺失时 throw,且失败不缓存可重试', async () => {+ mockElectronApp({+ getPath: () => '/xdt-lazy-rg/user-data',+ getAppPath: h.getAppPath,+ isPackaged: false,+ });+ mockFsProbe();+ mockEffectiveEndpoint();++ const { desktopCodexRuntimeConfig, ensureBundledRipgrepReady } = await import(+ '../runtime-configs.js'+ );+ // import 期零探测:getAppPath 与 fs 都不该被碰过。+ expect(h.getAppPath).not.toHaveBeenCalled();+ expect(h.existsSync).not.toHaveBeenCalled();++ expect(() => desktopCodexRuntimeConfig.pathPrepends).toThrow(/Bundled ripgrep not found/u);+ expect(() => ensureBundledRipgrepReady()).toThrow(/Bundled ripgrep not found/u);++ // 失败不缓存:补装 rg(existsSync 转 true)后同进程重试即成功。+ h.existsSync.mockReturnValue(true);+ expect(desktopCodexRuntimeConfig.pathPrepends).toEqual([expectedDevDir]);+ });++ it('探测成功后 memoize:重复访问 pathPrepends / getRipgrepBinaryPath 不再打 fs', async () => {+ mockElectronApp({+ getPath: () => '/xdt-lazy-rg/user-data',+ getAppPath: h.getAppPath,+ isPackaged: false,+ });+ mockFsProbe();+ mockEffectiveEndpoint();+ h.existsSync.mockReturnValue(true);++ const { desktopCodexRuntimeConfig, getRipgrepBinaryPath, ensureBundledRipgrepReady } =+ await import('../runtime-configs.js');++ expect(desktopCodexRuntimeConfig.pathPrepends).toEqual([expectedDevDir]);+ const probeCallsAfterHit = h.existsSync.mock.calls.length;+ expect(probeCallsAfterHit).toBeGreaterThan(0);++ // 此后所有访问路径(spawn env、file-browser 搜索、启动期预热)都只吃缓存。+ desktopCodexRuntimeConfig.pathPrepends;+ ensureBundledRipgrepReady();+ expect(getRipgrepBinaryPath()).toBe(path.join(expectedDevDir, rgBinaryName));+ expect(h.existsSync.mock.calls.length).toBe(probeCallsAfterHit);+ });+});diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 10f5306b68..959740cf35 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -101,6 +101,7 @@ import {import {buildDesktopClaudeRuntimeConfig,desktopCodexRuntimeConfig,+ ensureBundledRipgrepReady,} from './runtime-configs.js';import { getClaudeEndpoint, setClaudeProxyGatewayKeyReader, setClaudeProxyOAuthSpawnChecker } from './anthropic-compat-proxy-host.js';import { resolveRemoteClaudeRoute } from './remote-claude-route.js';@@ -598,6 +599,12 @@ export function getMaker(): Maker {if (!codexPath) {throw new Error('getMaker: Codex binary not provisioned (bootstrap must run agent-binaries.prepare("codex") before getMaker)');}+ // bundled ripgrep 检查与上面 claude/codex 二进制同层:真正的启动期 fail-fast+ // 在 splash check-environment(Phase 2.5,缺 rg 时 splash 进失败态可重试);+ // 这里是防御性断言 —— 走到本函数说明 bootstrap 已完成环境检查,缺 rg 即顺序+ // 错误,早抛比 spawn 时再炸清晰(throw 会被 bootstrap 的 register catch 兜住+ // 并留 ERROR 日志,与 claude/codex 缺失的处理一致)。+ ensureBundledRipgrepReady();// 图片送进模型前的 last-mile resize (省 vision token)。host 注入 logger// 让 sharp 失败 / 超时 / LRU 淘汰等告警进项目日志, 而不是默默丢黑洞。diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.tsindex 104ae67196..7f3573140a 100644--- a/apps/desktop/src/main/maker-host/runtime-configs.ts+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts@@ -42,7 +42,18 @@ function ripgrepBinaryName(): string {return process.platform === 'win32' ? 'rg.exe' : 'rg';}+// 探测结果 memoize:pathPrepends getter 每次 codex spawn 都会读、getRipgrepBinaryPath+// 被 file-browser / pi-host 每次搜索调用,不能每次都重打 fs 探测 + chmod。+// 只缓存成功结果 —— 探测失败的 throw 不缓存,下次调用重新探测(dev 期补装 rg 后+// 不必纠结缓存住了失败态)。+let cachedBundledRipgrepDir: string | undefined;++// 不在模块顶层调用(issue #1956):本函数在 dev/测试分支依赖 app.getAppPath(),+// 顶层求值会让任何 import 链摸到本模块的纯 node / vitest 环境在收集阶段就炸。+// 调用点:desktopCodexRuntimeConfig.pathPrepends 的 lazy getter、+// getRipgrepBinaryPath(),以及启动期 fail-fast 的 ensureBundledRipgrepReady()。function bundledRipgrepDir(): string {+ if (cachedBundledRipgrepDir) return cachedBundledRipgrepDir;const key = platformKey();const file = ripgrepBinaryName();const candidates = app.isPackaged@@ -59,11 +70,12 @@ function bundledRipgrepDir(): string {if (process.platform !== 'win32') {try { fs.chmodSync(bin, 0o755); } catch { /* ignore */ }}+ cachedBundledRipgrepDir = dir;return dir;}throw new Error(- `Bundled ripgrep not found for ${key}. Run "pnpm update:ripgrep" before starting desktop dev or packaging.`,+ `Bundled ripgrep not found for ${key}. Run "pnpm install:ripgrep" before starting desktop dev or packaging.`,);}@@ -76,6 +88,19 @@ export function getRipgrepBinaryPath(): string {return path.join(bundledRipgrepDir(), ripgrepBinaryName());}+/**+ * 启动期 fail-fast 预热(issue #1956):import 本模块不再探测 ripgrep(见+ * desktopCodexRuntimeConfig.pathPrepends 的 lazy getter),缺 rg 的显式失败由+ * 两个启动期调用点承担 —— bootstrap 的 splash check-environment(Phase 2.5,+ * 缺失时 splash 进失败态可重试,与 claude/codex binary 缺失同一体验)和+ * getMaker() 首次构造(防御性断言,与那里的 claude/codex 检查同层)。+ * dev 忘跑 "pnpm install:ripgrep" 会在 splash 即失败;生产打包缺资源同样+ * 在启动期暴露,语义不变。+ */+export function ensureBundledRipgrepReady(): void {+ bundledRipgrepDir();+}+// memorySettings 在 main 启动期已 ready (userData 同步可访问)。// 原生 auto-memory 与 Maker Memory 都从持久化 store 读, 重启后用户上次设置 100% 恢复。// 默认值由 memory-settings-store.ts 维护 (maker=false / claudeCode=true / codex=true)。@@ -239,7 +264,13 @@ export const desktopCodexRuntimeConfig: AgentRuntimeConfig = {behaviorFlags: (ctx) => (ctx.spawnMode === 'remote' ? {} : toolchainThreadCapEnv()),// 产品身份 + Skill 来源优先级 + Codex 专属段。systemPrompt: composeHostPrompt(codexSystemPrompt),- pathPrepends: [bundledRipgrepDir()],+ // lazy getter(与 endpoint/memoryEnabled 同一惯用法,issue #1956):import 期+ // 不探测 bundled ripgrep,纯 node / vitest 环境 import 本模块不再炸;真正的+ // fail-fast 由 maker-host 启动期的 ensureBundledRipgrepReady() 承担,此处 getter+ // 在 env-builder 每次 codex spawn 时求值(结果已 memoize)。+ get pathPrepends() {+ return [bundledRipgrepDir()];+ },userDataPath: app.getPath('userData'),get memoryEnabled() {return readMemorySettings().codex;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.tsindex 7d6e46b464..6ea69d4143 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.ts@@ -33,13 +33,10 @@ vi.mock('electron', () => ({ipcMain: { handle: vi.fn() },BrowserWindow: { getAllWindows: h.getAllWindows },// 停用轴接线让本测试的 import 链带上 model-disable-store / auth-adapters →- // runtime-configs:模块加载期会读 app.getPath 并跑 bundledRipgrepDir 探测- // (getAppPath + isPackaged;dev 探测最终命中 cwd()/../ripgrep-bin)。补齐这- // 三个成员避免 collect 失败。+ // runtime-configs:模块加载期会读 app.getPath('userData')(userDataPath 字段)。+ // ripgrep 探测已惰性化(issue #1956),import 不再需要 getAppPath / isPackaged。app: {getPath: vi.fn(() => '/tmp/cindy-test-user-data'),- getAppPath: vi.fn(() => '/tmp/cindy-test-app'),- isPackaged: false,},}));diff --git a/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx b/apps/desktop/src/renderer/contexts/EnvCheckContext.tsxindex 89e405772a..897b9a5b87 100644--- a/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx+++ b/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx@@ -344,7 +344,11 @@ export function EnvCheckProvider({ children }: { children: ReactNode }) {try {const res = await window.electronAPI.checkEnvironment();setResult(res);- setStatus('passed');+ // claude/codex 缺失在 dev 维持既有放行(注释见上:dev 跑检查只为让+ // 路径就绪);但 bundled ripgrep 缺失不能放行 —— #1956 的启动期+ // fail-fast 在 dev 同样要成立,否则 dev 缺 rg 会被这里的无条件+ // passed 吞掉,直到首次 codex spawn / 文件搜索才炸。+ setStatus(res.ripgrep?.status === 'failed' ? 'failed' : 'passed');} catch {setStatus('passed');}diff --git a/apps/desktop/src/renderer/contexts/__tests__/EnvCheckContext.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/EnvCheckContext.test.tsxindex a3a5c0fffe..d398e22b4f 100644--- a/apps/desktop/src/renderer/contexts/__tests__/EnvCheckContext.test.tsx+++ b/apps/desktop/src/renderer/contexts/__tests__/EnvCheckContext.test.tsx@@ -81,6 +81,38 @@ async function mountAndKick() {const flush = () => act(async () => {});+describe('EnvCheckContext dev 短路径的 ripgrep fail-fast (#1956)', () => {+ // vitest 下 import.meta.env.DEV === true,mount 的 auto-check 走 dev 短路径,+ // 只消费 envCheckCalls[0]。+ it('dev:ripgrep failed 进 failed 态,不被 dev 的无条件放行吞掉', async () => {+ const view = renderHook(() => useEnvCheck(), { wrapper });+ await waitFor(() => expect(envCheckCalls.length).toBe(1));++ await act(async () => {+ envCheckCalls[0].resolve({+ allPassed: false,+ ripgrep: { status: 'failed', error: 'Bundled ripgrep not found' },+ });+ });++ await waitFor(() => expect(view.result.current.status).toBe('failed'));+ });++ it('dev:claude/codex 缺失维持既有放行(只有 ripgrep 失败才拦)', async () => {+ const view = renderHook(() => useEnvCheck(), { wrapper });+ await waitFor(() => expect(envCheckCalls.length).toBe(1));++ await act(async () => {+ envCheckCalls[0].resolve({+ allPassed: false,+ claudeCode: { status: 'failed', error: 'no claude binary' },+ });+ });++ await waitFor(() => expect(view.result.current.status).toBe('passed'));+ });+});+describe('EnvCheckContext 启动下载进度时序', () => {it('热更先下(常态):Phase 2 在途期间热更进度直接驱动 splash,二进制接管时归零', async () => {const { result } = await mountAndKick();diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 44e76f8983..6e63f6fff7 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -59,6 +59,8 @@ interface EnvCheckResult {codex: { status: 'passed' | 'failed' | 'skipped'; path?: string; error?: string };/** pi 可选实验 agent:failed 不影响 allPassed;本次启动会禁用 pi。 */pi?: { status: 'passed' | 'failed' | 'skipped'; path?: string; error?: string };+ /** bundled ripgrep(必需):failed 时 allPassed=false,splash 进失败态可重试 (#1956)。 */+ ripgrep?: { status: 'passed' | 'failed' | 'skipped'; error?: string };allPassed: boolean;platform: 'darwin' | 'win32' | 'linux';}