diff --git a/docs/browser-serving.md b/docs/browser-serving.md index 59890f09e9..1b30c39fb4 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/app.py b/src/toad/app.py index 47339e85cf..5eda86e0ca 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 f78779b726..2042f86343 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 18d0184c1a..c7a9a4e99d 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) @@ -237,7 +240,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,26 +250,42 @@ 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") @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 5a570dd467..9c0731ae12 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/history_changes.py b/src/toad/client/history_changes.py index a379707a58..018b953b0f 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) @@ -157,18 +162,36 @@ 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.""" + 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:] + # 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. + # 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: + 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 = (covered.header,) 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 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))) @@ -233,9 +256,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() diff --git a/src/toad/client/local_connection.py b/src/toad/client/local_connection.py index 6101d512f8..8baa713132 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/prompt_composer.py b/src/toad/client/prompt_composer.py index d24a79a156..c52a825801 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/client/sidebar_filter.py b/src/toad/client/sidebar_filter.py index 5d708b0538..57454572f3 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 0000000000..95b135813e --- /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 6fd57bb1b6..86f9a22a19 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/history.py b/src/toad/qt/history.py index abbe1330d1..dc054c7ba2 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 @@ -208,20 +208,68 @@ 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) + 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 @@ -325,11 +373,15 @@ 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.""" 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, @@ -444,14 +496,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): @@ -604,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: @@ -778,19 +854,33 @@ 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) + # 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: return self.drawn = drawn - self.documents = tuple(window.rows.header_document(header, window.font(), width) for header in headers) - self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, not self.stacked.keys) + 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.resize(width, sum(int(document.size().height()) for document in self.documents)) self.move(window.viewport().mapTo(window, QPoint(x, 0))) self.raise_() @@ -1021,6 +1111,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.""" @@ -1327,9 +1419,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: @@ -1370,7 +1468,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() diff --git a/src/toad/qt/main.py b/src/toad/qt/main.py index f7a4f369f8..a3bf744fde 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/name_wave.py b/src/toad/qt/name_wave.py index 79801b124f..12c2dff770 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/opening_view.py b/src/toad/qt/opening_view.py index 3d7137f610..7718684b1d 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/src/toad/qt/thread_comms_panel.py b/src/toad/qt/thread_comms_panel.py index 295f78fa35..125823bdf8 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 b8c331e054..de123a2f02 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, @@ -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 @@ -997,11 +998,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 +1018,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 @@ -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. @@ -1773,6 +1776,10 @@ 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; 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) diff --git a/src/toad/web_server.py b/src/toad/web_server.py index 942484a884..68ef7d1e00 100644 --- a/src/toad/web_server.py +++ b/src/toad/web_server.py @@ -1,23 +1,68 @@ -"""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 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 +73,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 +218,129 @@ 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 LocalBrowserAuthentication: +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: + from agent_comms.transport.tailnet_buses import TailnetBuses + + me = TailnetBuses.this_machine() + endpoint = TailnetBrowserEndpoint( + me.dns_name, https_port, OwnerOnlyDirectory.user_runtime() + ) + return cls(endpoint, me.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(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 +354,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/src/toad/widgets/sidebar_tree.py b/src/toad/widgets/sidebar_tree.py index cb7165b381..5e48448998 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 0000000000..e789badaea --- /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() diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 2009ea4ffc..aa294d4a63 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 @@ -2832,8 +2833,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), diff --git a/tools/systemd/toad-serve.service b/tools/systemd/toad-serve.service index 78368e24ed..fe19cc19cb 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