Skip to content

Commit b03cd1a

Browse files
garrytanclaude
andauthored
v1.42.1.0 feat: gate terminal-agent teardown on ServerConfig.ownsTerminalAgent (unblocks gbrowser embedder) (garrytan#1615)
* feat: gate terminal-agent teardown on ServerConfig.ownsTerminalAgent Adds ownsTerminalAgent?: boolean to ServerConfig (default true). Wraps the three shutdown side effects (pkill -f terminal-agent\.ts + 2 safeUnlinkQuiet calls for terminal-port and terminal-internal-token) inside a single if (ownsTerminalAgent) block. Embedders (gbrowser phoenix overlay) pass false to keep their own PTY lifecycle intact across gstack's teardown. CLI start() call site passes ownsTerminalAgent: true explicitly; static-grep test in the new test file catches a refactor that drops it. Strict opt-out: only explicit false flips the gate (cfg.ownsTerminalAgent === false ? false : true). Defends against JS callers passing truthy non-bool values. Adds __resetShuttingDown test-only export mirroring __resetRegistry. The module-scoped isShuttingDown latch otherwise silently no-ops a second shutdown() in the same process. Drops dead try/catch wrappers around safeUnlinkQuiet inside the new gate — safeUnlinkQuiet already swallows all errors internally. New test file (4 cases) stubs both process.exit AND child_process.spawnSync so a real pkill -f terminal-agent\.ts never fires on the developer machine. beforeAll/afterAll save and restore real-daemon file contents in the state dir so the test cannot clobber a running gstack session. * chore: file followup TODOs (identity-based pkill, cfg.config composition gap, ownership-object trigger) Three P3 followups surfaced by /autoplan + /plan-eng-review while reviewing the ownsTerminalAgent gate: - Identity-based terminal-agent kill: pkill -f terminal-agent\.ts is a latent CLI footgun (regex match kills sibling gstack sessions, editor processes, etc.). Replace with PID-tracked process.kill at both cli.ts:1047 and server.ts:1281. - shutdown() reads module-level config, not cfg.config (pre-existing composition gap). Same gap applies to cleanSingletonLocks(resolveChromiumProfile()) at server.ts:1298 (should be cfg.chromiumProfile). Both are followup work for the embedder-composition story. - 4th caller-owned teardown gate trigger: today ServerConfig has 3 (xvfb?, proxyBridge?, ownsTerminalAgent). If a 4th appears, collapse to cfg.callerOwns?: Set<...> ownership object. * chore: bump version and changelog (v1.42.1.0) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: note ServerConfig.ownsTerminalAgent in CLAUDE.md sidebar block Adds a one-paragraph reference for the v1.42.1.0 embedder teardown gate right after the Sidebar architecture block. Covers default semantics, when embedders must pass `false`, polarity inversion vs xvfb?/proxyBridge?, and the static-grep CI test that pins the CLI call site. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 7ca04d8 commit b03cd1a

7 files changed

Lines changed: 407 additions & 11 deletions

File tree

CHANGELOG.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,47 @@
11
# Changelog
22

3+
## [1.42.1.0] - 2026-05-19
4+
5+
## **Embedder PTY teardown stops clobbering — gbrowser's phoenix overlay survives every shutdown.**
6+
## **`buildFetchHandler` gains an explicit ownership flag for terminal-agent files; CLI behavior preserved bit-for-bit.**
7+
8+
`browse/src/server.ts` factory shutdown unconditionally killed the terminal-agent and unlinked its discovery files on every teardown. Correct for gstack's CLI path, wrong for embedders that pass their own pre-launched `BrowserManager` and run their own PTY server. Their `terminal-port` file got clobbered every cycle, `/health.terminalPort` reported null until the overlay rewrote it. gbrowser's phoenix overlay shipped a client-side mitigation; with this PR landed, that mitigation becomes redundant. The new `ServerConfig.ownsTerminalAgent?: boolean` (default `true`) gates the three teardown side effects together: `pkill -f terminal-agent\.ts`, `safeUnlinkQuiet(<stateDir>/terminal-port)`, `safeUnlinkQuiet(<stateDir>/terminal-internal-token)`. Embedders pass `false` to keep their PTY lifecycle intact.
9+
10+
### The numbers that matter
11+
12+
Source: `bun test browse/test/server-embedder-terminal-port.test.ts browse/test/server-factory.test.ts` — 32 tests, all green. Static-grep test pins the CLI `start()` call site so a refactor that drops the explicit `: true` fails CI.
13+
14+
| Surface | Before | After |
15+
|---|---|---|
16+
| gbrowser phoenix overlay teardown | `terminal-port` unlinked every cycle; `/health.terminalPort: null` until overlay rewrites; client-side mitigation required | Pass `ownsTerminalAgent: false` — files untouched, embedder owns full lifecycle |
17+
| gstack CLI shutdown | `pkill` + 2 unlinks fire | Identical (default `true`, explicit `: true` at `start()` call site documents intent + static-grep test) |
18+
| Test runner safety | n/a | `spawnSync` stubbed in all 4 cases so real `pkill -f terminal-agent\.ts` cannot run on developer machine |
19+
| Multi-case shutdown tests | Module-scoped `isShuttingDown` silently no-ops 2nd shutdown | New `__resetShuttingDown` test-only export mirrors `__resetRegistry` precedent |
20+
| Real-daemon collision risk | Test mutates `~/.gstack/.../terminal-port` — would clobber a running developer daemon | `beforeAll` saves real contents, `afterAll` restores; tests safe to run while gstack is alive |
21+
22+
### What this means for builders
23+
24+
If you embed gstack's `buildFetchHandler` and run your own PTY server, pass `ownsTerminalAgent: false` in your cfg and your `terminal-port`/`terminal-internal-token` files survive every gstack teardown — no more client-side rewrite mitigation. If you use the gstack CLI, nothing changes. The flag is the third caller-owned teardown gate in `ServerConfig` (joining `xvfb?` and `proxyBridge?`); if a fourth appears we collapse to an ownership object.
25+
26+
### Itemized changes
27+
28+
**Added**
29+
- `ServerConfig.ownsTerminalAgent?: boolean` in `browse/src/server.ts` (default `true`). JSDoc enumerates all three gated side effects, the pkill regex breadth caveat, and the polarity inversion vs `xvfb?`/`proxyBridge?` (which gate by *presence* of caller-owned handles)
30+
- `__resetShuttingDown()` test-only export in `browse/src/server.ts`, mirroring `__resetRegistry` precedent in `token-registry.ts`. JSDoc warns about production-import footgun
31+
- `browse/test/server-embedder-terminal-port.test.ts` (4 tests): `ownsTerminalAgent: false` preserves files + skips pkill, explicit `true` deletes + invokes pkill, unset defaults to `true`, static-grep test asserts CLI call site documents intent. Tests save+restore real-daemon `terminal-port`/`terminal-internal-token` contents in `beforeAll`/`afterAll` so a running developer session is never clobbered
32+
33+
**Changed**
34+
- `buildFetchHandler` JSDoc references the new field alongside `beforeRoute` and `browserManager` in the embedder-composition paragraph
35+
- CLI `start()` call site explicitly passes `ownsTerminalAgent: true` with a comment pointing at `cli.ts:1037-1063`. Documents intent + caught by the new static-grep test if a refactor drops it
36+
- Strict opt-out semantics: `cfg.ownsTerminalAgent === false ? false : true` — only explicit `false` flips the gate. Defends against JS callers bypassing TS and passing truthy non-bool values
37+
38+
**Removed**
39+
- Dead `try { safeUnlinkQuiet(...) } catch {}` wrappers inside the new gate. `safeUnlinkQuiet` already swallows all errors internally; the outer try/catch was slop-scan flagged dead code
40+
41+
**For contributors**
42+
- Followup TODOs filed in `TODOS.md`: identity-based terminal-agent kill (replace `pkill -f` with PID-tracked `process.kill`), the pre-existing `shutdown()` reads module-level `config` (composition gap with parallel `chromiumProfile` gap), and the 4th-gate-collapse-to-ownership-object trigger
43+
- Plan + reviews under `~/.gstack/projects/garrytan-gstack/`: autoplan CEO + Eng dual voices (Codex + Claude subagent), interactive `/plan-eng-review` (D3: drop dead try/catch), `/ship` adversarial pass (strict-bool + JSDoc hardening + test save/restore)
44+
345
## [1.42.0.0] - 2026-05-19
446

547
## **Daegu wave: 23 community-filed bugs land as one bisect-clean PR with the documented sidebar security stack finally enforced.**

CLAUDE.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,20 @@ Activity / Refs / Inspector as debug overlays behind the footer's
236236
flow, dual-token model, and threat-model boundary — silent failures
237237
here usually trace to not understanding the cross-component flow.
238238

239+
**Embedder terminal-agent ownership** (v1.42.1.0+). `buildFetchHandler`
240+
in `browse/src/server.ts` accepts `ServerConfig.ownsTerminalAgent?:
241+
boolean` (default `true`). When `true`, factory shutdown runs the full
242+
teardown: `pkill -f terminal-agent\.ts` plus `safeUnlinkQuiet` on
243+
`<stateDir>/terminal-port` and `<stateDir>/terminal-internal-token`.
244+
Embedders (e.g. the gbrowser phoenix overlay) that pre-launch their
245+
own PTY server must pass `false` so their discovery files survive
246+
gstack teardown cycles. The flag is the third caller-owned teardown
247+
gate in `ServerConfig` (alongside `xvfb?` and `proxyBridge?`); polarity
248+
is inverted (explicit bool vs presence) and documented in the field's
249+
JSDoc. CLI `start()` always passes `true` explicitly — the static-grep
250+
test in `browse/test/server-embedder-terminal-port.test.ts` fails CI
251+
if a refactor drops it.
252+
239253
**WebSocket auth uses Sec-WebSocket-Protocol, not cookies.** Browsers
240254
can't set `Authorization` on a WebSocket upgrade, but they CAN set
241255
`Sec-WebSocket-Protocol` via `new WebSocket(url, [token])`. The agent

TODOS.md

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,99 @@
11
# TODOS
22

3+
## browse server: terminal-agent teardown follow-ups (filed v1.41 via /plan-eng-review)
4+
5+
### P3: Identity-based terminal-agent kill (replace pkill regex with PID)
6+
7+
**What:** Record the spawned terminal-agent PID at `browse/src/cli.ts:1057` and
8+
replace `pkill -f terminal-agent\.ts` at both `cli.ts:1047` and
9+
`server.ts:1281` (now inside the `if (ownsTerminalAgent)` gate) with
10+
`process.kill(pid, signal)` against the recorded PID.
11+
12+
**Why:** `pkill -f terminal-agent\.ts` matches by command-line regex, so today
13+
it can kill ANY process whose argv contains `terminal-agent.ts` — sibling
14+
gstack sessions, editor processes that have the file open, a second gstack
15+
run on the same host. Latent footgun for the CLI path, not just embedders.
16+
17+
**Pros:** Removes a real cross-session foot-cannon. PID-based kill is the
18+
correct identity primitive. Lets us tighten `pkill -f`'s broad-match warning
19+
in the new `ownsTerminalAgent` JSDoc to "historical" rather than "current".
20+
21+
**Cons:** Requires threading the PID through the CLI-to-server state path
22+
(currently the parent server reads `terminal-port` to discover the agent; it
23+
would also need `terminal-agent-pid`). Touches `cli.ts`, `server.ts`, and
24+
`terminal-agent.ts` together — bigger surface than the v1.41 fix.
25+
26+
**Context:** Surfaced by both Codex and Claude subagent during /autoplan
27+
review of the `ownsTerminalAgent` gate. Currently documented as out-of-scope
28+
in `browse/src/server.ts` JSDoc for `ServerConfig.ownsTerminalAgent`. The
29+
embedder fix (ownsTerminalAgent: false) means embedders don't hit this; CLI
30+
users still do.
31+
32+
**Depends on:** None.
33+
34+
---
35+
36+
### P3: shutdown() reads module-level `config`, not `cfg.config` (composition gap)
37+
38+
**What:** `browse/src/server.ts:shutdown()` reads `path.dirname(config.stateFile)`
39+
where `config` is the module-level value resolved at import time, not the
40+
`cfg.config` passed into `buildFetchHandler`. Same gap applies to
41+
`cleanSingletonLocks(resolveChromiumProfile())` at server.ts:1298 — should
42+
read `cfg.chromiumProfile`.
43+
44+
**Why:** Embedders today happen to share state-dir resolution with the CLI
45+
(both go through `resolveConfig()` against the same env), so this doesn't
46+
bite. But if an embedder ever passes a divergent `cfg.config` (e.g., a test
47+
harness pointing at a temp dir), shutdown will operate on the wrong paths.
48+
The `ownsTerminalAgent` flag exposes the problem without fixing it.
49+
50+
**Pros:** Closes the embedder-composition story properly. Pairs with
51+
`cfg.chromiumProfile` to give a single coherent "this factory teardown
52+
respects cfg" contract.
53+
54+
**Cons:** Pre-existing — not a regression. Two call sites today (1285 for
55+
terminal files, 1298 for chromium locks). Threading `cfg.config` and
56+
`cfg.chromiumProfile` into the right closures is straightforward but
57+
broader than the v1.41 fix.
58+
59+
**Context:** Flagged by both Codex and Claude subagent in the /plan-eng-review
60+
dual voices. Documented as out-of-scope in the v1.41 plan; same shape as the
61+
`chromiumProfile` PR-body note to the gbrowser team.
62+
63+
**Depends on:** None.
64+
65+
---
66+
67+
### P3: Ownership-object refactor if a 4th caller-owned teardown gate appears
68+
69+
**What:** Today `ServerConfig` has three caller-owned teardown gates:
70+
`xvfb?` (presence ⇒ don't close), `proxyBridge?` (same), and now
71+
`ownsTerminalAgent` (explicit boolean). If a 4th gate appears, collapse to
72+
`cfg.callerOwns?: Set<'terminalAgent' | 'xvfb' | 'proxyBridge' | ...>` or
73+
similar.
74+
75+
**Why:** Three independent flags is below the refactor threshold — each
76+
field has clear, distinct semantics and the JSDoc voice is consistent. A
77+
fourth tips the cost balance: the per-field surface gets noisy, and
78+
"what does this factory own?" becomes a question you have to ask of three
79+
or four scattered fields instead of one explicit set.
80+
81+
**Pros:** Single source of truth for "what gstack tears down". Trivial
82+
extension surface for future caller-owned resources. Easier to assert in
83+
tests ("the set should contain X, not Y").
84+
85+
**Cons:** Premature today. The polarity-inversion note in the
86+
`ownsTerminalAgent` JSDoc only hurts a little — it's one anomaly, not a
87+
pattern. Refactoring now to an ownership object would touch every embedder.
88+
89+
**Context:** Recommended by Claude subagent during /plan-ceo-review dual
90+
voice (autoplan). Trigger: a 4th caller-owned teardown gate in this same
91+
`ServerConfig` shape.
92+
93+
**Depends on:** A 4th gate to motivate the refactor.
94+
95+
---
96+
397
## /sync-gbrain memory stage perf follow-up
498

599
### P2: Investigate `gbrain import` perf on large staging dirs

VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.42.0.0
1+
1.42.1.0

browse/src/server.ts

Lines changed: 66 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,35 @@ export interface ServerConfig {
205205
* dispatch; returning null falls through.
206206
*/
207207
beforeRoute?: (req: Request, surface: Surface, auth: TokenInfo | null) => Promise<Response | null>;
208+
/**
209+
* Whether gstack owns the lifecycle of the terminal-agent process and its
210+
* discovery files (`<stateDir>/terminal-port`, `<stateDir>/terminal-internal-token`).
211+
*
212+
* When true (default), shutdown() runs three side effects:
213+
* 1. `pkill -f terminal-agent\.ts` — regex-broad, matches ANY process whose
214+
* command line contains `terminal-agent.ts` on this host (including
215+
* sibling gstack sessions). Pre-existing CLI behavior, not introduced by
216+
* this flag. Identity-based PID kill is a separate followup (see TODOS).
217+
* 2. `safeUnlinkQuiet(<stateDir>/terminal-port)`
218+
* 3. `safeUnlinkQuiet(<stateDir>/terminal-internal-token)`
219+
*
220+
* This is correct for gstack's CLI path, which spawns `terminal-agent.ts` as
221+
* the producer of those files (see cli.ts:1037-1063).
222+
*
223+
* Embedders (gbrowser phoenix overlay, future hosts) that run their own PTY
224+
* server and write those files themselves should pass `false`. When `false`,
225+
* the embedder owns BOTH the agent process AND both discovery files —
226+
* terminal-agent.ts's own SIGTERM cleanup only removes `terminal-port`
227+
* (see terminal-agent.ts:558), so the internal-token file is the embedder's
228+
* full responsibility.
229+
*
230+
* Polarity note: this differs from `xvfb?` and `proxyBridge?`, which gate by
231+
* the *presence* of a caller-owned handle (presence ⇒ don't close). This
232+
* field gates by an explicit boolean because there is no handle object —
233+
* the terminal-agent is started elsewhere (cli.ts), and shutdown's only
234+
* reference is the regex-based pkill + the file paths.
235+
*/
236+
ownsTerminalAgent?: boolean;
208237
}
209238

210239
/**
@@ -1229,8 +1258,11 @@ if (import.meta.main) {
12291258
/**
12301259
* Build a request handler set for the browse daemon. Embedders (gbrowser
12311260
* phoenix overlay) call this directly with their own cfg to compose overlay
1232-
* routes via cfg.beforeRoute. The CLI path calls it through start() with
1233-
* env-derived defaults — externally-observable behavior is identical.
1261+
* routes via cfg.beforeRoute, pass a pre-launched cfg.browserManager, and
1262+
* opt out of terminal-agent teardown via cfg.ownsTerminalAgent (default
1263+
* true, set to false when the embedder runs its own PTY server). The CLI
1264+
* path calls this through start() with env-derived defaults and explicit
1265+
* cfg.ownsTerminalAgent: true — externally-observable behavior is identical.
12341266
*
12351267
* Auth state lives ENTIRELY inside the factory closure: cfg.authToken is the
12361268
* single source of truth for the bearer secret, factory-scoped validateAuth
@@ -1260,6 +1292,11 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
12601292
initRegistry(cfg.authToken);
12611293

12621294
const { authToken, browserManager: cfgBrowserManager, startTime, beforeRoute, browsePort } = cfg;
1295+
// Strict opt-out: only explicit `false` flips the gate. Any other value
1296+
// (undefined, truthy non-bool from a JS caller bypassing TS, etc.) defaults
1297+
// to gstack-owns. Matches the "default-true preserves CLI bit-for-bit"
1298+
// premise even under malformed cfg.
1299+
const ownsTerminalAgent = cfg.ownsTerminalAgent === false ? false : true;
12631300

12641301
// Factory-scoped validateAuth. Closes over cfg.authToken so every internal
12651302
// auth check sees the same token the routes receive. Module-level
@@ -1277,14 +1314,16 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
12771314
isShuttingDown = true;
12781315

12791316
console.log('[browse] Shutting down...');
1280-
try {
1281-
const { spawnSync } = require('child_process');
1282-
spawnSync('pkill', ['-f', 'terminal-agent\\.ts'], { stdio: 'ignore', timeout: 3000 });
1283-
} catch (err: any) {
1284-
console.warn('[browse] Failed to kill terminal-agent:', err.message);
1317+
if (ownsTerminalAgent) {
1318+
try {
1319+
const { spawnSync } = require('child_process');
1320+
spawnSync('pkill', ['-f', 'terminal-agent\\.ts'], { stdio: 'ignore', timeout: 3000 });
1321+
} catch (err: any) {
1322+
console.warn('[browse] Failed to kill terminal-agent:', err.message);
1323+
}
1324+
safeUnlinkQuiet(path.join(path.dirname(config.stateFile), 'terminal-port'));
1325+
safeUnlinkQuiet(path.join(path.dirname(config.stateFile), 'terminal-internal-token'));
12851326
}
1286-
try { safeUnlinkQuiet(path.join(path.dirname(config.stateFile), 'terminal-port')); } catch {}
1287-
try { safeUnlinkQuiet(path.join(path.dirname(config.stateFile), 'terminal-internal-token')); } catch {}
12881327
try { detachSession(); } catch (err: any) {
12891328
console.warn('[browse] Failed to detach CDP session:', err.message);
12901329
}
@@ -2541,6 +2580,7 @@ export async function start() {
25412580
xvfb,
25422581
proxyBridge,
25432582
startTime,
2583+
ownsTerminalAgent: true, // CLI spawns terminal-agent.ts itself (see cli.ts:1037-1063)
25442584
});
25452585

25462586
const server = Bun.serve({
@@ -2686,6 +2726,23 @@ export async function start() {
26862726
}
26872727
}
26882728

2729+
/**
2730+
* Test-only. Resets the module-level shutdown latch so a second test case
2731+
* can exercise shutdown() in the same process. Mirrors __resetRegistry in
2732+
* token-registry.ts. shutdown() short-circuits when isShuttingDown is true
2733+
* (see line near the start of shutdown), so without this, tests that call
2734+
* shutdown() more than once silently no-op after the first call.
2735+
*
2736+
* DO NOT call from production code. Defeats the shutdown re-entry guard,
2737+
* which can race process.exit with cfgBrowserManager.close() and the pkill /
2738+
* safeUnlinkQuiet side effects. The `__` prefix is the convention; nothing
2739+
* enforces it. If you find yourself reaching for this outside a test file,
2740+
* the right fix is to make isShuttingDown factory-scoped instead.
2741+
*/
2742+
export function __resetShuttingDown(): void {
2743+
isShuttingDown = false;
2744+
}
2745+
26892746
// Auto-kickoff only when this module is the entry point. Embedders
26902747
// (gbrowser phoenix overlay) import { start, buildFetchHandler, ... }
26912748
// without triggering the listener-binding side effects.

0 commit comments

Comments
 (0)