diff --git a/internal/browserext/ext/background.js b/internal/browserext/ext/background.js index 95032ee07..61e15c82a 100644 --- a/internal/browserext/ext/background.js +++ b/internal/browserext/ext/background.js @@ -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, release, releaseAll, send, settle, sleep, state, waitLoad, watch, watchConsole } from "./cdp.js"; +import { attach, fault, forget, hold, 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"; @@ -318,6 +318,16 @@ const TYPE_WAIT_MS = 40000; // how long a call waits for typing still going on in its tab const TYPING_WAIT_MS = 60000; +// stopped answers a call in a tab the user stopped Magpie Browser in +// (Cancel on Chrome's bar) with that, once, before anything attaches to it +// again +function stopped(t) { + if (!t.stoppedByUser) return; + t.stoppedByUser = false; + t.typingFailed = null; + 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."); +} + async function ready(session, args) { const tabId = await tabFor(session, args); const t = state(tabId); @@ -325,15 +335,12 @@ async function ready(session, args) { 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`); } + stopped(t); 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); return t; @@ -705,8 +712,10 @@ const TOOLS = { } 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); + // the debugger stays on the tab for as long as the typing lasts, + // but is never put back on it: a user who pressed Cancel on + // Chrome's bar stopped this typing too + const keep = setInterval(() => hold(t.tabId), 10000); try { await typeIn(); } finally { @@ -961,6 +970,7 @@ const TOOLS = { async browser_dialog(session, args) { const tabId = await tabFor(session, args); const t = state(tabId); + stopped(t); await attach(tabId); const accept = args.accept !== false; if (t.dialog) { diff --git a/internal/browserext/ext/cdp.js b/internal/browserext/ext/cdp.js index a94a9c1be..e8da2612a 100644 --- a/internal/browserext/ext/cdp.js +++ b/internal/browserext/ext/cdp.js @@ -120,6 +120,19 @@ function why(m) { return m; } +// hold keeps a tab's attachment on while typing that outlived its call +// goes on: it puts off the let-go and never attaches again. A tab that +// was let go, or that the user stopped (Cancel on Chrome's bar), stays +// so: the typing's next key then fails and the typing ends. +export function hold(tabId) { + const t = tabs.get(tabId); + if (!t || !t.attached || t.stoppedByUser || t.attaching) return false; + clearTimeout(t.idle); + t.idle = setTimeout(() => detach(tabId), BUSY_MS); + t.busy = true; + return true; +} + // 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) { diff --git a/internal/browserext/ext/human.js b/internal/browserext/ext/human.js index 97b59091c..1d2bffed7 100644 --- a/internal/browserext/ext/human.js +++ b/internal/browserext/ext/human.js @@ -190,6 +190,8 @@ export async function type(t, text, opts = {}) { let held = false; for (let i = 0; i < chars.length; i++) { progress.done = i; + // the user pressed Cancel on Chrome's bar: not one key more + if (t.stoppedByUser) throw new Error("the user stopped Magpie Browser in this tab (Cancel on Chrome's bar)"); const ch = chars[i]; if (ch === "\r") continue; if (ch === "\n") { diff --git a/internal/browserext/ext/manifest.json b/internal/browserext/ext/manifest.json index 29e84e98d..a4e7877bb 100644 --- a/internal/browserext/ext/manifest.json +++ b/internal/browserext/ext/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "Magpie Browser", - "version": "0.1.8", + "version": "0.1.9", "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", diff --git a/internal/browserext/stop_test.go b/internal/browserext/stop_test.go new file mode 100644 index 000000000..4309abb9f --- /dev/null +++ b/internal/browserext/stop_test.go @@ -0,0 +1,87 @@ +package browserext + +import ( + "context" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// A user who presses Cancel on Chrome's "is debugging this browser" bar +// while browser_type's typing goes on after its call has stopped that +// typing too: the timer that keeps the tab attached for the typing never +// attaches the debugger again, and not one key more goes into the page. +func TestCancelStopsTypingThatOutlivedItsCall(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("no node on PATH") + } + dir, err := filepath.Abs("ext") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + out, err := exec.CommandContext(ctx, node, "--input-type=module", "-e", cancelStopsTypingJS, dir).CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } +} + +const cancelStopsTypingJS = ` +import { pathToFileURL } from "node:url"; +import path from "node:path"; +const dir = process.argv[1]; +const attached = new Set(); +let attaches = 0, onDetach; +const keys = []; +globalThis.chrome = { + debugger: { + attach: async ({ tabId }) => { attaches++; attached.add(tabId); }, + detach: async ({ tabId }) => { attached.delete(tabId); }, + sendCommand: async (to, method, params) => { + if (!attached.has(to.tabId)) throw new Error("Debugger is not attached to the tab with id: " + to.tabId + "."); + if (method === "Input.dispatchKeyEvent" && params.text) keys.push(params.text); + return {}; + }, + onEvent: { addListener() {} }, + onDetach: { addListener(f) { onDetach = f; } }, + }, + tabs: { get: async () => ({ url: "https://example.com/" }) }, +}; +const cdp = await import(pathToFileURL(path.join(dir, "cdp.js")).href); +const human = await import(pathToFileURL(path.join(dir, "human.js")).href); +const fail = (m) => { console.error(m); process.exit(1); }; +const wait = async (ok) => { for (let i = 0; i < 400 && !ok(); i++) await new Promise((r) => setTimeout(r, 25)); if (!ok()) fail("timed out"); }; + +// typing still going on holds its tab +await cdp.attach(1); +const t = cdp.state(1); +const typing = human.type(t, "a line typed at a person's pace", {}).then(() => "finished", (e) => String(e.message || e)); +await wait(() => keys.length >= 4); +if (!cdp.hold(1)) fail("hold let go of a tab typing goes on in"); + +// the user presses Cancel: Chrome detaches and says why +attached.delete(1); +onDetach({ tabId: 1 }, "canceled_by_user"); +const at = keys.length; +if (cdp.hold(1)) fail("hold went on after the user's Cancel"); +if (attaches !== 1 || attached.has(1)) fail("the debugger was attached again after the user's Cancel: " + attaches + " attaches"); +const end = await typing; +if (end === "finished") fail("the typing finished after the user's Cancel"); +if (keys.length !== at) fail((keys.length - at) + " keys went in after the user's Cancel"); + +// a typing that sees the stop first sends nothing more, even attached +t.stoppedByUser = false; +await cdp.attach(1); +const second = human.type(t, "another line typed here", {}).then(() => "finished", (e) => String(e.message || e)); +await wait(() => keys.length >= at + 3); +t.stoppedByUser = true; +await new Promise((r) => setTimeout(r, 400)); +const n = keys.length; +const end2 = await second; +if (end2 === "finished" || !/stopped/.test(end2)) fail("the typing went on with the stop set: " + end2); +if (keys.length !== n) fail("keys went in with the stop set"); +process.exit(0); +`