fix(sessions): preserve cross-session input ownership and history (#6613)

* fix(webui): reconcile cross-session history by message ID

* fix(sessions): preserve target authority and input ownership

Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed.

Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430.

* fix(sessions): complete input identity integration across boundaries

Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery.

Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run.

* fix(sessions): unify input recording and block remote commands

* fix(webui): keep input ownership checks page-bounded

Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages.

Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed.

* fix(webui): preserve response ownership during history replay

* fix: resolve strict typing in response replay

* fix: preserve continuation ownership during recovery

* test: diagnose stuck gateway asyncio shutdown

* test: retain gateway thread stack diagnostics

* test(webui): stabilize native autoscroll browser setup
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-11 10:46:44 +08:00
1 parent 0ce335bf12
commit 394a78e82d
51 files changed
+1412 -334

No files matched your search

+3
View File
@@ -64,6 +64,7 @@ class TranscriptInput:
current_role: str = "user"
session_summary: SessionSummary | None = None
runtime_context_blocks: Sequence[RuntimeContextBlock] | None = None
input_metadata: Mapping[str, Any] | None = None
@property
def message_count(self) -> int:
@@ -295,6 +296,8 @@ class ContextBuilder:
current_role=transcript.current_role,
runtime_context_blocks=transcript.runtime_context_blocks,
)
if transcript.input_metadata:
current["_meta"] = {**current.get("_meta", {}), **transcript.input_metadata}
messages.append(current)
return messages
+24 -35
View File
@@ -41,9 +41,7 @@ from nanobot.agent.turn_delivery import (
from nanobot.agent.turn_delivery import TurnRoute as TurnRoute
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.bus.events import (
INBOUND_META_LOCAL_MEDIA,
INBOUND_META_RUNTIME_CONTROL,
INBOUND_META_TURN_ID,
INBOUND_META_USER_SHELL,
RUNTIME_CONTROL_SESSION_DISCARD,
InboundMessage,
@@ -85,6 +83,7 @@ from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
from nanobot.session.message_metadata import input_history_metadata, persisted_message
from nanobot.session.model_selection import (
SESSION_MODEL_PRESET_METADATA_KEY,
model_preset_from_metadata,
@@ -646,7 +645,9 @@ class AgentLoop:
) -> None:
from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.session_messages import session_message_runtime_context
self.register_runtime_context_provider(session_message_runtime_context)
runtime_control = AgentRuntimeControl(self)
self.register_runtime_context_provider(runtime_control.workspace_context)
self.register_runtime_context_provider(
@@ -698,18 +699,6 @@ class AgentLoop:
def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]:
return self._local_trigger_turns.pending_trigger_ids_for_session(session_key)
@staticmethod
def _input_history_extra(msg: InboundMessage) -> dict[str, Any]:
"""Keep input admission separate from the run that eventually consumes it."""
extra: dict[str, Any] = {"timestamp": msg.timestamp.isoformat()}
turn_id = msg.metadata.get(INBOUND_META_TURN_ID)
if isinstance(turn_id, str) and turn_id:
extra[INBOUND_META_TURN_ID] = turn_id
local_media = msg.metadata.get(INBOUND_META_LOCAL_MEDIA)
if isinstance(local_media, list) and local_media:
extra[INBOUND_META_LOCAL_MEDIA] = [path for path in cast(list[object], local_media) if isinstance(path, str)]
return extra
async def _persist_user_message_early(
self,
msg: InboundMessage,
@@ -727,7 +716,7 @@ class AgentLoop:
content_value = cast(object, msg.content)
has_text = isinstance(content_value, str) and content_value.strip()
if has_text or media_paths or runtime_context_blocks:
extra = self._input_history_extra(msg) | ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
extra = input_history_metadata(msg) | ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
extra.update(kwargs)
if HIDDEN_HISTORY_META in msg.metadata:
extra[HIDDEN_HISTORY_META] = msg.metadata[HIDDEN_HISTORY_META]
@@ -759,6 +748,11 @@ class AgentLoop:
media=ctx.msg.media if ctx.kind is TurnKind.USER and ctx.msg.media else None,
session_summary=ctx.pending_summary,
runtime_context_blocks=ctx.runtime_context_blocks,
input_metadata=(
None
if turn_continuation.internal_continuation_inbound(ctx.msg.metadata)
else input_history_metadata(ctx.msg)
),
)
async def _request_context_for_turn(self, ctx: TurnContext) -> RequestContext:
@@ -1103,7 +1097,7 @@ class AgentLoop:
)
row: dict[str, Any] = {
"role": "user", "content": user_content,
"_meta": self._input_history_extra(pending_msg),
"_meta": input_history_metadata(pending_msg),
}
if HIDDEN_HISTORY_META in pending_msg.metadata:
row[HIDDEN_HISTORY_META] = pending_msg.metadata[HIDDEN_HISTORY_META]
@@ -1114,9 +1108,10 @@ class AgentLoop:
else {}
)
if pending_msg.is_user_input:
route = self.turn_delivery_factory.input_route(pending_msg, active_session_key or pending_msg.session_key)
scope = await self.runner.prepare_prompt(
self.workspace_scopes.for_turn,
channel=pending_msg.channel,
channel=route.channel,
message_metadata=_prompt_scope_metadata(metadata),
session_metadata=_prompt_scope_metadata(session.metadata) if session is not None else None,
)
@@ -1125,8 +1120,8 @@ class AgentLoop:
if scope != effective_scope:
return None
pending_request = RequestContext(
channel=pending_msg.channel,
chat_id=pending_msg.chat_id,
channel=route.channel,
chat_id=route.chat_id,
message_id=metadata.get("message_id"),
session_key=active_session_key,
session_generation=session.generation if session is not None else None,
@@ -1251,6 +1246,15 @@ class AgentLoop:
workspace=effective_scope.project_path,
include_memory=session.policy.persist if session is not None else True,
)
if initial_message is not None and turn_continuation.internal_continuation_inbound(initial_message.metadata):
build_transcript = transcript_builder
def transcript_builder(transcript: TranscriptInput) -> list[dict[str, Any]]:
messages = build_transcript(transcript)
if transcript.current_message is not None:
messages[-1][HIDDEN_HISTORY_META] = {"kind": "internal_continuation"}
return messages
if request_context is None:
request_ctx = dataclasses.replace(
request_ctx,
@@ -2505,16 +2509,8 @@ class AgentLoop:
if summary_checkpoint is not None and checkpoint_boundary == message_index:
session.commit_summary_checkpoint(summary_checkpoint.summary)
entry = dict(message)
entry = persisted_message(message)
followup_id = entry.pop(PENDING_FOLLOWUP_ID_KEY, None)
internal_meta = cast(object, entry.pop("_meta", None))
runtime_context_meta = (
cast(dict[str, Any], internal_meta).get(
RUNTIME_CONTEXT_MESSAGE_META
)
if isinstance(internal_meta, dict)
else None
)
role, content = entry.get("role"), entry.get("content")
if role == "assistant" and not content and not entry.get("tool_calls"):
continue # skip empty assistant messages — they poison session context
@@ -2553,13 +2549,6 @@ class AgentLoop:
if not filtered:
continue
entry["content"] = filtered
if isinstance(runtime_context_meta, dict):
entry[RUNTIME_CONTEXT_HISTORY_META] = runtime_context_meta
if isinstance(internal_meta, dict):
for key in ("timestamp", INBOUND_META_TURN_ID):
value = cast(dict[str, Any], internal_meta).get(key)
if isinstance(value, str) and value:
entry[key] = value
entry.setdefault("timestamp", datetime.now().isoformat())
session.messages.append(entry)
if role == "user" and isinstance(followup_id, str) and followup_id:
+47 -11
View File
@@ -26,7 +26,7 @@ from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.context import tool_log_content_allowed
from nanobot.agent.tools.execution import ToolCallResult, execute_tool_calls
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.events import NO_EVENTS, EventSink, ModelRequestEvent
from nanobot.events import NO_EVENTS, EventSink, ModelRequestEvent, ResponseInputsEvent
from nanobot.llm_usage.context import (
LLMUsageSource,
bind_llm_usage_source,
@@ -177,6 +177,31 @@ class AgentRunner:
"""Append injected messages without rewriting the raw transcript."""
messages.extend(injections)
@staticmethod
def _response_input_ids(messages: list[dict[str, Any]]) -> tuple[str, ...]:
"""Consecutive inputs share an answer; tool rounds keep their input owner."""
identifiers: list[str] = []
for message in reversed(messages):
if message.get("role") != "user":
if identifiers:
break
continue
marker = message.get(HIDDEN_HISTORY_META)
if isinstance(marker, dict) and cast(dict[str, Any], marker).get("kind") == "internal_continuation":
if identifiers:
break
continue
metadata: dict[str, Any] = message.get("_meta") or {}
input_id = metadata.get("input_id")
if not isinstance(input_id, str) or not input_id:
break
identifiers.append(input_id)
return tuple(reversed(identifiers))
@staticmethod
def _with_response_inputs(input_ids: tuple[str, ...], response: dict[str, Any]) -> dict[str, Any]:
return {**response, "_meta": {**response.get("_meta", {}), "response_input_ids": list(input_ids)}}
async def _try_drain_injections(
self,
spec: AgentRunSpec,
@@ -426,11 +451,15 @@ class AgentRunner:
if interrupted:
length_recovery_parts.clear()
else:
messages.append(build_length_recovery_message(segment_content))
messages.append({
**build_length_recovery_message(segment_content),
HIDDEN_HISTORY_META: {"kind": "internal_continuation"},
})
if hook.wants_streaming():
segment_context.stream_continues_current_message = not interrupted
await hook.on_stream_end(segment_context, resuming=True)
response_input_ids: tuple[str, ...] = ()
iteration = -1
followup_requested = False
while (
@@ -454,6 +483,9 @@ class AgentRunner:
if drained_before_request:
had_injections = True
await end_length_segment(interrupted=drained_before_request)
response_input_ids = self._response_input_ids(messages)
if spec.events.accepts(ResponseInputsEvent):
await spec.events.emit(ResponseInputsEvent(response_input_ids))
context = AgentHookContext(
iteration=iteration,
messages=messages,
@@ -513,6 +545,7 @@ class AgentRunner:
assistant_message,
response,
)
assistant_message = self._with_response_inputs(response_input_ids, assistant_message)
messages.append(assistant_message)
await self._emit_checkpoint(
spec,
@@ -669,14 +702,14 @@ class AgentRunner:
len(length_recovery_parts),
_MAX_LENGTH_RECOVERIES,
)
messages.append(conversation_state.project_response_message(
messages.append(self._with_response_inputs(response_input_ids, conversation_state.project_response_message(
build_assistant_message(
clean,
reasoning_content=response.reasoning_content,
thinking_blocks=response.thinking_blocks,
),
response,
))
)))
# The next input snapshot decides whether to continue this
# answer or close its stream before answering a new question.
pending_length_segment = (context, clean or "")
@@ -711,6 +744,7 @@ class AgentRunner:
assistant_message,
response,
)
assistant_message = self._with_response_inputs(response_input_ids, assistant_message)
messages.append(assistant_message)
await self._emit_checkpoint(
spec,
@@ -738,10 +772,10 @@ class AgentRunner:
if not is_blank_text(interrupted_content):
# This is unsynchronized output, not a completed response or
# provider-owned projection. Keep it in the next native delta.
messages.append({
messages.append(self._with_response_inputs(response_input_ids, {
**build_assistant_message(interrupted_content),
"_interrupted": True,
})
}))
# Check for mid-turn injections BEFORE signaling stream end.
# If injections are found we keep the stream alive (resuming=True)
@@ -808,7 +842,7 @@ class AgentRunner:
final_content = EMPTY_FINAL_RESPONSE_MESSAGE
stop_reason = "empty_final_response"
error = final_content
self._append_final_message(messages, final_content)
self._append_final_message(messages, final_content, response_input_ids)
context.final_content = final_content
context.error = error
context.stop_reason = stop_reason
@@ -868,7 +902,7 @@ class AgentRunner:
pending_stream_content = terminal_tail
else:
final_content = terminal_content
self._append_final_message(messages, terminal_content)
self._append_final_message(messages, terminal_content, response_input_ids)
return AgentRunResult(
final_content=final_content,
@@ -1496,7 +1530,9 @@ class AgentRunner:
})
@staticmethod
def _append_final_message(messages: list[dict[str, Any]], content: str | None) -> None:
def _append_final_message(
messages: list[dict[str, Any]], content: str | None, input_ids: tuple[str, ...],
) -> None:
if not content:
return
if (
@@ -1506,9 +1542,9 @@ class AgentRunner:
):
if messages[-1].get("content") == content:
return
messages[-1] = build_assistant_message(content)
messages[-1] = AgentRunner._with_response_inputs(input_ids, build_assistant_message(content))
return
messages.append(build_assistant_message(content))
messages.append(AgentRunner._with_response_inputs(input_ids, build_assistant_message(content)))
@staticmethod
def _append_model_error_placeholder(messages: list[dict[str, Any]]) -> None:
+19 -19
View File
@@ -40,6 +40,22 @@ MIN_REPLY_TIMEOUT_SECONDS = 5
MAX_REPLY_TIMEOUT_SECONDS = 60
async def session_message_runtime_context(
request: RequestContext,
) -> RuntimeContextBlock | None:
envelope = session_message_envelope(request.metadata)
if envelope is None:
return None
source = session_handle_for_name(
envelope["source_session_key"],
envelope["source_handle"],
)
content = f"Message from @{source.name}."
if envelope["expect_reply"]:
content += " Reply with send_session_message."
return RuntimeContextBlock(source="session_message", content=content)
class SessionMessageError(ValueError):
pass
@@ -113,25 +129,6 @@ class SendSessionMessageTool(Tool):
def description(self) -> str:
return "Send a message to a persisted session by @handle."
def runtime_context_provider(self):
return self._provide_runtime_context
async def _provide_runtime_context(
self,
request: RequestContext,
) -> RuntimeContextBlock | None:
envelope = session_message_envelope(request.metadata)
if envelope is None:
return None
source = session_handle_for_name(
envelope["source_session_key"],
envelope["source_handle"],
)
content = f"Message from @{source.name}."
if envelope["expect_reply"]:
content += " Reply with send_session_message."
return RuntimeContextBlock(source="session_message", content=content)
async def execute(
self,
to: str,
@@ -171,6 +168,8 @@ class SendSessionMessageTool(Tool):
expect_reply: bool,
reply_timeout_seconds: int | None = None,
) -> str:
if content.lstrip().startswith("/"):
raise SessionMessageError("slash commands cannot be sent between sessions")
timeout_seconds = self._validate_reply_timeout(expect_reply, reply_timeout_seconds)
try:
target_name = normalize_session_handle(target_handle)
@@ -215,6 +214,7 @@ class SendSessionMessageTool(Tool):
content=content,
metadata={SESSION_MESSAGE_METADATA_KEY: envelope},
session_key_override=target.session_key,
require_existing_session=True,
input_role="user",
))
sent_at.append(now)
+21 -3
View File
@@ -24,6 +24,7 @@ from nanobot.events import (
AgentEvent,
ContextCompactionEvent,
EventSink,
ResponseInputsEvent,
ResponseSource,
ResponseSourceEvent,
)
@@ -34,6 +35,7 @@ from nanobot.session.keys import (
is_internal_session,
last_channel_from_metadata,
)
from nanobot.session.message_metadata import input_history_metadata
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import strip_think
@@ -110,7 +112,7 @@ class TurnDeliveryFactory:
*,
enable_stream: bool = False,
) -> TurnDelivery:
route = self._default_route(msg, session_key)
route = self.input_route(msg, session_key)
if self.route_policy is not None:
route = self.route_policy(msg, session_key, route)
if not isinstance(cast(object, route), TurnRoute):
@@ -178,7 +180,8 @@ class TurnDeliveryFactory:
return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata), session_key)
@staticmethod
def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute:
def input_route(msg: InboundMessage, session_key: str) -> TurnRoute:
"""Resolve the input's destination without acquiring a turn lifecycle owner."""
if msg.channel != "system":
return TurnRoute(
channel=msg.channel,
@@ -219,6 +222,7 @@ class TurnDelivery:
_stop_reason: str | None = field(init=False, default=None)
_failure_error_kind: str | None = field(init=False, default=None)
_retry_status: RetryStatusEvent | None = field(init=False, default=None)
_response_input_ids: tuple[str, ...] | None = field(init=False, default=None)
_response_source: ResponseSource | None = field(init=False, default=None)
_response_source_seen: bool = field(init=False, default=False)
_response_content: str | None = field(init=False, default=None)
@@ -227,8 +231,13 @@ class TurnDelivery:
def __post_init__(self) -> None:
self.run_id = uuid4().hex
input_id = input_history_metadata(self.input_message)["input_id"]
self._response_input_ids = (input_id,) if input_id else None
self._routed_events = _bind_events(self.bus, self.route, self.session_key)
self.events = EventSink(self._publish_event, self._routed_events.accepts)
self.events = EventSink(
self._publish_event,
lambda event_type: event_type is ResponseInputsEvent or self._routed_events.accepts(event_type),
)
self.delivery_message = dataclasses.replace(
self.input_message,
channel=self.route.channel,
@@ -376,6 +385,10 @@ class TurnDelivery:
**response.metadata,
"response_sources": [dataclasses.asdict(self._response_source)],
})
if self._response_input_ids is not None and (response.channel, response.chat_id) == (self.route.channel, self.route.chat_id):
response = dataclasses.replace(response, metadata={
**response.metadata, "response_input_ids": list(self._response_input_ids),
})
if response.channel != "websocket" or stop_reason != "error":
delivery = DeliveryRequest.from_context(
self.input_message.metadata, self.session_key,
@@ -460,6 +473,9 @@ class TurnDelivery:
return f"{self._stream_base_id}:{self._stream_segment}"
async def _publish_event(self, event: AgentEvent) -> None:
if isinstance(event, ResponseInputsEvent):
self._response_input_ids = event.input_ids
return
if isinstance(event, ResponseSourceEvent):
self._response_source_seen = True
self._response_source = event.source
@@ -484,6 +500,8 @@ class TurnDelivery:
self._stream_sources.append(source)
if self._routed_events.accepts(type(event)):
metadata = deepcopy(self.route.metadata)
if self._response_input_ids is not None:
metadata["response_input_ids"] = list(self._response_input_ids)
if self._response_source_seen and self._routed_events.accepts(ResponseSourceEvent):
metadata["response_sources"] = (
[] if self._stream_source_unknown else
+1
View File
@@ -92,6 +92,7 @@ class UserInputEvent(AgentEvent):
content: str
created_at_ms: int
input_id: str
provenance: dict[str, Any]
@@ -2498,6 +2498,7 @@ async def test_send_projects_external_user_input_to_existing_wire_event() -> Non
event=UserInputEvent(
content="hello from another session",
created_at_ms=1234,
input_id="session-message:external-input",
provenance={"name": "luma"},
),
)
@@ -2510,6 +2511,7 @@ async def test_send_projects_external_user_input_to_existing_wire_event() -> Non
"text": "hello from another session",
"created_at_ms": 1234,
"starts_turn": False,
"input_id": "session-message:external-input",
"provenance": {"name": "luma"},
}
@@ -5424,6 +5426,7 @@ async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
"text": "hello from A",
"starts_turn": True,
"turn_id": "turn-a",
"input_id": "user:turn-a",
"active_turn_id": "turn-a",
"started_at": pytest.approx(wth.websocket_turn_wall_started_at("shared-chat")),
}
@@ -5433,6 +5436,7 @@ async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
"text": "one more detail",
"starts_turn": False,
"turn_id": "steer-a",
"input_id": "user:steer-a",
"active_turn_id": "turn-a",
"started_at": pytest.approx(wth.websocket_turn_wall_started_at("shared-chat")),
}
@@ -364,6 +364,7 @@ async def test_same_session_projects_one_turn_to_both_clients(bus: MagicMock) ->
"text": "hello from terminal A",
"starts_turn": True,
"turn_id": "turn-a",
"input_id": "user:turn-a",
"active_turn_id": "turn-a",
"started_at": projected.raw["started_at"],
}
+7
View File
@@ -27,6 +27,13 @@ class ModelRequestEvent(AgentEvent):
request_usage: LLMUsage | None = None
@dataclass(frozen=True)
class ResponseInputsEvent(AgentEvent):
"""Identify the inputs being answered by the next model request."""
input_ids: tuple[str, ...]
@dataclass(frozen=True)
class ResponseSource:
"""Display-safe identity captured at the actual provider invocation."""
+7
View File
@@ -167,6 +167,13 @@ class HistoryReader:
(self.key, ordinal),
).fetchone()[0])
def has_input(self, input_id: str) -> bool:
return self._db.execute(
"""SELECT 1 FROM history_entries WHERE session_key=? AND kind='input'
AND json_extract(record, '$.content.input_id')=?""",
(self.key, input_id),
).fetchone() is not None
def navigation(self) -> Iterator[tuple[int, int, HistoryFact]]:
"""Read input/answer records only, never file diffs or tool result bodies."""
kinds = (HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT,
+6
View File
@@ -303,6 +303,12 @@ class Session:
if not any(key in message for key in ("tool_calls", "reasoning_content", "thinking_blocks")):
continue
entry: dict[str, Any] = {"role": message["role"], "content": content}
if include_runtime_context and "input_id" in message and not is_hidden_history_message(message):
entry["_meta"] = {"input_id": message["input_id"]}
marker = message.get(HIDDEN_HISTORY_META)
if include_runtime_context and isinstance(marker, dict) and cast(dict[str, Any], marker).get("kind") == "internal_continuation":
# Attribution must distinguish persisted continuations from no-ID automation inputs.
entry[HIDDEN_HISTORY_META] = {"kind": "internal_continuation"}
for key in ("tool_calls", "tool_call_id", "name", "reasoning_content", "thinking_blocks"):
if key in message:
entry[key] = message[key]
+49
View File
@@ -0,0 +1,49 @@
"""Admission identity and metadata shared by normal commits and checkpoint recovery."""
from __future__ import annotations
from typing import Any, cast
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_TURN_ID, InboundMessage
from nanobot.runtime_context import RUNTIME_CONTEXT_HISTORY_META, RUNTIME_CONTEXT_MESSAGE_META
from nanobot.session.session_messages import session_message_input, session_message_public_metadata
def input_history_metadata(message: InboundMessage) -> dict[str, Any]:
# None marks an input without a public ID; synthetic continuations omit the key.
extra: dict[str, Any] = {"timestamp": message.timestamp.isoformat(), "input_id": None}
envelope = session_message_input(message)
if envelope is not None:
extra["session_message"] = session_message_public_metadata(envelope)
extra["input_id"] = f"session-message:{envelope['message_id']}"
turn_id = message.metadata.get(INBOUND_META_TURN_ID)
if isinstance(turn_id, str) and turn_id:
extra[INBOUND_META_TURN_ID] = turn_id
if message.is_user_input and envelope is None:
extra["input_id"] = f"user:{turn_id}"
local_media = message.metadata.get(INBOUND_META_LOCAL_MEDIA)
if isinstance(local_media, list) and local_media:
extra[INBOUND_META_LOCAL_MEDIA] = [path for path in cast(list[object], local_media) if isinstance(path, str)]
return extra
def persisted_message(message: dict[str, Any]) -> dict[str, Any]:
"""Move internal transcript annotations to their durable history fields."""
entry = dict(message)
metadata = entry.pop("_meta", None)
if not isinstance(metadata, dict):
return entry
metadata = cast(dict[str, Any], metadata)
if entry.get("role") == "user":
if "input_id" in metadata:
entry["input_id"] = metadata["input_id"]
for key in ("timestamp", INBOUND_META_TURN_ID):
if isinstance(value := metadata.get(key), str) and value:
entry[key] = value
if isinstance(source := metadata.get("session_message"), dict):
entry["session_message"] = source
if isinstance(context := metadata.get(RUNTIME_CONTEXT_MESSAGE_META), dict):
entry[RUNTIME_CONTEXT_HISTORY_META] = context
elif entry.get("role") == "assistant" and "response_input_ids" in metadata:
entry["response_input_ids"] = metadata["response_input_ids"]
return entry
+12 -5
View File
@@ -11,6 +11,8 @@ from loguru import logger
from nanobot.bus.events import InboundMessage
from nanobot.session.manager import Session
from nanobot.session.message_metadata import persisted_message
from nanobot.session.session_messages import session_message_envelope, session_message_input
RUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"
PENDING_USER_TURN_KEY = "pending_user_turn"
@@ -66,7 +68,7 @@ class RecoveryAdmission(Protocol):
def record_pending_followup(session: Session, message: InboundMessage) -> str | None:
"""Durably journal a WebUI follow-up before injecting it into a live turn."""
if message.channel != "websocket":
if message.channel != "websocket" and session_message_input(message) is None:
return None
try:
metadata_value: object = json.loads(json.dumps(message.metadata))
@@ -115,7 +117,7 @@ def pending_followups(session: Session) -> list[InboundMessage]:
sender_id = cast(object, record.get("sender_id"))
chat_id = cast(object, record.get("chat_id"))
content = cast(object, record.get("content"))
metadata = cast(object, record.get("metadata"))
metadata_value = cast(object, record.get("metadata"))
if (
not isinstance(followup_id, str)
or not followup_id
@@ -125,8 +127,9 @@ def pending_followups(session: Session) -> list[InboundMessage]:
or not chat_id
):
continue
if not isinstance(content, str) or not isinstance(metadata, dict):
if not isinstance(content, str) or not isinstance(metadata_value, dict):
continue
metadata = cast(dict[str, Any], metadata_value)
media_value = cast(object, record.get("media"))
media = (
[item for item in cast(list[object], media_value) if isinstance(item, str)]
@@ -136,15 +139,18 @@ def pending_followups(session: Session) -> list[InboundMessage]:
timestamp = record.get("timestamp")
# Older journals did not retain admission time; retain their existing recovery policy.
received_at = datetime.fromisoformat(timestamp) if isinstance(timestamp, str) else datetime.now()
envelope = session_message_envelope(metadata)
is_session_input = envelope is not None and envelope["target_session_key"] == session.key
messages.append(
InboundMessage(
channel="websocket",
channel="system" if is_session_input else "websocket",
input_role="user" if is_session_input else None,
sender_id=sender_id,
chat_id=chat_id,
content=content,
timestamp=received_at,
media=media,
metadata={**cast(dict[str, Any], metadata), PENDING_FOLLOWUP_ID_KEY: followup_id},
metadata={**metadata, PENDING_FOLLOWUP_ID_KEY: followup_id},
session_key_override=session.key,
require_existing_session=True,
)
@@ -378,6 +384,7 @@ def restore_runtime_checkpoint(session: Session) -> bool:
}
)
restored = [persisted_message(message) for message in restored]
overlap = 0
# Cumulative checkpoints contain only the delta after accepted input. The
# owner commits it and clears the checkpoint in one transaction, so none of
+21 -2
View File
@@ -2,9 +2,12 @@ from __future__ import annotations
import re
from collections.abc import Mapping
from typing import Any, TypedDict, cast
from typing import TYPE_CHECKING, Any, TypedDict, cast
from nanobot.session.session_handles import normalize_session_handle
from nanobot.session.session_handles import normalize_session_handle, session_handle_for_name
if TYPE_CHECKING:
from nanobot.bus.events import InboundMessage
SESSION_MESSAGE_METADATA_KEY = "_session_message"
@@ -67,6 +70,22 @@ def session_message_envelope(
}
def session_message_input(message: InboundMessage) -> SessionMessageEnvelope | None:
envelope = session_message_envelope(message.metadata)
if (
message.channel == "system" and message.is_user_input and envelope is not None
and envelope["target_session_key"] == message.session_key
):
return envelope
return None
def session_message_public_metadata(envelope: SessionMessageEnvelope) -> dict[str, Any]:
"""Return stable provenance without private routing identifiers."""
source = session_handle_for_name(envelope["source_session_key"], envelope["source_handle"])
return {"message_id": envelope["message_id"], "session": source.public_payload()}
def _session_key(value: object) -> str | None:
if not isinstance(value, str):
return None
+16 -2
View File
@@ -117,9 +117,15 @@ def _create_schema_v4(db: sqlite3.Connection) -> None:
db.execute("ALTER TABLE session_archives_v4 RENAME TO session_archives")
def _create_schema_v5(db: sqlite3.Connection) -> None:
db.execute("""CREATE UNIQUE INDEX history_input_identity ON history_entries (
session_key, json_extract(record, '$.content.input_id')
) WHERE kind='input'""")
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (
_create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4,
_create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4, _create_schema_v5,
)
@@ -589,7 +595,15 @@ class SqliteSessionStore:
).fetchone()
ordinal, position = (int(tail[0]), int(tail[1])) if tail is not None else (0, 0)
completed = tail is not None and bool(tail[2])
appended = False
for kind, created_at_ms, record, preview in encoded:
if kind is HistoryKind.INPUT and db.execute(
"""SELECT 1 FROM history_entries WHERE session_key=? AND kind='input'
AND json_extract(record, '$.content.input_id')=json_extract(?, '$.content.input_id')""",
(key, record),
).fetchone() is not None:
continue
appended = True
if completed:
ordinal, position = ordinal + 1, 0
if position == 0:
@@ -612,7 +626,7 @@ class SqliteSessionStore:
db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
(created_at_ms, key))
if encoded:
if appended:
db.execute("UPDATE history_heads SET revision=revision+1 WHERE session_key=?", (key,))
return errors
+4 -3
View File
@@ -769,10 +769,11 @@ class SessionState:
)
async def queue_followup(self, key: str, message: InboundMessage) -> str | None:
if message.channel != "websocket":
return None
from nanobot.session.recovery import record_pending_followup
from nanobot.session.session_messages import session_message_input
if message.channel != "websocket" and session_message_input(message) is None:
return None
payload = deepcopy(message)
+14 -30
View File
@@ -42,10 +42,10 @@ from nanobot.runtime_context import public_history_message
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import session_handle_for_name
from nanobot.session.session_messages import (
SessionMessageEnvelope,
SESSION_MESSAGE_METADATA_KEY,
session_message_envelope,
session_message_public_metadata,
)
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.utils.helpers import strip_think, truncate_text
@@ -58,7 +58,7 @@ from nanobot.webui.metadata import (
from nanobot.webui.recovery import RecoveryCoordinator
from nanobot.webui.session_identity import is_webui_session_key, webui_session_key
from nanobot.webui.star_prompt import update_star_prompt
from nanobot.webui.transcript import append_session_message_input
from nanobot.webui.transcript import WebUITranscriptRecorder
WEBUI_SESSION_METADATA_KEY = "webui"
WEBUI_TITLE_METADATA_KEY = "title"
@@ -85,19 +85,6 @@ class _WebsocketTurn:
_WEBSOCKET_ACTIVE_TURNS: dict[str, dict[str, _WebsocketTurn]] = {}
def _session_message_public_metadata(
envelope: SessionMessageEnvelope,
) -> dict[str, Any]:
source = session_handle_for_name(
envelope["source_session_key"],
envelope["source_handle"],
)
return {
"message_id": envelope["message_id"],
"session": source.public_payload(),
}
def _validated_llm_runtime(value: object) -> LLMRuntime | None:
return value if isinstance(value, LLMRuntime) else None
@@ -672,20 +659,16 @@ class WebuiTurnCoordinator:
)
if metadata is None or metadata.get(WEBUI_SESSION_METADATA_KEY) is not True:
return
public_metadata = _session_message_public_metadata(envelope)
try:
await append_session_message_input(
session_key,
sessions=self.sessions,
content=event.content,
created_at_ms=envelope["created_at_ms"],
session_message=public_metadata,
)
except (OSError, TypeError, ValueError, SessionConflictError):
logger.opt(exception=True).warning(
"Failed to persist session input {}",
envelope["message_id"],
)
public_metadata = session_message_public_metadata(envelope)
revision = await self.sessions.state.project_history(session_key, lambda history: history.revision)
if revision is None:
return
generation = event.context.session_generation or revision[0]
metadata = {SESSION_MESSAGE_METADATA_KEY: envelope, HISTORY_GENERATION_METADATA_KEY: generation}
if not await WebUITranscriptRecorder(self.sessions).append_user_message(
session_key.split(":", 1)[1], event.content, metadata=metadata,
):
logger.warning("Failed to persist session input {}", envelope["message_id"])
return
await self.bus.publish_outbound(outbound_message_for_event(
channel="websocket",
@@ -693,6 +676,7 @@ class WebuiTurnCoordinator:
event=UserInputEvent(
content=event.content,
created_at_ms=envelope["created_at_ms"],
input_id=f"session-message:{envelope['message_id']}",
provenance={"session_message": public_metadata},
),
))
+1 -1
View File
@@ -37,7 +37,7 @@ _MESSAGE_KINDS = {
}
_CONTENT_FIELDS = frozenset({
"text", "media_paths", "media", "media_urls", "reply_to", "agent_ui", "cli_apps", "mcp_presets", "session_mentions",
"session_message", INBOUND_META_LOCAL_MEDIA, "tool_events", "edits", "source", "response_sources", "resuming",
"session_message", "input_id", "response_input_ids", 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", "render_as",
+1
View File
@@ -246,6 +246,7 @@ class WebUICommandRouter:
}
if turn_id is not None:
body["turn_id"] = turn_id
body["input_id"] = f"user:{turn_id}"
if media:
body["media_urls"] = media
if cli_apps:
+1
View File
@@ -295,6 +295,7 @@ class WebUIOutboundDelivery:
body: UserInputWirePayload = {
"event": "user_message", "chat_id": msg.chat_id, "text": event.content,
"created_at_ms": event.created_at_ms, "starts_turn": False,
"input_id": event.input_id,
}
if event.provenance:
body["provenance"] = event.provenance
+1
View File
@@ -172,6 +172,7 @@ class UserInputWirePayload(_ChatWirePayload):
created_at_ms: int
starts_turn: bool
provenance: NotRequired[dict[str, Any]]
input_id: NotRequired[str]
class PairingChangedWirePayload(TypedDict):
+7 -2
View File
@@ -140,7 +140,12 @@ class RecoveryCoordinator:
and state["status"] == "resuming"
and state["recovery_id"] == recovery_id
)
if message.channel != "websocket":
from nanobot.session.session_messages import session_message_input
chat_id = message.chat_id if message.channel == "websocket" else None
if session_message_input(message) is not None:
chat_id = webui_chat_id(message.session_key)
if chat_id is None:
return True
session = await self.sessions.state.get(message.session_key)
state = recovery_state_from_metadata(session.metadata)
@@ -164,7 +169,7 @@ class RecoveryCoordinator:
reason="superseded",
)
await self.sessions.state.restore_interruption(session)
await self._publish(message.chat_id, recovered)
await self._publish(chat_id, recovered)
return True
async def turn_completed(
+155 -53
View File
@@ -36,6 +36,10 @@ from nanobot.session.history_graph import (
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_messages import (
session_message_envelope,
session_message_public_metadata,
)
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.state import SessionOperationQueueFullError
from nanobot.webui.history import (
@@ -46,7 +50,7 @@ from nanobot.webui.history import (
)
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
from nanobot.webui.outbound_wire import project_tool_events
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
from nanobot.webui.session_identity import webui_session_key
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
WEBUI_FORK_MARKER_EVENT = "fork_marker"
@@ -487,21 +491,6 @@ def append_transcript_object(
sessions.append_history(session_key, [fact_from_record(_record_for_append(obj))])
async def append_session_message_input(
session_key: str, *, sessions: SessionManager, content: str, created_at_ms: int,
session_message: Mapping[str, Any],
) -> None:
chat_id = _chat_id_from_session_key(session_key)
if chat_id is None:
return
event = build_user_transcript_event(chat_id, content)
if event is None:
return
event.update(created_at_ms=created_at_ms, session_message=dict(session_message))
await sessions.state.append_history(session_key, [fact_from_record(event)],
expected_generation=None)
def normalize_webui_turn_id(value: Any) -> str:
if isinstance(value, str):
candidate = value.strip()
@@ -549,6 +538,10 @@ class WebUITranscriptRecorder:
event["source"] = source
if include_source and metadata is not None and "response_sources" in metadata:
event["response_sources"] = _response_sources(metadata["response_sources"])
if event.get("event") == "user" and (turn_id := (metadata or {}).get(WEBUI_TURN_METADATA_KEY)):
event["input_id"] = f"user:{turn_id}"
if include_source and metadata is not None and "response_input_ids" in metadata:
event["response_input_ids"] = list(metadata["response_input_ids"])
self._annotate_turn(chat_id, event, metadata, phase)
async def prepare_and_append(
@@ -578,7 +571,10 @@ class WebUITranscriptRecorder:
mcp_presets: list[dict[str, Any]] | None = None,
session_mentions: Sequence[Mapping[str, Any]] | None = None,
) -> bool:
if text.strip() == "/stop" and not media_paths:
envelope = session_message_envelope(metadata)
if envelope is not None and envelope["target_session_key"] != webui_session_key(chat_id):
envelope = None
if text.strip() == "/stop" and not media_paths and envelope is None:
return False
event = build_user_transcript_event(
chat_id,
@@ -591,6 +587,12 @@ class WebUITranscriptRecorder:
)
if event is None:
return False
if envelope is not None:
event.update(
created_at_ms=envelope["created_at_ms"],
session_message=session_message_public_metadata(envelope),
input_id=f"session-message:{envelope['message_id']}",
)
return await self.prepare_and_append(chat_id, event, metadata=metadata, phase="user")
async def append(
@@ -648,13 +650,6 @@ class WebUITranscriptRecorder:
self._turn_sequences.pop((chat_id, turn_id), None)
def _chat_id_from_session_key(session_key: str) -> str | None:
chat_id = webui_chat_id(session_key)
if chat_id is None:
return None
return chat_id.strip() or None
def normalize_session_mentions_metadata(raw: object) -> list[dict[str, str]]:
"""Validate session-reference metadata crossing a persistence seam."""
if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes, bytearray)):
@@ -832,6 +827,8 @@ def _session_user_event(
provenance = normalize_session_message_ui_metadata(message.get("session_message"))
if provenance:
event["session_message"] = provenance
if isinstance(message_id := message.get("input_id"), str) and message_id:
event["input_id"] = message_id
input_id = message.get(INBOUND_META_TURN_ID)
if isinstance(input_id, str) and _WEBUI_TURN_ID_RE.fullmatch(input_id):
event["turn_id"] = input_id
@@ -868,6 +865,8 @@ def _session_assistant_event(
}
if media_paths:
event["media"] = media_paths
if "response_input_ids" in message:
event["response_input_ids"] = message["response_input_ids"]
latency_ms = message.get("latency_ms")
if isinstance(latency_ms, int | float) and latency_ms >= 0:
event["latency_ms"] = int(latency_ms)
@@ -890,7 +889,7 @@ def _session_backfill_turns(
assistant_records: list[dict[str, Any]] = []
def flush() -> None:
if current_user is None or not assistant_records:
if current_user is None:
return
signature = tuple(
text
@@ -1120,9 +1119,16 @@ def _recover_incomplete_turns(
return recovered
def _needs_user_event_backfill(lines: list[dict[str, Any]]) -> bool:
return any(
not any(record.get("event") == "user" for record in turn)
def _needs_user_event_backfill(lines: list[dict[str, Any]], history: HistoryReader) -> bool:
referenced_inputs = {
input_id
for record in lines
if isinstance(references := record.get("response_input_ids"), list)
for input_id in cast(list[object], references)
if isinstance(input_id, str) and input_id
}
return any(not history.has_input(input_id) for input_id in referenced_inputs) or any(
not any(record.get("event") == "user" or isinstance(record.get("response_input_ids"), list) for record in turn)
and _transcript_turn_signature(turn)
for turn in _split_transcript_turns(lines)
)
@@ -1132,8 +1138,21 @@ def _with_backfilled_user(
records: list[dict[str, Any]],
user_event: dict[str, Any],
) -> list[dict[str, Any]]:
input_id = user_event.get("input_id")
legacy = not any("response_input_ids" in record for record in records)
for index, rec in enumerate(records):
if rec.get("event") in _TURN_DISPLAY_EVENTS:
if (
input_id and input_id in rec.get("response_input_ids", [])
or (not input_id or legacy) and rec.get("event") in _TURN_DISPLAY_EVENTS
):
if input_id:
references = rec.get("response_input_ids")
if isinstance(references, list):
references = cast(list[object], references)
following = {value for value in references[references.index(input_id) + 1:]
if isinstance(value, str)}
index = next((i for i, prior in enumerate(records[:index])
if prior.get("event") == "user" and prior.get("input_id") in following), index)
return [*records[:index], dict(user_event), *records[index:]]
return records
@@ -1358,6 +1377,8 @@ def build_webui_trace_detail_response(
def _client_projection_event_id(record: Mapping[str, Any]) -> str:
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY)
if record.get("event") == "user" and isinstance(input_id := record.get("input_id"), str) and input_id:
identity = f"input:{record.get('chat_id')}:{input_id}"
if not isinstance(identity, str) or not identity:
identity = _stable_record_digest(dict(record))
digest = hashlib.sha256(f"event\0{identity}".encode("utf-8")).hexdigest()[:20]
@@ -1389,6 +1410,8 @@ def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]:
created_at_ms = _valid_created_at_ms(record.get("created_at_ms"))
if created_at_ms is not None:
fields["created_at_ms"] = created_at_ms
if isinstance(input_id := record.get("input_id"), str):
fields["input_id"] = input_id
receipts = record.get(_WEBUI_PROJECTION_RECEIPTS_KEY)
if receipts:
fields["projection_receipts"] = receipts
@@ -1419,8 +1442,11 @@ def _client_projection_event(
) -> dict[str, Any] | None:
event = record.get("event")
common = _client_projection_common_fields(record)
if event in {"delta", "stream_end", "message"} and "response_sources" in record:
common["response_sources"] = _response_sources(record["response_sources"])
if event in {"delta", "stream_end", "message"}:
if "response_sources" in record:
common["response_sources"] = _response_sources(record["response_sources"])
if "response_input_ids" in record:
common["response_input_ids"] = record["response_input_ids"]
if event == "user":
projected: dict[str, Any] = {
"event": "user_message",
@@ -1839,7 +1865,9 @@ def build_webui_thread_response(
session_turns = _session_backfill_turns(session_key, session_messages or [])
return session_turns
if _needs_user_event_backfill(lines):
# Truncation can discard every reference that proves an input is missing.
# Complete pages keep the ordinary missing-input fast-path decision.
if replay_stats.truncated_oversized_turn or _needs_user_event_backfill(lines, history):
view, _ = _prompt_view_snapshot(
session_key, history=history, session_turns_loader=load_session_turns,
session_version_loader=session_version_loader,
@@ -1849,8 +1877,14 @@ def build_webui_thread_response(
for turn in selected_turns:
# Page selection assigns this absolute identity before any recovery.
ordinal = int(turn[0][_WEBUI_REPLAY_IDENTITY_KEY].split(":")[1])
user = view.backfilled_users.get(ordinal)
recovered_lines.extend(_with_backfilled_user(turn, user) if user is not None else turn)
for anchor, user in view.backfill_plan.get(ordinal, []):
# Positions are stable even when the record at the anchor was
# removed by oversized-turn selection or delta compaction.
index = next((i for i, record in enumerate(turn)
if (identity := record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")).startswith(f"turn:{ordinal}:record:")
and int(identity.rsplit(":", 1)[1]) >= anchor), len(turn))
turn.insert(index, dict(user))
recovered_lines.extend(turn)
lines = recovered_lines
if _needs_incomplete_turn_recovery(lines):
lines = _recover_incomplete_turns(lines, load_session_turns())
@@ -1920,6 +1954,7 @@ def build_webui_thread_response(
class PromptSummary(TypedDict):
inputId: str
id: str
preview: str
answerPreview: str
@@ -1933,16 +1968,20 @@ class _BackfillCandidate(NamedTuple):
signature: str
answer_preview: str
has_user: bool
input_ids: tuple[str, ...] | None
class _ChunkPromptView(NamedTuple):
prompts: tuple[PromptSummary, ...]
candidates: tuple[_BackfillCandidate, ...]
input_ids: frozenset[str]
answers: dict[str, str]
turns: dict[int, list[dict[str, Any]]]
class _PromptView(NamedTuple):
prompts: tuple[PromptSummary, ...]
backfilled_users: dict[int, dict[str, Any]]
backfill_plan: dict[int, list[tuple[int, dict[str, Any]]]]
needs_canonical: bool
@@ -1960,6 +1999,7 @@ def prompt_index_revision(session_key: str, session_version: tuple[str, int] | N
def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> PromptSummary:
return {
"id": _client_projection_event_id(record),
"inputId": str(record.get("input_id") or ""),
"preview": str(record.get("text") or "").strip()[:320],
"answerPreview": answer,
"createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0,
@@ -1971,29 +2011,41 @@ def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> Prompt
def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
result: list[PromptSummary] = []
candidates: list[_BackfillCandidate] = []
input_ids: set[str] = set()
answers: dict[str, str] = {}
response_inputs: dict[int, list[str]] = {}
turns: dict[int, list[dict[str, Any]]] = {}
for ordinal, position, fact in history.navigation():
record = record_from_fact(fact, history.key)
record[_WEBUI_REPLAY_IDENTITY_KEY] = f"turn:{ordinal}:record:{position}"
turns.setdefault(ordinal, []).append(record)
if record.get("event") in {"message", "stream_end"} and not record.get("kind"):
if isinstance(references := record.get("response_input_ids"), list):
identifiers = [value for value in cast(list[object], references) if isinstance(value, str) and value]
response_inputs.setdefault(ordinal, []).extend(identifiers)
answer = str(record.get("text") or "").strip()[:240]
if answer:
for input_id in identifiers:
answers.setdefault(input_id, answer)
for ordinal, records in turns.items():
has_user = any(record.get("event") == "user" for record in records)
signature = _transcript_turn_signature(records)
candidates.append(_BackfillCandidate(ordinal, _assistant_signature_identity(signature),
signature[0][:240] if signature else "", has_user))
candidates.append(_BackfillCandidate(
ordinal, _assistant_signature_identity(signature),
signature[0][:240] if signature else "", has_user,
tuple(dict.fromkeys(response_inputs[ordinal])) if ordinal in response_inputs else None,
))
seen_turns: set[str] = set()
seen_messages: set[str] = set()
for index, record in enumerate(records):
if record.get("event") != "user":
continue
turn_id = str(record.get("turn_id") or "")
provenance = normalize_session_message_ui_metadata(record.get("session_message"))
if provenance:
message_id = str(provenance["message_id"])
if message_id in seen_messages:
continue
seen_messages.add(message_id)
elif turn_id and turn_id in seen_turns:
input_id = record.get("input_id")
if isinstance(input_id, str) and input_id:
input_ids.add(input_id)
result.append(_prompt_summary(record, ordinal, answers.get(input_id, "")))
continue
if turn_id and turn_id in seen_turns:
continue
if turn_id:
seen_turns.add(turn_id)
@@ -2006,7 +2058,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
if answer:
break
result.append(_prompt_summary(record, ordinal, answer))
return _ChunkPromptView(tuple(result), tuple(candidates))
return _ChunkPromptView(tuple(result), tuple(candidates), frozenset(input_ids), answers, turns)
def _build_prompt_view(
@@ -2018,7 +2070,11 @@ def _build_prompt_view(
raw_prompts = list(chunk.prompts)
candidates = list(chunk.candidates)
session_turns = None
needs_canonical = any(not candidate.has_user and candidate.signature for candidate in candidates)
needs_canonical = any(
not set(candidate.input_ids).issubset(chunk.input_ids)
if candidate.input_ids is not None else not candidate.has_user and bool(candidate.signature)
for candidate in candidates
)
if needs_canonical and session_turns_loader is not None:
session_turns = session_turns_loader()
entries: list[tuple[int, PromptSummary, dict[str, Any] | None]] = [
@@ -2028,9 +2084,30 @@ def _build_prompt_view(
signature_positions: dict[str, list[int]] = {}
for position, turn in enumerate(session_turns or []):
signature_positions.setdefault(_assistant_signature_identity(turn.assistant_signature), []).append(position)
canonical_inputs = {
user["input_id"]: user
for turn in session_turns or []
for user in (turn.user_event,)
if isinstance(user.get("input_id"), str)
}
represented = set(chunk.input_ids)
# Identity references take precedence over legacy answer matching, even when
# the matching legacy answer occurs earlier in the display history.
reserved = {input_id for candidate in candidates for input_id in candidate.input_ids or ()
if input_id in canonical_inputs}
used_positions: set[int] = set()
for candidate in candidates:
if not session_turns:
break
if candidate.input_ids is not None:
for input_id in candidate.input_ids:
if input_id in represented or input_id not in canonical_inputs:
continue
user = dict(canonical_inputs[input_id])
summary = _prompt_summary(user, candidate.ordinal, chunk.answers.get(input_id, ""))
entries.append((candidate.ordinal, summary, user))
represented.add(input_id)
continue
positions = signature_positions.get(candidate.signature)
if not candidate.signature or not positions:
continue
@@ -2044,15 +2121,40 @@ def _build_prompt_view(
if candidate.has_user:
continue
user = dict(session_turns[match].user_event)
if match in used_positions or user.get("input_id") in represented or user.get("input_id") in reserved:
continue
used_positions.add(match)
if isinstance(input_id := user.get("input_id"), str) and input_id:
represented.add(input_id)
summary = _prompt_summary(user, candidate.ordinal, candidate.answer_preview)
entries.append((candidate.ordinal, summary, user))
prompts: list[PromptSummary] = []
backfilled_users: dict[int, dict[str, Any]] = {}
for ordinal, prompt, user in sorted(entries, key=lambda entry: entry[0]):
prompts.append(prompt)
backfilled_users: dict[int, list[dict[str, Any]]] = {}
for ordinal, _, user in entries:
if user is not None:
backfilled_users[ordinal] = user
return _PromptView(tuple(prompts), backfilled_users, needs_canonical)
backfilled_users.setdefault(ordinal, []).append(user)
order: dict[tuple[int, str], int] = {}
plan: dict[int, list[tuple[int, dict[str, Any]]]] = {}
for ordinal, records in chunk.turns.items():
users = backfilled_users.get(ordinal, [])
recovered_ids = {_client_projection_event_id(user) for user in users}
for user in users:
records = _with_backfilled_user(records, user)
next_anchor = 2**63 - 1
reverse_plan: list[tuple[int, dict[str, Any]]] = []
for position in range(len(records) - 1, -1, -1):
record = records[position]
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")
if identity.startswith(f"turn:{ordinal}:record:"):
next_anchor = int(identity.rsplit(":", 1)[1])
if record.get("event") == "user":
event_id = _client_projection_event_id(record)
order[(ordinal, event_id)] = position
if event_id in recovered_ids:
reverse_plan.append((next_anchor, record))
if reverse_plan:
plan[ordinal] = list(reversed(reverse_plan))
entries.sort(key=lambda entry: (entry[0], order.get((entry[0], entry[1]["id"]), 0)))
return _PromptView(tuple(prompt for _, prompt, _ in entries), plan, needs_canonical)
def build_prompt_index(
+7
View File
@@ -819,6 +819,7 @@ class TestToolEventProgress:
chat_id="chat-a",
content="Can you include the key detail?",
session_key_override=session_key,
metadata={WEBUI_TURN_METADATA_KEY: "followup"},
))
release_first_request.set()
# Events synchronize injection; the deadline only guards against a stuck worker.
@@ -855,6 +856,11 @@ class TestToolEventProgress:
for message in outbound
if isinstance(message.event, StreamDeltaEvent)
] == ["Checking", "The late result is ready"]
assert [
message.metadata["response_input_ids"]
for message in outbound
if isinstance(message.event, StreamDeltaEvent)
] == [[], ["user:followup"]]
assert any(isinstance(message.event, ProgressEvent) for message in outbound)
assert len([
message for message in outbound if isinstance(message.event, TurnEndEvent)
@@ -902,6 +908,7 @@ class TestToolEventProgress:
WEBUI_TURN_METADATA_KEY,
"_history_generation",
"latency_ms",
"response_input_ids",
}
for message in visible_events
)
+90 -1
View File
@@ -13,6 +13,7 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
from nanobot.runtime_context import public_history_message
from nanobot.session.manager import SessionManager
from nanobot.session.recovery import (
@@ -71,7 +72,7 @@ async def test_committed_model_failure_continues_with_tool_results_without_resen
monkeypatch.setattr(read_tool, "execute", execute)
request = InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="Read the note and summarize it",
metadata={"webui": True, "webui_turn_id": "request-1"},
metadata={"webui": True, "webui_turn_id": "request-1", "message_id": "original-input"},
)
try:
with coordinator.connected():
@@ -83,9 +84,20 @@ async def test_committed_model_failure_continues_with_tool_results_without_resen
await loop._dispatch_one(bus.inbound.get_nowait(), asyncio.Queue())
final = await sessions.state.get(request.session_key)
assert final.metadata[RECOVERY_METADATA_KEY]["status"] == "recovered"
answer = next(row for row in final.messages if row.get("content") == "Finished from the saved result.")
user = next(row for row in final.messages if row.get("role") == "user")
assert user["input_id"]
assert answer["response_input_ids"] == [user["input_id"]]
assert execute.await_count == 1
assert sum(message.get("role") == "user" for message in final.messages) == 1
assert any(message.get("role") == "tool" and "saved evidence" in message["content"] for message in requests[-1]["messages"])
continuation = requests[-1]["messages"][-1]
assert continuation["_hidden_history"] == {"kind": "internal_continuation"}
# The marker is runner bookkeeping, not part of an OpenAI-compatible wire request.
wire_messages = OpenAICompatProvider._sanitize_messages(
OpenAICompatProvider(api_key="test"), requests[-1]["messages"], model="test-model",
)
assert all("_hidden_history" not in row for row in wire_messages)
assert requests[0]["messages"][0] == requests[-1]["messages"][0]
assert requests[0]["tools"] == requests[-1]["tools"]
assert requests[-1]["messages"][:len(requests[1]["messages"])] == requests[1]["messages"]
@@ -542,3 +554,80 @@ async def test_new_input_waits_for_real_recovery_cancellation_before_reading_dra
assert RUNTIME_CHECKPOINT_KEY not in saved.metadata
finally:
await reopened.state.aclose()
@pytest.mark.asyncio
async def test_length_recovery_retains_original_prompt_attribution(tmp_path: Path, history) -> None:
bus = MessageBus()
sessions = history.sessions
session = sessions.get_or_create("websocket:chat")
session.metadata["title"] = "Saved recovery"
sessions.save(session)
recovery = RecoveryCoordinator(sessions, bus)
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.can_resume_conversation_state.return_value = False
requests = []
responses = iter([
LLMResponse(content=None, reasoning_content="thinking", finish_reason="length"),
LLMResponse(content="network failure", finish_reason="error", error_kind="connection"),
LLMResponse(content="Recovered answer"),
])
async def respond(**kwargs):
requests.append(deepcopy(kwargs["messages"]))
return next(responses)
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model",
session_manager=sessions, recovery_admission=recovery)
loop.turn_delivery_factory = TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions))
coordinator = WebuiTurnCoordinator(bus, sessions, loop.schedule_background, recovery=recovery)
request = InboundMessage(channel="websocket", sender_id="user", chat_id="chat", content="Original question",
metadata={"webui": True, "webui_turn_id": "original", "message_id": "original"})
recorder = WebUITranscriptRecorder(sessions)
try:
await recorder.prepare_and_append("chat", {"event": "user", "chat_id": "chat", "text": request.content},
metadata=await history.metadata("chat", request.metadata))
with coordinator.connected():
await loop._dispatch_one(request, asyncio.Queue())
state = (await sessions.state.get(request.session_key)).metadata[RECOVERY_METADATA_KEY]
assert state["status"] == "awaiting_user"
persisted = SessionManager(tmp_path).get_or_create(request.session_key)
assert any(row.get("_hidden_history") == {"kind": "internal_continuation"} for row in persisted.messages)
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})
await loop._dispatch_one(bus.inbound.get_nowait(), asyncio.Queue())
final = SessionManager(tmp_path).get_or_create(request.session_key)
answer = next(row for row in final.messages if row.get("content") == "Recovered answer")
assert answer["response_input_ids"] == ["user:original"]
outbound = [bus.outbound.get_nowait() for _ in range(bus.outbound.qsize())]
delivered = next(row for row in outbound if row.content == "Recovered answer")
await recorder.prepare_and_append("chat", {"event": "message", "chat_id": "chat", "text": delivered.content},
metadata=await history.metadata("chat", delivered.metadata), include_source=True)
assert history.prompts(request.session_key)[0]["answerPreview"] == "Recovered answer"
wire = OpenAICompatProvider._sanitize_messages(OpenAICompatProvider(api_key="test"), requests[-1], model="test-model")
assert all("_hidden_history" not in row for row in wire)
finally:
await loop.aclose()
def test_persisted_automation_input_blocks_prior_prompt_attribution(tmp_path: Path) -> None:
from nanobot.agent.runner import AgentRunner
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
sessions = SessionManager(tmp_path)
session = sessions.get_or_create("websocket:chat")
session.add_message("user", "Original question", input_id="user:original")
session.add_message("assistant", "Original answer")
session.add_message("user", "Scheduled task", **{AUTOMATION_HISTORY_META: True})
session.add_message("assistant", "Thinking", reasoning_content="thinking")
session.add_message("user", "Continue", _hidden_history={"kind": "internal_continuation"})
sessions.save(session)
replay = SessionManager(tmp_path).get_or_create("websocket:chat").get_history()
assert AgentRunner._response_input_ids(replay) == ()
assert replay[-1]["_hidden_history"] == {"kind": "internal_continuation"}
public = session.get_history(include_runtime_context=False)
assert all("_hidden_history" not in row for row in public)
wire = OpenAICompatProvider._sanitize_messages(OpenAICompatProvider(api_key="test"), replay, model="test-model")
assert all("_hidden_history" not in row and AUTOMATION_HISTORY_META not in row for row in wire)
+80 -2
View File
@@ -654,6 +654,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
assert result.messages[-1] == {
"role": "assistant",
"content": "Read the directory twice. More investigation remains.",
"_meta": {"response_input_ids": []},
}
assert len(calls) == 3
assert calls[-1]["tools"] is None
@@ -718,7 +719,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
assert result.stop_reason == "completed"
assert result.messages == [
{"role": "user", "content": "do task"},
{"role": "assistant", "content": "recovered answer"},
{"role": "assistant", "content": "recovered answer", "_meta": {"response_input_ids": []}},
]
assert [item["tools"] for item in calls] == [definitions, definitions, None]
assert ["on_content_delta" in item for item in calls] == [True, True, False]
@@ -986,7 +987,7 @@ async def test_runner_length_recovery_returns_all_segments():
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "give a long answer"}],
initial_messages=[{"role": "user", "content": "give a long answer", "_meta": {"input_id": "long"}}],
tools=tools,
model="test-model",
max_iterations=5,
@@ -1000,6 +1001,7 @@ async def test_runner_length_recovery_returns_all_segments():
if message.get("role") == "assistant"
] == ["first", "second", "third"]
assert provider.chat_stream_with_retry.await_count == 3
assert [m["_meta"]["response_input_ids"] for m in result.messages if m.get("role") == "assistant"] == [["long"]] * 3
@pytest.mark.asyncio
@@ -1243,3 +1245,79 @@ async def test_runner_passes_generation_settings_to_provider():
assert captured["temperature"] == 0.3
assert captured["max_tokens"] == 8192
assert captured["reasoning_effort"] == "high"
@pytest.mark.asyncio
@pytest.mark.parametrize("automated", [False, True])
async def test_runner_continuation_preserves_request_ownership(automated):
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="first"), LLMResponse(content="continued"),
])
tools = MagicMock()
tools.get_definitions.return_value = []
inputs = [
{"role": "user", "content": "old", "_meta": {"input_id": "old"}},
{"role": "assistant", "content": "old answer"},
({"role": "user", "content": "scheduled", "_automation_turn": True}
if automated else {"role": "user", "content": "new", "_meta": {"input_id": "new"}}),
]
result = await AgentRunner().run(make_run_spec(
provider, initial_messages=inputs, tools=tools, model="test-model",
max_iterations=2, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=AsyncMock(side_effect=["Continue", None]),
))
answers = [m for m in result.messages if m.get("role") == "assistant"][-2:]
assert [m["_meta"]["response_input_ids"] for m in answers] == (
[[], []] if automated else [["new"], ["new"]]
)
@pytest.mark.asyncio
@pytest.mark.parametrize("automated", [False, True])
async def test_interrupted_output_ownership_survives_persistence_and_later_checkpoint(tmp_path, automated):
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
from nanobot.session.manager import Session, SessionManager
from nanobot.session.message_metadata import persisted_message
provider = MagicMock(spec=LLMProvider)
calls = 0
async def chat_stream_with_retry(**kwargs):
nonlocal calls
calls += 1
if calls == 1:
await kwargs["on_content_delta"]("partial")
return LLMResponse(content="failed", finish_reason="error")
return LLMResponse(content="done")
provider.chat_stream_with_retry = chat_stream_with_retry
tools = MagicMock()
tools.get_definitions.return_value = []
hook = AgentHook()
hook.wants_streaming = MagicMock(return_value=True)
checkpoints = []
async def checkpoint(payload):
checkpoints.append(payload)
initial = [{"role": "user", "content": "task", **(
{"_automation_turn": True} if automated else {"_meta": {"input_id": "input-1"}}
)}]
# An injection after the failed request makes the next request and its checkpoint reachable.
injection = {"role": "user", "content": "follow up", "_meta": {"input_id": "next"}}
drain = AsyncMock(side_effect=[[], [], [injection], [], [], []])
result = await AgentRunner().run(make_run_spec(
provider, initial_messages=initial, tools=tools, model="test-model",
max_iterations=3, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
hook=hook, checkpoint_callback=checkpoint, injection_callback=drain,
))
interrupted = next(m for m in result.messages if m.get("_interrupted"))
assert interrupted["_meta"]["response_input_ids"] == ([] if automated else ["input-1"])
manager = SessionManager(tmp_path)
manager.save(Session(key="cli:ownership", messages=[persisted_message(m) for m in result.messages]))
loaded = manager.read_session_snapshot("cli:ownership")
persisted_interrupted = next(m for m in loaded.messages if m.get("_interrupted"))
assert persisted_interrupted == persisted_message(interrupted)
assert persisted_interrupted["response_input_ids"] == ([] if automated else ["input-1"])
assert any(interrupted in cp["preceding_messages"] for cp in checkpoints)
+4 -8
View File
@@ -611,16 +611,12 @@ async def test_checkpoint2_preserves_final_response_in_history_before_followup()
assert call_count["n"] == 2
assert captured_messages[-1] == [
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "first answer"},
{"role": "assistant", "content": "first answer", "_meta": {"response_input_ids": []}},
{"role": "user", "content": "follow-up question"},
]
assert [
{"role": message["role"], "content": message["content"]}
for message in result.messages
if message.get("role") == "assistant"
] == [
{"role": "assistant", "content": "first answer"},
{"role": "assistant", "content": "second answer"},
assert [message for message in result.messages if message.get("role") == "assistant"] == [
{"role": "assistant", "content": "first answer", "_meta": {"response_input_ids": []}},
{"role": "assistant", "content": "second answer", "_meta": {"response_input_ids": []}},
]
+166 -5
View File
@@ -12,12 +12,19 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import UserInputEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import UserInputAccepted
from nanobot.channels.manager import ChannelManager
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.providers.base import LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.security.workspace_access import current_workspace_scope
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.recovery import PENDING_FOLLOWUPS_KEY
from nanobot.session.session_handles import SessionHandleResolver
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
from nanobot.session.webui_turns import WebuiTurnCoordinator
from nanobot.session.webui_turns import WebuiTurnCoordinator, WebuiTurnRoutePolicy
from nanobot.webui.gateway_services import build_gateway_services
from nanobot.webui.history import record_from_fact
from nanobot.webui.transcript import build_prompt_index, build_webui_thread_response
@pytest.fixture
@@ -147,14 +154,19 @@ async def test_path_followup_reaches_running_turn(loop: AgentLoop) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("message_count", [1, 2], ids=["idle", "active"])
@pytest.mark.parametrize("message_count", [1, 3], ids=["idle", "batched-followups"])
async def test_cross_session_input_preserves_source_in_live_events_and_history(
loop: AgentLoop, message_count: int,
loop: AgentLoop, message_count: int, tmp_path: Path,
) -> None:
source_key, target_key = "websocket:source", "websocket:target"
project = tmp_path / "target-project"
project.mkdir()
target_scope = {"project_path": str(project), "access_mode": "restricted"}
await loop.sessions.state.get(source_key)
await loop.sessions.state.get(target_key)
await loop.sessions.state.mutate_metadata(target_key, lambda metadata: metadata.update(webui=True))
await loop.sessions.state.mutate_metadata(
target_key, lambda metadata: metadata.update(webui=True, workspace_scope=target_scope),
)
handles = SessionHandleResolver(loop.sessions)
source = await handles.ahandle_for_session(source_key)
destination = await handles.ahandle_for_session(target_key)
@@ -170,11 +182,15 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
loop.bus.publish_outbound = AsyncMock()
started, release = asyncio.Event(), asyncio.Event()
observed_scopes = []
async def respond(**kwargs):
observed_scopes.append(current_workspace_scope())
started.set()
await release.wait()
return LLMResponse(content="Reviewed", tool_calls=[], usage=None)
loop.runner.run = AsyncMock(wraps=loop.runner.run)
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
run = asyncio.create_task(loop.run())
try:
@@ -190,6 +206,10 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
while len(accepted) < index + 1:
await asyncio.sleep(0)
await asyncio.wait_for(started.wait(), 3)
if index:
async with asyncio.timeout(3):
while loop._pending_queues[target_key].empty():
await asyncio.sleep(0)
release.set()
await asyncio.wait_for(
asyncio.gather(*loop._active_tasks[target_key]), 5,
@@ -209,10 +229,151 @@ async def test_cross_session_input_preserves_source_in_live_events_and_history(
inputs = [record for record in records if record.get("event") == "user"]
assert [record["text"] for record in inputs] == [f"Review {i}" for i in range(message_count)]
assert all(record["session_message"]["session"] == provenance for record in inputs)
loop.provider.chat_stream_with_retry.assert_awaited()
assert [record["created_at_ms"] for record in inputs] == [event.created_at_ms for event in events]
session = await loop.sessions.state.get(target_key)
stored_inputs = [row for row in session.messages if row.get("role") == "user"]
assert [row["session_message"] for row in stored_inputs] == [
event.provenance["session_message"] for event in events
]
assert [row["input_id"] for row in stored_inputs] == [row["input_id"] for row in inputs] == [event.input_id for event in events]
assert [scope.metadata() for scope in observed_scopes] == [target_scope] * min(message_count, 2)
assert all(scope.source_channel == "websocket" for scope in observed_scopes)
response = next(call.args[0] for call in reversed(loop.bus.publish_outbound.await_args_list)
if call.args[0].content == "Reviewed")
assert response.metadata["response_input_ids"] == [row["input_id"] for row in stored_inputs[0 if message_count == 1 else 1:]]
loop.runner.run.assert_awaited_once()
assert PENDING_FOLLOWUPS_KEY not in session.metadata
finally:
release.set()
disconnect()
disconnect_accepted()
run.cancel()
await asyncio.gather(run, return_exceptions=True)
@pytest.mark.asyncio
async def test_busy_cross_session_input_uses_target_scope_and_keeps_its_answer(loop: AgentLoop, tmp_path: Path) -> None:
source_key, target_key = "websocket:source", "websocket:target"
await loop.sessions.state.get(source_key)
await loop.sessions.state.get(target_key)
await loop.sessions.state.mutate_metadata(target_key, lambda metadata: metadata.update(webui=True))
handles = SessionHandleResolver(loop.sessions)
destination = await handles.ahandle_for_session(target_key)
assert destination is not None
tool = SendSessionMessageTool(sessions=loop.sessions, bus=loop.bus)
coordinator = WebuiTurnCoordinator(
bus=loop.bus, sessions=loop.sessions,
schedule_background=lambda coro: coro.close(),
)
disconnect = coordinator.subscribe()
accepted = []
disconnect_accepted = loop.bus.subscribe(accepted.append, UserInputAccepted)
project = tmp_path / "target-project"
project.mkdir()
target_scope = {"project_path": str(project), "access_mode": "restricted"}
await loop.sessions.state.mutate_metadata(
target_key, lambda metadata: metadata.update(workspace_scope=target_scope),
)
config = WebSocketConfig()
gateway = build_gateway_services(
config=config, bus=loop.bus, session_manager=loop.sessions,
static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
default_restrict_to_workspace=False, runtime_model_name=None,
runtime_surface="browser", runtime_capabilities_overrides=None,
)
channel = WebSocketChannel(config, loop.bus, gateway=gateway)
async def deliver(msg):
await ChannelManager._send_once(channel, msg)
loop.bus.publish_outbound = AsyncMock(side_effect=deliver)
policy = WebuiTurnRoutePolicy(loop.sessions)
loop.turn_delivery_factory.route_policy = policy
loop.turn_delivery_factory.route_admission = policy.admit
loop.runner.run = AsyncMock(wraps=loop.runner.run)
metadata = {"webui": True, "webui_turn_id": "original", "_wants_stream": True,
HISTORY_GENERATION_METADATA_KEY: (await loop.sessions.state.get(target_key)).generation}
await gateway.transcripts.append_user_message("target", "Original question", metadata=metadata)
started, release = asyncio.Event(), asyncio.Event()
calls = []
async def respond(**kwargs):
calls.append(current_workspace_scope())
content = f"Answer {len(calls)}"
await kwargs["on_content_delta"](content)
if len(calls) == 1:
started.set()
await release.wait()
return LLMResponse(content=content, tool_calls=[], usage=None)
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
run = asyncio.create_task(loop.run())
try:
await loop.bus.publish_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="target", content="Original question",
metadata=metadata,
))
await asyncio.wait_for(started.wait(), 3)
with request_context(RequestContext(
channel="websocket", chat_id="source", session_key=source_key,
)):
await tool.execute(to=destination.name, content="Review", expect_reply=False)
async with asyncio.timeout(3):
while len(accepted) < 2 or loop._pending_queues[target_key].empty():
await asyncio.sleep(0)
release.set()
await asyncio.wait_for(asyncio.gather(*loop._active_tasks[target_key]), 5)
assert [scope.metadata() for scope in calls] == [target_scope, target_scope]
assert all(scope.source_channel == "websocket" for scope in calls)
loop.runner.run.assert_awaited_once()
session = await loop.sessions.state.get(target_key)
stored = [row for row in session.messages if row.get("role") == "user"]
assert [public_history_message(row)["content"] for row in stored] == ["Original question", "Review"]
records = await loop.sessions.state.project_history(
target_key,
lambda history: [record_from_fact(fact, target_key) for fact in history.all_facts()],
)
displayed = next(row for row in records if row.get("session_message"))
assert stored[1]["session_message"] == displayed["session_message"]
assert stored[1]["input_id"] == displayed["input_id"]
answers = [row for row in records if row.get("event") == "stream_end"]
assert [row["response_input_ids"] for row in answers] == [[row["input_id"]] for row in stored]
prompts, page = await loop.sessions.state.project_history(target_key, lambda history: (
build_prompt_index(target_key, history=history, session_messages_loader=lambda: session.messages),
build_webui_thread_response(target_key, history=history, session_messages=session.messages),
))
assert [prompt["answerPreview"] for prompt in prompts] == ["Answer 1", "Answer 2"]
users = [row for row in page["events"] if row["event"] == "user_message"]
assert [row["text"] for row in users] == ["Original question", "Review"]
assert [row["input_id"] for row in users] == [row["input_id"] for row in stored]
assert PENDING_FOLLOWUPS_KEY not in session.metadata
finally:
release.set()
disconnect()
disconnect_accepted()
run.cancel()
await asyncio.gather(run, return_exceptions=True)
@pytest.mark.asyncio
@pytest.mark.parametrize("expect_reply", [True, False])
@pytest.mark.parametrize("disabled", [True, False])
async def test_session_message_source_context_independent_of_tool_policy(
loop: AgentLoop, expect_reply: bool, disabled: bool,
) -> None:
from nanobot.session.manager import SessionPolicy
session = loop.sessions.get_or_create("telegram:target")
loop.sessions.save(session)
await loop.sessions.state.set_policy(
"telegram:target",
SessionPolicy(disabled_tools=frozenset({"send_session_message"}) if disabled else frozenset()),
)
msg = _message("Please review this")
msg.metadata[SESSION_MESSAGE_METADATA_KEY]["expect_reply"] = expect_reply
await loop._process_message(msg)
messages = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
content = next(row["content"] for row in reversed(messages) if row.get("role") == "user")
assert content.startswith("Please review this")
assert content.count("Message from @luma.") == 1
assert ("Reply with send_session_message." in content) is expect_reply
+2 -1
View File
@@ -458,6 +458,7 @@ def test_get_history_does_not_duplicate_persisted_cli_app_runtime_context():
"entry_point": "cli-anything-drawio",
}],
RUNTIME_CONTEXT_HISTORY_META: marker,
"input_id": "user:cli-app",
})
model_history = session.get_history(max_messages=500)
@@ -466,7 +467,7 @@ def test_get_history_does_not_duplicate_persisted_cli_app_runtime_context():
include_runtime_context=False,
)
assert model_history == [{"role": "user", "content": content}]
assert model_history == [{"role": "user", "content": content, "_meta": {"input_id": "user:cli-app"}}]
assert model_history[0]["content"].count("CLI App Attachment: @drawio") == 1
assert public_history == [{"role": "user", "content": "please use @drawio"}]
+1 -1
View File
@@ -263,7 +263,7 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
assert initial_reply.metadata["slack"] == slack_route
assert saved_route == {"channel": "slack", "chat_id": "C1", "metadata": thread_metadata}
assert (late_reply.channel, late_reply.chat_id) == ("slack", "C1")
assert late_reply.metadata == thread_metadata
assert late_reply.metadata == {**thread_metadata, "response_input_ids": []}
finally:
release_child.set()
loop.stop()
+19 -3
View File
@@ -18,6 +18,7 @@ from nanobot.session.recovery import (
pending_followups,
restore_runtime_checkpoint,
)
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
from nanobot.webui.recovery import RecoveryCoordinator
@@ -148,7 +149,8 @@ async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path):
@pytest.mark.parametrize("interrupt", [False, True], ids=["completed", "checkpoint-recovery"])
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt):
@pytest.mark.parametrize("cross_session", [False, True])
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt, cross_session):
import asyncio
provider = MagicMock(aclose=AsyncMock())
@@ -173,12 +175,19 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
draft = await loop.sessions.state.get("websocket:chat")
draft.add_message(
"user", "intentionally identical text", **{INBOUND_META_TURN_ID: "initial-input"},
timestamp="2026-10-18T19:00:00",
timestamp="2026-10-18T19:00:00", input_id="user:initial-input",
)
await loop.sessions.state.prepare_input(draft)
queue = asyncio.Queue()
for turn_id in ("first-input", "second-input"):
message = _input("intentionally identical text", turn_id)
if cross_session:
message.channel, message.input_role = "system", "user"
message.chat_id = message.session_key_override = draft.key
message.metadata = {SESSION_MESSAGE_METADATA_KEY: {
"message_id": turn_id, "created_at_ms": 1, "expect_reply": False,
"source_handle": "luma", "source_session_key": "websocket:source", "target_session_key": draft.key,
}}
identifier = await loop.sessions.state.queue_followup(draft.key, message)
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
queue.put_nowait(message)
@@ -218,7 +227,14 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
stored = await reopened.state.get(draft.key)
inputs = [row for row in stored.messages if row.get("role") == "user"]
assert [public_history_message(row)["content"] for row in inputs] == ["intentionally identical text"] * 3
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
if cross_session:
assert [row["session_message"]["message_id"] for row in inputs[1:]] == ["first-input", "second-input"]
else:
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
prefix = "session-message" if cross_session else "user"
input_ids = ["user:initial-input", f"{prefix}:first-input", f"{prefix}:second-input"]
assert [row["input_id"] for row in inputs] == input_ids
assert stored.messages[-1]["response_input_ids"] == input_ids
assert [row["timestamp"] for row in inputs] == ["2026-10-18T19:00:00"] * 3
assert pending_followups(stored) == []
assert bus.inbound.empty()
+20 -11
View File
@@ -20,6 +20,7 @@ from nanobot.session.recovery import (
pending_followups,
record_pending_followup,
)
from nanobot.session.session_messages import SESSION_MESSAGE_METADATA_KEY
from nanobot.webui import history as history_module
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
@@ -204,20 +205,21 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
@pytest.mark.asyncio
async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path) -> None:
@pytest.mark.parametrize("cross_session", [False, True])
async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path, cross_session: bool) -> None:
sessions = SessionManager(tmp_path)
session = sessions.get_or_create("websocket:chat")
_persist(sessions, session)
followup_id = record_pending_followup(
session,
InboundMessage(
channel="websocket",
sender_id="user",
chat_id="chat",
content="also check the logs",
metadata={"webui": True},
),
metadata = {SESSION_MESSAGE_METADATA_KEY: {
"message_id": "source-message", "created_at_ms": 1, "expect_reply": False,
"source_handle": "luma", "source_session_key": "websocket:source", "target_session_key": session.key,
}} if cross_session else {"webui": True}
message = InboundMessage(
channel="system" if cross_session else "websocket", sender_id="session" if cross_session else "user",
chat_id=session.key if cross_session else "chat", content="/stop" if cross_session else "also check the logs", metadata=metadata,
session_key_override=session.key, input_role="user" if cross_session else None,
)
followup_id = record_pending_followup(session, message)
assert followup_id is not None
sessions.save(session)
@@ -225,9 +227,16 @@ async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_pat
await coordinator.scan()
queued = bus.inbound.get_nowait()
assert queued.content == "also check the logs"
assert (queued.channel, queued.content, queued.input_role, queued.timestamp) == (
message.channel, message.content, message.input_role, message.timestamp,
)
assert queued.session_key == session.key
assert queued.require_existing_session
if cross_session:
assert queued.metadata[SESSION_MESSAGE_METADATA_KEY] == metadata[SESSION_MESSAGE_METADATA_KEY]
assert queued.metadata["_recovery_followup_id"] == followup_id
restored = restarted.get_or_create("websocket:chat")
assert record_pending_followup(restored, queued) == followup_id
assert len(pending_followups(restored)) == 1
acknowledge_pending_followups(restored, [followup_id])
@@ -0,0 +1,31 @@
import pytest
from nanobot.agent.tools.session_messages import SendSessionMessageTool, SessionMessageError
from nanobot.bus.queue import MessageBus
from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import SessionHandleResolver
async def test_session_send_rejects_commands_and_delivers_normal_input(tmp_path):
manager = SessionManager(tmp_path)
bus = MessageBus()
tool = SendSessionMessageTool(sessions=manager, bus=bus)
try:
await manager.state.get("websocket:source")
await manager.state.get("websocket:target")
handles = SessionHandleResolver(manager)
target = await handles.ahandle_for_session("websocket:target")
assert target is not None
for content in ("/stop", " /stop", "\n\t/restart", "/restart"):
with pytest.raises(SessionMessageError, match="slash commands"):
await tool.enqueue(source_session_key="websocket:source", target_handle=target.name,
content=content, expect_reply=False)
assert bus.inbound_size == 0
await tool.enqueue(source_session_key="websocket:source", target_handle=target.name,
content="Please review /restart", expect_reply=False)
message = await bus.consume_inbound()
assert message.content == "Please review /restart"
assert message.session_key == "websocket:target"
assert bus.inbound_size == 0
finally:
await manager.state.aclose()
+1 -1
View File
@@ -251,7 +251,7 @@ def test_v4_archive_upgrade_removes_orphans_and_preserves_existing_membership(tm
db.execute("INSERT INTO storage_meta (key, value) VALUES ('session_archives_imported', '1')")
store.initialize(workspace)
store.initialize(workspace)
assert _database_snapshot(store.path)[0] == 4
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
assert store.archived_keys() == ["chat:empty-fork", "chat:extensions"]
assert store.archives_imported()
assert store.load("chat:extensions") == original
+32 -2
View File
@@ -311,8 +311,8 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
"source_session_key": "websocket:source",
"target_session_key": "websocket:target",
}
append_input = AsyncMock(side_effect=None if write_succeeds else OSError("write failed"))
monkeypatch.setattr(wth, "append_session_message_input", append_input)
append_input = AsyncMock(return_value=write_succeeds)
monkeypatch.setattr(wth.WebUITranscriptRecorder, "append_user_message", append_input)
coordinator = wth.WebuiTurnCoordinator(
bus=bus,
sessions=sessions,
@@ -345,6 +345,36 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
}
@pytest.mark.asyncio
async def test_session_input_rejects_replaced_target_generation(tmp_path) -> None:
bus = MessageBus()
bus.publish_outbound = AsyncMock()
sessions = SessionManager(tmp_path)
target = sessions.get_or_create("websocket:target")
target.metadata["webui"] = True
sessions.save(target)
source = session_handle_for_name("websocket:source", "luma")
coordinator = wth.WebuiTurnCoordinator(
bus=bus, sessions=sessions, schedule_background=lambda coro: coro.close(),
)
coordinator.subscribe()
await bus.publish(UserInputAccepted(
context=RuntimeEventContext(
channel="system", chat_id="websocket:target", session_key="websocket:target",
session_generation="replaced-generation",
metadata={SESSION_MESSAGE_METADATA_KEY: {
"message_id": "message-1", "created_at_ms": 123, "expect_reply": False,
"source_handle": source.name, "source_session_key": "websocket:source",
"target_session_key": "websocket:target",
}},
),
content="Review this",
))
bus.publish_outbound.assert_not_awaited()
records = await sessions.state.project_history("websocket:target", lambda h: list(h.all_facts()))
assert records == []
@pytest.mark.asyncio
async def test_fallback_model_ignores_non_websocket_requests() -> None:
bus = MessageBus()
@@ -0,0 +1,154 @@
from nanobot.webui.transcript import TranscriptReplayStats
def test_grouped_backfill_keeps_response_input_order_in_page_and_index(history, tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:backfill-order"
ids = ["input:first", "input:second", "input:third"]
messages = [
{"role": "user", "content": name, "input_id": input_id}
for name, input_id in zip(("first", "second", "third"), ids)
] + [{"role": "assistant", "content": "answer"}]
history.append(key, {"event": "user", "text": "second", "input_id": ids[1]})
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ids})
history.append(key, {"event": "turn_end"})
def loader():
return messages
index = history.prompts(key, session_messages_loader=loader)
stats = TranscriptReplayStats()
page = history.build(key, limit=1, session_messages_loader=loader, stats=stats)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert [event["text"] for event in users] == ["first", "second", "third"]
assert [prompt["inputId"] for prompt in index] == ids
assert [prompt["id"] for prompt in index] == [event["projection_id"] for event in users]
assert stats.parsed_records < 10
def test_identity_backfill_is_not_repeated_by_legacy_answer_matching(history, tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:backfill-duplicate"
messages = [
{"role": "user", "content": "question", "input_id": "input:one"},
{"role": "assistant", "content": "answer"},
]
history.append(key, {"event": "message", "text": "answer"})
history.append(key, {"event": "turn_end"})
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ["input:one"]})
history.append(key, {"event": "turn_end"})
def loader():
return messages
index = history.prompts(key, session_messages_loader=loader)
page = history.build(key, limit=10, session_messages_loader=loader)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert [prompt["inputId"] for prompt in index] == ["input:one"]
assert [event["text"] for event in users] == ["question"]
assert index[0]["id"] == users[0]["projection_id"]
latest = history.build(key, limit=1, session_messages_loader=loader)
older = history.build(key, limit=1, before=latest["page"]["before_cursor"], session_messages_loader=loader)
paged_users = [event for part in (older, latest) for event in part["events"] if event["event"] == "user_message"]
assert [event["projection_id"] for event in paged_users] == [index[0]["id"]]
def test_empty_response_inputs_do_not_use_legacy_answer_matching(history, tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:empty-response-inputs"
messages = [
{"role": "user", "content": "question", "input_id": "input:one"},
{"role": "assistant", "content": "answer"},
]
history.append(key, {"event": "message", "text": "answer", "response_input_ids": []})
history.append(key, {"event": "turn_end"})
history.append(key, {"event": "message", "text": "answer"})
history.append(key, {"event": "turn_end"})
def loader():
return messages
index = history.prompts(key, session_messages_loader=loader)
page = history.build(key, limit=10, session_messages_loader=loader)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert [prompt["inputId"] for prompt in index] == ["input:one"]
assert [event["projection_id"] for event in users] == [index[0]["id"]]
latest = history.build(key, limit=1, session_messages_loader=loader)
older = history.build(key, limit=1, before=latest["page"]["before_cursor"], session_messages_loader=loader)
assert not [event for event in older["events"] if event["event"] == "user_message"]
assert [event["projection_id"] for event in latest["events"] if event["event"] == "user_message"] == [index[0]["id"]]
def test_truncated_turn_applies_plan_when_reference_anchor_is_dropped(history, tmp_path, monkeypatch):
from nanobot.webui import transcript
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 5)
key = "websocket:truncated-backfill"
ids = ["input:a", "input:b", "input:c"]
messages = [{"role": "user", "content": text, "input_id": ident}
for text, ident in zip(("A", "B", "C"), ids)]
history.append(key, {"event": "user", "text": "B", "input_id": ids[1]})
history.append(key, {"event": "message", "text": "first", "response_input_ids": ids[:2]})
for i in range(12):
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
history.append(key, {"event": "message", "text": "last", "response_input_ids": ids[2:]})
history.append(key, {"event": "turn_end"})
index = history.prompts(key, session_messages_loader=lambda: messages)
page = history.build(key, limit=10, session_messages_loader=lambda: messages)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert page["page"]["truncated_oversized_turn"]
assert not page["page"]["has_more_before"]
assert [event["text"] for event in users] == ["A", "B", "C"]
assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index]
def test_truncated_turn_recovers_even_if_all_missing_references_were_dropped(history, tmp_path, monkeypatch):
from nanobot.webui import transcript
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4)
key = "websocket:truncated-no-reference"
messages = [{"role": "user", "content": "A", "input_id": "a"}]
history.append(key, {"event": "user", "text": "B", "input_id": "b"})
history.append(key, {"event": "message", "text": "old", "response_input_ids": ["a", "b"]})
for i in range(10):
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
history.append(key, {"event": "message", "text": "new"})
history.append(key, {"event": "turn_end"})
index = history.prompts(key, session_messages_loader=lambda: messages)
page = history.build(key, limit=10, session_messages_loader=lambda: messages)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert page["page"]["truncated_oversized_turn"]
assert [event["text"] for event in users] == ["A", "B"]
assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index]
def test_completed_stream_compaction_and_truncation_keep_shared_backfill_anchor(history, tmp_path, monkeypatch):
from nanobot.webui import transcript
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:stream-anchor"
ids = ["input:a", "input:b", "input:c"]
messages = [{"role": "user", "content": text, "input_id": ident}
for text, ident in zip(("A", "B", "C"), ids)]
history.append(key, {"event": "user", "text": "B", "input_id": ids[1]})
history.append(key, {"event": "message", "text": "answer", "response_input_ids": ids})
for i in range(10):
history.append(key, {"event": "message", "kind": "tool_hint", "text": str(i)})
for text in ("one", "two", "three"):
history.append(key, {"event": "delta", "text": text})
history.append(key, {"event": "stream_end", "text": "onetwothree"})
history.append(key, {"event": "turn_end"})
def loader():
return messages
index = history.prompts(key, session_messages_loader=loader)
stats = TranscriptReplayStats()
full = history.build(key, limit=10, session_messages_loader=loader, stats=stats)
assert stats.compacted_delta_records == 3
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 8)
truncated_stats = TranscriptReplayStats()
truncated = history.build(key, limit=10, session_messages_loader=loader, stats=truncated_stats)
assert truncated["page"]["truncated_oversized_turn"]
assert truncated_stats.compacted_delta_records == 3
expected_ids = [prompt["id"] for prompt in index]
assert [prompt["inputId"] for prompt in index] == ids
for page in (full, truncated):
users = [event for event in page["events"] if event["event"] == "user_message"]
assert [event["text"] for event in users] == ["A", "B", "C"]
assert [event["projection_id"] for event in users] == expected_ids
+109 -19
View File
@@ -89,6 +89,64 @@ async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(
_stop_gateway(process)
# Test-only injection: report locations without task names, frame data or source.
_TASK_DIAGNOSTICS = """
import asyncio, os, signal, sys
if sys.platform.startswith('linux') and os.name == 'posix':
original_run = asyncio.run
def diagnostic_run(coro, *args, **kwargs):
async def wrapped():
loop = asyncio.get_running_loop()
def dump_tasks():
with open(os.environ['SMOKE_TASK_DIAGNOSTICS'], 'w', encoding='utf-8') as output:
print('Gateway async task locations:', file=output)
for number, task in enumerate(asyncio.all_tasks(loop), 1):
for frame in task.get_stack():
code = frame.f_code
print(f'{number} {os.path.basename(code.co_filename)} {code.co_name} {frame.f_lineno}', file=output)
print('Gateway async task locations end', file=output)
loop.add_signal_handler(signal.SIGUSR1, dump_tasks)
return await coro
return original_run(wrapped(), *args, **kwargs)
asyncio.run = diagnostic_run
"""
async def _stop_inline_gateway(process: subprocess.Popen[bytes], *, diagnostics: Path, timeout: float = 30) -> None:
if process.poll() is not None:
return
if sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
else:
process.terminate()
try:
await asyncio.to_thread(process.wait, timeout=timeout)
except subprocess.TimeoutExpired:
try:
if sys.platform.startswith("linux") and os.name == "posix":
try:
process.send_signal(signal.SIGUSR1)
await asyncio.to_thread(process.wait, timeout=1)
except (ProcessLookupError, subprocess.TimeoutExpired):
pass
finally:
try:
process.kill()
except ProcessLookupError:
pass
finally:
await asyncio.to_thread(process.wait, timeout=10)
if diagnostics.exists():
print(diagnostics.read_text(encoding="utf-8"))
stacks = diagnostics.with_name("gateway-stacks.log")
if stacks.exists():
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
stacks.read_text(encoding="utf-8"))
print("Gateway shutdown stack locations:", frames[-80:])
raise
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
@@ -583,7 +641,7 @@ async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during
config = json.loads(config_path.read_text(encoding="utf-8"))
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
config_path.write_text(json.dumps(config), encoding="utf-8")
launcher = """
launcher = _TASK_DIAGNOSTICS + """
import asyncio, faulthandler, httpx, sys
from pathlib import Path
from nanobot.session.state import SessionState
@@ -615,6 +673,8 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
diagnostics = tmp_path / "gateway-tasks.log"
env["SMOKE_TASK_DIAGNOSTICS"] = str(diagnostics)
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
process = None
try:
@@ -717,23 +777,53 @@ with Path(config).with_name('gateway-stacks.log').open('w') as stacks:
release_close.set()
release_checkpoint.set()
try:
if process is not None and process.poll() is None:
if sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
else:
process.terminate()
try:
# Keep the test model/barrier server live while its client exits.
await asyncio.to_thread(process.wait, timeout=30)
except subprocess.TimeoutExpired:
process.kill()
await asyncio.to_thread(process.wait, timeout=10)
stacks = tmp_path / "gateway-stacks.log"
if stacks.exists():
frames = re.findall(r'File "[^"\n]*[/\\]([^/\\"\n]+)", line (\d+) in (\w+)',
stacks.read_text(encoding="utf-8"))
print("Gateway shutdown stack locations:", frames[-80:])
raise
if process is not None:
# Keep the model/barrier server live while its client exits.
await _stop_inline_gateway(process, diagnostics=diagnostics)
finally:
await server.cleanup()
@pytest.mark.skipif(not (sys.platform.startswith("linux") and os.name == "posix"), reason="Linux signals only")
@pytest.mark.asyncio
async def test_inline_gateway_timeout_dumps_tasks_and_reaps(tmp_path: Path, capsys: pytest.CaptureFixture) -> None:
(tmp_path / "gateway-stacks.log").write_text(
'Thread secret\n File "/private/path/gateway.py", line 42 in blocked\n secret source\n'
)
log_path = tmp_path / "diagnostic.log"
diagnostics = tmp_path / "tasks.log"
script = _TASK_DIAGNOSTICS + """
async def blocked():
secret_variable = 'must-not-appear-in-diagnostics'
await asyncio.Event().wait()
async def main():
signal.signal(signal.SIGTERM, signal.SIG_IGN)
asyncio.create_task(blocked(), name='private-task-name')
print('ready', flush=True)
await asyncio.Event().wait()
asyncio.run(main())
"""
with log_path.open("wb") as log:
process = subprocess.Popen([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT,
env={**os.environ, "SMOKE_TASK_DIAGNOSTICS": str(diagnostics)})
try:
deadline = time.monotonic() + 5
while "ready" not in log_path.read_text() and time.monotonic() < deadline:
await asyncio.sleep(0.01)
assert "ready" in log_path.read_text()
with pytest.raises(subprocess.TimeoutExpired):
await _stop_inline_gateway(process, diagnostics=diagnostics, timeout=0.1)
assert process.returncode is not None
captured = capsys.readouterr().out
assert "('gateway.py', '42', 'blocked')" in captured
assert "/private/path" not in captured
assert "secret source" not in captured
output = diagnostics.read_text()
assert "Gateway async task locations end" in output
assert "<string> blocked " in output
assert "private-task-name" not in output
assert "must-not-appear-in-diagnostics" not in output
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=10)
+90 -4
View File
@@ -13,16 +13,21 @@ from nanobot.webui.client_contract import webui_contract
from nanobot.webui.gateway_services import build_gateway_services
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch):
@pytest.mark.parametrize("identified", [False, True])
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch, identified):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:navigation"
for i in range(120):
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}"})
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}"})
input_identity = {"input_id": f"user:t{i}"} if identified else {}
response_identity = {"response_input_ids": [f"user:t{i}"]} if identified else {}
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}", **input_identity})
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}", **response_identity})
history.append(key, {"event": "turn_end", "chat_id": "navigation", "turn_id": f"t{i}"})
with monkeypatch.context() as patch:
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("page scanned full history")))
latest = history.build(key, limit=3)
index = history.prompts(key)
assert len(index) == 120
latest = history.build(key, limit=3)
assert len(latest["events"]) < len(index)
target = index[42]
stats = transcript.TranscriptReplayStats()
@@ -148,6 +153,64 @@ def test_recovered_prompt_identity_time_and_cursor_survive_pages(history, tmp_pa
assert history.prompts(key, session_messages_loader=loader) == index
@pytest.mark.parametrize("second_recorded", [True, False])
@pytest.mark.parametrize("grouped", [True, False])
def test_cross_session_inputs_are_reconciled_by_identity_across_turns(
history, tmp_path, monkeypatch, second_recorded, grouped,
):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:cross-session-replay"
provenance = [
{"message_id": f"message-{i}", "session": {"id": "handle_" + "1" * 32, "name": "luma"}}
for i in range(2)
]
input_ids = [f"session-message:{source['message_id']}" for source in provenance]
messages = [
{"role": "user", "content": "original question", "input_id": "user:original"},
{"role": "assistant", "content": "original answer"},
]
history.append(key, {"event": "user", "text": "original question", "input_id": "user:original"})
for i, source in enumerate(provenance):
messages.append({"role": "user", "content": "same message", "session_message": source, "input_id": input_ids[i]})
if not grouped or i == 1:
messages.append({"role": "assistant", "content": f"answer {i}"})
if i == 0 or second_recorded:
history.append(key, {"event": "user", "text": "same message", "session_message": source, "input_id": input_ids[i]})
history.append(key, {"event": "message", "text": "original answer", "response_input_ids": ["user:original"]})
assert [prompt["answerPreview"] for prompt in history.prompts(key)] == ["original answer"] + [""] * (2 if second_recorded else 1)
history.append(key, {"event": "turn_end"})
for i in ([1] if grouped else range(2)):
history.append(key, {"event": "message", "text": f"answer {i}", "response_input_ids": input_ids if grouped else [input_ids[i]]})
history.append(key, {"event": "turn_end"})
def loader():
assert not second_recorded, "complete display history must not load model history"
return messages
with monkeypatch.context() as patch:
if second_recorded:
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("page scanned full history")))
latest = history.build(key, limit=1, session_messages_loader=loader)
assert [event["text"] for event in latest["events"] if event["event"] == "user_message"] == (
[] if second_recorded else ["same message"]
)
page = history.build(key, limit=10, session_messages_loader=loader)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert [user["text"] for user in users] == ["original question", "same message", "same message"]
assert [user["provenance"]["session_message"]["message_id"] for user in users[1:]] == [
"message-0", "message-1",
]
prompts = history.prompts(key, session_messages_loader=loader)
assert [prompt["id"] for prompt in prompts] == [user["projection_id"] for user in users]
assert [prompt["answerPreview"] for prompt in prompts] == ["original answer", "answer 1" if grouped else "answer 0", "answer 1"]
assert [prompt["inputId"] for prompt in prompts] == ["user:original", *input_ids]
revision = history.revision(key)
history.append(key, {"event": "user", "text": "same message", "session_message": provenance[0], "input_id": input_ids[0]})
assert history.revision(key) == revision
assert history.build(key, limit=10, session_messages_loader=loader) == page
assert history.build(key, limit=1, session_messages_loader=loader) == latest
@pytest.mark.asyncio
async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(history, tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
@@ -331,3 +394,26 @@ def test_indexed_backfill_preserves_unique_in_suffix_matching(history, tmp_path,
assert [user["text"] for user in users] == (["question 2"] if with_anchor else [])
if with_anchor:
assert users[0]["projection_id"] == prompts[-1]["id"]
def test_recover_multiple_missing_inputs_for_one_answer_across_pages(history, tmp_path, monkeypatch):
"""A grouped answer can stand for multiple inputs absent from display history."""
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:missing-grouped-inputs"
ids = ["session-message:first", "session-message:second"]
messages = [
{"role": "user", "content": "first", "input_id": ids[0]},
{"role": "user", "content": "second", "input_id": ids[1]},
{"role": "assistant", "content": "shared answer"},
]
history.append(key, {"event": "message", "text": "shared answer", "response_input_ids": ids})
history.append(key, {"event": "turn_end"})
def loader():
return messages
page = history.build(key, limit=1, session_messages_loader=loader)
users = [event for event in page["events"] if event["event"] == "user_message"]
assert [event["text"] for event in users] == ["first", "second"]
prompts = history.prompts(key, session_messages_loader=loader)
assert [prompt["inputId"] for prompt in prompts] == ids
assert [prompt["id"] for prompt in prompts] == [event["projection_id"] for event in users]
+13 -11
View File
@@ -8,7 +8,7 @@ test.use({ launchOptions: {
test("lets native autoscroll leave the live tail and reverse after returning", async ({ page }) => {
// A real scrolling control catches browser configurations without native autoscroll.
await page.setContent('<div id="control" style="height:600px;overflow:auto"><div style="height:5000px">Autoscroll control</div></div>');
await page.mouse.click(200, 200, { button: "middle" });
await page.locator("#control").click({ button: "middle", position: { x: 200, y: 200 } });
await page.mouse.move(200, 300);
await expect.poll(() => page.locator("#control").evaluate((node) => node.scrollTop)).toBeGreaterThan(100);
await page.keyboard.press("Escape");
@@ -16,24 +16,26 @@ test("lets native autoscroll leave the live tail and reverse after returning", a
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
await page.goto("/browser/fixture.html?case=history-boundary&local=1");
const body = page.getByTestId("thread-message-region");
await expect(body.getByText("Cached message 279", { exact: true })).toBeVisible();
const bottom = await body.evaluate((node) => node.scrollHeight - node.clientHeight);
expect(bottom).toBeGreaterThan(1_000);
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeGreaterThan(bottom - 1);
const bounds = await body.getByText("Cached message 279", { exact: true }).boundingBox();
// The plain-text fallback is replaced when the lazy Markdown renderer loads.
const tail = body.locator(".markdown-content").getByText("Cached message 279", { exact: true });
await expect(tail).toBeVisible();
const distanceFromBottom = () => body.evaluate((node) => node.scrollHeight - node.clientHeight - node.scrollTop);
expect(await body.evaluate((node) => node.scrollHeight - node.clientHeight)).toBeGreaterThan(1_000);
await expect.poll(distanceFromBottom).toBeLessThan(1);
await tail.click({ button: "middle" });
const bounds = await tail.boundingBox();
expect(bounds).not.toBeNull();
const x = bounds!.x + bounds!.width / 2;
const y = bounds!.y + bounds!.height / 2;
await page.mouse.click(x, y, { button: "middle" });
await page.mouse.move(x, y - 100);
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeLessThan(bottom - 150);
await expect.poll(distanceFromBottom).toBeGreaterThan(150);
await page.mouse.move(x, y + 100);
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeGreaterThan(bottom - 1);
await expect.poll(distanceFromBottom).toBeLessThan(1);
await page.mouse.move(x, y - 100);
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeLessThan(bottom - 150);
await expect.poll(distanceFromBottom).toBeGreaterThan(150);
await page.keyboard.press("Escape");
await expect(page.getByRole("button", { name: "Scroll to bottom" })).toBeVisible();
await page.getByRole("button", { name: "Scroll to bottom" }).click();
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeGreaterThan(bottom - 1);
await expect.poll(distanceFromBottom).toBeLessThan(1);
});
@@ -2,6 +2,7 @@ import type { UIMessage } from "@/lib/types";
export interface PromptAnchor {
answerPreview: string;
inputId?: string;
id: string;
turnId?: string;
label: string;
@@ -12,11 +13,20 @@ export interface PromptAnchor {
}
export function userPromptAnchors(messages: UIMessage[]): PromptAnchor[] {
const answers = new Map<string, string>();
for (const message of messages) {
if (message.role !== "assistant") continue;
const preview = truncatePreview(compactPreview(message.content), 240);
if (preview) for (const id of message.responseInputIds ?? []) {
if (!answers.has(id)) answers.set(id, preview);
}
}
let index = 0;
return messages.flatMap((message, messageIndex) => {
if (message.role !== "user") return [];
const anchor: PromptAnchor = {
answerPreview: nextAssistantPreview(messages, messageIndex),
answerPreview: message.inputId ? answers.get(message.inputId) ?? "" : nextAssistantPreview(messages, messageIndex),
inputId: message.inputId,
id: message.id,
...(message.turnId ? { turnId: message.turnId } : {}),
label: promptLabel(message.content, index),
+9 -66
View File
@@ -41,7 +41,7 @@ import type {
} from "@/lib/types";
type PendingStreamEvent =
| { kind: "delta"; text: string; turn: UIMessageTurnFields; streamId?: string; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"] }
| { kind: "delta"; text: string; turn: UIMessageTurnFields; streamId?: string; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"]; responseInputIds?: string[] }
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields; streamId?: string };
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
@@ -107,29 +107,6 @@ function transitionTurnDelivery(
return changed ? next : messages;
}
function appendProjectedSessionInput(
messages: UIMessage[],
event: Extract<InboundEvent, { event: "user_message" }>,
): UIMessage[] {
const sessionMessage = event.provenance?.session_message;
const messageId = sessionMessage?.message_id?.trim();
if (!sessionMessage || !messageId) return messages;
if (messages.some((message) => message.sessionMessage?.message_id === messageId)) return messages;
const row: UIMessage = {
id: `session-message:${messageId}`,
role: "user",
content: event.text,
createdAt: typeof event.created_at_ms === "number"
&& Number.isFinite(event.created_at_ms)
? event.created_at_ms
: Date.now(),
sessionMessage,
...turnFieldsFromEvent(event, "user"),
};
return [...messages, row];
}
function createTranscript(messages: UIMessage[], saved: ThreadTranscriptSnapshot | undefined, historyKey: string | null) {
const owner = new ThreadTranscript(messages, saved);
// The first paint must not enter the welcome layout while history is pending.
@@ -343,7 +320,8 @@ export function useNanobotStream(
|| nextEvent.streamId !== event.streamId
|| (nextEvent.kind === "delta" && event.kind === "delta"
&& (nextEvent.source !== event.source
|| JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources)))) break;
|| JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources)
|| JSON.stringify(nextEvent.responseInputIds) !== JSON.stringify(event.responseInputIds)))) break;
chunks.push(nextEvent.text);
if (nextEvent.turn.turnSeq !== undefined) members.push(nextEvent.turn.turnSeq);
turn = { ...turn, ...nextEvent.turn };
@@ -360,6 +338,8 @@ export function useNanobotStream(
turn_seq: turn.turnSeq,
source: event.source,
response_sources: event.responseSources,
response_input_ids: event.responseInputIds,
stream_id: event.streamId,
}
: {
event: "reasoning_delta",
@@ -679,47 +659,8 @@ export function useNanobotStream(
return;
}
if (ev.event === "user_message") {
if (ev.provenance?.session_message) {
flushPendingStreamEvents();
closeActiveAssistantStream();
clearActivitySegment();
setMessages((prev) => {
const next = appendProjectedSessionInput(prev, ev);
if (next !== prev) transcriptRef.current.registerInput(next[next.length - 1]);
return next;
});
return;
}
setMessages((prev) => {
if (ev.turn_id && prev.some((message) => (
message.role === "user" && message.turnId === ev.turn_id
))) return ev.media_urls?.length ? prev.map((message) => (
message.role === "user" && message.turnId === ev.turn_id
? { ...message, media: ev.media_urls }
: message
)) : prev;
const row: UIMessage = {
id: crypto.randomUUID(),
role: "user",
content: ev.text,
...(ev.turn_id ? { turnId: ev.turn_id } : {}),
turnPhase: "user",
turnSeq: 0,
deliveryStatus: "accepted",
createdAt: typeof ev.created_at_ms === "number"
&& Number.isFinite(ev.created_at_ms)
? ev.created_at_ms
: Date.now(),
...(ev.media_urls?.length ? { media: ev.media_urls } : {}),
...(ev.cli_apps?.length ? { cliApps: ev.cli_apps } : {}),
...(ev.mcp_presets?.length ? { mcpPresets: ev.mcp_presets } : {}),
...(ev.session_mentions?.length
? { sessionMentions: ev.session_mentions }
: {}),
};
transcriptRef.current.registerInput(row);
return [...prev, row];
});
flushPendingStreamEvents();
applyProjectionEvent(ev);
return;
}
if (ev.event === "model_request") {
@@ -754,6 +695,7 @@ export function useNanobotStream(
streamId: ev.stream_id,
source: ev.source,
responseSources: ev.response_sources,
responseInputIds: ev.response_input_ids,
});
schedulePendingStreamFlush();
return;
@@ -1004,6 +946,7 @@ export function useNanobotStream(
...base,
{
id: userMessageId,
inputId: `user:${turnId}`,
role: "user" as const,
content: outboundContent,
turnId,
+11 -5
View File
@@ -99,34 +99,40 @@ export function usePromptHistory(key: string | null, version: number, messages:
const indexed = useMemo(() => {
const ids = new Set<string>();
const inputIds = new Set<string>();
const turns = new Map<string, PromptAnchor | null>();
for (const prompt of index?.prompts ?? []) {
ids.add(prompt.id);
if (prompt.inputId) inputIds.add(prompt.inputId);
if (prompt.turnId) turns.set(prompt.turnId, turns.has(prompt.turnId) ? null : prompt);
}
return { ids, turns };
return { ids, inputIds, turns };
}, [index]);
const localCache = useRef<{ index: typeof index; users: UIMessage[]; prompts: PromptAnchor[] }>();
const localCache = useRef<{ index: typeof index; users: UIMessage[]; responses: string; prompts: PromptAnchor[] }>();
const prompts = useMemo(() => {
if (!enabled) return userPromptAnchors(messages);
if (!currentScope || index?.key !== key) return [];
// Live rows can still have optimistic render ids after admission. Match the
// host's unambiguous original transport id and content, not text alone.
const users = messages.filter((message) => {
if (message.role !== "user" || indexed.ids.has(message.id)) return false;
if (message.role !== "user" || indexed.ids.has(message.id)
|| (message.inputId && indexed.inputIds.has(message.inputId))) return false;
const admitted = message.turnId ? indexed.turns.get(message.turnId) : null;
return !admitted || admitted.preview !== message.content.trim().slice(0, 320);
});
if (!users.length) return index.prompts;
// Refresh consumed-input previews at response boundaries, not on every token.
const responses = JSON.stringify(messages.filter((message) => message.responseInputIds !== undefined)
.map((message) => [message.id, message.responseInputIds, message.isStreaming ? null : message.content.slice(0, 240)]));
const cached = localCache.current;
if (cached?.index === index && users.length === cached.users.length
if (cached?.index === index && cached.responses === responses && users.length === cached.users.length
&& users.every((user, position) => user === cached.users[position])) return cached.prompts;
const localIds = new Set(users.map((message) => message.id));
const local = userPromptAnchors(messages).filter((prompt) => localIds.has(prompt.id));
// Directory order is logical admission order. Unknown legacy times are zero,
// not a reason to move an old prompt ahead of its preceding inputs.
const merged = [...index.prompts, ...local].map((prompt, position) => ({ ...prompt, index: position }));
localCache.current = { index, users, prompts: merged };
localCache.current = { index, users, responses, prompts: merged };
return merged;
}, [currentScope, enabled, index, indexed, key, messages]);
+5 -1
View File
@@ -284,6 +284,9 @@ function hasValidProjectionMetadata(value: Record<string, unknown>): boolean {
"user", "reasoning", "activity", "answer", "complete",
].includes(String(value.turn_phase)))
&& (value.turn_seq === undefined || typeof value.turn_seq === "number")
&& (value.input_id === undefined || typeof value.input_id === "string")
&& (value.response_input_ids === undefined || (Array.isArray(value.response_input_ids)
&& value.response_input_ids.every((id: unknown) => typeof id === "string")))
&& (
value.response_sources === undefined
|| (isRecordArray(value.response_sources) && value.response_sources.every((source) => (
@@ -536,10 +539,11 @@ export async function fetchPromptIndex(token: string, key: string, signal: Abort
const prompts = body.prompts.map((item: unknown) => {
if (!isRecord(item) || typeof item.id !== "string" || typeof item.preview !== "string"
|| typeof item.answerPreview !== "string" || typeof item.cursor !== "string" || typeof item.turnId !== "string"
|| (item.inputId !== undefined && typeof item.inputId !== "string")
|| typeof item.createdAt !== "number" || !Number.isFinite(item.createdAt)) {
throw new Error("Invalid prompt summary");
}
return { id: item.id, preview: item.preview, answerPreview: item.answerPreview,
return { id: item.id, inputId: item.inputId, preview: item.preview, answerPreview: item.answerPreview,
cursor: item.cursor, createdAt: item.createdAt, turnId: item.turnId };
});
return { prompts: [...(cached?.prompts.slice(0, replaceFrom) ?? []), ...prompts],
+40 -17
View File
@@ -581,6 +581,7 @@ function appendAnswerText(
...(event.stream_id ? { streamId: event.stream_id } : {}),
...(event.source ? { source: event.source } : {}),
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}),
};
state.closedAssistantIds.delete(merged.id);
state.activeAssistantId = merged.id;
@@ -896,28 +897,46 @@ export function projectThreadEvent(
}
if (event.event === "user_message") {
const sessionMessageId = event.provenance?.session_message?.message_id?.trim();
if (event.provenance?.session_message) {
const messageId = event.provenance.session_message.message_id?.trim();
if (!messageId || state.messages.some(
(message) => message.sessionMessage?.message_id === messageId,
if (!sessionMessageId || state.messages.some(
(message) => message.sessionMessage?.message_id === sessionMessageId,
)) return state;
} else if (event.turn_id && state.messages.some(
(message) => message.role === "user" && message.turnId === event.turn_id,
)) return state;
if (state.activeAssistantId) {
state.messages = state.messages.map((message) => (
message.id === state.activeAssistantId ? { ...message, isStreaming: false } : message
));
} else if (event.turn_id) {
const existing = state.messages.findIndex((message) => message.role === "user" && message.turnId === event.turn_id);
if (existing >= 0) {
if (!options.persisted && event.media_urls?.length) {
const message = state.messages[existing];
const media = event.media_urls.map((item) => toMediaAttachment(item));
state.messages = replaceMessageAt(state.messages, existing, {
...message,
media,
images: media.every((item) => item.kind === "image")
? media.map(({ url, name }) => ({ url, name })) : undefined,
});
options.effects?.bodyWrites.add(message.id);
}
return state;
}
}
// Live input admission does not end the answer currently being generated.
// Historical records retain their existing implicit segment boundaries.
if (options.persisted) {
if (state.activeAssistantId) {
state.messages = state.messages.map((message) => (
message.id === state.activeAssistantId ? { ...message, isStreaming: false } : message
));
}
state.messages = closeReasoningStream(state.messages);
Object.assign(state, resetThreadProjectionCursor(state, state.messages));
} else if (sessionMessageId) {
Object.assign(state, clearThreadProjectionActivity(state));
}
state.messages = closeReasoningStream(
state.messages,
options.persisted ? undefined : options.now,
);
Object.assign(state, resetThreadProjectionCursor(state, state.messages));
const media = event.media_urls?.map((item) => toMediaAttachment(item));
const turn = turnFieldsFromEvent(event, "user");
const row: UIMessage = {
id: projectionMessageId(event, options),
id: !options.persisted && sessionMessageId ? `session-message:${sessionMessageId}` : projectionMessageId(event, options),
inputId: event.input_id,
role: "user",
content: event.text,
createdAt: projectionCreatedAt(event, options),
@@ -985,11 +1004,13 @@ export function projectThreadEvent(
...(event.stream_id ? { streamId: event.stream_id } : {}),
...(event.source ? { source: event.source } : {}),
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}),
createdAt: projectionCreatedAt(event, options),
}];
options.effects?.bodyWrites.add(id);
targetIndex = state.messages.length - 1;
} else if (targetIndex !== null && (typeof text === "string" || event.source || event.response_sources !== undefined)) {
} else if (targetIndex !== null && (typeof text === "string" || event.source
|| event.response_sources !== undefined || event.response_input_ids !== undefined)) {
const target = state.messages[targetIndex];
state.messages = replaceMessageAt(state.messages, targetIndex, {
...target,
@@ -998,6 +1019,7 @@ export function projectThreadEvent(
...(event.stream_id ? { streamId: event.stream_id } : {}),
...(event.source ? { source: event.source } : {}),
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}),
});
if (typeof text === "string") options.effects?.bodyWrites.add(target.id);
}
@@ -1101,6 +1123,7 @@ export function projectThreadEvent(
...(latencyMs !== undefined ? { latencyMs } : {}),
...(event.source ? { source: event.source } : {}),
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}),
...positionedTurnFields(
options.sideChannel ? undefined : state.messages.find((message) => message.id === state.activeAssistantId),
turnFieldsForProjection(state, event, "answer"),
+8 -1
View File
@@ -249,12 +249,18 @@ export class ThreadTranscript {
project(event: ThreadProjectionEvent, options: {
createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number;
}): UIMessage[] {
if (!options.persisted && event.event === "user_message" && !event.provenance?.session_message) {
event = { turn_seq: 0, ...event };
}
// Telemetry never contributes body sources, memberships, or admission barriers.
if (event.event === "model_request") {
this.projection = projectThreadEvent(this.projection, event, options);
return this.messages;
}
if (!options.persisted && this.represented(event)) return this.messages;
const updatesInputMedia = event.event === "user_message" && !event.provenance?.session_message
&& !!event.turn_id && !!event.media_urls?.length
&& this.messages.some((message) => message.role === "user" && message.turnId === event.turn_id);
if (!options.persisted && !updatesInputMedia && this.represented(event)) return this.messages;
if (!event.projection_id && (!event.turn_id || event.turn_seq === undefined)) {
event = { ...event, projection_id: options.createId() };
}
@@ -307,6 +313,7 @@ export class ThreadTranscript {
} else {
projection = projectThreadEvent(projection, event, { ...options, effects });
}
if (event.event === "user_message" && projection.messages === this.messages) return this.messages;
this.projection = projection;
const connected = new Set<Unit>();
const existing = this.bySource.get(source);
+9
View File
@@ -120,6 +120,10 @@ export interface UIMessage {
renderAs?: "text";
/** Invocation-time snapshots, never resolved from today's model presets. */
responseSources?: ResponseSource[];
/** Stable input identity, independent of its arrival or execution turn. */
inputId?: string;
/** Inputs actually consumed by this response. An empty list means no user input. */
responseInputIds?: string[];
kind?: MessageKind;
isStreaming?: boolean;
createdAt: number;
@@ -1544,6 +1548,7 @@ export type InboundEvent =
mcp_presets?: UIMcpPresetAttachment[];
session_mentions?: SessionMention[];
provenance?: { session_message?: UISessionMessage };
input_id?: string;
} & InboundTurnMetadata)
| ({
event: "message";
@@ -1564,6 +1569,7 @@ export type InboundEvent =
/** Lightweight provenance for proactive assistant messages. */
source?: UIMessageSource;
response_sources?: ResponseSource[];
response_input_ids?: string[];
/** Optional structured payload on progress frames (channel-specific). */
agent_ui?: AgentUIBlob;
} & InboundTurnMetadata)
@@ -1582,6 +1588,7 @@ export type InboundEvent =
/** Lightweight provenance for proactive streamed assistant messages. */
source?: UIMessageSource;
response_sources?: ResponseSource[];
response_input_ids?: string[];
} & InboundTurnMetadata)
| ({
event: "stream_end";
@@ -1591,6 +1598,7 @@ export type InboundEvent =
/** Lightweight provenance for proactive streamed assistant messages. */
source?: UIMessageSource;
response_sources?: ResponseSource[];
response_input_ids?: string[];
/** This answer segment ended, but the active agent turn will continue. */
resuming?: boolean;
/** The next answer segment continues this same assistant message. */
@@ -1766,6 +1774,7 @@ interface WebuiThreadPagePayload {
export interface PromptSummary {
id: string;
inputId?: string;
preview: string;
answerPreview: string;
createdAt: number;
+3 -2
View File
@@ -134,7 +134,7 @@ describe("webui API helpers", () => {
});
it("revalidates prompt summaries and replaces only the changed suffix", async () => {
const prompt = { id: "u1", preview: "question", answerPreview: "", cursor: "cursor", turnId: "t1", createdAt: 1 };
const prompt = { id: "u1", inputId: "user:t1", preview: "question", answerPreview: "", cursor: "cursor", turnId: "t1", createdAt: 1 };
const cached = { revision: "first", prompts: [prompt] };
const signal = new AbortController().signal;
vi.mocked(fetch).mockResolvedValueOnce({ status: 304 } as Response);
@@ -146,6 +146,7 @@ describe("webui API helpers", () => {
}) } as Response);
const appended = await fetchPromptIndex("tok", "websocket:chat-1", signal, cached);
expect(appended.prompts.map((item) => item.id)).toEqual(["u1", "u2"]);
expect(appended.prompts[1].inputId).toBe("user:t1");
expect(appended.prompts[0]).toBe(prompt);
vi.mocked(fetch).mockResolvedValueOnce({ ok: true, json: async () => ({ revision: "third", replaceFrom: 1, prompts: [] }) } as Response);
expect((await fetchPromptIndex("tok", "websocket:chat-1", signal, appended)).prompts).toEqual([prompt]);
@@ -259,7 +260,7 @@ describe("webui API helpers", () => {
[{ provider: "xai", model: "grok", preset: "snapshot", fallback: true }],
[{ provider: "xai", model: "grok", preset: "legacy snapshot" }],
])("accepts optional recorded response sources: %j", async (response_sources) => {
const event = { event: "stream_end", chat_id: "chat-1", text: "Reply", response_sources };
const event = { event: "stream_end", chat_id: "chat-1", text: "Reply", response_sources, response_input_ids: ["session-message:received"] };
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
@@ -167,14 +167,15 @@ describe("canonical thread event projection", () => {
expect(messages[0]).toMatchObject({ content: "Complete answer", projectionStartSeq: 1, turnSeq: 3 });
});
it.each(["message", "stream_end"] as const)("preserves recorded sources in %s replay", (event) => {
it.each(["message", "stream_end"] as const)("preserves recorded response metadata in %s replay", (event) => {
const source = { provider: "xai", model: "grok", preset: "saved backup", fallback: true };
const messages = projectThreadEvents([
{ event, chat_id: "chat", text: "Recovered", response_sources: [source] },
{ event, chat_id: "chat", text: "Recovered", response_sources: [source], response_input_ids: ["session-message:received"] },
{ event: "turn_end", chat_id: "chat" },
{ event: "message", chat_id: "chat", text: "Legacy response" },
]);
expect(messages[0].responseSources).toEqual([source]);
expect(messages[0].responseInputIds).toEqual(["session-message:received"]);
expect(messages[1].responseSources).toBeUndefined();
});
+12
View File
@@ -41,6 +41,18 @@ function receive(thread: ThreadTranscript, ...events: ThreadProjectionEvent[]):
}
describe("ThreadTranscript admission", () => {
it("updates a represented live input's final image URL without duplicating it", () => {
const thread = new ThreadTranscript();
const first: ThreadProjectionEvent = { ...at("upload", 1), event: "user_message", text: "look", starts_turn: true,
media_urls: [{ kind: "image", url: "data:image/png;base64,AAAA", name: "image.png" }] };
receive(thread, first);
receive(thread, { ...first, media_urls: [{ kind: "image", url: "/api/media/final", name: "image.png" }] });
expect(thread.messages).toHaveLength(1);
expect(thread.messages[0]).toMatchObject({ media: [{ url: "/api/media/final" }], images: [{ url: "/api/media/final" }] });
const restored = new ThreadTranscript([], thread.save());
expect(restored.messages[0].media?.[0].url).toBe("/api/media/final");
});
it("keeps the history boundary unknown through live delivery and a failed first read", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
+32 -4
View File
@@ -3,6 +3,7 @@ import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
import { useNanobotStream } from "@/hooks/useNanobotStream";
import { userPromptAnchors } from "@/components/thread/promptNavigation";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import { composerUsageSnapshots } from "@/lib/model-request";
@@ -2556,16 +2557,32 @@ describe("useNanobotStream", () => {
expect(result.current.runStartedAt).toBe(1_700_000_000);
});
it("projects a cross-session input with its public handle exactly once", () => {
it("keeps an existing answer stream open when an ordinary input arrives", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-live-input", EMPTY_MESSAGES),
{ wrapper: wrap(fake.client) });
act(() => {
fake.emit("chat-live-input", { event: "delta", chat_id: "chat-live-input", stream_id: "answer", text: "first" });
fake.emit("chat-live-input", { event: "user_message", chat_id: "chat-live-input", turn_id: "queued", text: "next", starts_turn: false });
fake.emit("chat-live-input", { event: "delta", chat_id: "chat-live-input", stream_id: "answer", text: " second" });
fake.emit("chat-live-input", { event: "stream_end", chat_id: "chat-live-input", stream_id: "answer", resuming: true });
});
expect(result.current.messages.filter((row) => row.role === "assistant").map((row) => row.content)).toEqual(["first second"]);
expect(result.current.messages.filter((row) => row.role === "user").map((row) => row.content)).toEqual(["next"]);
});
it("projects a cross-session input once without interrupting the answer being streamed", () => {
const fake = fakeClient();
const original: UIMessage[] = [{ id: "original", inputId: "user:original", role: "user", content: "original", createdAt: 1 }];
const { result } = renderHook(
() => useNanobotStream("chat-target", EMPTY_MESSAGES),
() => useNanobotStream("chat-target", original),
{ wrapper: wrap(fake.client) },
);
const event: InboundEvent = {
event: "user_message",
chat_id: "chat-target",
text: "Please review this.",
input_id: "session-message:message-1",
created_at_ms: 1_700_000_000_123,
starts_turn: false,
provenance: {
@@ -2580,18 +2597,29 @@ describe("useNanobotStream", () => {
};
act(() => {
fake.emit("chat-target", { event: "delta", chat_id: "chat-target", text: "Original",
stream_id: "original-answer", response_input_ids: ["user:original"] });
fake.emit("chat-target", event);
fake.emit("chat-target", event);
fake.emit("chat-target", { event: "delta", chat_id: "chat-target", text: " answer",
stream_id: "original-answer", response_input_ids: ["user:original"] });
fake.emit("chat-target", { event: "stream_end", chat_id: "chat-target", stream_id: "original-answer",
response_input_ids: ["user:original"], resuming: true });
});
expect(result.current.messages).toEqual([expect.objectContaining({
expect(userPromptAnchors(result.current.messages).map((prompt) => prompt.answerPreview)).toEqual(["Original answer", ""]);
expect(result.current.messages.filter((row) => row.role === "assistant")).toHaveLength(1);
expect(result.current.messages.filter((row) => row.sessionMessage)).toEqual([expect.objectContaining({
id: "session-message:message-1",
inputId: "session-message:message-1",
role: "user",
content: "Please review this.",
createdAt: 1_700_000_000_123,
sessionMessage: event.provenance?.session_message,
})]);
expect(result.current.isStreaming).toBe(true);
act(() => fake.emit("chat-target", { event: "message", chat_id: "chat-target", text: "Review answer",
response_input_ids: ["session-message:message-1"] }));
expect(userPromptAnchors(result.current.messages).map((prompt) => prompt.answerPreview)).toEqual(["Original answer", "Review answer"]);
});
it("marks only the optimistic turn named by a correlated rejection as failed", () => {
+28
View File
@@ -221,3 +221,31 @@ it("keeps the request operation with failures and retries", async () => {
act(() => result.current.cancel());
expect(result.current.operation).toBeNull();
});
it("associates live answers and merges the persisted directory by input ID across turns", async () => {
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [], revision: "empty" });
const users: UIMessage[] = [
{ id: "local-original", inputId: "user:original", role: "user", content: "same", createdAt: 1 },
{ id: "local-session", inputId: "session-message:received", role: "user", content: "same", createdAt: 2 },
];
const { result, rerender } = renderHook(({ messages, version }) => usePromptHistory("a", version, messages), {
wrapper: wrapper(), initialProps: { messages: users, version: 1 },
});
await waitFor(() => expect(result.current.prompts).toHaveLength(2));
const messages: UIMessage[] = [...users,
{ id: "original-answer", role: "assistant", content: "Original answer", createdAt: 3, responseInputIds: ["user:original"] },
];
rerender({ messages, version: 1 });
expect(result.current.prompts.map((prompt) => prompt.answerPreview)).toEqual(["Original answer", ""]);
messages.push({ id: "session-answer", role: "assistant", content: "Session answer", createdAt: 4,
responseInputIds: ["session-message:received"] });
rerender({ messages: [...messages], version: 1 });
expect(result.current.prompts.map((prompt) => prompt.answerPreview)).toEqual(["Original answer", "Session answer"]);
const persisted = result.current.prompts.map((prompt, index) => ({ ...prompt, id: `persisted-${index}`,
cursor: String(index), turnId: `execution-${index}` }));
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: persisted, revision: "persisted" });
rerender({ messages, version: 2 });
await waitFor(() => expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["persisted-0", "persisted-1"]));
expect(result.current.prompts.map((prompt) => prompt.answerPreview)).toEqual(["Original answer", "Session answer"]);
});