Skip to content

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.

perf(computer): read the browser's tab strip only as far as it needs

jeffrey37d3931ae549
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md
index 9a1d7be0..97fd7471 100644
--- a/apps/computer/local-daemon/README.md
+++ b/apps/computer/local-daemon/README.md
@@ -376,7 +376,11 @@ the task; `rate_limited` also puts the site (its registrable domain) in a
Once a task opens a site there, the browser tools refuse that site for the
rest of the task, and `launch_app` refuses to open it in another browser.
A change in the number of tabs between the task's inputs stops the task with
-`COMPUTER_TAB_CHANGED`, because the next input could reach another page. A
+`COMPUTER_TAB_CHANGED`, because the next input could reach another page. The
+Daemon reads the tab strip before an input only when the window's title in
+`list_windows` differs from the front tab's title after the last input; after
+an input it reads the strip only to its depth, unless a script returned reads
+the Agent may act on, and not at all after a script that sent no input. A
tab that the task's own input or script opens or closes is the task's: the
task holds the browser's input lease, and the count is kept once the tab strip
settles, since the browser shows such a tab a moment later. The input's
diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go
index c4ed7799..422d88a3 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go
@@ -247,7 +247,7 @@ func (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urls
return nil, err
}
}
- tabs, title, _ := c.agentChromeTabsAndTitle(ctx, pid, window.WindowID)
+ tabs, title, _ := c.agentChromeTabsAndTitle(ctx, pid, window.WindowID, 0)
c.op.mu.Lock()
c.op.chromeTabs, c.op.chromeTitle, c.op.chromePID, c.op.chromeWindow = tabs, title, pid, window.WindowID
c.op.mu.Unlock()
@@ -415,7 +415,7 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, u
m.setSharedWindow(b.Bundle, pid, window.WindowID)
// The front tab's title, so the first input reports only a change it
// made; the window search above keeps no title.
- _, title, _ := c.agentChromeTabsAndTitle(ctx, pid, window.WindowID)
+ _, title, _ := c.agentChromeTabsAndTitle(ctx, pid, window.WindowID, 0)
c.op.mu.Lock()
c.op.chromeTabs, c.op.chromeTitle, c.op.chromePID, c.op.chromeWindow = tabs, title, pid, window.WindowID
c.op.mu.Unlock()
diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go
index fec93667..080736f8 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go
@@ -195,7 +195,7 @@ func (c *cuaSession) launchAgentChrome(ctx context.Context, b agentBrowser, urls
m.mu.Lock()
m.agentChromePID, m.agentChromeChecked = pid, time.Now()
m.mu.Unlock()
- tabs, title, _ := c.agentChromeTabsAndTitle(ctx, pid, window.WindowID)
+ tabs, title, _ := c.agentChromeTabsAndTitle(ctx, pid, window.WindowID, 0)
c.op.mu.Lock()
c.op.chromeTabs, c.op.chromeTitle, c.op.chromePID, c.op.chromeWindow = tabs, title, pid, window.WindowID
c.op.mu.Unlock()
@@ -577,15 +577,25 @@ func (c *cuaSession) agentChromeKeys(ctx context.Context, arguments map[string]a
// It returns 0 when the read fails or is cut short: the tab strip follows the
// page in the tree, so a cut read may miss it.
func (c *cuaSession) agentChromeTabs(ctx context.Context, pid int, window float64) int {
- count, _, _ := c.agentChromeTabsAndTitle(ctx, pid, window)
+ count, _, _ := c.agentChromeTabsAndTitle(ctx, pid, window, 0)
return count
}
+// agentChromeTabDepth bounds a read of the tab strip alone: the strip lies
+// within four levels of the window, while a shop's page runs much deeper, so
+// the bounded read skips most of the page.
+const agentChromeTabDepth = 6
+
// agentChromeTabsAndTitle is agentChromeTabs with the title of the window's
-// front tab and the label of a tab's Close button, from the same read.
-func (c *cuaSession) agentChromeTabsAndTitle(ctx context.Context, pid int, window float64) (int, string, string) {
- read, err := c.client.request(ctx, "tools/call", map[string]any{"name": "get_window_state", "arguments": map[string]any{
- "pid": pid, "window_id": window, "include_screenshot": false, "max_elements": 6000, "timeout_ms": 6000, "session": c.label}})
+// front tab and the label of a tab's Close button, from the same read. A
+// depth above 0 bounds the read; Cua then keeps only the rows within it, so
+// an earlier token of a deeper row cannot be carried over that read.
+func (c *cuaSession) agentChromeTabsAndTitle(ctx context.Context, pid int, window float64, depth int) (int, string, string) {
+ arguments := map[string]any{"pid": pid, "window_id": window, "include_screenshot": false, "max_elements": 6000, "timeout_ms": 6000, "session": c.label}
+ if depth > 0 {
+ arguments["max_depth"] = depth
+ }
+ read, err := c.client.request(ctx, "tools/call", map[string]any{"name": "get_window_state", "arguments": arguments})
if err != nil {
slog.Warn("agent_browser.tabs_unread", "pid", pid, "window_id", window, "error", err)
return 0, "", ""
@@ -665,6 +675,27 @@ func tabStrip(tree string) (count int, close string) {
return count, close
}
+// agentChromeWindowTitle returns the title list_windows gives window, which
+// for a browser is its front tab's, or "" when it is not listed.
+func (c *cuaSession) agentChromeWindowTitle(ctx context.Context, pid int, window float64) string {
+ result, err := c.client.request(ctx, "tools/call", map[string]any{"name": "list_windows", "arguments": map[string]any{"pid": pid}})
+ if err != nil {
+ return ""
+ }
+ var listed struct {
+ Structured struct {
+ Windows []listedWindow `json:"windows"`
+ } `json:"structuredContent"`
+ }
+ _ = json.Unmarshal(result, &listed)
+ for _, w := range listed.Structured.Windows {
+ if w.WindowID == window {
+ return w.Title
+ }
+ }
+ return ""
+}
+
// agentChromeTabWindow names the window whose tabs hold the task: the one
// it opened with launch_app, when an input goes to that browser and names
// no other window. An input to another app or window, such as one of the
@@ -688,10 +719,11 @@ func (c *cuaSession) agentChromeTabWindow(pid, window any) (int, float64, bool)
// different count means someone else opened or closed a tab, and the tab in
// front may not be this task's. The task then stops, as after a reported
// check. A strip that cannot be read, or a task that has no count yet, is not
-// held.
+// held. The strip is read only when the window's title, which list_windows
+// gives without a read, differs from the front tab's title after that input.
func (c *cuaSession) checkAgentChromeTabs(ctx context.Context, pid, window any) error {
c.op.mu.Lock()
- want := c.op.chromeTabs
+ want, title := c.op.chromeTabs, c.op.chromeTitle
c.op.mu.Unlock()
if want == 0 {
return nil
@@ -700,8 +732,19 @@ func (c *cuaSession) checkAgentChromeTabs(ctx context.Context, pid, window any)
if !ok {
return nil
}
- got := c.agentChromeTabs(ctx, number, id)
+ if title != "" && c.agentChromeWindowTitle(ctx, number, id) == title {
+ // The front tab still shows what this task's last input left. A
+ // tab someone opened behind it changes nothing this input reaches,
+ // and a full read here would cost a walk of the page.
+ return nil
+ }
+ got, front, _ := c.agentChromeTabsAndTitle(ctx, number, id, 0)
if got == 0 || got == want {
+ if got > 0 {
+ c.op.mu.Lock()
+ c.op.chromeTitle = front
+ c.op.mu.Unlock()
+ }
return nil
}
c.op.mu.Lock()
@@ -716,15 +759,17 @@ func (c *cuaSession) checkAgentChromeTabs(ctx context.Context, pid, window any)
// other task changes the tabs. Only a task that opened its tab with
// launch_app holds a count. It returns a note on what the input changed in
// the window, from the same read: a click result says nothing of where the
-// page went, and the Agent read the window only to learn that.
-func (c *cuaSession) recordAgentChromeTabs(ctx context.Context, pid, window any) string {
+// page went, and the Agent read the window only to learn that. Only full
+// keeps the read whole: after a script whose reads the Agent may act on, a
+// bounded read would drop their rows from Cua's snapshot.
+func (c *cuaSession) recordAgentChromeTabs(ctx context.Context, pid, window any, full bool) string {
c.op.mu.Lock()
before, title := c.op.chromeTabs, c.op.chromeTitle
c.op.mu.Unlock()
if before == 0 {
return ""
}
- got, front, close := c.settledAgentChromeTabs(ctx, pid, window)
+ got, front, close := c.settledAgentChromeTabs(ctx, pid, window, full)
if got == 0 {
return ""
}
@@ -751,17 +796,26 @@ func (c *cuaSession) recordAgentChromeTabs(ctx context.Context, pid, window any)
// a moment after the input that opened or closed it returns, and the next
// input's pause already covers that wait. The count is 0 when the strip
// cannot be read.
-func (c *cuaSession) settledAgentChromeTabs(ctx context.Context, pid, window any) (int, string, string) {
+func (c *cuaSession) settledAgentChromeTabs(ctx context.Context, pid, window any, full bool) (int, string, string) {
number, id, ok := c.agentChromeTabWindow(pid, window)
if !ok {
return 0, "", ""
}
- got, title, close := c.agentChromeTabsAndTitle(ctx, number, id)
+ depth := agentChromeTabDepth
+ if full {
+ depth = 0
+ }
+ got, title, close := c.agentChromeTabsAndTitle(ctx, number, id, depth)
+ if got == 0 && depth > 0 {
+ // A strip deeper than the bound, as in a browser laid out otherwise.
+ depth = 0
+ got, title, close = c.agentChromeTabsAndTitle(ctx, number, id, depth)
+ }
for range 3 {
if got == 0 || sleepContext(ctx, inputSettle) != nil {
break
}
- next, nextTitle, nextClose := c.agentChromeTabsAndTitle(ctx, number, id)
+ next, nextTitle, nextClose := c.agentChromeTabsAndTitle(ctx, number, id, depth)
title, close = nextTitle, nextClose
if next == got {
break
diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome_pace.go b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome_pace.go
index 20ad7b36..f4f28c9e 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome_pace.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome_pace.go
@@ -37,6 +37,27 @@ const (
agentChromeCooldown = time.Hour
)
+// scriptInputsSent counts the inputs in a script result's call log; known is
+// false when the result holds no call log to count.
+func scriptInputsSent(result json.RawMessage) (sent int, known bool) {
+ var reply struct {
+ Structured struct {
+ Calls *[]struct {
+ Op string `json:"op"`
+ } `json:"calls"`
+ } `json:"structuredContent"`
+ }
+ if json.Unmarshal(result, &reply) != nil || reply.Structured.Calls == nil {
+ return 0, false
+ }
+ for _, call := range *reply.Structured.Calls {
+ if inputTools[call.Op] || call.Op == "set_value" {
+ sent++
+ }
+ }
+ return sent, true
+}
+
// agentChromePause is the gap kept between two inputs to the Computer's own
// browser; a test replaces it.
var agentChromePause = func() time.Duration {
@@ -203,22 +224,7 @@ func (c *cuaSession) paceAgentChrome(ctx context.Context, reserve int) (int, err
// lists them, to both budgets. A failed call may still have taken effect, so
// every listed input counts.
func (c *cuaSession) countScriptInputs(result json.RawMessage) {
- var reply struct {
- Structured struct {
- Calls []struct {
- Op string `json:"op"`
- } `json:"calls"`
- } `json:"structuredContent"`
- }
- if json.Unmarshal(result, &reply) != nil {
- return
- }
- sent := 0
- for _, call := range reply.Structured.Calls {
- if inputTools[call.Op] || call.Op == "set_value" {
- sent++
- }
- }
+ sent, _ := scriptInputsSent(result)
if sent == 0 {
return
}
diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.go
index 121910ea..45191934 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/cua.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/cua.go
@@ -557,9 +557,16 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessage
if paced && name == "run_script" && err == nil {
c.countScriptInputs(result)
}
- // A script that throws has still sent the inputs before the throw.
- if paced && (err == nil || name == "run_script") {
- if note := c.recordAgentChromeTabs(ctx, target["pid"], target["window_id"]); note != "" && result != nil {
+ // A script that throws has still sent the inputs before the throw. One
+ // that sent none changed no tab, and a read of the strip after it would
+ // stale the tokens its queries returned, which the Daemon keeps no rows of.
+ sentNone := false
+ if name == "run_script" {
+ sent, known := scriptInputsSent(result)
+ sentNone = known && sent == 0
+ }
+ if paced && (err == nil || name == "run_script") && !sentNone {
+ if note := c.recordAgentChromeTabs(ctx, target["pid"], target["window_id"], len(scriptReads) > 0); note != "" && result != nil {
result = withNote(result, note)
}
}
@@ -1318,7 +1325,7 @@ func (c *cuaSession) locate(ctx context.Context, name string, arguments map[stri
}
read, err := c.client.request(ctx, "tools/call", map[string]any{"name": "get_window_state", "arguments": map[string]any{
"pid": arguments["pid"], "window_id": arguments["window_id"], "tree_format": "elements", "include_screenshot": false,
- "max_elements": 3000, "timeout_ms": float64(windowReadTimeoutMs), "session": arguments["session"]}})
+ "max_elements": 6000, "timeout_ms": float64(windowReadTimeoutMs), "session": arguments["session"]}})
if err != nil {
return err
}
diff --git a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go
index 027736a8..fcff87db 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go
@@ -206,6 +206,15 @@ func runToolFixture(mode string) {
}
result = map[string]any{"content": []any{}}
switch request.Params.Name {
+ case "run_script":
+ if mode == "tabs-titled" {
+ // The driver's call log: a click when the script clicks.
+ calls := []any{}
+ if script, _ := request.Params.Arguments["script"].(string); strings.Contains(script, "app.click(") {
+ calls = append(calls, map[string]any{"op": "click"})
+ }
+ result = map[string]any{"content": []any{}, "structuredContent": map[string]any{"calls": calls}}
+ }
case "hotkey":
if mode == "tabs-off-space" && strings.Count(string(data), `"keys":["cmd","t"]`) == 0 {
result = map[string]any{"isError": true, "content": []any{map[string]string{"type": "text", "text": "off_space_or_ax_unresolved"}}}
@@ -214,7 +223,12 @@ func runToolFixture(mode string) {
result = map[string]any{"isError": true, "content": []any{map[string]string{"type": "text", "text": "keys were not delivered"}}}
}
case "list_windows":
- windows := []any{map[string]any{"pid": 42, "window_id": 9, "title": "b", "z_index": 3, "is_on_screen": true, "bounds": map[string]any{"width": 800, "height": 600}}}
+ title := "b"
+ if mode == "tabs-titled" {
+ // The window's title is its front tab's, as Chrome's is.
+ title = fmt.Sprintf("Tab %d", tabs-1)
+ }
+ windows := []any{map[string]any{"pid": 42, "window_id": 9, "title": title, "z_index": 3, "is_on_screen": true, "bounds": map[string]any{"width": 800, "height": 600}}}
if strings.HasPrefix(mode, "tabs-everyday") && strings.Count(string(data), `"name":"open"`) >= 2 {
// After the start and the command line, a window of
// the user's that Chrome restored late lists before
@@ -234,6 +248,13 @@ func runToolFixture(mode string) {
result = map[string]any{"content": []any{}, "structuredContent": map[string]any{"tree_markdown": "", "degraded_reason": "ax_window_unresolved"}}
break
}
+ if mode == "tabs-titled" {
+ // Each read logs its depth bound, 0 for a whole read.
+ depth, _ := request.Params.Arguments["max_depth"].(float64)
+ f, _ := os.OpenFile(marker, os.O_APPEND|os.O_WRONLY, 0o600)
+ _, _ = fmt.Fprintf(f, `{"name":"read","arguments":{"max_depth":%v}}`+"\n", depth)
+ _ = f.Close()
+ }
var tree strings.Builder
for i := range tabs {
fmt.Fprintf(&tree, "- [%d] AXRadioButton \"Tab %d\"\n- [%d] AXButton \"Close\" [actions=[press]]\n", 2*i, i, 2*i+1)
@@ -1170,6 +1191,78 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsOwnInputChangesLate(t *testing.T)
}
}
+// An input whose window still shows the front tab the last input left skips
+// the read of the tab strip before it, and the reads after it stop at the
+// strip's depth, unless a script's reads must stay in Cua's snapshot.
+func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("the Computer's own Chrome is macOS only")
+ }
+ inputSettle = 0
+ t.Cleanup(func() { inputSettle = 300 * time.Millisecond })
+ pause := agentChromePause
+ agentChromePause = func() time.Duration { return 0 }
+ t.Cleanup(func() { agentChromePause = pause })
+ marker := filepath.Join(t.TempDir(), "calls.jsonl")
+ c := cuaFixtureSession(t, "tabs-titled", marker)
+ original := agentChromePID
+ agentChromePID = func(context.Context, string) (int, string, error) { return 42, "--mute-audio", nil }
+ t.Cleanup(func() { agentChromePID = original })
+ c.op.manager.agentChromeOwner = c.op
+ c.op.chromeTabs, c.op.chromeTitle, c.op.chromePID, c.op.chromeWindow = 1, "Tab 0", 42, 9
+ reads := func() []string {
+ var got []string
+ for _, call := range fixtureCalls(t, marker) {
+ if call.Name == "read" {
+ got = append(got, fmt.Sprint(call.Arguments["max_depth"]))
+ } else {
+ got = append(got, call.Name)
+ }
+ }
+ return got
+ }
+ if _, err := c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`)); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := reads(), []string{"click", "6", "6"}; !slices.Equal(got, want) {
+ t.Fatalf("calls=%v, want the click alone, then two bounded reads", got)
+ }
+ // After a script that returned reads, the reads after it are whole.
+ if note := c.recordAgentChromeTabs(t.Context(), float64(42), float64(9), true); note != "" {
+ t.Fatalf("note=%q, want none", note)
+ }
+ if got := reads(); !slices.Equal(got[len(got)-2:], []string{"0", "0"}) {
+ t.Fatalf("calls=%v, want two whole reads after a script with reads", got)
+ }
+ // A script that sent no input reads no tab strip after it, so the
+ // tokens its queries returned stay current; one that clicked does.
+ before := len(reads())
+ if _, err := c.call(t.Context(), "run_script", json.RawMessage(`{"script":"return 1"}`)); err != nil {
+ t.Fatal(err)
+ }
+ if got := reads()[before:]; !slices.Equal(got, []string{"run_script"}) {
+ t.Fatalf("calls for a script with no input=%v, want the script alone", got)
+ }
+ before = len(reads())
+ if _, err := c.call(t.Context(), "run_script", json.RawMessage(`{"script":"const app = await cua.getApp({pid: 42, windowId: 9}); await app.click(\"s1:1\"); return 1"}`)); err != nil {
+ t.Fatal(err)
+ }
+ if got := reads()[before:]; !slices.Equal(got, []string{"run_script", "6", "6"}) {
+ t.Fatalf("calls for a script that clicked=%v, want two bounded reads after it", got)
+ }
+ // A front tab that changed since the last input is read whole first.
+ c.op.chromeTitle = "Elsewhere"
+ if _, err := c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`)); err != nil {
+ t.Fatal(err)
+ }
+ if got := reads(); !slices.Equal(got[len(got)-4:], []string{"0", "click", "6", "6"}) {
+ t.Fatalf("calls=%v, want a whole read before the click", got)
+ }
+ if err := c.drain(); err != nil {
+ t.Fatal(err)
+ }
+}
+
func TestLocalToolCuaMacAgentChromeKeepsTabsItsScriptsChange(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("the Computer's own Chrome is macOS only")