@amd-gaia/agent-ui 0.26.1-rc.2 → 0.27.0-rc.2
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/dist/assets/AdvancedSettings-DHERtrno.js +1 -0
- package/dist/assets/AutomationsSettings-4FWcRau9.js +1 -0
- package/dist/assets/ConnectorsPane-BGI8nBUb.css +1 -0
- package/dist/assets/ConnectorsPane-Dkat1zLC.js +1 -0
- package/dist/assets/DocumentLibrary-Dll55N7l.js +5 -0
- package/dist/assets/DocumentLibrary-fEMoY7lH.css +1 -0
- package/dist/assets/FileBrowser-1goNp4CP.css +1 -0
- package/dist/assets/FileBrowser-wFHqH6K_.js +4 -0
- package/dist/assets/MemoryDashboard-BuUBoNq8.js +1 -0
- package/dist/assets/MemoryDashboard-RpfLag-v.css +1 -0
- package/dist/assets/MessagingSettings-DomiT2rX.js +1 -0
- package/dist/assets/MobileAccessModal-B2gaE8nk.js +2 -0
- package/dist/assets/{MobileAccessModal-CX4NZmr4.css → MobileAccessModal-BrZMaERi.css} +1 -1
- package/dist/assets/ScheduleManager-8UE81KlQ.js +1 -0
- package/dist/assets/ScheduleManager-BZzEH2-W.css +1 -0
- package/dist/assets/Temml-CCjoacWt.woff2 +0 -0
- package/dist/assets/index-BiETDNik.css +1 -0
- package/dist/assets/index-HCZ86cyP.js +220 -0
- package/dist/assets/useFocusTrap-BFi0chLf.js +6 -0
- package/dist/assets/zap-DjkIffnX.js +1 -0
- package/dist/index.html +3 -3
- package/dist/sw.js +1 -1
- package/main.cjs +130 -40
- package/package.json +5 -3
- package/preload.cjs +28 -0
- package/services/browser-pane/bridge-error.cjs +20 -0
- package/services/browser-pane/bridge-server.cjs +496 -0
- package/services/browser-pane/cdp-session.cjs +375 -0
- package/services/browser-pane/contract.d.ts +448 -0
- package/services/browser-pane/dev-servers.cjs +478 -0
- package/services/browser-pane/input.cjs +375 -0
- package/services/browser-pane/ipc.cjs +267 -0
- package/services/browser-pane/navigation-policy.cjs +255 -0
- package/services/browser-pane/pane-host.cjs +1686 -0
- package/services/browser-pane/picker-world.js +360 -0
- package/services/browser-pane/picker.cjs +261 -0
- package/services/browser-pane/service-ports.cjs +66 -0
- package/services/dev-qa-mode.cjs +32 -0
- package/dist/assets/AdvancedSettings-C-9ErldS.js +0 -1
- package/dist/assets/AutomationsSettings-CL3K4hLZ.js +0 -1
- package/dist/assets/ConnectorsPane-DpGR78cA.js +0 -1
- package/dist/assets/ConnectorsPane-w-HLcq3n.css +0 -1
- package/dist/assets/DocumentLibrary-BKZdx6rJ.css +0 -1
- package/dist/assets/DocumentLibrary-N7tBbt9v.js +0 -5
- package/dist/assets/FileBrowser-CO2p3xa2.js +0 -4
- package/dist/assets/FileBrowser-CrRQXiPo.css +0 -1
- package/dist/assets/MemoryDashboard-1OIrKFIa.js +0 -1
- package/dist/assets/MemoryDashboard-B4AO_CU8.css +0 -1
- package/dist/assets/MessagingSettings-0AJnsoWA.js +0 -1
- package/dist/assets/MobileAccessModal-CnPB1BEN.js +0 -2
- package/dist/assets/ScheduleManager-BYOhqnfv.js +0 -1
- package/dist/assets/ScheduleManager-DQBnf_IN.css +0 -1
- package/dist/assets/index-Bkx-QRv4.css +0 -1
- package/dist/assets/index-C-3wCH_s.js +0 -116
- package/dist/assets/useT-DuzpQY8p.js +0 -6
- package/dist/assets/zap-gF9QDKfa.js +0 -1
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
// Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* How the agent's clicks, typing and key presses reach a pane page: trusted
|
|
6
|
+
* CDP input events at the target's on-screen point, never el.click(). A
|
|
7
|
+
* target is a selector Python built from its snapshot ref, in the main frame
|
|
8
|
+
* or any child frame, cross-site ones included. Before any input lands the
|
|
9
|
+
* target is scrolled into view and checked: still on the page, visible,
|
|
10
|
+
* enabled, and not covered by something else, in its own frame and in every
|
|
11
|
+
* frame above it.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
"use strict";
|
|
15
|
+
|
|
16
|
+
const { BridgeError } = require("./bridge-error.cjs");
|
|
17
|
+
|
|
18
|
+
/** @typedef {import("./contract").ActAction} ActAction */
|
|
19
|
+
/** @typedef {import("./contract").ActTarget} ActTarget */
|
|
20
|
+
/** @typedef {import("./contract").AllowedKey} AllowedKey */
|
|
21
|
+
|
|
22
|
+
/** The only keys the agent may press; model text never becomes a raw key event. */
|
|
23
|
+
const KEYS = Object.freeze({
|
|
24
|
+
Enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" },
|
|
25
|
+
Escape: { key: "Escape", code: "Escape", keyCode: 27 },
|
|
26
|
+
Tab: { key: "Tab", code: "Tab", keyCode: 9 },
|
|
27
|
+
Backspace: { key: "Backspace", code: "Backspace", keyCode: 8 },
|
|
28
|
+
Space: { key: " ", code: "Space", keyCode: 32, text: " " },
|
|
29
|
+
PageDown: { key: "PageDown", code: "PageDown", keyCode: 34 },
|
|
30
|
+
PageUp: { key: "PageUp", code: "PageUp", keyCode: 33 },
|
|
31
|
+
Home: { key: "Home", code: "Home", keyCode: 36 },
|
|
32
|
+
End: { key: "End", code: "End", keyCode: 35 },
|
|
33
|
+
ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 },
|
|
34
|
+
ArrowUp: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 },
|
|
35
|
+
ArrowRight: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 },
|
|
36
|
+
ArrowDown: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 },
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** Input types that take no typing: the agent clicks them instead. */
|
|
40
|
+
const UNTYPED_INPUTS = new Set(["checkbox", "radio", "submit", "button", "reset", "image", "file", "range", "color", "hidden"]);
|
|
41
|
+
|
|
42
|
+
const PROBE_TIMEOUT_MS = 5000;
|
|
43
|
+
|
|
44
|
+
// Runs in the target's frame. Waits two frames after scrolling (or 120 ms when
|
|
45
|
+
// a hidden view does not paint) so the point is where the element settled.
|
|
46
|
+
// The point is in that frame's viewport; toMainFrame moves it to the page's.
|
|
47
|
+
const PROBE_JS = `async (sel) => {
|
|
48
|
+
const el = document.querySelector(sel);
|
|
49
|
+
if (!el) return { fail: "gone" };
|
|
50
|
+
el.scrollIntoView({ block: "center", inline: "center" });
|
|
51
|
+
await new Promise((r) => { requestAnimationFrame(() => requestAnimationFrame(r)); setTimeout(r, 120); });
|
|
52
|
+
const r = el.getBoundingClientRect();
|
|
53
|
+
const st = getComputedStyle(el);
|
|
54
|
+
if (r.width < 1 || r.height < 1 || st.visibility === "hidden" || st.display === "none" || el.closest("[inert]")) return { fail: "hidden" };
|
|
55
|
+
if (el.disabled || el.closest("fieldset[disabled]") || el.getAttribute("aria-disabled") === "true") return { fail: "disabled" };
|
|
56
|
+
const x = r.left + r.width / 2;
|
|
57
|
+
const y = r.top + r.height / 2;
|
|
58
|
+
const top = document.elementFromPoint(x, y);
|
|
59
|
+
const mine = (n) => n === el || el.contains(n) || [...(el.labels || [])].some((l) => l.contains(n));
|
|
60
|
+
if (!top) return { fail: "hidden" };
|
|
61
|
+
if (!mine(top)) {
|
|
62
|
+
const label = (top.innerText || "").replace(/\\s+/g, " ").trim().slice(0, 60);
|
|
63
|
+
return { fail: "covered", by: label ? '"' + label + '"' : "a <" + top.tagName.toLowerCase() + "> element" };
|
|
64
|
+
}
|
|
65
|
+
return { x, y, tag: el.tagName.toLowerCase(), type: (el.getAttribute("type") || "").toLowerCase(), editable: el.isContentEditable };
|
|
66
|
+
}`;
|
|
67
|
+
|
|
68
|
+
// Selects the field's current text, so the typing that follows replaces it.
|
|
69
|
+
const SELECT_TEXT_JS = `(sel) => {
|
|
70
|
+
const el = document.querySelector(sel);
|
|
71
|
+
if (!el) return false;
|
|
72
|
+
el.focus();
|
|
73
|
+
if (typeof el.select === "function") el.select();
|
|
74
|
+
else { const range = document.createRange(); range.selectNodeContents(el); const s = getSelection(); s.removeAllRanges(); s.addRange(range); }
|
|
75
|
+
return true;
|
|
76
|
+
}`;
|
|
77
|
+
|
|
78
|
+
// A <select> opens a native popup that input events cannot drive, so the option is set the way a pick would set it.
|
|
79
|
+
const CHOOSE_OPTION_JS = `([sel, label]) => {
|
|
80
|
+
const el = document.querySelector(sel);
|
|
81
|
+
if (!el) return { fail: "gone" };
|
|
82
|
+
const want = label.trim().toLowerCase();
|
|
83
|
+
const opt = [...el.options].find((o) => (o.label || o.text).trim().toLowerCase() === want);
|
|
84
|
+
if (!opt) return { fail: "option", options: [...el.options].map((o) => (o.label || o.text).trim()).slice(0, 20) };
|
|
85
|
+
el.value = opt.value;
|
|
86
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
87
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
88
|
+
return { chosen: opt.label || opt.text };
|
|
89
|
+
}`;
|
|
90
|
+
|
|
91
|
+
const FOCUS_JS = `(sel) => { const el = document.querySelector(sel); if (!el) return false; el.focus(); return true; }`;
|
|
92
|
+
|
|
93
|
+
// Scrolls an element into view in its frame and returns its box there; no actionability checks.
|
|
94
|
+
const BOX_JS = `async (sel) => {
|
|
95
|
+
const el = document.querySelector(sel);
|
|
96
|
+
if (!el) return null;
|
|
97
|
+
el.scrollIntoView({ block: "center", inline: "center" });
|
|
98
|
+
await new Promise((r) => { requestAnimationFrame(() => requestAnimationFrame(r)); setTimeout(r, 120); });
|
|
99
|
+
const r = el.getBoundingClientRect();
|
|
100
|
+
return { x: r.left, y: r.top, width: r.width, height: r.height };
|
|
101
|
+
}`;
|
|
102
|
+
|
|
103
|
+
// Runs in a child frame: its index in window.parent, which works across sites.
|
|
104
|
+
const FRAME_INDEX_JS = `() => {
|
|
105
|
+
if (window.parent === window) return -1;
|
|
106
|
+
for (let i = 0; i < parent.length; i++) if (parent[i] === window) return i;
|
|
107
|
+
return -1;
|
|
108
|
+
}`;
|
|
109
|
+
|
|
110
|
+
// Runs in the parent of a frame: where that frame's content box starts in this
|
|
111
|
+
// viewport, after scrolling it so the point (x, y) in the child shows, and
|
|
112
|
+
// whether something in this frame covers that point.
|
|
113
|
+
const FRAME_BOX_JS = `([index, x, y]) => {
|
|
114
|
+
const fe = [...document.querySelectorAll("iframe, frame")].find((f) => f.contentWindow === window[index]);
|
|
115
|
+
if (!fe) return { fail: "frame" };
|
|
116
|
+
const corner = () => {
|
|
117
|
+
const r = fe.getBoundingClientRect();
|
|
118
|
+
const st = getComputedStyle(fe);
|
|
119
|
+
return { left: r.left + fe.clientLeft + parseFloat(st.paddingLeft), top: r.top + fe.clientTop + parseFloat(st.paddingTop) };
|
|
120
|
+
};
|
|
121
|
+
const shows = (c) => c.left + x >= 0 && c.top + y >= 0 && c.left + x < innerWidth && c.top + y < innerHeight;
|
|
122
|
+
let c = corner();
|
|
123
|
+
if (!shows(c)) { fe.scrollIntoView({ block: "center", inline: "center" }); c = corner(); }
|
|
124
|
+
if (!shows(c)) return { fail: "hidden" };
|
|
125
|
+
const top = document.elementFromPoint(c.left + x, c.top + y);
|
|
126
|
+
if (top !== fe) {
|
|
127
|
+
if (!top) return { fail: "hidden" };
|
|
128
|
+
const label = (top.innerText || "").replace(/\\s+/g, " ").trim().slice(0, 60);
|
|
129
|
+
return { fail: "covered", by: label ? '"' + label + '"' : "a <" + top.tagName.toLowerCase() + "> element" };
|
|
130
|
+
}
|
|
131
|
+
return c;
|
|
132
|
+
}`;
|
|
133
|
+
|
|
134
|
+
const call = (fn, arg) => `(${fn})(${JSON.stringify(arg)})`;
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
/** @param {string} name */
|
|
138
|
+
function keyFor(name) {
|
|
139
|
+
if (!Object.prototype.hasOwnProperty.call(KEYS, name)) {
|
|
140
|
+
throw new BridgeError("bad_request", `"${name}" is not a key GAIA may press. Keys: ${Object.keys(KEYS).join(", ")}.`);
|
|
141
|
+
}
|
|
142
|
+
return KEYS[name];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The frame a target lives in, in this process or another.
|
|
147
|
+
*
|
|
148
|
+
* @param {Electron.WebContents} wc
|
|
149
|
+
* @param {string | null} frameId "processId:routingId", or null for the main frame.
|
|
150
|
+
*/
|
|
151
|
+
function frameFor(wc, frameId) {
|
|
152
|
+
const main = wc.mainFrame;
|
|
153
|
+
if (frameId === null) return main;
|
|
154
|
+
const frame = main.framesInSubtree.find((f) => `${f.processId}:${f.routingId}` === frameId);
|
|
155
|
+
if (!frame) {
|
|
156
|
+
throw new BridgeError("element_not_found", "The frame that element was in is gone. Call browser_snapshot() to get current refs.");
|
|
157
|
+
}
|
|
158
|
+
return frame;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The http(s) origin a frame acts as, or null. An about:blank or srcdoc frame
|
|
163
|
+
* acts as the frame that made it, and Chromium reports that origin; a
|
|
164
|
+
* sandboxed or data: frame has an opaque origin, which no approval covers.
|
|
165
|
+
*/
|
|
166
|
+
function frameOrigin(frame) {
|
|
167
|
+
const origin = frame.origin;
|
|
168
|
+
if (typeof origin === "string") return /^https?:\/\/[^/]+$/.test(origin) ? origin : null;
|
|
169
|
+
try {
|
|
170
|
+
const url = new URL(frame.url);
|
|
171
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url.origin : null;
|
|
172
|
+
} catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function withTimeout(promise, what) {
|
|
178
|
+
let timer;
|
|
179
|
+
const deadline = new Promise((_, reject) => {
|
|
180
|
+
timer = setTimeout(() => reject(new BridgeError("timeout", `${what} took longer than ${PROBE_TIMEOUT_MS / 1000} s.`)), PROBE_TIMEOUT_MS);
|
|
181
|
+
});
|
|
182
|
+
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* What one action sends to the page. Once `stop.reason` is set (a box opened
|
|
187
|
+
* on the page mid-action) every later step throws instead of reaching the page.
|
|
188
|
+
*
|
|
189
|
+
* @param {{ send: (method: string, params?: object) => Promise<any> }} cdp
|
|
190
|
+
* @param {{ reason: string | null }} [stop]
|
|
191
|
+
*/
|
|
192
|
+
function context(cdp, stop = { reason: null }) {
|
|
193
|
+
const guard = () => {
|
|
194
|
+
if (stop.reason) throw new BridgeError("dialog_open", stop.reason);
|
|
195
|
+
};
|
|
196
|
+
return {
|
|
197
|
+
send: (method, params) => {
|
|
198
|
+
guard();
|
|
199
|
+
return cdp.send(method, params);
|
|
200
|
+
},
|
|
201
|
+
exec: (frame, code, what = "Reading the page") => {
|
|
202
|
+
guard();
|
|
203
|
+
return withTimeout(frame.executeJavaScript(code, false), what);
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const unreachableFrame = () =>
|
|
209
|
+
new BridgeError("unsupported", "That element is inside a frame GAIA can't reach from the page. Ask the user to do this step in the browser pane.");
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Move a point in `frame`'s viewport into the main frame's, one parent at a
|
|
213
|
+
* time: each parent finds the frame's element, scrolls it into view if the
|
|
214
|
+
* point is off screen, and adds where its content box starts.
|
|
215
|
+
*
|
|
216
|
+
* @returns {Promise<{ x: number, y: number }>}
|
|
217
|
+
*/
|
|
218
|
+
async function toMainFrame(ctx, frame, x, y) {
|
|
219
|
+
for (let f = frame; f.parent; f = f.parent) {
|
|
220
|
+
let box;
|
|
221
|
+
try {
|
|
222
|
+
const index = await ctx.exec(f, `(${FRAME_INDEX_JS})()`);
|
|
223
|
+
box = index >= 0 ? await ctx.exec(f.parent, call(FRAME_BOX_JS, [index, x, y])) : { fail: "frame" };
|
|
224
|
+
} catch (err) {
|
|
225
|
+
if (err instanceof BridgeError && err.code !== "timeout") throw err;
|
|
226
|
+
throw unreachableFrame();
|
|
227
|
+
}
|
|
228
|
+
if (!box || box.fail === "frame") throw unreachableFrame();
|
|
229
|
+
if (box.fail === "hidden") {
|
|
230
|
+
throw new BridgeError("not_actionable", "That element's frame is not visible on the page, so it can't be clicked. Call browser_snapshot() to see what is there now.");
|
|
231
|
+
}
|
|
232
|
+
if (box.fail === "covered") {
|
|
233
|
+
throw new BridgeError("not_actionable", `That element is covered by ${box.by}. Close or dismiss that first, then try again.`, { coveredBy: box.by });
|
|
234
|
+
}
|
|
235
|
+
x += box.left;
|
|
236
|
+
y += box.top;
|
|
237
|
+
}
|
|
238
|
+
return { x, y };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Scroll the target into view and check it can take input. The point it
|
|
243
|
+
* returns is in the main frame's viewport, where trusted input lands.
|
|
244
|
+
*
|
|
245
|
+
* @returns {Promise<{ x: number, y: number, tag: string, type: string, editable: boolean }>}
|
|
246
|
+
*/
|
|
247
|
+
async function locate(ctx, frame, selector) {
|
|
248
|
+
const found = await ctx.exec(frame, call(PROBE_JS, selector), "Finding the element");
|
|
249
|
+
if (!found || found.fail === "gone") {
|
|
250
|
+
throw new BridgeError("element_not_found", "That element is not on the page any more. Call browser_snapshot() to get current refs, then retry.");
|
|
251
|
+
}
|
|
252
|
+
if (found.fail === "hidden") {
|
|
253
|
+
throw new BridgeError("not_actionable", "That element is not visible on the page, so it can't be clicked. Call browser_snapshot() to see what is there now.");
|
|
254
|
+
}
|
|
255
|
+
if (found.fail === "disabled") {
|
|
256
|
+
throw new BridgeError("not_actionable", "That element is disabled (greyed out). Fill in what the page still needs first, then try again.");
|
|
257
|
+
}
|
|
258
|
+
if (found.fail === "covered") {
|
|
259
|
+
throw new BridgeError("not_actionable", `That element is covered by ${found.by}. Close or dismiss that first, then try again.`, { coveredBy: found.by });
|
|
260
|
+
}
|
|
261
|
+
return { ...found, ...(await toMainFrame(ctx, frame, found.x, found.y)) };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* An element's box in the main frame's viewport, scrolled into view, for a picture of it.
|
|
266
|
+
*
|
|
267
|
+
* @returns {Promise<{ x: number, y: number, width: number, height: number }>}
|
|
268
|
+
*/
|
|
269
|
+
async function elementBox(ctx, frame, selector) {
|
|
270
|
+
const box = await ctx.exec(frame, call(BOX_JS, selector), "Finding the element");
|
|
271
|
+
if (!box || box.width < 1 || box.height < 1) {
|
|
272
|
+
throw new BridgeError("element_not_found", "That element is not on the page any more, or has no size. Call browser_snapshot() to get current refs.");
|
|
273
|
+
}
|
|
274
|
+
const centre = await toMainFrame(ctx, frame, box.x + box.width / 2, box.y + box.height / 2);
|
|
275
|
+
return { x: centre.x - box.width / 2, y: centre.y - box.height / 2, width: box.width, height: box.height };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function clickAt(ctx, { x, y }) {
|
|
279
|
+
await ctx.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
|
|
280
|
+
await ctx.send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", buttons: 1, clickCount: 1 });
|
|
281
|
+
await ctx.send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", buttons: 0, clickCount: 1 });
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function pressKey(ctx, name) {
|
|
285
|
+
const def = keyFor(name);
|
|
286
|
+
const base = { key: def.key, code: def.code, windowsVirtualKeyCode: def.keyCode, nativeVirtualKeyCode: def.keyCode };
|
|
287
|
+
await ctx.send("Input.dispatchKeyEvent", def.text ? { type: "keyDown", ...base, text: def.text, unmodifiedText: def.text } : { type: "rawKeyDown", ...base });
|
|
288
|
+
await ctx.send("Input.dispatchKeyEvent", { type: "keyUp", ...base });
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function fill(ctx, frame, selector, text, pressEnter) {
|
|
292
|
+
const at = await locate(ctx, frame, selector);
|
|
293
|
+
if (at.tag === "select") {
|
|
294
|
+
const res = await ctx.exec(frame, call(CHOOSE_OPTION_JS, [selector, text]));
|
|
295
|
+
if (res && res.fail === "option") {
|
|
296
|
+
throw new BridgeError("not_actionable", `That dropdown has no option "${text}". Its options: ${res.options.join(", ")}.`);
|
|
297
|
+
}
|
|
298
|
+
if (!res || res.fail) throw new BridgeError("element_not_found", "That dropdown is not on the page any more. Call browser_snapshot() to get current refs.");
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (at.tag === "input" && at.type === "password") {
|
|
302
|
+
throw new BridgeError(
|
|
303
|
+
"not_actionable",
|
|
304
|
+
"That is a password field. GAIA never types passwords. Ask the user to sign in by hand in the browser pane, then continue."
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
const typeable = at.tag === "textarea" || at.editable || (at.tag === "input" && !UNTYPED_INPUTS.has(at.type));
|
|
308
|
+
if (!typeable) {
|
|
309
|
+
throw new BridgeError("not_actionable", "That element doesn't take typing (it is a button, link, checkbox or similar). Use browser_click on it instead.");
|
|
310
|
+
}
|
|
311
|
+
await clickIn(ctx, frame, at);
|
|
312
|
+
await ctx.exec(frame, call(SELECT_TEXT_JS, selector));
|
|
313
|
+
if (text) await ctx.send("Input.insertText", { text });
|
|
314
|
+
else await pressKey(ctx, "Backspace");
|
|
315
|
+
if (pressEnter) await pressKey(ctx, "Enter");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Click at `at` only if the browser's own hit test puts that point inside
|
|
320
|
+
* `frame`'s site. The point comes from scripts the page can tamper with, so
|
|
321
|
+
* it is checked where the page can't reach before any input is sent.
|
|
322
|
+
*/
|
|
323
|
+
async function clickIn(ctx, frame, at) {
|
|
324
|
+
if (typeof ctx.landing !== "function" || typeof ctx.frameSite !== "function") {
|
|
325
|
+
throw new BridgeError("internal", "GAIA can't check where a click lands in this tab, so it sends none.");
|
|
326
|
+
}
|
|
327
|
+
const want = ctx.frameSite(frame);
|
|
328
|
+
const got = await ctx.landing(at.x, at.y);
|
|
329
|
+
if (!want || got !== want) {
|
|
330
|
+
throw new BridgeError(
|
|
331
|
+
"not_actionable",
|
|
332
|
+
"Nothing was clicked: the spot the page gave for that element is not inside the element's own frame, so the click could land somewhere else. Call browser_snapshot() and try again, or ask the user to do this step."
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
await clickAt(ctx, at);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Keys land in the focused frame: it must be the target's frame, or with no target, a frame on an approved site. */
|
|
339
|
+
function checkFocus(ctx, frame) {
|
|
340
|
+
if (typeof ctx.focusedFrame !== "function" || typeof ctx.frameSite !== "function") {
|
|
341
|
+
throw new BridgeError("internal", "GAIA can't check where a key press lands in this tab, so it sends none.");
|
|
342
|
+
}
|
|
343
|
+
const focused = ctx.focusedFrame();
|
|
344
|
+
const ok = frame ? focused === frame : (ctx.allowed || []).includes(ctx.frameSite(focused));
|
|
345
|
+
if (!ok) {
|
|
346
|
+
throw new BridgeError(
|
|
347
|
+
"not_actionable",
|
|
348
|
+
"No key was pressed: the keyboard focus is in a different frame than the element, so the key could land somewhere else. Call browser_snapshot() and try again, or ask the user to do this step."
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Carry out one agent action as trusted input. The caller has already
|
|
355
|
+
* checked the tab is the agent's to act in, and the frame's site.
|
|
356
|
+
*
|
|
357
|
+
* @param {{ ctx: ReturnType<typeof context>, action: ActAction, frame: Electron.WebFrameMain | null, selector: string | null }} op
|
|
358
|
+
*/
|
|
359
|
+
async function perform({ ctx, action, frame, selector }) {
|
|
360
|
+
if (action.kind === "press") {
|
|
361
|
+
keyFor(action.key);
|
|
362
|
+
if (frame) {
|
|
363
|
+
await locate(ctx, frame, selector);
|
|
364
|
+
await ctx.exec(frame, call(FOCUS_JS, selector));
|
|
365
|
+
}
|
|
366
|
+
checkFocus(ctx, frame);
|
|
367
|
+
await pressKey(ctx, action.key);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (!frame) throw new BridgeError("bad_request", `A ${action.kind} needs a target element.`);
|
|
371
|
+
if (action.kind === "click") await clickIn(ctx, frame, await locate(ctx, frame, selector));
|
|
372
|
+
else await fill(ctx, frame, selector, action.text, action.pressEnter);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
module.exports = { FRAME_BOX_JS, FRAME_INDEX_JS, KEYS, PROBE_JS, context, elementBox, frameFor, frameOrigin, keyFor, locate, perform };
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The browser pane service: one pane session with its policy, one PaneHost per
|
|
6
|
+
* app window, and the IPC channels the window's toolbar calls. preload.cjs
|
|
7
|
+
* exposes the same channel names as window.gaiaBrowserPane.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
"use strict";
|
|
11
|
+
|
|
12
|
+
const fs = require("fs");
|
|
13
|
+
const path = require("path");
|
|
14
|
+
const { PaneHost, PANE_PARTITION } = require("./pane-host.cjs");
|
|
15
|
+
const { installSessionPolicy } = require("./navigation-policy.cjs");
|
|
16
|
+
|
|
17
|
+
/** @typedef {import("./contract").RecentPage} RecentPage */
|
|
18
|
+
/** @typedef {import("./contract").ChatKey} ChatKey */
|
|
19
|
+
|
|
20
|
+
const CHANNELS = Object.freeze({
|
|
21
|
+
getState: "pane:get-state",
|
|
22
|
+
state: "pane:state",
|
|
23
|
+
command: "pane:command",
|
|
24
|
+
setBounds: "pane:set-bounds",
|
|
25
|
+
setView: "pane:set-view",
|
|
26
|
+
claimDraft: "pane:claim-draft",
|
|
27
|
+
forgetChat: "pane:forget-chat",
|
|
28
|
+
setOccluded: "pane:set-occluded",
|
|
29
|
+
openTab: "pane:open-tab",
|
|
30
|
+
closeTab: "pane:close-tab",
|
|
31
|
+
selectTab: "pane:select-tab",
|
|
32
|
+
navigate: "pane:navigate",
|
|
33
|
+
history: "pane:history",
|
|
34
|
+
toggleDevTools: "pane:toggle-devtools",
|
|
35
|
+
clearData: "pane:clear-data",
|
|
36
|
+
openExternal: "pane:open-external",
|
|
37
|
+
setControl: "pane:set-control",
|
|
38
|
+
setViewport: "pane:set-viewport",
|
|
39
|
+
togglePicking: "pane:toggle-picking",
|
|
40
|
+
picked: "pane:picked",
|
|
41
|
+
stopDevServer: "pane:stop-dev-server",
|
|
42
|
+
answerDialog: "pane:answer-dialog",
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const HISTORY_ACTIONS = new Set(["back", "forward", "reload", "stop"]);
|
|
46
|
+
|
|
47
|
+
// The new-chat screen's pages, under a key no chat id can be.
|
|
48
|
+
const DRAFT_KEY = "";
|
|
49
|
+
|
|
50
|
+
/** Each chat's recent pages, kept as a small JSON file so the new tab page survives a restart. */
|
|
51
|
+
function fileRecentStore(filePath) {
|
|
52
|
+
return {
|
|
53
|
+
/** @returns {Map<ChatKey, RecentPage[]>} */
|
|
54
|
+
load() {
|
|
55
|
+
let raw;
|
|
56
|
+
try {
|
|
57
|
+
raw = fs.readFileSync(filePath, "utf8");
|
|
58
|
+
} catch (err) {
|
|
59
|
+
if (err.code === "ENOENT") return new Map();
|
|
60
|
+
console.error(`[browser-pane] Could not read recent pages from ${filePath}: ${err.message}`);
|
|
61
|
+
return new Map();
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const byChat = JSON.parse(raw);
|
|
65
|
+
if (byChat === null || typeof byChat !== "object" || Array.isArray(byChat)) {
|
|
66
|
+
throw new Error("expected recent pages keyed by chat (an older version kept one shared list)");
|
|
67
|
+
}
|
|
68
|
+
const pages = new Map();
|
|
69
|
+
for (const [key, list] of Object.entries(byChat)) {
|
|
70
|
+
if (!Array.isArray(list)) continue;
|
|
71
|
+
const valid = list.filter((p) => p && typeof p.url === "string" && typeof p.title === "string");
|
|
72
|
+
if (valid.length) pages.set(key === DRAFT_KEY ? null : key, valid);
|
|
73
|
+
}
|
|
74
|
+
return pages;
|
|
75
|
+
} catch (err) {
|
|
76
|
+
console.error(`[browser-pane] Ignoring unreadable recent pages in ${filePath}: ${err.message}`);
|
|
77
|
+
return new Map();
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
/** @param {Map<ChatKey, RecentPage[]>} pages */
|
|
81
|
+
save(pages) {
|
|
82
|
+
const byChat = Object.fromEntries([...pages].map(([chat, list]) => [chat ?? DRAFT_KEY, list]));
|
|
83
|
+
const tmp = `${filePath}.tmp`;
|
|
84
|
+
try {
|
|
85
|
+
fs.writeFileSync(tmp, JSON.stringify(byChat));
|
|
86
|
+
fs.renameSync(tmp, filePath);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
console.error(`[browser-pane] Could not save recent pages to ${filePath}: ${err.message}`);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const isSessionId = (v) => typeof v === "string" && v !== "" && v.length <= 200;
|
|
95
|
+
|
|
96
|
+
function requireString(value, what) {
|
|
97
|
+
if (typeof value !== "string" || value === "") {
|
|
98
|
+
throw new Error(`Browser pane: ${what} must be a non-empty string, got ${JSON.stringify(value)}`);
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function parseRect(rect) {
|
|
104
|
+
const ok =
|
|
105
|
+
rect &&
|
|
106
|
+
["x", "y", "width", "height"].every((k) => typeof rect[k] === "number" && Number.isFinite(rect[k]));
|
|
107
|
+
return ok ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const VIEWPORT_LIMITS = { min: 200, max: 4000 };
|
|
111
|
+
|
|
112
|
+
/** The Responsive control's choice, or null; anything else is a bug in the renderer. */
|
|
113
|
+
function parseViewportChoice(choice) {
|
|
114
|
+
if (choice === null) return null;
|
|
115
|
+
const size = choice && choice.size;
|
|
116
|
+
const scheme = choice && choice.colorScheme;
|
|
117
|
+
const dim = (n) => Number.isInteger(n) && n >= VIEWPORT_LIMITS.min && n <= VIEWPORT_LIMITS.max;
|
|
118
|
+
const sizeOk = size === null || (size && dim(size.width) && dim(size.height) && typeof size.mobile === "boolean");
|
|
119
|
+
if (!choice || !sizeOk || (scheme !== null && scheme !== "light" && scheme !== "dark")) {
|
|
120
|
+
throw new Error(`Browser pane: bad viewport ${JSON.stringify(choice)}`);
|
|
121
|
+
}
|
|
122
|
+
return { size: size && { width: size.width, height: size.height, mobile: size.mobile }, colorScheme: scheme };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* @param {{
|
|
127
|
+
* ipcMain: Electron.IpcMain,
|
|
128
|
+
* session: Electron.Session,
|
|
129
|
+
* shell: Electron.Shell,
|
|
130
|
+
* userDataDir: string,
|
|
131
|
+
* savePathFor: (filename: string) => string,
|
|
132
|
+
* blockedPorts: () => number[],
|
|
133
|
+
* devServers: import("./dev-servers.cjs").DevServerSupervisor,
|
|
134
|
+
* }} deps
|
|
135
|
+
*/
|
|
136
|
+
function createBrowserPaneService({ ipcMain, session, shell, userDataDir, savePathFor, blockedPorts, devServers }) {
|
|
137
|
+
/** @type {PaneHost | null} */
|
|
138
|
+
let host = null;
|
|
139
|
+
/** The dev servers are app-wide, not the window's, so they join the state here. */
|
|
140
|
+
const withServers = (state) => ({ ...state, devServers: devServers.list() });
|
|
141
|
+
/** Deleted chats, for every window this run: a window made later must refuse them too. */
|
|
142
|
+
const goneChats = new Set();
|
|
143
|
+
const recentStore = fileRecentStore(path.join(userDataDir, "browser-pane-recent.json"));
|
|
144
|
+
|
|
145
|
+
installSessionPolicy(session, {
|
|
146
|
+
blockedPorts,
|
|
147
|
+
savePathFor,
|
|
148
|
+
onPermissionDenied: (webContents, permission, origin) => {
|
|
149
|
+
console.log(`[browser-pane] Denied ${permission} for ${origin || "a pane page"}`);
|
|
150
|
+
if (host) host.notePermissionDenied(webContents, permission, origin);
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
function requireHost(event) {
|
|
155
|
+
if (!host) throw new Error("The browser pane is not ready: the GAIA window has not opened yet.");
|
|
156
|
+
if (event.sender !== host.window.webContents) {
|
|
157
|
+
throw new Error("Only the GAIA window can drive the browser pane.");
|
|
158
|
+
}
|
|
159
|
+
return host;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const handle = (channel, fn) => {
|
|
163
|
+
ipcMain.handle(channel, (event, ...args) => fn(requireHost(event), ...args));
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
handle(CHANNELS.getState, (h) => withServers(h.state()));
|
|
167
|
+
handle(CHANNELS.setOccluded, (h, occluded) => h.setOccluded(occluded === true));
|
|
168
|
+
handle(CHANNELS.openTab, (h, url) => h.openTab(url === null ? null : requireString(url, "url")));
|
|
169
|
+
handle(CHANNELS.closeTab, (h, id) => h.closeTab(requireString(id, "tab id")));
|
|
170
|
+
handle(CHANNELS.selectTab, (h, id) => h.selectTab(requireString(id, "tab id")));
|
|
171
|
+
handle(CHANNELS.navigate, (h, id, url) => h.navigate(requireString(id, "tab id"), requireString(url, "url")));
|
|
172
|
+
handle(CHANNELS.history, (h, id, action) => {
|
|
173
|
+
if (!HISTORY_ACTIONS.has(action)) {
|
|
174
|
+
throw new Error(`Browser pane: unknown history action ${JSON.stringify(action)}`);
|
|
175
|
+
}
|
|
176
|
+
h.history(requireString(id, "tab id"), action);
|
|
177
|
+
});
|
|
178
|
+
handle(CHANNELS.toggleDevTools, (h, id) => h.toggleDevTools(requireString(id, "tab id")));
|
|
179
|
+
handle(CHANNELS.clearData, (h) => h.clearBrowsingData());
|
|
180
|
+
handle(CHANNELS.openExternal, (h, id) => h.openExternal(requireString(id, "tab id")));
|
|
181
|
+
handle(CHANNELS.setControl, (h, id, control) => h.setControl(requireString(id, "tab id"), control));
|
|
182
|
+
handle(CHANNELS.togglePicking, (h) => h.togglePicking());
|
|
183
|
+
handle(CHANNELS.answerDialog, (h, id, accept, text) => {
|
|
184
|
+
if (typeof accept !== "boolean") throw new Error("accept must be true or false.");
|
|
185
|
+
if (text !== null && typeof text !== "string") throw new Error("text must be a string or null.");
|
|
186
|
+
h.userAnswerDialog(requireString(id, "tab id"), accept, text);
|
|
187
|
+
});
|
|
188
|
+
handle(CHANNELS.setViewport, (h, id, choice) => h.setUserViewport(requireString(id, "tab id"), parseViewportChoice(choice)));
|
|
189
|
+
handle(CHANNELS.stopDevServer, async (_h, key) => {
|
|
190
|
+
await devServers.stop(requireString(key, "dev server key"));
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// Sent on every resize, so it is fire-and-forget; a throw here would reach the crash handler.
|
|
194
|
+
ipcMain.on(CHANNELS.setBounds, (event, rect) => {
|
|
195
|
+
const parsed = parseRect(rect);
|
|
196
|
+
if (!host || event.sender !== host.window.webContents || !parsed) {
|
|
197
|
+
console.error(`[browser-pane] Ignored bounds ${JSON.stringify(rect)} from an unexpected sender or shape`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
host.setBounds(parsed);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
// The three below are fire-and-forget like bounds, so they reach main in the order the renderer sent them.
|
|
204
|
+
const on = (channel, what, valid, fn) => {
|
|
205
|
+
ipcMain.on(channel, (event, ...args) => {
|
|
206
|
+
if (!host || event.sender !== host.window.webContents || !valid(...args)) {
|
|
207
|
+
console.error(`[browser-pane] Ignored ${what} ${JSON.stringify(args)} from an unexpected sender or shape`);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
fn(host, ...args);
|
|
212
|
+
} catch (err) {
|
|
213
|
+
console.error(`[browser-pane] ${what} failed: ${err.message}`);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
on(CHANNELS.setView, "pane view", (chat, visible) => (chat === null || isSessionId(chat)) && typeof visible === "boolean", (h, chat, visible) =>
|
|
219
|
+
h.setView(chat, visible)
|
|
220
|
+
);
|
|
221
|
+
on(CHANNELS.claimDraft, "new chat's tabs", isSessionId, (h, sessionId) => h.claimDraft(sessionId));
|
|
222
|
+
// Deleting a chat closes its tabs and stops the dev servers only it was using.
|
|
223
|
+
on(CHANNELS.forgetChat, "deleted chat", isSessionId, (h, sessionId) => {
|
|
224
|
+
h.forgetChat(sessionId);
|
|
225
|
+
devServers.forgetChat(sessionId).catch((err) => console.error(`[browser-pane] Stopping the dev servers of deleted chat ${sessionId} failed: ${err.message}`));
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
/** The window's PaneHost, for the bridge; null while no window is open. */
|
|
230
|
+
getHost: () => host,
|
|
231
|
+
/** Push the state again, e.g. when a dev server starts or stops. */
|
|
232
|
+
publish: () => {
|
|
233
|
+
if (host) host.publish();
|
|
234
|
+
},
|
|
235
|
+
/** Give the pane to a (re)created app window. Tabs of a closed window close with it. */
|
|
236
|
+
attach(window) {
|
|
237
|
+
if (host) host.dispose();
|
|
238
|
+
const send = (channel, payload) => {
|
|
239
|
+
if (!window.isDestroyed()) window.webContents.send(channel, payload);
|
|
240
|
+
};
|
|
241
|
+
const created = new PaneHost({
|
|
242
|
+
window,
|
|
243
|
+
session,
|
|
244
|
+
recentStore,
|
|
245
|
+
blockedPorts,
|
|
246
|
+
goneChats,
|
|
247
|
+
publish: (state) => send(CHANNELS.state, withServers(state)),
|
|
248
|
+
onToggleRequest: () => send(CHANNELS.command, { kind: "toggle" }),
|
|
249
|
+
onShowRequest: (chat) => send(CHANNELS.command, { kind: "show", chat }),
|
|
250
|
+
onPicked: (event) => send(CHANNELS.picked, event),
|
|
251
|
+
openExternal: (url) => {
|
|
252
|
+
shell.openExternal(url).catch((err) =>
|
|
253
|
+
console.error(`[browser-pane] Could not open ${url} in the system browser: ${err.message}`)
|
|
254
|
+
);
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
host = created;
|
|
258
|
+
window.on("closed", () => {
|
|
259
|
+
created.dispose();
|
|
260
|
+
if (host === created) host = null;
|
|
261
|
+
});
|
|
262
|
+
return created;
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
module.exports = { CHANNELS, PANE_PARTITION, createBrowserPaneService, fileRecentStore };
|