diff --git a/internal/browserext/ext/background.js b/internal/browserext/ext/background.js index 73bf9763c..a37923ad4 100644 --- a/internal/browserext/ext/background.js +++ b/internal/browserext/ext/background.js @@ -100,20 +100,32 @@ connect(); // ---- sessions: each agent's tab ------------------------------------------ +// Each agent session (gateway.BrowserSessionHeader: one `magpie mcp +// browser`, or one caller of magpie's MCP router) works in a tab of its +// own and opens its tabs in a tab group of its own, so two agents at once +// never act in one tab unless one picks the other's by its id. const sessions = new Map(); // session → tabId +const groups = new Map(); // session → tab group id let loaded = false; async function loadSessions() { if (loaded) return; loaded = true; try { - const { sessions: s } = await chrome.storage.session.get("sessions"); + const { sessions: s, groups: g } = await chrome.storage.session.get(["sessions", "groups"]); for (const [k, v] of Object.entries(s || {})) sessions.set(k, v); + for (const [k, v] of Object.entries(g || {})) groups.set(k, v); } catch {} } function saveSessions() { - chrome.storage.session.set({ sessions: Object.fromEntries(sessions) }).catch(() => {}); + chrome.storage.session.set({ sessions: Object.fromEntries(sessions), groups: Object.fromEntries(groups) }).catch(() => {}); +} + +// heldByOther is whether another session works in tabId +function heldByOther(session, tabId) { + for (const [k, v] of sessions) if (k !== session && v === tabId) return true; + return false; } chrome.tabs.onRemoved.addListener((tabId) => { @@ -147,18 +159,47 @@ async function tabFor(session, args) { } const [active] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); if (!active) throw new Error("no browser window is open: open one, or call browser_tabs with action new"); + if (heldByOther(session, active.id)) { + // another agent works in the tab the user is looking at: this one is + // given a tab of its own, behind it, in its own group + const tab = await chrome.tabs.create({ url: "about:blank", active: false, windowId: active.windowId }); + await group(session, tab.id, tab.windowId); + sessions.set(session, tab.id); + saveSessions(); + return tab.id; + } sessions.set(session, active.id); saveSessions(); return active.id; } -// the tab group agents' tabs are opened in, one per window -async function group(tabId, windowId) { +// group puts a tab the session opened in the session's tab group in that +// window: "Magpie" for the first session, "Magpie 2", "Magpie 3" for the +// ones working beside it. A group no live session has (one an earlier run +// left) is taken over by its title. +async function group(session, tabId, windowId) { try { - const [g] = await chrome.tabGroups.query({ windowId, title: "Magpie" }); - if (g) return await chrome.tabs.group({ tabIds: [tabId], groupId: g.id }); - const id = await chrome.tabs.group({ tabIds: [tabId], createProperties: { windowId } }); - await chrome.tabGroups.update(id, { title: "Magpie", color: "grey" }); + const had = groups.get(session); + if (had !== undefined) { + const g = await chrome.tabGroups.get(had).catch(() => null); + if (g && g.windowId === windowId) return await chrome.tabs.group({ tabIds: [tabId], groupId: g.id }); + } + const others = new Set([...groups].filter(([k]) => k !== session).map(([, v]) => v)); + const inWindow = await chrome.tabGroups.query({ windowId }); + for (let n = 1; ; n++) { + const title = n === 1 ? "Magpie" : `Magpie ${n}`; + const g = inWindow.find((x) => x.title === title); + if (g && others.has(g.id)) continue; + let id; + if (g) id = await chrome.tabs.group({ tabIds: [tabId], groupId: g.id }); + else { + id = await chrome.tabs.group({ tabIds: [tabId], createProperties: { windowId } }); + await chrome.tabGroups.update(id, { title, color: "grey" }); + } + groups.set(session, id); + saveSessions(); + return; + } } catch {} } @@ -184,6 +225,7 @@ async function ready(session, args) { t.stoppedByUser = false; throw new Error("the user stopped Magpie Browser in this tab (Cancel on Chrome's bar): ask them before going on. The next call attaches to it again."); } + 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; @@ -237,8 +279,7 @@ async function act(t, what, fn) { if (t.dialog) return { content: [text(out.join("\n"))] }; if (opened && opened.openerTabId === t.tabId) { // a link that opens a new tab: the agent goes on in it - const s = [...sessions].find(([, v]) => v === t.tabId); - if (s) { sessions.set(s[0], opened.id); saveSessions(); } + if (t.by) { sessions.set(t.by, opened.id); saveSessions(); } const nt = state(opened.id); await attach(opened.id); await waitLoad(nt, 15000); @@ -337,7 +378,7 @@ const TOOLS = { if (action === "new") { const [w] = await chrome.windows.getAll({ windowTypes: ["normal"] }).then((ws) => ws.filter((x) => x.focused).concat(ws)); const tab = await chrome.tabs.create({ url: args.url ? withScheme(args.url) : "about:blank", active: args.background ? false : true, ...(w ? { windowId: w.id } : {}) }); - await group(tab.id, tab.windowId); + await group(session, tab.id, tab.windowId); sessions.set(session, tab.id); saveSessions(); const t = state(tab.id); @@ -358,8 +399,9 @@ const TOOLS = { } const all = await chrome.tabs.query({}); const mine = sessions.get(session); - const lines = all.map((x) => `${x.id === mine ? "*" : x.active ? "+" : " "} t${x.id} ${x.title ? JSON.stringify(x.title.slice(0, 100)) : ""} ${x.url ? x.url.slice(0, 200) : ""}`); - return { content: [text(`${all.length} tabs (* is the one calls go to, + a window's shown tab):\n` + lines.join("\n"))] }; + const titles = new Map((await chrome.tabGroups.query({}).catch(() => [])).map((g) => [g.id, g.title])); + const lines = all.map((x) => `${x.id === mine ? "*" : heldByOther(session, x.id) ? "~" : x.active ? "+" : " "} t${x.id}${titles.get(x.groupId) ? ` [${titles.get(x.groupId)}]` : ""} ${x.title ? JSON.stringify(x.title.slice(0, 100)) : ""} ${x.url ? x.url.slice(0, 200) : ""}`); + return { content: [text(`${all.length} tabs (* is the one calls go to, ~ one another agent works in: leave it to them, + a window's shown tab):\n` + lines.join("\n"))] }; }, async browser_navigate(session, args) { diff --git a/internal/browserext/ext/manifest.json b/internal/browserext/ext/manifest.json index b4f151a3a..c9222a5e3 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.0", + "version": "0.1.1", "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/ext/popup.js b/internal/browserext/ext/popup.js index ad1bb4b30..ddf6d7f9c 100644 --- a/internal/browserext/ext/popup.js +++ b/internal/browserext/ext/popup.js @@ -2,8 +2,8 @@ import { GATEWAY } from "./config.js"; const zh = /^zh/i.test(navigator.language); const say = zh - ? { on: "已连接 Magpie", off: "未连接 Magpie", onHint: "通过 Magpie 运行的智能体可以使用这个浏览器里的标签页。它们打开的标签页放在 “Magpie” 分组里。", offHint: "请确认 Magpie 正在运行。扩展会自动重连。" } - : { on: "Connected to Magpie", off: "Not connected to Magpie", onHint: "Agents you run through Magpie can use this browser's tabs. Tabs they open go in the \"Magpie\" group.", offHint: "Check that Magpie is running. The extension reconnects by itself." }; + ? { on: "已连接 Magpie", off: "未连接 Magpie", onHint: "通过 Magpie 运行的智能体可以使用这个浏览器里的标签页。它们打开的标签页放在各自的 “Magpie” 分组里。", offHint: "请确认 Magpie 正在运行。扩展会自动重连。" } + : { on: "Connected to Magpie", off: "Not connected to Magpie", onHint: "Agents you run through Magpie can use this browser's tabs. Each puts the tabs it opens in a \"Magpie\" group of its own.", offHint: "Check that Magpie is running. The extension reconnects by itself." }; async function show() { const { status } = await chrome.storage.session.get("status"); diff --git a/internal/gateway/browser_e2e_test.go b/internal/gateway/browser_e2e_test.go index 0986b5945..c09892c70 100644 --- a/internal/gateway/browser_e2e_test.go +++ b/internal/gateway/browser_e2e_test.go @@ -49,100 +49,8 @@ const browserFixture = ` // Chromium that takes --load-extension (Chrome for Testing, as Playwright // has it) to run it. func TestBrowserToolsInARealBrowser(t *testing.T) { - chrome := os.Getenv("MAGPIE_BROWSER_CHROME") - if chrome == "" { - t.Skip("MAGPIE_BROWSER_CHROME names no Chromium") - } - fresh(t) - s := New() - srv := httptest.NewServer(lanGuard(s.Handler())) - t.Cleanup(srv.Close) - site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - if r.URL.Path == "/two" { - io.WriteString(w, "Two

Page two

") - return - } - io.WriteString(w, browserFixture) - })) - t.Cleanup(site.Close) - - ext := t.TempDir() - if err := browserext.Write(ext, srv.URL); err != nil { - t.Fatal(err) - } - profile := t.TempDir() - cmd := exec.Command(chrome, "--headless=new", "--user-data-dir="+profile, - "--disable-extensions-except="+ext, "--load-extension="+ext, - "--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") - var logs bytes.Buffer - cmd.Stdout, cmd.Stderr = &logs, &logs - if err := cmd.Start(); err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - defer cmd.Wait() - defer cmd.Process.Kill() - if t.Failed() { - t.Logf("chromium said:\n%s", logs.String()) - // what it runs: is the extension's worker among them - if port, err := os.ReadFile(filepath.Join(profile, "DevToolsActivePort")); err == nil { - if resp, err := http.Get("http://127.0.0.1:" + strings.SplitN(string(port), "\n", 2)[0] + "/json/list"); err == nil { - b, _ := io.ReadAll(resp.Body) - resp.Body.Close() - t.Logf("its targets: %s", b) - } - } - } - }) - for deadline := time.Now().Add(60 * time.Second); s.browser.current() == nil; { - if time.Now().After(deadline) { - t.Fatal("the extension never connected") - } - time.Sleep(50 * time.Millisecond) - } - - call := func(tool string, args map[string]any) imageReply { - t.Helper() - req, _ := http.NewRequest(http.MethodPost, srv.URL+BrowserMCPPath, strings.NewReader(imageToolCall(tool, args))) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json, text/event-stream") - req.Header.Set(BrowserSessionHeader, "e2e") - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatal(err) - } - b, _ := io.ReadAll(resp.Body) - resp.Body.Close() - var m imageReply - if resp.StatusCode != 200 || json.Unmarshal(b, &m) != nil || m.Error != nil || len(m.Result.Content) == 0 { - t.Fatalf("%s: %d %s", tool, resp.StatusCode, b) - } - return m - } - // ok calls a tool that should work and answers with its text - ok := func(tool string, args map[string]any, want ...string) string { - t.Helper() - m := call(tool, args) - var said []string - for _, c := range m.Result.Content { - said = append(said, c.Text) - } - out := strings.Join(said, "\n") - if m.Result.IsError { - t.Fatalf("%s %v failed: %s", tool, args, out) - } - for _, w := range want { - if !strings.Contains(out, w) { - t.Fatalf("%s %v doesn't say %q:\n%s", tool, args, w, out) - } - } - return out - } + srv, site := realBrowser(t) + call, ok := browserCaller(t, srv, "e2e") ref := func(page, role, name string) string { t.Helper() m := regexp.MustCompile(`- ` + role + ` "` + regexp.QuoteMeta(name) + `"(?: \[[a-z=, ]+\])? \[ref=(e\d+)\]`).FindStringSubmatch(page) @@ -221,3 +129,165 @@ func TestBrowserToolsInARealBrowser(t *testing.T) { t.Fatalf("a closed tab still answers: %+v", m.Result) } } + +// realBrowser starts a Chromium with the extension magpie writes loaded +// in a profile of its own, pointed at a gateway of the test's, and waits +// for it to connect; site serves browserFixture (and /two). +func realBrowser(t *testing.T) (srv, site *httptest.Server) { + t.Helper() + chrome := os.Getenv("MAGPIE_BROWSER_CHROME") + if chrome == "" { + t.Skip("MAGPIE_BROWSER_CHROME names no Chromium") + } + fresh(t) + + s := New() + srv = httptest.NewServer(lanGuard(s.Handler())) + t.Cleanup(srv.Close) + site = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if r.URL.Path == "/two" { + io.WriteString(w, "Two

Page two

") + return + } + io.WriteString(w, browserFixture) + })) + t.Cleanup(site.Close) + + ext := t.TempDir() + if err := browserext.Write(ext, srv.URL); err != nil { + t.Fatal(err) + } + profile := t.TempDir() + cmd := exec.Command(chrome, "--headless=new", "--user-data-dir="+profile, + "--disable-extensions-except="+ext, "--load-extension="+ext, + "--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") + var logs bytes.Buffer + cmd.Stdout, cmd.Stderr = &logs, &logs + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + defer cmd.Wait() + defer cmd.Process.Kill() + if t.Failed() { + t.Logf("chromium said:\n%s", logs.String()) + // what it runs: is the extension's worker among them + if port, err := os.ReadFile(filepath.Join(profile, "DevToolsActivePort")); err == nil { + if resp, err := http.Get("http://127.0.0.1:" + strings.SplitN(string(port), "\n", 2)[0] + "/json/list"); err == nil { + b, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Logf("its targets: %s", b) + } + } + } + }) + for deadline := time.Now().Add(60 * time.Second); s.browser.current() == nil; { + if time.Now().After(deadline) { + t.Fatal("the extension never connected") + } + time.Sleep(50 * time.Millisecond) + } + return srv, site +} + +// browserCaller calls the browser's tools as the agent session session: +// call answers with the reply, ok with the text of one that should work. +func browserCaller(t *testing.T, srv *httptest.Server, session string) (call func(string, map[string]any) imageReply, ok func(string, map[string]any, ...string) string) { + call = func(tool string, args map[string]any) imageReply { + t.Helper() + req, _ := http.NewRequest(http.MethodPost, srv.URL+BrowserMCPPath, strings.NewReader(imageToolCall(tool, args))) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set(BrowserSessionHeader, session) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(resp.Body) + resp.Body.Close() + var m imageReply + if resp.StatusCode != 200 || json.Unmarshal(b, &m) != nil || m.Error != nil || len(m.Result.Content) == 0 { + t.Fatalf("%s: %d %s", tool, resp.StatusCode, b) + } + return m + } + // ok calls a tool that should work and answers with its text + ok = func(tool string, args map[string]any, want ...string) string { + t.Helper() + m := call(tool, args) + var said []string + for _, c := range m.Result.Content { + said = append(said, c.Text) + } + out := strings.Join(said, "\n") + if m.Result.IsError { + t.Fatalf("%s %v failed: %s", tool, args, out) + } + for _, w := range want { + if !strings.Contains(out, w) { + t.Fatalf("%s %v doesn't say %q:\n%s", tool, args, w, out) + } + } + return out + } + return call, ok +} + +// Two agent sessions at once in a real Chromium (packinggoodsllc_07668 on +// Discord: two agents behind one router took one tab): the first works in +// the tab the user is looking at, the second, finding that tab another's, +// in a new tab of its own; each opens its tabs in a group of its own +// ("Magpie", "Magpie 2"), and each sees the other's tab marked ~. +func TestBrowserSessionsApartInARealBrowser(t *testing.T) { + srv, site := realBrowser(t) + _, a := browserCaller(t, srv, "agent-a") + _, b := browserCaller(t, srv, "agent-b") + tabOf := func(page string) string { + t.Helper() + m := regexp.MustCompile(`Tab (t\d+):`).FindStringSubmatch(page) + if m == nil { + t.Fatalf("no tab in:\n%s", page) + } + return m[1] + } + ta := tabOf(a("browser_navigate", map[string]any{"url": site.URL}, "Magpie fixture")) + tb := tabOf(b("browser_navigate", map[string]any{"url": site.URL + "/two"}, "Page two")) + if ta == tb { + t.Fatalf("both sessions work in %s", ta) + } + if got := tabOf(a("browser_snapshot", nil)); got != ta { + t.Fatalf("a went from %s to %s", ta, got) + } + a("browser_evaluate", map[string]any{"script": "document.title"}, "Fixture") + b("browser_evaluate", map[string]any{"script": "document.title"}, "Two") + if list := a("browser_tabs", nil); !regexp.MustCompile(`(?m)^\* `+ta+` `).MatchString(list) || !regexp.MustCompile(`(?m)^~ `+tb+` `).MatchString(list) { + t.Fatalf("a's list doesn't mark its tab %s * and b's %s ~:\n%s", ta, tb, list) + } + + // a tab each opens goes in its own group, and calls go on in it + a("browser_tabs", map[string]any{"action": "new", "url": site.URL}) + b("browser_tabs", map[string]any{"action": "new", "url": site.URL + "/two"}) + // the group of the tab a list marks mark with the page title + groupOf := func(list, mark, title string) string { + t.Helper() + m := regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(mark) + ` t\d+ \[(Magpie(?: \d+)?)\] "` + title + `"`).FindStringSubmatch(list) + if m == nil { + t.Fatalf("no %s tab %q in a Magpie group:\n%s", mark, title, list) + } + return m[1] + } + list := a("browser_tabs", nil) + ga, gb := groupOf(list, "*", "Fixture"), groupOf(list, "~", "Two") + if ga == gb { + t.Fatalf("both sessions' tabs are in %s:\n%s", ga, list) + } + list = b("browser_tabs", nil) + if groupOf(list, "*", "Two") != gb || groupOf(list, "~", "Fixture") != ga { + t.Fatalf("b's list doesn't have its tab in %s and a's in %s:\n%s", gb, ga, list) + } +} diff --git a/internal/gateway/browser_tools.go b/internal/gateway/browser_tools.go index 658a2bccb..505d41021 100644 --- a/internal/gateway/browser_tools.go +++ b/internal/gateway/browser_tools.go @@ -6,7 +6,7 @@ package gateway const browserInstructions = `These tools use 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 browser_tabs or browser_snapshot. Calls go to the tab the user is looking at until you open or select another; tabs you open go in the "Magpie" tab group. +- Start with browser_tabs or browser_snapshot. Calls go to the tab the user is looking at until you open or select another (to a new tab of your own when another agent works in that one); tabs you open go in your own tab group ("Magpie", or "Magpie 2" and on beside other agents). Leave the tabs browser_tabs marks ~ to the agents working in them. - browser_snapshot shows the page as an accessibility tree. Elements you can act on carry a ref (e12); pass it to browser_click, browser_type and the rest. Refs stay the element's while the page keeps it. Every action answers with the page after it, so you rarely need another snapshot. - Prefer refs to browser_evaluate. Use browser_screenshot when the layout or an image matters. - This is the user's browser: don't close tabs you didn't open, don't change their settings, and ask before sending, buying, posting or deleting anything on their behalf. When a site wants a sign-in, a captcha or a 2FA code, ask the user to do it in the tab, then go on.` @@ -42,7 +42,7 @@ func browserTools() []any { return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": desc} } return []any{ - browserTool("browser_tabs", "Tabs", "List the browser's tabs, open a new one (in the Magpie tab group), switch the tab calls go to, or close one.", false, map[string]any{ + browserTool("browser_tabs", "Tabs", "List the browser's tabs, open a new one (in this session's Magpie tab group), switch the tab calls go to, or close one.", false, map[string]any{ "action": enum("list (default), new, select or close", "list", "new", "select", "close"), "url": str("For new: the page to open in it."), "background": boolean("For new: open it without bringing it to the front."),