browser: let a tab go 20s after its last call, CDP as Claude in Chrome uses it, input a person sends
Discord again took Magpie Browser for a bot. This lines the extension
up with Claude in Chrome 1.0.105 (fcoeoabgfenejglbffodgkkbkcdhcgfn), read
from its assets/mcpPermissions-*.js, and with what a real mouse and
keyboard send:
- A tab is let go 20s after the last call in it ends (Claude's qC=2e4),
not 5 minutes after it was last attached. Before it goes, focus
emulation is turned off, as Claude's detachDebugger does. A page behind
the user's tab no longer goes on for minutes saying it has focus while
its window reports 0x0. A tab no call used is left on its clock, so
another session's calls don't hold it; typing that goes on after its
call keeps its tab (re-armed every 10s) and lets it go when it ends.
- Attach turns on Page, Network (the page can't see it; settle needs it)
and Runtime only where it was already (a dev host or browser_console),
then focus emulation once. DOM.enable and Accessibility.enable are gone:
Claude turns neither on, nothing listened to their events, and the
calls magpie makes (getFullAXTree, resolveNode, getContentQuads, ...)
work without them.
- A pressed button has pressure 0.5 (was 0; Claude sends force 0.5 when
buttons != 0). Shift, Control, Alt and Meta have location 1 (left), as
a real keyboard's; Claude passes the key's location too.
- No nativeVirtualKeyCode: it took the Windows code, and on macOS it is
read as a Mac key code. Claude doesn't send it.
- Long text keeps a person's pace (~165ms a character, quickened only
past 4 minutes) instead of fitting 35s, which reached 20+ characters a
second. browser_type answers after 40s with how far it got; the typing
goes on, and the tab's next call waits for it (BUSY after 60s).
- manifest 0.1.8.
Run on mote, headful Chrome for Testing (MAGPIE_BROWSER_HEADFUL=1):
go test ./internal/gateway -run TestBrowser -v: all 27 pass, among them
the new TestBrowserLetsATabGoAfterItsCalls (23.7s; the page's own
document.hasFocus() is on during calls and off within 15-45s after),
TestBrowserTypesALongTextAtAPersonsPace (66s, <= 9 chars/s, Enter after
the whole text) and TestBrowserActsLikeAPerson (pressure 0.5, Shift
location 1). Snapshots, frames from other sites, uploads and drags pass
without DOM/Accessibility enabled.
Broken by hand: IDLE_MS back to 5 minutes, TestBrowserLetsATabGoAfterItsCalls
is red ("still has emulated focus 45s after the last call"). Without force 0.5
on a click, TestBrowserActsLikeAPerson is red ("pressure 0: a mouse's is
0.5"); without location 1 on human.js's Shift, red ("location 0"),
once the test checks every Shift down, not only the last, which came
from keys.js's Shift+Enter.
go vet (darwin, windows, linux) ./internal/gateway ./internal/browserext:
ok. go test ./internal/browserext ./internal/gateway -timeout 45m
(headless): ok, gateway 866s.
Not tried: a real Discord account. Per the 11-08 limit nothing scripted
touches it. Not fixed: a background tab's outerWidth/outerHeight/screenX
are 0 while focus is emulated (Claude in Chrome has the same; the device
metrics override broke availHeight), and a page's own window.open from
the agent's tab still comes to the front for a moment.
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, KEY } from "./config.js";
|
||||
import { attach, fault, forget, read, send, settle, sleep, state, waitLoad, watch, watchConsole } from "./cdp.js";
|
||||
import { attach, fault, forget, read, release, releaseAll, send, settle, sleep, state, waitLoad, watch, watchConsole } from "./cdp.js";
|
||||
import { find, take } from "./snapshot.js";
|
||||
import { press as keyPress } from "./keys.js";
|
||||
import * as human from "./human.js";
|
||||
@@ -287,7 +287,11 @@ function failure(e) {
|
||||
return fail(`${code}: ${m}${after && !m.includes(after) ? "\n" + after : ""}`);
|
||||
}
|
||||
|
||||
// calls running now: tabs are let go only once none is
|
||||
let running = 0;
|
||||
|
||||
async function run(m) {
|
||||
running++;
|
||||
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)`);
|
||||
@@ -304,19 +308,34 @@ async function run(m) {
|
||||
return r;
|
||||
} catch (e) {
|
||||
return failure(e);
|
||||
} finally {
|
||||
if (--running === 0) releaseAll();
|
||||
}
|
||||
}
|
||||
|
||||
// how long browser_type waits for its typing before it answers
|
||||
const TYPE_WAIT_MS = 40000;
|
||||
// how long a call waits for typing still going on in its tab
|
||||
const TYPING_WAIT_MS = 60000;
|
||||
|
||||
async function ready(session, args) {
|
||||
const tabId = await tabFor(session, args);
|
||||
const t = state(tabId);
|
||||
if (t.typing) {
|
||||
await Promise.race([t.typing, sleep(TYPING_WAIT_MS)]);
|
||||
if (t.typing) throw fault("BUSY", `still typing in this tab, about ${Math.max(1, Math.ceil((t.typingEnds - Date.now()) / 1000))}s more: call again then`);
|
||||
}
|
||||
if (t.typingFailed) {
|
||||
const why = t.typingFailed;
|
||||
t.typingFailed = null;
|
||||
throw fault("TYPING_FAILED", `the typing the last browser_type went on with stopped: ${why}. Take a snapshot to see what went in.`);
|
||||
}
|
||||
if (t.stoppedByUser) {
|
||||
t.stoppedByUser = false;
|
||||
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);
|
||||
await send(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
|
||||
return t;
|
||||
}
|
||||
|
||||
@@ -684,12 +703,33 @@ const TOOLS = {
|
||||
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");
|
||||
const progress = {};
|
||||
const job = (async () => {
|
||||
// the debugger stays on the tab for as long as the typing lasts
|
||||
const keep = setInterval(() => attach(t.tabId).catch(() => {}), 10000);
|
||||
try {
|
||||
await typeIn();
|
||||
} finally {
|
||||
clearInterval(keep);
|
||||
}
|
||||
})();
|
||||
async function typeIn() {
|
||||
if (args.text) await human.type(t, args.text, { progress, 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");
|
||||
}
|
||||
}
|
||||
// a long text is typed at a person's pace, longer than a call may
|
||||
// wait: the call answers and the typing goes on, and the tab's next
|
||||
// call waits for it
|
||||
const finished = await Promise.race([job.then(() => true), sleep(TYPE_WAIT_MS).then(() => false)]);
|
||||
if (finished) return "";
|
||||
t.typing = job.then(() => { t.typingFailed = null; }, (e) => { t.typingFailed = String(e && e.message || e).slice(0, 200); })
|
||||
.finally(() => { t.typing = null; human.done(t); if (!running) release(t.tabId); });
|
||||
t.typingEnds = Date.now() + human.typingTime([...args.text].slice(progress.done).join(""));
|
||||
return `Typing into ${el.ref}: ${progress.done} of ${progress.of} characters so far. The rest goes in at a person's pace, about ${Math.ceil((t.typingEnds - Date.now()) / 1000)}s more${args.submit ? ", then Enter" : ""}; the next call in this tab waits for it.`;
|
||||
}, el);
|
||||
},
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 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, and doesn't come and go between an agent's calls.
|
||||
// tab is attached while a call works in it and let go 20s after the last
|
||||
// call ends, as Claude in Chrome does, so a site never sits for minutes
|
||||
// under a debugger with its focus emulated.
|
||||
//
|
||||
// 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
|
||||
@@ -10,7 +10,10 @@
|
||||
// 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 = 5 * 60 * 1000;
|
||||
// let go this long after the last call in a tab ends
|
||||
const IDLE_MS = 20 * 1000;
|
||||
// a bound on one call (or a typing that goes on after its call)
|
||||
const BUSY_MS = 5 * 60 * 1000;
|
||||
const LOG_KEPT = 300;
|
||||
|
||||
// tabId → what is known of the page while attached
|
||||
@@ -50,7 +53,8 @@ export function forget(tabId) {
|
||||
export async function attach(tabId) {
|
||||
const t = state(tabId);
|
||||
clearTimeout(t.idle);
|
||||
t.idle = setTimeout(() => detach(tabId), IDLE_MS);
|
||||
t.idle = setTimeout(() => detach(tabId), BUSY_MS);
|
||||
t.busy = true;
|
||||
if (t.attached) return t;
|
||||
if (!t.attaching) {
|
||||
t.attaching = (async () => {
|
||||
@@ -66,13 +70,16 @@ export async function attach(tabId) {
|
||||
t.frameOf.clear();
|
||||
t.worlds.clear();
|
||||
if (!t.console) t.console = await devHost(tabId);
|
||||
// what Claude in Chrome turns on, and Network, which the page can't
|
||||
// see, for knowing when it is quiet. DOM and Accessibility stay off:
|
||||
// their calls work without them, and on they keep Blink's whole
|
||||
// accessibility tree live while the tab is attached.
|
||||
await Promise.all([
|
||||
send(tabId, "Page.enable"),
|
||||
...(t.console ? [send(tabId, "Runtime.enable")] : []),
|
||||
send(tabId, "Network.enable"),
|
||||
send(tabId, "DOM.enable"),
|
||||
send(tabId, "Accessibility.enable"),
|
||||
]);
|
||||
await send(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
|
||||
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
|
||||
@@ -113,9 +120,27 @@ function why(m) {
|
||||
return m;
|
||||
}
|
||||
|
||||
// release lets a tab a call used go IDLE_MS from now, unless typing goes
|
||||
// on in it. A tab no call used since is left on its clock.
|
||||
export function release(tabId) {
|
||||
const t = tabs.get(tabId);
|
||||
if (!t || !t.attached || !t.busy || t.typing) return;
|
||||
t.busy = false;
|
||||
clearTimeout(t.idle);
|
||||
t.idle = setTimeout(() => detach(tabId), IDLE_MS);
|
||||
}
|
||||
|
||||
// releaseAll is release for every attached tab, once no call is running
|
||||
export function releaseAll() {
|
||||
for (const id of tabs.keys()) release(id);
|
||||
}
|
||||
|
||||
export async function detach(tabId) {
|
||||
const t = tabs.get(tabId);
|
||||
if (!t || !t.attached) return;
|
||||
clearTimeout(t.idle);
|
||||
// the page's focus is its own again before the debugger goes
|
||||
await send(tabId, "Emulation.setFocusEmulationEnabled", { enabled: false }).catch(() => {});
|
||||
t.attached = false;
|
||||
try { await chrome.debugger.detach({ tabId }); } catch {}
|
||||
}
|
||||
@@ -133,8 +158,6 @@ async function child(t, sid) {
|
||||
await Promise.all([
|
||||
...(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),
|
||||
]).catch(() => {});
|
||||
await autoAttach(t.tabId, sid);
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ export async function move(t, x, y, opts = {}) {
|
||||
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,
|
||||
button: buttons ? "left" : "none", buttons, ...(buttons ? { force: 0.5 } : {}),
|
||||
});
|
||||
t.mouse = { x: px, y: py };
|
||||
await sleep(rand(7, 17));
|
||||
@@ -92,7 +92,7 @@ export async function click(t, x, y, opts = {}) {
|
||||
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 send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x, y, button, buttons: BUTTON_BIT[button], clickCount: i, modifiers, force: 0.5 });
|
||||
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));
|
||||
@@ -104,7 +104,7 @@ export async function click(t, x, y, opts = {}) {
|
||||
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 });
|
||||
await send(t.tabId, "Input.dispatchMouseEvent", { type: "mousePressed", x: p.x, y: p.y, button: "left", buttons: 1, clickCount: 1, force: 0.5 });
|
||||
try {
|
||||
await sleep(rand(90, 180));
|
||||
await move(t, q.x, q.y, { buttons: 1 });
|
||||
@@ -154,7 +154,7 @@ export function keyOf(ch) {
|
||||
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 });
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", { type: down ? "rawKeyDown" : "keyUp", key: "Shift", code: "ShiftLeft", location: 1, windowsVirtualKeyCode: 16, modifiers: down ? 8 : 0 });
|
||||
}
|
||||
|
||||
// the pause after a key: a typist is quicker inside a word than between
|
||||
@@ -167,19 +167,29 @@ function gap(ch, scale) {
|
||||
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;
|
||||
// how long typing may take in all. A person types a few characters a
|
||||
// second, and a site can time a message from its first key to its
|
||||
// sending, so a long text keeps a person's pace (browser_type goes on
|
||||
// after its call has answered) and is only quickened past four minutes.
|
||||
const TYPE_LONGEST_MS = 240000;
|
||||
|
||||
// how long typing text takes at a person's pace, about
|
||||
export const typingTime = (text) => [...String(text)].length * 165;
|
||||
|
||||
// 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 est = typingTime(text);
|
||||
const scale = est > TYPE_LONGEST_MS ? TYPE_LONGEST_MS / est : 1;
|
||||
const progress = opts.progress || {};
|
||||
progress.of = chars.length;
|
||||
progress.done = 0;
|
||||
const newline = opts.newline ?? "Shift+Enter";
|
||||
let held = false;
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
progress.done = i;
|
||||
const ch = chars[i];
|
||||
if (ch === "\r") continue;
|
||||
if (ch === "\n") {
|
||||
@@ -213,22 +223,23 @@ export async function type(t, text, opts = {}) {
|
||||
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 });
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyDown", key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode, text: ch, unmodifiedText: 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 });
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", key: k.key, code: k.code, windowsVirtualKeyCode: 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);
|
||||
progress.done = chars.length;
|
||||
}
|
||||
|
||||
// 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 });
|
||||
const ime = (type) => send(t.tabId, "Input.dispatchKeyEvent", { type, key: "Process", code: "", windowsVirtualKeyCode: 229 });
|
||||
let ok = true;
|
||||
for (let j = 1; j <= run.length && ok; j++) {
|
||||
await ime("rawKeyDown");
|
||||
|
||||
@@ -75,6 +75,8 @@ export async function press(t, combo) {
|
||||
for (const m of mods) if (!(m in MODS)) throw new Error(`"${m}" isn't a modifier: use Control, Alt, Shift or Meta`);
|
||||
let modifiers = mods.reduce((a, m) => a | MODS[m], 0);
|
||||
const k = describe(keyName, !!(modifiers & 8));
|
||||
// a modifier pressed alone is the left one, as on a keyboard
|
||||
if (/Left$/.test(k.code)) k.location = 1;
|
||||
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
|
||||
@@ -83,22 +85,22 @@ export async function press(t, combo) {
|
||||
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 send(t.tabId, "Input.dispatchKeyEvent", { type: "rawKeyDown", modifiers: held, key: m, code: KEYS[m].code, location: 1, windowsVirtualKeyCode: KEYS[m].keyCode });
|
||||
await hold(30, 80);
|
||||
}
|
||||
// a chord with Control, Alt or Meta types no text
|
||||
const typed = k.text && !(modifiers & 7);
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", {
|
||||
type: typed ? "keyDown" : "rawKeyDown", modifiers, key: k.key, code: k.code,
|
||||
windowsVirtualKeyCode: k.keyCode, nativeVirtualKeyCode: k.keyCode,
|
||||
type: typed ? "keyDown" : "rawKeyDown", modifiers, key: k.key, code: k.code, location: k.location || 0,
|
||||
windowsVirtualKeyCode: k.keyCode,
|
||||
...(typed ? { text: k.text, unmodifiedText: k.text } : {}),
|
||||
...(commands.length ? { commands } : {}),
|
||||
});
|
||||
await hold(50, 120);
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers, key: k.key, code: k.code, windowsVirtualKeyCode: k.keyCode });
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers, key: k.key, code: k.code, location: k.location || 0, 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 });
|
||||
await send(t.tabId, "Input.dispatchKeyEvent", { type: "keyUp", modifiers: held, key: m, code: KEYS[m].code, location: 1, windowsVirtualKeyCode: KEYS[m].keyCode });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Magpie Browser",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"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",
|
||||
|
||||
@@ -278,6 +278,10 @@ 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 "/focus":
|
||||
// a page that says in its title whether it thinks it has focus
|
||||
io.WriteString(w, `<!doctype html><title>Focus ?</title><h1>Focus</h1><script>setInterval(() => { document.title = "Focus " + (document.hasFocus() ? "on" : "off"); }, 200);</script>`)
|
||||
return
|
||||
case "/human":
|
||||
io.WriteString(w, humanFixture)
|
||||
return
|
||||
@@ -521,6 +525,55 @@ func TestBrowserLeavesTheUsersTabAlone(t *testing.T) {
|
||||
shown("after a recording")
|
||||
}
|
||||
|
||||
// A tab is let go about 20s after the last call in it ends, as Claude in
|
||||
// Chrome does: a page behind the user's never goes on for minutes with
|
||||
// its focus emulated (Discord took that for a bot).
|
||||
func TestBrowserLetsATabGoAfterItsCalls(t *testing.T) {
|
||||
if os.Getenv("MAGPIE_BROWSER_HEADFUL") == "" {
|
||||
t.Skip("headless, every tab has focus: MAGPIE_BROWSER_HEADFUL=1 runs it")
|
||||
}
|
||||
srv, site := realBrowser(t)
|
||||
_, ok := browserCaller(t, srv, "letgo")
|
||||
ok("browser_navigate", map[string]any{"url": site.URL + "/focus"}, "Focus")
|
||||
title := func() string {
|
||||
m := regexp.MustCompile(`(?m)^. t\d+ \[Magpie\] "(Focus [^"]*)"`).FindStringSubmatch(ok("browser_tabs", nil))
|
||||
if m == nil {
|
||||
t.Fatal("no Focus tab in the list")
|
||||
}
|
||||
return m[1]
|
||||
}
|
||||
// a timer behind the user's tab runs once a second
|
||||
until := func(want string, within time.Duration) (string, time.Duration) {
|
||||
start := time.Now()
|
||||
for {
|
||||
got := title()
|
||||
if got == want || time.Since(start) > within {
|
||||
return got, time.Since(start)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
if got, _ := until("Focus on", 5*time.Second); got != "Focus on" {
|
||||
t.Fatalf("while the agent works in it, the tab behind the user's has %q, not focus", got)
|
||||
}
|
||||
start := time.Now()
|
||||
for title() != "Focus off" {
|
||||
// tabs lists, and touches no tab: it doesn't hold this one
|
||||
if time.Since(start) > 45*time.Second {
|
||||
t.Fatalf("the tab still has emulated focus %s after the last call in it", time.Since(start).Round(time.Second))
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if d := time.Since(start); d < 15*time.Second {
|
||||
t.Fatalf("let go after %s, before the 20s a next call may come in", d.Round(time.Second))
|
||||
}
|
||||
// a call in it takes it again
|
||||
ok("browser_snapshot", nil, "Focus")
|
||||
if got, _ := until("Focus on", 5*time.Second); got != "Focus on" {
|
||||
t.Fatalf("a call after it was let go left %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An older extension, loaded from the folder magpie writes, has the folder
|
||||
// written with this magpie's when it connects, for the browser to read
|
||||
// when it starts again.
|
||||
@@ -581,7 +634,9 @@ const humanFixture = `<!doctype html>
|
||||
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);
|
||||
// a mouse button held down presses at 0.5, as a real mouse's does
|
||||
buy.addEventListener("pointerdown", (ev) => { seen.pressure = ev.pressure; });
|
||||
addEventListener("keydown", (ev) => { seen.keys.push([ev.key, performance.now(), ev.isTrusted]); if (ev.key === "Shift") { seen.shift++; if (seen.shiftAt === undefined || ev.location !== 1) seen.shiftAt = ev.location; } }, 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; } });
|
||||
@@ -633,6 +688,8 @@ func TestBrowserActsLikeAPerson(t *testing.T) {
|
||||
Composed []string
|
||||
Wheels int
|
||||
Sent string
|
||||
Pressure *float64
|
||||
ShiftAt *int
|
||||
}
|
||||
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 {
|
||||
@@ -646,6 +703,11 @@ func TestBrowserActsLikeAPerson(t *testing.T) {
|
||||
} 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.Pressure == nil {
|
||||
t.Errorf("no pressure seen on Buy's pointerdown")
|
||||
} else if *seen.Pressure != 0.5 {
|
||||
t.Errorf("the button went down at pressure %v: a mouse's is 0.5", *seen.Pressure)
|
||||
}
|
||||
if seen.MovesBeforeClick < 4 {
|
||||
t.Errorf("the mouse moved %d times before the click, not along a path", seen.MovesBeforeClick)
|
||||
}
|
||||
@@ -674,6 +736,11 @@ func TestBrowserActsLikeAPerson(t *testing.T) {
|
||||
if seen.Shift < 2 {
|
||||
t.Errorf("Shift was pressed %d times for H and W", seen.Shift)
|
||||
}
|
||||
if seen.ShiftAt == nil {
|
||||
t.Errorf("no Shift keydown seen")
|
||||
} else if *seen.ShiftAt != 1 {
|
||||
t.Errorf("Shift came from keyboard location %v, not the left Shift (1)", *seen.ShiftAt)
|
||||
}
|
||||
if strings.Join(seen.Composed, "") != "你好早上好" {
|
||||
t.Errorf("Chinese didn't come through an IME's composition: %q", seen.Composed)
|
||||
}
|
||||
@@ -714,3 +781,40 @@ func TestBrowserActsLikeAPerson(t *testing.T) {
|
||||
t.Fatalf("closing the user's tab: %+v", m.Result)
|
||||
}
|
||||
}
|
||||
|
||||
// A long text goes in at a person's pace, not squeezed into what one call
|
||||
// may wait: Discord can time a message from its first key to its sending,
|
||||
// and 800 characters typed in 35s is no person's. The call answers when
|
||||
// it has waited long enough, the typing goes on, and the tab's next call
|
||||
// waits for it (Enter included).
|
||||
func TestBrowserTypesALongTextAtAPersonsPace(t *testing.T) {
|
||||
srv, site := realBrowser(t)
|
||||
_, ok := browserCaller(t, srv, "typist")
|
||||
shop := strings.Replace(site.URL, "127.0.0.1", "shop.example", 1) + "/human"
|
||||
page := ok("browser_tabs", map[string]any{"action": "new", "url": shop}, "Shop")
|
||||
m := regexp.MustCompile(`- textbox "Chat" \[ref=(e\d+)\]`).FindStringSubmatch(page)
|
||||
if m == nil {
|
||||
t.Fatalf("no Chat box in:\n%s", page)
|
||||
}
|
||||
text := strings.TrimSpace(strings.Repeat("a long line of chat ", 16))
|
||||
start := time.Now()
|
||||
first := ok("browser_type", map[string]any{"ref": m[1], "text": text, "submit": true}, "characters so far", "then Enter", "the next call in this tab waits for it")
|
||||
if took := time.Since(start); took > 60*time.Second {
|
||||
t.Fatalf("browser_type answered after %v: past what a call may wait", took)
|
||||
}
|
||||
out := ok("browser_evaluate", map[string]any{"script": "() => ({sent: seen.sent, first: seen.keys[0][1], last: seen.keys[seen.keys.length - 1][1], n: seen.keys.length})"})
|
||||
var got struct {
|
||||
Sent string
|
||||
First, Last float64
|
||||
N int
|
||||
}
|
||||
if i := strings.Index(out, "{"); i < 0 || json.Unmarshal([]byte(out[i:strings.LastIndex(out, "}")+1]), &got) != nil {
|
||||
t.Fatalf("the page's record: %s", out)
|
||||
}
|
||||
if got.Sent != text {
|
||||
t.Fatalf("the chat box sent %q after %q, not the whole text", got.Sent, first)
|
||||
}
|
||||
if cps := float64(len(text)) / ((got.Last - got.First) / 1000); cps > 9 {
|
||||
t.Errorf("%d characters typed at %.1f a second: no person's pace", len(text), cps)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user