fix(session): prevent consumed follow-ups from replaying after restart (#6299)

* fix(session): atomically acknowledge consumed follow-ups

* refactor(webui): drop legacy follow-up replay compatibility
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-19 11:31:19 +08:00
1 parent 743d40bbba
commit 53e0edf709
17 files changed
+645 -215

No files matched your search

+26 -23
View File
@@ -46,6 +46,7 @@ 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_RUNTIME_CONTROL,
INBOUND_META_TURN_ID,
INBOUND_META_USER_SHELL,
RUNTIME_CONTROL_SESSION_DISCARD,
InboundMessage,
@@ -95,7 +96,6 @@ from nanobot.session.recovery import (
REQUEST_ORIGIN_METADATA_KEY,
RecoveryAdmission,
RequestOrigin,
acknowledge_pending_followups,
pending_followups,
request_origin_from_metadata,
restore_pending_interruption,
@@ -697,6 +697,15 @@ 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
return extra
async def _persist_user_message_early(
self,
msg: InboundMessage,
@@ -715,7 +724,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: dict[str, Any] = ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
extra = self._input_history_extra(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]
@@ -734,7 +743,7 @@ class AgentLoop:
self._mark_pending_user_turn(session)
followup_id = msg.metadata.get(PENDING_FOLLOWUP_ID_KEY)
if isinstance(followup_id, str) and followup_id:
acknowledge_pending_followups(session, [followup_id])
session.consumed_followup_ids |= {followup_id}
await self.sessions.state.prepare_input(session)
return True
return False
@@ -1104,7 +1113,10 @@ class AgentLoop:
content,
image_paths=image_paths,
)
row: dict[str, Any] = {"role": "user", "content": user_content}
row: dict[str, Any] = {
"role": "user", "content": user_content,
"_meta": self._input_history_extra(pending_msg),
}
if HIDDEN_HISTORY_META in pending_msg.metadata:
row[HIDDEN_HISTORY_META] = pending_msg.metadata[HIDDEN_HISTORY_META]
metadata_value = cast(object, pending_msg.metadata)
@@ -1146,9 +1158,7 @@ class AgentLoop:
blocks,
)
if runtime_marker is not None:
row["_meta"] = {
RUNTIME_CONTEXT_MESSAGE_META: runtime_marker,
}
row["_meta"][RUNTIME_CONTEXT_MESSAGE_META] = runtime_marker
if (
pending_msg.sender_id == "subagent"
and metadata.get("injected_event") == "subagent_result"
@@ -2481,18 +2491,7 @@ class AgentLoop:
session.commit_summary_checkpoint(summary_checkpoint.summary)
entry = dict(message)
followup_id_value = cast(object, entry.pop(PENDING_FOLLOWUP_ID_KEY, None))
followup_ids = (
[followup_id_value]
if isinstance(followup_id_value, str)
else [
followup_id
for followup_id in cast(list[object], followup_id_value)
if isinstance(followup_id, str)
]
if isinstance(followup_id_value, list)
else []
)
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(
@@ -2541,10 +2540,15 @@ class AgentLoop:
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":
saved_followup_ids.update(followup_id for followup_id in followup_ids if followup_id)
if role == "user" and isinstance(followup_id, str) and followup_id:
saved_followup_ids.add(followup_id)
if role == "assistant":
last_assistant_idx = len(session.messages) - 1
declared_tool_call_ids.update(
@@ -2561,8 +2565,7 @@ class AgentLoop:
session.commit_summary_checkpoint(summary_checkpoint.summary)
if turn_latency_ms is not None and last_assistant_idx is not None:
session.messages[last_assistant_idx]["latency_ms"] = int(turn_latency_ms)
if saved_followup_ids:
acknowledge_pending_followups(session, saved_followup_ids)
session.consumed_followup_ids |= saved_followup_ids
session.updated_at = datetime.now()
def _persist_subagent_followup(self, session: Session, msg: InboundMessage) -> bool:
+2
View File
@@ -149,6 +149,8 @@ class Session:
# Owner-private committed snapshot. Never mutate or expose its records as draft data.
_baseline: Session | None = field(default=None, repr=False, compare=False)
# Explicit draft command, committed with history against the latest owner journal.
consumed_followup_ids: frozenset[str] = field(default_factory=frozenset, repr=False, compare=False)
persisted: bool = field(default=False, repr=False, compare=False)
revision: int = field(default=0, repr=False, compare=False)
generation: str = field(default_factory=lambda: uuid4().hex, repr=False, compare=False)
+5
View File
@@ -88,6 +88,7 @@ def record_pending_followup(session: Session, message: InboundMessage) -> str |
"sender_id": message.sender_id,
"chat_id": message.chat_id,
"content": message.content,
"timestamp": message.timestamp.isoformat(),
"media": list(message.media or []),
"metadata": metadata,
}
@@ -129,12 +130,16 @@ def pending_followups(session: Session) -> list[InboundMessage]:
if isinstance(media_value, list)
else []
)
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()
messages.append(
InboundMessage(
channel="websocket",
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},
session_key_override=session.key,
+6 -8
View File
@@ -504,6 +504,8 @@ class SessionState:
setattr(draft, item.name, getattr(fresh, item.name))
def _apply_turn(self, draft: Session) -> tuple[Session, int]:
from nanobot.session.recovery import PENDING_FOLLOWUPS_KEY, acknowledge_pending_followups
baseline = draft._baseline # pyright: ignore[reportPrivateUsage]
if baseline is None:
raise ValueError("session changes require an owner-issued draft")
@@ -517,20 +519,15 @@ class SessionState:
):
raise SessionConflictError("session was reset")
for key in baseline.metadata.keys() | draft.metadata.keys():
if key == PENDING_FOLLOWUPS_KEY:
# queue_followup owns this journal; a draft may predate its inputs.
continue
missing = object()
before = baseline.metadata.get(key, missing)
after = draft.metadata.get(key, missing)
if before == after:
continue
existing = current.metadata.get(key, missing)
if key == "pending_user_followups":
old_records = cast(list[dict[str, Any]], before) if isinstance(before, list) else []
new_records = cast(list[dict[str, Any]], after) if isinstance(after, list) else []
removed_ids = {item["id"] for item in old_records} - {item["id"] for item in new_records}
from nanobot.session.recovery import acknowledge_pending_followups
acknowledge_pending_followups(current, removed_ids)
continue
if existing != before and existing != after:
raise SessionConflictError(f"turn metadata changed: {key}")
if after is missing:
@@ -554,6 +551,7 @@ class SessionState:
if existing != before and existing != after:
raise SessionConflictError(f"session {name} changed")
setattr(current, name, deepcopy(after))
acknowledge_pending_followups(current, draft.consumed_followup_ids)
current.policy = draft.policy
current.updated_at = max(current.updated_at, draft.updated_at)
return current, self._changed_start(before_messages, current.messages)
+194 -83
View File
@@ -22,6 +22,7 @@ from urllib.parse import unquote, urlparse
from loguru import logger
from nanobot.bus.events import INBOUND_META_TURN_ID
from nanobot.config.paths import get_webui_dir
from nanobot.runtime_context import public_history_message
from nanobot.session.automation_turns import is_automation_kind
@@ -282,6 +283,7 @@ class TranscriptReplayStats:
capped_by_bytes: bool = False
capped_by_records: bool = False
truncated_oversized_turn: bool = False
canonical_backfill_revision: str | None = None
def _record_json_line(record: dict[str, Any]) -> str:
@@ -1534,6 +1536,8 @@ def _is_legacy_raw_subagent_result(message: dict[str, Any]) -> bool:
def _session_user_event(
session_key: str,
message: dict[str, Any],
*,
canonical_position: int | None = None,
) -> dict[str, Any] | None:
if message.get("role") != "user":
return None
@@ -1549,7 +1553,7 @@ def _session_user_event(
mcp_presets = message.get("mcp_presets")
session_mentions = message.get("session_mentions")
chat_id = session_key.split(":", 1)[1] if ":" in session_key else session_key
return build_user_transcript_event(
event = build_user_transcript_event(
chat_id,
text,
media_paths=cast(list[Any], media) if isinstance(media, list) else None,
@@ -1559,6 +1563,27 @@ def _session_user_event(
cast(list[Any], session_mentions) if isinstance(session_mentions, list) else None
),
)
if event is None:
return None
timestamp = message.get("timestamp")
created_at_ms = None
if isinstance(timestamp, str):
try:
created_at_ms = _valid_created_at_ms(datetime.fromisoformat(timestamp).timestamp() * 1000)
except (ValueError, OverflowError, OSError):
pass
event["created_at_ms"] = created_at_ms if created_at_ms is not None else 0
provenance = normalize_session_message_ui_metadata(message.get("session_message"))
if provenance:
event["session_message"] = provenance
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
event["turn_phase"] = "user"
event[_WEBUI_REPLAY_IDENTITY_KEY] = f"input:{session_key}:{input_id}"
elif canonical_position is not None:
event[_WEBUI_REPLAY_IDENTITY_KEY] = f"canonical:{session_key}:message:{canonical_position}"
return event
def _assistant_text_signature(value: Any) -> str:
@@ -1617,11 +1642,11 @@ def _session_backfill_turns(
)
)
for message in session_messages:
for position, message in enumerate(session_messages):
role = message.get("role")
if role == "user":
flush()
current_user = _session_user_event(session_key, message)
current_user = _session_user_event(session_key, message, canonical_position=position)
assistant_records = []
continue
if role == "assistant" and current_user is not None:
@@ -1741,15 +1766,15 @@ def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]
def _find_unique_session_turn(
session_turns: list[_SessionBackfillTurn],
signature: tuple[str, ...],
session_signatures: list[str],
signature: str,
start: int,
) -> int | None:
if not signature:
return None
found: int | None = None
for index in range(start, len(session_turns)):
if session_turns[index].assistant_signature != signature:
for index in range(start, len(session_signatures)):
if session_signatures[index] != signature:
continue
if found is not None:
return None
@@ -1760,7 +1785,7 @@ def _find_unique_session_turn(
def _user_recovery_signature(event: dict[str, Any]) -> str:
fields = {
key: event[key]
for key in ("text", "media_paths", "cli_apps", "mcp_presets", "session_mentions")
for key in ("text", "media_paths", "cli_apps", "mcp_presets", "session_mentions", "session_message")
if key in event
}
return json.dumps(fields, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
@@ -1851,6 +1876,14 @@ 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)
and _transcript_turn_signature(turn)
for turn in _split_transcript_turns(lines)
)
def _with_backfilled_user(
records: list[dict[str, Any]],
user_event: dict[str, Any],
@@ -1861,33 +1894,6 @@ def _with_backfilled_user(
return records
def _needs_user_event_backfill(lines: list[dict[str, Any]]) -> bool:
for turn in _split_transcript_turns(lines):
if any(record.get("event") == "user" for record in turn):
continue
if _transcript_turn_signature(turn):
return True
return False
def _inject_missing_user_events(
lines: list[dict[str, Any]],
session_turns: list[_SessionBackfillTurn],
) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
session_cursor = 0
for turn in _split_transcript_turns(lines):
has_user = any(rec.get("event") == "user" for rec in turn)
signature = _transcript_turn_signature(turn)
match_index = _find_unique_session_turn(session_turns, signature, session_cursor)
if match_index is None:
out.extend(turn)
continue
out.extend(turn if has_user else _with_backfilled_user(turn, session_turns[match_index][0]))
session_cursor = match_index + 1
return out
def _format_tool_call_trace(call: Any) -> str | None:
if not call or not isinstance(call, dict):
return None
@@ -2534,20 +2540,29 @@ def build_webui_thread_response(
)
if not lines and active_turn_started_at is None:
return None
needs_user_backfill = _needs_user_event_backfill(lines)
needs_incomplete_recovery = _needs_incomplete_turn_recovery(lines)
if (
session_messages is None
and session_messages_loader is not None
and (needs_user_backfill or needs_incomplete_recovery)
):
session_messages = session_messages_loader()
if session_messages and (needs_user_backfill or needs_incomplete_recovery):
session_turns = _session_backfill_turns(session_key, session_messages)
if needs_user_backfill:
lines = _inject_missing_user_events(lines, session_turns)
if needs_incomplete_recovery:
lines = _recover_incomplete_turns(lines, session_turns)
view = None
if _needs_user_event_backfill(lines):
view = _build_prompt_view(
session_key, session_messages=session_messages,
session_messages_loader=session_messages_loader,
)
replay_stats.canonical_backfill_revision = view.canonical_revision
recovered_lines: list[dict[str, Any]] = []
selected_turns = _split_transcript_turns(lines)
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)
lines = recovered_lines
if _needs_incomplete_turn_recovery(lines):
session_turns = view.session_turns if view is not None else None
if session_turns is None:
if session_messages is None and session_messages_loader is not None:
session_messages = session_messages_loader()
session_turns = _session_backfill_turns(session_key, session_messages or [])
replay_stats.canonical_backfill_revision = _canonical_backfill_revision(session_turns)
lines = _recover_incomplete_turns(lines, session_turns)
lines = _ensure_replay_identities(lines)
payload: dict[str, Any] = {
"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION,
@@ -2589,14 +2604,61 @@ class PromptSummary(TypedDict):
turnId: str
class _BackfillCandidate(NamedTuple):
ordinal: int
signature: str
answer_preview: str
has_user: bool
class _ChunkPromptView(NamedTuple):
prompts: tuple[PromptSummary, ...]
candidates: tuple[_BackfillCandidate, ...]
class _PromptView(NamedTuple):
prompts: list[PromptSummary]
backfilled_users: dict[int, dict[str, Any]]
session_turns: list[_SessionBackfillTurn] | None
canonical_revision: str | None
def _assistant_signature_identity(signature: tuple[str, ...]) -> str:
if not signature:
return ""
return hashlib.sha256(json.dumps(signature, ensure_ascii=False).encode("utf-8")).hexdigest()
def _canonical_backfill_revision(turns: list[_SessionBackfillTurn]) -> str:
return hashlib.sha256(json.dumps(turns, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()[:32]
def webui_display_revision(revision: str | None, canonical_revision: str | None) -> str | None:
"""Bind recovered display validators to the canonical snapshot actually used."""
if revision is None or canonical_revision is None:
return revision
return hashlib.sha256(f"{revision}\0{canonical_revision}".encode("ascii")).hexdigest()[:32]
def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> PromptSummary:
return {
"id": _client_projection_event_id(record),
"preview": str(record.get("text") or "").strip()[:320],
"answerPreview": answer,
"createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0,
"cursor": _encode_page_cursor(ordinal),
"turnId": str(record.get("turn_id") or ""),
}
@lru_cache(maxsize=64)
def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: int) -> tuple[PromptSummary, ...]:
# Stored records use compact JSON. A normal chunk already fits the page byte
# budget, so do not serialize all answer/tool bodies again just to count them.
def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: int) -> _ChunkPromptView:
# Cache only navigation/recovery inputs, not full answer, trace or tool bodies
# for ordinary complete turns. Page selection still reads bounded chunks.
check_turn_bytes = identity[2] > _MAX_TRANSCRIPT_PAGE_BYTES
result: list[PromptSummary] = []
turns = _split_transcript_turns(_read_transcript_file(path))
for ordinal, raw_turn in enumerate(turns, start):
candidates: list[_BackfillCandidate] = []
for ordinal, raw_turn in enumerate(_split_transcript_turns(_read_transcript_file(path)), start):
turn, _ = _compact_completed_stream_deltas(raw_turn)
if len(turn) > _MAX_TRANSCRIPT_PAGE_RECORDS or (check_turn_bytes and _records_bytes(turn) > _MAX_TRANSCRIPT_PAGE_BYTES):
turn = _trim_oversized_turn(
@@ -2604,13 +2666,18 @@ def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: i
max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
)
records = _records_with_replay_identity(turn, turn_ordinal=ordinal)
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,
))
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 "")
# Match the client projector's user-message deduplication.
# Match the client projector's existing per-turn delivery deduplication.
provenance = normalize_session_message_ui_metadata(record.get("session_message"))
if provenance:
message_id = str(provenance["message_id"])
@@ -2629,20 +2696,18 @@ def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: i
answer = str(following.get("text") or "").strip()[:240]
if answer:
break
result.append({
"id": _client_projection_event_id(record),
"preview": str(record.get("text") or "").strip()[:320],
"answerPreview": answer,
"createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0,
"cursor": _encode_page_cursor(ordinal),
"turnId": turn_id,
})
return tuple(result)
result.append(_prompt_summary(record, ordinal, answer))
return _ChunkPromptView(tuple(result), tuple(candidates))
def build_prompt_index(session_key: str) -> list[PromptSummary]:
"""Read every prompt, without materializing full history or touching SQLite."""
result: list[PromptSummary] = []
def _build_prompt_view(
session_key: str,
*,
session_messages: list[dict[str, Any]] | None = None,
session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None,
) -> _PromptView:
raw_prompts: list[PromptSummary] = []
candidates: list[_BackfillCandidate] = []
start = 0
chunks = [
(_segment_file_path(session_key, entry["id"]), entry["turn_count"])
@@ -2654,9 +2719,50 @@ def build_prompt_index(session_key: str) -> list[PromptSummary]:
stat = path.stat()
except FileNotFoundError:
continue
result.extend(_chunk_prompt_summaries(path, (stat.st_ino, stat.st_mtime_ns, stat.st_size), start))
chunk = _chunk_prompt_summaries(path, (stat.st_ino, stat.st_mtime_ns, stat.st_size), start)
raw_prompts.extend(chunk.prompts)
candidates.extend(chunk.candidates)
start += count
return result
session_turns = None
canonical_revision = None
if any(not candidate.has_user and candidate.signature for candidate in candidates):
if session_messages is None and session_messages_loader is not None:
session_messages = session_messages_loader()
session_turns = _session_backfill_turns(session_key, session_messages or [])
canonical_revision = _canonical_backfill_revision(session_turns)
entries: list[tuple[int, PromptSummary, dict[str, Any] | None]] = [
(decode_transcript_cursor(prompt["cursor"]) or 0, prompt, None) for prompt in raw_prompts
]
session_cursor = 0
session_signatures = [_assistant_signature_identity(turn.assistant_signature) for turn in session_turns or []]
for candidate in candidates:
if not session_turns:
break
match = _find_unique_session_turn(session_signatures, candidate.signature, session_cursor)
if match is None:
continue
session_cursor = match + 1
if candidate.has_user:
continue
user = dict(session_turns[match].user_event)
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)
if user is not None:
backfilled_users[ordinal] = user
return _PromptView(prompts, backfilled_users, session_turns, canonical_revision)
def build_prompt_index(
session_key: str,
*,
session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None,
) -> list[PromptSummary]:
"""Read the display prompt directory; only missing-user turns load canonical history."""
return _build_prompt_view(session_key, session_messages_loader=session_messages_loader).prompts
# Short-lived response snapshots share the chunk summaries; they do not retain
@@ -2671,23 +2777,28 @@ class PromptIndexResponse(TypedDict):
revision: NotRequired[str | None]
def prompt_index_response(session_key: str, previous_revision: str | None) -> PromptIndexResponse:
def prompt_index_response(
session_key: str,
previous_revision: str | None,
*,
session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None,
) -> PromptIndexResponse:
path = webui_transcript_path(session_key)
revision = webui_transcript_revision(session_key)
transcript_revision = webui_transcript_revision(session_key)
view = _build_prompt_view(session_key, session_messages_loader=session_messages_loader)
revision = webui_display_revision(transcript_revision, view.canonical_revision)
current = tuple(view.prompts)
with _PROMPT_SNAPSHOT_LOCK:
previous = _PROMPT_SNAPSHOTS.get((path, previous_revision)) if previous_revision else None
current = _PROMPT_SNAPSHOTS.get((path, revision)) if revision else None
if current is None:
current = tuple(build_prompt_index(session_key))
# Do not label a read made across an append/rotation as one stable revision.
if revision != webui_transcript_revision(session_key):
return {"prompts": current, "replaceFrom": 0}
if revision:
with _PROMPT_SNAPSHOT_LOCK:
_PROMPT_SNAPSHOTS[path, revision] = current
_PROMPT_SNAPSHOTS.move_to_end((path, revision))
while len(_PROMPT_SNAPSHOTS) > 8:
_PROMPT_SNAPSHOTS.popitem(last=False)
# Do not label a read made across an append/rotation as one stable revision.
if transcript_revision != webui_transcript_revision(session_key):
return {"prompts": current, "replaceFrom": 0}
if revision:
with _PROMPT_SNAPSHOT_LOCK:
_PROMPT_SNAPSHOTS[path, revision] = current
_PROMPT_SNAPSHOTS.move_to_end((path, revision))
while len(_PROMPT_SNAPSHOTS) > 8:
_PROMPT_SNAPSHOTS.popitem(last=False)
replace_from = 0
if previous is not None:
for old, new in zip(previous, current):
+31 -32
View File
@@ -134,6 +134,7 @@ from nanobot.webui.transcript import (
build_session_thread_response,
build_webui_thread_response,
build_webui_trace_detail_response,
webui_display_revision,
webui_transcript_revision,
)
from nanobot.webui.workspace_browser import browse_workspace_directories
@@ -1041,8 +1042,21 @@ class GatewayHTTPHandler:
cleaned.append(row)
return {"sessions": cleaned}
def _read_session_messages(self, key: str) -> list[dict[str, Any]] | None:
if self.session_manager is None:
return None
session_data = self.session_manager.read_session_file(key)
raw_messages = session_data.get("messages") if isinstance(session_data, dict) else None
if not isinstance(raw_messages, list):
return None
return [
cast(dict[str, Any], message)
for message in cast(list[Any], raw_messages)
if isinstance(message, dict)
]
def _handle_prompt_index_get(self, request: WsRequest, key: str) -> Response:
from nanobot.webui.transcript import prompt_index_response, webui_transcript_revision
from nanobot.webui.transcript import prompt_index_response
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
@@ -1051,12 +1065,15 @@ class GatewayHTTPHandler:
return _http_error(400, "invalid session key")
if not _is_websocket_channel_session_key(decoded_key):
return _http_error(404, "session not found")
revision = webui_transcript_revision(decoded_key)
query = _parse_query(request.path)
data = prompt_index_response(
decoded_key, _query_first(query, "since"),
session_messages_loader=lambda: self._read_session_messages(decoded_key),
)
revision = data.get("revision")
etag = _quoted_etag(revision) if revision else None
if etag and _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag):
return _http_response(b"", status=304, extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)])
query = _parse_query(request.path)
data = prompt_index_response(decoded_key, _query_first(query, "since"))
headers = list(_NO_STORE_HEADERS)
response_revision = data.get("revision")
if response_revision:
@@ -1160,20 +1177,6 @@ class GatewayHTTPHandler:
diagnostics.session_hash = hashlib.sha256(decoded_key.encode("utf-8")).hexdigest()[:12]
scope = self.workspaces.scope_for_session_key(decoded_key)
def load_session_messages() -> list[dict[str, Any]] | None:
if self.session_manager is None:
return None
session_data = self.session_manager.read_session_file(decoded_key)
raw_messages = session_data.get("messages") if isinstance(session_data, dict) else None
if not isinstance(raw_messages, list):
return None
raw_session_messages = cast(list[Any], raw_messages)
return [
cast(dict[str, Any], raw_message)
for raw_message in raw_session_messages
if isinstance(raw_message, dict)
]
query = _parse_query(request.path)
raw_limit = _query_first(query, "limit")
limit: int | None = None
@@ -1226,17 +1229,8 @@ class GatewayHTTPHandler:
"workspace_scope": scope.payload(),
}
initial_revision = webui_transcript_revision(decoded_key, variant=revision_variant)
etag = _quoted_etag(initial_revision) if initial_revision is not None else None
if etag is not None and _etag_matches(
_case_insensitive_header(request.headers, "If-None-Match"),
etag,
):
return _http_response(
b"",
status=304,
extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)],
)
build_started = time.perf_counter()
replay_stats = diagnostics.transcript if diagnostics is not None else TranscriptReplayStats()
data = build_webui_thread_response(
decoded_key,
augment_user_media=self.media.augment_transcript_media,
@@ -1245,7 +1239,7 @@ class GatewayHTTPHandler:
text,
workspace_path=scope.project_path,
),
session_messages_loader=load_session_messages,
session_messages_loader=lambda: self._read_session_messages(decoded_key),
active_turn_started_at=active_turn_started_at,
active_turn_id=active_turn_id,
active_turn_transcript_persistence_failed=(
@@ -1255,7 +1249,7 @@ class GatewayHTTPHandler:
direction=direction,
before=before,
after=after,
stats=diagnostics.transcript if diagnostics is not None else None,
stats=replay_stats,
)
if diagnostics is not None:
diagnostics.build_ms = (time.perf_counter() - build_started) * 1000
@@ -1275,8 +1269,13 @@ class GatewayHTTPHandler:
final_revision = webui_transcript_revision(decoded_key, variant=revision_variant)
response_headers = list(_NO_STORE_HEADERS)
if final_revision is not None and final_revision == initial_revision:
data["revision"] = final_revision
response_headers.append(("ETag", _quoted_etag(final_revision)))
display_revision = webui_display_revision(final_revision, replay_stats.canonical_backfill_revision)
assert display_revision is not None
etag = _quoted_etag(display_revision)
response_headers.append(("ETag", etag))
if _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag):
return _http_response(b"", status=304, extra_headers=response_headers)
data["revision"] = display_revision
return _http_json_response(
data,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),