browser: Magpie Browser acts like a person and stays out of the user's tabs

The owner, 11-05: Magpie Browser interrupts the user's own browsing, and
driving Discord with it gets the account flagged by Discord's bot check,
which never happened under Claude's Chrome extension.

What a site could see, and what changed (extension 0.1.6):
- CDP's Runtime domain was on in every tab, which bot checks look for.
  It is now off until browser_console is asked for (on localhost, 127.x,
  [::1], *.localhost and *.test it is on from the start, as before).
  The first console call says it reads the console from then on.
- Every read and helper (the clickable scan's getComputedStyle and
  querySelectorAll on each element, focus, readyState, innerText,
  scroll position) ran in the page's own world, where a page's patched
  functions see each call. They now run in an isolated world of the
  extension's (Page.createIsolatedWorld, DOM.resolveNode in it).
  browser_evaluate stays in the page's world, since the agent's script
  is for the page's JavaScript.
- A click jumped to an element's exact middle. The mouse now moves along
  a curved, eased path to a spot drawn around the middle, then presses
  and lets go at uneven timings. Hover and drag go the same way.
- Text went in with Input.insertText, with no key events. It is now
  typed a key at a time with US key codes, Shift held for capitals and
  symbols, at a typist's uneven rhythm (35s at most for a whole text).
  Chinese, Japanese and Korean come through an IME composition, emoji
  through insertText, and a newline as Shift+Enter so a chat box doesn't
  send early. A field's old text is cleared with Backspace only when it
  has some, and submit waits a moment before Enter.
- A scroll was one wheel event. It is several notches now.
- Actions follow each other at a person's pace (350 to 1600ms apart),
  and the debugger stays attached for 5 minutes idle, not 2, so Chrome's
  bar doesn't come and go between calls.

The user's tabs:
- A call naming one of the user's own tabs (one outside every Magpie
  group) now opens that page in a background tab of the agent's own, in
  its group, and the agent is told so; naming it again goes on in that
  copy. This is how Claude's extension keeps to its own group.
- tab_close refuses a tab of the user's.
- A tab an action opens always goes in the agent's group, and a page
  that opens a window of its own gives focus back to the window the user
  was in.
- The tool's instructions said calls go to the tab the user is looking
  at. They now say the agent works in tabs of its own, that naming the
  user's tab copies it, that steps take a person's time, and how the
  console starts.

Run at this head (rebased on fe61503e6), on mote with Chromium 1248
(Chrome for Testing, --headless=new):
- gofmt -l clean; go vet for darwin, linux and windows on
  internal/gateway and internal/browserext
- go test ./internal/browserext: ok
- go test -run TestBrowser ./internal/gateway, with
  MAGPIE_BROWSER_CHROME: 21 of 21 pass, the six real-browser tests among
  them
- New TestBrowserActsLikeAPerson, on shop.example (mapped to the test's
  site, so not a developer's host). It checks that the page never sees
  its getComputedStyle, querySelectorAll, elementFromPoint or focus
  called. It checks that a click is trusted, off the middle, after 4 or
  more mousemoves. It checks a keydown per character at uneven gaps,
  Shift for capitals, and Chinese through compositionend, both in a
  textarea and in a contenteditable chat box. In that chat box a newline
  doesn't send and submit does. It also checks that a 600px scroll is 3
  or more wheel events, that the console is off until asked for, and
  that a named user tab is copied into the group and left as it was.

Broken by hand, each red in that test:
- Runtime always on: console says nothing about starting
- a click at the exact middle with one mousemove: "landed on the middle
  (-0.5, -0.375)" and "moved 1 times"
- insertText for typing: 0 keydowns, even gaps, no Shift, no composition
- the clickable scan in the page's world: the page saw 27 calls
- naming the user's tab acting in it: "doesn't say is the user's own tab"

Not tried:
- The real Discord or a real account. Whether Discord's check now passes
  is not something a test here shows. The reasons it is likely to are the
  differences above, and that they match what Claude's extension does
  (Runtime only when asked, reads outside the page's world, a move before
  each click).
- Headful (MAGPIE_BROWSER_HEADFUL=1) on mote. TestBrowserLeavesTheUsersTabAlone
  fails at random steps there on origin/main fe61503e6 too, even right
  after a plain navigate, because the window counts as hidden on mote's
  idle display (#5513).
- Edge, Windows and Linux Chrome.

The user reloads Magpie Browser in chrome://extensions to get 0.1.6.
This commit is contained in:
yetone
2026-11-06 18:41:38 +08:00
parent 9a0aab32c1
commit 8f69ca29c4
9 changed files with 649 additions and 104 deletions
+110 -50
View File
@@ -3,9 +3,10 @@
// out in this browser's own tabs, signed in to whatever the user is.
import { GATEWAY } from "./config.js";
import { attach, fault, forget, send, settle, sleep, state, waitLoad, watch } from "./cdp.js";
import { attach, fault, forget, read, send, settle, sleep, state, waitLoad, watch, watchConsole } from "./cdp.js";
import { find, take } from "./snapshot.js";
import { press as keyPress, typeSlowly } from "./keys.js";
import { press as keyPress } from "./keys.js";
import * as human from "./human.js";
const VERSION = chrome.runtime.getManifest().version;
const ACT_SNAPSHOT_MAX = 30000;
@@ -141,15 +142,50 @@ function tabArg(v) {
return Number(m[1]);
}
// ours is whether a tab is an agent's: one a session works in, or one in
// a Magpie tab group
async function ours(tab) {
for (const v of sessions.values()) if (v === tab.id) return true;
if (tab.groupId === undefined || tab.groupId < 0) return false;
const g = await chrome.tabGroups.get(tab.groupId).catch(() => null);
return !!g && /^Magpie( \d+)?$/.test(g.title || "");
}
// what a call is told before its answer: session → text
const said = new Map();
// the tab of its own a session was given for a user's tab it named:
// "session|tab" → tab
const copies = new Map();
// the tab a call works in: the one it names, else the session's, else a
// new one of the session's own. The user's tabs are theirs: an agent never
// starts in the one they are looking at (it navigated it away under them),
// and works in one of theirs only when it names it.
// acts in one of them, the one they are looking at or one behind it. One
// it names has its page opened in a tab of the agent's own, behind, in its
// group, signed in the same, and the agent goes on there.
async function tabFor(session, args) {
await loadSessions();
const named = tabArg(args.tab);
if (named !== null) {
await chrome.tabs.get(named).catch(() => { throw fault("BAD_ARGS", `there is no tab t${named} now: call browser_tabs for the open ones`); });
const tab = await chrome.tabs.get(named).catch(() => { throw fault("BAD_ARGS", `there is no tab t${named} now: call browser_tabs for the open ones`); });
if (!(await ours(tab))) {
const key = session + "|" + named;
const was = copies.get(key);
if (was !== undefined && (await chrome.tabs.get(was).then(() => true, () => false))) {
sessions.set(session, was);
saveSessions();
return was;
}
const url = tab.url || tab.pendingUrl || "about:blank";
const copy = await open(session, url, false);
copies.set(key, copy.id);
// loaded before the call reads it
for (let end = Date.now() + 20000; Date.now() < end; await sleep(150)) {
const c = await chrome.tabs.get(copy.id).catch(() => null);
if (!c || c.status === "complete") break;
}
said.set(session, `t${named} is the user's own tab, which agents leave to them: its page (${url.slice(0, 200)}) is opened in t${copy.id}, a tab of your own behind theirs, and calls go there.`);
return copy.id;
}
sessions.set(session, named);
saveSessions();
return named;
@@ -243,7 +279,17 @@ 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 || {});
const session = m.session || "default";
said.delete(session);
const r = await tool(session, m.args || {});
const note = said.get(session);
if (note) {
said.delete(session);
const first = r.content && r.content.find((c) => c.type === "text");
if (first) first.text = note + "\n\n" + first.text;
else (r.content = r.content || []).unshift(text(note));
}
return r;
} catch (e) {
return failure(e);
}
@@ -293,7 +339,7 @@ const PRESSES = new Set(["button", "link", "clickable", "menuitem", "tab", "tree
// 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 scroll = await read(t, "scrollX + ',' + scrollY").catch(() => 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)) };
@@ -312,6 +358,10 @@ async function act(t, what, fn, el = null, press = false) {
const shown = mine && all.find((x) => x.active && x.windowId === mine.windowId);
const behind = shown && shown.id !== t.tabId ? shown : null;
const was = press ? await look(t, el) : null;
// the window the user works in: a page that opens a window of its own
// (window.open with a size) doesn't take it from them
const focused = await chrome.windows.getLastFocused({ windowTypes: ["normal"] }).catch(() => null);
await human.pace(t);
t.sentInput = false;
let opened = null;
// a tab the link opens comes up in front of the user's: their tab is
@@ -320,6 +370,7 @@ async function act(t, what, fn, el = null, press = false) {
if (before.has(tab.id) || !(tab.openerTabId === t.tabId || (behind && tab.openerTabId === behind.id) || !opened)) return;
opened = tab;
if (behind && (tab.openerTabId === t.tabId || tab.openerTabId === behind.id)) chrome.tabs.update(behind.id, { active: true }).catch(() => {});
if (focused && tab.windowId !== focused.id && focused.focused) chrome.windows.update(focused.id, { focused: true }).catch(() => {});
};
chrome.tabs.onCreated.addListener(onCreated);
let said;
@@ -336,6 +387,7 @@ async function act(t, what, fn, el = null, press = false) {
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 {
human.done(t);
setTimeout(() => chrome.tabs.onCreated.removeListener(onCreated), 1500);
}
if (!t.dialog) await settle(t, 2500, 400, el ? [el] : []);
@@ -347,10 +399,8 @@ async function act(t, what, fn, el = null, press = false) {
if (opened && (opened.openerTabId === t.tabId || (behind && opened.openerTabId === behind.id))) {
// a link that opens a new tab: the agent goes on in it, in its group,
// and the user keeps the tab they had in front
if (behind) {
await chrome.tabs.update(behind.id, { active: true }).catch(() => {});
if (t.by) await group(t.by, opened.id, opened.windowId).catch(() => {});
}
if (behind) await chrome.tabs.update(behind.id, { active: true }).catch(() => {});
if (t.by) await group(t.by, opened.id, opened.windowId).catch(() => {});
if (t.by) { sessions.set(t.by, opened.id); saveSessions(); }
const nt = state(opened.id);
await attach(opened.id);
@@ -386,7 +436,10 @@ async function point(t, el) {
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);
const tries = [[0.5, 0.5], [0.3, 0.5], [0.7, 0.5], [0.5, 0.3], [0.5, 0.7], [0.2, 0.2], [0.8, 0.8]];
// somewhere near the middle, as a person aims, then other spots when
// something covers it
const a = human.aim(x0, y0, x1, y1);
const tries = [[(a.x - x0) / (x1 - x0 || 1), (a.y - y0) / (y1 - y0 || 1)], [0.5, 0.5], [0.3, 0.5], [0.7, 0.5], [0.5, 0.3], [0.5, 0.7], [0.2, 0.2], [0.8, 0.8]];
let cover = "";
for (const [fx, fy] of tries) {
const x = x0 + (x1 - x0) * fx, y = y0 + (y1 - y0) * fy;
@@ -448,16 +501,8 @@ const BUTTONS = { left: "left", right: "right", middle: "middle" };
const MODS = { Alt: 1, Control: 2, Ctrl: 2, Meta: 4, Command: 4, Cmd: 4, Shift: 8 };
async function mouse(t, x, y, opts = {}) {
const button = BUTTONS[opts.button] || "left";
const modifiers = (opts.modifiers || []).reduce((a, m) => a | (MODS[m] || 0), 0);
const count = opts.double ? 2 : 1;
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x, y, modifiers });
await sleep(30 + Math.random() * 40);
for (let i = 1; i <= count; i++) {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, clickCount: i, modifiers, buttons: 1 });
await sleep(40 + Math.random() * 50);
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button, clickCount: i, modifiers });
}
await human.click(t, x, y, { button: BUTTONS[opts.button] || "left", double: !!opts.double, modifiers });
}
// opensATab is whether el is, or is in, a link that opens in a new tab
@@ -511,6 +556,8 @@ const TOOLS = {
if (action === "close") {
const id = args.tab ? tabArg(args.tab) : sessions.get(session);
if (id === undefined || id === null) throw fault("BAD_ARGS", "tab is needed");
const tab = await chrome.tabs.get(id).catch(() => { throw fault("BAD_ARGS", `there is no tab t${id} now`); });
if (!(await ours(tab))) throw fault("UNACTIONABLE", `t${id} is the user's own tab: agents close only their own (in a Magpie group); ask the user to close it`);
await chrome.tabs.remove(id);
return { content: [text(`Closed t${id}.`)] };
}
@@ -585,7 +632,7 @@ const TOOLS = {
const el = await find(t, args.ref);
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 });
await human.move(t, p.x, p.y);
}, el);
},
@@ -595,30 +642,42 @@ const TOOLS = {
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 () => {
// into the field as a person goes: a click on it, its old text
// selected and taken out with Backspace, then the keys
const p = await point(t, el).catch(() => null);
if (p) await mouse(t, p.x, p.y);
const ok = await call(t, el, `function(clear) {
const kind = await call(t, el, `function(clear) {
const e = this;
const edit = (x) => x && (x.isContentEditable || /^(INPUT|TEXTAREA)$/.test(x.tagName));
let to = edit(e) ? e : (e.querySelector && e.querySelector('input,textarea,[contenteditable=""],[contenteditable="true"]')) || e;
if (document.activeElement !== to && !(to.contains && to.contains(document.activeElement))) to.focus();
const a = document.activeElement;
if (!edit(a) && !(a && a.isContentEditable)) return false;
if (!edit(a) && !(a && a.isContentEditable)) return "";
let empty;
if (/^(INPUT|TEXTAREA)$/.test(a.tagName)) {
empty = !a.value;
if (clear) a.select(); else { try { const n = a.value.length; a.setSelectionRange(n, n); } catch {} }
} else {
empty = !a.textContent.replace(/[\u200b\ufeff\s]/g, "");
const s = getSelection(), r = document.createRange();
r.selectNodeContents(a);
if (!clear) r.collapse(false);
s.removeAllRanges(); s.addRange(r);
}
return true;
return (a.tagName === "INPUT" ? "line" : "lines") + (empty ? " empty" : "");
}`, [args.clear !== false]);
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");
if (!kind) throw fault("UNACTIONABLE", `${el.ref} (${el.role} "${el.name}") doesn't take text: click the field itself`);
if (args.clear !== false && !kind.endsWith("empty")) {
await sleep(120 + Math.random() * 200);
await keyPress(t, "Backspace");
await sleep(150 + Math.random() * 250);
}
if (args.text) await human.type(t, args.text, { newline: kind.startsWith("line ") || kind === "line" ? "" : "Shift+Enter", press: (k) => keyPress(t, k) });
if (args.submit) {
// a look over what was typed before sending it
await sleep(250 + Math.random() * 450);
await keyPress(t, "Enter");
}
}, el);
},
@@ -628,7 +687,7 @@ const TOOLS = {
let el = null;
if (args.ref) el = await find(t, args.ref);
return act(t, `Pressed ${args.key}.`, async () => {
if (el) await call(t, el, "function(){ this.focus() }");
if (el) await call(t, el, "function(){ if (document.activeElement !== this && !this.contains(document.activeElement)) this.focus() }");
await keyPress(t, args.key);
}, el);
},
@@ -682,10 +741,10 @@ const TOOLS = {
const dx = dir === "left" ? -amount : dir === "right" ? amount : 0;
const dy = dir === "up" ? -amount : dir === "down" ? amount : 0;
return act(t, `Scrolled ${dir} ${amount}px.`, async () => {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: dx, deltaY: dy });
// a little off the middle, where a hand rests
await human.wheel(t, x + (Math.random() - 0.5) * 60, y + (Math.random() - 0.5) * 60, dx, dy);
await sleep(250);
const r = await send(t.tabId, "Runtime.evaluate", { expression: "[scrollX, scrollY, document.documentElement.scrollHeight, innerHeight]", returnByValue: true });
const [sx, sy, h, ih] = r.result.value;
const [sx, sy, h, ih] = await read(t, "[scrollX, scrollY, document.documentElement.scrollHeight, innerHeight]");
return `Scrolled ${dir} ${amount}px; the page is at ${Math.round(sy)} of ${Math.max(0, h - ih)}px down${sx ? `, ${Math.round(sx)}px across` : ""}.`;
});
},
@@ -698,16 +757,7 @@ const TOOLS = {
return act(t, `Dragged ${a.ref} onto ${b.ref}.`, async () => {
const p = await point(t, a);
const q = await point(t, b);
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y });
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x: p.x, y: p.y, button: "left", clickCount: 1, buttons: 1 });
try {
for (let i = 1; i <= 12; i++) {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x + ((q.x - p.x) * i) / 12, y: p.y + ((q.y - p.y) * i) / 12, button: "left", buttons: 1 });
await sleep(25);
}
} finally {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x: q.x, y: q.y, button: "left", clickCount: 1 });
}
await human.drag(t, p, q);
}, a);
},
@@ -755,9 +805,9 @@ const TOOLS = {
const end = Date.now() + bound;
for (;;) {
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 v = await read(t, "[location.href, document.body ? document.body.innerText : '']").catch(() => null);
if (v) {
const [href, body] = v;
const ok = (!args.text || body.includes(args.text)) && (!args.textGone || !body.includes(args.textGone)) && (!args.url || href.includes(args.url));
if (ok) break;
}
@@ -810,8 +860,11 @@ const TOOLS = {
let r;
if (args.ref) {
const el = await find(t, args.ref);
// the script is the agent's, for the page's own JavaScript: the
// element as the page's world has it
const o = await send(t.tabId, "DOM.resolveNode", { backendNodeId: el.backend, objectGroup: "magpie-eval" }, el.sid);
r = await send(t.tabId, "Runtime.callFunctionOn", {
objectId: el.objectId, returnByValue: true, awaitPromise: true,
objectId: o.object.objectId, returnByValue: true, awaitPromise: true,
functionDeclaration: fn ? `function() { return (${src})(this); }` : `function() { return (${src}); }`,
}, el.sid);
} else {
@@ -830,14 +883,21 @@ const TOOLS = {
const t = await ready(session, args);
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();
let s = String((await read(t, "document.body ? document.body.innerText : ''")) || "").replace(/\n{3,}/g, "\n\n").trim();
if (s.length > max) s = s.slice(0, max) + `\n… (cut at ${max} characters of ${s.length})`;
return { content: [text(`${await head(t)}\n\n${s || "(the page has no text)"}`)] };
},
async browser_console(session, args) {
const t = await ready(session, args);
// the console is read only once asked for (on a developer's own host
// from the start): a site can tell when it is
if (await watchConsole(t)) {
await sleep(300);
if (!t.logs.some((l) => l.level !== "network")) {
return { content: [text("Magpie Browser reads this tab's console from now on (it is off until asked for, since a site can tell it is read). What the page logs next shows here: do what logs it, then call console again." + (t.logs.length ? "\n\n" + t.logs.map((l) => `[${new Date(l.at).toISOString().slice(11, 19)}] ${l.level}: ${l.text}`).join("\n") : ""))] };
}
}
const levels = args.level === "errors" ? ["error", "assert"] : args.level === "network" ? ["network"] : null;
let logs = t.logs.filter((l) => !levels || levels.includes(l.level));
const n = Math.min(Number(args.limit) || 50, 300);
+100 -25
View File
@@ -1,9 +1,16 @@
// The DevTools protocol over chrome.debugger, one attachment per tab. A
// tab stays attached while an agent works in it and is let go after a
// quiet spell, so Chrome's "is debugging this browser" bar is up only
// while it is used.
// while it is used, and doesn't come and go between an agent's calls.
//
// The page never learns it is driven. Runtime is left off (a page can
// tell it is on: Chrome then reads what the page logs, and a logged
// object's getters run), save on a developer's own host or once an agent
// asks for the console. Everything magpie reads or runs in a page runs
// in an isolated world of its own, which the page's scripts can't see or
// patch: nothing of magpie's shows in the page's own JavaScript.
const IDLE_MS = 2 * 60 * 1000;
const IDLE_MS = 5 * 60 * 1000;
const LOG_KEPT = 300;
// tabId → what is known of the page while attached
@@ -22,8 +29,12 @@ export function state(tabId) {
// 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
worlds: new Map(), // "session|frame" → magpie's isolated world there
sentInput: false,
console: false, // Runtime is on: the page's logs are read
mouse: null, // where the mouse last was, {x, y}
lastInput: 0, // when the last action's input ended
lastWheel: 0,
};
tabs.set(tabId, t);
}
@@ -54,9 +65,10 @@ export async function attach(tabId) {
t.children.clear();
t.frameOf.clear();
t.worlds.clear();
if (!t.console) t.console = await devHost(tabId);
await Promise.all([
send(tabId, "Page.enable"),
send(tabId, "Runtime.enable"),
...(t.console ? [send(tabId, "Runtime.enable")] : []),
send(tabId, "Network.enable"),
send(tabId, "DOM.enable"),
send(tabId, "Accessibility.enable"),
@@ -72,6 +84,25 @@ export async function attach(tabId) {
return t;
}
// devHost is whether a tab shows a developer's own page (localhost, a
// .test or .localhost name), whose logs are read from the start: no site
// there watches for a debugger
const DEV = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\]|.+\.localhost|.+\.test)$/i;
async function devHost(tabId) {
const tab = await chrome.tabs.get(tabId).catch(() => null);
try { return DEV.test(new URL(tab && (tab.pendingUrl || tab.url)).hostname); } catch { return false; }
}
// watchConsole turns Runtime on in a tab and its frames, so what the page
// logs from now on is read; asked for by browser_console
export async function watchConsole(t) {
if (t.console) return false;
t.console = true;
await send(t.tabId, "Runtime.enable").catch(() => {});
for (const sid of t.frameOf.keys()) send(t.tabId, "Runtime.enable", {}, sid).catch(() => {});
return true;
}
function why(m) {
if (/chrome:\/\/|chrome-extension:\/\/|Cannot access|Cannot attach/i.test(m)) {
return "Chrome doesn't let an extension control this page (a chrome:// page, the Web Store or another extension's page): open a web page in the tab first";
@@ -100,7 +131,7 @@ function autoAttach(tabId, sid) {
async function child(t, sid) {
await Promise.all([
send(t.tabId, "Runtime.enable", {}, sid),
...(t.console ? [send(t.tabId, "Runtime.enable", {}, sid)] : []),
send(t.tabId, "Network.enable", {}, sid),
send(t.tabId, "DOM.enable", {}, sid),
send(t.tabId, "Accessibility.enable", {}, sid),
@@ -194,6 +225,8 @@ chrome.debugger.onEvent.addListener((src, method, p) => {
if (!p.frame.parentId) {
t.mainFrame = p.frame.id;
t.inflight.clear();
// a developer's own page: its logs are read from the start
try { if (!t.console && DEV.test(new URL(p.frame.url).hostname)) watchConsole(t); } catch {}
}
break;
case "Runtime.consoleAPICalled": {
@@ -263,27 +296,69 @@ async function mainFrame(t) {
return t.mainFrame;
}
const STALE_WORLD = /Cannot find context|context with specified id|Execution context was destroyed|Inspected target navigated/i;
// world is magpie's isolated world in a frame (the tab's main frame
// without one, or the frame of session sid): its execution context id, a
// new one for each document
export async function world(t, frame, sid) {
if (!frame) frame = sid ? t.frameOf.get(sid)?.frame : await mainFrame(t);
if (!frame) throw new Error("the page has no frame to read");
const k = (sid || "") + "|" + frame;
let ctx = t.worlds.get(k);
if (!ctx) {
ctx = (await send(t.tabId, "Page.createIsolatedWorld", { frameId: frame, worldName: "magpie" }, sid)).executionContextId;
t.worlds.set(k, ctx);
}
return ctx;
}
// inWorld runs fn(ctx) in magpie's world of a frame, in a new one when
// the document it had is gone
async function inWorld(t, where, fn) {
for (let i = 0; ; i++) {
let ctx;
try {
ctx = await world(t, where.frame, where.sid);
return await fn(ctx);
} catch (e) {
if (i > 0 || !STALE_WORLD.test(String(e && e.message || e))) throw e;
if (where.frame) t.worlds.delete((where.sid || "") + "|" + where.frame);
else for (const [k, v] of t.worlds) if (v === ctx) t.worlds.delete(k);
if (!where.frame && !where.sid) t.mainFrame = null; // a new document may be a new frame
}
}
}
// read evaluates an expression in magpie's world of the main frame (or
// where: {frame, sid}) and answers its value
export async function read(t, expression, where = {}) {
return inWorld(t, where, async (contextId) => {
const r = await send(t.tabId, "Runtime.evaluate", { expression, contextId, returnByValue: true, awaitPromise: true }, where.sid);
if (r.exceptionDetails) throw new Error((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text);
return r.result.value;
});
}
// evaluate is read answering the remote object, for the caller to walk
export async function evaluate(t, expression, objectGroup, where = {}) {
return inWorld(t, where, async (contextId) => (await send(t.tabId, "Runtime.evaluate", { expression, contextId, objectGroup }, where.sid)).result);
}
// resolve is an element (by backendNodeId) as an object in magpie's world
// of the frame its document is
export async function resolve(t, backendNodeId, where = {}, objectGroup = "magpie-act") {
return inWorld(t, where, async (executionContextId) =>
(await send(t.tabId, "DOM.resolveNode", { backendNodeId, objectGroup, executionContextId }, where.sid)).object);
}
// 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;
try {
const v = await read(t, WATCH, { frame, sid });
return Array.isArray(v) ? v : null;
} catch { return null; }
}
// settle waits for the page to go quiet after an action: no load under
@@ -312,8 +387,8 @@ export async function waitLoad(t, bound = 30000) {
while (Date.now() < end) {
if (!t.loading) {
try {
const r = await send(t.tabId, "Runtime.evaluate", { expression: "document.readyState", returnByValue: true });
if (r.result.value === "complete" || r.result.value === "interactive") return true;
const v = await read(t, "document.readyState");
if (v === "complete" || v === "interactive") return true;
} catch {}
}
await sleep(150);
+245
View File
@@ -0,0 +1,245 @@
// Input as a person makes it. A site that watches for automation reads
// how input arrives: a pointer that jumps to the exact middle of a button
// and clicks in the same instant, text that appears with no key pressed,
// a page scrolled in one leap, one action straight after another. Here the
// mouse travels a curved, uneven path to a point somewhere on the element,
// waits a moment and holds the button as a finger does; text is typed key
// by key with a typist's uneven rhythm (an input method's composition for
// Chinese, Japanese and Korean); a scroll is the wheel's notches; and an
// action waits a person's moment after the last one.
import { send, sleep } from "./cdp.js";
const rand = (a, b) => a + Math.random() * (b - a);
// a normal draw (Box–Muller), for what clusters around a value
function gauss(mean, sd) {
let u = 0, v = 0;
while (!u) u = Math.random();
while (!v) v = Math.random();
return mean + sd * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
// pace waits until a person's moment has passed since the last action in
// the tab: no one clicks the next thing in the same instant
export async function pace(t) {
const since = Date.now() - (t.lastInput || 0);
const want = clamp(gauss(750, 250), 350, 1600);
if (since < want) await sleep(want - since);
}
export function done(t) {
t.lastInput = Date.now();
}
// aim is where on a box [x0, y0, x1, y1] to put the mouse: near the middle,
// rarely the exact middle, never at the edges
export function aim(x0, y0, x1, y1) {
const w = x1 - x0, h = y1 - y0;
const fx = clamp(gauss(0.5, 0.12), 0.25, 0.75);
const fy = clamp(gauss(0.5, 0.1), 0.3, 0.7);
return { x: x0 + w * fx, y: y0 + h * fy };
}
const ease = (s) => (s < 0.5 ? 2 * s * s : 1 - Math.pow(-2 * s + 2, 2) / 2);
// move takes the mouse from where it was to (x, y) along a curve, quick in
// the middle and slow at both ends, a few pixels off a straight line;
// buttons is held down for a drag
export async function move(t, x, y, opts = {}) {
const buttons = opts.buttons || 0;
const modifiers = opts.modifiers || 0;
let from = t.mouse;
if (!from) {
// the first move in a tab comes in from somewhere off to one side
const m = await send(t.tabId, "Page.getLayoutMetrics").catch(() => null);
const vw = (m && (m.cssVisualViewport || m.layoutViewport)) || { clientWidth: 1000, clientHeight: 700 };
from = { x: clamp(x + rand(-260, 260), 2, vw.clientWidth - 2), y: clamp(y + rand(120, 260) * (Math.random() < 0.5 ? -1 : 1), 2, vw.clientHeight - 2) };
}
const dx = x - from.x, dy = y - from.y;
const dist = Math.hypot(dx, dy);
const steps = clamp(Math.round(dist / rand(18, 30)), dist < 3 ? 1 : 4, 40);
// two control points off the line, on one side: an arm's arc
const side = Math.random() < 0.5 ? -1 : 1;
const bend = clamp(dist * rand(0.05, 0.2), 0, 120) * side;
const nx = dist ? -dy / dist : 0, ny = dist ? dx / dist : 0;
const c1 = { x: from.x + dx * 0.3 + nx * bend, y: from.y + dy * 0.3 + ny * bend };
const c2 = { x: from.x + dx * 0.7 + nx * bend * 0.6, y: from.y + dy * 0.7 + ny * bend * 0.6 };
for (let i = 1; i <= steps; i++) {
const s = ease(i / steps), r = 1 - s;
let px = r * r * r * from.x + 3 * r * r * s * c1.x + 3 * r * s * s * c2.x + s * s * s * x;
let py = r * r * r * from.y + 3 * r * r * s * c1.y + 3 * r * s * s * c2.y + s * s * s * y;
if (i < steps) { px += rand(-0.7, 0.7); py += rand(-0.7, 0.7); }
await send(t.tabId, "Input.dispatchMouseEvent", {
type: "mouseMoved", x: Math.round(px * 100) / 100, y: Math.round(py * 100) / 100, modifiers,
button: buttons ? "left" : "none", buttons,
});
t.mouse = { x: px, y: py };
await sleep(rand(7, 17));
}
t.mouse = { x, y };
}
const BUTTONS = { left: "left", right: "right", middle: "middle" };
const BUTTON_BIT = { left: 1, right: 2, middle: 4 };
// click moves to (x, y), waits as a hand settles on the spot, and presses
// and lets go of the button (twice for a double click)
export async function click(t, x, y, opts = {}) {
const button = BUTTONS[opts.button] || "left";
const modifiers = opts.modifiers || 0;
const count = opts.double ? 2 : 1;
await move(t, x, y, { modifiers });
await sleep(clamp(gauss(110, 40), 45, 260));
for (let i = 1; i <= count; i++) {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, buttons: BUTTON_BIT[button], clickCount: i, modifiers });
await sleep(clamp(gauss(80, 22), 40, 150));
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button, buttons: 0, clickCount: i, modifiers });
if (i < count) await sleep(rand(70, 130));
}
}
// drag presses at one point, moves to the other with the button held and
// lets go there
export async function drag(t, p, q) {
await move(t, p.x, p.y);
await sleep(rand(80, 160));
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x: p.x, y: p.y, button: "left", buttons: 1, clickCount: 1 });
try {
await sleep(rand(90, 180));
await move(t, q.x, q.y, { buttons: 1 });
await sleep(rand(80, 160));
} finally {
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseReleased", x: q.x, y: q.y, button: "left", buttons: 0, clickCount: 1 });
}
}
// wheel scrolls by (dx, dy) at (x, y) a wheel notch at a time, the mouse
// moved there first
export async function wheel(t, x, y, dx, dy) {
if (!t.mouse || Math.hypot(t.mouse.x - x, t.mouse.y - y) > 40) await move(t, x, y);
const total = Math.abs(dx) + Math.abs(dy);
const notch = 100;
let n = Math.max(1, Math.round(total / notch));
let left = { x: dx, y: dy };
for (let i = 0; i < n; i++) {
const last = i === n - 1;
const sx = last ? left.x : Math.round(dx / n), sy = last ? left.y : Math.round(dy / n);
left = { x: left.x - sx, y: left.y - sy };
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: sx, deltaY: sy });
// a flick turns a few notches quickly, then the finger comes back
await sleep(i % 4 === 3 ? rand(120, 260) : rand(28, 70));
}
}
// ---- keys ----------------------------------------------------------------
// a US layout: the key a character is on, and whether Shift is held
const SHIFTED = { "!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0", "_": "-", "+": "=", "{": "[", "}": "]", "|": "\\", ":": ";", "\"": "'", "<": ",", ">": ".", "?": "/", "~": "`" };
const PUNCT = { "-": ["Minus", 189], "=": ["Equal", 187], "[": ["BracketLeft", 219], "]": ["BracketRight", 221], "\\": ["Backslash", 220], ";": ["Semicolon", 186], "'": ["Quote", 222], ",": ["Comma", 188], ".": ["Period", 190], "/": ["Slash", 191], "`": ["Backquote", 192], " ": ["Space", 32] };
// keyOf is the key a character is typed with on a US keyboard, or null
// when it isn't on one
export function keyOf(ch) {
let base = ch, shift = false;
if (/^[A-Z]$/.test(ch)) { base = ch.toLowerCase(); shift = true; }
else if (SHIFTED[ch]) { base = SHIFTED[ch]; shift = true; }
if (/^[a-z]$/.test(base)) return { key: ch, code: "Key" + base.toUpperCase(), keyCode: base.toUpperCase().charCodeAt(0), shift };
if (/^[0-9]$/.test(base)) return { key: ch, code: "Digit" + base, keyCode: base.charCodeAt(0), shift };
if (PUNCT[base]) return { key: ch, code: PUNCT[base][0], keyCode: PUNCT[base][1], shift };
return null;
}
// text typed through an input method: Chinese, Japanese, Korean
const IME = /[぀-ヿ㐀-䶿一-鿿豈-﫿가-힯 -〿＀-￯]/;
async function shiftKey(t, down) {
await send(t.tabId, "Input.dispatchKeyEvent", { type: down ? "rawKeyDown" : "keyUp", key: "Shift", code: "ShiftLeft", windowsVirtualKeyCode: 16, modifiers: down ? 8 : 0 });
}
// the pause after a key: a typist is quicker inside a word than between
// words, and stops to think now and then; scaled down for a long text
function gap(ch, scale) {
let ms = clamp(gauss(105, 38), 38, 260);
if (ch === " ") ms += rand(10, 70);
else if (/[.,!?;:,。!?;:、]/.test(ch)) ms += rand(60, 220);
if (Math.random() < 0.035) ms += rand(250, 700);
return Math.max(10, ms * scale);
}
// how long typing may take in all: the gateway waits 100s for a call
const TYPE_BUDGET_MS = 35000;
// type types text into the focused element. newline is how a line break
// is typed there: "Shift+Enter" in a field where Enter sends (a chat box),
// "" where there are no lines (a one-line field drops it).
export async function type(t, text, opts = {}) {
const chars = [...String(text)];
const est = chars.length * 120;
const scale = est > TYPE_BUDGET_MS ? TYPE_BUDGET_MS / est : 1;
const newline = opts.newline ?? "Shift+Enter";
let held = false;
for (let i = 0; i < chars.length; i++) {
const ch = chars[i];
if (ch === "\r") continue;
if (ch === "\n") {
if (held) { await shiftKey(t, false); held = false; }
if (newline) await opts.press(newline);
await sleep(gap(ch, scale));
continue;
}
if (IME.test(ch)) {
if (held) { await shiftKey(t, false); held = false; }
// a word or two at a time: what an input method commits
let run = ch;
const len = Math.round(rand(1, 4));
while (run.length < len && i + 1 < chars.length && IME.test(chars[i + 1])) run += chars[++i];
await compose(t, run, scale);
await sleep(gap(run.slice(-1), scale) * 1.5);
continue;
}
const k = keyOf(ch);
if (!k) {
// an emoji or a letter no US key has: chosen from a picker, as a
// person enters one
if (held) { await shiftKey(t, false); held = false; }
await send(t.tabId, "Input.insertText", { text: ch });
await sleep(gap(ch, scale) * 2);
continue;
}
if (k.shift !== held) {
await shiftKey(t, k.shift);
held = k.shift;
await sleep(rand(15, 45) * scale);
}
const mods = held ? 8 : 0;
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyDown", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, text: ch, unmodifiedText: k.shift ? ch : ch, modifiers: mods });
// the key comes up while the next is already on its way down, now
// and then, as fingers roll
await sleep(clamp(gauss(55, 18), 18, 120) * Math.max(scale, 0.3));
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode, modifiers: mods });
const next = chars[i + 1];
if (held && !(next && keyOf(next) && keyOf(next).shift)) { await sleep(rand(10, 40) * scale); await shiftKey(t, false); held = false; }
await sleep(gap(ch, scale));
}
if (held) await shiftKey(t, false);
}
// compose enters text as an input method does: the keys go to it (key
// "Process"), the text under composition grows, and it is committed
async function compose(t, run, scale) {
const ime = (type) => send(t.tabId, "Input.dispatchKeyEvent", { type, key: "Process", code: "", windowsVirtualKeyCode: 229, nativeVirtualKeyCode: 229 });
let ok = true;
for (let j = 1; j <= run.length && ok; j++) {
await ime("rawKeyDown");
const part = run.slice(0, j);
ok = await send(t.tabId, "Input.imeSetComposition", { text: part, selectionStart: part.length, selectionEnd: part.length }).then(() => true, () => false);
await sleep(clamp(gauss(50, 15), 20, 100) * Math.max(scale, 0.3));
await ime("keyUp");
await sleep(clamp(gauss(140, 50), 50, 320) * scale);
}
await ime("rawKeyDown");
await send(t.tabId, "Input.insertText", { text: run });
await sleep(rand(20, 60) * Math.max(scale, 0.3));
await ime("keyUp");
}
+6 -13
View File
@@ -77,10 +77,14 @@ export async function press(t, combo) {
const k = describe(keyName, !!(modifiers & 8));
const commands = [];
if (mac && (modifiers & 4) && MAC_COMMANDS[k.key.toLowerCase()]) commands.push(MAC_COMMANDS[k.key.toLowerCase()]);
// held as a hand holds them: the modifiers a moment first, the key
// down for as long as a press lasts
const hold = (a, b) => sleep(a + Math.random() * (b - a));
let held = 0;
for (const m of mods) {
held |= MODS[m];
await send(t.tabId, "Input.dispatchKeyEvent", { type: "rawKeyDown", modifiers: held, key: m, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].keyCode });
await hold(30, 80);
}
// a chord with Control, Alt or Meta types no text
const typed = k.text && !(modifiers & 7);
@@ -90,22 +94,11 @@ export async function press(t, combo) {
...(typed ? { text: k.text, unmodifiedText: k.text } : {}),
...(commands.length ? { commands } : {}),
});
await sleep(20);
await hold(50, 120);
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers, key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode });
for (const m of mods.reverse()) {
await hold(20, 60);
held &= ~MODS[m];
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers: held, key: m, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].keyCode });
}
}
// typeSlowly types text a key at a time, for a field that listens to
// each key (an autocomplete, a field that formats as you type).
export async function typeSlowly(t, text) {
for (const ch of String(text)) {
if (ch === "\n") { await press(t, "Enter"); continue; }
const k = /^[a-z0-9]$/i.test(ch) ? describe(ch.toLowerCase(), ch !== ch.toLowerCase()) : { key: ch, code: "", keyCode: 0, text: ch };
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyDown", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, text: k.text, unmodifiedText: k.text, modifiers: /[A-Z]/.test(ch) ? 8 : 0 });
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode });
await sleep(30 + Math.random() * 50);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Magpie Browser",
"version": "0.1.5",
"version": "0.1.6",
"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",
+14 -12
View File
@@ -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 { fault, send } from "./cdp.js";
import { evaluate, fault, read, resolve, send } from "./cdp.js";
const INTERACTIVE = new Set([
"button", "link", "textbox", "searchbox", "checkbox", "radio", "combobox",
@@ -43,12 +43,14 @@ const CLICKABLE = `(() => {
return out;
})()`;
async function clickables(tabId) {
// run in magpie's isolated world: the page's scripts never see the scan
async function clickables(t) {
const tabId = t.tabId;
const ids = new Set();
try {
const r = await send(tabId, "Runtime.evaluate", { expression: CLICKABLE, objectGroup: "magpie-snap" });
if (!r.result || !r.result.objectId) return ids;
const props = await send(tabId, "Runtime.getProperties", { objectId: r.result.objectId, ownProperties: true });
const r = await evaluate(t, CLICKABLE, "magpie-snap");
if (!r || !r.objectId) return ids;
const props = await send(tabId, "Runtime.getProperties", { objectId: r.objectId, ownProperties: true });
await Promise.all(props.result.filter((p) => /^\d+$/.test(p.name) && p.value && p.value.objectId).map(async (p) => {
try {
const d = await send(tabId, "DOM.describeNode", { objectId: p.value.objectId });
@@ -115,9 +117,9 @@ export async function take(t, opts = {}) {
const tabId = t.tabId;
const [{ nodes }, clickable, inner, info] = await Promise.all([
send(tabId, "Accessibility.getFullAXTree"),
clickables(tabId),
clickables(t),
frames(t),
send(tabId, "Runtime.evaluate", { expression: "[location.href, document.title]", returnByValue: true }).then((r) => r.result.value).catch(() => ["", ""]),
read(t, "[location.href, document.title]").catch(() => ["", ""]),
]);
const [url, title] = info;
// a new document starts its refs over; the same one keeps them
@@ -285,17 +287,17 @@ export async function find(t, ref) {
const r = t.refs.get(ref);
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" }, 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 };
const o = await resolve(t, r.backend, r);
const c = await send(t.tabId, "Runtime.callFunctionOn", { objectId: o.objectId, functionDeclaration: "function(){return this.isConnected}", returnByValue: true }, r.sid);
if (c.result.value) return { ...r, ref, objectId: o.objectId };
} catch {}
// the page drew it again: the same role and name, if only one has it
await take(t, { maxChars: 1 });
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" }, v.sid);
return { ...v, ref: nref, objectId: o.object.objectId };
const o = await resolve(t, v.backend, v);
return { ...v, ref: nref, objectId: o.objectId };
}
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`);
+169
View File
@@ -7,6 +7,7 @@ import (
"html"
"image/jpeg"
"io"
"math"
"net/http"
"net/http/httptest"
"net/url"
@@ -277,6 +278,9 @@ func realBrowserFrom(t *testing.T, ext func(*httptest.Server) string) (srv, site
// behind another tab
io.WriteString(w, `<!doctype html><title>Watch 0</title><h1>The user's page</h1><script>let hid = 0; document.addEventListener("visibilitychange", () => { if (document.hidden) document.title = "Watch " + ++hid; });</script>`)
return
case "/human":
io.WriteString(w, humanFixture)
return
case "/refused":
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, "<!doctype html><title>Denied</title><h1>Access denied</h1>")
@@ -301,6 +305,9 @@ func realBrowserFrom(t *testing.T, ext func(*httptest.Server) string) (srv, site
// (Linux), and Chrome waits on it before the extension's storage
// answers
"--use-mock-keychain", "--password-store=basic",
// a site's own name, not a developer's host: shop.example is the
// test's site
"--host-resolver-rules=MAP shop.example 127.0.0.1",
// the user's own page, which the extension never attaches to
site.URL+"/watch")
var logs bytes.Buffer
@@ -545,3 +552,165 @@ func TestBrowserOlderExtensionsFolderWritten(t *testing.T) {
time.Sleep(50 * time.Millisecond)
}
}
// A shop's page that watches for an automated browser the ways bot checks
// do: its own getComputedStyle,
// querySelectorAll, elementFromPoint and focus counting the calls a script
// in its world makes, and every mouse, key, composition and wheel event.
const humanFixture = `<!doctype html>
<title>Shop</title>
<h1>Shop</h1>
<button id="buy" style="width: 121px; height: 41px">Buy</button>
<button onclick="console.log('bought')">Log</button>
<input aria-label="Search" id="search">
<textarea aria-label="Message" id="msg"></textarea>
<div contenteditable="true" role="textbox" aria-label="Chat" id="chat" style="min-height: 2em; border: 1px solid"></div>
<div style="height: 4000px"></div>
<script>
const seen = { calls: [], moves: 0, movesBeforeClick: -1, click: null, keys: [], shift: 0, composed: [], wheels: 0 };
window.seen = seen;
const spy = (o, k, name) => { const f = o[k]; o[k] = function (...a) { seen.calls.push(name); return f.apply(this, a); }; };
spy(window, "getComputedStyle", "getComputedStyle");
spy(Document.prototype, "querySelectorAll", "querySelectorAll");
spy(Element.prototype, "querySelectorAll", "querySelectorAll");
spy(Document.prototype, "elementFromPoint", "elementFromPoint");
spy(HTMLElement.prototype, "focus", "focus");
addEventListener("mousemove", () => seen.moves++, true);
buy.addEventListener("click", (ev) => {
const r = buy.getBoundingClientRect();
seen.movesBeforeClick = seen.moves;
seen.click = { trusted: ev.isTrusted, dx: ev.clientX - (r.left + r.width / 2), dy: ev.clientY - (r.top + r.height / 2) };
});
addEventListener("keydown", (ev) => { seen.keys.push([ev.key, performance.now(), ev.isTrusted]); if (ev.key === "Shift") seen.shift++; }, true);
addEventListener("compositionend", (ev) => seen.composed.push(ev.data), true);
// a chat box sends on Enter, as Discord's does
chat.addEventListener("keydown", (ev) => { if (ev.key === "Enter" && !ev.shiftKey) { ev.preventDefault(); seen.sent = chat.innerText; } });
addEventListener("wheel", () => seen.wheels++, { capture: true, passive: true });
</script>`
// The extension drives a site the way a person does, so the bot checks
// sites like Discord run don't find it (the owner, 11-05: Discord flagged
// the account under Magpie Browser, never under Claude's extension): CDP's
// Runtime domain, which a page can find by what the console does with its
// values, stays off until console is asked for on a site's own host; its reads and helpers run in a world of its own, so the page's
// own functions never see a call; a click comes after the mouse has moved
// there, trusted and off the exact middle; text is typed a key at a time
// at uneven gaps, capitals with Shift, Chinese through an IME's
// composition; a scroll is several wheel notches; and naming the user's
// own tab opens its page in a tab of the agent's, leaving theirs alone.
func TestBrowserActsLikeAPerson(t *testing.T) {
srv, site := realBrowser(t)
call, ok := browserCaller(t, srv, "person")
shop := strings.Replace(site.URL, "127.0.0.1", "shop.example", 1) + "/human"
page := ok("browser_tabs", map[string]any{"action": "new", "url": shop}, "Opened t", "Shop")
ref := func(role, name string) string {
t.Helper()
m := regexp.MustCompile(`- ` + role + ` "` + 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]
}
page = ok("browser_snapshot", nil, "Shop")
ok("browser_click", map[string]any{"ref": ref("button", "Buy")}, "Clicked")
ok("browser_type", map[string]any{"ref": ref("textbox", "Search"), "text": "Hello, World"}, "Typed into")
ok("browser_type", map[string]any{"ref": ref("textbox", "Message"), "text": "你好 ok"}, "Typed into")
ok("browser_type", map[string]any{"ref": ref("textbox", "Chat"), "text": "早上好\nline two", "submit": true}, "Typed into")
ok("browser_scroll", map[string]any{"direction": "down", "amount": 600}, "Scrolled")
ok("browser_wait", map[string]any{"text": "Shop"})
ok("browser_text", nil, "Shop")
var seen struct {
Calls []string
Moves int
MovesBeforeClick int
Click *struct {
Trusted bool
Dx, Dy float64
}
Keys [][]any
Shift int
Composed []string
Wheels int
Sent string
}
out := ok("browser_evaluate", map[string]any{"script": "() => seen"})
if i := strings.Index(out, "{"); i < 0 || json.Unmarshal([]byte(out[i:strings.LastIndex(out, "}")+1]), &seen) != nil {
t.Fatalf("the page's record: %s", out)
}
if len(seen.Calls) != 0 {
t.Errorf("the page saw the extension call its own functions: %v", seen.Calls)
}
if seen.Click == nil || !seen.Click.Trusted {
t.Errorf("no trusted click on Buy: %+v", seen.Click)
} else if math.Abs(seen.Click.Dx) <= 0.5 && math.Abs(seen.Click.Dy) <= 0.5 {
t.Errorf("the click landed on the middle of Buy (%v, %v)", seen.Click.Dx, seen.Click.Dy)
}
if seen.MovesBeforeClick < 4 {
t.Errorf("the mouse moved %d times before the click, not along a path", seen.MovesBeforeClick)
}
var typed, gaps []float64
for _, k := range seen.Keys {
if k[0] != "Shift" && k[0] != "Backspace" && k[0] != "Process" {
typed = append(typed, k[1].(float64))
}
if k[2] != true {
t.Errorf("an untrusted keydown: %v", k)
}
}
if len(typed) < len("Hello, World")+len(" ok") {
t.Errorf("%d keydowns for %d typed characters: text went in without keys", len(typed), len("Hello, World")+len(" ok"))
}
for i := 1; i < len(typed) && i < 12; i++ {
gaps = append(gaps, typed[i]-typed[i-1])
}
lo, hi := 1e9, 0.0
for _, g := range gaps {
lo, hi = min(lo, g), max(hi, g)
}
if len(gaps) < 5 || hi-lo < 20 {
t.Errorf("the gaps between keys are even (%v): a person's are not", gaps)
}
if seen.Shift < 2 {
t.Errorf("Shift was pressed %d times for H and W", seen.Shift)
}
if strings.Join(seen.Composed, "") != "你好早上好" {
t.Errorf("Chinese didn't come through an IME's composition: %q", seen.Composed)
}
if seen.Sent != "早上好\nline two" {
t.Errorf("the chat box sent %q: a newline must not send it early, submit must", seen.Sent)
}
if seen.Wheels < 3 {
t.Errorf("a 600px scroll came as %d wheel events", seen.Wheels)
}
ok("browser_evaluate", map[string]any{"script": "() => search.value + '|' + msg.value"}, "Hello, World|你好 ok")
// the console is off on a site's own host until asked for, then read
ok("browser_console", nil, "reads this tab's console from now on")
ok("browser_click", map[string]any{"ref": ref("button", "Log")})
ok("browser_console", nil, "bought")
// the user's own tab, named, is opened in one of the agent's
users := regexp.MustCompile(`(?m)^[+ ] (t\d+) "Watch 0" .*/watch$`).FindStringSubmatch(ok("browser_tabs", nil))
if users == nil {
t.Fatal("no user's page")
}
got := ok("browser_snapshot", map[string]any{"tab": users[1]}, "is the user's own tab", "The user's page")
copied := regexp.MustCompile(`opened in (t\d+)`).FindStringSubmatch(got)
if copied == nil || copied[1] == users[1] {
t.Fatalf("no tab of the agent's for the user's %s:\n%s", users[1], got)
}
if again := ok("browser_snapshot", map[string]any{"tab": users[1]}); strings.Contains(again, "is the user's own tab") || !strings.Contains(again, copied[1]) {
t.Fatalf("naming the user's tab again didn't go on in %s:\n%s", copied[1], again)
}
list := ok("browser_tabs", nil)
if !regexp.MustCompile(`(?m)^\* ` + copied[1] + ` \[Magpie\] "Watch 0"`).MatchString(list) {
t.Fatalf("the copy %s isn't the agent's, in its group:\n%s", copied[1], list)
}
if !regexp.MustCompile(`(?m)^[+ ] ` + users[1] + ` "Watch 0" .*/watch$`).MatchString(list) {
t.Fatalf("the user's tab %s changed:\n%s", users[1], list)
}
if m := call("browser_tabs", map[string]any{"action": "close", "tab": users[1]}); !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "the user's own tab") {
t.Fatalf("closing the user's tab: %+v", m.Result)
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ func browserOneTool() map[string]any {
return map[string]any{
"name": "browser",
"title": "Browser",
"description": "Act in the user's own browser, in tabs of your own opened behind the one they are looking at, in your Magpie tab group; their own tabs only when you name one. Actions, with the arguments each takes:\n" +
"description": "Act in the user's own browser, in tabs of your own opened behind the one they are looking at, in your Magpie tab group; a tab of the user's you name has its page opened in one of yours. Actions, with the arguments each takes:\n" +
"tabs: list them. tab_new [url, front]. tab_select [tab]. tab_close [tab]. browsers: the connected ones. use_browser [browser].\n" +
"navigate [url]. back. forward. reload.\n" +
"snapshot [interactive, ref, maxChars]: the page as an accessibility tree, a ref on each element you can act on.\n" +
+3 -2
View File
@@ -7,13 +7,14 @@ package gateway
const browserInstructions = `The browser tool uses the user's own browser (Chrome, Edge or another Chromium browser with Magpie Browser installed): its real tabs, signed in to the sites the user is signed in to. Use it when a task needs the user's sessions or a real browser.
How to work:
- Start with action tabs or 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 that tabs marks ~ to the agents working in them.
- Start with tab_new (with a url) or snapshot. You work in tabs of your own, opened behind the user's in your own tab group ("Magpie", or "Magpie 2" and on beside other agents), so the user goes on using their browser undisturbed. Naming one of the user's own tabs opens its page in a tab of yours, signed in the same; theirs is left alone. Leave the tabs that tabs marks ~ to the agents working in them.
- Clicks, typing and scrolling go at a person's pace, so a step takes a second or two: don't hurry them with repeated calls. console starts reading a tab's console the first time it is asked (except on localhost and other development hosts, read from the start).
- With two browsers connected (Chrome and Edge, or two profiles), calls go to the last to connect: action browsers lists them, and use_browser picks one.
- snapshot shows the page as an accessibility tree. Elements you can act on carry a ref (e12); pass it to click, 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 evaluate. When the layout or an image matters, add screenshot: true to an action (a small picture of the window comes with its answer), or take a screenshot.
- 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.`
- This is the user's browser: you can close only tabs you opened, 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.`
func browserTabArg() map[string]any {
return map[string]any{"type": "string", "description": "The tab to act in (t123, from browser_tabs). Without it: the tab this session works in, or a new one of its own behind the tab the user is looking at."}