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
6 changes: 6 additions & 0 deletions src/toad/client/fragments.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,12 @@ def source_identity(self) -> EventSourceKey | ToolCallId:
def key(self) -> FragmentKey:
return FragmentKey(self.source_identity, self.part_position.index)

@property
def pinned_dividers(self) -> tuple[Divider, ...]:
"""The header a top row in this fragment pins, and an arrival burst stacks: none for a
fragment that draws no header."""
return ()

@property
def details_link(self) -> FragmentDetails:
return FragmentDetails(self.key)
Expand Down
153 changes: 137 additions & 16 deletions src/toad/client/history_changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from abc import abstractmethod
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, ClassVar

from toad.client.reader_position import (
BlockPosition,
Expand All @@ -21,8 +21,10 @@
)


from toad.client.line_blocks import Divider, MutedRole

if TYPE_CHECKING:
from toad.client.line_blocks import Divider
from toad.client.fragments import FragmentKey, HistoryFragment
from toad.client.transcript_fragments import TranscriptFragment
from toad.widgets.history_anchor import HistoryWindow
from toad.widgets.transcript_history import FragmentSpan, TranscriptPageView
Expand Down Expand Up @@ -94,23 +96,113 @@ class PinnedHeader:
width: int


@dataclass(frozen=True)
class BurstMessage:
"""One message of an arrival burst: where it is drawn (`key`, its first arriving part) and
the header its flow draws, which the pin draws again."""

key: FragmentKey
header: Divider


@dataclass(frozen=True)
class StackedHeaders:
"""The burst's headers a pin stacks above the top row's own: a count line, then each
earlier message of the burst whose head the reader has scrolled past. `keys[i]` is the
message `headers[i]` opens; the count line opens the earliest one."""

headers: tuple[Divider, ...] = ()
keys: tuple[FragmentKey, ...] = ()


NO_STACK = StackedHeaders()


@dataclass(frozen=True)
class ArrivalBurst:
"""Messages that arrived together at the end a reader follows (Tristan, 2026-11-18: "show
the headers for all of them, like stacked, and then ... show the most recent one. So it'd
be like, three came in, here's the latest").

Arrivals whose publications come within `gap` seconds of each other are one burst; one
after the gap starts the next. The window shows the latest as it shows any arrival, and its
pin stacks the headers of the others the reader has scrolled past (`stack`). Nothing is
collapsed or copied: the pin draws the messages' own header blocks. The burst ends when
the reader scrolls up by hand or opens a stacked header (`PinsMessageHeader`)."""

messages: tuple[BurstMessage, ...] = ()
last: float = float("-inf")
gap: ClassVar[float] = 4.0
shown: ClassVar[int] = 3
"""The most earlier headers stacked; the count line says how many came."""

def live(self, now: float) -> bool:
return bool(self.messages) and now - self.last <= self.gap

def arrived(self, fragments: tuple[HistoryFragment, ...], now: float) -> ArrivalBurst:
"""`fragments` arrived at the followed end: each message among them with a header
joins this burst, or starts the next one after the gap."""
kept = self.messages if self.live(now) else ()
seen = {message.key.source for message in kept}
joined = []
for fragment in fragments:
if fragment.pinned_dividers and fragment.source_identity not in seen:
seen.add(fragment.source_identity)
joined.append(BurstMessage(fragment.key, fragment.pinned_dividers[-1]))
if not joined:
return self
return ArrivalBurst(kept + tuple(joined), now)

def stack(self, window: PinsMessageHeader, pinned: PinnedHeader) -> StackedHeaders:
"""The earlier messages whose head is scrolled above the top row, the most recent
`shown` of them, under a count line; none for a burst of one, or once the reader is
above the burst (no head is above the top row then). The top row's own message pins
its header as before and is not stacked twice."""
if len(self.messages) < 2 or not pinned.width:
return NO_STACK
own = pinned.headers[-1:]
above = [message for message in self.messages[:-1]
if message.header not in own
and (top := window.message_top(message.key)) is not None and top < window.scroll_y]
if not above:
return NO_STACK
stacked = above[-self.shown:]
count = Divider.titled(f"{len(self.messages)} new", MutedRole)
return StackedHeaders((count, *(message.header for message in stacked)),
(above[0].key, *(message.key for message in stacked)))


NO_BURST = ArrivalBurst()


class HeaderPin:
"""The overlay a history window floats over its top row: the header of the message the reader
is in, while that header is scrolled above, so the reader of a long message still sees who
sent it to whom, and when. It draws the message's own header block, as the flow does, and
keeps no copy of the message. A plain mixin, as `LatestJumpBar` is: Textual's widget
metaclass refuses an `ABC` base and Qt's shiboken metaclass clashes with one."""

def pin(self, pinned: PinnedHeader) -> None:
"""Draw the one header the window's top row needs, or none, in the column its message
draws it in, so it sits and wraps exactly as the flow's own header does."""
if pinned.headers:
self.draw_pinned(pinned.headers[-1], pinned.x, pinned.width)
self.show_pin(bool(pinned.headers))
sent it to whom, and when; above it, a burst's stacked headers (`ArrivalBurst`). It draws
the messages' own header blocks, as the flow does, and keeps no copy of a message. A plain
mixin, as `LatestJumpBar` is: Textual's widget metaclass refuses an `ABC` base and Qt's
shiboken metaclass clashes with one."""

stacked: StackedHeaders = NO_STACK

def pin(self, pinned: PinnedHeader, stacked: StackedHeaders = NO_STACK) -> None:
"""Draw the headers the window's top row needs, or none, in the column its message
draws them in, so each sits and wraps exactly as the flow's own header does."""
self.stacked = stacked
headers = stacked.headers + pinned.headers[-1:]
if headers:
self.draw_pinned(headers, pinned.x, pinned.width)
self.show_pin(bool(headers))

def opened_at(self, index: int) -> FragmentKey | None:
"""The message the pin's `index`th drawn header opens: a stacked one's, none for the
top row's own (the reader is already in that message)."""
keys = self.stacked.keys
return keys[index] if 0 <= index < len(keys) else None

@abstractmethod
def draw_pinned(self, header: Divider, x: int, width: int) -> None:
"""Draw `header` in the column at `x`, `width` wide, in the toolkit's unit."""
def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None:
"""Draw `headers`, top to bottom, in the column at `x`, `width` wide, in the toolkit's unit."""

@abstractmethod
def show_pin(self, shown: bool) -> None:
Expand All @@ -125,6 +217,10 @@ class PinsMessageHeader:
`top_page` and `live_message_header` answer."""

sticky_header: HeaderPin
arrival_burst: ArrivalBurst
_restoring: bool
pinned_scroll_y: float = 0.0
"""The offset the pin was last drawn at: a reader's own scroll up from it ends a burst."""

def top_message_header(self) -> PinnedHeader:
"""The header of the message drawn on the window's top row, when that header is scrolled
Expand All @@ -134,8 +230,33 @@ def top_message_header(self) -> PinnedHeader:
def repin_header(self) -> None:
"""Pin from where the reader is now. The window calls this on every scroll offset and
every committed geometry change: a reflow, a filter, replaced rows or a restored tab can
change the top row's message at an unchanged offset."""
self.sticky_header.pin(self.top_message_header())
change the top row's message at an unchanged offset. Only the reader scrolls a window up:
following, gliding and placing an arrival move it down or keep it (`layout_scroll`)."""
burst = self.arrival_burst
if burst.messages and self.scroll_y < self.pinned_scroll_y and not self._restoring:
burst = self.arrival_burst = NO_BURST
self.pinned_scroll_y = self.scroll_y
pinned = self.top_message_header()
self.sticky_header.pin(pinned, burst.stack(self, pinned) if burst.messages else NO_STACK)

def open_pinned(self, index: int) -> bool:
"""The reader chose the pin's `index`th header: a stacked one scrolls to its message,
whose head comes to the top row, and the burst ends. False for the top row's own."""
key = self.sticky_header.opened_at(index)
if key is None:
return False
top = self.message_top(key)
self.arrival_burst = NO_BURST
if top is not None:
self.release_anchor()
self.scroll_y = top
self.repin_header()
return True

@abstractmethod
def message_top(self, key: FragmentKey) -> float | None:
"""The offset that puts the drawn message `key`'s first row on the window's top row, in
the window's unit; None when no drawn row holds it."""


class NoHistoryChange:
Expand Down
12 changes: 12 additions & 0 deletions src/toad/client/history_pager.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from agent_comms.messaging.message_reference import MessageReference
from toad.client.fragments import FragmentKey, HistoryFragment
from toad.client.history_changes import NO_BURST, ArrivalBurst
from toad.client.history_preparation import (
NEWER_END,
OLDER_END,
Expand Down Expand Up @@ -172,6 +173,15 @@ class PagingWindow(ReaderWindow):
histories: set
scroll_target_y: float
max_scroll_y: float
arrival_burst: ArrivalBurst = NO_BURST
"""The messages that last arrived together at the end the reader follows."""

def arrivals_followed(self, arrivals: tuple[HistoryFragment, ...]) -> None:
"""`arrivals` were published at the followed end: they join the burst while the reader
follows it, or while the burst is still arriving (Textual stops following where it
shows a tall arrival from its head)."""
if arrivals and (self.follows_tail or self.arrival_burst.live(monotonic())):
self.arrival_burst = self.arrival_burst.arrived(arrivals, monotonic())
lookahead: DirectionalPreparation
presentation_budget: PresentationBudget
configuration_state: object
Expand Down Expand Up @@ -808,6 +818,7 @@ def current() -> bool:
arrivals = self._source_state.arriving(staged, followed_end)
await self._extend_and_trim(edge, end, local, protected, staged, current=current)
self._require_can_draw()
self.window.arrivals_followed(arrivals)
self.hold_arrival(arrivals)
self.repaint(arrivals)
self.rows_published()
Expand Down Expand Up @@ -1205,6 +1216,7 @@ async def show_newest(self, request: ReplacementViewportRequest, *,
self._generation += 1
published = await self.jump_latest(request, publication_current)
if published:
self.window.arrivals_followed(arrivals)
self.repaint(arrivals, continuing=retained)
return published

Expand Down
45 changes: 35 additions & 10 deletions src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,26 +729,29 @@ class QtStickyHeader(HeaderPin, QWidget):
"""`HeaderPin` floated over the history's top edge, drawn by the history rows' own
delegate. A child of the window, not the viewport, as `QtJumpBar` is: the viewport's
children scroll with its contents, and QScroller's grab on the viewport would take its
taps. Opaque, so the row it covers does not show through, as Textual's overlay is."""
taps. Opaque, so the row it covers does not show through, as Textual's overlay is. Taps
pass through to the row beneath, except on a burst's stacked headers, which open their
messages."""

def __init__(self, window: QtHistoryWindow) -> None:
super().__init__(window)
self.history_window = window
self.document: QTextDocument | None = None
self.documents: tuple[QTextDocument, ...] = ()
self.drawn: tuple = ()
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.hide()

def draw_pinned(self, header: Divider, x: int, width: int) -> None:
"""Every scroll offset pins; only a different header, column, font or link context
lays the header out again."""
def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None:
"""Every scroll offset pins; only different headers, column, font or link context lay
them out again."""
window = self.history_window
drawn = (header, x, width, window.font().key(), window.rows.links_revision)
drawn = (headers, x, width, window.font().key(), window.rows.links_revision)
if drawn == self.drawn:
return
self.drawn = drawn
self.document = window.rows.header_document(header, window.font(), width)
self.resize(width, int(self.document.size().height()))
self.documents = tuple(window.rows.header_document(header, window.font(), width) for header in headers)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, not self.stacked.keys)
self.resize(width, sum(int(document.size().height()) for document in self.documents))
self.move(window.viewport().mapTo(window, QPoint(x, 0)))
self.raise_()
self.update()
Expand All @@ -757,14 +760,28 @@ def show_pin(self, shown: bool) -> None:
if self.isVisible() != shown:
self.setVisible(shown)

def mouseReleaseEvent(self, event) -> None: # type: ignore[override]
"""A tap on a stacked header opens its message; the top row's own passes through."""
y, top = event.position().y(), 0
for index, document in enumerate(self.documents):
top += int(document.size().height())
if y < top:
if self.history_window.open_pinned(index):
event.accept()
return
break
event.ignore()

def paintEvent(self, event) -> None: # type: ignore[override]
if self.document is None:
if not self.documents:
return
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(BackgroundColour.rgb(self.history_window.rows.renderer.scheme).hex))
context = QAbstractTextDocumentLayout.PaintContext()
context.palette = self.palette()
self.document.documentLayout().draw(painter, context)
for document in self.documents:
document.documentLayout().draw(painter, context)
painter.translate(0, document.size().height())
painter.end()


Expand Down Expand Up @@ -1422,6 +1439,14 @@ def live_message_header(self) -> PinnedHeader:
"""Qt draws no live blocks: the draft is rows, so a row under the top edge pins."""
return PinnedHeader((), 0, 0)

def message_top(self, key) -> float | None:
"""Qt keeps rows by pixel: the row's top under the viewport, plus the offset."""
model_rows = self.model_rows
row = model_rows.row_of(key)
if row < 0:
return None
return self.scroll_y + self.visualRect(model_rows.index(row, 0)).top()

def placements(self, bodies) -> Iterator[tuple[object, int]]:
return iter(())

Expand Down
8 changes: 7 additions & 1 deletion src/toad/widgets/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@
from toad.widgets.goal_bar import GoalBar
from toad.widgets.history_anchor import HistoryWindow
from toad.client.history_changes import PinsMessageHeader
from toad.client.fragments import FragmentKey
from toad.client.reader_position import FragmentPosition
from toad.widgets.input_delivery import InputDeliveryBar, InputDeliveryDetails
from toad.widgets.markdown_note import MarkdownNote, StopReasonNote
from toad.widgets.menu import Menu
Expand Down Expand Up @@ -488,7 +490,7 @@ class Window(
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.jump_bar = JumpBar(BackToBottom(JumpBar.label))
self.sticky_header = StickyHeader()
self.sticky_header = StickyHeader(self)

def apply_native_layout(self) -> None:
super().apply_native_layout()
Expand All @@ -502,6 +504,10 @@ def watch_scroll_y(self, old_value: float, new_value: float) -> None:
super().watch_scroll_y(old_value, new_value)
self.repin_header()

def message_top(self, key: FragmentKey) -> float | None:
location = FragmentPosition(key, 0.0, 1, block=0).page(self)
return location.destination(self, 0.0) if location.laid_out(self) else None

def prepare_viewport(self) -> None:
"""Committed geometry can change the top row's message at an unchanged offset
(a reflow, a filter, replaced pages, a restored tab); pin from that scene too."""
Expand Down
Loading
Loading