diff --git a/src/toad/client/relationship_tree_state.py b/src/toad/client/relationship_tree_state.py index c40e4cd0b..4191c7157 100644 --- a/src/toad/client/relationship_tree_state.py +++ b/src/toad/client/relationship_tree_state.py @@ -6,9 +6,11 @@ """ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass, field from toad.client.panel_source import PanelSource +from toad.client.relationship_row_menu import entry_target @dataclass @@ -21,8 +23,8 @@ class RelationshipTreeState: class RelationshipPanel(PanelSource): """The thread sidebar's Comms panel as both frontends hold it: Textual's `ThreadCommsSidebar` and Qt's `QtThreadCommsPanel` inherit this. It keeps each thread's - tree state across binds, says whose relationships these are, and decides which entries - the sidebar's search keeps.""" + tree state across binds, says whose relationships these are, re-reads relationships before + opening a row, and warns on a stale entry or wrong bus.""" wrong_bus_warning = "This view is on a different bus — switch to that bus to open it." changed_entry_warning = "This item changed — refreshed the list." @@ -44,3 +46,53 @@ def context_note(snapshot) -> str: @staticmethod def context_tooltip(snapshot) -> str: return f"{snapshot.incoming_basis}\nLatest {snapshot.history_messages} messages" + + def notify_comms_warning(self, message: str) -> None: + raise NotImplementedError + + def refresh_after_changed_entry(self) -> None: + raise NotImplementedError + + def select_relationship_target(self, target) -> None: + raise NotImplementedError + + def open_relationship_target(self, access, target) -> None: + if not self.thread_identity.belongs_to_wire(access.observation.observed().root): + self.notify_comms_warning(self.wrong_bus_warning) + return + self.select_relationship_target(target) + + async def open_current_relationship( + self, + access, + preparation, + group, + entry, + *, + still_current: Callable[[], bool] | None = None, + ) -> None: + """Open the relationship as it stands now: the list read again, and a relationship + that changed since it was drawn is not opened.""" + if not entry.available: + return + is_current = (lambda: True) if still_current is None else still_current + + async def _open(identity) -> None: + if not is_current(): + return + service = await self.observed_source(access, preparation, identity.root_path) + if service is None or not is_current(): + return + snapshot = await preparation.run_thread( + service.relationships, identity.thread_name() + ) + if not is_current(): + return + current = snapshot.current_entry(group, entry) + if current is None: + self.notify_comms_warning(self.changed_entry_warning) + self.refresh_after_changed_entry() + return + self.open_relationship_target(access, entry_target(current)) + + await self.thread_identity.inspect_owner(_open, lambda _text: None) diff --git a/src/toad/qt/context_panel.py b/src/toad/qt/context_panel.py index af30808ac..f4e621036 100644 --- a/src/toad/qt/context_panel.py +++ b/src/toad/qt/context_panel.py @@ -160,29 +160,33 @@ async def _refresh(self, *, force: bool = False) -> None: return self._refresh_task = asyncio.current_task() try: - identity = self.thread_identity - root = identity.root_path - if root is None: - self._status.setText("Context · no thread root") - self._older.setEnabled(False) - self._newer.setEnabled(False) - self._tree.clear() - return - app = self._app - access = app.coordination_access - observed = await self.observed_source(access, app.preparation, root) - if observed is None or identity != self.thread_identity: - return - previous = self.observe_revision(access.revision) - acquired = await self.acquire_inspection(observed, access.revision, identity) - if identity != self.thread_identity: - return - self.receive_inspection(acquired) - self._status.setText(self.state.status) - self.state.present(lambda current: self._inspection_acquired(previous, current, force)) + await self.thread_identity.inspect_owner( + lambda identity: self._refresh_owner(identity, force=force), + self._show_detached, + ) finally: self._refresh_task = None + def _show_detached(self, text: str) -> None: + self._status.setText(f"Context · {text}") + self._older.setEnabled(False) + self._newer.setEnabled(False) + self._tree.clear() + + async def _refresh_owner(self, identity, *, force: bool) -> None: + app = self._app + access = app.coordination_access + observed = await self.observed_source(access, app.preparation, identity.root_path) + if observed is None or identity != self.thread_identity: + return + previous = self.observe_revision(access.revision) + acquired = await self.acquire_inspection(observed, access.revision, identity) + if identity != self.thread_identity: + return + self.receive_inspection(acquired) + self._status.setText(self.state.status) + self.state.present(lambda current: self._inspection_acquired(previous, current, force)) + def show_source_unavailable(self, text: str) -> None: self._status.setText(text) self._tree.clear() diff --git a/src/toad/qt/thread_comms_panel.py b/src/toad/qt/thread_comms_panel.py index 29ecbaff3..3b612ffae 100644 --- a/src/toad/qt/thread_comms_panel.py +++ b/src/toad/qt/thread_comms_panel.py @@ -93,9 +93,11 @@ def __init__(self, app, search: SidebarFilter, parent: QWidget | None = None) -> # The thread sidebar's search narrows the relationship rows, as Textual's # `ThreadCommsSidebar` follows its sidebar's search (`SearchFollower`). self._search = search - search.subscribe(lambda _text: self.present()) + search.subscribe(lambda _text: self._reapply_search()) self._states: dict[SessionIdentity, RelationshipTreeState] = {} self._snapshot: ThreadCommsSnapshot | None = None + self._snapshot_identity: SessionIdentity | None = None + self._revision: object = None self._refresh_task: asyncio.Task | None = None column = QVBoxLayout(self) column.setContentsMargins(UiGap.frame, UiGap.normal, UiGap.frame, UiGap.normal) @@ -144,7 +146,15 @@ def _category_toggled(self, category: type[MessageCategory], on: bool) -> None: self._categories.set_category(category, on) self._sync_checks() - def present(self) -> None: + def _reapply_search(self) -> None: + if self._snapshot is not None and self._snapshot_identity == self.thread_identity: + self._apply(self._snapshot) + else: + self.present() + + def present(self, *, force: bool = False) -> None: + if force: + self._revision = None self._sync_checks() asyncio.ensure_future(self._refresh()) @@ -153,25 +163,32 @@ async def _refresh(self) -> None: return self._refresh_task = asyncio.current_task() try: - identity = self.thread_identity - root = identity.root_path - if root is None: - self._context.setText("No thread root") - self._tree.clear() - return - app = self._app - access = app.coordination_access - service = await self.observed_source(access, app.preparation, root) - if service is None or identity != self.thread_identity: - return - snapshot = await app.preparation.run_thread(service.relationships, identity.thread_name()) - if identity != self.thread_identity: - return - self._apply(snapshot) + await self.thread_identity.inspect_owner( + self._refresh_owner, + self.show_source_unavailable, + ) finally: self._refresh_task = None + async def _refresh_owner(self, identity) -> None: + app = self._app + service = await self.observed_source(app.coordination_access, app.preparation, identity.root_path) + if service is None or identity != self.thread_identity: + return + revision = await app.preparation.run_thread(service.wire_revision) + if identity == self._snapshot_identity and revision == self._revision: + return + snapshot = await app.preparation.run_thread(service.relationships, identity.thread_name()) + if identity != self.thread_identity: + return + self._snapshot_identity = identity + self._revision = revision + self._apply(snapshot) + def show_source_unavailable(self, text: str) -> None: + self._snapshot = None + self._snapshot_identity = None + self._revision = None self._context.setText(text) self._tree.clear() @@ -210,7 +227,11 @@ def _row_entry(self, item: QTreeWidgetItem | None) -> tuple[object, Relationship def _item_clicked(self, item: QTreeWidgetItem) -> None: shown = self._row_entry(item) if shown is not None and shown[1].available: - asyncio.ensure_future(self._open_current(*shown)) + asyncio.ensure_future( + self.open_current_relationship( + self._app.coordination_access, self._app.preparation, *shown + ) + ) def _offer_row_menu(self, point) -> None: """The relationship's own menu (`RelationshipLine.menu_entries`) for the row under @@ -225,32 +246,24 @@ async def _offer_read(self, item: QtRelationshipItem) -> None: self._app.offer_entries(entries) def relationship_opener(self, line: QtRelationshipItem): - """Open reads the list again first (`_open_current`), as Textual's opener does.""" - return lambda: asyncio.ensure_future(self._open_current(line.group, line.entry)) + """Open reads the list again first (`open_current_relationship`), as Textual does.""" + return lambda: asyncio.ensure_future( + self.open_current_relationship( + self._app.coordination_access, self._app.preparation, line.group, line.entry + ) + ) def copy_name(self, name: str) -> None: self._app.copy_to_clipboard(name) - async def _open_current(self, group, entry: RelationshipEntry) -> None: - """Open the relationship as it stands now: the list read again, and a relationship - that changed since it was drawn is not opened (Textual's `_navigate_current`).""" - app = self._app - identity = self.thread_identity - if identity.root_path is None: - return - if identity.root_path != app.coordination_access.observation.observed().root: - app.show_warning(self.wrong_bus_warning, "Comms") - return - service = await self.observed_source(app.coordination_access, app.preparation, identity.root_path) - if service is None: - return - snapshot = await app.preparation.run_thread(service.relationships, identity.thread_name()) - current = snapshot.current_entry(group, entry) - if current is None: - app.show_warning(self.changed_entry_warning, "Comms") - self.present() - return - app.open_target(entry_target(current)) + def notify_comms_warning(self, message: str) -> None: + self._app.show_warning(message, "Comms") + + def refresh_after_changed_entry(self) -> None: + self.present(force=True) + + def select_relationship_target(self, target) -> None: + self._app.open_target(target) def _item_expanded(self, item: QTreeWidgetItem) -> None: group_type = item.data(0, Qt.ItemDataRole.UserRole) @@ -277,4 +290,4 @@ async def write_order(self, order: type[ThreadSort]) -> None: app.preparation, service, identity, snapshot.sortable_groups, order) finally: if identity == self.thread_identity: - self.present() + self.present(force=True) diff --git a/src/toad/widgets/thread_comms.py b/src/toad/widgets/thread_comms.py index 6d86dff80..4c8e54b33 100644 --- a/src/toad/widgets/thread_comms.py +++ b/src/toad/widgets/thread_comms.py @@ -531,20 +531,18 @@ def row_for(self, selection): def navigation_root(self): return self.thread_identity.root_path - def open_target(self, target: NavigationTarget): - identity = self.thread_identity - if ( - identity.root_path - != self.app.coordination_access.observation.observed().root - ): - self.notify( - self.wrong_bus_warning, - title="Comms", - severity="warning", - ) - return + def notify_comms_warning(self, message: str) -> None: + self.notify(message, title="Comms", severity="warning") + + def refresh_after_changed_entry(self) -> None: + self.refresh_relationships(force=True) + + def select_relationship_target(self, target) -> None: self.publish_core(SelectTarget(target)) + def open_target(self, target: NavigationTarget): + self.open_relationship_target(self.app.coordination_access, target) + def request_navigation(self, row, *, entry=None, generation=None): if not row.is_attached: return @@ -554,28 +552,17 @@ def request_navigation(self, row, *, entry=None, generation=None): self.run_worker(self._navigate_current(group, expected, observed_generation)) async def _navigate_current(self, group_key, expected, generation): - if generation != self._generation or not expected.available: - return - identity = self.thread_identity - service = await self.relationship_source(identity) - if service is None: - return - snapshot = await self.app.preparation.run_thread(service.relationships, identity.thread_name()) - if ( - generation != self._generation - or not self.is_attached - or not self.screen.is_current - ): - return - current = snapshot.current_entry(group_key, expected) - if current is None: - self.notify( - self.changed_entry_warning, - title="Comms", - ) - self.refresh_relationships(force=True) - return - self.open_target(entry_target(current)) + await self.open_current_relationship( + self.app.coordination_access, + self.app.preparation, + group_key, + expected, + still_current=lambda: ( + generation == self._generation + and self.is_attached + and self.screen.is_current + ), + ) def relationship_opener(self, row: RelationshipRow) -> Callable[[], object]: entry, generation = row.entry, self._generation diff --git a/tests/guards/test_shared_frontend_members.py b/tests/guards/test_shared_frontend_members.py index 9e45b3ffd..cc5340db5 100644 --- a/tests/guards/test_shared_frontend_members.py +++ b/tests/guards/test_shared_frontend_members.py @@ -621,3 +621,95 @@ def test_gui_and_tui_share_theme_tones_and_resolve_identical_colours() -> None: assert f"background-color:{renderer.colour(role)}" in html +def test_relationship_panel_owns_open_current_and_target_on_both_frontends(): + import asyncio + from pathlib import Path + from agent_comms.registry.relationships import RelationshipEntry + from agent_comms.registry.thread_identity import RecordedThreadIncarnation + from toad.client.relationship_tree_state import RelationshipPanel + from toad.qt.thread_comms_panel import QtThreadCommsPanel + from toad.thread_identity import NoThreadIdentity, ThreadIdentity + from toad.widgets.thread_comms import ThreadCommsSidebar + + for member in ("open_current_relationship", "open_relationship_target"): + _owned_by(RelationshipPanel, member, QtThreadCommsPanel, ThreadCommsSidebar) + assert "_open_current" not in vars(QtThreadCommsPanel) + + events: list[tuple] = [] + + class _Prep: + async def run_thread(self, fn, *args): + return fn(*args) + + class _Observed: + def __init__(self, root: Path): + self.root = root + + class _Service: + def __init__(self, current): + self._current = current + + def relationships(self, _name: str): + current = self._current + return type("_Snap", (), {"current_entry": lambda _s, _g, _e: current})() + + class _Access: + def __init__(self, observed_root: Path, service): + self.observation = type("_Obs", (), {"observed": lambda _s: _Observed(observed_root)})() + self._service = service + + def observing(self, _root): + return self._service + + class _ProbePanel(RelationshipPanel): + def __init__(self, identity): + self.thread_identity = identity + self._states = {} + + def notify_comms_warning(self, message: str) -> None: + events.append(("warn", message)) + + def refresh_after_changed_entry(self) -> None: + events.append(("refresh",)) + + def select_relationship_target(self, target) -> None: + events.append(("open", target)) + + def show_source_unavailable(self, text: str) -> None: + events.append(("unavail", text)) + + entry = RelationshipEntry( + target="peer", + kind="thread", + available=True, + ) + bound = ThreadIdentity(RecordedThreadIncarnation(name="me", created_at=1.0), "/tmp/bus-a") + + async def _run() -> None: + # 1. Detached identity silently does nothing without touching access. + await _ProbePanel(NoThreadIdentity()).open_current_relationship(None, _Prep(), object, entry) + assert events == [] + + # 2. Stale entry warns and refreshes. + await _ProbePanel(bound).open_current_relationship( + _Access(Path("/tmp/bus-a"), _Service(None)), _Prep(), object, entry + ) + assert events == [("warn", RelationshipPanel.changed_entry_warning), ("refresh",)] + events.clear() + + # 3. Wrong bus warns instead of selecting target. + await _ProbePanel(bound).open_current_relationship( + _Access(Path("/tmp/bus-b"), _Service(entry)), _Prep(), object, entry + ) + assert events == [("warn", RelationshipPanel.wrong_bus_warning)] + events.clear() + + # 4. Matching bus selects the current entry target. + await _ProbePanel(bound).open_current_relationship( + _Access(Path("/tmp/bus-a"), _Service(entry)), _Prep(), object, entry + ) + assert len(events) == 1 and events[0][0] == "open" + + asyncio.run(_run()) + +