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.
feat(computer): run each Agent's browser calls in its own lane
jeffrey4f6e3969b9cf
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex b8fb670d..e343371b 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -178,8 +178,21 @@ Daemon stops the old service before starting the new one. The Daemon takes theservice's pid from the socket peer rather than a file in /tmp, which macOS cleansafter 3 days unused.-On one computer, an input call holds the screen and clipboard until it ends, and-other tasks' input calls queue. A queued call that is cancelled returns+On one computer, a desktop call holds the screen and clipboard until it ends, and+other tasks' desktop calls queue. Browser calls run in lanes of their own, one+per Agent: the tasks of one Agent take turns in its browser, and different+Agents' browser calls run at the same time as each other and as desktop reads.+A desktop input that needs the front window or the clipboard waits for the+browser calls in flight. From the moment it starts waiting, new browser calls+wait for it, because a browser call can bring Chrome forward or copy and paste+in the page. These inputs are keys and text, foreground and modifier clicks,+double-clicks, which may fall back to the front app, drags, cursor moves,+scripts, batches, app launches, bringing a window to the front, window moves,+the clipboard tools, all native Linux input, every Windows input, and text+recognition on Windows or when it pages on macOS. A+macOS background click, right-click or scroll to a known app runs beside+browser calls, unless the app is a Chromium browser other than the Computer's+own Chrome. A queued call that is cancelled returns`COMPUTER_BUSY` without sending input. `check_permissions` only reads permissionsand never requests them, and the permission answer must come from the Cua serviceitself. Only the owner's Request on a permission card asks macOS: the Daemon runs@@ -231,8 +244,7 @@ application. Before pasting it saves the whole clipboard and restores it 200 msafter the paste, unless someone changed the clipboard in between. It alsorestores on cancellation; saving and restoring each have a 5-second limit thatcancellation does not shorten. A file the Agent copied in Finder before typing a-path therefore stays on the clipboard. Every Cua call and every browser action-share one input lock.+path therefore stays on the clipboard. No browser call runs during the paste.A single macOS input tool reports only whether the input was delivered;`run_actions` reads the window once after the last step. When a Finder list row@@ -329,7 +341,16 @@ the 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 neitherpaced nor held, and a paced script may not call `launch_app`.-The two macOS tool groups share one persistent action record. After a+Desktop input keeps one persistent action record,+`computer-tools/action.json`. Each Agent's browser and each seat in the+everyday Chrome keep their own, `computer-tools/action-browser-<hash>.json`.+Each record file is removed once its action settles. An unknown record blocks its own desktop, Agent browser or seat,+and a Daemon restart reads every record again. The two sides also block each+other where one could still reach the other: an unknown browser action blocks+desktop input that needs the front window or the clipboard, and an unknown+desktop input of that kind blocks browser calls, so does a record that an+older Daemon left without saying which kind it was. Such a call returns+`COMPUTER_ACTION_UNKNOWN`. After acancellation, the original connection must confirm that the Cua session wascleaned up; the exit of a shared service's proxy process does not count, and aDaemon restart does not clear unknown actions. Without the original connection's@@ -427,15 +448,23 @@ same Agent profile, identified by the profile's `SingletonLock` and thatprocess's command line. Otherwise Chrome would hand every new launch to theold process. A managed Chrome that exits during a task, closed by the user orcrashed, starts again on the next browser call. A cancelled browser call whose-outcome is unknown blocks later input until its task ends; the task then stops-the Agent Chrome, which proves no command still runs, and settles the record.-The owner's everyday Chrome is never stopped. Its unknown action settles once-the task's Playwright child, the only sender, has stopped. One task or Live-call holds the owner's Chrome profile at a time. A task waits up to 40 seconds-for it and a Live call up to 8 seconds; the call then fails with-`BROWSER_BUSY`, which Live reports as `browser_busy`. A task passes the-profile on when it ends and its Playwright child has stopped, even when an-unrelated part of its cleanup fails. The `computer` tool names are Cua 0.35.4's real names, such as+outcome is unknown blocks that Agent's later browser calls until its task ends;+the task then stops the Agent Chrome, which proves no command still runs, and+settles the record. The owner's everyday Chrome is never stopped. A task holds+one seat in it. When every installed version of the Playwright Extension in+the profile is 0.5.0 or later, the extension keeps several Playwright clients+connected, each in its own tab group. Each Agent then has its own seat, and+Agents work in their own background tabs at once. An earlier extension may drop+one client when the next connects, so its whole profile is one seat. Release+bundles patch Playwright to keep focus emulation on its CDP connections, this+Chrome and the Agent Chrome alike. Without it a background tab is hidden: it+stops rendering, clicks wait for it, and mouse and key events are lost. One task or Live call holds a seat at a time, so tasks of+one Agent take turns. An unknown action blocks the calls to its seat and+settles once the task's Playwright child, the only sender, has stopped. A task+waits up to 40 seconds for a seat and a Live call up to 8 seconds; the call+then fails with `BROWSER_BUSY`, which Live reports as `browser_busy`. A task+passes the seat on when it ends and its Playwright child has stopped, even when+an unrelated part of its cleanup fails. The `computer` tool names are Cua 0.35.4's real names, such as`move_cursor`, `press_key`, `launch_app` and `bring_to_front`. `doctor` reportsChrome and the extension.diff --git a/apps/computer/local-daemon/internal/linger/localtools/browser.go b/apps/computer/local-daemon/internal/linger/localtools/browser.goindex 2fa6875b..602843f1 100644--- a/apps/computer/local-daemon/internal/linger/localtools/browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/browser.go@@ -4,6 +4,7 @@ import ("context""encoding/json""errors"+ "fmt""os""path/filepath""regexp"@@ -32,30 +33,63 @@ var liveProfileWait = 8 * time.Secondvar errBrowserBusy = errors.New("BROWSER_BUSY: the user's Chrome is in use by another task or browser call. No action was taken; retry after it finishes")// nativeBrowserCall runs one browser tool in the Agent Chrome profile or in-// the owner's connected Chrome. It never depends on the desktop driver; the-// shared action journal still serializes it with desktop input.+// the owner's connected Chrome. It never depends on the desktop driver and+// runs in its Agent's browser lane, beside desktop input and other Agents'+// browser calls.func (op *operation) nativeBrowserCall(ctx context.Context, name string, args json.RawMessage) (output json.RawMessage, callErr error) {op.manager.retryCleanup()+ // Calls of one task take turns from here on: switching to the owner's+ // Chrome below ends the session an earlier call may still be using.+ release, err := op.holdBrowserCalls(ctx)+ if err != nil {+ return nil, err+ }+ defer release()chrome, err := op.resolveUserChrome(ctx)if err != nil {return nil, err}+ seat := ""if chrome != nil {- if err := op.holdUserChromeProfile(ctx, chrome.Profile); err != nil {+ if seat, err = op.holdUserChromeProfile(ctx, chrome.Profile); err != nil {return nil, err}}- ctx, release, err := op.manager.holdInputs(ctx)+ ctx, releaseLane, err := op.manager.holdLane(ctx, browserLane(op.spec.AgentID))if err != nil {return nil, err}- defer release()+ defer releaseLane()+ ctx, releaseFocus, err := op.manager.holdBrowserFocus(ctx)+ if err != nil {+ return nil, err+ }+ defer releaseFocus()if chrome == nil {if err := op.dropExitedBrowser(); err != nil {return nil, err}}- receipt, err := op.manager.journal.begin(ctx, actionIdentity{AgentID: op.spec.AgentID, OperationID: op.identity.OperationID, Session: op.label + "-browser"})+ // This task holds one unknown action at a time: an Agent Chrome action+ // left before the owner connected their Chrome settles when the task+ // ends, and a second one would take its place.+ op.mu.Lock()+ unknown := op.browserUnknown != nil+ op.mu.Unlock()+ if unknown {+ return nil, fmt.Errorf("COMPUTER_ACTION_UNKNOWN: an earlier browser action of this task has no verified cleanup receipt; the browser stays blocked until the task ends: %w", errNotSent)+ }+ // An Agent Chrome action is recorded for that Agent; one in the owner's+ // Chrome for the seat this task holds, which another task may take next.+ journalName := browserLane(op.spec.AgentID)+ if chrome != nil {+ journalName = chromeProfileJournal(seat)+ }+ journal, err := op.manager.namedJournal(journalName)+ if err != nil {+ return nil, err+ }+ receipt, err := journal.begin(ctx, actionIdentity{AgentID: op.spec.AgentID, OperationID: op.identity.OperationID, Session: op.label + "-browser"})if err != nil {return nil, err}@@ -108,14 +142,6 @@ func (op *operation) nativeBrowserCall(ctx context.Context, name string, args js// which later tasks of the same Agent reuse.// A rejected token fails the call: it never falls back to the Agent profile.func (op *operation) userChromeCall(ctx context.Context, chrome *browserConnection, name string, args json.RawMessage, confirmed *bool) (json.RawMessage, error) {- // A parallel call may have rejected or replaced this connection while- // this one waited for the journal; never restart a relay for it.- op.connectMu.Lock()- current := op.userChrome == chrome && !op.userChromeRejected.Load()- op.connectMu.Unlock()- if !current {- return nil, errUserChromeRejected- }var err errorif op.browser == nil {session, err := op.manager.checkoutUserChrome(ctx, op, chrome)@@ -148,26 +174,41 @@ func (op *operation) userChromeCall(ctx context.Context, chrome *browserConnectireturn result, err}-// holdUserChromeProfile admits this Operation to its everyday Chrome profile-// for the rest of the task. It waits outside the action journal: that queue-// serializes input of every Operation, including the task holding the profile.-func (op *operation) holdUserChromeProfile(ctx context.Context, profile string) error {+// holdBrowserCalls admits one browser call of this Operation at a time. The+// calls share op.browser, op.nativeBrowser, op.nativeProxy and the owner's+// Chrome session, which a call replaces when the owner connects mid-task.+func (op *operation) holdBrowserCalls(ctx context.Context) (func(), error) {+ op.browserCallsOnce.Do(func() { op.browserCalls = make(chan struct{}, 1) })+ select {+ case op.browserCalls <- struct{}{}:+ return func() { <-op.browserCalls }, nil+ case <-ctx.Done():+ return nil, fmt.Errorf("COMPUTER_BUSY: another browser call of this task was running until this call ended (%v): %w", ctx.Err(), errNotSent) //nolint:errorlint // the wait's end is detail; the call classifies as not sent only+ }+}++// holdUserChromeProfile admits this Operation to its seat in the everyday+// Chrome profile for the rest of the task and returns the seat. It waits+// outside the browser lane: another task of the same Agent may hold the seat+// and wait for that lane.+func (op *operation) holdUserChromeProfile(ctx context.Context, profile string) (string, error) {op.profileMu.Lock()defer op.profileMu.Unlock()if op.releaseProfile != nil {- return nil+ return op.chromeSeat, nil}if op.live {var cancel context.CancelFuncctx, cancel = context.WithTimeoutCause(ctx, liveProfileWait, errBrowserBusy)defer cancel()}- release, err := op.manager.acquireChromeProfile(ctx, profile)+ seat := userChromeSeat(op.manager.env, profile, op.spec.AgentID)+ release, err := op.manager.acquireChromeProfile(ctx, seat)if err != nil {- return err+ return "", err}- op.releaseProfile = release- return nil+ op.releaseProfile, op.chromeSeat = release, seat+ return seat, nil}var errUserChromeRequired = errors.New("BROWSER_CONNECTION_REQUIRED: the user has not connected their everyday Chrome. Run `teamhub browser connect` to post a connection card for them in this chat, then end your turn; the card result wakes you when they connect or decline. Do not use another browser or tool instead, and never ask for the token in a message")@@ -245,7 +286,7 @@ func (op *operation) releaseChromeProfile() {defer op.profileMu.Unlock()if op.releaseProfile != nil {op.releaseProfile()- op.releaseProfile = nil+ op.releaseProfile, op.chromeSeat = nil, ""}}@@ -266,12 +307,14 @@ func BrowserCallNotRun(err error) string {return ""}-func (m *Manager) acquireChromeProfile(ctx context.Context, profile string) (func(), error) {+// acquireChromeProfile admits a task to one seat in an everyday Chrome+// profile; see userChromeSeat.+func (m *Manager) acquireChromeProfile(ctx context.Context, seat string) (func(), error) {m.mu.Lock()- slot := m.chromeProfiles[profile]+ slot := m.chromeProfiles[seat]if slot == nil {slot = make(chan struct{}, 1)- m.chromeProfiles[profile] = slot+ m.chromeProfiles[seat] = slot}m.mu.Unlock()waitCtx, cancel := context.WithTimeout(ctx, profileWait)@@ -284,8 +327,8 @@ func (m *Manager) acquireChromeProfile(ctx context.Context, profile string) (funreturn releaseOnce(slot), nildefault:}- // A Live call between turns gives the profile up to a task.- m.releaseIdleLiveChrome(profile)+ // A Live call between turns gives the seat up to a task.+ m.releaseIdleLiveChrome(seat)select {case slot <- struct{}{}:return releaseOnce(slot), nil@@ -299,7 +342,8 @@ func (m *Manager) acquireChromeProfile(ctx context.Context, profile string) (fun}}-// tryChromeProfile admits a caller only when no task holds the profile.+// tryChromeProfile admits a caller only when no task holds the whole+// profile, as it does while the extension keeps one client.func (m *Manager) tryChromeProfile(profile string) (func(), bool) {m.mu.Lock()slot := m.chromeProfiles[profile]@@ -391,7 +435,8 @@ func (op *operation) markBrowserUnknown(receipt *actionReceipt, userChrome bool)}// settleBrowserUnknown completes a browser action whose outcome is unknown,-// which otherwise blocks every later input on this Computer. Only a stopped+// which otherwise blocks later calls to the same Agent browser or everyday+// Chrome seat, and desktop input that needs the front window or the clipboard. Only a stopped// sender proves that none of its commands still runs. For the Agent Chrome// this stops that browser; the next call starts it again with the same// profile. The owner's everyday Chrome is never stopped: its action settlesdiff --git a/apps/computer/local-daemon/internal/linger/localtools/browser_connection.go b/apps/computer/local-daemon/internal/linger/localtools/browser_connection.goindex ddbe4c25..78aec595 100644--- a/apps/computer/local-daemon/internal/linger/localtools/browser_connection.go+++ b/apps/computer/local-daemon/internal/linger/localtools/browser_connection.go@@ -207,16 +207,17 @@ func (m *Manager) BrowserConnection(ctx context.Context, tenantID, ownerActorID,if err != nil {return BrowserStatus{}, err}- // A running task owns this profile's extension connection. Verifying now- // would open a second relay into it, so ask the owner to retry instead.- release, admitted := m.tryChromeProfile(chrome.profile)- if !admitted {- return BrowserStatus{}, &BrowserCommandError{"BROWSER_BUSY", "an Agent task is using this Chrome; try again after it finishes", true}+ // An extension that keeps one client lets verifying take it from a task.+ // A running task then owns it, so ask the owner to retry instead, and+ // stop an idle relay of an earlier task before verifying opens another.+ if !extensionTakesManyClients(m.env, chrome.profile) {+ release, admitted := m.tryChromeProfile(chrome.profile)+ if !admitted {+ return BrowserStatus{}, &BrowserCommandError{"BROWSER_BUSY", "an Agent task is using this Chrome; try again after it finishes", true}+ }+ defer release()+ m.closeIdleUserChrome(func(s *userChromeSession) bool { return s.profile == chrome.profile })}- defer release()- // An idle relay of an earlier task still holds this profile's extension- // connection; stop it before verifying opens another.- m.closeIdleUserChrome(func(s *userChromeSession) bool { return s.profile == chrome.profile })connection := &browserConnection{TenantID: tenantID, OwnerActorID: ownerActorID, Profile: chrome.profile, Token: token, State: browserConnected, ConfiguredAt: time.Now().UTC()}// The token is accepted only after the extension really connects; a// rejected one is never stored, so nothing switches silently.diff --git a/apps/computer/local-daemon/internal/linger/localtools/browser_socket_test.go b/apps/computer/local-daemon/internal/linger/localtools/browser_socket_test.goindex a331cb89..e2e98309 100644--- a/apps/computer/local-daemon/internal/linger/localtools/browser_socket_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/browser_socket_test.go@@ -214,8 +214,9 @@ func TestBrowserActiveInitializationFailureFollowsCleanupReceipt(t *testing.T) {m.options.NodePath = filepath.Join(t.TempDir(), "missing-node")}_, err = op.nativeBrowserCall(t.Context(), "browser_snapshot", json.RawMessage(`{}`))- if err == nil || errors.Is(err, mcpproxy.ErrCleanupUnconfirmed) != unknown || m.journal.blocked() != unknown || (op.browser != nil) != unknown {- t.Fatalf("initialization outcome was not preserved: unknown=%v, client=%v, blocked=%v, err=%v", unknown, op.browser != nil, m.journal.blocked(), err)+ blocked := laneBlocked(t, m, browserLane("fixture"))+ if err == nil || errors.Is(err, mcpproxy.ErrCleanupUnconfirmed) != unknown || blocked != unknown || m.journal.blocked() || (op.browser != nil) != unknown {+ t.Fatalf("initialization outcome was not preserved: unknown=%v, client=%v, blocked=%v, err=%v", unknown, op.browser != nil, blocked, err)}if unknown {if _, err := op.nativeBrowserCall(t.Context(), "browser_snapshot", json.RawMessage(`{}`)); err == nil {diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.goindex b4d30984..f2141dc4 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua.go@@ -341,11 +341,18 @@ func (c *cuaSession) permissions(ctx context.Context) (json.RawMessage, error) {}func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessage) (output json.RawMessage, callErr error) {- ctx, release, err := c.op.manager.holdInputs(ctx)+ ctx, release, err := c.op.manager.holdLane(ctx, desktopLane)if err != nil {return nil, err}defer release()+ if c.needsFocus(ctx, name, args) {+ var releaseFocus func()+ if ctx, releaseFocus, err = c.op.manager.holdFocusedInput(ctx); err != nil {+ return nil, err+ }+ defer releaseFocus()+ }c.mu.Lock()pending := c.unknown != nilc.mu.Unlock()@@ -434,7 +441,7 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessage// Only the retained original transport can drain an older cancelled call.// This never constructs a new client to clear an unknown prior action.c.op.manager.retryCleanup()- receipt, err := c.op.manager.journal.begin(ctx, actionIdentity{AgentID: c.op.spec.AgentID, OperationID: c.op.identity.OperationID, Session: c.label})+ receipt, err := c.op.manager.journal.begin(ctx, actionIdentity{AgentID: c.op.spec.AgentID, OperationID: c.op.identity.OperationID, Session: c.label, Background: !holdsFocus(ctx)})if err != nil {return nil, err}@@ -519,6 +526,47 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessagereturn c.finishInput(ctx, name, arguments, appKeys, result, err)}+// cuaReadTools send no input.+var cuaReadTools = map[string]bool{"list_windows": true, "get_window_state": true, "get_desktop_state": true, "get_screen_size": true, "get_cursor_position": true, checkPermissionsTool: true, "report_blocker": true}++// backgroundTools are the macOS inputs Cua delivers to the target app in the+// background, without the front window or the clipboard. A double-click is+// not one: when a Finder row refuses AXOpen, sendInput brings Finder to the+// front and double-clicks there.+var backgroundTools = map[string]bool{"click": true, "right_click": true, "scroll": true}++// needsFocus reports a call that must not run beside browser calls; see+// focusGate. Only reads and a macOS background input to a known app other+// than a Chromium browser run beside them. Keys and text may go to the+// front app or through the clipboard, and a script or a batch may send+// anything. Chrome is left out because its window may be a Playwright+// browser's, whose page a background click would meet mid-action.+func (c *cuaSession) needsFocus(ctx context.Context, name string, args json.RawMessage) bool {+ switch {+ case cuaReadTools[name]:+ return false+ case name == "recognize_text":+ // A paged read presses keys in the window.+ return runtime.GOOS != "darwin" || pagedRead(args)+ case runtime.GOOS != "darwin" || !backgroundTools[name]:+ return true+ }+ var arguments map[string]any+ if json.Unmarshal(args, &arguments) != nil {+ return true+ }+ if modifiers, _ := arguments["modifier"].([]any); len(modifiers) > 0 || foregroundInput(name, arguments) {+ return true+ }+ pid, _ := arguments["pid"].(float64)+ if token, ok := arguments["element_token"].(string); ok && pid == 0 {+ if key, _, found := c.op.reads.row(token); found {+ pid = float64(key.pid)+ }+ }+ return pid <= 0 || c.op.manager.chromiumProcess(ctx, int(pid))+}+// checkPermissionsCall answers check_permissions, which sends no input.func (c *cuaSession) checkPermissionsCall(ctx context.Context) (json.RawMessage, error) {result, err := c.permissions(ctx)diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_peer_darwin_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_peer_darwin_test.goindex 1d139338..49ccd9cb 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_peer_darwin_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_peer_darwin_test.go@@ -1,6 +1,7 @@package localtoolsimport (+ "io""net""os""path/filepath"@@ -21,7 +22,10 @@ func TestCuaServicePIDNamesTheListeningProcess(t *testing.T) {}defer listener.Close()go func() {+ // Close only after the caller does: the pid read fails on a+ // connection this side already closed.if connection, err := listener.Accept(); err == nil {+ _, _ = io.Copy(io.Discard, connection)_ = connection.Close()}}()diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script.goindex ba8aceae..3126e360 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script.go@@ -130,7 +130,7 @@ func forbiddenKey(value any, word string) bool {// scriptArguments checks a run_script call, reads a Skill's script file into// script with args as a constant on its first line, and fits its time limit-// into what remains of the call after waiting for the input lock. In a+// 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) error {diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_service_darwin_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_service_darwin_test.goindex c5142a87..298fee65 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_service_darwin_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_service_darwin_test.go@@ -1,6 +1,7 @@package localtoolsimport (+ "io""net""os""os/exec"@@ -27,7 +28,13 @@ func TestCuaServiceFixtureProcess(t *testing.T) {if err != nil {return}- _ = connection.Close()+ // Keep the connection until the caller closes it, as the real service+ // does: a caller reads the peer pid after connecting, and that read+ // fails once this side has closed.+ go func() {+ _, _ = io.Copy(io.Discard, connection)+ _ = connection.Close()+ }()}}diff --git a/apps/computer/local-daemon/internal/linger/localtools/evidence.go b/apps/computer/local-daemon/internal/linger/localtools/evidence.goindex 55903c76..c12fbfa0 100644--- a/apps/computer/local-daemon/internal/linger/localtools/evidence.go+++ b/apps/computer/local-daemon/internal/linger/localtools/evidence.go@@ -98,11 +98,23 @@ var screenshotLink = regexp.MustCompile(`\]\(([^)\n]+\.jpeg)\)`)// browserScreenshot captures the visible page. Playwright also saves the// image in the Operation's output directory; that copy is removed.func (op *operation) browserScreenshot(ctx context.Context) *permission.Screenshot {- ctx, release, err := op.manager.holdInputs(ctx)+ releaseCalls, err := op.holdBrowserCalls(ctx)+ if err != nil {+ return nil+ }+ defer releaseCalls()+ ctx, release, err := op.manager.holdLane(ctx, browserLane(op.spec.AgentID))if err != nil {return nil}defer release()+ // Playwright opens a page again before the capture when the last one+ // closed, as a browser call does.+ ctx, releaseFocus, err := op.manager.holdBrowserFocus(ctx)+ if err != nil {+ return nil+ }+ defer releaseFocus()if op.browser == nil {return nil}diff --git a/apps/computer/local-daemon/internal/linger/localtools/focus.go b/apps/computer/local-daemon/internal/linger/localtools/focus.gonew file mode 100644index 00000000..f06a8fe9--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/focus.go@@ -0,0 +1,176 @@+package localtools++import (+ "context"+ "errors"+ "fmt"+ "os/exec"+ "strconv"+ "strings"+ "sync"+)++// focusGate admits any number of browser calls at once, or one desktop input+// that depends on the front window or the clipboard. A browser call can bring+// Chrome forward, as a new or selected tab or a page Playwright opens again+// does, and a key combination in the page can copy or paste through the+// clipboard; keys, pastes and foreground clicks sent to the desktop at that+// moment would land in Chrome or paste the page's text. A waiting desktop+// input holds back new browser calls, so a stream of them cannot starve it.+type focusGate struct {+ mu sync.Mutex+ readers int+ writer bool+ waiting int+ changed chan struct{}+ // chromium remembers the pids found running a Chromium browser; see+ // chromiumProcess.+ chromium map[int]bool+}++// focusHeld marks a context whose call holds the gate; its value is true for+// the exclusive hold.+type focusHeld struct{}++// holdFocus takes the gate, shared for a browser call or exclusive for a+// desktop input. A context that already holds it exclusively takes nothing.+func (m *Manager) holdFocus(ctx context.Context, exclusive bool) (context.Context, func(), error) {+ if held, ok := ctx.Value(focusHeld{}).(bool); ok {+ if held || !exclusive {+ return ctx, func() {}, nil+ }+ return ctx, nil, errors.New("a call that holds the browser side of the focus gate cannot send desktop input")+ }+ g := &m.focus+ g.mu.Lock()+ if exclusive {+ g.waiting+++ }+ for {+ free := !g.writer && (exclusive && g.readers == 0 || !exclusive && g.waiting == 0)+ if free {+ if exclusive {+ g.waiting--+ g.writer = true+ } else {+ g.readers+++ }+ g.mu.Unlock()+ return context.WithValue(ctx, focusHeld{}, exclusive), func() { g.release(exclusive) }, nil+ }+ if g.changed == nil {+ g.changed = make(chan struct{})+ }+ changed := g.changed+ g.mu.Unlock()+ select {+ case <-changed:+ g.mu.Lock()+ case <-ctx.Done():+ g.mu.Lock()+ if exclusive {+ g.waiting--+ g.wake()+ }+ g.mu.Unlock()+ return ctx, nil, fmt.Errorf("COMPUTER_BUSY: desktop input and browser calls were taking turns until this call ended (%v): %w", ctx.Err(), errNotSent) //nolint:errorlint // the wait's end is detail; the call classifies as not sent only+ }+ }+}++// holdFocusedInput takes the gate for a desktop input that needs the front+// window or the clipboard. A browser action of unknown outcome may still bring+// Chrome forward or use the clipboard, so it refuses the input until that+// action settles.+func (m *Manager) holdFocusedInput(ctx context.Context) (context.Context, func(), error) {+ held := holdsFocus(ctx)+ ctx, release, err := m.holdFocus(ctx, true)+ if err != nil || held {+ return ctx, release, err+ }+ if m.browserActionUnknown() {+ release()+ return ctx, nil, fmt.Errorf("COMPUTER_ACTION_UNKNOWN: an earlier browser action has no verified cleanup receipt; input that needs the front window or the clipboard waits until its task ends; a restart alone does not clear it: %w", errNotSent)+ }+ return ctx, release, nil+}++// holdBrowserFocus takes the gate for a browser call, which an unknown+// desktop input that needed the front window or the clipboard refuses.+func (m *Manager) holdBrowserFocus(ctx context.Context) (context.Context, func(), error) {+ ctx, release, err := m.holdFocus(ctx, false)+ if err != nil {+ return ctx, nil, err+ }+ if m.journal.blocksFocus() {+ release()+ return ctx, nil, fmt.Errorf("COMPUTER_ACTION_UNKNOWN: an earlier desktop input that needed the front window or the clipboard has no verified cleanup receipt; browser calls wait until its task ends; a restart alone does not clear it: %w", errNotSent)+ }+ return ctx, release, nil+}++// holdsFocus reports whether ctx holds the gate exclusively.+func holdsFocus(ctx context.Context) bool {+ held, _ := ctx.Value(focusHeld{}).(bool)+ return held+}++// chromiumProcess reports whether pid runs a Chromium browser other than the+// Computer's own browser, which only Cua drives. A pid found running one is+// not looked up again.+func (m *Manager) chromiumProcess(ctx context.Context, pid int) bool {+ m.mu.Lock()+ own := m.agentChromePID == pid+ m.mu.Unlock()+ if own {+ return false+ }+ m.focus.mu.Lock()+ known := m.focus.chromium[pid]+ m.focus.mu.Unlock()+ if known {+ return true+ }+ app, err := processCommand(ctx, pid)+ if err != nil {+ // Unknown counts as Chromium; an exited pid is not remembered.+ return true+ }+ chromium := strings.Contains(app, "Chrom") || strings.Contains(app, "Microsoft Edge") || strings.Contains(app, "Brave")+ if chromium {+ // Only Chromium is remembered: a reused pid then errs toward+ // waiting for browser calls, never toward running beside them.+ m.focus.mu.Lock()+ if m.focus.chromium == nil || len(m.focus.chromium) > 256 {+ m.focus.chromium = map[int]bool{}+ }+ m.focus.chromium[pid] = true+ m.focus.mu.Unlock()+ }+ return chromium+}++// processCommand returns the executable a macOS process runs; a test seam.+var processCommand = func(ctx context.Context, pid int) (string, error) {+ output, err := exec.CommandContext(ctx, "/bin/ps", "-o", "comm=", "-p", strconv.Itoa(pid)).Output()+ return string(output), err+}++func (g *focusGate) release(exclusive bool) {+ g.mu.Lock()+ defer g.mu.Unlock()+ if exclusive {+ g.writer = false+ } else {+ g.readers--+ }+ g.wake()+}++// wake lets every waiter check the gate again. The caller holds g.mu.+func (g *focusGate) wake() {+ if g.changed != nil {+ close(g.changed)+ g.changed = nil+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/journal.go b/apps/computer/local-daemon/internal/linger/localtools/journal.goindex 41d5aba1..82387778 100644--- a/apps/computer/local-daemon/internal/linger/localtools/journal.go+++ b/apps/computer/local-daemon/internal/linger/localtools/journal.go@@ -18,6 +18,11 @@ type actionIdentity struct {AgentID string `json:"agent_id"`OperationID string `json:"operation_id"`Session string `json:"session"`+ // Background marks a desktop input that needed neither the front window+ // nor the clipboard; see focusGate. Any other unknown desktop input,+ // including a record without the field, also blocks browser calls until+ // it settles.+ Background bool `json:"background,omitempty"`}type actionJournal struct {@@ -73,7 +78,7 @@ func (j *actionJournal) begin(ctx context.Context, identity actionIdentity) (*ac}if j.active != nil {<-j.slot- return nil, errors.New("COMPUTER_ACTION_UNKNOWN: an earlier action has no verified cleanup receipt; input remains blocked")+ return nil, errors.New("COMPUTER_ACTION_UNKNOWN: an earlier action has no verified cleanup receipt; this desktop, Agent browser or everyday Chrome seat stays blocked until it settles")}identity.Nonce = rand.Text()if err := j.persist(&identity); err != nil {@@ -84,16 +89,24 @@ func (j *actionJournal) begin(ctx context.Context, identity actionIdentity) (*acreturn &actionReceipt{journal: j, nonce: identity.Nonce}, nil}+// persist records active, or removes the record once nothing is pending, so+// the record of an Agent's browser that is never used again leaves no file.func (j *actionJournal) persist(active *actionIdentity) error {- data, err := json.Marshal(struct {- Version int `json:"version"`- Active *actionIdentity `json:"active"`- }{1, active})- if err != nil {- return err- }- if err := privatefs.WriteFile(j.path, data, false); err != nil {- return err+ if active == nil {+ if err := os.Remove(j.path); err != nil && !errors.Is(err, os.ErrNotExist) {+ return err+ }+ } else {+ data, err := json.Marshal(struct {+ Version int `json:"version"`+ Active *actionIdentity `json:"active"`+ }{1, active})+ if err != nil {+ return err+ }+ if err := privatefs.WriteFile(j.path, data, false); err != nil {+ return err+ }}// Windows cannot open a directory for flushing; NTFS journals the rename.if runtime.GOOS == "windows" {@@ -133,3 +146,11 @@ func (j *actionJournal) blocked() bool {defer j.mu.Unlock()return j.active != nil}++// blocksFocus reports an unknown desktop input that a browser call bringing+// Chrome forward or using the clipboard could still meet.+func (j *actionJournal) blocksFocus() bool {+ j.mu.Lock()+ defer j.mu.Unlock()+ return j.active != nil && !j.active.Background+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/lanes_linux_test.go b/apps/computer/local-daemon/internal/linger/localtools/lanes_linux_test.gonew file mode 100644index 00000000..6992e480--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/lanes_linux_test.go@@ -0,0 +1,76 @@+package localtools++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "sync"+ "testing"+ "time"+)++// X11 input waits for browser calls in flight, and an input the journal+// refuses frees the desktop lane and the focus gate it took.+func TestLinuxInputTakesTurnsWithBrowserCallsAndFreesItsHoldsOnRefusal(t *testing.T) {+ m := laneManager(t, t.TempDir())+ op := agentBrowserOp(t, m, "a")+ _, releaseBrowser, err := m.holdBrowserFocus(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ waiting, cancel := context.WithTimeout(t.Context(), 150*time.Millisecond)+ defer cancel()+ if _, err := op.beginDesktop(waiting, true); !errors.Is(err, errNotSent) {+ t.Fatalf("input did not wait for the browser call in flight: %v", err)+ }+ releaseBrowser()+ leaveUnknown(t, m.journal)+ if _, err := op.beginDesktop(t.Context(), true); err == nil {+ t.Fatal("input began beside a desktop input of unknown outcome")+ }+ free, cancelFree := context.WithTimeout(t.Context(), time.Second)+ defer cancelFree()+ _, releaseLane, err := m.holdLane(free, desktopLane)+ if err != nil {+ t.Fatalf("refused input kept the desktop lane: %v", err)+ }+ releaseLane()+ _, releaseFocus, err := m.holdFocus(free, true)+ if err != nil {+ t.Fatalf("refused input kept the focus gate: %v", err)+ }+ releaseFocus()+}++// One Agent's Chrome that is slow to start does not hold up another Agent's.+func TestTwoAgentsStartTheirChromeTogether(t *testing.T) {+ bin, started := t.TempDir(), t.TempDir()+ chrome := filepath.Join(bin, "chromium")+ script := "#!/bin/sh\n: > \"" + started + "/$$\"\nexec /bin/sleep 60\n"+ if err := os.WriteFile(chrome, []byte(script), 0o700); err != nil {+ t.Fatal(err)+ }+ m := laneManager(t, t.TempDir())+ m.env = []string{"PATH=" + bin, "DISPLAY=:0", "HOME=" + t.TempDir()}+ m.options.StateDirectory = t.TempDir()+ if chromeExecutable(m.env) != chrome {+ t.Skip("a system Chrome comes before the fixture")+ }+ ctx, cancel := context.WithCancel(t.Context())+ var wg sync.WaitGroup+ defer func() { cancel(); wg.Wait() }()+ for _, agent := range []string{"a", "b"} {+ wg.Go(func() { _, _ = m.nativeBrowserFor(ctx, agent) })+ }+ deadline := time.Now().Add(5 * time.Second)+ for {+ if entries, _ := os.ReadDir(started); len(entries) == 2 {+ return+ }+ if time.Now().After(deadline) {+ t.Fatal("the second Agent's Chrome waited for the first one to start")+ }+ time.Sleep(20 * time.Millisecond)+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/lanes_test.go b/apps/computer/local-daemon/internal/linger/localtools/lanes_test.gonew file mode 100644index 00000000..849c6a6b--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/lanes_test.go@@ -0,0 +1,687 @@+package localtools++import (+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider"+)++// laneJournal returns the action journal of a browser lane or seat.+func laneJournal(t *testing.T, m *Manager, lane string) *actionJournal {+ t.Helper()+ journal, err := m.namedJournal(lane)+ if err != nil {+ t.Fatal(err)+ }+ return journal+}++// laneBlocked reports whether a lane's journal holds an unknown action.+func laneBlocked(t *testing.T, m *Manager, lane string) bool {+ t.Helper()+ return laneJournal(t, m, lane).blocked()+}++func laneManager(t *testing.T, directory string) *Manager {+ t.Helper()+ journal, err := openJournal(filepath.Join(directory, "action.json"))+ if err != nil {+ t.Fatal(err)+ }+ m := &Manager{journal: journal, operations: map[*operation]bool{}, browsers: map[string]*nativeBrowser{}, chromeProfiles: map[string]chan struct{}{}}+ if err := m.openBrowserJournals(); err != nil {+ t.Fatal(err)+ }+ return m+}++// leaveUnknown records an action of unknown outcome in a journal.+func leaveUnknown(t *testing.T, journal *actionJournal) {+ t.Helper()+ receipt, err := journal.begin(t.Context(), actionIdentity{AgentID: "a", OperationID: "earlier", Session: "s"})+ if err != nil {+ t.Fatal(err)+ }+ if err := receipt.finish(false); err != nil {+ t.Fatal(err)+ }+}++// agentBrowserOp is a task of agent whose running Agent Chrome answers each+// browser call after 250 ms, through the fixture's delayed click.+func agentBrowserOp(t *testing.T, m *Manager, agent string) *operation {+ t.Helper()+ ctx, cancel := context.WithCancel(t.Context())+ t.Cleanup(cancel)+ op := &operation{manager: m, spec: provider.OperationSpec{AgentID: agent, WorkingDirectory: t.TempDir()}, identity: mcpproxy.OperationIdentity{OperationID: agent + "-" + t.Name()}, directory: t.TempDir(), ctx: ctx, cancel: cancel, label: "linger-" + agent}+ op.nativeBrowser = &nativeBrowser{done: make(chan struct{})}+ var err error+ if op.nativeProxy, err = openNativeCDPProxy("http://127.0.0.1:1"); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = op.nativeProxy.close() })+ op.browser = fixtureClient(t, "delay", "")+ return op+}++type span struct{ start, end time.Time }++func (s span) overlaps(other span) bool {+ return s.start.Before(other.end) && other.start.Before(s.end)+}++// timedCalls runs each call at once and returns when each ran.+func timedCalls(t *testing.T, calls ...func() error) []span {+ t.Helper()+ spans := make([]span, len(calls))+ var wg sync.WaitGroup+ for i, call := range calls {+ wg.Go(func() {+ spans[i].start = time.Now()+ if err := call(); err != nil {+ t.Errorf("call %d: %v", i, err)+ }+ spans[i].end = time.Now()+ })+ }+ wg.Wait()+ return spans+}++func browserClick(op *operation) func() error {+ return func() error {+ _, err := op.nativeBrowserCall(op.ctx, "click", json.RawMessage(`{}`))+ return err+ }+}++// Each fixture call takes 250 ms.+func TestBrowserCallsOfTwoAgentsRunTogetherAndOneAgentsTasksTakeTurns(t *testing.T) {+ m := laneManager(t, t.TempDir())+ a, b, again := agentBrowserOp(t, m, "a"), agentBrowserOp(t, m, "b"), agentBrowserOp(t, m, "a")+ started := time.Now()+ timedCalls(t, browserClick(a), browserClick(b))+ if elapsed := time.Since(started); elapsed >= 450*time.Millisecond {+ t.Fatalf("browser calls of two Agents queued behind each other: %v", elapsed)+ }+ started = time.Now()+ timedCalls(t, browserClick(a), browserClick(again))+ if elapsed := time.Since(started); elapsed < 500*time.Millisecond {+ t.Fatalf("two tasks of one Agent drove its browser at once: %v", elapsed)+ }+}++// A desktop input that needs the front window waits for browser calls in+// flight and holds back new ones; the call sends nothing until then.+func TestFocusedDesktopInputAndBrowserCallsTakeTurns(t *testing.T) {+ m := laneManager(t, t.TempDir())+ a, b := agentBrowserOp(t, m, "a"), agentBrowserOp(t, m, "b")+ exclusive := func() error {+ // Start once the browser calls are in flight.+ time.Sleep(50 * time.Millisecond)+ ctx, release, err := m.holdFocus(t.Context(), true)+ if err != nil {+ return err+ }+ if !holdsFocus(ctx) {+ return errors.New("exclusive hold not marked")+ }+ time.Sleep(250 * time.Millisecond)+ release()+ return nil+ }+ spans := timedCalls(t, browserClick(a), exclusive, browserClick(b))+ if !spans[0].overlaps(spans[2]) {+ t.Fatalf("browser calls of two Agents queued behind each other: %v", spans)+ }+ held := span{spans[1].end.Add(-250 * time.Millisecond), spans[1].end}+ if held.start.Before(spans[0].end) || held.start.Before(spans[2].end) {+ t.Fatalf("a focused desktop input ran beside a browser call: %v", spans)+ }+ // A browser call that arrives while that input waits runs after it.+ ctx, release, err := m.holdFocus(t.Context(), true)+ if err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() { done <- browserClick(a)() }()+ select {+ case err := <-done:+ t.Fatalf("a browser call ran during focused desktop input: %v", err)+ case <-time.After(100 * time.Millisecond):+ }+ if _, _, err := m.holdFocus(ctx, true); err != nil {+ t.Fatalf("a nested input did not reuse the hold: %v", err)+ }+ release()+ if err := <-done; err != nil {+ t.Fatal(err)+ }+}++func TestCancelledFocusWaitIsNotSentAndFreesWaiters(t *testing.T) {+ m := laneManager(t, t.TempDir())+ _, release, err := m.holdFocus(t.Context(), false)+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)+ defer cancel()+ if _, _, err := m.holdFocus(ctx, true); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_BUSY") {+ t.Fatalf("cancelled exclusive wait: %v", err)+ }+ // The abandoned writer no longer holds back browser calls.+ _, again, err := m.holdFocus(t.Context(), false)+ if err != nil {+ t.Fatal(err)+ }+ again()+ release()+}++// An unknown browser action blocks its Agent's browser and desktop input that+// needs the front window, also after a restart, and nothing else.+func TestUnknownBrowserActionBlocksItsAgentAndFocusedInput(t *testing.T) {+ directory := t.TempDir()+ leaveUnknown(t, laneJournal(t, laneManager(t, directory), browserLane("a")))+ m := laneManager(t, directory)+ if _, _, err := m.holdFocusedInput(t.Context()); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_ACTION_UNKNOWN") {+ t.Fatalf("focused desktop input ran beside an unknown browser action: %v", err)+ }+ if _, release, err := m.holdFocus(t.Context(), true); err != nil {+ t.Fatalf("the refused input kept the gate: %v", err)+ } else {+ release()+ }+ a, b := agentBrowserOp(t, m, "a"), agentBrowserOp(t, m, "b")+ if err := browserClick(a)(); err == nil || !strings.Contains(err.Error(), "COMPUTER_ACTION_UNKNOWN") {+ t.Fatalf("the Agent's unknown action admitted its next browser call: %v", err)+ }+ if err := browserClick(b)(); err != nil {+ t.Fatalf("another Agent's browser waited for it: %v", err)+ }+ desktop, err := m.journal.begin(t.Context(), actionIdentity{AgentID: "c", OperationID: "desktop", Session: "s", Background: true})+ if err != nil {+ t.Fatalf("background desktop input waited for a browser action: %v", err)+ }+ _ = desktop.finish(true)+}++// A task that holds one unknown browser action sends no other browser call+// until it ends, even to a browser whose journal is another one: an unknown+// action in the owner's Chrome stops its later Agent Chrome calls.+func TestTaskWithUnknownBrowserActionSendsNoOther(t *testing.T) {+ m := laneManager(t, t.TempDir())+ op := agentBrowserOp(t, m, "a")+ journal, err := m.namedJournal(chromeProfileJournal("Default"))+ if err != nil {+ t.Fatal(err)+ }+ receipt, err := journal.begin(t.Context(), actionIdentity{AgentID: "a", OperationID: "earlier", Session: "s"})+ if err != nil {+ t.Fatal(err)+ }+ op.markBrowserUnknown(receipt, true)+ if err := browserClick(op)(); !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_ACTION_UNKNOWN") {+ t.Fatalf("a second unknown action could replace the first: %v", err)+ }+ _ = receipt.finish(true)+}++func TestUnknownDesktopInputBlocksBrowsersOnlyWhenItNeededFocus(t *testing.T) {+ for _, tc := range []struct {+ name string+ record string+ blocked bool+ }{+ {"background", `{"version":1,"active":{"nonce":"n","agent_id":"x","operation_id":"o","session":"s","background":true}}`, false},+ {"focused", `{"version":1,"active":{"nonce":"n","agent_id":"x","operation_id":"o","session":"s"}}`, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ directory := t.TempDir()+ // A record without the background field may be a browser+ // action, so it blocks browsers too.+ if err := os.WriteFile(filepath.Join(directory, "action.json"), []byte(tc.record), 0o600); err != nil {+ t.Fatal(err)+ }+ m := laneManager(t, directory)+ err := browserClick(agentBrowserOp(t, m, "a"))()+ if tc.blocked != (err != nil) || tc.blocked && (!errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_ACTION_UNKNOWN")) {+ t.Fatalf("browser call with a %s unknown desktop input: %v", tc.name, err)+ }+ if !m.journal.blocked() {+ t.Fatal("the unknown desktop input was dropped")+ }+ })+ }+}++func TestLaneRecordsSurviveRestartPerLane(t *testing.T) {+ directory := t.TempDir()+ m := laneManager(t, directory)+ for _, lane := range []string{browserLane("a"), chromeProfileJournal("Default")} {+ journal, err := m.namedJournal(lane)+ if err != nil {+ t.Fatal(err)+ }+ receipt, err := journal.begin(t.Context(), actionIdentity{AgentID: "a", OperationID: "op", Session: "s"})+ if err != nil {+ t.Fatal(err)+ }+ if err := receipt.finish(false); err != nil {+ t.Fatal(err)+ }+ }+ restarted := laneManager(t, directory)+ if !laneBlocked(t, restarted, browserLane("a")) || !laneBlocked(t, restarted, chromeProfileJournal("Default")) {+ t.Fatal("a restart cleared an unknown browser action")+ }+ if laneBlocked(t, restarted, browserLane("b")) || restarted.journal.blocked() {+ t.Fatal("an unknown browser action blocked another lane after a restart")+ }+ // A settled record leaves no file behind.+ journal, _ := restarted.namedJournal(browserLane("b"))+ receipt, err := journal.begin(t.Context(), actionIdentity{AgentID: "b", OperationID: "op", Session: "s"})+ if err != nil {+ t.Fatal(err)+ }+ if err := receipt.finish(true); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(journal.path); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("settled record kept its file: %v", err)+ }+}++// A browser call of one Agent and Cua input, which holds only the desktop+// lane and the focus gate, never wait on each other's locks in a cycle.+func TestLanesAndFocusUnderLoad(t *testing.T) {+ m := laneManager(t, t.TempDir())+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)+ defer cancel()+ var wg sync.WaitGroup+ for worker := range 16 {+ wg.Go(func() {+ for range 200 {+ var held context.Context+ var releases []func()+ var err error+ if worker%4 == 0 {+ var release func()+ if held, release, err = m.holdLane(ctx, desktopLane); err == nil {+ releases = append(releases, release)+ held, release, err = m.holdFocus(held, true)+ releases = append(releases, release)+ }+ } else {+ var release func()+ if held, release, err = m.holdLane(ctx, browserLane(string(rune('a'+worker%3)))); err == nil {+ releases = append(releases, release)+ held, release, err = m.holdFocus(held, false)+ releases = append(releases, release)+ }+ }+ _ = held+ for i := len(releases) - 1; i >= 0; i-- {+ if releases[i] != nil {+ releases[i]()+ }+ }+ if err != nil {+ t.Errorf("worker %d: %v", worker, err)+ return+ }+ }+ })+ }+ wg.Wait()+}++func TestCuaInputNeedsFocusUnlessBackgroundToAnotherApp(t *testing.T) {+ previous := processCommand+ t.Cleanup(func() { processCommand = previous })+ processCommand = func(_ context.Context, pid int) (string, error) {+ if pid == 7 {+ return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\n", nil+ }+ return "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit\n", nil+ }+ m := laneManager(t, t.TempDir())+ m.agentChromePID = 9+ c := &cuaSession{op: &operation{manager: m}}+ c.op.reads.observe(json.RawMessage(`{"content":[{"type":"text","text":"window_id=3 pid=42\n- [5] AXButton Save"}],"structuredContent":{"snapshot_id":"s1"}}`))+ for _, tc := range []struct {+ name, args string+ darwin bool+ }{+ {"get_window_state", `{"pid":42}`, false},+ {"recognize_text", `{"pid":42}`, false},+ {"recognize_text", `{"pid":42,"pages":3}`, true},+ {"click", `{"pid":42,"window_id":3,"element_token":"s1:5"}`, false},+ {"double_click", `{"element_token":"s1:5"}`, true},+ {"scroll", `{"pid":9}`, false},+ {"click", `{"pid":7}`, true},+ {"click", `{"pid":42,"delivery_mode":"foreground"}`, true},+ {"click", `{"pid":42,"modifier":["cmd"]}`, true},+ {"click", `{"element_token":"unknown"}`, true},+ {"type_text", `{"pid":42,"text":"x"}`, true},+ {"run_actions", `{"actions":[]}`, true},+ {"run_script", `{"script":"return 1"}`, true},+ {"launch_app", `{}`, true},+ {"clipboard_write", `{"text":"x"}`, true},+ } {+ want := !cuaReadTools[tc.name]+ if runtime.GOOS == "darwin" {+ want = tc.darwin+ }+ if got := c.needsFocus(t.Context(), tc.name, json.RawMessage(tc.args)); got != want {+ t.Errorf("%s %s: needsFocus=%v, want %v", tc.name, tc.args, got, want)+ }+ }+}++// chromeHome is a user's home whose Chrome profile "Default" has the+// Playwright Extension installed in each version given.+func chromeHome(t *testing.T, versions ...string) []string {+ t.Helper()+ home := t.TempDir()+ data := filepath.Join(home, "Library", "Application Support", "Google", "Chrome")+ env := []string{"HOME=" + home}+ if runtime.GOOS == "windows" {+ data = filepath.Join(home, "Google", "Chrome", "User Data")+ env = []string{"LOCALAPPDATA=" + home}+ }+ for _, version := range versions {+ if err := os.MkdirAll(filepath.Join(data, "Default", "Extensions", playwrightExtensionID, version), 0o700); err != nil {+ t.Fatal(err)+ }+ }+ return env+}++func TestExtensionThatKeepsManyClientsGivesEachAgentItsOwnSeat(t *testing.T) {+ if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {+ t.Skip("the everyday Chrome is connected on macOS and Windows")+ }+ for _, test := range []struct {+ versions []string+ many bool+ }{+ {[]string{"0.5.0_0"}, true},+ {[]string{"0.10.1_0"}, true},+ {[]string{"1.0_0"}, true},+ {[]string{"0.4.9_0"}, false},+ {[]string{"0.5.0_0", "0.4.2_0"}, false},+ {[]string{"0.5.x_0"}, false},+ {nil, false},+ } {+ env := chromeHome(t, test.versions...)+ if got := extensionTakesManyClients(env, "Default"); got != test.many {+ t.Errorf("versions %v: many clients = %v, want %v", test.versions, got, test.many)+ }+ }+ previous := profileWait+ profileWait = 300 * time.Millisecond+ defer func() { profileWait = previous }()+ hold := func(m *Manager, agent string) (*operation, string, error) {+ op := agentBrowserOp(t, m, agent)+ seat, err := op.holdUserChromeProfile(t.Context(), "Default")+ return op, seat, err+ }+ m := laneManager(t, t.TempDir())+ m.env = chromeHome(t, "0.5.0_0")+ a, seatA, err := hold(m, "a")+ if err != nil {+ t.Fatal(err)+ }+ if _, seatB, err := hold(m, "b"); err != nil || seatB == seatA {+ t.Fatalf("another Agent waited for the profile: seat %q err=%v", seatB, err)+ }+ if _, _, err := hold(m, "a"); !errors.Is(err, errBrowserBusy) {+ t.Fatalf("a second task of the Agent shared its tabs: %v", err)+ }+ a.releaseChromeProfile()+ if _, _, err := hold(m, "a"); err != nil {+ t.Fatalf("the freed seat stayed busy: %v", err)+ }+ // An extension that keeps one client admits one task to the profile.+ m = laneManager(t, t.TempDir())+ m.env = chromeHome(t, "0.4.9_0")+ if _, seat, err := hold(m, "a"); err != nil || seat != "Default" {+ t.Fatalf("seat %q err=%v, want the whole profile", seat, err)+ }+ if _, _, err := hold(m, "b"); !errors.Is(err, errBrowserBusy) {+ t.Fatalf("two Agents shared a profile whose extension keeps one client: %v", err)+ }+}++// extensionVersions installs the Playwright Extension versions in the+// "Default" profile of the everyday Chrome that chromeEnv names.+func extensionVersions(t *testing.T, chromeEnv string, versions ...string) {+ t.Helper()+ _, root, _ := strings.Cut(chromeEnv, "=")+ data := filepath.Join(root, "Library", "Application Support", "Google", "Chrome")+ if runtime.GOOS == "windows" {+ data = filepath.Join(root, "Google", "Chrome", "User Data")+ }+ for _, version := range versions {+ if err := os.MkdirAll(filepath.Join(data, "Default", "Extensions", playwrightExtensionID, version), 0o700); err != nil {+ t.Fatal(err)+ }+ }+}++// With an extension that keeps many clients, two Agents keep their own+// connections to one Chrome profile, and an unknown action blocks only the+// seat it was sent to.+func TestEverydayChromeSeatsKeepAgentsApart(t *testing.T) {+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ marker := filepath.Join(t.TempDir(), "launches")+ m := laneManager(t, t.TempDir())+ m.options = Options{StateDirectory: t.TempDir(), NodePath: executable, PlaywrightEntry: fixtureEntry(t)}+ chromeEnv := fakeEverydayChrome(t)+ extensionVersions(t, chromeEnv, "0.5.0_0")+ m.env = []string{chromeEnv, "LINGER_LOCAL_TOOL_FIXTURE=count-launch", "LINGER_LOCAL_TOOL_MARKER=" + marker}+ workspace := t.TempDir()+ chrome := &browserConnection{Profile: "Default", Token: "token-a", State: browserConnected}+ task := func(agent string) error {+ t.Helper()+ _, cancel := context.WithCancel(t.Context())+ op := &operation{manager: m, label: "linger-test", directory: t.TempDir(), cancel: cancel, userChrome: chrome,+ spec: provider.OperationSpec{TenantID: "t", OwnerActorID: "u", AgentID: agent, WorkingDirectory: workspace}}+ _, callErr := op.nativeBrowserCall(t.Context(), "browser_snapshot", json.RawMessage(`{}`))+ if err := op.close(); err != nil {+ t.Fatal(err)+ }+ return callErr+ }+ for _, agent := range []string{"a", "b"} {+ if err := task(agent); err != nil {+ t.Fatal(err)+ }+ }+ m.mu.Lock()+ idle := len(m.userChromeSessions)+ m.mu.Unlock()+ if idle != 2 {+ t.Fatalf("%d idle connections, want each Agent's kept", idle)+ }+ leaveUnknown(t, laneJournal(t, m, chromeProfileJournal("Default\x00a")))+ if err := task("a"); err == nil || !strings.Contains(err.Error(), "COMPUTER_ACTION_UNKNOWN") {+ t.Fatalf("the seat with an unknown action took a call: %v", err)+ }+ if err := task("b"); err != nil {+ t.Fatalf("another Agent's seat was blocked: %v", err)+ }+ if err := m.closeUserChrome(); err != nil {+ t.Fatal(err)+ }+}++// Verifying a token opens one more client, which an extension that keeps+// many clients accepts beside a running task, even one that took the whole+// profile before the extension updated.+func TestBrowserConfigureBesideATaskWhenTheExtensionKeepsManyClients(t *testing.T) {+ m := newConnectionManager(t)+ chromeEnv := fakeEverydayChrome(t)+ extensionVersions(t, chromeEnv, "0.5.0_0")+ m.env = []string{chromeEnv}+ release, err := m.acquireChromeProfile(t.Context(), "Default")+ if err != nil {+ t.Fatal(err)+ }+ defer release()+ _, err = m.BrowserConnection(t.Context(), "tenant", "owner", "configure", "Default", strings.Repeat("A", 43))+ var typed *BrowserCommandError+ if errors.As(err, &typed) && typed.Code == "BROWSER_BUSY" {+ t.Fatalf("configure waited for a task on another seat: %v", err)+ }+}++// A Cua input that needs the front window waits for browser calls in flight;+// a background click to another app runs beside them.+func TestCuaCallTakesTheFocusGateItNeeds(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("background input exists on macOS")+ }+ previous := processCommand+ t.Cleanup(func() { processCommand = previous })+ processCommand = func(context.Context, int) (string, error) {+ return "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit", nil+ }+ c := cuaFixtureSession(t, "window-view", filepath.Join(t.TempDir(), "calls.jsonl"))+ m := c.op.manager+ _, releaseBrowser, err := m.holdBrowserFocus(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ done := make(chan struct{})+ go func() {+ defer close(done)+ _, _ = c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":7,"x":5,"y":5}`))+ }()+ select {+ case <-done:+ // A blocked click never returns; the long limit only absorbs a slow,+ // loaded test machine, where one fixture click takes over a second.+ case <-time.After(30 * time.Second):+ t.Fatal("a background click waited for a browser call")+ }+ done = make(chan struct{})+ go func() {+ defer close(done)+ _, _ = c.call(t.Context(), "press_key", json.RawMessage(`{"pid":42,"window_id":7,"key":"a"}`))+ }()+ select {+ case <-done:+ t.Fatal("a key press ran beside a browser call")+ case <-time.After(300 * time.Millisecond):+ }+ releaseBrowser()+ select {+ case <-done:+ case <-time.After(30 * time.Second):+ t.Fatal("the key press never ran after the browser call")+ }+ if err := c.drain(); err != nil {+ t.Fatal(err)+ }+}++// The screenshot that evidence takes drives the page as a browser call does,+// so it waits its turn in the Agent's browser lane and at the focus gate.+func TestBrowserScreenshotTakesTurnsLikeABrowserCall(t *testing.T) {+ m := laneManager(t, t.TempDir())+ op := agentBrowserOp(t, m, "a")+ holds := []struct {+ name string+ hold func(context.Context) (context.Context, func(), error)+ }{+ {"the task's browser calls", func(ctx context.Context) (context.Context, func(), error) {+ release, err := op.holdBrowserCalls(ctx)+ return ctx, release, err+ }},+ {"the Agent's browser lane", func(ctx context.Context) (context.Context, func(), error) {+ return m.holdLane(ctx, browserLane("a"))+ }},+ {"focused desktop input", func(ctx context.Context) (context.Context, func(), error) { return m.holdFocus(ctx, true) }},+ }+ for _, held := range holds {+ _, release, err := held.hold(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ done := make(chan struct{})+ go func() { op.browserScreenshot(op.ctx); close(done) }()+ select {+ case <-done:+ t.Fatalf("screenshot ran while %s held it back", held.name)+ case <-time.After(100 * time.Millisecond):+ }+ release()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatalf("screenshot did not run once %s let go", held.name)+ }+ }+}++// A Cua input whose outcome is unknown records whether it needed the front+// window, which decides whether it blocks browser calls.+func TestUnknownCuaInputRecordsWhetherItNeededFocus(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("background input exists on macOS")+ }+ previous := processCommand+ t.Cleanup(func() { processCommand = previous })+ processCommand = func(context.Context, int) (string, error) {+ return "/System/Applications/TextEdit.app/Contents/MacOS/TextEdit", nil+ }+ for _, input := range []struct {+ name, args string+ blocksFocus bool+ }{+ {"background click", `{"pid":42,"window_id":7,"x":5,"y":5}`, false},+ {"foreground click", `{"pid":42,"window_id":9,"x":5,"y":5,"delivery_mode":"foreground"}`, true},+ } {+ marker := filepath.Join(t.TempDir(), "submitted")+ c := cuaFixtureSession(t, "delay", marker)+ ctx, cancel := context.WithCancel(t.Context())+ done := make(chan error, 1)+ go func() { _, err := c.call(ctx, "click", json.RawMessage(input.args)); done <- err }()+ for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(time.Millisecond) {+ if _, err := os.Stat(marker); err == nil {+ break+ }+ if time.Now().After(deadline) {+ cancel()+ t.Fatalf("%s was not sent: %v", input.name, <-done)+ }+ }+ cancel()+ if err := <-done; !errors.Is(err, errOutcomeUnknown) {+ t.Fatalf("%s: %v, want an unknown outcome", input.name, err)+ }+ journal := c.op.manager.journal+ if !journal.blocked() || journal.blocksFocus() != input.blocksFocus {+ t.Fatalf("%s: blocked %v, blocks browser calls %v", input.name, journal.blocked(), journal.blocksFocus())+ }+ if err := c.drain(); err != nil {+ t.Fatal(err)+ }+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/linux_native.go b/apps/computer/local-daemon/internal/linger/localtools/linux_native.goindex e293b1dd..0d3af44c 100644--- a/apps/computer/local-daemon/internal/linger/localtools/linux_native.go+++ b/apps/computer/local-daemon/internal/linger/localtools/linux_native.go@@ -127,12 +127,21 @@ func (op *operation) beginDesktop(ctx context.Context, input bool) (*localLinuxLif !op.manager.localLinux() {return nil, errors.New("native Linux desktop unavailable")}- ctx, release, err := op.manager.holdInputs(ctx)+ ctx, releaseLane, err := op.manager.holdLane(ctx, desktopLane)if err != nil {return nil, err}+ release := releaseLanevar receipt *actionReceiptif input {+ // X11 input goes to the active window, which a browser call could+ // change; see focusGate.+ var releaseFocus func()+ if ctx, releaseFocus, err = op.manager.holdFocusedInput(ctx); err != nil {+ releaseLane()+ return nil, err+ }+ release = func() { releaseFocus(); releaseLane() }receipt, err = op.manager.journal.begin(ctx, actionIdentity{AgentID: op.spec.AgentID, OperationID: op.identity.OperationID, Session: op.label + "-linux"})if err != nil {release()diff --git a/apps/computer/local-daemon/internal/linger/localtools/live_session.go b/apps/computer/local-daemon/internal/linger/localtools/live_session.goindex 3e17eddd..472eaa35 100644--- a/apps/computer/local-daemon/internal/linger/localtools/live_session.go+++ b/apps/computer/local-daemon/internal/linger/localtools/live_session.go@@ -130,17 +130,17 @@ func (m *Manager) liveSlots() chan struct{} {return m.liveSlot}-// releaseIdleLiveChrome closes the Live browser sessions that hold profile+// releaseIdleLiveChrome closes the Live browser sessions that hold seat// between calls, so a task waiting for the owner's Chrome gets it. A Live// call in progress keeps it: it holds the Live slot, and so does the call// that asks.-func (m *Manager) releaseIdleLiveChrome(profile string) {+func (m *Manager) releaseIdleLiveChrome(seat string) {if !m.tryLockLive() {return}defer m.unlockLive()for key, session := range m.liveSessions {- if !session.op.holdsChromeProfile(profile) {+ if !session.op.holdsChromeSeat(seat) {continue}// An unconfirmed cleanup keeps the profile until retryCleanup@@ -150,11 +150,8 @@ func (m *Manager) releaseIdleLiveChrome(profile string) {}}-func (op *operation) holdsChromeProfile(profile string) bool {- op.connectMu.Lock()- chrome := op.userChrome- op.connectMu.Unlock()+func (op *operation) holdsChromeSeat(seat string) bool {op.profileMu.Lock()defer op.profileMu.Unlock()- return op.releaseProfile != nil && chrome != nil && chrome.Profile == profile+ return op.releaseProfile != nil && op.chromeSeat == seat}diff --git a/apps/computer/local-daemon/internal/linger/localtools/manager.go b/apps/computer/local-daemon/internal/linger/localtools/manager.goindex 1009a51e..130dc2cc 100644--- a/apps/computer/local-daemon/internal/linger/localtools/manager.go+++ b/apps/computer/local-daemon/internal/linger/localtools/manager.go@@ -50,10 +50,17 @@ type Manager struct {// cuaGrant is the running `cua-driver permissions grant`, at most one.cuaGrantMu sync.MutexcuaGrant *exec.Cmd- // inputs admits one desktop or browser action at a time across- // Operations; see holdInputs. It is made on first use.- inputs chan struct{}- inputsOnce sync.Once+ // lanes admit one call at a time to the desktop and to each Agent's+ // browser; see holdLane. Guarded by laneMu.+ laneMu sync.Mutex+ lanes map[string]chan struct{}+ // browserJournals are the action journals of browser lanes and of seats+ // in the everyday Chrome by path, including those of earlier Daemons.+ // Guarded by laneMu.+ browserJournals map[string]*actionJournal+ // focus keeps browser calls apart from desktop input that depends on+ // the front window or the clipboard; see holdFocus.+ focus focusGateoperations map[*operation]boolbrowsers map[string]*nativeBrowser// browserMu serializes the private browser connection records.@@ -61,8 +68,9 @@ type Manager struct {// noEverydayChrome marks a Linux desktop: it has no everyday Chrome// profile lookup, so its Agents keep their own browser.noEverydayChrome bool- // chromeProfiles admits one Operation at a time to each everyday Chrome- // profile, so tabs, refs and downloads of two tasks never mix.+ // chromeProfiles admits one Operation at a time to each seat in an+ // everyday Chrome profile, so tabs, refs and downloads of two tasks never+ // mix; see userChromeSeat.chromeProfiles map[string]chan struct{}// userChromeSessions keeps idle connections to everyday Chrome for the// next task of the same Agent; see checkoutUserChrome.@@ -109,6 +117,9 @@ func New(options Options) (*Manager, error) {if err != nil {return nil, err}+ if err := m.openBrowserJournals(); err != nil {+ return nil, err+ }}return m, nil}@@ -150,9 +161,15 @@ type operation struct {connectMu sync.MutexuserChromeVerified booluserChromeRejected atomic.Bool- // profileMu guards releaseProfile while a call waits for the profile.+ // browserCalls admits one browser call of this Operation at a time; see+ // holdBrowserCalls.+ browserCalls chan struct{}+ browserCallsOnce sync.Once+ // profileMu guards releaseProfile and chromeSeat while a call waits for+ // the seat.profileMu sync.MutexreleaseProfile func()+ chromeSeat stringbrowserUnknown *actionReceipt// browserUnknownUser marks an unknown action sent to the owner's Chrome.browserUnknownUser bool@@ -480,24 +497,111 @@ func (op *operation) wrap(call func(context.Context, string, json.RawMessage) (j}}-// inputsHeld marks a context whose call already holds Manager.inputs.-type inputsHeld struct{}+// desktopLane is the desktop of the signed-in user, which every Cua and+// native Linux call shares, with the Computer's own browser that Cua drives.+// Each Agent's Playwright browser, the Agent Chrome or the owner's connected+// Chrome, is a lane of its own: those calls go over CDP or the extension.+const desktopLane = "desktop"++// browserLane names the lane of one Agent's Playwright browser. All browser+// calls of an Operation share it, also after the owner connects their Chrome+// mid-task, and every task of the Agent shares that Agent's Chrome.+func browserLane(agentID string) string { return "browser:" + agentID }++// chromeProfileJournal names the action journal of one seat in the owner's+// everyday Chrome. Its lock is the seat's slot; see acquireChromeProfile.+func chromeProfileJournal(seat string) string { return "chrome:" + seat }++// laneHeld marks a context whose call already holds the named lane.+type laneHeld struct{ lane string }++// lane returns the slot that admits one call of a lane at a time.+func (m *Manager) lane(name string) chan struct{} {+ m.laneMu.Lock()+ defer m.laneMu.Unlock()+ if m.lanes == nil {+ m.lanes = map[string]chan struct{}{}+ }+ if m.lanes[name] == nil {+ m.lanes[name] = make(chan struct{}, 1)+ }+ return m.lanes[name]+}++// browserJournalPrefix starts the file name of every browser action record.+const browserJournalPrefix = "action-browser-"++// openBrowserJournals reads the browser action records an earlier Daemon+// left, so an unknown one blocks desktop input that needs the front window+// before its Agent calls the browser again.+func (m *Manager) openBrowserJournals() error {+ paths, err := filepath.Glob(filepath.Join(filepath.Dir(m.journal.path), browserJournalPrefix+"*.json"))+ if err != nil {+ return err+ }+ m.browserJournals = map[string]*actionJournal{}+ for _, path := range paths {+ if m.browserJournals[path], err = openJournal(path); err != nil {+ return err+ }+ }+ return nil+}++// browserActionUnknown reports a browser action whose outcome is unknown,+// in any Agent's browser or everyday Chrome profile.+func (m *Manager) browserActionUnknown() bool {+ m.laneMu.Lock()+ defer m.laneMu.Unlock()+ for _, journal := range m.browserJournals {+ if journal.blocked() {+ return true+ }+ }+ return false+}-// holdInputs takes the Manager's input slot unless ctx already holds it, so-// a run_actions call keeps the screen and the clipboard-// until it ends. A cancelled call stops waiting. Browser calls take it only-// after their Chrome profile, so a call never waits for a profile while it-// holds the slot.-func (m *Manager) holdInputs(ctx context.Context) (context.Context, func(), error) {- if ctx.Value(inputsHeld{}) != nil {+// namedJournal returns the action journal of an Agent's browser lane or of a+// seat in the everyday Chrome; desktop input uses m.journal. It opens on first+// use and reads its file, so a record left before a restart blocks its lane or+// seat again.+func (m *Manager) namedJournal(name string) (*actionJournal, error) {+ m.laneMu.Lock()+ defer m.laneMu.Unlock()+ sum := sha256.Sum256([]byte(name))+ path := filepath.Join(filepath.Dir(m.journal.path), browserJournalPrefix+hex.EncodeToString(sum[:16])+".json")+ if journal := m.browserJournals[path]; journal != nil {+ return journal, nil+ }+ journal, err := openJournal(path)+ if err != nil {+ return nil, err+ }+ if m.browserJournals == nil {+ m.browserJournals = map[string]*actionJournal{}+ }+ m.browserJournals[path] = journal+ return journal, nil+}++// holdLane takes a lane unless ctx already holds it, so a run_actions call+// keeps the screen and the clipboard until it ends. A cancelled call stops+// waiting. No call holds two lanes. Browser calls take their lane only after+// their Chrome profile, so a call never waits for a profile while it holds a+// lane.+func (m *Manager) holdLane(ctx context.Context, name string) (context.Context, func(), error) {+ if ctx.Value(laneHeld{name}) != nil {return ctx, func() {}, nil}- m.inputsOnce.Do(func() { m.inputs = make(chan struct{}, 1) })+ slot := m.lane(name)select {- case m.inputs <- struct{}{}:- return context.WithValue(ctx, inputsHeld{}, true), func() { <-m.inputs }, nil+ case slot <- struct{}{}:+ return context.WithValue(ctx, laneHeld{name}, true), func() { <-slot }, nilcase <-ctx.Done():- return ctx, nil, fmt.Errorf("COMPUTER_BUSY: another task was using the screen until this call ended (%v): %w", ctx.Err(), errNotSent) //nolint:errorlint // the wait's end is detail; the call classifies as not sent only+ if name == desktopLane {+ return ctx, nil, fmt.Errorf("COMPUTER_BUSY: another task was using the screen until this call ended (%v): %w", ctx.Err(), errNotSent) //nolint:errorlint // the wait's end is detail; the call classifies as not sent only+ }+ return ctx, nil, fmt.Errorf("COMPUTER_BUSY: another task of this Agent was using its browser until this call ended (%v): %w", ctx.Err(), errNotSent) //nolint:errorlint // the wait's end is detail; the call classifies as not sent only}}@@ -627,12 +731,12 @@ func (op *operation) close() error {op.browser, op.userChromeSession = nil, nil}}- // No call of this task runs any more, so its everyday Chrome profile- // passes on once its Playwright child has stopped. A failing cleanup- // step unrelated to that Chrome keeps this task for retries but must- // not keep the owner's Chrome from every later task. A child whose- // exit is unconfirmed keeps the profile: a second relay must not- // attach to the same extension.+ // No call of this task runs any more, so its seat in the everyday+ // Chrome passes on once its Playwright child has stopped. A failing+ // cleanup step unrelated to that Chrome keeps this task for retries+ // but must not keep the owner's Chrome from every later task. A child+ // whose exit is unconfirmed keeps the seat: a second relay must not+ // take its place.if op.userChromeSession == nil {op.releaseChromeProfile()}diff --git a/apps/computer/local-daemon/internal/linger/localtools/native_browser.go b/apps/computer/local-daemon/internal/linger/localtools/native_browser.goindex b4af5167..728412be 100644--- a/apps/computer/local-daemon/internal/linger/localtools/native_browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/native_browser.go@@ -28,20 +28,25 @@ type nativeBrowser struct {err error}+// nativeBrowserFor returns the Agent's running Chrome or starts it. Only+// calls in the Agent's browser lane start it, so one Agent never starts two;+// m.mu guards just the table, and a start does not hold up other Agents.func (m *Manager) nativeBrowserFor(ctx context.Context, agentID string) (*nativeBrowser, error) {m.mu.Lock()- defer m.mu.Unlock()if existing := m.browsers[agentID]; existing != nil {select {case <-existing.done:if err := existing.cleanupError(); err != nil {+ m.mu.Unlock()return existing, err}delete(m.browsers, agentID)default:+ m.mu.Unlock()return existing, nil}}+ m.mu.Unlock()// This is a dedicated Agent profile, never the user's default Chrome// profile. Cua observes the same native window Playwright attaches to.executable := chromeExecutable(m.env)@@ -85,7 +90,8 @@ func (m *Manager) nativeBrowserFor(ctx context.Context, agentID string) (*nativereturn m.awaitNativeBrowser(ctx, agentID, browser, portFile)}-// The caller holds m.mu while publishing or retaining the original process.+// awaitNativeBrowser publishes the started browser, or retains a process+// whose stop is unconfirmed, under m.mu.func (m *Manager) awaitNativeBrowser(ctx context.Context, agentID string, browser *nativeBrowser, portFile string) (*nativeBrowser, error) {readyCtx, cancel := context.WithTimeout(ctx, 30*time.Second)defer cancel()@@ -94,7 +100,7 @@ func (m *Manager) awaitNativeBrowser(ctx context.Context, agentID string, browsecase <-browser.done:err := errors.New("BROWSER_UNAVAILABLE: managed Chrome exited; close an older Computer-owned Chrome before retrying")if cleanupErr := browser.cleanupError(); cleanupErr != nil {- m.browsers[agentID] = browser+ m.publishBrowser(agentID, browser)return browser, errors.Join(err, cleanupErr)}return nil, err@@ -112,7 +118,7 @@ func (m *Manager) awaitNativeBrowser(ctx context.Context, agentID string, browseif requestErr == nil {_ = response.Body.Close()if response.StatusCode == http.StatusOK {- m.browsers[agentID] = browser+ m.publishBrowser(agentID, browser)return browser, nil}}@@ -122,7 +128,7 @@ func (m *Manager) awaitNativeBrowser(ctx context.Context, agentID string, browsecase <-readyCtx.Done():err := errors.New("BROWSER_UNAVAILABLE: managed Chrome did not become ready")if cleanupErr := browser.close(); cleanupErr != nil {- m.browsers[agentID] = browser+ m.publishBrowser(agentID, browser)return browser, errors.Join(err, cleanupErr)}return nil, err@@ -131,6 +137,12 @@ func (m *Manager) awaitNativeBrowser(ctx context.Context, agentID string, browse}}+func (m *Manager) publishBrowser(agentID string, browser *nativeBrowser) {+ m.mu.Lock()+ m.browsers[agentID] = browser+ m.mu.Unlock()+}+// snapProfileRoot returns where a Snap browser keeps Agent profiles. Snap// confinement denies hidden folders in the home folder, such as the Computer's// state folder, so Chromium could not lock a profile there and exited.diff --git a/apps/computer/local-daemon/internal/linger/localtools/native_browser_close_unix_test.go b/apps/computer/local-daemon/internal/linger/localtools/native_browser_close_unix_test.goindex 81615b73..480ec5e9 100644--- a/apps/computer/local-daemon/internal/linger/localtools/native_browser_close_unix_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/native_browser_close_unix_test.go@@ -217,7 +217,7 @@ func TestNativeBrowserFailedTreeReceiptKeepsActionBlocked(t *testing.T) {if _, err := op.nativeBrowserCall(ctx, "browser_snapshot", json.RawMessage(`{}`)); !errors.Is(err, mcpproxy.ErrCleanupUnconfirmed) {t.Fatalf("failed whole-tree receipt was accepted: %v", err)}- if op.nativeBrowser != f.browser || m.browsers["fixture"] != f.browser || !journal.blocked() {+ if op.nativeBrowser != f.browser || m.browsers["fixture"] != f.browser || !laneBlocked(t, m, browserLane("fixture")) || journal.blocked() {t.Fatal("unknown owner or action fence was lost")}if f.closeCalls.Load() != 1 {diff --git a/apps/computer/local-daemon/internal/linger/localtools/user_chrome.go b/apps/computer/local-daemon/internal/linger/localtools/user_chrome.goindex ebacefe0..939b2370 100644--- a/apps/computer/local-daemon/internal/linger/localtools/user_chrome.go+++ b/apps/computer/local-daemon/internal/linger/localtools/user_chrome.go@@ -6,6 +6,7 @@ import ("os/exec""path/filepath""runtime"+ "strconv""strings")@@ -93,6 +94,65 @@ func chromeUserDataDirectory(env []string) string {type userChromeInstall struct{ executable, profile string }+// manyClientsExtension is the first Playwright Extension version that keeps+// several Playwright clients connected at once, each in its own tab group.+// An earlier version may drop one client when the next connects.+var manyClientsExtension = [3]int{0, 5, 0}++// extensionTakesManyClients reports whether every installed version of the+// Playwright Extension in profile is at least manyClientsExtension. Chrome may+// keep an old version folder until it restarts, so any older or unreadable+// folder counts against it.+func extensionTakesManyClients(env []string, profile string) bool {+ data := chromeUserDataDirectory(env)+ if data == "" {+ return false+ }+ entries, err := os.ReadDir(filepath.Join(data, profile, "Extensions", playwrightExtensionID))+ if err != nil {+ return false+ }+ found := false+ for _, entry := range entries {+ if !entry.IsDir() {+ continue+ }+ version, _, _ := strings.Cut(entry.Name(), "_")+ if !versionAtLeast(version, manyClientsExtension) {+ return false+ }+ found = true+ }+ return found+}++func versionAtLeast(version string, minimum [3]int) bool {+ parts := strings.Split(version, ".")+ for i, want := range minimum {+ got := 0+ if i < len(parts) {+ var err error+ if got, err = strconv.Atoi(parts[i]); err != nil {+ return false+ }+ }+ if got != want {+ return got > want+ }+ }+ return true+}++// userChromeSeat names what one task holds in the owner's everyday Chrome:+// its Agent's own tabs when the extension keeps several clients, or else the+// whole profile. Tasks of one seat take turns; seats of one profile do not.+func userChromeSeat(env []string, profile, agentID string) string {+ if extensionTakesManyClients(env, profile) {+ return profile + "\x00" + agentID+ }+ return profile+}+// findUserChrome resolves the Chrome profile with the Playwright Extension.// The extension token belongs to one profile; Chrome opens the connect page// in exactly that profile.diff --git a/apps/computer/local-daemon/internal/linger/localtools/user_chrome_session.go b/apps/computer/local-daemon/internal/linger/localtools/user_chrome_session.goindex 77683dfb..d0c2e079 100644--- a/apps/computer/local-daemon/internal/linger/localtools/user_chrome_session.go+++ b/apps/computer/local-daemon/internal/linger/localtools/user_chrome_session.go@@ -22,15 +22,17 @@ var userChromeIdle = 10 * time.Minute// userChromeSession is one Playwright child connected through the extension.// Tasks of the same Agent, owner, Chrome profile, token and workspace take-// turns on it, so the next task continues in the same tab. The profile slot+// turns on it, so the next task continues in the same tab. The seat's slot// already admits one task at a time, so at most one task holds it.type userChromeSession struct {key string- // owner and profile name the extension connection the session holds: one- // Chrome profile keeps one relay, so a session of the same profile under- // another key, or of an owner who disconnects, stops while idle.+ // owner, profile and seat name the extension connection the session+ // holds. A seat keeps one relay, so a session of the same seat under+ // another key, or of an owner who disconnects, stops while idle; when the+ // extension keeps one client the seat is the whole profile.owner stringprofile string+ seat stringclient *mcpClientdirectory stringsocketsDir string@@ -73,8 +75,11 @@ func (m *Manager) checkoutUserChrome(ctx context.Context, op *operation, chrome}m.closeStrayUserChrome(existing)}- m.closeIdleUserChrome(func(s *userChromeSession) bool { return s.profile == chrome.Profile })- session := &userChromeSession{key: key, inUse: true, owner: browserOwner(op.spec.TenantID, op.spec.OwnerActorID), profile: chrome.Profile,+ op.profileMu.Lock()+ seat := op.chromeSeat+ op.profileMu.Unlock()+ m.closeIdleUserChrome(func(s *userChromeSession) bool { return s.seat == seat })+ session := &userChromeSession{key: key, inUse: true, owner: browserOwner(op.spec.TenantID, op.spec.OwnerActorID), profile: chrome.Profile, seat: seat,directory: filepath.Join(m.options.StateDirectory, "computer-tools", "user-chrome", key),output: filepath.Join(op.spec.WorkingDirectory, ".linger", "browser-output", key)}if err := privatefs.EnsureDir(session.directory); err != nil {diff --git a/apps/computer/local-daemon/internal/linger/localtools/user_chrome_test.go b/apps/computer/local-daemon/internal/linger/localtools/user_chrome_test.goindex 7d7f3f0a..8ab4a099 100644--- a/apps/computer/local-daemon/internal/linger/localtools/user_chrome_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/user_chrome_test.go@@ -455,7 +455,7 @@ func liveSessionOnProfile(t *testing.T, m *Manager, key, profile string) *operatt.Fatal(err)}ctx, cancel := context.WithCancel(context.Background())- op := &operation{manager: m, label: "linger-live", ctx: ctx, cancel: cancel, directory: t.TempDir(), userChrome: &browserConnection{Profile: profile}, releaseProfile: release}+ op := &operation{manager: m, label: "linger-live", ctx: ctx, cancel: cancel, directory: t.TempDir(), userChrome: &browserConnection{Profile: profile}, releaseProfile: release, chromeSeat: profile}m.tryLockLive()if m.liveSessions == nil {m.liveSessions = map[string]*liveBrowserSession{}@@ -754,7 +754,11 @@ func TestFailedCleanupPassesTheChromeProfileOn(t *testing.T) {// for every later task.func TestUserChromeUnknownActionSettlesWhenTheTaskStops(t *testing.T) {m := newConnectionManager(t)- receipt, err := m.journal.begin(t.Context(), actionIdentity{AgentID: "agent", OperationID: "op", Session: "linger-task-browser"})+ journal, err := m.namedJournal(chromeProfileJournal("Default"))+ if err != nil {+ t.Fatal(err)+ }+ receipt, err := journal.begin(t.Context(), actionIdentity{AgentID: "agent", OperationID: "op", Session: "linger-task-browser"})if err != nil {t.Fatal(err)}@@ -768,7 +772,7 @@ func TestUserChromeUnknownActionSettlesWhenTheTaskStops(t *testing.T) {if err := op.close(); err != nil {t.Fatalf("close err=%v, want the stopped child to settle the action", err)}- next, err := m.journal.begin(t.Context(), actionIdentity{AgentID: "agent", OperationID: "next", Session: "linger-next-browser"})+ next, err := journal.begin(t.Context(), actionIdentity{AgentID: "other-agent", OperationID: "next", Session: "linger-next-browser"})if err != nil {t.Fatalf("input stayed blocked: %v", err)}diff --git a/apps/node-services/release-lockfiles/computer.yaml b/apps/node-services/release-lockfiles/computer.yamlindex 3d9fd2cb..f9edb2d5 100644--- a/apps/node-services/release-lockfiles/computer.yaml+++ b/apps/node-services/release-lockfiles/computer.yaml@@ -9,6 +9,7 @@ patchedDependencies:"@hocuspocus/[email protected]": 26806fa621c7cafd75f6e2737e820e6a341b46132399176083b6b342198eab76"@livekit/[email protected]": a2a99608ccad5c400634accbbb04b77a0f96bba6949baaa6c88b4568f7526753[email protected]: 7a922549743b0a521c959c1d7400ddb6cad1ca8c43c7692e2dc8847bd3f2ea25+ [email protected]: 78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5eimporters:.: {}apps/computer:@@ -2797,7 +2798,7 @@ snapshots:"@playwright/[email protected]":dependencies:playwright: 1.64.0-alpha-1790635538000- playwright-core: 1.64.0-alpha-1790635538000+ playwright-core: 1.64.0-alpha-1790635538000(patch_hash=78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5e)"@protobufjs/[email protected]": {}"@protobufjs/[email protected]": {}"@protobufjs/[email protected]": {}@@ -3678,10 +3679,11 @@ snapshots:- [email protected]: {}+ [email protected](patch_hash=78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5e):+ {}dependencies:- playwright-core: 1.64.0-alpha-1790635538000+ playwright-core: 1.64.0-alpha-1790635538000(patch_hash=78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5e)dependencies:nanoid: 3.3.16diff --git a/docs/architecture.md b/docs/architecture.mdindex 9f544116..dc0c79b6 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -117,9 +117,10 @@ Composio holds the app keys; an approved write runs exactly once## Inside Cua, Playwright and Shell-Desktop and browser actions share one input slot and a log written before each-action, so two agents never fight over the screen and an uncertain input is-never sent twice.+The screen has one input lane and each agent's browser has its own, so two+agents never fight over the screen while their browsers work at the same time.+Desktop input that needs the front window waits for browser calls in flight.+Each input is logged before it runs, so an uncertain input is never sent twice.```text┌─ Cua · Playwright · Shell ───────────────────────────────────────────────────┐@@ -127,15 +128,17 @@ never sent twice.│ │ Cua │ │ Playwright │ │ Shell │ ││ │ reads app windows │ │ own Chrome profile per │ │ the Runtime's │ ││ │ as elements, then │ │ agent, or your signed-in │ │ own command │ │-│ │ clicks, types, drags │ │ Chrome, one task at a time │ │ tool, run in │ │+│ │ clicks, types, drags │ │ Chrome, a seat per agent │ │ tool, run in │ ││ └──────────┬───────────┘ └─────────────┬──────────────┘ │ the Agent │ ││ ┌──────────┴───────────────────────────┴──────────────┐ │ workspace with │ │-│ │ one input slot: a second task waits for the screen │ │ your account │ │+│ │ one lane for the screen, one per agent's browser │ │ your account │ ││ │ each input is logged before it runs; an unknown │ │ │ │-│ │ result blocks further input and is never replayed │ │ │ │+│ │ result blocks its lane and is never replayed │ │ │ ││ └─────────────────────────────────────────────────────┘ └──────────────────┘ │└──────────────────────────────────────────────────────────────────────────────┘```<sub>On Linux, AT-SPI and xdotool replace Cua, and only the agent's own Chrome-profile is used. Page scripts are not offered to agents.</sub>+profile is used. With a Playwright Extension older than 0.5.0, agents take+turns in one seat of your signed-in Chrome. Page scripts are not offered to+agents.</sub>diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 00000000..ac9aa699--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,17 @@+diff --git a/lib/coreBundle.js b/lib/coreBundle.js+index 3d050d3f66703342cead4d35b900e1027c5af8df..9117ee3528b5ea9a2ce3bbc964545867ec0785e0 100644+--- a/lib/coreBundle.js++++ b/lib/coreBundle.js+@@ -38891,7 +38891,11 @@ var init_crPage = __esm({+ const skipDefaultOverrides = browserOptions.noDefaults && this._crPage._browserContext === this._crPage._browserContext._browser._defaultContext;+ if (this._crPage._browserContext.needsPlaywrightBinding())+ promises2.push(this.exposePlaywrightBinding());+- if (this._isMainFrame() && !skipDefaultOverrides)++ // Linger: keep focus emulation on every CDP connection, the user's++ // Chrome through the extension and the Agent Chrome alike. Without++ // it a background tab is hidden, stops rendering and drops input,++ // so several Agents could not work in their own tabs at once.++ if (this._isMainFrame())+ promises2.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true }));+ const options = this._crPage._browserContext._options;+ if (options.bypassCSP)diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3aa46326..1ece6d34 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -11,6 +11,7 @@ patchedDependencies:'@hocuspocus/[email protected]': 26806fa621c7cafd75f6e2737e820e6a341b46132399176083b6b342198eab76'@livekit/[email protected]': a2a99608ccad5c400634accbbb04b77a0f96bba6949baaa6c88b4568f7526753[email protected]: 7a922549743b0a521c959c1d7400ddb6cad1ca8c43c7692e2dc8847bd3f2ea25+ [email protected]: 78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5eimporters:@@ -9745,7 +9746,7 @@ snapshots:'@playwright/[email protected]':dependencies:playwright: 1.64.0-alpha-1790635538000- playwright-core: 1.64.0-alpha-1790635538000+ playwright-core: 1.64.0-alpha-1790635538000(patch_hash=78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5e)'@playwright/[email protected]':dependencies:@@ -14022,7 +14023,7 @@ snapshots:- [email protected]: {}+ [email protected](patch_hash=78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5e): {}dependencies:@@ -14032,7 +14033,7 @@ snapshots:dependencies:- playwright-core: 1.64.0-alpha-1790635538000+ playwright-core: 1.64.0-alpha-1790635538000(patch_hash=78d5eb47c9c7095d8c87a9f21aba2d7f240636ea9a759299d3f99d7f7f9bcd5e)diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 3af33413..b82510f3 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -30,3 +30,7 @@ patchedDependencies:# full inference process per worker."@livekit/[email protected]": patches/@[email protected]"[email protected]": patches/[email protected]+ # Playwright MCP drops focus emulation on CDP connections, the user's Chrome+ # and the Agent Chrome; background tabs then stop rendering and drop input,+ # so Agents could not work in parallel in their own tabs.+ "[email protected]": patches/[email protected]