cdp-toolkit 3.3.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.
@@ -29,6 +29,7 @@
29
29
  * function through script.callFunction and PARSE its text back into SnapshotNode[], which is
30
30
  * genuinely new integration work, not a reimplementation of the walker itself.
31
31
  */
32
+ import { keepFrontApp } from "../frontApp.ts";
32
33
  import { spawn } from "node:child_process";
33
34
  import { fileURLToPath } from "node:url";
34
35
  import { existsSync } from "node:fs";
@@ -59,7 +60,7 @@ import { takeStampedSnapshot } from "./snapshot.ts";
59
60
  import { selectRule, buildFulfillParams, effectiveAction } from "../tools/network_mock.ts";
60
61
  import type {
61
62
  BrowsingContextId, BrowsingContextInfo, BrowsingContextLocator, BrowsingContextReadinessState,
62
- BrowsingContextCaptureScreenshotParameters, ScriptSharedReference, ScriptRemoteValue, ScriptLocalValue,
63
+ BrowsingContextCaptureScreenshotParameters, BrowsingContextCreateParameters, ScriptSharedReference, ScriptRemoteValue, ScriptLocalValue,
63
64
  ScriptNodeRemoteValue, ScriptExceptionDetails, InputSourceActions, InputPointerSourceAction, InputKeySourceAction,
64
65
  InputWheelSourceAction, NetworkCookie,
65
66
  } from "./protocol.ts";
@@ -1360,8 +1361,12 @@ class BidiPageDriver implements PageDriver {
1360
1361
  await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
1361
1362
  return;
1362
1363
  }
1363
- const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
1364
- await this.callFunctionValue(clear, [], ref);
1364
+ // Refuse a disabled or read-only field before the clear, as the Chrome driver does.
1365
+ const clear = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}return 'ok';}";
1366
+ const state = await this.callFunctionValue(clear, [], ref);
1367
+ if (state === "disabled" || state === "readonly") {
1368
+ throw driverError("page-error", `cannot fill a ${state} field: it was left unchanged`);
1369
+ }
1365
1370
  await this.sendKeys(value);
1366
1371
  }
1367
1372
  async typeText(loc: ElementLocator, text: string): Promise<void> {
@@ -1858,6 +1863,15 @@ class BidiPageDriver implements PageDriver {
1858
1863
  }
1859
1864
  }
1860
1865
 
1866
+ /**
1867
+ * browsingContext.create params for new_page / claim_page. background:true unless focus is
1868
+ * explicitly true: per the BiDi spec a context created without it becomes the active tab, which
1869
+ * switches the user's visible tab. Exported for the unit test (no fake BiDi transport exists).
1870
+ */
1871
+ export function bidiCreateTabParams(opts?: { focus?: boolean }): BrowsingContextCreateParameters {
1872
+ return { type: "tab", background: opts?.focus !== true };
1873
+ }
1874
+
1861
1875
  /* --------------------------------- BrowserDriver --------------------------------- */
1862
1876
  class BidiBrowserDriver implements BrowserDriver {
1863
1877
  readonly scheme = "bidi";
@@ -1878,10 +1892,11 @@ class BidiBrowserDriver implements BrowserDriver {
1878
1892
  conn.release();
1879
1893
  }
1880
1894
  }
1881
- async newPage(url?: string): Promise<PageInfo> {
1895
+ async newPage(url?: string, opts?: { focus?: boolean }): Promise<PageInfo> {
1882
1896
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
1883
1897
  try {
1884
- const { context } = await conn.send("browsingContext.create", { type: "tab" }).catch((e) => { throw mapBidiError(e); });
1898
+ const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => { throw mapBidiError(e); });
1899
+ const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
1885
1900
  // Established fact: navigating the default about:home context to a data: URL is rejected,
1886
1901
  // so a fresh context is created here FIRST and only then navigated, never reused as-is.
1887
1902
  if (url) await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => { throw mapBidiError(e); });
@@ -1893,7 +1908,7 @@ class BidiBrowserDriver implements BrowserDriver {
1893
1908
  async closePage(id: string): Promise<{ success: boolean }> {
1894
1909
  const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
1895
1910
  try {
1896
- await conn.send("browsingContext.close", { context: id }).catch((e) => { throw mapBidiError(e); });
1911
+ await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => { throw mapBidiError(e); }));
1897
1912
  return { success: true };
1898
1913
  } finally {
1899
1914
  conn.release();
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`.
@@ -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
@@ -749,6 +749,17 @@ export interface InterceptRule {
749
749
  */
750
750
  export type LifetimeModel = "per-call" | "session";
751
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
+
752
763
  /** Browser-scoped operations. One per browser process. */
753
764
  export interface BrowserDriver {
754
765
  /** Uid scheme tag owned by this driver, e.g. "cdp" or "bidi". */
@@ -761,11 +772,14 @@ export interface BrowserDriver {
761
772
 
762
773
  /** opts.all: include non-page targets (workers, iframes, ...) when the driver has that concept. */
763
774
  listPages(opts?: { all?: boolean }): Promise<PageInfo[]>;
764
- 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>;
765
778
  /** success mirrors the underlying protocol's own success signal when it has one (CDP's
766
779
  * Target.closeTarget); a driver without such a signal reports true once close resolves. */
767
780
  closePage(id: string): Promise<{ success: boolean }>;
768
- /** 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. */
769
783
  activatePage(id: string): Promise<PageInfo>;
770
784
 
771
785
  /** Acquire a page handle. The caller MUST release() it. Prefer withDriver. */
@@ -894,10 +908,11 @@ export interface PageDriver {
894
908
  /** Overwrite an element's value. One atomic commit under
895
909
  * "input.insertTextAtomic", else synthesized keystrokes, so per-key handlers
896
910
  * on the page WILL fire. Callers must not depend on either behavior. */
897
- setValue(loc: ElementLocator, value: string): Promise<void>;
911
+ setValue(loc: ElementLocator, value: string): Promise<void | TextInputPath>;
898
912
  /** Append text at the focus point without clearing first. */
899
- typeText(loc: ElementLocator, text: string): Promise<void>;
900
- 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 }>;
901
916
  /** Attach absolute file paths to a file input. */
902
917
  setFiles(loc: ElementLocator, files: readonly string[]): Promise<void>;
903
918
 
@@ -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": [
@@ -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",