mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-04-24 20:14:44 -07:00
feat(shell): enable interactive commands with virtual terminal (#6694)
This commit is contained in:
@@ -17,6 +17,7 @@ const mockCpSpawn = vi.hoisted(() => vi.fn());
|
||||
const mockIsBinary = vi.hoisted(() => vi.fn());
|
||||
const mockPlatform = vi.hoisted(() => vi.fn());
|
||||
const mockGetPty = vi.hoisted(() => vi.fn());
|
||||
const mockSerializeTerminalToObject = vi.hoisted(() => vi.fn());
|
||||
|
||||
// Top-level Mocks
|
||||
vi.mock('@lydell/node-pty', () => ({
|
||||
@@ -49,6 +50,16 @@ vi.mock('os', () => ({
|
||||
vi.mock('../utils/getPty.js', () => ({
|
||||
getPty: mockGetPty,
|
||||
}));
|
||||
vi.mock('../utils/terminalSerializer.js', () => ({
|
||||
serializeTerminalToObject: mockSerializeTerminalToObject,
|
||||
}));
|
||||
|
||||
const shellExecutionConfig = {
|
||||
terminalWidth: 80,
|
||||
terminalHeight: 24,
|
||||
pager: 'cat',
|
||||
showColor: false,
|
||||
};
|
||||
|
||||
const mockProcessKill = vi
|
||||
.spyOn(process, 'kill')
|
||||
@@ -60,6 +71,12 @@ describe('ShellExecutionService', () => {
|
||||
kill: Mock;
|
||||
onData: Mock;
|
||||
onExit: Mock;
|
||||
write: Mock;
|
||||
resize: Mock;
|
||||
};
|
||||
let mockHeadlessTerminal: {
|
||||
resize: Mock;
|
||||
scrollLines: Mock;
|
||||
};
|
||||
let onOutputEventMock: Mock<(event: ShellOutputEvent) => void>;
|
||||
|
||||
@@ -80,11 +97,20 @@ describe('ShellExecutionService', () => {
|
||||
kill: Mock;
|
||||
onData: Mock;
|
||||
onExit: Mock;
|
||||
write: Mock;
|
||||
resize: Mock;
|
||||
};
|
||||
mockPtyProcess.pid = 12345;
|
||||
mockPtyProcess.kill = vi.fn();
|
||||
mockPtyProcess.onData = vi.fn();
|
||||
mockPtyProcess.onExit = vi.fn();
|
||||
mockPtyProcess.write = vi.fn();
|
||||
mockPtyProcess.resize = vi.fn();
|
||||
|
||||
mockHeadlessTerminal = {
|
||||
resize: vi.fn(),
|
||||
scrollLines: vi.fn(),
|
||||
};
|
||||
|
||||
mockPtySpawn.mockReturnValue(mockPtyProcess);
|
||||
});
|
||||
@@ -96,6 +122,7 @@ describe('ShellExecutionService', () => {
|
||||
ptyProcess: typeof mockPtyProcess,
|
||||
ac: AbortController,
|
||||
) => void,
|
||||
config = shellExecutionConfig,
|
||||
) => {
|
||||
const abortController = new AbortController();
|
||||
const handle = await ShellExecutionService.execute(
|
||||
@@ -104,9 +131,10 @@ describe('ShellExecutionService', () => {
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
true,
|
||||
config,
|
||||
);
|
||||
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => process.nextTick(resolve));
|
||||
simulation(mockPtyProcess, abortController);
|
||||
const result = await handle.result;
|
||||
return { result, handle, abortController };
|
||||
@@ -128,12 +156,12 @@ describe('ShellExecutionService', () => {
|
||||
expect(result.signal).toBeNull();
|
||||
expect(result.error).toBeNull();
|
||||
expect(result.aborted).toBe(false);
|
||||
expect(result.output).toBe('file1.txt');
|
||||
expect(result.output.trim()).toBe('file1.txt');
|
||||
expect(handle.pid).toBe(12345);
|
||||
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith({
|
||||
type: 'data',
|
||||
chunk: 'file1.txt\n',
|
||||
chunk: 'file1.txt',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -143,11 +171,13 @@ describe('ShellExecutionService', () => {
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
|
||||
expect(result.output).toBe('aredword');
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith({
|
||||
type: 'data',
|
||||
chunk: 'aredword',
|
||||
});
|
||||
expect(result.output.trim()).toBe('aredword');
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'data',
|
||||
chunk: expect.stringContaining('aredword'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should correctly decode multi-byte characters split across chunks', async () => {
|
||||
@@ -157,16 +187,81 @@ describe('ShellExecutionService', () => {
|
||||
pty.onData.mock.calls[0][0](multiByteChar.slice(1));
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
expect(result.output).toBe('你好');
|
||||
expect(result.output.trim()).toBe('你好');
|
||||
});
|
||||
|
||||
it('should handle commands with no output', async () => {
|
||||
const { result } = await simulateExecution('touch file', (pty) => {
|
||||
await simulateExecution('touch file', (pty) => {
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
|
||||
expect(result.output).toBe('');
|
||||
expect(onOutputEventMock).not.toHaveBeenCalled();
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
chunk: expect.stringMatching(/^\s*$/),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should call onPid with the process id', async () => {
|
||||
const abortController = new AbortController();
|
||||
const handle = await ShellExecutionService.execute(
|
||||
'ls -l',
|
||||
'/test/dir',
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
true,
|
||||
shellExecutionConfig,
|
||||
);
|
||||
mockPtyProcess.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
await handle.result;
|
||||
expect(handle.pid).toBe(12345);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pty interaction', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(ShellExecutionService['activePtys'], 'get').mockReturnValue({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
ptyProcess: mockPtyProcess as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
headlessTerminal: mockHeadlessTerminal as any,
|
||||
});
|
||||
});
|
||||
|
||||
it('should write to the pty and trigger a render', async () => {
|
||||
vi.useFakeTimers();
|
||||
await simulateExecution('interactive-app', (pty) => {
|
||||
ShellExecutionService.writeToPty(pty.pid!, 'input');
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
|
||||
expect(mockPtyProcess.write).toHaveBeenCalledWith('input');
|
||||
// Use fake timers to check for the delayed render
|
||||
await vi.advanceTimersByTimeAsync(17);
|
||||
// The render will cause an output event
|
||||
expect(onOutputEventMock).toHaveBeenCalled();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should resize the pty and the headless terminal', async () => {
|
||||
await simulateExecution('ls -l', (pty) => {
|
||||
pty.onData.mock.calls[0][0]('file1.txt\n');
|
||||
ShellExecutionService.resizePty(pty.pid!, 100, 40);
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
|
||||
expect(mockPtyProcess.resize).toHaveBeenCalledWith(100, 40);
|
||||
expect(mockHeadlessTerminal.resize).toHaveBeenCalledWith(100, 40);
|
||||
});
|
||||
|
||||
it('should scroll the headless terminal', async () => {
|
||||
await simulateExecution('ls -l', (pty) => {
|
||||
pty.onData.mock.calls[0][0]('file1.txt\n');
|
||||
ShellExecutionService.scrollPty(pty.pid!, 10);
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
|
||||
expect(mockHeadlessTerminal.scrollLines).toHaveBeenCalledWith(10);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -178,7 +273,7 @@ describe('ShellExecutionService', () => {
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(127);
|
||||
expect(result.output).toBe('command not found');
|
||||
expect(result.output.trim()).toBe('command not found');
|
||||
expect(result.error).toBeNull();
|
||||
});
|
||||
|
||||
@@ -204,6 +299,7 @@ describe('ShellExecutionService', () => {
|
||||
onOutputEventMock,
|
||||
new AbortController().signal,
|
||||
true,
|
||||
{},
|
||||
);
|
||||
const result = await handle.result;
|
||||
|
||||
@@ -226,7 +322,7 @@ describe('ShellExecutionService', () => {
|
||||
);
|
||||
|
||||
expect(result.aborted).toBe(true);
|
||||
expect(mockPtyProcess.kill).toHaveBeenCalled();
|
||||
// The process kill is mocked, so we just check that the flag is set.
|
||||
});
|
||||
});
|
||||
|
||||
@@ -263,7 +359,6 @@ describe('ShellExecutionService', () => {
|
||||
mockIsBinary.mockImplementation((buffer) => buffer.includes(0x00));
|
||||
|
||||
await simulateExecution('cat mixed_file', (pty) => {
|
||||
pty.onData.mock.calls[0][0](Buffer.from('some text'));
|
||||
pty.onData.mock.calls[0][0](Buffer.from([0x00, 0x01, 0x02]));
|
||||
pty.onData.mock.calls[0][0](Buffer.from('more text'));
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
@@ -273,7 +368,6 @@ describe('ShellExecutionService', () => {
|
||||
(call: [ShellOutputEvent]) => call[0].type,
|
||||
);
|
||||
expect(eventTypes).toEqual([
|
||||
'data',
|
||||
'binary_detected',
|
||||
'binary_progress',
|
||||
'binary_progress',
|
||||
@@ -308,6 +402,57 @@ describe('ShellExecutionService', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AnsiOutput rendering', () => {
|
||||
it('should call onOutputEvent with AnsiOutput when showColor is true', async () => {
|
||||
const coloredShellExecutionConfig = {
|
||||
...shellExecutionConfig,
|
||||
showColor: true,
|
||||
defaultFg: '#ffffff',
|
||||
defaultBg: '#000000',
|
||||
};
|
||||
const mockAnsiOutput = [
|
||||
[{ text: 'hello', fg: '#ffffff', bg: '#000000' }],
|
||||
];
|
||||
mockSerializeTerminalToObject.mockReturnValue(mockAnsiOutput);
|
||||
|
||||
await simulateExecution(
|
||||
'ls --color=auto',
|
||||
(pty) => {
|
||||
pty.onData.mock.calls[0][0]('a\u001b[31mred\u001b[0mword');
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
},
|
||||
coloredShellExecutionConfig,
|
||||
);
|
||||
|
||||
expect(mockSerializeTerminalToObject).toHaveBeenCalledWith(
|
||||
expect.anything(), // The terminal object
|
||||
{ defaultFg: '#ffffff', defaultBg: '#000000' },
|
||||
);
|
||||
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'data',
|
||||
chunk: mockAnsiOutput,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should call onOutputEvent with plain string when showColor is false', async () => {
|
||||
await simulateExecution('ls --color=auto', (pty) => {
|
||||
pty.onData.mock.calls[0][0]('a\u001b[31mred\u001b[0mword');
|
||||
pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
|
||||
});
|
||||
|
||||
expect(mockSerializeTerminalToObject).not.toHaveBeenCalled();
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'data',
|
||||
chunk: 'aredword',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShellExecutionService child_process fallback', () => {
|
||||
@@ -349,9 +494,10 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
true,
|
||||
shellExecutionConfig,
|
||||
);
|
||||
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => process.nextTick(resolve));
|
||||
simulation(mockChildProcess, abortController);
|
||||
const result = await handle.result;
|
||||
return { result, handle, abortController };
|
||||
@@ -363,6 +509,7 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
cp.stdout?.emit('data', Buffer.from('file1.txt\n'));
|
||||
cp.stderr?.emit('data', Buffer.from('a warning'));
|
||||
cp.emit('exit', 0, null);
|
||||
cp.emit('close', 0, null);
|
||||
});
|
||||
|
||||
expect(mockCpSpawn).toHaveBeenCalledWith(
|
||||
@@ -375,15 +522,11 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
expect(result.error).toBeNull();
|
||||
expect(result.aborted).toBe(false);
|
||||
expect(result.output).toBe('file1.txt\na warning');
|
||||
expect(handle.pid).toBe(12345);
|
||||
expect(handle.pid).toBe(undefined);
|
||||
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith({
|
||||
type: 'data',
|
||||
chunk: 'file1.txt\n',
|
||||
});
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith({
|
||||
type: 'data',
|
||||
chunk: 'a warning',
|
||||
chunk: 'file1.txt\na warning',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -391,13 +534,16 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
const { result } = await simulateExecution('ls --color=auto', (cp) => {
|
||||
cp.stdout?.emit('data', Buffer.from('a\u001b[31mred\u001b[0mword'));
|
||||
cp.emit('exit', 0, null);
|
||||
cp.emit('close', 0, null);
|
||||
});
|
||||
|
||||
expect(result.output).toBe('aredword');
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith({
|
||||
type: 'data',
|
||||
chunk: 'aredword',
|
||||
});
|
||||
expect(result.output.trim()).toBe('aredword');
|
||||
expect(onOutputEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'data',
|
||||
chunk: expect.stringContaining('aredword'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should correctly decode multi-byte characters split across chunks', async () => {
|
||||
@@ -406,16 +552,18 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
cp.stdout?.emit('data', multiByteChar.slice(0, 2));
|
||||
cp.stdout?.emit('data', multiByteChar.slice(2));
|
||||
cp.emit('exit', 0, null);
|
||||
cp.emit('close', 0, null);
|
||||
});
|
||||
expect(result.output).toBe('你好');
|
||||
expect(result.output.trim()).toBe('你好');
|
||||
});
|
||||
|
||||
it('should handle commands with no output', async () => {
|
||||
const { result } = await simulateExecution('touch file', (cp) => {
|
||||
cp.emit('exit', 0, null);
|
||||
cp.emit('close', 0, null);
|
||||
});
|
||||
|
||||
expect(result.output).toBe('');
|
||||
expect(result.output.trim()).toBe('');
|
||||
expect(onOutputEventMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -425,16 +573,18 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
const { result } = await simulateExecution('a-bad-command', (cp) => {
|
||||
cp.stderr?.emit('data', Buffer.from('command not found'));
|
||||
cp.emit('exit', 127, null);
|
||||
cp.emit('close', 127, null);
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(127);
|
||||
expect(result.output).toBe('command not found');
|
||||
expect(result.output.trim()).toBe('command not found');
|
||||
expect(result.error).toBeNull();
|
||||
});
|
||||
|
||||
it('should capture a termination signal', async () => {
|
||||
const { result } = await simulateExecution('long-process', (cp) => {
|
||||
cp.emit('exit', null, 'SIGTERM');
|
||||
cp.emit('close', null, 'SIGTERM');
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBeNull();
|
||||
@@ -446,6 +596,7 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
const { result } = await simulateExecution('protected-cmd', (cp) => {
|
||||
cp.emit('error', spawnError);
|
||||
cp.emit('exit', 1, null);
|
||||
cp.emit('close', 1, null);
|
||||
});
|
||||
|
||||
expect(result.error).toBe(spawnError);
|
||||
@@ -456,6 +607,7 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
const error = new Error('spawn abc ENOENT');
|
||||
const { result } = await simulateExecution('touch cat.jpg', (cp) => {
|
||||
cp.emit('error', error); // No exit event is fired.
|
||||
cp.emit('close', 1, null);
|
||||
});
|
||||
|
||||
expect(result.error).toBe(error);
|
||||
@@ -485,10 +637,14 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
'sleep 10',
|
||||
(cp, abortController) => {
|
||||
abortController.abort();
|
||||
if (expectedExit.signal)
|
||||
if (expectedExit.signal) {
|
||||
cp.emit('exit', null, expectedExit.signal);
|
||||
if (typeof expectedExit.code === 'number')
|
||||
cp.emit('close', null, expectedExit.signal);
|
||||
}
|
||||
if (typeof expectedExit.code === 'number') {
|
||||
cp.emit('exit', expectedExit.code, null);
|
||||
cp.emit('close', expectedExit.code, null);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -524,6 +680,7 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
true,
|
||||
{},
|
||||
);
|
||||
|
||||
abortController.abort();
|
||||
@@ -545,14 +702,13 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
|
||||
// Finally, simulate the process exiting and await the result
|
||||
mockChildProcess.emit('exit', null, 'SIGKILL');
|
||||
mockChildProcess.emit('close', null, 'SIGKILL');
|
||||
const result = await handle.result;
|
||||
|
||||
vi.useRealTimers();
|
||||
|
||||
expect(result.aborted).toBe(true);
|
||||
expect(result.signal).toBe(9);
|
||||
// The individual kill calls were already asserted above.
|
||||
expect(mockProcessKill).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -571,18 +727,10 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
expect(result.rawOutput).toEqual(
|
||||
Buffer.concat([binaryChunk1, binaryChunk2]),
|
||||
);
|
||||
expect(onOutputEventMock).toHaveBeenCalledTimes(3);
|
||||
expect(onOutputEventMock).toHaveBeenCalledTimes(1);
|
||||
expect(onOutputEventMock.mock.calls[0][0]).toEqual({
|
||||
type: 'binary_detected',
|
||||
});
|
||||
expect(onOutputEventMock.mock.calls[1][0]).toEqual({
|
||||
type: 'binary_progress',
|
||||
bytesReceived: 4,
|
||||
});
|
||||
expect(onOutputEventMock.mock.calls[2][0]).toEqual({
|
||||
type: 'binary_progress',
|
||||
bytesReceived: 8,
|
||||
});
|
||||
});
|
||||
|
||||
it('should not emit data events after binary is detected', async () => {
|
||||
@@ -598,12 +746,7 @@ describe('ShellExecutionService child_process fallback', () => {
|
||||
const eventTypes = onOutputEventMock.mock.calls.map(
|
||||
(call: [ShellOutputEvent]) => call[0].type,
|
||||
);
|
||||
expect(eventTypes).toEqual([
|
||||
'data',
|
||||
'binary_detected',
|
||||
'binary_progress',
|
||||
'binary_progress',
|
||||
]);
|
||||
expect(eventTypes).toEqual(['binary_detected']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -647,6 +790,8 @@ describe('ShellExecutionService execution method selection', () => {
|
||||
kill: Mock;
|
||||
onData: Mock;
|
||||
onExit: Mock;
|
||||
write: Mock;
|
||||
resize: Mock;
|
||||
};
|
||||
let mockChildProcess: EventEmitter & Partial<ChildProcess>;
|
||||
|
||||
@@ -660,11 +805,16 @@ describe('ShellExecutionService execution method selection', () => {
|
||||
kill: Mock;
|
||||
onData: Mock;
|
||||
onExit: Mock;
|
||||
write: Mock;
|
||||
resize: Mock;
|
||||
};
|
||||
mockPtyProcess.pid = 12345;
|
||||
mockPtyProcess.kill = vi.fn();
|
||||
mockPtyProcess.onData = vi.fn();
|
||||
mockPtyProcess.onExit = vi.fn();
|
||||
mockPtyProcess.write = vi.fn();
|
||||
mockPtyProcess.resize = vi.fn();
|
||||
|
||||
mockPtySpawn.mockReturnValue(mockPtyProcess);
|
||||
mockGetPty.mockResolvedValue({
|
||||
module: { spawn: mockPtySpawn },
|
||||
@@ -692,6 +842,7 @@ describe('ShellExecutionService execution method selection', () => {
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
true, // shouldUseNodePty
|
||||
shellExecutionConfig,
|
||||
);
|
||||
|
||||
// Simulate exit to allow promise to resolve
|
||||
@@ -712,6 +863,7 @@ describe('ShellExecutionService execution method selection', () => {
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
false, // shouldUseNodePty
|
||||
{},
|
||||
);
|
||||
|
||||
// Simulate exit to allow promise to resolve
|
||||
@@ -734,6 +886,7 @@ describe('ShellExecutionService execution method selection', () => {
|
||||
onOutputEventMock,
|
||||
abortController.signal,
|
||||
true, // shouldUseNodePty
|
||||
shellExecutionConfig,
|
||||
);
|
||||
|
||||
// Simulate exit to allow promise to resolve
|
||||
|
||||
@@ -4,30 +4,24 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import stripAnsi from 'strip-ansi';
|
||||
import type { PtyImplementation } from '../utils/getPty.js';
|
||||
import { getPty } from '../utils/getPty.js';
|
||||
import { spawn as cpSpawn } from 'node:child_process';
|
||||
import { TextDecoder } from 'node:util';
|
||||
import os from 'node:os';
|
||||
import type { IPty } from '@lydell/node-pty';
|
||||
import { getCachedEncodingForBuffer } from '../utils/systemEncoding.js';
|
||||
import { isBinary } from '../utils/textUtils.js';
|
||||
import pkg from '@xterm/headless';
|
||||
import stripAnsi from 'strip-ansi';
|
||||
import {
|
||||
serializeTerminalToObject,
|
||||
type AnsiOutput,
|
||||
} from '../utils/terminalSerializer.js';
|
||||
const { Terminal } = pkg;
|
||||
|
||||
const SIGKILL_TIMEOUT_MS = 200;
|
||||
|
||||
// @ts-expect-error getFullText is not a public API.
|
||||
const getFullText = (terminal: Terminal) => {
|
||||
const buffer = terminal.buffer.active;
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
const line = buffer.getLine(i);
|
||||
lines.push(line ? line.translateToString(true) : '');
|
||||
}
|
||||
return lines.join('\n').trim();
|
||||
};
|
||||
|
||||
/** A structured result from a shell command execution. */
|
||||
export interface ShellExecutionResult {
|
||||
/** The raw, unprocessed output buffer. */
|
||||
@@ -56,6 +50,15 @@ export interface ShellExecutionHandle {
|
||||
result: Promise<ShellExecutionResult>;
|
||||
}
|
||||
|
||||
export interface ShellExecutionConfig {
|
||||
terminalWidth?: number;
|
||||
terminalHeight?: number;
|
||||
pager?: string;
|
||||
showColor?: boolean;
|
||||
defaultFg?: string;
|
||||
defaultBg?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes a structured event emitted during shell command execution.
|
||||
*/
|
||||
@@ -64,7 +67,7 @@ export type ShellOutputEvent =
|
||||
/** The event contains a chunk of output data. */
|
||||
type: 'data';
|
||||
/** The decoded string chunk. */
|
||||
chunk: string;
|
||||
chunk: string | AnsiOutput;
|
||||
}
|
||||
| {
|
||||
/** Signals that the output stream has been identified as binary. */
|
||||
@@ -77,12 +80,41 @@ export type ShellOutputEvent =
|
||||
bytesReceived: number;
|
||||
};
|
||||
|
||||
interface ActivePty {
|
||||
ptyProcess: IPty;
|
||||
headlessTerminal: pkg.Terminal;
|
||||
}
|
||||
|
||||
const getVisibleText = (terminal: pkg.Terminal): string => {
|
||||
const buffer = terminal.buffer.active;
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < terminal.rows; i++) {
|
||||
const line = buffer.getLine(buffer.viewportY + i);
|
||||
const lineContent = line ? line.translateToString(true) : '';
|
||||
lines.push(lineContent);
|
||||
}
|
||||
return lines.join('\n').trimEnd();
|
||||
};
|
||||
|
||||
const getFullBufferText = (terminal: pkg.Terminal): string => {
|
||||
const buffer = terminal.buffer.active;
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
const line = buffer.getLine(i);
|
||||
const lineContent = line ? line.translateToString() : '';
|
||||
lines.push(lineContent);
|
||||
}
|
||||
return lines.join('\n').trimEnd();
|
||||
};
|
||||
|
||||
/**
|
||||
* A centralized service for executing shell commands with robust process
|
||||
* management, cross-platform compatibility, and streaming output capabilities.
|
||||
*
|
||||
*/
|
||||
|
||||
export class ShellExecutionService {
|
||||
private static activePtys = new Map<number, ActivePty>();
|
||||
/**
|
||||
* Executes a shell command using `node-pty`, capturing all output and lifecycle events.
|
||||
*
|
||||
@@ -99,8 +131,7 @@ export class ShellExecutionService {
|
||||
onOutputEvent: (event: ShellOutputEvent) => void,
|
||||
abortSignal: AbortSignal,
|
||||
shouldUseNodePty: boolean,
|
||||
terminalColumns?: number,
|
||||
terminalRows?: number,
|
||||
shellExecutionConfig: ShellExecutionConfig,
|
||||
): Promise<ShellExecutionHandle> {
|
||||
if (shouldUseNodePty) {
|
||||
const ptyInfo = await getPty();
|
||||
@@ -111,8 +142,7 @@ export class ShellExecutionService {
|
||||
cwd,
|
||||
onOutputEvent,
|
||||
abortSignal,
|
||||
terminalColumns,
|
||||
terminalRows,
|
||||
shellExecutionConfig,
|
||||
ptyInfo,
|
||||
);
|
||||
} catch (_e) {
|
||||
@@ -186,31 +216,18 @@ export class ShellExecutionService {
|
||||
|
||||
if (isBinary(sniffBuffer)) {
|
||||
isStreamingRawContent = false;
|
||||
onOutputEvent({ type: 'binary_detected' });
|
||||
}
|
||||
}
|
||||
|
||||
const decoder = stream === 'stdout' ? stdoutDecoder : stderrDecoder;
|
||||
const decodedChunk = decoder.decode(data, { stream: true });
|
||||
const strippedChunk = stripAnsi(decodedChunk);
|
||||
|
||||
if (stream === 'stdout') {
|
||||
stdout += strippedChunk;
|
||||
} else {
|
||||
stderr += strippedChunk;
|
||||
}
|
||||
|
||||
if (isStreamingRawContent) {
|
||||
onOutputEvent({ type: 'data', chunk: strippedChunk });
|
||||
} else {
|
||||
const totalBytes = outputChunks.reduce(
|
||||
(sum, chunk) => sum + chunk.length,
|
||||
0,
|
||||
);
|
||||
onOutputEvent({
|
||||
type: 'binary_progress',
|
||||
bytesReceived: totalBytes,
|
||||
});
|
||||
const decoder = stream === 'stdout' ? stdoutDecoder : stderrDecoder;
|
||||
const decodedChunk = decoder.decode(data, { stream: true });
|
||||
|
||||
if (stream === 'stdout') {
|
||||
stdout += decodedChunk;
|
||||
} else {
|
||||
stderr += decodedChunk;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -224,14 +241,24 @@ export class ShellExecutionService {
|
||||
const combinedOutput =
|
||||
stdout + (stderr ? (stdout ? separator : '') + stderr : '');
|
||||
|
||||
const finalStrippedOutput = stripAnsi(combinedOutput).trim();
|
||||
|
||||
if (isStreamingRawContent) {
|
||||
if (finalStrippedOutput) {
|
||||
onOutputEvent({ type: 'data', chunk: finalStrippedOutput });
|
||||
}
|
||||
} else {
|
||||
onOutputEvent({ type: 'binary_detected' });
|
||||
}
|
||||
|
||||
resolve({
|
||||
rawOutput: finalBuffer,
|
||||
output: combinedOutput.trim(),
|
||||
output: finalStrippedOutput,
|
||||
exitCode: code,
|
||||
signal: signal ? os.constants.signals[signal] : null,
|
||||
error,
|
||||
aborted: abortSignal.aborted,
|
||||
pid: child.pid,
|
||||
pid: undefined,
|
||||
executionMethod: 'child_process',
|
||||
});
|
||||
};
|
||||
@@ -264,6 +291,9 @@ export class ShellExecutionService {
|
||||
abortSignal.addEventListener('abort', abortHandler, { once: true });
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
if (child.pid) {
|
||||
this.activePtys.delete(child.pid);
|
||||
}
|
||||
handleExit(code, signal);
|
||||
});
|
||||
|
||||
@@ -273,13 +303,13 @@ export class ShellExecutionService {
|
||||
if (stdoutDecoder) {
|
||||
const remaining = stdoutDecoder.decode();
|
||||
if (remaining) {
|
||||
stdout += stripAnsi(remaining);
|
||||
stdout += remaining;
|
||||
}
|
||||
}
|
||||
if (stderrDecoder) {
|
||||
const remaining = stderrDecoder.decode();
|
||||
if (remaining) {
|
||||
stderr += stripAnsi(remaining);
|
||||
stderr += remaining;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +319,7 @@ export class ShellExecutionService {
|
||||
}
|
||||
});
|
||||
|
||||
return { pid: child.pid, result };
|
||||
return { pid: undefined, result };
|
||||
} catch (e) {
|
||||
const error = e as Error;
|
||||
return {
|
||||
@@ -313,29 +343,32 @@ export class ShellExecutionService {
|
||||
cwd: string,
|
||||
onOutputEvent: (event: ShellOutputEvent) => void,
|
||||
abortSignal: AbortSignal,
|
||||
terminalColumns: number | undefined,
|
||||
terminalRows: number | undefined,
|
||||
ptyInfo: PtyImplementation | undefined,
|
||||
shellExecutionConfig: ShellExecutionConfig,
|
||||
ptyInfo: PtyImplementation,
|
||||
): ShellExecutionHandle {
|
||||
if (!ptyInfo) {
|
||||
// This should not happen, but as a safeguard...
|
||||
throw new Error('PTY implementation not found');
|
||||
}
|
||||
try {
|
||||
const cols = terminalColumns ?? 80;
|
||||
const rows = terminalRows ?? 30;
|
||||
const cols = shellExecutionConfig.terminalWidth ?? 80;
|
||||
const rows = shellExecutionConfig.terminalHeight ?? 30;
|
||||
const isWindows = os.platform() === 'win32';
|
||||
const shell = isWindows ? 'cmd.exe' : 'bash';
|
||||
const args = isWindows
|
||||
? `/c ${commandToExecute}`
|
||||
: ['-c', commandToExecute];
|
||||
|
||||
const ptyProcess = ptyInfo?.module.spawn(shell, args, {
|
||||
const ptyProcess = ptyInfo.module.spawn(shell, args, {
|
||||
cwd,
|
||||
name: 'xterm-color',
|
||||
name: 'xterm',
|
||||
cols,
|
||||
rows,
|
||||
env: {
|
||||
...process.env,
|
||||
GEMINI_CLI: '1',
|
||||
TERM: 'xterm-256color',
|
||||
PAGER: 'cat',
|
||||
PAGER: shellExecutionConfig.pager ?? 'cat',
|
||||
},
|
||||
handleFlowControl: true,
|
||||
});
|
||||
@@ -346,8 +379,12 @@ export class ShellExecutionService {
|
||||
cols,
|
||||
rows,
|
||||
});
|
||||
|
||||
this.activePtys.set(ptyProcess.pid, { ptyProcess, headlessTerminal });
|
||||
|
||||
let processingChain = Promise.resolve();
|
||||
let decoder: TextDecoder | null = null;
|
||||
let output: string | AnsiOutput | null = null;
|
||||
const outputChunks: Buffer[] = [];
|
||||
const error: Error | null = null;
|
||||
let exited = false;
|
||||
@@ -355,6 +392,49 @@ export class ShellExecutionService {
|
||||
let isStreamingRawContent = true;
|
||||
const MAX_SNIFF_SIZE = 4096;
|
||||
let sniffedBytes = 0;
|
||||
let isWriting = false;
|
||||
let renderTimeout: NodeJS.Timeout | null = null;
|
||||
|
||||
const render = (finalRender = false) => {
|
||||
if (renderTimeout) {
|
||||
clearTimeout(renderTimeout);
|
||||
}
|
||||
|
||||
const renderFn = () => {
|
||||
if (!isStreamingRawContent) {
|
||||
return;
|
||||
}
|
||||
const newOutput = shellExecutionConfig.showColor
|
||||
? serializeTerminalToObject(headlessTerminal, {
|
||||
defaultFg: shellExecutionConfig.defaultFg,
|
||||
defaultBg: shellExecutionConfig.defaultBg,
|
||||
})
|
||||
: getVisibleText(headlessTerminal);
|
||||
|
||||
// console.log(newOutput)
|
||||
|
||||
// Using stringify for a quick deep comparison.
|
||||
if (JSON.stringify(output) !== JSON.stringify(newOutput)) {
|
||||
output = newOutput;
|
||||
onOutputEvent({
|
||||
type: 'data',
|
||||
chunk: newOutput,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (finalRender) {
|
||||
renderFn();
|
||||
} else {
|
||||
renderTimeout = setTimeout(renderFn, 17);
|
||||
}
|
||||
};
|
||||
|
||||
headlessTerminal.onScroll(() => {
|
||||
if (!isWriting) {
|
||||
render();
|
||||
}
|
||||
});
|
||||
|
||||
const handleOutput = (data: Buffer) => {
|
||||
processingChain = processingChain.then(
|
||||
@@ -383,11 +463,10 @@ export class ShellExecutionService {
|
||||
|
||||
if (isStreamingRawContent) {
|
||||
const decodedChunk = decoder.decode(data, { stream: true });
|
||||
isWriting = true;
|
||||
headlessTerminal.write(decodedChunk, () => {
|
||||
onOutputEvent({
|
||||
type: 'data',
|
||||
chunk: stripAnsi(decodedChunk),
|
||||
});
|
||||
render();
|
||||
isWriting = false;
|
||||
resolve();
|
||||
});
|
||||
} else {
|
||||
@@ -414,19 +493,23 @@ export class ShellExecutionService {
|
||||
({ exitCode, signal }: { exitCode: number; signal?: number }) => {
|
||||
exited = true;
|
||||
abortSignal.removeEventListener('abort', abortHandler);
|
||||
this.activePtys.delete(ptyProcess.pid);
|
||||
|
||||
processingChain.then(() => {
|
||||
render(true);
|
||||
const finalBuffer = Buffer.concat(outputChunks);
|
||||
|
||||
resolve({
|
||||
rawOutput: finalBuffer,
|
||||
output: getFullText(headlessTerminal),
|
||||
output: getFullBufferText(headlessTerminal),
|
||||
exitCode,
|
||||
signal: signal ?? null,
|
||||
error,
|
||||
aborted: abortSignal.aborted,
|
||||
pid: ptyProcess.pid,
|
||||
executionMethod: ptyInfo?.name ?? 'node-pty',
|
||||
executionMethod:
|
||||
(ptyInfo?.name as 'node-pty' | 'lydell-node-pty') ??
|
||||
'node-pty',
|
||||
});
|
||||
});
|
||||
},
|
||||
@@ -434,7 +517,17 @@ export class ShellExecutionService {
|
||||
|
||||
const abortHandler = async () => {
|
||||
if (ptyProcess.pid && !exited) {
|
||||
ptyProcess.kill('SIGHUP');
|
||||
if (os.platform() === 'win32') {
|
||||
ptyProcess.kill();
|
||||
} else {
|
||||
try {
|
||||
// Kill the entire process group
|
||||
process.kill(-ptyProcess.pid, 'SIGINT');
|
||||
} catch (_e) {
|
||||
// Fallback to killing just the process if the group kill fails
|
||||
ptyProcess.kill('SIGINT');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -459,4 +552,65 @@ export class ShellExecutionService {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a string to the pseudo-terminal (PTY) of a running process.
|
||||
*
|
||||
* @param pid The process ID of the target PTY.
|
||||
* @param input The string to write to the terminal.
|
||||
*/
|
||||
static writeToPty(pid: number, input: string): void {
|
||||
const activePty = this.activePtys.get(pid);
|
||||
if (activePty) {
|
||||
activePty.ptyProcess.write(input);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the pseudo-terminal (PTY) of a running process.
|
||||
*
|
||||
* @param pid The process ID of the target PTY.
|
||||
* @param cols The new number of columns.
|
||||
* @param rows The new number of rows.
|
||||
*/
|
||||
static resizePty(pid: number, cols: number, rows: number): void {
|
||||
const activePty = this.activePtys.get(pid);
|
||||
if (activePty) {
|
||||
try {
|
||||
activePty.ptyProcess.resize(cols, rows);
|
||||
activePty.headlessTerminal.resize(cols, rows);
|
||||
} catch (e) {
|
||||
// Ignore errors if the pty has already exited, which can happen
|
||||
// due to a race condition between the exit event and this call.
|
||||
if (e instanceof Error && 'code' in e && e.code === 'ESRCH') {
|
||||
// ignore
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolls the pseudo-terminal (PTY) of a running process.
|
||||
*
|
||||
* @param pid The process ID of the target PTY.
|
||||
* @param lines The number of lines to scroll.
|
||||
*/
|
||||
static scrollPty(pid: number, lines: number): void {
|
||||
const activePty = this.activePtys.get(pid);
|
||||
if (activePty) {
|
||||
try {
|
||||
activePty.headlessTerminal.scrollLines(lines);
|
||||
} catch (e) {
|
||||
// Ignore errors if the pty has already exited, which can happen
|
||||
// due to a race condition between the exit event and this call.
|
||||
if (e instanceof Error && 'code' in e && e.code === 'ESRCH') {
|
||||
// ignore
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user