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:

  1. 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.
  2. 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.
  3. 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.

Architecture for multi-session Chrome tab ownership isolation, physical desktop input mutex, and the 6th status color


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-mcp subprocess;
  • pageId: 2 in Session A might be an admin dashboard, while pageId: 2 in Session B is a docs page;
  • Storing raw pageId values 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:

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/list and 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/list to record before_ids. After receiving a successful response, fetch it again, compute the diff, claim the newly created targetId, and bind it to this process’s local_page_id.
  • Soft hints: pump_stdout intercepts 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’s pageId, the proxy short-circuits and returns an MCP error directly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Core blocking logic in chrome-devtools-mcp-lazy.py (sanitized and condensed)
page_id = arguments.get("pageId")
if isinstance(page_id, int) and tool_name not in {"new_page", "list_pages"}:
blocking_pid = registry.check_blocking_owner(page_id)
if blocking_pid is not None:
write_client(
{
"jsonrpc": "2.0",
"id": msg.get("id"),
"result": {
"isError": True,
"content": [
{
"type": "text",
"text": (
f"Blocked: pageId {page_id} is owned by another active AGY session "
f"(pid {blocking_pid}). Use one of your own tabs or call new_page to open a separate tab."
),
}
],
},
}
)
continue

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
2
3
4
allow_focus = os.environ.get("AGY_CHROME_ALLOW_FOCUS", "0") == "1"
if tool_name == "select_page" and not allow_focus and arguments.get("bringToFront"):
arguments["bringToFront"] = False
modified = True

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
2
3
4
5
6
7
8
# Matched examples:
# xdotool mousemove 100 200
# env DISPLAY=:0 timeout 5 wmctrl -a Chrome
# python3 -c "import pyautogui; pyautogui.click()"
#
# Passed through with zero false positives:
# grep -n xdotool ~/.gemini/config/hooks/ui-action-state.py
# echo "don't run xdotool"

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 .lock file):
    • 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 PostToolUse and Stop hooks.

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
"title-ui-action": {
"PreToolUse": [
{
"matcher": ".*mcp.*|browser_.*|run_command",
"hooks": [
{
"type": "command",
"command": "python3 ~/.gemini/config/hooks/ui-action-state.py start",
"timeout": 25
}
]
}
],
"PostToolUse": [
{
"matcher": ".*mcp.*|browser_.*|run_command",
"hooks": [
{
"type": "command",
"command": "python3 ~/.gemini/config/hooks/ui-action-state.py end",
"timeout": 5
}
]
}
],
"Stop": [
{
"type": "command",
"command": "python3 ~/.gemini/config/hooks/ui-action-state.py clear",
"timeout": 5
}
]
}
}

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:

  1. PreToolUse (start): atomically writes {"active": true, "ts": now, "kind": "chrome"} → flips immediately to 🟠;
  2. PostToolUse (end): does not delete the file; atomically updates it to {"active": false, "ts": now, "kind": "chrome"} → title.py keeps 🟠 lit for 15 seconds while active is false. Continuous browser work stays solid orange, and falls back smoothly to 🟣 15 seconds after UI calls stop;
  3. Two fail-safes against stuck state:
    • An active: true record older than 180 seconds is treated as stale and falls back to 🟣;
    • The Stop hook deletes the state file immediately, and title.py forces 🟢 whenever idle (not is_busy) is detected—so a finished session never stays stuck on orange.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Core state check in title.py
UI_HOLD_SECONDS = 15.0
UI_ACTIVE_STALE_SECONDS = 180.0

def is_ui_action_active(state_key: str) -> bool:
state_file = UI_STATE_DIR / f"{state_key}.json"
if not state_file.is_file():
return False
info = json.loads(state_file.read_text(encoding="utf-8"))
age = time.time() - float(info["ts"])
if age < -5.0:
return False
if info.get("active") is True:
return age < UI_ACTIVE_STALE_SECONDS
return age < UI_HOLD_SECONDS

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() forwarded SIGTERM to the chrome-devtools-mcp child process, but the main thread remained blocked in sys.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 the finally: 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
2
3
4
5
6
7
def forward_signal(signum: int, _frame: object) -> None:
if proc.poll() is None:
try:
proc.send_signal(signum)
except ProcessLookupError:
pass
raise SystemExit(128 + signum)

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 → writes conv-<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, bringToFront focus stealing is suppressed, and manually opened unowned tabs remain accessible;
  • Collision-free physical desktop input: Lexical command-head parsing eliminates grep false 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