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