fix(webui): drive slash command routing from metadata

This commit is contained in:
chengyongru
2026-07-07 15:42:04 +08:00
committed by Xubin Ren
parent 8a231b6e4d
commit fa73448f6f
10 changed files with 243 additions and 68 deletions
+50 -49
View File
@@ -90,47 +90,49 @@ import { cn } from "@/lib/utils";
const ACCEPT_ATTR = "image/png,image/jpeg,image/webp,image/gif";
const VOICE_SHORTCUT_CODE = "KeyD";
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
const FALLBACK_SIDE_CHANNEL_COMMANDS = new Set([
"/new",
"/stop",
"/restart",
"/status",
"/model",
"/history",
"/goal",
"/trigger",
"/dream",
"/dream-log",
"/dream-restore",
"/dream-prompt",
"/skill",
"/help",
"/pairing",
]);
type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows";
type ResolvedSlashCommandLifecycle =
| "side_channel"
| "finalize_active_turn"
| "stop_active_turn"
| "agent_turn";
function slashCommandName(content: string): string {
return content.split(/\s+/, 1)[0];
}
function isExactSlashCommand(content: string, commandName: string): boolean {
if (slashCommandName(content) !== commandName) return false;
return content.slice(commandName.length).trim().length === 0;
function slashCommandArgs(content: string, commandName: string): string {
return content.slice(commandName.length).trim();
}
function shouldFinalizeActiveTurn(content: string): boolean {
return isExactSlashCommand(content, "/new");
}
function isSlashCommandSideChannel(content: string, visibleSlashCommands: SlashCommand[]): boolean {
function matchingSlashCommand(content: string, slashCommands: SlashCommand[]): SlashCommand | null {
const commandName = slashCommandName(content);
if (!commandName.startsWith("/")) return false;
if (commandName === "/goal" && content.slice(commandName.length).trim().length > 0) {
return false;
if (!commandName.startsWith("/")) return null;
const command = slashCommands.find((item) => item.command === commandName);
if (!command) return null;
if (slashCommandArgs(content, command.command).length > 0 && !command.acceptsArgs) return null;
return command;
}
function slashCommandLifecycle(
content: string,
slashCommands: SlashCommand[],
): ResolvedSlashCommandLifecycle | null {
const command = matchingSlashCommand(content, slashCommands);
if (!command) return null;
if (command.lifecycle === "agent_turn_with_args") {
return slashCommandArgs(content, command.command).length > 0
? "agent_turn"
: "side_channel";
}
return command.lifecycle;
}
function isSideChannelLifecycle(lifecycle: ResolvedSlashCommandLifecycle | null): boolean {
return (
FALLBACK_SIDE_CHANNEL_COMMANDS.has(commandName)
|| visibleSlashCommands.some((command) => command.command === commandName)
lifecycle === "side_channel"
|| lifecycle === "finalize_active_turn"
|| lifecycle === "stop_active_turn"
);
}
@@ -310,7 +312,12 @@ type MentionCandidate =
| { kind: "cli"; name: string; app: CliAppInfo }
| { kind: "mcp"; name: string; preset: McpPresetInfo };
interface SlashPaletteCommand extends SlashCommand {
interface SlashPaletteCommand {
command: string;
title: string;
description: string;
icon: string;
argHint?: string;
detail: string;
badge?: string;
recent: boolean;
@@ -968,18 +975,12 @@ export function ThreadComposer({
}, [cursorPosition, disabled, slashMenuDismissed, value]);
const visibleSlashCommands = useMemo(() => {
const baseCommands = slashCommands.filter((command) => command.command !== "/stop");
const baseCommands = slashCommands.filter(
(command) => command.command !== "/stop" && command.command !== "/restart",
);
if (!(isStreaming && onStop)) return baseCommands;
const stopCommand = slashCommands.find((command) => command.command === "/stop") ?? {
command: "/stop",
title: "Stop current task",
description: "Cancel the active agent turn for this chat.",
icon: "square",
};
return [
stopCommand,
...baseCommands,
];
const stopCommand = slashCommands.find((command) => command.command === "/stop");
return stopCommand ? [stopCommand, ...baseCommands] : baseCommands;
}, [isStreaming, onStop, slashCommands]);
const filteredSlashCommands = useMemo<SlashPaletteCommand[]>(() => {
@@ -1526,11 +1527,13 @@ export function ThreadComposer({
payload === undefined
&& attachedCliApps.length === 0
&& attachedMcpPresets.length === 0;
const slashLifecycle = hasPlainTextCommandPayload
? slashCommandLifecycle(content, slashCommands)
: null;
if (
hasPlainTextCommandPayload
slashLifecycle === "stop_active_turn"
&& isStreaming
&& onStop
&& isExactSlashCommand(content, "/stop")
) {
handleStop();
setQueuedPrompts([]);
@@ -1538,11 +1541,9 @@ export function ThreadComposer({
clearComposerText();
return;
}
const isSlashSideChannel =
hasPlainTextCommandPayload
&& isSlashCommandSideChannel(content, visibleSlashCommands);
const isSlashSideChannel = isSideChannelLifecycle(slashLifecycle);
const finalizeActiveTurn =
isSlashSideChannel && shouldFinalizeActiveTurn(content);
slashLifecycle === "finalize_active_turn";
onSend(
content,
payload,
@@ -1572,8 +1573,8 @@ export function ThreadComposer({
onSend,
onStop,
readyImages,
slashCommands,
value,
visibleSlashCommands,
]);
const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
+29 -8
View File
@@ -20,6 +20,7 @@ import type {
SkillDetail,
SkillsPayload,
SlashCommand,
SlashCommandLifecycle,
TranscriptionSettingsUpdate,
WebSearchSettingsUpdate,
WorkspacesPayload,
@@ -29,6 +30,20 @@ import type {
import { fetchWithTimeout } from "./http";
const API_READ_TIMEOUT_MS = 20_000;
const SLASH_COMMAND_LIFECYCLES = new Set<SlashCommandLifecycle>([
"side_channel",
"finalize_active_turn",
"stop_active_turn",
"agent_turn",
"agent_turn_with_args",
]);
function isSlashCommandLifecycle(value: unknown): value is SlashCommandLifecycle {
return (
typeof value === "string"
&& SLASH_COMMAND_LIFECYCLES.has(value as SlashCommandLifecycle)
);
}
export class ApiError extends Error {
status: number;
@@ -498,6 +513,8 @@ export async function listSlashCommands(
description: string;
icon: string;
arg_hint?: string;
lifecycle?: unknown;
accepts_args?: unknown;
};
const body = await request<{ commands: Row[] }>(
`${base}/api/commands`,
@@ -506,14 +523,18 @@ export async function listSlashCommands(
API_READ_TIMEOUT_MS,
);
return body.commands
.filter((command) => !["/stop", "/restart"].includes(command.command))
.map((command) => ({
command: command.command,
title: command.title,
description: command.description,
icon: command.icon,
argHint: command.arg_hint ?? "",
}));
.flatMap((command) => {
if (!isSlashCommandLifecycle(command.lifecycle)) return [];
return [{
command: command.command,
title: command.title,
description: command.description,
icon: command.icon,
argHint: command.arg_hint ?? "",
lifecycle: command.lifecycle,
acceptsArgs: command.accepts_args === true,
}];
});
}
export async function fetchSidebarState(
+9
View File
@@ -781,12 +781,21 @@ export interface TranscriptionSettingsUpdate {
maxUploadMb: number;
}
export type SlashCommandLifecycle =
| "side_channel"
| "finalize_active_turn"
| "stop_active_turn"
| "agent_turn"
| "agent_turn_with_args";
export interface SlashCommand {
command: string;
title: string;
description: string;
icon: string;
argHint?: string;
lifecycle: SlashCommandLifecycle;
acceptsArgs: boolean;
}
export type ConnectionStatus =
+32
View File
@@ -674,12 +674,16 @@ describe("webui API helpers", () => {
title: "Stop current task",
description: "Cancel the active task.",
icon: "square",
lifecycle: "stop_active_turn",
accepts_args: false,
},
{
command: "/restart",
title: "Restart nanobot",
description: "Restart the bot process.",
icon: "rotate-cw",
lifecycle: "side_channel",
accepts_args: false,
},
{
command: "/history",
@@ -687,18 +691,46 @@ describe("webui API helpers", () => {
description: "Print the last N messages.",
icon: "history",
arg_hint: "[n]",
lifecycle: "side_channel",
accepts_args: true,
},
{
command: "/legacy",
title: "Legacy row",
description: "Old metadata should not be guessed.",
icon: "circle-help",
},
],
}),
} as Response);
await expect(listSlashCommands("tok")).resolves.toEqual([
{
command: "/stop",
title: "Stop current task",
description: "Cancel the active task.",
icon: "square",
argHint: "",
lifecycle: "stop_active_turn",
acceptsArgs: false,
},
{
command: "/restart",
title: "Restart nanobot",
description: "Restart the bot process.",
icon: "rotate-cw",
argHint: "",
lifecycle: "side_channel",
acceptsArgs: false,
},
{
command: "/history",
title: "Show conversation history",
description: "Print the last N messages.",
icon: "history",
argHint: "[n]",
lifecycle: "side_channel",
acceptsArgs: true,
},
]);
expect(fetch).toHaveBeenCalledWith(
+77 -3
View File
@@ -19,6 +19,8 @@ const COMMANDS: SlashCommand[] = [
title: "Stop current task",
description: "Cancel the active agent turn.",
icon: "square",
lifecycle: "stop_active_turn",
acceptsArgs: false,
},
{
command: "/history",
@@ -26,6 +28,8 @@ const COMMANDS: SlashCommand[] = [
description: "Print the last N persisted messages.",
icon: "history",
argHint: "[n]",
lifecycle: "side_channel",
acceptsArgs: true,
},
];
@@ -863,6 +867,8 @@ describe("ThreadComposer", () => {
description: "Show or switch the active model preset.",
icon: "brain",
argHint: "[preset]",
lifecycle: "side_channel",
acceptsArgs: true,
},
COMMANDS[1],
]}
@@ -886,7 +892,7 @@ describe("ThreadComposer", () => {
onStop={onStop}
isStreaming
placeholder="Type your message..."
slashCommands={[COMMANDS[1]]}
slashCommands={COMMANDS}
/>,
);
@@ -940,6 +946,8 @@ describe("ThreadComposer", () => {
title: `Command ${index}`,
description: `Description ${index}`,
icon: "activity",
lifecycle: "side_channel",
acceptsArgs: false,
}))}
/>,
);
@@ -1329,7 +1337,7 @@ describe("ThreadComposer", () => {
expect(onSend).toHaveBeenCalledWith("/history", undefined, { sideChannel: true });
});
it("marks builtin slash commands as side-channel sends before command metadata loads", () => {
it("does not infer side-channel behavior before command metadata loads", () => {
const onSend = vi.fn();
render(
<ThreadComposer
@@ -1342,7 +1350,7 @@ describe("ThreadComposer", () => {
fireEvent.change(input, { target: { value: "/status" } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("/status", undefined, { sideChannel: true });
expect(onSend).toHaveBeenCalledWith("/status", undefined, undefined);
});
it("marks new chat commands as side-channel sends that finalize the active turn", () => {
@@ -1351,6 +1359,16 @@ describe("ThreadComposer", () => {
<ThreadComposer
onSend={onSend}
placeholder="Type your message..."
slashCommands={[
{
command: "/new",
title: "New chat",
description: "Stop the current task and start a fresh conversation.",
icon: "square-pen",
lifecycle: "finalize_active_turn",
acceptsArgs: false,
},
]}
/>,
);
@@ -1365,6 +1383,32 @@ describe("ThreadComposer", () => {
);
});
it("does not classify exact-only slash commands with arguments", () => {
const onSend = vi.fn();
render(
<ThreadComposer
onSend={onSend}
placeholder="Type your message..."
slashCommands={[
{
command: "/new",
title: "New chat",
description: "Stop the current task and start a fresh conversation.",
icon: "square-pen",
lifecycle: "finalize_active_turn",
acceptsArgs: false,
},
]}
/>,
);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "/new with a title" } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("/new with a title", undefined, undefined);
});
it("routes a manually submitted stop command through the stop handler", () => {
const onSend = vi.fn();
const onStop = vi.fn();
@@ -1374,6 +1418,7 @@ describe("ThreadComposer", () => {
onStop={onStop}
isStreaming
placeholder="Type your message..."
slashCommands={COMMANDS}
/>,
);
@@ -1399,6 +1444,8 @@ describe("ThreadComposer", () => {
description: "Tell the agent to treat the request as a long-running goal.",
icon: "activity",
argHint: "<goal>",
lifecycle: "agent_turn_with_args",
acceptsArgs: true,
},
]}
/>,
@@ -1415,6 +1462,33 @@ describe("ThreadComposer", () => {
);
});
it("keeps goal usage commands on the side-channel path", () => {
const onSend = vi.fn();
render(
<ThreadComposer
onSend={onSend}
placeholder="Type your message..."
slashCommands={[
{
command: "/goal",
title: "Start long-running goal",
description: "Tell the agent to treat the request as a long-running goal.",
icon: "activity",
argHint: "<goal>",
lifecycle: "agent_turn_with_args",
acceptsArgs: true,
},
]}
/>,
);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "/goal" } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
expect(onSend).toHaveBeenCalledWith("/goal", undefined, { sideChannel: true });
});
it("shows a stop button while streaming", () => {
const onStop = vi.fn();
render(
+2
View File
@@ -1252,6 +1252,8 @@ describe("ThreadShell", () => {
description: "Print the last N persisted messages.",
icon: "history",
arg_hint: "[n]",
lifecycle: "side_channel",
accepts_args: true,
},
],
});