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

fix: reach the harness behind a credential-bootstrap wrapper on stop/timeout/cancel (#7496)

[._.]/ Adam Eivy6f5d1bcb6771
diff --git a/server/lib/README.md b/server/lib/README.md
index 64588caeb2..4654917f24 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -260,8 +260,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (`PUBLIC_REVIEW_EXECUTION_PROFILE`, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE`, `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE`); `publicReviewPostureForProfile` maps it to the enforceable POSTURE a provider must carry a maintained recipe for (`no-tool` or `sandboxed-actions`), which is how a pipeline stage stays vendor-agnostic. |
| `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. |
+| `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. 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/credentialBootstrap.test.js b/server/lib/credentialBootstrap.test.js
index 621048a032..e6ee993660 100644
--- a/server/lib/credentialBootstrap.test.js
+++ b/server/lib/credentialBootstrap.test.js
@@ -95,14 +95,23 @@ describe('credentialBootstrap', () => {
it.each([PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE])(
'never wraps a %s spawn, even with a bootstrap configured', (safetyProfile) => {
+ // `wrapped: false` matters as much as the argv here: an unwrapped
+ // posture must also keep the unwrapped TEARDOWN, so the enforced recipe
+ // is never spawned detached into a process group of its own (#7496).
expect(applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile })).toEqual({
command: 'claude',
args: ['--restricted'],
+ wrapped: false,
});
expect(resolveCliSpawn(provider, 'claude', ['--restricted'], process.env, { safetyProfile })).toEqual({
command: 'claude',
args: ['--restricted'],
+ wrapped: false,
});
+ expect(needsProcessGroup(
+ applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile }).wrapped,
+ false,
+ )).toBe(false);
});
it('still wraps an ordinary (profile-less or unknown-profile) spawn', () => {
diff --git a/server/lib/streamingSpawn.js b/server/lib/streamingSpawn.js
index 825aba0dba..4e29f7668c 100644
--- a/server/lib/streamingSpawn.js
+++ b/server/lib/streamingSpawn.js
@@ -22,6 +22,8 @@
import { spawn } from './childProcess.js';
import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';
import { createLineReader, createOutputTail } from './streamLines.js';
+import { killProcessTree } from './bufferedSpawn.js';
+import { trackDetachedGroup } from './credentialBootstrap.js';
/**
* How often `isCancelled` is asked. A second is well under human perception for
@@ -34,7 +36,7 @@ const CANCEL_POLL_MS = 1_000;
* @param {string} cmd
* @param {string[]} args
* @param {(line: string) => void} [onLine] - called once per non-empty line
- * @param {{timeoutMs?: number, cwd?: string, env?: object, spawnImpl?: Function, splitRe?: RegExp, isCancelled?: () => boolean}} [options]
+ * @param {{timeoutMs?: number, cwd?: string, env?: object, spawnImpl?: Function, splitRe?: RegExp, isCancelled?: () => boolean, processGroup?: boolean}} [options]
* `timeoutMs: 0` (default) means no timeout. `splitRe` is forwarded to the
* line readers — pass `/[\r\n]+/` for a tool whose progress bar redraws the
* same line with a bare `\r`, so each redraw surfaces instead of the stream
@@ -47,16 +49,26 @@ const CANCEL_POLL_MS = 1_000;
* recurring offender — see `services/vllmQwenManager.js#startVllmQwenProject`)
* gets silently remapped. Audit a new docker-compose target's variable names
* against `lib/ports.js` before assuming the default inheritance is safe.
+ * `processGroup` spawns the child detached and signals its whole group on
+ * timeout/cancel — pass `needsProcessGroup(wrapped)` when the command is a
+ * credential-bootstrap WRAPPER supervising the real harness, which a per-pid
+ * SIGKILL would leave running (#7496). Off by default: for an ordinary
+ * command the direct child IS the thing to kill.
* @returns {Promise<{success: boolean, error?: string}>}
*/
-export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env, spawnImpl = spawn, splitRe, isCancelled } = {}) {
+export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env, spawnImpl = spawn, splitRe, isCancelled, processGroup = false } = {}) {
return new Promise((resolve) => {
const child = spawnImpl(cmd, args, safeChildProcessOptions({
env: env ? safeChildProcessEnv(env) : process.env,
...(cwd ? { cwd } : {}),
shell: false,
stdio: ['ignore', '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 settled = false;
// Recent output, kept so a non-zero exit reports what the tool actually said.
@@ -79,7 +91,7 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env
const timer = timeoutMs > 0
? setTimeout(() => {
- child.kill('SIGKILL');
+ killProcessTree(child, 'SIGKILL', { processGroup });
finish({ success: false, error: `timed out after ${Math.round(timeoutMs / 1000)}s` });
}, timeoutMs)
: null;
@@ -98,7 +110,7 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env
let cancelled = false;
try { cancelled = isCancelled(); } catch (err) { console.error(`⚠️ cancellation check failed for ${cmd}: ${err.message}`); }
if (!cancelled) return;
- child.kill('SIGKILL');
+ killProcessTree(child, 'SIGKILL', { processGroup });
finish({ success: false, error: 'cancelled' });
}, CANCEL_POLL_MS)
: null;
diff --git a/server/lib/streamingSpawn.test.js b/server/lib/streamingSpawn.test.js
index 5480fb109c..7f3c0ee380 100644
--- a/server/lib/streamingSpawn.test.js
+++ b/server/lib/streamingSpawn.test.js
@@ -105,3 +105,51 @@ describe('runStreamingCommand — stream separation', () => {
expect(lines).toContain('ERR-two');
});
});
+
+// #7496. `opencodeTask` hands this helper a credential-bootstrap WRAPPER rather
+// than the harness, and a per-pid SIGKILL reaches only that wrapper — the
+// harness behind it keeps running past the task's timeout or the user's cancel.
+describe('runStreamingCommand — process-group teardown', () => {
+ const SH = '/bin/sh';
+ // A wrapper that outlives its own SIGKILL'd child: `sleep` is a separate
+ // process, so killing only the shell's pid leaves it running. Printing its
+ // pid is what lets the assertion probe the real outcome.
+ const FORKING_WRAPPER = ['-c', 'sleep 30 & echo $!; wait'];
+
+ const probeAlive = (pid) => {
+ // Signal 0 tests for existence without delivering anything.
+ try { process.kill(pid, 0); return true; } catch { return false; }
+ };
+
+ it.skipIf(process.platform === 'win32')('takes the grandchild down with the wrapper on timeout', async () => {
+ let grandchildPid = null;
+ const result = await runStreamingCommand(SH, FORKING_WRAPPER, (line) => {
+ if (grandchildPid === null && /^\d+$/.test(line)) grandchildPid = Number(line);
+ }, { timeoutMs: 300, processGroup: true });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/timed out/);
+ expect(Number.isInteger(grandchildPid)).toBe(true);
+
+ await new Promise(resolve => setTimeout(resolve, 200));
+ const alive = probeAlive(grandchildPid);
+ if (alive) process.kill(grandchildPid, 'SIGKILL');
+ expect(alive).toBe(false);
+ });
+
+ it.skipIf(process.platform === 'win32')('leaves an ordinary command on the per-pid kill', async () => {
+ // Without the flag the grandchild survives — which is correct for every
+ // ordinary caller (an npm install, a model download), whose direct child IS
+ // the process to kill. This is the baseline the test above is measured from.
+ let grandchildPid = null;
+ await runStreamingCommand(SH, FORKING_WRAPPER, (line) => {
+ if (grandchildPid === null && /^\d+$/.test(line)) grandchildPid = Number(line);
+ }, { timeoutMs: 300 });
+
+ await new Promise(resolve => setTimeout(resolve, 200));
+ const alive = probeAlive(grandchildPid);
+ // Clean up regardless — this test deliberately strands a `sleep`.
+ if (alive) process.kill(grandchildPid, 'SIGKILL');
+ expect(alive).toBe(true);
+ });
+});
diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.js
index 5d36e0905f..bb52d88ab8 100644
--- a/server/lib/tuiUsageScrape.js
+++ b/server/lib/tuiUsageScrape.js
@@ -6,6 +6,7 @@ import { stripAnsi } from './ansiStrip.js';
import { sleep } from './fileUtils.js';
import { buildCliChildEnv } from './cliChildEnv.js';
import { SUBMIT_KEY } from './tuiHandshake.js';
+import { killProcessTree } from './bufferedSpawn.js';
/**
* Drive an interactive coding-agent TUI (Antigravity `agy`, Grok Build `grok`)
@@ -91,6 +92,13 @@ export async function scrapeTuiUsage({
idleMs = DEFAULT_IDLE_MS,
renderCapMs = DEFAULT_RENDER_CAP_MS,
timeoutMs = DEFAULT_HARD_TIMEOUT_MS,
+ // True when `command` is a credential-bootstrap WRAPPER rather than the
+ // harness itself. node-pty's `kill()` signals its direct child's pid alone,
+ // so a wrapper that forks would leave the harness rendering into a PTY nobody
+ // reads any more — and this scrape's every exit runs through killPty (#7496).
+ // forkpty already makes the PTY child a session leader whose descendants share
+ // its group, so the group signal is exact.
+ processGroup = false,
} = {}) {
if (!command || typeof command !== 'string') throw new Error('scrapeTuiUsage: command is required');
if (!slashCommand || typeof slashCommand !== 'string') throw new Error('scrapeTuiUsage: slashCommand is required');
@@ -132,7 +140,9 @@ export async function scrapeTuiUsage({
});
pty.onExit(() => { exited = true; });
- const killPty = () => { try { if (!exited) pty.kill(); } catch { /* already gone */ } };
+ // 'SIGHUP' is node-pty's own POSIX default for `kill()`; naming it keeps the
+ // signal identical while letting killProcessTree take the group path.
+ const killPty = () => { try { if (!exited) killProcessTree(pty, 'SIGHUP', { processGroup }); } catch { /* already gone */ } };
// Absolute backstop so a wedged TUI can't hang the request forever.
let hardTimer = null;
diff --git a/server/services/askService.js b/server/services/askService.js
index 2999669874..e7100f5ab1 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -37,8 +37,8 @@ import { isOpenchamberCommand, ensureOpenchamberHeadlessArgs } from '../lib/open
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
-import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
-import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
+import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
+import { applyCredentialBootstrap, needsProcessGroup, trackDetachedGroup } from '../lib/credentialBootstrap.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
import { evaluateSecretEndpoint } from '../lib/aiToolkit/endpointGuard.js';
@@ -548,6 +548,11 @@ async function* streamCompletion(provider, model, prompt, signal) {
// private records, and a bare harness would fall through to the machine's
// ambient vendor auth instead of the backend this provider is configured for.
const bootstrapped = applyCredentialBootstrap(provider, provider.command, deliveredArgs);
+ // A bootstrap-wrapped child is the WRAPPER supervising the harness, so both
+ // stop paths below — the timeout and the user's abort — must signal the whole
+ // process group or the harness keeps running (and keeps reading the private
+ // records this call handed it) past the rejection (#7496).
+ const processGroup = needsProcessGroup(bootstrapped.wrapped);
const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(bootstrapped.command, bootstrapped.args, childEnv);
const out = await new Promise((resolve, reject) => {
let buf = '';
@@ -555,7 +560,12 @@ async function* streamCompletion(provider, model, prompt, signal) {
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
+ 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, the abort listener, and the close
// handler are all racing each other. Without a settled flag, SIGKILL on a
@@ -579,12 +589,12 @@ async function* streamCompletion(provider, model, prompt, signal) {
child.stderr.on('data', (d) => { buf += d.toString(); });
timer = setTimeout(() => {
- child.kill('SIGKILL');
+ killProcessTree(child, 'SIGKILL', { processGroup });
settle(reject, new Error('CLI timed out'));
}, provider.timeout || 300000);
function onAbort() {
- child.kill('SIGKILL');
+ killProcessTree(child, 'SIGKILL', { processGroup });
settle(reject, new Error('aborted'));
}
if (signal) {
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index be370fa060..75ff7d2ace 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -297,6 +297,67 @@ describe('runAsk', () => {
expect(args.slice(0, 3)).toEqual(['run', 'claude-code', '--']);
// The harness's own argv (Ask's model pin) follows the separator.
expect(args.slice(3)).toEqual(expect.arrayContaining(['--model', 'sonnet']));
+ // #7496: the direct child is now the WRAPPER, so both stop paths below (the
+ // timeout and the user's abort) have to reach the harness behind it.
+ expect(spawn.mock.calls[0][2].detached).toBe(true);
+ });
+
+ // #7496. Ask's abort IS the user pressing stop, and it carries private
+ // records — a harness left running past it keeps reading them. A per-pid
+ // SIGKILL reaches only the bootstrap wrapper.
+ it('SIGKILLs the whole process group when the user aborts a bootstrap-wrapped ask', async () => {
+ // Spy so the negative pid never reaches a real process group.
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ providers.getActiveProvider.mockResolvedValue({
+ id: 'claude-code', type: 'cli', enabled: true, command: 'claude', args: [], defaultModel: 'sonnet',
+ credentialBootstrap: { command: 'token-cli', args: ['run'] },
+ });
+ const controller = new AbortController();
+ const kill = vi.fn();
+ spawn.mockImplementation(() => {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 828282,
+ stdout: new EventEmitter(), stderr: new EventEmitter(),
+ stdin: Object.assign(new EventEmitter(), { end: vi.fn() }), kill,
+ });
+ setImmediate(() => controller.abort());
+ return child;
+ });
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'hi', signal: controller.signal })) events.push(evt);
+
+ expect(killSpy).toHaveBeenCalledWith(-828282, 'SIGKILL');
+ // The group signal landed, so killProcessTree never falls back to the
+ // wrapper's own pid — the harness behind it is covered by the same signal.
+ expect(kill).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+
+ it('SIGKILLs only the child when an UNWRAPPED ask is aborted', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ providers.getActiveProvider.mockResolvedValue({
+ id: 'claude-code', type: 'cli', enabled: true, command: 'claude', args: [], defaultModel: 'sonnet',
+ });
+ const controller = new AbortController();
+ const kill = vi.fn();
+ spawn.mockImplementation(() => {
+ const child = Object.assign(new EventEmitter(), {
+ pid: 929292,
+ stdout: new EventEmitter(), stderr: new EventEmitter(),
+ stdin: Object.assign(new EventEmitter(), { end: vi.fn() }), kill,
+ });
+ setImmediate(() => controller.abort());
+ return child;
+ });
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'hi', signal: controller.signal })) events.push(evt);
+
+ expect(spawn.mock.calls[0][2].detached).toBe(false);
+ expect(killSpy).not.toHaveBeenCalledWith(-929292, expect.anything());
+ expect(kill).toHaveBeenCalledWith('SIGKILL');
+ killSpy.mockRestore();
});
it('keeps streamed content and emits an error when the canonical reader fails', async () => {
diff --git a/server/services/modelCapabilityTests.test.js b/server/services/modelCapabilityTests.test.js
index 44aae2b337..f38adc077b 100644
--- a/server/services/modelCapabilityTests.test.js
+++ b/server/services/modelCapabilityTests.test.js
@@ -35,7 +35,12 @@ vi.mock('./providers.js', () => {
});
vi.mock('./ollamaManager.js', () => ({ getModelCapabilities: vi.fn(async () => null) }));
vi.mock('./localLlm.js', () => ({ ollamaBadgeCapabilities: (raw) => raw }));
-vi.mock('../lib/bufferedSpawn.js', () => ({
+// Spread the real module and override only the two entry points this suite
+// drives. A hand-listed mock silently drops everything else — it dropped
+// `IS_WIN32`, which `credentialBootstrap.js` reads for its process-group
+// decision, and every opencode-task case threw on the missing export.
+vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => ({
+ ...(await importOriginal()),
bufferedSpawn: vi.fn(),
prepareCliSpawn: vi.fn((command, args) => ({ command, args })),
}));
diff --git a/server/services/opencodeTask.js b/server/services/opencodeTask.js
index 3f1d3a6cb0..5172f4e41c 100644
--- a/server/services/opencodeTask.js
+++ b/server/services/opencodeTask.js
@@ -20,7 +20,7 @@
import { ServerError } from '../lib/errorHandler.js';
import { runStreamingCommand } from '../lib/streamingSpawn.js';
import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
-import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
+import { applyCredentialBootstrap, needsProcessGroup } from '../lib/credentialBootstrap.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { isOpencodeCommand, prefixOpencodeModel, getOpencodeLocalProviderNamespace } from '../lib/providerModels.js';
import { parseAgentLine } from '../lib/opencodeStream.js';
@@ -86,6 +86,10 @@ export async function runOpencodeTask({ provider, modelId, cwd, prompt, timeoutM
// Credential-bootstrap wrap first (credentialBootstrap.js), then shim resolution.
const bootstrapped = applyCredentialBootstrap(provider, provider.command, args);
const spawnTarget = prepareCliSpawn(bootstrapped.command, bootstrapped.args, env);
+ // A bootstrap-wrapped child is the WRAPPER supervising the harness, so the
+ // timeout and the cancellation poll inside runStreamingCommand must signal
+ // the whole process group or the harness runs on past the task (#7496).
+ const processGroup = needsProcessGroup(bootstrapped.wrapped);
const result = await runStreamingCommand(spawnTarget.command, spawnTarget.args, (line) => {
const event = parseAgentLine(line);
@@ -94,7 +98,7 @@ export async function runOpencodeTask({ provider, modelId, cwd, prompt, timeoutM
// Hook failures are already caught by runStreamingCommand — this runs
// outside the request lifecycle, where a throw would take the process down.
onEvent?.(event);
- }, { cwd, env, timeoutMs, isCancelled: () => signal?.aborted === true });
+ }, { cwd, env, timeoutMs, processGroup, isCancelled: () => signal?.aborted === true });
return { success: result.success, error: result.error || null, events };
}
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 93524313f3..12b809050b 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -6,7 +6,7 @@ import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';
import { commandBasename } from '../lib/providerModels.js';
import { PROVIDER_FAMILIES, familyForProvider } from '../lib/providerFamilies.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
-import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
+import { applyCredentialBootstrap, needsProcessGroup } from '../lib/credentialBootstrap.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
import { parseHumanReset, normalizeResetAt } from '../lib/quotaReset.js';
import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';
@@ -703,7 +703,12 @@ function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name, rea
// credential bootstrap when configured (credentialBootstrap.js), or the
// TUI comes up unauthenticated and never renders a usage panel.
const spawned = applyCredentialBootstrap(provider, command, args);
- const text = await scrapeTuiUsage({ command: spawned.command, args: spawned.args, slashCommand, env, readyMarker });
+ const text = await scrapeTuiUsage({
+ command: spawned.command, args: spawned.args, slashCommand, env, readyMarker,
+ // The scrape kills the PTY on every exit path; with a wrapper in front
+ // that has to reach the harness behind it, not just the wrapper (#7496).
+ processGroup: needsProcessGroup(spawned.wrapped),
+ });
// The panel's reset is relative (agy) or zone-less (grok) — both resolve
// against the read's own clock and the zone the child rendered in.
const { limits, plan } = parse(text, { now: Date.now(), timezone: tz });
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 446ee85b11..d957bc9915 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -435,6 +435,45 @@ describe('getProviderQuotas', () => {
getAllProviders.mockResolvedValueOnce({ activeProvider: null, providers: [] });
expect(await getProviderQuotas({ family: 'grok' })).toEqual([]);
});
+
+ // #7496. The scrape kills its PTY on every exit path, and with a credential
+ // bootstrap the PTY's direct child is the WRAPPER — node-pty's kill() signals
+ // that pid alone, so the harness would go on rendering into a PTY nobody
+ // reads. The flag has to travel from the wrap decision to the scrape.
+ it('asks for a process-group teardown when the scraped command is bootstrap-wrapped', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [{
+ id: 'grok', enabled: true, type: 'tui', command: 'grok',
+ credentialBootstrap: { command: 'token-cli', args: ['run'] },
+ }]
+ });
+ getSettings.mockResolvedValueOnce({});
+ scrapeTuiUsage.mockResolvedValue('Weekly limit: 5% Next reset: Jan 1, 00:00');
+
+ await getProviderQuotas({ family: 'grok' });
+
+ expect(scrapeTuiUsage).toHaveBeenCalledWith(expect.objectContaining({
+ command: 'token-cli',
+ processGroup: true,
+ }));
+ });
+
+ it('leaves an unwrapped scrape on the plain node-pty kill', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [{ id: 'grok', enabled: true, type: 'tui', command: 'grok' }]
+ });
+ getSettings.mockResolvedValueOnce({});
+ scrapeTuiUsage.mockResolvedValue('Weekly limit: 5% Next reset: Jan 1, 00:00');
+
+ await getProviderQuotas({ family: 'grok' });
+
+ expect(scrapeTuiUsage).toHaveBeenCalledWith(expect.objectContaining({
+ command: 'grok',
+ processGroup: false,
+ }));
+ });
});
describe('agyRefreshToIso', () => {