Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(teamhub): let the live voice read long pages in parts and close tabs
muterCd1fc986b3a3a
diff --git a/apps/teamhub/internal/voice/voice_live_browser.go b/apps/teamhub/internal/voice/voice_live_browser.goindex 59b53bfa..5db4d754 100644--- a/apps/teamhub/internal/voice/voice_live_browser.go+++ b/apps/teamhub/internal/voice/voice_live_browser.go@@ -51,15 +51,22 @@ func (s *Service) callVoiceLiveBrowser(ctx context.Context, session voicelive.Se}// The page the live voice saw last: where a hand-off continues, and what a// risky click would press.- lastPage := ""+ // landing is the first page of a tab a click opened, while the live voice+ // is still on that tab.+ lastPage, cameFrom, landing := "", -1, ""if previous, err := s.queries.GetLatestVoiceLiveToolOutput(ctx, store.GetLatestVoiceLiveToolOutputParams{- VoiceSessionID: session.ID, Name: voicelive.ToolComputerBrowser,+ VoiceSessionID: session.ID, Name: voicelive.ToolComputerBrowser, CallID: request.CallId,}); err == nil {var shown struct {- Page string `json:"page"`+ Page string `json:"page"`+ CameFromTab *int `json:"came_from_tab"`+ LandingURL string `json:"landing_url"`}_ = json.Unmarshal([]byte(previous), &shown)- lastPage = shown.Page+ lastPage, landing = shown.Page, shown.LandingURL+ if shown.CameFromTab != nil {+ cameFrom = *shown.CameFromTab+ }} else if !errors.Is(err, pgx.ErrNoRows) {return "", err}@@ -87,12 +94,29 @@ func (s *Service) callVoiceLiveBrowser(ctx context.Context, session voicelive.Sereturn prompt, err}}- result, err := browser.CallLocalBrowserTool(ctx, roomagent.LocalBrowserToolCall{+ call := roomagent.LocalBrowserToolCall{TenantID: session.TenantID, OwnerActorID: session.HumanActorID,ComputerID: target.ComputerID, AgentID: target.AgentManagementID,ToolSessionID: "voice-" + strings.TrimPrefix(session.ID, "voice_session_"),ToolName: toolName, Arguments: arguments,- })+ }+ // Closing a tab, or going back from the page a click opened in a new tab,+ // closes that tab and returns to the one it came from: going back inside+ // it would leave a second copy of the page the user came from.+ count, current := voicelive.BrowserTabs(lastPage)+ closing := closesLiveBrowserTab(args.Action, lastPage, cameFrom, landing)+ if closing && count <= 1 {+ if args.Action == "close" {+ return voicelive.Output(map[string]string{"error": "only_tab", "detail": "This is the only tab, so it stays open: use back for the previous page or open another address."}), nil+ }+ closing = false+ }+ var result roomagent.LocalBrowserToolResult+ if closing {+ result, err = s.closeLiveBrowserTab(ctx, browser, call, current, cameFrom, count)+ } else {+ result, err = browser.CallLocalBrowserTool(ctx, call)+ }if err != nil {var rejected *roomagent.LocalComputerToolErrorif errors.As(err, &rejected) {@@ -105,13 +129,111 @@ func (s *Service) callVoiceLiveBrowser(ctx context.Context, session voicelive.Ses.logger.Warn("live local browser call failed", "voice_session_id", session.ID, "tool", toolName, "error", err)return voicelive.ErrorOutput("browser_unavailable"), nil}- page, truncated := voicelive.BrowserPage(result.Text)- output := map[string]any{"page": page}- if truncated {+ if closing {+ cameFrom, landing = -1, ""+ } else {+ result, cameFrom = s.followLiveBrowserTab(ctx, session, browser, call, args.Action, lastPage, cameFrom, result)+ switch nowCount, nowCurrent := voicelive.BrowserTabs(result.Text); {+ case cameFrom < 0:+ landing = ""+ case nowCurrent != current || nowCount != count:+ // The click just moved to the tab it opened.+ landing = voicelive.BrowserPageURL(result.Text)+ }+ }+ part, find := 0, ""+ if args.Action == "look" {+ part, find = int(args.Part), args.Find+ }+ shown := voicelive.BrowserPage(result.Text, part, find)+ output := map[string]any{"page": shown.Page}+ if shown.Parts > 1 {+ output["part"], output["parts"] = shown.Part, shown.Parts+ }+ if !shown.Found {+ output["find"] = "not_found"+ }+ if shown.Truncated {output["truncated"] = true}if result.IsError {output["error"] = "action_failed"}+ if cameFrom >= 0 {+ output["came_from_tab"] = cameFrom+ if landing != "" {+ output["landing_url"] = landing+ }+ }return voicelive.Output(output), nil}++// closesLiveBrowserTab reports whether an action closes the current tab:+// close always does, and back does on the first page of a tab a click opened,+// whatever history the site gave that tab.+func closesLiveBrowserTab(action, lastPage string, cameFrom int, landing string) bool {+ return action == "close" ||+ action == "back" && cameFrom >= 0 && landing != "" && voicelive.BrowserPageURL(lastPage) == landing+}++// closeLiveBrowserTab closes the current tab and reads the one it came from,+// or the tab before it when that is unknown.+func (s *Service) closeLiveBrowserTab(ctx context.Context, browser roomagent.LocalBrowserTool, call roomagent.LocalBrowserToolCall, current, cameFrom, count int) (roomagent.LocalBrowserToolResult, error) {+ call.ToolName, call.Arguments = "browser_tabs", map[string]any{"action": "close", "index": current}+ if closed, err := browser.CallLocalBrowserTool(ctx, call); err != nil || closed.IsError {+ return closed, err+ }+ back := max(current-1, 0)+ if cameFrom >= 0 && cameFrom < count && cameFrom != current {+ back = cameFrom+ }+ if back > current {+ back--+ }+ call.ToolName, call.Arguments = "browser_tabs", map[string]any{"action": "select", "index": back}+ if selected, err := browser.CallLocalBrowserTool(ctx, call); err != nil || selected.IsError {+ return selected, err+ }+ call.ToolName, call.Arguments = "browser_snapshot", map[string]any{}+ return browser.CallLocalBrowserTool(ctx, call)+}++// followLiveBrowserTab keeps the live voice on the tab the user sees, as a+// person would: a click that opens a new tab moves to it. Leaving that tab is+// closesLiveBrowserTab's. It returns the page to show and the tab the current+// one came from, or -1. A follow-up step that fails leaves the first result.+func (s *Service) followLiveBrowserTab(ctx context.Context, session voicelive.Session, browser roomagent.LocalBrowserTool, call roomagent.LocalBrowserToolCall, action, lastPage string, cameFrom int, result roomagent.LocalBrowserToolResult) (roomagent.LocalBrowserToolResult, int) {+ if result.IsError {+ return result, -1+ }+ beforeCount, beforeCurrent := voicelive.BrowserTabs(lastPage)+ count, current := voicelive.BrowserTabs(result.Text)+ switch {+ // Tabs are listed in the order they opened, so the new one is the last.+ case action == "click" && count > beforeCount && current != count-1:+ if page, ok := s.switchLiveBrowserTab(ctx, session, browser, call, count-1); ok {+ return page, current+ }+ }+ // Other steps stay on the same tab and keep where it came from.+ if current == beforeCurrent && count >= beforeCount {+ return result, cameFrom+ }+ return result, -1+}++// switchLiveBrowserTab brings a tab to the front and reads its page.+func (s *Service) switchLiveBrowserTab(ctx context.Context, session voicelive.Session, browser roomagent.LocalBrowserTool, call roomagent.LocalBrowserToolCall, index int) (roomagent.LocalBrowserToolResult, bool) {+ call.ToolName, call.Arguments = "browser_tabs", map[string]any{"action": "select", "index": index}+ if selected, err := browser.CallLocalBrowserTool(ctx, call); err != nil || selected.IsError {+ s.logger.Warn("live browser could not select a tab", "voice_session_id", session.ID, "error", err)+ return roomagent.LocalBrowserToolResult{}, false+ }+ call.ToolName, call.Arguments = "browser_snapshot", map[string]any{}+ page, err := browser.CallLocalBrowserTool(ctx, call)+ if err != nil || page.IsError {+ s.logger.Warn("live browser could not read the selected tab", "voice_session_id", session.ID, "error", err)+ return roomagent.LocalBrowserToolResult{}, false+ }+ return page, true+}diff --git a/apps/teamhub/internal/voice/voice_live_browser_close_test.go b/apps/teamhub/internal/voice/voice_live_browser_close_test.gonew file mode 100644index 00000000..cc6120ef--- /dev/null+++ b/apps/teamhub/internal/voice/voice_live_browser_close_test.go@@ -0,0 +1,58 @@+package voice++import (+ "io"+ "log/slog"+ "testing"++ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"+)++const (+ toutiaoPage = "### Open tabs\n- 0: [Jay Chou - Search](https://www.bing.com/search?q=jay)\n- 1: (current) [Tour dates - Toutiao](https://www.toutiao.com/article/1)\n### Page\n- Page URL: https://www.toutiao.com/article/1\n"+ toutiaoNext = "### Open tabs\n- 0: [Jay Chou - Search](https://www.bing.com/search?q=jay)\n- 1: (current) [Next article - Toutiao](https://www.toutiao.com/article/2)\n### Page\n- Page URL: https://www.toutiao.com/article/2\n"+ jaySearch = "### Page\n- Page URL: https://www.bing.com/search?q=jay\n"+)++func TestBackClosesATabStillOnThePageItsClickOpened(t *testing.T) {+ landing := "https://www.toutiao.com/article/1"+ for _, check := range []struct {+ name, action, page, landing string+ cameFrom int+ closes bool+ }{+ // Bing opens results through its own redirect, so the new tab can go+ // back to a second copy of the search: it is closed instead.+ {"back on the landing page", "back", toutiaoPage, landing, 0, true},+ {"back after reading on in that tab", "back", toutiaoNext, landing, 0, false},+ {"back on a tab nothing opened", "back", jaySearch, "", -1, false},+ {"close always closes", "close", jaySearch, "", -1, true},+ } {+ if got := closesLiveBrowserTab(check.action, check.page, check.cameFrom, check.landing); got != check.closes {+ t.Fatalf("%s: closes=%v", check.name, got)+ }+ }+}++func TestCloseReturnsToTheTabItCameFrom(t *testing.T) {+ service := &Service{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}+ browser := &fakeLiveBrowser{answers: map[string]string{"browser_snapshot": jaySearch}}+ result, err := service.closeLiveBrowserTab(t.Context(), browser, roomagent.LocalBrowserToolCall{}, 1, 0, 2)+ if err != nil || result.Text != jaySearch {+ t.Fatalf("page=%q err=%v", result.Text, err)+ }+ if len(browser.calls) != 3 || browser.calls[0].Arguments["action"] != "close" || browser.calls[0].Arguments["index"] != 1 ||+ browser.calls[1].Arguments["action"] != "select" || browser.calls[1].Arguments["index"] != 0 ||+ browser.calls[2].ToolName != "browser_snapshot" {+ t.Fatalf("calls=%+v", browser.calls)+ }+ // Without a known origin it returns to the tab before; a later origin+ // moves down one place once the tab before it is gone.+ for _, check := range []struct{ current, cameFrom, count, selected int }{{2, -1, 3, 1}, {0, -1, 2, 0}, {0, 2, 3, 1}} {+ browser = &fakeLiveBrowser{answers: map[string]string{}}+ _, _ = service.closeLiveBrowserTab(t.Context(), browser, roomagent.LocalBrowserToolCall{}, check.current, check.cameFrom, check.count)+ if browser.calls[1].Arguments["index"] != check.selected {+ t.Fatalf("%+v: selected %v", check, browser.calls[1].Arguments["index"])+ }+ }+}diff --git a/apps/teamhub/internal/voice/voice_live_browser_test.go b/apps/teamhub/internal/voice/voice_live_browser_test.gonew file mode 100644index 00000000..003b10d7--- /dev/null+++ b/apps/teamhub/internal/voice/voice_live_browser_test.go@@ -0,0 +1,66 @@+package voice++import (+ "context"+ "io"+ "log/slog"+ "testing"++ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/voicelive"+)++type fakeLiveBrowser struct {+ calls []roomagent.LocalBrowserToolCall+ answers map[string]string+}++func (b *fakeLiveBrowser) CallLocalBrowserTool(_ context.Context, call roomagent.LocalBrowserToolCall) (roomagent.LocalBrowserToolResult, error) {+ b.calls = append(b.calls, call)+ return roomagent.LocalBrowserToolResult{Text: b.answers[call.ToolName]}, nil+}++const (+ searchPage = "### Page\n- Page URL: https://www.bing.com/search?q=xai\n"+ clickedPage = "### Open tabs\n- 0: (current) [xai - Search](https://www.bing.com/search?q=xai)\n- 1: [xAI News](https://x.ai/news)\n### Page\n- Page URL: https://www.bing.com/search?q=xai\n"+ articlePage = "### Open tabs\n- 0: [xai - Search](https://www.bing.com/search?q=xai)\n- 1: (current) [xAI News](https://x.ai/news)\n### Page\n- Page URL: https://x.ai/news\n"+)++func TestLiveBrowserFollowsTheTabAClickOpens(t *testing.T) {+ service := &Service{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}+ browser := &fakeLiveBrowser{answers: map[string]string{"browser_snapshot": articlePage}}+ result, cameFrom := service.followLiveBrowserTab(t.Context(), voicelive.Session{}, browser,+ roomagent.LocalBrowserToolCall{ToolName: "browser_click"}, "click", searchPage, -1,+ roomagent.LocalBrowserToolResult{Text: clickedPage})+ if result.Text != articlePage || cameFrom != 0 {+ t.Fatalf("page=%q came_from=%d", result.Text, cameFrom)+ }+ if len(browser.calls) != 2 || browser.calls[0].Arguments["action"] != "select" || browser.calls[0].Arguments["index"] != 1 {+ t.Fatalf("calls=%+v", browser.calls)+ }++ // A look on that tab keeps where it came from.+ _, cameFrom = service.followLiveBrowserTab(t.Context(), voicelive.Session{}, browser,+ roomagent.LocalBrowserToolCall{}, "look", articlePage, 0, roomagent.LocalBrowserToolResult{Text: articlePage})+ if cameFrom != 0 {+ t.Fatalf("look lost the tab it came from: %d", cameFrom)+ }++}++func TestLiveBrowserStaysOnATabWithoutANewOne(t *testing.T) {+ service := &Service{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}+ browser := &fakeLiveBrowser{}+ result, cameFrom := service.followLiveBrowserTab(t.Context(), voicelive.Session{}, browser,+ roomagent.LocalBrowserToolCall{}, "click", searchPage, -1, roomagent.LocalBrowserToolResult{Text: searchPage})+ if result.Text != searchPage || cameFrom != -1 || len(browser.calls) != 0 {+ t.Fatalf("page=%q came_from=%d calls=%d", result.Text, cameFrom, len(browser.calls))+ }+ // Back on a tab that has its own history is an ordinary back.+ moved := "### Page\n- Page URL: https://x.ai/\n"+ result, _ = service.followLiveBrowserTab(t.Context(), voicelive.Session{}, browser,+ roomagent.LocalBrowserToolCall{}, "back", articlePage, 0, roomagent.LocalBrowserToolResult{Text: moved})+ if result.Text != moved || len(browser.calls) != 0 {+ t.Fatalf("page=%q calls=%d", result.Text, len(browser.calls))+ }+}diff --git a/apps/teamhub/internal/voicelive/browser.go b/apps/teamhub/internal/voicelive/browser.goindex 968ed311..31c355a0 100644--- a/apps/teamhub/internal/voicelive/browser.go+++ b/apps/teamhub/internal/voicelive/browser.go@@ -1,8 +1,12 @@package voiceliveimport (+ "encoding/json"+ "fmt""regexp"+ "strconv""strings"+ "unicode/utf8")// ToolComputerBrowser drives the Chrome on the owner's Local Computer. It is@@ -21,21 +25,29 @@ var BrowserTool = Tool{Name: ToolComputerBrowser,Description: "Operate the Chrome on the user's own Local Computer yourself while you keep talking, like sitting next to them; they can watch it on their own desktop. " +"Use it when the user wants to open, browse, search or read a website together with you or asks what is on that page; a site the user names is opened here, not answered with web search. " +- "action: open (url), look (read the page as text with refs), click (ref), type (ref, text, submit to press Enter), back. Every result is the page as text with refs; read it before you click or type and never guess what a page says. " +- "Say only what you found and what comes next, never each step. A login, QR code or CAPTCHA is the user's: stop and ask them to take over on their own desktop, then look again when they say they are done. " ++ "action: open (url), look (read the page as text with refs), click (ref), type (ref, text, submit to press Enter), back, close (close this tab and return to the page it came from, when the user wants a page closed). Every result is the page as text with refs; read it before you click or type and never guess what a page says. " ++ "A long page comes in parts (part 1 of parts): to see what is further down, such as more search results or the rest of an article, look with part 2 and so on, or look with find set to words you expect there (a title, a heading). " ++ "Before the first call of a request, tell the user in one natural sentence what you are opening or looking for; after that say only what you found and what comes next, never each step. A login, QR code or CAPTCHA is the user's: stop and ask them to take over on their own desktop, then look again when they say they are done. " +"Set commits=true on a click that sends, submits, posts, pays, orders, transfers, confirms or deletes something in the user's name, judged by what it does in any language; it and every Enter return needs_confirmation: restate it, and call again with confirmed=true only after the user says yes. " +"If a few tries make no progress (an element that will not respond, a page that will not load), stop and tell the user where it is stuck. Long work across many pages or that ends in a document is start_task: say in its goal what is done and the page to go on from. still_working means a slow step goes on while you keep talking; you are told when its page arrives.",Parameters: objectSchema([]string{"action", "commits"}, map[string]any{- "action": map[string]any{"type": "string", "enum": []string{"open", "look", "click", "type", "back"}},+ "action": map[string]any{"type": "string", "enum": []string{"open", "look", "click", "type", "back", "close"}},"url": stringProperty("For open: the address"),"ref": stringProperty("For click and type: the element ref from the latest page text"),"text": stringProperty("For type: the text to enter"),"submit": map[string]any{"type": "boolean", "description": "For type: press Enter after typing"},+ "part": map[string]any{"type": "integer", "description": "For look: which part of a long page to read, from 1"},+ "find": stringProperty("For look: words to find on the page; returns the part that holds them"),"commits": map[string]any{"type": "boolean", "description": "For click: whether it sends, submits, pays, orders or deletes something in the user's name; false for anything else"},"confirmed": map[string]any{"type": "boolean", "description": "Only after the user said yes to this exact click or Enter"},}),}+// browserConnectionSteps is where the Web app connects the owner's Chrome.+// The live model cannot post the connection card an Agent posts, so it reads+// out these steps instead of guessing at the interface.+const browserConnectionSteps = "Give them the exact steps, not a guess: click their profile picture at the bottom of the left sidebar, choose Settings, open Computers, select this computer, click Connect Chrome, then follow the three steps there (install the Playwright Extension in Chrome, copy the token it shows, paste it and connect). Do not say you cannot see their screen; these steps are the whole answer."+// BrowserConnectionDetail tells the live model what to say when the owner's// Chrome is not connected or is busy, so nothing ran: the user connects it// once under Settings, Computers, or the work goes to a background task,@@ -43,9 +55,9 @@ var BrowserTool = Tool{func BrowserConnectionDetail(code string) (string, bool) {switch code {case "browser_connection_required":- return "Nothing was done: the user's Chrome is not connected to you yet. Tell them so in one sentence and that they can connect it once in Settings under Computers; until then offer to do it as a background task with start_task (surface web). Never call this tool again in this call until they say it is connected, and never blame Chrome, sleep or a frozen window.", true+ return "Nothing was done: the user's Chrome is not connected to you yet. Tell them so in one sentence and that they can connect it once in Settings under Computers. " + browserConnectionSteps + " Until then offer to do it as a background task with start_task (surface web). Never call this tool again in this call until they say it is connected, and never blame Chrome, sleep or a frozen window.", truecase "browser_connection_invalid":- return "Nothing was done: the saved connection to the user's Chrome no longer works. Tell them so in one sentence and that they can reconnect it in Settings under Computers; until then offer to do it as a background task with start_task (surface web). Never call this tool again in this call until they say it is reconnected.", true+ return "Nothing was done: the saved connection to the user's Chrome no longer works. Tell them so in one sentence and that they can reconnect it in Settings under Computers. " + browserConnectionSteps + " Until then offer to do it as a background task with start_task (surface web). Never call this tool again in this call until they say it is reconnected.", truecase "browser_busy":return "Nothing was done: a background task is using the user's Chrome right now. Tell them so in one sentence and offer to try again when that task finishes; do not call this tool again right away.", true}@@ -59,6 +71,9 @@ type BrowserArguments struct {Ref string `json:"ref"`Text string `json:"text"`Submit bool `json:"submit"`+ // Part and Find choose which part of a long page a look returns.+ Part LoosePart `json:"part"`+ Find string `json:"find"`// Commits is the model's word that a click acts in the user's name.Commits LooseBool `json:"commits"`// Confirmed is the model's word that the user said yes; TeamHub@@ -121,6 +136,9 @@ func BrowserCall(args BrowserArguments) (string, map[string]any, bool) {return "browser_type", map[string]any{"target": ref, "element": "field " + ref, "text": args.Text, "submit": args.Submit}, truecase "back":return "browser_navigate_back", map[string]any{}, true+ case "close":+ // TeamHub picks the tab to close and the one to return to.+ return "browser_tabs", map[string]any{"action": "close"}, true}return "", nil, false}@@ -141,10 +159,139 @@ func BrowserPageURL(page string) string {return ""}-// BrowserPage trims a browser tool result to what a voice model needs: the-// page and its refs, without the code that ran or every link target.-func BrowserPage(text string) (string, bool) {+// BrowserPage trims a browser tool result to what a voice model needs and+// returns the part a look asked for. It drops the code that ran, link+// targets, empty layout lines and citation counts, but no word or ref the page+// shows. A page longer than MaxBrowserPageRunes is cut at line ends into parts+// that each repeat the tabs, address and title above the snapshot; find picks+// the part holding most of its words, otherwise part (from 1) is used.+func BrowserPage(text string, part int, find string) BrowserPageResult {text = ranCodePattern.ReplaceAllString(text, "")text = urlLinePattern.ReplaceAllString(text, "")- return Truncate(strings.TrimSpace(text), MaxBrowserPageRunes)+ text = strings.TrimSpace(text)+ head, body, tail := text, "", ""+ if at := strings.Index(text, snapshotHeading); at >= 0 {+ head = strings.TrimSpace(text[:at])+ body = strings.TrimPrefix(text[at+len(snapshotHeading):], "\n")+ body = strings.TrimPrefix(body, "```yaml\n")+ if end := strings.Index(body, "\n```"); end >= 0 {+ body, tail = body[:end], strings.TrimSpace(body[end+len("\n```"):])+ }+ }+ lines := compactSnapshot(body)+ budget := MaxBrowserPageRunes - utf8.RuneCountInString(head) - utf8.RuneCountInString(tail) - 64+ parts := splitLines(lines, max(budget, MaxBrowserPageRunes/2))+ chosen := min(max(part, 1), len(parts))+ found := true+ if terms := strings.Fields(strings.ToLower(find)); len(terms) > 0 {+ // The model often sends a few words ("ticket price cost"): the part+ // holding most of them wins, the earliest on a tie.+ found = false+ best := 0+ for index, candidate := range parts {+ candidate = strings.ToLower(candidate)+ hits := 0+ for _, term := range terms {+ if strings.Contains(candidate, term) {+ hits+++ }+ }+ if hits > best {+ chosen, found, best = index+1, true, hits+ }+ }+ }+ page := head+ if body != "" {+ page += "\n" + snapshotHeading+ if len(parts) > 1 {+ page += fmt.Sprintf(" (part %d of %d)", chosen, len(parts))+ }+ page += "\n```yaml\n" + parts[chosen-1] + "\n```"+ }+ if tail != "" && chosen == len(parts) {+ page += "\n" + tail+ }+ page, cut := Truncate(page, MaxBrowserPageRunes)+ return BrowserPageResult{Page: page, Part: chosen, Parts: len(parts), Found: found, Truncated: cut}+}++// BrowserPageResult is one part of a page as the live model reads it.+type BrowserPageResult struct {+ Page string+ Part, Parts int+ // Found is false when find matched nothing; Page is then part 1 or the+ // part asked for.+ Found bool+ Truncated bool+}++const snapshotHeading = "### Snapshot"++var (+ // layoutLinePattern is a line of a role that is never pressed, with no+ // name and no text of its own, such as "- generic [ref=e1]:".+ layoutLinePattern = regexp.MustCompile(`^\s*- (?:generic|group|list|listitem|region|navigation|banner|main|contentinfo|complementary|article|section|separator|paragraph|figure|rowgroup)(?: \[[^\]]*\])*:?\s*$`)+ // citationCountPattern is a source badge's count, such as "+2".+ citationCountPattern = regexp.MustCompile(`^\s*- generic(?: \[[^\]]*\])*: "?\+\d+"?\s*$`)+ // pressableCursorPattern marks a link or button as clickable, which its+ // role already says.+ pressableCursorPattern = regexp.MustCompile(`^(\s*- (?:link|button)\b.*?) \[cursor=pointer\]`)+)++// compactSnapshot drops snapshot lines that carry no word the page shows and+// nothing to press.+func compactSnapshot(body string) []string {+ var lines []string+ for line := range strings.SplitSeq(body, "\n") {+ if strings.TrimSpace(line) == "" || citationCountPattern.MatchString(line) {+ continue+ }+ if layoutLinePattern.MatchString(line) && !strings.Contains(line, "[cursor=pointer]") {+ continue+ }+ lines = append(lines, pressableCursorPattern.ReplaceAllString(line, "$1"))+ }+ return lines+}++// splitLines joins lines into parts of at most budget runes, cutting only at+// line ends; a single longer line is cut on its own.+func splitLines(lines []string, budget int) []string {+ parts := []string{""}+ size := 0+ for _, line := range lines {+ length := utf8.RuneCountInString(line) + 1+ if size > 0 && size+length > budget {+ parts = append(parts, "")+ size = 0+ }+ if parts[len(parts)-1] != "" {+ parts[len(parts)-1] += "\n"+ }+ parts[len(parts)-1] += line+ size += length+ }+ return parts+}++// LoosePart reads a part number the model may send as a number or a string.+type LoosePart int++// UnmarshalJSON accepts 2 and "2"; anything else reads as 0, the first part.+func (p *LoosePart) UnmarshalJSON(raw []byte) error {+ var value any+ if err := json.Unmarshal(raw, &value); err != nil {+ return err+ }+ switch typed := value.(type) {+ case float64:+ *p = LoosePart(typed)+ case string:+ number, _ := strconv.Atoi(strings.TrimSpace(typed))+ *p = LoosePart(number)+ default:+ *p = 0+ }+ return nil}diff --git a/apps/teamhub/internal/voicelive/browser_tabs.go b/apps/teamhub/internal/voicelive/browser_tabs.gonew file mode 100644index 00000000..ff9f075d--- /dev/null+++ b/apps/teamhub/internal/voicelive/browser_tabs.go@@ -0,0 +1,34 @@+package voicelive++import (+ "regexp"+ "strconv"+ "strings"+)++var browserTabLinePattern = regexp.MustCompile(`^- (\d+):( \(current\))? \[`)++// BrowserTabs reads the open tabs a browser page text lists: how many there+// are and the index of the current one. A page with a single tab lists none,+// so it reads as one tab, the current one.+func BrowserTabs(page string) (count, current int) {+ _, section, found := strings.Cut(page, "### Open tabs\n")+ if !found {+ return 1, 0+ }+ section, _, _ = strings.Cut(section, "\n###")+ for _, line := range strings.Split(section, "\n") {+ match := browserTabLinePattern.FindStringSubmatch(line)+ if match == nil {+ continue+ }+ count+++ if match[2] != "" {+ current, _ = strconv.Atoi(match[1])+ }+ }+ if count == 0 {+ return 1, 0+ }+ return count, current+}diff --git a/apps/teamhub/internal/voicelive/browser_tabs_test.go b/apps/teamhub/internal/voicelive/browser_tabs_test.gonew file mode 100644index 00000000..3afeb933--- /dev/null+++ b/apps/teamhub/internal/voicelive/browser_tabs_test.go@@ -0,0 +1,21 @@+package voicelive++import "testing"++func TestBrowserTabsReadsTheOpenTabs(t *testing.T) {+ page := "### Open tabs\n" ++ "- 0: (current) [OpenAI news - Search](https://www.bing.com/search?q=OpenAI+news)\n" ++ "- 1: [OpenAI acquires Odessia](https://www.unite.ai/odessia)\n" ++ "### Page\n- Page URL: https://www.bing.com/search?q=OpenAI+news\n" ++ "### Snapshot\n```yaml\n- 2: [not a tab](https://example.com)\n```"+ if count, current := BrowserTabs(page); count != 2 || current != 0 {+ t.Fatalf("count=%d current=%d", count, current)+ }+ switched := "### Open tabs\n- 0: [a](https://a)\n- 1: (current) [b](https://b)\n### Page\n"+ if count, current := BrowserTabs(switched); count != 2 || current != 1 {+ t.Fatalf("count=%d current=%d", count, current)+ }+ if count, current := BrowserTabs("### Page\n- Page URL: https://a\n"); count != 1 || current != 0 {+ t.Fatalf("one tab: count=%d current=%d", count, current)+ }+}diff --git a/apps/teamhub/internal/voicelive/browser_test.go b/apps/teamhub/internal/voicelive/browser_test.goindex 22c7fed8..e7222ccc 100644--- a/apps/teamhub/internal/voicelive/browser_test.go+++ b/apps/teamhub/internal/voicelive/browser_test.go@@ -1,8 +1,10 @@package voiceliveimport (+ "fmt""strings""testing"+ "unicode/utf8")func TestBrowserActionsMapToTheComputersBrowserTools(t *testing.T) {@@ -37,12 +39,64 @@ func TestBrowserActionsMapToTheComputersBrowserTools(t *testing.T) {}func TestBrowserPageKeepsThePageAndDropsNoise(t *testing.T) {- page, truncated := BrowserPage("### Ran Playwright code\n```js\nawait page.goto('x');\n```\n### Page\n- Page URL: https://x\n- link \"News\" [ref=e1]:\n - /url: https://x/news\n")- if truncated || strings.Contains(page, "page.goto") || strings.Contains(page, "/url:") || !strings.Contains(page, `link "News" [ref=e1]`) {- t.Fatalf("page: %q", page)+ shown := BrowserPage("### Ran Playwright code\n```js\nawait page.goto('x');\n```\n### Page\n- Page URL: https://x\n### Snapshot\n```yaml\n- generic [ref=e1]:\n - list [ref=e2]:\n - listitem [ref=e3]:\n - link \"News\" [ref=e4] [cursor=pointer]:\n - /url: https://x/news\n - link [ref=e5] [cursor=pointer]:\n - heading \"Untitled link text\" [level=2] [ref=e6]\n - generic [ref=e7]: Zhihu\n - generic [ref=e8]: \"+2\"\n - strong [aria-hidden] [ref=e9]: Primeval Forest\n - generic [ref=e10] [cursor=pointer]\n```\n", 0, "")+ page := shown.Page+ for _, gone := range []string{"page.goto", "/url:", "[ref=e1]", "[ref=e2]", "[ref=e3]", `"+2"`} {+ if strings.Contains(page, gone) {+ t.Fatalf("%s stays in %q", gone, page)+ }+ }+ // Every word and everything to press stays, hidden-from-reader text too.+ for _, kept := range []string{"Page URL: https://x", `link "News" [ref=e4]`, "link [ref=e5]", `heading "Untitled link text"`, "Zhihu", "Primeval Forest", "[ref=e10] [cursor=pointer]"} {+ if !strings.Contains(page, kept) {+ t.Fatalf("%s is missing from %q", kept, page)+ }+ }+ if strings.Contains(page, `link "News" [ref=e4] [cursor=pointer]`) || shown.Parts != 1 || shown.Truncated {+ t.Fatalf("shown: %+v", shown)+ }+}++func TestBrowserPageSplitsALongPageIntoParts(t *testing.T) {+ var snapshot strings.Builder+ for index := range 400 {+ fmt.Fprintf(&snapshot, "- link \"Result %d about the lake\" [ref=e%d] [cursor=pointer]\n", index, index)+ }+ text := "### Open tabs\n- 0: (current) [Search](https://bing.test)\n### Page\n- Page URL: https://bing.test\n### Snapshot\n```yaml\n" + snapshot.String() + "```\n"+ first := BrowserPage(text, 0, "")+ if first.Parts < 3 || first.Part != 1 || first.Truncated || !strings.Contains(first.Page, "Result 0 about") || strings.Contains(first.Page, "Result 399 about") {+ t.Fatalf("first: part %d of %d, truncated %v", first.Part, first.Parts, first.Truncated)+ }+ last := BrowserPage(text, 99, "")+ if last.Part != last.Parts || !strings.Contains(last.Page, "Result 399 about") {+ t.Fatalf("last: part %d of %d", last.Part, last.Parts)+ }+ // Each part keeps the tabs and address the tab handling reads.+ for _, shown := range []BrowserPageResult{first, last} {+ if !strings.Contains(shown.Page, "### Open tabs") || BrowserPageURL(shown.Page) != "https://bing.test" ||+ !strings.Contains(shown.Page, fmt.Sprintf("(part %d of %d)", shown.Part, shown.Parts)) || utf8.RuneCountInString(shown.Page) > MaxBrowserPageRunes {+ t.Fatalf("part %d: %q", shown.Part, shown.Page[:200])+ }+ }+ found := BrowserPage(text, 0, "result 250 ABOUT")+ if !found.Found || found.Part == 1 || !strings.Contains(found.Page, "Result 250 about") {+ t.Fatalf("find: part %d found %v", found.Part, found.Found)+ }+ if some := BrowserPage(text, 0, "price 250 tickets"); !some.Found || !strings.Contains(some.Page, "Result 250 about") {+ t.Fatalf("some words: part %d found %v", some.Part, some.Found)+ }+ if missing := BrowserPage(text, 2, "no such words"); missing.Found || missing.Part != 2 {+ t.Fatalf("missing: part %d found %v", missing.Part, missing.Found)+ }+}++func TestBrowserArgumentsReadAPartGivenAsText(t *testing.T) {+ var args BrowserArguments+ if err := DecodeArguments(`{"action":"look","part":"2","find":"Zhihu"}`, &args); err != nil || args.Part != 2 || args.Find != "Zhihu" {+ t.Fatalf("args=%+v err=%v", args, err)}- if _, truncated := BrowserPage(strings.Repeat("x", MaxBrowserPageRunes+10)); !truncated {- t.Fatal("long pages are truncated")+ if err := DecodeArguments(`{"action":"look","part":3}`, &args); err != nil || args.Part != 3 {+ t.Fatalf("args=%+v err=%v", args, err)}}@@ -91,7 +145,8 @@ func TestBrowserPageURLReadsWhereThePageIs(t *testing.T) {func TestBrowserConnectionDetailSendsTheUserToConnectChrome(t *testing.T) {for _, code := range []string{"browser_connection_required", "browser_connection_invalid"} {detail, ok := BrowserConnectionDetail(code)- if !ok || !strings.Contains(detail, "Settings under Computers") || !strings.Contains(detail, "start_task") {+ if !ok || !strings.Contains(detail, "Settings under Computers") || !strings.Contains(detail, "Connect Chrome") ||+ !strings.Contains(detail, "Playwright Extension") || !strings.Contains(detail, "start_task") {t.Fatalf("%s: %q", code, detail)}}