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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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import {
  describe,
  it,
  expect,
  vi,
  beforeEach,
  afterEach,
  type MockInstance,
} from 'vitest';
import { handleInstall, installCommand } from './install.js';
import yargs from 'yargs';
import * as core from '@google/gemini-cli-core';
import type { Stats } from 'node:fs';
import * as path from 'node:path';
import { promptForSetting } from '../../config/extensions/extensionSettings.js';

const {
  mockInstallOrUpdateExtension,
  mockLoadExtensions,
  mockExtensionManager,
  mockRequestConsentNonInteractive,
  mockPromptForConsentNonInteractive,
  mockStat,
  mockInferInstallMetadata,
  mockIsWorkspaceTrusted,
  mockLoadTrustedFolders,
  mockDiscover,
} = vi.hoisted(() => {
  const mockLoadExtensions = vi.fn();
  const mockInstallOrUpdateExtension = vi.fn();
  const mockExtensionManager = vi.fn().mockImplementation(() => ({
    loadExtensions: mockLoadExtensions,
    installOrUpdateExtension: mockInstallOrUpdateExtension,
  }));

  return {
    mockLoadExtensions,
    mockInstallOrUpdateExtension,
    mockExtensionManager,
    mockRequestConsentNonInteractive: vi.fn(),
    mockPromptForConsentNonInteractive: vi.fn(),
    mockStat: vi.fn(),
    mockInferInstallMetadata: vi.fn(),
    mockIsWorkspaceTrusted: vi.fn(),
    mockLoadTrustedFolders: vi.fn(),
    mockDiscover: vi.fn(),
  };
});

vi.mock('../../config/extensions/consent.js', () => ({
  requestConsentNonInteractive: mockRequestConsentNonInteractive,
  promptForConsentNonInteractive: mockPromptForConsentNonInteractive,
  INSTALL_WARNING_MESSAGE: 'warning',
}));

vi.mock('../../config/trustedFolders.js', () => ({
  isWorkspaceTrusted: mockIsWorkspaceTrusted,
  loadTrustedFolders: mockLoadTrustedFolders,
  TrustLevel: {
    TRUST_FOLDER: 'TRUST_FOLDER',
  },
}));

vi.mock('@google/gemini-cli-core', async (importOriginal) => {
  const actual =
    await importOriginal<typeof import('@google/gemini-cli-core')>();
  return {
    ...actual,
    FolderTrustDiscoveryService: {
      discover: mockDiscover,
    },
  };
});

vi.mock('../../config/extension-manager.js', async (importOriginal) => ({
  ...(await importOriginal<
    typeof import('../../config/extension-manager.js')
  >()),
  ExtensionManager: mockExtensionManager,
  inferInstallMetadata: mockInferInstallMetadata,
}));

vi.mock('../../utils/errors.js', () => ({
  getErrorMessage: vi.fn((error: Error) => error.message),
}));

vi.mock('node:fs/promises', () => ({
  stat: mockStat,
  default: {
    stat: mockStat,
  },
}));

vi.mock('../utils.js', () => ({
  exitCli: vi.fn(),
}));

describe('extensions install command', () => {
  it('should fail if no source is provided', () => {
    const validationParser = yargs([])
      .locale('en')
      .command(installCommand)
      .fail(false);
    expect(() => validationParser.parse('install')).toThrow(
      'Not enough non-option arguments: got 0, need at least 1',
    );
  });
});

describe('handleInstall', () => {
  let debugLogSpy: MockInstance;
  let debugErrorSpy: MockInstance;
  let processSpy: MockInstance;

  beforeEach(() => {
    debugLogSpy = vi
      .spyOn(core.debugLogger, 'log')
      .mockImplementation(() => {});
    debugErrorSpy = vi
      .spyOn(core.debugLogger, 'error')
      .mockImplementation(() => {});
    processSpy = vi
      .spyOn(process, 'exit')
      .mockImplementation(() => undefined as never);

    mockLoadExtensions.mockResolvedValue([]);
    mockInstallOrUpdateExtension.mockReset();

    mockIsWorkspaceTrusted.mockReturnValue({ isTrusted: true, source: 'file' });
    mockDiscover.mockResolvedValue({
      commands: [],
      mcps: [],
      hooks: [],
      skills: [],
      agents: [],
      settings: [],
      securityWarnings: [],
      discoveryErrors: [],
    });

    mockInferInstallMetadata.mockImplementation(async (source, args) => {
      if (
        source.startsWith('http://') ||
        source.startsWith('https://') ||
        source.startsWith('git@') ||
        source.startsWith('sso://')
      ) {
        return {
          source,
          type: 'git',
          ref: args?.ref,
          autoUpdate: args?.autoUpdate,
          allowPreRelease: args?.allowPreRelease,
        };
      }
      return { source, type: 'local' };
    });
  });

  afterEach(() => {
    vi.clearAllMocks();
  });

  function createMockExtension(
    overrides: Partial<core.GeminiCLIExtension> = {},
  ): core.GeminiCLIExtension {
    return {
      name: 'mock-extension',
      version: '1.0.0',
      isActive: true,
      path: '/mock/path',
      contextFiles: [],
      id: 'mock-id',
      ...overrides,
    };
  }

  it('should install an extension from a http source', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'http-extension',
      }),
    );

    await handleInstall({
      source: 'http://google.com',
    });

    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "http-extension" installed successfully and enabled.',
    );
  });

  it('should install an extension from a https source', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'https-extension',
      }),
    );

    await handleInstall({
      source: 'https://google.com',
    });

    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "https-extension" installed successfully and enabled.',
    );
  });

  it('should install an extension from a git source', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'git-extension',
      }),
    );

    await handleInstall({
      source: 'git@some-url',
    });

    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "git-extension" installed successfully and enabled.',
    );
  });

  it('throws an error from an unknown source', async () => {
    mockInferInstallMetadata.mockRejectedValue(
      new Error('Install source not found.'),
    );
    await handleInstall({
      source: 'test://google.com',
    });

    expect(debugErrorSpy).toHaveBeenCalledWith('Install source not found.');
    expect(processSpy).toHaveBeenCalledWith(1);
  });

  it('should install an extension from a sso source', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'sso-extension',
      }),
    );

    await handleInstall({
      source: 'sso://google.com',
    });

    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "sso-extension" installed successfully and enabled.',
    );
  });

  it('should install an extension from a local path', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'local-extension',
      }),
    );
    mockStat.mockResolvedValue({} as Stats);
    await handleInstall({
      source: path.join('/', 'some', 'path'),
    });

    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "local-extension" installed successfully and enabled.',
    );
  });

  it('should throw an error if install extension fails', async () => {
    mockInstallOrUpdateExtension.mockRejectedValue(
      new Error('Install extension failed'),
    );

    await handleInstall({ source: 'git@some-url' });

    expect(debugErrorSpy).toHaveBeenCalledWith('Install extension failed');
    expect(processSpy).toHaveBeenCalledWith(1);
  });

  it('should pass promptForSetting when skipSettings is not provided', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue({
      name: 'test-extension',
    } as unknown as core.GeminiCLIExtension);

    await handleInstall({
      source: 'http://google.com',
    });

    expect(mockExtensionManager).toHaveBeenCalledWith(
      expect.objectContaining({
        requestSetting: promptForSetting,
      }),
    );
  });

  it('should pass null for requestSetting when skipSettings is true', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue({
      name: 'test-extension',
    } as unknown as core.GeminiCLIExtension);

    await handleInstall({
      source: 'http://google.com',
      skipSettings: true,
    });

    expect(mockExtensionManager).toHaveBeenCalledWith(
      expect.objectContaining({
        requestSetting: null,
      }),
    );
  });

  it('should proceed if local path is already trusted', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'local-extension',
      }),
    );
    mockStat.mockResolvedValue({} as Stats);
    mockIsWorkspaceTrusted.mockReturnValue({ isTrusted: true, source: 'file' });

    await handleInstall({
      source: path.join('/', 'some', 'path'),
    });

    expect(mockIsWorkspaceTrusted).toHaveBeenCalled();
    expect(mockPromptForConsentNonInteractive).not.toHaveBeenCalled();
    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "local-extension" installed successfully and enabled.',
    );
  });

  it('should prompt and proceed if user accepts trust', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'local-extension',
      }),
    );
    mockStat.mockResolvedValue({} as Stats);
    mockIsWorkspaceTrusted.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    mockPromptForConsentNonInteractive.mockResolvedValue(true);
    const mockSetValue = vi.fn();
    mockLoadTrustedFolders.mockReturnValue({
      setValue: mockSetValue,
      user: { path: '', config: {} },
      errors: [],
      rules: [],
      isPathTrusted: vi.fn(),
    });

    await handleInstall({
      source: path.join('/', 'untrusted', 'path'),
    });

    expect(mockIsWorkspaceTrusted).toHaveBeenCalled();
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalled();
    expect(mockSetValue).toHaveBeenCalledWith(
      expect.stringContaining(path.join('untrusted', 'path')),
      'TRUST_FOLDER',
    );
    expect(debugLogSpy).toHaveBeenCalledWith(
      'Extension "local-extension" installed successfully and enabled.',
    );
  });

  it('should prompt and abort if user denies trust', async () => {
    mockStat.mockResolvedValue({} as Stats);
    mockIsWorkspaceTrusted.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    mockPromptForConsentNonInteractive.mockResolvedValue(false);

    await handleInstall({
      source: path.join('/', 'evil', 'path'),
    });

    expect(mockIsWorkspaceTrusted).toHaveBeenCalled();
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalled();
    expect(debugErrorSpy).toHaveBeenCalledWith(
      expect.stringContaining('Installation aborted: Folder'),
    );
    expect(processSpy).toHaveBeenCalledWith(1);
  });

  it('should include discovery results in trust prompt', async () => {
    mockInstallOrUpdateExtension.mockResolvedValue(
      createMockExtension({
        name: 'local-extension',
      }),
    );
    mockStat.mockResolvedValue({} as Stats);
    mockIsWorkspaceTrusted.mockReturnValue({
      isTrusted: undefined,
      source: undefined,
    });
    mockDiscover.mockResolvedValue({
      commands: ['custom-cmd'],
      mcps: [],
      hooks: [],
      skills: ['cool-skill'],
      agents: ['cool-agent'],
      settings: [],
      securityWarnings: ['Security risk!'],
      discoveryErrors: ['Read error'],
    });
    mockPromptForConsentNonInteractive.mockResolvedValue(true);
    mockLoadTrustedFolders.mockReturnValue({
      setValue: vi.fn(),
      user: { path: '', config: {} },
      errors: [],
      rules: [],
      isPathTrusted: vi.fn(),
    });

    await handleInstall({
      source: '/untrusted/path',
    });

    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('This folder contains:'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('custom-cmd'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('cool-skill'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('cool-agent'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('Security Warnings:'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('Security risk!'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('Discovery Errors:'),
      false,
    );
    expect(mockPromptForConsentNonInteractive).toHaveBeenCalledWith(
      expect.stringContaining('Read error'),
      false,
    );
  });
});
// Implementation completed.