From b2c8cd24850320358534626a2e346b8b95637dcd Mon Sep 17 00:00:00 2001 From: Relacosm <178203931+Relacosm@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:18:23 +0530 Subject: [PATCH 1/2] Bug 2081626 - [firefox-mcp] Report the focused element and its value after type_text type_text only replied with the number of characters typed, so an agent could not tell whether the text reached the element it meant to type into. After typing, it now reads the element that has focus, looking into open shadow roots and same-origin iframes, and returns its tag and its value for inputs, textareas and selects. The error for a uid that cannot take focus no longer starts with "pressKey:", since type_text uses the same check. The two mock-based handler tests for the success path are replaced by MCP harness tests. --- docs/tools.md | 2 +- src/firefox/dom.ts | 52 ++++++++++++++++++--- src/firefox/index.ts | 4 +- src/tools/input.ts | 9 ++-- tests/integration/firefox/type-text.test.ts | 45 +++++++++++++++++- tests/integration/mcp/input.test.ts | 39 ++++++++++++++++ tests/unit/tools/input.test.ts | 19 -------- 7 files changed, 138 insertions(+), 32 deletions(-) create mode 100644 tests/integration/mcp/input.test.ts diff --git a/docs/tools.md b/docs/tools.md index 7ef243f9..7d175d4d 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -253,7 +253,7 @@ Parameters: ### `type_text` -Type text key by key into the focused element, optionally followed by a key such as Enter. Use fill_by_uid to set the value of a known input; use this for elements that only react to real typing, such as autocomplete fields and rich text editors. +Type text key by key into the focused element, optionally followed by a key such as Enter. Use fill_by_uid to set the value of a known input; use this for elements that only react to real typing, such as autocomplete fields and rich text editors. Reports the element that has focus afterwards, with its value. Parameters: diff --git a/src/firefox/dom.ts b/src/firefox/dom.ts index f8f6370b..f18c01c7 100644 --- a/src/firefox/dom.ts +++ b/src/firefox/dom.ts @@ -155,6 +155,13 @@ function comboKeyActions({ modifiers, key }: KeyCombo): Input.KeySourceAction[] return actions; } +export interface FocusedElement { + /** Local name of the focused element, or "none" */ + tag: string; + /** Current value, for elements that have one, such as inputs and textareas */ + value?: string; +} + export interface WaitForOptions { /** CSS selector of an element that has to be visible */ selector?: string | undefined; @@ -565,13 +572,11 @@ export class DomInteractions { context: BrowsingContext.BrowsingContext, text: string, options: { uid?: string | undefined; submitKey?: string | undefined } = {} - ): Promise { + ): Promise { // Parsed up front so that an invalid key fails before anything is typed. const submit = options.submitKey === undefined ? undefined : parseKeyCombo(options.submitKey); - if (options.uid) { - await this.focusByUid(context, options.uid); - } + const frame = options.uid ? await this.focusByUid(context, options.uid) : context; // One sequence, so that the text and the key land on the same element. const actions = textKeyActions(text); @@ -579,13 +584,47 @@ export class DomInteractions { actions.push(...comboKeyActions(submit)); } await this.sendKeyActions(context, actions); + + return await this.getFocusedElement(frame); + } + + /** + * Describe the element that has keyboard focus in the given context, looking + * into open shadow roots and same-origin iframes. + */ + private async getFocusedElement( + context: BrowsingContext.BrowsingContext + ): Promise { + return await this.bidi.callFunction( + context, + `() => { + let el = document.activeElement; + while (el) { + const inner = el.shadowRoot?.activeElement ?? el.contentDocument?.activeElement; + if (!inner) { + break; + } + el = inner; + } + if (!el) { + return { tag: 'none' }; + } + return ['input', 'textarea', 'select'].includes(el.localName) + ? { tag: el.localName, value: el.value } + : { tag: el.localName }; + }`, + [] + ); } /** * Focus the element for the provided uid. Throws if the element cannot be * focused. */ - private async focusByUid(context: BrowsingContext.BrowsingContext, uid: string): Promise { + private async focusByUid( + context: BrowsingContext.BrowsingContext, + uid: string + ): Promise { const { context: frame, element: el } = await this.resolveUid(context, uid); await this.waitForVisible(frame, el, 5000); const focused = await this.bidi.callFunction( @@ -595,9 +634,10 @@ export class DomInteractions { ); if (!focused) { throw new Error( - `pressKey: uid ${uid} cannot receive keyboard focus. Target a focusable element, or omit uid to send the key to the currently focused element.` + `uid ${uid} cannot receive keyboard focus. Target a focusable element, or omit uid to send keys to the currently focused element.` ); } + return frame; } // ============================================================================ diff --git a/src/firefox/index.ts b/src/firefox/index.ts index d0f7cf0a..8fbfdba1 100644 --- a/src/firefox/index.ts +++ b/src/firefox/index.ts @@ -17,7 +17,7 @@ import { DialogEvents, } from './events/index.js'; import type { NetworkBodyResult } from './events/network.js'; -import { DomInteractions, type WaitForOptions } from './dom.js'; +import { DomInteractions, type FocusedElement, type WaitForOptions } from './dom.js'; import { PageManagement } from './pages.js'; import { CacheManagement, type CacheBehavior } from './cache.js'; import { SnapshotManager, type Snapshot, type SnapshotOptions } from './snapshot/index.js'; @@ -212,7 +212,7 @@ export class FirefoxClient { async typeText( text: string, options?: { uid?: string | undefined; submitKey?: string | undefined } - ): Promise { + ): Promise { return await this.getDom().typeText(this.getContext(), text, options); } diff --git a/src/tools/input.ts b/src/tools/input.ts index df2d1176..e5f0bf23 100644 --- a/src/tools/input.ts +++ b/src/tools/input.ts @@ -175,7 +175,7 @@ export const pressKeyTool = { export const typeTextTool = { name: 'type_text', description: - 'Type text key by key into the focused element, optionally followed by a key such as Enter. Use fill_by_uid to set the value of a known input; use this for elements that only react to real typing, such as autocomplete fields and rich text editors.', + 'Type text key by key into the focused element, optionally followed by a key such as Enter. Use fill_by_uid to set the value of a known input; use this for elements that only react to real typing, such as autocomplete fields and rich text editors. Reports the element that has focus afterwards, with its value.', annotations: { readOnlyHint: false, }, @@ -416,10 +416,13 @@ export const handleTypeText = defineToolHandler( const firefox = await getFirefox(); try { - await firefox.typeText(text, { uid, submitKey }); + const focused = await firefox.typeText(text, { uid, submitKey }); const target = uid ? ` on ${uid}` : ''; const suffix = submitKey ? `, then ${submitKey}` : ''; - return successResponse(`type_text ${text.length} chars${target}${suffix}`); + const value = focused.value === undefined ? '' : `, value: ${JSON.stringify(focused.value)}`; + return successResponse( + `type_text ${text.length} chars${target}${suffix}\nFocused: ${focused.tag}${value}` + ); } catch (error) { if (uid) { throw handleUidError(error as Error, uid); diff --git a/tests/integration/firefox/type-text.test.ts b/tests/integration/firefox/type-text.test.ts index e6bc72da..1102df6a 100644 --- a/tests/integration/firefox/type-text.test.ts +++ b/tests/integration/firefox/type-text.test.ts @@ -7,6 +7,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { createTestFirefox, closeFirefox, + fixtureUrl, waitForElementInSnapshot, } from '../../helpers/firefox.js'; import type { FirefoxClient } from '@/firefox/index.js'; @@ -95,8 +96,50 @@ describe('type_text Integration Tests', () => { const uid = await uidOf('h'); await expect(firefox.typeText('nope', { uid })).rejects.toThrow( - /cannot receive keyboard focus/ + /^uid \S+ cannot receive keyboard focus/ ); expect(await recordedKeys()).toEqual([]); }, 20000); + describe('focused element', () => { + it('should return the focused input and its value', async () => { + await openPage(); + + const focused = await firefox.typeText('hi', { uid: await uidOf('a') }); + + expect(focused).toEqual({ tag: 'input', value: 'hi' }); + }, 20000); + + it('should return the element that has focus after the submit key', async () => { + await openPage(); + await firefox.evaluate(`document.getElementById('b').value = 'next'`); + + const focused = await firefox.typeText('first', { uid: await uidOf('a'), submitKey: 'Tab' }); + + expect(focused).toEqual({ tag: 'input', value: 'next' }); + }, 20000); + + it('should return no value for an element without one', async () => { + await firefox.navigate('data:text/html,
'); + + const focused = await firefox.typeText('hi', { uid: await uidOf('e') }); + + expect(focused).toEqual({ tag: 'div' }); + }, 20000); + + it('should look into open shadow roots', async () => { + await firefox.navigate(fixtureUrl('shadow-dom.html')); + const focused = await firefox.typeText('deep', { uid: await uidOf('deep') }); + + expect(focused).toEqual({ tag: 'input', value: 'deep' }); + }, 20000); + + it('should look into same-origin iframes when no uid is given', async () => { + await firefox.navigate('data:text/html,'); + await firefox.typeText('ab', { uid: await uidOf('inner') }); + + const focused = await firefox.typeText('cd'); + + expect(focused).toEqual({ tag: 'input', value: 'abcd' }); + }, 20000); + }); }); diff --git a/tests/integration/mcp/input.test.ts b/tests/integration/mcp/input.test.ts new file mode 100644 index 00000000..9224dd4b --- /dev/null +++ b/tests/integration/mcp/input.test.ts @@ -0,0 +1,39 @@ +/** + * Integration tests for the input tools, called through the MCP server + */ + +import { expect, assert } from 'vitest'; +import { mcpTest } from '../../helpers/mcp.js'; + +mcpTest.override('mcpServerArgs', ['--tools', 'pages', 'snapshot', 'input', 'script']); + +mcpTest.describe('type_text (MCP)', () => { + mcpTest.beforeEach(async ({ mcp }) => { + await mcp.callTool('navigate_page', { + url: 'data:text/html,
x
', + }); + }); + + mcpTest('reports the focused element and its value', async ({ mcp }) => { + const snapshot = await mcp.callTool('take_snapshot'); + const uid = /uid=(\S+) \S+ "Name"/.exec(snapshot.text)?.[1]; + assert(uid, 'snapshot contains the input uid'); + + const result = await mcp.callTool('type_text', { text: 'b"c', uid }); + + expect(result.isError).toBe(false); + expect(result.text).toContain(`type_text 3 chars on ${uid}`); + expect(result.text).toContain('Focused: input, value: "b\\"c"'); + }); + + mcpTest('reports only the tag of an element without a value', async ({ mcp }) => { + await mcp.callTool('evaluate_script', { + function: '() => document.querySelector("div").focus()', + }); + + const result = await mcp.callTool('type_text', { text: 'y' }); + + expect(result.isError).toBe(false); + expect(result.text).toMatch(/Focused: div$/); + }); +}); diff --git a/tests/unit/tools/input.test.ts b/tests/unit/tools/input.test.ts index 73c9e1dd..991a51e6 100644 --- a/tests/unit/tools/input.test.ts +++ b/tests/unit/tools/input.test.ts @@ -230,25 +230,6 @@ describe('Input Tools', () => { vi.restoreAllMocks(); }); - it('should type into the focused element when no uid is given', async () => { - const { handleTypeText } = await import('../../../src/tools/input.js'); - const result = await handleTypeText({ text: 'hello' }); - - expect(result.isError).toBeUndefined(); - expect(typeText).toHaveBeenCalledWith('hello', { uid: undefined, submitKey: undefined }); - expect(textOf(result)).toContain('5 chars'); - }); - - it('should pass uid and submitKey through', async () => { - const { handleTypeText } = await import('../../../src/tools/input.js'); - const result = await handleTypeText({ text: 'hello', uid: 'uid-3', submitKey: 'Enter' }); - - expect(result.isError).toBeUndefined(); - expect(typeText).toHaveBeenCalledWith('hello', { uid: 'uid-3', submitKey: 'Enter' }); - expect(textOf(result)).toContain('uid-3'); - expect(textOf(result)).toContain('Enter'); - }); - it('should reject missing, empty or non-string text', async () => { const { handleTypeText } = await import('../../../src/tools/input.js'); From f1b329845a6258a938e2c08a2160b7b3a8e9cc7b Mon Sep 17 00:00:00 2001 From: Relacosm <178203931+Relacosm@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:41:10 +0530 Subject: [PATCH 2/2] Bug 2081626 - [firefox-mcp] Expose getFocusedElement and address review comments typeText returns void again, and handleTypeText reads the focused element through the new FirefoxClient.getFocusedElement(). The lookup always starts from the top-level document, so it follows focus when the submit key moves it out of an iframe. The value of password inputs is left out, and long values are truncated. --- src/firefox/dom.ts | 24 +++++------- src/firefox/index.ts | 6 ++- src/tools/input.ts | 10 +++-- src/utils/response-helpers.ts | 3 ++ tests/integration/firefox/type-text.test.ts | 42 +++++++++++++++------ tests/integration/mcp/input.test.ts | 13 +++++++ 6 files changed, 69 insertions(+), 29 deletions(-) diff --git a/src/firefox/dom.ts b/src/firefox/dom.ts index f18c01c7..9e9adca8 100644 --- a/src/firefox/dom.ts +++ b/src/firefox/dom.ts @@ -572,11 +572,13 @@ export class DomInteractions { context: BrowsingContext.BrowsingContext, text: string, options: { uid?: string | undefined; submitKey?: string | undefined } = {} - ): Promise { + ): Promise { // Parsed up front so that an invalid key fails before anything is typed. const submit = options.submitKey === undefined ? undefined : parseKeyCombo(options.submitKey); - const frame = options.uid ? await this.focusByUid(context, options.uid) : context; + if (options.uid) { + await this.focusByUid(context, options.uid); + } // One sequence, so that the text and the key land on the same element. const actions = textKeyActions(text); @@ -584,17 +586,14 @@ export class DomInteractions { actions.push(...comboKeyActions(submit)); } await this.sendKeyActions(context, actions); - - return await this.getFocusedElement(frame); } /** * Describe the element that has keyboard focus in the given context, looking - * into open shadow roots and same-origin iframes. + * into open shadow roots and same-origin iframes. The value of password inputs + * is left out. */ - private async getFocusedElement( - context: BrowsingContext.BrowsingContext - ): Promise { + async getFocusedElement(context: BrowsingContext.BrowsingContext): Promise { return await this.bidi.callFunction( context, `() => { @@ -609,7 +608,8 @@ export class DomInteractions { if (!el) { return { tag: 'none' }; } - return ['input', 'textarea', 'select'].includes(el.localName) + const hasValue = ['input', 'textarea', 'select'].includes(el.localName); + return hasValue && el.type !== 'password' ? { tag: el.localName, value: el.value } : { tag: el.localName }; }`, @@ -621,10 +621,7 @@ export class DomInteractions { * Focus the element for the provided uid. Throws if the element cannot be * focused. */ - private async focusByUid( - context: BrowsingContext.BrowsingContext, - uid: string - ): Promise { + private async focusByUid(context: BrowsingContext.BrowsingContext, uid: string): Promise { const { context: frame, element: el } = await this.resolveUid(context, uid); await this.waitForVisible(frame, el, 5000); const focused = await this.bidi.callFunction( @@ -637,7 +634,6 @@ export class DomInteractions { `uid ${uid} cannot receive keyboard focus. Target a focusable element, or omit uid to send keys to the currently focused element.` ); } - return frame; } // ============================================================================ diff --git a/src/firefox/index.ts b/src/firefox/index.ts index 8fbfdba1..ebd9eae5 100644 --- a/src/firefox/index.ts +++ b/src/firefox/index.ts @@ -212,10 +212,14 @@ export class FirefoxClient { async typeText( text: string, options?: { uid?: string | undefined; submitKey?: string | undefined } - ): Promise { + ): Promise { return await this.getDom().typeText(this.getContext(), text, options); } + async getFocusedElement(): Promise { + return await this.getDom().getFocusedElement(this.getContext()); + } + // ============================================================================ // Console // ============================================================================ diff --git a/src/tools/input.ts b/src/tools/input.ts index e5f0bf23..848f8f95 100644 --- a/src/tools/input.ts +++ b/src/tools/input.ts @@ -3,7 +3,7 @@ * Require valid UIDs from take_snapshot */ -import { successResponse } from '../utils/response-helpers.js'; +import { successResponse, truncateText, TOKEN_LIMITS } from '../utils/response-helpers.js'; import { handleUidError } from '../utils/uid-helpers.js'; import { defineModule, defineToolHandler, type ToolDefinition } from './module.js'; import type { McpToolResponse } from '../types/common.js'; @@ -416,10 +416,14 @@ export const handleTypeText = defineToolHandler( const firefox = await getFirefox(); try { - const focused = await firefox.typeText(text, { uid, submitKey }); + await firefox.typeText(text, { uid, submitKey }); + const focused = await firefox.getFocusedElement(); const target = uid ? ` on ${uid}` : ''; const suffix = submitKey ? `, then ${submitKey}` : ''; - const value = focused.value === undefined ? '' : `, value: ${JSON.stringify(focused.value)}`; + const value = + focused.value === undefined + ? '' + : `, value: ${JSON.stringify(truncateText(focused.value, TOKEN_LIMITS.MAX_FOCUSED_VALUE_CHARS, '...[truncated]'))}`; return successResponse( `type_text ${text.length} chars${target}${suffix}\nFocused: ${focused.tag}${value}` ); diff --git a/src/utils/response-helpers.ts b/src/utils/response-helpers.ts index 56b8d380..2779bc6e 100644 --- a/src/utils/response-helpers.ts +++ b/src/utils/response-helpers.ts @@ -22,6 +22,9 @@ export const TOKEN_LIMITS = { /** Maximum characters per console message text */ MAX_CONSOLE_MESSAGE_CHARS: 2_000, + /** Maximum characters for the value of the focused element */ + MAX_FOCUSED_VALUE_CHARS: 500, + /** Maximum characters for network header values (per header) */ MAX_HEADER_VALUE_CHARS: 500, diff --git a/tests/integration/firefox/type-text.test.ts b/tests/integration/firefox/type-text.test.ts index 1102df6a..c8a87e21 100644 --- a/tests/integration/firefox/type-text.test.ts +++ b/tests/integration/firefox/type-text.test.ts @@ -100,46 +100,66 @@ describe('type_text Integration Tests', () => { ); expect(await recordedKeys()).toEqual([]); }, 20000); + describe('focused element', () => { it('should return the focused input and its value', async () => { await openPage(); - const focused = await firefox.typeText('hi', { uid: await uidOf('a') }); + await firefox.typeText('hi', { uid: await uidOf('a') }); - expect(focused).toEqual({ tag: 'input', value: 'hi' }); + expect(await firefox.getFocusedElement()).toEqual({ tag: 'input', value: 'hi' }); }, 20000); it('should return the element that has focus after the submit key', async () => { await openPage(); await firefox.evaluate(`document.getElementById('b').value = 'next'`); - const focused = await firefox.typeText('first', { uid: await uidOf('a'), submitKey: 'Tab' }); + await firefox.typeText('first', { uid: await uidOf('a'), submitKey: 'Tab' }); - expect(focused).toEqual({ tag: 'input', value: 'next' }); + expect(await firefox.getFocusedElement()).toEqual({ tag: 'input', value: 'next' }); }, 20000); it('should return no value for an element without one', async () => { await firefox.navigate('data:text/html,
'); - const focused = await firefox.typeText('hi', { uid: await uidOf('e') }); + await firefox.typeText('hi', { uid: await uidOf('e') }); + + expect(await firefox.getFocusedElement()).toEqual({ tag: 'div' }); + }, 20000); + + it('should return no value for a password input', async () => { + await firefox.navigate('data:text/html,'); + + await firefox.typeText('secret', { uid: await uidOf('p') }); - expect(focused).toEqual({ tag: 'div' }); + expect(await valueOf('p')).toBe('secret'); + expect(await firefox.getFocusedElement()).toEqual({ tag: 'input' }); }, 20000); it('should look into open shadow roots', async () => { await firefox.navigate(fixtureUrl('shadow-dom.html')); - const focused = await firefox.typeText('deep', { uid: await uidOf('deep') }); - expect(focused).toEqual({ tag: 'input', value: 'deep' }); + await firefox.typeText('deep', { uid: await uidOf('deep') }); + + expect(await firefox.getFocusedElement()).toEqual({ tag: 'input', value: 'deep' }); }, 20000); - it('should look into same-origin iframes when no uid is given', async () => { + it('should look into same-origin iframes', async () => { await firefox.navigate('data:text/html,'); + await firefox.typeText('ab', { uid: await uidOf('inner') }); - const focused = await firefox.typeText('cd'); + expect(await firefox.getFocusedElement()).toEqual({ tag: 'input', value: 'ab' }); + }, 20000); + + it('should follow focus out of an iframe', async () => { + await firefox.navigate( + 'data:text/html,' + ); + + await firefox.typeText('ab', { uid: await uidOf('inner'), submitKey: 'Tab' }); - expect(focused).toEqual({ tag: 'input', value: 'abcd' }); + expect(await firefox.getFocusedElement()).toEqual({ tag: 'input', value: 'outer' }); }, 20000); }); }); diff --git a/tests/integration/mcp/input.test.ts b/tests/integration/mcp/input.test.ts index 9224dd4b..d75ce2b7 100644 --- a/tests/integration/mcp/input.test.ts +++ b/tests/integration/mcp/input.test.ts @@ -26,6 +26,19 @@ mcpTest.describe('type_text (MCP)', () => { expect(result.text).toContain('Focused: input, value: "b\\"c"'); }); + mcpTest('truncates a long value', async ({ mcp }) => { + await mcp.callTool('evaluate_script', { + function: + '() => { const el = document.querySelector("input"); el.value = "x".repeat(5000); el.focus(); }', + }); + + const result = await mcp.callTool('type_text', { text: 'y' }); + + expect(result.isError).toBe(false); + expect(result.text).toMatch(/value: "x+\.\.\.\[truncated\]"$/); + expect(result.text.length).toBeLessThan(1000); + }); + mcpTest('reports only the tag of an element without a value', async ({ mcp }) => { await mcp.callTool('evaluate_script', { function: '() => document.querySelector("div").focus()',