Skip to content
26 changes: 26 additions & 0 deletions packages/core/src/core/coreToolScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,16 @@ export type ExecutingToolCall = {
executionStartTime?: number;
outcome?: ToolConfirmationOutcome;
pid?: number;
/**
* Set during a foreground shell-tool invocation: the AbortController
* the user/UI can fire (with `signal.reason = { kind: 'background' }`)
* to promote the running command to a background entry. Set right
* after `setPidCallback` fires (see ShellTool.execute), cleared
* implicitly when the tool transitions to a terminal status. Only
* meaningful for the shell tool's foreground path; absent on every
* other tool kind.
*/
promoteAbortController?: AbortController;
};

export type CancelledToolCall = {
Expand Down Expand Up @@ -1849,11 +1859,27 @@ export class CoreToolScheduler {
);
this.notifyToolCallsUpdate();
};
// Stash the promote AbortController on the executing tool call so
// a UI surface (PR-3 Ctrl+B keybind) can find the foreground
// shell's promote trigger by callId. Calling `.abort({ kind:
// 'background', shellId })` on it tells `ShellExecutionService`
// to skip the kill, snapshot output, and return
// `result.promoted: true` — `shell.ts` then registers the
// `BackgroundShellEntry`.
const setPromoteAbortControllerCallback = (ac: AbortController) => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
this.toolCalls = this.toolCalls.map((tc) =>
tc.request.callId === callId && tc.status === 'executing'
? { ...tc, promoteAbortController: ac }
: tc,
);
this.notifyToolCallsUpdate();
};
promise = invocation.execute(
signal,
liveOutputCallback,
shellExecutionConfig,
setPidCallback,
setPromoteAbortControllerCallback,
);
} else {
promise = invocation.execute(
Expand Down
13 changes: 9 additions & 4 deletions packages/core/src/services/shellExecutionService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,7 @@ describe('ShellExecutionService', () => {
);
});

it('signal.reason = { kind: "background" } skips kill and resolves with promoted: true', async () => {
it('signal.reason = { kind: "background" } skips kill and resolves with promoted: true (and aborted: false per design question 7)', async () => {
// Critical: do NOT fire onExit — the child is still alive after the
// background-promote abort. The result Promise must resolve via the
// abort handler's own immediate resolve, not via the exit handler.
Expand All @@ -653,7 +653,11 @@ describe('ShellExecutionService', () => {
},
);

expect(result.aborted).toBe(true);
// `aborted: false` (despite signal.aborted = true) is intentional —
// see #3831 design question 7. The flag answers "emit cancel/timeout
// copy?" not "did the signal fire?", and a promoted shell is
// neither cancelled nor timed out.
expect(result.aborted).toBe(false);
expect(result.promoted).toBe(true);
expect(result.exitCode).toBeNull();
expect(result.signal).toBeNull();
Expand Down Expand Up @@ -1410,7 +1414,7 @@ describe('ShellExecutionService child_process fallback', () => {
);
});

it('signal.reason = { kind: "background" } skips kill and resolves with promoted: true', async () => {
it('signal.reason = { kind: "background" } skips kill and resolves with promoted: true (and aborted: false per design question 7)', async () => {
mockPlatform.mockReturnValue('linux');
// Critical: do NOT fire 'exit' — the child is still alive after the
// background-promote abort. The result Promise must resolve via the
Expand All @@ -1427,7 +1431,8 @@ describe('ShellExecutionService child_process fallback', () => {
},
);

expect(result.aborted).toBe(true);
// See PTY equivalent test for the rationale on `aborted: false`.
expect(result.aborted).toBe(false);
expect(result.promoted).toBe(true);
expect(result.exitCode).toBeNull();
expect(result.signal).toBeNull();
Expand Down
28 changes: 26 additions & 2 deletions packages/core/src/services/shellExecutionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,15 @@ export interface ShellExecutionResult {
* alive and the caller has taken over its lifecycle. Callers receiving
* `promoted: true` must NOT treat exitCode/signal as terminal — the
* underlying process has not exited.
*
* Note on the result shape: when `promoted: true`, `aborted` is set to
* `false` even though the AbortSignal fired. The contract is that
* `aborted` answers "should the caller emit a cancel/timeout
* message?" — and a promoted shell is neither cancelled nor timed
* out (the child kept running, ownership simply transferred). This
* lets existing `if (result.aborted)` branches stay unchanged; new
* promote handling lives in a separate `if (result.promoted)` arm.
* Settled in #3831 design question 7 / @tanzhenxin's PR-1 review note.
*/
promoted?: boolean;
/** The process ID of the spawned shell. */
Expand Down Expand Up @@ -699,7 +708,19 @@ export class ShellExecutionService {
exitCode: null,
signal: null,
error: null,
aborted: true,
// `aborted: false` (despite the abort signal having fired) is
// intentional — this is the result-shape decision settled in
// #3831 design question 7 (raised by @tanzhenxin in the PR-1
// review). The flag answers "should the caller emit cancel /
// timeout copy?" not "did the abort signal fire?" — and a
// promoted shell did NOT cancel (the child kept running), so
// existing `if (result.aborted)` branches in callers (e.g.
// `tools/shell.ts`) fall through naturally to the success-shape
// arm where we then check `result.promoted`. Without this,
// every consumer would have to remember to check `promoted`
// before `aborted` to avoid emitting "cancelled" copy for a
// process that's still running.
aborted: false,
promoted: true,
pid: child.pid,
executionMethod: 'child_process',
Expand Down Expand Up @@ -1289,7 +1310,10 @@ export class ShellExecutionService {
exitCode: null,
signal: null,
error,
aborted: true,
// See childProcessFallback for the full rationale — promoted
// results are NOT user-cancellations, so callers' `if
// (result.aborted)` branches must NOT trigger.
aborted: false,
promoted: true,
pid: ptyProcess.pid,
executionMethod:
Expand Down
146 changes: 145 additions & 1 deletion packages/core/src/tools/shell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ vi.mock('os');
vi.mock('crypto');

import { isCommandAllowed } from '../utils/shell-utils.js';
import { ShellTool } from './shell.js';
import { ShellTool, type ShellToolInvocation } from './shell.js';
import { detectBlockedSleepPattern } from './shell.js';
import { stripShellWrapper } from '../utils/shell-utils.js';
import { type Config } from '../config/config.js';
Expand Down Expand Up @@ -1594,6 +1594,150 @@ describe('ShellTool', () => {
);
});
});

describe('foreground → background promote (#3831 PR-2)', () => {
it('exposes a promote AbortController via setPromoteAbortControllerCallback', async () => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
const setPromoteAc = vi.fn();
const invocation = shellTool.build({
command: 'npm run dev',
is_background: false,
});
// Cast to the concrete invocation type to access the extra
// ShellTool-specific execute() params (setPidCallback +
// setPromoteAbortControllerCallback) — the base ToolInvocation
// type only has the 3-param signature shared across all tools.
const promise = (invocation as ShellToolInvocation).execute(
mockAbortSignal,
undefined,
{},
undefined,
setPromoteAc,
);
resolveShellExecution({ pid: 12345 });
await promise;

// Called once, with an AbortController whose signal is wired
// into the combined signal handed to ShellExecutionService.
expect(setPromoteAc).toHaveBeenCalledTimes(1);
const passedAc = setPromoteAc.mock.calls[0][0] as AbortController;
expect(passedAc).toBeInstanceOf(AbortController);
});

it('registers a bg_xxx entry on `result.promoted: true` and returns promote-flavored ToolResult', async () => {
const writeFileSyncSpy = vi.mocked(fs.writeFileSync);
writeFileSyncSpy.mockReturnValue(undefined);
const registry = mockConfig.getBackgroundShellRegistry();
const invocation = shellTool.build({
command: 'tail -f /tmp/never.log',
is_background: false,
});
const promise = invocation.execute(mockAbortSignal);
// Service signals promote: snapshot ready, child still alive.
resolveShellExecution({
output: 'partial output before promote',
exitCode: null,
signal: null,
aborted: false, // ← per #3831 design question 7
promoted: true,
pid: 99999,
});
const result = await promise;

// Entry registered with the spawn pid + promote AbortController.
expect(registry.register).toHaveBeenCalledTimes(1);
const entry = (registry.register as Mock).mock.calls[0][0];
expect(entry.command).toBe('tail -f /tmp/never.log');
expect(entry.cwd).toBe('/test/dir');
expect(entry.status).toBe('running');
expect(entry.pid).toBe(99999);
expect(entry.shellId).toMatch(/^bg_/);
expect(entry.outputPath).toContain(entry.shellId);
expect(entry.abortController).toBeInstanceOf(AbortController);

// Snapshot written to disk.
expect(writeFileSyncSpy).toHaveBeenCalledWith(
entry.outputPath,
'partial output before promote',
);

// Model-facing copy points at /tasks / dialog / task_stop.
expect(result.llmContent).toContain(
`promoted to background as ${entry.shellId}`,
);
expect(result.llmContent).toContain(`PID: 99999`);
expect(result.llmContent).toContain('/tasks');
expect(result.llmContent).toContain(
`task_stop({ task_id: '${entry.shellId}'`,
);
expect(result.returnDisplay).toContain(
`Promoted to background: ${entry.shellId}`,
);
// No `error` on the result — promote is a success-shaped outcome
// per #3831 design question 7 / @tanzhenxin's PR-1 review.
expect(result.error).toBeUndefined();
});

it("entry.abortController is a FRESH controller (not the already-aborted promote controller) so task_stop's abort() actually fires kill listeners", async () => {
// Real-bug regression: if `entry.abortController` were the
// same `promoteAbortController` that triggered the promote,
// it would already be in the `aborted: true` state by the time
// it landed in the registry. `task_stop bg_xxx` calls
// `entry.abortController.abort()` which is a no-op on an
// already-aborted controller, AND `ShellExecutionService` has
// detached its abort listener as part of the promote handoff,
// so the still-running child would survive task_stop forever.
// Pin: entry.abortController.signal.aborted === false at
// registration.
const writeFileSyncSpy = vi.mocked(fs.writeFileSync);
writeFileSyncSpy.mockReturnValue(undefined);
const registry = mockConfig.getBackgroundShellRegistry();
const invocation = shellTool.build({
command: 'tail -f /tmp/never.log',
is_background: false,
});
const promise = invocation.execute(mockAbortSignal);
resolveShellExecution({
output: '',
exitCode: null,
signal: null,
aborted: false,
promoted: true,
pid: 77777,
});
await promise;

const entry = (registry.register as Mock).mock.calls[0][0];
expect(entry.abortController.signal.aborted).toBe(false);
});

it('survives a snapshot write failure — registry entry still registered', async () => {
const writeFileSyncSpy = vi.mocked(fs.writeFileSync);
writeFileSyncSpy.mockImplementation(() => {
throw new Error('ENOSPC: no space left on device');
});
const registry = mockConfig.getBackgroundShellRegistry();
const invocation = shellTool.build({
command: 'tail -f /tmp/never.log',
is_background: false,
});
const promise = invocation.execute(mockAbortSignal);
resolveShellExecution({
output: 'pre-promote',
exitCode: null,
signal: null,
aborted: false,
promoted: true,
pid: 88888,
});
const result = await promise;

// The disk write failure is logged + swallowed: the entry is
// still valuable on its own; the file is the inspection
// surface, not the source of truth.
expect(registry.register).toHaveBeenCalledTimes(1);
expect(result.llmContent).toContain('promoted to background');
});
});
});

describe('getDefaultPermission and getConfirmationDetails', () => {
Expand Down
Loading
Loading