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): find the Computer's Chrome window and refuse keys in any language and from any script
jeffrey1f5ddec49d97
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex db5ac5d5..d335a62a 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -334,19 +334,28 @@ starts with it, and one running without it returns`COMPUTER_BROWSER_RESTART_REQUIRED`. The Daemon never quits the user's Chrome,because a quit loses text typed into a page and not yet sent: the Agent asksthe user to quit Chrome, and the next `launch_app` starts it with the flag and-`--restore-last-session`. The Computer's window is the new window with one tab-whose address bar shows the site just opened, so a window the user opens or-Chrome restores meanwhile is never taken for it. The Daemon finds the running-Chrome by its executable wherever the app is installed. The user's Chrome-takes no keys from the Computer (`COMPUTER_KEYS_REFUSED`), in any of its-windows, in tool calls, `run_actions` steps, paged `recognize_text` reads and-scripts that target it: a shortcut runs as a menu command in the Chrome window-that has the keyboard, and Cua types text as keys that all read as the A key.-Only a plain key bound to an element of the Computer's window goes, and Cua-sends it only when no other Chrome window could take it. The Agent fills fields with+`--restore-last-session`. The Daemon records that question in+`computer-tools/everyday-chrome-quit` in the state directory, so a Daemon+restart keeps it, and removes the record once Chrome started. Before the+Computer opens its window, it waits until the list of Chrome windows stops+changing, so every restored window is there. The Computer's window is the new+window with one tab: the one whose address bar shows the site just opened, or+the only new window when the home page moved to another site. Two new windows+of the site are refused with `COMPUTER_WINDOW_AMBIGUOUS`. The address bar and+the tabs are found by role and place in the window, not by their names, which+follow the user's language. The Daemon finds the running Chrome by its+executable wherever the app is installed. The user's Chrome takes no keys from+the Computer (`COMPUTER_KEYS_REFUSED`), in any of its windows, in tool calls,+`run_actions` steps, paged `recognize_text` reads and every script: a shortcut+runs as a menu command in the Chrome window that has the keyboard, and Cua+types text as keys that all read as the A key. A key goes to the window its+`element_token` was read from, and a key that names no app is refused while+that Chrome runs. Only a plain key bound to an element of the Computer's+window goes, and Cua sends it only when no other Chrome window could take it.+The Agent fills fields with`set_value`, presses the page's buttons and goes back through its links.-The separate Chrome profile earlier versions used, `computer-tools/agent-chrome`,-is removed when the Daemon starts and that Chrome no longer runs.+The Daemon removes the separate Chrome profile `computer-tools/agent-chrome`+when it starts, after quitting the Chrome that still runs on it.Edge and Firefox each run as a separate instance with their own profile under`computer-tools/agent-<browser>` in the state directory, so the user signs inthere once. Safari cannot run a second profile; the Computer uses its owndiff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.goindex a217c74f..76326860 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go@@ -48,8 +48,8 @@ type agentBrowser struct {Shared bool// Everyday marks the user's everyday Chrome: the Computer opens each// site in a window of its own there, by command line, and the running- // instance must carry Settings, so a covered window keeps working. One- // started without them restarts only after the user agreed.+ // instance must carry Settings, so a covered window keeps working. The+ // user quits one started without them; the Computer never does.Everyday bool}@@ -194,8 +194,8 @@ func (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urlsreturn nil, err}m.mu.Lock()- own := m.sharedBrowserWindow- if m.sharedBrowserPID != pid {+ own := m.sharedWindows[b.Bundle].Window+ if m.sharedWindows[b.Bundle].PID != pid {own = 0}m.mu.Unlock()@@ -238,9 +238,7 @@ func (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urls// window's accessibility tree resolves; opening a tab waits for it.c.agentChromeTabsUntil(ctx, pid, window.WindowID, agentSafariWindowWait, func(n int) bool { return n > 0 })}- m.mu.Lock()- m.sharedBrowserBundle, m.sharedBrowserPID, m.sharedBrowserWindow = b.Bundle, pid, window.WindowID- m.mu.Unlock()+ m.setSharedWindow(b.Bundle, pid, window.WindowID)for _, url := range urls {if err := c.agentChromeOpenTab(ctx, b, pid, window.WindowID, offSpace(window), url); err != nil {return nil, err@@ -316,7 +314,9 @@ var everydayChromePID = func(ctx context.Context) (int, string, error) {// ends where the first argument starts.func everydayChromeCommand(args string) bool {index := strings.Index(args, everydayChromeExecutable)- if !strings.HasPrefix(args, "/") || index < 0 {+ // A command that only names Chrome's path as an argument has an option+ // or another path before it.+ if !strings.HasPrefix(args, "/") || index < 0 || strings.Contains(args[:index], " -") || strings.Contains(args[:index], " /") {return false}rest := args[index+len(everydayChromeExecutable):]@@ -360,19 +360,19 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, ureturn nil, err}if pid > 0 && !b.startedWith(command) {- m.mu.Lock()- m.everydayChromeQuitAsked = true- m.mu.Unlock()+ if err := m.everydayChromeQuitAsked(true); err != nil {+ return nil, err+ }return nil, fmt.Errorf("%s: %w", everydayChromeQuit, errNotSent)}restored := falseif pid == 0 {// After the user quit Chrome for the Computer, it reopens their- // windows and tabs, as the question to quit promised.- m.mu.Lock()- restored, m.everydayChromeQuitAsked = m.everydayChromeQuitAsked, false- m.mu.Unlock()- args := append([]string{"-g", "-b", b.Bundle, "--args"}, b.Settings...)+ // windows and tabs, as the question to quit promised. A second+ // instance is started (-n) so a Chrome on another profile, such as+ // a test browser, cannot take the command and drop the settings.+ restored = m.quitAsked()+ args := append([]string{"-n", "-g", "-b", b.Bundle, "--args"}, b.Settings...)if restored {args = append(args, "--restore-last-session")}@@ -382,6 +382,9 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, uif pid, err = c.waitEverydayChrome(ctx); err != nil {return nil, err}+ if err := m.everydayChromeQuitAsked(false); err != nil {+ return nil, err+ }}windows, err := c.appWindows(ctx, pid)if err != nil {@@ -398,53 +401,77 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, uif output, err := agentChromeOpen(ctx, open); err != nil {return nil, fmt.Errorf("launch_app: %s: %w", strings.TrimSpace(string(output)), err)}- // The Computer's window is a new window with one tab whose address bar- // shows the site just opened. A window the user opens meanwhile, or one- // Chrome restores late, fails that test, so it is never taken for it.- var window listedWindow- tabs := 0- for deadline := time.Now().Add(agentSafariWindowWait); window.WindowID == 0; {+ window, tabs, err := c.everydayChromeWindow(ctx, b, pid, before, site)+ if err != nil {+ return nil, err+ }+ m.setSharedWindow(b.Bundle, pid, window.WindowID)+ c.op.mu.Lock()+ c.op.chromeTabs, c.op.chromePID, c.op.chromeWindow = tabs, pid, window.WindowID+ c.op.mu.Unlock()+ 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+ }+ text := fmt.Sprintf("Opened %s in a new window of the user's Chrome (pid %d), window %q [window_id: %v]. The window has %d tab(s).\n%s", urls[0], pid, window.Title, window.WindowID, tabs, note)+ return json.Marshal(map[string]any{"content": []any{map[string]string{"type": "text", "text": text}},+ "structuredContent": map[string]any{"browser": b.Name, "pid": pid, "windows": []map[string]any{{"window_id": window.WindowID, "title": window.Title, "on_screen": window.IsOnScreen}}, "tabs": tabs, "note": note}})+}++// everydayChromeWindow finds the window the command line just opened: a+// window not in before, with one tab. When several such windows show, such+// as one the user opened meanwhile, the one whose address bar shows site is+// it; a lone new window counts once it has stood for everydayChromeSettle,+// so a home page that moves to another site, such as a sign-in page, still+// 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+ for deadline := time.Now().Add(agentSafariWindowWait); ; {windows, err := c.appWindows(ctx, pid)if err != nil {- return nil, err+ return listedWindow{}, 0, err}+ var fresh, matching []listedWindowfor _, w := range windows {- if before[w.WindowID] || siteOf(c.windowAddress(ctx, b, pid, w.WindowID)) != site {+ if before[w.WindowID] || c.agentChromeTabs(ctx, pid, w.WindowID) != 1 {continue}- if n := c.agentChromeTabs(ctx, pid, w.WindowID); n == 1 {- window, tabs = w, n- break+ fresh = append(fresh, w)+ if siteOf(c.windowAddress(ctx, b, pid, w.WindowID)) == site {+ matching = append(matching, w)}}- if window.WindowID != 0 {- break+ if len(fresh) > 0 && seen.IsZero() {+ seen = time.Now()+ }+ settled := !seen.IsZero() && time.Since(seen) >= everydayChromeSettle+ switch {+ case len(matching) == 1:+ return matching[0], 1, nil+ case len(matching) == 0 && len(fresh) == 1 && settled:+ return fresh[0], 1, nil+ case len(fresh) > 1 && settled && len(matching) != 1, len(fresh) > 1 && time.Now().After(deadline):+ return listedWindow{}, 0, fmt.Errorf("COMPUTER_WINDOW_AMBIGUOUS: %d new one-tab windows of the user's Chrome could be the one the Computer opened, so it works in none of them; ask the user to close the windows they do not need, then call launch_app again", len(fresh))}if time.Now().After(deadline) {- return nil, errors.New("launch_app: the user's Chrome did not open a window for the Computer")+ return listedWindow{}, 0, errors.New("launch_app: the user's Chrome did not open a window for the Computer")}if err := sleepContext(ctx, 200*time.Millisecond); err != nil {- return nil, err+ return listedWindow{}, 0, err}}- m.mu.Lock()- m.sharedBrowserBundle, m.sharedBrowserPID, m.sharedBrowserWindow = b.Bundle, pid, window.WindowID- m.mu.Unlock()- c.op.mu.Lock()- c.op.chromeTabs, c.op.chromePID, c.op.chromeWindow = tabs, pid, window.WindowID- c.op.mu.Unlock()- 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- }- text := fmt.Sprintf("Opened %s in a new window of the user's Chrome (pid %d), window %q [window_id: %v]. The window has %d tab(s).\n%s", urls[0], pid, window.Title, window.WindowID, tabs, note)- return json.Marshal(map[string]any{"content": []any{map[string]string{"type": "text", "text": text}},- "structuredContent": map[string]any{"browser": b.Name, "pid": pid, "windows": []map[string]any{{"window_id": window.WindowID, "title": window.Title, "on_screen": window.IsOnScreen}}, "tabs": tabs, "note": note}})}+// everydayChromeSettle is how long a window list of the user's Chrome must+// stay the same before the Computer trusts it: Chrome reopens restored+// windows one after another.+var everydayChromeSettle = 1500 * time.Millisecond+// windowAddress returns the web address the address bar of window shows,// with https:// added when the bar leaves out the scheme, or "" when the-// bar cannot be read.+// bar cannot be read. The address bar is the window's one text field of+// role b.AddressRole outside the page; its name follows the user's+// language, so it is not read.func (c *cuaSession) windowAddress(ctx context.Context, b agentBrowser, pid int, window float64) 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, "tree_format": "elements", "include_screenshot": false, "max_elements": 3000, "timeout_ms": 4000, "session": c.label}})@@ -455,15 +482,15 @@ func (c *cuaSession) windowAddress(ctx context.Context, b agentBrowser, pid int,Structured struct {Elements []struct {Role string `json:"role"`- Label string `json:"label"`Value any `json:"value"`+ InWeb bool `json:"in_web_content"`} `json:"elements"`} `json:"structuredContent"`}_ = json.Unmarshal(read, &state)for _, element := range state.Structured.Elements {value, ok := element.Value.(string)- if !ok || element.Role != b.AddressRole || element.Label != b.AddressLabel {+ if !ok || element.Role != b.AddressRole || element.InWeb {continue}if !strings.Contains(value, "://") {@@ -475,17 +502,27 @@ func (c *cuaSession) windowAddress(ctx context.Context, b agentBrowser, pid int,}// waitEverydayChrome waits until the user's Chrome that just started runs-// and shows a window, and returns its pid.+// and its window list has stood for everydayChromeSettle, so every window it+// restores is there before the Computer opens its own, and returns its pid.func (c *cuaSession) waitEverydayChrome(ctx context.Context) (int, error) {+ last, since := "", time.Now()for deadline := time.Now().Add(agentSafariWindowWait); ; {pid, _, err := everydayChromePID(ctx)if err != nil {return 0, err}if pid > 0 {- if windows, err := c.appWindows(ctx, pid); err != nil {+ windows, err := c.appWindows(ctx, pid)+ if err != nil {return 0, err- } else if len(windows) > 0 {+ }+ ids := make([]string, 0, len(windows))+ for _, w := range windows {+ ids = append(ids, fmt.Sprint(w.WindowID))+ }+ if list := strings.Join(ids, ","); list != last {+ last, since = list, time.Now()+ } else if len(windows) > 0 && time.Since(since) >= everydayChromeSettle {return pid, nil}}@@ -498,28 +535,114 @@ func (c *cuaSession) waitEverydayChrome(ctx context.Context) (int, error) {}}-// userChrome reports whether pid is the user's everyday Chrome, whichever of-// its windows an input names: a key reaches the Chrome window that has the-// keyboard, not the one named. The pid the Computer opened its window in is-// known; any other pid is looked up, so the rule holds before the Computer-// opened a window too.-func (c *cuaSession) userChrome(ctx context.Context, pid any) (bool, error) {- number, ok := pid.(float64)- if !ok || runtime.GOOS != "darwin" {- return false, nil+// everydayChromeQuitAsked records, in the state directory so a Daemon+// restart keeps it, whether the Computer asked the user to quit their Chrome+// and has not started it again since.+func (m *Manager) everydayChromeQuitAsked(asked bool) error {+ path := filepath.Join(m.options.StateDirectory, "computer-tools", "everyday-chrome-quit")+ if !asked {+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {+ return err+ }+ return nil+ }+ if err := privatefs.EnsureDir(filepath.Dir(path)); err != nil {+ return err+ }+ return os.WriteFile(path, nil, 0o600)+}++// quitAsked reports whether the Computer asked the user to quit their+// Chrome; see everydayChromeQuitAsked.+func (m *Manager) quitAsked() bool {+ _, err := os.Stat(filepath.Join(m.options.StateDirectory, "computer-tools", "everyday-chrome-quit"))+ return err == nil+}++// sharedWindow is the window the Computer opened as its own in one of the+// user's own browsers, and that browser's pid.+type sharedWindow struct {+ PID int+ Window float64+}++// setSharedWindow records the Computer's window in the user's browser+// bundle. Callers do not hold m.mu.+func (m *Manager) setSharedWindow(bundle string, pid int, window float64) {+ m.mu.Lock()+ defer m.mu.Unlock()+ if m.sharedWindows == nil {+ m.sharedWindows = map[string]sharedWindow{}+ }+ m.sharedWindows[bundle] = sharedWindow{PID: pid, Window: window}+}++// sharedWindowOf returns the Computer's window in the user's browser that+// runs as pid. Callers do not hold m.mu.+func (m *Manager) sharedWindowOf(pid int) (sharedWindow, bool) {+ m.mu.Lock()+ defer m.mu.Unlock()+ for _, shared := range m.sharedWindows {+ if pid > 0 && shared.PID == pid {+ return shared, true+ }+ }+ return sharedWindow{}, false+}++// userChromeWindow returns the pid of the user's everyday Chrome, or 0 when+// it does not run, and the window the Computer opened as its own there, or+// 0. Chrome is looked up on each call, so the key rule holds before the+// Computer opened a window and after Chrome restarts.+func (c *cuaSession) userChromeWindow(ctx context.Context) (sharedWindow, error) {+ if runtime.GOOS != "darwin" {+ return sharedWindow{}, nil+ }+ pid, _, err := everydayChromePID(ctx)+ if err != nil {+ return sharedWindow{}, fmt.Errorf("COMPUTER_INPUT_NOT_SENT: could not tell whether the user's Chrome runs: %w: %w", err, errNotSent)}m := c.op.managerm.mu.Lock()- shared := m.sharedBrowserBundle == "com.google.Chrome" && m.sharedBrowserPID > 0 && int(number) == m.sharedBrowserPID+ own := m.sharedWindows["com.google.Chrome"]m.mu.Unlock()- if shared {- return true, nil+ if pid == 0 || own.PID != pid {+ own.Window = 0}- running, _, err := everydayChromePID(ctx)- if err != nil {- return false, fmt.Errorf("COMPUTER_INPUT_NOT_SENT: could not tell whether the input goes to the user's Chrome: %w: %w", err, errNotSent)+ own.PID = pid+ return own, nil+}++// userChromeKeys refuses a key tool, or a paged read, that reaches the user's+// everyday Chrome. A key goes to the Chrome window that has the keyboard, so+// the window is the one the element_token was read from, not the one named,+// and a key that names no app is refused while that Chrome runs.+func (c *cuaSession) userChromeKeys(ctx context.Context, name string, arguments map[string]any, paged bool) error {+ chrome, err := c.userChromeWindow(ctx)+ if err != nil || chrome.PID == 0 {+ return err+ }+ pid, window := arguments["pid"], arguments["window_id"]+ if token, ok := arguments["element_token"].(string); ok {+ // A token the Computer did not see read cannot be placed in a+ // window, so it is not taken for one in the Computer's window.+ window = nil+ if key, found := c.op.reads.window(token); found {+ pid, window = float64(key.pid), float64(key.window)+ }+ }+ number, ok := pid.(float64)+ if !ok {+ return fmt.Errorf("COMPUTER_TARGET_REQUIRED: while the user's Chrome runs, a key names its app by pid, so it cannot reach Chrome unseen: %w", errNotSent)+ }+ if int(number) != chrome.PID {+ return nil+ }+ if paged {+ return fmt.Errorf("%s: %w", everydayChromeKeysRefused, errNotSent)}- return running > 0 && running == int(number), nil+ id, _ := window.(float64)+ return everydayChromeKeys(name, arguments, chrome.Window != 0 && id == chrome.Window)}// everydayChromeKeysRefused tells the Agent how to work without keys in thediff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.goindex 9ffb6d61..575ba505 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go@@ -7,6 +7,7 @@ import ("errors""fmt""log/slog"+ "maps""os""os/exec""path/filepath"@@ -427,11 +428,10 @@ func (c *cuaSession) isAgentChrome(ctx context.Context, pid, window any) (bool,m := c.op.managerm.mu.Lock()known, checked := m.agentChromePID, m.agentChromeChecked- shared, sharedWindow := m.sharedBrowserPID, m.sharedBrowserWindowm.mu.Unlock()- if shared > 0 && shared == int(number) {+ if shared, ok := m.sharedWindowOf(int(number)); ok {id, named := window.(float64)- return !named || id == sharedWindow, nil+ return !named || id == shared.Window, nil}if known > 0 && known == int(number) && time.Since(checked) < agentChromeRecheck {return true, nil@@ -487,11 +487,15 @@ func (c *cuaSession) agentChromeRunning(ctx context.Context) (int, error) {}m := c.op.managerm.mu.Lock()- shared, bundle := m.sharedBrowserPID, m.sharedBrowserBundle+ shared := maps.Clone(m.sharedWindows)m.mu.Unlock()- if own == 0 && shared > 0 {- if running, _ := sharedBrowserRunning(ctx, bundle); running == shared {- return shared, nil+ if own == 0 {+ // The user's own browsers are checked in a fixed order, so one+ // call names the same browser each time.+ for _, bundle := range slices.Sorted(maps.Keys(shared)) {+ if running, _ := sharedBrowserRunning(ctx, bundle); running > 0 && running == shared[bundle].PID {+ return running, nil+ }}}m.mu.Lock()@@ -548,13 +552,11 @@ func (c *cuaSession) agentChromeKeys(ctx context.Context, arguments map[string]aif _, ok := arguments["window_id"].(float64); ok {return nil}- m := c.op.manager- m.mu.Lock()- shared, sharedWindow := m.sharedBrowserPID, m.sharedBrowserWindow- m.mu.Unlock()- if pid, ok := arguments["pid"].(float64); ok && shared > 0 && int(pid) == shared {- arguments["window_id"] = sharedWindow- return nil+ if pid, ok := arguments["pid"].(float64); ok {+ if shared, found := c.op.manager.sharedWindowOf(int(pid)); found {+ arguments["window_id"] = shared.Window+ return nil+ }}windows, err := c.appWindows(ctx, arguments["pid"])if err != nil {@@ -604,13 +606,24 @@ func (c *cuaSession) agentChromeTabs(ctx context.Context, pid int, window float6}// countTabs counts the tab rows of a browser window's tree: a radio button-// whose next row, or a row nested under it, is a Close or Close tab button.+// outside the page that holds a button, its Close button.func countTabs(tree string) int {rows := strings.Split(tree, "\n")indent := func(row string) int { return len(row) - len(strings.TrimLeft(row, " ")) }count := 0+ // web is the indent of the page being skipped, or -1: a radio button+ // in a page is not a tab.+ web := -1for i, row := range rows {- if !strings.Contains(row, "] AXRadioButton \"") {+ if web >= 0 && indent(row) > web {+ continue+ }+ web = -1+ if strings.Contains(row, "] AXWebArea") || strings.HasPrefix(strings.TrimLeft(row, " -"), "AXWebArea") {+ web = indent(row)+ continue+ }+ if !strings.Contains(row, "] AXRadioButton") {continue}if strings.Contains(row, "id=TabBarTab") {@@ -618,11 +631,13 @@ func countTabs(tree string) int {count++continue}+ // A tab holds its Close button, whose name follows the user's+ // language, so any button inside it counts.for j, next := range rows[i+1:] {if j > 0 && indent(next) <= indent(row) {break}- if trimmed := strings.TrimSpace(next); strings.HasSuffix(trimmed, `AXButton "Close" [actions=[press]]`) || strings.HasSuffix(trimmed, `AXButton "Close tab" [actions=[press]]`) {+ if trimmed := strings.TrimSpace(next); strings.Contains(trimmed, "] AXButton") && strings.HasSuffix(trimmed, "[actions=[press]]") {count++break}diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.goindex 324df202..86fb750f 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua.go@@ -223,7 +223,7 @@ const MacToolGuide = `Computer tools on this Mac (MCP server "computer"):- report_blocker({kind, url}) as soon as a page in the Computer's own browser shows a check only the user may pass (captcha, verification, login_required, rate_limited) or one item that cannot be viewed (content_unavailable). Never try to pass the check.The Computer's own browser takes input at a person's pace, within a budget per task and per day, and a script there sends at most 20 inputs: return what you have and look at the window before the next script. A tab that a link in the script opens is the task's and is in front afterwards. The browser tools stay off every site a task opened in that browser.Plan as many steps as you can in one run_actions call, as in one script; its read shows their effect, so do not read again before the next input unless you need another window. Keys are often shorter than clicks: in Finder, cmd+shift+g then a path and Return opens a folder, cmd+down opens the selected item, and in the Trash cmd+delete puts the selected item back.-In Chrome, launch_app({bundle_id: "com.google.Chrome", urls: [url]}) opens a URL in a new tab without bringing Chrome forward; its pages read as empty while the window is covered or on another Space. Add agent_browser: true to use the Computer's own browser window instead: it keeps working while covered, but not on another desktop (Space). Chrome's own toolbar, such as Back and the address bar, refuses background input. In the Computer's window of the user's everyday Chrome no key or shortcut is sent: fill fields with set_value, press the page's buttons, and go back through its links. In Edge or Firefox press escape to close a page overlay, or hotkey cmd+[ to go back. A web control that ignores a background click, such as an option in a menu that opens on hover, takes one click with delivery_mode "foreground" at x,y of a screenshot.+In Chrome, launch_app({bundle_id: "com.google.Chrome", urls: [url]}) opens a URL in a new tab without bringing Chrome forward; its pages read as empty while the window is covered or on another Space. Add agent_browser: true to use the Computer's own browser window instead: it keeps working while covered, but not on another desktop (Space). Chrome's own toolbar, such as Back and the address bar, refuses background input. The user's everyday Chrome takes no shortcut, typed text or unbound key in any window; only one plain key bound to an element of the Computer's window, such as Return in its search box, goes. Fill fields with set_value, press the page's buttons, and go back through its links. In Edge or Firefox press escape to close a page overlay, or hotkey cmd+[ to go back. A web control that ignores a background click, such as an option in a menu that opens on hover, takes one click with delivery_mode "foreground" at x,y of a screenshot.A menu item in the read, such as File > Put Back, can be clicked directly; do not click a menu bar title first, because an open menu holds the app until it closes. A right_click menu does not show in the read, so select the row with click and use the menu bar item or its keyboard shortcut.Before the first shell screenshot, or when one fails or comes back blank, run ` + "`teamhub computer permissions status`" + `; if Screen Recording is missing for Linger, run ` + "`teamhub computer permissions request --permissions screen_recording`" + ` and end your turn — the card wakes you. Never operate System Settings or privacy prompts yourself.` + browserToolGuide@@ -398,22 +398,9 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessage// A key to the user's Chrome reaches the window that has the keyboard,// whichever window it names, so it is refused before anything is taken.if name == "hotkey" || name == "type_text" || name == "press_key" || paged {- user, err := c.userChrome(ctx, arguments["pid"])- if err != nil {+ if err := c.userChromeKeys(ctx, name, arguments, paged); err != nil {return nil, err}- if user && paged {- return nil, fmt.Errorf("%s: %w", everydayChromeKeysRefused, errNotSent)- }- if user {- own, err := c.isAgentChrome(ctx, arguments["pid"], arguments["window_id"])- if err != nil {- return nil, err- }- if err := everydayChromeKeys(name, arguments, own); err != nil {- return nil, err- }- }}agentChrome, err := c.claimAgentChromeInput(ctx, name, arguments, paged)if err != nil {@@ -459,13 +446,13 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessage}}if name == "run_script" {- noKeys := false- if scriptTarget != nil {- if noKeys, err = c.userChrome(ctx, scriptTarget["pid"]); err != nil {- return nil, err- }+ // A script's body may reach any app, so its guard checks every key+ // against the user's Chrome, whatever window args names.+ chrome, err := c.userChromeWindow(ctx)+ if err != nil {+ return nil, err}- if err := scriptArguments(ctx, arguments, c.reviewScope(), scriptInputs, noKeys); err != nil {+ if err := scriptArguments(ctx, arguments, c.reviewScope(), scriptInputs, chrome); err != nil {return nil, err}}diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script.goindex ab020ee9..d36768b4 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,11 @@ var scriptForbidden = []string{"delivery_mode", "foreground", "screenshot_out_fi// Computer's own browser: the guard waits a person's pause before each input,// throws once the script tries to send more than inputLimit inputs, and// refuses launch_app, whose site checks run only in the Daemon's own call.-func guardedScript(args, body string, deadline int64, inputLimit int, noKeys bool) string {+// While the user's everyday Chrome runs as chrome.PID, the guard refuses+// every key to it, and a key that names no app, by the rule of+// everydayChromeKeys: only one plain press_key bound to an element token in+// the Computer's window chrome.Window goes.+func guardedScript(args, body string, deadline int64, inputLimit int, chrome sharedWindow) string {pattern := make([]string, 0, len(scriptForbidden))for _, word := range scriptForbidden {pattern = append(pattern, regexp.QuoteMeta(word))@@ -80,8 +84,12 @@ 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;const plainProtos = [Object.prototype, Array.prototype, null], real = globalThis.cua;const bad = /`+strings.Join(pattern, "|")+`/;-const limit = `+strconv.Itoa(inputLimit)+`, noKeys = `+strconv.FormatBool(noKeys)+`, rest = real.sleep, random = Math.random, floor = Math.floor; let sent = 0;-const keyed = (k, c) => k === "hotkey" || k === "typeText" || k === "pressKey" && (c.length !== 2 || c[1] === null || c[1] === undefined || typeof c[0] !== "string" || c[0].indexOf("+") >= 0) || k === "call" && (c[0] === "hotkey" || c[0] === "type_text" || c[0] === "press_key" && (c[1] === null || typeof c[1] !== "object" || typeof c[1].element_token !== "string" || c[1].modifiers !== undefined || typeof c[1].key !== "string" || c[1].key.indexOf("+") >= 0));+const limit = `+strconv.Itoa(inputLimit)+`, chrome = `+strconv.Itoa(chrome.PID)+`, own = `+strconv.FormatFloat(chrome.Window, 'f', -1, 64)+`, rest = real.sleep, random = Math.random, floor = Math.floor; let sent = 0;+const plainKey = (key, token, win) => typeof key === "string" && key.indexOf("+") < 0 && typeof token === "string" && own !== 0 && win === own;+const keyed = (k, c, o) => { if (chrome === 0) return false;+if (k === "call") { if (c[0] !== "hotkey" && c[0] !== "type_text" && c[0] !== "press_key") return false; const a = c[1] !== null && typeof c[1] === "object" ? c[1] : {};+if (typeof a.pid !== "number") return true; if (a.pid !== chrome) return false; return !(c[0] === "press_key" && a.modifiers === undefined && plainKey(a.key, a.element_token, a.window_id)); }+if (k !== "hotkey" && k !== "typeText" && k !== "pressKey") return false; if (o.pid !== chrome) return false; return !(k === "pressKey" && c.length === 2 && plainKey(c[0], c[1], o.windowId)); };const inputMethods = {__proto__: null, click: true, doubleClick: true, rightClick: true, drag: true, scroll: true, typeText: true, pressKey: true, hotkey: true, setValue: true};const inputOps = {__proto__: null, click: true, double_click: true, right_click: true, drag: true, scroll: true, type_text: true, press_key: true, hotkey: true, set_value: true};const input = (k, c) => inputMethods[k] === true || k === "call" && typeof c[0] === "string" && inputOps[c[0]] === true;@@ -98,7 +106,7 @@ if (limit > 0 && k === "typeText") { const given = c.length > 2 && c[2] !== nullif (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); return r !== null && typeof r === "object" && typeof r.then === "function" ? apply(then, r, [out]) : out(r); };if (limit > 0 && (k === "launchApp" || k === "call" && c[0] === "launch_app")) throw new Error("COMPUTER_SCRIPT_REFUSED: a script in the Computer's own browser opens no app or URL, so the site checks of launch_app hold; call launch_app as its own tool");-if (noKeys && keyed(k, c)) throw new Error(`+strconv.Quote(everydayChromeKeysRefused)+`);+if (keyed(k, c, o)) throw new Error(`+strconv.Quote(everydayChromeKeysRefused)+`);if (limit <= 0 || !input(k, c)) 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]); }; }}); } }@@ -137,7 +145,7 @@ func forbiddenKey(value any, word string) bool {// into what remains of the call after waiting for the desktop lane. In a// reviewed Run, whose review scope is not empty, a script file runs only as// the judge allowed it in that scope: the body it read and the args it saw.-func scriptArguments(ctx context.Context, arguments map[string]any, reviewScope string, inputLimit int, noKeys bool) error {+func scriptArguments(ctx context.Context, arguments map[string]any, reviewScope string, inputLimit int, chrome sharedWindow) error {for key := range arguments {switch key {case "script", "script_file", "args", "timeout_ms", "max_calls":@@ -196,7 +204,7 @@ func scriptArguments(ctx context.Context, arguments map[string]any, reviewScopearguments["timeout_ms"] = timeoutdelete(arguments, "script_file")delete(arguments, "args")- arguments["script"] = guardedScript(string(encoded), script, time.Now().Add(time.Duration(timeout)*time.Millisecond).UnixMilli(), inputLimit, noKeys)+ arguments["script"] = guardedScript(string(encoded), script, time.Now().Add(time.Duration(timeout)*time.Millisecond).UnixMilli(), inputLimit, chrome)return nil}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 25552cb1..361045f9 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@@ -14,9 +14,9 @@ import (// the same prelude's semantics.const guardHarness = `import fs from "fs";const log = [];-class App { constructor(n) { this.n = n; } click(a) { log.push("raw:" + JSON.stringify(a)); return "clicked"; } typeText(text, on, options) { log.push("type:" + JSON.stringify(options)); return "typed"; } pressKey(key, on) { log.push("key:" + key); return "pressed"; } }+class App { constructor(n, pid, windowId) { this.n = n; this.pid = pid; this.windowId = windowId; } hotkey(keys) { log.push("hotkey:" + keys.join("+")); return "hotkeyed"; } click(a) { log.push("raw:" + JSON.stringify(a)); return "clicked"; } typeText(text, on, options) { log.push("type:" + JSON.stringify(options)); return "typed"; } pressKey(key, on) { log.push("key:" + key); return "pressed"; } }const fake = { call(t, a) { log.push("call:" + t + ":" + JSON.stringify(a)); return Promise.resolve({ok: true}); },- getApp() { return Promise.resolve(new App("a")); },+ getApp(target) { return Promise.resolve(new App("a", target && target.pid, target && target.windowId)); },listApps() { return Promise.resolve([new App("b")]); },box() { return Promise.resolve({inner: {app: new App("c")}}); },sleep(ms) { log.push("sleep:" + (ms >= 100 && ms < 250 ? "paced" : ms)); return Promise.resolve(); } };@@ -55,7 +55,7 @@ func TestScriptGuardRefusesForbiddenInputInAJSEngine(t *testing.T) {for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {script := filepath.Join(dir, "script.js")- if err := os.WriteFile(script, []byte(guardedScript(`{"n":1}`, tc.body, 42, 0, false)), 0o600); err != nil {+ if err := os.WriteFile(script, []byte(guardedScript(`{"n":1}`, tc.body, 42, 0, sharedWindow{})), 0o600); err != nil {t.Fatal(err)}out, err := exec.Command(node, harness, script).CombinedOutput()@@ -84,7 +84,7 @@ func TestScriptGuardPacesInputsForTheComputersChrome(t *testing.T) {if err := os.WriteFile(harness, []byte(guardHarness), 0o600); err != nil {t.Fatal(err)}- if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, 2, false)), 0o600); err != nil {+ if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, 2, sharedWindow{})), 0o600); err != nil {t.Fatal(err)}out, err := exec.Command(node, harness, script).CombinedOutput()@@ -112,7 +112,7 @@ func TestScriptGuardSpeedsTypingAndCapsWaits(t *testing.T) {if err := os.WriteFile(harness, []byte(guardHarness), 0o600); err != nil {t.Fatal(err)}- if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, 20, false)), 0o600); err != nil {+ if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, 20, sharedWindow{})), 0o600); err != nil {t.Fatal(err)}out, err := exec.Command(node, harness, script).CombinedOutput()@@ -145,7 +145,7 @@ func TestScriptGuardRefusesLaunchAppForTheComputersChrome(t *testing.T) {want string}{{2, "threw:COMPUTER_SCRIPT_REFUSED"}, {0, "call:launch_app"}} {script := filepath.Join(dir, "script.js")- if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, tc.limit, false)), 0o600); err != nil {+ if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, tc.limit, sharedWindow{})), 0o600); err != nil {t.Fatal(err)}out, err := exec.Command(node, harness, script).CombinedOutput()@@ -170,21 +170,29 @@ func TestScriptGuardRefusesKeysForTheEverydayChrome(t *testing.T) {if err := os.WriteFile(harness, []byte(guardHarness), 0o600); err != nil {t.Fatal(err)}+ // The user's Chrome runs as pid 1, and the Computer's window there is 12.for _, tc := range []struct{ body, want string }{- {`return await cua.call("hotkey", {pid: 1, keys: ["cmd", "["]});`, "threw:COMPUTER_KEYS_REFUSED"},- {`const app = await cua.getApp({pid: 1}); return app.typeText("kettle", {role: "AXTextField"});`, "threw:COMPUTER_KEYS_REFUSED"},- {`return await cua.call("press_key", {pid: 1, key: "return"});`, "threw:COMPUTER_KEYS_REFUSED"},- {`return await cua.call("press_key", {pid: 1, key: "return", element_token: "s1:2", modifiers: ["cmd"]});`, "threw:COMPUTER_KEYS_REFUSED"},- {`return await cua.call("press_key", {pid: 1, key: "return", element_token: "s1:2", modifiers: []});`, "threw:COMPUTER_KEYS_REFUSED"},- {`return await cua.call("press_key", {pid: 1, key: "cmd+r", element_token: "s1:2"});`, "threw:COMPUTER_KEYS_REFUSED"},- {`const app = await cua.getApp({pid: 1}); return app.pressKey("cmd+r", "s1:2");`, "threw:COMPUTER_KEYS_REFUSED"},- {`const app = await cua.getApp({pid: 1}); return app.pressKey("return");`, "threw:COMPUTER_KEYS_REFUSED"},- {`const app = await cua.getApp({pid: 1}); return app.pressKey("return", "s1:2");`, "pressed"},- {`return await cua.call("press_key", {pid: 1, key: "return", element_token: "s1:2"});`, "call:press_key"},+ {`return await cua.call("hotkey", {pid: 1, window_id: 12, keys: ["cmd", "["]});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("hotkey", {keys: ["cmd", "w"]});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("hotkey", {pid: 2, keys: ["cmd", "s"]});`, "call:hotkey"},+ {`const app = await cua.getApp({pid: 1, windowId: 12}); return app.typeText("kettle", "s1:2");`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 1, windowId: 9}); return app.hotkey(["cmd", "w"]);`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 2, windowId: 5}); return app.hotkey(["cmd", "s"]);`, "hotkeyed"},+ {`return await cua.call("press_key", {pid: 1, window_id: 12, key: "return"});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("press_key", {pid: 1, window_id: 12, key: "return", element_token: "s1:2", modifiers: ["cmd"]});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("press_key", {pid: 1, window_id: 12, key: "return", element_token: "s1:2", modifiers: []});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("press_key", {pid: 1, window_id: 12, key: "cmd+r", element_token: "s1:2"});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("press_key", {pid: 1, window_id: 9, key: "return", element_token: "s1:2"});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("press_key", {pid: 1, window_id: 12, key: "return", element_token: "s1:2"});`, "call:press_key"},+ {`const app = await cua.getApp({pid: 1, windowId: 12}); return app.pressKey("cmd+r", "s1:2");`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 1, windowId: 12}); return app.pressKey("return");`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 1, windowId: 12}); return app.pressKey("return", [3, 4]);`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 1, windowId: 9}); return app.pressKey("return", "s1:2");`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 1, windowId: 12}); return app.pressKey("return", "s1:2");`, "pressed"},{`return await cua.call("click", {pid: 1, element_token: "s1:2"});`, "call:click"},} {script := filepath.Join(dir, "script.js")- if err := os.WriteFile(script, []byte(guardedScript(`{}`, tc.body, 42, 20, true)), 0o600); err != nil {+ if err := os.WriteFile(script, []byte(guardedScript(`{}`, tc.body, 42, 20, sharedWindow{PID: 1, Window: 12})), 0o600); err != nil {t.Fatal(err)}out, err := exec.Command(node, harness, script).CombinedOutput()diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script_test.goindex ab2cdb26..68c9ff1b 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script_test.go@@ -16,22 +16,22 @@ import (func TestScriptArgumentsBoundTheScript(t *testing.T) {arguments := map[string]any{"script": "return 1;"}- if err := scriptArguments(context.Background(), arguments, "", 0, false); err != nil || arguments["timeout_ms"] != float64(scriptTimeoutMs) {+ if err := scriptArguments(context.Background(), arguments, "", 0, sharedWindow{}); err != nil || arguments["timeout_ms"] != float64(scriptTimeoutMs) {t.Fatalf("default: %v %v", err, arguments)}arguments = map[string]any{"script": "return 1;", "timeout_ms": float64(500000)}- if err := scriptArguments(context.Background(), arguments, "", 0, false); err != nil || arguments["timeout_ms"] != float64(scriptMaxTimeoutMs) {+ if err := scriptArguments(context.Background(), arguments, "", 0, sharedWindow{}); err != nil || arguments["timeout_ms"] != float64(scriptMaxTimeoutMs) {t.Fatalf("cap: %v %v", err, arguments)}ctx, cancel := context.WithTimeout(context.Background(), time.Minute)defer cancel()arguments = map[string]any{"script": "return 1;", "timeout_ms": float64(90000)}- if err := scriptArguments(ctx, arguments, "", 0, false); err != nil || arguments["timeout_ms"].(float64) > 45000 {+ if err := scriptArguments(ctx, arguments, "", 0, sharedWindow{}); err != nil || arguments["timeout_ms"].(float64) > 45000 {t.Fatalf("deadline: %v %v", err, arguments)}late, stop := context.WithTimeout(context.Background(), 10*time.Second)defer stop()- if err := scriptArguments(late, map[string]any{"script": "return 1;"}, "", 0, false); !errors.Is(err, errNotSent) {+ if err := scriptArguments(late, map[string]any{"script": "return 1;"}, "", 0, sharedWindow{}); !errors.Is(err, errNotSent) {t.Fatalf("late: %v", err)}for _, refused := range []map[string]any{@@ -40,7 +40,7 @@ func TestScriptArgumentsBoundTheScript(t *testing.T) {{"script": `await cua.call("click", {pid: 1, x: 2, y: 3, delivery_mode: "foreground"})`},{"script": `await app.getState({screenshot_out_file: "/tmp/a.png"})`},} {- if err := scriptArguments(context.Background(), refused, "", 0, false); !errors.Is(err, errNotSent) {+ if err := scriptArguments(context.Background(), refused, "", 0, sharedWindow{}); !errors.Is(err, errNotSent) {t.Fatalf("%v: got %v", refused, err)}}@@ -56,7 +56,7 @@ func TestScriptArgumentsReadASkillScriptWithArgs(t *testing.T) {t.Fatal(err)}arguments := map[string]any{"script_file": file, "args": map[string]any{"pid": float64(7)}}- if err := scriptArguments(context.Background(), arguments, "", 0, false); err != nil {+ if err := scriptArguments(context.Background(), arguments, "", 0, sharedWindow{}); err != nil {t.Fatal(err)}script, _ := arguments["script"].(string)@@ -70,19 +70,19 @@ func TestScriptArgumentsReadASkillScriptWithArgs(t *testing.T) {{"script": `return cua.call("click", {delivery_mode: "foreground"});`},{"script_file": file, "args": map[string]any{"click": []any{map[string]any{"delivery_mode": "foreground"}}}},} {- if err := scriptArguments(context.Background(), refused, "", 0, false); !errors.Is(err, errNotSent) {+ if err := scriptArguments(context.Background(), refused, "", 0, sharedWindow{}); !errors.Is(err, errNotSent) {t.Fatalf("%v: got %v", refused, err)}}// args carry page and user text, which may name a forbidden option.- if err := scriptArguments(context.Background(), map[string]any{"script_file": file, "args": map[string]any{"text": "in the foreground"}}, "", 0, false); err != nil {+ if err := scriptArguments(context.Background(), map[string]any{"script_file": file, "args": map[string]any{"text": "in the foreground"}}, "", 0, sharedWindow{}); err != nil {t.Fatalf("user text in args: %v", err)}// A reviewed Run runs a script file only as a review allowed it.- if err := scriptArguments(context.Background(), map[string]any{"script_file": file, "args": map[string]any{"pid": float64(7)}}, permission.ScriptScope("agent-1", "context-1"), 0, false); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_SCRIPT_REFUSED") {+ if err := scriptArguments(context.Background(), map[string]any{"script_file": file, "args": map[string]any{"pid": float64(7)}}, permission.ScriptScope("agent-1", "context-1"), 0, sharedWindow{}); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_SCRIPT_REFUSED") {t.Fatalf("unreviewed script file in a reviewed Run: %v", err)}- if err := scriptArguments(context.Background(), map[string]any{"script": "return 1;"}, permission.ScriptScope("agent-1", "context-1"), 0, false); err != nil {+ if err := scriptArguments(context.Background(), map[string]any{"script": "return 1;"}, permission.ScriptScope("agent-1", "context-1"), 0, sharedWindow{}); err != nil {t.Fatalf("inline script in a reviewed Run: %v", err)}}diff --git a/apps/computer/local-daemon/internal/linger/localtools/evidence.go b/apps/computer/local-daemon/internal/linger/localtools/evidence.goindex c12fbfa0..dd60c760 100644--- a/apps/computer/local-daemon/internal/linger/localtools/evidence.go+++ b/apps/computer/local-daemon/internal/linger/localtools/evidence.go@@ -641,6 +641,19 @@ func applyDiff(previous map[int]string, text string) map[int]string {return rows}+// window returns the window a token was read from, even when a later read+// of that window replaced its snapshot.+func (w *windowReads) window(token string) (windowKey, bool) {+ snapshot, _, ok := strings.Cut(token, ":")+ if !ok {+ return windowKey{}, false+ }+ w.mu.Lock()+ defer w.mu.Unlock()+ key, found := w.snapshots[snapshot]+ return key, found+}+// row returns the window and row text a token names, when the token is from// that window's latest read.func (w *windowReads) row(token string) (windowKey, string, bool) {diff --git a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.goindex cc18918f..c671c5a2 100644--- a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go@@ -215,7 +215,7 @@ func runToolFixture(mode string) {}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}}}- if mode == "tabs-everyday" && strings.Count(string(data), `"name":"open"`) >= 2 {+ 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// the Computer's window.@@ -242,6 +242,9 @@ func runToolFixture(mode string) {// Chrome's does: window 12 shows the site just opened.window, _ := request.Params.Arguments["window_id"].(float64)address := map[float64]string{12: "example.com"}[window]+ if mode == "tabs-everyday-twin" && window == 11 {+ address = "example.com/feed"+ }if address == "" {address = "news.example.org/today"}@@ -1911,6 +1914,9 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *tdata := everydayChromeDataeverydayChromeData = func() string { return t.TempDir() }t.Cleanup(func() { everydayChromeData = data })+ settle := everydayChromeSettle+ everydayChromeSettle = 0+ t.Cleanup(func() { everydayChromeSettle = settle })b := agentBrowsers[0]// A Chrome started without the setting is never quit by the Computer.if _, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"}); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_BROWSER_RESTART_REQUIRED") || len(opened) != 0 {@@ -1919,11 +1925,17 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *t// The user quits it; the Computer starts it with the setting and their// windows, then opens the site in a new window.running = 0+ if !c.op.manager.quitAsked() {+ t.Fatal("the question to quit Chrome was not recorded")+ }result, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"})if err != nil {t.Fatal(err)}- if len(opened) != 2 || !slices.Contains(opened[0], "--restore-last-session") || !slices.Contains(opened[0], "--disable-backgrounding-occluded-windows") || !slices.Equal(opened[1][len(opened[1])-3:], []string{"--profile-directory=Default", "--new-window", "https://example.com/"}) {+ if c.op.manager.quitAsked() {+ t.Fatal("the question to quit Chrome outlived the start")+ }+ if len(opened) != 2 || opened[0][0] != "-n" || !slices.Contains(opened[0], "--restore-last-session") || !slices.Contains(opened[0], "--disable-backgrounding-occluded-windows") || !slices.Equal(opened[1][len(opened[1])-3:], []string{"--profile-directory=Default", "--new-window", "https://example.com/"}) {t.Fatalf("opened=%v, want a start with the user's windows, then the site in a new window", opened)}// Window 11, restored late, lists first, but it shows another site.@@ -1948,23 +1960,45 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *t{"press_key", `{"pid":42,"window_id":12,"key":"cmd+r","element_token":"s1:1"}`},{"press_key", `{"pid":42,"window_id":9,"key":"return","element_token":"s1:1"}`},{"recognize_text", `{"pid":42,"window_id":12,"pages":2,"next_key":"pagedown"}`},+ // A token read from the user's window 9 places the key there,+ // whatever window_id names; one never read places it nowhere.+ {"press_key", `{"pid":42,"window_id":12,"key":"return","element_token":"s9:1"}`},+ {"press_key", `{"pid":42,"key":"return","element_token":"s7:1"}`},} {+ c.op.reads.mu.Lock()+ if c.op.reads.snapshots == nil {+ c.op.reads.windows, c.op.reads.snapshots = map[windowKey]*windowRows{}, map[string]windowKey{}+ }+ c.op.reads.snapshots["s9"] = windowKey{pid: 42, window: 9}+ c.op.reads.mu.Unlock()if _, err := c.call(t.Context(), call.name, json.RawMessage(call.args)); !strings.Contains(fmt.Sprint(err), "COMPUTER_KEYS_REFUSED") {t.Fatalf("%s %s: err=%v, want refused", call.name, call.args, err)}}+ // A key that names no app could reach the user's Chrome by its token.+ if _, err := c.call(t.Context(), "type_text", json.RawMessage(`{"text":"kettle","element_token":"s9:1"}`)); !strings.Contains(fmt.Sprint(err), "COMPUTER_KEYS_REFUSED") {+ t.Fatalf("type_text by token alone: err=%v, want refused", err)+ }+ if _, err := c.call(t.Context(), "hotkey", json.RawMessage(`{"keys":["cmd","w"],"element_token":"s7:1"}`)); !strings.Contains(fmt.Sprint(err), "COMPUTER_TARGET_REQUIRED") {+ t.Fatalf("hotkey with no pid: err=%v, want refused", err)+ }+ // A token read from the Computer's window 12 takes one plain key.+ c.op.reads.mu.Lock()+ c.op.reads.snapshots["s1"] = windowKey{pid: 42, window: 12}+ c.op.reads.mu.Unlock()if _, err := c.call(t.Context(), "press_key", json.RawMessage(`{"pid":42,"window_id":12,"key":"return","element_token":"s1:1"}`)); err != nil {t.Fatalf("Return bound to a field: %v", err)}if _, err := c.call(t.Context(), "set_value", json.RawMessage(`{"pid":42,"window_id":12,"value":"kettle","element_token":"s1:1"}`)); err != nil {t.Fatalf("set_value: %v", err)}- // A script there, or in one of the user's windows, may not send keys.- for _, script := range []string{`{"script":"return 1"}`, `{"script":"return 1","args":{"pid":42,"window_id":9}}`} {+ // Any script, whatever it targets, is guarded against keys to the+ // user's Chrome, with the Computer's window 12 as the one exception.+ for _, script := range []string{`{"script":"return 1"}`, `{"script":"return 1","args":{"pid":42,"window_id":9}}`, `{"script":"return 1","args":{"pid":7}}`} {if _, err := c.call(t.Context(), "run_script", json.RawMessage(script)); err != nil {t.Fatal(err)}- if calls := fixtureCalls(t, marker); !strings.Contains(fmt.Sprint(calls[len(calls)-1]), "noKeys = true") {+ if calls := fixtureCalls(t, marker); !strings.Contains(fmt.Sprint(calls[len(calls)-1]), "chrome = 42, own = 12") {t.Fatalf("%s: last call=%v, want a script guarded against keys", script, calls[len(calls)-1])}}@@ -1973,6 +2007,46 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *t}}+// A window of the user's that shows the same site and opens beside the+// Computer's leaves the Computer unable to tell them apart, so it takes+// neither.+func TestLocalToolCuaMacEverydayChromeRefusesTwoWindowsOfTheSite(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("the Computer's window in the user's Chrome is macOS only")+ }+ inputSettle = 0+ t.Cleanup(func() { inputSettle = 300 * time.Millisecond })+ marker := filepath.Join(t.TempDir(), "calls.jsonl")+ c := cuaFixtureSession(t, "tabs-everyday-twin", marker)+ pid := everydayChromePID+ everydayChromePID = func(context.Context) (int, string, error) {+ return 42, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --disable-backgrounding-occluded-windows", nil+ }+ t.Cleanup(func() { everydayChromePID = pid })+ open := agentChromeOpen+ agentChromeOpen = func(context.Context, []string) ([]byte, error) {+ f, err := os.OpenFile(marker, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ // One command line shows both windows, as the fixture lists them+ // from the second open on.+ _, err = f.WriteString(`{"name":"open"}` + "\n" + `{"name":"open"}` + "\n")+ return nil, err+ }+ t.Cleanup(func() { agentChromeOpen = open })+ data := everydayChromeData+ everydayChromeData = func() string { return t.TempDir() }+ t.Cleanup(func() { everydayChromeData = data })+ settle := everydayChromeSettle+ everydayChromeSettle = 0+ t.Cleanup(func() { everydayChromeSettle = settle })+ if _, err := c.launchAgentChrome(t.Context(), agentBrowsers[0], []string{"https://example.com/"}); !strings.Contains(fmt.Sprint(err), "COMPUTER_WINDOW_AMBIGUOUS") {+ t.Fatalf("err=%v, want two windows of the site refused", err)+ }+}+// A launch opens a fresh window when the listed one has left the// accessibility tree.func TestLocalToolCuaMacAgentChromeOpensAFreshWindowForAnUnreadableOne(t *testing.T) {diff --git a/apps/computer/local-daemon/internal/linger/localtools/manager.go b/apps/computer/local-daemon/internal/linger/localtools/manager.goindex ed46edf5..578e1788 100644--- a/apps/computer/local-daemon/internal/linger/localtools/manager.go+++ b/apps/computer/local-daemon/internal/linger/localtools/manager.go@@ -91,16 +91,11 @@ type Manager struct {agentChromeOwner *operationagentChromePID intagentChromeChecked time.Time- // sharedBrowserBundle, sharedBrowserPID and sharedBrowserWindow are the- // user's own browser the Computer works in, such as their everyday Chrome- // or Safari, and the window in it that the Computer opened as its own;- // see launchEverydayChrome and launchAgentSafari.- sharedBrowserBundle string- sharedBrowserPID int- sharedBrowserWindow float64- // everydayChromeQuitAsked records that the Computer asked the user to quit- // their Chrome, so the next start of it brings back their windows.- everydayChromeQuitAsked bool+ // sharedWindows holds, by bundle id, the user's own browser the Computer+ // works in, such as their everyday Chrome or Safari, and the window in it+ // that the Computer opened as its own; see launchEverydayChrome and+ // launchAgentSafari.+ sharedWindows map[string]sharedWindow// paceMu guards the persisted pace record of the Computer's own browser// and paceLast, when that Chrome last received input; see// paceAgentChrome.@@ -133,19 +128,24 @@ func New(options Options) (*Manager, error) {}// retireAgentChromeProfile removes the separate Chrome profile the Computer-// used before it worked in a window of the user's everyday Chrome. A profile-// whose Chrome still runs stays until a later start finds it closed.+// used before it worked in a window of the user's everyday Chrome. A Chrome+// still running on it is the Computer's own, so it is quit first; a profile+// whose Chrome does not quit stays until a later start.func retireAgentChromeProfile(state string) {directory := filepath.Join(state, "computer-tools", "agent-chrome")if _, err := os.Stat(directory); err != nil {return}- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), agentChromeWait+5*time.Second)defer cancel()- if pid, _, err := agentChromePID(ctx, directory); err != nil || pid > 0 {- return+ pid, _, err := agentChromePID(ctx, directory)+ if err == nil && pid > 0 {+ _, err = stopAgentChrome(ctx, directory, pid)+ }+ if err == nil {+ err = os.RemoveAll(directory)}- if err := os.RemoveAll(directory); err != nil {+ if err != nil {slog.Warn("agent_browser.retire_profile_failed", "error", err)}}diff --git a/skills/builtin/humanlike-browse/1.0.5/SKILL.md b/skills/builtin/humanlike-browse/1.0.5/SKILL.mdindex 2d80eed4..6f2aa03e 100644--- a/skills/builtin/humanlike-browse/1.0.5/SKILL.md+++ b/skills/builtin/humanlike-browse/1.0.5/SKILL.md@@ -32,7 +32,7 @@ The user watches the window, and each turn of yours costs seconds. The Computer- Browse in this conversation yourself. Do not hand the browsing to a background Task: starting one adds a minute, and the user watches this Room.- Put each page visit in one `run_script`: search, wait, read what you need, open the item, wait, read it, go back. Return to the model only to choose something, such as which items to open.- Fill a search box with `setValue`, then click the site's search button. Return on the box also works in Edge and Firefox.-- The user's Chrome takes no keys from the Computer: a key could reach the Chrome window the user is typing in. There, never use `typeText`, `hotkey` or a key without an element; Return bound to the search box goes only while no other Chrome window could take it.+- The user's Chrome takes no keys from the Computer: a key could reach the Chrome window the user is typing in. There, never use `typeText`, `hotkey` or a key without an element; only Return bound to the search box of the Computer's window goes, and only while no other Chrome window could take it.- After a click that loads something, wait with `app.waitFor` for what the next page shows, such as a heading or a button, with `timeout_ms` about 8000. Never wait with `cua.sleep`; one sleep lasts at most 1.5 s there.- Read only what you need: `app.query({role, name})`, `getState({query})` or `get_window_state` with `query`. Read the whole tree only to find your way on a page you have not seen.