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): leave quitting the user's Chrome to the user and refuse its keys in every window
jeffreyd35a1ab351a6
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex 5e3fd806..db5ac5d5 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -331,13 +331,19 @@ Chrome's command line, one site per call, so no key reaches the user's otherwindows. A covered window keeps working only when Chrome runs with`--disable-backgrounding-occluded-windows`: a Chrome that is not runningstarts with it, and one running without it returns-`COMPUTER_BROWSER_RESTART_REQUIRED` until the Agent passes `restart_browser`-after the user agreed. The restart quits Chrome as its menu does and reopens it-with `--restore-last-session`. The user's Chrome takes no keys from the-Computer (`COMPUTER_KEYS_REFUSED`): 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 goes, and Cua sends it only-when no other Chrome window could take it. The Agent fills fields with+`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 asks+the 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`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.diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.goindex 37bc9ec0..a217c74f 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_browser.go@@ -9,10 +9,10 @@ import ("os""os/exec""path/filepath"+ "runtime""slices""strconv""strings"- "syscall""time""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs"@@ -290,9 +290,10 @@ func (c *cuaSession) waitSafariWindows(ctx context.Context, b agentBrowser, pid}// everydayChromePID finds the user's everyday Chrome: the main process of-// Google Chrome on its default profile. Chrome instances on a profile of their-// own, such as a test browser, name --user-data-dir and are not it. It returns-// the pid and command line, or 0 when that Chrome is not running.+// Google Chrome on its default profile, wherever the app is installed. Chrome+// instances on a profile of their own, such as a test browser, name+// --user-data-dir and are not it. It returns the pid and command line, or 0+// when that Chrome is not running.var everydayChromePID = func(ctx context.Context) (int, string, error) {output, err := exec.CommandContext(ctx, "/bin/ps", "-axww", "-o", "pid=,args=").Output()if err != nil {@@ -300,7 +301,7 @@ var everydayChromePID = func(ctx context.Context) (int, string, error) {}for _, line := range strings.Split(string(output), "\n") {pidText, args, _ := strings.Cut(strings.TrimSpace(line), " ")- if !strings.HasPrefix(args, everydayChromeExecutable) || strings.Contains(args, "--type=") || strings.Contains(args, "--user-data-dir=") {+ if !everydayChromeCommand(args) {continue}if pid, err := strconv.Atoi(pidText); err == nil {@@ -310,34 +311,19 @@ var everydayChromePID = func(ctx context.Context) (int, string, error) {return 0, "", nil}-const everydayChromeExecutable = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"--// stopEverydayChrome asks the user's Chrome to quit, as quitting from its-// menu does, and waits until it is gone. Chrome saves its session first, so-// the restart brings back the user's windows and tabs.-var stopEverydayChrome = func(ctx context.Context, pid int) error {- process, err := os.FindProcess(pid)- if err != nil {- return err- }- if err := process.Signal(syscall.SIGTERM); err != nil {- return err- }- for deadline := time.Now().Add(everydayChromeQuitWait); ; {- if running, _, err := everydayChromePID(ctx); err != nil || running == 0 {- return err- }- if time.Now().After(deadline) {- return errors.New("COMPUTER_BROWSER_RESTART_FAILED: the user's Chrome did not quit, so it was not restarted; ask the user to quit Chrome and try again")- }- if err := sleepContext(ctx, 200*time.Millisecond); err != nil {- return err- }- }+// everydayChromeCommand reports whether args starts Google Chrome's own+// executable on the default profile. The executable path has spaces, so it+// ends where the first argument starts.+func everydayChromeCommand(args string) bool {+ index := strings.Index(args, everydayChromeExecutable)+ if !strings.HasPrefix(args, "/") || index < 0 {+ return false+ }+ rest := args[index+len(everydayChromeExecutable):]+ return (rest == "" || rest[0] == ' ') && !strings.Contains(args, "--type=") && !strings.Contains(args, "--user-data-dir=")}-// everydayChromeQuitWait bounds how long the user's Chrome may take to quit.-var everydayChromeQuitWait = 20 * time.Second+const everydayChromeExecutable = "/Google Chrome.app/Contents/MacOS/Google Chrome"// sharedBrowserRunning returns the pid of the user's own browser named by// bundle, or 0.@@ -349,40 +335,45 @@ func sharedBrowserRunning(ctx context.Context, bundle string) (int, error) {return lsappPID(ctx, bundle)}-// everydayChromeRestart asks for the user's consent before the Computer-// restarts their Chrome.-const everydayChromeRestart = "COMPUTER_BROWSER_RESTART_REQUIRED: the user's Chrome runs without the setting that keeps the Computer's window working while other windows cover it, and Chrome takes it only when it starts; nothing was opened. Ask the user with a question card whether the Computer may restart Chrome now: Chrome quits and reopens with their windows and tabs, but text typed into a page and not yet sent may be lost. If the user agrees, call launch_app again with restart_browser: true; if not, end the task"+// everydayChromeQuit asks the user to quit their Chrome. Only the user+// quits it: a quit loses text typed into a page and not yet sent, and no+// tool call can prove the user agreed to that.+const everydayChromeQuit = "COMPUTER_BROWSER_RESTART_REQUIRED: the user's Chrome runs without the setting that keeps the Computer's window working while other windows cover it, and Chrome takes it only when it starts; nothing was opened. Ask the user with a question card to quit Chrome from its menu (Google Chrome > Quit Google Chrome) and leave it closed, then end your turn. When they answer that Chrome is closed, call launch_app again: the Computer starts Chrome with that setting and brings back their windows and tabs. If they decline, end the task"// launchEverydayChrome opens url in a new window of the user's everyday// Chrome, the Computer's own window there, which the task then works in. The// window opens through Chrome's command line, as a link from another app// does, so no key reaches the user's other Chrome windows. A Chrome that is// not running starts with the setting the window needs; one running without-// it restarts only when restart says the user agreed.-func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, urls []string, restart bool) (json.RawMessage, error) {+// it is never quit by the Computer: the user quits it.+func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, urls []string) (json.RawMessage, error) {if len(urls) != 1 {return nil, fmt.Errorf("launch_app opens one site at a time in the user's Chrome; call it once for each site: %w", errNotSent)}+ site := siteOf(urls[0])+ if site == "" {+ return nil, fmt.Errorf("launch_app opens a web address in the user's Chrome: %w", errNotSent)+ }+ m := c.op.managerpid, command, err := everydayChromePID(ctx)if err != nil {return nil, err}- restarted := falseif pid > 0 && !b.startedWith(command) {- if !restart {- return nil, fmt.Errorf("%s: %w", everydayChromeRestart, errNotSent)- }- if err := stopEverydayChrome(ctx, pid); err != nil {- return nil, err- }- pid, restarted = 0, true+ m.mu.Lock()+ m.everydayChromeQuitAsked = true+ m.mu.Unlock()+ return nil, fmt.Errorf("%s: %w", everydayChromeQuit, errNotSent)}+ restored := falseif pid == 0 {- // Chrome starts with the setting first, bringing back the user's- // windows after a restart; the Computer's window opens after them,- // so it is the one window that was not there before.+ // 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...)- if restarted {+ if restored {args = append(args, "--restore-last-session")}if output, err := agentChromeOpen(ctx, args); err != nil {@@ -407,6 +398,9 @@ 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 listedWindowtabs := 0for deadline := time.Now().Add(agentSafariWindowWait); window.WindowID == 0; {@@ -415,11 +409,12 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, ureturn nil, err}for _, w := range windows {- if !before[w.WindowID] {- if n := c.agentChromeTabs(ctx, pid, w.WindowID); n > 0 {- window, tabs = w, n- break- }+ if before[w.WindowID] || siteOf(c.windowAddress(ctx, b, pid, w.WindowID)) != site {+ continue+ }+ if n := c.agentChromeTabs(ctx, pid, w.WindowID); n == 1 {+ window, tabs = w, n+ break}}if window.WindowID != 0 {@@ -432,7 +427,6 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, ureturn nil, err}}- m := c.op.managerm.mu.Lock()m.sharedBrowserBundle, m.sharedBrowserPID, m.sharedBrowserWindow = b.Bundle, pid, window.WindowIDm.mu.Unlock()@@ -440,16 +434,48 @@ func (c *cuaSession) launchEverydayChrome(ctx context.Context, b agentBrowser, uc.op.chromeTabs, c.op.chromePID, c.op.chromeWindow = tabs, pid, window.WindowIDc.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 restarted {- note = "Restarted the user's Chrome with their windows and tabs. " + note+ 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}})}+// 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.+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}})+ if err != nil {+ return ""+ }+ var state struct {+ Structured struct {+ Elements []struct {+ Role string `json:"role"`+ Label string `json:"label"`+ Value any `json:"value"`+ } `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 {+ continue+ }+ if !strings.Contains(value, "://") {+ value = "https://" + value+ }+ return value+ }+ return ""+}+// waitEverydayChrome waits until the user's Chrome that just started runs-// and shows its windows, and returns its pid.+// and shows a window, and returns its pid.func (c *cuaSession) waitEverydayChrome(ctx context.Context) (int, error) {for deadline := time.Now().Add(agentSafariWindowWait); ; {pid, _, err := everydayChromePID(ctx)@@ -460,9 +486,7 @@ func (c *cuaSession) waitEverydayChrome(ctx context.Context) (int, error) {if windows, err := c.appWindows(ctx, pid); err != nil {return 0, err} else if len(windows) > 0 {- // Restored windows appear one after another; a short settle- // keeps a late one from reading as the Computer's.- return pid, sleepContext(ctx, everydayChromeSettle)+ return pid, nil}}if time.Now().After(deadline) {@@ -474,18 +498,28 @@ func (c *cuaSession) waitEverydayChrome(ctx context.Context) (int, error) {}}-// everydayChromeSettle is how long a just-started Chrome gets to reopen the-// user's windows.-var everydayChromeSettle = 2 * time.Second--// everydayChrome reports whether pid is the user's everyday Chrome that the-// Computer opened its window in.-func (c *cuaSession) everydayChrome(pid any) bool {+// 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+ }m := c.op.managerm.mu.Lock()- defer m.mu.Unlock()- return ok && m.sharedBrowserPID > 0 && int(number) == m.sharedBrowserPID && m.sharedBrowserBundle == "com.google.Chrome"+ shared := m.sharedBrowserBundle == "com.google.Chrome" && m.sharedBrowserPID > 0 && int(number) == m.sharedBrowserPID+ m.mu.Unlock()+ if shared {+ return true, nil+ }+ 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)+ }+ return running > 0 && running == int(number), nil}// everydayChromeKeysRefused tells the Agent how to work without keys in the@@ -496,14 +530,20 @@ const everydayChromeKeysRefused = "COMPUTER_KEYS_REFUSED: the user's everyday Ch// plain key bound to an element, such as Return in a search box, may go:// Cua delivers it only when no other Chrome window could receive it.// Shortcuts are menu commands, which Chrome runs in the window that has the-// keyboard, and typed text arrives as keys that all read as the A key.-func everydayChromeKeys(name string, arguments map[string]any) error {- modifiers, _ := arguments["modifiers"].([]any)+// keyboard, and typed text arrives as keys that all read as the A key. own+// says the key names the Computer's window; one of the user's windows takes+// none. The script guard (keyed in guardedScript) applies the same rule.+func everydayChromeKeys(name string, arguments map[string]any, own bool) error {+ if name != "hotkey" && name != "type_text" && name != "press_key" {+ return nil+ }_, bound := arguments["element_token"].(string)- if name == "hotkey" || name == "type_text" || name == "press_key" && (!bound || len(modifiers) > 0) {- return fmt.Errorf("%s: %w", everydayChromeKeysRefused, errNotSent)+ _, modified := arguments["modifiers"]+ key, plain := arguments["key"].(string)+ if own && name == "press_key" && bound && !modified && plain && !strings.Contains(key, "+") {+ return nil}- return nil+ return fmt.Errorf("%s: %w", everydayChromeKeysRefused, errNotSent)}// everydayChromeData is the user's Chrome data folder, whose Local Statediff --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 fccf9d30..abcbb537 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@@ -46,3 +46,44 @@ func TestPickAgentBrowserTakesTheFirstInstalledOrTheNamedOne(t *testing.T) {t.Fatal("agentBrowserApp misread an app")}}++func TestEverydayChromeCommandFindsChromeInAnyFolder(t *testing.T) {+ for args, want := range map[string]bool{+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome": true,+ "/Users/a/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --disable-backgrounding-occluded-windows": true,+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --user-data-dir=/tmp/test": false,+ "/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Framework.framework/Helpers/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper --type=renderer": false,+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary": false,+ "tail -f /Applications/Google Chrome.app/Contents/MacOS/Google Chrome": false,+ } {+ if got := everydayChromeCommand(args); got != want {+ t.Errorf("%q: %v, want %v", args, got, want)+ }+ }+}++func TestEverydayChromeKeysAllowOnlyOnePlainBoundKey(t *testing.T) {+ for _, tc := range []struct {+ name string+ arguments map[string]any+ allowed bool+ }{+ {"press_key", map[string]any{"key": "return", "element_token": "s1:1"}, true},+ {"set_value", map[string]any{"value": "kettle", "element_token": "s1:1"}, true},+ {"press_key", map[string]any{"key": "return"}, false},+ {"press_key", map[string]any{"key": "return", "element_token": "s1:1", "modifiers": []any{}}, false},+ {"press_key", map[string]any{"key": "return", "element_token": "s1:1", "modifiers": "cmd"}, false},+ {"press_key", map[string]any{"key": "cmd+r", "element_token": "s1:1"}, false},+ {"press_key", map[string]any{"key": 13.0, "element_token": "s1:1"}, false},+ {"hotkey", map[string]any{"keys": []any{"cmd", "["}}, false},+ {"type_text", map[string]any{"text": "kettle", "element_token": "s1:1"}, false},+ } {+ if err := everydayChromeKeys(tc.name, tc.arguments, true); (err == nil) != tc.allowed {+ t.Errorf("%s %v: err=%v, want allowed=%v", tc.name, tc.arguments, err, tc.allowed)+ }+ }+ // One of the user's windows takes no key at all.+ if err := everydayChromeKeys("press_key", map[string]any{"key": "return", "element_token": "s1:1"}, false); err == nil {+ t.Error("a bound Return went to one of the user's windows")+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.goindex feff01de..9ffb6d61 100644--- a/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go+++ b/apps/computer/local-daemon/internal/linger/localtools/agent_chrome.go@@ -58,7 +58,7 @@ var agentChromePID = func(ctx context.Context, directory string) (int, string, e// brings its first window forward once, where the user is. Later URLs open// in a new tab through the window's accessibility tree and one Return key to// that browser alone, so the user's apps, focus and Space stay as they are.-func (c *cuaSession) launchAgentChrome(ctx context.Context, b agentBrowser, urls []string, restart bool) (json.RawMessage, error) {+func (c *cuaSession) launchAgentChrome(ctx context.Context, b agentBrowser, urls []string) (json.RawMessage, error) {var sites []stringfor _, address := range urls {if site := siteOf(address); site != "" {@@ -79,7 +79,7 @@ func (c *cuaSession) launchAgentChrome(ctx context.Context, b agentBrowser, urlsreturn nil, err}if b.Everyday {- return c.launchEverydayChrome(ctx, b, urls, restart)+ return c.launchEverydayChrome(ctx, b, urls)}if b.Shared {return c.launchAgentSafari(ctx, b, urls)diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.goindex 2533e485..324df202 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua.go@@ -160,8 +160,7 @@ func (m *Manager) openCua(ctx context.Context, op *operation) (*cuaSession, []toif item.Name == "launch_app" && runtime.GOOS == "darwin" {item.Description = "Open a macOS app in the background through Launch Services, as `open -g` does, and return its pid and windows. Optional urls are handed to the app; for Finder, pass a folder to open it in a window."item.InputSchema = schema(map[string]any{"bundle_id": map[string]string{"type": "string", "description": "Preferred, for example com.apple.TextEdit."}, "name": map[string]string{"type": "string", "description": "App name, when the bundle id is unknown."}, "urls": map[string]any{"type": "array", "items": map[string]string{"type": "string"}, "description": "Files or folders to open in the app."},- "agent_browser": map[string]string{"type": "boolean", "description": "Open the URLs in the Computer's own browser window, which keeps working while other windows cover it on the user's desktop. Only a site's home page opens there, such as https://www.example.com/. With no bundle_id it is the first installed of Chrome, Edge, Firefox and Safari; a bundle_id of com.google.Chrome, com.microsoft.edgemac, org.mozilla.firefox or com.apple.Safari picks one. In Chrome and Safari it is a window of the Computer's own in the user's everyday browser, with the user's sign-ins; in Chrome it opens one site per call. Edge and Firefox run as separate instances with their own sign-ins."},- "restart_browser": map[string]string{"type": "boolean", "description": "With agent_browser in Chrome: restart the user's Chrome so the Computer's window keeps working while covered. Pass it only after the user agreed to a COMPUTER_BROWSER_RESTART_REQUIRED question."}})+ "agent_browser": map[string]string{"type": "boolean", "description": "Open the URLs in the Computer's own browser window, which keeps working while other windows cover it on the user's desktop. Only a site's home page opens there, such as https://www.example.com/. With no bundle_id it is the first installed of Chrome, Edge, Firefox and Safari; a bundle_id of com.google.Chrome, com.microsoft.edgemac, org.mozilla.firefox or com.apple.Safari picks one. In Chrome and Safari it is a window of the Computer's own in the user's everyday browser, with the user's sign-ins; in Chrome it opens one site per call. Edge and Firefox run as separate instances with their own sign-ins."}})}if item.Name == "get_desktop_state" {item.Description += " Read-only whole-screen view; act through the window tools with a pid and window_id. A system privacy prompt about CuaDriver belongs to the user: never answer it, and keep working through the window tools."@@ -396,6 +395,26 @@ 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 {+ 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 {return nil, err@@ -439,14 +458,14 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessagereturn nil, err}}- everyday := paced && c.everydayChrome(target["pid"])- if everyday && name != "run_script" {- if err := everydayChromeKeys(name, arguments); err != nil {- return nil, err- }- }if name == "run_script" {- if err := scriptArguments(ctx, arguments, c.reviewScope(), scriptInputs, everyday); err != nil {+ noKeys := false+ if scriptTarget != nil {+ if noKeys, err = c.userChrome(ctx, scriptTarget["pid"]); err != nil {+ return nil, err+ }+ }+ if err := scriptArguments(ctx, arguments, c.reviewScope(), scriptInputs, noKeys); err != nil {return nil, err}}@@ -1958,8 +1977,7 @@ func (c *cuaSession) launchApp(ctx context.Context, arguments map[string]any) (jif err != nil {return nil, err}- restart, _ := arguments["restart_browser"].(bool)- return c.launchAgentChrome(ctx, b, addresses, restart)+ return c.launchAgentChrome(ctx, b, addresses)}app, flag := bundle, "-b"if app == "" {diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script.goindex e32a1ac1..ab020ee9 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script.go@@ -81,7 +81,7 @@ const apply = Reflect.apply, stringify = JSON.stringify, parse = JSON.parse, tesconst 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));+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 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;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 352d385f..25552cb1 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,7 +14,7 @@ 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"; } }+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"; } }const fake = { call(t, a) { log.push("call:" + t + ":" + JSON.stringify(a)); return Promise.resolve({ok: true}); },getApp() { return Promise.resolve(new App("a")); },listApps() { return Promise.resolve([new App("b")]); },@@ -175,6 +175,11 @@ func TestScriptGuardRefusesKeysForTheEverydayChrome(t *testing.T) {{`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("click", {pid: 1, element_token: "s1:2"});`, "call:click"},} {diff --git a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.goindex 59ae8573..cc18918f 100644--- a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go@@ -215,11 +215,12 @@ 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" {- // Each start or command line of the user's Chrome- // shows one more window beside the user's own.- for i := range strings.Count(string(data), `"name":"open"`) {- windows = append(windows, map[string]any{"pid": 42, "window_id": 11 + i, "title": "Home", "z_index": 2, "is_on_screen": true, "bounds": map[string]any{"width": 900, "height": 700}})+ if 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.+ for _, id := range []int{11, 12} {+ windows = append(windows, map[string]any{"pid": 42, "window_id": id, "title": "Home", "z_index": 2, "is_on_screen": true, "bounds": map[string]any{"width": 900, "height": 700}})}}if mode == "tabs-ghost" {@@ -237,8 +238,15 @@ func runToolFixture(mode string) {for i := range tabs {fmt.Fprintf(&tree, "- [%d] AXRadioButton \"Tab %d\"\n- [%d] AXButton \"Close\" [actions=[press]]\n", 2*i, i, 2*i+1)}+ // The address bar shows its site without the scheme, as+ // 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 address == "" {+ address = "news.example.org/today"+ }result = map[string]any{"content": []any{}, "structuredContent": map[string]any{"tree_markdown": tree.String(), "elements": []any{- map[string]any{"element_token": "s1:1", "role": "AXTextField", "label": "Address and search bar"},+ map[string]any{"element_token": "s1:1", "role": "AXTextField", "label": "Address and search bar", "value": address},}}}}break@@ -1868,8 +1876,9 @@ func TestLocalToolCuaDeltaCountFailureReadsFullWindowOnlyOnce(t *testing.T) {}}-// A launch opens a fresh window when the listed one has left the-// accessibility tree.+// The user quits their Chrome themselves; the Computer then starts it with+// the setting and opens its own window, found by the site it shows, and the+// user's Chrome takes no keys in any of its windows.func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *testing.T) {if runtime.GOOS != "darwin" {t.Skip("the Computer's window in the user's Chrome is macOS only")@@ -1881,22 +1890,15 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *tt.Cleanup(func() { agentChromePause = pause })marker := filepath.Join(t.TempDir(), "calls.jsonl")c := cuaFixtureSession(t, "tabs-everyday", marker)- command := everydayChromeExecutable+ running, command := 42, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"pid := everydayChromePID- everydayChromePID = func(context.Context) (int, string, error) { return 42, command, nil }+ everydayChromePID = func(context.Context) (int, string, error) { return running, command, nil }t.Cleanup(func() { everydayChromePID = pid })- stopped := 0- stop := stopEverydayChrome- stopEverydayChrome = func(context.Context, int) error {- stopped++- command = everydayChromeExecutable + " --disable-backgrounding-occluded-windows"- return nil- }- t.Cleanup(func() { stopEverydayChrome = stop })var opened [][]stringopen := agentChromeOpenagentChromeOpen = func(_ context.Context, args []string) ([]byte, error) {opened = append(opened, args)+ running, command = 42, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --disable-backgrounding-occluded-windows"f, err := os.OpenFile(marker, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)if err != nil {return nil, err@@ -1909,26 +1911,25 @@ 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 restarts only with consent.- if _, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"}, false); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_BROWSER_RESTART_REQUIRED") || stopped != 0 || len(opened) != 0 {- t.Fatalf("err=%v stopped=%d opened=%v, want a refused launch", err, stopped, opened)- }- result, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"}, true)+ // 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 {+ t.Fatalf("err=%v opened=%v, want a refused launch", err, opened)+ }+ // The user quits it; the Computer starts it with the setting and their+ // windows, then opens the site in a new window.+ running = 0+ result, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"})if err != nil {t.Fatal(err)}- if stopped != 1 || 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/"}) {- t.Fatalf("stopped=%d opened=%v, want a restart, then the site in a new window", stopped, opened)+ 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/"}) {+ 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.if !strings.Contains(string(result), `"window_id":12`) || !strings.Contains(string(result), "takes no keys") {- t.Fatalf("result=%s, want the new window 12 after the restored one, and the note", result)+ t.Fatalf("result=%s, want the new window 12 that shows the site, and the note", result)}- // The new window is the Computer's: input to it is paced and held, and- // the user's own window 9 is not the Computer's.if own, err := c.isAgentChrome(t.Context(), float64(42), float64(12)); err != nil || !own {t.Fatalf("own=%v err=%v, want window 12 as the Computer's", own, err)}@@ -1937,37 +1938,43 @@ func TestLocalToolCuaMacEverydayChromeOpensTheComputersWindowAndTakesNoKeys(t *tt.Fatalf("the user's own Chrome window %v read as the Computer's", user)}}- for _, call := range []string{- `{"pid":42,"window_id":12,"keys":["cmd","["]}`,+ // 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","["]}`},+ {"hotkey", `{"pid":42,"window_id":9,"keys":["cmd","w"]}`},+ {"type_text", `{"pid":42,"window_id":12,"text":"kettle","element_token":"s1:1"}`},+ {"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"}`},+ {"recognize_text", `{"pid":42,"window_id":12,"pages":2,"next_key":"pagedown"}`},} {- if _, err := c.call(t.Context(), "hotkey", json.RawMessage(call)); !strings.Contains(fmt.Sprint(err), "COMPUTER_KEYS_REFUSED") {- t.Fatalf("hotkey err=%v, want refused", err)+ 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)}}- if _, err := c.call(t.Context(), "type_text", json.RawMessage(`{"pid":42,"window_id":12,"text":"kettle","element_token":"s1:1"}`)); !strings.Contains(fmt.Sprint(err), "COMPUTER_KEYS_REFUSED") {- t.Fatalf("type_text err=%v, want refused", err)- }- if _, err := c.call(t.Context(), "press_key", json.RawMessage(`{"pid":42,"window_id":12,"key":"return"}`)); !strings.Contains(fmt.Sprint(err), "COMPUTER_KEYS_REFUSED") {- t.Fatalf("unbound press_key err=%v, want refused", err)- }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 may not send keys either.- if _, err := c.call(t.Context(), "run_script", json.RawMessage(`{"script":"return 1"}`)); err != nil {- t.Fatal(err)- }- if calls := fixtureCalls(t, marker); !strings.Contains(fmt.Sprint(calls[len(calls)-1]), "noKeys = true") {- t.Fatalf("last call=%v, want a script guarded against keys", calls[len(calls)-1])+ // 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}}`} {+ 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") {+ t.Fatalf("%s: last call=%v, want a script guarded against keys", script, calls[len(calls)-1])+ }}if err := c.drain(); err != nil {t.Fatal(err)}}+// A launch opens a fresh window when the listed one has left the+// accessibility tree.func TestLocalToolCuaMacAgentChromeOpensAFreshWindowForAnUnreadableOne(t *testing.T) {if runtime.GOOS != "darwin" {t.Skip("the Computer's own Chrome is macOS only")@@ -1997,7 +2004,7 @@ func TestLocalToolCuaMacAgentChromeOpensAFreshWindowForAnUnreadableOne(t *testin}t.Cleanup(func() { agentChromeOpen = open })b := agentBrowser{Name: "Chrome", Bundle: "com.google.Chrome", Directory: "agent-chrome-test", Args: func(string) []string { return nil }, AddressRole: "AXTextField", AddressLabel: "Address and search bar"}- result, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"}, false)+ result, err := c.launchAgentChrome(t.Context(), b, []string{"https://example.com/"})if err != nil {t.Fatal(err)}diff --git a/apps/computer/local-daemon/internal/linger/localtools/manager.go b/apps/computer/local-daemon/internal/linger/localtools/manager.goindex 201295ca..ed46edf5 100644--- a/apps/computer/local-daemon/internal/linger/localtools/manager.go+++ b/apps/computer/local-daemon/internal/linger/localtools/manager.go@@ -98,6 +98,9 @@ type Manager struct {sharedBrowserBundle stringsharedBrowserPID intsharedBrowserWindow 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// paceMu guards the persisted pace record of the Computer's own browser// and paceLast, when that Chrome last received input; see// paceAgentChrome.diff --git a/skills/builtin/humanlike-browse/1.0.5/SKILL.md b/skills/builtin/humanlike-browse/1.0.5/SKILL.mdindex 8c0b3f7a..2d80eed4 100644--- a/skills/builtin/humanlike-browse/1.0.5/SKILL.md+++ b/skills/builtin/humanlike-browse/1.0.5/SKILL.md@@ -11,7 +11,7 @@ description: Read, survey, post to or manage a site that watches for automated b- Anything else on a social network, a marketplace or a site where the user is signed in: only the computer tools, through `launch_app({agent_browser: true, urls: [url]})`. In Chrome or Safari this opens a window of the Computer's own in the user's everyday browser, with the user's sign-ins; Edge and Firefox run as separate instances. Pass `bundle_id` only when the user asks for one browser. The browser tools drive a page in a way these sites detect, so never use them on these sites; the Computer keeps them off every site the task opened this way.- If `launch_app` has no `agent_browser`, this needs a Mac Computer: tell the user and stop.- If a call says a computer tool does not exist, take the tool's exact name from your tool list and call it again before telling the user the tools are unavailable.-- If `launch_app` answers `COMPUTER_BROWSER_RESTART_REQUIRED`, ask the user with a question card whether the Computer may restart Chrome, saying that their windows and tabs come back. Only if they agree, call `launch_app` again with `restart_browser: true`; otherwise end the task.+- If `launch_app` answers `COMPUTER_BROWSER_RESTART_REQUIRED`, ask the user with a question card to quit Chrome from its menu and leave it closed, saying that the Computer starts it again with their windows and tabs; then end your turn. When they answer that Chrome is closed, call `launch_app` again; if they decline, end the task.- If the site asks to sign in, ask the user to sign in once in that browser window and stop; the sign-in stays for later tasks.## Move like a person