cdp-toolkit 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cdp/driver.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget, type PageConnection } from "../client.ts";
9
9
  import { openSession } from "./session.ts";
10
+ import { keepFrontApp } from "../frontApp.ts";
10
11
  import type { Target, TargetSelector } from "../types.ts";
11
12
  import { chromeLeaseBackend, LeaseConflictError } from "../leases.ts";
12
13
  import { currentEndpoint } from "../endpoints.ts";
@@ -21,7 +22,7 @@ import {
21
22
  type DragDestination, type DragOptions,
22
23
  type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel, type MouseButtonOptions,
23
24
  type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo, type ScreenshotOptions, type ScrollOptions, type SnapshotNode, type UidStability,
24
- type BandConsumer, type BandedCapture, type CaptureDelivery, type TiledScreenshotResult,
25
+ type BandConsumer, type BandedCapture, type CaptureDelivery, type TiledScreenshotResult, type TextInputPath,
25
26
  } from "../driver.ts";
26
27
  /* ------------------------------ error + uid codec ------------------------------ */
27
28
  function driverError(code: DriverErrorCode, message: string, data?: unknown): DriverError {
@@ -92,6 +93,89 @@ async function centerOf(conn: PageConnection, objectId: string): Promise<{ x: nu
92
93
  if (!result.value) throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
93
94
  return result.value;
94
95
  }
96
+ /**
97
+ * Keyboard input on a BACKGROUND tab. Measured on Vivaldi (Chromium 156) with one page connection
98
+ * held open: on a tab that never had a trusted click, Input.insertText and Input.dispatchKeyEvent
99
+ * (keyDown with text, and type:"char") changed nothing in an input, a textarea or a
100
+ * contenteditable, and no keydown event fired at all. Emulation.setFocusEmulationEnabled made
101
+ * document.hasFocus() true and visibilityState "visible" but did not change that, and element
102
+ * focus() did not either. A trusted click did (hasFocus() true, then insertText landed), and
103
+ * document.execCommand('insertText') landed every time.
104
+ *
105
+ * So the trusted commit stays first, is VERIFIED, and an in-page commit runs only when it did not
106
+ * land. "Landed" means the element's text changed from a snapshot taken just before the commit,
107
+ * or a beforeinput/input event fired on it: never "equals the requested text", or an input mask
108
+ * or maxlength would read as a miss and insert twice.
109
+ */
110
+ const SNAPSHOT_TEXT_FN =
111
+ "function(){var e=this;e.__cdpSawInput=false;var f=function(){e.__cdpSawInput=true;};" +
112
+ "e.addEventListener('beforeinput',f,{capture:true,once:true});e.addEventListener('input',f,{capture:true,once:true});" +
113
+ "return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);}";
114
+ // Re-checked once after a short wait before calling it a miss: a false miss would double-insert.
115
+ const LANDED_TEXT_FN =
116
+ "function(before){var e=this;var now=function(){return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);};" +
117
+ "var hit=function(){return e.__cdpSawInput===true||now()!==before;};" +
118
+ "if(hit())return true;return new Promise(function(r){setTimeout(function(){r(hit());},50);});}";
119
+ const FALLBACK_TEXT_FN =
120
+ "function(t){var e=this;if(e.disabled||e.readOnly)return 'skipped';var ce=e.isContentEditable===true;" +
121
+ "var ta=e instanceof HTMLTextAreaElement;var inp=e instanceof HTMLInputElement&&!/^(checkbox|radio|file|button|submit|reset|image|hidden|range|color)$/i.test(e.type);" +
122
+ "if(!ce&&!ta&&!inp)return 'skipped';e.focus();" +
123
+ "if(ce){var r=document.createRange();r.selectNodeContents(e);r.collapse(false);var s=window.getSelection();s.removeAllRanges();s.addRange(r);}" +
124
+ "else{try{var n=e.value.length;e.setSelectionRange(n,n);}catch(x){}}" +
125
+ "var read=function(){return ce?e.textContent:e.value;};var before=read();" +
126
+ "if(document.execCommand('insertText',false,t)&&read()!==before){e.dispatchEvent(new Event('change',{bubbles:true}));return 'execCommand';}" +
127
+ "if(ce)return 'failed';var proto=ta?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;" +
128
+ "Object.getOwnPropertyDescriptor(proto,'value').set.call(e,before+t);" +
129
+ "e.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertText',data:t}));" +
130
+ "e.dispatchEvent(new Event('change',{bubbles:true}));return 'setter';}";
131
+
132
+ /** Commit `text` at the element's caret: trusted Input.insertText, verified, else in-page. */
133
+ export async function insertTextVerified(
134
+ conn: Pick<PageConnection, "send">,
135
+ objectId: string,
136
+ text: string,
137
+ sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
138
+ ): Promise<TextInputPath> {
139
+ const call = async (fn: string, args: unknown[] = [], awaitPromise = false): Promise<unknown> => {
140
+ const { result, exceptionDetails } = await conn.send<{ result?: { value?: unknown }; exceptionDetails?: { text?: string } }>("Runtime.callFunctionOn", {
141
+ objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise,
142
+ });
143
+ if (exceptionDetails) throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`);
144
+ return result?.value;
145
+ };
146
+ const before = await call(SNAPSHOT_TEXT_FN);
147
+ await sendInput("Input.insertText", { text });
148
+ if ((await call(LANDED_TEXT_FN, [before], true)) === true) return "trusted";
149
+ const via = await call(FALLBACK_TEXT_FN, [text]);
150
+ if (via === "execCommand" || via === "setter" || via === "skipped") return via;
151
+ throw driverError(
152
+ "page-error",
153
+ "text did not land: trusted Input.insertText was not delivered (a background tab gets no trusted keyboard input) and document.execCommand('insertText') changed nothing on this element",
154
+ );
155
+ }
156
+ /**
157
+ * Run a trusted key press and report whether the page saw it. A background tab that never had a
158
+ * trusted click gets no keydown at all (measured, see insertTextVerified), and an untrusted
159
+ * synthetic key could not submit a form or move focus, so nothing is faked: the caller is told
160
+ * { delivered:false } instead. A one-shot capture keydown listener on window is the witness.
161
+ * Unknown is reported as nothing (void), never false: a probe that fails, or a key that
162
+ * navigated the page away, says nothing about delivery. A key handled inside a cross-origin
163
+ * iframe is invisible to the witness, so false is a strong hint, not proof.
164
+ */
165
+ const ARM_KEY_WITNESS =
166
+ "(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()";
167
+ const READ_KEY_WITNESS =
168
+ "(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()";
169
+ export async function pressKeyObserved(conn: Pick<PageConnection, "send">, dispatch: () => Promise<void>): Promise<{ delivered: boolean } | void> {
170
+ const eval_ = (expression: string, awaitPromise = false) =>
171
+ conn.send<{ result?: { value?: unknown } }>("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => undefined);
172
+ const armed = (await eval_(ARM_KEY_WITNESS)) === true;
173
+ await dispatch();
174
+ if (!armed) return;
175
+ const seen = await eval_(READ_KEY_WITNESS, true);
176
+ if (seen === false) return { delivered: false };
177
+ if (seen === true) return { delivered: true };
178
+ }
95
179
  async function focusElement(conn: PageConnection, objectId: string): Promise<void> {
96
180
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
97
181
  }
@@ -130,16 +214,23 @@ async function awaitScrollSettle(conn: PageConnection): Promise<void> {
130
214
  // connection, so this function's dispatch is logged like every other (see ../activity.ts).
131
215
  // It is a parameter rather than a `conn.send` here because the choke point is per-PAGE
132
216
  // (it knows the target id) and this helper only has a connection.
133
- async function setValueOnObject(
217
+ export async function setValueOnObject(
134
218
  conn: PageConnection,
135
219
  objectId: string,
136
220
  value: string,
137
221
  sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
138
- ): Promise<void> {
222
+ ): Promise<TextInputPath> {
139
223
  await focusElement(conn, objectId);
140
- const fn = "function(){if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}}";
141
- await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
142
- if (value.length) await sendInput("Input.insertText", { text: value });
224
+ // A disabled or read-only field is refused BEFORE the clear: clearing it would destroy a value
225
+ // the user could not have changed either, and reporting filled:true for it would be a lie.
226
+ const fn = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}return 'ok';}";
227
+ const { result } = await conn.send<{ result?: { value?: unknown } }>("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
228
+ if (result?.value === "disabled" || result?.value === "readonly") {
229
+ throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`);
230
+ }
231
+ // The one behavioral departure from input.ts: the commit is verified, with an in-page fallback
232
+ // for a background tab (see insertTextVerified).
233
+ return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted";
143
234
  }
144
235
  interface KeySpec { key: string; code: string; keyCode: number; text?: string }
145
236
  // Copied verbatim from src/tools/input.ts `NAMED_KEYS`.
@@ -653,7 +744,7 @@ const CDP_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>([
653
744
  "emulate.mediaFeatures", "emulate.deviceMetrics", "emulate.networkConditions",
654
745
  "screenshot.fullPage", "screenshot.element", "screenshot.scale", "screenshot.renderSize", "screenshot.tile", "network.intercept",
655
746
  "snapshot.accessibilityTree", "input.insertTextAtomic", "locate.text", "locate.xpath",
656
- "capture.screencast", "input.raw", "input.html5Drag", "emulate.focus",
747
+ "capture.screencast", "input.raw", "input.modifierClick", "input.html5Drag", "emulate.focus",
657
748
  "browser.downloads", "browser.permissions", "worker.targets", "frame.targets",
658
749
  ]);
659
750
  /* ---------------------------------- PageDriver ---------------------------------- */
@@ -1060,17 +1151,17 @@ class CdpPageDriver implements PageDriver {
1060
1151
  await this.dispatchInput("Input.setInterceptDrags", { enabled: false }).catch(() => undefined);
1061
1152
  }
1062
1153
  }
1063
- async setValue(loc: ElementLocator, value: string): Promise<void> {
1154
+ async setValue(loc: ElementLocator, value: string): Promise<TextInputPath> {
1064
1155
  const { objectId } = await resolveElementLocator(this.conn, loc);
1065
- await setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
1156
+ return setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
1066
1157
  }
1067
- async typeText(loc: ElementLocator, text: string): Promise<void> {
1158
+ async typeText(loc: ElementLocator, text: string): Promise<TextInputPath> {
1068
1159
  const { objectId } = await resolveElementLocator(this.conn, loc);
1069
1160
  await focusElement(this.conn, objectId);
1070
- if (text.length) await this.dispatchInput("Input.insertText", { text });
1161
+ return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
1071
1162
  }
1072
1163
  // Copied dispatch logic verbatim from src/tools/input.ts `pressKey`.
1073
- async pressKey(press: KeyPress): Promise<void> {
1164
+ async pressKey(press: KeyPress): Promise<{ delivered: boolean } | void> {
1074
1165
  const spec = resolveKey(press.key);
1075
1166
  let modBits = 0;
1076
1167
  for (const m of press.modifiers ?? []) {
@@ -1081,8 +1172,10 @@ class CdpPageDriver implements PageDriver {
1081
1172
  const suppressText = (modBits & ~(MODIFIER_BITS.shift as number)) !== 0;
1082
1173
  const down: Record<string, unknown> = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
1083
1174
  if (spec.text && !suppressText) down.text = spec.text;
1084
- await this.dispatchInput("Input.dispatchKeyEvent", down);
1085
- await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
1175
+ return pressKeyObserved(this.conn, async () => {
1176
+ await this.dispatchInput("Input.dispatchKeyEvent", down);
1177
+ await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
1178
+ });
1086
1179
  }
1087
1180
  async setFiles(loc: ElementLocator, files: readonly string[]): Promise<void> {
1088
1181
  const { objectId } = await resolveElementLocator(this.conn, loc);
@@ -1732,11 +1825,16 @@ export const NEW_TARGET_SETTLE_MS = 2000;
1732
1825
  * this id, capped at NEW_TARGET_SETTLE_MS. The listener is registered BEFORE
1733
1826
  * createTarget because the event can beat the command's response. A browser
1734
1827
  * that never sends the event costs at most the cap, never a failure.
1828
+ *
1829
+ * The tab opens with background:true unless opts.focus is true: a tab the
1830
+ * toolkit opens must not switch the user's visible tab or take keyboard focus.
1831
+ * Without the flag Chromium (Vivaldi included) foregrounds every new tab.
1735
1832
  */
1736
1833
  export async function createSettledTarget(
1737
1834
  conn: Pick<CdpConnection, "send" | "on">,
1738
1835
  url: string,
1739
1836
  settleMs = NEW_TARGET_SETTLE_MS,
1837
+ opts: { focus?: boolean } = {},
1740
1838
  ): Promise<string> {
1741
1839
  const changed = new Set<string>();
1742
1840
  let id = "";
@@ -1749,7 +1847,9 @@ export async function createSettledTarget(
1749
1847
  });
1750
1848
  try {
1751
1849
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => undefined);
1752
- const { targetId } = await conn.send<{ targetId: string }>("Target.createTarget", { url });
1850
+ const create = () => conn.send<{ targetId: string }>("Target.createTarget", { url, background: opts.focus !== true });
1851
+ // A background createTarget still brings the browser app forward on macOS: put the user's app back.
1852
+ const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
1753
1853
  if (!targetId) throw driverError("page-error", "Target.createTarget returned no targetId");
1754
1854
  id = targetId;
1755
1855
  if (!changed.has(targetId)) {
@@ -1776,9 +1876,9 @@ class CdpBrowserDriver implements BrowserDriver {
1776
1876
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
1777
1877
  return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
1778
1878
  }
1779
- async newPage(url?: string): Promise<PageInfo> {
1879
+ async newPage(url?: string, opts?: { focus?: boolean }): Promise<PageInfo> {
1780
1880
  return withBrowserConn(async (conn) => {
1781
- const targetId = await createSettledTarget(conn, url ?? "about:blank");
1881
+ const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
1782
1882
  return { id: targetId, url: url ?? "about:blank", title: "" };
1783
1883
  });
1784
1884
  }
@@ -1787,7 +1887,8 @@ class CdpBrowserDriver implements BrowserDriver {
1787
1887
  * builds), never hardcoded. */
1788
1888
  async closePage(id: string): Promise<{ success: boolean }> {
1789
1889
  return withBrowserConn(async (conn) => {
1790
- const res = await conn.send<{ success?: boolean }>("Target.closeTarget", { targetId: id });
1890
+ // Closing a tab also brings the browser app forward on macOS (measured): put the user's app back.
1891
+ const res = await keepFrontApp(() => conn.send<{ success?: boolean }>("Target.closeTarget", { targetId: id }));
1791
1892
  // Opportunistic, not load-bearing: the beacon socket dies with the tab
1792
1893
  // anyway, and readBeaconOver's dead-connection branch would drop it on the
1793
1894
  // next read. Dropping it here just avoids holding a corpse until then.
package/src/driver.ts CHANGED
@@ -148,11 +148,12 @@ export type Capability =
148
148
  | "input.insertTextAtomic" // atomic value commit, not synthesized keystrokes
149
149
  | "locate.text" // find a node by visible text substring
150
150
  | "locate.xpath" // find a node by xpath
151
- | "input.raw" // raw single mouse-event dispatch (dispatch_mouse's move/down/up primitive); Chrome only
151
+ | "input.raw" // raw single mouse-event dispatch (dispatch_mouse's move/down/up primitive); Chrome, and Firefox 160+ (BiDi)
152
+ | "input.modifierClick" // click with Alt/Control/Meta/Shift held; Chrome, and Firefox 160+ (BiDi key source ticked with the pointer)
152
153
  | "input.html5Drag" // real HTML5 drag events (drag's mode:"html5"); Chrome only, see PageDriver.drag
153
154
  | "emulate.focus" // fake page focus without moving the OS window (focus_emulation / click_focus_gated); Chrome only — BiDi's emulation module has no focus primitive
154
- | "browser.downloads" // capture a file download to a known path (wait_for_download); Chrome only
155
- | "browser.permissions" // grant/reset browser permissions for an origin (grant_permissions); Chrome only
155
+ | "browser.downloads" // capture a file download to a known path (wait_for_download); Chrome, Firefox 160+
156
+ | "browser.permissions" // grant/reset browser permissions for an origin (grant_permissions); Chrome, Firefox 160+
156
157
  | "worker.targets" // address a service/shared worker as a target ("worker:<substr>"), incl. waking an evicted MV3 worker; Chrome only
157
158
  | "frame.targets"; // address an out-of-process (cross-origin) iframe as a target ("frame:<substr>"); Chrome only — same-site iframes are not targets at all
158
159
 
@@ -262,12 +263,23 @@ export interface NavigateResult {
262
263
  waitedFor: "load" | "domcontentloaded" | "committed" | "timeout";
263
264
  }
264
265
 
266
+ /** One raw mouse event for PageDriver.dispatchMouse. `modifiers` are held for this one event only. */
267
+ export interface RawMouseEvent {
268
+ action: "move" | "down" | "up";
269
+ x: number;
270
+ y: number;
271
+ button?: "left" | "right" | "middle";
272
+ clickCount?: number;
273
+ modifiers?: readonly string[];
274
+ }
275
+
265
276
  export interface MouseButtonOptions {
266
277
  button?: "left" | "right" | "middle";
267
278
  clickCount?: number;
268
279
  /** "Alt" | "Control" | "Meta" | "Shift", held for the press/release. CDP bits: Alt=1,
269
- * Control=2, Meta=4, Shift=8 (cdp/driver.ts's inputModifierBits). A non-empty array is
270
- * "unsupported" on the Firefox/BiDi driver today: see click()'s implementation note. */
280
+ * Control=2, Meta=4, Shift=8 (cdp/driver.ts's inputModifierBits). On the Firefox/BiDi driver a
281
+ * non-empty array rides a key input source ticked with the pointer (capability
282
+ * "input.modifierClick", Firefox 160+; an older Firefox gets "unsupported"). */
271
283
  modifiers?: readonly string[];
272
284
  }
273
285
 
@@ -737,6 +749,17 @@ export interface InterceptRule {
737
749
  */
738
750
  export type LifetimeModel = "per-call" | "session";
739
751
 
752
+ /**
753
+ * How a setValue/typeText commit actually reached the page (Chrome driver). "trusted": the
754
+ * Input.insertText commit landed. A background tab never receives trusted keyboard input, so the
755
+ * driver falls back in-page: "execCommand" (document.execCommand('insertText'), which fires real
756
+ * beforeinput/input events) or "setter" (native value setter plus input/change events, for a
757
+ * field execCommand cannot edit). "skipped": type_text on a disabled, read-only or non-text
758
+ * element, which trusted typing would not have changed either (setValue refuses a disabled or
759
+ * read-only field with a page-error instead, before clearing it).
760
+ */
761
+ export type TextInputPath = "trusted" | "execCommand" | "setter" | "skipped";
762
+
740
763
  /** Browser-scoped operations. One per browser process. */
741
764
  export interface BrowserDriver {
742
765
  /** Uid scheme tag owned by this driver, e.g. "cdp" or "bidi". */
@@ -749,11 +772,14 @@ export interface BrowserDriver {
749
772
 
750
773
  /** opts.all: include non-page targets (workers, iframes, ...) when the driver has that concept. */
751
774
  listPages(opts?: { all?: boolean }): Promise<PageInfo[]>;
752
- newPage(url?: string): Promise<PageInfo>;
775
+ /** Opens the tab in the BACKGROUND by default, so the user's active tab and keyboard focus
776
+ * stay put. opts.focus:true opens it in the foreground (the old default). */
777
+ newPage(url?: string, opts?: { focus?: boolean }): Promise<PageInfo>;
753
778
  /** success mirrors the underlying protocol's own success signal when it has one (CDP's
754
779
  * Target.closeTarget); a driver without such a signal reports true once close resolves. */
755
780
  closePage(id: string): Promise<{ success: boolean }>;
756
- /** Bring a page to the front. Also writes the selected-page state file. */
781
+ /** Bring a page to the front: takes the user's active tab and window focus. Only an explicit
782
+ * opt-in may call this (select_page with focus:true); nothing calls it implicitly. */
757
783
  activatePage(id: string): Promise<PageInfo>;
758
784
 
759
785
  /** Acquire a page handle. The caller MUST release() it. Prefer withDriver. */
@@ -874,13 +900,19 @@ export interface PageDriver {
874
900
  * "wheel" input source via input.performActions. Universal: both drivers must implement it
875
901
  * (absent from driver.ts's REQUIRED_CAPABILITIES, unlike dispatch_mouse). */
876
902
  scroll(anchor: ElementLocator | { x: number; y: number } | undefined, opts: ScrollOptions): Promise<{ x: number; y: number }>;
903
+ /** One raw mouse event at viewport coordinates (dispatch_mouse), capability "input.raw". Only
904
+ * the Firefox/BiDi driver implements it on this interface: Chrome's dispatch_mouse is the
905
+ * standalone raw-CDP tool in tools/dispatch-mouse.ts, which has no PageDriver. Callers check the
906
+ * method exists; the Firefox tool handler (bidi-tools.ts) does. */
907
+ dispatchMouse?(event: RawMouseEvent): Promise<void>;
877
908
  /** Overwrite an element's value. One atomic commit under
878
909
  * "input.insertTextAtomic", else synthesized keystrokes, so per-key handlers
879
910
  * on the page WILL fire. Callers must not depend on either behavior. */
880
- setValue(loc: ElementLocator, value: string): Promise<void>;
911
+ setValue(loc: ElementLocator, value: string): Promise<void | TextInputPath>;
881
912
  /** Append text at the focus point without clearing first. */
882
- typeText(loc: ElementLocator, text: string): Promise<void>;
883
- pressKey(press: KeyPress): Promise<void>;
913
+ typeText(loc: ElementLocator, text: string): Promise<void | TextInputPath>;
914
+ /** A driver that can tell returns { delivered:false } when the page saw no keydown. */
915
+ pressKey(press: KeyPress): Promise<void | { delivered: boolean }>;
884
916
  /** Attach absolute file paths to a file input. */
885
917
  setFiles(loc: ElementLocator, files: readonly string[]): Promise<void>;
886
918
 
@@ -1,20 +1,23 @@
1
1
  /**
2
2
  * The complete Firefox tool registry: the 23 tools shared with Chrome (src/shared-tools.ts), the
3
3
  * 7 Firefox-only console/network/mock tools (src/bidi-tools.ts), the 3 lease tools
4
- * (src/leases-tools.ts), and extract_page (src/tools/extract.ts), which is backend-neutral by
5
- * construction (its page work runs entirely through Driver.evaluate). This is what src/neutral.ts
6
- * used to be; it now composes four files instead of reimplementing everything in one.
4
+ * (src/leases-tools.ts), the 2 browser-scoped tools wait_for_download / grant_permissions
5
+ * (src/bidi-browser-tools.ts, Firefox 160+), and extract_page (src/tools/extract.ts), which is
6
+ * backend-neutral by construction (its page work runs entirely through Driver.evaluate). This is
7
+ * what src/neutral.ts used to be; it now composes five files instead of reimplementing everything in one.
7
8
  */
8
9
  import type { BrowserDriver } from "./driver.ts";
9
10
  import type { ToolName } from "./index.ts";
10
11
  import { SHARED_TOOLS } from "./shared-tools.ts";
11
12
  import { BIDI_ONLY_TOOLS } from "./bidi-tools.ts";
12
13
  import { LEASE_TOOLS } from "./leases-tools.ts";
14
+ import { BIDI_BROWSER_TOOLS } from "./bidi-browser-tools.ts";
13
15
  import { extractPage } from "./tools/extract.ts";
14
16
 
15
17
  export const FIREFOX_TOOLS: Partial<Record<ToolName, (driver: BrowserDriver, args: never) => Promise<unknown>>> = {
16
18
  ...SHARED_TOOLS,
17
19
  ...BIDI_ONLY_TOOLS,
18
20
  ...LEASE_TOOLS,
21
+ ...BIDI_BROWSER_TOOLS,
19
22
  extract_page: extractPage,
20
23
  };
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Keep the user's frontmost app in front when a background tab opens (macOS).
3
+ *
4
+ * Measured on a Chromium-based browser: Target.createTarget {background:true} leaves the user's
5
+ * active tab alone but still brings the browser APP in front of whatever app the user is in.
6
+ * CDP has no flag for that, so on macOS the driver notes the frontmost process before the call
7
+ * and, if it changed afterwards, puts it back (System Events, by pid). Off-mac this is a no-op.
8
+ * CDP_RESTORE_FRONT_APP=0 turns it off. Read per call so tests can flip it.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+
12
+ export interface FrontAppOps {
13
+ front(): Promise<number | null>;
14
+ setFront(pid: number): Promise<void>;
15
+ }
16
+
17
+ function run(cmd: string, args: string[]): Promise<string> {
18
+ return new Promise((resolve) => {
19
+ execFile(cmd, args, { timeout: 2_000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
20
+ });
21
+ }
22
+
23
+ export const macFrontAppOps: FrontAppOps = {
24
+ async front() {
25
+ // lsappinfo needs no Automation consent and answers in a few ms.
26
+ const asn = (await run("lsappinfo", ["front"])).trim();
27
+ if (!asn) return null;
28
+ const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
29
+ return m ? Number(m[1]) : null;
30
+ },
31
+ async setFront(pid) {
32
+ await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
33
+ },
34
+ };
35
+
36
+ export function restoreFrontAppEnabled(platform: string = process.platform): boolean {
37
+ return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
38
+ }
39
+
40
+ /**
41
+ * Run `fn` (which may raise the browser app) and put the prior frontmost app back if it lost
42
+ * the front. Checks again after `recheckMs`, since the raise can land just after the CDP reply.
43
+ */
44
+ export async function keepFrontApp<T>(
45
+ fn: () => Promise<T>,
46
+ opts: { ops?: FrontAppOps; enabled?: boolean; recheckMs?: number } = {},
47
+ ): Promise<T> {
48
+ const enabled = opts.enabled ?? restoreFrontAppEnabled();
49
+ if (!enabled) return fn();
50
+ const ops = opts.ops ?? macFrontAppOps;
51
+ const before = await ops.front().catch(() => null);
52
+ const result = await fn();
53
+ if (before === null) return result;
54
+ const fix = async (): Promise<void> => {
55
+ const now = await ops.front().catch(() => null);
56
+ if (now !== null && now !== before) await ops.setFront(before).catch(() => undefined);
57
+ };
58
+ await fix();
59
+ await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
60
+ await fix();
61
+ return result;
62
+ }
@@ -119,7 +119,7 @@ export interface ClaimPageResult {
119
119
  */
120
120
  export async function claimPage(
121
121
  driver: BrowserDriver,
122
- args: { target?: TargetSelector; targetId?: string; url?: string; label?: string; ttlMs?: number } = {},
122
+ args: { target?: TargetSelector; targetId?: string; url?: string; label?: string; ttlMs?: number; focus?: boolean } = {},
123
123
  ): Promise<ClaimPageResult> {
124
124
  const hasTarget = typeof args.target === "string" && args.target.length > 0;
125
125
  const hasTargetId = typeof args.targetId === "string" && args.targetId.length > 0;
@@ -156,7 +156,8 @@ export async function claimPage(
156
156
  // expiry, so the tab stays attributable to `label` after the lease is gone.
157
157
  // Claiming an EXISTING tab (the branches above) records nothing, because
158
158
  // this toolkit did not create it and provenance is not ownership.
159
- const page = await newTrackedPage(driver, backend, { url: args.url, label });
159
+ // Background unless focus:true, same as new_page. focus is ignored on takeover.
160
+ const page = await newTrackedPage(driver, backend, { url: args.url, label, focus: args.focus === true });
160
161
  targetId = page.id;
161
162
  url = page.url;
162
163
  opened = true;
package/src/manifest.ts CHANGED
@@ -56,7 +56,7 @@ export const MANIFEST: ToolSpec[] = [
56
56
  },
57
57
  {
58
58
  "name": "new_page",
59
- "description": "Open a browser tab, optionally claim it; navigation is not awaited.",
59
+ "description": "Open a browser tab in the background, optionally claim it; navigation is not awaited.",
60
60
  "inputSchema": {
61
61
  "type": "object",
62
62
  "properties": {
@@ -83,6 +83,10 @@ export const MANIFEST: ToolSpec[] = [
83
83
  "ttlMs": {
84
84
  "type": "number",
85
85
  "description": "Lease TTL in milliseconds."
86
+ },
87
+ "focus": {
88
+ "type": "boolean",
89
+ "description": "Open in the foreground and take focus; default false (background tab)."
86
90
  }
87
91
  },
88
92
  "required": [],
@@ -112,7 +116,7 @@ export const MANIFEST: ToolSpec[] = [
112
116
  },
113
117
  {
114
118
  "name": "select_page",
115
- "description": "Focus a selected page and persist it as active; target must resolve explicitly.",
119
+ "description": "Persist a page as selected; focus:true also raises it. Target must resolve explicitly.",
116
120
  "inputSchema": {
117
121
  "type": "object",
118
122
  "properties": {
@@ -123,6 +127,10 @@ export const MANIFEST: ToolSpec[] = [
123
127
  "target": {
124
128
  "type": "string",
125
129
  "description": "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
130
+ },
131
+ "focus": {
132
+ "type": "boolean",
133
+ "description": "Also raise the tab and take window focus; default false (selection only)."
126
134
  }
127
135
  },
128
136
  "required": [
@@ -622,7 +630,7 @@ export const MANIFEST: ToolSpec[] = [
622
630
  },
623
631
  {
624
632
  "name": "dispatch_mouse",
625
- "description": "Dispatch one raw mouse event at viewport coordinates; Chrome-only.",
633
+ "description": "Dispatch one raw mouse event at viewport coordinates; Firefox needs 160 or newer.",
626
634
  "inputSchema": {
627
635
  "type": "object",
628
636
  "properties": {
@@ -779,7 +787,7 @@ export const MANIFEST: ToolSpec[] = [
779
787
  },
780
788
  {
781
789
  "name": "grant_permissions",
782
- "description": "Grant or reset browser permissions; permissions are origin-scoped and Chrome-only.",
790
+ "description": "Grant or reset browser permissions; permissions are origin-scoped (Chrome, Firefox 160+).",
783
791
  "inputSchema": {
784
792
  "type": "object",
785
793
  "properties": {
@@ -1714,7 +1722,7 @@ export const MANIFEST: ToolSpec[] = [
1714
1722
  },
1715
1723
  {
1716
1724
  "name": "claim_page",
1717
- "description": "Claim an existing tab or open a fresh one; CLI use is refused.",
1725
+ "description": "Claim an existing tab or open a fresh one in the background; CLI use is refused.",
1718
1726
  "inputSchema": {
1719
1727
  "type": "object",
1720
1728
  "properties": {
@@ -1737,6 +1745,10 @@ export const MANIFEST: ToolSpec[] = [
1737
1745
  "ttlMs": {
1738
1746
  "type": "number",
1739
1747
  "description": "Lease TTL in milliseconds."
1748
+ },
1749
+ "focus": {
1750
+ "type": "boolean",
1751
+ "description": "Fresh tab only: open it in the foreground; default false (background)."
1740
1752
  }
1741
1753
  },
1742
1754
  "required": [],
package/src/origins.ts CHANGED
@@ -261,9 +261,10 @@ export async function originIndex(
261
261
  export async function newTrackedPage(
262
262
  driver: BrowserDriver,
263
263
  backend: LeaseBackend,
264
- opts: { url?: string; label?: string } = {},
264
+ opts: { url?: string; label?: string; focus?: boolean } = {},
265
265
  ): Promise<PageInfo> {
266
- const page = await driver.newPage(opts.url);
266
+ // Background by default: only an explicit focus:true may switch the user's visible tab.
267
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true });
267
268
  await recordOrigin(backend, page.id, { label: opts.label });
268
269
  return page;
269
270
  }
package/src/policy.ts CHANGED
@@ -60,7 +60,8 @@ export const MUTATING_TOOLS: ReadonlySet<string> = new Set([
60
60
  // pages
61
61
  "new_page", // Target.createTarget
62
62
  "close_page", // Target.closeTarget
63
- // borderline: Target.activateTarget raises the tab and steals window focus. A state change.
63
+ // borderline: writes the selected-state file; with focus:true also Target.activateTarget,
64
+ // which raises the tab and takes window focus. A state change either way.
64
65
  "select_page",
65
66
  "navigate_page", // Page.navigate / reload / history
66
67
  "set_cookie",
@@ -95,8 +96,8 @@ export const MUTATING_TOOLS: ReadonlySet<string> = new Set([
95
96
  "dispatch_mouse",
96
97
  "focus_emulation", // Emulation.setFocusEmulationEnabled
97
98
  "click_focus_gated",
98
- "wait_for_download", // borderline: Browser.setDownloadBehavior changes browser state
99
- "grant_permissions", // Browser.grantPermissions
99
+ "wait_for_download", // borderline: Browser.setDownloadBehavior / BiDi browser.setDownloadBehavior changes browser state
100
+ "grant_permissions", // Browser.grantPermissions / BiDi permissions.setPermission
100
101
  // leases: claim installs an activity beacon in the page and writes a lease; release can close a tab
101
102
  "claim_page",
102
103
  "release_page",