From cd4c88909972e6281922b4f2a019bf91bf723794 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 01:59:10 -0500 Subject: [PATCH] Fix disconnect black screen and stop WireView RPC storm on activity/read ticks --- src/toad/client/connection.py | 13 +++ src/toad/client/history.py | 48 ++++++-- src/toad/client/prepared_pages.py | 5 + src/toad/qt/page.py | 4 + src/toad/qt/window.py | 6 +- src/toad/widgets/comms_chat.py | 2 + .../test_mobile_chrome_polish_and_suspend.py | 110 ++++++++++++++++++ 7 files changed, 178 insertions(+), 10 deletions(-) diff --git a/src/toad/client/connection.py b/src/toad/client/connection.py index cfc4b1a20..5d8c16f23 100644 --- a/src/toad/client/connection.py +++ b/src/toad/client/connection.py @@ -271,6 +271,12 @@ async def holds_async(self, runtime, access: CoordinationAccess, source: str | P worker thread, while remote connections read their in-memory observation directly.""" return await runtime.run_thread(self.holds, access, source) + def route_replaced(self, access: CoordinationAccess, source: str | Path) -> bool: + """Whether the current observation is live on a *different* bus root than ``source``. + A temporary disconnect (``FailedObservation``) or startup (``Unobserved``) has not + replaced the route and must not hide already-open conversation views.""" + return access.observation.observed().replaces(source) + @abstractmethod def observing(self, access: CoordinationAccess, source: str | Path) -> Observing: """The observation serving ``source``, or the refusal that it is not this Core's.""" @@ -486,6 +492,10 @@ def is_current(self) -> bool: def observes(self, root: str | Path) -> bool: return False + def replaces(self, root: str | Path) -> bool: + """Whether this observation is live on a different bus than ``root``.""" + return False + def serving(self, source: str | Path): """This observation, when ``source`` is the root it observes.""" if not self.observes(source): @@ -883,6 +893,9 @@ def observes(self, root: str | Path) -> bool: """Core's served root as Core spells it; a local member resolves on this machine.""" return Path(root) == self.root + def replaces(self, root: str | Path) -> bool: + return not self.observes(root) + def historical_threads(self, senders: HistoricalSenders) -> tuple[HistoricalThread, ...]: """The preserved identities attached history sources keep, for every sender or one.""" return self.core.call(CommsHistoricalThreadsTool(senders=senders)).threads diff --git a/src/toad/client/history.py b/src/toad/client/history.py index f1567826e..f7a493003 100644 --- a/src/toad/client/history.py +++ b/src/toad/client/history.py @@ -18,7 +18,8 @@ from agent_comms.messaging.message_reference import MessageReference from agent_comms.messaging.messages import Message -from agent_comms.messaging.revision_views import RosterView +from agent_comms.messaging.revision_views import RegistrationsView +from agent_comms.presentation import WireRevision from agent_comms.messaging.notification_reads import LiveNotificationRead from agent_comms.messaging.page_traversal import ( LiveCursor, @@ -226,7 +227,8 @@ def read_visible(self) -> PaintedRead: async def _mark_read(self, snapshot: HistorySourceSnapshot) -> None: if not await self.source_is_current(snapshot): if snapshot.current(self): - self.withdraw_view() + if self.page_source.route_replaced(): + self.withdraw_view() elif self.is_attached: self.mark_visible_after_paint() return @@ -337,12 +339,34 @@ async def _refresh(self) -> SourceWork: _config_revision: ReadState = NoRevision() """The announcement the thread's config (compose, label, status, mentions) was last read at.""" + @staticmethod + def _conversation_stores_changed(seen: ConversationObservation, announced: ReadState) -> bool: + """Whether ``announced`` moved any store that can change this wire conversation's + messages, sequence, or display selection (bus, history, registry, catalog). + Pure activity, read-marker, notification, goal, or expiry ticks need zero RPCs.""" + if isinstance(seen, ConversationRevision) and isinstance(announced, WireRevision): + before = seen.stores + return ( + not before.selection_reusable_from(announced) + or before.bus_seq != announced.bus_seq + or before.bus_changes != announced.bus_changes + ) + return not seen.matches_stores(announced) + + def needs_wire_refresh(self, announced: ReadState) -> bool: + """Whether ``announced`` moved any store affecting this wire conversation's + messages, display selection, or thread config (bus, history, registry, catalog).""" + history = self.message_history + return ( + history.undrawn + or self._conversation_stores_changed(history.page_source.revision, announced) + or announced.changed_since(RegistrationsView(), self._config_revision) + ) + async def _refresh_source(self) -> None: """Read what changed in the conversation and draw it: the history's source work. - The thread's config is read on the first refresh and when the roster moved (the - roster owner's own signal: a channel gets no `thread_presented`), not on every bus - message. (Each frontend's view wrote this sequence; Qt's read the announcement after - the read it describes, so a roster change during the read was counted as seen.)""" + The thread's config is read on the first refresh and when registrations/catalog moved + (RegistrationsView), not on every activity heartbeat or bus message.""" history = self.message_history announced = self.app.coordination_access.revision try: @@ -352,7 +376,7 @@ async def _refresh_source(self) -> None: self._refreshed_from = announced self.submissions.settle() self.source_drawn() - if announced.changed_since(RosterView(), self._config_revision): + if announced.changed_since(RegistrationsView(), self._config_revision): self._config_revision = announced self.read_thread_config() @@ -433,7 +457,7 @@ async def reconcile_finished_source_work(self, event: TranscriptSourceWorkFinish # reads the observer's snapshot, which only now shows it. await self._refresh() return - if source.revision.matches_stores(access.revision): + if not self._conversation_stores_changed(source.revision, access.revision): return snapshot = history.source_snapshot() if not snapshot.current(history): @@ -445,7 +469,7 @@ async def reconcile_finished_source_work(self, event: TranscriptSourceWorkFinish revision = await source.read_revision() if (source is history.page_source and snapshot.current(history) and source.uses_observation(access.observation.observed()) - and not source.revision.matches_stores(revision)): + and self._conversation_stores_changed(source.revision, revision)): await self._refresh() dispatch_sync: Callable[[object], None] @@ -752,6 +776,12 @@ async def route_is_current(self) -> bool: access = self.loader.access return await access.connection.holds_async(self.runtime, access, self.loader.root) + def route_replaced(self) -> bool: + if self.closed: + return False + access = self.loader.access + return access.connection.route_replaced(access, self.loader.root) + def status_thread(self, access): return self.loader.conversation.status_thread(self.loader.root, access) diff --git a/src/toad/client/prepared_pages.py b/src/toad/client/prepared_pages.py index af428d63e..c418c9499 100644 --- a/src/toad/client/prepared_pages.py +++ b/src/toad/client/prepared_pages.py @@ -622,6 +622,11 @@ async def route_is_current(self) -> bool: new ``ReplaceablePageSource`` subclass has to answer; the caller ``HistoryReads.source_is_current`` depends on every source satisfying it.""" + def route_replaced(self) -> bool: + """Whether the active connection has moved to a different bus than this source's. + False during temporary disconnects so open views keep their messages visible.""" + return False + def reads_from(self, root: str | Path) -> bool: """Whether this reader reads a conversation from ``root``; a closed one reads none.""" return False diff --git a/src/toad/qt/page.py b/src/toad/qt/page.py index 378dd7c38..1fa6e7e01 100644 --- a/src/toad/qt/page.py +++ b/src/toad/qt/page.py @@ -33,6 +33,10 @@ def mode(self) -> str: def reload(self) -> None: """A page fed by its own subscription has nothing to read again.""" + def stores_observed(self, revision) -> None: + """Core announced a store revision; reload unless this page knows it is unchanged.""" + self.reload() + def workspace_navigation_owner(self, views) -> NavigationOwner: """What the workspace navigates through while this page is selected (`QtWorkspaceViews.navigation_owner`): nothing, for a page that does not navigate.""" diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 28a6fe9b0..f8c505ab2 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -1554,6 +1554,10 @@ def conversation(self) -> ConversationKind: def reload(self) -> None: self.message_history.page_source.schedule_refresh(self) + def stores_observed(self, revision) -> None: + if self.needs_wire_refresh(revision): + self.reload() + def source_read(self) -> None: self.content_ready.set() @@ -2095,7 +2099,7 @@ def _sync_keyboard_chrome(self) -> None: def stores_changed(self, event: CoordinationObserved, subscription: object) -> None: self.bus_label.present(self) - self.workspace_sessions.selected.reload() + self.workspace_sessions.selected.stores_observed(event.revision) def external_transcript_changed(self, event: ExternalTranscriptChanged, subscription: object) -> None: self.workspace_sessions.external_transcript_changed() diff --git a/src/toad/widgets/comms_chat.py b/src/toad/widgets/comms_chat.py index 7eb4c3fd8..9dd12333f 100644 --- a/src/toad/widgets/comms_chat.py +++ b/src/toad/widgets/comms_chat.py @@ -142,6 +142,8 @@ async def initialize_view(self) -> None: @handles(core_events.CoordinationObserved) async def _coordination_observed(self, event: core_events.CoordinationObserved) -> None: """One canonical observation invalidates commands and the mounted source.""" + if not self.needs_wire_refresh(event.revision): + return self.on_composer("refresh_commands", lambda prompt: prompt.slash_complete.refresh_commands()) await self._refresh() diff --git a/tests/model/test_mobile_chrome_polish_and_suspend.py b/tests/model/test_mobile_chrome_polish_and_suspend.py index 34d8bab96..3e6982876 100644 --- a/tests/model/test_mobile_chrome_polish_and_suspend.py +++ b/tests/model/test_mobile_chrome_polish_and_suspend.py @@ -2,6 +2,8 @@ and virtual-scroll applicationStateChanged cleanup.""" from __future__ import annotations +import asyncio +from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock @@ -11,6 +13,8 @@ from textual.geometry import Spacing from toad.client.application import ACTIVE_PRESENCE, SUSPENDED_PRESENCE +from toad.client.connection import FailedObservation, NotObserving, Observation, Observing, RemoteCoreConnection +from toad.client.history import ReadMarkedHistory, WirePageBuffer from toad.preferences import SavedSettings from toad.qt.side_bar import QtSideBarToggle from toad.qt.virtual_scroll import RowDocumentStore @@ -140,3 +144,109 @@ def preparation_for(self, *args, **kwargs): return None # Must not raise RuntimeError on deleted QTimer after tab cleanup. store._application_state_changed(Qt.ApplicationState.ApplicationSuspended) store._application_state_changed(Qt.ApplicationState.ApplicationActive) + + +def test_disconnect_does_not_withdraw_open_channel_view(): + """Temporary disconnects (`FailedObservation`) and startup (`Unobserved`) must not call + `withdraw_view()` -> `self.view.hide()` on open conversation views; only switching to a + live observation of a *different* bus root replaces the route.""" + + class LiveBus(Observing): + def __init__(self, root_path: Path): + self._root = root_path + + @property + def root(self) -> Path: + return self._root + + @property + def core(self): + return MagicMock() + + def opened_selection(self, access): + return None + + async def read(self, request): + return None + + def subscribe_notifications(self, view, build_read): + return False + + def user_identity(self, project): + return None + + failed = FailedObservation(ConnectionError("offline"), selection=MagicMock(), access=MagicMock()) + pending = NotObserving(access=MagicMock()) + same_bus = LiveBus(Path("/bus-a")) + other_bus = LiveBus(Path("/bus-b")) + + assert not failed.replaces("/bus-a") + assert not pending.replaces("/bus-a") + assert not same_bus.replaces("/bus-a") + assert other_bus.replaces("/bus-a") + + withdrawn: list[str] = [] + + def run_mark_read(obs: Observation) -> None: + withdrawn.clear() + access = SimpleNamespace( + observation=SimpleNamespace(observed=lambda: obs), + connection=RemoteCoreConnection.__new__(RemoteCoreConnection), + ) + buf = WirePageBuffer.__new__(WirePageBuffer) + buf.scope = SimpleNamespace(closed=False) + buf.loader = SimpleNamespace(access=access, root=Path("/bus-a")) + buf.runtime = None + + class DummyHistory(ReadMarkedHistory): + page_source = buf + is_attached = True + + async def source_is_current(self, snap): + return False + + def withdraw_view(self) -> None: + withdrawn.append("withdrawn") + + history = DummyHistory.__new__(DummyHistory) + snap = SimpleNamespace(current=lambda h: True) + asyncio.run(history._mark_read(snap)) + + run_mark_read(failed) + assert withdrawn == [], "Internet disconnect must leave the channel view visible" + run_mark_read(pending) + assert withdrawn == [], "Unobserved startup state must leave the channel view visible" + run_mark_read(other_bus) + assert withdrawn == ["withdrawn"], "Switching to a different bus root withdraws old tabs" + + +def test_wire_view_skips_rpc_storm_on_pure_activity_or_read_ticks(): + """Activity heartbeats, read marks, notifications, goal ticks, and expiry ticks must not + trigger `comms_conversation_revision` / `comms_latest_sequence` / `comms_wire_revision` + RPCs when bus_seq, bus_changes, history, registry, and catalog did not move.""" + from dataclasses import replace + + from agent_comms.messaging.revision_views import RegistrationsView + from agent_comms.presentation import WireRevision + from agent_comms.storage.file_observation import FileIdentity, FileRevision + from toad.client.history import ConversationRevision, WireView + + base = WireRevision.empty() + seen = ConversationRevision(stores=base, selection=MagicMock()) + rev = lambda n: FileRevision(FileIdentity(device=1, inode=n), size=10 * n, mtime_ns=n, ctime_ns=n) + + # Pure activity / reads / expiry / notification ticks -> unchanged for wire history & config. + activity_tick = replace(base, expiry_tick=90, notification_evidence=5, + activity=(rev(1),), reads=(rev(2),)) + assert not WireView._conversation_stores_changed(seen, activity_tick) + assert not activity_tick.changed_since(RegistrationsView(), base) + + # New bus message -> bus_seq advances -> must refresh wire history (not thread config). + bus_msg = replace(base, bus_seq=1) + assert WireView._conversation_stores_changed(seen, bus_msg) + assert not bus_msg.changed_since(RegistrationsView(), base) + + # Registry / catalog change -> must refresh both wire history and thread config. + reg_change = replace(base, catalog=(rev(3),)) + assert WireView._conversation_stores_changed(seen, reg_change) + assert reg_change.changed_since(RegistrationsView(), base)