Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/toad/client/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down
48 changes: 39 additions & 9 deletions src/toad/client/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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()

Expand Down Expand Up @@ -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):
Expand All @@ -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]
Expand Down Expand Up @@ -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)

Expand Down
5 changes: 5 additions & 0 deletions src/toad/client/prepared_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/toad/qt/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
6 changes: 5 additions & 1 deletion src/toad/qt/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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()
Expand Down
2 changes: 2 additions & 0 deletions src/toad/widgets/comms_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
110 changes: 110 additions & 0 deletions tests/model/test_mobile_chrome_polish_and_suspend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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)
Loading