diff --git a/src/toad/client/history.py b/src/toad/client/history.py index 2a926436d..ad37d02a9 100644 --- a/src/toad/client/history.py +++ b/src/toad/client/history.py @@ -79,8 +79,23 @@ class ReadMarkedHistory(ReadMarking, ResumesSource): def __init__(self, *args, **kwargs) -> None: self._painted_reads: dict[FragmentKey, EvidencedFragment] = {} + self._last_sent_references: tuple[MessageReference, ...] = () super().__init__(*args, **kwargs) + @property + def last_sent_references(self) -> tuple[MessageReference, ...]: + """The most recent outgoing message's references, updated incrementally when + pages commit — never a reverse scan of all fragments.""" + return self._last_sent_references + + def note_sent_references(self, fragments: tuple) -> None: + """Check the given (new) fragments for the most recent sent references. + Called by the page commit path with only the arriving fragments.""" + for fragment in reversed(fragments): + if references := fragment.sent_references: + self._last_sent_references = references + return + # Reading the bound source's first page; a frontend may show it. reading = False diff --git a/src/toad/message_rows.py b/src/toad/message_rows.py index 5782e4275..4026a1f3e 100644 --- a/src/toad/message_rows.py +++ b/src/toad/message_rows.py @@ -135,7 +135,9 @@ def recorded(self, source: HistorySource, name: str) -> LineLink: class MessageFileReader(MroProjection[FileReader]): """Whose read a message's files are, from where it was sent: a channel message is read in - its channel; a direct message in the DM with the participant that is not its reader.""" + its channel; a direct message in its own DM, as its sender. The reader is not always a + participant: #any shows DMs between two other threads, and naming the reader's DM with + the sender there was refused, failing the whole page (2026-11-18).""" @handles(ChannelTarget) def channel(self, target: ChannelTarget, row: MessageRow) -> FileReader: @@ -143,7 +145,7 @@ def channel(self, target: ChannelTarget, row: MessageRow) -> FileReader: @handles(ThreadTarget) def direct(self, target: ThreadTarget, row: MessageRow) -> FileReader: - return FileReader(target.name if row.outgoing else row.message.sender, row.reader) + return FileReader(target.name, row.message.sender) MESSAGE_FILE_READER = MessageFileReader() diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index dc054c7ba..c9fcdb885 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -76,7 +76,7 @@ from toad.transcript_filter import DrawnFilter, FilterState from toad.frame_presentation import ARRIVAL from toad.motion import FOLLOW_ARRIVAL, HEAD_REVEAL, TransitionTarget -from toad.qt.widget_animation import WidgetAnimation +from toad.qt.widget_animation import WidgetAnimation, frame_interval from ui_theme.scheme import BackgroundColour, ForegroundColour, PrimaryColour, SurfaceHoverColour if TYPE_CHECKING: @@ -149,6 +149,7 @@ def __init__(self, prepared: PreparedTranscriptPage, history: QtConversationHist self.prepared = prepared self.history = history self.display = False + self._shown: tuple[HistoryFragment, ...] | None = None prepared.configure(batch_size=PresentationBudget.batch_items) @classmethod @@ -157,8 +158,12 @@ def drawn_for(cls, owner: QtConversationHistory, prepared: PreparedTranscriptPag @property def shown_fragments(self) -> tuple[HistoryFragment, ...]: - selected = self.history.selected_categories - return tuple(fragment for fragment in self.prepared.fragments_in_range if fragment.shown_in(selected)) + shown = self._shown + if shown is None: + selected = self.history.selected_categories + shown = tuple(fragment for fragment in self.prepared.fragments_in_range if fragment.shown_in(selected)) + self._shown = shown + return shown @property def line_count(self) -> int: @@ -166,14 +171,17 @@ def line_count(self) -> int: return sum(self.history.fragment_height(fragment) for fragment in self.shown_fragments) def range_changed(self) -> None: + self._shown = None self.history.window.committed_pages_changed() def set_categories(self, selected) -> None: """A filter change: the history's selection decides which rows show.""" + self._shown = None self.range_changed() def remove(self) -> None: """An evicted page's rows go with the next row reset.""" + self._shown = None self.display = False def drawn_height(self, fragment: HistoryFragment) -> int: @@ -1008,19 +1016,18 @@ def __init__(self, renderer: QtLineRenderer, scope, parent: QWidget | None = Non self._settle_timer.setSingleShot(True) self._settle_timer.timeout.connect(self._settle) self.verticalScrollBar().valueChanged.connect(self.scrolled) - # Touch-down scroll throttle: QScroller emits valueChanged at touch rate - # (90Hz on Pixel 8a, up to 240Hz on higher-rate panels) while the finger - # is dragging. The post-scroll chain (`respond_to_scroll` → - # `lookahead.observe` + `request_preparation` + `tail_follow_changed` + - # `_after_jump_bar_change → refresh_bindings`) is sized for frame-rate - # inertia ticks, not touch rate. Track QScroller's Dragging state and - # skip `respond_to_scroll` while the finger is down; `_on_scroller_state` - # fires it once when the drag ends (and Scrolling/Inactive ticks still - # run it as before). Leaves at_end/follows_tail transitions in `scrolled` - # alone — those are cheap and only do work when the state actually flips. - # A finger pulling past an edge is the one drag that asks for rows at once - # (`overshot`): no scroll travel measures it. - self._scroller_dragging = False + # Frame-rate coalescing: QScroller fires valueChanged at touch rate (90Hz + # on Pixel 8a, up to 240Hz). The post-scroll chain (repin_header, + # lookahead, page requests, tail-follow) runs once per display frame — + # the same cadence as the TUI. Each valueChanged records the latest offset + # and starts a single-shot timer at the display's frame interval; the + # timer fires the full shared response. At frame-rate input (fling, + # keyboard), the timer fires on the next event-loop pass (0 ms remaining), + # so there is no added latency. + self._scroll_frame_timer = QTimer(self) + self._scroll_frame_timer.setSingleShot(True) + self._scroll_frame_timer.timeout.connect(self._scroll_frame) + self._scroll_frame_pending = False self._overshoot = 0.0 _scroller = QScroller.scroller(self.viewport()) _scroller.stateChanged.connect(self._on_scroller_state) @@ -1456,6 +1463,8 @@ def drop_live(self, block: QtLiveBlock) -> None: def committed_pages_changed(self) -> None: """Saved rows arrived: they now carry the output of every finished live block.""" self.live_blocks = [block for block in self.live_blocks if not block.finished] + if self.history.pages: + self.history.note_sent_references(self.history.pages[-1].shown_fragments) self.show_pages() def restyle_rows(self) -> None: @@ -1489,21 +1498,16 @@ def keep_reader(self, key, offset: int) -> None: self.reader_position = RowPosition(self.scroll_y) def scrolled(self, value: int) -> None: - """The reader moved: join or leave the end, then delegate the post-anchor response - (lookahead, settle timer, preparation, tail-follow) to the shared template on - `JumpsToLatest.respond_to_scroll` — same gate Textual uses, so no-travel ticks - from QScroller don't restart the settle timer during Android touch scrolls. - - Touch-down throttle: while QScroller is in Dragging state the finger is - tracking the viewport and valueChanged fires at touch rate. The - post-scroll chain is deferred until drag ends; `_on_scroller_state` - fires `respond_to_scroll` once on the transition out of Dragging. The - at_end/follows_tail transitions here stay — they're cheap state flips - and consumers (jump bar + anchor) need to see them during drag.""" + """The reader moved: join or leave the end, and schedule the full response on the + next display frame. QScroller fires valueChanged at touch rate during a drag; + coalescing to frames runs the same work at the same cadence as the TUI. + + The at_end/follows_tail transitions are immediate — they are cheap state flips + and consumers (jump bar + anchor) need to see them during every touch tick.""" # Every offset pins, the window's own as well as the reader's: a glide down into a tall - # arrival moves the top row into it, and returning before this left the arrival's header - # unpinned until the reader scrolled (Tristan, Android, 2026-11-18). - self.repin_header() + # arrival moves the top row into it, and skipping the window's own offsets left the + # arrival's header unpinned and its burst unstacked (Tristan, Android, 2026-11-18). + self._schedule_scroll_frame() if self._restoring: return if self.at_end and not self.follows_tail: @@ -1512,9 +1516,25 @@ def scrolled(self, value: int) -> None: self.release_anchor() elif not self.follows_tail: self.reader_position = RowPosition(value) - if self._scroller_dragging: - return - self.respond_to_scroll(value) + self._reader_scrolled = True + + _reader_scrolled = False + + def _schedule_scroll_frame(self) -> None: + if not self._scroll_frame_pending: + self._scroll_frame_pending = True + interval = max(1, round(frame_interval(QWidget.screen(self)) * 1000)) + self._scroll_frame_timer.start(interval) + + def _scroll_frame(self) -> None: + """One display frame's scroll response: the pin for every offset, and the reader's + response (velocity, page requests, tail-follow) when the reader moved. Runs at frame + rate regardless of input rate — the same cadence as the TUI.""" + self._scroll_frame_pending = False + self.repin_header() + if self._reader_scrolled: + self._reader_scrolled = False + self.respond_to_scroll(self.verticalScrollBar().value()) _flinging = False @@ -1540,11 +1560,8 @@ def reveal_head_at(self, point: QPoint) -> bool: return True def _on_scroller_state(self, state) -> None: - """On the drag → not-drag edge, answer the drag's last position at once. A finger - taking the rows stops a head reveal; a press that stops a fling is remembered, so - its release is not read as a tap on a row.""" - was_dragging = self._scroller_dragging - self._scroller_dragging = (state == QScroller.State.Dragging) + """A finger taking the rows stops a head reveal; a press that stops a fling is + remembered, so its release is not read as a tap on a row.""" if state in (QScroller.State.Pressed, QScroller.State.Dragging) and self.head_reveal is not None: self.head_reveal.cancel() if state == QScroller.State.Pressed: @@ -1552,8 +1569,6 @@ def _on_scroller_state(self, state) -> None: self._flinging = state == QScroller.State.Scrolling if state == QScroller.State.Inactive: self._overshoot = 0.0 - if was_dragging and not self._scroller_dragging: - self.respond_to_scroll(self.verticalScrollBar().value()) def overshot(self, distance: float) -> None: """A finger (or a fling's momentum) pulled the rows past an edge: the content can't diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index de123a2f0..85089ba7c 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -113,6 +113,8 @@ from toad.constants import WELCOME from toad.core import session_requests from toad.core.events import CoordinationObserved, ExternalTranscriptChanged, TabHistoryChanged +from agent_comms.messaging.revision_views import RosterView +from agent_comms.presentation import NoRevision, ReadState from toad.launch_binding import AgentBinding, NoAgent from toad.launch_opening import LaunchOpening, NoLaunchOpening from toad.navigation_context import HomeNavigation, NavigationOwner @@ -1292,12 +1294,28 @@ async def _refresh_source(self) -> None: finally: self.content_ready.set() self.submissions.settle() - followed = (str(source.root), next(( - references for fragment in reversed(history.fragments) if (references := fragment.sent_references)), ()), + followed = (str(source.root), history.last_sent_references, history.pages[-1].prepared.page.source.selection.notification_identity) self.on_composer("receipt", lambda composer: composer.receipt.follow(*followed)) self.refresh_thread_status() self.sync_working() + # Thread config (compose, label, status, mentions) is read on the first refresh and when + # the roster moved, the roster owner's own signal: channels get no thread_presented. + revision = self.app.coordination_access.revision + if revision.changed_since(RosterView(), self._config_revision): + self._config_revision = revision + asyncio.ensure_future(self._refresh_thread_config()) + + _config_revision: ReadState = NoRevision() + + def thread_presented(self, presentation) -> None: + super().thread_presented(presentation) + asyncio.ensure_future(self._refresh_thread_config()) + + async def _refresh_thread_config(self) -> None: + """Read compose access, status, label and mentions — facts that change when thread + config changes (ThreadsObserved), not on every bus message.""" + source = self.app.source() label = self.conversation.label(source.references()) self.on_composer("label", lambda composer: composer.labelled(label)) compose = await asyncio.to_thread(self.conversation.compose_access, source.core) diff --git a/src/toad/widgets/comms_chat.py b/src/toad/widgets/comms_chat.py index bd8bf45fd..02e3ef9a8 100644 --- a/src/toad/widgets/comms_chat.py +++ b/src/toad/widgets/comms_chat.py @@ -1,6 +1,8 @@ """Native Toad conversation view for an agent-comms channel or DM.""" from __future__ import annotations +from agent_comms.messaging.revision_views import RosterView +from agent_comms.presentation import NoRevision, ReadState import re from functools import partial @@ -44,7 +46,6 @@ Window, ) from toad.widgets.flash import Flash -from toad.client.history_preparation import NEWER_END, OLDER_END from toad.widgets.prompt import MessagePrompt, Prompt from toad.widgets.session_details import ConversationSessionDetails from toad.widgets.wire_history import HistoryLoading, WireFragment, WireHistory @@ -254,66 +255,54 @@ def history_loading(self) -> bool: return self.message_history.reading async def _refresh_source(self) -> None: - """Read what changed in the conversation and draw it: the history's source work.""" + """Read what changed in the conversation and draw it: the history's source work. + Thread-config reads (compose, status, mentions, label) are driven by + thread_presented, not by every bus message.""" history = self.message_history announced = self.app.coordination_access.revision - newly_announced = announced != self._refreshed_from - changed = await history.read_changes() - # Source observation and its pending first page belong to the - # history, even before this tab is drawable. Composer work follows. - source = history.page_source - snapshot = history.source_snapshot() - if not await history.source_is_current(snapshot): - return - compose = await source.compose_access() - if not await history.source_is_current(snapshot): - return - await self.refresh_composer(compose) + await history.read_changes() self._refreshed_from = announced - # A sent message may now be drawn: its queue entry retires before mentions are read. self.submissions.settle() - # Composer mentions and DM status read the observer's snapshot - # and the agent records, which can take seconds on a busy bus. They are - # not this conversation's messages, so they run after this work ends - # and the history can load pages while they wait. - self.run_worker(partial(self._refresh_labels, source, changed, newly_announced, compose.read_only), - group=self.LABELS_GROUP) + # Thread config (compose, label, status, mentions) is read on the first refresh and when + # the roster moved, the roster owner's own signal: channels get no thread_presented. + if announced.changed_since(RosterView(), self._config_revision): + self._config_revision = announced + self.run_worker(self._refresh_thread_config, group=self.LABELS_GROUP) + + _config_revision: ReadState = NoRevision() LABELS_GROUP = "chat-labels" - async def _refresh_labels(self, source, changed: bool, newly_announced: bool, read_only: bool) -> None: - """Refresh composer mentions and status for the history as it is drawn now.""" + def thread_presented(self, presentation) -> None: + super().thread_presented(presentation) + self.run_worker(self._refresh_thread_config, group=self.LABELS_GROUP) + + async def _refresh_thread_config(self) -> None: + """Read compose access, status, mentions and label — facts that change when thread + config changes (ThreadsObserved), not on every bus message.""" history = self.message_history + source = history.page_source snapshot = history.source_snapshot() - conversation = self.conversation - if source is not history.page_source: + if not await history.source_is_current(snapshot): + return + compose = await source.compose_access() + if not await history.source_is_current(snapshot): return + await self.refresh_composer(compose) try: - # An unchanged history may have read the stores before the observer - # announced the change; mention completion reads the observer's snapshot. - if changed or newly_announced: - await source.update_mentions(self) - if changed: - if not await history.source_is_current(snapshot): - return - if (not self.is_attached or source is not history.page_source - or not self.query_ancestor(SessionScope).is_current): - return - self.call_after_refresh(history.mark_visible) - if not changed: + await source.update_mentions(self) + if not await history.source_is_current(snapshot): return - status = await source.status_text(read_only=read_only) + self.call_after_refresh(history.mark_visible) + status = await source.status_text(read_only=compose.read_only) except (CoordinationReadUnavailable, ReadAgain): - # The coordination store is busy or moved on: the observer's next - # announcement refreshes this view and reads the labels again. return - if not await history.source_is_current(snapshot) or self.conversation != conversation: + if not await history.source_is_current(snapshot) or self.conversation != self.conversation: return self.thread_status = status if self.window.follows_tail: self.window.anchor() - if NEWER_END.visible_more(history) or (OLDER_END.visible_more(history) and self.window.max_scroll_y == 0): - history.request_preparation() + def channel_prompt(self, placeholder: str) -> ChannelPrompt: return ChannelPrompt(project=self.project_path, placeholder=placeholder, submissions=self.submissions)