diff --git a/src/toad/client/application.py b/src/toad/client/application.py index 536571438..f16c6f222 100644 --- a/src/toad/client/application.py +++ b/src/toad/client/application.py @@ -116,8 +116,10 @@ def activate(self, app: ClientApplication) -> ApplicationPresence: class SuspendedPresence(ApplicationPresence): def activate(self, app: ClientApplication) -> ApplicationPresence: + # `resume()` publishes `CoordinationObserved` once the fresh observation attaches, + # which triggers `stores_changed` -> `selected.reload()` on the new observer instead + # of racing a synchronous reload against the retiring one (`ObserverRetired`). app.coordination_access.resume() - app.workspace_sessions.selected.reload() return ACTIVE_PRESENCE def deactivate(self, app: ClientApplication) -> ApplicationPresence: diff --git a/src/toad/client/connection.py b/src/toad/client/connection.py index 338b21434..c33426e51 100644 --- a/src/toad/client/connection.py +++ b/src/toad/client/connection.py @@ -26,10 +26,12 @@ from agent_comms.errors import RouteChangedError from agent_comms.execution.child_process import ( Platform, + RelayEnding, WorkerStart, join_retirement, ) from agent_comms.execution.remote_core_process import ProcessRemoteCoreAccess +from agent_comms.transport.remote_core import ConnectorObserverClosed, ServiceFailed from agent_comms.team.team_board_selection import NamedTeamBoards, TeamBoardSelection from agent_comms.execution.transcript_sources import TranscriptCursor from agent_comms.installer.active_route import CommsRoute @@ -348,6 +350,58 @@ def observe(self, access: CoordinationAccess) -> Observing | FailedObservation: return access.observation.failed(error, UnselectedRoute()) return access.observe_remote(self, Path(served.root)) + def resume_observe(self, access: CoordinationAccess, served_root: Path) -> Observing | FailedObservation: + """Re-open observation on the already-known served root after suspension without + paying a cold `CommsServedRootTool` HTTPS round-trip first.""" + return access.observe_remote(self, served_root) + + +class ObservationFailureReport(MroDispatch): + """Route observation disconnects by failure kind: expected remote socket drops log + quietly and auto-retry without popping an error toast; real Core service crashes + (`ServiceFailed`) and unexpected observer deaths still surface through the host.""" + + @handles(ConnectorObserverClosed) + def connector_closed( + self, error: ConnectorObserverClosed, app: CommsHost, title: str | None, + ) -> object: + self.dispatch_sync(error.ending, error, app, title) + return self.DISCARD + + @handles(ServiceFailed) + def service_failed( + self, ending: ServiceFailed, error: Exception, app: CommsHost, title: str | None, + ) -> object: + self._surface(error, app, title) + return self.DISCARD + + @handles(RelayEnding) + def transient_relay( + self, ending: RelayEnding, error: Exception, app: CommsHost, title: str | None, + ) -> object: + app.log_error(str(error)) + return self.DISCARD + + @handles(OSError) + def transient_io(self, error: OSError, app: CommsHost, title: str | None) -> object: + app.log_error(str(error)) + return self.DISCARD + + @handles(Exception) + def unexpected(self, error: Exception, app: CommsHost, title: str | None) -> object: + self._surface(error, app, title) + return self.DISCARD + + @staticmethod + def _surface(error: Exception, app: CommsHost, title: str | None) -> None: + if title is None: + app.report_fatal(error) + else: + app.show_error(error, title) + + +OBSERVATION_FAILURE_REPORT = ObservationFailureReport() + @dataclass(frozen=True) class UnselectedRoute: @@ -501,6 +555,15 @@ def activate(self, access: CoordinationAccess): for view in tuple(access.sidebar_views): self.show_sidebar(view) + def retains_root_cache(self, previous_root: Path | None) -> bool: + """Whether attaching this observation preserves cached per-root read receipts and + thread status (transient failures keep the last root's cache until a different root + attaches).""" + return True + + def record_observed_root(self, access: CoordinationAccess) -> None: + """Record the active bus root when an `Observing` attaches.""" + def attach(self, access, previous): previous.subscriptions.close() if not self.is_current(): @@ -513,13 +576,15 @@ def attach(self, access, previous): subscribers = tuple(dict.fromkeys(( *access.notification_views, *previous.pending_notification_views(), ))) + if not self.retains_root_cache(access._last_observed_root): + access.thread_status.clear() + access.notification_known.clear() + self.record_observed_root(access) access.revision = NoRevision() access.sidebar_interest = access.sidebar_current = None access.team_interest = StopTeamHud() - access.thread_status.clear() access.views_interest = None access.notification_views.clear() - access.notification_known.clear() access.notification_interest = ObserveNotifications(frozenset()) self.activate(access) self.rebind_notifications(subscribers) @@ -684,7 +749,9 @@ def subscribe_notifications( def thread_interest(self, access: CoordinationAccess): if access.retry.began(): - access.app.show_error(self.error, "Thread status unavailable") + OBSERVATION_FAILURE_REPORT.dispatch_sync( + self.error, access.app, "Thread status unavailable" + ) def observe_team(self, wanted: ObserveTeamHud | StopTeamHud): self.access.events.publish(TeamHudFailed(self.error)) @@ -905,14 +972,20 @@ def tell(self, wanted) -> None: except ObservationEnded: pass + def retains_root_cache(self, previous_root: Path | None) -> bool: + return previous_root is None or self.root == previous_root + + def record_observed_root(self, access: CoordinationAccess) -> None: + access._last_observed_root = self.root + def receive_failed(self, error: Exception): - """The observation closed: the failure becomes current and retries; the reader is - told once per outage, not once per reopen that closes again.""" + """The observation closed: the failure becomes current and retries; expected remote + socket drops log quietly while real service crashes surface once per outage.""" if self.is_current(): self.failed(error, self.opened_selection()) if self.access.retry.began(): error.add_note(self.access.retry.quiet_note(time.monotonic())) - self.access.app.report_fatal(error) + OBSERVATION_FAILURE_REPORT.dispatch_sync(error, self.access.app, None) def views_changed(self, event=None, subscription=None): access, root = self.access, str(self.root) @@ -992,7 +1065,10 @@ def through(self, connection: RemoteCoreConnection, access: CoordinationAccess): def resumed_through(self, connection: RemoteCoreConnection, access: CoordinationAccess): """After Android suspension or a network switch, the existing WebSocket may be - half-open; open a fresh observation instead of waiting on heartbeat timeout.""" + half-open; open a fresh observation on the known served root instead of waiting + on heartbeat timeout or paying a cold `CommsServedRootTool` round-trip.""" + if self.connection is connection: + return connection.resume_observe(access, self.served_root) return connection.observe(access) def user_identity(self, project: Checkout) -> Thread: @@ -1022,6 +1098,8 @@ def __init__(self, app: CommsHost, connection: CoreConnection) -> None: self.transcripts = CoordinationTranscriptReader(self) self.observation: Observation = NotObserving(access=self) + self._last_observed_root: Path | None = None + self._retained_remote: dict[Path, tuple[SidebarModel, RegistryReads]] = {} self.retry = ObservationRetry() self.events = CoreEventStream(self) self.revision: ReadState = NoRevision() @@ -1091,10 +1169,18 @@ def require(self, selected: RouteSelection) -> Observing: def observe_remote(self, connection: RemoteCoreConnection, root: Path) -> RemoteObserving: """Observe the Core behind the connector: its peer carries the observation, and the - root it serves keys every root-scoped request.""" + root it serves keys every root-scoped request. Reconnecting to the same root reuses + its retained sidebar model and registry cache so the UI never flashes blank or + re-downloads the whole registry while the fresh WebSocket syncs.""" with self.opening: + retained = self._retained_remote.get(root) + if retained is None: + retained = (SidebarModel(self.app.schedule_ui), RegistryReads()) + self._retained_remote[root] = retained + sidebar, registry_reads = retained return self.observation.adopt(RemoteObserving( - SidebarModel(self.app.schedule_ui), ObservationProcess(connection), + sidebar, ObservationProcess(connection), + registry_reads=registry_reads, connection=connection, served_root=root, access=self)) @handles(RevisionObserved) @@ -1415,10 +1501,8 @@ def resume(self) -> None: self.route_task = asyncio.create_task(self.resume_route()) async def resume_route(self) -> None: - previous = self.observation await self.preparation.run_thread(self.reopen_current) - if not previous.is_current(): - self.events.publish(CoordinationObserved(self.revision)) + self.events.publish(CoordinationObserved(self.revision)) async def observe_route(self) -> None: """A changed route selection opens (and observes) the newly selected service.""" diff --git a/src/toad/client/sidebar_state.py b/src/toad/client/sidebar_state.py index da8c6ea9e..6179a383d 100644 --- a/src/toad/client/sidebar_state.py +++ b/src/toad/client/sidebar_state.py @@ -212,11 +212,13 @@ def bind_failed_observation(self, observed: FailedObservation) -> None: def bind_observation(self, observed: Observing) -> None: if self.model_state.observes(observed): return + same_root = self.model_state.serves(observed.root) self.unsubscribe() self.model_state = Behind(observed) observed.sidebar.channels.subscribe(self.channels_changed) observed.sidebar.threads.subscribe(self.threads_changed) - self.model_replaced() + if not same_root: + self.model_replaced() self.present() def channels_changed(self, changes: Changes[str]) -> None: diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index aa7450cac..a5995294c 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -495,7 +495,7 @@ def prepare_inline( 1-line summary or collapsed tool call) immediately using the already-warm `self.renderer` so it lays out in one frame (< 1 ms) without a RenderProcessPool round-trip.""" - if width <= 0 or not fragment.has_blocks: + if self._stopped or width <= 0 or not fragment.has_blocks: return False blocks = tuple(fragment.line_blocks) if not blocks or not all(block.renders_inline for block in blocks): @@ -514,7 +514,7 @@ def prepare_inline( tuple((header, html((header,))) for header in pinned), ) self._row_prepared(key, rendered) - return True + return key in self._prepared TILE = 256 """Pixels of a row's height one picture holds. A row is as tall as its message, and a diff --git a/src/toad/qt/transcript_history.py b/src/toad/qt/transcript_history.py index 0add817bf..adee8ea21 100644 --- a/src/toad/qt/transcript_history.py +++ b/src/toad/qt/transcript_history.py @@ -34,6 +34,13 @@ class QtTranscriptHistory(QtConversationHistory, CommittedHistoryBase, ReportsCo fragment_classes = QT_FRAGMENT_CLASSES + @property + def undrawn(self) -> bool: + """Transcript pages carry `TranscriptCursor`, not wire `AfterMessage` cursors; + match Textual's `TranscriptHistory` (`HistoryPager.undrawn`) so arrival capture + never calls wire-only `.requires_read()` on `NoNativeTranscriptCursor`.""" + return not self.draws_rows + @classmethod def initial_state(cls, view): """Start a bound thread unread, so mounting requests its first saved page. diff --git a/src/toad/qt/virtual_scroll.py b/src/toad/qt/virtual_scroll.py index 5e8667e8e..f705d8c0c 100644 --- a/src/toad/qt/virtual_scroll.py +++ b/src/toad/qt/virtual_scroll.py @@ -412,6 +412,7 @@ class RowDocumentStore(ABC): MAX_DOCUMENTS = 500 ROW_PADDING = 0 MEASURE_SLICE_SECONDS = 0.008 + SUSPEND_RELEASE_MS = 60_000 def __init__(self) -> None: self.view: DetachedCanvas | VirtualRowCanvas = DetachedCanvas() @@ -436,6 +437,10 @@ def __init__(self) -> None: self._measure_timer.setSingleShot(True) self._measure_timer.setInterval(0) self._measure_timer.timeout.connect(self._measure_slice) + self._suspend_release_timer = QTimer() + self._suspend_release_timer.setSingleShot(True) + self._suspend_release_timer.setInterval(self.SUSPEND_RELEASE_MS) + self._suspend_release_timer.timeout.connect(self.release_documents) self._arrivals_moved_rows = False app = QGuiApplication.instance() if app is not None: @@ -445,6 +450,7 @@ def bind_view(self, view: VirtualRowCanvas) -> None: self.view = view self._viewport_update_timer.setParent(view) self._measure_timer.setParent(view) + self._suspend_release_timer.setParent(view) def set_scroll_paused(self, paused: bool) -> None: """Pause background off-screen row measurement during active finger drag or fling.""" @@ -649,8 +655,14 @@ def _update_viewport(self) -> None: self.view.rows_repainted() def _application_state_changed(self, state: Qt.ApplicationState) -> None: + """Defer dropping laid-out documents and tiles across brief Android app switches so + reopening within `SUSPEND_RELEASE_MS` paints from warm caches without a 100+ ms + re-layout/re-rasterize stall, while prolonged backgrounding still returns memory.""" if state is Qt.ApplicationState.ApplicationSuspended: - self.release_documents() + if not self._stopped and not self._suspend_release_timer.isActive(): + self._suspend_release_timer.start() + elif state is Qt.ApplicationState.ApplicationActive: + self._suspend_release_timer.stop() def release_documents(self) -> None: self._documents.clear() @@ -827,6 +839,7 @@ def cleanup(self) -> None: self.preparing = False self._viewport_update_timer.stop() self._measure_timer.stop() + self._suspend_release_timer.stop() self.preparer.clear() self.stop_preparation() self.preparer.stop() diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index c2f5abcd6..f1eb6448d 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -2287,6 +2287,7 @@ def user_identity(self, project): access = SimpleNamespace( observation=None, + _last_observed_root=None, sidebar_waiters=[], sidebar_views=(), revision=None, diff --git a/tests/model/test_android_resync_lazy_load_catchup.py b/tests/model/test_android_resync_lazy_load_catchup.py index 6feaf191d..b2550b987 100644 --- a/tests/model/test_android_resync_lazy_load_catchup.py +++ b/tests/model/test_android_resync_lazy_load_catchup.py @@ -17,9 +17,19 @@ 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.remote_core import ( + ConnectorClosed, + ConnectorObserverClosed, + ServiceFailed, +) 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 agent_comms.ui_model.sidebar import SidebarModel +from PySide6.QtCore import Qt +from PySide6.QtGui import QFont +from PySide6.QtWidgets import QApplication +from yarl import URL from toad.client.application import ACTIVE_PRESENCE from toad.client.committed_presentation import ( @@ -30,6 +40,7 @@ RetainViewportCommit, ) from toad.client.connection import ( + OBSERVATION_FAILURE_REPORT, ClosedObservation, CoordinationAccess, FailedObservation, @@ -37,6 +48,11 @@ RemoteObserving, UnselectedRoute, ) +from toad.client.sidebar_state import SidebarStateMachine +from toad.qt.history import HistoryRowDelegate, RowPictures +from toad.qt.lines import QtLineRenderer +from toad.qt.transcript_history import QtTranscriptHistory +from toad.qt.window import PRESENCE_TRANSITIONS from toad.client.history_pager import ( NEWER_END, OLDER_END, @@ -87,6 +103,18 @@ def observe(self, access: CoordinationAccess): access.observation = fresh return fresh + def resume_observe(self, access: CoordinationAccess, served_root: Path): + calls.append(f"resume_observe:{served_root}") + fresh = RemoteObserving( + sidebar=SimpleNamespace(), + process=SimpleNamespace(), + connection=self, + served_root=served_root, + access=access, + ) + access.observation = fresh + return fresh + class FakePreparation: async def run_thread(self, fn, *args, **kwargs): return fn(*args, **kwargs) @@ -116,7 +144,7 @@ async def run_thread(self, fn, *args, **kwargs): assert not access.retry.waiting(time.monotonic()) await access.route_task - assert calls == ["reset_connections", "observe"] + assert calls == ["reset_connections", "resume_observe:/bus"] assert access.observation is not old_obs assert len(events_published) == 1 and isinstance(events_published[0], CoordinationObserved) @@ -140,10 +168,6 @@ def test_focus_returned_clears_failed_backoff_and_ignores_closed(): def test_application_presence_distinguishes_suspend_from_focus_loss(): - from PySide6.QtCore import Qt - - from toad.qt.window import PRESENCE_TRANSITIONS - actions: list[str] = [] app = SimpleNamespace( application=SimpleNamespace(backgrounded=lambda: actions.append("backgrounded")), @@ -162,12 +186,13 @@ def test_application_presence_distinguishes_suspend_from_focus_loss(): presence = PRESENCE_TRANSITIONS[Qt.ApplicationState.ApplicationActive](presence, app) assert actions == ["backgrounded", "focus_returned", "reload"] - # Android suspend + transient inactive -> full resume (recycles sockets + fresh observation) + # Android suspend + transient inactive -> full resume (recycles sockets + fresh observation; + # reload runs via CoordinationObserved once the new observer attaches, not racing the old one) actions.clear() presence = PRESENCE_TRANSITIONS[Qt.ApplicationState.ApplicationSuspended](presence, app) presence = PRESENCE_TRANSITIONS[Qt.ApplicationState.ApplicationInactive](presence, app) presence = PRESENCE_TRANSITIONS[Qt.ApplicationState.ApplicationActive](presence, app) - assert actions == ["backgrounded", "resume", "reload"] + assert actions == ["backgrounded", "resume"] @pytest.mark.asyncio @@ -653,3 +678,138 @@ def publish_committed(self) -> None: assert op.coverage.summary == "Saved history available" assert published_calls == ["publish_committed"] assert painted_calls == ["cursor-1"] + + +# --- Bug 5: Quiet transient disconnects, same-root reconnect caching, and phone log crashes --- + + +def test_observation_failure_report_quiets_transient_disconnects_and_surfaces_real_crashes(): + logged: list[str] = [] + fatals: list[Exception] = [] + shown: list[tuple[Exception, str]] = [] + app = SimpleNamespace( + log_error=logged.append, + report_fatal=fatals.append, + show_error=lambda err, title: shown.append((err, title)), + ) + url = URL("https://ts-gaming.tail553874.ts.net/observe") + + # Transient remote socket close / EOF -> log quietly, zero popup toasts. + OBSERVATION_FAILURE_REPORT.dispatch_sync( + ConnectorObserverClosed(url, ConnectorClosed()), app, None + ) + OBSERVATION_FAILURE_REPORT.dispatch_sync( + OSError("got end of file during message"), app, "Thread status unavailable" + ) + assert len(logged) == 2 + assert fatals == [] + assert shown == [] + + # Real remote service traceback and local observer death -> still surfaced. + svc_err = ConnectorObserverClosed(url, ServiceFailed("Traceback: boom")) + local_err = ObserverDied("killed") + OBSERVATION_FAILURE_REPORT.dispatch_sync(svc_err, app, None) + OBSERVATION_FAILURE_REPORT.dispatch_sync(local_err, app, "Thread status unavailable") + assert fatals == [svc_err] + assert shown == [(local_err, "Thread status unavailable")] + + +def test_same_root_reconnect_retains_notification_cache_and_sidebar_rows(): + replaced: list[str] = [] + + class FakeSidebar(SidebarStateMachine): + def accepts_observation(self) -> bool: + return True + + def sync(self, *, change, reorder: bool = False) -> None: + pass + + def show_status(self, text: str) -> None: + pass + + def hide_status(self) -> None: + pass + + def coordination_access(self): + return SimpleNamespace(update_sidebar_interest=lambda: None) + + def model_replaced(self) -> None: + replaced.append("replaced") + + sidebar_view = FakeSidebar() + root_a = Path("/bus-a") + root_b = Path("/bus-b") + obs_a1 = RemoteObserving( + sidebar=SidebarModel(lambda cb: None), + process=SimpleNamespace(), + connection=SimpleNamespace(), + served_root=root_a, + access=SimpleNamespace(), + ) + obs_a2 = RemoteObserving( + sidebar=obs_a1.sidebar, + process=SimpleNamespace(), + connection=SimpleNamespace(), + served_root=root_a, + access=SimpleNamespace(), + ) + obs_b = RemoteObserving( + sidebar=SidebarModel(lambda cb: None), + process=SimpleNamespace(), + connection=SimpleNamespace(), + served_root=root_b, + access=SimpleNamespace(), + ) + + sidebar_view.bind_observation(obs_a1) + assert replaced == ["replaced"] + assert obs_a2.retains_root_cache(root_a) is True + assert obs_b.retains_root_cache(root_a) is False + + # Same-root reconnect keeps rows in place without wiping the tree. + sidebar_view.bind_observation(obs_a2) + assert replaced == ["replaced"] + + # Switching to a different bus root clears old rows. + sidebar_view.bind_observation(obs_b) + assert replaced == ["replaced", "replaced"] + + +def test_qt_transcript_history_undrawn_and_stopped_prepare_inline_do_not_crash(): + _app = QApplication.instance() or QApplication([]) + + # QtTranscriptHistory.undrawn uses draws_rows, never wire-only page.after.requires_read(). + hist = object.__new__(QtTranscriptHistory) + hist.pages = (SimpleNamespace(shown_fragments=()),) + assert hist.undrawn is True + hist.pages = (SimpleNamespace(shown_fragments=(SimpleNamespace(has_blocks=True),)),) + assert hist.undrawn is False + + # Stopped delegate: prepare_inline returns False instead of letting final_document_for KeyError. + delegate = HistoryRowDelegate( + QtLineRenderer.__new__(QtLineRenderer), + RowPictures(1024), + SimpleNamespace(), + ) + delegate._stopped = True + frag = SimpleNamespace( + key="k", + shown=None, + revision=0, + has_blocks=True, + line_blocks=(SimpleNamespace(renders_inline=True),), + header_blocks=0, + pinned_dividers=(), + ) + assert delegate.prepare_inline(frag, QFont(), 320) is False + + # Brief Android suspend defers release_documents instead of wiping warm caches immediately. + released: list[str] = [] + delegate._stopped = False + delegate.release_documents = lambda: released.append("released") # type: ignore[method-assign] + delegate._application_state_changed(Qt.ApplicationState.ApplicationSuspended) + assert released == [] + assert delegate._suspend_release_timer.isActive() + delegate._application_state_changed(Qt.ApplicationState.ApplicationActive) + assert not delegate._suspend_release_timer.isActive() + assert released == []