High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: tab locking for multi-agent coordination (P3)
bot3e26ec96135f
diff --git a/TODO.md b/TODO.mdindex 761404df..81451d36 100644--- a/TODO.md+++ b/TODO.md@@ -22,9 +22,9 @@ now consumed by Go). **92 unit tests + ~100 integration, 28.9% coverage.**P0 (K10 profile hang), P1 (token optimization: maxTokens/selector/compact),P2 (K11 file path, blockImages on CreateTab) — all resolved.-### P3: Multi-Agent-- [ ] **Tab locking** — `POST /tab/lock`, `POST /tab/unlock` with timeout-based deadlock prevention.-- [ ] **Tab ownership tracking** — Show owner in `/tabs` response.+### ~~P3: Multi-Agent~~ — DONE+- [x] **Tab locking** — `POST /tab/lock`, `POST /tab/unlock` with timeout-based deadlock prevention (default 30s, max 5min). Same owner can re-lock (extend). 409 on conflict.+- [x] **Tab ownership tracking** — `/tabs` shows `owner` and `lockedUntil` on locked tabs.### P4: Quality of Life- [ ] **Headed mode testing** — Run Section 2 tests to validate non-headless.diff --git a/bridge.go b/bridge.goindex 15b5b166..f2583890 100644--- a/bridge.go+++ b/bridge.go@@ -35,6 +35,7 @@ type Bridge struct {tabs map[string]*TabEntrysnapshots map[string]*refCachestealthScript string // injected on every new tab+ locks *lockManagermu sync.RWMutex}diff --git a/handlers.go b/handlers.goindex b2aee3a6..0b0a2818 100644--- a/handlers.go+++ b/handlers.go@@ -38,12 +38,17 @@ func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {tabs := make([]map[string]any, 0, len(targets))for _, t := range targets {- tabs = append(tabs, map[string]any{+ entry := map[string]any{"id": string(t.TargetID),"url": t.URL,"title": t.Title,"type": t.Type,- })+ }+ if lock := b.locks.Get(string(t.TargetID)); lock != nil {+ entry["owner"] = lock.Owner+ entry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)+ }+ tabs = append(tabs, entry)}jsonResp(w, 200, map[string]any{"tabs": tabs})}@@ -357,6 +362,65 @@ func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {}}+// ── POST /tab/lock ─────────────────────────────────────────++func (b *Bridge) handleTabLock(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Owner string `json:"owner"`+ TimeoutSec int `json:"timeoutSec"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.TabID == "" || req.Owner == "" {+ jsonResp(w, 400, map[string]string{"error": "tabId and owner required"})+ return+ }++ timeout := defaultLockTimeout+ if req.TimeoutSec > 0 {+ timeout = time.Duration(req.TimeoutSec) * time.Second+ }++ if err := b.locks.Lock(req.TabID, req.Owner, timeout); err != nil {+ jsonResp(w, 409, map[string]string{"error": err.Error()})+ return+ }++ lock := b.locks.Get(req.TabID)+ jsonResp(w, 200, map[string]any{+ "locked": true,+ "owner": lock.Owner,+ "expiresAt": lock.ExpiresAt.Format(time.RFC3339),+ })+}++// ── POST /tab/unlock ───────────────────────────────────────++func (b *Bridge) handleTabUnlock(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Owner string `json:"owner"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.TabID == "" || req.Owner == "" {+ jsonResp(w, 400, map[string]string{"error": "tabId and owner required"})+ return+ }++ if err := b.locks.Unlock(req.TabID, req.Owner); err != nil {+ jsonResp(w, 409, map[string]string{"error": err.Error()})+ return+ }++ jsonResp(w, 200, map[string]any{"unlocked": true})+}+// ── POST /shutdown ─────────────────────────────────────────func (b *Bridge) handleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {diff --git a/lock.go b/lock.gonew file mode 100644index 00000000..4e728895--- /dev/null+++ b/lock.go@@ -0,0 +1,105 @@+package main++import (+ "fmt"+ "sync"+ "time"+)++// TabLock represents an active lock held by an agent on a tab.+type TabLock struct {+ Owner string `json:"owner"`+ LockedAt time.Time `json:"lockedAt"`+ ExpiresAt time.Time `json:"expiresAt"`+}++// lockManager handles tab locking with timeout-based deadlock prevention.+type lockManager struct {+ locks map[string]*TabLock // tabID → lock+ mu sync.Mutex+}++const (+ defaultLockTimeout = 30 * time.Second+ maxLockTimeout = 5 * time.Minute+)++func newLockManager() *lockManager {+ return &lockManager{locks: make(map[string]*TabLock)}+}++// Lock acquires a lock on a tab for the given owner. Returns error if already+// locked by a different owner (and not expired).+func (lm *lockManager) Lock(tabID, owner string, timeout time.Duration) error {+ if owner == "" {+ return fmt.Errorf("owner required")+ }+ if timeout <= 0 {+ timeout = defaultLockTimeout+ }+ if timeout > maxLockTimeout {+ timeout = maxLockTimeout+ }++ lm.mu.Lock()+ defer lm.mu.Unlock()++ if existing, ok := lm.locks[tabID]; ok {+ if time.Now().Before(existing.ExpiresAt) && existing.Owner != owner {+ return fmt.Errorf("tab locked by %q until %s", existing.Owner, existing.ExpiresAt.Format(time.RFC3339))+ }+ }++ lm.locks[tabID] = &TabLock{+ Owner: owner,+ LockedAt: time.Now(),+ ExpiresAt: time.Now().Add(timeout),+ }+ return nil+}++// Unlock releases a lock. Only the owner (or anyone after expiry) can unlock.+func (lm *lockManager) Unlock(tabID, owner string) error {+ lm.mu.Lock()+ defer lm.mu.Unlock()++ existing, ok := lm.locks[tabID]+ if !ok {+ return nil // not locked, idempotent+ }++ if existing.Owner != owner && time.Now().Before(existing.ExpiresAt) {+ return fmt.Errorf("tab locked by %q, cannot unlock", existing.Owner)+ }++ delete(lm.locks, tabID)+ return nil+}++// Get returns the lock info for a tab, or nil if unlocked/expired.+func (lm *lockManager) Get(tabID string) *TabLock {+ lm.mu.Lock()+ defer lm.mu.Unlock()++ lock, ok := lm.locks[tabID]+ if !ok {+ return nil+ }+ if time.Now().After(lock.ExpiresAt) {+ delete(lm.locks, tabID)+ return nil+ }+ return lock+}++// CheckAccess returns an error if the tab is locked by someone other than owner.+func (lm *lockManager) CheckAccess(tabID, owner string) error {+ lock := lm.Get(tabID)+ if lock == nil {+ return nil+ }+ if owner == "" || lock.Owner != owner {+ return fmt.Errorf("tab locked by %q until %s", lock.Owner, lock.ExpiresAt.Format(time.RFC3339))+ }+ return nil+}diff --git a/lock_handler_test.go b/lock_handler_test.gonew file mode 100644index 00000000..5d83edf9--- /dev/null+++ b/lock_handler_test.go@@ -0,0 +1,78 @@+package main++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestHandleTabLock(t *testing.T) {+ b := &Bridge{locks: newLockManager()}++ // Lock a tab+ body, _ := json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-a", "timeoutSec": 10})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))+ b.handleTabLock(w, r)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp map[string]any+ _ = json.Unmarshal(w.Body.Bytes(), &resp)+ if resp["locked"] != true {+ t.Fatalf("expected locked=true: %v", resp)+ }+ if resp["owner"] != "agent-a" {+ t.Fatalf("expected owner=agent-a: %v", resp)+ }++ // Conflict from different owner+ body, _ = json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-b"})+ w = httptest.NewRecorder()+ r, _ = http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))+ b.handleTabLock(w, r)++ if w.Code != 409 {+ t.Fatalf("expected 409, got %d", w.Code)+ }+}++func TestHandleTabUnlock(t *testing.T) {+ b := &Bridge{locks: newLockManager()}+ _ = b.locks.Lock("t1", "agent-a", 0)++ // Wrong owner+ body, _ := json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-b"})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tab/unlock", bytes.NewReader(body))+ b.handleTabUnlock(w, r)+ if w.Code != 409 {+ t.Fatalf("expected 409, got %d", w.Code)+ }++ // Correct owner+ body, _ = json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-a"})+ w = httptest.NewRecorder()+ r, _ = http.NewRequest("POST", "/tab/unlock", bytes.NewReader(body))+ b.handleTabUnlock(w, r)+ if w.Code != 200 {+ t.Fatalf("expected 200, got %d", w.Code)+ }+}++func TestHandleTabLockValidation(t *testing.T) {+ b := &Bridge{locks: newLockManager()}++ // Missing fields+ body, _ := json.Marshal(map[string]any{"tabId": "t1"})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))+ b.handleTabLock(w, r)+ if w.Code != 400 {+ t.Fatalf("expected 400, got %d", w.Code)+ }+}diff --git a/lock_test.go b/lock_test.gonew file mode 100644index 00000000..1398d36a--- /dev/null+++ b/lock_test.go@@ -0,0 +1,115 @@+package main++import (+ "testing"+ "time"+)++func TestLockBasic(t *testing.T) {+ lm := newLockManager()++ // Lock succeeds+ if err := lm.Lock("tab1", "agent-a", 5*time.Second); err != nil {+ t.Fatal(err)+ }++ // Same owner can re-lock (extend)+ if err := lm.Lock("tab1", "agent-a", 5*time.Second); err != nil {+ t.Fatal(err)+ }++ // Different owner blocked+ if err := lm.Lock("tab1", "agent-b", 5*time.Second); err == nil {+ t.Fatal("expected lock conflict")+ }++ // Unlock+ if err := lm.Unlock("tab1", "agent-a"); err != nil {+ t.Fatal(err)+ }++ // Now agent-b can lock+ if err := lm.Lock("tab1", "agent-b", 5*time.Second); err != nil {+ t.Fatal(err)+ }+}++func TestLockExpiry(t *testing.T) {+ lm := newLockManager()++ if err := lm.Lock("tab1", "agent-a", 1*time.Millisecond); err != nil {+ t.Fatal(err)+ }+ time.Sleep(5 * time.Millisecond)++ // Expired — different owner can now lock+ if err := lm.Lock("tab1", "agent-b", 5*time.Second); err != nil {+ t.Fatalf("expected expired lock to allow new owner: %v", err)+ }+}++func TestLockCheckAccess(t *testing.T) {+ lm := newLockManager()++ // No lock — anyone can access+ if err := lm.CheckAccess("tab1", "anyone"); err != nil {+ t.Fatal(err)+ }++ _ = lm.Lock("tab1", "agent-a", 5*time.Second)++ // Owner can access+ if err := lm.CheckAccess("tab1", "agent-a"); err != nil {+ t.Fatal(err)+ }++ // Non-owner blocked+ if err := lm.CheckAccess("tab1", "agent-b"); err == nil {+ t.Fatal("expected access denied")+ }++ // Empty owner blocked+ if err := lm.CheckAccess("tab1", ""); err == nil {+ t.Fatal("expected access denied for empty owner")+ }+}++func TestUnlockIdempotent(t *testing.T) {+ lm := newLockManager()++ // Unlocking a non-locked tab is fine+ if err := lm.Unlock("tab1", "anyone"); err != nil {+ t.Fatal(err)+ }+}++func TestUnlockWrongOwner(t *testing.T) {+ lm := newLockManager()+ _ = lm.Lock("tab1", "agent-a", 5*time.Second)++ if err := lm.Unlock("tab1", "agent-b"); err == nil {+ t.Fatal("expected unlock denied for wrong owner")+ }+}++func TestMaxTimeout(t *testing.T) {+ lm := newLockManager()+ _ = lm.Lock("tab1", "agent-a", 10*time.Minute) // exceeds max++ lock := lm.Get("tab1")+ if lock == nil {+ t.Fatal("expected lock")+ }+ // Should be capped to maxLockTimeout (5 min)+ maxExpiry := time.Now().Add(maxLockTimeout + time.Second)+ if lock.ExpiresAt.After(maxExpiry) {+ t.Fatalf("lock timeout not capped: expires %v", lock.ExpiresAt)+ }+}++func TestLockRequiresOwner(t *testing.T) {+ lm := newLockManager()+ if err := lm.Lock("tab1", "", 5*time.Second); err == nil {+ t.Fatal("expected error for empty owner")+ }+}diff --git a/main.go b/main.goindex 37b237b3..f1f7fb7d 100644--- a/main.go+++ b/main.go@@ -222,6 +222,7 @@ func main() {bridge.browserCtx = browserCtxbridge.tabs = make(map[string]*TabEntry)bridge.snapshots = make(map[string]*refCache)+ bridge.locks = newLockManager()// Register the initial tabinitTargetID := chromedp.FromContext(browserCtx).Target.TargetID@@ -250,6 +251,8 @@ func main() {mux.HandleFunc("POST /actions", bridge.handleActions)mux.HandleFunc("POST /evaluate", bridge.handleEvaluate)mux.HandleFunc("POST /tab", bridge.handleTab)+ mux.HandleFunc("POST /tab/lock", bridge.handleTabLock)+ mux.HandleFunc("POST /tab/unlock", bridge.handleTabUnlock)mux.HandleFunc("GET /cookies", bridge.handleGetCookies)mux.HandleFunc("POST /cookies", bridge.handleSetCookies)mux.HandleFunc("GET /stealth/status", bridge.handleStealthStatus)