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

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/hooks/useHistoryManager.ts +111 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/hooks/useInputHistory.test.ts +261 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/hooks/useInputHistory.ts +111 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/hooks/useKeypress.test.ts +280 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/hooks/useKeypress.ts +39 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/hooks/useKittyKeyboardProtocol.ts +31 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/hooks/useLoadingIndicator.test.ts +139 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/hooks/useLoadingIndicator.ts +57 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/hooks/useLogger.ts +32 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/hooks/useMessageQueue.test.ts +226 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/hooks/useMessageQueue.ts +69 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/hooks/usePhraseCycler.test.ts +145 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/hooks/usePhraseCycler.ts +198 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/hooks/usePrivacySettings.test.ts +242 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/hooks/usePrivacySettings.ts +150 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/hooks/useQwenAuth.test.ts +437 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/hooks/useQwenAuth.ts +120 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/hooks/useReactToolScheduler.ts +309 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/hooks/useRefreshMemoryCommand.ts +7 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/hooks/useReverseSearchCompletion.test.tsx +260 -0
projects/ui/qwen-code/packages/cli/src/ui/hooks/useHistoryManager.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useRef, useCallback } from 'react';
8
+ import { HistoryItem } from '../types.js';
9
+
10
+ // Type for the updater function passed to updateHistoryItem
11
+ type HistoryItemUpdater = (
12
+ prevItem: HistoryItem,
13
+ ) => Partial<Omit<HistoryItem, 'id'>>;
14
+
15
+ export interface UseHistoryManagerReturn {
16
+ history: HistoryItem[];
17
+ addItem: (itemData: Omit<HistoryItem, 'id'>, baseTimestamp: number) => number; // Returns the generated ID
18
+ updateItem: (
19
+ id: number,
20
+ updates: Partial<Omit<HistoryItem, 'id'>> | HistoryItemUpdater,
21
+ ) => void;
22
+ clearItems: () => void;
23
+ loadHistory: (newHistory: HistoryItem[]) => void;
24
+ }
25
+
26
+ /**
27
+ * Custom hook to manage the chat history state.
28
+ *
29
+ * Encapsulates the history array, message ID generation, adding items,
30
+ * updating items, and clearing the history.
31
+ */
32
+ export function useHistory(): UseHistoryManagerReturn {
33
+ const [history, setHistory] = useState<HistoryItem[]>([]);
34
+ const messageIdCounterRef = useRef(0);
35
+
36
+ // Generates a unique message ID based on a timestamp and a counter.
37
+ const getNextMessageId = useCallback((baseTimestamp: number): number => {
38
+ messageIdCounterRef.current += 1;
39
+ return baseTimestamp + messageIdCounterRef.current;
40
+ }, []);
41
+
42
+ const loadHistory = useCallback((newHistory: HistoryItem[]) => {
43
+ setHistory(newHistory);
44
+ }, []);
45
+
46
+ // Adds a new item to the history state with a unique ID.
47
+ const addItem = useCallback(
48
+ (itemData: Omit<HistoryItem, 'id'>, baseTimestamp: number): number => {
49
+ const id = getNextMessageId(baseTimestamp);
50
+ const newItem: HistoryItem = { ...itemData, id } as HistoryItem;
51
+
52
+ setHistory((prevHistory) => {
53
+ if (prevHistory.length > 0) {
54
+ const lastItem = prevHistory[prevHistory.length - 1];
55
+ // Prevent adding duplicate consecutive user messages
56
+ if (
57
+ lastItem.type === 'user' &&
58
+ newItem.type === 'user' &&
59
+ lastItem.text === newItem.text
60
+ ) {
61
+ return prevHistory; // Don't add the duplicate
62
+ }
63
+ }
64
+ return [...prevHistory, newItem];
65
+ });
66
+ return id; // Return the generated ID (even if not added, to keep signature)
67
+ },
68
+ [getNextMessageId],
69
+ );
70
+
71
+ /**
72
+ * Updates an existing history item identified by its ID.
73
+ * @deprecated Prefer not to update history item directly as we are currently
74
+ * rendering all history items in <Static /> for performance reasons. Only use
75
+ * if ABSOLUTELY NECESSARY
76
+ */
77
+ //
78
+ const updateItem = useCallback(
79
+ (
80
+ id: number,
81
+ updates: Partial<Omit<HistoryItem, 'id'>> | HistoryItemUpdater,
82
+ ) => {
83
+ setHistory((prevHistory) =>
84
+ prevHistory.map((item) => {
85
+ if (item.id === id) {
86
+ // Apply updates based on whether it's an object or a function
87
+ const newUpdates =
88
+ typeof updates === 'function' ? updates(item) : updates;
89
+ return { ...item, ...newUpdates } as HistoryItem;
90
+ }
91
+ return item;
92
+ }),
93
+ );
94
+ },
95
+ [],
96
+ );
97
+
98
+ // Clears the entire history state and resets the ID counter.
99
+ const clearItems = useCallback(() => {
100
+ setHistory([]);
101
+ messageIdCounterRef.current = 0;
102
+ }, []);
103
+
104
+ return {
105
+ history,
106
+ addItem,
107
+ updateItem,
108
+ clearItems,
109
+ loadHistory,
110
+ };
111
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useInputHistory.test.ts ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { useInputHistory } from './useInputHistory.js';
9
+
10
+ describe('useInputHistory', () => {
11
+ const mockOnSubmit = vi.fn();
12
+ const mockOnChange = vi.fn();
13
+
14
+ beforeEach(() => {
15
+ vi.clearAllMocks();
16
+ });
17
+
18
+ const userMessages = ['message 1', 'message 2', 'message 3'];
19
+
20
+ it('should initialize with historyIndex -1 and empty originalQueryBeforeNav', () => {
21
+ const { result } = renderHook(() =>
22
+ useInputHistory({
23
+ userMessages: [],
24
+ onSubmit: mockOnSubmit,
25
+ isActive: true,
26
+ currentQuery: '',
27
+ onChange: mockOnChange,
28
+ }),
29
+ );
30
+
31
+ // Internal state is not directly testable, but we can infer from behavior.
32
+ // Attempting to navigate down should do nothing if historyIndex is -1.
33
+ act(() => {
34
+ result.current.navigateDown();
35
+ });
36
+ expect(mockOnChange).not.toHaveBeenCalled();
37
+ });
38
+
39
+ describe('handleSubmit', () => {
40
+ it('should call onSubmit with trimmed value and reset history', () => {
41
+ const { result } = renderHook(() =>
42
+ useInputHistory({
43
+ userMessages,
44
+ onSubmit: mockOnSubmit,
45
+ isActive: true,
46
+ currentQuery: ' test query ',
47
+ onChange: mockOnChange,
48
+ }),
49
+ );
50
+
51
+ act(() => {
52
+ result.current.handleSubmit(' submit value ');
53
+ });
54
+
55
+ expect(mockOnSubmit).toHaveBeenCalledWith('submit value');
56
+ // Check if history is reset (e.g., by trying to navigate down)
57
+ act(() => {
58
+ result.current.navigateDown();
59
+ });
60
+ expect(mockOnChange).not.toHaveBeenCalled();
61
+ });
62
+
63
+ it('should not call onSubmit if value is empty after trimming', () => {
64
+ const { result } = renderHook(() =>
65
+ useInputHistory({
66
+ userMessages,
67
+ onSubmit: mockOnSubmit,
68
+ isActive: true,
69
+ currentQuery: '',
70
+ onChange: mockOnChange,
71
+ }),
72
+ );
73
+
74
+ act(() => {
75
+ result.current.handleSubmit(' ');
76
+ });
77
+
78
+ expect(mockOnSubmit).not.toHaveBeenCalled();
79
+ });
80
+ });
81
+
82
+ describe('navigateUp', () => {
83
+ it('should not navigate if isActive is false', () => {
84
+ const { result } = renderHook(() =>
85
+ useInputHistory({
86
+ userMessages,
87
+ onSubmit: mockOnSubmit,
88
+ isActive: false,
89
+ currentQuery: 'current',
90
+ onChange: mockOnChange,
91
+ }),
92
+ );
93
+ act(() => {
94
+ const navigated = result.current.navigateUp();
95
+ expect(navigated).toBe(false);
96
+ });
97
+ expect(mockOnChange).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('should not navigate if userMessages is empty', () => {
101
+ const { result } = renderHook(() =>
102
+ useInputHistory({
103
+ userMessages: [],
104
+ onSubmit: mockOnSubmit,
105
+ isActive: true,
106
+ currentQuery: 'current',
107
+ onChange: mockOnChange,
108
+ }),
109
+ );
110
+ act(() => {
111
+ const navigated = result.current.navigateUp();
112
+ expect(navigated).toBe(false);
113
+ });
114
+ expect(mockOnChange).not.toHaveBeenCalled();
115
+ });
116
+
117
+ it('should call onChange with the last message when navigating up from initial state', () => {
118
+ const currentQuery = 'current query';
119
+ const { result } = renderHook(() =>
120
+ useInputHistory({
121
+ userMessages,
122
+ onSubmit: mockOnSubmit,
123
+ isActive: true,
124
+ currentQuery,
125
+ onChange: mockOnChange,
126
+ }),
127
+ );
128
+
129
+ act(() => {
130
+ result.current.navigateUp();
131
+ });
132
+
133
+ expect(mockOnChange).toHaveBeenCalledWith(userMessages[2]); // Last message
134
+ });
135
+
136
+ it('should store currentQuery as originalQueryBeforeNav on first navigateUp', () => {
137
+ const currentQuery = 'original user input';
138
+ const { result } = renderHook(() =>
139
+ useInputHistory({
140
+ userMessages,
141
+ onSubmit: mockOnSubmit,
142
+ isActive: true,
143
+ currentQuery,
144
+ onChange: mockOnChange,
145
+ }),
146
+ );
147
+
148
+ act(() => {
149
+ result.current.navigateUp(); // historyIndex becomes 0
150
+ });
151
+ expect(mockOnChange).toHaveBeenCalledWith(userMessages[2]);
152
+
153
+ // Navigate down to restore original query
154
+ act(() => {
155
+ result.current.navigateDown(); // historyIndex becomes -1
156
+ });
157
+ expect(mockOnChange).toHaveBeenCalledWith(currentQuery);
158
+ });
159
+
160
+ it('should navigate through history messages on subsequent navigateUp calls', () => {
161
+ const { result } = renderHook(() =>
162
+ useInputHistory({
163
+ userMessages,
164
+ onSubmit: mockOnSubmit,
165
+ isActive: true,
166
+ currentQuery: '',
167
+ onChange: mockOnChange,
168
+ }),
169
+ );
170
+
171
+ act(() => {
172
+ result.current.navigateUp(); // Navigates to 'message 3'
173
+ });
174
+ expect(mockOnChange).toHaveBeenCalledWith(userMessages[2]);
175
+
176
+ act(() => {
177
+ result.current.navigateUp(); // Navigates to 'message 2'
178
+ });
179
+ expect(mockOnChange).toHaveBeenCalledWith(userMessages[1]);
180
+
181
+ act(() => {
182
+ result.current.navigateUp(); // Navigates to 'message 1'
183
+ });
184
+ expect(mockOnChange).toHaveBeenCalledWith(userMessages[0]);
185
+ });
186
+ });
187
+
188
+ describe('navigateDown', () => {
189
+ it('should not navigate if isActive is false', () => {
190
+ const initialProps = {
191
+ userMessages,
192
+ onSubmit: mockOnSubmit,
193
+ isActive: true, // Start active to allow setup navigation
194
+ currentQuery: 'current',
195
+ onChange: mockOnChange,
196
+ };
197
+ const { result, rerender } = renderHook(
198
+ (props) => useInputHistory(props),
199
+ {
200
+ initialProps,
201
+ },
202
+ );
203
+
204
+ // First navigate up to have something in history
205
+ act(() => {
206
+ result.current.navigateUp();
207
+ });
208
+ mockOnChange.mockClear(); // Clear calls from setup
209
+
210
+ // Set isActive to false for the actual test
211
+ rerender({ ...initialProps, isActive: false });
212
+
213
+ act(() => {
214
+ const navigated = result.current.navigateDown();
215
+ expect(navigated).toBe(false);
216
+ });
217
+ expect(mockOnChange).not.toHaveBeenCalled();
218
+ });
219
+
220
+ it('should not navigate if historyIndex is -1 (not in history navigation)', () => {
221
+ const { result } = renderHook(() =>
222
+ useInputHistory({
223
+ userMessages,
224
+ onSubmit: mockOnSubmit,
225
+ isActive: true,
226
+ currentQuery: 'current',
227
+ onChange: mockOnChange,
228
+ }),
229
+ );
230
+ act(() => {
231
+ const navigated = result.current.navigateDown();
232
+ expect(navigated).toBe(false);
233
+ });
234
+ expect(mockOnChange).not.toHaveBeenCalled();
235
+ });
236
+
237
+ it('should restore originalQueryBeforeNav when navigating down to initial state', () => {
238
+ const originalQuery = 'my original input';
239
+ const { result } = renderHook(() =>
240
+ useInputHistory({
241
+ userMessages,
242
+ onSubmit: mockOnSubmit,
243
+ isActive: true,
244
+ currentQuery: originalQuery,
245
+ onChange: mockOnChange,
246
+ }),
247
+ );
248
+
249
+ act(() => {
250
+ result.current.navigateUp(); // Navigates to 'message 3', stores 'originalQuery'
251
+ });
252
+ expect(mockOnChange).toHaveBeenCalledWith(userMessages[2]);
253
+ mockOnChange.mockClear();
254
+
255
+ act(() => {
256
+ result.current.navigateDown(); // Navigates back to original query
257
+ });
258
+ expect(mockOnChange).toHaveBeenCalledWith(originalQuery);
259
+ });
260
+ });
261
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useInputHistory.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ interface UseInputHistoryProps {
10
+ userMessages: readonly string[];
11
+ onSubmit: (value: string) => void;
12
+ isActive: boolean;
13
+ currentQuery: string; // Renamed from query to avoid confusion
14
+ onChange: (value: string) => void;
15
+ }
16
+
17
+ export interface UseInputHistoryReturn {
18
+ handleSubmit: (value: string) => void;
19
+ navigateUp: () => boolean;
20
+ navigateDown: () => boolean;
21
+ }
22
+
23
+ export function useInputHistory({
24
+ userMessages,
25
+ onSubmit,
26
+ isActive,
27
+ currentQuery,
28
+ onChange,
29
+ }: UseInputHistoryProps): UseInputHistoryReturn {
30
+ const [historyIndex, setHistoryIndex] = useState<number>(-1);
31
+ const [originalQueryBeforeNav, setOriginalQueryBeforeNav] =
32
+ useState<string>('');
33
+
34
+ const resetHistoryNav = useCallback(() => {
35
+ setHistoryIndex(-1);
36
+ setOriginalQueryBeforeNav('');
37
+ }, []);
38
+
39
+ const handleSubmit = useCallback(
40
+ (value: string) => {
41
+ const trimmedValue = value.trim();
42
+ if (trimmedValue) {
43
+ onSubmit(trimmedValue); // Parent handles clearing the query
44
+ }
45
+ resetHistoryNav();
46
+ },
47
+ [onSubmit, resetHistoryNav],
48
+ );
49
+
50
+ const navigateUp = useCallback(() => {
51
+ if (!isActive) return false;
52
+ if (userMessages.length === 0) return false;
53
+
54
+ let nextIndex = historyIndex;
55
+ if (historyIndex === -1) {
56
+ // Store the current query from the parent before navigating
57
+ setOriginalQueryBeforeNav(currentQuery);
58
+ nextIndex = 0;
59
+ } else if (historyIndex < userMessages.length - 1) {
60
+ nextIndex = historyIndex + 1;
61
+ } else {
62
+ return false; // Already at the oldest message
63
+ }
64
+
65
+ if (nextIndex !== historyIndex) {
66
+ setHistoryIndex(nextIndex);
67
+ const newValue = userMessages[userMessages.length - 1 - nextIndex];
68
+ onChange(newValue);
69
+ return true;
70
+ }
71
+ return false;
72
+ }, [
73
+ historyIndex,
74
+ setHistoryIndex,
75
+ onChange,
76
+ userMessages,
77
+ isActive,
78
+ currentQuery, // Use currentQuery from props
79
+ setOriginalQueryBeforeNav,
80
+ ]);
81
+
82
+ const navigateDown = useCallback(() => {
83
+ if (!isActive) return false;
84
+ if (historyIndex === -1) return false; // Not currently navigating history
85
+
86
+ const nextIndex = historyIndex - 1;
87
+ setHistoryIndex(nextIndex);
88
+
89
+ if (nextIndex === -1) {
90
+ // Reached the end of history navigation, restore original query
91
+ onChange(originalQueryBeforeNav);
92
+ } else {
93
+ const newValue = userMessages[userMessages.length - 1 - nextIndex];
94
+ onChange(newValue);
95
+ }
96
+ return true;
97
+ }, [
98
+ historyIndex,
99
+ setHistoryIndex,
100
+ originalQueryBeforeNav,
101
+ onChange,
102
+ userMessages,
103
+ isActive,
104
+ ]);
105
+
106
+ return {
107
+ handleSubmit,
108
+ navigateUp,
109
+ navigateDown,
110
+ };
111
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useKeypress.test.ts ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import { useKeypress, Key } from './useKeypress.js';
10
+ import { KeypressProvider } from '../contexts/KeypressContext.js';
11
+ import { useStdin } from 'ink';
12
+ import { EventEmitter } from 'events';
13
+ import { PassThrough } from 'stream';
14
+
15
+ // Mock the 'ink' module to control stdin
16
+ vi.mock('ink', async (importOriginal) => {
17
+ const original = await importOriginal<typeof import('ink')>();
18
+ return {
19
+ ...original,
20
+ useStdin: vi.fn(),
21
+ };
22
+ });
23
+
24
+ // Mock the 'readline' module
25
+ vi.mock('readline', () => {
26
+ const mockedReadline = {
27
+ createInterface: vi.fn().mockReturnValue({ close: vi.fn() }),
28
+ // The paste workaround involves replacing stdin with a PassThrough stream.
29
+ // This mock ensures that when emitKeypressEvents is called on that
30
+ // stream, we simulate the 'keypress' events that the hook expects.
31
+ emitKeypressEvents: vi.fn((stream: EventEmitter) => {
32
+ if (stream instanceof PassThrough) {
33
+ stream.on('data', (data) => {
34
+ const str = data.toString();
35
+ for (const char of str) {
36
+ stream.emit('keypress', null, {
37
+ name: char,
38
+ sequence: char,
39
+ ctrl: false,
40
+ meta: false,
41
+ shift: false,
42
+ });
43
+ }
44
+ });
45
+ }
46
+ }),
47
+ };
48
+ return {
49
+ ...mockedReadline,
50
+ default: mockedReadline,
51
+ };
52
+ });
53
+
54
+ class MockStdin extends EventEmitter {
55
+ isTTY = true;
56
+ setRawMode = vi.fn();
57
+ on = this.addListener;
58
+ removeListener = this.removeListener;
59
+ write = vi.fn();
60
+ resume = vi.fn();
61
+
62
+ private isLegacy = false;
63
+
64
+ setLegacy(isLegacy: boolean) {
65
+ this.isLegacy = isLegacy;
66
+ }
67
+
68
+ // Helper to simulate a full paste event.
69
+ paste(text: string) {
70
+ if (this.isLegacy) {
71
+ const PASTE_START = '\x1B[200~';
72
+ const PASTE_END = '\x1B[201~';
73
+ this.emit('data', Buffer.from(`${PASTE_START}${text}${PASTE_END}`));
74
+ } else {
75
+ this.emit('keypress', null, { name: 'paste-start' });
76
+ this.emit('keypress', null, { sequence: text });
77
+ this.emit('keypress', null, { name: 'paste-end' });
78
+ }
79
+ }
80
+
81
+ // Helper to simulate the start of a paste, without the end.
82
+ startPaste(text: string) {
83
+ if (this.isLegacy) {
84
+ this.emit('data', Buffer.from('\x1B[200~' + text));
85
+ } else {
86
+ this.emit('keypress', null, { name: 'paste-start' });
87
+ this.emit('keypress', null, { sequence: text });
88
+ }
89
+ }
90
+
91
+ // Helper to simulate a single keypress event.
92
+ pressKey(key: Partial<Key>) {
93
+ if (this.isLegacy) {
94
+ this.emit('data', Buffer.from(key.sequence ?? ''));
95
+ } else {
96
+ this.emit('keypress', null, key);
97
+ }
98
+ }
99
+ }
100
+
101
+ describe('useKeypress', () => {
102
+ let stdin: MockStdin;
103
+ const mockSetRawMode = vi.fn();
104
+ const onKeypress = vi.fn();
105
+ let originalNodeVersion: string;
106
+
107
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
108
+ React.createElement(KeypressProvider, null, children);
109
+
110
+ beforeEach(() => {
111
+ vi.clearAllMocks();
112
+ stdin = new MockStdin();
113
+ (useStdin as vi.Mock).mockReturnValue({
114
+ stdin,
115
+ setRawMode: mockSetRawMode,
116
+ });
117
+
118
+ originalNodeVersion = process.versions.node;
119
+ vi.unstubAllEnvs();
120
+ });
121
+
122
+ afterEach(() => {
123
+ Object.defineProperty(process.versions, 'node', {
124
+ value: originalNodeVersion,
125
+ configurable: true,
126
+ });
127
+ });
128
+
129
+ const setNodeVersion = (version: string) => {
130
+ Object.defineProperty(process.versions, 'node', {
131
+ value: version,
132
+ configurable: true,
133
+ });
134
+ };
135
+
136
+ it('should not listen if isActive is false', () => {
137
+ renderHook(() => useKeypress(onKeypress, { isActive: false }), {
138
+ wrapper,
139
+ });
140
+ act(() => stdin.pressKey({ name: 'a' }));
141
+ expect(onKeypress).not.toHaveBeenCalled();
142
+ });
143
+
144
+ it.each([
145
+ { key: { name: 'a', sequence: 'a' } },
146
+ { key: { name: 'left', sequence: '\x1b[D' } },
147
+ { key: { name: 'right', sequence: '\x1b[C' } },
148
+ { key: { name: 'up', sequence: '\x1b[A' } },
149
+ { key: { name: 'down', sequence: '\x1b[B' } },
150
+ ])('should listen for keypress when active for key $key.name', ({ key }) => {
151
+ renderHook(() => useKeypress(onKeypress, { isActive: true }), { wrapper });
152
+ act(() => stdin.pressKey(key));
153
+ expect(onKeypress).toHaveBeenCalledWith(expect.objectContaining(key));
154
+ });
155
+
156
+ it('should set and release raw mode', () => {
157
+ const { unmount } = renderHook(
158
+ () => useKeypress(onKeypress, { isActive: true }),
159
+ { wrapper },
160
+ );
161
+ expect(mockSetRawMode).toHaveBeenCalledWith(true);
162
+ unmount();
163
+ expect(mockSetRawMode).toHaveBeenCalledWith(false);
164
+ });
165
+
166
+ it('should stop listening after being unmounted', () => {
167
+ const { unmount } = renderHook(
168
+ () => useKeypress(onKeypress, { isActive: true }),
169
+ { wrapper },
170
+ );
171
+ unmount();
172
+ act(() => stdin.pressKey({ name: 'a' }));
173
+ expect(onKeypress).not.toHaveBeenCalled();
174
+ });
175
+
176
+ it('should correctly identify alt+enter (meta key)', () => {
177
+ renderHook(() => useKeypress(onKeypress, { isActive: true }), { wrapper });
178
+ const key = { name: 'return', sequence: '\x1B\r' };
179
+ act(() => stdin.pressKey(key));
180
+ expect(onKeypress).toHaveBeenCalledWith(
181
+ expect.objectContaining({ ...key, meta: true, paste: false }),
182
+ );
183
+ });
184
+
185
+ describe.each([
186
+ {
187
+ description: 'Modern Node (>= v20)',
188
+ setup: () => setNodeVersion('20.0.0'),
189
+ isLegacy: false,
190
+ },
191
+ {
192
+ description: 'Legacy Node (< v20)',
193
+ setup: () => setNodeVersion('18.0.0'),
194
+ isLegacy: true,
195
+ },
196
+ {
197
+ description: 'Workaround Env Var',
198
+ setup: () => {
199
+ setNodeVersion('20.0.0');
200
+ vi.stubEnv('PASTE_WORKAROUND', 'true');
201
+ },
202
+ isLegacy: true,
203
+ },
204
+ ])('in $description', ({ setup, isLegacy }) => {
205
+ beforeEach(() => {
206
+ setup();
207
+ stdin.setLegacy(isLegacy);
208
+ });
209
+
210
+ it('should process a paste as a single event', () => {
211
+ renderHook(() => useKeypress(onKeypress, { isActive: true }), {
212
+ wrapper,
213
+ });
214
+ const pasteText = 'hello world';
215
+ act(() => stdin.paste(pasteText));
216
+
217
+ expect(onKeypress).toHaveBeenCalledTimes(1);
218
+ expect(onKeypress).toHaveBeenCalledWith({
219
+ name: '',
220
+ ctrl: false,
221
+ meta: false,
222
+ shift: false,
223
+ paste: true,
224
+ sequence: pasteText,
225
+ });
226
+ });
227
+
228
+ it('should handle keypress interspersed with pastes', () => {
229
+ renderHook(() => useKeypress(onKeypress, { isActive: true }), {
230
+ wrapper,
231
+ });
232
+
233
+ const keyA = { name: 'a', sequence: 'a' };
234
+ act(() => stdin.pressKey(keyA));
235
+ expect(onKeypress).toHaveBeenCalledWith(
236
+ expect.objectContaining({ ...keyA, paste: false }),
237
+ );
238
+
239
+ const pasteText = 'pasted';
240
+ act(() => stdin.paste(pasteText));
241
+ expect(onKeypress).toHaveBeenCalledWith(
242
+ expect.objectContaining({ paste: true, sequence: pasteText }),
243
+ );
244
+
245
+ const keyB = { name: 'b', sequence: 'b' };
246
+ act(() => stdin.pressKey(keyB));
247
+ expect(onKeypress).toHaveBeenCalledWith(
248
+ expect.objectContaining({ ...keyB, paste: false }),
249
+ );
250
+
251
+ expect(onKeypress).toHaveBeenCalledTimes(3);
252
+ });
253
+
254
+ it('should emit partial paste content if unmounted mid-paste', () => {
255
+ const { unmount } = renderHook(
256
+ () => useKeypress(onKeypress, { isActive: true }),
257
+ { wrapper },
258
+ );
259
+ const pasteText = 'incomplete paste';
260
+
261
+ act(() => stdin.startPaste(pasteText));
262
+
263
+ // No event should be fired yet.
264
+ expect(onKeypress).not.toHaveBeenCalled();
265
+
266
+ // Unmounting should trigger the flush.
267
+ unmount();
268
+
269
+ expect(onKeypress).toHaveBeenCalledTimes(1);
270
+ expect(onKeypress).toHaveBeenCalledWith({
271
+ name: '',
272
+ ctrl: false,
273
+ meta: false,
274
+ shift: false,
275
+ paste: true,
276
+ sequence: pasteText,
277
+ });
278
+ });
279
+ });
280
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useKeypress.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useEffect } from 'react';
8
+ import {
9
+ useKeypressContext,
10
+ KeypressHandler,
11
+ Key,
12
+ } from '../contexts/KeypressContext.js';
13
+
14
+ export { Key };
15
+
16
+ /**
17
+ * A hook that listens for keypress events from stdin.
18
+ *
19
+ * @param onKeypress - The callback function to execute on each keypress.
20
+ * @param options - Options to control the hook's behavior.
21
+ * @param options.isActive - Whether the hook should be actively listening for input.
22
+ */
23
+ export function useKeypress(
24
+ onKeypress: KeypressHandler,
25
+ { isActive }: { isActive: boolean },
26
+ ) {
27
+ const { subscribe, unsubscribe } = useKeypressContext();
28
+
29
+ useEffect(() => {
30
+ if (!isActive) {
31
+ return;
32
+ }
33
+
34
+ subscribe(onKeypress);
35
+ return () => {
36
+ unsubscribe(onKeypress);
37
+ };
38
+ }, [isActive, onKeypress, subscribe, unsubscribe]);
39
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useKittyKeyboardProtocol.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState } from 'react';
8
+ import {
9
+ isKittyProtocolEnabled,
10
+ isKittyProtocolSupported,
11
+ } from '../utils/kittyProtocolDetector.js';
12
+
13
+ export interface KittyProtocolStatus {
14
+ supported: boolean;
15
+ enabled: boolean;
16
+ checking: boolean;
17
+ }
18
+
19
+ /**
20
+ * Hook that returns the cached Kitty keyboard protocol status.
21
+ * Detection is done once at app startup to avoid repeated queries.
22
+ */
23
+ export function useKittyKeyboardProtocol(): KittyProtocolStatus {
24
+ const [status] = useState<KittyProtocolStatus>({
25
+ supported: isKittyProtocolSupported(),
26
+ enabled: isKittyProtocolEnabled(),
27
+ checking: false,
28
+ });
29
+
30
+ return status;
31
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useLoadingIndicator.test.ts ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import { useLoadingIndicator } from './useLoadingIndicator.js';
10
+ import { StreamingState } from '../types.js';
11
+ import {
12
+ WITTY_LOADING_PHRASES,
13
+ PHRASE_CHANGE_INTERVAL_MS,
14
+ } from './usePhraseCycler.js';
15
+
16
+ describe('useLoadingIndicator', () => {
17
+ beforeEach(() => {
18
+ vi.useFakeTimers();
19
+ });
20
+
21
+ afterEach(() => {
22
+ vi.useRealTimers(); // Restore real timers after each test
23
+ act(() => vi.runOnlyPendingTimers);
24
+ });
25
+
26
+ it('should initialize with default values when Idle', () => {
27
+ const { result } = renderHook(() =>
28
+ useLoadingIndicator(StreamingState.Idle),
29
+ );
30
+ expect(result.current.elapsedTime).toBe(0);
31
+ expect(result.current.currentLoadingPhrase).toBe(WITTY_LOADING_PHRASES[0]);
32
+ });
33
+
34
+ it('should reflect values when Responding', async () => {
35
+ const { result } = renderHook(() =>
36
+ useLoadingIndicator(StreamingState.Responding),
37
+ );
38
+
39
+ // Initial state before timers advance
40
+ expect(result.current.elapsedTime).toBe(0);
41
+ expect(WITTY_LOADING_PHRASES).toContain(
42
+ result.current.currentLoadingPhrase,
43
+ );
44
+
45
+ await act(async () => {
46
+ await vi.advanceTimersByTimeAsync(PHRASE_CHANGE_INTERVAL_MS + 1);
47
+ });
48
+
49
+ // Phrase should cycle if PHRASE_CHANGE_INTERVAL_MS has passed
50
+ expect(WITTY_LOADING_PHRASES).toContain(
51
+ result.current.currentLoadingPhrase,
52
+ );
53
+ });
54
+
55
+ it('should show waiting phrase and retain elapsedTime when WaitingForConfirmation', async () => {
56
+ const { result, rerender } = renderHook(
57
+ ({ streamingState }) => useLoadingIndicator(streamingState),
58
+ { initialProps: { streamingState: StreamingState.Responding } },
59
+ );
60
+
61
+ await act(async () => {
62
+ await vi.advanceTimersByTimeAsync(60000);
63
+ });
64
+ expect(result.current.elapsedTime).toBe(60);
65
+
66
+ act(() => {
67
+ rerender({ streamingState: StreamingState.WaitingForConfirmation });
68
+ });
69
+
70
+ expect(result.current.currentLoadingPhrase).toBe(
71
+ 'Waiting for user confirmation...',
72
+ );
73
+ expect(result.current.elapsedTime).toBe(60); // Elapsed time should be retained
74
+
75
+ // Timer should not advance further
76
+ await act(async () => {
77
+ await vi.advanceTimersByTimeAsync(2000);
78
+ });
79
+ expect(result.current.elapsedTime).toBe(60);
80
+ });
81
+
82
+ it('should reset elapsedTime and use a witty phrase when transitioning from WaitingForConfirmation to Responding', async () => {
83
+ const { result, rerender } = renderHook(
84
+ ({ streamingState }) => useLoadingIndicator(streamingState),
85
+ { initialProps: { streamingState: StreamingState.Responding } },
86
+ );
87
+
88
+ await act(async () => {
89
+ await vi.advanceTimersByTimeAsync(5000); // 5s
90
+ });
91
+ expect(result.current.elapsedTime).toBe(5);
92
+
93
+ act(() => {
94
+ rerender({ streamingState: StreamingState.WaitingForConfirmation });
95
+ });
96
+ expect(result.current.elapsedTime).toBe(5);
97
+ expect(result.current.currentLoadingPhrase).toBe(
98
+ 'Waiting for user confirmation...',
99
+ );
100
+
101
+ act(() => {
102
+ rerender({ streamingState: StreamingState.Responding });
103
+ });
104
+ expect(result.current.elapsedTime).toBe(0); // Should reset
105
+ expect(WITTY_LOADING_PHRASES).toContain(
106
+ result.current.currentLoadingPhrase,
107
+ );
108
+
109
+ await act(async () => {
110
+ await vi.advanceTimersByTimeAsync(1000);
111
+ });
112
+ expect(result.current.elapsedTime).toBe(1);
113
+ });
114
+
115
+ it('should reset timer and phrase when streamingState changes from Responding to Idle', async () => {
116
+ const { result, rerender } = renderHook(
117
+ ({ streamingState }) => useLoadingIndicator(streamingState),
118
+ { initialProps: { streamingState: StreamingState.Responding } },
119
+ );
120
+
121
+ await act(async () => {
122
+ await vi.advanceTimersByTimeAsync(10000); // 10s
123
+ });
124
+ expect(result.current.elapsedTime).toBe(10);
125
+
126
+ act(() => {
127
+ rerender({ streamingState: StreamingState.Idle });
128
+ });
129
+
130
+ expect(result.current.elapsedTime).toBe(0);
131
+ expect(result.current.currentLoadingPhrase).toBe(WITTY_LOADING_PHRASES[0]);
132
+
133
+ // Timer should not advance
134
+ await act(async () => {
135
+ await vi.advanceTimersByTimeAsync(2000);
136
+ });
137
+ expect(result.current.elapsedTime).toBe(0);
138
+ });
139
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useLoadingIndicator.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { StreamingState } from '../types.js';
8
+ import { useTimer } from './useTimer.js';
9
+ import { usePhraseCycler } from './usePhraseCycler.js';
10
+ import { useState, useEffect, useRef } from 'react'; // Added useRef
11
+
12
+ export const useLoadingIndicator = (streamingState: StreamingState) => {
13
+ const [timerResetKey, setTimerResetKey] = useState(0);
14
+ const isTimerActive = streamingState === StreamingState.Responding;
15
+
16
+ const elapsedTimeFromTimer = useTimer(isTimerActive, timerResetKey);
17
+
18
+ const isPhraseCyclingActive = streamingState === StreamingState.Responding;
19
+ const isWaiting = streamingState === StreamingState.WaitingForConfirmation;
20
+ const currentLoadingPhrase = usePhraseCycler(
21
+ isPhraseCyclingActive,
22
+ isWaiting,
23
+ );
24
+
25
+ const [retainedElapsedTime, setRetainedElapsedTime] = useState(0);
26
+ const prevStreamingStateRef = useRef<StreamingState | null>(null);
27
+
28
+ useEffect(() => {
29
+ if (
30
+ prevStreamingStateRef.current === StreamingState.WaitingForConfirmation &&
31
+ streamingState === StreamingState.Responding
32
+ ) {
33
+ setTimerResetKey((prevKey) => prevKey + 1);
34
+ setRetainedElapsedTime(0); // Clear retained time when going back to responding
35
+ } else if (
36
+ streamingState === StreamingState.Idle &&
37
+ prevStreamingStateRef.current === StreamingState.Responding
38
+ ) {
39
+ setTimerResetKey((prevKey) => prevKey + 1); // Reset timer when becoming idle from responding
40
+ setRetainedElapsedTime(0);
41
+ } else if (streamingState === StreamingState.WaitingForConfirmation) {
42
+ // Capture the time when entering WaitingForConfirmation
43
+ // elapsedTimeFromTimer will hold the last value from when isTimerActive was true.
44
+ setRetainedElapsedTime(elapsedTimeFromTimer);
45
+ }
46
+
47
+ prevStreamingStateRef.current = streamingState;
48
+ }, [streamingState, elapsedTimeFromTimer]);
49
+
50
+ return {
51
+ elapsedTime:
52
+ streamingState === StreamingState.WaitingForConfirmation
53
+ ? retainedElapsedTime
54
+ : elapsedTimeFromTimer,
55
+ currentLoadingPhrase,
56
+ };
57
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useLogger.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useEffect } from 'react';
8
+ import { sessionId, Logger } from '@qwen-code/qwen-code-core';
9
+
10
+ /**
11
+ * Hook to manage the logger instance.
12
+ */
13
+ export const useLogger = () => {
14
+ const [logger, setLogger] = useState<Logger | null>(null);
15
+
16
+ useEffect(() => {
17
+ const newLogger = new Logger(sessionId);
18
+ /**
19
+ * Start async initialization, no need to await. Using await slows down the
20
+ * time from launch to see the gemini-cli prompt and it's better to not save
21
+ * messages than for the cli to hanging waiting for the logger to loading.
22
+ */
23
+ newLogger
24
+ .initialize()
25
+ .then(() => {
26
+ setLogger(newLogger);
27
+ })
28
+ .catch(() => {});
29
+ }, []);
30
+
31
+ return logger;
32
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useMessageQueue.test.ts ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import { useMessageQueue } from './useMessageQueue.js';
10
+ import { StreamingState } from '../types.js';
11
+
12
+ describe('useMessageQueue', () => {
13
+ let mockSubmitQuery: ReturnType<typeof vi.fn>;
14
+
15
+ beforeEach(() => {
16
+ mockSubmitQuery = vi.fn();
17
+ vi.useFakeTimers();
18
+ });
19
+
20
+ afterEach(() => {
21
+ vi.useRealTimers();
22
+ vi.clearAllMocks();
23
+ });
24
+
25
+ it('should initialize with empty queue', () => {
26
+ const { result } = renderHook(() =>
27
+ useMessageQueue({
28
+ streamingState: StreamingState.Idle,
29
+ submitQuery: mockSubmitQuery,
30
+ }),
31
+ );
32
+
33
+ expect(result.current.messageQueue).toEqual([]);
34
+ expect(result.current.getQueuedMessagesText()).toBe('');
35
+ });
36
+
37
+ it('should add messages to queue', () => {
38
+ const { result } = renderHook(() =>
39
+ useMessageQueue({
40
+ streamingState: StreamingState.Responding,
41
+ submitQuery: mockSubmitQuery,
42
+ }),
43
+ );
44
+
45
+ act(() => {
46
+ result.current.addMessage('Test message 1');
47
+ result.current.addMessage('Test message 2');
48
+ });
49
+
50
+ expect(result.current.messageQueue).toEqual([
51
+ 'Test message 1',
52
+ 'Test message 2',
53
+ ]);
54
+ });
55
+
56
+ it('should filter out empty messages', () => {
57
+ const { result } = renderHook(() =>
58
+ useMessageQueue({
59
+ streamingState: StreamingState.Responding,
60
+ submitQuery: mockSubmitQuery,
61
+ }),
62
+ );
63
+
64
+ act(() => {
65
+ result.current.addMessage('Valid message');
66
+ result.current.addMessage(' '); // Only whitespace
67
+ result.current.addMessage(''); // Empty
68
+ result.current.addMessage('Another valid message');
69
+ });
70
+
71
+ expect(result.current.messageQueue).toEqual([
72
+ 'Valid message',
73
+ 'Another valid message',
74
+ ]);
75
+ });
76
+
77
+ it('should clear queue', () => {
78
+ const { result } = renderHook(() =>
79
+ useMessageQueue({
80
+ streamingState: StreamingState.Responding,
81
+ submitQuery: mockSubmitQuery,
82
+ }),
83
+ );
84
+
85
+ act(() => {
86
+ result.current.addMessage('Test message');
87
+ });
88
+
89
+ expect(result.current.messageQueue).toEqual(['Test message']);
90
+
91
+ act(() => {
92
+ result.current.clearQueue();
93
+ });
94
+
95
+ expect(result.current.messageQueue).toEqual([]);
96
+ });
97
+
98
+ it('should return queued messages as text with double newlines', () => {
99
+ const { result } = renderHook(() =>
100
+ useMessageQueue({
101
+ streamingState: StreamingState.Responding,
102
+ submitQuery: mockSubmitQuery,
103
+ }),
104
+ );
105
+
106
+ act(() => {
107
+ result.current.addMessage('Message 1');
108
+ result.current.addMessage('Message 2');
109
+ result.current.addMessage('Message 3');
110
+ });
111
+
112
+ expect(result.current.getQueuedMessagesText()).toBe(
113
+ 'Message 1\n\nMessage 2\n\nMessage 3',
114
+ );
115
+ });
116
+
117
+ it('should auto-submit queued messages when transitioning to Idle', () => {
118
+ const { result, rerender } = renderHook(
119
+ ({ streamingState }) =>
120
+ useMessageQueue({
121
+ streamingState,
122
+ submitQuery: mockSubmitQuery,
123
+ }),
124
+ {
125
+ initialProps: { streamingState: StreamingState.Responding },
126
+ },
127
+ );
128
+
129
+ // Add some messages
130
+ act(() => {
131
+ result.current.addMessage('Message 1');
132
+ result.current.addMessage('Message 2');
133
+ });
134
+
135
+ expect(result.current.messageQueue).toEqual(['Message 1', 'Message 2']);
136
+
137
+ // Transition to Idle
138
+ rerender({ streamingState: StreamingState.Idle });
139
+
140
+ expect(mockSubmitQuery).toHaveBeenCalledWith('Message 1\n\nMessage 2');
141
+ expect(result.current.messageQueue).toEqual([]);
142
+ });
143
+
144
+ it('should not auto-submit when queue is empty', () => {
145
+ const { rerender } = renderHook(
146
+ ({ streamingState }) =>
147
+ useMessageQueue({
148
+ streamingState,
149
+ submitQuery: mockSubmitQuery,
150
+ }),
151
+ {
152
+ initialProps: { streamingState: StreamingState.Responding },
153
+ },
154
+ );
155
+
156
+ // Transition to Idle with empty queue
157
+ rerender({ streamingState: StreamingState.Idle });
158
+
159
+ expect(mockSubmitQuery).not.toHaveBeenCalled();
160
+ });
161
+
162
+ it('should not auto-submit when not transitioning to Idle', () => {
163
+ const { result, rerender } = renderHook(
164
+ ({ streamingState }) =>
165
+ useMessageQueue({
166
+ streamingState,
167
+ submitQuery: mockSubmitQuery,
168
+ }),
169
+ {
170
+ initialProps: { streamingState: StreamingState.Responding },
171
+ },
172
+ );
173
+
174
+ // Add messages
175
+ act(() => {
176
+ result.current.addMessage('Message 1');
177
+ });
178
+
179
+ // Transition to WaitingForConfirmation (not Idle)
180
+ rerender({ streamingState: StreamingState.WaitingForConfirmation });
181
+
182
+ expect(mockSubmitQuery).not.toHaveBeenCalled();
183
+ expect(result.current.messageQueue).toEqual(['Message 1']);
184
+ });
185
+
186
+ it('should handle multiple state transitions correctly', () => {
187
+ const { result, rerender } = renderHook(
188
+ ({ streamingState }) =>
189
+ useMessageQueue({
190
+ streamingState,
191
+ submitQuery: mockSubmitQuery,
192
+ }),
193
+ {
194
+ initialProps: { streamingState: StreamingState.Idle },
195
+ },
196
+ );
197
+
198
+ // Start responding
199
+ rerender({ streamingState: StreamingState.Responding });
200
+
201
+ // Add messages while responding
202
+ act(() => {
203
+ result.current.addMessage('First batch');
204
+ });
205
+
206
+ // Go back to idle - should submit
207
+ rerender({ streamingState: StreamingState.Idle });
208
+
209
+ expect(mockSubmitQuery).toHaveBeenCalledWith('First batch');
210
+ expect(result.current.messageQueue).toEqual([]);
211
+
212
+ // Start responding again
213
+ rerender({ streamingState: StreamingState.Responding });
214
+
215
+ // Add more messages
216
+ act(() => {
217
+ result.current.addMessage('Second batch');
218
+ });
219
+
220
+ // Go back to idle - should submit again
221
+ rerender({ streamingState: StreamingState.Idle });
222
+
223
+ expect(mockSubmitQuery).toHaveBeenCalledWith('Second batch');
224
+ expect(mockSubmitQuery).toHaveBeenCalledTimes(2);
225
+ });
226
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useMessageQueue.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useCallback, useEffect, useState } from 'react';
8
+ import { StreamingState } from '../types.js';
9
+
10
+ export interface UseMessageQueueOptions {
11
+ streamingState: StreamingState;
12
+ submitQuery: (query: string) => void;
13
+ }
14
+
15
+ export interface UseMessageQueueReturn {
16
+ messageQueue: string[];
17
+ addMessage: (message: string) => void;
18
+ clearQueue: () => void;
19
+ getQueuedMessagesText: () => string;
20
+ }
21
+
22
+ /**
23
+ * Hook for managing message queuing during streaming responses.
24
+ * Allows users to queue messages while the AI is responding and automatically
25
+ * sends them when streaming completes.
26
+ */
27
+ export function useMessageQueue({
28
+ streamingState,
29
+ submitQuery,
30
+ }: UseMessageQueueOptions): UseMessageQueueReturn {
31
+ const [messageQueue, setMessageQueue] = useState<string[]>([]);
32
+
33
+ // Add a message to the queue
34
+ const addMessage = useCallback((message: string) => {
35
+ const trimmedMessage = message.trim();
36
+ if (trimmedMessage.length > 0) {
37
+ setMessageQueue((prev) => [...prev, trimmedMessage]);
38
+ }
39
+ }, []);
40
+
41
+ // Clear the entire queue
42
+ const clearQueue = useCallback(() => {
43
+ setMessageQueue([]);
44
+ }, []);
45
+
46
+ // Get all queued messages as a single text string
47
+ const getQueuedMessagesText = useCallback(() => {
48
+ if (messageQueue.length === 0) return '';
49
+ return messageQueue.join('\n\n');
50
+ }, [messageQueue]);
51
+
52
+ // Process queued messages when streaming becomes idle
53
+ useEffect(() => {
54
+ if (streamingState === StreamingState.Idle && messageQueue.length > 0) {
55
+ // Combine all messages with double newlines for clarity
56
+ const combinedMessage = messageQueue.join('\n\n');
57
+ // Clear the queue and submit
58
+ setMessageQueue([]);
59
+ submitQuery(combinedMessage);
60
+ }
61
+ }, [streamingState, messageQueue, submitQuery]);
62
+
63
+ return {
64
+ messageQueue,
65
+ addMessage,
66
+ clearQueue,
67
+ getQueuedMessagesText,
68
+ };
69
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/usePhraseCycler.test.ts ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import {
10
+ usePhraseCycler,
11
+ WITTY_LOADING_PHRASES,
12
+ PHRASE_CHANGE_INTERVAL_MS,
13
+ } from './usePhraseCycler.js';
14
+
15
+ describe('usePhraseCycler', () => {
16
+ beforeEach(() => {
17
+ vi.useFakeTimers();
18
+ });
19
+
20
+ afterEach(() => {
21
+ vi.restoreAllMocks();
22
+ });
23
+
24
+ it('should initialize with the first witty phrase when not active and not waiting', () => {
25
+ const { result } = renderHook(() => usePhraseCycler(false, false));
26
+ expect(result.current).toBe(WITTY_LOADING_PHRASES[0]);
27
+ });
28
+
29
+ it('should show "Waiting for user confirmation..." when isWaiting is true', () => {
30
+ const { result, rerender } = renderHook(
31
+ ({ isActive, isWaiting }) => usePhraseCycler(isActive, isWaiting),
32
+ { initialProps: { isActive: true, isWaiting: false } },
33
+ );
34
+ rerender({ isActive: true, isWaiting: true });
35
+ expect(result.current).toBe('Waiting for user confirmation...');
36
+ });
37
+
38
+ it('should not cycle phrases if isActive is false and not waiting', () => {
39
+ const { result } = renderHook(() => usePhraseCycler(false, false));
40
+ act(() => {
41
+ vi.advanceTimersByTime(PHRASE_CHANGE_INTERVAL_MS * 2);
42
+ });
43
+ expect(result.current).toBe(WITTY_LOADING_PHRASES[0]);
44
+ });
45
+
46
+ it('should cycle through witty phrases when isActive is true and not waiting', () => {
47
+ const { result } = renderHook(() => usePhraseCycler(true, false));
48
+ // Initial phrase should be one of the witty phrases
49
+ expect(WITTY_LOADING_PHRASES).toContain(result.current);
50
+ const _initialPhrase = result.current;
51
+
52
+ act(() => {
53
+ vi.advanceTimersByTime(PHRASE_CHANGE_INTERVAL_MS);
54
+ });
55
+ // Phrase should change and be one of the witty phrases
56
+ expect(WITTY_LOADING_PHRASES).toContain(result.current);
57
+
58
+ const _secondPhrase = result.current;
59
+ act(() => {
60
+ vi.advanceTimersByTime(PHRASE_CHANGE_INTERVAL_MS);
61
+ });
62
+ expect(WITTY_LOADING_PHRASES).toContain(result.current);
63
+ });
64
+
65
+ it('should reset to a witty phrase when isActive becomes true after being false (and not waiting)', () => {
66
+ // Ensure there are at least two phrases for this test to be meaningful.
67
+ if (WITTY_LOADING_PHRASES.length < 2) {
68
+ return;
69
+ }
70
+
71
+ // Mock Math.random to make the test deterministic.
72
+ let callCount = 0;
73
+ vi.spyOn(Math, 'random').mockImplementation(() => {
74
+ // Cycle through 0, 1, 0, 1, ...
75
+ const val = callCount % 2;
76
+ callCount++;
77
+ return val / WITTY_LOADING_PHRASES.length;
78
+ });
79
+
80
+ const { result, rerender } = renderHook(
81
+ ({ isActive, isWaiting }) => usePhraseCycler(isActive, isWaiting),
82
+ { initialProps: { isActive: false, isWaiting: false } },
83
+ );
84
+
85
+ // Activate
86
+ rerender({ isActive: true, isWaiting: false });
87
+ const firstActivePhrase = result.current;
88
+ expect(WITTY_LOADING_PHRASES).toContain(firstActivePhrase);
89
+ // With our mock, this should be the first phrase.
90
+ expect(firstActivePhrase).toBe(WITTY_LOADING_PHRASES[0]);
91
+
92
+ act(() => {
93
+ vi.advanceTimersByTime(PHRASE_CHANGE_INTERVAL_MS);
94
+ });
95
+
96
+ // Phrase should change to the second phrase.
97
+ expect(result.current).not.toBe(firstActivePhrase);
98
+ expect(result.current).toBe(WITTY_LOADING_PHRASES[1]);
99
+
100
+ // Set to inactive - should reset to the default initial phrase
101
+ rerender({ isActive: false, isWaiting: false });
102
+ expect(result.current).toBe(WITTY_LOADING_PHRASES[0]);
103
+
104
+ // Set back to active - should pick a random witty phrase (which our mock controls)
105
+ act(() => {
106
+ rerender({ isActive: true, isWaiting: false });
107
+ });
108
+ // The random mock will now return 0, so it should be the first phrase again.
109
+ expect(result.current).toBe(WITTY_LOADING_PHRASES[0]);
110
+ });
111
+
112
+ it('should clear phrase interval on unmount when active', () => {
113
+ const { unmount } = renderHook(() => usePhraseCycler(true, false));
114
+ const clearIntervalSpy = vi.spyOn(global, 'clearInterval');
115
+ unmount();
116
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
117
+ });
118
+
119
+ it('should reset to a witty phrase when transitioning from waiting to active', () => {
120
+ const { result, rerender } = renderHook(
121
+ ({ isActive, isWaiting }) => usePhraseCycler(isActive, isWaiting),
122
+ { initialProps: { isActive: true, isWaiting: false } },
123
+ );
124
+
125
+ const _initialPhrase = result.current;
126
+ expect(WITTY_LOADING_PHRASES).toContain(_initialPhrase);
127
+
128
+ // Cycle to a different phrase (potentially)
129
+ act(() => {
130
+ vi.advanceTimersByTime(PHRASE_CHANGE_INTERVAL_MS);
131
+ });
132
+ if (WITTY_LOADING_PHRASES.length > 1) {
133
+ // This check is probabilistic with random selection
134
+ }
135
+ expect(WITTY_LOADING_PHRASES).toContain(result.current);
136
+
137
+ // Go to waiting state
138
+ rerender({ isActive: false, isWaiting: true });
139
+ expect(result.current).toBe('Waiting for user confirmation...');
140
+
141
+ // Go back to active cycling - should pick a random witty phrase
142
+ rerender({ isActive: true, isWaiting: false });
143
+ expect(WITTY_LOADING_PHRASES).toContain(result.current);
144
+ });
145
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/usePhraseCycler.ts ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useEffect, useRef } from 'react';
8
+
9
+ export const WITTY_LOADING_PHRASES = [
10
+ "I'm Feeling Lucky",
11
+ 'Shipping awesomeness... ',
12
+ 'Painting the serifs back on...',
13
+ 'Navigating the slime mold...',
14
+ 'Consulting the digital spirits...',
15
+ 'Reticulating splines...',
16
+ 'Warming up the AI hamsters...',
17
+ 'Asking the magic conch shell...',
18
+ 'Generating witty retort...',
19
+ 'Polishing the algorithms...',
20
+ "Don't rush perfection (or my code)...",
21
+ 'Brewing fresh bytes...',
22
+ 'Counting electrons...',
23
+ 'Engaging cognitive processors...',
24
+ 'Checking for syntax errors in the universe...',
25
+ 'One moment, optimizing humor...',
26
+ 'Shuffling punchlines...',
27
+ 'Untangling neural nets...',
28
+ 'Compiling brilliance...',
29
+ 'Loading wit.exe...',
30
+ 'Summoning the cloud of wisdom...',
31
+ 'Preparing a witty response...',
32
+ "Just a sec, I'm debugging reality...",
33
+ 'Confuzzling the options...',
34
+ 'Tuning the cosmic frequencies...',
35
+ 'Crafting a response worthy of your patience...',
36
+ 'Compiling the 1s and 0s...',
37
+ 'Resolving dependencies... and existential crises...',
38
+ 'Defragmenting memories... both RAM and personal...',
39
+ 'Rebooting the humor module...',
40
+ 'Caching the essentials (mostly cat memes)...',
41
+ 'Optimizing for ludicrous speed',
42
+ "Swapping bits... don't tell the bytes...",
43
+ 'Garbage collecting... be right back...',
44
+ 'Assembling the interwebs...',
45
+ 'Converting coffee into code...',
46
+ 'Updating the syntax for reality...',
47
+ 'Rewiring the synapses...',
48
+ 'Looking for a misplaced semicolon...',
49
+ "Greasin' the cogs of the machine...",
50
+ 'Pre-heating the servers...',
51
+ 'Calibrating the flux capacitor...',
52
+ 'Engaging the improbability drive...',
53
+ 'Channeling the Force...',
54
+ 'Aligning the stars for optimal response...',
55
+ 'So say we all...',
56
+ 'Loading the next great idea...',
57
+ "Just a moment, I'm in the zone...",
58
+ 'Preparing to dazzle you with brilliance...',
59
+ "Just a tick, I'm polishing my wit...",
60
+ "Hold tight, I'm crafting a masterpiece...",
61
+ "Just a jiffy, I'm debugging the universe...",
62
+ "Just a moment, I'm aligning the pixels...",
63
+ "Just a sec, I'm optimizing the humor...",
64
+ "Just a moment, I'm tuning the algorithms...",
65
+ 'Warp speed engaged...',
66
+ 'Mining for more Dilithium crystals...',
67
+ "Don't panic...",
68
+ 'Following the white rabbit...',
69
+ 'The truth is in here... somewhere...',
70
+ 'Blowing on the cartridge...',
71
+ 'Loading... Do a barrel roll!',
72
+ 'Waiting for the respawn...',
73
+ 'Finishing the Kessel Run in less than 12 parsecs...',
74
+ "The cake is not a lie, it's just still loading...",
75
+ 'Fiddling with the character creation screen...',
76
+ "Just a moment, I'm finding the right meme...",
77
+ "Pressing 'A' to continue...",
78
+ 'Herding digital cats...',
79
+ 'Polishing the pixels...',
80
+ 'Finding a suitable loading screen pun...',
81
+ 'Distracting you with this witty phrase...',
82
+ 'Almost there... probably...',
83
+ 'Our hamsters are working as fast as they can...',
84
+ 'Giving Cloudy a pat on the head...',
85
+ 'Petting the cat...',
86
+ 'Rickrolling my boss...',
87
+ 'Never gonna give you up, never gonna let you down...',
88
+ 'Slapping the bass...',
89
+ 'Tasting the snozberries...',
90
+ "I'm going the distance, I'm going for speed...",
91
+ 'Is this the real life? Is this just fantasy?...',
92
+ "I've got a good feeling about this...",
93
+ 'Poking the bear...',
94
+ 'Doing research on the latest memes...',
95
+ 'Figuring out how to make this more witty...',
96
+ 'Hmmm... let me think...',
97
+ 'What do you call a fish with no eyes? A fsh...',
98
+ 'Why did the computer go to therapy? It had too many bytes...',
99
+ "Why don't programmers like nature? It has too many bugs...",
100
+ 'Why do programmers prefer dark mode? Because light attracts bugs...',
101
+ 'Why did the developer go broke? Because they used up all their cache...',
102
+ "What can you do with a broken pencil? Nothing, it's pointless...",
103
+ 'Applying percussive maintenance...',
104
+ 'Searching for the correct USB orientation...',
105
+ 'Ensuring the magic smoke stays inside the wires...',
106
+ 'Rewriting in Rust for no particular reason...',
107
+ 'Trying to exit Vim...',
108
+ 'Spinning up the hamster wheel...',
109
+ "That's not a bug, it's an undocumented feature...",
110
+ 'Engage.',
111
+ "I'll be back... with an answer.",
112
+ 'My other process is a TARDIS...',
113
+ 'Communing with the machine spirit...',
114
+ 'Letting the thoughts marinate...',
115
+ 'Just remembered where I put my keys...',
116
+ 'Pondering the orb...',
117
+ "I've seen things you people wouldn't believe... like a user who reads loading messages.",
118
+ 'Initiating thoughtful gaze...',
119
+ "What's a computer's favorite snack? Microchips.",
120
+ "Why do Java developers wear glasses? Because they don't C#.",
121
+ 'Charging the laser... pew pew!',
122
+ 'Dividing by zero... just kidding!',
123
+ 'Looking for an adult superviso... I mean, processing.',
124
+ 'Making it go beep boop.',
125
+ 'Buffering... because even AIs need a moment.',
126
+ 'Entangling quantum particles for a faster response...',
127
+ 'Polishing the chrome... on the algorithms.',
128
+ 'Are you not entertained? (Working on it!)',
129
+ 'Summoning the code gremlins... to help, of course.',
130
+ 'Just waiting for the dial-up tone to finish...',
131
+ 'Recalibrating the humor-o-meter.',
132
+ 'My other loading screen is even funnier.',
133
+ "Pretty sure there's a cat walking on the keyboard somewhere...",
134
+ 'Enhancing... Enhancing... Still loading.',
135
+ "It's not a bug, it's a feature... of this loading screen.",
136
+ 'Have you tried turning it off and on again? (The loading screen, not me.)',
137
+ 'Constructing additional pylons...',
138
+ 'New line? That’s Ctrl+J.',
139
+ ];
140
+
141
+ export const PHRASE_CHANGE_INTERVAL_MS = 15000;
142
+
143
+ /**
144
+ * Custom hook to manage cycling through loading phrases.
145
+ * @param isActive Whether the phrase cycling should be active.
146
+ * @param isWaiting Whether to show a specific waiting phrase.
147
+ * @returns The current loading phrase.
148
+ */
149
+ export const usePhraseCycler = (isActive: boolean, isWaiting: boolean) => {
150
+ const [currentLoadingPhrase, setCurrentLoadingPhrase] = useState(
151
+ WITTY_LOADING_PHRASES[0],
152
+ );
153
+ const phraseIntervalRef = useRef<NodeJS.Timeout | null>(null);
154
+
155
+ useEffect(() => {
156
+ if (isWaiting) {
157
+ setCurrentLoadingPhrase('Waiting for user confirmation...');
158
+ if (phraseIntervalRef.current) {
159
+ clearInterval(phraseIntervalRef.current);
160
+ phraseIntervalRef.current = null;
161
+ }
162
+ } else if (isActive) {
163
+ if (phraseIntervalRef.current) {
164
+ clearInterval(phraseIntervalRef.current);
165
+ }
166
+ // Select an initial random phrase
167
+ const initialRandomIndex = Math.floor(
168
+ Math.random() * WITTY_LOADING_PHRASES.length,
169
+ );
170
+ setCurrentLoadingPhrase(WITTY_LOADING_PHRASES[initialRandomIndex]);
171
+
172
+ phraseIntervalRef.current = setInterval(() => {
173
+ // Select a new random phrase
174
+ const randomIndex = Math.floor(
175
+ Math.random() * WITTY_LOADING_PHRASES.length,
176
+ );
177
+ setCurrentLoadingPhrase(WITTY_LOADING_PHRASES[randomIndex]);
178
+ }, PHRASE_CHANGE_INTERVAL_MS);
179
+ } else {
180
+ // Idle or other states, clear the phrase interval
181
+ // and reset to the first phrase for next active state.
182
+ if (phraseIntervalRef.current) {
183
+ clearInterval(phraseIntervalRef.current);
184
+ phraseIntervalRef.current = null;
185
+ }
186
+ setCurrentLoadingPhrase(WITTY_LOADING_PHRASES[0]);
187
+ }
188
+
189
+ return () => {
190
+ if (phraseIntervalRef.current) {
191
+ clearInterval(phraseIntervalRef.current);
192
+ phraseIntervalRef.current = null;
193
+ }
194
+ };
195
+ }, [isActive, isWaiting]);
196
+
197
+ return currentLoadingPhrase;
198
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/usePrivacySettings.test.ts ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
8
+ import { renderHook, waitFor } from '@testing-library/react';
9
+ import {
10
+ Config,
11
+ CodeAssistServer,
12
+ LoggingContentGenerator,
13
+ UserTierId,
14
+ GeminiClient,
15
+ ContentGenerator,
16
+ } from '@qwen-code/qwen-code-core';
17
+ import { OAuth2Client } from 'google-auth-library';
18
+ import { usePrivacySettings } from './usePrivacySettings.js';
19
+
20
+ // Mock the dependencies
21
+ vi.mock('@qwen-code/qwen-code-core', () => {
22
+ // Mock classes for instanceof checks
23
+ class MockCodeAssistServer {
24
+ projectId = 'test-project-id';
25
+ loadCodeAssist = vi.fn();
26
+ getCodeAssistGlobalUserSetting = vi.fn();
27
+ setCodeAssistGlobalUserSetting = vi.fn();
28
+
29
+ constructor(
30
+ _client?: GeminiClient,
31
+ _projectId?: string,
32
+ _httpOptions?: Record<string, unknown>,
33
+ _sessionId?: string,
34
+ _userTier?: UserTierId,
35
+ ) {}
36
+ }
37
+
38
+ class MockLoggingContentGenerator {
39
+ getWrapped = vi.fn();
40
+
41
+ constructor(
42
+ _wrapped?: ContentGenerator,
43
+ _config?: Record<string, unknown>,
44
+ ) {}
45
+ }
46
+
47
+ return {
48
+ Config: vi.fn(),
49
+ CodeAssistServer: MockCodeAssistServer,
50
+ LoggingContentGenerator: MockLoggingContentGenerator,
51
+ GeminiClient: vi.fn(),
52
+ UserTierId: {
53
+ FREE: 'free-tier',
54
+ LEGACY: 'legacy-tier',
55
+ STANDARD: 'standard-tier',
56
+ },
57
+ };
58
+ });
59
+
60
+ describe('usePrivacySettings', () => {
61
+ let mockConfig: Config;
62
+ let mockClient: GeminiClient;
63
+ let mockCodeAssistServer: CodeAssistServer;
64
+ let mockLoggingContentGenerator: LoggingContentGenerator;
65
+
66
+ beforeEach(() => {
67
+ vi.clearAllMocks();
68
+
69
+ // Create mock CodeAssistServer instance
70
+ mockCodeAssistServer = new CodeAssistServer(
71
+ null as unknown as OAuth2Client,
72
+ 'test-project-id',
73
+ ) as unknown as CodeAssistServer;
74
+ (
75
+ mockCodeAssistServer.loadCodeAssist as ReturnType<typeof vi.fn>
76
+ ).mockResolvedValue({
77
+ currentTier: { id: UserTierId.FREE },
78
+ });
79
+ (
80
+ mockCodeAssistServer.getCodeAssistGlobalUserSetting as ReturnType<
81
+ typeof vi.fn
82
+ >
83
+ ).mockResolvedValue({
84
+ freeTierDataCollectionOptin: true,
85
+ });
86
+ (
87
+ mockCodeAssistServer.setCodeAssistGlobalUserSetting as ReturnType<
88
+ typeof vi.fn
89
+ >
90
+ ).mockResolvedValue({
91
+ freeTierDataCollectionOptin: false,
92
+ });
93
+
94
+ // Create mock LoggingContentGenerator that wraps the CodeAssistServer
95
+ mockLoggingContentGenerator = new LoggingContentGenerator(
96
+ mockCodeAssistServer,
97
+ null as unknown as Config,
98
+ ) as unknown as LoggingContentGenerator;
99
+ (
100
+ mockLoggingContentGenerator.getWrapped as ReturnType<typeof vi.fn>
101
+ ).mockReturnValue(mockCodeAssistServer);
102
+
103
+ // Create mock GeminiClient
104
+ mockClient = {
105
+ getContentGenerator: vi.fn().mockReturnValue(mockLoggingContentGenerator),
106
+ } as unknown as GeminiClient;
107
+
108
+ // Create mock Config
109
+ mockConfig = {
110
+ getGeminiClient: vi.fn().mockReturnValue(mockClient),
111
+ } as unknown as Config;
112
+ });
113
+
114
+ it('should handle LoggingContentGenerator wrapper correctly and not throw "Oauth not being used" error', async () => {
115
+ const { result } = renderHook(() => usePrivacySettings(mockConfig));
116
+
117
+ // Initial state should be loading
118
+ expect(result.current.privacyState.isLoading).toBe(true);
119
+ expect(result.current.privacyState.error).toBeUndefined();
120
+
121
+ // Wait for the hook to complete
122
+ await waitFor(() => {
123
+ expect(result.current.privacyState.isLoading).toBe(false);
124
+ });
125
+
126
+ // Should not have the "Oauth not being used" error
127
+ expect(result.current.privacyState.error).toBeUndefined();
128
+ expect(result.current.privacyState.isFreeTier).toBe(true);
129
+ expect(result.current.privacyState.dataCollectionOptIn).toBe(true);
130
+
131
+ // Verify that getWrapped was called to unwrap the LoggingContentGenerator
132
+ expect(mockLoggingContentGenerator.getWrapped).toHaveBeenCalled();
133
+ });
134
+
135
+ it('should work with direct CodeAssistServer (no wrapper)', async () => {
136
+ // Test case where the content generator is directly a CodeAssistServer
137
+ const directServer = new CodeAssistServer(
138
+ null as unknown as OAuth2Client,
139
+ 'test-project-id',
140
+ ) as unknown as CodeAssistServer;
141
+ (directServer.loadCodeAssist as ReturnType<typeof vi.fn>).mockResolvedValue(
142
+ {
143
+ currentTier: { id: UserTierId.FREE },
144
+ },
145
+ );
146
+ (
147
+ directServer.getCodeAssistGlobalUserSetting as ReturnType<typeof vi.fn>
148
+ ).mockResolvedValue({
149
+ freeTierDataCollectionOptin: true,
150
+ });
151
+
152
+ mockClient.getContentGenerator = vi.fn().mockReturnValue(directServer);
153
+
154
+ const { result } = renderHook(() => usePrivacySettings(mockConfig));
155
+
156
+ await waitFor(() => {
157
+ expect(result.current.privacyState.isLoading).toBe(false);
158
+ });
159
+
160
+ expect(result.current.privacyState.error).toBeUndefined();
161
+ expect(result.current.privacyState.isFreeTier).toBe(true);
162
+ expect(result.current.privacyState.dataCollectionOptIn).toBe(true);
163
+ });
164
+
165
+ it('should handle paid tier users correctly', async () => {
166
+ // Mock paid tier response
167
+ (
168
+ mockCodeAssistServer.loadCodeAssist as ReturnType<typeof vi.fn>
169
+ ).mockResolvedValue({
170
+ currentTier: { id: UserTierId.STANDARD },
171
+ });
172
+
173
+ const { result } = renderHook(() => usePrivacySettings(mockConfig));
174
+
175
+ await waitFor(() => {
176
+ expect(result.current.privacyState.isLoading).toBe(false);
177
+ });
178
+
179
+ expect(result.current.privacyState.error).toBeUndefined();
180
+ expect(result.current.privacyState.isFreeTier).toBe(false);
181
+ expect(result.current.privacyState.dataCollectionOptIn).toBeUndefined();
182
+ });
183
+
184
+ it('should throw error when content generator is not a CodeAssistServer', async () => {
185
+ // Mock a non-CodeAssistServer content generator
186
+ const mockOtherGenerator = { someOtherMethod: vi.fn() };
187
+ (
188
+ mockLoggingContentGenerator.getWrapped as ReturnType<typeof vi.fn>
189
+ ).mockReturnValue(mockOtherGenerator);
190
+
191
+ const { result } = renderHook(() => usePrivacySettings(mockConfig));
192
+
193
+ await waitFor(() => {
194
+ expect(result.current.privacyState.isLoading).toBe(false);
195
+ });
196
+
197
+ expect(result.current.privacyState.error).toBe('Oauth not being used');
198
+ });
199
+
200
+ it('should throw error when CodeAssistServer has no projectId', async () => {
201
+ // Mock CodeAssistServer without projectId
202
+ const mockServerNoProject = {
203
+ ...mockCodeAssistServer,
204
+ projectId: undefined,
205
+ };
206
+ (
207
+ mockLoggingContentGenerator.getWrapped as ReturnType<typeof vi.fn>
208
+ ).mockReturnValue(mockServerNoProject);
209
+
210
+ const { result } = renderHook(() => usePrivacySettings(mockConfig));
211
+
212
+ await waitFor(() => {
213
+ expect(result.current.privacyState.isLoading).toBe(false);
214
+ });
215
+
216
+ expect(result.current.privacyState.error).toBe('Oauth not being used');
217
+ });
218
+
219
+ it('should update data collection opt-in setting', async () => {
220
+ const { result } = renderHook(() => usePrivacySettings(mockConfig));
221
+
222
+ // Wait for initial load
223
+ await waitFor(() => {
224
+ expect(result.current.privacyState.isLoading).toBe(false);
225
+ });
226
+
227
+ // Update the setting
228
+ await result.current.updateDataCollectionOptIn(false);
229
+
230
+ // Wait for update to complete
231
+ await waitFor(() => {
232
+ expect(result.current.privacyState.dataCollectionOptIn).toBe(false);
233
+ });
234
+
235
+ expect(
236
+ mockCodeAssistServer.setCodeAssistGlobalUserSetting,
237
+ ).toHaveBeenCalledWith({
238
+ cloudaicompanionProject: 'test-project-id',
239
+ freeTierDataCollectionOptin: false,
240
+ });
241
+ });
242
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/usePrivacySettings.ts ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {
9
+ Config,
10
+ CodeAssistServer,
11
+ UserTierId,
12
+ LoggingContentGenerator,
13
+ } from '@qwen-code/qwen-code-core';
14
+
15
+ export interface PrivacyState {
16
+ isLoading: boolean;
17
+ error?: string;
18
+ isFreeTier?: boolean;
19
+ dataCollectionOptIn?: boolean;
20
+ }
21
+
22
+ export const usePrivacySettings = (config: Config) => {
23
+ const [privacyState, setPrivacyState] = useState<PrivacyState>({
24
+ isLoading: true,
25
+ });
26
+
27
+ useEffect(() => {
28
+ const fetchInitialState = async () => {
29
+ setPrivacyState({
30
+ isLoading: true,
31
+ });
32
+ try {
33
+ const server = getCodeAssistServer(config);
34
+ const tier = await getTier(server);
35
+ if (tier !== UserTierId.FREE) {
36
+ // We don't need to fetch opt-out info since non-free tier
37
+ // data gathering is already worked out some other way.
38
+ setPrivacyState({
39
+ isLoading: false,
40
+ isFreeTier: false,
41
+ });
42
+ return;
43
+ }
44
+
45
+ const optIn = await getRemoteDataCollectionOptIn(server);
46
+ setPrivacyState({
47
+ isLoading: false,
48
+ isFreeTier: true,
49
+ dataCollectionOptIn: optIn,
50
+ });
51
+ } catch (e) {
52
+ setPrivacyState({
53
+ isLoading: false,
54
+ error: e instanceof Error ? e.message : String(e),
55
+ });
56
+ }
57
+ };
58
+ fetchInitialState();
59
+ }, [config]);
60
+
61
+ const updateDataCollectionOptIn = useCallback(
62
+ async (optIn: boolean) => {
63
+ try {
64
+ const server = getCodeAssistServer(config);
65
+ const updatedOptIn = await setRemoteDataCollectionOptIn(server, optIn);
66
+ setPrivacyState({
67
+ isLoading: false,
68
+ isFreeTier: true,
69
+ dataCollectionOptIn: updatedOptIn,
70
+ });
71
+ } catch (e) {
72
+ setPrivacyState({
73
+ isLoading: false,
74
+ error: e instanceof Error ? e.message : String(e),
75
+ });
76
+ }
77
+ },
78
+ [config],
79
+ );
80
+
81
+ return {
82
+ privacyState,
83
+ updateDataCollectionOptIn,
84
+ };
85
+ };
86
+
87
+ function getCodeAssistServer(config: Config): CodeAssistServer {
88
+ let server = config.getGeminiClient().getContentGenerator();
89
+
90
+ // Unwrap LoggingContentGenerator if present
91
+ if (server instanceof LoggingContentGenerator) {
92
+ server = server.getWrapped();
93
+ }
94
+
95
+ // Neither of these cases should ever happen.
96
+ if (!(server instanceof CodeAssistServer)) {
97
+ throw new Error('Oauth not being used');
98
+ } else if (!server.projectId) {
99
+ throw new Error('Oauth not being used');
100
+ }
101
+ return server;
102
+ }
103
+
104
+ async function getTier(server: CodeAssistServer): Promise<UserTierId> {
105
+ const loadRes = await server.loadCodeAssist({
106
+ cloudaicompanionProject: server.projectId,
107
+ metadata: {
108
+ ideType: 'IDE_UNSPECIFIED',
109
+ platform: 'PLATFORM_UNSPECIFIED',
110
+ pluginType: 'GEMINI',
111
+ duetProject: server.projectId,
112
+ },
113
+ });
114
+ if (!loadRes.currentTier) {
115
+ throw new Error('User does not have a current tier');
116
+ }
117
+ return loadRes.currentTier.id;
118
+ }
119
+
120
+ async function getRemoteDataCollectionOptIn(
121
+ server: CodeAssistServer,
122
+ ): Promise<boolean> {
123
+ try {
124
+ const resp = await server.getCodeAssistGlobalUserSetting();
125
+ return resp.freeTierDataCollectionOptin;
126
+ } catch (error: unknown) {
127
+ if (error && typeof error === 'object' && 'response' in error) {
128
+ const gaxiosError = error as {
129
+ response?: {
130
+ status?: unknown;
131
+ };
132
+ };
133
+ if (gaxiosError.response?.status === 404) {
134
+ return true;
135
+ }
136
+ }
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ async function setRemoteDataCollectionOptIn(
142
+ server: CodeAssistServer,
143
+ optIn: boolean,
144
+ ): Promise<boolean> {
145
+ const resp = await server.setCodeAssistGlobalUserSetting({
146
+ cloudaicompanionProject: server.projectId,
147
+ freeTierDataCollectionOptin: optIn,
148
+ });
149
+ return resp.freeTierDataCollectionOptin;
150
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useQwenAuth.test.ts ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import { useQwenAuth, DeviceAuthorizationInfo } from './useQwenAuth.js';
10
+ import {
11
+ AuthType,
12
+ qwenOAuth2Events,
13
+ QwenOAuth2Event,
14
+ } from '@qwen-code/qwen-code-core';
15
+ import { LoadedSettings } from '../../config/settings.js';
16
+
17
+ // Mock the qwenOAuth2Events
18
+ vi.mock('@qwen-code/qwen-code-core', async () => {
19
+ const actual = await vi.importActual('@qwen-code/qwen-code-core');
20
+ const mockEmitter = {
21
+ on: vi.fn().mockReturnThis(),
22
+ off: vi.fn().mockReturnThis(),
23
+ emit: vi.fn().mockReturnThis(),
24
+ };
25
+ return {
26
+ ...actual,
27
+ qwenOAuth2Events: mockEmitter,
28
+ QwenOAuth2Event: {
29
+ AuthUri: 'authUri',
30
+ AuthProgress: 'authProgress',
31
+ },
32
+ };
33
+ });
34
+
35
+ const mockQwenOAuth2Events = vi.mocked(qwenOAuth2Events);
36
+
37
+ describe('useQwenAuth', () => {
38
+ const mockDeviceAuth: DeviceAuthorizationInfo = {
39
+ verification_uri: 'https://oauth.qwen.com/device',
40
+ verification_uri_complete: 'https://oauth.qwen.com/device?user_code=ABC123',
41
+ user_code: 'ABC123',
42
+ expires_in: 1800,
43
+ };
44
+
45
+ const createMockSettings = (authType: AuthType): LoadedSettings =>
46
+ ({
47
+ merged: {
48
+ selectedAuthType: authType,
49
+ },
50
+ }) as LoadedSettings;
51
+
52
+ beforeEach(() => {
53
+ vi.clearAllMocks();
54
+ });
55
+
56
+ afterEach(() => {
57
+ vi.clearAllMocks();
58
+ });
59
+
60
+ it('should initialize with default state when not Qwen auth', () => {
61
+ const settings = createMockSettings(AuthType.USE_GEMINI);
62
+ const { result } = renderHook(() => useQwenAuth(settings, false));
63
+
64
+ expect(result.current).toEqual({
65
+ isQwenAuthenticating: false,
66
+ deviceAuth: null,
67
+ authStatus: 'idle',
68
+ authMessage: null,
69
+ isQwenAuth: false,
70
+ cancelQwenAuth: expect.any(Function),
71
+ });
72
+ });
73
+
74
+ it('should initialize with default state when Qwen auth but not authenticating', () => {
75
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
76
+ const { result } = renderHook(() => useQwenAuth(settings, false));
77
+
78
+ expect(result.current).toEqual({
79
+ isQwenAuthenticating: false,
80
+ deviceAuth: null,
81
+ authStatus: 'idle',
82
+ authMessage: null,
83
+ isQwenAuth: true,
84
+ cancelQwenAuth: expect.any(Function),
85
+ });
86
+ });
87
+
88
+ it('should set up event listeners when Qwen auth and authenticating', () => {
89
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
90
+ renderHook(() => useQwenAuth(settings, true));
91
+
92
+ expect(mockQwenOAuth2Events.on).toHaveBeenCalledWith(
93
+ QwenOAuth2Event.AuthUri,
94
+ expect.any(Function),
95
+ );
96
+ expect(mockQwenOAuth2Events.on).toHaveBeenCalledWith(
97
+ QwenOAuth2Event.AuthProgress,
98
+ expect.any(Function),
99
+ );
100
+ });
101
+
102
+ it('should handle device auth event', () => {
103
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
104
+ let handleDeviceAuth: (deviceAuth: DeviceAuthorizationInfo) => void;
105
+
106
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
107
+ if (event === QwenOAuth2Event.AuthUri) {
108
+ handleDeviceAuth = handler;
109
+ }
110
+ return mockQwenOAuth2Events;
111
+ });
112
+
113
+ const { result } = renderHook(() => useQwenAuth(settings, true));
114
+
115
+ act(() => {
116
+ handleDeviceAuth!(mockDeviceAuth);
117
+ });
118
+
119
+ expect(result.current.deviceAuth).toEqual(mockDeviceAuth);
120
+ expect(result.current.authStatus).toBe('polling');
121
+ expect(result.current.isQwenAuthenticating).toBe(true);
122
+ });
123
+
124
+ it('should handle auth progress event - success', () => {
125
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
126
+ let handleAuthProgress: (
127
+ status: 'success' | 'error' | 'polling' | 'timeout' | 'rate_limit',
128
+ message?: string,
129
+ ) => void;
130
+
131
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
132
+ if (event === QwenOAuth2Event.AuthProgress) {
133
+ handleAuthProgress = handler;
134
+ }
135
+ return mockQwenOAuth2Events;
136
+ });
137
+
138
+ const { result } = renderHook(() => useQwenAuth(settings, true));
139
+
140
+ act(() => {
141
+ handleAuthProgress!('success', 'Authentication successful!');
142
+ });
143
+
144
+ expect(result.current.authStatus).toBe('success');
145
+ expect(result.current.authMessage).toBe('Authentication successful!');
146
+ });
147
+
148
+ it('should handle auth progress event - error', () => {
149
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
150
+ let handleAuthProgress: (
151
+ status: 'success' | 'error' | 'polling' | 'timeout' | 'rate_limit',
152
+ message?: string,
153
+ ) => void;
154
+
155
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
156
+ if (event === QwenOAuth2Event.AuthProgress) {
157
+ handleAuthProgress = handler;
158
+ }
159
+ return mockQwenOAuth2Events;
160
+ });
161
+
162
+ const { result } = renderHook(() => useQwenAuth(settings, true));
163
+
164
+ act(() => {
165
+ handleAuthProgress!('error', 'Authentication failed');
166
+ });
167
+
168
+ expect(result.current.authStatus).toBe('error');
169
+ expect(result.current.authMessage).toBe('Authentication failed');
170
+ });
171
+
172
+ it('should handle auth progress event - polling', () => {
173
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
174
+ let handleAuthProgress: (
175
+ status: 'success' | 'error' | 'polling' | 'timeout' | 'rate_limit',
176
+ message?: string,
177
+ ) => void;
178
+
179
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
180
+ if (event === QwenOAuth2Event.AuthProgress) {
181
+ handleAuthProgress = handler;
182
+ }
183
+ return mockQwenOAuth2Events;
184
+ });
185
+
186
+ const { result } = renderHook(() => useQwenAuth(settings, true));
187
+
188
+ act(() => {
189
+ handleAuthProgress!('polling', 'Waiting for user authorization...');
190
+ });
191
+
192
+ expect(result.current.authStatus).toBe('polling');
193
+ expect(result.current.authMessage).toBe(
194
+ 'Waiting for user authorization...',
195
+ );
196
+ });
197
+
198
+ it('should handle auth progress event - rate_limit', () => {
199
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
200
+ let handleAuthProgress: (
201
+ status: 'success' | 'error' | 'polling' | 'timeout' | 'rate_limit',
202
+ message?: string,
203
+ ) => void;
204
+
205
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
206
+ if (event === QwenOAuth2Event.AuthProgress) {
207
+ handleAuthProgress = handler;
208
+ }
209
+ return mockQwenOAuth2Events;
210
+ });
211
+
212
+ const { result } = renderHook(() => useQwenAuth(settings, true));
213
+
214
+ act(() => {
215
+ handleAuthProgress!(
216
+ 'rate_limit',
217
+ 'Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.',
218
+ );
219
+ });
220
+
221
+ expect(result.current.authStatus).toBe('rate_limit');
222
+ expect(result.current.authMessage).toBe(
223
+ 'Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.',
224
+ );
225
+ });
226
+
227
+ it('should handle auth progress event without message', () => {
228
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
229
+ let handleAuthProgress: (
230
+ status: 'success' | 'error' | 'polling' | 'timeout' | 'rate_limit',
231
+ message?: string,
232
+ ) => void;
233
+
234
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
235
+ if (event === QwenOAuth2Event.AuthProgress) {
236
+ handleAuthProgress = handler;
237
+ }
238
+ return mockQwenOAuth2Events;
239
+ });
240
+
241
+ const { result } = renderHook(() => useQwenAuth(settings, true));
242
+
243
+ act(() => {
244
+ handleAuthProgress!('success');
245
+ });
246
+
247
+ expect(result.current.authStatus).toBe('success');
248
+ expect(result.current.authMessage).toBe(null);
249
+ });
250
+
251
+ it('should clean up event listeners when auth type changes', () => {
252
+ const qwenSettings = createMockSettings(AuthType.QWEN_OAUTH);
253
+ const { rerender } = renderHook(
254
+ ({ settings, isAuthenticating }) =>
255
+ useQwenAuth(settings, isAuthenticating),
256
+ { initialProps: { settings: qwenSettings, isAuthenticating: true } },
257
+ );
258
+
259
+ // Change to non-Qwen auth
260
+ const geminiSettings = createMockSettings(AuthType.USE_GEMINI);
261
+ rerender({ settings: geminiSettings, isAuthenticating: true });
262
+
263
+ expect(mockQwenOAuth2Events.off).toHaveBeenCalledWith(
264
+ QwenOAuth2Event.AuthUri,
265
+ expect.any(Function),
266
+ );
267
+ expect(mockQwenOAuth2Events.off).toHaveBeenCalledWith(
268
+ QwenOAuth2Event.AuthProgress,
269
+ expect.any(Function),
270
+ );
271
+ });
272
+
273
+ it('should clean up event listeners when authentication stops', () => {
274
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
275
+ const { rerender } = renderHook(
276
+ ({ isAuthenticating }) => useQwenAuth(settings, isAuthenticating),
277
+ { initialProps: { isAuthenticating: true } },
278
+ );
279
+
280
+ // Stop authentication
281
+ rerender({ isAuthenticating: false });
282
+
283
+ expect(mockQwenOAuth2Events.off).toHaveBeenCalledWith(
284
+ QwenOAuth2Event.AuthUri,
285
+ expect.any(Function),
286
+ );
287
+ expect(mockQwenOAuth2Events.off).toHaveBeenCalledWith(
288
+ QwenOAuth2Event.AuthProgress,
289
+ expect.any(Function),
290
+ );
291
+ });
292
+
293
+ it('should clean up event listeners on unmount', () => {
294
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
295
+ const { unmount } = renderHook(() => useQwenAuth(settings, true));
296
+
297
+ unmount();
298
+
299
+ expect(mockQwenOAuth2Events.off).toHaveBeenCalledWith(
300
+ QwenOAuth2Event.AuthUri,
301
+ expect.any(Function),
302
+ );
303
+ expect(mockQwenOAuth2Events.off).toHaveBeenCalledWith(
304
+ QwenOAuth2Event.AuthProgress,
305
+ expect.any(Function),
306
+ );
307
+ });
308
+
309
+ it('should reset state when switching from Qwen auth to another auth type', () => {
310
+ const qwenSettings = createMockSettings(AuthType.QWEN_OAUTH);
311
+ let handleDeviceAuth: (deviceAuth: DeviceAuthorizationInfo) => void;
312
+
313
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
314
+ if (event === QwenOAuth2Event.AuthUri) {
315
+ handleDeviceAuth = handler;
316
+ }
317
+ return mockQwenOAuth2Events;
318
+ });
319
+
320
+ const { result, rerender } = renderHook(
321
+ ({ settings, isAuthenticating }) =>
322
+ useQwenAuth(settings, isAuthenticating),
323
+ { initialProps: { settings: qwenSettings, isAuthenticating: true } },
324
+ );
325
+
326
+ // Simulate device auth
327
+ act(() => {
328
+ handleDeviceAuth!(mockDeviceAuth);
329
+ });
330
+
331
+ expect(result.current.deviceAuth).toEqual(mockDeviceAuth);
332
+ expect(result.current.authStatus).toBe('polling');
333
+
334
+ // Switch to different auth type
335
+ const geminiSettings = createMockSettings(AuthType.USE_GEMINI);
336
+ rerender({ settings: geminiSettings, isAuthenticating: true });
337
+
338
+ expect(result.current.isQwenAuthenticating).toBe(false);
339
+ expect(result.current.deviceAuth).toBe(null);
340
+ expect(result.current.authStatus).toBe('idle');
341
+ expect(result.current.authMessage).toBe(null);
342
+ });
343
+
344
+ it('should reset state when authentication stops', () => {
345
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
346
+ let handleDeviceAuth: (deviceAuth: DeviceAuthorizationInfo) => void;
347
+
348
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
349
+ if (event === QwenOAuth2Event.AuthUri) {
350
+ handleDeviceAuth = handler;
351
+ }
352
+ return mockQwenOAuth2Events;
353
+ });
354
+
355
+ const { result, rerender } = renderHook(
356
+ ({ isAuthenticating }) => useQwenAuth(settings, isAuthenticating),
357
+ { initialProps: { isAuthenticating: true } },
358
+ );
359
+
360
+ // Simulate device auth
361
+ act(() => {
362
+ handleDeviceAuth!(mockDeviceAuth);
363
+ });
364
+
365
+ expect(result.current.deviceAuth).toEqual(mockDeviceAuth);
366
+ expect(result.current.authStatus).toBe('polling');
367
+
368
+ // Stop authentication
369
+ rerender({ isAuthenticating: false });
370
+
371
+ expect(result.current.isQwenAuthenticating).toBe(false);
372
+ expect(result.current.deviceAuth).toBe(null);
373
+ expect(result.current.authStatus).toBe('idle');
374
+ expect(result.current.authMessage).toBe(null);
375
+ });
376
+
377
+ it('should handle cancelQwenAuth function', () => {
378
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
379
+ let handleDeviceAuth: (deviceAuth: DeviceAuthorizationInfo) => void;
380
+
381
+ mockQwenOAuth2Events.on.mockImplementation((event, handler) => {
382
+ if (event === QwenOAuth2Event.AuthUri) {
383
+ handleDeviceAuth = handler;
384
+ }
385
+ return mockQwenOAuth2Events;
386
+ });
387
+
388
+ const { result } = renderHook(() => useQwenAuth(settings, true));
389
+
390
+ // Set up some state
391
+ act(() => {
392
+ handleDeviceAuth!(mockDeviceAuth);
393
+ });
394
+
395
+ expect(result.current.deviceAuth).toEqual(mockDeviceAuth);
396
+
397
+ // Cancel auth
398
+ act(() => {
399
+ result.current.cancelQwenAuth();
400
+ });
401
+
402
+ expect(result.current.isQwenAuthenticating).toBe(false);
403
+ expect(result.current.deviceAuth).toBe(null);
404
+ expect(result.current.authStatus).toBe('idle');
405
+ expect(result.current.authMessage).toBe(null);
406
+ });
407
+
408
+ it('should maintain isQwenAuth flag correctly', () => {
409
+ // Test with Qwen OAuth
410
+ const qwenSettings = createMockSettings(AuthType.QWEN_OAUTH);
411
+ const { result: qwenResult } = renderHook(() =>
412
+ useQwenAuth(qwenSettings, false),
413
+ );
414
+ expect(qwenResult.current.isQwenAuth).toBe(true);
415
+
416
+ // Test with other auth types
417
+ const geminiSettings = createMockSettings(AuthType.USE_GEMINI);
418
+ const { result: geminiResult } = renderHook(() =>
419
+ useQwenAuth(geminiSettings, false),
420
+ );
421
+ expect(geminiResult.current.isQwenAuth).toBe(false);
422
+
423
+ const oauthSettings = createMockSettings(AuthType.LOGIN_WITH_GOOGLE);
424
+ const { result: oauthResult } = renderHook(() =>
425
+ useQwenAuth(oauthSettings, false),
426
+ );
427
+ expect(oauthResult.current.isQwenAuth).toBe(false);
428
+ });
429
+
430
+ it('should set isQwenAuthenticating to true when starting authentication with Qwen auth', () => {
431
+ const settings = createMockSettings(AuthType.QWEN_OAUTH);
432
+ const { result } = renderHook(() => useQwenAuth(settings, true));
433
+
434
+ expect(result.current.isQwenAuthenticating).toBe(true);
435
+ expect(result.current.authStatus).toBe('idle');
436
+ });
437
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useQwenAuth.ts ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useCallback, useEffect } from 'react';
8
+ import { LoadedSettings } from '../../config/settings.js';
9
+ import {
10
+ AuthType,
11
+ qwenOAuth2Events,
12
+ QwenOAuth2Event,
13
+ } from '@qwen-code/qwen-code-core';
14
+
15
+ export interface DeviceAuthorizationInfo {
16
+ verification_uri: string;
17
+ verification_uri_complete: string;
18
+ user_code: string;
19
+ expires_in: number;
20
+ }
21
+
22
+ interface QwenAuthState {
23
+ isQwenAuthenticating: boolean;
24
+ deviceAuth: DeviceAuthorizationInfo | null;
25
+ authStatus:
26
+ | 'idle'
27
+ | 'polling'
28
+ | 'success'
29
+ | 'error'
30
+ | 'timeout'
31
+ | 'rate_limit';
32
+ authMessage: string | null;
33
+ }
34
+
35
+ export const useQwenAuth = (
36
+ settings: LoadedSettings,
37
+ isAuthenticating: boolean,
38
+ ) => {
39
+ const [qwenAuthState, setQwenAuthState] = useState<QwenAuthState>({
40
+ isQwenAuthenticating: false,
41
+ deviceAuth: null,
42
+ authStatus: 'idle',
43
+ authMessage: null,
44
+ });
45
+
46
+ const isQwenAuth = settings.merged.selectedAuthType === AuthType.QWEN_OAUTH;
47
+
48
+ // Set up event listeners when authentication starts
49
+ useEffect(() => {
50
+ if (!isQwenAuth || !isAuthenticating) {
51
+ // Reset state when not authenticating or not Qwen auth
52
+ setQwenAuthState({
53
+ isQwenAuthenticating: false,
54
+ deviceAuth: null,
55
+ authStatus: 'idle',
56
+ authMessage: null,
57
+ });
58
+ return;
59
+ }
60
+
61
+ setQwenAuthState((prev) => ({
62
+ ...prev,
63
+ isQwenAuthenticating: true,
64
+ authStatus: 'idle',
65
+ }));
66
+
67
+ // Set up event listeners
68
+ const handleDeviceAuth = (deviceAuth: DeviceAuthorizationInfo) => {
69
+ setQwenAuthState((prev) => ({
70
+ ...prev,
71
+ deviceAuth: {
72
+ verification_uri: deviceAuth.verification_uri,
73
+ verification_uri_complete: deviceAuth.verification_uri_complete,
74
+ user_code: deviceAuth.user_code,
75
+ expires_in: deviceAuth.expires_in,
76
+ },
77
+ authStatus: 'polling',
78
+ }));
79
+ };
80
+
81
+ const handleAuthProgress = (
82
+ status: 'success' | 'error' | 'polling' | 'timeout' | 'rate_limit',
83
+ message?: string,
84
+ ) => {
85
+ setQwenAuthState((prev) => ({
86
+ ...prev,
87
+ authStatus: status,
88
+ authMessage: message || null,
89
+ }));
90
+ };
91
+
92
+ // Add event listeners
93
+ qwenOAuth2Events.on(QwenOAuth2Event.AuthUri, handleDeviceAuth);
94
+ qwenOAuth2Events.on(QwenOAuth2Event.AuthProgress, handleAuthProgress);
95
+
96
+ // Cleanup event listeners when component unmounts or auth finishes
97
+ return () => {
98
+ qwenOAuth2Events.off(QwenOAuth2Event.AuthUri, handleDeviceAuth);
99
+ qwenOAuth2Events.off(QwenOAuth2Event.AuthProgress, handleAuthProgress);
100
+ };
101
+ }, [isQwenAuth, isAuthenticating]);
102
+
103
+ const cancelQwenAuth = useCallback(() => {
104
+ // Emit cancel event to stop polling
105
+ qwenOAuth2Events.emit(QwenOAuth2Event.AuthCancel);
106
+
107
+ setQwenAuthState({
108
+ isQwenAuthenticating: false,
109
+ deviceAuth: null,
110
+ authStatus: 'idle',
111
+ authMessage: null,
112
+ });
113
+ }, []);
114
+
115
+ return {
116
+ ...qwenAuthState,
117
+ isQwenAuth,
118
+ cancelQwenAuth,
119
+ };
120
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useReactToolScheduler.ts ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ Config,
9
+ ToolCallRequestInfo,
10
+ ExecutingToolCall,
11
+ ScheduledToolCall,
12
+ ValidatingToolCall,
13
+ WaitingToolCall,
14
+ CompletedToolCall,
15
+ CancelledToolCall,
16
+ CoreToolScheduler,
17
+ OutputUpdateHandler,
18
+ AllToolCallsCompleteHandler,
19
+ ToolCallsUpdateHandler,
20
+ ToolCall,
21
+ Status as CoreStatus,
22
+ EditorType,
23
+ } from '@qwen-code/qwen-code-core';
24
+ import { useCallback, useState, useMemo } from 'react';
25
+ import {
26
+ HistoryItemToolGroup,
27
+ IndividualToolCallDisplay,
28
+ ToolCallStatus,
29
+ HistoryItemWithoutId,
30
+ } from '../types.js';
31
+
32
+ export type ScheduleFn = (
33
+ request: ToolCallRequestInfo | ToolCallRequestInfo[],
34
+ signal: AbortSignal,
35
+ ) => void;
36
+ export type MarkToolsAsSubmittedFn = (callIds: string[]) => void;
37
+
38
+ export type TrackedScheduledToolCall = ScheduledToolCall & {
39
+ responseSubmittedToGemini?: boolean;
40
+ };
41
+ export type TrackedValidatingToolCall = ValidatingToolCall & {
42
+ responseSubmittedToGemini?: boolean;
43
+ };
44
+ export type TrackedWaitingToolCall = WaitingToolCall & {
45
+ responseSubmittedToGemini?: boolean;
46
+ };
47
+ export type TrackedExecutingToolCall = ExecutingToolCall & {
48
+ responseSubmittedToGemini?: boolean;
49
+ };
50
+ export type TrackedCompletedToolCall = CompletedToolCall & {
51
+ responseSubmittedToGemini?: boolean;
52
+ };
53
+ export type TrackedCancelledToolCall = CancelledToolCall & {
54
+ responseSubmittedToGemini?: boolean;
55
+ };
56
+
57
+ export type TrackedToolCall =
58
+ | TrackedScheduledToolCall
59
+ | TrackedValidatingToolCall
60
+ | TrackedWaitingToolCall
61
+ | TrackedExecutingToolCall
62
+ | TrackedCompletedToolCall
63
+ | TrackedCancelledToolCall;
64
+
65
+ export function useReactToolScheduler(
66
+ onComplete: (tools: CompletedToolCall[]) => Promise<void>,
67
+ config: Config,
68
+ setPendingHistoryItem: React.Dispatch<
69
+ React.SetStateAction<HistoryItemWithoutId | null>
70
+ >,
71
+ getPreferredEditor: () => EditorType | undefined,
72
+ onEditorClose: () => void,
73
+ ): [TrackedToolCall[], ScheduleFn, MarkToolsAsSubmittedFn] {
74
+ const [toolCallsForDisplay, setToolCallsForDisplay] = useState<
75
+ TrackedToolCall[]
76
+ >([]);
77
+
78
+ const outputUpdateHandler: OutputUpdateHandler = useCallback(
79
+ (toolCallId, outputChunk) => {
80
+ setPendingHistoryItem((prevItem) => {
81
+ if (prevItem?.type === 'tool_group') {
82
+ return {
83
+ ...prevItem,
84
+ tools: prevItem.tools.map((toolDisplay) =>
85
+ toolDisplay.callId === toolCallId &&
86
+ toolDisplay.status === ToolCallStatus.Executing
87
+ ? { ...toolDisplay, resultDisplay: outputChunk }
88
+ : toolDisplay,
89
+ ),
90
+ };
91
+ }
92
+ return prevItem;
93
+ });
94
+
95
+ setToolCallsForDisplay((prevCalls) =>
96
+ prevCalls.map((tc) => {
97
+ if (tc.request.callId === toolCallId && tc.status === 'executing') {
98
+ const executingTc = tc as TrackedExecutingToolCall;
99
+ return { ...executingTc, liveOutput: outputChunk };
100
+ }
101
+ return tc;
102
+ }),
103
+ );
104
+ },
105
+ [setPendingHistoryItem],
106
+ );
107
+
108
+ const allToolCallsCompleteHandler: AllToolCallsCompleteHandler = useCallback(
109
+ async (completedToolCalls) => {
110
+ await onComplete(completedToolCalls);
111
+ },
112
+ [onComplete],
113
+ );
114
+
115
+ const toolCallsUpdateHandler: ToolCallsUpdateHandler = useCallback(
116
+ (updatedCoreToolCalls: ToolCall[]) => {
117
+ setToolCallsForDisplay((prevTrackedCalls) =>
118
+ updatedCoreToolCalls.map((coreTc) => {
119
+ const existingTrackedCall = prevTrackedCalls.find(
120
+ (ptc) => ptc.request.callId === coreTc.request.callId,
121
+ );
122
+ const newTrackedCall: TrackedToolCall = {
123
+ ...coreTc,
124
+ responseSubmittedToGemini:
125
+ existingTrackedCall?.responseSubmittedToGemini ?? false,
126
+ } as TrackedToolCall;
127
+ return newTrackedCall;
128
+ }),
129
+ );
130
+ },
131
+ [setToolCallsForDisplay],
132
+ );
133
+
134
+ const scheduler = useMemo(
135
+ () =>
136
+ new CoreToolScheduler({
137
+ toolRegistry: config.getToolRegistry(),
138
+ outputUpdateHandler,
139
+ onAllToolCallsComplete: allToolCallsCompleteHandler,
140
+ onToolCallsUpdate: toolCallsUpdateHandler,
141
+ getPreferredEditor,
142
+ config,
143
+ onEditorClose,
144
+ }),
145
+ [
146
+ config,
147
+ outputUpdateHandler,
148
+ allToolCallsCompleteHandler,
149
+ toolCallsUpdateHandler,
150
+ getPreferredEditor,
151
+ onEditorClose,
152
+ ],
153
+ );
154
+
155
+ const schedule: ScheduleFn = useCallback(
156
+ (
157
+ request: ToolCallRequestInfo | ToolCallRequestInfo[],
158
+ signal: AbortSignal,
159
+ ) => {
160
+ void scheduler.schedule(request, signal);
161
+ },
162
+ [scheduler],
163
+ );
164
+
165
+ const markToolsAsSubmitted: MarkToolsAsSubmittedFn = useCallback(
166
+ (callIdsToMark: string[]) => {
167
+ setToolCallsForDisplay((prevCalls) =>
168
+ prevCalls.map((tc) =>
169
+ callIdsToMark.includes(tc.request.callId)
170
+ ? { ...tc, responseSubmittedToGemini: true }
171
+ : tc,
172
+ ),
173
+ );
174
+ },
175
+ [],
176
+ );
177
+
178
+ return [toolCallsForDisplay, schedule, markToolsAsSubmitted];
179
+ }
180
+
181
+ /**
182
+ * Maps a CoreToolScheduler status to the UI's ToolCallStatus enum.
183
+ */
184
+ function mapCoreStatusToDisplayStatus(coreStatus: CoreStatus): ToolCallStatus {
185
+ switch (coreStatus) {
186
+ case 'validating':
187
+ return ToolCallStatus.Executing;
188
+ case 'awaiting_approval':
189
+ return ToolCallStatus.Confirming;
190
+ case 'executing':
191
+ return ToolCallStatus.Executing;
192
+ case 'success':
193
+ return ToolCallStatus.Success;
194
+ case 'cancelled':
195
+ return ToolCallStatus.Canceled;
196
+ case 'error':
197
+ return ToolCallStatus.Error;
198
+ case 'scheduled':
199
+ return ToolCallStatus.Pending;
200
+ default: {
201
+ const exhaustiveCheck: never = coreStatus;
202
+ console.warn(`Unknown core status encountered: ${exhaustiveCheck}`);
203
+ return ToolCallStatus.Error;
204
+ }
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Transforms `TrackedToolCall` objects into `HistoryItemToolGroup` objects for UI display.
210
+ */
211
+ export function mapToDisplay(
212
+ toolOrTools: TrackedToolCall[] | TrackedToolCall,
213
+ ): HistoryItemToolGroup {
214
+ const toolCalls = Array.isArray(toolOrTools) ? toolOrTools : [toolOrTools];
215
+
216
+ const toolDisplays = toolCalls.map(
217
+ (trackedCall): IndividualToolCallDisplay => {
218
+ let displayName: string;
219
+ let description: string;
220
+ let renderOutputAsMarkdown = false;
221
+
222
+ if (trackedCall.status === 'error') {
223
+ displayName =
224
+ trackedCall.tool === undefined
225
+ ? trackedCall.request.name
226
+ : trackedCall.tool.displayName;
227
+ description = JSON.stringify(trackedCall.request.args);
228
+ } else {
229
+ displayName = trackedCall.tool.displayName;
230
+ description = trackedCall.invocation.getDescription();
231
+ renderOutputAsMarkdown = trackedCall.tool.isOutputMarkdown;
232
+ }
233
+
234
+ const baseDisplayProperties: Omit<
235
+ IndividualToolCallDisplay,
236
+ 'status' | 'resultDisplay' | 'confirmationDetails'
237
+ > = {
238
+ callId: trackedCall.request.callId,
239
+ name: displayName,
240
+ description,
241
+ renderOutputAsMarkdown,
242
+ };
243
+
244
+ switch (trackedCall.status) {
245
+ case 'success':
246
+ return {
247
+ ...baseDisplayProperties,
248
+ status: mapCoreStatusToDisplayStatus(trackedCall.status),
249
+ resultDisplay: trackedCall.response.resultDisplay,
250
+ confirmationDetails: undefined,
251
+ };
252
+ case 'error':
253
+ return {
254
+ ...baseDisplayProperties,
255
+ status: mapCoreStatusToDisplayStatus(trackedCall.status),
256
+ resultDisplay: trackedCall.response.resultDisplay,
257
+ confirmationDetails: undefined,
258
+ };
259
+ case 'cancelled':
260
+ return {
261
+ ...baseDisplayProperties,
262
+ status: mapCoreStatusToDisplayStatus(trackedCall.status),
263
+ resultDisplay: trackedCall.response.resultDisplay,
264
+ confirmationDetails: undefined,
265
+ };
266
+ case 'awaiting_approval':
267
+ return {
268
+ ...baseDisplayProperties,
269
+ status: mapCoreStatusToDisplayStatus(trackedCall.status),
270
+ resultDisplay: undefined,
271
+ confirmationDetails: trackedCall.confirmationDetails,
272
+ };
273
+ case 'executing':
274
+ return {
275
+ ...baseDisplayProperties,
276
+ status: mapCoreStatusToDisplayStatus(trackedCall.status),
277
+ resultDisplay:
278
+ (trackedCall as TrackedExecutingToolCall).liveOutput ?? undefined,
279
+ confirmationDetails: undefined,
280
+ };
281
+ case 'validating': // Fallthrough
282
+ case 'scheduled':
283
+ return {
284
+ ...baseDisplayProperties,
285
+ status: mapCoreStatusToDisplayStatus(trackedCall.status),
286
+ resultDisplay: undefined,
287
+ confirmationDetails: undefined,
288
+ };
289
+ default: {
290
+ const exhaustiveCheck: never = trackedCall;
291
+ return {
292
+ callId: (exhaustiveCheck as TrackedToolCall).request.callId,
293
+ name: 'Unknown Tool',
294
+ description: 'Encountered an unknown tool call state.',
295
+ status: ToolCallStatus.Error,
296
+ resultDisplay: 'Unknown tool call state',
297
+ confirmationDetails: undefined,
298
+ renderOutputAsMarkdown: false,
299
+ };
300
+ }
301
+ }
302
+ },
303
+ );
304
+
305
+ return {
306
+ type: 'tool_group',
307
+ tools: toolDisplays,
308
+ };
309
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useRefreshMemoryCommand.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export const REFRESH_MEMORY_COMMAND_NAME = '/refreshmemory';
projects/ui/qwen-code/packages/cli/src/ui/hooks/useReverseSearchCompletion.test.tsx ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 } from 'vitest';
10
+ import { renderHook, act } from '@testing-library/react';
11
+ import { useReverseSearchCompletion } from './useReverseSearchCompletion.js';
12
+ import { useTextBuffer } from '../components/shared/text-buffer.js';
13
+
14
+ describe('useReverseSearchCompletion', () => {
15
+ function useTextBufferForTest(text: string) {
16
+ return useTextBuffer({
17
+ initialText: text,
18
+ initialCursorOffset: text.length,
19
+ viewport: { width: 80, height: 20 },
20
+ isValidPath: () => false,
21
+ onChange: () => {},
22
+ });
23
+ }
24
+
25
+ describe('Core Hook Behavior', () => {
26
+ describe('State Management', () => {
27
+ it('should initialize with default state', () => {
28
+ const mockShellHistory = ['echo hello'];
29
+
30
+ const { result } = renderHook(() =>
31
+ useReverseSearchCompletion(
32
+ useTextBufferForTest(''),
33
+ mockShellHistory,
34
+ false,
35
+ ),
36
+ );
37
+
38
+ expect(result.current.suggestions).toEqual([]);
39
+ expect(result.current.activeSuggestionIndex).toBe(-1);
40
+ expect(result.current.visibleStartIndex).toBe(0);
41
+ expect(result.current.showSuggestions).toBe(false);
42
+ expect(result.current.isLoadingSuggestions).toBe(false);
43
+ });
44
+
45
+ it('should reset state when reverseSearchActive becomes false', () => {
46
+ const mockShellHistory = ['echo hello'];
47
+ const { result, rerender } = renderHook(
48
+ ({ text, active }) => {
49
+ const textBuffer = useTextBufferForTest(text);
50
+ return useReverseSearchCompletion(
51
+ textBuffer,
52
+ mockShellHistory,
53
+ active,
54
+ );
55
+ },
56
+ { initialProps: { text: 'echo', active: true } },
57
+ );
58
+
59
+ // Simulate reverseSearchActive becoming false
60
+ rerender({ text: 'echo', active: false });
61
+
62
+ expect(result.current.suggestions).toEqual([]);
63
+ expect(result.current.activeSuggestionIndex).toBe(-1);
64
+ expect(result.current.visibleStartIndex).toBe(0);
65
+ expect(result.current.showSuggestions).toBe(false);
66
+ });
67
+
68
+ describe('Navigation', () => {
69
+ it('should handle navigateUp with no suggestions', () => {
70
+ const mockShellHistory = ['echo hello'];
71
+
72
+ const { result } = renderHook(() =>
73
+ useReverseSearchCompletion(
74
+ useTextBufferForTest('grep'),
75
+ mockShellHistory,
76
+ true,
77
+ ),
78
+ );
79
+
80
+ act(() => {
81
+ result.current.navigateUp();
82
+ });
83
+
84
+ expect(result.current.activeSuggestionIndex).toBe(-1);
85
+ });
86
+
87
+ it('should handle navigateDown with no suggestions', () => {
88
+ const mockShellHistory = ['echo hello'];
89
+ const { result } = renderHook(() =>
90
+ useReverseSearchCompletion(
91
+ useTextBufferForTest('grep'),
92
+ mockShellHistory,
93
+ true,
94
+ ),
95
+ );
96
+
97
+ act(() => {
98
+ result.current.navigateDown();
99
+ });
100
+
101
+ expect(result.current.activeSuggestionIndex).toBe(-1);
102
+ });
103
+
104
+ it('should navigate up through suggestions with wrap-around', () => {
105
+ const mockShellHistory = [
106
+ 'ls -l',
107
+ 'ls -la',
108
+ 'cd /some/path',
109
+ 'git status',
110
+ 'echo "Hello, World!"',
111
+ 'echo Hi',
112
+ ];
113
+
114
+ const { result } = renderHook(() =>
115
+ useReverseSearchCompletion(
116
+ useTextBufferForTest('echo'),
117
+ mockShellHistory,
118
+ true,
119
+ ),
120
+ );
121
+
122
+ expect(result.current.suggestions.length).toBe(2);
123
+ expect(result.current.activeSuggestionIndex).toBe(0);
124
+
125
+ act(() => {
126
+ result.current.navigateUp();
127
+ });
128
+
129
+ expect(result.current.activeSuggestionIndex).toBe(1);
130
+ });
131
+
132
+ it('should navigate down through suggestions with wrap-around', () => {
133
+ const mockShellHistory = [
134
+ 'ls -l',
135
+ 'ls -la',
136
+ 'cd /some/path',
137
+ 'git status',
138
+ 'echo "Hello, World!"',
139
+ 'echo Hi',
140
+ ];
141
+ const { result } = renderHook(() =>
142
+ useReverseSearchCompletion(
143
+ useTextBufferForTest('ls'),
144
+ mockShellHistory,
145
+ true,
146
+ ),
147
+ );
148
+
149
+ expect(result.current.suggestions.length).toBe(2);
150
+ expect(result.current.activeSuggestionIndex).toBe(0);
151
+
152
+ act(() => {
153
+ result.current.navigateDown();
154
+ });
155
+
156
+ expect(result.current.activeSuggestionIndex).toBe(1);
157
+ });
158
+
159
+ it('should handle navigation with multiple suggestions', () => {
160
+ const mockShellHistory = [
161
+ 'ls -l',
162
+ 'ls -la',
163
+ 'cd /some/path/l',
164
+ 'git status',
165
+ 'echo "Hello, World!"',
166
+ 'echo "Hi all"',
167
+ ];
168
+
169
+ const { result } = renderHook(() =>
170
+ useReverseSearchCompletion(
171
+ useTextBufferForTest('l'),
172
+ mockShellHistory,
173
+ true,
174
+ ),
175
+ );
176
+
177
+ expect(result.current.suggestions.length).toBe(5);
178
+ expect(result.current.activeSuggestionIndex).toBe(0);
179
+
180
+ act(() => {
181
+ result.current.navigateDown();
182
+ });
183
+ expect(result.current.activeSuggestionIndex).toBe(1);
184
+
185
+ act(() => {
186
+ result.current.navigateDown();
187
+ });
188
+ expect(result.current.activeSuggestionIndex).toBe(2);
189
+
190
+ act(() => {
191
+ result.current.navigateUp();
192
+ });
193
+ expect(result.current.activeSuggestionIndex).toBe(1);
194
+
195
+ act(() => {
196
+ result.current.navigateUp();
197
+ });
198
+ expect(result.current.activeSuggestionIndex).toBe(0);
199
+
200
+ act(() => {
201
+ result.current.navigateUp();
202
+ });
203
+ expect(result.current.activeSuggestionIndex).toBe(4);
204
+ });
205
+
206
+ it('should handle navigation with large suggestion lists and scrolling', () => {
207
+ const largeMockCommands = Array.from(
208
+ { length: 15 },
209
+ (_, i) => `echo ${i}`,
210
+ );
211
+
212
+ const { result } = renderHook(() =>
213
+ useReverseSearchCompletion(
214
+ useTextBufferForTest('echo'),
215
+ largeMockCommands,
216
+ true,
217
+ ),
218
+ );
219
+
220
+ expect(result.current.suggestions.length).toBe(15);
221
+ expect(result.current.activeSuggestionIndex).toBe(0);
222
+ expect(result.current.visibleStartIndex).toBe(0);
223
+
224
+ act(() => {
225
+ result.current.navigateUp();
226
+ });
227
+
228
+ expect(result.current.activeSuggestionIndex).toBe(14);
229
+ expect(result.current.visibleStartIndex).toBe(Math.max(0, 15 - 8));
230
+ });
231
+ });
232
+ });
233
+ });
234
+
235
+ describe('Filtering', () => {
236
+ it('filters history by buffer.text and sets showSuggestions', () => {
237
+ const history = ['foo', 'barfoo', 'baz'];
238
+ const { result } = renderHook(() =>
239
+ useReverseSearchCompletion(useTextBufferForTest('foo'), history, true),
240
+ );
241
+
242
+ // should only return the two entries containing "foo"
243
+ expect(result.current.suggestions.map((s) => s.value)).toEqual([
244
+ 'foo',
245
+ 'barfoo',
246
+ ]);
247
+ expect(result.current.showSuggestions).toBe(true);
248
+ });
249
+
250
+ it('hides suggestions when there are no matches', () => {
251
+ const history = ['alpha', 'beta'];
252
+ const { result } = renderHook(() =>
253
+ useReverseSearchCompletion(useTextBufferForTest('γ'), history, true),
254
+ );
255
+
256
+ expect(result.current.suggestions).toEqual([]);
257
+ expect(result.current.showSuggestions).toBe(false);
258
+ });
259
+ });
260
+ });