1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { act, renderHook } from '@testing-library/react';
import {
vi,
describe,
it,
expect,
beforeEach,
afterEach,
type Mock,
} from 'vitest';
const mockIsBinary = vi.hoisted(() => vi.fn());
const mockShellExecutionService = vi.hoisted(() => vi.fn());
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const original =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...original,
ShellExecutionService: { execute: mockShellExecutionService },
isBinary: mockIsBinary,
};
});
vi.mock('fs');
vi.mock('os');
vi.mock('crypto');
vi.mock('../utils/textUtils.js');
import {
useShellCommandProcessor,
OUTPUT_UPDATE_INTERVAL_MS,
} from './shellCommandProcessor.js';
import {
type Config,
type GeminiClient,
type ShellExecutionResult,
type ShellOutputEvent,
} from '@google/gemini-cli-core';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as crypto from 'crypto';
import { ToolCallStatus } from '../types.js';
describe('useShellCommandProcessor', () => {
let addItemToHistoryMock: Mock;
let setPendingHistoryItemMock: Mock;
let onExecMock: Mock;
let onDebugMessageMock: Mock;
let mockConfig: Config;
let mockGeminiClient: GeminiClient;
let mockShellOutputCallback: (event: ShellOutputEvent) => void;
let resolveExecutionPromise: (result: ShellExecutionResult) => void;
beforeEach(() => {
vi.clearAllMocks();
addItemToHistoryMock = vi.fn();
setPendingHistoryItemMock = vi.fn();
onExecMock = vi.fn();
onDebugMessageMock = vi.fn();
mockConfig = { getTargetDir: () => '/test/dir' } as Config;
mockGeminiClient = { addHistory: vi.fn() } as unknown as GeminiClient;
vi.mocked(os.platform).mockReturnValue('linux');
vi.mocked(os.tmpdir).mockReturnValue('/tmp');
(vi.mocked(crypto.randomBytes) as Mock).mockReturnValue(
Buffer.from('abcdef', 'hex'),
);
mockIsBinary.mockReturnValue(false);
vi.mocked(fs.existsSync).mockReturnValue(false);
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
mockShellOutputCallback = callback;
return {
pid: 12345,
result: new Promise((resolve) => {
resolveExecutionPromise = resolve;
}),
};
});
});
const renderProcessorHook = () =>
renderHook(() =>
useShellCommandProcessor(
addItemToHistoryMock,
setPendingHistoryItemMock,
onExecMock,
onDebugMessageMock,
mockConfig,
mockGeminiClient,
),
);
const createMockServiceResult = (
overrides: Partial<ShellExecutionResult> = {},
): ShellExecutionResult => ({
rawOutput: Buffer.from(overrides.output || ''),
output: 'Success',
exitCode: 0,
signal: null,
error: null,
aborted: false,
pid: 12345,
...overrides,
});
it('should initiate command execution and set pending state', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('ls -l', new AbortController().signal);
});
expect(addItemToHistoryMock).toHaveBeenCalledWith(
{ type: 'user_shell', text: 'ls -l' },
expect.any(Number),
);
expect(setPendingHistoryItemMock).toHaveBeenCalledWith({
type: 'tool_group',
tools: [
expect.objectContaining({
name: 'Shell Command',
status: ToolCallStatus.Executing,
}),
],
});
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
const wrappedCommand = `{ ls -l; }; __code=$?; pwd > "${tmpFile}"; exit $__code`;
expect(mockShellExecutionService).toHaveBeenCalledWith(
wrappedCommand,
'/test/dir',
expect.any(Function),
expect.any(Object),
);
expect(onExecMock).toHaveBeenCalledWith(expect.any(Promise));
});
it('should handle successful execution and update history correctly', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'echo "ok"',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
act(() => {
resolveExecutionPromise(createMockServiceResult({ output: 'ok' }));
});
await act(async () => await execPromise);
expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
expect(addItemToHistoryMock).toHaveBeenCalledTimes(2); // Initial + final
expect(addItemToHistoryMock.mock.calls[1][0]).toEqual(
expect.objectContaining({
tools: [
expect.objectContaining({
status: ToolCallStatus.Success,
resultDisplay: 'ok',
}),
],
}),
);
expect(mockGeminiClient.addHistory).toHaveBeenCalled();
});
it('should handle command failure and display error status', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'bad-cmd',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
act(() => {
resolveExecutionPromise(
createMockServiceResult({ exitCode: 127, output: 'not found' }),
);
});
await act(async () => await execPromise);
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
expect(finalHistoryItem.tools[0].status).toBe(ToolCallStatus.Error);
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
'Command exited with code 127',
);
expect(finalHistoryItem.tools[0].resultDisplay).toContain('not found');
});
describe('UI Streaming and Throttling', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
});
afterEach(() => {
vi.useRealTimers();
});
it('should throttle pending UI updates for text streams', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'stream',
new AbortController().signal,
);
});
// Simulate rapid output
act(() => {
mockShellOutputCallback({
type: 'data',
chunk: 'hello',
});
});
// Should not have updated the UI yet
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(1); // Only the initial call
// Advance time and send another event to trigger the throttled update
await act(async () => {
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
mockShellOutputCallback({
type: 'data',
chunk: 'hello world',
});
});
// Should now have been called with the cumulative output
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
expect.objectContaining({
tools: [expect.objectContaining({ resultDisplay: 'hello world' })],
}),
);
});
it('should show binary progress messages correctly', async () => {
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'cat img',
new AbortController().signal,
);
});
// Should immediately show the detection message
act(() => {
mockShellOutputCallback({ type: 'binary_detected' });
});
await act(async () => {
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
});
// Send another event to trigger the update
act(() => {
mockShellOutputCallback({ type: 'binary_progress', bytesReceived: 0 });
});
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
expect.objectContaining({
tools: [
expect.objectContaining({
resultDisplay: '[Binary output detected. Halting stream...]',
}),
],
}),
);
// Now test progress updates
await act(async () => {
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
});
act(() => {
mockShellOutputCallback({
type: 'binary_progress',
bytesReceived: 2048,
});
});
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
expect.objectContaining({
tools: [
expect.objectContaining({
resultDisplay: '[Receiving binary output... 2.0 KB received]',
}),
],
}),
);
});
});
it('should not wrap the command on Windows', async () => {
vi.mocked(os.platform).mockReturnValue('win32');
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('dir', new AbortController().signal);
});
expect(mockShellExecutionService).toHaveBeenCalledWith(
'dir',
'/test/dir',
expect.any(Function),
expect.any(Object),
);
});
it('should handle command abort and display cancelled status', async () => {
const { result } = renderProcessorHook();
const abortController = new AbortController();
act(() => {
result.current.handleShellCommand('sleep 5', abortController.signal);
});
const execPromise = onExecMock.mock.calls[0][0];
act(() => {
abortController.abort();
resolveExecutionPromise(
createMockServiceResult({ aborted: true, output: 'Canceled' }),
);
});
await act(async () => await execPromise);
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
expect(finalHistoryItem.tools[0].status).toBe(ToolCallStatus.Canceled);
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
'Command was cancelled.',
);
});
it('should handle binary output result correctly', async () => {
const { result } = renderProcessorHook();
const binaryBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
mockIsBinary.mockReturnValue(true);
act(() => {
result.current.handleShellCommand(
'cat image.png',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
act(() => {
resolveExecutionPromise(
createMockServiceResult({ rawOutput: binaryBuffer }),
);
});
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).toBe(
'[Command produced binary output, which is not shown.]',
);
});
it('should handle promise rejection and show an error', async () => {
const { result } = renderProcessorHook();
const testError = new Error('Unexpected failure');
mockShellExecutionService.mockImplementation(() => ({
pid: 12345,
result: Promise.reject(testError),
}));
act(() => {
result.current.handleShellCommand(
'a-command',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
await act(async () => await execPromise);
expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);
expect(addItemToHistoryMock.mock.calls[1][0]).toEqual({
type: 'error',
text: 'An unexpected error occurred: Unexpected failure',
});
});
it('should handle synchronous errors during execution and clean up resources', async () => {
const testError = new Error('Synchronous spawn error');
mockShellExecutionService.mockImplementation(() => {
throw testError;
});
// Mock that the temp file was created before the error was thrown
vi.mocked(fs.existsSync).mockReturnValue(true);
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'a-command',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
await act(async () => await execPromise);
expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);
expect(addItemToHistoryMock.mock.calls[1][0]).toEqual({
type: 'error',
text: 'An unexpected error occurred: Synchronous spawn error',
});
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
// Verify that the temporary file was cleaned up
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
});
describe('Directory Change Warning', () => {
it('should show a warning if the working directory changes', async () => {
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue('/test/dir/new'); // A different directory
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand(
'cd new',
new AbortController().signal,
);
});
const execPromise = onExecMock.mock.calls[0][0];
act(() => {
resolveExecutionPromise(createMockServiceResult());
});
await act(async () => await execPromise);
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
"WARNING: shell mode is stateless; the directory change to '/test/dir/new' will not persist.",
);
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
});
it('should NOT show a warning if the directory does not change', async () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue('/test/dir'); // The same directory
const { result } = renderProcessorHook();
act(() => {
result.current.handleShellCommand('ls', new AbortController().signal);
});
const execPromise = onExecMock.mock.calls[0][0];
act(() => {
resolveExecutionPromise(createMockServiceResult());
});
await act(async () => await execPromise);
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
expect(finalHistoryItem.tools[0].resultDisplay).not.toContain('WARNING');
});
});
});
|