feat(webui): complete bang commands and literal output (NAN-291) (#6173)

* feat(webui): complete direct bang shell commands

Reuse the gateway user-shell side channel, retain failed drafts without reconnect replay, and preserve literal output across live delivery and history. Highlight the bang prefix before and after sending.

NAN-291

* fix(clients): preserve literal shell output through display metadata
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-26 23:35:26 +08:00
1 parent f23a6d1485
commit 7e5dcb79e0
43 files changed
+805 -100

No files matched your search

+105 -1
View File
@@ -1,17 +1,23 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { setAppLanguage } from "@/i18n";
import { parseWebuiThreadPayload } from "@/lib/api";
import * as clipboard from "@/lib/clipboard";
import { formatMessageEndTime } from "@/lib/format-time";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { ThreadTranscript } from "@/lib/thread-transcript";
import type {
CliAppInfo,
McpPresetInfo,
SlashCommand,
ThreadProjectionEvent,
UIMessage,
} from "@/lib/types";
import { createStreamClient } from "./stream-client";
const CLI_APPS: CliAppInfo[] = [
{
@@ -104,6 +110,90 @@ function menuActions(root: ParentNode = document): HTMLElement {
}
describe("MessageBubble", () => {
it.each(["live", "paged history"] as const)("renders and copies literal output unchanged through %s, alongside ordinary Markdown", async (source) => {
const raw = [
" Switched model preset to `raw`.",
"__pycache__ <script>alert(\"raw\")</script>",
"![capture](https://example.invalid/output.png)",
"```mermaid",
"graph TD; A-->B",
"```",
"$$x^2$$",
"\x1b[31mred\x1b[0m",
"[Subagent task completed]",
"Task: print this",
"Result:",
" literal result\t",
"Summarize this naturally",
"",
"",
].join("\n");
const shellEvents: ThreadProjectionEvent[] = [
{ event: "user_message", chat_id: "literal-chat", turn_id: "shell", turn_seq: 1, starts_turn: false, text: "!printf output" },
{ event: "message", chat_id: "literal-chat", turn_id: "shell", turn_seq: 2, render_as: "text", text: raw },
];
const normalEvents: ThreadProjectionEvent[] = [
{ event: "user_message", chat_id: "literal-chat", turn_id: "normal", turn_seq: 1, starts_turn: true, text: "Explain the output" },
{ event: "message", chat_id: "literal-chat", turn_id: "normal", turn_seq: 2, text: "**Normal reply** [docs](https://example.invalid/docs)" },
{ event: "turn_end", chat_id: "literal-chat", turn_id: "normal", turn_seq: 3 },
];
const transcript = new ThreadTranscript();
if (source === "live") {
const { client, receive } = createStreamClient();
const unsubscribe = client.onTranscript("literal-chat", (event) => {
if (event.event === "user_message" || event.event === "message" || event.event === "turn_end") {
transcript.project(event, { createId: () => crypto.randomUUID(), now: 1_800_000_000_000 });
}
});
try {
[...shellEvents, ...normalEvents].forEach(receive);
} finally {
unsubscribe();
client.close();
}
} else {
expect(transcript.accept(parseWebuiThreadPayload({
schemaVersion: 3, projection: "events", events: normalEvents, completed_turn_ids: ["normal"],
page: { before_cursor: "before-normal", has_more_before: true, user_message_offset: 1 },
}), transcript.begin("initial"))).toBe(true);
expect(transcript.accept(parseWebuiThreadPayload({
schemaVersion: 3, projection: "events", events: shellEvents,
page: { before_cursor: null, has_more_before: false, user_message_offset: 0 },
}), transcript.begin("older"))).toBe(true);
}
const writeText = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);
try {
const { container } = render(<ThreadMessages messages={projectWebuiThreadMessages(transcript.messages)} />);
const output = screen.getByTestId("plain-code-fallback");
expect(output.textContent).toBe(raw);
expect(output).toHaveClass("whitespace-pre-wrap");
expect(output.querySelector("code")!.childNodes).toHaveLength(1);
expect(output.querySelector("code")!.firstChild!.nodeType).toBe(Node.TEXT_NODE);
expect((await screen.findByText("Normal reply")).tagName).toBe("STRONG");
expect(container.querySelector("img, script, .katex, [data-testid='mermaid-block']")).toBeNull();
expect(screen.getByRole("link", { name: "docs" })).toHaveAttribute("href", "https://example.invalid/docs");
fireEvent.click(screen.getByRole("button", { name: "Copy code" }));
await waitFor(() => expect(writeText).toHaveBeenNthCalledWith(1, raw));
fireEvent.click(within(output.closest<HTMLElement>("[data-thread-display-unit]")!).getByRole("button", { name: "Message actions" }));
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
await waitFor(() => expect(writeText).toHaveBeenNthCalledWith(2, raw));
} finally {
writeText.mockRestore();
}
});
it.each([undefined, "TEXT"])("keeps Markdown after bang input unless render_as is literally text (%s)", async (render_as) => {
const payload = parseWebuiThreadPayload({
schemaVersion: 3, projection: "events", events: [
{ event: "user_message", chat_id: "chat", text: "!echo **ordinary output**", starts_turn: true, turn_id: "bang" },
{ event: "message", chat_id: "chat", text: "**ordinary output**", render_as, turn_id: "bang" },
],
});
const { container } = render(<ThreadMessages messages={projectWebuiThreadMessages(projectThreadEvents(payload.events))} />);
await waitFor(() => expect(container.querySelector("[data-assistant-message] strong")?.textContent).toBe("ordinary output"));
expect(screen.queryByTestId("plain-code-fallback")).not.toBeInTheDocument();
});
it.each([false, undefined])("keeps normal sources out of the block menu (fallback: %s)", (fallback) => {
const message: UIMessage = { id: "primary", role: "assistant", content: "Hello", createdAt: 0,
responseSources: [{ provider: "openai_codex", model: "gpt", preset: "codex", fallback }] };
@@ -498,6 +588,20 @@ describe("MessageBubble", () => {
expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
});
it.each(["! ls", " !pwd", '!echo "$github" @zoom\nWrite-Output "hello!"'])("highlights a sent bang prefix while preserving the command literally: %s", (content) => {
const message: UIMessage = { id: "u-shell", role: "user", content, createdAt: Date.now() };
const { container, rerender } = render(<MessageBubble message={message} cliApps={CLI_APPS} />);
const prefix = screen.getByTestId("message-shell-prefix");
expect(prefix).toHaveTextContent(/^!$/);
expect(prefix).toHaveClass("font-normal");
expect(prefix.style.color).toBe("var(--inline-reference-highlight)");
expect(container.querySelector("[data-user-text-bubble] p")?.textContent).toBe(content);
rerender(<MessageBubble message={{ ...message, content: "Explain !pwd, please!" }} />);
expect(screen.queryByTestId("message-shell-prefix")).not.toBeInTheDocument();
expect(container.querySelector("[data-user-text-bubble] p")?.textContent).toBe("Explain !pwd, please!");
});
it("highlights skill references without a live skill catalog", () => {
const message: UIMessage = {
id: "u-skill-reference",
+48
View File
@@ -779,6 +779,54 @@ describe("NanobotClient", () => {
).toBe(false);
});
it("sends bang commands with a receipt without taking over an active run or replaying on reconnect", async () => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
const socket = lastSocket();
socket.fakeOpen();
socket.fakeMessage({ event: "goal_status", chat_id: "shell", status: "running", turn_id: "agent", started_at: 12_345 });
const run = client.getRunState("shell");
const pending = client.sendUserShellCommand("shell", "!pwd", { turnId: "bang" });
expect(JSON.parse(socket.sent.at(-1)!)).toMatchObject({ type: "message", chat_id: "shell", content: "!pwd", turn_id: "bang", webui: true, user_shell: true });
socket.fakeMessage({ event: "message_accepted", chat_id: "shell", turn_id: "bang", starts_turn: false, active_turn_id: "agent", started_at: 12_345 });
await expect(pending).resolves.toBeUndefined();
socket.fakeMessage({ event: "message", chat_id: "shell", turn_id: "bang", text: "Exit code: 0" });
expect(client.getRunState("shell")).toEqual(run);
socket.close();
await vi.advanceTimersByTimeAsync(1_000);
lastSocket().fakeOpen();
expect(lastSocket().sent.map((frame) => JSON.parse(frame)).filter((frame) => frame.type === "message")).toEqual([]);
client.close();
});
it.each(["disconnected", "write failure"])("does not queue a failed bang command for reconnect: %s", async (failure) => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
const socket = lastSocket();
if (failure === "write failure") {
socket.fakeOpen();
vi.spyOn(socket, "send").mockImplementationOnce(() => { throw new Error("send failed"); });
}
await expect(client.sendUserShellCommand("shell", "!pwd", { turnId: "bang" })).rejects.toThrow();
expect(client.getRunState("shell").active).toBe(false);
socket.close();
await vi.advanceTimersByTimeAsync(1_000);
lastSocket().fakeOpen();
expect(lastSocket().sent.map((frame) => JSON.parse(frame)).filter((frame) => frame.type === "message")).toEqual([]);
client.close();
});
it("reports a gateway-rejected bang command to its receipt waiter", async () => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
const socket = lastSocket();
socket.fakeOpen();
const pending = client.sendUserShellCommand("shell", "!pwd", { turnId: "bang" });
socket.fakeMessage({ event: "error", chat_id: "shell", turn_id: "bang", detail: "workspace_scope_rejected", reason: "Workspace unavailable" });
await expect(pending).rejects.toThrow("Workspace unavailable");
client.close();
});
it("does not register injected guidance as an independently unsettled run", () => {
const client = new NanobotClient({
url: "ws://test",
@@ -1,5 +1,6 @@
import {
act,
createEvent,
fireEvent,
render,
screen,
@@ -443,6 +444,31 @@ describe("local attachment paths and video ingress", () => {
const local = { path: "C:\\project\\my clip.mp4", name: "my clip.mp4", size: 12,
mime: "video/mp4", kind: "video" as const, url: "/api/media/sig/local" };
it("leaves a path pasted into a bang command as Shell text", () => {
const inspect = vi.fn().mockResolvedValue(local);
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i) as HTMLTextAreaElement;
fireEvent.change(input, { target: { value: "!cat " } });
input.setSelectionRange(5, 5);
const event = createEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
fireEvent(input, event);
expect(event.defaultPrevented).toBe(false);
expect(inspect).not.toHaveBeenCalled();
});
it("keeps a pending path literal when its draft becomes a bang command", async () => {
let complete!: (attachment: typeof local) => void;
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
fireEvent.change(input, { target: { value: `!${local.path}` } });
await act(async () => complete(local));
expect(input).toHaveValue(`!${local.path}`);
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith(`!${local.path}`, undefined, { sideChannel: true, userShell: true });
});
it("confirms a large pasted video path and sends only the borrowed reference", async () => {
const inspect = vi.fn().mockResolvedValue({ ...local, size: 64 * 1024 * 1024 + 1 });
const onSend = vi.fn();
+110
View File
@@ -2626,6 +2626,24 @@ describe("ThreadComposer", () => {
expect(onSend).toHaveBeenCalledWith(text, undefined, undefined);
});
it("highlights only the leading bang with the skill-reference color and preserves literal command text", () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} />);
const input = screen.getByLabelText("Message input") as HTMLTextAreaElement;
fireEvent.change(input, { target: { value: "$workflow " } });
const referenceColor = screen.getByTestId("composer-skill-reference-workflow").style.color;
const command = ' !echo "hello! $workflow @typography"\nWrite-Output done';
fireEvent.change(input, { target: { value: command } });
const bang = screen.getByTestId("composer-shell-prefix");
expect(bang).toHaveTextContent(/^!$/);
expect(bang.style.color).toBe(referenceColor);
expect(input.previousElementSibling).toHaveAttribute("aria-hidden", "true");
expect(input.previousElementSibling?.textContent).toBe(command);
expect(input).toHaveValue(command);
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith(command.trim(), undefined, { sideChannel: true, userShell: true });
});
it.each(["", "/history "])("mirrors inline references during composition without submitting the IME confirmation: %s", (prefix) => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} slashCommands={COMMANDS} />);
@@ -3243,6 +3261,98 @@ describe("ThreadComposer", () => {
expect(onSend).toHaveBeenCalledWith("Draw a friendly robot", undefined, undefined);
});
it.each(["!pwd", " ! pwd ", "!Write-Output first\nWrite-Output second", "!"])("runs bang input directly without a configured model: %s", (command) => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} modelNeedsSetup />);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: command } });
fireEvent.click(screen.getByRole("button", { name: "Run Shell command" }));
expect(onSend).toHaveBeenCalledWith(command.trim(), undefined, { sideChannel: true, userShell: true });
expect(input).toHaveValue("");
});
it("keeps bang commands separate from pending guidance and the active turn", async () => {
const onSend = vi.fn();
const onStop = vi.fn();
const { rerender } = render(<ThreadComposer onSend={onSend} onStop={onStop} isStreaming />);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "waiting guidance" } });
fireEvent.keyDown(input, { key: "Enter" });
fireEvent.change(input, { target: { value: "!pwd" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledOnce();
expect(onSend).toHaveBeenCalledWith("!pwd", undefined, { sideChannel: true, userShell: true });
expect(within(screen.getByRole("group", { name: "Waiting to send" })).getByText("waiting guidance")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
expect(onStop).not.toHaveBeenCalled();
rerender(<ThreadComposer onSend={onSend} onStop={onStop} isStreaming={false} />);
await waitFor(() => expect(onSend).toHaveBeenCalledTimes(2));
expect(onSend).toHaveBeenLastCalledWith("waiting guidance");
});
it.each(["!echo @gimp", "!echo $weather"])("keeps bang arguments literal instead of opening a mention or skill menu: %s", (command) => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} cliApps={CLI_APPS} skills={[{ name: "weather", description: "Weather", source: "builtin", available: true }]} />);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: command, selectionStart: command.length } });
expect(input).toHaveValue(command);
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith(command, undefined, { sideChannel: true, userShell: true });
});
it("keeps exclamation marks inside ordinary messages on the chat path", () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} />);
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "Please explain !pwd" } });
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("Please explain !pwd", undefined, undefined);
});
it("retains a bang draft when delivery is rejected without retrying it", async () => {
const onSend = vi.fn().mockRejectedValue(new Error("Shell send rejected"));
const { rerender } = render(<ThreadComposer onSend={onSend} />);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "!pwd" } });
fireEvent.keyDown(input, { key: "Enter" });
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Shell send rejected"));
expect(input).toHaveValue("!pwd");
rerender(<ThreadComposer onSend={onSend} isStreaming={false} />);
expect(onSend).toHaveBeenCalledOnce();
expect(onSend).toHaveBeenCalledWith("!pwd", undefined, { sideChannel: true, userShell: true });
});
it("rejects attachments on bang input without losing the draft or attachment", async () => {
const onSend = vi.fn();
const { container } = render(<ThreadComposer onSend={onSend} />);
fireEvent.change(container.querySelector('input[type="file"]')!, {
target: { files: [new File(["image"], "photo.png", { type: "image/png" })] },
});
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "!pwd" } });
await waitFor(() => expect(screen.getByRole("button", { name: "Run Shell command" })).toBeEnabled());
fireEvent.keyDown(input, { key: "Enter" });
expect(screen.getByRole("alert")).toHaveTextContent("Remove attachments and quoted text before running a command.");
expect(onSend).not.toHaveBeenCalled();
expect(input).toHaveValue("!pwd");
expect(screen.getByRole("button", { name: "Remove attachment" })).toHaveAttribute("aria-description", "photo.png");
});
it("rejects quoted context on bang input without clearing it", () => {
const onSend = vi.fn();
const onQuotedContextChange = vi.fn();
render(<ThreadComposer onSend={onSend} quotedContext="keep this quote" onQuotedContextChange={onQuotedContextChange} />);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "!pwd" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(screen.getByRole("alert")).toHaveTextContent("Remove attachments and quoted text before running a command.");
expect(input).toHaveValue("!pwd");
expect(onSend).not.toHaveBeenCalled();
expect(onQuotedContextChange).not.toHaveBeenCalled();
});
it("marks known slash commands as side-channel sends", () => {
const onSend = vi.fn();
render(
+29
View File
@@ -101,6 +101,7 @@ function fakeClient() {
return () => errorHandlers.delete(handler);
},
sendMessage: vi.fn(lifecycle.sendMessage.bind(lifecycle)),
sendUserShellCommand: vi.fn(lifecycle.sendUserShellCommand.bind(lifecycle)),
sendAttachments: vi.fn(async (...args: Parameters<NanobotClient["sendAttachments"]>) => {
lifecycle.sendMessage(args[0], args[1], undefined, args[3]);
}),
@@ -3059,6 +3060,34 @@ describe("useNanobotStream", () => {
expect(result.current.messages[0].content).toBe("long task");
});
it("delivers bang output separately while the active Agent answer continues", async () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("shell", EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
act(() => { result.current.send("long task"); });
const activeTurnId = fake.client.sendMessage.mock.calls.at(-1)![3]!.turnId!;
act(() => { fake.emit("shell", { event: "delta", chat_id: "shell", text: "first ", turn_id: activeTurnId, stream_id: "answer" }); });
await flushStreamFrame();
const answerId = result.current.messages.find((row) => row.role === "assistant")!.id;
let shell!: ReturnType<typeof result.current.send>;
act(() => { shell = result.current.send("!pwd", undefined, { sideChannel: true, userShell: true }); });
expect(fake.client.sendUserShellCommand).toHaveBeenCalledWith("shell", "!pwd", expect.objectContaining({ turnId: shell!.turnId, startsNewRun: false }));
expect(fake.client.sendMessage).toHaveBeenCalledOnce();
act(() => {
fake.emit("shell", { event: "message_accepted", chat_id: "shell", turn_id: shell!.turnId, starts_turn: false, active_turn_id: activeTurnId });
fake.emit("shell", { event: "message", chat_id: "shell", text: "```text\nPath\n----\n```", turn_id: shell!.turnId });
});
await shell!.delivery;
expect(result.current.isStreaming).toBe(true);
act(() => { fake.emit("shell", { event: "delta", chat_id: "shell", text: "last", turn_id: activeTurnId, stream_id: "answer" }); });
await flushStreamFrame();
expect(result.current.messages.find((row) => row.id === answerId)).toMatchObject({ content: "first last", isStreaming: true });
const shellAnswer = result.current.messages.find((row) => row.turnId === shell!.turnId && row.role === "assistant");
expect(shellAnswer).toMatchObject({ content: "```text\nPath\n----\n```" });
expect(Boolean(shellAnswer!.isStreaming)).toBe(false);
act(() => { fake.emit("shell", { event: "turn_end", chat_id: "shell", turn_id: activeTurnId }); });
expect(result.current.isStreaming).toBe(false);
});
it("does not mark side-channel slash commands as streaming", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-status", EMPTY_MESSAGES), {