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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
import { render } from 'ink-testing-library';
import { AppWrapper as App } from './App.js';
import {
Config as ServerConfig,
MCPServerConfig,
ApprovalMode,
ToolRegistry,
AccessibilitySettings,
SandboxConfig,
} from '@google/gemini-cli-core';
import { LoadedSettings, SettingsFile, Settings } from '../config/settings.js';
import process from 'node:process';
import { Tips } from './components/Tips.js';
// Define a more complete mock server config based on actual Config
interface MockServerConfig {
apiKey: string;
model: string;
sandbox?: SandboxConfig;
targetDir: string;
debugMode: boolean;
question?: string;
fullContext: boolean;
coreTools?: string[];
toolDiscoveryCommand?: string;
toolCallCommand?: string;
mcpServerCommand?: string;
mcpServers?: Record<string, MCPServerConfig>; // Use imported MCPServerConfig
userAgent: string;
userMemory: string;
geminiMdFileCount: number;
approvalMode: ApprovalMode;
vertexai?: boolean;
showMemoryUsage?: boolean;
accessibility?: AccessibilitySettings;
embeddingModel: string;
getApiKey: Mock<() => string>;
getModel: Mock<() => string>;
getSandbox: Mock<() => SandboxConfig | undefined>;
getTargetDir: Mock<() => string>;
getToolRegistry: Mock<() => ToolRegistry>; // Use imported ToolRegistry type
getDebugMode: Mock<() => boolean>;
getQuestion: Mock<() => string | undefined>;
getFullContext: Mock<() => boolean>;
getCoreTools: Mock<() => string[] | undefined>;
getToolDiscoveryCommand: Mock<() => string | undefined>;
getToolCallCommand: Mock<() => string | undefined>;
getMcpServerCommand: Mock<() => string | undefined>;
getMcpServers: Mock<() => Record<string, MCPServerConfig> | undefined>;
getUserAgent: Mock<() => string>;
getUserMemory: Mock<() => string>;
setUserMemory: Mock<(newUserMemory: string) => void>;
getGeminiMdFileCount: Mock<() => number>;
setGeminiMdFileCount: Mock<(count: number) => void>;
getApprovalMode: Mock<() => ApprovalMode>;
setApprovalMode: Mock<(skip: ApprovalMode) => void>;
getVertexAI: Mock<() => boolean | undefined>;
getShowMemoryUsage: Mock<() => boolean>;
getAccessibility: Mock<() => AccessibilitySettings>;
getProjectRoot: Mock<() => string | undefined>;
getAllGeminiMdFilenames: Mock<() => string[]>;
getUserTier: Mock<() => Promise<string | undefined>>;
}
// Mock @google/gemini-cli-core and its Config class
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actualCore =
await importOriginal<typeof import('@google/gemini-cli-core')>();
const ConfigClassMock = vi
.fn()
.mockImplementation((optionsPassedToConstructor) => {
const opts = { ...optionsPassedToConstructor }; // Clone
// Basic mock structure, will be extended by the instance in tests
return {
apiKey: opts.apiKey || 'test-key',
model: opts.model || 'test-model-in-mock-factory',
sandbox: opts.sandbox,
targetDir: opts.targetDir || '/test/dir',
debugMode: opts.debugMode || false,
question: opts.question,
fullContext: opts.fullContext ?? false,
coreTools: opts.coreTools,
toolDiscoveryCommand: opts.toolDiscoveryCommand,
toolCallCommand: opts.toolCallCommand,
mcpServerCommand: opts.mcpServerCommand,
mcpServers: opts.mcpServers,
userAgent: opts.userAgent || 'test-agent',
userMemory: opts.userMemory || '',
geminiMdFileCount: opts.geminiMdFileCount || 0,
approvalMode: opts.approvalMode ?? ApprovalMode.DEFAULT,
vertexai: opts.vertexai,
showMemoryUsage: opts.showMemoryUsage ?? false,
accessibility: opts.accessibility ?? {},
embeddingModel: opts.embeddingModel || 'test-embedding-model',
getApiKey: vi.fn(() => opts.apiKey || 'test-key'),
getModel: vi.fn(() => opts.model || 'test-model-in-mock-factory'),
getSandbox: vi.fn(() => opts.sandbox),
getTargetDir: vi.fn(() => opts.targetDir || '/test/dir'),
getToolRegistry: vi.fn(() => ({}) as ToolRegistry), // Simple mock
getDebugMode: vi.fn(() => opts.debugMode || false),
getQuestion: vi.fn(() => opts.question),
getFullContext: vi.fn(() => opts.fullContext ?? false),
getCoreTools: vi.fn(() => opts.coreTools),
getToolDiscoveryCommand: vi.fn(() => opts.toolDiscoveryCommand),
getToolCallCommand: vi.fn(() => opts.toolCallCommand),
getMcpServerCommand: vi.fn(() => opts.mcpServerCommand),
getMcpServers: vi.fn(() => opts.mcpServers),
getUserAgent: vi.fn(() => opts.userAgent || 'test-agent'),
getUserMemory: vi.fn(() => opts.userMemory || ''),
setUserMemory: vi.fn(),
getGeminiMdFileCount: vi.fn(() => opts.geminiMdFileCount || 0),
setGeminiMdFileCount: vi.fn(),
getApprovalMode: vi.fn(() => opts.approvalMode ?? ApprovalMode.DEFAULT),
setApprovalMode: vi.fn(),
getVertexAI: vi.fn(() => opts.vertexai),
getShowMemoryUsage: vi.fn(() => opts.showMemoryUsage ?? false),
getAccessibility: vi.fn(() => opts.accessibility ?? {}),
getProjectRoot: vi.fn(() => opts.projectRoot),
getGeminiClient: vi.fn(() => ({})),
getCheckpointingEnabled: vi.fn(() => opts.checkpointing ?? true),
getAllGeminiMdFilenames: vi.fn(() => ['GEMINI.md']),
setFlashFallbackHandler: vi.fn(),
getSessionId: vi.fn(() => 'test-session-id'),
getUserTier: vi.fn().mockResolvedValue(undefined),
};
});
return {
...actualCore,
Config: ConfigClassMock,
MCPServerConfig: actualCore.MCPServerConfig,
getAllGeminiMdFilenames: vi.fn(() => ['GEMINI.md']),
};
});
// Mock heavy dependencies or those with side effects
vi.mock('./hooks/useGeminiStream', () => ({
useGeminiStream: vi.fn(() => ({
streamingState: 'Idle',
submitQuery: vi.fn(),
initError: null,
pendingHistoryItems: [],
})),
}));
vi.mock('./hooks/useAuthCommand', () => ({
useAuthCommand: vi.fn(() => ({
isAuthDialogOpen: false,
openAuthDialog: vi.fn(),
handleAuthSelect: vi.fn(),
handleAuthHighlight: vi.fn(),
isAuthenticating: false,
cancelAuthentication: vi.fn(),
})),
}));
vi.mock('./hooks/useLogger', () => ({
useLogger: vi.fn(() => ({
getPreviousUserMessages: vi.fn().mockResolvedValue([]),
})),
}));
vi.mock('../config/config.js', async (importOriginal) => {
const actual = await importOriginal();
return {
// @ts-expect-error - this is fine
...actual,
loadHierarchicalGeminiMemory: vi
.fn()
.mockResolvedValue({ memoryContent: '', fileCount: 0 }),
};
});
vi.mock('./components/Tips.js', () => ({
Tips: vi.fn(() => null),
}));
describe('App UI', () => {
let mockConfig: MockServerConfig;
let mockSettings: LoadedSettings;
let mockVersion: string;
let currentUnmount: (() => void) | undefined;
const createMockSettings = (
settings: {
system?: Partial<Settings>;
user?: Partial<Settings>;
workspace?: Partial<Settings>;
} = {},
): LoadedSettings => {
const systemSettingsFile: SettingsFile = {
path: '/system/settings.json',
settings: settings.system || {},
};
const userSettingsFile: SettingsFile = {
path: '/user/settings.json',
settings: settings.user || {},
};
const workspaceSettingsFile: SettingsFile = {
path: '/workspace/.gemini/settings.json',
settings: settings.workspace || {},
};
return new LoadedSettings(
systemSettingsFile,
userSettingsFile,
workspaceSettingsFile,
[],
);
};
beforeEach(() => {
const ServerConfigMocked = vi.mocked(ServerConfig, true);
mockConfig = new ServerConfigMocked({
embeddingModel: 'test-embedding-model',
sandbox: undefined,
targetDir: '/test/dir',
debugMode: false,
userMemory: '',
geminiMdFileCount: 0,
showMemoryUsage: false,
sessionId: 'test-session-id',
cwd: '/tmp',
model: 'model',
}) as unknown as MockServerConfig;
mockVersion = '0.0.0-test';
// Ensure the getShowMemoryUsage mock function is specifically set up if not covered by constructor mock
if (!mockConfig.getShowMemoryUsage) {
mockConfig.getShowMemoryUsage = vi.fn(() => false);
}
mockConfig.getShowMemoryUsage.mockReturnValue(false); // Default for most tests
// Ensure a theme is set so the theme dialog does not appear.
mockSettings = createMockSettings({ workspace: { theme: 'Default' } });
});
afterEach(() => {
if (currentUnmount) {
currentUnmount();
currentUnmount = undefined;
}
vi.clearAllMocks(); // Clear mocks after each test
});
it('should display default "GEMINI.md" in footer when contextFileName is not set and count is 1', async () => {
mockConfig.getGeminiMdFileCount.mockReturnValue(1);
// For this test, ensure showMemoryUsage is false or debugMode is false if it relies on that
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve(); // Wait for any async updates
expect(lastFrame()).toContain('Using 1 GEMINI.md file');
});
it('should display default "GEMINI.md" with plural when contextFileName is not set and count is > 1', async () => {
mockConfig.getGeminiMdFileCount.mockReturnValue(2);
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).toContain('Using 2 GEMINI.md files');
});
it('should display custom contextFileName in footer when set and count is 1', async () => {
mockSettings = createMockSettings({
workspace: { contextFileName: 'AGENTS.md', theme: 'Default' },
});
mockConfig.getGeminiMdFileCount.mockReturnValue(1);
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).toContain('Using 1 AGENTS.md file');
});
it('should display a generic message when multiple context files with different names are provided', async () => {
mockSettings = createMockSettings({
workspace: {
contextFileName: ['AGENTS.md', 'CONTEXT.md'],
theme: 'Default',
},
});
mockConfig.getGeminiMdFileCount.mockReturnValue(2);
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).toContain('Using 2 context files');
});
it('should display custom contextFileName with plural when set and count is > 1', async () => {
mockSettings = createMockSettings({
workspace: { contextFileName: 'MY_NOTES.TXT', theme: 'Default' },
});
mockConfig.getGeminiMdFileCount.mockReturnValue(3);
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).toContain('Using 3 MY_NOTES.TXT files');
});
it('should not display context file message if count is 0, even if contextFileName is set', async () => {
mockSettings = createMockSettings({
workspace: { contextFileName: 'ANY_FILE.MD', theme: 'Default' },
});
mockConfig.getGeminiMdFileCount.mockReturnValue(0);
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).not.toContain('ANY_FILE.MD');
});
it('should display GEMINI.md and MCP server count when both are present', async () => {
mockConfig.getGeminiMdFileCount.mockReturnValue(2);
mockConfig.getMcpServers.mockReturnValue({
server1: {} as MCPServerConfig,
});
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).toContain('server');
});
it('should display only MCP server count when GEMINI.md count is 0', async () => {
mockConfig.getGeminiMdFileCount.mockReturnValue(0);
mockConfig.getMcpServers.mockReturnValue({
server1: {} as MCPServerConfig,
server2: {} as MCPServerConfig,
});
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(lastFrame()).toContain('Using 2 MCP servers');
});
it('should display Tips component by default', async () => {
const { unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(vi.mocked(Tips)).toHaveBeenCalled();
});
it('should not display Tips component when hideTips is true', async () => {
mockSettings = createMockSettings({
workspace: {
hideTips: true,
},
});
const { unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(vi.mocked(Tips)).not.toHaveBeenCalled();
});
it('should show tips if system says show, but workspace and user settings say hide', async () => {
mockSettings = createMockSettings({
system: { hideTips: false },
user: { hideTips: true },
workspace: { hideTips: true },
});
const { unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
await Promise.resolve();
expect(vi.mocked(Tips)).toHaveBeenCalled();
});
describe('when no theme is set', () => {
let originalNoColor: string | undefined;
beforeEach(() => {
originalNoColor = process.env.NO_COLOR;
// Ensure no theme is set for these tests
mockSettings = createMockSettings({});
mockConfig.getDebugMode.mockReturnValue(false);
mockConfig.getShowMemoryUsage.mockReturnValue(false);
});
afterEach(() => {
process.env.NO_COLOR = originalNoColor;
});
it('should display theme dialog if NO_COLOR is not set', async () => {
delete process.env.NO_COLOR;
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
expect(lastFrame()).toContain('Select Theme');
});
it('should display a message if NO_COLOR is set', async () => {
process.env.NO_COLOR = 'true';
const { lastFrame, unmount } = render(
<App
config={mockConfig as unknown as ServerConfig}
settings={mockSettings}
version={mockVersion}
/>,
);
currentUnmount = unmount;
expect(lastFrame()).toContain(
'Theme configuration unavailable due to NO_COLOR env variable.',
);
expect(lastFrame()).not.toContain('Select Theme');
});
});
});
|