diff --git a/src/toad/arrivals.py b/src/toad/arrivals.py index 934589e0d..b540486ec 100644 --- a/src/toad/arrivals.py +++ b/src/toad/arrivals.py @@ -148,6 +148,7 @@ def land(self) -> None: if target is not None and owner.follows_tail: with owner.layout_scroll(): target.land(owner) + owner.request_preparation() if self.keys: owner.repaint_arrival_keys(self.keys) @@ -263,6 +264,9 @@ def follow_end(self) -> None: """Place the window at its followed tail (toolkits with a specialized jump override).""" self.scroll_y = self.tail_scroll_y + def request_preparation(self) -> None: + """Prepare the viewport after an arrival scroll lands; paging windows override.""" + # ---- Shared semantic operations ---- def arrive_fragments(self, fragments: Sequence[HistoryFragment], *, live: bool = False) -> None: diff --git a/src/toad/client/connection.py b/src/toad/client/connection.py index 2ae440497..338b21434 100644 --- a/src/toad/client/connection.py +++ b/src/toad/client/connection.py @@ -484,6 +484,16 @@ def stop_updates(self) -> Observation: def retire(self, access: CoordinationAccess) -> None: """An observation without a process has nothing to retire.""" + def pending_notification_views(self) -> tuple[NotificationSubscriber, ...]: + """Notification subscribers retained while this observation could not subscribe them.""" + return () + + def rebind_notifications(self, subscribers: tuple[NotificationSubscriber, ...]) -> None: + """Re-attach active notification views once this observation becomes current.""" + + def discard_notification_view(self, view: NotificationSubscriber) -> None: + """Forget a view that stopped showing notifications before this observation ended.""" + def activate(self, access: CoordinationAccess): """The new current observation shows itself in every view following the sidebar, hidden or shown: a failure as the failure, a reopened service as its rows. This is @@ -500,6 +510,9 @@ def attach(self, access, previous): for _, waiter in waiters: if not waiter.done(): waiter.set_exception(RouteChangedError("Comms service changed before the sidebar was read")) + subscribers = tuple(dict.fromkeys(( + *access.notification_views, *previous.pending_notification_views(), + ))) access.revision = NoRevision() access.sidebar_interest = access.sidebar_current = None access.team_interest = StopTeamHud() @@ -509,6 +522,7 @@ def attach(self, access, previous): access.notification_known.clear() access.notification_interest = ObserveNotifications(frozenset()) self.activate(access) + self.rebind_notifications(subscribers) access.events.publish(ObservedServiceChanged()) @@ -647,6 +661,18 @@ def observe_notifications(self, wanted: ObserveNotifications): for view in tuple(self.access.notification_views): view.notifications_failed(self.error) + def pending_notification_views(self) -> tuple[NotificationSubscriber, ...]: + return tuple(self.failed_notification_views) + + def rebind_notifications(self, subscribers: tuple[NotificationSubscriber, ...]) -> None: + for view in subscribers: + if view not in self.failed_notification_views: + self.failed_notification_views.add(view) + view.notifications_failed(self.error) + + def discard_notification_view(self, view: NotificationSubscriber) -> None: + self.failed_notification_views.discard(view) + def subscribe_notifications( self, view: NotificationSubscriber, build_read: Callable[[str], ReadNotifications], ) -> bool: @@ -918,6 +944,10 @@ def observe_sidebar(self, wanted): def observe_notifications(self, wanted: ObserveNotifications): self.tell(wanted) + def rebind_notifications(self, subscribers: tuple[NotificationSubscriber, ...]) -> None: + for view in subscribers: + view.rebind_notifications() + def subscribe_notifications( self, view: NotificationSubscriber, build_read: Callable[[str], ReadNotifications], ) -> bool: @@ -1186,6 +1216,7 @@ def stop_notifications(self, view: NotificationSubscriber) -> bool: """Whether `view` was showing a read.""" shown = view in self.notification_views self.notification_views.pop(view, None) + self.observation.discard_notification_view(view) self._request_interest() return shown diff --git a/src/toad/client/history_notifications.py b/src/toad/client/history_notifications.py index d04406aab..c32dcf492 100644 --- a/src/toad/client/history_notifications.py +++ b/src/toad/client/history_notifications.py @@ -121,6 +121,13 @@ def notifications_reload(self) -> None: if self.can_draw_on_screen: self.run_notification_work(self._reload_notification_sources()) + def rebind_notifications(self) -> None: + """Core's observation attached anew (reconnect, restart, or mobile resume): drop the + old read key and re-subscribe the visible messages on the new observation.""" + self.checked_references = None + if self.can_draw_on_screen: + self.check_notifications_after_refresh() + async def _reload_notification_sources(self): for target in self.notification_targets(): await target.reload_notification_source() diff --git a/src/toad/client/history_pager.py b/src/toad/client/history_pager.py index 38b1e9265..f52d3c420 100644 --- a/src/toad/client/history_pager.py +++ b/src/toad/client/history_pager.py @@ -320,6 +320,8 @@ def layout_scroll(self): if not restoring: if rows := self.scroll_y - previous: self.shift_travel(rows, destination) + if not self.gliding_to_end(): + self.request_preparation() self.lookahead.relocated(rows) finally: self._restoring = restoring diff --git a/src/toad/client/subscribers.py b/src/toad/client/subscribers.py index a0616b75e..7c0d987ce 100644 --- a/src/toad/client/subscribers.py +++ b/src/toad/client/subscribers.py @@ -185,3 +185,7 @@ def notifications_failed(self, error: Exception) -> None: def notifications_reload(self) -> None: raise NotImplementedError + + def rebind_notifications(self) -> None: + """Core's observation changed or reconnected; subscribe this view's visible reads again.""" + raise NotImplementedError diff --git a/src/toad/qt/goal.py b/src/toad/qt/goal.py index ab6d9c6ac..04716c508 100644 --- a/src/toad/qt/goal.py +++ b/src/toad/qt/goal.py @@ -263,10 +263,24 @@ def show_goal_text(self, objective: str, progress: str, shows_progress: bool) -> self.fit_document() def fit_document(self) -> None: - """The document is as tall as its text, up to its share of the window.""" + """The document is as tall as its wrapped text at the viewport width, up to its share + of the window.""" body = self.document.widget() - cap = int(QWidget.window(self).height() * self.document_share) or body.sizeHint().height() - self.document.setFixedHeight(max(1, min(body.sizeHint().height(), cap))) + width = self.document.viewport().width() + if width <= 0: + margins = self.layout().contentsMargins() + width = max(0, self.width() - margins.left() - margins.right()) + content_height = ( + body.heightForWidth(width) + if width > 0 and body.hasHeightForWidth() + else body.sizeHint().height() + ) + cap = int(QWidget.window(self).height() * self.document_share) or content_height + self.document.setFixedHeight(max(1, min(content_height, cap))) + + def showEvent(self, event) -> None: # type: ignore[override] + super().showEvent(event) + self.fit_document() def resizeEvent(self, event) -> None: # type: ignore[override] super().resizeEvent(event) diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index 592c3017a..8ac197019 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -2237,3 +2237,190 @@ def _counting_new_doc(f, w): assert new_doc_calls == 3 finally: delegate.cleanup() + + +def test_observation_attach_rebinds_notification_views_across_resume_and_reconnect(): + from types import SimpleNamespace + from weakref import WeakKeyDictionary + from agent_comms.messaging.notification_reads import LiveNotificationRead + from agent_comms.ui_model.observation import ObserveNotifications, ReadNotifications + from toad.client.connection import FailedObservation, Observation, Observing + from toad.client.subscribers import NotificationSubscriber + + class _View(NotificationSubscriber): + def __init__(self) -> None: + self.rebound = 0 + self.failed: list[Exception] = [] + + def notifications_observed(self, outcomes) -> None: + pass + + def notifications_failed(self, error: Exception) -> None: + self.failed.append(error) + + def notifications_reload(self) -> None: + pass + + def rebind_notifications(self) -> None: + self.rebound += 1 + + class _FakeObserving(Observing): + root = Path("/tmp/fake-bus") + + def activate(self, access) -> None: + pass + + @property + def core(self): + raise AssertionError("unused") + + def opened_selection(self): + return None + + def user_identity(self, project): + raise AssertionError("unused") + + access = SimpleNamespace( + observation=None, + sidebar_waiters=[], + sidebar_views=(), + revision=None, + sidebar_interest=None, + sidebar_current=None, + team_interest=None, + thread_status=MagicMock(), + views_interest=None, + notification_views=WeakKeyDictionary(), + notification_known={}, + notification_interest=ObserveNotifications(frozenset()), + events=MagicMock(), + ) + + obs1 = _FakeObserving(sidebar=MagicMock(), process=MagicMock(), access=access) + obs2 = _FakeObserving(sidebar=MagicMock(), process=MagicMock(), access=access) + failed = FailedObservation(RuntimeError("socket reset"), None, access=access) + obs3 = _FakeObserving(sidebar=MagicMock(), process=MagicMock(), access=access) + + view_live = _View() + view_closed = _View() + read = ReadNotifications("/tmp/fake-bus", LiveNotificationRead(())) + + # 1. Android resume (Observing -> Observing) rebinds every active notification view. + access.observation = obs2 + access.notification_views[view_live] = read + access.notification_views[view_closed] = read + obs2.attach(access, obs1) + assert view_live.rebound == 1 + assert view_closed.rebound == 1 + assert len(access.notification_views) == 0 + + # 2. Disconnect -> reconnect (Observing -> FailedObservation -> Observing) preserves + # live views and drops views closed during the outage. + access.notification_views[view_live] = read + access.notification_views[view_closed] = read + access.observation = failed + failed.attach(access, obs2) + assert len(view_live.failed) == 1 + assert len(view_closed.failed) == 1 + failed.discard_notification_view(view_closed) + + access.observation = obs3 + obs3.attach(access, failed) + assert view_live.rebound == 2 + assert view_closed.rebound == 1 + + +def test_arrival_glide_and_layout_scroll_request_preparation(): + from toad.arrivals import AnimatesArrivals, ViewportArrival + from toad.client.history_pager import ReaderPlacement + from toad.client.reader_position import TAIL_ARRIVAL_TARGET + + class _Window(AnimatesArrivals, ReaderPlacement): + def __init__(self) -> None: + self._restoring = False + self.scroll_y = 0.0 + self.scroll_target_y = 0.0 + self.tail_scroll_y = 240.0 + self.follows_tail = True + self.lookahead = MagicMock() + self.preparations = 0 + self._clock = AnimationClock(lambda _interval: None) + + @property + def animation_clock(self) -> AnimationClock: + return self._clock + + @property + def arrival_animation_visible(self) -> bool: + return True + + def arrival_rows_height(self, keys): + return 80.0 + + def repaint_arrival_keys(self, keys) -> None: + pass + + def shift_travel(self, rows: float, destination: float) -> None: + pass + + def request_preparation(self) -> None: + self.preparations += 1 + + win = _Window() + # Non-glide programmatic layout scroll requests preparation once. + with win.layout_scroll(): + win.scroll_y = 100.0 + assert win.preparations == 1 + + # Mid-glide ticks must NOT spam preparation, while landing requests it once. + arrival = ViewportArrival(win, ("row-1",)) + win.arrivals.append(arrival) + arrival.attach_scroll(100.0, TAIL_ARRIVAL_TARGET, 240.0) + win.glide = arrival + arrival.apply_amount(0.5) + assert win.preparations == 1 + arrival.land() + assert win.scroll_y == 240.0 + assert win.preparations >= 2 + + +def test_qt_goal_bar_fit_document_uses_wrapped_height_for_width(monkeypatch): + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + app = QApplication.instance() or QApplication([]) + from PySide6.QtWidgets import QScrollArea, QVBoxLayout + from toad.qt.goal import QtGoalBar, WrappedText + + win = QWidget() + win.resize(412, 915) + bar = QWidget(win) + bar.resize(412, 200) + lay = QVBoxLayout(bar) + lay.setContentsMargins(8, 4, 8, 4) + doc = QScrollArea(bar) + doc.setWidgetResizable(True) + body = QWidget(doc) + body_lay = QVBoxLayout(body) + body_lay.setContentsMargins(0, 0, 0, 0) + obj = WrappedText() + obj.setText( + "Objective: Ship Android/Qt Toad mobile UX fixes (IME adjustResize/safe-area, " + "tab close, sidebar bands), profile & fix Pixel 8a scroll FPS with FrameProbe" + ) + body_lay.addWidget(obj) + body_lay.addStretch(1) + doc.setWidget(body) + lay.addWidget(doc) + bar.document = doc + bar.document_share = QtGoalBar.document_share + try: + win.show() + app.processEvents() + unwrapped_h = body.sizeHint().height() + QtGoalBar.fit_document(bar) + assert doc.height() > unwrapped_h + assert doc.height() == min( + body.heightForWidth(doc.viewport().width()), + int(win.height() * QtGoalBar.document_share), + ) + finally: + win.deleteLater() diff --git a/tools/android/bundle_check.py b/tools/android/bundle_check.py index b60a03cf0..6ba953eec 100644 --- a/tools/android/bundle_check.py +++ b/tools/android/bundle_check.py @@ -228,12 +228,15 @@ def lazy_findings(self, loaded: set[str]) -> dict[str, list[ImportSite]]: "blank and sys.exit(f'error: application actions with an empty summary at -O{sys.flags.optimize}: {blank}'); " "from agent_comms.installer.harness_install import HarnessSession; " "'claude_bridge' in HarnessSession.__registry__ or sys.exit('error: HarnessSession discovery missed claude_bridge'); " + "from agent_comms.cli_verbs.thread import ThreadCliCommand; " "from agent_comms.coordination.tables.assignments import WakeAssignment; " + "from agent_comms.nominal.field_codec import FieldCodec; " "from agent_comms.planning.goal_ledger import FailedTurnEvidence; " "from agent_comms.ui_model.teammate_state import TeammateState; " "FailedTurnEvidence.recorded_member(FailedTurnEvidence.declared_name) is FailedTurnEvidence or sys.exit('error: FailedTurnEvidence lookup failed'); " "WakeAssignment.recorded_member(WakeAssignment.declared_name) is WakeAssignment or sys.exit('error: WakeAssignment lookup failed'); " "all(issubclass(TeammateState.recorded_member(n), TeammateState) for n in ('idle', 'blocked', 'moving', 'spinning')) or sys.exit('error: TeammateState lookup failed'); " + "FieldCodec.encode(ThreadCliCommand(name='probe'))['kind'] == 'thread' or sys.exit('error: ThreadCliCommand encode failed'); " "print('shipped app imports toad.qt.main; every application action has a summary'); print(json.dumps(sorted(sys.modules)))")], capture_output=True, text=True, timeout=120, cwd=recipes, check=False, env=os.environ | {"PYTHONOPTIMIZE": str(optimize)})