browser: frames from other sites are read and acted on; failures say their kind
A page's cross-site iframes (out-of-process frames) were missing from the
snapshot: Page.getFrameTree on the parent doesn't list them, so a checkout
form or a login inside such a frame couldn't be read or clicked. The
snapshot now adds each frame whose session was auto-attached under its
parent (t.frameOf), and actions on its refs go to that frame's session.
A failed action now says its kind (STALE_REF, DIALOG_OPEN, LOAD_FAILED,
PAGE_BLOCKED, WAIT_TIMEOUT, OUTCOME_UNKNOWN, BAD_ARGS ...) with what to try next, and an action
settles on the DOM going quiet before it says done. Extension 0.1.3.
Run on mote at this head: go test -tags nogui -run Browser
./internal/gateway/ ./internal/browserext/ with a real Chromium
(MAGPIE_BROWSER_CHROME, Chrome for Testing 1234): ok, including
TestBrowserFramesAndFailuresInARealBrowser. Red on the old code ("no
textbox Card"); the settle taken out by hand made it red ("doesn't say
done"). gofmt clean; go vet -tags nogui for darwin, linux and windows ok.
Not tried: a real site's payment iframe in the owner's own Chrome.
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
// out in this browser's own tabs, signed in to whatever the user is.
|
||||
|
||||
import { GATEWAY } from "./config.js";
|
||||
import { attach, forget, send, settle, sleep, state, waitLoad } from "./cdp.js";
|
||||
import { attach, fault, forget, send, settle, sleep, state, waitLoad, watch } from "./cdp.js";
|
||||
import { find, take } from "./snapshot.js";
|
||||
import { press as keyPress, typeSlowly } from "./keys.js";
|
||||
|
||||
@@ -137,7 +137,7 @@ chrome.tabs.onRemoved.addListener((tabId) => {
|
||||
function tabArg(v) {
|
||||
if (v === undefined || v === null || v === "") return null;
|
||||
const m = /^t?(\d+)$/i.exec(String(v).trim());
|
||||
if (!m) throw new Error(`"${v}" isn't a tab: tabs look like t123, from browser_tabs`);
|
||||
if (!m) throw fault("BAD_ARGS", `"${v}" isn't a tab: tabs look like t123, from browser_tabs`);
|
||||
return Number(m[1]);
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ async function tabFor(session, args) {
|
||||
await loadSessions();
|
||||
const named = tabArg(args.tab);
|
||||
if (named !== null) {
|
||||
await chrome.tabs.get(named).catch(() => { throw new Error(`there is no tab t${named} now: call browser_tabs for the open ones`); });
|
||||
await chrome.tabs.get(named).catch(() => { throw fault("BAD_ARGS", `there is no tab t${named} now: call browser_tabs for the open ones`); });
|
||||
sessions.set(session, named);
|
||||
saveSessions();
|
||||
return named;
|
||||
@@ -158,7 +158,7 @@ async function tabFor(session, args) {
|
||||
if (ok) return had;
|
||||
}
|
||||
const [active] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
|
||||
if (!active) throw new Error("no browser window is open: open one, or call browser_tabs with action new");
|
||||
if (!active) throw fault("BAD_ARGS", "no browser window is open: open one, or call browser_tabs with action new");
|
||||
if (heldByOther(session, active.id)) {
|
||||
// another agent works in the tab the user is looking at: this one is
|
||||
// given a tab of its own, behind it, in its own group
|
||||
@@ -208,13 +208,37 @@ async function group(session, tabId, windowId) {
|
||||
const text = (s) => ({ type: "text", text: s });
|
||||
const fail = (s) => ({ content: [text(s)], isError: true });
|
||||
|
||||
// what each kind of failure means for trying again, said after it
|
||||
const AFTER = {
|
||||
STALE_REF: "Take a snapshot and use a ref from it.",
|
||||
AMBIGUOUS: "Take a snapshot and pick one.",
|
||||
UNACTIONABLE: "The same call fails the same way until the page changes.",
|
||||
BAD_ARGS: "Fix the arguments; the call did nothing.",
|
||||
WAIT_TIMEOUT: "The page may still be working: wait again, or take a snapshot to see where it is.",
|
||||
SITE_REFUSED: "The site turned the browser away. Don't try again at once: tell the user, who may need to sign in or wait.",
|
||||
LOAD_FAILED: "The address didn't load: check it, or the user's connection.",
|
||||
PAGE_BLOCKED: "Nothing works in this tab until that changes: use another tab.",
|
||||
OUTCOME_UNKNOWN: "It may or may not have happened: take a snapshot to see before doing it again, since a form or a purchase could go twice.",
|
||||
};
|
||||
const GONE = /Execution context was destroyed|Cannot find context|Inspected target navigated or closed|Target closed|No node with given id|Could not find node|Node with given id does not belong/i;
|
||||
|
||||
// failure answers with the kind of failure first (STALE_REF: …) and what
|
||||
// it means for trying again
|
||||
function failure(e) {
|
||||
const m = String((e && e.message) || e);
|
||||
const code = (e && e.code) || (GONE.test(m) ? "STALE_REF" : "");
|
||||
if (!code) return fail(m);
|
||||
const after = AFTER[code] || "";
|
||||
return fail(`${code}: ${m}${after && !m.includes(after) ? "\n" + after : ""}`);
|
||||
}
|
||||
|
||||
async function run(m) {
|
||||
try {
|
||||
const tool = TOOLS[m.tool];
|
||||
if (!tool) return fail(`magpie's browser extension has no tool ${m.tool}: update it (magpie writes it again on start; reload it in chrome://extensions)`);
|
||||
return await tool(m.session || "default", m.args || {});
|
||||
} catch (e) {
|
||||
return fail(String((e && e.message) || e));
|
||||
return failure(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,7 +247,7 @@ async function ready(session, args) {
|
||||
const t = state(tabId);
|
||||
if (t.stoppedByUser) {
|
||||
t.stoppedByUser = false;
|
||||
throw new Error("the user stopped Magpie Browser in this tab (Cancel on Chrome's bar): ask them before going on. The next call attaches to it again.");
|
||||
throw fault("USER_STOPPED", "the user stopped Magpie Browser in this tab (Cancel on Chrome's bar): ask them before going on. The next call attaches to it again.");
|
||||
}
|
||||
t.by = session; // whose call this is: act moves that session on to a tab it opens
|
||||
await attach(tabId);
|
||||
@@ -251,12 +275,31 @@ function notices(t) {
|
||||
return out;
|
||||
}
|
||||
|
||||
const dialogOpen = (t) => fail("DIALOG_OPEN: " + notices(t).join("\n"));
|
||||
|
||||
// roles a click is for: one that changes nothing on the page did nothing
|
||||
// a reader can see (a checkbox's tick is no change to the document)
|
||||
const PRESSES = new Set(["button", "link", "clickable", "menuitem", "tab", "treeitem", "PopUpButton", "DisclosureTriangle"]);
|
||||
|
||||
// look is what a click can be seen to change: the address, the page's
|
||||
// scroll, its requests and its document (the element's frame and the main
|
||||
// one); null where a part can't be read
|
||||
async function look(t, el) {
|
||||
const tab = await chrome.tabs.get(t.tabId).catch(() => null);
|
||||
const scroll = await send(t.tabId, "Runtime.evaluate", { expression: "scrollX + ',' + scrollY", returnByValue: true }).then((r) => r.result.value, () => null);
|
||||
const doc = [await watch(t)];
|
||||
if (el && (el.sid || el.frame)) doc.push(await watch(t, el.frame, el.sid));
|
||||
return { url: tab && tab.url, scroll, reqs: t.reqs, doc: doc.map((d) => (d ? d[0] : null)) };
|
||||
}
|
||||
|
||||
// act runs an action, waits for the page to settle and answers with what
|
||||
// happened and the page after it. A dialog the action opens stops the
|
||||
// page; it is reported rather than waited on.
|
||||
async function act(t, what, fn) {
|
||||
if (t.dialog) return fail(notices(t).join("\n"));
|
||||
async function act(t, what, fn, el = null, press = false) {
|
||||
if (t.dialog) return dialogOpen(t);
|
||||
const before = new Set((await chrome.tabs.query({})).map((x) => x.id));
|
||||
const was = press ? await look(t, el) : null;
|
||||
t.sentInput = false;
|
||||
let opened = null;
|
||||
const onCreated = (tab) => { if (!before.has(tab.id) && (tab.openerTabId === t.tabId || !opened)) opened = tab; };
|
||||
chrome.tabs.onCreated.addListener(onCreated);
|
||||
@@ -268,10 +311,15 @@ async function act(t, what, fn) {
|
||||
p,
|
||||
(async () => { while (!t.dialog) await sleep(100); return ""; })(),
|
||||
]);
|
||||
} catch (e) {
|
||||
// the page went away under an action already under way: what it did
|
||||
// isn't known
|
||||
if (t.sentInput && !e.code) throw fault("OUTCOME_UNKNOWN", `${what.replace(/\.$/, "")} was under way when the page changed (${String(e.message || e).slice(0, 200)})`);
|
||||
throw e;
|
||||
} finally {
|
||||
setTimeout(() => chrome.tabs.onCreated.removeListener(onCreated), 1500);
|
||||
}
|
||||
if (!t.dialog) await settle(t);
|
||||
if (!t.dialog) await settle(t, 2500, 400, el ? [el] : []);
|
||||
const out = [];
|
||||
if (said) out.push(said);
|
||||
else out.push(what);
|
||||
@@ -288,6 +336,12 @@ async function act(t, what, fn) {
|
||||
out.push("", await page(nt));
|
||||
return { content: [text(out.join("\n"))] };
|
||||
}
|
||||
if (was && !opened && !t.answered) {
|
||||
const now = await look(t, el);
|
||||
const same = now.url === was.url && now.scroll === was.scroll && now.reqs === was.reqs &&
|
||||
now.doc.every((d, i) => d !== null && was.doc[i] !== null && d === was.doc[i]);
|
||||
if (same) out.push(`NO_EFFECT: nothing on the page changed after it: no new content, no request, no new address. It may not have worked, or it acts out of sight (a copy to the clipboard). Check with a screenshot before trying again, and never press a send, buy or post button a second time to see.`);
|
||||
}
|
||||
out.push("", await page(t));
|
||||
return { content: [text(out.join("\n"))] };
|
||||
}
|
||||
@@ -295,14 +349,16 @@ async function act(t, what, fn) {
|
||||
// point is where to click an element: the middle of its first box that
|
||||
// isn't covered by something else, scrolled into view
|
||||
async function point(t, el) {
|
||||
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }).catch(() => {});
|
||||
if (el.sid) await reveal(t, el.sid);
|
||||
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }, el.sid).catch(() => {});
|
||||
const off = await offset(t, el.sid);
|
||||
let quads;
|
||||
try {
|
||||
quads = (await send(t.tabId, "DOM.getContentQuads", { backendNodeId: el.backend })).quads;
|
||||
quads = (await send(t.tabId, "DOM.getContentQuads", { backendNodeId: el.backend }, el.sid)).quads;
|
||||
} catch {
|
||||
quads = [];
|
||||
}
|
||||
if (!quads.length) throw new Error(`${el.ref} (${el.role} "${el.name}") has no box on the page (hidden or collapsed): open what holds it first, or take a snapshot`);
|
||||
if (!quads.length) throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") has no box on the page (hidden or collapsed): open what holds it first, or take a snapshot`);
|
||||
const q = quads[0];
|
||||
const xs = [q[0], q[2], q[4], q[6]], ys = [q[1], q[3], q[5], q[7]];
|
||||
const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);
|
||||
@@ -324,13 +380,44 @@ async function point(t, el) {
|
||||
}`,
|
||||
arguments: [{ value: x }, { value: y }],
|
||||
returnByValue: true,
|
||||
}).catch(() => ({ result: { value: "" } }));
|
||||
}, el.sid).catch(() => ({ result: { value: "" } }));
|
||||
const v = r.result.value;
|
||||
if (!v) return { x, y };
|
||||
// the mouse goes to the tab, in the page's own coordinates
|
||||
if (!v) return { x: x + off.x, y: y + off.y };
|
||||
if (v !== "outside") cover = v;
|
||||
}
|
||||
if (cover) throw new Error(`${el.ref} (${el.role} "${el.name}") is covered by ${cover}: close or move what covers it (a dialog, a cookie banner, a menu) and try again`);
|
||||
throw new Error(`${el.ref} (${el.role} "${el.name}") is outside the window: scroll to it (browser_scroll) and try again`);
|
||||
if (cover) throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") is covered by ${cover}: close or move what covers it (a dialog, a cookie banner, a menu) and try again`);
|
||||
throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") is outside the window: scroll to it (browser_scroll) and try again`);
|
||||
}
|
||||
|
||||
// reveal scrolls the frames from other sites that hold an element (its
|
||||
// session sid) into view, the innermost first
|
||||
async function reveal(t, sid) {
|
||||
for (let n = 0; sid && n < 8; n++) {
|
||||
const f = t.frameOf.get(sid);
|
||||
if (!f) return;
|
||||
try {
|
||||
const { backendNodeId } = await send(t.tabId, "DOM.getFrameOwner", { frameId: f.frame }, f.parent);
|
||||
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId }, f.parent);
|
||||
} catch {}
|
||||
sid = f.parent;
|
||||
}
|
||||
}
|
||||
|
||||
// offset is where the document of a frame from another site (session sid)
|
||||
// starts in the tab's: that frame's session measures from its own corner
|
||||
async function offset(t, sid) {
|
||||
let x = 0, y = 0;
|
||||
for (let n = 0; sid && n < 8; n++) {
|
||||
const f = t.frameOf.get(sid);
|
||||
if (!f) throw fault("STALE_REF", "the frame that element was in has gone");
|
||||
const { backendNodeId } = await send(t.tabId, "DOM.getFrameOwner", { frameId: f.frame }, f.parent);
|
||||
const { model } = await send(t.tabId, "DOM.getBoxModel", { backendNodeId }, f.parent);
|
||||
x += model.content[0];
|
||||
y += model.content[1];
|
||||
sid = f.parent;
|
||||
}
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
const BUTTONS = { left: "left", right: "right", middle: "middle" };
|
||||
@@ -353,14 +440,14 @@ async function call(t, el, fn, args = []) {
|
||||
const r = await send(t.tabId, "Runtime.callFunctionOn", {
|
||||
objectId: el.objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })),
|
||||
returnByValue: true, awaitPromise: true,
|
||||
});
|
||||
}, el.sid);
|
||||
if (r.exceptionDetails) throw new Error((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text);
|
||||
return r.result.value;
|
||||
}
|
||||
|
||||
function need(args, ...names) {
|
||||
for (const n of names) {
|
||||
if (args[n] === undefined || args[n] === null || args[n] === "") throw new Error(`${n} is needed`);
|
||||
if (args[n] === undefined || args[n] === null || args[n] === "") throw fault("BAD_ARGS", `${n} is needed`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,7 +480,7 @@ const TOOLS = {
|
||||
}
|
||||
if (action === "close") {
|
||||
const id = args.tab ? tabArg(args.tab) : sessions.get(session);
|
||||
if (id === undefined || id === null) throw new Error("tab is needed");
|
||||
if (id === undefined || id === null) throw fault("BAD_ARGS", "tab is needed");
|
||||
await chrome.tabs.remove(id);
|
||||
return { content: [text(`Closed t${id}.`)] };
|
||||
}
|
||||
@@ -414,26 +501,33 @@ const TOOLS = {
|
||||
} else if (go === "back" || go === "forward") {
|
||||
const h = await send(t.tabId, "Page.getNavigationHistory");
|
||||
const e = h.entries[h.currentIndex + (go === "back" ? -1 : 1)];
|
||||
if (!e) throw new Error(`there is no page to go ${go} to`);
|
||||
if (!e) throw fault("BAD_ARGS", `there is no page to go ${go} to`);
|
||||
await send(t.tabId, "Page.navigateToHistoryEntry", { entryId: e.id });
|
||||
said = `Went ${go} to ${e.url}.`;
|
||||
} else {
|
||||
need(args, "url");
|
||||
const url = withScheme(args.url);
|
||||
t.loading = true;
|
||||
t.docStatus = 0;
|
||||
const r = await send(t.tabId, "Page.navigate", { url });
|
||||
if (r.errorText) { t.loading = false; throw new Error(`${url} didn't load: ${r.errorText}`); }
|
||||
if (r.errorText) { t.loading = false; throw fault("LOAD_FAILED", `${url} didn't load: ${r.errorText}`); }
|
||||
said = `Opened ${url}.`;
|
||||
}
|
||||
const loaded = await waitLoad(t);
|
||||
await settle(t);
|
||||
if (!loaded) said += " (It is still loading after 30s.)";
|
||||
return { content: [text([said, ...notices(t), "", await page(t)].join("\n"))] };
|
||||
const out = [said, ...notices(t), "", await page(t)].join("\n");
|
||||
// a sign-in wall, a bot check or a rate limit: the page shown is the
|
||||
// site's refusal, not what was asked for
|
||||
if (go !== "back" && go !== "forward" && [401, 403, 429, 999].includes(t.docStatus)) {
|
||||
return fail(`SITE_REFUSED: the site answered ${t.docStatus} (${t.docStatus === 429 ? "too many requests" : t.docStatus === 401 ? "not signed in" : "refused"}).\n${AFTER.SITE_REFUSED}\n\n${out}`);
|
||||
}
|
||||
return { content: [text(out)] };
|
||||
},
|
||||
|
||||
async browser_snapshot(session, args) {
|
||||
const t = await ready(session, args);
|
||||
if (t.dialog) return fail(notices(t).join("\n"));
|
||||
if (t.dialog) return dialogOpen(t);
|
||||
const s = await take(t, { interactive: !!args.interactive, ref: args.ref, maxChars: Math.min(Number(args.maxChars) || 60000, 200000) });
|
||||
return { content: [text(`${await head(t)}\n${s.count} refs, ${s.interactive} to act on\n\n${s.text || "(the page shows nothing)"}`)] };
|
||||
},
|
||||
@@ -445,7 +539,7 @@ const TOOLS = {
|
||||
return act(t, `Clicked ${el.ref} (${el.role} "${el.name}").`, async () => {
|
||||
const p = await point(t, el);
|
||||
await mouse(t, p.x, p.y, args);
|
||||
});
|
||||
}, el, PRESSES.has(el.role) && !args.button && !args.double);
|
||||
},
|
||||
|
||||
async browser_hover(session, args) {
|
||||
@@ -455,12 +549,12 @@ const TOOLS = {
|
||||
return act(t, `Hovering over ${el.ref}.`, async () => {
|
||||
const p = await point(t, el);
|
||||
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y });
|
||||
});
|
||||
}, el);
|
||||
},
|
||||
|
||||
async browser_type(session, args) {
|
||||
need(args, "ref");
|
||||
if (typeof args.text !== "string") throw new Error("text is needed");
|
||||
if (typeof args.text !== "string") throw fault("BAD_ARGS", "text is needed");
|
||||
const t = await ready(session, args);
|
||||
const el = await find(t, args.ref);
|
||||
return act(t, `Typed into ${el.ref}${args.submit ? " and pressed Enter" : ""}.`, async () => {
|
||||
@@ -483,12 +577,12 @@ const TOOLS = {
|
||||
}
|
||||
return true;
|
||||
}`, [args.clear !== false]);
|
||||
if (!ok) throw new Error(`${el.ref} (${el.role} "${el.name}") doesn't take text: click the field itself`);
|
||||
if (!ok) throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") doesn't take text: click the field itself`);
|
||||
if (args.clear !== false) await keyPress(t, "Delete");
|
||||
if (args.slowly) await typeSlowly(t, args.text);
|
||||
else if (args.text) await send(t.tabId, "Input.insertText", { text: args.text });
|
||||
if (args.submit) await keyPress(t, "Enter");
|
||||
});
|
||||
}, el);
|
||||
},
|
||||
|
||||
async browser_press(session, args) {
|
||||
@@ -499,13 +593,13 @@ const TOOLS = {
|
||||
return act(t, `Pressed ${args.key}.`, async () => {
|
||||
if (el) await call(t, el, "function(){ this.focus() }");
|
||||
await keyPress(t, args.key);
|
||||
});
|
||||
}, el);
|
||||
},
|
||||
|
||||
async browser_select(session, args) {
|
||||
need(args, "ref");
|
||||
const values = Array.isArray(args.values) ? args.values.map(String) : args.value !== undefined ? [String(args.value)] : [];
|
||||
if (!values.length) throw new Error("values is needed");
|
||||
if (!values.length) throw fault("BAD_ARGS", "values is needed");
|
||||
const t = await ready(session, args);
|
||||
const el = await find(t, args.ref);
|
||||
return act(t, `Chose ${values.map((v) => JSON.stringify(v)).join(", ")} in ${el.ref}.`, async () => {
|
||||
@@ -525,8 +619,8 @@ const TOOLS = {
|
||||
s.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
return "";
|
||||
}`, [values]);
|
||||
if (why) throw new Error(`${el.ref} (${el.role} "${el.name}") ${why}`);
|
||||
});
|
||||
if (why) throw fault(/^takes one/.test(why) ? "BAD_ARGS" : "UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") ${why}`);
|
||||
}, el);
|
||||
},
|
||||
|
||||
async browser_scroll(session, args) {
|
||||
@@ -537,10 +631,14 @@ const TOOLS = {
|
||||
if (args.ref) {
|
||||
const el = await find(t, args.ref);
|
||||
if (!args.direction) {
|
||||
return act(t, `Scrolled ${el.ref} into view.`, () => send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }));
|
||||
return act(t, `Scrolled ${el.ref} into view.`, async () => {
|
||||
if (el.sid) await reveal(t, el.sid);
|
||||
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }, el.sid);
|
||||
}, el);
|
||||
}
|
||||
const q = (await send(t.tabId, "DOM.getContentQuads", { backendNodeId: el.backend }).catch(() => ({ quads: [] }))).quads[0];
|
||||
if (q) { x = (q[0] + q[4]) / 2; y = (q[1] + q[5]) / 2; }
|
||||
const off = await offset(t, el.sid);
|
||||
const q = (await send(t.tabId, "DOM.getContentQuads", { backendNodeId: el.backend }, el.sid).catch(() => ({ quads: [] }))).quads[0];
|
||||
if (q) { x = (q[0] + q[4]) / 2 + off.x; y = (q[1] + q[5]) / 2 + off.y; }
|
||||
}
|
||||
const dir = args.direction || "down";
|
||||
const amount = Number(args.amount) || Math.round((dir === "left" || dir === "right" ? vw.clientWidth : vw.clientHeight) * 0.8);
|
||||
@@ -573,30 +671,30 @@ const TOOLS = {
|
||||
} finally {
|
||||
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x: q.x, y: q.y, button: "left", clickCount: 1 });
|
||||
}
|
||||
});
|
||||
}, a);
|
||||
},
|
||||
|
||||
async browser_upload(session, args) {
|
||||
need(args, "ref");
|
||||
const files = Array.isArray(args.paths) ? args.paths.map(String) : [];
|
||||
if (!files.length) throw new Error("paths is needed: the files' full paths on this computer");
|
||||
if (!files.length) throw fault("BAD_ARGS", "paths is needed: the files' full paths on this computer");
|
||||
const t = await ready(session, args);
|
||||
const el = await find(t, args.ref);
|
||||
return act(t, `Chose ${files.length} file${files.length > 1 ? "s" : ""} in ${el.ref}.`, async () => {
|
||||
const isInput = await call(t, el, 'function(){ return this.tagName === "INPUT" && this.type === "file" }');
|
||||
const set = (backendNodeId) => send(t.tabId, "DOM.setFileInputFiles", { files, backendNodeId }).catch((e) => {
|
||||
const set = (backendNodeId, sid) => send(t.tabId, "DOM.setFileInputFiles", { files, backendNodeId }, sid).catch((e) => {
|
||||
const m = String(e.message || e);
|
||||
if (/not allowed|permission|denied/i.test(m)) throw new Error("Chrome didn't let Magpie Browser choose files: turn on \"Allow access to file URLs\" for Magpie Browser in chrome://extensions");
|
||||
if (/not allowed|permission|denied/i.test(m)) throw fault("UNACTIONABLE", "Chrome didn't let Magpie Browser choose files: turn on \"Allow access to file URLs\" for Magpie Browser in chrome://extensions");
|
||||
throw e;
|
||||
});
|
||||
if (isInput) return void (await set(el.backend));
|
||||
if (isInput) return void (await set(el.backend, el.sid));
|
||||
// a button that opens the file picker: the picker is caught and
|
||||
// answered with the files
|
||||
await send(t.tabId, "Page.setInterceptFileChooserDialog", { enabled: true });
|
||||
try {
|
||||
const opened = new Promise((resolve, reject) => {
|
||||
t.chooser = resolve;
|
||||
setTimeout(() => reject(new Error(`clicking ${el.ref} opened no file picker: use the file field's ref`)), 5000);
|
||||
setTimeout(() => reject(fault("UNACTIONABLE", `clicking ${el.ref} opened no file picker: use the file field's ref`)), 5000);
|
||||
});
|
||||
const p = await point(t, el);
|
||||
await mouse(t, p.x, p.y);
|
||||
@@ -606,7 +704,7 @@ const TOOLS = {
|
||||
t.chooser = null;
|
||||
await send(t.tabId, "Page.setInterceptFileChooserDialog", { enabled: false }).catch(() => {});
|
||||
}
|
||||
});
|
||||
}, el);
|
||||
},
|
||||
|
||||
async browser_wait(session, args) {
|
||||
@@ -616,17 +714,17 @@ const TOOLS = {
|
||||
await sleep(Math.min(Number(args.seconds), 60) * 1000);
|
||||
return { content: [text([`Waited ${args.seconds}s.`, ...notices(t), "", await page(t)].join("\n"))] };
|
||||
}
|
||||
if (!args.text && !args.textGone && !args.url) throw new Error("text, textGone, url or seconds is needed");
|
||||
if (!args.text && !args.textGone && !args.url) throw fault("BAD_ARGS", "text, textGone, url or seconds is needed");
|
||||
const end = Date.now() + bound;
|
||||
for (;;) {
|
||||
if (t.dialog) return fail(notices(t).join("\n"));
|
||||
if (t.dialog) return dialogOpen(t);
|
||||
const r = await send(t.tabId, "Runtime.evaluate", { expression: "[location.href, document.body ? document.body.innerText : '']", returnByValue: true }).catch(() => null);
|
||||
if (r && r.result && r.result.value) {
|
||||
const [href, body] = r.result.value;
|
||||
const ok = (!args.text || body.includes(args.text)) && (!args.textGone || !body.includes(args.textGone)) && (!args.url || href.includes(args.url));
|
||||
if (ok) break;
|
||||
}
|
||||
if (Date.now() > end) throw new Error(`waited ${bound / 1000}s and the page still ${args.text ? `doesn't show "${args.text}"` : args.textGone ? `shows "${args.textGone}"` : `isn't at ${args.url}`}`);
|
||||
if (Date.now() > end) throw fault("WAIT_TIMEOUT", `waited ${bound / 1000}s and the page still ${args.text ? `doesn't show "${args.text}"` : args.textGone ? `shows "${args.textGone}"` : `isn't at ${args.url}`}`);
|
||||
await sleep(250);
|
||||
}
|
||||
await settle(t);
|
||||
@@ -635,14 +733,16 @@ const TOOLS = {
|
||||
|
||||
async browser_screenshot(session, args) {
|
||||
const t = await ready(session, args);
|
||||
if (t.dialog) return fail(notices(t).join("\n"));
|
||||
if (t.dialog) return dialogOpen(t);
|
||||
const params = { format: args.png ? "png" : "jpeg", ...(args.png ? {} : { quality: 80 }) };
|
||||
if (args.ref) {
|
||||
const el = await find(t, args.ref);
|
||||
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }).catch(() => {});
|
||||
const { model } = await send(t.tabId, "DOM.getBoxModel", { backendNodeId: el.backend });
|
||||
if (el.sid) await reveal(t, el.sid);
|
||||
await send(t.tabId, "DOM.scrollIntoViewIfNeeded", { backendNodeId: el.backend }, el.sid).catch(() => {});
|
||||
const off = await offset(t, el.sid);
|
||||
const { model } = await send(t.tabId, "DOM.getBoxModel", { backendNodeId: el.backend }, el.sid);
|
||||
const b = model.border;
|
||||
const xs = [b[0], b[2], b[4], b[6]], ys = [b[1], b[3], b[5], b[7]];
|
||||
const xs = [b[0], b[2], b[4], b[6]].map((v) => v + off.x), ys = [b[1], b[3], b[5], b[7]].map((v) => v + off.y);
|
||||
const lm = await send(t.tabId, "Page.getLayoutMetrics");
|
||||
const vv = lm.cssVisualViewport;
|
||||
params.clip = { x: Math.min(...xs) + vv.pageX, y: Math.min(...ys) + vv.pageY, width: Math.max(1, Math.max(...xs) - Math.min(...xs)), height: Math.max(1, Math.max(...ys) - Math.min(...ys)), scale: 1 };
|
||||
@@ -667,7 +767,7 @@ const TOOLS = {
|
||||
async browser_evaluate(session, args) {
|
||||
need(args, "script");
|
||||
const t = await ready(session, args);
|
||||
if (t.dialog) return fail(notices(t).join("\n"));
|
||||
if (t.dialog) return dialogOpen(t);
|
||||
const src = String(args.script).trim();
|
||||
// async may touch its parameters (async()=>…), and a parameter list
|
||||
// holds no parentheses, so (async () => …)() stays an expression.
|
||||
@@ -678,13 +778,13 @@ const TOOLS = {
|
||||
r = await send(t.tabId, "Runtime.callFunctionOn", {
|
||||
objectId: el.objectId, returnByValue: true, awaitPromise: true,
|
||||
functionDeclaration: fn ? `function() { return (${src})(this); }` : `function() { return (${src}); }`,
|
||||
});
|
||||
}, el.sid);
|
||||
} else {
|
||||
r = await send(t.tabId, "Runtime.evaluate", { expression: fn ? `(${src})()` : src, returnByValue: true, awaitPromise: true, userGesture: true });
|
||||
}
|
||||
if (r.exceptionDetails) {
|
||||
const d = r.exceptionDetails;
|
||||
throw new Error("the script threw: " + ((d.exception && d.exception.description) || d.text));
|
||||
throw fault("SCRIPT_ERROR", "the script threw: " + ((d.exception && d.exception.description) || d.text));
|
||||
}
|
||||
let out = r.result.value === undefined ? (r.result.description || r.result.type) : JSON.stringify(r.result.value, null, 1);
|
||||
if (out && out.length > 20000) out = out.slice(0, 20000) + "\n… (cut at 20000 characters)";
|
||||
@@ -693,7 +793,7 @@ const TOOLS = {
|
||||
|
||||
async browser_text(session, args) {
|
||||
const t = await ready(session, args);
|
||||
if (t.dialog) return fail(notices(t).join("\n"));
|
||||
if (t.dialog) return dialogOpen(t);
|
||||
const max = Math.min(Number(args.maxChars) || 40000, 200000);
|
||||
const r = await send(t.tabId, "Runtime.evaluate", { expression: "document.body ? document.body.innerText : ''", returnByValue: true });
|
||||
let s = String(r.result.value || "").replace(/\n{3,}/g, "\n\n").trim();
|
||||
|
||||
+136
-11
@@ -16,8 +16,14 @@ export function state(tabId) {
|
||||
tabId, attached: false, attaching: null, idle: 0,
|
||||
refs: new Map(), keys: new Map(), next: 1, doc: "",
|
||||
logs: [], dialog: null, answer: null, chooser: null,
|
||||
inflight: new Map(), lastNet: 0, loading: false,
|
||||
inflight: new Map(), lastNet: 0, loading: false, reqs: 0,
|
||||
stoppedByUser: false,
|
||||
// a frame from another site runs in a process of its own, reached
|
||||
// through a session of its own: frame id → session, and session →
|
||||
// { frame, parent session }
|
||||
children: new Map(), frameOf: new Map(),
|
||||
worlds: new Map(), // "session|frame" → the isolated world settle reads
|
||||
sentInput: false,
|
||||
};
|
||||
tabs.set(tabId, t);
|
||||
}
|
||||
@@ -41,10 +47,13 @@ export async function attach(tabId) {
|
||||
await chrome.debugger.attach({ tabId }, "1.3");
|
||||
} catch (e) {
|
||||
const m = String(e && e.message || e);
|
||||
if (!/already attached/i.test(m)) throw new Error(why(m));
|
||||
if (!/already attached/i.test(m)) throw fault("PAGE_BLOCKED", why(m));
|
||||
}
|
||||
t.attached = true;
|
||||
t.stoppedByUser = false;
|
||||
t.children.clear();
|
||||
t.frameOf.clear();
|
||||
t.worlds.clear();
|
||||
await Promise.all([
|
||||
send(tabId, "Page.enable"),
|
||||
send(tabId, "Runtime.enable"),
|
||||
@@ -53,6 +62,10 @@ export async function attach(tabId) {
|
||||
send(tabId, "Accessibility.enable"),
|
||||
]);
|
||||
await send(tabId, "Page.setInterceptFileChooserDialog", { enabled: false }).catch(() => {});
|
||||
// frames from other sites: Chrome 125 and on hands an extension
|
||||
// their sessions; before it they stay unreadable, as said in the
|
||||
// snapshot
|
||||
await autoAttach(tabId);
|
||||
})().finally(() => { t.attaching = null; });
|
||||
}
|
||||
await t.attaching;
|
||||
@@ -76,10 +89,46 @@ export async function detach(tabId) {
|
||||
try { await chrome.debugger.detach({ tabId }); } catch {}
|
||||
}
|
||||
|
||||
export function send(tabId, method, params = {}) {
|
||||
return chrome.debugger.sendCommand({ tabId }, method, params).catch((e) => {
|
||||
// autoAttach asks for the sessions of the frames from other sites that a
|
||||
// page (or such a frame: session sid) holds, as each one appears
|
||||
function autoAttach(tabId, sid) {
|
||||
return send(tabId, "Target.setAutoAttach", {
|
||||
autoAttach: true, waitForDebuggerOnStart: false, flatten: true,
|
||||
filter: [{ type: "iframe", exclude: false }, { exclude: true }],
|
||||
}, sid).catch(() => {});
|
||||
}
|
||||
|
||||
async function child(t, sid) {
|
||||
await Promise.all([
|
||||
send(t.tabId, "Runtime.enable", {}, sid),
|
||||
send(t.tabId, "Network.enable", {}, sid),
|
||||
send(t.tabId, "DOM.enable", {}, sid),
|
||||
send(t.tabId, "Accessibility.enable", {}, sid),
|
||||
]).catch(() => {});
|
||||
await autoAttach(t.tabId, sid);
|
||||
}
|
||||
|
||||
// fault is an error the model is told the kind of, so it knows whether
|
||||
// trying again can help: STALE_REF, AMBIGUOUS, UNACTIONABLE, BAD_ARGS,
|
||||
// WAIT_TIMEOUT, SITE_REFUSED, LOAD_FAILED, PAGE_BLOCKED, USER_STOPPED,
|
||||
// DIALOG_OPEN, OUTCOME_UNKNOWN, SCRIPT_ERROR
|
||||
export function fault(code, message) {
|
||||
const e = new Error(message);
|
||||
e.code = code;
|
||||
return e;
|
||||
}
|
||||
|
||||
// send sends a command to the tab, or to the session of a frame from
|
||||
// another site in it (sid)
|
||||
export function send(tabId, method, params = {}, sid) {
|
||||
const to = sid ? { tabId, sessionId: sid } : { tabId };
|
||||
if (method.startsWith("Input.")) {
|
||||
const t = tabs.get(tabId);
|
||||
if (t) t.sentInput = true;
|
||||
}
|
||||
return chrome.debugger.sendCommand(to, method, params).catch((e) => {
|
||||
const m = String(e && e.message || e);
|
||||
if (/Debugger is not attached|No tab with given id|detached/i.test(m)) {
|
||||
if (!sid && /Debugger is not attached|No tab with given id|detached/i.test(m)) {
|
||||
const t = tabs.get(tabId);
|
||||
if (t) t.attached = false;
|
||||
}
|
||||
@@ -94,21 +143,46 @@ const STREAMING = new Set(["EventSource", "WebSocket", "Ping", "CSPViolationRepo
|
||||
chrome.debugger.onEvent.addListener((src, method, p) => {
|
||||
const t = tabs.get(src.tabId);
|
||||
if (!t) return;
|
||||
const sid = src.sessionId;
|
||||
// a frame's own session: its requests, logs and frames count; its
|
||||
// page events aren't the tab's
|
||||
if (sid && method.startsWith("Page.")) return;
|
||||
const req = (id) => (sid ? sid + ":" + id : id);
|
||||
switch (method) {
|
||||
case "Target.attachedToTarget": {
|
||||
const info = p.targetInfo || {};
|
||||
if (info.type !== "iframe") break;
|
||||
t.children.set(info.targetId, p.sessionId);
|
||||
t.frameOf.set(p.sessionId, { frame: info.targetId, parent: sid });
|
||||
child(t, p.sessionId);
|
||||
break;
|
||||
}
|
||||
case "Target.detachedFromTarget": {
|
||||
const f = t.frameOf.get(p.sessionId);
|
||||
if (f) {
|
||||
if (t.children.get(f.frame) === p.sessionId) t.children.delete(f.frame);
|
||||
t.frameOf.delete(p.sessionId);
|
||||
}
|
||||
for (const k of t.worlds.keys()) if (k.startsWith(p.sessionId + "|")) t.worlds.delete(k);
|
||||
break;
|
||||
}
|
||||
case "Network.requestWillBeSent":
|
||||
if (!STREAMING.has(p.type) && !/^data:|^blob:/.test(p.request.url)) t.inflight.set(p.requestId, Date.now());
|
||||
if (!STREAMING.has(p.type) && !/^data:|^blob:/.test(p.request.url)) t.inflight.set(req(p.requestId), Date.now());
|
||||
t.lastNet = Date.now();
|
||||
t.reqs++;
|
||||
break;
|
||||
case "Network.loadingFinished":
|
||||
case "Network.loadingFailed":
|
||||
t.inflight.delete(p.requestId);
|
||||
t.inflight.delete(req(p.requestId));
|
||||
t.lastNet = Date.now();
|
||||
if (method === "Network.loadingFailed" && !p.canceled && p.type === "Document") log(t, "network", `failed: ${p.errorText}`);
|
||||
break;
|
||||
case "Network.responseReceived":
|
||||
if (p.response.status >= 400) log(t, "network", `${p.response.status} ${p.type} ${p.response.url.slice(0, 300)}`);
|
||||
// what the site answered the page itself with
|
||||
if (!sid && p.type === "Document" && (!t.mainFrame || p.frameId === t.mainFrame)) t.docStatus = p.response.status;
|
||||
// a streamed answer (server-sent events, a long poll) isn't waited for
|
||||
if (/text\/event-stream/i.test(p.response.mimeType || "")) t.inflight.delete(p.requestId);
|
||||
if (/text\/event-stream/i.test(p.response.mimeType || "")) t.inflight.delete(req(p.requestId));
|
||||
break;
|
||||
case "Page.frameStartedLoading":
|
||||
if (!p.frameId || p.frameId === t.mainFrame) t.loading = true;
|
||||
@@ -155,6 +229,9 @@ chrome.debugger.onDetach.addListener((src, reason) => {
|
||||
const t = tabs.get(src.tabId);
|
||||
if (!t) return;
|
||||
t.attached = false;
|
||||
t.children.clear();
|
||||
t.frameOf.clear();
|
||||
t.worlds.clear();
|
||||
// the user pressed Cancel on Chrome's bar: they want it stopped
|
||||
if (reason === "canceled_by_user") t.stoppedByUser = true;
|
||||
});
|
||||
@@ -167,15 +244,63 @@ function log(t, level, text) {
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
export { sleep };
|
||||
|
||||
// A MutationObserver in an isolated world of a frame: the page can't see
|
||||
// it, and it counts what the page changes. Each read answers [how many
|
||||
// changes so far, ms since the last one].
|
||||
const WATCH = `(() => {
|
||||
if (!window.__magpieWatch) {
|
||||
const w = window.__magpieWatch = { n: 0, at: 0 };
|
||||
new MutationObserver((r) => { w.n += r.length; w.at = Date.now(); })
|
||||
.observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
|
||||
}
|
||||
const w = window.__magpieWatch;
|
||||
return [w.n, w.at ? Date.now() - w.at : 1e9];
|
||||
})()`;
|
||||
|
||||
async function mainFrame(t) {
|
||||
if (t.mainFrame) return t.mainFrame;
|
||||
try { t.mainFrame = (await send(t.tabId, "Page.getFrameTree")).frameTree.frame.id; } catch {}
|
||||
return t.mainFrame;
|
||||
}
|
||||
|
||||
// watch reads the changes in a frame (the tab's main frame without one),
|
||||
// or null when it can't be read
|
||||
export async function watch(t, frame, sid) {
|
||||
if (!frame) frame = sid ? t.frameOf.get(sid)?.frame : await mainFrame(t);
|
||||
if (!frame) return null;
|
||||
const k = (sid || "") + "|" + frame;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
let ctx = t.worlds.get(k);
|
||||
if (!ctx) {
|
||||
try {
|
||||
ctx = (await send(t.tabId, "Page.createIsolatedWorld", { frameId: frame, worldName: "magpie-watch" }, sid)).executionContextId;
|
||||
t.worlds.set(k, ctx);
|
||||
} catch { return null; }
|
||||
}
|
||||
try {
|
||||
const r = await send(t.tabId, "Runtime.evaluate", { expression: WATCH, contextId: ctx, returnByValue: true }, sid);
|
||||
if (r.result && Array.isArray(r.result.value)) return r.result.value;
|
||||
} catch {}
|
||||
t.worlds.delete(k); // a new document: a new world
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// settle waits for the page to go quiet after an action: no load under
|
||||
// way and no request open for a short spell, or until the bound.
|
||||
export async function settle(t, bound = 2500, quiet = 400) {
|
||||
// way, no request open and nothing on the page changed for a short spell
|
||||
// (in the frames given, the main one besides), or until the bound. A
|
||||
// frame that can't be watched is waited for by its requests alone.
|
||||
export async function settle(t, bound = 2500, quiet = 400, frames = []) {
|
||||
const end = Date.now() + bound;
|
||||
await sleep(60);
|
||||
const watched = [{}, ...frames.filter((f) => f && (f.frame || f.sid))];
|
||||
while (Date.now() < end) {
|
||||
const now = Date.now();
|
||||
for (const [id, at] of t.inflight) if (now - at > 10000) t.inflight.delete(id); // a long poll
|
||||
if (!t.loading && t.inflight.size === 0 && now - t.lastNet >= quiet) return;
|
||||
if (!t.loading && t.inflight.size === 0 && now - t.lastNet >= quiet) {
|
||||
const reads = await Promise.all(watched.map((f) => watch(t, f.frame, f.sid)));
|
||||
if (reads.every((r) => !r || r[1] >= quiet)) return;
|
||||
}
|
||||
await sleep(80);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Magpie Browser",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "Lets the agents you run through Magpie use this browser: your tabs, signed in to the sites you use.",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwjVk++2N/+l0PX53QSgXvBmDiyIOFXPDRTSo6l7HfM633QbDes2FXjS09l6hY33gsVX9eXE9O+94jQD2SVKSBn8V/EsL3f7mbNfkBqsZ4hYF3ogYxHUjJD6wjKHMFZQi54ArMZBI/psMUBbIjVTeuU9EGwnxoYU5umC8UHvEwkb4ZO0lprP3PGbHDjxrNi5fdFI8azVjyX0zlYlSw2wv0bCAZdkWuRoZWWgKdQwpdtRHrDQMnulWXT5DmNLYDpHgCreDrVaVLXzIAblSLOkZFo/T5xBiicmEbkWPbb8d3iE0OQStm1HYLdp4LLeKnnU6B7Kj/woOFt1uGIwoMqPzswIDAQAB",
|
||||
"minimum_chrome_version": "116",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// each element it can act on given a ref (e3) that stays the element's
|
||||
// from one snapshot to the next, for as long as the page keeps it.
|
||||
|
||||
import { send } from "./cdp.js";
|
||||
import { fault, send } from "./cdp.js";
|
||||
|
||||
const INTERACTIVE = new Set([
|
||||
"button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox",
|
||||
@@ -61,27 +61,48 @@ async function clickables(tabId) {
|
||||
return ids;
|
||||
}
|
||||
|
||||
// frames of the page's own process, read beside the main one; a frame
|
||||
// from another site runs in a process of its own, which this tab's
|
||||
// debugger doesn't reach
|
||||
async function frames(tabId) {
|
||||
const out = new Map(); // owner element's backendNodeId → nodes
|
||||
let tree;
|
||||
try { tree = (await send(tabId, "Page.getFrameTree")).frameTree; } catch { return out; }
|
||||
const kids = [];
|
||||
(function walk(f) { for (const c of f.childFrames || []) { kids.push(c.frame); walk(c); } })(tree);
|
||||
await Promise.all(kids.slice(0, 20).map(async (f) => {
|
||||
try {
|
||||
const owner = await send(tabId, "DOM.getFrameOwner", { frameId: f.id });
|
||||
const { nodes } = await send(tabId, "Accessibility.getFullAXTree", { frameId: f.id });
|
||||
out.set(owner.backendNodeId, nodes);
|
||||
} catch {
|
||||
// the page's frames, read beside the main one: a frame of the page's own
|
||||
// process through the tab, a frame from another site (a process of its
|
||||
// own) through its session. Keyed by the session the owner element is in
|
||||
// and its backendNodeId, since each process numbers its nodes itself.
|
||||
async function frames(t) {
|
||||
const out = new Map(); // "session:backend" → { nodes, sid, frame } | null
|
||||
const done = new Set();
|
||||
let left = 30;
|
||||
const read = async (sid, depth) => {
|
||||
if (depth > 4) return;
|
||||
let tree;
|
||||
try { tree = (await send(t.tabId, "Page.getFrameTree", {}, sid)).frameTree; } catch { return; }
|
||||
const kids = [];
|
||||
(function walk(f) { for (const c of f.childFrames || []) { kids.push(c.frame); walk(c); } })(tree);
|
||||
// a frame from another site is left out of its parent's tree: it is
|
||||
// known by the session attached for it
|
||||
for (const [, v] of t.frameOf) if ((v.parent || undefined) === sid && !kids.some((k) => k.id === v.frame)) kids.push({ id: v.frame });
|
||||
await Promise.all(kids.map(async (f) => {
|
||||
if (done.has(f.id)) return;
|
||||
let owner;
|
||||
// a frame whose element is in another process is read from there
|
||||
try { owner = (await send(t.tabId, "DOM.getFrameOwner", { frameId: f.id }, sid)).backendNodeId; } catch { return; }
|
||||
if (done.has(f.id) || left <= 0) return;
|
||||
done.add(f.id);
|
||||
left--;
|
||||
const key = (sid || "") + ":" + owner;
|
||||
const own = t.children.get(f.id);
|
||||
try {
|
||||
const owner = await send(tabId, "DOM.getFrameOwner", { frameId: f.id });
|
||||
out.set(owner.backendNodeId, null);
|
||||
} catch {}
|
||||
}
|
||||
}));
|
||||
if (own) {
|
||||
const { nodes } = await send(t.tabId, "Accessibility.getFullAXTree", {}, own);
|
||||
out.set(key, { nodes, sid: own, frame: f.id });
|
||||
await read(own, depth + 1);
|
||||
} else {
|
||||
const { nodes } = await send(t.tabId, "Accessibility.getFullAXTree", { frameId: f.id }, sid);
|
||||
out.set(key, { nodes, sid, frame: f.id });
|
||||
}
|
||||
} catch {
|
||||
out.set(key, null);
|
||||
}
|
||||
}));
|
||||
};
|
||||
await read(undefined, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -95,7 +116,7 @@ export async function take(t, opts = {}) {
|
||||
const [{ nodes }, clickable, inner, info] = await Promise.all([
|
||||
send(tabId, "Accessibility.getFullAXTree"),
|
||||
clickables(tabId),
|
||||
frames(tabId),
|
||||
frames(t),
|
||||
send(tabId, "Runtime.evaluate", { expression: "[location.href, document.title]", returnByValue: true }).then((r) => r.result.value).catch(() => ["", ""]),
|
||||
]);
|
||||
const [url, title] = info;
|
||||
@@ -117,6 +138,9 @@ export async function take(t, opts = {}) {
|
||||
return m;
|
||||
};
|
||||
|
||||
// where a ref's element is: the session (a frame from another site)
|
||||
// and the frame its document is
|
||||
let sid, frame;
|
||||
const refFor = (role, name, backend) => {
|
||||
const k = role + "|" + name;
|
||||
const nth = seen.get(k) || 0;
|
||||
@@ -127,7 +151,7 @@ export async function take(t, opts = {}) {
|
||||
ref = "e" + t.next++;
|
||||
t.keys.set(key, ref);
|
||||
}
|
||||
refs.set(ref, { backend, role, name, key });
|
||||
refs.set(ref, { backend, role, name, key, ...(sid ? { sid } : {}), ...(frame ? { frame } : {}) });
|
||||
return ref;
|
||||
};
|
||||
|
||||
@@ -166,18 +190,20 @@ export async function take(t, opts = {}) {
|
||||
return;
|
||||
}
|
||||
const backend = n.backendDOMNodeId;
|
||||
const isClick = backend && clickable.has(backend);
|
||||
// the pointer-cursor scan reads the main document only
|
||||
const isClick = backend && !sid && !frame && clickable.has(backend);
|
||||
const at = (sid || "") + ":" + backend;
|
||||
const props = {};
|
||||
for (const p of n.properties || []) props[p.name] = p.value && p.value.value;
|
||||
const acts = INTERACTIVE.has(role) || isClick || (props.focusable && props.editable);
|
||||
if (TRANSPARENT.has(role) && !name && !acts) {
|
||||
// an iframe's document is read under its element
|
||||
if (backend && inner.has(backend)) return frame(backend, depth);
|
||||
if (backend && inner.has(at)) return inFrame(at, depth);
|
||||
return children();
|
||||
}
|
||||
if (role === "Iframe" || role === "iframe") {
|
||||
lines.push(" ".repeat(depth) + "- iframe" + (name ? " " + q(name) : ""));
|
||||
if (backend && inner.has(backend)) frame(backend, depth + 1);
|
||||
if (backend && inner.has(at)) inFrame(at, depth + 1);
|
||||
return;
|
||||
}
|
||||
let shown = isClick && TRANSPARENT.has(role) ? "clickable" : role;
|
||||
@@ -204,25 +230,35 @@ export async function take(t, opts = {}) {
|
||||
for (const c of n.childIds || []) walk(byId, byId.get(c), opts.interactive ? depth : depth + 1, under);
|
||||
};
|
||||
|
||||
const frame = (backend, depth) => {
|
||||
const list = inner.get(backend);
|
||||
if (!list) {
|
||||
lines.push(" ".repeat(depth) + "- (a frame from another site: not readable here; use a screenshot, or open its address in a tab)");
|
||||
const inFrame = (at, depth) => {
|
||||
const f = inner.get(at);
|
||||
if (!f) {
|
||||
lines.push(" ".repeat(depth) + "- (a frame this browser doesn't let Magpie Browser read: use a screenshot, or open its address in a tab)");
|
||||
return;
|
||||
}
|
||||
const byId = index(list);
|
||||
walk(byId, list.find((n) => !n.parentId) || list[0], depth, "");
|
||||
const was = [sid, frame];
|
||||
[sid, frame] = [f.sid, f.frame];
|
||||
try {
|
||||
const byId = index(f.nodes);
|
||||
walk(byId, f.nodes.find((n) => !n.parentId) || f.nodes[0], depth, "");
|
||||
} finally {
|
||||
[sid, frame] = was;
|
||||
}
|
||||
};
|
||||
|
||||
const byId = index(nodes);
|
||||
let list = nodes;
|
||||
let root = nodes.find((n) => !n.parentId) || nodes[0];
|
||||
if (opts.ref) {
|
||||
const r = t.refs.get(opts.ref);
|
||||
const n = r && nodes.find((x) => x.backendDOMNodeId === r.backend);
|
||||
if (!n) throw new Error(`ref ${opts.ref} isn't on the page now: take a snapshot without ref`);
|
||||
// the ref's own document: the main one, or the frame it is in
|
||||
const f = r && (r.sid || r.frame) ? [...inner.values()].find((x) => x && x.sid === r.sid && x.frame === r.frame) : null;
|
||||
if (f) { list = f.nodes; [sid, frame] = [f.sid, f.frame]; }
|
||||
const n = r && list.find((x) => x.backendDOMNodeId === r.backend);
|
||||
if (!n) throw fault("STALE_REF", `ref ${opts.ref} isn't on the page now: take a snapshot without ref`);
|
||||
root = n;
|
||||
}
|
||||
walk(byId, root, 0, "");
|
||||
walk(index(list), root, 0, "");
|
||||
[sid, frame] = [undefined, undefined];
|
||||
// the old refs stay good for elements still on the page that this
|
||||
// snapshot didn't show (a scoped one)
|
||||
if (opts.ref) for (const [k, v] of refs) t.refs.set(k, v);
|
||||
@@ -244,13 +280,13 @@ export async function take(t, opts = {}) {
|
||||
// that says what the page has.
|
||||
export async function find(t, ref) {
|
||||
const m = /^(?:ref=)?(e\d+)$/i.exec(String(ref || "").trim());
|
||||
if (!m) throw new Error(`"${ref}" isn't a ref: refs look like e12, from the latest snapshot`);
|
||||
if (!m) throw fault("BAD_ARGS", `"${ref}" isn't a ref: refs look like e12, from the latest snapshot`);
|
||||
ref = m[1].toLowerCase();
|
||||
const r = t.refs.get(ref);
|
||||
if (!r) throw new Error(`ref ${ref} isn't in the latest snapshot of this tab: take a snapshot and use a ref from it`);
|
||||
if (!r) throw fault("STALE_REF", `ref ${ref} isn't in the latest snapshot of this tab: take a snapshot and use a ref from it`);
|
||||
try {
|
||||
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: r.backend, objectGroup: "magpie-act" });
|
||||
const c = await send(t.tabId, "Runtime.callFunctionOn", { objectId: o.object.objectId, functionDeclaration: "function(){return this.isConnected}", returnByValue: true });
|
||||
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: r.backend, objectGroup: "magpie-act" }, r.sid);
|
||||
const c = await send(t.tabId, "Runtime.callFunctionOn", { objectId: o.object.objectId, functionDeclaration: "function(){return this.isConnected}", returnByValue: true }, r.sid);
|
||||
if (c.result.value) return { ...r, ref, objectId: o.object.objectId };
|
||||
} catch {}
|
||||
// the page drew it again: the same role and name, if only one has it
|
||||
@@ -258,9 +294,9 @@ export async function find(t, ref) {
|
||||
const same = [...t.refs].filter(([, v]) => v.role === r.role && v.name === r.name);
|
||||
if (same.length === 1) {
|
||||
const [nref, v] = same[0];
|
||||
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: v.backend, objectGroup: "magpie-act" });
|
||||
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: v.backend, objectGroup: "magpie-act" }, v.sid);
|
||||
return { ...v, ref: nref, objectId: o.object.objectId };
|
||||
}
|
||||
if (same.length > 1) throw new Error(`${ref} (${r.role} "${r.name}") was redrawn and ${same.length} elements now match it: take a snapshot and pick one`);
|
||||
throw new Error(`${ref} (${r.role} "${r.name}") is no longer on the page: take a snapshot`);
|
||||
if (same.length > 1) throw fault("AMBIGUOUS", `${ref} (${r.role} "${r.name}") was redrawn and ${same.length} elements now match it: take a snapshot and pick one`);
|
||||
throw fault("STALE_REF", `${ref} (${r.role} "${r.name}") is no longer on the page: take a snapshot`);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -43,6 +45,97 @@ const browserFixture = `<!doctype html>
|
||||
document.addEventListener('mouseup', (e) => { if (down === 'src' && e.target.id === 'dst') out.textContent = 'dropped'; down = null; });
|
||||
</script>`
|
||||
|
||||
// A page with a frame from another site (SRC: 127.0.0.1 and localhost are
|
||||
// two sites, so Chrome runs it in a process of its own) below the fold,
|
||||
// and buttons that change nothing, and change the page twice a moment
|
||||
// apart with no request.
|
||||
const framesFixture = `<!doctype html>
|
||||
<title>Frames</title>
|
||||
<h1>Frames fixture</h1>
|
||||
<button>Does nothing</button>
|
||||
<button onclick="out.textContent = 'working'; setTimeout(() => out.textContent = 'done', 250)">Works a while</button>
|
||||
<div id="out" role="status"></div>
|
||||
<div style="height: 1500px"></div>
|
||||
<iframe title="Checkout" src="SRC" style="width: 420px; height: 160px; margin-left: 30px"></iframe>
|
||||
<script>const out = document.getElementById('out');</script>`
|
||||
|
||||
// what the frame from the other site shows
|
||||
const innerFixture = `<!doctype html>
|
||||
<title>Checkout</title>
|
||||
<input aria-label="Card" id="card">
|
||||
<button onclick="said.textContent = 'paid ' + card.value">Pay</button>
|
||||
<div id="said" role="status"></div>
|
||||
<script>const said = document.getElementById('said'), card = document.getElementById('card');</script>`
|
||||
|
||||
// Frames from another site and the kinds of failure, in a real Chromium:
|
||||
// the frame's elements are in the snapshot with refs, typed into, clicked
|
||||
// and measured where they are on the page, below the fold; an action
|
||||
// answers once the page has stopped changing, not when its requests end;
|
||||
// a click that changes nothing says NO_EFFECT; and each failure starts
|
||||
// with its kind.
|
||||
func TestBrowserFramesAndFailuresInARealBrowser(t *testing.T) {
|
||||
srv, site := realBrowser(t)
|
||||
call, ok := browserCaller(t, srv, "e2e-frames")
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
io.WriteString(w, innerFixture)
|
||||
}))
|
||||
t.Cleanup(other.Close)
|
||||
inner := strings.Replace(other.URL, "127.0.0.1", "localhost", 1) + "/inner"
|
||||
ref := func(page, role, name string) string {
|
||||
t.Helper()
|
||||
m := regexp.MustCompile(`- ` + role + ` "` + regexp.QuoteMeta(name) + `"(?: \[[a-z=, ]+\])? \[ref=(e\d+)\]`).FindStringSubmatch(page)
|
||||
if m == nil {
|
||||
t.Fatalf("no %s %q with a ref in:\n%s", role, name, page)
|
||||
}
|
||||
return m[1]
|
||||
}
|
||||
failed := func(tool string, args map[string]any, code string) string {
|
||||
t.Helper()
|
||||
m := call(tool, args)
|
||||
out := m.Result.Content[0].Text
|
||||
if !m.Result.IsError || !strings.HasPrefix(out, code+": ") {
|
||||
t.Fatalf("%s %v answered (error %v):\n%s\nwant it to fail %s", tool, args, m.Result.IsError, out, code)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
page := ok("browser_navigate", map[string]any{"url": site.URL + "/frames?src=" + url.QueryEscape(inner)}, "Frames fixture")
|
||||
// the frame loads after the page: read until it is there
|
||||
for end := time.Now().Add(10 * time.Second); !strings.Contains(page, `button "Pay"`) && time.Now().Before(end); time.Sleep(200 * time.Millisecond) {
|
||||
page = ok("browser_snapshot", nil)
|
||||
}
|
||||
if strings.Contains(page, "doesn't let Magpie Browser read") {
|
||||
t.Fatalf("the frame from the other site isn't read:\n%s", page)
|
||||
}
|
||||
ok("browser_type", map[string]any{"ref": ref(page, "textbox", "Card"), "text": "4242"}, "Typed into")
|
||||
pay := ref(page, "button", "Pay")
|
||||
ok("browser_click", map[string]any{"ref": pay}, "Clicked", "paid 4242")
|
||||
ok("browser_evaluate", map[string]any{"ref": pay, "script": "(el) => [el.ownerDocument.getElementById('said').textContent, location.host]"}, "paid 4242", strings.TrimPrefix(strings.TrimSuffix(inner, "/inner"), "http://"))
|
||||
png := call("browser_screenshot", map[string]any{"ref": pay, "png": true})
|
||||
if b, _ := base64.StdEncoding.DecodeString(png.Result.Content[0].Data); png.Result.IsError || !bytes.HasPrefix(b, []byte("\x89PNG")) {
|
||||
t.Fatalf("the frame's button has no screenshot: %+v", png.Result.Content[len(png.Result.Content)-1])
|
||||
}
|
||||
ok("browser_snapshot", map[string]any{"ref": pay}, `button "Pay"`)
|
||||
|
||||
// settled when the page stops changing: the second change comes
|
||||
// 250ms after the first, with no request between
|
||||
ok("browser_scroll", map[string]any{"direction": "up", "amount": 5000})
|
||||
page = ok("browser_snapshot", nil)
|
||||
if out := ok("browser_click", map[string]any{"ref": ref(page, "button", "Works a while")}, "done"); strings.Contains(out, "NO_EFFECT") {
|
||||
t.Fatalf("a click that changed the page says NO_EFFECT:\n%s", out)
|
||||
}
|
||||
ok("browser_click", map[string]any{"ref": ref(page, "button", "Does nothing")}, "NO_EFFECT")
|
||||
|
||||
failed("browser_click", map[string]any{"ref": "nope"}, "BAD_ARGS")
|
||||
failed("browser_click", map[string]any{"ref": "e9999"}, "STALE_REF")
|
||||
failed("browser_click", nil, "BAD_ARGS")
|
||||
failed("browser_wait", map[string]any{"text": "never shown", "timeout": 1}, "WAIT_TIMEOUT")
|
||||
failed("browser_evaluate", map[string]any{"script": "(() => { throw new Error('nope') })()"}, "SCRIPT_ERROR")
|
||||
failed("browser_navigate", map[string]any{"url": site.URL + "/refused"}, "SITE_REFUSED")
|
||||
failed("browser_navigate", map[string]any{"url": "http://127.0.0.1:1/"}, "LOAD_FAILED")
|
||||
}
|
||||
|
||||
// Magpie Browser in a real Chromium: the extension magpie writes, loaded
|
||||
// as a user loads it, connects to the gateway, and every tool an agent
|
||||
// calls is carried out in a real tab. Set MAGPIE_BROWSER_CHROME to a
|
||||
@@ -157,9 +250,17 @@ func realBrowser(t *testing.T) (srv, site *httptest.Server) {
|
||||
t.Cleanup(srv.Close)
|
||||
site = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if r.URL.Path == "/two" {
|
||||
switch r.URL.Path {
|
||||
case "/two":
|
||||
io.WriteString(w, "<!doctype html><title>Two</title><h1>Page two</h1>")
|
||||
return
|
||||
case "/frames":
|
||||
io.WriteString(w, strings.Replace(framesFixture, "SRC", html.EscapeString(r.URL.Query().Get("src")), 1))
|
||||
return
|
||||
case "/refused":
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
io.WriteString(w, "<!doctype html><title>Denied</title><h1>Access denied</h1>")
|
||||
return
|
||||
}
|
||||
io.WriteString(w, browserFixture)
|
||||
}))
|
||||
|
||||
@@ -9,6 +9,8 @@ How to work:
|
||||
- Start with browser_tabs or browser_snapshot. Calls go to the tab the user is looking at until you open or select another (to a new tab of your own when another agent works in that one); tabs you open go in your own tab group ("Magpie", or "Magpie 2" and on beside other agents). Leave the tabs browser_tabs marks ~ to the agents working in them.
|
||||
- With two browsers connected (Chrome and Edge, or two profiles), calls go to the last to connect: browser_tabs with action browsers lists them, and action use picks one.
|
||||
- browser_snapshot shows the page as an accessibility tree. Elements you can act on carry a ref (e12); pass it to browser_click, browser_type and the rest. Refs stay the element's while the page keeps it. Every action answers with the page after it, so you rarely need another snapshot.
|
||||
- Frames from other sites (a payment form, a sign-in box, an embedded editor) are read and acted on like the rest of the page.
|
||||
- A failure starts with its kind and says whether trying again can help: STALE_REF and AMBIGUOUS (take a snapshot, use a ref from it), UNACTIONABLE (the page must change first), BAD_ARGS, WAIT_TIMEOUT, SITE_REFUSED (the site turned the browser away: tell the user), LOAD_FAILED, PAGE_BLOCKED, USER_STOPPED, DIALOG_OPEN, SCRIPT_ERROR, and OUTCOME_UNKNOWN (the page changed mid-action: snapshot before doing it again). A click answered NO_EFFECT changed nothing on the page: check before clicking again.
|
||||
- Prefer refs to browser_evaluate. Use browser_screenshot when the layout or an image matters.
|
||||
- This is the user's browser: don't close tabs you didn't open, don't change their settings, and ask before sending, buying, posting or deleting anything on their behalf. When a site wants a sign-in, a captcha or a 2FA code, ask the user to do it in the tab, then go on.`
|
||||
|
||||
|
||||
Reference in New Issue
Block a user