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

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/components/DebugProfiler.tsx +36 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/components/DetailedMessagesDisplay.tsx +82 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/components/EditorSettingsDialog.tsx +172 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/components/FolderTrustDialog.test.tsx +36 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/components/FolderTrustDialog.tsx +74 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/components/Footer.test.tsx +159 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/components/Footer.tsx +155 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/components/GeminiRespondingSpinner.tsx +34 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/components/Header.test.tsx +44 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/components/Header.tsx +70 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/components/Help.tsx +174 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/components/HistoryItemDisplay.test.tsx +125 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/components/HistoryItemDisplay.tsx +98 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/components/InputPrompt.test.tsx +1467 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/components/InputPrompt.tsx +641 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/components/LoadingIndicator.test.tsx +296 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/components/LoadingIndicator.tsx +82 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/components/MemoryUsageDisplay.tsx +36 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/components/ModelStatsDisplay.test.tsx +252 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/components/ModelStatsDisplay.tsx +197 -0
projects/ui/qwen-code/packages/cli/src/ui/components/DebugProfiler.tsx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Text } from 'ink';
8
+ import { useEffect, useRef, useState } from 'react';
9
+ import { Colors } from '../colors.js';
10
+ import { useKeypress } from '../hooks/useKeypress.js';
11
+
12
+ export const DebugProfiler = () => {
13
+ const numRenders = useRef(0);
14
+ const [showNumRenders, setShowNumRenders] = useState(false);
15
+
16
+ useEffect(() => {
17
+ numRenders.current++;
18
+ });
19
+
20
+ useKeypress(
21
+ (key) => {
22
+ if (key.ctrl && key.name === 'b') {
23
+ setShowNumRenders((prev) => !prev);
24
+ }
25
+ },
26
+ { isActive: true },
27
+ );
28
+
29
+ if (!showNumRenders) {
30
+ return null;
31
+ }
32
+
33
+ return (
34
+ <Text color={Colors.AccentYellow}>Renders: {numRenders.current} </Text>
35
+ );
36
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/DetailedMessagesDisplay.tsx ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { ConsoleMessageItem } from '../types.js';
11
+ import { MaxSizedBox } from './shared/MaxSizedBox.js';
12
+
13
+ interface DetailedMessagesDisplayProps {
14
+ messages: ConsoleMessageItem[];
15
+ maxHeight: number | undefined;
16
+ width: number;
17
+ // debugMode is not needed here if App.tsx filters debug messages before passing them.
18
+ // If DetailedMessagesDisplay should handle filtering, add debugMode prop.
19
+ }
20
+
21
+ export const DetailedMessagesDisplay: React.FC<
22
+ DetailedMessagesDisplayProps
23
+ > = ({ messages, maxHeight, width }) => {
24
+ if (messages.length === 0) {
25
+ return null; // Don't render anything if there are no messages
26
+ }
27
+
28
+ const borderAndPadding = 4;
29
+ return (
30
+ <Box
31
+ flexDirection="column"
32
+ marginTop={1}
33
+ borderStyle="round"
34
+ borderColor={Colors.Gray}
35
+ paddingX={1}
36
+ width={width}
37
+ >
38
+ <Box marginBottom={1}>
39
+ <Text bold color={Colors.Foreground}>
40
+ Debug Console <Text color={Colors.Gray}>(ctrl+o to close)</Text>
41
+ </Text>
42
+ </Box>
43
+ <MaxSizedBox maxHeight={maxHeight} maxWidth={width - borderAndPadding}>
44
+ {messages.map((msg, index) => {
45
+ let textColor = Colors.Foreground;
46
+ let icon = '\u2139'; // Information source (ℹ)
47
+
48
+ switch (msg.type) {
49
+ case 'warn':
50
+ textColor = Colors.AccentYellow;
51
+ icon = '\u26A0'; // Warning sign (⚠)
52
+ break;
53
+ case 'error':
54
+ textColor = Colors.AccentRed;
55
+ icon = '\u2716'; // Heavy multiplication x (✖)
56
+ break;
57
+ case 'debug':
58
+ textColor = Colors.Gray; // Or Colors.Gray
59
+ icon = '\u1F50D'; // Left-pointing magnifying glass (????)
60
+ break;
61
+ case 'log':
62
+ default:
63
+ // Default textColor and icon are already set
64
+ break;
65
+ }
66
+
67
+ return (
68
+ <Box key={index} flexDirection="row">
69
+ <Text color={textColor}>{icon} </Text>
70
+ <Text color={textColor} wrap="wrap">
71
+ {msg.content}
72
+ {msg.count && msg.count > 1 && (
73
+ <Text color={Colors.Gray}> (x{msg.count})</Text>
74
+ )}
75
+ </Text>
76
+ </Box>
77
+ );
78
+ })}
79
+ </MaxSizedBox>
80
+ </Box>
81
+ );
82
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/EditorSettingsDialog.tsx ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import {
11
+ EDITOR_DISPLAY_NAMES,
12
+ editorSettingsManager,
13
+ type EditorDisplay,
14
+ } from '../editors/editorSettingsManager.js';
15
+ import { RadioButtonSelect } from './shared/RadioButtonSelect.js';
16
+ import { LoadedSettings, SettingScope } from '../../config/settings.js';
17
+ import { EditorType, isEditorAvailable } from '@qwen-code/qwen-code-core';
18
+ import { useKeypress } from '../hooks/useKeypress.js';
19
+
20
+ interface EditorDialogProps {
21
+ onSelect: (editorType: EditorType | undefined, scope: SettingScope) => void;
22
+ settings: LoadedSettings;
23
+ onExit: () => void;
24
+ }
25
+
26
+ export function EditorSettingsDialog({
27
+ onSelect,
28
+ settings,
29
+ onExit,
30
+ }: EditorDialogProps): React.JSX.Element {
31
+ const [selectedScope, setSelectedScope] = useState<SettingScope>(
32
+ SettingScope.User,
33
+ );
34
+ const [focusedSection, setFocusedSection] = useState<'editor' | 'scope'>(
35
+ 'editor',
36
+ );
37
+ useKeypress(
38
+ (key) => {
39
+ if (key.name === 'tab') {
40
+ setFocusedSection((prev) => (prev === 'editor' ? 'scope' : 'editor'));
41
+ }
42
+ if (key.name === 'escape') {
43
+ onExit();
44
+ }
45
+ },
46
+ { isActive: true },
47
+ );
48
+
49
+ const editorItems: EditorDisplay[] =
50
+ editorSettingsManager.getAvailableEditorDisplays();
51
+
52
+ const currentPreference =
53
+ settings.forScope(selectedScope).settings.preferredEditor;
54
+ let editorIndex = currentPreference
55
+ ? editorItems.findIndex(
56
+ (item: EditorDisplay) => item.type === currentPreference,
57
+ )
58
+ : 0;
59
+ if (editorIndex === -1) {
60
+ console.error(`Editor is not supported: ${currentPreference}`);
61
+ editorIndex = 0;
62
+ }
63
+
64
+ const scopeItems = [
65
+ { label: 'User Settings', value: SettingScope.User },
66
+ { label: 'Workspace Settings', value: SettingScope.Workspace },
67
+ ];
68
+
69
+ const handleEditorSelect = (editorType: EditorType | 'not_set') => {
70
+ if (editorType === 'not_set') {
71
+ onSelect(undefined, selectedScope);
72
+ return;
73
+ }
74
+ onSelect(editorType, selectedScope);
75
+ };
76
+
77
+ const handleScopeSelect = (scope: SettingScope) => {
78
+ setSelectedScope(scope);
79
+ setFocusedSection('editor');
80
+ };
81
+
82
+ let otherScopeModifiedMessage = '';
83
+ const otherScope =
84
+ selectedScope === SettingScope.User
85
+ ? SettingScope.Workspace
86
+ : SettingScope.User;
87
+ if (settings.forScope(otherScope).settings.preferredEditor !== undefined) {
88
+ otherScopeModifiedMessage =
89
+ settings.forScope(selectedScope).settings.preferredEditor !== undefined
90
+ ? `(Also modified in ${otherScope})`
91
+ : `(Modified in ${otherScope})`;
92
+ }
93
+
94
+ let mergedEditorName = 'None';
95
+ if (
96
+ settings.merged.preferredEditor &&
97
+ isEditorAvailable(settings.merged.preferredEditor)
98
+ ) {
99
+ mergedEditorName =
100
+ EDITOR_DISPLAY_NAMES[settings.merged.preferredEditor as EditorType];
101
+ }
102
+
103
+ return (
104
+ <Box
105
+ borderStyle="round"
106
+ borderColor={Colors.Gray}
107
+ flexDirection="row"
108
+ padding={1}
109
+ width="100%"
110
+ >
111
+ <Box flexDirection="column" width="45%" paddingRight={2}>
112
+ <Text bold={focusedSection === 'editor'}>
113
+ {focusedSection === 'editor' ? '> ' : ' '}Select Editor{' '}
114
+ <Text color={Colors.Gray}>{otherScopeModifiedMessage}</Text>
115
+ </Text>
116
+ <RadioButtonSelect
117
+ items={editorItems.map((item) => ({
118
+ label: item.name,
119
+ value: item.type,
120
+ disabled: item.disabled,
121
+ }))}
122
+ initialIndex={editorIndex}
123
+ onSelect={handleEditorSelect}
124
+ isFocused={focusedSection === 'editor'}
125
+ key={selectedScope}
126
+ />
127
+
128
+ <Box marginTop={1} flexDirection="column">
129
+ <Text bold={focusedSection === 'scope'}>
130
+ {focusedSection === 'scope' ? '> ' : ' '}Apply To
131
+ </Text>
132
+ <RadioButtonSelect
133
+ items={scopeItems}
134
+ initialIndex={0}
135
+ onSelect={handleScopeSelect}
136
+ isFocused={focusedSection === 'scope'}
137
+ />
138
+ </Box>
139
+
140
+ <Box marginTop={1}>
141
+ <Text color={Colors.Gray}>
142
+ (Use Enter to select, Tab to change focus)
143
+ </Text>
144
+ </Box>
145
+ </Box>
146
+
147
+ <Box flexDirection="column" width="55%" paddingLeft={2}>
148
+ <Text bold>Editor Preference</Text>
149
+ <Box flexDirection="column" gap={1} marginTop={1}>
150
+ <Text color={Colors.Gray}>
151
+ These editors are currently supported. Please note that some editors
152
+ cannot be used in sandbox mode.
153
+ </Text>
154
+ <Text color={Colors.Gray}>
155
+ Your preferred editor is:{' '}
156
+ <Text
157
+ color={
158
+ mergedEditorName === 'None'
159
+ ? Colors.AccentRed
160
+ : Colors.AccentCyan
161
+ }
162
+ bold
163
+ >
164
+ {mergedEditorName}
165
+ </Text>
166
+ .
167
+ </Text>
168
+ </Box>
169
+ </Box>
170
+ </Box>
171
+ );
172
+ }
projects/ui/qwen-code/packages/cli/src/ui/components/FolderTrustDialog.test.tsx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { waitFor } from '@testing-library/react';
9
+ import { vi } from 'vitest';
10
+ import { FolderTrustDialog, FolderTrustChoice } from './FolderTrustDialog.js';
11
+
12
+ describe('FolderTrustDialog', () => {
13
+ it('should render the dialog with title and description', () => {
14
+ const { lastFrame } = renderWithProviders(
15
+ <FolderTrustDialog onSelect={vi.fn()} />,
16
+ );
17
+
18
+ expect(lastFrame()).toContain('Do you trust this folder?');
19
+ expect(lastFrame()).toContain(
20
+ 'Trusting a folder allows Gemini to execute commands it suggests.',
21
+ );
22
+ });
23
+
24
+ it('should call onSelect with DO_NOT_TRUST when escape is pressed', async () => {
25
+ const onSelect = vi.fn();
26
+ const { stdin } = renderWithProviders(
27
+ <FolderTrustDialog onSelect={onSelect} />,
28
+ );
29
+
30
+ stdin.write('\x1b');
31
+
32
+ await waitFor(() => {
33
+ expect(onSelect).toHaveBeenCalledWith(FolderTrustChoice.DO_NOT_TRUST);
34
+ });
35
+ });
36
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/FolderTrustDialog.tsx ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 React from 'react';
9
+ import { Colors } from '../colors.js';
10
+ import {
11
+ RadioButtonSelect,
12
+ RadioSelectItem,
13
+ } from './shared/RadioButtonSelect.js';
14
+ import { useKeypress } from '../hooks/useKeypress.js';
15
+
16
+ export enum FolderTrustChoice {
17
+ TRUST_FOLDER = 'trust_folder',
18
+ TRUST_PARENT = 'trust_parent',
19
+ DO_NOT_TRUST = 'do_not_trust',
20
+ }
21
+
22
+ interface FolderTrustDialogProps {
23
+ onSelect: (choice: FolderTrustChoice) => void;
24
+ }
25
+
26
+ export const FolderTrustDialog: React.FC<FolderTrustDialogProps> = ({
27
+ onSelect,
28
+ }) => {
29
+ useKeypress(
30
+ (key) => {
31
+ if (key.name === 'escape') {
32
+ onSelect(FolderTrustChoice.DO_NOT_TRUST);
33
+ }
34
+ },
35
+ { isActive: true },
36
+ );
37
+
38
+ const options: Array<RadioSelectItem<FolderTrustChoice>> = [
39
+ {
40
+ label: 'Trust folder',
41
+ value: FolderTrustChoice.TRUST_FOLDER,
42
+ },
43
+ {
44
+ label: 'Trust parent folder',
45
+ value: FolderTrustChoice.TRUST_PARENT,
46
+ },
47
+ {
48
+ label: "Don't trust (esc)",
49
+ value: FolderTrustChoice.DO_NOT_TRUST,
50
+ },
51
+ ];
52
+
53
+ return (
54
+ <Box
55
+ flexDirection="column"
56
+ borderStyle="round"
57
+ borderColor={Colors.AccentYellow}
58
+ padding={1}
59
+ width="100%"
60
+ marginLeft={1}
61
+ >
62
+ <Box flexDirection="column" marginBottom={1}>
63
+ <Text bold>Do you trust this folder?</Text>
64
+ <Text>
65
+ Trusting a folder allows Gemini to execute commands it suggests. This
66
+ is a security feature to prevent accidental execution in untrusted
67
+ directories.
68
+ </Text>
69
+ </Box>
70
+
71
+ <RadioButtonSelect items={options} onSelect={onSelect} isFocused />
72
+ </Box>
73
+ );
74
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/Footer.test.tsx ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { Footer } from './Footer.js';
10
+ import * as useTerminalSize from '../hooks/useTerminalSize.js';
11
+ import { tildeifyPath } from '@qwen-code/qwen-code-core';
12
+ import path from 'node:path';
13
+
14
+ vi.mock('../hooks/useTerminalSize.js');
15
+ const useTerminalSizeMock = vi.mocked(useTerminalSize.useTerminalSize);
16
+
17
+ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
18
+ const original =
19
+ await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
20
+ return {
21
+ ...original,
22
+ shortenPath: (p: string, len: number) => {
23
+ if (p.length > len) {
24
+ return '...' + p.slice(p.length - len + 3);
25
+ }
26
+ return p;
27
+ },
28
+ };
29
+ });
30
+
31
+ const defaultProps = {
32
+ model: 'gemini-pro',
33
+ targetDir:
34
+ '/Users/test/project/foo/bar/and/some/more/directories/to/make/it/long',
35
+ branchName: 'main',
36
+ debugMode: false,
37
+ debugMessage: '',
38
+ corgiMode: false,
39
+ errorCount: 0,
40
+ showErrorDetails: false,
41
+ showMemoryUsage: false,
42
+ promptTokenCount: 100,
43
+ nightly: false,
44
+ };
45
+
46
+ const renderWithWidth = (width: number, props = defaultProps) => {
47
+ useTerminalSizeMock.mockReturnValue({ columns: width, rows: 24 });
48
+ return render(<Footer {...props} />);
49
+ };
50
+
51
+ describe('<Footer />', () => {
52
+ it('renders the component', () => {
53
+ const { lastFrame } = renderWithWidth(120);
54
+ expect(lastFrame()).toBeDefined();
55
+ });
56
+
57
+ describe('path display', () => {
58
+ it('should display shortened path on a wide terminal', () => {
59
+ const { lastFrame } = renderWithWidth(120);
60
+ const tildePath = tildeifyPath(defaultProps.targetDir);
61
+ const expectedPath = '...' + tildePath.slice(tildePath.length - 48 + 3);
62
+ expect(lastFrame()).toContain(expectedPath);
63
+ });
64
+
65
+ it('should display only the base directory name on a narrow terminal', () => {
66
+ const { lastFrame } = renderWithWidth(79);
67
+ const expectedPath = path.basename(defaultProps.targetDir);
68
+ expect(lastFrame()).toContain(expectedPath);
69
+ });
70
+
71
+ it('should use wide layout at 80 columns', () => {
72
+ const { lastFrame } = renderWithWidth(80);
73
+ const tildePath = tildeifyPath(defaultProps.targetDir);
74
+ const expectedPath = '...' + tildePath.slice(tildePath.length - 32 + 3);
75
+ expect(lastFrame()).toContain(expectedPath);
76
+ });
77
+
78
+ it('should use narrow layout at 79 columns', () => {
79
+ const { lastFrame } = renderWithWidth(79);
80
+ const expectedPath = path.basename(defaultProps.targetDir);
81
+ expect(lastFrame()).toContain(expectedPath);
82
+ const tildePath = tildeifyPath(defaultProps.targetDir);
83
+ const unexpectedPath = '...' + tildePath.slice(tildePath.length - 31 + 3);
84
+ expect(lastFrame()).not.toContain(unexpectedPath);
85
+ });
86
+ });
87
+
88
+ it('displays the branch name when provided', () => {
89
+ const { lastFrame } = renderWithWidth(120);
90
+ expect(lastFrame()).toContain(`(${defaultProps.branchName}*)`);
91
+ });
92
+
93
+ it('does not display the branch name when not provided', () => {
94
+ const { lastFrame } = renderWithWidth(120, {
95
+ ...defaultProps,
96
+ branchName: undefined,
97
+ });
98
+ expect(lastFrame()).not.toContain(`(${defaultProps.branchName}*)`);
99
+ });
100
+
101
+ it('displays the model name and context percentage', () => {
102
+ const { lastFrame } = renderWithWidth(120);
103
+ expect(lastFrame()).toContain(defaultProps.model);
104
+ expect(lastFrame()).toMatch(/\(\d+% context[\s\S]*left\)/);
105
+ });
106
+
107
+ describe('sandbox and trust info', () => {
108
+ it('should display untrusted when isTrustedFolder is false', () => {
109
+ const { lastFrame } = renderWithWidth(120, {
110
+ ...defaultProps,
111
+ isTrustedFolder: false,
112
+ });
113
+ expect(lastFrame()).toContain('untrusted');
114
+ });
115
+
116
+ it('should display custom sandbox info when SANDBOX env is set', () => {
117
+ vi.stubEnv('SANDBOX', 'gemini-cli-test-sandbox');
118
+ const { lastFrame } = renderWithWidth(120, {
119
+ ...defaultProps,
120
+ isTrustedFolder: undefined,
121
+ });
122
+ expect(lastFrame()).toContain('test');
123
+ vi.unstubAllEnvs();
124
+ });
125
+
126
+ it('should display macOS Seatbelt info when SANDBOX is sandbox-exec', () => {
127
+ vi.stubEnv('SANDBOX', 'sandbox-exec');
128
+ vi.stubEnv('SEATBELT_PROFILE', 'test-profile');
129
+ const { lastFrame } = renderWithWidth(120, {
130
+ ...defaultProps,
131
+ isTrustedFolder: true,
132
+ });
133
+ expect(lastFrame()).toMatch(/macOS Seatbelt.*\(test-profile\)/s);
134
+ vi.unstubAllEnvs();
135
+ });
136
+
137
+ it('should display "no sandbox" when SANDBOX is not set and folder is trusted', () => {
138
+ // Clear any SANDBOX env var that might be set.
139
+ vi.stubEnv('SANDBOX', '');
140
+ const { lastFrame } = renderWithWidth(120, {
141
+ ...defaultProps,
142
+ isTrustedFolder: true,
143
+ });
144
+ expect(lastFrame()).toContain('no sandbox');
145
+ vi.unstubAllEnvs();
146
+ });
147
+
148
+ it('should prioritize untrusted message over sandbox info', () => {
149
+ vi.stubEnv('SANDBOX', 'gemini-cli-test-sandbox');
150
+ const { lastFrame } = renderWithWidth(120, {
151
+ ...defaultProps,
152
+ isTrustedFolder: false,
153
+ });
154
+ expect(lastFrame()).toContain('untrusted');
155
+ expect(lastFrame()).not.toMatch(/test-sandbox/s);
156
+ vi.unstubAllEnvs();
157
+ });
158
+ });
159
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/Footer.tsx ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { theme } from '../semantic-colors.js';
10
+ import { shortenPath, tildeifyPath } from '@qwen-code/qwen-code-core';
11
+ import { ConsoleSummaryDisplay } from './ConsoleSummaryDisplay.js';
12
+ import process from 'node:process';
13
+ import path from 'node:path';
14
+ import Gradient from 'ink-gradient';
15
+ import { MemoryUsageDisplay } from './MemoryUsageDisplay.js';
16
+ import { ContextUsageDisplay } from './ContextUsageDisplay.js';
17
+ import { DebugProfiler } from './DebugProfiler.js';
18
+
19
+ import { useTerminalSize } from '../hooks/useTerminalSize.js';
20
+ import { isNarrowWidth } from '../utils/isNarrowWidth.js';
21
+
22
+ interface FooterProps {
23
+ model: string;
24
+ targetDir: string;
25
+ branchName?: string;
26
+ debugMode: boolean;
27
+ debugMessage: string;
28
+ corgiMode: boolean;
29
+ errorCount: number;
30
+ showErrorDetails: boolean;
31
+ showMemoryUsage?: boolean;
32
+ promptTokenCount: number;
33
+ nightly: boolean;
34
+ vimMode?: string;
35
+ isTrustedFolder?: boolean;
36
+ }
37
+
38
+ export const Footer: React.FC<FooterProps> = ({
39
+ model,
40
+ targetDir,
41
+ branchName,
42
+ debugMode,
43
+ debugMessage,
44
+ corgiMode,
45
+ errorCount,
46
+ showErrorDetails,
47
+ showMemoryUsage,
48
+ promptTokenCount,
49
+ nightly,
50
+ vimMode,
51
+ isTrustedFolder,
52
+ }) => {
53
+ const { columns: terminalWidth } = useTerminalSize();
54
+
55
+ const isNarrow = isNarrowWidth(terminalWidth);
56
+
57
+ // Adjust path length based on terminal width
58
+ const pathLength = Math.max(20, Math.floor(terminalWidth * 0.4));
59
+ const displayPath = isNarrow
60
+ ? path.basename(tildeifyPath(targetDir))
61
+ : shortenPath(tildeifyPath(targetDir), pathLength);
62
+
63
+ return (
64
+ <Box
65
+ justifyContent="space-between"
66
+ width="100%"
67
+ flexDirection={isNarrow ? 'column' : 'row'}
68
+ alignItems={isNarrow ? 'flex-start' : 'center'}
69
+ >
70
+ <Box>
71
+ {debugMode && <DebugProfiler />}
72
+ {vimMode && <Text color={theme.text.secondary}>[{vimMode}] </Text>}
73
+ {nightly ? (
74
+ <Gradient colors={theme.ui.gradient}>
75
+ <Text>
76
+ {displayPath}
77
+ {branchName && <Text> ({branchName}*)</Text>}
78
+ </Text>
79
+ </Gradient>
80
+ ) : (
81
+ <Text color={theme.text.link}>
82
+ {displayPath}
83
+ {branchName && (
84
+ <Text color={theme.text.secondary}> ({branchName}*)</Text>
85
+ )}
86
+ </Text>
87
+ )}
88
+ {debugMode && (
89
+ <Text color={theme.status.error}>
90
+ {' ' + (debugMessage || '--debug')}
91
+ </Text>
92
+ )}
93
+ </Box>
94
+
95
+ {/* Middle Section: Centered Trust/Sandbox Info */}
96
+ <Box
97
+ flexGrow={isNarrow ? 0 : 1}
98
+ alignItems="center"
99
+ justifyContent={isNarrow ? 'flex-start' : 'center'}
100
+ display="flex"
101
+ paddingX={isNarrow ? 0 : 1}
102
+ paddingTop={isNarrow ? 1 : 0}
103
+ >
104
+ {isTrustedFolder === false ? (
105
+ <Text color={theme.status.warning}>untrusted</Text>
106
+ ) : process.env['SANDBOX'] &&
107
+ process.env['SANDBOX'] !== 'sandbox-exec' ? (
108
+ <Text color="green">
109
+ {process.env['SANDBOX'].replace(/^gemini-(?:cli-)?/, '')}
110
+ </Text>
111
+ ) : process.env['SANDBOX'] === 'sandbox-exec' ? (
112
+ <Text color={theme.status.warning}>
113
+ macOS Seatbelt{' '}
114
+ <Text color={theme.text.secondary}>
115
+ ({process.env['SEATBELT_PROFILE']})
116
+ </Text>
117
+ </Text>
118
+ ) : (
119
+ <Text color={theme.status.error}>
120
+ no sandbox <Text color={theme.text.secondary}>(see /docs)</Text>
121
+ </Text>
122
+ )}
123
+ </Box>
124
+
125
+ {/* Right Section: Gemini Label and Console Summary */}
126
+ <Box alignItems="center" paddingTop={isNarrow ? 1 : 0}>
127
+ <Text color={theme.text.accent}>
128
+ {isNarrow ? '' : ' '}
129
+ {model}{' '}
130
+ <ContextUsageDisplay
131
+ promptTokenCount={promptTokenCount}
132
+ model={model}
133
+ />
134
+ </Text>
135
+ {corgiMode && (
136
+ <Text>
137
+ <Text color={theme.ui.symbol}>| </Text>
138
+ <Text color={theme.status.error}>▼</Text>
139
+ <Text color={theme.text.primary}>(´</Text>
140
+ <Text color={theme.status.error}>ᴥ</Text>
141
+ <Text color={theme.text.primary}>`)</Text>
142
+ <Text color={theme.status.error}>▼ </Text>
143
+ </Text>
144
+ )}
145
+ {!showErrorDetails && errorCount > 0 && (
146
+ <Box>
147
+ <Text color={theme.ui.symbol}>| </Text>
148
+ <ConsoleSummaryDisplay errorCount={errorCount} />
149
+ </Box>
150
+ )}
151
+ {showMemoryUsage && <MemoryUsageDisplay />}
152
+ </Box>
153
+ </Box>
154
+ );
155
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/GeminiRespondingSpinner.tsx ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Spinner from 'ink-spinner';
10
+ import type { SpinnerName } from 'cli-spinners';
11
+ import { useStreamingContext } from '../contexts/StreamingContext.js';
12
+ import { StreamingState } from '../types.js';
13
+
14
+ interface GeminiRespondingSpinnerProps {
15
+ /**
16
+ * Optional string to display when not in Responding state.
17
+ * If not provided and not Responding, renders null.
18
+ */
19
+ nonRespondingDisplay?: string;
20
+ spinnerType?: SpinnerName;
21
+ }
22
+
23
+ export const GeminiRespondingSpinner: React.FC<
24
+ GeminiRespondingSpinnerProps
25
+ > = ({ nonRespondingDisplay, spinnerType = 'dots' }) => {
26
+ const streamingState = useStreamingContext();
27
+
28
+ if (streamingState === StreamingState.Responding) {
29
+ return <Spinner type={spinnerType} />;
30
+ } else if (nonRespondingDisplay) {
31
+ return <Text>{nonRespondingDisplay}</Text>;
32
+ }
33
+ return null;
34
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/Header.test.tsx ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, beforeEach } from 'vitest';
9
+ import { Header } from './Header.js';
10
+ import * as useTerminalSize from '../hooks/useTerminalSize.js';
11
+ import { longAsciiLogo } from './AsciiArt.js';
12
+
13
+ vi.mock('../hooks/useTerminalSize.js');
14
+
15
+ describe('<Header />', () => {
16
+ beforeEach(() => {});
17
+
18
+ it('renders the long logo on a wide terminal', () => {
19
+ vi.spyOn(useTerminalSize, 'useTerminalSize').mockReturnValue({
20
+ columns: 120,
21
+ rows: 20,
22
+ });
23
+ const { lastFrame } = render(<Header version="1.0.0" nightly={false} />);
24
+ expect(lastFrame()).toContain(longAsciiLogo);
25
+ });
26
+
27
+ it('renders custom ASCII art when provided', () => {
28
+ const customArt = 'CUSTOM ART';
29
+ const { lastFrame } = render(
30
+ <Header version="1.0.0" nightly={false} customAsciiArt={customArt} />,
31
+ );
32
+ expect(lastFrame()).toContain(customArt);
33
+ });
34
+
35
+ it('displays the version number when nightly is true', () => {
36
+ const { lastFrame } = render(<Header version="1.0.0" nightly={true} />);
37
+ expect(lastFrame()).toContain('v1.0.0');
38
+ });
39
+
40
+ it('does not display the version number when nightly is false', () => {
41
+ const { lastFrame } = render(<Header version="1.0.0" nightly={false} />);
42
+ expect(lastFrame()).not.toContain('v1.0.0');
43
+ });
44
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/Header.tsx ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { Colors } from '../colors.js';
11
+ import { shortAsciiLogo, longAsciiLogo, tinyAsciiLogo } from './AsciiArt.js';
12
+ import { getAsciiArtWidth } from '../utils/textUtils.js';
13
+ import { useTerminalSize } from '../hooks/useTerminalSize.js';
14
+
15
+ interface HeaderProps {
16
+ customAsciiArt?: string; // For user-defined ASCII art
17
+ version: string;
18
+ nightly: boolean;
19
+ }
20
+
21
+ export const Header: React.FC<HeaderProps> = ({
22
+ customAsciiArt,
23
+ version,
24
+ nightly,
25
+ }) => {
26
+ const { columns: terminalWidth } = useTerminalSize();
27
+ let displayTitle;
28
+ const widthOfLongLogo = getAsciiArtWidth(longAsciiLogo);
29
+ const widthOfShortLogo = getAsciiArtWidth(shortAsciiLogo);
30
+
31
+ if (customAsciiArt) {
32
+ displayTitle = customAsciiArt;
33
+ } else if (terminalWidth >= widthOfLongLogo) {
34
+ displayTitle = longAsciiLogo;
35
+ } else if (terminalWidth >= widthOfShortLogo) {
36
+ displayTitle = shortAsciiLogo;
37
+ } else {
38
+ displayTitle = tinyAsciiLogo;
39
+ }
40
+
41
+ const artWidth = getAsciiArtWidth(displayTitle);
42
+
43
+ return (
44
+ <Box
45
+ alignItems="flex-start"
46
+ width={artWidth}
47
+ flexShrink={0}
48
+ flexDirection="column"
49
+ >
50
+ {Colors.GradientColors ? (
51
+ <Gradient colors={Colors.GradientColors}>
52
+ <Text>{displayTitle}</Text>
53
+ </Gradient>
54
+ ) : (
55
+ <Text>{displayTitle}</Text>
56
+ )}
57
+ {nightly && (
58
+ <Box width="100%" flexDirection="row" justifyContent="flex-end">
59
+ {Colors.GradientColors ? (
60
+ <Gradient colors={Colors.GradientColors}>
61
+ <Text>v{version}</Text>
62
+ </Gradient>
63
+ ) : (
64
+ <Text>v{version}</Text>
65
+ )}
66
+ </Box>
67
+ )}
68
+ </Box>
69
+ );
70
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/Help.tsx ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { SlashCommand } from '../commands/types.js';
11
+
12
+ interface Help {
13
+ commands: readonly SlashCommand[];
14
+ }
15
+
16
+ export const Help: React.FC<Help> = ({ commands }) => (
17
+ <Box
18
+ flexDirection="column"
19
+ marginBottom={1}
20
+ borderColor={Colors.Gray}
21
+ borderStyle="round"
22
+ padding={1}
23
+ >
24
+ {/* Basics */}
25
+ <Text bold color={Colors.Foreground}>
26
+ Basics:
27
+ </Text>
28
+ <Text color={Colors.Foreground}>
29
+ <Text bold color={Colors.AccentPurple}>
30
+ Add context
31
+ </Text>
32
+ : Use{' '}
33
+ <Text bold color={Colors.AccentPurple}>
34
+ @
35
+ </Text>{' '}
36
+ to specify files for context (e.g.,{' '}
37
+ <Text bold color={Colors.AccentPurple}>
38
+ @src/myFile.ts
39
+ </Text>
40
+ ) to target specific files or folders.
41
+ </Text>
42
+ <Text color={Colors.Foreground}>
43
+ <Text bold color={Colors.AccentPurple}>
44
+ Shell mode
45
+ </Text>
46
+ : Execute shell commands via{' '}
47
+ <Text bold color={Colors.AccentPurple}>
48
+ !
49
+ </Text>{' '}
50
+ (e.g.,{' '}
51
+ <Text bold color={Colors.AccentPurple}>
52
+ !npm run start
53
+ </Text>
54
+ ) or use natural language (e.g.{' '}
55
+ <Text bold color={Colors.AccentPurple}>
56
+ start server
57
+ </Text>
58
+ ).
59
+ </Text>
60
+
61
+ <Box height={1} />
62
+
63
+ {/* Commands */}
64
+ <Text bold color={Colors.Foreground}>
65
+ Commands:
66
+ </Text>
67
+ {commands
68
+ .filter((command) => command.description)
69
+ .map((command: SlashCommand) => (
70
+ <Box key={command.name} flexDirection="column">
71
+ <Text color={Colors.Foreground}>
72
+ <Text bold color={Colors.AccentPurple}>
73
+ {' '}
74
+ /{command.name}
75
+ </Text>
76
+ {command.description && ' - ' + command.description}
77
+ </Text>
78
+ {command.subCommands &&
79
+ command.subCommands.map((subCommand) => (
80
+ <Text key={subCommand.name} color={Colors.Foreground}>
81
+ <Text bold color={Colors.AccentPurple}>
82
+ {' '}
83
+ {subCommand.name}
84
+ </Text>
85
+ {subCommand.description && ' - ' + subCommand.description}
86
+ </Text>
87
+ ))}
88
+ </Box>
89
+ ))}
90
+ <Text color={Colors.Foreground}>
91
+ <Text bold color={Colors.AccentPurple}>
92
+ {' '}
93
+ !{' '}
94
+ </Text>
95
+ - shell command
96
+ </Text>
97
+
98
+ <Box height={1} />
99
+
100
+ {/* Shortcuts */}
101
+ <Text bold color={Colors.Foreground}>
102
+ Keyboard Shortcuts:
103
+ </Text>
104
+ <Text color={Colors.Foreground}>
105
+ <Text bold color={Colors.AccentPurple}>
106
+ Alt+Left/Right
107
+ </Text>{' '}
108
+ - Jump through words in the input
109
+ </Text>
110
+ <Text color={Colors.Foreground}>
111
+ <Text bold color={Colors.AccentPurple}>
112
+ Ctrl+C
113
+ </Text>{' '}
114
+ - Quit application
115
+ </Text>
116
+ <Text color={Colors.Foreground}>
117
+ <Text bold color={Colors.AccentPurple}>
118
+ {process.platform === 'win32' ? 'Ctrl+Enter' : 'Ctrl+J'}
119
+ </Text>{' '}
120
+ {process.platform === 'linux'
121
+ ? '- New line (Alt+Enter works for certain linux distros)'
122
+ : '- New line'}
123
+ </Text>
124
+ <Text color={Colors.Foreground}>
125
+ <Text bold color={Colors.AccentPurple}>
126
+ Ctrl+L
127
+ </Text>{' '}
128
+ - Clear the screen
129
+ </Text>
130
+ <Text color={Colors.Foreground}>
131
+ <Text bold color={Colors.AccentPurple}>
132
+ {process.platform === 'darwin' ? 'Ctrl+X / Meta+Enter' : 'Ctrl+X'}
133
+ </Text>{' '}
134
+ - Open input in external editor
135
+ </Text>
136
+ <Text color={Colors.Foreground}>
137
+ <Text bold color={Colors.AccentPurple}>
138
+ Ctrl+Y
139
+ </Text>{' '}
140
+ - Toggle YOLO mode
141
+ </Text>
142
+ <Text color={Colors.Foreground}>
143
+ <Text bold color={Colors.AccentPurple}>
144
+ Enter
145
+ </Text>{' '}
146
+ - Send message
147
+ </Text>
148
+ <Text color={Colors.Foreground}>
149
+ <Text bold color={Colors.AccentPurple}>
150
+ Esc
151
+ </Text>{' '}
152
+ - Cancel operation
153
+ </Text>
154
+ <Text color={Colors.Foreground}>
155
+ <Text bold color={Colors.AccentPurple}>
156
+ Shift+Tab
157
+ </Text>{' '}
158
+ - Toggle auto-accepting edits
159
+ </Text>
160
+ <Text color={Colors.Foreground}>
161
+ <Text bold color={Colors.AccentPurple}>
162
+ Up/Down
163
+ </Text>{' '}
164
+ - Cycle through your prompt history
165
+ </Text>
166
+ <Box height={1} />
167
+ <Text color={Colors.Foreground}>
168
+ For a full list of shortcuts, see{' '}
169
+ <Text bold color={Colors.AccentPurple}>
170
+ docs/keyboard-shortcuts.md
171
+ </Text>
172
+ </Text>
173
+ </Box>
174
+ );
projects/ui/qwen-code/packages/cli/src/ui/components/HistoryItemDisplay.test.tsx ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { HistoryItemDisplay } from './HistoryItemDisplay.js';
10
+ import { HistoryItem, MessageType } from '../types.js';
11
+ import { SessionStatsProvider } from '../contexts/SessionContext.js';
12
+
13
+ // Mock child components
14
+ vi.mock('./messages/ToolGroupMessage.js', () => ({
15
+ ToolGroupMessage: () => <div />,
16
+ }));
17
+
18
+ describe('<HistoryItemDisplay />', () => {
19
+ const baseItem = {
20
+ id: 1,
21
+ timestamp: 12345,
22
+ isPending: false,
23
+ terminalWidth: 80,
24
+ };
25
+
26
+ it('renders UserMessage for "user" type', () => {
27
+ const item: HistoryItem = {
28
+ ...baseItem,
29
+ type: MessageType.USER,
30
+ text: 'Hello',
31
+ };
32
+ const { lastFrame } = render(
33
+ <HistoryItemDisplay {...baseItem} item={item} />,
34
+ );
35
+ expect(lastFrame()).toContain('Hello');
36
+ });
37
+
38
+ it('renders UserMessage for "user" type with slash command', () => {
39
+ const item: HistoryItem = {
40
+ ...baseItem,
41
+ type: MessageType.USER,
42
+ text: '/theme',
43
+ };
44
+ const { lastFrame } = render(
45
+ <HistoryItemDisplay {...baseItem} item={item} />,
46
+ );
47
+ expect(lastFrame()).toContain('/theme');
48
+ });
49
+
50
+ it('renders StatsDisplay for "stats" type', () => {
51
+ const item: HistoryItem = {
52
+ ...baseItem,
53
+ type: MessageType.STATS,
54
+ duration: '1s',
55
+ };
56
+ const { lastFrame } = render(
57
+ <SessionStatsProvider>
58
+ <HistoryItemDisplay {...baseItem} item={item} />
59
+ </SessionStatsProvider>,
60
+ );
61
+ expect(lastFrame()).toContain('Stats');
62
+ });
63
+
64
+ it('renders AboutBox for "about" type', () => {
65
+ const item: HistoryItem = {
66
+ ...baseItem,
67
+ type: MessageType.ABOUT,
68
+ cliVersion: '1.0.0',
69
+ osVersion: 'test-os',
70
+ sandboxEnv: 'test-env',
71
+ modelVersion: 'test-model',
72
+ selectedAuthType: 'test-auth',
73
+ gcpProject: 'test-project',
74
+ ideClient: 'test-ide',
75
+ };
76
+ const { lastFrame } = render(
77
+ <HistoryItemDisplay {...baseItem} item={item} />,
78
+ );
79
+ expect(lastFrame()).toContain('About Qwen Code');
80
+ });
81
+
82
+ it('renders ModelStatsDisplay for "model_stats" type', () => {
83
+ const item: HistoryItem = {
84
+ ...baseItem,
85
+ type: 'model_stats',
86
+ };
87
+ const { lastFrame } = render(
88
+ <SessionStatsProvider>
89
+ <HistoryItemDisplay {...baseItem} item={item} />
90
+ </SessionStatsProvider>,
91
+ );
92
+ expect(lastFrame()).toContain(
93
+ 'No API calls have been made in this session.',
94
+ );
95
+ });
96
+
97
+ it('renders ToolStatsDisplay for "tool_stats" type', () => {
98
+ const item: HistoryItem = {
99
+ ...baseItem,
100
+ type: 'tool_stats',
101
+ };
102
+ const { lastFrame } = render(
103
+ <SessionStatsProvider>
104
+ <HistoryItemDisplay {...baseItem} item={item} />
105
+ </SessionStatsProvider>,
106
+ );
107
+ expect(lastFrame()).toContain(
108
+ 'No tool calls have been made in this session.',
109
+ );
110
+ });
111
+
112
+ it('renders SessionSummaryDisplay for "quit" type', () => {
113
+ const item: HistoryItem = {
114
+ ...baseItem,
115
+ type: 'quit',
116
+ duration: '1s',
117
+ };
118
+ const { lastFrame } = render(
119
+ <SessionStatsProvider>
120
+ <HistoryItemDisplay {...baseItem} item={item} />
121
+ </SessionStatsProvider>,
122
+ );
123
+ expect(lastFrame()).toContain('Agent powering down. Goodbye!');
124
+ });
125
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/HistoryItemDisplay.tsx ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import type { HistoryItem } from '../types.js';
9
+ import { UserMessage } from './messages/UserMessage.js';
10
+ import { UserShellMessage } from './messages/UserShellMessage.js';
11
+ import { GeminiMessage } from './messages/GeminiMessage.js';
12
+ import { InfoMessage } from './messages/InfoMessage.js';
13
+ import { ErrorMessage } from './messages/ErrorMessage.js';
14
+ import { ToolGroupMessage } from './messages/ToolGroupMessage.js';
15
+ import { GeminiMessageContent } from './messages/GeminiMessageContent.js';
16
+ import { CompressionMessage } from './messages/CompressionMessage.js';
17
+ import { Box } from 'ink';
18
+ import { AboutBox } from './AboutBox.js';
19
+ import { StatsDisplay } from './StatsDisplay.js';
20
+ import { ModelStatsDisplay } from './ModelStatsDisplay.js';
21
+ import { ToolStatsDisplay } from './ToolStatsDisplay.js';
22
+ import { SessionSummaryDisplay } from './SessionSummaryDisplay.js';
23
+ import { Config } from '@qwen-code/qwen-code-core';
24
+ import { Help } from './Help.js';
25
+ import { SlashCommand } from '../commands/types.js';
26
+
27
+ interface HistoryItemDisplayProps {
28
+ item: HistoryItem;
29
+ availableTerminalHeight?: number;
30
+ terminalWidth: number;
31
+ isPending: boolean;
32
+ config?: Config;
33
+ isFocused?: boolean;
34
+ commands?: readonly SlashCommand[];
35
+ }
36
+
37
+ export const HistoryItemDisplay: React.FC<HistoryItemDisplayProps> = ({
38
+ item,
39
+ availableTerminalHeight,
40
+ terminalWidth,
41
+ isPending,
42
+ config,
43
+ commands,
44
+ isFocused = true,
45
+ }) => (
46
+ <Box flexDirection="column" key={item.id}>
47
+ {/* Render standard message types */}
48
+ {item.type === 'user' && <UserMessage text={item.text} />}
49
+ {item.type === 'user_shell' && <UserShellMessage text={item.text} />}
50
+ {item.type === 'gemini' && (
51
+ <GeminiMessage
52
+ text={item.text}
53
+ isPending={isPending}
54
+ availableTerminalHeight={availableTerminalHeight}
55
+ terminalWidth={terminalWidth}
56
+ />
57
+ )}
58
+ {item.type === 'gemini_content' && (
59
+ <GeminiMessageContent
60
+ text={item.text}
61
+ isPending={isPending}
62
+ availableTerminalHeight={availableTerminalHeight}
63
+ terminalWidth={terminalWidth}
64
+ />
65
+ )}
66
+ {item.type === 'info' && <InfoMessage text={item.text} />}
67
+ {item.type === 'error' && <ErrorMessage text={item.text} />}
68
+ {item.type === 'about' && (
69
+ <AboutBox
70
+ cliVersion={item.cliVersion}
71
+ osVersion={item.osVersion}
72
+ sandboxEnv={item.sandboxEnv}
73
+ modelVersion={item.modelVersion}
74
+ selectedAuthType={item.selectedAuthType}
75
+ gcpProject={item.gcpProject}
76
+ ideClient={item.ideClient}
77
+ />
78
+ )}
79
+ {item.type === 'help' && commands && <Help commands={commands} />}
80
+ {item.type === 'stats' && <StatsDisplay duration={item.duration} />}
81
+ {item.type === 'model_stats' && <ModelStatsDisplay />}
82
+ {item.type === 'tool_stats' && <ToolStatsDisplay />}
83
+ {item.type === 'quit' && <SessionSummaryDisplay duration={item.duration} />}
84
+ {item.type === 'tool_group' && (
85
+ <ToolGroupMessage
86
+ toolCalls={item.tools}
87
+ groupId={item.id}
88
+ availableTerminalHeight={availableTerminalHeight}
89
+ terminalWidth={terminalWidth}
90
+ config={config}
91
+ isFocused={isFocused}
92
+ />
93
+ )}
94
+ {item.type === 'compression' && (
95
+ <CompressionMessage compression={item.compression} />
96
+ )}
97
+ </Box>
98
+ );
projects/ui/qwen-code/packages/cli/src/ui/components/InputPrompt.test.tsx ADDED
@@ -0,0 +1,1467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { waitFor } from '@testing-library/react';
9
+ import { InputPrompt, InputPromptProps } from './InputPrompt.js';
10
+ import type { TextBuffer } from './shared/text-buffer.js';
11
+ import { Config } from '@qwen-code/qwen-code-core';
12
+ import * as path from 'path';
13
+ import {
14
+ CommandContext,
15
+ SlashCommand,
16
+ CommandKind,
17
+ } from '../commands/types.js';
18
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
19
+ import {
20
+ useShellHistory,
21
+ UseShellHistoryReturn,
22
+ } from '../hooks/useShellHistory.js';
23
+ import {
24
+ useCommandCompletion,
25
+ UseCommandCompletionReturn,
26
+ } from '../hooks/useCommandCompletion.js';
27
+ import {
28
+ useInputHistory,
29
+ UseInputHistoryReturn,
30
+ } from '../hooks/useInputHistory.js';
31
+ import * as clipboardUtils from '../utils/clipboardUtils.js';
32
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
33
+
34
+ vi.mock('../hooks/useShellHistory.js');
35
+ vi.mock('../hooks/useCommandCompletion.js');
36
+ vi.mock('../hooks/useInputHistory.js');
37
+ vi.mock('../utils/clipboardUtils.js');
38
+
39
+ const mockSlashCommands: SlashCommand[] = [
40
+ {
41
+ name: 'clear',
42
+ kind: CommandKind.BUILT_IN,
43
+ description: 'Clear screen',
44
+ action: vi.fn(),
45
+ },
46
+ {
47
+ name: 'memory',
48
+ kind: CommandKind.BUILT_IN,
49
+ description: 'Manage memory',
50
+ subCommands: [
51
+ {
52
+ name: 'show',
53
+ kind: CommandKind.BUILT_IN,
54
+ description: 'Show memory',
55
+ action: vi.fn(),
56
+ },
57
+ {
58
+ name: 'add',
59
+ kind: CommandKind.BUILT_IN,
60
+ description: 'Add to memory',
61
+ action: vi.fn(),
62
+ },
63
+ {
64
+ name: 'refresh',
65
+ kind: CommandKind.BUILT_IN,
66
+ description: 'Refresh memory',
67
+ action: vi.fn(),
68
+ },
69
+ ],
70
+ },
71
+ {
72
+ name: 'chat',
73
+ description: 'Manage chats',
74
+ kind: CommandKind.BUILT_IN,
75
+ subCommands: [
76
+ {
77
+ name: 'resume',
78
+ description: 'Resume a chat',
79
+ kind: CommandKind.BUILT_IN,
80
+ action: vi.fn(),
81
+ completion: async () => ['fix-foo', 'fix-bar'],
82
+ },
83
+ ],
84
+ },
85
+ ];
86
+
87
+ describe('InputPrompt', () => {
88
+ let props: InputPromptProps;
89
+ let mockShellHistory: UseShellHistoryReturn;
90
+ let mockCommandCompletion: UseCommandCompletionReturn;
91
+ let mockInputHistory: UseInputHistoryReturn;
92
+ let mockBuffer: TextBuffer;
93
+ let mockCommandContext: CommandContext;
94
+
95
+ const mockedUseShellHistory = vi.mocked(useShellHistory);
96
+ const mockedUseCommandCompletion = vi.mocked(useCommandCompletion);
97
+ const mockedUseInputHistory = vi.mocked(useInputHistory);
98
+
99
+ beforeEach(() => {
100
+ vi.resetAllMocks();
101
+
102
+ mockCommandContext = createMockCommandContext();
103
+
104
+ mockBuffer = {
105
+ text: '',
106
+ cursor: [0, 0],
107
+ lines: [''],
108
+ setText: vi.fn((newText: string) => {
109
+ mockBuffer.text = newText;
110
+ mockBuffer.lines = [newText];
111
+ mockBuffer.cursor = [0, newText.length];
112
+ mockBuffer.viewportVisualLines = [newText];
113
+ mockBuffer.allVisualLines = [newText];
114
+ }),
115
+ replaceRangeByOffset: vi.fn(),
116
+ viewportVisualLines: [''],
117
+ allVisualLines: [''],
118
+ visualCursor: [0, 0],
119
+ visualScrollRow: 0,
120
+ handleInput: vi.fn(),
121
+ move: vi.fn(),
122
+ moveToOffset: (offset: number) => {
123
+ mockBuffer.cursor = [0, offset];
124
+ },
125
+ killLineRight: vi.fn(),
126
+ killLineLeft: vi.fn(),
127
+ openInExternalEditor: vi.fn(),
128
+ newline: vi.fn(),
129
+ backspace: vi.fn(),
130
+ preferredCol: null,
131
+ selectionAnchor: null,
132
+ insert: vi.fn(),
133
+ del: vi.fn(),
134
+ undo: vi.fn(),
135
+ redo: vi.fn(),
136
+ replaceRange: vi.fn(),
137
+ deleteWordLeft: vi.fn(),
138
+ deleteWordRight: vi.fn(),
139
+ } as unknown as TextBuffer;
140
+
141
+ mockShellHistory = {
142
+ history: [],
143
+ addCommandToHistory: vi.fn(),
144
+ getPreviousCommand: vi.fn().mockReturnValue(null),
145
+ getNextCommand: vi.fn().mockReturnValue(null),
146
+ resetHistoryPosition: vi.fn(),
147
+ };
148
+ mockedUseShellHistory.mockReturnValue(mockShellHistory);
149
+
150
+ mockCommandCompletion = {
151
+ suggestions: [],
152
+ activeSuggestionIndex: -1,
153
+ isLoadingSuggestions: false,
154
+ showSuggestions: false,
155
+ visibleStartIndex: 0,
156
+ isPerfectMatch: false,
157
+ navigateUp: vi.fn(),
158
+ navigateDown: vi.fn(),
159
+ resetCompletionState: vi.fn(),
160
+ setActiveSuggestionIndex: vi.fn(),
161
+ setShowSuggestions: vi.fn(),
162
+ handleAutocomplete: vi.fn(),
163
+ };
164
+ mockedUseCommandCompletion.mockReturnValue(mockCommandCompletion);
165
+
166
+ mockInputHistory = {
167
+ navigateUp: vi.fn(),
168
+ navigateDown: vi.fn(),
169
+ handleSubmit: vi.fn(),
170
+ };
171
+ mockedUseInputHistory.mockReturnValue(mockInputHistory);
172
+
173
+ props = {
174
+ buffer: mockBuffer,
175
+ onSubmit: vi.fn(),
176
+ userMessages: [],
177
+ onClearScreen: vi.fn(),
178
+ config: {
179
+ getProjectRoot: () => path.join('test', 'project'),
180
+ getTargetDir: () => path.join('test', 'project', 'src'),
181
+ getVimMode: () => false,
182
+ getWorkspaceContext: () => ({
183
+ getDirectories: () => ['/test/project/src'],
184
+ }),
185
+ } as unknown as Config,
186
+ slashCommands: mockSlashCommands,
187
+ commandContext: mockCommandContext,
188
+ shellModeActive: false,
189
+ setShellModeActive: vi.fn(),
190
+ inputWidth: 80,
191
+ suggestionsWidth: 80,
192
+ focus: true,
193
+ };
194
+ });
195
+
196
+ const wait = (ms = 50) => new Promise((resolve) => setTimeout(resolve, ms));
197
+
198
+ it('should call shellHistory.getPreviousCommand on up arrow in shell mode', async () => {
199
+ props.shellModeActive = true;
200
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
201
+ await wait();
202
+
203
+ stdin.write('\u001B[A');
204
+ await wait();
205
+
206
+ expect(mockShellHistory.getPreviousCommand).toHaveBeenCalled();
207
+ unmount();
208
+ });
209
+
210
+ it('should call shellHistory.getNextCommand on down arrow in shell mode', async () => {
211
+ props.shellModeActive = true;
212
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
213
+ await wait();
214
+
215
+ stdin.write('\u001B[B');
216
+ await wait();
217
+
218
+ expect(mockShellHistory.getNextCommand).toHaveBeenCalled();
219
+ unmount();
220
+ });
221
+
222
+ it('should set the buffer text when a shell history command is retrieved', async () => {
223
+ props.shellModeActive = true;
224
+ vi.mocked(mockShellHistory.getPreviousCommand).mockReturnValue(
225
+ 'previous command',
226
+ );
227
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
228
+ await wait();
229
+
230
+ stdin.write('\u001B[A');
231
+ await wait();
232
+
233
+ expect(mockShellHistory.getPreviousCommand).toHaveBeenCalled();
234
+ expect(props.buffer.setText).toHaveBeenCalledWith('previous command');
235
+ unmount();
236
+ });
237
+
238
+ it('should call shellHistory.addCommandToHistory on submit in shell mode', async () => {
239
+ props.shellModeActive = true;
240
+ props.buffer.setText('ls -l');
241
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
242
+ await wait();
243
+
244
+ stdin.write('\r');
245
+ await wait();
246
+
247
+ expect(mockShellHistory.addCommandToHistory).toHaveBeenCalledWith('ls -l');
248
+ expect(props.onSubmit).toHaveBeenCalledWith('ls -l');
249
+ unmount();
250
+ });
251
+
252
+ it('should NOT call shell history methods when not in shell mode', async () => {
253
+ props.buffer.setText('some text');
254
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
255
+ await wait();
256
+
257
+ stdin.write('\u001B[A'); // Up arrow
258
+ await wait();
259
+ stdin.write('\u001B[B'); // Down arrow
260
+ await wait();
261
+ stdin.write('\r'); // Enter
262
+ await wait();
263
+
264
+ expect(mockShellHistory.getPreviousCommand).not.toHaveBeenCalled();
265
+ expect(mockShellHistory.getNextCommand).not.toHaveBeenCalled();
266
+ expect(mockShellHistory.addCommandToHistory).not.toHaveBeenCalled();
267
+
268
+ expect(mockInputHistory.navigateUp).toHaveBeenCalled();
269
+ expect(mockInputHistory.navigateDown).toHaveBeenCalled();
270
+ expect(props.onSubmit).toHaveBeenCalledWith('some text');
271
+ unmount();
272
+ });
273
+
274
+ it('should call completion.navigateUp for both up arrow and Ctrl+P when suggestions are showing', async () => {
275
+ mockedUseCommandCompletion.mockReturnValue({
276
+ ...mockCommandCompletion,
277
+ showSuggestions: true,
278
+ suggestions: [
279
+ { label: 'memory', value: 'memory' },
280
+ { label: 'memcache', value: 'memcache' },
281
+ ],
282
+ });
283
+
284
+ props.buffer.setText('/mem');
285
+
286
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
287
+ await wait();
288
+
289
+ // Test up arrow
290
+ stdin.write('\u001B[A'); // Up arrow
291
+ await wait();
292
+
293
+ stdin.write('\u0010'); // Ctrl+P
294
+ await wait();
295
+ expect(mockCommandCompletion.navigateUp).toHaveBeenCalledTimes(2);
296
+ expect(mockCommandCompletion.navigateDown).not.toHaveBeenCalled();
297
+
298
+ unmount();
299
+ });
300
+
301
+ it('should call completion.navigateDown for both down arrow and Ctrl+N when suggestions are showing', async () => {
302
+ mockedUseCommandCompletion.mockReturnValue({
303
+ ...mockCommandCompletion,
304
+ showSuggestions: true,
305
+ suggestions: [
306
+ { label: 'memory', value: 'memory' },
307
+ { label: 'memcache', value: 'memcache' },
308
+ ],
309
+ });
310
+ props.buffer.setText('/mem');
311
+
312
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
313
+ await wait();
314
+
315
+ // Test down arrow
316
+ stdin.write('\u001B[B'); // Down arrow
317
+ await wait();
318
+
319
+ stdin.write('\u000E'); // Ctrl+N
320
+ await wait();
321
+ expect(mockCommandCompletion.navigateDown).toHaveBeenCalledTimes(2);
322
+ expect(mockCommandCompletion.navigateUp).not.toHaveBeenCalled();
323
+
324
+ unmount();
325
+ });
326
+
327
+ it('should NOT call completion navigation when suggestions are not showing', async () => {
328
+ mockedUseCommandCompletion.mockReturnValue({
329
+ ...mockCommandCompletion,
330
+ showSuggestions: false,
331
+ });
332
+ props.buffer.setText('some text');
333
+
334
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
335
+ await wait();
336
+
337
+ stdin.write('\u001B[A'); // Up arrow
338
+ await wait();
339
+ stdin.write('\u001B[B'); // Down arrow
340
+ await wait();
341
+ stdin.write('\u0010'); // Ctrl+P
342
+ await wait();
343
+ stdin.write('\u000E'); // Ctrl+N
344
+ await wait();
345
+
346
+ expect(mockCommandCompletion.navigateUp).not.toHaveBeenCalled();
347
+ expect(mockCommandCompletion.navigateDown).not.toHaveBeenCalled();
348
+ unmount();
349
+ });
350
+
351
+ describe('clipboard image paste', () => {
352
+ beforeEach(() => {
353
+ vi.mocked(clipboardUtils.clipboardHasImage).mockResolvedValue(false);
354
+ vi.mocked(clipboardUtils.saveClipboardImage).mockResolvedValue(null);
355
+ vi.mocked(clipboardUtils.cleanupOldClipboardImages).mockResolvedValue(
356
+ undefined,
357
+ );
358
+ });
359
+
360
+ it('should handle Ctrl+V when clipboard has an image', async () => {
361
+ vi.mocked(clipboardUtils.clipboardHasImage).mockResolvedValue(true);
362
+ vi.mocked(clipboardUtils.saveClipboardImage).mockResolvedValue(
363
+ '/test/.gemini-clipboard/clipboard-123.png',
364
+ );
365
+
366
+ const { stdin, unmount } = renderWithProviders(
367
+ <InputPrompt {...props} />,
368
+ );
369
+ await wait();
370
+
371
+ // Send Ctrl+V
372
+ stdin.write('\x16'); // Ctrl+V
373
+ await wait();
374
+
375
+ expect(clipboardUtils.clipboardHasImage).toHaveBeenCalled();
376
+ expect(clipboardUtils.saveClipboardImage).toHaveBeenCalledWith(
377
+ props.config.getTargetDir(),
378
+ );
379
+ expect(clipboardUtils.cleanupOldClipboardImages).toHaveBeenCalledWith(
380
+ props.config.getTargetDir(),
381
+ );
382
+ expect(mockBuffer.replaceRangeByOffset).toHaveBeenCalled();
383
+ unmount();
384
+ });
385
+
386
+ it('should not insert anything when clipboard has no image', async () => {
387
+ vi.mocked(clipboardUtils.clipboardHasImage).mockResolvedValue(false);
388
+
389
+ const { stdin, unmount } = renderWithProviders(
390
+ <InputPrompt {...props} />,
391
+ );
392
+ await wait();
393
+
394
+ stdin.write('\x16'); // Ctrl+V
395
+ await wait();
396
+
397
+ expect(clipboardUtils.clipboardHasImage).toHaveBeenCalled();
398
+ expect(clipboardUtils.saveClipboardImage).not.toHaveBeenCalled();
399
+ expect(mockBuffer.setText).not.toHaveBeenCalled();
400
+ unmount();
401
+ });
402
+
403
+ it('should handle image save failure gracefully', async () => {
404
+ vi.mocked(clipboardUtils.clipboardHasImage).mockResolvedValue(true);
405
+ vi.mocked(clipboardUtils.saveClipboardImage).mockResolvedValue(null);
406
+
407
+ const { stdin, unmount } = renderWithProviders(
408
+ <InputPrompt {...props} />,
409
+ );
410
+ await wait();
411
+
412
+ stdin.write('\x16'); // Ctrl+V
413
+ await wait();
414
+
415
+ expect(clipboardUtils.saveClipboardImage).toHaveBeenCalled();
416
+ expect(mockBuffer.setText).not.toHaveBeenCalled();
417
+ unmount();
418
+ });
419
+
420
+ it('should insert image path at cursor position with proper spacing', async () => {
421
+ const imagePath = path.join(
422
+ 'test',
423
+ '.gemini-clipboard',
424
+ 'clipboard-456.png',
425
+ );
426
+ vi.mocked(clipboardUtils.clipboardHasImage).mockResolvedValue(true);
427
+ vi.mocked(clipboardUtils.saveClipboardImage).mockResolvedValue(imagePath);
428
+
429
+ // Set initial text and cursor position
430
+ mockBuffer.text = 'Hello world';
431
+ mockBuffer.cursor = [0, 5]; // Cursor after "Hello"
432
+ mockBuffer.lines = ['Hello world'];
433
+ mockBuffer.replaceRangeByOffset = vi.fn();
434
+
435
+ const { stdin, unmount } = renderWithProviders(
436
+ <InputPrompt {...props} />,
437
+ );
438
+ await wait();
439
+
440
+ stdin.write('\x16'); // Ctrl+V
441
+ await wait();
442
+
443
+ // Should insert at cursor position with spaces
444
+ expect(mockBuffer.replaceRangeByOffset).toHaveBeenCalled();
445
+
446
+ // Get the actual call to see what path was used
447
+ const actualCall = vi.mocked(mockBuffer.replaceRangeByOffset).mock
448
+ .calls[0];
449
+ expect(actualCall[0]).toBe(5); // start offset
450
+ expect(actualCall[1]).toBe(5); // end offset
451
+ expect(actualCall[2]).toBe(
452
+ ' @' + path.relative(path.join('test', 'project', 'src'), imagePath),
453
+ );
454
+ unmount();
455
+ });
456
+
457
+ it('should handle errors during clipboard operations', async () => {
458
+ const consoleErrorSpy = vi
459
+ .spyOn(console, 'error')
460
+ .mockImplementation(() => {});
461
+ vi.mocked(clipboardUtils.clipboardHasImage).mockRejectedValue(
462
+ new Error('Clipboard error'),
463
+ );
464
+
465
+ const { stdin, unmount } = renderWithProviders(
466
+ <InputPrompt {...props} />,
467
+ );
468
+ await wait();
469
+
470
+ stdin.write('\x16'); // Ctrl+V
471
+ await wait();
472
+
473
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
474
+ 'Error handling clipboard image:',
475
+ expect.any(Error),
476
+ );
477
+ expect(mockBuffer.setText).not.toHaveBeenCalled();
478
+
479
+ consoleErrorSpy.mockRestore();
480
+ unmount();
481
+ });
482
+ });
483
+
484
+ it('should complete a partial parent command', async () => {
485
+ // SCENARIO: /mem -> Tab
486
+ mockedUseCommandCompletion.mockReturnValue({
487
+ ...mockCommandCompletion,
488
+ showSuggestions: true,
489
+ suggestions: [{ label: 'memory', value: 'memory', description: '...' }],
490
+ activeSuggestionIndex: 0,
491
+ });
492
+ props.buffer.setText('/mem');
493
+
494
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
495
+ await wait();
496
+
497
+ stdin.write('\t'); // Press Tab
498
+ await wait();
499
+
500
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(0);
501
+ unmount();
502
+ });
503
+
504
+ it('should append a sub-command when the parent command is already complete', async () => {
505
+ // SCENARIO: /memory -> Tab (to accept 'add')
506
+ mockedUseCommandCompletion.mockReturnValue({
507
+ ...mockCommandCompletion,
508
+ showSuggestions: true,
509
+ suggestions: [
510
+ { label: 'show', value: 'show' },
511
+ { label: 'add', value: 'add' },
512
+ ],
513
+ activeSuggestionIndex: 1, // 'add' is highlighted
514
+ });
515
+ props.buffer.setText('/memory ');
516
+
517
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
518
+ await wait();
519
+
520
+ stdin.write('\t'); // Press Tab
521
+ await wait();
522
+
523
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(1);
524
+ unmount();
525
+ });
526
+
527
+ it('should handle the "backspace" edge case correctly', async () => {
528
+ // SCENARIO: /memory -> Backspace -> /memory -> Tab (to accept 'show')
529
+ mockedUseCommandCompletion.mockReturnValue({
530
+ ...mockCommandCompletion,
531
+ showSuggestions: true,
532
+ suggestions: [
533
+ { label: 'show', value: 'show' },
534
+ { label: 'add', value: 'add' },
535
+ ],
536
+ activeSuggestionIndex: 0, // 'show' is highlighted
537
+ });
538
+ // The user has backspaced, so the query is now just '/memory'
539
+ props.buffer.setText('/memory');
540
+
541
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
542
+ await wait();
543
+
544
+ stdin.write('\t'); // Press Tab
545
+ await wait();
546
+
547
+ // It should NOT become '/show'. It should correctly become '/memory show'.
548
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(0);
549
+ unmount();
550
+ });
551
+
552
+ it('should complete a partial argument for a command', async () => {
553
+ // SCENARIO: /chat resume fi- -> Tab
554
+ mockedUseCommandCompletion.mockReturnValue({
555
+ ...mockCommandCompletion,
556
+ showSuggestions: true,
557
+ suggestions: [{ label: 'fix-foo', value: 'fix-foo' }],
558
+ activeSuggestionIndex: 0,
559
+ });
560
+ props.buffer.setText('/chat resume fi-');
561
+
562
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
563
+ await wait();
564
+
565
+ stdin.write('\t'); // Press Tab
566
+ await wait();
567
+
568
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(0);
569
+ unmount();
570
+ });
571
+
572
+ it('should autocomplete on Enter when suggestions are active, without submitting', async () => {
573
+ mockedUseCommandCompletion.mockReturnValue({
574
+ ...mockCommandCompletion,
575
+ showSuggestions: true,
576
+ suggestions: [{ label: 'memory', value: 'memory' }],
577
+ activeSuggestionIndex: 0,
578
+ });
579
+ props.buffer.setText('/mem');
580
+
581
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
582
+ await wait();
583
+
584
+ stdin.write('\r');
585
+ await wait();
586
+
587
+ // The app should autocomplete the text, NOT submit.
588
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(0);
589
+
590
+ expect(props.onSubmit).not.toHaveBeenCalled();
591
+ unmount();
592
+ });
593
+
594
+ it('should complete a command based on its altNames', async () => {
595
+ props.slashCommands = [
596
+ {
597
+ name: 'help',
598
+ altNames: ['?'],
599
+ kind: CommandKind.BUILT_IN,
600
+ description: '...',
601
+ },
602
+ ];
603
+
604
+ mockedUseCommandCompletion.mockReturnValue({
605
+ ...mockCommandCompletion,
606
+ showSuggestions: true,
607
+ suggestions: [{ label: 'help', value: 'help' }],
608
+ activeSuggestionIndex: 0,
609
+ });
610
+ props.buffer.setText('/?');
611
+
612
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
613
+ await wait();
614
+
615
+ stdin.write('\t'); // Press Tab for autocomplete
616
+ await wait();
617
+
618
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(0);
619
+ unmount();
620
+ });
621
+
622
+ it('should not submit on Enter when the buffer is empty or only contains whitespace', async () => {
623
+ props.buffer.setText(' '); // Set buffer to whitespace
624
+
625
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
626
+ await wait();
627
+
628
+ stdin.write('\r'); // Press Enter
629
+ await wait();
630
+
631
+ expect(props.onSubmit).not.toHaveBeenCalled();
632
+ unmount();
633
+ });
634
+
635
+ it('should submit directly on Enter when isPerfectMatch is true', async () => {
636
+ mockedUseCommandCompletion.mockReturnValue({
637
+ ...mockCommandCompletion,
638
+ showSuggestions: false,
639
+ isPerfectMatch: true,
640
+ });
641
+ props.buffer.setText('/clear');
642
+
643
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
644
+ await wait();
645
+
646
+ stdin.write('\r');
647
+ await wait();
648
+
649
+ expect(props.onSubmit).toHaveBeenCalledWith('/clear');
650
+ unmount();
651
+ });
652
+
653
+ it('should submit directly on Enter when a complete leaf command is typed', async () => {
654
+ mockedUseCommandCompletion.mockReturnValue({
655
+ ...mockCommandCompletion,
656
+ showSuggestions: false,
657
+ isPerfectMatch: false, // Added explicit isPerfectMatch false
658
+ });
659
+ props.buffer.setText('/clear');
660
+
661
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
662
+ await wait();
663
+
664
+ stdin.write('\r');
665
+ await wait();
666
+
667
+ expect(props.onSubmit).toHaveBeenCalledWith('/clear');
668
+ unmount();
669
+ });
670
+
671
+ it('should autocomplete an @-path on Enter without submitting', async () => {
672
+ mockedUseCommandCompletion.mockReturnValue({
673
+ ...mockCommandCompletion,
674
+ showSuggestions: true,
675
+ suggestions: [{ label: 'index.ts', value: 'index.ts' }],
676
+ activeSuggestionIndex: 0,
677
+ });
678
+ props.buffer.setText('@src/components/');
679
+
680
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
681
+ await wait();
682
+
683
+ stdin.write('\r');
684
+ await wait();
685
+
686
+ expect(mockCommandCompletion.handleAutocomplete).toHaveBeenCalledWith(0);
687
+ expect(props.onSubmit).not.toHaveBeenCalled();
688
+ unmount();
689
+ });
690
+
691
+ it('should add a newline on enter when the line ends with a backslash', async () => {
692
+ // This test simulates multi-line input, not submission
693
+ mockBuffer.text = 'first line\\';
694
+ mockBuffer.cursor = [0, 11];
695
+ mockBuffer.lines = ['first line\\'];
696
+
697
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
698
+ await wait();
699
+
700
+ stdin.write('\r');
701
+ await wait();
702
+
703
+ expect(props.onSubmit).not.toHaveBeenCalled();
704
+ expect(props.buffer.backspace).toHaveBeenCalled();
705
+ expect(props.buffer.newline).toHaveBeenCalled();
706
+ unmount();
707
+ });
708
+
709
+ it('should clear the buffer on Ctrl+C if it has text', async () => {
710
+ props.buffer.setText('some text to clear');
711
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
712
+ await wait();
713
+
714
+ stdin.write('\x03'); // Ctrl+C character
715
+ await wait();
716
+
717
+ expect(props.buffer.setText).toHaveBeenCalledWith('');
718
+ expect(mockCommandCompletion.resetCompletionState).toHaveBeenCalled();
719
+ expect(props.onSubmit).not.toHaveBeenCalled();
720
+ unmount();
721
+ });
722
+
723
+ it('should NOT clear the buffer on Ctrl+C if it is empty', async () => {
724
+ props.buffer.text = '';
725
+ const { stdin, unmount } = renderWithProviders(<InputPrompt {...props} />);
726
+ await wait();
727
+
728
+ stdin.write('\x03'); // Ctrl+C character
729
+ await wait();
730
+
731
+ expect(props.buffer.setText).not.toHaveBeenCalled();
732
+ unmount();
733
+ });
734
+
735
+ describe('cursor-based completion trigger', () => {
736
+ it('should trigger completion when cursor is after @ without spaces', async () => {
737
+ // Set up buffer state
738
+ mockBuffer.text = '@src/components';
739
+ mockBuffer.lines = ['@src/components'];
740
+ mockBuffer.cursor = [0, 15];
741
+
742
+ mockedUseCommandCompletion.mockReturnValue({
743
+ ...mockCommandCompletion,
744
+ showSuggestions: true,
745
+ suggestions: [{ label: 'Button.tsx', value: 'Button.tsx' }],
746
+ });
747
+
748
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
749
+ await wait();
750
+
751
+ // Verify useCompletion was called with correct signature
752
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
753
+ mockBuffer,
754
+ ['/test/project/src'],
755
+ path.join('test', 'project', 'src'),
756
+ mockSlashCommands,
757
+ mockCommandContext,
758
+ false,
759
+ expect.any(Object),
760
+ );
761
+
762
+ unmount();
763
+ });
764
+
765
+ it('should trigger completion when cursor is after / without spaces', async () => {
766
+ mockBuffer.text = '/memory';
767
+ mockBuffer.lines = ['/memory'];
768
+ mockBuffer.cursor = [0, 7];
769
+
770
+ mockedUseCommandCompletion.mockReturnValue({
771
+ ...mockCommandCompletion,
772
+ showSuggestions: true,
773
+ suggestions: [{ label: 'show', value: 'show' }],
774
+ });
775
+
776
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
777
+ await wait();
778
+
779
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
780
+ mockBuffer,
781
+ ['/test/project/src'],
782
+ path.join('test', 'project', 'src'),
783
+ mockSlashCommands,
784
+ mockCommandContext,
785
+ false,
786
+ expect.any(Object),
787
+ );
788
+
789
+ unmount();
790
+ });
791
+
792
+ it('should NOT trigger completion when cursor is after space following @', async () => {
793
+ mockBuffer.text = '@src/file.ts hello';
794
+ mockBuffer.lines = ['@src/file.ts hello'];
795
+ mockBuffer.cursor = [0, 18];
796
+
797
+ mockedUseCommandCompletion.mockReturnValue({
798
+ ...mockCommandCompletion,
799
+ showSuggestions: false,
800
+ suggestions: [],
801
+ });
802
+
803
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
804
+ await wait();
805
+
806
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
807
+ mockBuffer,
808
+ ['/test/project/src'],
809
+ path.join('test', 'project', 'src'),
810
+ mockSlashCommands,
811
+ mockCommandContext,
812
+ false,
813
+ expect.any(Object),
814
+ );
815
+
816
+ unmount();
817
+ });
818
+
819
+ it('should NOT trigger completion when cursor is after space following /', async () => {
820
+ mockBuffer.text = '/memory add';
821
+ mockBuffer.lines = ['/memory add'];
822
+ mockBuffer.cursor = [0, 11];
823
+
824
+ mockedUseCommandCompletion.mockReturnValue({
825
+ ...mockCommandCompletion,
826
+ showSuggestions: false,
827
+ suggestions: [],
828
+ });
829
+
830
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
831
+ await wait();
832
+
833
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
834
+ mockBuffer,
835
+ ['/test/project/src'],
836
+ path.join('test', 'project', 'src'),
837
+ mockSlashCommands,
838
+ mockCommandContext,
839
+ false,
840
+ expect.any(Object),
841
+ );
842
+
843
+ unmount();
844
+ });
845
+
846
+ it('should NOT trigger completion when cursor is not after @ or /', async () => {
847
+ mockBuffer.text = 'hello world';
848
+ mockBuffer.lines = ['hello world'];
849
+ mockBuffer.cursor = [0, 5];
850
+
851
+ mockedUseCommandCompletion.mockReturnValue({
852
+ ...mockCommandCompletion,
853
+ showSuggestions: false,
854
+ suggestions: [],
855
+ });
856
+
857
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
858
+ await wait();
859
+
860
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
861
+ mockBuffer,
862
+ ['/test/project/src'],
863
+ path.join('test', 'project', 'src'),
864
+ mockSlashCommands,
865
+ mockCommandContext,
866
+ false,
867
+ expect.any(Object),
868
+ );
869
+
870
+ unmount();
871
+ });
872
+
873
+ it('should handle multiline text correctly', async () => {
874
+ mockBuffer.text = 'first line\n/memory';
875
+ mockBuffer.lines = ['first line', '/memory'];
876
+ mockBuffer.cursor = [1, 7];
877
+
878
+ mockedUseCommandCompletion.mockReturnValue({
879
+ ...mockCommandCompletion,
880
+ showSuggestions: false,
881
+ suggestions: [],
882
+ });
883
+
884
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
885
+ await wait();
886
+
887
+ // Verify useCompletion was called with the buffer
888
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
889
+ mockBuffer,
890
+ ['/test/project/src'],
891
+ path.join('test', 'project', 'src'),
892
+ mockSlashCommands,
893
+ mockCommandContext,
894
+ false,
895
+ expect.any(Object),
896
+ );
897
+
898
+ unmount();
899
+ });
900
+
901
+ it('should handle single line slash command correctly', async () => {
902
+ mockBuffer.text = '/memory';
903
+ mockBuffer.lines = ['/memory'];
904
+ mockBuffer.cursor = [0, 7];
905
+
906
+ mockedUseCommandCompletion.mockReturnValue({
907
+ ...mockCommandCompletion,
908
+ showSuggestions: true,
909
+ suggestions: [{ label: 'show', value: 'show' }],
910
+ });
911
+
912
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
913
+ await wait();
914
+
915
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
916
+ mockBuffer,
917
+ ['/test/project/src'],
918
+ path.join('test', 'project', 'src'),
919
+ mockSlashCommands,
920
+ mockCommandContext,
921
+ false,
922
+ expect.any(Object),
923
+ );
924
+
925
+ unmount();
926
+ });
927
+
928
+ it('should handle Unicode characters (emojis) correctly in paths', async () => {
929
+ // Test with emoji in path after @
930
+ mockBuffer.text = '@src/file👍.txt';
931
+ mockBuffer.lines = ['@src/file👍.txt'];
932
+ mockBuffer.cursor = [0, 14]; // After the emoji character
933
+
934
+ mockedUseCommandCompletion.mockReturnValue({
935
+ ...mockCommandCompletion,
936
+ showSuggestions: true,
937
+ suggestions: [{ label: 'file👍.txt', value: 'file👍.txt' }],
938
+ });
939
+
940
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
941
+ await wait();
942
+
943
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
944
+ mockBuffer,
945
+ ['/test/project/src'],
946
+ path.join('test', 'project', 'src'),
947
+ mockSlashCommands,
948
+ mockCommandContext,
949
+ false,
950
+ expect.any(Object),
951
+ );
952
+
953
+ unmount();
954
+ });
955
+
956
+ it('should handle Unicode characters with spaces after them', async () => {
957
+ // Test with emoji followed by space - should NOT trigger completion
958
+ mockBuffer.text = '@src/file👍.txt hello';
959
+ mockBuffer.lines = ['@src/file👍.txt hello'];
960
+ mockBuffer.cursor = [0, 20]; // After the space
961
+
962
+ mockedUseCommandCompletion.mockReturnValue({
963
+ ...mockCommandCompletion,
964
+ showSuggestions: false,
965
+ suggestions: [],
966
+ });
967
+
968
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
969
+ await wait();
970
+
971
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
972
+ mockBuffer,
973
+ ['/test/project/src'],
974
+ path.join('test', 'project', 'src'),
975
+ mockSlashCommands,
976
+ mockCommandContext,
977
+ false,
978
+ expect.any(Object),
979
+ );
980
+
981
+ unmount();
982
+ });
983
+
984
+ it('should handle escaped spaces in paths correctly', async () => {
985
+ // Test with escaped space in path - should trigger completion
986
+ mockBuffer.text = '@src/my\\ file.txt';
987
+ mockBuffer.lines = ['@src/my\\ file.txt'];
988
+ mockBuffer.cursor = [0, 16]; // After the escaped space and filename
989
+
990
+ mockedUseCommandCompletion.mockReturnValue({
991
+ ...mockCommandCompletion,
992
+ showSuggestions: true,
993
+ suggestions: [{ label: 'my file.txt', value: 'my file.txt' }],
994
+ });
995
+
996
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
997
+ await wait();
998
+
999
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
1000
+ mockBuffer,
1001
+ ['/test/project/src'],
1002
+ path.join('test', 'project', 'src'),
1003
+ mockSlashCommands,
1004
+ mockCommandContext,
1005
+ false,
1006
+ expect.any(Object),
1007
+ );
1008
+
1009
+ unmount();
1010
+ });
1011
+
1012
+ it('should NOT trigger completion after unescaped space following escaped space', async () => {
1013
+ // Test: @path/my\ file.txt hello (unescaped space after escaped space)
1014
+ mockBuffer.text = '@path/my\\ file.txt hello';
1015
+ mockBuffer.lines = ['@path/my\\ file.txt hello'];
1016
+ mockBuffer.cursor = [0, 24]; // After "hello"
1017
+
1018
+ mockedUseCommandCompletion.mockReturnValue({
1019
+ ...mockCommandCompletion,
1020
+ showSuggestions: false,
1021
+ suggestions: [],
1022
+ });
1023
+
1024
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
1025
+ await wait();
1026
+
1027
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
1028
+ mockBuffer,
1029
+ ['/test/project/src'],
1030
+ path.join('test', 'project', 'src'),
1031
+ mockSlashCommands,
1032
+ mockCommandContext,
1033
+ false,
1034
+ expect.any(Object),
1035
+ );
1036
+
1037
+ unmount();
1038
+ });
1039
+
1040
+ it('should handle multiple escaped spaces in paths', async () => {
1041
+ // Test with multiple escaped spaces
1042
+ mockBuffer.text = '@docs/my\\ long\\ file\\ name.md';
1043
+ mockBuffer.lines = ['@docs/my\\ long\\ file\\ name.md'];
1044
+ mockBuffer.cursor = [0, 29]; // At the end
1045
+
1046
+ mockedUseCommandCompletion.mockReturnValue({
1047
+ ...mockCommandCompletion,
1048
+ showSuggestions: true,
1049
+ suggestions: [
1050
+ { label: 'my long file name.md', value: 'my long file name.md' },
1051
+ ],
1052
+ });
1053
+
1054
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
1055
+ await wait();
1056
+
1057
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
1058
+ mockBuffer,
1059
+ ['/test/project/src'],
1060
+ path.join('test', 'project', 'src'),
1061
+ mockSlashCommands,
1062
+ mockCommandContext,
1063
+ false,
1064
+ expect.any(Object),
1065
+ );
1066
+
1067
+ unmount();
1068
+ });
1069
+
1070
+ it('should handle escaped spaces in slash commands', async () => {
1071
+ // Test escaped spaces with slash commands (though less common)
1072
+ mockBuffer.text = '/memory\\ test';
1073
+ mockBuffer.lines = ['/memory\\ test'];
1074
+ mockBuffer.cursor = [0, 13]; // At the end
1075
+
1076
+ mockedUseCommandCompletion.mockReturnValue({
1077
+ ...mockCommandCompletion,
1078
+ showSuggestions: true,
1079
+ suggestions: [{ label: 'test-command', value: 'test-command' }],
1080
+ });
1081
+
1082
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
1083
+ await wait();
1084
+
1085
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
1086
+ mockBuffer,
1087
+ ['/test/project/src'],
1088
+ path.join('test', 'project', 'src'),
1089
+ mockSlashCommands,
1090
+ mockCommandContext,
1091
+ false,
1092
+ expect.any(Object),
1093
+ );
1094
+
1095
+ unmount();
1096
+ });
1097
+
1098
+ it('should handle Unicode characters with escaped spaces', async () => {
1099
+ // Test combining Unicode and escaped spaces
1100
+ mockBuffer.text = '@' + path.join('files', 'emoji\\ 👍\\ test.txt');
1101
+ mockBuffer.lines = ['@' + path.join('files', 'emoji\\ 👍\\ test.txt')];
1102
+ mockBuffer.cursor = [0, 25]; // After the escaped space and emoji
1103
+
1104
+ mockedUseCommandCompletion.mockReturnValue({
1105
+ ...mockCommandCompletion,
1106
+ showSuggestions: true,
1107
+ suggestions: [
1108
+ { label: 'emoji 👍 test.txt', value: 'emoji 👍 test.txt' },
1109
+ ],
1110
+ });
1111
+
1112
+ const { unmount } = renderWithProviders(<InputPrompt {...props} />);
1113
+ await wait();
1114
+
1115
+ expect(mockedUseCommandCompletion).toHaveBeenCalledWith(
1116
+ mockBuffer,
1117
+ ['/test/project/src'],
1118
+ path.join('test', 'project', 'src'),
1119
+ mockSlashCommands,
1120
+ mockCommandContext,
1121
+ false,
1122
+ expect.any(Object),
1123
+ );
1124
+
1125
+ unmount();
1126
+ });
1127
+ });
1128
+
1129
+ describe('vim mode', () => {
1130
+ it('should not call buffer.handleInput when vim mode is enabled and vim handles the input', async () => {
1131
+ props.vimModeEnabled = true;
1132
+ props.vimHandleInput = vi.fn().mockReturnValue(true); // Mock that vim handled it.
1133
+ const { stdin, unmount } = renderWithProviders(
1134
+ <InputPrompt {...props} />,
1135
+ );
1136
+ await wait();
1137
+
1138
+ stdin.write('i');
1139
+ await wait();
1140
+
1141
+ expect(props.vimHandleInput).toHaveBeenCalled();
1142
+ expect(mockBuffer.handleInput).not.toHaveBeenCalled();
1143
+ unmount();
1144
+ });
1145
+
1146
+ it('should call buffer.handleInput when vim mode is enabled but vim does not handle the input', async () => {
1147
+ props.vimModeEnabled = true;
1148
+ props.vimHandleInput = vi.fn().mockReturnValue(false); // Mock that vim did NOT handle it.
1149
+ const { stdin, unmount } = renderWithProviders(
1150
+ <InputPrompt {...props} />,
1151
+ );
1152
+ await wait();
1153
+
1154
+ stdin.write('i');
1155
+ await wait();
1156
+
1157
+ expect(props.vimHandleInput).toHaveBeenCalled();
1158
+ expect(mockBuffer.handleInput).toHaveBeenCalled();
1159
+ unmount();
1160
+ });
1161
+
1162
+ it('should call handleInput when vim mode is disabled', async () => {
1163
+ // Mock vimHandleInput to return false (vim didn't handle the input)
1164
+ props.vimHandleInput = vi.fn().mockReturnValue(false);
1165
+ const { stdin, unmount } = renderWithProviders(
1166
+ <InputPrompt {...props} />,
1167
+ );
1168
+ await wait();
1169
+
1170
+ stdin.write('i');
1171
+ await wait();
1172
+
1173
+ expect(props.vimHandleInput).toHaveBeenCalled();
1174
+ expect(mockBuffer.handleInput).toHaveBeenCalled();
1175
+ unmount();
1176
+ });
1177
+ });
1178
+
1179
+ describe('unfocused paste', () => {
1180
+ it('should handle bracketed paste when not focused', async () => {
1181
+ props.focus = false;
1182
+ const { stdin, unmount } = renderWithProviders(
1183
+ <InputPrompt {...props} />,
1184
+ );
1185
+ await wait();
1186
+
1187
+ stdin.write('\x1B[200~pasted text\x1B[201~');
1188
+ await wait();
1189
+
1190
+ expect(mockBuffer.handleInput).toHaveBeenCalledWith(
1191
+ expect.objectContaining({
1192
+ paste: true,
1193
+ sequence: 'pasted text',
1194
+ }),
1195
+ );
1196
+ unmount();
1197
+ });
1198
+
1199
+ it('should ignore regular keypresses when not focused', async () => {
1200
+ props.focus = false;
1201
+ const { stdin, unmount } = renderWithProviders(
1202
+ <InputPrompt {...props} />,
1203
+ );
1204
+ await wait();
1205
+
1206
+ stdin.write('a');
1207
+ await wait();
1208
+
1209
+ expect(mockBuffer.handleInput).not.toHaveBeenCalled();
1210
+ unmount();
1211
+ });
1212
+ });
1213
+
1214
+ describe('multiline paste', () => {
1215
+ it.each([
1216
+ {
1217
+ description: 'with \n newlines',
1218
+ pastedText: 'This \n is \n a \n multiline \n paste.',
1219
+ },
1220
+ {
1221
+ description: 'with extra slashes before \n newlines',
1222
+ pastedText: 'This \\\n is \\\n a \\\n multiline \\\n paste.',
1223
+ },
1224
+ {
1225
+ description: 'with \r\n newlines',
1226
+ pastedText: 'This\r\nis\r\na\r\nmultiline\r\npaste.',
1227
+ },
1228
+ ])('should handle multiline paste $description', async ({ pastedText }) => {
1229
+ const { stdin, unmount } = renderWithProviders(
1230
+ <InputPrompt {...props} />,
1231
+ );
1232
+ await wait();
1233
+
1234
+ // Simulate a bracketed paste event from the terminal
1235
+ stdin.write(`\x1b[200~${pastedText}\x1b[201~`);
1236
+ await wait();
1237
+
1238
+ // Verify that the buffer's handleInput was called once with the full text
1239
+ expect(props.buffer.handleInput).toHaveBeenCalledTimes(1);
1240
+ expect(props.buffer.handleInput).toHaveBeenCalledWith(
1241
+ expect.objectContaining({
1242
+ paste: true,
1243
+ sequence: pastedText,
1244
+ }),
1245
+ );
1246
+
1247
+ unmount();
1248
+ });
1249
+ });
1250
+
1251
+ describe('enhanced input UX - double ESC clear functionality', () => {
1252
+ it('should clear buffer on second ESC press', async () => {
1253
+ const onEscapePromptChange = vi.fn();
1254
+ props.onEscapePromptChange = onEscapePromptChange;
1255
+ props.buffer.setText('text to clear');
1256
+
1257
+ const { stdin, unmount } = renderWithProviders(
1258
+ <InputPrompt {...props} />,
1259
+ );
1260
+ await wait();
1261
+
1262
+ stdin.write('\x1B');
1263
+ await wait();
1264
+
1265
+ stdin.write('\x1B');
1266
+ await wait();
1267
+
1268
+ expect(props.buffer.setText).toHaveBeenCalledWith('');
1269
+ expect(mockCommandCompletion.resetCompletionState).toHaveBeenCalled();
1270
+ unmount();
1271
+ });
1272
+
1273
+ it('should reset escape state on any non-ESC key', async () => {
1274
+ const onEscapePromptChange = vi.fn();
1275
+ props.onEscapePromptChange = onEscapePromptChange;
1276
+ props.buffer.setText('some text');
1277
+
1278
+ const { stdin, unmount } = renderWithProviders(
1279
+ <InputPrompt {...props} />,
1280
+ );
1281
+
1282
+ stdin.write('\x1B');
1283
+
1284
+ await waitFor(() => {
1285
+ expect(onEscapePromptChange).toHaveBeenCalledWith(true);
1286
+ });
1287
+
1288
+ stdin.write('a');
1289
+
1290
+ await waitFor(() => {
1291
+ expect(onEscapePromptChange).toHaveBeenCalledWith(false);
1292
+ });
1293
+ unmount();
1294
+ });
1295
+
1296
+ it('should handle ESC in shell mode by disabling shell mode', async () => {
1297
+ props.shellModeActive = true;
1298
+
1299
+ const { stdin, unmount } = renderWithProviders(
1300
+ <InputPrompt {...props} />,
1301
+ );
1302
+ await wait();
1303
+
1304
+ stdin.write('\x1B');
1305
+ await wait();
1306
+
1307
+ expect(props.setShellModeActive).toHaveBeenCalledWith(false);
1308
+ unmount();
1309
+ });
1310
+
1311
+ it('should handle ESC when completion suggestions are showing', async () => {
1312
+ mockedUseCommandCompletion.mockReturnValue({
1313
+ ...mockCommandCompletion,
1314
+ showSuggestions: true,
1315
+ suggestions: [{ label: 'suggestion', value: 'suggestion' }],
1316
+ });
1317
+
1318
+ const { stdin, unmount } = renderWithProviders(
1319
+ <InputPrompt {...props} />,
1320
+ );
1321
+ await wait();
1322
+
1323
+ stdin.write('\x1B');
1324
+ await wait();
1325
+
1326
+ expect(mockCommandCompletion.resetCompletionState).toHaveBeenCalled();
1327
+ unmount();
1328
+ });
1329
+
1330
+ it('should not call onEscapePromptChange when not provided', async () => {
1331
+ props.onEscapePromptChange = undefined;
1332
+ props.buffer.setText('some text');
1333
+
1334
+ const { stdin, unmount } = renderWithProviders(
1335
+ <InputPrompt {...props} />,
1336
+ );
1337
+ await wait();
1338
+
1339
+ stdin.write('\x1B');
1340
+ await wait();
1341
+
1342
+ unmount();
1343
+ });
1344
+
1345
+ it('should not interfere with existing keyboard shortcuts', async () => {
1346
+ const { stdin, unmount } = renderWithProviders(
1347
+ <InputPrompt {...props} />,
1348
+ );
1349
+ await wait();
1350
+
1351
+ stdin.write('\x0C');
1352
+ await wait();
1353
+
1354
+ expect(props.onClearScreen).toHaveBeenCalled();
1355
+
1356
+ stdin.write('\x01');
1357
+ await wait();
1358
+
1359
+ expect(props.buffer.move).toHaveBeenCalledWith('home');
1360
+ unmount();
1361
+ });
1362
+ });
1363
+
1364
+ describe('reverse search', () => {
1365
+ beforeEach(async () => {
1366
+ props.shellModeActive = true;
1367
+
1368
+ vi.mocked(useShellHistory).mockReturnValue({
1369
+ history: ['echo hello', 'echo world', 'ls'],
1370
+ getPreviousCommand: vi.fn(),
1371
+ getNextCommand: vi.fn(),
1372
+ addCommandToHistory: vi.fn(),
1373
+ resetHistoryPosition: vi.fn(),
1374
+ });
1375
+ });
1376
+
1377
+ it('invokes reverse search on Ctrl+R', async () => {
1378
+ const { stdin, stdout, unmount } = renderWithProviders(
1379
+ <InputPrompt {...props} />,
1380
+ );
1381
+ await wait();
1382
+
1383
+ stdin.write('\x12');
1384
+ await wait();
1385
+
1386
+ const frame = stdout.lastFrame();
1387
+ expect(frame).toContain('(r:)');
1388
+ expect(frame).toContain('echo hello');
1389
+ expect(frame).toContain('echo world');
1390
+ expect(frame).toContain('ls');
1391
+
1392
+ unmount();
1393
+ });
1394
+
1395
+ it('resets reverse search state on Escape', async () => {
1396
+ const { stdin, stdout, unmount } = renderWithProviders(
1397
+ <InputPrompt {...props} />,
1398
+ );
1399
+ await wait();
1400
+
1401
+ stdin.write('\x12');
1402
+ await wait();
1403
+ stdin.write('\x1B');
1404
+
1405
+ await waitFor(() => {
1406
+ expect(stdout.lastFrame()).not.toContain('(r:)');
1407
+ });
1408
+
1409
+ expect(stdout.lastFrame()).not.toContain('echo hello');
1410
+
1411
+ unmount();
1412
+ });
1413
+
1414
+ it('completes the highlighted entry on Tab and exits reverse-search', async () => {
1415
+ const { stdin, stdout, unmount } = renderWithProviders(
1416
+ <InputPrompt {...props} />,
1417
+ );
1418
+ stdin.write('\x12');
1419
+ await wait();
1420
+ stdin.write('\t');
1421
+
1422
+ await waitFor(() => {
1423
+ expect(stdout.lastFrame()).not.toContain('(r:)');
1424
+ });
1425
+
1426
+ expect(props.buffer.setText).toHaveBeenCalledWith('echo hello');
1427
+ unmount();
1428
+ });
1429
+
1430
+ it('submits the highlighted entry on Enter and exits reverse-search', async () => {
1431
+ const { stdin, stdout, unmount } = renderWithProviders(
1432
+ <InputPrompt {...props} />,
1433
+ );
1434
+ stdin.write('\x12');
1435
+ await wait();
1436
+ expect(stdout.lastFrame()).toContain('(r:)');
1437
+ stdin.write('\r');
1438
+
1439
+ await waitFor(() => {
1440
+ expect(stdout.lastFrame()).not.toContain('(r:)');
1441
+ });
1442
+
1443
+ expect(props.onSubmit).toHaveBeenCalledWith('echo hello');
1444
+ unmount();
1445
+ });
1446
+
1447
+ it('text and cursor position should be restored after reverse search', async () => {
1448
+ props.buffer.setText('initial text');
1449
+ props.buffer.cursor = [0, 3];
1450
+ const { stdin, stdout, unmount } = renderWithProviders(
1451
+ <InputPrompt {...props} />,
1452
+ );
1453
+ stdin.write('\x12');
1454
+ await wait();
1455
+ expect(stdout.lastFrame()).toContain('(r:)');
1456
+ stdin.write('\x1B');
1457
+
1458
+ await waitFor(() => {
1459
+ expect(stdout.lastFrame()).not.toContain('(r:)');
1460
+ });
1461
+ expect(props.buffer.text).toBe('initial text');
1462
+ expect(props.buffer.cursor).toEqual([0, 3]);
1463
+
1464
+ unmount();
1465
+ });
1466
+ });
1467
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/InputPrompt.tsx ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React, { useCallback, useEffect, useState, useRef } from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { theme } from '../semantic-colors.js';
10
+ import { SuggestionsDisplay } from './SuggestionsDisplay.js';
11
+ import { useInputHistory } from '../hooks/useInputHistory.js';
12
+ import { TextBuffer, logicalPosToOffset } from './shared/text-buffer.js';
13
+ import { cpSlice, cpLen } from '../utils/textUtils.js';
14
+ import chalk from 'chalk';
15
+ import stringWidth from 'string-width';
16
+ import { useShellHistory } from '../hooks/useShellHistory.js';
17
+ import { useReverseSearchCompletion } from '../hooks/useReverseSearchCompletion.js';
18
+ import { useCommandCompletion } from '../hooks/useCommandCompletion.js';
19
+ import { useKeypress, Key } from '../hooks/useKeypress.js';
20
+ import { keyMatchers, Command } from '../keyMatchers.js';
21
+ import { CommandContext, SlashCommand } from '../commands/types.js';
22
+ import { Config } from '@qwen-code/qwen-code-core';
23
+ import {
24
+ clipboardHasImage,
25
+ saveClipboardImage,
26
+ cleanupOldClipboardImages,
27
+ } from '../utils/clipboardUtils.js';
28
+ import * as path from 'path';
29
+
30
+ export interface InputPromptProps {
31
+ buffer: TextBuffer;
32
+ onSubmit: (value: string) => void;
33
+ userMessages: readonly string[];
34
+ onClearScreen: () => void;
35
+ config: Config;
36
+ slashCommands: readonly SlashCommand[];
37
+ commandContext: CommandContext;
38
+ placeholder?: string;
39
+ focus?: boolean;
40
+ inputWidth: number;
41
+ suggestionsWidth: number;
42
+ shellModeActive: boolean;
43
+ setShellModeActive: (value: boolean) => void;
44
+ onEscapePromptChange?: (showPrompt: boolean) => void;
45
+ vimHandleInput?: (key: Key) => boolean;
46
+ }
47
+
48
+ export const InputPrompt: React.FC<InputPromptProps> = ({
49
+ buffer,
50
+ onSubmit,
51
+ userMessages,
52
+ onClearScreen,
53
+ config,
54
+ slashCommands,
55
+ commandContext,
56
+ placeholder = ' Type your message or @path/to/file',
57
+ focus = true,
58
+ inputWidth,
59
+ suggestionsWidth,
60
+ shellModeActive,
61
+ setShellModeActive,
62
+ onEscapePromptChange,
63
+ vimHandleInput,
64
+ }) => {
65
+ const [justNavigatedHistory, setJustNavigatedHistory] = useState(false);
66
+ const [escPressCount, setEscPressCount] = useState(0);
67
+ const [showEscapePrompt, setShowEscapePrompt] = useState(false);
68
+ const escapeTimerRef = useRef<NodeJS.Timeout | null>(null);
69
+
70
+ const [dirs, setDirs] = useState<readonly string[]>(
71
+ config.getWorkspaceContext().getDirectories(),
72
+ );
73
+ const dirsChanged = config.getWorkspaceContext().getDirectories();
74
+ useEffect(() => {
75
+ if (dirs.length !== dirsChanged.length) {
76
+ setDirs(dirsChanged);
77
+ }
78
+ }, [dirs.length, dirsChanged]);
79
+ const [reverseSearchActive, setReverseSearchActive] = useState(false);
80
+ const [textBeforeReverseSearch, setTextBeforeReverseSearch] = useState('');
81
+ const [cursorPosition, setCursorPosition] = useState<[number, number]>([
82
+ 0, 0,
83
+ ]);
84
+ const shellHistory = useShellHistory(config.getProjectRoot());
85
+ const historyData = shellHistory.history;
86
+
87
+ const completion = useCommandCompletion(
88
+ buffer,
89
+ dirs,
90
+ config.getTargetDir(),
91
+ slashCommands,
92
+ commandContext,
93
+ reverseSearchActive,
94
+ config,
95
+ );
96
+
97
+ const reverseSearchCompletion = useReverseSearchCompletion(
98
+ buffer,
99
+ historyData,
100
+ reverseSearchActive,
101
+ );
102
+ const resetCompletionState = completion.resetCompletionState;
103
+ const resetReverseSearchCompletionState =
104
+ reverseSearchCompletion.resetCompletionState;
105
+
106
+ const resetEscapeState = useCallback(() => {
107
+ if (escapeTimerRef.current) {
108
+ clearTimeout(escapeTimerRef.current);
109
+ escapeTimerRef.current = null;
110
+ }
111
+ setEscPressCount(0);
112
+ setShowEscapePrompt(false);
113
+ }, []);
114
+
115
+ // Notify parent component about escape prompt state changes
116
+ useEffect(() => {
117
+ if (onEscapePromptChange) {
118
+ onEscapePromptChange(showEscapePrompt);
119
+ }
120
+ }, [showEscapePrompt, onEscapePromptChange]);
121
+
122
+ // Clear escape prompt timer on unmount
123
+ useEffect(
124
+ () => () => {
125
+ if (escapeTimerRef.current) {
126
+ clearTimeout(escapeTimerRef.current);
127
+ }
128
+ },
129
+ [],
130
+ );
131
+
132
+ const handleSubmitAndClear = useCallback(
133
+ (submittedValue: string) => {
134
+ if (shellModeActive) {
135
+ shellHistory.addCommandToHistory(submittedValue);
136
+ }
137
+ // Clear the buffer *before* calling onSubmit to prevent potential re-submission
138
+ // if onSubmit triggers a re-render while the buffer still holds the old value.
139
+ buffer.setText('');
140
+ onSubmit(submittedValue);
141
+ resetCompletionState();
142
+ resetReverseSearchCompletionState();
143
+ },
144
+ [
145
+ onSubmit,
146
+ buffer,
147
+ resetCompletionState,
148
+ shellModeActive,
149
+ shellHistory,
150
+ resetReverseSearchCompletionState,
151
+ ],
152
+ );
153
+
154
+ const customSetTextAndResetCompletionSignal = useCallback(
155
+ (newText: string) => {
156
+ buffer.setText(newText);
157
+ setJustNavigatedHistory(true);
158
+ },
159
+ [buffer, setJustNavigatedHistory],
160
+ );
161
+
162
+ const inputHistory = useInputHistory({
163
+ userMessages,
164
+ onSubmit: handleSubmitAndClear,
165
+ isActive:
166
+ (!completion.showSuggestions || completion.suggestions.length === 1) &&
167
+ !shellModeActive,
168
+ currentQuery: buffer.text,
169
+ onChange: customSetTextAndResetCompletionSignal,
170
+ });
171
+
172
+ // Effect to reset completion if history navigation just occurred and set the text
173
+ useEffect(() => {
174
+ if (justNavigatedHistory) {
175
+ resetCompletionState();
176
+ resetReverseSearchCompletionState();
177
+ setJustNavigatedHistory(false);
178
+ }
179
+ }, [
180
+ justNavigatedHistory,
181
+ buffer.text,
182
+ resetCompletionState,
183
+ setJustNavigatedHistory,
184
+ resetReverseSearchCompletionState,
185
+ ]);
186
+
187
+ // Handle clipboard image pasting with Ctrl+V
188
+ const handleClipboardImage = useCallback(async () => {
189
+ try {
190
+ if (await clipboardHasImage()) {
191
+ const imagePath = await saveClipboardImage(config.getTargetDir());
192
+ if (imagePath) {
193
+ // Clean up old images
194
+ cleanupOldClipboardImages(config.getTargetDir()).catch(() => {
195
+ // Ignore cleanup errors
196
+ });
197
+
198
+ // Get relative path from current directory
199
+ const relativePath = path.relative(config.getTargetDir(), imagePath);
200
+
201
+ // Insert @path reference at cursor position
202
+ const insertText = `@${relativePath}`;
203
+ const currentText = buffer.text;
204
+ const [row, col] = buffer.cursor;
205
+
206
+ // Calculate offset from row/col
207
+ let offset = 0;
208
+ for (let i = 0; i < row; i++) {
209
+ offset += buffer.lines[i].length + 1; // +1 for newline
210
+ }
211
+ offset += col;
212
+
213
+ // Add spaces around the path if needed
214
+ let textToInsert = insertText;
215
+ const charBefore = offset > 0 ? currentText[offset - 1] : '';
216
+ const charAfter =
217
+ offset < currentText.length ? currentText[offset] : '';
218
+
219
+ if (charBefore && charBefore !== ' ' && charBefore !== '\n') {
220
+ textToInsert = ' ' + textToInsert;
221
+ }
222
+ if (!charAfter || (charAfter !== ' ' && charAfter !== '\n')) {
223
+ textToInsert = textToInsert + ' ';
224
+ }
225
+
226
+ // Insert at cursor position
227
+ buffer.replaceRangeByOffset(offset, offset, textToInsert);
228
+ }
229
+ }
230
+ } catch (error) {
231
+ console.error('Error handling clipboard image:', error);
232
+ }
233
+ }, [buffer, config]);
234
+
235
+ const handleInput = useCallback(
236
+ (key: Key) => {
237
+ /// We want to handle paste even when not focused to support drag and drop.
238
+ if (!focus && !key.paste) {
239
+ return;
240
+ }
241
+
242
+ if (key.paste) {
243
+ // Ensure we never accidentally interpret paste as regular input.
244
+ buffer.handleInput(key);
245
+ return;
246
+ }
247
+
248
+ if (vimHandleInput && vimHandleInput(key)) {
249
+ return;
250
+ }
251
+
252
+ // Reset ESC count and hide prompt on any non-ESC key
253
+ if (key.name !== 'escape') {
254
+ if (escPressCount > 0 || showEscapePrompt) {
255
+ resetEscapeState();
256
+ }
257
+ }
258
+
259
+ if (
260
+ key.sequence === '!' &&
261
+ buffer.text === '' &&
262
+ !completion.showSuggestions
263
+ ) {
264
+ setShellModeActive(!shellModeActive);
265
+ buffer.setText(''); // Clear the '!' from input
266
+ return;
267
+ }
268
+
269
+ if (keyMatchers[Command.ESCAPE](key)) {
270
+ if (reverseSearchActive) {
271
+ setReverseSearchActive(false);
272
+ reverseSearchCompletion.resetCompletionState();
273
+ buffer.setText(textBeforeReverseSearch);
274
+ const offset = logicalPosToOffset(
275
+ buffer.lines,
276
+ cursorPosition[0],
277
+ cursorPosition[1],
278
+ );
279
+ buffer.moveToOffset(offset);
280
+ return;
281
+ }
282
+ if (shellModeActive) {
283
+ setShellModeActive(false);
284
+ resetEscapeState();
285
+ return;
286
+ }
287
+
288
+ if (completion.showSuggestions) {
289
+ completion.resetCompletionState();
290
+ resetEscapeState();
291
+ return;
292
+ }
293
+
294
+ // Handle double ESC for clearing input
295
+ if (escPressCount === 0) {
296
+ if (buffer.text === '') {
297
+ return;
298
+ }
299
+ setEscPressCount(1);
300
+ setShowEscapePrompt(true);
301
+ if (escapeTimerRef.current) {
302
+ clearTimeout(escapeTimerRef.current);
303
+ }
304
+ escapeTimerRef.current = setTimeout(() => {
305
+ resetEscapeState();
306
+ }, 500);
307
+ } else {
308
+ // clear input and immediately reset state
309
+ buffer.setText('');
310
+ resetCompletionState();
311
+ resetEscapeState();
312
+ }
313
+ return;
314
+ }
315
+
316
+ if (shellModeActive && keyMatchers[Command.REVERSE_SEARCH](key)) {
317
+ setReverseSearchActive(true);
318
+ setTextBeforeReverseSearch(buffer.text);
319
+ setCursorPosition(buffer.cursor);
320
+ return;
321
+ }
322
+
323
+ if (keyMatchers[Command.CLEAR_SCREEN](key)) {
324
+ onClearScreen();
325
+ return;
326
+ }
327
+
328
+ if (reverseSearchActive) {
329
+ const {
330
+ activeSuggestionIndex,
331
+ navigateUp,
332
+ navigateDown,
333
+ showSuggestions,
334
+ suggestions,
335
+ } = reverseSearchCompletion;
336
+
337
+ if (showSuggestions) {
338
+ if (keyMatchers[Command.NAVIGATION_UP](key)) {
339
+ navigateUp();
340
+ return;
341
+ }
342
+ if (keyMatchers[Command.NAVIGATION_DOWN](key)) {
343
+ navigateDown();
344
+ return;
345
+ }
346
+ if (keyMatchers[Command.ACCEPT_SUGGESTION_REVERSE_SEARCH](key)) {
347
+ reverseSearchCompletion.handleAutocomplete(activeSuggestionIndex);
348
+ reverseSearchCompletion.resetCompletionState();
349
+ setReverseSearchActive(false);
350
+ return;
351
+ }
352
+ }
353
+
354
+ if (keyMatchers[Command.SUBMIT_REVERSE_SEARCH](key)) {
355
+ const textToSubmit =
356
+ showSuggestions && activeSuggestionIndex > -1
357
+ ? suggestions[activeSuggestionIndex].value
358
+ : buffer.text;
359
+ handleSubmitAndClear(textToSubmit);
360
+ reverseSearchCompletion.resetCompletionState();
361
+ setReverseSearchActive(false);
362
+ return;
363
+ }
364
+
365
+ // Prevent up/down from falling through to regular history navigation
366
+ if (
367
+ keyMatchers[Command.NAVIGATION_UP](key) ||
368
+ keyMatchers[Command.NAVIGATION_DOWN](key)
369
+ ) {
370
+ return;
371
+ }
372
+ }
373
+
374
+ // If the command is a perfect match, pressing enter should execute it.
375
+ if (completion.isPerfectMatch && keyMatchers[Command.RETURN](key)) {
376
+ handleSubmitAndClear(buffer.text);
377
+ return;
378
+ }
379
+
380
+ if (completion.showSuggestions) {
381
+ if (completion.suggestions.length > 1) {
382
+ if (keyMatchers[Command.COMPLETION_UP](key)) {
383
+ completion.navigateUp();
384
+ return;
385
+ }
386
+ if (keyMatchers[Command.COMPLETION_DOWN](key)) {
387
+ completion.navigateDown();
388
+ return;
389
+ }
390
+ }
391
+
392
+ if (keyMatchers[Command.ACCEPT_SUGGESTION](key)) {
393
+ if (completion.suggestions.length > 0) {
394
+ const targetIndex =
395
+ completion.activeSuggestionIndex === -1
396
+ ? 0 // Default to the first if none is active
397
+ : completion.activeSuggestionIndex;
398
+ if (targetIndex < completion.suggestions.length) {
399
+ completion.handleAutocomplete(targetIndex);
400
+ }
401
+ }
402
+ return;
403
+ }
404
+ }
405
+
406
+ if (!shellModeActive) {
407
+ if (keyMatchers[Command.HISTORY_UP](key)) {
408
+ inputHistory.navigateUp();
409
+ return;
410
+ }
411
+ if (keyMatchers[Command.HISTORY_DOWN](key)) {
412
+ inputHistory.navigateDown();
413
+ return;
414
+ }
415
+ // Handle arrow-up/down for history on single-line or at edges
416
+ if (
417
+ keyMatchers[Command.NAVIGATION_UP](key) &&
418
+ (buffer.allVisualLines.length === 1 ||
419
+ (buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0))
420
+ ) {
421
+ inputHistory.navigateUp();
422
+ return;
423
+ }
424
+ if (
425
+ keyMatchers[Command.NAVIGATION_DOWN](key) &&
426
+ (buffer.allVisualLines.length === 1 ||
427
+ buffer.visualCursor[0] === buffer.allVisualLines.length - 1)
428
+ ) {
429
+ inputHistory.navigateDown();
430
+ return;
431
+ }
432
+ } else {
433
+ // Shell History Navigation
434
+ if (keyMatchers[Command.NAVIGATION_UP](key)) {
435
+ const prevCommand = shellHistory.getPreviousCommand();
436
+ if (prevCommand !== null) buffer.setText(prevCommand);
437
+ return;
438
+ }
439
+ if (keyMatchers[Command.NAVIGATION_DOWN](key)) {
440
+ const nextCommand = shellHistory.getNextCommand();
441
+ if (nextCommand !== null) buffer.setText(nextCommand);
442
+ return;
443
+ }
444
+ }
445
+
446
+ if (keyMatchers[Command.SUBMIT](key)) {
447
+ if (buffer.text.trim()) {
448
+ const [row, col] = buffer.cursor;
449
+ const line = buffer.lines[row];
450
+ const charBefore = col > 0 ? cpSlice(line, col - 1, col) : '';
451
+ if (charBefore === '\\') {
452
+ buffer.backspace();
453
+ buffer.newline();
454
+ } else {
455
+ handleSubmitAndClear(buffer.text);
456
+ }
457
+ }
458
+ return;
459
+ }
460
+
461
+ // Newline insertion
462
+ if (keyMatchers[Command.NEWLINE](key)) {
463
+ buffer.newline();
464
+ return;
465
+ }
466
+
467
+ // Ctrl+A (Home) / Ctrl+E (End)
468
+ if (keyMatchers[Command.HOME](key)) {
469
+ buffer.move('home');
470
+ return;
471
+ }
472
+ if (keyMatchers[Command.END](key)) {
473
+ buffer.move('end');
474
+ buffer.moveToOffset(cpLen(buffer.text));
475
+ return;
476
+ }
477
+ // Ctrl+C (Clear input)
478
+ if (keyMatchers[Command.CLEAR_INPUT](key)) {
479
+ if (buffer.text.length > 0) {
480
+ buffer.setText('');
481
+ resetCompletionState();
482
+ }
483
+ return;
484
+ }
485
+
486
+ // Kill line commands
487
+ if (keyMatchers[Command.KILL_LINE_RIGHT](key)) {
488
+ buffer.killLineRight();
489
+ return;
490
+ }
491
+ if (keyMatchers[Command.KILL_LINE_LEFT](key)) {
492
+ buffer.killLineLeft();
493
+ return;
494
+ }
495
+
496
+ // External editor
497
+ if (keyMatchers[Command.OPEN_EXTERNAL_EDITOR](key)) {
498
+ buffer.openInExternalEditor();
499
+ return;
500
+ }
501
+
502
+ // Ctrl+V for clipboard image paste
503
+ if (keyMatchers[Command.PASTE_CLIPBOARD_IMAGE](key)) {
504
+ handleClipboardImage();
505
+ return;
506
+ }
507
+
508
+ // Fall back to the text buffer's default input handling for all other keys
509
+ buffer.handleInput(key);
510
+ },
511
+ [
512
+ focus,
513
+ buffer,
514
+ completion,
515
+ shellModeActive,
516
+ setShellModeActive,
517
+ onClearScreen,
518
+ inputHistory,
519
+ handleSubmitAndClear,
520
+ shellHistory,
521
+ reverseSearchCompletion,
522
+ handleClipboardImage,
523
+ resetCompletionState,
524
+ escPressCount,
525
+ showEscapePrompt,
526
+ resetEscapeState,
527
+ vimHandleInput,
528
+ reverseSearchActive,
529
+ textBeforeReverseSearch,
530
+ cursorPosition,
531
+ ],
532
+ );
533
+
534
+ useKeypress(handleInput, {
535
+ isActive: true,
536
+ });
537
+
538
+ const linesToRender = buffer.viewportVisualLines;
539
+ const [cursorVisualRowAbsolute, cursorVisualColAbsolute] =
540
+ buffer.visualCursor;
541
+ const scrollVisualRow = buffer.visualScrollRow;
542
+
543
+ return (
544
+ <>
545
+ <Box
546
+ borderStyle="round"
547
+ borderColor={
548
+ shellModeActive ? theme.status.warning : theme.border.focused
549
+ }
550
+ paddingX={1}
551
+ >
552
+ <Text
553
+ color={shellModeActive ? theme.status.warning : theme.text.accent}
554
+ >
555
+ {shellModeActive ? (
556
+ reverseSearchActive ? (
557
+ <Text color={theme.text.link}>(r:) </Text>
558
+ ) : (
559
+ '! '
560
+ )
561
+ ) : (
562
+ '> '
563
+ )}
564
+ </Text>
565
+ <Box flexGrow={1} flexDirection="column">
566
+ {buffer.text.length === 0 && placeholder ? (
567
+ focus ? (
568
+ <Text>
569
+ {chalk.inverse(placeholder.slice(0, 1))}
570
+ <Text color={theme.text.secondary}>{placeholder.slice(1)}</Text>
571
+ </Text>
572
+ ) : (
573
+ <Text color={theme.text.secondary}>{placeholder}</Text>
574
+ )
575
+ ) : (
576
+ linesToRender.map((lineText, visualIdxInRenderedSet) => {
577
+ const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
578
+ let display = cpSlice(lineText, 0, inputWidth);
579
+ const currentVisualWidth = stringWidth(display);
580
+ if (currentVisualWidth < inputWidth) {
581
+ display = display + ' '.repeat(inputWidth - currentVisualWidth);
582
+ }
583
+
584
+ if (focus && visualIdxInRenderedSet === cursorVisualRow) {
585
+ const relativeVisualColForHighlight = cursorVisualColAbsolute;
586
+
587
+ if (relativeVisualColForHighlight >= 0) {
588
+ if (relativeVisualColForHighlight < cpLen(display)) {
589
+ const charToHighlight =
590
+ cpSlice(
591
+ display,
592
+ relativeVisualColForHighlight,
593
+ relativeVisualColForHighlight + 1,
594
+ ) || ' ';
595
+ const highlighted = chalk.inverse(charToHighlight);
596
+ display =
597
+ cpSlice(display, 0, relativeVisualColForHighlight) +
598
+ highlighted +
599
+ cpSlice(display, relativeVisualColForHighlight + 1);
600
+ } else if (
601
+ relativeVisualColForHighlight === cpLen(display) &&
602
+ cpLen(display) === inputWidth
603
+ ) {
604
+ display = display + chalk.inverse(' ');
605
+ }
606
+ }
607
+ }
608
+ return (
609
+ <Text key={`line-${visualIdxInRenderedSet}`}>{display}</Text>
610
+ );
611
+ })
612
+ )}
613
+ </Box>
614
+ </Box>
615
+ {completion.showSuggestions && (
616
+ <Box paddingRight={2}>
617
+ <SuggestionsDisplay
618
+ suggestions={completion.suggestions}
619
+ activeIndex={completion.activeSuggestionIndex}
620
+ isLoading={completion.isLoadingSuggestions}
621
+ width={suggestionsWidth}
622
+ scrollOffset={completion.visibleStartIndex}
623
+ userInput={buffer.text}
624
+ />
625
+ </Box>
626
+ )}
627
+ {reverseSearchActive && (
628
+ <Box paddingRight={2}>
629
+ <SuggestionsDisplay
630
+ suggestions={reverseSearchCompletion.suggestions}
631
+ activeIndex={reverseSearchCompletion.activeSuggestionIndex}
632
+ isLoading={reverseSearchCompletion.isLoadingSuggestions}
633
+ width={suggestionsWidth}
634
+ scrollOffset={reverseSearchCompletion.visibleStartIndex}
635
+ userInput={buffer.text}
636
+ />
637
+ </Box>
638
+ )}
639
+ </>
640
+ );
641
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/LoadingIndicator.test.tsx ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { render } from 'ink-testing-library';
9
+ import { Text } from 'ink';
10
+ import { LoadingIndicator } from './LoadingIndicator.js';
11
+ import { StreamingContext } from '../contexts/StreamingContext.js';
12
+ import { StreamingState } from '../types.js';
13
+ import { vi } from 'vitest';
14
+ import * as useTerminalSize from '../hooks/useTerminalSize.js';
15
+
16
+ // Mock GeminiRespondingSpinner
17
+ vi.mock('./GeminiRespondingSpinner.js', () => ({
18
+ GeminiRespondingSpinner: ({
19
+ nonRespondingDisplay,
20
+ }: {
21
+ nonRespondingDisplay?: string;
22
+ }) => {
23
+ const streamingState = React.useContext(StreamingContext)!;
24
+ if (streamingState === StreamingState.Responding) {
25
+ return <Text>MockRespondingSpinner</Text>;
26
+ } else if (nonRespondingDisplay) {
27
+ return <Text>{nonRespondingDisplay}</Text>;
28
+ }
29
+ return null;
30
+ },
31
+ }));
32
+
33
+ vi.mock('../hooks/useTerminalSize.js', () => ({
34
+ useTerminalSize: vi.fn(),
35
+ }));
36
+
37
+ const useTerminalSizeMock = vi.mocked(useTerminalSize.useTerminalSize);
38
+
39
+ const renderWithContext = (
40
+ ui: React.ReactElement,
41
+ streamingStateValue: StreamingState,
42
+ width = 120,
43
+ ) => {
44
+ useTerminalSizeMock.mockReturnValue({ columns: width, rows: 24 });
45
+ const contextValue: StreamingState = streamingStateValue;
46
+ return render(
47
+ <StreamingContext.Provider value={contextValue}>
48
+ {ui}
49
+ </StreamingContext.Provider>,
50
+ );
51
+ };
52
+
53
+ describe('<LoadingIndicator />', () => {
54
+ const defaultProps = {
55
+ currentLoadingPhrase: 'Loading...',
56
+ elapsedTime: 5,
57
+ };
58
+
59
+ it('should not render when streamingState is Idle', () => {
60
+ const { lastFrame } = renderWithContext(
61
+ <LoadingIndicator {...defaultProps} />,
62
+ StreamingState.Idle,
63
+ );
64
+ expect(lastFrame()).toBe('');
65
+ });
66
+
67
+ it('should render spinner, phrase, and time when streamingState is Responding', () => {
68
+ const { lastFrame } = renderWithContext(
69
+ <LoadingIndicator {...defaultProps} />,
70
+ StreamingState.Responding,
71
+ );
72
+ const output = lastFrame();
73
+ expect(output).toContain('MockRespondingSpinner');
74
+ expect(output).toContain('Loading...');
75
+ expect(output).toContain('(esc to cancel, 5s)');
76
+ });
77
+
78
+ it('should render spinner (static), phrase but no time/cancel when streamingState is WaitingForConfirmation', () => {
79
+ const props = {
80
+ currentLoadingPhrase: 'Confirm action',
81
+ elapsedTime: 10,
82
+ };
83
+ const { lastFrame } = renderWithContext(
84
+ <LoadingIndicator {...props} />,
85
+ StreamingState.WaitingForConfirmation,
86
+ );
87
+ const output = lastFrame();
88
+ expect(output).toContain('⠏'); // Static char for WaitingForConfirmation
89
+ expect(output).toContain('Confirm action');
90
+ expect(output).not.toContain('(esc to cancel)');
91
+ expect(output).not.toContain(', 10s');
92
+ });
93
+
94
+ it('should display the currentLoadingPhrase correctly', () => {
95
+ const props = {
96
+ currentLoadingPhrase: 'Processing data...',
97
+ elapsedTime: 3,
98
+ };
99
+ const { lastFrame } = renderWithContext(
100
+ <LoadingIndicator {...props} />,
101
+ StreamingState.Responding,
102
+ );
103
+ expect(lastFrame()).toContain('Processing data...');
104
+ });
105
+
106
+ it('should display the elapsedTime correctly when Responding', () => {
107
+ const props = {
108
+ currentLoadingPhrase: 'Working...',
109
+ elapsedTime: 60,
110
+ };
111
+ const { lastFrame } = renderWithContext(
112
+ <LoadingIndicator {...props} />,
113
+ StreamingState.Responding,
114
+ );
115
+ expect(lastFrame()).toContain('(esc to cancel, 1m)');
116
+ });
117
+
118
+ it('should display the elapsedTime correctly in human-readable format', () => {
119
+ const props = {
120
+ currentLoadingPhrase: 'Working...',
121
+ elapsedTime: 125,
122
+ };
123
+ const { lastFrame } = renderWithContext(
124
+ <LoadingIndicator {...props} />,
125
+ StreamingState.Responding,
126
+ );
127
+ expect(lastFrame()).toContain('(esc to cancel, 2m 5s)');
128
+ });
129
+
130
+ it('should render rightContent when provided', () => {
131
+ const rightContent = <Text>Extra Info</Text>;
132
+ const { lastFrame } = renderWithContext(
133
+ <LoadingIndicator {...defaultProps} rightContent={rightContent} />,
134
+ StreamingState.Responding,
135
+ );
136
+ expect(lastFrame()).toContain('Extra Info');
137
+ });
138
+
139
+ it('should transition correctly between states using rerender', () => {
140
+ const { lastFrame, rerender } = renderWithContext(
141
+ <LoadingIndicator {...defaultProps} />,
142
+ StreamingState.Idle,
143
+ );
144
+ expect(lastFrame()).toBe(''); // Initial: Idle
145
+
146
+ // Transition to Responding
147
+ rerender(
148
+ <StreamingContext.Provider value={StreamingState.Responding}>
149
+ <LoadingIndicator
150
+ currentLoadingPhrase="Now Responding"
151
+ elapsedTime={2}
152
+ />
153
+ </StreamingContext.Provider>,
154
+ );
155
+ let output = lastFrame();
156
+ expect(output).toContain('MockRespondingSpinner');
157
+ expect(output).toContain('Now Responding');
158
+ expect(output).toContain('(esc to cancel, 2s)');
159
+
160
+ // Transition to WaitingForConfirmation
161
+ rerender(
162
+ <StreamingContext.Provider value={StreamingState.WaitingForConfirmation}>
163
+ <LoadingIndicator
164
+ currentLoadingPhrase="Please Confirm"
165
+ elapsedTime={15}
166
+ />
167
+ </StreamingContext.Provider>,
168
+ );
169
+ output = lastFrame();
170
+ expect(output).toContain('⠏');
171
+ expect(output).toContain('Please Confirm');
172
+ expect(output).not.toContain('(esc to cancel)');
173
+ expect(output).not.toContain(', 15s');
174
+
175
+ // Transition back to Idle
176
+ rerender(
177
+ <StreamingContext.Provider value={StreamingState.Idle}>
178
+ <LoadingIndicator {...defaultProps} />
179
+ </StreamingContext.Provider>,
180
+ );
181
+ expect(lastFrame()).toBe('');
182
+ });
183
+
184
+ it('should display fallback phrase if thought is empty', () => {
185
+ const props = {
186
+ thought: null,
187
+ currentLoadingPhrase: 'Loading...',
188
+ elapsedTime: 5,
189
+ };
190
+ const { lastFrame } = renderWithContext(
191
+ <LoadingIndicator {...props} />,
192
+ StreamingState.Responding,
193
+ );
194
+ const output = lastFrame();
195
+ expect(output).toContain('Loading...');
196
+ });
197
+
198
+ it('should display the subject of a thought', () => {
199
+ const props = {
200
+ thought: {
201
+ subject: 'Thinking about something...',
202
+ description: 'and other stuff.',
203
+ },
204
+ elapsedTime: 5,
205
+ };
206
+ const { lastFrame } = renderWithContext(
207
+ <LoadingIndicator {...props} />,
208
+ StreamingState.Responding,
209
+ );
210
+ const output = lastFrame();
211
+ expect(output).toBeDefined();
212
+ if (output) {
213
+ expect(output).toContain('Thinking about something...');
214
+ expect(output).not.toContain('and other stuff.');
215
+ }
216
+ });
217
+
218
+ it('should prioritize thought.subject over currentLoadingPhrase', () => {
219
+ const props = {
220
+ thought: {
221
+ subject: 'This should be displayed',
222
+ description: 'A description',
223
+ },
224
+ currentLoadingPhrase: 'This should not be displayed',
225
+ elapsedTime: 5,
226
+ };
227
+ const { lastFrame } = renderWithContext(
228
+ <LoadingIndicator {...props} />,
229
+ StreamingState.Responding,
230
+ );
231
+ const output = lastFrame();
232
+ expect(output).toContain('This should be displayed');
233
+ expect(output).not.toContain('This should not be displayed');
234
+ });
235
+
236
+ describe('responsive layout', () => {
237
+ it('should render on a single line on a wide terminal', () => {
238
+ const { lastFrame } = renderWithContext(
239
+ <LoadingIndicator
240
+ {...defaultProps}
241
+ rightContent={<Text>Right</Text>}
242
+ />,
243
+ StreamingState.Responding,
244
+ 120,
245
+ );
246
+ const output = lastFrame();
247
+ // Check for single line output
248
+ expect(output?.includes('\n')).toBe(false);
249
+ expect(output).toContain('Loading...');
250
+ expect(output).toContain('(esc to cancel, 5s)');
251
+ expect(output).toContain('Right');
252
+ });
253
+
254
+ it('should render on multiple lines on a narrow terminal', () => {
255
+ const { lastFrame } = renderWithContext(
256
+ <LoadingIndicator
257
+ {...defaultProps}
258
+ rightContent={<Text>Right</Text>}
259
+ />,
260
+ StreamingState.Responding,
261
+ 79,
262
+ );
263
+ const output = lastFrame();
264
+ const lines = output?.split('\n');
265
+ // Expecting 3 lines:
266
+ // 1. Spinner + Primary Text
267
+ // 2. Cancel + Timer
268
+ // 3. Right Content
269
+ expect(lines).toHaveLength(3);
270
+ if (lines) {
271
+ expect(lines[0]).toContain('Loading...');
272
+ expect(lines[0]).not.toContain('(esc to cancel, 5s)');
273
+ expect(lines[1]).toContain('(esc to cancel, 5s)');
274
+ expect(lines[2]).toContain('Right');
275
+ }
276
+ });
277
+
278
+ it('should use wide layout at 80 columns', () => {
279
+ const { lastFrame } = renderWithContext(
280
+ <LoadingIndicator {...defaultProps} />,
281
+ StreamingState.Responding,
282
+ 80,
283
+ );
284
+ expect(lastFrame()?.includes('\n')).toBe(false);
285
+ });
286
+
287
+ it('should use narrow layout at 79 columns', () => {
288
+ const { lastFrame } = renderWithContext(
289
+ <LoadingIndicator {...defaultProps} />,
290
+ StreamingState.Responding,
291
+ 79,
292
+ );
293
+ expect(lastFrame()?.includes('\n')).toBe(true);
294
+ });
295
+ });
296
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/LoadingIndicator.tsx ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { ThoughtSummary } from '@qwen-code/qwen-code-core';
8
+ import React from 'react';
9
+ import { Box, Text } from 'ink';
10
+ import { Colors } from '../colors.js';
11
+ import { useStreamingContext } from '../contexts/StreamingContext.js';
12
+ import { StreamingState } from '../types.js';
13
+ import { GeminiRespondingSpinner } from './GeminiRespondingSpinner.js';
14
+ import { formatDuration } from '../utils/formatters.js';
15
+ import { useTerminalSize } from '../hooks/useTerminalSize.js';
16
+ import { isNarrowWidth } from '../utils/isNarrowWidth.js';
17
+
18
+ interface LoadingIndicatorProps {
19
+ currentLoadingPhrase?: string;
20
+ elapsedTime: number;
21
+ rightContent?: React.ReactNode;
22
+ thought?: ThoughtSummary | null;
23
+ }
24
+
25
+ export const LoadingIndicator: React.FC<LoadingIndicatorProps> = ({
26
+ currentLoadingPhrase,
27
+ elapsedTime,
28
+ rightContent,
29
+ thought,
30
+ }) => {
31
+ const streamingState = useStreamingContext();
32
+ const { columns: terminalWidth } = useTerminalSize();
33
+ const isNarrow = isNarrowWidth(terminalWidth);
34
+
35
+ if (streamingState === StreamingState.Idle) {
36
+ return null;
37
+ }
38
+
39
+ const primaryText = thought?.subject || currentLoadingPhrase;
40
+
41
+ const cancelAndTimerContent =
42
+ streamingState !== StreamingState.WaitingForConfirmation
43
+ ? `(esc to cancel, ${elapsedTime < 60 ? `${elapsedTime}s` : formatDuration(elapsedTime * 1000)})`
44
+ : null;
45
+
46
+ return (
47
+ <Box paddingLeft={0} flexDirection="column">
48
+ {/* Main loading line */}
49
+ <Box
50
+ width="100%"
51
+ flexDirection={isNarrow ? 'column' : 'row'}
52
+ alignItems={isNarrow ? 'flex-start' : 'center'}
53
+ >
54
+ <Box>
55
+ <Box marginRight={1}>
56
+ <GeminiRespondingSpinner
57
+ nonRespondingDisplay={
58
+ streamingState === StreamingState.WaitingForConfirmation
59
+ ? '⠏'
60
+ : ''
61
+ }
62
+ />
63
+ </Box>
64
+ {primaryText && (
65
+ <Text color={Colors.AccentPurple}>{primaryText}</Text>
66
+ )}
67
+ {!isNarrow && cancelAndTimerContent && (
68
+ <Text color={Colors.Gray}> {cancelAndTimerContent}</Text>
69
+ )}
70
+ </Box>
71
+ {!isNarrow && <Box flexGrow={1}>{/* Spacer */}</Box>}
72
+ {!isNarrow && rightContent && <Box>{rightContent}</Box>}
73
+ </Box>
74
+ {isNarrow && cancelAndTimerContent && (
75
+ <Box>
76
+ <Text color={Colors.Gray}>{cancelAndTimerContent}</Text>
77
+ </Box>
78
+ )}
79
+ {isNarrow && rightContent && <Box>{rightContent}</Box>}
80
+ </Box>
81
+ );
82
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/MemoryUsageDisplay.tsx ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React, { useEffect, useState } from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import process from 'node:process';
11
+ import { formatMemoryUsage } from '../utils/formatters.js';
12
+
13
+ export const MemoryUsageDisplay: React.FC = () => {
14
+ const [memoryUsage, setMemoryUsage] = useState<string>('');
15
+ const [memoryUsageColor, setMemoryUsageColor] = useState<string>(Colors.Gray);
16
+
17
+ useEffect(() => {
18
+ const updateMemory = () => {
19
+ const usage = process.memoryUsage().rss;
20
+ setMemoryUsage(formatMemoryUsage(usage));
21
+ setMemoryUsageColor(
22
+ usage >= 2 * 1024 * 1024 * 1024 ? Colors.AccentRed : Colors.Gray,
23
+ );
24
+ };
25
+ const intervalId = setInterval(updateMemory, 2000);
26
+ updateMemory(); // Initial update
27
+ return () => clearInterval(intervalId);
28
+ }, []);
29
+
30
+ return (
31
+ <Box>
32
+ <Text color={Colors.Gray}>| </Text>
33
+ <Text color={memoryUsageColor}>{memoryUsage}</Text>
34
+ </Box>
35
+ );
36
+ };
projects/ui/qwen-code/packages/cli/src/ui/components/ModelStatsDisplay.test.tsx ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, beforeAll, afterAll } from 'vitest';
9
+ import { ModelStatsDisplay } from './ModelStatsDisplay.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
+ sessionStartTime: new Date(),
28
+ metrics,
29
+ lastPromptTokenCount: 0,
30
+ promptCount: 5,
31
+ },
32
+
33
+ getPromptCount: () => 5,
34
+ startNewPrompt: vi.fn(),
35
+ });
36
+
37
+ return render(<ModelStatsDisplay />);
38
+ };
39
+
40
+ describe('<ModelStatsDisplay />', () => {
41
+ beforeAll(() => {
42
+ vi.spyOn(Number.prototype, 'toLocaleString').mockImplementation(function (
43
+ this: number,
44
+ ) {
45
+ // Use a stable 'en-US' format for test consistency.
46
+ return new Intl.NumberFormat('en-US').format(this);
47
+ });
48
+ });
49
+
50
+ afterAll(() => {
51
+ vi.restoreAllMocks();
52
+ });
53
+
54
+ it('should render "no API calls" message when there are no active models', () => {
55
+ const { lastFrame } = renderWithMockedStats({
56
+ models: {},
57
+ tools: {
58
+ totalCalls: 0,
59
+ totalSuccess: 0,
60
+ totalFail: 0,
61
+ totalDurationMs: 0,
62
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
63
+ byName: {},
64
+ },
65
+ });
66
+
67
+ expect(lastFrame()).toContain(
68
+ 'No API calls have been made in this session.',
69
+ );
70
+ expect(lastFrame()).toMatchSnapshot();
71
+ });
72
+
73
+ it('should not display conditional rows if no model has data for them', () => {
74
+ const { lastFrame } = renderWithMockedStats({
75
+ models: {
76
+ 'gemini-2.5-pro': {
77
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 100 },
78
+ tokens: {
79
+ prompt: 10,
80
+ candidates: 20,
81
+ total: 30,
82
+ cached: 0,
83
+ thoughts: 0,
84
+ tool: 0,
85
+ },
86
+ },
87
+ },
88
+ tools: {
89
+ totalCalls: 0,
90
+ totalSuccess: 0,
91
+ totalFail: 0,
92
+ totalDurationMs: 0,
93
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
94
+ byName: {},
95
+ },
96
+ });
97
+
98
+ const output = lastFrame();
99
+ expect(output).not.toContain('Cached');
100
+ expect(output).not.toContain('Thoughts');
101
+ expect(output).not.toContain('Tool');
102
+ expect(output).toMatchSnapshot();
103
+ });
104
+
105
+ it('should display conditional rows if at least one model has data', () => {
106
+ const { lastFrame } = renderWithMockedStats({
107
+ models: {
108
+ 'gemini-2.5-pro': {
109
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 100 },
110
+ tokens: {
111
+ prompt: 10,
112
+ candidates: 20,
113
+ total: 30,
114
+ cached: 5,
115
+ thoughts: 2,
116
+ tool: 0,
117
+ },
118
+ },
119
+ 'gemini-2.5-flash': {
120
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 50 },
121
+ tokens: {
122
+ prompt: 5,
123
+ candidates: 10,
124
+ total: 15,
125
+ cached: 0,
126
+ thoughts: 0,
127
+ tool: 3,
128
+ },
129
+ },
130
+ },
131
+ tools: {
132
+ totalCalls: 0,
133
+ totalSuccess: 0,
134
+ totalFail: 0,
135
+ totalDurationMs: 0,
136
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
137
+ byName: {},
138
+ },
139
+ });
140
+
141
+ const output = lastFrame();
142
+ expect(output).toContain('Cached');
143
+ expect(output).toContain('Thoughts');
144
+ expect(output).toContain('Tool');
145
+ expect(output).toMatchSnapshot();
146
+ });
147
+
148
+ it('should display stats for multiple models correctly', () => {
149
+ const { lastFrame } = renderWithMockedStats({
150
+ models: {
151
+ 'gemini-2.5-pro': {
152
+ api: { totalRequests: 10, totalErrors: 1, totalLatencyMs: 1000 },
153
+ tokens: {
154
+ prompt: 100,
155
+ candidates: 200,
156
+ total: 300,
157
+ cached: 50,
158
+ thoughts: 10,
159
+ tool: 5,
160
+ },
161
+ },
162
+ 'gemini-2.5-flash': {
163
+ api: { totalRequests: 20, totalErrors: 2, totalLatencyMs: 500 },
164
+ tokens: {
165
+ prompt: 200,
166
+ candidates: 400,
167
+ total: 600,
168
+ cached: 100,
169
+ thoughts: 20,
170
+ tool: 10,
171
+ },
172
+ },
173
+ },
174
+ tools: {
175
+ totalCalls: 0,
176
+ totalSuccess: 0,
177
+ totalFail: 0,
178
+ totalDurationMs: 0,
179
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
180
+ byName: {},
181
+ },
182
+ });
183
+
184
+ const output = lastFrame();
185
+ expect(output).toContain('gemini-2.5-pro');
186
+ expect(output).toContain('gemini-2.5-flash');
187
+ expect(output).toMatchSnapshot();
188
+ });
189
+
190
+ it('should handle large values without wrapping or overlapping', () => {
191
+ const { lastFrame } = renderWithMockedStats({
192
+ models: {
193
+ 'gemini-2.5-pro': {
194
+ api: {
195
+ totalRequests: 999999999,
196
+ totalErrors: 123456789,
197
+ totalLatencyMs: 9876,
198
+ },
199
+ tokens: {
200
+ prompt: 987654321,
201
+ candidates: 123456789,
202
+ total: 999999999,
203
+ cached: 123456789,
204
+ thoughts: 111111111,
205
+ tool: 222222222,
206
+ },
207
+ },
208
+ },
209
+ tools: {
210
+ totalCalls: 0,
211
+ totalSuccess: 0,
212
+ totalFail: 0,
213
+ totalDurationMs: 0,
214
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
215
+ byName: {},
216
+ },
217
+ });
218
+
219
+ expect(lastFrame()).toMatchSnapshot();
220
+ });
221
+
222
+ it('should display a single model correctly', () => {
223
+ const { lastFrame } = renderWithMockedStats({
224
+ models: {
225
+ 'gemini-2.5-pro': {
226
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 100 },
227
+ tokens: {
228
+ prompt: 10,
229
+ candidates: 20,
230
+ total: 30,
231
+ cached: 5,
232
+ thoughts: 2,
233
+ tool: 1,
234
+ },
235
+ },
236
+ },
237
+ tools: {
238
+ totalCalls: 0,
239
+ totalSuccess: 0,
240
+ totalFail: 0,
241
+ totalDurationMs: 0,
242
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
243
+ byName: {},
244
+ },
245
+ });
246
+
247
+ const output = lastFrame();
248
+ expect(output).toContain('gemini-2.5-pro');
249
+ expect(output).not.toContain('gemini-2.5-flash');
250
+ expect(output).toMatchSnapshot();
251
+ });
252
+ });
projects/ui/qwen-code/packages/cli/src/ui/components/ModelStatsDisplay.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 from 'react';
8
+ import { Box, Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import { formatDuration } from '../utils/formatters.js';
11
+ import {
12
+ calculateAverageLatency,
13
+ calculateCacheHitRate,
14
+ calculateErrorRate,
15
+ } from '../utils/computeStats.js';
16
+ import { useSessionStats, ModelMetrics } from '../contexts/SessionContext.js';
17
+
18
+ const METRIC_COL_WIDTH = 28;
19
+ const MODEL_COL_WIDTH = 22;
20
+
21
+ interface StatRowProps {
22
+ title: string;
23
+ values: Array<string | React.ReactElement>;
24
+ isSubtle?: boolean;
25
+ isSection?: boolean;
26
+ }
27
+
28
+ const StatRow: React.FC<StatRowProps> = ({
29
+ title,
30
+ values,
31
+ isSubtle = false,
32
+ isSection = false,
33
+ }) => (
34
+ <Box>
35
+ <Box width={METRIC_COL_WIDTH}>
36
+ <Text bold={isSection} color={isSection ? undefined : Colors.LightBlue}>
37
+ {isSubtle ? ` ↳ ${title}` : title}
38
+ </Text>
39
+ </Box>
40
+ {values.map((value, index) => (
41
+ <Box width={MODEL_COL_WIDTH} key={index}>
42
+ <Text>{value}</Text>
43
+ </Box>
44
+ ))}
45
+ </Box>
46
+ );
47
+
48
+ export const ModelStatsDisplay: React.FC = () => {
49
+ const { stats } = useSessionStats();
50
+ const { models } = stats.metrics;
51
+ const activeModels = Object.entries(models).filter(
52
+ ([, metrics]) => metrics.api.totalRequests > 0,
53
+ );
54
+
55
+ if (activeModels.length === 0) {
56
+ return (
57
+ <Box
58
+ borderStyle="round"
59
+ borderColor={Colors.Gray}
60
+ paddingY={1}
61
+ paddingX={2}
62
+ >
63
+ <Text>No API calls have been made in this session.</Text>
64
+ </Box>
65
+ );
66
+ }
67
+
68
+ const modelNames = activeModels.map(([name]) => name);
69
+
70
+ const getModelValues = (
71
+ getter: (metrics: ModelMetrics) => string | React.ReactElement,
72
+ ) => activeModels.map(([, metrics]) => getter(metrics));
73
+
74
+ const hasThoughts = activeModels.some(
75
+ ([, metrics]) => metrics.tokens.thoughts > 0,
76
+ );
77
+ const hasTool = activeModels.some(([, metrics]) => metrics.tokens.tool > 0);
78
+ const hasCached = activeModels.some(
79
+ ([, metrics]) => metrics.tokens.cached > 0,
80
+ );
81
+
82
+ return (
83
+ <Box
84
+ borderStyle="round"
85
+ borderColor={Colors.Gray}
86
+ flexDirection="column"
87
+ paddingY={1}
88
+ paddingX={2}
89
+ >
90
+ <Text bold color={Colors.AccentPurple}>
91
+ Model Stats For Nerds
92
+ </Text>
93
+ <Box height={1} />
94
+
95
+ {/* Header */}
96
+ <Box>
97
+ <Box width={METRIC_COL_WIDTH}>
98
+ <Text bold>Metric</Text>
99
+ </Box>
100
+ {modelNames.map((name) => (
101
+ <Box width={MODEL_COL_WIDTH} key={name}>
102
+ <Text bold>{name}</Text>
103
+ </Box>
104
+ ))}
105
+ </Box>
106
+
107
+ {/* Divider */}
108
+ <Box
109
+ borderStyle="single"
110
+ borderBottom={true}
111
+ borderTop={false}
112
+ borderLeft={false}
113
+ borderRight={false}
114
+ />
115
+
116
+ {/* API Section */}
117
+ <StatRow title="API" values={[]} isSection />
118
+ <StatRow
119
+ title="Requests"
120
+ values={getModelValues((m) => m.api.totalRequests.toLocaleString())}
121
+ />
122
+ <StatRow
123
+ title="Errors"
124
+ values={getModelValues((m) => {
125
+ const errorRate = calculateErrorRate(m);
126
+ return (
127
+ <Text
128
+ color={
129
+ m.api.totalErrors > 0 ? Colors.AccentRed : Colors.Foreground
130
+ }
131
+ >
132
+ {m.api.totalErrors.toLocaleString()} ({errorRate.toFixed(1)}%)
133
+ </Text>
134
+ );
135
+ })}
136
+ />
137
+ <StatRow
138
+ title="Avg Latency"
139
+ values={getModelValues((m) => {
140
+ const avgLatency = calculateAverageLatency(m);
141
+ return formatDuration(avgLatency);
142
+ })}
143
+ />
144
+
145
+ <Box height={1} />
146
+
147
+ {/* Tokens Section */}
148
+ <StatRow title="Tokens" values={[]} isSection />
149
+ <StatRow
150
+ title="Total"
151
+ values={getModelValues((m) => (
152
+ <Text color={Colors.AccentYellow}>
153
+ {m.tokens.total.toLocaleString()}
154
+ </Text>
155
+ ))}
156
+ />
157
+ <StatRow
158
+ title="Prompt"
159
+ isSubtle
160
+ values={getModelValues((m) => m.tokens.prompt.toLocaleString())}
161
+ />
162
+ {hasCached && (
163
+ <StatRow
164
+ title="Cached"
165
+ isSubtle
166
+ values={getModelValues((m) => {
167
+ const cacheHitRate = calculateCacheHitRate(m);
168
+ return (
169
+ <Text color={Colors.AccentGreen}>
170
+ {m.tokens.cached.toLocaleString()} ({cacheHitRate.toFixed(1)}%)
171
+ </Text>
172
+ );
173
+ })}
174
+ />
175
+ )}
176
+ {hasThoughts && (
177
+ <StatRow
178
+ title="Thoughts"
179
+ isSubtle
180
+ values={getModelValues((m) => m.tokens.thoughts.toLocaleString())}
181
+ />
182
+ )}
183
+ {hasTool && (
184
+ <StatRow
185
+ title="Tool"
186
+ isSubtle
187
+ values={getModelValues((m) => m.tokens.tool.toLocaleString())}
188
+ />
189
+ )}
190
+ <StatRow
191
+ title="Output"
192
+ isSubtle
193
+ values={getModelValues((m) => m.tokens.candidates.toLocaleString())}
194
+ />
195
+ </Box>
196
+ );
197
+ };