From 27f1a836b5c04a30763dd91960059f81c05bf505 Mon Sep 17 00:00:00 2001 From: chengyongru Date: Wed, 11 Nov 2026 13:52:33 +0800 Subject: [PATCH] fix(webui): settle interrupted turns before replaying follow-ups --- nanobot/webui/recovery.py | 27 +++++++++++++++++ tests/session/test_recovery.py | 53 ++++++++++++++++++++++++++++++---- 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/nanobot/webui/recovery.py b/nanobot/webui/recovery.py index 06e920ded..fa8c13e5b 100644 --- a/nanobot/webui/recovery.py +++ b/nanobot/webui/recovery.py @@ -17,6 +17,7 @@ from nanobot.bus.outbound_events import ( ) from nanobot.bus.queue import MessageBus from nanobot.session import turn_continuation +from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata from nanobot.session.manager import Session, SessionManager from nanobot.session.recovery import ( @@ -99,6 +100,7 @@ class RecoveryCoordinator: session = await self.sessions.state.get(key) try: await self._recover_session(session, route[1]) + await self._close_interrupted_turns(session) await self._requeue_pending_followups(session) except Exception: logger.exception("failed to recover interrupted WebUI session {}", session.key) @@ -427,6 +429,31 @@ class RecoveryCoordinator: ) ) + async def _close_interrupted_turns(self, session: Session) -> None: + # Startup has no live execution owners. Persist their terminal identities + # before admitting new work so reconnecting clients can settle old runs. + queued_turns = {message.metadata.get(WEBUI_TURN_METADATA_KEY) for message in pending_followups(session)} + + def completions(history: HistoryReader) -> list[HistoryFact]: + if not history.turn_count: + return [] + tail = history.read_entries(history.turn_count - 1) + if not tail or tail[-1][1].kind is HistoryKind.COMPLETION: + # In particular, don't bypass a transcript_incomplete marker. + return [] + sequences: dict[str, int] = {} + for _, fact in tail: + if fact.turn_id and fact.turn_id not in queued_turns: + sequences[fact.turn_id] = max(sequences.get(fact.turn_id, 0), fact.sequence or 0) + return [HistoryFact( + HistoryKind.COMPLETION, {"outcome": "interrupted"}, turn_id=turn_id, + phase="complete", sequence=sequence + 1, created_at_ms=int(datetime.now().timestamp() * 1000), + ) for turn_id, sequence in sequences.items()] + + facts = await self.sessions.state.project_history(session.key, completions) + if facts: + await self.sessions.state.append_history(session.key, facts, expected_generation=session.generation) + async def _requeue_pending_followups(self, session: Session) -> None: for message in pending_followups(session): await self.bus.publish_inbound(message) diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.py index 01cd50dba..239103472 100644 --- a/tests/session/test_recovery.py +++ b/tests/session/test_recovery.py @@ -9,6 +9,7 @@ from nanobot.bus.events import InboundMessage from nanobot.bus.outbound_events import RecoveryStateEvent, SessionUpdatedEvent from nanobot.bus.queue import MessageBus from nanobot.providers.base import ProviderConversationState +from nanobot.session.display_history import HistoryFact, HistoryKind from nanobot.session.keys import UNIFIED_SESSION_KEY from nanobot.session.manager import Session, SessionManager from nanobot.session.recovery import ( @@ -63,14 +64,12 @@ async def test_restart_before_model_call_waits_for_confirmation(tmp_path: Path) @pytest.mark.asyncio -async def test_stale_incomplete_transcript_waits_for_confirmation(tmp_path: Path, monkeypatch) -> None: +async def test_stale_incomplete_transcript_waits_for_confirmation(tmp_path: Path) -> None: sessions = SessionManager(tmp_path) session = sessions.get_or_create("websocket:chat") _persist(sessions, session) - monkeypatch.setattr( - "nanobot.webui.transcript.has_unfinished_transcript_tail", - lambda _key, **_kwargs: True, - ) + incomplete = HistoryFact(HistoryKind.COMPLETION, {"transcript_incomplete": True}, turn_id="failed-persistence") + sessions.append_history(session.key, [incomplete]) coordinator, bus, restarted = _coordinator(tmp_path) await coordinator.scan() @@ -79,6 +78,7 @@ async def test_stale_incomplete_transcript_waits_for_confirmation(tmp_path: Path state = restarted.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY] assert state["status"] == "awaiting_user" assert state["reason"] == "interrupted_without_checkpoint" + assert await restarted.state.project_history(session.key, lambda history: history.all_facts()) == [incomplete] event = bus.outbound.get_nowait().event assert isinstance(event, RecoveryStateEvent) assert event.status == "awaiting_user" @@ -204,6 +204,49 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery( assert loaded == ["websocket:pending"] +@pytest.mark.asyncio +@pytest.mark.parametrize("interrupted_turn, activity", [("original", False), ("original", True), ("recovery:previous", True)]) +async def test_restart_closes_interrupted_turn_before_requeuing_followup( + tmp_path: Path, interrupted_turn: str, activity: bool, +) -> None: + sessions = SessionManager(tmp_path) + session = sessions.get_or_create("websocket:chat") + session.messages.append({"role": "user", "content": "old request"}) + session.metadata[PENDING_USER_TURN_KEY] = True + record_pending_followup(session, InboundMessage( + channel="websocket", sender_id="user", chat_id="chat", content="new request", + metadata={"webui": True, "webui_turn_id": "queued"}, + )) + _persist(sessions, session) + facts = [HistoryFact(HistoryKind.INPUT, {"text": "old request"}, turn_id="original", phase="user")] + if interrupted_turn != "original": + facts.append(HistoryFact(HistoryKind.COMPLETION, {"outcome": "interrupted"}, turn_id="original", phase="complete")) + if activity: + facts.append(HistoryFact(HistoryKind.TOOL_ACTIVITY, {"text": "waiting"}, turn_id=interrupted_turn, phase="activity", sequence=7)) + facts.append(HistoryFact(HistoryKind.INPUT, {"text": "new request"}, turn_id="queued", phase="user")) + sessions.append_history(session.key, facts) + + coordinator, bus, restarted = _coordinator(tmp_path) + await coordinator.scan() + + def completions(history): + return [fact for fact in history.all_facts() if fact.kind is HistoryKind.COMPLETION] + + ended = await restarted.state.project_history(session.key, completions) + assert interrupted_turn in {fact.turn_id for fact in ended} + assert "queued" not in {fact.turn_id for fact in ended} + assert all(fact.content["outcome"] == "interrupted" for fact in ended) + queued = bus.inbound.get_nowait() + assert queued.metadata["webui_turn_id"] == "queued" + assert await coordinator.admit(queued) + assert (await restarted.state.get(session.key)).metadata[RECOVERY_METADATA_KEY]["reason"] == "superseded" + + # Repeated startup must not append another completion or lose the queued input. + await coordinator.scan() + assert await restarted.state.project_history(session.key, completions) == ended + assert len(pending_followups(await restarted.state.get(session.key))) == 1 + + @pytest.mark.asyncio @pytest.mark.parametrize("cross_session", [False, True]) async def test_live_turn_followup_survives_restart_until_it_is_committed(tmp_path: Path, cross_session: bool) -> None: