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

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx +95 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/hooks/useSettingsCommand.ts +25 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/hooks/useShellHistory.test.ts +219 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/hooks/useShellHistory.ts +133 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/hooks/useShowMemoryCommand.ts +75 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/hooks/useSlashCompletion.test.ts +434 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/hooks/useSlashCompletion.ts +187 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/hooks/useStateAndRef.ts +36 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/hooks/useTerminalSize.ts +32 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/hooks/useThemeCommand.ts +110 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/hooks/useTimer.test.ts +120 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/hooks/useTimer.ts +65 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/hooks/useToolScheduler.test.ts +1123 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/hooks/vim.test.ts +1691 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/hooks/vim.ts +784 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx +117 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/privacy/CloudPaidPrivacyNotice.tsx +59 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx +62 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/privacy/PrivacyNotice.tsx +42 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/themes/ansi-light.ts +150 -0
projects/ui/qwen-code/packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useEffect, useCallback } from 'react';
8
+ import { useCompletion } from './useCompletion.js';
9
+ import { TextBuffer } from '../components/shared/text-buffer.js';
10
+ import { Suggestion } from '../components/SuggestionsDisplay.js';
11
+
12
+ export interface UseReverseSearchCompletionReturn {
13
+ suggestions: Suggestion[];
14
+ activeSuggestionIndex: number;
15
+ visibleStartIndex: number;
16
+ showSuggestions: boolean;
17
+ isLoadingSuggestions: boolean;
18
+ navigateUp: () => void;
19
+ navigateDown: () => void;
20
+ handleAutocomplete: (i: number) => void;
21
+ resetCompletionState: () => void;
22
+ }
23
+
24
+ export function useReverseSearchCompletion(
25
+ buffer: TextBuffer,
26
+ shellHistory: readonly string[],
27
+ reverseSearchActive: boolean,
28
+ ): UseReverseSearchCompletionReturn {
29
+ const {
30
+ suggestions,
31
+ activeSuggestionIndex,
32
+ visibleStartIndex,
33
+ showSuggestions,
34
+ isLoadingSuggestions,
35
+
36
+ setSuggestions,
37
+ setShowSuggestions,
38
+ setActiveSuggestionIndex,
39
+ resetCompletionState,
40
+ navigateUp,
41
+ navigateDown,
42
+ } = useCompletion();
43
+
44
+ useEffect(() => {
45
+ if (!reverseSearchActive) {
46
+ resetCompletionState();
47
+ }
48
+ }, [reverseSearchActive, resetCompletionState]);
49
+
50
+ useEffect(() => {
51
+ if (!reverseSearchActive) {
52
+ return;
53
+ }
54
+
55
+ const q = buffer.text.toLowerCase();
56
+ const matches = shellHistory.reduce<Suggestion[]>((acc, cmd) => {
57
+ const idx = cmd.toLowerCase().indexOf(q);
58
+ if (idx !== -1) {
59
+ acc.push({ label: cmd, value: cmd, matchedIndex: idx });
60
+ }
61
+ return acc;
62
+ }, []);
63
+ setSuggestions(matches);
64
+ setShowSuggestions(matches.length > 0);
65
+ setActiveSuggestionIndex(matches.length > 0 ? 0 : -1);
66
+ }, [
67
+ buffer.text,
68
+ shellHistory,
69
+ reverseSearchActive,
70
+ setActiveSuggestionIndex,
71
+ setShowSuggestions,
72
+ setSuggestions,
73
+ ]);
74
+
75
+ const handleAutocomplete = useCallback(
76
+ (i: number) => {
77
+ if (i < 0 || i >= suggestions.length) return;
78
+ buffer.setText(suggestions[i].value);
79
+ resetCompletionState();
80
+ },
81
+ [buffer, suggestions, resetCompletionState],
82
+ );
83
+
84
+ return {
85
+ suggestions,
86
+ activeSuggestionIndex,
87
+ visibleStartIndex,
88
+ showSuggestions,
89
+ isLoadingSuggestions,
90
+ navigateUp,
91
+ navigateDown,
92
+ handleAutocomplete,
93
+ resetCompletionState,
94
+ };
95
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useSettingsCommand.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ export function useSettingsCommand() {
10
+ const [isSettingsDialogOpen, setIsSettingsDialogOpen] = useState(false);
11
+
12
+ const openSettingsDialog = useCallback(() => {
13
+ setIsSettingsDialogOpen(true);
14
+ }, []);
15
+
16
+ const closeSettingsDialog = useCallback(() => {
17
+ setIsSettingsDialogOpen(false);
18
+ }, []);
19
+
20
+ return {
21
+ isSettingsDialogOpen,
22
+ openSettingsDialog,
23
+ closeSettingsDialog,
24
+ };
25
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useShellHistory.test.ts ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { renderHook, act, waitFor } from '@testing-library/react';
8
+ import { useShellHistory } from './useShellHistory.js';
9
+ import * as fs from 'fs/promises';
10
+ import * as path from 'path';
11
+ import * as os from 'os';
12
+ import * as crypto from 'crypto';
13
+
14
+ vi.mock('fs/promises');
15
+ vi.mock('os');
16
+ vi.mock('crypto');
17
+
18
+ const MOCKED_PROJECT_ROOT = '/test/project';
19
+ const MOCKED_HOME_DIR = '/test/home';
20
+ const MOCKED_PROJECT_HASH = 'mocked_hash';
21
+
22
+ const MOCKED_HISTORY_DIR = path.join(
23
+ MOCKED_HOME_DIR,
24
+ '.qwen',
25
+ 'tmp',
26
+ MOCKED_PROJECT_HASH,
27
+ );
28
+ const MOCKED_HISTORY_FILE = path.join(MOCKED_HISTORY_DIR, 'shell_history');
29
+
30
+ describe('useShellHistory', () => {
31
+ const mockedFs = vi.mocked(fs);
32
+ const mockedOs = vi.mocked(os);
33
+ const mockedCrypto = vi.mocked(crypto);
34
+
35
+ beforeEach(() => {
36
+ vi.resetAllMocks();
37
+
38
+ mockedFs.readFile.mockResolvedValue('');
39
+ mockedFs.writeFile.mockResolvedValue(undefined);
40
+ mockedFs.mkdir.mockResolvedValue(undefined);
41
+ mockedOs.homedir.mockReturnValue(MOCKED_HOME_DIR);
42
+
43
+ const hashMock = {
44
+ update: vi.fn().mockReturnThis(),
45
+ digest: vi.fn().mockReturnValue(MOCKED_PROJECT_HASH),
46
+ };
47
+ mockedCrypto.createHash.mockReturnValue(hashMock as never);
48
+ });
49
+
50
+ it('should initialize and read the history file from the correct path', async () => {
51
+ mockedFs.readFile.mockResolvedValue('cmd1\ncmd2');
52
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
53
+
54
+ await waitFor(() => {
55
+ expect(mockedFs.readFile).toHaveBeenCalledWith(
56
+ MOCKED_HISTORY_FILE,
57
+ 'utf-8',
58
+ );
59
+ });
60
+
61
+ let command: string | null = null;
62
+ act(() => {
63
+ command = result.current.getPreviousCommand();
64
+ });
65
+
66
+ // History is loaded newest-first: ['cmd2', 'cmd1']
67
+ expect(command).toBe('cmd2');
68
+ });
69
+
70
+ it('should handle a nonexistent history file gracefully', async () => {
71
+ const error = new Error('File not found') as NodeJS.ErrnoException;
72
+ error.code = 'ENOENT';
73
+ mockedFs.readFile.mockRejectedValue(error);
74
+
75
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
76
+
77
+ await waitFor(() => {
78
+ expect(mockedFs.readFile).toHaveBeenCalled();
79
+ });
80
+
81
+ let command: string | null = null;
82
+ act(() => {
83
+ command = result.current.getPreviousCommand();
84
+ });
85
+
86
+ expect(command).toBe(null);
87
+ });
88
+
89
+ it('should add a command and write to the history file', async () => {
90
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
91
+
92
+ await waitFor(() => expect(mockedFs.readFile).toHaveBeenCalled());
93
+
94
+ act(() => {
95
+ result.current.addCommandToHistory('new_command');
96
+ });
97
+
98
+ await waitFor(() => {
99
+ expect(mockedFs.mkdir).toHaveBeenCalledWith(MOCKED_HISTORY_DIR, {
100
+ recursive: true,
101
+ });
102
+ expect(mockedFs.writeFile).toHaveBeenCalledWith(
103
+ MOCKED_HISTORY_FILE,
104
+ 'new_command', // Written to file oldest-first.
105
+ );
106
+ });
107
+
108
+ let command: string | null = null;
109
+ act(() => {
110
+ command = result.current.getPreviousCommand();
111
+ });
112
+ expect(command).toBe('new_command');
113
+ });
114
+
115
+ it('should navigate history correctly with previous/next commands', async () => {
116
+ mockedFs.readFile.mockResolvedValue('cmd1\ncmd2\ncmd3');
117
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
118
+
119
+ // Wait for history to be loaded: ['cmd3', 'cmd2', 'cmd1']
120
+ await waitFor(() => expect(mockedFs.readFile).toHaveBeenCalled());
121
+
122
+ let command: string | null = null;
123
+
124
+ act(() => {
125
+ command = result.current.getPreviousCommand();
126
+ });
127
+ expect(command).toBe('cmd3');
128
+
129
+ act(() => {
130
+ command = result.current.getPreviousCommand();
131
+ });
132
+ expect(command).toBe('cmd2');
133
+
134
+ act(() => {
135
+ command = result.current.getPreviousCommand();
136
+ });
137
+ expect(command).toBe('cmd1');
138
+
139
+ // Should stay at the oldest command
140
+ act(() => {
141
+ command = result.current.getPreviousCommand();
142
+ });
143
+ expect(command).toBe('cmd1');
144
+
145
+ act(() => {
146
+ command = result.current.getNextCommand();
147
+ });
148
+ expect(command).toBe('cmd2');
149
+
150
+ act(() => {
151
+ command = result.current.getNextCommand();
152
+ });
153
+ expect(command).toBe('cmd3');
154
+
155
+ // Should return to the "new command" line (represented as empty string)
156
+ act(() => {
157
+ command = result.current.getNextCommand();
158
+ });
159
+ expect(command).toBe('');
160
+ });
161
+
162
+ it('should not add empty or whitespace-only commands to history', async () => {
163
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
164
+ await waitFor(() => expect(mockedFs.readFile).toHaveBeenCalled());
165
+
166
+ act(() => {
167
+ result.current.addCommandToHistory(' ');
168
+ });
169
+
170
+ expect(mockedFs.writeFile).not.toHaveBeenCalled();
171
+ });
172
+
173
+ it('should truncate history to MAX_HISTORY_LENGTH (100)', async () => {
174
+ const oldCommands = Array.from({ length: 120 }, (_, i) => `old_cmd_${i}`);
175
+ mockedFs.readFile.mockResolvedValue(oldCommands.join('\n'));
176
+
177
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
178
+ await waitFor(() => expect(mockedFs.readFile).toHaveBeenCalled());
179
+
180
+ act(() => {
181
+ result.current.addCommandToHistory('new_cmd');
182
+ });
183
+
184
+ // Wait for the async write to happen and then inspect the arguments.
185
+ await waitFor(() => expect(mockedFs.writeFile).toHaveBeenCalled());
186
+
187
+ // The hook stores history newest-first.
188
+ // Initial state: ['old_cmd_119', ..., 'old_cmd_0']
189
+ // After adding 'new_cmd': ['new_cmd', 'old_cmd_119', ..., 'old_cmd_21'] (100 items)
190
+ // Written to file (reversed): ['old_cmd_21', ..., 'old_cmd_119', 'new_cmd']
191
+ const writtenContent = mockedFs.writeFile.mock.calls[0][1] as string;
192
+ const writtenLines = writtenContent.split('\n');
193
+
194
+ expect(writtenLines.length).toBe(100);
195
+ expect(writtenLines[0]).toBe('old_cmd_21'); // New oldest command
196
+ expect(writtenLines[99]).toBe('new_cmd'); // Newest command
197
+ });
198
+
199
+ it('should move an existing command to the top when re-added', async () => {
200
+ mockedFs.readFile.mockResolvedValue('cmd1\ncmd2\ncmd3');
201
+ const { result } = renderHook(() => useShellHistory(MOCKED_PROJECT_ROOT));
202
+
203
+ // Initial state: ['cmd3', 'cmd2', 'cmd1']
204
+ await waitFor(() => expect(mockedFs.readFile).toHaveBeenCalled());
205
+
206
+ act(() => {
207
+ result.current.addCommandToHistory('cmd1');
208
+ });
209
+
210
+ // After re-adding 'cmd1': ['cmd1', 'cmd3', 'cmd2']
211
+ // Written to file (reversed): ['cmd2', 'cmd3', 'cmd1']
212
+ await waitFor(() => expect(mockedFs.writeFile).toHaveBeenCalled());
213
+
214
+ const writtenContent = mockedFs.writeFile.mock.calls[0][1] as string;
215
+ const writtenLines = writtenContent.split('\n');
216
+
217
+ expect(writtenLines).toEqual(['cmd2', 'cmd3', 'cmd1']);
218
+ });
219
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useShellHistory.ts ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 * as fs from 'fs/promises';
9
+ import * as path from 'path';
10
+ import { isNodeError, getProjectTempDir } from '@qwen-code/qwen-code-core';
11
+
12
+ const HISTORY_FILE = 'shell_history';
13
+ const MAX_HISTORY_LENGTH = 100;
14
+
15
+ export interface UseShellHistoryReturn {
16
+ history: string[];
17
+ addCommandToHistory: (command: string) => void;
18
+ getPreviousCommand: () => string | null;
19
+ getNextCommand: () => string | null;
20
+ resetHistoryPosition: () => void;
21
+ }
22
+
23
+ async function getHistoryFilePath(projectRoot: string): Promise<string> {
24
+ const historyDir = getProjectTempDir(projectRoot);
25
+ return path.join(historyDir, HISTORY_FILE);
26
+ }
27
+
28
+ // Handle multiline commands
29
+ async function readHistoryFile(filePath: string): Promise<string[]> {
30
+ try {
31
+ const text = await fs.readFile(filePath, 'utf-8');
32
+ const result: string[] = [];
33
+ let cur = '';
34
+
35
+ for (const raw of text.split(/\r?\n/)) {
36
+ if (!raw.trim()) continue;
37
+ const line = raw;
38
+
39
+ const m = cur.match(/(\\+)$/);
40
+ if (m && m[1].length % 2) {
41
+ // odd number of trailing '\'
42
+ cur = cur.slice(0, -1) + ' ' + line;
43
+ } else {
44
+ if (cur) result.push(cur);
45
+ cur = line;
46
+ }
47
+ }
48
+
49
+ if (cur) result.push(cur);
50
+ return result;
51
+ } catch (err) {
52
+ if (isNodeError(err) && err.code === 'ENOENT') return [];
53
+ console.error('Error reading history:', err);
54
+ return [];
55
+ }
56
+ }
57
+
58
+ async function writeHistoryFile(
59
+ filePath: string,
60
+ history: string[],
61
+ ): Promise<void> {
62
+ try {
63
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
64
+ await fs.writeFile(filePath, history.join('\n'));
65
+ } catch (error) {
66
+ console.error('Error writing shell history:', error);
67
+ }
68
+ }
69
+
70
+ export function useShellHistory(projectRoot: string): UseShellHistoryReturn {
71
+ const [history, setHistory] = useState<string[]>([]);
72
+ const [historyIndex, setHistoryIndex] = useState(-1);
73
+ const [historyFilePath, setHistoryFilePath] = useState<string | null>(null);
74
+
75
+ useEffect(() => {
76
+ async function loadHistory() {
77
+ const filePath = await getHistoryFilePath(projectRoot);
78
+ setHistoryFilePath(filePath);
79
+ const loadedHistory = await readHistoryFile(filePath);
80
+ setHistory(loadedHistory.reverse()); // Newest first
81
+ }
82
+ loadHistory();
83
+ }, [projectRoot]);
84
+
85
+ const addCommandToHistory = useCallback(
86
+ (command: string) => {
87
+ if (!command.trim() || !historyFilePath) {
88
+ return;
89
+ }
90
+ const newHistory = [command, ...history.filter((c) => c !== command)]
91
+ .slice(0, MAX_HISTORY_LENGTH)
92
+ .filter(Boolean);
93
+ setHistory(newHistory);
94
+ // Write to file in reverse order (oldest first)
95
+ writeHistoryFile(historyFilePath, [...newHistory].reverse());
96
+ setHistoryIndex(-1);
97
+ },
98
+ [history, historyFilePath],
99
+ );
100
+
101
+ const getPreviousCommand = useCallback(() => {
102
+ if (history.length === 0) {
103
+ return null;
104
+ }
105
+ const newIndex = Math.min(historyIndex + 1, history.length - 1);
106
+ setHistoryIndex(newIndex);
107
+ return history[newIndex] ?? null;
108
+ }, [history, historyIndex]);
109
+
110
+ const getNextCommand = useCallback(() => {
111
+ if (historyIndex < 0) {
112
+ return null;
113
+ }
114
+ const newIndex = historyIndex - 1;
115
+ setHistoryIndex(newIndex);
116
+ if (newIndex < 0) {
117
+ return '';
118
+ }
119
+ return history[newIndex] ?? null;
120
+ }, [history, historyIndex]);
121
+
122
+ const resetHistoryPosition = useCallback(() => {
123
+ setHistoryIndex(-1);
124
+ }, []);
125
+
126
+ return {
127
+ history,
128
+ addCommandToHistory,
129
+ getPreviousCommand,
130
+ getNextCommand,
131
+ resetHistoryPosition,
132
+ };
133
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useShowMemoryCommand.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Message, MessageType } from '../types.js';
8
+ import { Config } from '@qwen-code/qwen-code-core';
9
+ import { LoadedSettings } from '../../config/settings.js';
10
+
11
+ export function createShowMemoryAction(
12
+ config: Config | null,
13
+ settings: LoadedSettings,
14
+ addMessage: (message: Message) => void,
15
+ ) {
16
+ return async () => {
17
+ if (!config) {
18
+ addMessage({
19
+ type: MessageType.ERROR,
20
+ content: 'Configuration not available. Cannot show memory.',
21
+ timestamp: new Date(),
22
+ });
23
+ return;
24
+ }
25
+
26
+ const debugMode = config.getDebugMode();
27
+
28
+ if (debugMode) {
29
+ console.log('[DEBUG] Show Memory command invoked.');
30
+ }
31
+
32
+ const currentMemory = config.getUserMemory();
33
+ const fileCount = config.getGeminiMdFileCount();
34
+ const contextFileName = settings.merged.contextFileName;
35
+ const contextFileNames = Array.isArray(contextFileName)
36
+ ? contextFileName
37
+ : [contextFileName];
38
+
39
+ if (debugMode) {
40
+ console.log(
41
+ `[DEBUG] Showing memory. Content from config.getUserMemory() (first 200 chars): ${currentMemory.substring(0, 200)}...`,
42
+ );
43
+ console.log(`[DEBUG] Number of context files loaded: ${fileCount}`);
44
+ }
45
+
46
+ if (fileCount > 0) {
47
+ const allNamesTheSame = new Set(contextFileNames).size < 2;
48
+ const name = allNamesTheSame ? contextFileNames[0] : 'context';
49
+ addMessage({
50
+ type: MessageType.INFO,
51
+ content: `Loaded memory from ${fileCount} ${name} file${
52
+ fileCount > 1 ? 's' : ''
53
+ }.`,
54
+ timestamp: new Date(),
55
+ });
56
+ }
57
+
58
+ if (currentMemory && currentMemory.trim().length > 0) {
59
+ addMessage({
60
+ type: MessageType.INFO,
61
+ content: `Current combined memory content:\n\`\`\`markdown\n${currentMemory}\n\`\`\``,
62
+ timestamp: new Date(),
63
+ });
64
+ } else {
65
+ addMessage({
66
+ type: MessageType.INFO,
67
+ content:
68
+ fileCount > 0
69
+ ? 'Hierarchical memory (QWEN.md or other context files) is loaded but content is empty.'
70
+ : 'No hierarchical memory (QWEN.md or other context files) is currently loaded.',
71
+ timestamp: new Date(),
72
+ });
73
+ }
74
+ };
75
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useSlashCompletion.test.ts ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, vi } from 'vitest';
10
+ import { renderHook, waitFor } from '@testing-library/react';
11
+ import { useSlashCompletion } from './useSlashCompletion.js';
12
+ import { CommandContext, SlashCommand } from '../commands/types.js';
13
+ import { useState } from 'react';
14
+ import { Suggestion } from '../components/SuggestionsDisplay.js';
15
+
16
+ // Test harness to capture the state from the hook's callbacks.
17
+ function useTestHarnessForSlashCompletion(
18
+ enabled: boolean,
19
+ query: string | null,
20
+ slashCommands: readonly SlashCommand[],
21
+ commandContext: CommandContext,
22
+ ) {
23
+ const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
24
+ const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);
25
+ const [isPerfectMatch, setIsPerfectMatch] = useState(false);
26
+
27
+ const { completionStart, completionEnd } = useSlashCompletion({
28
+ enabled,
29
+ query,
30
+ slashCommands,
31
+ commandContext,
32
+ setSuggestions,
33
+ setIsLoadingSuggestions,
34
+ setIsPerfectMatch,
35
+ });
36
+
37
+ return {
38
+ suggestions,
39
+ isLoadingSuggestions,
40
+ isPerfectMatch,
41
+ completionStart,
42
+ completionEnd,
43
+ };
44
+ }
45
+
46
+ describe('useSlashCompletion', () => {
47
+ // A minimal mock is sufficient for these tests.
48
+ const mockCommandContext = {} as CommandContext;
49
+
50
+ describe('Top-Level Commands', () => {
51
+ it('should suggest all top-level commands for the root slash', async () => {
52
+ const slashCommands = [
53
+ { name: 'help', altNames: ['?'], description: 'Show help' },
54
+ {
55
+ name: 'stats',
56
+ altNames: ['usage'],
57
+ description: 'check session stats. Usage: /stats [model|tools]',
58
+ },
59
+ { name: 'clear', description: 'Clear the screen' },
60
+ {
61
+ name: 'memory',
62
+ description: 'Manage memory',
63
+ subCommands: [{ name: 'show', description: 'Show memory' }],
64
+ },
65
+ { name: 'chat', description: 'Manage chat history' },
66
+ ] as unknown as SlashCommand[];
67
+ const { result } = renderHook(() =>
68
+ useTestHarnessForSlashCompletion(
69
+ true,
70
+ '/',
71
+ slashCommands,
72
+ mockCommandContext,
73
+ ),
74
+ );
75
+
76
+ expect(result.current.suggestions.length).toBe(slashCommands.length);
77
+ expect(result.current.suggestions.map((s) => s.label)).toEqual(
78
+ expect.arrayContaining(['help', 'clear', 'memory', 'chat', 'stats']),
79
+ );
80
+ });
81
+
82
+ it('should filter commands based on partial input', async () => {
83
+ const slashCommands = [
84
+ { name: 'memory', description: 'Manage memory' },
85
+ ] as unknown as SlashCommand[];
86
+ const { result } = renderHook(() =>
87
+ useTestHarnessForSlashCompletion(
88
+ true,
89
+ '/mem',
90
+ slashCommands,
91
+ mockCommandContext,
92
+ ),
93
+ );
94
+
95
+ expect(result.current.suggestions).toEqual([
96
+ { label: 'memory', value: 'memory', description: 'Manage memory' },
97
+ ]);
98
+ });
99
+
100
+ it('should suggest commands based on partial altNames', async () => {
101
+ const slashCommands = [
102
+ {
103
+ name: 'stats',
104
+ altNames: ['usage'],
105
+ description: 'check session stats. Usage: /stats [model|tools]',
106
+ },
107
+ ] as unknown as SlashCommand[];
108
+ const { result } = renderHook(() =>
109
+ useTestHarnessForSlashCompletion(
110
+ true,
111
+ '/usag',
112
+ slashCommands,
113
+ mockCommandContext,
114
+ ),
115
+ );
116
+
117
+ expect(result.current.suggestions).toEqual([
118
+ {
119
+ label: 'stats',
120
+ value: 'stats',
121
+ description: 'check session stats. Usage: /stats [model|tools]',
122
+ },
123
+ ]);
124
+ });
125
+
126
+ it('should NOT provide suggestions for a perfectly typed command that is a leaf node', async () => {
127
+ const slashCommands = [
128
+ { name: 'clear', description: 'Clear the screen', action: vi.fn() },
129
+ ] as unknown as SlashCommand[];
130
+ const { result } = renderHook(() =>
131
+ useTestHarnessForSlashCompletion(
132
+ true,
133
+ '/clear',
134
+ slashCommands,
135
+ mockCommandContext,
136
+ ),
137
+ );
138
+
139
+ expect(result.current.suggestions).toHaveLength(0);
140
+ });
141
+
142
+ it.each([['/?'], ['/usage']])(
143
+ 'should not suggest commands when altNames is fully typed',
144
+ async (query) => {
145
+ const mockSlashCommands = [
146
+ {
147
+ name: 'help',
148
+ altNames: ['?'],
149
+ description: 'Show help',
150
+ action: vi.fn(),
151
+ },
152
+ {
153
+ name: 'stats',
154
+ altNames: ['usage'],
155
+ description: 'check session stats. Usage: /stats [model|tools]',
156
+ action: vi.fn(),
157
+ },
158
+ ] as unknown as SlashCommand[];
159
+
160
+ const { result } = renderHook(() =>
161
+ useTestHarnessForSlashCompletion(
162
+ true,
163
+ query,
164
+ mockSlashCommands,
165
+ mockCommandContext,
166
+ ),
167
+ );
168
+
169
+ expect(result.current.suggestions).toHaveLength(0);
170
+ },
171
+ );
172
+
173
+ it('should not provide suggestions for a fully typed command that has no sub-commands or argument completion', async () => {
174
+ const slashCommands = [
175
+ { name: 'clear', description: 'Clear the screen' },
176
+ ] as unknown as SlashCommand[];
177
+ const { result } = renderHook(() =>
178
+ useTestHarnessForSlashCompletion(
179
+ true,
180
+ '/clear ',
181
+ slashCommands,
182
+ mockCommandContext,
183
+ ),
184
+ );
185
+
186
+ expect(result.current.suggestions).toHaveLength(0);
187
+ });
188
+
189
+ it('should not provide suggestions for an unknown command', async () => {
190
+ const slashCommands = [
191
+ { name: 'help', description: 'Show help' },
192
+ ] as unknown as SlashCommand[];
193
+ const { result } = renderHook(() =>
194
+ useTestHarnessForSlashCompletion(
195
+ true,
196
+ '/unknown-command',
197
+ slashCommands,
198
+ mockCommandContext,
199
+ ),
200
+ );
201
+
202
+ expect(result.current.suggestions).toHaveLength(0);
203
+ });
204
+ });
205
+
206
+ describe('Sub-Commands', () => {
207
+ it('should suggest sub-commands for a parent command', async () => {
208
+ const slashCommands = [
209
+ {
210
+ name: 'memory',
211
+ description: 'Manage memory',
212
+ subCommands: [
213
+ { name: 'show', description: 'Show memory' },
214
+ { name: 'add', description: 'Add to memory' },
215
+ ],
216
+ },
217
+ ] as unknown as SlashCommand[];
218
+
219
+ const { result } = renderHook(() =>
220
+ useTestHarnessForSlashCompletion(
221
+ true,
222
+ '/memory',
223
+ slashCommands,
224
+ mockCommandContext,
225
+ ),
226
+ );
227
+
228
+ expect(result.current.suggestions).toHaveLength(2);
229
+ expect(result.current.suggestions).toEqual(
230
+ expect.arrayContaining([
231
+ { label: 'show', value: 'show', description: 'Show memory' },
232
+ { label: 'add', value: 'add', description: 'Add to memory' },
233
+ ]),
234
+ );
235
+ });
236
+
237
+ it('should suggest all sub-commands when the query ends with the parent command and a space', async () => {
238
+ const slashCommands = [
239
+ {
240
+ name: 'memory',
241
+ description: 'Manage memory',
242
+ subCommands: [
243
+ { name: 'show', description: 'Show memory' },
244
+ { name: 'add', description: 'Add to memory' },
245
+ ],
246
+ },
247
+ ] as unknown as SlashCommand[];
248
+ const { result } = renderHook(() =>
249
+ useTestHarnessForSlashCompletion(
250
+ true,
251
+ '/memory ',
252
+ slashCommands,
253
+ mockCommandContext,
254
+ ),
255
+ );
256
+
257
+ expect(result.current.suggestions).toHaveLength(2);
258
+ expect(result.current.suggestions).toEqual(
259
+ expect.arrayContaining([
260
+ { label: 'show', value: 'show', description: 'Show memory' },
261
+ { label: 'add', value: 'add', description: 'Add to memory' },
262
+ ]),
263
+ );
264
+ });
265
+
266
+ it('should filter sub-commands by prefix', async () => {
267
+ const slashCommands = [
268
+ {
269
+ name: 'memory',
270
+ description: 'Manage memory',
271
+ subCommands: [
272
+ { name: 'show', description: 'Show memory' },
273
+ { name: 'add', description: 'Add to memory' },
274
+ ],
275
+ },
276
+ ] as unknown as SlashCommand[];
277
+ const { result } = renderHook(() =>
278
+ useTestHarnessForSlashCompletion(
279
+ true,
280
+ '/memory a',
281
+ slashCommands,
282
+ mockCommandContext,
283
+ ),
284
+ );
285
+
286
+ expect(result.current.suggestions).toEqual([
287
+ { label: 'add', value: 'add', description: 'Add to memory' },
288
+ ]);
289
+ });
290
+
291
+ it('should provide no suggestions for an invalid sub-command', async () => {
292
+ const slashCommands = [
293
+ {
294
+ name: 'memory',
295
+ description: 'Manage memory',
296
+ subCommands: [
297
+ { name: 'show', description: 'Show memory' },
298
+ { name: 'add', description: 'Add to memory' },
299
+ ],
300
+ },
301
+ ] as unknown as SlashCommand[];
302
+ const { result } = renderHook(() =>
303
+ useTestHarnessForSlashCompletion(
304
+ true,
305
+ '/memory dothisnow',
306
+ slashCommands,
307
+ mockCommandContext,
308
+ ),
309
+ );
310
+
311
+ expect(result.current.suggestions).toHaveLength(0);
312
+ });
313
+ });
314
+
315
+ describe('Argument Completion', () => {
316
+ it('should call the command.completion function for argument suggestions', async () => {
317
+ const availableTags = [
318
+ 'my-chat-tag-1',
319
+ 'my-chat-tag-2',
320
+ 'another-channel',
321
+ ];
322
+ const mockCompletionFn = vi
323
+ .fn()
324
+ .mockImplementation(
325
+ async (_context: CommandContext, partialArg: string) =>
326
+ availableTags.filter((tag) => tag.startsWith(partialArg)),
327
+ );
328
+
329
+ const slashCommands = [
330
+ {
331
+ name: 'chat',
332
+ description: 'Manage chat history',
333
+ subCommands: [
334
+ {
335
+ name: 'resume',
336
+ description: 'Resume a saved chat',
337
+ completion: mockCompletionFn,
338
+ },
339
+ ],
340
+ },
341
+ ] as unknown as SlashCommand[];
342
+
343
+ const { result } = renderHook(() =>
344
+ useTestHarnessForSlashCompletion(
345
+ true,
346
+ '/chat resume my-ch',
347
+ slashCommands,
348
+ mockCommandContext,
349
+ ),
350
+ );
351
+
352
+ await waitFor(() => {
353
+ expect(mockCompletionFn).toHaveBeenCalledWith(
354
+ mockCommandContext,
355
+ 'my-ch',
356
+ );
357
+ });
358
+
359
+ await waitFor(() => {
360
+ expect(result.current.suggestions).toEqual([
361
+ { label: 'my-chat-tag-1', value: 'my-chat-tag-1' },
362
+ { label: 'my-chat-tag-2', value: 'my-chat-tag-2' },
363
+ ]);
364
+ });
365
+ });
366
+
367
+ it('should call command.completion with an empty string when args start with a space', async () => {
368
+ const mockCompletionFn = vi
369
+ .fn()
370
+ .mockResolvedValue(['my-chat-tag-1', 'my-chat-tag-2', 'my-channel']);
371
+
372
+ const slashCommands = [
373
+ {
374
+ name: 'chat',
375
+ description: 'Manage chat history',
376
+ subCommands: [
377
+ {
378
+ name: 'resume',
379
+ description: 'Resume a saved chat',
380
+ completion: mockCompletionFn,
381
+ },
382
+ ],
383
+ },
384
+ ] as unknown as SlashCommand[];
385
+
386
+ const { result } = renderHook(() =>
387
+ useTestHarnessForSlashCompletion(
388
+ true,
389
+ '/chat resume ',
390
+ slashCommands,
391
+ mockCommandContext,
392
+ ),
393
+ );
394
+
395
+ await waitFor(() => {
396
+ expect(mockCompletionFn).toHaveBeenCalledWith(mockCommandContext, '');
397
+ });
398
+
399
+ await waitFor(() => {
400
+ expect(result.current.suggestions).toHaveLength(3);
401
+ });
402
+ });
403
+
404
+ it('should handle completion function that returns null', async () => {
405
+ const completionFn = vi.fn().mockResolvedValue(null);
406
+ const slashCommands = [
407
+ {
408
+ name: 'chat',
409
+ description: 'Manage chat history',
410
+ subCommands: [
411
+ {
412
+ name: 'resume',
413
+ description: 'Resume a saved chat',
414
+ completion: completionFn,
415
+ },
416
+ ],
417
+ },
418
+ ] as unknown as SlashCommand[];
419
+
420
+ const { result } = renderHook(() =>
421
+ useTestHarnessForSlashCompletion(
422
+ true,
423
+ '/chat resume ',
424
+ slashCommands,
425
+ mockCommandContext,
426
+ ),
427
+ );
428
+
429
+ await waitFor(() => {
430
+ expect(result.current.suggestions).toHaveLength(0);
431
+ });
432
+ });
433
+ });
434
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useSlashCompletion.ts ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { Suggestion } from '../components/SuggestionsDisplay.js';
9
+ import { CommandContext, SlashCommand } from '../commands/types.js';
10
+
11
+ export interface UseSlashCompletionProps {
12
+ enabled: boolean;
13
+ query: string | null;
14
+ slashCommands: readonly SlashCommand[];
15
+ commandContext: CommandContext;
16
+ setSuggestions: (suggestions: Suggestion[]) => void;
17
+ setIsLoadingSuggestions: (isLoading: boolean) => void;
18
+ setIsPerfectMatch: (isMatch: boolean) => void;
19
+ }
20
+
21
+ export function useSlashCompletion(props: UseSlashCompletionProps): {
22
+ completionStart: number;
23
+ completionEnd: number;
24
+ } {
25
+ const {
26
+ enabled,
27
+ query,
28
+ slashCommands,
29
+ commandContext,
30
+ setSuggestions,
31
+ setIsLoadingSuggestions,
32
+ setIsPerfectMatch,
33
+ } = props;
34
+ const [completionStart, setCompletionStart] = useState(-1);
35
+ const [completionEnd, setCompletionEnd] = useState(-1);
36
+
37
+ useEffect(() => {
38
+ if (!enabled || query === null) {
39
+ return;
40
+ }
41
+
42
+ const fullPath = query?.substring(1) || '';
43
+ const hasTrailingSpace = !!query?.endsWith(' ');
44
+ const rawParts = fullPath.split(/\s+/).filter((p) => p);
45
+ let commandPathParts = rawParts;
46
+ let partial = '';
47
+
48
+ if (!hasTrailingSpace && rawParts.length > 0) {
49
+ partial = rawParts[rawParts.length - 1];
50
+ commandPathParts = rawParts.slice(0, -1);
51
+ }
52
+
53
+ let currentLevel: readonly SlashCommand[] | undefined = slashCommands;
54
+ let leafCommand: SlashCommand | null = null;
55
+
56
+ for (const part of commandPathParts) {
57
+ if (!currentLevel) {
58
+ leafCommand = null;
59
+ currentLevel = [];
60
+ break;
61
+ }
62
+ const found: SlashCommand | undefined = currentLevel.find(
63
+ (cmd) => cmd.name === part || cmd.altNames?.includes(part),
64
+ );
65
+ if (found) {
66
+ leafCommand = found;
67
+ currentLevel = found.subCommands as readonly SlashCommand[] | undefined;
68
+ } else {
69
+ leafCommand = null;
70
+ currentLevel = [];
71
+ break;
72
+ }
73
+ }
74
+
75
+ let exactMatchAsParent: SlashCommand | undefined;
76
+ if (!hasTrailingSpace && currentLevel) {
77
+ exactMatchAsParent = currentLevel.find(
78
+ (cmd) =>
79
+ (cmd.name === partial || cmd.altNames?.includes(partial)) &&
80
+ cmd.subCommands,
81
+ );
82
+
83
+ if (exactMatchAsParent) {
84
+ leafCommand = exactMatchAsParent;
85
+ currentLevel = exactMatchAsParent.subCommands;
86
+ partial = '';
87
+ }
88
+ }
89
+
90
+ setIsPerfectMatch(false);
91
+ if (!hasTrailingSpace) {
92
+ if (leafCommand && partial === '' && leafCommand.action) {
93
+ setIsPerfectMatch(true);
94
+ } else if (currentLevel) {
95
+ const perfectMatch = currentLevel.find(
96
+ (cmd) =>
97
+ (cmd.name === partial || cmd.altNames?.includes(partial)) &&
98
+ cmd.action,
99
+ );
100
+ if (perfectMatch) {
101
+ setIsPerfectMatch(true);
102
+ }
103
+ }
104
+ }
105
+
106
+ const depth = commandPathParts.length;
107
+ const isArgumentCompletion =
108
+ leafCommand?.completion &&
109
+ (hasTrailingSpace ||
110
+ (rawParts.length > depth && depth > 0 && partial !== ''));
111
+
112
+ if (hasTrailingSpace || exactMatchAsParent) {
113
+ setCompletionStart(query.length);
114
+ setCompletionEnd(query.length);
115
+ } else if (partial) {
116
+ if (isArgumentCompletion) {
117
+ const commandSoFar = `/${commandPathParts.join(' ')}`;
118
+ const argStartIndex =
119
+ commandSoFar.length + (commandPathParts.length > 0 ? 1 : 0);
120
+ setCompletionStart(argStartIndex);
121
+ } else {
122
+ setCompletionStart(query.length - partial.length);
123
+ }
124
+ setCompletionEnd(query.length);
125
+ } else {
126
+ setCompletionStart(1);
127
+ setCompletionEnd(query.length);
128
+ }
129
+
130
+ if (isArgumentCompletion) {
131
+ const fetchAndSetSuggestions = async () => {
132
+ setIsLoadingSuggestions(true);
133
+ const argString = rawParts.slice(depth).join(' ');
134
+ const results =
135
+ (await leafCommand!.completion!(commandContext, argString)) || [];
136
+ const finalSuggestions = results.map((s) => ({ label: s, value: s }));
137
+ setSuggestions(finalSuggestions);
138
+ setIsLoadingSuggestions(false);
139
+ };
140
+ fetchAndSetSuggestions();
141
+ return;
142
+ }
143
+
144
+ const commandsToSearch = currentLevel || [];
145
+ if (commandsToSearch.length > 0) {
146
+ let potentialSuggestions = commandsToSearch.filter(
147
+ (cmd) =>
148
+ cmd.description &&
149
+ (cmd.name.startsWith(partial) ||
150
+ cmd.altNames?.some((alt) => alt.startsWith(partial))),
151
+ );
152
+
153
+ if (potentialSuggestions.length > 0 && !hasTrailingSpace) {
154
+ const perfectMatch = potentialSuggestions.find(
155
+ (s) => s.name === partial || s.altNames?.includes(partial),
156
+ );
157
+ if (perfectMatch && perfectMatch.action) {
158
+ potentialSuggestions = [];
159
+ }
160
+ }
161
+
162
+ const finalSuggestions = potentialSuggestions.map((cmd) => ({
163
+ label: cmd.name,
164
+ value: cmd.name,
165
+ description: cmd.description,
166
+ }));
167
+
168
+ setSuggestions(finalSuggestions);
169
+ return;
170
+ }
171
+
172
+ setSuggestions([]);
173
+ }, [
174
+ enabled,
175
+ query,
176
+ slashCommands,
177
+ commandContext,
178
+ setSuggestions,
179
+ setIsLoadingSuggestions,
180
+ setIsPerfectMatch,
181
+ ]);
182
+
183
+ return {
184
+ completionStart,
185
+ completionEnd,
186
+ };
187
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useStateAndRef.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+
9
+ // Hook to return state, state setter, and ref to most up-to-date value of state.
10
+ // We need this in order to setState and reference the updated state multiple
11
+ // times in the same function.
12
+ export const useStateAndRef = <
13
+ // Everything but function.
14
+ T extends object | null | undefined | number | string,
15
+ >(
16
+ initialValue: T,
17
+ ) => {
18
+ const [_, setState] = React.useState<T>(initialValue);
19
+ const ref = React.useRef<T>(initialValue);
20
+
21
+ const setStateInternal = React.useCallback<typeof setState>(
22
+ (newStateOrCallback) => {
23
+ let newValue: T;
24
+ if (typeof newStateOrCallback === 'function') {
25
+ newValue = newStateOrCallback(ref.current);
26
+ } else {
27
+ newValue = newStateOrCallback;
28
+ }
29
+ setState(newValue);
30
+ ref.current = newValue;
31
+ },
32
+ [],
33
+ );
34
+
35
+ return [ref, setStateInternal] as const;
36
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useTerminalSize.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 { useEffect, useState } from 'react';
8
+
9
+ const TERMINAL_PADDING_X = 8;
10
+
11
+ export function useTerminalSize(): { columns: number; rows: number } {
12
+ const [size, setSize] = useState({
13
+ columns: (process.stdout.columns || 60) - TERMINAL_PADDING_X,
14
+ rows: process.stdout.rows || 20,
15
+ });
16
+
17
+ useEffect(() => {
18
+ function updateSize() {
19
+ setSize({
20
+ columns: (process.stdout.columns || 60) - TERMINAL_PADDING_X,
21
+ rows: process.stdout.rows || 20,
22
+ });
23
+ }
24
+
25
+ process.stdout.on('resize', updateSize);
26
+ return () => {
27
+ process.stdout.off('resize', updateSize);
28
+ };
29
+ }, []);
30
+
31
+ return size;
32
+ }
projects/ui/qwen-code/packages/cli/src/ui/hooks/useThemeCommand.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useState, useCallback, useEffect } from 'react';
8
+ import { themeManager } from '../themes/theme-manager.js';
9
+ import { LoadedSettings, SettingScope } from '../../config/settings.js'; // Import LoadedSettings, AppSettings, MergedSetting
10
+ import { type HistoryItem, MessageType } from '../types.js';
11
+ import process from 'node:process';
12
+
13
+ interface UseThemeCommandReturn {
14
+ isThemeDialogOpen: boolean;
15
+ openThemeDialog: () => void;
16
+ handleThemeSelect: (
17
+ themeName: string | undefined,
18
+ scope: SettingScope,
19
+ ) => void; // Added scope
20
+ handleThemeHighlight: (themeName: string | undefined) => void;
21
+ }
22
+
23
+ export const useThemeCommand = (
24
+ loadedSettings: LoadedSettings,
25
+ setThemeError: (error: string | null) => void,
26
+ addItem: (item: Omit<HistoryItem, 'id'>, timestamp: number) => void,
27
+ ): UseThemeCommandReturn => {
28
+ const [isThemeDialogOpen, setIsThemeDialogOpen] = useState(false);
29
+
30
+ // Check for invalid theme configuration on startup
31
+ useEffect(() => {
32
+ const effectiveTheme = loadedSettings.merged.theme;
33
+ if (effectiveTheme && !themeManager.findThemeByName(effectiveTheme)) {
34
+ setIsThemeDialogOpen(true);
35
+ setThemeError(`Theme "${effectiveTheme}" not found.`);
36
+ } else {
37
+ setThemeError(null);
38
+ }
39
+ }, [loadedSettings.merged.theme, setThemeError]);
40
+
41
+ const openThemeDialog = useCallback(() => {
42
+ if (process.env['NO_COLOR']) {
43
+ addItem(
44
+ {
45
+ type: MessageType.INFO,
46
+ text: 'Theme configuration unavailable due to NO_COLOR env variable.',
47
+ },
48
+ Date.now(),
49
+ );
50
+ return;
51
+ }
52
+ setIsThemeDialogOpen(true);
53
+ }, [addItem]);
54
+
55
+ const applyTheme = useCallback(
56
+ (themeName: string | undefined) => {
57
+ if (!themeManager.setActiveTheme(themeName)) {
58
+ // If theme is not found, open the theme selection dialog and set error message
59
+ setIsThemeDialogOpen(true);
60
+ setThemeError(`Theme "${themeName}" not found.`);
61
+ } else {
62
+ setThemeError(null); // Clear any previous theme error on success
63
+ }
64
+ },
65
+ [setThemeError],
66
+ );
67
+
68
+ const handleThemeHighlight = useCallback(
69
+ (themeName: string | undefined) => {
70
+ applyTheme(themeName);
71
+ },
72
+ [applyTheme],
73
+ );
74
+
75
+ const handleThemeSelect = useCallback(
76
+ (themeName: string | undefined, scope: SettingScope) => {
77
+ try {
78
+ // Merge user and workspace custom themes (workspace takes precedence)
79
+ const mergedCustomThemes = {
80
+ ...(loadedSettings.user.settings.customThemes || {}),
81
+ ...(loadedSettings.workspace.settings.customThemes || {}),
82
+ };
83
+ // Only allow selecting themes available in the merged custom themes or built-in themes
84
+ const isBuiltIn = themeManager.findThemeByName(themeName);
85
+ const isCustom = themeName && mergedCustomThemes[themeName];
86
+ if (!isBuiltIn && !isCustom) {
87
+ setThemeError(`Theme "${themeName}" not found in selected scope.`);
88
+ setIsThemeDialogOpen(true);
89
+ return;
90
+ }
91
+ loadedSettings.setValue(scope, 'theme', themeName); // Update the merged settings
92
+ if (loadedSettings.merged.customThemes) {
93
+ themeManager.loadCustomThemes(loadedSettings.merged.customThemes);
94
+ }
95
+ applyTheme(loadedSettings.merged.theme); // Apply the current theme
96
+ setThemeError(null);
97
+ } finally {
98
+ setIsThemeDialogOpen(false); // Close the dialog
99
+ }
100
+ },
101
+ [applyTheme, loadedSettings, setThemeError],
102
+ );
103
+
104
+ return {
105
+ isThemeDialogOpen,
106
+ openThemeDialog,
107
+ handleThemeSelect,
108
+ handleThemeHighlight,
109
+ };
110
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useTimer.test.ts ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { useTimer } from './useTimer.js';
10
+
11
+ describe('useTimer', () => {
12
+ beforeEach(() => {
13
+ vi.useFakeTimers();
14
+ });
15
+
16
+ afterEach(() => {
17
+ vi.restoreAllMocks();
18
+ });
19
+
20
+ it('should initialize with 0', () => {
21
+ const { result } = renderHook(() => useTimer(false, 0));
22
+ expect(result.current).toBe(0);
23
+ });
24
+
25
+ it('should not increment time if isActive is false', () => {
26
+ const { result } = renderHook(() => useTimer(false, 0));
27
+ act(() => {
28
+ vi.advanceTimersByTime(5000);
29
+ });
30
+ expect(result.current).toBe(0);
31
+ });
32
+
33
+ it('should increment time every second if isActive is true', () => {
34
+ const { result } = renderHook(() => useTimer(true, 0));
35
+ act(() => {
36
+ vi.advanceTimersByTime(1000);
37
+ });
38
+ expect(result.current).toBe(1);
39
+ act(() => {
40
+ vi.advanceTimersByTime(2000);
41
+ });
42
+ expect(result.current).toBe(3);
43
+ });
44
+
45
+ it('should reset to 0 and start incrementing when isActive becomes true from false', () => {
46
+ const { result, rerender } = renderHook(
47
+ ({ isActive, resetKey }) => useTimer(isActive, resetKey),
48
+ { initialProps: { isActive: false, resetKey: 0 } },
49
+ );
50
+ expect(result.current).toBe(0);
51
+
52
+ rerender({ isActive: true, resetKey: 0 });
53
+ expect(result.current).toBe(0); // Should reset to 0 upon becoming active
54
+
55
+ act(() => {
56
+ vi.advanceTimersByTime(1000);
57
+ });
58
+ expect(result.current).toBe(1);
59
+ });
60
+
61
+ it('should reset to 0 when resetKey changes while active', () => {
62
+ const { result, rerender } = renderHook(
63
+ ({ isActive, resetKey }) => useTimer(isActive, resetKey),
64
+ { initialProps: { isActive: true, resetKey: 0 } },
65
+ );
66
+ act(() => {
67
+ vi.advanceTimersByTime(3000); // 3s
68
+ });
69
+ expect(result.current).toBe(3);
70
+
71
+ rerender({ isActive: true, resetKey: 1 }); // Change resetKey
72
+ expect(result.current).toBe(0); // Should reset to 0
73
+
74
+ act(() => {
75
+ vi.advanceTimersByTime(1000);
76
+ });
77
+ expect(result.current).toBe(1); // Starts incrementing from 0
78
+ });
79
+
80
+ it('should be 0 if isActive is false, regardless of resetKey changes', () => {
81
+ const { result, rerender } = renderHook(
82
+ ({ isActive, resetKey }) => useTimer(isActive, resetKey),
83
+ { initialProps: { isActive: false, resetKey: 0 } },
84
+ );
85
+ expect(result.current).toBe(0);
86
+
87
+ rerender({ isActive: false, resetKey: 1 });
88
+ expect(result.current).toBe(0);
89
+ });
90
+
91
+ it('should clear timer on unmount', () => {
92
+ const { unmount } = renderHook(() => useTimer(true, 0));
93
+ const clearIntervalSpy = vi.spyOn(global, 'clearInterval');
94
+ unmount();
95
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
96
+ });
97
+
98
+ it('should preserve elapsedTime when isActive becomes false, and reset to 0 when it becomes active again', () => {
99
+ const { result, rerender } = renderHook(
100
+ ({ isActive, resetKey }) => useTimer(isActive, resetKey),
101
+ { initialProps: { isActive: true, resetKey: 0 } },
102
+ );
103
+
104
+ act(() => {
105
+ vi.advanceTimersByTime(3000); // Advance to 3 seconds
106
+ });
107
+ expect(result.current).toBe(3);
108
+
109
+ rerender({ isActive: false, resetKey: 0 });
110
+ expect(result.current).toBe(3); // Time should be preserved when timer becomes inactive
111
+
112
+ // Now make it active again, it should reset to 0
113
+ rerender({ isActive: true, resetKey: 0 });
114
+ expect(result.current).toBe(0);
115
+ act(() => {
116
+ vi.advanceTimersByTime(1000);
117
+ });
118
+ expect(result.current).toBe(1);
119
+ });
120
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/useTimer.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ /**
10
+ * Custom hook to manage a timer that increments every second.
11
+ * @param isActive Whether the timer should be running.
12
+ * @param resetKey A key that, when changed, will reset the timer to 0 and restart the interval.
13
+ * @returns The elapsed time in seconds.
14
+ */
15
+ export const useTimer = (isActive: boolean, resetKey: unknown) => {
16
+ const [elapsedTime, setElapsedTime] = useState(0);
17
+ const timerRef = useRef<NodeJS.Timeout | null>(null);
18
+ const prevResetKeyRef = useRef(resetKey);
19
+ const prevIsActiveRef = useRef(isActive);
20
+
21
+ useEffect(() => {
22
+ let shouldResetTime = false;
23
+
24
+ if (prevResetKeyRef.current !== resetKey) {
25
+ shouldResetTime = true;
26
+ prevResetKeyRef.current = resetKey;
27
+ }
28
+
29
+ if (prevIsActiveRef.current === false && isActive) {
30
+ // Transitioned from inactive to active
31
+ shouldResetTime = true;
32
+ }
33
+
34
+ if (shouldResetTime) {
35
+ setElapsedTime(0);
36
+ }
37
+ prevIsActiveRef.current = isActive;
38
+
39
+ // Manage interval
40
+ if (isActive) {
41
+ // Clear previous interval unconditionally before starting a new one
42
+ // This handles resetKey changes while active, ensuring a fresh interval start.
43
+ if (timerRef.current) {
44
+ clearInterval(timerRef.current);
45
+ }
46
+ timerRef.current = setInterval(() => {
47
+ setElapsedTime((prev) => prev + 1);
48
+ }, 1000);
49
+ } else {
50
+ if (timerRef.current) {
51
+ clearInterval(timerRef.current);
52
+ timerRef.current = null;
53
+ }
54
+ }
55
+
56
+ return () => {
57
+ if (timerRef.current) {
58
+ clearInterval(timerRef.current);
59
+ timerRef.current = null;
60
+ }
61
+ };
62
+ }, [isActive, resetKey]);
63
+
64
+ return elapsedTime;
65
+ };
projects/ui/qwen-code/packages/cli/src/ui/hooks/useToolScheduler.test.ts ADDED
@@ -0,0 +1,1123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+ import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
9
+ import { renderHook, act } from '@testing-library/react';
10
+ import {
11
+ useReactToolScheduler,
12
+ mapToDisplay,
13
+ } from './useReactToolScheduler.js';
14
+ import { PartUnion, FunctionResponse } from '@google/genai';
15
+ import {
16
+ Config,
17
+ ToolCallRequestInfo,
18
+ ToolRegistry,
19
+ ToolResult,
20
+ ToolCallConfirmationDetails,
21
+ ToolConfirmationOutcome,
22
+ ToolCallResponseInfo,
23
+ ToolCall, // Import from core
24
+ Status as ToolCallStatusType,
25
+ ApprovalMode,
26
+ Kind,
27
+ BaseDeclarativeTool,
28
+ BaseToolInvocation,
29
+ ToolInvocation,
30
+ AnyDeclarativeTool,
31
+ AnyToolInvocation,
32
+ } from '@qwen-code/qwen-code-core';
33
+ import {
34
+ HistoryItemWithoutId,
35
+ ToolCallStatus,
36
+ HistoryItemToolGroup,
37
+ } from '../types.js';
38
+
39
+ // Mocks
40
+ vi.mock('@qwen-code/qwen-code-core', async () => {
41
+ const actual = await vi.importActual('@qwen-code/qwen-code-core');
42
+ return {
43
+ ...actual,
44
+ ToolRegistry: vi.fn(),
45
+ Config: vi.fn(),
46
+ };
47
+ });
48
+
49
+ const mockToolRegistry = {
50
+ getTool: vi.fn(),
51
+ };
52
+
53
+ const mockConfig = {
54
+ getToolRegistry: vi.fn(() => mockToolRegistry as unknown as ToolRegistry),
55
+ getApprovalMode: vi.fn(() => ApprovalMode.DEFAULT),
56
+ getUsageStatisticsEnabled: () => true,
57
+ getDebugMode: () => false,
58
+ getSessionId: () => 'test-session-id',
59
+ getContentGeneratorConfig: () => ({
60
+ model: 'test-model',
61
+ authType: 'oauth-personal',
62
+ }),
63
+ };
64
+
65
+ class MockToolInvocation extends BaseToolInvocation<object, ToolResult> {
66
+ constructor(
67
+ private readonly tool: MockTool,
68
+ params: object,
69
+ ) {
70
+ super(params);
71
+ }
72
+
73
+ getDescription(): string {
74
+ return JSON.stringify(this.params);
75
+ }
76
+
77
+ override shouldConfirmExecute(
78
+ abortSignal: AbortSignal,
79
+ ): Promise<ToolCallConfirmationDetails | false> {
80
+ return this.tool.shouldConfirmExecute(this.params, abortSignal);
81
+ }
82
+
83
+ execute(
84
+ signal: AbortSignal,
85
+ updateOutput?: (output: string) => void,
86
+ terminalColumns?: number,
87
+ terminalRows?: number,
88
+ ): Promise<ToolResult> {
89
+ return this.tool.execute(
90
+ this.params,
91
+ signal,
92
+ updateOutput,
93
+ terminalColumns,
94
+ terminalRows,
95
+ );
96
+ }
97
+ }
98
+
99
+ class MockTool extends BaseDeclarativeTool<object, ToolResult> {
100
+ constructor(
101
+ name: string,
102
+ displayName: string,
103
+ canUpdateOutput = false,
104
+ shouldConfirm = false,
105
+ isOutputMarkdown = false,
106
+ ) {
107
+ super(
108
+ name,
109
+ displayName,
110
+ 'A mock tool for testing',
111
+ Kind.Other,
112
+ {},
113
+ isOutputMarkdown,
114
+ canUpdateOutput,
115
+ );
116
+ if (shouldConfirm) {
117
+ this.shouldConfirmExecute.mockImplementation(
118
+ async (): Promise<ToolCallConfirmationDetails | false> => ({
119
+ type: 'edit',
120
+ title: 'Mock Tool Requires Confirmation',
121
+ onConfirm: mockOnUserConfirmForToolConfirmation,
122
+ filePath: 'mock',
123
+ fileName: 'mockToolRequiresConfirmation.ts',
124
+ fileDiff: 'Mock tool requires confirmation',
125
+ originalContent: 'Original content',
126
+ newContent: 'New content',
127
+ }),
128
+ );
129
+ }
130
+ }
131
+
132
+ execute = vi.fn();
133
+ shouldConfirmExecute = vi.fn();
134
+
135
+ protected createInvocation(
136
+ params: object,
137
+ ): ToolInvocation<object, ToolResult> {
138
+ return new MockToolInvocation(this, params);
139
+ }
140
+ }
141
+
142
+ const mockTool = new MockTool('mockTool', 'Mock Tool');
143
+ const mockToolWithLiveOutput = new MockTool(
144
+ 'mockToolWithLiveOutput',
145
+ 'Mock Tool With Live Output',
146
+ true,
147
+ );
148
+ let mockOnUserConfirmForToolConfirmation: Mock;
149
+ const mockToolRequiresConfirmation = new MockTool(
150
+ 'mockToolRequiresConfirmation',
151
+ 'Mock Tool Requires Confirmation',
152
+ false,
153
+ true,
154
+ );
155
+
156
+ describe('useReactToolScheduler in YOLO Mode', () => {
157
+ let onComplete: Mock;
158
+ let setPendingHistoryItem: Mock;
159
+
160
+ beforeEach(() => {
161
+ onComplete = vi.fn();
162
+ setPendingHistoryItem = vi.fn();
163
+ mockToolRegistry.getTool.mockClear();
164
+ (mockToolRequiresConfirmation.execute as Mock).mockClear();
165
+ (mockToolRequiresConfirmation.shouldConfirmExecute as Mock).mockClear();
166
+
167
+ // IMPORTANT: Enable YOLO mode for this test suite
168
+ (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.YOLO);
169
+
170
+ vi.useFakeTimers();
171
+ });
172
+
173
+ afterEach(() => {
174
+ vi.clearAllTimers();
175
+ vi.useRealTimers();
176
+ // IMPORTANT: Disable YOLO mode after this test suite
177
+ (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.DEFAULT);
178
+ });
179
+
180
+ const renderSchedulerInYoloMode = () =>
181
+ renderHook(() =>
182
+ useReactToolScheduler(
183
+ onComplete,
184
+ mockConfig as unknown as Config,
185
+ setPendingHistoryItem,
186
+ () => undefined,
187
+ () => {},
188
+ ),
189
+ );
190
+
191
+ it('should skip confirmation and execute tool directly when yoloMode is true', async () => {
192
+ mockToolRegistry.getTool.mockReturnValue(mockToolRequiresConfirmation);
193
+ const expectedOutput = 'YOLO Confirmed output';
194
+ (mockToolRequiresConfirmation.execute as Mock).mockResolvedValue({
195
+ llmContent: expectedOutput,
196
+ returnDisplay: 'YOLO Formatted tool output',
197
+ summary: 'YOLO summary',
198
+ } as ToolResult);
199
+
200
+ const { result } = renderSchedulerInYoloMode();
201
+ const schedule = result.current[1];
202
+ const request: ToolCallRequestInfo = {
203
+ callId: 'yoloCall',
204
+ name: 'mockToolRequiresConfirmation',
205
+ args: { data: 'any data' },
206
+ } as any;
207
+
208
+ act(() => {
209
+ schedule(request, new AbortController().signal);
210
+ });
211
+
212
+ await act(async () => {
213
+ await vi.runAllTimersAsync(); // Process validation
214
+ });
215
+ await act(async () => {
216
+ await vi.runAllTimersAsync(); // Process scheduling
217
+ });
218
+ await act(async () => {
219
+ await vi.runAllTimersAsync(); // Process execution
220
+ });
221
+
222
+ // Check that shouldConfirmExecute was NOT called
223
+ expect(
224
+ mockToolRequiresConfirmation.shouldConfirmExecute,
225
+ ).not.toHaveBeenCalled();
226
+
227
+ // Check that execute WAS called
228
+ expect(mockToolRequiresConfirmation.execute).toHaveBeenCalledWith(
229
+ request.args,
230
+ expect.any(AbortSignal),
231
+ undefined,
232
+ undefined,
233
+ undefined,
234
+ );
235
+
236
+ // Check that onComplete was called with success
237
+ expect(onComplete).toHaveBeenCalledWith([
238
+ expect.objectContaining({
239
+ status: 'success',
240
+ request,
241
+ response: expect.objectContaining({
242
+ resultDisplay: 'YOLO Formatted tool output',
243
+ responseParts: {
244
+ functionResponse: {
245
+ id: 'yoloCall',
246
+ name: 'mockToolRequiresConfirmation',
247
+ response: { output: expectedOutput },
248
+ },
249
+ },
250
+ }),
251
+ }),
252
+ ]);
253
+
254
+ // Ensure no confirmation UI was triggered (setPendingHistoryItem should not have been called with confirmation details)
255
+ const setPendingHistoryItemCalls = setPendingHistoryItem.mock.calls;
256
+ const confirmationCall = setPendingHistoryItemCalls.find((call) => {
257
+ const item = typeof call[0] === 'function' ? call[0]({}) : call[0];
258
+ return item?.tools?.[0]?.confirmationDetails;
259
+ });
260
+ expect(confirmationCall).toBeUndefined();
261
+ });
262
+ });
263
+
264
+ describe('useReactToolScheduler', () => {
265
+ // TODO(ntaylormullen): The following tests are skipped due to difficulties in
266
+ // reliably testing the asynchronous state updates and interactions with timers.
267
+ // These tests involve complex sequences of events, including confirmations,
268
+ // live output updates, and cancellations, which are challenging to assert
269
+ // correctly with the current testing setup. Further investigation is needed
270
+ // to find a robust way to test these scenarios.
271
+ let onComplete: Mock;
272
+ let setPendingHistoryItem: Mock;
273
+ let capturedOnConfirmForTest:
274
+ | ((outcome: ToolConfirmationOutcome) => void | Promise<void>)
275
+ | undefined;
276
+
277
+ beforeEach(() => {
278
+ onComplete = vi.fn();
279
+ capturedOnConfirmForTest = undefined;
280
+ setPendingHistoryItem = vi.fn((updaterOrValue) => {
281
+ let pendingItem: HistoryItemWithoutId | null = null;
282
+ if (typeof updaterOrValue === 'function') {
283
+ // Loosen the type for prevState to allow for more flexible updates in tests
284
+ const prevState: Partial<HistoryItemToolGroup> = {
285
+ type: 'tool_group', // Still default to tool_group for most cases
286
+ tools: [],
287
+ };
288
+
289
+ pendingItem = updaterOrValue(prevState as any); // Allow any for more flexibility
290
+ } else {
291
+ pendingItem = updaterOrValue;
292
+ }
293
+ // Capture onConfirm if it exists, regardless of the exact type of pendingItem
294
+ // This is a common pattern in these tests.
295
+ if (
296
+ (pendingItem as HistoryItemToolGroup)?.tools?.[0]?.confirmationDetails
297
+ ?.onConfirm
298
+ ) {
299
+ capturedOnConfirmForTest = (pendingItem as HistoryItemToolGroup)
300
+ .tools[0].confirmationDetails?.onConfirm;
301
+ }
302
+ });
303
+
304
+ mockToolRegistry.getTool.mockClear();
305
+ (mockTool.execute as Mock).mockClear();
306
+ (mockTool.shouldConfirmExecute as Mock).mockClear();
307
+ (mockToolWithLiveOutput.execute as Mock).mockClear();
308
+ (mockToolWithLiveOutput.shouldConfirmExecute as Mock).mockClear();
309
+ (mockToolRequiresConfirmation.execute as Mock).mockClear();
310
+ (mockToolRequiresConfirmation.shouldConfirmExecute as Mock).mockClear();
311
+
312
+ mockOnUserConfirmForToolConfirmation = vi.fn();
313
+ (
314
+ mockToolRequiresConfirmation.shouldConfirmExecute as Mock
315
+ ).mockImplementation(
316
+ async (): Promise<ToolCallConfirmationDetails | null> =>
317
+ ({
318
+ onConfirm: mockOnUserConfirmForToolConfirmation,
319
+ fileName: 'mockToolRequiresConfirmation.ts',
320
+ fileDiff: 'Mock tool requires confirmation',
321
+ type: 'edit',
322
+ title: 'Mock Tool Requires Confirmation',
323
+ }) as any,
324
+ );
325
+
326
+ vi.useFakeTimers();
327
+ });
328
+
329
+ afterEach(() => {
330
+ vi.clearAllTimers();
331
+ vi.useRealTimers();
332
+ });
333
+
334
+ const renderScheduler = () =>
335
+ renderHook(() =>
336
+ useReactToolScheduler(
337
+ onComplete,
338
+ mockConfig as unknown as Config,
339
+ setPendingHistoryItem,
340
+ () => undefined,
341
+ () => {},
342
+ ),
343
+ );
344
+
345
+ it('initial state should be empty', () => {
346
+ const { result } = renderScheduler();
347
+ expect(result.current[0]).toEqual([]);
348
+ });
349
+
350
+ it('should schedule and execute a tool call successfully', async () => {
351
+ mockToolRegistry.getTool.mockReturnValue(mockTool);
352
+ (mockTool.execute as Mock).mockResolvedValue({
353
+ llmContent: 'Tool output',
354
+ returnDisplay: 'Formatted tool output',
355
+ summary: 'Formatted summary',
356
+ } as ToolResult);
357
+ (mockTool.shouldConfirmExecute as Mock).mockResolvedValue(null);
358
+
359
+ const { result } = renderScheduler();
360
+ const schedule = result.current[1];
361
+ const request: ToolCallRequestInfo = {
362
+ callId: 'call1',
363
+ name: 'mockTool',
364
+ args: { param: 'value' },
365
+ } as any;
366
+
367
+ act(() => {
368
+ schedule(request, new AbortController().signal);
369
+ });
370
+ await act(async () => {
371
+ await vi.runAllTimersAsync();
372
+ });
373
+ await act(async () => {
374
+ await vi.runAllTimersAsync();
375
+ });
376
+ await act(async () => {
377
+ await vi.runAllTimersAsync();
378
+ });
379
+
380
+ expect(mockTool.execute).toHaveBeenCalledWith(
381
+ request.args,
382
+ expect.any(AbortSignal),
383
+ undefined,
384
+ undefined,
385
+ undefined,
386
+ );
387
+ expect(onComplete).toHaveBeenCalledWith([
388
+ expect.objectContaining({
389
+ status: 'success',
390
+ request,
391
+ response: expect.objectContaining({
392
+ resultDisplay: 'Formatted tool output',
393
+ responseParts: {
394
+ functionResponse: {
395
+ id: 'call1',
396
+ name: 'mockTool',
397
+ response: { output: 'Tool output' },
398
+ },
399
+ },
400
+ }),
401
+ }),
402
+ ]);
403
+ expect(result.current[0]).toEqual([]);
404
+ });
405
+
406
+ it('should handle tool not found', async () => {
407
+ mockToolRegistry.getTool.mockReturnValue(undefined);
408
+ const { result } = renderScheduler();
409
+ const schedule = result.current[1];
410
+ const request: ToolCallRequestInfo = {
411
+ callId: 'call1',
412
+ name: 'nonexistentTool',
413
+ args: {},
414
+ } as any;
415
+
416
+ act(() => {
417
+ schedule(request, new AbortController().signal);
418
+ });
419
+ await act(async () => {
420
+ await vi.runAllTimersAsync();
421
+ });
422
+ await act(async () => {
423
+ await vi.runAllTimersAsync();
424
+ });
425
+
426
+ expect(onComplete).toHaveBeenCalledWith([
427
+ expect.objectContaining({
428
+ status: 'error',
429
+ request,
430
+ response: expect.objectContaining({
431
+ error: expect.objectContaining({
432
+ message: 'Tool "nonexistentTool" not found in registry.',
433
+ }),
434
+ }),
435
+ }),
436
+ ]);
437
+ expect(result.current[0]).toEqual([]);
438
+ });
439
+
440
+ it('should handle error during shouldConfirmExecute', async () => {
441
+ mockToolRegistry.getTool.mockReturnValue(mockTool);
442
+ const confirmError = new Error('Confirmation check failed');
443
+ (mockTool.shouldConfirmExecute as Mock).mockRejectedValue(confirmError);
444
+
445
+ const { result } = renderScheduler();
446
+ const schedule = result.current[1];
447
+ const request: ToolCallRequestInfo = {
448
+ callId: 'call1',
449
+ name: 'mockTool',
450
+ args: {},
451
+ } as any;
452
+
453
+ act(() => {
454
+ schedule(request, new AbortController().signal);
455
+ });
456
+ await act(async () => {
457
+ await vi.runAllTimersAsync();
458
+ });
459
+ await act(async () => {
460
+ await vi.runAllTimersAsync();
461
+ });
462
+
463
+ expect(onComplete).toHaveBeenCalledWith([
464
+ expect.objectContaining({
465
+ status: 'error',
466
+ request,
467
+ response: expect.objectContaining({
468
+ error: confirmError,
469
+ }),
470
+ }),
471
+ ]);
472
+ expect(result.current[0]).toEqual([]);
473
+ });
474
+
475
+ it('should handle error during execute', async () => {
476
+ mockToolRegistry.getTool.mockReturnValue(mockTool);
477
+ (mockTool.shouldConfirmExecute as Mock).mockResolvedValue(null);
478
+ const execError = new Error('Execution failed');
479
+ (mockTool.execute as Mock).mockRejectedValue(execError);
480
+
481
+ const { result } = renderScheduler();
482
+ const schedule = result.current[1];
483
+ const request: ToolCallRequestInfo = {
484
+ callId: 'call1',
485
+ name: 'mockTool',
486
+ args: {},
487
+ } as any;
488
+
489
+ act(() => {
490
+ schedule(request, new AbortController().signal);
491
+ });
492
+ await act(async () => {
493
+ await vi.runAllTimersAsync();
494
+ });
495
+ await act(async () => {
496
+ await vi.runAllTimersAsync();
497
+ });
498
+ await act(async () => {
499
+ await vi.runAllTimersAsync();
500
+ });
501
+
502
+ expect(onComplete).toHaveBeenCalledWith([
503
+ expect.objectContaining({
504
+ status: 'error',
505
+ request,
506
+ response: expect.objectContaining({
507
+ error: execError,
508
+ }),
509
+ }),
510
+ ]);
511
+ expect(result.current[0]).toEqual([]);
512
+ });
513
+
514
+ it.skip('should handle tool requiring confirmation - approved', async () => {
515
+ mockToolRegistry.getTool.mockReturnValue(mockToolRequiresConfirmation);
516
+ const expectedOutput = 'Confirmed output';
517
+ (mockToolRequiresConfirmation.execute as Mock).mockResolvedValue({
518
+ llmContent: expectedOutput,
519
+ returnDisplay: 'Confirmed display',
520
+ summary: 'Confirmed summary',
521
+ } as ToolResult);
522
+
523
+ const { result } = renderScheduler();
524
+ const schedule = result.current[1];
525
+ const request: ToolCallRequestInfo = {
526
+ callId: 'callConfirm',
527
+ name: 'mockToolRequiresConfirmation',
528
+ args: { data: 'sensitive' },
529
+ } as any;
530
+
531
+ act(() => {
532
+ schedule(request, new AbortController().signal);
533
+ });
534
+ await act(async () => {
535
+ await vi.runAllTimersAsync();
536
+ });
537
+
538
+ expect(setPendingHistoryItem).toHaveBeenCalled();
539
+ expect(capturedOnConfirmForTest).toBeDefined();
540
+
541
+ await act(async () => {
542
+ await capturedOnConfirmForTest?.(ToolConfirmationOutcome.ProceedOnce);
543
+ });
544
+
545
+ await act(async () => {
546
+ await vi.runAllTimersAsync();
547
+ });
548
+ await act(async () => {
549
+ await vi.runAllTimersAsync();
550
+ });
551
+ await act(async () => {
552
+ await vi.runAllTimersAsync();
553
+ });
554
+
555
+ expect(mockOnUserConfirmForToolConfirmation).toHaveBeenCalledWith(
556
+ ToolConfirmationOutcome.ProceedOnce,
557
+ );
558
+ expect(mockToolRequiresConfirmation.execute).toHaveBeenCalled();
559
+ expect(onComplete).toHaveBeenCalledWith([
560
+ expect.objectContaining({
561
+ status: 'success',
562
+ request,
563
+ response: expect.objectContaining({
564
+ resultDisplay: 'Confirmed display',
565
+ responseParts: expect.arrayContaining([
566
+ expect.objectContaining({
567
+ functionResponse: expect.objectContaining({
568
+ response: { output: expectedOutput },
569
+ }),
570
+ }),
571
+ ]),
572
+ }),
573
+ }),
574
+ ]);
575
+ });
576
+
577
+ it.skip('should handle tool requiring confirmation - cancelled by user', async () => {
578
+ mockToolRegistry.getTool.mockReturnValue(mockToolRequiresConfirmation);
579
+ const { result } = renderScheduler();
580
+ const schedule = result.current[1];
581
+ const request: ToolCallRequestInfo = {
582
+ callId: 'callConfirmCancel',
583
+ name: 'mockToolRequiresConfirmation',
584
+ args: {},
585
+ } as any;
586
+
587
+ act(() => {
588
+ schedule(request, new AbortController().signal);
589
+ });
590
+ await act(async () => {
591
+ await vi.runAllTimersAsync();
592
+ });
593
+
594
+ expect(setPendingHistoryItem).toHaveBeenCalled();
595
+ expect(capturedOnConfirmForTest).toBeDefined();
596
+
597
+ await act(async () => {
598
+ await capturedOnConfirmForTest?.(ToolConfirmationOutcome.Cancel);
599
+ });
600
+ await act(async () => {
601
+ await vi.runAllTimersAsync();
602
+ });
603
+ await act(async () => {
604
+ await vi.runAllTimersAsync();
605
+ });
606
+
607
+ expect(mockOnUserConfirmForToolConfirmation).toHaveBeenCalledWith(
608
+ ToolConfirmationOutcome.Cancel,
609
+ );
610
+ expect(onComplete).toHaveBeenCalledWith([
611
+ expect.objectContaining({
612
+ status: 'cancelled',
613
+ request,
614
+ response: expect.objectContaining({
615
+ responseParts: expect.arrayContaining([
616
+ expect.objectContaining({
617
+ functionResponse: expect.objectContaining({
618
+ response: expect.objectContaining({
619
+ error: `User did not allow tool call ${request.name}. Reason: User cancelled.`,
620
+ }),
621
+ }),
622
+ }),
623
+ ]),
624
+ }),
625
+ }),
626
+ ]);
627
+ });
628
+
629
+ it.skip('should handle live output updates', async () => {
630
+ mockToolRegistry.getTool.mockReturnValue(mockToolWithLiveOutput);
631
+ let liveUpdateFn: ((output: string) => void) | undefined;
632
+ let resolveExecutePromise: (value: ToolResult) => void;
633
+ const executePromise = new Promise<ToolResult>((resolve) => {
634
+ resolveExecutePromise = resolve;
635
+ });
636
+
637
+ (mockToolWithLiveOutput.execute as Mock).mockImplementation(
638
+ async (
639
+ _args: Record<string, unknown>,
640
+ _signal: AbortSignal,
641
+ updateFn: ((output: string) => void) | undefined,
642
+ ) => {
643
+ liveUpdateFn = updateFn;
644
+ return executePromise;
645
+ },
646
+ );
647
+ (mockToolWithLiveOutput.shouldConfirmExecute as Mock).mockResolvedValue(
648
+ null,
649
+ );
650
+
651
+ const { result } = renderScheduler();
652
+ const schedule = result.current[1];
653
+ const request: ToolCallRequestInfo = {
654
+ callId: 'liveCall',
655
+ name: 'mockToolWithLiveOutput',
656
+ args: {},
657
+ } as any;
658
+
659
+ act(() => {
660
+ schedule(request, new AbortController().signal);
661
+ });
662
+ await act(async () => {
663
+ await vi.runAllTimersAsync();
664
+ });
665
+
666
+ expect(liveUpdateFn).toBeDefined();
667
+ expect(setPendingHistoryItem).toHaveBeenCalled();
668
+
669
+ await act(async () => {
670
+ liveUpdateFn?.('Live output 1');
671
+ });
672
+ await act(async () => {
673
+ await vi.runAllTimersAsync();
674
+ });
675
+
676
+ await act(async () => {
677
+ liveUpdateFn?.('Live output 2');
678
+ });
679
+ await act(async () => {
680
+ await vi.runAllTimersAsync();
681
+ });
682
+
683
+ act(() => {
684
+ resolveExecutePromise({
685
+ llmContent: 'Final output',
686
+ returnDisplay: 'Final display',
687
+ summary: 'Final summary',
688
+ } as ToolResult);
689
+ });
690
+ await act(async () => {
691
+ await vi.runAllTimersAsync();
692
+ });
693
+ await act(async () => {
694
+ await vi.runAllTimersAsync();
695
+ });
696
+
697
+ expect(onComplete).toHaveBeenCalledWith([
698
+ expect.objectContaining({
699
+ status: 'success',
700
+ request,
701
+ response: expect.objectContaining({
702
+ resultDisplay: 'Final display',
703
+ responseParts: expect.arrayContaining([
704
+ expect.objectContaining({
705
+ functionResponse: expect.objectContaining({
706
+ response: { output: 'Final output' },
707
+ }),
708
+ }),
709
+ ]),
710
+ }),
711
+ }),
712
+ ]);
713
+ expect(result.current[0]).toEqual([]);
714
+ });
715
+
716
+ it('should schedule and execute multiple tool calls', async () => {
717
+ const tool1 = new MockTool('tool1', 'Tool 1');
718
+ tool1.execute.mockResolvedValue({
719
+ llmContent: 'Output 1',
720
+ returnDisplay: 'Display 1',
721
+ summary: 'Summary 1',
722
+ } as ToolResult);
723
+ tool1.shouldConfirmExecute.mockResolvedValue(null);
724
+
725
+ const tool2 = new MockTool('tool2', 'Tool 2');
726
+ tool2.execute.mockResolvedValue({
727
+ llmContent: 'Output 2',
728
+ returnDisplay: 'Display 2',
729
+ summary: 'Summary 2',
730
+ } as ToolResult);
731
+ tool2.shouldConfirmExecute.mockResolvedValue(null);
732
+
733
+ mockToolRegistry.getTool.mockImplementation((name) => {
734
+ if (name === 'tool1') return tool1;
735
+ if (name === 'tool2') return tool2;
736
+ return undefined;
737
+ });
738
+
739
+ const { result } = renderScheduler();
740
+ const schedule = result.current[1];
741
+ const requests: ToolCallRequestInfo[] = [
742
+ { callId: 'multi1', name: 'tool1', args: { p: 1 } } as any,
743
+ { callId: 'multi2', name: 'tool2', args: { p: 2 } } as any,
744
+ ];
745
+
746
+ act(() => {
747
+ schedule(requests, new AbortController().signal);
748
+ });
749
+ await act(async () => {
750
+ await vi.runAllTimersAsync();
751
+ });
752
+ await act(async () => {
753
+ await vi.runAllTimersAsync();
754
+ });
755
+ await act(async () => {
756
+ await vi.runAllTimersAsync();
757
+ });
758
+ await act(async () => {
759
+ await vi.runAllTimersAsync();
760
+ });
761
+
762
+ expect(onComplete).toHaveBeenCalledTimes(1);
763
+ const completedCalls = onComplete.mock.calls[0][0] as ToolCall[];
764
+ expect(completedCalls.length).toBe(2);
765
+
766
+ const call1Result = completedCalls.find(
767
+ (c) => c.request.callId === 'multi1',
768
+ );
769
+ const call2Result = completedCalls.find(
770
+ (c) => c.request.callId === 'multi2',
771
+ );
772
+
773
+ expect(call1Result).toMatchObject({
774
+ status: 'success',
775
+ request: requests[0],
776
+ response: expect.objectContaining({
777
+ resultDisplay: 'Display 1',
778
+ responseParts: {
779
+ functionResponse: {
780
+ id: 'multi1',
781
+ name: 'tool1',
782
+ response: { output: 'Output 1' },
783
+ },
784
+ },
785
+ }),
786
+ });
787
+ expect(call2Result).toMatchObject({
788
+ status: 'success',
789
+ request: requests[1],
790
+ response: expect.objectContaining({
791
+ resultDisplay: 'Display 2',
792
+ responseParts: {
793
+ functionResponse: {
794
+ id: 'multi2',
795
+ name: 'tool2',
796
+ response: { output: 'Output 2' },
797
+ },
798
+ },
799
+ }),
800
+ });
801
+ expect(result.current[0]).toEqual([]);
802
+ });
803
+
804
+ it.skip('should throw error if scheduling while already running', async () => {
805
+ mockToolRegistry.getTool.mockReturnValue(mockTool);
806
+ const longExecutePromise = new Promise<ToolResult>((resolve) =>
807
+ setTimeout(
808
+ () =>
809
+ resolve({
810
+ llmContent: 'done',
811
+ returnDisplay: 'done display',
812
+ summary: 'done summary',
813
+ }),
814
+ 50,
815
+ ),
816
+ );
817
+ (mockTool.execute as Mock).mockReturnValue(longExecutePromise);
818
+ (mockTool.shouldConfirmExecute as Mock).mockResolvedValue(null);
819
+
820
+ const { result } = renderScheduler();
821
+ const schedule = result.current[1];
822
+ const request1: ToolCallRequestInfo = {
823
+ callId: 'run1',
824
+ name: 'mockTool',
825
+ args: {},
826
+ } as any;
827
+ const request2: ToolCallRequestInfo = {
828
+ callId: 'run2',
829
+ name: 'mockTool',
830
+ args: {},
831
+ } as any;
832
+
833
+ act(() => {
834
+ schedule(request1, new AbortController().signal);
835
+ });
836
+ await act(async () => {
837
+ await vi.runAllTimersAsync();
838
+ });
839
+
840
+ expect(() => schedule(request2, new AbortController().signal)).toThrow(
841
+ 'Cannot schedule tool calls while other tool calls are running',
842
+ );
843
+
844
+ await act(async () => {
845
+ await vi.advanceTimersByTimeAsync(50);
846
+ await vi.runAllTimersAsync();
847
+ await act(async () => {
848
+ await vi.runAllTimersAsync();
849
+ });
850
+ });
851
+ expect(onComplete).toHaveBeenCalledWith([
852
+ expect.objectContaining({
853
+ status: 'success',
854
+ request: request1,
855
+ response: expect.objectContaining({ resultDisplay: 'done display' }),
856
+ }),
857
+ ]);
858
+ expect(result.current[0]).toEqual([]);
859
+ });
860
+ });
861
+
862
+ describe('mapToDisplay', () => {
863
+ const baseRequest: ToolCallRequestInfo = {
864
+ callId: 'testCallId',
865
+ name: 'testTool',
866
+ args: { foo: 'bar' },
867
+ } as any;
868
+
869
+ const baseTool = new MockTool('testTool', 'Test Tool Display');
870
+
871
+ const baseResponse: ToolCallResponseInfo = {
872
+ callId: 'testCallId',
873
+ responseParts: [
874
+ {
875
+ functionResponse: {
876
+ name: 'testTool',
877
+ id: 'testCallId',
878
+ response: { output: 'Test output' },
879
+ } as FunctionResponse,
880
+ } as PartUnion,
881
+ ],
882
+ resultDisplay: 'Test display output',
883
+ error: undefined,
884
+ } as any;
885
+
886
+ // Define a more specific type for extraProps for these tests
887
+ // This helps ensure that tool and confirmationDetails are only accessed when they are expected to exist.
888
+ type MapToDisplayExtraProps =
889
+ | {
890
+ tool?: AnyDeclarativeTool;
891
+ invocation?: AnyToolInvocation;
892
+ liveOutput?: string;
893
+ response?: ToolCallResponseInfo;
894
+ confirmationDetails?: ToolCallConfirmationDetails;
895
+ }
896
+ | {
897
+ tool: AnyDeclarativeTool;
898
+ invocation?: AnyToolInvocation;
899
+ response?: ToolCallResponseInfo;
900
+ confirmationDetails?: ToolCallConfirmationDetails;
901
+ }
902
+ | {
903
+ response: ToolCallResponseInfo;
904
+ tool?: undefined;
905
+ confirmationDetails?: ToolCallConfirmationDetails;
906
+ }
907
+ | {
908
+ confirmationDetails: ToolCallConfirmationDetails;
909
+ tool?: AnyDeclarativeTool;
910
+ invocation?: AnyToolInvocation;
911
+ response?: ToolCallResponseInfo;
912
+ };
913
+
914
+ const baseInvocation = baseTool.build(baseRequest.args);
915
+ const testCases: Array<{
916
+ name: string;
917
+ status: ToolCallStatusType;
918
+ extraProps?: MapToDisplayExtraProps;
919
+ expectedStatus: ToolCallStatus;
920
+ expectedResultDisplay?: string;
921
+ expectedName?: string;
922
+ expectedDescription?: string;
923
+ }> = [
924
+ {
925
+ name: 'validating',
926
+ status: 'validating',
927
+ extraProps: { tool: baseTool, invocation: baseInvocation },
928
+ expectedStatus: ToolCallStatus.Executing,
929
+ expectedName: baseTool.displayName,
930
+ expectedDescription: baseInvocation.getDescription(),
931
+ },
932
+ {
933
+ name: 'awaiting_approval',
934
+ status: 'awaiting_approval',
935
+ extraProps: {
936
+ tool: baseTool,
937
+ invocation: baseInvocation,
938
+ confirmationDetails: {
939
+ onConfirm: vi.fn(),
940
+ type: 'edit',
941
+ title: 'Test Tool Display',
942
+ serverName: 'testTool',
943
+ toolName: 'testTool',
944
+ toolDisplayName: 'Test Tool Display',
945
+ filePath: 'mock',
946
+ fileName: 'test.ts',
947
+ fileDiff: 'Test diff',
948
+ originalContent: 'Original content',
949
+ newContent: 'New content',
950
+ } as ToolCallConfirmationDetails,
951
+ },
952
+ expectedStatus: ToolCallStatus.Confirming,
953
+ expectedName: baseTool.displayName,
954
+ expectedDescription: baseInvocation.getDescription(),
955
+ },
956
+ {
957
+ name: 'scheduled',
958
+ status: 'scheduled',
959
+ extraProps: { tool: baseTool, invocation: baseInvocation },
960
+ expectedStatus: ToolCallStatus.Pending,
961
+ expectedName: baseTool.displayName,
962
+ expectedDescription: baseInvocation.getDescription(),
963
+ },
964
+ {
965
+ name: 'executing no live output',
966
+ status: 'executing',
967
+ extraProps: { tool: baseTool, invocation: baseInvocation },
968
+ expectedStatus: ToolCallStatus.Executing,
969
+ expectedName: baseTool.displayName,
970
+ expectedDescription: baseInvocation.getDescription(),
971
+ },
972
+ {
973
+ name: 'executing with live output',
974
+ status: 'executing',
975
+ extraProps: {
976
+ tool: baseTool,
977
+ invocation: baseInvocation,
978
+ liveOutput: 'Live test output',
979
+ },
980
+ expectedStatus: ToolCallStatus.Executing,
981
+ expectedResultDisplay: 'Live test output',
982
+ expectedName: baseTool.displayName,
983
+ expectedDescription: baseInvocation.getDescription(),
984
+ },
985
+ {
986
+ name: 'success',
987
+ status: 'success',
988
+ extraProps: {
989
+ tool: baseTool,
990
+ invocation: baseInvocation,
991
+ response: baseResponse,
992
+ },
993
+ expectedStatus: ToolCallStatus.Success,
994
+ expectedResultDisplay: baseResponse.resultDisplay as any,
995
+ expectedName: baseTool.displayName,
996
+ expectedDescription: baseInvocation.getDescription(),
997
+ },
998
+ {
999
+ name: 'error tool not found',
1000
+ status: 'error',
1001
+ extraProps: {
1002
+ response: {
1003
+ ...baseResponse,
1004
+ error: new Error('Test error tool not found'),
1005
+ resultDisplay: 'Error display tool not found',
1006
+ },
1007
+ },
1008
+ expectedStatus: ToolCallStatus.Error,
1009
+ expectedResultDisplay: 'Error display tool not found',
1010
+ expectedName: baseRequest.name,
1011
+ expectedDescription: JSON.stringify(baseRequest.args),
1012
+ },
1013
+ {
1014
+ name: 'error tool execution failed',
1015
+ status: 'error',
1016
+ extraProps: {
1017
+ tool: baseTool,
1018
+ response: {
1019
+ ...baseResponse,
1020
+ error: new Error('Tool execution failed'),
1021
+ resultDisplay: 'Execution failed display',
1022
+ },
1023
+ },
1024
+ expectedStatus: ToolCallStatus.Error,
1025
+ expectedResultDisplay: 'Execution failed display',
1026
+ expectedName: baseTool.displayName, // Changed from baseTool.name
1027
+ expectedDescription: baseInvocation.getDescription(),
1028
+ },
1029
+ {
1030
+ name: 'cancelled',
1031
+ status: 'cancelled',
1032
+ extraProps: {
1033
+ tool: baseTool,
1034
+ invocation: baseInvocation,
1035
+ response: {
1036
+ ...baseResponse,
1037
+ resultDisplay: 'Cancelled display',
1038
+ },
1039
+ },
1040
+ expectedStatus: ToolCallStatus.Canceled,
1041
+ expectedResultDisplay: 'Cancelled display',
1042
+ expectedName: baseTool.displayName,
1043
+ expectedDescription: baseInvocation.getDescription(),
1044
+ },
1045
+ ];
1046
+
1047
+ testCases.forEach(
1048
+ ({
1049
+ name: testName,
1050
+ status,
1051
+ extraProps,
1052
+ expectedStatus,
1053
+ expectedResultDisplay,
1054
+ expectedName,
1055
+ expectedDescription,
1056
+ }) => {
1057
+ it(`should map ToolCall with status '${status}' (${testName}) correctly`, () => {
1058
+ const toolCall: ToolCall = {
1059
+ request: baseRequest,
1060
+ status,
1061
+ ...(extraProps || {}),
1062
+ } as ToolCall;
1063
+
1064
+ const display = mapToDisplay(toolCall);
1065
+ expect(display.type).toBe('tool_group');
1066
+ expect(display.tools.length).toBe(1);
1067
+ const toolDisplay = display.tools[0];
1068
+
1069
+ expect(toolDisplay.callId).toBe(baseRequest.callId);
1070
+ expect(toolDisplay.status).toBe(expectedStatus);
1071
+ expect(toolDisplay.resultDisplay).toBe(expectedResultDisplay);
1072
+
1073
+ expect(toolDisplay.name).toBe(expectedName);
1074
+ expect(toolDisplay.description).toBe(expectedDescription);
1075
+
1076
+ expect(toolDisplay.renderOutputAsMarkdown).toBe(
1077
+ extraProps?.tool?.isOutputMarkdown ?? false,
1078
+ );
1079
+ if (status === 'awaiting_approval') {
1080
+ expect(toolDisplay.confirmationDetails).toBe(
1081
+ extraProps!.confirmationDetails,
1082
+ );
1083
+ } else {
1084
+ expect(toolDisplay.confirmationDetails).toBeUndefined();
1085
+ }
1086
+ });
1087
+ },
1088
+ );
1089
+
1090
+ it('should map an array of ToolCalls correctly', () => {
1091
+ const toolCall1: ToolCall = {
1092
+ request: { ...baseRequest, callId: 'call1' },
1093
+ status: 'success',
1094
+ tool: baseTool,
1095
+ invocation: baseTool.build(baseRequest.args),
1096
+ response: { ...baseResponse, callId: 'call1' },
1097
+ } as ToolCall;
1098
+ const toolForCall2 = new MockTool(
1099
+ baseTool.name,
1100
+ baseTool.displayName,
1101
+ false,
1102
+ false,
1103
+ true,
1104
+ );
1105
+ const toolCall2: ToolCall = {
1106
+ request: { ...baseRequest, callId: 'call2' },
1107
+ status: 'executing',
1108
+ tool: toolForCall2,
1109
+ invocation: toolForCall2.build(baseRequest.args),
1110
+ liveOutput: 'markdown output',
1111
+ } as ToolCall;
1112
+
1113
+ const display = mapToDisplay([toolCall1, toolCall2]);
1114
+ expect(display.tools.length).toBe(2);
1115
+ expect(display.tools[0].callId).toBe('call1');
1116
+ expect(display.tools[0].status).toBe(ToolCallStatus.Success);
1117
+ expect(display.tools[0].renderOutputAsMarkdown).toBe(false);
1118
+ expect(display.tools[1].callId).toBe('call2');
1119
+ expect(display.tools[1].status).toBe(ToolCallStatus.Executing);
1120
+ expect(display.tools[1].resultDisplay).toBe('markdown output');
1121
+ expect(display.tools[1].renderOutputAsMarkdown).toBe(true);
1122
+ });
1123
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/vim.test.ts ADDED
@@ -0,0 +1,1691 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
8
+ import { renderHook, act } from '@testing-library/react';
9
+ import React from 'react';
10
+ import { useVim } from './vim.js';
11
+ import type { TextBuffer } from '../components/shared/text-buffer.js';
12
+ import { textBufferReducer } from '../components/shared/text-buffer.js';
13
+
14
+ // Mock the VimModeContext
15
+ const mockVimContext = {
16
+ vimEnabled: true,
17
+ vimMode: 'NORMAL' as const,
18
+ toggleVimEnabled: vi.fn(),
19
+ setVimMode: vi.fn(),
20
+ };
21
+
22
+ vi.mock('../contexts/VimModeContext.js', () => ({
23
+ useVimMode: () => mockVimContext,
24
+ VimModeProvider: ({ children }: { children: React.ReactNode }) => children,
25
+ }));
26
+
27
+ // Test constants
28
+ const TEST_SEQUENCES = {
29
+ ESCAPE: { sequence: '\u001b', name: 'escape' },
30
+ LEFT: { sequence: 'h' },
31
+ RIGHT: { sequence: 'l' },
32
+ UP: { sequence: 'k' },
33
+ DOWN: { sequence: 'j' },
34
+ INSERT: { sequence: 'i' },
35
+ APPEND: { sequence: 'a' },
36
+ DELETE_CHAR: { sequence: 'x' },
37
+ DELETE: { sequence: 'd' },
38
+ CHANGE: { sequence: 'c' },
39
+ WORD_FORWARD: { sequence: 'w' },
40
+ WORD_BACKWARD: { sequence: 'b' },
41
+ WORD_END: { sequence: 'e' },
42
+ LINE_START: { sequence: '0' },
43
+ LINE_END: { sequence: '$' },
44
+ REPEAT: { sequence: '.' },
45
+ } as const;
46
+
47
+ describe('useVim hook', () => {
48
+ let mockBuffer: Partial<TextBuffer>;
49
+ let mockHandleFinalSubmit: vi.Mock;
50
+
51
+ const createMockBuffer = (
52
+ text = 'hello world',
53
+ cursor: [number, number] = [0, 5],
54
+ ) => {
55
+ const cursorState = { pos: cursor };
56
+ const lines = text.split('\n');
57
+
58
+ return {
59
+ lines,
60
+ get cursor() {
61
+ return cursorState.pos;
62
+ },
63
+ set cursor(newPos: [number, number]) {
64
+ cursorState.pos = newPos;
65
+ },
66
+ text,
67
+ move: vi.fn().mockImplementation((direction: string) => {
68
+ let [row, col] = cursorState.pos;
69
+ const _line = lines[row] || '';
70
+ if (direction === 'left') {
71
+ col = Math.max(0, col - 1);
72
+ } else if (direction === 'right') {
73
+ col = Math.min(line.length, col + 1);
74
+ } else if (direction === 'home') {
75
+ col = 0;
76
+ } else if (direction === 'end') {
77
+ col = line.length;
78
+ }
79
+ cursorState.pos = [row, col];
80
+ }),
81
+ del: vi.fn(),
82
+ moveToOffset: vi.fn(),
83
+ insert: vi.fn(),
84
+ newline: vi.fn(),
85
+ replaceRangeByOffset: vi.fn(),
86
+ handleInput: vi.fn(),
87
+ setText: vi.fn(),
88
+ // Vim-specific methods
89
+ vimDeleteWordForward: vi.fn(),
90
+ vimDeleteWordBackward: vi.fn(),
91
+ vimDeleteWordEnd: vi.fn(),
92
+ vimChangeWordForward: vi.fn(),
93
+ vimChangeWordBackward: vi.fn(),
94
+ vimChangeWordEnd: vi.fn(),
95
+ vimDeleteLine: vi.fn(),
96
+ vimChangeLine: vi.fn(),
97
+ vimDeleteToEndOfLine: vi.fn(),
98
+ vimChangeToEndOfLine: vi.fn(),
99
+ vimChangeMovement: vi.fn(),
100
+ vimMoveLeft: vi.fn(),
101
+ vimMoveRight: vi.fn(),
102
+ vimMoveUp: vi.fn(),
103
+ vimMoveDown: vi.fn(),
104
+ vimMoveWordForward: vi.fn(),
105
+ vimMoveWordBackward: vi.fn(),
106
+ vimMoveWordEnd: vi.fn(),
107
+ vimDeleteChar: vi.fn(),
108
+ vimInsertAtCursor: vi.fn(),
109
+ vimAppendAtCursor: vi.fn().mockImplementation(() => {
110
+ // Append moves cursor right (vim 'a' behavior - position after current char)
111
+ const [row, col] = cursorState.pos;
112
+ const _line = lines[row] || '';
113
+ // In vim, 'a' moves cursor to position after current character
114
+ // This allows inserting at the end of the line
115
+ cursorState.pos = [row, col + 1];
116
+ }),
117
+ vimOpenLineBelow: vi.fn(),
118
+ vimOpenLineAbove: vi.fn(),
119
+ vimAppendAtLineEnd: vi.fn(),
120
+ vimInsertAtLineStart: vi.fn(),
121
+ vimMoveToLineStart: vi.fn(),
122
+ vimMoveToLineEnd: vi.fn(),
123
+ vimMoveToFirstNonWhitespace: vi.fn(),
124
+ vimMoveToFirstLine: vi.fn(),
125
+ vimMoveToLastLine: vi.fn(),
126
+ vimMoveToLine: vi.fn(),
127
+ vimEscapeInsertMode: vi.fn().mockImplementation(() => {
128
+ // Escape moves cursor left unless at beginning of line
129
+ const [row, col] = cursorState.pos;
130
+ if (col > 0) {
131
+ cursorState.pos = [row, col - 1];
132
+ }
133
+ }),
134
+ };
135
+ };
136
+
137
+ const _createMockSettings = (vimMode = true) => ({
138
+ getValue: vi.fn().mockReturnValue(vimMode),
139
+ setValue: vi.fn(),
140
+ merged: { vimMode },
141
+ });
142
+
143
+ const renderVimHook = (buffer?: Partial<TextBuffer>) =>
144
+ renderHook(() =>
145
+ useVim((buffer || mockBuffer) as TextBuffer, mockHandleFinalSubmit),
146
+ );
147
+
148
+ const exitInsertMode = (result: {
149
+ current: {
150
+ handleInput: (input: { sequence: string; name: string }) => void;
151
+ };
152
+ }) => {
153
+ act(() => {
154
+ result.current.handleInput({ sequence: '\u001b', name: 'escape' });
155
+ });
156
+ };
157
+
158
+ beforeEach(() => {
159
+ vi.clearAllMocks();
160
+ mockHandleFinalSubmit = vi.fn();
161
+ mockBuffer = createMockBuffer();
162
+ // Reset mock context to default state
163
+ mockVimContext.vimEnabled = true;
164
+ mockVimContext.vimMode = 'NORMAL';
165
+ mockVimContext.toggleVimEnabled.mockClear();
166
+ mockVimContext.setVimMode.mockClear();
167
+ });
168
+
169
+ describe('Mode switching', () => {
170
+ it('should start in NORMAL mode', () => {
171
+ const { result } = renderVimHook();
172
+ expect(result.current.mode).toBe('NORMAL');
173
+ });
174
+
175
+ it('should switch to INSERT mode with i command', () => {
176
+ const { result } = renderVimHook();
177
+
178
+ act(() => {
179
+ result.current.handleInput(TEST_SEQUENCES.INSERT);
180
+ });
181
+
182
+ expect(result.current.mode).toBe('INSERT');
183
+ expect(mockVimContext.setVimMode).toHaveBeenCalledWith('INSERT');
184
+ });
185
+
186
+ it('should switch back to NORMAL mode with Escape', () => {
187
+ const { result } = renderVimHook();
188
+
189
+ act(() => {
190
+ result.current.handleInput(TEST_SEQUENCES.INSERT);
191
+ });
192
+ expect(result.current.mode).toBe('INSERT');
193
+
194
+ exitInsertMode(result);
195
+ expect(result.current.mode).toBe('NORMAL');
196
+ });
197
+
198
+ it('should properly handle escape followed immediately by a command', () => {
199
+ const testBuffer = createMockBuffer('hello world test', [0, 6]);
200
+ const { result } = renderVimHook(testBuffer);
201
+
202
+ act(() => {
203
+ result.current.handleInput({ sequence: 'i' });
204
+ });
205
+ expect(result.current.mode).toBe('INSERT');
206
+
207
+ vi.clearAllMocks();
208
+
209
+ exitInsertMode(result);
210
+ expect(result.current.mode).toBe('NORMAL');
211
+
212
+ act(() => {
213
+ result.current.handleInput({ sequence: 'b' });
214
+ });
215
+
216
+ expect(testBuffer.vimMoveWordBackward).toHaveBeenCalledWith(1);
217
+ });
218
+ });
219
+
220
+ describe('Navigation commands', () => {
221
+ it('should handle h (left movement)', () => {
222
+ const { result } = renderVimHook();
223
+
224
+ act(() => {
225
+ result.current.handleInput({ sequence: 'h' });
226
+ });
227
+
228
+ expect(mockBuffer.vimMoveLeft).toHaveBeenCalledWith(1);
229
+ });
230
+
231
+ it('should handle l (right movement)', () => {
232
+ const { result } = renderVimHook();
233
+
234
+ act(() => {
235
+ result.current.handleInput({ sequence: 'l' });
236
+ });
237
+
238
+ expect(mockBuffer.vimMoveRight).toHaveBeenCalledWith(1);
239
+ });
240
+
241
+ it('should handle j (down movement)', () => {
242
+ const testBuffer = createMockBuffer('first line\nsecond line');
243
+ const { result } = renderVimHook(testBuffer);
244
+
245
+ act(() => {
246
+ result.current.handleInput({ sequence: 'j' });
247
+ });
248
+
249
+ expect(testBuffer.vimMoveDown).toHaveBeenCalledWith(1);
250
+ });
251
+
252
+ it('should handle k (up movement)', () => {
253
+ const testBuffer = createMockBuffer('first line\nsecond line');
254
+ const { result } = renderVimHook(testBuffer);
255
+
256
+ act(() => {
257
+ result.current.handleInput({ sequence: 'k' });
258
+ });
259
+
260
+ expect(testBuffer.vimMoveUp).toHaveBeenCalledWith(1);
261
+ });
262
+
263
+ it('should handle 0 (move to start of line)', () => {
264
+ const { result } = renderVimHook();
265
+
266
+ act(() => {
267
+ result.current.handleInput({ sequence: '0' });
268
+ });
269
+
270
+ expect(mockBuffer.vimMoveToLineStart).toHaveBeenCalled();
271
+ });
272
+
273
+ it('should handle $ (move to end of line)', () => {
274
+ const { result } = renderVimHook();
275
+
276
+ act(() => {
277
+ result.current.handleInput({ sequence: '$' });
278
+ });
279
+
280
+ expect(mockBuffer.vimMoveToLineEnd).toHaveBeenCalled();
281
+ });
282
+ });
283
+
284
+ describe('Mode switching commands', () => {
285
+ it('should handle a (append after cursor)', () => {
286
+ const { result } = renderVimHook();
287
+
288
+ act(() => {
289
+ result.current.handleInput({ sequence: 'a' });
290
+ });
291
+
292
+ expect(mockBuffer.vimAppendAtCursor).toHaveBeenCalled();
293
+ expect(result.current.mode).toBe('INSERT');
294
+ });
295
+
296
+ it('should handle A (append at end of line)', () => {
297
+ const { result } = renderVimHook();
298
+
299
+ act(() => {
300
+ result.current.handleInput({ sequence: 'A' });
301
+ });
302
+
303
+ expect(mockBuffer.vimAppendAtLineEnd).toHaveBeenCalled();
304
+ expect(result.current.mode).toBe('INSERT');
305
+ });
306
+
307
+ it('should handle o (open line below)', () => {
308
+ const { result } = renderVimHook();
309
+
310
+ act(() => {
311
+ result.current.handleInput({ sequence: 'o' });
312
+ });
313
+
314
+ expect(mockBuffer.vimOpenLineBelow).toHaveBeenCalled();
315
+ expect(result.current.mode).toBe('INSERT');
316
+ });
317
+
318
+ it('should handle O (open line above)', () => {
319
+ const { result } = renderVimHook();
320
+
321
+ act(() => {
322
+ result.current.handleInput({ sequence: 'O' });
323
+ });
324
+
325
+ expect(mockBuffer.vimOpenLineAbove).toHaveBeenCalled();
326
+ expect(result.current.mode).toBe('INSERT');
327
+ });
328
+ });
329
+
330
+ describe('Edit commands', () => {
331
+ it('should handle x (delete character)', () => {
332
+ const { result } = renderVimHook();
333
+ vi.clearAllMocks();
334
+
335
+ act(() => {
336
+ result.current.handleInput({ sequence: 'x' });
337
+ });
338
+
339
+ expect(mockBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
340
+ });
341
+
342
+ it('should move cursor left when deleting last character on line (vim behavior)', () => {
343
+ const testBuffer = createMockBuffer('hello', [0, 4]);
344
+ const { result } = renderVimHook(testBuffer);
345
+
346
+ act(() => {
347
+ result.current.handleInput({ sequence: 'x' });
348
+ });
349
+
350
+ expect(testBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
351
+ });
352
+
353
+ it('should handle first d key (sets pending state)', () => {
354
+ const { result } = renderVimHook();
355
+
356
+ act(() => {
357
+ result.current.handleInput({ sequence: 'd' });
358
+ });
359
+
360
+ expect(mockBuffer.replaceRangeByOffset).not.toHaveBeenCalled();
361
+ });
362
+ });
363
+
364
+ describe('Count handling', () => {
365
+ it('should handle count input and return to count 0 after command', () => {
366
+ const { result } = renderVimHook();
367
+
368
+ act(() => {
369
+ const handled = result.current.handleInput({ sequence: '3' });
370
+ expect(handled).toBe(true);
371
+ });
372
+
373
+ act(() => {
374
+ const handled = result.current.handleInput({ sequence: 'h' });
375
+ expect(handled).toBe(true);
376
+ });
377
+
378
+ expect(mockBuffer.vimMoveLeft).toHaveBeenCalledWith(3);
379
+ });
380
+
381
+ it('should only delete 1 character with x command when no count is specified', () => {
382
+ const testBuffer = createMockBuffer();
383
+ const { result } = renderVimHook(testBuffer);
384
+
385
+ act(() => {
386
+ result.current.handleInput({ sequence: 'x' });
387
+ });
388
+
389
+ expect(testBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
390
+ });
391
+ });
392
+
393
+ describe('Word movement', () => {
394
+ it('should properly initialize vim hook with word movement support', () => {
395
+ const testBuffer = createMockBuffer('cat elephant mouse', [0, 0]);
396
+ const { result } = renderVimHook(testBuffer);
397
+
398
+ expect(result.current.vimModeEnabled).toBe(true);
399
+ expect(result.current.mode).toBe('NORMAL');
400
+ expect(result.current.handleInput).toBeDefined();
401
+ });
402
+
403
+ it('should support vim mode and basic operations across multiple lines', () => {
404
+ const testBuffer = createMockBuffer(
405
+ 'first line word\nsecond line word',
406
+ [0, 11],
407
+ );
408
+ const { result } = renderVimHook(testBuffer);
409
+
410
+ expect(result.current.vimModeEnabled).toBe(true);
411
+ expect(result.current.mode).toBe('NORMAL');
412
+ expect(result.current.handleInput).toBeDefined();
413
+ expect(testBuffer.replaceRangeByOffset).toBeDefined();
414
+ expect(testBuffer.moveToOffset).toBeDefined();
415
+ });
416
+
417
+ it('should handle w (next word)', () => {
418
+ const testBuffer = createMockBuffer('hello world test');
419
+ const { result } = renderVimHook(testBuffer);
420
+
421
+ act(() => {
422
+ result.current.handleInput({ sequence: 'w' });
423
+ });
424
+
425
+ expect(testBuffer.vimMoveWordForward).toHaveBeenCalledWith(1);
426
+ });
427
+
428
+ it('should handle b (previous word)', () => {
429
+ const testBuffer = createMockBuffer('hello world test', [0, 6]);
430
+ const { result } = renderVimHook(testBuffer);
431
+
432
+ act(() => {
433
+ result.current.handleInput({ sequence: 'b' });
434
+ });
435
+
436
+ expect(testBuffer.vimMoveWordBackward).toHaveBeenCalledWith(1);
437
+ });
438
+
439
+ it('should handle e (end of word)', () => {
440
+ const testBuffer = createMockBuffer('hello world test');
441
+ const { result } = renderVimHook(testBuffer);
442
+
443
+ act(() => {
444
+ result.current.handleInput({ sequence: 'e' });
445
+ });
446
+
447
+ expect(testBuffer.vimMoveWordEnd).toHaveBeenCalledWith(1);
448
+ });
449
+
450
+ it('should handle w when cursor is on the last word', () => {
451
+ const testBuffer = createMockBuffer('hello world', [0, 8]);
452
+ const { result } = renderVimHook(testBuffer);
453
+
454
+ act(() => {
455
+ result.current.handleInput({ sequence: 'w' });
456
+ });
457
+
458
+ expect(testBuffer.vimMoveWordForward).toHaveBeenCalledWith(1);
459
+ });
460
+
461
+ it('should handle first c key (sets pending change state)', () => {
462
+ const { result } = renderVimHook();
463
+
464
+ act(() => {
465
+ result.current.handleInput({ sequence: 'c' });
466
+ });
467
+
468
+ expect(result.current.mode).toBe('NORMAL');
469
+ expect(mockBuffer.del).not.toHaveBeenCalled();
470
+ });
471
+
472
+ it('should clear pending state on invalid command sequence (df)', () => {
473
+ const { result } = renderVimHook();
474
+
475
+ act(() => {
476
+ result.current.handleInput({ sequence: 'd' });
477
+ result.current.handleInput({ sequence: 'f' });
478
+ });
479
+
480
+ expect(mockBuffer.replaceRangeByOffset).not.toHaveBeenCalled();
481
+ expect(mockBuffer.del).not.toHaveBeenCalled();
482
+ });
483
+
484
+ it('should clear pending state with Escape in NORMAL mode', () => {
485
+ const { result } = renderVimHook();
486
+
487
+ act(() => {
488
+ result.current.handleInput({ sequence: 'd' });
489
+ });
490
+
491
+ exitInsertMode(result);
492
+
493
+ expect(mockBuffer.replaceRangeByOffset).not.toHaveBeenCalled();
494
+ });
495
+ });
496
+
497
+ describe('Disabled vim mode', () => {
498
+ it('should not respond to vim commands when disabled', () => {
499
+ mockVimContext.vimEnabled = false;
500
+ const { result } = renderVimHook(mockBuffer);
501
+
502
+ act(() => {
503
+ result.current.handleInput({ sequence: 'h' });
504
+ });
505
+
506
+ expect(mockBuffer.move).not.toHaveBeenCalled();
507
+ });
508
+ });
509
+
510
+ // These tests are no longer applicable at the hook level
511
+
512
+ describe('Command repeat system', () => {
513
+ it('should repeat x command from current cursor position', () => {
514
+ const testBuffer = createMockBuffer('abcd\nefgh\nijkl', [0, 1]);
515
+ const { result } = renderVimHook(testBuffer);
516
+
517
+ act(() => {
518
+ result.current.handleInput({ sequence: 'x' });
519
+ });
520
+ expect(testBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
521
+
522
+ testBuffer.cursor = [1, 2];
523
+
524
+ act(() => {
525
+ result.current.handleInput({ sequence: '.' });
526
+ });
527
+ expect(testBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
528
+ });
529
+
530
+ it('should repeat dd command from current position', () => {
531
+ const testBuffer = createMockBuffer('line1\nline2\nline3', [1, 0]);
532
+ const { result } = renderVimHook(testBuffer);
533
+
534
+ act(() => {
535
+ result.current.handleInput({ sequence: 'd' });
536
+ });
537
+ act(() => {
538
+ result.current.handleInput({ sequence: 'd' });
539
+ });
540
+ expect(testBuffer.vimDeleteLine).toHaveBeenCalledTimes(1);
541
+
542
+ testBuffer.cursor = [0, 0];
543
+
544
+ act(() => {
545
+ result.current.handleInput({ sequence: '.' });
546
+ });
547
+
548
+ expect(testBuffer.vimDeleteLine).toHaveBeenCalledTimes(2);
549
+ });
550
+
551
+ it('should repeat ce command from current position', () => {
552
+ const testBuffer = createMockBuffer('word', [0, 0]);
553
+ const { result } = renderVimHook(testBuffer);
554
+
555
+ act(() => {
556
+ result.current.handleInput({ sequence: 'c' });
557
+ });
558
+ act(() => {
559
+ result.current.handleInput({ sequence: 'e' });
560
+ });
561
+ expect(testBuffer.vimChangeWordEnd).toHaveBeenCalledTimes(1);
562
+
563
+ // Exit INSERT mode to complete the command
564
+ exitInsertMode(result);
565
+
566
+ testBuffer.cursor = [0, 2];
567
+
568
+ act(() => {
569
+ result.current.handleInput({ sequence: '.' });
570
+ });
571
+
572
+ expect(testBuffer.vimChangeWordEnd).toHaveBeenCalledTimes(2);
573
+ });
574
+
575
+ it('should repeat cc command from current position', () => {
576
+ const testBuffer = createMockBuffer('line1\nline2\nline3', [1, 2]);
577
+ const { result } = renderVimHook(testBuffer);
578
+
579
+ act(() => {
580
+ result.current.handleInput({ sequence: 'c' });
581
+ });
582
+ act(() => {
583
+ result.current.handleInput({ sequence: 'c' });
584
+ });
585
+ expect(testBuffer.vimChangeLine).toHaveBeenCalledTimes(1);
586
+
587
+ // Exit INSERT mode to complete the command
588
+ exitInsertMode(result);
589
+
590
+ testBuffer.cursor = [0, 1];
591
+
592
+ act(() => {
593
+ result.current.handleInput({ sequence: '.' });
594
+ });
595
+
596
+ expect(testBuffer.vimChangeLine).toHaveBeenCalledTimes(2);
597
+ });
598
+
599
+ it('should repeat cw command from current position', () => {
600
+ const testBuffer = createMockBuffer('hello world test', [0, 6]);
601
+ const { result } = renderVimHook(testBuffer);
602
+
603
+ act(() => {
604
+ result.current.handleInput({ sequence: 'c' });
605
+ });
606
+ act(() => {
607
+ result.current.handleInput({ sequence: 'w' });
608
+ });
609
+ expect(testBuffer.vimChangeWordForward).toHaveBeenCalledTimes(1);
610
+
611
+ // Exit INSERT mode to complete the command
612
+ exitInsertMode(result);
613
+
614
+ testBuffer.cursor = [0, 0];
615
+
616
+ act(() => {
617
+ result.current.handleInput({ sequence: '.' });
618
+ });
619
+
620
+ expect(testBuffer.vimChangeWordForward).toHaveBeenCalledTimes(2);
621
+ });
622
+
623
+ it('should repeat D command from current position', () => {
624
+ const testBuffer = createMockBuffer('hello world test', [0, 6]);
625
+ const { result } = renderVimHook(testBuffer);
626
+
627
+ act(() => {
628
+ result.current.handleInput({ sequence: 'D' });
629
+ });
630
+ expect(testBuffer.vimDeleteToEndOfLine).toHaveBeenCalledTimes(1);
631
+
632
+ testBuffer.cursor = [0, 2];
633
+ vi.clearAllMocks(); // Clear all mocks instead of just one method
634
+
635
+ act(() => {
636
+ result.current.handleInput({ sequence: '.' });
637
+ });
638
+
639
+ expect(testBuffer.vimDeleteToEndOfLine).toHaveBeenCalledTimes(1);
640
+ });
641
+
642
+ it('should repeat C command from current position', () => {
643
+ const testBuffer = createMockBuffer('hello world test', [0, 6]);
644
+ const { result } = renderVimHook(testBuffer);
645
+
646
+ act(() => {
647
+ result.current.handleInput({ sequence: 'C' });
648
+ });
649
+ expect(testBuffer.vimChangeToEndOfLine).toHaveBeenCalledTimes(1);
650
+
651
+ // Exit INSERT mode to complete the command
652
+ exitInsertMode(result);
653
+
654
+ testBuffer.cursor = [0, 2];
655
+
656
+ act(() => {
657
+ result.current.handleInput({ sequence: '.' });
658
+ });
659
+
660
+ expect(testBuffer.vimChangeToEndOfLine).toHaveBeenCalledTimes(2);
661
+ });
662
+
663
+ it('should repeat command after cursor movement', () => {
664
+ const testBuffer = createMockBuffer('test text', [0, 0]);
665
+ const { result } = renderVimHook(testBuffer);
666
+
667
+ act(() => {
668
+ result.current.handleInput({ sequence: 'x' });
669
+ });
670
+ expect(testBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
671
+
672
+ testBuffer.cursor = [0, 2];
673
+
674
+ act(() => {
675
+ result.current.handleInput({ sequence: '.' });
676
+ });
677
+ expect(testBuffer.vimDeleteChar).toHaveBeenCalledWith(1);
678
+ });
679
+
680
+ it('should move cursor to the correct position after exiting INSERT mode with "a"', () => {
681
+ const testBuffer = createMockBuffer('hello world', [0, 10]);
682
+ const { result } = renderVimHook(testBuffer);
683
+
684
+ act(() => {
685
+ result.current.handleInput({ sequence: 'a' });
686
+ });
687
+ expect(result.current.mode).toBe('INSERT');
688
+ expect(testBuffer.cursor).toEqual([0, 11]);
689
+
690
+ exitInsertMode(result);
691
+ expect(result.current.mode).toBe('NORMAL');
692
+ expect(testBuffer.cursor).toEqual([0, 10]);
693
+ });
694
+ });
695
+
696
+ describe('Special characters and edge cases', () => {
697
+ it('should handle ^ (move to first non-whitespace character)', () => {
698
+ const testBuffer = createMockBuffer(' hello world', [0, 5]);
699
+ const { result } = renderVimHook(testBuffer);
700
+
701
+ act(() => {
702
+ result.current.handleInput({ sequence: '^' });
703
+ });
704
+
705
+ expect(testBuffer.vimMoveToFirstNonWhitespace).toHaveBeenCalled();
706
+ });
707
+
708
+ it('should handle G without count (go to last line)', () => {
709
+ const testBuffer = createMockBuffer('line1\nline2\nline3', [0, 0]);
710
+ const { result } = renderVimHook(testBuffer);
711
+
712
+ act(() => {
713
+ result.current.handleInput({ sequence: 'G' });
714
+ });
715
+
716
+ expect(testBuffer.vimMoveToLastLine).toHaveBeenCalled();
717
+ });
718
+
719
+ it('should handle gg (go to first line)', () => {
720
+ const testBuffer = createMockBuffer('line1\nline2\nline3', [2, 0]);
721
+ const { result } = renderVimHook(testBuffer);
722
+
723
+ // First 'g' sets pending state
724
+ act(() => {
725
+ result.current.handleInput({ sequence: 'g' });
726
+ });
727
+
728
+ // Second 'g' executes the command
729
+ act(() => {
730
+ result.current.handleInput({ sequence: 'g' });
731
+ });
732
+
733
+ expect(testBuffer.vimMoveToFirstLine).toHaveBeenCalled();
734
+ });
735
+
736
+ it('should handle count with movement commands', () => {
737
+ const testBuffer = createMockBuffer('hello world test', [0, 0]);
738
+ const { result } = renderVimHook(testBuffer);
739
+
740
+ act(() => {
741
+ result.current.handleInput({ sequence: '3' });
742
+ });
743
+
744
+ act(() => {
745
+ result.current.handleInput(TEST_SEQUENCES.WORD_FORWARD);
746
+ });
747
+
748
+ expect(testBuffer.vimMoveWordForward).toHaveBeenCalledWith(3);
749
+ });
750
+ });
751
+
752
+ describe('Vim word operations', () => {
753
+ describe('dw (delete word forward)', () => {
754
+ it('should delete from cursor to start of next word', () => {
755
+ const testBuffer = createMockBuffer('hello world test', [0, 0]);
756
+ const { result } = renderVimHook(testBuffer);
757
+
758
+ act(() => {
759
+ result.current.handleInput({ sequence: 'd' });
760
+ });
761
+ act(() => {
762
+ result.current.handleInput({ sequence: 'w' });
763
+ });
764
+
765
+ expect(testBuffer.vimDeleteWordForward).toHaveBeenCalledWith(1);
766
+ });
767
+
768
+ it('should actually delete the complete word including trailing space', () => {
769
+ // This test uses the real text-buffer reducer instead of mocks
770
+ const initialState = {
771
+ lines: ['hello world test'],
772
+ cursorRow: 0,
773
+ cursorCol: 0,
774
+ preferredCol: null,
775
+ undoStack: [],
776
+ redoStack: [],
777
+ clipboard: null,
778
+ selectionAnchor: null,
779
+ };
780
+
781
+ const result = textBufferReducer(initialState, {
782
+ type: 'vim_delete_word_forward',
783
+ payload: { count: 1 },
784
+ });
785
+
786
+ // Should delete "hello " (word + space), leaving "world test"
787
+ expect(result.lines).toEqual(['world test']);
788
+ expect(result.cursorRow).toBe(0);
789
+ expect(result.cursorCol).toBe(0);
790
+ });
791
+
792
+ it('should delete word from middle of word correctly', () => {
793
+ const initialState = {
794
+ lines: ['hello world test'],
795
+ cursorRow: 0,
796
+ cursorCol: 2, // cursor on 'l' in "hello"
797
+ preferredCol: null,
798
+ undoStack: [],
799
+ redoStack: [],
800
+ clipboard: null,
801
+ selectionAnchor: null,
802
+ };
803
+
804
+ const result = textBufferReducer(initialState, {
805
+ type: 'vim_delete_word_forward',
806
+ payload: { count: 1 },
807
+ });
808
+
809
+ // Should delete "llo " (rest of word + space), leaving "he world test"
810
+ expect(result.lines).toEqual(['heworld test']);
811
+ expect(result.cursorRow).toBe(0);
812
+ expect(result.cursorCol).toBe(2);
813
+ });
814
+
815
+ it('should handle dw at end of line', () => {
816
+ const initialState = {
817
+ lines: ['hello world'],
818
+ cursorRow: 0,
819
+ cursorCol: 6, // cursor on 'w' in "world"
820
+ preferredCol: null,
821
+ undoStack: [],
822
+ redoStack: [],
823
+ clipboard: null,
824
+ selectionAnchor: null,
825
+ };
826
+
827
+ const result = textBufferReducer(initialState, {
828
+ type: 'vim_delete_word_forward',
829
+ payload: { count: 1 },
830
+ });
831
+
832
+ // Should delete "world" (no trailing space at end), leaving "hello "
833
+ expect(result.lines).toEqual(['hello ']);
834
+ expect(result.cursorRow).toBe(0);
835
+ expect(result.cursorCol).toBe(6);
836
+ });
837
+
838
+ it('should delete multiple words with count', () => {
839
+ const testBuffer = createMockBuffer('one two three four', [0, 0]);
840
+ const { result } = renderVimHook(testBuffer);
841
+
842
+ act(() => {
843
+ result.current.handleInput({ sequence: '2' });
844
+ });
845
+ act(() => {
846
+ result.current.handleInput({ sequence: 'd' });
847
+ });
848
+ act(() => {
849
+ result.current.handleInput({ sequence: 'w' });
850
+ });
851
+
852
+ expect(testBuffer.vimDeleteWordForward).toHaveBeenCalledWith(2);
853
+ });
854
+
855
+ it('should record command for repeat with dot', () => {
856
+ const testBuffer = createMockBuffer('hello world test', [0, 0]);
857
+ const { result } = renderVimHook(testBuffer);
858
+
859
+ // Execute dw
860
+ act(() => {
861
+ result.current.handleInput({ sequence: 'd' });
862
+ });
863
+ act(() => {
864
+ result.current.handleInput({ sequence: 'w' });
865
+ });
866
+
867
+ vi.clearAllMocks();
868
+
869
+ // Execute dot repeat
870
+ act(() => {
871
+ result.current.handleInput({ sequence: '.' });
872
+ });
873
+
874
+ expect(testBuffer.vimDeleteWordForward).toHaveBeenCalledWith(1);
875
+ });
876
+ });
877
+
878
+ describe('de (delete word end)', () => {
879
+ it('should delete from cursor to end of current word', () => {
880
+ const testBuffer = createMockBuffer('hello world test', [0, 1]);
881
+ const { result } = renderVimHook(testBuffer);
882
+
883
+ act(() => {
884
+ result.current.handleInput({ sequence: 'd' });
885
+ });
886
+ act(() => {
887
+ result.current.handleInput({ sequence: 'e' });
888
+ });
889
+
890
+ expect(testBuffer.vimDeleteWordEnd).toHaveBeenCalledWith(1);
891
+ });
892
+
893
+ it('should handle count with de', () => {
894
+ const testBuffer = createMockBuffer('one two three four', [0, 0]);
895
+ const { result } = renderVimHook(testBuffer);
896
+
897
+ act(() => {
898
+ result.current.handleInput({ sequence: '3' });
899
+ });
900
+ act(() => {
901
+ result.current.handleInput({ sequence: 'd' });
902
+ });
903
+ act(() => {
904
+ result.current.handleInput({ sequence: 'e' });
905
+ });
906
+
907
+ expect(testBuffer.vimDeleteWordEnd).toHaveBeenCalledWith(3);
908
+ });
909
+ });
910
+
911
+ describe('cw (change word forward)', () => {
912
+ it('should change from cursor to start of next word and enter INSERT mode', () => {
913
+ const testBuffer = createMockBuffer('hello world test', [0, 0]);
914
+ const { result } = renderVimHook(testBuffer);
915
+
916
+ act(() => {
917
+ result.current.handleInput({ sequence: 'c' });
918
+ });
919
+ act(() => {
920
+ result.current.handleInput({ sequence: 'w' });
921
+ });
922
+
923
+ expect(testBuffer.vimChangeWordForward).toHaveBeenCalledWith(1);
924
+ expect(result.current.mode).toBe('INSERT');
925
+ expect(mockVimContext.setVimMode).toHaveBeenCalledWith('INSERT');
926
+ });
927
+
928
+ it('should handle count with cw', () => {
929
+ const testBuffer = createMockBuffer('one two three four', [0, 0]);
930
+ const { result } = renderVimHook(testBuffer);
931
+
932
+ act(() => {
933
+ result.current.handleInput({ sequence: '2' });
934
+ });
935
+ act(() => {
936
+ result.current.handleInput({ sequence: 'c' });
937
+ });
938
+ act(() => {
939
+ result.current.handleInput({ sequence: 'w' });
940
+ });
941
+
942
+ expect(testBuffer.vimChangeWordForward).toHaveBeenCalledWith(2);
943
+ expect(result.current.mode).toBe('INSERT');
944
+ });
945
+
946
+ it('should be repeatable with dot', () => {
947
+ const testBuffer = createMockBuffer('hello world test more', [0, 0]);
948
+ const { result } = renderVimHook(testBuffer);
949
+
950
+ // Execute cw
951
+ act(() => {
952
+ result.current.handleInput({ sequence: 'c' });
953
+ });
954
+ act(() => {
955
+ result.current.handleInput({ sequence: 'w' });
956
+ });
957
+
958
+ // Exit INSERT mode
959
+ exitInsertMode(result);
960
+
961
+ vi.clearAllMocks();
962
+ mockVimContext.setVimMode.mockClear();
963
+
964
+ // Execute dot repeat
965
+ act(() => {
966
+ result.current.handleInput({ sequence: '.' });
967
+ });
968
+
969
+ expect(testBuffer.vimChangeWordForward).toHaveBeenCalledWith(1);
970
+ expect(result.current.mode).toBe('INSERT');
971
+ });
972
+ });
973
+
974
+ describe('ce (change word end)', () => {
975
+ it('should change from cursor to end of word and enter INSERT mode', () => {
976
+ const testBuffer = createMockBuffer('hello world test', [0, 1]);
977
+ const { result } = renderVimHook(testBuffer);
978
+
979
+ act(() => {
980
+ result.current.handleInput({ sequence: 'c' });
981
+ });
982
+ act(() => {
983
+ result.current.handleInput({ sequence: 'e' });
984
+ });
985
+
986
+ expect(testBuffer.vimChangeWordEnd).toHaveBeenCalledWith(1);
987
+ expect(result.current.mode).toBe('INSERT');
988
+ });
989
+
990
+ it('should handle count with ce', () => {
991
+ const testBuffer = createMockBuffer('one two three four', [0, 0]);
992
+ const { result } = renderVimHook(testBuffer);
993
+
994
+ act(() => {
995
+ result.current.handleInput({ sequence: '2' });
996
+ });
997
+ act(() => {
998
+ result.current.handleInput({ sequence: 'c' });
999
+ });
1000
+ act(() => {
1001
+ result.current.handleInput({ sequence: 'e' });
1002
+ });
1003
+
1004
+ expect(testBuffer.vimChangeWordEnd).toHaveBeenCalledWith(2);
1005
+ expect(result.current.mode).toBe('INSERT');
1006
+ });
1007
+ });
1008
+
1009
+ describe('cc (change line)', () => {
1010
+ it('should change entire line and enter INSERT mode', () => {
1011
+ const testBuffer = createMockBuffer('hello world\nsecond line', [0, 5]);
1012
+ const { result } = renderVimHook(testBuffer);
1013
+
1014
+ act(() => {
1015
+ result.current.handleInput({ sequence: 'c' });
1016
+ });
1017
+ act(() => {
1018
+ result.current.handleInput({ sequence: 'c' });
1019
+ });
1020
+
1021
+ expect(testBuffer.vimChangeLine).toHaveBeenCalledWith(1);
1022
+ expect(result.current.mode).toBe('INSERT');
1023
+ });
1024
+
1025
+ it('should change multiple lines with count', () => {
1026
+ const testBuffer = createMockBuffer(
1027
+ 'line1\nline2\nline3\nline4',
1028
+ [1, 0],
1029
+ );
1030
+ const { result } = renderVimHook(testBuffer);
1031
+
1032
+ act(() => {
1033
+ result.current.handleInput({ sequence: '3' });
1034
+ });
1035
+ act(() => {
1036
+ result.current.handleInput({ sequence: 'c' });
1037
+ });
1038
+ act(() => {
1039
+ result.current.handleInput({ sequence: 'c' });
1040
+ });
1041
+
1042
+ expect(testBuffer.vimChangeLine).toHaveBeenCalledWith(3);
1043
+ expect(result.current.mode).toBe('INSERT');
1044
+ });
1045
+
1046
+ it('should be repeatable with dot', () => {
1047
+ const testBuffer = createMockBuffer('line1\nline2\nline3', [0, 0]);
1048
+ const { result } = renderVimHook(testBuffer);
1049
+
1050
+ // Execute cc
1051
+ act(() => {
1052
+ result.current.handleInput({ sequence: 'c' });
1053
+ });
1054
+ act(() => {
1055
+ result.current.handleInput({ sequence: 'c' });
1056
+ });
1057
+
1058
+ // Exit INSERT mode
1059
+ exitInsertMode(result);
1060
+
1061
+ vi.clearAllMocks();
1062
+ mockVimContext.setVimMode.mockClear();
1063
+
1064
+ // Execute dot repeat
1065
+ act(() => {
1066
+ result.current.handleInput({ sequence: '.' });
1067
+ });
1068
+
1069
+ expect(testBuffer.vimChangeLine).toHaveBeenCalledWith(1);
1070
+ expect(result.current.mode).toBe('INSERT');
1071
+ });
1072
+ });
1073
+
1074
+ describe('db (delete word backward)', () => {
1075
+ it('should delete from cursor to start of previous word', () => {
1076
+ const testBuffer = createMockBuffer('hello world test', [0, 11]);
1077
+ const { result } = renderVimHook(testBuffer);
1078
+
1079
+ act(() => {
1080
+ result.current.handleInput({ sequence: 'd' });
1081
+ });
1082
+ act(() => {
1083
+ result.current.handleInput({ sequence: 'b' });
1084
+ });
1085
+
1086
+ expect(testBuffer.vimDeleteWordBackward).toHaveBeenCalledWith(1);
1087
+ });
1088
+
1089
+ it('should handle count with db', () => {
1090
+ const testBuffer = createMockBuffer('one two three four', [0, 18]);
1091
+ const { result } = renderVimHook(testBuffer);
1092
+
1093
+ act(() => {
1094
+ result.current.handleInput({ sequence: '2' });
1095
+ });
1096
+ act(() => {
1097
+ result.current.handleInput({ sequence: 'd' });
1098
+ });
1099
+ act(() => {
1100
+ result.current.handleInput({ sequence: 'b' });
1101
+ });
1102
+
1103
+ expect(testBuffer.vimDeleteWordBackward).toHaveBeenCalledWith(2);
1104
+ });
1105
+ });
1106
+
1107
+ describe('cb (change word backward)', () => {
1108
+ it('should change from cursor to start of previous word and enter INSERT mode', () => {
1109
+ const testBuffer = createMockBuffer('hello world test', [0, 11]);
1110
+ const { result } = renderVimHook(testBuffer);
1111
+
1112
+ act(() => {
1113
+ result.current.handleInput({ sequence: 'c' });
1114
+ });
1115
+ act(() => {
1116
+ result.current.handleInput({ sequence: 'b' });
1117
+ });
1118
+
1119
+ expect(testBuffer.vimChangeWordBackward).toHaveBeenCalledWith(1);
1120
+ expect(result.current.mode).toBe('INSERT');
1121
+ });
1122
+
1123
+ it('should handle count with cb', () => {
1124
+ const testBuffer = createMockBuffer('one two three four', [0, 18]);
1125
+ const { result } = renderVimHook(testBuffer);
1126
+
1127
+ act(() => {
1128
+ result.current.handleInput({ sequence: '3' });
1129
+ });
1130
+ act(() => {
1131
+ result.current.handleInput({ sequence: 'c' });
1132
+ });
1133
+ act(() => {
1134
+ result.current.handleInput({ sequence: 'b' });
1135
+ });
1136
+
1137
+ expect(testBuffer.vimChangeWordBackward).toHaveBeenCalledWith(3);
1138
+ expect(result.current.mode).toBe('INSERT');
1139
+ });
1140
+ });
1141
+
1142
+ describe('Pending state handling', () => {
1143
+ it('should clear pending delete state after dw', () => {
1144
+ const testBuffer = createMockBuffer('hello world', [0, 0]);
1145
+ const { result } = renderVimHook(testBuffer);
1146
+
1147
+ // Press 'd' to enter pending delete state
1148
+ act(() => {
1149
+ result.current.handleInput({ sequence: 'd' });
1150
+ });
1151
+
1152
+ // Complete with 'w'
1153
+ act(() => {
1154
+ result.current.handleInput({ sequence: 'w' });
1155
+ });
1156
+
1157
+ // Next 'd' should start a new pending state, not continue the previous one
1158
+ act(() => {
1159
+ result.current.handleInput({ sequence: 'd' });
1160
+ });
1161
+
1162
+ // This should trigger dd (delete line), not an error
1163
+ act(() => {
1164
+ result.current.handleInput({ sequence: 'd' });
1165
+ });
1166
+
1167
+ expect(testBuffer.vimDeleteLine).toHaveBeenCalledWith(1);
1168
+ });
1169
+
1170
+ it('should clear pending change state after cw', () => {
1171
+ const testBuffer = createMockBuffer('hello world', [0, 0]);
1172
+ const { result } = renderVimHook(testBuffer);
1173
+
1174
+ // Execute cw
1175
+ act(() => {
1176
+ result.current.handleInput({ sequence: 'c' });
1177
+ });
1178
+ act(() => {
1179
+ result.current.handleInput({ sequence: 'w' });
1180
+ });
1181
+
1182
+ // Exit INSERT mode
1183
+ exitInsertMode(result);
1184
+
1185
+ // Next 'c' should start a new pending state
1186
+ act(() => {
1187
+ result.current.handleInput({ sequence: 'c' });
1188
+ });
1189
+ act(() => {
1190
+ result.current.handleInput({ sequence: 'c' });
1191
+ });
1192
+
1193
+ expect(testBuffer.vimChangeLine).toHaveBeenCalledWith(1);
1194
+ });
1195
+
1196
+ it('should clear pending state with escape', () => {
1197
+ const testBuffer = createMockBuffer('hello world', [0, 0]);
1198
+ const { result } = renderVimHook(testBuffer);
1199
+
1200
+ // Enter pending delete state
1201
+ act(() => {
1202
+ result.current.handleInput({ sequence: 'd' });
1203
+ });
1204
+
1205
+ // Press escape to clear pending state
1206
+ act(() => {
1207
+ result.current.handleInput({ name: 'escape' });
1208
+ });
1209
+
1210
+ // Now 'w' should just move cursor, not delete
1211
+ act(() => {
1212
+ result.current.handleInput({ sequence: 'w' });
1213
+ });
1214
+
1215
+ expect(testBuffer.vimDeleteWordForward).not.toHaveBeenCalled();
1216
+ // w should move to next word after clearing pending state
1217
+ expect(testBuffer.vimMoveWordForward).toHaveBeenCalledWith(1);
1218
+ });
1219
+ });
1220
+
1221
+ describe('NORMAL mode escape behavior', () => {
1222
+ it('should pass escape through when no pending operator is active', () => {
1223
+ mockVimContext.vimMode = 'NORMAL';
1224
+ const { result } = renderVimHook();
1225
+
1226
+ const handled = result.current.handleInput({ name: 'escape' });
1227
+
1228
+ expect(handled).toBe(false);
1229
+ });
1230
+
1231
+ it('should handle escape and clear pending operator', () => {
1232
+ mockVimContext.vimMode = 'NORMAL';
1233
+ const { result } = renderVimHook();
1234
+
1235
+ act(() => {
1236
+ result.current.handleInput({ sequence: 'd' });
1237
+ });
1238
+
1239
+ let handled: boolean | undefined;
1240
+ act(() => {
1241
+ handled = result.current.handleInput({ name: 'escape' });
1242
+ });
1243
+
1244
+ expect(handled).toBe(true);
1245
+ });
1246
+ });
1247
+ });
1248
+
1249
+ describe('Shell command pass-through', () => {
1250
+ it('should pass through ctrl+r in INSERT mode', () => {
1251
+ mockVimContext.vimMode = 'INSERT';
1252
+ const { result } = renderVimHook();
1253
+
1254
+ const handled = result.current.handleInput({ name: 'r', ctrl: true });
1255
+
1256
+ expect(handled).toBe(false);
1257
+ });
1258
+
1259
+ it('should pass through ! in INSERT mode when buffer is empty', () => {
1260
+ mockVimContext.vimMode = 'INSERT';
1261
+ const emptyBuffer = createMockBuffer('');
1262
+ const { result } = renderVimHook(emptyBuffer);
1263
+
1264
+ const handled = result.current.handleInput({ sequence: '!' });
1265
+
1266
+ expect(handled).toBe(false);
1267
+ });
1268
+
1269
+ it('should handle ! as input in INSERT mode when buffer is not empty', () => {
1270
+ mockVimContext.vimMode = 'INSERT';
1271
+ const nonEmptyBuffer = createMockBuffer('not empty');
1272
+ const { result } = renderVimHook(nonEmptyBuffer);
1273
+ const key = { sequence: '!', name: '!' };
1274
+
1275
+ act(() => {
1276
+ result.current.handleInput(key);
1277
+ });
1278
+
1279
+ expect(nonEmptyBuffer.handleInput).toHaveBeenCalledWith(
1280
+ expect.objectContaining(key),
1281
+ );
1282
+ });
1283
+ });
1284
+
1285
+ // Line operations (dd, cc) are tested in text-buffer.test.ts
1286
+
1287
+ describe('Reducer-based integration tests', () => {
1288
+ describe('de (delete word end)', () => {
1289
+ it('should delete from cursor to end of current word', () => {
1290
+ const initialState = {
1291
+ lines: ['hello world test'],
1292
+ cursorRow: 0,
1293
+ cursorCol: 1, // cursor on 'e' in "hello"
1294
+ preferredCol: null,
1295
+ undoStack: [],
1296
+ redoStack: [],
1297
+ clipboard: null,
1298
+ selectionAnchor: null,
1299
+ };
1300
+
1301
+ const result = textBufferReducer(initialState, {
1302
+ type: 'vim_delete_word_end',
1303
+ payload: { count: 1 },
1304
+ });
1305
+
1306
+ // Should delete "ello" (from cursor to end of word), leaving "h world test"
1307
+ expect(result.lines).toEqual(['h world test']);
1308
+ expect(result.cursorRow).toBe(0);
1309
+ expect(result.cursorCol).toBe(1);
1310
+ });
1311
+
1312
+ it('should delete multiple word ends with count', () => {
1313
+ const initialState = {
1314
+ lines: ['hello world test more'],
1315
+ cursorRow: 0,
1316
+ cursorCol: 1, // cursor on 'e' in "hello"
1317
+ preferredCol: null,
1318
+ undoStack: [],
1319
+ redoStack: [],
1320
+ clipboard: null,
1321
+ selectionAnchor: null,
1322
+ };
1323
+
1324
+ const result = textBufferReducer(initialState, {
1325
+ type: 'vim_delete_word_end',
1326
+ payload: { count: 2 },
1327
+ });
1328
+
1329
+ // Should delete "ello world" (to end of second word), leaving "h test more"
1330
+ expect(result.lines).toEqual(['h test more']);
1331
+ expect(result.cursorRow).toBe(0);
1332
+ expect(result.cursorCol).toBe(1);
1333
+ });
1334
+ });
1335
+
1336
+ describe('db (delete word backward)', () => {
1337
+ it('should delete from cursor to start of previous word', () => {
1338
+ const initialState = {
1339
+ lines: ['hello world test'],
1340
+ cursorRow: 0,
1341
+ cursorCol: 11, // cursor on 't' in "test"
1342
+ preferredCol: null,
1343
+ undoStack: [],
1344
+ redoStack: [],
1345
+ clipboard: null,
1346
+ selectionAnchor: null,
1347
+ };
1348
+
1349
+ const result = textBufferReducer(initialState, {
1350
+ type: 'vim_delete_word_backward',
1351
+ payload: { count: 1 },
1352
+ });
1353
+
1354
+ // Should delete "world" (previous word only), leaving "hello test"
1355
+ expect(result.lines).toEqual(['hello test']);
1356
+ expect(result.cursorRow).toBe(0);
1357
+ expect(result.cursorCol).toBe(6);
1358
+ });
1359
+
1360
+ it('should delete multiple words backward with count', () => {
1361
+ const initialState = {
1362
+ lines: ['hello world test more'],
1363
+ cursorRow: 0,
1364
+ cursorCol: 17, // cursor on 'm' in "more"
1365
+ preferredCol: null,
1366
+ undoStack: [],
1367
+ redoStack: [],
1368
+ clipboard: null,
1369
+ selectionAnchor: null,
1370
+ };
1371
+
1372
+ const result = textBufferReducer(initialState, {
1373
+ type: 'vim_delete_word_backward',
1374
+ payload: { count: 2 },
1375
+ });
1376
+
1377
+ // Should delete "world test " (two words backward), leaving "hello more"
1378
+ expect(result.lines).toEqual(['hello more']);
1379
+ expect(result.cursorRow).toBe(0);
1380
+ expect(result.cursorCol).toBe(6);
1381
+ });
1382
+ });
1383
+
1384
+ describe('cw (change word forward)', () => {
1385
+ it('should delete from cursor to start of next word', () => {
1386
+ const initialState = {
1387
+ lines: ['hello world test'],
1388
+ cursorRow: 0,
1389
+ cursorCol: 0, // cursor on 'h' in "hello"
1390
+ preferredCol: null,
1391
+ undoStack: [],
1392
+ redoStack: [],
1393
+ clipboard: null,
1394
+ selectionAnchor: null,
1395
+ };
1396
+
1397
+ const result = textBufferReducer(initialState, {
1398
+ type: 'vim_change_word_forward',
1399
+ payload: { count: 1 },
1400
+ });
1401
+
1402
+ // Should delete "hello " (word + space), leaving "world test"
1403
+ expect(result.lines).toEqual(['world test']);
1404
+ expect(result.cursorRow).toBe(0);
1405
+ expect(result.cursorCol).toBe(0);
1406
+ });
1407
+
1408
+ it('should change multiple words with count', () => {
1409
+ const initialState = {
1410
+ lines: ['hello world test more'],
1411
+ cursorRow: 0,
1412
+ cursorCol: 0,
1413
+ preferredCol: null,
1414
+ undoStack: [],
1415
+ redoStack: [],
1416
+ clipboard: null,
1417
+ selectionAnchor: null,
1418
+ };
1419
+
1420
+ const result = textBufferReducer(initialState, {
1421
+ type: 'vim_change_word_forward',
1422
+ payload: { count: 2 },
1423
+ });
1424
+
1425
+ // Should delete "hello world " (two words), leaving "test more"
1426
+ expect(result.lines).toEqual(['test more']);
1427
+ expect(result.cursorRow).toBe(0);
1428
+ expect(result.cursorCol).toBe(0);
1429
+ });
1430
+ });
1431
+
1432
+ describe('ce (change word end)', () => {
1433
+ it('should change from cursor to end of current word', () => {
1434
+ const initialState = {
1435
+ lines: ['hello world test'],
1436
+ cursorRow: 0,
1437
+ cursorCol: 1, // cursor on 'e' in "hello"
1438
+ preferredCol: null,
1439
+ undoStack: [],
1440
+ redoStack: [],
1441
+ clipboard: null,
1442
+ selectionAnchor: null,
1443
+ };
1444
+
1445
+ const result = textBufferReducer(initialState, {
1446
+ type: 'vim_change_word_end',
1447
+ payload: { count: 1 },
1448
+ });
1449
+
1450
+ // Should delete "ello" (from cursor to end of word), leaving "h world test"
1451
+ expect(result.lines).toEqual(['h world test']);
1452
+ expect(result.cursorRow).toBe(0);
1453
+ expect(result.cursorCol).toBe(1);
1454
+ });
1455
+
1456
+ it('should change multiple word ends with count', () => {
1457
+ const initialState = {
1458
+ lines: ['hello world test'],
1459
+ cursorRow: 0,
1460
+ cursorCol: 1, // cursor on 'e' in "hello"
1461
+ preferredCol: null,
1462
+ undoStack: [],
1463
+ redoStack: [],
1464
+ clipboard: null,
1465
+ selectionAnchor: null,
1466
+ };
1467
+
1468
+ const result = textBufferReducer(initialState, {
1469
+ type: 'vim_change_word_end',
1470
+ payload: { count: 2 },
1471
+ });
1472
+
1473
+ // Should delete "ello world" (to end of second word), leaving "h test"
1474
+ expect(result.lines).toEqual(['h test']);
1475
+ expect(result.cursorRow).toBe(0);
1476
+ expect(result.cursorCol).toBe(1);
1477
+ });
1478
+ });
1479
+
1480
+ describe('cb (change word backward)', () => {
1481
+ it('should change from cursor to start of previous word', () => {
1482
+ const initialState = {
1483
+ lines: ['hello world test'],
1484
+ cursorRow: 0,
1485
+ cursorCol: 11, // cursor on 't' in "test"
1486
+ preferredCol: null,
1487
+ undoStack: [],
1488
+ redoStack: [],
1489
+ clipboard: null,
1490
+ selectionAnchor: null,
1491
+ };
1492
+
1493
+ const result = textBufferReducer(initialState, {
1494
+ type: 'vim_change_word_backward',
1495
+ payload: { count: 1 },
1496
+ });
1497
+
1498
+ // Should delete "world" (previous word only), leaving "hello test"
1499
+ expect(result.lines).toEqual(['hello test']);
1500
+ expect(result.cursorRow).toBe(0);
1501
+ expect(result.cursorCol).toBe(6);
1502
+ });
1503
+ });
1504
+
1505
+ describe('cc (change line)', () => {
1506
+ it('should clear the line and place cursor at the start', () => {
1507
+ const initialState = {
1508
+ lines: [' hello world'],
1509
+ cursorRow: 0,
1510
+ cursorCol: 5, // cursor on 'o'
1511
+ preferredCol: null,
1512
+ undoStack: [],
1513
+ redoStack: [],
1514
+ clipboard: null,
1515
+ selectionAnchor: null,
1516
+ };
1517
+
1518
+ const result = textBufferReducer(initialState, {
1519
+ type: 'vim_change_line',
1520
+ payload: { count: 1 },
1521
+ });
1522
+
1523
+ expect(result.lines).toEqual(['']);
1524
+ expect(result.cursorRow).toBe(0);
1525
+ expect(result.cursorCol).toBe(0);
1526
+ });
1527
+ });
1528
+
1529
+ describe('dd (delete line)', () => {
1530
+ it('should delete the current line', () => {
1531
+ const initialState = {
1532
+ lines: ['line1', 'line2', 'line3'],
1533
+ cursorRow: 1,
1534
+ cursorCol: 2,
1535
+ preferredCol: null,
1536
+ undoStack: [],
1537
+ redoStack: [],
1538
+ clipboard: null,
1539
+ selectionAnchor: null,
1540
+ };
1541
+
1542
+ const result = textBufferReducer(initialState, {
1543
+ type: 'vim_delete_line',
1544
+ payload: { count: 1 },
1545
+ });
1546
+
1547
+ expect(result.lines).toEqual(['line1', 'line3']);
1548
+ expect(result.cursorRow).toBe(1);
1549
+ expect(result.cursorCol).toBe(0);
1550
+ });
1551
+
1552
+ it('should delete multiple lines with count', () => {
1553
+ const initialState = {
1554
+ lines: ['line1', 'line2', 'line3', 'line4'],
1555
+ cursorRow: 1,
1556
+ cursorCol: 2,
1557
+ preferredCol: null,
1558
+ undoStack: [],
1559
+ redoStack: [],
1560
+ clipboard: null,
1561
+ selectionAnchor: null,
1562
+ };
1563
+
1564
+ const result = textBufferReducer(initialState, {
1565
+ type: 'vim_delete_line',
1566
+ payload: { count: 2 },
1567
+ });
1568
+
1569
+ // Should delete lines 1 and 2
1570
+ expect(result.lines).toEqual(['line1', 'line4']);
1571
+ expect(result.cursorRow).toBe(1);
1572
+ expect(result.cursorCol).toBe(0);
1573
+ });
1574
+
1575
+ it('should handle deleting last line', () => {
1576
+ const initialState = {
1577
+ lines: ['only line'],
1578
+ cursorRow: 0,
1579
+ cursorCol: 3,
1580
+ preferredCol: null,
1581
+ undoStack: [],
1582
+ redoStack: [],
1583
+ clipboard: null,
1584
+ selectionAnchor: null,
1585
+ };
1586
+
1587
+ const result = textBufferReducer(initialState, {
1588
+ type: 'vim_delete_line',
1589
+ payload: { count: 1 },
1590
+ });
1591
+
1592
+ // Should leave an empty line when deleting the only line
1593
+ expect(result.lines).toEqual(['']);
1594
+ expect(result.cursorRow).toBe(0);
1595
+ expect(result.cursorCol).toBe(0);
1596
+ });
1597
+ });
1598
+
1599
+ describe('D (delete to end of line)', () => {
1600
+ it('should delete from cursor to end of line', () => {
1601
+ const initialState = {
1602
+ lines: ['hello world test'],
1603
+ cursorRow: 0,
1604
+ cursorCol: 6, // cursor on 'w' in "world"
1605
+ preferredCol: null,
1606
+ undoStack: [],
1607
+ redoStack: [],
1608
+ clipboard: null,
1609
+ selectionAnchor: null,
1610
+ };
1611
+
1612
+ const result = textBufferReducer(initialState, {
1613
+ type: 'vim_delete_to_end_of_line',
1614
+ });
1615
+
1616
+ // Should delete "world test", leaving "hello "
1617
+ expect(result.lines).toEqual(['hello ']);
1618
+ expect(result.cursorRow).toBe(0);
1619
+ expect(result.cursorCol).toBe(6);
1620
+ });
1621
+
1622
+ it('should handle D at end of line', () => {
1623
+ const initialState = {
1624
+ lines: ['hello world'],
1625
+ cursorRow: 0,
1626
+ cursorCol: 11, // cursor at end
1627
+ preferredCol: null,
1628
+ undoStack: [],
1629
+ redoStack: [],
1630
+ clipboard: null,
1631
+ selectionAnchor: null,
1632
+ };
1633
+
1634
+ const result = textBufferReducer(initialState, {
1635
+ type: 'vim_delete_to_end_of_line',
1636
+ });
1637
+
1638
+ // Should not change anything when at end of line
1639
+ expect(result.lines).toEqual(['hello world']);
1640
+ expect(result.cursorRow).toBe(0);
1641
+ expect(result.cursorCol).toBe(11);
1642
+ });
1643
+ });
1644
+
1645
+ describe('C (change to end of line)', () => {
1646
+ it('should change from cursor to end of line', () => {
1647
+ const initialState = {
1648
+ lines: ['hello world test'],
1649
+ cursorRow: 0,
1650
+ cursorCol: 6, // cursor on 'w' in "world"
1651
+ preferredCol: null,
1652
+ undoStack: [],
1653
+ redoStack: [],
1654
+ clipboard: null,
1655
+ selectionAnchor: null,
1656
+ };
1657
+
1658
+ const result = textBufferReducer(initialState, {
1659
+ type: 'vim_change_to_end_of_line',
1660
+ });
1661
+
1662
+ // Should delete "world test", leaving "hello "
1663
+ expect(result.lines).toEqual(['hello ']);
1664
+ expect(result.cursorRow).toBe(0);
1665
+ expect(result.cursorCol).toBe(6);
1666
+ });
1667
+
1668
+ it('should handle C at beginning of line', () => {
1669
+ const initialState = {
1670
+ lines: ['hello world'],
1671
+ cursorRow: 0,
1672
+ cursorCol: 0,
1673
+ preferredCol: null,
1674
+ undoStack: [],
1675
+ redoStack: [],
1676
+ clipboard: null,
1677
+ selectionAnchor: null,
1678
+ };
1679
+
1680
+ const result = textBufferReducer(initialState, {
1681
+ type: 'vim_change_to_end_of_line',
1682
+ });
1683
+
1684
+ // Should delete entire line content
1685
+ expect(result.lines).toEqual(['']);
1686
+ expect(result.cursorRow).toBe(0);
1687
+ expect(result.cursorCol).toBe(0);
1688
+ });
1689
+ });
1690
+ });
1691
+ });
projects/ui/qwen-code/packages/cli/src/ui/hooks/vim.ts ADDED
@@ -0,0 +1,784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { useCallback, useReducer, useEffect } from 'react';
8
+ import type { Key } from './useKeypress.js';
9
+ import type { TextBuffer } from '../components/shared/text-buffer.js';
10
+ import { useVimMode } from '../contexts/VimModeContext.js';
11
+
12
+ export type VimMode = 'NORMAL' | 'INSERT';
13
+
14
+ // Constants
15
+ const DIGIT_MULTIPLIER = 10;
16
+ const DEFAULT_COUNT = 1;
17
+ const DIGIT_1_TO_9 = /^[1-9]$/;
18
+
19
+ // Command types
20
+ const CMD_TYPES = {
21
+ DELETE_WORD_FORWARD: 'dw',
22
+ DELETE_WORD_BACKWARD: 'db',
23
+ DELETE_WORD_END: 'de',
24
+ CHANGE_WORD_FORWARD: 'cw',
25
+ CHANGE_WORD_BACKWARD: 'cb',
26
+ CHANGE_WORD_END: 'ce',
27
+ DELETE_CHAR: 'x',
28
+ DELETE_LINE: 'dd',
29
+ CHANGE_LINE: 'cc',
30
+ DELETE_TO_EOL: 'D',
31
+ CHANGE_TO_EOL: 'C',
32
+ CHANGE_MOVEMENT: {
33
+ LEFT: 'ch',
34
+ DOWN: 'cj',
35
+ UP: 'ck',
36
+ RIGHT: 'cl',
37
+ },
38
+ } as const;
39
+
40
+ // Helper function to clear pending state
41
+ const createClearPendingState = () => ({
42
+ count: 0,
43
+ pendingOperator: null as 'g' | 'd' | 'c' | null,
44
+ });
45
+
46
+ // State and action types for useReducer
47
+ type VimState = {
48
+ mode: VimMode;
49
+ count: number;
50
+ pendingOperator: 'g' | 'd' | 'c' | null;
51
+ lastCommand: { type: string; count: number } | null;
52
+ };
53
+
54
+ type VimAction =
55
+ | { type: 'SET_MODE'; mode: VimMode }
56
+ | { type: 'SET_COUNT'; count: number }
57
+ | { type: 'INCREMENT_COUNT'; digit: number }
58
+ | { type: 'CLEAR_COUNT' }
59
+ | { type: 'SET_PENDING_OPERATOR'; operator: 'g' | 'd' | 'c' | null }
60
+ | {
61
+ type: 'SET_LAST_COMMAND';
62
+ command: { type: string; count: number } | null;
63
+ }
64
+ | { type: 'CLEAR_PENDING_STATES' }
65
+ | { type: 'ESCAPE_TO_NORMAL' };
66
+
67
+ const initialVimState: VimState = {
68
+ mode: 'NORMAL',
69
+ count: 0,
70
+ pendingOperator: null,
71
+ lastCommand: null,
72
+ };
73
+
74
+ // Reducer function
75
+ const vimReducer = (state: VimState, action: VimAction): VimState => {
76
+ switch (action.type) {
77
+ case 'SET_MODE':
78
+ return { ...state, mode: action.mode };
79
+
80
+ case 'SET_COUNT':
81
+ return { ...state, count: action.count };
82
+
83
+ case 'INCREMENT_COUNT':
84
+ return { ...state, count: state.count * DIGIT_MULTIPLIER + action.digit };
85
+
86
+ case 'CLEAR_COUNT':
87
+ return { ...state, count: 0 };
88
+
89
+ case 'SET_PENDING_OPERATOR':
90
+ return { ...state, pendingOperator: action.operator };
91
+
92
+ case 'SET_LAST_COMMAND':
93
+ return { ...state, lastCommand: action.command };
94
+
95
+ case 'CLEAR_PENDING_STATES':
96
+ return {
97
+ ...state,
98
+ ...createClearPendingState(),
99
+ };
100
+
101
+ case 'ESCAPE_TO_NORMAL':
102
+ // Handle escape - clear all pending states (mode is updated via context)
103
+ return {
104
+ ...state,
105
+ ...createClearPendingState(),
106
+ };
107
+
108
+ default:
109
+ return state;
110
+ }
111
+ };
112
+
113
+ /**
114
+ * React hook that provides vim-style editing functionality for text input.
115
+ *
116
+ * Features:
117
+ * - Modal editing (INSERT/NORMAL modes)
118
+ * - Navigation: h,j,k,l,w,b,e,0,$,^,gg,G with count prefixes
119
+ * - Editing: x,a,i,o,O,A,I,d,c,D,C with count prefixes
120
+ * - Complex operations: dd,cc,dw,cw,db,cb,de,ce
121
+ * - Command repetition (.)
122
+ * - Settings persistence
123
+ *
124
+ * @param buffer - TextBuffer instance for text manipulation
125
+ * @param onSubmit - Optional callback for command submission
126
+ * @returns Object with vim state and input handler
127
+ */
128
+ export function useVim(buffer: TextBuffer, onSubmit?: (value: string) => void) {
129
+ const { vimEnabled, vimMode, setVimMode } = useVimMode();
130
+ const [state, dispatch] = useReducer(vimReducer, initialVimState);
131
+
132
+ // Sync vim mode from context to local state
133
+ useEffect(() => {
134
+ dispatch({ type: 'SET_MODE', mode: vimMode });
135
+ }, [vimMode]);
136
+
137
+ // Helper to update mode in both reducer and context
138
+ const updateMode = useCallback(
139
+ (mode: VimMode) => {
140
+ setVimMode(mode);
141
+ dispatch({ type: 'SET_MODE', mode });
142
+ },
143
+ [setVimMode],
144
+ );
145
+
146
+ // Helper functions using the reducer state
147
+ const getCurrentCount = useCallback(
148
+ () => state.count || DEFAULT_COUNT,
149
+ [state.count],
150
+ );
151
+
152
+ /** Executes common commands to eliminate duplication in dot (.) repeat command */
153
+ const executeCommand = useCallback(
154
+ (cmdType: string, count: number) => {
155
+ switch (cmdType) {
156
+ case CMD_TYPES.DELETE_WORD_FORWARD: {
157
+ buffer.vimDeleteWordForward(count);
158
+ break;
159
+ }
160
+
161
+ case CMD_TYPES.DELETE_WORD_BACKWARD: {
162
+ buffer.vimDeleteWordBackward(count);
163
+ break;
164
+ }
165
+
166
+ case CMD_TYPES.DELETE_WORD_END: {
167
+ buffer.vimDeleteWordEnd(count);
168
+ break;
169
+ }
170
+
171
+ case CMD_TYPES.CHANGE_WORD_FORWARD: {
172
+ buffer.vimChangeWordForward(count);
173
+ updateMode('INSERT');
174
+ break;
175
+ }
176
+
177
+ case CMD_TYPES.CHANGE_WORD_BACKWARD: {
178
+ buffer.vimChangeWordBackward(count);
179
+ updateMode('INSERT');
180
+ break;
181
+ }
182
+
183
+ case CMD_TYPES.CHANGE_WORD_END: {
184
+ buffer.vimChangeWordEnd(count);
185
+ updateMode('INSERT');
186
+ break;
187
+ }
188
+
189
+ case CMD_TYPES.DELETE_CHAR: {
190
+ buffer.vimDeleteChar(count);
191
+ break;
192
+ }
193
+
194
+ case CMD_TYPES.DELETE_LINE: {
195
+ buffer.vimDeleteLine(count);
196
+ break;
197
+ }
198
+
199
+ case CMD_TYPES.CHANGE_LINE: {
200
+ buffer.vimChangeLine(count);
201
+ updateMode('INSERT');
202
+ break;
203
+ }
204
+
205
+ case CMD_TYPES.CHANGE_MOVEMENT.LEFT:
206
+ case CMD_TYPES.CHANGE_MOVEMENT.DOWN:
207
+ case CMD_TYPES.CHANGE_MOVEMENT.UP:
208
+ case CMD_TYPES.CHANGE_MOVEMENT.RIGHT: {
209
+ const movementMap: Record<string, 'h' | 'j' | 'k' | 'l'> = {
210
+ [CMD_TYPES.CHANGE_MOVEMENT.LEFT]: 'h',
211
+ [CMD_TYPES.CHANGE_MOVEMENT.DOWN]: 'j',
212
+ [CMD_TYPES.CHANGE_MOVEMENT.UP]: 'k',
213
+ [CMD_TYPES.CHANGE_MOVEMENT.RIGHT]: 'l',
214
+ };
215
+ const movementType = movementMap[cmdType];
216
+ if (movementType) {
217
+ buffer.vimChangeMovement(movementType, count);
218
+ updateMode('INSERT');
219
+ }
220
+ break;
221
+ }
222
+
223
+ case CMD_TYPES.DELETE_TO_EOL: {
224
+ buffer.vimDeleteToEndOfLine();
225
+ break;
226
+ }
227
+
228
+ case CMD_TYPES.CHANGE_TO_EOL: {
229
+ buffer.vimChangeToEndOfLine();
230
+ updateMode('INSERT');
231
+ break;
232
+ }
233
+
234
+ default:
235
+ return false;
236
+ }
237
+ return true;
238
+ },
239
+ [buffer, updateMode],
240
+ );
241
+
242
+ /**
243
+ * Handles key input in INSERT mode
244
+ * @param normalizedKey - The normalized key input
245
+ * @returns boolean indicating if the key was handled
246
+ */
247
+ const handleInsertModeInput = useCallback(
248
+ (normalizedKey: Key): boolean => {
249
+ // Handle escape key immediately - switch to NORMAL mode on any escape
250
+ if (normalizedKey.name === 'escape') {
251
+ // Vim behavior: move cursor left when exiting insert mode (unless at beginning of line)
252
+ buffer.vimEscapeInsertMode();
253
+ dispatch({ type: 'ESCAPE_TO_NORMAL' });
254
+ updateMode('NORMAL');
255
+ return true;
256
+ }
257
+
258
+ // In INSERT mode, let InputPrompt handle completion keys and special commands
259
+ if (
260
+ normalizedKey.name === 'tab' ||
261
+ (normalizedKey.name === 'return' && !normalizedKey.ctrl) ||
262
+ normalizedKey.name === 'up' ||
263
+ normalizedKey.name === 'down' ||
264
+ (normalizedKey.ctrl && normalizedKey.name === 'r')
265
+ ) {
266
+ return false; // Let InputPrompt handle completion
267
+ }
268
+
269
+ // Let InputPrompt handle Ctrl+V for clipboard image pasting
270
+ if (normalizedKey.ctrl && normalizedKey.name === 'v') {
271
+ return false; // Let InputPrompt handle clipboard functionality
272
+ }
273
+
274
+ // Let InputPrompt handle shell commands
275
+ if (normalizedKey.sequence === '!' && buffer.text.length === 0) {
276
+ return false;
277
+ }
278
+
279
+ // Special handling for Enter key to allow command submission (lower priority than completion)
280
+ if (
281
+ normalizedKey.name === 'return' &&
282
+ !normalizedKey.ctrl &&
283
+ !normalizedKey.meta
284
+ ) {
285
+ if (buffer.text.trim() && onSubmit) {
286
+ // Handle command submission directly
287
+ const submittedValue = buffer.text;
288
+ buffer.setText('');
289
+ onSubmit(submittedValue);
290
+ return true;
291
+ }
292
+ return true; // Handled by vim (even if no onSubmit callback)
293
+ }
294
+
295
+ // useKeypress already provides the correct format for TextBuffer
296
+ buffer.handleInput(normalizedKey);
297
+ return true; // Handled by vim
298
+ },
299
+ [buffer, dispatch, updateMode, onSubmit],
300
+ );
301
+
302
+ /**
303
+ * Normalizes key input to ensure all required properties are present
304
+ * @param key - Raw key input
305
+ * @returns Normalized key with all properties
306
+ */
307
+ const normalizeKey = useCallback(
308
+ (key: Key): Key => ({
309
+ name: key.name || '',
310
+ sequence: key.sequence || '',
311
+ ctrl: key.ctrl || false,
312
+ meta: key.meta || false,
313
+ shift: key.shift || false,
314
+ paste: key.paste || false,
315
+ }),
316
+ [],
317
+ );
318
+
319
+ /**
320
+ * Handles change movement commands (ch, cj, ck, cl)
321
+ * @param movement - The movement direction
322
+ * @returns boolean indicating if command was handled
323
+ */
324
+ const handleChangeMovement = useCallback(
325
+ (movement: 'h' | 'j' | 'k' | 'l'): boolean => {
326
+ const count = getCurrentCount();
327
+ dispatch({ type: 'CLEAR_COUNT' });
328
+ buffer.vimChangeMovement(movement, count);
329
+ updateMode('INSERT');
330
+
331
+ const cmdTypeMap = {
332
+ h: CMD_TYPES.CHANGE_MOVEMENT.LEFT,
333
+ j: CMD_TYPES.CHANGE_MOVEMENT.DOWN,
334
+ k: CMD_TYPES.CHANGE_MOVEMENT.UP,
335
+ l: CMD_TYPES.CHANGE_MOVEMENT.RIGHT,
336
+ };
337
+
338
+ dispatch({
339
+ type: 'SET_LAST_COMMAND',
340
+ command: { type: cmdTypeMap[movement], count },
341
+ });
342
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: null });
343
+ return true;
344
+ },
345
+ [getCurrentCount, dispatch, buffer, updateMode],
346
+ );
347
+
348
+ /**
349
+ * Handles operator-motion commands (dw/cw, db/cb, de/ce)
350
+ * @param operator - The operator type ('d' for delete, 'c' for change)
351
+ * @param motion - The motion type ('w', 'b', 'e')
352
+ * @returns boolean indicating if command was handled
353
+ */
354
+ const handleOperatorMotion = useCallback(
355
+ (operator: 'd' | 'c', motion: 'w' | 'b' | 'e'): boolean => {
356
+ const count = getCurrentCount();
357
+
358
+ const commandMap = {
359
+ d: {
360
+ w: CMD_TYPES.DELETE_WORD_FORWARD,
361
+ b: CMD_TYPES.DELETE_WORD_BACKWARD,
362
+ e: CMD_TYPES.DELETE_WORD_END,
363
+ },
364
+ c: {
365
+ w: CMD_TYPES.CHANGE_WORD_FORWARD,
366
+ b: CMD_TYPES.CHANGE_WORD_BACKWARD,
367
+ e: CMD_TYPES.CHANGE_WORD_END,
368
+ },
369
+ };
370
+
371
+ const cmdType = commandMap[operator][motion];
372
+ executeCommand(cmdType, count);
373
+
374
+ dispatch({
375
+ type: 'SET_LAST_COMMAND',
376
+ command: { type: cmdType, count },
377
+ });
378
+ dispatch({ type: 'CLEAR_COUNT' });
379
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: null });
380
+
381
+ return true;
382
+ },
383
+ [getCurrentCount, executeCommand, dispatch],
384
+ );
385
+
386
+ const handleInput = useCallback(
387
+ (key: Key): boolean => {
388
+ if (!vimEnabled) {
389
+ return false; // Let InputPrompt handle it
390
+ }
391
+
392
+ let normalizedKey: Key;
393
+ try {
394
+ normalizedKey = normalizeKey(key);
395
+ } catch (error) {
396
+ // Handle malformed key inputs gracefully
397
+ console.warn('Malformed key input in vim mode:', key, error);
398
+ return false;
399
+ }
400
+
401
+ // Handle INSERT mode
402
+ if (state.mode === 'INSERT') {
403
+ return handleInsertModeInput(normalizedKey);
404
+ }
405
+
406
+ // Handle NORMAL mode
407
+ if (state.mode === 'NORMAL') {
408
+ // If in NORMAL mode, allow escape to pass through to other handlers
409
+ // if there's no pending operation.
410
+ if (normalizedKey.name === 'escape') {
411
+ if (state.pendingOperator) {
412
+ dispatch({ type: 'CLEAR_PENDING_STATES' });
413
+ return true; // Handled by vim
414
+ }
415
+ return false; // Pass through to other handlers
416
+ }
417
+
418
+ // Handle count input (numbers 1-9, and 0 if count > 0)
419
+ if (
420
+ DIGIT_1_TO_9.test(normalizedKey.sequence) ||
421
+ (normalizedKey.sequence === '0' && state.count > 0)
422
+ ) {
423
+ dispatch({
424
+ type: 'INCREMENT_COUNT',
425
+ digit: parseInt(normalizedKey.sequence, 10),
426
+ });
427
+ return true; // Handled by vim
428
+ }
429
+
430
+ const repeatCount = getCurrentCount();
431
+
432
+ switch (normalizedKey.sequence) {
433
+ case 'h': {
434
+ // Check if this is part of a change command (ch)
435
+ if (state.pendingOperator === 'c') {
436
+ return handleChangeMovement('h');
437
+ }
438
+
439
+ // Normal left movement
440
+ buffer.vimMoveLeft(repeatCount);
441
+ dispatch({ type: 'CLEAR_COUNT' });
442
+ return true;
443
+ }
444
+
445
+ case 'j': {
446
+ // Check if this is part of a change command (cj)
447
+ if (state.pendingOperator === 'c') {
448
+ return handleChangeMovement('j');
449
+ }
450
+
451
+ // Normal down movement
452
+ buffer.vimMoveDown(repeatCount);
453
+ dispatch({ type: 'CLEAR_COUNT' });
454
+ return true;
455
+ }
456
+
457
+ case 'k': {
458
+ // Check if this is part of a change command (ck)
459
+ if (state.pendingOperator === 'c') {
460
+ return handleChangeMovement('k');
461
+ }
462
+
463
+ // Normal up movement
464
+ buffer.vimMoveUp(repeatCount);
465
+ dispatch({ type: 'CLEAR_COUNT' });
466
+ return true;
467
+ }
468
+
469
+ case 'l': {
470
+ // Check if this is part of a change command (cl)
471
+ if (state.pendingOperator === 'c') {
472
+ return handleChangeMovement('l');
473
+ }
474
+
475
+ // Normal right movement
476
+ buffer.vimMoveRight(repeatCount);
477
+ dispatch({ type: 'CLEAR_COUNT' });
478
+ return true;
479
+ }
480
+
481
+ case 'w': {
482
+ // Check if this is part of a delete or change command (dw/cw)
483
+ if (state.pendingOperator === 'd') {
484
+ return handleOperatorMotion('d', 'w');
485
+ }
486
+ if (state.pendingOperator === 'c') {
487
+ return handleOperatorMotion('c', 'w');
488
+ }
489
+
490
+ // Normal word movement
491
+ buffer.vimMoveWordForward(repeatCount);
492
+ dispatch({ type: 'CLEAR_COUNT' });
493
+ return true;
494
+ }
495
+
496
+ case 'b': {
497
+ // Check if this is part of a delete or change command (db/cb)
498
+ if (state.pendingOperator === 'd') {
499
+ return handleOperatorMotion('d', 'b');
500
+ }
501
+ if (state.pendingOperator === 'c') {
502
+ return handleOperatorMotion('c', 'b');
503
+ }
504
+
505
+ // Normal backward word movement
506
+ buffer.vimMoveWordBackward(repeatCount);
507
+ dispatch({ type: 'CLEAR_COUNT' });
508
+ return true;
509
+ }
510
+
511
+ case 'e': {
512
+ // Check if this is part of a delete or change command (de/ce)
513
+ if (state.pendingOperator === 'd') {
514
+ return handleOperatorMotion('d', 'e');
515
+ }
516
+ if (state.pendingOperator === 'c') {
517
+ return handleOperatorMotion('c', 'e');
518
+ }
519
+
520
+ // Normal word end movement
521
+ buffer.vimMoveWordEnd(repeatCount);
522
+ dispatch({ type: 'CLEAR_COUNT' });
523
+ return true;
524
+ }
525
+
526
+ case 'x': {
527
+ // Delete character under cursor
528
+ buffer.vimDeleteChar(repeatCount);
529
+ dispatch({
530
+ type: 'SET_LAST_COMMAND',
531
+ command: { type: CMD_TYPES.DELETE_CHAR, count: repeatCount },
532
+ });
533
+ dispatch({ type: 'CLEAR_COUNT' });
534
+ return true;
535
+ }
536
+
537
+ case 'i': {
538
+ // Enter INSERT mode at current position
539
+ buffer.vimInsertAtCursor();
540
+ updateMode('INSERT');
541
+ dispatch({ type: 'CLEAR_COUNT' });
542
+ return true;
543
+ }
544
+
545
+ case 'a': {
546
+ // Enter INSERT mode after current position
547
+ buffer.vimAppendAtCursor();
548
+ updateMode('INSERT');
549
+ dispatch({ type: 'CLEAR_COUNT' });
550
+ return true;
551
+ }
552
+
553
+ case 'o': {
554
+ // Insert new line after current line and enter INSERT mode
555
+ buffer.vimOpenLineBelow();
556
+ updateMode('INSERT');
557
+ dispatch({ type: 'CLEAR_COUNT' });
558
+ return true;
559
+ }
560
+
561
+ case 'O': {
562
+ // Insert new line before current line and enter INSERT mode
563
+ buffer.vimOpenLineAbove();
564
+ updateMode('INSERT');
565
+ dispatch({ type: 'CLEAR_COUNT' });
566
+ return true;
567
+ }
568
+
569
+ case '0': {
570
+ // Move to start of line
571
+ buffer.vimMoveToLineStart();
572
+ dispatch({ type: 'CLEAR_COUNT' });
573
+ return true;
574
+ }
575
+
576
+ case '$': {
577
+ // Move to end of line
578
+ buffer.vimMoveToLineEnd();
579
+ dispatch({ type: 'CLEAR_COUNT' });
580
+ return true;
581
+ }
582
+
583
+ case '^': {
584
+ // Move to first non-whitespace character
585
+ buffer.vimMoveToFirstNonWhitespace();
586
+ dispatch({ type: 'CLEAR_COUNT' });
587
+ return true;
588
+ }
589
+
590
+ case 'g': {
591
+ if (state.pendingOperator === 'g') {
592
+ // Second 'g' - go to first line (gg command)
593
+ buffer.vimMoveToFirstLine();
594
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: null });
595
+ } else {
596
+ // First 'g' - wait for second g
597
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: 'g' });
598
+ }
599
+ dispatch({ type: 'CLEAR_COUNT' });
600
+ return true;
601
+ }
602
+
603
+ case 'G': {
604
+ if (state.count > 0) {
605
+ // Go to specific line number (1-based) when a count was provided
606
+ buffer.vimMoveToLine(state.count);
607
+ } else {
608
+ // Go to last line when no count was provided
609
+ buffer.vimMoveToLastLine();
610
+ }
611
+ dispatch({ type: 'CLEAR_COUNT' });
612
+ return true;
613
+ }
614
+
615
+ case 'I': {
616
+ // Enter INSERT mode at start of line (first non-whitespace)
617
+ buffer.vimInsertAtLineStart();
618
+ updateMode('INSERT');
619
+ dispatch({ type: 'CLEAR_COUNT' });
620
+ return true;
621
+ }
622
+
623
+ case 'A': {
624
+ // Enter INSERT mode at end of line
625
+ buffer.vimAppendAtLineEnd();
626
+ updateMode('INSERT');
627
+ dispatch({ type: 'CLEAR_COUNT' });
628
+ return true;
629
+ }
630
+
631
+ case 'd': {
632
+ if (state.pendingOperator === 'd') {
633
+ // Second 'd' - delete N lines (dd command)
634
+ const repeatCount = getCurrentCount();
635
+ executeCommand(CMD_TYPES.DELETE_LINE, repeatCount);
636
+ dispatch({
637
+ type: 'SET_LAST_COMMAND',
638
+ command: { type: CMD_TYPES.DELETE_LINE, count: repeatCount },
639
+ });
640
+ dispatch({ type: 'CLEAR_COUNT' });
641
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: null });
642
+ } else {
643
+ // First 'd' - wait for movement command
644
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: 'd' });
645
+ }
646
+ return true;
647
+ }
648
+
649
+ case 'c': {
650
+ if (state.pendingOperator === 'c') {
651
+ // Second 'c' - change N entire lines (cc command)
652
+ const repeatCount = getCurrentCount();
653
+ executeCommand(CMD_TYPES.CHANGE_LINE, repeatCount);
654
+ dispatch({
655
+ type: 'SET_LAST_COMMAND',
656
+ command: { type: CMD_TYPES.CHANGE_LINE, count: repeatCount },
657
+ });
658
+ dispatch({ type: 'CLEAR_COUNT' });
659
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: null });
660
+ } else {
661
+ // First 'c' - wait for movement command
662
+ dispatch({ type: 'SET_PENDING_OPERATOR', operator: 'c' });
663
+ }
664
+ return true;
665
+ }
666
+
667
+ case 'D': {
668
+ // Delete from cursor to end of line (equivalent to d$)
669
+ executeCommand(CMD_TYPES.DELETE_TO_EOL, 1);
670
+ dispatch({
671
+ type: 'SET_LAST_COMMAND',
672
+ command: { type: CMD_TYPES.DELETE_TO_EOL, count: 1 },
673
+ });
674
+ dispatch({ type: 'CLEAR_COUNT' });
675
+ return true;
676
+ }
677
+
678
+ case 'C': {
679
+ // Change from cursor to end of line (equivalent to c$)
680
+ executeCommand(CMD_TYPES.CHANGE_TO_EOL, 1);
681
+ dispatch({
682
+ type: 'SET_LAST_COMMAND',
683
+ command: { type: CMD_TYPES.CHANGE_TO_EOL, count: 1 },
684
+ });
685
+ dispatch({ type: 'CLEAR_COUNT' });
686
+ return true;
687
+ }
688
+
689
+ case '.': {
690
+ // Repeat last command
691
+ if (state.lastCommand) {
692
+ const cmdData = state.lastCommand;
693
+
694
+ // All repeatable commands are now handled by executeCommand
695
+ executeCommand(cmdData.type, cmdData.count);
696
+ }
697
+
698
+ dispatch({ type: 'CLEAR_COUNT' });
699
+ return true;
700
+ }
701
+
702
+ default: {
703
+ // Check for arrow keys (they have different sequences but known names)
704
+ if (normalizedKey.name === 'left') {
705
+ // Left arrow - same as 'h'
706
+ if (state.pendingOperator === 'c') {
707
+ return handleChangeMovement('h');
708
+ }
709
+
710
+ // Normal left movement (same as 'h')
711
+ buffer.vimMoveLeft(repeatCount);
712
+ dispatch({ type: 'CLEAR_COUNT' });
713
+ return true;
714
+ }
715
+
716
+ if (normalizedKey.name === 'down') {
717
+ // Down arrow - same as 'j'
718
+ if (state.pendingOperator === 'c') {
719
+ return handleChangeMovement('j');
720
+ }
721
+
722
+ // Normal down movement (same as 'j')
723
+ buffer.vimMoveDown(repeatCount);
724
+ dispatch({ type: 'CLEAR_COUNT' });
725
+ return true;
726
+ }
727
+
728
+ if (normalizedKey.name === 'up') {
729
+ // Up arrow - same as 'k'
730
+ if (state.pendingOperator === 'c') {
731
+ return handleChangeMovement('k');
732
+ }
733
+
734
+ // Normal up movement (same as 'k')
735
+ buffer.vimMoveUp(repeatCount);
736
+ dispatch({ type: 'CLEAR_COUNT' });
737
+ return true;
738
+ }
739
+
740
+ if (normalizedKey.name === 'right') {
741
+ // Right arrow - same as 'l'
742
+ if (state.pendingOperator === 'c') {
743
+ return handleChangeMovement('l');
744
+ }
745
+
746
+ // Normal right movement (same as 'l')
747
+ buffer.vimMoveRight(repeatCount);
748
+ dispatch({ type: 'CLEAR_COUNT' });
749
+ return true;
750
+ }
751
+
752
+ // Unknown command, clear count and pending states
753
+ dispatch({ type: 'CLEAR_PENDING_STATES' });
754
+ return true; // Still handled by vim to prevent other handlers
755
+ }
756
+ }
757
+ }
758
+
759
+ return false; // Not handled by vim
760
+ },
761
+ [
762
+ vimEnabled,
763
+ normalizeKey,
764
+ handleInsertModeInput,
765
+ state.mode,
766
+ state.count,
767
+ state.pendingOperator,
768
+ state.lastCommand,
769
+ dispatch,
770
+ getCurrentCount,
771
+ handleChangeMovement,
772
+ handleOperatorMotion,
773
+ buffer,
774
+ executeCommand,
775
+ updateMode,
776
+ ],
777
+ );
778
+
779
+ return {
780
+ mode: state.mode,
781
+ vimModeEnabled: vimEnabled,
782
+ handleInput, // Expose the input handler for InputPrompt to use
783
+ };
784
+ }
projects/ui/qwen-code/packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Box, Newline, Text } from 'ink';
8
+ import { RadioButtonSelect } from '../components/shared/RadioButtonSelect.js';
9
+ import { usePrivacySettings } from '../hooks/usePrivacySettings.js';
10
+ import { CloudPaidPrivacyNotice } from './CloudPaidPrivacyNotice.js';
11
+ import { Config } from '@qwen-code/qwen-code-core';
12
+ import { Colors } from '../colors.js';
13
+ import { useKeypress } from '../hooks/useKeypress.js';
14
+
15
+ interface CloudFreePrivacyNoticeProps {
16
+ config: Config;
17
+ onExit: () => void;
18
+ }
19
+
20
+ export const CloudFreePrivacyNotice = ({
21
+ config,
22
+ onExit,
23
+ }: CloudFreePrivacyNoticeProps) => {
24
+ const { privacyState, updateDataCollectionOptIn } =
25
+ usePrivacySettings(config);
26
+
27
+ useKeypress(
28
+ (key) => {
29
+ if (privacyState.error && key.name === 'escape') {
30
+ onExit();
31
+ }
32
+ },
33
+ { isActive: true },
34
+ );
35
+
36
+ if (privacyState.isLoading) {
37
+ return <Text color={Colors.Gray}>Loading...</Text>;
38
+ }
39
+
40
+ if (privacyState.error) {
41
+ return (
42
+ <Box flexDirection="column" marginY={1}>
43
+ <Text color={Colors.AccentRed}>
44
+ Error loading Opt-in settings: {privacyState.error}
45
+ </Text>
46
+ <Text color={Colors.Gray}>Press Esc to exit.</Text>
47
+ </Box>
48
+ );
49
+ }
50
+
51
+ if (privacyState.isFreeTier === false) {
52
+ return <CloudPaidPrivacyNotice onExit={onExit} />;
53
+ }
54
+
55
+ const items = [
56
+ { label: 'Yes', value: true },
57
+ { label: 'No', value: false },
58
+ ];
59
+
60
+ return (
61
+ <Box flexDirection="column" marginY={1}>
62
+ <Text bold color={Colors.AccentPurple}>
63
+ Gemini Code Assist for Individuals Privacy Notice
64
+ </Text>
65
+ <Newline />
66
+ <Text>
67
+ This notice and our Privacy Policy
68
+ <Text color={Colors.AccentBlue}>[1]</Text> describe how Gemini Code
69
+ Assist handles your data. Please read them carefully.
70
+ </Text>
71
+ <Newline />
72
+ <Text>
73
+ When you use Gemini Code Assist for individuals with Gemini CLI, Google
74
+ collects your prompts, related code, generated output, code edits,
75
+ related feature usage information, and your feedback to provide,
76
+ improve, and develop Google products and services and machine learning
77
+ technologies.
78
+ </Text>
79
+ <Newline />
80
+ <Text>
81
+ To help with quality and improve our products (such as generative
82
+ machine-learning models), human reviewers may read, annotate, and
83
+ process the data collected above. We take steps to protect your privacy
84
+ as part of this process. This includes disconnecting the data from your
85
+ Google Account before reviewers see or annotate it, and storing those
86
+ disconnected copies for up to 18 months. Please don&apos;t submit
87
+ confidential information or any data you wouldn&apos;t want a reviewer
88
+ to see or Google to use to improve our products, services and
89
+ machine-learning technologies.
90
+ </Text>
91
+ <Newline />
92
+ <Box flexDirection="column">
93
+ <Text>
94
+ Allow Google to use this data to develop and improve our products?
95
+ </Text>
96
+ <RadioButtonSelect
97
+ items={items}
98
+ initialIndex={privacyState.dataCollectionOptIn ? 0 : 1}
99
+ onSelect={(value) => {
100
+ updateDataCollectionOptIn(value);
101
+ // Only exit if there was no error.
102
+ if (!privacyState.error) {
103
+ onExit();
104
+ }
105
+ }}
106
+ />
107
+ </Box>
108
+ <Newline />
109
+ <Text>
110
+ <Text color={Colors.AccentBlue}>[1]</Text>{' '}
111
+ https://policies.google.com/privacy
112
+ </Text>
113
+ <Newline />
114
+ <Text color={Colors.Gray}>Press Enter to choose an option and exit.</Text>
115
+ </Box>
116
+ );
117
+ };
projects/ui/qwen-code/packages/cli/src/ui/privacy/CloudPaidPrivacyNotice.tsx ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Box, Newline, Text } from 'ink';
8
+ import { Colors } from '../colors.js';
9
+ import { useKeypress } from '../hooks/useKeypress.js';
10
+
11
+ interface CloudPaidPrivacyNoticeProps {
12
+ onExit: () => void;
13
+ }
14
+
15
+ export const CloudPaidPrivacyNotice = ({
16
+ onExit,
17
+ }: CloudPaidPrivacyNoticeProps) => {
18
+ useKeypress(
19
+ (key) => {
20
+ if (key.name === 'escape') {
21
+ onExit();
22
+ }
23
+ },
24
+ { isActive: true },
25
+ );
26
+
27
+ return (
28
+ <Box flexDirection="column" marginBottom={1}>
29
+ <Text bold color={Colors.AccentPurple}>
30
+ Vertex AI Notice
31
+ </Text>
32
+ <Newline />
33
+ <Text>
34
+ Service Specific Terms<Text color={Colors.AccentBlue}>[1]</Text> are
35
+ incorporated into the agreement under which Google has agreed to provide
36
+ Google Cloud Platform<Text color={Colors.AccentGreen}>[2]</Text> to
37
+ Customer (the “Agreement”). If the Agreement authorizes the resale or
38
+ supply of Google Cloud Platform under a Google Cloud partner or reseller
39
+ program, then except for in the section entitled “Partner-Specific
40
+ Terms”, all references to Customer in the Service Specific Terms mean
41
+ Partner or Reseller (as applicable), and all references to Customer Data
42
+ in the Service Specific Terms mean Partner Data. Capitalized terms used
43
+ but not defined in the Service Specific Terms have the meaning given to
44
+ them in the Agreement.
45
+ </Text>
46
+ <Newline />
47
+ <Text>
48
+ <Text color={Colors.AccentBlue}>[1]</Text>{' '}
49
+ https://cloud.google.com/terms/service-terms
50
+ </Text>
51
+ <Text>
52
+ <Text color={Colors.AccentGreen}>[2]</Text>{' '}
53
+ https://cloud.google.com/terms/services
54
+ </Text>
55
+ <Newline />
56
+ <Text color={Colors.Gray}>Press Esc to exit.</Text>
57
+ </Box>
58
+ );
59
+ };
projects/ui/qwen-code/packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Box, Newline, Text } from 'ink';
8
+ import { Colors } from '../colors.js';
9
+ import { useKeypress } from '../hooks/useKeypress.js';
10
+
11
+ interface GeminiPrivacyNoticeProps {
12
+ onExit: () => void;
13
+ }
14
+
15
+ export const GeminiPrivacyNotice = ({ onExit }: GeminiPrivacyNoticeProps) => {
16
+ useKeypress(
17
+ (key) => {
18
+ if (key.name === 'escape') {
19
+ onExit();
20
+ }
21
+ },
22
+ { isActive: true },
23
+ );
24
+
25
+ return (
26
+ <Box flexDirection="column" marginBottom={1}>
27
+ <Text bold color={Colors.AccentPurple}>
28
+ Gemini API Key Notice
29
+ </Text>
30
+ <Newline />
31
+ <Text>
32
+ By using the Gemini API<Text color={Colors.AccentBlue}>[1]</Text>,
33
+ Google AI Studio
34
+ <Text color={Colors.AccentRed}>[2]</Text>, and the other Google
35
+ developer services that reference these terms (collectively, the
36
+ &quot;APIs&quot; or &quot;Services&quot;), you are agreeing to Google
37
+ APIs Terms of Service (the &quot;API Terms&quot;)
38
+ <Text color={Colors.AccentGreen}>[3]</Text>, and the Gemini API
39
+ Additional Terms of Service (the &quot;Additional Terms&quot;)
40
+ <Text color={Colors.AccentPurple}>[4]</Text>.
41
+ </Text>
42
+ <Newline />
43
+ <Text>
44
+ <Text color={Colors.AccentBlue}>[1]</Text>{' '}
45
+ https://ai.google.dev/docs/gemini_api_overview
46
+ </Text>
47
+ <Text>
48
+ <Text color={Colors.AccentRed}>[2]</Text> https://aistudio.google.com/
49
+ </Text>
50
+ <Text>
51
+ <Text color={Colors.AccentGreen}>[3]</Text>{' '}
52
+ https://developers.google.com/terms
53
+ </Text>
54
+ <Text>
55
+ <Text color={Colors.AccentPurple}>[4]</Text>{' '}
56
+ https://ai.google.dev/gemini-api/terms
57
+ </Text>
58
+ <Newline />
59
+ <Text color={Colors.Gray}>Press Esc to exit.</Text>
60
+ </Box>
61
+ );
62
+ };
projects/ui/qwen-code/packages/cli/src/ui/privacy/PrivacyNotice.tsx ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Box } from 'ink';
8
+ import { type Config, AuthType } from '@qwen-code/qwen-code-core';
9
+ import { GeminiPrivacyNotice } from './GeminiPrivacyNotice.js';
10
+ import { CloudPaidPrivacyNotice } from './CloudPaidPrivacyNotice.js';
11
+ import { CloudFreePrivacyNotice } from './CloudFreePrivacyNotice.js';
12
+
13
+ interface PrivacyNoticeProps {
14
+ onExit: () => void;
15
+ config: Config;
16
+ }
17
+
18
+ const PrivacyNoticeText = ({
19
+ config,
20
+ onExit,
21
+ }: {
22
+ config: Config;
23
+ onExit: () => void;
24
+ }) => {
25
+ const authType = config.getContentGeneratorConfig()?.authType;
26
+
27
+ switch (authType) {
28
+ case AuthType.USE_GEMINI:
29
+ return <GeminiPrivacyNotice onExit={onExit} />;
30
+ case AuthType.USE_VERTEX_AI:
31
+ return <CloudPaidPrivacyNotice onExit={onExit} />;
32
+ case AuthType.LOGIN_WITH_GOOGLE:
33
+ default:
34
+ return <CloudFreePrivacyNotice config={config} onExit={onExit} />;
35
+ }
36
+ };
37
+
38
+ export const PrivacyNotice = ({ onExit, config }: PrivacyNoticeProps) => (
39
+ <Box borderStyle="round" padding={1} flexDirection="column">
40
+ <PrivacyNoticeText config={config} onExit={onExit} />
41
+ </Box>
42
+ );
projects/ui/qwen-code/packages/cli/src/ui/themes/ansi-light.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 { type ColorsTheme, Theme } from './theme.js';
8
+ import { lightSemanticColors } from './semantic-tokens.js';
9
+
10
+ const ansiLightColors: ColorsTheme = {
11
+ type: 'light',
12
+ Background: 'white',
13
+ Foreground: '#444',
14
+ LightBlue: 'blue',
15
+ AccentBlue: 'blue',
16
+ AccentPurple: 'purple',
17
+ AccentCyan: 'cyan',
18
+ AccentGreen: 'green',
19
+ AccentYellow: 'orange',
20
+ AccentRed: 'red',
21
+ DiffAdded: '#E5F2E5',
22
+ DiffRemoved: '#FFE5E5',
23
+ Comment: 'gray',
24
+ Gray: 'gray',
25
+ GradientColors: ['blue', 'green'],
26
+ };
27
+
28
+ export const ANSILight: Theme = new Theme(
29
+ 'ANSI Light',
30
+ 'light',
31
+ {
32
+ hljs: {
33
+ display: 'block',
34
+ overflowX: 'auto',
35
+ padding: '0.5em',
36
+ background: 'white',
37
+ color: 'black',
38
+ },
39
+ 'hljs-keyword': {
40
+ color: 'blue',
41
+ },
42
+ 'hljs-literal': {
43
+ color: 'blue',
44
+ },
45
+ 'hljs-symbol': {
46
+ color: 'blue',
47
+ },
48
+ 'hljs-name': {
49
+ color: 'blue',
50
+ },
51
+ 'hljs-link': {
52
+ color: 'blue',
53
+ },
54
+ 'hljs-built_in': {
55
+ color: 'cyan',
56
+ },
57
+ 'hljs-type': {
58
+ color: 'cyan',
59
+ },
60
+ 'hljs-number': {
61
+ color: 'green',
62
+ },
63
+ 'hljs-class': {
64
+ color: 'green',
65
+ },
66
+ 'hljs-string': {
67
+ color: 'red',
68
+ },
69
+ 'hljs-meta-string': {
70
+ color: 'red',
71
+ },
72
+ 'hljs-regexp': {
73
+ color: 'magenta',
74
+ },
75
+ 'hljs-template-tag': {
76
+ color: 'magenta',
77
+ },
78
+ 'hljs-subst': {
79
+ color: 'black',
80
+ },
81
+ 'hljs-function': {
82
+ color: 'black',
83
+ },
84
+ 'hljs-title': {
85
+ color: 'black',
86
+ },
87
+ 'hljs-params': {
88
+ color: 'black',
89
+ },
90
+ 'hljs-formula': {
91
+ color: 'black',
92
+ },
93
+ 'hljs-comment': {
94
+ color: 'gray',
95
+ },
96
+ 'hljs-quote': {
97
+ color: 'gray',
98
+ },
99
+ 'hljs-doctag': {
100
+ color: 'gray',
101
+ },
102
+ 'hljs-meta': {
103
+ color: 'gray',
104
+ },
105
+ 'hljs-meta-keyword': {
106
+ color: 'gray',
107
+ },
108
+ 'hljs-tag': {
109
+ color: 'gray',
110
+ },
111
+ 'hljs-variable': {
112
+ color: 'purple',
113
+ },
114
+ 'hljs-template-variable': {
115
+ color: 'purple',
116
+ },
117
+ 'hljs-attr': {
118
+ color: 'blue',
119
+ },
120
+ 'hljs-attribute': {
121
+ color: 'blue',
122
+ },
123
+ 'hljs-builtin-name': {
124
+ color: 'blue',
125
+ },
126
+ 'hljs-section': {
127
+ color: 'orange',
128
+ },
129
+ 'hljs-bullet': {
130
+ color: 'orange',
131
+ },
132
+ 'hljs-selector-tag': {
133
+ color: 'orange',
134
+ },
135
+ 'hljs-selector-id': {
136
+ color: 'orange',
137
+ },
138
+ 'hljs-selector-class': {
139
+ color: 'orange',
140
+ },
141
+ 'hljs-selector-attr': {
142
+ color: 'orange',
143
+ },
144
+ 'hljs-selector-pseudo': {
145
+ color: 'orange',
146
+ },
147
+ },
148
+ ansiLightColors,
149
+ lightSemanticColors,
150
+ );