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.
fix(computer): hold each launched window and fence script reads by input
jeffrey736cba62043b
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex 8dc19f0b..43658b50 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -398,8 +398,9 @@ of recent reads and moves an Agent's element token, in an input or writteninto a script, to the current snapshot when its row reads the same there.A script's reads after its last input count too: the script guard returnsthem beside the script's value, and the Daemon takes them out of the result.-Only the window-the task opened with `launch_app` is held. A script that names no window in+A read that started before an input finished, such as one beside an input+the script did not await, does not count. Only the windows+the task opened with `launch_app` are held, each to its own tab count. A script that names no window inits `args` is taken to drive that window; a script to another app is neitherpaced nor held, and no script may open an app or URL. The browserwindow is the largest window whose tab strip reads: a starting Chrome can listdiff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.goindex 8431fbb6..d19ae54f 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go@@ -248,9 +248,7 @@ func (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urls}}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()+ c.holdAgentChromeWindow(pid, window.WindowID, tabs, title)note := "This is the Computer's own window in the user's Safari. Safari has no separate profile, so this window has the user's Safari sign-ins; work only in this window, never in the user's other Safari windows. It works while other windows cover it, but only on the desktop (Space) the user is on. Keys without an element go to this window in the background. Type into a page field with type_text and the field's element_token. Move between pages as a person does: through the page's search box, menus and links, back with cmd+[; never type an address into the address bar. Close a tab with its tab's close action, not cmd+w."if started {note = "Opened a new Safari window for the Computer. " + note@@ -416,9 +414,7 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, u// list_windows gives the front tab's title, so the first input reports// only a change it made. A title that moved on since then costs the// first input's check one read of the strip.- c.op.mu.Lock()- c.op.chromeTabs, c.op.chromeTitle, c.op.chromePID, c.op.chromeWindow = tabs, window.Title, pid, window.WindowID- c.op.mu.Unlock()+ c.holdAgentChromeWindow(pid, window.WindowID, tabs, window.Title)note := "This is the Computer's own window in the user's everyday Chrome, with the user's sign-ins; work only in this window, never in the user's other Chrome windows. It works while other windows cover it, but only on the desktop (Space) the user is on. The user's Chrome takes no keys from the Computer, because a key could reach the window the user is typing in: fill a field with set_value, press the page's own buttons, such as its search button, and go back through the page's links. Close a tab with the Close button of its tab; closing the window's last tab closes the window. If a site asks to sign in, ask the user to sign in once in this window."if restored {note = "Started the user's Chrome again with their windows and tabs. " + note@@ -436,6 +432,7 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, u// finds its window. Windows that stay ambiguous are refused.func (c *cuaSession) everydayChromeWindow(ctx context.Context, b agentBrowser, pid int, before map[float64]bool, site string) (listedWindow, int, error) {var seen time.Time+ var candidate float64for deadline := time.Now().Add(sharedBrowserWindowWait); ; {windows, err := c.appWindows(ctx, pid)if err != nil {@@ -451,7 +448,14 @@ func (c *cuaSession) everydayChromeWindow(ctx context.Context, b agentBrowser, pmatching = append(matching, w)}}- if len(fresh) > 0 && seen.IsZero() {+ // The wait counts from when the lone candidate showed: one that+ // left, or another in its place, starts it again.+ switch {+ case len(fresh) == 0:+ seen = time.Time{}+ case len(fresh) == 1 && fresh[0].WindowID != candidate:+ seen, candidate = time.Now(), fresh[0].WindowID+ case seen.IsZero():seen = time.Now()}settled := !seen.IsZero() && time.Since(seen) >= everydayChromeSettlediff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_browser_test.go b/apps/computer/local-daemon/internal/linger/localtools/agent_browser_test.goindex 7e1a0556..7d56ca16 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_browser_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_browser_test.go@@ -21,7 +21,7 @@ func TestCountTabsReadsChromeEdgeAndFirefoxStrips(t *testing.T) {}}// A page's own radio buttons are not tabs.- if got := countTabs("- [9] AXRadioButton \"Small\"\n- [10] AXRadioButton \"Large\"\n- [11] AXButton \"Close\" [actions=[press]]"); got != 1 {+ if got, _ := tabStrip("- [9] AXRadioButton \"Small\"\n- [10] AXRadioButton \"Large\"\n- [11] AXButton \"Close\" [actions=[press]]"); got != 1 {t.Errorf("page radios: %d tabs, want 1", got)}}@@ -84,3 +84,25 @@ func TestSharedWindowsKeepEveryWindowOfTheBrowser(t *testing.T) {t.Fatalf("safari=%+v ok=%v, want Safari's window kept apart", safari, ok)}}++// Each window a task opened stays held to its own tabs after it opens+// another, and an input that names no window goes to the latest one.+func TestAgentChromeHoldsEachWindowTheTaskOpened(t *testing.T) {+ c := &cuaSession{op: &operation{}}+ c.holdAgentChromeWindow(42, 9, 2, "Shop")+ c.holdAgentChromeWindow(42, 13, 1, "News")+ if _, id, held, ok := c.agentChromeTabWindow(float64(42), float64(9)); !ok || id != 9 || held != (heldTabs{count: 2, title: "Shop"}) {+ t.Fatalf("first window id=%v held=%+v ok=%v, want its own tabs", id, held, ok)+ }+ if _, id, held, ok := c.agentChromeTabWindow(float64(42), nil); !ok || id != 13 || held.count != 1 {+ t.Fatalf("no window id=%v held=%+v ok=%v, want the latest", id, held, ok)+ }+ if _, _, _, ok := c.agentChromeTabWindow(float64(42), float64(5)); ok {+ t.Fatal("a window the task did not open is held")+ }+ // A browser started again runs as another pid: no earlier window is held.+ c.holdAgentChromeWindow(77, 3, 1, "Home")+ if _, _, _, ok := c.agentChromeTabWindow(float64(42), float64(9)); ok {+ t.Fatal("a window of the earlier browser is still held")+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.goindex 2c563153..2eddf2a9 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go@@ -196,9 +196,7 @@ func (c *cuaSession) launchAgentChrome(ctx context.Context, b agentBrowser, urlsm.agentChromePID, m.agentChromeChecked = pid, time.Now()m.mu.Unlock()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()+ c.holdAgentChromeWindow(pid, window.WindowID, tabs, title)opened := "No URL was opened, so no tab is this task's."if len(urls) > 0 {opened = "The last one is this task's and in front; pass tabs to a Skill script that checks it."@@ -623,15 +621,10 @@ func (c *cuaSession) agentChromeTabsAndTitle(ctx context.Context, pid int, windoreturn count, state.Structured.Title, close}-// countTabs counts the tab rows of a browser window's tree: a radio button-// outside the page that holds a button, its Close button.-func countTabs(tree string) int {- count, _ := tabStrip(tree)- return count-}--// tabStrip is countTabs with the label of a tab's Close button, which follows-// the user's language; it is empty for a Safari tab, which has none.+// tabStrip counts the tab rows of a browser window's tree, each a radio+// button outside the page that holds a button, its Close button, and returns+// the label of that button, which follows the user's language; it is empty+// for a Safari tab, which has none.func tabStrip(tree string) (count int, close string) {rows := strings.Split(tree, "\n")indent := func(row string) int { return len(row) - len(strings.TrimLeft(row, " ")) }@@ -696,22 +689,45 @@ func (c *cuaSession) agentChromeWindowTitle(ctx context.Context, pid int, windowreturn ""}-// 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-// user's own Safari windows, is not held.-func (c *cuaSession) agentChromeTabWindow(pid, window any) (int, float64, bool) {+// heldTabs is what a window the task opened with launch_app showed after+// the task's last input there: its tab count and its front tab's title. A+// count of 0 holds nothing, as for a strip that could not be read.+type heldTabs struct {+ count int+ title string+}++// holdAgentChromeWindow makes window, in the browser that runs as pid, the+// task's latest window, held to tabs and title. A window the task opened+// before stays held to its own tabs, so going back to it keeps its check;+// a browser that runs as another pid holds none of them.+func (c *cuaSession) holdAgentChromeWindow(pid int, window float64, tabs int, title string) {c.op.mu.Lock()- own, ownWindow := c.op.chromePID, c.op.chromeWindow- c.op.mu.Unlock()+ defer c.op.mu.Unlock()+ if c.op.chromePID != pid || c.op.chromeHeld == nil {+ c.op.chromeHeld = map[float64]heldTabs{}+ }+ c.op.chromeHeld[window] = heldTabs{count: tabs, title: title}+ c.op.chromePID, c.op.chromeWindow = pid, window+}++// agentChromeTabWindow names the window whose tabs hold the task: one it+// opened with launch_app, when an input goes to that browser, or its latest+// such window when the input names none. An input to another app or window,+// such as one of the user's own Safari windows, is not held.+func (c *cuaSession) agentChromeTabWindow(pid, window any) (int, float64, heldTabs, bool) {+ c.op.mu.Lock()+ defer c.op.mu.Unlock()+ own, id := c.op.chromePID, c.op.chromeWindownumber, ok := pid.(float64)if !ok || own == 0 || int(number) != own {- return 0, 0, false+ return 0, 0, heldTabs{}, false}- if id, ok := window.(float64); ok && id != ownWindow {- return 0, 0, false+ if named, ok := window.(float64); ok {+ id = named}- return own, ownWindow, true+ held, ok := c.op.chromeHeld[id]+ return own, id, held, ok}// checkAgentChromeTabs holds the task to the tabs it left: the Computer's@@ -722,14 +738,9 @@ func (c *cuaSession) agentChromeTabWindow(pid, window any) (int, float64, bool)// 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, title := c.op.chromeTabs, c.op.chromeTitle- c.op.mu.Unlock()- if want == 0 {- return nil- }- number, id, ok := c.agentChromeTabWindow(pid, window)- if !ok {+ number, id, held, ok := c.agentChromeTabWindow(pid, window)+ want, title := held.count, held.title+ if !ok || want == 0 {return nil}if title != "" && c.agentChromeWindowTitle(ctx, number, id) == title {@@ -742,7 +753,7 @@ func (c *cuaSession) checkAgentChromeTabs(ctx context.Context, pid, window any)if got == 0 || got == want {if got > 0 {c.op.mu.Lock()- c.op.chromeTitle = front+ c.op.chromeHeld[id] = heldTabs{count: want, title: front}c.op.mu.Unlock()}return nil@@ -763,18 +774,17 @@ func (c *cuaSession) checkAgentChromeTabs(ctx context.Context, pid, window any)// 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 {+ number, id, held, ok := c.agentChromeTabWindow(pid, window)+ before, title := held.count, held.title+ if !ok || before == 0 {return ""}- got, front, close := c.settledAgentChromeTabs(ctx, pid, window, full, before)+ got, front, close := c.settledAgentChromeTabs(ctx, number, id, full, before)if got == 0 {return ""}c.op.mu.Lock()- c.op.chromeTabs, c.op.chromeTitle = got, front+ c.op.chromeHeld[id] = heldTabs{count: got, title: front}c.op.mu.Unlock()switch {case got != before && front == title:@@ -801,11 +811,7 @@ 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, full bool, before int) (int, string, string) {- number, id, ok := c.agentChromeTabWindow(pid, window)- if !ok {- return 0, "", ""- }+func (c *cuaSession) settledAgentChromeTabs(ctx context.Context, number int, id float64, full bool, before int) (int, string, string) {depth := agentChromeTabDepthif full {depth = 0diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script.goindex d6090661..40583afa 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script.go@@ -69,7 +69,10 @@ var scriptForbidden = []string{"delivery_mode", "foreground", "screenshot_out_fi// could not verify in time. A script reads text, so getState takes no// screenshot unless the script asks for one: Cua's default captures one per// read, which took seconds on a busy page. The guard returns the window reads-// made after the script's last input beside its value, under scriptReadsKey,+// made after the script's last input beside its value, under scriptReadsKey:+// a read that started before an input finished, such as one beside an input+// the script did not await, is dropped, since it may show the page before+// that input,// for scriptResultReads to take out. It keeps a read by the pid and window_id// that Cua puts in every getState and get_window_state result, as in a tool// read, so a script read lands on the same window key as the Computer's own. A positive inputLimit paces the script for the@@ -93,7 +96,7 @@ const keys = Object.keys, names = Object.getOwnPropertyNames, proto = Object.getconst apply = Reflect.apply, stringify = JSON.stringify, parse = JSON.parse, test = RegExp.prototype.test, then = Promise.prototype.then, slice = Array.prototype.slice;const plainProtos = [Object.prototype, Array.prototype, null], real = globalThis.cua;const bad = /`+strings.Join(pattern, "|")+`/;-const limit = `+strconv.Itoa(inputLimit)+`, chrome = `+strconv.Itoa(chrome)+`, rest = real.sleep, random = Math.random, floor = Math.floor; let sent = 0, reads = [], readChars = 0;+const limit = `+strconv.Itoa(inputLimit)+`, chrome = `+strconv.Itoa(chrome)+`, rest = real.sleep, random = Math.random, floor = Math.floor; let sent = 0, reads = [], readChars = 0, inputs = 0;const reading = (k, c) => k === "getState" || k === "call" && c[0] === "get_window_state";const keep = r => { if (r === null || typeof r !== "object" || typeof r.snapshot_id !== "string" || typeof r.pid !== "number" || typeof r.window_id !== "number") return; const read = {snapshot_id: r.snapshot_id, pid: r.pid, window_id: r.window_id}; for (const f of ["tree_markdown", "tree_diff", "since", "since_status"]) if (typeof r[f] === "string") read[f] = r[f]; const size = (read.tree_markdown || "").length + (read.tree_diff || "").length; reads[reads.length] = read; readChars += size; while (reads.length > `+strconv.Itoa(scriptReadsKept)+` || readChars > `+strconv.Itoa(scriptReadCharacters)+` && reads.length > 0) { const first = reads[0]; readChars -= (first.tree_markdown || "").length + (first.tree_diff || "").length; reads = apply(slice, reads, [1]); } };const keyOps = {__proto__: null, hotkey: true, type_text: true, press_key: true}, keyMethods = {__proto__: null, hotkey: true, typeText: true, pressKey: true};@@ -116,11 +119,11 @@ define(w, k, {enumerable: true, get() { const v = o[k]; if (typeof v !== "functiif (limit > 0 && k === "typeText") { const given = c.length > 2 && c[2] !== null && typeof c[2] === "object" ? c[2] : {}; const t = {length: 3}; define(t, 0, {value: c[0]}); define(t, 1, {value: c[1]}); define(t, 2, {value: {delay_ms: `+strconv.Itoa(agentChromeTypeDelay)+`, ...given}}); c = t; }if (k === "getState" && (c.length === 0 || c[0] === undefined || c[0] !== null && typeof c[0] === "object" && c[0].include_screenshot === undefined)) { const t = {length: 1}; define(t, 0, {value: {include_screenshot: false, ...(c.length > 0 && c[0] !== undefined ? c[0] : {})}}); c = t; }if (limit > 0 && k === "sleep" && o === real && typeof c[0] === "number" && c[0] > `+strconv.Itoa(scriptSleepLimit)+`) { const t = {length: 1}; define(t, 0, {value: `+strconv.Itoa(scriptSleepLimit)+`}); c = t; }-const run = () => { const r = apply(v, o, c); const seen = x => { if (reading(k, c)) keep(x); return out(x); }; return r !== null && typeof r === "object" && typeof r.then === "function" ? apply(then, r, [seen]) : seen(r); };+const sends = input(k, c), fence = () => { reads = []; readChars = 0; inputs++; };+const run = () => { if (sends) fence(); const at = inputs, r = apply(v, o, c); const seen = x => { if (sends) fence(); else if (reading(k, c) && at === inputs) keep(x); return out(x); }; const missed = e => { if (sends) fence(); throw e; }; return r !== null && typeof r === "object" && typeof r.then === "function" ? apply(then, r, [seen, missed]) : seen(r); };if (launches(k, c)) throw new Error("COMPUTER_SCRIPT_REFUSED: a script opens no app or URL, so the site checks of launch_app hold and the key rule knows every app the script reaches; call launch_app as its own tool");if (keyed(k, c, o)) throw new Error(`+strconv.Quote(everydayChromeKeysRefused)+`);-if (input(k, c)) { reads = []; readChars = 0; }-if (limit <= 0 || !input(k, c)) return run();+if (limit <= 0 || !sends) return run();if (++sent > limit) throw new Error("COMPUTER_SCRIPT_INPUT_LIMIT: a script sends at most " + limit + " inputs to the Computer's own browser; return what you have, look at the window, then continue in a new script");return apply(then, apply(rest, real, [`+strconv.Itoa(scriptInputPauseMin)+` + floor(random() * `+strconv.Itoa(scriptInputPauseSpan)+`)]), [run]); }; }}); } }return freeze(w); };diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.goindex caff3f53..7cbbc31b 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go@@ -102,6 +102,37 @@ func TestScriptGuardPacesInputsForTheComputersChrome(t *testing.T) {}}+// A paced input reaches the driver after its pause, so a read the script+// makes during that pause, beside an input it did not await, shows the page+// before the input and is not returned; a read after the input is.+func TestScriptGuardDropsAReadThatAnInputOverlaps(t *testing.T) {+ node, err := exec.LookPath("node")+ if err != nil {+ t.Skip("node is not installed")+ }+ dir := t.TempDir()+ harness := filepath.Join(dir, "harness.mjs")+ if err := os.WriteFile(harness, []byte(guardHarness), 0o600); err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct{ body, want string }{+ {`const app = await cua.getApp({pid: 4}); const click = app.click(1); await app.getState({query: "rows"}); await click; return "done";`, `"result":"done"`},+ {`const app = await cua.getApp({pid: 4}); await app.click(1); await app.getState({query: "rows"}); return "done";`, `"result":{"__computer_reads":[`},+ } {+ script := filepath.Join(dir, "script.js")+ if err := os.WriteFile(script, []byte(guardedScript(`{}`, tc.body, 42, 2, 0)), 0o600); err != nil {+ t.Fatal(err)+ }+ out, err := exec.Command(node, harness, script).CombinedOutput()+ if err != nil {+ t.Fatalf("node: %v\n%s", err, out)+ }+ if got := string(out); !strings.Contains(got, tc.want) || !strings.Contains(got, "sleep:paced") {+ t.Fatalf("script %s: got %s, want %s", tc.body, got, tc.want)+ }+ }+}+// In the Computer's own browser a script types with a short gap between// characters unless it names one, and one fixed wait lasts at most// scriptSleepLimit: pages are waited for with app.waitFor.diff --git a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.goindex b5335305..11a3fd6b 100644--- a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go@@ -2,15 +2,10 @@ package localtoolsimport ("bufio"- "bytes""context"- "encoding/base64""encoding/json""errors""fmt"- "image"- "image/color"- "image/png""io""net""net/http"@@ -134,35 +129,6 @@ func runToolFixture(mode string) {case "tools/list":result = map[string]any{"tools": []tool{{Name: "click", InputSchema: json.RawMessage(`{"additionalProperties":false,"properties":{"session":{"type":"string"}},"required":["session"],"type":"object"}`)}, {Name: "browser_snapshot", InputSchema: json.RawMessage(`{"additionalProperties":false,"properties":{},"type":"object"}`)}}}case "tools/call":- if strings.HasPrefix(mode, "pages") && request.Params.Name != "start_session" && request.Params.Name != "end_session" && request.Params.Name != "check_permissions" {- // A picture viewer: page k shows one white pixel at (10+2k, 6),- // and keys past page 2 change nothing. Mode pages-refused- // refuses the second key.- marker := os.Getenv("LINGER_LOCAL_TOOL_MARKER")- data, _ := os.ReadFile(marker)- presses := strings.Count(string(data), `"name":"press_key"`)- result = map[string]any{"content": []any{}}- switch request.Params.Name {- case "press_key":- f, _ := os.OpenFile(marker, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)- _ = json.NewEncoder(f).Encode(request.Params)- _ = f.Close()- if mode == "pages-hang" {- // The key never completes, so its outcome stays unknown.- continue- }- if mode == "pages-refused" && presses == 1 {- result = map[string]any{"isError": true, "content": []any{map[string]string{"type": "text", "text": "off_space_or_ax_unresolved"}}}- }- case "get_window_state":- picture := image.NewRGBA(image.Rect(0, 0, 40, 30))- picture.Set(10+2*min(presses, 2), 6, color.White)- var encoded bytes.Buffer- _ = png.Encode(&encoded, picture)- result = map[string]any{"content": []any{map[string]string{"type": "image", "mimeType": "image/png", "data": base64.StdEncoding.EncodeToString(encoded.Bytes())}}}- }- break- }if strings.HasPrefix(mode, "tabs") && request.Params.Name != "start_session" && request.Params.Name != "end_session" && request.Params.Name != "check_permissions" {// The Computer's Chrome: one window, where cmd+t adds a tab and// cmd+w closes one unless mode tabs-refused refuses it, and each@@ -1112,13 +1078,13 @@ func TestLocalToolCuaMacAgentChromeStopsWhenSomeoneElseChangesTheTabs(t *testingagentChromePID = 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.chromePID, c.op.chromeWindow = 1, 42, 9+ c.holdAgentChromeWindow(42, 9, 1, "")// The task's own cmd+t opens a tab that is the task's.if _, err := c.call(t.Context(), "hotkey", json.RawMessage(`{"pid":42,"window_id":9,"keys":["cmd","t"]}`)); err != nil {t.Fatal(err)}- if c.op.chromeTabs != 2 {- t.Fatalf("tabs after the task's own tab=%d, want 2", c.op.chromeTabs)+ if c.op.chromeHeld[9].count != 2 {+ t.Fatalf("tabs after the task's own tab=%d, want 2", c.op.chromeHeld[9].count)}// A tab someone else opens stops the task before its next input.f, err := os.OpenFile(marker, os.O_APPEND|os.O_WRONLY, 0o600)@@ -1157,7 +1123,7 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsOwnInputChangesLate(t *testing.T)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.chromePID, c.op.chromeWindow = 1, 42, 9+ c.holdAgentChromeWindow(42, 9, 1, "")// The click below presses a row of page text, which lists no press.c.snapshots = newSnapshotRows()c.snapshots.record(windowRead{Snapshot: "s1", PID: 42, Window: 9, Tree: `- [1] AXStaticText = "Sort by time"`})@@ -1173,8 +1139,8 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsOwnInputChangesLate(t *testing.T)if err != nil {t.Fatal(err)}- if c.op.chromeTabs != step.want {- t.Fatalf("tabs after the task's own %s=%d, want %d", step.keys, c.op.chromeTabs, step.want)+ if c.op.chromeHeld[9].count != step.want {+ t.Fatalf("tabs after the task's own %s=%d, want %d", step.keys, c.op.chromeHeld[9].count, step.want)}if !strings.Contains(string(result), step.note) {t.Fatalf("result after the task's own %s=%s, want note %s", step.keys, result, step.note)@@ -1210,7 +1176,7 @@ func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testingagentChromePID = 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+ c.holdAgentChromeWindow(42, 9, 1, "Tab 0")reads := func() []string {var got []stringfor _, call := range fixtureCalls(t, marker) {@@ -1255,7 +1221,7 @@ func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testing// result reports the count without saying the input closed it. Fewer// tabs in a bounded read are proven by whole reads, since a strip split// across the bound would read as fewer too.- c.op.chromeTabs = 2+ c.op.chromeHeld[9] = heldTabs{count: 2, title: "Tab 0"}before = len(reads())result, err := c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`))if err != nil {@@ -1268,7 +1234,7 @@ func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testingt.Fatalf("result=%s, want the neutral note %s", result, note)}// A front tab that changed since the last input is read whole first.- c.op.chromeTitle = "Elsewhere"+ c.op.chromeHeld[9] = heldTabs{count: c.op.chromeHeld[9].count, title: "Elsewhere"}if _, err := c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`)); err != nil {t.Fatal(err)}@@ -1295,7 +1261,7 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsScriptsChange(t *testing.T) {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.chromePID, c.op.chromeWindow = 1, 42, 9+ c.holdAgentChromeWindow(42, 9, 1, "")// change writes a tab change to the fixture's record; shown says whether// the next read already shows it, as for a change made between inputs.change := func(keys string, shown bool) {@@ -1323,8 +1289,8 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsScriptsChange(t *testing.T) {if _, err := c.call(t.Context(), "run_script", json.RawMessage(step.script)); err != nil {t.Fatalf("script that sent %s: %v", step.keys, err)}- if c.op.chromeTabs != step.want {- t.Fatalf("tabs after the script that sent %s=%d, want %d", step.keys, c.op.chromeTabs, step.want)+ if c.op.chromeHeld[9].count != step.want {+ t.Fatalf("tabs after the script that sent %s=%d, want %d", step.keys, c.op.chromeHeld[9].count, step.want)}if _, err := c.call(t.Context(), "click", click); err != nil {t.Fatalf("input after the script that sent %s: %v", step.keys, err)@@ -1361,7 +1327,7 @@ func TestLocalToolCuaMacAgentChromeHoldsOnlyItsOwnWindow(t *testing.T) {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.chromePID, c.op.chromeWindow = 2, 42, 9+ c.holdAgentChromeWindow(42, 9, 2, "")// A script to another app while that browser runs is neither paced nor// held to its tabs, though the browser shows another count.if _, err := c.call(t.Context(), "run_script", json.RawMessage(`{"script":"return 1","args":{"pid":99}}`)); err != nil {@@ -1370,8 +1336,8 @@ func TestLocalToolCuaMacAgentChromeHoldsOnlyItsOwnWindow(t *testing.T) {if calls := fixtureCalls(t, marker); len(calls) == 0 || !strings.Contains(fmt.Sprint(calls[len(calls)-1]), "const limit = 0,") {t.Fatalf("calls=%v, want an unpaced script", calls)}- if c.op.chromeTabs != 2 {- t.Fatalf("tabs=%d after a script to another app, want 2", c.op.chromeTabs)+ if c.op.chromeHeld[9].count != 2 {+ t.Fatalf("tabs=%d after a script to another app, want 2", c.op.chromeHeld[9].count)}// A task stopped by a check opens no URL there either.c.op.chromeBlocked = "captcha"@@ -2114,8 +2080,8 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *t}// launch_app keeps the front tab's title from list_windows, so the// first input, which changes no tab, reports no change.- if c.op.chromeTitle != "Tab 0" {- t.Fatalf("front title after launch_app=%q, want Tab 0", c.op.chromeTitle)+ if got := c.op.chromeHeld[12].title; got != "Tab 0" {+ t.Fatalf("front title after launch_app=%q, want Tab 0", got)}if result, err := c.call(t.Context(), "set_value", json.RawMessage(`{"pid":42,"window_id":12,"value":"kettle","element_token":"s1:1"}`)); err != nil || strings.Contains(string(result), "tab in front") {t.Fatalf("set_value result=%s err=%v, want no tab note", result, err)@@ -2222,7 +2188,7 @@ func TestLocalToolCuaMacAgentChromeOpensAFreshWindowForAnUnreadableOne(t *testint.Fatalf("result=%s, want the note for a started browser", result)}// Typing there is paced at the default speed unless the Agent sets one.- c.op.chromeTabs, c.op.chromePID, c.op.chromeWindow = 1, 42, 9+ c.holdAgentChromeWindow(42, 9, 1, "")if _, err := c.call(t.Context(), "type_text", json.RawMessage(`{"pid":42,"window_id":9,"text":"kettle","element_token":"s1:1"}`)); err != nil {t.Fatal(err)}diff --git a/apps/computer/local-daemon/internal/linger/localtools/manager.go b/apps/computer/local-daemon/internal/linger/localtools/manager.goindex 26393aee..1ac282b4 100644--- a/apps/computer/local-daemon/internal/linger/localtools/manager.go+++ b/apps/computer/local-daemon/internal/linger/localtools/manager.go@@ -229,13 +229,11 @@ type operation struct {chromeInputs intchromeBlocked stringchromeSites map[string]bool- // chromeTabs is the tab count of the Computer's own browser after this- // task's last input there, and chromePID and chromeWindow the browser- // and window this task opened with launch_app; see checkAgentChromeTabs.- // chromeTitle is the front tab's title read with chromeTabs, from- // launch_app on. Guarded by mu.- chromeTabs int- chromeTitle string+ // chromeHeld holds each window this task opened with launch_app to+ // what it showed after the task's last input there, chromePID is the+ // browser they belong to and chromeWindow the latest of them; see+ // checkAgentChromeTabs. Guarded by mu.+ chromeHeld map[float64]heldTabschromePID intchromeWindow float64closeOnce sync.Once