cdp-toolkit 3.3.0 → 3.5.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/CHANGELOG.md +24 -0
- package/CONTRACT.md +1 -1
- package/README.md +20 -4
- package/dist/bidi/mux-daemon.js +231 -10
- package/dist/cli.js +409 -52
- package/dist/index.js +380 -43
- package/dist/mcp.js +433 -67
- package/package.json +1 -1
- package/src/bidi/driver.ts +21 -6
- package/src/cdp/driver.ts +190 -21
- package/src/cdp/hiddenTabs.ts +285 -0
- package/src/client.ts +12 -3
- package/src/driver.ts +26 -5
- package/src/frontApp.ts +62 -0
- package/src/leases-tools.ts +9 -2
- package/src/leases.ts +6 -0
- package/src/manifest.ts +15 -3
- package/src/mcp.ts +4 -0
- package/src/origins.ts +3 -2
- package/src/policy.ts +2 -1
- package/src/shared-tools.ts +79 -26
- package/src/toolDocs.ts +15 -12
- package/src/types.ts +3 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cdp-toolkit",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.5.0",
|
|
4
4
|
"description": "A lightweight chrome-devtools-mcp alternative: an MCP server + CLI that drives the tabs you name, one target per call over one direct WebSocket, with a bounded timeout on every call, so a stuck page can't wedge your agent or force a /mcp restart. Chrome over CDP and Firefox over WebDriver BiDi, with tools a backend can't run absent from tools/list rather than throwing mid-task. 48 tools (only 5 core tools listed by default, plus search_tools/call_tool to reach the rest) including built-in network mocking, a cookie group, tab leases with human-activity detection, real HTML5 drag-and-drop, raw mouse/scroll dispatch, downloads, permission grants, and tab-to-video screen recording so several agents can drive one browser without stealing each other's tabs or a human's. No Puppeteer, no all-target fan-out.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/bidi/driver.ts
CHANGED
|
@@ -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
|
-
|
|
1364
|
-
|
|
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
|
|
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,8 +7,10 @@
|
|
|
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
|
-
import { chromeLeaseBackend, LeaseConflictError } from "../leases.ts";
|
|
12
|
+
import { chromeLeaseBackend, isLongLivedProcess, LeaseConflictError } from "../leases.ts";
|
|
13
|
+
import { disposeHiddenTabs, existingHiddenTabOwner, hiddenTabOwner, hiddenTabsRequested, type HiddenTabOwner } from "./hiddenTabs.ts";
|
|
12
14
|
import { currentEndpoint } from "../endpoints.ts";
|
|
13
15
|
import { BEACON_READ_EXPRESSION, BEACON_SOURCE, BeaconSessions, RENDERER_PROBE_EXPRESSION, RENDERER_PROBE_TIMEOUT_MS, sendInput } from "../activity.ts";
|
|
14
16
|
import { resolveUid } from "../tools/snapshot.ts";
|
|
@@ -21,7 +23,7 @@ import {
|
|
|
21
23
|
type DragDestination, type DragOptions,
|
|
22
24
|
type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel, type MouseButtonOptions,
|
|
23
25
|
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,
|
|
26
|
+
type BandConsumer, type BandedCapture, type CaptureDelivery, type TiledScreenshotResult, type TextInputPath,
|
|
25
27
|
} from "../driver.ts";
|
|
26
28
|
/* ------------------------------ error + uid codec ------------------------------ */
|
|
27
29
|
function driverError(code: DriverErrorCode, message: string, data?: unknown): DriverError {
|
|
@@ -92,6 +94,89 @@ async function centerOf(conn: PageConnection, objectId: string): Promise<{ x: nu
|
|
|
92
94
|
if (!result.value) throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
|
|
93
95
|
return result.value;
|
|
94
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* Keyboard input on a BACKGROUND tab. Measured on Vivaldi (Chromium 156) with one page connection
|
|
99
|
+
* held open: on a tab that never had a trusted click, Input.insertText and Input.dispatchKeyEvent
|
|
100
|
+
* (keyDown with text, and type:"char") changed nothing in an input, a textarea or a
|
|
101
|
+
* contenteditable, and no keydown event fired at all. Emulation.setFocusEmulationEnabled made
|
|
102
|
+
* document.hasFocus() true and visibilityState "visible" but did not change that, and element
|
|
103
|
+
* focus() did not either. A trusted click did (hasFocus() true, then insertText landed), and
|
|
104
|
+
* document.execCommand('insertText') landed every time.
|
|
105
|
+
*
|
|
106
|
+
* So the trusted commit stays first, is VERIFIED, and an in-page commit runs only when it did not
|
|
107
|
+
* land. "Landed" means the element's text changed from a snapshot taken just before the commit,
|
|
108
|
+
* or a beforeinput/input event fired on it: never "equals the requested text", or an input mask
|
|
109
|
+
* or maxlength would read as a miss and insert twice.
|
|
110
|
+
*/
|
|
111
|
+
const SNAPSHOT_TEXT_FN =
|
|
112
|
+
"function(){var e=this;e.__cdpSawInput=false;var f=function(){e.__cdpSawInput=true;};" +
|
|
113
|
+
"e.addEventListener('beforeinput',f,{capture:true,once:true});e.addEventListener('input',f,{capture:true,once:true});" +
|
|
114
|
+
"return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);}";
|
|
115
|
+
// Re-checked once after a short wait before calling it a miss: a false miss would double-insert.
|
|
116
|
+
const LANDED_TEXT_FN =
|
|
117
|
+
"function(before){var e=this;var now=function(){return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);};" +
|
|
118
|
+
"var hit=function(){return e.__cdpSawInput===true||now()!==before;};" +
|
|
119
|
+
"if(hit())return true;return new Promise(function(r){setTimeout(function(){r(hit());},50);});}";
|
|
120
|
+
const FALLBACK_TEXT_FN =
|
|
121
|
+
"function(t){var e=this;if(e.disabled||e.readOnly)return 'skipped';var ce=e.isContentEditable===true;" +
|
|
122
|
+
"var ta=e instanceof HTMLTextAreaElement;var inp=e instanceof HTMLInputElement&&!/^(checkbox|radio|file|button|submit|reset|image|hidden|range|color)$/i.test(e.type);" +
|
|
123
|
+
"if(!ce&&!ta&&!inp)return 'skipped';e.focus();" +
|
|
124
|
+
"if(ce){var r=document.createRange();r.selectNodeContents(e);r.collapse(false);var s=window.getSelection();s.removeAllRanges();s.addRange(r);}" +
|
|
125
|
+
"else{try{var n=e.value.length;e.setSelectionRange(n,n);}catch(x){}}" +
|
|
126
|
+
"var read=function(){return ce?e.textContent:e.value;};var before=read();" +
|
|
127
|
+
"if(document.execCommand('insertText',false,t)&&read()!==before){e.dispatchEvent(new Event('change',{bubbles:true}));return 'execCommand';}" +
|
|
128
|
+
"if(ce)return 'failed';var proto=ta?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;" +
|
|
129
|
+
"Object.getOwnPropertyDescriptor(proto,'value').set.call(e,before+t);" +
|
|
130
|
+
"e.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertText',data:t}));" +
|
|
131
|
+
"e.dispatchEvent(new Event('change',{bubbles:true}));return 'setter';}";
|
|
132
|
+
|
|
133
|
+
/** Commit `text` at the element's caret: trusted Input.insertText, verified, else in-page. */
|
|
134
|
+
export async function insertTextVerified(
|
|
135
|
+
conn: Pick<PageConnection, "send">,
|
|
136
|
+
objectId: string,
|
|
137
|
+
text: string,
|
|
138
|
+
sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
|
|
139
|
+
): Promise<TextInputPath> {
|
|
140
|
+
const call = async (fn: string, args: unknown[] = [], awaitPromise = false): Promise<unknown> => {
|
|
141
|
+
const { result, exceptionDetails } = await conn.send<{ result?: { value?: unknown }; exceptionDetails?: { text?: string } }>("Runtime.callFunctionOn", {
|
|
142
|
+
objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise,
|
|
143
|
+
});
|
|
144
|
+
if (exceptionDetails) throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`);
|
|
145
|
+
return result?.value;
|
|
146
|
+
};
|
|
147
|
+
const before = await call(SNAPSHOT_TEXT_FN);
|
|
148
|
+
await sendInput("Input.insertText", { text });
|
|
149
|
+
if ((await call(LANDED_TEXT_FN, [before], true)) === true) return "trusted";
|
|
150
|
+
const via = await call(FALLBACK_TEXT_FN, [text]);
|
|
151
|
+
if (via === "execCommand" || via === "setter" || via === "skipped") return via;
|
|
152
|
+
throw driverError(
|
|
153
|
+
"page-error",
|
|
154
|
+
"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",
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Run a trusted key press and report whether the page saw it. A background tab that never had a
|
|
159
|
+
* trusted click gets no keydown at all (measured, see insertTextVerified), and an untrusted
|
|
160
|
+
* synthetic key could not submit a form or move focus, so nothing is faked: the caller is told
|
|
161
|
+
* { delivered:false } instead. A one-shot capture keydown listener on window is the witness.
|
|
162
|
+
* Unknown is reported as nothing (void), never false: a probe that fails, or a key that
|
|
163
|
+
* navigated the page away, says nothing about delivery. A key handled inside a cross-origin
|
|
164
|
+
* iframe is invisible to the witness, so false is a strong hint, not proof.
|
|
165
|
+
*/
|
|
166
|
+
const ARM_KEY_WITNESS =
|
|
167
|
+
"(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()";
|
|
168
|
+
const READ_KEY_WITNESS =
|
|
169
|
+
"(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()";
|
|
170
|
+
export async function pressKeyObserved(conn: Pick<PageConnection, "send">, dispatch: () => Promise<void>): Promise<{ delivered: boolean } | void> {
|
|
171
|
+
const eval_ = (expression: string, awaitPromise = false) =>
|
|
172
|
+
conn.send<{ result?: { value?: unknown } }>("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => undefined);
|
|
173
|
+
const armed = (await eval_(ARM_KEY_WITNESS)) === true;
|
|
174
|
+
await dispatch();
|
|
175
|
+
if (!armed) return;
|
|
176
|
+
const seen = await eval_(READ_KEY_WITNESS, true);
|
|
177
|
+
if (seen === false) return { delivered: false };
|
|
178
|
+
if (seen === true) return { delivered: true };
|
|
179
|
+
}
|
|
95
180
|
async function focusElement(conn: PageConnection, objectId: string): Promise<void> {
|
|
96
181
|
await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
|
|
97
182
|
}
|
|
@@ -130,16 +215,23 @@ async function awaitScrollSettle(conn: PageConnection): Promise<void> {
|
|
|
130
215
|
// connection, so this function's dispatch is logged like every other (see ../activity.ts).
|
|
131
216
|
// It is a parameter rather than a `conn.send` here because the choke point is per-PAGE
|
|
132
217
|
// (it knows the target id) and this helper only has a connection.
|
|
133
|
-
async function setValueOnObject(
|
|
218
|
+
export async function setValueOnObject(
|
|
134
219
|
conn: PageConnection,
|
|
135
220
|
objectId: string,
|
|
136
221
|
value: string,
|
|
137
222
|
sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
|
|
138
|
-
): Promise<
|
|
223
|
+
): Promise<TextInputPath> {
|
|
139
224
|
await focusElement(conn, objectId);
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
225
|
+
// A disabled or read-only field is refused BEFORE the clear: clearing it would destroy a value
|
|
226
|
+
// the user could not have changed either, and reporting filled:true for it would be a lie.
|
|
227
|
+
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';}";
|
|
228
|
+
const { result } = await conn.send<{ result?: { value?: unknown } }>("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
|
|
229
|
+
if (result?.value === "disabled" || result?.value === "readonly") {
|
|
230
|
+
throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`);
|
|
231
|
+
}
|
|
232
|
+
// The one behavioral departure from input.ts: the commit is verified, with an in-page fallback
|
|
233
|
+
// for a background tab (see insertTextVerified).
|
|
234
|
+
return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted";
|
|
143
235
|
}
|
|
144
236
|
interface KeySpec { key: string; code: string; keyCode: number; text?: string }
|
|
145
237
|
// Copied verbatim from src/tools/input.ts `NAMED_KEYS`.
|
|
@@ -1060,17 +1152,17 @@ class CdpPageDriver implements PageDriver {
|
|
|
1060
1152
|
await this.dispatchInput("Input.setInterceptDrags", { enabled: false }).catch(() => undefined);
|
|
1061
1153
|
}
|
|
1062
1154
|
}
|
|
1063
|
-
async setValue(loc: ElementLocator, value: string): Promise<
|
|
1155
|
+
async setValue(loc: ElementLocator, value: string): Promise<TextInputPath> {
|
|
1064
1156
|
const { objectId } = await resolveElementLocator(this.conn, loc);
|
|
1065
|
-
|
|
1157
|
+
return setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
|
|
1066
1158
|
}
|
|
1067
|
-
async typeText(loc: ElementLocator, text: string): Promise<
|
|
1159
|
+
async typeText(loc: ElementLocator, text: string): Promise<TextInputPath> {
|
|
1068
1160
|
const { objectId } = await resolveElementLocator(this.conn, loc);
|
|
1069
1161
|
await focusElement(this.conn, objectId);
|
|
1070
|
-
|
|
1162
|
+
return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
|
|
1071
1163
|
}
|
|
1072
1164
|
// Copied dispatch logic verbatim from src/tools/input.ts `pressKey`.
|
|
1073
|
-
async pressKey(press: KeyPress): Promise<void> {
|
|
1165
|
+
async pressKey(press: KeyPress): Promise<{ delivered: boolean } | void> {
|
|
1074
1166
|
const spec = resolveKey(press.key);
|
|
1075
1167
|
let modBits = 0;
|
|
1076
1168
|
for (const m of press.modifiers ?? []) {
|
|
@@ -1081,8 +1173,10 @@ class CdpPageDriver implements PageDriver {
|
|
|
1081
1173
|
const suppressText = (modBits & ~(MODIFIER_BITS.shift as number)) !== 0;
|
|
1082
1174
|
const down: Record<string, unknown> = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
|
|
1083
1175
|
if (spec.text && !suppressText) down.text = spec.text;
|
|
1084
|
-
|
|
1085
|
-
|
|
1176
|
+
return pressKeyObserved(this.conn, async () => {
|
|
1177
|
+
await this.dispatchInput("Input.dispatchKeyEvent", down);
|
|
1178
|
+
await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
|
|
1179
|
+
});
|
|
1086
1180
|
}
|
|
1087
1181
|
async setFiles(loc: ElementLocator, files: readonly string[]): Promise<void> {
|
|
1088
1182
|
const { objectId } = await resolveElementLocator(this.conn, loc);
|
|
@@ -1732,11 +1826,22 @@ export const NEW_TARGET_SETTLE_MS = 2000;
|
|
|
1732
1826
|
* this id, capped at NEW_TARGET_SETTLE_MS. The listener is registered BEFORE
|
|
1733
1827
|
* createTarget because the event can beat the command's response. A browser
|
|
1734
1828
|
* that never sends the event costs at most the cap, never a failure.
|
|
1829
|
+
*
|
|
1830
|
+
* The tab opens with background:true unless opts.focus is true: a tab the
|
|
1831
|
+
* toolkit opens must not switch the user's visible tab or take keyboard focus.
|
|
1832
|
+
* Without the flag Chromium (Vivaldi included) foregrounds every new tab.
|
|
1833
|
+
*
|
|
1834
|
+
* opts.hidden (the CDP_HIDDEN_TABS path, see ./hiddenTabs.ts) sends {background:true,
|
|
1835
|
+
* hidden:true} instead and skips keepFrontApp: a hidden target activates nothing, so there is no
|
|
1836
|
+
* front app to put back. A hidden target emits its first targetInfoChanged like any other
|
|
1837
|
+
* (measured ~46ms on Vivaldi 156), so the settle wait is unchanged. Without opts.hidden the
|
|
1838
|
+
* params are exactly what they were before hidden tabs existed.
|
|
1735
1839
|
*/
|
|
1736
1840
|
export async function createSettledTarget(
|
|
1737
1841
|
conn: Pick<CdpConnection, "send" | "on">,
|
|
1738
1842
|
url: string,
|
|
1739
1843
|
settleMs = NEW_TARGET_SETTLE_MS,
|
|
1844
|
+
opts: { focus?: boolean; hidden?: boolean } = {},
|
|
1740
1845
|
): Promise<string> {
|
|
1741
1846
|
const changed = new Set<string>();
|
|
1742
1847
|
let id = "";
|
|
@@ -1749,7 +1854,12 @@ export async function createSettledTarget(
|
|
|
1749
1854
|
});
|
|
1750
1855
|
try {
|
|
1751
1856
|
await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => undefined);
|
|
1752
|
-
const
|
|
1857
|
+
const hidden = opts.hidden === true;
|
|
1858
|
+
const params = hidden ? { url, background: true, hidden: true } : { url, background: opts.focus !== true };
|
|
1859
|
+
const create = () => conn.send<{ targetId: string }>("Target.createTarget", params);
|
|
1860
|
+
// A background createTarget still brings the browser app forward on macOS: put the user's app back.
|
|
1861
|
+
// A hidden one does not, and a foreground one is meant to.
|
|
1862
|
+
const { targetId } = opts.focus === true || hidden ? await create() : await keepFrontApp(create);
|
|
1753
1863
|
if (!targetId) throw driverError("page-error", "Target.createTarget returned no targetId");
|
|
1754
1864
|
id = targetId;
|
|
1755
1865
|
if (!changed.has(targetId)) {
|
|
@@ -1763,6 +1873,29 @@ export async function createSettledTarget(
|
|
|
1763
1873
|
off();
|
|
1764
1874
|
}
|
|
1765
1875
|
}
|
|
1876
|
+
/**
|
|
1877
|
+
* Hidden tabs are on: CDP_HIDDEN_TABS is set AND this is the long-lived MCP server. Under the
|
|
1878
|
+
* one-shot CLI a hidden tab would die with the process that created it at exit, so the CLI keeps
|
|
1879
|
+
* the visible path whatever the env says, the same carve-out requireLease makes (../leases.ts).
|
|
1880
|
+
*/
|
|
1881
|
+
export function hiddenTabsEnabled(): boolean {
|
|
1882
|
+
return hiddenTabsRequested() && isLongLivedProcess();
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
/** The current endpoint's hidden-tab owner, created on first use. */
|
|
1886
|
+
function currentHiddenOwner(): HiddenTabOwner {
|
|
1887
|
+
return hiddenTabOwner(currentEndpoint().base, () => ({
|
|
1888
|
+
connect: () => openBrowser(),
|
|
1889
|
+
createSettled: (conn, url, opts) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, opts),
|
|
1890
|
+
}));
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
/** The current endpoint's owner when `id` is one of its live hidden tabs. Never creates one. */
|
|
1894
|
+
function hiddenOwnerOf(id: string): HiddenTabOwner | undefined {
|
|
1895
|
+
const owner = existingHiddenTabOwner(currentEndpoint().base);
|
|
1896
|
+
return owner?.has(id) ? owner : undefined;
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1766
1899
|
class CdpBrowserDriver implements BrowserDriver {
|
|
1767
1900
|
readonly scheme = "cdp";
|
|
1768
1901
|
readonly lifetime: LifetimeModel = "per-call";
|
|
@@ -1774,11 +1907,18 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1774
1907
|
async listPages(opts?: { all?: boolean }): Promise<PageInfo[]> {
|
|
1775
1908
|
const targets = await listTargets();
|
|
1776
1909
|
const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1910
|
+
// `hidden` is set by listTargets on this process's hidden tabs only (./hiddenTabs.ts).
|
|
1911
|
+
return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type, ...(t.hidden ? { hidden: true } : {}) }));
|
|
1912
|
+
}
|
|
1913
|
+
async newPage(url?: string, opts?: { focus?: boolean }): Promise<PageInfo> {
|
|
1914
|
+
// CDP_HIDDEN_TABS (MCP server only): a hidden target on the held owner connection, which
|
|
1915
|
+
// never brings the browser app forward. focus:true keeps the visible path below.
|
|
1916
|
+
if (opts?.focus !== true && hiddenTabsEnabled()) {
|
|
1917
|
+
const id = await currentHiddenOwner().create(url ?? "about:blank");
|
|
1918
|
+
return { id, url: url ?? "about:blank", title: "", hidden: true };
|
|
1919
|
+
}
|
|
1780
1920
|
return withBrowserConn(async (conn) => {
|
|
1781
|
-
const targetId = await createSettledTarget(conn, url ?? "about:blank");
|
|
1921
|
+
const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
|
|
1782
1922
|
return { id: targetId, url: url ?? "about:blank", title: "" };
|
|
1783
1923
|
});
|
|
1784
1924
|
}
|
|
@@ -1786,8 +1926,17 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1786
1926
|
* propagated (defaulting true only when the response omits it, matching newer Chromium
|
|
1787
1927
|
* builds), never hardcoded. */
|
|
1788
1928
|
async closePage(id: string): Promise<{ success: boolean }> {
|
|
1929
|
+
// A hidden tab is closed over its owner (closing it raises nothing, so no keepFrontApp).
|
|
1930
|
+
// Checked regardless of the env, so a tab opened before the env changed still closes cleanly.
|
|
1931
|
+
const owner = hiddenOwnerOf(id);
|
|
1932
|
+
if (owner) {
|
|
1933
|
+
const res = await owner.close(id);
|
|
1934
|
+
if (res.success) beaconSessions.drop(beaconKey(id));
|
|
1935
|
+
return res;
|
|
1936
|
+
}
|
|
1789
1937
|
return withBrowserConn(async (conn) => {
|
|
1790
|
-
|
|
1938
|
+
// Closing a tab also brings the browser app forward on macOS (measured): put the user's app back.
|
|
1939
|
+
const res = await keepFrontApp(() => conn.send<{ success?: boolean }>("Target.closeTarget", { targetId: id }));
|
|
1791
1940
|
// Opportunistic, not load-bearing: the beacon socket dies with the tab
|
|
1792
1941
|
// anyway, and readBeaconOver's dead-connection branch would drop it on the
|
|
1793
1942
|
// next read. Dropping it here just avoids holding a corpse until then.
|
|
@@ -1795,8 +1944,24 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1795
1944
|
return { success: res.success ?? true };
|
|
1796
1945
|
});
|
|
1797
1946
|
}
|
|
1947
|
+
/**
|
|
1948
|
+
* On a hidden tab this REVEALS rather than activates: Target.activateTarget and
|
|
1949
|
+
* Page.bringToFront return ok on a hidden target and show nothing (measured), so it cannot be
|
|
1950
|
+
* brought forward in place. Instead its current URL opens in a new VISIBLE, foreground tab (the
|
|
1951
|
+
* flash is the point: the caller asked to show it), then the hidden tab is closed, and the new
|
|
1952
|
+
* tab's id is returned with `revealedFrom` naming the old one. In-page state that a URL does
|
|
1953
|
+
* not carry (form input, scroll, sessionStorage, a POST result) does not survive the move.
|
|
1954
|
+
*/
|
|
1798
1955
|
async activatePage(id: string): Promise<PageInfo> {
|
|
1799
1956
|
const target = await resolveTarget(id).catch(noSuchTarget);
|
|
1957
|
+
const owner = hiddenOwnerOf(target.id);
|
|
1958
|
+
if (owner) {
|
|
1959
|
+
const url = target.url || "about:blank";
|
|
1960
|
+
const newId = await withBrowserConn((conn) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, { focus: true }));
|
|
1961
|
+
await owner.close(target.id).catch(() => undefined);
|
|
1962
|
+
beaconSessions.drop(beaconKey(target.id));
|
|
1963
|
+
return { id: newId, url, title: target.title, revealedFrom: target.id };
|
|
1964
|
+
}
|
|
1800
1965
|
await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
|
|
1801
1966
|
return { id: target.id, url: target.url, title: target.title };
|
|
1802
1967
|
}
|
|
@@ -1926,13 +2091,17 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1926
2091
|
* path and the CLI's exit path; a tool must never call it (see ../driver.ts). */
|
|
1927
2092
|
async dispose(): Promise<void> {
|
|
1928
2093
|
beaconSessions.clear();
|
|
2094
|
+
// Hidden tabs die with their owner anyway; closing them first is explicit and bounded.
|
|
2095
|
+
await disposeHiddenTabs();
|
|
1929
2096
|
}
|
|
1930
2097
|
}
|
|
1931
2098
|
/** Construct the CDP implementation of the frozen Driver contract. */
|
|
1932
2099
|
export function createCdpDriver(): BrowserDriver { return new CdpBrowserDriver(); }
|
|
1933
2100
|
export { CdpBrowserDriver, CdpPageDriver };
|
|
1934
2101
|
/* ------------------------------------------------------------------------------
|
|
1935
|
-
* CDP methods/domains used: Target.createTarget/closeTarget/activateTarget
|
|
2102
|
+
* CDP methods/domains used: Target.createTarget/closeTarget/activateTarget, plus
|
|
2103
|
+
* Target.attachToTarget, targetDestroyed and Emulation.setDeviceMetricsOverride on the hidden-tab
|
|
2104
|
+
* owner (./hiddenTabs.ts); Page.enable/
|
|
1936
2105
|
* navigate/reload/getFrameTree/loadEventFired/domContentEventFired/frameStoppedLoading/
|
|
1937
2106
|
* captureScreenshot/getLayoutMetrics/javascriptDialogOpening/handleJavaScriptDialog/
|
|
1938
2107
|
* addScriptToEvaluateOnNewDocument (the activity beacon, see ../activity.ts);
|