diff --git a/src/toad/client/history.py b/src/toad/client/history.py index e77bbf3d4..31efe223c 100644 --- a/src/toad/client/history.py +++ b/src/toad/client/history.py @@ -595,11 +595,18 @@ class WireSource(BusQueueSource, ConversationSource): me: str style: WireMessageStyle access: CoordinationAccess = field(kw_only=True) - core: CoreAccess = field(kw_only=True) + fixed_core: CoreAccess | None = field(default=None, kw_only=True) fragments: type[EvidencedFragment] = field(kw_only=True) tail_limit: int = 20 page_limit: int = 40 + @property + def core(self) -> CoreAccess: + """The live CoreAccess: explicit override when supplied (unit tests), else resolved + from the current Observation so opening a view during a disconnect never fails in + `__init__` and reconnecting automatically picks up the fresh CoreAccess.""" + return self.fixed_core if self.fixed_core is not None else self.access.observation.observed().core + def observe(self, seen: ConversationObservation) -> SourceObservation: """The observed state owns how changed or unchanged history is drawn.""" revision = self.core.call(CommsConversationRevisionTool( diff --git a/src/toad/client/history_notifications.py b/src/toad/client/history_notifications.py index b7cb25038..9380a8a7e 100644 --- a/src/toad/client/history_notifications.py +++ b/src/toad/client/history_notifications.py @@ -146,7 +146,7 @@ def can_draw_on_screen(self) -> bool: @property def notification_root(self) -> str: - return str(self.app.source().root) + return self.coordination_root or str(self.app.source().root) def subscribe_notifications(self, references) -> bool: """Route through the current `Observation` so a disconnected or closed observation diff --git a/src/toad/client/history_state.py b/src/toad/client/history_state.py index 93ba41947..ac14e4f63 100644 --- a/src/toad/client/history_state.py +++ b/src/toad/client/history_state.py @@ -33,8 +33,7 @@ ObservationEnded, ObserverUnattached, RouteChangedError, - ConnectionError, - TimeoutError, + OSError, http.client.HTTPException, ) diff --git a/src/toad/client/sidebar_state.py b/src/toad/client/sidebar_state.py index 6179a383d..5424ccc34 100644 --- a/src/toad/client/sidebar_state.py +++ b/src/toad/client/sidebar_state.py @@ -48,6 +48,14 @@ def shows_model(self) -> bool: def serves(self, path) -> bool: return False + def retained_root(self): + """Last observed bus root kept across a transient outage, or None.""" + return None + + def retained_model(self) -> SidebarModel | None: + """Last shown SidebarModel kept across a transient outage, or None.""" + return None + def observes(self, observed: Observing) -> bool: return False @@ -81,6 +89,17 @@ def shows_rows(self, view: SidebarStateMachine) -> bool: @dataclass(frozen=True) class FailedSidebarState(SidebarModelState): observed: FailedObservation + retained_root_path: object = None + retained_sidebar: SidebarModel | None = None + + def serves(self, path) -> bool: + return self.retained_root_path is not None and self.retained_root_path == path + + def retained_root(self): + return self.retained_root_path + + def retained_model(self) -> SidebarModel | None: + return self.retained_sidebar def shows_child(self, view: SidebarStateMachine, child) -> bool: return child is view.unavailable @@ -103,6 +122,12 @@ def root(self): def serves(self, path) -> bool: return self.observed.root == path + def retained_root(self): + return self.observed.root + + def retained_model(self) -> SidebarModel | None: + return self.observed.sidebar + def observes(self, observed: Observing) -> bool: return self.observed is observed @@ -204,9 +229,17 @@ def stop_showing(self) -> None: self.unsubscribe() def bind_failed_observation(self, observed: FailedObservation) -> None: + previous = self.model_state + retained_root = previous.retained_root() + retained_model = previous.retained_model() self.unsubscribe() - self.model_state = FailedSidebarState(observed) - self.model_replaced() + self.model_state = FailedSidebarState( + observed, + retained_root_path=retained_root, + retained_sidebar=retained_model, + ) + if retained_model is None: + self.model_replaced() self.present() def bind_observation(self, observed: Observing) -> None: diff --git a/src/toad/qt/conversation.py b/src/toad/qt/conversation.py index 25f6bfd4f..ce736d244 100644 --- a/src/toad/qt/conversation.py +++ b/src/toad/qt/conversation.py @@ -251,6 +251,10 @@ def mount_composer(self, focus: bool = False) -> None: else: composer, reused = build(), False except Exception as error: + # Keep the placeholder slot resumable instead of stranding a permanently blank box. + self._composer_reserved = reserved + if shiboken6.isValid(self) and shiboken6.isValid(self.messages): + self.messages.viewport().installEventFilter(self) self.app.show_error(error, "Composer mount failed") return if reused: diff --git a/src/toad/qt/float_layer.py b/src/toad/qt/float_layer.py index 1a6098be7..14a1adcf5 100644 --- a/src/toad/qt/float_layer.py +++ b/src/toad/qt/float_layer.py @@ -10,7 +10,7 @@ from __future__ import annotations from PySide6.QtCore import QEvent, QObject, QTimer, Qt -from PySide6.QtWidgets import QFrame, QLabel, QVBoxLayout, QWidget +from PySide6.QtWidgets import QFrame, QLabel, QSizePolicy, QVBoxLayout, QWidget from pyqt_reactive.protocols.widget_adapters import PyQtWidgetMeta from pyqt_reactive.theming import ColorScheme, StatusColorRole from pyqt_reactive.widgets.status_line import NoticeLine @@ -79,6 +79,9 @@ def __init__(self, scheme: ColorScheme, background_hex: str, text: str, role: St layout.setContentsMargins(UiGap.tight, UiGap.tight, UiGap.tight, UiGap.tight) line = NoticeLine(scheme) line.setParent(self) + policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + policy.setHeightForWidth(True) + line.setSizePolicy(policy) line.show_status(text, role) layout.addWidget(line) self.expiry = QTimer(self) @@ -91,7 +94,7 @@ def dismiss(self) -> None: self.hide() self.deleteLater() if (layer := self.parentWidget()) is not None: - layer.adjustSize() + layer.follow_content() def mousePressEvent(self, event) -> None: # noqa: N802 - Qt virtual method name self.dismiss() @@ -175,7 +178,13 @@ def follow_content(self, *_destroyed: object) -> None: def place(self) -> None: window = self.parentWidget() margins = window.contentsMargins() - width = window.width() - margins.left() - margins.right() - self.setFixedWidth(max(1, width)) - self.adjustSize() + width = max(1, window.width() - margins.left() - margins.right()) + self.setFixedWidth(width) + layout = self.layout() + layout.activate() + height = layout.totalHeightForWidth(width) + if height <= 0: + height = self.sizeHint().height() + self.resize(width, max(1, height)) self.move(margins.left(), margins.top()) + layout.activate() diff --git a/src/toad/qt/goal.py b/src/toad/qt/goal.py index 04716c508..78fd9198b 100644 --- a/src/toad/qt/goal.py +++ b/src/toad/qt/goal.py @@ -146,10 +146,12 @@ class QtGoalBar(QtCoreObserver, GoalBarOwner, GoalCollapse, QWidget, metaclass=P document_share = 0.2 - def __init__(self, app: ClientApplication, renderer: QtLineRenderer, peer: ThreadIncarnation) -> None: + def __init__(self, app: ClientApplication, renderer: QtLineRenderer, peer: ThreadIncarnation, + *, root: str | None = None) -> None: super().__init__() self.app, self.peer = app, peer - self.goal_source = CommsGoalSource(app, peer, str(app.source().root)) + self.root = root if root is not None else str(app.source().root) + self.goal_source = CommsGoalSource(app, peer, self.root) self.session = QtGoalSession(self) self.goal_observation = GoalObservation(self) self._goal_display: GoalDisplay = NoGoal() @@ -233,7 +235,7 @@ def mount(self) -> None: self.is_attached = True self.observe_core_callback( self.coordination.events, ThreadRowsChanged, self.rows_changed, - factory=partial(ThreadCallbackSubscription, scope=(str(self.app.source().root), self.peer.name))) + factory=partial(ThreadCallbackSubscription, scope=(self.root, self.peer.name))) self.goal_observation.invalidate() def rows_changed(self, event: ThreadRowsChanged) -> None: diff --git a/src/toad/qt/thread_view.py b/src/toad/qt/thread_view.py index 1361bee1d..3e8d99cbd 100644 --- a/src/toad/qt/thread_view.py +++ b/src/toad/qt/thread_view.py @@ -187,7 +187,9 @@ def _setup_prompt_stack(self, app: QtToadApp, layout: QVBoxLayout, incarnation) The composer is built once the transcript has painted (`reserve_composer`); its slot is reserved here so it lands in order, with the question under it.""" self.thread_activity = QtSessionDetails(self, app.renderer) - self.goal_bar = None if incarnation is None else QtGoalBar(app, app.renderer, incarnation) + self.goal_bar = None if incarnation is None else QtGoalBar( + app, app.renderer, incarnation, root=self.coordination_root + ) self.activity = tuple(row for row in (self.thread_activity, self.goal_bar) if row is not None) self._composer_slot = QVBoxLayout() self._composer_slot.setContentsMargins(0, 0, 0, 0) diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 7f25951d7..cded40e65 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -1246,7 +1246,7 @@ def present(self, **changes: object) -> None: thread here on each observation was 17% of the phone's UI thread during a burst of arrivals (2026-11-18).""" super().present(**changes) - model = self.model_state.shown if self.model_state.shows_model() else None + model = self.model_state.shown if self.model_state.shows_model() else self.model_state.retained_model() if model is None and self.groups: self.groups = {} self.redraw(lambda top: None) @@ -1487,12 +1487,14 @@ def __init__(self, app: QtToadApp, entry: QtHistorySessionEntry) -> None: label = entry.unobserved_tab().label() self._setup_conversation(app) self.message_history = QtWireHistory(self.messages, self, app) - source = app.source() # WireSource IS a BusQueueSource (client/history.py): the submissions read its - # pending/queued/held state as `CommsChatView` does. + # pending/queued/held state as `CommsChatView` does. Resolve live CoreAccess via + # `app.coordination_access` instead of `app.source().core` so opening or restoring + # a tab during a disconnect never crashes `__init__` and reconnects seamlessly. wire = WireSource( - source.root, self.conversation, source.project, entry.viewer, self.configuration_state.fields.ui.message_style(), - access=app.coordination_access, core=source.core, fragments=QtWireFragment) + Path(entry.key.root), self.conversation, entry.project, entry.viewer, + self.configuration_state.fields.ui.message_style(), + access=app.coordination_access, fragments=QtWireFragment) self.queue_source = wire self.message_history.initialize_source(wire) self.message_history.observe_source() @@ -1565,7 +1567,9 @@ def read_thread_config(self) -> None: async def thread_label_read(self) -> None: # The label reads Core's thread references: off the GUI loop, as compose access is. # Read on the loop it held a tab's opening for 104 ms on the desktop (frame probe). - references = await self.app.preparation.run_thread(self.app.source().references) + # Resolve `app.source()` inside `run_thread` so a disconnected FailedObservation + # raises inside the worker where `_refresh_thread_config` catches transient errors. + references = await self.app.preparation.run_thread(lambda: self.app.source().references()) label = self.conversation.label(references) self._composer_label = label self.on_composer("label", lambda composer: composer.labelled(label)) @@ -1590,7 +1594,7 @@ def compose_channel_activity(self) -> Iterator[ChannelActivitySidebar]: def compose_peer_activity(self, peer: ThreadIncarnation) -> Iterator[QtGoalBar | PeerActivity]: # The peer's goal sits over its activity and the composer, as the TUI's goal bar # sits over its prompt. - self.goal_bar = QtGoalBar(self.app, self.app.renderer, peer) + self.goal_bar = QtGoalBar(self.app, self.app.renderer, peer, root=self.coordination_root) yield self.goal_bar self.thread_activity = PeerActivity(self.app, self.app.renderer, peer, self.sync_working) yield self.thread_activity diff --git a/src/toad/widgets/comms_chat.py b/src/toad/widgets/comms_chat.py index cf6dadda3..0ba7d9c0a 100644 --- a/src/toad/widgets/comms_chat.py +++ b/src/toad/widgets/comms_chat.py @@ -116,7 +116,7 @@ async def initialize_view(self) -> None: ) source = WireSource( observed.root, self.conversation, self.project_path, self._me, - self.settings.ui.message_style(), access=self.app.coordination_access, core=observed.core, + self.settings.ui.message_style(), access=self.app.coordination_access, fragments=WireFragment, ) self.queue_source = source diff --git a/tests/model/test_android_resync_lazy_load_catchup.py b/tests/model/test_android_resync_lazy_load_catchup.py index b2550b987..38c20c467 100644 --- a/tests/model/test_android_resync_lazy_load_catchup.py +++ b/tests/model/test_android_resync_lazy_load_catchup.py @@ -3,6 +3,7 @@ from __future__ import annotations import http.client +import socket import threading import time from dataclasses import dataclass @@ -14,6 +15,7 @@ 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.messaging.display_references import ProjectReferences from agent_comms.presentation import NoRevision from agent_comms.transcript.transcript_drafts import NoDraft from agent_comms.transcript.transcripts import TranscriptPage @@ -28,7 +30,8 @@ from agent_comms.ui_model.sidebar import SidebarModel from PySide6.QtCore import Qt from PySide6.QtGui import QFont -from PySide6.QtWidgets import QApplication +from PySide6.QtWidgets import QApplication, QWidget +from pyqt_reactive.theming import ColorScheme, StatusColorRole from yarl import URL from toad.client.application import ACTIVE_PRESENCE @@ -48,9 +51,16 @@ RemoteObserving, UnselectedRoute, ) -from toad.client.sidebar_state import SidebarStateMachine +from toad.client.history import WireSource +from toad.client.history_state import TRANSIENT_SOURCE_ERRORS +from toad.client.sidebar_state import FailedSidebarState, SidebarStateMachine +from toad.markdown_links import LinkContext +from toad.motion import AnimationClock +from toad.preferences import DiffSettings +from toad.qt.float_layer import QtFloatLayer from toad.qt.history import HistoryRowDelegate, RowPictures from toad.qt.lines import QtLineRenderer +from toad.qt.theme import current_scheme from toad.qt.transcript_history import QtTranscriptHistory from toad.qt.window import PRESENCE_TRANSITIONS from toad.client.history_pager import ( @@ -813,3 +823,104 @@ def test_qt_transcript_history_undrawn_and_stopped_prepare_inline_do_not_crash() delegate._application_state_changed(Qt.ApplicationState.ApplicationActive) assert not delegate._suspend_release_timer.isActive() assert released == [] + + +def test_failed_observation_retains_sidebar_model_and_oserror_is_transient(): + # Network-handoff OSErrors (ENETUNREACH, gaierror) are transient, never permanent tab retirement. + assert issubclass(socket.gaierror, TRANSIENT_SOURCE_ERRORS) + assert issubclass(OSError, TRANSIENT_SOURCE_ERRORS) + + # Sidebar retains its last SidebarModel across a transient FailedObservation -> same-root reconnect. + 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(), + ) + failed = FailedObservation(OSError("network unreachable"), UnselectedRoute(), access=SimpleNamespace()) + + sidebar_view.bind_observation(obs_a1) + assert replaced == ["replaced"] + sidebar_view.bind_failed_observation(failed) + assert isinstance(sidebar_view.model_state, FailedSidebarState) + assert sidebar_view.model_state.retained_model() is obs_a1.sidebar + assert sidebar_view.model_state.serves(root_a) is True + assert replaced == ["replaced"] + sidebar_view.bind_observation(obs_a2) + assert replaced == ["replaced"] + sidebar_view.bind_observation(obs_b) + assert replaced == ["replaced", "replaced"] + + # WireSource resolves live CoreAccess dynamically so constructing a tab while disconnected succeeds. + live_core = object() + access = SimpleNamespace(observation=failed) + wire = WireSource( + root_a, SimpleNamespace(), SimpleNamespace(), "user", SimpleNamespace(), + access=access, fragments=SimpleNamespace(), + ) + with pytest.raises(OSError, match="network unreachable"): + _ = wire.core + access.observation = SimpleNamespace(observed=lambda: SimpleNamespace(core=live_core)) + assert wire.core is live_core + + # QtFloatLayer sizes wrapped multi-line error toasts to full heightForWidth instead of clipping. + _app = QApplication.instance() or QApplication([]) + win = QWidget() + win.resize(320, 720) + scheme = current_scheme({"HOME": str(Path.home())}) + cs = ColorScheme.from_theme(scheme) + renderer = QtLineRenderer(scheme, LinkContext(Path("."), ProjectReferences()), DiffSettings()) + clock = AnimationClock(lambda _: None, enabled=False) + layer = QtFloatLayer(cs, renderer, clock, win) + long_msg = ( + "History: OSError: Network is unreachable while reading #model\n" + "Log: /data/data/org.toadcomms.toadcomms/files/state/toad/logs/errors/" + "History_2026-11-27T23_13_56_123456.txt" + ) + layer.post(long_msg, StatusColorRole.ERROR, 5.0) + win.show() + _app.processEvents() + card = layer._notice_cards()[0] + line = card.layout().itemAt(0).widget() + needed = line.heightForWidth(max(1, line.width())) + assert line.height() >= needed + assert layer.height() >= card.height() >= needed diff --git a/tests/textual/test_conversation_kind.py b/tests/textual/test_conversation_kind.py index 201f23faa..f283ce8ca 100644 --- a/tests/textual/test_conversation_kind.py +++ b/tests/textual/test_conversation_kind.py @@ -72,7 +72,7 @@ def test_conversation_family_resolves_copied_pages_and_current_labels( page = conversation.page( WireSource(comms.root, conversation, comms.registry.require(viewer).worktree, viewer, IrcMessageStyle(), access=AppAgents.unrun(tmp_path, LaunchRoot.from_path(comms.root)).app.coordination_access, - core=LocalCoreAccess(comms), fragments=WireFragment), + fixed_core=LocalCoreAccess(comms), fragments=WireFragment), PageBounds(limit=8), ) assert body in [message.body for message in page.messages] diff --git a/tests/textual/test_message_file_chips.py b/tests/textual/test_message_file_chips.py index 478fd67bd..ae91778bd 100644 --- a/tests/textual/test_message_file_chips.py +++ b/tests/textual/test_message_file_chips.py @@ -54,7 +54,7 @@ def test_a_page_draws_each_message_s_files_and_a_chip_fetches_the_sent_bytes(tmp source = WireSource(comms.root, ChannelConversation(ChannelTarget("#team")), project, comms.messaging.user_identity(project).name, IrcMessageStyle(), access=AppAgents.unrun(project.path, LaunchRoot.from_path(comms.root)).app.coordination_access, - core=core, fragments=WireFragment) + fixed_core=core, fragments=WireFragment) through = source.observe(UnobservedConversation()).through prepared = source.read(PageRequest(OLDER_END, through), through) assert core.called.count("comms_message_files") == 1 diff --git a/tests/textual/test_older_bus.py b/tests/textual/test_older_bus.py index d1d4a4da4..1e72f0870 100644 --- a/tests/textual/test_older_bus.py +++ b/tests/textual/test_older_bus.py @@ -82,7 +82,7 @@ def test_a_page_from_an_older_bus_draws_its_messages_and_asks_it_for_no_files(tm source = WireSource(comms.root, ChannelConversation(ChannelTarget("#team")), project, comms.messaging.user_identity(project).name, IrcMessageStyle(), access=AppAgents.unrun(project.path, LaunchRoot.from_path(comms.root)).app.coordination_access, - core=core, fragments=WireFragment) + fixed_core=core, fragments=WireFragment) through = source.observe(UnobservedConversation()).through prepared = source.read(PageRequest(OLDER_END, through), through) assert len(prepared.fragments) == 2 diff --git a/tests/textual/test_wire_source.py b/tests/textual/test_wire_source.py index d0d0302fb..c2e28ece4 100644 --- a/tests/textual/test_wire_source.py +++ b/tests/textual/test_wire_source.py @@ -36,7 +36,7 @@ def channel_source(comms, target, project): viewer = comms.messaging.user_identity(project).name return WireSource(comms, ChannelConversation(ChannelTarget(target)), project, viewer, IrcMessageStyle(), access=AppAgents.unrun(project.path, LaunchRoot.from_path(comms.root)).app.coordination_access, - core=LocalCoreAccess(comms), fragments=WireFragment) + fixed_core=LocalCoreAccess(comms), fragments=WireFragment) def observed(source):