Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions browse/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,7 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
const newPid = spawnTerminalAgent({
stateFile: config.stateFile,
serverPort: newState.port,
ownerPid: newState.pid,
cwd: config.projectDir,
});
if (newPid) {
Expand Down Expand Up @@ -1222,6 +1223,7 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
spawnTerminalAgent({
stateFile: config.stateFile,
serverPort: respawned.port,
ownerPid: respawned.pid,
cwd: config.projectDir,
});
} catch (err: any) {
Expand Down
1 change: 1 addition & 0 deletions browse/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1551,6 +1551,7 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
const pid = spawnTerminalAgent({
stateFile: cfg.config.stateFile,
serverPort: cfg.browsePort,
ownerPid: process.pid,
cwd: cfg.config.projectDir,
});
if (pid) {
Expand Down
3 changes: 3 additions & 0 deletions browse/src/terminal-agent-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export function resolveTerminalAgentScript(searchHints: { metaDir?: string; exec
export function spawnTerminalAgent(opts: {
stateFile: string;
serverPort: number;
/** PID of the browse server that owns this agent. */
ownerPid: number;
cwd?: string;
/** Optional extra env vars to add to the agent's process env. */
extraEnv?: Record<string, string>;
Expand All @@ -74,6 +76,7 @@ export function spawnTerminalAgent(opts: {
...process.env,
BROWSE_STATE_FILE: opts.stateFile,
BROWSE_SERVER_PORT: String(opts.serverPort),
BROWSE_OWNER_PID: String(opts.ownerPid),
...(opts.extraEnv || {}),
},
stdio: ['ignore', 'ignore', 'ignore'],
Expand Down
25 changes: 25 additions & 0 deletions browse/src/terminal-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ import { writeAgentRecord, clearAgentRecord } from './terminal-agent-control';
const STATE_FILE = process.env.BROWSE_STATE_FILE || path.join(process.env.HOME || '/tmp', '.gstack', 'browse.json');
const PORT_FILE = path.join(path.dirname(STATE_FILE), 'terminal-port');
const BROWSE_SERVER_PORT = parseInt(process.env.BROWSE_SERVER_PORT || '0', 10);
const BROWSE_OWNER_PID = parseInt(process.env.BROWSE_OWNER_PID || '0', 10);
const OWNER_WATCHDOG_MS = parseInt(
process.env.GSTACK_TERMINAL_OWNER_WATCHDOG_MS || '15000',
10,
);
const EXTENSION_ID = process.env.BROWSE_EXTENSION_ID || ''; // optional: tighten Origin check
const INTERNAL_TOKEN = crypto.randomBytes(32).toString('base64url'); // shared with parent server via env at spawn
/**
Expand Down Expand Up @@ -987,13 +992,33 @@ function main() {
console.log(`[terminal-agent] listening on 127.0.0.1:${port} pid=${process.pid} gen=${CURRENT_GEN}`);

// Cleanup port file + agent record on exit.
let cleaningUp = false;
const cleanup = () => {
if (cleaningUp) return;
cleaningUp = true;
safeUnlink(PORT_FILE);
safeUnlink(INTERNAL_TOKEN_FILE);
clearAgentRecord(dir);
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);

// The terminal agent is intentionally detached so it survives the short-lived
// CLI launcher, but its real owner is the persistent browse server. If that
// server crashes or is killed before running normal shutdown, the agent would
// otherwise be adopted by PID 1 and live forever. Poll the server PID and use
// the same cleanup path as an intentional shutdown when it disappears.
if (BROWSE_OWNER_PID > 0) {
const ownerWatchdog = setInterval(() => {
try {
process.kill(BROWSE_OWNER_PID, 0);
} catch {
cleanup();
}
}, OWNER_WATCHDOG_MS);
(ownerWatchdog as any)?.unref?.();
}
}

// Export the internal token so cli.ts can pass the SAME value to the parent
Expand Down
68 changes: 68 additions & 0 deletions browse/test/terminal-agent-owner-watchdog.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

const AGENT_SCRIPT = path.join(import.meta.dir, '../src/terminal-agent.ts');
const spawned: any[] = [];
const tempDirs: string[] = [];

function isAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}

async function waitFor(predicate: () => boolean, timeoutMs = 5_000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (predicate()) return true;
await Bun.sleep(25);
}
return predicate();
}

afterEach(() => {
for (const proc of spawned.splice(0)) {
try { proc.kill?.('SIGKILL'); } catch {}
}
for (const dir of tempDirs.splice(0)) {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
}
});

describe('terminal-agent owner lifecycle', () => {
test('exits after its owning browse server process exits', async () => {
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-term-owner-'));
tempDirs.push(stateDir);
const stateFile = path.join(stateDir, 'browse.json');
fs.writeFileSync(stateFile, JSON.stringify({ token: 'test-token' }));

const owner = Bun.spawn(['sleep', '30'], { stdio: ['ignore', 'ignore', 'ignore'] });
spawned.push(owner);
const agent = Bun.spawn(['bun', 'run', AGENT_SCRIPT], {
env: {
...process.env,
BROWSE_STATE_FILE: stateFile,
BROWSE_SERVER_PORT: '0',
BROWSE_OWNER_PID: String(owner.pid),
GSTACK_TERMINAL_OWNER_WATCHDOG_MS: '25',
},
stdio: ['ignore', 'ignore', 'ignore'],
});
spawned.push(agent);

expect(await waitFor(() => fs.existsSync(path.join(stateDir, 'terminal-agent-pid')))).toBe(true);
expect(isAlive(agent.pid)).toBe(true);

owner.kill('SIGTERM');
await owner.exited;

expect(await waitFor(() => !isAlive(agent.pid))).toBe(true);
expect(fs.existsSync(path.join(stateDir, 'terminal-agent-pid'))).toBe(false);
expect(fs.existsSync(path.join(stateDir, 'terminal-port'))).toBe(false);
});
});