diff --git a/src/toad/acp/agent_controller.py b/src/toad/acp/agent_controller.py index dfeea4680..78a65464a 100644 --- a/src/toad/acp/agent_controller.py +++ b/src/toad/acp/agent_controller.py @@ -159,16 +159,7 @@ async def restore(self, binding: SurfaceBinding) -> None: async def publish_transcript_snapshot( self, update: TranscriptSnapshotUpdate, binding: SurfaceBinding, session: SessionBinding ) -> None: - if binding.target is None or not session.accepts_snapshot(update.identity, self.agent): - return # No view or matching request owns this publication. - snapshot = await self.transcripts.publication(update) - if self.session is not session: - return - if self.surface is not binding: - return - if not session.accepts_snapshot(snapshot.identity, self.agent): - return - self.agent.events.publish(core_events.CommsUpdated(snapshot, session.session_id)) + await binding.publish_transcript_snapshot(session, update, self) def connection_closed(self) -> None: from toad.core.events import McpClientStopped diff --git a/src/toad/ansi/_ansi.py b/src/toad/ansi/_ansi.py index 707ea2045..aac9c8965 100644 --- a/src/toad/ansi/_ansi.py +++ b/src/toad/ansi/_ansi.py @@ -52,6 +52,13 @@ class DECInvoke(NamedTuple): gr: int | None = None shift: int | None = None + def apply_slots(self, owner: DECState) -> None: + """Apply GL or GR slot selection from this DEC invocation onto the DEC state.""" + if self.gl is not None: + owner.gl_slot = self.gl + elif self.gr is not None: + owner.gr_slot = self.gr + class EscapeSequence(DeclaredFamily, affix="Sequence"): """External ESC introducer declarations own sequence consumption.""" @@ -705,9 +712,7 @@ def change(cls, state: TerminalState, enabled: bool) -> None: class MouseMode(TerminalMode): @classmethod def change(cls, state: TerminalState, enabled: bool) -> None: - if state.mouse_tracking is None: - state.mouse_tracking = MouseTracking() - cls.update(state.mouse_tracking, enabled) + cls.update(state.ensure_mouse_tracking(), enabled) @classmethod @abstractmethod @@ -726,9 +731,7 @@ def change(cls, state: TerminalState, enabled: bool) -> None: if not enabled: state.mouse_tracking = None else: - if state.mouse_tracking is None: - state.mouse_tracking = MouseTracking() - state.mouse_tracking.tracking = cls.tracking + state.ensure_mouse_tracking().tracking = cls.tracking class MouseButtonMode(MouseTrackingMode, declared_name="1000"): @@ -1255,10 +1258,7 @@ def update(self, dec: DEC | None, dec_invoke: DECInvoke | None) -> None: if dec_invoke.shift: self.shift = dec_invoke.shift else: - if dec_invoke.gl is not None: - self.gl_slot = dec_invoke.gl - elif dec_invoke.gr is not None: - self.gr_slot = dec_invoke.gr + dec_invoke.apply_slots(self) def translate(self, text: str) -> str: translate_table: dict[int, str] | None @@ -1712,3 +1712,9 @@ def update_line( buffer.line_to_fold.append(len(buffer.folded_lines)) for fold in line_record.folds: buffer.folded_lines.append(fold) + + def ensure_mouse_tracking(self) -> MouseTracking: + """Return the active mouse tracking record, creating it on first use.""" + if self.mouse_tracking is None: + self.mouse_tracking = MouseTracking() + return self.mouse_tracking diff --git a/src/toad/client/commands.py b/src/toad/client/commands.py index 969fbec11..dde45ed89 100644 --- a/src/toad/client/commands.py +++ b/src/toad/client/commands.py @@ -201,6 +201,10 @@ def close_session(self) -> None: def request_new_session(self, prompt: str) -> None: """Open a new session in this conversation's working directory.""" + def default_testimonial_text(self): + """Build the default testimonial message using the active agent title when present.""" + return f"I'm running {self.agent_title} in the terminal with Toad." if self.agent_title is not None else 'Try Toad, the universal interface for AI in your terminal' + class SharedContextualCommand(ABC): """A command available for a target context. Native commands inherit this diff --git a/src/toad/client/reader_position.py b/src/toad/client/reader_position.py index 3d4f21670..7adb09862 100644 --- a/src/toad/client/reader_position.py +++ b/src/toad/client/reader_position.py @@ -169,6 +169,16 @@ def find_in(self, pages: Iterator[ReaderPage], position: FragmentPosition) -> Fr """Already located; `UnloadedFragment` searches the remaining pages.""" return self + def reveal_above(self, window) -> bool: + """Start head reveal if this fragment location is laid out above the current scroll position.""" + if self.laid_out(window): + target_y = self.destination(window, 0.0) + if target_y < window.scroll_y: + window.release_anchor() + window.start_head_reveal(target_y) + return True + return False + class UnloadedFragment(FragmentLocation): """No loaded page draws a destination for this fragment occurrence.""" @@ -192,6 +202,9 @@ def find_in(self, pages: Iterator[ReaderPage], position: FragmentPosition) -> Fr return page.fragment_row(position.key, position.block).find_in(pages, position) return self + def reveal_above(self, window) -> bool: + return False + class ArrivalTarget(ABC): """Where an arriving message glides a following viewport, and how it lands.""" diff --git a/src/toad/client/session_tracker.py b/src/toad/client/session_tracker.py index b4ed48faf..6b400540b 100644 --- a/src/toad/client/session_tracker.py +++ b/src/toad/client/session_tracker.py @@ -130,6 +130,11 @@ def welcome_section_open(self, title: str) -> bool: def set_welcome_section_open(self, title: str, value: bool) -> None: self.expanded[f"welcome:{title}"] = value + def preserve_selected_target(self) -> None: + """Keep the newly selected row in selected_targets when a prior selection existed.""" + if self.selected is not None: + self.selected_targets = (self.selected,) + @dataclass(frozen=True) class SessionName: diff --git a/src/toad/client/structured_context.py b/src/toad/client/structured_context.py index 0cbeb75d1..ff2827ad0 100644 --- a/src/toad/client/structured_context.py +++ b/src/toad/client/structured_context.py @@ -59,7 +59,9 @@ class StructuredPart(ABC): kind_title: ClassVar[str] = "Section" badge_titles: ClassVar[tuple[str, ...]] = () - expands_in_tree: ClassVar[bool] = True + def collapses_solo_in_tree(self): + """Whether a single part with no children omits its wrapper section node.""" + return False @property @abstractmethod @@ -381,7 +383,8 @@ class AnswerPart(BodyTextPart): """Plain assistant answer text outside ``, ``, and `` blocks.""" kind_title = "Answer" - expands_in_tree = False + def collapses_solo_in_tree(self): + return not self.children body_text: str diff --git a/src/toad/core/context_inspection.py b/src/toad/core/context_inspection.py index e9d9acf56..abd683e78 100644 --- a/src/toad/core/context_inspection.py +++ b/src/toad/core/context_inspection.py @@ -471,7 +471,7 @@ def structured_parts(self) -> tuple[StructuredPart, ...]: def children(self): parts = self.structured_parts() - if not parts or (len(parts) == 1 and not parts[0].expands_in_tree and not parts[0].children): + if not parts or (len(parts) == 1 and parts[0].collapses_solo_in_tree()): return () return tuple( StructuredSectionNode(f"{self.key}/part/{i}", part) diff --git a/src/toad/qt/virtual_scroll.py b/src/toad/qt/virtual_scroll.py index 6810e1330..a107159eb 100644 --- a/src/toad/qt/virtual_scroll.py +++ b/src/toad/qt/virtual_scroll.py @@ -324,6 +324,10 @@ def __init__(self, size: QSize | None = None, extent: int | None = None) -> None self.size = size self.extent = extent + def extent_or(self, width: int): + """Return the recorded row extent or the fallback viewport width.""" + return width if self.extent is None else self.extent + class RowSize: """One row slot's measured size at the current font and width, and its preparation key.""" @@ -337,6 +341,24 @@ def __init__(self, key: Hashable, size: QSize | None, font: QFont, estimated: bo self.estimated = estimated self.row = row + def measured_metrics(self, width: int, owner: RowDocumentStore): + """Return (height, hinted_width, estimated) when this row size is populated.""" + if self.size is not None: + return (self.size.height(), owner.hinted_width(self.key, width), self.estimated) + return None + + def usable_row(self, measured: bool) -> RowSize | None: + """Return this row size entry when present and acceptable under the measured filter.""" + if self.size is None or (measured and self.estimated): + return None + return self + + def usable_size(self, measured: bool) -> QSize | None: + """Return the kept QSize when present and acceptable under the measured filter.""" + if self.size is None or (measured and self.estimated): + return None + return self.size + class ViewportCanvas: """Shared canvas surface exposed to row delegates for tap highlights and unified viewport @@ -552,7 +574,7 @@ def row_extent(self, key: Hashable, width: int) -> int: if widths is None: return width entry = widths.get(width) - return width if entry is None or entry.extent is None else entry.extent + return width if entry is None else entry.extent_or(width) def measured_height(self, key: Hashable, font: QFont, width: int, formatting: RowFormatting) -> int: size = self.measured_size_for(key, width) @@ -710,17 +732,17 @@ def kept_size(self, row: int, *, measured: bool = False) -> QSize | None: if row < 0 or row >= len(self._row_sizes): return None kept = self._row_sizes[row] - if kept is None or kept.size is None or (measured and kept.estimated): + if kept is None: return None - return kept.size + return kept.usable_size(measured) def kept_row(self, row: int, *, measured: bool = False) -> RowSize | None: if row < 0 or row >= len(self._row_sizes): return None kept = self._row_sizes[row] - if kept is None or kept.size is None or (measured and kept.estimated): + if kept is None: return None - return kept + return kept.usable_row(measured) def hinted_width(self, key: Hashable, layout_width: int) -> int: return layout_width @@ -730,8 +752,8 @@ def measure_row(self, row: int, fragment, font: QFont, width: int, *, allow_esti if not fragment.has_blocks: return 0, width, False kept = self.kept_row(row, measured=not allow_estimate) - if kept is not None and kept.size is not None: - return kept.size.height(), self.hinted_width(kept.key, width), kept.estimated + if kept is not None and (_found := kept.measured_metrics(width, self)) is not None: + return _found key = self.preparation_key_for(fragment, font, width) size = self.measured_size_for(key, width) if size is not None: diff --git a/src/toad/sidebar_navigation.py b/src/toad/sidebar_navigation.py index b1159ee9b..b9fb89a09 100644 --- a/src/toad/sidebar_navigation.py +++ b/src/toad/sidebar_navigation.py @@ -92,8 +92,8 @@ def apply(self) -> None: with self.sidebar.selection_change(): header = SidebarSelection(selected.channel, selected.channel) state.selected = header if self.sidebar.row_for(header) is not None else None - if had_selection and not state.selected_targets and state.selected is not None: - state.selected_targets = (state.selected,) + if had_selection and (not state.selected_targets): + state.preserve_selected_target() def restore_scroll(self) -> bool: if not self.sidebar.model_state.shows_model(): diff --git a/src/toad/slash_command.py b/src/toad/slash_command.py index 39f7a5824..7390bc86a 100644 --- a/src/toad/slash_command.py +++ b/src/toad/slash_command.py @@ -334,9 +334,7 @@ def parse(cls, arguments: str) -> Self: async def apply(self, conversation: AgentConversationCommands) -> bool: default = ( - f"I'm running {conversation.agent_title} in the terminal with Toad." - if conversation.agent_title is not None - else "Try Toad, the universal interface for AI in your terminal" + conversation.default_testimonial_text() ) conversation.app.open_url(tweet_intent_url( self.text or default, diff --git a/src/toad/surface_binding.py b/src/toad/surface_binding.py index 6e612fe63..85e51f089 100644 --- a/src/toad/surface_binding.py +++ b/src/toad/surface_binding.py @@ -5,6 +5,7 @@ from agent_comms.nominal.declared_family import DeclaredFamily from metaclass_registry.mro_dispatch import MroDispatch +from toad.core import events as core_events class SurfaceBinding(DeclaredFamily, affix="SurfaceBinding"): @@ -53,6 +54,18 @@ def post(self, message) -> bool: ... def close(self) -> None: """An absent frontend has no subscription to release.""" + async def publish_transcript_snapshot(self, session, update, owner) -> None: + if self.target is None or not session.accepts_snapshot(update.identity, owner.agent): + return + snapshot = await owner.transcripts.publication(update) + if owner.session is not session: + return + if owner.surface is not self: + return + if not session.accepts_snapshot(snapshot.identity, owner.agent): + return + owner.agent.events.publish(core_events.CommsUpdated(snapshot, session.session_id)) + class ViewSurfaceBinding(SurfaceBinding, MroDispatch): """The surface a frontend's view lends its bound agent: it holds the view weakly, so a diff --git a/src/toad/target_commands.py b/src/toad/target_commands.py index d313f6c43..30f37a2a7 100644 --- a/src/toad/target_commands.py +++ b/src/toad/target_commands.py @@ -60,6 +60,10 @@ def execute_command(self, command): self.current() command.execute(self) + def has_closable_session(self): + """Whether this context names a live session mode that can be closed.""" + return self.mode is not None and self.app.has_session(self.mode) + class ContextualCommand(SharedContextualCommand, CommandPresentation, ABC): @@ -177,9 +181,7 @@ class CloseViewCommand(ViewCommand, declared_name="close_view"): def available(self, ctx: TargetContext) -> bool: return ( - not ctx.targets - and ctx.mode is not None - and ctx.app.has_session(ctx.mode) + not ctx.targets and ctx.has_closable_session() ) def execute(self, ctx: TargetContext) -> None: diff --git a/src/toad/widgets/transcript_history.py b/src/toad/widgets/transcript_history.py index 0cdcccce1..cc5917e30 100644 --- a/src/toad/widgets/transcript_history.py +++ b/src/toad/widgets/transcript_history.py @@ -698,12 +698,8 @@ async def reveal_message_head( # glide its head smoothly into view through the shared `HeadReveal` transition. if head_placement.draws and window.animation_clock.enabled: placed_head = page.fragment_row(head.key, 0) - if placed_head.located and placed_head.laid_out(window): - target_y = placed_head.destination(window, 0.0) - if target_y < window.scroll_y: - window.release_anchor() - window.start_head_reveal(target_y) - return head + if placed_head.reveal_above(window): + return head # A head with no drawn child has no row to place the reader on. return await head.lines_for(width, theme).block_span(lambda span: span.drawn).placed_by( partial(self._place_reader_at_head, head, fragment, page, staged, current),