From 7e5dcb79e0671066f30c73a91656005de058dad9 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:35:26 +0800 Subject: [PATCH] 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 --- docs/webui.md | 2 + nanobot/channels/websocket/runtime.py | 6 +- .../tests/test_websocket_outbound_delivery.py | 30 ++++- nanobot/webui/history.py | 2 +- nanobot/webui/transcript.py | 40 ++++++- tests/utils/test_webui_transcript.py | 51 ++++++++ tests/webui/test_gateway_webui_smoke.py | 14 ++- tui/src/app/app.ts | 4 +- tui/src/app/composer.test.ts | 36 +++++- tui/src/app/transcript.test.ts | 50 ++++++-- tui/src/client/api.ts | 10 +- tui/src/client/client.test.ts | 6 + tui/src/client/history.test.ts | 19 +++ tui/src/client/types.ts | 2 + tui/src/client/validation.ts | 5 + tui/src/rendering/transcript.ts | 27 +++-- webui/browser/inline-references-fixture.tsx | 8 +- webui/browser/inline-references.spec.ts | 41 +++++++ webui/src/components/CodeBlock.tsx | 4 +- webui/src/components/MessageBubble.tsx | 40 ++++--- .../src/components/thread/ThreadComposer.tsx | 95 +++++++++------ webui/src/hooks/useNanobotStream.ts | 9 +- webui/src/i18n/locales/en/common.json | 4 + webui/src/i18n/locales/es/common.json | 4 + webui/src/i18n/locales/fr/common.json | 4 + webui/src/i18n/locales/id/common.json | 4 + webui/src/i18n/locales/ja/common.json | 4 + webui/src/i18n/locales/ko/common.json | 4 + webui/src/i18n/locales/pt-BR/common.json | 4 + webui/src/i18n/locales/vi/common.json | 4 + webui/src/i18n/locales/zh-CN/common.json | 4 + webui/src/i18n/locales/zh-TW/common.json | 4 + webui/src/lib/activity-timeline.ts | 2 +- webui/src/lib/nanobot-client.ts | 32 ++++- webui/src/lib/subagent-channel-display.ts | 2 +- webui/src/lib/thread-display-projection.ts | 4 +- webui/src/lib/thread-event-projection.ts | 1 + webui/src/lib/types.ts | 4 + webui/src/tests/message-bubble.test.tsx | 106 ++++++++++++++++- webui/src/tests/nanobot-client.test.ts | 48 ++++++++ .../src/tests/thread-composer-attach.test.tsx | 26 +++++ webui/src/tests/thread-composer.test.tsx | 110 ++++++++++++++++++ webui/src/tests/useNanobotStream.test.tsx | 29 +++++ 43 files changed, 805 insertions(+), 100 deletions(-) diff --git a/docs/webui.md b/docs/webui.md index 0c7a2bfab..1bc4917a8 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -183,6 +183,8 @@ In Restricted mode, ordinary file and shell work stays inside the selected proje The composer supports text, attachments (images, documents, and videos), slash commands and `@` mentions. With voice transcription configured, the empty composer offers voice input; transcription is added to the draft before sending. +Start a message with `!` to run a Shell command directly in the topic's workspace, without calling the model (for example, `!git status`). Multiline commands are supported; remove attachments and quoted text before running a command. Commands run immediately, separately from waiting messages, and use the topic's existing permissions and Shell limits. + Images appear as thumbnails above the draft. Hover over a thumbnail for its filename and size; use its top-right × to remove it before sending. Documents and videos keep their file cards, and attachment errors remain visible. Choose or drop MP4, WebM, or MOV videos into the composer (one per message, up to 20 MiB per upload). You can play them in WebUI; the Agent cannot directly analyze their contents yet. diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index db8a767cc..d712205ab 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -22,6 +22,7 @@ from websockets.exceptions import ConnectionClosed from websockets.http11 import Request as WsRequest from nanobot.bus.events import ( + INBOUND_META_USER_SHELL, OUTBOUND_META_AGENT_UI, OutboundMessage, ) @@ -1235,12 +1236,15 @@ class WebSocketChannel(BaseChannel): """Serialize one ordinary outbound message selected by the projector.""" conns = list(self._subs.get(msg.chat_id, ())) text = msg.content - wire_text = self._media.rewrite_local_markdown_images(text) + user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True + wire_text = text if user_shell else self._media.rewrite_local_markdown_images(text) payload: dict[str, Any] = { "event": "message", "chat_id": msg.chat_id, "text": wire_text, } + if user_shell: + payload["render_as"] = "text" turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY) if isinstance(turn_id, str) and turn_id: payload["turn_id"] = turn_id diff --git a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py index 93f64ae19..5e06a5ca3 100644 --- a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py +++ b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py @@ -10,7 +10,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest -from nanobot.bus.events import OutboundMessage +from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage from nanobot.bus.queue import MessageBus from nanobot.channels.manager import ChannelManager from nanobot.channels.websocket import runtime @@ -478,3 +478,31 @@ async def test_normal_cleanup_can_overlap_connection_retirement(monkeypatch) -> assert connection not in channel._connection_outbound assert connection not in channel._conn_chats assert channel._subs == {} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("user_shell", [True, False]) +async def test_shell_output_is_literal_without_changing_other_command_replies( + user_shell: bool, monkeypatch: pytest.MonkeyPatch, +) -> None: + channel = _channel() + connection = _RecordingConnection() + channel._attach(cast(Any, connection), "shell-output") + output = "Path\n----\n __pycache__\n```mermaid\nflowchart LR\n```\n![preview](local.png)\n" + rewritten = output.replace("local.png", "/api/media/signed") + monkeypatch.setattr(channel._media, "rewrite_local_markdown_images", lambda text: rewritten) + message = OutboundMessage( + channel="websocket", chat_id="shell-output", content=output, + metadata={"render_as": "text", INBOUND_META_USER_SHELL: user_shell}, + ) + try: + await channel.send(message) + payload = json.loads(await asyncio.wait_for(connection.sent.get(), timeout=1)) + assert payload["text"] == (output if user_shell else rewritten) + assert payload.get("render_as") == ("text" if user_shell else None) + persisted = channel._persist_turn_transcript_event.await_args + assert persisted.args[1] == payload + assert persisted.kwargs["transcript_overrides"] == {"text": output} + assert message.content == output + finally: + await channel._cleanup_connection(cast(Any, connection)) diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py index 406d67c56..347d48515 100644 --- a/nanobot/webui/history.py +++ b/nanobot/webui/history.py @@ -40,7 +40,7 @@ _CONTENT_FIELDS = frozenset({ "session_message", INBOUND_META_LOCAL_MEDIA, "tool_events", "edits", "source", "response_sources", "resuming", "merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state", "outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message", - "transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", + "transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as", }) diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index af8d7f472..6c72af476 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -22,6 +22,7 @@ from urllib.parse import unquote, urlparse from loguru import logger from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_TURN_ID +from nanobot.command.builtin import USER_SHELL_COMMAND from nanobot.runtime_context import public_history_message from nanobot.session.automation_turns import is_automation_kind from nanobot.session.display_history import ( @@ -757,6 +758,15 @@ def _is_legacy_raw_subagent_result(message: dict[str, Any]) -> bool: ) +def _is_user_shell_command(message: Mapping[str, Any]) -> bool: + content = message.get("content") + return ( + message.get("role") == "user" and message.get("_command") is True + and isinstance(content, str) + and (content == USER_SHELL_COMMAND or content.startswith(f"{USER_SHELL_COMMAND} ")) + ) + + def _session_user_event( session_key: str, message: dict[str, Any], @@ -1453,9 +1463,12 @@ def _client_projection_event( if event == "message": text = record.get("text") content = text if isinstance(text, str) else "" - if augment_assistant_text is not None: + render_as_text = record.get("render_as") == "text" + if not render_as_text and augment_assistant_text is not None: content = augment_assistant_text(content) projected = {"event": "message", **common, "text": content} + if render_as_text: + projected["render_as"] = "text" kind = record.get("kind") if kind in {"tool_hint", "progress", "reasoning"}: projected["kind"] = kind @@ -1795,6 +1808,31 @@ def build_webui_thread_response( lines = recovered_lines if _needs_incomplete_turn_recovery(lines): lines = _recover_incomplete_turns(lines, load_session_turns()) + bang_inputs = { + record.get("turn_id") for record in lines + if record.get("event") == "user" and isinstance(text := record.get("text"), str) + and text.startswith("!") + } + legacy_shell_candidates = { + record.get("turn_id") for record in lines + if record.get("event") == "message" and record.get("kind") is None + and record.get("render_as") != "text" and record.get("turn_id") in bang_inputs + and isinstance(record.get("turn_id"), str) + } + if legacy_shell_candidates: + if session_messages is None and session_messages_loader is not None: + session_messages = session_messages_loader() + shell_turns = { + message.get(INBOUND_META_TURN_ID) for message in session_messages or [] + if _is_user_shell_command(message) + and message.get(INBOUND_META_TURN_ID) in legacy_shell_candidates + } + lines = [ + {**record, "render_as": "text"} + if record.get("event") == "message" and record.get("kind") is None + and record.get("turn_id") in shell_turns else record + for record in lines + ] lines = _ensure_replay_identities(lines) payload: dict[str, Any] = { "schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index 3ff704f52..37a5af88f 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -1191,3 +1191,54 @@ def test_build_response_schema(history, monkeypatch, tmp_path) -> None: assert out["schemaVersion"] == WEBUI_TRANSCRIPT_SCHEMA_VERSION assert out["sessionKey"] == key assert len(_conversation_events(out)) == 1 + + +def test_shell_output_format_survives_reload_and_paging_without_loading_model_history(history, tmp_path) -> None: + from nanobot.session.manager import SessionManager + + key = "websocket:shell-output" + output = "Path\n----\n __pycache__\n```mermaid\nflowchart LR\n```\n![preview](local.png)\n" + history.append(key, {"event": "user", "text": "!pwd", "turn_id": "shell-turn"}) + history.append(key, { + "event": "message", "text": output, "render_as": "text", "turn_id": "shell-turn", + }) + history.append(key, {"event": "turn_end", "turn_id": "shell-turn"}) + _append_numbered_turn(history, key, "shell-output", 2) + reopened = SessionManager(tmp_path) + + def fail_if_loaded(): + pytest.fail("Recorded output formatting must not load model history") + + def build(**kwargs): + return reopened.project_history(key, lambda snapshot: transcript_module.build_webui_thread_response( + key, history=snapshot, session_messages_loader=fail_if_loaded, + augment_assistant_text=lambda text: text.replace("local.png", "/api/media/signed"), **kwargs, + )) + + latest = build(limit=2, direction="latest") + older = build(limit=2, before=latest["page"]["before_cursor"]) + [answer] = [event for event in older["events"] if event["event"] == "message"] + assert answer["text"] == output + assert answer["render_as"] == "text" + assert history.read(key)[1]["text"] == output + assert history.read(key)[1]["render_as"] == "text" + + +@pytest.mark.parametrize("command", [True, False]) +def test_existing_shell_output_uses_canonical_command_identity_not_bang_text(history, command) -> None: + key = "websocket:existing-shell-output" + output = "Path\n----\n__pycache__" + history.append(key, {"event": "user", "text": "!pwd", "turn_id": "shell-turn"}) + history.append(key, {"event": "message", "text": output, "turn_id": "shell-turn"}) + history.append(key, {"event": "turn_end", "turn_id": "shell-turn"}) + messages = [ + {"role": "user", "content": "/__shell pwd" if command else "!pwd", + "webui_turn_id": "shell-turn", "_command": command}, + {"role": "assistant", "content": output, "_command": command}, + ] + response = history.build(key, session_messages=messages) + [answer] = [event for event in response["events"] if event["event"] == "message"] + assert answer["text"] == output + assert answer.get("render_as") == ("text" if command else None) + assert history.read(key)[1]["text"] == output + assert messages[1]["content"] == output diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.py index a2b178991..d82a030cc 100644 --- a/tests/webui/test_gateway_webui_smoke.py +++ b/tests/webui/test_gateway_webui_smoke.py @@ -259,13 +259,15 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa await ws.send(json.dumps({ "type": "message", "chat_id": chat_id, - "content": "!printf shell-ok", + "content": "!echo shell-ok", "webui": True, "user_shell": True, "turn_id": "shell-turn", })) shell = await _recv_until(ws, "message") - assert "shell-ok" in shell["text"] + assert shell["text"].splitlines()[0] == "shell-ok" + assert "Exit code: 0" in shell["text"] + assert shell["render_as"] == "text" assert shell["turn_id"] == "shell-turn" await _recv_until(ws, "turn_end") @@ -286,8 +288,12 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa ] assert "/model" in contents assert any("Current model: `custom/smoke-model`" in text for text in contents) - assert "!printf shell-ok" in contents - assert any("shell-ok" in text for text in contents) + assert "!echo shell-ok" in contents + assert shell["text"] in contents + [shell_history] = [event for event in thread["events"] if event.get("event") == "message" + and event.get("turn_id") == "shell-turn"] + assert shell_history["text"] == shell["text"] + assert shell_history["render_as"] == shell["render_as"] finally: _stop_gateway(process) diff --git a/tui/src/app/app.ts b/tui/src/app/app.ts index 17fa644c1..26630926d 100644 --- a/tui/src/app/app.ts +++ b/tui/src/app/app.ts @@ -770,7 +770,7 @@ export class NanobotTui { if (this.modelCommandTurns.delete(event.turn_id)) { void this.refreshSessionMetadata(event.chat_id) } - if (!silent) this.transcript.assistant(event.text) + if (!silent) this.transcript.assistant(event.text, event.render_as) if (!this.activeTurn) this.status.content = "Ready" return } @@ -780,6 +780,8 @@ export class NanobotTui { this.activeLabel = event.kind === "tool_hint" ? "Working" : "Thinking" this.transcript.progress(event.text, event.tool_events) this.setActive(true) + } else if (event.render_as === "text") { + this.transcript.assistant(event.text, event.render_as) } else { this.finalMessage = event.text } diff --git a/tui/src/app/composer.test.ts b/tui/src/app/composer.test.ts index ef8c3c484..b55072b44 100644 --- a/tui/src/app/composer.test.ts +++ b/tui/src/app/composer.test.ts @@ -7,6 +7,7 @@ import type { ClipboardImageReader } from "../composer/clipboard-image" import { options, client, mount, waitUntil, occurrences } from "./test-support" import { LOCAL_COMMANDS } from "./commands" import type { CommandMenu } from "../menus/command-menu" +import type { Transcript } from "../rendering/transcript" describe("NanobotTui composer", () => { let setup: TestRendererSetup | undefined @@ -986,8 +987,8 @@ describe("NanobotTui composer", () => { expect(sent).toEqual(["start an active turn"]) }) - test("runs bang commands through the gateway without steering the agent", async () => { - setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" }) + test("runs bang commands through the gateway and copies their literal output without steering the agent", async () => { + setup = await createRenderer({ width: 100, height: 32, screenMode: "alternate-screen" }) const sent: string[] = [] const sentOptions: MessageOptions[] = [] const app = NanobotTui.mount( @@ -997,7 +998,9 @@ describe("NanobotTui composer", () => { new MockTreeSitterClient({ autoResolveTimeout: 0 }), ) app.accept({ event: "attached", chat_id: "chat" }) - const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; activeTurn: boolean } + const ui = app as unknown as { + ready: boolean; composer: TextareaRenderable; activeTurn: boolean; transcript: Transcript + } await waitUntil(() => ui.ready) app.accept({ event: "goal_status", chat_id: "chat", status: "running" }) @@ -1009,9 +1012,32 @@ describe("NanobotTui composer", () => { expect(sentOptions).toEqual([{ userShell: true }]) expect(ui.activeTurn).toBe(true) - app.accept({ event: "message", chat_id: "chat", text: "/tmp/project", turn_id: "turn" }) + const output = [ + " __pycache__ `ticks` ``` ````", + "![image](image.png) HTML", + "\\(x_1^2\\)", + "```mermaid", + "graph TD; A --> B", + "```", + "", + ].join("\n") + app.accept({ event: "message", chat_id: "chat", text: output, render_as: "text", turn_id: "turn" }) await setup.flush() - expect(setup.captureCharFrame()).toContain("/tmp/project") + const text = ui.transcript.root.getChildren().flatMap((row) => row.getChildren()) + .find((child) => child instanceof TextRenderable && child.plainText === output) + expect(text).toBeInstanceOf(TextRenderable) + expect(setup.captureCharFrame()).toContain("![image](image.png) HTML") + expect(setup.captureCharFrame()).toContain("\\(x_1^2\\)") + expect(setup.captureCharFrame()).toContain("```mermaid") expect(ui.activeTurn).toBe(true) + + let copied = "" + setup.renderer.copyToClipboardOSC52 = (value) => { copied = value; return true } + if (!(text instanceof TextRenderable)) throw new Error("missing literal shell output") + await setup.mockMouse.drag(text.screenX, text.screenY, text.screenX, text.screenY + text.height - 1) + expect(setup.renderer.getSelection()?.getSelectedText()).toBe(output) + setup.mockInput.pressCtrlC() + await waitUntil(() => copied.length > 0) + expect(copied).toBe(output) }) }) diff --git a/tui/src/app/transcript.test.ts b/tui/src/app/transcript.test.ts index 9cf7d2f15..c9098f94f 100644 --- a/tui/src/app/transcript.test.ts +++ b/tui/src/app/transcript.test.ts @@ -1,8 +1,9 @@ import { afterEach, describe, expect, test } from "bun:test" -import { BoxRenderable, CliRenderEvents, TextareaRenderable, TextRenderable } from "@opentui/core" +import { BoxRenderable, CliRenderEvents, MarkdownRenderable, TextareaRenderable, TextRenderable } from "@opentui/core" import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing" import { NanobotTui } from "./app" import { options, client, mount, waitUntil, occurrences } from "./test-support" +import type { Transcript } from "../rendering/transcript" describe("NanobotTui transcript", () => { let setup: TestRendererSetup | undefined @@ -16,9 +17,11 @@ describe("NanobotTui transcript", () => { createTestRenderer(rendererOptions) ) test("loads earlier transcript pages in place when PageUp reaches the top", async () => { - setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" }) + setup = await createRenderer({ width: 100, height: 40, screenMode: "alternate-screen" }) const original = globalThis.fetch const requests: string[] = [] + const oldest = "oldest answer `ticks` __pycache__\n ![image](image.png) HTML\n" + const recent = "recent answer \\(x_1^2\\)\n```mermaid\ngraph TD; A --> B\n```\n" globalThis.fetch = ((input: string | URL | Request) => { const url = String(input) requests.push(url) @@ -27,12 +30,13 @@ describe("NanobotTui transcript", () => { schemaVersion: 3, projection: "events", events: older ? [ - { event: "user_message", chat_id: "chat", starts_turn: true, text: "oldest question" }, - { event: "stream_end", chat_id: "chat", text: "oldest answer" }, + { event: "user_message", chat_id: "chat", starts_turn: false, text: "!cat oldest.log", turn_id: "old-shell" }, + { event: "message", chat_id: "chat", text: oldest, render_as: "text", turn_id: "old-shell" }, ] : [ - { event: "user_message", chat_id: "chat", starts_turn: true, text: "recent question" }, - { event: "stream_end", chat_id: "chat", text: "recent answer" }, + { event: "user_message", chat_id: "chat", starts_turn: false, text: "!cat recent.log", turn_id: "recent-shell" }, + { event: "message", chat_id: "chat", text: recent, render_as: "text", turn_id: "recent-shell" }, + { event: "stream_end", chat_id: "chat", text: "Normal \\(x_1^2\\)", turn_id: "agent" }, ], page: older ? { has_more_before: false, before_cursor: null } @@ -55,20 +59,48 @@ describe("NanobotTui transcript", () => { await setup.flush() const frame = setup.captureCharFrame() - expect(frame.indexOf("oldest question")).toBeLessThan(frame.indexOf("recent question")) + expect(frame.indexOf("!cat oldest.log")).toBeLessThan(frame.indexOf("!cat recent.log")) expect(frame.indexOf("oldest answer")).toBeLessThan(frame.indexOf("recent answer")) expect((app as unknown as { historyHasMore: boolean }).historyHasMore).toBe(false) + const transcript = (app as unknown as { transcript: Transcript }).transcript + const cells = transcript.root.getChildren().flatMap((row) => row.getChildren()) + expect(cells.filter((child) => child instanceof TextRenderable) + .map((child) => child.plainText)).toEqual(expect.arrayContaining([oldest, recent])) + expect(cells.filter((child) => child instanceof MarkdownRenderable) + .map((child) => child.content)).toEqual(["Normal x₁²"]) + expect(frame).toContain("![image](image.png) HTML") + expect(frame).toContain("```mermaid") const composer = (app as unknown as { composer: TextareaRenderable }).composer setup.mockInput.pressArrow("up") - expect(composer.plainText).toBe("recent question") + expect(composer.plainText).toBe("!cat recent.log") setup.mockInput.pressArrow("up") - expect(composer.plainText).toBe("oldest question") + expect(composer.plainText).toBe("!cat oldest.log") } finally { globalThis.fetch = original } }) + test("shows literal shell output from another client without replacing a pending Markdown reply", async () => { + setup = await createRenderer({ width: 100, height: 26, screenMode: "alternate-screen" }) + const app = mount(setup) + app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "agent" }) + app.accept({ event: "message", chat_id: "chat", text: "Normal \\(x_1^2\\)", turn_id: "agent" }) + const output = " __pycache__ `ticks` ![image](image.png) HTML\n" + app.accept({ event: "message", chat_id: "chat", text: output, render_as: "text", turn_id: "other-shell" }) + await setup.flush() + expect(setup.captureCharFrame()).toContain("__pycache__ `ticks` ![image](image.png) HTML") + const ui = app as unknown as { activeTurn: boolean; transcript: Transcript } + expect(ui.activeTurn).toBe(true) + + app.accept({ event: "turn_end", chat_id: "chat", turn_id: "agent" }) + await setup.flush() + const cells = ui.transcript.root.getChildren().flatMap((row) => row.getChildren()) + expect(cells.some((child) => child instanceof TextRenderable && child.plainText === output)).toBe(true) + expect(cells.some((child) => child instanceof MarkdownRenderable && child.content === "Normal x₁²")).toBe(true) + expect(ui.activeTurn).toBe(false) + }) + test("replaces streamed drafts with canonical stream-end text", async () => { setup = await createRenderer({ width: 80, height: 20, screenMode: "alternate-screen" }) const app = mount(setup) diff --git a/tui/src/client/api.ts b/tui/src/client/api.ts index f0c8f1b37..7a92958a8 100644 --- a/tui/src/client/api.ts +++ b/tui/src/client/api.ts @@ -229,12 +229,15 @@ export async function fetchHistory( }) } else { // A final message can repeat the answer already saved by stream_end. - if (stream && stream.turnId === event.turn_id) stream.row.content = event.text - else if (!lastAnswer || lastAnswer.turnId !== event.turn_id || lastAnswer.row.content !== event.text) { + if (stream && stream.turnId === event.turn_id) { + stream.row.content = event.text + lastAnswer = stream + } else if (!lastAnswer || lastAnswer.turnId !== event.turn_id || lastAnswer.row.content !== event.text) { const row: HistoryMessage = { role: "assistant", content: event.text, forkIndex: userIndex } messages.push(row) lastAnswer = { row, turnId: event.turn_id } } + if (event.render_as === "text" && lastAnswer) lastAnswer.row.renderAs = event.render_as stream = null } break @@ -258,7 +261,8 @@ export async function fetchHistory( } } return { - messages: messages.filter((row) => row.role !== "assistant" || row.content.trim()), + messages: messages.filter((row) => row.role !== "assistant" + || (row.renderAs === "text" ? row.content : row.content.trim())), hasMoreBefore: payload.page?.has_more_before === true, beforeCursor: typeof payload.page?.before_cursor === "string" ? payload.page.before_cursor diff --git a/tui/src/client/client.test.ts b/tui/src/client/client.test.ts index a9ffe1a99..11ffec15f 100644 --- a/tui/src/client/client.test.ts +++ b/tui/src/client/client.test.ts @@ -502,6 +502,8 @@ describe("gateway protocol", () => { starts_turn: true, media_urls: [{ kind: "file", url: "/api/media/sig/file", name: "report.pdf" }], }, + { event: "message", chat_id: "one", text: " __pycache__ `ticks`\n", render_as: "text" }, + { event: "message", chat_id: "one", text: "**Markdown reply**" }, { event: "delta", chat_id: "one", text: "hello" }, { event: "stream_end", chat_id: "one", resuming: false }, { event: "turn_end", chat_id: "one", latency_ms: 12 }, @@ -522,6 +524,10 @@ describe("gateway protocol", () => { socket.emit("message", { data: JSON.stringify(frame) }) } expect(delivered).toEqual(frames) + socket.emit("message", { data: JSON.stringify({ + event: "message", chat_id: "one", text: "**Markdown reply**", render_as: true, + }) }) + expect(delivered.at(-1)).toEqual({ event: "message", chat_id: "one", text: "**Markdown reply**" }) } finally { client.close() Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original }) diff --git a/tui/src/client/history.test.ts b/tui/src/client/history.test.ts index dd1c123eb..0ba951c37 100644 --- a/tui/src/client/history.test.ts +++ b/tui/src/client/history.test.ts @@ -40,6 +40,25 @@ test("restores canonical event history, media, tools, file edits and absolute fo }) }) +test("preserves literal shell output and leaves ordinary replies as Markdown", async () => { + const output = " __pycache__ `ticks`\n![image](image.png) HTML\n```mermaid\ngraph TD; A --> B\n```\n" + respond([ + { event: "user_message", starts_turn: false, text: "!ls", turn_id: "shell" }, + { event: "message", text: output, render_as: "text", turn_id: "shell" }, + { event: "user_message", starts_turn: true, text: "explain", turn_id: "answer" }, + { event: "message", text: "**Markdown** \\(x_1^2\\)", turn_id: "answer" }, + { event: "turn_end", turn_id: "answer" }, + { event: "message", text: "**Another reply**", render_as: true, turn_id: "next" }, + ]) + expect((await fetchHistory("http://fixture", "token", "chat")).messages).toEqual([ + { role: "user", content: "!ls", turnId: "shell" }, + { role: "assistant", content: output, renderAs: "text", forkIndex: 1 }, + { role: "user", content: "explain", turnId: "answer" }, + { role: "assistant", content: "**Markdown** \\(x_1^2\\)", forkIndex: 2 }, + { role: "assistant", content: "**Another reply**", forkIndex: 2 }, + ]) +}) + test("keeps distinct answer segments and resumes an unfinished stream", async () => { respond([ { event: "user_message", starts_turn: true, text: "question" }, diff --git a/tui/src/client/types.ts b/tui/src/client/types.ts index 352fd57a3..027a85add 100644 --- a/tui/src/client/types.ts +++ b/tui/src/client/types.ts @@ -116,6 +116,7 @@ export type InboundEvent = event: "message" chat_id: string text: string + render_as?: "text" kind?: "tool_hint" | "progress" | "reasoning" tool_events?: ToolProgressEvent[] turn_id?: string @@ -229,6 +230,7 @@ export type ApiReauthenticator = ( export interface HistoryMessage { role: "user" | "assistant" | "activity" content: string + renderAs?: "text" turnId?: string media?: MediaAttachment[] toolEvents?: ToolProgressEvent[] diff --git a/tui/src/client/validation.ts b/tui/src/client/validation.ts index 99b8cd94d..e141d230c 100644 --- a/tui/src/client/validation.ts +++ b/tui/src/client/validation.ts @@ -233,5 +233,10 @@ export function decodeInboundEvent(value: unknown): InboundEvent | null | undefi && typeof record.model_preset !== "string") || !optional(record.context_window_tokens, "number")) ) return null + if (name === "message" && record.render_as !== undefined && record.render_as !== "text") { + const message = { ...record } + delete message.render_as + return message as InboundEvent + } return value as InboundEvent } diff --git a/tui/src/rendering/transcript.ts b/tui/src/rendering/transcript.ts index 9d45c4801..d49b19f35 100644 --- a/tui/src/rendering/transcript.ts +++ b/tui/src/rendering/transcript.ts @@ -262,7 +262,7 @@ export class Transcript { else if (message.role === "user") { this.user(message.content, message.turnId, message.media) } - else if (message.role === "assistant") this.assistant(message.content) + else if (message.role === "assistant") this.assistant(message.content, message.renderAs) else if (message.fileEdits?.length) this.fileEdits(message.fileEdits) else this.progress(message.content, message.toolEvents) } @@ -282,7 +282,7 @@ export class Transcript { this.writeUser(message.content, message.media, index++) if (message.turnId) this.userTurnIds.add(message.turnId) } else if (message.role === "assistant") { - this.writeMarkdown(message.content, false, index++) + this.writeAnswer(message.content, message.renderAs, index++) } else { const activity = this.createActivity(index++) const events: ToolProgressEvent[] = message.fileEdits?.length @@ -319,11 +319,11 @@ export class Transcript { return true } - assistant(content: string): void { - if (!content.trim()) return + assistant(content: string, renderAs?: "text"): void { + if (!(renderAs === "text" ? content : content.trim())) return this.noteOutput() this.finishActivity() - this.writeMarkdown(content, false) + this.writeAnswer(content, renderAs) } notice(content: string, error = false): void { @@ -756,17 +756,26 @@ export class Transcript { return markdown } - private writeMarkdown(content: string, streaming: boolean, index?: number): void { - this.writeAssistant(this.createMarkdown(content, streaming), index) + private writeAnswer(content: string, renderAs?: "text", index?: number): void { + if (renderAs !== "text") { + this.writeAssistant(this.createMarkdown(content, false), index) + return + } + const text = this.createText(content, "text", false, "assistant-text") + text.width = "auto" + text.minWidth = 0 + text.flexGrow = 1 + text.flexShrink = 1 + this.writeAssistant(text, index) } - private writeAssistant(markdown: MarkdownRenderable, index?: number): BoxRenderable { + private writeAssistant(content: MarkdownRenderable | TextRenderable, index?: number): BoxRenderable { const row = this.createRow("assistant", "row") const prefix = this.createText("•", "muted", false, "role-marker") prefix.width = 2 prefix.flexShrink = 0 row.add(prefix) - row.add(markdown) + row.add(content) this.root.add(row, index) this.wrote = true return row diff --git a/webui/browser/inline-references-fixture.tsx b/webui/browser/inline-references-fixture.tsx index 441d2d2be..f249d15d5 100644 --- a/webui/browser/inline-references-fixture.tsx +++ b/webui/browser/inline-references-fixture.tsx @@ -28,9 +28,13 @@ export function InlineReferencesFixture() {
{[answer, ...sent].map(message => )} setSent(current => [...current, { + onSend={(text, _media, options) => setSent(current => [...current, { id: `sent-${current.length}`, role: "user", content: text, createdAt: current.length + 2, - }])} /> + }, ...(options?.userShell ? [{ + id: `shell-${current.length}`, role: "assistant" as const, renderAs: "text" as const, + content: " __pycache__\n```mermaid\nflowchart LR\n```\n![preview](local.png)\nraw\n", + createdAt: current.length + 3, + }] : [])])} />
; } diff --git a/webui/browser/inline-references.spec.ts b/webui/browser/inline-references.spec.ts index 187851cc3..794aa9b38 100644 --- a/webui/browser/inline-references.spec.ts +++ b/webui/browser/inline-references.spec.ts @@ -1,3 +1,5 @@ +import { EOL } from "node:os"; + import { expect, test, type Locator } from "@playwright/test"; async function expectMatchingInputLayers(input: Locator) { @@ -134,6 +136,45 @@ for (const narrow of [false, true]) { await expect(command.locator("span")).toHaveCSS("opacity", "0.9"); await expect(page.locator("[data-user-text-bubble]").last().locator("p")).toHaveText(text); await page.screenshot({ path: info.outputPath("slash-command-and-skill.png") }); + + const shellCommand = ' !echo "hello! $workflow @typography"\nWrite-Output "命令输出"'; + await input.fill(shellCommand); + const bang = page.getByTestId("composer-shell-prefix"); + await expect(bang).toHaveText("!"); + await expect(bang).toHaveCSS("color", await page.getByTestId("message-skill-reference-workflow").evaluate(node => getComputedStyle(node).color)); + await expect(bang).toHaveCSS("font-weight", "400"); + await expectMatchingInputLayers(input); + await input.press("ControlOrMeta+a"); + await input.press("ControlOrMeta+c"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(shellCommand); + await input.press("ArrowRight"); + await page.screenshot({ path: info.outputPath("composer-bang.png") }); + const prefixColor = await bang.evaluate(node => getComputedStyle(node).color); + await page.getByRole("button", { name: "Run Shell command", exact: true }).click(); + const sentPrefix = page.getByTestId("message-shell-prefix"); + await expect(sentPrefix).toHaveText("!"); + await expect(sentPrefix).toHaveCSS("color", prefixColor); + await expect(sentPrefix).toHaveCSS("font-weight", "400"); + const sentCommand = page.locator("[data-user-text-bubble]").last().locator("p"); + expect(await sentCommand.textContent()).toBe(shellCommand.trim()); + await sentCommand.evaluate(node => { + const range = document.createRange(); + range.selectNodeContents(node); + const selection = window.getSelection()!; + selection.removeAllRanges(); + selection.addRange(range); + }); + await page.keyboard.press("ControlOrMeta+c"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(shellCommand.trim().replaceAll("\n", EOL)); + await page.evaluate(() => window.getSelection()?.removeAllRanges()); + await page.screenshot({ path: info.outputPath("sent-bang.png") }); + + const output = page.getByTestId("plain-code-fallback"); + const literal = " __pycache__\n```mermaid\nflowchart LR\n```\n![preview](local.png)\nraw\n"; + expect(await output.textContent()).toBe(literal); + await expect(output.locator("img, b")).toHaveCount(0); + await page.getByRole("button", { name: "Copy code", exact: true }).click(); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(literal); expect(errors).toEqual([]); }); } diff --git a/webui/src/components/CodeBlock.tsx b/webui/src/components/CodeBlock.tsx index 0d581af56..a2c190543 100644 --- a/webui/src/components/CodeBlock.tsx +++ b/webui/src/components/CodeBlock.tsx @@ -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(null); const [copied, setCopied] = useState(false); const [highlightedSource, setHighlightedSource] = useState(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"; diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 23c249157..b3c3e1149 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -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]} + + ! + + {userContent.slice(bangPrefix[0].length)} + + ) : slashCommand ? ( <>
- {/* 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__ ", + "![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(); + 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), {