Chrome DevTools for coding agents
fix(script): surface non-Error thrown and rejected values in evaluate_script (#2951) (#3127)
Yuri (IURII) Trukhinb1e6e6850dca
diff --git a/src/tools/script.ts b/src/tools/script.tsindex 989f2f59..c2dd6d2c 100644--- a/src/tools/script.ts+++ b/src/tools/script.ts@@ -243,9 +243,32 @@ const performEvaluation = async ([],() => (...args: unknown[]) => unknown>(`(\n${functionSource}\n)`);+ // Normalize non-Error values inside the page callback (serialized by Puppeteer) so CDP preserves the message.result = await evaluatable.evaluate(async (fn, ...args) => {- return JSON.stringify(await fn(...args));+ try {+ return JSON.stringify(await fn(...args));+ } catch (err) {+ if (+ err instanceof Error ||+ (typeof err === 'object' &&+ err !== null &&+ 'message' in err &&+ typeof err.message === 'string')+ ) {+ throw err;+ }+ let message: string;+ try {+ message =+ typeof err === 'object' && err !== null+ ? JSON.stringify(err)+ : String(err);+ } catch {+ message = String(err);+ }+ throw new Error(message);+ }},fn,...args,diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.tsindex 1dfe1910..c1d84304 100644--- a/tests/tools/script.test.ts+++ b/tests/tools/script.test.ts@@ -118,6 +118,40 @@ describe('script', () => {);});});+ it('surfaces non-Error values when script throws or rejects', async () => {+ await withMcpContext(async (response, context, args) => {+ const cases = [+ {fn: "() => { throw 'str-thrown'; }", expected: 'str-thrown'},+ {fn: "async () => { throw 'async-str'; }", expected: 'async-str'},+ {fn: '() => Promise.reject(42)', expected: '42'},+ {fn: '() => { throw {code: 42}; }', expected: '{"code":42}'},+ {+ fn: "() => { throw new Error('err-thrown'); }",+ expected: 'err-thrown',+ },+ ];+ for (const testCase of cases) {+ let caught: unknown;+ try {+ await evaluateScript(args).handler(+ {params: {function: testCase.fn}},+ response,+ context,+ );+ } catch (err) {+ caught = err;+ }+ assert.ok(+ caught instanceof Error,+ `Expected Error for ${testCase.fn}`,+ );+ assert.ok(+ caught.message.includes(testCase.expected),+ `Expected "${caught.message}" to include "${testCase.expected}"`,+ );+ }+ });+ });it('serializes script results inside the browser', async () => {await withMcpContext(async (response, context, args) => {await evaluateScript(args).handler(