summaryrefslogtreecommitdiff
path: root/packages/cli/src/ui/hooks/shellCommandProcessor.test.ts
blob: 2f0f6604b2acbf3ecc133edfcc8f84d63463cadc (plain)
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/* eslint-disable @typescript-eslint/no-explicit-any */
import { act, renderHook } from '@testing-library/react';
import { useShellCommandProcessor } from './shellCommandProcessor.js';
import { type Config } from '@gemini-code/core';
import { type PartListUnion } from '@google/genai';
import { existsSync, readFileSync, unlinkSync } from 'fs';
import type * as FsMod from 'fs';
import type { exec as ExecType } from 'child_process'; // For typing the injected mock

// Mocks
const mockAddItemToHistory = vi.fn();
const mockSetPendingHistoryItem = vi.fn();
const mockOnExec = vi.fn(async (promise) => await promise);
const mockOnDebugMessage = vi.fn();
const mockGetTargetDir = vi.fn();
let mockExecuteCommand: ReturnType<typeof vi.fn>; // This will be our injected mock for child_process.exec

const mockConfig = {
  getTargetDir: mockGetTargetDir,
} as unknown as Config;

vi.mock('crypto', () => ({
  default: {
    randomBytes: vi.fn(() => ({ toString: vi.fn(() => 'randomBytes') })),
  },
  randomBytes: vi.fn(() => ({ toString: vi.fn(() => 'randomBytes') })),
}));

vi.mock('path', () => ({
  default: {
    join: vi.fn((...args) => args.join('/')),
    sep: '/',
  },
  join: vi.fn((...args) => args.join('/')),
  sep: '/',
}));

vi.mock('os', () => ({
  default: {
    tmpdir: vi.fn(() => '/tmp'),
  },
  tmpdir: vi.fn(() => '/tmp'),
}));

// Configure the fs mock to use new vi.fn() instances created within the factory
vi.mock('fs', async (importOriginal) => {
  const original = (await importOriginal()) as typeof FsMod;
  const internalMockFsExistsSync = vi.fn();
  const internalMockFsReadFileSync = vi.fn();
  const internalMockFsUnlinkSync = vi.fn();
  return {
    ...original,
    existsSync: internalMockFsExistsSync,
    readFileSync: internalMockFsReadFileSync,
    unlinkSync: internalMockFsUnlinkSync,
  };
});

describe('useShellCommandProcessor', () => {
  // These spies will point to the vi.fn() instances created by the vi.mock('fs') factory.
  let existsSyncSpy: ReturnType<typeof vi.mocked<typeof existsSync>>;
  let readFileSyncSpy: ReturnType<typeof vi.mocked<typeof readFileSync>>;
  let unlinkSyncSpy: ReturnType<typeof vi.mocked<typeof unlinkSync>>;

  beforeEach(() => {
    vi.clearAllMocks();
    mockExecuteCommand = vi.fn(); // Injected exec command mock

    // Assign the imported (and mocked by vi.mock factory) fs functions to spies
    existsSyncSpy = existsSync as unknown as ReturnType<
      typeof vi.mocked<typeof existsSync>
    >;
    readFileSyncSpy = readFileSync as unknown as ReturnType<
      typeof vi.mocked<typeof readFileSync>
    >;
    unlinkSyncSpy = unlinkSync as unknown as ReturnType<
      typeof vi.mocked<typeof unlinkSync>
    >;

    // It's important to reset these spies if they are to be configured per test
    existsSyncSpy.mockReset();
    readFileSyncSpy.mockReset();
    unlinkSyncSpy.mockReset();

    mockGetTargetDir.mockReturnValue('/current/dir');
  });

  const setupHook = () =>
    renderHook(() =>
      useShellCommandProcessor(
        mockAddItemToHistory,
        mockSetPendingHistoryItem,
        mockOnExec,
        mockOnDebugMessage,
        mockConfig,
        mockExecuteCommand as unknown as typeof ExecType, // Cast to satisfy TypeScript
      ),
    );

  it('should return false for non-string input', () => {
    const { result } = setupHook();
    const handled = result.current.handleShellCommand(
      [{ text: 'not a string' }] as PartListUnion,
      new AbortController().signal,
    );
    expect(handled).toBe(false);
    expect(mockAddItemToHistory).not.toHaveBeenCalled();
  });

  it('should handle empty shell command', () => {
    const { result } = setupHook();
    act(() => {
      const handled = result.current.handleShellCommand(
        '',
        new AbortController().signal,
      );
      expect(handled).toBe(true);
    });
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      1,
      { type: 'user_shell', text: '' },
      expect.any(Number),
    );
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      2,
      { type: 'error', text: 'Empty shell command.' },
      expect.any(Number),
    );
    expect(mockExecuteCommand).not.toHaveBeenCalled();
  });

  it('should execute a successful command and add output to history', async () => {
    const { result } = setupHook();
    const command = '!ls -l';
    const stdout = 'total 0';
    const stderr = '';

    mockExecuteCommand.mockImplementation((_cmd, _options, callback) => {
      if (callback) callback(null, stdout, stderr);
      return {} as any;
    });
    existsSyncSpy.mockReturnValue(false);

    await act(async () => {
      result.current.handleShellCommand(command, new AbortController().signal);
      await new Promise(process.nextTick);
    });

    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      1,
      { type: 'user_shell', text: command },
      expect.any(Number),
    );
    expect(mockOnDebugMessage).toHaveBeenCalledWith(
      expect.stringContaining('Executing shell command in /current/dir:'),
    );
    expect(mockExecuteCommand).toHaveBeenCalledWith(
      '{ !ls -l; }; __code=$?; pwd >/tmp/shell_pwd_randomBytes.tmp; exit $__code',
      { cwd: '/current/dir' },
      expect.any(Function),
    );
    expect(mockOnExec).toHaveBeenCalled();
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      2,
      { type: 'info', text: stdout },
      expect.any(Number),
    );
  });

  it('should handle command with stderr output', async () => {
    const { result } = setupHook();
    const command = '!some_command_with_stderr';
    const stdout = 'some output';
    const stderr = 'some error output';

    mockExecuteCommand.mockImplementation((_cmd, _options, callback) => {
      if (callback) callback(null, stdout, stderr);
      return {} as any;
    });
    existsSyncSpy.mockReturnValue(false);

    await act(async () => {
      result.current.handleShellCommand(command, new AbortController().signal);
      await new Promise(process.nextTick);
    });
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      1,
      { type: 'user_shell', text: command },
      expect.any(Number),
    );
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      2,
      { type: 'info', text: `${stdout}\n${stderr}` },
      expect.any(Number),
    );
  });

  it('should handle command with only stderr output', async () => {
    const { result } = setupHook();
    const command = '!command_only_stderr';
    const stdout = '';
    const stderr = 'just stderr';

    mockExecuteCommand.mockImplementation((_cmd, _options, callback) => {
      if (callback) callback(null, stdout, stderr);
      return {} as any;
    });
    existsSyncSpy.mockReturnValue(false);

    await act(async () => {
      result.current.handleShellCommand(command, new AbortController().signal);
      await new Promise(process.nextTick);
    });
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      1,
      { type: 'user_shell', text: command },
      expect.any(Number),
    );
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      2,
      { type: 'info', text: stderr },
      expect.any(Number),
    );
  });

  it('should handle command error', async () => {
    const { result } = setupHook();
    const command = '!failing_command';
    const error = new Error('Command failed');

    mockExecuteCommand.mockImplementation((_cmd, _options, callback) => {
      if (callback) callback(error, '', '');
      return {} as any;
    });
    existsSyncSpy.mockReturnValue(false);

    await act(async () => {
      result.current.handleShellCommand(command, new AbortController().signal);
      await new Promise(process.nextTick);
    });
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      1,
      { type: 'user_shell', text: command },
      expect.any(Number),
    );
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      2,
      { type: 'error', text: error.message },
      expect.any(Number),
    );
  });

  it('should correctly handle commands ending with &', async () => {
    const { result } = setupHook();
    const command = '!sleep 5 &';
    mockGetTargetDir.mockReturnValue('/current/dir');

    mockExecuteCommand.mockImplementation((_cmd, _options, callback) => {
      if (callback) callback(null, '', '');
      return {} as any;
    });
    existsSyncSpy.mockReturnValue(false);

    await act(async () => {
      result.current.handleShellCommand(command, new AbortController().signal);
      await new Promise(process.nextTick);
    });

    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      1,
      { type: 'user_shell', text: command },
      expect.any(Number),
    );
    expect(mockExecuteCommand).toHaveBeenCalledWith(
      '{ !sleep 5 & }; __code=$?; pwd >/tmp/shell_pwd_randomBytes.tmp; exit $__code',
      { cwd: '/current/dir' },
      expect.any(Function),
    );
    expect(mockAddItemToHistory).toHaveBeenNthCalledWith(
      2,
      { type: 'info', text: '(Command produced no output)' },
      expect.any(Number),
    );
  });
});