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): address review of browser lanes
jeffrey6266a5fcb120
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex e343371b..a269755f 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -185,7 +185,9 @@ 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 thebrowser calls in flight. From the moment it starts waiting, new browser callswait 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,+in the page. A browser call holds its turn until it returns, so one long call,+such as a slow navigation or `browser_wait_for`, delays the waiting input and+with it every Agent's next browser call. 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@@ -350,7 +352,11 @@ other where one could still reach the other: an unknown browser action blocksdesktop input that needs the front window or the clipboard, and an unknowndesktop input of that kind blocks browser calls, so does a record that anolder Daemon left without saying which kind it was. Such a call returns-`COMPUTER_ACTION_UNKNOWN`. After a+`COMPUTER_ACTION_UNKNOWN` and names the Agent and the record file that blocks it.+A record that an earlier Daemon left has no task here to settle it; the error+says so, and removing that file once the action is known to be finished frees+the desktop. An unknown action on a whole everyday Chrome profile, left before+the extension kept many clients, also blocks every seat of that profile. 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'sdiff --git a/apps/computer/local-daemon/internal/linger/localtools/browser.go b/apps/computer/local-daemon/internal/linger/localtools/browser.goindex 602843f1..4760e0ee 100644--- a/apps/computer/local-daemon/internal/linger/localtools/browser.go+++ b/apps/computer/local-daemon/internal/linger/localtools/browser.go@@ -84,6 +84,17 @@ func (op *operation) nativeBrowserCall(ctx context.Context, name string, args jsjournalName := browserLane(op.spec.AgentID)if chrome != nil {journalName = chromeProfileJournal(seat)+ // The seat follows the installed extension. An action left on the+ // whole profile before an upgrade may still reach this Agent's tabs.+ if seat != chrome.Profile {+ whole, err := op.manager.namedJournal(chromeProfileJournal(chrome.Profile))+ if err != nil {+ return nil, err+ }+ if unknown := whole.unknownAction(); unknown != "" {+ return nil, fmt.Errorf("COMPUTER_ACTION_UNKNOWN: an earlier action in this Chrome profile has no verified cleanup receipt; %s: %w", unknown, errNotSent)+ }+ }}journal, err := op.manager.namedJournal(journalName)if err != nil {diff --git a/apps/computer/local-daemon/internal/linger/localtools/focus.go b/apps/computer/local-daemon/internal/linger/localtools/focus.goindex f06a8fe9..7829e524 100644--- a/apps/computer/local-daemon/internal/linger/localtools/focus.go+++ b/apps/computer/local-daemon/internal/linger/localtools/focus.go@@ -88,9 +88,9 @@ func (m *Manager) holdFocusedInput(ctx context.Context) (context.Context, func()if err != nil || held {return ctx, release, err}- if m.browserActionUnknown() {+ if unknown := m.browserActionUnknown(); unknown != "" {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, nil, fmt.Errorf("COMPUTER_ACTION_UNKNOWN: an earlier browser action has no verified cleanup receipt, so input that needs the front window or the clipboard waits; %s: %w", unknown, errNotSent)}return ctx, release, nil}diff --git a/apps/computer/local-daemon/internal/linger/localtools/journal.go b/apps/computer/local-daemon/internal/linger/localtools/journal.goindex 82387778..709e98e5 100644--- a/apps/computer/local-daemon/internal/linger/localtools/journal.go+++ b/apps/computer/local-daemon/internal/linger/localtools/journal.go@@ -5,6 +5,7 @@ import ("crypto/rand""encoding/json""errors"+ "fmt""os""path/filepath""runtime"@@ -29,7 +30,10 @@ type actionJournal struct {mu sync.Mutexpath stringactive *actionIdentity- slot chan struct{}+ // restored marks an active record read from disk: an earlier Daemon left+ // it, so no task of this one holds its receipt.+ restored bool+ slot chan struct{}}type actionReceipt struct {@@ -60,7 +64,7 @@ func openJournal(path string) (*actionJournal, error) {if json.Unmarshal(data, &stored) != nil || stored.Version != 1 || (stored.Active != nil && stored.Active.Nonce == "") {return nil, errors.New("invalid local tool action state; input remains blocked")}- j.active = stored.Active+ j.active, j.restored = stored.Active, stored.Active != nilreturn j, nil}@@ -85,7 +89,7 @@ func (j *actionJournal) begin(ctx context.Context, identity actionIdentity) (*ac<-j.slotreturn nil, err}- j.active = &identity+ j.active, j.restored = &identity, falsereturn &actionReceipt{journal: j, nonce: identity.Nonce}, nil}@@ -141,6 +145,20 @@ func (r *actionReceipt) finish(confirmed bool) error {return err}+// unknownAction describes the unknown action this journal holds, or returns+// "" when it holds none.+func (j *actionJournal) unknownAction() string {+ j.mu.Lock()+ defer j.mu.Unlock()+ if j.active == nil {+ return ""+ }+ if j.restored {+ return fmt.Sprintf("Agent %q left it in %s before the Daemon restarted; no task settles it; the user removes that file once they know the action finished", j.active.AgentID, j.path)+ }+ return fmt.Sprintf("Agent %q left it in %s; it settles when that task ends", j.active.AgentID, j.path)+}+func (j *actionJournal) blocked() bool {j.mu.Lock()defer j.mu.Unlock()diff --git a/apps/computer/local-daemon/internal/linger/localtools/lanes_test.go b/apps/computer/local-daemon/internal/linger/localtools/lanes_test.goindex 849c6a6b..dcd585cb 100644--- a/apps/computer/local-daemon/internal/linger/localtools/lanes_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/lanes_test.go@@ -9,6 +9,7 @@ import ("runtime""strings""sync"+ "sync/atomic""testing""time"@@ -74,30 +75,6 @@ func agentBrowserOp(t *testing.T, m *Manager, agent string) *operation {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(`{}`))@@ -105,65 +82,113 @@ func browserClick(op *operation) func() error {}}-// Each fixture call takes 250 ms.+// Browser calls of two Agents run together; tasks of one Agent take turns.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)+ b, again := agentBrowserOp(t, m, "b"), agentBrowserOp(t, m, "a")+ // Hold Agent a's lane as a call of its in flight does.+ _, release, err := m.holdLane(t.Context(), browserLane("a"))+ if err != nil {+ t.Fatal(err)+ }+ if err := browserClick(b)(); err != nil {+ t.Fatalf("Agent b's browser call failed while Agent a's ran: %v", err)+ }+ done := make(chan error, 1)+ go func() { done <- browserClick(again)() }()+ select {+ case err := <-done:+ t.Fatalf("two tasks of one Agent drove its browser at once: %v", err)+ case <-time.After(100 * time.Millisecond):+ }+ release()+ if err := <-done; err != nil {+ t.Fatal(err)+ }+}++// focusBusy reports whether a hold of the gate waits: it gives up after a+// short wait and then returns the not-sent error.+func focusBusy(t *testing.T, m *Manager, exclusive bool) bool {+ t.Helper()+ ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)+ defer cancel()+ _, release, err := m.holdFocus(ctx, exclusive)+ if err == nil {+ release()+ return false}- 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)+ if !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "COMPUTER_BUSY") {+ t.Fatalf("a cancelled wait for the gate: %v", err)}+ return true}// 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)+ _, releaseBrowser, err := m.holdFocus(t.Context(), false)+ if err != nil {+ t.Fatal(err)+ }+ if focusBusy(t, m, false) {+ t.Fatal("browser calls of two Agents queued behind each other")+ }+ if !focusBusy(t, m, true) {+ t.Fatal("a focused desktop input ran beside a browser call")+ }+ type hold struct {+ ctx context.Context+ release func()+ }+ held := make(chan hold, 1)+ go func() {ctx, release, err := m.holdFocus(t.Context(), true)if err != nil {- return err+ t.Error(err)+ release = func() {}}- if !holdsFocus(ctx) {- return errors.New("exclusive hold not marked")+ held <- hold{ctx, release}+ }()+ deadline := time.Now().Add(5 * time.Second)+ for {+ m.focus.mu.Lock()+ waiting := m.focus.waiting+ m.focus.mu.Unlock()+ if waiting == 1 {+ break}- time.Sleep(250 * time.Millisecond)- release()- return nil+ if time.Now().After(deadline) {+ t.Fatal("the desktop input never waited")+ }+ time.Sleep(time.Millisecond)}- 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)+ // A browser call that arrives while that input waits runs after it.+ if !focusBusy(t, m, false) {+ t.Fatal("a browser call overtook a waiting desktop input")}- 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)+ select {+ case <-held:+ t.Fatal("a focused desktop input ran beside a browser call")+ default:}- // 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)+ releaseBrowser()+ input := <-held+ if !holdsFocus(input.ctx) {+ t.Fatal("exclusive hold not marked")+ }+ if _, _, err := m.holdFocus(input.ctx, true); err != nil {+ t.Fatalf("a nested input did not reuse the hold: %v", err)}done := make(chan error, 1)- go func() { done <- browserClick(a)() }()+ go func() { done <- browserClick(agentBrowserOp(t, m, "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()+ input.release()if err := <-done; err != nil {t.Fatal(err)}@@ -289,6 +314,10 @@ func TestLaneRecordsSurviveRestartPerLane(t *testing.T) {if laneBlocked(t, restarted, browserLane("b")) || restarted.journal.blocked() {t.Fatal("an unknown browser action blocked another lane after a restart")}+ // No task of this Daemon settles the record, so the refusal names it.+ if _, _, err := restarted.holdFocusedInput(t.Context()); err == nil || !strings.Contains(err.Error(), "before the Daemon restarted") || !strings.Contains(err.Error(), browserJournalPrefix) {+ t.Fatalf("focused desktop input after a restart left browser records: %v", err)+ }// 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"})@@ -309,6 +338,9 @@ func TestLanesAndFocusUnderLoad(t *testing.T) {m := laneManager(t, t.TempDir())ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)defer cancel()+ // Each side counts itself in before it looks at the other, so a desktop+ // input and a browser call holding the gate at once see each other.+ var desktop, browsers atomic.Int32var wg sync.WaitGroupfor worker := range 16 {wg.Go(func() {@@ -331,7 +363,20 @@ func TestLanesAndFocusUnderLoad(t *testing.T) {releases = append(releases, release)}}- _ = held+ if err == nil {+ if holdsFocus(held) {+ if desktop.Add(1) > 1 || browsers.Load() > 0 {+ t.Error("a focused desktop input ran beside another holder of the gate")+ }+ desktop.Add(-1)+ } else {+ browsers.Add(1)+ if desktop.Load() > 0 {+ t.Error("a browser call ran beside a focused desktop input")+ }+ browsers.Add(-1)+ }+ }for i := len(releases) - 1; i >= 0; i-- {if releases[i] != nil {releases[i]()@@ -526,6 +571,13 @@ func TestEverydayChromeSeatsKeepAgentsApart(t *testing.T) {if err := task("b"); err != nil {t.Fatalf("another Agent's seat was blocked: %v", err)}+ // A record left on the whole profile, before the extension kept many+ // clients, still guards every seat of that profile.+ whole := laneJournal(t, m, chromeProfileJournal("Default"))+ leaveUnknown(t, whole)+ if err := task("b"); err == nil || !strings.Contains(err.Error(), "COMPUTER_ACTION_UNKNOWN") || !strings.Contains(err.Error(), whole.path) {+ t.Fatalf("a seat ran beside an unknown action on its whole profile: %v", err)+ }if err := m.closeUserChrome(); 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 130dc2cc..f5c07930 100644--- a/apps/computer/local-daemon/internal/linger/localtools/manager.go+++ b/apps/computer/local-daemon/internal/linger/localtools/manager.go@@ -8,6 +8,7 @@ import ("encoding/json""errors""fmt"+ "maps""os""os/exec""path/filepath"@@ -548,17 +549,17 @@ func (m *Manager) openBrowserJournals() error {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 {+// browserActionUnknown describes a browser action whose outcome is unknown,+// in any Agent's browser or everyday Chrome seat, or returns "" when none is.+func (m *Manager) browserActionUnknown() string {m.laneMu.Lock()defer m.laneMu.Unlock()- for _, journal := range m.browserJournals {- if journal.blocked() {- return true+ for _, path := range slices.Sorted(maps.Keys(m.browserJournals)) {+ if unknown := m.browserJournals[path].unknownAction(); unknown != "" {+ return unknown}}- return false+ return ""}// namedJournal returns the action journal of an Agent's browser lane or of adiff --git a/apps/computer/scripts/bundle-computer-tools.mjs b/apps/computer/scripts/bundle-computer-tools.mjsindex a8b98083..e3542558 100644--- a/apps/computer/scripts/bundle-computer-tools.mjs+++ b/apps/computer/scripts/bundle-computer-tools.mjs@@ -304,6 +304,24 @@ async function assetFiles(root, relative = "") {return files;}+// The pnpm patch keeps focus emulation on CDP connections; without it Agents+// cannot work in background tabs at once. An install that skipped the patch+// would still bundle, so check the staged file itself.+async function assertPlaywrightPatched(root, packages) {+ const core = packages.filter(({ name }) => name === "playwright-core");+ if (core.length === 0) throw new Error("Playwright core was not staged");+ for (const { path: relative } of core) {+ const bundle = await readFile(+ path.join(root, relative, "lib/coreBundle.js"),+ "utf8",+ );+ if (!bundle.includes("// Linger: keep focus emulation on every CDP"))+ throw new Error(+ `${relative}/lib/coreBundle.js lacks the focus emulation patch`,+ );+ }+}+export async function stageComputerTools(bundle,{@@ -315,6 +333,7 @@ export async function stageComputerTools(await rm(root, { recursive: true, force: true });await mkdir(root, { recursive: true });const packages = await stagePackages(root);+ await assertPlaywrightPatched(root, packages);await mkdir(path.join(root, "extensions"), { recursive: true });await cp(path.join(computerRoot, "tools/pi-mcp.mjs"),diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex b82510f3..0eb33bd6 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -32,5 +32,7 @@ patchedDependencies:"[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.+ # so Agents could not work in parallel in their own tabs. Re-create the patch+ # on each @playwright/mcp bump; bundle-computer-tools.mjs refuses a bundle+ # without the patched line."[email protected]": patches/[email protected]