π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(local-file-shell): stop Windows grepContent from returning false zero matches (#19980)
Arvin Xueb4c2245e5df
diff --git a/packages/local-file-shell/src/contentSearch/__tests__/windowsFindstrArgv.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/windowsFindstrArgv.test.tsnew file mode 100644index 00000000000..c52c134e683--- /dev/null+++ b/packages/local-file-shell/src/contentSearch/__tests__/windowsFindstrArgv.test.ts@@ -0,0 +1,164 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { beforeEach, describe, expect, it, vi } from 'vitest';++const execaMock = vi.hoisted(() => vi.fn());+vi.mock('execa', () => ({ execa: execaMock }));+const { WindowsContentSearchImpl } = await import('../impl/windows');++/**+ * Windows machines without `rg` used to fall to a findstr engine that ran+ * `cmd /c findstr /R "<pattern>" *.*`. libuv escapes the embedded quotes to+ * `\"`, cmd.exe strips only the outer pair, and findstr then searched for the+ * literal `"<pattern>"` β so almost every call answered "Found 0 matches".+ * findstr also has no `|`, `\d`, UTF-8 CJK or glob support, so the fix drops it:+ * without `rg`, Windows searches with the Node engine.+ */+describe('Windows grepContent without rg', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grep-win-repro-'));+ const file = path.join(dir, 'colour-grid.php');+ fs.writeFileSync(file, '$img = mvx_image($id);\n// ηΉε¨ a\n');+ fs.writeFileSync(path.join(dir, 'notes.txt'), 'image of a cat\n');++ beforeEach(() => {+ execaMock.mockReset();+ execaMock.mockImplementation(async (cmd: string) => {+ if (cmd === 'where') throw new Error('INFO: Could not find files for the given pattern(s).');+ // Any other spawn (the old findstr path) answers "no output", like the+ // quoted findstr did on real Windows.+ return { exitCode: 1, stderr: '', stdout: '' };+ });+ });++ const spawnedCmd = () => execaMock.mock.calls.some(([cmd]) => cmd === 'cmd');++ it('finds a plain pattern instead of the quoted literal', async () => {+ const result = await new WindowsContentSearchImpl().grep({+ output_mode: 'count',+ pattern: 'a',+ scope: dir,+ });++ expect(spawnedCmd()).toBe(false);+ expect(result.success).toBe(true);+ expect(result.total_matches).toBeGreaterThan(0);+ });++ it('honours glob instead of searching *.*', async () => {+ const result = await new WindowsContentSearchImpl().grep({+ glob: '*.php',+ output_mode: 'files_with_matches',+ pattern: 'image',+ scope: dir,+ });++ expect(result.matches.map((m) => path.basename(m))).toEqual(['colour-grid.php']);+ });++ it('supports alternation and CJK patterns', async () => {+ const result = await new WindowsContentSearchImpl().grep({+ output_mode: 'content',+ pattern: 'nothing-here|ηΉε¨',+ scope: dir,+ });++ expect(result.total_matches).toBe(1);+ expect(result.matches[0]).toContain('ηΉε¨');+ });++ it('searches a file scope', async () => {+ const result = await new WindowsContentSearchImpl().grep({+ output_mode: 'content',+ path: file,+ pattern: 'image',+ });++ expect(result.total_matches).toBe(1);+ expect(result.matches[0]).toContain('mvx_image');+ });++ it('reports an invalid pattern instead of rejecting', async () => {+ const result = await new WindowsContentSearchImpl().grep({+ output_mode: 'content',+ pattern: '(',+ scope: dir,+ });++ expect(result.success).toBe(false);+ expect(result.error).toContain('Invalid regular expression');+ });+});++describe('Windows grepContent with rg', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grep-win-rg-'));+ const file = path.join(dir, 'colour-grid.php');+ fs.writeFileSync(file, '$img = mvx_image($id);\n');++ const rgCall = () => execaMock.mock.calls.find(([cmd]) => cmd === 'rg')!;++ beforeEach(() => {+ execaMock.mockReset();+ execaMock.mockImplementation(async (cmd: string) => {+ if (cmd === 'where') return { exitCode: 0, stderr: '', stdout: 'C:\\bin\\rg.exe' };+ return { exitCode: 0, stderr: '', stdout: './colour-grid.php:$img = mvx_image($id);' };+ });+ });++ it('passes pattern and glob to rg as separate, unquoted argv', async () => {+ await new WindowsContentSearchImpl().grep({+ glob: '*.php',+ output_mode: 'content',+ pattern: 'image',+ scope: dir,+ });++ const [, args] = rgCall();+ expect(args).toContain('image');+ expect(args.join(' ')).toContain('-g *.php');+ });++ it('searches a file scope from its directory, not with cwd=<file>', async () => {+ await new WindowsContentSearchImpl().grep({+ output_mode: 'content',+ path: file,+ pattern: 'image',+ });++ const [, args, options] = rgCall();+ expect(fs.statSync(options.cwd).isDirectory()).toBe(true);+ expect(args.at(-1)).toBe('./colour-grid.php');+ });++ it('reports an rg failure instead of zero matches', async () => {+ execaMock.mockImplementation(async (cmd: string) => {+ if (cmd === 'where') return { exitCode: 0, stderr: '', stdout: 'C:\\bin\\rg.exe' };+ return { exitCode: 2, stderr: 'regex parse error: unclosed group', stdout: '' };+ });++ const result = await new WindowsContentSearchImpl().grep({+ output_mode: 'content',+ pattern: '(',+ scope: dir,+ });++ expect(result.success).toBe(false);+ expect(result.error).toContain('regex parse error');+ });++ it('falls back to a real search when the rg binary fails to spawn', async () => {+ execaMock.mockImplementation(async (cmd: string) => {+ if (cmd === 'where') return { exitCode: 0, stderr: '', stdout: 'C:\\bin\\rg.exe' };+ // execa with `reject: false` resolves a spawn failure: no exit code.+ return { code: 'ENOENT', exitCode: undefined, failed: true, stderr: '', stdout: '' };+ });++ const result = await new WindowsContentSearchImpl({+ getBestTool: async () => 'rg',+ }).grep({ output_mode: 'content', pattern: 'image', scope: dir });++ expect(result.engine).toBe('nodejs');+ expect(result.total_matches).toBe(1);+ });+});diff --git a/packages/local-file-shell/src/contentSearch/__tests__/windowsSilentZero.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/windowsSilentZero.test.tsnew file mode 100644index 00000000000..01372c0c0d2--- /dev/null+++ b/packages/local-file-shell/src/contentSearch/__tests__/windowsSilentZero.test.ts@@ -0,0 +1,38 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++import { MacOSContentSearchImpl } from '../impl/macOS';+import { WindowsContentSearchImpl } from '../impl/windows';++/**+ * Runs the real Windows impl (real execa) on a non-Windows host, where neither+ * `where` nor `cmd` exists: the engine it would spawn is missing. That failure+ * used to resolve (execa `reject: false`) and come back as+ * `{ success: true, total_matches: 0 }` β indistinguishable from "no match".+ */+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grep-win-silent-'));+const file = path.join(dir, 'SFSD_HMI_Demo_v3.html');+fs.writeFileSync(file, '<script>function gateLogin(){}</script>\n<p>ηΉε¨</p>\n');++describe('WindowsContentSearchImpl does not swallow a missing engine', () => {+ it('control: macOS impl finds gateLogin in the same file', async () => {+ const r = await new MacOSContentSearchImpl().grep({+ output_mode: 'content',+ path: file,+ pattern: 'gateLogin',+ });+ expect(r.total_matches).toBe(1);+ });++ it('engine unavailable β must not be reported as 0 matches', async () => {+ const r = await new WindowsContentSearchImpl().grep({+ output_mode: 'content',+ pattern: 'gateLogin',+ scope: dir,+ });+ expect(r.success === false || r.total_matches > 0).toBe(true);+ });+});diff --git a/packages/local-file-shell/src/contentSearch/base.ts b/packages/local-file-shell/src/contentSearch/base.tsindex ec6dc0866c5..98d000151f3 100644--- a/packages/local-file-shell/src/contentSearch/base.ts+++ b/packages/local-file-shell/src/contentSearch/base.ts@@ -1,4 +1,5 @@import { readFile, stat } from 'node:fs/promises';+import path from 'node:path';import fg from 'fast-glob';@@ -98,6 +99,19 @@ export abstract class BaseContentSearch {};}+ protected async isFile(target: string): Promise<boolean> {+ try {+ return (await stat(target)).isFile();+ } catch {+ return false;+ }+ }++ /** `.` for a directory search; the file's own name when `scope` names a file. */+ protected searchTarget(searchPath: string, searchRoot: string): string {+ return searchPath === searchRoot ? '.' : `./${path.basename(searchPath)}`;+ }+/*** Build command-line arguments for grep tools.*diff --git a/packages/local-file-shell/src/contentSearch/impl/unix.ts b/packages/local-file-shell/src/contentSearch/impl/unix.tsindex 1185ecac07c..0144f2a990d 100644--- a/packages/local-file-shell/src/contentSearch/impl/unix.ts+++ b/packages/local-file-shell/src/contentSearch/impl/unix.ts@@ -1,4 +1,3 @@-import { stat } from 'node:fs/promises';import path from 'node:path';import { execa } from 'execa';@@ -265,19 +264,6 @@ export abstract class UnixContentSearch extends BaseContentSearch {}}- private async isFile(target: string): Promise<boolean> {- try {- return (await stat(target)).isFile();- } catch {- return false;- }- }-- /** `.` for a directory search; the file's own name when `scope` names a file. */- private searchTarget(searchPath: string, searchRoot: string): string {- return searchPath === searchRoot ? '.' : `./${path.basename(searchPath)}`;- }-/*** `searchRoot`/`target` must be the same pair the main search ran with: a* file-valued `scope` is legal, but execa's `cwd` must be a directory, sodiff --git a/packages/local-file-shell/src/contentSearch/impl/windows.ts b/packages/local-file-shell/src/contentSearch/impl/windows.tsindex 41c4b6f980b..2f9e39a465d 100644--- a/packages/local-file-shell/src/contentSearch/impl/windows.ts+++ b/packages/local-file-shell/src/contentSearch/impl/windows.ts@@ -1,3 +1,5 @@+import path from 'node:path';+import { execa } from 'execa';import { createLogger } from '../../logger';@@ -10,13 +12,21 @@ const logger = createLogger('contentSearch:windows');/*** Windows content search tool type- * Priority: rg > findstr/powershell > nodejs+ * Priority: rg > nodejs+ *+ * There is deliberately no findstr tier. It was run as+ * `cmd /c findstr /R "<pattern>" *.*`: libuv escapes the embedded quotes to `\"`,+ * cmd.exe strips only the outer pair, and findstr then searched for the literal+ * `"<pattern>"` β so nearly every search on a machine without `rg` answered+ * "0 matches". Even correctly quoted, findstr has no `|` alternation, no+ * `\d`/`\s`/`+`/`{n}`, reads files in the OEM code page (no UTF-8 CJK) and+ * cannot take a glob, so the Node engine is the only faithful fallback.*/-type WindowsContentSearchTool = 'findstr' | 'nodejs' | 'rg';+type WindowsContentSearchTool = 'nodejs' | 'rg';/*** Windows content search implementation- * Uses rg > findstr > nodejs fallback strategy+ * Uses rg > nodejs fallback strategy*/export class WindowsContentSearchImpl extends BaseContentSearch {private currentTool: WindowsContentSearchTool | null = null;@@ -47,26 +57,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {return 'rg';}- // findstr is always available on Windows- return 'findstr';- }-- private async fallbackToNextTool(- currentTool: WindowsContentSearchTool,- ): Promise<WindowsContentSearchTool> {- const priority: WindowsContentSearchTool[] = ['rg', 'findstr', 'nodejs'];- const currentIndex = priority.indexOf(currentTool);-- for (let i = currentIndex + 1; i < priority.length; i++) {- const nextTool = priority[i];- if (nextTool === 'nodejs' || nextTool === 'findstr') {- return nextTool;- }- if (await this.checkToolAvailable(nextTool)) {- return nextTool;- }- }-return 'nodejs';}@@ -84,7 +74,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {if (preferredTool === 'rg') {if (await this.checkToolAvailable('rg')) {logger.debug(`${logPrefix} Using preferred tool: rg`);- return this.grepWithRipgrep(params);+ return await this.grepWithRipgrep(params);}logger.warn(`${logPrefix} ripgrep (rg) not available, falling back to other tools`);}@@ -94,7 +84,10 @@ export class WindowsContentSearchImpl extends BaseContentSearch {logger.info(`Using content search tool: ${this.currentTool}`);}- return this.grepWithTool(this.currentTool, params);+ // `await` so a rejected search (e.g. the Node engine's `new RegExp` on an+ // invalid pattern) lands in the catch below instead of escaping as a+ // thrown IPC error.+ return await this.grepWithTool(this.currentTool, params);} catch (error) {logger.error(`${logPrefix} Grep failed:`, error);return {@@ -115,9 +108,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {case 'rg': {return this.grepWithRipgrep(params);}- case 'findstr': {- return this.grepWithFindstr(params);- }default: {return this.grepWithNodejs(params);}@@ -129,28 +119,49 @@ export class WindowsContentSearchImpl extends BaseContentSearch {const searchPath = this.resolveSearchPath(params);const logPrefix = `[grepContent:rg]`;+ // `scope` may name a single file, but a process `cwd` must be a directory:+ // search the file from its parent, the same way the unix impl does.+ const searchRoot = (await this.isFile(searchPath)) ? path.dirname(searchPath) : searchPath;+ const target = this.searchTarget(searchPath, searchRoot);+try {- const args = this.buildGrepArgs('rg', params);+ const args = this.buildGrepArgs('rg', params, target);logger.debug(`${logPrefix} Executing: rg ${args.join(' ')}`);- const { stdout, stderr, exitCode } = await execa('rg', args, {- cwd: searchPath,+ const { stdout, stderr, exitCode, shortMessage } = await execa('rg', args, {+ cwd: searchRoot,reject: false,stdin: 'ignore',});+ // With `reject: false`, a process that never started (ENOENT, EACCES, a+ // bad cwd) still resolves β only without an exit code. Treating that as+ // empty output is how a missing engine used to read as "0 matches".+ if (exitCode === undefined) {+ throw new Error(shortMessage || 'rg failed to start');+ }++ // rg exits 2 on errors. With matches in hand those are partial (an+ // unreadable file), but with none there is no answer to give β report the+ // error rather than a "no matches" the search never established.+ if (exitCode > 1 && !stdout.trim()) {+ const error = `rg exited with code ${exitCode}: ${stderr.trim().split('\n').slice(0, 5).join('\n')}`;+ logger.warn(`${logPrefix} ${error}`);+ return { engine: 'rg', error, matches: [], success: false, total_matches: 0 };+ }+if (exitCode !== 0 && exitCode !== 1 && stderr) {logger.warn(`${logPrefix} rg exited with code ${exitCode}: ${stderr}`);}- // Same normalisation as the unix impl: rg runs with `cwd = searchPath`- // and searches `.`, so its output is relative β make it absolute so the- // engine no longer decides the path shape callers receive.+ // Same normalisation as the unix impl: rg runs with `cwd = searchRoot`+ // and searches a relative target, so its output is relative β make it+ // absolute so the engine no longer decides the path shape callers receive.const lines = stdout.trim().split('\n').filter(Boolean)- .map((line) => toAbsoluteMatchLine(searchPath, line));+ .map((line) => toAbsoluteMatchLine(searchRoot, line));let matches: string[] = [];let totalMatches = 0;@@ -164,7 +175,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {matches = lines;const hasContext = params['-A'] || params['-B'] || params['-C'];if (hasContext) {- totalMatches = await this.getActualMatchCount(params);+ totalMatches = await this.getActualMatchCount(params, searchRoot, target);} else {totalMatches = lines.length;}@@ -198,22 +209,32 @@ export class WindowsContentSearchImpl extends BaseContentSearch {total_matches: totalMatches,};} catch (error) {- logger.warn(`${logPrefix} rg failed, falling back to findstr:`, error);- this.currentTool = await this.fallbackToNextTool('rg');- return this.grepWithTool(this.currentTool, params);+ logger.warn(`${logPrefix} rg failed, falling back to Node.js:`, error);+ // Only pin later searches to Node when rg is really gone; one failing+ // call should not downgrade the shared instance for the whole session.+ if (!(await this.checkToolAvailable('rg'))) this.currentTool = 'nodejs';+ return this.grepWithNodejs(params);}}- private async getActualMatchCount(params: GrepContentParams): Promise<number> {+ private async getActualMatchCount(+ params: GrepContentParams,+ searchRoot: string,+ target: string,+ ): Promise<number> {const countParams = { ...params, '-A': undefined, '-B': undefined, '-C': undefined };- const args = this.buildGrepArgs('rg', {- ...countParams,- output_mode: 'count',- } as GrepContentParams);+ const args = this.buildGrepArgs(+ 'rg',+ {+ ...countParams,+ output_mode: 'count',+ } as GrepContentParams,+ target,+ );try {const { stdout } = await execa('rg', args, {- cwd: this.resolveSearchPath(params),+ cwd: searchRoot,reject: false,stdin: 'ignore',});@@ -231,98 +252,6 @@ export class WindowsContentSearchImpl extends BaseContentSearch {}}- private async grepWithFindstr(params: GrepContentParams): Promise<GrepContentResult> {- const { pattern, output_mode = 'files_with_matches' } = params;- const searchPath = this.resolveSearchPath(params);- const logPrefix = `[grepContent:findstr]`;-- try {- const args: string[] = ['/S'];-- if (params['-i']) {- args.push('/I');- }-- if (params['-n']) {- args.push('/N');- }-- args.push('/R');- args.push(`"${pattern}"`);-- const filePattern = params.glob || params.type ? `*.${params.type || '*'}` : '*.*';- args.push(filePattern);-- logger.debug(`${logPrefix} Executing: findstr ${args.join(' ')}`);-- const { stdout, exitCode } = await execa('cmd', ['/c', `findstr ${args.join(' ')}`], {- cwd: searchPath,- reject: false,- stdin: 'ignore',- });-- if (exitCode !== 0 && exitCode !== 1) {- logger.warn(`${logPrefix} findstr exited with code ${exitCode}`);- }-- const lines = stdout.trim().split('\r\n').filter(Boolean);- let matches: string[] = [];- let totalMatches = 0;-- switch (output_mode) {- case 'files_with_matches': {- const files = new Set<string>();- for (const line of lines) {- const match = line.match(/^([^:]+):/);- if (match) {- files.add(match[1]);- }- }- matches = [...files];- totalMatches = matches.length;- break;- }- case 'content': {- matches = lines;- totalMatches = lines.length;- break;- }- case 'count': {- const fileCounts = new Map<string, number>();- for (const line of lines) {- const match = line.match(/^([^:]+):/);- if (match) {- fileCounts.set(match[1], (fileCounts.get(match[1]) || 0) + 1);- }- }- matches = [...fileCounts.entries()].map(([file, count]) => `${file}:${count}`);- totalMatches = lines.length;- break;- }- }-- if (params.head_limit && matches.length > params.head_limit) {- matches = matches.slice(0, params.head_limit);- }-- logger.info(`${logPrefix} Search completed`, {- matchCount: matches.length,- totalMatches,- });-- return {- engine: 'findstr',- matches,- success: true,- total_matches: totalMatches,- };- } catch (error) {- logger.warn(`${logPrefix} findstr failed, falling back to Node.js:`, error);- this.currentTool = 'nodejs';- return this.grepWithNodejs(params);- }- }-protected override getDefaultIgnorePatterns(): string[] {return [...super.getDefaultIgnorePatterns(),