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): close script key reroutes and keep every Computer window in the user's Chrome
jeffrey02538e4cbee0
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex 0464be84..e2f4c423 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -340,8 +340,10 @@ restart keeps it, and removes the record once Chrome started. Before theComputer opens its window, it waits until the list of Chrome windows stopschanging, so every restored window is there. The Computer's window is the newwindow 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 only new window when the home page moved to another site. Two or more new+one-tab windows that the site does not tell apart are refused with+`COMPUTER_WINDOW_AMBIGUOUS`. Every window the Computer opened there stays its+own for pacing and the key rule, until Chrome restarts. The address bar andthe tabs are found by role and place in the window, not by their names, whichfollow the user's language. The Daemon finds the running Chrome by itsexecutable wherever the app is installed. The user's Chrome takes no keys from@@ -353,7 +355,9 @@ types text as keys that all read as the A key. A key goes to the window itsthat Chrome runs. Only a plain key bound to an element of the Computer'swindow goes, as a tool call, and Cua sends it only when no other Chrome windowcould take it. A script sends that Chrome no key at all, because it cannot-prove which window a token was read from, and it does not start Chrome.+prove which window a token was read from. It refuses a key whose arguments+name an app or window of their own, and no script opens an app or URL, so the+key rule knows every app a script reaches.The Agent fills fields with`set_value`, presses the page's buttons and goes back through its links.The Daemon removes the separate Chrome profile `computer-tools/agent-chrome`@@ -384,7 +388,7 @@ into a script, to the current snapshot when its row reads the same there.Only the windowthe task opened with `launch_app` is held. A script that names no window inits `args` is taken to drive that window; a script to another app is neither-paced nor held, and a paced script may not call `launch_app`. The browser+paced 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 lista larger surface without an accessibility window, which is skipped. The`launch_app` result tells the Agent to move between pages through the site'sdiff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.goindex ee886e8c..c1dad55a 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go@@ -18,9 +18,10 @@ import ("github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs")-// agentBrowser is one browser the Computer can run as its own: a separate-// instance on a profile of its own, with no remote debugging, so sites see a-// person's browser and the user's everyday browser stays untouched.+// agentBrowser is one browser the Computer browses watched sites in, with no+// remote debugging, so sites see a person's browser: a window of its own in+// the user's browser (Shared), or a separate instance on a profile of its+// own.type agentBrowser struct {// Name is how messages and the model name the browser.Name string@@ -31,7 +32,8 @@ type agentBrowser struct {// Args start the browser on profile, after open's --args.Args func(profile string) []string// Settings are what a running instance's command line must carry for- // the tools to rely on it; one without them is restarted.+ // the tools to rely on it. The Computer restarts its own instance that+ // lacks them; the user quits their everyday Chrome.Settings []string// AddressRole and AddressLabel find the address bar; an empty label// takes the first element with that role, which in the browser's@@ -102,7 +104,7 @@ var agentBrowsers = []agentBrowser{// device trust: sites that watch for automated browsing trust that// browser most, and the user signs in only once.{Name: "Chrome", Bundle: "com.google.Chrome", App: "Google Chrome.app", Settings: everydayChromeArgs,- AddressRole: "AXTextField", AddressLabel: "Address and search bar", Shared: true, Everyday: true},+ AddressRole: "AXTextField", Shared: true, Everyday: true},{Name: "Edge", Bundle: "com.microsoft.edgemac", App: "Microsoft Edge.app", Directory: "agent-edge", Args: chromium,Settings: append(slices.Clone(chromiumArgs), "-AppleLanguages"), AddressRole: "AXTextField", AddressLabel: "Address and search bar"},// Firefox keeps its window working while covered without a flag. Its@@ -176,9 +178,10 @@ func (b agentBrowser) startedWith(command string) bool {// Safari: the window this task or an earlier one opened there, or a new one.// Each URL opens in a new tab of that window, as in the other browsers, and// the window's first tab stays as its spare tab.-// agentSafariWindowWait bounds the wait for a new Safari window to become+// sharedBrowserWindowWait bounds the wait for a new window of the user's+// Safari or Chrome to become// readable.-var agentSafariWindowWait = 30 * time.Second+var sharedBrowserWindowWait = 30 * time.Secondfunc (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urls []string) (json.RawMessage, error) {m := c.op.manager@@ -194,7 +197,7 @@ func (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urlsreturn nil, err}m.mu.Lock()- own := m.sharedWindows[b.Bundle].Window+ own := m.sharedWindows[b.Bundle].latest()if m.sharedWindows[b.Bundle].PID != pid {own = 0}@@ -236,7 +239,7 @@ func (c *cuaSession) launchAgentSafari(ctx context.Context, b agentBrowser, urlsif started {// Safari can take longer than a Chromium start before the new// 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 })+ c.agentChromeTabsUntil(ctx, pid, window.WindowID, sharedBrowserWindowWait, func(n int) bool { return n > 0 })}m.setSharedWindow(b.Bundle, pid, window.WindowID)for _, url := range urls {@@ -298,22 +301,22 @@ var everydayChromePID = func(ctx context.Context) (int, string, error) {if err != nil {return 0, "", err}- lines, err := exec.CommandContext(ctx, "/bin/ps", "-axww", "-o", "pid=,args=").Output()- if err != nil {- return 0, "", err- }- commands := map[string]string{}- for _, line := range strings.Split(string(lines), "\n") {- pidText, args, _ := strings.Cut(strings.TrimSpace(line), " ")- commands[pidText] = args- }for _, line := range strings.Split(string(paths), "\n") {pidText, path, _ := strings.Cut(strings.TrimSpace(line), " ")- if !everydayChromeProcess(path, commands[pidText]) {+ if !strings.HasPrefix(path, "/") || !strings.HasSuffix(path, everydayChromeExecutable) {+ continue+ }+ // Only Chrome's own processes need their arguments read.+ args, err := exec.CommandContext(ctx, "/bin/ps", "-ww", "-o", "args=", "-p", pidText).Output()+ if err != nil {+ continue // it ended between the two reads+ }+ command := strings.TrimSpace(string(args))+ if !everydayChromeProcess(path, command) {continue}if pid, err := strconv.Atoi(pidText); err == nil {- return pid, commands[pidText], nil+ return pid, command, nil}}return 0, "", nil@@ -430,7 +433,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- for deadline := time.Now().Add(agentSafariWindowWait); ; {+ for deadline := time.Now().Add(sharedBrowserWindowWait); ; {windows, err := c.appWindows(ctx, pid)if err != nil {return listedWindow{}, 0, err@@ -454,11 +457,11 @@ func (c *cuaSession) everydayChromeWindow(ctx context.Context, b agentBrowser, preturn matching[0], 1, nilcase 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):+ case len(fresh) > 1 && (settled || 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 listedWindow{}, 0, errors.New("launch_app: the user's Chrome did not open a window for the Computer")+ return listedWindow{}, 0, fmt.Errorf("launch_app: the user's Chrome showed no readable new window for %s; a window it opened may still be there, so ask the user to close it before trying again", site)}if err := sleepContext(ctx, 200*time.Millisecond); err != nil {return listedWindow{}, 0, err@@ -466,9 +469,11 @@ func (c *cuaSession) everydayChromeWindow(ctx context.Context, b agentBrowser, p}}-// 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.+// everydayChromeSettle is how long the Computer lets the user's Chrome+// settle before it trusts what it sees: the window list must stay the same+// that long after a start, since Chrome reopens restored windows one after+// another, and a new window must have stood that long before it is taken+// without its site.var everydayChromeSettle = 1500 * time.Millisecond// windowAddress returns the web address the address bar of window shows,@@ -510,7 +515,7 @@ func (c *cuaSession) windowAddress(ctx context.Context, b agentBrowser, pid int,// 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); ; {+ for deadline := time.Now().Add(sharedBrowserWindowWait); ; {pid, _, err := everydayChromePID(ctx)if err != nil {return 0, err@@ -563,25 +568,40 @@ func (m *Manager) quitAsked() bool {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.+// sharedWindow is the windows the Computer opened as its own in one of the+// user's browsers, latest last, and that browser's pid. A task may open+// several, one site each, and every one stays the Computer's.type sharedWindow struct {- PID int- Window float64+ PID int+ Windows []float64+}++// latest is the window the Computer opened last, or 0.+func (s sharedWindow) latest() float64 {+ if len(s.Windows) == 0 {+ return 0+ }+ return s.Windows[len(s.Windows)-1]}-// setSharedWindow records the Computer's window in the user's browser-// bundle. Callers do not hold m.mu.+// setSharedWindow records window as the Computer's in the user's browser+// bundle running as pid; a new pid starts a new record. 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}+ shared := m.sharedWindows[bundle]+ if shared.PID != pid {+ shared = sharedWindow{PID: pid}+ }+ shared.Windows = append(slices.DeleteFunc(slices.Clone(shared.Windows), func(w float64) bool { return w == window }), window)+ m.sharedWindows[bundle] = shared}-// sharedWindowOf returns the Computer's window in the user's browser that+// sharedWindowOf returns the Computer's windows 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()@@ -595,8 +615,8 @@ func (m *Manager) sharedWindowOf(pid int) (sharedWindow, bool) {}// 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+// it does not run, and the windows the Computer opened as its own there.+// 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" {@@ -611,7 +631,7 @@ func (c *cuaSession) userChromeWindow(ctx context.Context) (sharedWindow, error)own := m.sharedWindows["com.google.Chrome"]m.mu.Unlock()if pid == 0 || own.PID != pid {- own.Window = 0+ own.Windows = nil}own.PID = pidreturn own, nil@@ -629,7 +649,9 @@ func (c *cuaSession) userChromeKeys(ctx context.Context, name string, argumentspid, 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, so it is not taken for one in the Computer's window. Cua+ // refuses a token read from another pid than the one named, so a+ // token cannot carry a key into another app.window = nilif key, found := c.op.reads.window(token); found {pid, window = float64(key.pid), float64(key.window)@@ -645,8 +667,8 @@ func (c *cuaSession) userChromeKeys(ctx context.Context, name string, argumentsif paged {return fmt.Errorf("%s: %w", everydayChromeKeysRefused, errNotSent)}- id, _ := window.(float64)- return everydayChromeKeys(name, arguments, chrome.Window != 0 && id == chrome.Window)+ id, named := window.(float64)+ return everydayChromeKeys(name, arguments, named && slices.Contains(chrome.Windows, id))}// everydayChromeKeysRefused tells the Agent how to work without keys in thediff --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 6c8208de..251334b8 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@@ -90,3 +90,22 @@ func TestEverydayChromeKeysAllowOnlyOnePlainBoundKey(t *testing.T) {t.Error("a bound Return went to one of the user's windows")}}++func TestSharedWindowsKeepEveryWindowOfTheBrowser(t *testing.T) {+ m := &Manager{}+ m.setSharedWindow("com.google.Chrome", 42, 11)+ m.setSharedWindow("com.google.Chrome", 42, 12)+ m.setSharedWindow("com.apple.Safari", 7, 3)+ shared, ok := m.sharedWindowOf(42)+ if !ok || len(shared.Windows) != 2 || shared.latest() != 12 {+ t.Fatalf("shared=%+v ok=%v, want windows 11 and 12 with 12 latest", shared, ok)+ }+ // A restarted Chrome has a new pid, and none of the old windows.+ m.setSharedWindow("com.google.Chrome", 43, 20)+ if shared, _ := m.sharedWindowOf(43); len(shared.Windows) != 1 || shared.latest() != 20 {+ t.Fatalf("shared=%+v, want only window 20 after the restart", shared)+ }+ if safari, ok := m.sharedWindowOf(7); !ok || safari.latest() != 3 {+ t.Fatalf("safari=%+v ok=%v, want Safari's window kept apart", safari, ok)+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.goindex 069f6291..ff2cc341 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go@@ -431,7 +431,7 @@ func (c *cuaSession) isAgentChrome(ctx context.Context, pid, window any) (bool,m.mu.Unlock()if shared, ok := m.sharedWindowOf(int(number)); ok {id, named := window.(float64)- return !named || id == shared.Window, nil+ return !named || slices.Contains(shared.Windows, id), nil}if known > 0 && known == int(number) && time.Since(checked) < agentChromeRecheck {return true, nil@@ -554,7 +554,7 @@ func (c *cuaSession) agentChromeKeys(ctx context.Context, arguments map[string]a}if pid, ok := arguments["pid"].(float64); ok {if shared, found := c.op.manager.sharedWindowOf(int(pid)); found {- arguments["window_id"] = shared.Window+ arguments["window_id"] = shared.latest()return nil}}diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.goindex 8a2fc9d0..1f094656 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. 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, and never from run_script. 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, and never from run_script. Fill fields with set_value, press the page's buttons, and go back through its links. In Safari, 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@@ -270,7 +270,7 @@ var macCompactTools = map[string]macCompactTool{"double_click": {"Double-click an element by element_token, by role and name, or a point x,y of the window's latest screenshot." + macInputResult, macPointer, []string{"pid"}},"right_click": {"Right-click an element by element_token, by role and name, or a point x,y, to open its context menu; read the window to see the menu." + macInputResult, macPointer, []string{"pid"}},"hotkey": {macKeyDescriptions["hotkey"] + macKeyRouting + macInputResult, map[string]any{"pid": macPID, "keys": map[string]any{"type": "array", "items": macString}, "window_id": macWindowID}, []string{"pid", "keys"}},- "press_key": {macKeyDescriptions["press_key"] + macKeyRouting + macInputResult, map[string]any{"pid": macPID, "key": macString, "modifiers": map[string]any{"type": "array", "items": macString}, "window_id": macWindowID}, []string{"pid", "key"}},+ "press_key": {macKeyDescriptions["press_key"] + macKeyRouting + macInputResult, map[string]any{"pid": macPID, "key": macString, "modifiers": map[string]any{"type": "array", "items": macString}, "window_id": macWindowID, "element_token": macToken}, []string{"pid", "key"}},"type_text": {macKeyDescriptions["type_text"] + macKeyRouting + macInputResult, map[string]any{"pid": macPID, "text": macString, "window_id": macWindowID, "element_token": macToken, "role": macRole, "name": macLabel, "nth": macNth}, []string{"pid", "text"}},"scroll": {"Scroll a window, or the element element_token, by amount lines in direction." + macInputResult, map[string]any{"pid": macPID, "window_id": macWindowID, "element_token": macToken, "role": macRole, "name": macLabel, "nth": macNth, "direction": map[string]any{"type": "string", "enum": []string{"up", "down", "left", "right"}}, "amount": map[string]any{"type": "integer"}}, []string{"pid", "direction"}},"get_window_state": {macWindowStateDescription, map[string]any{diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script.goindex bf746fb0..ceb73292 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script.go@@ -19,7 +19,7 @@ const macScriptDescription = "Run a JavaScript program that drives apps on this"- app.getState({query?, max_elements?, timeout_ms?, since?: \"latest\", tree_format?: \"elements\"}) returns {tree_markdown, window_title, snapshot_id, truncated?, elements?}; rows read as in get_window_state. In a script the walk stops after 250 nodes and 1000 ms unless you pass max_elements and timeout_ms, which cuts a browser page: pass about 3000 and 4000 there\n" +"- app.query({role?, name?}) finds named elements {element_token, role, label, frame}; app.waitFor({role?, name?, text?, gone?, timeout_ms?}) waits until the window shows (or no longer shows) them; text also matches static text\n" +"- app.click(t), doubleClick(t), typeText(text, t?), pressKey(\"escape\", t?), hotkey([\"cmd\",\"s\"]), scroll(t, \"down\", amount?), setValue(t, value), where t is {role, name, nth?}, an element_token, a row number of this app's last getState(), or [x, y] pixels of its last screenshot\n" +- "- cua.call(tool, args) for click, press_key, type_text, scroll, get_window_state, list_windows or launch_app with their usual arguments.\n" ++ "- cua.call(tool, args) for click, press_key, type_text, scroll, get_window_state or list_windows with their usual arguments. A script opens no app or URL: call launch_app as its own tool first.\n" +"Inputs go to the app in the background, as the other computer tools do; a control that reacts only to a real pointer needs the click tool with delivery_mode \"foreground\". A failed call throws (catch it to recover), and the error names the line. timeout_ms is the wall-time limit (default 60000, at most 100000); max_calls bounds driver calls (default 100, at most 500). A Skill that ships a script names it with script_file and passes its inputs as args, read in the script as the constant args. Return only what you need, such as extracted text; the result is cut at 40000 characters and carries no screenshots: call get_window_state to look at the window."// scriptTimeoutMs bounds a script below the two-minute limit of one local@@ -68,12 +68,14 @@ var scriptForbidden = []string{"delivery_mode", "foreground", "screenshot_out_fi// could not verify in time. A positive inputLimit paces the script for the// 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.-// While the user's everyday Chrome runs as chrome, the guard refuses every-// key to it and every key that names no app: a script cannot prove which-// window an element token was read from, so even the one key a tool call-// may send there (see everydayChromeKeys) is refused. It also refuses to-// start Chrome, whose pid the guard would not know.+// refuses to open an app or URL, whose site checks run only in the Daemon's+// own launch_app and which could start Chrome with a pid the guard does not+// know. While the user's everyday Chrome runs as chrome, the guard refuses+// every key to it, every key that names no app, and every key whose+// arguments name an app or window of their own, which Cua lets override the+// app the call is made on: a script cannot prove which window an element+// token was read from, so even the one key a tool call may send there (see+// everydayChromeKeys) is refused.func guardedScript(args, body string, deadline int64, inputLimit int, chrome int) string {pattern := make([]string, 0, len(scriptForbidden))for _, word := range scriptForbidden {@@ -87,9 +89,10 @@ const plainProtos = [Object.prototype, Array.prototype, null], real = globalThisconst 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;const keyOps = {__proto__: null, hotkey: true, type_text: true, press_key: true}, keyMethods = {__proto__: null, hotkey: true, typeText: true, pressKey: true};-const keyed = (k, c, o) => chrome > 0 && (k === "call" ? keyOps[c[0]] === true && (c[1] === null || typeof c[1] !== "object" || typeof c[1].pid !== "number" || c[1].pid === chrome) : keyMethods[k] === true && (typeof o.pid !== "number" || o.pid === chrome));-const namesChrome = v => v === "Google Chrome" || v === "com.google.Chrome" || v !== null && typeof v === "object" && (v.name === "Google Chrome" || v.bundle_id === "com.google.Chrome" || v.bundleId === "com.google.Chrome");-const startsChrome = (k, c) => k === "launchApp" && namesChrome(c[0]) || k === "call" && c[0] === "launch_app" && namesChrome(c[1]);+const routes = v => v !== null && typeof v === "object" && (v.pid !== undefined || v.app !== undefined || v.target !== undefined || v.window_id !== undefined || v.windowId !== undefined);+const rerouted = c => { for (let i = 0; i < c.length; i++) if (routes(c[i])) return true; return false; };+const keyed = (k, c, o) => chrome > 0 && (k === "call" ? keyOps[c[0]] === true && (c[1] === null || typeof c[1] !== "object" || typeof c[1].pid !== "number" || c[1].pid === chrome || c[1].app !== undefined || c[1].target !== undefined) : keyMethods[k] === true && (typeof o.pid !== "number" || o.pid === chrome || rerouted(c)));+const launches = (k, c) => k === "launch" || k === "launchApp" || k === "call" && c[0] === "launch_app";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;@@ -105,8 +108,7 @@ 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 (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 (startsChrome(k, c)) throw new Error("COMPUTER_SCRIPT_REFUSED: a script does not start Google Chrome; call launch_app as its own tool");+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 (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");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 259c9a5f..6cf195e8 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,8 +14,9 @@ import (// the same prelude's semantics.const guardHarness = `import fs from "fs";const log = [];-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"; } }+class App { constructor(n, pid, windowId) { this.n = n; this.pid = pid; this.windowId = windowId; } hotkey(keys, on, options) { log.push("hotkey:" + keys.join("+") + ":" + JSON.stringify({pid: this.pid, ...on, ...options})); 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}); },+ launch(name) { log.push("launched:" + name); return Promise.resolve(new App("l", 7, 1)); },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")}}); },@@ -127,9 +128,9 @@ func TestScriptGuardSpeedsTypingAndCapsWaits(t *testing.T) {}}-// A paced script opens no app or URL, so launch_app's site checks hold; an-// unpaced script may still call it.-func TestScriptGuardRefusesLaunchAppForTheComputersChrome(t *testing.T) {+// No script opens an app or URL, paced or not: launch_app's site checks hold,+// and the key rule knows every app the script reaches.+func TestScriptGuardRefusesLaunchApp(t *testing.T) {node, err := exec.LookPath("node")if err != nil {t.Skip("node is not installed")@@ -139,21 +140,24 @@ func TestScriptGuardRefusesLaunchAppForTheComputersChrome(t *testing.T) {if err := os.WriteFile(harness, []byte(guardHarness), 0o600); err != nil {t.Fatal(err)}- body := `return await cua.call("launch_app", {urls: ["https://example.com/"]});`for _, tc := range []struct {+ body stringlimit int- want string- }{{2, "threw:COMPUTER_SCRIPT_REFUSED"}, {0, "call:launch_app"}} {+ }{+ {`return await cua.call("launch_app", {urls: ["https://example.com/"]});`, 2},+ {`return await cua.call("launch_app", {urls: ["https://example.com/"]});`, 0},+ {`return await cua.launch("com.google.Chrome");`, 0},+ } {script := filepath.Join(dir, "script.js")- if err := os.WriteFile(script, []byte(guardedScript(`{}`, body, 42, tc.limit, 0)), 0o600); err != nil {+ if err := os.WriteFile(script, []byte(guardedScript(`{}`, tc.body, 42, tc.limit, 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) || tc.limit > 0 && strings.Contains(got, "call:launch_app") {- t.Fatalf("limit %d: got %s, want %q", tc.limit, got, tc.want)+ if got := string(out); !strings.Contains(got, "threw:COMPUTER_SCRIPT_REFUSED") || strings.Contains(got, "call:launch_app") || strings.Contains(got, "launched") {+ t.Fatalf("%s (limit %d): got %s, want refused", tc.body, tc.limit, got)}}}@@ -184,6 +188,12 @@ func TestScriptGuardRefusesKeysForTheEverydayChrome(t *testing.T) {{`const app = await cua.getApp({pid: 2, windowId: 5}); return app.pressKey("return", "s1:2");`, "pressed"},{`return await cua.call("click", {pid: 1, element_token: "s1:2"});`, "call:click"},{`return await cua.call("launch_app", {bundle_id: "com.google.Chrome"});`, "threw:COMPUTER_SCRIPT_REFUSED"},+ // Arguments that name an app or window of their own would override+ // the app the key is called on.+ {`const app = await cua.getApp({pid: 2, windowId: 5}); return app.hotkey(["cmd", "w"], undefined, {pid: 1});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 2, windowId: 5}); return app.pressKey("return", {app: "Google Chrome"});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`return await cua.call("press_key", {pid: 2, key: "return", target: {pid: 1}});`, "threw:COMPUTER_KEYS_REFUSED"},+ {`const app = await cua.getApp({pid: 2, windowId: 5}); return app.pressKey("return", {role: "AXTextField", name: "Search"});`, "pressed"},// An app object whose pid the guard cannot read could be that Chrome.{`const apps = await cua.listApps(); return apps[0].hotkey(["cmd", "w"]);`, "threw:COMPUTER_KEYS_REFUSED"},{`const app = await cua.getApp({name: "Google Chrome"}); return app.hotkey(["cmd", "w"]);`, "threw:COMPUTER_KEYS_REFUSED"},diff --git a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.goindex 94ebf538..480c9f8a 100644--- a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go@@ -1950,6 +1950,14 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *tt.Fatalf("the user's own Chrome window %v read as the Computer's", user)}}+ // Token s1 was read from the Computer's window 12, so only the rule for+ // keys refuses what follows with it.+ 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["s1"] = windowKey{pid: 42, window: 12}+ c.op.reads.mu.Unlock()// No key reaches the user's Chrome, in the Computer's window or theirs.for _, call := range []struct{ name, args string }{{"hotkey", `{"pid":42,"window_id":12,"keys":["cmd","["]}`},@@ -1958,7 +1966,7 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *t{"press_key", `{"pid":42,"window_id":12,"key":"return"}`},{"press_key", `{"pid":42,"window_id":12,"key":"return","element_token":"s1:1","modifiers":[]}`},{"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"}`},+ {"press_key", `{"pid":42,"window_id":9,"key":"return","element_token":"s9: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.@@ -1982,10 +1990,6 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *tif _, 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)}diff --git a/skills/builtin/humanlike-browse/1.0.5/SKILL.md b/skills/builtin/humanlike-browse/1.0.5/SKILL.mdindex 837c46ef..4fd77b2f 100644--- a/skills/builtin/humanlike-browse/1.0.5/SKILL.md+++ b/skills/builtin/humanlike-browse/1.0.5/SKILL.md@@ -31,7 +31,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.+- Fill a search box with `setValue`, then click the site's search button. Return on the box also works in Safari, 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; only Return bound to the search box of the Computer's window goes, as its own `press_key` call and never inside `run_script`, 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.