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。

fix(file-browser): reject on ripgrep fatal exit instead of returning empty results (#3141)

Battleplus87bf4418fd60
diff --git a/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts b/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts
new file mode 100644
index 0000000000..3592f60d06
--- /dev/null
+++ b/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts
@@ -0,0 +1,225 @@
+/**
+ * ripgrep 退出码处理回归测试。
+ *
+ * 覆盖:
+ * - listAllFiles 在 rg 致命退出(非零 exit)时应 reject
+ * - RipgrepSearcher 在 rg 退出码 2 时应 emit type:'error'
+ * - 退出码 1(无匹配)在 RipgrepSearcher 中仍应正常 end
+ *
+ * 使用 vi.mock 模拟 child_process.spawn,避免跨平台可执行文件问题。
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+import type { ChildProcessWithoutNullStreams } from 'node:child_process';
+
+/* ------------------------------------------------------------------ */
+/* Mock child_process.spawn */
+/* ------------------------------------------------------------------ */
+
+type SpawnHandler = (
+ command: string,
+ args?: readonly string[],
+ options?: Record<string, unknown>,
+) => ChildProcessWithoutNullStreams;
+
+let spawnHandler: SpawnHandler = () => {
+ throw new Error('spawnHandler not set');
+};
+
+vi.mock('node:child_process', () => ({
+ spawn: (...args: Parameters<SpawnHandler>) => spawnHandler(...args),
+}));
+
+function createFakeChild(exitCode: number, stdoutLines: string[] = []): ChildProcessWithoutNullStreams {
+ const child = new EventEmitter() as ChildProcessWithoutNullStreams;
+ const stdout = new PassThrough();
+ (child as any).stdout = stdout;
+ (child as any).stderr = new PassThrough();
+ (child as any).killed = false;
+ (child as any).exitCode = null;
+
+ // Simulate async process lifecycle: write lines, then close stdout, then emit close
+ let ended = false;
+ process.nextTick(() => {
+ if (ended) return;
+ for (const line of stdoutLines) {
+ if (ended) break;
+ stdout.write(line + '\n');
+ }
+ if (!ended) {
+ ended = true;
+ stdout.end();
+ }
+ (child as any).exitCode = exitCode;
+ child.emit('close', exitCode, null);
+ });
+
+ child.kill = vi.fn(() => {
+ (child as any).killed = true;
+ if (!ended) {
+ ended = true;
+ stdout.end();
+ }
+ return true;
+ }) as any;
+
+ return child;
+}
+
+/* ------------------------------------------------------------------ */
+/* listAllFiles tests */
+/* ------------------------------------------------------------------ */
+
+describe('listAllFiles error handling', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('rejects when rg exits with non-zero code', async () => {
+ spawnHandler = () => createFakeChild(2);
+
+ const { listAllFiles } = await import('../listAllFiles.js');
+ await expect(
+ listAllFiles({ rgPath: '/fake/rg', workdir: '/tmp/work' }),
+ ).rejects.toThrow(/ripgrep exited with code 2/);
+ });
+
+ it('resolves when rg exits with code 0', async () => {
+ spawnHandler = () => createFakeChild(0, ['file1.ts', 'file2.js']);
+
+ const { listAllFiles } = await import('../listAllFiles.js');
+ const result = await listAllFiles({ rgPath: '/fake/rg', workdir: '/tmp/work' });
+ expect(result.truncated).toBe(false);
+ expect(result.files).toEqual(['file1.ts', 'file2.js']);
+ });
+
+ it('resolves when truncated (rg killed by us, exit code non-zero is OK)', async () => {
+ // When we kill rg after cap, it exits non-zero — should still resolve
+ spawnHandler = () => createFakeChild(1, ['a.ts', 'b.ts']);
+
+ const { listAllFiles } = await import('../listAllFiles.js');
+ const result = await listAllFiles({ rgPath: '/fake/rg', workdir: '/tmp/work', cap: 1 });
+ expect(result.files.length).toBe(1);
+ expect(result.truncated).toBe(true);
+ });
+});
+
+/* ------------------------------------------------------------------ */
+/* RipgrepSearcher tests */
+/* ------------------------------------------------------------------ */
+
+describe('RipgrepSearcher fatal exit handling', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ function makeLogger() {
+ return {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ }
+
+ async function importSearcher() {
+ const mod = await import('../search/RipgrepSearcher.js');
+ return mod.RipgrepSearcher;
+ }
+
+ function waitForSearch(
+ searcher: InstanceType<ReturnType<typeof importSearcher>> extends Promise<infer P> ? P : never,
+ searchId: string,
+ ): Promise<void> {
+ return new Promise<void>((resolve) => {
+ const handler = (ev: any) => {
+ if (ev.searchId === searchId && (ev.type === 'end' || ev.type === 'error')) {
+ searcher.removeListener('event', handler);
+ resolve();
+ }
+ };
+ searcher.on('event', handler);
+ });
+ }
+
+ it('emits type:error when rg exits with code 2', async () => {
+ spawnHandler = () => createFakeChild(2);
+
+ const RipgrepSearcher = await importSearcher();
+ const logger = makeLogger();
+ const searcher = new RipgrepSearcher({ rgPath: '/fake/rg', logger });
+
+ const events: unknown[] = [];
+ searcher.on('event', (ev) => events.push(ev));
+
+ const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work' });
+ await waitForSearch(searcher, searchId);
+
+ const errorEvents = events.filter(
+ (e: any) => e.type === 'error' && e.searchId === searchId,
+ );
+ expect(errorEvents.length).toBe(1);
+ expect((errorEvents[0] as any).message).toMatch(/fatal error/);
+
+ const endEvents = events.filter(
+ (e: any) => e.type === 'end' && e.searchId === searchId,
+ );
+ expect(endEvents.length).toBe(0);
+ });
+
+ it('emits type:end when rg exits with code 1 (no matches)', async () => {
+ spawnHandler = () => createFakeChild(1);
+
+ const RipgrepSearcher = await importSearcher();
+ const logger = makeLogger();
+ const searcher = new RipgrepSearcher({ rgPath: '/fake/rg', logger });
+
+ const events: unknown[] = [];
+ searcher.on('event', (ev) => events.push(ev));
+
+ const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work' });
+ await waitForSearch(searcher, searchId);
+
+ const errorEvents = events.filter(
+ (e: any) => e.type === 'error' && e.searchId === searchId,
+ );
+ expect(errorEvents.length).toBe(0);
+
+ const endEvents = events.filter(
+ (e: any) => e.type === 'end' && e.searchId === searchId,
+ );
+ expect(endEvents.length).toBe(1);
+ expect((endEvents[0] as any).truncated).toBe(false);
+ });
+
+ it('emits type:end when rg exits with code 0', async () => {
+ spawnHandler = () =>
+ createFakeChild(0, [
+ JSON.stringify({ type: 'match', data: { path: { text: 'a.ts' }, lines: { text: 'needle' }, line_number: 1, submatches: [] } }),
+ JSON.stringify({ type: 'summary', data: { stats: { matches: 1 }, elapsed_total: { human: '0.01s' } } }),
+ ]);
+
+ const RipgrepSearcher = await importSearcher();
+ const logger = makeLogger();
+ const searcher = new RipgrepSearcher({ rgPath: '/fake/rg', logger });
+
+ const events: unknown[] = [];
+ searcher.on('event', (ev) => events.push(ev));
+
+ const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work' });
+ await waitForSearch(searcher, searchId);
+
+ const errorEvents = events.filter(
+ (e: any) => e.type === 'error' && e.searchId === searchId,
+ );
+ expect(errorEvents.length).toBe(0);
+
+ const endEvents = events.filter(
+ (e: any) => e.type === 'end' && e.searchId === searchId,
+ );
+ expect(endEvents.length).toBe(1);
+ expect((endEvents[0] as any).totalMatches).toBe(1);
+ });
+});
diff --git a/packages/file-browser-core/src/listAllFiles.ts b/packages/file-browser-core/src/listAllFiles.ts
index dc35cadba0..35c39606e8 100644
--- a/packages/file-browser-core/src/listAllFiles.ts
+++ b/packages/file-browser-core/src/listAllFiles.ts
@@ -130,10 +130,21 @@ export function listAllFiles(args: ListAllFilesArgs): Promise<ListAllFilesResult
reader.close();
const elapsedMs = Date.now() - start;
// truncated 时 rg 因被我们 SIGTERM 退出,code/signal 不一定 0 — 仍当 success。
- if (!truncated && code !== 0 && code !== null) {
- // rg exit code 1 = no matches(--files 模式下不会出现);其它非零是真错。
- // 但 --files 即使工作目录空也是 exit 0,所以非 0 必然异常。
- log.warn('rg exited non-zero', { code, signal, elapsedMs, files: files.length });
+ // signal 非空 = 被 OOM killer / SIGKILL 等意外终止(code 为 null)。
+ if (!truncated && signal !== null) {
+ log.warn('rg killed by signal', { signal, elapsedMs, files: files.length });
+ reject(new Error(`ripgrep killed by signal ${signal}`));
+ return;
+ }
+ // exit code 1 = no matches (--files 模式下空目录/全部被忽略);>= 2 = 致命错误。
+ if (!truncated && code !== null && code >= 2) {
+ log.warn('rg exited with fatal error', { code, signal, elapsedMs, files: files.length });
+ reject(new Error(`ripgrep exited with code ${code}${signal ? ` (signal: ${signal})` : ''}`));
+ return;
+ }
+ if (!truncated && code === 1) {
+ // exit 1 = 空目录或全部被 .gitignore 排除;合法的空清单。
+ log.debug('rg exited 1 (no files)', { elapsedMs });
}
log.debug('rg done', { workdir: args.workdir, files: files.length, truncated, elapsedMs });
resolve({ files, truncated, elapsedMs });
diff --git a/packages/file-browser-core/src/search/RipgrepSearcher.ts b/packages/file-browser-core/src/search/RipgrepSearcher.ts
index cc6b6c9f6f..acecfe3bb6 100644
--- a/packages/file-browser-core/src/search/RipgrepSearcher.ts
+++ b/packages/file-browser-core/src/search/RipgrepSearcher.ts
@@ -230,7 +230,18 @@ export class RipgrepSearcher extends EventEmitter {
child.on('close', (code, signal) => {
if (state.ended) return;
// rg 退出码: 0 = 有命中, 1 = 无命中, 2 = 致命错误。
- if (code !== 0 && code !== 1 && signal === null) {
+ // signal 非空 = 被 OOM killer / SIGKILL 等意外终止(此时 code 为 null)。
+ if (signal !== null) {
+ this.log.warn('rg killed by signal', { searchId, signal });
+ this.emitError(searchId, `ripgrep killed by signal ${signal}`);
+ return;
+ }
+ if (code === 2) {
+ this.log.warn('rg exited with fatal error', { searchId, code });
+ this.emitError(searchId, `ripgrep exited with fatal error (code ${code})`);
+ return;
+ }
+ if (code !== 0 && code !== 1) {
this.log.warn('rg exited non-zero', { searchId, code });
}
this.finalize(searchId, false);
@@ -253,6 +264,21 @@ export class RipgrepSearcher extends EventEmitter {
for (const id of Array.from(this.active.keys())) this.cancel(id);
}
+ /** Emit an error event and clean up the search state. */
+ private emitError(searchId: string, message: string): void {
+ const state = this.active.get(searchId);
+ if (!state || state.ended) return;
+ state.ended = true;
+ try { state.reader.close(); } catch { /* ignore */ }
+ this.killChild(state.child);
+ this.active.delete(searchId);
+ this.emit('event', {
+ type: 'error',
+ searchId,
+ message,
+ } satisfies SearchEvent);
+ }
+
private finalize(searchId: string, truncated: boolean): void {
const state = this.active.get(searchId);
if (!state || state.ended) return;