diff --git a/docs/tools.md b/docs/tools.md index 7ef243f..7d175d4 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 f8f6370..9e9adca 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; @@ -581,6 +588,35 @@ export class DomInteractions { await this.sendKeyActions(context, actions); } + /** + * Describe the element that has keyboard focus in the given context, looking + * into open shadow roots and same-origin iframes. The value of password inputs + * is left out. + */ + 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' }; + } + const hasValue = ['input', 'textarea', 'select'].includes(el.localName); + return hasValue && el.type !== 'password' + ? { tag: el.localName, value: el.value } + : { tag: el.localName }; + }`, + [] + ); + } + /** * Focus the element for the provided uid. Throws if the element cannot be * focused. @@ -595,7 +631,7 @@ 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.` ); } } diff --git a/src/firefox/index.ts b/src/firefox/index.ts index d0f7cf0..ebd9eae 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'; @@ -216,6 +216,10 @@ export class FirefoxClient { 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 df2d117..848f8f9 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'; @@ -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, }, @@ -417,9 +417,16 @@ export const handleTypeText = defineToolHandler( try { await firefox.typeText(text, { uid, submitKey }); + const focused = await firefox.getFocusedElement(); 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(truncateText(focused.value, TOKEN_LIMITS.MAX_FOCUSED_VALUE_CHARS, '...[truncated]'))}`; + 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/src/utils/response-helpers.ts b/src/utils/response-helpers.ts index 56b8d38..2779bc6 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 e6bc72d..c8a87e2 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,70 @@ 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(); + + await firefox.typeText('hi', { uid: await uidOf('a') }); + + 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'`); + + await firefox.typeText('first', { uid: await uidOf('a'), submitKey: 'Tab' }); + + 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,
'); + + 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(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')); + + 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', async () => { + await firefox.navigate('data:text/html,'); + + await firefox.typeText('ab', { uid: await uidOf('inner') }); + + 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(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 new file mode 100644 index 0000000..d75ce2b --- /dev/null +++ b/tests/integration/mcp/input.test.ts @@ -0,0 +1,52 @@ +/** + * 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('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()', + }); + + 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 73c9e1d..991a51e 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');