diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 7152f7d96..d92f1ffe5 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -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: diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 122a745ea..66d9708a8 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -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) diff --git a/nanobot/session/recovery.py b/nanobot/session/recovery.py index d069d7a01..36076ba13 100644 --- a/nanobot/session/recovery.py +++ b/nanobot/session/recovery.py @@ -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, diff --git a/nanobot/session/state.py b/nanobot/session/state.py index 1335465a5..d8e1219c5 100644 --- a/nanobot/session/state.py +++ b/nanobot/session/state.py @@ -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) diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index c280acdc3..90a1636de 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -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): diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 78afff9af..9cc80fb42 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -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"), diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py index 02e6db35e..c4d7b2104 100644 --- a/tests/agent/test_loop_save_turn.py +++ b/tests/agent/test_loop_save_turn.py @@ -205,31 +205,20 @@ async def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> async def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None: loop = _make_full_loop(tmp_path) - session = await loop.sessions.state.get("websocket:chat") - session.metadata[PENDING_FOLLOWUPS_KEY] = [ - { - "id": "followup-1", - "sender_id": "user", - "chat_id": "chat", - "content": "queued while busy", - "media": [], - "metadata": {}, - } - ] - - persisted = await loop._persist_user_message_early( - InboundMessage( - channel="websocket", - sender_id="user", - chat_id="chat", - content="queued while busy", - metadata={PENDING_FOLLOWUP_ID_KEY: "followup-1"}, - ), - session, + loop.provider.aclose = AsyncMock() + message = InboundMessage( + channel="websocket", sender_id="user", chat_id="chat", content="queued while busy", ) - - assert persisted is True - assert PENDING_FOLLOWUPS_KEY not in session.metadata + try: + identifier = await loop.sessions.state.queue_followup(message.session_key, message) + message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier + # Control: unlike mid-turn injection, this draft already sees the journal. + session = await loop.sessions.state.get(message.session_key) + assert await loop._persist_user_message_early(message, session) + assert PENDING_FOLLOWUPS_KEY not in session.metadata + assert PENDING_FOLLOWUPS_KEY not in (await loop.sessions.state.get(session.key)).metadata + finally: + await loop.aclose() async def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None: @@ -598,34 +587,6 @@ def test_save_turn_commits_summary_boundary_without_rewriting_raw_history() -> N ] -def test_save_turn_acknowledges_every_merged_recovery_followup() -> None: - """Persisting a merged injected row retires every durable follow-up ID.""" - loop = _mk_loop() - session = Session( - key="test:recovery-followups", - metadata={ - PENDING_FOLLOWUPS_KEY: [ - {"id": "first"}, - {"id": "second"}, - ] - }, - ) - - loop._save_turn( - session, - [ - { - "role": "user", - "content": "first\n\nsecond", - PENDING_FOLLOWUP_ID_KEY: ["first", "second"], - } - ], - skip=0, - ) - - assert PENDING_FOLLOWUPS_KEY not in session.metadata - - def test_save_turn_keeps_image_placeholder_and_runtime_context() -> None: loop = _mk_loop() session = Session(key="test:image") diff --git a/tests/session/test_followup_commit.py b/tests/session/test_followup_commit.py new file mode 100644 index 000000000..971a0fdd5 --- /dev/null +++ b/tests/session/test_followup_commit.py @@ -0,0 +1,172 @@ +"""Follow-up consumption commits against the owner, not an old turn snapshot.""" + +import sqlite3 +from datetime import datetime +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from nanobot.agent.context import TranscriptInput +from nanobot.agent.loop import AgentLoop +from nanobot.agent.tools.context import RequestContext +from nanobot.bus.events import INBOUND_META_TURN_ID, InboundMessage +from nanobot.bus.queue import MessageBus +from nanobot.providers.base import GenerationSettings, LLMResponse +from nanobot.runtime_context import public_history_message +from nanobot.session.manager import SessionManager +from nanobot.session.recovery import PENDING_FOLLOWUP_ID_KEY, pending_followups +from nanobot.webui.recovery import RecoveryCoordinator + + +def _loop(sessions): + loop = AgentLoop.__new__(AgentLoop) + loop.sessions = sessions + return loop + + +def _input(text, turn_id): + return InboundMessage( + channel="websocket", sender_id="user", chat_id="chat", content=text, + timestamp=datetime(2026, 10, 18, 19, 0, 0), + metadata={INBOUND_META_TURN_ID: turn_id}, + ) + + +@pytest.mark.parametrize("count", [1, 2]) +@pytest.mark.parametrize("leave_unconsumed", [False, True]) +async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monkeypatch, count, leave_unconsumed): + monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui") + sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions") + state = sessions.state + try: + draft = await state.get("websocket:chat") + draft.add_message("user", "initial input") + await state.prepare_input(draft) + consumed = [] + for index in range(count): + message = _input(f"follow-up {index}", f"input-{index}") + consumed.append(await state.queue_followup(draft.key, message)) + await state.checkpoint_view(draft, {"phase": "final_response"}) + _loop(sessions)._save_turn(draft, [ + *[ + {"role": "user", "content": f"follow-up {index}", PENDING_FOLLOWUP_ID_KEY: identifier} + for index, identifier in enumerate(consumed) + ], + {"role": "assistant", "content": "completed answer"}, + ], skip=0) + if leave_unconsumed: + await state.queue_followup(draft.key, _input("arrived after model boundary", "late-input")) + await state.finish_turn(draft) + committed = await state.get(draft.key) + expected = ["arrived after model boundary"] if leave_unconsumed else [] + assert [item.content for item in pending_followups(committed)] == expected + assert [item["content"] for item in committed.messages] == [ + "initial input", *[f"follow-up {index}" for index in range(count)], "completed answer", + ] + finally: + await state.aclose() + + reopened = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions") + try: + bus = MessageBus() + await RecoveryCoordinator(reopened, bus).scan() + queued = [] + while not bus.inbound.empty(): + queued.append(bus.inbound.get_nowait().content) + assert queued == expected + assert (await reopened.state.get(draft.key)).messages == committed.messages + finally: + await reopened.state.aclose() + + +async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(tmp_path): + sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions") + state = sessions.state + try: + draft = await state.get("websocket:chat") + draft.add_message("user", "initial input") + await state.prepare_input(draft) + identifier = await state.queue_followup(draft.key, _input("consumed input", "follow-up")) + _loop(sessions)._save_turn(draft, [ + {"role": "user", "content": "consumed input", PENDING_FOLLOWUP_ID_KEY: identifier}, + {"role": "assistant", "content": "completed answer"}, + ], skip=0) + with sqlite3.connect(sessions._store.path) as db: + db.execute("""CREATE TRIGGER reject_ack BEFORE DELETE ON pending_inputs + BEGIN SELECT RAISE(ABORT, 'failed follow-up commit'); END""") + with pytest.raises(sqlite3.IntegrityError, match="failed follow-up commit"): + await state.finish_turn(draft) + # Both the durable snapshot and published cache remain at the pre-commit boundary. + for stored in (sessions.read_session_snapshot(draft.key), state.peek(draft.key)): + assert [row["content"] for row in stored.messages] == ["initial input"] + assert [item.content for item in pending_followups(stored)] == ["consumed input"] + with sqlite3.connect(sessions._store.path) as db: + db.execute("DROP TRIGGER reject_ack") + await state.finish_turn(draft) + committed = sessions.read_session_snapshot(draft.key) + assert [row["content"] for row in committed.messages] == [ + "initial input", "consumed input", "completed answer", + ] + assert pending_followups(committed) == [] + finally: + await state.aclose() + + +async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path): + sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions") + state = sessions.state + message = _input("queued input", "original-input") + try: + draft = await state.get(message.session_key) + await state.queue_followup(draft.key, message) + recovered = pending_followups(await state.get(draft.key))[0] + assert recovered.timestamp == message.timestamp + assert recovered.metadata[INBOUND_META_TURN_ID] == "original-input" + assert await _loop(sessions)._persist_user_message_early(recovered, draft) + row = (await state.get(draft.key)).messages[-1] + assert row["timestamp"] == message.timestamp.isoformat() + assert row[INBOUND_META_TURN_ID] == "original-input" + assert pending_followups(await state.get(draft.key)) == [] + finally: + await state.aclose() + + +async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path): + import asyncio + + provider = MagicMock(aclose=AsyncMock()) + provider.get_default_model.return_value = "test-model" + provider.generation = GenerationSettings() + provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="completed answer")) + loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path / "workspace", model="test-model") + loop.sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions") + try: + draft = await loop.sessions.state.get("websocket:chat") + draft.add_message("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) + identifier = await loop.sessions.state.queue_followup(draft.key, message) + message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier + queue.put_nowait(message) + runtime = loop.llm_runtime() + result = await loop._run_agent_loop( + TranscriptInput(history=draft.get_history(), current_message=None), + runtime=runtime, session=draft, pending_queue=queue, + request_context=RequestContext( + channel="websocket", chat_id="chat", session_key=draft.key, + turn_id="active-run", runtime=runtime, + ), + ) + loop._save_turn(draft, result.messages, skip=2) + await loop.sessions.state.finish_turn(draft) + stored = await loop.sessions.state.get(draft.key) + injected = [row for row in stored.messages if row.get("role") == "user"][1:] + assert [public_history_message(row)["content"] for row in injected] == ["intentionally identical text"] * 2 + assert [row[INBOUND_META_TURN_ID] for row in injected] == ["first-input", "second-input"] + assert [row["timestamp"] for row in injected] == ["2026-10-18T19:00:00"] * 2 + assert pending_followups(stored) == [] + provider.chat_stream_with_retry.assert_awaited_once() + finally: + await loop.aclose() diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index f060fa158..8c27a39e3 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -522,6 +522,32 @@ def test_latest_page_reads_active_chunk_once(tmp_path, monkeypatch) -> None: assert read_chunk_ids == ["active"] +def test_cold_complete_page_does_not_parse_unselected_transcript_files(tmp_path, monkeypatch) -> None: + key = "websocket:cold-bounded-page" + _write_segmented_turns(tmp_path, monkeypatch, key, "cold-bounded-page", 12) + original = transcript_module._read_transcript_file + reads: list[Path] = [] + + def track_read(path): + reads.append(path) + return original(path) + + def fail_if_loaded(): + raise AssertionError("complete pages must not load canonical history") + + monkeypatch.setattr(transcript_module, "_read_transcript_file", track_read) + latest = build_webui_thread_response(key, limit=1, session_messages_loader=fail_if_loaded) + + assert latest is not None + assert _message_contents(latest) == _numbered_turn_texts(12, 12) + assert reads == [transcript_module.webui_transcript_path(key)] + transcript_module.build_prompt_index(key, session_messages_loader=fail_if_loaded) + reads.clear() + warmed = build_webui_thread_response(key, limit=1, session_messages_loader=fail_if_loaded) + assert warmed == latest + assert reads == [transcript_module.webui_transcript_path(key)] + + def test_page_cursor_survives_active_rotation_after_latest_page( tmp_path, monkeypatch, diff --git a/tests/webui/test_prompt_index.py b/tests/webui/test_prompt_index.py index e9b4b2e94..7e7f6193c 100644 --- a/tests/webui/test_prompt_index.py +++ b/tests/webui/test_prompt_index.py @@ -9,6 +9,7 @@ from websockets.http11 import Request from nanobot.bus.queue import MessageBus from nanobot.channels.websocket.runtime import WebSocketConfig +from nanobot.session.manager import SessionManager from nanobot.webui import transcript from nanobot.webui.client_contract import webui_contract from nanobot.webui.gateway_services import build_gateway_services @@ -122,3 +123,83 @@ def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(tmp_pat assert transcript.prompt_index_response(key, replaced["revision"])["replaceFrom"] == 0 transcript.delete_webui_transcript(key) assert transcript.prompt_index_response(key, replaced["revision"])["prompts"] == () + + +@pytest.mark.parametrize("input_id", [None, "injected-guidance"]) +def test_recovered_prompt_identity_time_and_cursor_survive_pages(tmp_path, monkeypatch, input_id): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:recovered-navigation" + messages = [{"role": "system", "content": "context"}] + for i in range(2): + user = {"role": "user", "content": "same guidance", "timestamp": f"2026-06-02T10:0{i}:00+00:00"} + if input_id: + user["webui_turn_id"] = f"{input_id}-{i}" + messages.extend([user, {"role": "assistant", "content": f"answer {i}"}]) + transcript.append_transcript_object(key, {"event": "message", "text": f"answer {i}", "turn_id": f"execution-{i}"}) + transcript.append_transcript_object(key, {"event": "turn_end", "turn_id": f"execution-{i}"}) + def loader(): + return messages + + cold_page = transcript.build_webui_thread_response(key, limit=1, session_messages_loader=loader) + index = transcript.build_prompt_index(key, session_messages_loader=loader) + assert transcript.build_webui_thread_response(key, limit=1, session_messages_loader=loader) == cold_page + assert len(index) == 2 + assert index[0]["id"] != index[1]["id"] + assert [prompt["createdAt"] for prompt in index] == [1780394400000, 1780394460000] + for position, prompt in enumerate(index): + page = transcript.build_webui_thread_response(key, after=prompt["cursor"], limit=1, session_messages_loader=loader) + user = next(event for event in page["events"] if event["event"] == "user_message") + assert user["projection_id"] == prompt["id"] + assert user["created_at_ms"] == prompt["createdAt"] + assert user.get("turn_id") == (f"{input_id}-{position}" if input_id else None) + assert transcript.build_prompt_index(key, session_messages_loader=loader) == index + + +@pytest.mark.asyncio +async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(tmp_path, monkeypatch): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:canonical-revision" + manager = SessionManager(tmp_path) + session = manager.get_or_create(key) + session.messages = [ + {"role": "user", "content": "guidance", "webui_turn_id": "input", "timestamp": "2026-06-02T10:00:00+00:00"}, + {"role": "assistant", "content": "answer"}, + ] + manager.save(session) + for event in ({"event": "message", "text": "answer"}, {"event": "turn_end"}): + transcript.append_transcript_object(key, event) + gateway = build_gateway_services( + config=WebSocketConfig(), bus=MessageBus(), session_manager=manager, + 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, + ) + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + auth = [("Authorization", "Bearer test-token")] + base = "/api/sessions/websocket%3Acanonical-revision/webui-thread" + initial = {} + for path in (base, base + "/prompts"): + response = await gateway.http._dispatch_session_routes(Request(path, Headers(auth)), path) + assert response.status_code == 200 + initial[path] = response + unchanged = await gateway.http._dispatch_session_routes( + Request(path, Headers([*auth, ("If-None-Match", response.headers["ETag"])])), path, + ) + assert unchanged.status_code == 304 + # A canonical-only update must invalidate the recovered display even when + # transcript artifacts and the session's updated_at are unchanged. + session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00" + manager.save(session) + changed = {} + for path, previous in initial.items(): + response = await gateway.http._dispatch_session_routes( + Request(path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path, + ) + assert response.status_code == 200 + assert response.headers["ETag"] != previous.headers["ETag"] + changed[path] = json.loads(response.body) + user = next(event for event in changed[base]["events"] if event["event"] == "user_message") + prompt = changed[base + "/prompts"]["prompts"][0] + assert user["created_at_ms"] == prompt["createdAt"] == 1780394460000 + assert user["projection_id"] == prompt["id"] + assert prompt["id"] == json.loads(initial[base + "/prompts"].body)["prompts"][0]["id"] diff --git a/webui/src/components/thread/promptNavigation.ts b/webui/src/components/thread/promptNavigation.ts index 504bffb9e..a5666d5f8 100644 --- a/webui/src/components/thread/promptNavigation.ts +++ b/webui/src/components/thread/promptNavigation.ts @@ -3,6 +3,7 @@ import type { UIMessage } from "@/lib/types"; export interface PromptAnchor { answerPreview: string; id: string; + turnId?: string; label: string; preview: string; createdAt: number; @@ -17,6 +18,7 @@ export function userPromptAnchors(messages: UIMessage[]): PromptAnchor[] { const anchor: PromptAnchor = { answerPreview: nextAssistantPreview(messages, messageIndex), id: message.id, + ...(message.turnId ? { turnId: message.turnId } : {}), label: promptLabel(message.content, index), preview: promptPreview(message.content, index), createdAt: message.createdAt, diff --git a/webui/src/hooks/usePromptHistory.ts b/webui/src/hooks/usePromptHistory.ts index ffbda78e9..62a57d346 100644 --- a/webui/src/hooks/usePromptHistory.ts +++ b/webui/src/hooks/usePromptHistory.ts @@ -92,24 +92,38 @@ export function usePromptHistory(key: string | null, version: number, messages: return () => controller.abort(); }, [client, enabled, getToken, key, version, refresh]); - const indexedIds = useMemo(() => new Set(index?.prompts.map((prompt) => prompt.id)), [index]); + const indexed = useMemo(() => { + const ids = new Set(); + const turns = new Map(); + for (const prompt of index?.prompts ?? []) { + ids.add(prompt.id); + if (prompt.turnId) turns.set(prompt.turnId, turns.has(prompt.turnId) ? null : prompt); + } + return { ids, turns }; + }, [index]); const localCache = useRef<{ index: typeof index; users: UIMessage[]; prompts: PromptAnchor[] }>(); const prompts = useMemo(() => { if (!enabled) return userPromptAnchors(messages); if (!currentScope || index?.key !== key) return []; - // Keep live prompts and legacy prompts backfilled by the history reader - // navigable, even when they have no persisted transcript cursor yet. - const users = messages.filter((message) => message.role === "user" && !indexedIds.has(message.id)); + // 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; + 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; const cached = localCache.current; if (cached?.index === index && users.length === cached.users.length && users.every((user, position) => user === cached.users[position])) return cached.prompts; - const local = userPromptAnchors(messages).filter((prompt) => !indexedIds.has(prompt.id)); - const merged = [...index.prompts, ...local].sort((a, b) => a.createdAt - b.createdAt) - .map((prompt, position) => ({ ...prompt, index: position })); + 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 }; return merged; - }, [currentScope, enabled, index, indexedIds, key, messages]); + }, [currentScope, enabled, index, indexed, key, messages]); const updateMessages = useCallback((update: (messages: UIMessage[]) => UIMessage[]) => { setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) }))); diff --git a/webui/src/lib/format-time.ts b/webui/src/lib/format-time.ts index bd1fd4e9c..f43bb1d07 100644 --- a/webui/src/lib/format-time.ts +++ b/webui/src/lib/format-time.ts @@ -2,9 +2,9 @@ import i18n from "i18next"; import { normalizeLocale } from "@/i18n/config"; -/** Loose ISO-or-epoch parser; returns ``null`` for missing/invalid input. */ +/** Loose ISO-or-epoch parser; zero denotes an unknown persisted message time. */ function parseDate(value: string | number | null | undefined): Date | null { - if (value === null || value === undefined || value === "") return null; + if (value === null || value === undefined || value === "" || value === 0) return null; const d = new Date(value); return Number.isNaN(d.getTime()) ? null : d; } diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index d78da705f..a338ec15a 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -421,9 +421,9 @@ export function closeThreadProjectionAnswer( } function projectionCreatedAt(event: ThreadProjectionEvent, options: ThreadProjectionOptions): number { - return typeof event.created_at_ms === "number" && Number.isFinite(event.created_at_ms) + return typeof event.created_at_ms === "number" && Number.isFinite(event.created_at_ms) && event.created_at_ms >= 0 ? event.created_at_ms - : options.now; + : options.persisted ? 0 : options.now; } function projectionMessageId( @@ -785,7 +785,7 @@ export function projectThreadEvent( ); Object.assign(state, resetThreadProjectionCursor(state, state.messages)); const media = event.media_urls?.map((item) => toMediaAttachment(item)); - const turn = turnFieldsForProjection(state, event, "user"); + const turn = turnFieldsFromEvent(event, "user"); const row: UIMessage = { id: projectionMessageId(event, options), role: "user", @@ -999,13 +999,10 @@ export function projectThreadEvent( export function projectThreadEvents(events: ThreadProjectionEvent[]): UIMessage[] { let state = createThreadProjectionState(); - const fallbackNow = Date.now(); events.forEach((event, index) => { state = projectThreadEvent(state, event, { createId: () => `history-${index}`, - now: typeof event.created_at_ms === "number" - ? event.created_at_ms - : fallbackNow + index, + now: 0, persisted: true, }); }); diff --git a/webui/src/tests/prompt-navigator.test.tsx b/webui/src/tests/prompt-navigator.test.tsx index f7ef0037e..1df4ebc8a 100644 --- a/webui/src/tests/prompt-navigator.test.tsx +++ b/webui/src/tests/prompt-navigator.test.tsx @@ -50,3 +50,17 @@ it("lets users type into prompt search immediately after opening it", async () = expect(onJumpToPrompt).toHaveBeenCalledWith("two"); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); }); + + +it("keeps an unknown recovered time blank while the prompt remains navigable", async () => { + const user = userEvent.setup(); + const onJumpToPrompt = vi.fn(); + render(); + await user.click(screen.getByRole("button", { name: "Message navigation" })); + const prompt = screen.getByRole("button", { name: "Jump to message: Undated recovered input" }); + expect(prompt.textContent).toBe("Undated recovered input"); + await user.click(prompt); + expect(onJumpToPrompt).toHaveBeenCalledWith("undated"); +}); diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.ts index ee8f48d26..673d2ce80 100644 --- a/webui/src/tests/thread-event-projection.test.ts +++ b/webui/src/tests/thread-event-projection.test.ts @@ -131,3 +131,16 @@ describe("canonical thread event projection", () => { expect(messages[0].activitySegmentId).toBe(messages[1].activitySegmentId); }); }); + + +it("uses deterministic unknown replay time and preserves distinct same-text inputs", () => { + const events: ThreadProjectionEvent[] = [ + { event: "user_message", chat_id: "chat", text: "same", starts_turn: true, turn_id: "input-one", projection_id: "u1" }, + { event: "turn_end", chat_id: "chat", turn_id: "input-one" }, + { event: "user_message", chat_id: "chat", text: "same", starts_turn: true, turn_id: "input-two", projection_id: "u2" }, + ]; + const messages = projectThreadEvents(events); + expect(messages.map((message) => message.id)).toEqual(["u1", "u2"]); + expect(messages.map((message) => message.createdAt)).toEqual([0, 0]); + expect(projectThreadEvents(events)).toEqual(messages); +}); diff --git a/webui/src/tests/usePromptHistory.test.tsx b/webui/src/tests/usePromptHistory.test.tsx index e436ba743..f2fe49da9 100644 --- a/webui/src/tests/usePromptHistory.test.tsx +++ b/webui/src/tests/usePromptHistory.test.tsx @@ -143,3 +143,35 @@ it("reuses the full directory during token updates and conditional revalidation" expect(api.fetchPromptIndex).toHaveBeenLastCalledWith("test", "a", expect.any(AbortSignal), { prompts: index, revision: "first" }); expect(result.current.prompts).toBe(anchors); }); + + +it("merges a live input by transport identity without adding an anchor or reordering unknown-time prompts", async () => { + const recovered = [ + { id: "old", preview: "older", answerPreview: "", createdAt: 1000, cursor: "0", turnId: "old-input" }, + { id: "persisted", preview: "same", answerPreview: "answer", createdAt: 0, cursor: "1", turnId: "input" }, + ]; + vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: recovered, revision: "recovered" }); + const users: UIMessage[] = [ + { id: "optimistic", role: "user", content: "same", createdAt: 2000, turnId: "input" }, + { id: "distinct", role: "user", content: "same", createdAt: 3000, turnId: "other-input" }, + ]; + const { result, rerender } = renderHook(({ key, version }) => usePromptHistory(key, version, users), { + wrapper: wrapper(), initialProps: { key: "a", version: 1 }, + }); + await waitFor(() => expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"])); + vi.mocked(api.fetchWebuiThread).mockResolvedValue({ schemaVersion: 3, projection: "events", events: [ + { event: "user_message", chat_id: "a", text: "same", starts_turn: true, projection_id: "persisted", turn_id: "input", created_at_ms: 0 }, + { event: "message", chat_id: "a", text: "answer", projection_id: "answer" }, + ] }); + await act(async () => result.current.jump("persisted")); + expect(result.current.target?.id).toBe("persisted"); + expect(result.current.window?.messages[0].createdAt).toBe(0); + rerender({ key: "a", version: 2 }); + await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(2)); + expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]); + rerender({ key: "b", version: 1 }); + await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(3)); + expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]); + expect(result.current.window).toBeNull(); + expect(result.current.target).toBeNull(); +});