Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

wip: squash for rebase

[._.]/ Adam Eivy27b08688d042
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index 91a6af8c7e..fa84f4e073 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -580,7 +580,12 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
<strong>Args Separator</strong> (e.g. <code>--</code>) is inserted before the harness's own
arguments when the bootstrap CLI needs its flags kept apart from the harness's.
Bootstrap Args are stored and shown in clear text (agent records, run transcripts, the shell
- line typed for a TUI session) — put a secret in Environment Variables marked secret, never here.
+ line typed for a TUI session) — put a secret in Environment Variables marked secret, never here.{' '}
+ <strong>Your bootstrap CLI should <code>exec</code> the harness, or forward the signals it
+ receives to it.</strong> Stop, timeout and cancel signal the wrapped spawn's whole process
+ group, so a wrapper that forks is still taken down with its harness — but a wrapper that
+ re-parents the harness out of that group, or traps signals without passing them on, can leave
+ it running after PortOS has finished the run.
</p>
{/* The CLI/TUI backends that can authenticate: the vLLM compose
diff --git a/server/lib/README.md b/server/lib/README.md
index 64dd65c2e3..64588caeb2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -261,6 +261,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `release-flow`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. |
| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
| `credentialBootstrap.js` | Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static `apiKey` PortOS stores — a `provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? }` record. `hasCredentialBootstrap(provider)` and `applyCredentialBootstrap(provider, command, args)` (pure) return the command+args PortOS should actually spawn: `<command> <args...> <harnessId ?? command> [<argsSeparator>] <args...>` — the bootstrap CLI in front of the harness invocation, naming the harness as `harnessId` when the bootstrap CLI uses its own identifier rather than the binary name, and inserting `argsSeparator` (e.g. `--`) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. `resolveCliSpawn(provider, command, args, childEnv)` composes that with Windows shim resolution (`bufferedSpawn.js`) for the three headless spawn sites that repeated the same sequence (`runner.js`, `cliProviderRun.js`, `visionCli.js`) — the argv analog of why `cliChildEnv.js`'s `buildCliChildEnv` exists. Every call site keeps resolving `provider.command`/`args` unchanged for vendor detection, prompt-delivery convention, and the TUI's own ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call — plus anything that observes the launching shell or PATH (missing-binary detection, readiness probes), which must read the SPAWNED pair. A public-review posture is never wrapped (the enforced recipe is the sandbox); the skip lives in the helper, keyed on `safetyProfile`. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. |
+| `credentialBootstrap.js` | Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static `apiKey` PortOS stores — a `provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? }` record. `hasCredentialBootstrap(provider)` and `applyCredentialBootstrap(provider, command, args)` (pure) return the command+args PortOS should actually spawn: `<command> <args...> <harnessId ?? command> [<argsSeparator>] <args...>` — the bootstrap CLI in front of the harness invocation, naming the harness as `harnessId` when the bootstrap CLI uses its own identifier rather than the binary name, and inserting `argsSeparator` (e.g. `--`) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. `resolveCliSpawn(provider, command, args, childEnv)` composes that with Windows shim resolution (`bufferedSpawn.js`) for the three headless spawn sites that repeated the same sequence (`runner.js`, `cliProviderRun.js`, `visionCli.js`) — the argv analog of why `cliChildEnv.js`'s `buildCliChildEnv` exists. Every call site keeps resolving `provider.command`/`args` unchanged for vendor detection, prompt-delivery convention, and TUI ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call. Both also return `wrapped`, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: `needsProcessGroup(wrapped)` says whether to spawn `detached` and kill with `{ processGroup: true }` (POSIX only — Windows' `taskkill /T` is already tree-wide), and `processGroupKillable(child, processGroup)` adapts a child for the aiToolkit runner's external-run registry, whose vendored `killProcessTree` has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. `trackDetachedGroup(child, processGroup)` / `signalDetachedGroups(signal, logFailure)` are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at `npm start`) from orphaning one. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. |
| `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. |
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index d9df674fe6..2d57a093e5 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -277,7 +277,17 @@ export function killProcessTree(child, signal = 'SIGTERM', { processGroup = fals
return;
}
if (processGroup && child.pid) {
- try { process.kill(-child.pid, signal); return; }
+ try {
+ process.kill(-child.pid, signal);
+ // Node sets `.killed` only from `child.kill()`, so a group signal would
+ // otherwise leave it false and defeat every `if (!child.killed)` re-entry
+ // guard that gates a second kill — exactly why the Windows branch above
+ // sets it by hand too. Only for a real ChildProcess: a node-pty IPty has
+ // no `killed` of its own, and inventing one would start short-circuiting
+ // PTY teardown paths that deliberately re-kill.
+ if (isChildProcess) child.killed = true;
+ return;
+ }
catch { /* ESRCH — the group is already gone; fall through to the pid */ }
}
if (isPidOnly) {
diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.js
index f0aaf0e6ce..38cc3819e0 100644
--- a/server/lib/bufferedSpawn.test.js
+++ b/server/lib/bufferedSpawn.test.js
@@ -125,6 +125,12 @@ describe('killProcessTree', () => {
killProcessTree(child, undefined, { processGroup: true });
expect(killSpy).toHaveBeenCalledWith(-555, 'SIGTERM');
expect(child.kill).not.toHaveBeenCalled();
+ // Node sets `.killed` only from `child.kill()`, so the group path must set
+ // it by hand — for the same reason the Windows taskkill branch does. Every
+ // re-entrant guard gated on `!child.killed` (the runner's timeout, the
+ // fallback-signal detector, cliProviderRun, visionCli) would otherwise
+ // never engage for a group-killed child and fire a redundant second kill.
+ expect(child.killed).toBe(true);
killSpy.mockRestore();
});
@@ -134,6 +140,21 @@ describe('killProcessTree', () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { throw new Error('ESRCH'); });
killProcessTree(child, 'SIGKILL', { processGroup: true });
expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+ // The group signal did NOT land, so `.killed` is left to the real
+ // `child.kill()` the fallback just made — never stamped on a failed group.
+ killSpy.mockRestore();
+ });
+
+ it('on non-Windows leaves a node-pty handle\'s killed state alone on the group path', () => {
+ if (IS_WIN32) return; // platform-gated behavior
+ // An IPty has no `killed` of its own; inventing one would start
+ // short-circuiting PTY teardown paths that deliberately re-kill.
+ const pty = { pid: 556, kill: vi.fn() };
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ killProcessTree(pty, 'SIGHUP', { processGroup: true });
+ expect(killSpy).toHaveBeenCalledWith(-556, 'SIGHUP');
+ expect(pty.kill).not.toHaveBeenCalled();
+ expect(pty.killed).toBeUndefined();
killSpy.mockRestore();
});
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index b7814f6175..d93a9a2cf4 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -26,7 +26,7 @@ import { filterCallerModeEligible } from './callerModePolicy.js';
import { buildVendorSpawnConfig, supportsPublicReviewProvider } from './providerVendors.js';
import { isPublicReviewNoToolProfile } from './agentExecutionProfiles.js';
import { resolveCliModel } from './providerModels.js';
-import { resolveCliSpawn } from './credentialBootstrap.js';
+import { resolveCliSpawn, needsProcessGroup, trackDetachedGroup } from './credentialBootstrap.js';
// How much stderr to hand back to callers. Enough to carry a rate-limit banner
// or a stack's first frames, short enough to embed in an error message or a
@@ -164,12 +164,22 @@ export function runCliProviderPrompt(args = {}) {
// prepareCliPrompt (above), which still keys prompt-delivery convention
// off the harness's own command, not the bootstrap CLI's — and never under
// a public-review `safetyProfile`, whose enforced recipe is the sandbox.
- const { command: spawnCommand, args: wrappedArgs } = resolveCliSpawn(provider, provider.command, spawnArgs, childEnv, { safetyProfile });
+ const { command: spawnCommand, args: wrappedArgs, wrapped } = resolveCliSpawn(provider, provider.command, spawnArgs, childEnv, { safetyProfile });
+ // A bootstrap-wrapped child is a supervising WRAPPER, not the harness, so
+ // the timeout kill below has to signal the whole process group or it leaves
+ // the harness running past the run (#7496). False for every unwrapped
+ // spawn — including a public-review posture, which is never wrapped.
+ const processGroup = needsProcessGroup(wrapped);
const child = spawn(spawnCommand, wrappedArgs, {
cwd: effectiveCwd,
stdio: ['pipe', 'pipe', 'pipe'],
env: childEnv,
+ detached: processGroup,
});
+ // Remember the detached group so the graceful-shutdown sweep can reach it:
+ // detaching moved this child out of the server's own process group, and a
+ // shutdown driven by a signal to THAT group would otherwise orphan it (#7496).
+ trackDetachedGroup(child, processGroup);
// Single settlement gate — the timer, spawn error, and close handler all
// race. Without it a SIGKILL that doesn't kill synchronously lets the
@@ -183,7 +193,7 @@ export function runCliProviderPrompt(args = {}) {
};
const timer = setTimeout(() => {
- if (!child.killed) killProcessTree(child);
+ if (!child.killed) killProcessTree(child, 'SIGTERM', { processGroup });
done({ error: `Provider call timed out after ${timeoutMs}ms`, text: stdout.trim(), stderr, stderrTail: stderrTailOf(stderr) });
}, timeoutMs);
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index 19727ed29c..c3521c94f7 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -252,3 +252,59 @@ describe('runCliProviderPrompt', () => {
});
});
});
+
+// #7496. With a credentialBootstrap provider the direct child is the user's
+// bootstrap CLI, not the harness, and `<bootstrap> run <harness> -- <args>` is
+// the shape of a supervising PARENT. Stop/timeout is a safety control, so the
+// timeout must take down the harness behind the wrapper, not just the wrapper.
+describe('runCliProviderPrompt — credential-bootstrap process-group teardown', () => {
+ // `sh -c cat <harnessId>` runs `cat` with $0 set to the harness id, so the
+ // stdin round-trip still works through a real bootstrap-shaped wrap.
+ const bootstrapProvider = {
+ id: 'gemini-cli',
+ type: 'cli',
+ command: 'cat',
+ args: [],
+ credentialBootstrap: { command: 'sh', args: ['-c', 'cat'] },
+ };
+
+ it.skipIf(process.platform === 'win32')('round-trips the prompt through the bootstrap wrapper', async () => {
+ const result = await runCliProviderPrompt({ provider: bootstrapProvider, prompt: 'wrapped round-trip' });
+ expect(result.error).toBeUndefined();
+ expect(result.text).toBe('wrapped round-trip');
+ });
+
+ // The end-to-end proof of the whole change: a wrapper that IGNORES SIGTERM
+ // and leaves a live grandchild is exactly the shape the issue describes.
+ // Under the old per-pid kill the `sleep` outlived the run; the group kill
+ // reaps it with its parent.
+ it.skipIf(process.platform === 'win32')('takes the harness down with the wrapper on timeout', async () => {
+ const result = await runCliProviderPrompt({
+ provider: {
+ id: 'gemini-cli',
+ type: 'cli',
+ command: 'stand-in-harness',
+ args: [],
+ // A no-op TERM handler, so the wrapper survives the signal without
+ // forwarding it — a trap of "" instead would set SIG_IGN, which the
+ // grandchild INHERITS, and the test would then prove nothing about
+ // reach. Print the grandchild's pid so the assertion can probe it.
+ credentialBootstrap: { command: 'sh', args: ['-c', 'trap ":" TERM; sleep 30 & echo $!; wait'] },
+ },
+ prompt: 'ignored',
+ timeoutMs: 300,
+ });
+
+ expect(result.error).toMatch(/timed out/);
+ const grandchildPid = Number(result.text.trim());
+ expect(Number.isInteger(grandchildPid)).toBe(true);
+
+ // Signal 0 probes for existence without delivering anything. The group
+ // SIGTERM has to have reached the `sleep`, not just the trapping wrapper.
+ await new Promise(resolve => setTimeout(resolve, 200));
+ let alive = true;
+ try { process.kill(grandchildPid, 0); } catch { alive = false; }
+ if (alive) process.kill(grandchildPid, 'SIGKILL');
+ expect(alive).toBe(false);
+ });
+});
diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.js
index c7a9914211..eeb030e119 100644
--- a/server/lib/credentialBootstrap.js
+++ b/server/lib/credentialBootstrap.js
@@ -39,13 +39,20 @@
* The skip lives here rather than at each call site so a new spawn site can't
* forget it.
*
+ * Wrapping also changes TEARDOWN, so every site that spawns a long-lived child
+ * here owes a second thing: the direct child is then the WRAPPER, and nothing
+ * obliges it to `exec`-replace itself, so a per-pid SIGTERM can leave the
+ * harness running. `needsProcessGroup` + `trackDetachedGroup` /
+ * `signalDetachedGroups` / `processGroupKillable` below are that half of the
+ * contract — see `needsProcessGroup` (#7496).
+ *
* Imports only `bufferedSpawn.js` and `agentExecutionProfiles.js` (both of
* which `cliProviderRun.js` already depends on directly) so any spawn site —
* including the standalone `portos-autofixer` process via `cliProviderRun.js`
* — can import this module without dragging in the AI toolkit or data layer.
*/
-import { resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';
+import { IS_WIN32, resolveWindowsExecutable, prepareWindowsSafeSpawn, killProcessTree } from './bufferedSpawn.js';
import { isPublicReviewRestrictedProfile } from './agentExecutionProfiles.js';
/** True when a provider names a bootstrap CLI to wrap its harness spawn. */
@@ -76,20 +83,158 @@ export function hasCredentialBootstrap(provider) {
* @param {{credentialBootstrap?: {command: string, args?: string[], harnessId?: string, argsSeparator?: string}}|null|undefined} provider
* @param {string} command - the harness binary PortOS would otherwise spawn
* @param {string[]} [args] - the harness's own argv
+ * `wrapped` reports whether the wrap actually applied — including the
+ * public-review skip, so a posture that is deliberately NOT wrapped also keeps
+ * the unwrapped teardown. It matters for process teardown, not argv: once a
+ * bootstrap CLI sits in front of the harness, the direct child PortOS holds is
+ * the WRAPPER, and `<bootstrap> run <harness> -- <args>` is the shape of a
+ * supervising parent. A plain SIGTERM to the direct child then leaves the
+ * harness running. See `needsProcessGroup` (#7496).
+ *
* @param {{safetyProfile?: string|null}} [options] - the run's execution
* profile; a public-review posture is returned unwrapped (see module doc)
- * @returns {{command: string, args: string[]}}
+ * @returns {{command: string, args: string[], wrapped: boolean}}
*/
export function applyCredentialBootstrap(provider, command, args, { safetyProfile = null } = {}) {
const bootstrap = provider?.credentialBootstrap;
const harnessArgs = Array.isArray(args) ? args : [];
- if (!hasCredentialBootstrap(provider) || isPublicReviewRestrictedProfile(safetyProfile)) return { command, args: harnessArgs };
+ if (!hasCredentialBootstrap(provider) || isPublicReviewRestrictedProfile(safetyProfile)) {
+ return { command, args: harnessArgs, wrapped: false };
+ }
const harnessId = (typeof bootstrap.harnessId === 'string' && bootstrap.harnessId) || command;
const separator = (typeof bootstrap.argsSeparator === 'string' && bootstrap.argsSeparator && harnessArgs.length > 0)
? [bootstrap.argsSeparator] : [];
return {
command: bootstrap.command,
args: [...(Array.isArray(bootstrap.args) ? bootstrap.args : []), harnessId, ...separator, ...harnessArgs],
+ wrapped: true,
+ };
+}
+
+/**
+ * Should this spawn get its own process group, so stop/timeout/cancel reaches
+ * the harness BEHIND the bootstrap wrapper and not just the wrapper itself?
+ *
+ * Stop/timeout/cancel is a safety control: a harness that survives it keeps
+ * running — possibly with `--dangerously-skip-permissions` in a worktree,
+ * holding a freshly minted credential — after PortOS has finalized the run and
+ * released the lane. On POSIX a signal to the direct child's pid reaches only
+ * that pid, so a forking wrapper that does not forward SIGTERM orphans the
+ * harness. Spawning `detached: true` puts wrapper and harness in one process
+ * group that `killProcessTree(child, sig, { processGroup: true })` signals
+ * whole.
+ *
+ * POSIX-only, deliberately:
+ * - On Windows `killProcessTree` already uses `taskkill /T`, which is
+ * tree-wide rather than group-based, so the hole does not exist there.
+ * - `detached: true` on Windows opens a new console window per spawn.
+ *
+ * False for an unwrapped spawn — including a public-review posture, which is
+ * never wrapped — so nothing changes for those: the harness is the direct child
+ * there and today's per-pid signal is exact.
+ *
+ * @param {boolean} wrapped - the `wrapped` flag from applyCredentialBootstrap/resolveCliSpawn
+ * @param {boolean} [isWin32] - injectable for tests; defaults to the real platform
+ * @returns {boolean}
+ */
+export function needsProcessGroup(wrapped, isWin32 = IS_WIN32) {
+ return Boolean(wrapped) && !isWin32;
+}
+
+/**
+ * pids of the children this process spawned into their own process group.
+ *
+ * Detaching is what makes stop/timeout/cancel reach the harness, but it also
+ * moves the child OUT of the server's process group — so a shutdown driven by a
+ * signal aimed at THAT group (Ctrl-C at an `npm start` terminal, `kill -<pgid>`)
+ * no longer reaches it. pm2's TreeKill walks the pid tree and is unaffected.
+ * This set is what lets the shutdown handler restore exactly that lost reach,
+ * across every detached spawn site at once, rather than each registry (agents,
+ * runs, vision calls, ask calls) having to be swept separately and one forgotten.
+ */
+const detachedGroupPids = new Set();
+
+/**
+ * Remember a detached child's process group until it closes. No-op — and the
+ * child is returned untouched — when the spawn was not detached.
+ *
+ * Keyed by pid rather than by handle so the shutdown sweep needs nothing but
+ * `process.kill`.
+ *
+ * Cleared on `close` — NOT on `exit`, and adding `exit` would defeat the whole
+ * point. `exit` fires when the WRAPPER is reaped; `close` waits for its stdio to
+ * close, which the harness is still holding precisely in the case this registry
+ * exists for (a wrapper that forked and left the harness running). Forgetting the
+ * group at `exit` would drop it exactly when the harness is its only member —
+ * the orphan we are trying to reach.
+ *
+ * That deferral does not risk signalling a recycled pid: `kill(-pid)` addresses a
+ * process GROUP, and a pgid cannot be reallocated while its group still has a
+ * member. So as long as anything in the group is alive the number stays ours,
+ * and once the group empties the harness's descriptors are closed, so `close`
+ * has fired. `error` covers a child that never started and will emit neither.
+ *
+ * @template T
+ * @param {T & {pid?: number, once?: Function}} child
+ * @param {boolean} processGroup - the `needsProcessGroup` result used for this spawn
+ * @returns {T} the same child, for call-site chaining
+ */
+export function trackDetachedGroup(child, processGroup) {
+ if (!processGroup || !child?.pid || typeof child.once !== 'function') return child;
+ const { pid } = child;
+ detachedGroupPids.add(pid);
+ const forget = () => detachedGroupPids.delete(pid);
+ child.once('close', forget);
+ child.once('error', forget);
+ return child;
+}
+
+/**
+ * SIGTERM every live detached process group. Best-effort and synchronous: it
+ * runs inside the graceful-shutdown window, where an already-dead group (ESRCH)
+ * is not a fault and nothing may propagate out of a signal handler.
+ *
+ * @param {NodeJS.Signals} [signal]
+ * @param {(label: string, err: Error) => void} [logFailure]
+ * @returns {number} how many groups were signalled
+ */
+export function signalDetachedGroups(signal = 'SIGTERM', logFailure = null) {
+ let signalled = 0;
+ for (const pid of detachedGroupPids) {
+ try { process.kill(-pid, signal); signalled += 1; }
+ catch (err) { if (err?.code !== 'ESRCH') logFailure?.(`⚠️ Group ${signal} for pid ${pid}`, err); }
+ }
+ return signalled;
+}
+
+/** Test-only: drop every tracked group without signalling it. */
+export function resetDetachedGroupsForTests() {
+ detachedGroupPids.clear();
+}
+
+/**
+ * Wrap a spawned child in the minimal `{ pid, killed, kill(signal) }` shape the
+ * aiToolkit runner's external-run registry consumes (`registerExternalRun`),
+ * so its `stopRun` — the /runs Stop button — signals the whole process group
+ * instead of the wrapper alone.
+ *
+ * The toolkit carries its OWN self-contained `killProcessTree` with no
+ * `processGroup` option (see `server/lib/aiToolkit/AGENTS.md` — that directory
+ * imports nothing out to PortOS), and it reaches a non-ChildProcess killable
+ * through the handle's own `.kill()`. Handing it this adapter is therefore how
+ * a host-owned group kill reaches a toolkit-driven stop without editing the
+ * vendored copy. Returns the child UNCHANGED when `processGroup` is false, so
+ * an unwrapped run registers exactly what it registers today.
+ *
+ * @param {import('child_process').ChildProcess|{pid?: number, kill: Function}} child
+ * @param {boolean} processGroup
+ */
+export function processGroupKillable(child, processGroup) {
+ if (!processGroup) return child;
+ return {
+ get pid() { return child.pid; },
+ get killed() { return child.killed; },
+ kill: (signal) => killProcessTree(child, signal || 'SIGTERM', { processGroup: true }),
};
}
@@ -112,10 +257,11 @@ export function applyCredentialBootstrap(provider, command, args, { safetyProfil
* @param {NodeJS.ProcessEnv} childEnv - resolved against this so a
* provider-configured PATH override is honored
* @param {{safetyProfile?: string|null}} [options] - forwarded to `applyCredentialBootstrap`
- * @returns {{command: string, args: string[]}}
+ * @returns {{command: string, args: string[], wrapped: boolean}} `wrapped` is
+ * carried through from `applyCredentialBootstrap` — see `needsProcessGroup`
*/
export function resolveCliSpawn(provider, command, args, childEnv, options = {}) {
const bootstrapped = applyCredentialBootstrap(provider, command, args, options);
const resolvedCommand = resolveWindowsExecutable(bootstrapped.command, undefined, childEnv) || bootstrapped.command;
- return prepareWindowsSafeSpawn(resolvedCommand, bootstrapped.args);
+ return { ...prepareWindowsSafeSpawn(resolvedCommand, bootstrapped.args), wrapped: bootstrapped.wrapped };
}
diff --git a/server/lib/credentialBootstrap.test.js b/server/lib/credentialBootstrap.test.js
index dd4dd062d5..621048a032 100644
--- a/server/lib/credentialBootstrap.test.js
+++ b/server/lib/credentialBootstrap.test.js
@@ -1,5 +1,6 @@
-import { describe, it, expect, vi } from 'vitest';
-import { hasCredentialBootstrap, applyCredentialBootstrap, resolveCliSpawn } from './credentialBootstrap.js';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+import { hasCredentialBootstrap, applyCredentialBootstrap, resolveCliSpawn, needsProcessGroup, processGroupKillable, trackDetachedGroup, signalDetachedGroups, resetDetachedGroupsForTests } from './credentialBootstrap.js';
import { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from './agentExecutionProfiles.js';
vi.mock('./bufferedSpawn.js', async (importOriginal) => ({
@@ -26,6 +27,7 @@ describe('credentialBootstrap', () => {
expect(applyCredentialBootstrap(provider, 'opencode', ['run', '--print'])).toEqual({
command: 'token-cli',
args: ['run', 'opencode', 'run', '--print'],
+ wrapped: true,
});
});
@@ -34,15 +36,17 @@ describe('credentialBootstrap', () => {
expect(applyCredentialBootstrap(provider, 'claude', ['-p', '-'])).toEqual({
command: 'token-cli',
args: ['claude', '-p', '-'],
+ wrapped: true,
});
});
it('returns the harness command unchanged when no bootstrap is configured', () => {
- expect(applyCredentialBootstrap({}, 'claude', ['-p', '-'])).toEqual({ command: 'claude', args: ['-p', '-'] });
- expect(applyCredentialBootstrap(null, 'claude', ['-p', '-'])).toEqual({ command: 'claude', args: ['-p', '-'] });
+ expect(applyCredentialBootstrap({}, 'claude', ['-p', '-'])).toEqual({ command: 'claude', args: ['-p', '-'], wrapped: false });
+ expect(applyCredentialBootstrap(null, 'claude', ['-p', '-'])).toEqual({ command: 'claude', args: ['-p', '-'], wrapped: false });
expect(applyCredentialBootstrap({ credentialBootstrap: null }, 'claude', ['-p', '-'])).toEqual({
command: 'claude',
args: ['-p', '-'],
+ wrapped: false,
});
});
@@ -51,6 +55,7 @@ describe('credentialBootstrap', () => {
expect(applyCredentialBootstrap(provider, 'claude', ['-p', '-'])).toEqual({
command: 'token-cli',
args: ['run', 'claude-code', '-p', '-'],
+ wrapped: true,
});
});
@@ -59,6 +64,7 @@ describe('credentialBootstrap', () => {
expect(applyCredentialBootstrap(provider, 'claude', ['-p', '-'])).toEqual({
command: 'token-cli',
args: ['run', 'claude', '--', '-p', '-'],
+ wrapped: true,
});
});
@@ -67,14 +73,16 @@ describe('credentialBootstrap', () => {
expect(applyCredentialBootstrap(provider, 'claude', [])).toEqual({
command: 'token-cli',
args: ['run', 'claude'],
+ wrapped: true,
});
});
it('defaults missing harness args to an empty array', () => {
- expect(applyCredentialBootstrap({}, 'claude')).toEqual({ command: 'claude', args: [] });
+ expect(applyCredentialBootstrap({}, 'claude')).toEqual({ command: 'claude', args: [], wrapped: false });
expect(applyCredentialBootstrap({ credentialBootstrap: { command: 'token-cli' } }, 'claude')).toEqual({
command: 'token-cli',
args: ['claude'],
+ wrapped: true,
});
});
});
@@ -109,11 +117,173 @@ describe('credentialBootstrap', () => {
expect(resolveCliSpawn(provider, 'claude', ['-p', '-'], process.env)).toEqual({
command: 'token-cli',
args: ['run', 'claude', '-p', '-'],
+ wrapped: true,
});
});
it('falls through to the harness unchanged when no bootstrap is configured', () => {
- expect(resolveCliSpawn({}, 'claude', ['-p', '-'], process.env)).toEqual({ command: 'claude', args: ['-p', '-'] });
+ expect(resolveCliSpawn({}, 'claude', ['-p', '-'], process.env)).toEqual({ command: 'claude', args: ['-p', '-'], wrapped: false });
+ });
+ });
+
+ describe('needsProcessGroup', () => {
+ // The safety contract: a wrapped POSIX spawn MUST get its own process group,
+ // because the direct child is the bootstrap wrapper and a per-pid SIGTERM
+ // would leave the harness behind it running past stop/timeout/cancel (#7496).
+ it('is true only for a wrapped spawn on POSIX', () => {
+ expect(needsProcessGroup(true, false)).toBe(true);
+ expect(needsProcessGroup(false, false)).toBe(false);
+ });
+
+ // Windows takes the taskkill /T branch in killProcessTree, which is
+ // tree-wide rather than group-based, and `detached: true` there would open a
+ // console window per spawn.
+ it('is false on Windows even when wrapped', () => {
+ expect(needsProcessGroup(true, true)).toBe(false);
+ expect(needsProcessGroup(false, true)).toBe(false);
+ });
+
+ it('coerces a missing flag rather than leaking undefined into spawn options', () => {
+ expect(needsProcessGroup(undefined, false)).toBe(false);
+ });
+ });
+
+ describe('processGroupKillable', () => {
+ it('returns the child itself when no process group is needed', () => {
+ const child = { pid: 42, killed: false, kill: vi.fn() };
+ expect(processGroupKillable(child, false)).toBe(child);
+ });
+
+ // The aiToolkit runner's stopRun (/runs Stop) reaches a non-ChildProcess
+ // killable through its own `.kill()`, and its vendored killProcessTree has
+ // no processGroup option — so the adapter is what makes that stop signal the
+ // whole group instead of the wrapper alone.
+ it('routes kill through a group signal and mirrors the live pid/killed state', () => {
+ const killSpy = vi.fn();
+ const child = { pid: 4242, killed: false, kill: killSpy };
+ const killable = processGroupKillable(child, true);
+
+ expect(killable.pid).toBe(4242);
+ expect(killable.killed).toBe(false);
+
+ killable.kill('SIGTERM');
+ // POSIX + non-ChildProcess + processGroup → killProcessTree signals -pid,
+ // which fails with ESRCH for this fake and falls back to the handle's own
+ // kill. Either way the handle is reached, never bypassed.
+ expect(killSpy).toHaveBeenCalledWith('SIGTERM');
+
+ child.killed = true;
+ expect(killable.killed).toBe(true);
+ });
+
+ it('defaults to SIGTERM when the toolkit calls kill() with no signal', () => {
+ const killSpy = vi.fn();
+ const killable = processGroupKillable({ pid: 7, killed: false, kill: killSpy }, true);
+ killable.kill();
+ expect(killSpy).toHaveBeenCalledWith('SIGTERM');
+ });
+ });
+
+ // Detaching is what gives stop/timeout/cancel its reach, but it also moves
+ // the child OUT of the server's process group — so a shutdown driven by a
+ // signal to THAT group stops reaching it. This registry is what lets the
+ // shutdown handler restore exactly that lost reach across every detached
+ // spawn site at once (agent runs, CLI runs, vision calls), rather than
+ // sweeping each registry separately and forgetting one.
+ describe('detached-group registry', () => {
+ const fakeChild = (pid) => Object.assign(new EventEmitter(), { pid });
+
+ beforeEach(() => { resetDetachedGroupsForTests(); });
+ afterEach(() => { resetDetachedGroupsForTests(); });
+
+ it('signals each tracked group and reports how many it reached', () => {
+ // Spy so the negative pids never reach real process groups.
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ trackDetachedGroup(fakeChild(101), true);
+ trackDetachedGroup(fakeChild(202), true);
+
+ expect(signalDetachedGroups()).toBe(2);
+ expect(killSpy).toHaveBeenCalledWith(-101, 'SIGTERM');
+ expect(killSpy).toHaveBeenCalledWith(-202, 'SIGTERM');
+ killSpy.mockRestore();
+ });
+
+ it('tracks nothing for an undetached spawn, and returns the child either way', () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = fakeChild(303);
+
+ expect(trackDetachedGroup(child, false)).toBe(child);
+ expect(trackDetachedGroup(fakeChild(404), true)).toBeTruthy();
+
+ expect(signalDetachedGroups()).toBe(1);
+ expect(killSpy).not.toHaveBeenCalledWith(-303, expect.anything());
+ killSpy.mockRestore();
+ });
+
+ it('forgets a group once its child closes, so a recycled pid is never signalled', () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = fakeChild(505);
+ trackDetachedGroup(child, true);
+
+ child.emit('close', 0);
+
+ expect(signalDetachedGroups()).toBe(0);
+ expect(killSpy).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+
+ // The load-bearing distinction: 'exit' fires when the WRAPPER is reaped,
+ // 'close' waits for its stdio — which the harness is still holding in
+ // exactly the case this registry exists for. Forgetting at 'exit' would drop
+ // the group precisely when the orphaned harness is its only member.
+ it('keeps tracking a group whose wrapper exited while the harness holds its stdio', () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = fakeChild(515);
+ trackDetachedGroup(child, true);
+
+ child.emit('exit', 0, null);
+
+ expect(signalDetachedGroups()).toBe(1);
+ expect(killSpy).toHaveBeenCalledWith(-515, 'SIGTERM');
+ killSpy.mockRestore();
+ });
+
+ it('forgets a group whose child failed to spawn at all', () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = fakeChild(606);
+ trackDetachedGroup(child, true);
+
+ child.emit('error', new Error('ENOENT'));
+
+ expect(signalDetachedGroups()).toBe(0);
+ killSpy.mockRestore();
+ });
+
+ it('skips a pidless child rather than signalling group 0 — the server itself', () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ trackDetachedGroup(fakeChild(undefined), true);
+ trackDetachedGroup(fakeChild(0), true);
+
+ expect(signalDetachedGroups()).toBe(0);
+ expect(killSpy).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+
+ it('treats an already-dead group as done, and logs any other failure without throwing', () => {
+ const esrch = Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' });
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { throw esrch; });
+ const logFailure = vi.fn();
+ trackDetachedGroup(fakeChild(707), true);
+
+ expect(signalDetachedGroups('SIGTERM', logFailure)).toBe(0);
+ expect(logFailure).not.toHaveBeenCalled();
+
+ killSpy.mockImplementation(() => { throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' }); });
+ // Nothing may propagate out of a signal handler.
+ expect(() => signalDetachedGroups('SIGTERM', logFailure)).not.toThrow();
+ expect(logFailure).toHaveBeenCalledTimes(1);
+ expect(logFailure.mock.calls[0][0]).toContain('Group SIGTERM for pid 707');
+ killSpy.mockRestore();
});
});
});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index efb5da127c..405aba26b8 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -41,7 +41,7 @@ import { resolveForgeTokenEnv } from './forgeAuth.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
-import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
+import { applyCredentialBootstrap, needsProcessGroup, trackDetachedGroup } from '../lib/credentialBootstrap.js';
import { prClaimWasVerified } from '../lib/prDisposition.js';
import { resolvePrOwnership } from '../lib/slashdoInvocation.js';
import { doneSentinelPath } from '../lib/agentSentinel.js';
@@ -236,7 +236,13 @@ export async function spawnDirectly({
// credentialBootstrap.js. Applied AFTER prepareCliPrompt, which still keys
// prompt-delivery convention off the harness's own command — and never under
// a public-review `safetyProfile`, whose enforced recipe is the sandbox.
- const { command: bootstrappedCommand, args: bootstrappedArgs } = applyCredentialBootstrap(provider, cliConfig.command, deliveredArgs, { safetyProfile });
+ const { command: bootstrappedCommand, args: bootstrappedArgs, wrapped } = applyCredentialBootstrap(provider, cliConfig.command, deliveredArgs, { safetyProfile });
+ // A bootstrap-wrapped child is the WRAPPER supervising the harness, so every
+ // stop/timeout/cancel for this agent must signal the whole process group —
+ // here, and in agentManagement's pause/terminate/force-kill, which reads the
+ // flag back off the activeAgents entry below (#7496). The private-security
+ // sandbox wrap below is likewise a supervising parent, so it keeps the flag.
+ const processGroup = needsProcessGroup(wrapped);
const preparedSpawn = prepareCliSpawn(bootstrappedCommand, bootstrappedArgs, childEnv);
const isolatedSpawn = isPrivateSecurityTask(task)
? await import('../lib/privateSecuritySandbox.js')
@@ -265,9 +271,17 @@ export async function spawnDirectly({
cwd,
shell: false,
stdio: ['pipe', 'pipe', 'pipe'],
- env: isolatedSpawn.env
+ env: isolatedSpawn.env,
+ // Never `unref()`ed — this stays an ordinary awaited child, just one in
+ // its own signalable process group. See needsProcessGroup.
+ detached: processGroup
});
+ // Remember the detached group so the graceful-shutdown sweep can reach it:
+ // detaching moved this child out of the server's own process group, and a
+ // shutdown driven by a signal to THAT group would otherwise orphan it (#7496).
+ trackDetachedGroup(claudeProcess, processGroup);
+
// Every child listener is registered HERE, in the same tick as spawn(), into
// forwarding shims that buffer until the real handler bodies exist further
// down (#5791). Those bodies close over state built by the async setup that
@@ -326,6 +340,9 @@ export async function spawnDirectly({
activeAgents.set(agentId, {
process: claudeProcess,
+ // Read by agentManagement's pause/terminate/force-kill paths, which hold
+ // only this entry and cannot re-derive the bootstrap wrap (#7496).
+ processGroup,
taskId: task.id,
startedAt: Date.now(),
runId,
@@ -450,7 +467,7 @@ export async function spawnDirectly({
category: analysis.category
});
// killProcessTree so a Windows cmd.exe-wrapped shim's real child isn't orphaned (#2243).
- killProcessTree(claudeProcess, 'SIGTERM');
+ killProcessTree(claudeProcess, 'SIGTERM', { processGroup });
};
// If no output after 3 seconds, transition from initializing to working to show progress
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 8173e3e9c6..b765d6e384 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -1419,4 +1419,90 @@ describe('stream error containment', () => {
expect(finalizeAgent).not.toHaveBeenCalled();
});
});
+
+ // #7496. With a credentialBootstrap provider the direct child is the user's
+ // bootstrap CLI, not the harness — and `<bootstrap> run <harness> -- <args>`
+ // is the shape of a supervising PARENT, not an exec-replacement. A per-pid
+ // SIGTERM would leave the harness running (possibly with
+ // `--dangerously-skip-permissions` in a worktree, holding a freshly minted
+ // credential) after the agent is finalized and its lane released.
+ describe('credential-bootstrap process-group teardown', () => {
+ const bootstrapArgs = {
+ ...minimalArgs,
+ provider: {
+ ...minimalArgs.provider,
+ credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' },
+ },
+ };
+
+ it('spawns a bootstrap-wrapped child detached and records the flag for the stop paths', async () => {
+ const { spawn } = await import('../lib/childProcess.js');
+ const { activeAgents } = await import('./agentState.js');
+ activeAgents.clear();
+ spawn.mockClear();
+
+ const spawnPromise = spawnDirectly(bootstrapArgs);
+ await vi.waitFor(() => expect(activeAgents.has(bootstrapArgs.agentId)).toBe(true), { interval: 5 });
+
+ const [command, , options] = spawn.mock.calls.at(-1);
+ expect(command).toBe('token-cli');
+ expect(options.detached).toBe(true);
+ // agentManagement's pause/terminate/force-kill hold only this entry and
+ // cannot re-derive the wrap, so the flag has to travel with it.
+ expect(activeAgents.get(bootstrapArgs.agentId).processGroup).toBe(true);
+
+ activeAgents.delete(bootstrapArgs.agentId);
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ });
+
+ it('leaves an unwrapped provider attached with no group flag', async () => {
+ const { spawn } = await import('../lib/childProcess.js');
+ const { activeAgents } = await import('./agentState.js');
+ activeAgents.clear();
+ spawn.mockClear();
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+ await vi.waitFor(() => expect(activeAgents.has(minimalArgs.agentId)).toBe(true), { interval: 5 });
+
+ const [, , options] = spawn.mock.calls.at(-1);
+ expect(options.detached).toBe(false);
+ expect(activeAgents.get(minimalArgs.agentId).processGroup).toBe(false);
+
+ activeAgents.delete(minimalArgs.agentId);
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ });
+
+ it('kills by process group when a provider-fallback signal stops a wrapped run', async () => {
+ killProcessTree.mockClear();
+ const spawnPromise = spawnDirectly(bootstrapArgs);
+ await new Promise((r) => setTimeout(r, 10));
+
+ fakeProcess.stdout.emit('data', Buffer.from('Now using extra usage\n'));
+
+ expect(killProcessTree).toHaveBeenCalledTimes(1);
+ expect(killProcessTree.mock.calls[0][1]).toBe('SIGTERM');
+ expect(killProcessTree.mock.calls[0][2]).toEqual({ processGroup: true });
+
+ fakeProcess.killed = true;
+ fakeProcess.emit('close', 143);
+ await spawnPromise.catch(() => {});
+ });
+
+ it('kills by pid alone when the same signal stops an UNWRAPPED run', async () => {
+ killProcessTree.mockClear();
+ const spawnPromise = spawnDirectly(minimalArgs);
+ await new Promise((r) => setTimeout(r, 10));
+
+ fakeProcess.stdout.emit('data', Buffer.from('Now using extra usage\n'));
+
+ expect(killProcessTree).toHaveBeenCalledTimes(1);
+ expect(killProcessTree.mock.calls[0][2]).toEqual({ processGroup: false });
+
+ fakeProcess.killed = true;
+ fakeProcess.emit('close', 143);
+ await spawnPromise.catch(() => {});
+ });
+ });
});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index fc8d847b54..32623b6fea 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -292,11 +292,14 @@ export async function pauseAgent(agentId, reason = null) {
}, 250);
} else {
// killProcessTree so a Windows cmd.exe-wrapped CLI shim's real child is
- // taken down, not orphaned (#2243). No behavior change on POSIX.
- killProcessTree(agent.process, 'SIGTERM');
+ // taken down, not orphaned (#2243). `processGroup` (set at spawn time by
+ // agentCliSpawning) additionally reaches the harness behind a credential-
+ // bootstrap wrapper on POSIX; it is false for every other agent, so their
+ // teardown is unchanged (#7496).
+ killProcessTree(agent.process, 'SIGTERM', { processGroup: agent.processGroup });
const killTimer = setTimeout(() => {
if (activeAgents.has(agentId)) {
- killProcessTree(agent.process, 'SIGKILL');
+ killProcessTree(agent.process, 'SIGKILL', { processGroup: agent.processGroup });
}
}, 5000);
const agentEntry = activeAgents.get(agentId);
@@ -761,13 +764,15 @@ export async function terminateAgent(agentId) {
}
// Kill the process — killProcessTree so a Windows cmd.exe-wrapped shim's
- // real child isn't orphaned (#2243). POSIX behavior unchanged.
- killProcessTree(agent.process, 'SIGTERM');
+ // real child isn't orphaned (#2243), and `processGroup` so a credential-
+ // bootstrap wrapper's harness goes down with it rather than outliving the
+ // terminated run (#7496).
+ killProcessTree(agent.process, 'SIGTERM', { processGroup: agent.processGroup });
// Give it a moment, then force kill if still running
const killTimer = setTimeout(() => {
if (activeAgents.has(agentId)) {
- killProcessTree(agent.process, 'SIGKILL');
+ killProcessTree(agent.process, 'SIGKILL', { processGroup: agent.processGroup });
unregisterSpawnedAgent(agent.pid);
activeAgents.delete(agentId);
}
@@ -864,8 +869,9 @@ export async function killAgent(agentId) {
}
// Kill the process immediately with SIGKILL — killProcessTree so a Windows
- // cmd.exe-wrapped shim's real child isn't orphaned (#2243). POSIX unchanged.
- killProcessTree(agent.process, 'SIGKILL');
+ // cmd.exe-wrapped shim's real child isn't orphaned (#2243), and
+ // `processGroup` so a credential-bootstrap wrapper's harness dies too (#7496).
+ killProcessTree(agent.process, 'SIGKILL', { processGroup: agent.processGroup });
unregisterSpawnedAgent(agent.pid);
activeAgents.delete(agentId);
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index cb639bb465..9a7bd124dd 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -2255,3 +2255,85 @@ describe('lifecycle ledger — pause and interruption', () => {
expect(ledgerCalls('run.interrupted')).toHaveLength(0);
});
});
+
+// #7496. A credential-bootstrap provider's agent child is the user's bootstrap
+// CLI supervising the harness, spawned into its own process group by
+// `agentCliSpawning` and flagged `processGroup: true` on its activeAgents entry.
+// These stop paths hold only that entry — they cannot re-derive the wrap — so
+// the flag has to be honored here or a terminate/force-kill leaves the harness
+// running (possibly with `--dangerously-skip-permissions` in a worktree,
+// holding a freshly minted credential) after the run is finalized.
+describe('credential-bootstrap process-group teardown', () => {
+ let killSpy;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ pausedAgents.clear();
+ // Spy so a negative pid never reaches a real process group; returning
+ // truthy makes killProcessTree treat the group signal as delivered.
+ killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', description: 'Do work', metadata: {} });
+ });
+
+ afterEach(() => {
+ killSpy.mockRestore();
+ });
+
+ const wrappedAgent = (kill = vi.fn()) => Object.assign(
+ Object.create(ChildProcess.prototype), { kill, pid: 909090 },
+ );
+
+ it('terminateAgent signals the whole group for a wrapped agent', async () => {
+ const kill = vi.fn();
+ activeAgents.set('agent-1', {
+ process: wrappedAgent(kill), processGroup: true, taskId: 'task-1', runId: 'run-1', pid: 909090,
+ });
+
+ await terminateAgent('agent-1');
+
+ expect(killSpy).toHaveBeenCalledWith(-909090, 'SIGTERM');
+ // The group signal landed, so killProcessTree never falls back to the
+ // wrapper's own pid — the harness behind it is covered.
+ expect(kill).not.toHaveBeenCalled();
+ clearTimeout(activeAgents.get('agent-1')?.killTimer);
+ });
+
+ it('terminateAgent signals only the child for an unwrapped agent', async () => {
+ const kill = vi.fn();
+ activeAgents.set('agent-1', {
+ process: fakeChildProcess(kill), taskId: 'task-1', runId: 'run-1', pid: 123,
+ });
+
+ await terminateAgent('agent-1');
+
+ expect(killSpy).not.toHaveBeenCalledWith(-123, expect.anything());
+ expect(kill).toHaveBeenCalledWith('SIGTERM');
+ clearTimeout(activeAgents.get('agent-1')?.killTimer);
+ });
+
+ it('killAgent SIGKILLs the whole group for a wrapped agent', async () => {
+ const kill = vi.fn();
+ activeAgents.set('agent-1', {
+ process: wrappedAgent(kill), processGroup: true, taskId: 'task-1', runId: 'run-1', pid: 909090,
+ });
+
+ await killAgent('agent-1');
+
+ expect(killSpy).toHaveBeenCalledWith(-909090, 'SIGKILL');
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it('pauseAgent signals the whole group for a wrapped agent', async () => {
+ const kill = vi.fn();
+ activeAgents.set('agent-1', {
+ process: wrappedAgent(kill), processGroup: true, taskId: 'task-1', runId: 'run-1', pid: 909090,
+ });
+
+ await pauseAgent('agent-1', 'billing window');
+
+ expect(killSpy).toHaveBeenCalledWith(-909090, 'SIGTERM');
+ expect(kill).not.toHaveBeenCalled();
+ clearTimeout(activeAgents.get('agent-1')?.killTimer);
+ });
+});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index bdb4ec18d4..935ecc0419 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -37,6 +37,7 @@ import { startIdleReaper, stopIdleReaper } from '../lib/managedDaemon.js';
import { adoptNpmGlobalBinDir } from '../lib/npmGlobalBin.js';
import { conflictJournalStore } from '../lib/conflictJournal.js';
import { markHostShuttingDown, writeHostShutdownMarker } from '../lib/hostShutdown.js';
+import { signalDetachedGroups } from '../lib/credentialBootstrap.js';
import { setUserCatalogTypes } from '../lib/catalogTypes.js';
import { runMigrations } from '../../scripts/run-migrations.js';
@@ -1046,6 +1047,20 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
writeHostShutdownMarker({ agentIds: [...activeAgents.keys()], signal })
.then(() => finish(), (err) => finishWithError('⚠️ Host-shutdown marker failed', err)));
+ // Reach every child spawned into its own process group — agent runs, CLI
+ // runs and vision calls alike. A credential-bootstrap-wrapped child is
+ // spawned `detached: true` so stop/timeout/cancel can signal its whole
+ // group (#7496); that also moves it OUT of this server's process group, and
+ // the one teardown route it thereby loses is a signal aimed at THAT group —
+ // Ctrl-C at an `npm start` terminal, or `kill -<pgid>`. (pm2's TreeKill
+ // walks the pid TREE, so the managed path is unaffected, and every child
+ // already survives a plain SIGTERM to the parent.) This restores exactly
+ // that lost reach rather than orphaning a harness holding a freshly minted
+ // credential. Before the teardown below, while the process still owns its
+ // state; best-effort, like everything else in this window.
+ const detachedGroups = signalDetachedGroups('SIGTERM', logBootstrapFailure);
+ if (detachedGroups) console.log(`🛑 Signalled ${detachedGroups} detached process group(s)`);
+
// Terminate the Codex app-server child before the socket teardown below.
// pm2's TreeKill would reap it anyway, but a direct SIGTERM keeps a manual
// `kill` of the server from orphaning a Codex process holding the user's
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 9116179bad..ab52ace1e9 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -126,3 +126,27 @@ describe('bounded server shutdown', () => {
expect(error).toHaveBeenCalledTimes(1);
});
});
+
+// #7496. A credential-bootstrap-wrapped child is spawned `detached: true` so
+// stop/timeout/cancel can signal its whole process group. That detach moves it
+// out of the server's own process group, so a shutdown driven by a signal aimed
+// at that group (Ctrl-C at an `npm start` terminal, `kill -<pgid>`) no longer
+// reaches it. The sweep has to cover EVERY detached spawn site — agent runs,
+// CLI runs and vision calls — which is why it reads the credentialBootstrap
+// registry rather than `activeAgents`, whose map holds only the agent children.
+describe('shutdown handler — detached-group teardown (#7496)', () => {
+ const code = stripCommentsAndNormalize(extractDeclaration(SRC, 'shutdown') || '');
+
+ it('sweeps the detached-group registry, not just the agent map', () => {
+ const signalAt = code.indexOf('signalDetachedGroups(');
+ expect(signalAt, 'signalDetachedGroups(...) is not called in shutdown()').toBeGreaterThan(-1);
+ // A sweep over activeAgents would silently miss every executeCliRun /
+ // describeImageViaCli child, which are detached by the same rule.
+ expect(code).not.toContain('signalDetachedAgentGroups');
+ });
+
+ it('signals the groups before dropping connections', () => {
+ // Signalling after the server has begun closing would race process.exit.
+ expect(code.indexOf('signalDetachedGroups(')).toBeLessThan(code.indexOf('closeAllConnections'));
+ });
+});
diff --git a/server/services/runner.js b/server/services/runner.js
index c55a252090..36a690264c 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -10,7 +10,7 @@ import { resolveSpawnCwd } from '../lib/spawnCwd.js';
import { hasModelFlag, extractBakedModel, isCodexProvider } from '../lib/providerModels.js';
import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
-import { resolveCliSpawn } from '../lib/credentialBootstrap.js';
+import { resolveCliSpawn, needsProcessGroup, processGroupKillable, trackDetachedGroup } from '../lib/credentialBootstrap.js';
import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
import { killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { isHostShuttingDown } from '../lib/hostShutdown.js';
@@ -335,6 +335,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
const stdoutIsResponse = isCodexProvider(provider);
let immediateFallbackAnalysis = null;
let childProcess = null;
+ // True when the child is a credential-bootstrap WRAPPER supervising the real
+ // harness, so every stop/timeout/cancel below must signal the whole process
+ // group rather than the wrapper's pid alone (#7496). Set at spawn time; false
+ // for every unwrapped provider, which keeps their teardown byte-identical.
+ let processGroup = false;
// Set by the wall-clock timeout below so the close handler can classify the
// kill as a timeout instead of scanning the model's output for a category.
let timeoutError = null;
@@ -346,7 +351,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
if (!analysis) return;
immediateFallbackAnalysis = analysis;
console.log(`⚡ Run ${runId} detected fallback signal (${analysis.category}); stopping ${provider.name || provider.id || provider.command}`);
- killProcessTree(childProcess);
+ killProcessTree(childProcess, 'SIGTERM', { processGroup });
};
// Resolve (and log) the working directory before spawning, so a supplied-but-
@@ -417,13 +422,23 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
// still keys off the harness's own command, not the bootstrap CLI's.
const runCommand = vision?.invocation.command || provider.command;
const runCwd = vision?.invocation.cwd || effectiveCwd;
- const { command: spawnCommand, args: spawnArgs } = resolveCliSpawn(provider, runCommand, args, childEnv);
+ const { command: spawnCommand, args: spawnArgs, wrapped } = resolveCliSpawn(provider, runCommand, args, childEnv);
+ processGroup = needsProcessGroup(wrapped);
childProcess = spawn(spawnCommand, spawnArgs, {
cwd: runCwd,
- env: childEnv
+ env: childEnv,
+ // Own process group ONLY for a bootstrap-wrapped spawn — see
+ // needsProcessGroup. Never `unref()`ed: the child must still keep this
+ // run's lifecycle observable exactly as a non-detached one does.
+ detached: processGroup,
});
+ // Remember the detached group so the graceful-shutdown sweep can reach it:
+ // detaching moved this child out of the server's own process group, and a
+ // shutdown driven by a signal to THAT group would otherwise orphan it (#7496).
+ trackDetachedGroup(childProcess, processGroup);
+
// Claim the child's 'error' event in the SAME tick as spawn(). Everything
// between here and the terminal handlers below — stdin delivery, the
// external-run registration, the onRunStarted hook — can throw, and a throw
@@ -450,7 +465,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
// Track active run via the toolkit's declared external-run registry so its
// stopRun/isRunActive/deleteRun account for this host-spawned child process.
- toolkit.services.runner.registerExternalRun(runId, childProcess);
+ // Register a group-aware killable for a wrapped child: the toolkit's own
+ // self-contained killProcessTree has no processGroup option, so /runs Stop
+ // would otherwise signal the wrapper alone (#7496). Unwrapped runs register
+ // the raw ChildProcess exactly as before.
+ toolkit.services.runner.registerExternalRun(runId, processGroupKillable(childProcess, processGroup));
// Call hooks — isolated like every other hook invocation here: a throw would
// otherwise reject executeCliRun with the child already spawned and
@@ -470,7 +489,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc
// leaves `exitCode: null` — not the 124 the TUI runner synthesizes for
// the same condition.
timeoutError = `CLI run timed out after ${effectiveTimeout}ms`;
- killProcessTree(childProcess);
+ killProcessTree(childProcess, 'SIGTERM', { processGroup });
}
}, effectiveTimeout) : null;
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 2fd607d051..60e4fd06fc 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -711,6 +711,134 @@ describe('executeCliRun — credential-bootstrap wrapping', () => {
// after the harness args, the exact mistake the wrap exists to prevent.
expect(args).toEqual(['run', 'claude-code', '--', '-p', '-']);
});
+
+ // #7496. With a bootstrap provider the direct child is the WRAPPER, not the
+ // harness, and nothing obliges it to exec-replace itself. A per-pid SIGTERM
+ // would then leave the harness running — possibly with
+ // `--dangerously-skip-permissions` in a worktree, holding a freshly minted
+ // credential — after the run is finalized and the lane released. These assert
+ // the group reaches it, and that an unwrapped provider is untouched.
+ const bootstrapProvider = (timeout = 5000) => ({
+ id: 'claude',
+ command: 'claude',
+ args: [],
+ timeout,
+ credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' },
+ });
+
+ it('spawns a bootstrap-wrapped child detached, so its process group is signalable', async () => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ setImmediate(() => { child.emit('close', 0); });
+ await executeCliRun({ runId: 'run-bootstrap-detached', provider: bootstrapProvider(), prompt: 'p', workspacePath: TEST_WORKSPACE });
+
+ const [, , options] = spawn.mock.calls.at(-1);
+ expect(options.detached).toBe(true);
+ });
+
+ it('leaves an unwrapped provider attached — its direct child IS the harness', async () => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+
+ setImmediate(() => { child.emit('close', 0); });
+ await executeCliRun({
+ runId: 'run-unwrapped-attached',
+ provider: { id: 'codex', command: 'codex', args: [], timeout: 5000 },
+ prompt: 'p',
+ workspacePath: TEST_WORKSPACE,
+ });
+
+ const [, , options] = spawn.mock.calls.at(-1);
+ expect(options.detached).toBe(false);
+ });
+
+ it('signals the whole process group on timeout for a bootstrap-wrapped run', async () => {
+ // Spy so the negative pid never reaches a real process group.
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = makeChild();
+ child.pid = 424242;
+ spawn.mockReturnValue(child);
+
+ const run = executeCliRun({ runId: 'run-bootstrap-timeout', provider: bootstrapProvider(10), prompt: 'p', workspacePath: TEST_WORKSPACE });
+ await new Promise(resolve => setTimeout(resolve, 60));
+
+ expect(killSpy).toHaveBeenCalledWith(-424242, 'SIGTERM');
+ // The wrapper's own pid is never signalled directly: the group signal
+ // succeeded, so killProcessTree returns without the per-pid fallback.
+ expect(child.kill).not.toHaveBeenCalled();
+
+ child.emit('close', null);
+ await run;
+ killSpy.mockRestore();
+ });
+
+ it('signals only the child pid on timeout for an unwrapped run', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = makeChild();
+ child.pid = 515151;
+ spawn.mockReturnValue(child);
+
+ const run = executeCliRun({
+ runId: 'run-unwrapped-timeout',
+ provider: { id: 'codex', command: 'codex', args: [], timeout: 10 },
+ prompt: 'p',
+ workspacePath: TEST_WORKSPACE,
+ });
+ await new Promise(resolve => setTimeout(resolve, 60));
+
+ expect(killSpy).not.toHaveBeenCalledWith(-515151, expect.anything());
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+
+ child.emit('close', null);
+ await run;
+ killSpy.mockRestore();
+ });
+
+ it('registers a group-aware killable so /runs Stop reaches the harness, not just the wrapper', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const registered = [];
+ const toolkit = fakeToolkit();
+ toolkit.services.runner.registerExternalRun = vi.fn((runId, killable) => registered.push(killable));
+ setAIToolkit(toolkit, { dataDir: '/tmp/test-runner' });
+
+ const child = makeChild();
+ child.pid = 616161;
+ spawn.mockReturnValue(child);
+
+ setImmediate(() => { child.emit('close', 0); });
+ await executeCliRun({ runId: 'run-bootstrap-stop', provider: bootstrapProvider(), prompt: 'p', workspacePath: TEST_WORKSPACE });
+
+ expect(registered).toHaveLength(1);
+ // The toolkit's vendored killProcessTree has no processGroup option and
+ // reaches a non-ChildProcess killable through its own .kill().
+ expect(registered[0]).not.toBe(child);
+ expect(registered[0].pid).toBe(616161);
+ registered[0].kill('SIGTERM');
+ expect(killSpy).toHaveBeenCalledWith(-616161, 'SIGTERM');
+ killSpy.mockRestore();
+ });
+
+ it('registers the raw child for an unwrapped run, unchanged', async () => {
+ const registered = [];
+ const toolkit = fakeToolkit();
+ toolkit.services.runner.registerExternalRun = vi.fn((runId, killable) => registered.push(killable));
+ setAIToolkit(toolkit, { dataDir: '/tmp/test-runner' });
+
+ const child = makeChild();
+ child.pid = 717171;
+ spawn.mockReturnValue(child);
+
+ setImmediate(() => { child.emit('close', 0); });
+ await executeCliRun({
+ runId: 'run-unwrapped-stop',
+ provider: { id: 'codex', command: 'codex', args: [], timeout: 5000 },
+ prompt: 'p',
+ workspacePath: TEST_WORKSPACE,
+ });
+
+ expect(registered).toEqual([child]);
+ });
});
describe('executeCliRun — stdin pipe containment (#5655)', () => {
diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.js
index 474ef7f84c..526a58c2f6 100644
--- a/server/services/tuiPromptRunner.js
+++ b/server/services/tuiPromptRunner.js
@@ -75,7 +75,8 @@ import {
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { isCodexCommand } from '../lib/codex.js';
import { isClaudeCommand } from '../lib/providerModels.js';
-import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
+import { applyCredentialBootstrap, needsProcessGroup, processGroupKillable } from '../lib/credentialBootstrap.js';
+import { killProcessTree } from '../lib/bufferedSpawn.js';
// One-shot defaults that don't apply to the long-running agent path:
// - hard run cap (5 min vs unbounded for agents)
@@ -176,7 +177,23 @@ export async function executeTuiRun({ runId, provider, prompt, screenshots = [],
// bootstrap CLI in front of the harness invocation for a credential-
// bootstrap-configured provider (see credentialBootstrap.js), or an
// identical copy otherwise.
- const { command: spawnCommand, args: spawnArgs } = applyCredentialBootstrap(provider, command, args);
+ const { command: spawnCommand, args: spawnArgs, wrapped } = applyCredentialBootstrap(provider, command, args);
+ // When the wrap applied, the PTY's direct child is the bootstrap WRAPPER and
+ // node-pty's `kill()` signals that pid alone, so a cancel/timeout would leave
+ // the harness running (#7496). forkpty already makes the PTY child a session
+ // leader whose descendants share its process group, so signalling the group is
+ // exact. False — and byte-identical to today — for every unwrapped provider.
+ const processGroup = needsProcessGroup(wrapped);
+ // 'SIGHUP' is node-pty's own POSIX default for `kill()`; naming it explicitly
+ // keeps the signal identical while letting killProcessTree take the group path.
+ const killPty = (target) => killProcessTree(target, 'SIGHUP', { processGroup });
+ // Deliberately NOT `trackDetachedGroup`ed, unlike the headless spawn sites.
+ // That registry exists because `detached: true` moves a child OUT of the
+ // server's process group; forkpty already put this PTY in its own session for
+ // every provider, wrapped or not, so nothing was lost here to restore. Adding
+ // it would instead start killing TUI runs on a host restart that pm2 already
+ // tree-kills — and that `hostShutdown.js` deliberately preserves as
+ // INTERRUPTED for the next boot's recovery rather than terminating (#3202).
const promptDelayMs = provider.tuiPromptDelayMs ?? DEFAULT_TUI_PROMPT_DELAY_MS;
const idleThresholdMs = idleMs ?? provider.tuiOneShotIdleMs ?? DEFAULT_ONE_SHOT_IDLE_MS;
const totalTimeoutMs = timeout ?? provider.timeout ?? DEFAULT_TIMEOUT_MS;
@@ -315,7 +332,10 @@ ${prompt}`;
// tokens with no way to cancel from the UI. Mirrors executeCliRun's
// registration of its ChildProcess; node-pty's IPty exposes the same
// .kill(signal?) interface so the patched stopRun works unchanged.
- registerActiveRun(runId, ptyProcess);
+ // A group-aware killable for a wrapped PTY: the toolkit's own self-contained
+ // killProcessTree has no processGroup option, so /runs Stop would otherwise
+ // signal the wrapper alone. Unwrapped runs register the raw IPty as before.
+ registerActiveRun(runId, processGroupKillable(ptyProcess, processGroup));
// Fire the toolkit's `onRunStarted` hook now that the PTY is alive — the
// CLI/API paths fire it inside the toolkit's executeCliRun/executeApiRun,
@@ -477,7 +497,7 @@ ${prompt}`;
// Kill the PTY if still alive — one-shot runs don't leave a session
// behind for the user to interact with.
- try { if (ptyProcess && !ptyProcess.killed) ptyProcess.kill(); } catch { /* already gone */ }
+ try { if (ptyProcess && !ptyProcess.killed) killPty(ptyProcess); } catch { /* already gone */ }
// Prefer the response file the TUI was directed to write; fall back
// to the ANSI-stripped screen scrape when the file is missing/empty
@@ -519,7 +539,7 @@ ${prompt}`;
// failure we report below rejects executeProviderRunOnce and spins up a
// fallback provider while the original PTY keeps running — two live runs
// for one request. Idempotent: no-op if the kill above already fired.
- try { if (ptyProcess && !ptyProcess.killed) ptyProcess.kill(); } catch { /* already gone */ }
+ try { if (ptyProcess && !ptyProcess.killed) killPty(ptyProcess); } catch { /* already gone */ }
// A step BEFORE onComplete threw, so the caller's onComplete-driven
// settle never fired. executeProviderRunOnce (promptRunner.js) settles
// its OUTER Promise only via onComplete (→ safeReject) or the returned
diff --git a/server/services/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.js
index f548a8f1ca..bf91d0809d 100644
--- a/server/services/tuiPromptRunner.test.js
+++ b/server/services/tuiPromptRunner.test.js
@@ -1608,4 +1608,88 @@ describe('executeTuiRun', () => {
}));
});
});
+
+ // #7496. tuiPromptRunner spawns its OWN PTY directly — no hosting login shell —
+ // so with a credentialBootstrap provider the PTY's direct child is the bootstrap
+ // WRAPPER, and node-pty's `kill()` signals `this.pid` alone. A wrapper that
+ // forks and does not forward the signal keeps the harness alive; node-pty then
+ // never observes an exit, so the pty master never closes and the kernel's
+ // terminal-hangup backstop never fires either. forkpty already makes the PTY
+ // child a session leader whose descendants share its process group, so the group
+ // signal is the exact reach this path needs.
+ describe('executeTuiRun — credential-bootstrap process-group teardown', () => {
+ const bootstrapProvider = {
+ id: 'claude',
+ type: 'tui',
+ command: 'echo',
+ credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' },
+ };
+
+ let killSpy;
+ beforeEach(() => {
+ // Spy so the negative pid never reaches a real process group.
+ killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ });
+ afterEach(() => { killSpy.mockRestore(); });
+
+ it('signals the whole group when finish() tears a wrapped PTY down', async () => {
+ const promise = executeTuiRun({
+ runId: 'run-bootstrap-kill', provider: bootstrapProvider,
+ prompt: 'a prompt long enough to clear the guard', workspacePath: TEST_WORKSPACE, timeout: 60000,
+ });
+ await flushAsync();
+
+ const pty = ptyInstances[0];
+ pty.pid = 212121;
+ expect(ptySpawnMock.mock.calls[0][0]).toBe('token-cli');
+
+ // A non-zero exit drives finish(), whose cleanup kills the PTY.
+ pty.emitExit({ exitCode: 2 });
+ await promise;
+
+ expect(killSpy).toHaveBeenCalledWith(-212121, 'SIGHUP');
+ // The group signal landed, so killProcessTree never falls back to the
+ // handle's own kill — the harness behind the wrapper is covered.
+ expect(pty.kill).not.toHaveBeenCalled();
+ });
+
+ it('leaves an unwrapped PTY on the plain node-pty kill', async () => {
+ const promise = executeTuiRun({
+ runId: 'run-unwrapped-kill', provider: { id: 'claude', type: 'tui', command: 'echo' },
+ prompt: 'a prompt long enough to clear the guard', workspacePath: TEST_WORKSPACE, timeout: 60000,
+ });
+ await flushAsync();
+
+ const pty = ptyInstances[0];
+ pty.pid = 232323;
+ pty.emitExit({ exitCode: 2 });
+ await promise;
+
+ expect(killSpy).not.toHaveBeenCalledWith(-232323, expect.anything());
+ // SIGHUP is node-pty's own POSIX default for a bare kill(), so naming it
+ // keeps this path byte-identical to the previous `ptyProcess.kill()`.
+ expect(pty.kill).toHaveBeenCalledWith('SIGHUP');
+ });
+
+ it('registers a group-aware killable so /runs Stop reaches the harness, not just the wrapper', async () => {
+ const promise = executeTuiRun({
+ runId: 'run-bootstrap-stop', provider: bootstrapProvider,
+ prompt: 'a prompt long enough to clear the guard', workspacePath: TEST_WORKSPACE, timeout: 60000,
+ });
+ await flushAsync();
+
+ const pty = ptyInstances[0];
+ pty.pid = 252525;
+ const [, registered] = runnerMocks.registerActiveRun.mock.calls.at(-1);
+ // The toolkit's vendored killProcessTree has no processGroup option and
+ // reaches a non-ChildProcess killable through its own .kill().
+ expect(registered).not.toBe(pty);
+ expect(registered.pid).toBe(252525);
+ registered.kill('SIGTERM');
+ expect(killSpy).toHaveBeenCalledWith(-252525, 'SIGTERM');
+
+ pty.emitExit({ exitCode: 0 });
+ await promise;
+ });
+ });
});
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index 2a68f13726..4849f792ba 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -33,7 +33,7 @@ import { resolveCliModel, isCodexProvider, buildCodexStartupArgs, buildEffortArg
import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
-import { resolveCliSpawn } from '../lib/credentialBootstrap.js';
+import { resolveCliSpawn, needsProcessGroup, trackDetachedGroup } from '../lib/credentialBootstrap.js';
const CLI_VISION_TIMEOUT_MS = 120000;
const IMAGE_BASENAME = 'vision-input.png';
@@ -247,14 +247,23 @@ async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnIm
// (credentialBootstrap.js) when configured — applied AFTER prepareCliPrompt
// (above), which still keys prompt-delivery convention off the harness's
// own command, not the bootstrap CLI's.
- const { command: spawnCommand, args: spawnArgs } = resolveCliSpawn(provider, command, deliveredArgs, childEnv);
+ const { command: spawnCommand, args: spawnArgs, wrapped } = resolveCliSpawn(provider, command, deliveredArgs, childEnv);
+ // A bootstrap-wrapped child is the WRAPPER supervising the harness, so both
+ // kills below must signal the whole process group (#7496). False — and so
+ // byte-identical to today — for every unwrapped provider.
+ const processGroup = needsProcessGroup(wrapped);
const text = await new Promise((resolve, reject) => {
const child = spawnImpl(spawnCommand, spawnArgs, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
+ detached: processGroup,
});
+ // Remember the detached group so the graceful-shutdown sweep can reach it:
+ // detaching moved this child out of the server's own process group, and a
+ // shutdown driven by a signal to THAT group would otherwise orphan it (#7496).
+ trackDetachedGroup(child, processGroup);
let out = '';
let err = '';
let killTimer = null;
@@ -263,8 +272,8 @@ async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnIm
// the promise would hang forever and the temp dir (cleaned in `finally`)
// would leak. Escalate to SIGKILL on a short grace timer.
const timer = timeout > 0 ? setTimeout(() => {
- if (!child.killed) killProcessTree(child);
- killTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000);
+ if (!child.killed) killProcessTree(child, 'SIGTERM', { processGroup });
+ killTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) killProcessTree(child, 'SIGKILL', { processGroup }); }, 5000);
killTimer?.unref?.();
reject(new Error(`${command} vision call timed out after ${timeout}ms`));
}, timeout) : null;
diff --git a/server/services/visionCli.test.js b/server/services/visionCli.test.js
index 29be3c32e2..893d273a45 100644
--- a/server/services/visionCli.test.js
+++ b/server/services/visionCli.test.js
@@ -321,6 +321,55 @@ describe('describeImageViaCli', () => {
expect(child.kill).toHaveBeenCalledWith('SIGTERM');
});
+ // #7496. With a credentialBootstrap provider the direct child is the user's
+ // bootstrap CLI supervising the harness, not the harness itself, so the
+ // timeout has to signal the whole process group or a wedged vision call
+ // leaves a harness running past the rejection.
+ describe('credential-bootstrap process-group teardown', () => {
+ const bootstrapProvider = {
+ id: 'codex',
+ command: 'codex',
+ args: [],
+ credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' },
+ };
+
+ it('spawns a bootstrap-wrapped child detached, and an unwrapped one attached', async () => {
+ const wrappedChild = makeFakeChild();
+ const wrappedSpawn = spawnEmitting(wrappedChild, (c) => { c.emit('close', 0); });
+ await describeImageViaCli({
+ provider: bootstrapProvider, dataUrl: PNG_DATA_URL, prompt: 'p', spawnImpl: wrappedSpawn,
+ });
+ expect(wrappedSpawn.mock.calls[0][0]).toBe('token-cli');
+ expect(wrappedSpawn.mock.calls[0][2].detached).toBe(true);
+
+ const plainChild = makeFakeChild();
+ const plainSpawn = spawnEmitting(plainChild, (c) => { c.emit('close', 0); });
+ await describeImageViaCli({
+ provider: { id: 'codex', command: 'codex', args: [] },
+ dataUrl: PNG_DATA_URL, prompt: 'p', spawnImpl: plainSpawn,
+ });
+ expect(plainSpawn.mock.calls[0][2].detached).toBe(false);
+ });
+
+ it('signals the whole group on timeout for a wrapped provider', async () => {
+ // Spy so the negative pid never reaches a real process group.
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = makeFakeChild();
+ child.pid = 818181;
+ const promise = describeImageViaCli({
+ provider: bootstrapProvider, dataUrl: PNG_DATA_URL, prompt: 'p', timeout: 20,
+ spawnImpl: vi.fn(() => child),
+ });
+
+ await expect(promise).rejects.toThrow(/timed out after 20ms/);
+ expect(killSpy).toHaveBeenCalledWith(-818181, 'SIGTERM');
+ // The group signal landed, so the per-pid fallback never runs — the
+ // harness behind the wrapper is covered by the same signal.
+ expect(child.kill).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+ });
+
it('contains an EPIPE on stdin from a vision CLI that died before reading the prompt (#5655)', async () => {
// describeImageViaCli runs outside the Express request lifecycle, so an
// unlistened 'error' on the stdin stream would kill the server process