pi-chrome 0.15.47 → 0.15.49
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 +18 -0
- package/README.md +15 -1
- package/SECURITY.md +1 -1
- package/docs/ARCHITECTURE.md +16 -4
- package/docs/COMPARISON.md +1 -1
- package/extensions/chrome-profile-bridge/browser-extension/manifest.json +1 -1
- package/extensions/chrome-profile-bridge/browser-extension/service_worker.js +161 -91
- package/extensions/chrome-profile-bridge/index.ts +97 -106
- package/package.json +2 -2
- package/test-suite/README.md +18 -0
- package/test-suite/challenges/21-keyboard-modifiers.html +5 -2
- package/test-suite/challenges/43-hard-background.html +42 -0
- package/test-suite/challenges/44-input-reliability.html +105 -0
- package/test-suite/manifest.json +119 -2
- package/test-suite/unit/automation-target.test.mjs +1 -1
- package/test-suite/unit/background-policy.test.mjs +489 -0
- package/test-suite/unit/input-reliability.test.mjs +401 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
// Runtime regressions for the Pi session policy and the real worker dispatch/input paths.
|
|
2
|
+
// Chrome APIs are mocked: these tests prove explicit focus calls, not OS/Spaces behavior.
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import vm from "node:vm";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { stripTypeScriptTypes } from "node:module";
|
|
8
|
+
import { test } from "node:test";
|
|
9
|
+
|
|
10
|
+
const indexSource = fs.readFileSync(new URL("../../extensions/chrome-profile-bridge/index.ts", import.meta.url), "utf8");
|
|
11
|
+
const workerSource = fs.readFileSync(new URL("../../extensions/chrome-profile-bridge/browser-extension/service_worker.js", import.meta.url), "utf8");
|
|
12
|
+
const clone = (value) => JSON.parse(JSON.stringify(value));
|
|
13
|
+
function section(start, end) {
|
|
14
|
+
const from = indexSource.indexOf(start);
|
|
15
|
+
const to = indexSource.indexOf(end, from);
|
|
16
|
+
assert.ok(from >= 0 && to > from, `Missing source section: ${start}`);
|
|
17
|
+
return indexSource.slice(from, to);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Load the shipped policy, existing command handler, and actual tool registrations. Only the
|
|
21
|
+
// bridge/Pi UI/typebox/formatting/filesystem boundaries are replaced; no live server is opened.
|
|
22
|
+
function piHarness({ session = "alpha", send } = {}) {
|
|
23
|
+
const calls = [], tools = new Map(), notices = [], writes = [];
|
|
24
|
+
let authorized = true;
|
|
25
|
+
const ctx = { key: `session:${session}`, title: `Pi Session: ${session}`, cwd: "/fixture", ui: { notify: (...args) => notices.push(args) } };
|
|
26
|
+
const bridge = {
|
|
27
|
+
connected: true, status: () => ({}),
|
|
28
|
+
async send(action, params, timeout, signal) {
|
|
29
|
+
calls.push({ action, params: clone(params), timeout, signal });
|
|
30
|
+
if (signal?.aborted) throw new Error("Chrome command aborted");
|
|
31
|
+
if (send) return send(action, params, timeout, signal);
|
|
32
|
+
if (action === "tab.version") return { capabilities: { hardBackground: true } };
|
|
33
|
+
if (action === "tab.list") return [];
|
|
34
|
+
if (action.startsWith("page.screenshot")) return { dataUrl: "data:image/png;base64,dGVzdA==", method: "cdp" };
|
|
35
|
+
return {};
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
const Type = new Proxy({}, { get: () => (value = {}) => value });
|
|
39
|
+
const sandbox = {
|
|
40
|
+
console, Buffer, Type,
|
|
41
|
+
Date,
|
|
42
|
+
DEFAULT_HOST: "127.0.0.1", DEFAULT_PORT: 17318, DEFAULT_TIMEOUT_MS: 30000, MAX_ELEMENTS: 80,
|
|
43
|
+
BACKGROUND_PARAM_DESCRIPTION: "background policy",
|
|
44
|
+
ChromeProfileBridge: function () { return bridge; },
|
|
45
|
+
requireChromeControlAuthorized() { if (!authorized) throw new Error("Chrome control locked"); },
|
|
46
|
+
sessionCtx: ctx, sessionKeyFor: (c) => c?.key, sessionGroupTitle: (c) => c.title,
|
|
47
|
+
chromeToolsRegistered: false, StringEnum: () => ({}),
|
|
48
|
+
tabActionValues: [], snapshotModeValues: [], waitForValues: [], imageFormatValues: [],
|
|
49
|
+
safeJson: JSON.stringify, truncateText: (s) => s, formatChromeSnapshot: JSON.stringify,
|
|
50
|
+
formatChromeInspect: JSON.stringify, summarizeActionResult: () => "", formatIncludedSnapshotText: (_r, text) => text,
|
|
51
|
+
workspaceCwd: () => ctx.cwd, ...path,
|
|
52
|
+
mkdir: async () => {}, writeFile: async (...args) => writes.push(args),
|
|
53
|
+
};
|
|
54
|
+
const registrations = indexSource.slice(indexSource.indexOf("function registerChromeTools(pi:"), indexSource.lastIndexOf("\n}"));
|
|
55
|
+
vm.runInNewContext(stripTypeScriptTypes([
|
|
56
|
+
section("const bridge = new ChromeProfileBridge(", "\n\tlet chromeAuthorizedUntil:"),
|
|
57
|
+
section("const authorizedBridgeSend =", '\n\tpi.on("session_start",'),
|
|
58
|
+
section("const BACKGROUND_DESC:", "\n\tconst authorizeFor ="),
|
|
59
|
+
registrations,
|
|
60
|
+
"globalThis.send = authorizedBridgeSend; globalThis.background = backgroundHandler;",
|
|
61
|
+
].join("\n")), sandbox);
|
|
62
|
+
sandbox.registerChromeTools({ registerTool: (tool) => tools.set(tool.name, tool) });
|
|
63
|
+
return {
|
|
64
|
+
calls, tools, notices, writes, ctx,
|
|
65
|
+
send: async (...args) => sandbox.send(...args),
|
|
66
|
+
background: (arg) => sandbox.background(ctx, arg),
|
|
67
|
+
tool: (name, params = {}, signal) => tools.get(name).execute("test", params, signal, undefined, ctx),
|
|
68
|
+
authorize: (value) => { authorized = value; },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const flagCases = [
|
|
73
|
+
[{}, false], [{ background: false }, false], [{ background: true }, true],
|
|
74
|
+
[{ foreground: true }, false], [{ foreground: false }, true],
|
|
75
|
+
[{ background: false, foreground: false }, false], [{ background: true, foreground: true }, true],
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
test("session background on overrides all per-call/legacy foreground flags; off preserves per-call background", async () => {
|
|
79
|
+
const h = piHarness();
|
|
80
|
+
for (const mode of ["on", "off"]) {
|
|
81
|
+
await h.background(mode);
|
|
82
|
+
for (const [flags, requestedBackground] of flagCases) {
|
|
83
|
+
const params = Object.freeze({ ...flags, targetId: "2" });
|
|
84
|
+
await h.send("page.snapshot", params);
|
|
85
|
+
const wire = h.calls.at(-1).params;
|
|
86
|
+
assert.equal(wire.background, mode === "on" || requestedBackground);
|
|
87
|
+
assert.equal(wire.foreground, !wire.background);
|
|
88
|
+
assert.equal(wire.sessionKey, "session:alpha");
|
|
89
|
+
assert.equal(wire.sessionGroupTitle, "Pi Session: alpha");
|
|
90
|
+
assert.equal(wire.joinSessionGroup, true);
|
|
91
|
+
assert.deepEqual(params, { ...flags, targetId: "2" }, "caller params not mutated");
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("every registered page tool, tab.new, and chrome_launch(url) use the central policy", async () => {
|
|
97
|
+
const h = piHarness();
|
|
98
|
+
const cases = [
|
|
99
|
+
["chrome_launch", { url: "https://example.test" }, "tab.new"],
|
|
100
|
+
["chrome_tab", { action: "new", group: false, groupTitle: "other" }, "tab.new"],
|
|
101
|
+
["chrome_snapshot", {}, "page.snapshot"], ["chrome_find", { query: "button" }, "page.snapshot"],
|
|
102
|
+
["chrome_inspect", { uid: "el-1" }, "page.inspect"], ["chrome_navigate", { url: "https://example.test" }, "page.navigate"],
|
|
103
|
+
["chrome_evaluate", { expression: "1" }, "page.evaluate"], ["chrome_click", { uid: "el-1" }, "page.click"],
|
|
104
|
+
["chrome_type", { text: "abc" }, "page.type"], ["chrome_fill", { text: "abc" }, "page.fill"],
|
|
105
|
+
["chrome_key", { key: "Enter" }, "page.key"], ["chrome_wait_for", { kind: "expression", value: "true" }, "page.waitFor"],
|
|
106
|
+
["chrome_list_console_messages", {}, "page.console.list"], ["chrome_list_network_requests", {}, "page.network.list"],
|
|
107
|
+
["chrome_get_network_request", { requestId: "1" }, "page.network.get"], ["chrome_screenshot", {}, "page.screenshot"],
|
|
108
|
+
["chrome_hover", {}, "page.hover"], ["chrome_drag", {}, "page.drag"], ["chrome_tap", {}, "page.tap"],
|
|
109
|
+
["chrome_scroll", {}, "page.scroll"], ["chrome_upload_file", { paths: ["fixture.txt"] }, "page.upload"],
|
|
110
|
+
];
|
|
111
|
+
for (const [name, params, action] of cases) {
|
|
112
|
+
await h.tool(name, { ...params, background: false, foreground: true });
|
|
113
|
+
const call = h.calls.at(-1);
|
|
114
|
+
assert.equal(call.action, action === "tab.new" || action === "page.screenshot" ? `${action}.background` : action, name);
|
|
115
|
+
assert.equal(call.params.foreground, false, name);
|
|
116
|
+
assert.equal(call.params.background, true, name);
|
|
117
|
+
if (action === "tab.new") assert.equal(call.params.groupTitle, "Pi Session: alpha");
|
|
118
|
+
}
|
|
119
|
+
assert.equal(h.writes[0][1].toString(), "test", "screenshot tool still writes decoded bytes");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("typing options and verification pass through real tool registrations without bypassing authorization", async () => {
|
|
123
|
+
const h = piHarness({ send: async () => ({ result: { input: "chrome", typing: "keys" }, snapshot: { url: "https://fixture.test" } }) });
|
|
124
|
+
for (const name of ["chrome_type", "chrome_fill"]) {
|
|
125
|
+
assert.equal(h.tools.get(name).parameters.perCharacter.default, false);
|
|
126
|
+
const result = await h.tool(name, { uid: "el-1", text: "hello", perCharacter: true, includeSnapshot: true, domFallback: false });
|
|
127
|
+
assert.equal(h.calls.at(-1).params.perCharacter, true);
|
|
128
|
+
assert.equal(h.calls.at(-1).params.includeSnapshot, true);
|
|
129
|
+
assert.equal(h.calls.at(-1).params.domFallback, false);
|
|
130
|
+
assert.equal(h.calls.at(-1).params.background, true);
|
|
131
|
+
assert.equal(result.details.result.result.typing, "keys");
|
|
132
|
+
assert.equal(result.details.result.snapshot.url, "https://fixture.test");
|
|
133
|
+
}
|
|
134
|
+
h.authorize(false);
|
|
135
|
+
const count = h.calls.length;
|
|
136
|
+
for (const [name, params] of [["chrome_type", { text: "x" }], ["chrome_fill", { text: "x" }], ["chrome_key", { key: "a" }], ["chrome_upload_file", { paths: ["/fixture.txt"] }]]) {
|
|
137
|
+
await assert.rejects(h.tool(name, params), /Chrome control locked/);
|
|
138
|
+
}
|
|
139
|
+
assert.equal(h.calls.length, count);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("activation is rejected before dispatch; existing on/off/toggle/status commands suffice", async () => {
|
|
143
|
+
const h = piHarness();
|
|
144
|
+
await assert.rejects(h.tool("chrome_tab", { action: "activate", targetId: "2", background: false }), /background mode.*\/chrome background off/);
|
|
145
|
+
assert.equal(h.calls.length, 0);
|
|
146
|
+
await h.background("off");
|
|
147
|
+
await h.tool("chrome_tab", { action: "activate", targetId: "2" });
|
|
148
|
+
assert.equal(h.calls.at(-1).params.foreground, true);
|
|
149
|
+
await h.background("toggle");
|
|
150
|
+
await h.background("status");
|
|
151
|
+
assert.match(h.notices.at(-1)[0], /on.*Hard background/);
|
|
152
|
+
for (const arg of ["lock", "unlock", "invalid"]) {
|
|
153
|
+
await h.background(arg);
|
|
154
|
+
assert.match(h.notices.at(-1)[0], /Unknown background setting/);
|
|
155
|
+
await assert.rejects(h.send("tab.activate", {}), /background mode/);
|
|
156
|
+
}
|
|
157
|
+
await h.background("");
|
|
158
|
+
await h.send("tab.activate", {});
|
|
159
|
+
for (const arg of ["true", "1", "on"]) {
|
|
160
|
+
await h.background(arg);
|
|
161
|
+
await assert.rejects(h.send("tab.activate", {}), /background mode/);
|
|
162
|
+
}
|
|
163
|
+
for (const arg of ["false", "0", "off"]) {
|
|
164
|
+
await h.background(arg);
|
|
165
|
+
await h.send("tab.activate", {});
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test("older companions reject background-only wire actions; launch and screenshots never retry unsafe actions", async () => {
|
|
170
|
+
const h = piHarness({ send: async (action) => { throw new Error(`Unknown action: ${action}`); } });
|
|
171
|
+
for (const [tool, params] of [
|
|
172
|
+
["chrome_tab", { action: "new" }], ["chrome_launch", { url: "https://example.test" }],
|
|
173
|
+
["chrome_screenshot", {}], ["chrome_screenshot", { fullPage: true }],
|
|
174
|
+
]) {
|
|
175
|
+
await assert.rejects(h.tool(tool, params), /Reload Pi Chrome Connector/);
|
|
176
|
+
}
|
|
177
|
+
assert.deepEqual(h.calls.map((c) => c.action), ["tab.new.background", "tab.new.background", "page.screenshot.background", "page.screenshot.background"]);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("transport failures propagate without fallback; single dispatch preserves authorization/timeout/signal", async () => {
|
|
181
|
+
const offline = piHarness({ send: async () => { throw new Error("offline"); } });
|
|
182
|
+
await assert.rejects(offline.send("tab.new", {}), /offline/);
|
|
183
|
+
assert.equal(offline.calls.length, 1);
|
|
184
|
+
const h = piHarness(), controller = new AbortController();
|
|
185
|
+
await h.send("tab.new", {}, 900, controller.signal);
|
|
186
|
+
assert.equal(h.calls.length, 1);
|
|
187
|
+
assert.equal(h.calls[0].timeout, 900);
|
|
188
|
+
assert.equal(h.calls[0].signal, controller.signal);
|
|
189
|
+
controller.abort();
|
|
190
|
+
await assert.rejects(h.send("tab.new", {}, 900, controller.signal), /Chrome command aborted/);
|
|
191
|
+
h.authorize(false);
|
|
192
|
+
await assert.rejects(h.send("tab.new", {}), /Chrome control locked/);
|
|
193
|
+
assert.equal(h.calls.length, 2, "locked call does not reach bridge");
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("shared-owner sessions retain independent policies; per-call background still works with mode off", async () => {
|
|
197
|
+
const sharedCalls = [];
|
|
198
|
+
const send = async (action, params) => { sharedCalls.push({ action, params }); return {}; };
|
|
199
|
+
const a = piHarness({ session: "A", send }), b = piHarness({ session: "B", send });
|
|
200
|
+
await b.background("off");
|
|
201
|
+
await a.send("tab.new", { background: false });
|
|
202
|
+
await b.send("tab.new", {});
|
|
203
|
+
assert.equal(sharedCalls[0].params.sessionKey, "session:A");
|
|
204
|
+
assert.equal(sharedCalls[0].params.foreground, false);
|
|
205
|
+
assert.equal(sharedCalls[0].action, "tab.new.background");
|
|
206
|
+
assert.equal(sharedCalls[1].params.sessionKey, "session:B");
|
|
207
|
+
assert.equal(sharedCalls[1].params.foreground, true);
|
|
208
|
+
assert.equal(sharedCalls[1].action, "tab.new");
|
|
209
|
+
await b.send("tab.new", { background: true });
|
|
210
|
+
assert.equal(sharedCalls[2].action, "tab.new.background");
|
|
211
|
+
assert.equal(sharedCalls[2].params.foreground, false);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
function workerHarness({ withWindows = true } = {}) {
|
|
215
|
+
const calls = [];
|
|
216
|
+
const tabs = new Map([
|
|
217
|
+
[1, { id: 1, windowId: 1, active: true, groupId: -1, url: "https://user.test/", title: "User" }],
|
|
218
|
+
[2, { id: 2, windowId: 1, active: false, groupId: -1, url: "https://target.test/", title: "Target" }],
|
|
219
|
+
]);
|
|
220
|
+
let focusedWindow = 1, nextTab = 3, nextWindow = 2;
|
|
221
|
+
const storage = {}, groups = new Map();
|
|
222
|
+
const listener = { addListener() {}, removeListener() {} };
|
|
223
|
+
const chrome = {
|
|
224
|
+
runtime: { id: "test", getManifest: () => ({ version: "0.0.0" }), onInstalled: listener, onStartup: listener },
|
|
225
|
+
alarms: { onAlarm: listener, create() {} }, action: { onClicked: listener }, webNavigation: { onCommitted: listener },
|
|
226
|
+
storage: { session: { get: async (key) => ({ [key]: storage[key] }), set: async (value) => Object.assign(storage, value) } },
|
|
227
|
+
tabs: {
|
|
228
|
+
onUpdated: listener,
|
|
229
|
+
query: async (query = {}) => [...tabs.values()].filter((t) => (!query.active || t.active) && (query.windowId === undefined || query.windowId === t.windowId)).map(clone),
|
|
230
|
+
get: async (id) => { if (!tabs.has(id)) throw new Error("No tab"); return clone(tabs.get(id)); },
|
|
231
|
+
create: async (params) => {
|
|
232
|
+
calls.push({ action: "tabs.create", params });
|
|
233
|
+
const tab = { id: nextTab++, windowId: params.windowId ?? 1, active: params.active, url: params.url, groupId: -1 };
|
|
234
|
+
if (tab.active) for (const t of tabs.values()) if (t.windowId === tab.windowId) t.active = false;
|
|
235
|
+
tabs.set(tab.id, tab);
|
|
236
|
+
return clone(tab);
|
|
237
|
+
},
|
|
238
|
+
update: async (id, params) => {
|
|
239
|
+
calls.push({ action: "tabs.update", id, params });
|
|
240
|
+
const tab = tabs.get(id);
|
|
241
|
+
if (params.active) for (const t of tabs.values()) if (t.windowId === tab.windowId) t.active = false;
|
|
242
|
+
Object.assign(tab, params);
|
|
243
|
+
return clone(tab);
|
|
244
|
+
},
|
|
245
|
+
remove: async (id) => tabs.delete(id),
|
|
246
|
+
group: async ({ groupId, tabIds }) => {
|
|
247
|
+
const id = groupId ?? groups.size + 1;
|
|
248
|
+
if (!groups.has(id)) groups.set(id, { id, windowId: tabs.get(tabIds[0]).windowId });
|
|
249
|
+
for (const tid of tabIds) tabs.get(tid).groupId = id;
|
|
250
|
+
return id;
|
|
251
|
+
},
|
|
252
|
+
ungroup: async (id) => { tabs.get(id).groupId = -1; },
|
|
253
|
+
captureVisibleTab: async () => { calls.push({ action: "captureVisibleTab" }); throw new Error("activation-based capture forbidden"); },
|
|
254
|
+
},
|
|
255
|
+
tabGroups: {
|
|
256
|
+
query: async ({ windowId } = {}) => [...groups.values()].filter((g) => windowId === undefined || g.windowId === windowId).map(clone),
|
|
257
|
+
get: async (id) => groups.get(id),
|
|
258
|
+
update: async (id, props) => Object.assign(groups.get(id), props),
|
|
259
|
+
},
|
|
260
|
+
windows: {
|
|
261
|
+
update: async (id, params) => { calls.push({ action: "windows.update", id, params }); if (params.focused) focusedWindow = id; },
|
|
262
|
+
},
|
|
263
|
+
debugger: {
|
|
264
|
+
onDetach: listener, getTargets: (cb) => cb([]), attach: async () => {}, detach: async () => {},
|
|
265
|
+
sendCommand: (target, method, params, callback) => {
|
|
266
|
+
calls.push({ action: "cdp", target, method, params });
|
|
267
|
+
try { callback(h.cdpResult(method, params)); }
|
|
268
|
+
catch (error) { chrome.runtime.lastError = { message: error.message }; callback(); chrome.runtime.lastError = undefined; }
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
scripting: { executeScript: async () => [{ result: { ok: true, value: { elements: [], url: "https://target.test/" } } }] },
|
|
272
|
+
};
|
|
273
|
+
if (withWindows) chrome.windows.create = async (params) => {
|
|
274
|
+
calls.push({ action: "windows.create", params });
|
|
275
|
+
const id = nextWindow++;
|
|
276
|
+
if (params.focused) focusedWindow = id;
|
|
277
|
+
const tab = { id: nextTab++, windowId: id, active: true, url: params.url, groupId: -1 };
|
|
278
|
+
tabs.set(tab.id, tab);
|
|
279
|
+
return { id, tabs: [clone(tab)] };
|
|
280
|
+
};
|
|
281
|
+
const w = {
|
|
282
|
+
chrome, console, setTimeout, clearTimeout, setInterval: () => 0, clearInterval() {},
|
|
283
|
+
fetch: async () => { throw new Error("no network in unit tests"); }, navigator: { userAgent: "unit-test" },
|
|
284
|
+
};
|
|
285
|
+
w.self = w;
|
|
286
|
+
vm.runInNewContext(workerSource, w);
|
|
287
|
+
w.sleep = async () => {}; // Skip human timing, not CDP dispatch.
|
|
288
|
+
w.resolveTargetInTab = async () => ({ found: true, x: 40, y: 50, tag: "BUTTON" });
|
|
289
|
+
const h = {
|
|
290
|
+
w, chrome, calls, tabs, focusedWindow: () => focusedWindow,
|
|
291
|
+
cdpResult: (method) => method === "Page.captureScreenshot" ? { data: "c2NyZWVuc2hvdA==" }
|
|
292
|
+
: method === "DOM.requestNode" ? { nodeId: 1 }
|
|
293
|
+
: { result: { type: "boolean", value: true, objectId: "file-input" } },
|
|
294
|
+
};
|
|
295
|
+
return h;
|
|
296
|
+
}
|
|
297
|
+
function assertNoFocus(h) {
|
|
298
|
+
assert.equal(h.focusedWindow(), 1);
|
|
299
|
+
assert.equal(h.tabs.get(1).active, true);
|
|
300
|
+
assert.ok(!h.calls.some((c) => c.action === "windows.update" || c.action === "captureVisibleTab" || (c.action === "tabs.update" && c.params.active) || (c.action === "tabs.create" && c.params.active)));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
test("Pi-to-worker background aliases preserve grouping, screenshot output, and ownership-aware cleanup", async () => {
|
|
304
|
+
const h = workerHarness();
|
|
305
|
+
const pi = piHarness({ send: (action, params) => h.w.dispatch(action, params) });
|
|
306
|
+
const opened = await pi.tool("chrome_tab", { action: "new", group: false, groupTitle: "wrong", background: false });
|
|
307
|
+
assert.equal(opened.details.result.group.title, "Pi Session: alpha");
|
|
308
|
+
const launched = await pi.tool("chrome_launch", { url: "https://fixture.test" });
|
|
309
|
+
const shot = await pi.tool("chrome_screenshot", { targetId: "2", background: false });
|
|
310
|
+
assert.equal(shot.details.method, "cdp");
|
|
311
|
+
assert.equal(pi.writes[0][1].toString(), "screenshot");
|
|
312
|
+
assertNoFocus(h);
|
|
313
|
+
await h.w.dispatch("automation.cleanup", { sessionKey: "session:alpha" });
|
|
314
|
+
assert.ok(!h.tabs.has(opened.details.result.tab.id));
|
|
315
|
+
assert.ok(!h.tabs.has(launched.details.result.tab.id));
|
|
316
|
+
assert.ok(h.tabs.has(1) && h.tabs.has(2), "user/adopted tabs survive cleanup");
|
|
317
|
+
assert.equal(h.tabs.get(2).groupId, -1, "adopted tab is safely ungrouped");
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
test("worker advertises support, keeps new tabs inactive, and rejects activation before target resolution", async () => {
|
|
321
|
+
const h = workerHarness();
|
|
322
|
+
assert.equal((await h.w.dispatch("tab.version", {})).capabilities.hardBackground, true);
|
|
323
|
+
for (const flags of [{}, { foreground: false }, { background: true, foreground: true }]) {
|
|
324
|
+
const result = await h.w.dispatch("tab.new", { ...flags, sessionKey: "alpha", groupTitle: "Pi Session: alpha" });
|
|
325
|
+
assert.equal(result.tab.active, false);
|
|
326
|
+
await assert.rejects(h.w.dispatch("tab.activate", { ...flags, targetId: "missing" }), /background mode/);
|
|
327
|
+
}
|
|
328
|
+
assertNoFocus(h);
|
|
329
|
+
const active = await h.w.dispatch("tab.activate", { targetId: "2", foreground: true, background: false });
|
|
330
|
+
assert.equal(active.id, 2);
|
|
331
|
+
assert.equal(active.active, true);
|
|
332
|
+
const opened = await h.w.dispatch("tab.new", { foreground: true });
|
|
333
|
+
assert.equal(opened.tab.active, true);
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
test("background-only worker aliases force safe behavior even with foreground flags", async () => {
|
|
337
|
+
const h = workerHarness();
|
|
338
|
+
const opened = await h.w.dispatch("tab.new.background", { foreground: true, background: false });
|
|
339
|
+
assert.equal(opened.tab.active, false);
|
|
340
|
+
const shot = await h.w.dispatch("page.screenshot.background", { targetId: "2", foreground: true, background: false });
|
|
341
|
+
assert.equal(shot.method, "cdp");
|
|
342
|
+
assertNoFocus(h);
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
test("implicit automation windows stay unfocused; tab fallback stays inactive", async () => {
|
|
346
|
+
for (const withWindows of [true, false]) {
|
|
347
|
+
const h = workerHarness({ withWindows });
|
|
348
|
+
const tab = await h.w.dispatch("page.navigate", { url: "https://fixture.test", waitUntilLoad: false, background: true, foreground: true, sessionKey: "alpha" });
|
|
349
|
+
assert.notEqual(tab.id, 1);
|
|
350
|
+
assertNoFocus(h);
|
|
351
|
+
assert.ok(h.calls.filter((c) => c.action === "windows.create").every((c) => c.params.focused === false));
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
test("all worker page/input paths veto conflicting foreground flags without replacing trusted input", async () => {
|
|
356
|
+
const h = workerHarness();
|
|
357
|
+
const actions = [
|
|
358
|
+
["navigate", { url: "https://target.test/", waitUntilLoad: false }], ["snapshot", {}], ["inspect", { uid: "el-1" }],
|
|
359
|
+
["evaluate", { expression: "true" }], ["waitFor", { kind: "expression", value: "true" }],
|
|
360
|
+
["console.list", {}], ["network.list", {}], ["network.get", { requestId: "1" }],
|
|
361
|
+
["click", { x: 40, y: 50, includeSnapshot: true }], ["fill", { selector: "input", text: "a", submit: true }],
|
|
362
|
+
["type", { selector: "input", text: "a", pressEnter: true }], ["key", { key: "Enter" }], ["hover", { x: 40, y: 50 }],
|
|
363
|
+
["drag", { fromX: 40, fromY: 50, toX: 80, toY: 90 }], ["tap", { x: 40, y: 50 }],
|
|
364
|
+
["scroll", { deltaY: 10 }], ["upload", { selector: "input", paths: ["/fixture.txt"] }],
|
|
365
|
+
];
|
|
366
|
+
for (const [action, params] of actions) {
|
|
367
|
+
const result = await h.w.dispatch(`page.${action}`, { targetId: "2", ...params, background: true, foreground: true, domFallback: false });
|
|
368
|
+
if (["click", "fill", "type", "key", "hover", "drag", "tap", "scroll"].includes(action)) assert.equal((result.result ?? result).input, "chrome", action);
|
|
369
|
+
assertNoFocus(h);
|
|
370
|
+
}
|
|
371
|
+
const methods = new Set(h.calls.filter((c) => c.action === "cdp").map((c) => c.method));
|
|
372
|
+
for (const method of ["Input.dispatchMouseEvent", "Input.dispatchKeyEvent", "Input.dispatchTouchEvent", "DOM.setFileInputFiles"]) assert.ok(methods.has(method), method);
|
|
373
|
+
h.chrome.debugger = undefined;
|
|
374
|
+
for (const action of ["click", "fill"]) {
|
|
375
|
+
await assert.rejects(h.w.dispatch(`page.${action}`, { targetId: "2", selector: "input", text: "a", background: true, domFallback: false }), /chrome.debugger API unavailable/);
|
|
376
|
+
}
|
|
377
|
+
assertNoFocus(h);
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
test("CDP PNG/JPEG screenshots preserve active tabs and pass viewport/quality options", async () => {
|
|
381
|
+
for (const targetId of ["1", "2"]) {
|
|
382
|
+
for (const options of [{}, { format: "png", quality: 70 }, { format: "jpeg", quality: 0 }, { format: "jpeg", quality: 83 }]) {
|
|
383
|
+
const h = workerHarness();
|
|
384
|
+
const result = await h.w.dispatch("page.screenshot", { targetId, background: true, foreground: true, ...options });
|
|
385
|
+
const capture = h.calls.find((c) => c.method === "Page.captureScreenshot");
|
|
386
|
+
const format = options.format ?? "png";
|
|
387
|
+
assert.equal(result.dataUrl, `data:image/${format};base64,c2NyZWVuc2hvdA==`);
|
|
388
|
+
assert.equal(result.method, "cdp");
|
|
389
|
+
assert.equal(result.tab.id, Number(targetId));
|
|
390
|
+
assert.equal(capture.target.tabId, Number(targetId));
|
|
391
|
+
assert.deepEqual(clone(capture.params), { format, fromSurface: true, captureBeyondViewport: false, ...(format === "jpeg" ? { quality: options.quality } : {}) });
|
|
392
|
+
assertNoFocus(h);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
test("screenshot failures never fall back to activation/visible-tab capture", async () => {
|
|
398
|
+
for (const failure of ["attach", "capture", "empty", "missing"]) {
|
|
399
|
+
const h = workerHarness();
|
|
400
|
+
if (failure === "attach") h.chrome.debugger.attach = async () => { throw new Error("permission denied"); };
|
|
401
|
+
else h.cdpResult = () => {
|
|
402
|
+
if (failure === "capture") throw new Error("capture failed");
|
|
403
|
+
return failure === "empty" ? { data: "" } : undefined;
|
|
404
|
+
};
|
|
405
|
+
await assert.rejects(h.w.dispatch("page.screenshot", { targetId: "2", background: true }), /no tab-activation fallback/);
|
|
406
|
+
assertNoFocus(h);
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
test("screenshot does not restore/override a user tab switch during capture; watch mode explicitly activates", async () => {
|
|
411
|
+
const h = workerHarness();
|
|
412
|
+
h.cdpResult = () => {
|
|
413
|
+
h.tabs.get(1).active = false;
|
|
414
|
+
h.tabs.get(2).active = true; // Human selection while CDP is pending.
|
|
415
|
+
return { data: "dGVzdA==" };
|
|
416
|
+
};
|
|
417
|
+
const result = await h.w.dispatch("page.screenshot", { targetId: "1", background: true });
|
|
418
|
+
assert.equal(result.tab.id, 1);
|
|
419
|
+
assert.equal(h.tabs.get(2).active, true);
|
|
420
|
+
assert.ok(!h.calls.some((c) => c.action === "tabs.update" || c.action === "windows.update"));
|
|
421
|
+
|
|
422
|
+
const watch = workerHarness();
|
|
423
|
+
const shot = await watch.w.dispatch("page.screenshot", { targetId: "2", foreground: true, background: false });
|
|
424
|
+
assert.equal(shot.tab.active, true);
|
|
425
|
+
assert.equal(watch.calls.filter((c) => c.action === "tabs.update" && c.params.active).length, 1);
|
|
426
|
+
assert.equal(watch.calls.filter((c) => c.action === "windows.update").length, 1);
|
|
427
|
+
assert.ok(!watch.calls.some((c) => c.action === "captureVisibleTab"));
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
test("challenge 43 grader rejects activation/synthetic input and retains sticky failures", () => {
|
|
431
|
+
const lib = fs.readFileSync(new URL("../_lib.js", import.meta.url), "utf8");
|
|
432
|
+
const html = fs.readFileSync(new URL("../challenges/43-hard-background.html", import.meta.url), "utf8");
|
|
433
|
+
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
|
434
|
+
function page() {
|
|
435
|
+
const listeners = new Map();
|
|
436
|
+
const add = (name, fn) => listeners.set(name, fn);
|
|
437
|
+
const document = {
|
|
438
|
+
hidden: true, get visibilityState() { return this.hidden ? "hidden" : "visible"; }, hasFocus: () => false,
|
|
439
|
+
body: { insertBefore() {} }, createElement: () => ({ style: {} }),
|
|
440
|
+
getElementById: (id) => id === "verify" ? { addEventListener: add } : null,
|
|
441
|
+
addEventListener: add,
|
|
442
|
+
};
|
|
443
|
+
const p = { document, addEventListener: add, location: { search: "" }, URLSearchParams,
|
|
444
|
+
performance: { now: () => 1 }, localStorage: { setItem() {} } };
|
|
445
|
+
p.window = p;
|
|
446
|
+
vm.runInNewContext(`${lib}\n${script}`, p);
|
|
447
|
+
return { p, document, fire: (name, event = {}) => listeners.get(name)(event) };
|
|
448
|
+
}
|
|
449
|
+
const visible = page();
|
|
450
|
+
visible.document.hidden = false;
|
|
451
|
+
assert.throws(() => visible.p.armBackgroundProbe(), /Select another tab/);
|
|
452
|
+
const good = page();
|
|
453
|
+
good.p.armBackgroundProbe();
|
|
454
|
+
assert.throws(() => good.p.armBackgroundProbe(), /Already armed/);
|
|
455
|
+
good.fire("click", { isTrusted: true });
|
|
456
|
+
assert.equal(good.p.__verdict, "PASS");
|
|
457
|
+
good.document.hidden = false;
|
|
458
|
+
good.fire("visibilitychange");
|
|
459
|
+
assert.equal(good.p.__verdict, "FAIL", "late activation must invalidate an earlier pass");
|
|
460
|
+
const synthetic = page();
|
|
461
|
+
synthetic.p.armBackgroundProbe();
|
|
462
|
+
synthetic.fire("click", { isTrusted: false });
|
|
463
|
+
synthetic.fire("click", { isTrusted: true });
|
|
464
|
+
assert.equal(synthetic.p.__verdict, "FAIL", "trusted retry cannot hide synthetic input");
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
test("full-page tiles remain CDP-only, pin the resolved target, and restore both scroll axes after success/failure", async () => {
|
|
468
|
+
for (const fail of [false, true]) {
|
|
469
|
+
const h = workerHarness(), scrolls = [];
|
|
470
|
+
h.w.executeInTab = async (params, fn, args) => {
|
|
471
|
+
assert.equal(params.targetId, 2);
|
|
472
|
+
assert.equal(params.foreground, false);
|
|
473
|
+
if (fn.name === "captureFullPageTiles") return { width: 800, height: 1200, viewportHeight: 600, dpr: 2, originalScrollY: 73, originalScrollX: 31, tiles: [{ y: 0, scrollY: 0 }, { y: 600, scrollY: 600 }] };
|
|
474
|
+
scrolls.push(clone(args));
|
|
475
|
+
};
|
|
476
|
+
let captures = 0;
|
|
477
|
+
h.cdpResult = () => { if (++captures === 2 && fail) throw new Error("tile failed"); return { data: "dGlsZQ==" }; };
|
|
478
|
+
const shot = h.w.dispatch("page.screenshot", { urlIncludes: "target.test", fullPage: true, background: true, foreground: true });
|
|
479
|
+
if (fail) await assert.rejects(shot, /tile failed/);
|
|
480
|
+
else {
|
|
481
|
+
const result = await shot;
|
|
482
|
+
assert.equal(result.method, "cdp");
|
|
483
|
+
assert.equal(result.tiles.length, 2);
|
|
484
|
+
assert.equal(result.dimensions.dpr, 2);
|
|
485
|
+
}
|
|
486
|
+
assert.deepEqual(scrolls, [[0], [600], [73, 31]]);
|
|
487
|
+
assertNoFocus(h);
|
|
488
|
+
}
|
|
489
|
+
});
|