@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.
Files changed (56) hide show
  1. package/dist/assets/AdvancedSettings-DHERtrno.js +1 -0
  2. package/dist/assets/AutomationsSettings-4FWcRau9.js +1 -0
  3. package/dist/assets/ConnectorsPane-BGI8nBUb.css +1 -0
  4. package/dist/assets/ConnectorsPane-Dkat1zLC.js +1 -0
  5. package/dist/assets/DocumentLibrary-Dll55N7l.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-wFHqH6K_.js +4 -0
  9. package/dist/assets/MemoryDashboard-BuUBoNq8.js +1 -0
  10. package/dist/assets/MemoryDashboard-RpfLag-v.css +1 -0
  11. package/dist/assets/MessagingSettings-DomiT2rX.js +1 -0
  12. package/dist/assets/MobileAccessModal-B2gaE8nk.js +2 -0
  13. package/dist/assets/{MobileAccessModal-CX4NZmr4.css → MobileAccessModal-BrZMaERi.css} +1 -1
  14. package/dist/assets/ScheduleManager-8UE81KlQ.js +1 -0
  15. package/dist/assets/ScheduleManager-BZzEH2-W.css +1 -0
  16. package/dist/assets/Temml-CCjoacWt.woff2 +0 -0
  17. package/dist/assets/index-BiETDNik.css +1 -0
  18. package/dist/assets/index-HCZ86cyP.js +220 -0
  19. package/dist/assets/useFocusTrap-BFi0chLf.js +6 -0
  20. package/dist/assets/zap-DjkIffnX.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,360 @@
1
+ // Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ // The element picker. picker.cjs runs this function in a CDP isolated world
5
+ // on the pane page, so page scripts can neither see its variables nor call
6
+ // its binding. The outline lives in a closed shadow root. Hover outlines an
7
+ // element, a click selects it, Shift-click adds it, ArrowUp and ArrowDown
8
+ // walk the last selected element to its parent and back to a child, and
9
+ // Escape or Enter ends picking. Page clicks are swallowed while it runs.
10
+ // Main gives each selected element a pick ref and calls stamp() to write it
11
+ // on the element as data-gaia-pick, the attribute the agent's clicks target.
12
+
13
+ (function startPicker(cfg) {
14
+ "use strict";
15
+ const { binding, pickAttr, styleProps, maxHtml, maxText, maxName } = cfg;
16
+ const send = (msg) => globalThis[binding](JSON.stringify(msg));
17
+ if (globalThis.__gaiaPicker) globalThis.__gaiaPicker.stop();
18
+
19
+ const host = document.createElement("gaia-picker");
20
+ host.style.cssText = "all:initial;position:fixed;inset:0;pointer-events:none;z-index:2147483647;display:block;";
21
+ const root = host.attachShadow({ mode: "closed" });
22
+ root.innerHTML = `<style>
23
+ .box{position:fixed;box-sizing:border-box;border:2px solid #2563eb;background:rgba(37,99,235,.12);pointer-events:none;border-radius:2px}
24
+ .box.sel{border-color:#e11d48;background:rgba(225,29,72,.10)}
25
+ .tag{position:absolute;left:-2px;bottom:100%;margin-bottom:2px;font:600 11px/1.4 ui-monospace,Menlo,monospace;color:#fff;background:#2563eb;padding:1px 5px;border-radius:3px;white-space:nowrap;max-width:360px;overflow:hidden;text-overflow:ellipsis}
26
+ .box.sel .tag{background:#e11d48}
27
+ .box.below .tag{bottom:auto;top:100%;margin:2px 0 0}
28
+ </style>`;
29
+ const layer = document.createElement("div");
30
+ root.appendChild(layer);
31
+ (document.documentElement || document).appendChild(host);
32
+
33
+ /** @type {Element | null} */
34
+ let hovered = null;
35
+ /** @type {Element[]} */
36
+ let selected = [];
37
+ /** @type {Element[]} where ArrowDown returns to after ArrowUp */
38
+ let walked = [];
39
+ const tokens = new WeakMap();
40
+ const byToken = new Map();
41
+ let nextToken = 1;
42
+ let frame = 0;
43
+
44
+ function tokenOf(el) {
45
+ let t = tokens.get(el);
46
+ if (!t) {
47
+ t = `t${nextToken++}`;
48
+ tokens.set(el, t);
49
+ byToken.set(t, el);
50
+ }
51
+ return t;
52
+ }
53
+
54
+ function labelOf(el) {
55
+ const classes = [...el.classList].filter((c) => /^[\w-]+$/.test(c)).slice(0, 2);
56
+ return [el.tagName.toLowerCase(), ...classes].join(".");
57
+ }
58
+
59
+ function oneLine(s, max) {
60
+ return String(s || "").replace(/\s+/g, " ").trim().slice(0, max);
61
+ }
62
+
63
+ const IMPLICIT_ROLES = {
64
+ a: (el) => (el.hasAttribute("href") ? "link" : "generic"),
65
+ button: () => "button",
66
+ select: () => "combobox",
67
+ textarea: () => "textbox",
68
+ img: () => "img",
69
+ nav: () => "navigation",
70
+ main: () => "main",
71
+ header: () => "banner",
72
+ footer: () => "contentinfo",
73
+ form: () => "form",
74
+ ul: () => "list",
75
+ ol: () => "list",
76
+ li: () => "listitem",
77
+ table: () => "table",
78
+ dialog: () => "dialog",
79
+ input: (el) => {
80
+ const type = (el.getAttribute("type") || "text").toLowerCase();
81
+ if (type === "checkbox" || type === "radio") return type;
82
+ if (type === "submit" || type === "button" || type === "reset") return "button";
83
+ return "textbox";
84
+ },
85
+ };
86
+
87
+ function roleOf(el) {
88
+ const explicit = el.getAttribute("role");
89
+ if (explicit) return oneLine(explicit, 40);
90
+ const tag = el.tagName.toLowerCase();
91
+ if (/^h[1-6]$/.test(tag)) return "heading";
92
+ const implicit = IMPLICIT_ROLES[tag];
93
+ return implicit ? implicit(el) : "generic";
94
+ }
95
+
96
+ function nameOf(el) {
97
+ const labelled = el.getAttribute("aria-labelledby");
98
+ const byId = labelled
99
+ ? labelled.split(/\s+/).map((id) => document.getElementById(id)).filter(Boolean).map((n) => n.innerText).join(" ")
100
+ : "";
101
+ const fromLabel = el.labels && el.labels.length ? el.labels[0].innerText : "";
102
+ // A password field is named by its label or placeholder, never by what was typed.
103
+ const secret = el.tagName.toLowerCase() === "input" && String(el.type || "").toLowerCase() === "password";
104
+ return oneLine(
105
+ el.getAttribute("aria-label") || byId || fromLabel || el.getAttribute("alt") || el.getAttribute("title") ||
106
+ (["input", "select", "textarea"].includes(el.tagName.toLowerCase())
107
+ ? el.getAttribute("placeholder") || (secret ? "" : el.value)
108
+ : el.innerText),
109
+ maxName
110
+ );
111
+ }
112
+
113
+ function cssEscape(s) {
114
+ return globalThis.CSS && CSS.escape ? CSS.escape(s) : s.replace(/[^\w-]/g, "\\$&");
115
+ }
116
+
117
+ function unique(sel) {
118
+ try {
119
+ return document.querySelectorAll(sel).length === 1;
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ /** The shortest selector that finds only this element: #id, [data-testid], then a tag:nth-of-type path. */
126
+ function selectorOf(el) {
127
+ if (el.id && unique(`#${cssEscape(el.id)}`)) return `#${cssEscape(el.id)}`;
128
+ const testId = el.getAttribute("data-testid");
129
+ if (testId && unique(`[data-testid="${testId.replace(/"/g, '\\"')}"]`)) return `[data-testid="${testId.replace(/"/g, '\\"')}"]`;
130
+ const parts = [];
131
+ for (let n = el; n && n.nodeType === 1 && n !== document.documentElement; n = n.parentElement) {
132
+ let part = n.tagName.toLowerCase();
133
+ if (n.id && unique(`#${cssEscape(n.id)}`)) {
134
+ parts.unshift(`#${cssEscape(n.id)}`);
135
+ break;
136
+ }
137
+ const cls = [...n.classList].filter((c) => /^[\w-]+$/.test(c)).slice(0, 2);
138
+ if (cls.length) part += `.${cls.join(".")}`;
139
+ const parent = n.parentElement;
140
+ if (parent) {
141
+ const same = [...parent.children].filter((c) => c.tagName === n.tagName);
142
+ if (same.length > 1) part += `:nth-of-type(${same.indexOf(n) + 1})`;
143
+ }
144
+ parts.unshift(part);
145
+ const sel = parts.join(" > ");
146
+ if (unique(sel)) return sel;
147
+ }
148
+ return parts.join(" > ");
149
+ }
150
+
151
+ /** Clears the value attribute of every password field in a copied element, itself included. */
152
+ function dropSecrets(copy) {
153
+ const secret = (n) => n.tagName.toLowerCase() === "input" && String(n.getAttribute("type") || "").toLowerCase() === "password";
154
+ for (const n of [copy, ...copy.querySelectorAll("input")]) {
155
+ if (secret(n)) n.removeAttribute("value");
156
+ }
157
+ }
158
+
159
+ /** outerHTML with descendants past depth 2 folded to a comment and the pick stamps left out. */
160
+ function htmlOf(el) {
161
+ const copy = el.cloneNode(true);
162
+ dropSecrets(copy);
163
+ const fold = (node, depth) => {
164
+ for (const child of [...node.children]) {
165
+ child.removeAttribute(pickAttr);
166
+ child.removeAttribute("data-gaia-ref");
167
+ if (depth >= 2 && child.children.length) {
168
+ const n = child.children.length;
169
+ child.replaceChildren(document.createComment(` ${n} ${n === 1 ? "child" : "children"} `));
170
+ } else {
171
+ fold(child, depth + 1);
172
+ }
173
+ }
174
+ };
175
+ copy.removeAttribute(pickAttr);
176
+ copy.removeAttribute("data-gaia-ref");
177
+ fold(copy, 1);
178
+ const html = copy.outerHTML;
179
+ return html.length > maxHtml ? `${html.slice(0, maxHtml - 20)}<!-- truncated -->` : html;
180
+ }
181
+
182
+ // Values a property has on most elements, left out so the styles stay short.
183
+ const DEFAULTS = {
184
+ position: ["static"],
185
+ margin: ["0px"],
186
+ padding: ["0px"],
187
+ gap: ["normal"],
188
+ "background-color": ["rgba(0, 0, 0, 0)", "transparent"],
189
+ "line-height": ["normal"],
190
+ "border-radius": ["0px"],
191
+ "box-shadow": ["none"],
192
+ opacity: ["1"],
193
+ "z-index": ["auto"],
194
+ };
195
+
196
+ function stylesOf(el) {
197
+ const cs = getComputedStyle(el);
198
+ const out = {};
199
+ for (const prop of styleProps) {
200
+ const value = cs.getPropertyValue(prop);
201
+ if (!value || (DEFAULTS[prop] || []).includes(value)) continue;
202
+ if (prop === "border" && /^0px /.test(value)) continue;
203
+ out[prop] = value.slice(0, 200);
204
+ }
205
+ return out;
206
+ }
207
+
208
+ function describe(el) {
209
+ const r = el.getBoundingClientRect();
210
+ return {
211
+ token: tokenOf(el),
212
+ tag: el.tagName.toLowerCase(),
213
+ label: labelOf(el),
214
+ selector: selectorOf(el),
215
+ role: roleOf(el),
216
+ name: nameOf(el),
217
+ text: oneLine(el.innerText || el.textContent, maxText),
218
+ outerHTML: htmlOf(el),
219
+ styles: stylesOf(el),
220
+ rect: { x: r.x, y: r.y, width: r.width, height: r.height },
221
+ scroll: { x: scrollX, y: scrollY },
222
+ url: location.href,
223
+ title: document.title,
224
+ };
225
+ }
226
+
227
+ function emit() {
228
+ send({ type: "selection", elements: selected.map(describe) });
229
+ }
230
+
231
+ function place(box, el, cls) {
232
+ const r = el.getBoundingClientRect();
233
+ box.className = `box ${cls}${r.top < 18 ? " below" : ""}`;
234
+ box.style.left = `${r.left}px`;
235
+ box.style.top = `${r.top}px`;
236
+ box.style.width = `${r.width}px`;
237
+ box.style.height = `${r.height}px`;
238
+ box.firstChild.textContent = labelOf(el);
239
+ }
240
+
241
+ function draw() {
242
+ frame = 0;
243
+ const shown = [...selected.map((el) => [el, "sel"]), ...(hovered && !selected.includes(hovered) ? [[hovered, "hover"]] : [])];
244
+ while (layer.children.length < shown.length) {
245
+ const box = document.createElement("div");
246
+ box.appendChild(document.createElement("span")).className = "tag";
247
+ layer.appendChild(box);
248
+ }
249
+ while (layer.children.length > shown.length) layer.lastChild.remove();
250
+ shown.forEach(([el, cls], i) => place(layer.children[i], el, cls));
251
+ }
252
+
253
+ function redraw() {
254
+ if (!frame) frame = requestAnimationFrame(draw);
255
+ }
256
+
257
+ function targetOf(e) {
258
+ const t = e.composedPath ? e.composedPath()[0] : e.target;
259
+ const el = t && t.nodeType === 1 ? t : t && t.parentElement;
260
+ return el && el !== host && el !== document.documentElement ? el : null;
261
+ }
262
+
263
+ function swallow(e) {
264
+ e.preventDefault();
265
+ e.stopImmediatePropagation();
266
+ }
267
+
268
+ function onMove(e) {
269
+ const el = targetOf(e);
270
+ if (el === hovered) return;
271
+ hovered = el;
272
+ redraw();
273
+ }
274
+
275
+ function onClick(e) {
276
+ swallow(e);
277
+ const el = targetOf(e);
278
+ if (!el) return;
279
+ walked = [];
280
+ if (e.shiftKey) {
281
+ if (!selected.includes(el)) selected = [...selected, el];
282
+ } else {
283
+ selected = [el];
284
+ }
285
+ redraw();
286
+ emit();
287
+ }
288
+
289
+ function walk(up) {
290
+ const last = selected[selected.length - 1];
291
+ const from = last || hovered;
292
+ if (!from) return;
293
+ let to = null;
294
+ if (up) {
295
+ const parent = from.parentElement;
296
+ if (parent && parent !== document.documentElement) {
297
+ walked.push(from);
298
+ to = parent;
299
+ }
300
+ } else {
301
+ const back = walked.pop();
302
+ to = back && from.contains(back) ? back : from.firstElementChild;
303
+ }
304
+ if (!to) return;
305
+ if (last) {
306
+ selected = [...selected.slice(0, -1).filter((el) => el !== to), to];
307
+ emit();
308
+ } else {
309
+ hovered = to;
310
+ }
311
+ redraw();
312
+ }
313
+
314
+ function onKey(e) {
315
+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {
316
+ swallow(e);
317
+ walk(e.key === "ArrowUp");
318
+ } else if (e.key === "Escape" || e.key === "Enter") {
319
+ swallow(e);
320
+ send({ type: "end" });
321
+ stop();
322
+ }
323
+ }
324
+
325
+ const SWALLOWED = ["pointerdown", "pointerup", "mousedown", "mouseup", "dblclick", "auxclick", "contextmenu", "submit"];
326
+ const listeners = [
327
+ ["mousemove", onMove],
328
+ ["click", onClick],
329
+ ["keydown", onKey],
330
+ ["keyup", (e) => { if (/^(Arrow(Up|Down)|Escape|Enter)$/.test(e.key)) swallow(e); }],
331
+ ["scroll", redraw],
332
+ ["resize", redraw],
333
+ ...SWALLOWED.map((type) => [type, swallow]),
334
+ ];
335
+ for (const [type, fn] of listeners) window.addEventListener(type, fn, true);
336
+
337
+ function stop() {
338
+ for (const [type, fn] of listeners) window.removeEventListener(type, fn, true);
339
+ if (frame) cancelAnimationFrame(frame);
340
+ host.remove();
341
+ if (globalThis.__gaiaPicker === api) delete globalThis.__gaiaPicker;
342
+ }
343
+
344
+ const api = {
345
+ stop,
346
+ /** Main's refs for the tokens it was sent: written on each element, where the agent's clicks find it. */
347
+ stamp(refs) {
348
+ for (const [token, ref] of Object.entries(refs)) {
349
+ const el = byToken.get(token);
350
+ if (el) el.setAttribute(pickAttr, ref);
351
+ }
352
+ },
353
+ /** Hidden while main takes a crop, so the outline is not in the picture. */
354
+ hide(hidden) {
355
+ host.style.display = hidden ? "none" : "block";
356
+ },
357
+ };
358
+ globalThis.__gaiaPicker = api;
359
+ return true;
360
+ })
@@ -0,0 +1,261 @@
1
+ // Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The element picker on one pane tab. picker-world.js runs in a CDP isolated
6
+ * world and reports the user's selection through a binding exposed only to
7
+ * that world, so the page can neither see the picker nor fake a pick. For
8
+ * each selected element this gives it a pick ref (p1, p2 ...), has the world
9
+ * stamp the ref on the element, reads the React component in the page's main
10
+ * world (fiber expandos are invisible from an isolated world), takes a crop,
11
+ * and hands the renderer a PickedElement per chip.
12
+ */
13
+
14
+ "use strict";
15
+
16
+ const crypto = require("crypto");
17
+ const fs = require("fs");
18
+ const path = require("path");
19
+
20
+ /** @typedef {import("./contract").PickedElement} PickedElement */
21
+
22
+ const WORLD_SOURCE = fs.readFileSync(path.join(__dirname, "picker-world.js"), "utf8");
23
+ const PICK_ATTR = "data-gaia-pick";
24
+ const STYLE_PROPS = Object.freeze([
25
+ "display", "position", "width", "height", "margin", "padding", "gap",
26
+ "color", "background-color", "font-family", "font-size", "font-weight", "line-height",
27
+ "border", "border-radius", "box-shadow", "opacity", "z-index",
28
+ ]);
29
+ const LIMITS = Object.freeze({ url: 2000, title: 300, label: 120, selector: 500, role: 40, name: 200, text: 300, html: 1536 });
30
+ const CROP_MAX_WIDTH = 800;
31
+ const CROP_MAX_HEIGHT = 1200;
32
+
33
+ // Runs in the page's main world, where React keeps its fibers on the DOM node.
34
+ // React 18 and older stamp _debugSource; React 19 dev keeps a _debugStack whose
35
+ // frame inside the component gives its file and line.
36
+ const REACT_LOOKUP_JS = `(sel) => {
37
+ const el = document.querySelector(sel);
38
+ if (!el) return null;
39
+ const key = Object.keys(el).find((k) => k.startsWith("__reactFiber$") || k.startsWith("__reactInternalInstance$"));
40
+ if (!key) return null;
41
+ const host = el[key];
42
+ for (let f = host; f; f = f.return) {
43
+ const t = f.type;
44
+ const fn = typeof t === "function" ? t : t && typeof t === "object" ? t.render || t.type : null;
45
+ const name = (t && t.displayName) || (fn && (fn.displayName || fn.name)) || "";
46
+ if (!name || typeof name !== "string") continue;
47
+ let source = null;
48
+ const ds = host._debugSource || f._debugSource;
49
+ if (ds && typeof ds.fileName === "string") source = { file: ds.fileName, line: Number(ds.lineNumber) || 0 };
50
+ const stack = host._debugStack && String(host._debugStack.stack || "");
51
+ if (!source && stack) {
52
+ const frame = stack.split("\\n").find((l) => l.includes(" " + name + " ") || l.includes(" " + name + "("));
53
+ const m = frame && /\\(?((?:https?|file):[^\\s()]+):(\\d+):\\d+\\)?\\s*$/.exec(frame);
54
+ if (m) {
55
+ let file = m[1];
56
+ try { const u = new URL(file); file = u.pathname; } catch {}
57
+ source = { file, line: Number(m[2]) || 0 };
58
+ }
59
+ }
60
+ return { name, source };
61
+ }
62
+ return null;
63
+ }`;
64
+
65
+ function clip(value, max) {
66
+ const s = String(value ?? "");
67
+ return s.length > max ? s.slice(0, max) : s;
68
+ }
69
+
70
+ function finite(n) {
71
+ return typeof n === "number" && Number.isFinite(n) ? n : 0;
72
+ }
73
+
74
+ /** Only the curated properties, as short strings. */
75
+ function pickStyles(styles) {
76
+ const out = {};
77
+ for (const prop of STYLE_PROPS) {
78
+ if (styles && typeof styles[prop] === "string") out[prop] = clip(styles[prop], 200);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** What the main world reported, kept only when it has the expected shape. */
84
+ function parseComponent(found) {
85
+ if (!found || typeof found.name !== "string" || !found.name) return null;
86
+ const src = found.source;
87
+ const source =
88
+ src && typeof src.file === "string" && src.file
89
+ ? { file: clip(src.file, 300), line: Math.max(0, Math.floor(finite(src.line))) }
90
+ : null;
91
+ return { name: clip(found.name, 120), source };
92
+ }
93
+
94
+ /**
95
+ * One chip's data from what the world described, capped the way the UI
96
+ * server validates it. The world computes the fields in page context, so a
97
+ * page can make them long or odd; it can't make them escape these limits.
98
+ *
99
+ * @returns {PickedElement}
100
+ */
101
+ function buildPickedElement(raw, { ref, component, crop }) {
102
+ const r = raw.rect || {};
103
+ return {
104
+ ref,
105
+ url: clip(raw.url, LIMITS.url),
106
+ title: clip(raw.title, LIMITS.title),
107
+ tag: /^[a-z][a-z0-9-]{0,39}$/.test(raw.tag) ? raw.tag : "element",
108
+ label: clip(raw.label, LIMITS.label),
109
+ selector: clip(raw.selector, LIMITS.selector),
110
+ role: clip(raw.role, LIMITS.role),
111
+ name: clip(raw.name, LIMITS.name),
112
+ text: clip(raw.text, LIMITS.text),
113
+ rect: { x: finite(r.x), y: finite(r.y), width: Math.max(0, finite(r.width)), height: Math.max(0, finite(r.height)) },
114
+ component,
115
+ outerHTML: clip(raw.outerHTML, LIMITS.html),
116
+ styles: pickStyles(raw.styles),
117
+ crop,
118
+ };
119
+ }
120
+
121
+ /** The crop's rect in page coordinates, or null when the element has no size to picture. */
122
+ function cropRect(raw) {
123
+ const r = raw.rect || {};
124
+ const s = raw.scroll || {};
125
+ const width = Math.min(finite(r.width), 4000);
126
+ const height = Math.min(finite(r.height), CROP_MAX_HEIGHT);
127
+ if (width < 1 || height < 1) return null;
128
+ return { x: Math.max(0, finite(r.x) + finite(s.x)), y: Math.max(0, finite(r.y) + finite(s.y)), width, height };
129
+ }
130
+
131
+ class PickerSession {
132
+ /**
133
+ * @param {{
134
+ * cdp: import("./cdp-session.cjs").TabCdp,
135
+ * wc: Electron.WebContents,
136
+ * allocateRef: () => string,
137
+ * encodeCrop: (png: Buffer, maxWidth: number) => string,
138
+ * onSelection: (elements: PickedElement[]) => void,
139
+ * onEnd: () => void,
140
+ * logger?: { error: (...args: any[]) => void },
141
+ * }} deps
142
+ */
143
+ constructor(deps) {
144
+ this.deps = deps;
145
+ this.logger = deps.logger || console;
146
+ this.binding = `__gaiaPick_${crypto.randomBytes(8).toString("hex")}`;
147
+ this.worldName = `gaia-picker-${crypto.randomBytes(8).toString("hex")}`;
148
+ this.contextId = null;
149
+ this.ended = false;
150
+ /** @type {Map<string, string>} world token to pick ref, so a chip keeps its ref while others come and go */
151
+ this.refs = new Map();
152
+ /** @type {Map<string, { component: PickedElement["component"], crop: string | null }>} by ref */
153
+ this.extras = new Map();
154
+ this.queue = Promise.resolve();
155
+ this.offBinding = null;
156
+ }
157
+
158
+ async start() {
159
+ const { cdp } = this.deps;
160
+ this.offBinding = cdp.onBinding((params) => this.onBinding(params));
161
+ await cdp.send("Runtime.addBinding", { name: this.binding, executionContextName: this.worldName });
162
+ const { frameTree } = await cdp.send("Page.getFrameTree");
163
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
164
+ frameId: frameTree.frame.id,
165
+ worldName: this.worldName,
166
+ grantUniveralAccess: false,
167
+ });
168
+ this.contextId = executionContextId;
169
+ const cfg = { binding: this.binding, pickAttr: PICK_ATTR, styleProps: STYLE_PROPS, maxHtml: LIMITS.html, maxText: LIMITS.text, maxName: LIMITS.name };
170
+ await this.inWorld(`(${WORLD_SOURCE})(${JSON.stringify(cfg)})`);
171
+ }
172
+
173
+ /** Ends picking; the chips made so far stay. Safe to call more than once. */
174
+ async stop() {
175
+ if (this.ended) return;
176
+ this.ended = true;
177
+ if (this.offBinding) this.offBinding();
178
+ const { cdp } = this.deps;
179
+ // The page may have navigated away, taking the world with it; then there is nothing to remove.
180
+ await this.inWorld("globalThis.__gaiaPicker && globalThis.__gaiaPicker.stop()").catch(() => {});
181
+ await cdp.send("Runtime.removeBinding", { name: this.binding }).catch((err) => {
182
+ this.logger.error(`[browser-pane] Could not remove the picker binding: ${err.message}`);
183
+ });
184
+ this.deps.onEnd();
185
+ }
186
+
187
+ async inWorld(expression) {
188
+ const res = await this.deps.cdp.send("Runtime.evaluate", { expression, contextId: this.contextId, returnByValue: true });
189
+ if (res && res.exceptionDetails) {
190
+ const d = res.exceptionDetails;
191
+ throw new Error((d.exception && d.exception.description) || d.text || "the picker script failed");
192
+ }
193
+ return res && res.result ? res.result.value : undefined;
194
+ }
195
+
196
+ onBinding(params) {
197
+ if (this.ended || params.name !== this.binding || params.executionContextId !== this.contextId) return;
198
+ let msg;
199
+ try {
200
+ msg = JSON.parse(params.payload);
201
+ } catch (err) {
202
+ this.logger.error(`[browser-pane] Ignored an unreadable message from the picker: ${err.message}`);
203
+ return;
204
+ }
205
+ if (msg.type === "end") {
206
+ this.stop().catch((err) => this.logger.error(`[browser-pane] Ending the picker failed: ${err.message}`));
207
+ } else if (msg.type === "selection" && Array.isArray(msg.elements)) {
208
+ // In order: a quick second click must not overtake the first.
209
+ this.queue = this.queue
210
+ .then(() => this.select(msg.elements))
211
+ .catch((err) => this.logger.error(`[browser-pane] Could not build the picked elements: ${err.message}`));
212
+ }
213
+ }
214
+
215
+ async select(raws) {
216
+ const fresh = {};
217
+ for (const raw of raws) {
218
+ if (!this.refs.has(raw.token)) {
219
+ const ref = this.deps.allocateRef();
220
+ this.refs.set(raw.token, ref);
221
+ fresh[raw.token] = ref;
222
+ }
223
+ }
224
+ if (Object.keys(fresh).length) await this.inWorld(`globalThis.__gaiaPicker.stamp(${JSON.stringify(fresh)})`);
225
+ const elements = [];
226
+ for (const raw of raws) {
227
+ const ref = this.refs.get(raw.token);
228
+ if (!this.extras.has(ref)) this.extras.set(ref, await this.extrasFor(ref, raw));
229
+ elements.push(buildPickedElement(raw, { ref, ...this.extras.get(ref) }));
230
+ }
231
+ if (!this.ended) this.deps.onSelection(elements);
232
+ }
233
+
234
+ async extrasFor(ref, raw) {
235
+ const selector = `[${PICK_ATTR}="${ref}"]`;
236
+ const found = await this.deps.wc.mainFrame
237
+ .executeJavaScript(`(${REACT_LOOKUP_JS})(${JSON.stringify(selector)})`, false)
238
+ .catch((err) => {
239
+ this.logger.error(`[browser-pane] Could not read the React component of ${ref}: ${err.message}`);
240
+ return null;
241
+ });
242
+ const crop = await this.crop(raw).catch((err) => {
243
+ this.logger.error(`[browser-pane] Could not take a picture of ${ref}; its chip has no screenshot: ${err.message}`);
244
+ return null;
245
+ });
246
+ return { component: parseComponent(found), crop };
247
+ }
248
+
249
+ async crop(raw) {
250
+ const rect = cropRect(raw);
251
+ if (!rect) return null;
252
+ await this.inWorld("globalThis.__gaiaPicker.hide(true)");
253
+ try {
254
+ return this.deps.encodeCrop(await this.deps.cdp.screenshot(rect), CROP_MAX_WIDTH);
255
+ } finally {
256
+ await this.inWorld("globalThis.__gaiaPicker && globalThis.__gaiaPicker.hide(false)").catch(() => {});
257
+ }
258
+ }
259
+ }
260
+
261
+ module.exports = { PICK_ATTR, PickerSession, REACT_LOOKUP_JS, STYLE_PROPS, buildPickedElement, cropRect, parseComponent };
@@ -0,0 +1,66 @@
1
+ // Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * Loopback ports GAIA's other services listen on, which no pane page may
6
+ * reach: the daemon (its port is in host/instance.json), the local model
7
+ * server, and the MCP bridge and adapters. The app's own backend and the pane
8
+ * bridge are added by main, which knows those ports first-hand.
9
+ */
10
+
11
+ "use strict";
12
+
13
+ const fs = require("fs");
14
+ const os = require("os");
15
+ const path = require("path");
16
+
17
+ /** Lemonade's default port; LEMONADE_BASE_URL can name another. Python: lemonade_client.DEFAULT_PORT. */
18
+ const LEMONADE_DEFAULT_PORT = 13305;
19
+ /** MCP bridge, Agent UI MCP, TUI MCP, Telegram and Slack health. Python: gaia/mcp/ports.py. */
20
+ const MCP_PORTS = [8765, 8766, 8767, 8768, 8769];
21
+ const CACHE_MS = 5000;
22
+
23
+ /** Where the daemon records its port. Python: gaia/daemon/paths.py host_dir(). */
24
+ function daemonInstanceFile(env = process.env, home = os.homedir()) {
25
+ if (env.GAIA_DAEMON_HOME) return path.join(env.GAIA_DAEMON_HOME, "instance.json");
26
+ const gaiaHome = (env.GAIA_HOME || "").trim();
27
+ if (gaiaHome) return path.join(gaiaHome.replace(/^~(?=$|[\\/])/, home), "host", "instance.json");
28
+ return path.join(home, ".gaia", "host", "instance.json");
29
+ }
30
+
31
+ function portOfUrl(raw) {
32
+ try {
33
+ const url = new URL(raw);
34
+ if (url.port) return Number(url.port);
35
+ return url.protocol === "https:" ? 443 : 80;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ /** The ports, read now: a missing or unreadable daemon record just leaves its port out. */
42
+ function readServicePorts({ env = process.env, home = os.homedir(), readFile = fs.readFileSync, logger = console } = {}) {
43
+ const ports = new Set([LEMONADE_DEFAULT_PORT, ...MCP_PORTS]);
44
+ const lemonade = env.LEMONADE_BASE_URL ? portOfUrl(env.LEMONADE_BASE_URL) : null;
45
+ if (lemonade) ports.add(lemonade);
46
+ const file = daemonInstanceFile(env, home);
47
+ try {
48
+ const port = Number(JSON.parse(readFile(file, "utf8")).port);
49
+ if (Number.isInteger(port) && port > 0 && port < 65536) ports.add(port);
50
+ } catch (err) {
51
+ if (err.code !== "ENOENT") logger.error(`[browser-pane] Could not read the daemon's port from ${file}: ${err.message}`);
52
+ }
53
+ return [...ports];
54
+ }
55
+
56
+ /** readServicePorts, cached for a few seconds: the request filter asks on every request. */
57
+ function servicePorts(opts = {}) {
58
+ const now = Date.now();
59
+ const cache = servicePorts.cache;
60
+ if (cache && now - cache.at < CACHE_MS) return cache.ports;
61
+ const ports = readServicePorts(opts);
62
+ servicePorts.cache = { at: now, ports };
63
+ return ports;
64
+ }
65
+
66
+ module.exports = { LEMONADE_DEFAULT_PORT, MCP_PORTS, daemonInstanceFile, readServicePorts, servicePorts };