ADAPT-Chase commited on
Commit
faa8208
·
verified ·
1 Parent(s): ec0453e

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/components/OpenAIKeyPrompt.test.tsx +64 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/components/OpenAIKeyPrompt.tsx +197 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/components/PrepareLabel.tsx +48 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/components/QwenOAuthProgress.test.tsx +546 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/components/QwenOAuthProgress.tsx +267 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/components/SessionSummaryDisplay.test.tsx +75 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/components/SessionSummaryDisplay.tsx +18 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/components/SettingsDialog.test.tsx +865 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/components/SettingsDialog.tsx +753 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/components/ShellConfirmationDialog.test.tsx +53 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/components/ShellConfirmationDialog.tsx +103 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/components/ShellModeIndicator.tsx +18 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/components/ShowMoreLines.tsx +40 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/components/StatsDisplay.test.tsx +401 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/components/StatsDisplay.tsx +273 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/components/SuggestionsDisplay.tsx +102 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/components/ThemeDialog.tsx +310 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/components/Tips.tsx +45 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/components/TodoDisplay.test.tsx +97 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/components/TodoDisplay.tsx +72 -0
projects/ui/qwen-code/packages/cli/src/ui/components/OpenAIKeyPrompt.test.tsx ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { render } from 'ink-testing-library';
8
+ import { describe, it, expect, vi } from 'vitest';
9
+ import { OpenAIKeyPrompt } from './OpenAIKeyPrompt.js';
10
+
11
+ describe('OpenAIKeyPrompt', () => {
12
+ it('should render the prompt correctly', () => {
13
+ const onSubmit = vi.fn();
14
+ const onCancel = vi.fn();
15
+
16
+ const { lastFrame } = render(
17
+ <OpenAIKeyPrompt onSubmit={onSubmit} onCancel={onCancel} />,
18
+ );
19
+
20
+ expect(lastFrame()).toContain('OpenAI Configuration Required');
21
+ expect(lastFrame()).toContain('https://platform.openai.com/api-keys');
22
+ expect(lastFrame()).toContain(
23
+ 'Press Enter to continue, Tab/↑↓ to navigate, Esc to cancel',
24
+ );
25
+ });
26
+
27
+ it('should show the component with proper styling', () => {
28
+ const onSubmit = vi.fn();
29
+ const onCancel = vi.fn();
30
+
31
+ const { lastFrame } = render(
32
+ <OpenAIKeyPrompt onSubmit={onSubmit} onCancel={onCancel} />,
33
+ );
34
+
35
+ const output = lastFrame();
36
+ expect(output).toContain('OpenAI Configuration Required');
37
+ expect(output).toContain('API Key:');
38
+ expect(output).toContain('Base URL:');
39
+ expect(output).toContain('Model:');
40
+ expect(output).toContain(
41
+ 'Press Enter to continue, Tab/↑↓ to navigate, Esc to cancel',
42
+ );
43
+ });
44
+
45
+ it('should handle paste with control characters', async () => {
46
+ const onSubmit = vi.fn();
47
+ const onCancel = vi.fn();
48
+
49
+ const { stdin } = render(
50
+ <OpenAIKeyPrompt onSubmit={onSubmit} onCancel={onCancel} />,
51
+ );
52
+
53
+ // Simulate paste with control characters
54
+ const pasteWithControlChars = '\x1b[200~sk-test123\x1b[201~';
55
+ stdin.write(pasteWithControlChars);
56
+
57
+ // Wait a bit for processing
58
+ await new Promise((resolve) => setTimeout(resolve, 50));
59
+
60
+ // The component should have filtered out the control characters
61
+ // and only kept 'sk-test123'
62
+ expect(onSubmit).not.toHaveBeenCalled(); // Should not submit yet
63
+ });
64
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/OpenAIKeyPrompt.tsx ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React, { useState } from 'react';
8
+ import { Box, Text, useInput } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+
11
+ interface OpenAIKeyPromptProps {
12
+ onSubmit: (apiKey: string, baseUrl: string, model: string) => void;
13
+ onCancel: () => void;
14
+ }
15
+
16
+ export function OpenAIKeyPrompt({
17
+ onSubmit,
18
+ onCancel,
19
+ }: OpenAIKeyPromptProps): React.JSX.Element {
20
+ const [apiKey, setApiKey] = useState('');
21
+ const [baseUrl, setBaseUrl] = useState('');
22
+ const [model, setModel] = useState('');
23
+ const [currentField, setCurrentField] = useState<
24
+ 'apiKey' | 'baseUrl' | 'model'
25
+ >('apiKey');
26
+
27
+ useInput((input, key) => {
28
+ // 过滤粘贴相关的控制序列
29
+ let cleanInput = (input || '')
30
+ // 过滤 ESC 开头的控制序列(如 \u001b[200~、\u001b[201~ 等)
31
+ .replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '') // eslint-disable-line no-control-regex
32
+ // 过滤粘贴开始标记 [200~
33
+ .replace(/\[200~/g, '')
34
+ // 过滤粘贴结束标记 [201~
35
+ .replace(/\[201~/g, '')
36
+ // 过滤单独的 [ 和 ~ 字符(可能是粘贴标记的残留)
37
+ .replace(/^\[|~$/g, '');
38
+
39
+ // 再过滤所有不可见字符(ASCII < 32,除了回车换行)
40
+ cleanInput = cleanInput
41
+ .split('')
42
+ .filter((ch) => ch.charCodeAt(0) >= 32)
43
+ .join('');
44
+
45
+ if (cleanInput.length > 0) {
46
+ if (currentField === 'apiKey') {
47
+ setApiKey((prev) => prev + cleanInput);
48
+ } else if (currentField === 'baseUrl') {
49
+ setBaseUrl((prev) => prev + cleanInput);
50
+ } else if (currentField === 'model') {
51
+ setModel((prev) => prev + cleanInput);
52
+ }
53
+ return;
54
+ }
55
+
56
+ // 检查是否是 Enter 键(通过检查输入是否包含换行符)
57
+ if (input.includes('\n') || input.includes('\r')) {
58
+ if (currentField === 'apiKey') {
59
+ // 允许空 API key 跳转到下一个字段,让用户稍后可以返回修改
60
+ setCurrentField('baseUrl');
61
+ return;
62
+ } else if (currentField === 'baseUrl') {
63
+ setCurrentField('model');
64
+ return;
65
+ } else if (currentField === 'model') {
66
+ // 只有在提交时才检查 API key 是否为空
67
+ if (apiKey.trim()) {
68
+ onSubmit(apiKey.trim(), baseUrl.trim(), model.trim());
69
+ } else {
70
+ // 如果 API key 为空,回到 API key 字段
71
+ setCurrentField('apiKey');
72
+ }
73
+ }
74
+ return;
75
+ }
76
+
77
+ if (key.escape) {
78
+ onCancel();
79
+ return;
80
+ }
81
+
82
+ // Handle Tab key for field navigation
83
+ if (key.tab) {
84
+ if (currentField === 'apiKey') {
85
+ setCurrentField('baseUrl');
86
+ } else if (currentField === 'baseUrl') {
87
+ setCurrentField('model');
88
+ } else if (currentField === 'model') {
89
+ setCurrentField('apiKey');
90
+ }
91
+ return;
92
+ }
93
+
94
+ // Handle arrow keys for field navigation
95
+ if (key.upArrow) {
96
+ if (currentField === 'baseUrl') {
97
+ setCurrentField('apiKey');
98
+ } else if (currentField === 'model') {
99
+ setCurrentField('baseUrl');
100
+ }
101
+ return;
102
+ }
103
+
104
+ if (key.downArrow) {
105
+ if (currentField === 'apiKey') {
106
+ setCurrentField('baseUrl');
107
+ } else if (currentField === 'baseUrl') {
108
+ setCurrentField('model');
109
+ }
110
+ return;
111
+ }
112
+
113
+ // Handle backspace - check both key.backspace and delete key
114
+ if (key.backspace || key.delete) {
115
+ if (currentField === 'apiKey') {
116
+ setApiKey((prev) => prev.slice(0, -1));
117
+ } else if (currentField === 'baseUrl') {
118
+ setBaseUrl((prev) => prev.slice(0, -1));
119
+ } else if (currentField === 'model') {
120
+ setModel((prev) => prev.slice(0, -1));
121
+ }
122
+ return;
123
+ }
124
+ });
125
+
126
+ return (
127
+ <Box
128
+ borderStyle="round"
129
+ borderColor={Colors.AccentBlue}
130
+ flexDirection="column"
131
+ padding={1}
132
+ width="100%"
133
+ >
134
+ <Text bold color={Colors.AccentBlue}>
135
+ OpenAI Configuration Required
136
+ </Text>
137
+ <Box marginTop={1}>
138
+ <Text>
139
+ Please enter your OpenAI configuration. You can get an API key from{' '}
140
+ <Text color={Colors.AccentBlue}>
141
+ https://platform.openai.com/api-keys
142
+ </Text>
143
+ </Text>
144
+ </Box>
145
+ <Box marginTop={1} flexDirection="row">
146
+ <Box width={12}>
147
+ <Text
148
+ color={currentField === 'apiKey' ? Colors.AccentBlue : Colors.Gray}
149
+ >
150
+ API Key:
151
+ </Text>
152
+ </Box>
153
+ <Box flexGrow={1}>
154
+ <Text>
155
+ {currentField === 'apiKey' ? '> ' : ' '}
156
+ {apiKey || ' '}
157
+ </Text>
158
+ </Box>
159
+ </Box>
160
+ <Box marginTop={1} flexDirection="row">
161
+ <Box width={12}>
162
+ <Text
163
+ color={currentField === 'baseUrl' ? Colors.AccentBlue : Colors.Gray}
164
+ >
165
+ Base URL:
166
+ </Text>
167
+ </Box>
168
+ <Box flexGrow={1}>
169
+ <Text>
170
+ {currentField === 'baseUrl' ? '> ' : ' '}
171
+ {baseUrl}
172
+ </Text>
173
+ </Box>
174
+ </Box>
175
+ <Box marginTop={1} flexDirection="row">
176
+ <Box width={12}>
177
+ <Text
178
+ color={currentField === 'model' ? Colors.AccentBlue : Colors.Gray}
179
+ >
180
+ Model:
181
+ </Text>
182
+ </Box>
183
+ <Box flexGrow={1}>
184
+ <Text>
185
+ {currentField === 'model' ? '> ' : ' '}
186
+ {model}
187
+ </Text>
188
+ </Box>
189
+ </Box>
190
+ <Box marginTop={1}>
191
+ <Text color={Colors.Gray}>
192
+ Press Enter to continue, Tab/↑↓ to navigate, Esc to cancel
193
+ </Text>
194
+ </Box>
195
+ </Box>
196
+ );
197
+ }
projects/ui/qwen-code/packages/cli/src/ui/components/PrepareLabel.tsx ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+
11
+ interface PrepareLabelProps {
12
+ label: string;
13
+ matchedIndex?: number;
14
+ userInput: string;
15
+ textColor: string;
16
+ highlightColor?: string;
17
+ }
18
+
19
+ export const PrepareLabel: React.FC<PrepareLabelProps> = ({
20
+ label,
21
+ matchedIndex,
22
+ userInput,
23
+ textColor,
24
+ highlightColor = Colors.AccentYellow,
25
+ }) => {
26
+ if (
27
+ matchedIndex === undefined ||
28
+ matchedIndex < 0 ||
29
+ matchedIndex >= label.length ||
30
+ userInput.length === 0
31
+ ) {
32
+ return <Text color={textColor}>{label}</Text>;
33
+ }
34
+
35
+ const start = label.slice(0, matchedIndex);
36
+ const match = label.slice(matchedIndex, matchedIndex + userInput.length);
37
+ const end = label.slice(matchedIndex + userInput.length);
38
+
39
+ return (
40
+ <Text>
41
+ <Text color={textColor}>{start}</Text>
42
+ <Text color="black" bold backgroundColor={highlightColor}>
43
+ {match}
44
+ </Text>
45
+ <Text color={textColor}>{end}</Text>
46
+ </Text>
47
+ );
48
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/QwenOAuthProgress.test.tsx ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ // React import not needed for test files
8
+ import { render } from 'ink-testing-library';
9
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
10
+ import { QwenOAuthProgress } from './QwenOAuthProgress.js';
11
+ import { DeviceAuthorizationInfo } from '../hooks/useQwenAuth.js';
12
+
13
+ // Mock qrcode-terminal module
14
+ vi.mock('qrcode-terminal', () => ({
15
+ default: {
16
+ generate: vi.fn(),
17
+ },
18
+ }));
19
+
20
+ // Mock ink-spinner
21
+ vi.mock('ink-spinner', () => ({
22
+ default: ({ type }: { type: string }) => `MockSpinner(${type})`,
23
+ }));
24
+
25
+ // Mock ink-link
26
+ vi.mock('ink-link', () => ({
27
+ default: ({ children }: { children: React.ReactNode; url: string }) =>
28
+ children,
29
+ }));
30
+
31
+ describe('QwenOAuthProgress', () => {
32
+ const mockOnTimeout = vi.fn();
33
+ const mockOnCancel = vi.fn();
34
+
35
+ const createMockDeviceAuth = (
36
+ overrides: Partial<DeviceAuthorizationInfo> = {},
37
+ ): DeviceAuthorizationInfo => ({
38
+ verification_uri: 'https://example.com/device',
39
+ verification_uri_complete: 'https://example.com/device?user_code=ABC123',
40
+ user_code: 'ABC123',
41
+ expires_in: 300,
42
+ ...overrides,
43
+ });
44
+
45
+ const mockDeviceAuth = createMockDeviceAuth();
46
+
47
+ const renderComponent = (
48
+ props: Partial<{
49
+ deviceAuth: DeviceAuthorizationInfo;
50
+ authStatus:
51
+ | 'idle'
52
+ | 'polling'
53
+ | 'success'
54
+ | 'error'
55
+ | 'timeout'
56
+ | 'rate_limit';
57
+ authMessage: string | null;
58
+ }> = {},
59
+ ) =>
60
+ render(
61
+ <QwenOAuthProgress
62
+ onTimeout={mockOnTimeout}
63
+ onCancel={mockOnCancel}
64
+ {...props}
65
+ />,
66
+ );
67
+
68
+ beforeEach(() => {
69
+ vi.clearAllMocks();
70
+ vi.useFakeTimers();
71
+ });
72
+
73
+ afterEach(() => {
74
+ vi.useRealTimers();
75
+ });
76
+
77
+ describe('Loading state (no deviceAuth)', () => {
78
+ it('should render loading state when deviceAuth is not provided', () => {
79
+ const { lastFrame } = renderComponent();
80
+
81
+ const output = lastFrame();
82
+ expect(output).toContain('MockSpinner(dots)');
83
+ expect(output).toContain('Waiting for Qwen OAuth authentication...');
84
+ expect(output).toContain('(Press ESC to cancel)');
85
+ });
86
+
87
+ it('should render loading state with gray border', () => {
88
+ const { lastFrame } = renderComponent();
89
+ const output = lastFrame();
90
+
91
+ // Should not contain auth flow elements
92
+ expect(output).not.toContain('Qwen OAuth Authentication');
93
+ expect(output).not.toContain('Please visit this URL to authorize:');
94
+ // Loading state still shows time remaining with default timeout
95
+ expect(output).toContain('Time remaining:');
96
+ });
97
+ });
98
+
99
+ describe('Authenticated state (with deviceAuth)', () => {
100
+ it('should render authentication flow when deviceAuth is provided', () => {
101
+ const { lastFrame } = renderComponent({ deviceAuth: mockDeviceAuth });
102
+
103
+ const output = lastFrame();
104
+ // Initially no QR code shown until it's generated, but the status area should be visible
105
+ expect(output).toContain('MockSpinner(dots)');
106
+ expect(output).toContain('Waiting for authorization');
107
+ expect(output).toContain('Time remaining: 5:00');
108
+ expect(output).toContain('(Press ESC to cancel)');
109
+ });
110
+
111
+ it('should display correct URL in Static component when QR code is generated', async () => {
112
+ const qrcode = await import('qrcode-terminal');
113
+ const mockGenerate = vi.mocked(qrcode.default.generate);
114
+
115
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
116
+ let qrCallback: any = null;
117
+ mockGenerate.mockImplementation((url, options, callback) => {
118
+ qrCallback = callback;
119
+ });
120
+
121
+ const customAuth = createMockDeviceAuth({
122
+ verification_uri_complete: 'https://custom.com/auth?code=XYZ789',
123
+ });
124
+
125
+ const { lastFrame, rerender } = renderComponent({
126
+ deviceAuth: customAuth,
127
+ });
128
+
129
+ // Manually trigger the QR code callback
130
+ if (qrCallback && typeof qrCallback === 'function') {
131
+ qrCallback('Mock QR Code Data');
132
+ }
133
+
134
+ rerender(
135
+ <QwenOAuthProgress
136
+ onTimeout={mockOnTimeout}
137
+ onCancel={mockOnCancel}
138
+ deviceAuth={customAuth}
139
+ />,
140
+ );
141
+
142
+ expect(lastFrame()).toContain('https://custom.com/auth?code=XYZ789');
143
+ });
144
+
145
+ it('should format time correctly', () => {
146
+ const deviceAuthWithCustomTime: DeviceAuthorizationInfo = {
147
+ ...mockDeviceAuth,
148
+ expires_in: 125, // 2 minutes and 5 seconds
149
+ };
150
+
151
+ const { lastFrame } = render(
152
+ <QwenOAuthProgress
153
+ onTimeout={mockOnTimeout}
154
+ onCancel={mockOnCancel}
155
+ deviceAuth={deviceAuthWithCustomTime}
156
+ />,
157
+ );
158
+
159
+ const output = lastFrame();
160
+ expect(output).toContain('Time remaining: 2:05');
161
+ });
162
+
163
+ it('should format single digit seconds with leading zero', () => {
164
+ const deviceAuthWithCustomTime: DeviceAuthorizationInfo = {
165
+ ...mockDeviceAuth,
166
+ expires_in: 67, // 1 minute and 7 seconds
167
+ };
168
+
169
+ const { lastFrame } = render(
170
+ <QwenOAuthProgress
171
+ onTimeout={mockOnTimeout}
172
+ onCancel={mockOnCancel}
173
+ deviceAuth={deviceAuthWithCustomTime}
174
+ />,
175
+ );
176
+
177
+ const output = lastFrame();
178
+ expect(output).toContain('Time remaining: 1:07');
179
+ });
180
+ });
181
+
182
+ describe('Timer functionality', () => {
183
+ it('should countdown and call onTimeout when timer expires', async () => {
184
+ const deviceAuthWithShortTime: DeviceAuthorizationInfo = {
185
+ ...mockDeviceAuth,
186
+ expires_in: 2, // 2 seconds
187
+ };
188
+
189
+ const { rerender } = render(
190
+ <QwenOAuthProgress
191
+ onTimeout={mockOnTimeout}
192
+ onCancel={mockOnCancel}
193
+ deviceAuth={deviceAuthWithShortTime}
194
+ />,
195
+ );
196
+
197
+ // Advance timer by 1 second
198
+ vi.advanceTimersByTime(1000);
199
+ rerender(
200
+ <QwenOAuthProgress
201
+ onTimeout={mockOnTimeout}
202
+ onCancel={mockOnCancel}
203
+ deviceAuth={deviceAuthWithShortTime}
204
+ />,
205
+ );
206
+
207
+ // Advance timer by another second to trigger timeout
208
+ vi.advanceTimersByTime(1000);
209
+ rerender(
210
+ <QwenOAuthProgress
211
+ onTimeout={mockOnTimeout}
212
+ onCancel={mockOnCancel}
213
+ deviceAuth={deviceAuthWithShortTime}
214
+ />,
215
+ );
216
+
217
+ expect(mockOnTimeout).toHaveBeenCalledTimes(1);
218
+ });
219
+
220
+ it('should update time remaining display', async () => {
221
+ const { lastFrame, rerender } = render(
222
+ <QwenOAuthProgress
223
+ onTimeout={mockOnTimeout}
224
+ onCancel={mockOnCancel}
225
+ deviceAuth={mockDeviceAuth}
226
+ />,
227
+ );
228
+
229
+ // Initial time should be 5:00
230
+ expect(lastFrame()).toContain('Time remaining: 5:00');
231
+
232
+ // Advance by 1 second
233
+ vi.advanceTimersByTime(1000);
234
+ rerender(
235
+ <QwenOAuthProgress
236
+ onTimeout={mockOnTimeout}
237
+ onCancel={mockOnCancel}
238
+ deviceAuth={mockDeviceAuth}
239
+ />,
240
+ );
241
+
242
+ // Should now show 4:59
243
+ expect(lastFrame()).toContain('Time remaining: 4:59');
244
+ });
245
+
246
+ it('should use default 300 second timeout when deviceAuth is null', () => {
247
+ const { lastFrame } = render(
248
+ <QwenOAuthProgress onTimeout={mockOnTimeout} onCancel={mockOnCancel} />,
249
+ );
250
+
251
+ // Should show default 5:00 (300 seconds) timeout
252
+ expect(lastFrame()).toContain('Time remaining: 5:00');
253
+
254
+ // The timer functionality is already tested in other tests,
255
+ // this test mainly verifies the default timeout value is used
256
+ });
257
+ });
258
+
259
+ describe('Animated dots', () => {
260
+ it('should cycle through animated dots', async () => {
261
+ const { lastFrame, rerender } = render(
262
+ <QwenOAuthProgress
263
+ onTimeout={mockOnTimeout}
264
+ onCancel={mockOnCancel}
265
+ deviceAuth={mockDeviceAuth}
266
+ />,
267
+ );
268
+
269
+ // Initial state should have no dots
270
+ expect(lastFrame()).toContain('Waiting for authorization');
271
+
272
+ // Advance by 500ms to add first dot
273
+ vi.advanceTimersByTime(500);
274
+ rerender(
275
+ <QwenOAuthProgress
276
+ onTimeout={mockOnTimeout}
277
+ onCancel={mockOnCancel}
278
+ deviceAuth={mockDeviceAuth}
279
+ />,
280
+ );
281
+ expect(lastFrame()).toContain('Waiting for authorization.');
282
+
283
+ // Advance by another 500ms to add second dot
284
+ vi.advanceTimersByTime(500);
285
+ rerender(
286
+ <QwenOAuthProgress
287
+ onTimeout={mockOnTimeout}
288
+ onCancel={mockOnCancel}
289
+ deviceAuth={mockDeviceAuth}
290
+ />,
291
+ );
292
+ expect(lastFrame()).toContain('Waiting for authorization..');
293
+
294
+ // Advance by another 500ms to add third dot
295
+ vi.advanceTimersByTime(500);
296
+ rerender(
297
+ <QwenOAuthProgress
298
+ onTimeout={mockOnTimeout}
299
+ onCancel={mockOnCancel}
300
+ deviceAuth={mockDeviceAuth}
301
+ />,
302
+ );
303
+ expect(lastFrame()).toContain('Waiting for authorization...');
304
+
305
+ // Advance by another 500ms to reset dots
306
+ vi.advanceTimersByTime(500);
307
+ rerender(
308
+ <QwenOAuthProgress
309
+ onTimeout={mockOnTimeout}
310
+ onCancel={mockOnCancel}
311
+ deviceAuth={mockDeviceAuth}
312
+ />,
313
+ );
314
+ expect(lastFrame()).toContain('Waiting for authorization');
315
+ });
316
+ });
317
+
318
+ describe('QR Code functionality', () => {
319
+ it('should generate QR code when deviceAuth is provided', async () => {
320
+ const qrcode = await import('qrcode-terminal');
321
+ const mockGenerate = vi.mocked(qrcode.default.generate);
322
+
323
+ mockGenerate.mockImplementation((url, options, callback) => {
324
+ callback!('Mock QR Code Data');
325
+ });
326
+
327
+ render(
328
+ <QwenOAuthProgress
329
+ onTimeout={mockOnTimeout}
330
+ onCancel={mockOnCancel}
331
+ deviceAuth={mockDeviceAuth}
332
+ />,
333
+ );
334
+
335
+ expect(mockGenerate).toHaveBeenCalledWith(
336
+ mockDeviceAuth.verification_uri_complete,
337
+ { small: true },
338
+ expect.any(Function),
339
+ );
340
+ });
341
+
342
+ it('should display QR code in Static component when available', async () => {
343
+ const qrcode = await import('qrcode-terminal');
344
+ const mockGenerate = vi.mocked(qrcode.default.generate);
345
+
346
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
347
+ let qrCallback: any = null;
348
+ mockGenerate.mockImplementation((url, options, callback) => {
349
+ qrCallback = callback;
350
+ });
351
+
352
+ const { lastFrame, rerender } = render(
353
+ <QwenOAuthProgress
354
+ onTimeout={mockOnTimeout}
355
+ onCancel={mockOnCancel}
356
+ deviceAuth={mockDeviceAuth}
357
+ />,
358
+ );
359
+
360
+ // Manually trigger the QR code callback
361
+ if (qrCallback && typeof qrCallback === 'function') {
362
+ qrCallback('Mock QR Code Data');
363
+ }
364
+
365
+ rerender(
366
+ <QwenOAuthProgress
367
+ onTimeout={mockOnTimeout}
368
+ onCancel={mockOnCancel}
369
+ deviceAuth={mockDeviceAuth}
370
+ />,
371
+ );
372
+
373
+ const output = lastFrame();
374
+ expect(output).toContain('Or scan the QR code below:');
375
+ expect(output).toContain('Mock QR Code Data');
376
+ });
377
+
378
+ it('should handle QR code generation errors gracefully', async () => {
379
+ const qrcode = await import('qrcode-terminal');
380
+ const mockGenerate = vi.mocked(qrcode.default.generate);
381
+ const consoleErrorSpy = vi
382
+ .spyOn(console, 'error')
383
+ .mockImplementation(() => {});
384
+
385
+ mockGenerate.mockImplementation(() => {
386
+ throw new Error('QR Code generation failed');
387
+ });
388
+
389
+ const { lastFrame } = render(
390
+ <QwenOAuthProgress
391
+ onTimeout={mockOnTimeout}
392
+ onCancel={mockOnCancel}
393
+ deviceAuth={mockDeviceAuth}
394
+ />,
395
+ );
396
+
397
+ // Should not crash and should not show QR code section since QR generation failed
398
+ const output = lastFrame();
399
+ expect(output).not.toContain('Or scan the QR code below:');
400
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
401
+ 'Failed to generate QR code:',
402
+ expect.any(Error),
403
+ );
404
+
405
+ consoleErrorSpy.mockRestore();
406
+ });
407
+
408
+ it('should not generate QR code when deviceAuth is null', async () => {
409
+ const qrcode = await import('qrcode-terminal');
410
+ const mockGenerate = vi.mocked(qrcode.default.generate);
411
+
412
+ render(
413
+ <QwenOAuthProgress onTimeout={mockOnTimeout} onCancel={mockOnCancel} />,
414
+ );
415
+
416
+ expect(mockGenerate).not.toHaveBeenCalled();
417
+ });
418
+ });
419
+
420
+ describe('User interactions', () => {
421
+ it('should call onCancel when ESC key is pressed', () => {
422
+ const { stdin } = render(
423
+ <QwenOAuthProgress
424
+ onTimeout={mockOnTimeout}
425
+ onCancel={mockOnCancel}
426
+ deviceAuth={mockDeviceAuth}
427
+ />,
428
+ );
429
+
430
+ // Simulate ESC key press
431
+ stdin.write('\u001b'); // ESC character
432
+
433
+ expect(mockOnCancel).toHaveBeenCalledTimes(1);
434
+ });
435
+
436
+ it('should call onCancel when ESC is pressed in loading state', () => {
437
+ const { stdin } = render(
438
+ <QwenOAuthProgress onTimeout={mockOnTimeout} onCancel={mockOnCancel} />,
439
+ );
440
+
441
+ // Simulate ESC key press
442
+ stdin.write('\u001b'); // ESC character
443
+
444
+ expect(mockOnCancel).toHaveBeenCalledTimes(1);
445
+ });
446
+
447
+ it('should not call onCancel for other key presses', () => {
448
+ const { stdin } = render(
449
+ <QwenOAuthProgress
450
+ onTimeout={mockOnTimeout}
451
+ onCancel={mockOnCancel}
452
+ deviceAuth={mockDeviceAuth}
453
+ />,
454
+ );
455
+
456
+ // Simulate other key presses
457
+ stdin.write('a');
458
+ stdin.write('\r'); // Enter
459
+ stdin.write(' '); // Space
460
+
461
+ expect(mockOnCancel).not.toHaveBeenCalled();
462
+ });
463
+ });
464
+
465
+ describe('Props changes', () => {
466
+ it('should display initial timer value from deviceAuth', () => {
467
+ const deviceAuthWith10Min: DeviceAuthorizationInfo = {
468
+ ...mockDeviceAuth,
469
+ expires_in: 600, // 10 minutes
470
+ };
471
+
472
+ const { lastFrame } = render(
473
+ <QwenOAuthProgress
474
+ onTimeout={mockOnTimeout}
475
+ onCancel={mockOnCancel}
476
+ deviceAuth={deviceAuthWith10Min}
477
+ />,
478
+ );
479
+
480
+ expect(lastFrame()).toContain('Time remaining: 10:00');
481
+ });
482
+
483
+ it('should reset to loading state when deviceAuth becomes null', () => {
484
+ const { rerender, lastFrame } = render(
485
+ <QwenOAuthProgress
486
+ onTimeout={mockOnTimeout}
487
+ onCancel={mockOnCancel}
488
+ deviceAuth={mockDeviceAuth}
489
+ />,
490
+ );
491
+
492
+ // Initially shows waiting for authorization
493
+ expect(lastFrame()).toContain('Waiting for authorization');
494
+
495
+ rerender(
496
+ <QwenOAuthProgress onTimeout={mockOnTimeout} onCancel={mockOnCancel} />,
497
+ );
498
+
499
+ expect(lastFrame()).toContain('Waiting for Qwen OAuth authentication...');
500
+ expect(lastFrame()).not.toContain('Waiting for authorization');
501
+ });
502
+ });
503
+
504
+ describe('Timeout state', () => {
505
+ it('should render timeout state when authStatus is timeout', () => {
506
+ const { lastFrame } = renderComponent({
507
+ authStatus: 'timeout',
508
+ authMessage: 'Custom timeout message',
509
+ });
510
+
511
+ const output = lastFrame();
512
+ expect(output).toContain('Qwen OAuth Authentication Timeout');
513
+ expect(output).toContain('Custom timeout message');
514
+ expect(output).toContain(
515
+ 'Press any key to return to authentication type selection.',
516
+ );
517
+ });
518
+
519
+ it('should render default timeout message when no authMessage provided', () => {
520
+ const { lastFrame } = renderComponent({
521
+ authStatus: 'timeout',
522
+ });
523
+
524
+ const output = lastFrame();
525
+ expect(output).toContain('Qwen OAuth Authentication Timeout');
526
+ expect(output).toContain(
527
+ 'OAuth token expired (over 300 seconds). Please select authentication method again.',
528
+ );
529
+ });
530
+
531
+ it('should call onCancel for any key press in timeout state', () => {
532
+ const { stdin } = renderComponent({
533
+ authStatus: 'timeout',
534
+ });
535
+
536
+ // Simulate any key press
537
+ stdin.write('a');
538
+ expect(mockOnCancel).toHaveBeenCalledTimes(1);
539
+
540
+ // Reset mock and try enter key
541
+ mockOnCancel.mockClear();
542
+ stdin.write('\r');
543
+ expect(mockOnCancel).toHaveBeenCalledTimes(1);
544
+ });
545
+ });
546
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/QwenOAuthProgress.tsx ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React, { useState, useEffect, useMemo } from 'react';
8
+ import { Box, Text, useInput } from 'ink';
9
+ import Spinner from 'ink-spinner';
10
+ import Link from 'ink-link';
11
+ import qrcode from 'qrcode-terminal';
12
+ import { Colors } from '../colors.js';
13
+ import { DeviceAuthorizationInfo } from '../hooks/useQwenAuth.js';
14
+
15
+ interface QwenOAuthProgressProps {
16
+ onTimeout: () => void;
17
+ onCancel: () => void;
18
+ deviceAuth?: DeviceAuthorizationInfo;
19
+ authStatus?:
20
+ | 'idle'
21
+ | 'polling'
22
+ | 'success'
23
+ | 'error'
24
+ | 'timeout'
25
+ | 'rate_limit';
26
+ authMessage?: string | null;
27
+ }
28
+
29
+ /**
30
+ * Static QR Code Display Component
31
+ * Renders the QR code and URL once and doesn't re-render unless the URL changes
32
+ */
33
+ function QrCodeDisplay({
34
+ verificationUrl,
35
+ qrCodeData,
36
+ }: {
37
+ verificationUrl: string;
38
+ qrCodeData: string | null;
39
+ }): React.JSX.Element | null {
40
+ if (!qrCodeData) {
41
+ return null;
42
+ }
43
+
44
+ return (
45
+ <Box
46
+ borderStyle="round"
47
+ borderColor={Colors.AccentBlue}
48
+ flexDirection="column"
49
+ padding={1}
50
+ width="100%"
51
+ >
52
+ <Text bold color={Colors.AccentBlue}>
53
+ Qwen OAuth Authentication
54
+ </Text>
55
+
56
+ <Box marginTop={1}>
57
+ <Text>Please visit this URL to authorize:</Text>
58
+ </Box>
59
+
60
+ <Link url={verificationUrl} fallback={false}>
61
+ <Text color={Colors.AccentGreen} bold>
62
+ {verificationUrl}
63
+ </Text>
64
+ </Link>
65
+
66
+ <Box marginTop={1}>
67
+ <Text>Or scan the QR code below:</Text>
68
+ </Box>
69
+
70
+ <Box marginTop={1}>
71
+ <Text>{qrCodeData}</Text>
72
+ </Box>
73
+ </Box>
74
+ );
75
+ }
76
+
77
+ /**
78
+ * Dynamic Status Display Component
79
+ * Shows the loading spinner, timer, and status messages
80
+ */
81
+ function StatusDisplay({
82
+ timeRemaining,
83
+ dots,
84
+ }: {
85
+ timeRemaining: number;
86
+ dots: string;
87
+ }): React.JSX.Element {
88
+ const formatTime = (seconds: number): string => {
89
+ const minutes = Math.floor(seconds / 60);
90
+ const remainingSeconds = seconds % 60;
91
+ return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
92
+ };
93
+
94
+ return (
95
+ <Box
96
+ borderStyle="round"
97
+ borderColor={Colors.AccentBlue}
98
+ flexDirection="column"
99
+ padding={1}
100
+ width="100%"
101
+ >
102
+ <Box marginTop={1}>
103
+ <Text>
104
+ <Spinner type="dots" /> Waiting for authorization{dots}
105
+ </Text>
106
+ </Box>
107
+
108
+ <Box marginTop={1} justifyContent="space-between">
109
+ <Text color={Colors.Gray}>
110
+ Time remaining: {formatTime(timeRemaining)}
111
+ </Text>
112
+ <Text color={Colors.AccentPurple}>(Press ESC to cancel)</Text>
113
+ </Box>
114
+ </Box>
115
+ );
116
+ }
117
+
118
+ export function QwenOAuthProgress({
119
+ onTimeout,
120
+ onCancel,
121
+ deviceAuth,
122
+ authStatus,
123
+ authMessage,
124
+ }: QwenOAuthProgressProps): React.JSX.Element {
125
+ const defaultTimeout = deviceAuth?.expires_in || 300; // Default 5 minutes
126
+ const [timeRemaining, setTimeRemaining] = useState<number>(defaultTimeout);
127
+ const [dots, setDots] = useState<string>('');
128
+ const [qrCodeData, setQrCodeData] = useState<string | null>(null);
129
+
130
+ useInput((input, key) => {
131
+ if (authStatus === 'timeout') {
132
+ // Any key press in timeout state should trigger cancel to return to auth dialog
133
+ onCancel();
134
+ } else if (key.escape) {
135
+ onCancel();
136
+ }
137
+ });
138
+
139
+ // Generate QR code once when device auth is available
140
+ useEffect(() => {
141
+ if (!deviceAuth?.verification_uri_complete) {
142
+ return;
143
+ }
144
+
145
+ const generateQR = () => {
146
+ try {
147
+ qrcode.generate(
148
+ deviceAuth.verification_uri_complete,
149
+ { small: true },
150
+ (qrcode: string) => {
151
+ setQrCodeData(qrcode);
152
+ },
153
+ );
154
+ } catch (error) {
155
+ console.error('Failed to generate QR code:', error);
156
+ setQrCodeData(null);
157
+ }
158
+ };
159
+
160
+ generateQR();
161
+ }, [deviceAuth?.verification_uri_complete]);
162
+
163
+ // Countdown timer
164
+ useEffect(() => {
165
+ const timer = setInterval(() => {
166
+ setTimeRemaining((prev) => {
167
+ if (prev <= 1) {
168
+ onTimeout();
169
+ return 0;
170
+ }
171
+ return prev - 1;
172
+ });
173
+ }, 1000);
174
+
175
+ return () => clearInterval(timer);
176
+ }, [onTimeout]);
177
+
178
+ // Animated dots
179
+ useEffect(() => {
180
+ const dotsTimer = setInterval(() => {
181
+ setDots((prev) => {
182
+ if (prev.length >= 3) return '';
183
+ return prev + '.';
184
+ });
185
+ }, 500);
186
+
187
+ return () => clearInterval(dotsTimer);
188
+ }, []);
189
+
190
+ // Memoize the QR code display to prevent unnecessary re-renders
191
+ const qrCodeDisplay = useMemo(() => {
192
+ if (!deviceAuth?.verification_uri_complete) return null;
193
+
194
+ return (
195
+ <QrCodeDisplay
196
+ verificationUrl={deviceAuth.verification_uri_complete}
197
+ qrCodeData={qrCodeData}
198
+ />
199
+ );
200
+ }, [deviceAuth?.verification_uri_complete, qrCodeData]);
201
+
202
+ // Handle timeout state
203
+ if (authStatus === 'timeout') {
204
+ return (
205
+ <Box
206
+ borderStyle="round"
207
+ borderColor={Colors.AccentRed}
208
+ flexDirection="column"
209
+ padding={1}
210
+ width="100%"
211
+ >
212
+ <Text bold color={Colors.AccentRed}>
213
+ Qwen OAuth Authentication Timeout
214
+ </Text>
215
+
216
+ <Box marginTop={1}>
217
+ <Text>
218
+ {authMessage ||
219
+ `OAuth token expired (over ${defaultTimeout} seconds). Please select authentication method again.`}
220
+ </Text>
221
+ </Box>
222
+
223
+ <Box marginTop={1}>
224
+ <Text color={Colors.Gray}>
225
+ Press any key to return to authentication type selection.
226
+ </Text>
227
+ </Box>
228
+ </Box>
229
+ );
230
+ }
231
+
232
+ // Show loading state when no device auth is available yet
233
+ if (!deviceAuth) {
234
+ return (
235
+ <Box
236
+ borderStyle="round"
237
+ borderColor={Colors.Gray}
238
+ flexDirection="column"
239
+ padding={1}
240
+ width="100%"
241
+ >
242
+ <Box>
243
+ <Text>
244
+ <Spinner type="dots" /> Waiting for Qwen OAuth authentication...
245
+ </Text>
246
+ </Box>
247
+ <Box marginTop={1} justifyContent="space-between">
248
+ <Text color={Colors.Gray}>
249
+ Time remaining: {Math.floor(timeRemaining / 60)}:
250
+ {(timeRemaining % 60).toString().padStart(2, '0')}
251
+ </Text>
252
+ <Text color={Colors.AccentPurple}>(Press ESC to cancel)</Text>
253
+ </Box>
254
+ </Box>
255
+ );
256
+ }
257
+
258
+ return (
259
+ <Box flexDirection="column" width="100%">
260
+ {/* Static QR Code Display */}
261
+ {qrCodeDisplay}
262
+
263
+ {/* Dynamic Status Display */}
264
+ <StatusDisplay timeRemaining={timeRemaining} dots={dots} />
265
+ </Box>
266
+ );
267
+ }
projects/ui/qwen-code/packages/cli/src/ui/components/SessionSummaryDisplay.test.tsx ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { render } from 'ink-testing-library';
8
+ import { describe, it, expect, vi } from 'vitest';
9
+ import { SessionSummaryDisplay } from './SessionSummaryDisplay.js';
10
+ import * as SessionContext from '../contexts/SessionContext.js';
11
+ import { SessionMetrics } from '../contexts/SessionContext.js';
12
+
13
+ vi.mock('../contexts/SessionContext.js', async (importOriginal) => {
14
+ const actual = await importOriginal<typeof SessionContext>();
15
+ return {
16
+ ...actual,
17
+ useSessionStats: vi.fn(),
18
+ };
19
+ });
20
+
21
+ const useSessionStatsMock = vi.mocked(SessionContext.useSessionStats);
22
+
23
+ const renderWithMockedStats = (metrics: SessionMetrics) => {
24
+ useSessionStatsMock.mockReturnValue({
25
+ stats: {
26
+ sessionStartTime: new Date(),
27
+ metrics,
28
+ lastPromptTokenCount: 0,
29
+ promptCount: 5,
30
+ },
31
+
32
+ getPromptCount: () => 5,
33
+ startNewPrompt: vi.fn(),
34
+ });
35
+
36
+ return render(<SessionSummaryDisplay duration="1h 23m 45s" />);
37
+ };
38
+
39
+ describe('<SessionSummaryDisplay />', () => {
40
+ it('renders the summary display with a title', () => {
41
+ const metrics: SessionMetrics = {
42
+ models: {
43
+ 'gemini-2.5-pro': {
44
+ api: { totalRequests: 10, totalErrors: 1, totalLatencyMs: 50234 },
45
+ tokens: {
46
+ prompt: 1000,
47
+ candidates: 2000,
48
+ total: 3500,
49
+ cached: 500,
50
+ thoughts: 300,
51
+ tool: 200,
52
+ },
53
+ },
54
+ },
55
+ tools: {
56
+ totalCalls: 0,
57
+ totalSuccess: 0,
58
+ totalFail: 0,
59
+ totalDurationMs: 0,
60
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
61
+ byName: {},
62
+ },
63
+ files: {
64
+ totalLinesAdded: 42,
65
+ totalLinesRemoved: 15,
66
+ },
67
+ };
68
+
69
+ const { lastFrame } = renderWithMockedStats(metrics);
70
+ const output = lastFrame();
71
+
72
+ expect(output).toContain('Agent powering down. Goodbye!');
73
+ expect(output).toMatchSnapshot();
74
+ });
75
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/SessionSummaryDisplay.tsx ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { StatsDisplay } from './StatsDisplay.js';
9
+
10
+ interface SessionSummaryDisplayProps {
11
+ duration: string;
12
+ }
13
+
14
+ export const SessionSummaryDisplay: React.FC<SessionSummaryDisplayProps> = ({
15
+ duration,
16
+ }) => (
17
+ <StatsDisplay title="Agent powering down. Goodbye!" duration={duration} />
18
+ );
projects/ui/qwen-code/packages/cli/src/ui/components/SettingsDialog.test.tsx ADDED
@@ -0,0 +1,865 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ *
9
+ *
10
+ * This test suite covers:
11
+ * - Initial rendering and display state
12
+ * - Keyboard navigation (arrows, vim keys, Tab)
13
+ * - Settings toggling (Enter, Space)
14
+ * - Focus section switching between settings and scope selector
15
+ * - Scope selection and settings persistence across scopes
16
+ * - Restart-required vs immediate settings behavior
17
+ * - VimModeContext integration
18
+ * - Complex user interaction workflows
19
+ * - Error handling and edge cases
20
+ * - Display values for inherited and overridden settings
21
+ *
22
+ */
23
+
24
+ import { render } from 'ink-testing-library';
25
+ import { waitFor } from '@testing-library/react';
26
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
27
+ import { SettingsDialog } from './SettingsDialog.js';
28
+ import { LoadedSettings } from '../../config/settings.js';
29
+ import { VimModeProvider } from '../contexts/VimModeContext.js';
30
+
31
+ // Mock the VimModeContext
32
+ const mockToggleVimEnabled = vi.fn();
33
+ const mockSetVimMode = vi.fn();
34
+
35
+ vi.mock('../contexts/VimModeContext.js', async () => {
36
+ const actual = await vi.importActual('../contexts/VimModeContext.js');
37
+ return {
38
+ ...actual,
39
+ useVimMode: () => ({
40
+ vimEnabled: false,
41
+ vimMode: 'INSERT' as const,
42
+ toggleVimEnabled: mockToggleVimEnabled,
43
+ setVimMode: mockSetVimMode,
44
+ }),
45
+ };
46
+ });
47
+
48
+ vi.mock('../../utils/settingsUtils.js', async () => {
49
+ const actual = await vi.importActual('../../utils/settingsUtils.js');
50
+ return {
51
+ ...actual,
52
+ saveModifiedSettings: vi.fn(),
53
+ };
54
+ });
55
+
56
+ // Mock the useKeypress hook to avoid context issues
57
+ interface Key {
58
+ name: string;
59
+ ctrl: boolean;
60
+ meta: boolean;
61
+ shift: boolean;
62
+ paste: boolean;
63
+ sequence: string;
64
+ }
65
+
66
+ // Variables for keypress simulation (not currently used)
67
+ // let currentKeypressHandler: ((key: Key) => void) | null = null;
68
+ // let isKeypressActive = false;
69
+
70
+ vi.mock('../hooks/useKeypress.js', () => ({
71
+ useKeypress: vi.fn(
72
+ (_handler: (key: Key) => void, _options: { isActive: boolean }) => {
73
+ // Mock implementation - simplified for test stability
74
+ },
75
+ ),
76
+ }));
77
+
78
+ // Helper function to simulate key presses (commented out for now)
79
+ // const simulateKeyPress = async (keyData: Partial<Key> & { name: string }) => {
80
+ // if (currentKeypressHandler) {
81
+ // const key: Key = {
82
+ // ctrl: false,
83
+ // meta: false,
84
+ // shift: false,
85
+ // paste: false,
86
+ // sequence: keyData.sequence || keyData.name,
87
+ // ...keyData,
88
+ // };
89
+ // currentKeypressHandler(key);
90
+ // // Allow React to process the state update
91
+ // await new Promise(resolve => setTimeout(resolve, 10));
92
+ // }
93
+ // };
94
+
95
+ // Mock console.log to avoid noise in tests
96
+ // const originalConsoleLog = console.log;
97
+ // const originalConsoleError = console.error;
98
+
99
+ describe('SettingsDialog', () => {
100
+ const wait = (ms = 50) => new Promise((resolve) => setTimeout(resolve, ms));
101
+
102
+ beforeEach(() => {
103
+ vi.clearAllMocks();
104
+ // Reset keypress mock state (variables are commented out)
105
+ // currentKeypressHandler = null;
106
+ // isKeypressActive = false;
107
+ // console.log = vi.fn();
108
+ // console.error = vi.fn();
109
+ mockToggleVimEnabled.mockResolvedValue(true);
110
+ });
111
+
112
+ afterEach(() => {
113
+ // Reset keypress mock state (variables are commented out)
114
+ // currentKeypressHandler = null;
115
+ // isKeypressActive = false;
116
+ // console.log = originalConsoleLog;
117
+ // console.error = originalConsoleError;
118
+ });
119
+
120
+ const createMockSettings = (
121
+ userSettings = {},
122
+ systemSettings = {},
123
+ workspaceSettings = {},
124
+ ) =>
125
+ new LoadedSettings(
126
+ {
127
+ settings: { customThemes: {}, mcpServers: {}, ...systemSettings },
128
+ path: '/system/settings.json',
129
+ },
130
+ {
131
+ settings: {
132
+ customThemes: {},
133
+ mcpServers: {},
134
+ ...userSettings,
135
+ },
136
+ path: '/user/settings.json',
137
+ },
138
+ {
139
+ settings: { customThemes: {}, mcpServers: {}, ...workspaceSettings },
140
+ path: '/workspace/settings.json',
141
+ },
142
+ [],
143
+ );
144
+
145
+ describe('Initial Rendering', () => {
146
+ it('should render the settings dialog with default state', () => {
147
+ const settings = createMockSettings();
148
+ const onSelect = vi.fn();
149
+
150
+ const { lastFrame } = render(
151
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
152
+ );
153
+
154
+ const output = lastFrame();
155
+ expect(output).toContain('Settings');
156
+ expect(output).toContain('Apply To');
157
+ expect(output).toContain('Use Enter to select, Tab to change focus');
158
+ });
159
+
160
+ it('should show settings list with default values', () => {
161
+ const settings = createMockSettings();
162
+ const onSelect = vi.fn();
163
+
164
+ const { lastFrame } = render(
165
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
166
+ );
167
+
168
+ const output = lastFrame();
169
+ // Should show some default settings
170
+ expect(output).toContain('●'); // Active indicator
171
+ });
172
+
173
+ it('should highlight first setting by default', () => {
174
+ const settings = createMockSettings();
175
+ const onSelect = vi.fn();
176
+
177
+ const { lastFrame } = render(
178
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
179
+ );
180
+
181
+ const output = lastFrame();
182
+ // First item should be highlighted with green color and active indicator
183
+ expect(output).toContain('●');
184
+ });
185
+ });
186
+
187
+ describe('Settings Navigation', () => {
188
+ it('should navigate down with arrow key', async () => {
189
+ const settings = createMockSettings();
190
+ const onSelect = vi.fn();
191
+
192
+ const { stdin, unmount } = render(
193
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
194
+ );
195
+
196
+ // Press down arrow
197
+ stdin.write('\u001B[B'); // Down arrow
198
+ await wait();
199
+
200
+ // The active index should have changed (tested indirectly through behavior)
201
+ unmount();
202
+ });
203
+
204
+ it('should navigate up with arrow key', async () => {
205
+ const settings = createMockSettings();
206
+ const onSelect = vi.fn();
207
+
208
+ const { stdin, unmount } = render(
209
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
210
+ );
211
+
212
+ // First go down, then up
213
+ stdin.write('\u001B[B'); // Down arrow
214
+ await wait();
215
+ stdin.write('\u001B[A'); // Up arrow
216
+ await wait();
217
+
218
+ unmount();
219
+ });
220
+
221
+ it('should navigate with vim keys (j/k)', async () => {
222
+ const settings = createMockSettings();
223
+ const onSelect = vi.fn();
224
+
225
+ const { stdin, unmount } = render(
226
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
227
+ );
228
+
229
+ // Navigate with vim keys
230
+ stdin.write('j'); // Down
231
+ await wait();
232
+ stdin.write('k'); // Up
233
+ await wait();
234
+
235
+ unmount();
236
+ });
237
+
238
+ it('should not navigate beyond bounds', async () => {
239
+ const settings = createMockSettings();
240
+ const onSelect = vi.fn();
241
+
242
+ const { stdin, unmount } = render(
243
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
244
+ );
245
+
246
+ // Try to go up from first item
247
+ stdin.write('\u001B[A'); // Up arrow
248
+ await wait();
249
+
250
+ // Should still be on first item
251
+ unmount();
252
+ });
253
+ });
254
+
255
+ describe('Settings Toggling', () => {
256
+ it('should toggle setting with Enter key', async () => {
257
+ const settings = createMockSettings();
258
+ const onSelect = vi.fn();
259
+
260
+ const { stdin, unmount } = render(
261
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
262
+ );
263
+
264
+ // Press Enter to toggle current setting
265
+ stdin.write('\u000D'); // Enter key
266
+ await wait();
267
+
268
+ unmount();
269
+ });
270
+
271
+ it('should toggle setting with Space key', async () => {
272
+ const settings = createMockSettings();
273
+ const onSelect = vi.fn();
274
+
275
+ const { stdin, unmount } = render(
276
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
277
+ );
278
+
279
+ // Press Space to toggle current setting
280
+ stdin.write(' '); // Space key
281
+ await wait();
282
+
283
+ unmount();
284
+ });
285
+
286
+ it('should handle vim mode setting specially', async () => {
287
+ const settings = createMockSettings();
288
+ const onSelect = vi.fn();
289
+
290
+ const { stdin, unmount } = render(
291
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
292
+ );
293
+
294
+ // Navigate to vim mode setting and toggle it
295
+ // This would require knowing the exact position, so we'll just test that the mock is called
296
+ stdin.write('\u000D'); // Enter key
297
+ await wait();
298
+
299
+ // The mock should potentially be called if vim mode was toggled
300
+ unmount();
301
+ });
302
+ });
303
+
304
+ describe('Scope Selection', () => {
305
+ it('should switch between scopes', async () => {
306
+ const settings = createMockSettings();
307
+ const onSelect = vi.fn();
308
+
309
+ const { stdin, unmount } = render(
310
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
311
+ );
312
+
313
+ // Switch to scope focus
314
+ stdin.write('\t'); // Tab key
315
+ await wait();
316
+
317
+ // Select different scope (numbers 1-3 typically available)
318
+ stdin.write('2'); // Select second scope option
319
+ await wait();
320
+
321
+ unmount();
322
+ });
323
+
324
+ it('should reset to settings focus when scope is selected', async () => {
325
+ const settings = createMockSettings();
326
+ const onSelect = vi.fn();
327
+
328
+ const { lastFrame, unmount } = render(
329
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
330
+ );
331
+
332
+ // Wait for initial render
333
+ await waitFor(() => {
334
+ expect(lastFrame()).toContain('Hide Window Title');
335
+ });
336
+
337
+ // The UI should show the settings section is active and scope section is inactive
338
+ expect(lastFrame()).toContain('● Hide Window Title'); // Settings section active
339
+ expect(lastFrame()).toContain(' Apply To'); // Scope section inactive
340
+
341
+ // This test validates the initial state - scope selection behavior
342
+ // is complex due to keypress handling, so we focus on state validation
343
+
344
+ unmount();
345
+ });
346
+ });
347
+
348
+ describe('Restart Prompt', () => {
349
+ it('should show restart prompt for restart-required settings', async () => {
350
+ const settings = createMockSettings();
351
+ const onRestartRequest = vi.fn();
352
+
353
+ const { unmount } = render(
354
+ <SettingsDialog
355
+ settings={settings}
356
+ onSelect={() => {}}
357
+ onRestartRequest={onRestartRequest}
358
+ />,
359
+ );
360
+
361
+ // This test would need to trigger a restart-required setting change
362
+ // The exact steps depend on which settings require restart
363
+ await wait();
364
+
365
+ unmount();
366
+ });
367
+
368
+ it('should handle restart request when r is pressed', async () => {
369
+ const settings = createMockSettings();
370
+ const onRestartRequest = vi.fn();
371
+
372
+ const { stdin, unmount } = render(
373
+ <SettingsDialog
374
+ settings={settings}
375
+ onSelect={() => {}}
376
+ onRestartRequest={onRestartRequest}
377
+ />,
378
+ );
379
+
380
+ // Press 'r' key (this would only work if restart prompt is showing)
381
+ stdin.write('r');
382
+ await wait();
383
+
384
+ // If restart prompt was showing, onRestartRequest should be called
385
+ unmount();
386
+ });
387
+ });
388
+
389
+ describe('Escape Key Behavior', () => {
390
+ it('should call onSelect with undefined when Escape is pressed', async () => {
391
+ const settings = createMockSettings();
392
+ const onSelect = vi.fn();
393
+
394
+ const { lastFrame, unmount } = render(
395
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
396
+ );
397
+
398
+ // Wait for initial render
399
+ await waitFor(() => {
400
+ expect(lastFrame()).toContain('Hide Window Title');
401
+ });
402
+
403
+ // Verify the dialog is rendered properly
404
+ expect(lastFrame()).toContain('Settings');
405
+ expect(lastFrame()).toContain('Apply To');
406
+
407
+ // This test validates rendering - escape key behavior depends on complex
408
+ // keypress handling that's difficult to test reliably in this environment
409
+
410
+ unmount();
411
+ });
412
+ });
413
+
414
+ describe('Settings Persistence', () => {
415
+ it('should persist settings across scope changes', async () => {
416
+ const settings = createMockSettings({ vimMode: true });
417
+ const onSelect = vi.fn();
418
+
419
+ const { stdin, unmount } = render(
420
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
421
+ );
422
+
423
+ // Switch to scope selector
424
+ stdin.write('\t'); // Tab
425
+ await wait();
426
+
427
+ // Change scope
428
+ stdin.write('2'); // Select workspace scope
429
+ await wait();
430
+
431
+ // Settings should be reloaded for new scope
432
+ unmount();
433
+ });
434
+
435
+ it('should show different values for different scopes', () => {
436
+ const settings = createMockSettings(
437
+ { vimMode: true }, // User settings
438
+ { vimMode: false }, // System settings
439
+ { autoUpdate: false }, // Workspace settings
440
+ );
441
+ const onSelect = vi.fn();
442
+
443
+ const { lastFrame } = render(
444
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
445
+ );
446
+
447
+ // Should show user scope values initially
448
+ const output = lastFrame();
449
+ expect(output).toContain('Settings');
450
+ });
451
+ });
452
+
453
+ describe('Error Handling', () => {
454
+ it('should handle vim mode toggle errors gracefully', async () => {
455
+ mockToggleVimEnabled.mockRejectedValue(new Error('Toggle failed'));
456
+
457
+ const settings = createMockSettings();
458
+ const onSelect = vi.fn();
459
+
460
+ const { stdin, unmount } = render(
461
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
462
+ );
463
+
464
+ // Try to toggle a setting (this might trigger vim mode toggle)
465
+ stdin.write('\u000D'); // Enter
466
+ await wait();
467
+
468
+ // Should not crash
469
+ unmount();
470
+ });
471
+ });
472
+
473
+ describe('Complex State Management', () => {
474
+ it('should track modified settings correctly', async () => {
475
+ const settings = createMockSettings();
476
+ const onSelect = vi.fn();
477
+
478
+ const { stdin, unmount } = render(
479
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
480
+ );
481
+
482
+ // Toggle a setting
483
+ stdin.write('\u000D'); // Enter
484
+ await wait();
485
+
486
+ // Toggle another setting
487
+ stdin.write('\u001B[B'); // Down
488
+ await wait();
489
+ stdin.write('\u000D'); // Enter
490
+ await wait();
491
+
492
+ // Should track multiple modified settings
493
+ unmount();
494
+ });
495
+
496
+ it('should handle scrolling when there are many settings', async () => {
497
+ const settings = createMockSettings();
498
+ const onSelect = vi.fn();
499
+
500
+ const { stdin, unmount } = render(
501
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
502
+ );
503
+
504
+ // Navigate down many times to test scrolling
505
+ for (let i = 0; i < 10; i++) {
506
+ stdin.write('\u001B[B'); // Down arrow
507
+ await wait(10);
508
+ }
509
+
510
+ unmount();
511
+ });
512
+ });
513
+
514
+ describe('VimMode Integration', () => {
515
+ it('should sync with VimModeContext when vim mode is toggled', async () => {
516
+ const settings = createMockSettings();
517
+ const onSelect = vi.fn();
518
+
519
+ const { stdin, unmount } = render(
520
+ <VimModeProvider settings={settings}>
521
+ <SettingsDialog settings={settings} onSelect={onSelect} />
522
+ </VimModeProvider>,
523
+ );
524
+
525
+ // Navigate to and toggle vim mode setting
526
+ // This would require knowing the exact position of vim mode setting
527
+ stdin.write('\u000D'); // Enter
528
+ await wait();
529
+
530
+ unmount();
531
+ });
532
+ });
533
+
534
+ describe('Specific Settings Behavior', () => {
535
+ it('should show correct display values for settings with different states', () => {
536
+ const settings = createMockSettings(
537
+ { vimMode: true, hideTips: false }, // User settings
538
+ { hideWindowTitle: true }, // System settings
539
+ { ideMode: false }, // Workspace settings
540
+ );
541
+ const onSelect = vi.fn();
542
+
543
+ const { lastFrame } = render(
544
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
545
+ );
546
+
547
+ const output = lastFrame();
548
+ // Should contain settings labels
549
+ expect(output).toContain('Settings');
550
+ });
551
+
552
+ it('should handle immediate settings save for non-restart-required settings', async () => {
553
+ const settings = createMockSettings();
554
+ const onSelect = vi.fn();
555
+
556
+ const { stdin, unmount } = render(
557
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
558
+ );
559
+
560
+ // Toggle a non-restart-required setting (like hideTips)
561
+ stdin.write('\u000D'); // Enter - toggle current setting
562
+ await wait();
563
+
564
+ // Should save immediately without showing restart prompt
565
+ unmount();
566
+ });
567
+
568
+ it('should show restart prompt for restart-required settings', async () => {
569
+ const settings = createMockSettings();
570
+ const onSelect = vi.fn();
571
+
572
+ const { lastFrame, unmount } = render(
573
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
574
+ );
575
+
576
+ // This test would need to navigate to a specific restart-required setting
577
+ // Since we can't easily target specific settings, we test the general behavior
578
+ await wait();
579
+
580
+ // Should not show restart prompt initially
581
+ expect(lastFrame()).not.toContain(
582
+ 'To see changes, Gemini CLI must be restarted',
583
+ );
584
+
585
+ unmount();
586
+ });
587
+
588
+ it('should clear restart prompt when switching scopes', async () => {
589
+ const settings = createMockSettings();
590
+ const onSelect = vi.fn();
591
+
592
+ const { unmount } = render(
593
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
594
+ );
595
+
596
+ // Restart prompt should be cleared when switching scopes
597
+ unmount();
598
+ });
599
+ });
600
+
601
+ describe('Settings Display Values', () => {
602
+ it('should show correct values for inherited settings', () => {
603
+ const settings = createMockSettings(
604
+ {},
605
+ { vimMode: true, hideWindowTitle: false }, // System settings
606
+ {},
607
+ );
608
+ const onSelect = vi.fn();
609
+
610
+ const { lastFrame } = render(
611
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
612
+ );
613
+
614
+ const output = lastFrame();
615
+ // Settings should show inherited values
616
+ expect(output).toContain('Settings');
617
+ });
618
+
619
+ it('should show override indicator for overridden settings', () => {
620
+ const settings = createMockSettings(
621
+ { vimMode: false }, // User overrides
622
+ { vimMode: true }, // System default
623
+ {},
624
+ );
625
+ const onSelect = vi.fn();
626
+
627
+ const { lastFrame } = render(
628
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
629
+ );
630
+
631
+ const output = lastFrame();
632
+ // Should show settings with override indicators
633
+ expect(output).toContain('Settings');
634
+ });
635
+ });
636
+
637
+ describe('Keyboard Shortcuts Edge Cases', () => {
638
+ it('should handle rapid key presses gracefully', async () => {
639
+ const settings = createMockSettings();
640
+ const onSelect = vi.fn();
641
+
642
+ const { stdin, unmount } = render(
643
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
644
+ );
645
+
646
+ // Rapid navigation
647
+ for (let i = 0; i < 5; i++) {
648
+ stdin.write('\u001B[B'); // Down arrow
649
+ stdin.write('\u001B[A'); // Up arrow
650
+ }
651
+ await wait(100);
652
+
653
+ // Should not crash
654
+ unmount();
655
+ });
656
+
657
+ it('should handle Ctrl+C to reset current setting to default', async () => {
658
+ const settings = createMockSettings({ vimMode: true }); // Start with vimMode enabled
659
+ const onSelect = vi.fn();
660
+
661
+ const { stdin, unmount } = render(
662
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
663
+ );
664
+
665
+ // Press Ctrl+C to reset current setting to default
666
+ stdin.write('\u0003'); // Ctrl+C
667
+ await wait();
668
+
669
+ // Should reset the current setting to its default value
670
+ unmount();
671
+ });
672
+
673
+ it('should handle Ctrl+L to reset current setting to default', async () => {
674
+ const settings = createMockSettings({ vimMode: true }); // Start with vimMode enabled
675
+ const onSelect = vi.fn();
676
+
677
+ const { stdin, unmount } = render(
678
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
679
+ );
680
+
681
+ // Press Ctrl+L to reset current setting to default
682
+ stdin.write('\u000C'); // Ctrl+L
683
+ await wait();
684
+
685
+ // Should reset the current setting to its default value
686
+ unmount();
687
+ });
688
+
689
+ it('should handle navigation when only one setting exists', async () => {
690
+ const settings = createMockSettings();
691
+ const onSelect = vi.fn();
692
+
693
+ const { stdin, unmount } = render(
694
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
695
+ );
696
+
697
+ // Try to navigate when potentially at bounds
698
+ stdin.write('\u001B[B'); // Down
699
+ await wait();
700
+ stdin.write('\u001B[A'); // Up
701
+ await wait();
702
+
703
+ unmount();
704
+ });
705
+
706
+ it('should properly handle Tab navigation between sections', async () => {
707
+ const settings = createMockSettings();
708
+ const onSelect = vi.fn();
709
+
710
+ const { lastFrame, unmount } = render(
711
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
712
+ );
713
+
714
+ // Wait for initial render
715
+ await waitFor(() => {
716
+ expect(lastFrame()).toContain('Hide Window Title');
717
+ });
718
+
719
+ // Verify initial state: settings section active, scope section inactive
720
+ expect(lastFrame()).toContain('● Hide Window Title'); // Settings section active
721
+ expect(lastFrame()).toContain(' Apply To'); // Scope section inactive
722
+
723
+ // This test validates the rendered UI structure for tab navigation
724
+ // Actual tab behavior testing is complex due to keypress handling
725
+
726
+ unmount();
727
+ });
728
+ });
729
+
730
+ describe('Error Recovery', () => {
731
+ it('should handle malformed settings gracefully', () => {
732
+ // Create settings with potentially problematic values
733
+ const settings = createMockSettings(
734
+ { vimMode: null as unknown as boolean }, // Invalid value
735
+ {},
736
+ {},
737
+ );
738
+ const onSelect = vi.fn();
739
+
740
+ const { lastFrame } = render(
741
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
742
+ );
743
+
744
+ // Should still render without crashing
745
+ expect(lastFrame()).toContain('Settings');
746
+ });
747
+
748
+ it('should handle missing setting definitions gracefully', () => {
749
+ const settings = createMockSettings();
750
+ const onSelect = vi.fn();
751
+
752
+ // Should not crash even if some settings are missing definitions
753
+ const { lastFrame } = render(
754
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
755
+ );
756
+
757
+ expect(lastFrame()).toContain('Settings');
758
+ });
759
+ });
760
+
761
+ describe('Complex User Interactions', () => {
762
+ it('should handle complete user workflow: navigate, toggle, change scope, exit', async () => {
763
+ const settings = createMockSettings();
764
+ const onSelect = vi.fn();
765
+
766
+ const { lastFrame, unmount } = render(
767
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
768
+ );
769
+
770
+ // Wait for initial render
771
+ await waitFor(() => {
772
+ expect(lastFrame()).toContain('Hide Window Title');
773
+ });
774
+
775
+ // Verify the complete UI is rendered with all necessary sections
776
+ expect(lastFrame()).toContain('Settings'); // Title
777
+ expect(lastFrame()).toContain('● Hide Window Title'); // Active setting
778
+ expect(lastFrame()).toContain('Apply To'); // Scope section
779
+ expect(lastFrame()).toContain('1. User Settings'); // Scope options
780
+ expect(lastFrame()).toContain(
781
+ '(Use Enter to select, Tab to change focus)',
782
+ ); // Help text
783
+
784
+ // This test validates the complete UI structure is available for user workflow
785
+ // Individual interactions are tested in focused unit tests
786
+
787
+ unmount();
788
+ });
789
+
790
+ it('should allow changing multiple settings without losing pending changes', async () => {
791
+ const settings = createMockSettings();
792
+ const onSelect = vi.fn();
793
+
794
+ const { stdin, unmount } = render(
795
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
796
+ );
797
+
798
+ // Toggle first setting (should require restart)
799
+ stdin.write('\u000D'); // Enter
800
+ await wait();
801
+
802
+ // Navigate to next setting and toggle it (should not require restart - e.g., vimMode)
803
+ stdin.write('\u001B[B'); // Down
804
+ await wait();
805
+ stdin.write('\u000D'); // Enter
806
+ await wait();
807
+
808
+ // Navigate to another setting and toggle it (should also require restart)
809
+ stdin.write('\u001B[B'); // Down
810
+ await wait();
811
+ stdin.write('\u000D'); // Enter
812
+ await wait();
813
+
814
+ // The test verifies that all changes are preserved and the dialog still works
815
+ // This tests the fix for the bug where changing one setting would reset all pending changes
816
+ unmount();
817
+ });
818
+
819
+ it('should maintain state consistency during complex interactions', async () => {
820
+ const settings = createMockSettings({ vimMode: true });
821
+ const onSelect = vi.fn();
822
+
823
+ const { stdin, unmount } = render(
824
+ <SettingsDialog settings={settings} onSelect={onSelect} />,
825
+ );
826
+
827
+ // Multiple scope changes
828
+ stdin.write('\t'); // Tab to scope
829
+ await wait();
830
+ stdin.write('2'); // Workspace
831
+ await wait();
832
+ stdin.write('\t'); // Tab to settings
833
+ await wait();
834
+ stdin.write('\t'); // Tab to scope
835
+ await wait();
836
+ stdin.write('1'); // User
837
+ await wait();
838
+
839
+ // Should maintain consistent state
840
+ unmount();
841
+ });
842
+
843
+ it('should handle restart workflow correctly', async () => {
844
+ const settings = createMockSettings();
845
+ const onRestartRequest = vi.fn();
846
+
847
+ const { stdin, unmount } = render(
848
+ <SettingsDialog
849
+ settings={settings}
850
+ onSelect={() => {}}
851
+ onRestartRequest={onRestartRequest}
852
+ />,
853
+ );
854
+
855
+ // This would test the restart workflow if we could trigger it
856
+ stdin.write('r'); // Try restart key
857
+ await wait();
858
+
859
+ // Without restart prompt showing, this should have no effect
860
+ expect(onRestartRequest).not.toHaveBeenCalled();
861
+
862
+ unmount();
863
+ });
864
+ });
865
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/SettingsDialog.tsx ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React, { useState, useEffect } from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import {
11
+ LoadedSettings,
12
+ SettingScope,
13
+ Settings,
14
+ } from '../../config/settings.js';
15
+ import {
16
+ getScopeItems,
17
+ getScopeMessageForSetting,
18
+ } from '../../utils/dialogScopeUtils.js';
19
+ import { RadioButtonSelect } from './shared/RadioButtonSelect.js';
20
+ import {
21
+ getDialogSettingKeys,
22
+ getSettingValue,
23
+ setPendingSettingValue,
24
+ getDisplayValue,
25
+ hasRestartRequiredSettings,
26
+ saveModifiedSettings,
27
+ getSettingDefinition,
28
+ isDefaultValue,
29
+ requiresRestart,
30
+ getRestartRequiredFromModified,
31
+ getDefaultValue,
32
+ setPendingSettingValueAny,
33
+ getNestedValue,
34
+ } from '../../utils/settingsUtils.js';
35
+ import { useVimMode } from '../contexts/VimModeContext.js';
36
+ import { useKeypress } from '../hooks/useKeypress.js';
37
+ import chalk from 'chalk';
38
+ import { cpSlice, cpLen } from '../utils/textUtils.js';
39
+
40
+ interface SettingsDialogProps {
41
+ settings: LoadedSettings;
42
+ onSelect: (settingName: string | undefined, scope: SettingScope) => void;
43
+ onRestartRequest?: () => void;
44
+ }
45
+
46
+ const maxItemsToShow = 8;
47
+
48
+ export function SettingsDialog({
49
+ settings,
50
+ onSelect,
51
+ onRestartRequest,
52
+ }: SettingsDialogProps): React.JSX.Element {
53
+ // Get vim mode context to sync vim mode changes
54
+ const { vimEnabled, toggleVimEnabled } = useVimMode();
55
+
56
+ // Focus state: 'settings' or 'scope'
57
+ const [focusSection, setFocusSection] = useState<'settings' | 'scope'>(
58
+ 'settings',
59
+ );
60
+ // Scope selector state (User by default)
61
+ const [selectedScope, setSelectedScope] = useState<SettingScope>(
62
+ SettingScope.User,
63
+ );
64
+ // Active indices
65
+ const [activeSettingIndex, setActiveSettingIndex] = useState(0);
66
+ // Scroll offset for settings
67
+ const [scrollOffset, setScrollOffset] = useState(0);
68
+ const [showRestartPrompt, setShowRestartPrompt] = useState(false);
69
+
70
+ // Local pending settings state for the selected scope
71
+ const [pendingSettings, setPendingSettings] = useState<Settings>(() =>
72
+ // Deep clone to avoid mutation
73
+ structuredClone(settings.forScope(selectedScope).settings),
74
+ );
75
+
76
+ // Track which settings have been modified by the user
77
+ const [modifiedSettings, setModifiedSettings] = useState<Set<string>>(
78
+ new Set(),
79
+ );
80
+
81
+ // Preserve pending changes across scope switches (boolean and number values only)
82
+ type PendingValue = boolean | number;
83
+ const [globalPendingChanges, setGlobalPendingChanges] = useState<
84
+ Map<string, PendingValue>
85
+ >(new Map());
86
+
87
+ // Track restart-required settings across scope changes
88
+ const [_restartRequiredSettings, setRestartRequiredSettings] = useState<
89
+ Set<string>
90
+ >(new Set());
91
+
92
+ useEffect(() => {
93
+ // Base settings for selected scope
94
+ let updated = structuredClone(settings.forScope(selectedScope).settings);
95
+ // Overlay globally pending (unsaved) changes so user sees their modifications in any scope
96
+ const newModified = new Set<string>();
97
+ const newRestartRequired = new Set<string>();
98
+ for (const [key, value] of globalPendingChanges.entries()) {
99
+ const def = getSettingDefinition(key);
100
+ if (def?.type === 'boolean' && typeof value === 'boolean') {
101
+ updated = setPendingSettingValue(key, value, updated);
102
+ } else if (def?.type === 'number' && typeof value === 'number') {
103
+ updated = setPendingSettingValueAny(key, value, updated);
104
+ }
105
+ newModified.add(key);
106
+ if (requiresRestart(key)) newRestartRequired.add(key);
107
+ }
108
+ setPendingSettings(updated);
109
+ setModifiedSettings(newModified);
110
+ setRestartRequiredSettings(newRestartRequired);
111
+ setShowRestartPrompt(newRestartRequired.size > 0);
112
+ }, [selectedScope, settings, globalPendingChanges]);
113
+
114
+ const generateSettingsItems = () => {
115
+ const settingKeys = getDialogSettingKeys();
116
+
117
+ return settingKeys.map((key: string) => {
118
+ const definition = getSettingDefinition(key);
119
+
120
+ return {
121
+ label: definition?.label || key,
122
+ value: key,
123
+ type: definition?.type,
124
+ toggle: () => {
125
+ if (definition?.type !== 'boolean') {
126
+ // For non-boolean (e.g., number) items, toggle will be handled via edit mode.
127
+ return;
128
+ }
129
+ const currentValue = getSettingValue(key, pendingSettings, {});
130
+ const newValue = !currentValue;
131
+
132
+ setPendingSettings((prev) =>
133
+ setPendingSettingValue(key, newValue, prev),
134
+ );
135
+
136
+ if (!requiresRestart(key)) {
137
+ const immediateSettings = new Set([key]);
138
+ const immediateSettingsObject = setPendingSettingValueAny(
139
+ key,
140
+ newValue,
141
+ {} as Settings,
142
+ );
143
+
144
+ console.log(
145
+ `[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
146
+ newValue,
147
+ );
148
+ saveModifiedSettings(
149
+ immediateSettings,
150
+ immediateSettingsObject,
151
+ settings,
152
+ selectedScope,
153
+ );
154
+
155
+ // Special handling for vim mode to sync with VimModeContext
156
+ if (key === 'vimMode' && newValue !== vimEnabled) {
157
+ // Call toggleVimEnabled to sync the VimModeContext local state
158
+ toggleVimEnabled().catch((error) => {
159
+ console.error('Failed to toggle vim mode:', error);
160
+ });
161
+ }
162
+
163
+ // Remove from modifiedSettings since it's now saved
164
+ setModifiedSettings((prev) => {
165
+ const updated = new Set(prev);
166
+ updated.delete(key);
167
+ return updated;
168
+ });
169
+
170
+ // Also remove from restart-required settings if it was there
171
+ setRestartRequiredSettings((prev) => {
172
+ const updated = new Set(prev);
173
+ updated.delete(key);
174
+ return updated;
175
+ });
176
+
177
+ // Remove from global pending changes if present
178
+ setGlobalPendingChanges((prev) => {
179
+ if (!prev.has(key)) return prev;
180
+ const next = new Map(prev);
181
+ next.delete(key);
182
+ return next;
183
+ });
184
+
185
+ // Refresh pending settings from the saved state
186
+ setPendingSettings(
187
+ structuredClone(settings.forScope(selectedScope).settings),
188
+ );
189
+ } else {
190
+ // For restart-required settings, track as modified
191
+ setModifiedSettings((prev) => {
192
+ const updated = new Set(prev).add(key);
193
+ const needsRestart = hasRestartRequiredSettings(updated);
194
+ console.log(
195
+ `[DEBUG SettingsDialog] Modified settings:`,
196
+ Array.from(updated),
197
+ 'Needs restart:',
198
+ needsRestart,
199
+ );
200
+ if (needsRestart) {
201
+ setShowRestartPrompt(true);
202
+ setRestartRequiredSettings((prevRestart) =>
203
+ new Set(prevRestart).add(key),
204
+ );
205
+ }
206
+ return updated;
207
+ });
208
+
209
+ // Add/update pending change globally so it persists across scopes
210
+ setGlobalPendingChanges((prev) => {
211
+ const next = new Map(prev);
212
+ next.set(key, newValue as PendingValue);
213
+ return next;
214
+ });
215
+ }
216
+ },
217
+ };
218
+ });
219
+ };
220
+
221
+ const items = generateSettingsItems();
222
+
223
+ // Number edit state
224
+ const [editingKey, setEditingKey] = useState<string | null>(null);
225
+ const [editBuffer, setEditBuffer] = useState<string>('');
226
+ const [editCursorPos, setEditCursorPos] = useState<number>(0); // Cursor position within edit buffer
227
+ const [cursorVisible, setCursorVisible] = useState<boolean>(true);
228
+
229
+ useEffect(() => {
230
+ if (!editingKey) {
231
+ setCursorVisible(true);
232
+ return;
233
+ }
234
+ const id = setInterval(() => setCursorVisible((v) => !v), 500);
235
+ return () => clearInterval(id);
236
+ }, [editingKey]);
237
+
238
+ const startEditingNumber = (key: string, initial?: string) => {
239
+ setEditingKey(key);
240
+ const initialValue = initial ?? '';
241
+ setEditBuffer(initialValue);
242
+ setEditCursorPos(cpLen(initialValue)); // Position cursor at end of initial value
243
+ };
244
+
245
+ const commitNumberEdit = (key: string) => {
246
+ if (editBuffer.trim() === '') {
247
+ // Nothing entered; cancel edit
248
+ setEditingKey(null);
249
+ setEditBuffer('');
250
+ setEditCursorPos(0);
251
+ return;
252
+ }
253
+ const parsed = Number(editBuffer.trim());
254
+ if (Number.isNaN(parsed)) {
255
+ // Invalid number; cancel edit
256
+ setEditingKey(null);
257
+ setEditBuffer('');
258
+ setEditCursorPos(0);
259
+ return;
260
+ }
261
+
262
+ // Update pending
263
+ setPendingSettings((prev) => setPendingSettingValueAny(key, parsed, prev));
264
+
265
+ if (!requiresRestart(key)) {
266
+ const immediateSettings = new Set([key]);
267
+ const immediateSettingsObject = setPendingSettingValueAny(
268
+ key,
269
+ parsed,
270
+ {} as Settings,
271
+ );
272
+ saveModifiedSettings(
273
+ immediateSettings,
274
+ immediateSettingsObject,
275
+ settings,
276
+ selectedScope,
277
+ );
278
+
279
+ // Remove from modified sets if present
280
+ setModifiedSettings((prev) => {
281
+ const updated = new Set(prev);
282
+ updated.delete(key);
283
+ return updated;
284
+ });
285
+ setRestartRequiredSettings((prev) => {
286
+ const updated = new Set(prev);
287
+ updated.delete(key);
288
+ return updated;
289
+ });
290
+
291
+ // Remove from global pending since it's immediately saved
292
+ setGlobalPendingChanges((prev) => {
293
+ if (!prev.has(key)) return prev;
294
+ const next = new Map(prev);
295
+ next.delete(key);
296
+ return next;
297
+ });
298
+ } else {
299
+ // Mark as modified and needing restart
300
+ setModifiedSettings((prev) => {
301
+ const updated = new Set(prev).add(key);
302
+ const needsRestart = hasRestartRequiredSettings(updated);
303
+ if (needsRestart) {
304
+ setShowRestartPrompt(true);
305
+ setRestartRequiredSettings((prevRestart) =>
306
+ new Set(prevRestart).add(key),
307
+ );
308
+ }
309
+ return updated;
310
+ });
311
+
312
+ // Record pending change globally for persistence across scopes
313
+ setGlobalPendingChanges((prev) => {
314
+ const next = new Map(prev);
315
+ next.set(key, parsed as PendingValue);
316
+ return next;
317
+ });
318
+ }
319
+
320
+ setEditingKey(null);
321
+ setEditBuffer('');
322
+ setEditCursorPos(0);
323
+ };
324
+
325
+ // Scope selector items
326
+ const scopeItems = getScopeItems();
327
+
328
+ const handleScopeHighlight = (scope: SettingScope) => {
329
+ setSelectedScope(scope);
330
+ };
331
+
332
+ const handleScopeSelect = (scope: SettingScope) => {
333
+ handleScopeHighlight(scope);
334
+ setFocusSection('settings');
335
+ };
336
+
337
+ // Scroll logic for settings
338
+ const visibleItems = items.slice(scrollOffset, scrollOffset + maxItemsToShow);
339
+ // Always show arrows for consistent UI and to indicate circular navigation
340
+ const showScrollUp = true;
341
+ const showScrollDown = true;
342
+
343
+ useKeypress(
344
+ (key) => {
345
+ const { name, ctrl } = key;
346
+ if (name === 'tab') {
347
+ setFocusSection((prev) => (prev === 'settings' ? 'scope' : 'settings'));
348
+ }
349
+ if (focusSection === 'settings') {
350
+ // If editing a number, capture numeric input and control keys
351
+ if (editingKey) {
352
+ if (key.paste && key.sequence) {
353
+ const pasted = key.sequence.replace(/[^0-9\-+.]/g, '');
354
+ if (pasted) {
355
+ setEditBuffer((b) => {
356
+ const before = cpSlice(b, 0, editCursorPos);
357
+ const after = cpSlice(b, editCursorPos);
358
+ return before + pasted + after;
359
+ });
360
+ setEditCursorPos((pos) => pos + cpLen(pasted));
361
+ }
362
+ return;
363
+ }
364
+ if (name === 'backspace' || name === 'delete') {
365
+ if (name === 'backspace' && editCursorPos > 0) {
366
+ setEditBuffer((b) => {
367
+ const before = cpSlice(b, 0, editCursorPos - 1);
368
+ const after = cpSlice(b, editCursorPos);
369
+ return before + after;
370
+ });
371
+ setEditCursorPos((pos) => pos - 1);
372
+ } else if (name === 'delete' && editCursorPos < cpLen(editBuffer)) {
373
+ setEditBuffer((b) => {
374
+ const before = cpSlice(b, 0, editCursorPos);
375
+ const after = cpSlice(b, editCursorPos + 1);
376
+ return before + after;
377
+ });
378
+ // Cursor position stays the same for delete
379
+ }
380
+ return;
381
+ }
382
+ if (name === 'escape') {
383
+ commitNumberEdit(editingKey);
384
+ return;
385
+ }
386
+ if (name === 'return') {
387
+ commitNumberEdit(editingKey);
388
+ return;
389
+ }
390
+ // Allow digits, minus, plus, and dot
391
+ const ch = key.sequence;
392
+ if (/[0-9\-+.]/.test(ch)) {
393
+ setEditBuffer((currentBuffer) => {
394
+ const beforeCursor = cpSlice(currentBuffer, 0, editCursorPos);
395
+ const afterCursor = cpSlice(currentBuffer, editCursorPos);
396
+ return beforeCursor + ch + afterCursor;
397
+ });
398
+ setEditCursorPos((pos) => pos + 1);
399
+ return;
400
+ }
401
+ // Arrow key navigation
402
+ if (name === 'left') {
403
+ setEditCursorPos((pos) => Math.max(0, pos - 1));
404
+ return;
405
+ }
406
+ if (name === 'right') {
407
+ setEditCursorPos((pos) => Math.min(cpLen(editBuffer), pos + 1));
408
+ return;
409
+ }
410
+ // Home and End keys
411
+ if (name === 'home') {
412
+ setEditCursorPos(0);
413
+ return;
414
+ }
415
+ if (name === 'end') {
416
+ setEditCursorPos(cpLen(editBuffer));
417
+ return;
418
+ }
419
+ // Block other keys while editing
420
+ return;
421
+ }
422
+ if (name === 'up' || name === 'k') {
423
+ // If editing, commit first
424
+ if (editingKey) {
425
+ commitNumberEdit(editingKey);
426
+ }
427
+ const newIndex =
428
+ activeSettingIndex > 0 ? activeSettingIndex - 1 : items.length - 1;
429
+ setActiveSettingIndex(newIndex);
430
+ // Adjust scroll offset for wrap-around
431
+ if (newIndex === items.length - 1) {
432
+ setScrollOffset(Math.max(0, items.length - maxItemsToShow));
433
+ } else if (newIndex < scrollOffset) {
434
+ setScrollOffset(newIndex);
435
+ }
436
+ } else if (name === 'down' || name === 'j') {
437
+ // If editing, commit first
438
+ if (editingKey) {
439
+ commitNumberEdit(editingKey);
440
+ }
441
+ const newIndex =
442
+ activeSettingIndex < items.length - 1 ? activeSettingIndex + 1 : 0;
443
+ setActiveSettingIndex(newIndex);
444
+ // Adjust scroll offset for wrap-around
445
+ if (newIndex === 0) {
446
+ setScrollOffset(0);
447
+ } else if (newIndex >= scrollOffset + maxItemsToShow) {
448
+ setScrollOffset(newIndex - maxItemsToShow + 1);
449
+ }
450
+ } else if (name === 'return' || name === 'space') {
451
+ const currentItem = items[activeSettingIndex];
452
+ if (currentItem?.type === 'number') {
453
+ startEditingNumber(currentItem.value);
454
+ } else {
455
+ currentItem?.toggle();
456
+ }
457
+ } else if (/^[0-9]$/.test(key.sequence || '') && !editingKey) {
458
+ const currentItem = items[activeSettingIndex];
459
+ if (currentItem?.type === 'number') {
460
+ startEditingNumber(currentItem.value, key.sequence);
461
+ }
462
+ } else if (ctrl && (name === 'c' || name === 'l')) {
463
+ // Ctrl+C or Ctrl+L: Clear current setting and reset to default
464
+ const currentSetting = items[activeSettingIndex];
465
+ if (currentSetting) {
466
+ const defaultValue = getDefaultValue(currentSetting.value);
467
+ const defType = currentSetting.type;
468
+ if (defType === 'boolean') {
469
+ const booleanDefaultValue =
470
+ typeof defaultValue === 'boolean' ? defaultValue : false;
471
+ setPendingSettings((prev) =>
472
+ setPendingSettingValue(
473
+ currentSetting.value,
474
+ booleanDefaultValue,
475
+ prev,
476
+ ),
477
+ );
478
+ } else if (defType === 'number') {
479
+ if (typeof defaultValue === 'number') {
480
+ setPendingSettings((prev) =>
481
+ setPendingSettingValueAny(
482
+ currentSetting.value,
483
+ defaultValue,
484
+ prev,
485
+ ),
486
+ );
487
+ }
488
+ }
489
+
490
+ // Remove from modified settings since it's now at default
491
+ setModifiedSettings((prev) => {
492
+ const updated = new Set(prev);
493
+ updated.delete(currentSetting.value);
494
+ return updated;
495
+ });
496
+
497
+ // Remove from restart-required settings if it was there
498
+ setRestartRequiredSettings((prev) => {
499
+ const updated = new Set(prev);
500
+ updated.delete(currentSetting.value);
501
+ return updated;
502
+ });
503
+
504
+ // If this setting doesn't require restart, save it immediately
505
+ if (!requiresRestart(currentSetting.value)) {
506
+ const immediateSettings = new Set([currentSetting.value]);
507
+ const toSaveValue =
508
+ currentSetting.type === 'boolean'
509
+ ? typeof defaultValue === 'boolean'
510
+ ? defaultValue
511
+ : false
512
+ : typeof defaultValue === 'number'
513
+ ? defaultValue
514
+ : undefined;
515
+ const immediateSettingsObject =
516
+ toSaveValue !== undefined
517
+ ? setPendingSettingValueAny(
518
+ currentSetting.value,
519
+ toSaveValue,
520
+ {} as Settings,
521
+ )
522
+ : ({} as Settings);
523
+
524
+ saveModifiedSettings(
525
+ immediateSettings,
526
+ immediateSettingsObject,
527
+ settings,
528
+ selectedScope,
529
+ );
530
+
531
+ // Remove from global pending changes if present
532
+ setGlobalPendingChanges((prev) => {
533
+ if (!prev.has(currentSetting.value)) return prev;
534
+ const next = new Map(prev);
535
+ next.delete(currentSetting.value);
536
+ return next;
537
+ });
538
+ } else {
539
+ // Track default reset as a pending change if restart required
540
+ if (
541
+ (currentSetting.type === 'boolean' &&
542
+ typeof defaultValue === 'boolean') ||
543
+ (currentSetting.type === 'number' &&
544
+ typeof defaultValue === 'number')
545
+ ) {
546
+ setGlobalPendingChanges((prev) => {
547
+ const next = new Map(prev);
548
+ next.set(currentSetting.value, defaultValue as PendingValue);
549
+ return next;
550
+ });
551
+ }
552
+ }
553
+ }
554
+ }
555
+ }
556
+ if (showRestartPrompt && name === 'r') {
557
+ // Only save settings that require restart (non-restart settings were already saved immediately)
558
+ const restartRequiredSettings =
559
+ getRestartRequiredFromModified(modifiedSettings);
560
+ const restartRequiredSet = new Set(restartRequiredSettings);
561
+
562
+ if (restartRequiredSet.size > 0) {
563
+ saveModifiedSettings(
564
+ restartRequiredSet,
565
+ pendingSettings,
566
+ settings,
567
+ selectedScope,
568
+ );
569
+
570
+ // Remove saved keys from global pending changes
571
+ setGlobalPendingChanges((prev) => {
572
+ if (prev.size === 0) return prev;
573
+ const next = new Map(prev);
574
+ for (const key of restartRequiredSet) {
575
+ next.delete(key);
576
+ }
577
+ return next;
578
+ });
579
+ }
580
+
581
+ setShowRestartPrompt(false);
582
+ setRestartRequiredSettings(new Set()); // Clear restart-required settings
583
+ if (onRestartRequest) onRestartRequest();
584
+ }
585
+ if (name === 'escape') {
586
+ if (editingKey) {
587
+ commitNumberEdit(editingKey);
588
+ } else {
589
+ onSelect(undefined, selectedScope);
590
+ }
591
+ }
592
+ },
593
+ { isActive: true },
594
+ );
595
+
596
+ return (
597
+ <Box
598
+ borderStyle="round"
599
+ borderColor={Colors.Gray}
600
+ flexDirection="row"
601
+ padding={1}
602
+ width="100%"
603
+ height="100%"
604
+ >
605
+ <Box flexDirection="column" flexGrow={1}>
606
+ <Text bold color={Colors.AccentBlue}>
607
+ Settings
608
+ </Text>
609
+ <Box height={1} />
610
+ {showScrollUp && <Text color={Colors.Gray}>▲</Text>}
611
+ {visibleItems.map((item, idx) => {
612
+ const isActive =
613
+ focusSection === 'settings' &&
614
+ activeSettingIndex === idx + scrollOffset;
615
+
616
+ const scopeSettings = settings.forScope(selectedScope).settings;
617
+ const mergedSettings = settings.merged;
618
+
619
+ let displayValue: string;
620
+ if (editingKey === item.value) {
621
+ // Show edit buffer with advanced cursor highlighting
622
+ if (cursorVisible && editCursorPos < cpLen(editBuffer)) {
623
+ // Cursor is in the middle or at start of text
624
+ const beforeCursor = cpSlice(editBuffer, 0, editCursorPos);
625
+ const atCursor = cpSlice(
626
+ editBuffer,
627
+ editCursorPos,
628
+ editCursorPos + 1,
629
+ );
630
+ const afterCursor = cpSlice(editBuffer, editCursorPos + 1);
631
+ displayValue =
632
+ beforeCursor + chalk.inverse(atCursor) + afterCursor;
633
+ } else if (cursorVisible && editCursorPos >= cpLen(editBuffer)) {
634
+ // Cursor is at the end - show inverted space
635
+ displayValue = editBuffer + chalk.inverse(' ');
636
+ } else {
637
+ // Cursor not visible
638
+ displayValue = editBuffer;
639
+ }
640
+ } else if (item.type === 'number') {
641
+ // For numbers, get the actual current value from pending settings
642
+ const path = item.value.split('.');
643
+ const currentValue = getNestedValue(pendingSettings, path);
644
+
645
+ const defaultValue = getDefaultValue(item.value);
646
+
647
+ if (currentValue !== undefined && currentValue !== null) {
648
+ displayValue = String(currentValue);
649
+ } else {
650
+ displayValue =
651
+ defaultValue !== undefined && defaultValue !== null
652
+ ? String(defaultValue)
653
+ : '';
654
+ }
655
+
656
+ // Add * if value differs from default OR if currently being modified
657
+ const isModified = modifiedSettings.has(item.value);
658
+ const effectiveCurrentValue =
659
+ currentValue !== undefined && currentValue !== null
660
+ ? currentValue
661
+ : defaultValue;
662
+ const isDifferentFromDefault =
663
+ effectiveCurrentValue !== defaultValue;
664
+
665
+ if (isDifferentFromDefault || isModified) {
666
+ displayValue += '*';
667
+ }
668
+ } else {
669
+ // For booleans and other types, use existing logic
670
+ displayValue = getDisplayValue(
671
+ item.value,
672
+ scopeSettings,
673
+ mergedSettings,
674
+ modifiedSettings,
675
+ pendingSettings,
676
+ );
677
+ }
678
+ const shouldBeGreyedOut = isDefaultValue(item.value, scopeSettings);
679
+
680
+ // Generate scope message for this setting
681
+ const scopeMessage = getScopeMessageForSetting(
682
+ item.value,
683
+ selectedScope,
684
+ settings,
685
+ );
686
+
687
+ return (
688
+ <React.Fragment key={item.value}>
689
+ <Box flexDirection="row" alignItems="center">
690
+ <Box minWidth={2} flexShrink={0}>
691
+ <Text color={isActive ? Colors.AccentGreen : Colors.Gray}>
692
+ {isActive ? '●' : ''}
693
+ </Text>
694
+ </Box>
695
+ <Box minWidth={50}>
696
+ <Text
697
+ color={isActive ? Colors.AccentGreen : Colors.Foreground}
698
+ >
699
+ {item.label}
700
+ {scopeMessage && (
701
+ <Text color={Colors.Gray}> {scopeMessage}</Text>
702
+ )}
703
+ </Text>
704
+ </Box>
705
+ <Box minWidth={3} />
706
+ <Text
707
+ color={
708
+ isActive
709
+ ? Colors.AccentGreen
710
+ : shouldBeGreyedOut
711
+ ? Colors.Gray
712
+ : Colors.Foreground
713
+ }
714
+ >
715
+ {displayValue}
716
+ </Text>
717
+ </Box>
718
+ <Box height={1} />
719
+ </React.Fragment>
720
+ );
721
+ })}
722
+ {showScrollDown && <Text color={Colors.Gray}>▼</Text>}
723
+
724
+ <Box height={1} />
725
+
726
+ <Box marginTop={1} flexDirection="column">
727
+ <Text bold={focusSection === 'scope'} wrap="truncate">
728
+ {focusSection === 'scope' ? '> ' : ' '}Apply To
729
+ </Text>
730
+ <RadioButtonSelect
731
+ items={scopeItems}
732
+ initialIndex={0}
733
+ onSelect={handleScopeSelect}
734
+ onHighlight={handleScopeHighlight}
735
+ isFocused={focusSection === 'scope'}
736
+ showNumbers={focusSection === 'scope'}
737
+ />
738
+ </Box>
739
+
740
+ <Box height={1} />
741
+ <Text color={Colors.Gray}>
742
+ (Use Enter to select, Tab to change focus)
743
+ </Text>
744
+ {showRestartPrompt && (
745
+ <Text color={Colors.AccentYellow}>
746
+ To see changes, Gemini CLI must be restarted. Press r to exit and
747
+ apply changes now.
748
+ </Text>
749
+ )}
750
+ </Box>
751
+ </Box>
752
+ );
753
+ }
projects/ui/qwen-code/packages/cli/src/ui/components/ShellConfirmationDialog.test.tsx ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { renderWithProviders } from '../../test-utils/render.js';
8
+ import { describe, it, expect, vi } from 'vitest';
9
+ import { ShellConfirmationDialog } from './ShellConfirmationDialog.js';
10
+
11
+ describe('ShellConfirmationDialog', () => {
12
+ const onConfirm = vi.fn();
13
+
14
+ const request = {
15
+ commands: ['ls -la', 'echo "hello"'],
16
+ onConfirm,
17
+ };
18
+
19
+ it('renders correctly', () => {
20
+ const { lastFrame } = renderWithProviders(
21
+ <ShellConfirmationDialog request={request} />,
22
+ );
23
+ expect(lastFrame()).toMatchSnapshot();
24
+ });
25
+
26
+ it('calls onConfirm with ProceedOnce when "Yes, allow once" is selected', () => {
27
+ const { lastFrame } = renderWithProviders(
28
+ <ShellConfirmationDialog request={request} />,
29
+ );
30
+ const select = lastFrame()!.toString();
31
+ // Simulate selecting the first option
32
+ // This is a simplified way to test the selection
33
+ expect(select).toContain('Yes, allow once');
34
+ });
35
+
36
+ it('calls onConfirm with ProceedAlways when "Yes, allow always for this session" is selected', () => {
37
+ const { lastFrame } = renderWithProviders(
38
+ <ShellConfirmationDialog request={request} />,
39
+ );
40
+ const select = lastFrame()!.toString();
41
+ // Simulate selecting the second option
42
+ expect(select).toContain('Yes, allow always for this session');
43
+ });
44
+
45
+ it('calls onConfirm with Cancel when "No (esc)" is selected', () => {
46
+ const { lastFrame } = renderWithProviders(
47
+ <ShellConfirmationDialog request={request} />,
48
+ );
49
+ const select = lastFrame()!.toString();
50
+ // Simulate selecting the third option
51
+ expect(select).toContain('No (esc)');
52
+ });
53
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/ShellConfirmationDialog.tsx ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { ToolConfirmationOutcome } from '@qwen-code/qwen-code-core';
8
+ import { Box, Text } from 'ink';
9
+ import React from 'react';
10
+ import { Colors } from '../colors.js';
11
+ import { useKeypress } from '../hooks/useKeypress.js';
12
+ import { RenderInline } from '../utils/InlineMarkdownRenderer.js';
13
+ import {
14
+ RadioButtonSelect,
15
+ RadioSelectItem,
16
+ } from './shared/RadioButtonSelect.js';
17
+
18
+ export interface ShellConfirmationRequest {
19
+ commands: string[];
20
+ onConfirm: (
21
+ outcome: ToolConfirmationOutcome,
22
+ approvedCommands?: string[],
23
+ ) => void;
24
+ }
25
+
26
+ export interface ShellConfirmationDialogProps {
27
+ request: ShellConfirmationRequest;
28
+ }
29
+
30
+ export const ShellConfirmationDialog: React.FC<
31
+ ShellConfirmationDialogProps
32
+ > = ({ request }) => {
33
+ const { commands, onConfirm } = request;
34
+
35
+ useKeypress(
36
+ (key) => {
37
+ if (key.name === 'escape') {
38
+ onConfirm(ToolConfirmationOutcome.Cancel);
39
+ }
40
+ },
41
+ { isActive: true },
42
+ );
43
+
44
+ const handleSelect = (item: ToolConfirmationOutcome) => {
45
+ if (item === ToolConfirmationOutcome.Cancel) {
46
+ onConfirm(item);
47
+ } else {
48
+ // For both ProceedOnce and ProceedAlways, we approve all the
49
+ // commands that were requested.
50
+ onConfirm(item, commands);
51
+ }
52
+ };
53
+
54
+ const options: Array<RadioSelectItem<ToolConfirmationOutcome>> = [
55
+ {
56
+ label: 'Yes, allow once',
57
+ value: ToolConfirmationOutcome.ProceedOnce,
58
+ },
59
+ {
60
+ label: 'Yes, allow always for this session',
61
+ value: ToolConfirmationOutcome.ProceedAlways,
62
+ },
63
+ {
64
+ label: 'No (esc)',
65
+ value: ToolConfirmationOutcome.Cancel,
66
+ },
67
+ ];
68
+
69
+ return (
70
+ <Box
71
+ flexDirection="column"
72
+ borderStyle="round"
73
+ borderColor={Colors.AccentYellow}
74
+ padding={1}
75
+ width="100%"
76
+ marginLeft={1}
77
+ >
78
+ <Box flexDirection="column" marginBottom={1}>
79
+ <Text bold>Shell Command Execution</Text>
80
+ <Text>A custom command wants to run the following shell commands:</Text>
81
+ <Box
82
+ flexDirection="column"
83
+ borderStyle="round"
84
+ borderColor={Colors.Gray}
85
+ paddingX={1}
86
+ marginTop={1}
87
+ >
88
+ {commands.map((cmd) => (
89
+ <Text key={cmd} color={Colors.AccentCyan}>
90
+ <RenderInline text={cmd} />
91
+ </Text>
92
+ ))}
93
+ </Box>
94
+ </Box>
95
+
96
+ <Box marginBottom={1}>
97
+ <Text>Do you want to proceed?</Text>
98
+ </Box>
99
+
100
+ <RadioButtonSelect items={options} onSelect={handleSelect} isFocused />
101
+ </Box>
102
+ );
103
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/ShellModeIndicator.tsx ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+
11
+ export const ShellModeIndicator: React.FC = () => (
12
+ <Box>
13
+ <Text color={Colors.AccentYellow}>
14
+ shell mode enabled
15
+ <Text color={Colors.Gray}> (esc to disable)</Text>
16
+ </Text>
17
+ </Box>
18
+ );
projects/ui/qwen-code/packages/cli/src/ui/components/ShowMoreLines.tsx ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Box, Text } from 'ink';
8
+ import { useOverflowState } from '../contexts/OverflowContext.js';
9
+ import { useStreamingContext } from '../contexts/StreamingContext.js';
10
+ import { StreamingState } from '../types.js';
11
+ import { Colors } from '../colors.js';
12
+
13
+ interface ShowMoreLinesProps {
14
+ constrainHeight: boolean;
15
+ }
16
+
17
+ export const ShowMoreLines = ({ constrainHeight }: ShowMoreLinesProps) => {
18
+ const overflowState = useOverflowState();
19
+ const streamingState = useStreamingContext();
20
+
21
+ if (
22
+ overflowState === undefined ||
23
+ overflowState.overflowingIds.size === 0 ||
24
+ !constrainHeight ||
25
+ !(
26
+ streamingState === StreamingState.Idle ||
27
+ streamingState === StreamingState.WaitingForConfirmation
28
+ )
29
+ ) {
30
+ return null;
31
+ }
32
+
33
+ return (
34
+ <Box>
35
+ <Text color={Colors.Gray} wrap="truncate">
36
+ Press ctrl-s to show more lines
37
+ </Text>
38
+ </Box>
39
+ );
40
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/StatsDisplay.test.tsx ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { render } from 'ink-testing-library';
8
+ import { describe, it, expect, vi } from 'vitest';
9
+ import { StatsDisplay } from './StatsDisplay.js';
10
+ import * as SessionContext from '../contexts/SessionContext.js';
11
+ import { SessionMetrics } from '../contexts/SessionContext.js';
12
+
13
+ // Mock the context to provide controlled data for testing
14
+ vi.mock('../contexts/SessionContext.js', async (importOriginal) => {
15
+ const actual = await importOriginal<typeof SessionContext>();
16
+ return {
17
+ ...actual,
18
+ useSessionStats: vi.fn(),
19
+ };
20
+ });
21
+
22
+ const useSessionStatsMock = vi.mocked(SessionContext.useSessionStats);
23
+
24
+ const renderWithMockedStats = (metrics: SessionMetrics) => {
25
+ useSessionStatsMock.mockReturnValue({
26
+ stats: {
27
+ sessionId: 'test-session-id',
28
+ sessionStartTime: new Date(),
29
+ metrics,
30
+ lastPromptTokenCount: 0,
31
+ promptCount: 5,
32
+ },
33
+
34
+ getPromptCount: () => 5,
35
+ startNewPrompt: vi.fn(),
36
+ });
37
+
38
+ return render(<StatsDisplay duration="1s" />);
39
+ };
40
+
41
+ describe('<StatsDisplay />', () => {
42
+ it('renders only the Performance section in its zero state', () => {
43
+ const zeroMetrics: SessionMetrics = {
44
+ models: {},
45
+ tools: {
46
+ totalCalls: 0,
47
+ totalSuccess: 0,
48
+ totalFail: 0,
49
+ totalDurationMs: 0,
50
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
51
+ byName: {},
52
+ },
53
+ files: {
54
+ totalLinesAdded: 0,
55
+ totalLinesRemoved: 0,
56
+ },
57
+ };
58
+
59
+ const { lastFrame } = renderWithMockedStats(zeroMetrics);
60
+ const output = lastFrame();
61
+
62
+ expect(output).toContain('Performance');
63
+ expect(output).toContain('Interaction Summary');
64
+ expect(output).not.toContain('Efficiency & Optimizations');
65
+ expect(output).not.toContain('Model'); // The table header
66
+ expect(output).toMatchSnapshot();
67
+ });
68
+
69
+ it('renders a table with two models correctly', () => {
70
+ const metrics: SessionMetrics = {
71
+ models: {
72
+ 'gemini-2.5-pro': {
73
+ api: { totalRequests: 3, totalErrors: 0, totalLatencyMs: 15000 },
74
+ tokens: {
75
+ prompt: 1000,
76
+ candidates: 2000,
77
+ total: 43234,
78
+ cached: 500,
79
+ thoughts: 100,
80
+ tool: 50,
81
+ },
82
+ },
83
+ 'gemini-2.5-flash': {
84
+ api: { totalRequests: 5, totalErrors: 1, totalLatencyMs: 4500 },
85
+ tokens: {
86
+ prompt: 25000,
87
+ candidates: 15000,
88
+ total: 150000000,
89
+ cached: 10000,
90
+ thoughts: 2000,
91
+ tool: 1000,
92
+ },
93
+ },
94
+ },
95
+ tools: {
96
+ totalCalls: 0,
97
+ totalSuccess: 0,
98
+ totalFail: 0,
99
+ totalDurationMs: 0,
100
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
101
+ byName: {},
102
+ },
103
+ files: {
104
+ totalLinesAdded: 0,
105
+ totalLinesRemoved: 0,
106
+ },
107
+ };
108
+
109
+ const { lastFrame } = renderWithMockedStats(metrics);
110
+ const output = lastFrame();
111
+
112
+ expect(output).toContain('gemini-2.5-pro');
113
+ expect(output).toContain('gemini-2.5-flash');
114
+ expect(output).toContain('1,000');
115
+ expect(output).toContain('25,000');
116
+ expect(output).toMatchSnapshot();
117
+ });
118
+
119
+ it('renders all sections when all data is present', () => {
120
+ const metrics: SessionMetrics = {
121
+ models: {
122
+ 'gemini-2.5-pro': {
123
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 100 },
124
+ tokens: {
125
+ prompt: 100,
126
+ candidates: 100,
127
+ total: 250,
128
+ cached: 50,
129
+ thoughts: 0,
130
+ tool: 0,
131
+ },
132
+ },
133
+ },
134
+ tools: {
135
+ totalCalls: 2,
136
+ totalSuccess: 1,
137
+ totalFail: 1,
138
+ totalDurationMs: 123,
139
+ totalDecisions: { accept: 1, reject: 0, modify: 0 },
140
+ byName: {
141
+ 'test-tool': {
142
+ count: 2,
143
+ success: 1,
144
+ fail: 1,
145
+ durationMs: 123,
146
+ decisions: { accept: 1, reject: 0, modify: 0 },
147
+ },
148
+ },
149
+ },
150
+ files: {
151
+ totalLinesAdded: 0,
152
+ totalLinesRemoved: 0,
153
+ },
154
+ };
155
+
156
+ const { lastFrame } = renderWithMockedStats(metrics);
157
+ const output = lastFrame();
158
+
159
+ expect(output).toContain('Performance');
160
+ expect(output).toContain('Interaction Summary');
161
+ expect(output).toContain('User Agreement');
162
+ expect(output).toContain('Savings Highlight');
163
+ expect(output).toContain('gemini-2.5-pro');
164
+ expect(output).toMatchSnapshot();
165
+ });
166
+
167
+ describe('Conditional Rendering Tests', () => {
168
+ it('hides User Agreement when no decisions are made', () => {
169
+ const metrics: SessionMetrics = {
170
+ models: {},
171
+ tools: {
172
+ totalCalls: 2,
173
+ totalSuccess: 1,
174
+ totalFail: 1,
175
+ totalDurationMs: 123,
176
+ totalDecisions: { accept: 0, reject: 0, modify: 0 }, // No decisions
177
+ byName: {
178
+ 'test-tool': {
179
+ count: 2,
180
+ success: 1,
181
+ fail: 1,
182
+ durationMs: 123,
183
+ decisions: { accept: 0, reject: 0, modify: 0 },
184
+ },
185
+ },
186
+ },
187
+ files: {
188
+ totalLinesAdded: 0,
189
+ totalLinesRemoved: 0,
190
+ },
191
+ };
192
+
193
+ const { lastFrame } = renderWithMockedStats(metrics);
194
+ const output = lastFrame();
195
+
196
+ expect(output).toContain('Interaction Summary');
197
+ expect(output).toContain('Success Rate');
198
+ expect(output).not.toContain('User Agreement');
199
+ expect(output).toMatchSnapshot();
200
+ });
201
+
202
+ it('hides Efficiency section when cache is not used', () => {
203
+ const metrics: SessionMetrics = {
204
+ models: {
205
+ 'gemini-2.5-pro': {
206
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 100 },
207
+ tokens: {
208
+ prompt: 100,
209
+ candidates: 100,
210
+ total: 200,
211
+ cached: 0,
212
+ thoughts: 0,
213
+ tool: 0,
214
+ },
215
+ },
216
+ },
217
+ tools: {
218
+ totalCalls: 0,
219
+ totalSuccess: 0,
220
+ totalFail: 0,
221
+ totalDurationMs: 0,
222
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
223
+ byName: {},
224
+ },
225
+ files: {
226
+ totalLinesAdded: 0,
227
+ totalLinesRemoved: 0,
228
+ },
229
+ };
230
+
231
+ const { lastFrame } = renderWithMockedStats(metrics);
232
+ const output = lastFrame();
233
+
234
+ expect(output).not.toContain('Efficiency & Optimizations');
235
+ expect(output).toMatchSnapshot();
236
+ });
237
+ });
238
+
239
+ describe('Conditional Color Tests', () => {
240
+ it('renders success rate in green for high values', () => {
241
+ const metrics: SessionMetrics = {
242
+ models: {},
243
+ tools: {
244
+ totalCalls: 10,
245
+ totalSuccess: 10,
246
+ totalFail: 0,
247
+ totalDurationMs: 0,
248
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
249
+ byName: {},
250
+ },
251
+ files: {
252
+ totalLinesAdded: 0,
253
+ totalLinesRemoved: 0,
254
+ },
255
+ };
256
+ const { lastFrame } = renderWithMockedStats(metrics);
257
+ expect(lastFrame()).toMatchSnapshot();
258
+ });
259
+
260
+ it('renders success rate in yellow for medium values', () => {
261
+ const metrics: SessionMetrics = {
262
+ models: {},
263
+ tools: {
264
+ totalCalls: 10,
265
+ totalSuccess: 9,
266
+ totalFail: 1,
267
+ totalDurationMs: 0,
268
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
269
+ byName: {},
270
+ },
271
+ files: {
272
+ totalLinesAdded: 0,
273
+ totalLinesRemoved: 0,
274
+ },
275
+ };
276
+ const { lastFrame } = renderWithMockedStats(metrics);
277
+ expect(lastFrame()).toMatchSnapshot();
278
+ });
279
+
280
+ it('renders success rate in red for low values', () => {
281
+ const metrics: SessionMetrics = {
282
+ models: {},
283
+ tools: {
284
+ totalCalls: 10,
285
+ totalSuccess: 5,
286
+ totalFail: 5,
287
+ totalDurationMs: 0,
288
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
289
+ byName: {},
290
+ },
291
+ files: {
292
+ totalLinesAdded: 0,
293
+ totalLinesRemoved: 0,
294
+ },
295
+ };
296
+ const { lastFrame } = renderWithMockedStats(metrics);
297
+ expect(lastFrame()).toMatchSnapshot();
298
+ });
299
+ });
300
+
301
+ describe('Code Changes Display', () => {
302
+ it('displays Code Changes when line counts are present', () => {
303
+ const metrics: SessionMetrics = {
304
+ models: {},
305
+ tools: {
306
+ totalCalls: 1,
307
+ totalSuccess: 1,
308
+ totalFail: 0,
309
+ totalDurationMs: 100,
310
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
311
+ byName: {},
312
+ },
313
+ files: {
314
+ totalLinesAdded: 42,
315
+ totalLinesRemoved: 18,
316
+ },
317
+ };
318
+
319
+ const { lastFrame } = renderWithMockedStats(metrics);
320
+ const output = lastFrame();
321
+
322
+ expect(output).toContain('Code Changes:');
323
+ expect(output).toContain('+42');
324
+ expect(output).toContain('-18');
325
+ expect(output).toMatchSnapshot();
326
+ });
327
+
328
+ it('hides Code Changes when no lines are added or removed', () => {
329
+ const metrics: SessionMetrics = {
330
+ models: {},
331
+ tools: {
332
+ totalCalls: 1,
333
+ totalSuccess: 1,
334
+ totalFail: 0,
335
+ totalDurationMs: 100,
336
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
337
+ byName: {},
338
+ },
339
+ files: {
340
+ totalLinesAdded: 0,
341
+ totalLinesRemoved: 0,
342
+ },
343
+ };
344
+
345
+ const { lastFrame } = renderWithMockedStats(metrics);
346
+ const output = lastFrame();
347
+
348
+ expect(output).not.toContain('Code Changes:');
349
+ expect(output).toMatchSnapshot();
350
+ });
351
+ });
352
+
353
+ describe('Title Rendering', () => {
354
+ const zeroMetrics: SessionMetrics = {
355
+ models: {},
356
+ tools: {
357
+ totalCalls: 0,
358
+ totalSuccess: 0,
359
+ totalFail: 0,
360
+ totalDurationMs: 0,
361
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
362
+ byName: {},
363
+ },
364
+ files: {
365
+ totalLinesAdded: 0,
366
+ totalLinesRemoved: 0,
367
+ },
368
+ };
369
+
370
+ it('renders the default title when no title prop is provided', () => {
371
+ const { lastFrame } = renderWithMockedStats(zeroMetrics);
372
+ const output = lastFrame();
373
+ expect(output).toContain('Session Stats');
374
+ expect(output).not.toContain('Agent powering down');
375
+ expect(output).toMatchSnapshot();
376
+ });
377
+
378
+ it('renders the custom title when a title prop is provided', () => {
379
+ useSessionStatsMock.mockReturnValue({
380
+ stats: {
381
+ sessionId: 'test-session-id',
382
+ sessionStartTime: new Date(),
383
+ metrics: zeroMetrics,
384
+ lastPromptTokenCount: 0,
385
+ promptCount: 5,
386
+ },
387
+
388
+ getPromptCount: () => 5,
389
+ startNewPrompt: vi.fn(),
390
+ });
391
+
392
+ const { lastFrame } = render(
393
+ <StatsDisplay duration="1s" title="Agent powering down. Goodbye!" />,
394
+ );
395
+ const output = lastFrame();
396
+ expect(output).toContain('Agent powering down. Goodbye!');
397
+ expect(output).not.toContain('Session Stats');
398
+ expect(output).toMatchSnapshot();
399
+ });
400
+ });
401
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/StatsDisplay.tsx ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import Gradient from 'ink-gradient';
10
+ import { theme } from '../semantic-colors.js';
11
+ import { formatDuration } from '../utils/formatters.js';
12
+ import { useSessionStats, ModelMetrics } from '../contexts/SessionContext.js';
13
+ import {
14
+ getStatusColor,
15
+ TOOL_SUCCESS_RATE_HIGH,
16
+ TOOL_SUCCESS_RATE_MEDIUM,
17
+ USER_AGREEMENT_RATE_HIGH,
18
+ USER_AGREEMENT_RATE_MEDIUM,
19
+ } from '../utils/displayUtils.js';
20
+ import { computeSessionStats } from '../utils/computeStats.js';
21
+
22
+ // A more flexible and powerful StatRow component
23
+ interface StatRowProps {
24
+ title: string;
25
+ children: React.ReactNode; // Use children to allow for complex, colored values
26
+ }
27
+
28
+ const StatRow: React.FC<StatRowProps> = ({ title, children }) => (
29
+ <Box>
30
+ {/* Fixed width for the label creates a clean "gutter" for alignment */}
31
+ <Box width={28}>
32
+ <Text color={theme.text.link}>{title}</Text>
33
+ </Box>
34
+ {children}
35
+ </Box>
36
+ );
37
+
38
+ // A SubStatRow for indented, secondary information
39
+ interface SubStatRowProps {
40
+ title: string;
41
+ children: React.ReactNode;
42
+ }
43
+
44
+ const SubStatRow: React.FC<SubStatRowProps> = ({ title, children }) => (
45
+ <Box paddingLeft={2}>
46
+ {/* Adjust width for the "» " prefix */}
47
+ <Box width={26}>
48
+ <Text>» {title}</Text>
49
+ </Box>
50
+ {children}
51
+ </Box>
52
+ );
53
+
54
+ // A Section component to group related stats
55
+ interface SectionProps {
56
+ title: string;
57
+ children: React.ReactNode;
58
+ }
59
+
60
+ const Section: React.FC<SectionProps> = ({ title, children }) => (
61
+ <Box flexDirection="column" width="100%" marginBottom={1}>
62
+ <Text bold>{title}</Text>
63
+ {children}
64
+ </Box>
65
+ );
66
+
67
+ const ModelUsageTable: React.FC<{
68
+ models: Record<string, ModelMetrics>;
69
+ totalCachedTokens: number;
70
+ cacheEfficiency: number;
71
+ }> = ({ models, totalCachedTokens, cacheEfficiency }) => {
72
+ const nameWidth = 25;
73
+ const requestsWidth = 8;
74
+ const inputTokensWidth = 15;
75
+ const outputTokensWidth = 15;
76
+
77
+ return (
78
+ <Box flexDirection="column" marginTop={1}>
79
+ {/* Header */}
80
+ <Box>
81
+ <Box width={nameWidth}>
82
+ <Text bold>Model Usage</Text>
83
+ </Box>
84
+ <Box width={requestsWidth} justifyContent="flex-end">
85
+ <Text bold>Reqs</Text>
86
+ </Box>
87
+ <Box width={inputTokensWidth} justifyContent="flex-end">
88
+ <Text bold>Input Tokens</Text>
89
+ </Box>
90
+ <Box width={outputTokensWidth} justifyContent="flex-end">
91
+ <Text bold>Output Tokens</Text>
92
+ </Box>
93
+ </Box>
94
+ {/* Divider */}
95
+ <Box
96
+ borderStyle="round"
97
+ borderBottom={true}
98
+ borderTop={false}
99
+ borderLeft={false}
100
+ borderRight={false}
101
+ width={nameWidth + requestsWidth + inputTokensWidth + outputTokensWidth}
102
+ ></Box>
103
+
104
+ {/* Rows */}
105
+ {Object.entries(models).map(([name, modelMetrics]) => (
106
+ <Box key={name}>
107
+ <Box width={nameWidth}>
108
+ <Text>{name.replace('-001', '')}</Text>
109
+ </Box>
110
+ <Box width={requestsWidth} justifyContent="flex-end">
111
+ <Text>{modelMetrics.api.totalRequests}</Text>
112
+ </Box>
113
+ <Box width={inputTokensWidth} justifyContent="flex-end">
114
+ <Text color={theme.status.warning}>
115
+ {modelMetrics.tokens.prompt.toLocaleString()}
116
+ </Text>
117
+ </Box>
118
+ <Box width={outputTokensWidth} justifyContent="flex-end">
119
+ <Text color={theme.status.warning}>
120
+ {modelMetrics.tokens.candidates.toLocaleString()}
121
+ </Text>
122
+ </Box>
123
+ </Box>
124
+ ))}
125
+ {cacheEfficiency > 0 && (
126
+ <Box flexDirection="column" marginTop={1}>
127
+ <Text>
128
+ <Text color={theme.status.success}>Savings Highlight:</Text>{' '}
129
+ {totalCachedTokens.toLocaleString()} ({cacheEfficiency.toFixed(1)}
130
+ %) of input tokens were served from the cache, reducing costs.
131
+ </Text>
132
+ <Box height={1} />
133
+ <Text color={theme.text.secondary}>
134
+ » Tip: For a full token breakdown, run `/stats model`.
135
+ </Text>
136
+ </Box>
137
+ )}
138
+ </Box>
139
+ );
140
+ };
141
+
142
+ interface StatsDisplayProps {
143
+ duration: string;
144
+ title?: string;
145
+ }
146
+
147
+ export const StatsDisplay: React.FC<StatsDisplayProps> = ({
148
+ duration,
149
+ title,
150
+ }) => {
151
+ const { stats } = useSessionStats();
152
+ const { metrics } = stats;
153
+ const { models, tools, files } = metrics;
154
+ const computed = computeSessionStats(metrics);
155
+
156
+ const successThresholds = {
157
+ green: TOOL_SUCCESS_RATE_HIGH,
158
+ yellow: TOOL_SUCCESS_RATE_MEDIUM,
159
+ };
160
+ const agreementThresholds = {
161
+ green: USER_AGREEMENT_RATE_HIGH,
162
+ yellow: USER_AGREEMENT_RATE_MEDIUM,
163
+ };
164
+ const successColor = getStatusColor(computed.successRate, successThresholds);
165
+ const agreementColor = getStatusColor(
166
+ computed.agreementRate,
167
+ agreementThresholds,
168
+ );
169
+
170
+ const renderTitle = () => {
171
+ if (title) {
172
+ return theme.ui.gradient && theme.ui.gradient.length > 0 ? (
173
+ <Gradient colors={theme.ui.gradient}>
174
+ <Text bold>{title}</Text>
175
+ </Gradient>
176
+ ) : (
177
+ <Text bold color={theme.text.accent}>
178
+ {title}
179
+ </Text>
180
+ );
181
+ }
182
+ return (
183
+ <Text bold color={theme.text.accent}>
184
+ Session Stats
185
+ </Text>
186
+ );
187
+ };
188
+
189
+ return (
190
+ <Box
191
+ borderStyle="round"
192
+ borderColor={theme.border.default}
193
+ flexDirection="column"
194
+ paddingY={1}
195
+ paddingX={2}
196
+ >
197
+ {renderTitle()}
198
+ <Box height={1} />
199
+
200
+ <Section title="Interaction Summary">
201
+ <StatRow title="Session ID:">
202
+ <Text>{stats.sessionId}</Text>
203
+ </StatRow>
204
+ <StatRow title="Tool Calls:">
205
+ <Text>
206
+ {tools.totalCalls} ({' '}
207
+ <Text color={theme.status.success}>✔ {tools.totalSuccess}</Text>{' '}
208
+ <Text color={theme.status.error}>✖ {tools.totalFail}</Text> )
209
+ </Text>
210
+ </StatRow>
211
+ <StatRow title="Success Rate:">
212
+ <Text color={successColor}>{computed.successRate.toFixed(1)}%</Text>
213
+ </StatRow>
214
+ {computed.totalDecisions > 0 && (
215
+ <StatRow title="User Agreement:">
216
+ <Text color={agreementColor}>
217
+ {computed.agreementRate.toFixed(1)}%{' '}
218
+ <Text color={theme.text.secondary}>
219
+ ({computed.totalDecisions} reviewed)
220
+ </Text>
221
+ </Text>
222
+ </StatRow>
223
+ )}
224
+ {files &&
225
+ (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && (
226
+ <StatRow title="Code Changes:">
227
+ <Text>
228
+ <Text color={theme.status.success}>
229
+ +{files.totalLinesAdded}
230
+ </Text>{' '}
231
+ <Text color={theme.status.error}>
232
+ -{files.totalLinesRemoved}
233
+ </Text>
234
+ </Text>
235
+ </StatRow>
236
+ )}
237
+ </Section>
238
+
239
+ <Section title="Performance">
240
+ <StatRow title="Wall Time:">
241
+ <Text>{duration}</Text>
242
+ </StatRow>
243
+ <StatRow title="Agent Active:">
244
+ <Text>{formatDuration(computed.agentActiveTime)}</Text>
245
+ </StatRow>
246
+ <SubStatRow title="API Time:">
247
+ <Text>
248
+ {formatDuration(computed.totalApiTime)}{' '}
249
+ <Text color={theme.text.secondary}>
250
+ ({computed.apiTimePercent.toFixed(1)}%)
251
+ </Text>
252
+ </Text>
253
+ </SubStatRow>
254
+ <SubStatRow title="Tool Time:">
255
+ <Text>
256
+ {formatDuration(computed.totalToolTime)}{' '}
257
+ <Text color={theme.text.secondary}>
258
+ ({computed.toolTimePercent.toFixed(1)}%)
259
+ </Text>
260
+ </Text>
261
+ </SubStatRow>
262
+ </Section>
263
+
264
+ {Object.keys(models).length > 0 && (
265
+ <ModelUsageTable
266
+ models={models}
267
+ totalCachedTokens={computed.totalCachedTokens}
268
+ cacheEfficiency={computed.cacheEfficiency}
269
+ />
270
+ )}
271
+ </Box>
272
+ );
273
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/SuggestionsDisplay.tsx ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Box, Text } from 'ink';
8
+ import { Colors } from '../colors.js';
9
+ import { PrepareLabel } from './PrepareLabel.js';
10
+ export interface Suggestion {
11
+ label: string;
12
+ value: string;
13
+ description?: string;
14
+ matchedIndex?: number;
15
+ }
16
+ interface SuggestionsDisplayProps {
17
+ suggestions: Suggestion[];
18
+ activeIndex: number;
19
+ isLoading: boolean;
20
+ width: number;
21
+ scrollOffset: number;
22
+ userInput: string;
23
+ }
24
+
25
+ export const MAX_SUGGESTIONS_TO_SHOW = 8;
26
+
27
+ export function SuggestionsDisplay({
28
+ suggestions,
29
+ activeIndex,
30
+ isLoading,
31
+ width,
32
+ scrollOffset,
33
+ userInput,
34
+ }: SuggestionsDisplayProps) {
35
+ if (isLoading) {
36
+ return (
37
+ <Box paddingX={1} width={width}>
38
+ <Text color="gray">Loading suggestions...</Text>
39
+ </Box>
40
+ );
41
+ }
42
+
43
+ if (suggestions.length === 0) {
44
+ return null; // Don't render anything if there are no suggestions
45
+ }
46
+
47
+ // Calculate the visible slice based on scrollOffset
48
+ const startIndex = scrollOffset;
49
+ const endIndex = Math.min(
50
+ scrollOffset + MAX_SUGGESTIONS_TO_SHOW,
51
+ suggestions.length,
52
+ );
53
+ const visibleSuggestions = suggestions.slice(startIndex, endIndex);
54
+
55
+ return (
56
+ <Box flexDirection="column" paddingX={1} width={width}>
57
+ {scrollOffset > 0 && <Text color={Colors.Foreground}>▲</Text>}
58
+
59
+ {visibleSuggestions.map((suggestion, index) => {
60
+ const originalIndex = startIndex + index;
61
+ const isActive = originalIndex === activeIndex;
62
+ const textColor = isActive ? Colors.AccentPurple : Colors.Gray;
63
+ const labelElement = (
64
+ <PrepareLabel
65
+ label={suggestion.label}
66
+ matchedIndex={suggestion.matchedIndex}
67
+ userInput={userInput}
68
+ textColor={textColor}
69
+ />
70
+ );
71
+
72
+ return (
73
+ <Box key={`${suggestion.value}-${originalIndex}`} width={width}>
74
+ <Box flexDirection="row">
75
+ {userInput.startsWith('/') ? (
76
+ // only use box model for (/) command mode
77
+ <Box width={20} flexShrink={0}>
78
+ {labelElement}
79
+ </Box>
80
+ ) : (
81
+ labelElement
82
+ )}
83
+ {suggestion.description ? (
84
+ <Box flexGrow={1}>
85
+ <Text color={textColor} wrap="truncate">
86
+ {suggestion.description}
87
+ </Text>
88
+ </Box>
89
+ ) : null}
90
+ </Box>
91
+ </Box>
92
+ );
93
+ })}
94
+ {endIndex < suggestions.length && <Text color="gray">▼</Text>}
95
+ {suggestions.length > MAX_SUGGESTIONS_TO_SHOW && (
96
+ <Text color="gray">
97
+ ({activeIndex + 1}/{suggestions.length})
98
+ </Text>
99
+ )}
100
+ </Box>
101
+ );
102
+ }
projects/ui/qwen-code/packages/cli/src/ui/components/ThemeDialog.tsx ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React, { useCallback, useState } from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import { themeManager, DEFAULT_THEME } from '../themes/theme-manager.js';
11
+ import { RadioButtonSelect } from './shared/RadioButtonSelect.js';
12
+ import { DiffRenderer } from './messages/DiffRenderer.js';
13
+ import { colorizeCode } from '../utils/CodeColorizer.js';
14
+ import { LoadedSettings, SettingScope } from '../../config/settings.js';
15
+ import {
16
+ getScopeItems,
17
+ getScopeMessageForSetting,
18
+ } from '../../utils/dialogScopeUtils.js';
19
+ import { useKeypress } from '../hooks/useKeypress.js';
20
+
21
+ interface ThemeDialogProps {
22
+ /** Callback function when a theme is selected */
23
+ onSelect: (themeName: string | undefined, scope: SettingScope) => void;
24
+
25
+ /** Callback function when a theme is highlighted */
26
+ onHighlight: (themeName: string | undefined) => void;
27
+ /** The settings object */
28
+ settings: LoadedSettings;
29
+ availableTerminalHeight?: number;
30
+ terminalWidth: number;
31
+ }
32
+
33
+ export function ThemeDialog({
34
+ onSelect,
35
+ onHighlight,
36
+ settings,
37
+ availableTerminalHeight,
38
+ terminalWidth,
39
+ }: ThemeDialogProps): React.JSX.Element {
40
+ const [selectedScope, setSelectedScope] = useState<SettingScope>(
41
+ SettingScope.User,
42
+ );
43
+
44
+ // Track the currently highlighted theme name
45
+ const [highlightedThemeName, setHighlightedThemeName] = useState<
46
+ string | undefined
47
+ >(settings.merged.theme || DEFAULT_THEME.name);
48
+
49
+ // Generate theme items filtered by selected scope
50
+ const customThemes =
51
+ selectedScope === SettingScope.User
52
+ ? settings.user.settings.customThemes || {}
53
+ : settings.merged.customThemes || {};
54
+ const builtInThemes = themeManager
55
+ .getAvailableThemes()
56
+ .filter((theme) => theme.type !== 'custom');
57
+ const customThemeNames = Object.keys(customThemes);
58
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
59
+ // Generate theme items
60
+ const themeItems = [
61
+ ...builtInThemes.map((theme) => ({
62
+ label: theme.name,
63
+ value: theme.name,
64
+ themeNameDisplay: theme.name,
65
+ themeTypeDisplay: capitalize(theme.type),
66
+ })),
67
+ ...customThemeNames.map((name) => ({
68
+ label: name,
69
+ value: name,
70
+ themeNameDisplay: name,
71
+ themeTypeDisplay: 'Custom',
72
+ })),
73
+ ];
74
+ const [selectInputKey, setSelectInputKey] = useState(Date.now());
75
+
76
+ // Find the index of the selected theme, but only if it exists in the list
77
+ const selectedThemeName = settings.merged.theme || DEFAULT_THEME.name;
78
+ const initialThemeIndex = themeItems.findIndex(
79
+ (item) => item.value === selectedThemeName,
80
+ );
81
+ // If not found, fall back to the first theme
82
+ const safeInitialThemeIndex = initialThemeIndex >= 0 ? initialThemeIndex : 0;
83
+
84
+ const scopeItems = getScopeItems();
85
+
86
+ const handleThemeSelect = useCallback(
87
+ (themeName: string) => {
88
+ onSelect(themeName, selectedScope);
89
+ },
90
+ [onSelect, selectedScope],
91
+ );
92
+
93
+ const handleThemeHighlight = (themeName: string) => {
94
+ setHighlightedThemeName(themeName);
95
+ onHighlight(themeName);
96
+ };
97
+
98
+ const handleScopeHighlight = useCallback((scope: SettingScope) => {
99
+ setSelectedScope(scope);
100
+ setSelectInputKey(Date.now());
101
+ }, []);
102
+
103
+ const handleScopeSelect = useCallback(
104
+ (scope: SettingScope) => {
105
+ handleScopeHighlight(scope);
106
+ setFocusedSection('theme'); // Reset focus to theme section
107
+ },
108
+ [handleScopeHighlight],
109
+ );
110
+
111
+ const [focusedSection, setFocusedSection] = useState<'theme' | 'scope'>(
112
+ 'theme',
113
+ );
114
+
115
+ useKeypress(
116
+ (key) => {
117
+ if (key.name === 'tab') {
118
+ setFocusedSection((prev) => (prev === 'theme' ? 'scope' : 'theme'));
119
+ }
120
+ if (key.name === 'escape') {
121
+ onSelect(undefined, selectedScope);
122
+ }
123
+ },
124
+ { isActive: true },
125
+ );
126
+
127
+ // Generate scope message for theme setting
128
+ const otherScopeModifiedMessage = getScopeMessageForSetting(
129
+ 'theme',
130
+ selectedScope,
131
+ settings,
132
+ );
133
+
134
+ // Constants for calculating preview pane layout.
135
+ // These values are based on the JSX structure below.
136
+ const PREVIEW_PANE_WIDTH_PERCENTAGE = 0.55;
137
+ // A safety margin to prevent text from touching the border.
138
+ // This is a complete hack unrelated to the 0.9 used in App.tsx
139
+ const PREVIEW_PANE_WIDTH_SAFETY_MARGIN = 0.9;
140
+ // Combined horizontal padding from the dialog and preview pane.
141
+ const TOTAL_HORIZONTAL_PADDING = 4;
142
+ const colorizeCodeWidth = Math.max(
143
+ Math.floor(
144
+ (terminalWidth - TOTAL_HORIZONTAL_PADDING) *
145
+ PREVIEW_PANE_WIDTH_PERCENTAGE *
146
+ PREVIEW_PANE_WIDTH_SAFETY_MARGIN,
147
+ ),
148
+ 1,
149
+ );
150
+
151
+ const DIALOG_PADDING = 2;
152
+ const selectThemeHeight = themeItems.length + 1;
153
+ const SCOPE_SELECTION_HEIGHT = 4; // Height for the scope selection section + margin.
154
+ const SPACE_BETWEEN_THEME_SELECTION_AND_APPLY_TO = 1;
155
+ const TAB_TO_SELECT_HEIGHT = 2;
156
+ availableTerminalHeight = availableTerminalHeight ?? Number.MAX_SAFE_INTEGER;
157
+ availableTerminalHeight -= 2; // Top and bottom borders.
158
+ availableTerminalHeight -= TAB_TO_SELECT_HEIGHT;
159
+
160
+ let totalLeftHandSideHeight =
161
+ DIALOG_PADDING +
162
+ selectThemeHeight +
163
+ SCOPE_SELECTION_HEIGHT +
164
+ SPACE_BETWEEN_THEME_SELECTION_AND_APPLY_TO;
165
+
166
+ let showScopeSelection = true;
167
+ let includePadding = true;
168
+
169
+ // Remove content from the LHS that can be omitted if it exceeds the available height.
170
+ if (totalLeftHandSideHeight > availableTerminalHeight) {
171
+ includePadding = false;
172
+ totalLeftHandSideHeight -= DIALOG_PADDING;
173
+ }
174
+
175
+ if (totalLeftHandSideHeight > availableTerminalHeight) {
176
+ // First, try hiding the scope selection
177
+ totalLeftHandSideHeight -= SCOPE_SELECTION_HEIGHT;
178
+ showScopeSelection = false;
179
+ }
180
+
181
+ // Don't focus the scope selection if it is hidden due to height constraints.
182
+ const currentFocusedSection = !showScopeSelection ? 'theme' : focusedSection;
183
+
184
+ // Vertical space taken by elements other than the two code blocks in the preview pane.
185
+ // Includes "Preview" title, borders, and margin between blocks.
186
+ const PREVIEW_PANE_FIXED_VERTICAL_SPACE = 8;
187
+
188
+ // The right column doesn't need to ever be shorter than the left column.
189
+ availableTerminalHeight = Math.max(
190
+ availableTerminalHeight,
191
+ totalLeftHandSideHeight,
192
+ );
193
+ const availableTerminalHeightCodeBlock =
194
+ availableTerminalHeight -
195
+ PREVIEW_PANE_FIXED_VERTICAL_SPACE -
196
+ (includePadding ? 2 : 0) * 2;
197
+
198
+ // Subtract margin between code blocks from available height.
199
+ const availableHeightForPanes = Math.max(
200
+ 0,
201
+ availableTerminalHeightCodeBlock - 1,
202
+ );
203
+
204
+ // The code block is slightly longer than the diff, so give it more space.
205
+ const codeBlockHeight = Math.ceil(availableHeightForPanes * 0.6);
206
+ const diffHeight = Math.floor(availableHeightForPanes * 0.4);
207
+ return (
208
+ <Box
209
+ borderStyle="round"
210
+ borderColor={Colors.Gray}
211
+ flexDirection="column"
212
+ paddingTop={includePadding ? 1 : 0}
213
+ paddingBottom={includePadding ? 1 : 0}
214
+ paddingLeft={1}
215
+ paddingRight={1}
216
+ width="100%"
217
+ >
218
+ <Box flexDirection="row">
219
+ {/* Left Column: Selection */}
220
+ <Box flexDirection="column" width="45%" paddingRight={2}>
221
+ <Text bold={currentFocusedSection === 'theme'} wrap="truncate">
222
+ {currentFocusedSection === 'theme' ? '> ' : ' '}Select Theme{' '}
223
+ <Text color={Colors.Gray}>{otherScopeModifiedMessage}</Text>
224
+ </Text>
225
+ <RadioButtonSelect
226
+ key={selectInputKey}
227
+ items={themeItems}
228
+ initialIndex={safeInitialThemeIndex}
229
+ onSelect={handleThemeSelect}
230
+ onHighlight={handleThemeHighlight}
231
+ isFocused={currentFocusedSection === 'theme'}
232
+ maxItemsToShow={8}
233
+ showScrollArrows={true}
234
+ showNumbers={currentFocusedSection === 'theme'}
235
+ />
236
+
237
+ {/* Scope Selection */}
238
+ {showScopeSelection && (
239
+ <Box marginTop={1} flexDirection="column">
240
+ <Text bold={currentFocusedSection === 'scope'} wrap="truncate">
241
+ {currentFocusedSection === 'scope' ? '> ' : ' '}Apply To
242
+ </Text>
243
+ <RadioButtonSelect
244
+ items={scopeItems}
245
+ initialIndex={0} // Default to User Settings
246
+ onSelect={handleScopeSelect}
247
+ onHighlight={handleScopeHighlight}
248
+ isFocused={currentFocusedSection === 'scope'}
249
+ showNumbers={currentFocusedSection === 'scope'}
250
+ />
251
+ </Box>
252
+ )}
253
+ </Box>
254
+
255
+ {/* Right Column: Preview */}
256
+ <Box flexDirection="column" width="55%" paddingLeft={2}>
257
+ <Text bold>Preview</Text>
258
+ {/* Get the Theme object for the highlighted theme, fall back to default if not found */}
259
+ {(() => {
260
+ const previewTheme =
261
+ themeManager.getTheme(
262
+ highlightedThemeName || DEFAULT_THEME.name,
263
+ ) || DEFAULT_THEME;
264
+ return (
265
+ <Box
266
+ borderStyle="single"
267
+ borderColor={Colors.Gray}
268
+ paddingTop={includePadding ? 1 : 0}
269
+ paddingBottom={includePadding ? 1 : 0}
270
+ paddingLeft={1}
271
+ paddingRight={1}
272
+ flexDirection="column"
273
+ >
274
+ {colorizeCode(
275
+ `# function
276
+ def fibonacci(n):
277
+ a, b = 0, 1
278
+ for _ in range(n):
279
+ a, b = b, a + b
280
+ return a`,
281
+ 'python',
282
+ codeBlockHeight,
283
+ colorizeCodeWidth,
284
+ )}
285
+ <Box marginTop={1} />
286
+ <DiffRenderer
287
+ diffContent={`--- a/util.py
288
+ +++ b/util.py
289
+ @@ -1,2 +1,2 @@
290
+ - print("Hello, " + name)
291
+ + print(f"Hello, {name}!")
292
+ `}
293
+ availableTerminalHeight={diffHeight}
294
+ terminalWidth={colorizeCodeWidth}
295
+ theme={previewTheme}
296
+ />
297
+ </Box>
298
+ );
299
+ })()}
300
+ </Box>
301
+ </Box>
302
+ <Box marginTop={1}>
303
+ <Text color={Colors.Gray} wrap="truncate">
304
+ (Use Enter to select
305
+ {showScopeSelection ? ', Tab to change focus' : ''})
306
+ </Text>
307
+ </Box>
308
+ </Box>
309
+ );
310
+ }
projects/ui/qwen-code/packages/cli/src/ui/components/Tips.tsx ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import { type Config } from '@qwen-code/qwen-code-core';
11
+
12
+ interface TipsProps {
13
+ config: Config;
14
+ }
15
+
16
+ export const Tips: React.FC<TipsProps> = ({ config }) => {
17
+ const geminiMdFileCount = config.getGeminiMdFileCount();
18
+ return (
19
+ <Box flexDirection="column">
20
+ <Text color={Colors.Foreground}>Tips for getting started:</Text>
21
+ <Text color={Colors.Foreground}>
22
+ 1. Ask questions, edit files, or run commands.
23
+ </Text>
24
+ <Text color={Colors.Foreground}>
25
+ 2. Be specific for the best results.
26
+ </Text>
27
+ {geminiMdFileCount === 0 && (
28
+ <Text color={Colors.Foreground}>
29
+ 3. Create{' '}
30
+ <Text bold color={Colors.AccentPurple}>
31
+ QWEN.md
32
+ </Text>{' '}
33
+ files to customize your interactions with Qwen Code.
34
+ </Text>
35
+ )}
36
+ <Text color={Colors.Foreground}>
37
+ {geminiMdFileCount === 0 ? '4.' : '3.'}{' '}
38
+ <Text bold color={Colors.AccentPurple}>
39
+ /help
40
+ </Text>{' '}
41
+ for more information.
42
+ </Text>
43
+ </Box>
44
+ );
45
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/TodoDisplay.test.tsx ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { render } from 'ink-testing-library';
8
+ import { describe, it, expect } from 'vitest';
9
+ import { TodoItem, TodoDisplay } from './TodoDisplay.js';
10
+
11
+ describe('TodoDisplay', () => {
12
+ const mockTodos: TodoItem[] = [
13
+ {
14
+ id: '1',
15
+ content: 'Complete feature implementation',
16
+ status: 'completed',
17
+ },
18
+ {
19
+ id: '2',
20
+ content: 'Write unit tests',
21
+ status: 'in_progress',
22
+ },
23
+ {
24
+ id: '3',
25
+ content: 'Update documentation',
26
+ status: 'pending',
27
+ },
28
+ ];
29
+
30
+ it('should render todo list', () => {
31
+ const { lastFrame } = render(<TodoDisplay todos={mockTodos} />);
32
+
33
+ const output = lastFrame();
34
+
35
+ // Check all todo items are displayed
36
+ expect(output).toContain('Complete feature implementation');
37
+ expect(output).toContain('Write unit tests');
38
+ expect(output).toContain('Update documentation');
39
+ });
40
+
41
+ it('should display correct status icons', () => {
42
+ const { lastFrame } = render(<TodoDisplay todos={mockTodos} />);
43
+
44
+ const output = lastFrame();
45
+
46
+ // Check status icons are present
47
+ expect(output).toContain('●'); // completed
48
+ expect(output).toContain('◐'); // in_progress
49
+ expect(output).toContain('○'); // pending
50
+ });
51
+
52
+ it('should handle empty todo list', () => {
53
+ const { lastFrame } = render(<TodoDisplay todos={[]} />);
54
+
55
+ const output = lastFrame();
56
+
57
+ // Should render nothing for empty todos
58
+ expect(output).toBe('');
59
+ });
60
+
61
+ it('should handle undefined todos', () => {
62
+ const { lastFrame } = render(
63
+ <TodoDisplay todos={undefined as unknown as TodoItem[]} />,
64
+ );
65
+
66
+ const output = lastFrame();
67
+
68
+ // Should render nothing for undefined todos
69
+ expect(output).toBe('');
70
+ });
71
+
72
+ it('should render tasks with different statuses', () => {
73
+ const allCompleted: TodoItem[] = [
74
+ { id: '1', content: 'Task 1', status: 'completed' },
75
+ { id: '2', content: 'Task 2', status: 'completed' },
76
+ ];
77
+
78
+ const { lastFrame } = render(<TodoDisplay todos={allCompleted} />);
79
+
80
+ const output = lastFrame();
81
+ expect(output).toContain('Task 1');
82
+ expect(output).toContain('Task 2');
83
+ });
84
+
85
+ it('should render tasks with mixed statuses', () => {
86
+ const mixedTodos: TodoItem[] = [
87
+ { id: '1', content: 'Task 1', status: 'pending' },
88
+ { id: '2', content: 'Task 2', status: 'in_progress' },
89
+ ];
90
+
91
+ const { lastFrame } = render(<TodoDisplay todos={mixedTodos} />);
92
+
93
+ const output = lastFrame();
94
+ expect(output).toContain('Task 1');
95
+ expect(output).toContain('Task 2');
96
+ });
97
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/TodoDisplay.tsx ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+
11
+ export interface TodoItem {
12
+ id: string;
13
+ content: string;
14
+ status: 'pending' | 'in_progress' | 'completed';
15
+ }
16
+
17
+ interface TodoDisplayProps {
18
+ todos: TodoItem[];
19
+ }
20
+
21
+ const STATUS_ICONS = {
22
+ pending: '○',
23
+ in_progress: '◐',
24
+ completed: '●',
25
+ } as const;
26
+
27
+ export const TodoDisplay: React.FC<TodoDisplayProps> = ({ todos }) => {
28
+ if (!todos || todos.length === 0) {
29
+ return null;
30
+ }
31
+
32
+ return (
33
+ <Box flexDirection="column">
34
+ {todos.map((todo) => (
35
+ <TodoItemRow key={todo.id} todo={todo} />
36
+ ))}
37
+ </Box>
38
+ );
39
+ };
40
+
41
+ interface TodoItemRowProps {
42
+ todo: TodoItem;
43
+ }
44
+
45
+ const TodoItemRow: React.FC<TodoItemRowProps> = ({ todo }) => {
46
+ const statusIcon = STATUS_ICONS[todo.status];
47
+ const isCompleted = todo.status === 'completed';
48
+ const isInProgress = todo.status === 'in_progress';
49
+
50
+ // Use the same color for both status icon and text, like RadioButtonSelect
51
+ const itemColor = isCompleted
52
+ ? Colors.Foreground
53
+ : isInProgress
54
+ ? Colors.AccentGreen
55
+ : Colors.Foreground;
56
+
57
+ return (
58
+ <Box flexDirection="row" minHeight={1}>
59
+ {/* Status Icon */}
60
+ <Box width={3}>
61
+ <Text color={itemColor}>{statusIcon}</Text>
62
+ </Box>
63
+
64
+ {/* Content */}
65
+ <Box flexGrow={1}>
66
+ <Text color={itemColor} strikethrough={isCompleted} wrap="wrap">
67
+ {todo.content}
68
+ </Text>
69
+ </Box>
70
+ </Box>
71
+ );
72
+ };