@google/gemini-cli 0.1.10-dev.15 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +16 -2
  2. package/dist/google-gemini-cli-0.1.9.tgz +0 -0
  3. package/dist/package.json +7 -7
  4. package/dist/src/config/auth.js +6 -5
  5. package/dist/src/config/auth.js.map +1 -1
  6. package/dist/src/config/config.d.ts +0 -1
  7. package/dist/src/config/config.js +62 -50
  8. package/dist/src/config/config.js.map +1 -1
  9. package/dist/src/config/extension.d.ts +1 -0
  10. package/dist/src/config/extension.js +34 -6
  11. package/dist/src/config/extension.js.map +1 -1
  12. package/dist/src/config/sandboxConfig.d.ts +1 -1
  13. package/dist/src/config/sandboxConfig.js +1 -1
  14. package/dist/src/config/sandboxConfig.js.map +1 -1
  15. package/dist/src/config/settings.d.ts +7 -2
  16. package/dist/src/config/settings.js +101 -3
  17. package/dist/src/config/settings.js.map +1 -1
  18. package/dist/src/gemini.js +30 -21
  19. package/dist/src/gemini.js.map +1 -1
  20. package/dist/src/generated/git-commit.d.ts +1 -1
  21. package/dist/src/generated/git-commit.js +1 -1
  22. package/dist/src/nonInteractiveCli.d.ts +1 -1
  23. package/dist/src/nonInteractiveCli.js +4 -2
  24. package/dist/src/nonInteractiveCli.js.map +1 -1
  25. package/dist/src/services/CommandService.d.ts +13 -0
  26. package/dist/src/services/CommandService.js +30 -0
  27. package/dist/src/services/CommandService.js.map +1 -0
  28. package/dist/src/ui/App.js +71 -12
  29. package/dist/src/ui/App.js.map +1 -1
  30. package/dist/src/ui/commands/clearCommand.d.ts +7 -0
  31. package/dist/src/ui/commands/clearCommand.js +15 -0
  32. package/dist/src/ui/commands/clearCommand.js.map +1 -0
  33. package/dist/src/ui/commands/helpCommand.d.ts +7 -0
  34. package/dist/src/ui/commands/helpCommand.js +18 -0
  35. package/dist/src/ui/commands/helpCommand.js.map +1 -0
  36. package/dist/src/ui/commands/memoryCommand.d.ts +7 -0
  37. package/dist/src/ui/commands/memoryCommand.js +81 -0
  38. package/dist/src/ui/commands/memoryCommand.js.map +1 -0
  39. package/dist/src/ui/commands/types.d.ts +63 -0
  40. package/dist/src/{gemini.test.d.ts → ui/commands/types.js} +1 -0
  41. package/dist/src/ui/commands/types.js.map +1 -0
  42. package/dist/src/ui/components/AuthDialog.js +36 -8
  43. package/dist/src/ui/components/AuthDialog.js.map +1 -1
  44. package/dist/src/ui/components/Help.d.ts +1 -1
  45. package/dist/src/ui/components/Help.js +3 -2
  46. package/dist/src/ui/components/Help.js.map +1 -1
  47. package/dist/src/ui/components/InputPrompt.d.ts +2 -1
  48. package/dist/src/ui/components/InputPrompt.js +106 -157
  49. package/dist/src/ui/components/InputPrompt.js.map +1 -1
  50. package/dist/src/ui/components/LoadingIndicator.js +2 -1
  51. package/dist/src/ui/components/LoadingIndicator.js.map +1 -1
  52. package/dist/src/ui/components/ThemeDialog.js +10 -9
  53. package/dist/src/ui/components/ThemeDialog.js.map +1 -1
  54. package/dist/src/ui/components/messages/CompressionMessage.js +1 -1
  55. package/dist/src/ui/components/shared/MaxSizedBox.js +1 -1
  56. package/dist/src/ui/components/shared/MaxSizedBox.js.map +1 -1
  57. package/dist/src/ui/components/shared/text-buffer.d.ts +2 -1
  58. package/dist/src/ui/components/shared/text-buffer.js +3 -3
  59. package/dist/src/ui/components/shared/text-buffer.js.map +1 -1
  60. package/dist/src/ui/contexts/SessionContext.d.ts +4 -1
  61. package/dist/src/ui/contexts/SessionContext.js +12 -2
  62. package/dist/src/ui/contexts/SessionContext.js.map +1 -1
  63. package/dist/src/ui/hooks/atCommandProcessor.js +5 -7
  64. package/dist/src/ui/hooks/atCommandProcessor.js.map +1 -1
  65. package/dist/src/ui/hooks/slashCommandProcessor.d.ts +6 -10
  66. package/dist/src/ui/hooks/slashCommandProcessor.js +217 -121
  67. package/dist/src/ui/hooks/slashCommandProcessor.js.map +1 -1
  68. package/dist/src/ui/hooks/useCompletion.d.ts +2 -2
  69. package/dist/src/ui/hooks/useCompletion.js +106 -56
  70. package/dist/src/ui/hooks/useCompletion.js.map +1 -1
  71. package/dist/src/ui/hooks/useGeminiStream.d.ts +3 -3
  72. package/dist/src/ui/hooks/useGeminiStream.js +45 -28
  73. package/dist/src/ui/hooks/useGeminiStream.js.map +1 -1
  74. package/dist/src/ui/types.d.ts +10 -0
  75. package/dist/src/ui/utils/InlineMarkdownRenderer.d.ts +16 -0
  76. package/dist/src/ui/utils/InlineMarkdownRenderer.js +104 -0
  77. package/dist/src/ui/utils/InlineMarkdownRenderer.js.map +1 -0
  78. package/dist/src/ui/utils/MarkdownDisplay.js +1 -80
  79. package/dist/src/ui/utils/MarkdownDisplay.js.map +1 -1
  80. package/dist/src/ui/utils/TableRenderer.js +50 -32
  81. package/dist/src/ui/utils/TableRenderer.js.map +1 -1
  82. package/dist/src/ui/utils/errorParsing.d.ts +2 -10
  83. package/dist/src/ui/utils/errorParsing.js +34 -23
  84. package/dist/src/ui/utils/errorParsing.js.map +1 -1
  85. package/dist/src/utils/sandbox-macos-permissive-proxied.sb +1 -1
  86. package/dist/src/utils/sandbox-macos-restrictive-proxied.sb +1 -1
  87. package/dist/src/utils/userStartupWarnings.d.ts +6 -0
  88. package/dist/src/utils/userStartupWarnings.js +33 -0
  89. package/dist/src/utils/userStartupWarnings.js.map +1 -0
  90. package/dist/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +8 -8
  92. package/dist/src/gemini.test.js +0 -122
  93. package/dist/src/gemini.test.js.map +0 -1
  94. package/dist/src/ui/App.test.d.ts +0 -6
  95. package/dist/src/ui/App.test.js +0 -299
  96. package/dist/src/ui/App.test.js.map +0 -1
  97. package/dist/src/ui/components/AuthDialog.test.d.ts +0 -6
  98. package/dist/src/ui/components/AuthDialog.test.js +0 -69
  99. package/dist/src/ui/components/AuthDialog.test.js.map +0 -1
  100. package/dist/src/ui/components/HistoryItemDisplay.test.d.ts +0 -6
  101. package/dist/src/ui/components/HistoryItemDisplay.test.js +0 -81
  102. package/dist/src/ui/components/HistoryItemDisplay.test.js.map +0 -1
  103. package/dist/src/ui/components/InputPrompt.test.d.ts +0 -6
  104. package/dist/src/ui/components/InputPrompt.test.js +0 -154
  105. package/dist/src/ui/components/InputPrompt.test.js.map +0 -1
  106. package/dist/src/ui/components/LoadingIndicator.test.d.ts +0 -6
  107. package/dist/src/ui/components/LoadingIndicator.test.js +0 -141
  108. package/dist/src/ui/components/LoadingIndicator.test.js.map +0 -1
  109. package/dist/src/ui/components/ModelStatsDisplay.test.d.ts +0 -6
  110. package/dist/src/ui/components/ModelStatsDisplay.test.js +0 -217
  111. package/dist/src/ui/components/ModelStatsDisplay.test.js.map +0 -1
  112. package/dist/src/ui/components/SessionSummaryDisplay.test.d.ts +0 -6
  113. package/dist/src/ui/components/SessionSummaryDisplay.test.js +0 -60
  114. package/dist/src/ui/components/SessionSummaryDisplay.test.js.map +0 -1
  115. package/dist/src/ui/components/StatsDisplay.test.d.ts +0 -6
  116. package/dist/src/ui/components/StatsDisplay.test.js +0 -275
  117. package/dist/src/ui/components/StatsDisplay.test.js.map +0 -1
  118. package/dist/src/ui/components/ToolStatsDisplay.test.d.ts +0 -6
  119. package/dist/src/ui/components/ToolStatsDisplay.test.js +0 -160
  120. package/dist/src/ui/components/ToolStatsDisplay.test.js.map +0 -1
  121. package/dist/src/ui/components/messages/DiffRenderer.test.d.ts +0 -6
  122. package/dist/src/ui/components/messages/DiffRenderer.test.js +0 -239
  123. package/dist/src/ui/components/messages/DiffRenderer.test.js.map +0 -1
  124. package/dist/src/ui/components/messages/ToolConfirmationMessage.test.d.ts +0 -6
  125. package/dist/src/ui/components/messages/ToolConfirmationMessage.test.js +0 -37
  126. package/dist/src/ui/components/messages/ToolConfirmationMessage.test.js.map +0 -1
  127. package/dist/src/ui/components/messages/ToolMessage.test.d.ts +0 -6
  128. package/dist/src/ui/components/messages/ToolMessage.test.js +0 -116
  129. package/dist/src/ui/components/messages/ToolMessage.test.js.map +0 -1
  130. package/dist/src/ui/components/shared/MaxSizedBox.test.d.ts +0 -6
  131. package/dist/src/ui/components/shared/MaxSizedBox.test.js +0 -134
  132. package/dist/src/ui/components/shared/MaxSizedBox.test.js.map +0 -1
  133. package/dist/src/ui/contexts/SessionContext.test.d.ts +0 -6
  134. package/dist/src/ui/contexts/SessionContext.test.js +0 -96
  135. package/dist/src/ui/contexts/SessionContext.test.js.map +0 -1
  136. package/dist/src/ui/hooks/useGeminiStream.test.d.ts +0 -6
  137. package/dist/src/ui/hooks/useGeminiStream.test.js +0 -775
  138. package/dist/src/ui/hooks/useGeminiStream.test.js.map +0 -1
  139. package/dist/src/ui/utils/MarkdownDisplay.test.d.ts +0 -6
  140. package/dist/src/ui/utils/MarkdownDisplay.test.js +0 -176
  141. package/dist/src/ui/utils/MarkdownDisplay.test.js.map +0 -1
@@ -1,775 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2025 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- /* eslint-disable @typescript-eslint/no-explicit-any */
7
- import { describe, it, expect, vi, beforeEach } from 'vitest';
8
- import { renderHook, act, waitFor } from '@testing-library/react';
9
- import { useGeminiStream, mergePartListUnions } from './useGeminiStream.js';
10
- import { useInput } from 'ink';
11
- import { useReactToolScheduler, } from './useReactToolScheduler.js';
12
- import { AuthType } from '@google/gemini-cli-core';
13
- import { MessageType, StreamingState } from '../types.js';
14
- // --- MOCKS ---
15
- const mockSendMessageStream = vi
16
- .fn()
17
- .mockReturnValue((async function* () { })());
18
- const mockStartChat = vi.fn();
19
- const MockedGeminiClientClass = vi.hoisted(() => vi.fn().mockImplementation(function (_config) {
20
- // _config
21
- this.startChat = mockStartChat;
22
- this.sendMessageStream = mockSendMessageStream;
23
- this.addHistory = vi.fn();
24
- }));
25
- const MockedUserPromptEvent = vi.hoisted(() => vi.fn().mockImplementation(() => { }));
26
- vi.mock('@google/gemini-cli-core', async (importOriginal) => {
27
- const actualCoreModule = (await importOriginal());
28
- return {
29
- ...actualCoreModule,
30
- GitService: vi.fn(),
31
- GeminiClient: MockedGeminiClientClass,
32
- UserPromptEvent: MockedUserPromptEvent,
33
- };
34
- });
35
- const mockUseReactToolScheduler = useReactToolScheduler;
36
- vi.mock('./useReactToolScheduler.js', async (importOriginal) => {
37
- const actualSchedulerModule = (await importOriginal());
38
- return {
39
- ...(actualSchedulerModule || {}),
40
- useReactToolScheduler: vi.fn(),
41
- };
42
- });
43
- vi.mock('ink', async (importOriginal) => {
44
- const actualInkModule = (await importOriginal());
45
- return { ...(actualInkModule || {}), useInput: vi.fn() };
46
- });
47
- vi.mock('./shellCommandProcessor.js', () => ({
48
- useShellCommandProcessor: vi.fn().mockReturnValue({
49
- handleShellCommand: vi.fn(),
50
- }),
51
- }));
52
- vi.mock('./atCommandProcessor.js', () => ({
53
- handleAtCommand: vi
54
- .fn()
55
- .mockResolvedValue({ shouldProceed: true, processedQuery: 'mocked' }),
56
- }));
57
- vi.mock('../utils/markdownUtilities.js', () => ({
58
- findLastSafeSplitPoint: vi.fn((s) => s.length),
59
- }));
60
- vi.mock('./useStateAndRef.js', () => ({
61
- useStateAndRef: vi.fn((initial) => {
62
- let val = initial;
63
- const ref = { current: val };
64
- const setVal = vi.fn((updater) => {
65
- if (typeof updater === 'function') {
66
- val = updater(val);
67
- }
68
- else {
69
- val = updater;
70
- }
71
- ref.current = val;
72
- });
73
- return [ref, setVal];
74
- }),
75
- }));
76
- vi.mock('./useLogger.js', () => ({
77
- useLogger: vi.fn().mockReturnValue({
78
- logMessage: vi.fn().mockResolvedValue(undefined),
79
- }),
80
- }));
81
- const mockStartNewTurn = vi.fn();
82
- const mockAddUsage = vi.fn();
83
- vi.mock('../contexts/SessionContext.js', () => ({
84
- useSessionStats: vi.fn(() => ({
85
- startNewTurn: mockStartNewTurn,
86
- addUsage: mockAddUsage,
87
- })),
88
- }));
89
- vi.mock('./slashCommandProcessor.js', () => ({
90
- handleSlashCommand: vi.fn().mockReturnValue(false),
91
- }));
92
- const mockParseAndFormatApiError = vi.hoisted(() => vi.fn());
93
- vi.mock('../utils/errorParsing.js', () => ({
94
- parseAndFormatApiError: mockParseAndFormatApiError,
95
- }));
96
- // --- END MOCKS ---
97
- describe('mergePartListUnions', () => {
98
- it('should merge multiple PartListUnion arrays', () => {
99
- const list1 = [{ text: 'Hello' }];
100
- const list2 = [
101
- { inlineData: { mimeType: 'image/png', data: 'abc' } },
102
- ];
103
- const list3 = [{ text: 'World' }, { text: '!' }];
104
- const result = mergePartListUnions([list1, list2, list3]);
105
- expect(result).toEqual([
106
- { text: 'Hello' },
107
- { inlineData: { mimeType: 'image/png', data: 'abc' } },
108
- { text: 'World' },
109
- { text: '!' },
110
- ]);
111
- });
112
- it('should handle empty arrays in the input list', () => {
113
- const list1 = [{ text: 'First' }];
114
- const list2 = [];
115
- const list3 = [{ text: 'Last' }];
116
- const result = mergePartListUnions([list1, list2, list3]);
117
- expect(result).toEqual([{ text: 'First' }, { text: 'Last' }]);
118
- });
119
- it('should handle a single PartListUnion array', () => {
120
- const list1 = [
121
- { text: 'One' },
122
- { inlineData: { mimeType: 'image/jpeg', data: 'xyz' } },
123
- ];
124
- const result = mergePartListUnions([list1]);
125
- expect(result).toEqual(list1);
126
- });
127
- it('should return an empty array if all input arrays are empty', () => {
128
- const list1 = [];
129
- const list2 = [];
130
- const result = mergePartListUnions([list1, list2]);
131
- expect(result).toEqual([]);
132
- });
133
- it('should handle input list being empty', () => {
134
- const result = mergePartListUnions([]);
135
- expect(result).toEqual([]);
136
- });
137
- it('should correctly merge when PartListUnion items are single Parts not in arrays', () => {
138
- const part1 = { text: 'Single part 1' };
139
- const part2 = { inlineData: { mimeType: 'image/gif', data: 'gif' } };
140
- const listContainingSingleParts = [
141
- part1,
142
- [part2],
143
- { text: 'Another single part' },
144
- ];
145
- const result = mergePartListUnions(listContainingSingleParts);
146
- expect(result).toEqual([
147
- { text: 'Single part 1' },
148
- { inlineData: { mimeType: 'image/gif', data: 'gif' } },
149
- { text: 'Another single part' },
150
- ]);
151
- });
152
- it('should handle a mix of arrays and single parts, including empty arrays and undefined/null parts if they were possible (though PartListUnion typing restricts this)', () => {
153
- const list1 = [{ text: 'A' }];
154
- const list2 = [];
155
- const part3 = { text: 'B' };
156
- const list4 = [
157
- { text: 'C' },
158
- { inlineData: { mimeType: 'text/plain', data: 'D' } },
159
- ];
160
- const result = mergePartListUnions([list1, list2, part3, list4]);
161
- expect(result).toEqual([
162
- { text: 'A' },
163
- { text: 'B' },
164
- { text: 'C' },
165
- { inlineData: { mimeType: 'text/plain', data: 'D' } },
166
- ]);
167
- });
168
- it('should preserve the order of parts from the input arrays', () => {
169
- const listA = [{ text: '1' }, { text: '2' }];
170
- const listB = [{ text: '3' }];
171
- const listC = [{ text: '4' }, { text: '5' }];
172
- const result = mergePartListUnions([listA, listB, listC]);
173
- expect(result).toEqual([
174
- { text: '1' },
175
- { text: '2' },
176
- { text: '3' },
177
- { text: '4' },
178
- { text: '5' },
179
- ]);
180
- });
181
- it('should handle cases where some PartListUnion items are single Parts and others are arrays of Parts', () => {
182
- const singlePart1 = { text: 'First single' };
183
- const arrayPart1 = [
184
- { text: 'Array item 1' },
185
- { text: 'Array item 2' },
186
- ];
187
- const singlePart2 = {
188
- inlineData: { mimeType: 'application/json', data: 'e30=' },
189
- }; // {}
190
- const arrayPart2 = [{ text: 'Last array item' }];
191
- const result = mergePartListUnions([
192
- singlePart1,
193
- arrayPart1,
194
- singlePart2,
195
- arrayPart2,
196
- ]);
197
- expect(result).toEqual([
198
- { text: 'First single' },
199
- { text: 'Array item 1' },
200
- { text: 'Array item 2' },
201
- { inlineData: { mimeType: 'application/json', data: 'e30=' } },
202
- { text: 'Last array item' },
203
- ]);
204
- });
205
- });
206
- // --- Tests for useGeminiStream Hook ---
207
- describe('useGeminiStream', () => {
208
- let mockAddItem;
209
- let mockSetShowHelp;
210
- let mockConfig;
211
- let mockOnDebugMessage;
212
- let mockHandleSlashCommand;
213
- let mockScheduleToolCalls;
214
- let mockCancelAllToolCalls;
215
- let mockMarkToolsAsSubmitted;
216
- beforeEach(() => {
217
- vi.clearAllMocks(); // Clear mocks before each test
218
- mockAddItem = vi.fn();
219
- mockSetShowHelp = vi.fn();
220
- // Define the mock for getGeminiClient
221
- const mockGetGeminiClient = vi.fn().mockImplementation(() => {
222
- // MockedGeminiClientClass is defined in the module scope by the previous change.
223
- // It will use the mockStartChat and mockSendMessageStream that are managed within beforeEach.
224
- const clientInstance = new MockedGeminiClientClass(mockConfig);
225
- return clientInstance;
226
- });
227
- mockConfig = {
228
- apiKey: 'test-api-key',
229
- model: 'gemini-pro',
230
- sandbox: false,
231
- targetDir: '/test/dir',
232
- debugMode: false,
233
- question: undefined,
234
- fullContext: false,
235
- coreTools: [],
236
- toolDiscoveryCommand: undefined,
237
- toolCallCommand: undefined,
238
- mcpServerCommand: undefined,
239
- mcpServers: undefined,
240
- userAgent: 'test-agent',
241
- userMemory: '',
242
- geminiMdFileCount: 0,
243
- alwaysSkipModificationConfirmation: false,
244
- vertexai: false,
245
- showMemoryUsage: false,
246
- contextFileName: undefined,
247
- getToolRegistry: vi.fn(() => ({ getToolSchemaList: vi.fn(() => []) })),
248
- getProjectRoot: vi.fn(() => '/test/dir'),
249
- getCheckpointingEnabled: vi.fn(() => false),
250
- getGeminiClient: mockGetGeminiClient,
251
- getUsageStatisticsEnabled: () => true,
252
- getDebugMode: () => false,
253
- addHistory: vi.fn(),
254
- };
255
- mockOnDebugMessage = vi.fn();
256
- mockHandleSlashCommand = vi.fn().mockResolvedValue(false);
257
- // Mock return value for useReactToolScheduler
258
- mockScheduleToolCalls = vi.fn();
259
- mockCancelAllToolCalls = vi.fn();
260
- mockMarkToolsAsSubmitted = vi.fn();
261
- // Default mock for useReactToolScheduler to prevent toolCalls being undefined initially
262
- mockUseReactToolScheduler.mockReturnValue([
263
- [], // Default to empty array for toolCalls
264
- mockScheduleToolCalls,
265
- mockCancelAllToolCalls,
266
- mockMarkToolsAsSubmitted,
267
- ]);
268
- // Reset mocks for GeminiClient instance methods (startChat and sendMessageStream)
269
- // The GeminiClient constructor itself is mocked at the module level.
270
- mockStartChat.mockClear().mockResolvedValue({
271
- sendMessageStream: mockSendMessageStream,
272
- }); // GeminiChat -> any
273
- mockSendMessageStream
274
- .mockClear()
275
- .mockReturnValue((async function* () { })());
276
- });
277
- const mockLoadedSettings = {
278
- merged: { preferredEditor: 'vscode' },
279
- user: { path: '/user/settings.json', settings: {} },
280
- workspace: { path: '/workspace/.gemini/settings.json', settings: {} },
281
- errors: [],
282
- forScope: vi.fn(),
283
- setValue: vi.fn(),
284
- };
285
- const renderTestHook = (initialToolCalls = [], geminiClient) => {
286
- let currentToolCalls = initialToolCalls;
287
- const setToolCalls = (newToolCalls) => {
288
- currentToolCalls = newToolCalls;
289
- };
290
- mockUseReactToolScheduler.mockImplementation(() => [
291
- currentToolCalls,
292
- mockScheduleToolCalls,
293
- mockCancelAllToolCalls,
294
- mockMarkToolsAsSubmitted,
295
- ]);
296
- const client = geminiClient || mockConfig.getGeminiClient();
297
- const { result, rerender } = renderHook((props) => {
298
- // Update the mock's return value if new toolCalls are passed in props
299
- if (props.toolCalls) {
300
- setToolCalls(props.toolCalls);
301
- }
302
- return useGeminiStream(props.client, props.history, props.addItem, props.setShowHelp, props.config, props.onDebugMessage, props.handleSlashCommand, props.shellModeActive, () => 'vscode', () => { }, () => Promise.resolve());
303
- }, {
304
- initialProps: {
305
- client,
306
- history: [],
307
- addItem: mockAddItem,
308
- setShowHelp: mockSetShowHelp,
309
- config: mockConfig,
310
- onDebugMessage: mockOnDebugMessage,
311
- handleSlashCommand: mockHandleSlashCommand,
312
- shellModeActive: false,
313
- loadedSettings: mockLoadedSettings,
314
- toolCalls: initialToolCalls,
315
- },
316
- });
317
- return {
318
- result,
319
- rerender,
320
- mockMarkToolsAsSubmitted,
321
- mockSendMessageStream,
322
- client,
323
- };
324
- };
325
- it('should not submit tool responses if not all tool calls are completed', () => {
326
- const toolCalls = [
327
- {
328
- request: {
329
- callId: 'call1',
330
- name: 'tool1',
331
- args: {},
332
- isClientInitiated: false,
333
- },
334
- status: 'success',
335
- responseSubmittedToGemini: false,
336
- response: {
337
- callId: 'call1',
338
- responseParts: [{ text: 'tool 1 response' }],
339
- error: undefined,
340
- resultDisplay: 'Tool 1 success display',
341
- },
342
- tool: {
343
- name: 'tool1',
344
- description: 'desc1',
345
- getDescription: vi.fn(),
346
- },
347
- startTime: Date.now(),
348
- endTime: Date.now(),
349
- },
350
- {
351
- request: { callId: 'call2', name: 'tool2', args: {} },
352
- status: 'executing',
353
- responseSubmittedToGemini: false,
354
- tool: {
355
- name: 'tool2',
356
- description: 'desc2',
357
- getDescription: vi.fn(),
358
- },
359
- startTime: Date.now(),
360
- liveOutput: '...',
361
- },
362
- ];
363
- const { mockMarkToolsAsSubmitted, mockSendMessageStream } = renderTestHook(toolCalls);
364
- // Effect for submitting tool responses depends on toolCalls and isResponding
365
- // isResponding is initially false, so the effect should run.
366
- expect(mockMarkToolsAsSubmitted).not.toHaveBeenCalled();
367
- expect(mockSendMessageStream).not.toHaveBeenCalled(); // submitQuery uses this
368
- });
369
- it('should submit tool responses when all tool calls are completed and ready', async () => {
370
- const toolCall1ResponseParts = [
371
- { text: 'tool 1 final response' },
372
- ];
373
- const toolCall2ResponseParts = [
374
- { text: 'tool 2 final response' },
375
- ];
376
- const completedToolCalls = [
377
- {
378
- request: {
379
- callId: 'call1',
380
- name: 'tool1',
381
- args: {},
382
- isClientInitiated: false,
383
- },
384
- status: 'success',
385
- responseSubmittedToGemini: false,
386
- response: { callId: 'call1', responseParts: toolCall1ResponseParts },
387
- },
388
- {
389
- request: {
390
- callId: 'call2',
391
- name: 'tool2',
392
- args: {},
393
- isClientInitiated: false,
394
- },
395
- status: 'error',
396
- responseSubmittedToGemini: false,
397
- response: { callId: 'call2', responseParts: toolCall2ResponseParts },
398
- },
399
- ];
400
- // Capture the onComplete callback
401
- let capturedOnComplete = null;
402
- mockUseReactToolScheduler.mockImplementation((onComplete) => {
403
- capturedOnComplete = onComplete;
404
- return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
405
- });
406
- renderHook(() => useGeminiStream(new MockedGeminiClientClass(mockConfig), [], mockAddItem, mockSetShowHelp, mockConfig, mockOnDebugMessage, mockHandleSlashCommand, false, () => 'vscode', () => { }, () => Promise.resolve()));
407
- // Trigger the onComplete callback with completed tools
408
- await act(async () => {
409
- if (capturedOnComplete) {
410
- await capturedOnComplete(completedToolCalls);
411
- }
412
- });
413
- await waitFor(() => {
414
- expect(mockMarkToolsAsSubmitted).toHaveBeenCalledTimes(1);
415
- expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
416
- });
417
- const expectedMergedResponse = mergePartListUnions([
418
- toolCall1ResponseParts,
419
- toolCall2ResponseParts,
420
- ]);
421
- expect(mockSendMessageStream).toHaveBeenCalledWith(expectedMergedResponse, expect.any(AbortSignal));
422
- });
423
- it('should handle all tool calls being cancelled', async () => {
424
- const cancelledToolCalls = [
425
- {
426
- request: {
427
- callId: '1',
428
- name: 'testTool',
429
- args: {},
430
- isClientInitiated: false,
431
- },
432
- status: 'cancelled',
433
- response: { callId: '1', responseParts: [{ text: 'cancelled' }] },
434
- responseSubmittedToGemini: false,
435
- },
436
- ];
437
- const client = new MockedGeminiClientClass(mockConfig);
438
- // Capture the onComplete callback
439
- let capturedOnComplete = null;
440
- mockUseReactToolScheduler.mockImplementation((onComplete) => {
441
- capturedOnComplete = onComplete;
442
- return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
443
- });
444
- renderHook(() => useGeminiStream(client, [], mockAddItem, mockSetShowHelp, mockConfig, mockOnDebugMessage, mockHandleSlashCommand, false, () => 'vscode', () => { }, () => Promise.resolve()));
445
- // Trigger the onComplete callback with cancelled tools
446
- await act(async () => {
447
- if (capturedOnComplete) {
448
- await capturedOnComplete(cancelledToolCalls);
449
- }
450
- });
451
- await waitFor(() => {
452
- expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['1']);
453
- expect(client.addHistory).toHaveBeenCalledWith({
454
- role: 'user',
455
- parts: [{ text: 'cancelled' }],
456
- });
457
- // Ensure we do NOT call back to the API
458
- expect(mockSendMessageStream).not.toHaveBeenCalled();
459
- });
460
- });
461
- it('should not flicker streaming state to Idle between tool completion and submission', async () => {
462
- const toolCallResponseParts = [
463
- { text: 'tool 1 final response' },
464
- ];
465
- const initialToolCalls = [
466
- {
467
- request: {
468
- callId: 'call1',
469
- name: 'tool1',
470
- args: {},
471
- isClientInitiated: false,
472
- },
473
- status: 'executing',
474
- responseSubmittedToGemini: false,
475
- tool: {
476
- name: 'tool1',
477
- description: 'desc',
478
- getDescription: vi.fn(),
479
- },
480
- startTime: Date.now(),
481
- },
482
- ];
483
- const completedToolCalls = [
484
- {
485
- ...initialToolCalls[0],
486
- status: 'success',
487
- response: {
488
- callId: 'call1',
489
- responseParts: toolCallResponseParts,
490
- error: undefined,
491
- resultDisplay: 'Tool 1 success display',
492
- },
493
- endTime: Date.now(),
494
- },
495
- ];
496
- // Capture the onComplete callback
497
- let capturedOnComplete = null;
498
- let currentToolCalls = initialToolCalls;
499
- mockUseReactToolScheduler.mockImplementation((onComplete) => {
500
- capturedOnComplete = onComplete;
501
- return [
502
- currentToolCalls,
503
- mockScheduleToolCalls,
504
- mockMarkToolsAsSubmitted,
505
- ];
506
- });
507
- const { result, rerender } = renderHook(() => useGeminiStream(new MockedGeminiClientClass(mockConfig), [], mockAddItem, mockSetShowHelp, mockConfig, mockOnDebugMessage, mockHandleSlashCommand, false, () => 'vscode', () => { }, () => Promise.resolve()));
508
- // 1. Initial state should be Responding because a tool is executing.
509
- expect(result.current.streamingState).toBe(StreamingState.Responding);
510
- // 2. Update the tool calls to completed state and rerender
511
- currentToolCalls = completedToolCalls;
512
- mockUseReactToolScheduler.mockImplementation((onComplete) => {
513
- capturedOnComplete = onComplete;
514
- return [
515
- completedToolCalls,
516
- mockScheduleToolCalls,
517
- mockMarkToolsAsSubmitted,
518
- ];
519
- });
520
- act(() => {
521
- rerender();
522
- });
523
- // 3. The state should *still* be Responding, not Idle.
524
- // This is because the completed tool's response has not been submitted yet.
525
- expect(result.current.streamingState).toBe(StreamingState.Responding);
526
- // 4. Trigger the onComplete callback to simulate tool completion
527
- await act(async () => {
528
- if (capturedOnComplete) {
529
- await capturedOnComplete(completedToolCalls);
530
- }
531
- });
532
- // 5. Wait for submitQuery to be called
533
- await waitFor(() => {
534
- expect(mockSendMessageStream).toHaveBeenCalledWith(toolCallResponseParts, expect.any(AbortSignal));
535
- });
536
- // 6. After submission, the state should remain Responding until the stream completes.
537
- expect(result.current.streamingState).toBe(StreamingState.Responding);
538
- });
539
- describe('User Cancellation', () => {
540
- let useInputCallback;
541
- const mockUseInput = useInput;
542
- beforeEach(() => {
543
- // Capture the callback passed to useInput
544
- mockUseInput.mockImplementation((callback) => {
545
- useInputCallback = callback;
546
- });
547
- });
548
- const simulateEscapeKeyPress = () => {
549
- act(() => {
550
- useInputCallback('', { escape: true });
551
- });
552
- };
553
- it('should cancel an in-progress stream when escape is pressed', async () => {
554
- const mockStream = (async function* () {
555
- yield { type: 'content', value: 'Part 1' };
556
- // Keep the stream open
557
- await new Promise(() => { });
558
- })();
559
- mockSendMessageStream.mockReturnValue(mockStream);
560
- const { result } = renderTestHook();
561
- // Start a query
562
- await act(async () => {
563
- result.current.submitQuery('test query');
564
- });
565
- // Wait for the first part of the response
566
- await waitFor(() => {
567
- expect(result.current.streamingState).toBe(StreamingState.Responding);
568
- });
569
- // Simulate escape key press
570
- simulateEscapeKeyPress();
571
- // Verify cancellation message is added
572
- await waitFor(() => {
573
- expect(mockAddItem).toHaveBeenCalledWith({
574
- type: MessageType.INFO,
575
- text: 'Request cancelled.',
576
- }, expect.any(Number));
577
- });
578
- // Verify state is reset
579
- expect(result.current.streamingState).toBe(StreamingState.Idle);
580
- });
581
- it('should not do anything if escape is pressed when not responding', () => {
582
- const { result } = renderTestHook();
583
- expect(result.current.streamingState).toBe(StreamingState.Idle);
584
- // Simulate escape key press
585
- simulateEscapeKeyPress();
586
- // No change should happen, no cancellation message
587
- expect(mockAddItem).not.toHaveBeenCalledWith(expect.objectContaining({
588
- text: 'Request cancelled.',
589
- }), expect.any(Number));
590
- });
591
- it('should prevent further processing after cancellation', async () => {
592
- let continueStream;
593
- const streamPromise = new Promise((resolve) => {
594
- continueStream = resolve;
595
- });
596
- const mockStream = (async function* () {
597
- yield { type: 'content', value: 'Initial' };
598
- await streamPromise; // Wait until we manually continue
599
- yield { type: 'content', value: ' Canceled' };
600
- })();
601
- mockSendMessageStream.mockReturnValue(mockStream);
602
- const { result } = renderTestHook();
603
- await act(async () => {
604
- result.current.submitQuery('long running query');
605
- });
606
- await waitFor(() => {
607
- expect(result.current.streamingState).toBe(StreamingState.Responding);
608
- });
609
- // Cancel the request
610
- simulateEscapeKeyPress();
611
- // Allow the stream to continue
612
- act(() => {
613
- continueStream();
614
- });
615
- // Wait a bit to see if the second part is processed
616
- await new Promise((resolve) => setTimeout(resolve, 50));
617
- // The text should not have been updated with " Canceled"
618
- const lastCall = mockAddItem.mock.calls.find((call) => call[0].type === 'gemini');
619
- expect(lastCall?.[0].text).toBe('Initial');
620
- // The final state should be idle after cancellation
621
- expect(result.current.streamingState).toBe(StreamingState.Idle);
622
- });
623
- it('should not cancel if a tool call is in progress (not just responding)', async () => {
624
- const toolCalls = [
625
- {
626
- request: { callId: 'call1', name: 'tool1', args: {} },
627
- status: 'executing',
628
- responseSubmittedToGemini: false,
629
- tool: {
630
- name: 'tool1',
631
- description: 'desc1',
632
- getDescription: vi.fn(),
633
- },
634
- startTime: Date.now(),
635
- liveOutput: '...',
636
- },
637
- ];
638
- const abortSpy = vi.spyOn(AbortController.prototype, 'abort');
639
- const { result } = renderTestHook(toolCalls);
640
- // State is `Responding` because a tool is running
641
- expect(result.current.streamingState).toBe(StreamingState.Responding);
642
- // Try to cancel
643
- simulateEscapeKeyPress();
644
- // Nothing should happen because the state is not `Responding`
645
- expect(abortSpy).not.toHaveBeenCalled();
646
- });
647
- });
648
- describe('Client-Initiated Tool Calls', () => {
649
- it('should execute a client-initiated tool without sending a response to Gemini', async () => {
650
- const clientToolRequest = {
651
- shouldScheduleTool: true,
652
- toolName: 'save_memory',
653
- toolArgs: { fact: 'test fact' },
654
- };
655
- mockHandleSlashCommand.mockResolvedValue(clientToolRequest);
656
- const completedToolCall = {
657
- request: {
658
- callId: 'client-call-1',
659
- name: clientToolRequest.toolName,
660
- args: clientToolRequest.toolArgs,
661
- isClientInitiated: true,
662
- },
663
- status: 'success',
664
- responseSubmittedToGemini: false,
665
- response: {
666
- callId: 'client-call-1',
667
- responseParts: [{ text: 'Memory saved' }],
668
- resultDisplay: 'Success: Memory saved',
669
- error: undefined,
670
- },
671
- tool: {
672
- name: clientToolRequest.toolName,
673
- description: 'Saves memory',
674
- getDescription: vi.fn(),
675
- },
676
- };
677
- // Capture the onComplete callback
678
- let capturedOnComplete = null;
679
- mockUseReactToolScheduler.mockImplementation((onComplete) => {
680
- capturedOnComplete = onComplete;
681
- return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
682
- });
683
- const { result } = renderHook(() => useGeminiStream(new MockedGeminiClientClass(mockConfig), [], mockAddItem, mockSetShowHelp, mockConfig, mockOnDebugMessage, mockHandleSlashCommand, false, () => 'vscode', () => { }, () => Promise.resolve()));
684
- // --- User runs the slash command ---
685
- await act(async () => {
686
- await result.current.submitQuery('/memory add "test fact"');
687
- });
688
- // Trigger the onComplete callback with the completed client-initiated tool
689
- await act(async () => {
690
- if (capturedOnComplete) {
691
- await capturedOnComplete([completedToolCall]);
692
- }
693
- });
694
- // --- Assert the outcome ---
695
- await waitFor(() => {
696
- // The tool should be marked as submitted locally
697
- expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith([
698
- 'client-call-1',
699
- ]);
700
- // Crucially, no message should be sent to the Gemini API
701
- expect(mockSendMessageStream).not.toHaveBeenCalled();
702
- });
703
- });
704
- });
705
- describe('Memory Refresh on save_memory', () => {
706
- it('should call performMemoryRefresh when a save_memory tool call completes successfully', async () => {
707
- const mockPerformMemoryRefresh = vi.fn();
708
- const completedToolCall = {
709
- request: {
710
- callId: 'save-mem-call-1',
711
- name: 'save_memory',
712
- args: { fact: 'test' },
713
- isClientInitiated: true,
714
- },
715
- status: 'success',
716
- responseSubmittedToGemini: false,
717
- response: {
718
- callId: 'save-mem-call-1',
719
- responseParts: [{ text: 'Memory saved' }],
720
- resultDisplay: 'Success: Memory saved',
721
- error: undefined,
722
- },
723
- tool: {
724
- name: 'save_memory',
725
- description: 'Saves memory',
726
- getDescription: vi.fn(),
727
- },
728
- };
729
- // Capture the onComplete callback
730
- let capturedOnComplete = null;
731
- mockUseReactToolScheduler.mockImplementation((onComplete) => {
732
- capturedOnComplete = onComplete;
733
- return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
734
- });
735
- renderHook(() => useGeminiStream(new MockedGeminiClientClass(mockConfig), [], mockAddItem, mockSetShowHelp, mockConfig, mockOnDebugMessage, mockHandleSlashCommand, false, () => 'vscode', () => { }, mockPerformMemoryRefresh));
736
- // Trigger the onComplete callback with the completed save_memory tool
737
- await act(async () => {
738
- if (capturedOnComplete) {
739
- await capturedOnComplete([completedToolCall]);
740
- }
741
- });
742
- await waitFor(() => {
743
- expect(mockPerformMemoryRefresh).toHaveBeenCalledTimes(1);
744
- });
745
- });
746
- });
747
- describe('Error Handling', () => {
748
- it('should call parseAndFormatApiError with the correct authType on stream initialization failure', async () => {
749
- // 1. Setup
750
- const mockError = new Error('Rate limit exceeded');
751
- const mockAuthType = AuthType.LOGIN_WITH_GOOGLE;
752
- mockParseAndFormatApiError.mockClear();
753
- mockSendMessageStream.mockReturnValue((async function* () {
754
- yield { type: 'content', value: '' };
755
- throw mockError;
756
- })());
757
- const testConfig = {
758
- ...mockConfig,
759
- getContentGeneratorConfig: vi.fn(() => ({
760
- authType: mockAuthType,
761
- })),
762
- };
763
- const { result } = renderHook(() => useGeminiStream(new MockedGeminiClientClass(testConfig), [], mockAddItem, mockSetShowHelp, testConfig, mockOnDebugMessage, mockHandleSlashCommand, false, () => 'vscode', () => { }, () => Promise.resolve()));
764
- // 2. Action
765
- await act(async () => {
766
- await result.current.submitQuery('test query');
767
- });
768
- // 3. Assertion
769
- await waitFor(() => {
770
- expect(mockParseAndFormatApiError).toHaveBeenCalledWith('Rate limit exceeded', mockAuthType);
771
- });
772
- });
773
- });
774
- });
775
- //# sourceMappingURL=useGeminiStream.test.js.map