Add files using upload-large-folder tool
Browse files- projects/ui/qwen-code/packages/cli/src/ui/components/ToolStatsDisplay.test.tsx +180 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/ToolStatsDisplay.tsx +208 -0
- projects/ui/qwen-code/packages/cli/src/ui/components/UpdateNotification.tsx +23 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/KeypressContext.test.tsx +391 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/KeypressContext.tsx +440 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/OverflowContext.tsx +87 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/SessionContext.test.tsx +132 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/SessionContext.tsx +143 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/SettingsContext.tsx +20 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/StreamingContext.tsx +22 -0
- projects/ui/qwen-code/packages/cli/src/ui/contexts/VimModeContext.tsx +79 -0
- projects/ui/qwen-code/packages/cli/src/ui/editors/editorSettingsManager.ts +66 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/atCommandProcessor.test.ts +1102 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/atCommandProcessor.ts +485 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/shellCommandProcessor.test.ts +481 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/shellCommandProcessor.ts +314 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/slashCommandProcessor.test.ts +1040 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/slashCommandProcessor.ts +571 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/useAtCompletion.test.ts +497 -0
- projects/ui/qwen-code/packages/cli/src/ui/hooks/useAtCompletion.ts +242 -0
projects/ui/qwen-code/packages/cli/src/ui/components/ToolStatsDisplay.test.tsx
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 { ToolStatsDisplay } from './ToolStatsDisplay.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(<ToolStatsDisplay />);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
describe('<ToolStatsDisplay />', () => {
|
| 41 |
+
it('should render "no tool calls" message when there are no active tools', () => {
|
| 42 |
+
const { lastFrame } = renderWithMockedStats({
|
| 43 |
+
models: {},
|
| 44 |
+
tools: {
|
| 45 |
+
totalCalls: 0,
|
| 46 |
+
totalSuccess: 0,
|
| 47 |
+
totalFail: 0,
|
| 48 |
+
totalDurationMs: 0,
|
| 49 |
+
totalDecisions: { accept: 0, reject: 0, modify: 0 },
|
| 50 |
+
byName: {},
|
| 51 |
+
},
|
| 52 |
+
});
|
| 53 |
+
|
| 54 |
+
expect(lastFrame()).toContain(
|
| 55 |
+
'No tool calls have been made in this session.',
|
| 56 |
+
);
|
| 57 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it('should display stats for a single tool correctly', () => {
|
| 61 |
+
const { lastFrame } = renderWithMockedStats({
|
| 62 |
+
models: {},
|
| 63 |
+
tools: {
|
| 64 |
+
totalCalls: 1,
|
| 65 |
+
totalSuccess: 1,
|
| 66 |
+
totalFail: 0,
|
| 67 |
+
totalDurationMs: 100,
|
| 68 |
+
totalDecisions: { accept: 1, reject: 0, modify: 0 },
|
| 69 |
+
byName: {
|
| 70 |
+
'test-tool': {
|
| 71 |
+
count: 1,
|
| 72 |
+
success: 1,
|
| 73 |
+
fail: 0,
|
| 74 |
+
durationMs: 100,
|
| 75 |
+
decisions: { accept: 1, reject: 0, modify: 0 },
|
| 76 |
+
},
|
| 77 |
+
},
|
| 78 |
+
},
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
const output = lastFrame();
|
| 82 |
+
expect(output).toContain('test-tool');
|
| 83 |
+
expect(output).toMatchSnapshot();
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
it('should display stats for multiple tools correctly', () => {
|
| 87 |
+
const { lastFrame } = renderWithMockedStats({
|
| 88 |
+
models: {},
|
| 89 |
+
tools: {
|
| 90 |
+
totalCalls: 3,
|
| 91 |
+
totalSuccess: 2,
|
| 92 |
+
totalFail: 1,
|
| 93 |
+
totalDurationMs: 300,
|
| 94 |
+
totalDecisions: { accept: 1, reject: 1, modify: 1 },
|
| 95 |
+
byName: {
|
| 96 |
+
'tool-a': {
|
| 97 |
+
count: 2,
|
| 98 |
+
success: 1,
|
| 99 |
+
fail: 1,
|
| 100 |
+
durationMs: 200,
|
| 101 |
+
decisions: { accept: 1, reject: 1, modify: 0 },
|
| 102 |
+
},
|
| 103 |
+
'tool-b': {
|
| 104 |
+
count: 1,
|
| 105 |
+
success: 1,
|
| 106 |
+
fail: 0,
|
| 107 |
+
durationMs: 100,
|
| 108 |
+
decisions: { accept: 0, reject: 0, modify: 1 },
|
| 109 |
+
},
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
const output = lastFrame();
|
| 115 |
+
expect(output).toContain('tool-a');
|
| 116 |
+
expect(output).toContain('tool-b');
|
| 117 |
+
expect(output).toMatchSnapshot();
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
+
it('should handle large values without wrapping or overlapping', () => {
|
| 121 |
+
const { lastFrame } = renderWithMockedStats({
|
| 122 |
+
models: {},
|
| 123 |
+
tools: {
|
| 124 |
+
totalCalls: 999999999,
|
| 125 |
+
totalSuccess: 888888888,
|
| 126 |
+
totalFail: 111111111,
|
| 127 |
+
totalDurationMs: 987654321,
|
| 128 |
+
totalDecisions: {
|
| 129 |
+
accept: 123456789,
|
| 130 |
+
reject: 98765432,
|
| 131 |
+
modify: 12345,
|
| 132 |
+
},
|
| 133 |
+
byName: {
|
| 134 |
+
'long-named-tool-for-testing-wrapping-and-such': {
|
| 135 |
+
count: 999999999,
|
| 136 |
+
success: 888888888,
|
| 137 |
+
fail: 111111111,
|
| 138 |
+
durationMs: 987654321,
|
| 139 |
+
decisions: {
|
| 140 |
+
accept: 123456789,
|
| 141 |
+
reject: 98765432,
|
| 142 |
+
modify: 12345,
|
| 143 |
+
},
|
| 144 |
+
},
|
| 145 |
+
},
|
| 146 |
+
},
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
+
expect(lastFrame()).toMatchSnapshot();
|
| 150 |
+
});
|
| 151 |
+
|
| 152 |
+
it('should handle zero decisions gracefully', () => {
|
| 153 |
+
const { lastFrame } = renderWithMockedStats({
|
| 154 |
+
models: {},
|
| 155 |
+
tools: {
|
| 156 |
+
totalCalls: 1,
|
| 157 |
+
totalSuccess: 1,
|
| 158 |
+
totalFail: 0,
|
| 159 |
+
totalDurationMs: 100,
|
| 160 |
+
totalDecisions: { accept: 0, reject: 0, modify: 0 },
|
| 161 |
+
byName: {
|
| 162 |
+
'test-tool': {
|
| 163 |
+
count: 1,
|
| 164 |
+
success: 1,
|
| 165 |
+
fail: 0,
|
| 166 |
+
durationMs: 100,
|
| 167 |
+
decisions: { accept: 0, reject: 0, modify: 0 },
|
| 168 |
+
},
|
| 169 |
+
},
|
| 170 |
+
},
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
const output = lastFrame();
|
| 174 |
+
expect(output).toContain('Total Reviewed Suggestions:');
|
| 175 |
+
expect(output).toContain('0');
|
| 176 |
+
expect(output).toContain('Overall Agreement Rate:');
|
| 177 |
+
expect(output).toContain('--');
|
| 178 |
+
expect(output).toMatchSnapshot();
|
| 179 |
+
});
|
| 180 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/components/ToolStatsDisplay.tsx
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
getStatusColor,
|
| 13 |
+
TOOL_SUCCESS_RATE_HIGH,
|
| 14 |
+
TOOL_SUCCESS_RATE_MEDIUM,
|
| 15 |
+
USER_AGREEMENT_RATE_HIGH,
|
| 16 |
+
USER_AGREEMENT_RATE_MEDIUM,
|
| 17 |
+
} from '../utils/displayUtils.js';
|
| 18 |
+
import { useSessionStats } from '../contexts/SessionContext.js';
|
| 19 |
+
import { ToolCallStats } from '@qwen-code/qwen-code-core';
|
| 20 |
+
|
| 21 |
+
const TOOL_NAME_COL_WIDTH = 25;
|
| 22 |
+
const CALLS_COL_WIDTH = 8;
|
| 23 |
+
const SUCCESS_RATE_COL_WIDTH = 15;
|
| 24 |
+
const AVG_DURATION_COL_WIDTH = 15;
|
| 25 |
+
|
| 26 |
+
const StatRow: React.FC<{
|
| 27 |
+
name: string;
|
| 28 |
+
stats: ToolCallStats;
|
| 29 |
+
}> = ({ name, stats }) => {
|
| 30 |
+
const successRate = stats.count > 0 ? (stats.success / stats.count) * 100 : 0;
|
| 31 |
+
const avgDuration = stats.count > 0 ? stats.durationMs / stats.count : 0;
|
| 32 |
+
const successColor = getStatusColor(successRate, {
|
| 33 |
+
green: TOOL_SUCCESS_RATE_HIGH,
|
| 34 |
+
yellow: TOOL_SUCCESS_RATE_MEDIUM,
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
return (
|
| 38 |
+
<Box>
|
| 39 |
+
<Box width={TOOL_NAME_COL_WIDTH}>
|
| 40 |
+
<Text color={Colors.LightBlue}>{name}</Text>
|
| 41 |
+
</Box>
|
| 42 |
+
<Box width={CALLS_COL_WIDTH} justifyContent="flex-end">
|
| 43 |
+
<Text>{stats.count}</Text>
|
| 44 |
+
</Box>
|
| 45 |
+
<Box width={SUCCESS_RATE_COL_WIDTH} justifyContent="flex-end">
|
| 46 |
+
<Text color={successColor}>{successRate.toFixed(1)}%</Text>
|
| 47 |
+
</Box>
|
| 48 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 49 |
+
<Text>{formatDuration(avgDuration)}</Text>
|
| 50 |
+
</Box>
|
| 51 |
+
</Box>
|
| 52 |
+
);
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
export const ToolStatsDisplay: React.FC = () => {
|
| 56 |
+
const { stats } = useSessionStats();
|
| 57 |
+
const { tools } = stats.metrics;
|
| 58 |
+
const activeTools = Object.entries(tools.byName).filter(
|
| 59 |
+
([, metrics]) => metrics.count > 0,
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
if (activeTools.length === 0) {
|
| 63 |
+
return (
|
| 64 |
+
<Box
|
| 65 |
+
borderStyle="round"
|
| 66 |
+
borderColor={Colors.Gray}
|
| 67 |
+
paddingY={1}
|
| 68 |
+
paddingX={2}
|
| 69 |
+
>
|
| 70 |
+
<Text>No tool calls have been made in this session.</Text>
|
| 71 |
+
</Box>
|
| 72 |
+
);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
const totalDecisions = Object.values(tools.byName).reduce(
|
| 76 |
+
(acc, tool) => {
|
| 77 |
+
acc.accept += tool.decisions.accept;
|
| 78 |
+
acc.reject += tool.decisions.reject;
|
| 79 |
+
acc.modify += tool.decisions.modify;
|
| 80 |
+
return acc;
|
| 81 |
+
},
|
| 82 |
+
{ accept: 0, reject: 0, modify: 0 },
|
| 83 |
+
);
|
| 84 |
+
|
| 85 |
+
const totalReviewed =
|
| 86 |
+
totalDecisions.accept + totalDecisions.reject + totalDecisions.modify;
|
| 87 |
+
const agreementRate =
|
| 88 |
+
totalReviewed > 0 ? (totalDecisions.accept / totalReviewed) * 100 : 0;
|
| 89 |
+
const agreementColor = getStatusColor(agreementRate, {
|
| 90 |
+
green: USER_AGREEMENT_RATE_HIGH,
|
| 91 |
+
yellow: USER_AGREEMENT_RATE_MEDIUM,
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
return (
|
| 95 |
+
<Box
|
| 96 |
+
borderStyle="round"
|
| 97 |
+
borderColor={Colors.Gray}
|
| 98 |
+
flexDirection="column"
|
| 99 |
+
paddingY={1}
|
| 100 |
+
paddingX={2}
|
| 101 |
+
width={70}
|
| 102 |
+
>
|
| 103 |
+
<Text bold color={Colors.AccentPurple}>
|
| 104 |
+
Tool Stats For Nerds
|
| 105 |
+
</Text>
|
| 106 |
+
<Box height={1} />
|
| 107 |
+
|
| 108 |
+
{/* Header */}
|
| 109 |
+
<Box>
|
| 110 |
+
<Box width={TOOL_NAME_COL_WIDTH}>
|
| 111 |
+
<Text bold>Tool Name</Text>
|
| 112 |
+
</Box>
|
| 113 |
+
<Box width={CALLS_COL_WIDTH} justifyContent="flex-end">
|
| 114 |
+
<Text bold>Calls</Text>
|
| 115 |
+
</Box>
|
| 116 |
+
<Box width={SUCCESS_RATE_COL_WIDTH} justifyContent="flex-end">
|
| 117 |
+
<Text bold>Success Rate</Text>
|
| 118 |
+
</Box>
|
| 119 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 120 |
+
<Text bold>Avg Duration</Text>
|
| 121 |
+
</Box>
|
| 122 |
+
</Box>
|
| 123 |
+
|
| 124 |
+
{/* Divider */}
|
| 125 |
+
<Box
|
| 126 |
+
borderStyle="single"
|
| 127 |
+
borderBottom={true}
|
| 128 |
+
borderTop={false}
|
| 129 |
+
borderLeft={false}
|
| 130 |
+
borderRight={false}
|
| 131 |
+
width="100%"
|
| 132 |
+
/>
|
| 133 |
+
|
| 134 |
+
{/* Tool Rows */}
|
| 135 |
+
{activeTools.map(([name, stats]) => (
|
| 136 |
+
<StatRow key={name} name={name} stats={stats as ToolCallStats} />
|
| 137 |
+
))}
|
| 138 |
+
|
| 139 |
+
<Box height={1} />
|
| 140 |
+
|
| 141 |
+
{/* User Decision Summary */}
|
| 142 |
+
<Text bold>User Decision Summary</Text>
|
| 143 |
+
<Box>
|
| 144 |
+
<Box
|
| 145 |
+
width={TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH}
|
| 146 |
+
>
|
| 147 |
+
<Text color={Colors.LightBlue}>Total Reviewed Suggestions:</Text>
|
| 148 |
+
</Box>
|
| 149 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 150 |
+
<Text>{totalReviewed}</Text>
|
| 151 |
+
</Box>
|
| 152 |
+
</Box>
|
| 153 |
+
<Box>
|
| 154 |
+
<Box
|
| 155 |
+
width={TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH}
|
| 156 |
+
>
|
| 157 |
+
<Text> » Accepted:</Text>
|
| 158 |
+
</Box>
|
| 159 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 160 |
+
<Text color={Colors.AccentGreen}>{totalDecisions.accept}</Text>
|
| 161 |
+
</Box>
|
| 162 |
+
</Box>
|
| 163 |
+
<Box>
|
| 164 |
+
<Box
|
| 165 |
+
width={TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH}
|
| 166 |
+
>
|
| 167 |
+
<Text> » Rejected:</Text>
|
| 168 |
+
</Box>
|
| 169 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 170 |
+
<Text color={Colors.AccentRed}>{totalDecisions.reject}</Text>
|
| 171 |
+
</Box>
|
| 172 |
+
</Box>
|
| 173 |
+
<Box>
|
| 174 |
+
<Box
|
| 175 |
+
width={TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH}
|
| 176 |
+
>
|
| 177 |
+
<Text> » Modified:</Text>
|
| 178 |
+
</Box>
|
| 179 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 180 |
+
<Text color={Colors.AccentYellow}>{totalDecisions.modify}</Text>
|
| 181 |
+
</Box>
|
| 182 |
+
</Box>
|
| 183 |
+
|
| 184 |
+
{/* Divider */}
|
| 185 |
+
<Box
|
| 186 |
+
borderStyle="single"
|
| 187 |
+
borderBottom={true}
|
| 188 |
+
borderTop={false}
|
| 189 |
+
borderLeft={false}
|
| 190 |
+
borderRight={false}
|
| 191 |
+
width="100%"
|
| 192 |
+
/>
|
| 193 |
+
|
| 194 |
+
<Box>
|
| 195 |
+
<Box
|
| 196 |
+
width={TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH}
|
| 197 |
+
>
|
| 198 |
+
<Text> Overall Agreement Rate:</Text>
|
| 199 |
+
</Box>
|
| 200 |
+
<Box width={AVG_DURATION_COL_WIDTH} justifyContent="flex-end">
|
| 201 |
+
<Text bold color={totalReviewed > 0 ? agreementColor : undefined}>
|
| 202 |
+
{totalReviewed > 0 ? `${agreementRate.toFixed(1)}%` : '--'}
|
| 203 |
+
</Text>
|
| 204 |
+
</Box>
|
| 205 |
+
</Box>
|
| 206 |
+
</Box>
|
| 207 |
+
);
|
| 208 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/components/UpdateNotification.tsx
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { Box, Text } from 'ink';
|
| 8 |
+
import { Colors } from '../colors.js';
|
| 9 |
+
|
| 10 |
+
interface UpdateNotificationProps {
|
| 11 |
+
message: string;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export const UpdateNotification = ({ message }: UpdateNotificationProps) => (
|
| 15 |
+
<Box
|
| 16 |
+
borderStyle="round"
|
| 17 |
+
borderColor={Colors.AccentYellow}
|
| 18 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React from 'react';
|
| 8 |
+
import { renderHook, act, waitFor } from '@testing-library/react';
|
| 9 |
+
import { vi, Mock } from 'vitest';
|
| 10 |
+
import {
|
| 11 |
+
KeypressProvider,
|
| 12 |
+
useKeypressContext,
|
| 13 |
+
Key,
|
| 14 |
+
} from './KeypressContext.js';
|
| 15 |
+
import { useStdin } from 'ink';
|
| 16 |
+
import { EventEmitter } from 'events';
|
| 17 |
+
import {
|
| 18 |
+
KITTY_KEYCODE_ENTER,
|
| 19 |
+
KITTY_KEYCODE_NUMPAD_ENTER,
|
| 20 |
+
KITTY_KEYCODE_TAB,
|
| 21 |
+
KITTY_KEYCODE_BACKSPACE,
|
| 22 |
+
} from '../utils/platformConstants.js';
|
| 23 |
+
|
| 24 |
+
// Mock the 'ink' module to control stdin
|
| 25 |
+
vi.mock('ink', async (importOriginal) => {
|
| 26 |
+
const original = await importOriginal<typeof import('ink')>();
|
| 27 |
+
return {
|
| 28 |
+
...original,
|
| 29 |
+
useStdin: vi.fn(),
|
| 30 |
+
};
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
class MockStdin extends EventEmitter {
|
| 34 |
+
isTTY = true;
|
| 35 |
+
setRawMode = vi.fn();
|
| 36 |
+
override on = this.addListener;
|
| 37 |
+
override removeListener = super.removeListener;
|
| 38 |
+
write = vi.fn();
|
| 39 |
+
resume = vi.fn();
|
| 40 |
+
pause = vi.fn();
|
| 41 |
+
|
| 42 |
+
// Helper to simulate a keypress event
|
| 43 |
+
pressKey(key: Partial<Key>) {
|
| 44 |
+
this.emit('keypress', null, key);
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// Helper to simulate a kitty protocol sequence
|
| 48 |
+
sendKittySequence(sequence: string) {
|
| 49 |
+
this.emit('data', Buffer.from(sequence));
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// Helper to simulate a paste event
|
| 53 |
+
sendPaste(text: string) {
|
| 54 |
+
const PASTE_MODE_PREFIX = `\x1b[200~`;
|
| 55 |
+
const PASTE_MODE_SUFFIX = `\x1b[201~`;
|
| 56 |
+
this.emit('data', Buffer.from(PASTE_MODE_PREFIX));
|
| 57 |
+
this.emit('data', Buffer.from(text));
|
| 58 |
+
this.emit('data', Buffer.from(PASTE_MODE_SUFFIX));
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
describe('KeypressContext - Kitty Protocol', () => {
|
| 63 |
+
let stdin: MockStdin;
|
| 64 |
+
const mockSetRawMode = vi.fn();
|
| 65 |
+
|
| 66 |
+
const wrapper = ({
|
| 67 |
+
children,
|
| 68 |
+
kittyProtocolEnabled = true,
|
| 69 |
+
}: {
|
| 70 |
+
children: React.ReactNode;
|
| 71 |
+
kittyProtocolEnabled?: boolean;
|
| 72 |
+
}) => (
|
| 73 |
+
<KeypressProvider kittyProtocolEnabled={kittyProtocolEnabled}>
|
| 74 |
+
{children}
|
| 75 |
+
</KeypressProvider>
|
| 76 |
+
);
|
| 77 |
+
|
| 78 |
+
beforeEach(() => {
|
| 79 |
+
vi.clearAllMocks();
|
| 80 |
+
stdin = new MockStdin();
|
| 81 |
+
(useStdin as Mock).mockReturnValue({
|
| 82 |
+
stdin,
|
| 83 |
+
setRawMode: mockSetRawMode,
|
| 84 |
+
});
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
describe('Enter key handling', () => {
|
| 88 |
+
it('should recognize regular enter key (keycode 13) in kitty protocol', async () => {
|
| 89 |
+
const keyHandler = vi.fn();
|
| 90 |
+
|
| 91 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 92 |
+
wrapper: ({ children }) =>
|
| 93 |
+
wrapper({ children, kittyProtocolEnabled: true }),
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
act(() => {
|
| 97 |
+
result.current.subscribe(keyHandler);
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
// Send kitty protocol sequence for regular enter: ESC[13u
|
| 101 |
+
act(() => {
|
| 102 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_ENTER}u`);
|
| 103 |
+
});
|
| 104 |
+
|
| 105 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 106 |
+
expect.objectContaining({
|
| 107 |
+
name: 'return',
|
| 108 |
+
kittyProtocol: true,
|
| 109 |
+
ctrl: false,
|
| 110 |
+
meta: false,
|
| 111 |
+
shift: false,
|
| 112 |
+
}),
|
| 113 |
+
);
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
it('should recognize numpad enter key (keycode 57414) in kitty protocol', async () => {
|
| 117 |
+
const keyHandler = vi.fn();
|
| 118 |
+
|
| 119 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 120 |
+
wrapper: ({ children }) =>
|
| 121 |
+
wrapper({ children, kittyProtocolEnabled: true }),
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
act(() => {
|
| 125 |
+
result.current.subscribe(keyHandler);
|
| 126 |
+
});
|
| 127 |
+
|
| 128 |
+
// Send kitty protocol sequence for numpad enter: ESC[57414u
|
| 129 |
+
act(() => {
|
| 130 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_NUMPAD_ENTER}u`);
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 134 |
+
expect.objectContaining({
|
| 135 |
+
name: 'return',
|
| 136 |
+
kittyProtocol: true,
|
| 137 |
+
ctrl: false,
|
| 138 |
+
meta: false,
|
| 139 |
+
shift: false,
|
| 140 |
+
}),
|
| 141 |
+
);
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
it('should handle numpad enter with modifiers', async () => {
|
| 145 |
+
const keyHandler = vi.fn();
|
| 146 |
+
|
| 147 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 148 |
+
wrapper: ({ children }) =>
|
| 149 |
+
wrapper({ children, kittyProtocolEnabled: true }),
|
| 150 |
+
});
|
| 151 |
+
|
| 152 |
+
act(() => {
|
| 153 |
+
result.current.subscribe(keyHandler);
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
// Send kitty protocol sequence for numpad enter with Shift (modifier 2): ESC[57414;2u
|
| 157 |
+
act(() => {
|
| 158 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_NUMPAD_ENTER};2u`);
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 162 |
+
expect.objectContaining({
|
| 163 |
+
name: 'return',
|
| 164 |
+
kittyProtocol: true,
|
| 165 |
+
ctrl: false,
|
| 166 |
+
meta: false,
|
| 167 |
+
shift: true,
|
| 168 |
+
}),
|
| 169 |
+
);
|
| 170 |
+
});
|
| 171 |
+
|
| 172 |
+
it('should handle numpad enter with Ctrl modifier', async () => {
|
| 173 |
+
const keyHandler = vi.fn();
|
| 174 |
+
|
| 175 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 176 |
+
wrapper: ({ children }) =>
|
| 177 |
+
wrapper({ children, kittyProtocolEnabled: true }),
|
| 178 |
+
});
|
| 179 |
+
|
| 180 |
+
act(() => {
|
| 181 |
+
result.current.subscribe(keyHandler);
|
| 182 |
+
});
|
| 183 |
+
|
| 184 |
+
// Send kitty protocol sequence for numpad enter with Ctrl (modifier 5): ESC[57414;5u
|
| 185 |
+
act(() => {
|
| 186 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_NUMPAD_ENTER};5u`);
|
| 187 |
+
});
|
| 188 |
+
|
| 189 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 190 |
+
expect.objectContaining({
|
| 191 |
+
name: 'return',
|
| 192 |
+
kittyProtocol: true,
|
| 193 |
+
ctrl: true,
|
| 194 |
+
meta: false,
|
| 195 |
+
shift: false,
|
| 196 |
+
}),
|
| 197 |
+
);
|
| 198 |
+
});
|
| 199 |
+
|
| 200 |
+
it('should handle numpad enter with Alt modifier', async () => {
|
| 201 |
+
const keyHandler = vi.fn();
|
| 202 |
+
|
| 203 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 204 |
+
wrapper: ({ children }) =>
|
| 205 |
+
wrapper({ children, kittyProtocolEnabled: true }),
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
act(() => {
|
| 209 |
+
result.current.subscribe(keyHandler);
|
| 210 |
+
});
|
| 211 |
+
|
| 212 |
+
// Send kitty protocol sequence for numpad enter with Alt (modifier 3): ESC[57414;3u
|
| 213 |
+
act(() => {
|
| 214 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_NUMPAD_ENTER};3u`);
|
| 215 |
+
});
|
| 216 |
+
|
| 217 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 218 |
+
expect.objectContaining({
|
| 219 |
+
name: 'return',
|
| 220 |
+
kittyProtocol: true,
|
| 221 |
+
ctrl: false,
|
| 222 |
+
meta: true,
|
| 223 |
+
shift: false,
|
| 224 |
+
}),
|
| 225 |
+
);
|
| 226 |
+
});
|
| 227 |
+
|
| 228 |
+
it('should not process kitty sequences when kitty protocol is disabled', async () => {
|
| 229 |
+
const keyHandler = vi.fn();
|
| 230 |
+
|
| 231 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 232 |
+
wrapper: ({ children }) =>
|
| 233 |
+
wrapper({ children, kittyProtocolEnabled: false }),
|
| 234 |
+
});
|
| 235 |
+
|
| 236 |
+
act(() => {
|
| 237 |
+
result.current.subscribe(keyHandler);
|
| 238 |
+
});
|
| 239 |
+
|
| 240 |
+
// Send kitty protocol sequence for numpad enter
|
| 241 |
+
act(() => {
|
| 242 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_NUMPAD_ENTER}u`);
|
| 243 |
+
});
|
| 244 |
+
|
| 245 |
+
// When kitty protocol is disabled, the sequence should be passed through
|
| 246 |
+
// as individual keypresses, not recognized as a single enter key
|
| 247 |
+
expect(keyHandler).not.toHaveBeenCalledWith(
|
| 248 |
+
expect.objectContaining({
|
| 249 |
+
name: 'return',
|
| 250 |
+
kittyProtocol: true,
|
| 251 |
+
}),
|
| 252 |
+
);
|
| 253 |
+
});
|
| 254 |
+
});
|
| 255 |
+
|
| 256 |
+
describe('Escape key handling', () => {
|
| 257 |
+
it('should recognize escape key (keycode 27) in kitty protocol', async () => {
|
| 258 |
+
const keyHandler = vi.fn();
|
| 259 |
+
|
| 260 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 261 |
+
wrapper: ({ children }) =>
|
| 262 |
+
wrapper({ children, kittyProtocolEnabled: true }),
|
| 263 |
+
});
|
| 264 |
+
|
| 265 |
+
act(() => {
|
| 266 |
+
result.current.subscribe(keyHandler);
|
| 267 |
+
});
|
| 268 |
+
|
| 269 |
+
// Send kitty protocol sequence for escape: ESC[27u
|
| 270 |
+
act(() => {
|
| 271 |
+
stdin.sendKittySequence('\x1b[27u');
|
| 272 |
+
});
|
| 273 |
+
|
| 274 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 275 |
+
expect.objectContaining({
|
| 276 |
+
name: 'escape',
|
| 277 |
+
kittyProtocol: true,
|
| 278 |
+
}),
|
| 279 |
+
);
|
| 280 |
+
});
|
| 281 |
+
});
|
| 282 |
+
|
| 283 |
+
describe('Tab and Backspace handling', () => {
|
| 284 |
+
it('should recognize Tab key in kitty protocol', async () => {
|
| 285 |
+
const keyHandler = vi.fn();
|
| 286 |
+
const { result } = renderHook(() => useKeypressContext(), { wrapper });
|
| 287 |
+
act(() => result.current.subscribe(keyHandler));
|
| 288 |
+
|
| 289 |
+
act(() => {
|
| 290 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_TAB}u`);
|
| 291 |
+
});
|
| 292 |
+
|
| 293 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 294 |
+
expect.objectContaining({
|
| 295 |
+
name: 'tab',
|
| 296 |
+
kittyProtocol: true,
|
| 297 |
+
shift: false,
|
| 298 |
+
}),
|
| 299 |
+
);
|
| 300 |
+
});
|
| 301 |
+
|
| 302 |
+
it('should recognize Shift+Tab in kitty protocol', async () => {
|
| 303 |
+
const keyHandler = vi.fn();
|
| 304 |
+
const { result } = renderHook(() => useKeypressContext(), { wrapper });
|
| 305 |
+
act(() => result.current.subscribe(keyHandler));
|
| 306 |
+
|
| 307 |
+
// Modifier 2 is Shift
|
| 308 |
+
act(() => {
|
| 309 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_TAB};2u`);
|
| 310 |
+
});
|
| 311 |
+
|
| 312 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 313 |
+
expect.objectContaining({
|
| 314 |
+
name: 'tab',
|
| 315 |
+
kittyProtocol: true,
|
| 316 |
+
shift: true,
|
| 317 |
+
}),
|
| 318 |
+
);
|
| 319 |
+
});
|
| 320 |
+
|
| 321 |
+
it('should recognize Backspace key in kitty protocol', async () => {
|
| 322 |
+
const keyHandler = vi.fn();
|
| 323 |
+
const { result } = renderHook(() => useKeypressContext(), { wrapper });
|
| 324 |
+
act(() => result.current.subscribe(keyHandler));
|
| 325 |
+
|
| 326 |
+
act(() => {
|
| 327 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_BACKSPACE}u`);
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 331 |
+
expect.objectContaining({
|
| 332 |
+
name: 'backspace',
|
| 333 |
+
kittyProtocol: true,
|
| 334 |
+
meta: false,
|
| 335 |
+
}),
|
| 336 |
+
);
|
| 337 |
+
});
|
| 338 |
+
|
| 339 |
+
it('should recognize Option+Backspace in kitty protocol', async () => {
|
| 340 |
+
const keyHandler = vi.fn();
|
| 341 |
+
const { result } = renderHook(() => useKeypressContext(), { wrapper });
|
| 342 |
+
act(() => result.current.subscribe(keyHandler));
|
| 343 |
+
|
| 344 |
+
// Modifier 3 is Alt/Option
|
| 345 |
+
act(() => {
|
| 346 |
+
stdin.sendKittySequence(`\x1b[${KITTY_KEYCODE_BACKSPACE};3u`);
|
| 347 |
+
});
|
| 348 |
+
|
| 349 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 350 |
+
expect.objectContaining({
|
| 351 |
+
name: 'backspace',
|
| 352 |
+
kittyProtocol: true,
|
| 353 |
+
meta: true,
|
| 354 |
+
}),
|
| 355 |
+
);
|
| 356 |
+
});
|
| 357 |
+
});
|
| 358 |
+
|
| 359 |
+
describe('paste mode', () => {
|
| 360 |
+
it('should handle multiline paste as a single event', async () => {
|
| 361 |
+
const keyHandler = vi.fn();
|
| 362 |
+
const pastedText = 'This \n is \n a \n multiline \n paste.';
|
| 363 |
+
|
| 364 |
+
const { result } = renderHook(() => useKeypressContext(), {
|
| 365 |
+
wrapper,
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
act(() => {
|
| 369 |
+
result.current.subscribe(keyHandler);
|
| 370 |
+
});
|
| 371 |
+
|
| 372 |
+
// Simulate a bracketed paste event
|
| 373 |
+
act(() => {
|
| 374 |
+
stdin.sendPaste(pastedText);
|
| 375 |
+
});
|
| 376 |
+
|
| 377 |
+
await waitFor(() => {
|
| 378 |
+
// Expect the handler to be called exactly once for the entire paste
|
| 379 |
+
expect(keyHandler).toHaveBeenCalledTimes(1);
|
| 380 |
+
});
|
| 381 |
+
|
| 382 |
+
// Verify the single event contains the full pasted text
|
| 383 |
+
expect(keyHandler).toHaveBeenCalledWith(
|
| 384 |
+
expect.objectContaining({
|
| 385 |
+
paste: true,
|
| 386 |
+
sequence: pastedText,
|
| 387 |
+
}),
|
| 388 |
+
);
|
| 389 |
+
});
|
| 390 |
+
});
|
| 391 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/KeypressContext.tsx
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
Config,
|
| 9 |
+
KittySequenceOverflowEvent,
|
| 10 |
+
logKittySequenceOverflow,
|
| 11 |
+
} from '@qwen-code/qwen-code-core';
|
| 12 |
+
import { useStdin } from 'ink';
|
| 13 |
+
import React, {
|
| 14 |
+
createContext,
|
| 15 |
+
useCallback,
|
| 16 |
+
useContext,
|
| 17 |
+
useEffect,
|
| 18 |
+
useRef,
|
| 19 |
+
} from 'react';
|
| 20 |
+
import readline from 'readline';
|
| 21 |
+
import { PassThrough } from 'stream';
|
| 22 |
+
import {
|
| 23 |
+
BACKSLASH_ENTER_DETECTION_WINDOW_MS,
|
| 24 |
+
KITTY_CTRL_C,
|
| 25 |
+
KITTY_KEYCODE_BACKSPACE,
|
| 26 |
+
KITTY_KEYCODE_ENTER,
|
| 27 |
+
KITTY_KEYCODE_NUMPAD_ENTER,
|
| 28 |
+
KITTY_KEYCODE_TAB,
|
| 29 |
+
MAX_KITTY_SEQUENCE_LENGTH,
|
| 30 |
+
} from '../utils/platformConstants.js';
|
| 31 |
+
|
| 32 |
+
import { FOCUS_IN, FOCUS_OUT } from '../hooks/useFocus.js';
|
| 33 |
+
|
| 34 |
+
const ESC = '\u001B';
|
| 35 |
+
export const PASTE_MODE_PREFIX = `${ESC}[200~`;
|
| 36 |
+
export const PASTE_MODE_SUFFIX = `${ESC}[201~`;
|
| 37 |
+
|
| 38 |
+
export interface Key {
|
| 39 |
+
name: string;
|
| 40 |
+
ctrl: boolean;
|
| 41 |
+
meta: boolean;
|
| 42 |
+
shift: boolean;
|
| 43 |
+
paste: boolean;
|
| 44 |
+
sequence: string;
|
| 45 |
+
kittyProtocol?: boolean;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
export type KeypressHandler = (key: Key) => void;
|
| 49 |
+
|
| 50 |
+
interface KeypressContextValue {
|
| 51 |
+
subscribe: (handler: KeypressHandler) => void;
|
| 52 |
+
unsubscribe: (handler: KeypressHandler) => void;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
const KeypressContext = createContext<KeypressContextValue | undefined>(
|
| 56 |
+
undefined,
|
| 57 |
+
);
|
| 58 |
+
|
| 59 |
+
export function useKeypressContext() {
|
| 60 |
+
const context = useContext(KeypressContext);
|
| 61 |
+
if (!context) {
|
| 62 |
+
throw new Error(
|
| 63 |
+
'useKeypressContext must be used within a KeypressProvider',
|
| 64 |
+
);
|
| 65 |
+
}
|
| 66 |
+
return context;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
export function KeypressProvider({
|
| 70 |
+
children,
|
| 71 |
+
kittyProtocolEnabled,
|
| 72 |
+
config,
|
| 73 |
+
}: {
|
| 74 |
+
children: React.ReactNode;
|
| 75 |
+
kittyProtocolEnabled: boolean;
|
| 76 |
+
config?: Config;
|
| 77 |
+
}) {
|
| 78 |
+
const { stdin, setRawMode } = useStdin();
|
| 79 |
+
const subscribers = useRef<Set<KeypressHandler>>(new Set()).current;
|
| 80 |
+
|
| 81 |
+
const subscribe = useCallback(
|
| 82 |
+
(handler: KeypressHandler) => {
|
| 83 |
+
subscribers.add(handler);
|
| 84 |
+
},
|
| 85 |
+
[subscribers],
|
| 86 |
+
);
|
| 87 |
+
|
| 88 |
+
const unsubscribe = useCallback(
|
| 89 |
+
(handler: KeypressHandler) => {
|
| 90 |
+
subscribers.delete(handler);
|
| 91 |
+
},
|
| 92 |
+
[subscribers],
|
| 93 |
+
);
|
| 94 |
+
|
| 95 |
+
useEffect(() => {
|
| 96 |
+
setRawMode(true);
|
| 97 |
+
|
| 98 |
+
const keypressStream = new PassThrough();
|
| 99 |
+
let usePassthrough = false;
|
| 100 |
+
const nodeMajorVersion = parseInt(process.versions.node.split('.')[0], 10);
|
| 101 |
+
if (
|
| 102 |
+
nodeMajorVersion < 20 ||
|
| 103 |
+
process.env['PASTE_WORKAROUND'] === '1' ||
|
| 104 |
+
process.env['PASTE_WORKAROUND'] === 'true'
|
| 105 |
+
) {
|
| 106 |
+
usePassthrough = true;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
let isPaste = false;
|
| 110 |
+
let pasteBuffer = Buffer.alloc(0);
|
| 111 |
+
let kittySequenceBuffer = '';
|
| 112 |
+
let backslashTimeout: NodeJS.Timeout | null = null;
|
| 113 |
+
let waitingForEnterAfterBackslash = false;
|
| 114 |
+
|
| 115 |
+
const parseKittySequence = (sequence: string): Key | null => {
|
| 116 |
+
const kittyPattern = new RegExp(`^${ESC}\\[(\\d+)(;(\\d+))?([u~])$`);
|
| 117 |
+
const match = sequence.match(kittyPattern);
|
| 118 |
+
if (!match) return null;
|
| 119 |
+
|
| 120 |
+
const keyCode = parseInt(match[1], 10);
|
| 121 |
+
const modifiers = match[3] ? parseInt(match[3], 10) : 1;
|
| 122 |
+
const modifierBits = modifiers - 1;
|
| 123 |
+
const shift = (modifierBits & 1) === 1;
|
| 124 |
+
const alt = (modifierBits & 2) === 2;
|
| 125 |
+
const ctrl = (modifierBits & 4) === 4;
|
| 126 |
+
|
| 127 |
+
if (keyCode === 27) {
|
| 128 |
+
return {
|
| 129 |
+
name: 'escape',
|
| 130 |
+
ctrl,
|
| 131 |
+
meta: alt,
|
| 132 |
+
shift,
|
| 133 |
+
paste: false,
|
| 134 |
+
sequence,
|
| 135 |
+
kittyProtocol: true,
|
| 136 |
+
};
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if (keyCode === KITTY_KEYCODE_TAB) {
|
| 140 |
+
return {
|
| 141 |
+
name: 'tab',
|
| 142 |
+
ctrl,
|
| 143 |
+
meta: alt,
|
| 144 |
+
shift,
|
| 145 |
+
paste: false,
|
| 146 |
+
sequence,
|
| 147 |
+
kittyProtocol: true,
|
| 148 |
+
};
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
if (keyCode === KITTY_KEYCODE_BACKSPACE) {
|
| 152 |
+
return {
|
| 153 |
+
name: 'backspace',
|
| 154 |
+
ctrl,
|
| 155 |
+
meta: alt,
|
| 156 |
+
shift,
|
| 157 |
+
paste: false,
|
| 158 |
+
sequence,
|
| 159 |
+
kittyProtocol: true,
|
| 160 |
+
};
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
if (
|
| 164 |
+
keyCode === KITTY_KEYCODE_ENTER ||
|
| 165 |
+
keyCode === KITTY_KEYCODE_NUMPAD_ENTER
|
| 166 |
+
) {
|
| 167 |
+
return {
|
| 168 |
+
name: 'return',
|
| 169 |
+
ctrl,
|
| 170 |
+
meta: alt,
|
| 171 |
+
shift,
|
| 172 |
+
paste: false,
|
| 173 |
+
sequence,
|
| 174 |
+
kittyProtocol: true,
|
| 175 |
+
};
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
if (keyCode >= 97 && keyCode <= 122 && ctrl) {
|
| 179 |
+
const letter = String.fromCharCode(keyCode);
|
| 180 |
+
return {
|
| 181 |
+
name: letter,
|
| 182 |
+
ctrl: true,
|
| 183 |
+
meta: alt,
|
| 184 |
+
shift,
|
| 185 |
+
paste: false,
|
| 186 |
+
sequence,
|
| 187 |
+
kittyProtocol: true,
|
| 188 |
+
};
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
return null;
|
| 192 |
+
};
|
| 193 |
+
|
| 194 |
+
const broadcast = (key: Key) => {
|
| 195 |
+
for (const handler of subscribers) {
|
| 196 |
+
handler(key);
|
| 197 |
+
}
|
| 198 |
+
};
|
| 199 |
+
|
| 200 |
+
const handleKeypress = (_: unknown, key: Key) => {
|
| 201 |
+
if (key.name === 'paste-start') {
|
| 202 |
+
isPaste = true;
|
| 203 |
+
return;
|
| 204 |
+
}
|
| 205 |
+
if (key.name === 'paste-end') {
|
| 206 |
+
isPaste = false;
|
| 207 |
+
broadcast({
|
| 208 |
+
name: '',
|
| 209 |
+
ctrl: false,
|
| 210 |
+
meta: false,
|
| 211 |
+
shift: false,
|
| 212 |
+
paste: true,
|
| 213 |
+
sequence: pasteBuffer.toString(),
|
| 214 |
+
});
|
| 215 |
+
pasteBuffer = Buffer.alloc(0);
|
| 216 |
+
return;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
if (isPaste) {
|
| 220 |
+
pasteBuffer = Buffer.concat([pasteBuffer, Buffer.from(key.sequence)]);
|
| 221 |
+
return;
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
if (key.name === 'return' && waitingForEnterAfterBackslash) {
|
| 225 |
+
if (backslashTimeout) {
|
| 226 |
+
clearTimeout(backslashTimeout);
|
| 227 |
+
backslashTimeout = null;
|
| 228 |
+
}
|
| 229 |
+
waitingForEnterAfterBackslash = false;
|
| 230 |
+
broadcast({
|
| 231 |
+
...key,
|
| 232 |
+
shift: true,
|
| 233 |
+
sequence: '\r', // Corrected escaping for newline
|
| 234 |
+
});
|
| 235 |
+
return;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
if (key.sequence === '\\' && !key.name) {
|
| 239 |
+
// Corrected escaping for backslash
|
| 240 |
+
waitingForEnterAfterBackslash = true;
|
| 241 |
+
backslashTimeout = setTimeout(() => {
|
| 242 |
+
waitingForEnterAfterBackslash = false;
|
| 243 |
+
backslashTimeout = null;
|
| 244 |
+
broadcast(key);
|
| 245 |
+
}, BACKSLASH_ENTER_DETECTION_WINDOW_MS);
|
| 246 |
+
return;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
if (waitingForEnterAfterBackslash && key.name !== 'return') {
|
| 250 |
+
if (backslashTimeout) {
|
| 251 |
+
clearTimeout(backslashTimeout);
|
| 252 |
+
backslashTimeout = null;
|
| 253 |
+
}
|
| 254 |
+
waitingForEnterAfterBackslash = false;
|
| 255 |
+
broadcast({
|
| 256 |
+
name: '',
|
| 257 |
+
sequence: '\\',
|
| 258 |
+
ctrl: false,
|
| 259 |
+
meta: false,
|
| 260 |
+
shift: false,
|
| 261 |
+
paste: false,
|
| 262 |
+
});
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
if (['up', 'down', 'left', 'right'].includes(key.name)) {
|
| 266 |
+
broadcast(key);
|
| 267 |
+
return;
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
if (
|
| 271 |
+
(key.ctrl && key.name === 'c') ||
|
| 272 |
+
key.sequence === `${ESC}${KITTY_CTRL_C}`
|
| 273 |
+
) {
|
| 274 |
+
kittySequenceBuffer = '';
|
| 275 |
+
if (key.sequence === `${ESC}${KITTY_CTRL_C}`) {
|
| 276 |
+
broadcast({
|
| 277 |
+
name: 'c',
|
| 278 |
+
ctrl: true,
|
| 279 |
+
meta: false,
|
| 280 |
+
shift: false,
|
| 281 |
+
paste: false,
|
| 282 |
+
sequence: key.sequence,
|
| 283 |
+
kittyProtocol: true,
|
| 284 |
+
});
|
| 285 |
+
} else {
|
| 286 |
+
broadcast(key);
|
| 287 |
+
}
|
| 288 |
+
return;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
if (kittyProtocolEnabled) {
|
| 292 |
+
if (
|
| 293 |
+
kittySequenceBuffer ||
|
| 294 |
+
(key.sequence.startsWith(`${ESC}[`) &&
|
| 295 |
+
!key.sequence.startsWith(PASTE_MODE_PREFIX) &&
|
| 296 |
+
!key.sequence.startsWith(PASTE_MODE_SUFFIX) &&
|
| 297 |
+
!key.sequence.startsWith(FOCUS_IN) &&
|
| 298 |
+
!key.sequence.startsWith(FOCUS_OUT))
|
| 299 |
+
) {
|
| 300 |
+
kittySequenceBuffer += key.sequence;
|
| 301 |
+
const kittyKey = parseKittySequence(kittySequenceBuffer);
|
| 302 |
+
if (kittyKey) {
|
| 303 |
+
kittySequenceBuffer = '';
|
| 304 |
+
broadcast(kittyKey);
|
| 305 |
+
return;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
if (config?.getDebugMode()) {
|
| 309 |
+
const codes = Array.from(kittySequenceBuffer).map((ch) =>
|
| 310 |
+
ch.charCodeAt(0),
|
| 311 |
+
);
|
| 312 |
+
console.warn('Kitty sequence buffer has char codes:', codes);
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
if (kittySequenceBuffer.length > MAX_KITTY_SEQUENCE_LENGTH) {
|
| 316 |
+
if (config) {
|
| 317 |
+
const event = new KittySequenceOverflowEvent(
|
| 318 |
+
kittySequenceBuffer.length,
|
| 319 |
+
kittySequenceBuffer,
|
| 320 |
+
);
|
| 321 |
+
logKittySequenceOverflow(config, event);
|
| 322 |
+
}
|
| 323 |
+
kittySequenceBuffer = '';
|
| 324 |
+
} else {
|
| 325 |
+
return;
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
if (key.name === 'return' && key.sequence === `${ESC}\r`) {
|
| 331 |
+
key.meta = true;
|
| 332 |
+
}
|
| 333 |
+
broadcast({ ...key, paste: isPaste });
|
| 334 |
+
};
|
| 335 |
+
|
| 336 |
+
const handleRawKeypress = (data: Buffer) => {
|
| 337 |
+
const pasteModePrefixBuffer = Buffer.from(PASTE_MODE_PREFIX);
|
| 338 |
+
const pasteModeSuffixBuffer = Buffer.from(PASTE_MODE_SUFFIX);
|
| 339 |
+
|
| 340 |
+
let pos = 0;
|
| 341 |
+
while (pos < data.length) {
|
| 342 |
+
const prefixPos = data.indexOf(pasteModePrefixBuffer, pos);
|
| 343 |
+
const suffixPos = data.indexOf(pasteModeSuffixBuffer, pos);
|
| 344 |
+
const isPrefixNext =
|
| 345 |
+
prefixPos !== -1 && (suffixPos === -1 || prefixPos < suffixPos);
|
| 346 |
+
const isSuffixNext =
|
| 347 |
+
suffixPos !== -1 && (prefixPos === -1 || suffixPos < prefixPos);
|
| 348 |
+
|
| 349 |
+
let nextMarkerPos = -1;
|
| 350 |
+
let markerLength = 0;
|
| 351 |
+
|
| 352 |
+
if (isPrefixNext) {
|
| 353 |
+
nextMarkerPos = prefixPos;
|
| 354 |
+
} else if (isSuffixNext) {
|
| 355 |
+
nextMarkerPos = suffixPos;
|
| 356 |
+
}
|
| 357 |
+
markerLength = pasteModeSuffixBuffer.length;
|
| 358 |
+
|
| 359 |
+
if (nextMarkerPos === -1) {
|
| 360 |
+
keypressStream.write(data.slice(pos));
|
| 361 |
+
return;
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
const nextData = data.slice(pos, nextMarkerPos);
|
| 365 |
+
if (nextData.length > 0) {
|
| 366 |
+
keypressStream.write(nextData);
|
| 367 |
+
}
|
| 368 |
+
const createPasteKeyEvent = (
|
| 369 |
+
name: 'paste-start' | 'paste-end',
|
| 370 |
+
): Key => ({
|
| 371 |
+
name,
|
| 372 |
+
ctrl: false,
|
| 373 |
+
meta: false,
|
| 374 |
+
shift: false,
|
| 375 |
+
paste: false,
|
| 376 |
+
sequence: '',
|
| 377 |
+
});
|
| 378 |
+
if (isPrefixNext) {
|
| 379 |
+
handleKeypress(undefined, createPasteKeyEvent('paste-start'));
|
| 380 |
+
} else if (isSuffixNext) {
|
| 381 |
+
handleKeypress(undefined, createPasteKeyEvent('paste-end'));
|
| 382 |
+
}
|
| 383 |
+
pos = nextMarkerPos + markerLength;
|
| 384 |
+
}
|
| 385 |
+
};
|
| 386 |
+
|
| 387 |
+
let rl: readline.Interface;
|
| 388 |
+
if (usePassthrough) {
|
| 389 |
+
rl = readline.createInterface({
|
| 390 |
+
input: keypressStream,
|
| 391 |
+
escapeCodeTimeout: 0,
|
| 392 |
+
});
|
| 393 |
+
readline.emitKeypressEvents(keypressStream, rl);
|
| 394 |
+
keypressStream.on('keypress', handleKeypress);
|
| 395 |
+
stdin.on('data', handleRawKeypress);
|
| 396 |
+
} else {
|
| 397 |
+
rl = readline.createInterface({ input: stdin, escapeCodeTimeout: 0 });
|
| 398 |
+
readline.emitKeypressEvents(stdin, rl);
|
| 399 |
+
stdin.on('keypress', handleKeypress);
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
return () => {
|
| 403 |
+
if (usePassthrough) {
|
| 404 |
+
keypressStream.removeListener('keypress', handleKeypress);
|
| 405 |
+
stdin.removeListener('data', handleRawKeypress);
|
| 406 |
+
} else {
|
| 407 |
+
stdin.removeListener('keypress', handleKeypress);
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
rl.close();
|
| 411 |
+
|
| 412 |
+
// Restore the terminal to its original state.
|
| 413 |
+
setRawMode(false);
|
| 414 |
+
|
| 415 |
+
if (backslashTimeout) {
|
| 416 |
+
clearTimeout(backslashTimeout);
|
| 417 |
+
backslashTimeout = null;
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
// Flush any pending paste data to avoid data loss on exit.
|
| 421 |
+
if (isPaste) {
|
| 422 |
+
broadcast({
|
| 423 |
+
name: '',
|
| 424 |
+
ctrl: false,
|
| 425 |
+
meta: false,
|
| 426 |
+
shift: false,
|
| 427 |
+
paste: true,
|
| 428 |
+
sequence: pasteBuffer.toString(),
|
| 429 |
+
});
|
| 430 |
+
pasteBuffer = Buffer.alloc(0);
|
| 431 |
+
}
|
| 432 |
+
};
|
| 433 |
+
}, [stdin, setRawMode, kittyProtocolEnabled, config, subscribers]);
|
| 434 |
+
|
| 435 |
+
return (
|
| 436 |
+
<KeypressContext.Provider value={{ subscribe, unsubscribe }}>
|
| 437 |
+
{children}
|
| 438 |
+
</KeypressContext.Provider>
|
| 439 |
+
);
|
| 440 |
+
}
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/OverflowContext.tsx
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, {
|
| 8 |
+
createContext,
|
| 9 |
+
useContext,
|
| 10 |
+
useState,
|
| 11 |
+
useCallback,
|
| 12 |
+
useMemo,
|
| 13 |
+
} from 'react';
|
| 14 |
+
|
| 15 |
+
interface OverflowState {
|
| 16 |
+
overflowingIds: ReadonlySet<string>;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
interface OverflowActions {
|
| 20 |
+
addOverflowingId: (id: string) => void;
|
| 21 |
+
removeOverflowingId: (id: string) => void;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const OverflowStateContext = createContext<OverflowState | undefined>(
|
| 25 |
+
undefined,
|
| 26 |
+
);
|
| 27 |
+
|
| 28 |
+
const OverflowActionsContext = createContext<OverflowActions | undefined>(
|
| 29 |
+
undefined,
|
| 30 |
+
);
|
| 31 |
+
|
| 32 |
+
export const useOverflowState = (): OverflowState | undefined =>
|
| 33 |
+
useContext(OverflowStateContext);
|
| 34 |
+
|
| 35 |
+
export const useOverflowActions = (): OverflowActions | undefined =>
|
| 36 |
+
useContext(OverflowActionsContext);
|
| 37 |
+
|
| 38 |
+
export const OverflowProvider: React.FC<{ children: React.ReactNode }> = ({
|
| 39 |
+
children,
|
| 40 |
+
}) => {
|
| 41 |
+
const [overflowingIds, setOverflowingIds] = useState(new Set<string>());
|
| 42 |
+
|
| 43 |
+
const addOverflowingId = useCallback((id: string) => {
|
| 44 |
+
setOverflowingIds((prevIds) => {
|
| 45 |
+
if (prevIds.has(id)) {
|
| 46 |
+
return prevIds;
|
| 47 |
+
}
|
| 48 |
+
const newIds = new Set(prevIds);
|
| 49 |
+
newIds.add(id);
|
| 50 |
+
return newIds;
|
| 51 |
+
});
|
| 52 |
+
}, []);
|
| 53 |
+
|
| 54 |
+
const removeOverflowingId = useCallback((id: string) => {
|
| 55 |
+
setOverflowingIds((prevIds) => {
|
| 56 |
+
if (!prevIds.has(id)) {
|
| 57 |
+
return prevIds;
|
| 58 |
+
}
|
| 59 |
+
const newIds = new Set(prevIds);
|
| 60 |
+
newIds.delete(id);
|
| 61 |
+
return newIds;
|
| 62 |
+
});
|
| 63 |
+
}, []);
|
| 64 |
+
|
| 65 |
+
const stateValue = useMemo(
|
| 66 |
+
() => ({
|
| 67 |
+
overflowingIds,
|
| 68 |
+
}),
|
| 69 |
+
[overflowingIds],
|
| 70 |
+
);
|
| 71 |
+
|
| 72 |
+
const actionsValue = useMemo(
|
| 73 |
+
() => ({
|
| 74 |
+
addOverflowingId,
|
| 75 |
+
removeOverflowingId,
|
| 76 |
+
}),
|
| 77 |
+
[addOverflowingId, removeOverflowingId],
|
| 78 |
+
);
|
| 79 |
+
|
| 80 |
+
return (
|
| 81 |
+
<OverflowStateContext.Provider value={stateValue}>
|
| 82 |
+
<OverflowActionsContext.Provider value={actionsValue}>
|
| 83 |
+
{children}
|
| 84 |
+
</OverflowActionsContext.Provider>
|
| 85 |
+
</OverflowStateContext.Provider>
|
| 86 |
+
);
|
| 87 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/SessionContext.test.tsx
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { type MutableRefObject } from 'react';
|
| 8 |
+
import { render } from 'ink-testing-library';
|
| 9 |
+
import { renderHook } from '@testing-library/react';
|
| 10 |
+
import { act } from 'react-dom/test-utils';
|
| 11 |
+
import {
|
| 12 |
+
SessionStatsProvider,
|
| 13 |
+
useSessionStats,
|
| 14 |
+
SessionMetrics,
|
| 15 |
+
} from './SessionContext.js';
|
| 16 |
+
import { describe, it, expect, vi } from 'vitest';
|
| 17 |
+
import { uiTelemetryService } from '@qwen-code/qwen-code-core';
|
| 18 |
+
|
| 19 |
+
/**
|
| 20 |
+
* A test harness component that uses the hook and exposes the context value
|
| 21 |
+
* via a mutable ref. This allows us to interact with the context's functions
|
| 22 |
+
* and assert against its state directly in our tests.
|
| 23 |
+
*/
|
| 24 |
+
const TestHarness = ({
|
| 25 |
+
contextRef,
|
| 26 |
+
}: {
|
| 27 |
+
contextRef: MutableRefObject<ReturnType<typeof useSessionStats> | undefined>;
|
| 28 |
+
}) => {
|
| 29 |
+
contextRef.current = useSessionStats();
|
| 30 |
+
return null;
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
describe('SessionStatsContext', () => {
|
| 34 |
+
it('should provide the correct initial state', () => {
|
| 35 |
+
const contextRef: MutableRefObject<
|
| 36 |
+
ReturnType<typeof useSessionStats> | undefined
|
| 37 |
+
> = { current: undefined };
|
| 38 |
+
|
| 39 |
+
render(
|
| 40 |
+
<SessionStatsProvider>
|
| 41 |
+
<TestHarness contextRef={contextRef} />
|
| 42 |
+
</SessionStatsProvider>,
|
| 43 |
+
);
|
| 44 |
+
|
| 45 |
+
const stats = contextRef.current?.stats;
|
| 46 |
+
|
| 47 |
+
expect(stats?.sessionStartTime).toBeInstanceOf(Date);
|
| 48 |
+
expect(stats?.metrics).toBeDefined();
|
| 49 |
+
expect(stats?.metrics.models).toEqual({});
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
it('should update metrics when the uiTelemetryService emits an update', () => {
|
| 53 |
+
const contextRef: MutableRefObject<
|
| 54 |
+
ReturnType<typeof useSessionStats> | undefined
|
| 55 |
+
> = { current: undefined };
|
| 56 |
+
|
| 57 |
+
render(
|
| 58 |
+
<SessionStatsProvider>
|
| 59 |
+
<TestHarness contextRef={contextRef} />
|
| 60 |
+
</SessionStatsProvider>,
|
| 61 |
+
);
|
| 62 |
+
|
| 63 |
+
const newMetrics: SessionMetrics = {
|
| 64 |
+
models: {
|
| 65 |
+
'gemini-pro': {
|
| 66 |
+
api: {
|
| 67 |
+
totalRequests: 1,
|
| 68 |
+
totalErrors: 0,
|
| 69 |
+
totalLatencyMs: 123,
|
| 70 |
+
},
|
| 71 |
+
tokens: {
|
| 72 |
+
prompt: 100,
|
| 73 |
+
candidates: 200,
|
| 74 |
+
total: 300,
|
| 75 |
+
cached: 50,
|
| 76 |
+
thoughts: 20,
|
| 77 |
+
tool: 10,
|
| 78 |
+
},
|
| 79 |
+
},
|
| 80 |
+
},
|
| 81 |
+
tools: {
|
| 82 |
+
totalCalls: 1,
|
| 83 |
+
totalSuccess: 1,
|
| 84 |
+
totalFail: 0,
|
| 85 |
+
totalDurationMs: 456,
|
| 86 |
+
totalDecisions: {
|
| 87 |
+
accept: 1,
|
| 88 |
+
reject: 0,
|
| 89 |
+
modify: 0,
|
| 90 |
+
},
|
| 91 |
+
byName: {
|
| 92 |
+
'test-tool': {
|
| 93 |
+
count: 1,
|
| 94 |
+
success: 1,
|
| 95 |
+
fail: 0,
|
| 96 |
+
durationMs: 456,
|
| 97 |
+
decisions: {
|
| 98 |
+
accept: 1,
|
| 99 |
+
reject: 0,
|
| 100 |
+
modify: 0,
|
| 101 |
+
},
|
| 102 |
+
},
|
| 103 |
+
},
|
| 104 |
+
},
|
| 105 |
+
};
|
| 106 |
+
|
| 107 |
+
act(() => {
|
| 108 |
+
uiTelemetryService.emit('update', {
|
| 109 |
+
metrics: newMetrics,
|
| 110 |
+
lastPromptTokenCount: 100,
|
| 111 |
+
});
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
const stats = contextRef.current?.stats;
|
| 115 |
+
expect(stats?.metrics).toEqual(newMetrics);
|
| 116 |
+
expect(stats?.lastPromptTokenCount).toBe(100);
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it('should throw an error when useSessionStats is used outside of a provider', () => {
|
| 120 |
+
// Suppress console.error for this test since we expect an error
|
| 121 |
+
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
| 122 |
+
|
| 123 |
+
try {
|
| 124 |
+
// Expect renderHook itself to throw when the hook is used outside a provider
|
| 125 |
+
expect(() => {
|
| 126 |
+
renderHook(() => useSessionStats());
|
| 127 |
+
}).toThrow('useSessionStats must be used within a SessionStatsProvider');
|
| 128 |
+
} finally {
|
| 129 |
+
consoleSpy.mockRestore();
|
| 130 |
+
}
|
| 131 |
+
});
|
| 132 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/SessionContext.tsx
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, {
|
| 8 |
+
createContext,
|
| 9 |
+
useCallback,
|
| 10 |
+
useContext,
|
| 11 |
+
useState,
|
| 12 |
+
useMemo,
|
| 13 |
+
useEffect,
|
| 14 |
+
} from 'react';
|
| 15 |
+
|
| 16 |
+
import {
|
| 17 |
+
uiTelemetryService,
|
| 18 |
+
SessionMetrics,
|
| 19 |
+
ModelMetrics,
|
| 20 |
+
sessionId,
|
| 21 |
+
} from '@qwen-code/qwen-code-core';
|
| 22 |
+
|
| 23 |
+
// --- Interface Definitions ---
|
| 24 |
+
|
| 25 |
+
export type { SessionMetrics, ModelMetrics };
|
| 26 |
+
|
| 27 |
+
export interface SessionStatsState {
|
| 28 |
+
sessionId: string;
|
| 29 |
+
sessionStartTime: Date;
|
| 30 |
+
metrics: SessionMetrics;
|
| 31 |
+
lastPromptTokenCount: number;
|
| 32 |
+
promptCount: number;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
export interface ComputedSessionStats {
|
| 36 |
+
totalApiTime: number;
|
| 37 |
+
totalToolTime: number;
|
| 38 |
+
agentActiveTime: number;
|
| 39 |
+
apiTimePercent: number;
|
| 40 |
+
toolTimePercent: number;
|
| 41 |
+
cacheEfficiency: number;
|
| 42 |
+
totalDecisions: number;
|
| 43 |
+
successRate: number;
|
| 44 |
+
agreementRate: number;
|
| 45 |
+
totalCachedTokens: number;
|
| 46 |
+
totalPromptTokens: number;
|
| 47 |
+
totalLinesAdded: number;
|
| 48 |
+
totalLinesRemoved: number;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// Defines the final "value" of our context, including the state
|
| 52 |
+
// and the functions to update it.
|
| 53 |
+
interface SessionStatsContextValue {
|
| 54 |
+
stats: SessionStatsState;
|
| 55 |
+
startNewPrompt: () => void;
|
| 56 |
+
getPromptCount: () => number;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// --- Context Definition ---
|
| 60 |
+
|
| 61 |
+
const SessionStatsContext = createContext<SessionStatsContextValue | undefined>(
|
| 62 |
+
undefined,
|
| 63 |
+
);
|
| 64 |
+
|
| 65 |
+
// --- Provider Component ---
|
| 66 |
+
|
| 67 |
+
export const SessionStatsProvider: React.FC<{ children: React.ReactNode }> = ({
|
| 68 |
+
children,
|
| 69 |
+
}) => {
|
| 70 |
+
const [stats, setStats] = useState<SessionStatsState>({
|
| 71 |
+
sessionId,
|
| 72 |
+
sessionStartTime: new Date(),
|
| 73 |
+
metrics: uiTelemetryService.getMetrics(),
|
| 74 |
+
lastPromptTokenCount: 0,
|
| 75 |
+
promptCount: 0,
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
useEffect(() => {
|
| 79 |
+
const handleUpdate = ({
|
| 80 |
+
metrics,
|
| 81 |
+
lastPromptTokenCount,
|
| 82 |
+
}: {
|
| 83 |
+
metrics: SessionMetrics;
|
| 84 |
+
lastPromptTokenCount: number;
|
| 85 |
+
}) => {
|
| 86 |
+
setStats((prevState) => ({
|
| 87 |
+
...prevState,
|
| 88 |
+
metrics,
|
| 89 |
+
lastPromptTokenCount,
|
| 90 |
+
}));
|
| 91 |
+
};
|
| 92 |
+
|
| 93 |
+
uiTelemetryService.on('update', handleUpdate);
|
| 94 |
+
// Set initial state
|
| 95 |
+
handleUpdate({
|
| 96 |
+
metrics: uiTelemetryService.getMetrics(),
|
| 97 |
+
lastPromptTokenCount: uiTelemetryService.getLastPromptTokenCount(),
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
return () => {
|
| 101 |
+
uiTelemetryService.off('update', handleUpdate);
|
| 102 |
+
};
|
| 103 |
+
}, []);
|
| 104 |
+
|
| 105 |
+
const startNewPrompt = useCallback(() => {
|
| 106 |
+
setStats((prevState) => ({
|
| 107 |
+
...prevState,
|
| 108 |
+
promptCount: prevState.promptCount + 1,
|
| 109 |
+
}));
|
| 110 |
+
}, []);
|
| 111 |
+
|
| 112 |
+
const getPromptCount = useCallback(
|
| 113 |
+
() => stats.promptCount,
|
| 114 |
+
[stats.promptCount],
|
| 115 |
+
);
|
| 116 |
+
|
| 117 |
+
const value = useMemo(
|
| 118 |
+
() => ({
|
| 119 |
+
stats,
|
| 120 |
+
startNewPrompt,
|
| 121 |
+
getPromptCount,
|
| 122 |
+
}),
|
| 123 |
+
[stats, startNewPrompt, getPromptCount],
|
| 124 |
+
);
|
| 125 |
+
|
| 126 |
+
return (
|
| 127 |
+
<SessionStatsContext.Provider value={value}>
|
| 128 |
+
{children}
|
| 129 |
+
</SessionStatsContext.Provider>
|
| 130 |
+
);
|
| 131 |
+
};
|
| 132 |
+
|
| 133 |
+
// --- Consumer Hook ---
|
| 134 |
+
|
| 135 |
+
export const useSessionStats = () => {
|
| 136 |
+
const context = useContext(SessionStatsContext);
|
| 137 |
+
if (context === undefined) {
|
| 138 |
+
throw new Error(
|
| 139 |
+
'useSessionStats must be used within a SessionStatsProvider',
|
| 140 |
+
);
|
| 141 |
+
}
|
| 142 |
+
return context;
|
| 143 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/SettingsContext.tsx
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, { useContext } from 'react';
|
| 8 |
+
import { LoadedSettings } from '../../config/settings.js';
|
| 9 |
+
|
| 10 |
+
export const SettingsContext = React.createContext<LoadedSettings | undefined>(
|
| 11 |
+
undefined,
|
| 12 |
+
);
|
| 13 |
+
|
| 14 |
+
export const useSettings = () => {
|
| 15 |
+
const context = useContext(SettingsContext);
|
| 16 |
+
if (context === undefined) {
|
| 17 |
+
throw new Error('useSettings must be used within a SettingsProvider');
|
| 18 |
+
}
|
| 19 |
+
return context;
|
| 20 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/StreamingContext.tsx
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import React, { createContext } from 'react';
|
| 8 |
+
import { StreamingState } from '../types.js';
|
| 9 |
+
|
| 10 |
+
export const StreamingContext = createContext<StreamingState | undefined>(
|
| 11 |
+
undefined,
|
| 12 |
+
);
|
| 13 |
+
|
| 14 |
+
export const useStreamingContext = (): StreamingState => {
|
| 15 |
+
const context = React.useContext(StreamingContext);
|
| 16 |
+
if (context === undefined) {
|
| 17 |
+
throw new Error(
|
| 18 |
+
'useStreamingContext must be used within a StreamingContextProvider',
|
| 19 |
+
);
|
| 20 |
+
}
|
| 21 |
+
return context;
|
| 22 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/contexts/VimModeContext.tsx
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
createContext,
|
| 9 |
+
useCallback,
|
| 10 |
+
useContext,
|
| 11 |
+
useEffect,
|
| 12 |
+
useState,
|
| 13 |
+
} from 'react';
|
| 14 |
+
import { LoadedSettings, SettingScope } from '../../config/settings.js';
|
| 15 |
+
|
| 16 |
+
export type VimMode = 'NORMAL' | 'INSERT';
|
| 17 |
+
|
| 18 |
+
interface VimModeContextType {
|
| 19 |
+
vimEnabled: boolean;
|
| 20 |
+
vimMode: VimMode;
|
| 21 |
+
toggleVimEnabled: () => Promise<boolean>;
|
| 22 |
+
setVimMode: (mode: VimMode) => void;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
const VimModeContext = createContext<VimModeContextType | undefined>(undefined);
|
| 26 |
+
|
| 27 |
+
export const VimModeProvider = ({
|
| 28 |
+
children,
|
| 29 |
+
settings,
|
| 30 |
+
}: {
|
| 31 |
+
children: React.ReactNode;
|
| 32 |
+
settings: LoadedSettings;
|
| 33 |
+
}) => {
|
| 34 |
+
const initialVimEnabled = settings.merged.vimMode ?? false;
|
| 35 |
+
const [vimEnabled, setVimEnabled] = useState(initialVimEnabled);
|
| 36 |
+
const [vimMode, setVimMode] = useState<VimMode>(
|
| 37 |
+
initialVimEnabled ? 'NORMAL' : 'INSERT',
|
| 38 |
+
);
|
| 39 |
+
|
| 40 |
+
useEffect(() => {
|
| 41 |
+
// Initialize vimEnabled from settings on mount
|
| 42 |
+
const enabled = settings.merged.vimMode ?? false;
|
| 43 |
+
setVimEnabled(enabled);
|
| 44 |
+
// When vim mode is enabled, always start in NORMAL mode
|
| 45 |
+
if (enabled) {
|
| 46 |
+
setVimMode('NORMAL');
|
| 47 |
+
}
|
| 48 |
+
}, [settings.merged.vimMode]);
|
| 49 |
+
|
| 50 |
+
const toggleVimEnabled = useCallback(async () => {
|
| 51 |
+
const newValue = !vimEnabled;
|
| 52 |
+
setVimEnabled(newValue);
|
| 53 |
+
// When enabling vim mode, start in NORMAL mode
|
| 54 |
+
if (newValue) {
|
| 55 |
+
setVimMode('NORMAL');
|
| 56 |
+
}
|
| 57 |
+
await settings.setValue(SettingScope.User, 'vimMode', newValue);
|
| 58 |
+
return newValue;
|
| 59 |
+
}, [vimEnabled, settings]);
|
| 60 |
+
|
| 61 |
+
const value = {
|
| 62 |
+
vimEnabled,
|
| 63 |
+
vimMode,
|
| 64 |
+
toggleVimEnabled,
|
| 65 |
+
setVimMode,
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
return (
|
| 69 |
+
<VimModeContext.Provider value={value}>{children}</VimModeContext.Provider>
|
| 70 |
+
);
|
| 71 |
+
};
|
| 72 |
+
|
| 73 |
+
export const useVimMode = () => {
|
| 74 |
+
const context = useContext(VimModeContext);
|
| 75 |
+
if (context === undefined) {
|
| 76 |
+
throw new Error('useVimMode must be used within a VimModeProvider');
|
| 77 |
+
}
|
| 78 |
+
return context;
|
| 79 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/editors/editorSettingsManager.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
allowEditorTypeInSandbox,
|
| 9 |
+
checkHasEditorType,
|
| 10 |
+
type EditorType,
|
| 11 |
+
} from '@qwen-code/qwen-code-core';
|
| 12 |
+
|
| 13 |
+
export interface EditorDisplay {
|
| 14 |
+
name: string;
|
| 15 |
+
type: EditorType | 'not_set';
|
| 16 |
+
disabled: boolean;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
export const EDITOR_DISPLAY_NAMES: Record<EditorType, string> = {
|
| 20 |
+
cursor: 'Cursor',
|
| 21 |
+
emacs: 'Emacs',
|
| 22 |
+
neovim: 'Neovim',
|
| 23 |
+
vim: 'Vim',
|
| 24 |
+
vscode: 'VS Code',
|
| 25 |
+
vscodium: 'VSCodium',
|
| 26 |
+
windsurf: 'Windsurf',
|
| 27 |
+
zed: 'Zed',
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
class EditorSettingsManager {
|
| 31 |
+
private readonly availableEditors: EditorDisplay[];
|
| 32 |
+
|
| 33 |
+
constructor() {
|
| 34 |
+
const editorTypes = Object.keys(
|
| 35 |
+
EDITOR_DISPLAY_NAMES,
|
| 36 |
+
).sort() as EditorType[];
|
| 37 |
+
this.availableEditors = [
|
| 38 |
+
{
|
| 39 |
+
name: 'None',
|
| 40 |
+
type: 'not_set',
|
| 41 |
+
disabled: false,
|
| 42 |
+
},
|
| 43 |
+
...editorTypes.map((type) => {
|
| 44 |
+
const hasEditor = checkHasEditorType(type);
|
| 45 |
+
const isAllowedInSandbox = allowEditorTypeInSandbox(type);
|
| 46 |
+
|
| 47 |
+
let labelSuffix = !isAllowedInSandbox
|
| 48 |
+
? ' (Not available in sandbox)'
|
| 49 |
+
: '';
|
| 50 |
+
labelSuffix = !hasEditor ? ' (Not installed)' : labelSuffix;
|
| 51 |
+
|
| 52 |
+
return {
|
| 53 |
+
name: EDITOR_DISPLAY_NAMES[type] + labelSuffix,
|
| 54 |
+
type,
|
| 55 |
+
disabled: !hasEditor || !isAllowedInSandbox,
|
| 56 |
+
};
|
| 57 |
+
}),
|
| 58 |
+
];
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
getAvailableEditorDisplays(): EditorDisplay[] {
|
| 62 |
+
return this.availableEditors;
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
export const editorSettingsManager = new EditorSettingsManager();
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/atCommandProcessor.test.ts
ADDED
|
@@ -0,0 +1,1102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
|
| 8 |
+
import { handleAtCommand } from './atCommandProcessor.js';
|
| 9 |
+
import {
|
| 10 |
+
Config,
|
| 11 |
+
FileDiscoveryService,
|
| 12 |
+
GlobTool,
|
| 13 |
+
ReadManyFilesTool,
|
| 14 |
+
StandardFileSystemService,
|
| 15 |
+
ToolRegistry,
|
| 16 |
+
} from '@qwen-code/qwen-code-core';
|
| 17 |
+
import * as os from 'os';
|
| 18 |
+
import { ToolCallStatus } from '../types.js';
|
| 19 |
+
import { UseHistoryManagerReturn } from './useHistoryManager.js';
|
| 20 |
+
import * as fsPromises from 'fs/promises';
|
| 21 |
+
import * as path from 'path';
|
| 22 |
+
|
| 23 |
+
describe('handleAtCommand', () => {
|
| 24 |
+
let testRootDir: string;
|
| 25 |
+
let mockConfig: Config;
|
| 26 |
+
|
| 27 |
+
const mockAddItem: Mock<UseHistoryManagerReturn['addItem']> = vi.fn();
|
| 28 |
+
const mockOnDebugMessage: Mock<(message: string) => void> = vi.fn();
|
| 29 |
+
|
| 30 |
+
let abortController: AbortController;
|
| 31 |
+
|
| 32 |
+
async function createTestFile(fullPath: string, fileContents: string) {
|
| 33 |
+
await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
|
| 34 |
+
await fsPromises.writeFile(fullPath, fileContents);
|
| 35 |
+
return path.resolve(testRootDir, fullPath);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
beforeEach(async () => {
|
| 39 |
+
vi.resetAllMocks();
|
| 40 |
+
|
| 41 |
+
testRootDir = await fsPromises.mkdtemp(
|
| 42 |
+
path.join(os.tmpdir(), 'folder-structure-test-'),
|
| 43 |
+
);
|
| 44 |
+
|
| 45 |
+
abortController = new AbortController();
|
| 46 |
+
|
| 47 |
+
const getToolRegistry = vi.fn();
|
| 48 |
+
|
| 49 |
+
mockConfig = {
|
| 50 |
+
getToolRegistry,
|
| 51 |
+
getTargetDir: () => testRootDir,
|
| 52 |
+
isSandboxed: () => false,
|
| 53 |
+
getFileService: () => new FileDiscoveryService(testRootDir),
|
| 54 |
+
getFileFilteringRespectGitIgnore: () => true,
|
| 55 |
+
getFileFilteringRespectGeminiIgnore: () => true,
|
| 56 |
+
getFileFilteringOptions: () => ({
|
| 57 |
+
respectGitIgnore: true,
|
| 58 |
+
respectGeminiIgnore: true,
|
| 59 |
+
}),
|
| 60 |
+
getFileSystemService: () => new StandardFileSystemService(),
|
| 61 |
+
getEnableRecursiveFileSearch: vi.fn(() => true),
|
| 62 |
+
getWorkspaceContext: () => ({
|
| 63 |
+
isPathWithinWorkspace: () => true,
|
| 64 |
+
getDirectories: () => [testRootDir],
|
| 65 |
+
}),
|
| 66 |
+
getMcpServers: () => ({}),
|
| 67 |
+
getMcpServerCommand: () => undefined,
|
| 68 |
+
getPromptRegistry: () => ({
|
| 69 |
+
getPromptsByServer: () => [],
|
| 70 |
+
}),
|
| 71 |
+
getDebugMode: () => false,
|
| 72 |
+
} as unknown as Config;
|
| 73 |
+
|
| 74 |
+
const registry = new ToolRegistry(mockConfig);
|
| 75 |
+
registry.registerTool(new ReadManyFilesTool(mockConfig));
|
| 76 |
+
registry.registerTool(new GlobTool(mockConfig));
|
| 77 |
+
getToolRegistry.mockReturnValue(registry);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
afterEach(async () => {
|
| 81 |
+
abortController.abort();
|
| 82 |
+
await fsPromises.rm(testRootDir, { recursive: true, force: true });
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('should pass through query if no @ command is present', async () => {
|
| 86 |
+
const query = 'regular user query';
|
| 87 |
+
|
| 88 |
+
const result = await handleAtCommand({
|
| 89 |
+
query,
|
| 90 |
+
config: mockConfig,
|
| 91 |
+
addItem: mockAddItem,
|
| 92 |
+
onDebugMessage: mockOnDebugMessage,
|
| 93 |
+
messageId: 123,
|
| 94 |
+
signal: abortController.signal,
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
expect(result).toEqual({
|
| 98 |
+
processedQuery: [{ text: query }],
|
| 99 |
+
shouldProceed: true,
|
| 100 |
+
});
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
it('should pass through original query if only a lone @ symbol is present', async () => {
|
| 104 |
+
const queryWithSpaces = ' @ ';
|
| 105 |
+
|
| 106 |
+
const result = await handleAtCommand({
|
| 107 |
+
query: queryWithSpaces,
|
| 108 |
+
config: mockConfig,
|
| 109 |
+
addItem: mockAddItem,
|
| 110 |
+
onDebugMessage: mockOnDebugMessage,
|
| 111 |
+
messageId: 124,
|
| 112 |
+
signal: abortController.signal,
|
| 113 |
+
});
|
| 114 |
+
|
| 115 |
+
expect(result).toEqual({
|
| 116 |
+
processedQuery: [{ text: queryWithSpaces }],
|
| 117 |
+
shouldProceed: true,
|
| 118 |
+
});
|
| 119 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 120 |
+
'Lone @ detected, will be treated as text in the modified query.',
|
| 121 |
+
);
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
it('should process a valid text file path', async () => {
|
| 125 |
+
const fileContent = 'This is the file content.';
|
| 126 |
+
const filePath = await createTestFile(
|
| 127 |
+
path.join(testRootDir, 'path', 'to', 'file.txt'),
|
| 128 |
+
fileContent,
|
| 129 |
+
);
|
| 130 |
+
const query = `@${filePath}`;
|
| 131 |
+
|
| 132 |
+
const result = await handleAtCommand({
|
| 133 |
+
query,
|
| 134 |
+
config: mockConfig,
|
| 135 |
+
addItem: mockAddItem,
|
| 136 |
+
onDebugMessage: mockOnDebugMessage,
|
| 137 |
+
messageId: 125,
|
| 138 |
+
signal: abortController.signal,
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
expect(result).toEqual({
|
| 142 |
+
processedQuery: [
|
| 143 |
+
{ text: `@${filePath}` },
|
| 144 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 145 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 146 |
+
{ text: fileContent },
|
| 147 |
+
{ text: '\n--- End of content ---' },
|
| 148 |
+
],
|
| 149 |
+
shouldProceed: true,
|
| 150 |
+
});
|
| 151 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 152 |
+
expect.objectContaining({
|
| 153 |
+
type: 'tool_group',
|
| 154 |
+
tools: [expect.objectContaining({ status: ToolCallStatus.Success })],
|
| 155 |
+
}),
|
| 156 |
+
125,
|
| 157 |
+
);
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
it('should process a valid directory path and convert to glob', async () => {
|
| 161 |
+
const fileContent = 'This is the file content.';
|
| 162 |
+
const filePath = await createTestFile(
|
| 163 |
+
path.join(testRootDir, 'path', 'to', 'file.txt'),
|
| 164 |
+
fileContent,
|
| 165 |
+
);
|
| 166 |
+
const dirPath = path.dirname(filePath);
|
| 167 |
+
const query = `@${dirPath}`;
|
| 168 |
+
const resolvedGlob = `${dirPath}/**`;
|
| 169 |
+
|
| 170 |
+
const result = await handleAtCommand({
|
| 171 |
+
query,
|
| 172 |
+
config: mockConfig,
|
| 173 |
+
addItem: mockAddItem,
|
| 174 |
+
onDebugMessage: mockOnDebugMessage,
|
| 175 |
+
messageId: 126,
|
| 176 |
+
signal: abortController.signal,
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
expect(result).toEqual({
|
| 180 |
+
processedQuery: [
|
| 181 |
+
{ text: `@${resolvedGlob}` },
|
| 182 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 183 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 184 |
+
{ text: fileContent },
|
| 185 |
+
{ text: '\n--- End of content ---' },
|
| 186 |
+
],
|
| 187 |
+
shouldProceed: true,
|
| 188 |
+
});
|
| 189 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 190 |
+
`Path ${dirPath} resolved to directory, using glob: ${resolvedGlob}`,
|
| 191 |
+
);
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
it('should handle query with text before and after @command', async () => {
|
| 195 |
+
const fileContent = 'Markdown content.';
|
| 196 |
+
const filePath = await createTestFile(
|
| 197 |
+
path.join(testRootDir, 'doc.md'),
|
| 198 |
+
fileContent,
|
| 199 |
+
);
|
| 200 |
+
const textBefore = 'Explain this: ';
|
| 201 |
+
const textAfter = ' in detail.';
|
| 202 |
+
const query = `${textBefore}@${filePath}${textAfter}`;
|
| 203 |
+
|
| 204 |
+
const result = await handleAtCommand({
|
| 205 |
+
query,
|
| 206 |
+
config: mockConfig,
|
| 207 |
+
addItem: mockAddItem,
|
| 208 |
+
onDebugMessage: mockOnDebugMessage,
|
| 209 |
+
messageId: 128,
|
| 210 |
+
signal: abortController.signal,
|
| 211 |
+
});
|
| 212 |
+
|
| 213 |
+
expect(result).toEqual({
|
| 214 |
+
processedQuery: [
|
| 215 |
+
{ text: `${textBefore}@${filePath}${textAfter}` },
|
| 216 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 217 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 218 |
+
{ text: fileContent },
|
| 219 |
+
{ text: '\n--- End of content ---' },
|
| 220 |
+
],
|
| 221 |
+
shouldProceed: true,
|
| 222 |
+
});
|
| 223 |
+
});
|
| 224 |
+
|
| 225 |
+
it('should correctly unescape paths with escaped spaces', async () => {
|
| 226 |
+
const fileContent = 'This is the file content.';
|
| 227 |
+
const filePath = await createTestFile(
|
| 228 |
+
path.join(testRootDir, 'path', 'to', 'my file.txt'),
|
| 229 |
+
fileContent,
|
| 230 |
+
);
|
| 231 |
+
const escapedpath = path.join(testRootDir, 'path', 'to', 'my\\ file.txt');
|
| 232 |
+
const query = `@${escapedpath}`;
|
| 233 |
+
|
| 234 |
+
const result = await handleAtCommand({
|
| 235 |
+
query,
|
| 236 |
+
config: mockConfig,
|
| 237 |
+
addItem: mockAddItem,
|
| 238 |
+
onDebugMessage: mockOnDebugMessage,
|
| 239 |
+
messageId: 125,
|
| 240 |
+
signal: abortController.signal,
|
| 241 |
+
});
|
| 242 |
+
|
| 243 |
+
expect(result).toEqual({
|
| 244 |
+
processedQuery: [
|
| 245 |
+
{ text: `@${filePath}` },
|
| 246 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 247 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 248 |
+
{ text: fileContent },
|
| 249 |
+
{ text: '\n--- End of content ---' },
|
| 250 |
+
],
|
| 251 |
+
shouldProceed: true,
|
| 252 |
+
});
|
| 253 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 254 |
+
expect.objectContaining({
|
| 255 |
+
type: 'tool_group',
|
| 256 |
+
tools: [expect.objectContaining({ status: ToolCallStatus.Success })],
|
| 257 |
+
}),
|
| 258 |
+
125,
|
| 259 |
+
);
|
| 260 |
+
});
|
| 261 |
+
|
| 262 |
+
it('should handle multiple @file references', async () => {
|
| 263 |
+
const content1 = 'Content file1';
|
| 264 |
+
const file1Path = await createTestFile(
|
| 265 |
+
path.join(testRootDir, 'file1.txt'),
|
| 266 |
+
content1,
|
| 267 |
+
);
|
| 268 |
+
const content2 = 'Content file2';
|
| 269 |
+
const file2Path = await createTestFile(
|
| 270 |
+
path.join(testRootDir, 'file2.md'),
|
| 271 |
+
content2,
|
| 272 |
+
);
|
| 273 |
+
const query = `@${file1Path} @${file2Path}`;
|
| 274 |
+
|
| 275 |
+
const result = await handleAtCommand({
|
| 276 |
+
query,
|
| 277 |
+
config: mockConfig,
|
| 278 |
+
addItem: mockAddItem,
|
| 279 |
+
onDebugMessage: mockOnDebugMessage,
|
| 280 |
+
messageId: 130,
|
| 281 |
+
signal: abortController.signal,
|
| 282 |
+
});
|
| 283 |
+
|
| 284 |
+
expect(result).toEqual({
|
| 285 |
+
processedQuery: [
|
| 286 |
+
{ text: query },
|
| 287 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 288 |
+
{ text: `\nContent from @${file1Path}:\n` },
|
| 289 |
+
{ text: content1 },
|
| 290 |
+
{ text: `\nContent from @${file2Path}:\n` },
|
| 291 |
+
{ text: content2 },
|
| 292 |
+
{ text: '\n--- End of content ---' },
|
| 293 |
+
],
|
| 294 |
+
shouldProceed: true,
|
| 295 |
+
});
|
| 296 |
+
});
|
| 297 |
+
|
| 298 |
+
it('should handle multiple @file references with interleaved text', async () => {
|
| 299 |
+
const text1 = 'Check ';
|
| 300 |
+
const content1 = 'C1';
|
| 301 |
+
const file1Path = await createTestFile(
|
| 302 |
+
path.join(testRootDir, 'f1.txt'),
|
| 303 |
+
content1,
|
| 304 |
+
);
|
| 305 |
+
const text2 = ' and ';
|
| 306 |
+
const content2 = 'C2';
|
| 307 |
+
const file2Path = await createTestFile(
|
| 308 |
+
path.join(testRootDir, 'f2.md'),
|
| 309 |
+
content2,
|
| 310 |
+
);
|
| 311 |
+
const text3 = ' please.';
|
| 312 |
+
const query = `${text1}@${file1Path}${text2}@${file2Path}${text3}`;
|
| 313 |
+
|
| 314 |
+
const result = await handleAtCommand({
|
| 315 |
+
query,
|
| 316 |
+
config: mockConfig,
|
| 317 |
+
addItem: mockAddItem,
|
| 318 |
+
onDebugMessage: mockOnDebugMessage,
|
| 319 |
+
messageId: 131,
|
| 320 |
+
signal: abortController.signal,
|
| 321 |
+
});
|
| 322 |
+
|
| 323 |
+
expect(result).toEqual({
|
| 324 |
+
processedQuery: [
|
| 325 |
+
{ text: query },
|
| 326 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 327 |
+
{ text: `\nContent from @${file1Path}:\n` },
|
| 328 |
+
{ text: content1 },
|
| 329 |
+
{ text: `\nContent from @${file2Path}:\n` },
|
| 330 |
+
{ text: content2 },
|
| 331 |
+
{ text: '\n--- End of content ---' },
|
| 332 |
+
],
|
| 333 |
+
shouldProceed: true,
|
| 334 |
+
});
|
| 335 |
+
});
|
| 336 |
+
|
| 337 |
+
it('should handle a mix of valid, invalid, and lone @ references', async () => {
|
| 338 |
+
const content1 = 'Valid content 1';
|
| 339 |
+
const file1Path = await createTestFile(
|
| 340 |
+
path.join(testRootDir, 'valid1.txt'),
|
| 341 |
+
content1,
|
| 342 |
+
);
|
| 343 |
+
const invalidFile = 'nonexistent.txt';
|
| 344 |
+
const content2 = 'Globbed content';
|
| 345 |
+
const file2Path = await createTestFile(
|
| 346 |
+
path.join(testRootDir, 'resolved', 'valid2.actual'),
|
| 347 |
+
content2,
|
| 348 |
+
);
|
| 349 |
+
const query = `Look at @${file1Path} then @${invalidFile} and also just @ symbol, then @${file2Path}`;
|
| 350 |
+
|
| 351 |
+
const result = await handleAtCommand({
|
| 352 |
+
query,
|
| 353 |
+
config: mockConfig,
|
| 354 |
+
addItem: mockAddItem,
|
| 355 |
+
onDebugMessage: mockOnDebugMessage,
|
| 356 |
+
messageId: 132,
|
| 357 |
+
signal: abortController.signal,
|
| 358 |
+
});
|
| 359 |
+
|
| 360 |
+
expect(result).toEqual({
|
| 361 |
+
processedQuery: [
|
| 362 |
+
{
|
| 363 |
+
text: `Look at @${file1Path} then @${invalidFile} and also just @ symbol, then @${file2Path}`,
|
| 364 |
+
},
|
| 365 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 366 |
+
{ text: `\nContent from @${file2Path}:\n` },
|
| 367 |
+
{ text: content2 },
|
| 368 |
+
{ text: `\nContent from @${file1Path}:\n` },
|
| 369 |
+
{ text: content1 },
|
| 370 |
+
{ text: '\n--- End of content ---' },
|
| 371 |
+
],
|
| 372 |
+
shouldProceed: true,
|
| 373 |
+
});
|
| 374 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 375 |
+
`Path ${invalidFile} not found directly, attempting glob search.`,
|
| 376 |
+
);
|
| 377 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 378 |
+
`Glob search for '**/*${invalidFile}*' found no files or an error. Path ${invalidFile} will be skipped.`,
|
| 379 |
+
);
|
| 380 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 381 |
+
'Lone @ detected, will be treated as text in the modified query.',
|
| 382 |
+
);
|
| 383 |
+
});
|
| 384 |
+
|
| 385 |
+
it('should return original query if all @paths are invalid or lone @', async () => {
|
| 386 |
+
const query = 'Check @nonexistent.txt and @ also';
|
| 387 |
+
|
| 388 |
+
const result = await handleAtCommand({
|
| 389 |
+
query,
|
| 390 |
+
config: mockConfig,
|
| 391 |
+
addItem: mockAddItem,
|
| 392 |
+
onDebugMessage: mockOnDebugMessage,
|
| 393 |
+
messageId: 133,
|
| 394 |
+
signal: abortController.signal,
|
| 395 |
+
});
|
| 396 |
+
|
| 397 |
+
expect(result).toEqual({
|
| 398 |
+
processedQuery: [{ text: 'Check @nonexistent.txt and @ also' }],
|
| 399 |
+
shouldProceed: true,
|
| 400 |
+
});
|
| 401 |
+
});
|
| 402 |
+
|
| 403 |
+
describe('git-aware filtering', () => {
|
| 404 |
+
beforeEach(async () => {
|
| 405 |
+
await fsPromises.mkdir(path.join(testRootDir, '.git'), {
|
| 406 |
+
recursive: true,
|
| 407 |
+
});
|
| 408 |
+
});
|
| 409 |
+
|
| 410 |
+
it('should skip git-ignored files in @ commands', async () => {
|
| 411 |
+
await createTestFile(
|
| 412 |
+
path.join(testRootDir, '.gitignore'),
|
| 413 |
+
'node_modules/package.json',
|
| 414 |
+
);
|
| 415 |
+
const gitIgnoredFile = await createTestFile(
|
| 416 |
+
path.join(testRootDir, 'node_modules', 'package.json'),
|
| 417 |
+
'the file contents',
|
| 418 |
+
);
|
| 419 |
+
|
| 420 |
+
const query = `@${gitIgnoredFile}`;
|
| 421 |
+
|
| 422 |
+
const result = await handleAtCommand({
|
| 423 |
+
query,
|
| 424 |
+
config: mockConfig,
|
| 425 |
+
addItem: mockAddItem,
|
| 426 |
+
onDebugMessage: mockOnDebugMessage,
|
| 427 |
+
messageId: 200,
|
| 428 |
+
signal: abortController.signal,
|
| 429 |
+
});
|
| 430 |
+
|
| 431 |
+
expect(result).toEqual({
|
| 432 |
+
processedQuery: [{ text: query }],
|
| 433 |
+
shouldProceed: true,
|
| 434 |
+
});
|
| 435 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 436 |
+
`Path ${gitIgnoredFile} is git-ignored and will be skipped.`,
|
| 437 |
+
);
|
| 438 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 439 |
+
`Ignored 1 files:\nGit-ignored: ${gitIgnoredFile}`,
|
| 440 |
+
);
|
| 441 |
+
});
|
| 442 |
+
|
| 443 |
+
it('should process non-git-ignored files normally', async () => {
|
| 444 |
+
await createTestFile(
|
| 445 |
+
path.join(testRootDir, '.gitignore'),
|
| 446 |
+
'node_modules/package.json',
|
| 447 |
+
);
|
| 448 |
+
|
| 449 |
+
const validFile = await createTestFile(
|
| 450 |
+
path.join(testRootDir, 'src', 'index.ts'),
|
| 451 |
+
'console.log("Hello world");',
|
| 452 |
+
);
|
| 453 |
+
const query = `@${validFile}`;
|
| 454 |
+
|
| 455 |
+
const result = await handleAtCommand({
|
| 456 |
+
query,
|
| 457 |
+
config: mockConfig,
|
| 458 |
+
addItem: mockAddItem,
|
| 459 |
+
onDebugMessage: mockOnDebugMessage,
|
| 460 |
+
messageId: 201,
|
| 461 |
+
signal: abortController.signal,
|
| 462 |
+
});
|
| 463 |
+
|
| 464 |
+
expect(result).toEqual({
|
| 465 |
+
processedQuery: [
|
| 466 |
+
{ text: `@${validFile}` },
|
| 467 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 468 |
+
{ text: `\nContent from @${validFile}:\n` },
|
| 469 |
+
{ text: 'console.log("Hello world");' },
|
| 470 |
+
{ text: '\n--- End of content ---' },
|
| 471 |
+
],
|
| 472 |
+
shouldProceed: true,
|
| 473 |
+
});
|
| 474 |
+
});
|
| 475 |
+
|
| 476 |
+
it('should handle mixed git-ignored and valid files', async () => {
|
| 477 |
+
await createTestFile(path.join(testRootDir, '.gitignore'), '.env');
|
| 478 |
+
const validFile = await createTestFile(
|
| 479 |
+
path.join(testRootDir, 'README.md'),
|
| 480 |
+
'# Project README',
|
| 481 |
+
);
|
| 482 |
+
const gitIgnoredFile = await createTestFile(
|
| 483 |
+
path.join(testRootDir, '.env'),
|
| 484 |
+
'SECRET=123',
|
| 485 |
+
);
|
| 486 |
+
const query = `@${validFile} @${gitIgnoredFile}`;
|
| 487 |
+
|
| 488 |
+
const result = await handleAtCommand({
|
| 489 |
+
query,
|
| 490 |
+
config: mockConfig,
|
| 491 |
+
addItem: mockAddItem,
|
| 492 |
+
onDebugMessage: mockOnDebugMessage,
|
| 493 |
+
messageId: 202,
|
| 494 |
+
signal: abortController.signal,
|
| 495 |
+
});
|
| 496 |
+
|
| 497 |
+
expect(result).toEqual({
|
| 498 |
+
processedQuery: [
|
| 499 |
+
{ text: `@${validFile} @${gitIgnoredFile}` },
|
| 500 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 501 |
+
{ text: `\nContent from @${validFile}:\n` },
|
| 502 |
+
{ text: '# Project README' },
|
| 503 |
+
{ text: '\n--- End of content ---' },
|
| 504 |
+
],
|
| 505 |
+
shouldProceed: true,
|
| 506 |
+
});
|
| 507 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 508 |
+
`Path ${gitIgnoredFile} is git-ignored and will be skipped.`,
|
| 509 |
+
);
|
| 510 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 511 |
+
`Ignored 1 files:\nGit-ignored: ${gitIgnoredFile}`,
|
| 512 |
+
);
|
| 513 |
+
});
|
| 514 |
+
|
| 515 |
+
it('should always ignore .git directory files', async () => {
|
| 516 |
+
const gitFile = await createTestFile(
|
| 517 |
+
path.join(testRootDir, '.git', 'config'),
|
| 518 |
+
'[core]\n\trepositoryformatversion = 0\n',
|
| 519 |
+
);
|
| 520 |
+
const query = `@${gitFile}`;
|
| 521 |
+
|
| 522 |
+
const result = await handleAtCommand({
|
| 523 |
+
query,
|
| 524 |
+
config: mockConfig,
|
| 525 |
+
addItem: mockAddItem,
|
| 526 |
+
onDebugMessage: mockOnDebugMessage,
|
| 527 |
+
messageId: 203,
|
| 528 |
+
signal: abortController.signal,
|
| 529 |
+
});
|
| 530 |
+
|
| 531 |
+
expect(result).toEqual({
|
| 532 |
+
processedQuery: [{ text: query }],
|
| 533 |
+
shouldProceed: true,
|
| 534 |
+
});
|
| 535 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 536 |
+
`Path ${gitFile} is git-ignored and will be skipped.`,
|
| 537 |
+
);
|
| 538 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 539 |
+
`Ignored 1 files:\nGit-ignored: ${gitFile}`,
|
| 540 |
+
);
|
| 541 |
+
});
|
| 542 |
+
});
|
| 543 |
+
|
| 544 |
+
describe('when recursive file search is disabled', () => {
|
| 545 |
+
beforeEach(() => {
|
| 546 |
+
vi.mocked(mockConfig.getEnableRecursiveFileSearch).mockReturnValue(false);
|
| 547 |
+
});
|
| 548 |
+
|
| 549 |
+
it('should not use glob search for a nonexistent file', async () => {
|
| 550 |
+
const invalidFile = 'nonexistent.txt';
|
| 551 |
+
const query = `@${invalidFile}`;
|
| 552 |
+
|
| 553 |
+
const result = await handleAtCommand({
|
| 554 |
+
query,
|
| 555 |
+
config: mockConfig,
|
| 556 |
+
addItem: mockAddItem,
|
| 557 |
+
onDebugMessage: mockOnDebugMessage,
|
| 558 |
+
messageId: 300,
|
| 559 |
+
signal: abortController.signal,
|
| 560 |
+
});
|
| 561 |
+
|
| 562 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 563 |
+
`Glob tool not found. Path ${invalidFile} will be skipped.`,
|
| 564 |
+
);
|
| 565 |
+
expect(result.processedQuery).toEqual([{ text: query }]);
|
| 566 |
+
expect(result.shouldProceed).toBe(true);
|
| 567 |
+
});
|
| 568 |
+
});
|
| 569 |
+
|
| 570 |
+
describe('gemini-ignore filtering', () => {
|
| 571 |
+
it('should skip gemini-ignored files in @ commands', async () => {
|
| 572 |
+
await createTestFile(
|
| 573 |
+
path.join(testRootDir, '.geminiignore'),
|
| 574 |
+
'build/output.js',
|
| 575 |
+
);
|
| 576 |
+
const geminiIgnoredFile = await createTestFile(
|
| 577 |
+
path.join(testRootDir, 'build', 'output.js'),
|
| 578 |
+
'console.log("Hello");',
|
| 579 |
+
);
|
| 580 |
+
const query = `@${geminiIgnoredFile}`;
|
| 581 |
+
|
| 582 |
+
const result = await handleAtCommand({
|
| 583 |
+
query,
|
| 584 |
+
config: mockConfig,
|
| 585 |
+
addItem: mockAddItem,
|
| 586 |
+
onDebugMessage: mockOnDebugMessage,
|
| 587 |
+
messageId: 204,
|
| 588 |
+
signal: abortController.signal,
|
| 589 |
+
});
|
| 590 |
+
|
| 591 |
+
expect(result).toEqual({
|
| 592 |
+
processedQuery: [{ text: query }],
|
| 593 |
+
shouldProceed: true,
|
| 594 |
+
});
|
| 595 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 596 |
+
`Path ${geminiIgnoredFile} is gemini-ignored and will be skipped.`,
|
| 597 |
+
);
|
| 598 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 599 |
+
`Ignored 1 files:\nGemini-ignored: ${geminiIgnoredFile}`,
|
| 600 |
+
);
|
| 601 |
+
});
|
| 602 |
+
});
|
| 603 |
+
it('should process non-ignored files when .geminiignore is present', async () => {
|
| 604 |
+
await createTestFile(
|
| 605 |
+
path.join(testRootDir, '.geminiignore'),
|
| 606 |
+
'build/output.js',
|
| 607 |
+
);
|
| 608 |
+
const validFile = await createTestFile(
|
| 609 |
+
path.join(testRootDir, 'src', 'index.ts'),
|
| 610 |
+
'console.log("Hello world");',
|
| 611 |
+
);
|
| 612 |
+
const query = `@${validFile}`;
|
| 613 |
+
|
| 614 |
+
const result = await handleAtCommand({
|
| 615 |
+
query,
|
| 616 |
+
config: mockConfig,
|
| 617 |
+
addItem: mockAddItem,
|
| 618 |
+
onDebugMessage: mockOnDebugMessage,
|
| 619 |
+
messageId: 205,
|
| 620 |
+
signal: abortController.signal,
|
| 621 |
+
});
|
| 622 |
+
|
| 623 |
+
expect(result).toEqual({
|
| 624 |
+
processedQuery: [
|
| 625 |
+
{ text: `@${validFile}` },
|
| 626 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 627 |
+
{ text: `\nContent from @${validFile}:\n` },
|
| 628 |
+
{ text: 'console.log("Hello world");' },
|
| 629 |
+
{ text: '\n--- End of content ---' },
|
| 630 |
+
],
|
| 631 |
+
shouldProceed: true,
|
| 632 |
+
});
|
| 633 |
+
});
|
| 634 |
+
|
| 635 |
+
it('should handle mixed gemini-ignored and valid files', async () => {
|
| 636 |
+
await createTestFile(
|
| 637 |
+
path.join(testRootDir, '.geminiignore'),
|
| 638 |
+
'dist/bundle.js',
|
| 639 |
+
);
|
| 640 |
+
const validFile = await createTestFile(
|
| 641 |
+
path.join(testRootDir, 'src', 'main.ts'),
|
| 642 |
+
'// Main application entry',
|
| 643 |
+
);
|
| 644 |
+
const geminiIgnoredFile = await createTestFile(
|
| 645 |
+
path.join(testRootDir, 'dist', 'bundle.js'),
|
| 646 |
+
'console.log("bundle");',
|
| 647 |
+
);
|
| 648 |
+
const query = `@${validFile} @${geminiIgnoredFile}`;
|
| 649 |
+
|
| 650 |
+
const result = await handleAtCommand({
|
| 651 |
+
query,
|
| 652 |
+
config: mockConfig,
|
| 653 |
+
addItem: mockAddItem,
|
| 654 |
+
onDebugMessage: mockOnDebugMessage,
|
| 655 |
+
messageId: 206,
|
| 656 |
+
signal: abortController.signal,
|
| 657 |
+
});
|
| 658 |
+
|
| 659 |
+
expect(result).toEqual({
|
| 660 |
+
processedQuery: [
|
| 661 |
+
{ text: `@${validFile} @${geminiIgnoredFile}` },
|
| 662 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 663 |
+
{ text: `\nContent from @${validFile}:\n` },
|
| 664 |
+
{ text: '// Main application entry' },
|
| 665 |
+
{ text: '\n--- End of content ---' },
|
| 666 |
+
],
|
| 667 |
+
shouldProceed: true,
|
| 668 |
+
});
|
| 669 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 670 |
+
`Path ${geminiIgnoredFile} is gemini-ignored and will be skipped.`,
|
| 671 |
+
);
|
| 672 |
+
expect(mockOnDebugMessage).toHaveBeenCalledWith(
|
| 673 |
+
`Ignored 1 files:\nGemini-ignored: ${geminiIgnoredFile}`,
|
| 674 |
+
);
|
| 675 |
+
});
|
| 676 |
+
|
| 677 |
+
describe('punctuation termination in @ commands', () => {
|
| 678 |
+
const punctuationTestCases = [
|
| 679 |
+
{
|
| 680 |
+
name: 'comma',
|
| 681 |
+
fileName: 'test.txt',
|
| 682 |
+
fileContent: 'File content here',
|
| 683 |
+
queryTemplate: (filePath: string) =>
|
| 684 |
+
`Look at @${filePath}, then explain it.`,
|
| 685 |
+
messageId: 400,
|
| 686 |
+
},
|
| 687 |
+
{
|
| 688 |
+
name: 'period',
|
| 689 |
+
fileName: 'readme.md',
|
| 690 |
+
fileContent: 'File content here',
|
| 691 |
+
queryTemplate: (filePath: string) =>
|
| 692 |
+
`Check @${filePath}. What does it say?`,
|
| 693 |
+
messageId: 401,
|
| 694 |
+
},
|
| 695 |
+
{
|
| 696 |
+
name: 'semicolon',
|
| 697 |
+
fileName: 'example.js',
|
| 698 |
+
fileContent: 'Code example',
|
| 699 |
+
queryTemplate: (filePath: string) =>
|
| 700 |
+
`Review @${filePath}; check for bugs.`,
|
| 701 |
+
messageId: 402,
|
| 702 |
+
},
|
| 703 |
+
{
|
| 704 |
+
name: 'exclamation mark',
|
| 705 |
+
fileName: 'important.txt',
|
| 706 |
+
fileContent: 'Important content',
|
| 707 |
+
queryTemplate: (filePath: string) =>
|
| 708 |
+
`Look at @${filePath}! This is critical.`,
|
| 709 |
+
messageId: 403,
|
| 710 |
+
},
|
| 711 |
+
{
|
| 712 |
+
name: 'question mark',
|
| 713 |
+
fileName: 'config.json',
|
| 714 |
+
fileContent: 'Config settings',
|
| 715 |
+
queryTemplate: (filePath: string) =>
|
| 716 |
+
`What is in @${filePath}? Please explain.`,
|
| 717 |
+
messageId: 404,
|
| 718 |
+
},
|
| 719 |
+
{
|
| 720 |
+
name: 'opening parenthesis',
|
| 721 |
+
fileName: 'func.ts',
|
| 722 |
+
fileContent: 'Function definition',
|
| 723 |
+
queryTemplate: (filePath: string) =>
|
| 724 |
+
`Analyze @${filePath}(the main function).`,
|
| 725 |
+
messageId: 405,
|
| 726 |
+
},
|
| 727 |
+
{
|
| 728 |
+
name: 'closing parenthesis',
|
| 729 |
+
fileName: 'data.json',
|
| 730 |
+
fileContent: 'Test data',
|
| 731 |
+
queryTemplate: (filePath: string) =>
|
| 732 |
+
`Use data from @${filePath}) for testing.`,
|
| 733 |
+
messageId: 406,
|
| 734 |
+
},
|
| 735 |
+
{
|
| 736 |
+
name: 'opening square bracket',
|
| 737 |
+
fileName: 'array.js',
|
| 738 |
+
fileContent: 'Array data',
|
| 739 |
+
queryTemplate: (filePath: string) =>
|
| 740 |
+
`Check @${filePath}[0] for the first element.`,
|
| 741 |
+
messageId: 407,
|
| 742 |
+
},
|
| 743 |
+
{
|
| 744 |
+
name: 'closing square bracket',
|
| 745 |
+
fileName: 'list.md',
|
| 746 |
+
fileContent: 'List content',
|
| 747 |
+
queryTemplate: (filePath: string) =>
|
| 748 |
+
`Review item @${filePath}] from the list.`,
|
| 749 |
+
messageId: 408,
|
| 750 |
+
},
|
| 751 |
+
{
|
| 752 |
+
name: 'opening curly brace',
|
| 753 |
+
fileName: 'object.ts',
|
| 754 |
+
fileContent: 'Object definition',
|
| 755 |
+
queryTemplate: (filePath: string) =>
|
| 756 |
+
`Parse @${filePath}{prop1: value1}.`,
|
| 757 |
+
messageId: 409,
|
| 758 |
+
},
|
| 759 |
+
{
|
| 760 |
+
name: 'closing curly brace',
|
| 761 |
+
fileName: 'config.yaml',
|
| 762 |
+
fileContent: 'Configuration',
|
| 763 |
+
queryTemplate: (filePath: string) =>
|
| 764 |
+
`Use settings from @${filePath}} for deployment.`,
|
| 765 |
+
messageId: 410,
|
| 766 |
+
},
|
| 767 |
+
];
|
| 768 |
+
|
| 769 |
+
it.each(punctuationTestCases)(
|
| 770 |
+
'should terminate @path at $name',
|
| 771 |
+
async ({ fileName, fileContent, queryTemplate, messageId }) => {
|
| 772 |
+
const filePath = await createTestFile(
|
| 773 |
+
path.join(testRootDir, fileName),
|
| 774 |
+
fileContent,
|
| 775 |
+
);
|
| 776 |
+
const query = queryTemplate(filePath);
|
| 777 |
+
|
| 778 |
+
const result = await handleAtCommand({
|
| 779 |
+
query,
|
| 780 |
+
config: mockConfig,
|
| 781 |
+
addItem: mockAddItem,
|
| 782 |
+
onDebugMessage: mockOnDebugMessage,
|
| 783 |
+
messageId,
|
| 784 |
+
signal: abortController.signal,
|
| 785 |
+
});
|
| 786 |
+
|
| 787 |
+
expect(result).toEqual({
|
| 788 |
+
processedQuery: [
|
| 789 |
+
{ text: query },
|
| 790 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 791 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 792 |
+
{ text: fileContent },
|
| 793 |
+
{ text: '\n--- End of content ---' },
|
| 794 |
+
],
|
| 795 |
+
shouldProceed: true,
|
| 796 |
+
});
|
| 797 |
+
},
|
| 798 |
+
);
|
| 799 |
+
|
| 800 |
+
it('should handle multiple @paths terminated by different punctuation', async () => {
|
| 801 |
+
const content1 = 'First file';
|
| 802 |
+
const file1Path = await createTestFile(
|
| 803 |
+
path.join(testRootDir, 'first.txt'),
|
| 804 |
+
content1,
|
| 805 |
+
);
|
| 806 |
+
const content2 = 'Second file';
|
| 807 |
+
const file2Path = await createTestFile(
|
| 808 |
+
path.join(testRootDir, 'second.txt'),
|
| 809 |
+
content2,
|
| 810 |
+
);
|
| 811 |
+
const query = `Compare @${file1Path}, @${file2Path}; what's different?`;
|
| 812 |
+
|
| 813 |
+
const result = await handleAtCommand({
|
| 814 |
+
query,
|
| 815 |
+
config: mockConfig,
|
| 816 |
+
addItem: mockAddItem,
|
| 817 |
+
onDebugMessage: mockOnDebugMessage,
|
| 818 |
+
messageId: 411,
|
| 819 |
+
signal: abortController.signal,
|
| 820 |
+
});
|
| 821 |
+
|
| 822 |
+
expect(result).toEqual({
|
| 823 |
+
processedQuery: [
|
| 824 |
+
{ text: `Compare @${file1Path}, @${file2Path}; what's different?` },
|
| 825 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 826 |
+
{ text: `\nContent from @${file1Path}:\n` },
|
| 827 |
+
{ text: content1 },
|
| 828 |
+
{ text: `\nContent from @${file2Path}:\n` },
|
| 829 |
+
{ text: content2 },
|
| 830 |
+
{ text: '\n--- End of content ---' },
|
| 831 |
+
],
|
| 832 |
+
shouldProceed: true,
|
| 833 |
+
});
|
| 834 |
+
});
|
| 835 |
+
|
| 836 |
+
it('should still handle escaped spaces in paths before punctuation', async () => {
|
| 837 |
+
const fileContent = 'Spaced file content';
|
| 838 |
+
const filePath = await createTestFile(
|
| 839 |
+
path.join(testRootDir, 'spaced file.txt'),
|
| 840 |
+
fileContent,
|
| 841 |
+
);
|
| 842 |
+
const escapedPath = path.join(testRootDir, 'spaced\\ file.txt');
|
| 843 |
+
const query = `Check @${escapedPath}, it has spaces.`;
|
| 844 |
+
|
| 845 |
+
const result = await handleAtCommand({
|
| 846 |
+
query,
|
| 847 |
+
config: mockConfig,
|
| 848 |
+
addItem: mockAddItem,
|
| 849 |
+
onDebugMessage: mockOnDebugMessage,
|
| 850 |
+
messageId: 412,
|
| 851 |
+
signal: abortController.signal,
|
| 852 |
+
});
|
| 853 |
+
|
| 854 |
+
expect(result).toEqual({
|
| 855 |
+
processedQuery: [
|
| 856 |
+
{ text: `Check @${filePath}, it has spaces.` },
|
| 857 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 858 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 859 |
+
{ text: fileContent },
|
| 860 |
+
{ text: '\n--- End of content ---' },
|
| 861 |
+
],
|
| 862 |
+
shouldProceed: true,
|
| 863 |
+
});
|
| 864 |
+
});
|
| 865 |
+
|
| 866 |
+
it('should not break file paths with periods in extensions', async () => {
|
| 867 |
+
const fileContent = 'TypeScript content';
|
| 868 |
+
const filePath = await createTestFile(
|
| 869 |
+
path.join(testRootDir, 'example.d.ts'),
|
| 870 |
+
fileContent,
|
| 871 |
+
);
|
| 872 |
+
const query = `Analyze @${filePath} for type definitions.`;
|
| 873 |
+
|
| 874 |
+
const result = await handleAtCommand({
|
| 875 |
+
query,
|
| 876 |
+
config: mockConfig,
|
| 877 |
+
addItem: mockAddItem,
|
| 878 |
+
onDebugMessage: mockOnDebugMessage,
|
| 879 |
+
messageId: 413,
|
| 880 |
+
signal: abortController.signal,
|
| 881 |
+
});
|
| 882 |
+
|
| 883 |
+
expect(result).toEqual({
|
| 884 |
+
processedQuery: [
|
| 885 |
+
{ text: `Analyze @${filePath} for type definitions.` },
|
| 886 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 887 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 888 |
+
{ text: fileContent },
|
| 889 |
+
{ text: '\n--- End of content ---' },
|
| 890 |
+
],
|
| 891 |
+
shouldProceed: true,
|
| 892 |
+
});
|
| 893 |
+
});
|
| 894 |
+
|
| 895 |
+
it('should handle file paths ending with period followed by space', async () => {
|
| 896 |
+
const fileContent = 'Config content';
|
| 897 |
+
const filePath = await createTestFile(
|
| 898 |
+
path.join(testRootDir, 'config.json'),
|
| 899 |
+
fileContent,
|
| 900 |
+
);
|
| 901 |
+
const query = `Check @${filePath}. This file contains settings.`;
|
| 902 |
+
|
| 903 |
+
const result = await handleAtCommand({
|
| 904 |
+
query,
|
| 905 |
+
config: mockConfig,
|
| 906 |
+
addItem: mockAddItem,
|
| 907 |
+
onDebugMessage: mockOnDebugMessage,
|
| 908 |
+
messageId: 414,
|
| 909 |
+
signal: abortController.signal,
|
| 910 |
+
});
|
| 911 |
+
|
| 912 |
+
expect(result).toEqual({
|
| 913 |
+
processedQuery: [
|
| 914 |
+
{ text: `Check @${filePath}. This file contains settings.` },
|
| 915 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 916 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 917 |
+
{ text: fileContent },
|
| 918 |
+
{ text: '\n--- End of content ---' },
|
| 919 |
+
],
|
| 920 |
+
shouldProceed: true,
|
| 921 |
+
});
|
| 922 |
+
});
|
| 923 |
+
|
| 924 |
+
it('should handle comma termination with complex file paths', async () => {
|
| 925 |
+
const fileContent = 'Package info';
|
| 926 |
+
const filePath = await createTestFile(
|
| 927 |
+
path.join(testRootDir, 'package.json'),
|
| 928 |
+
fileContent,
|
| 929 |
+
);
|
| 930 |
+
const query = `Review @${filePath}, then check dependencies.`;
|
| 931 |
+
|
| 932 |
+
const result = await handleAtCommand({
|
| 933 |
+
query,
|
| 934 |
+
config: mockConfig,
|
| 935 |
+
addItem: mockAddItem,
|
| 936 |
+
onDebugMessage: mockOnDebugMessage,
|
| 937 |
+
messageId: 415,
|
| 938 |
+
signal: abortController.signal,
|
| 939 |
+
});
|
| 940 |
+
|
| 941 |
+
expect(result).toEqual({
|
| 942 |
+
processedQuery: [
|
| 943 |
+
{ text: `Review @${filePath}, then check dependencies.` },
|
| 944 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 945 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 946 |
+
{ text: fileContent },
|
| 947 |
+
{ text: '\n--- End of content ---' },
|
| 948 |
+
],
|
| 949 |
+
shouldProceed: true,
|
| 950 |
+
});
|
| 951 |
+
});
|
| 952 |
+
|
| 953 |
+
it('should not terminate at period within file name', async () => {
|
| 954 |
+
const fileContent = 'Version info';
|
| 955 |
+
const filePath = await createTestFile(
|
| 956 |
+
path.join(testRootDir, 'version.1.2.3.txt'),
|
| 957 |
+
fileContent,
|
| 958 |
+
);
|
| 959 |
+
const query = `Check @${filePath} contains version information.`;
|
| 960 |
+
|
| 961 |
+
const result = await handleAtCommand({
|
| 962 |
+
query,
|
| 963 |
+
config: mockConfig,
|
| 964 |
+
addItem: mockAddItem,
|
| 965 |
+
onDebugMessage: mockOnDebugMessage,
|
| 966 |
+
messageId: 416,
|
| 967 |
+
signal: abortController.signal,
|
| 968 |
+
});
|
| 969 |
+
|
| 970 |
+
expect(result).toEqual({
|
| 971 |
+
processedQuery: [
|
| 972 |
+
{ text: `Check @${filePath} contains version information.` },
|
| 973 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 974 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 975 |
+
{ text: fileContent },
|
| 976 |
+
{ text: '\n--- End of content ---' },
|
| 977 |
+
],
|
| 978 |
+
shouldProceed: true,
|
| 979 |
+
});
|
| 980 |
+
});
|
| 981 |
+
|
| 982 |
+
it('should handle end of string termination for period and comma', async () => {
|
| 983 |
+
const fileContent = 'End file content';
|
| 984 |
+
const filePath = await createTestFile(
|
| 985 |
+
path.join(testRootDir, 'end.txt'),
|
| 986 |
+
fileContent,
|
| 987 |
+
);
|
| 988 |
+
const query = `Show me @${filePath}.`;
|
| 989 |
+
|
| 990 |
+
const result = await handleAtCommand({
|
| 991 |
+
query,
|
| 992 |
+
config: mockConfig,
|
| 993 |
+
addItem: mockAddItem,
|
| 994 |
+
onDebugMessage: mockOnDebugMessage,
|
| 995 |
+
messageId: 417,
|
| 996 |
+
signal: abortController.signal,
|
| 997 |
+
});
|
| 998 |
+
|
| 999 |
+
expect(result).toEqual({
|
| 1000 |
+
processedQuery: [
|
| 1001 |
+
{ text: `Show me @${filePath}.` },
|
| 1002 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 1003 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 1004 |
+
{ text: fileContent },
|
| 1005 |
+
{ text: '\n--- End of content ---' },
|
| 1006 |
+
],
|
| 1007 |
+
shouldProceed: true,
|
| 1008 |
+
});
|
| 1009 |
+
});
|
| 1010 |
+
|
| 1011 |
+
it('should handle files with special characters in names', async () => {
|
| 1012 |
+
const fileContent = 'File with special chars content';
|
| 1013 |
+
const filePath = await createTestFile(
|
| 1014 |
+
path.join(testRootDir, 'file$with&special#chars.txt'),
|
| 1015 |
+
fileContent,
|
| 1016 |
+
);
|
| 1017 |
+
const query = `Check @${filePath} for content.`;
|
| 1018 |
+
|
| 1019 |
+
const result = await handleAtCommand({
|
| 1020 |
+
query,
|
| 1021 |
+
config: mockConfig,
|
| 1022 |
+
addItem: mockAddItem,
|
| 1023 |
+
onDebugMessage: mockOnDebugMessage,
|
| 1024 |
+
messageId: 418,
|
| 1025 |
+
signal: abortController.signal,
|
| 1026 |
+
});
|
| 1027 |
+
|
| 1028 |
+
expect(result).toEqual({
|
| 1029 |
+
processedQuery: [
|
| 1030 |
+
{ text: `Check @${filePath} for content.` },
|
| 1031 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 1032 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 1033 |
+
{ text: fileContent },
|
| 1034 |
+
{ text: '\n--- End of content ---' },
|
| 1035 |
+
],
|
| 1036 |
+
shouldProceed: true,
|
| 1037 |
+
});
|
| 1038 |
+
});
|
| 1039 |
+
|
| 1040 |
+
it('should handle basic file names without special characters', async () => {
|
| 1041 |
+
const fileContent = 'Basic file content';
|
| 1042 |
+
const filePath = await createTestFile(
|
| 1043 |
+
path.join(testRootDir, 'basicfile.txt'),
|
| 1044 |
+
fileContent,
|
| 1045 |
+
);
|
| 1046 |
+
const query = `Check @${filePath} please.`;
|
| 1047 |
+
|
| 1048 |
+
const result = await handleAtCommand({
|
| 1049 |
+
query,
|
| 1050 |
+
config: mockConfig,
|
| 1051 |
+
addItem: mockAddItem,
|
| 1052 |
+
onDebugMessage: mockOnDebugMessage,
|
| 1053 |
+
messageId: 421,
|
| 1054 |
+
signal: abortController.signal,
|
| 1055 |
+
});
|
| 1056 |
+
|
| 1057 |
+
expect(result).toEqual({
|
| 1058 |
+
processedQuery: [
|
| 1059 |
+
{ text: `Check @${filePath} please.` },
|
| 1060 |
+
{ text: '\n--- Content from referenced files ---' },
|
| 1061 |
+
{ text: `\nContent from @${filePath}:\n` },
|
| 1062 |
+
{ text: fileContent },
|
| 1063 |
+
{ text: '\n--- End of content ---' },
|
| 1064 |
+
],
|
| 1065 |
+
shouldProceed: true,
|
| 1066 |
+
});
|
| 1067 |
+
});
|
| 1068 |
+
});
|
| 1069 |
+
|
| 1070 |
+
it("should not add the user's turn to history, as that is the caller's responsibility", async () => {
|
| 1071 |
+
// Arrange
|
| 1072 |
+
const fileContent = 'This is the file content.';
|
| 1073 |
+
const filePath = await createTestFile(
|
| 1074 |
+
path.join(testRootDir, 'path', 'to', 'another-file.txt'),
|
| 1075 |
+
fileContent,
|
| 1076 |
+
);
|
| 1077 |
+
const query = `A query with @${filePath}`;
|
| 1078 |
+
|
| 1079 |
+
// Act
|
| 1080 |
+
await handleAtCommand({
|
| 1081 |
+
query,
|
| 1082 |
+
config: mockConfig,
|
| 1083 |
+
addItem: mockAddItem,
|
| 1084 |
+
onDebugMessage: mockOnDebugMessage,
|
| 1085 |
+
messageId: 999,
|
| 1086 |
+
signal: abortController.signal,
|
| 1087 |
+
});
|
| 1088 |
+
|
| 1089 |
+
// Assert
|
| 1090 |
+
// It SHOULD be called for the tool_group
|
| 1091 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 1092 |
+
expect.objectContaining({ type: 'tool_group' }),
|
| 1093 |
+
999,
|
| 1094 |
+
);
|
| 1095 |
+
|
| 1096 |
+
// It should NOT have been called for the user turn
|
| 1097 |
+
const userTurnCalls = mockAddItem.mock.calls.filter(
|
| 1098 |
+
(call) => call[0].type === 'user',
|
| 1099 |
+
);
|
| 1100 |
+
expect(userTurnCalls).toHaveLength(0);
|
| 1101 |
+
});
|
| 1102 |
+
});
|
projects/ui/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6 |
+
|
| 7 |
+
import * as fs from 'fs/promises';
|
| 8 |
+
import * as path from 'path';
|
| 9 |
+
import { PartListUnion, PartUnion } from '@google/genai';
|
| 10 |
+
import {
|
| 11 |
+
AnyToolInvocation,
|
| 12 |
+
Config,
|
| 13 |
+
getErrorMessage,
|
| 14 |
+
isNodeError,
|
| 15 |
+
unescapePath,
|
| 16 |
+
} from '@qwen-code/qwen-code-core';
|
| 17 |
+
import {
|
| 18 |
+
HistoryItem,
|
| 19 |
+
IndividualToolCallDisplay,
|
| 20 |
+
ToolCallStatus,
|
| 21 |
+
} from '../types.js';
|
| 22 |
+
import { UseHistoryManagerReturn } from './useHistoryManager.js';
|
| 23 |
+
|
| 24 |
+
interface HandleAtCommandParams {
|
| 25 |
+
query: string;
|
| 26 |
+
config: Config;
|
| 27 |
+
addItem: UseHistoryManagerReturn['addItem'];
|
| 28 |
+
onDebugMessage: (message: string) => void;
|
| 29 |
+
messageId: number;
|
| 30 |
+
signal: AbortSignal;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
interface HandleAtCommandResult {
|
| 34 |
+
processedQuery: PartListUnion | null;
|
| 35 |
+
shouldProceed: boolean;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
interface AtCommandPart {
|
| 39 |
+
type: 'text' | 'atPath';
|
| 40 |
+
content: string;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/**
|
| 44 |
+
* Parses a query string to find all '@<path>' commands and text segments.
|
| 45 |
+
* Handles \ escaped spaces within paths.
|
| 46 |
+
*/
|
| 47 |
+
function parseAllAtCommands(query: string): AtCommandPart[] {
|
| 48 |
+
const parts: AtCommandPart[] = [];
|
| 49 |
+
let currentIndex = 0;
|
| 50 |
+
|
| 51 |
+
while (currentIndex < query.length) {
|
| 52 |
+
let atIndex = -1;
|
| 53 |
+
let nextSearchIndex = currentIndex;
|
| 54 |
+
// Find next unescaped '@'
|
| 55 |
+
while (nextSearchIndex < query.length) {
|
| 56 |
+
if (
|
| 57 |
+
query[nextSearchIndex] === '@' &&
|
| 58 |
+
(nextSearchIndex === 0 || query[nextSearchIndex - 1] !== '\\')
|
| 59 |
+
) {
|
| 60 |
+
atIndex = nextSearchIndex;
|
| 61 |
+
break;
|
| 62 |
+
}
|
| 63 |
+
nextSearchIndex++;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
if (atIndex === -1) {
|
| 67 |
+
// No more @
|
| 68 |
+
if (currentIndex < query.length) {
|
| 69 |
+
parts.push({ type: 'text', content: query.substring(currentIndex) });
|
| 70 |
+
}
|
| 71 |
+
break;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// Add text before @
|
| 75 |
+
if (atIndex > currentIndex) {
|
| 76 |
+
parts.push({
|
| 77 |
+
type: 'text',
|
| 78 |
+
content: query.substring(currentIndex, atIndex),
|
| 79 |
+
});
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// Parse @path
|
| 83 |
+
let pathEndIndex = atIndex + 1;
|
| 84 |
+
let inEscape = false;
|
| 85 |
+
while (pathEndIndex < query.length) {
|
| 86 |
+
const char = query[pathEndIndex];
|
| 87 |
+
if (inEscape) {
|
| 88 |
+
inEscape = false;
|
| 89 |
+
} else if (char === '\\') {
|
| 90 |
+
inEscape = true;
|
| 91 |
+
} else if (/[,\s;!?()[\]{}]/.test(char)) {
|
| 92 |
+
// Path ends at first whitespace or punctuation not escaped
|
| 93 |
+
break;
|
| 94 |
+
} else if (char === '.') {
|
| 95 |
+
// For . we need to be more careful - only terminate if followed by whitespace or end of string
|
| 96 |
+
// This allows file extensions like .txt, .js but terminates at sentence endings like "file.txt. Next sentence"
|
| 97 |
+
const nextChar =
|
| 98 |
+
pathEndIndex + 1 < query.length ? query[pathEndIndex + 1] : '';
|
| 99 |
+
if (nextChar === '' || /\s/.test(nextChar)) {
|
| 100 |
+
break;
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
pathEndIndex++;
|
| 104 |
+
}
|
| 105 |
+
const rawAtPath = query.substring(atIndex, pathEndIndex);
|
| 106 |
+
// unescapePath expects the @ symbol to be present, and will handle it.
|
| 107 |
+
const atPath = unescapePath(rawAtPath);
|
| 108 |
+
parts.push({ type: 'atPath', content: atPath });
|
| 109 |
+
currentIndex = pathEndIndex;
|
| 110 |
+
}
|
| 111 |
+
// Filter out empty text parts that might result from consecutive @paths or leading/trailing spaces
|
| 112 |
+
return parts.filter(
|
| 113 |
+
(part) => !(part.type === 'text' && part.content.trim() === ''),
|
| 114 |
+
);
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
/**
|
| 118 |
+
* Processes user input potentially containing one or more '@<path>' commands.
|
| 119 |
+
* If found, it attempts to read the specified files/directories using the
|
| 120 |
+
* 'read_many_files' tool. The user query is modified to include resolved paths,
|
| 121 |
+
* and the content of the files is appended in a structured block.
|
| 122 |
+
*
|
| 123 |
+
* @returns An object indicating whether the main hook should proceed with an
|
| 124 |
+
* LLM call and the processed query parts (including file content).
|
| 125 |
+
*/
|
| 126 |
+
export async function handleAtCommand({
|
| 127 |
+
query,
|
| 128 |
+
config,
|
| 129 |
+
addItem,
|
| 130 |
+
onDebugMessage,
|
| 131 |
+
messageId: userMessageTimestamp,
|
| 132 |
+
signal,
|
| 133 |
+
}: HandleAtCommandParams): Promise<HandleAtCommandResult> {
|
| 134 |
+
const commandParts = parseAllAtCommands(query);
|
| 135 |
+
const atPathCommandParts = commandParts.filter(
|
| 136 |
+
(part) => part.type === 'atPath',
|
| 137 |
+
);
|
| 138 |
+
|
| 139 |
+
if (atPathCommandParts.length === 0) {
|
| 140 |
+
return { processedQuery: [{ text: query }], shouldProceed: true };
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
// Get centralized file discovery service
|
| 144 |
+
const fileDiscovery = config.getFileService();
|
| 145 |
+
|
| 146 |
+
const respectFileIgnore = config.getFileFilteringOptions();
|
| 147 |
+
|
| 148 |
+
const pathSpecsToRead: string[] = [];
|
| 149 |
+
const atPathToResolvedSpecMap = new Map<string, string>();
|
| 150 |
+
const contentLabelsForDisplay: string[] = [];
|
| 151 |
+
const ignoredByReason: Record<string, string[]> = {
|
| 152 |
+
git: [],
|
| 153 |
+
gemini: [],
|
| 154 |
+
both: [],
|
| 155 |
+
};
|
| 156 |
+
|
| 157 |
+
const toolRegistry = config.getToolRegistry();
|
| 158 |
+
const readManyFilesTool = toolRegistry.getTool('read_many_files');
|
| 159 |
+
const globTool = toolRegistry.getTool('glob');
|
| 160 |
+
|
| 161 |
+
if (!readManyFilesTool) {
|
| 162 |
+
addItem(
|
| 163 |
+
{ type: 'error', text: 'Error: read_many_files tool not found.' },
|
| 164 |
+
userMessageTimestamp,
|
| 165 |
+
);
|
| 166 |
+
return { processedQuery: null, shouldProceed: false };
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
for (const atPathPart of atPathCommandParts) {
|
| 170 |
+
const originalAtPath = atPathPart.content; // e.g., "@file.txt" or "@"
|
| 171 |
+
|
| 172 |
+
if (originalAtPath === '@') {
|
| 173 |
+
onDebugMessage(
|
| 174 |
+
'Lone @ detected, will be treated as text in the modified query.',
|
| 175 |
+
);
|
| 176 |
+
continue;
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
const pathName = originalAtPath.substring(1);
|
| 180 |
+
if (!pathName) {
|
| 181 |
+
// This case should ideally not be hit if parseAllAtCommands ensures content after @
|
| 182 |
+
// but as a safeguard:
|
| 183 |
+
addItem(
|
| 184 |
+
{
|
| 185 |
+
type: 'error',
|
| 186 |
+
text: `Error: Invalid @ command '${originalAtPath}'. No path specified.`,
|
| 187 |
+
},
|
| 188 |
+
userMessageTimestamp,
|
| 189 |
+
);
|
| 190 |
+
// Decide if this is a fatal error for the whole command or just skip this @ part
|
| 191 |
+
// For now, let's be strict and fail the command if one @path is malformed.
|
| 192 |
+
return { processedQuery: null, shouldProceed: false };
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// Check if path should be ignored based on filtering options
|
| 196 |
+
|
| 197 |
+
const workspaceContext = config.getWorkspaceContext();
|
| 198 |
+
if (!workspaceContext.isPathWithinWorkspace(pathName)) {
|
| 199 |
+
onDebugMessage(
|
| 200 |
+
`Path ${pathName} is not in the workspace and will be skipped.`,
|
| 201 |
+
);
|
| 202 |
+
continue;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
const gitIgnored =
|
| 206 |
+
respectFileIgnore.respectGitIgnore &&
|
| 207 |
+
fileDiscovery.shouldIgnoreFile(pathName, {
|
| 208 |
+
respectGitIgnore: true,
|
| 209 |
+
respectGeminiIgnore: false,
|
| 210 |
+
});
|
| 211 |
+
const geminiIgnored =
|
| 212 |
+
respectFileIgnore.respectGeminiIgnore &&
|
| 213 |
+
fileDiscovery.shouldIgnoreFile(pathName, {
|
| 214 |
+
respectGitIgnore: false,
|
| 215 |
+
respectGeminiIgnore: true,
|
| 216 |
+
});
|
| 217 |
+
|
| 218 |
+
if (gitIgnored || geminiIgnored) {
|
| 219 |
+
const reason =
|
| 220 |
+
gitIgnored && geminiIgnored ? 'both' : gitIgnored ? 'git' : 'gemini';
|
| 221 |
+
ignoredByReason[reason].push(pathName);
|
| 222 |
+
const reasonText =
|
| 223 |
+
reason === 'both'
|
| 224 |
+
? 'ignored by both git and gemini'
|
| 225 |
+
: reason === 'git'
|
| 226 |
+
? 'git-ignored'
|
| 227 |
+
: 'gemini-ignored';
|
| 228 |
+
onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);
|
| 229 |
+
continue;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
for (const dir of config.getWorkspaceContext().getDirectories()) {
|
| 233 |
+
let currentPathSpec = pathName;
|
| 234 |
+
let resolvedSuccessfully = false;
|
| 235 |
+
try {
|
| 236 |
+
const absolutePath = path.resolve(dir, pathName);
|
| 237 |
+
const stats = await fs.stat(absolutePath);
|
| 238 |
+
if (stats.isDirectory()) {
|
| 239 |
+
currentPathSpec =
|
| 240 |
+
pathName + (pathName.endsWith(path.sep) ? `**` : `/**`);
|
| 241 |
+
onDebugMessage(
|
| 242 |
+
`Path ${pathName} resolved to directory, using glob: ${currentPathSpec}`,
|
| 243 |
+
);
|
| 244 |
+
} else {
|
| 245 |
+
onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`);
|
| 246 |
+
}
|
| 247 |
+
resolvedSuccessfully = true;
|
| 248 |
+
} catch (error) {
|
| 249 |
+
if (isNodeError(error) && error.code === 'ENOENT') {
|
| 250 |
+
if (config.getEnableRecursiveFileSearch() && globTool) {
|
| 251 |
+
onDebugMessage(
|
| 252 |
+
`Path ${pathName} not found directly, attempting glob search.`,
|
| 253 |
+
);
|
| 254 |
+
try {
|
| 255 |
+
const globResult = await globTool.buildAndExecute(
|
| 256 |
+
{
|
| 257 |
+
pattern: `**/*${pathName}*`,
|
| 258 |
+
path: dir,
|
| 259 |
+
},
|
| 260 |
+
signal,
|
| 261 |
+
);
|
| 262 |
+
if (
|
| 263 |
+
globResult.llmContent &&
|
| 264 |
+
typeof globResult.llmContent === 'string' &&
|
| 265 |
+
!globResult.llmContent.startsWith('No files found') &&
|
| 266 |
+
!globResult.llmContent.startsWith('Error:')
|
| 267 |
+
) {
|
| 268 |
+
const lines = globResult.llmContent.split('\n');
|
| 269 |
+
if (lines.length > 1 && lines[1]) {
|
| 270 |
+
const firstMatchAbsolute = lines[1].trim();
|
| 271 |
+
currentPathSpec = path.relative(dir, firstMatchAbsolute);
|
| 272 |
+
onDebugMessage(
|
| 273 |
+
`Glob search for ${pathName} found ${firstMatchAbsolute}, using relative path: ${currentPathSpec}`,
|
| 274 |
+
);
|
| 275 |
+
resolvedSuccessfully = true;
|
| 276 |
+
} else {
|
| 277 |
+
onDebugMessage(
|
| 278 |
+
`Glob search for '**/*${pathName}*' did not return a usable path. Path ${pathName} will be skipped.`,
|
| 279 |
+
);
|
| 280 |
+
}
|
| 281 |
+
} else {
|
| 282 |
+
onDebugMessage(
|
| 283 |
+
`Glob search for '**/*${pathName}*' found no files or an error. Path ${pathName} will be skipped.`,
|
| 284 |
+
);
|
| 285 |
+
}
|
| 286 |
+
} catch (globError) {
|
| 287 |
+
console.error(
|
| 288 |
+
`Error during glob search for ${pathName}: ${getErrorMessage(globError)}`,
|
| 289 |
+
);
|
| 290 |
+
onDebugMessage(
|
| 291 |
+
`Error during glob search for ${pathName}. Path ${pathName} will be skipped.`,
|
| 292 |
+
);
|
| 293 |
+
}
|
| 294 |
+
} else {
|
| 295 |
+
onDebugMessage(
|
| 296 |
+
`Glob tool not found. Path ${pathName} will be skipped.`,
|
| 297 |
+
);
|
| 298 |
+
}
|
| 299 |
+
} else {
|
| 300 |
+
console.error(
|
| 301 |
+
`Error stating path ${pathName}: ${getErrorMessage(error)}`,
|
| 302 |
+
);
|
| 303 |
+
onDebugMessage(
|
| 304 |
+
`Error stating path ${pathName}. Path ${pathName} will be skipped.`,
|
| 305 |
+
);
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
if (resolvedSuccessfully) {
|
| 309 |
+
pathSpecsToRead.push(currentPathSpec);
|
| 310 |
+
atPathToResolvedSpecMap.set(originalAtPath, currentPathSpec);
|
| 311 |
+
contentLabelsForDisplay.push(pathName);
|
| 312 |
+
break;
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
// Construct the initial part of the query for the LLM
|
| 318 |
+
let initialQueryText = '';
|
| 319 |
+
for (let i = 0; i < commandParts.length; i++) {
|
| 320 |
+
const part = commandParts[i];
|
| 321 |
+
if (part.type === 'text') {
|
| 322 |
+
initialQueryText += part.content;
|
| 323 |
+
} else {
|
| 324 |
+
// type === 'atPath'
|
| 325 |
+
const resolvedSpec = atPathToResolvedSpecMap.get(part.content);
|
| 326 |
+
if (
|
| 327 |
+
i > 0 &&
|
| 328 |
+
initialQueryText.length > 0 &&
|
| 329 |
+
!initialQueryText.endsWith(' ')
|
| 330 |
+
) {
|
| 331 |
+
// Add space if previous part was text and didn't end with space, or if previous was @path
|
| 332 |
+
const prevPart = commandParts[i - 1];
|
| 333 |
+
if (
|
| 334 |
+
prevPart.type === 'text' ||
|
| 335 |
+
(prevPart.type === 'atPath' &&
|
| 336 |
+
atPathToResolvedSpecMap.has(prevPart.content))
|
| 337 |
+
) {
|
| 338 |
+
initialQueryText += ' ';
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
if (resolvedSpec) {
|
| 342 |
+
initialQueryText += `@${resolvedSpec}`;
|
| 343 |
+
} else {
|
| 344 |
+
// If not resolved for reading (e.g. lone @ or invalid path that was skipped),
|
| 345 |
+
// add the original @-string back, ensuring spacing if it's not the first element.
|
| 346 |
+
if (
|
| 347 |
+
i > 0 &&
|
| 348 |
+
initialQueryText.length > 0 &&
|
| 349 |
+
!initialQueryText.endsWith(' ') &&
|
| 350 |
+
!part.content.startsWith(' ')
|
| 351 |
+
) {
|
| 352 |
+
initialQueryText += ' ';
|
| 353 |
+
}
|
| 354 |
+
initialQueryText += part.content;
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
initialQueryText = initialQueryText.trim();
|
| 359 |
+
|
| 360 |
+
// Inform user about ignored paths
|
| 361 |
+
const totalIgnored =
|
| 362 |
+
ignoredByReason['git'].length +
|
| 363 |
+
ignoredByReason['gemini'].length +
|
| 364 |
+
ignoredByReason['both'].length;
|
| 365 |
+
|
| 366 |
+
if (totalIgnored > 0) {
|
| 367 |
+
const messages = [];
|
| 368 |
+
if (ignoredByReason['git'].length) {
|
| 369 |
+
messages.push(`Git-ignored: ${ignoredByReason['git'].join(', ')}`);
|
| 370 |
+
}
|
| 371 |
+
if (ignoredByReason['gemini'].length) {
|
| 372 |
+
messages.push(`Gemini-ignored: ${ignoredByReason['gemini'].join(', ')}`);
|
| 373 |
+
}
|
| 374 |
+
if (ignoredByReason['both'].length) {
|
| 375 |
+
messages.push(`Ignored by both: ${ignoredByReason['both'].join(', ')}`);
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
const message = `Ignored ${totalIgnored} files:\n${messages.join('\n')}`;
|
| 379 |
+
console.log(message);
|
| 380 |
+
onDebugMessage(message);
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
// Fallback for lone "@" or completely invalid @-commands resulting in empty initialQueryText
|
| 384 |
+
if (pathSpecsToRead.length === 0) {
|
| 385 |
+
onDebugMessage('No valid file paths found in @ commands to read.');
|
| 386 |
+
if (initialQueryText === '@' && query.trim() === '@') {
|
| 387 |
+
// If the only thing was a lone @, pass original query (which might have spaces)
|
| 388 |
+
return { processedQuery: [{ text: query }], shouldProceed: true };
|
| 389 |
+
} else if (!initialQueryText && query) {
|
| 390 |
+
// If all @-commands were invalid and no surrounding text, pass original query
|
| 391 |
+
return { processedQuery: [{ text: query }], shouldProceed: true };
|
| 392 |
+
}
|
| 393 |
+
// Otherwise, proceed with the (potentially modified) query text that doesn't involve file reading
|
| 394 |
+
return {
|
| 395 |
+
processedQuery: [{ text: initialQueryText || query }],
|
| 396 |
+
shouldProceed: true,
|
| 397 |
+
};
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
const processedQueryParts: PartUnion[] = [{ text: initialQueryText }];
|
| 401 |
+
|
| 402 |
+
const toolArgs = {
|
| 403 |
+
paths: pathSpecsToRead,
|
| 404 |
+
file_filtering_options: {
|
| 405 |
+
respect_git_ignore: respectFileIgnore.respectGitIgnore,
|
| 406 |
+
respect_gemini_ignore: respectFileIgnore.respectGeminiIgnore,
|
| 407 |
+
},
|
| 408 |
+
// Use configuration setting
|
| 409 |
+
};
|
| 410 |
+
let toolCallDisplay: IndividualToolCallDisplay;
|
| 411 |
+
|
| 412 |
+
let invocation: AnyToolInvocation | undefined = undefined;
|
| 413 |
+
try {
|
| 414 |
+
invocation = readManyFilesTool.build(toolArgs);
|
| 415 |
+
const result = await invocation.execute(signal);
|
| 416 |
+
toolCallDisplay = {
|
| 417 |
+
callId: `client-read-${userMessageTimestamp}`,
|
| 418 |
+
name: readManyFilesTool.displayName,
|
| 419 |
+
description: invocation.getDescription(),
|
| 420 |
+
status: ToolCallStatus.Success,
|
| 421 |
+
resultDisplay:
|
| 422 |
+
result.returnDisplay ||
|
| 423 |
+
`Successfully read: ${contentLabelsForDisplay.join(', ')}`,
|
| 424 |
+
confirmationDetails: undefined,
|
| 425 |
+
};
|
| 426 |
+
|
| 427 |
+
if (Array.isArray(result.llmContent)) {
|
| 428 |
+
const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;
|
| 429 |
+
processedQueryParts.push({
|
| 430 |
+
text: '\n--- Content from referenced files ---',
|
| 431 |
+
});
|
| 432 |
+
for (const part of result.llmContent) {
|
| 433 |
+
if (typeof part === 'string') {
|
| 434 |
+
const match = fileContentRegex.exec(part);
|
| 435 |
+
if (match) {
|
| 436 |
+
const filePathSpecInContent = match[1]; // This is a resolved pathSpec
|
| 437 |
+
const fileActualContent = match[2].trim();
|
| 438 |
+
processedQueryParts.push({
|
| 439 |
+
text: `\nContent from @${filePathSpecInContent}:\n`,
|
| 440 |
+
});
|
| 441 |
+
processedQueryParts.push({ text: fileActualContent });
|
| 442 |
+
} else {
|
| 443 |
+
processedQueryParts.push({ text: part });
|
| 444 |
+
}
|
| 445 |
+
} else {
|
| 446 |
+
// part is a Part object.
|
| 447 |
+
processedQueryParts.push(part);
|
| 448 |
+
}
|
| 449 |
+
}
|
| 450 |
+
processedQueryParts.push({ text: '\n--- End of content ---' });
|
| 451 |
+
} else {
|
| 452 |
+
onDebugMessage(
|
| 453 |
+
'read_many_files tool returned no content or empty content.',
|
| 454 |
+
);
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
addItem(
|
| 458 |
+
{ type: 'tool_group', tools: [toolCallDisplay] } as Omit<
|
| 459 |
+
HistoryItem,
|
| 460 |
+
'id'
|
| 461 |
+
>,
|
| 462 |
+
userMessageTimestamp,
|
| 463 |
+
);
|
| 464 |
+
return { processedQuery: processedQueryParts, shouldProceed: true };
|
| 465 |
+
} catch (error: unknown) {
|
| 466 |
+
toolCallDisplay = {
|
| 467 |
+
callId: `client-read-${userMessageTimestamp}`,
|
| 468 |
+
name: readManyFilesTool.displayName,
|
| 469 |
+
description:
|
| 470 |
+
invocation?.getDescription() ??
|
| 471 |
+
'Error attempting to execute tool to read files',
|
| 472 |
+
status: ToolCallStatus.Error,
|
| 473 |
+
resultDisplay: `Error reading files (${contentLabelsForDisplay.join(', ')}): ${getErrorMessage(error)}`,
|
| 474 |
+
confirmationDetails: undefined,
|
| 475 |
+
};
|
| 476 |
+
addItem(
|
| 477 |
+
{ type: 'tool_group', tools: [toolCallDisplay] } as Omit<
|
| 478 |
+
HistoryItem,
|
| 479 |
+
'id'
|
| 480 |
+
>,
|
| 481 |
+
userMessageTimestamp,
|
| 482 |
+
);
|
| 483 |
+
return { processedQuery: null, shouldProceed: false };
|
| 484 |
+
}
|
| 485 |
+
}
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/shellCommandProcessor.test.ts
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { act, renderHook } from '@testing-library/react';
|
| 8 |
+
import {
|
| 9 |
+
vi,
|
| 10 |
+
describe,
|
| 11 |
+
it,
|
| 12 |
+
expect,
|
| 13 |
+
beforeEach,
|
| 14 |
+
afterEach,
|
| 15 |
+
type Mock,
|
| 16 |
+
} from 'vitest';
|
| 17 |
+
|
| 18 |
+
const mockIsBinary = vi.hoisted(() => vi.fn());
|
| 19 |
+
const mockShellExecutionService = vi.hoisted(() => vi.fn());
|
| 20 |
+
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
|
| 21 |
+
const original =
|
| 22 |
+
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
|
| 23 |
+
return {
|
| 24 |
+
...original,
|
| 25 |
+
ShellExecutionService: { execute: mockShellExecutionService },
|
| 26 |
+
isBinary: mockIsBinary,
|
| 27 |
+
};
|
| 28 |
+
});
|
| 29 |
+
vi.mock('fs');
|
| 30 |
+
vi.mock('os');
|
| 31 |
+
vi.mock('crypto');
|
| 32 |
+
vi.mock('../utils/textUtils.js');
|
| 33 |
+
|
| 34 |
+
import {
|
| 35 |
+
useShellCommandProcessor,
|
| 36 |
+
OUTPUT_UPDATE_INTERVAL_MS,
|
| 37 |
+
} from './shellCommandProcessor.js';
|
| 38 |
+
import {
|
| 39 |
+
type Config,
|
| 40 |
+
type GeminiClient,
|
| 41 |
+
type ShellExecutionResult,
|
| 42 |
+
type ShellOutputEvent,
|
| 43 |
+
} from '@qwen-code/qwen-code-core';
|
| 44 |
+
import * as fs from 'fs';
|
| 45 |
+
import * as os from 'os';
|
| 46 |
+
import * as path from 'path';
|
| 47 |
+
import * as crypto from 'crypto';
|
| 48 |
+
import { ToolCallStatus } from '../types.js';
|
| 49 |
+
|
| 50 |
+
describe('useShellCommandProcessor', () => {
|
| 51 |
+
let addItemToHistoryMock: Mock;
|
| 52 |
+
let setPendingHistoryItemMock: Mock;
|
| 53 |
+
let onExecMock: Mock;
|
| 54 |
+
let onDebugMessageMock: Mock;
|
| 55 |
+
let mockConfig: Config;
|
| 56 |
+
let mockGeminiClient: GeminiClient;
|
| 57 |
+
|
| 58 |
+
let mockShellOutputCallback: (event: ShellOutputEvent) => void;
|
| 59 |
+
let resolveExecutionPromise: (result: ShellExecutionResult) => void;
|
| 60 |
+
|
| 61 |
+
beforeEach(() => {
|
| 62 |
+
vi.clearAllMocks();
|
| 63 |
+
|
| 64 |
+
addItemToHistoryMock = vi.fn();
|
| 65 |
+
setPendingHistoryItemMock = vi.fn();
|
| 66 |
+
onExecMock = vi.fn();
|
| 67 |
+
onDebugMessageMock = vi.fn();
|
| 68 |
+
mockConfig = {
|
| 69 |
+
getTargetDir: () => '/test/dir',
|
| 70 |
+
getShouldUseNodePtyShell: () => false,
|
| 71 |
+
} as Config;
|
| 72 |
+
mockGeminiClient = { addHistory: vi.fn() } as unknown as GeminiClient;
|
| 73 |
+
|
| 74 |
+
vi.mocked(os.platform).mockReturnValue('linux');
|
| 75 |
+
vi.mocked(os.tmpdir).mockReturnValue('/tmp');
|
| 76 |
+
(vi.mocked(crypto.randomBytes) as Mock).mockReturnValue(
|
| 77 |
+
Buffer.from('abcdef', 'hex'),
|
| 78 |
+
);
|
| 79 |
+
mockIsBinary.mockReturnValue(false);
|
| 80 |
+
vi.mocked(fs.existsSync).mockReturnValue(false);
|
| 81 |
+
|
| 82 |
+
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
|
| 83 |
+
mockShellOutputCallback = callback;
|
| 84 |
+
return {
|
| 85 |
+
pid: 12345,
|
| 86 |
+
result: new Promise((resolve) => {
|
| 87 |
+
resolveExecutionPromise = resolve;
|
| 88 |
+
}),
|
| 89 |
+
};
|
| 90 |
+
});
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
const renderProcessorHook = () =>
|
| 94 |
+
renderHook(() =>
|
| 95 |
+
useShellCommandProcessor(
|
| 96 |
+
addItemToHistoryMock,
|
| 97 |
+
setPendingHistoryItemMock,
|
| 98 |
+
onExecMock,
|
| 99 |
+
onDebugMessageMock,
|
| 100 |
+
mockConfig,
|
| 101 |
+
mockGeminiClient,
|
| 102 |
+
),
|
| 103 |
+
);
|
| 104 |
+
|
| 105 |
+
const createMockServiceResult = (
|
| 106 |
+
overrides: Partial<ShellExecutionResult> = {},
|
| 107 |
+
): ShellExecutionResult => ({
|
| 108 |
+
rawOutput: Buffer.from(overrides.output || ''),
|
| 109 |
+
output: 'Success',
|
| 110 |
+
exitCode: 0,
|
| 111 |
+
signal: null,
|
| 112 |
+
error: null,
|
| 113 |
+
aborted: false,
|
| 114 |
+
pid: 12345,
|
| 115 |
+
executionMethod: 'child_process',
|
| 116 |
+
...overrides,
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it('should initiate command execution and set pending state', async () => {
|
| 120 |
+
const { result } = renderProcessorHook();
|
| 121 |
+
|
| 122 |
+
act(() => {
|
| 123 |
+
result.current.handleShellCommand('ls -l', new AbortController().signal);
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
expect(addItemToHistoryMock).toHaveBeenCalledWith(
|
| 127 |
+
{ type: 'user_shell', text: 'ls -l' },
|
| 128 |
+
expect.any(Number),
|
| 129 |
+
);
|
| 130 |
+
expect(setPendingHistoryItemMock).toHaveBeenCalledWith({
|
| 131 |
+
type: 'tool_group',
|
| 132 |
+
tools: [
|
| 133 |
+
expect.objectContaining({
|
| 134 |
+
name: 'Shell Command',
|
| 135 |
+
status: ToolCallStatus.Executing,
|
| 136 |
+
}),
|
| 137 |
+
],
|
| 138 |
+
});
|
| 139 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
|
| 140 |
+
const wrappedCommand = `{ ls -l; }; __code=$?; pwd > "${tmpFile}"; exit $__code`;
|
| 141 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 142 |
+
wrappedCommand,
|
| 143 |
+
'/test/dir',
|
| 144 |
+
expect.any(Function),
|
| 145 |
+
expect.any(Object),
|
| 146 |
+
false,
|
| 147 |
+
);
|
| 148 |
+
expect(onExecMock).toHaveBeenCalledWith(expect.any(Promise));
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
it('should handle successful execution and update history correctly', async () => {
|
| 152 |
+
const { result } = renderProcessorHook();
|
| 153 |
+
|
| 154 |
+
act(() => {
|
| 155 |
+
result.current.handleShellCommand(
|
| 156 |
+
'echo "ok"',
|
| 157 |
+
new AbortController().signal,
|
| 158 |
+
);
|
| 159 |
+
});
|
| 160 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 161 |
+
|
| 162 |
+
act(() => {
|
| 163 |
+
resolveExecutionPromise(createMockServiceResult({ output: 'ok' }));
|
| 164 |
+
});
|
| 165 |
+
await act(async () => await execPromise);
|
| 166 |
+
|
| 167 |
+
expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
|
| 168 |
+
expect(addItemToHistoryMock).toHaveBeenCalledTimes(2); // Initial + final
|
| 169 |
+
expect(addItemToHistoryMock.mock.calls[1][0]).toEqual(
|
| 170 |
+
expect.objectContaining({
|
| 171 |
+
tools: [
|
| 172 |
+
expect.objectContaining({
|
| 173 |
+
status: ToolCallStatus.Success,
|
| 174 |
+
resultDisplay: 'ok',
|
| 175 |
+
}),
|
| 176 |
+
],
|
| 177 |
+
}),
|
| 178 |
+
);
|
| 179 |
+
expect(mockGeminiClient.addHistory).toHaveBeenCalled();
|
| 180 |
+
});
|
| 181 |
+
|
| 182 |
+
it('should handle command failure and display error status', async () => {
|
| 183 |
+
const { result } = renderProcessorHook();
|
| 184 |
+
|
| 185 |
+
act(() => {
|
| 186 |
+
result.current.handleShellCommand(
|
| 187 |
+
'bad-cmd',
|
| 188 |
+
new AbortController().signal,
|
| 189 |
+
);
|
| 190 |
+
});
|
| 191 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 192 |
+
|
| 193 |
+
act(() => {
|
| 194 |
+
resolveExecutionPromise(
|
| 195 |
+
createMockServiceResult({ exitCode: 127, output: 'not found' }),
|
| 196 |
+
);
|
| 197 |
+
});
|
| 198 |
+
await act(async () => await execPromise);
|
| 199 |
+
|
| 200 |
+
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
|
| 201 |
+
expect(finalHistoryItem.tools[0].status).toBe(ToolCallStatus.Error);
|
| 202 |
+
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
|
| 203 |
+
'Command exited with code 127',
|
| 204 |
+
);
|
| 205 |
+
expect(finalHistoryItem.tools[0].resultDisplay).toContain('not found');
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
describe('UI Streaming and Throttling', () => {
|
| 209 |
+
beforeEach(() => {
|
| 210 |
+
vi.useFakeTimers({ toFake: ['Date'] });
|
| 211 |
+
});
|
| 212 |
+
afterEach(() => {
|
| 213 |
+
vi.useRealTimers();
|
| 214 |
+
});
|
| 215 |
+
|
| 216 |
+
it('should throttle pending UI updates for text streams', async () => {
|
| 217 |
+
const { result } = renderProcessorHook();
|
| 218 |
+
act(() => {
|
| 219 |
+
result.current.handleShellCommand(
|
| 220 |
+
'stream',
|
| 221 |
+
new AbortController().signal,
|
| 222 |
+
);
|
| 223 |
+
});
|
| 224 |
+
|
| 225 |
+
// Simulate rapid output
|
| 226 |
+
act(() => {
|
| 227 |
+
mockShellOutputCallback({
|
| 228 |
+
type: 'data',
|
| 229 |
+
chunk: 'hello',
|
| 230 |
+
});
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
// Should not have updated the UI yet
|
| 234 |
+
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(1); // Only the initial call
|
| 235 |
+
|
| 236 |
+
// Advance time and send another event to trigger the throttled update
|
| 237 |
+
await act(async () => {
|
| 238 |
+
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
|
| 239 |
+
});
|
| 240 |
+
act(() => {
|
| 241 |
+
mockShellOutputCallback({
|
| 242 |
+
type: 'data',
|
| 243 |
+
chunk: ' world',
|
| 244 |
+
});
|
| 245 |
+
});
|
| 246 |
+
|
| 247 |
+
// Should now have been called with the cumulative output
|
| 248 |
+
expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
|
| 249 |
+
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
|
| 250 |
+
expect.objectContaining({
|
| 251 |
+
tools: [expect.objectContaining({ resultDisplay: 'hello world' })],
|
| 252 |
+
}),
|
| 253 |
+
);
|
| 254 |
+
});
|
| 255 |
+
|
| 256 |
+
it('should show binary progress messages correctly', async () => {
|
| 257 |
+
const { result } = renderProcessorHook();
|
| 258 |
+
act(() => {
|
| 259 |
+
result.current.handleShellCommand(
|
| 260 |
+
'cat img',
|
| 261 |
+
new AbortController().signal,
|
| 262 |
+
);
|
| 263 |
+
});
|
| 264 |
+
|
| 265 |
+
// Should immediately show the detection message
|
| 266 |
+
act(() => {
|
| 267 |
+
mockShellOutputCallback({ type: 'binary_detected' });
|
| 268 |
+
});
|
| 269 |
+
await act(async () => {
|
| 270 |
+
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
|
| 271 |
+
});
|
| 272 |
+
// Send another event to trigger the update
|
| 273 |
+
act(() => {
|
| 274 |
+
mockShellOutputCallback({ type: 'binary_progress', bytesReceived: 0 });
|
| 275 |
+
});
|
| 276 |
+
|
| 277 |
+
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
|
| 278 |
+
expect.objectContaining({
|
| 279 |
+
tools: [
|
| 280 |
+
expect.objectContaining({
|
| 281 |
+
resultDisplay: '[Binary output detected. Halting stream...]',
|
| 282 |
+
}),
|
| 283 |
+
],
|
| 284 |
+
}),
|
| 285 |
+
);
|
| 286 |
+
|
| 287 |
+
// Now test progress updates
|
| 288 |
+
await act(async () => {
|
| 289 |
+
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
|
| 290 |
+
});
|
| 291 |
+
act(() => {
|
| 292 |
+
mockShellOutputCallback({
|
| 293 |
+
type: 'binary_progress',
|
| 294 |
+
bytesReceived: 2048,
|
| 295 |
+
});
|
| 296 |
+
});
|
| 297 |
+
|
| 298 |
+
expect(setPendingHistoryItemMock).toHaveBeenLastCalledWith(
|
| 299 |
+
expect.objectContaining({
|
| 300 |
+
tools: [
|
| 301 |
+
expect.objectContaining({
|
| 302 |
+
resultDisplay: '[Receiving binary output... 2.0 KB received]',
|
| 303 |
+
}),
|
| 304 |
+
],
|
| 305 |
+
}),
|
| 306 |
+
);
|
| 307 |
+
});
|
| 308 |
+
});
|
| 309 |
+
|
| 310 |
+
it('should not wrap the command on Windows', async () => {
|
| 311 |
+
vi.mocked(os.platform).mockReturnValue('win32');
|
| 312 |
+
const { result } = renderProcessorHook();
|
| 313 |
+
|
| 314 |
+
act(() => {
|
| 315 |
+
result.current.handleShellCommand('dir', new AbortController().signal);
|
| 316 |
+
});
|
| 317 |
+
|
| 318 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 319 |
+
'dir',
|
| 320 |
+
'/test/dir',
|
| 321 |
+
expect.any(Function),
|
| 322 |
+
expect.any(Object),
|
| 323 |
+
false,
|
| 324 |
+
);
|
| 325 |
+
});
|
| 326 |
+
|
| 327 |
+
it('should handle command abort and display cancelled status', async () => {
|
| 328 |
+
const { result } = renderProcessorHook();
|
| 329 |
+
const abortController = new AbortController();
|
| 330 |
+
|
| 331 |
+
act(() => {
|
| 332 |
+
result.current.handleShellCommand('sleep 5', abortController.signal);
|
| 333 |
+
});
|
| 334 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 335 |
+
|
| 336 |
+
act(() => {
|
| 337 |
+
abortController.abort();
|
| 338 |
+
resolveExecutionPromise(
|
| 339 |
+
createMockServiceResult({ aborted: true, output: 'Canceled' }),
|
| 340 |
+
);
|
| 341 |
+
});
|
| 342 |
+
await act(async () => await execPromise);
|
| 343 |
+
|
| 344 |
+
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
|
| 345 |
+
expect(finalHistoryItem.tools[0].status).toBe(ToolCallStatus.Canceled);
|
| 346 |
+
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
|
| 347 |
+
'Command was cancelled.',
|
| 348 |
+
);
|
| 349 |
+
});
|
| 350 |
+
|
| 351 |
+
it('should handle binary output result correctly', async () => {
|
| 352 |
+
const { result } = renderProcessorHook();
|
| 353 |
+
const binaryBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
|
| 354 |
+
mockIsBinary.mockReturnValue(true);
|
| 355 |
+
|
| 356 |
+
act(() => {
|
| 357 |
+
result.current.handleShellCommand(
|
| 358 |
+
'cat image.png',
|
| 359 |
+
new AbortController().signal,
|
| 360 |
+
);
|
| 361 |
+
});
|
| 362 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 363 |
+
|
| 364 |
+
act(() => {
|
| 365 |
+
resolveExecutionPromise(
|
| 366 |
+
createMockServiceResult({ rawOutput: binaryBuffer }),
|
| 367 |
+
);
|
| 368 |
+
});
|
| 369 |
+
await act(async () => await execPromise);
|
| 370 |
+
|
| 371 |
+
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
|
| 372 |
+
expect(finalHistoryItem.tools[0].status).toBe(ToolCallStatus.Success);
|
| 373 |
+
expect(finalHistoryItem.tools[0].resultDisplay).toBe(
|
| 374 |
+
'[Command produced binary output, which is not shown.]',
|
| 375 |
+
);
|
| 376 |
+
});
|
| 377 |
+
|
| 378 |
+
it('should handle promise rejection and show an error', async () => {
|
| 379 |
+
const { result } = renderProcessorHook();
|
| 380 |
+
const testError = new Error('Unexpected failure');
|
| 381 |
+
mockShellExecutionService.mockImplementation(() => ({
|
| 382 |
+
pid: 12345,
|
| 383 |
+
result: Promise.reject(testError),
|
| 384 |
+
}));
|
| 385 |
+
|
| 386 |
+
act(() => {
|
| 387 |
+
result.current.handleShellCommand(
|
| 388 |
+
'a-command',
|
| 389 |
+
new AbortController().signal,
|
| 390 |
+
);
|
| 391 |
+
});
|
| 392 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 393 |
+
|
| 394 |
+
await act(async () => await execPromise);
|
| 395 |
+
|
| 396 |
+
expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
|
| 397 |
+
expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);
|
| 398 |
+
expect(addItemToHistoryMock.mock.calls[1][0]).toEqual({
|
| 399 |
+
type: 'error',
|
| 400 |
+
text: 'An unexpected error occurred: Unexpected failure',
|
| 401 |
+
});
|
| 402 |
+
});
|
| 403 |
+
|
| 404 |
+
it('should handle synchronous errors during execution and clean up resources', async () => {
|
| 405 |
+
const testError = new Error('Synchronous spawn error');
|
| 406 |
+
mockShellExecutionService.mockImplementation(() => {
|
| 407 |
+
throw testError;
|
| 408 |
+
});
|
| 409 |
+
// Mock that the temp file was created before the error was thrown
|
| 410 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 411 |
+
|
| 412 |
+
const { result } = renderProcessorHook();
|
| 413 |
+
|
| 414 |
+
act(() => {
|
| 415 |
+
result.current.handleShellCommand(
|
| 416 |
+
'a-command',
|
| 417 |
+
new AbortController().signal,
|
| 418 |
+
);
|
| 419 |
+
});
|
| 420 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 421 |
+
|
| 422 |
+
await act(async () => await execPromise);
|
| 423 |
+
|
| 424 |
+
expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
|
| 425 |
+
expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);
|
| 426 |
+
expect(addItemToHistoryMock.mock.calls[1][0]).toEqual({
|
| 427 |
+
type: 'error',
|
| 428 |
+
text: 'An unexpected error occurred: Synchronous spawn error',
|
| 429 |
+
});
|
| 430 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
|
| 431 |
+
// Verify that the temporary file was cleaned up
|
| 432 |
+
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
|
| 433 |
+
});
|
| 434 |
+
|
| 435 |
+
describe('Directory Change Warning', () => {
|
| 436 |
+
it('should show a warning if the working directory changes', async () => {
|
| 437 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pwd_abcdef.tmp');
|
| 438 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 439 |
+
vi.mocked(fs.readFileSync).mockReturnValue('/test/dir/new'); // A different directory
|
| 440 |
+
|
| 441 |
+
const { result } = renderProcessorHook();
|
| 442 |
+
act(() => {
|
| 443 |
+
result.current.handleShellCommand(
|
| 444 |
+
'cd new',
|
| 445 |
+
new AbortController().signal,
|
| 446 |
+
);
|
| 447 |
+
});
|
| 448 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 449 |
+
|
| 450 |
+
act(() => {
|
| 451 |
+
resolveExecutionPromise(createMockServiceResult());
|
| 452 |
+
});
|
| 453 |
+
await act(async () => await execPromise);
|
| 454 |
+
|
| 455 |
+
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
|
| 456 |
+
expect(finalHistoryItem.tools[0].resultDisplay).toContain(
|
| 457 |
+
"WARNING: shell mode is stateless; the directory change to '/test/dir/new' will not persist.",
|
| 458 |
+
);
|
| 459 |
+
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
|
| 460 |
+
});
|
| 461 |
+
|
| 462 |
+
it('should NOT show a warning if the directory does not change', async () => {
|
| 463 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 464 |
+
vi.mocked(fs.readFileSync).mockReturnValue('/test/dir'); // The same directory
|
| 465 |
+
|
| 466 |
+
const { result } = renderProcessorHook();
|
| 467 |
+
act(() => {
|
| 468 |
+
result.current.handleShellCommand('ls', new AbortController().signal);
|
| 469 |
+
});
|
| 470 |
+
const execPromise = onExecMock.mock.calls[0][0];
|
| 471 |
+
|
| 472 |
+
act(() => {
|
| 473 |
+
resolveExecutionPromise(createMockServiceResult());
|
| 474 |
+
});
|
| 475 |
+
await act(async () => await execPromise);
|
| 476 |
+
|
| 477 |
+
const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
|
| 478 |
+
expect(finalHistoryItem.tools[0].resultDisplay).not.toContain('WARNING');
|
| 479 |
+
});
|
| 480 |
+
});
|
| 481 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/shellCommandProcessor.ts
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
HistoryItemWithoutId,
|
| 9 |
+
IndividualToolCallDisplay,
|
| 10 |
+
ToolCallStatus,
|
| 11 |
+
} from '../types.js';
|
| 12 |
+
import { useCallback } from 'react';
|
| 13 |
+
import {
|
| 14 |
+
Config,
|
| 15 |
+
GeminiClient,
|
| 16 |
+
isBinary,
|
| 17 |
+
ShellExecutionResult,
|
| 18 |
+
ShellExecutionService,
|
| 19 |
+
} from '@qwen-code/qwen-code-core';
|
| 20 |
+
import { type PartListUnion } from '@google/genai';
|
| 21 |
+
import { UseHistoryManagerReturn } from './useHistoryManager.js';
|
| 22 |
+
import { SHELL_COMMAND_NAME } from '../constants.js';
|
| 23 |
+
import { formatMemoryUsage } from '../utils/formatters.js';
|
| 24 |
+
import crypto from 'crypto';
|
| 25 |
+
import path from 'path';
|
| 26 |
+
import os from 'os';
|
| 27 |
+
import fs from 'fs';
|
| 28 |
+
|
| 29 |
+
export const OUTPUT_UPDATE_INTERVAL_MS = 1000;
|
| 30 |
+
const MAX_OUTPUT_LENGTH = 10000;
|
| 31 |
+
|
| 32 |
+
function addShellCommandToGeminiHistory(
|
| 33 |
+
geminiClient: GeminiClient,
|
| 34 |
+
rawQuery: string,
|
| 35 |
+
resultText: string,
|
| 36 |
+
) {
|
| 37 |
+
const modelContent =
|
| 38 |
+
resultText.length > MAX_OUTPUT_LENGTH
|
| 39 |
+
? resultText.substring(0, MAX_OUTPUT_LENGTH) + '\n... (truncated)'
|
| 40 |
+
: resultText;
|
| 41 |
+
|
| 42 |
+
geminiClient.addHistory({
|
| 43 |
+
role: 'user',
|
| 44 |
+
parts: [
|
| 45 |
+
{
|
| 46 |
+
text: `I ran the following shell command:
|
| 47 |
+
\`\`\`sh
|
| 48 |
+
${rawQuery}
|
| 49 |
+
\`\`\`
|
| 50 |
+
|
| 51 |
+
This produced the following result:
|
| 52 |
+
\`\`\`
|
| 53 |
+
${modelContent}
|
| 54 |
+
\`\`\``,
|
| 55 |
+
},
|
| 56 |
+
],
|
| 57 |
+
});
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* Hook to process shell commands.
|
| 62 |
+
* Orchestrates command execution and updates history and agent context.
|
| 63 |
+
*/
|
| 64 |
+
export const useShellCommandProcessor = (
|
| 65 |
+
addItemToHistory: UseHistoryManagerReturn['addItem'],
|
| 66 |
+
setPendingHistoryItem: React.Dispatch<
|
| 67 |
+
React.SetStateAction<HistoryItemWithoutId | null>
|
| 68 |
+
>,
|
| 69 |
+
onExec: (command: Promise<void>) => void,
|
| 70 |
+
onDebugMessage: (message: string) => void,
|
| 71 |
+
config: Config,
|
| 72 |
+
geminiClient: GeminiClient,
|
| 73 |
+
) => {
|
| 74 |
+
const handleShellCommand = useCallback(
|
| 75 |
+
(rawQuery: PartListUnion, abortSignal: AbortSignal): boolean => {
|
| 76 |
+
if (typeof rawQuery !== 'string' || rawQuery.trim() === '') {
|
| 77 |
+
return false;
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
const userMessageTimestamp = Date.now();
|
| 81 |
+
const callId = `shell-${userMessageTimestamp}`;
|
| 82 |
+
addItemToHistory(
|
| 83 |
+
{ type: 'user_shell', text: rawQuery },
|
| 84 |
+
userMessageTimestamp,
|
| 85 |
+
);
|
| 86 |
+
|
| 87 |
+
const isWindows = os.platform() === 'win32';
|
| 88 |
+
const targetDir = config.getTargetDir();
|
| 89 |
+
let commandToExecute = rawQuery;
|
| 90 |
+
let pwdFilePath: string | undefined;
|
| 91 |
+
|
| 92 |
+
// On non-windows, wrap the command to capture the final working directory.
|
| 93 |
+
if (!isWindows) {
|
| 94 |
+
let command = rawQuery.trim();
|
| 95 |
+
const pwdFileName = `shell_pwd_${crypto.randomBytes(6).toString('hex')}.tmp`;
|
| 96 |
+
pwdFilePath = path.join(os.tmpdir(), pwdFileName);
|
| 97 |
+
// Ensure command ends with a separator before adding our own.
|
| 98 |
+
if (!command.endsWith(';') && !command.endsWith('&')) {
|
| 99 |
+
command += ';';
|
| 100 |
+
}
|
| 101 |
+
commandToExecute = `{ ${command} }; __code=$?; pwd > "${pwdFilePath}"; exit $__code`;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
const executeCommand = async (
|
| 105 |
+
resolve: (value: void | PromiseLike<void>) => void,
|
| 106 |
+
) => {
|
| 107 |
+
let lastUpdateTime = Date.now();
|
| 108 |
+
let cumulativeStdout = '';
|
| 109 |
+
let isBinaryStream = false;
|
| 110 |
+
let binaryBytesReceived = 0;
|
| 111 |
+
|
| 112 |
+
const initialToolDisplay: IndividualToolCallDisplay = {
|
| 113 |
+
callId,
|
| 114 |
+
name: SHELL_COMMAND_NAME,
|
| 115 |
+
description: rawQuery,
|
| 116 |
+
status: ToolCallStatus.Executing,
|
| 117 |
+
resultDisplay: '',
|
| 118 |
+
confirmationDetails: undefined,
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
setPendingHistoryItem({
|
| 122 |
+
type: 'tool_group',
|
| 123 |
+
tools: [initialToolDisplay],
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
let executionPid: number | undefined;
|
| 127 |
+
|
| 128 |
+
const abortHandler = () => {
|
| 129 |
+
onDebugMessage(
|
| 130 |
+
`Aborting shell command (PID: ${executionPid ?? 'unknown'})`,
|
| 131 |
+
);
|
| 132 |
+
};
|
| 133 |
+
abortSignal.addEventListener('abort', abortHandler, { once: true });
|
| 134 |
+
|
| 135 |
+
onDebugMessage(`Executing in ${targetDir}: ${commandToExecute}`);
|
| 136 |
+
|
| 137 |
+
try {
|
| 138 |
+
const { pid, result } = await ShellExecutionService.execute(
|
| 139 |
+
commandToExecute,
|
| 140 |
+
targetDir,
|
| 141 |
+
(event) => {
|
| 142 |
+
switch (event.type) {
|
| 143 |
+
case 'data':
|
| 144 |
+
// Do not process text data if we've already switched to binary mode.
|
| 145 |
+
if (isBinaryStream) break;
|
| 146 |
+
cumulativeStdout += event.chunk;
|
| 147 |
+
break;
|
| 148 |
+
case 'binary_detected':
|
| 149 |
+
isBinaryStream = true;
|
| 150 |
+
break;
|
| 151 |
+
case 'binary_progress':
|
| 152 |
+
isBinaryStream = true;
|
| 153 |
+
binaryBytesReceived = event.bytesReceived;
|
| 154 |
+
break;
|
| 155 |
+
default: {
|
| 156 |
+
throw new Error('An unhandled ShellOutputEvent was found.');
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
// Compute the display string based on the *current* state.
|
| 161 |
+
let currentDisplayOutput: string;
|
| 162 |
+
if (isBinaryStream) {
|
| 163 |
+
if (binaryBytesReceived > 0) {
|
| 164 |
+
currentDisplayOutput = `[Receiving binary output... ${formatMemoryUsage(
|
| 165 |
+
binaryBytesReceived,
|
| 166 |
+
)} received]`;
|
| 167 |
+
} else {
|
| 168 |
+
currentDisplayOutput =
|
| 169 |
+
'[Binary output detected. Halting stream...]';
|
| 170 |
+
}
|
| 171 |
+
} else {
|
| 172 |
+
currentDisplayOutput = cumulativeStdout;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// Throttle pending UI updates to avoid excessive re-renders.
|
| 176 |
+
if (Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS) {
|
| 177 |
+
setPendingHistoryItem({
|
| 178 |
+
type: 'tool_group',
|
| 179 |
+
tools: [
|
| 180 |
+
{
|
| 181 |
+
...initialToolDisplay,
|
| 182 |
+
resultDisplay: currentDisplayOutput,
|
| 183 |
+
},
|
| 184 |
+
],
|
| 185 |
+
});
|
| 186 |
+
lastUpdateTime = Date.now();
|
| 187 |
+
}
|
| 188 |
+
},
|
| 189 |
+
abortSignal,
|
| 190 |
+
config.getShouldUseNodePtyShell(),
|
| 191 |
+
);
|
| 192 |
+
|
| 193 |
+
executionPid = pid;
|
| 194 |
+
|
| 195 |
+
result
|
| 196 |
+
.then((result: ShellExecutionResult) => {
|
| 197 |
+
setPendingHistoryItem(null);
|
| 198 |
+
|
| 199 |
+
let mainContent: string;
|
| 200 |
+
|
| 201 |
+
if (isBinary(result.rawOutput)) {
|
| 202 |
+
mainContent =
|
| 203 |
+
'[Command produced binary output, which is not shown.]';
|
| 204 |
+
} else {
|
| 205 |
+
mainContent =
|
| 206 |
+
result.output.trim() || '(Command produced no output)';
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
let finalOutput = mainContent;
|
| 210 |
+
let finalStatus = ToolCallStatus.Success;
|
| 211 |
+
|
| 212 |
+
if (result.error) {
|
| 213 |
+
finalStatus = ToolCallStatus.Error;
|
| 214 |
+
finalOutput = `${result.error.message}\n${finalOutput}`;
|
| 215 |
+
} else if (result.aborted) {
|
| 216 |
+
finalStatus = ToolCallStatus.Canceled;
|
| 217 |
+
finalOutput = `Command was cancelled.\n${finalOutput}`;
|
| 218 |
+
} else if (result.signal) {
|
| 219 |
+
finalStatus = ToolCallStatus.Error;
|
| 220 |
+
finalOutput = `Command terminated by signal: ${result.signal}.\n${finalOutput}`;
|
| 221 |
+
} else if (result.exitCode !== 0) {
|
| 222 |
+
finalStatus = ToolCallStatus.Error;
|
| 223 |
+
finalOutput = `Command exited with code ${result.exitCode}.\n${finalOutput}`;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
if (pwdFilePath && fs.existsSync(pwdFilePath)) {
|
| 227 |
+
const finalPwd = fs.readFileSync(pwdFilePath, 'utf8').trim();
|
| 228 |
+
if (finalPwd && finalPwd !== targetDir) {
|
| 229 |
+
const warning = `WARNING: shell mode is stateless; the directory change to '${finalPwd}' will not persist.`;
|
| 230 |
+
finalOutput = `${warning}\n\n${finalOutput}`;
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
const finalToolDisplay: IndividualToolCallDisplay = {
|
| 235 |
+
...initialToolDisplay,
|
| 236 |
+
status: finalStatus,
|
| 237 |
+
resultDisplay: finalOutput,
|
| 238 |
+
};
|
| 239 |
+
|
| 240 |
+
// Add the complete, contextual result to the local UI history.
|
| 241 |
+
addItemToHistory(
|
| 242 |
+
{
|
| 243 |
+
type: 'tool_group',
|
| 244 |
+
tools: [finalToolDisplay],
|
| 245 |
+
} as HistoryItemWithoutId,
|
| 246 |
+
userMessageTimestamp,
|
| 247 |
+
);
|
| 248 |
+
|
| 249 |
+
// Add the same complete, contextual result to the LLM's history.
|
| 250 |
+
addShellCommandToGeminiHistory(
|
| 251 |
+
geminiClient,
|
| 252 |
+
rawQuery,
|
| 253 |
+
finalOutput,
|
| 254 |
+
);
|
| 255 |
+
})
|
| 256 |
+
.catch((err) => {
|
| 257 |
+
setPendingHistoryItem(null);
|
| 258 |
+
const errorMessage =
|
| 259 |
+
err instanceof Error ? err.message : String(err);
|
| 260 |
+
addItemToHistory(
|
| 261 |
+
{
|
| 262 |
+
type: 'error',
|
| 263 |
+
text: `An unexpected error occurred: ${errorMessage}`,
|
| 264 |
+
},
|
| 265 |
+
userMessageTimestamp,
|
| 266 |
+
);
|
| 267 |
+
})
|
| 268 |
+
.finally(() => {
|
| 269 |
+
abortSignal.removeEventListener('abort', abortHandler);
|
| 270 |
+
if (pwdFilePath && fs.existsSync(pwdFilePath)) {
|
| 271 |
+
fs.unlinkSync(pwdFilePath);
|
| 272 |
+
}
|
| 273 |
+
resolve();
|
| 274 |
+
});
|
| 275 |
+
} catch (err) {
|
| 276 |
+
// This block handles synchronous errors from `execute`
|
| 277 |
+
setPendingHistoryItem(null);
|
| 278 |
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
| 279 |
+
addItemToHistory(
|
| 280 |
+
{
|
| 281 |
+
type: 'error',
|
| 282 |
+
text: `An unexpected error occurred: ${errorMessage}`,
|
| 283 |
+
},
|
| 284 |
+
userMessageTimestamp,
|
| 285 |
+
);
|
| 286 |
+
|
| 287 |
+
// Perform cleanup here as well
|
| 288 |
+
if (pwdFilePath && fs.existsSync(pwdFilePath)) {
|
| 289 |
+
fs.unlinkSync(pwdFilePath);
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
resolve(); // Resolve the promise to unblock `onExec`
|
| 293 |
+
}
|
| 294 |
+
};
|
| 295 |
+
|
| 296 |
+
const execPromise = new Promise<void>((resolve) => {
|
| 297 |
+
executeCommand(resolve);
|
| 298 |
+
});
|
| 299 |
+
|
| 300 |
+
onExec(execPromise);
|
| 301 |
+
return true;
|
| 302 |
+
},
|
| 303 |
+
[
|
| 304 |
+
config,
|
| 305 |
+
onDebugMessage,
|
| 306 |
+
addItemToHistory,
|
| 307 |
+
setPendingHistoryItem,
|
| 308 |
+
onExec,
|
| 309 |
+
geminiClient,
|
| 310 |
+
],
|
| 311 |
+
);
|
| 312 |
+
|
| 313 |
+
return { handleShellCommand };
|
| 314 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/slashCommandProcessor.test.ts
ADDED
|
@@ -0,0 +1,1040 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
const { logSlashCommand } = vi.hoisted(() => ({
|
| 8 |
+
logSlashCommand: vi.fn(),
|
| 9 |
+
}));
|
| 10 |
+
|
| 11 |
+
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
|
| 12 |
+
const original =
|
| 13 |
+
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
|
| 14 |
+
return {
|
| 15 |
+
...original,
|
| 16 |
+
logSlashCommand,
|
| 17 |
+
getIdeInstaller: vi.fn().mockReturnValue(null),
|
| 18 |
+
};
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
const { mockProcessExit } = vi.hoisted(() => ({
|
| 22 |
+
mockProcessExit: vi.fn((_code?: number): never => undefined as never),
|
| 23 |
+
}));
|
| 24 |
+
|
| 25 |
+
vi.mock('node:process', () => {
|
| 26 |
+
const mockProcess: Partial<NodeJS.Process> = {
|
| 27 |
+
exit: mockProcessExit,
|
| 28 |
+
platform: 'sunos',
|
| 29 |
+
} as unknown as NodeJS.Process;
|
| 30 |
+
return {
|
| 31 |
+
...mockProcess,
|
| 32 |
+
default: mockProcess,
|
| 33 |
+
};
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
const mockBuiltinLoadCommands = vi.fn();
|
| 37 |
+
vi.mock('../../services/BuiltinCommandLoader.js', () => ({
|
| 38 |
+
BuiltinCommandLoader: vi.fn().mockImplementation(() => ({
|
| 39 |
+
loadCommands: mockBuiltinLoadCommands,
|
| 40 |
+
})),
|
| 41 |
+
}));
|
| 42 |
+
|
| 43 |
+
const mockFileLoadCommands = vi.fn();
|
| 44 |
+
vi.mock('../../services/FileCommandLoader.js', () => ({
|
| 45 |
+
FileCommandLoader: vi.fn().mockImplementation(() => ({
|
| 46 |
+
loadCommands: mockFileLoadCommands,
|
| 47 |
+
})),
|
| 48 |
+
}));
|
| 49 |
+
|
| 50 |
+
const mockMcpLoadCommands = vi.fn();
|
| 51 |
+
vi.mock('../../services/McpPromptLoader.js', () => ({
|
| 52 |
+
McpPromptLoader: vi.fn().mockImplementation(() => ({
|
| 53 |
+
loadCommands: mockMcpLoadCommands,
|
| 54 |
+
})),
|
| 55 |
+
}));
|
| 56 |
+
|
| 57 |
+
vi.mock('../contexts/SessionContext.js', () => ({
|
| 58 |
+
useSessionStats: vi.fn(() => ({ stats: {} })),
|
| 59 |
+
}));
|
| 60 |
+
|
| 61 |
+
const { mockRunExitCleanup } = vi.hoisted(() => ({
|
| 62 |
+
mockRunExitCleanup: vi.fn(),
|
| 63 |
+
}));
|
| 64 |
+
|
| 65 |
+
vi.mock('../../utils/cleanup.js', () => ({
|
| 66 |
+
runExitCleanup: mockRunExitCleanup,
|
| 67 |
+
}));
|
| 68 |
+
|
| 69 |
+
import {
|
| 70 |
+
SlashCommandStatus,
|
| 71 |
+
ToolConfirmationOutcome,
|
| 72 |
+
makeFakeConfig,
|
| 73 |
+
} from '@qwen-code/qwen-code-core';
|
| 74 |
+
import { act, renderHook, waitFor } from '@testing-library/react';
|
| 75 |
+
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
|
| 76 |
+
import { LoadedSettings } from '../../config/settings.js';
|
| 77 |
+
import { BuiltinCommandLoader } from '../../services/BuiltinCommandLoader.js';
|
| 78 |
+
import { FileCommandLoader } from '../../services/FileCommandLoader.js';
|
| 79 |
+
import { McpPromptLoader } from '../../services/McpPromptLoader.js';
|
| 80 |
+
import {
|
| 81 |
+
CommandContext,
|
| 82 |
+
CommandKind,
|
| 83 |
+
ConfirmShellCommandsActionReturn,
|
| 84 |
+
SlashCommand,
|
| 85 |
+
} from '../commands/types.js';
|
| 86 |
+
import { MessageType } from '../types.js';
|
| 87 |
+
import { useSlashCommandProcessor } from './slashCommandProcessor.js';
|
| 88 |
+
|
| 89 |
+
function createTestCommand(
|
| 90 |
+
overrides: Partial<SlashCommand>,
|
| 91 |
+
kind: CommandKind = CommandKind.BUILT_IN,
|
| 92 |
+
): SlashCommand {
|
| 93 |
+
return {
|
| 94 |
+
name: 'test',
|
| 95 |
+
description: 'a test command',
|
| 96 |
+
kind,
|
| 97 |
+
...overrides,
|
| 98 |
+
};
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
describe('useSlashCommandProcessor', () => {
|
| 102 |
+
const mockAddItem = vi.fn();
|
| 103 |
+
const mockClearItems = vi.fn();
|
| 104 |
+
const mockLoadHistory = vi.fn();
|
| 105 |
+
const mockOpenThemeDialog = vi.fn();
|
| 106 |
+
const mockOpenAuthDialog = vi.fn();
|
| 107 |
+
const mockSetQuittingMessages = vi.fn();
|
| 108 |
+
|
| 109 |
+
const mockConfig = makeFakeConfig({});
|
| 110 |
+
|
| 111 |
+
const mockSettings = {} as LoadedSettings;
|
| 112 |
+
|
| 113 |
+
beforeEach(() => {
|
| 114 |
+
vi.clearAllMocks();
|
| 115 |
+
(vi.mocked(BuiltinCommandLoader) as Mock).mockClear();
|
| 116 |
+
mockBuiltinLoadCommands.mockResolvedValue([]);
|
| 117 |
+
mockFileLoadCommands.mockResolvedValue([]);
|
| 118 |
+
mockMcpLoadCommands.mockResolvedValue([]);
|
| 119 |
+
});
|
| 120 |
+
|
| 121 |
+
const setupProcessorHook = (
|
| 122 |
+
builtinCommands: SlashCommand[] = [],
|
| 123 |
+
fileCommands: SlashCommand[] = [],
|
| 124 |
+
mcpCommands: SlashCommand[] = [],
|
| 125 |
+
setIsProcessing = vi.fn(),
|
| 126 |
+
) => {
|
| 127 |
+
mockBuiltinLoadCommands.mockResolvedValue(Object.freeze(builtinCommands));
|
| 128 |
+
mockFileLoadCommands.mockResolvedValue(Object.freeze(fileCommands));
|
| 129 |
+
mockMcpLoadCommands.mockResolvedValue(Object.freeze(mcpCommands));
|
| 130 |
+
|
| 131 |
+
const { result } = renderHook(() =>
|
| 132 |
+
useSlashCommandProcessor(
|
| 133 |
+
mockConfig,
|
| 134 |
+
mockSettings,
|
| 135 |
+
mockAddItem,
|
| 136 |
+
mockClearItems,
|
| 137 |
+
mockLoadHistory,
|
| 138 |
+
vi.fn(), // refreshStatic
|
| 139 |
+
vi.fn(), // onDebugMessage
|
| 140 |
+
mockOpenThemeDialog, // openThemeDialog
|
| 141 |
+
mockOpenAuthDialog,
|
| 142 |
+
vi.fn(), // openEditorDialog
|
| 143 |
+
vi.fn(), // toggleCorgiMode
|
| 144 |
+
mockSetQuittingMessages,
|
| 145 |
+
vi.fn(), // openPrivacyNotice
|
| 146 |
+
vi.fn(), // openSettingsDialog
|
| 147 |
+
vi.fn(), // toggleVimEnabled
|
| 148 |
+
setIsProcessing,
|
| 149 |
+
),
|
| 150 |
+
);
|
| 151 |
+
|
| 152 |
+
return result;
|
| 153 |
+
};
|
| 154 |
+
|
| 155 |
+
describe('Initialization and Command Loading', () => {
|
| 156 |
+
it('should initialize CommandService with all required loaders', () => {
|
| 157 |
+
setupProcessorHook();
|
| 158 |
+
expect(BuiltinCommandLoader).toHaveBeenCalledWith(mockConfig);
|
| 159 |
+
expect(FileCommandLoader).toHaveBeenCalledWith(mockConfig);
|
| 160 |
+
expect(McpPromptLoader).toHaveBeenCalledWith(mockConfig);
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
it('should call loadCommands and populate state after mounting', async () => {
|
| 164 |
+
const testCommand = createTestCommand({ name: 'test' });
|
| 165 |
+
const result = setupProcessorHook([testCommand]);
|
| 166 |
+
|
| 167 |
+
await waitFor(() => {
|
| 168 |
+
expect(result.current.slashCommands).toHaveLength(1);
|
| 169 |
+
});
|
| 170 |
+
|
| 171 |
+
expect(result.current.slashCommands[0]?.name).toBe('test');
|
| 172 |
+
expect(mockBuiltinLoadCommands).toHaveBeenCalledTimes(1);
|
| 173 |
+
expect(mockFileLoadCommands).toHaveBeenCalledTimes(1);
|
| 174 |
+
expect(mockMcpLoadCommands).toHaveBeenCalledTimes(1);
|
| 175 |
+
});
|
| 176 |
+
|
| 177 |
+
it('should provide an immutable array of commands to consumers', async () => {
|
| 178 |
+
const testCommand = createTestCommand({ name: 'test' });
|
| 179 |
+
const result = setupProcessorHook([testCommand]);
|
| 180 |
+
|
| 181 |
+
await waitFor(() => {
|
| 182 |
+
expect(result.current.slashCommands).toHaveLength(1);
|
| 183 |
+
});
|
| 184 |
+
|
| 185 |
+
const commands = result.current.slashCommands;
|
| 186 |
+
|
| 187 |
+
expect(() => {
|
| 188 |
+
// @ts-expect-error - We are intentionally testing a violation of the readonly type.
|
| 189 |
+
commands.push(createTestCommand({ name: 'rogue' }));
|
| 190 |
+
}).toThrow(TypeError);
|
| 191 |
+
});
|
| 192 |
+
|
| 193 |
+
it('should override built-in commands with file-based commands of the same name', async () => {
|
| 194 |
+
const builtinAction = vi.fn();
|
| 195 |
+
const fileAction = vi.fn();
|
| 196 |
+
|
| 197 |
+
const builtinCommand = createTestCommand({
|
| 198 |
+
name: 'override',
|
| 199 |
+
description: 'builtin',
|
| 200 |
+
action: builtinAction,
|
| 201 |
+
});
|
| 202 |
+
const fileCommand = createTestCommand(
|
| 203 |
+
{ name: 'override', description: 'file', action: fileAction },
|
| 204 |
+
CommandKind.FILE,
|
| 205 |
+
);
|
| 206 |
+
|
| 207 |
+
const result = setupProcessorHook([builtinCommand], [fileCommand]);
|
| 208 |
+
|
| 209 |
+
await waitFor(() => {
|
| 210 |
+
// The service should only return one command with the name 'override'
|
| 211 |
+
expect(result.current.slashCommands).toHaveLength(1);
|
| 212 |
+
});
|
| 213 |
+
|
| 214 |
+
await act(async () => {
|
| 215 |
+
await result.current.handleSlashCommand('/override');
|
| 216 |
+
});
|
| 217 |
+
|
| 218 |
+
// Only the file-based command's action should be called.
|
| 219 |
+
expect(fileAction).toHaveBeenCalledTimes(1);
|
| 220 |
+
expect(builtinAction).not.toHaveBeenCalled();
|
| 221 |
+
});
|
| 222 |
+
});
|
| 223 |
+
|
| 224 |
+
describe('Command Execution Logic', () => {
|
| 225 |
+
it('should display an error for an unknown command', async () => {
|
| 226 |
+
const result = setupProcessorHook();
|
| 227 |
+
await waitFor(() => expect(result.current.slashCommands).toBeDefined());
|
| 228 |
+
|
| 229 |
+
await act(async () => {
|
| 230 |
+
await result.current.handleSlashCommand('/nonexistent');
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
// Expect 2 calls: one for the user's input, one for the error message.
|
| 234 |
+
expect(mockAddItem).toHaveBeenCalledTimes(2);
|
| 235 |
+
expect(mockAddItem).toHaveBeenLastCalledWith(
|
| 236 |
+
{
|
| 237 |
+
type: MessageType.ERROR,
|
| 238 |
+
text: 'Unknown command: /nonexistent',
|
| 239 |
+
},
|
| 240 |
+
expect.any(Number),
|
| 241 |
+
);
|
| 242 |
+
});
|
| 243 |
+
|
| 244 |
+
it('should display help for a parent command invoked without a subcommand', async () => {
|
| 245 |
+
const parentCommand: SlashCommand = {
|
| 246 |
+
name: 'parent',
|
| 247 |
+
description: 'a parent command',
|
| 248 |
+
kind: CommandKind.BUILT_IN,
|
| 249 |
+
subCommands: [
|
| 250 |
+
{
|
| 251 |
+
name: 'child1',
|
| 252 |
+
description: 'First child.',
|
| 253 |
+
kind: CommandKind.BUILT_IN,
|
| 254 |
+
},
|
| 255 |
+
],
|
| 256 |
+
};
|
| 257 |
+
const result = setupProcessorHook([parentCommand]);
|
| 258 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 259 |
+
|
| 260 |
+
await act(async () => {
|
| 261 |
+
await result.current.handleSlashCommand('/parent');
|
| 262 |
+
});
|
| 263 |
+
|
| 264 |
+
expect(mockAddItem).toHaveBeenCalledTimes(2);
|
| 265 |
+
expect(mockAddItem).toHaveBeenLastCalledWith(
|
| 266 |
+
{
|
| 267 |
+
type: MessageType.INFO,
|
| 268 |
+
text: expect.stringContaining(
|
| 269 |
+
"Command '/parent' requires a subcommand.",
|
| 270 |
+
),
|
| 271 |
+
},
|
| 272 |
+
expect.any(Number),
|
| 273 |
+
);
|
| 274 |
+
});
|
| 275 |
+
|
| 276 |
+
it('should correctly find and execute a nested subcommand', async () => {
|
| 277 |
+
const childAction = vi.fn();
|
| 278 |
+
const parentCommand: SlashCommand = {
|
| 279 |
+
name: 'parent',
|
| 280 |
+
description: 'a parent command',
|
| 281 |
+
kind: CommandKind.BUILT_IN,
|
| 282 |
+
subCommands: [
|
| 283 |
+
{
|
| 284 |
+
name: 'child',
|
| 285 |
+
description: 'a child command',
|
| 286 |
+
kind: CommandKind.BUILT_IN,
|
| 287 |
+
action: childAction,
|
| 288 |
+
},
|
| 289 |
+
],
|
| 290 |
+
};
|
| 291 |
+
const result = setupProcessorHook([parentCommand]);
|
| 292 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 293 |
+
|
| 294 |
+
await act(async () => {
|
| 295 |
+
await result.current.handleSlashCommand('/parent child with args');
|
| 296 |
+
});
|
| 297 |
+
|
| 298 |
+
expect(childAction).toHaveBeenCalledTimes(1);
|
| 299 |
+
|
| 300 |
+
expect(childAction).toHaveBeenCalledWith(
|
| 301 |
+
expect.objectContaining({
|
| 302 |
+
services: expect.objectContaining({
|
| 303 |
+
config: mockConfig,
|
| 304 |
+
}),
|
| 305 |
+
ui: expect.objectContaining({
|
| 306 |
+
addItem: mockAddItem,
|
| 307 |
+
}),
|
| 308 |
+
}),
|
| 309 |
+
'with args',
|
| 310 |
+
);
|
| 311 |
+
});
|
| 312 |
+
|
| 313 |
+
it('sets isProcessing to false if the the input is not a command', async () => {
|
| 314 |
+
const setMockIsProcessing = vi.fn();
|
| 315 |
+
const result = setupProcessorHook([], [], [], setMockIsProcessing);
|
| 316 |
+
|
| 317 |
+
await act(async () => {
|
| 318 |
+
await result.current.handleSlashCommand('imnotacommand');
|
| 319 |
+
});
|
| 320 |
+
|
| 321 |
+
expect(setMockIsProcessing).not.toHaveBeenCalled();
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
it('sets isProcessing to false if the command has an error', async () => {
|
| 325 |
+
const setMockIsProcessing = vi.fn();
|
| 326 |
+
const failCommand = createTestCommand({
|
| 327 |
+
name: 'fail',
|
| 328 |
+
action: vi.fn().mockRejectedValue(new Error('oh no!')),
|
| 329 |
+
});
|
| 330 |
+
|
| 331 |
+
const result = setupProcessorHook(
|
| 332 |
+
[failCommand],
|
| 333 |
+
[],
|
| 334 |
+
[],
|
| 335 |
+
setMockIsProcessing,
|
| 336 |
+
);
|
| 337 |
+
|
| 338 |
+
await act(async () => {
|
| 339 |
+
await result.current.handleSlashCommand('/fail');
|
| 340 |
+
});
|
| 341 |
+
|
| 342 |
+
expect(setMockIsProcessing).toHaveBeenNthCalledWith(1, true);
|
| 343 |
+
expect(setMockIsProcessing).toHaveBeenNthCalledWith(2, false);
|
| 344 |
+
});
|
| 345 |
+
|
| 346 |
+
it('should set isProcessing to true during execution and false afterwards', async () => {
|
| 347 |
+
const mockSetIsProcessing = vi.fn();
|
| 348 |
+
const command = createTestCommand({
|
| 349 |
+
name: 'long-running',
|
| 350 |
+
action: () => new Promise((resolve) => setTimeout(resolve, 50)),
|
| 351 |
+
});
|
| 352 |
+
|
| 353 |
+
const result = setupProcessorHook([command], [], [], mockSetIsProcessing);
|
| 354 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 355 |
+
|
| 356 |
+
const executionPromise = act(async () => {
|
| 357 |
+
await result.current.handleSlashCommand('/long-running');
|
| 358 |
+
});
|
| 359 |
+
|
| 360 |
+
// It should be true immediately after starting
|
| 361 |
+
expect(mockSetIsProcessing).toHaveBeenNthCalledWith(1, true);
|
| 362 |
+
// It should not have been called with false yet
|
| 363 |
+
expect(mockSetIsProcessing).not.toHaveBeenCalledWith(false);
|
| 364 |
+
|
| 365 |
+
await executionPromise;
|
| 366 |
+
|
| 367 |
+
// After the promise resolves, it should be called with false
|
| 368 |
+
expect(mockSetIsProcessing).toHaveBeenNthCalledWith(2, false);
|
| 369 |
+
expect(mockSetIsProcessing).toHaveBeenCalledTimes(2);
|
| 370 |
+
});
|
| 371 |
+
});
|
| 372 |
+
|
| 373 |
+
describe('Action Result Handling', () => {
|
| 374 |
+
it('should handle "dialog: theme" action', async () => {
|
| 375 |
+
const command = createTestCommand({
|
| 376 |
+
name: 'themecmd',
|
| 377 |
+
action: vi.fn().mockResolvedValue({ type: 'dialog', dialog: 'theme' }),
|
| 378 |
+
});
|
| 379 |
+
const result = setupProcessorHook([command]);
|
| 380 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 381 |
+
|
| 382 |
+
await act(async () => {
|
| 383 |
+
await result.current.handleSlashCommand('/themecmd');
|
| 384 |
+
});
|
| 385 |
+
|
| 386 |
+
expect(mockOpenThemeDialog).toHaveBeenCalled();
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
it('should handle "load_history" action', async () => {
|
| 390 |
+
const command = createTestCommand({
|
| 391 |
+
name: 'load',
|
| 392 |
+
action: vi.fn().mockResolvedValue({
|
| 393 |
+
type: 'load_history',
|
| 394 |
+
history: [{ type: MessageType.USER, text: 'old prompt' }],
|
| 395 |
+
clientHistory: [{ role: 'user', parts: [{ text: 'old prompt' }] }],
|
| 396 |
+
}),
|
| 397 |
+
});
|
| 398 |
+
const result = setupProcessorHook([command]);
|
| 399 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 400 |
+
|
| 401 |
+
await act(async () => {
|
| 402 |
+
await result.current.handleSlashCommand('/load');
|
| 403 |
+
});
|
| 404 |
+
|
| 405 |
+
expect(mockClearItems).toHaveBeenCalledTimes(1);
|
| 406 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 407 |
+
{ type: 'user', text: 'old prompt' },
|
| 408 |
+
expect.any(Number),
|
| 409 |
+
);
|
| 410 |
+
});
|
| 411 |
+
|
| 412 |
+
describe('with fake timers', () => {
|
| 413 |
+
// This test needs to let the async `waitFor` complete with REAL timers
|
| 414 |
+
// before switching to FAKE timers to test setTimeout.
|
| 415 |
+
it('should handle a "quit" action', async () => {
|
| 416 |
+
const quitAction = vi
|
| 417 |
+
.fn()
|
| 418 |
+
.mockResolvedValue({ type: 'quit', messages: [] });
|
| 419 |
+
const command = createTestCommand({
|
| 420 |
+
name: 'exit',
|
| 421 |
+
action: quitAction,
|
| 422 |
+
});
|
| 423 |
+
const result = setupProcessorHook([command]);
|
| 424 |
+
|
| 425 |
+
await waitFor(() =>
|
| 426 |
+
expect(result.current.slashCommands).toHaveLength(1),
|
| 427 |
+
);
|
| 428 |
+
|
| 429 |
+
vi.useFakeTimers();
|
| 430 |
+
|
| 431 |
+
try {
|
| 432 |
+
await act(async () => {
|
| 433 |
+
await result.current.handleSlashCommand('/exit');
|
| 434 |
+
});
|
| 435 |
+
|
| 436 |
+
await act(async () => {
|
| 437 |
+
await vi.advanceTimersByTimeAsync(200);
|
| 438 |
+
});
|
| 439 |
+
|
| 440 |
+
expect(mockSetQuittingMessages).toHaveBeenCalledWith([]);
|
| 441 |
+
expect(mockProcessExit).toHaveBeenCalledWith(0);
|
| 442 |
+
} finally {
|
| 443 |
+
vi.useRealTimers();
|
| 444 |
+
}
|
| 445 |
+
});
|
| 446 |
+
|
| 447 |
+
it('should call runExitCleanup when handling a "quit" action', async () => {
|
| 448 |
+
const quitAction = vi
|
| 449 |
+
.fn()
|
| 450 |
+
.mockResolvedValue({ type: 'quit', messages: [] });
|
| 451 |
+
const command = createTestCommand({
|
| 452 |
+
name: 'exit',
|
| 453 |
+
action: quitAction,
|
| 454 |
+
});
|
| 455 |
+
const result = setupProcessorHook([command]);
|
| 456 |
+
|
| 457 |
+
await waitFor(() =>
|
| 458 |
+
expect(result.current.slashCommands).toHaveLength(1),
|
| 459 |
+
);
|
| 460 |
+
|
| 461 |
+
vi.useFakeTimers();
|
| 462 |
+
|
| 463 |
+
try {
|
| 464 |
+
await act(async () => {
|
| 465 |
+
await result.current.handleSlashCommand('/exit');
|
| 466 |
+
});
|
| 467 |
+
|
| 468 |
+
await act(async () => {
|
| 469 |
+
await vi.advanceTimersByTimeAsync(200);
|
| 470 |
+
});
|
| 471 |
+
|
| 472 |
+
expect(mockRunExitCleanup).toHaveBeenCalledTimes(1);
|
| 473 |
+
} finally {
|
| 474 |
+
vi.useRealTimers();
|
| 475 |
+
}
|
| 476 |
+
});
|
| 477 |
+
});
|
| 478 |
+
|
| 479 |
+
it('should handle "submit_prompt" action returned from a file-based command', async () => {
|
| 480 |
+
const fileCommand = createTestCommand(
|
| 481 |
+
{
|
| 482 |
+
name: 'filecmd',
|
| 483 |
+
description: 'A command from a file',
|
| 484 |
+
action: async () => ({
|
| 485 |
+
type: 'submit_prompt',
|
| 486 |
+
content: 'The actual prompt from the TOML file.',
|
| 487 |
+
}),
|
| 488 |
+
},
|
| 489 |
+
CommandKind.FILE,
|
| 490 |
+
);
|
| 491 |
+
|
| 492 |
+
const result = setupProcessorHook([], [fileCommand]);
|
| 493 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 494 |
+
|
| 495 |
+
let actionResult;
|
| 496 |
+
await act(async () => {
|
| 497 |
+
actionResult = await result.current.handleSlashCommand('/filecmd');
|
| 498 |
+
});
|
| 499 |
+
|
| 500 |
+
expect(actionResult).toEqual({
|
| 501 |
+
type: 'submit_prompt',
|
| 502 |
+
content: 'The actual prompt from the TOML file.',
|
| 503 |
+
});
|
| 504 |
+
|
| 505 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 506 |
+
{ type: MessageType.USER, text: '/filecmd' },
|
| 507 |
+
expect.any(Number),
|
| 508 |
+
);
|
| 509 |
+
});
|
| 510 |
+
|
| 511 |
+
it('should handle "submit_prompt" action returned from a mcp-based command', async () => {
|
| 512 |
+
const mcpCommand = createTestCommand(
|
| 513 |
+
{
|
| 514 |
+
name: 'mcpcmd',
|
| 515 |
+
description: 'A command from mcp',
|
| 516 |
+
action: async () => ({
|
| 517 |
+
type: 'submit_prompt',
|
| 518 |
+
content: 'The actual prompt from the mcp command.',
|
| 519 |
+
}),
|
| 520 |
+
},
|
| 521 |
+
CommandKind.MCP_PROMPT,
|
| 522 |
+
);
|
| 523 |
+
|
| 524 |
+
const result = setupProcessorHook([], [], [mcpCommand]);
|
| 525 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 526 |
+
|
| 527 |
+
let actionResult;
|
| 528 |
+
await act(async () => {
|
| 529 |
+
actionResult = await result.current.handleSlashCommand('/mcpcmd');
|
| 530 |
+
});
|
| 531 |
+
|
| 532 |
+
expect(actionResult).toEqual({
|
| 533 |
+
type: 'submit_prompt',
|
| 534 |
+
content: 'The actual prompt from the mcp command.',
|
| 535 |
+
});
|
| 536 |
+
|
| 537 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 538 |
+
{ type: MessageType.USER, text: '/mcpcmd' },
|
| 539 |
+
expect.any(Number),
|
| 540 |
+
);
|
| 541 |
+
});
|
| 542 |
+
});
|
| 543 |
+
|
| 544 |
+
describe('Shell Command Confirmation Flow', () => {
|
| 545 |
+
// Use a generic vi.fn() for the action. We will change its behavior in each test.
|
| 546 |
+
const mockCommandAction = vi.fn();
|
| 547 |
+
|
| 548 |
+
const shellCommand = createTestCommand({
|
| 549 |
+
name: 'shellcmd',
|
| 550 |
+
action: mockCommandAction,
|
| 551 |
+
});
|
| 552 |
+
|
| 553 |
+
beforeEach(() => {
|
| 554 |
+
// Reset the mock before each test
|
| 555 |
+
mockCommandAction.mockClear();
|
| 556 |
+
|
| 557 |
+
// Default behavior: request confirmation
|
| 558 |
+
mockCommandAction.mockResolvedValue({
|
| 559 |
+
type: 'confirm_shell_commands',
|
| 560 |
+
commandsToConfirm: ['rm -rf /'],
|
| 561 |
+
originalInvocation: { raw: '/shellcmd' },
|
| 562 |
+
} as ConfirmShellCommandsActionReturn);
|
| 563 |
+
});
|
| 564 |
+
|
| 565 |
+
it('should set confirmation request when action returns confirm_shell_commands', async () => {
|
| 566 |
+
const result = setupProcessorHook([shellCommand]);
|
| 567 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 568 |
+
|
| 569 |
+
// This is intentionally not awaited, because the promise it returns
|
| 570 |
+
// will not resolve until the user responds to the confirmation.
|
| 571 |
+
act(() => {
|
| 572 |
+
result.current.handleSlashCommand('/shellcmd');
|
| 573 |
+
});
|
| 574 |
+
|
| 575 |
+
// We now wait for the state to be updated with the request.
|
| 576 |
+
await waitFor(() => {
|
| 577 |
+
expect(result.current.shellConfirmationRequest).not.toBeNull();
|
| 578 |
+
});
|
| 579 |
+
|
| 580 |
+
expect(result.current.shellConfirmationRequest?.commands).toEqual([
|
| 581 |
+
'rm -rf /',
|
| 582 |
+
]);
|
| 583 |
+
});
|
| 584 |
+
|
| 585 |
+
it('should do nothing if user cancels confirmation', async () => {
|
| 586 |
+
const result = setupProcessorHook([shellCommand]);
|
| 587 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 588 |
+
|
| 589 |
+
act(() => {
|
| 590 |
+
result.current.handleSlashCommand('/shellcmd');
|
| 591 |
+
});
|
| 592 |
+
|
| 593 |
+
// Wait for the confirmation dialog to be set
|
| 594 |
+
await waitFor(() => {
|
| 595 |
+
expect(result.current.shellConfirmationRequest).not.toBeNull();
|
| 596 |
+
});
|
| 597 |
+
|
| 598 |
+
const onConfirm = result.current.shellConfirmationRequest?.onConfirm;
|
| 599 |
+
expect(onConfirm).toBeDefined();
|
| 600 |
+
|
| 601 |
+
// Change the mock action's behavior for a potential second run.
|
| 602 |
+
// If the test is flawed, this will be called, and we can detect it.
|
| 603 |
+
mockCommandAction.mockResolvedValue({
|
| 604 |
+
type: 'message',
|
| 605 |
+
messageType: 'info',
|
| 606 |
+
content: 'This should not be called',
|
| 607 |
+
});
|
| 608 |
+
|
| 609 |
+
await act(async () => {
|
| 610 |
+
onConfirm!(ToolConfirmationOutcome.Cancel, []); // Pass empty array for safety
|
| 611 |
+
});
|
| 612 |
+
|
| 613 |
+
expect(result.current.shellConfirmationRequest).toBeNull();
|
| 614 |
+
// Verify the action was only called the initial time.
|
| 615 |
+
expect(mockCommandAction).toHaveBeenCalledTimes(1);
|
| 616 |
+
});
|
| 617 |
+
|
| 618 |
+
it('should re-run command with one-time allowlist on "Proceed Once"', async () => {
|
| 619 |
+
const result = setupProcessorHook([shellCommand]);
|
| 620 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 621 |
+
|
| 622 |
+
act(() => {
|
| 623 |
+
result.current.handleSlashCommand('/shellcmd');
|
| 624 |
+
});
|
| 625 |
+
await waitFor(() => {
|
| 626 |
+
expect(result.current.shellConfirmationRequest).not.toBeNull();
|
| 627 |
+
});
|
| 628 |
+
|
| 629 |
+
const onConfirm = result.current.shellConfirmationRequest?.onConfirm;
|
| 630 |
+
|
| 631 |
+
// **Change the mock's behavior for the SECOND run.**
|
| 632 |
+
// This is the key to testing the outcome.
|
| 633 |
+
mockCommandAction.mockResolvedValue({
|
| 634 |
+
type: 'message',
|
| 635 |
+
messageType: 'info',
|
| 636 |
+
content: 'Success!',
|
| 637 |
+
});
|
| 638 |
+
|
| 639 |
+
await act(async () => {
|
| 640 |
+
onConfirm!(ToolConfirmationOutcome.ProceedOnce, ['rm -rf /']);
|
| 641 |
+
});
|
| 642 |
+
|
| 643 |
+
expect(result.current.shellConfirmationRequest).toBeNull();
|
| 644 |
+
|
| 645 |
+
// The action should have been called twice (initial + re-run).
|
| 646 |
+
await waitFor(() => {
|
| 647 |
+
expect(mockCommandAction).toHaveBeenCalledTimes(2);
|
| 648 |
+
});
|
| 649 |
+
|
| 650 |
+
// We can inspect the context of the second call to ensure the one-time list was used.
|
| 651 |
+
const secondCallContext = mockCommandAction.mock
|
| 652 |
+
.calls[1][0] as CommandContext;
|
| 653 |
+
expect(
|
| 654 |
+
secondCallContext.session.sessionShellAllowlist.has('rm -rf /'),
|
| 655 |
+
).toBe(true);
|
| 656 |
+
|
| 657 |
+
// Verify the final success message was added.
|
| 658 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 659 |
+
{ type: MessageType.INFO, text: 'Success!' },
|
| 660 |
+
expect.any(Number),
|
| 661 |
+
);
|
| 662 |
+
|
| 663 |
+
// Verify the session-wide allowlist was NOT permanently updated.
|
| 664 |
+
// Re-render the hook by calling a no-op command to get the latest context.
|
| 665 |
+
await act(async () => {
|
| 666 |
+
result.current.handleSlashCommand('/no-op');
|
| 667 |
+
});
|
| 668 |
+
const finalContext = result.current.commandContext;
|
| 669 |
+
expect(finalContext.session.sessionShellAllowlist.size).toBe(0);
|
| 670 |
+
});
|
| 671 |
+
|
| 672 |
+
it('should re-run command and update session allowlist on "Proceed Always"', async () => {
|
| 673 |
+
const result = setupProcessorHook([shellCommand]);
|
| 674 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 675 |
+
|
| 676 |
+
act(() => {
|
| 677 |
+
result.current.handleSlashCommand('/shellcmd');
|
| 678 |
+
});
|
| 679 |
+
await waitFor(() => {
|
| 680 |
+
expect(result.current.shellConfirmationRequest).not.toBeNull();
|
| 681 |
+
});
|
| 682 |
+
|
| 683 |
+
const onConfirm = result.current.shellConfirmationRequest?.onConfirm;
|
| 684 |
+
mockCommandAction.mockResolvedValue({
|
| 685 |
+
type: 'message',
|
| 686 |
+
messageType: 'info',
|
| 687 |
+
content: 'Success!',
|
| 688 |
+
});
|
| 689 |
+
|
| 690 |
+
await act(async () => {
|
| 691 |
+
onConfirm!(ToolConfirmationOutcome.ProceedAlways, ['rm -rf /']);
|
| 692 |
+
});
|
| 693 |
+
|
| 694 |
+
expect(result.current.shellConfirmationRequest).toBeNull();
|
| 695 |
+
await waitFor(() => {
|
| 696 |
+
expect(mockCommandAction).toHaveBeenCalledTimes(2);
|
| 697 |
+
});
|
| 698 |
+
|
| 699 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 700 |
+
{ type: MessageType.INFO, text: 'Success!' },
|
| 701 |
+
expect.any(Number),
|
| 702 |
+
);
|
| 703 |
+
|
| 704 |
+
// Check that the session-wide allowlist WAS updated.
|
| 705 |
+
await waitFor(() => {
|
| 706 |
+
const finalContext = result.current.commandContext;
|
| 707 |
+
expect(finalContext.session.sessionShellAllowlist.has('rm -rf /')).toBe(
|
| 708 |
+
true,
|
| 709 |
+
);
|
| 710 |
+
});
|
| 711 |
+
});
|
| 712 |
+
});
|
| 713 |
+
|
| 714 |
+
describe('Command Parsing and Matching', () => {
|
| 715 |
+
it('should be case-sensitive', async () => {
|
| 716 |
+
const command = createTestCommand({ name: 'test' });
|
| 717 |
+
const result = setupProcessorHook([command]);
|
| 718 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 719 |
+
|
| 720 |
+
await act(async () => {
|
| 721 |
+
// Use uppercase when command is lowercase
|
| 722 |
+
await result.current.handleSlashCommand('/Test');
|
| 723 |
+
});
|
| 724 |
+
|
| 725 |
+
// It should fail and call addItem with an error
|
| 726 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 727 |
+
{
|
| 728 |
+
type: MessageType.ERROR,
|
| 729 |
+
text: 'Unknown command: /Test',
|
| 730 |
+
},
|
| 731 |
+
expect.any(Number),
|
| 732 |
+
);
|
| 733 |
+
});
|
| 734 |
+
|
| 735 |
+
it('should correctly match an altName', async () => {
|
| 736 |
+
const action = vi.fn();
|
| 737 |
+
const command = createTestCommand({
|
| 738 |
+
name: 'main',
|
| 739 |
+
altNames: ['alias'],
|
| 740 |
+
description: 'a command with an alias',
|
| 741 |
+
action,
|
| 742 |
+
});
|
| 743 |
+
const result = setupProcessorHook([command]);
|
| 744 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 745 |
+
|
| 746 |
+
await act(async () => {
|
| 747 |
+
await result.current.handleSlashCommand('/alias');
|
| 748 |
+
});
|
| 749 |
+
|
| 750 |
+
expect(action).toHaveBeenCalledTimes(1);
|
| 751 |
+
expect(mockAddItem).not.toHaveBeenCalledWith(
|
| 752 |
+
expect.objectContaining({ type: MessageType.ERROR }),
|
| 753 |
+
);
|
| 754 |
+
});
|
| 755 |
+
|
| 756 |
+
it('should handle extra whitespace around the command', async () => {
|
| 757 |
+
const action = vi.fn();
|
| 758 |
+
const command = createTestCommand({ name: 'test', action });
|
| 759 |
+
const result = setupProcessorHook([command]);
|
| 760 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 761 |
+
|
| 762 |
+
await act(async () => {
|
| 763 |
+
await result.current.handleSlashCommand(' /test with-args ');
|
| 764 |
+
});
|
| 765 |
+
|
| 766 |
+
expect(action).toHaveBeenCalledWith(expect.anything(), 'with-args');
|
| 767 |
+
});
|
| 768 |
+
|
| 769 |
+
it('should handle `?` as a command prefix', async () => {
|
| 770 |
+
const action = vi.fn();
|
| 771 |
+
const command = createTestCommand({ name: 'help', action });
|
| 772 |
+
const result = setupProcessorHook([command]);
|
| 773 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));
|
| 774 |
+
|
| 775 |
+
await act(async () => {
|
| 776 |
+
await result.current.handleSlashCommand('?help');
|
| 777 |
+
});
|
| 778 |
+
|
| 779 |
+
expect(action).toHaveBeenCalledTimes(1);
|
| 780 |
+
});
|
| 781 |
+
});
|
| 782 |
+
|
| 783 |
+
describe('Command Precedence', () => {
|
| 784 |
+
it('should override mcp-based commands with file-based commands of the same name', async () => {
|
| 785 |
+
const mcpAction = vi.fn();
|
| 786 |
+
const fileAction = vi.fn();
|
| 787 |
+
|
| 788 |
+
const mcpCommand = createTestCommand(
|
| 789 |
+
{
|
| 790 |
+
name: 'override',
|
| 791 |
+
description: 'mcp',
|
| 792 |
+
action: mcpAction,
|
| 793 |
+
},
|
| 794 |
+
CommandKind.MCP_PROMPT,
|
| 795 |
+
);
|
| 796 |
+
const fileCommand = createTestCommand(
|
| 797 |
+
{ name: 'override', description: 'file', action: fileAction },
|
| 798 |
+
CommandKind.FILE,
|
| 799 |
+
);
|
| 800 |
+
|
| 801 |
+
const result = setupProcessorHook([], [fileCommand], [mcpCommand]);
|
| 802 |
+
|
| 803 |
+
await waitFor(() => {
|
| 804 |
+
// The service should only return one command with the name 'override'
|
| 805 |
+
expect(result.current.slashCommands).toHaveLength(1);
|
| 806 |
+
});
|
| 807 |
+
|
| 808 |
+
await act(async () => {
|
| 809 |
+
await result.current.handleSlashCommand('/override');
|
| 810 |
+
});
|
| 811 |
+
|
| 812 |
+
// Only the file-based command's action should be called.
|
| 813 |
+
expect(fileAction).toHaveBeenCalledTimes(1);
|
| 814 |
+
expect(mcpAction).not.toHaveBeenCalled();
|
| 815 |
+
});
|
| 816 |
+
|
| 817 |
+
it('should prioritize a command with a primary name over a command with a matching alias', async () => {
|
| 818 |
+
const quitAction = vi.fn();
|
| 819 |
+
const exitAction = vi.fn();
|
| 820 |
+
|
| 821 |
+
const quitCommand = createTestCommand({
|
| 822 |
+
name: 'quit',
|
| 823 |
+
altNames: ['exit'],
|
| 824 |
+
action: quitAction,
|
| 825 |
+
});
|
| 826 |
+
|
| 827 |
+
const exitCommand = createTestCommand(
|
| 828 |
+
{
|
| 829 |
+
name: 'exit',
|
| 830 |
+
action: exitAction,
|
| 831 |
+
},
|
| 832 |
+
CommandKind.FILE,
|
| 833 |
+
);
|
| 834 |
+
|
| 835 |
+
// The order of commands in the final loaded array is not guaranteed,
|
| 836 |
+
// so the test must work regardless of which comes first.
|
| 837 |
+
const result = setupProcessorHook([quitCommand], [exitCommand]);
|
| 838 |
+
|
| 839 |
+
await waitFor(() => {
|
| 840 |
+
expect(result.current.slashCommands).toHaveLength(2);
|
| 841 |
+
});
|
| 842 |
+
|
| 843 |
+
await act(async () => {
|
| 844 |
+
await result.current.handleSlashCommand('/exit');
|
| 845 |
+
});
|
| 846 |
+
|
| 847 |
+
// The action for the command whose primary name is 'exit' should be called.
|
| 848 |
+
expect(exitAction).toHaveBeenCalledTimes(1);
|
| 849 |
+
// The action for the command that has 'exit' as an alias should NOT be called.
|
| 850 |
+
expect(quitAction).not.toHaveBeenCalled();
|
| 851 |
+
});
|
| 852 |
+
|
| 853 |
+
it('should add an overridden command to the history', async () => {
|
| 854 |
+
const quitCommand = createTestCommand({
|
| 855 |
+
name: 'quit',
|
| 856 |
+
altNames: ['exit'],
|
| 857 |
+
action: vi.fn(),
|
| 858 |
+
});
|
| 859 |
+
const exitCommand = createTestCommand(
|
| 860 |
+
{ name: 'exit', action: vi.fn() },
|
| 861 |
+
CommandKind.FILE,
|
| 862 |
+
);
|
| 863 |
+
|
| 864 |
+
const result = setupProcessorHook([quitCommand], [exitCommand]);
|
| 865 |
+
await waitFor(() => expect(result.current.slashCommands).toHaveLength(2));
|
| 866 |
+
|
| 867 |
+
await act(async () => {
|
| 868 |
+
await result.current.handleSlashCommand('/exit');
|
| 869 |
+
});
|
| 870 |
+
|
| 871 |
+
// It should be added to the history.
|
| 872 |
+
expect(mockAddItem).toHaveBeenCalledWith(
|
| 873 |
+
{ type: MessageType.USER, text: '/exit' },
|
| 874 |
+
expect.any(Number),
|
| 875 |
+
);
|
| 876 |
+
});
|
| 877 |
+
});
|
| 878 |
+
|
| 879 |
+
describe('Lifecycle', () => {
|
| 880 |
+
it('should abort command loading when the hook unmounts', () => {
|
| 881 |
+
const abortSpy = vi.spyOn(AbortController.prototype, 'abort');
|
| 882 |
+
const { unmount } = renderHook(() =>
|
| 883 |
+
useSlashCommandProcessor(
|
| 884 |
+
mockConfig,
|
| 885 |
+
mockSettings,
|
| 886 |
+
mockAddItem,
|
| 887 |
+
mockClearItems,
|
| 888 |
+
mockLoadHistory,
|
| 889 |
+
vi.fn(), // refreshStatic
|
| 890 |
+
vi.fn(), // onDebugMessage
|
| 891 |
+
vi.fn(), // openThemeDialog
|
| 892 |
+
mockOpenAuthDialog,
|
| 893 |
+
vi.fn(), // openEditorDialog
|
| 894 |
+
vi.fn(), // toggleCorgiMode
|
| 895 |
+
mockSetQuittingMessages,
|
| 896 |
+
vi.fn(), // openPrivacyNotice
|
| 897 |
+
|
| 898 |
+
vi.fn(), // openSettingsDialog
|
| 899 |
+
vi.fn(), // toggleVimEnabled
|
| 900 |
+
vi.fn().mockResolvedValue(false), // toggleVimEnabled
|
| 901 |
+
vi.fn(), // setIsProcessing
|
| 902 |
+
),
|
| 903 |
+
);
|
| 904 |
+
|
| 905 |
+
unmount();
|
| 906 |
+
|
| 907 |
+
expect(abortSpy).toHaveBeenCalledTimes(1);
|
| 908 |
+
});
|
| 909 |
+
});
|
| 910 |
+
|
| 911 |
+
describe('Slash Command Logging', () => {
|
| 912 |
+
const mockCommandAction = vi.fn().mockResolvedValue({ type: 'handled' });
|
| 913 |
+
const loggingTestCommands: SlashCommand[] = [
|
| 914 |
+
createTestCommand({
|
| 915 |
+
name: 'logtest',
|
| 916 |
+
action: vi
|
| 917 |
+
.fn()
|
| 918 |
+
.mockResolvedValue({ type: 'message', content: 'hello world' }),
|
| 919 |
+
}),
|
| 920 |
+
createTestCommand({
|
| 921 |
+
name: 'logwithsub',
|
| 922 |
+
subCommands: [
|
| 923 |
+
createTestCommand({
|
| 924 |
+
name: 'sub',
|
| 925 |
+
action: mockCommandAction,
|
| 926 |
+
}),
|
| 927 |
+
],
|
| 928 |
+
}),
|
| 929 |
+
createTestCommand({
|
| 930 |
+
name: 'fail',
|
| 931 |
+
action: vi.fn().mockRejectedValue(new Error('oh no!')),
|
| 932 |
+
}),
|
| 933 |
+
createTestCommand({
|
| 934 |
+
name: 'logalias',
|
| 935 |
+
altNames: ['la'],
|
| 936 |
+
action: mockCommandAction,
|
| 937 |
+
}),
|
| 938 |
+
];
|
| 939 |
+
|
| 940 |
+
beforeEach(() => {
|
| 941 |
+
mockCommandAction.mockClear();
|
| 942 |
+
vi.mocked(logSlashCommand).mockClear();
|
| 943 |
+
});
|
| 944 |
+
|
| 945 |
+
it('should log a simple slash command', async () => {
|
| 946 |
+
const result = setupProcessorHook(loggingTestCommands);
|
| 947 |
+
await waitFor(() =>
|
| 948 |
+
expect(result.current.slashCommands.length).toBeGreaterThan(0),
|
| 949 |
+
);
|
| 950 |
+
await act(async () => {
|
| 951 |
+
await result.current.handleSlashCommand('/logtest');
|
| 952 |
+
});
|
| 953 |
+
|
| 954 |
+
expect(logSlashCommand).toHaveBeenCalledWith(
|
| 955 |
+
mockConfig,
|
| 956 |
+
expect.objectContaining({
|
| 957 |
+
command: 'logtest',
|
| 958 |
+
subcommand: undefined,
|
| 959 |
+
status: SlashCommandStatus.SUCCESS,
|
| 960 |
+
}),
|
| 961 |
+
);
|
| 962 |
+
});
|
| 963 |
+
|
| 964 |
+
it('logs nothing for a bogus command', async () => {
|
| 965 |
+
const result = setupProcessorHook(loggingTestCommands);
|
| 966 |
+
await waitFor(() =>
|
| 967 |
+
expect(result.current.slashCommands.length).toBeGreaterThan(0),
|
| 968 |
+
);
|
| 969 |
+
await act(async () => {
|
| 970 |
+
await result.current.handleSlashCommand('/bogusbogusbogus');
|
| 971 |
+
});
|
| 972 |
+
|
| 973 |
+
expect(logSlashCommand).not.toHaveBeenCalled();
|
| 974 |
+
});
|
| 975 |
+
|
| 976 |
+
it('logs a failure event for a failed command', async () => {
|
| 977 |
+
const result = setupProcessorHook(loggingTestCommands);
|
| 978 |
+
await waitFor(() =>
|
| 979 |
+
expect(result.current.slashCommands.length).toBeGreaterThan(0),
|
| 980 |
+
);
|
| 981 |
+
await act(async () => {
|
| 982 |
+
await result.current.handleSlashCommand('/fail');
|
| 983 |
+
});
|
| 984 |
+
|
| 985 |
+
expect(logSlashCommand).toHaveBeenCalledWith(
|
| 986 |
+
mockConfig,
|
| 987 |
+
expect.objectContaining({
|
| 988 |
+
command: 'fail',
|
| 989 |
+
status: 'error',
|
| 990 |
+
subcommand: undefined,
|
| 991 |
+
}),
|
| 992 |
+
);
|
| 993 |
+
});
|
| 994 |
+
|
| 995 |
+
it('should log a slash command with a subcommand', async () => {
|
| 996 |
+
const result = setupProcessorHook(loggingTestCommands);
|
| 997 |
+
await waitFor(() =>
|
| 998 |
+
expect(result.current.slashCommands.length).toBeGreaterThan(0),
|
| 999 |
+
);
|
| 1000 |
+
await act(async () => {
|
| 1001 |
+
await result.current.handleSlashCommand('/logwithsub sub');
|
| 1002 |
+
});
|
| 1003 |
+
|
| 1004 |
+
expect(logSlashCommand).toHaveBeenCalledWith(
|
| 1005 |
+
mockConfig,
|
| 1006 |
+
expect.objectContaining({
|
| 1007 |
+
command: 'logwithsub',
|
| 1008 |
+
subcommand: 'sub',
|
| 1009 |
+
}),
|
| 1010 |
+
);
|
| 1011 |
+
});
|
| 1012 |
+
|
| 1013 |
+
it('should log the command path when an alias is used', async () => {
|
| 1014 |
+
const result = setupProcessorHook(loggingTestCommands);
|
| 1015 |
+
await waitFor(() =>
|
| 1016 |
+
expect(result.current.slashCommands.length).toBeGreaterThan(0),
|
| 1017 |
+
);
|
| 1018 |
+
await act(async () => {
|
| 1019 |
+
await result.current.handleSlashCommand('/la');
|
| 1020 |
+
});
|
| 1021 |
+
expect(logSlashCommand).toHaveBeenCalledWith(
|
| 1022 |
+
mockConfig,
|
| 1023 |
+
expect.objectContaining({
|
| 1024 |
+
command: 'logalias',
|
| 1025 |
+
}),
|
| 1026 |
+
);
|
| 1027 |
+
});
|
| 1028 |
+
|
| 1029 |
+
it('should not log for unknown commands', async () => {
|
| 1030 |
+
const result = setupProcessorHook(loggingTestCommands);
|
| 1031 |
+
await waitFor(() =>
|
| 1032 |
+
expect(result.current.slashCommands.length).toBeGreaterThan(0),
|
| 1033 |
+
);
|
| 1034 |
+
await act(async () => {
|
| 1035 |
+
await result.current.handleSlashCommand('/unknown');
|
| 1036 |
+
});
|
| 1037 |
+
expect(logSlashCommand).not.toHaveBeenCalled();
|
| 1038 |
+
});
|
| 1039 |
+
});
|
| 1040 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/slashCommandProcessor.ts
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { useCallback, useMemo, useEffect, useState } from 'react';
|
| 8 |
+
import { type PartListUnion } from '@google/genai';
|
| 9 |
+
import process from 'node:process';
|
| 10 |
+
import { UseHistoryManagerReturn } from './useHistoryManager.js';
|
| 11 |
+
import {
|
| 12 |
+
Config,
|
| 13 |
+
GitService,
|
| 14 |
+
Logger,
|
| 15 |
+
logSlashCommand,
|
| 16 |
+
makeSlashCommandEvent,
|
| 17 |
+
SlashCommandStatus,
|
| 18 |
+
ToolConfirmationOutcome,
|
| 19 |
+
} from '@qwen-code/qwen-code-core';
|
| 20 |
+
import { useSessionStats } from '../contexts/SessionContext.js';
|
| 21 |
+
import { runExitCleanup } from '../../utils/cleanup.js';
|
| 22 |
+
import {
|
| 23 |
+
Message,
|
| 24 |
+
MessageType,
|
| 25 |
+
HistoryItemWithoutId,
|
| 26 |
+
HistoryItem,
|
| 27 |
+
SlashCommandProcessorResult,
|
| 28 |
+
} from '../types.js';
|
| 29 |
+
import { LoadedSettings } from '../../config/settings.js';
|
| 30 |
+
import { type CommandContext, type SlashCommand } from '../commands/types.js';
|
| 31 |
+
import { CommandService } from '../../services/CommandService.js';
|
| 32 |
+
import { BuiltinCommandLoader } from '../../services/BuiltinCommandLoader.js';
|
| 33 |
+
import { FileCommandLoader } from '../../services/FileCommandLoader.js';
|
| 34 |
+
import { McpPromptLoader } from '../../services/McpPromptLoader.js';
|
| 35 |
+
|
| 36 |
+
/**
|
| 37 |
+
* Hook to define and process slash commands (e.g., /help, /clear).
|
| 38 |
+
*/
|
| 39 |
+
export const useSlashCommandProcessor = (
|
| 40 |
+
config: Config | null,
|
| 41 |
+
settings: LoadedSettings,
|
| 42 |
+
addItem: UseHistoryManagerReturn['addItem'],
|
| 43 |
+
clearItems: UseHistoryManagerReturn['clearItems'],
|
| 44 |
+
loadHistory: UseHistoryManagerReturn['loadHistory'],
|
| 45 |
+
refreshStatic: () => void,
|
| 46 |
+
onDebugMessage: (message: string) => void,
|
| 47 |
+
openThemeDialog: () => void,
|
| 48 |
+
openAuthDialog: () => void,
|
| 49 |
+
openEditorDialog: () => void,
|
| 50 |
+
toggleCorgiMode: () => void,
|
| 51 |
+
setQuittingMessages: (message: HistoryItem[]) => void,
|
| 52 |
+
openPrivacyNotice: () => void,
|
| 53 |
+
openSettingsDialog: () => void,
|
| 54 |
+
toggleVimEnabled: () => Promise<boolean>,
|
| 55 |
+
setIsProcessing: (isProcessing: boolean) => void,
|
| 56 |
+
setGeminiMdFileCount: (count: number) => void,
|
| 57 |
+
) => {
|
| 58 |
+
const session = useSessionStats();
|
| 59 |
+
const [commands, setCommands] = useState<readonly SlashCommand[]>([]);
|
| 60 |
+
const [reloadTrigger, setReloadTrigger] = useState(0);
|
| 61 |
+
|
| 62 |
+
const reloadCommands = useCallback(() => {
|
| 63 |
+
setReloadTrigger((v) => v + 1);
|
| 64 |
+
}, []);
|
| 65 |
+
const [shellConfirmationRequest, setShellConfirmationRequest] =
|
| 66 |
+
useState<null | {
|
| 67 |
+
commands: string[];
|
| 68 |
+
onConfirm: (
|
| 69 |
+
outcome: ToolConfirmationOutcome,
|
| 70 |
+
approvedCommands?: string[],
|
| 71 |
+
) => void;
|
| 72 |
+
}>(null);
|
| 73 |
+
const [confirmationRequest, setConfirmationRequest] = useState<null | {
|
| 74 |
+
prompt: React.ReactNode;
|
| 75 |
+
onConfirm: (confirmed: boolean) => void;
|
| 76 |
+
}>(null);
|
| 77 |
+
|
| 78 |
+
const [sessionShellAllowlist, setSessionShellAllowlist] = useState(
|
| 79 |
+
new Set<string>(),
|
| 80 |
+
);
|
| 81 |
+
const gitService = useMemo(() => {
|
| 82 |
+
if (!config?.getProjectRoot()) {
|
| 83 |
+
return;
|
| 84 |
+
}
|
| 85 |
+
return new GitService(config.getProjectRoot());
|
| 86 |
+
}, [config]);
|
| 87 |
+
|
| 88 |
+
const logger = useMemo(() => {
|
| 89 |
+
const l = new Logger(config?.getSessionId() || '');
|
| 90 |
+
// The logger's initialize is async, but we can create the instance
|
| 91 |
+
// synchronously. Commands that use it will await its initialization.
|
| 92 |
+
return l;
|
| 93 |
+
}, [config]);
|
| 94 |
+
|
| 95 |
+
const [pendingCompressionItem, setPendingCompressionItem] =
|
| 96 |
+
useState<HistoryItemWithoutId | null>(null);
|
| 97 |
+
|
| 98 |
+
const pendingHistoryItems = useMemo(() => {
|
| 99 |
+
const items: HistoryItemWithoutId[] = [];
|
| 100 |
+
if (pendingCompressionItem != null) {
|
| 101 |
+
items.push(pendingCompressionItem);
|
| 102 |
+
}
|
| 103 |
+
return items;
|
| 104 |
+
}, [pendingCompressionItem]);
|
| 105 |
+
|
| 106 |
+
const addMessage = useCallback(
|
| 107 |
+
(message: Message) => {
|
| 108 |
+
// Convert Message to HistoryItemWithoutId
|
| 109 |
+
let historyItemContent: HistoryItemWithoutId;
|
| 110 |
+
if (message.type === MessageType.ABOUT) {
|
| 111 |
+
historyItemContent = {
|
| 112 |
+
type: 'about',
|
| 113 |
+
cliVersion: message.cliVersion,
|
| 114 |
+
osVersion: message.osVersion,
|
| 115 |
+
sandboxEnv: message.sandboxEnv,
|
| 116 |
+
modelVersion: message.modelVersion,
|
| 117 |
+
selectedAuthType: message.selectedAuthType,
|
| 118 |
+
gcpProject: message.gcpProject,
|
| 119 |
+
ideClient: message.ideClient,
|
| 120 |
+
};
|
| 121 |
+
} else if (message.type === MessageType.HELP) {
|
| 122 |
+
historyItemContent = {
|
| 123 |
+
type: 'help',
|
| 124 |
+
timestamp: message.timestamp,
|
| 125 |
+
};
|
| 126 |
+
} else if (message.type === MessageType.STATS) {
|
| 127 |
+
historyItemContent = {
|
| 128 |
+
type: 'stats',
|
| 129 |
+
duration: message.duration,
|
| 130 |
+
};
|
| 131 |
+
} else if (message.type === MessageType.MODEL_STATS) {
|
| 132 |
+
historyItemContent = {
|
| 133 |
+
type: 'model_stats',
|
| 134 |
+
};
|
| 135 |
+
} else if (message.type === MessageType.TOOL_STATS) {
|
| 136 |
+
historyItemContent = {
|
| 137 |
+
type: 'tool_stats',
|
| 138 |
+
};
|
| 139 |
+
} else if (message.type === MessageType.QUIT) {
|
| 140 |
+
historyItemContent = {
|
| 141 |
+
type: 'quit',
|
| 142 |
+
duration: message.duration,
|
| 143 |
+
};
|
| 144 |
+
} else if (message.type === MessageType.COMPRESSION) {
|
| 145 |
+
historyItemContent = {
|
| 146 |
+
type: 'compression',
|
| 147 |
+
compression: message.compression,
|
| 148 |
+
};
|
| 149 |
+
} else {
|
| 150 |
+
historyItemContent = {
|
| 151 |
+
type: message.type,
|
| 152 |
+
text: message.content,
|
| 153 |
+
};
|
| 154 |
+
}
|
| 155 |
+
addItem(historyItemContent, message.timestamp.getTime());
|
| 156 |
+
},
|
| 157 |
+
[addItem],
|
| 158 |
+
);
|
| 159 |
+
const commandContext = useMemo(
|
| 160 |
+
(): CommandContext => ({
|
| 161 |
+
services: {
|
| 162 |
+
config,
|
| 163 |
+
settings,
|
| 164 |
+
git: gitService,
|
| 165 |
+
logger,
|
| 166 |
+
},
|
| 167 |
+
ui: {
|
| 168 |
+
addItem,
|
| 169 |
+
clear: () => {
|
| 170 |
+
clearItems();
|
| 171 |
+
console.clear();
|
| 172 |
+
refreshStatic();
|
| 173 |
+
},
|
| 174 |
+
loadHistory,
|
| 175 |
+
setDebugMessage: onDebugMessage,
|
| 176 |
+
pendingItem: pendingCompressionItem,
|
| 177 |
+
setPendingItem: setPendingCompressionItem,
|
| 178 |
+
toggleCorgiMode,
|
| 179 |
+
toggleVimEnabled,
|
| 180 |
+
setGeminiMdFileCount,
|
| 181 |
+
reloadCommands,
|
| 182 |
+
},
|
| 183 |
+
session: {
|
| 184 |
+
stats: session.stats,
|
| 185 |
+
sessionShellAllowlist,
|
| 186 |
+
},
|
| 187 |
+
}),
|
| 188 |
+
[
|
| 189 |
+
config,
|
| 190 |
+
settings,
|
| 191 |
+
gitService,
|
| 192 |
+
logger,
|
| 193 |
+
loadHistory,
|
| 194 |
+
addItem,
|
| 195 |
+
clearItems,
|
| 196 |
+
refreshStatic,
|
| 197 |
+
session.stats,
|
| 198 |
+
onDebugMessage,
|
| 199 |
+
pendingCompressionItem,
|
| 200 |
+
setPendingCompressionItem,
|
| 201 |
+
toggleCorgiMode,
|
| 202 |
+
toggleVimEnabled,
|
| 203 |
+
sessionShellAllowlist,
|
| 204 |
+
setGeminiMdFileCount,
|
| 205 |
+
reloadCommands,
|
| 206 |
+
],
|
| 207 |
+
);
|
| 208 |
+
|
| 209 |
+
useEffect(() => {
|
| 210 |
+
if (!config) {
|
| 211 |
+
return;
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
const ideClient = config.getIdeClient();
|
| 215 |
+
const listener = () => {
|
| 216 |
+
reloadCommands();
|
| 217 |
+
};
|
| 218 |
+
|
| 219 |
+
ideClient.addStatusChangeListener(listener);
|
| 220 |
+
|
| 221 |
+
return () => {
|
| 222 |
+
ideClient.removeStatusChangeListener(listener);
|
| 223 |
+
};
|
| 224 |
+
}, [config, reloadCommands]);
|
| 225 |
+
|
| 226 |
+
useEffect(() => {
|
| 227 |
+
const controller = new AbortController();
|
| 228 |
+
const load = async () => {
|
| 229 |
+
const loaders = [
|
| 230 |
+
new McpPromptLoader(config),
|
| 231 |
+
new BuiltinCommandLoader(config),
|
| 232 |
+
new FileCommandLoader(config),
|
| 233 |
+
];
|
| 234 |
+
const commandService = await CommandService.create(
|
| 235 |
+
loaders,
|
| 236 |
+
controller.signal,
|
| 237 |
+
);
|
| 238 |
+
setCommands(commandService.getCommands());
|
| 239 |
+
};
|
| 240 |
+
|
| 241 |
+
load();
|
| 242 |
+
|
| 243 |
+
return () => {
|
| 244 |
+
controller.abort();
|
| 245 |
+
};
|
| 246 |
+
}, [config, reloadTrigger]);
|
| 247 |
+
|
| 248 |
+
const handleSlashCommand = useCallback(
|
| 249 |
+
async (
|
| 250 |
+
rawQuery: PartListUnion,
|
| 251 |
+
oneTimeShellAllowlist?: Set<string>,
|
| 252 |
+
overwriteConfirmed?: boolean,
|
| 253 |
+
): Promise<SlashCommandProcessorResult | false> => {
|
| 254 |
+
if (typeof rawQuery !== 'string') {
|
| 255 |
+
return false;
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
const trimmed = rawQuery.trim();
|
| 259 |
+
if (!trimmed.startsWith('/') && !trimmed.startsWith('?')) {
|
| 260 |
+
return false;
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
setIsProcessing(true);
|
| 264 |
+
|
| 265 |
+
const userMessageTimestamp = Date.now();
|
| 266 |
+
addItem({ type: MessageType.USER, text: trimmed }, userMessageTimestamp);
|
| 267 |
+
|
| 268 |
+
const parts = trimmed.substring(1).trim().split(/\s+/);
|
| 269 |
+
const commandPath = parts.filter((p) => p); // The parts of the command, e.g., ['memory', 'add']
|
| 270 |
+
|
| 271 |
+
let currentCommands = commands;
|
| 272 |
+
let commandToExecute: SlashCommand | undefined;
|
| 273 |
+
let pathIndex = 0;
|
| 274 |
+
let hasError = false;
|
| 275 |
+
const canonicalPath: string[] = [];
|
| 276 |
+
|
| 277 |
+
for (const part of commandPath) {
|
| 278 |
+
// TODO: For better performance and architectural clarity, this two-pass
|
| 279 |
+
// search could be replaced. A more optimal approach would be to
|
| 280 |
+
// pre-compute a single lookup map in `CommandService.ts` that resolves
|
| 281 |
+
// all name and alias conflicts during the initial loading phase. The
|
| 282 |
+
// processor would then perform a single, fast lookup on that map.
|
| 283 |
+
|
| 284 |
+
// First pass: check for an exact match on the primary command name.
|
| 285 |
+
let foundCommand = currentCommands.find((cmd) => cmd.name === part);
|
| 286 |
+
|
| 287 |
+
// Second pass: if no primary name matches, check for an alias.
|
| 288 |
+
if (!foundCommand) {
|
| 289 |
+
foundCommand = currentCommands.find((cmd) =>
|
| 290 |
+
cmd.altNames?.includes(part),
|
| 291 |
+
);
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
if (foundCommand) {
|
| 295 |
+
commandToExecute = foundCommand;
|
| 296 |
+
canonicalPath.push(foundCommand.name);
|
| 297 |
+
pathIndex++;
|
| 298 |
+
if (foundCommand.subCommands) {
|
| 299 |
+
currentCommands = foundCommand.subCommands;
|
| 300 |
+
} else {
|
| 301 |
+
break;
|
| 302 |
+
}
|
| 303 |
+
} else {
|
| 304 |
+
break;
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
const resolvedCommandPath = canonicalPath;
|
| 309 |
+
const subcommand =
|
| 310 |
+
resolvedCommandPath.length > 1
|
| 311 |
+
? resolvedCommandPath.slice(1).join(' ')
|
| 312 |
+
: undefined;
|
| 313 |
+
|
| 314 |
+
try {
|
| 315 |
+
if (commandToExecute) {
|
| 316 |
+
const args = parts.slice(pathIndex).join(' ');
|
| 317 |
+
|
| 318 |
+
if (commandToExecute.action) {
|
| 319 |
+
const fullCommandContext: CommandContext = {
|
| 320 |
+
...commandContext,
|
| 321 |
+
invocation: {
|
| 322 |
+
raw: trimmed,
|
| 323 |
+
name: commandToExecute.name,
|
| 324 |
+
args,
|
| 325 |
+
},
|
| 326 |
+
overwriteConfirmed,
|
| 327 |
+
};
|
| 328 |
+
|
| 329 |
+
// If a one-time list is provided for a "Proceed" action, temporarily
|
| 330 |
+
// augment the session allowlist for this single execution.
|
| 331 |
+
if (oneTimeShellAllowlist && oneTimeShellAllowlist.size > 0) {
|
| 332 |
+
fullCommandContext.session = {
|
| 333 |
+
...fullCommandContext.session,
|
| 334 |
+
sessionShellAllowlist: new Set([
|
| 335 |
+
...fullCommandContext.session.sessionShellAllowlist,
|
| 336 |
+
...oneTimeShellAllowlist,
|
| 337 |
+
]),
|
| 338 |
+
};
|
| 339 |
+
}
|
| 340 |
+
const result = await commandToExecute.action(
|
| 341 |
+
fullCommandContext,
|
| 342 |
+
args,
|
| 343 |
+
);
|
| 344 |
+
|
| 345 |
+
if (result) {
|
| 346 |
+
switch (result.type) {
|
| 347 |
+
case 'tool':
|
| 348 |
+
return {
|
| 349 |
+
type: 'schedule_tool',
|
| 350 |
+
toolName: result.toolName,
|
| 351 |
+
toolArgs: result.toolArgs,
|
| 352 |
+
};
|
| 353 |
+
case 'message':
|
| 354 |
+
addItem(
|
| 355 |
+
{
|
| 356 |
+
type:
|
| 357 |
+
result.messageType === 'error'
|
| 358 |
+
? MessageType.ERROR
|
| 359 |
+
: MessageType.INFO,
|
| 360 |
+
text: result.content,
|
| 361 |
+
},
|
| 362 |
+
Date.now(),
|
| 363 |
+
);
|
| 364 |
+
return { type: 'handled' };
|
| 365 |
+
case 'dialog':
|
| 366 |
+
switch (result.dialog) {
|
| 367 |
+
case 'auth':
|
| 368 |
+
openAuthDialog();
|
| 369 |
+
return { type: 'handled' };
|
| 370 |
+
case 'theme':
|
| 371 |
+
openThemeDialog();
|
| 372 |
+
return { type: 'handled' };
|
| 373 |
+
case 'editor':
|
| 374 |
+
openEditorDialog();
|
| 375 |
+
return { type: 'handled' };
|
| 376 |
+
case 'privacy':
|
| 377 |
+
openPrivacyNotice();
|
| 378 |
+
return { type: 'handled' };
|
| 379 |
+
case 'settings':
|
| 380 |
+
openSettingsDialog();
|
| 381 |
+
return { type: 'handled' };
|
| 382 |
+
case 'help':
|
| 383 |
+
return { type: 'handled' };
|
| 384 |
+
default: {
|
| 385 |
+
const unhandled: never = result.dialog;
|
| 386 |
+
throw new Error(
|
| 387 |
+
`Unhandled slash command result: ${unhandled}`,
|
| 388 |
+
);
|
| 389 |
+
}
|
| 390 |
+
}
|
| 391 |
+
case 'load_history': {
|
| 392 |
+
await config
|
| 393 |
+
?.getGeminiClient()
|
| 394 |
+
?.setHistory(result.clientHistory);
|
| 395 |
+
fullCommandContext.ui.clear();
|
| 396 |
+
result.history.forEach((item, index) => {
|
| 397 |
+
fullCommandContext.ui.addItem(item, index);
|
| 398 |
+
});
|
| 399 |
+
return { type: 'handled' };
|
| 400 |
+
}
|
| 401 |
+
case 'quit':
|
| 402 |
+
setQuittingMessages(result.messages);
|
| 403 |
+
setTimeout(async () => {
|
| 404 |
+
await runExitCleanup();
|
| 405 |
+
process.exit(0);
|
| 406 |
+
}, 100);
|
| 407 |
+
return { type: 'handled' };
|
| 408 |
+
|
| 409 |
+
case 'submit_prompt':
|
| 410 |
+
return {
|
| 411 |
+
type: 'submit_prompt',
|
| 412 |
+
content: result.content,
|
| 413 |
+
};
|
| 414 |
+
case 'confirm_shell_commands': {
|
| 415 |
+
const { outcome, approvedCommands } = await new Promise<{
|
| 416 |
+
outcome: ToolConfirmationOutcome;
|
| 417 |
+
approvedCommands?: string[];
|
| 418 |
+
}>((resolve) => {
|
| 419 |
+
setShellConfirmationRequest({
|
| 420 |
+
commands: result.commandsToConfirm,
|
| 421 |
+
onConfirm: (
|
| 422 |
+
resolvedOutcome,
|
| 423 |
+
resolvedApprovedCommands,
|
| 424 |
+
) => {
|
| 425 |
+
setShellConfirmationRequest(null); // Close the dialog
|
| 426 |
+
resolve({
|
| 427 |
+
outcome: resolvedOutcome,
|
| 428 |
+
approvedCommands: resolvedApprovedCommands,
|
| 429 |
+
});
|
| 430 |
+
},
|
| 431 |
+
});
|
| 432 |
+
});
|
| 433 |
+
|
| 434 |
+
if (
|
| 435 |
+
outcome === ToolConfirmationOutcome.Cancel ||
|
| 436 |
+
!approvedCommands ||
|
| 437 |
+
approvedCommands.length === 0
|
| 438 |
+
) {
|
| 439 |
+
return { type: 'handled' };
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
| 443 |
+
setSessionShellAllowlist(
|
| 444 |
+
(prev) => new Set([...prev, ...approvedCommands]),
|
| 445 |
+
);
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
return await handleSlashCommand(
|
| 449 |
+
result.originalInvocation.raw,
|
| 450 |
+
// Pass the approved commands as a one-time grant for this execution.
|
| 451 |
+
new Set(approvedCommands),
|
| 452 |
+
);
|
| 453 |
+
}
|
| 454 |
+
case 'confirm_action': {
|
| 455 |
+
const { confirmed } = await new Promise<{
|
| 456 |
+
confirmed: boolean;
|
| 457 |
+
}>((resolve) => {
|
| 458 |
+
setConfirmationRequest({
|
| 459 |
+
prompt: result.prompt,
|
| 460 |
+
onConfirm: (resolvedConfirmed) => {
|
| 461 |
+
setConfirmationRequest(null);
|
| 462 |
+
resolve({ confirmed: resolvedConfirmed });
|
| 463 |
+
},
|
| 464 |
+
});
|
| 465 |
+
});
|
| 466 |
+
|
| 467 |
+
if (!confirmed) {
|
| 468 |
+
addItem(
|
| 469 |
+
{
|
| 470 |
+
type: MessageType.INFO,
|
| 471 |
+
text: 'Operation cancelled.',
|
| 472 |
+
},
|
| 473 |
+
Date.now(),
|
| 474 |
+
);
|
| 475 |
+
return { type: 'handled' };
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
return await handleSlashCommand(
|
| 479 |
+
result.originalInvocation.raw,
|
| 480 |
+
undefined,
|
| 481 |
+
true,
|
| 482 |
+
);
|
| 483 |
+
}
|
| 484 |
+
default: {
|
| 485 |
+
const unhandled: never = result;
|
| 486 |
+
throw new Error(
|
| 487 |
+
`Unhandled slash command result: ${unhandled}`,
|
| 488 |
+
);
|
| 489 |
+
}
|
| 490 |
+
}
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
return { type: 'handled' };
|
| 494 |
+
} else if (commandToExecute.subCommands) {
|
| 495 |
+
const helpText = `Command '/${commandToExecute.name}' requires a subcommand. Available:\n${commandToExecute.subCommands
|
| 496 |
+
.map((sc) => ` - ${sc.name}: ${sc.description || ''}`)
|
| 497 |
+
.join('\n')}`;
|
| 498 |
+
addMessage({
|
| 499 |
+
type: MessageType.INFO,
|
| 500 |
+
content: helpText,
|
| 501 |
+
timestamp: new Date(),
|
| 502 |
+
});
|
| 503 |
+
return { type: 'handled' };
|
| 504 |
+
}
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
addMessage({
|
| 508 |
+
type: MessageType.ERROR,
|
| 509 |
+
content: `Unknown command: ${trimmed}`,
|
| 510 |
+
timestamp: new Date(),
|
| 511 |
+
});
|
| 512 |
+
|
| 513 |
+
return { type: 'handled' };
|
| 514 |
+
} catch (e: unknown) {
|
| 515 |
+
hasError = true;
|
| 516 |
+
if (config) {
|
| 517 |
+
const event = makeSlashCommandEvent({
|
| 518 |
+
command: resolvedCommandPath[0],
|
| 519 |
+
subcommand,
|
| 520 |
+
status: SlashCommandStatus.ERROR,
|
| 521 |
+
});
|
| 522 |
+
logSlashCommand(config, event);
|
| 523 |
+
}
|
| 524 |
+
addItem(
|
| 525 |
+
{
|
| 526 |
+
type: MessageType.ERROR,
|
| 527 |
+
text: e instanceof Error ? e.message : String(e),
|
| 528 |
+
},
|
| 529 |
+
Date.now(),
|
| 530 |
+
);
|
| 531 |
+
return { type: 'handled' };
|
| 532 |
+
} finally {
|
| 533 |
+
if (config && resolvedCommandPath[0] && !hasError) {
|
| 534 |
+
const event = makeSlashCommandEvent({
|
| 535 |
+
command: resolvedCommandPath[0],
|
| 536 |
+
subcommand,
|
| 537 |
+
status: SlashCommandStatus.SUCCESS,
|
| 538 |
+
});
|
| 539 |
+
logSlashCommand(config, event);
|
| 540 |
+
}
|
| 541 |
+
setIsProcessing(false);
|
| 542 |
+
}
|
| 543 |
+
},
|
| 544 |
+
[
|
| 545 |
+
config,
|
| 546 |
+
addItem,
|
| 547 |
+
openAuthDialog,
|
| 548 |
+
commands,
|
| 549 |
+
commandContext,
|
| 550 |
+
addMessage,
|
| 551 |
+
openThemeDialog,
|
| 552 |
+
openPrivacyNotice,
|
| 553 |
+
openEditorDialog,
|
| 554 |
+
setQuittingMessages,
|
| 555 |
+
openSettingsDialog,
|
| 556 |
+
setShellConfirmationRequest,
|
| 557 |
+
setSessionShellAllowlist,
|
| 558 |
+
setIsProcessing,
|
| 559 |
+
setConfirmationRequest,
|
| 560 |
+
],
|
| 561 |
+
);
|
| 562 |
+
|
| 563 |
+
return {
|
| 564 |
+
handleSlashCommand,
|
| 565 |
+
slashCommands: commands,
|
| 566 |
+
pendingHistoryItems,
|
| 567 |
+
commandContext,
|
| 568 |
+
shellConfirmationRequest,
|
| 569 |
+
confirmationRequest,
|
| 570 |
+
};
|
| 571 |
+
};
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/useAtCompletion.test.ts
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
/** @vitest-environment jsdom */
|
| 8 |
+
|
| 9 |
+
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
| 10 |
+
import { renderHook, waitFor, act } from '@testing-library/react';
|
| 11 |
+
import { useAtCompletion } from './useAtCompletion.js';
|
| 12 |
+
import {
|
| 13 |
+
Config,
|
| 14 |
+
FileSearch,
|
| 15 |
+
FileSearchFactory,
|
| 16 |
+
} from '@qwen-code/qwen-code-core';
|
| 17 |
+
import {
|
| 18 |
+
createTmpDir,
|
| 19 |
+
cleanupTmpDir,
|
| 20 |
+
FileSystemStructure,
|
| 21 |
+
} from '@qwen-code/qwen-code-test-utils';
|
| 22 |
+
import { useState } from 'react';
|
| 23 |
+
import { Suggestion } from '../components/SuggestionsDisplay.js';
|
| 24 |
+
|
| 25 |
+
// Test harness to capture the state from the hook's callbacks.
|
| 26 |
+
function useTestHarnessForAtCompletion(
|
| 27 |
+
enabled: boolean,
|
| 28 |
+
pattern: string,
|
| 29 |
+
config: Config | undefined,
|
| 30 |
+
cwd: string,
|
| 31 |
+
) {
|
| 32 |
+
const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
|
| 33 |
+
const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false);
|
| 34 |
+
|
| 35 |
+
useAtCompletion({
|
| 36 |
+
enabled,
|
| 37 |
+
pattern,
|
| 38 |
+
config,
|
| 39 |
+
cwd,
|
| 40 |
+
setSuggestions,
|
| 41 |
+
setIsLoadingSuggestions,
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
return { suggestions, isLoadingSuggestions };
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
describe('useAtCompletion', () => {
|
| 48 |
+
let testRootDir: string;
|
| 49 |
+
let mockConfig: Config;
|
| 50 |
+
|
| 51 |
+
beforeEach(() => {
|
| 52 |
+
mockConfig = {
|
| 53 |
+
getFileFilteringOptions: vi.fn(() => ({
|
| 54 |
+
respectGitIgnore: true,
|
| 55 |
+
respectGeminiIgnore: true,
|
| 56 |
+
})),
|
| 57 |
+
getEnableRecursiveFileSearch: () => true,
|
| 58 |
+
} as unknown as Config;
|
| 59 |
+
vi.clearAllMocks();
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
afterEach(async () => {
|
| 63 |
+
if (testRootDir) {
|
| 64 |
+
await cleanupTmpDir(testRootDir);
|
| 65 |
+
}
|
| 66 |
+
vi.restoreAllMocks();
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
describe('File Search Logic', () => {
|
| 70 |
+
it('should perform a recursive search for an empty pattern', async () => {
|
| 71 |
+
const structure: FileSystemStructure = {
|
| 72 |
+
'file.txt': '',
|
| 73 |
+
src: {
|
| 74 |
+
'index.js': '',
|
| 75 |
+
components: ['Button.tsx', 'Button with spaces.tsx'],
|
| 76 |
+
},
|
| 77 |
+
};
|
| 78 |
+
testRootDir = await createTmpDir(structure);
|
| 79 |
+
|
| 80 |
+
const { result } = renderHook(() =>
|
| 81 |
+
useTestHarnessForAtCompletion(true, '', mockConfig, testRootDir),
|
| 82 |
+
);
|
| 83 |
+
|
| 84 |
+
await waitFor(() => {
|
| 85 |
+
expect(result.current.suggestions.length).toBeGreaterThan(0);
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 89 |
+
'src/',
|
| 90 |
+
'src/components/',
|
| 91 |
+
'file.txt',
|
| 92 |
+
'src/components/Button\\ with\\ spaces.tsx',
|
| 93 |
+
'src/components/Button.tsx',
|
| 94 |
+
'src/index.js',
|
| 95 |
+
]);
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
it('should correctly filter the recursive list based on a pattern', async () => {
|
| 99 |
+
const structure: FileSystemStructure = {
|
| 100 |
+
'file.txt': '',
|
| 101 |
+
src: {
|
| 102 |
+
'index.js': '',
|
| 103 |
+
components: {
|
| 104 |
+
'Button.tsx': '',
|
| 105 |
+
},
|
| 106 |
+
},
|
| 107 |
+
};
|
| 108 |
+
testRootDir = await createTmpDir(structure);
|
| 109 |
+
|
| 110 |
+
const { result } = renderHook(() =>
|
| 111 |
+
useTestHarnessForAtCompletion(true, 'src/', mockConfig, testRootDir),
|
| 112 |
+
);
|
| 113 |
+
|
| 114 |
+
await waitFor(() => {
|
| 115 |
+
expect(result.current.suggestions.length).toBeGreaterThan(0);
|
| 116 |
+
});
|
| 117 |
+
|
| 118 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 119 |
+
'src/',
|
| 120 |
+
'src/components/',
|
| 121 |
+
'src/index.js',
|
| 122 |
+
'src/components/Button.tsx',
|
| 123 |
+
]);
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
it('should append a trailing slash to directory paths in suggestions', async () => {
|
| 127 |
+
const structure: FileSystemStructure = {
|
| 128 |
+
'file.txt': '',
|
| 129 |
+
dir: {},
|
| 130 |
+
};
|
| 131 |
+
testRootDir = await createTmpDir(structure);
|
| 132 |
+
|
| 133 |
+
const { result } = renderHook(() =>
|
| 134 |
+
useTestHarnessForAtCompletion(true, '', mockConfig, testRootDir),
|
| 135 |
+
);
|
| 136 |
+
|
| 137 |
+
await waitFor(() => {
|
| 138 |
+
expect(result.current.suggestions.length).toBeGreaterThan(0);
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 142 |
+
'dir/',
|
| 143 |
+
'file.txt',
|
| 144 |
+
]);
|
| 145 |
+
});
|
| 146 |
+
});
|
| 147 |
+
|
| 148 |
+
describe('UI State and Loading Behavior', () => {
|
| 149 |
+
it('should be in a loading state during initial file system crawl', async () => {
|
| 150 |
+
testRootDir = await createTmpDir({});
|
| 151 |
+
const { result } = renderHook(() =>
|
| 152 |
+
useTestHarnessForAtCompletion(true, '', mockConfig, testRootDir),
|
| 153 |
+
);
|
| 154 |
+
|
| 155 |
+
// It's initially true because the effect runs synchronously.
|
| 156 |
+
expect(result.current.isLoadingSuggestions).toBe(true);
|
| 157 |
+
|
| 158 |
+
// Wait for the loading to complete.
|
| 159 |
+
await waitFor(() => {
|
| 160 |
+
expect(result.current.isLoadingSuggestions).toBe(false);
|
| 161 |
+
});
|
| 162 |
+
});
|
| 163 |
+
|
| 164 |
+
it('should NOT show a loading indicator for subsequent searches that complete under 200ms', async () => {
|
| 165 |
+
const structure: FileSystemStructure = { 'a.txt': '', 'b.txt': '' };
|
| 166 |
+
testRootDir = await createTmpDir(structure);
|
| 167 |
+
|
| 168 |
+
const { result, rerender } = renderHook(
|
| 169 |
+
({ pattern }) =>
|
| 170 |
+
useTestHarnessForAtCompletion(true, pattern, mockConfig, testRootDir),
|
| 171 |
+
{ initialProps: { pattern: 'a' } },
|
| 172 |
+
);
|
| 173 |
+
|
| 174 |
+
await waitFor(() => {
|
| 175 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 176 |
+
'a.txt',
|
| 177 |
+
]);
|
| 178 |
+
});
|
| 179 |
+
expect(result.current.isLoadingSuggestions).toBe(false);
|
| 180 |
+
|
| 181 |
+
rerender({ pattern: 'b' });
|
| 182 |
+
|
| 183 |
+
// Wait for the final result
|
| 184 |
+
await waitFor(() => {
|
| 185 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 186 |
+
'b.txt',
|
| 187 |
+
]);
|
| 188 |
+
});
|
| 189 |
+
|
| 190 |
+
expect(result.current.isLoadingSuggestions).toBe(false);
|
| 191 |
+
});
|
| 192 |
+
|
| 193 |
+
it('should show a loading indicator and clear old suggestions for subsequent searches that take longer than 200ms', async () => {
|
| 194 |
+
const structure: FileSystemStructure = { 'a.txt': '', 'b.txt': '' };
|
| 195 |
+
testRootDir = await createTmpDir(structure);
|
| 196 |
+
|
| 197 |
+
const realFileSearch = FileSearchFactory.create({
|
| 198 |
+
projectRoot: testRootDir,
|
| 199 |
+
ignoreDirs: [],
|
| 200 |
+
useGitignore: true,
|
| 201 |
+
useGeminiignore: true,
|
| 202 |
+
cache: false,
|
| 203 |
+
cacheTtl: 0,
|
| 204 |
+
enableRecursiveFileSearch: true,
|
| 205 |
+
});
|
| 206 |
+
await realFileSearch.initialize();
|
| 207 |
+
|
| 208 |
+
const mockFileSearch: FileSearch = {
|
| 209 |
+
initialize: vi.fn().mockResolvedValue(undefined),
|
| 210 |
+
search: vi.fn().mockImplementation(async (...args) => {
|
| 211 |
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
| 212 |
+
return realFileSearch.search(...args);
|
| 213 |
+
}),
|
| 214 |
+
};
|
| 215 |
+
vi.spyOn(FileSearchFactory, 'create').mockReturnValue(mockFileSearch);
|
| 216 |
+
|
| 217 |
+
const { result, rerender } = renderHook(
|
| 218 |
+
({ pattern }) =>
|
| 219 |
+
useTestHarnessForAtCompletion(true, pattern, mockConfig, testRootDir),
|
| 220 |
+
{ initialProps: { pattern: 'a' } },
|
| 221 |
+
);
|
| 222 |
+
|
| 223 |
+
// Wait for the initial (slow) search to complete
|
| 224 |
+
await waitFor(() => {
|
| 225 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 226 |
+
'a.txt',
|
| 227 |
+
]);
|
| 228 |
+
});
|
| 229 |
+
|
| 230 |
+
// Now, rerender to trigger the second search
|
| 231 |
+
rerender({ pattern: 'b' });
|
| 232 |
+
|
| 233 |
+
// Wait for the loading indicator to appear
|
| 234 |
+
await waitFor(() => {
|
| 235 |
+
expect(result.current.isLoadingSuggestions).toBe(true);
|
| 236 |
+
});
|
| 237 |
+
|
| 238 |
+
// Suggestions should be cleared while loading
|
| 239 |
+
expect(result.current.suggestions).toEqual([]);
|
| 240 |
+
|
| 241 |
+
// Wait for the final (slow) search to complete
|
| 242 |
+
await waitFor(
|
| 243 |
+
() => {
|
| 244 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 245 |
+
'b.txt',
|
| 246 |
+
]);
|
| 247 |
+
},
|
| 248 |
+
{ timeout: 1000 },
|
| 249 |
+
); // Increase timeout for the slow search
|
| 250 |
+
|
| 251 |
+
expect(result.current.isLoadingSuggestions).toBe(false);
|
| 252 |
+
});
|
| 253 |
+
|
| 254 |
+
it('should abort the previous search when a new one starts', async () => {
|
| 255 |
+
const structure: FileSystemStructure = { 'a.txt': '', 'b.txt': '' };
|
| 256 |
+
testRootDir = await createTmpDir(structure);
|
| 257 |
+
|
| 258 |
+
const abortSpy = vi.spyOn(AbortController.prototype, 'abort');
|
| 259 |
+
const mockFileSearch: FileSearch = {
|
| 260 |
+
initialize: vi.fn().mockResolvedValue(undefined),
|
| 261 |
+
search: vi.fn().mockImplementation(async (pattern: string) => {
|
| 262 |
+
const delay = pattern === 'a' ? 500 : 50;
|
| 263 |
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
| 264 |
+
return [pattern];
|
| 265 |
+
}),
|
| 266 |
+
};
|
| 267 |
+
vi.spyOn(FileSearchFactory, 'create').mockReturnValue(mockFileSearch);
|
| 268 |
+
|
| 269 |
+
const { result, rerender } = renderHook(
|
| 270 |
+
({ pattern }) =>
|
| 271 |
+
useTestHarnessForAtCompletion(true, pattern, mockConfig, testRootDir),
|
| 272 |
+
{ initialProps: { pattern: 'a' } },
|
| 273 |
+
);
|
| 274 |
+
|
| 275 |
+
// Wait for the hook to be ready (initialization is complete)
|
| 276 |
+
await waitFor(() => {
|
| 277 |
+
expect(mockFileSearch.search).toHaveBeenCalledWith(
|
| 278 |
+
'a',
|
| 279 |
+
expect.any(Object),
|
| 280 |
+
);
|
| 281 |
+
});
|
| 282 |
+
|
| 283 |
+
// Now that the first search is in-flight, trigger the second one.
|
| 284 |
+
act(() => {
|
| 285 |
+
rerender({ pattern: 'b' });
|
| 286 |
+
});
|
| 287 |
+
|
| 288 |
+
// The abort should have been called for the first search.
|
| 289 |
+
expect(abortSpy).toHaveBeenCalledTimes(1);
|
| 290 |
+
|
| 291 |
+
// Wait for the final result, which should be from the second, faster search.
|
| 292 |
+
await waitFor(
|
| 293 |
+
() => {
|
| 294 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual(['b']);
|
| 295 |
+
},
|
| 296 |
+
{ timeout: 1000 },
|
| 297 |
+
);
|
| 298 |
+
|
| 299 |
+
// The search spy should have been called for both patterns.
|
| 300 |
+
expect(mockFileSearch.search).toHaveBeenCalledWith(
|
| 301 |
+
'b',
|
| 302 |
+
expect.any(Object),
|
| 303 |
+
);
|
| 304 |
+
});
|
| 305 |
+
});
|
| 306 |
+
|
| 307 |
+
describe('State Management', () => {
|
| 308 |
+
it('should reset the state when disabled after being in a READY state', async () => {
|
| 309 |
+
const structure: FileSystemStructure = { 'a.txt': '' };
|
| 310 |
+
testRootDir = await createTmpDir(structure);
|
| 311 |
+
|
| 312 |
+
const { result, rerender } = renderHook(
|
| 313 |
+
({ enabled }) =>
|
| 314 |
+
useTestHarnessForAtCompletion(enabled, 'a', mockConfig, testRootDir),
|
| 315 |
+
{ initialProps: { enabled: true } },
|
| 316 |
+
);
|
| 317 |
+
|
| 318 |
+
// Wait for the hook to be ready and have suggestions
|
| 319 |
+
await waitFor(() => {
|
| 320 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 321 |
+
'a.txt',
|
| 322 |
+
]);
|
| 323 |
+
});
|
| 324 |
+
|
| 325 |
+
// Now, disable the hook
|
| 326 |
+
rerender({ enabled: false });
|
| 327 |
+
|
| 328 |
+
// The suggestions should be cleared immediately because of the RESET action
|
| 329 |
+
expect(result.current.suggestions).toEqual([]);
|
| 330 |
+
});
|
| 331 |
+
|
| 332 |
+
it('should reset the state when disabled after being in an ERROR state', async () => {
|
| 333 |
+
testRootDir = await createTmpDir({});
|
| 334 |
+
|
| 335 |
+
// Force an error during initialization
|
| 336 |
+
const mockFileSearch: FileSearch = {
|
| 337 |
+
initialize: vi
|
| 338 |
+
.fn()
|
| 339 |
+
.mockRejectedValue(new Error('Initialization failed')),
|
| 340 |
+
search: vi.fn(),
|
| 341 |
+
};
|
| 342 |
+
vi.spyOn(FileSearchFactory, 'create').mockReturnValue(mockFileSearch);
|
| 343 |
+
|
| 344 |
+
const { result, rerender } = renderHook(
|
| 345 |
+
({ enabled }) =>
|
| 346 |
+
useTestHarnessForAtCompletion(enabled, '', mockConfig, testRootDir),
|
| 347 |
+
{ initialProps: { enabled: true } },
|
| 348 |
+
);
|
| 349 |
+
|
| 350 |
+
// Wait for the hook to enter the error state
|
| 351 |
+
await waitFor(() => {
|
| 352 |
+
expect(result.current.isLoadingSuggestions).toBe(false);
|
| 353 |
+
});
|
| 354 |
+
expect(result.current.suggestions).toEqual([]); // No suggestions on error
|
| 355 |
+
|
| 356 |
+
// Now, disable the hook
|
| 357 |
+
rerender({ enabled: false });
|
| 358 |
+
|
| 359 |
+
// The state should still be reset (though visually it's the same)
|
| 360 |
+
// We can't directly inspect the internal state, but we can ensure it doesn't crash
|
| 361 |
+
// and the suggestions remain empty.
|
| 362 |
+
expect(result.current.suggestions).toEqual([]);
|
| 363 |
+
});
|
| 364 |
+
});
|
| 365 |
+
|
| 366 |
+
describe('Filtering and Configuration', () => {
|
| 367 |
+
it('should respect .gitignore files', async () => {
|
| 368 |
+
const gitignoreContent = ['dist/', '*.log'].join('\n');
|
| 369 |
+
const structure: FileSystemStructure = {
|
| 370 |
+
'.git': {},
|
| 371 |
+
'.gitignore': gitignoreContent,
|
| 372 |
+
dist: {},
|
| 373 |
+
'test.log': '',
|
| 374 |
+
src: {},
|
| 375 |
+
};
|
| 376 |
+
testRootDir = await createTmpDir(structure);
|
| 377 |
+
|
| 378 |
+
const { result } = renderHook(() =>
|
| 379 |
+
useTestHarnessForAtCompletion(true, '', mockConfig, testRootDir),
|
| 380 |
+
);
|
| 381 |
+
|
| 382 |
+
await waitFor(() => {
|
| 383 |
+
expect(result.current.suggestions.length).toBeGreaterThan(0);
|
| 384 |
+
});
|
| 385 |
+
|
| 386 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 387 |
+
'src/',
|
| 388 |
+
'.gitignore',
|
| 389 |
+
]);
|
| 390 |
+
});
|
| 391 |
+
|
| 392 |
+
it('should work correctly when config is undefined', async () => {
|
| 393 |
+
const structure: FileSystemStructure = {
|
| 394 |
+
node_modules: {},
|
| 395 |
+
src: {},
|
| 396 |
+
};
|
| 397 |
+
testRootDir = await createTmpDir(structure);
|
| 398 |
+
|
| 399 |
+
const { result } = renderHook(() =>
|
| 400 |
+
useTestHarnessForAtCompletion(true, '', undefined, testRootDir),
|
| 401 |
+
);
|
| 402 |
+
|
| 403 |
+
await waitFor(() => {
|
| 404 |
+
expect(result.current.suggestions.length).toBeGreaterThan(0);
|
| 405 |
+
});
|
| 406 |
+
|
| 407 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 408 |
+
'node_modules/',
|
| 409 |
+
'src/',
|
| 410 |
+
]);
|
| 411 |
+
});
|
| 412 |
+
|
| 413 |
+
it('should reset and re-initialize when the cwd changes', async () => {
|
| 414 |
+
const structure1: FileSystemStructure = { 'file1.txt': '' };
|
| 415 |
+
const rootDir1 = await createTmpDir(structure1);
|
| 416 |
+
const structure2: FileSystemStructure = { 'file2.txt': '' };
|
| 417 |
+
const rootDir2 = await createTmpDir(structure2);
|
| 418 |
+
|
| 419 |
+
const { result, rerender } = renderHook(
|
| 420 |
+
({ cwd, pattern }) =>
|
| 421 |
+
useTestHarnessForAtCompletion(true, pattern, mockConfig, cwd),
|
| 422 |
+
{
|
| 423 |
+
initialProps: {
|
| 424 |
+
cwd: rootDir1,
|
| 425 |
+
pattern: 'file',
|
| 426 |
+
},
|
| 427 |
+
},
|
| 428 |
+
);
|
| 429 |
+
|
| 430 |
+
// Wait for initial suggestions from the first directory
|
| 431 |
+
await waitFor(() => {
|
| 432 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 433 |
+
'file1.txt',
|
| 434 |
+
]);
|
| 435 |
+
});
|
| 436 |
+
|
| 437 |
+
// Change the CWD
|
| 438 |
+
act(() => {
|
| 439 |
+
rerender({ cwd: rootDir2, pattern: 'file' });
|
| 440 |
+
});
|
| 441 |
+
|
| 442 |
+
// After CWD changes, suggestions should be cleared and it should load again.
|
| 443 |
+
await waitFor(() => {
|
| 444 |
+
expect(result.current.isLoadingSuggestions).toBe(true);
|
| 445 |
+
expect(result.current.suggestions).toEqual([]);
|
| 446 |
+
});
|
| 447 |
+
|
| 448 |
+
// Wait for the new suggestions from the second directory
|
| 449 |
+
await waitFor(() => {
|
| 450 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 451 |
+
'file2.txt',
|
| 452 |
+
]);
|
| 453 |
+
});
|
| 454 |
+
expect(result.current.isLoadingSuggestions).toBe(false);
|
| 455 |
+
|
| 456 |
+
await cleanupTmpDir(rootDir1);
|
| 457 |
+
await cleanupTmpDir(rootDir2);
|
| 458 |
+
});
|
| 459 |
+
|
| 460 |
+
it('should perform a non-recursive search when enableRecursiveFileSearch is false', async () => {
|
| 461 |
+
const structure: FileSystemStructure = {
|
| 462 |
+
'file.txt': '',
|
| 463 |
+
src: {
|
| 464 |
+
'index.js': '',
|
| 465 |
+
},
|
| 466 |
+
};
|
| 467 |
+
testRootDir = await createTmpDir(structure);
|
| 468 |
+
|
| 469 |
+
const nonRecursiveConfig = {
|
| 470 |
+
getEnableRecursiveFileSearch: () => false,
|
| 471 |
+
getFileFilteringOptions: vi.fn(() => ({
|
| 472 |
+
respectGitIgnore: true,
|
| 473 |
+
respectGeminiIgnore: true,
|
| 474 |
+
})),
|
| 475 |
+
} as unknown as Config;
|
| 476 |
+
|
| 477 |
+
const { result } = renderHook(() =>
|
| 478 |
+
useTestHarnessForAtCompletion(
|
| 479 |
+
true,
|
| 480 |
+
'',
|
| 481 |
+
nonRecursiveConfig,
|
| 482 |
+
testRootDir,
|
| 483 |
+
),
|
| 484 |
+
);
|
| 485 |
+
|
| 486 |
+
await waitFor(() => {
|
| 487 |
+
expect(result.current.suggestions.length).toBeGreaterThan(0);
|
| 488 |
+
});
|
| 489 |
+
|
| 490 |
+
// Should only contain top-level items
|
| 491 |
+
expect(result.current.suggestions.map((s) => s.value)).toEqual([
|
| 492 |
+
'src/',
|
| 493 |
+
'file.txt',
|
| 494 |
+
]);
|
| 495 |
+
});
|
| 496 |
+
});
|
| 497 |
+
});
|
projects/ui/qwen-code/packages/cli/src/ui/hooks/useAtCompletion.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 8 |
+
import {
|
| 9 |
+
Config,
|
| 10 |
+
FileSearch,
|
| 11 |
+
FileSearchFactory,
|
| 12 |
+
escapePath,
|
| 13 |
+
} from '@qwen-code/qwen-code-core';
|
| 14 |
+
import {
|
| 15 |
+
Suggestion,
|
| 16 |
+
MAX_SUGGESTIONS_TO_SHOW,
|
| 17 |
+
} from '../components/SuggestionsDisplay.js';
|
| 18 |
+
|
| 19 |
+
export enum AtCompletionStatus {
|
| 20 |
+
IDLE = 'idle',
|
| 21 |
+
INITIALIZING = 'initializing',
|
| 22 |
+
READY = 'ready',
|
| 23 |
+
SEARCHING = 'searching',
|
| 24 |
+
ERROR = 'error',
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
interface AtCompletionState {
|
| 28 |
+
status: AtCompletionStatus;
|
| 29 |
+
suggestions: Suggestion[];
|
| 30 |
+
isLoading: boolean;
|
| 31 |
+
pattern: string | null;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
type AtCompletionAction =
|
| 35 |
+
| { type: 'INITIALIZE' }
|
| 36 |
+
| { type: 'INITIALIZE_SUCCESS' }
|
| 37 |
+
| { type: 'SEARCH'; payload: string }
|
| 38 |
+
| { type: 'SEARCH_SUCCESS'; payload: Suggestion[] }
|
| 39 |
+
| { type: 'SET_LOADING'; payload: boolean }
|
| 40 |
+
| { type: 'ERROR' }
|
| 41 |
+
| { type: 'RESET' };
|
| 42 |
+
|
| 43 |
+
const initialState: AtCompletionState = {
|
| 44 |
+
status: AtCompletionStatus.IDLE,
|
| 45 |
+
suggestions: [],
|
| 46 |
+
isLoading: false,
|
| 47 |
+
pattern: null,
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
function atCompletionReducer(
|
| 51 |
+
state: AtCompletionState,
|
| 52 |
+
action: AtCompletionAction,
|
| 53 |
+
): AtCompletionState {
|
| 54 |
+
switch (action.type) {
|
| 55 |
+
case 'INITIALIZE':
|
| 56 |
+
return {
|
| 57 |
+
...state,
|
| 58 |
+
status: AtCompletionStatus.INITIALIZING,
|
| 59 |
+
isLoading: true,
|
| 60 |
+
};
|
| 61 |
+
case 'INITIALIZE_SUCCESS':
|
| 62 |
+
return { ...state, status: AtCompletionStatus.READY, isLoading: false };
|
| 63 |
+
case 'SEARCH':
|
| 64 |
+
// Keep old suggestions, don't set loading immediately
|
| 65 |
+
return {
|
| 66 |
+
...state,
|
| 67 |
+
status: AtCompletionStatus.SEARCHING,
|
| 68 |
+
pattern: action.payload,
|
| 69 |
+
};
|
| 70 |
+
case 'SEARCH_SUCCESS':
|
| 71 |
+
return {
|
| 72 |
+
...state,
|
| 73 |
+
status: AtCompletionStatus.READY,
|
| 74 |
+
suggestions: action.payload,
|
| 75 |
+
isLoading: false,
|
| 76 |
+
};
|
| 77 |
+
case 'SET_LOADING':
|
| 78 |
+
// Only show loading if we are still in a searching state
|
| 79 |
+
if (state.status === AtCompletionStatus.SEARCHING) {
|
| 80 |
+
return { ...state, isLoading: action.payload, suggestions: [] };
|
| 81 |
+
}
|
| 82 |
+
return state;
|
| 83 |
+
case 'ERROR':
|
| 84 |
+
return {
|
| 85 |
+
...state,
|
| 86 |
+
status: AtCompletionStatus.ERROR,
|
| 87 |
+
isLoading: false,
|
| 88 |
+
suggestions: [],
|
| 89 |
+
};
|
| 90 |
+
case 'RESET':
|
| 91 |
+
return initialState;
|
| 92 |
+
default:
|
| 93 |
+
return state;
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
export interface UseAtCompletionProps {
|
| 98 |
+
enabled: boolean;
|
| 99 |
+
pattern: string;
|
| 100 |
+
config: Config | undefined;
|
| 101 |
+
cwd: string;
|
| 102 |
+
setSuggestions: (suggestions: Suggestion[]) => void;
|
| 103 |
+
setIsLoadingSuggestions: (isLoading: boolean) => void;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
export function useAtCompletion(props: UseAtCompletionProps): void {
|
| 107 |
+
const {
|
| 108 |
+
enabled,
|
| 109 |
+
pattern,
|
| 110 |
+
config,
|
| 111 |
+
cwd,
|
| 112 |
+
setSuggestions,
|
| 113 |
+
setIsLoadingSuggestions,
|
| 114 |
+
} = props;
|
| 115 |
+
const [state, dispatch] = useReducer(atCompletionReducer, initialState);
|
| 116 |
+
const fileSearch = useRef<FileSearch | null>(null);
|
| 117 |
+
const searchAbortController = useRef<AbortController | null>(null);
|
| 118 |
+
const slowSearchTimer = useRef<NodeJS.Timeout | null>(null);
|
| 119 |
+
|
| 120 |
+
useEffect(() => {
|
| 121 |
+
setSuggestions(state.suggestions);
|
| 122 |
+
}, [state.suggestions, setSuggestions]);
|
| 123 |
+
|
| 124 |
+
useEffect(() => {
|
| 125 |
+
setIsLoadingSuggestions(state.isLoading);
|
| 126 |
+
}, [state.isLoading, setIsLoadingSuggestions]);
|
| 127 |
+
|
| 128 |
+
useEffect(() => {
|
| 129 |
+
dispatch({ type: 'RESET' });
|
| 130 |
+
}, [cwd, config]);
|
| 131 |
+
|
| 132 |
+
// Reacts to user input (`pattern`) ONLY.
|
| 133 |
+
useEffect(() => {
|
| 134 |
+
if (!enabled) {
|
| 135 |
+
// reset when first getting out of completion suggestions
|
| 136 |
+
if (
|
| 137 |
+
state.status === AtCompletionStatus.READY ||
|
| 138 |
+
state.status === AtCompletionStatus.ERROR
|
| 139 |
+
) {
|
| 140 |
+
dispatch({ type: 'RESET' });
|
| 141 |
+
}
|
| 142 |
+
return;
|
| 143 |
+
}
|
| 144 |
+
if (pattern === null) {
|
| 145 |
+
dispatch({ type: 'RESET' });
|
| 146 |
+
return;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
if (state.status === AtCompletionStatus.IDLE) {
|
| 150 |
+
dispatch({ type: 'INITIALIZE' });
|
| 151 |
+
} else if (
|
| 152 |
+
(state.status === AtCompletionStatus.READY ||
|
| 153 |
+
state.status === AtCompletionStatus.SEARCHING) &&
|
| 154 |
+
pattern !== state.pattern // Only search if the pattern has changed
|
| 155 |
+
) {
|
| 156 |
+
dispatch({ type: 'SEARCH', payload: pattern });
|
| 157 |
+
}
|
| 158 |
+
}, [enabled, pattern, state.status, state.pattern]);
|
| 159 |
+
|
| 160 |
+
// The "Worker" that performs async operations based on status.
|
| 161 |
+
useEffect(() => {
|
| 162 |
+
const initialize = async () => {
|
| 163 |
+
try {
|
| 164 |
+
const searcher = FileSearchFactory.create({
|
| 165 |
+
projectRoot: cwd,
|
| 166 |
+
ignoreDirs: [],
|
| 167 |
+
useGitignore:
|
| 168 |
+
config?.getFileFilteringOptions()?.respectGitIgnore ?? true,
|
| 169 |
+
useGeminiignore:
|
| 170 |
+
config?.getFileFilteringOptions()?.respectGeminiIgnore ?? true,
|
| 171 |
+
cache: true,
|
| 172 |
+
cacheTtl: 30, // 30 seconds
|
| 173 |
+
enableRecursiveFileSearch:
|
| 174 |
+
config?.getEnableRecursiveFileSearch() ?? true,
|
| 175 |
+
});
|
| 176 |
+
await searcher.initialize();
|
| 177 |
+
fileSearch.current = searcher;
|
| 178 |
+
dispatch({ type: 'INITIALIZE_SUCCESS' });
|
| 179 |
+
if (state.pattern !== null) {
|
| 180 |
+
dispatch({ type: 'SEARCH', payload: state.pattern });
|
| 181 |
+
}
|
| 182 |
+
} catch (_) {
|
| 183 |
+
dispatch({ type: 'ERROR' });
|
| 184 |
+
}
|
| 185 |
+
};
|
| 186 |
+
|
| 187 |
+
const search = async () => {
|
| 188 |
+
if (!fileSearch.current || state.pattern === null) {
|
| 189 |
+
return;
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
if (slowSearchTimer.current) {
|
| 193 |
+
clearTimeout(slowSearchTimer.current);
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
const controller = new AbortController();
|
| 197 |
+
searchAbortController.current = controller;
|
| 198 |
+
|
| 199 |
+
slowSearchTimer.current = setTimeout(() => {
|
| 200 |
+
dispatch({ type: 'SET_LOADING', payload: true });
|
| 201 |
+
}, 200);
|
| 202 |
+
|
| 203 |
+
try {
|
| 204 |
+
const results = await fileSearch.current.search(state.pattern, {
|
| 205 |
+
signal: controller.signal,
|
| 206 |
+
maxResults: MAX_SUGGESTIONS_TO_SHOW * 3,
|
| 207 |
+
});
|
| 208 |
+
|
| 209 |
+
if (slowSearchTimer.current) {
|
| 210 |
+
clearTimeout(slowSearchTimer.current);
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
if (controller.signal.aborted) {
|
| 214 |
+
return;
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
const suggestions = results.map((p) => ({
|
| 218 |
+
label: p,
|
| 219 |
+
value: escapePath(p),
|
| 220 |
+
}));
|
| 221 |
+
dispatch({ type: 'SEARCH_SUCCESS', payload: suggestions });
|
| 222 |
+
} catch (error) {
|
| 223 |
+
if (!(error instanceof Error && error.name === 'AbortError')) {
|
| 224 |
+
dispatch({ type: 'ERROR' });
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
};
|
| 228 |
+
|
| 229 |
+
if (state.status === AtCompletionStatus.INITIALIZING) {
|
| 230 |
+
initialize();
|
| 231 |
+
} else if (state.status === AtCompletionStatus.SEARCHING) {
|
| 232 |
+
search();
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
return () => {
|
| 236 |
+
searchAbortController.current?.abort();
|
| 237 |
+
if (slowSearchTimer.current) {
|
| 238 |
+
clearTimeout(slowSearchTimer.current);
|
| 239 |
+
}
|
| 240 |
+
};
|
| 241 |
+
}, [state.status, state.pattern, config, cwd]);
|
| 242 |
+
}
|