ADAPT-Chase commited on
Commit
18d5bc2
·
verified ·
1 Parent(s): b0e2722

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/hooks/useAuthCommand.ts +92 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/hooks/useAutoAcceptIndicator.test.ts +300 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/hooks/useAutoAcceptIndicator.ts +52 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/hooks/useBracketedPaste.ts +37 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/hooks/useCommandCompletion.test.ts +518 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/hooks/useCommandCompletion.tsx +238 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/hooks/useCompletion.ts +128 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/hooks/useConsoleMessages.test.ts +147 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/hooks/useConsoleMessages.ts +110 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/hooks/useEditorSettings.test.ts +283 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/hooks/useEditorSettings.ts +75 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/hooks/useFocus.test.ts +119 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/hooks/useFocus.ts +48 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/hooks/useFolderTrust.test.ts +159 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/hooks/useFolderTrust.ts +72 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/hooks/useGeminiStream.test.tsx +1998 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/hooks/useGeminiStream.ts +1017 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/hooks/useGitBranchName.test.ts +237 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/hooks/useGitBranchName.ts +79 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/hooks/useHistoryManager.test.ts +202 -0
projects/ui/qwen-code/packages/cli/src/ui/hooks/useAuthCommand.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useCallback, useEffect } from 'react';
8
+ import { LoadedSettings, SettingScope } from '../../config/settings.js';
9
+ import {
10
+ AuthType,
11
+ Config,
12
+ clearCachedCredentialFile,
13
+ getErrorMessage,
14
+ } from '@qwen-code/qwen-code-core';
15
+ import { runExitCleanup } from '../../utils/cleanup.js';
16
+
17
+ export const useAuthCommand = (
18
+ settings: LoadedSettings,
19
+ setAuthError: (error: string | null) => void,
20
+ config: Config,
21
+ ) => {
22
+ const [isAuthDialogOpen, setIsAuthDialogOpen] = useState(
23
+ settings.merged.selectedAuthType === undefined,
24
+ );
25
+
26
+ const openAuthDialog = useCallback(() => {
27
+ setIsAuthDialogOpen(true);
28
+ }, []);
29
+
30
+ const [isAuthenticating, setIsAuthenticating] = useState(false);
31
+
32
+ useEffect(() => {
33
+ const authFlow = async () => {
34
+ const authType = settings.merged.selectedAuthType;
35
+ if (isAuthDialogOpen || !authType) {
36
+ return;
37
+ }
38
+
39
+ try {
40
+ setIsAuthenticating(true);
41
+ await config.refreshAuth(authType);
42
+ console.log(`Authenticated via "${authType}".`);
43
+ } catch (e) {
44
+ setAuthError(`Failed to login. Message: ${getErrorMessage(e)}`);
45
+ openAuthDialog();
46
+ } finally {
47
+ setIsAuthenticating(false);
48
+ }
49
+ };
50
+
51
+ void authFlow();
52
+ }, [isAuthDialogOpen, settings, config, setAuthError, openAuthDialog]);
53
+
54
+ const handleAuthSelect = useCallback(
55
+ async (authType: AuthType | undefined, scope: SettingScope) => {
56
+ if (authType) {
57
+ await clearCachedCredentialFile();
58
+
59
+ settings.setValue(scope, 'selectedAuthType', authType);
60
+ if (
61
+ authType === AuthType.LOGIN_WITH_GOOGLE &&
62
+ config.isBrowserLaunchSuppressed()
63
+ ) {
64
+ runExitCleanup();
65
+ console.log(
66
+ `
67
+ ----------------------------------------------------------------
68
+ Logging in with Google... Please restart Gemini CLI to continue.
69
+ ----------------------------------------------------------------
70
+ `,
71
+ );
72
+ process.exit(0);
73
+ }
74
+ }
75
+ setIsAuthDialogOpen(false);
76
+ setAuthError(null);
77
+ },
78
+ [settings, setAuthError, config],
79
+ );
80
+
81
+ const cancelAuthentication = useCallback(() => {
82
+ setIsAuthenticating(false);
83
+ }, []);
84
+
85
+ return {
86
+ isAuthDialogOpen,
87
+ openAuthDialog,
88
+ handleAuthSelect,
89
+ isAuthenticating,
90
+ cancelAuthentication,
91
+ };
92
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useAutoAcceptIndicator.test.ts ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ describe,
9
+ it,
10
+ expect,
11
+ vi,
12
+ beforeEach,
13
+ type MockedFunction,
14
+ type Mock,
15
+ } from 'vitest';
16
+ import { renderHook, act } from '@testing-library/react';
17
+ import { useAutoAcceptIndicator } from './useAutoAcceptIndicator.js';
18
+
19
+ import {
20
+ Config,
21
+ Config as ActualConfigType,
22
+ ApprovalMode,
23
+ } from '@qwen-code/qwen-code-core';
24
+ import { useKeypress, Key } from './useKeypress.js';
25
+
26
+ vi.mock('./useKeypress.js');
27
+
28
+ vi.mock('@qwen-code/qwen-code-core', async () => {
29
+ const actualServerModule = (await vi.importActual(
30
+ '@qwen-code/qwen-code-core',
31
+ )) as Record<string, unknown>;
32
+ return {
33
+ ...actualServerModule,
34
+ Config: vi.fn(),
35
+ };
36
+ });
37
+
38
+ interface MockConfigInstanceShape {
39
+ getApprovalMode: Mock<() => ApprovalMode>;
40
+ setApprovalMode: Mock<(value: ApprovalMode) => void>;
41
+ getCoreTools: Mock<() => string[]>;
42
+ getToolDiscoveryCommand: Mock<() => string | undefined>;
43
+ getTargetDir: Mock<() => string>;
44
+ getApiKey: Mock<() => string>;
45
+ getModel: Mock<() => string>;
46
+ getSandbox: Mock<() => boolean | string>;
47
+ getDebugMode: Mock<() => boolean>;
48
+ getQuestion: Mock<() => string | undefined>;
49
+ getFullContext: Mock<() => boolean>;
50
+ getUserAgent: Mock<() => string>;
51
+ getUserMemory: Mock<() => string>;
52
+ getGeminiMdFileCount: Mock<() => number>;
53
+ getToolRegistry: Mock<() => { discoverTools: Mock<() => void> }>;
54
+ }
55
+
56
+ type UseKeypressHandler = (key: Key) => void;
57
+
58
+ describe('useAutoAcceptIndicator', () => {
59
+ let mockConfigInstance: MockConfigInstanceShape;
60
+ let capturedUseKeypressHandler: UseKeypressHandler;
61
+ let mockedUseKeypress: MockedFunction<typeof useKeypress>;
62
+
63
+ beforeEach(() => {
64
+ vi.resetAllMocks();
65
+
66
+ (
67
+ Config as unknown as MockedFunction<() => MockConfigInstanceShape>
68
+ ).mockImplementation(() => {
69
+ const instanceGetApprovalModeMock = vi.fn();
70
+ const instanceSetApprovalModeMock = vi.fn();
71
+
72
+ const instance: MockConfigInstanceShape = {
73
+ getApprovalMode: instanceGetApprovalModeMock as Mock<
74
+ () => ApprovalMode
75
+ >,
76
+ setApprovalMode: instanceSetApprovalModeMock as Mock<
77
+ (value: ApprovalMode) => void
78
+ >,
79
+ getCoreTools: vi.fn().mockReturnValue([]) as Mock<() => string[]>,
80
+ getToolDiscoveryCommand: vi.fn().mockReturnValue(undefined) as Mock<
81
+ () => string | undefined
82
+ >,
83
+ getTargetDir: vi.fn().mockReturnValue('.') as Mock<() => string>,
84
+ getApiKey: vi.fn().mockReturnValue('test-api-key') as Mock<
85
+ () => string
86
+ >,
87
+ getModel: vi.fn().mockReturnValue('test-model') as Mock<() => string>,
88
+ getSandbox: vi.fn().mockReturnValue(false) as Mock<
89
+ () => boolean | string
90
+ >,
91
+ getDebugMode: vi.fn().mockReturnValue(false) as Mock<() => boolean>,
92
+ getQuestion: vi.fn().mockReturnValue(undefined) as Mock<
93
+ () => string | undefined
94
+ >,
95
+ getFullContext: vi.fn().mockReturnValue(false) as Mock<() => boolean>,
96
+ getUserAgent: vi.fn().mockReturnValue('test-user-agent') as Mock<
97
+ () => string
98
+ >,
99
+ getUserMemory: vi.fn().mockReturnValue('') as Mock<() => string>,
100
+ getGeminiMdFileCount: vi.fn().mockReturnValue(0) as Mock<() => number>,
101
+ getToolRegistry: vi
102
+ .fn()
103
+ .mockReturnValue({ discoverTools: vi.fn() }) as Mock<
104
+ () => { discoverTools: Mock<() => void> }
105
+ >,
106
+ };
107
+ instanceSetApprovalModeMock.mockImplementation((value: ApprovalMode) => {
108
+ instanceGetApprovalModeMock.mockReturnValue(value);
109
+ });
110
+ return instance;
111
+ });
112
+
113
+ mockedUseKeypress = useKeypress as MockedFunction<typeof useKeypress>;
114
+ mockedUseKeypress.mockImplementation(
115
+ (handler: UseKeypressHandler, _options) => {
116
+ capturedUseKeypressHandler = handler;
117
+ },
118
+ );
119
+
120
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
121
+ mockConfigInstance = new (Config as any)() as MockConfigInstanceShape;
122
+ });
123
+
124
+ it('should initialize with ApprovalMode.AUTO_EDIT if config.getApprovalMode returns ApprovalMode.AUTO_EDIT', () => {
125
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.AUTO_EDIT);
126
+ const { result } = renderHook(() =>
127
+ useAutoAcceptIndicator({
128
+ config: mockConfigInstance as unknown as ActualConfigType,
129
+ }),
130
+ );
131
+ expect(result.current).toBe(ApprovalMode.AUTO_EDIT);
132
+ expect(mockConfigInstance.getApprovalMode).toHaveBeenCalledTimes(1);
133
+ });
134
+
135
+ it('should initialize with ApprovalMode.DEFAULT if config.getApprovalMode returns ApprovalMode.DEFAULT', () => {
136
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.DEFAULT);
137
+ const { result } = renderHook(() =>
138
+ useAutoAcceptIndicator({
139
+ config: mockConfigInstance as unknown as ActualConfigType,
140
+ }),
141
+ );
142
+ expect(result.current).toBe(ApprovalMode.DEFAULT);
143
+ expect(mockConfigInstance.getApprovalMode).toHaveBeenCalledTimes(1);
144
+ });
145
+
146
+ it('should initialize with ApprovalMode.YOLO if config.getApprovalMode returns ApprovalMode.YOLO', () => {
147
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.YOLO);
148
+ const { result } = renderHook(() =>
149
+ useAutoAcceptIndicator({
150
+ config: mockConfigInstance as unknown as ActualConfigType,
151
+ }),
152
+ );
153
+ expect(result.current).toBe(ApprovalMode.YOLO);
154
+ expect(mockConfigInstance.getApprovalMode).toHaveBeenCalledTimes(1);
155
+ });
156
+
157
+ it('should toggle the indicator and update config when Shift+Tab or Ctrl+Y is pressed', () => {
158
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.DEFAULT);
159
+ const { result } = renderHook(() =>
160
+ useAutoAcceptIndicator({
161
+ config: mockConfigInstance as unknown as ActualConfigType,
162
+ }),
163
+ );
164
+ expect(result.current).toBe(ApprovalMode.DEFAULT);
165
+
166
+ act(() => {
167
+ capturedUseKeypressHandler({
168
+ name: 'tab',
169
+ shift: true,
170
+ } as Key);
171
+ });
172
+ expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith(
173
+ ApprovalMode.AUTO_EDIT,
174
+ );
175
+ expect(result.current).toBe(ApprovalMode.AUTO_EDIT);
176
+
177
+ act(() => {
178
+ capturedUseKeypressHandler({ name: 'y', ctrl: true } as Key);
179
+ });
180
+ expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith(
181
+ ApprovalMode.YOLO,
182
+ );
183
+ expect(result.current).toBe(ApprovalMode.YOLO);
184
+
185
+ act(() => {
186
+ capturedUseKeypressHandler({ name: 'y', ctrl: true } as Key);
187
+ });
188
+ expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith(
189
+ ApprovalMode.DEFAULT,
190
+ );
191
+ expect(result.current).toBe(ApprovalMode.DEFAULT);
192
+
193
+ act(() => {
194
+ capturedUseKeypressHandler({ name: 'y', ctrl: true } as Key);
195
+ });
196
+ expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith(
197
+ ApprovalMode.YOLO,
198
+ );
199
+ expect(result.current).toBe(ApprovalMode.YOLO);
200
+
201
+ act(() => {
202
+ capturedUseKeypressHandler({
203
+ name: 'tab',
204
+ shift: true,
205
+ } as Key);
206
+ });
207
+ expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith(
208
+ ApprovalMode.AUTO_EDIT,
209
+ );
210
+ expect(result.current).toBe(ApprovalMode.AUTO_EDIT);
211
+
212
+ act(() => {
213
+ capturedUseKeypressHandler({
214
+ name: 'tab',
215
+ shift: true,
216
+ } as Key);
217
+ });
218
+ expect(mockConfigInstance.setApprovalMode).toHaveBeenCalledWith(
219
+ ApprovalMode.DEFAULT,
220
+ );
221
+ expect(result.current).toBe(ApprovalMode.DEFAULT);
222
+ });
223
+
224
+ it('should not toggle if only one key or other keys combinations are pressed', () => {
225
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.DEFAULT);
226
+ renderHook(() =>
227
+ useAutoAcceptIndicator({
228
+ config: mockConfigInstance as unknown as ActualConfigType,
229
+ }),
230
+ );
231
+
232
+ act(() => {
233
+ capturedUseKeypressHandler({
234
+ name: 'tab',
235
+ shift: false,
236
+ } as Key);
237
+ });
238
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
239
+
240
+ act(() => {
241
+ capturedUseKeypressHandler({
242
+ name: 'unknown',
243
+ shift: true,
244
+ } as Key);
245
+ });
246
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
247
+
248
+ act(() => {
249
+ capturedUseKeypressHandler({
250
+ name: 'a',
251
+ shift: false,
252
+ ctrl: false,
253
+ } as Key);
254
+ });
255
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
256
+
257
+ act(() => {
258
+ capturedUseKeypressHandler({ name: 'y', ctrl: false } as Key);
259
+ });
260
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
261
+
262
+ act(() => {
263
+ capturedUseKeypressHandler({ name: 'a', ctrl: true } as Key);
264
+ });
265
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
266
+
267
+ act(() => {
268
+ capturedUseKeypressHandler({ name: 'y', shift: true } as Key);
269
+ });
270
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
271
+
272
+ act(() => {
273
+ capturedUseKeypressHandler({
274
+ name: 'a',
275
+ ctrl: true,
276
+ shift: true,
277
+ } as Key);
278
+ });
279
+ expect(mockConfigInstance.setApprovalMode).not.toHaveBeenCalled();
280
+ });
281
+
282
+ it('should update indicator when config value changes externally (useEffect dependency)', () => {
283
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.DEFAULT);
284
+ const { result, rerender } = renderHook(
285
+ (props: { config: ActualConfigType }) => useAutoAcceptIndicator(props),
286
+ {
287
+ initialProps: {
288
+ config: mockConfigInstance as unknown as ActualConfigType,
289
+ },
290
+ },
291
+ );
292
+ expect(result.current).toBe(ApprovalMode.DEFAULT);
293
+
294
+ mockConfigInstance.getApprovalMode.mockReturnValue(ApprovalMode.AUTO_EDIT);
295
+
296
+ rerender({ config: mockConfigInstance as unknown as ActualConfigType });
297
+ expect(result.current).toBe(ApprovalMode.AUTO_EDIT);
298
+ expect(mockConfigInstance.getApprovalMode).toHaveBeenCalledTimes(3);
299
+ });
300
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useAutoAcceptIndicator.ts ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { ApprovalMode, type Config } from '@qwen-code/qwen-code-core';
8
+ import { useEffect, useState } from 'react';
9
+ import { useKeypress } from './useKeypress.js';
10
+
11
+ export interface UseAutoAcceptIndicatorArgs {
12
+ config: Config;
13
+ }
14
+
15
+ export function useAutoAcceptIndicator({
16
+ config,
17
+ }: UseAutoAcceptIndicatorArgs): ApprovalMode {
18
+ const currentConfigValue = config.getApprovalMode();
19
+ const [showAutoAcceptIndicator, setShowAutoAcceptIndicator] =
20
+ useState(currentConfigValue);
21
+
22
+ useEffect(() => {
23
+ setShowAutoAcceptIndicator(currentConfigValue);
24
+ }, [currentConfigValue]);
25
+
26
+ useKeypress(
27
+ (key) => {
28
+ let nextApprovalMode: ApprovalMode | undefined;
29
+
30
+ if (key.ctrl && key.name === 'y') {
31
+ nextApprovalMode =
32
+ config.getApprovalMode() === ApprovalMode.YOLO
33
+ ? ApprovalMode.DEFAULT
34
+ : ApprovalMode.YOLO;
35
+ } else if (key.shift && key.name === 'tab') {
36
+ nextApprovalMode =
37
+ config.getApprovalMode() === ApprovalMode.AUTO_EDIT
38
+ ? ApprovalMode.DEFAULT
39
+ : ApprovalMode.AUTO_EDIT;
40
+ }
41
+
42
+ if (nextApprovalMode) {
43
+ config.setApprovalMode(nextApprovalMode);
44
+ // Update local state immediately for responsiveness
45
+ setShowAutoAcceptIndicator(nextApprovalMode);
46
+ }
47
+ },
48
+ { isActive: true },
49
+ );
50
+
51
+ return showAutoAcceptIndicator;
52
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useBracketedPaste.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useEffect } from 'react';
8
+
9
+ const ENABLE_BRACKETED_PASTE = '\x1b[?2004h';
10
+ const DISABLE_BRACKETED_PASTE = '\x1b[?2004l';
11
+
12
+ /**
13
+ * Enables and disables bracketed paste mode in the terminal.
14
+ *
15
+ * This hook ensures that bracketed paste mode is enabled when the component
16
+ * mounts and disabled when it unmounts or when the process exits.
17
+ */
18
+ export const useBracketedPaste = () => {
19
+ const cleanup = () => {
20
+ process.stdout.write(DISABLE_BRACKETED_PASTE);
21
+ };
22
+
23
+ useEffect(() => {
24
+ process.stdout.write(ENABLE_BRACKETED_PASTE);
25
+
26
+ process.on('exit', cleanup);
27
+ process.on('SIGINT', cleanup);
28
+ process.on('SIGTERM', cleanup);
29
+
30
+ return () => {
31
+ cleanup();
32
+ process.removeListener('exit', cleanup);
33
+ process.removeListener('SIGINT', cleanup);
34
+ process.removeListener('SIGTERM', cleanup);
35
+ };
36
+ }, []);
37
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useCommandCompletion.test.ts ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /** @vitest-environment jsdom */
8
+
9
+ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
10
+ import { renderHook, act, waitFor } from '@testing-library/react';
11
+ import { useCommandCompletion } from './useCommandCompletion.js';
12
+ import { CommandContext } from '../commands/types.js';
13
+ import { Config } from '@qwen-code/qwen-code-core';
14
+ import { useTextBuffer } from '../components/shared/text-buffer.js';
15
+ import { useEffect } from 'react';
16
+ import { Suggestion } from '../components/SuggestionsDisplay.js';
17
+ import { UseAtCompletionProps, useAtCompletion } from './useAtCompletion.js';
18
+ import {
19
+ UseSlashCompletionProps,
20
+ useSlashCompletion,
21
+ } from './useSlashCompletion.js';
22
+
23
+ vi.mock('./useAtCompletion', () => ({
24
+ useAtCompletion: vi.fn(),
25
+ }));
26
+
27
+ vi.mock('./useSlashCompletion', () => ({
28
+ useSlashCompletion: vi.fn(() => ({
29
+ completionStart: 0,
30
+ completionEnd: 0,
31
+ })),
32
+ }));
33
+
34
+ // Helper to set up mocks in a consistent way for both child hooks
35
+ const setupMocks = ({
36
+ atSuggestions = [],
37
+ slashSuggestions = [],
38
+ isLoading = false,
39
+ isPerfectMatch = false,
40
+ slashCompletionRange = { completionStart: 0, completionEnd: 0 },
41
+ }: {
42
+ atSuggestions?: Suggestion[];
43
+ slashSuggestions?: Suggestion[];
44
+ isLoading?: boolean;
45
+ isPerfectMatch?: boolean;
46
+ slashCompletionRange?: { completionStart: number; completionEnd: number };
47
+ }) => {
48
+ // Mock for @-completions
49
+ (useAtCompletion as vi.Mock).mockImplementation(
50
+ ({
51
+ enabled,
52
+ setSuggestions,
53
+ setIsLoadingSuggestions,
54
+ }: UseAtCompletionProps) => {
55
+ useEffect(() => {
56
+ if (enabled) {
57
+ setIsLoadingSuggestions(isLoading);
58
+ setSuggestions(atSuggestions);
59
+ }
60
+ }, [enabled, setSuggestions, setIsLoadingSuggestions]);
61
+ },
62
+ );
63
+
64
+ // Mock for /-completions
65
+ (useSlashCompletion as vi.Mock).mockImplementation(
66
+ ({
67
+ enabled,
68
+ setSuggestions,
69
+ setIsLoadingSuggestions,
70
+ setIsPerfectMatch,
71
+ }: UseSlashCompletionProps) => {
72
+ useEffect(() => {
73
+ if (enabled) {
74
+ setIsLoadingSuggestions(isLoading);
75
+ setSuggestions(slashSuggestions);
76
+ setIsPerfectMatch(isPerfectMatch);
77
+ }
78
+ }, [enabled, setSuggestions, setIsLoadingSuggestions, setIsPerfectMatch]);
79
+ // The hook returns a range, which we can mock simply
80
+ return slashCompletionRange;
81
+ },
82
+ );
83
+ };
84
+
85
+ describe('useCommandCompletion', () => {
86
+ const mockCommandContext = {} as CommandContext;
87
+ const mockConfig = {} as Config;
88
+ const testDirs: string[] = [];
89
+ const testRootDir = '/';
90
+
91
+ // Helper to create real TextBuffer objects within renderHook
92
+ function useTextBufferForTest(text: string, cursorOffset?: number) {
93
+ return useTextBuffer({
94
+ initialText: text,
95
+ initialCursorOffset: cursorOffset ?? text.length,
96
+ viewport: { width: 80, height: 20 },
97
+ isValidPath: () => false,
98
+ onChange: () => {},
99
+ });
100
+ }
101
+
102
+ beforeEach(() => {
103
+ vi.clearAllMocks();
104
+ // Reset to default mocks before each test
105
+ setupMocks({});
106
+ });
107
+
108
+ afterEach(() => {
109
+ vi.restoreAllMocks();
110
+ });
111
+
112
+ describe('Core Hook Behavior', () => {
113
+ describe('State Management', () => {
114
+ it('should initialize with default state', () => {
115
+ const { result } = renderHook(() =>
116
+ useCommandCompletion(
117
+ useTextBufferForTest(''),
118
+ testDirs,
119
+ testRootDir,
120
+ [],
121
+ mockCommandContext,
122
+ false,
123
+ mockConfig,
124
+ ),
125
+ );
126
+
127
+ expect(result.current.suggestions).toEqual([]);
128
+ expect(result.current.activeSuggestionIndex).toBe(-1);
129
+ expect(result.current.visibleStartIndex).toBe(0);
130
+ expect(result.current.showSuggestions).toBe(false);
131
+ expect(result.current.isLoadingSuggestions).toBe(false);
132
+ });
133
+
134
+ it('should reset state when completion mode becomes IDLE', async () => {
135
+ setupMocks({
136
+ atSuggestions: [{ label: 'src/file.txt', value: 'src/file.txt' }],
137
+ });
138
+
139
+ const { result } = renderHook(() => {
140
+ const textBuffer = useTextBufferForTest('@file');
141
+ const completion = useCommandCompletion(
142
+ textBuffer,
143
+ testDirs,
144
+ testRootDir,
145
+ [],
146
+ mockCommandContext,
147
+ false,
148
+ mockConfig,
149
+ );
150
+ return { completion, textBuffer };
151
+ });
152
+
153
+ await waitFor(() => {
154
+ expect(result.current.completion.suggestions).toHaveLength(1);
155
+ });
156
+
157
+ expect(result.current.completion.showSuggestions).toBe(true);
158
+
159
+ act(() => {
160
+ result.current.textBuffer.replaceRangeByOffset(
161
+ 0,
162
+ 5,
163
+ 'just some text',
164
+ );
165
+ });
166
+
167
+ await waitFor(() => {
168
+ expect(result.current.completion.showSuggestions).toBe(false);
169
+ });
170
+ });
171
+
172
+ it('should reset all state to default values', () => {
173
+ const { result } = renderHook(() =>
174
+ useCommandCompletion(
175
+ useTextBufferForTest('@files'),
176
+ testDirs,
177
+ testRootDir,
178
+ [],
179
+ mockCommandContext,
180
+ false,
181
+ mockConfig,
182
+ ),
183
+ );
184
+
185
+ act(() => {
186
+ result.current.setActiveSuggestionIndex(5);
187
+ result.current.setShowSuggestions(true);
188
+ });
189
+
190
+ act(() => {
191
+ result.current.resetCompletionState();
192
+ });
193
+
194
+ expect(result.current.activeSuggestionIndex).toBe(-1);
195
+ expect(result.current.visibleStartIndex).toBe(0);
196
+ expect(result.current.showSuggestions).toBe(false);
197
+ });
198
+
199
+ it('should call useAtCompletion with the correct query for an escaped space', async () => {
200
+ const text = '@src/a\\ file.txt';
201
+ renderHook(() =>
202
+ useCommandCompletion(
203
+ useTextBufferForTest(text),
204
+ testDirs,
205
+ testRootDir,
206
+ [],
207
+ mockCommandContext,
208
+ false,
209
+ mockConfig,
210
+ ),
211
+ );
212
+
213
+ await waitFor(() => {
214
+ expect(useAtCompletion).toHaveBeenLastCalledWith(
215
+ expect.objectContaining({
216
+ enabled: true,
217
+ pattern: 'src/a\\ file.txt',
218
+ }),
219
+ );
220
+ });
221
+ });
222
+
223
+ it('should correctly identify the completion context with multiple @ symbols', async () => {
224
+ const text = '@file1 @file2';
225
+ const cursorOffset = 3; // @fi|le1 @file2
226
+
227
+ renderHook(() =>
228
+ useCommandCompletion(
229
+ useTextBufferForTest(text, cursorOffset),
230
+ testDirs,
231
+ testRootDir,
232
+ [],
233
+ mockCommandContext,
234
+ false,
235
+ mockConfig,
236
+ ),
237
+ );
238
+
239
+ await waitFor(() => {
240
+ expect(useAtCompletion).toHaveBeenLastCalledWith(
241
+ expect.objectContaining({
242
+ enabled: true,
243
+ pattern: 'file1',
244
+ }),
245
+ );
246
+ });
247
+ });
248
+ });
249
+
250
+ describe('Navigation', () => {
251
+ const mockSuggestions = [
252
+ { label: 'cmd1', value: 'cmd1' },
253
+ { label: 'cmd2', value: 'cmd2' },
254
+ { label: 'cmd3', value: 'cmd3' },
255
+ { label: 'cmd4', value: 'cmd4' },
256
+ { label: 'cmd5', value: 'cmd5' },
257
+ ];
258
+
259
+ beforeEach(() => {
260
+ setupMocks({ slashSuggestions: mockSuggestions });
261
+ });
262
+
263
+ it('should handle navigateUp with no suggestions', () => {
264
+ setupMocks({ slashSuggestions: [] });
265
+
266
+ const { result } = renderHook(() =>
267
+ useCommandCompletion(
268
+ useTextBufferForTest('/'),
269
+ testDirs,
270
+ testRootDir,
271
+ [],
272
+ mockCommandContext,
273
+ false,
274
+ mockConfig,
275
+ ),
276
+ );
277
+
278
+ act(() => {
279
+ result.current.navigateUp();
280
+ });
281
+
282
+ expect(result.current.activeSuggestionIndex).toBe(-1);
283
+ });
284
+
285
+ it('should handle navigateDown with no suggestions', () => {
286
+ setupMocks({ slashSuggestions: [] });
287
+ const { result } = renderHook(() =>
288
+ useCommandCompletion(
289
+ useTextBufferForTest('/'),
290
+ testDirs,
291
+ testRootDir,
292
+ [],
293
+ mockCommandContext,
294
+ false,
295
+ mockConfig,
296
+ ),
297
+ );
298
+
299
+ act(() => {
300
+ result.current.navigateDown();
301
+ });
302
+
303
+ expect(result.current.activeSuggestionIndex).toBe(-1);
304
+ });
305
+
306
+ it('should navigate up through suggestions with wrap-around', async () => {
307
+ const { result } = renderHook(() =>
308
+ useCommandCompletion(
309
+ useTextBufferForTest('/'),
310
+ testDirs,
311
+ testRootDir,
312
+ [],
313
+ mockCommandContext,
314
+ false,
315
+ mockConfig,
316
+ ),
317
+ );
318
+
319
+ await waitFor(() => {
320
+ expect(result.current.suggestions.length).toBe(5);
321
+ });
322
+
323
+ expect(result.current.activeSuggestionIndex).toBe(0);
324
+
325
+ act(() => {
326
+ result.current.navigateUp();
327
+ });
328
+
329
+ expect(result.current.activeSuggestionIndex).toBe(4);
330
+ });
331
+
332
+ it('should navigate down through suggestions with wrap-around', async () => {
333
+ const { result } = renderHook(() =>
334
+ useCommandCompletion(
335
+ useTextBufferForTest('/'),
336
+ testDirs,
337
+ testRootDir,
338
+ [],
339
+ mockCommandContext,
340
+ false,
341
+ mockConfig,
342
+ ),
343
+ );
344
+
345
+ await waitFor(() => {
346
+ expect(result.current.suggestions.length).toBe(5);
347
+ });
348
+
349
+ act(() => {
350
+ result.current.setActiveSuggestionIndex(4);
351
+ });
352
+ expect(result.current.activeSuggestionIndex).toBe(4);
353
+
354
+ act(() => {
355
+ result.current.navigateDown();
356
+ });
357
+
358
+ expect(result.current.activeSuggestionIndex).toBe(0);
359
+ });
360
+
361
+ it('should handle navigation with multiple suggestions', async () => {
362
+ const { result } = renderHook(() =>
363
+ useCommandCompletion(
364
+ useTextBufferForTest('/'),
365
+ testDirs,
366
+ testRootDir,
367
+ [],
368
+ mockCommandContext,
369
+ false,
370
+ mockConfig,
371
+ ),
372
+ );
373
+
374
+ await waitFor(() => {
375
+ expect(result.current.suggestions.length).toBe(5);
376
+ });
377
+
378
+ expect(result.current.activeSuggestionIndex).toBe(0);
379
+
380
+ act(() => result.current.navigateDown());
381
+ expect(result.current.activeSuggestionIndex).toBe(1);
382
+
383
+ act(() => result.current.navigateDown());
384
+ expect(result.current.activeSuggestionIndex).toBe(2);
385
+
386
+ act(() => result.current.navigateUp());
387
+ expect(result.current.activeSuggestionIndex).toBe(1);
388
+
389
+ act(() => result.current.navigateUp());
390
+ expect(result.current.activeSuggestionIndex).toBe(0);
391
+
392
+ act(() => result.current.navigateUp());
393
+ expect(result.current.activeSuggestionIndex).toBe(4);
394
+ });
395
+
396
+ it('should automatically select the first item when suggestions are available', async () => {
397
+ setupMocks({ slashSuggestions: mockSuggestions });
398
+
399
+ const { result } = renderHook(() =>
400
+ useCommandCompletion(
401
+ useTextBufferForTest('/'),
402
+ testDirs,
403
+ testRootDir,
404
+ [],
405
+ mockCommandContext,
406
+ false,
407
+ mockConfig,
408
+ ),
409
+ );
410
+
411
+ await waitFor(() => {
412
+ expect(result.current.suggestions.length).toBe(
413
+ mockSuggestions.length,
414
+ );
415
+ expect(result.current.activeSuggestionIndex).toBe(0);
416
+ });
417
+ });
418
+ });
419
+ });
420
+
421
+ describe('handleAutocomplete', () => {
422
+ it('should complete a partial command', async () => {
423
+ setupMocks({
424
+ slashSuggestions: [{ label: 'memory', value: 'memory' }],
425
+ slashCompletionRange: { completionStart: 1, completionEnd: 4 },
426
+ });
427
+
428
+ const { result } = renderHook(() => {
429
+ const textBuffer = useTextBufferForTest('/mem');
430
+ const completion = useCommandCompletion(
431
+ textBuffer,
432
+ testDirs,
433
+ testRootDir,
434
+ [],
435
+ mockCommandContext,
436
+ false,
437
+ mockConfig,
438
+ );
439
+ return { ...completion, textBuffer };
440
+ });
441
+
442
+ await waitFor(() => {
443
+ expect(result.current.suggestions.length).toBe(1);
444
+ });
445
+
446
+ act(() => {
447
+ result.current.handleAutocomplete(0);
448
+ });
449
+
450
+ expect(result.current.textBuffer.text).toBe('/memory ');
451
+ });
452
+
453
+ it('should complete a file path', async () => {
454
+ setupMocks({
455
+ atSuggestions: [{ label: 'src/file1.txt', value: 'src/file1.txt' }],
456
+ });
457
+
458
+ const { result } = renderHook(() => {
459
+ const textBuffer = useTextBufferForTest('@src/fi');
460
+ const completion = useCommandCompletion(
461
+ textBuffer,
462
+ testDirs,
463
+ testRootDir,
464
+ [],
465
+ mockCommandContext,
466
+ false,
467
+ mockConfig,
468
+ );
469
+ return { ...completion, textBuffer };
470
+ });
471
+
472
+ await waitFor(() => {
473
+ expect(result.current.suggestions.length).toBe(1);
474
+ });
475
+
476
+ act(() => {
477
+ result.current.handleAutocomplete(0);
478
+ });
479
+
480
+ expect(result.current.textBuffer.text).toBe('@src/file1.txt ');
481
+ });
482
+
483
+ it('should complete a file path when cursor is not at the end of the line', async () => {
484
+ const text = '@src/fi is a good file';
485
+ const cursorOffset = 7; // after "i"
486
+
487
+ setupMocks({
488
+ atSuggestions: [{ label: 'src/file1.txt', value: 'src/file1.txt' }],
489
+ });
490
+
491
+ const { result } = renderHook(() => {
492
+ const textBuffer = useTextBufferForTest(text, cursorOffset);
493
+ const completion = useCommandCompletion(
494
+ textBuffer,
495
+ testDirs,
496
+ testRootDir,
497
+ [],
498
+ mockCommandContext,
499
+ false,
500
+ mockConfig,
501
+ );
502
+ return { ...completion, textBuffer };
503
+ });
504
+
505
+ await waitFor(() => {
506
+ expect(result.current.suggestions.length).toBe(1);
507
+ });
508
+
509
+ act(() => {
510
+ result.current.handleAutocomplete(0);
511
+ });
512
+
513
+ expect(result.current.textBuffer.text).toBe(
514
+ '@src/file1.txt is a good file',
515
+ );
516
+ });
517
+ });
518
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useCommandCompletion.tsx ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useCallback, useMemo, useEffect } from 'react';
8
+ import { Suggestion } from '../components/SuggestionsDisplay.js';
9
+ import { CommandContext, SlashCommand } from '../commands/types.js';
10
+ import {
11
+ logicalPosToOffset,
12
+ TextBuffer,
13
+ } from '../components/shared/text-buffer.js';
14
+ import { isSlashCommand } from '../utils/commandUtils.js';
15
+ import { toCodePoints } from '../utils/textUtils.js';
16
+ import { useAtCompletion } from './useAtCompletion.js';
17
+ import { useSlashCompletion } from './useSlashCompletion.js';
18
+ import { Config } from '@qwen-code/qwen-code-core';
19
+ import { useCompletion } from './useCompletion.js';
20
+
21
+ export enum CompletionMode {
22
+ IDLE = 'IDLE',
23
+ AT = 'AT',
24
+ SLASH = 'SLASH',
25
+ }
26
+
27
+ export interface UseCommandCompletionReturn {
28
+ suggestions: Suggestion[];
29
+ activeSuggestionIndex: number;
30
+ visibleStartIndex: number;
31
+ showSuggestions: boolean;
32
+ isLoadingSuggestions: boolean;
33
+ isPerfectMatch: boolean;
34
+ setActiveSuggestionIndex: React.Dispatch<React.SetStateAction<number>>;
35
+ setShowSuggestions: React.Dispatch<React.SetStateAction<boolean>>;
36
+ resetCompletionState: () => void;
37
+ navigateUp: () => void;
38
+ navigateDown: () => void;
39
+ handleAutocomplete: (indexToUse: number) => void;
40
+ }
41
+
42
+ export function useCommandCompletion(
43
+ buffer: TextBuffer,
44
+ dirs: readonly string[],
45
+ cwd: string,
46
+ slashCommands: readonly SlashCommand[],
47
+ commandContext: CommandContext,
48
+ reverseSearchActive: boolean = false,
49
+ config?: Config,
50
+ ): UseCommandCompletionReturn {
51
+ const {
52
+ suggestions,
53
+ activeSuggestionIndex,
54
+ visibleStartIndex,
55
+ showSuggestions,
56
+ isLoadingSuggestions,
57
+ isPerfectMatch,
58
+
59
+ setSuggestions,
60
+ setShowSuggestions,
61
+ setActiveSuggestionIndex,
62
+ setIsLoadingSuggestions,
63
+ setIsPerfectMatch,
64
+ setVisibleStartIndex,
65
+
66
+ resetCompletionState,
67
+ navigateUp,
68
+ navigateDown,
69
+ } = useCompletion();
70
+
71
+ const cursorRow = buffer.cursor[0];
72
+ const cursorCol = buffer.cursor[1];
73
+
74
+ const { completionMode, query, completionStart, completionEnd } =
75
+ useMemo(() => {
76
+ const currentLine = buffer.lines[cursorRow] || '';
77
+ if (cursorRow === 0 && isSlashCommand(currentLine.trim())) {
78
+ return {
79
+ completionMode: CompletionMode.SLASH,
80
+ query: currentLine,
81
+ completionStart: 0,
82
+ completionEnd: currentLine.length,
83
+ };
84
+ }
85
+
86
+ const codePoints = toCodePoints(currentLine);
87
+ for (let i = cursorCol - 1; i >= 0; i--) {
88
+ const char = codePoints[i];
89
+
90
+ if (char === ' ') {
91
+ let backslashCount = 0;
92
+ for (let j = i - 1; j >= 0 && codePoints[j] === '\\'; j--) {
93
+ backslashCount++;
94
+ }
95
+ if (backslashCount % 2 === 0) {
96
+ return {
97
+ completionMode: CompletionMode.IDLE,
98
+ query: null,
99
+ completionStart: -1,
100
+ completionEnd: -1,
101
+ };
102
+ }
103
+ } else if (char === '@') {
104
+ let end = codePoints.length;
105
+ for (let i = cursorCol; i < codePoints.length; i++) {
106
+ if (codePoints[i] === ' ') {
107
+ let backslashCount = 0;
108
+ for (let j = i - 1; j >= 0 && codePoints[j] === '\\'; j--) {
109
+ backslashCount++;
110
+ }
111
+
112
+ if (backslashCount % 2 === 0) {
113
+ end = i;
114
+ break;
115
+ }
116
+ }
117
+ }
118
+ const pathStart = i + 1;
119
+ const partialPath = currentLine.substring(pathStart, end);
120
+ return {
121
+ completionMode: CompletionMode.AT,
122
+ query: partialPath,
123
+ completionStart: pathStart,
124
+ completionEnd: end,
125
+ };
126
+ }
127
+ }
128
+ return {
129
+ completionMode: CompletionMode.IDLE,
130
+ query: null,
131
+ completionStart: -1,
132
+ completionEnd: -1,
133
+ };
134
+ }, [cursorRow, cursorCol, buffer.lines]);
135
+
136
+ useAtCompletion({
137
+ enabled: completionMode === CompletionMode.AT,
138
+ pattern: query || '',
139
+ config,
140
+ cwd,
141
+ setSuggestions,
142
+ setIsLoadingSuggestions,
143
+ });
144
+
145
+ const slashCompletionRange = useSlashCompletion({
146
+ enabled: completionMode === CompletionMode.SLASH,
147
+ query,
148
+ slashCommands,
149
+ commandContext,
150
+ setSuggestions,
151
+ setIsLoadingSuggestions,
152
+ setIsPerfectMatch,
153
+ });
154
+
155
+ useEffect(() => {
156
+ setActiveSuggestionIndex(suggestions.length > 0 ? 0 : -1);
157
+ setVisibleStartIndex(0);
158
+ }, [suggestions, setActiveSuggestionIndex, setVisibleStartIndex]);
159
+
160
+ useEffect(() => {
161
+ if (completionMode === CompletionMode.IDLE || reverseSearchActive) {
162
+ resetCompletionState();
163
+ return;
164
+ }
165
+ // Show suggestions if we are loading OR if there are results to display.
166
+ setShowSuggestions(isLoadingSuggestions || suggestions.length > 0);
167
+ }, [
168
+ completionMode,
169
+ suggestions.length,
170
+ isLoadingSuggestions,
171
+ reverseSearchActive,
172
+ resetCompletionState,
173
+ setShowSuggestions,
174
+ ]);
175
+
176
+ const handleAutocomplete = useCallback(
177
+ (indexToUse: number) => {
178
+ if (indexToUse < 0 || indexToUse >= suggestions.length) {
179
+ return;
180
+ }
181
+ const suggestion = suggestions[indexToUse].value;
182
+
183
+ let start = completionStart;
184
+ let end = completionEnd;
185
+ if (completionMode === CompletionMode.SLASH) {
186
+ start = slashCompletionRange.completionStart;
187
+ end = slashCompletionRange.completionEnd;
188
+ }
189
+
190
+ if (start === -1 || end === -1) {
191
+ return;
192
+ }
193
+
194
+ let suggestionText = suggestion;
195
+ if (completionMode === CompletionMode.SLASH) {
196
+ if (
197
+ start === end &&
198
+ start > 1 &&
199
+ (buffer.lines[cursorRow] || '')[start - 1] !== ' '
200
+ ) {
201
+ suggestionText = ' ' + suggestionText;
202
+ }
203
+ }
204
+
205
+ suggestionText += ' ';
206
+
207
+ buffer.replaceRangeByOffset(
208
+ logicalPosToOffset(buffer.lines, cursorRow, start),
209
+ logicalPosToOffset(buffer.lines, cursorRow, end),
210
+ suggestionText,
211
+ );
212
+ },
213
+ [
214
+ cursorRow,
215
+ buffer,
216
+ suggestions,
217
+ completionMode,
218
+ completionStart,
219
+ completionEnd,
220
+ slashCompletionRange,
221
+ ],
222
+ );
223
+
224
+ return {
225
+ suggestions,
226
+ activeSuggestionIndex,
227
+ visibleStartIndex,
228
+ showSuggestions,
229
+ isLoadingSuggestions,
230
+ isPerfectMatch,
231
+ setActiveSuggestionIndex,
232
+ setShowSuggestions,
233
+ resetCompletionState,
234
+ navigateUp,
235
+ navigateDown,
236
+ handleAutocomplete,
237
+ };
238
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useCompletion.ts ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useCallback } from 'react';
8
+
9
+ import {
10
+ MAX_SUGGESTIONS_TO_SHOW,
11
+ Suggestion,
12
+ } from '../components/SuggestionsDisplay.js';
13
+
14
+ export interface UseCompletionReturn {
15
+ suggestions: Suggestion[];
16
+ activeSuggestionIndex: number;
17
+ visibleStartIndex: number;
18
+ showSuggestions: boolean;
19
+ isLoadingSuggestions: boolean;
20
+ isPerfectMatch: boolean;
21
+ setSuggestions: React.Dispatch<React.SetStateAction<Suggestion[]>>;
22
+ setActiveSuggestionIndex: React.Dispatch<React.SetStateAction<number>>;
23
+ setVisibleStartIndex: React.Dispatch<React.SetStateAction<number>>;
24
+ setIsLoadingSuggestions: React.Dispatch<React.SetStateAction<boolean>>;
25
+ setIsPerfectMatch: React.Dispatch<React.SetStateAction<boolean>>;
26
+ setShowSuggestions: React.Dispatch<React.SetStateAction<boolean>>;
27
+ resetCompletionState: () => void;
28
+ navigateUp: () => void;
29
+ navigateDown: () => void;
30
+ }
31
+
32
+ export function useCompletion(): UseCompletionReturn {
33
+ const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
34
+ const [activeSuggestionIndex, setActiveSuggestionIndex] =
35
+ useState<number>(-1);
36
+ const [visibleStartIndex, setVisibleStartIndex] = useState<number>(0);
37
+ const [showSuggestions, setShowSuggestions] = useState<boolean>(false);
38
+ const [isLoadingSuggestions, setIsLoadingSuggestions] =
39
+ useState<boolean>(false);
40
+ const [isPerfectMatch, setIsPerfectMatch] = useState<boolean>(false);
41
+
42
+ const resetCompletionState = useCallback(() => {
43
+ setSuggestions([]);
44
+ setActiveSuggestionIndex(-1);
45
+ setVisibleStartIndex(0);
46
+ setShowSuggestions(false);
47
+ setIsLoadingSuggestions(false);
48
+ setIsPerfectMatch(false);
49
+ }, []);
50
+
51
+ const navigateUp = useCallback(() => {
52
+ if (suggestions.length === 0) return;
53
+
54
+ setActiveSuggestionIndex((prevActiveIndex) => {
55
+ // Calculate new active index, handling wrap-around
56
+ const newActiveIndex =
57
+ prevActiveIndex <= 0 ? suggestions.length - 1 : prevActiveIndex - 1;
58
+
59
+ // Adjust scroll position based on the new active index
60
+ setVisibleStartIndex((prevVisibleStart) => {
61
+ // Case 1: Wrapped around to the last item
62
+ if (
63
+ newActiveIndex === suggestions.length - 1 &&
64
+ suggestions.length > MAX_SUGGESTIONS_TO_SHOW
65
+ ) {
66
+ return Math.max(0, suggestions.length - MAX_SUGGESTIONS_TO_SHOW);
67
+ }
68
+ // Case 2: Scrolled above the current visible window
69
+ if (newActiveIndex < prevVisibleStart) {
70
+ return newActiveIndex;
71
+ }
72
+ // Otherwise, keep the current scroll position
73
+ return prevVisibleStart;
74
+ });
75
+
76
+ return newActiveIndex;
77
+ });
78
+ }, [suggestions.length]);
79
+
80
+ const navigateDown = useCallback(() => {
81
+ if (suggestions.length === 0) return;
82
+
83
+ setActiveSuggestionIndex((prevActiveIndex) => {
84
+ // Calculate new active index, handling wrap-around
85
+ const newActiveIndex =
86
+ prevActiveIndex >= suggestions.length - 1 ? 0 : prevActiveIndex + 1;
87
+
88
+ // Adjust scroll position based on the new active index
89
+ setVisibleStartIndex((prevVisibleStart) => {
90
+ // Case 1: Wrapped around to the first item
91
+ if (
92
+ newActiveIndex === 0 &&
93
+ suggestions.length > MAX_SUGGESTIONS_TO_SHOW
94
+ ) {
95
+ return 0;
96
+ }
97
+ // Case 2: Scrolled below the current visible window
98
+ const visibleEndIndex = prevVisibleStart + MAX_SUGGESTIONS_TO_SHOW;
99
+ if (newActiveIndex >= visibleEndIndex) {
100
+ return newActiveIndex - MAX_SUGGESTIONS_TO_SHOW + 1;
101
+ }
102
+ // Otherwise, keep the current scroll position
103
+ return prevVisibleStart;
104
+ });
105
+
106
+ return newActiveIndex;
107
+ });
108
+ }, [suggestions.length]);
109
+ return {
110
+ suggestions,
111
+ activeSuggestionIndex,
112
+ visibleStartIndex,
113
+ showSuggestions,
114
+ isLoadingSuggestions,
115
+ isPerfectMatch,
116
+
117
+ setSuggestions,
118
+ setShowSuggestions,
119
+ setActiveSuggestionIndex,
120
+ setVisibleStartIndex,
121
+ setIsLoadingSuggestions,
122
+ setIsPerfectMatch,
123
+
124
+ resetCompletionState,
125
+ navigateUp,
126
+ navigateDown,
127
+ };
128
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useConsoleMessages.test.ts ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { act, renderHook } from '@testing-library/react';
8
+ import { vi } from 'vitest';
9
+ import { useConsoleMessages } from './useConsoleMessages';
10
+ import { useCallback } from 'react';
11
+
12
+ describe('useConsoleMessages', () => {
13
+ beforeEach(() => {
14
+ vi.useFakeTimers();
15
+ });
16
+
17
+ afterEach(() => {
18
+ vi.runOnlyPendingTimers();
19
+ vi.useRealTimers();
20
+ });
21
+
22
+ const useTestableConsoleMessages = () => {
23
+ const { handleNewMessage, ...rest } = useConsoleMessages();
24
+ const log = useCallback(
25
+ (content: string) => handleNewMessage({ type: 'log', content, count: 1 }),
26
+ [handleNewMessage],
27
+ );
28
+ const error = useCallback(
29
+ (content: string) =>
30
+ handleNewMessage({ type: 'error', content, count: 1 }),
31
+ [handleNewMessage],
32
+ );
33
+ return {
34
+ ...rest,
35
+ log,
36
+ error,
37
+ clearConsoleMessages: rest.clearConsoleMessages,
38
+ };
39
+ };
40
+
41
+ it('should initialize with an empty array of console messages', () => {
42
+ const { result } = renderHook(() => useTestableConsoleMessages());
43
+ expect(result.current.consoleMessages).toEqual([]);
44
+ });
45
+
46
+ it('should add a new message when log is called', async () => {
47
+ const { result } = renderHook(() => useTestableConsoleMessages());
48
+
49
+ act(() => {
50
+ result.current.log('Test message');
51
+ });
52
+
53
+ await act(async () => {
54
+ await vi.advanceTimersByTimeAsync(20);
55
+ });
56
+
57
+ expect(result.current.consoleMessages).toEqual([
58
+ { type: 'log', content: 'Test message', count: 1 },
59
+ ]);
60
+ });
61
+
62
+ it('should batch and count identical consecutive messages', async () => {
63
+ const { result } = renderHook(() => useTestableConsoleMessages());
64
+
65
+ act(() => {
66
+ result.current.log('Test message');
67
+ result.current.log('Test message');
68
+ result.current.log('Test message');
69
+ });
70
+
71
+ await act(async () => {
72
+ await vi.advanceTimersByTimeAsync(20);
73
+ });
74
+
75
+ expect(result.current.consoleMessages).toEqual([
76
+ { type: 'log', content: 'Test message', count: 3 },
77
+ ]);
78
+ });
79
+
80
+ it('should not batch different messages', async () => {
81
+ const { result } = renderHook(() => useTestableConsoleMessages());
82
+
83
+ act(() => {
84
+ result.current.log('First message');
85
+ result.current.error('Second message');
86
+ });
87
+
88
+ await act(async () => {
89
+ await vi.advanceTimersByTimeAsync(20);
90
+ });
91
+
92
+ expect(result.current.consoleMessages).toEqual([
93
+ { type: 'log', content: 'First message', count: 1 },
94
+ { type: 'error', content: 'Second message', count: 1 },
95
+ ]);
96
+ });
97
+
98
+ it('should clear all messages when clearConsoleMessages is called', async () => {
99
+ const { result } = renderHook(() => useTestableConsoleMessages());
100
+
101
+ act(() => {
102
+ result.current.log('A message');
103
+ });
104
+
105
+ await act(async () => {
106
+ await vi.advanceTimersByTimeAsync(20);
107
+ });
108
+
109
+ expect(result.current.consoleMessages).toHaveLength(1);
110
+
111
+ act(() => {
112
+ result.current.clearConsoleMessages();
113
+ });
114
+
115
+ expect(result.current.consoleMessages).toHaveLength(0);
116
+ });
117
+
118
+ it('should clear the pending timeout when clearConsoleMessages is called', () => {
119
+ const { result } = renderHook(() => useTestableConsoleMessages());
120
+ const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
121
+
122
+ act(() => {
123
+ result.current.log('A message');
124
+ });
125
+
126
+ act(() => {
127
+ result.current.clearConsoleMessages();
128
+ });
129
+
130
+ expect(clearTimeoutSpy).toHaveBeenCalled();
131
+ clearTimeoutSpy.mockRestore();
132
+ });
133
+
134
+ it('should clean up the timeout on unmount', () => {
135
+ const { result, unmount } = renderHook(() => useTestableConsoleMessages());
136
+ const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
137
+
138
+ act(() => {
139
+ result.current.log('A message');
140
+ });
141
+
142
+ unmount();
143
+
144
+ expect(clearTimeoutSpy).toHaveBeenCalled();
145
+ clearTimeoutSpy.mockRestore();
146
+ });
147
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useConsoleMessages.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ useCallback,
9
+ useEffect,
10
+ useReducer,
11
+ useRef,
12
+ useTransition,
13
+ } from 'react';
14
+ import { ConsoleMessageItem } from '../types.js';
15
+
16
+ export interface UseConsoleMessagesReturn {
17
+ consoleMessages: ConsoleMessageItem[];
18
+ handleNewMessage: (message: ConsoleMessageItem) => void;
19
+ clearConsoleMessages: () => void;
20
+ }
21
+
22
+ type Action =
23
+ | { type: 'ADD_MESSAGES'; payload: ConsoleMessageItem[] }
24
+ | { type: 'CLEAR' };
25
+
26
+ function consoleMessagesReducer(
27
+ state: ConsoleMessageItem[],
28
+ action: Action,
29
+ ): ConsoleMessageItem[] {
30
+ switch (action.type) {
31
+ case 'ADD_MESSAGES': {
32
+ const newMessages = [...state];
33
+ for (const queuedMessage of action.payload) {
34
+ const lastMessage = newMessages[newMessages.length - 1];
35
+ if (
36
+ lastMessage &&
37
+ lastMessage.type === queuedMessage.type &&
38
+ lastMessage.content === queuedMessage.content
39
+ ) {
40
+ // Create a new object for the last message to ensure React detects
41
+ // the change, preventing mutation of the existing state object.
42
+ newMessages[newMessages.length - 1] = {
43
+ ...lastMessage,
44
+ count: lastMessage.count + 1,
45
+ };
46
+ } else {
47
+ newMessages.push({ ...queuedMessage, count: 1 });
48
+ }
49
+ }
50
+ return newMessages;
51
+ }
52
+ case 'CLEAR':
53
+ return [];
54
+ default:
55
+ return state;
56
+ }
57
+ }
58
+
59
+ export function useConsoleMessages(): UseConsoleMessagesReturn {
60
+ const [consoleMessages, dispatch] = useReducer(consoleMessagesReducer, []);
61
+ const messageQueueRef = useRef<ConsoleMessageItem[]>([]);
62
+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);
63
+ const [, startTransition] = useTransition();
64
+
65
+ const processQueue = useCallback(() => {
66
+ if (messageQueueRef.current.length > 0) {
67
+ const messagesToProcess = messageQueueRef.current;
68
+ messageQueueRef.current = [];
69
+ startTransition(() => {
70
+ dispatch({ type: 'ADD_MESSAGES', payload: messagesToProcess });
71
+ });
72
+ }
73
+ timeoutRef.current = null;
74
+ }, []);
75
+
76
+ const handleNewMessage = useCallback(
77
+ (message: ConsoleMessageItem) => {
78
+ messageQueueRef.current.push(message);
79
+ if (!timeoutRef.current) {
80
+ // Batch updates using a timeout. 16ms is a reasonable delay to batch
81
+ // rapid-fire messages without noticeable lag.
82
+ timeoutRef.current = setTimeout(processQueue, 16);
83
+ }
84
+ },
85
+ [processQueue],
86
+ );
87
+
88
+ const clearConsoleMessages = useCallback(() => {
89
+ if (timeoutRef.current) {
90
+ clearTimeout(timeoutRef.current);
91
+ timeoutRef.current = null;
92
+ }
93
+ messageQueueRef.current = [];
94
+ startTransition(() => {
95
+ dispatch({ type: 'CLEAR' });
96
+ });
97
+ }, []);
98
+
99
+ // Cleanup on unmount
100
+ useEffect(
101
+ () => () => {
102
+ if (timeoutRef.current) {
103
+ clearTimeout(timeoutRef.current);
104
+ }
105
+ },
106
+ [],
107
+ );
108
+
109
+ return { consoleMessages, handleNewMessage, clearConsoleMessages };
110
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useEditorSettings.test.ts ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ afterEach,
9
+ beforeEach,
10
+ describe,
11
+ expect,
12
+ it,
13
+ vi,
14
+ type MockedFunction,
15
+ } from 'vitest';
16
+ import { act } from 'react';
17
+ import { renderHook } from '@testing-library/react';
18
+ import { useEditorSettings } from './useEditorSettings.js';
19
+ import { LoadedSettings, SettingScope } from '../../config/settings.js';
20
+ import { MessageType, type HistoryItem } from '../types.js';
21
+ import {
22
+ type EditorType,
23
+ checkHasEditorType,
24
+ allowEditorTypeInSandbox,
25
+ } from '@qwen-code/qwen-code-core';
26
+
27
+ vi.mock('@qwen-code/qwen-code-core', async () => {
28
+ const actual = await vi.importActual('@qwen-code/qwen-code-core');
29
+ return {
30
+ ...actual,
31
+ checkHasEditorType: vi.fn(() => true),
32
+ allowEditorTypeInSandbox: vi.fn(() => true),
33
+ };
34
+ });
35
+
36
+ const mockCheckHasEditorType = vi.mocked(checkHasEditorType);
37
+ const mockAllowEditorTypeInSandbox = vi.mocked(allowEditorTypeInSandbox);
38
+
39
+ describe('useEditorSettings', () => {
40
+ let mockLoadedSettings: LoadedSettings;
41
+ let mockSetEditorError: MockedFunction<(error: string | null) => void>;
42
+ let mockAddItem: MockedFunction<
43
+ (item: Omit<HistoryItem, 'id'>, timestamp: number) => void
44
+ >;
45
+
46
+ beforeEach(() => {
47
+ vi.resetAllMocks();
48
+
49
+ mockLoadedSettings = {
50
+ setValue: vi.fn(),
51
+ } as unknown as LoadedSettings;
52
+
53
+ mockSetEditorError = vi.fn();
54
+ mockAddItem = vi.fn();
55
+
56
+ // Reset mock implementations to default
57
+ mockCheckHasEditorType.mockReturnValue(true);
58
+ mockAllowEditorTypeInSandbox.mockReturnValue(true);
59
+ });
60
+
61
+ afterEach(() => {
62
+ vi.restoreAllMocks();
63
+ });
64
+
65
+ it('should initialize with dialog closed', () => {
66
+ const { result } = renderHook(() =>
67
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
68
+ );
69
+
70
+ expect(result.current.isEditorDialogOpen).toBe(false);
71
+ });
72
+
73
+ it('should open editor dialog when openEditorDialog is called', () => {
74
+ const { result } = renderHook(() =>
75
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
76
+ );
77
+
78
+ act(() => {
79
+ result.current.openEditorDialog();
80
+ });
81
+
82
+ expect(result.current.isEditorDialogOpen).toBe(true);
83
+ });
84
+
85
+ it('should close editor dialog when exitEditorDialog is called', () => {
86
+ const { result } = renderHook(() =>
87
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
88
+ );
89
+ act(() => {
90
+ result.current.openEditorDialog();
91
+ result.current.exitEditorDialog();
92
+ });
93
+ expect(result.current.isEditorDialogOpen).toBe(false);
94
+ });
95
+
96
+ it('should handle editor selection successfully', () => {
97
+ const { result } = renderHook(() =>
98
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
99
+ );
100
+
101
+ const editorType: EditorType = 'vscode';
102
+ const scope = SettingScope.User;
103
+
104
+ act(() => {
105
+ result.current.openEditorDialog();
106
+ result.current.handleEditorSelect(editorType, scope);
107
+ });
108
+
109
+ expect(mockLoadedSettings.setValue).toHaveBeenCalledWith(
110
+ scope,
111
+ 'preferredEditor',
112
+ editorType,
113
+ );
114
+
115
+ expect(mockAddItem).toHaveBeenCalledWith(
116
+ {
117
+ type: MessageType.INFO,
118
+ text: 'Editor preference set to "vscode" in User settings.',
119
+ },
120
+ expect.any(Number),
121
+ );
122
+
123
+ expect(mockSetEditorError).toHaveBeenCalledWith(null);
124
+ expect(result.current.isEditorDialogOpen).toBe(false);
125
+ });
126
+
127
+ it('should handle clearing editor preference (undefined editor)', () => {
128
+ const { result } = renderHook(() =>
129
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
130
+ );
131
+
132
+ const scope = SettingScope.Workspace;
133
+
134
+ act(() => {
135
+ result.current.openEditorDialog();
136
+ result.current.handleEditorSelect(undefined, scope);
137
+ });
138
+
139
+ expect(mockLoadedSettings.setValue).toHaveBeenCalledWith(
140
+ scope,
141
+ 'preferredEditor',
142
+ undefined,
143
+ );
144
+
145
+ expect(mockAddItem).toHaveBeenCalledWith(
146
+ {
147
+ type: MessageType.INFO,
148
+ text: 'Editor preference cleared in Workspace settings.',
149
+ },
150
+ expect.any(Number),
151
+ );
152
+
153
+ expect(mockSetEditorError).toHaveBeenCalledWith(null);
154
+ expect(result.current.isEditorDialogOpen).toBe(false);
155
+ });
156
+
157
+ it('should handle different editor types', () => {
158
+ const { result } = renderHook(() =>
159
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
160
+ );
161
+
162
+ const editorTypes: EditorType[] = ['cursor', 'windsurf', 'vim'];
163
+ const scope = SettingScope.User;
164
+
165
+ editorTypes.forEach((editorType) => {
166
+ act(() => {
167
+ result.current.handleEditorSelect(editorType, scope);
168
+ });
169
+
170
+ expect(mockLoadedSettings.setValue).toHaveBeenCalledWith(
171
+ scope,
172
+ 'preferredEditor',
173
+ editorType,
174
+ );
175
+
176
+ expect(mockAddItem).toHaveBeenCalledWith(
177
+ {
178
+ type: MessageType.INFO,
179
+ text: `Editor preference set to "${editorType}" in User settings.`,
180
+ },
181
+ expect.any(Number),
182
+ );
183
+ });
184
+ });
185
+
186
+ it('should handle different setting scopes', () => {
187
+ const { result } = renderHook(() =>
188
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
189
+ );
190
+
191
+ const editorType: EditorType = 'vscode';
192
+ const scopes = [SettingScope.User, SettingScope.Workspace];
193
+
194
+ scopes.forEach((scope) => {
195
+ act(() => {
196
+ result.current.handleEditorSelect(editorType, scope);
197
+ });
198
+
199
+ expect(mockLoadedSettings.setValue).toHaveBeenCalledWith(
200
+ scope,
201
+ 'preferredEditor',
202
+ editorType,
203
+ );
204
+
205
+ expect(mockAddItem).toHaveBeenCalledWith(
206
+ {
207
+ type: MessageType.INFO,
208
+ text: `Editor preference set to "vscode" in ${scope} settings.`,
209
+ },
210
+ expect.any(Number),
211
+ );
212
+ });
213
+ });
214
+
215
+ it('should not set preference for unavailable editors', () => {
216
+ const { result } = renderHook(() =>
217
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
218
+ );
219
+
220
+ mockCheckHasEditorType.mockReturnValue(false);
221
+
222
+ const editorType: EditorType = 'vscode';
223
+ const scope = SettingScope.User;
224
+
225
+ act(() => {
226
+ result.current.openEditorDialog();
227
+ result.current.handleEditorSelect(editorType, scope);
228
+ });
229
+
230
+ expect(mockLoadedSettings.setValue).not.toHaveBeenCalled();
231
+ expect(mockAddItem).not.toHaveBeenCalled();
232
+ expect(result.current.isEditorDialogOpen).toBe(true);
233
+ });
234
+
235
+ it('should not set preference for editors not allowed in sandbox', () => {
236
+ const { result } = renderHook(() =>
237
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
238
+ );
239
+
240
+ mockAllowEditorTypeInSandbox.mockReturnValue(false);
241
+
242
+ const editorType: EditorType = 'vscode';
243
+ const scope = SettingScope.User;
244
+
245
+ act(() => {
246
+ result.current.openEditorDialog();
247
+ result.current.handleEditorSelect(editorType, scope);
248
+ });
249
+
250
+ expect(mockLoadedSettings.setValue).not.toHaveBeenCalled();
251
+ expect(mockAddItem).not.toHaveBeenCalled();
252
+ expect(result.current.isEditorDialogOpen).toBe(true);
253
+ });
254
+
255
+ it('should handle errors during editor selection', () => {
256
+ const { result } = renderHook(() =>
257
+ useEditorSettings(mockLoadedSettings, mockSetEditorError, mockAddItem),
258
+ );
259
+
260
+ const errorMessage = 'Failed to save settings';
261
+ (
262
+ mockLoadedSettings.setValue as MockedFunction<
263
+ typeof mockLoadedSettings.setValue
264
+ >
265
+ ).mockImplementation(() => {
266
+ throw new Error(errorMessage);
267
+ });
268
+
269
+ const editorType: EditorType = 'vscode';
270
+ const scope = SettingScope.User;
271
+
272
+ act(() => {
273
+ result.current.openEditorDialog();
274
+ result.current.handleEditorSelect(editorType, scope);
275
+ });
276
+
277
+ expect(mockSetEditorError).toHaveBeenCalledWith(
278
+ `Failed to set editor preference: Error: ${errorMessage}`,
279
+ );
280
+ expect(mockAddItem).not.toHaveBeenCalled();
281
+ expect(result.current.isEditorDialogOpen).toBe(true);
282
+ });
283
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useEditorSettings.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useCallback } from 'react';
8
+ import { LoadedSettings, SettingScope } from '../../config/settings.js';
9
+ import { type HistoryItem, MessageType } from '../types.js';
10
+ import {
11
+ allowEditorTypeInSandbox,
12
+ checkHasEditorType,
13
+ EditorType,
14
+ } from '@qwen-code/qwen-code-core';
15
+
16
+ interface UseEditorSettingsReturn {
17
+ isEditorDialogOpen: boolean;
18
+ openEditorDialog: () => void;
19
+ handleEditorSelect: (
20
+ editorType: EditorType | undefined,
21
+ scope: SettingScope,
22
+ ) => void;
23
+ exitEditorDialog: () => void;
24
+ }
25
+
26
+ export const useEditorSettings = (
27
+ loadedSettings: LoadedSettings,
28
+ setEditorError: (error: string | null) => void,
29
+ addItem: (item: Omit<HistoryItem, 'id'>, timestamp: number) => void,
30
+ ): UseEditorSettingsReturn => {
31
+ const [isEditorDialogOpen, setIsEditorDialogOpen] = useState(false);
32
+
33
+ const openEditorDialog = useCallback(() => {
34
+ setIsEditorDialogOpen(true);
35
+ }, []);
36
+
37
+ const handleEditorSelect = useCallback(
38
+ (editorType: EditorType | undefined, scope: SettingScope) => {
39
+ if (
40
+ editorType &&
41
+ (!checkHasEditorType(editorType) ||
42
+ !allowEditorTypeInSandbox(editorType))
43
+ ) {
44
+ return;
45
+ }
46
+
47
+ try {
48
+ loadedSettings.setValue(scope, 'preferredEditor', editorType);
49
+ addItem(
50
+ {
51
+ type: MessageType.INFO,
52
+ text: `Editor preference ${editorType ? `set to "${editorType}"` : 'cleared'} in ${scope} settings.`,
53
+ },
54
+ Date.now(),
55
+ );
56
+ setEditorError(null);
57
+ setIsEditorDialogOpen(false);
58
+ } catch (error) {
59
+ setEditorError(`Failed to set editor preference: ${error}`);
60
+ }
61
+ },
62
+ [loadedSettings, setEditorError, addItem],
63
+ );
64
+
65
+ const exitEditorDialog = useCallback(() => {
66
+ setIsEditorDialogOpen(false);
67
+ }, []);
68
+
69
+ return {
70
+ isEditorDialogOpen,
71
+ openEditorDialog,
72
+ handleEditorSelect,
73
+ exitEditorDialog,
74
+ };
75
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useFocus.test.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { renderHook, act } from '@testing-library/react';
8
+ import { EventEmitter } from 'events';
9
+ import { useFocus } from './useFocus.js';
10
+ import { vi } from 'vitest';
11
+ import { useStdin, useStdout } from 'ink';
12
+
13
+ // Mock the ink hooks
14
+ vi.mock('ink', async (importOriginal) => {
15
+ const original = await importOriginal<typeof import('ink')>();
16
+ return {
17
+ ...original,
18
+ useStdin: vi.fn(),
19
+ useStdout: vi.fn(),
20
+ };
21
+ });
22
+
23
+ const mockedUseStdin = vi.mocked(useStdin);
24
+ const mockedUseStdout = vi.mocked(useStdout);
25
+
26
+ describe('useFocus', () => {
27
+ let stdin: EventEmitter;
28
+ let stdout: { write: vi.Func };
29
+
30
+ beforeEach(() => {
31
+ stdin = new EventEmitter();
32
+ stdout = { write: vi.fn() };
33
+ mockedUseStdin.mockReturnValue({ stdin } as ReturnType<typeof useStdin>);
34
+ mockedUseStdout.mockReturnValue({ stdout } as unknown as ReturnType<
35
+ typeof useStdout
36
+ >);
37
+ });
38
+
39
+ afterEach(() => {
40
+ vi.clearAllMocks();
41
+ });
42
+
43
+ it('should initialize with focus and enable focus reporting', () => {
44
+ const { result } = renderHook(() => useFocus());
45
+
46
+ expect(result.current).toBe(true);
47
+ expect(stdout.write).toHaveBeenCalledWith('\x1b[?1004h');
48
+ });
49
+
50
+ it('should set isFocused to false when a focus-out event is received', () => {
51
+ const { result } = renderHook(() => useFocus());
52
+
53
+ // Initial state is focused
54
+ expect(result.current).toBe(true);
55
+
56
+ // Simulate focus-out event
57
+ act(() => {
58
+ stdin.emit('data', Buffer.from('\x1b[O'));
59
+ });
60
+
61
+ // State should now be unfocused
62
+ expect(result.current).toBe(false);
63
+ });
64
+
65
+ it('should set isFocused to true when a focus-in event is received', () => {
66
+ const { result } = renderHook(() => useFocus());
67
+
68
+ // Simulate focus-out to set initial state to false
69
+ act(() => {
70
+ stdin.emit('data', Buffer.from('\x1b[O'));
71
+ });
72
+ expect(result.current).toBe(false);
73
+
74
+ // Simulate focus-in event
75
+ act(() => {
76
+ stdin.emit('data', Buffer.from('\x1b[I'));
77
+ });
78
+
79
+ // State should now be focused
80
+ expect(result.current).toBe(true);
81
+ });
82
+
83
+ it('should clean up and disable focus reporting on unmount', () => {
84
+ const { unmount } = renderHook(() => useFocus());
85
+
86
+ // Ensure listener was attached
87
+ expect(stdin.listenerCount('data')).toBe(1);
88
+
89
+ unmount();
90
+
91
+ // Assert that the cleanup function was called
92
+ expect(stdout.write).toHaveBeenCalledWith('\x1b[?1004l');
93
+ expect(stdin.listenerCount('data')).toBe(0);
94
+ });
95
+
96
+ it('should handle multiple focus events correctly', () => {
97
+ const { result } = renderHook(() => useFocus());
98
+
99
+ act(() => {
100
+ stdin.emit('data', Buffer.from('\x1b[O'));
101
+ });
102
+ expect(result.current).toBe(false);
103
+
104
+ act(() => {
105
+ stdin.emit('data', Buffer.from('\x1b[O'));
106
+ });
107
+ expect(result.current).toBe(false);
108
+
109
+ act(() => {
110
+ stdin.emit('data', Buffer.from('\x1b[I'));
111
+ });
112
+ expect(result.current).toBe(true);
113
+
114
+ act(() => {
115
+ stdin.emit('data', Buffer.from('\x1b[I'));
116
+ });
117
+ expect(result.current).toBe(true);
118
+ });
119
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useFocus.ts ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useStdin, useStdout } from 'ink';
8
+ import { useEffect, useState } from 'react';
9
+
10
+ // ANSI escape codes to enable/disable terminal focus reporting
11
+ export const ENABLE_FOCUS_REPORTING = '\x1b[?1004h';
12
+ export const DISABLE_FOCUS_REPORTING = '\x1b[?1004l';
13
+
14
+ // ANSI escape codes for focus events
15
+ export const FOCUS_IN = '\x1b[I';
16
+ export const FOCUS_OUT = '\x1b[O';
17
+
18
+ export const useFocus = () => {
19
+ const { stdin } = useStdin();
20
+ const { stdout } = useStdout();
21
+ const [isFocused, setIsFocused] = useState(true);
22
+
23
+ useEffect(() => {
24
+ const handleData = (data: Buffer) => {
25
+ const sequence = data.toString();
26
+ const lastFocusIn = sequence.lastIndexOf(FOCUS_IN);
27
+ const lastFocusOut = sequence.lastIndexOf(FOCUS_OUT);
28
+
29
+ if (lastFocusIn > lastFocusOut) {
30
+ setIsFocused(true);
31
+ } else if (lastFocusOut > lastFocusIn) {
32
+ setIsFocused(false);
33
+ }
34
+ };
35
+
36
+ // Enable focus reporting
37
+ stdout?.write(ENABLE_FOCUS_REPORTING);
38
+ stdin?.on('data', handleData);
39
+
40
+ return () => {
41
+ // Disable focus reporting on cleanup
42
+ stdout?.write(DISABLE_FOCUS_REPORTING);
43
+ stdin?.removeListener('data', handleData);
44
+ };
45
+ }, [stdin, stdout]);
46
+
47
+ return isFocused;
48
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useFolderTrust.test.ts ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import { useFolderTrust } from './useFolderTrust.js';
10
+ import { LoadedSettings } from '../../config/settings.js';
11
+ import { FolderTrustChoice } from '../components/FolderTrustDialog.js';
12
+ import {
13
+ LoadedTrustedFolders,
14
+ TrustLevel,
15
+ } from '../../config/trustedFolders.js';
16
+ import * as process from 'process';
17
+
18
+ import * as trustedFolders from '../../config/trustedFolders.js';
19
+
20
+ vi.mock('process', () => ({
21
+ cwd: vi.fn(),
22
+ platform: 'linux',
23
+ }));
24
+
25
+ describe('useFolderTrust', () => {
26
+ let mockSettings: LoadedSettings;
27
+ let mockTrustedFolders: LoadedTrustedFolders;
28
+ let loadTrustedFoldersSpy: vi.SpyInstance;
29
+ let isWorkspaceTrustedSpy: vi.SpyInstance;
30
+ let onTrustChange: (isTrusted: boolean | undefined) => void;
31
+
32
+ beforeEach(() => {
33
+ mockSettings = {
34
+ merged: {
35
+ folderTrustFeature: true,
36
+ folderTrust: undefined,
37
+ },
38
+ setValue: vi.fn(),
39
+ } as unknown as LoadedSettings;
40
+
41
+ mockTrustedFolders = {
42
+ setValue: vi.fn(),
43
+ } as unknown as LoadedTrustedFolders;
44
+
45
+ loadTrustedFoldersSpy = vi
46
+ .spyOn(trustedFolders, 'loadTrustedFolders')
47
+ .mockReturnValue(mockTrustedFolders);
48
+ isWorkspaceTrustedSpy = vi.spyOn(trustedFolders, 'isWorkspaceTrusted');
49
+ (process.cwd as vi.Mock).mockReturnValue('/test/path');
50
+ onTrustChange = vi.fn();
51
+ });
52
+
53
+ afterEach(() => {
54
+ vi.clearAllMocks();
55
+ });
56
+
57
+ it('should not open dialog when folder is already trusted', () => {
58
+ isWorkspaceTrustedSpy.mockReturnValue(true);
59
+ const { result } = renderHook(() =>
60
+ useFolderTrust(mockSettings, onTrustChange),
61
+ );
62
+ expect(result.current.isFolderTrustDialogOpen).toBe(false);
63
+ expect(onTrustChange).toHaveBeenCalledWith(true);
64
+ });
65
+
66
+ it('should not open dialog when folder is already untrusted', () => {
67
+ isWorkspaceTrustedSpy.mockReturnValue(false);
68
+ const { result } = renderHook(() =>
69
+ useFolderTrust(mockSettings, onTrustChange),
70
+ );
71
+ expect(result.current.isFolderTrustDialogOpen).toBe(false);
72
+ expect(onTrustChange).toHaveBeenCalledWith(false);
73
+ });
74
+
75
+ it('should open dialog when folder trust is undefined', () => {
76
+ isWorkspaceTrustedSpy.mockReturnValue(undefined);
77
+ const { result } = renderHook(() =>
78
+ useFolderTrust(mockSettings, onTrustChange),
79
+ );
80
+ expect(result.current.isFolderTrustDialogOpen).toBe(true);
81
+ expect(onTrustChange).toHaveBeenCalledWith(undefined);
82
+ });
83
+
84
+ it('should handle TRUST_FOLDER choice', () => {
85
+ isWorkspaceTrustedSpy.mockReturnValue(undefined);
86
+ const { result } = renderHook(() =>
87
+ useFolderTrust(mockSettings, onTrustChange),
88
+ );
89
+
90
+ isWorkspaceTrustedSpy.mockReturnValue(true);
91
+ act(() => {
92
+ result.current.handleFolderTrustSelect(FolderTrustChoice.TRUST_FOLDER);
93
+ });
94
+
95
+ expect(loadTrustedFoldersSpy).toHaveBeenCalled();
96
+ expect(mockTrustedFolders.setValue).toHaveBeenCalledWith(
97
+ '/test/path',
98
+ TrustLevel.TRUST_FOLDER,
99
+ );
100
+ expect(result.current.isFolderTrustDialogOpen).toBe(false);
101
+ expect(onTrustChange).toHaveBeenLastCalledWith(true);
102
+ });
103
+
104
+ it('should handle TRUST_PARENT choice', () => {
105
+ isWorkspaceTrustedSpy.mockReturnValue(undefined);
106
+ const { result } = renderHook(() =>
107
+ useFolderTrust(mockSettings, onTrustChange),
108
+ );
109
+
110
+ isWorkspaceTrustedSpy.mockReturnValue(true);
111
+ act(() => {
112
+ result.current.handleFolderTrustSelect(FolderTrustChoice.TRUST_PARENT);
113
+ });
114
+
115
+ expect(mockTrustedFolders.setValue).toHaveBeenCalledWith(
116
+ '/test/path',
117
+ TrustLevel.TRUST_PARENT,
118
+ );
119
+ expect(result.current.isFolderTrustDialogOpen).toBe(false);
120
+ expect(onTrustChange).toHaveBeenLastCalledWith(true);
121
+ });
122
+
123
+ it('should handle DO_NOT_TRUST choice', () => {
124
+ isWorkspaceTrustedSpy.mockReturnValue(undefined);
125
+ const { result } = renderHook(() =>
126
+ useFolderTrust(mockSettings, onTrustChange),
127
+ );
128
+
129
+ isWorkspaceTrustedSpy.mockReturnValue(false);
130
+ act(() => {
131
+ result.current.handleFolderTrustSelect(FolderTrustChoice.DO_NOT_TRUST);
132
+ });
133
+
134
+ expect(mockTrustedFolders.setValue).toHaveBeenCalledWith(
135
+ '/test/path',
136
+ TrustLevel.DO_NOT_TRUST,
137
+ );
138
+ expect(result.current.isFolderTrustDialogOpen).toBe(false);
139
+ expect(onTrustChange).toHaveBeenLastCalledWith(false);
140
+ });
141
+
142
+ it('should do nothing for default choice', () => {
143
+ isWorkspaceTrustedSpy.mockReturnValue(undefined);
144
+ const { result } = renderHook(() =>
145
+ useFolderTrust(mockSettings, onTrustChange),
146
+ );
147
+
148
+ act(() => {
149
+ result.current.handleFolderTrustSelect(
150
+ 'invalid_choice' as FolderTrustChoice,
151
+ );
152
+ });
153
+
154
+ expect(mockTrustedFolders.setValue).not.toHaveBeenCalled();
155
+ expect(mockSettings.setValue).not.toHaveBeenCalled();
156
+ expect(result.current.isFolderTrustDialogOpen).toBe(true);
157
+ expect(onTrustChange).toHaveBeenCalledWith(undefined);
158
+ });
159
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useFolderTrust.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useCallback, useEffect } from 'react';
8
+ import { Settings, LoadedSettings } from '../../config/settings.js';
9
+ import { FolderTrustChoice } from '../components/FolderTrustDialog.js';
10
+ import {
11
+ loadTrustedFolders,
12
+ TrustLevel,
13
+ isWorkspaceTrusted,
14
+ } from '../../config/trustedFolders.js';
15
+ import * as process from 'process';
16
+
17
+ export const useFolderTrust = (
18
+ settings: LoadedSettings,
19
+ onTrustChange: (isTrusted: boolean | undefined) => void,
20
+ ) => {
21
+ const [isTrusted, setIsTrusted] = useState<boolean | undefined>(undefined);
22
+ const [isFolderTrustDialogOpen, setIsFolderTrustDialogOpen] = useState(false);
23
+
24
+ const { folderTrust, folderTrustFeature } = settings.merged;
25
+ useEffect(() => {
26
+ const trusted = isWorkspaceTrusted({
27
+ folderTrust,
28
+ folderTrustFeature,
29
+ } as Settings);
30
+ setIsTrusted(trusted);
31
+ setIsFolderTrustDialogOpen(trusted === undefined);
32
+ onTrustChange(trusted);
33
+ }, [onTrustChange, folderTrust, folderTrustFeature]);
34
+
35
+ const handleFolderTrustSelect = useCallback(
36
+ (choice: FolderTrustChoice) => {
37
+ const trustedFolders = loadTrustedFolders();
38
+ const cwd = process.cwd();
39
+ let trustLevel: TrustLevel;
40
+
41
+ switch (choice) {
42
+ case FolderTrustChoice.TRUST_FOLDER:
43
+ trustLevel = TrustLevel.TRUST_FOLDER;
44
+ break;
45
+ case FolderTrustChoice.TRUST_PARENT:
46
+ trustLevel = TrustLevel.TRUST_PARENT;
47
+ break;
48
+ case FolderTrustChoice.DO_NOT_TRUST:
49
+ trustLevel = TrustLevel.DO_NOT_TRUST;
50
+ break;
51
+ default:
52
+ return;
53
+ }
54
+
55
+ trustedFolders.setValue(cwd, trustLevel);
56
+ const trusted = isWorkspaceTrusted({
57
+ folderTrust,
58
+ folderTrustFeature,
59
+ } as Settings);
60
+ setIsTrusted(trusted);
61
+ setIsFolderTrustDialogOpen(false);
62
+ onTrustChange(trusted);
63
+ },
64
+ [onTrustChange, folderTrust, folderTrustFeature],
65
+ );
66
+
67
+ return {
68
+ isTrusted,
69
+ isFolderTrustDialogOpen,
70
+ handleFolderTrustSelect,
71
+ };
72
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useGeminiStream.test.tsx ADDED
@@ -0,0 +1,1998 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+ import {
9
+ describe,
10
+ it,
11
+ expect,
12
+ vi,
13
+ beforeEach,
14
+ Mock,
15
+ MockInstance,
16
+ } from 'vitest';
17
+ import { renderHook, act, waitFor } from '@testing-library/react';
18
+ import { useGeminiStream, mergePartListUnions } from './useGeminiStream.js';
19
+ import { useKeypress } from './useKeypress.js';
20
+ import * as atCommandProcessor from './atCommandProcessor.js';
21
+ import {
22
+ useReactToolScheduler,
23
+ TrackedToolCall,
24
+ TrackedCompletedToolCall,
25
+ TrackedExecutingToolCall,
26
+ TrackedCancelledToolCall,
27
+ } from './useReactToolScheduler.js';
28
+ import {
29
+ Config,
30
+ EditorType,
31
+ AuthType,
32
+ GeminiClient,
33
+ GeminiEventType as ServerGeminiEventType,
34
+ AnyToolInvocation,
35
+ ToolErrorType,
36
+ } from '@qwen-code/qwen-code-core';
37
+ import { Part, PartListUnion } from '@google/genai';
38
+ import { UseHistoryManagerReturn } from './useHistoryManager.js';
39
+ import {
40
+ HistoryItem,
41
+ MessageType,
42
+ SlashCommandProcessorResult,
43
+ StreamingState,
44
+ } from '../types.js';
45
+ import { LoadedSettings } from '../../config/settings.js';
46
+
47
+ // --- MOCKS ---
48
+ const mockSendMessageStream = vi
49
+ .fn()
50
+ .mockReturnValue((async function* () {})());
51
+ const mockStartChat = vi.fn();
52
+
53
+ const MockedGeminiClientClass = vi.hoisted(() =>
54
+ vi.fn().mockImplementation(function (this: any, _config: any) {
55
+ // _config
56
+ this.startChat = mockStartChat;
57
+ this.sendMessageStream = mockSendMessageStream;
58
+ this.addHistory = vi.fn();
59
+ }),
60
+ );
61
+
62
+ const MockedUserPromptEvent = vi.hoisted(() =>
63
+ vi.fn().mockImplementation(() => {}),
64
+ );
65
+ const mockParseAndFormatApiError = vi.hoisted(() => vi.fn());
66
+
67
+ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
68
+ const actualCoreModule = (await importOriginal()) as any;
69
+ return {
70
+ ...actualCoreModule,
71
+ GitService: vi.fn(),
72
+ GeminiClient: MockedGeminiClientClass,
73
+ UserPromptEvent: MockedUserPromptEvent,
74
+ parseAndFormatApiError: mockParseAndFormatApiError,
75
+ };
76
+ });
77
+
78
+ const mockUseReactToolScheduler = useReactToolScheduler as Mock;
79
+ vi.mock('./useReactToolScheduler.js', async (importOriginal) => {
80
+ const actualSchedulerModule = (await importOriginal()) as any;
81
+ return {
82
+ ...(actualSchedulerModule || {}),
83
+ useReactToolScheduler: vi.fn(),
84
+ };
85
+ });
86
+
87
+ vi.mock('./useKeypress.js', () => ({
88
+ useKeypress: vi.fn(),
89
+ }));
90
+
91
+ vi.mock('./shellCommandProcessor.js', () => ({
92
+ useShellCommandProcessor: vi.fn().mockReturnValue({
93
+ handleShellCommand: vi.fn(),
94
+ }),
95
+ }));
96
+
97
+ vi.mock('./atCommandProcessor.js');
98
+
99
+ vi.mock('../utils/markdownUtilities.js', () => ({
100
+ findLastSafeSplitPoint: vi.fn((s: string) => s.length),
101
+ }));
102
+
103
+ vi.mock('./useStateAndRef.js', () => ({
104
+ useStateAndRef: vi.fn((initial) => {
105
+ let val = initial;
106
+ const ref = { current: val };
107
+ const setVal = vi.fn((updater) => {
108
+ if (typeof updater === 'function') {
109
+ val = updater(val);
110
+ } else {
111
+ val = updater;
112
+ }
113
+ ref.current = val;
114
+ });
115
+ return [ref, setVal];
116
+ }),
117
+ }));
118
+
119
+ vi.mock('./useLogger.js', () => ({
120
+ useLogger: vi.fn().mockReturnValue({
121
+ logMessage: vi.fn().mockResolvedValue(undefined),
122
+ }),
123
+ }));
124
+
125
+ const mockStartNewPrompt = vi.fn();
126
+ const mockAddUsage = vi.fn();
127
+ vi.mock('../contexts/SessionContext.js', () => ({
128
+ useSessionStats: vi.fn(() => ({
129
+ startNewPrompt: mockStartNewPrompt,
130
+ addUsage: mockAddUsage,
131
+ getPromptCount: vi.fn(() => 5),
132
+ })),
133
+ }));
134
+
135
+ vi.mock('./slashCommandProcessor.js', () => ({
136
+ handleSlashCommand: vi.fn().mockReturnValue(false),
137
+ }));
138
+
139
+ // --- END MOCKS ---
140
+
141
+ describe('mergePartListUnions', () => {
142
+ it('should merge multiple PartListUnion arrays', () => {
143
+ const list1: PartListUnion = [{ text: 'Hello' }];
144
+ const list2: PartListUnion = [
145
+ { inlineData: { mimeType: 'image/png', data: 'abc' } },
146
+ ];
147
+ const list3: PartListUnion = [{ text: 'World' }, { text: '!' }];
148
+ const result = mergePartListUnions([list1, list2, list3]);
149
+ expect(result).toEqual([
150
+ { text: 'Hello' },
151
+ { inlineData: { mimeType: 'image/png', data: 'abc' } },
152
+ { text: 'World' },
153
+ { text: '!' },
154
+ ]);
155
+ });
156
+
157
+ it('should handle empty arrays in the input list', () => {
158
+ const list1: PartListUnion = [{ text: 'First' }];
159
+ const list2: PartListUnion = [];
160
+ const list3: PartListUnion = [{ text: 'Last' }];
161
+ const result = mergePartListUnions([list1, list2, list3]);
162
+ expect(result).toEqual([{ text: 'First' }, { text: 'Last' }]);
163
+ });
164
+
165
+ it('should handle a single PartListUnion array', () => {
166
+ const list1: PartListUnion = [
167
+ { text: 'One' },
168
+ { inlineData: { mimeType: 'image/jpeg', data: 'xyz' } },
169
+ ];
170
+ const result = mergePartListUnions([list1]);
171
+ expect(result).toEqual(list1);
172
+ });
173
+
174
+ it('should return an empty array if all input arrays are empty', () => {
175
+ const list1: PartListUnion = [];
176
+ const list2: PartListUnion = [];
177
+ const result = mergePartListUnions([list1, list2]);
178
+ expect(result).toEqual([]);
179
+ });
180
+
181
+ it('should handle input list being empty', () => {
182
+ const result = mergePartListUnions([]);
183
+ expect(result).toEqual([]);
184
+ });
185
+
186
+ it('should correctly merge when PartListUnion items are single Parts not in arrays', () => {
187
+ const part1: Part = { text: 'Single part 1' };
188
+ const part2: Part = { inlineData: { mimeType: 'image/gif', data: 'gif' } };
189
+ const listContainingSingleParts: PartListUnion[] = [
190
+ part1,
191
+ [part2],
192
+ { text: 'Another single part' },
193
+ ];
194
+ const result = mergePartListUnions(listContainingSingleParts);
195
+ expect(result).toEqual([
196
+ { text: 'Single part 1' },
197
+ { inlineData: { mimeType: 'image/gif', data: 'gif' } },
198
+ { text: 'Another single part' },
199
+ ]);
200
+ });
201
+
202
+ 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)', () => {
203
+ const list1: PartListUnion = [{ text: 'A' }];
204
+ const list2: PartListUnion = [];
205
+ const part3: Part = { text: 'B' };
206
+ const list4: PartListUnion = [
207
+ { text: 'C' },
208
+ { inlineData: { mimeType: 'text/plain', data: 'D' } },
209
+ ];
210
+ const result = mergePartListUnions([list1, list2, part3, list4]);
211
+ expect(result).toEqual([
212
+ { text: 'A' },
213
+ { text: 'B' },
214
+ { text: 'C' },
215
+ { inlineData: { mimeType: 'text/plain', data: 'D' } },
216
+ ]);
217
+ });
218
+
219
+ it('should preserve the order of parts from the input arrays', () => {
220
+ const listA: PartListUnion = [{ text: '1' }, { text: '2' }];
221
+ const listB: PartListUnion = [{ text: '3' }];
222
+ const listC: PartListUnion = [{ text: '4' }, { text: '5' }];
223
+ const result = mergePartListUnions([listA, listB, listC]);
224
+ expect(result).toEqual([
225
+ { text: '1' },
226
+ { text: '2' },
227
+ { text: '3' },
228
+ { text: '4' },
229
+ { text: '5' },
230
+ ]);
231
+ });
232
+
233
+ it('should handle cases where some PartListUnion items are single Parts and others are arrays of Parts', () => {
234
+ const singlePart1: Part = { text: 'First single' };
235
+ const arrayPart1: Part[] = [
236
+ { text: 'Array item 1' },
237
+ { text: 'Array item 2' },
238
+ ];
239
+ const singlePart2: Part = {
240
+ inlineData: { mimeType: 'application/json', data: 'e30=' },
241
+ }; // {}
242
+ const arrayPart2: Part[] = [{ text: 'Last array item' }];
243
+
244
+ const result = mergePartListUnions([
245
+ singlePart1,
246
+ arrayPart1,
247
+ singlePart2,
248
+ arrayPart2,
249
+ ]);
250
+ expect(result).toEqual([
251
+ { text: 'First single' },
252
+ { text: 'Array item 1' },
253
+ { text: 'Array item 2' },
254
+ { inlineData: { mimeType: 'application/json', data: 'e30=' } },
255
+ { text: 'Last array item' },
256
+ ]);
257
+ });
258
+ });
259
+
260
+ // --- Tests for useGeminiStream Hook ---
261
+ describe('useGeminiStream', () => {
262
+ let mockAddItem: Mock;
263
+ let mockConfig: Config;
264
+ let mockOnDebugMessage: Mock;
265
+ let mockHandleSlashCommand: Mock;
266
+ let mockScheduleToolCalls: Mock;
267
+ let mockCancelAllToolCalls: Mock;
268
+ let mockMarkToolsAsSubmitted: Mock;
269
+ let handleAtCommandSpy: MockInstance;
270
+
271
+ beforeEach(() => {
272
+ vi.clearAllMocks(); // Clear mocks before each test
273
+
274
+ mockAddItem = vi.fn();
275
+ // Define the mock for getGeminiClient
276
+ const mockGetGeminiClient = vi.fn().mockImplementation(() => {
277
+ // MockedGeminiClientClass is defined in the module scope by the previous change.
278
+ // It will use the mockStartChat and mockSendMessageStream that are managed within beforeEach.
279
+ const clientInstance = new MockedGeminiClientClass(mockConfig);
280
+ return clientInstance;
281
+ });
282
+
283
+ const contentGeneratorConfig = {
284
+ model: 'test-model',
285
+ apiKey: 'test-key',
286
+ vertexai: false,
287
+ authType: AuthType.USE_GEMINI,
288
+ };
289
+
290
+ mockConfig = {
291
+ apiKey: 'test-api-key',
292
+ model: 'gemini-pro',
293
+ sandbox: false,
294
+ targetDir: '/test/dir',
295
+ debugMode: false,
296
+ question: undefined,
297
+ fullContext: false,
298
+ coreTools: [],
299
+ toolDiscoveryCommand: undefined,
300
+ toolCallCommand: undefined,
301
+ mcpServerCommand: undefined,
302
+ mcpServers: undefined,
303
+ userAgent: 'test-agent',
304
+ userMemory: '',
305
+ geminiMdFileCount: 0,
306
+ alwaysSkipModificationConfirmation: false,
307
+ vertexai: false,
308
+ showMemoryUsage: false,
309
+ contextFileName: undefined,
310
+ getToolRegistry: vi.fn(
311
+ () => ({ getToolSchemaList: vi.fn(() => []) }) as any,
312
+ ),
313
+ getProjectRoot: vi.fn(() => '/test/dir'),
314
+ getCheckpointingEnabled: vi.fn(() => false),
315
+ getGeminiClient: mockGetGeminiClient,
316
+ getUsageStatisticsEnabled: () => true,
317
+ getDebugMode: () => false,
318
+ addHistory: vi.fn(),
319
+ getSessionId() {
320
+ return 'test-session-id';
321
+ },
322
+ setQuotaErrorOccurred: vi.fn(),
323
+ getQuotaErrorOccurred: vi.fn(() => false),
324
+ getModel: vi.fn(() => 'gemini-2.5-pro'),
325
+ getContentGeneratorConfig: vi
326
+ .fn()
327
+ .mockReturnValue(contentGeneratorConfig),
328
+ } as unknown as Config;
329
+ mockOnDebugMessage = vi.fn();
330
+ mockHandleSlashCommand = vi.fn().mockResolvedValue(false);
331
+
332
+ // Mock return value for useReactToolScheduler
333
+ mockScheduleToolCalls = vi.fn();
334
+ mockCancelAllToolCalls = vi.fn();
335
+ mockMarkToolsAsSubmitted = vi.fn();
336
+
337
+ // Default mock for useReactToolScheduler to prevent toolCalls being undefined initially
338
+ mockUseReactToolScheduler.mockReturnValue([
339
+ [], // Default to empty array for toolCalls
340
+ mockScheduleToolCalls,
341
+ mockCancelAllToolCalls,
342
+ mockMarkToolsAsSubmitted,
343
+ ]);
344
+
345
+ // Reset mocks for GeminiClient instance methods (startChat and sendMessageStream)
346
+ // The GeminiClient constructor itself is mocked at the module level.
347
+ mockStartChat.mockClear().mockResolvedValue({
348
+ sendMessageStream: mockSendMessageStream,
349
+ } as unknown as any); // GeminiChat -> any
350
+ mockSendMessageStream
351
+ .mockClear()
352
+ .mockReturnValue((async function* () {})());
353
+ handleAtCommandSpy = vi.spyOn(atCommandProcessor, 'handleAtCommand');
354
+ });
355
+
356
+ const mockLoadedSettings: LoadedSettings = {
357
+ merged: { preferredEditor: 'vscode' },
358
+ user: { path: '/user/settings.json', settings: {} },
359
+ workspace: { path: '/workspace/.qwen/settings.json', settings: {} },
360
+ errors: [],
361
+ forScope: vi.fn(),
362
+ setValue: vi.fn(),
363
+ } as unknown as LoadedSettings;
364
+
365
+ const renderTestHook = (
366
+ initialToolCalls: TrackedToolCall[] = [],
367
+ geminiClient?: any,
368
+ ) => {
369
+ let currentToolCalls = initialToolCalls;
370
+ const setToolCalls = (newToolCalls: TrackedToolCall[]) => {
371
+ currentToolCalls = newToolCalls;
372
+ };
373
+
374
+ mockUseReactToolScheduler.mockImplementation(() => [
375
+ currentToolCalls,
376
+ mockScheduleToolCalls,
377
+ mockCancelAllToolCalls,
378
+ mockMarkToolsAsSubmitted,
379
+ ]);
380
+
381
+ const client = geminiClient || mockConfig.getGeminiClient();
382
+
383
+ const { result, rerender } = renderHook(
384
+ (props: {
385
+ client: any;
386
+ history: HistoryItem[];
387
+ addItem: UseHistoryManagerReturn['addItem'];
388
+ config: Config;
389
+ onDebugMessage: (message: string) => void;
390
+ handleSlashCommand: (
391
+ cmd: PartListUnion,
392
+ ) => Promise<SlashCommandProcessorResult | false>;
393
+ shellModeActive: boolean;
394
+ loadedSettings: LoadedSettings;
395
+ toolCalls?: TrackedToolCall[]; // Allow passing updated toolCalls
396
+ }) => {
397
+ // Update the mock's return value if new toolCalls are passed in props
398
+ if (props.toolCalls) {
399
+ setToolCalls(props.toolCalls);
400
+ }
401
+ return useGeminiStream(
402
+ props.client,
403
+ props.history,
404
+ props.addItem,
405
+ props.config,
406
+ props.onDebugMessage,
407
+ props.handleSlashCommand,
408
+ props.shellModeActive,
409
+ () => 'vscode' as EditorType,
410
+ () => {},
411
+ () => Promise.resolve(),
412
+ false,
413
+ () => {},
414
+ () => {},
415
+ () => {},
416
+ );
417
+ },
418
+ {
419
+ initialProps: {
420
+ client,
421
+ history: [],
422
+ addItem: mockAddItem as unknown as UseHistoryManagerReturn['addItem'],
423
+ config: mockConfig,
424
+ onDebugMessage: mockOnDebugMessage,
425
+ handleSlashCommand: mockHandleSlashCommand as unknown as (
426
+ cmd: PartListUnion,
427
+ ) => Promise<SlashCommandProcessorResult | false>,
428
+ shellModeActive: false,
429
+ loadedSettings: mockLoadedSettings,
430
+ toolCalls: initialToolCalls,
431
+ },
432
+ },
433
+ );
434
+ return {
435
+ result,
436
+ rerender,
437
+ mockMarkToolsAsSubmitted,
438
+ mockSendMessageStream,
439
+ client,
440
+ };
441
+ };
442
+
443
+ it('should not submit tool responses if not all tool calls are completed', () => {
444
+ const toolCalls: TrackedToolCall[] = [
445
+ {
446
+ request: {
447
+ callId: 'call1',
448
+ name: 'tool1',
449
+ args: {},
450
+ isClientInitiated: false,
451
+ prompt_id: 'prompt-id-1',
452
+ },
453
+ status: 'success',
454
+ responseSubmittedToGemini: false,
455
+ response: {
456
+ callId: 'call1',
457
+ responseParts: [{ text: 'tool 1 response' }],
458
+ error: undefined,
459
+ errorType: undefined,
460
+ resultDisplay: 'Tool 1 success display',
461
+ },
462
+ tool: {
463
+ name: 'tool1',
464
+ displayName: 'tool1',
465
+ description: 'desc1',
466
+ build: vi.fn(),
467
+ } as any,
468
+ invocation: {
469
+ getDescription: () => `Mock description`,
470
+ } as unknown as AnyToolInvocation,
471
+ startTime: Date.now(),
472
+ endTime: Date.now(),
473
+ } as TrackedCompletedToolCall,
474
+ {
475
+ request: {
476
+ callId: 'call2',
477
+ name: 'tool2',
478
+ args: {},
479
+ prompt_id: 'prompt-id-1',
480
+ },
481
+ status: 'executing',
482
+ responseSubmittedToGemini: false,
483
+ tool: {
484
+ name: 'tool2',
485
+ displayName: 'tool2',
486
+ description: 'desc2',
487
+ build: vi.fn(),
488
+ } as any,
489
+ invocation: {
490
+ getDescription: () => `Mock description`,
491
+ } as unknown as AnyToolInvocation,
492
+ startTime: Date.now(),
493
+ liveOutput: '...',
494
+ } as TrackedExecutingToolCall,
495
+ ];
496
+
497
+ const { mockMarkToolsAsSubmitted, mockSendMessageStream } =
498
+ renderTestHook(toolCalls);
499
+
500
+ // Effect for submitting tool responses depends on toolCalls and isResponding
501
+ // isResponding is initially false, so the effect should run.
502
+
503
+ expect(mockMarkToolsAsSubmitted).not.toHaveBeenCalled();
504
+ expect(mockSendMessageStream).not.toHaveBeenCalled(); // submitQuery uses this
505
+ });
506
+
507
+ it('should submit tool responses when all tool calls are completed and ready', async () => {
508
+ const toolCall1ResponseParts: PartListUnion = [
509
+ { text: 'tool 1 final response' },
510
+ ];
511
+ const toolCall2ResponseParts: PartListUnion = [
512
+ { text: 'tool 2 final response' },
513
+ ];
514
+ const completedToolCalls: TrackedToolCall[] = [
515
+ {
516
+ request: {
517
+ callId: 'call1',
518
+ name: 'tool1',
519
+ args: {},
520
+ isClientInitiated: false,
521
+ prompt_id: 'prompt-id-2',
522
+ },
523
+ status: 'success',
524
+ responseSubmittedToGemini: false,
525
+ response: {
526
+ callId: 'call1',
527
+ responseParts: toolCall1ResponseParts,
528
+ errorType: undefined, // FIX: Added missing property
529
+ },
530
+ tool: {
531
+ displayName: 'MockTool',
532
+ },
533
+ invocation: {
534
+ getDescription: () => `Mock description`,
535
+ } as unknown as AnyToolInvocation,
536
+ } as TrackedCompletedToolCall,
537
+ {
538
+ request: {
539
+ callId: 'call2',
540
+ name: 'tool2',
541
+ args: {},
542
+ isClientInitiated: false,
543
+ prompt_id: 'prompt-id-2',
544
+ },
545
+ status: 'error',
546
+ responseSubmittedToGemini: false,
547
+ response: {
548
+ callId: 'call2',
549
+ responseParts: toolCall2ResponseParts,
550
+ errorType: ToolErrorType.UNHANDLED_EXCEPTION, // FIX: Added missing property
551
+ },
552
+ } as TrackedCompletedToolCall, // Treat error as a form of completion for submission
553
+ ];
554
+
555
+ // Capture the onComplete callback
556
+ let capturedOnComplete:
557
+ | ((completedTools: TrackedToolCall[]) => Promise<void>)
558
+ | null = null;
559
+
560
+ mockUseReactToolScheduler.mockImplementation((onComplete) => {
561
+ capturedOnComplete = onComplete;
562
+ return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
563
+ });
564
+
565
+ renderHook(() =>
566
+ useGeminiStream(
567
+ new MockedGeminiClientClass(mockConfig),
568
+ [],
569
+ mockAddItem,
570
+ mockConfig,
571
+ mockOnDebugMessage,
572
+ mockHandleSlashCommand,
573
+ false,
574
+ () => 'vscode' as EditorType,
575
+ () => {},
576
+ () => Promise.resolve(),
577
+ false,
578
+ () => {},
579
+ () => {},
580
+ () => {},
581
+ ),
582
+ );
583
+
584
+ // Trigger the onComplete callback with completed tools
585
+ await act(async () => {
586
+ if (capturedOnComplete) {
587
+ await capturedOnComplete(completedToolCalls);
588
+ }
589
+ });
590
+
591
+ await waitFor(() => {
592
+ expect(mockMarkToolsAsSubmitted).toHaveBeenCalledTimes(1);
593
+ expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
594
+ });
595
+
596
+ const expectedMergedResponse = mergePartListUnions([
597
+ toolCall1ResponseParts,
598
+ toolCall2ResponseParts,
599
+ ]);
600
+ expect(mockSendMessageStream).toHaveBeenCalledWith(
601
+ expectedMergedResponse,
602
+ expect.any(AbortSignal),
603
+ 'prompt-id-2',
604
+ );
605
+ });
606
+
607
+ it('should handle all tool calls being cancelled', async () => {
608
+ const cancelledToolCalls: TrackedToolCall[] = [
609
+ {
610
+ request: {
611
+ callId: '1',
612
+ name: 'testTool',
613
+ args: {},
614
+ isClientInitiated: false,
615
+ prompt_id: 'prompt-id-3',
616
+ },
617
+ status: 'cancelled',
618
+ response: {
619
+ callId: '1',
620
+ responseParts: [{ text: 'cancelled' }],
621
+ errorType: undefined, // FIX: Added missing property
622
+ },
623
+ responseSubmittedToGemini: false,
624
+ tool: {
625
+ displayName: 'mock tool',
626
+ },
627
+ invocation: {
628
+ getDescription: () => `Mock description`,
629
+ } as unknown as AnyToolInvocation,
630
+ } as TrackedCancelledToolCall,
631
+ ];
632
+ const client = new MockedGeminiClientClass(mockConfig);
633
+
634
+ // Capture the onComplete callback
635
+ let capturedOnComplete:
636
+ | ((completedTools: TrackedToolCall[]) => Promise<void>)
637
+ | null = null;
638
+
639
+ mockUseReactToolScheduler.mockImplementation((onComplete) => {
640
+ capturedOnComplete = onComplete;
641
+ return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
642
+ });
643
+
644
+ renderHook(() =>
645
+ useGeminiStream(
646
+ client,
647
+ [],
648
+ mockAddItem,
649
+ mockConfig,
650
+ mockOnDebugMessage,
651
+ mockHandleSlashCommand,
652
+ false,
653
+ () => 'vscode' as EditorType,
654
+ () => {},
655
+ () => Promise.resolve(),
656
+ false,
657
+ () => {},
658
+ () => {},
659
+ () => {},
660
+ ),
661
+ );
662
+
663
+ // Trigger the onComplete callback with cancelled tools
664
+ await act(async () => {
665
+ if (capturedOnComplete) {
666
+ await capturedOnComplete(cancelledToolCalls);
667
+ }
668
+ });
669
+
670
+ await waitFor(() => {
671
+ expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['1']);
672
+ expect(client.addHistory).toHaveBeenCalledWith({
673
+ role: 'user',
674
+ parts: [{ text: 'cancelled' }],
675
+ });
676
+ // Ensure we do NOT call back to the API
677
+ expect(mockSendMessageStream).not.toHaveBeenCalled();
678
+ });
679
+ });
680
+
681
+ it('should group multiple cancelled tool call responses into a single history entry', async () => {
682
+ const cancelledToolCall1: TrackedCancelledToolCall = {
683
+ request: {
684
+ callId: 'cancel-1',
685
+ name: 'toolA',
686
+ args: {},
687
+ isClientInitiated: false,
688
+ prompt_id: 'prompt-id-7',
689
+ },
690
+ tool: {
691
+ name: 'toolA',
692
+ displayName: 'toolA',
693
+ description: 'descA',
694
+ build: vi.fn(),
695
+ } as any,
696
+ invocation: {
697
+ getDescription: () => `Mock description`,
698
+ } as unknown as AnyToolInvocation,
699
+ status: 'cancelled',
700
+ response: {
701
+ callId: 'cancel-1',
702
+ responseParts: [
703
+ { functionResponse: { name: 'toolA', id: 'cancel-1' } },
704
+ ],
705
+ resultDisplay: undefined,
706
+ error: undefined,
707
+ errorType: undefined,
708
+ },
709
+ responseSubmittedToGemini: false,
710
+ };
711
+ const cancelledToolCall2: TrackedCancelledToolCall = {
712
+ request: {
713
+ callId: 'cancel-2',
714
+ name: 'toolB',
715
+ args: {},
716
+ isClientInitiated: false,
717
+ prompt_id: 'prompt-id-8',
718
+ },
719
+ tool: {
720
+ name: 'toolB',
721
+ displayName: 'toolB',
722
+ description: 'descB',
723
+ build: vi.fn(),
724
+ } as any,
725
+ invocation: {
726
+ getDescription: () => `Mock description`,
727
+ } as unknown as AnyToolInvocation,
728
+ status: 'cancelled',
729
+ response: {
730
+ callId: 'cancel-2',
731
+ responseParts: [
732
+ { functionResponse: { name: 'toolB', id: 'cancel-2' } },
733
+ ],
734
+ resultDisplay: undefined,
735
+ error: undefined,
736
+ errorType: undefined,
737
+ },
738
+ responseSubmittedToGemini: false,
739
+ };
740
+ const allCancelledTools = [cancelledToolCall1, cancelledToolCall2];
741
+ const client = new MockedGeminiClientClass(mockConfig);
742
+
743
+ let capturedOnComplete:
744
+ | ((completedTools: TrackedToolCall[]) => Promise<void>)
745
+ | null = null;
746
+
747
+ mockUseReactToolScheduler.mockImplementation((onComplete) => {
748
+ capturedOnComplete = onComplete;
749
+ return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
750
+ });
751
+
752
+ renderHook(() =>
753
+ useGeminiStream(
754
+ client,
755
+ [],
756
+ mockAddItem,
757
+ mockConfig,
758
+ mockOnDebugMessage,
759
+ mockHandleSlashCommand,
760
+ false,
761
+ () => 'vscode' as EditorType,
762
+ () => {},
763
+ () => Promise.resolve(),
764
+ false,
765
+ () => {},
766
+ () => {},
767
+ () => {},
768
+ ),
769
+ );
770
+
771
+ // Trigger the onComplete callback with multiple cancelled tools
772
+ await act(async () => {
773
+ if (capturedOnComplete) {
774
+ await capturedOnComplete(allCancelledTools);
775
+ }
776
+ });
777
+
778
+ await waitFor(() => {
779
+ // The tools should be marked as submitted locally
780
+ expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith([
781
+ 'cancel-1',
782
+ 'cancel-2',
783
+ ]);
784
+
785
+ // Crucially, addHistory should be called only ONCE
786
+ expect(client.addHistory).toHaveBeenCalledTimes(1);
787
+
788
+ // And that single call should contain BOTH function responses
789
+ expect(client.addHistory).toHaveBeenCalledWith({
790
+ role: 'user',
791
+ parts: [
792
+ ...(cancelledToolCall1.response.responseParts as Part[]),
793
+ ...(cancelledToolCall2.response.responseParts as Part[]),
794
+ ],
795
+ });
796
+
797
+ // No message should be sent back to the API for a turn with only cancellations
798
+ expect(mockSendMessageStream).not.toHaveBeenCalled();
799
+ });
800
+ });
801
+
802
+ it('should not flicker streaming state to Idle between tool completion and submission', async () => {
803
+ const toolCallResponseParts: PartListUnion = [
804
+ { text: 'tool 1 final response' },
805
+ ];
806
+
807
+ const initialToolCalls: TrackedToolCall[] = [
808
+ {
809
+ request: {
810
+ callId: 'call1',
811
+ name: 'tool1',
812
+ args: {},
813
+ isClientInitiated: false,
814
+ prompt_id: 'prompt-id-4',
815
+ },
816
+ status: 'executing',
817
+ responseSubmittedToGemini: false,
818
+ tool: {
819
+ name: 'tool1',
820
+ displayName: 'tool1',
821
+ description: 'desc',
822
+ build: vi.fn(),
823
+ } as any,
824
+ invocation: {
825
+ getDescription: () => `Mock description`,
826
+ } as unknown as AnyToolInvocation,
827
+ startTime: Date.now(),
828
+ } as TrackedExecutingToolCall,
829
+ ];
830
+
831
+ const completedToolCalls: TrackedToolCall[] = [
832
+ {
833
+ ...(initialToolCalls[0] as TrackedExecutingToolCall),
834
+ status: 'success',
835
+ response: {
836
+ callId: 'call1',
837
+ responseParts: toolCallResponseParts,
838
+ error: undefined,
839
+ errorType: undefined,
840
+ resultDisplay: 'Tool 1 success display',
841
+ },
842
+ endTime: Date.now(),
843
+ } as TrackedCompletedToolCall,
844
+ ];
845
+
846
+ // Capture the onComplete callback
847
+ let capturedOnComplete:
848
+ | ((completedTools: TrackedToolCall[]) => Promise<void>)
849
+ | null = null;
850
+ let currentToolCalls = initialToolCalls;
851
+
852
+ mockUseReactToolScheduler.mockImplementation((onComplete) => {
853
+ capturedOnComplete = onComplete;
854
+ return [
855
+ currentToolCalls,
856
+ mockScheduleToolCalls,
857
+ mockMarkToolsAsSubmitted,
858
+ ];
859
+ });
860
+
861
+ const { result, rerender } = renderHook(() =>
862
+ useGeminiStream(
863
+ new MockedGeminiClientClass(mockConfig),
864
+ [],
865
+ mockAddItem,
866
+ mockConfig,
867
+ mockOnDebugMessage,
868
+ mockHandleSlashCommand,
869
+ false,
870
+ () => 'vscode' as EditorType,
871
+ () => {},
872
+ () => Promise.resolve(),
873
+ false,
874
+ () => {},
875
+ () => {},
876
+ () => {},
877
+ ),
878
+ );
879
+
880
+ // 1. Initial state should be Responding because a tool is executing.
881
+ expect(result.current.streamingState).toBe(StreamingState.Responding);
882
+
883
+ // 2. Update the tool calls to completed state and rerender
884
+ currentToolCalls = completedToolCalls;
885
+ mockUseReactToolScheduler.mockImplementation((onComplete) => {
886
+ capturedOnComplete = onComplete;
887
+ return [
888
+ completedToolCalls,
889
+ mockScheduleToolCalls,
890
+ mockMarkToolsAsSubmitted,
891
+ ];
892
+ });
893
+
894
+ act(() => {
895
+ rerender();
896
+ });
897
+
898
+ // 3. The state should *still* be Responding, not Idle.
899
+ // This is because the completed tool's response has not been submitted yet.
900
+ expect(result.current.streamingState).toBe(StreamingState.Responding);
901
+
902
+ // 4. Trigger the onComplete callback to simulate tool completion
903
+ await act(async () => {
904
+ if (capturedOnComplete) {
905
+ await capturedOnComplete(completedToolCalls);
906
+ }
907
+ });
908
+
909
+ // 5. Wait for submitQuery to be called
910
+ await waitFor(() => {
911
+ expect(mockSendMessageStream).toHaveBeenCalledWith(
912
+ toolCallResponseParts,
913
+ expect.any(AbortSignal),
914
+ 'prompt-id-4',
915
+ );
916
+ });
917
+
918
+ // 6. After submission, the state should remain Responding until the stream completes.
919
+ expect(result.current.streamingState).toBe(StreamingState.Responding);
920
+ });
921
+
922
+ describe('User Cancellation', () => {
923
+ let keypressCallback: (key: any) => void;
924
+ const mockUseKeypress = useKeypress as Mock;
925
+
926
+ beforeEach(() => {
927
+ // Capture the callback passed to useKeypress
928
+ mockUseKeypress.mockImplementation((callback, options) => {
929
+ if (options.isActive) {
930
+ keypressCallback = callback;
931
+ } else {
932
+ keypressCallback = () => {};
933
+ }
934
+ });
935
+ });
936
+
937
+ const simulateEscapeKeyPress = () => {
938
+ act(() => {
939
+ keypressCallback({ name: 'escape' });
940
+ });
941
+ };
942
+
943
+ it('should cancel an in-progress stream when escape is pressed', async () => {
944
+ const mockStream = (async function* () {
945
+ yield { type: 'content', value: 'Part 1' };
946
+ // Keep the stream open
947
+ await new Promise(() => {});
948
+ })();
949
+ mockSendMessageStream.mockReturnValue(mockStream);
950
+
951
+ const { result } = renderTestHook();
952
+
953
+ // Start a query
954
+ await act(async () => {
955
+ result.current.submitQuery('test query');
956
+ });
957
+
958
+ // Wait for the first part of the response
959
+ await waitFor(() => {
960
+ expect(result.current.streamingState).toBe(StreamingState.Responding);
961
+ });
962
+
963
+ // Simulate escape key press
964
+ simulateEscapeKeyPress();
965
+
966
+ // Verify cancellation message is added
967
+ await waitFor(() => {
968
+ expect(mockAddItem).toHaveBeenCalledWith(
969
+ {
970
+ type: MessageType.INFO,
971
+ text: 'Request cancelled.',
972
+ },
973
+ expect.any(Number),
974
+ );
975
+ });
976
+
977
+ // Verify state is reset
978
+ expect(result.current.streamingState).toBe(StreamingState.Idle);
979
+ });
980
+
981
+ it('should call onCancelSubmit handler when escape is pressed', async () => {
982
+ const cancelSubmitSpy = vi.fn();
983
+ const mockStream = (async function* () {
984
+ yield { type: 'content', value: 'Part 1' };
985
+ // Keep the stream open
986
+ await new Promise(() => {});
987
+ })();
988
+ mockSendMessageStream.mockReturnValue(mockStream);
989
+
990
+ const { result } = renderHook(() =>
991
+ useGeminiStream(
992
+ mockConfig.getGeminiClient(),
993
+ [],
994
+ mockAddItem,
995
+ mockConfig,
996
+ mockOnDebugMessage,
997
+ mockHandleSlashCommand,
998
+ false,
999
+ () => 'vscode' as EditorType,
1000
+ () => {},
1001
+ () => Promise.resolve(),
1002
+ false,
1003
+ () => {},
1004
+ () => {},
1005
+ cancelSubmitSpy,
1006
+ ),
1007
+ );
1008
+
1009
+ // Start a query
1010
+ await act(async () => {
1011
+ result.current.submitQuery('test query');
1012
+ });
1013
+
1014
+ simulateEscapeKeyPress();
1015
+
1016
+ expect(cancelSubmitSpy).toHaveBeenCalled();
1017
+ });
1018
+
1019
+ it('should not do anything if escape is pressed when not responding', () => {
1020
+ const { result } = renderTestHook();
1021
+
1022
+ expect(result.current.streamingState).toBe(StreamingState.Idle);
1023
+
1024
+ // Simulate escape key press
1025
+ simulateEscapeKeyPress();
1026
+
1027
+ // No change should happen, no cancellation message
1028
+ expect(mockAddItem).not.toHaveBeenCalledWith(
1029
+ expect.objectContaining({
1030
+ text: 'Request cancelled.',
1031
+ }),
1032
+ expect.any(Number),
1033
+ );
1034
+ });
1035
+
1036
+ it('should prevent further processing after cancellation', async () => {
1037
+ let continueStream: () => void;
1038
+ const streamPromise = new Promise<void>((resolve) => {
1039
+ continueStream = resolve;
1040
+ });
1041
+
1042
+ const mockStream = (async function* () {
1043
+ yield { type: 'content', value: 'Initial' };
1044
+ await streamPromise; // Wait until we manually continue
1045
+ yield { type: 'content', value: ' Canceled' };
1046
+ })();
1047
+ mockSendMessageStream.mockReturnValue(mockStream);
1048
+
1049
+ const { result } = renderTestHook();
1050
+
1051
+ await act(async () => {
1052
+ result.current.submitQuery('long running query');
1053
+ });
1054
+
1055
+ await waitFor(() => {
1056
+ expect(result.current.streamingState).toBe(StreamingState.Responding);
1057
+ });
1058
+
1059
+ // Cancel the request
1060
+ simulateEscapeKeyPress();
1061
+
1062
+ // Allow the stream to continue
1063
+ act(() => {
1064
+ continueStream();
1065
+ });
1066
+
1067
+ // Wait a bit to see if the second part is processed
1068
+ await new Promise((resolve) => setTimeout(resolve, 50));
1069
+
1070
+ // The text should not have been updated with " Canceled"
1071
+ const lastCall = mockAddItem.mock.calls.find(
1072
+ (call) => call[0].type === 'gemini',
1073
+ );
1074
+ expect(lastCall?.[0].text).toBe('Initial');
1075
+
1076
+ // The final state should be idle after cancellation
1077
+ expect(result.current.streamingState).toBe(StreamingState.Idle);
1078
+ });
1079
+
1080
+ it('should not cancel if a tool call is in progress (not just responding)', async () => {
1081
+ const toolCalls: TrackedToolCall[] = [
1082
+ {
1083
+ request: { callId: 'call1', name: 'tool1', args: {} },
1084
+ status: 'executing',
1085
+ responseSubmittedToGemini: false,
1086
+ tool: {
1087
+ name: 'tool1',
1088
+ description: 'desc1',
1089
+ build: vi.fn().mockImplementation((_) => ({
1090
+ getDescription: () => `Mock description`,
1091
+ })),
1092
+ } as any,
1093
+ invocation: {
1094
+ getDescription: () => `Mock description`,
1095
+ },
1096
+ startTime: Date.now(),
1097
+ liveOutput: '...',
1098
+ } as TrackedExecutingToolCall,
1099
+ ];
1100
+
1101
+ const abortSpy = vi.spyOn(AbortController.prototype, 'abort');
1102
+ const { result } = renderTestHook(toolCalls);
1103
+
1104
+ // State is `Responding` because a tool is running
1105
+ expect(result.current.streamingState).toBe(StreamingState.Responding);
1106
+
1107
+ // Try to cancel
1108
+ simulateEscapeKeyPress();
1109
+
1110
+ // Nothing should happen because the state is not `Responding`
1111
+ expect(abortSpy).not.toHaveBeenCalled();
1112
+ });
1113
+ });
1114
+
1115
+ describe('Slash Command Handling', () => {
1116
+ it('should schedule a tool call when the command processor returns a schedule_tool action', async () => {
1117
+ const clientToolRequest: SlashCommandProcessorResult = {
1118
+ type: 'schedule_tool',
1119
+ toolName: 'save_memory',
1120
+ toolArgs: { fact: 'test fact' },
1121
+ };
1122
+ mockHandleSlashCommand.mockResolvedValue(clientToolRequest);
1123
+
1124
+ const { result } = renderTestHook();
1125
+
1126
+ await act(async () => {
1127
+ await result.current.submitQuery('/memory add "test fact"');
1128
+ });
1129
+
1130
+ await waitFor(() => {
1131
+ expect(mockScheduleToolCalls).toHaveBeenCalledWith(
1132
+ [
1133
+ expect.objectContaining({
1134
+ name: 'save_memory',
1135
+ args: { fact: 'test fact' },
1136
+ isClientInitiated: true,
1137
+ }),
1138
+ ],
1139
+ expect.any(AbortSignal),
1140
+ );
1141
+ expect(mockSendMessageStream).not.toHaveBeenCalled();
1142
+ });
1143
+ });
1144
+
1145
+ it('should stop processing and not call Gemini when a command is handled without a tool call', async () => {
1146
+ const uiOnlyCommandResult: SlashCommandProcessorResult = {
1147
+ type: 'handled',
1148
+ };
1149
+ mockHandleSlashCommand.mockResolvedValue(uiOnlyCommandResult);
1150
+
1151
+ const { result } = renderTestHook();
1152
+
1153
+ await act(async () => {
1154
+ await result.current.submitQuery('/help');
1155
+ });
1156
+
1157
+ await waitFor(() => {
1158
+ expect(mockHandleSlashCommand).toHaveBeenCalledWith('/help');
1159
+ expect(mockScheduleToolCalls).not.toHaveBeenCalled();
1160
+ expect(mockSendMessageStream).not.toHaveBeenCalled(); // No LLM call made
1161
+ });
1162
+ });
1163
+
1164
+ it('should call Gemini with prompt content when slash command returns a `submit_prompt` action', async () => {
1165
+ const customCommandResult: SlashCommandProcessorResult = {
1166
+ type: 'submit_prompt',
1167
+ content: 'This is the actual prompt from the command file.',
1168
+ };
1169
+ mockHandleSlashCommand.mockResolvedValue(customCommandResult);
1170
+
1171
+ const { result, mockSendMessageStream: localMockSendMessageStream } =
1172
+ renderTestHook();
1173
+
1174
+ await act(async () => {
1175
+ await result.current.submitQuery('/my-custom-command');
1176
+ });
1177
+
1178
+ await waitFor(() => {
1179
+ expect(mockHandleSlashCommand).toHaveBeenCalledWith(
1180
+ '/my-custom-command',
1181
+ );
1182
+
1183
+ expect(localMockSendMessageStream).not.toHaveBeenCalledWith(
1184
+ '/my-custom-command',
1185
+ expect.anything(),
1186
+ expect.anything(),
1187
+ );
1188
+
1189
+ expect(localMockSendMessageStream).toHaveBeenCalledWith(
1190
+ 'This is the actual prompt from the command file.',
1191
+ expect.any(AbortSignal),
1192
+ expect.any(String),
1193
+ );
1194
+
1195
+ expect(mockScheduleToolCalls).not.toHaveBeenCalled();
1196
+ });
1197
+ });
1198
+
1199
+ it('should correctly handle a submit_prompt action with empty content', async () => {
1200
+ const emptyPromptResult: SlashCommandProcessorResult = {
1201
+ type: 'submit_prompt',
1202
+ content: '',
1203
+ };
1204
+ mockHandleSlashCommand.mockResolvedValue(emptyPromptResult);
1205
+
1206
+ const { result, mockSendMessageStream: localMockSendMessageStream } =
1207
+ renderTestHook();
1208
+
1209
+ await act(async () => {
1210
+ await result.current.submitQuery('/emptycmd');
1211
+ });
1212
+
1213
+ await waitFor(() => {
1214
+ expect(mockHandleSlashCommand).toHaveBeenCalledWith('/emptycmd');
1215
+ expect(localMockSendMessageStream).toHaveBeenCalledWith(
1216
+ '',
1217
+ expect.any(AbortSignal),
1218
+ expect.any(String),
1219
+ );
1220
+ });
1221
+ });
1222
+ });
1223
+
1224
+ describe('Memory Refresh on save_memory', () => {
1225
+ it('should call performMemoryRefresh when a save_memory tool call completes successfully', async () => {
1226
+ const mockPerformMemoryRefresh = vi.fn();
1227
+ const completedToolCall: TrackedCompletedToolCall = {
1228
+ request: {
1229
+ callId: 'save-mem-call-1',
1230
+ name: 'save_memory',
1231
+ args: { fact: 'test' },
1232
+ isClientInitiated: true,
1233
+ prompt_id: 'prompt-id-6',
1234
+ },
1235
+ status: 'success',
1236
+ responseSubmittedToGemini: false,
1237
+ response: {
1238
+ callId: 'save-mem-call-1',
1239
+ responseParts: [{ text: 'Memory saved' }],
1240
+ resultDisplay: 'Success: Memory saved',
1241
+ error: undefined,
1242
+ errorType: undefined,
1243
+ },
1244
+ tool: {
1245
+ name: 'save_memory',
1246
+ displayName: 'save_memory',
1247
+ description: 'Saves memory',
1248
+ build: vi.fn(),
1249
+ } as any,
1250
+ invocation: {
1251
+ getDescription: () => `Mock description`,
1252
+ } as unknown as AnyToolInvocation,
1253
+ };
1254
+
1255
+ // Capture the onComplete callback
1256
+ let capturedOnComplete:
1257
+ | ((completedTools: TrackedToolCall[]) => Promise<void>)
1258
+ | null = null;
1259
+
1260
+ mockUseReactToolScheduler.mockImplementation((onComplete) => {
1261
+ capturedOnComplete = onComplete;
1262
+ return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
1263
+ });
1264
+
1265
+ renderHook(() =>
1266
+ useGeminiStream(
1267
+ new MockedGeminiClientClass(mockConfig),
1268
+ [],
1269
+ mockAddItem,
1270
+ mockConfig,
1271
+ mockOnDebugMessage,
1272
+ mockHandleSlashCommand,
1273
+ false,
1274
+ () => 'vscode' as EditorType,
1275
+ () => {},
1276
+ mockPerformMemoryRefresh,
1277
+ false,
1278
+ () => {},
1279
+ () => {},
1280
+ () => {},
1281
+ ),
1282
+ );
1283
+
1284
+ // Trigger the onComplete callback with the completed save_memory tool
1285
+ await act(async () => {
1286
+ if (capturedOnComplete) {
1287
+ await capturedOnComplete([completedToolCall]);
1288
+ }
1289
+ });
1290
+
1291
+ await waitFor(() => {
1292
+ expect(mockPerformMemoryRefresh).toHaveBeenCalledTimes(1);
1293
+ });
1294
+ });
1295
+ });
1296
+
1297
+ describe('Error Handling', () => {
1298
+ it('should call parseAndFormatApiError with the correct authType on stream initialization failure', async () => {
1299
+ // 1. Setup
1300
+ const mockError = new Error('Rate limit exceeded');
1301
+ const mockAuthType = AuthType.LOGIN_WITH_GOOGLE;
1302
+ mockParseAndFormatApiError.mockClear();
1303
+ mockSendMessageStream.mockReturnValue(
1304
+ (async function* () {
1305
+ yield { type: 'content', value: '' };
1306
+ throw mockError;
1307
+ })(),
1308
+ );
1309
+
1310
+ const testConfig = {
1311
+ ...mockConfig,
1312
+ getContentGeneratorConfig: vi.fn(() => ({
1313
+ authType: mockAuthType,
1314
+ })),
1315
+ getModel: vi.fn(() => 'gemini-2.5-pro'),
1316
+ } as unknown as Config;
1317
+
1318
+ const { result } = renderHook(() =>
1319
+ useGeminiStream(
1320
+ new MockedGeminiClientClass(testConfig),
1321
+ [],
1322
+ mockAddItem,
1323
+ testConfig,
1324
+ mockOnDebugMessage,
1325
+ mockHandleSlashCommand,
1326
+ false,
1327
+ () => 'vscode' as EditorType,
1328
+ () => {},
1329
+ () => Promise.resolve(),
1330
+ false,
1331
+ () => {},
1332
+ () => {},
1333
+ () => {},
1334
+ ),
1335
+ );
1336
+
1337
+ // 2. Action
1338
+ await act(async () => {
1339
+ await result.current.submitQuery('test query');
1340
+ });
1341
+
1342
+ // 3. Assertion
1343
+ await waitFor(() => {
1344
+ expect(mockParseAndFormatApiError).toHaveBeenCalledWith(
1345
+ 'Rate limit exceeded',
1346
+ mockAuthType,
1347
+ undefined,
1348
+ 'gemini-2.5-pro',
1349
+ 'gemini-2.5-flash',
1350
+ );
1351
+ });
1352
+ });
1353
+ });
1354
+
1355
+ describe('handleFinishedEvent', () => {
1356
+ it('should add info message for MAX_TOKENS finish reason', async () => {
1357
+ // Setup mock to return a stream with MAX_TOKENS finish reason
1358
+ mockSendMessageStream.mockReturnValue(
1359
+ (async function* () {
1360
+ yield {
1361
+ type: ServerGeminiEventType.Content,
1362
+ value: 'This is a truncated response...',
1363
+ };
1364
+ yield { type: ServerGeminiEventType.Finished, value: 'MAX_TOKENS' };
1365
+ })(),
1366
+ );
1367
+
1368
+ const { result } = renderHook(() =>
1369
+ useGeminiStream(
1370
+ new MockedGeminiClientClass(mockConfig),
1371
+ [],
1372
+ mockAddItem,
1373
+ mockConfig,
1374
+ mockOnDebugMessage,
1375
+ mockHandleSlashCommand,
1376
+ false,
1377
+ () => 'vscode' as EditorType,
1378
+ () => {},
1379
+ () => Promise.resolve(),
1380
+ false,
1381
+ () => {},
1382
+ () => {},
1383
+ () => {},
1384
+ ),
1385
+ );
1386
+
1387
+ // Submit a query
1388
+ await act(async () => {
1389
+ await result.current.submitQuery('Generate long text');
1390
+ });
1391
+
1392
+ // Check that the info message was added
1393
+ await waitFor(() => {
1394
+ expect(mockAddItem).toHaveBeenCalledWith(
1395
+ {
1396
+ type: 'info',
1397
+ text: '⚠️ Response truncated due to token limits.',
1398
+ },
1399
+ expect.any(Number),
1400
+ );
1401
+ });
1402
+ });
1403
+
1404
+ it('should not add message for STOP finish reason', async () => {
1405
+ // Setup mock to return a stream with STOP finish reason
1406
+ mockSendMessageStream.mockReturnValue(
1407
+ (async function* () {
1408
+ yield {
1409
+ type: ServerGeminiEventType.Content,
1410
+ value: 'Complete response',
1411
+ };
1412
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1413
+ })(),
1414
+ );
1415
+
1416
+ const { result } = renderHook(() =>
1417
+ useGeminiStream(
1418
+ new MockedGeminiClientClass(mockConfig),
1419
+ [],
1420
+ mockAddItem,
1421
+ mockConfig,
1422
+ mockOnDebugMessage,
1423
+ mockHandleSlashCommand,
1424
+ false,
1425
+ () => 'vscode' as EditorType,
1426
+ () => {},
1427
+ () => Promise.resolve(),
1428
+ false,
1429
+ () => {},
1430
+ () => {},
1431
+ () => {},
1432
+ ),
1433
+ );
1434
+
1435
+ // Submit a query
1436
+ await act(async () => {
1437
+ await result.current.submitQuery('Test normal completion');
1438
+ });
1439
+
1440
+ // Wait a bit to ensure no message is added
1441
+ await new Promise((resolve) => setTimeout(resolve, 100));
1442
+
1443
+ // Check that no info message was added for STOP
1444
+ const infoMessages = mockAddItem.mock.calls.filter(
1445
+ (call) => call[0].type === 'info',
1446
+ );
1447
+ expect(infoMessages).toHaveLength(0);
1448
+ });
1449
+
1450
+ it('should not add message for FINISH_REASON_UNSPECIFIED', async () => {
1451
+ // Setup mock to return a stream with FINISH_REASON_UNSPECIFIED
1452
+ mockSendMessageStream.mockReturnValue(
1453
+ (async function* () {
1454
+ yield {
1455
+ type: ServerGeminiEventType.Content,
1456
+ value: 'Response with unspecified finish',
1457
+ };
1458
+ yield {
1459
+ type: ServerGeminiEventType.Finished,
1460
+ value: 'FINISH_REASON_UNSPECIFIED',
1461
+ };
1462
+ })(),
1463
+ );
1464
+
1465
+ const { result } = renderHook(() =>
1466
+ useGeminiStream(
1467
+ new MockedGeminiClientClass(mockConfig),
1468
+ [],
1469
+ mockAddItem,
1470
+ mockConfig,
1471
+ mockOnDebugMessage,
1472
+ mockHandleSlashCommand,
1473
+ false,
1474
+ () => 'vscode' as EditorType,
1475
+ () => {},
1476
+ () => Promise.resolve(),
1477
+ false,
1478
+ () => {},
1479
+ () => {},
1480
+ () => {},
1481
+ ),
1482
+ );
1483
+
1484
+ // Submit a query
1485
+ await act(async () => {
1486
+ await result.current.submitQuery('Test unspecified finish');
1487
+ });
1488
+
1489
+ // Wait a bit to ensure no message is added
1490
+ await new Promise((resolve) => setTimeout(resolve, 100));
1491
+
1492
+ // Check that no info message was added
1493
+ const infoMessages = mockAddItem.mock.calls.filter(
1494
+ (call) => call[0].type === 'info',
1495
+ );
1496
+ expect(infoMessages).toHaveLength(0);
1497
+ });
1498
+
1499
+ it('should add appropriate messages for other finish reasons', async () => {
1500
+ const testCases = [
1501
+ {
1502
+ reason: 'SAFETY',
1503
+ message: '⚠️ Response stopped due to safety reasons.',
1504
+ },
1505
+ {
1506
+ reason: 'RECITATION',
1507
+ message: '⚠️ Response stopped due to recitation policy.',
1508
+ },
1509
+ {
1510
+ reason: 'LANGUAGE',
1511
+ message: '⚠️ Response stopped due to unsupported language.',
1512
+ },
1513
+ {
1514
+ reason: 'BLOCKLIST',
1515
+ message: '⚠️ Response stopped due to forbidden terms.',
1516
+ },
1517
+ {
1518
+ reason: 'PROHIBITED_CONTENT',
1519
+ message: '⚠️ Response stopped due to prohibited content.',
1520
+ },
1521
+ {
1522
+ reason: 'SPII',
1523
+ message:
1524
+ '⚠️ Response stopped due to sensitive personally identifiable information.',
1525
+ },
1526
+ { reason: 'OTHER', message: '⚠️ Response stopped for other reasons.' },
1527
+ {
1528
+ reason: 'MALFORMED_FUNCTION_CALL',
1529
+ message: '⚠️ Response stopped due to malformed function call.',
1530
+ },
1531
+ {
1532
+ reason: 'IMAGE_SAFETY',
1533
+ message: '⚠️ Response stopped due to image safety violations.',
1534
+ },
1535
+ {
1536
+ reason: 'UNEXPECTED_TOOL_CALL',
1537
+ message: '⚠️ Response stopped due to unexpected tool call.',
1538
+ },
1539
+ ];
1540
+
1541
+ for (const { reason, message } of testCases) {
1542
+ // Reset mocks for each test case
1543
+ mockAddItem.mockClear();
1544
+ mockSendMessageStream.mockReturnValue(
1545
+ (async function* () {
1546
+ yield {
1547
+ type: ServerGeminiEventType.Content,
1548
+ value: `Response for ${reason}`,
1549
+ };
1550
+ yield { type: ServerGeminiEventType.Finished, value: reason };
1551
+ })(),
1552
+ );
1553
+
1554
+ const { result } = renderHook(() =>
1555
+ useGeminiStream(
1556
+ new MockedGeminiClientClass(mockConfig),
1557
+ [],
1558
+ mockAddItem,
1559
+ mockConfig,
1560
+ mockOnDebugMessage,
1561
+ mockHandleSlashCommand,
1562
+ false,
1563
+ () => 'vscode' as EditorType,
1564
+ () => {},
1565
+ () => Promise.resolve(),
1566
+ false,
1567
+ () => {},
1568
+ () => {},
1569
+ () => {},
1570
+ ),
1571
+ );
1572
+
1573
+ await act(async () => {
1574
+ await result.current.submitQuery(`Test ${reason}`);
1575
+ });
1576
+
1577
+ await waitFor(() => {
1578
+ expect(mockAddItem).toHaveBeenCalledWith(
1579
+ {
1580
+ type: 'info',
1581
+ text: message,
1582
+ },
1583
+ expect.any(Number),
1584
+ );
1585
+ });
1586
+ }
1587
+ });
1588
+ });
1589
+
1590
+ describe('Thought Reset', () => {
1591
+ it('should reset thought to null when starting a new prompt', async () => {
1592
+ // First, simulate a response with a thought
1593
+ mockSendMessageStream.mockReturnValue(
1594
+ (async function* () {
1595
+ yield {
1596
+ type: ServerGeminiEventType.Thought,
1597
+ value: {
1598
+ subject: 'Previous thought',
1599
+ description: 'Old description',
1600
+ },
1601
+ };
1602
+ yield {
1603
+ type: ServerGeminiEventType.Content,
1604
+ value: 'Some response content',
1605
+ };
1606
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1607
+ })(),
1608
+ );
1609
+
1610
+ const { result } = renderHook(() =>
1611
+ useGeminiStream(
1612
+ new MockedGeminiClientClass(mockConfig),
1613
+ [],
1614
+ mockAddItem,
1615
+ mockConfig,
1616
+ mockOnDebugMessage,
1617
+ mockHandleSlashCommand,
1618
+ false,
1619
+ () => 'vscode' as EditorType,
1620
+ () => {},
1621
+ () => Promise.resolve(),
1622
+ false,
1623
+ () => {},
1624
+ () => {},
1625
+ () => {},
1626
+ ),
1627
+ );
1628
+
1629
+ // Submit first query to set a thought
1630
+ await act(async () => {
1631
+ await result.current.submitQuery('First query');
1632
+ });
1633
+
1634
+ // Wait for the first response to complete
1635
+ await waitFor(() => {
1636
+ expect(mockAddItem).toHaveBeenCalledWith(
1637
+ expect.objectContaining({
1638
+ type: 'gemini',
1639
+ text: 'Some response content',
1640
+ }),
1641
+ expect.any(Number),
1642
+ );
1643
+ });
1644
+
1645
+ // Now simulate a new response without a thought
1646
+ mockSendMessageStream.mockReturnValue(
1647
+ (async function* () {
1648
+ yield {
1649
+ type: ServerGeminiEventType.Content,
1650
+ value: 'New response content',
1651
+ };
1652
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1653
+ })(),
1654
+ );
1655
+
1656
+ // Submit second query - thought should be reset
1657
+ await act(async () => {
1658
+ await result.current.submitQuery('Second query');
1659
+ });
1660
+
1661
+ // The thought should be reset to null when starting the new prompt
1662
+ // We can verify this by checking that the LoadingIndicator would not show the previous thought
1663
+ // The actual thought state is internal to the hook, but we can verify the behavior
1664
+ // by ensuring the second response doesn't show the previous thought
1665
+ await waitFor(() => {
1666
+ expect(mockAddItem).toHaveBeenCalledWith(
1667
+ expect.objectContaining({
1668
+ type: 'gemini',
1669
+ text: 'New response content',
1670
+ }),
1671
+ expect.any(Number),
1672
+ );
1673
+ });
1674
+ });
1675
+
1676
+ it('should reset thought to null when user cancels', async () => {
1677
+ // Mock a stream that yields a thought then gets cancelled
1678
+ mockSendMessageStream.mockReturnValue(
1679
+ (async function* () {
1680
+ yield {
1681
+ type: ServerGeminiEventType.Thought,
1682
+ value: { subject: 'Some thought', description: 'Description' },
1683
+ };
1684
+ yield { type: ServerGeminiEventType.UserCancelled };
1685
+ })(),
1686
+ );
1687
+
1688
+ const { result } = renderHook(() =>
1689
+ useGeminiStream(
1690
+ new MockedGeminiClientClass(mockConfig),
1691
+ [],
1692
+ mockAddItem,
1693
+ mockConfig,
1694
+ mockOnDebugMessage,
1695
+ mockHandleSlashCommand,
1696
+ false,
1697
+ () => 'vscode' as EditorType,
1698
+ () => {},
1699
+ () => Promise.resolve(),
1700
+ false,
1701
+ () => {},
1702
+ () => {},
1703
+ () => {},
1704
+ ),
1705
+ );
1706
+
1707
+ // Submit query
1708
+ await act(async () => {
1709
+ await result.current.submitQuery('Test query');
1710
+ });
1711
+
1712
+ // Verify cancellation message was added
1713
+ await waitFor(() => {
1714
+ expect(mockAddItem).toHaveBeenCalledWith(
1715
+ expect.objectContaining({
1716
+ type: 'info',
1717
+ text: 'User cancelled the request.',
1718
+ }),
1719
+ expect.any(Number),
1720
+ );
1721
+ });
1722
+
1723
+ // Verify state is reset to idle
1724
+ expect(result.current.streamingState).toBe(StreamingState.Idle);
1725
+ });
1726
+
1727
+ it('should reset thought to null when there is an error', async () => {
1728
+ // Mock a stream that yields a thought then encounters an error
1729
+ mockSendMessageStream.mockReturnValue(
1730
+ (async function* () {
1731
+ yield {
1732
+ type: ServerGeminiEventType.Thought,
1733
+ value: { subject: 'Some thought', description: 'Description' },
1734
+ };
1735
+ yield {
1736
+ type: ServerGeminiEventType.Error,
1737
+ value: { error: { message: 'Test error' } },
1738
+ };
1739
+ })(),
1740
+ );
1741
+
1742
+ const { result } = renderHook(() =>
1743
+ useGeminiStream(
1744
+ new MockedGeminiClientClass(mockConfig),
1745
+ [],
1746
+ mockAddItem,
1747
+ mockConfig,
1748
+ mockOnDebugMessage,
1749
+ mockHandleSlashCommand,
1750
+ false,
1751
+ () => 'vscode' as EditorType,
1752
+ () => {},
1753
+ () => Promise.resolve(),
1754
+ false,
1755
+ () => {},
1756
+ () => {},
1757
+ () => {},
1758
+ ),
1759
+ );
1760
+
1761
+ // Submit query
1762
+ await act(async () => {
1763
+ await result.current.submitQuery('Test query');
1764
+ });
1765
+
1766
+ // Verify error message was added
1767
+ await waitFor(() => {
1768
+ expect(mockAddItem).toHaveBeenCalledWith(
1769
+ expect.objectContaining({
1770
+ type: 'error',
1771
+ }),
1772
+ expect.any(Number),
1773
+ );
1774
+ });
1775
+
1776
+ // Verify parseAndFormatApiError was called
1777
+ expect(mockParseAndFormatApiError).toHaveBeenCalledWith(
1778
+ { message: 'Test error' },
1779
+ expect.any(String),
1780
+ undefined,
1781
+ 'gemini-2.5-pro',
1782
+ 'gemini-2.5-flash',
1783
+ );
1784
+ });
1785
+ });
1786
+
1787
+ describe('Concurrent Execution Prevention', () => {
1788
+ it('should prevent concurrent submitQuery calls', async () => {
1789
+ let resolveFirstCall!: () => void;
1790
+ let resolveSecondCall!: () => void;
1791
+
1792
+ const firstCallPromise = new Promise<void>((resolve) => {
1793
+ resolveFirstCall = resolve;
1794
+ });
1795
+
1796
+ const secondCallPromise = new Promise<void>((resolve) => {
1797
+ resolveSecondCall = resolve;
1798
+ });
1799
+
1800
+ // Mock a long-running stream for the first call
1801
+ const firstStream = (async function* () {
1802
+ yield {
1803
+ type: ServerGeminiEventType.Content,
1804
+ value: 'First call content',
1805
+ };
1806
+ await firstCallPromise; // Wait until we manually resolve
1807
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1808
+ })();
1809
+
1810
+ // Mock a stream for the second call (should not be used)
1811
+ const secondStream = (async function* () {
1812
+ yield {
1813
+ type: ServerGeminiEventType.Content,
1814
+ value: 'Second call content',
1815
+ };
1816
+ await secondCallPromise;
1817
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1818
+ })();
1819
+
1820
+ let callCount = 0;
1821
+ mockSendMessageStream.mockImplementation(() => {
1822
+ callCount++;
1823
+ if (callCount === 1) {
1824
+ return firstStream;
1825
+ } else {
1826
+ return secondStream;
1827
+ }
1828
+ });
1829
+
1830
+ const { result } = renderTestHook();
1831
+
1832
+ // Start first call
1833
+ const firstCallResult = act(async () => {
1834
+ await result.current.submitQuery('First query');
1835
+ });
1836
+
1837
+ // Wait a bit to ensure first call has started
1838
+ await new Promise((resolve) => setTimeout(resolve, 10));
1839
+
1840
+ // Try to start second call while first is still running
1841
+ const secondCallResult = act(async () => {
1842
+ await result.current.submitQuery('Second query');
1843
+ });
1844
+
1845
+ // Resolve both calls
1846
+ resolveFirstCall();
1847
+ resolveSecondCall();
1848
+
1849
+ await Promise.all([firstCallResult, secondCallResult]);
1850
+
1851
+ // Verify only one call was made to sendMessageStream
1852
+ expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
1853
+ expect(mockSendMessageStream).toHaveBeenCalledWith(
1854
+ 'First query',
1855
+ expect.any(AbortSignal),
1856
+ expect.any(String),
1857
+ );
1858
+
1859
+ // Verify only the first query was added to history
1860
+ const userMessages = mockAddItem.mock.calls.filter(
1861
+ (call) => call[0].type === MessageType.USER,
1862
+ );
1863
+ expect(userMessages).toHaveLength(1);
1864
+ expect(userMessages[0][0].text).toBe('First query');
1865
+ });
1866
+
1867
+ it('should allow subsequent calls after first call completes', async () => {
1868
+ // Mock streams that complete immediately
1869
+ mockSendMessageStream
1870
+ .mockReturnValueOnce(
1871
+ (async function* () {
1872
+ yield {
1873
+ type: ServerGeminiEventType.Content,
1874
+ value: 'First response',
1875
+ };
1876
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1877
+ })(),
1878
+ )
1879
+ .mockReturnValueOnce(
1880
+ (async function* () {
1881
+ yield {
1882
+ type: ServerGeminiEventType.Content,
1883
+ value: 'Second response',
1884
+ };
1885
+ yield { type: ServerGeminiEventType.Finished, value: 'STOP' };
1886
+ })(),
1887
+ );
1888
+
1889
+ const { result } = renderTestHook();
1890
+
1891
+ // First call
1892
+ await act(async () => {
1893
+ await result.current.submitQuery('First query');
1894
+ });
1895
+
1896
+ // Second call after first completes
1897
+ await act(async () => {
1898
+ await result.current.submitQuery('Second query');
1899
+ });
1900
+
1901
+ // Both calls should have been made
1902
+ expect(mockSendMessageStream).toHaveBeenCalledTimes(2);
1903
+ expect(mockSendMessageStream).toHaveBeenNthCalledWith(
1904
+ 1,
1905
+ 'First query',
1906
+ expect.any(AbortSignal),
1907
+ expect.any(String),
1908
+ );
1909
+ expect(mockSendMessageStream).toHaveBeenNthCalledWith(
1910
+ 2,
1911
+ 'Second query',
1912
+ expect.any(AbortSignal),
1913
+ expect.any(String),
1914
+ );
1915
+ });
1916
+
1917
+ it('should reset execution flag even when query preparation fails', async () => {
1918
+ const { result } = renderTestHook();
1919
+
1920
+ // First call with empty query (should fail in preparation)
1921
+ await act(async () => {
1922
+ await result.current.submitQuery(' '); // Empty trimmed query
1923
+ });
1924
+
1925
+ // Second call should work normally
1926
+ await act(async () => {
1927
+ await result.current.submitQuery('Second query');
1928
+ });
1929
+
1930
+ // Verify that only the second call was made (empty query is filtered out)
1931
+ expect(mockSendMessageStream).toHaveBeenCalledTimes(1);
1932
+ expect(mockSendMessageStream).toHaveBeenCalledWith(
1933
+ 'Second query',
1934
+ expect.any(AbortSignal),
1935
+ expect.any(String),
1936
+ );
1937
+ });
1938
+ });
1939
+
1940
+ it('should process @include commands, adding user turn after processing to prevent race conditions', async () => {
1941
+ const rawQuery = '@include file.txt Summarize this.';
1942
+ const processedQueryParts = [
1943
+ { text: 'Summarize this with content from @file.txt' },
1944
+ { text: 'File content...' },
1945
+ ];
1946
+ const userMessageTimestamp = Date.now();
1947
+ vi.spyOn(Date, 'now').mockReturnValue(userMessageTimestamp);
1948
+
1949
+ handleAtCommandSpy.mockResolvedValue({
1950
+ processedQuery: processedQueryParts,
1951
+ shouldProceed: true,
1952
+ });
1953
+
1954
+ const { result } = renderHook(() =>
1955
+ useGeminiStream(
1956
+ mockConfig.getGeminiClient() as GeminiClient,
1957
+ [],
1958
+ mockAddItem,
1959
+ mockConfig,
1960
+ mockOnDebugMessage,
1961
+ mockHandleSlashCommand,
1962
+ false,
1963
+ vi.fn(),
1964
+ vi.fn(),
1965
+ vi.fn(),
1966
+ false,
1967
+ vi.fn(),
1968
+ vi.fn(),
1969
+ vi.fn(),
1970
+ ),
1971
+ );
1972
+
1973
+ await act(async () => {
1974
+ await result.current.submitQuery(rawQuery);
1975
+ });
1976
+
1977
+ expect(handleAtCommandSpy).toHaveBeenCalledWith(
1978
+ expect.objectContaining({
1979
+ query: rawQuery,
1980
+ }),
1981
+ );
1982
+
1983
+ expect(mockAddItem).toHaveBeenCalledWith(
1984
+ {
1985
+ type: MessageType.USER,
1986
+ text: rawQuery,
1987
+ },
1988
+ userMessageTimestamp,
1989
+ );
1990
+
1991
+ // FIX: This expectation now correctly matches the actual function call signature.
1992
+ expect(mockSendMessageStream).toHaveBeenCalledWith(
1993
+ processedQueryParts, // Argument 1: The parts array directly
1994
+ expect.any(AbortSignal), // Argument 2: An AbortSignal
1995
+ expect.any(String), // Argument 3: The prompt_id string
1996
+ );
1997
+ });
1998
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useGeminiStream.ts ADDED
@@ -0,0 +1,1017 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { type Part, type PartListUnion, FinishReason } from '@google/genai';
8
+ import {
9
+ Config,
10
+ ServerGeminiContentEvent as ContentEvent,
11
+ DEFAULT_GEMINI_FLASH_MODEL,
12
+ EditorType,
13
+ ServerGeminiErrorEvent as ErrorEvent,
14
+ GeminiClient,
15
+ ServerGeminiStreamEvent as GeminiEvent,
16
+ getErrorMessage,
17
+ GitService,
18
+ isNodeError,
19
+ logUserPrompt,
20
+ MessageSenderType,
21
+ parseAndFormatApiError,
22
+ ServerGeminiChatCompressedEvent,
23
+ GeminiEventType as ServerGeminiEventType,
24
+ ServerGeminiFinishedEvent,
25
+ ThoughtSummary,
26
+ ToolCallRequestInfo,
27
+ UnauthorizedError,
28
+ UserPromptEvent,
29
+ } from '@qwen-code/qwen-code-core';
30
+ import { promises as fs } from 'fs';
31
+ import path from 'path';
32
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
33
+ import { useSessionStats } from '../contexts/SessionContext.js';
34
+ import {
35
+ HistoryItem,
36
+ HistoryItemToolGroup,
37
+ HistoryItemWithoutId,
38
+ MessageType,
39
+ SlashCommandProcessorResult,
40
+ StreamingState,
41
+ ToolCallStatus,
42
+ } from '../types.js';
43
+ import { isAtCommand } from '../utils/commandUtils.js';
44
+ import { findLastSafeSplitPoint } from '../utils/markdownUtilities.js';
45
+ import { handleAtCommand } from './atCommandProcessor.js';
46
+ import { useShellCommandProcessor } from './shellCommandProcessor.js';
47
+ import { UseHistoryManagerReturn } from './useHistoryManager.js';
48
+ import { useKeypress } from './useKeypress.js';
49
+ import { useLogger } from './useLogger.js';
50
+ import {
51
+ mapToDisplay as mapTrackedToolCallsToDisplay,
52
+ TrackedCancelledToolCall,
53
+ TrackedCompletedToolCall,
54
+ TrackedToolCall,
55
+ useReactToolScheduler,
56
+ } from './useReactToolScheduler.js';
57
+ import { useStateAndRef } from './useStateAndRef.js';
58
+
59
+ export function mergePartListUnions(list: PartListUnion[]): PartListUnion {
60
+ const resultParts: PartListUnion = [];
61
+ for (const item of list) {
62
+ if (Array.isArray(item)) {
63
+ resultParts.push(...item);
64
+ } else {
65
+ resultParts.push(item);
66
+ }
67
+ }
68
+ return resultParts;
69
+ }
70
+
71
+ enum StreamProcessingStatus {
72
+ Completed,
73
+ UserCancelled,
74
+ Error,
75
+ }
76
+
77
+ /**
78
+ * Manages the Gemini stream, including user input, command processing,
79
+ * API interaction, and tool call lifecycle.
80
+ */
81
+ export const useGeminiStream = (
82
+ geminiClient: GeminiClient,
83
+ history: HistoryItem[],
84
+ addItem: UseHistoryManagerReturn['addItem'],
85
+ config: Config,
86
+ onDebugMessage: (message: string) => void,
87
+ handleSlashCommand: (
88
+ cmd: PartListUnion,
89
+ ) => Promise<SlashCommandProcessorResult | false>,
90
+ shellModeActive: boolean,
91
+ getPreferredEditor: () => EditorType | undefined,
92
+ onAuthError: () => void,
93
+ performMemoryRefresh: () => Promise<void>,
94
+ modelSwitchedFromQuotaError: boolean,
95
+ setModelSwitchedFromQuotaError: React.Dispatch<React.SetStateAction<boolean>>,
96
+ onEditorClose: () => void,
97
+ onCancelSubmit: () => void,
98
+ ) => {
99
+ const [initError, setInitError] = useState<string | null>(null);
100
+ const abortControllerRef = useRef<AbortController | null>(null);
101
+ const turnCancelledRef = useRef(false);
102
+ const isSubmittingQueryRef = useRef(false);
103
+ const [isResponding, setIsResponding] = useState<boolean>(false);
104
+ const [thought, setThought] = useState<ThoughtSummary | null>(null);
105
+ const [pendingHistoryItemRef, setPendingHistoryItem] =
106
+ useStateAndRef<HistoryItemWithoutId | null>(null);
107
+ const processedMemoryToolsRef = useRef<Set<string>>(new Set());
108
+ const { startNewPrompt, getPromptCount } = useSessionStats();
109
+ const logger = useLogger();
110
+ const gitService = useMemo(() => {
111
+ if (!config.getProjectRoot()) {
112
+ return;
113
+ }
114
+ return new GitService(config.getProjectRoot());
115
+ }, [config]);
116
+
117
+ const [toolCalls, scheduleToolCalls, markToolsAsSubmitted] =
118
+ useReactToolScheduler(
119
+ async (completedToolCallsFromScheduler) => {
120
+ // This onComplete is called when ALL scheduled tools for a given batch are done.
121
+ if (completedToolCallsFromScheduler.length > 0) {
122
+ // Add the final state of these tools to the history for display.
123
+ addItem(
124
+ mapTrackedToolCallsToDisplay(
125
+ completedToolCallsFromScheduler as TrackedToolCall[],
126
+ ),
127
+ Date.now(),
128
+ );
129
+
130
+ // Handle tool response submission immediately when tools complete
131
+ await handleCompletedTools(
132
+ completedToolCallsFromScheduler as TrackedToolCall[],
133
+ );
134
+ }
135
+ },
136
+ config,
137
+ setPendingHistoryItem,
138
+ getPreferredEditor,
139
+ onEditorClose,
140
+ );
141
+
142
+ const pendingToolCallGroupDisplay = useMemo(
143
+ () =>
144
+ toolCalls.length ? mapTrackedToolCallsToDisplay(toolCalls) : undefined,
145
+ [toolCalls],
146
+ );
147
+
148
+ const loopDetectedRef = useRef(false);
149
+
150
+ const onExec = useCallback(async (done: Promise<void>) => {
151
+ setIsResponding(true);
152
+ await done;
153
+ setIsResponding(false);
154
+ }, []);
155
+ const { handleShellCommand } = useShellCommandProcessor(
156
+ addItem,
157
+ setPendingHistoryItem,
158
+ onExec,
159
+ onDebugMessage,
160
+ config,
161
+ geminiClient,
162
+ );
163
+
164
+ const streamingState = useMemo(() => {
165
+ if (toolCalls.some((tc) => tc.status === 'awaiting_approval')) {
166
+ return StreamingState.WaitingForConfirmation;
167
+ }
168
+ if (
169
+ isResponding ||
170
+ toolCalls.some(
171
+ (tc) =>
172
+ tc.status === 'executing' ||
173
+ tc.status === 'scheduled' ||
174
+ tc.status === 'validating' ||
175
+ ((tc.status === 'success' ||
176
+ tc.status === 'error' ||
177
+ tc.status === 'cancelled') &&
178
+ !(tc as TrackedCompletedToolCall | TrackedCancelledToolCall)
179
+ .responseSubmittedToGemini),
180
+ )
181
+ ) {
182
+ return StreamingState.Responding;
183
+ }
184
+ return StreamingState.Idle;
185
+ }, [isResponding, toolCalls]);
186
+
187
+ const cancelOngoingRequest = useCallback(() => {
188
+ if (streamingState !== StreamingState.Responding) {
189
+ return;
190
+ }
191
+ if (turnCancelledRef.current) {
192
+ return;
193
+ }
194
+ turnCancelledRef.current = true;
195
+ isSubmittingQueryRef.current = false;
196
+ abortControllerRef.current?.abort();
197
+ if (pendingHistoryItemRef.current) {
198
+ addItem(pendingHistoryItemRef.current, Date.now());
199
+ }
200
+ addItem(
201
+ {
202
+ type: MessageType.INFO,
203
+ text: 'Request cancelled.',
204
+ },
205
+ Date.now(),
206
+ );
207
+ setPendingHistoryItem(null);
208
+ onCancelSubmit();
209
+ setIsResponding(false);
210
+ }, [
211
+ streamingState,
212
+ addItem,
213
+ setPendingHistoryItem,
214
+ onCancelSubmit,
215
+ pendingHistoryItemRef,
216
+ ]);
217
+
218
+ useKeypress(
219
+ (key) => {
220
+ if (key.name === 'escape') {
221
+ cancelOngoingRequest();
222
+ }
223
+ },
224
+ { isActive: streamingState === StreamingState.Responding },
225
+ );
226
+
227
+ const prepareQueryForGemini = useCallback(
228
+ async (
229
+ query: PartListUnion,
230
+ userMessageTimestamp: number,
231
+ abortSignal: AbortSignal,
232
+ prompt_id: string,
233
+ ): Promise<{
234
+ queryToSend: PartListUnion | null;
235
+ shouldProceed: boolean;
236
+ }> => {
237
+ if (turnCancelledRef.current) {
238
+ return { queryToSend: null, shouldProceed: false };
239
+ }
240
+ if (typeof query === 'string' && query.trim().length === 0) {
241
+ return { queryToSend: null, shouldProceed: false };
242
+ }
243
+
244
+ let localQueryToSendToGemini: PartListUnion | null = null;
245
+
246
+ if (typeof query === 'string') {
247
+ const trimmedQuery = query.trim();
248
+ logUserPrompt(
249
+ config,
250
+ new UserPromptEvent(
251
+ trimmedQuery.length,
252
+ prompt_id,
253
+ config.getContentGeneratorConfig()?.authType,
254
+ trimmedQuery,
255
+ ),
256
+ );
257
+ onDebugMessage(`User query: '${trimmedQuery}'`);
258
+ await logger?.logMessage(MessageSenderType.USER, trimmedQuery);
259
+
260
+ // Handle UI-only commands first
261
+ const slashCommandResult = await handleSlashCommand(trimmedQuery);
262
+
263
+ if (slashCommandResult) {
264
+ switch (slashCommandResult.type) {
265
+ case 'schedule_tool': {
266
+ const { toolName, toolArgs } = slashCommandResult;
267
+ const toolCallRequest: ToolCallRequestInfo = {
268
+ callId: `${toolName}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
269
+ name: toolName,
270
+ args: toolArgs,
271
+ isClientInitiated: true,
272
+ prompt_id,
273
+ };
274
+ scheduleToolCalls([toolCallRequest], abortSignal);
275
+ return { queryToSend: null, shouldProceed: false };
276
+ }
277
+ case 'submit_prompt': {
278
+ localQueryToSendToGemini = slashCommandResult.content;
279
+
280
+ return {
281
+ queryToSend: localQueryToSendToGemini,
282
+ shouldProceed: true,
283
+ };
284
+ }
285
+ case 'handled': {
286
+ return { queryToSend: null, shouldProceed: false };
287
+ }
288
+ default: {
289
+ const unreachable: never = slashCommandResult;
290
+ throw new Error(
291
+ `Unhandled slash command result type: ${unreachable}`,
292
+ );
293
+ }
294
+ }
295
+ }
296
+
297
+ if (shellModeActive && handleShellCommand(trimmedQuery, abortSignal)) {
298
+ return { queryToSend: null, shouldProceed: false };
299
+ }
300
+
301
+ // Handle @-commands (which might involve tool calls)
302
+ if (isAtCommand(trimmedQuery)) {
303
+ const atCommandResult = await handleAtCommand({
304
+ query: trimmedQuery,
305
+ config,
306
+ addItem,
307
+ onDebugMessage,
308
+ messageId: userMessageTimestamp,
309
+ signal: abortSignal,
310
+ });
311
+
312
+ // Add user's turn after @ command processing is done.
313
+ addItem(
314
+ { type: MessageType.USER, text: trimmedQuery },
315
+ userMessageTimestamp,
316
+ );
317
+
318
+ if (!atCommandResult.shouldProceed) {
319
+ return { queryToSend: null, shouldProceed: false };
320
+ }
321
+ localQueryToSendToGemini = atCommandResult.processedQuery;
322
+ } else {
323
+ // Normal query for Gemini
324
+ addItem(
325
+ { type: MessageType.USER, text: trimmedQuery },
326
+ userMessageTimestamp,
327
+ );
328
+ localQueryToSendToGemini = trimmedQuery;
329
+ }
330
+ } else {
331
+ // It's a function response (PartListUnion that isn't a string)
332
+ localQueryToSendToGemini = query;
333
+ }
334
+
335
+ if (localQueryToSendToGemini === null) {
336
+ onDebugMessage(
337
+ 'Query processing resulted in null, not sending to Gemini.',
338
+ );
339
+ return { queryToSend: null, shouldProceed: false };
340
+ }
341
+ return { queryToSend: localQueryToSendToGemini, shouldProceed: true };
342
+ },
343
+ [
344
+ config,
345
+ addItem,
346
+ onDebugMessage,
347
+ handleShellCommand,
348
+ handleSlashCommand,
349
+ logger,
350
+ shellModeActive,
351
+ scheduleToolCalls,
352
+ ],
353
+ );
354
+
355
+ // --- Stream Event Handlers ---
356
+
357
+ const handleContentEvent = useCallback(
358
+ (
359
+ eventValue: ContentEvent['value'],
360
+ currentGeminiMessageBuffer: string,
361
+ userMessageTimestamp: number,
362
+ ): string => {
363
+ if (turnCancelledRef.current) {
364
+ // Prevents additional output after a user initiated cancel.
365
+ return '';
366
+ }
367
+ let newGeminiMessageBuffer = currentGeminiMessageBuffer + eventValue;
368
+ if (
369
+ pendingHistoryItemRef.current?.type !== 'gemini' &&
370
+ pendingHistoryItemRef.current?.type !== 'gemini_content'
371
+ ) {
372
+ if (pendingHistoryItemRef.current) {
373
+ addItem(pendingHistoryItemRef.current, userMessageTimestamp);
374
+ }
375
+ setPendingHistoryItem({ type: 'gemini', text: '' });
376
+ newGeminiMessageBuffer = eventValue;
377
+ }
378
+ // Split large messages for better rendering performance. Ideally,
379
+ // we should maximize the amount of output sent to <Static />.
380
+ const splitPoint = findLastSafeSplitPoint(newGeminiMessageBuffer);
381
+ if (splitPoint === newGeminiMessageBuffer.length) {
382
+ // Update the existing message with accumulated content
383
+ setPendingHistoryItem((item) => ({
384
+ type: item?.type as 'gemini' | 'gemini_content',
385
+ text: newGeminiMessageBuffer,
386
+ }));
387
+ } else {
388
+ // This indicates that we need to split up this Gemini Message.
389
+ // Splitting a message is primarily a performance consideration. There is a
390
+ // <Static> component at the root of App.tsx which takes care of rendering
391
+ // content statically or dynamically. Everything but the last message is
392
+ // treated as static in order to prevent re-rendering an entire message history
393
+ // multiple times per-second (as streaming occurs). Prior to this change you'd
394
+ // see heavy flickering of the terminal. This ensures that larger messages get
395
+ // broken up so that there are more "statically" rendered.
396
+ const beforeText = newGeminiMessageBuffer.substring(0, splitPoint);
397
+ const afterText = newGeminiMessageBuffer.substring(splitPoint);
398
+ addItem(
399
+ {
400
+ type: pendingHistoryItemRef.current?.type as
401
+ | 'gemini'
402
+ | 'gemini_content',
403
+ text: beforeText,
404
+ },
405
+ userMessageTimestamp,
406
+ );
407
+ setPendingHistoryItem({ type: 'gemini_content', text: afterText });
408
+ newGeminiMessageBuffer = afterText;
409
+ }
410
+ return newGeminiMessageBuffer;
411
+ },
412
+ [addItem, pendingHistoryItemRef, setPendingHistoryItem],
413
+ );
414
+
415
+ const handleUserCancelledEvent = useCallback(
416
+ (userMessageTimestamp: number) => {
417
+ if (turnCancelledRef.current) {
418
+ return;
419
+ }
420
+ if (pendingHistoryItemRef.current) {
421
+ if (pendingHistoryItemRef.current.type === 'tool_group') {
422
+ const updatedTools = pendingHistoryItemRef.current.tools.map(
423
+ (tool) =>
424
+ tool.status === ToolCallStatus.Pending ||
425
+ tool.status === ToolCallStatus.Confirming ||
426
+ tool.status === ToolCallStatus.Executing
427
+ ? { ...tool, status: ToolCallStatus.Canceled }
428
+ : tool,
429
+ );
430
+ const pendingItem: HistoryItemToolGroup = {
431
+ ...pendingHistoryItemRef.current,
432
+ tools: updatedTools,
433
+ };
434
+ addItem(pendingItem, userMessageTimestamp);
435
+ } else {
436
+ addItem(pendingHistoryItemRef.current, userMessageTimestamp);
437
+ }
438
+ setPendingHistoryItem(null);
439
+ }
440
+ addItem(
441
+ { type: MessageType.INFO, text: 'User cancelled the request.' },
442
+ userMessageTimestamp,
443
+ );
444
+ setIsResponding(false);
445
+ setThought(null); // Reset thought when user cancels
446
+ },
447
+ [addItem, pendingHistoryItemRef, setPendingHistoryItem, setThought],
448
+ );
449
+
450
+ const handleErrorEvent = useCallback(
451
+ (eventValue: ErrorEvent['value'], userMessageTimestamp: number) => {
452
+ if (pendingHistoryItemRef.current) {
453
+ addItem(pendingHistoryItemRef.current, userMessageTimestamp);
454
+ setPendingHistoryItem(null);
455
+ }
456
+ addItem(
457
+ {
458
+ type: MessageType.ERROR,
459
+ text: parseAndFormatApiError(
460
+ eventValue.error,
461
+ config.getContentGeneratorConfig()?.authType,
462
+ undefined,
463
+ config.getModel(),
464
+ DEFAULT_GEMINI_FLASH_MODEL,
465
+ ),
466
+ },
467
+ userMessageTimestamp,
468
+ );
469
+ setThought(null); // Reset thought when there's an error
470
+ },
471
+ [addItem, pendingHistoryItemRef, setPendingHistoryItem, config, setThought],
472
+ );
473
+
474
+ const handleFinishedEvent = useCallback(
475
+ (event: ServerGeminiFinishedEvent, userMessageTimestamp: number) => {
476
+ const finishReason = event.value;
477
+
478
+ const finishReasonMessages: Record<FinishReason, string | undefined> = {
479
+ [FinishReason.FINISH_REASON_UNSPECIFIED]: undefined,
480
+ [FinishReason.STOP]: undefined,
481
+ [FinishReason.MAX_TOKENS]: 'Response truncated due to token limits.',
482
+ [FinishReason.SAFETY]: 'Response stopped due to safety reasons.',
483
+ [FinishReason.RECITATION]: 'Response stopped due to recitation policy.',
484
+ [FinishReason.LANGUAGE]:
485
+ 'Response stopped due to unsupported language.',
486
+ [FinishReason.BLOCKLIST]: 'Response stopped due to forbidden terms.',
487
+ [FinishReason.PROHIBITED_CONTENT]:
488
+ 'Response stopped due to prohibited content.',
489
+ [FinishReason.SPII]:
490
+ 'Response stopped due to sensitive personally identifiable information.',
491
+ [FinishReason.OTHER]: 'Response stopped for other reasons.',
492
+ [FinishReason.MALFORMED_FUNCTION_CALL]:
493
+ 'Response stopped due to malformed function call.',
494
+ [FinishReason.IMAGE_SAFETY]:
495
+ 'Response stopped due to image safety violations.',
496
+ [FinishReason.UNEXPECTED_TOOL_CALL]:
497
+ 'Response stopped due to unexpected tool call.',
498
+ };
499
+
500
+ const message = finishReasonMessages[finishReason];
501
+ if (message) {
502
+ addItem(
503
+ {
504
+ type: 'info',
505
+ text: `⚠️ ${message}`,
506
+ },
507
+ userMessageTimestamp,
508
+ );
509
+ }
510
+ },
511
+ [addItem],
512
+ );
513
+
514
+ const handleChatCompressionEvent = useCallback(
515
+ (eventValue: ServerGeminiChatCompressedEvent['value']) =>
516
+ addItem(
517
+ {
518
+ type: 'info',
519
+ text:
520
+ `IMPORTANT: This conversation approached the input token limit for ${config.getModel()}. ` +
521
+ `A compressed context will be sent for future messages (compressed from: ` +
522
+ `${eventValue?.originalTokenCount ?? 'unknown'} to ` +
523
+ `${eventValue?.newTokenCount ?? 'unknown'} tokens).`,
524
+ },
525
+ Date.now(),
526
+ ),
527
+ [addItem, config],
528
+ );
529
+
530
+ const handleMaxSessionTurnsEvent = useCallback(
531
+ () =>
532
+ addItem(
533
+ {
534
+ type: 'info',
535
+ text:
536
+ `The session has reached the maximum number of turns: ${config.getMaxSessionTurns()}. ` +
537
+ `Please update this limit in your setting.json file.`,
538
+ },
539
+ Date.now(),
540
+ ),
541
+ [addItem, config],
542
+ );
543
+
544
+ const handleSessionTokenLimitExceededEvent = useCallback(
545
+ (value: { currentTokens: number; limit: number; message: string }) =>
546
+ addItem(
547
+ {
548
+ type: 'error',
549
+ text:
550
+ `🚫 Session token limit exceeded: ${value.currentTokens.toLocaleString()} tokens > ${value.limit.toLocaleString()} limit.\n\n` +
551
+ `💡 Solutions:\n` +
552
+ ` • Start a new session: Use /clear command\n` +
553
+ ` • Increase limit: Add "sessionTokenLimit": (e.g., 128000) to your settings.json\n` +
554
+ ` • Compress history: Use /compress command to compress history`,
555
+ },
556
+ Date.now(),
557
+ ),
558
+ [addItem],
559
+ );
560
+
561
+ const handleLoopDetectedEvent = useCallback(() => {
562
+ addItem(
563
+ {
564
+ type: 'info',
565
+ text: `A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.`,
566
+ },
567
+ Date.now(),
568
+ );
569
+ }, [addItem]);
570
+
571
+ const processGeminiStreamEvents = useCallback(
572
+ async (
573
+ stream: AsyncIterable<GeminiEvent>,
574
+ userMessageTimestamp: number,
575
+ signal: AbortSignal,
576
+ ): Promise<StreamProcessingStatus> => {
577
+ let geminiMessageBuffer = '';
578
+ const toolCallRequests: ToolCallRequestInfo[] = [];
579
+ for await (const event of stream) {
580
+ switch (event.type) {
581
+ case ServerGeminiEventType.Thought:
582
+ setThought(event.value);
583
+ break;
584
+ case ServerGeminiEventType.Content:
585
+ geminiMessageBuffer = handleContentEvent(
586
+ event.value,
587
+ geminiMessageBuffer,
588
+ userMessageTimestamp,
589
+ );
590
+ break;
591
+ case ServerGeminiEventType.ToolCallRequest:
592
+ toolCallRequests.push(event.value);
593
+ break;
594
+ case ServerGeminiEventType.UserCancelled:
595
+ handleUserCancelledEvent(userMessageTimestamp);
596
+ break;
597
+ case ServerGeminiEventType.Error:
598
+ handleErrorEvent(event.value, userMessageTimestamp);
599
+ break;
600
+ case ServerGeminiEventType.ChatCompressed:
601
+ handleChatCompressionEvent(event.value);
602
+ break;
603
+ case ServerGeminiEventType.ToolCallConfirmation:
604
+ case ServerGeminiEventType.ToolCallResponse:
605
+ // do nothing
606
+ break;
607
+ case ServerGeminiEventType.MaxSessionTurns:
608
+ handleMaxSessionTurnsEvent();
609
+ break;
610
+ case ServerGeminiEventType.SessionTokenLimitExceeded:
611
+ handleSessionTokenLimitExceededEvent(event.value);
612
+ break;
613
+ case ServerGeminiEventType.Finished:
614
+ handleFinishedEvent(
615
+ event as ServerGeminiFinishedEvent,
616
+ userMessageTimestamp,
617
+ );
618
+ break;
619
+ case ServerGeminiEventType.LoopDetected:
620
+ // handle later because we want to move pending history to history
621
+ // before we add loop detected message to history
622
+ loopDetectedRef.current = true;
623
+ break;
624
+ default: {
625
+ // enforces exhaustive switch-case
626
+ const unreachable: never = event;
627
+ return unreachable;
628
+ }
629
+ }
630
+ }
631
+ if (toolCallRequests.length > 0) {
632
+ scheduleToolCalls(toolCallRequests, signal);
633
+ }
634
+ return StreamProcessingStatus.Completed;
635
+ },
636
+ [
637
+ handleContentEvent,
638
+ handleUserCancelledEvent,
639
+ handleErrorEvent,
640
+ scheduleToolCalls,
641
+ handleChatCompressionEvent,
642
+ handleFinishedEvent,
643
+ handleMaxSessionTurnsEvent,
644
+ handleSessionTokenLimitExceededEvent,
645
+ ],
646
+ );
647
+
648
+ const submitQuery = useCallback(
649
+ async (
650
+ query: PartListUnion,
651
+ options?: { isContinuation: boolean },
652
+ prompt_id?: string,
653
+ ) => {
654
+ // Prevent concurrent executions of submitQuery, but allow continuations
655
+ // which are part of the same logical flow (tool responses)
656
+ if (isSubmittingQueryRef.current && !options?.isContinuation) {
657
+ return;
658
+ }
659
+
660
+ if (
661
+ (streamingState === StreamingState.Responding ||
662
+ streamingState === StreamingState.WaitingForConfirmation) &&
663
+ !options?.isContinuation
664
+ )
665
+ return;
666
+
667
+ // Set the flag to indicate we're now executing
668
+ isSubmittingQueryRef.current = true;
669
+
670
+ const userMessageTimestamp = Date.now();
671
+
672
+ // Reset quota error flag when starting a new query (not a continuation)
673
+ if (!options?.isContinuation) {
674
+ setModelSwitchedFromQuotaError(false);
675
+ config.setQuotaErrorOccurred(false);
676
+ }
677
+
678
+ abortControllerRef.current = new AbortController();
679
+ const abortSignal = abortControllerRef.current.signal;
680
+ turnCancelledRef.current = false;
681
+
682
+ if (!prompt_id) {
683
+ prompt_id = config.getSessionId() + '########' + getPromptCount();
684
+ }
685
+
686
+ const { queryToSend, shouldProceed } = await prepareQueryForGemini(
687
+ query,
688
+ userMessageTimestamp,
689
+ abortSignal,
690
+ prompt_id!,
691
+ );
692
+
693
+ if (!shouldProceed || queryToSend === null) {
694
+ isSubmittingQueryRef.current = false;
695
+ return;
696
+ }
697
+
698
+ if (!options?.isContinuation) {
699
+ startNewPrompt();
700
+ setThought(null); // Reset thought when starting a new prompt
701
+ }
702
+
703
+ setIsResponding(true);
704
+ setInitError(null);
705
+
706
+ try {
707
+ const stream = geminiClient.sendMessageStream(
708
+ queryToSend,
709
+ abortSignal,
710
+ prompt_id!,
711
+ );
712
+ const processingStatus = await processGeminiStreamEvents(
713
+ stream,
714
+ userMessageTimestamp,
715
+ abortSignal,
716
+ );
717
+
718
+ if (processingStatus === StreamProcessingStatus.UserCancelled) {
719
+ isSubmittingQueryRef.current = false;
720
+ return;
721
+ }
722
+
723
+ if (pendingHistoryItemRef.current) {
724
+ addItem(pendingHistoryItemRef.current, userMessageTimestamp);
725
+ setPendingHistoryItem(null);
726
+ }
727
+ if (loopDetectedRef.current) {
728
+ loopDetectedRef.current = false;
729
+ handleLoopDetectedEvent();
730
+ }
731
+ } catch (error: unknown) {
732
+ if (error instanceof UnauthorizedError) {
733
+ onAuthError();
734
+ } else if (!isNodeError(error) || error.name !== 'AbortError') {
735
+ addItem(
736
+ {
737
+ type: MessageType.ERROR,
738
+ text: parseAndFormatApiError(
739
+ getErrorMessage(error) || 'Unknown error',
740
+ config.getContentGeneratorConfig()?.authType,
741
+ undefined,
742
+ config.getModel(),
743
+ DEFAULT_GEMINI_FLASH_MODEL,
744
+ ),
745
+ },
746
+ userMessageTimestamp,
747
+ );
748
+ }
749
+ } finally {
750
+ setIsResponding(false);
751
+ isSubmittingQueryRef.current = false;
752
+ }
753
+ },
754
+ [
755
+ streamingState,
756
+ setModelSwitchedFromQuotaError,
757
+ prepareQueryForGemini,
758
+ processGeminiStreamEvents,
759
+ pendingHistoryItemRef,
760
+ addItem,
761
+ setPendingHistoryItem,
762
+ setInitError,
763
+ geminiClient,
764
+ onAuthError,
765
+ config,
766
+ startNewPrompt,
767
+ getPromptCount,
768
+ handleLoopDetectedEvent,
769
+ ],
770
+ );
771
+
772
+ const handleCompletedTools = useCallback(
773
+ async (completedToolCallsFromScheduler: TrackedToolCall[]) => {
774
+ if (isResponding) {
775
+ return;
776
+ }
777
+
778
+ const completedAndReadyToSubmitTools =
779
+ completedToolCallsFromScheduler.filter(
780
+ (
781
+ tc: TrackedToolCall,
782
+ ): tc is TrackedCompletedToolCall | TrackedCancelledToolCall => {
783
+ const isTerminalState =
784
+ tc.status === 'success' ||
785
+ tc.status === 'error' ||
786
+ tc.status === 'cancelled';
787
+
788
+ if (isTerminalState) {
789
+ const completedOrCancelledCall = tc as
790
+ | TrackedCompletedToolCall
791
+ | TrackedCancelledToolCall;
792
+ return (
793
+ completedOrCancelledCall.response?.responseParts !== undefined
794
+ );
795
+ }
796
+ return false;
797
+ },
798
+ );
799
+
800
+ // Finalize any client-initiated tools as soon as they are done.
801
+ const clientTools = completedAndReadyToSubmitTools.filter(
802
+ (t) => t.request.isClientInitiated,
803
+ );
804
+ if (clientTools.length > 0) {
805
+ markToolsAsSubmitted(clientTools.map((t) => t.request.callId));
806
+ }
807
+
808
+ // Identify new, successful save_memory calls that we haven't processed yet.
809
+ const newSuccessfulMemorySaves = completedAndReadyToSubmitTools.filter(
810
+ (t) =>
811
+ t.request.name === 'save_memory' &&
812
+ t.status === 'success' &&
813
+ !processedMemoryToolsRef.current.has(t.request.callId),
814
+ );
815
+
816
+ if (newSuccessfulMemorySaves.length > 0) {
817
+ // Perform the refresh only if there are new ones.
818
+ void performMemoryRefresh();
819
+ // Mark them as processed so we don't do this again on the next render.
820
+ newSuccessfulMemorySaves.forEach((t) =>
821
+ processedMemoryToolsRef.current.add(t.request.callId),
822
+ );
823
+ }
824
+
825
+ const geminiTools = completedAndReadyToSubmitTools.filter(
826
+ (t) => !t.request.isClientInitiated,
827
+ );
828
+
829
+ if (geminiTools.length === 0) {
830
+ return;
831
+ }
832
+
833
+ // If all the tools were cancelled, don't submit a response to Gemini.
834
+ const allToolsCancelled = geminiTools.every(
835
+ (tc) => tc.status === 'cancelled',
836
+ );
837
+
838
+ if (allToolsCancelled) {
839
+ if (geminiClient) {
840
+ // We need to manually add the function responses to the history
841
+ // so the model knows the tools were cancelled.
842
+ const responsesToAdd = geminiTools.flatMap(
843
+ (toolCall) => toolCall.response.responseParts,
844
+ );
845
+ const combinedParts: Part[] = [];
846
+ for (const response of responsesToAdd) {
847
+ if (Array.isArray(response)) {
848
+ combinedParts.push(...response);
849
+ } else if (typeof response === 'string') {
850
+ combinedParts.push({ text: response });
851
+ } else {
852
+ combinedParts.push(response);
853
+ }
854
+ }
855
+ geminiClient.addHistory({
856
+ role: 'user',
857
+ parts: combinedParts,
858
+ });
859
+ }
860
+
861
+ const callIdsToMarkAsSubmitted = geminiTools.map(
862
+ (toolCall) => toolCall.request.callId,
863
+ );
864
+ markToolsAsSubmitted(callIdsToMarkAsSubmitted);
865
+ return;
866
+ }
867
+
868
+ const responsesToSend: PartListUnion[] = geminiTools.map(
869
+ (toolCall) => toolCall.response.responseParts,
870
+ );
871
+ const callIdsToMarkAsSubmitted = geminiTools.map(
872
+ (toolCall) => toolCall.request.callId,
873
+ );
874
+
875
+ const prompt_ids = geminiTools.map(
876
+ (toolCall) => toolCall.request.prompt_id,
877
+ );
878
+
879
+ markToolsAsSubmitted(callIdsToMarkAsSubmitted);
880
+
881
+ // Don't continue if model was switched due to quota error
882
+ if (modelSwitchedFromQuotaError) {
883
+ return;
884
+ }
885
+
886
+ submitQuery(
887
+ mergePartListUnions(responsesToSend),
888
+ {
889
+ isContinuation: true,
890
+ },
891
+ prompt_ids[0],
892
+ );
893
+ },
894
+ [
895
+ isResponding,
896
+ submitQuery,
897
+ markToolsAsSubmitted,
898
+ geminiClient,
899
+ performMemoryRefresh,
900
+ modelSwitchedFromQuotaError,
901
+ ],
902
+ );
903
+
904
+ const pendingHistoryItems = [
905
+ pendingHistoryItemRef.current,
906
+ pendingToolCallGroupDisplay,
907
+ ].filter((i) => i !== undefined && i !== null);
908
+
909
+ useEffect(() => {
910
+ const saveRestorableToolCalls = async () => {
911
+ if (!config.getCheckpointingEnabled()) {
912
+ return;
913
+ }
914
+ const restorableToolCalls = toolCalls.filter(
915
+ (toolCall) =>
916
+ (toolCall.request.name === 'replace' ||
917
+ toolCall.request.name === 'write_file') &&
918
+ toolCall.status === 'awaiting_approval',
919
+ );
920
+
921
+ if (restorableToolCalls.length > 0) {
922
+ const checkpointDir = config.getProjectTempDir()
923
+ ? path.join(config.getProjectTempDir(), 'checkpoints')
924
+ : undefined;
925
+
926
+ if (!checkpointDir) {
927
+ return;
928
+ }
929
+
930
+ try {
931
+ await fs.mkdir(checkpointDir, { recursive: true });
932
+ } catch (error) {
933
+ if (!isNodeError(error) || error.code !== 'EEXIST') {
934
+ onDebugMessage(
935
+ `Failed to create checkpoint directory: ${getErrorMessage(error)}`,
936
+ );
937
+ return;
938
+ }
939
+ }
940
+
941
+ for (const toolCall of restorableToolCalls) {
942
+ const filePath = toolCall.request.args['file_path'] as string;
943
+ if (!filePath) {
944
+ onDebugMessage(
945
+ `Skipping restorable tool call due to missing file_path: ${toolCall.request.name}`,
946
+ );
947
+ continue;
948
+ }
949
+
950
+ try {
951
+ let commitHash = await gitService?.createFileSnapshot(
952
+ `Snapshot for ${toolCall.request.name}`,
953
+ );
954
+
955
+ if (!commitHash) {
956
+ commitHash = await gitService?.getCurrentCommitHash();
957
+ }
958
+
959
+ if (!commitHash) {
960
+ onDebugMessage(
961
+ `Failed to create snapshot for ${filePath}. Skipping restorable tool call.`,
962
+ );
963
+ continue;
964
+ }
965
+
966
+ const timestamp = new Date()
967
+ .toISOString()
968
+ .replace(/:/g, '-')
969
+ .replace(/\./g, '_');
970
+ const toolName = toolCall.request.name;
971
+ const fileName = path.basename(filePath);
972
+ const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`;
973
+ const clientHistory = await geminiClient?.getHistory();
974
+ const toolCallWithSnapshotFilePath = path.join(
975
+ checkpointDir,
976
+ toolCallWithSnapshotFileName,
977
+ );
978
+
979
+ await fs.writeFile(
980
+ toolCallWithSnapshotFilePath,
981
+ JSON.stringify(
982
+ {
983
+ history,
984
+ clientHistory,
985
+ toolCall: {
986
+ name: toolCall.request.name,
987
+ args: toolCall.request.args,
988
+ },
989
+ commitHash,
990
+ filePath,
991
+ },
992
+ null,
993
+ 2,
994
+ ),
995
+ );
996
+ } catch (error) {
997
+ onDebugMessage(
998
+ `Failed to write restorable tool call file: ${getErrorMessage(
999
+ error,
1000
+ )}`,
1001
+ );
1002
+ }
1003
+ }
1004
+ }
1005
+ };
1006
+ saveRestorableToolCalls();
1007
+ }, [toolCalls, config, onDebugMessage, gitService, history, geminiClient]);
1008
+
1009
+ return {
1010
+ streamingState,
1011
+ submitQuery,
1012
+ initError,
1013
+ pendingHistoryItems,
1014
+ thought,
1015
+ cancelOngoingRequest,
1016
+ };
1017
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useGitBranchName.test.ts ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ afterEach,
9
+ beforeEach,
10
+ describe,
11
+ expect,
12
+ it,
13
+ vi,
14
+ MockedFunction,
15
+ } from 'vitest';
16
+ import { act } from 'react';
17
+ import { renderHook } from '@testing-library/react';
18
+ import { useGitBranchName } from './useGitBranchName.js';
19
+ import { fs, vol } from 'memfs'; // For mocking fs
20
+ import { EventEmitter } from 'node:events';
21
+ import { exec as mockExec, type ChildProcess } from 'node:child_process';
22
+ import type { FSWatcher } from 'memfs/lib/volume.js';
23
+
24
+ // Mock child_process
25
+ vi.mock('child_process');
26
+
27
+ // Mock fs and fs/promises
28
+ vi.mock('node:fs', async () => {
29
+ const memfs = await vi.importActual<typeof import('memfs')>('memfs');
30
+ return memfs.fs;
31
+ });
32
+
33
+ vi.mock('node:fs/promises', async () => {
34
+ const memfs = await vi.importActual<typeof import('memfs')>('memfs');
35
+ return memfs.fs.promises;
36
+ });
37
+
38
+ const CWD = '/test/project';
39
+ const GIT_HEAD_PATH = `${CWD}/.git/HEAD`;
40
+
41
+ describe('useGitBranchName', () => {
42
+ beforeEach(() => {
43
+ vol.reset(); // Reset in-memory filesystem
44
+ vol.fromJSON({
45
+ [GIT_HEAD_PATH]: 'ref: refs/heads/main',
46
+ });
47
+ vi.useFakeTimers(); // Use fake timers for async operations
48
+ });
49
+
50
+ afterEach(() => {
51
+ vi.restoreAllMocks();
52
+ vi.clearAllTimers();
53
+ });
54
+
55
+ it('should return branch name', async () => {
56
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementation(
57
+ (_command, _options, callback) => {
58
+ callback?.(null, 'main\n', '');
59
+ return new EventEmitter() as ChildProcess;
60
+ },
61
+ );
62
+
63
+ const { result, rerender } = renderHook(() => useGitBranchName(CWD));
64
+
65
+ await act(async () => {
66
+ vi.runAllTimers(); // Advance timers to trigger useEffect and exec callback
67
+ rerender(); // Rerender to get the updated state
68
+ });
69
+
70
+ expect(result.current).toBe('main');
71
+ });
72
+
73
+ it('should return undefined if git command fails', async () => {
74
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementation(
75
+ (_command, _options, callback) => {
76
+ callback?.(new Error('Git error'), '', 'error output');
77
+ return new EventEmitter() as ChildProcess;
78
+ },
79
+ );
80
+
81
+ const { result, rerender } = renderHook(() => useGitBranchName(CWD));
82
+ expect(result.current).toBeUndefined();
83
+
84
+ await act(async () => {
85
+ vi.runAllTimers();
86
+ rerender();
87
+ });
88
+ expect(result.current).toBeUndefined();
89
+ });
90
+
91
+ it('should return short commit hash if branch is HEAD (detached state)', async () => {
92
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementation(
93
+ (command, _options, callback) => {
94
+ if (command === 'git rev-parse --abbrev-ref HEAD') {
95
+ callback?.(null, 'HEAD\n', '');
96
+ } else if (command === 'git rev-parse --short HEAD') {
97
+ callback?.(null, 'a1b2c3d\n', '');
98
+ }
99
+ return new EventEmitter() as ChildProcess;
100
+ },
101
+ );
102
+
103
+ const { result, rerender } = renderHook(() => useGitBranchName(CWD));
104
+ await act(async () => {
105
+ vi.runAllTimers();
106
+ rerender();
107
+ });
108
+ expect(result.current).toBe('a1b2c3d');
109
+ });
110
+
111
+ it('should return undefined if branch is HEAD and getting commit hash fails', async () => {
112
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementation(
113
+ (command, _options, callback) => {
114
+ if (command === 'git rev-parse --abbrev-ref HEAD') {
115
+ callback?.(null, 'HEAD\n', '');
116
+ } else if (command === 'git rev-parse --short HEAD') {
117
+ callback?.(new Error('Git error'), '', 'error output');
118
+ }
119
+ return new EventEmitter() as ChildProcess;
120
+ },
121
+ );
122
+
123
+ const { result, rerender } = renderHook(() => useGitBranchName(CWD));
124
+ await act(async () => {
125
+ vi.runAllTimers();
126
+ rerender();
127
+ });
128
+ expect(result.current).toBeUndefined();
129
+ });
130
+
131
+ it('should update branch name when .git/HEAD changes', async ({ skip }) => {
132
+ skip(); // TODO: fix
133
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementationOnce(
134
+ (_command, _options, callback) => {
135
+ callback?.(null, 'main\n', '');
136
+ return new EventEmitter() as ChildProcess;
137
+ },
138
+ );
139
+
140
+ const { result, rerender } = renderHook(() => useGitBranchName(CWD));
141
+
142
+ await act(async () => {
143
+ vi.runAllTimers();
144
+ rerender();
145
+ });
146
+ expect(result.current).toBe('main');
147
+
148
+ // Simulate a branch change
149
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementationOnce(
150
+ (_command, _options, callback) => {
151
+ callback?.(null, 'develop\n', '');
152
+ return new EventEmitter() as ChildProcess;
153
+ },
154
+ );
155
+
156
+ // Simulate file change event
157
+ // Ensure the watcher is set up before triggering the change
158
+ await act(async () => {
159
+ fs.writeFileSync(GIT_HEAD_PATH, 'ref: refs/heads/develop'); // Trigger watcher
160
+ vi.runAllTimers(); // Process timers for watcher and exec
161
+ rerender();
162
+ });
163
+
164
+ expect(result.current).toBe('develop');
165
+ });
166
+
167
+ it('should handle watcher setup error silently', async () => {
168
+ // Remove .git/HEAD to cause an error in fs.watch setup
169
+ vol.unlinkSync(GIT_HEAD_PATH);
170
+
171
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementation(
172
+ (_command, _options, callback) => {
173
+ callback?.(null, 'main\n', '');
174
+ return new EventEmitter() as ChildProcess;
175
+ },
176
+ );
177
+
178
+ const { result, rerender } = renderHook(() => useGitBranchName(CWD));
179
+
180
+ await act(async () => {
181
+ vi.runAllTimers();
182
+ rerender();
183
+ });
184
+
185
+ expect(result.current).toBe('main'); // Branch name should still be fetched initially
186
+
187
+ // Try to trigger a change that would normally be caught by the watcher
188
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementationOnce(
189
+ (_command, _options, callback) => {
190
+ callback?.(null, 'develop\n', '');
191
+ return new EventEmitter() as ChildProcess;
192
+ },
193
+ );
194
+
195
+ // This write would trigger the watcher if it was set up
196
+ // but since it failed, the branch name should not update
197
+ // We need to create the file again for writeFileSync to not throw
198
+ vol.fromJSON({
199
+ [GIT_HEAD_PATH]: 'ref: refs/heads/develop',
200
+ });
201
+
202
+ await act(async () => {
203
+ fs.writeFileSync(GIT_HEAD_PATH, 'ref: refs/heads/develop');
204
+ vi.runAllTimers();
205
+ rerender();
206
+ });
207
+
208
+ // Branch name should not change because watcher setup failed
209
+ expect(result.current).toBe('main');
210
+ });
211
+
212
+ it('should cleanup watcher on unmount', async ({ skip }) => {
213
+ skip(); // TODO: fix
214
+ const closeMock = vi.fn();
215
+ const watchMock = vi.spyOn(fs, 'watch').mockReturnValue({
216
+ close: closeMock,
217
+ } as unknown as FSWatcher);
218
+
219
+ (mockExec as MockedFunction<typeof mockExec>).mockImplementation(
220
+ (_command, _options, callback) => {
221
+ callback?.(null, 'main\n', '');
222
+ return new EventEmitter() as ChildProcess;
223
+ },
224
+ );
225
+
226
+ const { unmount, rerender } = renderHook(() => useGitBranchName(CWD));
227
+
228
+ await act(async () => {
229
+ vi.runAllTimers();
230
+ rerender();
231
+ });
232
+
233
+ unmount();
234
+ expect(watchMock).toHaveBeenCalledWith(GIT_HEAD_PATH, expect.any(Function));
235
+ expect(closeMock).toHaveBeenCalled();
236
+ });
237
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useGitBranchName.ts ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useEffect, useCallback } from 'react';
8
+ import { exec } from 'node:child_process';
9
+ import fs from 'node:fs';
10
+ import fsPromises from 'node:fs/promises';
11
+ import path from 'path';
12
+
13
+ export function useGitBranchName(cwd: string): string | undefined {
14
+ const [branchName, setBranchName] = useState<string | undefined>(undefined);
15
+
16
+ const fetchBranchName = useCallback(
17
+ () =>
18
+ exec(
19
+ 'git rev-parse --abbrev-ref HEAD',
20
+ { cwd },
21
+ (error, stdout, _stderr) => {
22
+ if (error) {
23
+ setBranchName(undefined);
24
+ return;
25
+ }
26
+ const branch = stdout.toString().trim();
27
+ if (branch && branch !== 'HEAD') {
28
+ setBranchName(branch);
29
+ } else {
30
+ exec(
31
+ 'git rev-parse --short HEAD',
32
+ { cwd },
33
+ (error, stdout, _stderr) => {
34
+ if (error) {
35
+ setBranchName(undefined);
36
+ return;
37
+ }
38
+ setBranchName(stdout.toString().trim());
39
+ },
40
+ );
41
+ }
42
+ },
43
+ ),
44
+ [cwd, setBranchName],
45
+ );
46
+
47
+ useEffect(() => {
48
+ fetchBranchName(); // Initial fetch
49
+
50
+ const gitLogsHeadPath = path.join(cwd, '.git', 'logs', 'HEAD');
51
+ let watcher: fs.FSWatcher | undefined;
52
+
53
+ const setupWatcher = async () => {
54
+ try {
55
+ // Check if .git/logs/HEAD exists, as it might not in a new repo or orphaned head
56
+ await fsPromises.access(gitLogsHeadPath, fs.constants.F_OK);
57
+ watcher = fs.watch(gitLogsHeadPath, (eventType: string) => {
58
+ // Changes to .git/logs/HEAD (appends) indicate HEAD has likely changed
59
+ if (eventType === 'change' || eventType === 'rename') {
60
+ // Handle rename just in case
61
+ fetchBranchName();
62
+ }
63
+ });
64
+ } catch (_watchError) {
65
+ // Silently ignore watcher errors (e.g. permissions or file not existing),
66
+ // similar to how exec errors are handled.
67
+ // The branch name will simply not update automatically.
68
+ }
69
+ };
70
+
71
+ setupWatcher();
72
+
73
+ return () => {
74
+ watcher?.close();
75
+ };
76
+ }, [cwd, fetchBranchName]);
77
+
78
+ return branchName;
79
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useHistoryManager.test.ts ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import { useHistory } from './useHistoryManager.js';
10
+ import { HistoryItem } from '../types.js';
11
+
12
+ describe('useHistoryManager', () => {
13
+ it('should initialize with an empty history', () => {
14
+ const { result } = renderHook(() => useHistory());
15
+ expect(result.current.history).toEqual([]);
16
+ });
17
+
18
+ it('should add an item to history with a unique ID', () => {
19
+ const { result } = renderHook(() => useHistory());
20
+ const timestamp = Date.now();
21
+ const itemData: Omit<HistoryItem, 'id'> = {
22
+ type: 'user', // Replaced HistoryItemType.User
23
+ text: 'Hello',
24
+ };
25
+
26
+ act(() => {
27
+ result.current.addItem(itemData, timestamp);
28
+ });
29
+
30
+ expect(result.current.history).toHaveLength(1);
31
+ expect(result.current.history[0]).toEqual(
32
+ expect.objectContaining({
33
+ ...itemData,
34
+ id: expect.any(Number),
35
+ }),
36
+ );
37
+ // Basic check that ID incorporates timestamp
38
+ expect(result.current.history[0].id).toBeGreaterThanOrEqual(timestamp);
39
+ });
40
+
41
+ it('should generate unique IDs for items added with the same base timestamp', () => {
42
+ const { result } = renderHook(() => useHistory());
43
+ const timestamp = Date.now();
44
+ const itemData1: Omit<HistoryItem, 'id'> = {
45
+ type: 'user', // Replaced HistoryItemType.User
46
+ text: 'First',
47
+ };
48
+ const itemData2: Omit<HistoryItem, 'id'> = {
49
+ type: 'gemini', // Replaced HistoryItemType.Gemini
50
+ text: 'Second',
51
+ };
52
+
53
+ let id1!: number;
54
+ let id2!: number;
55
+
56
+ act(() => {
57
+ id1 = result.current.addItem(itemData1, timestamp);
58
+ id2 = result.current.addItem(itemData2, timestamp);
59
+ });
60
+
61
+ expect(result.current.history).toHaveLength(2);
62
+ expect(id1).not.toEqual(id2);
63
+ expect(result.current.history[0].id).toEqual(id1);
64
+ expect(result.current.history[1].id).toEqual(id2);
65
+ // IDs should be sequential based on the counter
66
+ expect(id2).toBeGreaterThan(id1);
67
+ });
68
+
69
+ it('should update an existing history item', () => {
70
+ const { result } = renderHook(() => useHistory());
71
+ const timestamp = Date.now();
72
+ const initialItem: Omit<HistoryItem, 'id'> = {
73
+ type: 'gemini', // Replaced HistoryItemType.Gemini
74
+ text: 'Initial content',
75
+ };
76
+ let itemId!: number;
77
+
78
+ act(() => {
79
+ itemId = result.current.addItem(initialItem, timestamp);
80
+ });
81
+
82
+ const updatedText = 'Updated content';
83
+ act(() => {
84
+ result.current.updateItem(itemId, { text: updatedText });
85
+ });
86
+
87
+ expect(result.current.history).toHaveLength(1);
88
+ expect(result.current.history[0]).toEqual({
89
+ ...initialItem,
90
+ id: itemId,
91
+ text: updatedText,
92
+ });
93
+ });
94
+
95
+ it('should not change history if updateHistoryItem is called with a nonexistent ID', () => {
96
+ const { result } = renderHook(() => useHistory());
97
+ const timestamp = Date.now();
98
+ const itemData: Omit<HistoryItem, 'id'> = {
99
+ type: 'user', // Replaced HistoryItemType.User
100
+ text: 'Hello',
101
+ };
102
+
103
+ act(() => {
104
+ result.current.addItem(itemData, timestamp);
105
+ });
106
+
107
+ const originalHistory = [...result.current.history]; // Clone before update attempt
108
+
109
+ act(() => {
110
+ result.current.updateItem(99999, { text: 'Should not apply' }); // Nonexistent ID
111
+ });
112
+
113
+ expect(result.current.history).toEqual(originalHistory);
114
+ });
115
+
116
+ it('should clear the history', () => {
117
+ const { result } = renderHook(() => useHistory());
118
+ const timestamp = Date.now();
119
+ const itemData1: Omit<HistoryItem, 'id'> = {
120
+ type: 'user', // Replaced HistoryItemType.User
121
+ text: 'First',
122
+ };
123
+ const itemData2: Omit<HistoryItem, 'id'> = {
124
+ type: 'gemini', // Replaced HistoryItemType.Gemini
125
+ text: 'Second',
126
+ };
127
+
128
+ act(() => {
129
+ result.current.addItem(itemData1, timestamp);
130
+ result.current.addItem(itemData2, timestamp);
131
+ });
132
+
133
+ expect(result.current.history).toHaveLength(2);
134
+
135
+ act(() => {
136
+ result.current.clearItems();
137
+ });
138
+
139
+ expect(result.current.history).toEqual([]);
140
+ });
141
+
142
+ it('should not add consecutive duplicate user messages', () => {
143
+ const { result } = renderHook(() => useHistory());
144
+ const timestamp = Date.now();
145
+ const itemData1: Omit<HistoryItem, 'id'> = {
146
+ type: 'user', // Replaced HistoryItemType.User
147
+ text: 'Duplicate message',
148
+ };
149
+ const itemData2: Omit<HistoryItem, 'id'> = {
150
+ type: 'user', // Replaced HistoryItemType.User
151
+ text: 'Duplicate message',
152
+ };
153
+ const itemData3: Omit<HistoryItem, 'id'> = {
154
+ type: 'gemini', // Replaced HistoryItemType.Gemini
155
+ text: 'Gemini response',
156
+ };
157
+ const itemData4: Omit<HistoryItem, 'id'> = {
158
+ type: 'user', // Replaced HistoryItemType.User
159
+ text: 'Another user message',
160
+ };
161
+
162
+ act(() => {
163
+ result.current.addItem(itemData1, timestamp);
164
+ result.current.addItem(itemData2, timestamp + 1); // Same text, different timestamp
165
+ result.current.addItem(itemData3, timestamp + 2);
166
+ result.current.addItem(itemData4, timestamp + 3);
167
+ });
168
+
169
+ expect(result.current.history).toHaveLength(3);
170
+ expect(result.current.history[0].text).toBe('Duplicate message');
171
+ expect(result.current.history[1].text).toBe('Gemini response');
172
+ expect(result.current.history[2].text).toBe('Another user message');
173
+ });
174
+
175
+ it('should add duplicate user messages if they are not consecutive', () => {
176
+ const { result } = renderHook(() => useHistory());
177
+ const timestamp = Date.now();
178
+ const itemData1: Omit<HistoryItem, 'id'> = {
179
+ type: 'user', // Replaced HistoryItemType.User
180
+ text: 'Message 1',
181
+ };
182
+ const itemData2: Omit<HistoryItem, 'id'> = {
183
+ type: 'gemini', // Replaced HistoryItemType.Gemini
184
+ text: 'Gemini response',
185
+ };
186
+ const itemData3: Omit<HistoryItem, 'id'> = {
187
+ type: 'user', // Replaced HistoryItemType.User
188
+ text: 'Message 1', // Duplicate text, but not consecutive
189
+ };
190
+
191
+ act(() => {
192
+ result.current.addItem(itemData1, timestamp);
193
+ result.current.addItem(itemData2, timestamp + 1);
194
+ result.current.addItem(itemData3, timestamp + 2);
195
+ });
196
+
197
+ expect(result.current.history).toHaveLength(3);
198
+ expect(result.current.history[0].text).toBe('Message 1');
199
+ expect(result.current.history[1].text).toBe('Gemini response');
200
+ expect(result.current.history[2].text).toBe('Message 1');
201
+ });
202
+ });