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

+3 -1
View File
@@ -14,6 +14,7 @@ interface CodeBlockProps {
className?: string;
chrome?: "default" | "none";
highlight?: boolean;
ansi?: boolean;
showLineNumbers?: boolean;
wrapLongLines?: boolean;
viewportHighlight?: boolean;
@@ -169,6 +170,7 @@ export const CodeBlock = memo(function CodeBlock({
className,
chrome = "default",
highlight = true,
ansi = true,
showLineNumbers = false,
wrapLongLines = true,
viewportHighlight = false,
@@ -177,7 +179,7 @@ export const CodeBlock = memo(function CodeBlock({
const rootRef = useRef<HTMLDivElement>(null);
const [copied, setCopied] = useState(false);
const [highlightedSource, setHighlightedSource] = useState<string | null>(null);
const renderAnsi = useMemo(() => shouldRenderAnsi(language, code), [language, code]);
const renderAnsi = useMemo(() => ansi && shouldRenderAnsi(language, code), [ansi, language, code]);
const plainCode = useMemo(() => renderAnsi ? stripAnsi(code) : code, [renderAnsi, code]);
const isDark = useThemeValue() === "dark";
const hasChrome = chrome === "default";
+26 -14
View File
@@ -12,10 +12,12 @@ import { useTranslation } from "react-i18next";
import { DisclosureContent } from "@/components/ui/disclosure";
import { AttachmentTile } from "@/components/AttachmentTile";
import { CodeBlock } from "@/components/CodeBlock";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
import { ImageGallery } from "@/components/ImageGallery";
import { InlineImageProvider, useInlineImages } from "@/components/InlineImageContext";
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { MarkdownText } from "@/components/MarkdownText";
import { SlashCommandText } from "@/components/SlashCommandText";
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
@@ -106,6 +108,7 @@ function useMessageCopy(content: string) {
}
function messageCopyContent(message: UIMessage, t: (key: string) => string) {
if (message.renderAs === "text") return message.content;
return message.role === "assistant" && message.compactReply === "empty"
? t("thread.compaction.empty")
: message.role === "assistant" && message.compactReply === "failed"
@@ -452,7 +455,16 @@ export function MessageBubble({
message.deliveryStatus === "sending" || message.deliveryStatus === "failed";
const quotedContext = parsedMessage.quotedContext;
const slashCommand = matchingSlashCommand(userContent, slashCommands);
const messageText = slashCommand ? (
const bangPrefix = /^(\s*)!/.exec(userContent);
const messageText = bangPrefix ? (
<>
{bangPrefix[1]}
<InlineTokenHighlight testId="message-shell-prefix" className="font-normal" color={INLINE_REFERENCE_HIGHLIGHT_COLOR}>
<span className="opacity-90">!</span>
</InlineTokenHighlight>
{userContent.slice(bangPrefix[0].length)}
</>
) : slashCommand ? (
<>
<SlashCommandText command={slashCommand.command} />
<UserMessageText
@@ -515,11 +527,7 @@ export function MessageBubble({
);
}
const assistantContent = message.compactReply === "empty"
? t("thread.compaction.empty")
: message.compactReply === "failed"
? t("thread.compaction.failed")
: message.content;
const assistantContent = messageCopyContent(message, t);
const empty = assistantContent.trim().length === 0;
const media = message.media ?? [];
const reasoning = message.role === "assistant" ? message.reasoning ?? "" : "";
@@ -543,14 +551,18 @@ export function MessageBubble({
) : empty && message.isStreaming ? null : (
<InlineImageProvider>
<div data-assistant-selectable={message.isStreaming ? undefined : "true"}>
{/* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */}
<MarkdownText
streaming={!!message.isStreaming}
preserveStreamingLayout
onOpenFilePreview={onOpenFilePreview}
>
{assistantContent}
</MarkdownText>
{message.renderAs === "text" ? (
<CodeBlock language="text" code={assistantContent} highlight={false} ansi={false} />
) : (
/* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */
<MarkdownText
streaming={!!message.isStreaming}
preserveStreamingLayout
onOpenFilePreview={onOpenFilePreview}
>
{assistantContent}
</MarkdownText>
)}
</div>
{media.length > 0 ? <MessageMedia media={media} align="left" /> : null}
</InlineImageProvider>
+59 -36
View File
@@ -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<CliAppMentionQuery | null>(() => {
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<CapabilityMentionSegment[]>(
() => 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<HTMLTextAreaElement>) => {
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<string>();
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({
<Tooltip>
<TooltipTrigger asChild>
<Button
type={showVoiceButton || showStopButton || modelNeedsSetup ? "button" : "submit"}
type={showVoiceButton || showStopButton || requiresModelSetup ? "button" : "submit"}
size="icon"
disabled={showVoiceButton ? voiceRecorder.buttonDisabled : showStopButton ? interactionDisabled : !canSend && !canOpenModelSettings}
aria-label={
@@ -2841,9 +2855,9 @@ export function ThreadComposer({
? voiceButtonLabel
: showStopButton
? t("thread.composer.stop")
: modelNeedsSetup
: requiresModelSetup
? t("thread.composer.configureModel", { defaultValue: "Configure model" })
: t("thread.composer.send")
: isUserShell ? t("thread.composer.shell.run") : t("thread.composer.send")
}
aria-keyshortcuts={showVoiceButton ? VOICE_SHORTCUT_ARIA : undefined}
onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined}
@@ -2854,7 +2868,7 @@ export function ThreadComposer({
event.preventDefault();
event.stopPropagation();
}}
onClick={showVoiceButton ? voiceRecorder.handleClick : showStopButton ? handleStop : modelNeedsSetup ? onModelBadgeClick : undefined}
onClick={showVoiceButton ? voiceRecorder.handleClick : showStopButton ? handleStop : requiresModelSetup ? onModelBadgeClick : undefined}
className={cn(
"composer-primary-action thread-composer-action thread-composer-round-action touch-target rounded-full bg-clip-padding",
actionState === "stop"
@@ -2867,7 +2881,9 @@ export function ThreadComposer({
isHero ? "h-8 w-8" : "h-9 w-9",
)}
>
<ComposerActionIcon state={actionState} />
{isUserShell && actionState === "send"
? <ToolRunIcon className="h-4 w-4" />
: <ComposerActionIcon state={actionState} />}
</Button>
</TooltipTrigger>
{showVoiceButton ? (
@@ -2883,6 +2899,8 @@ export function ThreadComposer({
</kbd>
) : null}
</TooltipContent>
) : isUserShell ? (
<TooltipContent>{t("thread.composer.shell.run")}</TooltipContent>
) : null}
</Tooltip>
</TooltipProvider>
@@ -3032,12 +3050,17 @@ function ComposerInlineReferenceOverlay({
const start = offset;
offset += segment.text.length;
if (segment.kind === "text") {
return <span key={`text-${index}`}>
{start === 0 && slashCommand ? <>
<SlashCommandText command={slashCommand} testId="composer-slash-command" />
{segment.text.slice(slashCommand.length)}
</> : segment.text}
</span>;
const bangPrefix = index === 0 ? /^(\s*)!/.exec(segment.text) : null;
return <span key={`text-${index}`}>{bangPrefix ? <>
{bangPrefix[1]}
<InlineTokenHighlight testId="composer-shell-prefix" className="font-normal" color={INLINE_REFERENCE_HIGHLIGHT_COLOR}>
<span className="opacity-90">!</span>
</InlineTokenHighlight>
{segment.text.slice(bangPrefix[0].length)}
</> : start === 0 && slashCommand ? <>
<SlashCommandText command={slashCommand} testId="composer-slash-command" />
{segment.text.slice(slashCommand.length)}
</> : segment.text}</span>;
}
if (segment.kind === "skill") {
return <SkillReferenceToken
+6 -3
View File
@@ -69,6 +69,7 @@ export interface SendOptions {
quotedContext?: string;
workspaceScope?: WorkspaceScopePayload | null;
sideChannel?: boolean;
userShell?: boolean;
finalizeActiveTurn?: boolean;
/** Append guidance to the running turn without detaching its active answer segment. */
continueActiveTurn?: boolean;
@@ -1023,9 +1024,11 @@ export function useNanobotStream(
delete clientOptions.sideChannel;
delete clientOptions.finalizeActiveTurn;
delete clientOptions.continueActiveTurn;
const delivery = wireMedia?.length
? client.sendAttachments(chatId, outboundContent, wireMedia, clientOptions)
: undefined;
const delivery = options?.userShell
? client.sendUserShellCommand(chatId, outboundContent, clientOptions)
: wireMedia?.length
? client.sendAttachments(chatId, outboundContent, wireMedia, clientOptions)
: undefined;
if (!delivery) client.sendMessage(chatId, outboundContent, undefined, clientOptions);
// Every caller may keep this promise to retain its draft until accepted.
// Also observe it here for queued/landing sends without an active composer.
+4
View File
@@ -2099,6 +2099,10 @@
"removeQuotedContext": "Remove quote",
"modelNotConfigured": "Model not configured",
"configureModel": "Configure model",
"shell": {
"run": "Run Shell command",
"removeContext": "Remove attachments and quoted text before running a command."
},
"chooseAI": "Choose model",
"switchModel": "Switch model",
"manageModels": "Manage presets",
+4
View File
@@ -1894,6 +1894,10 @@
"removeQuotedContext": "Quitar cita",
"modelNotConfigured": "Modelo no configurado",
"configureModel": "Configurar modelo",
"shell": {
"run": "Ejecutar comando de Shell",
"removeContext": "Elimina los archivos adjuntos y el texto citado antes de ejecutar un comando."
},
"chooseAI": "Elegir modelo",
"switchModel": "Cambiar modelo",
"manageModels": "Gestionar preajustes",
+4
View File
@@ -1893,6 +1893,10 @@
"removeQuotedContext": "Retirer la citation",
"modelNotConfigured": "Modèle non configuré",
"configureModel": "Configurer le modèle",
"shell": {
"run": "Exécuter une commande Shell",
"removeContext": "Retirez les pièces jointes et le texte cité avant d’exécuter une commande."
},
"chooseAI": "Choisir le modèle",
"switchModel": "Changer de modèle",
"manageModels": "Gérer les préréglages",
+4
View File
@@ -1893,6 +1893,10 @@
"removeQuotedContext": "Hapus kutipan",
"modelNotConfigured": "Model belum dikonfigurasi",
"configureModel": "Konfigurasi model",
"shell": {
"run": "Jalankan perintah Shell",
"removeContext": "Hapus lampiran dan teks kutipan sebelum menjalankan perintah."
},
"chooseAI": "Pilih model",
"switchModel": "Ganti model",
"manageModels": "Kelola preset",
+4
View File
@@ -1893,6 +1893,10 @@
"removeQuotedContext": "引用を削除",
"modelNotConfigured": "モデルが未設定です",
"configureModel": "モデルを設定",
"shell": {
"run": "Shell コマンドを実行",
"removeContext": "コマンドを実行する前に、添付ファイルと引用テキストを削除してください。"
},
"chooseAI": "モデルを選択",
"switchModel": "モデルを切り替え",
"manageModels": "プリセット管理",
+4
View File
@@ -1893,6 +1893,10 @@
"removeQuotedContext": "인용 삭제",
"modelNotConfigured": "모델이 설정되지 않음",
"configureModel": "모델 설정",
"shell": {
"run": "Shell 명령 실행",
"removeContext": "명령을 실행하기 전에 첨부 파일과 인용문을 제거하세요."
},
"chooseAI": "모델 선택",
"switchModel": "모델 전환",
"manageModels": "프리셋 관리",
+4
View File
@@ -1907,6 +1907,10 @@
"removeQuotedContext": "Remover citação",
"modelNotConfigured": "Modelo não configurado",
"configureModel": "Configurar modelo",
"shell": {
"run": "Executar comando Shell",
"removeContext": "Remova os anexos e o texto citado antes de executar um comando."
},
"chooseAI": "Escolher modelo",
"switchModel": "Trocar modelo",
"manageModels": "Gerenciar presets",
+4
View File
@@ -1893,6 +1893,10 @@
"removeQuotedContext": "Xóa trích dẫn",
"modelNotConfigured": "Chưa cấu hình mô hình",
"configureModel": "Cấu hình mô hình",
"shell": {
"run": "Chạy lệnh Shell",
"removeContext": "Xóa tệp đính kèm và văn bản trích dẫn trước khi chạy lệnh."
},
"chooseAI": "Chọn mô hình",
"switchModel": "Đổi mô hình",
"manageModels": "Quản lý bộ thiết lập",
+4
View File
@@ -2098,6 +2098,10 @@
"removeQuotedContext": "移除引用",
"modelNotConfigured": "模型未配置",
"configureModel": "配置模型",
"shell": {
"run": "执行 Shell 命令",
"removeContext": "执行命令前,请移除附件和引用文本。"
},
"chooseAI": "选择模型",
"switchModel": "切换模型",
"manageModels": "管理预设",
+4
View File
@@ -1893,6 +1893,10 @@
"removeQuotedContext": "移除引用",
"modelNotConfigured": "尚未設定模型",
"configureModel": "設定模型",
"shell": {
"run": "執行 Shell 命令",
"removeContext": "執行命令前,請移除附件和引用文字。"
},
"chooseAI": "選擇模型",
"switchModel": "切換模型",
"manageModels": "管理預設",
+1 -1
View File
@@ -175,7 +175,7 @@ function projectOrderedTurn(
};
for (const message of messages) {
if (message.kind === "compaction") {
if (message.kind === "compaction" || message.renderAs === "text") {
flushActivity();
flushAnswers();
units.push({
+28 -4
View File
@@ -766,6 +766,24 @@ export class NanobotClient {
}
}
async sendUserShellCommand(
chatId: string, content: string, options?: Parameters<NanobotClient["sendMessage"]>[3],
): Promise<void> {
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;
}
}
+1 -1
View File
@@ -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")) {
+2 -2
View File
@@ -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.") {
+1
View File
@@ -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 } : {}),
+4
View File
@@ -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
+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), {