diff --git a/internal/browserext/browserext.go b/internal/browserext/browserext.go index c0139f605..5276a7d9a 100644 --- a/internal/browserext/browserext.go +++ b/internal/browserext/browserext.go @@ -12,7 +12,10 @@ import ( "io/fs" "os" "path/filepath" + "strconv" "strings" + + "github.com/yetone/magpie/internal/settings" ) // ID is the extension's ID in every Chromium browser, fixed by the public @@ -75,3 +78,49 @@ func Write(dir, gatewayURL string) error { return os.Rename(tmp, to) }) } + +// Dir is where the extension is written: in the home folder, where Finder +// and Explorer show it, to drag from or choose. +func Dir() string { + home, err := os.UserHomeDir() + if err != nil { + return OldDir() + } + return filepath.Join(home, "Magpie Browser Extension") +} + +// OldDir is where v0.1.2442 wrote it, a hidden folder no one could find; +// a browser that loaded it from there keeps it. +func OldDir() string { return filepath.Join(settings.Dir(), "browser-extension") } + +// Refresh writes this magpie's extension over every folder an older one +// was written to, so a browser that reloads it gets this version. A folder +// never written stays unwritten. It says whether any folder has it. +func Refresh(gatewayURL string) bool { + written := false + for _, dir := range []string{Dir(), OldDir()} { + if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err == nil { + written = Write(dir, gatewayURL) == nil || written + } + } + return written +} + +// Older says whether version a (0.1.3) is before b: a newer extension's +// folder is never written over with an older magpie's. +func Older(a, b string) bool { + as, bs := strings.Split(a, "."), strings.Split(b, ".") + for i := 0; i < len(as) || i < len(bs); i++ { + var x, y int + if i < len(as) { + x, _ = strconv.Atoi(as[i]) + } + if i < len(bs) { + y, _ = strconv.Atoi(bs[i]) + } + if x != y { + return x < y + } + } + return false +} diff --git a/internal/browserext/browserext_test.go b/internal/browserext/browserext_test.go index 8ff00488c..341e6397c 100644 --- a/internal/browserext/browserext_test.go +++ b/internal/browserext/browserext_test.go @@ -47,3 +47,37 @@ func TestWritePointsAtTheGateway(t *testing.T) { t.Fatal("took an address that isn't http") } } + +// An extension is told to reload only into a newer version than its own. +func TestOlder(t *testing.T) { + for _, c := range []struct { + a, b string + want bool + }{{"0.1.3", "0.1.4", true}, {"0.1.9", "0.1.10", true}, {"0.1.4", "0.1.4", false}, {"0.1.5", "0.1.4", false}, {"", "0.1.4", true}, {"0.2", "0.1.9", false}} { + if got := Older(c.a, c.b); got != c.want { + t.Errorf("Older(%q, %q) = %v", c.a, c.b, got) + } + } +} + +// Refresh writes over the folders an older magpie wrote, and no other. +func TestRefreshWritesOnlyWrittenFolders(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + if Refresh("http://127.0.0.1:3425") { + t.Fatal("wrote a folder no one had") + } + if _, err := os.Stat(Dir()); !os.IsNotExist(err) { + t.Fatalf("made %s: %v", Dir(), err) + } + os.MkdirAll(Dir(), 0o755) + os.WriteFile(filepath.Join(Dir(), "manifest.json"), []byte(`{"version": "0.1.0"}`), 0o644) + if !Refresh("http://127.0.0.1:3425") { + t.Fatal("didn't write the written folder") + } + b, _ := os.ReadFile(filepath.Join(Dir(), "manifest.json")) + if !strings.Contains(string(b), `"version": "`+Version()+`"`) { + t.Fatalf("manifest: %s", b) + } +} diff --git a/internal/browserext/ext/background.js b/internal/browserext/ext/background.js index 47e2cee44..b2217b02f 100644 --- a/internal/browserext/ext/background.js +++ b/internal/browserext/ext/background.js @@ -141,8 +141,10 @@ function tabArg(v) { return Number(m[1]); } -// the tab a call works in: the one it names, else the session's, else the -// tab the user is looking at +// 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. async function tabFor(session, args) { await loadSessions(); const named = tabArg(args.tab); @@ -157,20 +159,24 @@ async function tabFor(session, args) { const ok = await chrome.tabs.get(had).then(() => true, () => false); if (ok) return had; } - const [active] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); - if (!active) throw fault("BAD_ARGS", "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; + return (await open(session, "about:blank", false)).id; +} + +// open is a new tab of the session's, in its tab group, behind the tab the +// user is looking at unless front: in the window they used last, or a +// window of its own, not brought forward, when none is open. +async function open(session, url, front) { + let w = await chrome.windows.getLastFocused({ windowTypes: ["normal"] }).catch(() => null); + let tab; + if (w) tab = await chrome.tabs.create({ url, active: !!front, windowId: w.id }); + else { + w = await chrome.windows.create({ url, focused: !!front }); + tab = w.tabs[0]; } - sessions.set(session, active.id); + await group(session, tab.id, tab.windowId); + sessions.set(session, tab.id); saveSessions(); - return active.id; + return tab; } // group puts a tab the session opened in the session's tab group in that @@ -297,11 +303,17 @@ async function look(t, el) { // page; it is reported rather than waited on. async function act(t, what, fn, el = null, press = false) { if (t.dialog) return dialogOpen(t); - const before = new Set((await chrome.tabs.query({})).map((x) => x.id)); + const all = await chrome.tabs.query({}); + const before = new Set(all.map((x) => x.id)); + // the tab the user has in front in this tab's window: a tab a link opens + // from a tab behind it is shown, with that one named as its opener + const mine = all.find((x) => x.id === t.tabId); + 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; t.sentInput = false; let opened = null; - const onCreated = (tab) => { if (!before.has(tab.id) && (tab.openerTabId === t.tabId || !opened)) opened = tab; }; + const onCreated = (tab) => { if (!before.has(tab.id) && (tab.openerTabId === t.tabId || (behind && tab.openerTabId === behind.id) || !opened)) opened = tab; }; chrome.tabs.onCreated.addListener(onCreated); let said; try { @@ -325,8 +337,13 @@ async function act(t, what, fn, el = null, press = false) { else out.push(what); out.push(...notices(t)); 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 + 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 (t.by) { sessions.set(t.by, opened.id); saveSessions(); } const nt = state(opened.id); await attach(opened.id); @@ -463,11 +480,8 @@ const TOOLS = { await loadSessions(); const action = args.action || "list"; 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(session, tab.id, tab.windowId); - sessions.set(session, tab.id); - saveSessions(); + // behind the user's tab; front shows it, when the user asked to see it + const tab = await open(session, args.url ? withScheme(args.url) : "about:blank", args.front === true); const t = state(tab.id); await attach(tab.id); if (args.url) { await waitLoad(t); await settle(t); } @@ -756,10 +770,17 @@ const TOOLS = { 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, then take it + // 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 }); - await sleep(300); - r = await shot(); + try { + await sleep(300); + r = await shot(); + } finally { + if (shown && shown.id !== t.tabId) await chrome.tabs.update(shown.id, { active: true }).catch(() => {}); + } } return { content: [{ type: "image", data: r.data, mimeType: args.png ? "image/png" : "image/jpeg" }, text(await head(t))] }; }, diff --git a/internal/browserext/ext/manifest.json b/internal/browserext/ext/manifest.json index 9381a153d..37c442afa 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.3", + "version": "0.1.4", "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/gateway/browser.go b/internal/gateway/browser.go index 788aba26e..66aadd04c 100644 --- a/internal/gateway/browser.go +++ b/internal/gateway/browser.go @@ -276,6 +276,15 @@ func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) { added = true log.Printf("Magpie Browser %s connected", m.Version) } + if browserext.Older(m.Version, browserext.Version()) { + // an older extension: its folder gets this magpie's, which + // the browser reads when it starts again (or the extension's + // reload on chrome://extensions). The extension isn't told + // to reload itself: an unpacked one that calls + // chrome.runtime.reload() doesn't come back (Chrome for + // Testing 1234, headless and not, loaded either way). + browserext.Refresh(URL()) + } case m.Type == "ping": c.send(ctx, map[string]string{"type": "pong"}) case m.ID != "": diff --git a/internal/gateway/browser_e2e_test.go b/internal/gateway/browser_e2e_test.go index 5328398e9..ee9263530 100644 --- a/internal/gateway/browser_e2e_test.go +++ b/internal/gateway/browser_e2e_test.go @@ -239,6 +239,20 @@ func TestBrowserToolsInARealBrowser(t *testing.T) { // 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() + srv, site, _ = realBrowserFrom(t, func(srv *httptest.Server) string { + ext := t.TempDir() + if err := browserext.Write(ext, srv.URL); err != nil { + t.Fatal(err) + } + return ext + }) + return srv, site +} + +// realBrowserFrom is realBrowser with the extension loaded from the folder +// ext writes, and the gateway's Server too. +func realBrowserFrom(t *testing.T, ext func(*httptest.Server) string) (srv, site *httptest.Server, s *Server) { t.Helper() chrome := os.Getenv("MAGPIE_BROWSER_CHROME") if chrome == "" { @@ -246,7 +260,7 @@ func realBrowser(t *testing.T) (srv, site *httptest.Server) { } fresh(t) - s := New() + s = New() srv = httptest.NewServer(lanGuard(s.Handler())) t.Cleanup(srv.Close) site = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -267,13 +281,10 @@ func realBrowser(t *testing.T) (srv, site *httptest.Server) { })) t.Cleanup(site.Close) - ext := t.TempDir() - if err := browserext.Write(ext, srv.URL); err != nil { - t.Fatal(err) - } + dir := ext(srv) profile := t.TempDir() cmd := exec.Command(chrome, "--headless=new", "--user-data-dir="+profile, - "--disable-extensions-except="+ext, "--load-extension="+ext, + "--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 @@ -305,7 +316,7 @@ func realBrowser(t *testing.T) (srv, site *httptest.Server) { } time.Sleep(50 * time.Millisecond) } - return srv, site + return srv, site, s } // browserCaller calls the browser's tools as the agent session session: @@ -352,9 +363,8 @@ func browserCaller(t *testing.T, srv *httptest.Server, session string) (call fun } // 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 +// Discord: two agents behind one router took one tab): each works 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) @@ -433,3 +443,81 @@ func TestBrowserToolActionsInARealBrowser(t *testing.T) { } ok("browser", map[string]any{"action": "tab_close"}, "Closed 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. +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)) + if users == nil { + t.Fatal("no shown about:blank tab 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) + } + } + 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) + } + shown("after a navigate") + if list := ok("browser_tabs", nil); !regexp.MustCompile(`(?m)^\* t\d+ \[Magpie\] "Fixture"`).MatchString(list) { + t.Fatalf("the agent's tab isn't in its Magpie group:\n%s", list) + } + link := regexp.MustCompile(`- link "Open two"(?: \[[a-z=, ]+\])? \[ref=(e\d+)\]`).FindStringSubmatch(page) + if link == nil { + t.Fatalf("no link Open two in:\n%s", page) + } + ok("browser_click", map[string]any{"ref": link[1]}, "opened a new tab", "Page two") + shown("after a link opened a tab") + if list := ok("browser_tabs", nil); !regexp.MustCompile(`(?m)^\* t\d+ \[Magpie\] "Two"`).MatchString(list) { + t.Fatalf("the tab the link opened isn't the agent's, in its group:\n%s", list) + } + ok("browser_tabs", map[string]any{"action": "new", "url": site.URL + "/two"}, "Page two") + shown("after tab new") + if m := call("browser_screenshot", nil); m.Result.IsError || m.Result.Content[0].Type != "image" { + t.Fatalf("screenshot: %+v", m.Result.Content) + } + shown("after a screenshot") + ok("browser", map[string]any{"action": "tab_new", "url": site.URL}, "Opened t") + shown("after the one tool's tab_new") +} + +// 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. +func TestBrowserOlderExtensionsFolderWritten(t *testing.T) { + var man string + realBrowserFrom(t, func(srv *httptest.Server) string { + t.Setenv("MAGPIE_ADDR", srv.Listener.Addr().String()) + dir := browserext.Dir() + if err := browserext.Write(dir, srv.URL); err != nil { + t.Fatal(err) + } + man = filepath.Join(dir, "manifest.json") + b, _ := os.ReadFile(man) + old := bytes.Replace(b, []byte(`"version": "`+browserext.Version()+`"`), []byte(`"version": "0.0.1"`), 1) + if bytes.Equal(old, b) { + t.Fatalf("no version in %s", b) + } + os.WriteFile(man, old, 0o644) + return dir + }) + for deadline := time.Now().Add(10 * time.Second); ; { + if b, _ := os.ReadFile(man); bytes.Contains(b, []byte(`"version": "`+browserext.Version()+`"`)) { + break + } + if time.Now().After(deadline) { + b, _ := os.ReadFile(man) + t.Fatalf("the folder still has:\n%s", b) + } + time.Sleep(50 * time.Millisecond) + } +} diff --git a/internal/gateway/browser_one.go b/internal/gateway/browser_one.go index 4a49dffc0..ab130d71b 100644 --- a/internal/gateway/browser_one.go +++ b/internal/gateway/browser_one.go @@ -67,8 +67,8 @@ func browserOneTool() map[string]any { return map[string]any{ "name": "browser", "title": "Browser", - "description": "Act in the user's own browser. Actions, with the arguments each takes:\n" + - "tabs: list them. tab_new [url, background]. tab_select [tab]. tab_close [tab]. browsers: the connected ones. use_browser [browser].\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; their own tabs only when you name one. 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" + "click [ref, double, button, modifiers]. type [ref, text, clear, submit, slowly]. press [key, ref]. hover [ref]. select [ref, values]. scroll [direction, amount, ref]. drag [from, to]. upload [ref, paths].\n" + @@ -78,11 +78,11 @@ func browserOneTool() map[string]any { "type": "object", "properties": map[string]any{ "action": map[string]any{"type": "string", "enum": browserActionOrder}, - "tab": str("t123, from tabs. Default: this session's tab, else the user's current one."), + "tab": str("t123, from tabs. Default: this session's own tab, else a new one behind the user's."), "ref": str("An element's ref from the latest snapshot (e12)."), "url": str("navigate, tab_new: the address; wait: until the address contains this."), "text": str("type: what to type; wait: until the page shows this."), - "background": boolean("tab_new: don't bring it to the front."), + "front": boolean("tab_new: show it to the user, only when they asked to see it."), "browser": str("use_browser: its id from browsers (b2) or name (Edge)."), "interactive": boolean("snapshot: only what you can act on, and headings."), "maxChars": num("snapshot, text: the most characters back."), diff --git a/internal/gateway/browser_tools.go b/internal/gateway/browser_tools.go index 56125968c..9f573248b 100644 --- a/internal/gateway/browser_tools.go +++ b/internal/gateway/browser_tools.go @@ -16,7 +16,7 @@ How to work: - 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.` 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 the user's current tab."} + 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."} } func browserRefArg(what string) map[string]any { @@ -47,10 +47,10 @@ func browserTools() []any { } return []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. With more than one browser connected: list them (browsers), or pick the one calls go to (use).", false, map[string]any{ - "action": enum("list (default), new, select, close, browsers or use", "list", "new", "select", "close", "browsers", "use"), - "url": str("For new: the page to open in it."), - "background": boolean("For new: open it without bringing it to the front."), - "browser": str("For use: the browser, by its id from browsers (b2) or its name (Edge)."), + "action": enum("list (default), new, select, close, browsers or use", "list", "new", "select", "close", "browsers", "use"), + "url": str("For new: the page to open in it."), + "front": boolean("For new: show it to the user, only when they asked to see it; it opens behind their tab otherwise."), + "browser": str("For use: the browser, by its id from browsers (b2) or its name (Edge)."), }), browserTool("browser_navigate", "Navigate", "Open a URL in the tab, or go back, forward or reload. Answers with the page once it has loaded.", false, map[string]any{ "url": str("The address to open (https:// is added when it has no scheme)."), diff --git a/internal/gui/browser.go b/internal/gui/browser.go index 9cf45b25b..ed2095062 100644 --- a/internal/gui/browser.go +++ b/internal/gui/browser.go @@ -10,7 +10,6 @@ import ( "github.com/yetone/magpie/internal/browserext" "github.com/yetone/magpie/internal/gateway" - "github.com/yetone/magpie/internal/settings" ) // Magpie Browser's extension, as the Library page sets it up: written to a @@ -18,20 +17,10 @@ import ( // own browser's chrome://extensions (or choose with Load unpacked), and // connected or not as the gateway says. -// browserExtDir is where the extension is written: in the home folder, -// where Finder and Explorer show it, to drag from or choose. -func browserExtDir() string { - home, err := os.UserHomeDir() - if err != nil { - return filepath.Join(settings.Dir(), "browser-extension") - } - return filepath.Join(home, "Magpie Browser Extension") -} - -// browserExtOldDir is where v0.1.2442 wrote it, a hidden folder no one -// could find to load; a browser that loaded it from there still does, so -// it is kept up to date too while it is there. -func browserExtOldDir() string { return filepath.Join(settings.Dir(), "browser-extension") } +// the folders it is written to (browserext.Dir, and OldDir while a +// browser still loads it from there) +func browserExtDir() string { return browserext.Dir() } +func browserExtOldDir() string { return browserext.OldDir() } type browserJSON struct { Dir string `json:"dir"`