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
4 changes: 3 additions & 1 deletion src/toad/client/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,10 @@ def activate(self, app: ClientApplication) -> ApplicationPresence:

class SuspendedPresence(ApplicationPresence):
def activate(self, app: ClientApplication) -> ApplicationPresence:
# `resume()` publishes `CoordinationObserved` once the fresh observation attaches,
# which triggers `stores_changed` -> `selected.reload()` on the new observer instead
# of racing a synchronous reload against the retiring one (`ObserverRetired`).
app.coordination_access.resume()
app.workspace_sessions.selected.reload()
return ACTIVE_PRESENCE

def deactivate(self, app: ClientApplication) -> ApplicationPresence:
Expand Down
108 changes: 96 additions & 12 deletions src/toad/client/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@
from agent_comms.errors import RouteChangedError
from agent_comms.execution.child_process import (
Platform,
RelayEnding,
WorkerStart,
join_retirement,
)
from agent_comms.execution.remote_core_process import ProcessRemoteCoreAccess
from agent_comms.transport.remote_core import ConnectorObserverClosed, ServiceFailed
from agent_comms.team.team_board_selection import NamedTeamBoards, TeamBoardSelection
from agent_comms.execution.transcript_sources import TranscriptCursor
from agent_comms.installer.active_route import CommsRoute
Expand Down Expand Up @@ -348,6 +350,58 @@ def observe(self, access: CoordinationAccess) -> Observing | FailedObservation:
return access.observation.failed(error, UnselectedRoute())
return access.observe_remote(self, Path(served.root))

def resume_observe(self, access: CoordinationAccess, served_root: Path) -> Observing | FailedObservation:
"""Re-open observation on the already-known served root after suspension without
paying a cold `CommsServedRootTool` HTTPS round-trip first."""
return access.observe_remote(self, served_root)


class ObservationFailureReport(MroDispatch):
"""Route observation disconnects by failure kind: expected remote socket drops log
quietly and auto-retry without popping an error toast; real Core service crashes
(`ServiceFailed`) and unexpected observer deaths still surface through the host."""

@handles(ConnectorObserverClosed)
def connector_closed(
self, error: ConnectorObserverClosed, app: CommsHost, title: str | None,
) -> object:
self.dispatch_sync(error.ending, error, app, title)
return self.DISCARD

@handles(ServiceFailed)
def service_failed(
self, ending: ServiceFailed, error: Exception, app: CommsHost, title: str | None,
) -> object:
self._surface(error, app, title)
return self.DISCARD

@handles(RelayEnding)
def transient_relay(
self, ending: RelayEnding, error: Exception, app: CommsHost, title: str | None,
) -> object:
app.log_error(str(error))
return self.DISCARD

@handles(OSError)
def transient_io(self, error: OSError, app: CommsHost, title: str | None) -> object:
app.log_error(str(error))
return self.DISCARD

@handles(Exception)
def unexpected(self, error: Exception, app: CommsHost, title: str | None) -> object:
self._surface(error, app, title)
return self.DISCARD

@staticmethod
def _surface(error: Exception, app: CommsHost, title: str | None) -> None:
if title is None:
app.report_fatal(error)
else:
app.show_error(error, title)


OBSERVATION_FAILURE_REPORT = ObservationFailureReport()


@dataclass(frozen=True)
class UnselectedRoute:
Expand Down Expand Up @@ -501,6 +555,15 @@ def activate(self, access: CoordinationAccess):
for view in tuple(access.sidebar_views):
self.show_sidebar(view)

def retains_root_cache(self, previous_root: Path | None) -> bool:
"""Whether attaching this observation preserves cached per-root read receipts and
thread status (transient failures keep the last root's cache until a different root
attaches)."""
return True

def record_observed_root(self, access: CoordinationAccess) -> None:
"""Record the active bus root when an `Observing` attaches."""

def attach(self, access, previous):
previous.subscriptions.close()
if not self.is_current():
Expand All @@ -513,13 +576,15 @@ def attach(self, access, previous):
subscribers = tuple(dict.fromkeys((
*access.notification_views, *previous.pending_notification_views(),
)))
if not self.retains_root_cache(access._last_observed_root):
access.thread_status.clear()
access.notification_known.clear()
self.record_observed_root(access)
access.revision = NoRevision()
access.sidebar_interest = access.sidebar_current = None
access.team_interest = StopTeamHud()
access.thread_status.clear()
access.views_interest = None
access.notification_views.clear()
access.notification_known.clear()
access.notification_interest = ObserveNotifications(frozenset())
self.activate(access)
self.rebind_notifications(subscribers)
Expand Down Expand Up @@ -684,7 +749,9 @@ def subscribe_notifications(

def thread_interest(self, access: CoordinationAccess):
if access.retry.began():
access.app.show_error(self.error, "Thread status unavailable")
OBSERVATION_FAILURE_REPORT.dispatch_sync(
self.error, access.app, "Thread status unavailable"
)

def observe_team(self, wanted: ObserveTeamHud | StopTeamHud):
self.access.events.publish(TeamHudFailed(self.error))
Expand Down Expand Up @@ -905,14 +972,20 @@ def tell(self, wanted) -> None:
except ObservationEnded:
pass

def retains_root_cache(self, previous_root: Path | None) -> bool:
return previous_root is None or self.root == previous_root

def record_observed_root(self, access: CoordinationAccess) -> None:
access._last_observed_root = self.root

def receive_failed(self, error: Exception):
"""The observation closed: the failure becomes current and retries; the reader is
told once per outage, not once per reopen that closes again."""
"""The observation closed: the failure becomes current and retries; expected remote
socket drops log quietly while real service crashes surface once per outage."""
if self.is_current():
self.failed(error, self.opened_selection())
if self.access.retry.began():
error.add_note(self.access.retry.quiet_note(time.monotonic()))
self.access.app.report_fatal(error)
OBSERVATION_FAILURE_REPORT.dispatch_sync(error, self.access.app, None)

def views_changed(self, event=None, subscription=None):
access, root = self.access, str(self.root)
Expand Down Expand Up @@ -992,7 +1065,10 @@ def through(self, connection: RemoteCoreConnection, access: CoordinationAccess):

def resumed_through(self, connection: RemoteCoreConnection, access: CoordinationAccess):
"""After Android suspension or a network switch, the existing WebSocket may be
half-open; open a fresh observation instead of waiting on heartbeat timeout."""
half-open; open a fresh observation on the known served root instead of waiting
on heartbeat timeout or paying a cold `CommsServedRootTool` round-trip."""
if self.connection is connection:
return connection.resume_observe(access, self.served_root)
return connection.observe(access)

def user_identity(self, project: Checkout) -> Thread:
Expand Down Expand Up @@ -1022,6 +1098,8 @@ def __init__(self, app: CommsHost, connection: CoreConnection) -> None:

self.transcripts = CoordinationTranscriptReader(self)
self.observation: Observation = NotObserving(access=self)
self._last_observed_root: Path | None = None
self._retained_remote: dict[Path, tuple[SidebarModel, RegistryReads]] = {}
self.retry = ObservationRetry()
self.events = CoreEventStream(self)
self.revision: ReadState = NoRevision()
Expand Down Expand Up @@ -1091,10 +1169,18 @@ def require(self, selected: RouteSelection) -> Observing:

def observe_remote(self, connection: RemoteCoreConnection, root: Path) -> RemoteObserving:
"""Observe the Core behind the connector: its peer carries the observation, and the
root it serves keys every root-scoped request."""
root it serves keys every root-scoped request. Reconnecting to the same root reuses
its retained sidebar model and registry cache so the UI never flashes blank or
re-downloads the whole registry while the fresh WebSocket syncs."""
with self.opening:
retained = self._retained_remote.get(root)
if retained is None:
retained = (SidebarModel(self.app.schedule_ui), RegistryReads())
self._retained_remote[root] = retained
sidebar, registry_reads = retained
return self.observation.adopt(RemoteObserving(
SidebarModel(self.app.schedule_ui), ObservationProcess(connection),
sidebar, ObservationProcess(connection),
registry_reads=registry_reads,
connection=connection, served_root=root, access=self))

@handles(RevisionObserved)
Expand Down Expand Up @@ -1415,10 +1501,8 @@ def resume(self) -> None:
self.route_task = asyncio.create_task(self.resume_route())

async def resume_route(self) -> None:
previous = self.observation
await self.preparation.run_thread(self.reopen_current)
if not previous.is_current():
self.events.publish(CoordinationObserved(self.revision))
self.events.publish(CoordinationObserved(self.revision))

async def observe_route(self) -> None:
"""A changed route selection opens (and observes) the newly selected service."""
Expand Down
4 changes: 3 additions & 1 deletion src/toad/client/sidebar_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,13 @@ def bind_failed_observation(self, observed: FailedObservation) -> None:
def bind_observation(self, observed: Observing) -> None:
if self.model_state.observes(observed):
return
same_root = self.model_state.serves(observed.root)
self.unsubscribe()
self.model_state = Behind(observed)
observed.sidebar.channels.subscribe(self.channels_changed)
observed.sidebar.threads.subscribe(self.threads_changed)
self.model_replaced()
if not same_root:
self.model_replaced()
self.present()

def channels_changed(self, changes: Changes[str]) -> None:
Expand Down
4 changes: 2 additions & 2 deletions src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ def prepare_inline(
1-line summary or collapsed tool call) immediately using the already-warm
`self.renderer` so it lays out in one frame (< 1 ms) without a RenderProcessPool
round-trip."""
if width <= 0 or not fragment.has_blocks:
if self._stopped or width <= 0 or not fragment.has_blocks:
return False
blocks = tuple(fragment.line_blocks)
if not blocks or not all(block.renders_inline for block in blocks):
Expand All @@ -514,7 +514,7 @@ def prepare_inline(
tuple((header, html((header,))) for header in pinned),
)
self._row_prepared(key, rendered)
return True
return key in self._prepared

TILE = 256
"""Pixels of a row's height one picture holds. A row is as tall as its message, and a
Expand Down
7 changes: 7 additions & 0 deletions src/toad/qt/transcript_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ class QtTranscriptHistory(QtConversationHistory, CommittedHistoryBase, ReportsCo

fragment_classes = QT_FRAGMENT_CLASSES

@property
def undrawn(self) -> bool:
"""Transcript pages carry `TranscriptCursor`, not wire `AfterMessage` cursors;
match Textual's `TranscriptHistory` (`HistoryPager.undrawn`) so arrival capture
never calls wire-only `.requires_read()` on `NoNativeTranscriptCursor`."""
return not self.draws_rows

@classmethod
def initial_state(cls, view):
"""Start a bound thread unread, so mounting requests its first saved page.
Expand Down
15 changes: 14 additions & 1 deletion src/toad/qt/virtual_scroll.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,7 @@ class RowDocumentStore(ABC):
MAX_DOCUMENTS = 500
ROW_PADDING = 0
MEASURE_SLICE_SECONDS = 0.008
SUSPEND_RELEASE_MS = 60_000

def __init__(self) -> None:
self.view: DetachedCanvas | VirtualRowCanvas = DetachedCanvas()
Expand All @@ -436,6 +437,10 @@ def __init__(self) -> None:
self._measure_timer.setSingleShot(True)
self._measure_timer.setInterval(0)
self._measure_timer.timeout.connect(self._measure_slice)
self._suspend_release_timer = QTimer()
self._suspend_release_timer.setSingleShot(True)
self._suspend_release_timer.setInterval(self.SUSPEND_RELEASE_MS)
self._suspend_release_timer.timeout.connect(self.release_documents)
self._arrivals_moved_rows = False
app = QGuiApplication.instance()
if app is not None:
Expand All @@ -445,6 +450,7 @@ def bind_view(self, view: VirtualRowCanvas) -> None:
self.view = view
self._viewport_update_timer.setParent(view)
self._measure_timer.setParent(view)
self._suspend_release_timer.setParent(view)

def set_scroll_paused(self, paused: bool) -> None:
"""Pause background off-screen row measurement during active finger drag or fling."""
Expand Down Expand Up @@ -649,8 +655,14 @@ def _update_viewport(self) -> None:
self.view.rows_repainted()

def _application_state_changed(self, state: Qt.ApplicationState) -> None:
"""Defer dropping laid-out documents and tiles across brief Android app switches so
reopening within `SUSPEND_RELEASE_MS` paints from warm caches without a 100+ ms
re-layout/re-rasterize stall, while prolonged backgrounding still returns memory."""
if state is Qt.ApplicationState.ApplicationSuspended:
self.release_documents()
if not self._stopped and not self._suspend_release_timer.isActive():
self._suspend_release_timer.start()
elif state is Qt.ApplicationState.ApplicationActive:
self._suspend_release_timer.stop()

def release_documents(self) -> None:
self._documents.clear()
Expand Down Expand Up @@ -827,6 +839,7 @@ def cleanup(self) -> None:
self.preparing = False
self._viewport_update_timer.stop()
self._measure_timer.stop()
self._suspend_release_timer.stop()
self.preparer.clear()
self.stop_preparation()
self.preparer.stop()
Expand Down
1 change: 1 addition & 0 deletions tests/model/test_android_perf_ux_arrivals.py
Original file line number Diff line number Diff line change
Expand Up @@ -2287,6 +2287,7 @@ def user_identity(self, project):

access = SimpleNamespace(
observation=None,
_last_observed_root=None,
sidebar_waiters=[],
sidebar_views=(),
revision=None,
Expand Down
Loading
Loading