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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/cli/src/services/prompt-processors/shellProcessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,25 @@ describe('ShellProcessor', () => {
]);
});

it('should not report PTY signal 0 as a termination', async () => {
const processor = new ShellProcessor('test-command');
const prompt: PromptPipelineContent =
createPromptPipelineContent('!{cmd}');
mockShellExecute.mockReturnValue({
result: Promise.resolve({
...SUCCESS_RESULT,
output: 'output',
stderr: '',
exitCode: 0,
signal: 0,
}),
});

const result = await processor.process(prompt, context);

expect(result).toEqual([{ text: 'output' }]);
});

it('should throw a detailed error if the shell fails to spawn', async () => {
const processor = new ShellProcessor('test-command');
const prompt: PromptPipelineContent =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
escapeShellArg,
getShellConfiguration,
ShellExecutionService,
isSignalTermination,
flatMapTextParts,
checkArgumentSafety,
} from '@qwen-code/qwen-code-core';
Expand Down Expand Up @@ -218,7 +219,7 @@ export class ShellProcessor implements IPromptProcessor {
executionResult.exitCode !== null
) {
processedPrompt += `\n[Shell command '${injection.resolvedCommand}' exited with code ${executionResult.exitCode}]`;
} else if (executionResult.signal !== null) {
} else if (isSignalTermination(executionResult.signal)) {
processedPrompt += `\n[Shell command '${injection.resolvedCommand}' terminated by signal ${executionResult.signal}]`;
}
}
Expand Down
23 changes: 23 additions & 0 deletions packages/cli/src/ui/hooks/shellCommandProcessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,29 @@ describe('useShellCommandProcessor', () => {
expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
});

it('should treat PTY clean-exit signal 0 as a successful command', async () => {
const { result } = renderProcessorHook();

act(() => {
result.current.handleShellCommand(
'pty-clean-exit',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];

act(() => {
resolveExecutionPromise(createMockServiceResult({ signal: 0 }));
});
await act(async () => await execPromise);

const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
expect(finalHistoryItem.tools[0].status).toBe(ToolCallStatus.Success);
expect(finalHistoryItem.tools[0].resultDisplay).not.toContain(
'terminated by signal',
);
});

describe('UI Streaming and Throttling', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/ui/hooks/shellCommandProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type {
import {
compactToolResultDisplayForHistory,
createDebugLogger,
isSignalTermination,
isBinary,
ShellExecutionService,
} from '@qwen-code/qwen-code-core';
Expand Down Expand Up @@ -288,7 +289,7 @@ export const useShellCommandProcessor = (
} else if (result.aborted) {
finalStatus = ToolCallStatus.Canceled;
finalOutput = `Command was cancelled.\n${finalOutput}`;
} else if (result.signal) {
} else if (isSignalTermination(result.signal)) {
finalStatus = ToolCallStatus.Error;
finalOutput = `Command terminated by signal: ${result.signal}.\n${finalOutput}`;
} else if (result.exitCode !== 0) {
Expand Down
14 changes: 12 additions & 2 deletions packages/core/src/services/shellExecutionService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,15 @@ describe('ShellExecutionService', () => {
});
});

it('normalizes node-pty clean-exit signal 0 to null', async () => {
const { result } = await simulateExecution('echo clean', (pty) => {
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: 0 });
});

expect(result.exitCode).toBe(0);
expect(result.signal).toBeNull();
});

it('disposes PTY terminal resources on natural exit', async () => {
const terminalDisposeSpy = vi.spyOn(Terminal.prototype, 'dispose');
const removeListenerSpy = vi.spyOn(mockPtyProcess, 'removeListener');
Expand Down Expand Up @@ -1051,13 +1060,14 @@ describe('ShellExecutionService', () => {
);
expect(result.promoted).toBe(true);
// After promote, drive the PTY's onExit to simulate natural
// completion. The service attaches a new exit listener for
// completion with its raw clean-exit signal metadata. The service
// attaches a new exit listener for
// post-promote settle — find the most-recently-registered.
const onExitRegistrations = mockPtyProcess.onExit.mock.calls;
expect(onExitRegistrations.length).toBeGreaterThanOrEqual(2);
const postPromoteExitHandler =
onExitRegistrations[onExitRegistrations.length - 1][0];
postPromoteExitHandler({ exitCode: 0, signal: undefined });
postPromoteExitHandler({ exitCode: 0, signal: 0 });
expect(settleCalls).toHaveLength(1);
expect(settleCalls[0].exitCode).toBe(0);
expect(settleCalls[0].signal).toBeNull();
Expand Down
33 changes: 27 additions & 6 deletions packages/core/src/services/shellExecutionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,18 @@ export type ShellAbortReason =
| { kind: 'cancel' }
| { kind: 'background'; shellId?: string };

/**
* Returns true only for a real process-signal termination.
* node-pty reports signal 0 for a clean exit; the service normalizes that
* value to null at its boundary, while this predicate remains defensive for
* legacy or mocked result objects.
*/
export function isSignalTermination(
signal: number | NodeJS.Signals | null,
): boolean {
return signal !== null && signal !== 0;
}

/** A structured result from a shell command execution. */
export interface ShellExecutionResult {
/**
Expand All @@ -161,9 +173,15 @@ export interface ShellExecutionResult {
rawOutput: Buffer;
/** The combined, decoded output as a string. */
output: string;
/** The process exit code, or null if terminated by a signal. */
/**
* The process exit code. Child-process signal termination reports null;
* PTY signal termination may still carry a numeric exit code.
*/
exitCode: number | null;
/** The signal that terminated the process, if any. */
/**
* The non-zero signal that terminated the process, if any. A node-pty
* clean-exit signal of 0 is normalized to null at the service boundary.
*/
signal: number | null;
/** An error object if the process failed to spawn. */
error: Error | null;
Expand Down Expand Up @@ -296,8 +314,11 @@ export interface ShellPostPromoteHandlers {
onData?: (event: ShellOutputEvent) => void;
/**
* Fired exactly once when the post-promote child settles — natural
* exit (`exitCode` set, `signal: null`), signal kill (`exitCode:
* null`, `signal` set), or spawn-side error (`error` set). NOT
* child-process exit (`exitCode` set, `signal: null`), natural PTY
* exit (`exitCode` set, clean-exit signal normalized to `null`), signal kill (which may carry
* `exitCode: 0` with a non-zero signal on PTY, or `exitCode: null`
* with a string signal from `child_process`), or spawn-side error
* (`error` set). NOT
* fired for the promote-time resolve itself (that's the
* `result.promoted` Promise resolution). Callers wire this to the
* registry's `complete` / `fail` transitions.
Expand Down Expand Up @@ -1888,7 +1909,7 @@ export class ShellExecutionService {
rawOutput: finalBuffer,
output: fullOutput,
exitCode,
signal: signal ?? null,
signal: signal === 0 ? null : (signal ?? null),
error,
aborted: abortSignal.aborted,
pid: ptyProcess.pid,
Expand Down Expand Up @@ -2132,7 +2153,7 @@ export class ShellExecutionService {
}) => {
firePostSettle({
exitCode,
signal: signal ?? null,
signal: signal === 0 ? null : (signal ?? null),
endTime: Date.now(),
});
},
Expand Down
Loading
Loading