From ccb1469c02e480706ca9d15186bfa7f68aa7536b Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 13:34:28 -0500 Subject: [PATCH 01/16] qt sidebar and tabs: an observation redraws only what changed Qt's Sidebar.present redrew every channel and thread line on each bare present, which `present_sidebar` makes on every sidebar observation; the rows' changes already reach `sync` as partial ChangedChannels/ChangedThreads. On Tristan's phone during a burst of arrivals that redraw was 17% of the UI thread. A bare present now runs the shared state transition and keeps the status line current in place, as Textual's sidebar does; `sync` applies every change the state machine hands it: a partial one that keeps the channel order touches its rows, every other one (all rows, a channel added, removed or moved) draws the tree again in place. The search filter asks for all rows, as Textual's search follower re-syncs every group. The tab bar removed and re-added every tab on each paint_tabs, which the sidebar asked for on each observation (8.6% of the phone's UI thread). It now changes nothing when the tabs are the same, retitles only a changed title when the tabs and their order are the same (Textual's tab strip reconciles its labels so), and re-marks the selected tab only when the tabs or the selection changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/qt/name_wave.py | 20 ++++++++-- src/toad/qt/window.py | 79 +++++++++++++++++++++------------------- 2 files changed, 58 insertions(+), 41 deletions(-) diff --git a/src/toad/qt/name_wave.py b/src/toad/qt/name_wave.py index 79801b124..12c2dff77 100644 --- a/src/toad/qt/name_wave.py +++ b/src/toad/qt/name_wave.py @@ -152,10 +152,21 @@ def __init__(self, clock, accent: QColor, ink: QColor) -> None: self.waves: dict[str, QtTabWave] = {} self.growing: dict[str, TabGrowth] = {} - def show_tabs(self, entries: list[tuple[str, str]]) -> None: - """Draw ``entries`` (title, mode) as the bar's tabs. Compared with what the bar showed: - a mode that is new grows in, a mode that is gone leaves a shrinking picture of itself. - The first drawing, a restore, appears at once.""" + def show_tabs(self, entries: list[tuple[str, str]]) -> bool: + """Draw ``entries`` (title, mode) as the bar's tabs; whether anything changed. The same + tabs in the same order only retitle the ones whose title changed, as Textual's tab + strip reconciles its labels: rebuilding every tab relaid and repainted the bar on each + sidebar observation (Tristan's phone, a burst of arrivals, 2026-11-18). Otherwise, + compared with what the bar showed: a mode that is new grows in, a mode that is gone + leaves a shrinking picture of itself. The first drawing, a restore, appears at once.""" + current = [(self.tabText(index), self.tabData(index)) for index in range(self.count())] + if current == entries: + return False + if [mode for _, mode in current] == [mode for _, mode in entries]: + for index, (title, _) in enumerate(entries): + if current[index][0] != title: + self.setTabText(index, title) + return True shown = {self.tabData(index): self.tabRect(index) for index in range(self.count())} modes = {mode for _, mode in entries} moving = bool(shown) and self.clock.enabled and self.isVisible() @@ -171,6 +182,7 @@ def show_tabs(self, entries: list[tuple[str, str]]) -> None: self.growing[mode] = TabGrowth(self, mode) for rect, picture in leaving: TabGhost(self, rect, picture) + return True def relayout(self) -> None: """Lay the tabs out again with the growing tabs' current widths.""" diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index b8c331e05..bbac7849d 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -100,7 +100,7 @@ from toad.client.referenced_core import ReferencedCore from toad.client.session_scope import NoSessionOrigin, SessionOrigin, SessionScope from toad.client.subscribers import SidebarSubscriber -from toad.sidebar_changes import SidebarChange +from toad.sidebar_changes import AllSidebarRows, SidebarChange from toad.sidebar_contracts import ( ChannelGroupRows, FindsOpenViews, @@ -997,11 +997,9 @@ def app(self) -> QtToadApp: return self.window def _on_filter_changed(self, _value: str) -> None: - """Re-present the whole tree so rows whose names newly stop (or newly start) - matching the filter appear / disappear. `present` is already the one wholesale - redraw, so routing the refresh through it keeps the filter path identical to - every other model-change path.""" - self.present() + """Every row may newly match or stop matching: all rows, as Textual's search + follower re-syncs every group.""" + self.present(change=AllSidebarRows(), reorder=True) def accepts_observation(self) -> bool: """The sidebar always shows while it exists: the window hides it through @@ -1019,41 +1017,43 @@ def hide_status(self) -> None: self._status_text = None def present(self, **changes: object) -> None: - """Run the state transitions, then paint status + rows + welcome. A targeted - `ChangedChannels` / `ChangedThreads` dispatched into `sync` touches only the - affected channel header + its member rows; broader state changes fall through - to the wholesale redraw that rebuilds the whole tree.""" - change = changes.get("change") + """Run the shared state transition, whose model change reaches `sync`, then keep the + status line current in place. A bare present (each observation, a show) draws no rows: + rows change only through the change the state machine hands `sync`, as Textual's + sidebar draws them. Redrawing every channel and thread here on each observation was + 17% of the phone's UI thread during a burst of arrivals (2026-11-18).""" super().present(**changes) + self._refresh_status_only() model = self.model_state.shown if self.model_state.shows_model() else None - if model is not None and change is not None and change.partial_update: - # The `sync` dispatch handled the typed partial update. Keep the status row - # fresh in place without rebuilding the rest of the tree. - self._refresh_status_only() - else: - def draw(top: KeptLines) -> None: - if self._status_text is not None: - top.keep(StatusSection(self._status_text)) - if model is not None: - self.draw_lines(model, top) - self.redraw(draw) - # A wholesale redraw rebuilt the channel items; rebind the per-channel groups - # against the new items so the next targeted `sync` operates on live children. - if model is not None: - self._rebind_groups_from_tree(model) - else: + if model is None: + if self.groups: self.groups = {} - if model is not None: - self.window.channel_sort.update_order(model.observation.channel_order()) - self.window.paint_tabs() + self.redraw(lambda top: None) + self._refresh_status_only() + return + self.window.channel_sort.update_order(model.observation.channel_order()) + self.window.paint_tabs() def sync(self, *, change: SidebarChange, reorder: bool = False) -> None: - """Dispatch a typed row change through `GroupedSidebar.apply_comms` so only the - affected header + member rows touch Qt. Wholesale changes (partial_update=False) - are left to the caller's follow-up `present()` to rebuild the tree.""" - if not self.model_state.shows_model() or not change.partial_update: + """Apply the change the shared state machine handed over. A partial one that keeps + the channels' order touches only its header and member rows (`apply_comms`); every + other one (all rows, a channel added, removed or moved) draws the tree again in + place, keeping each still-wanted line's item.""" + if not self.model_state.shows_model(): + return + model = self.model_state.shown + if change.partial_update and not reorder: + change.apply_comms(self, model.channels.rows) return - change.apply_comms(self, self.model_state.shown.channels.rows) + + def draw(top: KeptLines) -> None: + if self._status_text is not None: + top.keep(StatusSection(self._status_text)) + self.draw_lines(model, top) + self.redraw(draw) + # The redraw rebuilt the channel items; the groups bind to the new ones so the next + # partial change operates on live children. + self._rebind_groups_from_tree(model) def model_replaced(self) -> None: """Clear rows before the new observation's redraw lands; the next `present` will @@ -1773,13 +1773,18 @@ def follow_display(self, *_changed) -> None: screen.refreshRateChanged.connect(self.follow_display) def paint_tabs(self) -> None: + """The tabs as the navigation has them: a tab's title, unread count and busy wave. + Nothing is drawn or marked again when neither the tabs nor the selected one changed.""" self.tabs.blockSignals(True) badge = self.settings.sidebar.unread_counts.badge tabs = tuple(self.session_navigation.tabs) - self.tabs.show_tabs([(tab.label() + tab.unread_suffix(badge), tab.mode_name) for tab in tabs]) + changed = self.tabs.show_tabs([(tab.label() + tab.unread_suffix(badge), tab.mode_name) for tab in tabs]) self.tabs.follow_tabs(tabs) self.tabs.blockSignals(False) - self.mark_current() + modes = self.session_navigation.tab_modes + selected = modes.index(self.selected_mode) if self.selected_mode in modes else -1 + if changed or self.tabs.currentIndex() != selected: + self.mark_current() def mark_current(self) -> None: modes = self.session_navigation.tab_modes From 415b0dc878bc507edc60d3634ceceed2b7ac122f Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 13:37:45 -0500 Subject: [PATCH 02/16] burst stack: a burst ends when the reader leaves the end, not when the offset falls The arrival drive's burst check found "the burst holds 0 messages of 5 posted" at phone speed: the burst grew to 8 messages while the window followed, then emptied with the window still following. Rows above that shrink (a receipt, the queue rows closing) make Qt clamp the scroll offset up outside `layout_scroll`, and `repin_header` ended the burst on any upward offset. A reader's own scroll up releases the anchor, so the burst now ends only once the window no longer follows the end. Shared: both frontends' windows pin through `PinsMessageHeader`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/client/history_changes.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index a379707a5..ad6bbcbe6 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -233,9 +233,13 @@ 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. Only the reader scrolls a window up: - following, gliding and placing an arrival move it down or keep it (`layout_scroll`).""" + following, gliding and placing an arrival move it down or keep it (`layout_scroll`). + The burst ends when the reader leaves the end, not when the window's offset falls: rows + above that shrink (a receipt, the queue rows closing) clamp the offset up while the reader + still follows, and ending the burst there emptied it before it could stack.""" burst = self.arrival_burst - if burst.messages and self.scroll_y < self.pinned_scroll_y and not self._restoring: + if (burst.messages and not self.follows_tail 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() From fdeb5b5361c930e0a8560b9dca2e013c116f1b82 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 13:41:53 -0500 Subject: [PATCH 03/16] qt history: a rising row fades as one picture, not its rich text drawn again each frame A burst's arrivals fade in row after row (`ArrivalFade`), and each frame of the fade drew every rising row's rich text again: its document's layout and every glyph, at the frame's opacity. Their look does not change while they rise, so the delegate draws a rising row once into a picture (by width, height, pixel ratio and document) and paints that at each frame's opacity; the picture goes when the row has risen or its fade lands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/qt/history.py | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index abbe1330d..56f8b5c74 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -28,7 +28,7 @@ from agent_comms.messaging.messages import ConversationRole, Membership, NoticeRole from metaclass_registry.mro_dispatch import handles from PySide6.QtCore import QAbstractListModel, QEvent, QModelIndex, QPoint, QPointF, QRect, Qt, QTimer, QUrl, Signal -from PySide6.QtGui import QAbstractTextDocumentLayout, QColor, QDesktopServices, QFont, QFontMetrics, QPainter, QTextDocument +from PySide6.QtGui import QAbstractTextDocumentLayout, QColor, QDesktopServices, QFont, QFontMetrics, QPainter, QPixmap, QTextDocument from PySide6.QtWidgets import QApplication, QPushButton, QScroller, QStyleOptionViewItem, QWidget from pyqt_reactive.widgets.virtual_rows import HtmlRow, PlainRow, RowDocumentDelegate, RowFormatting, VirtualRowView from toad.client.pending import AwaitsFirstPage @@ -325,6 +325,8 @@ def __init__(self, renderer: QtLineRenderer) -> None: """Replaced, never mutated, when the link context settles or the app's renderer restyles: a preparation already on the pool keeps the binding it was handed.""" self.links_revision = 0 + # A rising row's picture while it fades in, by fragment key: (look, pixmap). + self.fading: dict = {} def link(self, links: LinkContext) -> None: """Rows draw with these names from now on; rows prepared before are stale.""" @@ -444,14 +446,37 @@ def paint(self, painter, option, index) -> None: # type: ignore[override] fragment = index.data(HistoryRows.FRAGMENT) opacity = self.view.arrival_opacity(fragment.key) if self.view.arrivals else None if opacity is None: + self.fading.pop(fragment.key, None) super().paint(painter, option, index) else: painter.save() painter.setOpacity(opacity) - super().paint(painter, option, index) + painter.drawPixmap(option.rect.topLeft(), self.fading_picture(painter, option, index, fragment.key)) painter.restore() self.view.row_painted(fragment, option.rect) + def fading_picture(self, painter: QPainter, option, index, key) -> QPixmap: + """A rising row drawn once into a picture, which each frame of its fade paints at that + frame's opacity: its look does not change while it rises, and laying its rich text out + and drawing every glyph again each frame was most of a burst's repaint on the phone + (2026-11-18). A new width, height, pixel ratio or document draws it again.""" + ratio = painter.device().devicePixelRatioF() + rect = option.rect + local = QStyleOptionViewItem(option) + local.rect = QRect(0, 0, rect.width(), rect.height()) + look = (rect.width(), rect.height(), ratio, id(self.painted_document(index, local))) + kept = self.fading.get(key) + if kept is not None and kept[0] == look: + return kept[1] + picture = QPixmap(max(1, round(rect.width() * ratio)), max(1, round(rect.height() * ratio))) + picture.setDevicePixelRatio(ratio) + picture.fill(Qt.GlobalColor.transparent) + drawing = QPainter(picture) + super().paint(drawing, local, index) + drawing.end() + self.fading[key] = (look, picture) + return picture + @dataclass(frozen=True) class PreparedOnFill(RowFormatting): @@ -1021,6 +1046,8 @@ def gliding_to_end(self) -> bool: def arrival_landed(self, fade: ArrivalFade) -> None: if fade in self.arrivals: self.arrivals.remove(fade) + for key in fade.positions: + self.rows.fading.pop(key, None) def arrival_opacity(self, key) -> float | None: """How far the row `key` has risen, while it is still rising.""" From cc9ba18b8be781b1ea9adb2d88b93902a71fe763 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 13:51:06 -0500 Subject: [PATCH 04/16] qt pin: a burst's stacked headers keep their layout as the stack shifts The pin laid out every header it draws again whenever the drawn set changed, and a burst's stack changes as each head glides past the top: each header's html built anew, its theme's colours resolved span by span. A phone-speed profile of a burst put that at a third of the UI thread (repin_header 31.9%, header_document 16.2%). The pin now keeps each header's document while its width, font, link context and renderer stay the same, and lays out only headers it has not. The renderer is part of that context, so a theme change lays the pin out again; before, an unchanged header set kept the old theme's document. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/qt/history.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 56f8b5c74..80a189945 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -803,18 +803,30 @@ def __init__(self, window: QtHistoryWindow) -> None: self.history_window = window self.documents: tuple[QTextDocument, ...] = () self.drawn: tuple = () + # Each pinned header's laid-out document, while the pin's width, font, link context and + # renderer stay the same. + self.laid_out: dict[Divider, QTextDocument] = {} + self.layout_context: tuple = () self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) self.hide() 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.""" + """Every scroll offset pins; only different headers, column, font, link context or + renderer (a theme) lay anything out again, and then only the headers not already laid + out: a burst's stack changes as each head glides past the top, and laying every stacked + header out again from its html (its theme's colours resolved span by span) was a third + of the phone's UI thread during a burst (2026-11-18).""" window = self.history_window - drawn = (headers, x, width, window.font().key(), window.rows.links_revision) + context = (width, window.font().key(), window.rows.links_revision, id(window.rows.renderer)) + drawn = (headers, x, context) if drawn == self.drawn: return self.drawn = drawn - self.documents = tuple(window.rows.header_document(header, window.font(), width) for header in headers) + kept = self.laid_out if context == self.layout_context else {} + self.layout_context = context + self.laid_out = {header: kept.get(header) or window.rows.header_document(header, window.font(), width) + for header in headers} + self.documents = tuple(self.laid_out[header] 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))) From 263874d9991c7928404adf08c44199ed8b456991 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:04:25 -0500 Subject: [PATCH 05/16] history rows: an arrival is an insert, not a reset; the composer reads its preview setting once per change The two largest per-frame costs left during a burst on the phone (busy main-thread time): every arrival reset the history model, so the view measured every row again (rows_changed / _update_viewport / sizeHint, ~23%), and each queue sync resolved the delivery-preview setting through the settings scope several times (~8%). HistoryRows.show now tells the view what changed. Rows of pages that did not change are the same fragment objects, so the unchanged rows before and after the change are found by identity, and only the rows between them are inserted, removed or changed (the changed rows keep their old content through the insert or removal and change in place after, as Qt's model contract requires; QAbstractItemModelTester in Fatal mode passes append, prepend, replaced live tail, arrivals before the draft, removal, mixed and full changes). With pyqt-reactive's kept row sizes (OpenHCSDev/PyQT-reactive#68) every unchanged row keeps its measured height. The row-key index is rebuilt only from the first changed row. show_pages and rows_changed lay out once and leave none pending (a model insert schedules Qt's own layout, which a direct doItemsLayout left to run a second time). PromptComposer keeps the delivery-preview setting as last read, until its change effect (apply_delivery_preview) drops it. Interpreter timings, offscreen: an append through HistoryRows into VirtualRowView, 1500 rows: 29-30 ms with the installed pyqt-reactive, 4.3-4.4 ms with #68 (main's reset path: 43.8 ms at 1000 rows). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/client/prompt_composer.py | 14 +++++-- src/toad/qt/history.py | 65 +++++++++++++++++++++++++----- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/src/toad/client/prompt_composer.py b/src/toad/client/prompt_composer.py index d24a79a15..c52a82580 100644 --- a/src/toad/client/prompt_composer.py +++ b/src/toad/client/prompt_composer.py @@ -36,8 +36,9 @@ def apply_input_text(self) -> None: @EachOpenWidget def apply_delivery_preview(self) -> None: - """The delivery preview was turned on or off: the prompt shows its queue rows, or - drops them for the held count, at once.""" + """The delivery preview was turned on or off: the prompt reads it again and shows its + queue rows, or drops them for the held count, at once.""" + self.kept_delivery_preview = None self.sync_queue() @@ -45,6 +46,11 @@ class PromptComposer(metaclass=AbstractHooksMeta): """A conversation's composer: its submission owner, queue and leading glyph.""" submissions: object | None + kept_delivery_preview: bool | None = None + """The delivery-preview setting as this prompt last read it, until it changes + (`PromptSettingEffects.apply_delivery_preview`): a queue sync reads it several times, and + each read resolved it through the settings scope again (~8% of the phone's main thread + during a burst of arrivals, 2026-11-18).""" queue_summary_lines: ClassVar[int] = 3 """The queue summary's most lines; a longer one is cut there, so its wrapping never pushes the history further.""" @@ -90,7 +96,9 @@ def offers_send_now(self) -> bool: def shows_delivery_preview(self) -> bool: """The `ui.input.delivery_preview` setting: the queue rows above the prompt, or only the held count in the info bar.""" - return self.settings.ui.input.delivery_preview + if self.kept_delivery_preview is None: + self.kept_delivery_preview = bool(self.settings.ui.input.delivery_preview) + return self.kept_delivery_preview @property def shows_delivery_controls(self) -> bool: diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 80a189945..21ce6d0be 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -208,16 +208,55 @@ def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole): # return None if answer is None else answer(self.fragments[index.row()]) def show(self, fragments: tuple[HistoryFragment, ...]) -> None: - self.beginResetModel() + """The rows the pages show now, told to the view as what changed: the rows of pages + that did not change are the same fragment objects, so the unchanged rows before and + after the change are found by identity, and only the rows between them are inserted, + removed or changed. The view keeps every other row's measured height + (`RowDocumentDelegate` row sizes); a reset made it measure the whole history again + on every arrival (Tristan, Pixel 8a, bursts at 30 ms a frame, 2026-11-18).""" + old = self.fragments + same = min(len(old), len(fragments)) + head = next((row for row in range(same) if old[row] is not fragments[row]), same) + tail = 0 + while tail < same - head and old[-1 - tail] is fragments[-1 - tail]: + tail += 1 + removed, added = len(old) - head - tail, len(fragments) - head - tail + if removed == added: + self._set(fragments, head) + if added: + self.dataChanged.emit(self.index(head, 0), self.index(head + added - 1, 0)) + return + # The first `changed` rows of the change keep their old content through the removal + # and the insertion (rows an insert or removal does not name must not change in it), + # then change in place, told as a data change. + changed = min(removed, added) + kept, end = old[:head + changed], old[len(old) - tail:] + if removed > changed: + self.beginRemoveRows(QModelIndex(), head + changed, head + removed - 1) + self._set(kept + end, head + changed) + self.endRemoveRows() + if added > changed: + self.beginInsertRows(QModelIndex(), head + changed, head + added - 1) + self._set(kept + fragments[head + changed:head + added] + end, head + changed) + self.endInsertRows() + self._set(fragments, head) + if changed: + self.dataChanged.emit(self.index(head, 0), self.index(head + changed - 1, 0)) + + def _set(self, fragments: tuple[HistoryFragment, ...], first: int) -> None: + """Hold these rows. Every row a key names is kept with the rows (a lookup is asked per + changed row on each receipt update, arrival, glide and reader restore); rows before + `first` did not move, so a change at the end indexes only the rows after it.""" + if fragments is self.fragments: + return + rows = self._rows if first else {} + if first: + for key in [key for key, row in rows.items() if row >= first]: + del rows[key] + for row in range(first, len(fragments)): + rows.setdefault(fragments[row].key, row) self.fragments = fragments - # Every row a key names, built with the rows: a lookup is asked per changed row on - # each receipt update, arrival, glide and reader restore, and a scan compared every - # row's key each time. - rows: dict = {} - for row, fragment in enumerate(fragments): - rows.setdefault(fragment.key, row) self._rows = rows - self.endResetModel() def row_of(self, key) -> int: return self._rows.get(key, -1) @@ -1366,9 +1405,15 @@ def show_pages(self) -> None: self.model_rows.show(tuple(fragment for page in history.pages if page.display for fragment in page.shown_fragments) + self.draft + tuple(block.fragment() for block in self.live_blocks)) - self.doItemsLayout() + self.lay_out_now() self.repin_header() + def lay_out_now(self) -> None: + """One layout now, and none left pending: a model insert or removal schedules Qt's own, + which a direct `doItemsLayout` would leave to run a second time on the next turn.""" + self.scheduleDelayedItemsLayout() + self.executeDelayedItemsLayout() + def show_draft(self, fragments: tuple[HistoryFragment, ...]) -> None: """Core's CLI draft as rows after the history (none clears it); the reader keeps their place.""" if not fragments and not self.draft: @@ -1409,7 +1454,7 @@ def rows_changed(self) -> None: reader-restore and the viewport update — there is no viewer to serve.""" try: key, offset = self.reader_place() - self.doItemsLayout() + self.lay_out_now() self.keep_reader(key, offset) self.repin_header() self.viewport().update() From a318ef940f5422e93546db6a5c67fdefefba9368 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:05:44 -0500 Subject: [PATCH 06/16] qt tabs: marking the selected tab presents the panes on every paint again The batch gate's hold and menu_parity drives found the comms sidebar placed as a 24 px band at the bottom with the tab strip, where main places it at the left beside the conversation, so no sidebar row was on screen to press. paint_tabs had stopped calling mark_current when neither the tabs nor the selection changed, and mark_current is what presents the panes (`show_current_tab` -> `present_panes` -> each side bar's present and the chrome's arrange): the side bars stayed presented as before the drive's resize to phone width. paint_tabs marks the selected tab every time again, as on main; the bar itself still redraws only what changed. Checked with an offscreen interpreter run at 412x915 on main and this branch: the same 108 conversation rows, 12 inside the tree's viewport with no tab open, the same layout after #comms opens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/qt/window.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index bbac7849d..e060bd45d 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -1773,18 +1773,17 @@ def follow_display(self, *_changed) -> None: screen.refreshRateChanged.connect(self.follow_display) def paint_tabs(self) -> None: - """The tabs as the navigation has them: a tab's title, unread count and busy wave. - Nothing is drawn or marked again when neither the tabs nor the selected one changed.""" + """The tabs as the navigation has them: a tab's title, unread count and busy wave; the + bar redraws only what changed (`show_tabs`). The selected tab is marked every time, as + before: marking it presents the panes, and a pane state change that asks for nothing + else (the sidebar leaving the whole window as the first tab opens) is presented there.""" self.tabs.blockSignals(True) badge = self.settings.sidebar.unread_counts.badge tabs = tuple(self.session_navigation.tabs) - changed = self.tabs.show_tabs([(tab.label() + tab.unread_suffix(badge), tab.mode_name) for tab in tabs]) + self.tabs.show_tabs([(tab.label() + tab.unread_suffix(badge), tab.mode_name) for tab in tabs]) self.tabs.follow_tabs(tabs) self.tabs.blockSignals(False) - modes = self.session_navigation.tab_modes - selected = modes.index(self.selected_mode) if self.selected_mode in modes else -1 - if changed or self.tabs.currentIndex() != selected: - self.mark_current() + self.mark_current() def mark_current(self) -> None: modes = self.session_navigation.tab_modes From e909e4e11d5e15a436f9ea313b24bbbec60c069b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:07:58 +0000 Subject: [PATCH 07/16] toad serve: add --public-url for tailnet-served browser workspaces The systemd unit bypassed ToadWebServer entirely with a raw python -c one-liner calling the unprotected base Server class. --tailnet-port never existed; the stale part was the unit's command. Add TailnetWebServer(Server) in web_server.py: same version check, no cookie gate (the tailnet's ACL is the access control), public_url passed through for correct WebSocket URL generation behind tailscale serve. The unit now uses `toad serve --public-url URL --port 8040 acp agent-comms-acp` instead of importing textual_serve directly. Co-Authored-By: Claude Opus 5.5 --- docs/browser-serving.md | 13 +++++++------ src/toad/cli.py | 22 ++++++++++++++++++---- src/toad/web_server.py | 30 ++++++++++++++++++++++++++++-- tools/systemd/toad-serve.service | 2 +- 4 files changed, 54 insertions(+), 13 deletions(-) diff --git a/docs/browser-serving.md b/docs/browser-serving.md index 59890f09e..aefeacddc 100644 --- a/docs/browser-serving.md +++ b/docs/browser-serving.md @@ -39,12 +39,13 @@ Host and an external bind fail closed. The server API is pinned to ## Desktop tailnet service -The desktop user service is `tools/systemd/toad-serve.service`. It starts the -existing `textual-serve` package using the Python under -`~/.local/share/agent-comms/current`, not a copied runtime. Each browser tab runs -`/home/ts/bin/toad-comms`, which selects the installed Toad through its normal -launcher. Restart the service after a runtime switch to move the server process -as well as newly opened Toad children onto the new runtime. +The desktop user service is `tools/systemd/toad-serve.service`. It runs +`toad serve --public-url` with the tailscale HTTPS endpoint, so textual-serve +generates the right WebSocket URLs and the local cookie gate is skipped (the +tailnet's ACL is the access control). Each browser tab runs `toad acp +agent-comms-acp` as its own process. Restart the service after a runtime switch +to move the server process as well as newly opened Toad children onto the new +runtime. Install the unit under `~/.config/systemd/user/toad-serve.service`, then run: diff --git a/src/toad/cli.py b/src/toad/cli.py index 18d0184c1..da3efb1a3 100644 --- a/src/toad/cli.py +++ b/src/toad/cli.py @@ -21,7 +21,7 @@ from toad.client.local_connection import select_connection from toad.launch_binding import AgentAttached, AgentBinding, LaunchAgentRefused from toad.preferences import SavedSettings -from toad.web_server import ToadWebServer +from toad.web_server import TailnetWebServer, ToadWebServer def persist_terminal_failure(error: Exception) -> None: @@ -245,17 +245,31 @@ def replay(path: str) -> None: default="127.0.0.1", help="Loopback address to listen on (127.0.0.1 or localhost).", ) +@click.option( + "--public-url", + metavar="URL", + default=None, + help="Public HTTPS URL (e.g. from tailscale serve). Skips the local cookie gate.", +) @click.argument("toad_args", metavar="[TOAD ARGS]...", nargs=-1, type=click.UNPROCESSED) -def serve(port: int, host: str, toad_args: tuple[str, ...]) -> None: +def serve(port: int, host: str, public_url: str | None, toad_args: tuple[str, ...]) -> None: """Serve a Toad command line in a web browser. Each browser tab runs `toad TOAD ARGS` as its own process, for example `toad serve acp agent-comms-acp`. - """ + Behind tailscale serve, pass --public-url with the HTTPS endpoint so + textual-serve generates the right WebSocket URLs. Access control is the + tailnet's; the local cookie gate is skipped. + """ command = shlex.join([sys.executable, "-m", "toad", *toad_args]) - server = ToadWebServer(command, host=host, port=port, title="Toad") + if public_url is not None: + server: ToadWebServer | TailnetWebServer = TailnetWebServer( + command, host=host, port=port, public_url=public_url, title="Toad" + ) + else: + server = ToadWebServer(command, host=host, port=port, title="Toad") TerminalApplicationLifetime.set_process_title("toad serve") server.serve() diff --git a/src/toad/web_server.py b/src/toad/web_server.py index 942484a88..ea94c6123 100644 --- a/src/toad/web_server.py +++ b/src/toad/web_server.py @@ -135,6 +135,33 @@ def decode(self, request: web.Request) -> BrowserAccess: return RejectedBrowserAccess() +def check_textual_serve_version() -> None: + if version("textual-serve") != "1.1.3": + raise RuntimeError("Browser serving requires reviewed textual-serve 1.1.3") + + +class TailnetWebServer(Server): + """Loopback backend behind tailscale serve; tailnet ACL replaces the cookie gate.""" + + def __init__( + self, + command: str, + *, + host: str = "127.0.0.1", + port: int = 8000, + public_url: str, + title: str | None = None, + ) -> None: + check_textual_serve_version() + self._tailnet_url = public_url + super().__init__( + command, host=host, port=port, title=title, public_url=public_url + ) + + async def on_startup(self, app: web.Application) -> None: + self.console.print(f"Toad tailnet browser: {self._tailnet_url}") + + class ToadWebServer(Server): """Keep the vendor server/child path; check local access before every route.""" @@ -146,8 +173,7 @@ def __init__( port: int = 8000, title: str | None = None, ) -> None: - if version("textual-serve") != "1.1.3": - raise RuntimeError("Browser serving requires reviewed textual-serve 1.1.3") + check_textual_serve_version() endpoint = LocalBrowserEndpoint(host, port) super().__init__( command, host=host, port=port, title=title, public_url=endpoint.url diff --git a/tools/systemd/toad-serve.service b/tools/systemd/toad-serve.service index 78368e24e..a726cec0d 100644 --- a/tools/systemd/toad-serve.service +++ b/tools/systemd/toad-serve.service @@ -5,7 +5,7 @@ After=network.target [Service] Type=simple WorkingDirectory=/home/ts -ExecStart=/home/ts/.local/share/agent-comms/current/bin/python -c "from textual_serve.server import Server; Server('/home/ts/bin/toad-comms', host='127.0.0.1', port=8040, public_url='https://desktop.tail553874.ts.net:8443').serve()" +ExecStart=/home/ts/bin/toad serve --port 8040 --public-url https://desktop.tail553874.ts.net:8443 acp agent-comms-acp UnsetEnvironment=PYTHONPATH NO_COLOR TOAD_VALIDATION Environment=PYTHONUNBUFFERED=1 Restart=on-failure From 735f4c9eabeed4f2c7c19fb0a5344ace9bad400f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:19:34 +0000 Subject: [PATCH 08/16] fix: burst stack must not cover a visible header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ArrivalBurst.stack() fired when pinned.headers was empty — the top row's own header divider was at the viewport's top, still visible in the flow. The stack drew "N new" + the earlier message's header at viewport y=0, covering the visible header with an identically-labelled one from the burst. Two "Agent" headers at the same pixels in a DM. Guard: return NO_STACK when pinned.headers is empty. The header is visible; there is nothing to stack on top of. Co-Authored-By: Claude Opus 5.5 --- src/toad/client/history_changes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index a379707a5..f6a23e992 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -158,7 +158,7 @@ def stack(self, window: PinsMessageHeader, pinned: PinnedHeader) -> StackedHeade `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: + if len(self.messages) < 2 or not pinned.width or not pinned.headers: return NO_STACK own = pinned.headers[-1:] above = [message for message in self.messages[:-1] From e3c914f97377b67a639598505c1446c832a7b742 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:24:40 -0500 Subject: [PATCH 09/16] history rows: a status change and a link change tell the kept row heights A row's kept height (OpenHCSDev/PyQT-reactive#68) answers without asking the row's key again, so a key that changes in place must be told. `request_show` changes a fragment's look in place (show sees the same object): the model now emits dataChanged for those rows, which drops their kept heights only, so each is measured again in its new look. A link or style change gives every row a new key: the delegate forgets every kept height. Live and draft rows are new fragment objects on each change, which show's identity comparison already tells as changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/qt/history.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 21ce6d0be..5853e4bb8 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -261,6 +261,15 @@ def _set(self, fragments: tuple[HistoryFragment, ...], first: int) -> None: def row_of(self, key) -> int: return self._rows.get(key, -1) + def changed(self, fragments: tuple[HistoryFragment, ...]) -> None: + """These rows' fragments now show differently (`request_show` changes a fragment in + place, so `show` sees the same object): each is told to the view as a data change, + which drops its kept height, so it is measured again in its new look.""" + for fragment in fragments: + if (row := self.row_of(fragment.key)) >= 0: + index = self.index(row, 0) + self.dataChanged.emit(index, index) + class ArrivalFade(WidgetAnimation): """Rows that arrived together, rising as the TUI's `ARRIVAL` cascade raises them: each fades @@ -371,6 +380,8 @@ def link(self, links: LinkContext) -> None: """Rows draw with these names from now on; rows prepared before are stale.""" self.renderer = self.app_renderer.with_links(links) self.links_revision += 1 + # Every row's key names the links it was drawn with: none keeps its height. + self.forget_row_sizes() def restyle(self) -> None: """The app's renderer took a new scheme or diff marks: rows draw by it from now on, @@ -668,6 +679,7 @@ async def _show(self, changes: list[tuple[HistoryFragment, Shown]]) -> None: update cost the whole history's measurement while the new looks were not even ready.""" changed = tuple(fragment for fragment, shown in changes if fragment.request_show(shown)) if changed: + self.window.model_rows.changed(changed) self.repaint(continuing=changed) def repaint(self, fragments: tuple[HistoryFragment, ...] = (), *, continuing=()) -> None: From 6d0d42eb384e82b93c33a8a462b776ea50b5dc11 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:31:51 -0500 Subject: [PATCH 10/16] toad + qt: --open NAME opens a thread or #channel at launch; search lists the exact name first One launch owner for both frontends: `ClientLaunch.startup` (local_connection) reads the Core (`select_connection`) and the conversation (`LaunchOpening.startup`, removing `--open NAME` as the connection's own options are removed) from the terminal launch's and Qt's desktop launch's arguments. The shared start (`ApplicationLifetime.start`) opens it after the saved tabs come back, through `TargetOpen`, as a sidebar row and a link naming it do. Sidebar search: `SidebarFilter.matching` is the one listing both frontends draw: matches ranked exact, then prefix, then the rest, each in model order. Textual's `TargetTree` kept its own copy of the match rule (`search` + `matches`); it now lists through its sidebar's filter, as Qt's channels tree and thread panel do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/app.py | 4 +- src/toad/application_lifetime.py | 12 +++-- src/toad/cli.py | 25 +++++---- src/toad/client/application.py | 4 +- src/toad/client/local_connection.py | 16 ++++++ src/toad/client/sidebar_filter.py | 20 +++++++- src/toad/launch_opening.py | 60 ++++++++++++++++++++++ src/toad/qt/client_start.py | 23 ++++++--- src/toad/qt/main.py | 8 +-- src/toad/qt/thread_comms_panel.py | 5 +- src/toad/qt/window.py | 9 ++-- src/toad/widgets/sidebar_tree.py | 20 ++++---- tests/textual/test_open_and_search_rank.py | 46 +++++++++++++++++ 13 files changed, 207 insertions(+), 45 deletions(-) create mode 100644 src/toad/launch_opening.py create mode 100644 tests/textual/test_open_and_search_rank.py diff --git a/src/toad/app.py b/src/toad/app.py index 47339e85c..5eda86e0c 100644 --- a/src/toad/app.py +++ b/src/toad/app.py @@ -42,6 +42,7 @@ from toad.core import input_events from toad.widgets.file_viewer import ImageViewer from toad.launch_binding import AgentBinding +from toad.launch_opening import LaunchOpening, NoLaunchOpening from toad.native_style import TransparentBackground from toad.neovim_editing import HostsNeovim from formbridge.forms.declared_fields import DeclaredField @@ -136,6 +137,7 @@ def __init__( project_dir: Checkout, connection: CoreConnection, agent_session_id: AcpSessionId | NoAcpSessionId = NoAcpSessionId(), + opening: LaunchOpening = NoLaunchOpening(), ) -> None: """Toad app. @@ -148,7 +150,7 @@ def __init__( self.render_processes: Renderer = TextualPreparedRenderer(self.preparation) self.background_render_slots = asyncio.Semaphore(1) self._background_render_tasks: set[asyncio.Task[object]] = set() - self.initialize_client(agent_binding, connection, agent_session_id) + self.initialize_client(agent_binding, connection, agent_session_id, opening) self.clipboard_transport = Clipboard.for_platform() self.input_attention = TerminalAttention(self) self._mode_switch_lock = asyncio.Lock() diff --git a/src/toad/application_lifetime.py b/src/toad/application_lifetime.py index f78779b72..2042f8634 100644 --- a/src/toad/application_lifetime.py +++ b/src/toad/application_lifetime.py @@ -17,6 +17,7 @@ from toad.version import VersionMonitor from toad.client.tab_identity.kinds import MailboxTab from toad.client.tab_identity import TabNotDrawnHere, TabTargetGone +from toad.launch_opening import LaunchOpening, NoLaunchOpening if TYPE_CHECKING: from ssl import SSLContext @@ -132,10 +133,13 @@ def observe_next_start(cls, observer: Callable[[ApplicationLifetime], None]) -> """Install the sole one-shot observer for the next owned startup.""" ApplicationLifetime._startup_hook = ApplicationLifetime._startup_hook.install(observer) - def __init__(self, app: ClientApplication, resumed_session: AcpSessionId | NoAcpSessionId) -> None: + def __init__(self, app: ClientApplication, resumed_session: AcpSessionId | NoAcpSessionId, + opening: LaunchOpening = NoLaunchOpening()) -> None: self.app = app # The agent session the launch asked to resume, if it named one. self.resumed_session = resumed_session + # The conversation the launch asked to open (`--open`), if it named one. + self.opening = opening def begin(self) -> None: """Run start as its own task: it awaits drawn frames, so neither Mount @@ -146,6 +150,7 @@ def begin(self) -> None: async def start(self) -> None: ApplicationLifetime._startup_hook = ApplicationLifetime._startup_hook.notify(self) await self.restore_workspace() + await self.opening.open(self.app) self.started() self.prepare_view_settings() self.settle_heap() @@ -260,8 +265,9 @@ def set_process_title(title: str) -> None: setproctitle.setproctitle(title) - def __init__(self, app: ToadApp, resumed_session: AcpSessionId | NoAcpSessionId) -> None: - super().__init__(app, resumed_session) + def __init__(self, app: ToadApp, resumed_session: AcpSessionId | NoAcpSessionId, + opening: LaunchOpening = NoLaunchOpening()) -> None: + super().__init__(app, resumed_session, opening) self.quit_warning_deadline = 0.0 self.usage = UsageReports(app) self.version = VersionMonitor() diff --git a/src/toad/cli.py b/src/toad/cli.py index 18d0184c1..a5322a027 100644 --- a/src/toad/cli.py +++ b/src/toad/cli.py @@ -18,7 +18,7 @@ from toad.app import ToadApp from toad.application_lifetime import TerminalApplicationLifetime from toad.client.connection import CoreConnection -from toad.client.local_connection import select_connection +from toad.client.local_connection import ClientLaunch from toad.launch_binding import AgentAttached, AgentBinding, LaunchAgentRefused from toad.preferences import SavedSettings from toad.web_server import ToadWebServer @@ -67,8 +67,8 @@ def parse_args(self, ctx, args): if "--version" in args or "-v" in args: return super().parse_args(ctx, args) - # The launch's connection; apps receive this captured value. - ctx.obj = select_connection(args) + # The launch's connection and the conversation it opens; apps receive this captured value. + ctx.obj = ClientLaunch.startup(args) # Check if first arg is a known subcommand if not args or args[0] not in self.commands: # If not a subcommand, prepend the default command name @@ -119,18 +119,20 @@ def main(ctx, version): @click.argument("project_dir", metavar="PATH", required=True) @click.option("-a", "--agent", metavar="AGENT", default="") @click.pass_obj -def run(connection: CoreConnection, project_dir: str, agent: str = "1"): - """Run an installed agent.""" +def run(launch: ClientLaunch, project_dir: str, agent: str = "1"): + """Run an installed agent. `--open NAME` (a thread, or #channel) opens that conversation + once the saved tabs are back.""" project = FieldCodec.decode(Checkout, project_dir).resolved(strict=True) - binding = asyncio.run(get_agent_binding(connection, agent)) + binding = asyncio.run(get_agent_binding(launch.connection, agent)) app = ToadApp( agent_binding=binding, project_dir=project, - connection=connection, + connection=launch.connection, + opening=launch.opening, ) run_terminal(app) @@ -157,7 +159,7 @@ def run(connection: CoreConnection, project_dir: str, agent: str = "1"): @click.option("-d", "--project-dir", "project_option", metavar="PATH", default=None) @click.pass_obj def acp( - connection: CoreConnection, + launch: ClientLaunch, command: str, title: str | None, project_dir: str | None, @@ -191,8 +193,9 @@ def acp( app = ToadApp( agent_binding=AgentAttached(agent_data), project_dir=FieldCodec.decode(Checkout, project_dir).resolved(strict=True), - connection=connection, + connection=launch.connection, agent_session_id=session_id, + opening=launch.opening, ) run_terminal(app) @@ -262,11 +265,11 @@ def serve(port: int, host: str, toad_args: tuple[str, ...]) -> None: @main.command("about") @click.pass_obj -def show_about(connection: CoreConnection) -> None: +def show_about(launch: ClientLaunch) -> None: """Show about information.""" - print(about.render(connection.location)) + print(about.render(launch.connection.location)) if __name__ == "__main__": diff --git a/src/toad/client/application.py b/src/toad/client/application.py index 5a570dd46..9c0731ae1 100644 --- a/src/toad/client/application.py +++ b/src/toad/client/application.py @@ -48,6 +48,7 @@ from toad.core import events as core_events from toad.core import session_requests from toad.launch_binding import AgentBinding +from toad.launch_opening import LaunchOpening, NoLaunchOpening from toad.navigation_preparation import NavigationReader from toad.session_host import NavigationHost from toad.session_navigation import SessionNavigation @@ -200,6 +201,7 @@ def initialize_client( agent_binding: AgentBinding, connection: CoreConnection, agent_session_id: AcpSessionId | NoAcpSessionId = NoAcpSessionId(), + opening: LaunchOpening = NoLaunchOpening(), ) -> None: """The launch's client owners, built once from the native constructor. @@ -211,7 +213,7 @@ def initialize_client( self.events = core_events.CoreEventStream(self) self.navigation_reader = NavigationReader() self.agent_binding = agent_binding - self.application = self.lifetime_kind(self, agent_session_id) + self.application = self.lifetime_kind(self, agent_session_id, opening) self.session_navigation = SessionNavigation(self) self.thread_navigation = ThreadNavigator(self) self.thread_actions = ThreadActions(self) diff --git a/src/toad/client/local_connection.py b/src/toad/client/local_connection.py index 6101d512f..8baa71313 100644 --- a/src/toad/client/local_connection.py +++ b/src/toad/client/local_connection.py @@ -31,6 +31,7 @@ from agent_comms.ui_model.sidebar import SidebarModel from toad.client.agent_processes import AgentProcesses, SpawnsAgentProcesses +from toad.launch_opening import LaunchOpening from toad.client.db import UNSCOPED_TABS, TabScope from toad.client.connection import ( AnsweringReads, @@ -59,6 +60,21 @@ def select_connection(arguments: list[str]) -> CoreConnection: arguments, lambda: LaunchRoot.from_path(CommsRoute.current().root))) +@dataclass(frozen=True) +class ClientLaunch: + """What a desktop launch's own arguments select, read once for Toad's terminal launch and + Qt's desktop launch alike: the Core it opens (`select_connection`) and the conversation + it opens there (`LaunchOpening`, `--open NAME`). Each is removed from ``arguments``, so + the frontend's own parser sees only the project and its agent.""" + + connection: CoreConnection + opening: LaunchOpening + + @classmethod + def startup(cls, arguments: list[str]) -> ClientLaunch: + return cls(select_connection(arguments), LaunchOpening.startup(arguments)) + + class LocalCoreConnection(LaunchRoot, CoreConnection): """A local connection inherits the selected root and its launch behavior.""" diff --git a/src/toad/client/sidebar_filter.py b/src/toad/client/sidebar_filter.py index 5d708b053..57454572f 100644 --- a/src/toad/client/sidebar_filter.py +++ b/src/toad/client/sidebar_filter.py @@ -7,7 +7,7 @@ match decision and the current text; Textual's `SideBar.search` reactive and Qt's `QLineEdit` both write through it, and every listing (Textual's `SidebarGroup.sync_members`, Qt's `Sidebar.draw_lines`) -reads through `matches` instead of comparing text itself. A new frontend never +reads through `matching` (which ranks what `matches`) instead of comparing text itself. A new frontend never reimplements the match rule; it hands the filter a row name and asks. The class is toolkit-neutral (no Textual, no Qt, no reactive); subscribers are a @@ -18,7 +18,7 @@ from __future__ import annotations from abc import abstractmethod -from collections.abc import Callable +from collections.abc import Callable, Iterable from metaclass_registry import AbstractHooksMeta @@ -66,6 +66,22 @@ def matches(self, name: str) -> bool: return True return self._text.casefold() in name.casefold() + def matching[T](self, items: Iterable[T], name: Callable[[T], str] = str) -> tuple[T, ...]: + """The listing both frontends draw: the ``items`` whose ``name`` matches, the name + typed exactly first, then names that start with it, then the rest, each in the + order given. Typing `claude-a` puts the live `claude-a` above every `claude-a…` + fork it is a prefix of.""" + listed = [item for item in items if self.matches(name(item))] + if not self._text: + return tuple(listed) + typed = self._text.casefold() + + def rank(item: T) -> int: + folded = name(item).casefold() + return 0 if folded == typed else 1 if folded.startswith(typed) else 2 + + return tuple(sorted(listed, key=rank)) + class SidebarSearchField(metaclass=AbstractHooksMeta): """The sidebar's search input as a frontend draws it: Textual's `SidebarSearch` and Qt's diff --git a/src/toad/launch_opening.py b/src/toad/launch_opening.py new file mode 100644 index 000000000..95b135813 --- /dev/null +++ b/src/toad/launch_opening.py @@ -0,0 +1,60 @@ +"""What a launch asks to open once its tabs are back: `--open NAME` names a thread, or a +`#channel`, and the start opens it as that conversation's sidebar row does. Declared once for +every frontend: the terminal launch and Qt's desktop launch read it from their arguments +here (`LaunchOpening.startup`), and the shared start opens it (`ApplicationLifetime.start`).""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import TYPE_CHECKING, ClassVar + +if TYPE_CHECKING: + from toad.client.application import ClientApplication + + +class LaunchOpening(ABC): + """The conversation a launch names, or none.""" + + argument: ClassVar[str] = "--open" + + @classmethod + def startup(cls, arguments: list[str]) -> LaunchOpening: + """Read this process's own `--open NAME`, removing it from ``arguments`` as the + connection's own options are removed, so each frontend's parser never sees it. A `--` + ends this process's options: after it the arguments belong to a command it runs.""" + own = arguments[:arguments.index("--")] if "--" in arguments else arguments + if cls.argument not in own: + return NoLaunchOpening() + index = own.index(cls.argument) + if index + 1 == len(own): + raise ValueError(f"{cls.argument} requires a thread or #channel name") + name = arguments[index + 1] + del arguments[index : index + 2] + return OpensTarget(name) + + @abstractmethod + async def open(self, app: ClientApplication) -> None: + """Open what the launch named, once the saved tabs are back.""" + + +@dataclass(frozen=True) +class NoLaunchOpening(LaunchOpening): + """The launch named nothing: the restored tabs are the start.""" + + async def open(self, app: ClientApplication) -> None: + pass + + +@dataclass(frozen=True) +class OpensTarget(LaunchOpening): + """A thread or `#channel` the launch named: opened from home, as its sidebar row and a + link naming it are (`TargetOpen`).""" + + name: str + + async def open(self, app: ClientApplication) -> None: + from toad.core.session_requests import TargetOpen + from toad.navigation_target import NavigationTarget + + await TargetOpen(NavigationTarget.named(self.name)).apply(app.session_navigation) diff --git a/src/toad/qt/client_start.py b/src/toad/qt/client_start.py index 6fd57bb1b..86f9a22a1 100644 --- a/src/toad/qt/client_start.py +++ b/src/toad/qt/client_start.py @@ -9,6 +9,7 @@ import sys from dataclasses import dataclass from pathlib import Path +from typing import TYPE_CHECKING import qasync from PySide6.QtCore import QEvent, QObject @@ -20,6 +21,7 @@ from toad.client.connection import CoreConnection from toad.launch_binding import AgentBinding +from toad.launch_opening import LaunchOpening, NoLaunchOpening from toad.application_lifetime import ApplicationStart from toad.qt.finger_press import FingerPress from toad.qt.finger_scrolling import FingerScrollGesture, FingerScrolling @@ -30,6 +32,10 @@ from toad.render_processes import RenderProcessPool from toad.work_preparation import PreparationRuntime +if TYPE_CHECKING: + # Android's start never loads the desktop's local connection. + from toad.client.local_connection import ClientLaunch + def _renderer_for_platform(connection: CoreConnection) -> Renderer: """A ProcessPool on hosts that fork, an in-thread renderer on Android's Python.""" @@ -46,7 +52,7 @@ class QtClientSettings: async def open_app(connection: CoreConnection, project: Checkout, scheme: ColourScheme, - agent: str = "") -> QtToadApp: + agent: str = "", opening: LaunchOpening = NoLaunchOpening()) -> QtToadApp: """The Qt client shown over the bus behind ``connection``, its saved tabs read and its sidebar observing; ``agent`` is the launch's ``-a``, attached when the connection starts agents (`AgentBinding.launched`), as Toad's terminal launch attaches it.""" @@ -56,7 +62,7 @@ async def open_app(connection: CoreConnection, project: Checkout, scheme: Colour FrameProbe.start_if_requested(QApplication.instance()) launch = await AgentBinding.launched(agent, connection.agent_processes) app = QtToadApp(connection, project, PreparationRuntime(_renderer_for_platform(connection)), scheme, - launch) + launch, opening) # The loop outlives the window: closing it starts the shared client shutdown, which # runs on this loop, so Qt must not stop the loop when the last window closes. QApplication.instance().setQuitOnLastWindowClosed(False) @@ -96,12 +102,12 @@ def ask(self) -> None: async def serve(connection: CoreConnection, project: Checkout, scheme: ColourScheme, - agent: str = "") -> None: + agent: str = "", opening: LaunchOpening = NoLaunchOpening()) -> None: """Show the bus behind ``connection`` until Qt is asked to end, then end the way every end does: the window closes while its client still serves its views, then the shared client shutdown, and qasync stops the loop when this returns. Desktop passes the process-decoding member, Android the one decoding in place.""" - app = await open_app(connection, project, scheme, agent) + app = await open_app(connection, project, scheme, agent, opening) application = QApplication.instance() request = EndRequest(asyncio.get_running_loop().create_future()) application.installEventFilter(request) @@ -111,11 +117,12 @@ async def serve(connection: CoreConnection, project: Checkout, scheme: ColourSch await app.close_client() -def serve_launch(connection: CoreConnection, own: list[str], scheme: ColourScheme) -> None: - """Serve ``connection``, the Core the desktop entry selected from its arguments, with the - project and ``-a`` agent the rest of ``own`` name, until the application ends.""" +def serve_launch(launch: ClientLaunch, own: list[str], scheme: ColourScheme) -> None: + """Serve the Core the desktop entry's ``launch`` selected from its arguments, opening the + conversation it named, with the project and ``-a`` agent the rest of ``own`` name, until + the application ends.""" parser = argparse.ArgumentParser(prog="toad.qt.main") parser.add_argument("project", type=Path, nargs="?", default=Path.home()) parser.add_argument("-a", "--agent", default="", help="The agent New Session starts, as Toad's -a.") options = parser.parse_args(own) - qasync.run(serve(connection, Checkout(options.project), scheme, options.agent)) + qasync.run(serve(launch.connection, Checkout(options.project), scheme, options.agent, launch.opening)) diff --git a/src/toad/qt/main.py b/src/toad/qt/main.py index f7a4f369f..a3bf744fd 100644 --- a/src/toad/qt/main.py +++ b/src/toad/qt/main.py @@ -1,5 +1,5 @@ """Start the Qt client on the Core its arguments select, as Toad's terminal launch does: -`python -m toad.qt.main [--comms-profile PROFILE | --comms-root ROOT] [PROJECT] [--agent NAME]`. +`python -m toad.qt.main [--comms-profile PROFILE | --comms-root ROOT] [--open NAME] [PROJECT] [--agent NAME]`. This module is the desktop entry and imports only what Qt's first frame needs: the frame is painted (`QtSplash`), then the client loads and serves (`toad.qt.client_start`).""" @@ -23,14 +23,14 @@ def main(arguments: list[str] = sys.argv) -> None: scheme = current_scheme(os.environ) QtSplash.shown(application, scheme) # The client loads once the first frame is up: importing it is most of a start. The - # desktop selects its Core as Toad's terminal launch does (`select_connection`: a UI + # desktop reads its launch as Toad's terminal launch does (`ClientLaunch`: a UI # profile reaches Core through its connector, otherwise this machine's bus, under which # agents start); Android's start is always remote and never loads `local_connection`. - from toad.client.local_connection import select_connection + from toad.client.local_connection import ClientLaunch from toad.qt.client_start import serve_launch own = arguments[1:] - serve_launch(select_connection(own), own, scheme) + serve_launch(ClientLaunch.startup(own), own, scheme) if __name__ == "__main__": diff --git a/src/toad/qt/thread_comms_panel.py b/src/toad/qt/thread_comms_panel.py index 295f78fa3..125823bdf 100644 --- a/src/toad/qt/thread_comms_panel.py +++ b/src/toad/qt/thread_comms_panel.py @@ -207,9 +207,8 @@ def _apply(self, snapshot: ThreadCommsSnapshot) -> None: if not entries: empty = QTreeWidgetItem(top, [group_type.empty_text]) empty.setFlags(empty.flags() & ~Qt.ItemFlag.ItemIsSelectable) - for entry in entries: - if self._search.matches(entry.target): - self._add_entry_item(top, entry) + for entry in self._search.matching(entries, lambda entry: entry.target): + self._add_entry_item(top, entry) def _add_entry_item(self, parent_item: QTreeWidgetItem, entry: RelationshipEntry) -> None: row = QtRelationshipItem(self, parent_item, parent_item.data(0, Qt.ItemDataRole.UserRole), entry) diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index b8c331e05..f660c7bdf 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -114,6 +114,7 @@ from toad.core import session_requests from toad.core.events import CoordinationObserved, ExternalTranscriptChanged, TabHistoryChanged from toad.launch_binding import AgentBinding, NoAgent +from toad.launch_opening import LaunchOpening, NoLaunchOpening from toad.navigation_context import HomeNavigation, NavigationOwner from toad.session_navigation import TabElement from toad.client.session_scope import HomeSessionOrigin @@ -1070,13 +1071,14 @@ def draw_lines(self, model: SidebarModel, top: KeptLines) -> None: top.keep(NewSessionRow()) threads = model.threads.rows matches = self.filter.matches + matching = self.filter.matching pending = self.window.thread_actions.pending counts = self.window.settings.sidebar.unread_counts for name, channel in model.channels.rows.items(): # A channel stays visible if its name matches OR any of its member thread # names do; hiding a channel whose only match is a buried thread would also # hide the thread. The group opens whichever path kept it. - members_shown = [m for m in channel.members if matches(m)] + members_shown = matching(channel.members) if not matches(name) and not members_shown: continue pinned_members = channel.pinned_members @@ -1520,14 +1522,15 @@ class QtToadApp(ClientApplication, LayoutFollower, CorePrewarm, QtWorkspaceFrame def __init__(self, connection: CoreConnection, project: Checkout, preparation: PreparationRuntime, scheme: ColourScheme, - launch: AgentBinding = NoAgent()) -> None: + launch: AgentBinding = NoAgent(), opening: LaunchOpening = NoLaunchOpening()) -> None: super().__init__(project, preparation, scheme) # Walk Core's declaration catalog once up front (shared with the Textual app # via CorePrewarm): a cold first tab otherwise imports every agent_comms # module under the GIL on its first wire revision / action menu. self._prewarm_core_modules() # The launch's agent, as Textual's `-a`: New Session starts its session. - self.initialize_client(launch, connection) + # The conversation the launch named (`--open`), opened once the saved tabs are back. + self.initialize_client(launch, connection, opening=opening) self.input_attention = QtWindowAttention(self) self.action_keys = ActionKeys(lambda: self.settings) # Until a conversation reads Core's display references, bodies link the project's files. diff --git a/src/toad/widgets/sidebar_tree.py b/src/toad/widgets/sidebar_tree.py index cb7165b38..5e4844899 100644 --- a/src/toad/widgets/sidebar_tree.py +++ b/src/toad/widgets/sidebar_tree.py @@ -52,6 +52,7 @@ from toad.native_style import EllipsisOverflow, NoWrap, PointerCursor, TwoRows from toad.no_worker import NoWorker from toad.widgets.side_bar import SideBar +from toad.client.sidebar_filter import SidebarFilter from textual import on from ui_theme.effects import NEW_MESSAGE @@ -264,7 +265,7 @@ class RowReconciliation: """One sync's model membership and transferable native rows, never a retained cache.""" def __init__(self, tree: TargetTree) -> None: - demand = Counter(key for key in tree.member_keys if tree.matches(key)) + demand = Counter(tree.filter.matching(tree.member_keys)) self.listed = frozenset(demand) self.sources = {} requests = {} @@ -462,11 +463,11 @@ def reconciliation_tree(self): @property def matching_keys(self): tree = self.reconciliation_tree - return tuple(key for key in self.member_keys if tree.matches(key)) + return tree.filter.matching(self.member_keys) @property def members_visible(self): - return self.expanded or bool(self.reconciliation_tree.search) + return self.expanded or bool(self.reconciliation_tree.filter.text) @RowReconciliation.sync def reconcile_rows(self, *, changed: frozenset[str]): @@ -481,7 +482,7 @@ def reconcile_rows(self, *, changed: frozenset[str]): return () keys = self.matching_keys tree = self.reconciliation_tree - self.set_display_constraint("sidebar-search", bool(keys) or not tree.search) + self.set_display_constraint("sidebar-search", bool(keys) or not tree.filter.text) self.member_container.set_display_constraint("members", self.members_visible) self._rows_pending = False self._step_full = False @@ -514,7 +515,9 @@ def on_mount(self) -> None: ) def _apply_search(self, value: str) -> None: - self.search = value.casefold() + # The sidebar wrote ``value`` into its filter first (`SideBar.watch_search` runs + # before watchers); the tree lists through that one owner. + self.filter = self.query_ancestor(SideBar).filter with self.reconcile_members(): for group in self.navigation_groups: group.sync_members(frozenset(group.member_keys)) @@ -525,10 +528,9 @@ class TargetTree(LineMenuTree, RowTree, HiddenActions, VisibleActions, StepsVert """Common row keyboard mechanics; specialized trees own data and state.""" navigation_groups: Iterable[SidebarGroup] - search = "" - - def matches(self, key: str) -> bool: - return self.search in key.casefold() + # The sidebar's search (`SidebarFilter`), which a searching tree takes from its sidebar + # (`SearchFollower`); a tree outside one lists every row, in model order. + filter: SidebarFilter = SidebarFilter() def preserve_reader(self, placements: list[WidgetPlacement]) -> None: """A sidebar viewport may retain its reader across a native relayout.""" diff --git a/tests/textual/test_open_and_search_rank.py b/tests/textual/test_open_and_search_rank.py new file mode 100644 index 000000000..e789badae --- /dev/null +++ b/tests/textual/test_open_and_search_rank.py @@ -0,0 +1,46 @@ +"""`--open NAME` opens that conversation once the launch's tabs are back, as its sidebar row does; +the sidebar search lists the name typed exactly above the names it is a prefix of.""" + +from functools import partial + +from toad.app import ToadApp +from toad.launch_opening import LaunchOpening, OpensTarget + + +def test_open_is_read_from_the_launch_and_removed(): + arguments = ["--open", "#source", "project", "--", "child", "--open", "other"] + assert LaunchOpening.startup(arguments) == OpensTarget("#source") + assert arguments == ["project", "--", "child", "--open", "other"] + + +async def test_launch_opens_the_named_channel(workspace): + me = workspace.project.name + workspace.thread(me, "source", running=True) + workspace.comms.messaging.send(me, "#source", "Opened by the launch") + launched = partial(ToadApp, opening=OpensTarget("#source")) + async with workspace.app(size=(100, 40), application=launched, session=False) as ui: + await ui.until_shows("Opened by the launch") + + +async def test_search_lists_the_exact_name_first(workspace): + from toad.widgets.comms_sidebar import CommsSidebar + + for name in ("claude-a", "claude-ab12", "claude-ac34"): # newest first: claude-a lists last + workspace.thread(name, "lab", running=True) + async with workspace.app(size=(120, 40)) as ui: + app, _pilot = ui.textual + sidebar = await ui.revealed(app.workspace_chrome.channels) + tree = app.screen.query_one(CommsSidebar) + await ui.until(lambda: tree.navigation.ready.is_set(), why="the channels sidebar's rows") + sidebar.search = "claude-a" + await ui.step() + + def listed(): + return [key for group in tree.navigation_groups for key in group.matching_keys] + + await ui.until(lambda: {"claude-a", "claude-ab12", "claude-ac34"} <= set(listed()), + why="every claude-a thread listed under the search") + model_order = [key for group in tree.navigation_groups for key in group.member_keys + if key.startswith("claude-a")] + assert model_order[0] != "claude-a", model_order # the model alone would not list it first + assert listed()[0] == "claude-a", listed() From f461d7576a7247a4397288ca4c0107700cf0c3ee Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:32:33 -0500 Subject: [PATCH 11/16] history: a burst leaves the top row's own message out of its stack by identity The re-gate's arrival drive found one burst head above the top row and none stacked: burst messages from one sender to one destination in the same second draw equal headers, and `ArrivalBurst.stack` left out every message whose header equalled the top row's, so the earlier ones were dropped with it. `PinnedHeader` now carries the top row's message (its fragment key's source, from the shared `FragmentRowUnderTop` both front ends pin through) and the stack leaves out only that message. The drive's count does the same. The Qt pin sets its tap pass-through before its unchanged-drawing return: equal headers can stand for other messages, so the flag follows the stack, not the drawing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/client/history_changes.py | 14 ++++++++++---- src/toad/qt/history.py | 4 +++- tools/qt_drive.py | 5 ++++- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index ad6bbcbe6..04e91d326 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -24,7 +24,8 @@ from toad.client.line_blocks import Divider, MutedRole if TYPE_CHECKING: - from toad.client.fragments import FragmentKey, HistoryFragment + from agent_comms.nominal.field_codec import ToolCallId + from toad.client.fragments import EventSourceKey, FragmentKey, HistoryFragment from toad.client.transcript_fragments import TranscriptFragment from toad.widgets.history_anchor import HistoryWindow from toad.widgets.transcript_history import FragmentSpan, TranscriptPageView @@ -82,7 +83,8 @@ class FragmentRowUnderTop: width: int def pinned_header(self) -> PinnedHeader: - return PinnedHeader(self.fragment.sticky_header(self.block, self.row), self.x, self.width) + return PinnedHeader(self.fragment.sticky_header(self.block, self.row), self.x, self.width, + self.fragment.key.source) @dataclass(frozen=True) @@ -94,6 +96,9 @@ class PinnedHeader: headers: tuple[Divider, ...] x: int width: int + source: EventSourceKey | ToolCallId | None = None + """The message the top row draws (its fragment key's `source`), by which a burst leaves the + top row's own message out of its stack; none where no drawn fragment is on the top row.""" @dataclass(frozen=True) @@ -160,9 +165,10 @@ def stack(self, window: PinsMessageHeader, pinned: PinnedHeader) -> StackedHeade 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:] + # The top row's own message by identity: messages from one sender to one destination in + # the same second draw equal headers, and comparing headers left such a message out. above = [message for message in self.messages[:-1] - if message.header not in own + if message.key.source != pinned.source and (top := window.message_top(message.key)) is not None and top < window.scroll_y] if not above: return NO_STACK diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 80a189945..e31fa4a6b 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -817,6 +817,9 @@ def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None: header out again from its html (its theme's colours resolved span by span) was a third of the phone's UI thread during a burst (2026-11-18).""" window = self.history_window + # Taps reach the stacked headers whenever a stack is pinned, even when its drawing is + # unchanged: equal headers can stand for other messages (one sender, one second). + self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, not self.stacked.keys) context = (width, window.font().key(), window.rows.links_revision, id(window.rows.renderer)) drawn = (headers, x, context) if drawn == self.drawn: @@ -827,7 +830,6 @@ def draw_pinned(self, headers: tuple[Divider, ...], x: int, width: int) -> None: self.laid_out = {header: kept.get(header) or window.rows.header_document(header, window.font(), width) for header in headers} self.documents = tuple(self.laid_out[header] 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_() diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 2009ea4ff..5e020cfaa 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -2832,8 +2832,11 @@ async def burst_stack(self, window, burst: int) -> None: top row; a tap on a stacked header brings that message's head to the top row.""" arrived = window.arrival_burst.messages pin = window.sticky_header + # The top row's own message pins its header as the top row's, not in the stack. + own = window.top_message_header().source above = [message for message in arrived[:-1] - if (top := window.message_top(message.key)) is not None and top < window.scroll_y] + if message.key.source != own + and (top := window.message_top(message.key)) is not None and top < window.scroll_y] texts = [document.toPlainText().strip() for document in pin.documents] latest_top = window.message_top(arrived[-1].key) if arrived else None self.report("burst-stack", arrived=len(arrived), above=len(above), stacked=len(pin.stacked.keys), From 06f0a9257abda5fd78f0dc920e541412e2085db8 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:32:33 -0500 Subject: [PATCH 12/16] qt_drive: a drive always keeps its settings under OUTDIR The isolation applied only when the shell held no XDG_CONFIG_HOME / XDG_STATE_HOME. A shell exporting XDG_CONFIG_HOME=~/.config gave the batch-4 gate's drives the reader's own toad.json: its ssh-origin layout docks both sidebars at the bottom, which left the hold drive's sidebar tree one line tall, so its holds and its tap landed on nothing (`held on []`, then "tapped row"). Their writes went to the real file too. Every gate script already names these same OUTDIR folders. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- tools/qt_drive.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 5e020cfaa..aa294d4a6 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -26,15 +26,16 @@ from typing import ClassVar -# A drive never touches the reader's own settings: run as a script with no XDG_CONFIG_HOME or -# XDG_STATE_HOME of its own, it keeps them under OUTDIR before anything of Toad is imported (a -# module can read them at import). Drives run without them wrote the real toad.json -# (2026-11-17); every caller had to remember to set both. +# A drive never touches the reader's own settings: run as a script, it keeps them under OUTDIR +# before anything of Toad is imported (a module can read them at import), whatever the shell +# holds. Drives run without them wrote the real toad.json (2026-11-17); a shell that exports +# XDG_CONFIG_HOME=~/.config handed the next gate's drives the reader's own layout (sidebars +# docked at the bottom, the tree one line tall) and its writes (2026-11-18). Every gate script +# names these same OUTDIR folders already. if __name__ == "__main__" and len(sys.argv) > 2: for variable, folder in (("XDG_CONFIG_HOME", "config"), ("XDG_STATE_HOME", "state")): - if not os.environ.get(variable): - os.environ[variable] = str((Path(sys.argv[2]) / folder).resolve()) - Path(os.environ[variable]).mkdir(parents=True, exist_ok=True) + os.environ[variable] = str((Path(sys.argv[2]) / folder).resolve()) + Path(os.environ[variable]).mkdir(parents=True, exist_ok=True) import qasync from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, QRect, QTimer, Qt From a60cd6602b90dcfbeeee81390afe17a31ad373b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:35:22 +0000 Subject: [PATCH 13/16] toad serve-tailnet: port the owner-only tailnet serving from feat/toad-serve-tailnet The unmerged feat/toad-serve-tailnet branch (head 7ba3e2167) carried owner-only tailnet serving behind tailscale serve: a TailnetBrowserEndpoint on a 0600 unix socket, TailnetBrowserAuthentication checking Tailscale-User-Login against the machine owner's login from tailscale status, and a ToadWebServer refactored to take any BrowserAuthentication. Port the architecture onto current main: - BrowserEndpoint ABC with LocalBrowserEndpoint and TailnetBrowserEndpoint - BrowserAuthentication ABC with Local and Tailnet siblings - ToadWebServer takes BrowserAuthentication; one class, two auth strategies - ToadWebServer.serve() overridden to listen on the endpoint's own socket - ProcessSingleton claims the tailnet lock so a second instance fails - OwnerOnlyDirectory verifies the runtime dir's ownership and mode The systemd unit now uses the installed toad command with no PYTHONPATH to a worktree: `toad serve-tailnet 8443 acp agent-comms-acp`. Co-Authored-By: Claude Opus 5.5 --- docs/browser-serving.md | 34 ++-- src/toad/cli.py | 28 +++- src/toad/web_server.py | 263 ++++++++++++++++++++++++++----- tools/systemd/toad-serve.service | 4 +- 4 files changed, 273 insertions(+), 56 deletions(-) diff --git a/docs/browser-serving.md b/docs/browser-serving.md index 59890f09e..1b30c39fb 100644 --- a/docs/browser-serving.md +++ b/docs/browser-serving.md @@ -37,26 +37,38 @@ each local port. Missing credentials, mismatched or null Origin, a DNS-rebinding Host and an external bind fail closed. The server API is pinned to `textual-serve==1.1.3`. +## Tailnet browser serving + +`toad serve-tailnet PORT` serves to this machine's tailnet owner only. It listens +on an owner-only unix socket (`0600` in the user's runtime directory) and checks +the `Tailscale-User-Login` header that `tailscale serve` attaches to each request. +The owner login and DNS name are read from `tailscale status --json --self` at +startup. + +```shell +toad serve-tailnet 8443 acp agent-comms-acp +``` + +No TCP listener exists: the only peer that reaches the routes is the tailscale +proxy. The unix socket is claimed with a lockfile so a second instance fails +rather than racing the first. + ## Desktop tailnet service -The desktop user service is `tools/systemd/toad-serve.service`. It starts the -existing `textual-serve` package using the Python under -`~/.local/share/agent-comms/current`, not a copied runtime. Each browser tab runs -`/home/ts/bin/toad-comms`, which selects the installed Toad through its normal -launcher. Restart the service after a runtime switch to move the server process -as well as newly opened Toad children onto the new runtime. +The desktop user service is `tools/systemd/toad-serve.service`. It runs `toad +serve-tailnet` with the installed runtime's toad. Each browser tab runs `toad acp +agent-comms-acp` as its own process. Restart the service after a runtime switch. Install the unit under `~/.config/systemd/user/toad-serve.service`, then run: ```shell systemctl --user daemon-reload systemctl --user enable --now toad-serve.service -tailscale serve --bg --https=8443 http://127.0.0.1:8040 +tailscale serve --bg --https=8443 unix:/run/user/$(id -u)/toad-serve-8443.sock ``` -Open `https://desktop.tail553874.ts.net:8443` from a tailnet device. The backend -binds only `127.0.0.1:8040`. This service uses tailnet access control rather than -the local `toad serve` cookie gate. A connected browser has full agent control; -never enable Funnel for port 8443. The connector's existing HTTPS/Funnel route +Open `https://desktop.tail553874.ts.net:8443` from a tailnet device. Only the +machine's tailnet owner is admitted. A connected browser has full agent control; +never enable Funnel for this port. The connector's existing HTTPS/Funnel route on port 443 is separate and must remain unchanged. `tailscale funnel status` is a read-only check, not permission to enable another public route. diff --git a/src/toad/cli.py b/src/toad/cli.py index 18d0184c1..8d8a606e0 100644 --- a/src/toad/cli.py +++ b/src/toad/cli.py @@ -237,7 +237,7 @@ def replay(path: str) -> None: "serve", context_settings={"allow_interspersed_args": False}, ) -@click.option("-p", "--port", metavar="PORT", default=8000, type=int) +@click.option("-p", "--port", metavar="PORT", default=8000, type=click.IntRange(1, 65535)) @click.option( "-H", "--host", @@ -247,17 +247,33 @@ def replay(path: str) -> None: ) @click.argument("toad_args", metavar="[TOAD ARGS]...", nargs=-1, type=click.UNPROCESSED) def serve(port: int, host: str, toad_args: tuple[str, ...]) -> None: - """Serve a Toad command line in a web browser. + """Serve a Toad command line in a web browser on this machine. Each browser tab runs `toad TOAD ARGS` as its own process, for example `toad serve acp agent-comms-acp`. """ + from toad.web_server import LocalBrowserAuthentication, LocalBrowserEndpoint + ToadWebServer.run_toad( + LocalBrowserAuthentication(LocalBrowserEndpoint(host, port)), toad_args + ) + + +@main.command( + "serve-tailnet", + context_settings={"allow_interspersed_args": False}, +) +@click.argument("https_port", metavar="PORT", type=click.IntRange(1, 65535)) +@click.argument("toad_args", metavar="[TOAD ARGS]...", nargs=-1, type=click.UNPROCESSED) +def serve_tailnet(https_port: int, toad_args: tuple[str, ...]) -> None: + """Serve a Toad command line to this machine's tailnet owner only. + + Listens on an owner-only unix socket for `tailscale serve --https=PORT`, which + supplies each caller's tailnet login. + """ + from toad.web_server import TailnetBrowserAuthentication - command = shlex.join([sys.executable, "-m", "toad", *toad_args]) - server = ToadWebServer(command, host=host, port=port, title="Toad") - TerminalApplicationLifetime.set_process_title("toad serve") - server.serve() + ToadWebServer.run_toad(TailnetBrowserAuthentication.from_status(https_port), toad_args) @main.command("about") diff --git a/src/toad/web_server.py b/src/toad/web_server.py index 942484a88..5ec5451a0 100644 --- a/src/toad/web_server.py +++ b/src/toad/web_server.py @@ -1,23 +1,69 @@ -"""Authenticated loopback access for the installed textual-serve routes.""" +"""Authenticated access to the installed textual-serve routes. + +A local endpoint listens on loopback TCP and is reached with a bootstrap capability; a +tailnet endpoint listens only on an owner-only unix socket that ``tailscale serve`` +proxies to, and that proxy supplies the caller's tailnet identity. +""" from __future__ import annotations +import asyncio import logging +import os import secrets +import shlex +import signal +import socket +import stat +import subprocess +import sys from abc import ABC, abstractmethod -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Iterator +from contextlib import AbstractContextManager, contextmanager from dataclasses import dataclass, field from importlib.metadata import version -from urllib.parse import quote +from pathlib import Path +from urllib.parse import quote, urlsplit +import platformdirs from aiohttp import web from textual_serve.server import Server +from toad.application_lifetime import TerminalApplicationLifetime + type Handler = Callable[[web.Request], Awaitable[web.StreamResponse]] +class BrowserEndpoint(ABC): + """Where the server listens and the origin browsers address.""" + + @property + @abstractmethod + def url(self) -> str: ... + + @property + @abstractmethod + def listens_on(self) -> str: ... + + @abstractmethod + def listening(self) -> AbstractContextManager[socket.socket]: ... + + @property + def authority(self) -> str: + return urlsplit(self.url).netloc + + def addresses(self, request: web.Request) -> bool: + hosts = request.headers.getall("Host", []) + origins = request.headers.getall("Origin", []) + if hosts != [self.authority]: + return False + if request.path == "/ws" and origins != [self.url]: + return False + return not origins or origins == [self.url] + + @dataclass(frozen=True) -class LocalBrowserEndpoint: +class LocalBrowserEndpoint(BrowserEndpoint): host: str port: int @@ -28,19 +74,95 @@ def __post_init__(self) -> None: ) @property - def authority(self) -> str: - return f"{self.host}:{self.port}" + def url(self) -> str: + return f"http://{self.host}:{self.port}" @property - def url(self) -> str: - return f"http://{self.authority}" + def listens_on(self) -> str: + return self.url + + @contextmanager + def listening(self) -> Iterator[socket.socket]: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind((self.host, self.port)) + yield listener @property def cookie_name(self) -> str: - # Cookies have no port scope; concurrent local servers need distinct names. return f"toad_web_session_{self.port}" +@dataclass(frozen=True) +class OwnerOnlyDirectory: + """A directory only this user can enter.""" + + path: Path + + @classmethod + def user_runtime(cls) -> OwnerOnlyDirectory: + return cls.decode(Path(platformdirs.user_runtime_dir())) + + @classmethod + def decode(cls, path: Path) -> OwnerOnlyDirectory: + path.mkdir(mode=0o700, exist_ok=True) + status = path.lstat() + if not stat.S_ISDIR(status.st_mode): + raise RuntimeError(f"{path} is not a directory") + if status.st_uid != os.getuid() or status.st_mode & 0o077: + raise RuntimeError( + f"{path} must be owned by uid {os.getuid()} with mode 0700, " + f"found uid {status.st_uid} mode {stat.S_IMODE(status.st_mode):o}" + ) + return cls(path) + + +@dataclass(frozen=True) +class TailnetBrowserEndpoint(BrowserEndpoint): + """A 0600 unix socket that only ``tailscale serve`` (root) and its owner can open.""" + + dns_name: str + https_port: int + directory: OwnerOnlyDirectory + + @property + def url(self) -> str: + if self.https_port == 443: + return f"https://{self.dns_name}" + return f"https://{self.dns_name}:{self.https_port}" + + @property + def socket_path(self) -> Path: + return self.directory.path / f"toad-serve-{self.https_port}.sock" + + @property + def lock_path(self) -> Path: + return self.directory.path / f"toad-serve-{self.https_port}.lock" + + @property + def listens_on(self) -> str: + return ( + f"unix:{self.socket_path} " + f"(tailscale serve --bg --https={self.https_port} unix:{self.socket_path})" + ) + + @contextmanager + def listening(self) -> Iterator[socket.socket]: + from agent_comms_hooks.process_claim import ProcessSingleton + + with ( + ProcessSingleton(self.lock_path).claimed(), + socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener, + ): + self.socket_path.unlink(missing_ok=True) + listener.bind(str(self.socket_path)) + try: + self.socket_path.chmod(0o600) + yield listener + finally: + self.socket_path.unlink(missing_ok=True) + + class BrowserAccess(ABC): async def dispatch( self, request: web.Request, handler: Handler @@ -97,71 +219,139 @@ async def respond( return response +class BrowserAuthentication(ABC): + endpoint: BrowserEndpoint + + def decode(self, request: web.Request) -> BrowserAccess: + if not self.endpoint.addresses(request): + return RejectedBrowserAccess() + return self.credential(request) + + @abstractmethod + def credential(self, request: web.Request) -> BrowserAccess: ... + + @property + @abstractmethod + def entry_url(self) -> str: ... + + +@dataclass(frozen=True) +class TailnetBrowserAuthentication(BrowserAuthentication): + """The tailnet login ``tailscale serve`` attaches to each request is the credential.""" + + endpoint: TailnetBrowserEndpoint + owner_login: str + + @classmethod + def from_status(cls, https_port: int) -> TailnetBrowserAuthentication: + result = subprocess.run( + ("tailscale", "status", "--json", "--self"), + check=True, + capture_output=True, + text=True, + timeout=10, + ) + import json + + status = json.loads(result.stdout) + dns_name = status["Self"]["DNSName"].rstrip(".") + user_id = str(status["Self"]["UserID"]) + owner_login = status["User"][user_id]["LoginName"] + endpoint = TailnetBrowserEndpoint( + dns_name, https_port, OwnerOnlyDirectory.user_runtime() + ) + return cls(endpoint, owner_login) + + def credential(self, request: web.Request) -> BrowserAccess: + if request.headers.getall("Tailscale-User-Login", []) == [self.owner_login]: + return AuthenticatedBrowserAccess() + return RejectedBrowserAccess() + + @property + def entry_url(self) -> str: + return f"{self.endpoint.url}/" + + @dataclass(frozen=True) -class LocalBrowserAuthentication: +class LocalBrowserAuthentication(BrowserAuthentication): endpoint: LocalBrowserEndpoint capability: str = field( default_factory=lambda: secrets.token_urlsafe(32), repr=False ) @property - def bootstrap_url(self) -> str: + def entry_url(self) -> str: return f"{self.endpoint.url}/?token={quote(self.capability)}" def accepts(self, candidate: str) -> bool: - # Compare bytes so an external non-ASCII credential is rejected, not a 500. return secrets.compare_digest( candidate.encode("utf-8", errors="surrogatepass"), self.capability.encode("ascii"), ) - def decode(self, request: web.Request) -> BrowserAccess: - """Decode external Host, Origin and credentials before any route handler.""" - hosts = request.headers.getall("Host", []) - origins = request.headers.getall("Origin", []) - if hosts != [self.endpoint.authority]: - return RejectedBrowserAccess() - if request.path == "/ws" and origins != [self.endpoint.url]: - return RejectedBrowserAccess() - if origins and origins != [self.endpoint.url]: - return RejectedBrowserAccess() - token = request.query.get("token") - if request.path == "/" and token is not None: - if request.method == "GET" and self.accepts(token): + def credential(self, request: web.Request) -> BrowserAccess: + match request.path, request.query.getall("token", []): + case "/", [token] if request.method == "GET" and self.accepts(token): return BootstrapBrowserAccess(self) - return RejectedBrowserAccess() + case "/", [_, *_]: + return RejectedBrowserAccess() if self.accepts(request.cookies.get(self.endpoint.cookie_name, "")): return AuthenticatedBrowserAccess() return RejectedBrowserAccess() class ToadWebServer(Server): - """Keep the vendor server/child path; check local access before every route.""" + """Keep the vendor server/child path; check access before every route.""" def __init__( self, command: str, + authentication: BrowserAuthentication, *, - host: str = "127.0.0.1", - port: int = 8000, title: str | None = None, ) -> None: if version("textual-serve") != "1.1.3": raise RuntimeError("Browser serving requires reviewed textual-serve 1.1.3") - endpoint = LocalBrowserEndpoint(host, port) - super().__init__( - command, host=host, port=port, title=title, public_url=endpoint.url + endpoint = authentication.endpoint + super().__init__(command, title=title, public_url=endpoint.url) + self.authentication = authentication + + @classmethod + def run_toad( + cls, authentication: BrowserAuthentication, toad_args: tuple[str, ...] + ) -> None: + import toad + + command = shlex.join( + [sys.executable, "-m", toad.__name__, *(toad_args or (".",))] ) - self.authentication = LocalBrowserAuthentication(endpoint) + server = cls(command, authentication, title="Toad") + TerminalApplicationLifetime.set_process_title("toad serve") + server.serve() + + def serve(self, debug: bool = False) -> None: + self.debug = debug + self.initialize_logging() + loop = asyncio.new_event_loop() + loop.add_signal_handler(signal.SIGINT, self.request_exit) + loop.add_signal_handler(signal.SIGTERM, self.request_exit) + with self.authentication.endpoint.listening() as listener: + web.run_app( + self._make_app(), + sock=listener, + handle_signals=False, + loop=loop, + print=lambda *args: None, + ) def initialize_logging(self) -> None: super().initialize_logging() - # Access URLs must never record the bootstrap bearer credential. logging.getLogger("aiohttp.access").disabled = True async def on_startup(self, app: web.Application) -> None: - self.console.print("Toad local browser (keep this URL private):") - self.console.print(self.authentication.bootstrap_url) + self.console.print("Toad browser (keep this URL private):") + self.console.print(self.authentication.entry_url) + self.console.print(f"Listening on {self.authentication.endpoint.listens_on}") async def _make_app(self) -> web.Application: app = await super()._make_app() @@ -175,7 +365,6 @@ async def local_capability( async def on_response_prepare( request: web.Request, response: web.StreamResponse ) -> None: - # Streaming download/WS handlers prepare before middleware returns. BrowserAccess.secure(response) app.middlewares.append(local_capability) diff --git a/tools/systemd/toad-serve.service b/tools/systemd/toad-serve.service index 78368e24e..fe19cc19c 100644 --- a/tools/systemd/toad-serve.service +++ b/tools/systemd/toad-serve.service @@ -1,11 +1,11 @@ [Unit] -Description=Toad browser workspace (loopback backend for tailnet-only Serve) +Description=Toad browser workspace (tailnet owner-only Serve) After=network.target [Service] Type=simple WorkingDirectory=/home/ts -ExecStart=/home/ts/.local/share/agent-comms/current/bin/python -c "from textual_serve.server import Server; Server('/home/ts/bin/toad-comms', host='127.0.0.1', port=8040, public_url='https://desktop.tail553874.ts.net:8443').serve()" +ExecStart=/home/ts/bin/toad serve-tailnet 8443 acp agent-comms-acp UnsetEnvironment=PYTHONPATH NO_COLOR TOAD_VALIDATION Environment=PYTHONUNBUFFERED=1 Restart=on-failure From 15153b85f7a6b5fc03f7585baa7853bb4eacdd6c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:37:26 +0000 Subject: [PATCH 14/16] fix: burst stack covers visible header as the overlay's last line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When B's header divider is the viewport's top row, pinned.headers is empty (the header is visible, no pin needed). The old code drew A's stacked header at y=0 on top of B's visible header — two Agent headers at the same pixels. The first attempt (returning NO_STACK when pinned is empty) killed the stack entirely, failing the drive's assertion that burst heads above the top row produce a visible stack. Fix: when pinned.headers is empty, find the burst message at the top row (reversed scan: message_top <= scroll_y). Its header becomes the overlay's last line (top_line) so the opaque overlay covers the flow's copy, and earlier messages stack above it. The overlay reads "N new / A / B" with B drawn once. The top-row header's key stays out of stacked.keys, so clicking it does nothing (the reader is already there). The overlay height = count + stacked + B_copy >= B_flow, so the flow's header is fully behind the opaque overlay in both Qt (WA_OpaquePaintEvent, sized to sum of doc heights at y=0) and Textual (dock=top, auto-height). Co-Authored-By: Claude Opus 5.5 --- src/toad/client/history_changes.py | 22 +++++++-- tests/textual/test_arrival_burst_stack.py | 55 +++++++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index f6a23e992..4b53adf1c 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -157,10 +157,24 @@ def stack(self, window: PinsMessageHeader, pinned: PinnedHeader) -> StackedHeade """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 or not pinned.headers: + its header as before and is not stacked twice. + + When the top row IS a header (pinned.headers empty), the burst message at that row + becomes the overlay's last line, so the overlay covers the flow's header with its + own copy and earlier messages stack above it — never A drawn over visible B.""" + if len(self.messages) < 2 or not pinned.width: return NO_STACK - own = pinned.headers[-1:] + if pinned.headers: + own = pinned.headers[-1:] + top_line: tuple[Divider, ...] = () + else: + at_top = next((message for message in reversed(self.messages) + if (t := window.message_top(message.key)) is not None + and t <= window.scroll_y), None) + if at_top is None: + return NO_STACK + own = (at_top.header,) + top_line = (at_top.header,) 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] @@ -168,7 +182,7 @@ def stack(self, window: PinsMessageHeader, pinned: PinnedHeader) -> StackedHeade 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)), + return StackedHeaders((count, *(message.header for message in stacked), *top_line), (above[0].key, *(message.key for message in stacked))) diff --git a/tests/textual/test_arrival_burst_stack.py b/tests/textual/test_arrival_burst_stack.py index c95fe8f90..74bb235a3 100644 --- a/tests/textual/test_arrival_burst_stack.py +++ b/tests/textual/test_arrival_burst_stack.py @@ -61,3 +61,58 @@ async def test_a_burst_stacks_the_earlier_headers_and_a_click_opens_one(workspac app.save_screenshot("burst-opened.svg", str(shots)) assert not window.arrival_burst.messages and not pin.stacked.keys assert not window.follows_tail + + +async def test_burst_stack_covers_visible_header_without_overlap(workspace, tmp_path): + """When a burst message's header is the viewport's top row (pinned.headers empty), + the overlay draws 'N new' + stacked earlier headers + that header as its last line, + covering the flow's copy so no other header sits on top of it.""" + workspace.thread("sender", "bstack", running=True) + comms = workspace.comms + for index in range(10): + comms.messaging.send("sender", "#bstack", f"fill {index}: " + "padding " * 6) + shots = Path(os.environ.get("BURST_SHOTS", tmp_path)) + async with workspace.app(size=(80, 30)) as ui: + app, pilot = ui.textual + await ui.open_channel("#bstack", actor="sender") + chat = app.screen.query_one(CommsChatView) + history, window = chat.message_history, chat.window + await ui.until(lambda: history.state.accepts_source_work, why="the channel's messages") + await ui.until(lambda: window.follows_tail, why="the reader on the tail") + + for index in range(BURST): + comms.messaging.send("sender", "#bstack", f"BURST {index}\n" + "\n".join( + f"line {row} of burst message {index}" for row in range(8))) + await refresh_chat(chat) + await ui.until_shows(f"BURST {BURST - 1}") + pin = window.sticky_header + await ui.until(lambda: pin.stacked.keys, why="the burst stacked", seconds=15) + + burst = window.arrival_burst.messages + assert len(burst) == BURST + latest = burst[-1] + top = window.message_top(latest.key) + assert top is not None, "latest burst message on screen" + + # Put the latest message's first row (Gap) at the viewport top. + # Its header divider is visible; pinned.headers is empty. + with window.layout_scroll(): + window.scroll_y = top + window.repin_header() + await pilot.pause() + app.save_screenshot("burst-header-at-top.svg", str(shots)) + + above = [m for m in burst[:-1] + if (t := window.message_top(m.key)) is not None and t < window.scroll_y] + assert above, "earlier burst heads are above the top row" + assert pin.display, "pin visible when burst heads are above" + assert pin.stacked.keys, "stacked keys present" + assert pin.headers[0].label == f"{BURST} new", pin.headers[:1] + # The latest header appears exactly once — as the overlay's last line, + # never A's header covering visible B. + latest_label = latest.header.label + overlay_labels = [h.label for h in pin.headers] + assert overlay_labels.count(latest_label) == 1, ( + f"latest header once in overlay, got {overlay_labels}") + assert overlay_labels[-1] == latest_label, ( + f"latest header is the overlay's last line, got {overlay_labels}") From fcd6a4f1831d9a8fc5e3391e79feea042c6aaaf2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 19:40:15 +0000 Subject: [PATCH 15/16] serve-tailnet: use TailnetSelf from agent-comms instead of hand-parsing status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TailnetBrowserAuthentication.from_status now calls TailnetBuses.this_machine() which returns a TailnetSelf(dns_name, owner_login) — the same tailscale status command and JSON parse that peer discovery already owns. Removes the subprocess import and raw dict-path reading that restated the status decode (IDEN-5: one fact, two stores). Co-Authored-By: Claude Opus 5.5 --- src/toad/web_server.py | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/src/toad/web_server.py b/src/toad/web_server.py index 5ec5451a0..68ef7d1e0 100644 --- a/src/toad/web_server.py +++ b/src/toad/web_server.py @@ -15,7 +15,6 @@ import signal import socket import stat -import subprocess import sys from abc import ABC, abstractmethod from collections.abc import Awaitable, Callable, Iterator @@ -244,23 +243,13 @@ class TailnetBrowserAuthentication(BrowserAuthentication): @classmethod def from_status(cls, https_port: int) -> TailnetBrowserAuthentication: - result = subprocess.run( - ("tailscale", "status", "--json", "--self"), - check=True, - capture_output=True, - text=True, - timeout=10, - ) - import json + from agent_comms.transport.tailnet_buses import TailnetBuses - status = json.loads(result.stdout) - dns_name = status["Self"]["DNSName"].rstrip(".") - user_id = str(status["Self"]["UserID"]) - owner_login = status["User"][user_id]["LoginName"] + me = TailnetBuses.this_machine() endpoint = TailnetBrowserEndpoint( - dns_name, https_port, OwnerOnlyDirectory.user_runtime() + me.dns_name, https_port, OwnerOnlyDirectory.user_runtime() ) - return cls(endpoint, owner_login) + return cls(endpoint, me.owner_login) def credential(self, request: web.Request) -> BrowserAccess: if request.headers.getall("Tailscale-User-Login", []) == [self.owner_login]: From 828294f9a3cfffcb3f6a88eb933634a4728826c3 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 14:43:01 -0500 Subject: [PATCH 16/16] history: a header drawn at the top edge is the stack's last line; the opening placeholder is a Page - ArrivalBurst.stack: with nothing pinned, a header is drawn at the top edge (the top row is a message's head or the gap before it). The first burst message starting at or below the top edge is that header; it becomes the overlay's last line, drawn once, so no earlier header is drawn over it (gaming-a-headers' overlap). Traced on a 5-message burst: tops 60/73/86/99/112 with the furthest scroll at 103. - QtOpeningSessionView inherits Page: the window asks every open view for external_transcript_changed, and the placeholder shown while a thread opens had none (batch-6 hold drive: AttributeError on a CLI-transcript change). - Dropped the cloud test that compared identical-by-construction header labels and scrolled to a position the window cannot reach. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/toad/client/history_changes.py | 16 ++++--- src/toad/qt/opening_view.py | 3 +- tests/textual/test_arrival_burst_stack.py | 55 ----------------------- 3 files changed, 12 insertions(+), 62 deletions(-) diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index c857a6bf2..018b953b0 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -171,15 +171,19 @@ def stack(self, window: PinsMessageHeader, pinned: PinnedHeader) -> StackedHeade return NO_STACK # The top row's own message by identity: messages from one sender to one destination in # the same second draw equal headers, and comparing headers left such a message out. - # When the top row IS that message's header (nothing pinned), the overlay would cover it: - # its header becomes the overlay's last line, drawn once, never an earlier one over it. + # Nothing pinned means a header is drawn at the top edge (the top row is a message's head, + # or the gap just before it, which the layout counts with the message above): the overlay + # would cover that header, so it becomes the overlay's last line, drawn once, and no + # earlier header is drawn over it. It is the first burst message starting at or below + # the top edge. top_line: tuple[Divider, ...] = () if not pinned.headers: - at_top = next((message for message in self.messages - if message.key.source == pinned.source), None) - if at_top is None: + covered = next((message for message in self.messages + if (top := window.message_top(message.key)) is not None + and top >= window.scroll_y), None) + if covered is None: return NO_STACK - top_line = (at_top.header,) + top_line = (covered.header,) above = [message for message in self.messages[:-1] if message.key.source != pinned.source and (top := window.message_top(message.key)) is not None and top < window.scroll_y] diff --git a/src/toad/qt/opening_view.py b/src/toad/qt/opening_view.py index 3d7137f61..7718684b1 100644 --- a/src/toad/qt/opening_view.py +++ b/src/toad/qt/opening_view.py @@ -21,9 +21,10 @@ from toad.qt.float_layer import QtPendingIndicator from toad.qt.lines import QtLineRenderer from toad.qt.metrics import UiGap +from toad.qt.page import Page -class QtOpeningSessionView(SessionScope, QWidget): +class QtOpeningSessionView(Page, SessionScope, QWidget): """The Qt placeholder a `ThreadOpening` mounts while async navigation runs. `session_navigation.new(identity, lambda: view, ...)` accepts any `SessionScope` diff --git a/tests/textual/test_arrival_burst_stack.py b/tests/textual/test_arrival_burst_stack.py index 74bb235a3..c95fe8f90 100644 --- a/tests/textual/test_arrival_burst_stack.py +++ b/tests/textual/test_arrival_burst_stack.py @@ -61,58 +61,3 @@ async def test_a_burst_stacks_the_earlier_headers_and_a_click_opens_one(workspac app.save_screenshot("burst-opened.svg", str(shots)) assert not window.arrival_burst.messages and not pin.stacked.keys assert not window.follows_tail - - -async def test_burst_stack_covers_visible_header_without_overlap(workspace, tmp_path): - """When a burst message's header is the viewport's top row (pinned.headers empty), - the overlay draws 'N new' + stacked earlier headers + that header as its last line, - covering the flow's copy so no other header sits on top of it.""" - workspace.thread("sender", "bstack", running=True) - comms = workspace.comms - for index in range(10): - comms.messaging.send("sender", "#bstack", f"fill {index}: " + "padding " * 6) - shots = Path(os.environ.get("BURST_SHOTS", tmp_path)) - async with workspace.app(size=(80, 30)) as ui: - app, pilot = ui.textual - await ui.open_channel("#bstack", actor="sender") - chat = app.screen.query_one(CommsChatView) - history, window = chat.message_history, chat.window - await ui.until(lambda: history.state.accepts_source_work, why="the channel's messages") - await ui.until(lambda: window.follows_tail, why="the reader on the tail") - - for index in range(BURST): - comms.messaging.send("sender", "#bstack", f"BURST {index}\n" + "\n".join( - f"line {row} of burst message {index}" for row in range(8))) - await refresh_chat(chat) - await ui.until_shows(f"BURST {BURST - 1}") - pin = window.sticky_header - await ui.until(lambda: pin.stacked.keys, why="the burst stacked", seconds=15) - - burst = window.arrival_burst.messages - assert len(burst) == BURST - latest = burst[-1] - top = window.message_top(latest.key) - assert top is not None, "latest burst message on screen" - - # Put the latest message's first row (Gap) at the viewport top. - # Its header divider is visible; pinned.headers is empty. - with window.layout_scroll(): - window.scroll_y = top - window.repin_header() - await pilot.pause() - app.save_screenshot("burst-header-at-top.svg", str(shots)) - - above = [m for m in burst[:-1] - if (t := window.message_top(m.key)) is not None and t < window.scroll_y] - assert above, "earlier burst heads are above the top row" - assert pin.display, "pin visible when burst heads are above" - assert pin.stacked.keys, "stacked keys present" - assert pin.headers[0].label == f"{BURST} new", pin.headers[:1] - # The latest header appears exactly once — as the overlay's last line, - # never A's header covering visible B. - latest_label = latest.header.label - overlay_labels = [h.label for h in pin.headers] - assert overlay_labels.count(latest_label) == 1, ( - f"latest header once in overlay, got {overlay_labels}") - assert overlay_labels[-1] == latest_label, ( - f"latest header is the overlay's last line, got {overlay_labels}")