From a09464ce46e8d5bcf0f84678bedef00da5e78cea Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Fri, 25 Sep 2026 14:16:52 -0400 Subject: [PATCH] fix(browser): surface structured CLI errors on nonzero exit --- .../cli/__tests__/browser-errors-3284.test.ts | 72 +++++++++++++++++++ .../cli/src/mcp-tools/browser-tools.ts | 53 ++++++++------ 2 files changed, 102 insertions(+), 23 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/browser-errors-3284.test.ts diff --git a/v3/@claude-flow/cli/__tests__/browser-errors-3284.test.ts b/v3/@claude-flow/cli/__tests__/browser-errors-3284.test.ts new file mode 100644 index 0000000000..559d6d045f --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/browser-errors-3284.test.ts @@ -0,0 +1,72 @@ +/** Regression for #3284: non-zero agent-browser exits carry JSON errors on stdout. */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const execFileSync = vi.hoisted(() => vi.fn()); +vi.mock('child_process', () => ({ execFileSync })); +vi.mock('../src/mcp-tools/validate-input.js', () => ({ + validateIdentifier: () => ({ valid: true }), + validateText: () => ({ valid: true }), +})); + +import { execBrowserCommand } from '../src/mcp-tools/browser-tools.js'; + +function failure(options: { stdout?: string | Buffer; code?: string; status?: number; stderr?: string }) { + return Object.assign(new Error('Command failed: agent-browser fill secret-value'), options); +} + +async function errorText() { + const result = await execBrowserCommand(['click', 'mat-option'], 'test-session'); + expect(result.isError).toBe(true); + return JSON.parse(result.content[0].text as string) as { success: boolean; error: string }; +} + +describe('#3284 browser CLI error propagation', () => { + beforeEach(() => execFileSync.mockReset()); + + it('surfaces the precise CLI JSON error on a direct non-zero exit', async () => { + execFileSync.mockImplementationOnce(() => { + throw failure({ status: 1, stdout: JSON.stringify({ success: false, data: 'private trace', error: 'Element not found: mat-option' }) }); + }); + expect(await errorText()).toEqual({ success: false, error: 'Element not found: mat-option' }); + expect(execFileSync).toHaveBeenCalledTimes(1); + }); + + it('surfaces the JSON error from the npx fallback after global ENOENT', async () => { + execFileSync + .mockImplementationOnce(() => { throw failure({ code: 'ENOENT' }); }) + .mockImplementationOnce(() => { + throw failure({ status: 1, stdout: Buffer.from(JSON.stringify({ success: false, error: 'Wait timed out after 25000ms' })) }); + }); + expect(await errorText()).toEqual({ success: false, error: 'Wait timed out after 25000ms' }); + expect(execFileSync.mock.calls[1][0]).toBe('npx'); + }); + + it('does not leak unrelated stdout, stderr, or command arguments when JSON is malformed', async () => { + execFileSync.mockImplementationOnce(() => { + throw failure({ status: 1, stdout: 'sensitive browser output', stderr: 'private stderr' }); + }); + const result = await errorText(); + expect(result.error).toBe('agent-browser exited with status 1 without a JSON error'); + expect(JSON.stringify(result)).not.toMatch(/sensitive|private|secret-value/); + }); + + it('does not turn an unsuccessful process into a success based on stdout', async () => { + execFileSync.mockImplementationOnce(() => { + throw failure({ status: 1, stdout: JSON.stringify({ success: true, data: 'unrelated' }) }); + }); + expect((await errorText()).error).toMatch(/exited with status 1/); + }); + + it('keeps the actionable install error when both executables are missing', async () => { + execFileSync.mockImplementationOnce(() => { throw failure({ code: 'ENOENT' }); }) + .mockImplementationOnce(() => { throw failure({ code: 'ENOENT' }); }); + expect((await errorText()).error).toMatch(/Neither agent-browser nor npx found/); + }); + + it('preserves the successful JSON result', async () => { + execFileSync.mockReturnValue(JSON.stringify({ success: true, data: { clicked: true } })); + const result = await execBrowserCommand(['click', 'mat-option'], 'test-session'); + expect(result.isError).not.toBe(true); + expect(JSON.parse(result.content[0].text as string)).toEqual({ success: true, data: { clicked: true } }); + }); +}); diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts index fe7b2ebd20..4bd1ffac1b 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts @@ -16,6 +16,34 @@ const browserSessions = new Map(); +/** Preserve agent-browser's JSON error on non-zero exit without echoing other process output. */ +function browserCommandFailure(error: unknown, missingExecutable?: string): MCPToolResult { + const err = error as NodeJS.ErrnoException & { stdout?: string | Buffer; status?: number }; + const stdout = typeof err?.stdout === 'string' + ? err.stdout + : Buffer.isBuffer(err?.stdout) ? err.stdout.toString('utf8') : ''; + let reason: string | undefined; + if (stdout.trim()) { + try { + const parsed: unknown = JSON.parse(stdout); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + const failure = parsed as { success?: unknown; error?: unknown }; + if (failure.success === false && typeof failure.error === 'string' && failure.error.trim()) { + reason = failure.error.slice(0, 2000); + } + } + } catch { /* non-JSON stdout is not an error message */ } + } + reason ??= err?.code === 'ENOENT' && missingExecutable + ? missingExecutable + : err?.code === 'ETIMEDOUT' + ? 'agent-browser command timed out' + : typeof err?.status === 'number' + ? `agent-browser exited with status ${err.status} without a JSON error` + : `agent-browser failed${err?.code ? ` (${err.code})` : ''} without a JSON error`; + return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: reason }) }], isError: true }; +} + /** * Execute agent-browser CLI command. * Tries global agent-browser first, falls back to npx if ENOENT. @@ -50,31 +78,10 @@ export async function execBrowserCommand(args: string[], session = 'default'): P windowsHide: true, }); } catch (npxError) { - const npxErr = npxError as NodeJS.ErrnoException; - return { - content: [{ - type: 'text', - text: JSON.stringify({ - success: false, - error: npxErr.code === 'ENOENT' - ? 'Neither agent-browser nor npx found. Install with: npm i -g agent-browser' - : npxErr instanceof Error ? npxErr.message : String(npxError), - }), - }], - isError: true, - }; + return browserCommandFailure(npxError, 'Neither agent-browser nor npx found. Install with: npm i -g agent-browser'); } } else { - return { - content: [{ - type: 'text', - text: JSON.stringify({ - success: false, - error: err instanceof Error ? err.message : String(error), - }), - }], - isError: true, - }; + return browserCommandFailure(error); } }