browser: the user's tab is never put behind, not even for a moment

The owner (11-03, again 11-04: "你到底彻底修复了没啊"): Magpie Browser
disturbs the user's browsing. v0.1.2864 moved agents into tabs of their
own, behind the user's, in a Magpie tab group, but two paths still took
the user's tab from under them:

- A screenshot that took over 8s brought the agent's tab forward for
  ~300ms and gave the user's back. With a recording on (v0.1.2865) every
  action takes one. Measured on mote, headful Chrome for Testing 1234:
  Chrome draws a background tab for Page.captureScreenshot (first ~5s,
  then 50-250ms), so the tab is never brought forward now; after 20s
  the call fails SCREENSHOT_FAILED instead.
- A link with target=_blank, clicked in the agent's background tab,
  opened its new tab in front, and the user's tab came back only after
  the new page settled (up to ~2.5s). Now such a link is clicked with
  Cmd (Ctrl off macOS) held, as a person opens one in the background,
  and a tab that still comes up in front (window.open, Enter on a link)
  is given back the moment it is created.

Extension 0.1.5.

Test: TestBrowserLeavesTheUsersTabAlone starts Chrome on a user page the
extension never attaches to (attaching turns on focus emulation, which
keeps a page "visible"); its title counts every visibilitychange to
hidden. Headless Chrome keeps every tab visible, so the moment-long case
is caught only with MAGPIE_BROWSER_HEADFUL=1 (a window on the screen);
the test says so in its log when headless.

Run on mote at this tree:
- gofmt clean; GOOS=darwin/linux/windows go vet ./internal/gateway clean
- go test ./internal/gateway -count=1 -timeout 45m: ok (1114s)
- MAGPIE_BROWSER_HEADFUL=1 go test ./internal/gateway -run TestBrowser:
  all 20 pass; TestBrowserLeavesTheUsersTabAlone -count=3 headful ok
Broken by hand, headful: the old screenshot dance fails "after a
screenshot ... Watch 1"; the click without Cmd fails "after a link
opened a tab ... Watch 1"; the fix before the Cmd click (restore on
create only) still failed at the link, which is why the Cmd click is in.
Headless, both breaks pass: that is the limit named above.

Not tried: Edge, Arc, Windows and Linux Chrome; a real site's
window.open popup (it is given back at once, a flash remains).
This commit is contained in:
yetone
2026-11-04 22:53:36 +08:00
parent d6e3a36ffc
commit e928b57f0e
3 changed files with 66 additions and 28 deletions
+30 -16
View File
@@ -224,6 +224,7 @@ const AFTER = {
SITE_REFUSED: "The site turned the browser away. Don't try again at once: tell the user, who may need to sign in or wait.",
LOAD_FAILED: "The address didn't load: check it, or the user's connection.",
PAGE_BLOCKED: "Nothing works in this tab until that changes: use another tab.",
SCREENSHOT_FAILED: "Go on without the picture: take a snapshot to read the page.",
OUTCOME_UNKNOWN: "It may or may not have happened: take a snapshot to see before doing it again, since a form or a purchase could go twice.",
};
const GONE = /Execution context was destroyed|Cannot find context|Inspected target navigated or closed|Target closed|No node with given id|Could not find node|Node with given id does not belong/i;
@@ -313,7 +314,13 @@ async function act(t, what, fn, el = null, press = false) {
const was = press ? await look(t, el) : null;
t.sentInput = false;
let opened = null;
const onCreated = (tab) => { if (!before.has(tab.id) && (tab.openerTabId === t.tabId || (behind && tab.openerTabId === behind.id) || !opened)) opened = tab; };
// a tab the link opens comes up in front of the user's: their tab is
// given back at once, not after the new page has loaded
const onCreated = (tab) => {
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(() => {});
};
chrome.tabs.onCreated.addListener(onCreated);
let said;
try {
@@ -453,6 +460,15 @@ async function mouse(t, x, y, opts = {}) {
}
}
// opensATab is whether el is, or is in, a link that opens in a new tab
async function opensATab(t, el) {
return await call(t, el, `function () {
const a = this.closest && this.closest("a[href], area[href]");
const to = a && (a.getAttribute("target") || (document.querySelector("base[target]") || {}).target || "").toLowerCase();
return !!to && !["_self", "_parent", "_top"].includes(to) && !/^(javascript|mailto|tel):/i.test(a.getAttribute("href"));
}`).catch(() => false);
}
async function call(t, el, fn, args = []) {
const r = await send(t.tabId, "Runtime.callFunctionOn", {
objectId: el.objectId, functionDeclaration: fn, arguments: args.map((value) => ({ value })),
@@ -550,9 +566,16 @@ const TOOLS = {
need(args, "ref");
const t = await ready(session, args);
const el = await find(t, args.ref);
let how = args;
if (!args.button && !args.double && !(args.modifiers || []).length && await opensATab(t, el) && !(await chrome.tabs.get(t.tabId)).active) {
// a link that opens a tab, clicked in a tab behind the user's: with
// Cmd (Ctrl) held, as a person opens one in the background, so the
// new tab never comes up in front of the user's for a moment
how = { ...args, modifiers: [/Mac/.test(navigator.userAgent) ? "Meta" : "Control"] };
}
return act(t, `Clicked ${el.ref} (${el.role} "${el.name}").`, async () => {
const p = await point(t, el);
await mouse(t, p.x, p.y, args);
await mouse(t, p.x, p.y, how);
}, el, PRESSES.has(el.role) && !args.button && !args.double);
},
@@ -768,20 +791,11 @@ const TOOLS = {
params.captureBeyondViewport = true;
}
const shot = () => send(t.tabId, "Page.captureScreenshot", params);
let r = await Promise.race([shot(), sleep(8000).then(() => null)]);
if (!r) {
// a tab in the background isn't drawn: show it for the picture,
// then give the window back the tab the user had in front
const tab = await chrome.tabs.get(t.tabId);
const [shown] = await chrome.tabs.query({ active: true, windowId: tab.windowId });
await chrome.tabs.update(t.tabId, { active: true });
try {
await sleep(300);
r = await shot();
} finally {
if (shown && shown.id !== t.tabId) await chrome.tabs.update(shown.id, { active: true }).catch(() => {});
}
}
// Chrome draws a tab behind the user's for the picture (the first one
// can take a few seconds); the tab is never brought forward for it,
// which took the user's tab from under them for a moment each time
const r = await Promise.race([shot(), sleep(20000).then(() => null)]);
if (!r) throw fault("SCREENSHOT_FAILED", "the tab, behind the one the user is looking at, wasn't drawn in 20s; it is left behind rather than brought in front of the user");
return { content: [{ type: "image", data: r.data, mimeType: args.png ? "image/png" : "image/jpeg" }, text(await head(t))] };
},
+1 -1
View File
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Magpie Browser",
"version": "0.1.4",
"version": "0.1.5",
"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",
+35 -11
View File
@@ -272,6 +272,11 @@ func realBrowserFrom(t *testing.T, ext func(*httptest.Server) string) (srv, site
case "/frames":
io.WriteString(w, strings.Replace(framesFixture, "SRC", html.EscapeString(r.URL.Query().Get("src")), 1))
return
case "/watch":
// the user's own page: its title counts the times it was put
// 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 "/refused":
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, "<!doctype html><title>Denied</title><h1>Access denied</h1>")
@@ -283,13 +288,21 @@ func realBrowserFrom(t *testing.T, ext func(*httptest.Server) string) (srv, site
dir := ext(srv)
profile := t.TempDir()
cmd := exec.Command(chrome, "--headless=new", "--user-data-dir="+profile,
head := "--headless=new"
if os.Getenv("MAGPIE_BROWSER_HEADFUL") != "" {
// a window on the screen: only then does Chrome put a tab behind
// another one out of sight (headless, every tab is visible)
head = "--window-size=1000,700"
}
cmd := exec.Command(chrome, head, "--user-data-dir="+profile,
"--disable-extensions-except="+dir, "--load-extension="+dir,
"--no-first-run", "--no-default-browser-check", "--disable-gpu", "--remote-debugging-port=0",
// with the test's own HOME there is no keychain (macOS) or keyring
// (Linux), and Chrome waits on it before the extension's storage
// answers
"--use-mock-keychain", "--password-store=basic", "about:blank")
"--use-mock-keychain", "--password-store=basic",
// the user's own page, which the extension never attaches to
site.URL+"/watch")
var logs bytes.Buffer
cmd.Stdout, cmd.Stderr = &logs, &logs
if err := cmd.Start(); err != nil {
@@ -445,24 +458,32 @@ func TestBrowserToolActionsInARealBrowser(t *testing.T) {
}
// Agents leave the user's tab alone (the owner, 11-03: Magpie Browser
// "老是会代替掉用户正在浏览的网页"): a call that names no tab works in a
// new one, behind the tab the user is looking at, in the session's Magpie
// group; a link that opens a tab, and tab_new, open behind it too, and a
// screenshot gives the window its shown tab back.
// "老是会代替掉用户正在浏览的网页"; 11-04: "你到底彻底修复了没啊"): a call
// that names no tab works in a new one, behind the tab the user is looking
// at, in the session's Magpie group; a link that opens a tab, tab_new,
// screenshots and a recording all happen behind it too. The user's page
// counts each time it is put behind another tab, so a tab brought forward
// for a moment and given back fails as well as one left in front.
func TestBrowserLeavesTheUsersTabAlone(t *testing.T) {
srv, site := realBrowser(t)
call, ok := browserCaller(t, srv, "quiet")
users := regexp.MustCompile(`(?m)^\+ (t\d+) .*about:blank$`).FindStringSubmatch(ok("browser_tabs", nil))
users := regexp.MustCompile(`(?m)^\+ (t\d+) "Watch 0" .*/watch$`).FindStringSubmatch(ok("browser_tabs", nil))
if users == nil {
t.Fatal("no shown about:blank tab to start with")
t.Fatal("no shown user's page to start with")
}
shown := func(when string) {
t.Helper()
list := ok("browser_tabs", nil)
if !regexp.MustCompile(`(?m)^\+ ` + users[1] + ` .*about:blank$`).MatchString(list) {
t.Fatalf("%s, the user's tab %s isn't shown and unchanged:\n%s", when, users[1], list)
if !regexp.MustCompile(`(?m)^\+ ` + users[1] + ` "Watch 0" .*/watch$`).MatchString(list) {
t.Fatalf("%s, the user's tab %s isn't shown, unchanged and never put behind (Watch N counts the times):\n%s", when, users[1], list)
}
}
shown("to start with")
if os.Getenv("MAGPIE_BROWSER_HEADFUL") == "" {
// headless, every tab is visible, so a tab brought forward for a
// moment and given back can't be told
t.Log("headless: only where the user's tab ends up is checked; MAGPIE_BROWSER_HEADFUL=1 catches a tab brought forward for a moment too")
}
page := ok("browser_navigate", map[string]any{"url": site.URL}, "Magpie fixture")
if strings.Contains(page, users[1]+":") {
t.Fatalf("navigated the user's tab:\n%s", page)
@@ -486,8 +507,11 @@ func TestBrowserLeavesTheUsersTabAlone(t *testing.T) {
t.Fatalf("screenshot: %+v", m.Result.Content)
}
shown("after a screenshot")
ok("browser", map[string]any{"action": "record_start"}, "Recording")
ok("browser", map[string]any{"action": "tab_new", "url": site.URL}, "Opened t")
shown("after the one tool's tab_new")
ok("browser", map[string]any{"action": "navigate", "url": site.URL + "/two", "screenshot": true}, "Page two")
ok("browser", map[string]any{"action": "record_stop"}, "Recorded 2 frames")
shown("after a recording")
}
// An older extension, loaded from the folder magpie writes, has the folder