Preventing Multi-Session Chrome Collisions: Tab Ownership Isolation, Desktop Input Mutex, and the 6th Status Color
Once agyr, the 5-color terminal title notifications, and the lazy-loading Chrome MCP proxy from earlier posts were running smoothly, a good problem quickly surfaced: I now routinely run three or four split terminal panes with parallel agy sessions working simultaneously.
As long as every session sticks to editing code, they stay out of each other’s way. The moment two sessions start driving the browser at the same time—or one invokes xdotool / wmctrl on the desktop—things break fast:
- Tab collisions: Every session shares a single debugging Chrome instance (
127.0.0.1:9223). Session B can easily click, navigate away from, or close the exact page Session A is debugging. - Focus stealing: A background session calls
select_page(bringToFront=true), yanking the Chrome window to the foreground right in the middle of what you are typing. - Invisible UI activity: In the 5-color terminal title bar (🔴/🔵/🟡/🟣/🟢), both code execution and UI automation show up as
🟣. At a glance, you cannot tell which pane is actively touching your browser or desktop.
This post walks through how I solved multi-session browser and desktop concurrency without giving up parallelism: hard tab ownership isolation in a bidirectional MCP proxy, a physical desktop input lease mutex backed by lexical Hook parsing, and a 6th status color (🟠) with a 15-second anti-flicker hold window.

1. Setting Boundaries: Why Not a Global Mutex for Chrome?
Before writing any code, I compared three designs. The trade-offs are straightforward:
| Approach | Core Mechanism | Pros | Dealbreaker |
|---|---|---|---|
| Global Chrome mutex | File lock in a Hook allowing only one session to call Chrome MCP at a time | Simplest to build | While Session A runs a long browser debug flow, Session B stalls and frequently hits Hook timeouts |
| Per-session Chrome instances | Dynamically allocate a debug port and separate profile per session | Strongest isolation | Loses shared login sessions (cookies), multiplies memory usage, and defeats the tab-group extension from Part 2 |
| Layered concurrency guards (chosen) | Shared Chrome instance + proxy-level tab ownership guardrails + focus-stealing prevention; cross-session lease mutex for physical input | Preserves shared logins, true multi-session parallelism, zero cross-tab interference, zero extra memory | Requires upgrading the lazy-loading script into a bidirectional JSON-RPC proxy |
The rule is simple: isolate parallelizable resources at fine granularity (browser tabs), and serialize only inherently global physical resources (mouse, keyboard, and window focus).
2. Reading the chrome-devtools-mcp Source: Dodging the pageId Trap
At first, I almost took a shortcut. Since click, navigate_page, and close_page in chrome-devtools-mcp all accept an explicit pageId, and I already had --backgroundNewPages enabled, why not record pageId directly in a shared lock file?
Reading McpContext.js in chrome-devtools-mcp (v1.14.0) stopped me cold: pageId is not a global identifier—it is a local counter incremented independently from 1 inside each MCP subprocess (let nextPageId = 1).
That means:
- Session A and Session B each spawn their own
chrome-devtools-mcpsubprocess; pageId: 2in Session A might be an admin dashboard, whilepageId: 2in Session B is a docs page;- Storing raw
pageIdvalues in a cross-process registry would not only fail to isolate sessions, it would block the wrong tabs with surgical precision.
The true globally unique, cross-process identifier is targetId, returned by Chrome’s CDP (Chrome DevTools Protocol) endpoint at GET http://127.0.0.1:9223/json/list. Cross-session isolation therefore needs a translation layer: each proxy process maintains an in-memory local_page_id ↔ targetId map, while the shared on-disk registry stores only global targetId → owner_pid entries.
3. Upgrading the Lazy-Loading Script into a Bidirectional MCP Proxy
In Part 2, ~/.gemini/bin/chrome-devtools-mcp-lazy.py was a one-way stdin forwarder: it intercepted the first tools/call to launch Chrome and let stdout pass straight through. To inspect page listings in MCP responses and block unauthorized tool calls, I upgraded it into a bidirectional JSON-RPC stdio proxy (main thread reads stdin; background pump_stdout thread reads subprocess stdout).
Here is the end-to-end flow across concurrent sessions:
sequenceDiagram
participant A as AGY Session A (Proxy PID 101)
participant B as AGY Session B (Proxy PID 202)
participant REG as .tab-owners.json (flock)
participant CDP as Chrome CDP /json/list
A->>CDP: Snapshot before_ids before calling new_page
A->>CDP: Diff after creating tab → targetId=T1
A->>REG: Acquire flock and claim T1 → owner_pid=101
B->>CDP: list_pages and map local_id ↔ targetId
B->>REG: Query owners & prune dead PIDs / closed tabs
Note over B: Annotate response:<br/>T1 [owned by another active session - DO NOT TOUCH]
B->>B: If model still attempts click/close on T1 → proxy short-circuits with isError: true
Note over B: Unauthorized calls reaching Chrome MCP: 0
The implementation breaks down into four mechanisms, built purely on the Python standard library (fcntl.flock on Linux/macOS, switching automatically to msvcrt.locking on Windows):
1. File-Locked Ownership Registry + Stale Entry Pruning
The shared registry lives inside the debugging profile directory (~/.local/share/chrome-mcp-profile/.tab-owners.json) paired with .tab-owners.lock. Every read or write runs two automatic cleanup passes:
- Probe each owner PID with
os.kill(pid, 0)and immediately reclaim entries from exited sessions; - Cross-check against the live set from CDP
/json/listand drop tabs that have already been closed.
2. new_page Diff Claiming + Soft/Hard Defense on list_pages
- Claiming: Before forwarding
new_page, fetch/json/listto recordbefore_ids. After receiving a successful response, fetch it again, compute the diff, claim the newly createdtargetId, and bind it to this process’slocal_page_id. - Soft hints:
pump_stdoutintercepts responses containing## Pages, appending[yours]to tabs owned by the current session and[owned by another active session - DO NOT TOUCH]to tabs owned by other live sessions—giving the model clear visibility first. - Hard blocking: If the model ignores the hint and still calls
click,fill,navigate_page,close_page, or any other tab-scoped tool against another active session’spageId, the proxy short-circuits and returns an MCP error directly:
1 | # Core blocking logic in chrome-devtools-mcp-lazy.py (sanitized and condensed) |
Unowned tabs are intentionally allowed: If you manually open a tab in the debugging Chrome instance (for example, to sign in or pass a CAPTCHA before handing off to AGY), it has no owner PID in .tab-owners.json. Any session can interact with it normally without disrupting human-in-the-loop workflows.
3. Suppressing select_page Focus Stealing
Even with --backgroundNewPages enabled, a model switching tabs can still pass bringToFront: true to select_page, yanking the entire Chrome window to the top of your screen. The proxy rewrites that argument to false:
1 | allow_focus = os.environ.get("AGY_CHROME_ALLOW_FOCUS", "0") == "1" |
If a workflow genuinely needs the browser brought to the foreground, setting AGY_CHROME_ALLOW_FOCUS=1 opts out on demand.
4. Physical Desktop Input Mutex: Lexical Command Detection + Lease Queueing
Browser tabs can run in parallel, but physical mouse, keyboard, clipboard, and desktop window control commands (xdotool, ydotool, wmctrl, xclip, scrot, osascript, pyautogui/pynput, etc.) share a single host-wide input stream. Two sessions issuing them at once will scramble your cursor and keystrokes.
I added a standalone Hook script at ~/.gemini/config/hooks/ui-action-state.py that consolidates UI action detection, the physical desktop input lease mutex, and terminal title state updates into one lightweight entry point (measured at ~25 ms per invocation):
1. Lexical Command-Head Parsing to Eliminate grep xdotool False Positives
Never match CommandLine with a naive substring regex—otherwise asking an agent to run grep -n xdotool title.py or echo "xdotool" will falsely trigger desktop-control mode.
Instead, the script tokenizes each statement using shlex.shlex(..., punctuation_chars=";&|(){}\n"), strips prefix wrappers like env, sudo, timeout, and nice, and inspects only the actual executable name (while recursively unpacking bash -c "..." and python3 -c "import pyautogui; ..."):
1 | # Matched examples: |
2. Physical Desktop Input Lease Mutex (Zero Queueing for Chrome Calls)
- Matching
chrome/browser: writes only the session-scoped UI state file with no lock, keeping multi-session Chrome automation fully parallel. - Matching
desktop: acquires a lease at/tmp/agy-ui-action/desktop-input.lease(guarded by a.lockfile):- Free lock, re-entrant acquisition by the same session, or a lease past its 60-second TTL (crash deadlock protection): acquires immediately and proceeds;
- Held by another session: polls with backoff for up to 20 seconds; proceeds if acquired, or returns
{"decision": "deny", "reason": "..."}on timeout so the agent retries later; - Released automatically by
PostToolUseandStophooks.
3. Decoupled Hook Registration in hooks.json
Without touching the existing deny-docker or title-waiting-choice hooks, I added a dedicated "title-ui-action" block:
1 | { |
The matcher intentionally avoids a blanket .*, keeping high-frequency tools like read_file, edit_file, and write_file off the Hook path while reliably catching chrome-devtools calls via call_mcp_tool.
5. The 6th Status Color (🟠) and the 15-Second Anti-Flicker Hold Window
The ~/.gemini/antigravity-cli/title.py script from Part 1 originally had five status colors. It is now a 6-color state machine:
| Priority | Dot | Trigger Condition | Meaning (At-a-Glance Signal) |
|---|---|---|---|
| 1 | 🔴 |
agent_state == "error" |
Error occurred; needs intervention |
| 2 | 🔵 |
ask_question flag present and not idle |
Waiting for your multiple-choice decision |
| 3 | 🟡 |
tool_confirmation_pending == true |
Waiting for command/tool approval |
| 4 | 🟠 |
Running and UI action active (including 15s hold window) | Session is driving the browser or desktop UI |
| 5 | 🟣 |
is_busy (running / subagents / background tasks) |
Normal thinking, editing code, or running commands |
| 6 | 🟢 |
idle |
Idle and ready |
Why Add a 15-Second Anti-Flicker Hold Window?
Real browser automation happens in short bursts: a click takes 200 ms, the model spends 4 seconds reading the snapshot, then calls fill for 300 ms.
If PostToolUse deleted the state file immediately on completion, the title bar would strobe between 🟠 and 🟣, creating more visual noise than signal.
To keep the indicator steady, state transitions work in three phases:
PreToolUse(start): atomically writes{"active": true, "ts": now, "kind": "chrome"}→ flips immediately to🟠;PostToolUse(end): does not delete the file; atomically updates it to{"active": false, "ts": now, "kind": "chrome"}→title.pykeeps🟠lit for 15 seconds whileactiveisfalse. Continuous browser work stays solid orange, and falls back smoothly to🟣15 seconds after UI calls stop;- Two fail-safes against stuck state:
- An
active: truerecord older than 180 seconds is treated as stale and falls back to🟣; - The
Stophook deletes the state file immediately, andtitle.pyforces🟢wheneveridle(not is_busy) is detected—so a finished session never stays stuck on orange.
- An
1 | # Core state check in title.py |
6. Two Real Pitfalls Caught Before Shipping
Never ship concurrency code on “looks right.” Running a two-process concurrency test suite and an end-to-end agy -p test caught two subtle bugs right away:
Pitfall 1: Proxy Hanging on SIGTERM and Nearly Leaving Orphaned Tab Ownership
In the two-process automated test, after spinning up real chrome-devtools-mcp-lazy.py proxies for Session A and Session B, calling terminate() (SIGTERM) on Session B hung until subprocess.TimeoutExpired.
The root cause was classic:
forward_signal()forwardedSIGTERMto thechrome-devtools-mcpchild process, but the main thread remained blocked insys.stdin.buffer.readline();- Because the test runner had not closed the stdin pipe yet, the main thread never woke up—so
registry.release_all_mine()and child cleanup in thefinally:block never ran.
The fix is one clean line: add raise SystemExit(128 + signum) inside forward_signal to interrupt the blocking stdin read, run the finally: cleanup to release tab ownership, and reap the child with wait(timeout=2.0) plus a kill() fallback:
1 | def forward_signal(signum: int, _frame: object) -> None: |
Re-running the two-process concurrency test dropped shutdown time to milliseconds and cleared .tab-owners.json immediately.
Pitfall 2: Testing New hooks.json Rules Inside the Already-Running Session
Right after editing all four files, I called chrome-devtools list_pages inside my currently running session, expecting the title bar to turn orange. Nothing happened—/tmp/agy-ui-action/ was not even created.
Investigation confirmed an important AGY CLI behavior: hooks.json and MCP proxy processes are loaded at agy startup; already-running sessions do not hot-reload new Hooks.
Verification is straightforward: launch a fresh agy -p session (pointed at a temporary AGY_UI_STATE_DIR) and invoke list_pages. You immediately see the full lifecycle:
PreToolUse→ writesconv-<hash>.json(active: true)PostToolUse→ updates to{"active": false, "ts": ..., "kind": "chrome"}Stop→ removes the state file cleanly on exit with zero residue
Finally, I pushed the entire change set to my private environment backup repo via sync.py push from Part 4, so a fresh machine still gets the complete setup from a single ./init.sh.
Summary
With these pieces in place, the last major gap in running parallel agy CLI sessions is closed:
- True multi-session Chrome parallelism: Shared login sessions stay intact, CDP
targetId+ file-locked tab ownership isolation blocks cross-session tampering,bringToFrontfocus stealing is suppressed, and manually opened unowned tabs remain accessible; - Collision-free physical desktop input: Lexical command-head parsing eliminates
grepfalse positives, while the cross-session lease mutex queues safely, denies on timeout, and expires stale leases via TTL; - Instant visual feedback in the terminal title: The 6th status color (
🟠) with a 15-second anti-flicker hold window makes it obvious at a glance which pane is thinking (🟣), waiting on your choice (🔵), or touching your browser/desktop (🟠).
Series Navigation
- Previous: Backing Up, Porting & One-Click Bootstrapping Local AGY Environments
- Next: From Single-Machine Tweaks to Cross-Host Engineering: Sub-Second Stop Gates, 3-Plugin Split & Per-Host Toggles
- Series Index: Google Antigravity (AGY) Engineering in Practice · Series Index
- Base Series: Google Antigravity (AGY) Field Guide · Series Index








