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
11 changes: 1 addition & 10 deletions src/toad/acp/agent_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 16 additions & 10 deletions src/toad/ansi/_ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
Expand All @@ -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"):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions src/toad/client/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions src/toad/client/reader_position.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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."""
Expand Down
5 changes: 5 additions & 0 deletions src/toad/client/session_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 5 additions & 2 deletions src/toad/client/structured_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -381,7 +383,8 @@ class AnswerPart(BodyTextPart):
"""Plain assistant answer text outside `<think>`, `<ctx>`, and `<tool_call>` blocks."""

kind_title = "Answer"
expands_in_tree = False
def collapses_solo_in_tree(self):
return not self.children

body_text: str

Expand Down
2 changes: 1 addition & 1 deletion src/toad/core/context_inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 29 additions & 7 deletions src/toad/qt/virtual_scroll.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions src/toad/sidebar_navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
4 changes: 1 addition & 3 deletions src/toad/slash_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions src/toad/surface_binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions src/toad/target_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down Expand Up @@ -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:
Expand Down
8 changes: 2 additions & 6 deletions src/toad/widgets/transcript_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading