gstack icon indicating copy to clipboard operation
gstack copied to clipboard

Per-session tab isolation for multiple local agent sessions (foundation already shipped)

Open charitarora opened this issue 5 months ago • 6 comments

Feature: per-session tab isolation for multiple local agent sessions

Motivation

When several local agent sessions run in parallel on one machine (e.g. several claude sessions across git worktrees, all using /browse), they all drive one shared headed browser and clobber each other's active tab — navigations, snapshots, and state stomp on whoever else is mid-task. The single shared ~/.gstack/chromium-profile already forces one Chromium instance, which is fine; the problem is that every local session is the same client, so there's no per-session tab to own.

(Context: surfaced while investigating #1953 — the shared-daemon multi-session pain.)

The isolation primitives already exist (but aren't reachable locally)

1.57.9 has everything needed for remote paired agents:

  • Per-tab ownership — tabOwnership: Map<tabId → clientId> (browse/src/browser-manager.ts:177).
  • Scoped sub-tokens — root mints a token for a named client with a tabPolicy (server.ts:2179 "Only the root token can mint sub-tokens"; /pair takes --client <name>, cli.ts:839).
  • own-only enforcement — checkTabAccess() lets a non-root client touch only its own tabs; root bypasses (browser-manager.ts:927 if (clientId === 'root') return true; server.ts:1044).

The gap

Local $B commands always authenticate with the root token: Authorization: Bearer ${state.token} (cli.ts:542/852/908), and root bypasses ownership. So local parallel sessions are indistinguishable — they share the one active tab. The clientId / own-only path only engages for clients that connect with a scoped token, which today means the remote-agent pairing flow — not bare local invocations.

Proposed design (small, reuses what's there)

Three pieces:

  1. Auto-mint a per-session own-only sub-token, clientId = <session>, keyed on the session id gstack already tracks (~/.gstack/sessions/$PPID, created in the skill preamble). Root mints it via the existing /pair machinery; cache it (e.g. ~/.gstack/sessions/<id>.token).
  2. Let the local CLI carry a per-session token via an env var (e.g. BROWSE_TOKEN / BROWSE_CLIENT_ID) instead of always using the root state.token. Default stays root when unset → fully backward compatible.
  3. Auto-open / claim that session's tab on first use; own-only then isolates it. A session's commands route to its own tab; snapshot/goto/etc. never touch another session's.

Considerations

  • Shared profile is fine — tabs in one Chromium share cookies/login, which is usually desired (same app, same auth). No second profile needed (and Chromium's SingletonLock precludes one anyway).
  • One daemon — per-git-root state already resolves to the single running daemon; sessions just present different tokens to it.
  • Cleanup — reuse the existing session-marker TTL (~/.gstack/sessions is already swept at 120m) to expire stale per-session tokens/tabs.
  • Backward compatible — no env set → root behaviour, unchanged.

Why it's worth it

Parallel multi-session agent work is increasingly common (worktree fan-out, orchestrators). The foundation is already shipped; this is mostly wiring (auto-mint + env-carried identity + auto-tab), not new architecture.

Happy to PR this if the approach sounds right — would want a quick maintainer steer on the env name (BROWSE_TOKEN vs a dedicated BROWSE_SESSION) and whether auto-mint should be opt-in.

charitarora avatar Jun 10 '26 19:06 charitarora

Concrete use case + clarified ask (from real multi-session usage)

Use case. I routinely run 4–6 parallel agent sessions via git worktrees — e.g. several claude sessions each reviewing a different screen of the same app (booking detail, mobile/responsive, an analytics screen), plus a feature session and a coordinator. Each needs to drive the headed browser (the app is auth-gated; I log in once, all sessions share the one profile — which is fine and desirable). Today they all authenticate to the daemon as root, so they share the single active tab and clobber each other — a goto/snapshot/click in one session stomps whatever another was doing. In practice that forces single-driver: only one session can use the browser at a time, which serialises work that is otherwise fully parallel.

The ask. A supported way for each local session to present its own scoped (own-only) token so it gets its own isolated tab in the shared browser — i.e. make per-session identity first-class for local sessions, the way the pairing flow already does for remote / --local agents.

What I verified already works today (but only as a fragile hack):

  • The daemon validates any bearer on POST /command and applies own-only tab isolation for non-root tokens (server.ts ~L1044); newtab is exempt, so each client opens its own tab.
  • A regular $B command sends Authorization: Bearer ${state.token} (cli.ts ~L542), and state.token comes from the state file — which is selectable via BROWSE_STATE_FILE (config.ts ~L60).
  • So you can manually: keep one root "owner" session alive (to own the daemon), mint a scoped token per session (pair --client <name>), write a per-session state file {port, token:<scoped>, mode}, and export BROWSE_STATE_FILE for that session → it then drives its own tab.

Why the hack isn't viable for routine use:

  • The daemon must be kept alive by the root owner (a scoped token can't start/manage the daemon).
  • browse rewrites the state file on some operations and can clobber the injected token.
  • It's unsupported → breaks on the next update, and you're hand-managing tokens + tabs.

So the foundation is entirely present (scoped tokens, own-only, tabOwnership, env-selectable state, any-bearer /command). What's missing is the wiring.

Restated proposed design (small, builds directly on the above):

  1. Auto-mint a per-session own-only sub-token, keyed on the session id gstack already tracks (~/.gstack/sessions/$PPID); cache it.
  2. CLI carries it via an env var (e.g. BROWSE_TOKEN / BROWSE_SESSION) — default stays root, so it's fully backward compatible.
  3. Auto-open/claim that session's tab on first use; own-only then isolates it.
  4. Reuse the existing session-marker TTL (~/.gstack/sessions sweep) to expire stale per-session tokens/tabs.

Net effect: N parallel local agent sessions each drive their own tab in the one shared (single-profile) browser, with no manual token plumbing. Happy to PR.

charitarora avatar Jun 11 '26 22:06 charitarora

This is a browser runtime session-isolation contract.

A persistent browser daemon is useful, but multiple local agent sessions should not accidentally share tabs, cookies, or browser state unless explicitly intended.

A standard AISP-style contract could model session-to-browser isolation:

[
  {
    "role": "system",
    "content": {
      "protocol": "AISP V1.0.0",
      "axiom_0": "Human_Sovereignty_and_Wellbeing",
      "id": "gstack_browser_session_isolation_aisp",
      "name": "gstack Browser Session Isolation Contract",
      "version": "1.0.0",
      "license": "MIT",
      "summary": "Machine-checkable contract for isolating browser tabs and state across local agent sessions.",
      "flow_format": "mermaid",
      "loading_mode": "node",
      "tools": ["browser", "filesystem"],
      "params": {
        "agent_session_id": "string",
        "browser_state_path": "string"
      },
      "system_prompt": ""
    }
  },
  {
    "role": "user",
    "content": {
      "instruction": "STRICTLY OBEY aisp_contract; its non_negotiable rules are inviolable; then RUN aisop.main",
      "user_input": "{user_input}",
      "aisp_contract": {
        "profile": "aisp.skill.v1",
        "invocation": {
          "mode": "browser_runtime_policy",
          "when_to_use": [
            "before opening browser tabs from an agent session",
            "when multiple local agent sessions share a browser daemon",
            "when session state or tabs may cross-contaminate"
          ],
          "when_not_to_use": [
            "single isolated browser session",
            "explicit shared browser workspace chosen by user"
          ]
        },
        "non_negotiable": [
          {
            "rule": "Browser tabs opened by one agent session must be associated with that session id.",
            "enforced_by": "bind.step2:sys.assert"
          },
          {
            "rule": "A session must not operate on another session's tabs unless explicitly attached.",
            "enforced_by": "gate.step2:sys.assert"
          },
          {
            "rule": "Shared browser state must be opt-in and traceable.",
            "enforced_by": "trace.step2:sys.assert"
          }
        ],
        "discovery": {
          "category": "browser_runtime",
          "tags": ["gstack", "browser", "tabs", "session-isolation", "daemon", "aisp"]
        },
        "risk_level": "high",
        "resources": [
          {
            "id": "browser_state",
            "path": "{browser_state_path}",
            "kind": "runtime_state",
            "mode": "read_only",
            "when": "Read before tab/session binding.",
            "scope": "skill"
          }
        ]
      },
      "aisop": {
        "main": "graph TD\n    bind[Bind session to browser context] --> gate[Gate tab access]\n    gate --> operate[Operate on allowed tabs]\n    operate --> trace[Record browser session trace]\n    trace --> end_node((End))"
      },
      "functions": {
        "bind": {
          "step1": "Associate new tabs/windows with agent_session_id.",
          "step2": "sys.assert('tabs are bound to session id', 'Browser tabs must be session-bound')",
          "output_mapping": "browser_session_binding"
        },
        "gate": {
          "step1": "Check whether requested tab belongs to agent_session_id or is explicitly shared.",
          "step2": "sys.assert('session only accesses owned or shared tabs', 'Cross-session tab access denied')",
          "output_mapping": "tab_access_decision"
        },
        "operate": {
          "step1": "Perform browser operation only on allowed tabs.",
          "output_mapping": "browser_operation_result"
        },
        "trace": {
          "step1": "Record session id, tab id, action, ownership, and shared/isolated mode.",
          "step2": "sys.assert('shared state decisions are traceable', 'Browser session sharing must be traceable')",
          "output_mapping": "browser_session_trace"
        },
        "end_node": {
          "step1": "Return browser_session_trace."
        }
      }
    }
  }
]

The key invariant:

persistent daemon does not mean unscoped shared browser state.

optimization2026 avatar Jun 30 '26 06:06 optimization2026

@charitarora Scoped tokens and tab ownership are available, but generic local-session identity and session-to-tab binding remain unimplemented.

time-attack avatar Jul 15 '26 22:07 time-attack

Thanks @charitarora for the idea. In the Oct 11 triage we grouped the open feature requests by theme so related asks get built together instead of one at a time. This one is part of the Browser and mobile QA theme in TODOS.md (https://github.com/garrytan/gstack/blob/50d020ad9/TODOS.md#L54-L69). Closing it here so the open list stays actionable; it isn't rejected, and the theme credits every linked reporter when it's picked up.

capy-ai[bot] avatar Oct 11 '26 15:10 capy-ai[bot]

Reopened under the parked label: this is tracked in the Browser and mobile QA theme in TODOS.md (https://github.com/garrytan/gstack/blob/main/TODOS.md#p3-feature-themes-from-the-wave-9-triage-filed-2026-10-11), and what fixes it is the next browser-engine wave, which takes the theme as a whole. Closed-but-tracked read as closed, so parked issues now stay open until they ship, are duplicates, or are declined (https://github.com/garrytan/gstack/blob/main/docs/triage.md).

capy-ai[bot] avatar Oct 25 '26 23:10 capy-ai[bot]

Thanks for the idea and the follow-ups. We're closing parked feature requests instead of keeping them open, and per-session tab isolation isn't scheduled. Closing.

capy-ai[bot] avatar Nov 16 '26 03:11 capy-ai[bot]