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

+5 -1
View File
@@ -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
@@ -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))
+1 -1
View File
@@ -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",
})
+39 -1
View File
@@ -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,