- {/* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */}
-
- {assistantContent}
-
+ {message.renderAs === "text" ? (
+
+ ) : (
+ /* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */
+
+ {assistantContent}
+
+ )}
{media.length > 0 ? : null}
diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx
index 53da2e6fd..050026496 100644
--- a/webui/src/components/thread/ThreadComposer.tsx
+++ b/webui/src/components/thread/ThreadComposer.tsx
@@ -53,8 +53,9 @@ import {
import {
composerMentionText,
isCapabilityMentionStart,
+ type CapabilityMentionSegment,
} from "@/lib/composer-mention-text";
-import { INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";
+import { INLINE_REFERENCE_HIGHLIGHT_COLOR, INLINE_TOKEN_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { SlashCommandText } from "@/components/SlashCommandText";
import {
ChevronDown,
@@ -1324,18 +1325,21 @@ export function ThreadComposer({
);
const hasErrors = images.some((img) => img.status === "error");
+ const isUserShell = value.trimStart().startsWith("!");
+ const requiresModelSetup = modelNeedsSetup && !isUserShell;
const hasComposerContent = value.trim().length > 0 || readyImages.length > 0;
const canSend =
!interactionDisabled
- && !modelNeedsSetup
+ && !requiresModelSetup
&& !encoding
&& !hasErrors
&& hasComposerContent;
const canOpenModelSettings = Boolean(
- modelNeedsSetup && onModelBadgeClick && !interactionDisabled,
+ requiresModelSetup && onModelBadgeClick && !interactionDisabled,
);
const canQueueGuidance =
isStreaming
+ && !isUserShell
&& !interactionDisabled
&& !modelNeedsSetup
&& !encoding
@@ -1354,7 +1358,7 @@ export function ThreadComposer({
}, [interactionDisabled, slashMenuDismissed, value]);
const skillQuery = useMemo(() => {
- if (interactionDisabled || slashMenuDismissed) return null;
+ if (interactionDisabled || isUserShell || slashMenuDismissed) return null;
const caret = Math.min(Math.max(cursorPosition, 0), value.length);
const beforeCaret = value.slice(0, caret);
const match = /\$([A-Za-z0-9_-]*)$/i.exec(beforeCaret);
@@ -1364,7 +1368,7 @@ export function ThreadComposer({
start: match.index,
text: match[1].toLowerCase(),
};
- }, [cursorPosition, interactionDisabled, slashMenuDismissed, value]);
+ }, [cursorPosition, interactionDisabled, isUserShell, slashMenuDismissed, value]);
const skillMenuActive = skillQuery !== null;
useEffect(() => {
@@ -1498,7 +1502,7 @@ export function ThreadComposer({
const showSlashMenu = filteredSlashCommands.length > 0;
const cliAppMention = useMemo(() => {
- if (interactionDisabled || cliAppMenuDismissed) return null;
+ if (interactionDisabled || isUserShell || cliAppMenuDismissed) return null;
const caret = Math.min(Math.max(cursorPosition, 0), value.length);
const beforeCaret = value.slice(0, caret);
const match = /@([\p{L}\p{N}_-]*)$/iu.exec(beforeCaret);
@@ -1509,7 +1513,7 @@ export function ThreadComposer({
start: match.index,
end: caret,
};
- }, [cliAppMenuDismissed, cursorPosition, interactionDisabled, value]);
+ }, [cliAppMenuDismissed, cursorPosition, interactionDisabled, isUserShell, value]);
const mentionSearchActive = cliAppMention !== null;
useEffect(() => {
@@ -1524,9 +1528,10 @@ export function ThreadComposer({
() => [...availableSessionMentions, ...boundSessionMentions],
[availableSessionMentions, boundSessionMentions],
);
- const mentionSegments = useMemo(
- () => splitCapabilityMentionSegments(value, cliApps, mcpPresets, sessionMentionCatalog),
- [cliApps, mcpPresets, sessionMentionCatalog, value],
+ const mentionSegments = useMemo(
+ () => isUserShell ? [{ kind: "text", text: value }]
+ : splitCapabilityMentionSegments(value, cliApps, mcpPresets, sessionMentionCatalog),
+ [cliApps, isUserShell, mcpPresets, sessionMentionCatalog, value],
);
const editMentionInput = useCallback((next: string, cursor: number) => {
setValue(next);
@@ -1543,7 +1548,7 @@ export function ThreadComposer({
const { rawSelection, replace: replaceMentionInput } = mentionInput;
const onPaste = useCallback((event: React.ClipboardEvent) => {
onAttachmentPaste(event);
- if (event.defaultPrevented || interactionDisabled || !onInspectAttachment) return;
+ if (event.defaultPrevented || interactionDisabled || isUserShell || !onInspectAttachment) return;
const raw = event.clipboardData.getData("text/plain");
const path = pastedFilePath(raw);
if (!path) return;
@@ -1562,11 +1567,11 @@ export function ThreadComposer({
if (error instanceof Error && "status" in error && error.status === 404) return;
setInlineError(error instanceof Error ? error.message : t("message.attachmentUnavailable"));
});
- }, [interactionDisabled, onAttachmentPaste, onInspectAttachment, rawSelection, replaceMentionInput, scopeIdentity, t, value]);
+ }, [interactionDisabled, isUserShell, onAttachmentPaste, onInspectAttachment, rawSelection, replaceMentionInput, scopeIdentity, t, value]);
useLayoutEffect(() => {
if (!pathInspection) return;
- if (pathInspection.scope !== scopeIdentity || !pathInspection.range.update(value)) {
+ if (isUserShell || pathInspection.scope !== scopeIdentity || !pathInspection.range.update(value)) {
pathCheckGeneration.current += 1;
setPathInspection(null);
return;
@@ -1583,7 +1588,7 @@ export function ThreadComposer({
}
}
setPathInspection(null);
- }, [addLocal, formatRejection, mentionInput.isComposing, pathInspection, rawSelection, replaceMentionInput, scopeIdentity, value]);
+ }, [addLocal, formatRejection, isUserShell, mentionInput.isComposing, pathInspection, rawSelection, replaceMentionInput, scopeIdentity, value]);
const draftText = composerMentionText(mentionInput.segments).raw;
const sessionDragInsertion = sessionDragPreview
@@ -1720,11 +1725,11 @@ export function ThreadComposer({
const showCliAppMenu = filteredMentionCandidates.length > 0;
const showAnyPalette = showSlashMenu || showCliAppMenu;
const inlineSegments = useMemo(
- () => withSkillReferences(displayMentionSegments),
- [displayMentionSegments],
+ () => isUserShell ? displayMentionSegments : withSkillReferences(displayMentionSegments),
+ [displayMentionSegments, isUserShell],
);
const slashCommand = matchingSlashCommand(sessionDragInsertion?.value ?? draftText, slashCommands);
- const hasInlineDecorations = slashCommand !== null || inlineSegments.some((segment) => segment.kind !== "text");
+ const hasInlineDecorations = isUserShell || slashCommand !== null || inlineSegments.some((segment) => segment.kind !== "text");
const activeCliMentionApps = useMemo(() => {
const seen = new Set();
return mentionSegments.flatMap((segment) => {
@@ -2184,13 +2189,17 @@ export function ThreadComposer({
}, [completedTurnIds, interactionDisabled, sendQueuedPrompt, isStreaming, pendingQueueKey, queuedPrompt, queuedPromptStorageKey]);
const submit = useCallback(() => {
- if (modelNeedsSetup) {
+ if (requiresModelSetup) {
if (hasComposerContent) {
setModelSetupAttentionRequest((request) => request + 1);
}
return;
}
if (!canSend) return;
+ if (isUserShell && (images.length > 0 || normalizedQuotedContext)) {
+ setInlineError(t("thread.composer.shell.removeContext"));
+ return;
+ }
const trimmed = value.trim();
const content = trimmed;
if (utf8Bytes(formatQuotedUserMessage(content, normalizedQuotedContext)) > maxTextBytes) {
@@ -2202,11 +2211,12 @@ export function ThreadComposer({
const payload = queuedImagesToSendImages(readyImagesToQueuedImages(readyImages));
const attachedCliApps = activeCliMentionApps.map(cliAppMentionPayload);
const attachedMcpPresets = activeMcpPresetMentions.map(mcpPresetMentionPayload);
- const options: SendOptions | undefined =
+ const options: SendOptions | undefined = !isUserShell && (
attachedCliApps.length > 0
|| attachedMcpPresets.length > 0
|| activeSessionMentions.length > 0
|| normalizedQuotedContext
+ )
? {
...(attachedCliApps.length > 0 ? { cliApps: attachedCliApps } : {}),
...(attachedMcpPresets.length > 0 ? { mcpPresets: attachedMcpPresets } : {}),
@@ -2235,10 +2245,10 @@ export function ThreadComposer({
onQuotedContextChange?.(null);
return;
}
- const isSlashSideChannel = isSideChannelLifecycle(slashLifecycle);
+ const isSideChannel = isUserShell || isSideChannelLifecycle(slashLifecycle);
const finalizeActiveTurn =
slashLifecycle === "finalize_active_turn";
- if (!slashLifecycle) {
+ if (!isUserShell && !slashLifecycle) {
const prompt = collectGuidancePrompt();
const error = queuedPromptError(prompt);
if (error) {
@@ -2260,7 +2270,7 @@ export function ThreadComposer({
if (draftKey && draftStore && draftStore.get(draftKey) !== submittedDraft) return;
if (draftKey) draftStore?.delete(draftKey);
if (hasTouchPrimaryPointer) textareaRef.current?.blur();
- if (!isStreaming || finalizeActiveTurn) setQueuedPrompt(null);
+ if ((!isStreaming && !isUserShell) || finalizeActiveTurn) setQueuedPrompt(null);
// Bubble owns the data URL copy; safe to revoke every staged blob
// preview here without affecting the rendered message.
clear();
@@ -2270,10 +2280,11 @@ export function ThreadComposer({
const result = onSend(
content,
payload,
- isSlashSideChannel
+ isSideChannel
? {
...options,
sideChannel: true,
+ ...(isUserShell ? { userShell: true } : {}),
...(finalizeActiveTurn ? { finalizeActiveTurn } : {}),
}
: isStreaming ? { ...options, continueActiveTurn: true } : options,
@@ -2308,15 +2319,18 @@ export function ThreadComposer({
hasTouchPrimaryPointer,
hasComposerContent,
handleStop,
+ images.length,
isStreaming,
+ isUserShell,
maxTextBytes,
- modelNeedsSetup,
+ requiresModelSetup,
onSend,
onStop,
onQuotedContextChange,
normalizedQuotedContext,
readyImages,
slashCommands,
+ t,
textTooLargeMessage,
value,
]);
@@ -2471,7 +2485,7 @@ export function ThreadComposer({
const showStopButton = isStreaming && !!onStop && !canSend;
const actionState: ComposerActionState = showVoiceButton
? voiceRecorder.state === "transcribing" ? "busy" : voiceRecorder.isRecording ? "recording" : "voice"
- : showStopButton ? "stop" : modelNeedsSetup ? "setup" : canSend || !isStreaming ? "send" : "busy";
+ : showStopButton ? "stop" : requiresModelSetup ? "setup" : canSend || !isStreaming ? "send" : "busy";
const relaxedHeroInput = isHero && images.length === 0 && !isStreaming;
const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused
&& value.length === 0 && images.length === 0 && !inlineError
@@ -2833,7 +2847,7 @@ export function ThreadComposer({
{showVoiceButton ? (
@@ -2883,6 +2899,8 @@ export function ThreadComposer({
) : null}
+ ) : isUserShell ? (
+ {t("thread.composer.shell.run")}
) : null}
@@ -3032,12 +3050,17 @@ function ComposerInlineReferenceOverlay({
const start = offset;
offset += segment.text.length;
if (segment.kind === "text") {
- return
- {start === 0 && slashCommand ? <>
-
- {segment.text.slice(slashCommand.length)}
- > : segment.text}
- ;
+ const bangPrefix = index === 0 ? /^(\s*)!/.exec(segment.text) : null;
+ return {bangPrefix ? <>
+ {bangPrefix[1]}
+
+ !
+
+ {segment.text.slice(bangPrefix[0].length)}
+ > : start === 0 && slashCommand ? <>
+
+ {segment.text.slice(slashCommand.length)}
+ > : segment.text};
}
if (segment.kind === "skill") {
return [3],
+ ): Promise {
+ const turnId = options?.turnId ?? crypto.randomUUID();
+ try {
+ await this.receipts.wait(turnId, () => {
+ if (!this.sendMessage(chatId, content, undefined, { ...options, turnId, userShell: true, startsNewRun: false })) {
+ throw new Error("Shell command was not sent; draft retained");
+ }
+ });
+ } catch (error) {
+ this.applyRunEffects(this.runs.transition({ kind: "reject", chatId, turnId }));
+ this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "message_rejected",
+ reason: error instanceof Error ? error.message : "Shell command send failed" });
+ throw error;
+ }
+ }
+
sendMessage(
chatId: string,
content: string,
@@ -776,12 +794,14 @@ export class NanobotClient {
sessionMentions?: SessionMention[];
quotedContext?: string;
intent?: "create_automation";
+ userShell?: boolean;
workspaceScope?: WorkspaceScopePayload | null;
turnId?: string;
/** False for side-channel or injected messages that do not own a lifecycle. */
startsNewRun?: boolean;
},
): boolean {
+ if (options?.userShell && this.socket?.readyState !== WS_OPEN) return false;
const temporary = this.temporaryChatIds.has(chatId);
if (!temporary) this.knownChats.add(chatId);
const frame: Outbound = {
@@ -796,6 +816,7 @@ export class NanobotClient {
: {}),
...(options?.quotedContext?.trim() ? { quoted_context: options.quotedContext.trim() } : {}),
...(options?.intent === "create_automation" ? { intent: options.intent } : {}),
+ ...(options?.userShell ? { user_shell: true } : {}),
...(options?.workspaceScope ? { workspace_scope: options.workspaceScope } : {}),
...(options?.turnId ? { turn_id: options.turnId } : {}),
webui: true,
@@ -819,6 +840,7 @@ export class NanobotClient {
role: options.startsNewRun === false ? "supplement" : "candidate-owner",
}));
}
+ if (options?.userShell) return this.rawSend(frame);
this.queueSend(frame);
return true;
}
@@ -1285,8 +1307,8 @@ export class NanobotClient {
return new TextEncoder().encode(JSON.stringify(frame)).byteLength <= this.maxFrameBytes;
}
- private rawSend(frame: Outbound): void {
- if (!this.socket) return;
+ private rawSend(frame: Outbound): boolean {
+ if (!this.socket) return false;
try {
this.socket.send(JSON.stringify(frame));
this.lastSocketMessageSend = null;
@@ -1297,9 +1319,11 @@ export class NanobotClient {
this.lastSocketMessageSend = ref;
}
}
+ return true;
} catch {
- // Send failure will materialize as a close; queue the frame for retry.
- this.sendQueue.push(frame);
+ // Shell commands require a new explicit submission, never reconnect replay.
+ if (frame.type !== "message" || !frame.user_shell) this.sendQueue.push(frame);
+ return false;
}
}
diff --git a/webui/src/lib/subagent-channel-display.ts b/webui/src/lib/subagent-channel-display.ts
index ce0f2278b..f6e34cfc0 100644
--- a/webui/src/lib/subagent-channel-display.ts
+++ b/webui/src/lib/subagent-channel-display.ts
@@ -47,7 +47,7 @@ export function scrubSubagentAnnounceBody(
/** Apply scrub to assistant rows that look like subagent inject announcements. */
export function scrubSubagentUiMessages(messages: UIMessage[]): UIMessage[] {
return messages.map((m) => {
- if (m.role !== "assistant" || typeof m.content !== "string") {
+ if (m.role !== "assistant" || m.renderAs === "text" || typeof m.content !== "string") {
return m;
}
if (!m.content.includes("[Subagent")) {
diff --git a/webui/src/lib/thread-display-projection.ts b/webui/src/lib/thread-display-projection.ts
index 55c1a9479..211e51d33 100644
--- a/webui/src/lib/thread-display-projection.ts
+++ b/webui/src/lib/thread-display-projection.ts
@@ -20,7 +20,7 @@ function prepareMessage(original: UIMessage): PreparedMessage {
message,
hidden: isSystemCommandTurnId(message.turnId)
|| (message.role === "user" && isModelCommandText(message.content))
- || (message.role === "assistant" && isModelCommandResponseText(message.content)),
+ || (message.role === "assistant" && message.renderAs !== "text" && isModelCommandResponseText(message.content)),
compact: message.role === "user" && message.content.trim().toLowerCase() === "/compact",
};
preparedMessages.set(original, prepared);
@@ -47,7 +47,7 @@ export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {
latestStart = message.createdAt;
if (message.turnId) starts.set(message.turnId, message.createdAt);
}
- if (message.role === "assistant" && !message.kind && !message.isStreaming
+ if (message.role === "assistant" && message.renderAs !== "text" && !message.kind && !message.isStreaming
&& message.turnId && compactTurns.has(message.turnId)) {
if (message.content === "Nothing to compact.") message = { ...message, compactReply: "empty" };
if (message.content === "Unable to compact context. Check the logs and try again.") {
diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts
index fce02c5f5..14156453d 100644
--- a/webui/src/lib/thread-event-projection.ts
+++ b/webui/src/lib/thread-event-projection.ts
@@ -1053,6 +1053,7 @@ export function projectThreadEvent(
: undefined;
const projected = {
content: event.text,
+ ...(event.render_as === "text" ? { renderAs: event.render_as } : {}),
...(media?.length ? { media } : {}),
...(latencyMs !== undefined ? { latencyMs } : {}),
...(event.source ? { source: event.source } : {}),
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 399fb9417..44690db8c 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -113,6 +113,8 @@ export interface UIMessage {
id: string;
role: Role;
content: string;
+ /** Literal output bypasses Markdown and content-based reply recognition. */
+ renderAs?: "text";
/** Invocation-time snapshots, never resolved from today's model presets. */
responseSources?: ResponseSource[];
kind?: MessageKind;
@@ -1514,6 +1516,7 @@ export type InboundEvent =
event: "message";
chat_id: string;
text: string;
+ render_as?: "text";
reply_to?: string;
media?: string[];
media_urls?: Array<{ url: string; name?: string; kind?: UIMediaKind }>;
@@ -1794,6 +1797,7 @@ export type Outbound =
session_mentions?: SessionMention[];
quoted_context?: string;
intent?: "create_automation";
+ user_shell?: true;
workspace_scope?: WorkspaceScopePayload;
turn_id?: string;
/** Marks messages sent by the embedded WebUI, without changing the
diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx
index 0fed9d784..568ef8f23 100644
--- a/webui/src/tests/message-bubble.test.tsx
+++ b/webui/src/tests/message-bubble.test.tsx
@@ -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__ ",
+ "",
+ "```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();
+ 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("[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();
+ 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();
+ 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();
+ 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",
diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts
index 260df4cc3..a15bea5b3 100644
--- a/webui/src/tests/nanobot-client.test.ts
+++ b/webui/src/tests/nanobot-client.test.ts
@@ -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",
diff --git a/webui/src/tests/thread-composer-attach.test.tsx b/webui/src/tests/thread-composer-attach.test.tsx
index 6ee778a81..2c0edfa9f 100644
--- a/webui/src/tests/thread-composer-attach.test.tsx
+++ b/webui/src/tests/thread-composer-attach.test.tsx
@@ -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();
+ 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( 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();
diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx
index 2661c6b20..18b79b69d 100644
--- a/webui/src/tests/thread-composer.test.tsx
+++ b/webui/src/tests/thread-composer.test.tsx
@@ -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();
+ 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();
@@ -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();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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(
diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx
index b0f71d8e8..d22285351 100644
--- a/webui/src/tests/useNanobotStream.test.tsx
+++ b/webui/src/tests/useNanobotStream.test.tsx
@@ -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) => {
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;
+ 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), {