fix(chat): preserve routing for side-channel command replies (#6736)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-20 16:47:07 +08:00
1 parent 3e9024ea04
commit cd75dbfaac
13 files changed
+155 -34

No files matched your search

+7
View File
@@ -56,6 +56,13 @@ class StreamedResponseEvent(AgentEvent):
pass pass
@dataclass(frozen=True)
class SideChannelReplyEvent(AgentEvent):
"""Command text that does not replace the active assistant answer."""
notification_id: str | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
class TurnEndEvent(AgentEvent): class TurnEndEvent(AgentEvent):
latency_ms: int | None = None latency_ms: int | None = None
@@ -15,6 +15,7 @@ from websockets.datastructures import Headers
from websockets.exceptions import ConnectionClosed from websockets.exceptions import ConnectionClosed
from websockets.frames import Close from websockets.frames import Close
from nanobot.agent.dream import DreamResult
from nanobot.bus.events import ( from nanobot.bus.events import (
INBOUND_META_RUNTIME_CONTROL, INBOUND_META_RUNTIME_CONTROL,
INBOUND_META_USER_SHELL, INBOUND_META_USER_SHELL,
@@ -47,6 +48,8 @@ from nanobot.channels.websocket.runtime import (
_parse_envelope, _parse_envelope,
_parse_inbound_payload, _parse_inbound_payload,
) )
from nanobot.command.builtin import cmd_dream
from nanobot.command.router import CommandContext
from nanobot.config.loader import load_config, save_config from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
from nanobot.pairing.events import PairingChanged from nanobot.pairing.events import PairingChanged
@@ -3531,6 +3534,50 @@ async def test_context_compaction_is_structured_persisted_and_summary_free(histo
assert {key: persisted[key] for key in expected} == expected assert {key: persisted[key] for key in expected} == expected
async def test_deferred_dream_reply_is_delivered_and_replayed_after_command_turn_end(history, monkeypatch) -> None:
finish_dream = asyncio.Event()
async def run_dream(*_args, **_kwargs):
await finish_dream.wait()
return DreamResult(had_input=True, changed=True)
monkeypatch.setattr("nanobot.agent.dream.run_dream", run_dream)
bus = MessageBus()
channel = _ch(bus, session_manager=history.sessions)
chat_id = "chat-dream"
mock_ws = AsyncMock()
channel._attach(mock_ws, chat_id)
metadata = await history.metadata(chat_id, {WEBUI_TURN_METADATA_KEY: "dream-turn"})
msg = InboundMessage("websocket", "user", chat_id, "/dream", metadata=metadata)
context = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content,
loop=cast(Any, SimpleNamespace(bus=bus)))
acknowledgement = await cmd_dream(context)
try:
await channel.send(acknowledgement)
await channel.send(OutboundMessage("websocket", chat_id, "", metadata=metadata, event=TurnEndEvent()))
finally:
finish_dream.set()
completion = await asyncio.wait_for(bus.consume_outbound(), 2)
await channel.send(completion)
replies, replayed = (
[event for event in events if event["event"] == "message"]
for events in (_sent_ws_payloads(mock_ws), history.build(msg.session_key)["events"])
)
assert len(replies) == len(replayed) == 2
ack, completed = replies
assert ack["text"] == "Dreaming..."
assert ack["turn_id"] == "dream-turn"
assert completed["text"].startswith("Dream completed")
assert completed["turn_id"] != ack["turn_id"]
for reply, replay in zip(replies, replayed, strict=True):
assert reply["side_channel"] is True
assert {key: replay[key] for key in ("turn_id", "turn_seq", "side_channel", "text")} == {
key: reply[key] for key in ("turn_id", "turn_seq", "side_channel", "text")
}
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_recovery_state_is_a_structured_event_not_assistant_text(history) -> None: async def test_recovery_state_is_a_structured_event_not_assistant_text(history) -> None:
bus = MagicMock() bus = MagicMock()
+27 -29
View File
@@ -7,11 +7,13 @@ import sys
from contextlib import suppress from contextlib import suppress
from dataclasses import replace from dataclasses import replace
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from uuid import uuid4
from loguru import logger from loguru import logger
from nanobot import __version__ from nanobot import __version__
from nanobot.bus.events import OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import SideChannelReplyEvent
from nanobot.command.router import CommandContext, CommandRouter from nanobot.command.router import CommandContext, CommandRouter
from nanobot.command.spec import BuiltinCommandSpec from nanobot.command.spec import BuiltinCommandSpec
from nanobot.command.spec import CommandLifecycle as CommandLifecycle from nanobot.command.spec import CommandLifecycle as CommandLifecycle
@@ -367,12 +369,23 @@ async def cmd_model(ctx: CommandContext) -> OutboundMessage:
) )
def _side_channel_reply(msg: InboundMessage, content: str, **metadata: Any) -> OutboundMessage:
return OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content=content,
metadata={**msg.metadata, **metadata},
event=SideChannelReplyEvent(),
)
async def cmd_dream(ctx: CommandContext) -> OutboundMessage: async def cmd_dream(ctx: CommandContext) -> OutboundMessage:
"""Manually trigger a Dream consolidation run.""" """Manually trigger a Dream consolidation run."""
import time import time
loop = ctx.loop loop = ctx.loop
msg = ctx.msg acknowledgement = _side_channel_reply(ctx.msg, "Dreaming...")
metadata = dict(acknowledgement.metadata)
async def _run_dream(): async def _run_dream():
from nanobot.agent.dream import run_dream from nanobot.agent.dream import run_dream
@@ -390,15 +403,15 @@ async def cmd_dream(ctx: CommandContext) -> OutboundMessage:
content = f"Dream completed in {elapsed:.1f}s; no memory changes." content = f"Dream completed in {elapsed:.1f}s; no memory changes."
if result.commit_sha: if result.commit_sha:
content += f" (commit {result.commit_sha})" content += f" (commit {result.commit_sha})"
await loop.bus.publish_outbound(OutboundMessage( await loop.bus.publish_outbound(replace(
channel=msg.channel, chat_id=msg.chat_id, content=content, acknowledgement,
metadata={"render_as": "text"} if not result.had_input else {}, content=content,
metadata=metadata if result.had_input else {**metadata, "render_as": "text"},
event=SideChannelReplyEvent(notification_id=f"command-result:{uuid4().hex}"),
)) ))
asyncio.create_task(_run_dream()) asyncio.create_task(_run_dream())
return OutboundMessage( return acknowledgement
channel=msg.channel, chat_id=msg.chat_id, content="Dreaming...",
)
async def cmd_dream_prompt(ctx: CommandContext) -> OutboundMessage: async def cmd_dream_prompt(ctx: CommandContext) -> OutboundMessage:
@@ -608,10 +621,7 @@ async def cmd_dream_log(ctx: CommandContext) -> OutboundMessage:
) )
else: else:
msg = "Dream history is not available because memory versioning is not initialized." msg = "Dream history is not available because memory versioning is not initialized."
return OutboundMessage( return _side_channel_reply(ctx.msg, msg, render_as="text")
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id,
content=msg, metadata={"render_as": "text"},
)
args = ctx.args.strip() args = ctx.args.strip()
@@ -646,10 +656,7 @@ async def cmd_dream_log(ctx: CommandContext) -> OutboundMessage:
"Use `/dream-prompt` to see or change how Dream organizes memory." "Use `/dream-prompt` to see or change how Dream organizes memory."
) )
return OutboundMessage( return _side_channel_reply(ctx.msg, content, render_as="text")
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id,
content=content, metadata={"render_as": "text"},
)
async def cmd_dream_restore(ctx: CommandContext) -> OutboundMessage: async def cmd_dream_restore(ctx: CommandContext) -> OutboundMessage:
@@ -662,9 +669,8 @@ async def cmd_dream_restore(ctx: CommandContext) -> OutboundMessage:
store = ctx.loop.consolidator.store store = ctx.loop.consolidator.store
git = store.git git = store.git
if not git.is_initialized(): if not git.is_initialized():
return OutboundMessage( return _side_channel_reply(
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id, ctx.msg, "Dream history is not available because memory versioning is not initialized.",
content="Dream history is not available because memory versioning is not initialized.",
) )
args = ctx.args.strip() args = ctx.args.strip()
@@ -706,10 +712,7 @@ async def cmd_dream_restore(ctx: CommandContext) -> OutboundMessage:
f"Couldn't restore Dream change `{sha}`.\n\n" f"Couldn't restore Dream change `{sha}`.\n\n"
"It may be the first saved version with no earlier state to restore." "It may be the first saved version with no earlier state to restore."
) )
return OutboundMessage( return _side_channel_reply(ctx.msg, content, render_as="text")
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id,
content=content, metadata={"render_as": "text"},
)
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage: async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
@@ -721,12 +724,7 @@ async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
ctx.loop.bus.publish_nowait(PairingChanged()) ctx.loop.bus.publish_nowait(PairingChanged())
reply = handle_pairing_command(ctx.msg.channel, ctx.args, on_change=changed) reply = handle_pairing_command(ctx.msg.channel, ctx.args, on_change=changed)
return OutboundMessage( return _side_channel_reply(ctx.msg, reply, **{PAIRING_COMMAND_META_KEY: True})
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content=reply,
metadata={PAIRING_COMMAND_META_KEY: True},
)
async def cmd_skill(ctx: CommandContext) -> OutboundMessage: async def cmd_skill(ctx: CommandContext) -> OutboundMessage:
+1
View File
@@ -41,6 +41,7 @@ _CONTENT_FIELDS = frozenset({
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state", "merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message", "outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
"transcript_incomplete", "stream_id", "text_from_seq", "compaction_id", "phase", "reason", "render_as", "transcript_incomplete", "stream_id", "text_from_seq", "compaction_id", "phase", "reason", "render_as",
"side_channel",
"request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot", "request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot",
}) })
+6
View File
@@ -19,6 +19,7 @@ from nanobot.bus.outbound_events import (
RetryWaitEvent, RetryWaitEvent,
RuntimeModelUpdatedEvent, RuntimeModelUpdatedEvent,
SessionUpdatedEvent, SessionUpdatedEvent,
SideChannelReplyEvent,
TurnEndEvent, TurnEndEvent,
TurnModelUpdatedEvent, TurnModelUpdatedEvent,
UserInputEvent, UserInputEvent,
@@ -452,6 +453,8 @@ class WebUIOutboundDelivery:
} }
if user_shell: if user_shell:
payload["render_as"] = "text" payload["render_as"] = "text"
if isinstance(msg.event, SideChannelReplyEvent):
payload["side_channel"] = True
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY) turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
if isinstance(turn_id, str) and turn_id: if isinstance(turn_id, str) and turn_id:
payload["turn_id"] = turn_id payload["turn_id"] = turn_id
@@ -483,6 +486,9 @@ class WebUIOutboundDelivery:
return dict(payload) return dict(payload)
async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None: async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None:
if isinstance(msg.event, SideChannelReplyEvent) and msg.event.notification_id is not None:
# A deferred reply can outlive the command's turn_end. It must not reuse that sequence.
msg = replace(msg, metadata={**msg.metadata, WEBUI_TURN_METADATA_KEY: msg.event.notification_id})
recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id))
body = await self._message_payload(msg, progress) body = await self._message_payload(msg, progress)
await self._persist_turn_transcript_event( await self._persist_turn_transcript_event(
+1
View File
@@ -128,6 +128,7 @@ class SubagentTaskWirePayload(_ChatWirePayload):
class MessageWirePayload(_ChatWirePayload): class MessageWirePayload(_ChatWirePayload):
event: Literal["message"] event: Literal["message"]
text: str text: str
side_channel: NotRequired[Literal[True]]
render_as: NotRequired[Literal["text"]] render_as: NotRequired[Literal["text"]]
media: NotRequired[list[str]] media: NotRequired[list[str]]
media_urls: NotRequired[list[dict[str, str]]] media_urls: NotRequired[list[dict[str, str]]]
+2
View File
@@ -1129,6 +1129,8 @@ def _client_projection_event(
content = text if isinstance(text, str) else "" content = text if isinstance(text, str) else ""
render_as_text = record.get("render_as") == "text" render_as_text = record.get("render_as") == "text"
projected = {"event": "message", **common, "text": content} projected = {"event": "message", **common, "text": content}
if record.get("side_channel") is True:
projected["side_channel"] = True
if render_as_text: if render_as_text:
projected["render_as"] = "text" projected["render_as"] = "text"
kind = record.get("kind") kind = record.get("kind")
+19 -2
View File
@@ -155,12 +155,15 @@ async def _run_dream_command(ctx: CommandContext) -> OutboundMessage:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_dream_no_history_explains_how_to_create_input(tmp_path) -> None: async def test_dream_no_history_explains_how_to_create_input(tmp_path) -> None:
ctx, bus = _make_dream_ctx(tmp_path) ctx, bus = _make_dream_ctx(tmp_path)
ctx.msg.metadata = {"slack": {"thread_ts": "123.456"}}
immediate = await _run_dream_command(ctx) immediate = await _run_dream_command(ctx)
assert immediate.content == "Dreaming..." assert immediate.content == "Dreaming..."
assert len(bus.outbound) == 1 assert immediate.metadata == ctx.msg.metadata
content = bus.outbound[0].content [completion] = bus.outbound
assert completion.metadata == {**ctx.msg.metadata, "render_as": "text"}
content = completion.content
assert "Dream has no conversation history to process yet." in content assert "Dream has no conversation history to process yet." in content
assert "`memory/history.jsonl`" in content assert "`memory/history.jsonl`" in content
assert "idle auto-compact" in content assert "idle auto-compact" in content
@@ -214,6 +217,20 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:
assert progress_sentinel not in completion.content assert progress_sentinel not in completion.content
@pytest.mark.parametrize("command,handler", [("/dream-log", cmd_dream_log), ("/dream-restore", cmd_dream_restore)])
@pytest.mark.parametrize("initialized", [False, True])
async def test_dream_inspection_replies_preserve_topic_routing(command, handler, initialized) -> None:
ctx = _make_ctx(command, _FakeGit(initialized=initialized))
ctx.msg.metadata = {"message_thread_id": 12, "message_id": 34}
reply = await handler(ctx)
assert reply.metadata == {
**ctx.msg.metadata,
**({"render_as": "text"} if initialized or command == "/dream-log" else {}),
}
@pytest.mark.parametrize("completed", [True, False]) @pytest.mark.parametrize("completed", [True, False])
async def test_dream_command_reports_outcome_and_versions_only_real_edits(tmp_path, completed) -> None: async def test_dream_command_reports_outcome_and_versions_only_real_edits(tmp_path, completed) -> None:
ctx, bus = _make_dream_ctx(tmp_path) ctx, bus = _make_dream_ctx(tmp_path)
+3 -1
View File
@@ -6,7 +6,7 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import cmd_pairing from nanobot.command.builtin import cmd_pairing
from nanobot.command.router import CommandContext from nanobot.command.router import CommandContext
from nanobot.pairing import store from nanobot.pairing import PAIRING_COMMAND_META_KEY, store
from nanobot.pairing.events import PairingChanged from nanobot.pairing.events import PairingChanged
@@ -19,10 +19,12 @@ async def test_pairing_command_notifies_after_persistence_without_a_file_watcher
bus.subscribe(lambda _event: approved.append(store.is_approved("telegram", "alice")), PairingChanged) bus.subscribe(lambda _event: approved.append(store.is_approved("telegram", "alice")), PairingChanged)
loop = MagicMock(bus=bus) loop = MagicMock(bus=bus)
msg = InboundMessage(channel="cli", sender_id="owner", chat_id="direct", content=f"/pairing approve {code}") msg = InboundMessage(channel="cli", sender_id="owner", chat_id="direct", content=f"/pairing approve {code}")
msg.metadata = {"webui_turn_id": "pairing-turn", "_history_generation": "admitted"}
ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content, args=f"approve {code}", loop=loop) ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw=msg.content, args=f"approve {code}", loop=loop)
result = await cmd_pairing(ctx) result = await cmd_pairing(ctx)
await bus.drain() await bus.drain()
assert "Approved" in result.content and approved == [True] assert "Approved" in result.content and approved == [True]
assert result.metadata == {**msg.metadata, PAIRING_COMMAND_META_KEY: True}
ctx.args = "approve invalid" ctx.args = "approve invalid"
await cmd_pairing(ctx) await cmd_pairing(ctx)
ctx.args = "list" ctx.args = "list"
+1
View File
@@ -369,6 +369,7 @@ function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet
return value as unknown as ThreadProjectionEvent; return value as unknown as ThreadProjectionEvent;
case "message": case "message":
if (typeof value.text !== "string") break; if (typeof value.text !== "string") break;
if (value.side_channel !== undefined && value.side_channel !== true) break;
if (value.tool_events !== undefined && !isRecordArray(value.tool_events)) break; if (value.tool_events !== undefined && !isRecordArray(value.tool_events)) break;
if (value.trace_detail !== undefined && ( if (value.trace_detail !== undefined && (
!["tool_hint", "progress"].includes(String(value.kind)) !["tool_hint", "progress"].includes(String(value.kind))
+3 -2
View File
@@ -1161,6 +1161,7 @@ function reduceThreadEvent(
const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0 const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0
? Math.round(event.latency_ms) ? Math.round(event.latency_ms)
: undefined; : undefined;
const sideChannel = event.side_channel === true || options.sideChannel;
const projected = { const projected = {
content: event.text, content: event.text,
...(event.render_as === "text" ? { renderAs: event.render_as } : {}), ...(event.render_as === "text" ? { renderAs: event.render_as } : {}),
@@ -1170,12 +1171,12 @@ function reduceThreadEvent(
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}), ...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}),
...positionedTurnFields( ...positionedTurnFields(
options.sideChannel ? undefined : state.messages.find((message) => message.id === state.activeAssistantId), sideChannel ? undefined : state.messages.find((message) => message.id === state.activeAssistantId),
turnFieldsForProjection(state, event, "answer"), turnFieldsForProjection(state, event, "answer"),
options, options,
), ),
}; };
if (options.sideChannel) { if (sideChannel) {
absorbProjectedAssistantMessage(state, event, projected, options); absorbProjectedAssistantMessage(state, event, projected, options);
return state; return state;
} }
+1
View File
@@ -1601,6 +1601,7 @@ export type InboundEvent =
event: "message"; event: "message";
chat_id: string; chat_id: string;
text: string; text: string;
side_channel?: true;
render_as?: "text"; render_as?: "text";
reply_to?: string; reply_to?: string;
media?: string[]; media?: string[];
+37
View File
@@ -3399,6 +3399,43 @@ describe("useNanobotStream", () => {
} }
}); });
it("keeps streaming when a deferred Dream reply arrives after its command has ended", async () => {
const fake = fakeClient();
const chatId = "chat-dream";
const { result } = renderHook(() => useNanobotStream(chatId, EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => { result.current.send("/dream", undefined, { sideChannel: true }); });
const dreamTurnId = fake.client.sendMessage.mock.calls.at(-1)![3]?.turnId;
act(() => {
fake.emit(chatId, { event: "message", chat_id: chatId, text: "Dreaming...",
turn_id: dreamTurnId, turn_seq: 1, side_channel: true });
fake.emit(chatId, { event: "turn_end", chat_id: chatId, turn_id: dreamTurnId, turn_seq: 2 });
});
act(() => { result.current.send("write normally"); });
const answerTurnId = fake.client.sendMessage.mock.calls.at(-1)![3]?.turnId;
act(() => {
fake.emit(chatId, { event: "delta", chat_id: chatId, text: "First half",
turn_id: answerTurnId, turn_seq: 1, stream_id: "answer-1" });
});
await flushStreamFrame();
const answerId = result.current.messages.find((message) => message.content === "First half")?.id;
expect(answerId).toBeDefined();
act(() => {
fake.emit(chatId, { event: "message", chat_id: chatId, text: "Dream completed.",
turn_id: "command-result:completion", turn_seq: 1, side_channel: true });
fake.emit(chatId, { event: "delta", chat_id: chatId, text: " and second half",
turn_id: answerTurnId, turn_seq: 2, stream_id: "answer-1" });
});
await flushStreamFrame();
expect(result.current.messages.find((message) => message.id === answerId)?.content)
.toBe("First half and second half");
expect(result.current.messages.map((message) => message.content)).toContain("Dream completed.");
});
it("keeps guided output in place while the active turn resumes", async () => { it("keeps guided output in place while the active turn resumes", async () => {
const fake = fakeClient(); const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-guide", EMPTY_MESSAGES), { const { result } = renderHook(() => useNanobotStream("chat-guide", EMPTY_MESSAGES), {