diff --git a/src/toad/client/committed_presentation.py b/src/toad/client/committed_presentation.py index 74b5adb10..6d1a5c16a 100644 --- a/src/toad/client/committed_presentation.py +++ b/src/toad/client/committed_presentation.py @@ -339,6 +339,7 @@ def arriving(self, prepared: PreparedTranscriptPage, followed_end: bool): ) def rows_published(self, owner) -> None: + super().rows_published(owner) if self.live_blocks and not NEWER_END.visible_more(owner): blocks, self.live_blocks = self.live_blocks, () self.retirement = owner.view.retire_blocks(blocks) diff --git a/src/toad/client/history.py b/src/toad/client/history.py index d941a6f2e..e77bbf3d4 100644 --- a/src/toad/client/history.py +++ b/src/toad/client/history.py @@ -41,7 +41,7 @@ from toad.client.connection import CoordinationAccess, Observation from toad.client.conversation import ConversationKind from toad.client.resource_release import ResourceRelease -from toad.core.events import CoordinationObserved, Publication +from toad.core.events import Publication from toad.core.source_events import TranscriptSourceWorkFinished from toad.client.conversation_capabilities import ( ConversationActivity, @@ -739,17 +739,6 @@ def reads_from(self, root: str | Path) -> bool: def uses_observation(self, observation: Observation) -> bool: return observation.observes(self.loader.root) - def observe_availability(self, view, access: CoordinationAccess, resume: Callable[[object], object]) -> ResourceRelease: - """A wire conversation has no thread transcript scope (`NoTranscript.observe` is a - no-op), so a read paused on `CoordinationReadUnavailable` resumes on Core's own - coordination stream instead of wedging the tab in `WorkingTranscript` forever.""" - release = ResourceRelease() - release.callback( - view.retire_core, - view.observe_core_callback(access.events, CoordinationObserved, resume), - ) - return release - async def route_is_current(self) -> bool: if self.closed: return False diff --git a/src/toad/client/history_state.py b/src/toad/client/history_state.py index 11492aa11..93ba41947 100644 --- a/src/toad/client/history_state.py +++ b/src/toad/client/history_state.py @@ -17,17 +17,21 @@ from agent_comms.nominal.declared_family import DeclaredFamily from agent_comms.nominal.lifecycle import LifecycleState from agent_comms.transcript.transcripts import TranscriptPage +from agent_comms.ui_model.observation import ObserverUnattached +from agent_comms.ui_model.observation_wire import ObservationEnded from toad.client.history_coverage import NO_COVERAGE, PAGE_COVERAGE, HistoryCoverage from toad.client.history_preparation import NEWER_END, OLDER_END, PageRequest from toad.client.resource_release import ResourceRelease from toad.client.subscribers import CoreObserver -# Network drops, route changes and remote socket failures are recoverable outages, never -# permanent source corruption: defer the operation so CoordinationObserved resumes it -# when connectivity returns instead of retiring the tab into RetiredSourceTranscript. +# Network drops, route changes, observer restarts and remote socket failures are recoverable +# outages, never permanent source corruption: defer the operation so CoordinationObserved +# resumes it when connectivity returns instead of retiring the tab into RetiredSourceTranscript. TRANSIENT_SOURCE_ERRORS = ( CoordinationReadUnavailable, + ObservationEnded, + ObserverUnattached, RouteChangedError, ConnectionError, TimeoutError, @@ -338,11 +342,9 @@ class WaitingSourceWork[Owner, Snapshot, Result]: @contextmanager def observe(self): - # The pager's page source owns how availability returns: a saved transcript watches - # its view's thread scope, while a wire conversation watches Core's coordination - # stream (`WirePageBuffer.observe_availability`) because its `thread_scope` is - # `NoTranscript` (whose `observe` is a no-op that left channel tabs wedged forever - # after any background/reconnect `CoordinationReadUnavailable`). + # `PreparedPageSource.observe_availability` watches both the view's thread scope + # (a no-op on wire conversations whose scope is `NoTranscript`) and Core's + # coordination stream so reconnection resumes paused transcript and wire reads alike. view = self.owner.view with self.owner.page_source.observe_availability( view, self.owner.app.coordination_access, self.resume @@ -389,6 +391,11 @@ def schedule_work(self, owner, work) -> SourceWork: self.owed[key] = work return DEFERRED_WORK + def publish(self) -> TranscriptState: + """Advance the wrapped state without dropping this running operation before `finish_source_work`.""" + object.__setattr__(self, "source", self.source.publish()) + return self + def rows_published(self, owner) -> None: self.source.rows_published(owner) diff --git a/src/toad/client/prepared_pages.py b/src/toad/client/prepared_pages.py index 1fd5ea168..af428d63e 100644 --- a/src/toad/client/prepared_pages.py +++ b/src/toad/client/prepared_pages.py @@ -36,6 +36,7 @@ from toad.client.resource_release import ResourceRelease from toad.client.submission import ComposeAccess, SubmissionOwner, SubmissionStart, SubmittedText from toad.commit_claims import RETAINED_SOURCE_CLAIM, CommitClaim, RetainedBlockClaim +from toad.core.events import CoordinationObserved from toad.status_thread import NoStatusThread from toad.work_preparation import ( PreparationRuntime, @@ -434,9 +435,16 @@ def measure_held(self, pages: tuple[PreparedTranscriptPage, ...], def observe_availability( self, view, access: CoordinationAccess, resume: Callable[[object], object] ) -> ResourceRelease: - """How a paused read learns its source can answer again: saved transcripts watch - their view's thread scope; wire conversations override this to watch Core's stream.""" - return view.thread_scope.observe(view, access, resume) + """How a paused read learns its source can answer again: watch both the view's thread + scope (a no-op on wire conversations whose scope is `NoTranscript`) and Core's + coordination stream so reconnection resumes paused transcript and wire reads alike.""" + release = ResourceRelease() + release.enter_context(view.thread_scope.observe(view, access, resume)) + release.callback( + view.retire_core, + view.observe_core_callback(access.events, CoordinationObserved, resume), + ) + return release def park(self, pages: tuple[PreparedTranscriptPage, ...], projection: HeldProjection = NoProjection()) -> None: diff --git a/src/toad/qt/mailbox_view.py b/src/toad/qt/mailbox_view.py index 35d58fe1b..482af9d4f 100644 --- a/src/toad/qt/mailbox_view.py +++ b/src/toad/qt/mailbox_view.py @@ -67,6 +67,10 @@ def __init__(self, app, project: Checkout, thread_incarnation: ThreadIncarnation # made the empty page look already published and no first-page read was scheduled. self._identity: ThreadIdentity | NoThreadIdentity = ThreadIdentity(thread_incarnation, root) self._lay_out_thread(app, thread_incarnation.name, thread_incarnation) + # Qt's mailbox view never hosts a local ACP agent: its composer and submission path + # always send through Core's inbox, including when opened on a local desktop bus + # where `NativeThreadNavigation.bind` calls `apply_native_load_plan`. + self.operational_sources = self.mailbox_sources() def composer_class(self) -> type[MailboxComposer]: """Textual's `MailboxSessionSources.prompt`: a `MailboxPrompt`.""" diff --git a/src/toad/transcript_publication.py b/src/toad/transcript_publication.py index efa5a32d4..8b709fed1 100644 --- a/src/toad/transcript_publication.py +++ b/src/toad/transcript_publication.py @@ -78,7 +78,11 @@ PreparedTranscriptPage, UnreadTranscriptPage, ) -from toad.client.history_state import LiveTranscript, PreparedReplacementViewportRequest +from toad.client.history_state import ( + TRANSIENT_SOURCE_ERRORS, + LiveTranscript, + PreparedReplacementViewportRequest, +) from toad.client.reader_position import LatestPosition, TailPosition from toad.worker_group import WorkerGroup @@ -202,22 +206,26 @@ async def publish(self) -> bool: try: if await self.capture_application(): return await self.publish_applied() - except CoordinationReadUnavailable, StaleRevision, ReadAgain: - # No usable source snapshot was acquired. Keep the original operation, - # mounted history and work slot unchanged until a new observation - # or the existing preparation completion resumes source work. A read dropped - # because its observation closed (`ObserverRetired`, a `ReadAgain`) is one of - # these: it escaped here until 2026-11-21, ending the publication's task with - # an exception nobody took (Qt), or a failed worker (Textual). + except ReloadRequired: + # Must precede `ReadAgain`: `ReloadRequired` subclasses `ReadAgain`, so catching + # `ReadAgain` first left this arm unreachable and kept resending a stale witness. + # The published witness names a source that is gone, so the resumed operation + # reads from fresh bounds. if self.current(): + self.owner.current_read = NotPublished() self.owner.source_requests.defer(self) return False - except ReloadRequired: - # The published witness names a source that is gone, so resending it never - # answers: the resumed operation reads from fresh bounds. + except (*TRANSIENT_SOURCE_ERRORS, StaleRevision, ReadAgain) as error: + # No usable source snapshot was acquired. Keep the original operation, + # mounted history and work slot unchanged until a new observation + # or the existing preparation completion resumes source work. A read dropped + # because its observation closed (`ObserverRetired`, a `ReadAgain`) or the + # connector/observer restarted (`ObservationEnded`, `RouteChangedError`, etc.) + # defers here instead of failing the publication task and wedging the view. if self.current(): - self.owner.current_read = NotPublished() self.owner.source_requests.defer(self) + if isinstance(error, TRANSIENT_SOURCE_ERRORS): + self.binding.view.app.coordination_access.check_route() return False return True diff --git a/tests/guards/test_shared_history_change.py b/tests/guards/test_shared_history_change.py index 9e5624bb2..ff5d095d3 100644 --- a/tests/guards/test_shared_history_change.py +++ b/tests/guards/test_shared_history_change.py @@ -96,8 +96,11 @@ def test_a_paused_source_observes_the_scope_its_pager_view_owns(): from toad.client.history_state import WaitingSourceWork from toad.client.prepared_pages import PreparedPageSource from toad.core.events import CoordinationObserved + from toad.transcript_scope import NoTranscript observed = [] + saved_subscribed = [] + saved_retired = [] @contextmanager def observe(owner, access, resume): @@ -105,7 +108,11 @@ def observe(owner, access, resume): yield access = SimpleNamespace(events=object()) - view = SimpleNamespace(thread_scope=SimpleNamespace(observe=observe)) + view = SimpleNamespace( + thread_scope=SimpleNamespace(observe=observe), + observe_core_callback=lambda stream, event_type, cb: (saved_subscribed.append((stream, event_type, cb)), "saved-sub")[1], + retire_core=lambda sub: saved_retired.append(sub), + ) owner = SimpleNamespace( view=view, page_source=PreparedPageSource(), @@ -114,15 +121,19 @@ def observe(owner, access, resume): waiting = WaitingSourceWork(owner, object(), lambda: None, object()) with waiting.observe(): - pass + assert saved_subscribed == [(access.events, CoordinationObserved, waiting.resume)] + assert saved_retired == [] assert observed == [(view, access, waiting.resume)] + assert saved_retired == ["saved-sub"] - # A wire conversation has NoTranscript as thread_scope, so WirePageBuffer must watch - # Core's CoordinationObserved stream instead of silently returning an empty release. + # A wire conversation has NoTranscript as thread_scope and inherits the same + # PreparedPageSource.observe_availability so both transcript and wire reads wake on + # CoordinationObserved. subscribed = [] retired = [] wire_view = SimpleNamespace( + thread_scope=NoTranscript(), observe_core_callback=lambda stream, event_type, cb: (subscribed.append((stream, event_type, cb)), "sub")[1], retire_core=lambda sub: retired.append(sub), ) diff --git a/tests/guards/test_shared_hook_sequences.py b/tests/guards/test_shared_hook_sequences.py index 58fae5b2b..3b5117fe7 100644 --- a/tests/guards/test_shared_hook_sequences.py +++ b/tests/guards/test_shared_hook_sequences.py @@ -896,6 +896,7 @@ def test_qt_live_blocks_survive_page_range_changes_and_retire_only_by_commit_cov from toad.qt.thread_view import QtThreadView from toad.transcript_publication import BoundView from toad.client.committed_presentation import CommitTranscript, block_claim + from toad.client.history_state import LiveTranscript from toad.arrivals import AnimatesArrivals redrawn = [] @@ -986,7 +987,7 @@ async def apply_coverage(): async def check_commit_retirement(): commit = CommitTranscript( - source=SimpleNamespace(), + source=LiveTranscript(), owner=fake_owner, live_blocks=(uncovered_response,), claims=(block_claim(uncovered_response),), diff --git a/tests/model/test_android_resync_lazy_load_catchup.py b/tests/model/test_android_resync_lazy_load_catchup.py index 6e73ecc14..6feaf191d 100644 --- a/tests/model/test_android_resync_lazy_load_catchup.py +++ b/tests/model/test_android_resync_lazy_load_catchup.py @@ -11,15 +11,19 @@ import pytest from agent_comms.acp_extension import TranscriptSnapshotUpdate +from agent_comms.coordination.errors import ReloadRequired, TranscriptChanged from agent_comms.errors import RouteChangedError from agent_comms.execution.transcript_sources import LatestPage, Through, UnreadTranscriptCursor from agent_comms.presentation import NoRevision from agent_comms.transcript.transcript_drafts import NoDraft from agent_comms.transcript.transcripts import TranscriptPage from agent_comms.transport.request import ConnectionDropped +from agent_comms.ui_model.observation import NotPublished, ObserverUnattached, Published +from agent_comms.ui_model.observation_wire import ObserverDied from toad.client.application import ACTIVE_PRESENCE from toad.client.committed_presentation import ( + CommitTranscript, FollowTailCommit, PreparedAppendCommit, PreparedPageCommit, @@ -42,12 +46,17 @@ PresentationBudget, Runway, ) -from toad.client.history_state import LiveTranscript, RetiredSourceTranscript, WorkingTranscript -from toad.client.prepared_pages import SavedHistory +from toad.client.history_state import ( + LiveTranscript, + RetiredSourceTranscript, + UnreadTranscript, + WorkingTranscript, +) +from toad.client.prepared_pages import PreparedPageSource, SavedHistory from toad.client.resource_release import ResourceRelease from toad.core.events import CoordinationObserved, CoreEventStream from toad.history_jump import FollowsTail -from toad.transcript_publication import SourcePublicationRequests +from toad.transcript_publication import SourcePublicationRequests, TranscriptPublication # --- Bug 1: Android background resume & transient-error recovery --- @@ -169,6 +178,8 @@ def test_application_presence_distinguishes_suspend_from_focus_loss(): TimeoutError("socket timed out"), RouteChangedError("observation dropped"), http.client.RemoteDisconnected("closed"), + ObserverDied("connector restarted"), + ObserverUnattached("reattaching"), ], ) async def test_working_transcript_defers_transient_transport_errors_instead_of_retiring_tab(error): @@ -513,3 +524,132 @@ async def publish_held_latest(self, _current=lambda: True) -> bool: assert await pager.extend("new") is True assert "load_intermediate_page" not in actions assert actions == ["get_adjacent", "update_edges", "publish_held_latest"] + + +# --- Bug 4: DM/thread view stale-witness, CoordinationObserved wakeup, and UnreadTranscript commit --- + + +def test_prepared_page_source_observe_availability_wakes_on_coordination_observed(): + class Publisher: + pass + + events = CoreEventStream(Publisher()) + resumed: list[object] = [] + + class FakeView: + def __init__(self) -> None: + self.thread_scope = SimpleNamespace(observe=lambda _v, _a, _cb: ResourceRelease()) + self._cb = None + + def _deliver(self, event, _sub) -> None: + self._cb(event) + + def observe_core_callback(self, stream, event_type, callback): + self._cb = callback + return stream.subscribe(event_type, self._deliver) + + def retire_core(self, subscription) -> None: + subscription.close() + + source = PreparedPageSource() + access = SimpleNamespace(events=events) + release = source.observe_availability(FakeView(), access, resumed.append) + try: + events.publish(CoordinationObserved(NoRevision())) + assert len(resumed) == 1 + finally: + release.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("error", "resets_read", "checks_route"), + [ + (ReloadRequired("witness gone"), True, False), + (TranscriptChanged(), True, False), + (ObserverDied("connector dropped"), False, True), + (RouteChangedError("route switched"), False, True), + (ConnectionDropped("socket reset"), False, True), + ], +) +async def test_transcript_publication_resets_witness_on_reload_and_defers_transient_errors( + error, resets_read, checks_route, +): + deferred: list[object] = [] + route_checks: list[str] = [] + + class FakePublication(TranscriptPublication): + def current(self) -> bool: + return True + + async def capture_application(self) -> bool: + return True + + async def publish_applied(self) -> bool: + raise error + + owner = SimpleNamespace( + current_read=Published(SimpleNamespace()), + source_requests=SimpleNamespace(defer=deferred.append), + ) + binding = SimpleNamespace( + view=SimpleNamespace( + on_native_pump=lambda: False, + live_blocks=(), + turns=SimpleNamespace(owner=SimpleNamespace(captured_snapshot=lambda _blocks: None)), + agent_binding=SimpleNamespace(committed_native_output=None), + app=SimpleNamespace( + coordination_access=SimpleNamespace( + check_route=lambda: route_checks.append("check"), + ) + ), + ), + window=SimpleNamespace(reader_position=None), + thread_scope=None, + ) + pub = FakePublication(binding, owner, 0) + + assert await pub.publish() is False + assert deferred == [pub] + assert isinstance(owner.current_read, NotPublished) is resets_read + assert bool(route_checks) is checks_route + + +@pytest.mark.asyncio +async def test_working_and_commit_transcript_publish_keeps_operation_active_until_finish(): + published_calls: list[str] = [] + painted_calls: list[object] = [] + + class FakeOwner: + def __init__(self) -> None: + self.window = SimpleNamespace(scroll_revision=0) + self.page_source = SimpleNamespace(through="cursor-1") + self.view = SimpleNamespace( + transcript=SimpleNamespace( + binding=SimpleNamespace( + painted=lambda _tr, cur: painted_calls.append(cur), + ) + ) + ) + self._source_state = UnreadTranscript() + + def paging_window(self): + return ("through", None, ()) + + def publish_committed(self) -> None: + published_calls.append("publish_committed") + self._source_state = self._source_state.publish() + + owner = FakeOwner() + op = CommitTranscript(owner._source_state, owner, live_blocks=(), claims=()) + owner._source_state = op + + op.rows_published(owner) + + # The running operation stayed mounted in `_source_state` so `finish_source_work` still matches it, + # while its wrapped state transitioned from UnreadTranscript to LiveTranscript ("Saved history available"). + assert owner._source_state is op + assert isinstance(op.source, LiveTranscript) + assert op.coverage.summary == "Saved history available" + assert published_calls == ["publish_committed"] + assert painted_calls == ["cursor-1"]