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

+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(