File size: 11,795 Bytes
9332ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import {
  vi,
  describe,
  it,
  expect,
  beforeEach,
  afterEach,
  type Mock,
  type MockInstance,
} from 'vitest';
import { act } from 'react';
import { renderHook } from '../../test-utils/render.js';
import { waitFor } from '../../test-utils/async.js';
import { useFolderTrust } from './useFolderTrust.js';
import type { LoadedSettings } from '../../config/settings.js';
import { FolderTrustChoice } from '../components/FolderTrustDialog.js';
import {
  TrustLevel,
  type LoadedTrustedFolders,
} from '../../config/trustedFolders.js';
import * as trustedFolders from '../../config/trustedFolders.js';
import { coreEvents, ExitCodes, isHeadlessMode } from '@google/gemini-cli-core';
import { MessageType } from '../types.js';

const mockedCwd = vi.hoisted(() => vi.fn().mockReturnValue('/mock/cwd'));
const mockedExit = vi.hoisted(() => vi.fn());

vi.mock('@google/gemini-cli-core', async () => {
  const actual = await vi.importActual<
    typeof import('@google/gemini-cli-core')
  >('@google/gemini-cli-core');
  return {
    ...actual,
    isHeadlessMode: vi.fn().mockReturnValue(false),
    FolderTrustDiscoveryService: {
      discover: vi.fn(() => new Promise(() => {})),
    },
  };
});

vi.mock('node:process', async () => {
  const actual =
    await vi.importActual<typeof import('node:process')>('node:process');
  return {
    ...actual,
    cwd: mockedCwd,
    exit: mockedExit,
    platform: 'linux',
  };
});

describe('useFolderTrust', () => {
  let mockSettings: LoadedSettings;
  let mockTrustedFolders: LoadedTrustedFolders;
  let isWorkspaceTrustedSpy: MockInstance;
  let onTrustChange: (isTrusted: boolean | undefined) => void;
  let addItem: Mock;

  const originalStdoutIsTTY = process.stdout.isTTY;
  const originalStdinIsTTY = process.stdin.isTTY;

  beforeEach(() => {
    vi.useFakeTimers();

    // Default to interactive mode for tests
    Object.defineProperty(process.stdout, 'isTTY', {
      value: true,
      configurable: true,
      writable: true,
    });
    Object.defineProperty(process.stdin, 'isTTY', {
      value: true,
      configurable: true,
      writable: true,
    });

    mockSettings = {
      merged: {
        security: {
          folderTrust: {
            enabled: true,
          },
        },
      },
      setValue: vi.fn(),
    } as unknown as LoadedSettings;

    mockTrustedFolders = {
      setValue: vi.fn(),
    } as unknown as LoadedTrustedFolders;

    vi.spyOn(trustedFolders, 'loadTrustedFolders').mockReturnValue(
      mockTrustedFolders,
    );
    isWorkspaceTrustedSpy = vi.spyOn(trustedFolders, 'isWorkspaceTrusted');
    mockedCwd.mockReturnValue('/test/path');
    onTrustChange = vi.fn();
    addItem = vi.fn();
  });

  afterEach(() => {
    vi.useRealTimers();
    vi.clearAllMocks();
    Object.defineProperty(process.stdout, 'isTTY', {
      value: originalStdoutIsTTY,
      configurable: true,
      writable: true,
    });
    Object.defineProperty(process.stdin, 'isTTY', {
      value: originalStdinIsTTY,
      configurable: true,
      writable: true,
    });
  });

  it('should not open dialog when folder is already trusted', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({ isTrusted: true, source: 'file' });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );
    expect(result.current.isFolderTrustDialogOpen).toBe(false);
    expect(onTrustChange).toHaveBeenCalledWith(true);
  });

  it('should not open dialog when folder is already untrusted', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({ isTrusted: false, source: 'file' });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );
    expect(result.current.isFolderTrustDialogOpen).toBe(false);
    expect(onTrustChange).toHaveBeenCalledWith(false);
  });

  it('should open dialog when folder trust is undefined', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );
    await waitFor(() => {
      expect(result.current.isFolderTrustDialogOpen).toBe(true);
    });
    expect(onTrustChange).toHaveBeenCalledWith(undefined);
  });

  it('should send a message if the folder is untrusted', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({ isTrusted: false, source: 'file' });
    await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );
    expect(addItem).toHaveBeenCalledWith(
      {
        text: 'This folder is untrusted, project settings, hooks, MCPs, and GEMINI.md files will not be applied for this folder.\nUse the `/permissions` command to change the trust level.',
        type: 'info',
      },
      expect.any(Number),
    );
  });

  it('should not send a message if the folder is trusted', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({ isTrusted: true, source: 'file' });
    await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );
    expect(addItem).not.toHaveBeenCalled();
  });

  it('should handle TRUST_FOLDER choice and trigger restart', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });

    (mockTrustedFolders.setValue as Mock).mockImplementation(() => {
      isWorkspaceTrustedSpy.mockReturnValue({
        isTrusted: true,
        source: 'file',
      });
    });

    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await waitFor(() => {
      expect(result.current.isTrusted).toBeUndefined();
    });

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        FolderTrustChoice.TRUST_FOLDER,
      );
    });

    await waitFor(() => {
      expect(mockTrustedFolders.setValue).toHaveBeenCalledWith(
        '/test/path',
        TrustLevel.TRUST_FOLDER,
      );
      expect(result.current.isRestarting).toBe(true);
      expect(result.current.isFolderTrustDialogOpen).toBe(true);
      expect(onTrustChange).toHaveBeenLastCalledWith(true);
    });
  });

  it('should handle TRUST_PARENT choice and trigger restart', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        FolderTrustChoice.TRUST_PARENT,
      );
    });

    await waitFor(() => {
      expect(mockTrustedFolders.setValue).toHaveBeenCalledWith(
        '/test/path',
        TrustLevel.TRUST_PARENT,
      );
      expect(result.current.isRestarting).toBe(true);
      expect(result.current.isFolderTrustDialogOpen).toBe(true);
      expect(onTrustChange).toHaveBeenLastCalledWith(true);
    });
  });

  it('should handle DO_NOT_TRUST choice and NOT trigger restart (implicit -> explicit)', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        FolderTrustChoice.DO_NOT_TRUST,
      );
    });

    await waitFor(() => {
      expect(mockTrustedFolders.setValue).toHaveBeenCalledWith(
        '/test/path',
        TrustLevel.DO_NOT_TRUST,
      );
      expect(onTrustChange).toHaveBeenLastCalledWith(false);
      expect(result.current.isRestarting).toBe(false);
      expect(result.current.isFolderTrustDialogOpen).toBe(false);
    });
  });

  it('should do nothing for default choice', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        'invalid_choice' as FolderTrustChoice,
      );
    });

    await waitFor(() => {
      expect(mockTrustedFolders.setValue).not.toHaveBeenCalled();
      expect(mockSettings.setValue).not.toHaveBeenCalled();
      expect(result.current.isFolderTrustDialogOpen).toBe(true);
      expect(onTrustChange).toHaveBeenCalledWith(undefined);
    });
  });

  it('should set isRestarting to true when trust status changes from false to true', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({ isTrusted: false, source: 'file' }); // Initially untrusted

    (mockTrustedFolders.setValue as Mock).mockImplementation(() => {
      isWorkspaceTrustedSpy.mockReturnValue({
        isTrusted: true,
        source: 'file',
      });
    });

    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await waitFor(() => {
      expect(result.current.isTrusted).toBe(false);
    });

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        FolderTrustChoice.TRUST_FOLDER,
      );
    });

    await waitFor(() => {
      expect(result.current.isRestarting).toBe(true);
      expect(result.current.isFolderTrustDialogOpen).toBe(true); // Dialog should stay open
    });
  });

  it('should not set isRestarting to true when trust status does not change (true -> true)', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: true,
      source: 'file',
    });
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        FolderTrustChoice.TRUST_FOLDER,
      );
    });

    await waitFor(() => {
      expect(result.current.isRestarting).toBe(false);
      expect(result.current.isFolderTrustDialogOpen).toBe(false); // Dialog should close
    });
  });

  it('should emit feedback on failure to set value', async () => {
    isWorkspaceTrustedSpy.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    (mockTrustedFolders.setValue as Mock).mockImplementation(() => {
      throw new Error('test error');
    });
    const emitFeedbackSpy = vi.spyOn(coreEvents, 'emitFeedback');
    const { result } = await renderHook(() =>
      useFolderTrust(mockSettings, onTrustChange, addItem),
    );

    await act(async () => {
      await result.current.handleFolderTrustSelect(
        FolderTrustChoice.TRUST_FOLDER,
      );
    });

    await vi.runAllTimersAsync();

    expect(emitFeedbackSpy).toHaveBeenCalledWith(
      'error',
      'Failed to save trust settings. Exiting Gemini CLI.',
    );
    expect(mockedExit).toHaveBeenCalledWith(ExitCodes.FATAL_CONFIG_ERROR);
  });

  describe('headless mode', () => {
    it('should force trust and hide dialog in headless mode', async () => {
      vi.mocked(isHeadlessMode).mockReturnValue(true);
      isWorkspaceTrustedSpy.mockReturnValue({
        isTrusted: false,
        source: 'file',
      });

      const { result } = await renderHook(() =>
        useFolderTrust(mockSettings, onTrustChange, addItem),
      );

      expect(result.current.isFolderTrustDialogOpen).toBe(false);
      expect(onTrustChange).toHaveBeenCalledWith(true);
      expect(addItem).toHaveBeenCalledWith(
        expect.objectContaining({
          type: MessageType.INFO,
          text: expect.stringContaining('This folder is untrusted'),
        }),
        expect.any(Number),
      );
    });
  });
});