diff --git a/src/toad/arrivals.py b/src/toad/arrivals.py index b540486ec..6be4abce4 100644 --- a/src/toad/arrivals.py +++ b/src/toad/arrivals.py @@ -148,7 +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() + owner.refresh_visible_notifications() if self.keys: owner.repaint_arrival_keys(self.keys) @@ -264,8 +264,32 @@ 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.""" + histories: Iterable[object] = () + + def refresh_visible_notifications(self) -> None: + """Refresh delivery/read receipts for histories now visible in this window without + re-arming source page reads (`history_pager.py` finish_source_work invariant).""" + for history in tuple(self.histories): + history.check_visible_notifications() + + def toolkit_animated_travel(self) -> float: + """Remaining distance of any toolkit-owned scroll animation or fling.""" + return 0.0 + + @property + def animated_travel(self) -> float: + """Remaining distance of a head reveal, else any toolkit-owned scroll travel.""" + if (travel := self.head_reveal_travel()) is not None: + return travel + return self.toolkit_animated_travel() + + def shift_toolkit_travel(self, rows: float, destination: float) -> None: + """Shift any toolkit-owned scroll animation or fling by `rows` after layout moves.""" + + def shift_travel(self, rows: float, destination: float) -> None: + """Keep a head reveal and any toolkit-owned scroll travel aimed at the same rows.""" + self.shift_arrival_motion(rows) + self.shift_toolkit_travel(rows, destination) # ---- Shared semantic operations ---- diff --git a/src/toad/client/bus_submission.py b/src/toad/client/bus_submission.py index dcb597687..95f82f2cf 100644 --- a/src/toad/client/bus_submission.py +++ b/src/toad/client/bus_submission.py @@ -79,10 +79,21 @@ def delivery_unknown(self, description: str, draft: SubmittedText) -> None: self.submission_composer.restore(draft) self.show_send_failure(self.unknown_notice(description)) + def can_refresh_composer(self) -> bool: + """Whether this view is attached and ready to draw compose access.""" + return True + @abstractmethod + def apply_compose_access(self, composer, access: ComposeAccess) -> None: + """Apply Core's compose access (read-only hold and file attachments) onto `composer`.""" + async def refresh_composer(self, access: ComposeAccess) -> None: """Draw compose from the caller's Core answer: held or open, and whether it offers files.""" + if not self.can_refresh_composer(): + return + self.composer_block = access.block_reason + self.on_composer("access", lambda composer: self.apply_compose_access(composer, access)) @abstractmethod def draws_user_message(self, reference: MessageReference) -> bool: ... diff --git a/src/toad/client/composer_pool.py b/src/toad/client/composer_pool.py index fb588dfb1..70a6e97a9 100644 --- a/src/toad/client/composer_pool.py +++ b/src/toad/client/composer_pool.py @@ -76,8 +76,19 @@ def capture_composer_draft(self) -> ComposerDraft: def reset_editor_draft(self, host: ComposerPoolHost, text: str) -> None: """Initialize this composer's editor for a fresh `host` with no captured state.""" + def rebind_toolkit_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> None: + """Toolkit-specific state rebinding before queue and prompt refresh.""" + + def after_rebind_conversation(self) -> None: + """Optional toolkit-specific post-rebind layout fit.""" + def rebind_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> None: """Rebind this existing composer widget to `host` and restore `draft`.""" + self.kept_delivery_preview = None + self.rebind_toolkit_conversation(host, draft) + self.sync_queue() + self.update_prompt() + self.after_rebind_conversation() class ComposerPoolHost: diff --git a/src/toad/client/fragments.py b/src/toad/client/fragments.py index 819efc0e0..0ae2b6e60 100644 --- a/src/toad/client/fragments.py +++ b/src/toad/client/fragments.py @@ -303,6 +303,9 @@ def in_flow_collapse_link(self) -> FragmentCollapse | None: """Collapse link when this row itself draws the message's leading header divider.""" return None + def retain_painted(self, owner) -> None: + """Non-message fragments carry no read-receipt evidence; `EvidencedFragment` overrides.""" + @cached_property def revision(self): """What makes the same fragment draw differently, derived once from its events as its diff --git a/src/toad/client/history.py b/src/toad/client/history.py index 896005e4c..d941a6f2e 100644 --- a/src/toad/client/history.py +++ b/src/toad/client/history.py @@ -37,6 +37,7 @@ from agent_comms.ui_model.observation import ReadNotifications from metaclass_registry.mro_dispatch import handles +from toad.client.composer_pool import ComposerPoolHost from toad.client.connection import CoordinationAccess, Observation from toad.client.conversation import ConversationKind from toad.client.resource_release import ResourceRelease @@ -47,7 +48,7 @@ ConversationSource, ) -from toad.client.fragments import EvidencedFragment, FragmentKey, MessageShown +from toad.client.fragments import EvidencedFragment, FragmentKey, HistoryFragment, MessageShown from toad.client.history_preparation import HistorySourceSnapshot, PageRequest from toad.client.history_reads import NothingToRead, PaintedRead, ReadMarking, ReadWork from toad.client.message_file_links import PageFiles @@ -198,7 +199,7 @@ async def refresh_source(self) -> None: """Read the conversation again, as the view reads it now.""" await self.view._refresh() - def retain_painted(self, fragment: EvidencedFragment) -> None: + def retain_painted(self, fragment: HistoryFragment) -> None: """Keep actual painted evidence until its original page is acknowledged.""" fragment.retain_painted(self) @@ -262,7 +263,7 @@ async def reload_notification_source(self) -> None: await self.refresh_source() -class WireView(ConversationActivity): +class WireView(ConversationActivity, ComposerPoolHost): """A frontend's view of one wire conversation, as its page source, its sends and its commands address it. A plain parent: each toolkit's widget metaclass would conflict with ABCMeta. @@ -274,6 +275,13 @@ class WireView(ConversationActivity): conversation: ConversationKind message_history: ReadMarkedHistory + @property + def composer_placeholder(self) -> str: + return self.conversation.initial_placeholder + + def show_mention_candidates(self, mentions) -> None: + self.on_composer("mentions", lambda composer: composer.set_mention_candidates(mentions)) + def begin_submission(self, owner, submission): """A channel or inbox message goes where this view's page source says.""" return self.message_history.page_source.begin_submission(self, owner, submission) diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index b050a833d..2d22fe5ca 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -306,7 +306,10 @@ def check_follow(self, window: HistoryWindow) -> bool: previous = window.scroll_y with window.layout_scroll(): window.scroll_y = window.tail_scroll_y - return previous != window.scroll_y + moved = previous != window.scroll_y + if moved: + window.refresh_visible_notifications() + return moved def finish_layout(self, answered: int) -> None: """No change waits on a layout.""" diff --git a/src/toad/client/history_notifications.py b/src/toad/client/history_notifications.py index c32dcf492..b7cb25038 100644 --- a/src/toad/client/history_notifications.py +++ b/src/toad/client/history_notifications.py @@ -185,6 +185,9 @@ def prepare_viewport(self) -> None: super().prepare_viewport() self.notification_view.check_notifications() + def check_visible_notifications(self) -> None: + self.notification_view.check_notifications_after_refresh() + @property def notification_references(self): return tuple(dict.fromkeys(reference for fragment in self.visible_fragments() diff --git a/src/toad/client/history_pager.py b/src/toad/client/history_pager.py index f52d3c420..d0e220f61 100644 --- a/src/toad/client/history_pager.py +++ b/src/toad/client/history_pager.py @@ -320,8 +320,6 @@ 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 @@ -842,6 +840,9 @@ def prepare_viewport(self) -> None: self.prepare_visible_pages() self.state.check_edges(self) + def check_visible_notifications(self) -> None: + """Refresh visible delivery/read receipts; histories carrying notifications override.""" + def invalidate_projection(self) -> None: self._generation += 1 diff --git a/src/toad/client/model_selection.py b/src/toad/client/model_selection.py index e40c900f0..84c19099d 100644 --- a/src/toad/client/model_selection.py +++ b/src/toad/client/model_selection.py @@ -116,7 +116,39 @@ def select_model(self, model_id: str) -> None: ... def connect_provider(self) -> None: ... @abstractmethod - def filter_models(self, placement: HighlightPlacement) -> None: ... + def search_query(self) -> str: ... + + @abstractmethod + def highlighted_model_id(self) -> str | None: ... + + @abstractmethod + def present_filtered_models( + self, + ranked: list[RankedModel], + highlighted_index: int | None, + summary: str, + ) -> None: ... + + def filter_models(self, placement: HighlightPlacement) -> None: + previous_id = self.highlighted_model_id() + ranked, summary = self.rank_models(self.search_query()) + highlighted = ( + placement.index([entry.choice.value for entry in ranked], previous_id) + if ranked + else None + ) + self.present_filtered_models(ranked, highlighted, summary) + + def search_changed(self) -> None: + self.filter_models(ResetsHighlight()) + self.refilter = KeepsHighlight() + + def note_highlight_moved(self) -> None: + self.refilter = KeepsHighlight() + + def submit(self) -> None: + if (model_id := self.highlighted_model_id()) is not None: + self.select_model(model_id) async def recent_choices(self, scope: str) -> list[str]: return await ModelConfigurationSetting().recent_choices(scope) diff --git a/src/toad/client/structured_context.py b/src/toad/client/structured_context.py index 9a234d697..0cbeb75d1 100644 --- a/src/toad/client/structured_context.py +++ b/src/toad/client/structured_context.py @@ -87,6 +87,26 @@ def wire_blocks(self, row, body_type) -> tuple[LineBlock, ...]: return self.line_blocks() +class RawTextPart(StructuredPart): + """A structured part whose searchable text is its `raw_text` field.""" + + raw_text: str + + @property + def text(self) -> str: + return self.raw_text + + +class BodyTextPart(StructuredPart): + """A structured part whose searchable text is its `body_text` field.""" + + body_text: str + + @property + def text(self) -> str: + return self.body_text + + @dataclass(frozen=True) class CertaintyClaim(StructuredPart): """One grounded or assumed epistemic claim from a `Certainty:` audit block.""" @@ -121,7 +141,7 @@ def line_blocks(self) -> tuple[LineBlock, ...]: @dataclass(frozen=True) -class ThinkingPart(StructuredPart): +class ThinkingPart(RawTextPart): """Visible reasoning (`` or Pi `ThinkingContent`), with parsed Certainty/Confidence.""" kind_title = "Thinking" @@ -132,10 +152,6 @@ class ThinkingPart(StructuredPart): confidence: str = "" streaming: bool = False - @property - def text(self) -> str: - return self.raw_text - @classmethod def from_text(cls, text: str, *, streaming: bool = False) -> ThinkingPart: cleaned = text.strip() @@ -202,7 +218,7 @@ def line_blocks(self) -> tuple[LineBlock, ...]: @dataclass(frozen=True) -class ContextSectionPart(StructuredPart): +class ContextSectionPart(BodyTextPart): """One named section inside a compact `` / `.live_ctx` document.""" kind_title = "Section" @@ -211,10 +227,6 @@ class ContextSectionPart(StructuredPart): heading: str body_text: str - @property - def text(self) -> str: - return self.body_text - @property def label(self) -> str: preview = compact_preview(self.body_text, 48) @@ -231,7 +243,7 @@ def line_blocks(self) -> tuple[LineBlock, ...]: @dataclass(frozen=True) -class LiveContextPart(StructuredPart): +class LiveContextPart(RawTextPart): """A compact structured `` or `.live_ctx` context block decomposed into sections.""" kind_title = "Context" @@ -243,10 +255,6 @@ class LiveContextPart(StructuredPart): sections: tuple[ContextSectionPart, ...] = () streaming: bool = False - @property - def text(self) -> str: - return self.raw_text - @classmethod def from_text(cls, text: str, *, title: str = "Context", streaming: bool = False) -> LiveContextPart: cleaned = text.strip() @@ -369,7 +377,7 @@ def line_blocks(self) -> tuple[LineBlock, ...]: @dataclass(frozen=True) -class AnswerPart(StructuredPart): +class AnswerPart(BodyTextPart): """Plain assistant answer text outside ``, ``, and `` blocks.""" kind_title = "Answer" @@ -377,10 +385,6 @@ class AnswerPart(StructuredPart): body_text: str - @property - def text(self) -> str: - return self.body_text - @property def label(self) -> str: preview = compact_preview(self.body_text, 56) diff --git a/src/toad/delivery_failure_view.py b/src/toad/delivery_failure_view.py index 6c7131a2f..afba78312 100644 --- a/src/toad/delivery_failure_view.py +++ b/src/toad/delivery_failure_view.py @@ -59,22 +59,17 @@ def release_pooled_composer(self, composer: Prompt) -> ComposerDraft: composer.reparent(park) return draft - async def refresh_composer(self, access: ComposeAccess) -> None: - """Draw compose from the caller's Core answer.""" - if not self.is_attached: - return - reason = access.block_reason - self.composer_block = reason - - def apply(prompt: Prompt) -> None: - prompt.offer_files(access.takes_files) - area = prompt.prompt_text_area - area.disabled = bool(reason) - area.tooltip = reason or None - if not area.disabled and self.screen.focused is None: - self.screen.set_focus(area) + def can_refresh_composer(self) -> bool: + return self.is_attached - self.on_composer("access", apply) + def apply_compose_access(self, prompt: Prompt, access: ComposeAccess) -> None: + reason = access.block_reason + prompt.offer_files(access.takes_files) + area = prompt.prompt_text_area + area.disabled = bool(reason) + area.tooltip = reason or None + if not area.disabled and self.screen.focused is None: + self.screen.set_focus(area) @property def submission_composer(self): diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index 9e758c4fd..0241efd66 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -823,11 +823,10 @@ def capture_composer_draft(self) -> ComposerDraft: dismissed_text=self.dismissed_text, ) - def rebind_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> None: + def rebind_toolkit_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> None: self.host = host self.info_bar.configuration_scope = host self.info_bar.status.configuration_scope = host - self.kept_delivery_preview = None self._last_queue_state = None self.given_placeholder = draft.placeholder or host.composer_placeholder self.mention_candidates = draft.mention_candidates @@ -849,9 +848,9 @@ def rebind_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> N self.failure.setText("") self.failure.hide() self.place_input_box() - self.update_prompt() + + def after_rebind_conversation(self) -> None: self.fit_height() - self.sync_queue() Composer.action_methods = ( diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 37be046bd..40d7c6a6c 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -66,7 +66,7 @@ Runway, ) from toad.client.line_blocks import BlockPreparation, Divider, LineBlock, LineLink -from toad.client.history_changes import FragmentRowUnderTop, HeaderPin, PinnedHeader, PinsMessageHeader, TopPage +from toad.client.history_changes import HeaderPin, PinnedHeader, PinsMessageHeader, TopPage from toad.client.history_preparation import HistorySourceSnapshot from toad.client.history_state import LiveTranscript from toad.client.prepared_pages import ( @@ -388,13 +388,19 @@ def block_row(self, fragment: HistoryFragment, font: QFont, width: int, y: int) header blocks are measured: past them the pin is the same in every block (`header_blocks`), so a `y` below them answers the first block after them.""" blocks = fragment.line_blocks + if not blocks: + return 0, 0 _cell, line = self._font_metrics(font) + if y < line: + return 0, 0 + decided = fragment.header_blocks + if decided == 0 and len(blocks) > 1: + return 0, 0 key = self.fragment_key(fragment, font, width) prepared = self.prepared_look(key) if prepared is None: return 0, 0 top = 0 - decided = fragment.header_blocks for index, html in enumerate(prepared.leading): if index == decided and index < len(blocks) - 1: return index, 0 @@ -407,6 +413,29 @@ def block_row(self, fragment: HistoryFragment, font: QFont, width: int, y: int) top += height return 0, 0 + def header_pin_threshold(self, fragment: HistoryFragment, font: QFont, width: int) -> float | None: + """Minimum pixel offset `y` inside `fragment` at which its sticky header pins + (`(block, row) > (header_blocks - 1, 0)`), skipping layout of the last header block + itself (`Divider` after the globally cached `Gap`).""" + decided = fragment.header_blocks + if decided <= 0: + return 0.0 + _cell, line = self._font_metrics(font) + if decided == 1: + return line + blocks = fragment.line_blocks + key = self.fragment_key(fragment, font, width) + prepared = self.prepared_look(key) + if prepared is None: + return None + top = 0.0 + for index in range(min(decided - 1, len(prepared.leading))): + block_key = blocks[index].standalone_cache_key( + key, index, lambda header: self.header_key(header, font, width) + ) + top += self.measured_height(block_key, font, width, HtmlRow(prepared.leading[index])) + return top + line + def header_document(self, header: Divider, font: QFont, width: int) -> QTextDocument | None: """A pinned header laid out as its row lays it out at this width. Reuses the same cache key as `block_row` so crossing a message during scroll lays its header out once, @@ -1216,18 +1245,17 @@ def row_index(self, model_rows: FragmentRowList) -> int: def collapse_link(self) -> FragmentCollapse | None: return self.fragment.header_collapse_link() - @cached_property - def under(self) -> FragmentRowUnderTop: - """The block and line on the top edge, worked out when a header is pinned: every - scroll offset names the reader's message, and only a display frame pins.""" - block, row = self.window.rows.block_row(self.fragment, self.window.font(), self.width, self.into) - return FragmentRowUnderTop(self.fragment, block, row, self.left, self.width) - def reader_position(self, window: QtHistoryWindow) -> FragmentPosition: return FragmentPosition(self.fragment.key, self.into / self.height, self.height, block=0) def pinned_header(self, window: QtHistoryWindow) -> PinnedHeader: - return self.under.pinned_header() + fragment = self.fragment + dividers = fragment.pinned_dividers + if not dividers: + return PinnedHeader((), self.left, self.width, fragment.key.source) + threshold = self.window.rows.header_pin_threshold(fragment, self.window.font(), self.width) + headers = dividers if threshold is not None and self.into >= threshold else () + return PinnedHeader(headers, self.left, self.width, fragment.key.source) @dataclass(frozen=True) @@ -1871,13 +1899,8 @@ def unfilled_rows(self) -> int: return 0 return max(0, height - self.total_height()) - @property - def animated_travel(self) -> float: - """Pixels the rows are still being carried with no finger on them, as Textual answers - with its scroll animation's distance to its target: a head reveal's way to its head, - or a fling's momentum (`fling_travel`).""" - if (travel := self.head_reveal_travel()) is not None: - return travel + def toolkit_animated_travel(self) -> float: + """Pixels a fling's momentum (`fling_travel`) still carries the rows.""" return 0.0 if self.widget_gone else self.fling_travel() def fling_travel(self) -> float: @@ -2286,12 +2309,10 @@ def viewportEvent(self, event: QEvent) -> bool: # type: ignore[override] event.setContentPos(event.contentPos() - QPointF(0, origin)) return handled - def shift_travel(self, rows: float, destination: float) -> None: - """A head reveal glides to the same message; a finger's drag or fling goes on from - the same rows at the same speed. QScroller prepares again from the moved origin: a - fling it had planned to end at the loaded edge is planned again at its present - speed, into the rows that landed.""" - self.shift_arrival_motion(rows) + def shift_toolkit_travel(self, rows: float, destination: float) -> None: + """A finger's drag or fling goes on from the same rows at the same speed. QScroller + prepares again from the moved origin: a fling it had planned to end at the loaded edge + is planned again at its present speed, into the rows that landed.""" scroller = QScroller.scroller(self.viewport()) if scroller.state() != QScroller.State.Inactive: self._travel_origin += rows diff --git a/src/toad/qt/model_selection.py b/src/toad/qt/model_selection.py index 098b60eb6..86cca797d 100644 --- a/src/toad/qt/model_selection.py +++ b/src/toad/qt/model_selection.py @@ -34,9 +34,8 @@ from toad.client.model_selection import ( CatalogChoiceSelection, CatalogModelField, - HighlightPlacement, - KeepsHighlight, ModelSelectionCore, + RankedModel, ResetsHighlight, SessionChoiceSelection, ) @@ -121,44 +120,42 @@ async def _load_recents(self, generation: int, scope: str) -> None: recent = await self.recent_choices(scope) self.apply_recents(generation, scope, recent) - def filter_models(self, placement: HighlightPlacement) -> None: + def search_query(self) -> str: + return self.search_input.text() + + def highlighted_model_id(self) -> str | None: current_item = self.option_list.currentItem() - previous_id = current_item.data(self.MODEL_ID_ROLE) if current_item is not None else None - ranked, summary = self.rank_models(self.search_input.text()) + return current_item.data(self.MODEL_ID_ROLE) if current_item is not None else None + + def present_filtered_models( + self, + ranked: list[RankedModel], + highlighted_index: int | None, + summary: str, + ) -> None: self.option_list.blockSignals(True) self.option_list.clear() - ids: list[str | None] = [] for entry in ranked: item = QListWidgetItem(entry.plain_label) item.setData(self.MODEL_ID_ROLE, entry.choice.value) if entry.choice.description: item.setToolTip(entry.choice.description) self.option_list.addItem(item) - ids.append(entry.choice.value) - if ids: - self.option_list.setCurrentRow(placement.index(ids, previous_id)) - else: - self.option_list.setCurrentRow(-1) + self.option_list.setCurrentRow(highlighted_index if highlighted_index is not None else -1) self.option_list.blockSignals(False) self.count_label.setText(summary) def _on_search_changed(self, _text: str) -> None: - self.filter_models(ResetsHighlight()) - self.refilter = KeepsHighlight() + self.search_changed() def _on_row_highlighted(self, _row: int) -> None: - self.refilter = KeepsHighlight() + self.note_highlight_moved() def _on_item_activated(self, item: QListWidgetItem) -> None: model_id = item.data(self.MODEL_ID_ROLE) if model_id is not None: self.select_model(model_id) - def submit(self) -> None: - item = self.option_list.currentItem() - if item is not None and (model_id := item.data(self.MODEL_ID_ROLE)) is not None: - self.select_model(model_id) - def eventFilter(self, watched: QObject, event: QEvent) -> bool: # type: ignore[override] if watched is self.search_input and event.type() == QEvent.Type.KeyPress: key = event.key() diff --git a/src/toad/qt/submission_view.py b/src/toad/qt/submission_view.py index 3cd392c24..ee605b1bb 100644 --- a/src/toad/qt/submission_view.py +++ b/src/toad/qt/submission_view.py @@ -20,12 +20,11 @@ def show_send_failure(self, text: str) -> None: composer_block: str = "" - async def refresh_composer(self, access: ComposeAccess) -> None: + def apply_compose_access(self, composer, access: ComposeAccess) -> None: """Hold the composer with the destination's read-only reason, or release it, and offer files where the bus takes them.""" - self.composer_block = access.block_reason - self.on_composer("hold", lambda composer: composer.hold(self.composer_block)) - self.on_composer("files", lambda composer: composer.offer_files(access.takes_files)) + composer.hold(access.block_reason) + composer.offer_files(access.takes_files) def draws_user_message(self, reference) -> bool: return self.message_history.draws(reference) diff --git a/src/toad/qt/virtual_scroll.py b/src/toad/qt/virtual_scroll.py index 0a7dd69e8..6810e1330 100644 --- a/src/toad/qt/virtual_scroll.py +++ b/src/toad/qt/virtual_scroll.py @@ -1220,58 +1220,58 @@ def paintEvent(self, event) -> None: # type: ignore[override] if clip.isEmpty(): return painter = QPainter(viewport) - bg_color = self.rows.background_qcolor() - fragments = self.model_rows.fragments - count = len(fragments) - if count == 0: - painter.fillRect(clip, bg_color) - painter.end() - return - self._ensure_offsets() - scroll_y = self.verticalScrollBar().value() - scroll_x = self.horizontalScrollBar().value() - vp_w = vp_rect.width() - total_h = self._offsets[count] - top_y = scroll_y + clip.top() - bot_y = scroll_y + clip.bottom() - animating = self.has_active_arrivals - slide_pad = int(math.ceil(self.arrival_slide_distance)) if animating else 0 - if top_y >= total_h + slide_pad: - painter.fillRect(clip, bg_color) - painter.end() - return - if animating: - # Clear once before painting arriving rows so semi-transparent tiles and local - # upward slide offsets never ghost or erase sibling rows in the same burst. - painter.fillRect(clip, bg_color) - first = max(0, bisect_right(self._offsets, max(0, top_y - slide_pad)) - 1) - last = min(count - 1, bisect_right(self._offsets, min(total_h - 1, bot_y)) - 1) - last_bottom = -1 - self.rows.begin_paint(painter, vp_rect, animating=animating) try: - for row in range(first, last + 1): - h = self._heights[row] - if h <= 0: - continue - y = self._offsets[row] - scroll_y - if y > clip.bottom(): - break - if y + h + slide_pad - 1 < clip.top(): - continue - row_w = max(vp_w, self._extents[row]) - rect = QRect(-scroll_x, y, row_w, h) - self.rows.paint_row(painter, row, fragments[row], rect, dirty) - last_bottom = y + h - finally: - self.rows.end_paint() - # Fill any empty area below the final row (or above row 0 on overscroll) when - # not already pre-cleared for an active arrival. - if not animating: - if last_bottom >= 0 and last_bottom <= clip.bottom(): - painter.fillRect(QRect(clip.left(), max(clip.top(), last_bottom), clip.width(), clip.bottom() - max(clip.top(), last_bottom) + 1), bg_color) - elif last_bottom < 0: + bg_color = self.rows.background_qcolor() + fragments = self.model_rows.fragments + count = len(fragments) + if count == 0: + painter.fillRect(clip, bg_color) + return + self._ensure_offsets() + scroll_y = self.verticalScrollBar().value() + scroll_x = self.horizontalScrollBar().value() + vp_w = vp_rect.width() + total_h = self._offsets[count] + top_y = scroll_y + clip.top() + bot_y = scroll_y + clip.bottom() + animating = self.has_active_arrivals + slide_pad = int(math.ceil(self.arrival_slide_distance)) if animating else 0 + if top_y >= total_h + slide_pad: painter.fillRect(clip, bg_color) - painter.end() + return + if animating: + # Clear once before painting arriving rows so semi-transparent tiles and local + # upward slide offsets never ghost or erase sibling rows in the same burst. + painter.fillRect(clip, bg_color) + first = max(0, bisect_right(self._offsets, max(0, top_y - slide_pad)) - 1) + last = min(count - 1, bisect_right(self._offsets, min(total_h - 1, bot_y)) - 1) + last_bottom = -1 + self.rows.begin_paint(painter, vp_rect, animating=animating) + try: + for row in range(first, last + 1): + h = self._heights[row] + if h <= 0: + continue + y = self._offsets[row] - scroll_y + if y > clip.bottom(): + break + if y + h + slide_pad - 1 < clip.top(): + continue + row_w = max(vp_w, self._extents[row]) + rect = QRect(-scroll_x, y, row_w, h) + self.rows.paint_row(painter, row, fragments[row], rect, dirty) + last_bottom = y + h + finally: + self.rows.end_paint() + # Fill any empty area below the final row (or above row 0 on overscroll) when + # not already pre-cleared for an active arrival. + if not animating: + if last_bottom >= 0 and last_bottom <= clip.bottom(): + painter.fillRect(QRect(clip.left(), max(clip.top(), last_bottom), clip.width(), clip.bottom() - max(clip.top(), last_bottom) + 1), bg_color) + elif last_bottom < 0: + painter.fillRect(clip, bg_color) + finally: + painter.end() def resizeEvent(self, event) -> None: # type: ignore[override] if event.size().width() != event.oldSize().width(): diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index c64045a3e..5b6d49edb 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -318,7 +318,15 @@ def activate(self, window: QtToadApp) -> None: self.toggle_members() -class OpenSection(WelcomeSectionLine, SidebarSection): +class OpensExpandedItem(SidebarItem): + """A sidebar item whose shared model owns whether it starts expanded (`opens_expanded`).""" + + def placed(self) -> None: + super().placed() + self.setExpanded(self.opens_expanded()) + + +class OpenSection(WelcomeSectionLine, SidebarSection, OpensExpandedItem): """A titled section of rows that are not the sidebar model's (the buses, in the sidebar while it holds the window and in the bus switcher): open as the shared sidebar state says (`WelcomeSectionLine`), so it stays as the reader left it however often it is drawn @@ -332,10 +340,6 @@ def section_title(self) -> str: def sidebar_state(self): return self.treeWidget().window.sidebar_state - def placed(self) -> None: - super().placed() - self.setExpanded(self.opens_expanded()) - class StatusSection(SidebarStatusLine, SidebarSection): """The status line at the top of the sidebar (the shared `SidebarStatusLine`, Textual's @@ -358,7 +362,7 @@ def update_status_in(self, root: QTreeWidgetItem, text: str | None) -> bool: return True -class ConversationRow(QtClockedWave, TargetLine, SidebarItem): +class ConversationRow(QtClockedWave, TargetLine, OpensExpandedItem): """A row that opens its target through the target's own polymorphic `open(context)`. `target` is a `NavigationTarget` (not specifically a `HistoryRouted`) because threads @@ -379,7 +383,6 @@ def placed(self) -> None: """A new channel line opens as its target opens by default (the feed does), as the Textual sidebar's ChannelGroup does; a working thread's line starts waving.""" super().placed() - self.setExpanded(self.opens_expanded()) self.follow_activity(self.busy) def take(self, line: SidebarItem) -> None: @@ -1434,10 +1437,6 @@ def _composer_mounted(self, composer: Composer) -> None: composer.labelled(self._composer_label) self.sync_status() - @property - def composer_placeholder(self) -> str: - return self.conversation.initial_placeholder - @property def mode(self) -> str: return self.entry.mode @@ -1509,9 +1508,6 @@ def compose_peer_activity(self, peer: ThreadIncarnation) -> Iterator[QtGoalBar | self.thread_activity = PeerActivity(self.app, self.app.renderer, peer, self.sync_working) yield self.thread_activity - def show_mention_candidates(self, mentions) -> None: - self.on_composer("mentions", lambda composer: composer.set_mention_candidates(mentions)) - # Commands the composer offers after a / @property diff --git a/src/toad/widgets/comms_chat.py b/src/toad/widgets/comms_chat.py index 1f88d87a5..cf6dadda3 100644 --- a/src/toad/widgets/comms_chat.py +++ b/src/toad/widgets/comms_chat.py @@ -156,10 +156,6 @@ async def _command_source_changed(self, event: core_events.LinkContextChanged) - await super()._command_source_changed(event) self.refresh_identity() - @property - def composer_placeholder(self) -> str: - return self.conversation.initial_placeholder - def attach_pooled_composer(self) -> Prompt | None: """Register this chat's first prompt in the shared workspace pool, or check out and reparent the pool's live prompt when this chat is the active tab.""" @@ -257,11 +253,6 @@ def compose_peer_activity(self, peer: ThreadIncarnation) -> ComposeResult: self.thread_activity = ConversationSessionDetails(peer) yield self.thread_activity - def show_mention_candidates(self, mentions) -> None: - # Queue mention updates when this chat's pooled composer is currently lent to another - # active tab, and apply them immediately when this chat holds it. - self.on_composer("mentions", lambda prompt: prompt.set_mention_candidates(mentions)) - def queue_controls_changed(self) -> None: """A message view has no goal bar to redraw.""" diff --git a/src/toad/widgets/history_anchor.py b/src/toad/widgets/history_anchor.py index a1cfdb9e1..ff3870be2 100644 --- a/src/toad/widgets/history_anchor.py +++ b/src/toad/widgets/history_anchor.py @@ -309,9 +309,8 @@ def history_geometry_targets(self) -> tuple[Widget, ...]: """The widgets the kept position is measured from: layout places them even off screen.""" return self.reader_for_layout().bodies(self) - def shift_travel(self, rows: float, destination: float) -> None: + def shift_toolkit_travel(self, rows: float, destination: float) -> None: """A running scroll animation and its target move by the rows layout moved the reader.""" - self.shift_arrival_motion(rows) self.app.animator.transform_running_animation(self, "scroll_y", lambda value: value + rows) self.scroll_target_y = destination + rows @@ -346,10 +345,7 @@ def lookahead(self) -> DirectionalPreparation: def runway(self, history) -> OffScreenRunway: return arranged(history).runway(arranged(self)) - @property - def animated_travel(self) -> float: - if (travel := self.head_reveal_travel()) is not None: - return travel + def toolkit_animated_travel(self) -> float: return self.scroll_target_y - self.scroll_y if self.app.animator.is_being_animated(self, "scroll_y") else 0 @property diff --git a/src/toad/widgets/model_selection.py b/src/toad/widgets/model_selection.py index 40c114fd2..f2f0b3922 100644 --- a/src/toad/widgets/model_selection.py +++ b/src/toad/widgets/model_selection.py @@ -20,10 +20,10 @@ ) from toad.client.model_selection import ( - HighlightPlacement, KeepsHighlight, ModelChoice, ModelSelectionCore, + RankedModel, ResetsHighlight, match_score, ) @@ -190,10 +190,19 @@ async def load_recents(self, generation: int, scope: str) -> None: recent = await self.recent_choices(scope) self.apply_recents(generation, scope, recent) - def filter_models(self, placement: HighlightPlacement) -> None: + def search_query(self) -> str: + return self.search_input.value + + def highlighted_model_id(self) -> str | None: highlighted = self.option_list.highlighted_option - previous_id = highlighted.id if highlighted is not None else None - ranked, summary = self.rank_models(self.search_input.value) + return highlighted.id if highlighted is not None else None + + def present_filtered_models( + self, + ranked: list[RankedModel], + highlighted_index: int | None, + summary: str, + ) -> None: options = [] for entry in ranked: model = entry.choice @@ -208,19 +217,13 @@ def filter_models(self, placement: HighlightPlacement) -> None: # Only the user moves the highlight with an OptionHighlighted; see on_option_highlighted. with self.option_list.prevent(OptionList.OptionHighlighted): self.option_list.set_options(options) - if options: - self.option_list.highlighted = placement.index( - [option.id for option in options], previous_id - ) - else: - self.option_list.highlighted = None + self.option_list.highlighted = highlighted_index self.query_one(ModelCount).update(summary) @on(Input.Changed) def on_search_changed(self, event: Input.Changed): event.stop() - self.filter_models(ResetsHighlight()) - self.refilter = KeepsHighlight() + self.search_changed() @on(Input.Submitted) def on_search_submitted(self, event: Input.Submitted) -> None: @@ -231,7 +234,7 @@ def on_search_submitted(self, event: Input.Submitted) -> None: def on_option_highlighted(self, event: OptionList.OptionHighlighted): """Arrow keys and the pointer: filter_models moves the highlight without this event.""" event.stop() - self.refilter = KeepsHighlight() + self.note_highlight_moved() @on(OptionList.OptionSelected, "SelectionOptionList") def on_option_selected(self, event: OptionList.OptionSelected): @@ -248,6 +251,4 @@ def submit(self): if connect.has_focus: connect.activate() return - if (option := self.option_list.highlighted_option) is not None: - if option.id is not None: - self.select_model(option.id) + super().submit() diff --git a/src/toad/widgets/prompt.py b/src/toad/widgets/prompt.py index dea9de63e..58fa52016 100644 --- a/src/toad/widgets/prompt.py +++ b/src/toad/widgets/prompt.py @@ -872,7 +872,7 @@ def reset_editor_draft(self, host: ComposerPoolHost, text: str) -> None: editor.post_message(editor.Changed(editor).set_sender(editor)) editor.update_suggestion() - def rebind_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> None: + def rebind_toolkit_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> None: self.submissions = host.submissions self._bind_conversation_reactives(host) self.slash_commands = list(draft.commands) @@ -881,11 +881,8 @@ def rebind_conversation(self, host: ComposerPoolHost, draft: ComposerDraft) -> N editor = self.prompt_text_area editor.disabled = bool(draft.read_only_reason) editor.tooltip = draft.read_only_reason or None - self.kept_delivery_preview = None self.sync_configuration() self.sync_session() - self.sync_queue() - self.update_prompt() @property def input_decision(self) -> InputDecision: diff --git a/tests/model/test_android_perf_ux_arrivals.py b/tests/model/test_android_perf_ux_arrivals.py index 8ac197019..4083cb309 100644 --- a/tests/model/test_android_perf_ux_arrivals.py +++ b/tests/model/test_android_perf_ux_arrivals.py @@ -2343,7 +2343,8 @@ def __init__(self) -> None: self.tail_scroll_y = 240.0 self.follows_tail = True self.lookahead = MagicMock() - self.preparations = 0 + self.notification_checks = 0 + self.histories = (self,) self._clock = AnimationClock(lambda _interval: None) @property @@ -2360,28 +2361,31 @@ def arrival_rows_height(self, keys): 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 + def check_visible_notifications(self) -> None: + self.notification_checks += 1 win = _Window() - # Non-glide programmatic layout scroll requests preparation once. + # Non-glide tail follow (`check_follow`) refreshes visible notifications once without + # re-arming source page reads, while an older-page `layout_scroll` shift stays quiet. + from toad.client.history_changes import NoHistoryChange with win.layout_scroll(): win.scroll_y = 100.0 - assert win.preparations == 1 + assert win.notification_checks == 0 + assert NoHistoryChange().check_follow(win) is True + assert win.scroll_y == 240.0 + assert win.notification_checks == 1 - # Mid-glide ticks must NOT spam preparation, while landing requests it once. + # Mid-glide ticks must NOT spam notifications, while landing refreshes them once. + win.scroll_y = 100.0 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 + assert win.notification_checks == 1 arrival.land() assert win.scroll_y == 240.0 - assert win.preparations >= 2 + assert win.notification_checks == 2 def test_qt_goal_bar_fit_document_uses_wrapped_height_for_width(monkeypatch): @@ -2424,3 +2428,110 @@ def test_qt_goal_bar_fit_document_uses_wrapped_height_for_width(monkeypatch): ) finally: win.deleteLater() + + +def test_header_pin_threshold_matches_block_row_without_laying_out_dividers(monkeypatch): + monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen") + QApplication.instance() or QApplication([]) + from dataclasses import dataclass + from PySide6.QtGui import QFont + from toad.client.line_blocks import Body, Divider, Gap, MutedRole, Span + from toad.qt.history import HistoryRowDelegate, QtLineRenderer, RenderedRow + from toad.qt.lines import DiffSettings, LinkContext + + class _EmptyRefs: + def find(self, text): + return () + + class _View: + def viewport_width(self): + return 412 + + def invalidate_row_height(self, row): + pass + + def rows_changed(self): + pass + + def rows_repainted(self): + pass + + @dataclass(frozen=True) + class _Frag: + key: tuple + shown: int + revision: int + line_blocks: tuple + header_blocks: int + pinned_dividers: tuple + + def sticky_header(self, block, row): + return self.pinned_dividers if (block, row) > (self.header_blocks - 1, 0) else () + + font = QFont("monospace", 10) + renderer = QtLineRenderer(current_scheme(os.environ), LinkContext(Path("."), _EmptyRefs()), DiffSettings()) + width = 412 + frags = [] + for idx in range(5): + divider = Divider((Span(f"sender-{idx} -> #comms ยท 10:0{idx}", MutedRole),), MutedRole) + blocks = (Gap(), divider, Body(f"Message {idx}\nline 2")) + frags.append(_Frag(("m", idx), 0, 0, blocks, 2, (divider,))) + + d_ref = HistoryRowDelegate(_View(), renderer, object()) + d_fast = HistoryRowDelegate(_View(), renderer, object()) + for frag in frags: + leading = tuple(renderer.at_width(50).html((b,)) for b in frag.line_blocks[:3]) + row = RenderedRow(renderer.at_width(50).html(frag.line_blocks), leading, frag.pinned_dividers) + d_ref._prepared[d_ref.fragment_key(frag, font, width)] = row + d_fast._prepared[d_fast.fragment_key(frag, font, width)] = row + + for frag in frags: + for y in range(0, 60, 3): + blk, row_idx = d_ref.block_row(frag, font, width, y) + expected = frag.sticky_header(blk, row_idx) + threshold = d_fast.header_pin_threshold(frag, font, width) + actual = frag.pinned_dividers if threshold is not None and y >= threshold else () + assert actual == expected + # Only the single globally shared Gap block is ever laid out, never any Divider. + assert len(d_fast._documents) == 1 + + +def test_every_history_fragment_subclass_supports_retain_painted(): + """Every HistoryFragment painted by QtHistoryWindow (including tool, thinking, context, + and live transcript fragments) must support retain_painted without crashing paintEvent.""" + import toad.qt.agent_surface + import toad.qt.live_turn + import toad.qt.transcript_fragments + from toad.client.fragments import EvidencedFragment, HistoryFragment + from toad.client.history import ReadMarkedHistory + + def walk(cls): + out = set() + for sub in cls.__subclasses__(): + out.add(sub) + out.update(walk(sub)) + return out + + all_subclasses = walk(HistoryFragment) + assert toad.qt.transcript_fragments.QtToolTranscriptFragment in all_subclasses + assert toad.qt.transcript_fragments.QtThinkingTranscriptFragment in all_subclasses + assert toad.qt.agent_surface.QtLiveToolFragment in all_subclasses + assert toad.qt.live_turn.QtLiveFragment in all_subclasses + + missing = [c.__name__ for c in all_subclasses if not callable(getattr(c, "retain_painted", None))] + assert not missing + + class _DummyOwner: + def __init__(self): + self._painted_reads = {} + self.marked = 0 + + def mark_visible_after_paint(self): + self.marked += 1 + + owner = _DummyOwner() + non_evidenced = HistoryFragment(events=()) + ReadMarkedHistory.retain_painted(owner, non_evidenced) + assert owner._painted_reads == {} + assert owner.marked == 0 + assert "retain_painted" in EvidencedFragment.__dict__ diff --git a/tests/textual/test_channel_scrolling.py b/tests/textual/test_channel_scrolling.py index 9f4a6de25..ba4b6419e 100644 --- a/tests/textual/test_channel_scrolling.py +++ b/tests/textual/test_channel_scrolling.py @@ -207,7 +207,7 @@ async def test_scrolling_prepared_history_keeps_its_intrinsic_content_geometry(w chat, history, window = await long_channel(workspace, ui) for _ in range(4): await ui.press("pageup") - await ui.until(lambda: window.max_scroll_y > 12, + await ui.until(lambda: window.max_scroll_y > 12 and history.state.accepts_source_work, why="prepared rows on both sides of the scroll trial") window.scroll_to(y=window.max_scroll_y / 2, animate=False, immediate=True) await ui.step() diff --git a/tests/textual/test_pooled_composer_neovim.py b/tests/textual/test_pooled_composer_neovim.py index 836c7c3ba..d8bb8f937 100644 --- a/tests/textual/test_pooled_composer_neovim.py +++ b/tests/textual/test_pooled_composer_neovim.py @@ -76,7 +76,7 @@ def draws_user_message(self) -> bool: def record_input(self, text: str) -> None: pass - async def refresh_composer(self, access) -> None: + def apply_compose_access(self, composer, access) -> None: pass @property diff --git a/tests/textual/test_worker_failed_toasts.py b/tests/textual/test_worker_failed_toasts.py index 6e848dedd..2f5226877 100644 --- a/tests/textual/test_worker_failed_toasts.py +++ b/tests/textual/test_worker_failed_toasts.py @@ -61,7 +61,11 @@ def observe(_view, _access, resume): return ResourceRelease() work = SourcePublicationRequests(owner=None) - view = SimpleNamespace(app=SimpleNamespace(coordination_access=None)) + view = SimpleNamespace( + app=SimpleNamespace(coordination_access=SimpleNamespace(events=SimpleNamespace())), + retire_core=lambda _sub: None, + observe_core_callback=lambda _events, _kind, _cb: object(), + ) work.defer(SimpleNamespace(binding=SimpleNamespace(view=view), thread_scope=SimpleNamespace(observe=observe))) assert borrowed == [work.thread_rows_changed] diff --git a/tools/qt_scroll_profile.py b/tools/qt_scroll_profile.py index 5462c0df0..e9e4e344e 100644 --- a/tools/qt_scroll_profile.py +++ b/tools/qt_scroll_profile.py @@ -32,7 +32,7 @@ from pathlib import Path import qasync -from PySide6.QtCore import QEvent, QPoint, QPointF, Qt +from PySide6.QtCore import QEvent, QEventLoop, QPoint, QPointF, Qt from PySide6.QtGui import QWheelEvent from PySide6.QtWidgets import QApplication @@ -68,6 +68,11 @@ def summary(name: str, frames: list[float], latencies: list[float]) -> dict: } +def flush_qt_events() -> None: + """Drain Qt paint/timer events without re-entering qasync's asyncio socket notifiers.""" + QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) + + class ScrollDrive: """Opens #comms, loads pages, and times the reader's scrolling interactions.""" @@ -124,7 +129,7 @@ def at_scroll(self, value: float) -> tuple[float, float]: """Apply one scroll position as input, flush the frame, and time both.""" start = time.perf_counter() self.window.scroll_y = value - QApplication.processEvents() + flush_qt_events() frame = self.frame() latency = (time.perf_counter() - start) * 1000.0 return frame, latency @@ -143,7 +148,7 @@ def fling_positions(self) -> list[float]: async def measure_fling(self) -> dict: self.window.scroll_y = self.window.max_scroll_y - QApplication.processEvents() + flush_qt_events() frames, latencies = [], [] for value in self.fling_positions(): frame, latency = self.at_scroll(value) @@ -155,7 +160,7 @@ async def measure_wheel(self) -> dict: """A wheel burst that reverses partway: Qt routes each step through wheelEvent.""" viewport = self.window.viewport() self.window.scroll_y = self.window.max_scroll_y / 2 - QApplication.processEvents() + flush_qt_events() frames, latencies = [], [] for step in range(24): delta = -120 if step < 12 else 120 # scroll up, then reverse @@ -164,7 +169,7 @@ async def measure_wheel(self) -> dict: QPoint(0, 0), QPoint(0, delta), Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier, Qt.ScrollPhase.NoScrollPhase, False) QApplication.sendEvent(viewport, event) - QApplication.processEvents() + flush_qt_events() frame = self.frame() frames.append(frame) latencies.append((time.perf_counter() - start) * 1000.0) @@ -193,14 +198,14 @@ async def measure_arrival(self) -> dict: rows, which is exactly what one wire arrival runs. Time the frame and the reader's displacement (a jump the reader would see).""" self.window.scroll_y = self.window.max_scroll_y * 0.4 - QApplication.processEvents() + flush_qt_events() newest = self.history.pages[-1] frames, latencies, jumps = [], [], [] for _ in range(12): before = self.window.scroll_y start = time.perf_counter() newest.range_changed() - QApplication.processEvents() + flush_qt_events() frame = self.frame() frames.append(frame) latencies.append((time.perf_counter() - start) * 1000.0) @@ -264,6 +269,10 @@ async def run(profile: Path, out: Path, do_profile: bool) -> None: finally: app.close() await app.close_client() + current = asyncio.current_task() + for task in asyncio.all_tasks(): + if task is not current and not task.done(): + task.cancel() QApplication.quit()