Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions packages/cli/src/ui/AppContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,7 @@ export const AppContainer = (props: AppContainerProps) => {
isConfigInitialized,
logger,
setSessionName,
historyManager.updateItem,
);

// onDebugMessage should log to debug logfile, not update footer debugMessage
Expand Down Expand Up @@ -1141,10 +1142,12 @@ export const AppContainer = (props: AppContainerProps) => {
.filter(Boolean)
.join('');
if (text) {
historyManager.addItem(
{ type: 'user' as const, text },
now,
);
const userHistoryItem = {
type: 'user',
text,
sentToModel: true,
} satisfies HistoryItemWithoutId;
historyManager.addItem(userHistoryItem, now);
}
}
// functionResponse parts are rendered as part of the tool_group below
Expand Down Expand Up @@ -2240,7 +2243,8 @@ export const AppContainer = (props: AppContainerProps) => {
if (dialogsVisible) return;
if (messageQueue.length === 0) return;

// Two-phase: batch plain prompts as one turn, else pop next slash command.
// Batch the leading plain-prompt run; if the queue starts with a slash
// command, submit that segment on its own to preserve typed order.
const plainPrompts = drainQueue();
const submission =
plainPrompts.length > 0 ? plainPrompts.join('\n\n') : popNextSegment();
Expand Down
244 changes: 207 additions & 37 deletions packages/cli/src/ui/hooks/slashCommandProcessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@

import { act, renderHook, waitFor } from '@testing-library/react';
import { vi, describe, it, expect, beforeEach } from 'vitest';
import { useSlashCommandProcessor } from './slashCommandProcessor.js';
import {
useSlashCommandProcessor,
type SlashCommandProcessorActions,
} from './slashCommandProcessor.js';
import type {
CommandContext,
ConfirmShellCommandsActionReturn,
Expand All @@ -26,6 +29,8 @@ import {
makeFakeConfig,
} from '@qwen-code/qwen-code-core';

type SlashCommandProcessorActionsArg = SlashCommandProcessorActions;

const { logSlashCommand } = vi.hoisted(() => ({
logSlashCommand: vi.fn(),
}));
Expand Down Expand Up @@ -107,6 +112,7 @@ function createTestCommand(

describe('useSlashCommandProcessor', () => {
const mockAddItem = vi.fn();
const mockUpdateItem = vi.fn();
const mockClearItems = vi.fn();
const mockLoadHistory = vi.fn();
const mockOpenThemeDialog = vi.fn();
Expand All @@ -121,8 +127,36 @@ describe('useSlashCommandProcessor', () => {
});
const mockSettings = {} as LoadedSettings;

const createMockActions = (): SlashCommandProcessorActionsArg => ({
openAuthDialog: mockOpenAuthDialog,
openArenaDialog: vi.fn(),
openThemeDialog: mockOpenThemeDialog,
openEditorDialog: vi.fn(),
openMemoryDialog: mockOpenMemoryDialog,
openSettingsDialog: vi.fn(),
openModelDialog: mockOpenModelDialog,
openManageModelsDialog: vi.fn(),
openTrustDialog: vi.fn(),
openPermissionsDialog: vi.fn(),
openApprovalModeDialog: vi.fn(),
openResumeDialog: vi.fn(),
handleResume: vi.fn(),
openDeleteDialog: vi.fn(),
quit: mockSetQuittingMessages,
setDebugMessage: vi.fn(),
dispatchExtensionStateUpdate: vi.fn(),
addConfirmUpdateExtensionRequest: vi.fn(),
openSubagentCreateDialog: vi.fn(),
openAgentsManagerDialog: vi.fn(),
openExtensionsManagerDialog: vi.fn(),
openMcpDialog: vi.fn(),
openHooksDialog: vi.fn(),
openRewindSelector: vi.fn(),
});

beforeEach(() => {
vi.clearAllMocks();
mockAddItem.mockReturnValue(1);
vi.mocked(BuiltinCommandLoader).mockClear();
mockBuiltinLoadCommands.mockResolvedValue([]);
mockFileLoadCommands.mockResolvedValue([]);
Expand Down Expand Up @@ -154,27 +188,12 @@ describe('useSlashCommandProcessor', () => {
setIsProcessing,
{ current: true }, // isIdleRef
vi.fn(), // setGeminiMdFileCount
{
openAuthDialog: mockOpenAuthDialog,
openThemeDialog: mockOpenThemeDialog,
openEditorDialog: vi.fn(),
openMemoryDialog: mockOpenMemoryDialog,
openSettingsDialog: vi.fn(),
openModelDialog: mockOpenModelDialog,
openTrustDialog: vi.fn(),
openPermissionsDialog: vi.fn(),
openApprovalModeDialog: vi.fn(),
openResumeDialog: vi.fn(),
quit: mockSetQuittingMessages,
setDebugMessage: vi.fn(),
dispatchExtensionStateUpdate: vi.fn(),
addConfirmUpdateExtensionRequest: vi.fn(),
openSubagentCreateDialog: vi.fn(),
openAgentsManagerDialog: vi.fn(),
},
createMockActions(),
new Map(), // extensionsUpdateState
true, // isConfigInitialized
null, // logger
undefined, // setSessionName
mockUpdateItem,
),
);

Expand Down Expand Up @@ -270,6 +289,24 @@ describe('useSlashCommandProcessor', () => {
);
});

it('should keep a bare slash in the slash command flow', async () => {
const result = setupProcessorHook();
await waitFor(() => expect(result.current.slashCommands).toBeDefined());

const commandResult = await act(async () =>
result.current.handleSlashCommand('/'),
);

expect(commandResult).toEqual({ type: 'handled' });
expect(mockAddItem).toHaveBeenLastCalledWith(
{
type: MessageType.ERROR,
text: 'Unknown command: /',
},
expect.any(Number),
);
});

it('should display help for a parent command invoked without a subcommand', async () => {
const parentCommand: SlashCommand = {
name: 'parent',
Expand Down Expand Up @@ -582,6 +619,7 @@ describe('useSlashCommandProcessor', () => {
{ type: MessageType.USER, text: '/filecmd' },
expect.any(Number),
);
expect(mockUpdateItem).toHaveBeenCalledWith(1, { sentToModel: true });
});

it('should handle "submit_prompt" action returned from a mcp-based command', async () => {
Expand Down Expand Up @@ -614,6 +652,7 @@ describe('useSlashCommandProcessor', () => {
{ type: MessageType.USER, text: '/mcpcmd' },
expect.any(Number),
);
expect(mockUpdateItem).toHaveBeenCalledWith(1, { sentToModel: true });
});
});

Expand Down Expand Up @@ -829,6 +868,23 @@ describe('useSlashCommandProcessor', () => {
);
});

it('should correctly match the help alias via slash prefix', async () => {
const action = vi.fn();
const command = createTestCommand({
name: 'help',
altNames: ['?'],
action,
});
const result = setupProcessorHook([command]);
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));

await act(async () => {
await result.current.handleSlashCommand('/?');
});

expect(action).toHaveBeenCalledTimes(1);
});

it('should handle extra whitespace around the command', async () => {
const action = vi.fn();
const command = createTestCommand({ name: 'test', action });
Expand All @@ -842,6 +898,137 @@ describe('useSlashCommandProcessor', () => {
expect(action).toHaveBeenCalledWith(expect.anything(), 'with-args');
});

it('should execute Unicode custom commands', async () => {
const action = vi.fn();
const command = createTestCommand({ name: '文档', action });
const result = setupProcessorHook([command]);
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));

await act(async () => {
await result.current.handleSlashCommand('/文档 查看内容');
});

expect(action).toHaveBeenCalledWith(expect.anything(), '查看内容');
});

it('should execute extension-qualified commands with dots', async () => {
const action = vi.fn();
const command = createTestCommand({ name: 'gcp.deploy', action });
const result = setupProcessorHook([command]);
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));

await act(async () => {
await result.current.handleSlashCommand('/gcp.deploy with-args');
});

expect(action).toHaveBeenCalledWith(expect.anything(), 'with-args');
});

it('should execute loaded commands with filename punctuation', async () => {
const action = vi.fn();
const command = createTestCommand({ name: 'deploy@prod', action });
const result = setupProcessorHook([command]);
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));

await act(async () => {
await result.current.handleSlashCommand('/deploy@prod with-args');
});

expect(action).toHaveBeenCalledWith(expect.anything(), 'with-args');
});

it('should execute loaded commands before falling back for slash-prefixed input with args', async () => {
const action = vi.fn();
const command = createTestCommand({ name: 'tmp', action });
const result = setupProcessorHook([command]);
await waitFor(() => expect(result.current.slashCommands).toHaveLength(1));

await act(async () => {
await result.current.handleSlashCommand('/tmp inspect');
});

expect(action).toHaveBeenCalledWith(expect.anything(), 'inspect');
expect(mockAddItem).not.toHaveBeenCalledWith(
expect.objectContaining({ type: MessageType.ERROR }),
expect.any(Number),
);
});

it('should return false for file-path-like input (issue #1804)', async () => {
const result = setupProcessorHook();
await waitFor(() => expect(result.current.slashCommands).toBeDefined());

// File paths should not enter the slash command flow when the first
// token contains a path separator.
const pathResult = await act(async () =>
result.current.handleSlashCommand('/api/apiFunction/接口的实现'),
);
expect(pathResult).toBe(false);

const absPathResult = await act(async () =>
result.current.handleSlashCommand(
'/Users/zhoushuo/Desktop/dw-operator-skill 帮我安装',
),
);
expect(absPathResult).toBe(false);
});

it('should return false for unknown slash-prefixed input with arguments', async () => {
const result = setupProcessorHook();
await waitFor(() => expect(result.current.slashCommands).toBeDefined());

const tmpResult = await act(async () =>
result.current.handleSlashCommand('/tmp inspect'),
);
const etcResult = await act(async () =>
result.current.handleSlashCommand('/etc explain'),
);
const readmeResult = await act(async () =>
result.current.handleSlashCommand('/README.md summarize'),
);
const dataResult = await act(async () =>
result.current.handleSlashCommand('/data foo'),
);
const vendorResult = await act(async () =>
result.current.handleSlashCommand('/vendor explain'),
);
const workspaceResult = await act(async () =>
result.current.handleSlashCommand('/workspace check'),
);

expect(tmpResult).toBe(false);
expect(etcResult).toBe(false);
expect(readmeResult).toBe(false);
expect(dataResult).toBe(false);
expect(vendorResult).toBe(false);
expect(workspaceResult).toBe(false);
expect(mockAddItem).not.toHaveBeenCalled();
});

it('should return false for slash-prefixed shell-metacharacter input', async () => {
const result = setupProcessorHook();
await waitFor(() => expect(result.current.slashCommands).toBeDefined());

const envResult = await act(async () =>
result.current.handleSlashCommand('/$HOME'),
);
const bangResult = await act(async () =>
result.current.handleSlashCommand('/!important'),
);
const pipeResult = await act(async () =>
result.current.handleSlashCommand('/|pipe'),
);
const semicolonResult = await act(async () =>
result.current.handleSlashCommand('/;comment'),
);

expect(envResult).toBe(false);
expect(bangResult).toBe(false);
expect(pipeResult).toBe(false);
expect(semicolonResult).toBe(false);
expect(mockAddItem).not.toHaveBeenCalled();
});

it('should handle `?` as a command prefix', async () => {
const action = vi.fn();
const command = createTestCommand({ name: 'help', action });
Expand Down Expand Up @@ -968,24 +1155,7 @@ describe('useSlashCommandProcessor', () => {
vi.fn(), // setIsProcessing
{ current: true }, // isIdleRef
vi.fn(), // setGeminiMdFileCount
{
openAuthDialog: mockOpenAuthDialog,
openThemeDialog: mockOpenThemeDialog,
openEditorDialog: vi.fn(),
openMemoryDialog: mockOpenMemoryDialog,
openSettingsDialog: vi.fn(),
openModelDialog: vi.fn(),
openTrustDialog: vi.fn(),
openPermissionsDialog: vi.fn(),
openApprovalModeDialog: vi.fn(),
openResumeDialog: vi.fn(),
quit: mockSetQuittingMessages,
setDebugMessage: vi.fn(),
dispatchExtensionStateUpdate: vi.fn(),
addConfirmUpdateExtensionRequest: vi.fn(),
openSubagentCreateDialog: vi.fn(),
openAgentsManagerDialog: vi.fn(),
},
createMockActions(),
new Map(), // extensionsUpdateState
true, // isConfigInitialized
null, // logger
Expand Down
Loading
Loading