Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
38 changes: 37 additions & 1 deletion src/firefox/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<FocusedElement> {
return await this.bidi.callFunction<FocusedElement>(
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.
Expand All @@ -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.`
);
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/firefox/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -216,6 +216,10 @@ export class FirefoxClient {
return await this.getDom().typeText(this.getContext(), text, options);
}

async getFocusedElement(): Promise<FocusedElement> {
return await this.getDom().getFocusedElement(this.getContext());
}

// ============================================================================
// Console
// ============================================================================
Expand Down
13 changes: 10 additions & 3 deletions src/tools/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
},
Expand Down Expand Up @@ -417,9 +417,16 @@ export const handleTypeText = defineToolHandler<typeof typeTextTool>(

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);
Expand Down
3 changes: 3 additions & 0 deletions src/utils/response-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down
65 changes: 64 additions & 1 deletion tests/integration/firefox/type-text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,<div id=e contenteditable></div>');

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,<input id=p type=password>');

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,<iframe srcdoc="<input id=inner>"></iframe>');

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,<iframe srcdoc="<input id=inner>"></iframe><input value=outer>'
);

await firefox.typeText('ab', { uid: await uidOf('inner'), submitKey: 'Tab' });

expect(await firefox.getFocusedElement()).toEqual({ tag: 'input', value: 'outer' });
}, 20000);
});
});
52 changes: 52 additions & 0 deletions tests/integration/mcp/input.test.ts
Original file line number Diff line number Diff line change
@@ -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,<input aria-label=Name><div contenteditable>x</div>',
});
});

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$/);
});
});
19 changes: 0 additions & 19 deletions tests/unit/tools/input.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down