diff --git a/internal/gateway/browser.go b/internal/gateway/browser.go index 66aadd04c..cb9a798a4 100644 --- a/internal/gateway/browser.go +++ b/internal/gateway/browser.go @@ -55,6 +55,7 @@ const browserCallWait = 100 * time.Second // Browser (Chrome and Edge both, two profiles of one). A session goes on in // the one it picked (browser_tabs use), else the last to connect. type browserRelay struct { + recs browserRecs mu sync.Mutex conns []*browserConn chosen map[string]*browserConn // session → the browser it picked @@ -342,11 +343,16 @@ func (s *Server) browserMCPCall(r *http.Request, m mcpMessage) (any, map[string] return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()} } one, shot := p.Name == "browser", false + acted := map[string]any{} // the arguments, for a recording's frame if one { tool, args, wants, err := browserUnfold(p.Arguments) if err != nil { return toolResult(err.Error(), true), nil } + json.Unmarshal(p.Arguments, &acted) + if tool == browserRecordTool { + return s.browserRecord(r, browserSession(r), acted["action"] == "record_stop"), nil + } p.Name, p.Arguments, shot = tool, args, wants } else if !browserToolNamed(p.Name) { return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name} @@ -390,37 +396,58 @@ func (s *Server) browserMCPCall(r *http.Request, m mcpMessage) (any, map[string] } } } - if shot && result["isError"] != true { - s.browserShot(r, session, result) + rec := s.browser.recs.on(session) && result["isError"] != true && browserRecWorth(p.Name, tabs.Action) + if (shot || rec) && result["isError"] != true { + data, why := s.browserPicture(r, session) + if shot { + s.browserShot(result, data, why) + } + if rec && data != "" { + name := strings.TrimPrefix(p.Name, "browser_") + if a, _ := acted["action"].(string); a != "" { + name = a + } + if f, err := browserRecFrame(data, browserRecSay(s.browser.recs.count(session)+1, name, acted)); err == nil { + s.browser.recs.add(session, f) + } + } } return said(result), nil } return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method} } -// browserShot adds a small picture of the window to an action's result. -// One that can't be taken says so; the action still happened. -func (s *Server) browserShot(r *http.Request, session string, result map[string]any) { - content, _ := result["content"].([]any) +// browserPicture is a picture of session's window (base64), or why there +// is none. +func (s *Server) browserPicture(r *http.Request, session string) (data, why string) { out, err := s.browser.call(r.Context(), session, "browser_screenshot", nil) + if err != nil { + return "", err.Error() + } var shot struct { Content []struct{ Type, Data string } IsError bool } - if err == nil && json.Unmarshal(out, &shot) == nil && !shot.IsError { + if json.Unmarshal(out, &shot) == nil && !shot.IsError { for _, c := range shot.Content { - if c.Type != "image" { - continue - } - if small, ok := browserSmall(c.Data); ok { - result["content"] = append(content, map[string]any{"type": "image", "data": small, "mimeType": "image/jpeg"}) - return + if c.Type == "image" && c.Data != "" { + return c.Data, "" } } } - why := "it didn't answer with a picture" - if err != nil { - why = err.Error() + return "", "it didn't answer with a picture" +} + +// browserShot adds a small picture of the window, data, to an action's +// result. One that couldn't be taken says why; the action still happened. +func (s *Server) browserShot(result map[string]any, data, why string) { + content, _ := result["content"].([]any) + if data != "" { + if small, ok := browserSmall(data); ok { + result["content"] = append(content, map[string]any{"type": "image", "data": small, "mimeType": "image/jpeg"}) + return + } + why = "it didn't answer with a picture" } result["content"] = append(content, map[string]any{"type": "text", "text": "(no screenshot: " + why + ")"}) } diff --git a/internal/gateway/browser_one.go b/internal/gateway/browser_one.go index ab130d71b..883ee6c8a 100644 --- a/internal/gateway/browser_one.go +++ b/internal/gateway/browser_one.go @@ -52,10 +52,17 @@ var browserActions = map[string]browserAction{ "text": {"browser_text", nil}, "console": {"browser_console", nil}, "dialog": {"browser_dialog", nil}, + // the gateway's own: browserRecord + "record_start": {browserRecordTool, map[string]any{"action": "start"}}, + "record_stop": {browserRecordTool, map[string]any{"action": "stop"}}, } +// browserRecordTool is the record actions' tool, which the gateway answers +// itself. +const browserRecordTool = "record" + // browserActionOrder is the order the schema lists them in. -var browserActionOrder = []string{"tabs", "tab_new", "tab_select", "tab_close", "browsers", "use_browser", "navigate", "back", "forward", "reload", "snapshot", "click", "type", "press", "hover", "select", "scroll", "drag", "upload", "wait", "screenshot", "evaluate", "text", "console", "dialog"} +var browserActionOrder = []string{"tabs", "tab_new", "tab_select", "tab_close", "browsers", "use_browser", "navigate", "back", "forward", "reload", "snapshot", "click", "type", "press", "hover", "select", "scroll", "drag", "upload", "wait", "screenshot", "evaluate", "text", "console", "dialog", "record_start", "record_stop"} func browserOneTool() map[string]any { str := func(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} } @@ -73,6 +80,7 @@ func browserOneTool() map[string]any { "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" + "wait [text, textGone, url, seconds, timeout]. screenshot [ref, fullPage, png]. evaluate [script, ref]. text [maxChars]: the visible text. console [level, limit]. dialog [accept, promptText].\n" + + "record_start: keep a picture of the window after each action that changes the page. record_stop: those pictures as a GIF, at a link to download, for the user to see what was done.\n" + "Every action takes tab, and screenshot: true to add a small picture of the window to its answer.", "inputSchema": map[string]any{ "type": "object", diff --git a/internal/gateway/browser_one_test.go b/internal/gateway/browser_one_test.go index b30936c89..dc9d622fa 100644 --- a/internal/gateway/browser_one_test.go +++ b/internal/gateway/browser_one_test.go @@ -31,6 +31,9 @@ func TestBrowserActionsCoverTheTools(t *testing.T) { if !ok { t.Fatalf("%s is listed but unknown", name) } + if a.tool == browserRecordTool { + continue // the gateway's own + } if !strings.Contains(string(src), " async "+a.tool+"(session, args) {") { t.Errorf("%s's %s isn't in background.js", name, a.tool) } diff --git a/internal/gateway/browser_record.go b/internal/gateway/browser_record.go new file mode 100644 index 000000000..48bfb59cd --- /dev/null +++ b/internal/gateway/browser_record.go @@ -0,0 +1,299 @@ +package gateway + +import ( + "bytes" + "encoding/base64" + "errors" + "fmt" + "image" + "image/color" + "image/color/palette" + "image/gif" + "image/jpeg" + "net/http" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/access" + "golang.org/x/image/draw" + "golang.org/x/image/font" + "golang.org/x/image/font/basicfont" + "golang.org/x/image/math/fixed" +) + +// A recording is a GIF of what an agent did in its tab: between the +// browser tool's record_start and record_stop, the gateway takes a picture +// of the window after each action that can change the page, with the +// action written under it. The gateway does it all, so any extension +// version records. + +const ( + // browserRecWidth is a frame's width: a window, readable, at a size a + // few hundred frames of keep small. + browserRecWidth = 800 + // browserRecMost is the most frames one recording keeps. + browserRecMost = 300 + // browserRecIdle is how long a recording nobody stops is kept. + browserRecIdle = 30 * time.Minute + // browserRecLabel is the height of the strip each frame's action is + // written in. + browserRecLabel = 22 +) + +type browserRec struct { + frames [][]byte // JPEG, browserRecWidth wide, its label drawn on + full bool // browserRecMost frames were taken; later ones weren't + started time.Time + last time.Time +} + +type browserRecs struct { + mu sync.Mutex + m map[string]*browserRec // session → its recording +} + +// start begins session's recording, over one it had. +func (rs *browserRecs) start(session string) { + rs.mu.Lock() + defer rs.mu.Unlock() + now := time.Now() + for k, r := range rs.m { + if now.Sub(r.last) > browserRecIdle { + delete(rs.m, k) + } + } + if rs.m == nil { + rs.m = map[string]*browserRec{} + } + rs.m[session] = &browserRec{started: now, last: now} +} + +func (rs *browserRecs) on(session string) bool { + rs.mu.Lock() + defer rs.mu.Unlock() + _, ok := rs.m[session] + return ok +} + +// add keeps a frame for session's recording, if it has one. +func (rs *browserRecs) add(session string, frame []byte) { + rs.mu.Lock() + defer rs.mu.Unlock() + r := rs.m[session] + if r == nil { + return + } + r.last = time.Now() + if len(r.frames) >= browserRecMost { + r.full = true + return + } + r.frames = append(r.frames, frame) +} + +// count is how many frames session's recording holds. +func (rs *browserRecs) count(session string) int { + rs.mu.Lock() + defer rs.mu.Unlock() + if r := rs.m[session]; r != nil { + return len(r.frames) + } + return 0 +} + +// stop ends session's recording and is it, nil when there was none. +func (rs *browserRecs) stop(session string) *browserRec { + rs.mu.Lock() + defer rs.mu.Unlock() + r := rs.m[session] + delete(rs.m, session) + return r +} + +// browserRecSkips are the actions after which nothing on the page can have +// changed, or a picture would open a tab (tab_close's tab is gone). +var browserRecSkips = map[string]bool{ + "browser_snapshot": true, "browser_text": true, "browser_console": true, + "browser_screenshot": true, +} + +// browserRecWorth: a picture after tool, with the tabs action tabs, goes +// in a recording. +func browserRecWorth(tool, tabs string) bool { + if tool == "browser_tabs" { + return tabs == "new" || tabs == "select" + } + return !browserRecSkips[tool] +} + +// browserRecSay is what a frame says was done: the action and what it was +// done to, never what was typed (a password, a message). +func browserRecSay(n int, action string, args map[string]any) string { + s := fmt.Sprintf("%d %s", n, action) + for _, k := range []string{"url", "ref", "key", "direction", "from"} { + if v, ok := args[k].(string); ok && v != "" { + if len(v) > 80 { + v = v[:77] + "..." + } + s += " " + v + if k == "from" { + if to, ok := args["to"].(string); ok { + s += " -> " + to + } + } + break + } + } + return s +} + +// browserRecFrame is the picture data (base64) as a frame: browserRecWidth +// wide, with label in a strip under it. +func browserRecFrame(data, label string) ([]byte, error) { + b, err := base64.StdEncoding.DecodeString(data) + if err != nil { + return nil, err + } + img, _, err := image.Decode(bytes.NewReader(b)) + if err != nil { + return nil, err + } + r := img.Bounds() + if r.Dx() == 0 || r.Dy() == 0 { + return nil, errors.New("an empty picture") + } + h := max(1, r.Dy()*browserRecWidth/r.Dx()) + dst := image.NewRGBA(image.Rect(0, 0, browserRecWidth, h+browserRecLabel)) + draw.ApproxBiLinear.Scale(dst, image.Rect(0, 0, browserRecWidth, h), img, r, draw.Src, nil) + draw.Draw(dst, image.Rect(0, h, browserRecWidth, h+browserRecLabel), image.NewUniform(color.RGBA{0x22, 0x22, 0x22, 0xff}), image.Point{}, draw.Src) + d := font.Drawer{Dst: dst, Src: image.White, Face: basicfont.Face7x13, Dot: fixed.P(8, h+browserRecLabel-6)} + d.DrawString(label) + var out bytes.Buffer + if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: 80}); err != nil { + return nil, err + } + return out.Bytes(), nil +} + +// browserGIF is frames as an animated GIF: a second a frame, the last held +// three. Each frame after the first holds only the rectangle that changed. +func browserGIF(frames [][]byte) ([]byte, error) { + pal := color.Palette(palette.Plan9) + near := make([]uint8, 1<<15) // 5 bits a channel → its nearest colour, +1 + index := func(c color.RGBA) uint8 { + k := int(c.R>>3)<<10 | int(c.G>>3)<<5 | int(c.B>>3) + if near[k] == 0 { + near[k] = uint8(pal.Index(color.RGBA{c.R&^7 | 4, c.G&^7 | 4, c.B&^7 | 4, 0xff})) + 1 + } + return near[k] - 1 + } + g := &gif.GIF{} + var prev *image.Paletted + for i, f := range frames { + img, err := jpeg.Decode(bytes.NewReader(f)) + if err != nil { + return nil, err + } + b := img.Bounds() + if prev != nil && b != prev.Bounds() { + // a window resized: every frame is the first one's size + dst := image.NewRGBA(prev.Bounds()) + draw.ApproxBiLinear.Scale(dst, dst.Bounds(), img, b, draw.Src, nil) + img, b = dst, dst.Bounds() + } + rgba, ok := img.(*image.RGBA) + if !ok { + rgba = image.NewRGBA(b) + draw.Draw(rgba, b, img, b.Min, draw.Src) + } + p := image.NewPaletted(b, pal) + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + o := rgba.PixOffset(x, y) + p.Pix[p.PixOffset(x, y)] = index(color.RGBA{rgba.Pix[o], rgba.Pix[o+1], rgba.Pix[o+2], 0xff}) + } + } + out := p + if prev != nil { + ch := changed(prev, p) + if ch.Empty() { + ch = image.Rect(b.Min.X, b.Min.Y, b.Min.X+1, b.Min.Y+1) + } + out = p.SubImage(ch).(*image.Paletted) + } + delay := 100 + if i == len(frames)-1 { + delay = 300 + } + g.Image = append(g.Image, out) + g.Delay = append(g.Delay, delay) + g.Disposal = append(g.Disposal, gif.DisposalNone) + if prev == nil { + g.Config = image.Config{ColorModel: pal, Width: b.Dx(), Height: b.Dy()} + } + prev = p + } + var buf bytes.Buffer + if err := gif.EncodeAll(&buf, g); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// changed is the smallest rectangle in which a and b, of one size, differ. +func changed(a, b *image.Paletted) image.Rectangle { + r := a.Bounds() + x0, y0, x1, y1 := r.Max.X, r.Max.Y, r.Min.X, r.Min.Y + for y := r.Min.Y; y < r.Max.Y; y++ { + row := a.PixOffset(r.Min.X, y) + ra, rb := a.Pix[row:row+r.Dx()], b.Pix[row:row+r.Dx()] + if bytes.Equal(ra, rb) { + continue + } + y0, y1 = min(y0, y), max(y1, y+1) + for x := range ra { + if ra[x] != rb[x] { + x0, x1 = min(x0, r.Min.X+x), max(x1, r.Min.X+x+1) + break + } + } + for x := len(ra) - 1; x >= 0; x-- { + if ra[x] != rb[x] { + x1 = max(x1, r.Min.X+x+1) + break + } + } + } + if x0 >= x1 || y0 >= y1 { + return image.Rectangle{} + } + return image.Rect(x0, y0, x1, y1) +} + +// browserRecord answers record_start and record_stop. +func (s *Server) browserRecord(r *http.Request, session string, stop bool) map[string]any { + if !stop { + s.browser.recs.start(session) + return toolResult("Recording. After each action that can change the page a picture of the window is kept, with the action under it; record_stop makes them a GIF.", false) + } + rec := s.browser.recs.stop(session) + if rec == nil { + return toolResult("Nothing is being recorded: record_start begins.", true) + } + if len(rec.frames) == 0 { + return toolResult("The recording has no frames: no action that changes the page was taken after record_start.", true) + } + data, err := browserGIF(rec.frames) + if err != nil { + return toolResult("The GIF couldn't be made: "+err.Error(), true) + } + u := imageMCPBase(r) + ImageMCPFiles + s.imageMCPKeepFile(data, "image/gif", access.Caller(r.Context()).KeyID) + var b strings.Builder + fmt.Fprintf(&b, "Recorded %d frames over %s, a %d KB GIF. Download it within the hour (the link opens without a header; whoever has it can open it), e.g. curl -o recording.gif '%s'\n%s\n", + len(rec.frames), time.Since(rec.started).Round(time.Second), (len(data)+1023)/1024, u, u) + if rec.full { + fmt.Fprintf(&b, "It holds the first %d frames; later actions weren't kept.\n", browserRecMost) + } + return withMeta(map[string]any{"content": []any{map[string]any{"type": "text", "text": b.String()}}, "isError": false}, FilesMeta, []MadeFile{{URL: u}}) +} diff --git a/internal/gateway/browser_record_test.go b/internal/gateway/browser_record_test.go new file mode 100644 index 000000000..d658d1ad5 --- /dev/null +++ b/internal/gateway/browser_record_test.go @@ -0,0 +1,132 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "image" + "image/color" + "image/gif" + "image/jpeg" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "golang.org/x/image/draw" +) + +func recJPEG(t *testing.T, w, h int, box image.Rectangle) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.Draw(img, img.Bounds(), image.White, image.Point{}, draw.Src) + draw.Draw(img, box, image.NewUniform(color.RGBA{0, 0, 0xff, 0xff}), image.Point{}, draw.Src) + var b bytes.Buffer + jpeg.Encode(&b, img, &jpeg.Options{Quality: 95}) + return b.Bytes() +} + +// A recording's GIF has a frame an action, held a second, the last three; +// after the first, a frame holds only what changed. +func TestBrowserGIFFramesHoldWhatChanged(t *testing.T) { + frames := [][]byte{ + recJPEG(t, 400, 300, image.Rectangle{}), + recJPEG(t, 400, 300, image.Rect(100, 100, 160, 140)), + recJPEG(t, 400, 300, image.Rect(100, 100, 160, 140)), + recJPEG(t, 800, 600, image.Rectangle{}), // a resized window + } + data, err := browserGIF(frames) + if err != nil { + t.Fatal(err) + } + g, err := gif.DecodeAll(bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + if len(g.Image) != 4 || g.Config.Width != 400 || g.Config.Height != 300 { + t.Fatalf("%d frames, %dx%d", len(g.Image), g.Config.Width, g.Config.Height) + } + if d := g.Delay; d[0] != 100 || d[3] != 300 { + t.Fatalf("delays %v", d) + } + if b := g.Image[1].Bounds(); b.Dx() > 80 || b.Dy() > 60 || !b.Overlaps(image.Rect(100, 100, 160, 140)) { + t.Fatalf("the second frame holds %v, not the box that changed", b) + } + if b := g.Image[2].Bounds(); b.Dx()*b.Dy() > 4 { + t.Fatalf("an unchanged frame holds %v", b) + } + if b := g.Image[3].Bounds(); !b.In(image.Rect(0, 0, 400, 300)) { + t.Fatalf("the resized frame is %v, outside the GIF", b) + } +} + +// A frame's label says what was done to what, never what was typed. +func TestBrowserRecSayKeepsTypedTextOut(t *testing.T) { + got := browserRecSay(3, "type", map[string]any{"ref": "e4", "text": "hunter2", "action": "type"}) + if got != "3 type e4" { + t.Fatalf("%q", got) + } + if got := browserRecSay(1, "navigate", map[string]any{"url": "https://example.com/"}); got != "1 navigate https://example.com/" { + t.Fatalf("%q", got) + } + if got := browserRecSay(2, "drag", map[string]any{"from": "e1", "to": "e2"}); got != "2 drag e1 -> e2" { + t.Fatalf("%q", got) + } +} + +// record_stop with nothing recorded says so, with no browser connected. +func TestBrowserRecordStopWithNothing(t *testing.T) { + fresh(t) + s := New() + srv := httptest.NewServer(lanGuard(s.Handler())) + t.Cleanup(srv.Close) + call, _ := browserCaller(t, srv, "rec") + if m := call("browser", map[string]any{"action": "record_stop"}); !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "record_start") { + t.Fatalf("%+v", m.Result) + } + call("browser", map[string]any{"action": "record_start"}) + if m := call("browser", map[string]any{"action": "record_stop"}); !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "no frames") { + t.Fatalf("%+v", m.Result) + } +} + +// Recording in a real Chromium: the actions that change the page are each +// a frame of the GIF at the answer's link, the ones that read it are not. +func TestBrowserRecordsAGIF(t *testing.T) { + srv, site := realBrowser(t) + call, ok := browserCaller(t, srv, "rec") + ok("browser", map[string]any{"action": "record_start"}, "Recording") + page := ok("browser", map[string]any{"action": "navigate", "url": site.URL}, "Magpie fixture") + name := regexp.MustCompile(`textbox "Name"[^\n]*\[ref=(e\d+)\]`).FindStringSubmatch(page) + if name == nil { + t.Fatalf("no Name field in:\n%s", page) + } + ok("browser", map[string]any{"action": "type", "ref": name[1], "text": "hunter2"}) + ok("browser", map[string]any{"action": "snapshot"}) + ok("browser", map[string]any{"action": "navigate", "url": site.URL + "/two"}, "Page two") + m := call("browser", map[string]any{"action": "record_stop"}) + if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "Recorded 3 frames") { + t.Fatalf("%+v", m.Result) + } + var files []MadeFile + if json.Unmarshal([]byte(m.meta(FilesMeta)), &files) != nil || len(files) != 1 { + t.Fatalf("files %s", m.meta(FilesMeta)) + } + resp, err := http.Get(files[0].URL) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(resp.Body) + resp.Body.Close() + g, err := gif.DecodeAll(bytes.NewReader(b)) + if err != nil { + t.Fatalf("%d %s: %v", resp.StatusCode, resp.Header.Get("Content-Type"), err) + } + if len(g.Image) != 3 || g.Config.Width != browserRecWidth { + t.Fatalf("%d frames, %d wide", len(g.Image), g.Config.Width) + } + if m := call("browser", map[string]any{"action": "record_stop"}); !m.Result.IsError { + t.Fatalf("a second stop: %+v", m.Result) + } +}