@amd-gaia/agent-ui 0.26.1-rc.2 → 0.27.0-rc.1

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.
Files changed (56) hide show
  1. package/dist/assets/AdvancedSettings-znkqGWxt.js +1 -0
  2. package/dist/assets/AutomationsSettings-By0Cy-Gu.js +1 -0
  3. package/dist/assets/ConnectorsPane-6hKjjRWm.js +1 -0
  4. package/dist/assets/ConnectorsPane-BGI8nBUb.css +1 -0
  5. package/dist/assets/DocumentLibrary-_PZjdm8h.js +5 -0
  6. package/dist/assets/DocumentLibrary-fEMoY7lH.css +1 -0
  7. package/dist/assets/FileBrowser-1goNp4CP.css +1 -0
  8. package/dist/assets/FileBrowser-C_cpUmtN.js +4 -0
  9. package/dist/assets/MemoryDashboard-BEafsLNv.js +1 -0
  10. package/dist/assets/MemoryDashboard-TCZiujy9.css +1 -0
  11. package/dist/assets/MessagingSettings-sBXQSmjR.js +1 -0
  12. package/dist/assets/{MobileAccessModal-CX4NZmr4.css → MobileAccessModal-BrZMaERi.css} +1 -1
  13. package/dist/assets/MobileAccessModal-b23-QxSf.js +2 -0
  14. package/dist/assets/ScheduleManager-BZzEH2-W.css +1 -0
  15. package/dist/assets/ScheduleManager-D_U1Igck.js +1 -0
  16. package/dist/assets/Temml-CCjoacWt.woff2 +0 -0
  17. package/dist/assets/index-BgqO1M5f.js +220 -0
  18. package/dist/assets/index-BiETDNik.css +1 -0
  19. package/dist/assets/useFocusTrap-JsuLBsNA.js +6 -0
  20. package/dist/assets/zap-DmECnAbs.js +1 -0
  21. package/dist/index.html +3 -3
  22. package/dist/sw.js +1 -1
  23. package/main.cjs +130 -40
  24. package/package.json +5 -3
  25. package/preload.cjs +28 -0
  26. package/services/browser-pane/bridge-error.cjs +20 -0
  27. package/services/browser-pane/bridge-server.cjs +496 -0
  28. package/services/browser-pane/cdp-session.cjs +375 -0
  29. package/services/browser-pane/contract.d.ts +448 -0
  30. package/services/browser-pane/dev-servers.cjs +478 -0
  31. package/services/browser-pane/input.cjs +375 -0
  32. package/services/browser-pane/ipc.cjs +267 -0
  33. package/services/browser-pane/navigation-policy.cjs +255 -0
  34. package/services/browser-pane/pane-host.cjs +1686 -0
  35. package/services/browser-pane/picker-world.js +360 -0
  36. package/services/browser-pane/picker.cjs +261 -0
  37. package/services/browser-pane/service-ports.cjs +66 -0
  38. package/services/dev-qa-mode.cjs +32 -0
  39. package/dist/assets/AdvancedSettings-C-9ErldS.js +0 -1
  40. package/dist/assets/AutomationsSettings-CL3K4hLZ.js +0 -1
  41. package/dist/assets/ConnectorsPane-DpGR78cA.js +0 -1
  42. package/dist/assets/ConnectorsPane-w-HLcq3n.css +0 -1
  43. package/dist/assets/DocumentLibrary-BKZdx6rJ.css +0 -1
  44. package/dist/assets/DocumentLibrary-N7tBbt9v.js +0 -5
  45. package/dist/assets/FileBrowser-CO2p3xa2.js +0 -4
  46. package/dist/assets/FileBrowser-CrRQXiPo.css +0 -1
  47. package/dist/assets/MemoryDashboard-1OIrKFIa.js +0 -1
  48. package/dist/assets/MemoryDashboard-B4AO_CU8.css +0 -1
  49. package/dist/assets/MessagingSettings-0AJnsoWA.js +0 -1
  50. package/dist/assets/MobileAccessModal-CnPB1BEN.js +0 -2
  51. package/dist/assets/ScheduleManager-BYOhqnfv.js +0 -1
  52. package/dist/assets/ScheduleManager-DQBnf_IN.css +0 -1
  53. package/dist/assets/index-Bkx-QRv4.css +0 -1
  54. package/dist/assets/index-C-3wCH_s.js +0 -116
  55. package/dist/assets/useT-DuzpQY8p.js +0 -6
  56. package/dist/assets/zap-gF9QDKfa.js +0 -1
@@ -0,0 +1,1686 @@
1
+ // Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * PaneHost owns every tab of the browser pane for one app window. Each tab
6
+ * with a page is a WebContentsView on its own partition, sandboxed and with
7
+ * no preload. The renderer draws the toolbar and a placeholder; this class
8
+ * keeps the native views on top of that placeholder and pushes the whole
9
+ * PaneState to the renderer after every change.
10
+ *
11
+ * Every tab belongs to one chat: the chat shown when it opened, or the
12
+ * new-chat screen (chat null) until its first message makes the chat. The
13
+ * window shows one chat's tabs at a time, and an agent only ever reaches its
14
+ * own chat's tabs. Other chats' pages stay alive, hidden, up to
15
+ * LIVE_VIEW_CAP; past it the least recently shown chat's pages close and
16
+ * load again from their saved history when that chat shows.
17
+ *
18
+ * Hidden always means view.setVisible(false). Offscreen or zero-size bounds
19
+ * stall or freeze page capture, so they are never used to hide a view.
20
+ */
21
+
22
+ "use strict";
23
+
24
+ const { WebContentsView, nativeImage } = require("electron");
25
+ const { attachTabPolicy, classifyNavigation, isLocalPageHost, portOf, reachesAppService } = require("./navigation-policy.cjs");
26
+ const { TabCdp } = require("./cdp-session.cjs");
27
+ const { BridgeError } = require("./bridge-error.cjs");
28
+ const input = require("./input.cjs");
29
+ const { PickerSession } = require("./picker.cjs");
30
+
31
+ /** @typedef {import("./contract").TabId} TabId */
32
+ /** @typedef {import("./contract").ChatKey} ChatKey */
33
+ /** @typedef {import("./contract").TabState} TabState */
34
+ /** @typedef {import("./contract").PaneState} PaneState */
35
+ /** @typedef {import("./contract").RecentPage} RecentPage */
36
+ /** @typedef {import("./contract").CssRect} CssRect */
37
+ /** @typedef {import("./contract").HistoryAction} HistoryAction */
38
+
39
+ const PANE_PARTITION = "persist:gaia-browser-pane";
40
+ // Docks DevTools inside the tab's own view, so it stays in the pane and moves with it.
41
+ const DEVTOOLS_MODE = "bottom";
42
+ const RECENT_LIMIT = 8;
43
+ // Chats whose recent pages are kept; the least recently visited drop first.
44
+ const RECENT_CHATS = 50;
45
+ const ERR_ABORTED = -3;
46
+ // Size a page lays out at before the pane has ever been shown; hidden, it still captures.
47
+ const HIDDEN_BOUNDS = { x: 0, y: 0, width: 1024, height: 768 };
48
+ // Keeps "GAIA is reading this page" up long enough to be seen between quick reads.
49
+ const BUSY_LINGER_MS = 1500;
50
+ // Lets a script redirect fire after load, so the agent reads where the page settled.
51
+ const SETTLE_MS = 400;
52
+ const LOAD_TIMEOUT_MS = 30000;
53
+ const EVAL_TIMEOUT_MS = 15000;
54
+ const ACT_TIMEOUT_MS = 15000;
55
+ // After the user clicks or types in a tab, the agent's input waits this long there.
56
+ const USER_PAUSE_MS = 4000;
57
+ // "GAIA is using this tab" stays up this long after an action, covering the model's think time between steps.
58
+ const ACT_LINGER_MS = 10000;
59
+ // The page reports the agent's own CDP input back as input events for a moment after it lands.
60
+ const AGENT_ECHO_MS = 100;
61
+ // A page may open one popup within this long of a click or keypress, as Chromium allows.
62
+ const POPUP_GESTURE_MS = 5000;
63
+ const USER_INPUT = new Set(["mouseDown", "rawKeyDown", "keyDown", "touchStart"]);
64
+ const CONTROLS = new Set(["shared", "user", "private"]);
65
+ // Electron answers a page's alert, confirm and prompt in this internal webContents
66
+ // listener: a native box over the whole window, and prompt() always cancelled.
67
+ // The pane replaces it so the user answers in the pane and the agent can answer too.
68
+ // tests/electron/pane-dialogs.test.cjs pins the Electron versions this was read in.
69
+ const RUN_DIALOG = "-run-dialog";
70
+ const CANCEL_DIALOGS = "-cancel-dialogs";
71
+ const LEAVE_MESSAGE = "Leave this page? Changes you made may not be saved.";
72
+ // Accepting a "leave this page?" box for a navigation the page started allows the next leave this long.
73
+ const LEAVE_ONCE_MS = 30000;
74
+ const SCRIPT_TIMEOUT_MS = 5000;
75
+ const MAX_SCRIPT_RESULT = 4000;
76
+ const STOPPED_FOR_DIALOG = "A box opened on the page, so GAIA stopped this step there.";
77
+ // Pages kept alive across all chats. Each is a renderer process of roughly 50 to 150 MB,
78
+ // so 12 stays near 1 to 2 GB while holding a QA chat's tabs and a few chats besides.
79
+ const LIVE_VIEW_CAP = 12;
80
+
81
+ /** True when an agent op may read or land on `url`: an origin the user approved, or one of the chat's dev servers (the bridge adds those). */
82
+ function inScope(url, allowedOrigins) {
83
+ let parsed;
84
+ try {
85
+ parsed = new URL(url);
86
+ } catch {
87
+ return false;
88
+ }
89
+ if (parsed.href === "about:blank") return true;
90
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
91
+ return allowedOrigins.includes(parsed.origin);
92
+ }
93
+
94
+ /** True for a page on this computer (localhost, 127.x, ::1, *.localhost): the only pages browser_eval runs on. */
95
+ function isLoopbackUrl(url) {
96
+ try {
97
+ const parsed = new URL(url);
98
+ return (parsed.protocol === "http:" || parsed.protocol === "https:") && isLocalPageHost(parsed.hostname);
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ /** The origin a frame acts as, for approval: its site's, or null when it has no http(s) one. */
105
+ function frameOriginOf(frame) {
106
+ const origin = input.frameOrigin(frame);
107
+ return origin && /^https?:\/\//.test(origin) ? origin : null;
108
+ }
109
+
110
+ /** True for a frame the op was not approved to read: approval is per frame origin, like a page's. */
111
+ function isUnapprovedFrame(frame, allowedOrigins) {
112
+ const origin = input.frameOrigin(frame);
113
+ return origin === null || !allowedOrigins.includes(origin);
114
+ }
115
+
116
+ /** True when `frame` sits somewhere inside `outer`. */
117
+ function isInside(frame, outer) {
118
+ for (let up = frame.parent; up; up = up.parent) if (up === outer) return true;
119
+ return false;
120
+ }
121
+
122
+ /** The unapproved frames a picture must leave out: each one whose ancestors up to the page are all approved. */
123
+ function unapprovedTopFrames(wc, allowedOrigins) {
124
+ const main = wc.mainFrame;
125
+ return main.framesInSubtree.filter((frame) => {
126
+ if (frame === main || !isUnapprovedFrame(frame, allowedOrigins)) return false;
127
+ for (let up = frame.parent; up && up !== main; up = up.parent) {
128
+ if (isUnapprovedFrame(up, allowedOrigins)) return false;
129
+ }
130
+ return true;
131
+ });
132
+ }
133
+
134
+ /**
135
+ * The page script browser_eval runs: the model's expression, awaited, as JSON
136
+ * capped at MAX_SCRIPT_RESULT characters. Elements, functions and cycles are
137
+ * written as short markers.
138
+ */
139
+ function scriptSource(expression) {
140
+ const body = expression.trim().replace(/;+$/, "");
141
+ return `(async () => {
142
+ let value;
143
+ try {
144
+ value = await (
145
+ ${body}
146
+ );
147
+ } catch (e) {
148
+ return { error: (e && e.name ? e.name + ": " : "") + ((e && e.message) || String(e)) };
149
+ }
150
+ const seen = new WeakSet();
151
+ const json = JSON.stringify(value, (key, v) => {
152
+ if (typeof v === "bigint") return v.toString();
153
+ if (typeof v === "function") return "[function]";
154
+ if (typeof Node !== "undefined" && v instanceof Node) return "[" + (v.nodeName || "node").toLowerCase() + " element]";
155
+ if (typeof v === "object" && v !== null) {
156
+ if (seen.has(v)) return "[already shown]";
157
+ seen.add(v);
158
+ }
159
+ return v;
160
+ });
161
+ const text = json === undefined ? "undefined" : json;
162
+ return { text: text.slice(0, ${MAX_SCRIPT_RESULT}), truncated: text.length > ${MAX_SCRIPT_RESULT} };
163
+ })()`;
164
+ }
165
+
166
+ function originOf(url) {
167
+ try {
168
+ const parsed = new URL(url);
169
+ return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+
175
+ function withTimeout(promise, ms, what) {
176
+ let timer;
177
+ const deadline = new Promise((_, reject) => {
178
+ timer = setTimeout(() => reject(new BridgeError("timeout", `${what} took longer than ${ms / 1000} s.`)), ms);
179
+ });
180
+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
181
+ }
182
+
183
+ function isShortcut(input, key) {
184
+ return (
185
+ input.type === "keyDown" &&
186
+ (input.meta || input.control) &&
187
+ input.shift &&
188
+ !input.alt &&
189
+ input.key.toLowerCase() === key
190
+ );
191
+ }
192
+
193
+ /** True for the key that toggles the pane: Cmd or Ctrl, Shift and B. */
194
+ function isToggleShortcut(input) {
195
+ return isShortcut(input, "b");
196
+ }
197
+
198
+ /** True for the key that starts or ends picking elements: Cmd or Ctrl, Shift and S. */
199
+ function isPickShortcut(input) {
200
+ return isShortcut(input, "s");
201
+ }
202
+
203
+ /** A crop as a PNG data URL no wider than maxWidth. */
204
+ function encodeCrop(png, maxWidth) {
205
+ let image = nativeImage.createFromBuffer(png);
206
+ if (image.getSize().width > maxWidth) image = image.resize({ width: maxWidth });
207
+ return image.toPNG().toString("base64");
208
+ }
209
+
210
+ /**
211
+ * Turn the placeholder's CSS rect into view bounds in window DIPs, clipped to
212
+ * the window's content. Null when nothing of it is inside the window.
213
+ *
214
+ * @param {CssRect} rect
215
+ * @param {number} zoomFactor The app window's zoom; CSS px times it gives DIPs.
216
+ * @param {{ width: number, height: number }} content
217
+ * @returns {Electron.Rectangle | null}
218
+ */
219
+ function toViewBounds(rect, zoomFactor, content) {
220
+ const left = Math.max(0, Math.round(rect.x * zoomFactor));
221
+ const top = Math.max(0, Math.round(rect.y * zoomFactor));
222
+ const right = Math.min(content.width, Math.round((rect.x + rect.width) * zoomFactor));
223
+ const bottom = Math.min(content.height, Math.round((rect.y + rect.height) * zoomFactor));
224
+ if (right <= left || bottom <= top) return null;
225
+ return { x: left, y: top, width: right - left, height: bottom - top };
226
+ }
227
+
228
+ function isWebUrl(url) {
229
+ return /^https?:/i.test(url);
230
+ }
231
+
232
+ class PaneHost {
233
+ /**
234
+ * @param {{
235
+ * window: Electron.BrowserWindow,
236
+ * session: Electron.Session,
237
+ * publish: (state: PaneState) => void,
238
+ * blockedPorts: () => number[],
239
+ * recentStore: { load: () => Map<ChatKey, RecentPage[]>, save: (pages: Map<ChatKey, RecentPage[]>) => void },
240
+ * goneChats: Set<string>,
241
+ * onToggleRequest: () => void,
242
+ * onShowRequest: (chat: string) => void,
243
+ * openExternal: (url: string) => void,
244
+ * onPicked: (event: import("./contract").PickEvent) => void,
245
+ * createCdp?: (webContents: Electron.WebContents) => TabCdp,
246
+ * createPicker?: (deps: ConstructorParameters<typeof PickerSession>[0]) => PickerSession,
247
+ * }} deps
248
+ */
249
+ constructor(deps) {
250
+ this.deps = deps;
251
+ this.window = deps.window;
252
+ /** Every chat's tabs; each record's `chat` says whose. */
253
+ /** @type {Map<TabId, { chat: ChatKey, state: TabState, view: Electron.WebContentsView | null }>} */
254
+ this.tabs = new Map();
255
+ /** Each chat's own active tab. A chat with no tabs has no entry. */
256
+ /** @type {Map<ChatKey, TabId>} */
257
+ this.activeByChat = new Map();
258
+ /** @type {ChatKey} The chat the window shows; the bridge's attach answers from it. */
259
+ this.shown = null;
260
+ /** Chats most recently shown first: whose pages to close first past LIVE_VIEW_CAP. */
261
+ /** @type {ChatKey[]} */
262
+ this.recency = [null];
263
+ this.nextId = 1;
264
+ this.visible = false;
265
+ this.occluded = false;
266
+ /** @type {Electron.Rectangle | null} */
267
+ this.bounds = null;
268
+ /** Each chat's recent pages, the chat visited last at the end. */
269
+ /** @type {Map<ChatKey, RecentPage[]>} */
270
+ this.recent = deps.recentStore.load();
271
+ this.disposed = false;
272
+ /** Chats the user deleted, shared by every window this app run; their ids never come back. */
273
+ /** @type {Set<string>} */
274
+ this.gone = deps.goneChats;
275
+ /** @type {{ tabId: TabId, session: PickerSession } | null} */
276
+ this.picker = null;
277
+ this.pickRuns = 0;
278
+ this.nextPickRef = 1;
279
+ }
280
+
281
+ /** The tab the user sees: the shown chat's active tab, or null while that chat has none. */
282
+ get activeTabId() {
283
+ return this.activeByChat.get(this.shown) ?? null;
284
+ }
285
+
286
+ /** @returns {PaneState} */
287
+ state() {
288
+ return {
289
+ chat: this.shown,
290
+ visible: this.visible,
291
+ occluded: this.occluded,
292
+ tabs: this.chatTabs(this.shown).map((t) => ({ ...t.state })),
293
+ activeTabId: this.activeTabId,
294
+ recent: (this.recent.get(this.shown) ?? []).slice(),
295
+ picking: this.picker !== null,
296
+ };
297
+ }
298
+
299
+ // ── Placement ─────────────────────────────────────────────────────────
300
+
301
+ /** @param {CssRect} rect */
302
+ setBounds(rect) {
303
+ const content = this.window.getContentBounds();
304
+ const zoom = this.window.webContents.getZoomFactor();
305
+ this.bounds = toViewBounds(rect, zoom, content);
306
+ this.syncViews();
307
+ }
308
+
309
+ /**
310
+ * The chat the window shows and whether its pane is open, set together so
311
+ * a switch never shows one chat's pages under another's open state. An
312
+ * open pane on a chat with no tabs gets a new tab page.
313
+ *
314
+ * @param {ChatKey} chat
315
+ * @param {boolean} visible
316
+ */
317
+ setView(chat, visible) {
318
+ if (chat !== null) this.requireLiveChat(chat);
319
+ const before = this.shown;
320
+ if (chat !== before) {
321
+ this.stopPicking();
322
+ this.shown = chat;
323
+ this.recency = [chat, ...this.recency.filter((c) => c !== chat)];
324
+ if (before !== null) this.releaseDialogs(before);
325
+ for (const tab of this.chatTabs(chat)) if (tab.saved) this.restoreView(tab);
326
+ }
327
+ this.visible = visible;
328
+ if (!visible) this.stopPicking();
329
+ if (visible && this.activeTabId === null) this.activeByChat.set(chat, this.addTab(chat));
330
+ this.trimViews(chat);
331
+ this.syncViews();
332
+ this.publish();
333
+ }
334
+
335
+ /**
336
+ * The new-chat screen's first message made `sessionId`: its tabs, and the
337
+ * screen itself if it still shows, become that chat's. Idempotent.
338
+ *
339
+ * @param {string} sessionId
340
+ */
341
+ claimDraft(sessionId) {
342
+ this.requireLiveChat(sessionId);
343
+ const moved = this.chatTabs(null);
344
+ for (const tab of moved) tab.chat = sessionId;
345
+ const draftActive = this.activeByChat.get(null);
346
+ this.activeByChat.delete(null);
347
+ if (draftActive !== undefined && !this.activeByChat.has(sessionId)) this.activeByChat.set(sessionId, draftActive);
348
+ const draftPages = this.recent.get(null);
349
+ if (draftPages) {
350
+ this.recent.delete(null);
351
+ for (const page of [...draftPages].reverse()) this.remember(sessionId, page.url, page.title);
352
+ }
353
+ if (this.shown === null) {
354
+ this.shown = sessionId;
355
+ this.recency = [sessionId, ...this.recency.filter((c) => c !== sessionId)];
356
+ }
357
+ this.syncViews();
358
+ this.publish();
359
+ }
360
+
361
+ /**
362
+ * The user deleted the chat: close its tabs, and refuse its id from now on.
363
+ *
364
+ * @param {string} sessionId
365
+ */
366
+ forgetChat(sessionId) {
367
+ this.gone.add(sessionId);
368
+ for (const tab of this.chatTabs(sessionId)) this.dropTab(tab);
369
+ this.activeByChat.delete(sessionId);
370
+ this.recency = this.recency.filter((c) => c !== sessionId);
371
+ if (this.recent.delete(sessionId)) this.deps.recentStore.save(this.recent);
372
+ this.syncViews();
373
+ this.publish();
374
+ }
375
+
376
+ /** @param {string} chat */
377
+ requireLiveChat(chat) {
378
+ if (this.gone.has(chat)) throw new Error(`Chat ${chat} was deleted, so the browser pane has no tabs for it.`);
379
+ }
380
+
381
+ /**
382
+ * While an app overlay covers the pane the live view is hidden, since a
383
+ * native view would paint over the overlay. Resolves with a still frame of
384
+ * the page for the placeholder, or null when no page was showing.
385
+ *
386
+ * @param {boolean} occluded
387
+ * @returns {Promise<string | null>}
388
+ */
389
+ async setOccluded(occluded) {
390
+ const wasShown = this.isShown();
391
+ this.occluded = occluded;
392
+ this.syncViews();
393
+ this.publish();
394
+ const tab = this.shownTab();
395
+ const view = tab && tab.view;
396
+ if (!occluded || !wasShown || !view) return null;
397
+ // A hidden view still captures a fresh frame, so hiding first keeps the overlay clear.
398
+ const image = await view.webContents.capturePage();
399
+ return image.toDataURL();
400
+ }
401
+
402
+ // ── Tabs ──────────────────────────────────────────────────────────────
403
+
404
+ /**
405
+ * A new tab in the shown chat, from the user.
406
+ *
407
+ * @param {string | null} url null opens a new tab page.
408
+ * @returns {TabId}
409
+ */
410
+ openTab(url) {
411
+ return this.openTabIn(this.shown, url);
412
+ }
413
+
414
+ /**
415
+ * A new tab that becomes `chat`'s active tab. A popup opens in its opener's chat.
416
+ *
417
+ * @param {ChatKey} chat
418
+ * @param {string | null} url
419
+ * @returns {TabId}
420
+ */
421
+ openTabIn(chat, url) {
422
+ if (chat !== null) this.requireLiveChat(chat);
423
+ if (chat === this.shown) this.stopPicking();
424
+ const id = this.addTab(chat);
425
+ this.activeByChat.set(chat, id);
426
+ if (url !== null) this.navigateTab(this.requireTab(id), url);
427
+ this.syncViews();
428
+ this.publish();
429
+ return id;
430
+ }
431
+
432
+ /** @param {TabId} id */
433
+ closeTab(id) {
434
+ const tab = this.userTab(id);
435
+ const { chat } = tab;
436
+ const order = this.chatTabs(chat).map((t) => t.state.id);
437
+ const index = order.indexOf(id);
438
+ this.dropTab(tab);
439
+ const rest = order.filter((t) => t !== id);
440
+ if (rest.length === 0) {
441
+ // Closing the chat's last tab leaves a new tab page, never an empty open pane.
442
+ this.activeByChat.set(chat, this.addTab(chat));
443
+ } else if (this.activeByChat.get(chat) === id) {
444
+ this.activeByChat.set(chat, rest[Math.min(index, rest.length - 1)]);
445
+ }
446
+ this.syncViews();
447
+ this.publish();
448
+ }
449
+
450
+ /** @param {TabId} id */
451
+ selectTab(id) {
452
+ const tab = this.userTab(id);
453
+ this.activate(tab);
454
+ }
455
+
456
+ /** Make `tab` its chat's active tab. */
457
+ activate(tab) {
458
+ if (tab.chat === this.shown && tab.state.id !== this.activeTabId) this.stopPicking();
459
+ this.activeByChat.set(tab.chat, tab.state.id);
460
+ this.syncViews();
461
+ this.publish();
462
+ }
463
+
464
+ /**
465
+ * @param {TabId} id
466
+ * @param {string} url Already a full URL; the address bar normalizes what was typed.
467
+ */
468
+ navigate(id, url) {
469
+ this.navigateTab(this.userTab(id), url);
470
+ }
471
+
472
+ navigateTab(tab, url) {
473
+ const verdict = classifyNavigation(url, { blockedPorts: this.deps.blockedPorts() });
474
+ if (!verdict.allowed) {
475
+ tab.state.notice = { kind: "blocked", url, message: verdict.message };
476
+ this.publish();
477
+ return;
478
+ }
479
+ this.load(tab, url).catch((err) => {
480
+ // did-fail-load puts the failure on the tab; this only keeps the rejection handled.
481
+ console.warn(`[browser-pane] ${url} did not finish loading: ${err.message}`);
482
+ });
483
+ }
484
+
485
+ /** Start loading an already-allowed URL; resolves when the page loads, rejects if it doesn't. */
486
+ load(tab, url) {
487
+ const view = this.ensureView(tab);
488
+ tab.leaving = () => this.load(tab, url);
489
+ tab.state.notice = null;
490
+ tab.state.url = url;
491
+ const loading = view.webContents.loadURL(url);
492
+ this.publish();
493
+ return loading;
494
+ }
495
+
496
+ /**
497
+ * @param {TabId} id
498
+ * @param {HistoryAction} action
499
+ */
500
+ history(id, action) {
501
+ this.historyStep(this.userTab(id), action);
502
+ }
503
+
504
+ historyStep(tab, action) {
505
+ if (!tab.view) throw new Error(`Tab ${tab.state.id} has no page to ${action}; open a page in it first.`);
506
+ const wc = tab.view.webContents;
507
+ if (action !== "stop") tab.leaving = () => this.historyLoad(tab, action);
508
+ if (action === "back") wc.navigationHistory.goBack();
509
+ else if (action === "forward") wc.navigationHistory.goForward();
510
+ else if (action === "reload") wc.reload();
511
+ else if (action === "stop") wc.stop();
512
+ else throw new Error(`Unknown history action "${action}"; use back, forward, reload or stop.`);
513
+ }
514
+
515
+ /** Repeat a history step that "leave this page?" stopped, and wait for its load. */
516
+ historyLoad(tab, action) {
517
+ const done = this.nextLoad(tab.view.webContents);
518
+ this.historyStep(tab, action);
519
+ return done;
520
+ }
521
+
522
+ /** @param {TabId} id */
523
+ toggleDevTools(id) {
524
+ const tab = this.userTab(id);
525
+ if (!tab.view) throw new Error(`Tab ${id} has no page to inspect; open a page in it first.`);
526
+ const wc = tab.view.webContents;
527
+ if (wc.isDevToolsOpened()) wc.closeDevTools();
528
+ else wc.openDevTools({ mode: DEVTOOLS_MODE });
529
+ }
530
+
531
+ /**
532
+ * Who may drive a tab: shared with the agent, held by the user (the agent
533
+ * is paused there), or private (the agent can't see it at all).
534
+ *
535
+ * @param {TabId} id
536
+ * @param {import("./contract").TabControl} control
537
+ */
538
+ setControl(id, control) {
539
+ if (!CONTROLS.has(control)) throw new Error(`Unknown tab control "${control}"; use shared, user or private.`);
540
+ const tab = this.userTab(id);
541
+ tab.state.control = control;
542
+ // Resume means go now, not after the last click's pause runs out.
543
+ if (control === "shared") tab.userInputAt = 0;
544
+ this.publish();
545
+ }
546
+
547
+ /**
548
+ * The user's Responsive choice. While it is set, an agent viewport request
549
+ * is reported back to the agent and not applied.
550
+ *
551
+ * @param {TabId} id
552
+ * @param {import("./contract").ViewportChoice | null} choice null fills the pane again.
553
+ */
554
+ async setUserViewport(id, choice) {
555
+ const tab = this.userTab(id);
556
+ tab.state.viewport = choice ? { ...choice, source: "user" } : null;
557
+ this.publish();
558
+ await this.applyViewport(tab);
559
+ }
560
+
561
+ /** Clears the pane's cookies, storage, cache, tab histories and recent pages. Nothing outside the pane. */
562
+ async clearBrowsingData() {
563
+ const ses = this.deps.session;
564
+ await Promise.all([ses.clearStorageData(), ses.clearCache(), ses.clearAuthCache()]);
565
+ this.recent.clear();
566
+ this.deps.recentStore.save(this.recent);
567
+ for (const tab of this.tabs.values()) {
568
+ if (tab.saved) {
569
+ const current = tab.saved.entries[tab.saved.index];
570
+ tab.saved = { entries: [{ url: current.url, title: current.title }], index: 0 };
571
+ tab.state.canGoBack = false;
572
+ tab.state.canGoForward = false;
573
+ }
574
+ if (!tab.view) continue;
575
+ tab.view.webContents.navigationHistory.clear();
576
+ this.readNavigation(tab);
577
+ }
578
+ this.publish();
579
+ }
580
+
581
+ /** @param {TabId} id */
582
+ openExternal(id) {
583
+ const { url } = this.userTab(id).state;
584
+ if (url === null || !isWebUrl(url)) {
585
+ throw new Error(`Tab ${id} has no web page to open in the system browser.`);
586
+ }
587
+ this.deps.openExternal(url);
588
+ }
589
+
590
+ // ── Element picker ────────────────────────────────────────────────────
591
+
592
+ /** Start picking elements on the tab the user is looking at, or end it if it runs. */
593
+ async togglePicking() {
594
+ if (this.picker) {
595
+ this.stopPicking();
596
+ return;
597
+ }
598
+ const tab = this.shownTab();
599
+ if (!tab || !tab.view || tab.state.url === null) {
600
+ throw new Error("There is no page to pick from: open a page in the browser pane first.");
601
+ }
602
+ const wc = tab.view.webContents;
603
+ const run = ++this.pickRuns;
604
+ const session = (this.deps.createPicker || ((d) => new PickerSession(d)))({
605
+ cdp: tab.cdp,
606
+ wc,
607
+ allocateRef: () => `p${this.nextPickRef++}`,
608
+ encodeCrop,
609
+ onSelection: (elements) => this.deps.onPicked({ run, elements }),
610
+ onEnd: () => {
611
+ if (this.picker && this.picker.session === session) {
612
+ this.picker = null;
613
+ this.publish();
614
+ }
615
+ },
616
+ });
617
+ this.picker = { tabId: tab.state.id, session };
618
+ this.publish();
619
+ try {
620
+ await session.start();
621
+ } catch (err) {
622
+ this.picker = null;
623
+ this.publish();
624
+ throw new Error(`Could not start picking elements on ${tab.state.url}: ${err.message}`);
625
+ }
626
+ // Arrow keys and Escape reach the picker only when the page has focus.
627
+ wc.focus();
628
+ }
629
+
630
+ /** End picking, keeping the chips already made. */
631
+ stopPicking() {
632
+ if (!this.picker) return;
633
+ const { session } = this.picker;
634
+ this.picker = null;
635
+ this.publish();
636
+ session.stop().catch((err) => console.error(`[browser-pane] Ending the element picker failed: ${err.message}`));
637
+ }
638
+
639
+ // ── Agent ops (the bridge) ────────────────────────────────────────────
640
+ //
641
+ // Every op that loads or reads a page takes allowedOrigins: this chat's dev
642
+ // servers plus the origins Python's site gate approved for that one call. A
643
+ // page or frame on any other origin is never read or shown in a picture,
644
+ // and a navigation that would land on one while the op runs is stopped.
645
+ //
646
+ // Every op names its chat (sessionId) and only ever finds that chat's
647
+ // tabs: another chat's tab id is "no such tab", like a closed one.
648
+
649
+ /** @param {string} sessionId */
650
+ attachSession(sessionId) {
651
+ if (this.disposed || sessionId !== this.shown || this.gone.has(sessionId)) return { status: "not_in_desktop" };
652
+ return { status: "attached", tabId: this.activeTabId, paneVisible: this.isShown() };
653
+ }
654
+
655
+ /** @param {string} sessionId */
656
+ requireSession(sessionId) {
657
+ if (sessionId !== this.shown || this.gone.has(sessionId)) {
658
+ throw new BridgeError(
659
+ "not_in_desktop",
660
+ "The user switched GAIA desktop to another chat, so this chat can't use the browser pane now. Ask the user to switch back to this chat."
661
+ );
662
+ }
663
+ }
664
+
665
+ /**
666
+ * The tabs the agent may know about: its own chat's, without private ones; an active private tab reads as none.
667
+ *
668
+ * @param {string} sessionId
669
+ */
670
+ listTabs(sessionId) {
671
+ const active = this.activeByChat.get(sessionId) ?? null;
672
+ const visible = this.chatTabs(sessionId).filter(({ state }) => state.control !== "private");
673
+ return {
674
+ tabs: visible.map(({ state }) => ({
675
+ id: state.id,
676
+ url: state.url,
677
+ title: state.title,
678
+ active: state.id === active,
679
+ openedBy: state.openedBy,
680
+ control: state.control,
681
+ })),
682
+ activeTabId: visible.some(({ state }) => state.id === active) ? active : null,
683
+ };
684
+ }
685
+
686
+ /**
687
+ * @param {string} sessionId
688
+ * @param {TabId | null} id null means the chat's active tab, the one the user sees.
689
+ */
690
+ agentTab(sessionId, id) {
691
+ const active = this.activeByChat.get(sessionId);
692
+ if (id === null && active === undefined) {
693
+ throw new BridgeError("no_page", "This chat has no tab in the browser pane yet. Open one with browser_open(url).");
694
+ }
695
+ const tab = this.tabs.get(id === null ? active : id);
696
+ if (tab && tab.state.control === "private" && id === null) {
697
+ throw new BridgeError(
698
+ "private_tab",
699
+ "The user marked the tab they are looking at private, so GAIA can't see or use it. Open your own tab with browser_open(url), or ask the user to switch tabs."
700
+ );
701
+ }
702
+ // Another chat's tab and a private tab are invisible to the agent, so naming one gets the same answer as a closed tab.
703
+ if (!tab || tab.chat !== sessionId || tab.state.control === "private") throw new BridgeError("no_such_tab", `No browser pane tab "${id}"; it may have been closed.`);
704
+ return tab;
705
+ }
706
+
707
+ /** Agent input lands only in a tab the user has not taken over and has not touched in the last few seconds. */
708
+ requireAgentInput(tab) {
709
+ if (tab.state.control === "user") {
710
+ throw new BridgeError(
711
+ "user_active",
712
+ "FAILED: this step was not done. The user took control of this browser tab, so GAIA is paused there. Stop using the browser now. Tell the user which steps are not done, and ask how to continue (they can press Resume in the browser pane)."
713
+ );
714
+ }
715
+ if (Date.now() - tab.userInputAt < USER_PAUSE_MS) {
716
+ throw new BridgeError(
717
+ "user_active",
718
+ "FAILED: this step was not done. The user is clicking or typing in this browser tab right now. Stop using the browser now. Tell the user which steps are not done, and ask how to continue."
719
+ );
720
+ }
721
+ }
722
+
723
+ requirePage(tab, allowedOrigins) {
724
+ const wc = tab.view && tab.view.webContents;
725
+ if (!wc || tab.state.url === null) {
726
+ throw new BridgeError("no_page", "The browser pane shows a new tab page with no web page in it. Open one with browser_open(url).");
727
+ }
728
+ const url = wc.getURL() || tab.state.url;
729
+ if (!inScope(url, allowedOrigins)) {
730
+ throw new BridgeError("off_scope", `The page is on ${originOf(url) || url}, which this call was not approved to read.`, {
731
+ origin: originOf(url) || url,
732
+ });
733
+ }
734
+ return wc;
735
+ }
736
+
737
+ /**
738
+ * Run one agent op on a tab: shows the strip, and stops navigations off the
739
+ * allowed origins. An acting op shows "GAIA is using this tab", which stays
740
+ * up between the agent's steps; touching the page then takes the tab over.
741
+ */
742
+ async withAgent(tab, allowedOrigins, fn, { acting = false } = {}) {
743
+ tab.busy = (tab.busy || 0) + 1;
744
+ clearTimeout(tab.busyTimer);
745
+ tab.state.agentBusy = true;
746
+ if (acting) {
747
+ clearTimeout(tab.actTimer);
748
+ tab.state.agentActing = true;
749
+ }
750
+ tab.scope = { allowed: allowedOrigins, blocked: null };
751
+ this.publish();
752
+ try {
753
+ const result = await fn();
754
+ if (tab.scope.blocked) throw this.blockedError(tab.scope.blocked);
755
+ return result;
756
+ } finally {
757
+ tab.scope = null;
758
+ tab.busy -= 1;
759
+ if (tab.busy === 0) {
760
+ tab.busyTimer = setTimeout(() => {
761
+ if (tab.busy !== 0 || !this.tabs.has(tab.state.id)) return;
762
+ tab.state.agentBusy = false;
763
+ this.publish();
764
+ }, BUSY_LINGER_MS);
765
+ tab.busyTimer.unref?.();
766
+ }
767
+ if (acting) {
768
+ tab.actTimer = setTimeout(() => {
769
+ if (!this.tabs.has(tab.state.id)) return;
770
+ tab.state.agentActing = false;
771
+ this.publish();
772
+ }, ACT_LINGER_MS);
773
+ tab.actTimer.unref?.();
774
+ }
775
+ }
776
+ }
777
+
778
+ blockedError(url) {
779
+ const origin = originOf(url) || url;
780
+ return new BridgeError("blocked_navigation", `Stopped the page from going to ${url}; ${origin} was not approved.`, { url, origin });
781
+ }
782
+
783
+ /** @param {string} sessionId @param {string} url @param {string[]} allowedOrigins */
784
+ async agentOpen(sessionId, url, allowedOrigins) {
785
+ this.checkAgentUrl(url, allowedOrigins);
786
+ const resolving = this.checkAgentAddress(url);
787
+ if (resolving) await resolving;
788
+ const id = this.addTab(sessionId);
789
+ const tab = this.requireTab(id);
790
+ tab.state.openedBy = sessionId;
791
+ if (sessionId === this.shown) this.stopPicking();
792
+ this.activeByChat.set(sessionId, id);
793
+ this.syncViews();
794
+ this.deps.onShowRequest(sessionId);
795
+ await this.withAgent(tab, allowedOrigins, () => this.agentLoad(tab, url));
796
+ return this.listTabs(sessionId);
797
+ }
798
+
799
+ /** browser_tabs(switch_to): show one of the chat's own tabs. */
800
+ agentSelect(sessionId, id) {
801
+ this.activate(this.agentTab(sessionId, id));
802
+ return this.listTabs(sessionId);
803
+ }
804
+
805
+ /**
806
+ * @param {string} sessionId
807
+ * @param {TabId | null} id
808
+ * @param {string} to A URL, or back, forward or reload.
809
+ * @param {string[]} allowedOrigins
810
+ */
811
+ async agentNavigate(sessionId, id, to, allowedOrigins) {
812
+ const tab = this.agentTab(sessionId, id);
813
+ this.requireAgentInput(tab);
814
+ this.requireNoDialog(tab);
815
+ if (to === "back" || to === "forward" || to === "reload") {
816
+ if (!tab.view) throw new BridgeError("no_page", "This tab has no page yet, so it has no history.");
817
+ const wc = tab.view.webContents;
818
+ const nav = wc.navigationHistory;
819
+ if (to === "back" && !nav.canGoBack()) throw new BridgeError("navigation_failed", "There is no earlier page in this tab.", { url: wc.getURL() });
820
+ if (to === "forward" && !nav.canGoForward()) throw new BridgeError("navigation_failed", "There is no later page in this tab.", { url: wc.getURL() });
821
+ // History moves no will-navigate sees, so the page it lands on is checked before it moves.
822
+ const entries = nav.getAllEntries();
823
+ const step = { back: -1, forward: 1, reload: 0 }[to];
824
+ const dest = (entries[nav.getActiveIndex() + step] || {}).url || "";
825
+ if (!inScope(dest, allowedOrigins)) throw this.offScopeError(dest, "open");
826
+ await this.withAgent(tab, allowedOrigins, async () => {
827
+ const done = this.nextLoad(wc);
828
+ this.historyStep(tab, to);
829
+ const went = await this.raceDialog(tab, done);
830
+ if (went.dialog) throw this.dialogError(went.dialog);
831
+ await this.settle(wc);
832
+ });
833
+ } else {
834
+ this.checkAgentUrl(to, allowedOrigins);
835
+ const resolving = this.checkAgentAddress(to);
836
+ if (resolving) await resolving;
837
+ this.deps.onShowRequest(sessionId);
838
+ await this.withAgent(tab, allowedOrigins, () => this.agentLoad(tab, to));
839
+ }
840
+ const wc = tab.view.webContents;
841
+ // Where a page lands is the agent's to read only on an approved site.
842
+ if (!inScope(wc.getURL(), allowedOrigins)) throw this.offScopeError(wc.getURL(), "read");
843
+ return { tabId: tab.state.id, url: wc.getURL(), title: wc.getTitle() };
844
+ }
845
+
846
+ /** A page or frame on a site this call was not approved for; names the site, never the address or title. */
847
+ offScopeError(url, verb) {
848
+ const origin = originOf(url) || "a page that is not a web address";
849
+ return new BridgeError("off_scope", `The page is on ${origin}, which this call was not approved to ${verb}.`, { origin });
850
+ }
851
+
852
+ /**
853
+ * Refuse an address whose name resolves to one of GAIA's own services on
854
+ * this computer. Only an address on one of those ports needs the lookup, so
855
+ * any other returns null at once and the load starts without waiting.
856
+ */
857
+ checkAgentAddress(url) {
858
+ const parsed = new URL(url);
859
+ const ports = this.deps.blockedPorts();
860
+ if (!ports.includes(portOf(parsed))) return null;
861
+ return reachesAppService(parsed, ports, this.deps.lookup).then((reaches) => {
862
+ if (reaches) throw new BridgeError("blocked_url", "The browser pane can't open GAIA's own service.", { url });
863
+ });
864
+ }
865
+
866
+ checkAgentUrl(url, allowedOrigins) {
867
+ const verdict = classifyNavigation(url, { blockedPorts: this.deps.blockedPorts() });
868
+ if (!verdict.allowed) throw new BridgeError("blocked_url", verdict.message, { url });
869
+ if (!inScope(url, allowedOrigins)) throw this.blockedError(url);
870
+ }
871
+
872
+ async agentLoad(tab, url) {
873
+ try {
874
+ const loaded = await this.raceDialog(tab, withTimeout(this.load(tab, url), LOAD_TIMEOUT_MS, `Loading ${url}`));
875
+ if (loaded.dialog) throw this.dialogError(loaded.dialog);
876
+ } catch (err) {
877
+ if (tab.scope && tab.scope.blocked) throw this.blockedError(tab.scope.blocked);
878
+ // "Leave this page?" stops the load first; the box is the answer, not the failed load.
879
+ if (tab.state.dialog) throw this.dialogError(tab.state.dialog);
880
+ if (err instanceof BridgeError) throw err;
881
+ throw new BridgeError("navigation_failed", err.message, { url });
882
+ }
883
+ await this.settle(tab.view.webContents);
884
+ }
885
+
886
+ /** Resolves when the next navigation in `wc` finishes, or rejects after LOAD_TIMEOUT_MS. */
887
+ nextLoad(wc) {
888
+ let done;
889
+ const finished = new Promise((resolve) => {
890
+ done = resolve;
891
+ wc.once("did-stop-loading", done);
892
+ // A same-document history step never starts loading, so it never stops either.
893
+ wc.once("did-navigate-in-page", done);
894
+ });
895
+ return withTimeout(finished, LOAD_TIMEOUT_MS, "The page").finally(() => {
896
+ wc.removeListener("did-stop-loading", done);
897
+ wc.removeListener("did-navigate-in-page", done);
898
+ });
899
+ }
900
+
901
+ /** Wait briefly for a script redirect, and for its load if one starts. */
902
+ async settle(wc) {
903
+ let started = false;
904
+ const onStart = (details) => {
905
+ if (details && details.isMainFrame && !details.isSameDocument) started = true;
906
+ };
907
+ wc.on("did-start-navigation", onStart);
908
+ await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));
909
+ wc.removeListener("did-start-navigation", onStart);
910
+ if (started && wc.isLoading()) await this.nextLoad(wc).catch(() => {});
911
+ }
912
+
913
+ /**
914
+ * Run a script in the page's frames. The script is Python's own (the
915
+ * snapshot or find script), never text from the model.
916
+ */
917
+ async agentEvaluate(sessionId, id, script, args, frames, allowedOrigins) {
918
+ const tab = this.agentTab(sessionId, id);
919
+ const wc = this.requirePage(tab, allowedOrigins);
920
+ this.requireNoDialog(tab);
921
+ return this.withAgent(tab, allowedOrigins, async () => {
922
+ const main = wc.mainFrame;
923
+ const targets = frames === "all" ? [main, ...main.framesInSubtree.filter((f) => f !== main)] : [main];
924
+ const code = `(${script})(${JSON.stringify(args)})`;
925
+ const results = [];
926
+ for (const frame of targets) {
927
+ const frameId = frame === main ? null : `${frame.processId}:${frame.routingId}`;
928
+ // A frame from another site is read only once that site is approved, like a page on it.
929
+ if (frame !== main && isUnapprovedFrame(frame, allowedOrigins)) {
930
+ const origin = frameOriginOf(frame);
931
+ results.push({ frameId, url: frame.url, ok: false, error: `Not read: a frame from ${origin || frame.url}, which was not approved.`, unapproved: origin });
932
+ continue;
933
+ }
934
+ try {
935
+ const read = await this.raceDialog(tab, withTimeout(frame.executeJavaScript(code, false), EVAL_TIMEOUT_MS, "Reading the page"));
936
+ if (read.dialog) throw this.dialogError(read.dialog);
937
+ results.push({ frameId, url: frame.url, ok: true, value: read.value });
938
+ } catch (err) {
939
+ if (err instanceof BridgeError && err.code === "dialog_open") throw err;
940
+ results.push({ frameId, url: frame.url, ok: false, error: err.message });
941
+ }
942
+ }
943
+ this.requirePage(tab, allowedOrigins);
944
+ return { tabId: tab.state.id, url: wc.getURL(), frames: results };
945
+ });
946
+ }
947
+
948
+ /** @param {string} sessionId @param {TabId | null} id */
949
+ async agentOrigin(sessionId, id) {
950
+ const tab = this.agentTab(sessionId, id);
951
+ const url = tab.view ? tab.view.webContents.getURL() || tab.state.url : tab.state.url;
952
+ const origin = url ? originOf(url) : null;
953
+ const hasCookies = origin ? (await this.deps.session.cookies.get({ url: origin })).length > 0 : false;
954
+ const main = tab.view ? tab.view.webContents.mainFrame : null;
955
+ const frameOrigins = main
956
+ ? [...new Set(main.framesInSubtree.filter((f) => f !== main).map(frameOriginOf))].filter((o) => o && o !== origin)
957
+ : [];
958
+ return { tabId: tab.state.id, url, origin, hasCookies, frameOrigins };
959
+ }
960
+
961
+ async agentScreenshot(sessionId, id, clip, maxWidth, allowedOrigins) {
962
+ const tab = this.agentTab(sessionId, id);
963
+ const wc = this.requirePage(tab, allowedOrigins);
964
+ this.requireNoDialog(tab);
965
+ return this.withAgent(tab, allowedOrigins, async () => {
966
+ const ctx = input.context(tab.cdp);
967
+ let rect = null;
968
+ if (clip) {
969
+ const frame = input.frameFor(wc, clip.frameId);
970
+ if (frame !== wc.mainFrame && unapprovedTopFrames(wc, allowedOrigins).some((f) => f === frame || isInside(frame, f))) {
971
+ const origin = frameOriginOf(frame) || frame.url;
972
+ throw new BridgeError("off_scope", `That element is in a frame from ${origin}, which this call was not approved to show.`, { origin });
973
+ }
974
+ const box = await input.elementBox(ctx, frame, clip.selector);
975
+ // The clip is in page coordinates: the box is in the viewport, so add how far the page scrolled.
976
+ const scrolled = await ctx.exec(wc.mainFrame, "({ x: scrollX, y: scrollY })");
977
+ rect = { ...box, x: box.x + scrolled.x, y: box.y + scrolled.y };
978
+ }
979
+ // A picture shows every frame on screen, so none may be from a site the user hasn't approved,
980
+ // before the capture or after it (a frame can appear while it is taken).
981
+ const frameGen = tab.frameGen;
982
+ await this.requireNoShownFrames(tab, allowedOrigins);
983
+ let image;
984
+ try {
985
+ image = nativeImage.createFromBuffer(await withTimeout(tab.cdp.screenshot(rect), EVAL_TIMEOUT_MS, "Taking the picture"));
986
+ } catch (err) {
987
+ if (err instanceof BridgeError) throw err;
988
+ throw new BridgeError("internal", `Could not take a picture of the page: ${err.message}`);
989
+ }
990
+ await this.requireNoShownFrames(tab, allowedOrigins);
991
+ if (tab.frameGen !== frameGen) {
992
+ throw new BridgeError("off_scope", "No picture was taken: the page's frames changed while it was being taken. Try again.");
993
+ }
994
+ if (image.getSize().width > maxWidth) image = image.resize({ width: maxWidth });
995
+ const size = image.getSize();
996
+ this.requirePage(tab, allowedOrigins);
997
+ return { png: image.toPNG().toString("base64"), width: size.width, height: size.height, url: wc.getURL() };
998
+ });
999
+ }
1000
+
1001
+ /** Refuse a picture while the page shows a frame from a site this call wasn't approved for. */
1002
+ async requireNoShownFrames(tab, allowedOrigins) {
1003
+ let sites;
1004
+ try {
1005
+ sites = await tab.cdp.shownUnapprovedSites(allowedOrigins);
1006
+ } catch (err) {
1007
+ throw new BridgeError("internal", `No picture was taken: GAIA could not check the page's frames (${err.message}).`);
1008
+ }
1009
+ if (sites.length === 0) return;
1010
+ const named = [...new Set(sites.map((s) => s || "a frame with no site of its own"))];
1011
+ throw new BridgeError(
1012
+ "off_scope",
1013
+ `No picture was taken: the page shows frames from ${named.join(", ")}, which the user has not approved. ` +
1014
+ "Call browser_snapshot to ask the user about those sites, then take the picture.",
1015
+ { origin: named[0], origins: named }
1016
+ );
1017
+ }
1018
+
1019
+ async agentLogs(sessionId, id, query, allowedOrigins) {
1020
+ const tab = this.agentTab(sessionId, id);
1021
+ const wc = this.requirePage(tab, allowedOrigins);
1022
+ return this.withAgent(tab, allowedOrigins, async () => ({ ...tab.cdp.logs(query), url: wc.getURL() }));
1023
+ }
1024
+
1025
+ /**
1026
+ * The only way the agent changes a page: a click, typing, or a key, as
1027
+ * trusted input (input.cjs). Refused in a tab the user holds or has just
1028
+ * touched. Waits for a navigation the action starts, and follows a popup
1029
+ * the pane opened as a new tab.
1030
+ *
1031
+ * @param {string} sessionId
1032
+ * @param {TabId | null} id
1033
+ * @param {import("./contract").ActAction} action
1034
+ * @param {import("./contract").ActTarget | null} target
1035
+ * @param {string[]} allowedOrigins
1036
+ */
1037
+ async agentAct(sessionId, id, action, target, allowedOrigins) {
1038
+ const tab = this.agentTab(sessionId, id);
1039
+ this.requireAgentInput(tab);
1040
+ const wc = this.requirePage(tab, allowedOrigins);
1041
+ this.requireNoDialog(tab);
1042
+ const frame = target ? input.frameFor(wc, target.frameId) : null;
1043
+ // Input in a frame lands on that frame's site, which needs approval like a page on it.
1044
+ if (frame && frame !== wc.mainFrame && isUnapprovedFrame(frame, allowedOrigins)) {
1045
+ const origin = frameOriginOf(frame) || "a frame with no site of its own";
1046
+ throw new BridgeError("off_scope", `That element is in a frame from ${origin}, which this call was not approved to use.`, { origin });
1047
+ }
1048
+ this.deps.onShowRequest(sessionId);
1049
+ const before = this.activeByChat.get(sessionId);
1050
+ return this.withAgent(
1051
+ tab,
1052
+ allowedOrigins,
1053
+ async () => {
1054
+ const stop = { reason: null };
1055
+ tab.dispatching = true;
1056
+ this.noteGesture(tab);
1057
+ let done;
1058
+ try {
1059
+ const ctx = {
1060
+ ...input.context(tab.cdp, stop),
1061
+ // Checked in the browser, not by the page's scripts: where a click lands and where keys go.
1062
+ landing: (x, y) => tab.cdp.landingOrigin(x, y),
1063
+ frameSite: (f) => (f === wc.mainFrame ? originOf(wc.getURL()) : input.frameOrigin(f)),
1064
+ focusedFrame: () => wc.focusedFrame || wc.mainFrame,
1065
+ allowed: allowedOrigins,
1066
+ };
1067
+ const acting = input.perform({ ctx, action, frame, selector: target && target.selector });
1068
+ done = await this.raceDialog(tab, withTimeout(acting, ACT_TIMEOUT_MS, "Acting on the page"));
1069
+ } catch (err) {
1070
+ if (err instanceof BridgeError) throw err;
1071
+ throw new BridgeError("internal", `Could not act on the page: ${err.message}`);
1072
+ } finally {
1073
+ tab.dispatching = false;
1074
+ tab.agentEchoUntil = Date.now() + AGENT_ECHO_MS;
1075
+ }
1076
+ // The page waits on the box, so the rest of this action must never land after it is answered.
1077
+ if (done.dialog) stop.reason = STOPPED_FOR_DIALOG;
1078
+ else await this.settle(wc);
1079
+ const reply = { tabId: tab.state.id, url: wc.getURL(), title: wc.getTitle() };
1080
+ const after = this.activeByChat.get(sessionId);
1081
+ if (after !== before && after !== undefined) reply.adoptedTabId = after;
1082
+ if (tab.state.dialog) reply.dialog = tab.state.dialog;
1083
+ return reply;
1084
+ },
1085
+ { acting: true }
1086
+ );
1087
+ }
1088
+
1089
+ /**
1090
+ * Run the model's JavaScript expression in the page's main world and
1091
+ * return its value as JSON. Only on a page on this computer, and only in a
1092
+ * tab the agent may act in; anything else is refused, never asked about.
1093
+ *
1094
+ * @param {string} sessionId
1095
+ * @param {TabId | null} id
1096
+ * @param {string} expression
1097
+ * @param {string[]} allowedOrigins
1098
+ */
1099
+ async agentScript(sessionId, id, expression, allowedOrigins) {
1100
+ const tab = this.agentTab(sessionId, id);
1101
+ this.requireAgentInput(tab);
1102
+ const wc = tab.view && tab.view.webContents;
1103
+ const url = (wc && wc.getURL()) || tab.state.url;
1104
+ if (!wc || url === null) {
1105
+ throw new BridgeError("no_page", "The browser pane shows a new tab page with no web page in it. Open one with browser_open(url).");
1106
+ }
1107
+ if (!isLoopbackUrl(url)) {
1108
+ throw new BridgeError(
1109
+ "unsupported",
1110
+ `browser_eval runs only on the user's own app on this computer (localhost), and this page is on ${originOf(url) || url}. Read it with browser_snapshot instead.`
1111
+ );
1112
+ }
1113
+ this.requirePage(tab, allowedOrigins);
1114
+ this.requireNoDialog(tab);
1115
+ return this.withAgent(
1116
+ tab,
1117
+ allowedOrigins,
1118
+ async () => {
1119
+ const reply = { tabId: tab.state.id, url: wc.getURL() };
1120
+ let ran;
1121
+ try {
1122
+ ran = await this.raceDialog(tab, withTimeout(wc.mainFrame.executeJavaScript(scriptSource(expression), false), SCRIPT_TIMEOUT_MS, "The script"));
1123
+ } catch (err) {
1124
+ return { ...reply, ok: false, error: err.message };
1125
+ }
1126
+ if (ran.dialog) return { ...reply, ok: false, error: STOPPED_FOR_DIALOG, dialog: ran.dialog };
1127
+ // The page runs the wrapper too, so its shape and size are checked here, not trusted.
1128
+ const value = ran.value && typeof ran.value === "object" ? ran.value : { text: String(ran.value) };
1129
+ if (value.error !== undefined) return { ...reply, ok: false, error: String(value.error).slice(0, MAX_SCRIPT_RESULT) };
1130
+ const text = typeof value.text === "string" ? value.text : String(value.text);
1131
+ return { ...reply, ok: true, json: text.slice(0, MAX_SCRIPT_RESULT), truncated: value.truncated === true || text.length > MAX_SCRIPT_RESULT };
1132
+ },
1133
+ { acting: true }
1134
+ );
1135
+ }
1136
+
1137
+ // ── Page boxes (alert, confirm, prompt, "leave this page?") ───────────
1138
+ //
1139
+ // One box at most per tab, held in tab.state.dialog until someone answers
1140
+ // it. The user answers in the pane; the agent answers with browser_dialog.
1141
+ // A box the agent's own action opened is dismissed when its turn ends, so
1142
+ // the page is never left waiting on nobody.
1143
+
1144
+ /** @param {any} tab */
1145
+ requireNoDialog(tab) {
1146
+ if (tab.state.dialog) throw this.dialogError(tab.state.dialog);
1147
+ }
1148
+
1149
+ dialogError(dialog) {
1150
+ return new BridgeError("dialog_open", `Nothing was done: the page is showing a ${dialog.type} box ("${dialog.message}"). Answer it first.`, { dialog });
1151
+ }
1152
+
1153
+ /** Waits on `work`, or on a box opening in `tab`, whichever comes first. */
1154
+ async raceDialog(tab, work) {
1155
+ let opened;
1156
+ const shown = new Promise((resolve) => {
1157
+ opened = resolve;
1158
+ });
1159
+ tab.dialogWaiters.add(opened);
1160
+ try {
1161
+ const first = await Promise.race([work.then((value) => ({ value, dialog: null })), shown.then((dialog) => ({ value: undefined, dialog }))]);
1162
+ // The page is waiting on the box, so `work` finishes only once it is answered.
1163
+ if (first.dialog) work.catch(() => {});
1164
+ return first;
1165
+ } finally {
1166
+ tab.dialogWaiters.delete(opened);
1167
+ }
1168
+ }
1169
+
1170
+ /**
1171
+ * @param {any} tab
1172
+ * @param {Omit<import("./contract").PageDialog, "openedBy">} dialog
1173
+ * @param {((accept: boolean, text: string) => void) | { leave: (() => Promise<unknown>) | null }} answer
1174
+ */
1175
+ openDialog(tab, dialog, answer) {
1176
+ const openedBy = tab.busy > 0 ? "agent" : "page";
1177
+ tab.state.dialog = { ...dialog, openedBy };
1178
+ tab.dialogAnswer = answer;
1179
+ for (const notify of tab.dialogWaiters) notify(tab.state.dialog);
1180
+ this.publish();
1181
+ }
1182
+
1183
+ /** Forget the box: Chromium closed it (the page navigated or closed). */
1184
+ dropDialog(tab) {
1185
+ if (!tab.state.dialog) return;
1186
+ tab.state.dialog = null;
1187
+ tab.dialogAnswer = null;
1188
+ this.publish();
1189
+ }
1190
+
1191
+ /**
1192
+ * Answer the tab's box. For "leave this page?", accepting repeats the
1193
+ * navigation that was stopped, when the pane started it.
1194
+ *
1195
+ * @returns {{ dialog: import("./contract").PageDialog, leaving: Promise<unknown> | null }}
1196
+ */
1197
+ answerDialog(tab, accept, text) {
1198
+ const dialog = tab.state.dialog;
1199
+ if (!dialog) {
1200
+ throw new BridgeError("not_actionable", "There is no box open on the page in the browser pane. Call browser_snapshot() to see the page.");
1201
+ }
1202
+ const answer = tab.dialogAnswer;
1203
+ this.dropDialog(tab);
1204
+ if (dialog.type !== "beforeunload") {
1205
+ answer(accept, dialog.type === "prompt" && accept ? (text === null ? dialog.defaultText : text) : "");
1206
+ return { dialog, leaving: null };
1207
+ }
1208
+ if (!accept) return { dialog, leaving: null };
1209
+ tab.leaveOnceUntil = Date.now() + LEAVE_ONCE_MS;
1210
+ return { dialog, leaving: answer.leave ? answer.leave() : null };
1211
+ }
1212
+
1213
+ /** The user's answer from the pane: any of the shown chat's tabs, any box. */
1214
+ userAnswerDialog(id, accept, text) {
1215
+ const { leaving } = this.answerDialog(this.userTab(id), accept, text);
1216
+ if (leaving) leaving.catch((err) => console.warn(`[browser-pane] Leaving the page did not finish: ${err.message}`));
1217
+ }
1218
+
1219
+ /** Python's site gate reads the box before an answer, to decide whether to ask the user. */
1220
+ agentDialog(sessionId, id) {
1221
+ const tab = this.agentTab(sessionId, id);
1222
+ return { tabId: tab.state.id, dialog: tab.state.dialog };
1223
+ }
1224
+
1225
+ /**
1226
+ * The agent answers the box. Dismissing is always allowed; accepting a
1227
+ * confirm, prompt or "leave this page?" needs the page's site approved.
1228
+ *
1229
+ * @param {string} sessionId
1230
+ * @param {TabId | null} id
1231
+ * @param {boolean} accept
1232
+ * @param {string | null} text
1233
+ * @param {string[]} allowedOrigins
1234
+ */
1235
+ async agentAnswerDialog(sessionId, id, accept, text, allowedOrigins) {
1236
+ const tab = this.agentTab(sessionId, id);
1237
+ this.requireAgentInput(tab);
1238
+ const pending = tab.state.dialog;
1239
+ if (pending && accept && pending.type !== "alert" && !inScope(pending.url, allowedOrigins)) {
1240
+ const origin = originOf(pending.url) || pending.url;
1241
+ throw new BridgeError("off_scope", `The box is from ${origin}, which this call was not approved to answer.`, { origin });
1242
+ }
1243
+ return this.withAgent(
1244
+ tab,
1245
+ allowedOrigins,
1246
+ async () => {
1247
+ const { dialog, leaving } = this.answerDialog(tab, accept, text);
1248
+ const wc = tab.view.webContents;
1249
+ if (leaving) {
1250
+ const left = await this.raceDialog(tab, withTimeout(leaving, LOAD_TIMEOUT_MS, "Leaving the page")).catch((err) => {
1251
+ throw new BridgeError("navigation_failed", err.message, { url: wc.getURL() });
1252
+ });
1253
+ if (!left.dialog) await this.settle(wc);
1254
+ } else {
1255
+ // A page often opens a second box right after the first.
1256
+ await this.settle(wc);
1257
+ }
1258
+ return { tabId: tab.state.id, answered: dialog, url: wc.getURL(), title: wc.getTitle(), dialog: tab.state.dialog };
1259
+ },
1260
+ { acting: true }
1261
+ );
1262
+ }
1263
+
1264
+ /** Dismiss the boxes this chat's agent opened and left, in its tabs still shared with it. */
1265
+ releaseDialogs(sessionId) {
1266
+ let dismissed = 0;
1267
+ for (const tab of this.chatTabs(sessionId)) {
1268
+ const d = tab.state.dialog;
1269
+ if (!d || d.openedBy !== "agent" || tab.state.control !== "shared") continue;
1270
+ this.answerDialog(tab, false, null);
1271
+ dismissed += 1;
1272
+ }
1273
+ return { dismissed };
1274
+ }
1275
+
1276
+ /** Called by Electron when a page's beforeunload asks to stay; it must decide now. */
1277
+ onPreventUnload(tab, event) {
1278
+ const leave = tab.leaving;
1279
+ tab.leaving = null;
1280
+ if (Date.now() < tab.leaveOnceUntil) {
1281
+ tab.leaveOnceUntil = 0;
1282
+ event.preventDefault();
1283
+ return;
1284
+ }
1285
+ this.openDialog(tab, { type: "beforeunload", message: LEAVE_MESSAGE, defaultText: "", url: tab.view.webContents.getURL() }, { leave });
1286
+ }
1287
+
1288
+ /**
1289
+ * Emulate a screen size and color scheme for the agent. The user's own
1290
+ * Responsive choice wins: then nothing changes and applied is false.
1291
+ *
1292
+ * @param {string} sessionId
1293
+ * @param {TabId | null} id
1294
+ * @param {import("./contract").ViewportChoice} choice
1295
+ */
1296
+ async agentViewport(sessionId, id, choice) {
1297
+ const tab = this.agentTab(sessionId, id);
1298
+ this.requireAgentInput(tab);
1299
+ if (!tab.view) throw new BridgeError("no_page", "This tab has no page yet. Open one with browser_open(url) first.");
1300
+ const current = tab.state.viewport;
1301
+ if (current && current.source === "user") return { tabId: tab.state.id, applied: false, viewport: current };
1302
+ tab.state.viewport = choice.size || choice.colorScheme ? { ...choice, source: "agent" } : null;
1303
+ this.deps.onShowRequest(sessionId);
1304
+ this.publish();
1305
+ await this.applyViewport(tab);
1306
+ return { tabId: tab.state.id, applied: true, viewport: tab.state.viewport };
1307
+ }
1308
+
1309
+ async applyViewport(tab) {
1310
+ if (!tab.cdp) return;
1311
+ const v = tab.state.viewport;
1312
+ if (v && v.size) {
1313
+ const { width, height, mobile } = v.size;
1314
+ await tab.cdp.send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 0, mobile });
1315
+ } else {
1316
+ await tab.cdp.send("Emulation.clearDeviceMetricsOverride");
1317
+ }
1318
+ await tab.cdp.send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: (v && v.colorScheme) || "" }] });
1319
+ }
1320
+
1321
+ /** A click or keystroke, the user's or the agent's: the page may open one popup soon after. */
1322
+ noteGesture(tab) {
1323
+ tab.gestureAt = Date.now();
1324
+ tab.popups = 1;
1325
+ }
1326
+
1327
+ /** A click or keystroke from the user: the agent waits, and mid-task it hands the tab to the user. */
1328
+ noteUserInput(tab) {
1329
+ tab.userInputAt = Date.now();
1330
+ if (tab.state.agentActing && tab.state.control === "shared") {
1331
+ tab.state.control = "user";
1332
+ this.publish();
1333
+ }
1334
+ }
1335
+
1336
+ dispose() {
1337
+ this.stopPicking();
1338
+ this.disposed = true;
1339
+ for (const tab of this.tabs.values()) this.destroyView(tab.view);
1340
+ this.tabs.clear();
1341
+ }
1342
+
1343
+ // ── Internals ─────────────────────────────────────────────────────────
1344
+
1345
+ /**
1346
+ * @param {ChatKey} chat
1347
+ * @returns {TabId}
1348
+ */
1349
+ addTab(chat) {
1350
+ const id = /** @type {TabId} */ (`tab-${this.nextId++}`);
1351
+ this.tabs.set(id, {
1352
+ chat,
1353
+ view: null,
1354
+ /** Set while the page is discarded: its history, to load again when its chat shows. */
1355
+ saved: null,
1356
+ state: {
1357
+ id,
1358
+ url: null,
1359
+ title: "New tab",
1360
+ loading: false,
1361
+ canGoBack: false,
1362
+ canGoForward: false,
1363
+ devToolsOpen: false,
1364
+ notice: null,
1365
+ openedBy: null,
1366
+ agentBusy: false,
1367
+ agentActing: false,
1368
+ control: "shared",
1369
+ viewport: null,
1370
+ dialog: null,
1371
+ },
1372
+ cdp: null,
1373
+ busy: 0,
1374
+ busyTimer: null,
1375
+ actTimer: null,
1376
+ scope: null,
1377
+ userInputAt: 0,
1378
+ gestureAt: 0,
1379
+ popups: 0,
1380
+ dispatching: false,
1381
+ agentEchoUntil: 0,
1382
+ dialogAnswer: null,
1383
+ dialogWaiters: new Set(),
1384
+ leaving: null,
1385
+ leaveOnceUntil: 0,
1386
+ });
1387
+ return id;
1388
+ }
1389
+
1390
+ /** @param {ChatKey} chat The chat's tabs, in the order they opened. */
1391
+ chatTabs(chat) {
1392
+ return [...this.tabs.values()].filter((t) => t.chat === chat);
1393
+ }
1394
+
1395
+ /** The tab the user sees, or null while the shown chat has none. */
1396
+ shownTab() {
1397
+ const id = this.activeTabId;
1398
+ return id === null ? null : this.requireTab(id);
1399
+ }
1400
+
1401
+ /** @param {TabId} id */
1402
+ requireTab(id) {
1403
+ const tab = this.tabs.get(id);
1404
+ if (!tab) throw new Error(`No browser pane tab "${id}"; it may have been closed.`);
1405
+ return tab;
1406
+ }
1407
+
1408
+ /** A tab the user acts on from the pane: only the shown chat's tabs are on screen. */
1409
+ userTab(id) {
1410
+ const tab = this.requireTab(id);
1411
+ if (tab.chat !== this.shown) throw new Error(`Browser pane tab "${id}" belongs to another chat than the one showing.`);
1412
+ return tab;
1413
+ }
1414
+
1415
+ /** Close a tab's page and forget the tab. The caller picks the chat's next active tab. */
1416
+ dropTab(tab) {
1417
+ if (this.picker && this.picker.tabId === tab.state.id) this.stopPicking();
1418
+ this.destroyView(tab.view);
1419
+ this.tabs.delete(tab.state.id);
1420
+ }
1421
+
1422
+ /**
1423
+ * Past LIVE_VIEW_CAP live pages, close whole chats' pages, least recently
1424
+ * shown first. Never the shown chat's, `keep`'s, or a chat whose page is
1425
+ * busy with the agent or waiting on a box.
1426
+ *
1427
+ * @param {ChatKey} keep
1428
+ */
1429
+ trimViews(keep) {
1430
+ let live = [...this.tabs.values()].filter((t) => t.view).length;
1431
+ if (live <= LIVE_VIEW_CAP) return;
1432
+ const owners = new Set([...this.tabs.values()].map((t) => t.chat));
1433
+ const oldestFirst = [...owners].filter((c) => !this.recency.includes(c)).concat([...this.recency].reverse());
1434
+ for (const chat of oldestFirst) {
1435
+ if (live <= LIVE_VIEW_CAP) break;
1436
+ if (chat === this.shown || chat === keep) continue;
1437
+ const pages = this.chatTabs(chat).filter((t) => t.view);
1438
+ if (pages.length === 0 || pages.some((t) => t.busy > 0 || t.state.dialog)) continue;
1439
+ for (const tab of pages) this.discard(tab);
1440
+ live -= pages.length;
1441
+ }
1442
+ }
1443
+
1444
+ /**
1445
+ * Close a hidden tab's page but keep its history, which carries each
1446
+ * entry's last saved scroll position and form values, to load it again.
1447
+ */
1448
+ discard(tab) {
1449
+ const nav = tab.view.webContents.navigationHistory;
1450
+ const entries = nav.getAllEntries();
1451
+ // A page that never finished its first load has no entry yet; its address is all there is.
1452
+ tab.saved = entries.length > 0 ? { entries, index: nav.getActiveIndex() } : { entries: [{ url: tab.state.url, title: tab.state.title }], index: 0 };
1453
+ this.destroyView(tab.view);
1454
+ tab.view = null;
1455
+ tab.cdp = null;
1456
+ tab.state.loading = false;
1457
+ tab.state.devToolsOpen = false;
1458
+ }
1459
+
1460
+ /** Load a discarded tab's page again where it was. */
1461
+ restoreView(tab) {
1462
+ const { saved } = tab;
1463
+ tab.saved = null;
1464
+ const wc = this.ensureView(tab).webContents;
1465
+ // did-fail-load puts a failure on the tab; this only keeps the rejection handled.
1466
+ wc.navigationHistory.restore(saved).catch((err) => console.warn(`[browser-pane] Reloading ${tab.state.url} did not finish: ${err.message}`));
1467
+ if (tab.state.viewport) {
1468
+ this.applyViewport(tab).catch((err) => console.error(`[browser-pane] Could not apply the tab's screen size again: ${err.message}`));
1469
+ }
1470
+ }
1471
+
1472
+ isShown() {
1473
+ return this.visible && !this.occluded && this.bounds !== null;
1474
+ }
1475
+
1476
+ syncViews() {
1477
+ if (this.disposed) return;
1478
+ const shown = this.isShown();
1479
+ for (const [id, tab] of this.tabs) {
1480
+ if (!tab.view) continue;
1481
+ if (this.bounds) tab.view.setBounds(this.bounds);
1482
+ tab.view.setVisible(shown && id === this.activeTabId);
1483
+ }
1484
+ }
1485
+
1486
+ publish() {
1487
+ if (this.disposed || this.window.isDestroyed()) return;
1488
+ this.deps.publish(this.state());
1489
+ }
1490
+
1491
+ ensureView(tab) {
1492
+ if (tab.view) return tab.view;
1493
+ const view = new WebContentsView({
1494
+ webPreferences: {
1495
+ partition: PANE_PARTITION,
1496
+ sandbox: true,
1497
+ contextIsolation: true,
1498
+ nodeIntegration: false,
1499
+ },
1500
+ });
1501
+ view.setVisible(false);
1502
+ if (!this.bounds) view.setBounds(HIDDEN_BOUNDS);
1503
+ tab.view = view;
1504
+ tab.cdp = (this.deps.createCdp || ((wc) => new TabCdp(wc)))(view.webContents);
1505
+ this.watch(tab);
1506
+ this.window.contentView.addChildView(view);
1507
+ this.trimViews(tab.chat);
1508
+ this.syncViews();
1509
+ return view;
1510
+ }
1511
+
1512
+ destroyView(view) {
1513
+ if (!view) return;
1514
+ if (!this.window.isDestroyed()) this.window.contentView.removeChildView(view);
1515
+ if (!view.webContents.isDestroyed()) view.webContents.close();
1516
+ }
1517
+
1518
+ readNavigation(tab) {
1519
+ const wc = tab.view.webContents;
1520
+ tab.state.canGoBack = wc.navigationHistory.canGoBack();
1521
+ tab.state.canGoForward = wc.navigationHistory.canGoForward();
1522
+ }
1523
+
1524
+ watch(tab) {
1525
+ const wc = tab.view.webContents;
1526
+ const s = tab.state;
1527
+ // A discarded or closed page can still send late events; only the tab's current page counts.
1528
+ const live = () => !this.disposed && this.tabs.has(s.id) && tab.view !== null && tab.view.webContents === wc;
1529
+ const update = (fn) => (...args) => {
1530
+ if (!live()) return;
1531
+ fn(...args);
1532
+ this.publish();
1533
+ };
1534
+
1535
+ attachTabPolicy(wc, {
1536
+ blockedPorts: this.deps.blockedPorts,
1537
+ openTab: (url) => this.openTabIn(tab.chat, url),
1538
+ allowPopup: () => {
1539
+ if (tab.popups < 1 || Date.now() - tab.gestureAt > POPUP_GESTURE_MS) return false;
1540
+ tab.popups -= 1;
1541
+ return true;
1542
+ },
1543
+ onBlocked: update((url, message) => {
1544
+ s.notice = { kind: "blocked", url, message };
1545
+ }),
1546
+ // While an agent op runs, the page may not wander to a site the user didn't approve.
1547
+ stopsAgent: (url) => {
1548
+ if (!tab.scope || inScope(url, tab.scope.allowed)) return false;
1549
+ tab.scope.blocked = url;
1550
+ return true;
1551
+ },
1552
+ });
1553
+
1554
+ wc.removeAllListeners(RUN_DIALOG);
1555
+ wc.on(RUN_DIALOG, (info, callback) => {
1556
+ if (!live()) return callback(false, "");
1557
+ // Chromium shows one box per page at a time; a second can only come from a frame racing the first.
1558
+ if (s.dialog) return callback(false, "");
1559
+ const url = (info.frame && info.frame.url) || wc.getURL();
1560
+ this.openDialog(tab, { type: info.dialogType, message: String(info.messageText || ""), defaultText: String(info.defaultPromptText || ""), url }, callback);
1561
+ });
1562
+ wc.on(CANCEL_DIALOGS, () => {
1563
+ if (s.dialog && s.dialog.type !== "beforeunload") this.dropDialog(tab);
1564
+ });
1565
+ wc.on("will-prevent-unload", (event) => {
1566
+ if (live()) this.onPreventUnload(tab, event);
1567
+ });
1568
+ // Unhandled, Electron picks the first device it finds; the pane offers none.
1569
+ wc.on("select-bluetooth-device", (event, _devices, callback) => {
1570
+ event.preventDefault();
1571
+ callback("");
1572
+ });
1573
+ wc.on("did-start-loading", update(() => { s.loading = true; }));
1574
+ wc.on("did-stop-loading", update(() => {
1575
+ s.loading = false;
1576
+ this.readNavigation(tab);
1577
+ }));
1578
+ wc.on("did-start-navigation", update((details) => {
1579
+ if (!details.isMainFrame || details.isSameDocument) return;
1580
+ // Started, so beforeunload already let it go: nothing left to repeat, and no box to keep.
1581
+ tab.leaving = null;
1582
+ if (s.dialog && s.dialog.type === "beforeunload") this.dropDialog(tab);
1583
+ if (this.picker && this.picker.tabId === s.id) this.stopPicking();
1584
+ s.notice = null;
1585
+ tab.cdp.onNavigationStarted();
1586
+ }));
1587
+ // Counts frames appearing or moving, so a picture can tell the frame tree changed while it was taken.
1588
+ tab.frameGen = 0;
1589
+ wc.on("frame-created", () => {
1590
+ tab.frameGen += 1;
1591
+ });
1592
+ wc.on("did-frame-navigate", () => {
1593
+ tab.frameGen += 1;
1594
+ });
1595
+ wc.on("did-navigate", update((_event, url) => {
1596
+ s.url = url;
1597
+ this.readNavigation(tab);
1598
+ this.remember(tab.chat, url, wc.getTitle());
1599
+ }));
1600
+ wc.on("did-navigate-in-page", update((_event, url, isMainFrame) => {
1601
+ if (!isMainFrame) return;
1602
+ s.url = url;
1603
+ this.readNavigation(tab);
1604
+ }));
1605
+ wc.on("page-title-updated", update((_event, title) => {
1606
+ s.title = title;
1607
+ if (s.url) this.remember(tab.chat, s.url, title);
1608
+ }));
1609
+ wc.on("did-fail-load", update((_event, code, description, url, isMainFrame) => {
1610
+ if (!isMainFrame || code === ERR_ABORTED) return;
1611
+ s.notice = { kind: "load-failed", url, message: `${description} (${code})` };
1612
+ }));
1613
+ wc.on("render-process-gone", update((_event, details) => {
1614
+ s.loading = false;
1615
+ this.dropDialog(tab);
1616
+ s.notice = {
1617
+ kind: "load-failed",
1618
+ url: s.url || "",
1619
+ message: `The page stopped working (${details.reason}). Reload to try again.`,
1620
+ };
1621
+ }));
1622
+ // Chromium refuses file: links from web pages before will-navigate fires; its console line is the only sign.
1623
+ wc.on("console-message", (event) => {
1624
+ const refused = /^Not allowed to load local resource: (\S+)/.exec(event.message || "");
1625
+ if (!refused) return;
1626
+ update(() => {
1627
+ s.notice = { kind: "blocked", url: refused[1], message: classifyNavigation(refused[1], { blockedPorts: [] }).message };
1628
+ })();
1629
+ });
1630
+ wc.on("devtools-opened", update(() => { s.devToolsOpen = true; }));
1631
+ wc.on("devtools-closed", update(() => { s.devToolsOpen = false; }));
1632
+ wc.on("input-event", (_event, event) => {
1633
+ if (USER_INPUT.has(event.type)) this.noteGesture(tab);
1634
+ if (!USER_INPUT.has(event.type) || tab.dispatching || Date.now() < tab.agentEchoUntil) return;
1635
+ if (live()) this.noteUserInput(tab);
1636
+ });
1637
+ wc.on("before-input-event", (event, input) => {
1638
+ if (isToggleShortcut(input)) {
1639
+ event.preventDefault();
1640
+ this.deps.onToggleRequest();
1641
+ } else if (isPickShortcut(input)) {
1642
+ event.preventDefault();
1643
+ this.togglePicking().catch((err) => console.error(`[browser-pane] ${err.message}`));
1644
+ }
1645
+ });
1646
+ }
1647
+
1648
+ /** Put a visited page at the top of its chat's new tab page list. */
1649
+ remember(chat, url, title) {
1650
+ if (!isWebUrl(url)) return;
1651
+ const rest = (this.recent.get(chat) ?? []).filter((p) => p.url !== url);
1652
+ this.recent.delete(chat);
1653
+ this.recent.set(chat, [{ url, title: title || url }, ...rest].slice(0, RECENT_LIMIT));
1654
+ for (const old of [...this.recent.keys()].slice(0, -RECENT_CHATS)) this.recent.delete(old);
1655
+ this.deps.recentStore.save(this.recent);
1656
+ }
1657
+
1658
+ /** Called by the policy when a page asked for a permission it was refused. */
1659
+ notePermissionDenied(webContents, permission, origin) {
1660
+ for (const tab of this.tabs.values()) {
1661
+ if (tab.view && tab.view.webContents === webContents) {
1662
+ tab.state.notice = { kind: "permission-denied", permission, origin };
1663
+ this.publish();
1664
+ return;
1665
+ }
1666
+ }
1667
+ }
1668
+ }
1669
+
1670
+ module.exports = {
1671
+ ACT_LINGER_MS,
1672
+ LIVE_VIEW_CAP,
1673
+ BridgeError,
1674
+ CANCEL_DIALOGS,
1675
+ LEAVE_MESSAGE,
1676
+ RUN_DIALOG,
1677
+ DEVTOOLS_MODE,
1678
+ PANE_PARTITION,
1679
+ PaneHost,
1680
+ USER_PAUSE_MS,
1681
+ inScope,
1682
+ isLoopbackUrl,
1683
+ isPickShortcut,
1684
+ isToggleShortcut,
1685
+ toViewBounds,
1686
+ };