diff --git a/src/toad/client/application.py b/src/toad/client/application.py index 751ca28f8..5a570dd46 100644 --- a/src/toad/client/application.py +++ b/src/toad/client/application.py @@ -343,7 +343,8 @@ def agent_processes(self) -> AgentProcesses: def sidebar_layout(self) -> SidebarLayout: """The one placement owner of this terminal's sidebars, kept in the settings file with every other setting, so an arrangement outlives the run in every frontend.""" - return SidebarLayout(self.saved_settings, TerminalOrigin.of()) + return SidebarLayout(self.saved_settings, TerminalOrigin.of(), + alone=lambda: self.selected_mode == WELCOME) def keep_settings(self) -> None: """A change meant for the next start (a sidebar moved, resized, folded) reaches the diff --git a/src/toad/client/application_actions.py b/src/toad/client/application_actions.py index 072011b9d..d5d2a42e2 100644 --- a/src/toad/client/application_actions.py +++ b/src/toad/client/application_actions.py @@ -261,10 +261,8 @@ class NewSessionAction(ApplicationAction): """Start this launch's session: its attached agent's, or a native thread.""" # The docstring is the text every menu and palette shows the reader. Both frontends fire - # this (Textual's `StartSessionButton` and Qt's Welcome `NewSessionButton`): the body - # lives on the ClientApplication so one owner answers the "new session" intent - # regardless of toolkit. The Textual welcome screen still binds its `n` key through its - # own `WelcomeStartSession` action, which forwards here. + # it from the comms sidebar's New Session row while no tab is shown + # (`NewSessionControl.action`), and Textual's `n` key there (`SoleNewSessionAction`). show = True async def apply(self, app: ClientApplication) -> None: @@ -380,13 +378,17 @@ async def apply(self, app: ClientApplication) -> None: class NewSessionControl: - """A control that starts a session: what it says and the action a press applies. - Textual's `NewSessionButton` (the Channels sidebar's row) and `StartSessionButton` (the - welcome's), Qt's `NewSessionRow` and `QtStartSessionButton` all inherit it. The sidebar's - starts a thread in the selected project; the welcome's starts this launch's session.""" + """The comms sidebar's first row, which starts a session: what it says and the action a + press applies. Textual's `NewSessionButton` and Qt's `NewSessionRow` inherit it. While no + tab is shown the sidebar holds the window where the welcome page stood, and the row starts + this launch's session as the welcome's button did (`NewSessionAction`: the attached agent's, + or a native thread); beside a tab it starts a thread in the selected project.""" label = "+ New Session" - action: type[ApplicationAction] = NewThreadAction + + @staticmethod + def action(app: ClientApplication) -> ApplicationAction: + return NewSessionAction() if app.sidebar_layout.alone else NewThreadAction() async def start_session(self, app: ClientApplication) -> None: - await self.action().apply(app) + await self.action(app).apply(app) diff --git a/src/toad/client/block_menu.py b/src/toad/client/block_menu.py index 2e3c4728b..5cf6ea2c5 100644 --- a/src/toad/client/block_menu.py +++ b/src/toad/client/block_menu.py @@ -15,7 +15,7 @@ from toad.client.input_modality import InputModality, KeyboardInput from toad.client.menu_entry import MenuEntry, strip_menu_markup from toad.keymap import KeymapCatalog -from toad.menus import MenuCommand +from toad.menus import MenuCommand, standard_commands if TYPE_CHECKING: from toad.preferences import ToadSettings @@ -28,6 +28,15 @@ class BlockMenu: input_modality: ClassVar[type[InputModality]] = KeyboardInput + @staticmethod + def block_commands(target: object, offered: Iterable[MenuCommand]) -> tuple[MenuCommand, ...]: + """A block's menu, declared once for both frontends: the family's commands that + apply to ``target`` (a Textual block cursor, a Qt history fragment; each answers + `allow_maximize`), then the block's own (``offered``: its `block_menu`). Textual's + `Menu` and Qt's `QtMenu` only draw it; a frontend that assembled its own list fails + `tests/model/test_menu_owners.py`.""" + return (*standard_commands(target), *offered) + @staticmethod def ordered(commands: Iterable[MenuCommand]) -> tuple[MenuCommand, ...]: """Commands with default keys first, each group in the order given.""" diff --git a/src/toad/client/bus_selection.py b/src/toad/client/bus_selection.py index b933a6549..1db3923e5 100644 --- a/src/toad/client/bus_selection.py +++ b/src/toad/client/bus_selection.py @@ -246,6 +246,9 @@ class BusListing: A plain parent: each frontend's widget brings its toolkit metaclass. """ + buses_title = "Buses" + """The title over the rows, wherever a listing draws one.""" + def picker_host(self) -> BusPickerHost: """The application this listing opens buses in.""" raise NotImplementedError diff --git a/src/toad/client/bus_submission.py b/src/toad/client/bus_submission.py index 0aa4111fa..765d843e4 100644 --- a/src/toad/client/bus_submission.py +++ b/src/toad/client/bus_submission.py @@ -181,6 +181,10 @@ async def send(self) -> None: ... def delivering(self) -> tuple[str, ...]: """The text this request still shows as submitting, or nothing once its destination has it.""" + def previewed(self) -> tuple[str, ...]: + """The text the delivery preview lists for this request: what is still submitting.""" + return self.delivering() + def settle(self) -> None: """A drawn message retires the requests it satisfies; an agent prompt is retired by its RPC.""" @@ -198,6 +202,11 @@ class SubmittingPhase(ABC): @abstractmethod def submitting(self, text: str) -> tuple[str, ...]: ... + def previewed(self, text: str) -> tuple[str, ...]: + """What the delivery preview lists for this submission: what is still submitting. + A phase whose message is neither submitting nor drawn yet keeps it listed.""" + return self.submitting(text) + class BusOutcome(SubmittingPhase): """Where a bus send stands: only a sent message can be drawn by its view.""" @@ -234,6 +243,13 @@ class SentMessage(DeliveryOutcome): def drawn_by(self, view: SubmissionView) -> bool: return view.draws_user_message(self.reference) + def previewed(self, text: str) -> tuple[str, ...]: + """Core has it and the history has not drawn it yet: the preview keeps it until the + execution settles on the draw, so a sent message is on screen at every instant (it + dropped out on Core's answer and showed nowhere until the history drew it — Tristan, + 2026-11-18: "there's a gap where I don't see the queue and I don't see the message").""" + return (text,) + async def settle_into(self, execution: BusSubmissionExecution) -> None: execution.outcome = self execution.owner.publish_pending() @@ -268,6 +284,9 @@ def delivering(self) -> tuple[str, ...]: destination is still shown, which is a different question.""" return self.outcome.submitting(self.submission.text) if self.current else () + def previewed(self) -> tuple[str, ...]: + return self.outcome.previewed(self.submission.text) if self.current else () + def retire_unsent(self) -> None: """A message to a view that changed before it left comes back as the draft.""" self.owner.view.delivery_refused("Message route changed; reopen this view", self.submission) @@ -380,9 +399,15 @@ def start_bus(self, submission: SubmittedText, destination: BusDestination): def delivering(self) -> tuple[str, ...]: return tuple(text for execution in self.active for text in execution.delivering()) + @property + def previewed(self) -> tuple[str, ...]: + """What the delivery preview lists: every request until the view draws it. Send now + reads `delivering` instead, since a message Core has cannot be sent again.""" + return tuple(text for execution in self.active for text in execution.previewed()) + @property def submitting(self) -> SubmittingTexts: - return SubmittingTexts(self.delivering) + return SubmittingTexts(self.previewed) @property def input_decision(self) -> InputDecision: diff --git a/src/toad/client/fragments.py b/src/toad/client/fragments.py index 2401c59c2..183dfddd5 100644 --- a/src/toad/client/fragments.py +++ b/src/toad/client/fragments.py @@ -234,6 +234,8 @@ class CursorRest: # The messages the cursor owns while the history draws them. rested: tuple[HistoryFragment, ...] = () + # A drawn message is never maximized (a Textual widget block may be, through its cursor). + allow_maximize: ClassVar[bool] = False @property def clipboard_text(self) -> str: diff --git a/src/toad/client/history_changes.py b/src/toad/client/history_changes.py index a7009d5ea..a379707a5 100644 --- a/src/toad/client/history_changes.py +++ b/src/toad/client/history_changes.py @@ -217,6 +217,8 @@ class PinsMessageHeader: `top_page` and `live_message_header` answer.""" sticky_header: HeaderPin + histories: set + """The pagers drawn in this window (`PagingWindow.histories`): each hears where it moved.""" arrival_burst: ArrivalBurst _restoring: bool pinned_scroll_y: float = 0.0 @@ -238,6 +240,8 @@ def repin_header(self) -> None: self.pinned_scroll_y = self.scroll_y pinned = self.top_message_header() self.sticky_header.pin(pinned, burst.stack(self, pinned) if burst.messages else NO_STACK) + for history in tuple(self.histories): + history.window_shown() def open_pinned(self, index: int) -> bool: """The reader chose the pin's `index`th header: a stacked one scrolls to its message, diff --git a/src/toad/client/history_pager.py b/src/toad/client/history_pager.py index d65d41d87..3dbf710df 100644 --- a/src/toad/client/history_pager.py +++ b/src/toad/client/history_pager.py @@ -314,6 +314,10 @@ class HistoryPager(ResumesSource): @abstractmethod def window(self) -> PagingWindow: ... + def window_shown(self) -> None: + """The window's shown rows changed (a scroll offset or a committed layout); a pager + that draws no bus messages has nothing to do with that.""" + @property @abstractmethod def can_draw_on_screen(self) -> bool: ... @@ -1206,6 +1210,15 @@ def required_presentations(self, screen) -> tuple[NativePresentation, ...]: class ConversationPager(HistoryPager): """A conversation's pager: it can replace its whole source with a newer reading of it.""" + view: object + """The conversation this pager draws, whose composer's submissions it settles.""" + + def window_shown(self) -> None: + """The window moved or laid out: a sent message it now shows retires from the delivery + preview on this frame. The view settles after reading a change, but a following window + scrolls to the new row one layout later, and nothing settled then.""" + self.view.submissions.settle() + async def show_newest(self, request: ReplacementViewportRequest, *, arrivals: tuple[HistoryFragment, ...] = (), publication_current: Callable[[], bool] = lambda: True) -> bool: @@ -1258,7 +1271,7 @@ def publish_core(self, event: object) -> None: class DrawsBusMessages: - """The fragments the loaded pages draw, and whether they include a bus message, scrolled into view or not.""" + """The fragments the loaded pages draw, and whether the window shows a bus message.""" pages: deque[DrawnPage] @@ -1267,4 +1280,14 @@ def fragments_in_range(self) -> tuple[HistoryFragment, ...]: return tuple(fragment for page in self.pages for fragment in page.prepared.fragments_in_range) def draws(self, reference: MessageReference) -> bool: - return any(fragment.draws(reference) for fragment in reversed(self.fragments_in_range)) + """Whether the window shows the bus message `reference` names: its first row is laid + out and starts above the window's bottom edge. A message only paged into range, or laid + out below the edge in the frame before a following window scrolls to it, is not shown + yet, so the delivery preview keeps it for that frame (it went for one frame before the + message came into view). `message_top` and `viewport_rows` are the window's unit.""" + window = self.window + for fragment in reversed(self.fragments_in_range): + if fragment.draws(reference): + top = window.message_top(fragment.key) + return top is not None and top < window.scroll_y + window.viewport_rows + return False diff --git a/src/toad/client/message_files.py b/src/toad/client/message_files.py index 50f57cbfd..d9030a0d7 100644 --- a/src/toad/client/message_files.py +++ b/src/toad/client/message_files.py @@ -39,8 +39,8 @@ def open(cls, composer: MessagePromptComposer) -> None: ... class WindowFilePicker(TitledChoice, FilePicker): - """The platform's file dialog. A phone shows its own file picker, which reaches the - phone's storage and its cloud drives.""" + """The platform's file dialog. A phone shows its own chooser: the apps that give a file + (its storage, photos and cloud drives) and the camera.""" title = "File dialog" diff --git a/src/toad/client/reader_position.py b/src/toad/client/reader_position.py index ece848820..5ee8614dc 100644 --- a/src/toad/client/reader_position.py +++ b/src/toad/client/reader_position.py @@ -96,9 +96,6 @@ def row_of(self, item) -> int: ... @abstractmethod def drawn_pages(self) -> Iterator[ReaderPage]: ... - @abstractmethod - def anchor(self) -> None: ... - @abstractmethod def release_anchor(self) -> None: ... diff --git a/src/toad/client/sidebar_filter.py b/src/toad/client/sidebar_filter.py index 425d12ecd..5d708b053 100644 --- a/src/toad/client/sidebar_filter.py +++ b/src/toad/client/sidebar_filter.py @@ -6,7 +6,7 @@ two frontends disagreed by construction. This class is the single owner of the 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 `QtChannelListing.keep` / `QtThreadListing.keep`) +`SidebarGroup.sync_members`, Qt's `Sidebar.draw_lines`) reads through `matches` instead of comparing text itself. A new frontend never reimplements the match rule; it hands the filter a row name and asks. diff --git a/src/toad/client/sidebar_lines.py b/src/toad/client/sidebar_lines.py index 70e7afb0d..0d096c72b 100644 --- a/src/toad/client/sidebar_lines.py +++ b/src/toad/client/sidebar_lines.py @@ -7,8 +7,13 @@ from __future__ import annotations +from collections.abc import Callable from typing import ClassVar +from toad.client.menu_entry import MenuEntry +from toad.client.relationship_row_menu import menu_entries_for_row +from toad.command_catalog import CommandCatalog + class DetailedLine: """A line of two rows: its title after its status prefix (the unread badge), then its @@ -55,10 +60,10 @@ def members_toggled(self) -> None: class WelcomeSectionLine(MemberGroupLine): - """A welcome section: it opens as the shared sidebar state says - (`SidebarState.welcome_section_open`) and records what the reader leaves it as, so it - stays put however often the welcome is drawn again. Textual's `WelcomeSection` and Qt's - `OpenSection`.""" + """A titled section of rows that are not the sidebar model's: it opens as the shared + sidebar state says (`SidebarState.welcome_section_open`) and records what the reader + leaves it as, so it stays put however often it is drawn again. Qt's `OpenSection` (the + buses, under the sidebar's rows while it holds the window, and in the bus switcher).""" @property def section_title(self) -> str: @@ -78,14 +83,14 @@ def members_toggled(self) -> None: class SidebarStatusLine(DetailedLine): """The sidebar's status: an observation status (`Connecting…`, `Behind`) or why the bus could not be read, its first line as the title and the rest as the detail under it. - Textual's `SidebarStatus`, Qt's `StatusSection` and `UnavailableSection`, and the - failed sidebar state's text all read it here.""" + Textual's `SidebarStatus`, Qt's `StatusSection`, and the failed sidebar state's text all + read it here.""" key: ClassVar[str] = "__status__" @staticmethod def unavailable_text(error: BaseException) -> str: - """What a sidebar or welcome says while the bus cannot be read: one persistent state, + """What a sidebar says while the bus cannot be read: one persistent state, the same however many reopen attempts (connection.ObservationRetry) fail behind it.""" return f"Comms unavailable; reconnecting\n{error}" @@ -99,7 +104,13 @@ def status_rows(text: str) -> tuple[str, str]: class TargetLine: """A line that opens a navigation target (a channel or a thread): it is keyed by the target's name and opens its members as the target says by default. Textual's - `CommsRow` and Qt's `ConversationRow`.""" + `CommsRow` and Qt's `ConversationRow`. + + Its menu is declared here and nowhere else: `menu_entries` is what a right-click or a + held finger offers in every frontend, and each toolkit only draws the entries + (Textual's `ActionMenu.offer`, Qt's menu panel). A toolkit line that defined its own + `menu_entries`, or built a menu by calling the owners below, fails + `tests/model/test_menu_owners.py`.""" target: object @@ -110,6 +121,47 @@ def target_name(self) -> str: def opens_expanded(self) -> bool: return self.target.expanded_by_default + @property + def menu_tree(self) -> LineMenuTree: + """The tree the line is drawn in, which supplies the context its commands run in.""" + raise NotImplementedError + + async def menu_entries(self) -> tuple[MenuEntry, ...]: + """The commands the line's target applies, in its tree's context.""" + return await CommandCatalog.pointer_menu(self.menu_tree.row_menu_context(self)) + + +class LineMenuTree: + """A tree of `TargetLine`s: the context a line's commands run in, and how a Comms + relationship opens. Textual's sidebar trees and Qt's `ConversationRows` and + `QtThreadCommsPanel` answer it.""" + + def row_menu_context(self, line: TargetLine): + """The command context for `line`'s target in this tree.""" + raise NotImplementedError + + def relationship_opener(self, line: RelationshipLine) -> Callable[[], object]: + """What Open runs for a relationship line, captured when the menu opens.""" + raise NotImplementedError + + def copy_name(self, name: str) -> None: + raise NotImplementedError + + +class RelationshipLine(TargetLine): + """A Comms relationship (Textual's `RelationshipRow`, Qt's `QtRelationshipItem`): its + menu is Open while the relationship is available, and Copy name.""" + + available: bool + + async def menu_entries(self) -> tuple[MenuEntry, ...]: + tree = self.menu_tree + return menu_entries_for_row( + target_name=self.target_name, + copy=tree.copy_name, + open_callback=tree.relationship_opener(self) if self.available else None, + ) + class HeaderLine: """A group's header line: its title, elided into the room the other stretches leave; diff --git a/src/toad/client/welcome.py b/src/toad/client/welcome.py index b901878cb..1fcd09453 100644 --- a/src/toad/client/welcome.py +++ b/src/toad/client/welcome.py @@ -1,104 +1,16 @@ -"""What Toad's welcome shows, for every frontend: its banner, and which of the sidebar -model's rows each section lists under which title. Each frontend draws them.""" +"""The welcome's location line, for every frontend: the comms sidebar draws it under Toad's +banner while it holds the window (no tab shown).""" from __future__ import annotations -from dataclasses import dataclass -from typing import ClassVar - -from agent_comms.ui_model.sidebar import ChannelRowModel, SidebarModel - -from toad.client.sidebar_lines import SidebarStatusLine -from toad.constants import ALL_COMMS_TARGET -from toad.setting_choices import UnreadCount -from toad.sidebar_rows import ChannelLineText - - -class WelcomeListing: - """Some of the sidebar model's rows, under a title. A plain parent: each frontend's - section composes it with its own widget base and metaclass.""" - - TITLE: ClassVar[str] = "" - LIMIT: ClassVar[int] = 8 - - def keys(self, model: SidebarModel) -> tuple[str, ...]: - raise NotImplementedError - - def listed(self, model: SidebarModel) -> tuple[str, ...]: - return self.keys(model)[: self.LIMIT] - - -class ChannelListing(WelcomeListing): - """The channels, in the order chosen for the sidebar.""" - - TITLE = "Channels" - - def keys(self, model: SidebarModel) -> tuple[str, ...]: - return tuple(model.channels.rows) - - @staticmethod - def line_text(channel: ChannelRowModel, counts: type[UnreadCount]) -> ChannelLineText: - """A channel on the welcome: its name with the unread badge after it, and no line - under it; the sidebar's channel line carries the summary.""" - badge = counts.badge(channel.unread) - return ChannelLineText("", f"{channel.label()} {badge}" if badge else channel.label(), "", - channel.tooltip()) - - -class ThreadListing(WelcomeListing): - """The threads of the all-comms channel: the active ones first, then the rest, each in - the order chosen for the channel. The welcome lists only the first few, and on a bus of - seventy stopped threads in creation order the one thread working now fell past them.""" - - TITLE = "Threads" - - def keys(self, model: SidebarModel) -> tuple[str, ...]: - listed = model.channels.rows.get(ALL_COMMS_TARGET) - members = tuple( - name - for name in (listed.members if listed is not None else ()) - if name in model.threads.rows - ) - return tuple(sorted(members, key=lambda name: not model.threads.rows[name].active)) - class WelcomeLocation: - """The welcome's location line: the attached agent's prefix, then where the welcome - works. Textual's names the project it was started in; a remote client (Qt) names the - bus connection it reads, its own launch directory saying nothing about that Core.""" + """The location line: the attached agent's prefix, then where the window works. + Textual's names the project it was started in; a remote client (Qt) names the bus + connection it reads, its own launch directory saying nothing about that Core.""" def location(self, app) -> str: raise NotImplementedError def location_line(self, app) -> str: return f"{app.agent_binding.welcome_prefix}{self.location(app)}" - - -class WelcomeContent: - """What the welcome lists above its buses for what the bus last answered: nothing until - it answers. A plain parent; the welcome draws each part through its own hooks - (`list_section`, `say_unavailable`).""" - - def draw(self, welcome, lines) -> None: - """Nothing has answered yet.""" - - -@dataclass(frozen=True) -class ListedModel(WelcomeContent): - """The bus answered: each welcome listing (channels, then threads) under its title.""" - - model: SidebarModel - - def draw(self, welcome, lines) -> None: - for listing in welcome.welcome_listings: - welcome.list_section(lines, listing, self.model) - - -@dataclass(frozen=True) -class ListedFailure(WelcomeContent): - """The bus could not be read: say why (`SidebarStatusLine.unavailable_text`).""" - - observed: object - - def draw(self, welcome, lines) -> None: - welcome.say_unavailable(lines, SidebarStatusLine.unavailable_text(self.observed.error)) diff --git a/src/toad/command_catalog.py b/src/toad/command_catalog.py index e68fa7c2b..4021fa4dd 100644 --- a/src/toad/command_catalog.py +++ b/src/toad/command_catalog.py @@ -2,10 +2,13 @@ from dataclasses import dataclass from collections.abc import Awaitable, Sequence +from functools import partial from agent_comms.errors import UnregisteredThreadError from formbridge.operations import ExclusiveKind, OperationKind -from toad.client.commands import CommandContextChanged, CommandRefused, ConversationCommands, LocalCommand +from toad.client.commands import (CommandContextChanged, CommandRefused, ConversationCommands, LocalCommand, + ViewLocalCommand) +from toad.client.menu_entry import MenuEntry from toad.slash_command import AgentAdvertisedCommand, CommandPresentation, SlashCommand from toad.target_commands import TargetContext, ThreadCommand @@ -65,6 +68,15 @@ def joined(cls, commands: dict[str, CommandPresentation], local: type[LocalComma target, ) + @classmethod + async def pointer_menu(cls, context: TargetContext) -> tuple[MenuEntry, ...]: + """What a right-click or a held finger on a channel or thread offers, in every + frontend: the commands its target context applies, each run in that context. + Textual's sidebar rows show these in an `ActionMenu`, Qt's in its menu panel.""" + choices = (await cls.read(context.app, (), context.acquired(), ViewLocalCommand)).target_choices + return tuple(MenuEntry(command.label(context), partial(context.execute_command, command)) + for command in choices) + def recognizes(self, text: str) -> bool: """Whether typed text starts with one of these commands.""" name = text.partition(" ")[0] @@ -73,11 +85,16 @@ def recognizes(self, text: str) -> bool: def command_named(self, name: str) -> SlashCommand: return next(command for command in self.commands if command.command == name) + @staticmethod + def may_name_command(text: str) -> bool: + """Whether typed text can name a command at all; anything else is a message.""" + return text.startswith("/") + @classmethod async def execute(cls, text: str, conversation: ConversationCommands) -> bool: """Run typed text as the conversation's command; False when it names none, so the text goes on as a message. A recognized command never falls through as text.""" - if not text.startswith("/"): + if not cls.may_name_command(text): return False try: catalog = await conversation.read_command_catalog() diff --git a/src/toad/conversation_submission.py b/src/toad/conversation_submission.py index 0d8ddfdb7..14e158a15 100644 --- a/src/toad/conversation_submission.py +++ b/src/toad/conversation_submission.py @@ -4,6 +4,7 @@ import asyncio from abc import abstractmethod +from collections.abc import Awaitable, Callable from dataclasses import dataclass from functools import partial from typing import ClassVar @@ -45,6 +46,11 @@ def matches(cls, event: UserInputSubmitted, owner: ConversationSubmissions): ... @abstractmethod async def execute(self, owner: ConversationSubmissions): ... + def started(self, owner: ConversationSubmissions) -> Callable[[], Awaitable[object]]: + """Take this submission now and return the work still to do. Most kinds do all of it + later; a message is listed now (`AgentInputSubmission.started`).""" + return partial(self.execute, owner) + @classmethod def from_event(cls, event: UserInputSubmitted, owner: ConversationSubmissions): kind = next( @@ -119,6 +125,14 @@ async def feedback(self, execution: SubmissionExecution): async def execute(self, owner: ConversationSubmissions): return await owner.begin(self).prepare() + def started(self, owner: ConversationSubmissions) -> Callable[[], Awaitable[object]]: + """Listed in the delivery preview in the call that takes it from the composer: the + composer's cleared editor and the message's preview row are one frame, never an empty + one between them (it was listed a worker turn later, after the clear was painted).""" + start = owner.begin(self) + owner.publish_pending() + return start.prepare + class OrdinaryInputSubmission(AgentInputSubmission): @classmethod @@ -262,6 +276,14 @@ async def submit(self, event: UserInputSubmitted): return return await InputSubmission.from_event(event, self).execute(self) + def received(self, event: UserInputSubmitted) -> Callable[[], Awaitable[object]]: + """What the composer handed over, taken in this call; returns the work still to do. + Text that may name a command waits for the catalog first, so it runs as `submit`; a + message is listed now (`InputSubmission.started`).""" + if not event.shell and CommandCatalog.may_name_command(event.body.strip()): + return partial(self.submit, event) + return InputSubmission.from_event(event, self).started(self) + def accepts_failure(self, message: CoreEventMessage): return self.view.agent_binding.accepts_failed_input(message) diff --git a/src/toad/history_jump.py b/src/toad/history_jump.py index aae0d2c00..3ef5ceb3d 100644 --- a/src/toad/history_jump.py +++ b/src/toad/history_jump.py @@ -89,6 +89,38 @@ def respond_to_scroll(self, position: float) -> None: self.tail_follow_changed() +class FollowsTail(JumpsToLatest): + """The one place a history window's reader joins or leaves its tail. + + Joining or leaving is one change of the reader's follow intent: it counts as a reader + move (`scroll_revision`, unless the window is moving itself), the window applies it in its + toolkit (`apply_anchor`), and the jump bar shows or hides from the result. Each window + lists this before its toolkit's scroll base, so this `anchor` answers in both frontends + ahead of Textual's own `Widget.anchor`, and a window supplies only `apply_anchor`. + + A subclass that defines `anchor` again is refused when its class is created: Qt's window + once carried its own copy without the last step, so its back-to-bottom bar stayed up + after a jump until the reader scrolled again (Tristan, Android, 2026-11-18).""" + + def __init_subclass__(cls, **kwargs) -> None: + super().__init_subclass__(**kwargs) + if "anchor" in vars(cls): + raise TypeError(f"{cls.__qualname__} redefines FollowsTail.anchor; " + "a window supplies apply_anchor, its toolkit's own move, instead") + + def anchor(self, anchor: bool = True) -> None: + changed = self.follows_tail != anchor + if not self._restoring and changed: + self.scroll_revision += 1 + self.apply_anchor(anchor) + if changed: + self.tail_follow_changed() + + @abstractmethod + def apply_anchor(self, anchor: bool) -> None: + """Join (`anchor`) or leave the tail in this toolkit, without counting or showing it.""" + + class ReaderWindow(JumpsToLatest): """A history window the reader keys move: a page either way, or back to the latest (`reader_actions`). Textual's `HistoryWindow` and Qt's `QtHistoryWindow` both list it.""" diff --git a/src/toad/menus.py b/src/toad/menus.py index a0926ae93..60d7e3c1a 100644 --- a/src/toad/menus.py +++ b/src/toad/menus.py @@ -167,7 +167,7 @@ class MaximizeBlockCommand(KeyedMenuCommand): @classmethod def offered_for(cls, target: object) -> bool: - return bool(getattr(target, "allow_maximize", False)) + return bool(target.allow_maximize) def apply(self, conversation: MenuConversation) -> None: conversation.maximize_block() diff --git a/src/toad/navigation_context.py b/src/toad/navigation_context.py index 65cebdc15..585eb435b 100644 --- a/src/toad/navigation_context.py +++ b/src/toad/navigation_context.py @@ -100,6 +100,17 @@ async def open_sidebar_target(self, target: NavigationDestination) -> None: self.app.show_info("Nothing opens from this view", "Navigation") +class HomeNavigation(NavigationOwner): + """Home (the welcome, while no tab is open) navigates as the reader at home: the + welcome's mode, its project and the reader's own thread. Textual's `WelcomeScreen` and + Qt's `QtWelcomeOrigin`.""" + + @property + def navigation_context(self) -> NavigationContext: + from toad.constants import WELCOME + return NavigationContext(self.app, WELCOME, self.project_path, self.thread_identity.thread_name()) + + class ThreadViewNavigation: """A view showing one thread navigates as that thread: its target is the thread, and what it opens attaches to the view's own tab, in its project, acting as the thread. diff --git a/src/toad/preferences.py b/src/toad/preferences.py index cde83eba0..33da8bcc9 100644 --- a/src/toad/preferences.py +++ b/src/toad/preferences.py @@ -94,7 +94,7 @@ class InputSettings(SettingsDeclaration, scopes=(ConversationSettingsOwner,)): file_picker: Annotated[ type[FilePicker], FieldLabel("File picker"), FamilyChoices(FilePicker), WireName("file-picker"), ] = WindowFilePicker - """What attaching a file to a message opens: the file dialog (on a phone, its own file picker) or the project path search.""" + """What attaching a file to a message opens: the file dialog (on a phone, Android's chooser: files, photos or the camera) or the project path search.""" delivery_preview: Annotated[ bool, FieldLabel("Show delivery preview?"), PromptSettingEffects.apply_delivery_preview, diff --git a/src/toad/qt/banner.py b/src/toad/qt/banner.py index 44bf4358b..a5ba7f62c 100644 --- a/src/toad/qt/banner.py +++ b/src/toad/qt/banner.py @@ -19,7 +19,7 @@ class Banner(WelcomeBanner, QWidget): Mono (`toad.qt.glyph_fonts`), which holds the blocks and box drawing; Android's own monospace font has neither. It takes the width and never asks for one.""" - LINES = WelcomeBanner.TEXT.splitlines() # the shared banner, as Textual's WelcomeTitle draws it + LINES = WelcomeBanner.TEXT.splitlines() # the shared banner, as Textual's SidebarBanner draws it COLUMNS = max(map(len, LINES)) def __init__(self, colour: str) -> None: diff --git a/src/toad/qt/bus_switcher.py b/src/toad/qt/bus_switcher.py index 8f0cc2998..ff9be0634 100644 --- a/src/toad/qt/bus_switcher.py +++ b/src/toad/qt/bus_switcher.py @@ -115,7 +115,7 @@ def show_rows(self, rows: tuple[PickerRow, ...]) -> None: KeptLines = self._KeptLines OpenSection = self._OpenSection def draw(top: "KeptLines") -> None: - with top.group(OpenSection("Buses")) as section: + with top.group(OpenSection(self.buses_title)) as section: for choice in rows: section.keep(BusRow(choice)) self._tree.redraw(draw) diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index 2b6058258..85a039536 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -547,6 +547,10 @@ def send(self, action: SubmitInputAction = SubmitAction()) -> None: self.dismissed_text = "" self.failure.hide() self.host.submit(TypedText(text, self.take_files()), action) + # The view listed the message in that call: draw its preview row with the cleared + # editor, in one frame, rather than on the next turn. + if self.queue_sync_pending: + self._sync_queue() # Toolkit-neutral action-family contract: Textual's Prompt inherits Submits + # DismissibleControl from widget_actions.py; the mixin lift itself is fork diff --git a/src/toad/qt/conversation.py b/src/toad/qt/conversation.py index 20da8dc3d..ed2d06cd4 100644 --- a/src/toad/qt/conversation.py +++ b/src/toad/qt/conversation.py @@ -118,6 +118,11 @@ class QtConversation( (`messages`), the flash (`feedback`), the sweep (`agent_activity`), its composer and the observing rows under the transcript (`activity`).""" + def workspace_navigation_owner(self, views): + """A conversation tab navigates as its view (`ConversationView` and `QtThreadView` + are `NavigationOwner`s, as Textual's views are).""" + return self + agent_binding: ObservedField[AgentConnection] = ObservedField(NoAgentConnection()) thread_presentation: ThreadPresentation = NoThreadPresentation() """The agent thread's latest settled presentation.""" @@ -330,7 +335,7 @@ def submit(self, text: TypedText, action: SubmitInputAction) -> None: `UserInputSubmitted` reaches `Conversation.submissions.submit`. No Qt view runs a shell, so typed input is never a shell command.""" event = action.submission_event(text.text, False, text.files) - self.run_worker(partial(self.submissions.submit, event), group="submit", exclusive=False) + self.run_worker(self.submissions.received(event), group="submit", exclusive=False) def update_slash_commands(self) -> None: """The composer asks for the commands it offers after a /.""" diff --git a/src/toad/qt/file_pickers.py b/src/toad/qt/file_pickers.py index 75a8c2091..03e4c9aed 100644 --- a/src/toad/qt/file_pickers.py +++ b/src/toad/qt/file_pickers.py @@ -1,8 +1,10 @@ """Qt's file pickers for a message composer: the file dialog and the project path search. -The dialog is Qt's own QFileDialog. On Android, Qt answers it with the system's document -picker (the Storage Access Framework), which returns a `content://` URL that QFile reads; -on a desktop it is the platform's dialog. The path search ranks the project's paths through +The dialog is Qt's own QFileDialog. On a desktop it is Qt's themed dialog (pyqt-reactive's +theme selects it). On Android it is native: Qt asks the activity for a document, and the +APK's activity offers Android's chooser in its place - the apps that give a file (Files, +Photos, Drive) and the camera (tools/android/keepalive AttachChooser). Either answer comes +back as a `content://` URL that QFile reads. The path search ranks the project's paths through the shared ProjectPaths, as Textual's @ completion does. Both hand the bytes they read to `MessagePromptComposer.file_picked`, which decides what is attached. """ diff --git a/src/toad/qt/history.py b/src/toad/qt/history.py index 175a6ad88..4169eff43 100644 --- a/src/toad/qt/history.py +++ b/src/toad/qt/history.py @@ -68,7 +68,7 @@ ToolTranscriptFragment, TranscriptFragment, ) -from toad.history_jump import JumpsToLatest, ReaderWindow +from toad.history_jump import FollowsTail, JumpsToLatest, ReaderWindow from toad.widget_view import WorkspaceHosted from toad.workspace_frame import WorkspaceFrame from toad.markdown_links import LinkContext @@ -819,7 +819,7 @@ def show_jump(self, shown: bool) -> None: self.setVisible(shown) -class QtHistoryWindow(ReaderWindow, WorkspaceHosted, VirtualRowView, +class QtHistoryWindow(FollowsTail, ReaderWindow, WorkspaceHosted, VirtualRowView, ReaderPlacement, PagingWindow, OpensLineLinks, PinsMessageHeader): """The reader window of one Qt conversation: pyqt-reactive's virtual rows of the history's shown fragments, scrolled by pixel. It answers the shared pager's window @@ -1178,10 +1178,7 @@ def fragment_location(self, key) -> FragmentLocation: def follows_tail(self) -> bool: return self._anchored - def anchor(self, anchor: bool = True) -> None: - changed = self._anchored != anchor - if not self._restoring and changed: - self.scroll_revision += 1 + def apply_anchor(self, anchor: bool) -> None: self._anchored = anchor if anchor: self.reader_position = self.reader_position.joined_tail() diff --git a/src/toad/qt/page.py b/src/toad/qt/page.py index 21c833604..6aac127c0 100644 --- a/src/toad/qt/page.py +++ b/src/toad/qt/page.py @@ -14,6 +14,8 @@ from collections.abc import Callable from typing import TYPE_CHECKING +from toad.navigation_context import NavigationOwner, NoNavigationOwner + if TYPE_CHECKING: from toad.client.tab_identity.kinds import CommsTab from toad.qt.window import QtToadApp @@ -27,6 +29,11 @@ class Page: def reload(self) -> None: """A page fed by its own subscription has nothing to read again.""" + def workspace_navigation_owner(self, views) -> NavigationOwner: + """What the workspace navigates through while this page is selected + (`QtWorkspaceViews.navigation_owner`): nothing, for a page that does not navigate.""" + return NoNavigationOwner(views.app) + def external_transcript_changed(self) -> None: """A page showing no thread's transcript has no CLI items to read.""" diff --git a/src/toad/qt/side_bar.py b/src/toad/qt/side_bar.py index 37be9719c..cd18df2d7 100644 --- a/src/toad/qt/side_bar.py +++ b/src/toad/qt/side_bar.py @@ -332,7 +332,8 @@ def fold(self, collapsed: bool) -> None: self.lay_out() def toggle_controls(self) -> None: - self.controls.setVisible(self.controls.isHidden()) + self.controls_wanted = not self.controls_wanted + self.controls.setVisible(self.controls_wanted and not self.holds_alone) def present(self) -> None: """Draw the strip, the slider and the placement actions from the one layout.""" @@ -349,14 +350,19 @@ def present(self) -> None: self._grid.addWidget(action, index // 2, index % 2) folded = self.collapsed self.content_stack.setVisible(not folded) - self.handle.setVisible(not folded) + # Holding the window alone there is nothing beside the bar to fold it for or to + # grip: only its content shows. + alone = self.holds_alone + self.toggle.setVisible(not alone) + self.handle.setVisible(not folded and not alone) + self.controls.setVisible(self.controls_wanted and not alone) def place(self, rect: QRect, cells: Size) -> None: """Take ``rect`` (``cells`` in the chrome's grid) and lay the parts inside it.""" self.setGeometry(rect) self._cells = cells local = QRect(0, 0, rect.width(), rect.height()) - parts = self.surface_parts(self.placement.side, cells) + parts = self.surface_parts(cells) self.toggle.setGeometry(cells_to_pixels(parts.toggle, cells, local)) self.handle.setGeometry(cells_to_pixels(parts.handle, cells, local)) self.content_stack.setGeometry(self._held_content(cells_to_pixels(parts.content, cells, local))) diff --git a/src/toad/qt/thread_comms_panel.py b/src/toad/qt/thread_comms_panel.py index 573b9bf1f..295f78fa3 100644 --- a/src/toad/qt/thread_comms_panel.py +++ b/src/toad/qt/thread_comms_panel.py @@ -44,7 +44,8 @@ from toad.client.sort_control import ThreadSortForm from toad.thread_identity import SessionIdentity from toad.qt.metrics import UiGap -from toad.client.relationship_row_menu import entry_target, menu_entries_for_row +from toad.client.relationship_row_menu import entry_target +from toad.client.sidebar_lines import LineMenuTree, RelationshipLine # The relationship an entry row shows; a group's own line keeps its group in UserRole. _ENTRY = Qt.ItemDataRole.UserRole.value + 1 @@ -62,7 +63,21 @@ async def write_picked(self, order: type[ThreadSort]) -> None: await self._panel.write_order(order) -class QtThreadCommsPanel(RelationshipPanel, SessionPanel, QWidget, metaclass=PyQtWidgetMeta): +class QtRelationshipItem(RelationshipLine, QTreeWidgetItem): + """One relationship in the Comms panel, as Textual's `RelationshipRow`: its menu is the + shared `RelationshipLine.menu_entries` (Open while available, Copy name).""" + + def __init__(self, panel: QtThreadCommsPanel, parent: QTreeWidgetItem, group, entry: RelationshipEntry) -> None: + super().__init__(parent, [entry.target if entry.available else f"{entry.target} (unavailable)"]) + self.panel, self.group, self.entry = panel, group, entry + self.target, self.available = entry_target(entry), entry.available + + @property + def menu_tree(self) -> QtThreadCommsPanel: + return self.panel + + +class QtThreadCommsPanel(LineMenuTree, RelationshipPanel, SessionPanel, QWidget, metaclass=PyQtWidgetMeta): spec_key: ClassVar[str] = "comms" """Which `ThreadSidebarPanelSpec.key` this widget renders — mirrors the TUI `SessionPanel.spec_key` convention so both frontends share one identity per panel.""" @@ -197,8 +212,7 @@ def _apply(self, snapshot: ThreadCommsSnapshot) -> None: self._add_entry_item(top, entry) def _add_entry_item(self, parent_item: QTreeWidgetItem, entry: RelationshipEntry) -> None: - display = entry.target if entry.available else f"{entry.target} (unavailable)" - row = QTreeWidgetItem(parent_item, [display]) + row = QtRelationshipItem(self, parent_item, parent_item.data(0, Qt.ItemDataRole.UserRole), entry) if entry.detail: row.setToolTip(0, entry.detail) row.setData(0, _ENTRY, entry) @@ -215,18 +229,25 @@ def _item_clicked(self, item: QTreeWidgetItem) -> None: asyncio.ensure_future(self._open_current(*shown)) def _offer_row_menu(self, point) -> None: - """Open / Copy for the row under ``point`` (viewport coordinates), from the shared - `menu_entries_for_row`, in the window's menu panel.""" - shown = self._row_entry(self._tree.itemAt(point)) - app = self._app() - if shown is None or app is None: + """The relationship's own menu (`RelationshipLine.menu_entries`) for the row under + ``point`` (viewport coordinates), in the window's menu panel; a group line has none.""" + item = self._tree.itemAt(point) + if self._row_entry(item) is None or self._app() is None: return - group, entry = shown - app.offer_entries(menu_entries_for_row( - target_name=entry.target, - copy=app.copy_to_clipboard, - open_callback=(lambda: asyncio.ensure_future(self._open_current(group, entry))) if entry.available else None, - )) + asyncio.ensure_future(self._offer_read(item)) + + async def _offer_read(self, item: QtRelationshipItem) -> None: + entries = await item.menu_entries() + if (app := self._app()) is not None: + app.offer_entries(entries) + + def relationship_opener(self, line: QtRelationshipItem): + """Open reads the list again first (`_open_current`), as Textual's opener does.""" + return lambda: asyncio.ensure_future(self._open_current(line.group, line.entry)) + + def copy_name(self, name: str) -> None: + if (app := self._app()) is not None: + app.copy_to_clipboard(name) async def _open_current(self, group, entry: RelationshipEntry) -> None: """Open the relationship as it stands now: the list read again, and a relationship diff --git a/src/toad/qt/thread_view.py b/src/toad/qt/thread_view.py index 86adc2814..6757ba23b 100644 --- a/src/toad/qt/thread_view.py +++ b/src/toad/qt/thread_view.py @@ -24,7 +24,7 @@ from toad.client.draft_fragments import DRAFT_FRAGMENTS from toad.client.history_rows_view import HistoryRowsBlocks, settled from toad.client.transcript_history_contract import TranscriptHistoryContract -from toad.navigation_context import ThreadViewNavigation +from toad.navigation_context import NavigationOwner, ThreadViewNavigation from toad.qt.bound_view import QtBoundViewHost from toad.qt.composer import Composer from toad.qt.conversation import QtConversation @@ -46,6 +46,7 @@ class QtThreadView( ThreadViewNavigation, HistoryRowsBlocks, QtBoundViewHost, + NavigationOwner, metaclass=PyQtWidgetMeta, ): """A `QtConversation` showing one bound thread's transcript. diff --git a/src/toad/qt/window.py b/src/toad/qt/window.py index 920d485a5..e72dfb129 100644 --- a/src/toad/qt/window.py +++ b/src/toad/qt/window.py @@ -17,6 +17,7 @@ from functools import partial from pathlib import Path +from agent_comms.messaging.channel_targets import ChannelSelection, NoChannel, OneChannel from agent_comms.messaging.message_reference import MessageReference from agent_comms.projects.checkouts import Checkout from agent_comms.registry.thread_identity import ThreadIncarnation @@ -86,12 +87,11 @@ from toad.client.platform import host from toad.client.line_blocks import LineLink, MutedRole from toad.qt.banner import Banner -from toad.client.welcome import ( - ChannelListing, ListedFailure, ListedModel, ThreadListing, WelcomeContent, WelcomeLocation, -) +from toad.client.welcome import WelcomeLocation from toad.client.name_wave import NameWave from toad.client.sidebar_lines import ( - BusChoiceLine, DetailedLine, HeaderLine, MemberGroupLine, RowTree, SidebarStatusLine, TargetLine, WelcomeSectionLine, + BusChoiceLine, DetailedLine, HeaderLine, LineMenuTree, MemberGroupLine, RowTree, SidebarStatusLine, TargetLine, + WelcomeSectionLine, ) from toad.keyed_rows import KeyedRows from toad.setting_choices import UnreadCount @@ -102,6 +102,7 @@ from toad.sidebar_changes import SidebarChange from toad.sidebar_contracts import ( ChannelGroupRows, + FindsOpenViews, GroupedSidebar, NavigationRefresh, ) @@ -112,7 +113,8 @@ from toad.core import session_requests from toad.core.events import CoordinationObserved, ExternalTranscriptChanged, TabHistoryChanged from toad.launch_binding import AgentBinding, NoAgent -from toad.navigation_context import NoNavigationOwner +from toad.navigation_context import HomeNavigation, NavigationOwner +from toad.session_navigation import TabElement from toad.client.session_scope import HomeSessionOrigin from toad.client.sidebar_filter import SidebarFilter from toad.client.sidebar_panels import PanelSpec @@ -126,11 +128,9 @@ from toad.qt.composer import ChannelComposer, ComposerEditor, MessageComposer from toad.qt.conversation import QtConversation from toad.qt.host import QtCommsHost, ScreenWideWindow -from toad.client.transcript_fragments import TranscriptFragment from toad.qt.history import QtWireFragment, QtWireHistory -from toad.menus import MenuCommand, MenuConversation, standard_commands +from toad.menus import MenuCommand, MenuConversation from toad.client.menu_entry import MenuEntry, strip_menu_markup as _strip_menu_markup_shared -from toad.client.relationship_row_menu import menu_entries_for_row from toad.qt.menu import QtMenu # Imported at load, not in open_transfer: this declares the Transfer members the shared # TransferMenuAction lists, so the menu offers Export and Import as Textual's does. @@ -169,16 +169,6 @@ class MenuActionRun(OperationKind): """One application action chosen from the menu.""" -def _block_menu_commands(fragment: TranscriptFragment) -> Iterator[MenuCommand]: - """The shared family-derived command list for ``fragment``, plus the per-fragment - menu entries each fragment answers via `block_menu`. Owner is - `toad.menus.standard_commands` for the family-wide list; `TranscriptFragment.block_menu` - (default `()`) and `BusMessageFragment.block_menu → message_menu(self.row)` decide - the per-fragment addition without the consumer having to ask what subclass it has.""" - yield from standard_commands(fragment) - yield from fragment.block_menu - - @dataclass(frozen=True) class ApplicationKeys: """The keys the Qt window answers anywhere: Android's back key and Escape both go back.""" @@ -266,13 +256,16 @@ def held_actions(self, listing: Welcome) -> tuple[OfferedAction, ...]: most lines. Legacy label-only API kept for bus rows which still use OfferedAction.""" return () - def menu_entries(self, listing: Welcome) -> tuple[MenuEntry, ...]: - """Rich menu-entry source — the single shape both frontends consume. A row that - has only label+run `held_actions` is adapted via `MenuEntry.from_offered`; a - row whose menu items come from a shared helper (e.g. `ConversationRow` - → `menu_entries_for_row`) returns the helper's output directly.""" + async def menu_entries_in(self, listing: Welcome) -> tuple[MenuEntry, ...]: + """What `HeldRowMenu` offers for this line: a bus line's shared `held_actions` + (`client/bus_selection.py`); a target line answers its declared + `TargetLine.menu_entries`.""" return tuple(MenuEntry.from_offered(action) for action in self.held_actions(listing)) + def channel_selection(self) -> ChannelSelection: + """The channel a line listed under this one is read in: none, for most lines.""" + return NoChannel() + class SidebarSection(MemberGroupLine, SidebarItem): """A group of rows with a title, such as Threads: the shared `MemberGroupLine` @@ -295,9 +288,10 @@ def activate(self, window: QtToadApp) -> None: class OpenSection(WelcomeSectionLine, SidebarSection): - """A welcome section (the shared `WelcomeSectionLine`, Textual's `WelcomeSection`): - open as the sidebar state says, so it stays as the reader left it however often the - listing is drawn again.""" + """A titled section of rows that are not the sidebar model's (the buses, in the sidebar + while it holds the window and in the bus switcher): open as the shared sidebar state says + (`WelcomeSectionLine`), so it stays as the reader left it however often it is drawn + again.""" @property def section_title(self) -> str: @@ -325,10 +319,6 @@ def __init__(self, text: str) -> None: self.draw("", title, detail, text) -class UnavailableSection(StatusSection): - """The welcome's line saying why the bus could not be read (`SidebarStatusLine`).""" - - class ConversationRow(NameWave, TargetLine, SidebarItem): """A row that opens its target through the target's own polymorphic `open(context)`. @@ -395,16 +385,17 @@ def wave_span(self) -> tuple[int, int] | None: def activate(self, window: QtToadApp) -> None: window.open_row(self) - def menu_entries(self, listing: Welcome) -> tuple[MenuEntry, ...]: - """Long-press menu for a conversation row: the shared Open/Copy items the - Textual sidebar's `widgets/thread_comms.show_row_menu` offers for its - RelationshipRows, via the single `menu_entries_for_row` helper.""" - host = listing.host - return menu_entries_for_row( - target_name=self.target.name, - copy=host.copy_to_clipboard, - open_callback=lambda: host.open_row(self), - ) + @property + def menu_tree(self) -> ConversationRows: + return self.treeWidget() + + async def menu_entries_in(self, listing: Welcome) -> tuple[MenuEntry, ...]: + return await self.menu_entries() + + def listed_channel(self) -> ChannelSelection: + """The channel this line is listed under, as Textual's sidebar selection names it.""" + parent = self.parent() + return parent.channel_selection() if parent is not None else NoChannel() class ThreadLine(ThreadRowFace, ConversationRow): @@ -431,6 +422,9 @@ def show_thread_text(self, text: ThreadLineText) -> None: class ChannelEntry(ChannelRowFace, ConversationRow): """A channel's line: the shared channel line text (`ChannelRowFace`).""" + def channel_selection(self) -> ChannelSelection: + return OneChannel(self.target_name) + @classmethod def of(cls, name: str, channel, *, counts: type[UnreadCount]) -> ChannelEntry: line = cls(channel_target(name)) @@ -459,8 +453,9 @@ def draw(self, badge: str, label: str, summary: str, tooltip: str) -> None: class NewSessionRow(NewSessionControl, SidebarItem): - """The Channels sidebar's first line, as Textual's `NewSessionButton`: a tap starts a - thread in the selected project through the shared `NewSessionControl`.""" + """The Channels sidebar's first line, as Textual's `NewSessionButton`: a tap starts what + the shared `NewSessionControl` says (this launch's session while no tab is shown, a thread + in the selected project beside one).""" key = NewSessionControl.label @@ -494,22 +489,6 @@ def held_actions(self, listing: Welcome) -> tuple[OfferedAction, ...]: from toad.qt.metrics import UiGap -class QtChannelListing(ChannelListing): - def keep(self, lines: KeptLines, model: SidebarModel, app: QtToadApp) -> None: - for name in self.listed(model): - line = ChannelEntry(channel_target(name)) - line.show_channel_text(self.line_text(model.channels.rows[name], app.settings.sidebar.unread_counts)) - lines.keep(line) - - -class QtThreadListing(ThreadListing): - def keep(self, lines: KeptLines, model: SidebarModel, app: QtToadApp) -> None: - for name in self.listed(model): - lines.keep(ThreadLine.of(name, model.threads.rows[name], pinned=False, - action_status=app.thread_actions.pending.get(name), - counts=app.settings.sidebar.unread_counts)) - - class BusAddress(BusAddressEntry, QLineEdit): """Where a reader types a machine to add by hand, under the welcome's Buses (`BusAddressEntry`, the field Textual's picker inherits too).""" @@ -529,9 +508,9 @@ class HeldRowMenu(QObject): """A tree line's menu (SidebarItem.menu_entries), offered where a mouse right-clicks it or a finger is held on it (`FingerPress` delivers a held finger as the same context-menu request), in the window's own panel, as its menu is (QtToadApp.offer). Every tree of - conversation rows has one: the welcome's and the sidebar's, as every Textual sidebar row - answers a right-click (`CommsRow.context_activation`). ``listing`` is what a row's - entries act through (its ``host`` window; the welcome's own rows reach the welcome).""" + conversation rows has one, as every Textual sidebar row answers a right-click + (`CommsRow.context_activation`). ``listing`` is what a row's entries act through: its + ``host`` window, and for a bus row the listing that can forget it (`BusListing`).""" def __init__(self, rows: ConversationRows, listing) -> None: super().__init__(rows) @@ -540,24 +519,35 @@ def __init__(self, rows: ConversationRows, listing) -> None: rows.customContextMenuRequested.connect(self.offer) def offer(self, point: QPoint) -> None: - """``point`` is in the tree's viewport, where QAbstractScrollArea reports it. - Reads the row's `menu_entries` — the richer single contract every row answers - (base rows adapt their `held_actions` via `MenuEntry.from_offered`, rich rows - like `ConversationRow` return the shared `menu_entries_for_row` output - directly).""" + """``point`` is in the tree's viewport, where QAbstractScrollArea reports it. The + line's own menu (`SidebarItem.menu_entries_in`: a target line's declared + `TargetLine.menu_entries`, a bus line's shared actions) is read, then offered.""" rows = self.rows item: SidebarItem | None = rows.itemAt(point) if item is None: return - entries = item.menu_entries(self.listing) + # In the host window's coordinates, where `offer_entries` places its anchor + # (`ConversationRows.window` names the app, hiding QWidget.window()). + pressed = rows.viewport().mapTo(self.listing.host, point) + asyncio.ensure_future(self.offer_read(item, QRect(pressed, QSize(1, 1)))) + + async def offer_read(self, item: SidebarItem, anchor: QRect) -> None: + """A target line's commands are read off the UI thread, then offered at the press.""" + entries = await item.menu_entries_in(self.listing) if entries: - # In the host window's coordinates, where `offer_entries` places its anchor - # (`ConversationRows.window` names the app, hiding QWidget.window()). - pressed = rows.viewport().mapTo(self.listing.host, point) - self.listing.host.offer_entries(entries, QRect(pressed, QSize(1, 1))) + self.listing.host.offer_entries(entries, anchor) -class QtWelcomeOrigin(HomeSessionOrigin): +@dataclass(frozen=True) +class QtTabAt(TabElement): + """The open tab a Qt pointer is on (a QTabBar keeps no object per tab), as Textual's + `SessionLabel`: its menu is the declared `TabElement.menu_entries`.""" + + app: QtToadApp + mode_name: str + + +class QtWelcomeOrigin(HomeSessionOrigin, HomeNavigation): """Standalone origin for Qt's welcome tab: Qt's `Welcome` widget cannot inherit `ProjectSessionOrigin` itself because `SessionOrigin`'s `AbstractHooksMeta` clashes with QWidget's shiboken6 metaclass, so the origin is a sibling object the window @@ -586,109 +576,25 @@ def thread_identity(self): ) -class QtStartSessionButton(NewSessionControl, QPushButton): - """The welcome's New Session, as Textual's `StartSessionButton`: this launch's session - (`NewSessionAction`), labelled and started through the shared `NewSessionControl`.""" - - action = NewSessionAction - - def __init__(self, window: QtToadApp, parent: QWidget | None = None) -> None: - super().__init__(self.label, parent) - self.setWindowFlags(Qt.WindowType.Widget) - self.setMinimumHeight(40) - self._host = window - self.clicked.connect(self._fire) - - def _fire(self) -> None: - self._host.run_operation(MenuActionRun, partial(self.start_session, self._host)) - - -class Welcome(Page, BusListing, NoConversationView, QWidget): - """Toad's welcome, while no conversation tab is open and in place of a saved tab this app - has not opened: the banner, the project, the channels and threads the shared welcome - lists, and the buses (BusListing): the remote ones this machine holds, with the peers - the tailnet reports holding one, a field to add a machine by name or address, and a held - finger on a saved one to forget it. A Qt client is always remote, so this machine's own - bus is not listed.""" +class Welcome(Page, NoConversationView, QWidget): + """The home page: what the pages show while no tab is (the welcome mode, the origin new + targets open from), and in place of a saved tab this app has not opened. It draws + nothing: while it is selected the comms sidebar holds the whole window + (`SidebarLayout.holds_alone`), with the banner, the bus, the buses and the hints the + welcome page used to show.""" mode = WELCOME - BUSES = "Buses" def __init__(self, window: QtToadApp) -> None: super().__init__() self.host = window - self.banner = Banner(window.renderer.theme(PrimaryColour)) - window.renderer.follows_theme(self.banner, lambda: self.banner.paint_in(window.renderer.theme(PrimaryColour))) - self.project = BusLabel(window) - self.project.setAlignment(Qt.AlignmentFlag.AlignCenter) - window.renderer.themed(self.project, lambda: self.project.setStyleSheet(window.renderer.color_style(MutedRole))) - self.new_session_button = QtStartSessionButton(window, parent=self) - self.rows = ConversationRows(window) - self.held_menu = HeldRowMenu(self.rows, self) - self.address = BusAddress(window) - # Gesture hint line below the rows, mirroring Textual's WelcomeNote(HINTS) - # at the tail of `WelcomeScreen.compose`. The content is owned per-frontend - # via `self.app.welcome_hints` — Textual carries keyboard shortcuts, Qt - # carries touch gestures. Strip Textual's `[b]...[/b]` markup for Qt since - # QLabel doesn't render it natively; the gestures text is plain already. - self.hints = QLabel(_strip_menu_markup_shared(window.welcome_hints), self) - self.hints.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.hints.setWordWrap(True) - window.renderer.themed(self.hints, lambda: self.hints.setStyleSheet(window.renderer.color_style(MutedRole))) - layout = QVBoxLayout(self) - layout.addSpacing(24) - layout.addWidget(self.banner) - layout.addWidget(self.project) - layout.addSpacing(8) - layout.addWidget(self.new_session_button) - layout.addSpacing(12) - layout.addWidget(self.rows, 1) - layout.addWidget(self.hints) - layout.addSpacing(4) - layout.addWidget(self.address) - self.content: WelcomeContent = WelcomeContent() - self.relist() - - def picker_host(self) -> BusPickerHost: - return self.host - - def held_rows(self) -> tuple[PickerRow, ...]: - return BusChoice.held(time()) - - def say_failure(self, reason: str) -> None: - self.host.show_warning(reason, "Tailnet buses") - - def present(self, model: SidebarModel) -> None: - self.content = ListedModel(model) - self.relist() - - def present_failed(self, observed: FailedObservation) -> None: - """The bus could not be read: say why, and keep the buses to switch to.""" - self.content = ListedFailure(observed) - self.relist() - - def show_rows(self, rows: tuple[PickerRow, ...]) -> None: - """What the welcome lists, then the Buses section with ``rows``: a tailnet answer - arrives between sidebar updates, and both redraw the same lines in place.""" - self.rows.redraw(partial(self.draw_lines, rows)) - - welcome_listings = (QtChannelListing(), QtThreadListing()) - - def list_section(self, top: KeptLines, listing, model: SidebarModel) -> None: - with top.group(OpenSection(listing.TITLE)) as lines: - listing.keep(lines, model, self.host) - def say_unavailable(self, top: KeptLines, text: str) -> None: - top.keep(UnavailableSection(text)) - - def draw_lines(self, buses: tuple[PickerRow, ...], top: KeptLines) -> None: - self.content.draw(self, top) - with top.group(OpenSection(self.BUSES)) as section: - for choice in buses: - section.keep(BusRow(choice)) + def workspace_navigation_owner(self, views): + """Home navigates through the welcome's origin, as Textual's `WelcomeScreen` does.""" + return views.home_origin def shown(self, window: QtToadApp, visited: Callable[[CommsTab], object]) -> None: - """The welcome leaves the sidebar as the user left it, as Textual's welcome does.""" + """The home page leaves the sidebar as the user left it, as Textual's does.""" class TreeItemRows[KeyT](KeyedRows[KeyT]): @@ -770,7 +676,7 @@ def __exit__(self, *raised: object) -> None: self.close() -class ConversationRows(RowTree, QTreeWidget): +class ConversationRows(LineMenuTree, RowTree, QTreeWidget): """A tree of Toad's conversation rows in the theme's sidebar tones, every other row a step off: pyqt-reactive's preview delegate paints each row's unread badge and label with its summary under it in muted text; a tap activates the line.""" @@ -800,6 +706,16 @@ def __init__(self, window: QtToadApp) -> None: self.setVerticalScrollMode(QTreeWidget.ScrollMode.ScrollPerPixel) self.itemClicked.connect(self.activate) + def row_menu_context(self, line: ConversationRow): + """Textual's context for the same line (`NavigationTarget.menu_context`): the open tab + showing its target, and the channel it is listed under.""" + sidebar = self.window.sidebar + return line.target.menu_context(sidebar, mode_name=sidebar.find_open_views().get(line.target_name), + channel=line.listed_channel()) + + def copy_name(self, name: str) -> None: + self.window.copy_to_clipboard(name) + def paint_colours(self) -> None: """The tree's stylesheet and its line delegate's colours, under the current scheme. The scrollbar is `RowTree.scrollbar_cells` wide, as Textual's sidebar viewport draws @@ -978,7 +894,58 @@ def parent(self) -> ChannelLine: return self.row -class Sidebar(WorkspaceHosted, SidebarStateMachine, ConversationRows): +class QtSidebarBuses(BusListing, ConversationRows): + """The buses this machine can open, under the bus line while the comms sidebar holds the + window, as Textual's `SidebarBuses`: the rows the welcome page listed, in the first screen + (above the search and the comms tree, which can list every thread). Its own tree, sized + to its rows, so a long list of threads never pushes it out of sight. A Qt client is + always remote, so this machine's own bus is not listed; a held finger on a saved one + offers to forget it (`BusRow.held_actions`).""" + + most_rows = 6 + """Rows shown before the list scrolls: a tailnet's buses, without taking the screen.""" + + def __init__(self, window: QtToadApp) -> None: + super().__init__(window) + self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) + self.held_menu = HeldRowMenu(self, self) + # Opening or closing its section changes how many lines it shows. + self.itemExpanded.connect(lambda item: self.fit_rows()) + self.itemCollapsed.connect(lambda item: self.fit_rows()) + self.relist() + + @property + def host(self) -> QtToadApp: + return self.window + + def picker_host(self) -> BusPickerHost: + return self.window + + def held_rows(self) -> tuple[PickerRow, ...]: + return BusChoice.held(time()) + + def say_failure(self, reason: str) -> None: + self.window.show_warning(reason, "Tailnet buses") + + def show_rows(self, rows: tuple[PickerRow, ...]) -> None: + def draw(top: KeptLines) -> None: + with top.group(OpenSection(self.buses_title)) as section: + for choice in rows: + section.keep(BusRow(choice)) + self.redraw(draw) + self.fit_rows() + + def fit_rows(self) -> None: + """As tall as its shown lines, up to `most_rows` of them.""" + self.doItemsLayout() + heights, item = [], self.topLevelItem(0) + while item is not None and len(heights) <= self.most_rows: + heights.append(self.visualItemRect(item).height()) + item = self.itemBelow(item) + self.setFixedHeight(sum(heights) + 2 * self.frameWidth()) + + +class Sidebar(FindsOpenViews, WorkspaceHosted, SidebarStateMachine, ConversationRows): @property def screen(self) -> WorkspaceFrame: @@ -1009,8 +976,8 @@ def __init__(self, window: QtToadApp) -> None: self.open_views = {} # The shared owner of the sidebar's search text and row-match decision. The # QLineEdit hosted by `QtSidebarSearch` writes the user's text into this - # instance; `draw_lines` / `QtChannelListing.keep` / `QtThreadListing.keep` - # ask the filter's `matches(name)` when deciding whether a row joins the + # instance; `draw_lines` asks the filter's `matches(name)` when deciding whether a + # row joins the # tree. Textual's `SideBar` also owns one (same class, same match rule). self.filter: SidebarFilter = SidebarFilter() self.filter.subscribe(self._on_filter_changed) @@ -1022,6 +989,12 @@ def host(self) -> QtToadApp: """The window a row's menu entries act in (`HeldRowMenu`).""" return self.window + @property + def app(self) -> QtToadApp: + """The application, as a Textual sidebar's `app` names it for the shared readers + (`FindsOpenViews`, `NavigationTarget.menu_context`).""" + 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 @@ -1071,7 +1044,6 @@ def draw(top: KeptLines) -> None: self.groups = {} if model is not None: self.window.channel_sort.update_order(model.observation.channel_order()) - self.window.workspace_sessions.home.present(model) self.window.paint_tabs() def sync(self, *, change: SidebarChange, reorder: bool = False) -> None: @@ -1089,12 +1061,6 @@ def model_replaced(self) -> None: self.groups = {} self.redraw(lambda top: None) - def find_open_views(self) -> dict[str, str]: - """Which channels Qt currently shows an open tab for. The Qt sidebar does not - yet hoist this out of the tab bar, so the hook returns the stored map (populated - elsewhere when tab routing lands).""" - return self.open_views - def reconcile_members(self): """Textual holds a DOM-level sync boundary here; Qt touches items directly.""" return nullcontext() @@ -1174,9 +1140,6 @@ def _rebind_groups_from_tree(self, model: SidebarModel) -> None: rebuilt[name] = group self.groups = rebuilt - def bind_failed_observation(self, observed: FailedObservation) -> None: - super().bind_failed_observation(observed) - self.window.workspace_sessions.home.present_failed(observed) class QtSessionEntry(SessionEntries): @@ -1216,7 +1179,7 @@ def location(self, app) -> str: class ConversationView(QtConversation, ConversationViewNavigation, MenuConversation, SessionScope, - WireView, metaclass=PyQtWidgetMeta): + WireView, NavigationOwner, metaclass=PyQtWidgetMeta): """One conversation tab, Textual's `CommsChatView`: a `QtConversation` whose history is the conversation's wire, paged lazily by the pager Textual's channels use and drawn as virtual rows, read again whenever Core's stores change; the composer and activity its @@ -1405,7 +1368,7 @@ def thread_identity(self): def open_block_menu(self, fragment: QtWireFragment, pressed: QPoint) -> None: """The block menu for `fragment`, at `pressed` (the window's coordinates).""" self.held_fragment = fragment - entries = QtMenu.command_entries(_block_menu_commands(fragment), self.app.settings, + entries = QtMenu.command_entries(QtMenu.block_commands(fragment, fragment.block_menu), self.app.settings, self._run_block_menu_command) if entries: self.app.offer_entries(entries, QRect(pressed, QSize(1, 1))) @@ -1459,7 +1422,7 @@ class QtWorkspaceViews(WorkspaceViews): def __init__(self, app: QtToadApp) -> None: self.app = app self.home = Welcome(app) - self._welcome_origin = QtWelcomeOrigin(app) + self.home_origin = QtWelcomeOrigin(app) self.pages = QStackedWidget(app) self.pages.addWidget(self.home) self.views: dict[str, ConversationView] = {} @@ -1475,12 +1438,14 @@ def origin(self, identity: str) -> SessionOrigin: if view := self.views.get(identity): return view.origin if identity == WELCOME: - return self._welcome_origin + return self.home_origin return NoSessionOrigin(identity) - def navigation_owner(self) -> NoNavigationOwner: - """Rows open from the sidebar through the shared history route; no view navigates.""" - return NoNavigationOwner(self.app) + def navigation_owner(self) -> NavigationOwner: + """Derived from the selected page, as Textual's `WorkspaceSessions.navigation_owner` + is from the selected view: a conversation tab navigates as itself, home as the + welcome's origin.""" + return self.selected.workspace_navigation_owner(self) def prepare(self, mode: str) -> Page: if view := self.views.get(mode): @@ -1594,6 +1559,37 @@ def __init__(self, connection: CoreConnection, project: Checkout, self.sidebar.filter, QtSidebarPanels(self.sidebar_state, (QtPanelEntry.of(CHANNELS_PANEL, self.sidebar, (self.channel_sort,), CHANNELS_PANEL.title),)), parent=self) + # While no tab is shown the comms sidebar holds the window (`SidebarLayout.holds_alone`) + # and carries what the welcome page did: Toad's banner, the bus this window reads and + # the buses it can open above the search and rows, so they are in the first screen + # however many threads the rows list; the hints and the field to add a machine below + # them. Beside a tab only the search and rows show. Textual's `ChannelsSidebar` + # composes the same parts in the same order. + self.banner = Banner(self.renderer.theme(PrimaryColour)) + self.renderer.follows_theme(self.banner, lambda: self.banner.paint_in(self.renderer.theme(PrimaryColour))) + self.bus_label = BusLabel(self) + self.bus_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.renderer.themed(self.bus_label, lambda: self.bus_label.setStyleSheet(self.renderer.color_style(MutedRole))) + self.hints = QLabel(_strip_menu_markup_shared(self.welcome_hints)) + self.hints.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.hints.setWordWrap(True) + self.renderer.themed(self.hints, lambda: self.hints.setStyleSheet(self.renderer.color_style(MutedRole))) + self.bus_address = BusAddress(self) + self.sidebar_buses = QtSidebarBuses(self) + self.channels_column = QWidget(self) + column = QVBoxLayout(self.channels_column) + column.setContentsMargins(0, 0, 0, 0) + column.setSpacing(UiGap.tight) + for part in (self.banner, self.bus_label, self.sidebar_buses): + column.addWidget(part) + column.addWidget(self.sidebar_search, 1) + # A clear gap under the rows: a row the tree's edge cuts must not read as running + # under the hints. + column.addSpacing(UiGap.loose) + for part in (self.hints, self.bus_address): + column.addWidget(part) + self.sole_parts = (self.banner, self.bus_label, self.sidebar_buses, self.hints, self.bus_address) + self.shown_alone: bool | None = None self.thread_pane = ThreadSettingsPane(self, parent=self, project_path=self.project_dir.path) # The pages and both sidebars live in one chrome that places them where the shared @@ -1605,7 +1601,7 @@ def __init__(self, connection: CoreConnection, project: Checkout, clock=self.animation_clock, available=self._pane_available, parent=self) self.channels_side = QtSideBar( - self.sidebar_layout, ChannelsSidebarPlacement, self.sidebar_search, + self.sidebar_layout, ChannelsSidebarPlacement, self.channels_column, heading=partial(self._pane_heading, ChannelsSidebarPlacement), laid_out=self.rearrange_sidebars, client=self, parent=self.chrome) self.thread_side = QtSideBar( @@ -1669,7 +1665,7 @@ def __init__(self, connection: CoreConnection, project: Checkout, from toad.qt.bus_switcher import QtBusSwitcher # Welcome is always a BusListing; the switcher registers/deregisters # itself while shown so answers reach both. - self._bus_listings: list[BusListing] = [self.workspace_sessions.home] + self._bus_listings: list[BusListing] = [self.sidebar_buses] self.bus_switcher = QtBusSwitcher(self) chrome_layout.addWidget(self.bus_switcher) # Paste surface for the bus-connect remediation ("Paste a profile" option on the @@ -1732,7 +1728,7 @@ def fit_safe_area(self, margins: QMargins) -> None: self.setContentsMargins(margins) def stores_changed(self, event: CoordinationObserved, subscription: object) -> None: - self.workspace_sessions.home.project.present(self) + self.bus_label.present(self) self.workspace_sessions.selected.reload() def external_transcript_changed(self, event: ExternalTranscriptChanged, subscription: object) -> None: @@ -1877,10 +1873,21 @@ def _bind_thread_pane(self) -> None: collapsed = self.sidebar_layout.is_collapsed(ThreadSidebarPlacement) self.thread_pane.bind(sessions.home if collapsed else sessions.selected) + def present_alone(self) -> None: + """Show the welcome's parts in the comms sidebar while it holds the window; hide them + when a tab is shown beside it.""" + alone = self.sidebar_layout.alone + if alone == self.shown_alone: + return + self.shown_alone = alone + for part in self.sole_parts: + part.setVisible(alone) + def present_panes(self) -> None: """Draw both sidebars from the one layout and place them; the thread's sidebar is presented only while a conversation is open.""" self._bind_thread_pane() + self.present_alone() for side in self.chrome.sidebars: side.present() self.chrome.arrange() @@ -2171,7 +2178,7 @@ def offer_tab_menu(self, point: QPoint) -> None: """The tab under a right-click or a held finger offers the shared tab menu.""" index = self.tabs.tabAt(point) if index >= 0: - self.offer_entries(self.session_navigation.tab_menu(self.session_navigation.tabs[index].mode_name)) + self.offer_entries(QtTabAt(self, self.session_navigation.tabs[index].mode_name).menu_entries()) def move_index(self, start: int, end: int) -> None: """A tab dragged from one place in the bar to another: it moves past the tab it diff --git a/src/toad/screens/welcome.py b/src/toad/screens/welcome.py index cdf51ce32..014a552bf 100644 --- a/src/toad/screens/welcome.py +++ b/src/toad/screens/welcome.py @@ -1,290 +1,37 @@ -"""What the workspace shows while no tab is open. - -The view is not a tab: the tab order selects it when its last tab closes and -at a launch that named no session to resume. It starts no agent; opening an -entry or a new session opens the first tab, which replaces it. +"""The home view: what the workspace selects while no tab is open. + +The view is not a tab: the tab order selects it when its last tab closes and at a launch +that named no session to resume. It draws nothing. While it is selected the comms sidebar +holds the whole window (`SidebarLayout.holds_alone`) with Toad's banner, the project, the +buses and the key hints (`ChannelsSidebar`); opening a row or a new session opens the first +tab, and the sidebar returns to its kept placement beside it. It stays the origin the +sidebar's targets open from. """ from __future__ import annotations - -from metaclass_registry.mro_dispatch import handles -from agent_comms.messaging.channel_targets import NoChannel from agent_comms.projects.checkouts import Checkout -from formbridge.key_declarations import TextEntryMode -from textual.app import ComposeResult - -from toad.widget_actions import NativeMethodKeys, TogglesIrc, WidgetAction -from textual.containers import VerticalGroup, VerticalScroll -from textual.content import Content -from textual.widgets import Static -from toad.client.application_actions import NewSessionAction as _SharedNewSession -from toad.client.welcome import ChannelListing, ThreadListing, WelcomeListing, WelcomeLocation -from toad.welcome_banner import WelcomeBanner -from toad.client.sidebar_lines import WelcomeSectionLine -from toad.core.events import SessionSelected -from toad.format_path import format_path -from toad.navigation_context import NavigationContext, NavigationOwner +from toad.app_node import ToadNode +from toad.client.session_scope import HomeSessionOrigin +from toad.navigation_context import HomeNavigation from toad.navigation_target import FeedTarget, NavigationTarget -from toad.navigation_target import channel_target, ThreadTarget -from toad.screens.bus_choice import ListsBuses from toad.screens.session_view import SessionView -from toad.client.session_scope import HomeSessionOrigin from toad.thread_identity import ThreadIdentity -from toad.widgets.comms_sidebar import ( - ChannelRow, - NewSessionButton, - ThreadStatusRow, -) -from toad.widgets.sidebar_tree import ( - RowReconciliation, - SidebarGroup, - TargetMenuTree, - GroupTitle, -) -from toad.widgets.splash_text import SplashText -from toad.app_node import ToadNode -from toad.native_style import ( - AutoHeight, - CenteredChildren, - FullWidth, - MutedText, - NoWrap, - SpacedAbove, -) -from textual.events import Mount -from textual import on - -from toad.sidebar_changes import SidebarChange -from toad.widgets.sidebar_tree import CommsRow, ListedRow - - -class WelcomeTitle(WelcomeBanner, SplashText, MutedText, NoWrap): - """The app's name, swept into the theme's colours each time the view shows.""" - - - def apply_native_layout(self) -> None: - super().apply_native_layout() - self.styles.width = self.styles.height = "auto" - - @on(Mount) - def on_mount(self) -> None: - self.watch(self.app, "app_focus", self.focus_changed, init=False) - - @property - def plays(self) -> bool: - view = self.query_ancestor(WelcomeScreen) - return self.is_attached and view.is_current and self.app.app_focus - - def focus_changed(self, focused: bool) -> None: - # An unfocused terminal runs no timer for this view. - if not focused: - self.stop_effect() - self.refresh() - - -class WelcomeHeading(MutedText, Static): - """How a title line on the splash looks, declared once. - - The look is MutedText; GroupTitle is the separate fact that a sidebar group's title - renders from its group and toggles its members on activation. A section whose rows are - not sidebar-model rows wants the look and not the group - and reusing the group variant - outside a SidebarGroup raises NoMatches from its own header_group, which is how I found - out it was two facts in one class. - """ - - -class WelcomeSectionTitle(WelcomeHeading, GroupTitle): - """A sidebar-group section's title line on the splash: the look, plus its group.""" - - -class WelcomeSection(WelcomeSectionLine, WelcomeListing, SpacedAbove, SidebarGroup[ListedRow]): - """Some of the sidebar model's rows under a title.""" - - def __init__(self) -> None: - super().__init__(WelcomeSectionTitle(Content(self.TITLE)), expanded=True) - # Shown once the model lists something for it. - self.display = False - - def on_mount(self) -> None: - self.expanded = self.opens() - super().on_mount() - - @property - def section_title(self) -> str: - return self.TITLE - - @property - def sidebar_state(self): - return self.app.sidebar_state - - @property - def member_keys(self): - return self.listed(self.query_ancestor(WelcomeEntries).model_state.shown) - - def sync_members(self, changed: frozenset[str]) -> None: - if not self.member_container.is_attached: - return - self.display = bool(self.member_keys) - self.reconcile_rows(changed=changed) - - -class WelcomeChannels(ChannelListing, WelcomeSection): - def new_row(self, key): - return ChannelRow(channel_target(key), key) - - def show_member(self, key, row): - channel = self.query_ancestor(WelcomeEntries).model_state.shown.channels.rows[ - key - ] - text = self.line_text(channel, self.app.settings.sidebar.unread_counts) - row.set_label(text.label) - row.tooltip = text.tooltip - row.refresh_paint() - - -class WelcomeThreads(ThreadListing, WelcomeSection): - def new_row(self, key): - return ThreadStatusRow(ThreadTarget(key), key) - - def show_member(self, key, row): - thread = self.query_ancestor(WelcomeEntries).model_state.shown.threads.rows[key] - row.show(thread) - - -class WelcomeBuses(SpacedAbove, AutoHeight, ListsBuses, VerticalGroup): - """The buses this machine can open, on the splash beside its channels and threads. - - Tristan: "I would like it to show the buses as well so that it would list out the buses - that are available", and then that it "didn't list the other buses on the tailnet". It - inherits the Open-bus dialog's own listing (ListsBuses), so the rows, the tailnet's - peers and what choosing one does are the dialog's, not a second set that can drift from - it - and a bus did not have to become a comms target to get keyboard navigation, - because BusRows is an OptionList and already has it. The application asks the tailnet - once per window, so showing the splash again lists its last answer without a sweep. - - Not a WelcomeSection: those read their keys from the sidebar model, and a bus is not in - it. - """ - - def compose(self) -> ComposeResult: - yield WelcomeHeading(Content("Buses")) - yield self.bus_rows() - - -class WelcomeEntries(FullWidth, AutoHeight, SpacedAbove, TargetMenuTree): - """New session, channels, threads and buses: the rows the sidebar opens, plus the buses - this machine can open.""" - - - def __init__(self) -> None: - super().__init__() - self.navigation_groups = (WelcomeChannels(), WelcomeThreads()) - - def compose(self) -> ComposeResult: - yield StartSessionButton() - yield from self.navigation_groups - yield WelcomeBuses() - - def accepts_observation(self) -> bool: - return self.is_attached and self.query_ancestor(WelcomeScreen).is_current - - def row_menu_context(self, row: CommsRow): - return row.target.menu_context(self, channel=NoChannel()) - - @RowReconciliation.sync - def sync(self, *, change: SidebarChange, reorder: bool = False) -> None: - channel_list, thread_list = self.navigation_groups - change.apply_welcome(channel_list, thread_list) - - @handles(SessionSelected) - async def present_selected(self, event: SessionSelected) -> None: - self.present() - - -class WelcomeColumn(AutoHeight, VerticalScroll): - def apply_native_layout(self) -> None: - super().apply_native_layout() - self.styles.width = 64 - self.styles.max_width = "100%" - self.styles.max_height = "100%" - - -class WelcomeNote(MutedText, SpacedAbove, Static): - """The project line and the key hints.""" - - -class WelcomeLocationNote(WelcomeLocation, WelcomeNote): - """The welcome's location line (`WelcomeLocation`): the project this TUI works in.""" - - def __init__(self, app, project) -> None: - self.project = project - super().__init__(self.location_line(app), markup=False) - - def location(self, app) -> str: - return format_path(self.project) - - -class WelcomeAction(WidgetAction, affix="Action"): - """What the welcome view does on its own keys.""" - - -class WelcomeStartSession(WelcomeAction): - """Textual's welcome binds `n` to a WelcomeAction so the screen's own key system - picks it up; the body lives on the shared `NewSessionAction` in - `toad.client.application_actions`, so Qt's Welcome button and this `n` key fire - the same ClientApplication-owned action.""" - - title = "New session" - keys = {TextEntryMode: ("n",)} - show = True - - async def apply(self, context: WelcomeScreen) -> None: - await _SharedNewSession().apply(context.app) - - -class StartSessionButton(NewSessionButton): - """The welcome view's New Session is this launch's, as its n key is; the sidebar's - makes another native thread.""" - - action = _SharedNewSession +from toad.widget_actions import TogglesIrc class WelcomeScreen( - NativeMethodKeys, TogglesIrc, - NavigationOwner, + HomeNavigation, HomeSessionOrigin, - CenteredChildren, SessionView, ToadNode, - actions=(WelcomeAction,), can_focus=False, ): - AUTO_FOCUS = "WelcomeEntries StartSessionButton" - - def __init__(self) -> None: super().__init__() - app = self.app - self.project_path = app.project_dir - - def compose(self) -> ComposeResult: - with WelcomeColumn(can_focus=False): - yield WelcomeTitle() - yield WelcomeLocationNote(self.app, self.project_path.path) - yield WelcomeEntries() - # Hints come from the app so Qt can supply its own gesture string; - # see `ToadApp.welcome_hints` / `QtToadApp.welcome_hints`. - yield WelcomeNote(self.app.welcome_hints) - - @property - def navigation_context(self) -> NavigationContext: - assert self.id is not None - return NavigationContext( - self.app, self.id, self.project_path, self.thread_identity.thread_name() - ) + self.project_path = self.app.project_dir def read_history_identity(self, project: Checkout) -> ThreadIdentity: observed = self.app.coordination_access.observation.observed() @@ -302,16 +49,5 @@ async def open_sidebar_target(self, target: NavigationTarget) -> None: await self.prepare_history_origin() await super().open_sidebar_target(target) - async def prepare_presentation(self) -> None: - await super().prepare_presentation() - # The view's frame is written first; the effect is built and played after it. - title = self.query_one(WelcomeTitle) - self.screen.frame_presentation.defer(title, title.play) - - async def retire_presentation(self) -> None: - self.query_one(WelcomeTitle).stop_effect() - await super().retire_presentation() - - async def toggle_irc(self) -> None: await self.open_sidebar_target(FeedTarget()) diff --git a/src/toad/session_navigation.py b/src/toad/session_navigation.py index d05704594..dbd0e84d5 100644 --- a/src/toad/session_navigation.py +++ b/src/toad/session_navigation.py @@ -76,6 +76,18 @@ class Detached: returning_view: SessionScope | None +class TabElement: + """An open tab as a pointer finds it: Textual's `SessionLabel`, Qt's `QtTabAt`. Its menu + is declared here, from the navigator's `tab_menu`, and each toolkit only draws the + entries; a toolkit tab that built its own fails `tests/model/test_menu_owners.py`.""" + + app: object + mode_name: str + + def menu_entries(self) -> tuple[MenuEntry, ...]: + return self.app.session_navigation.tab_menu(self.mode_name) + + class SessionNavigation(StartsSessions, SessionNavigator): def __init__(self, app: NavigationHost) -> None: self.app = app diff --git a/src/toad/sidebar_changes.py b/src/toad/sidebar_changes.py index 2a2e11358..ab4657a4d 100644 --- a/src/toad/sidebar_changes.py +++ b/src/toad/sidebar_changes.py @@ -15,7 +15,7 @@ from agent_comms.ui_model.sidebar import ChannelRowModel -from toad.sidebar_contracts import ActivityRows, GroupedSidebar, MemberRows, RelationshipMemberRows +from toad.sidebar_contracts import ActivityRows, GroupedSidebar, RelationshipMemberRows class SidebarChange(ABC): @@ -31,10 +31,6 @@ class SidebarChange(ABC): def apply_comms(self, sidebar: GroupedSidebar, rows: Mapping[str, ChannelRowModel]) -> None: ... - @abstractmethod - def apply_welcome(self, channel_list: MemberRows[str], thread_list: MemberRows[str]) -> None: - ... - @abstractmethod def apply_relationships(self, groups: Iterable[RelationshipMemberRows]) -> None: ... @@ -57,10 +53,6 @@ def apply_comms(self, sidebar: GroupedSidebar, rows: Mapping[str, ChannelRowMode group.present(rows[name]) group.sync_members(frozenset(group.member_keys)) - def apply_welcome(self, channel_list: MemberRows[str], thread_list: MemberRows[str]) -> None: - channel_list.sync_members(frozenset(channel_list.member_keys)) - thread_list.sync_members(frozenset(thread_list.member_keys)) - def apply_relationships(self, groups: Iterable[RelationshipMemberRows]) -> None: for group in groups: group.sync_members(frozenset(group.member_keys)) @@ -82,11 +74,6 @@ def apply_comms(self, sidebar: GroupedSidebar, rows: Mapping[str, ChannelRowMode if group is not None: group.sync_members(group.present(rows[name])) - def apply_welcome(self, channel_list: MemberRows[str], thread_list: MemberRows[str]) -> None: - channel_list.sync_members(self.names) - # A changed channel can change the welcome thread list's order. - thread_list.sync_members(frozenset()) - def apply_relationships(self, groups: Iterable[RelationshipMemberRows]) -> None: pass @@ -105,9 +92,6 @@ def apply_comms(self, sidebar: GroupedSidebar, rows: Mapping[str, ChannelRowMode for group in sidebar.groups.values(): group.repaint_members(self.names) - def apply_welcome(self, channel_list: MemberRows[str], thread_list: MemberRows[str]) -> None: - thread_list.sync_members(self.names) - def apply_relationships(self, groups: Iterable[RelationshipMemberRows]) -> None: for group in groups: changed = group.keys_for_threads(self.names) diff --git a/src/toad/sidebar_contracts.py b/src/toad/sidebar_contracts.py index 113e3c86e..30b46aa89 100644 --- a/src/toad/sidebar_contracts.py +++ b/src/toad/sidebar_contracts.py @@ -52,6 +52,26 @@ class NavigationRefresh(metaclass=AbstractHooksMeta): def apply(self) -> None: ... +class FindsOpenViews: + """Which open tab shows each thread of this sidebar's bus; the first tab claims it. + Textual's `CommsSidebar` and Qt's `Sidebar`: a row's menu runs its commands in that + tab's mode (`NavigationTarget.menu_context`).""" + + def find_open_views(self) -> dict[str, str]: + app = self.app + threads = self.model_state.shown.threads.rows + views: dict[str, str] = {} + for details in app.session_tracker.ordered_sessions: + screen = app.session_navigation.source(details.mode_name) + if screen is None: + continue + name = screen.thread_identity.thread_name() + if (name in threads and name not in views + and screen.belongs_to_wire(self.navigation_root)): + views[name] = details.mode_name + return views + + class GroupedSidebar(metaclass=AbstractHooksMeta): """A channel sidebar owns its groups, open-tab markers and navigation refresh.""" diff --git a/src/toad/sidebar_layout.py b/src/toad/sidebar_layout.py index 8c9736ab2..5f53dc11f 100644 --- a/src/toad/sidebar_layout.py +++ b/src/toad/sidebar_layout.py @@ -3,9 +3,9 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Iterator, Mapping +from collections.abc import Callable, Iterator, Mapping from dataclasses import dataclass, replace -from typing import TYPE_CHECKING, Protocol +from typing import TYPE_CHECKING, ClassVar, Protocol from agent_comms.nominal.declared_family import DeclaredFamily from metaclass_registry import AbstractHooksMeta @@ -13,6 +13,7 @@ from toad.sidebar_placement import ( ActiveSidebarPlacement, + ChannelsSidebarPlacement, BandSplit, SidebarEdge, SidebarFold, @@ -234,6 +235,20 @@ def toggle_pane(self) -> None: """A click on the strip: open a folded pane, fold an open one.""" self.fold(not self.collapsed) + controls_wanted = True + """Whether the reader shows the extent slider and placement actions (`toggle_controls`); + they are hidden while the surface holds the window alone, and come back as the reader + left them.""" + + @property + def holds_alone(self) -> bool: + """This surface takes the whole window (`SidebarLayout.holds_alone`).""" + return self.sidebar_layout.holds_alone(self.placement_identity) + + def content_padding(self) -> Spacing: + """The room the content leaves its strip and grip: none while it holds the window.""" + return Spacing() if self.holds_alone else self.placement.side.content_padding() + @property def placement(self) -> SidebarPlacement: return self.sidebar_layout.get(self.placement_identity) @@ -289,17 +304,17 @@ def dragged_percent(self, start_percent: int, delta: Offset, viewport_extent: in edge = self.placement.side return start_percent + round(100 * edge.sign * edge.coordinate(delta) / max(1, viewport_extent)) - @staticmethod - def surface_parts(edge: type[SidebarEdge], size: Size) -> SurfaceParts: - """Where a surface's toggle strip, resize handle and content go inside its own region, - in cells. Both sit on the conversation-facing side (the edge's opposite), as Textual - docks SideBarToggle and SidebarResizeHandle; the content keeps the edge's - ``content_padding`` clear of them.""" + def surface_parts(self, size: Size) -> SurfaceParts: + """Where this surface's toggle strip, resize handle and content go inside its own + region, in cells. Both sit on the conversation-facing side (the edge's opposite), as + Textual docks SideBarToggle and SidebarResizeHandle; the content keeps + `content_padding` clear of them. Holding the window alone, the content is all of it.""" + edge = self.placement.side inner = edge.opposite() cross = size.width toggle = inner.region(size, SidebarGeometry(0, edge.collapsed_extent, 0, cross), Spacing()) handle = inner.region(size, SidebarGeometry(edge.collapsed_extent, 1, 0, cross), Spacing()) - content = Region(0, 0, size.width, size.height).shrink(edge.content_padding()) + content = Region(0, 0, size.width, size.height).shrink(self.content_padding()) return SurfaceParts(toggle, handle, content) @@ -476,6 +491,12 @@ def presented_sidebars(self) -> tuple[Bar, ...]: ... def arrange_chrome(self, viewport: Size) -> ChromeArrangement[Bar]: bars = self.presented_sidebars() layout = self.sidebar_layout + # No tab shown: the sole bar is the whole window and nothing else is placed. + for bar in bars: + if layout.holds_alone(bar.placement_identity): + return ChromeArrangement(Region(viewport.width, 0, 0, viewport.height), + Spacing(left=viewport.width), + {bar: Region(0, 0, viewport.width, viewport.height)}) collapsed = {bar.placement_identity: bar.collapsed for bar in bars} resolved = layout.resolve(viewport, collapsed) # While a grip holds an extent the bars follow it, but the conversation keeps the room @@ -511,32 +532,57 @@ class SidebarLayout: minimum_percent = 15 maximum_percent = 50 + sole_role: ClassVar[type[SidebarPlacement]] = ChannelsSidebarPlacement + """The bar that takes the whole window while no tab is shown: the comms sidebar (its + channels, threads, search and buses), with Toad's banner at its head. It replaced the + welcome page (Tristan, 2026-11-18): opening a row gives the first tab, and the bar + returns to its kept placement beside it, with the other bars the view brings.""" # A grip or the slider held below this folds the pane when released. fold_percent = minimum_percent // 2 - def __init__(self, settings: ArrangementStore, origin: type[TerminalOrigin]) -> None: + def __init__(self, settings: ArrangementStore, origin: type[TerminalOrigin], + alone: Callable[[], bool] = lambda: False) -> None: self.settings, self.origin = settings, origin + # Whether no tab is shown: the application answers it from the selected view (the + # welcome mode is the one view that is not a tab), so nothing here keeps a copy. + self._alone = alone self._collapsed: dict[type[SidebarPlacement], bool] = {} # Extents a grip is holding: the bars are drawn at them, but nothing is written to the # settings until the hold ends (`keep_held`), so a drag costs only its layout. self._held: dict[type[SidebarPlacement], int] = {} + @property + def alone(self) -> bool: + """No tab is shown: the `sole_role` bar holds the window.""" + return self._alone() + + def holds_alone(self, identity: type[SidebarPlacement]) -> bool: + """Whether ``identity``'s bar takes the whole window: no tab is shown and it is the + `sole_role`. Such a bar is open whatever its kept fold, and shows no strip, grip or + placement controls: there is nothing beside it to make room for.""" + return identity is self.sole_role and self.alone + + def kept_collapsed(self, identity: type[SidebarPlacement]) -> bool: + """The fold kept for ``identity``: True (only its toggle) until something opens it. + `set_collapsed` and `toggle_collapsed` read and write this one, never the open state a + bar holding the window alone shows over it.""" + return self._collapsed.get(identity, True) + def is_collapsed(self, identity: type[SidebarPlacement]) -> bool: """Whether the bar for ``identity`` shows only its toggle (True) or its - expanded pane too (False). Defaults to True — a role starts collapsed - until something opens it.""" - return self._collapsed.get(identity, True) + expanded pane too (False): its kept fold, except that a bar holding the window + alone is open; its kept fold returns with the first tab.""" + return not self.holds_alone(identity) and self.kept_collapsed(identity) def set_collapsed(self, identity: type[SidebarPlacement], value: bool) -> bool: - """Set ``identity``'s collapsed state; returns whether the state changed.""" - if self.is_collapsed(identity) == value: - return False + """Keep ``identity``'s fold; returns whether what the bar shows changed.""" + shown = self.is_collapsed(identity) self._collapsed[identity] = value - return True + return self.is_collapsed(identity) != shown def toggle_collapsed(self, identity: type[SidebarPlacement]) -> bool: - """Flip ``identity``'s collapsed state; returns the new value.""" - new_value = not self.is_collapsed(identity) + """Flip ``identity``'s kept fold; returns the new value.""" + new_value = not self.kept_collapsed(identity) self._collapsed[identity] = new_value return new_value diff --git a/src/toad/widgets/channels_sidebar.py b/src/toad/widgets/channels_sidebar.py index f77d3163e..edfa10d9d 100644 --- a/src/toad/widgets/channels_sidebar.py +++ b/src/toad/widgets/channels_sidebar.py @@ -1,16 +1,142 @@ -"""The shared Channels view, including during a destination's loading frame.""" +"""The shared Channels view, including during a destination's loading frame. -from toad.native_style import StartsHidden +While no tab is shown it holds the whole window (`SidebarLayout.holds_alone`) and carries +what the welcome page did: Toad's banner, the project and the buses above the search and +rows, and the key hints below them. Qt's comms sidebar shows the same parts +(`QtToadApp.present_alone`).""" + +from formbridge.key_declarations import TextEntryMode +from textual import on +from textual.app import ComposeResult +from textual.containers import Center, VerticalGroup +from textual.content import Content +from textual.events import Mount +from textual.widget import Widget +from textual.widgets import Static + +from toad.client.application_actions import NewSessionAction +from toad.client.welcome import WelcomeLocation +from toad.constants import WELCOME +from toad.format_path import format_path +from toad.native_style import AutoHeight, MutedText, NoWrap, SpacedAbove, StartsHidden +from toad.screens.bus_choice import ListsBuses from toad.sidebar_layout import CHANNELS_PANEL from toad.sidebar_placement import ChannelsSidebarPlacement +from toad.welcome_banner import WelcomeBanner +from toad.widget_actions import ToggleIrcAction, WidgetAction from toad.widgets.comms_sidebar import CommsSidebar from toad.widgets.session_sort import ChannelListSort from toad.widgets.side_bar import SideBar -from textual.widget import Widget +from toad.widgets.splash_text import SplashText + + +class SidebarBanner(WelcomeBanner, SplashText, MutedText, NoWrap): + """The app's name at the head of the comms sidebar, swept into the theme's colours each + time the sidebar comes to hold the window.""" + + def apply_native_layout(self) -> None: + super().apply_native_layout() + self.styles.width = self.styles.height = "auto" + + @on(Mount) + def on_mount(self) -> None: + self.watch(self.app, "app_focus", self.focus_changed, init=False) + + @property + def plays(self) -> bool: + return (self.is_attached and self.query_ancestor(ChannelsSidebar).holds_alone + and self.app.app_focus) + + def focus_changed(self, focused: bool) -> None: + # An unfocused terminal runs no timer for this view. + if not focused: + self.stop_effect() + self.refresh() + + +class SidebarNote(MutedText, SpacedAbove, Static): + """A muted line under the banner or the rows: the project, the key hints. Centred, as + Qt's lines are.""" + + def apply_native_layout(self) -> None: + super().apply_native_layout() + self.styles.width = "100%" + self.styles.text_align = "center" + + +class SidebarLocationNote(WelcomeLocation, SidebarNote): + """The location line (`WelcomeLocation`): the project this TUI works in.""" + + def __init__(self) -> None: + super().__init__("", markup=False) + + @on(Mount) + def name_location(self) -> None: + self.update(self.location_line(self.app)) + + def location(self, app) -> str: + return format_path(app.project_dir.path) + + +class SidebarHints(SidebarNote): + """The keys the window answers while the sidebar holds it (`ToadApp.welcome_hints`).""" + + @on(Mount) + def name_keys(self) -> None: + self.update(Content.from_markup(self.app.welcome_hints)) + +class SidebarHeading(MutedText, Static): + """A section title that is not a sidebar group's (the buses are not sidebar-model rows).""" -class ChannelsSidebar(SideBar): + +class SidebarBuses(SpacedAbove, AutoHeight, ListsBuses, VerticalGroup): + """The buses this machine can open, under the project line while the sidebar holds the + window, in the first screen however many threads the rows list. + + Tristan: "I would like it to show the buses as well so that it would list out the buses + that are available", and then that it "didn't list the other buses on the tailnet". It + inherits the Open-bus dialog's own listing (ListsBuses), so the rows, the tailnet's peers + and what choosing one does are the dialog's, not a second set that can drift from it.""" + + def compose(self) -> ComposeResult: + yield SidebarHeading(Content(self.buses_title)) + yield self.bus_rows() + + +class SoleNewSessionAction(WidgetAction): + """`n` starts this launch's session while the sidebar holds the window, as the welcome's + key did (`NewSessionAction`).""" + + title = "New session" + keys = {TextEntryMode: ("n",)} + show = True + + def available(self, sidebar: ChannelsSidebar) -> bool: + return sidebar.holds_alone and sidebar.app.focused is not sidebar.search_input + + async def apply(self, sidebar: ChannelsSidebar) -> None: + await NewSessionAction().apply(sidebar.app) + + +class SoleIrcAction(WidgetAction): + """ctrl+g opens the channel view from home while the sidebar holds the window, as the + welcome's key did (`ToggleIrcAction` on the home view); beside a tab the view's own key + answers.""" + + title = ToggleIrcAction.title + keys = ToggleIrcAction.keys + + def available(self, sidebar: ChannelsSidebar) -> bool: + return sidebar.holds_alone + + async def apply(self, sidebar: ChannelsSidebar) -> None: + await sidebar.app.workspace_sessions.origin(WELCOME).require().toggle_irc() + + +class ChannelsSidebar(SideBar, actions=(SoleNewSessionAction, SoleIrcAction)): COMPOSITING_LAYER = True + def __init__(self, *, observe: bool = True, defer_mount: bool = False) -> None: self.roster = CommsSidebar(observe=observe) super().__init__( @@ -24,7 +150,35 @@ def __init__(self, *, observe: bool = True, defer_mount: bool = False) -> None: defer_mount=defer_mount, ) + def lead_parts(self) -> tuple[Widget, ...]: + # The banner keeps its own width (its sweep's frames are built for it), centred + # across the window it holds, as Qt's `Banner` and the welcome drew it. + # The buses sit under the location, in the first screen however many threads the + # rows below list (Qt's `QtSidebarBuses` sits there too). + self.banner = SidebarBanner() + return (Center(self.banner), SidebarLocationNote(), SidebarBuses()) + + def tail_parts(self) -> tuple[Widget, ...]: + return (SidebarHints(),) + + @on(Mount) + def show_alone_parts(self) -> None: + self.present_alone() + + def present_alone(self) -> None: + """Show the banner, project, buses and hints while the sidebar holds the window, and + sweep the banner each time it comes to; hide them beside a tab.""" + super().present_alone() + alone = self.holds_alone + for part in (*self.shell_lead, *self.shell_tail): + part.display = alone + if not self.banner.is_attached: + return + if alone: + self.banner.play() + else: + self.banner.stop_effect() + class ChannelsSlot(StartsHidden, Widget): """A tab declares where shared navigation belongs; it owns no channel rows.""" - diff --git a/src/toad/widgets/comms_menu.py b/src/toad/widgets/comms_menu.py index 730aeb395..3d8b09da7 100644 --- a/src/toad/widgets/comms_menu.py +++ b/src/toad/widgets/comms_menu.py @@ -104,6 +104,13 @@ class ActionMenu(ContextMenu[Callable[[], object]]): def show(cls, screen, anchor: Region, title: str, items): return super().show(screen, anchor, title, items, callback=cls.run_action) + @classmethod + def offer(cls, screen, anchor: Region, title: str, entries): + """The shared `MenuEntry` rows a right-click opens (a sidebar row's commands, a + relationship's Open and Copy, a tab's moves), as Qt's menu panel shows the same + entries.""" + return cls.show(screen, anchor, title, [(entry.run, entry.label) for entry in entries]) + @staticmethod async def run_action(action): if action is not None: diff --git a/src/toad/widgets/comms_sidebar.py b/src/toad/widgets/comms_sidebar.py index 2a8d2ca0d..91ca20aad 100644 --- a/src/toad/widgets/comms_sidebar.py +++ b/src/toad/widgets/comms_sidebar.py @@ -67,7 +67,7 @@ ) from textual.events import Mount -from toad.sidebar_contracts import ChannelGroupRows, GroupedSidebar +from toad.sidebar_contracts import ChannelGroupRows, FindsOpenViews, GroupedSidebar from toad.sidebar_navigation import SidebarNavigation from toad.widgets.sidebar_tree import CommsRow, ListedRow @@ -354,6 +354,7 @@ class CommsSidebar( SidebarVisibilityObserver, SearchFollower, SelectsTargets, + FindsOpenViews, GroupedSidebar, OpensSelected, ): @@ -490,21 +491,6 @@ def order_groups(self) -> None: self.sort_children(key=lambda child: positions.get(child, len(positions))) self.navigation.apply() - def find_open_views(self) -> dict[str, str]: - """Which open tab shows each thread of this service; the first tab claims it.""" - app = self.app - threads = self.model_state.shown.threads.rows - views: dict[str, str] = {} - for details in app.session_tracker.ordered_sessions: - screen = app.session_navigation.source(details.mode_name) - if screen is None: - continue - name = screen.thread_identity.thread_name() - if (name in threads and name not in views - and screen.belongs_to_wire(self.navigation_root)): - views[name] = details.mode_name - return views - @handles(SessionChangedEvent, ThreadIdentityChanged) async def session_changed(self, event: SessionChangedEvent | ThreadIdentityChanged) -> None: self.open_views = self.find_open_views() diff --git a/src/toad/widgets/conversation.py b/src/toad/widgets/conversation.py index d58e8871d..c1392b2cc 100644 --- a/src/toad/widgets/conversation.py +++ b/src/toad/widgets/conversation.py @@ -118,7 +118,7 @@ from toad.layout_preferences import FollowsLayoutPreferences from toad.client.line_blocks import LineLink from toad.live_output import LiveOutput -from toad.menus import MenuConversation, standard_commands +from toad.menus import MenuConversation from toad.messages import QueueEvidenceOwner from toad.native_style import ( AutoHeight, @@ -1523,7 +1523,7 @@ async def on_change_model(self, event: ChangeModel) -> None: @handles(input_events.UserInputSubmitted) async def on_user_input_submitted(self, event: input_events.UserInputSubmitted, message: CoreEventMessage) -> None: message.stop() - await self.submissions.submit(event) + await self.submissions.received(event)() def queue_controls_changed(self) -> None: """The composer's delivery controls moved; the goal bar redraws its separators.""" @@ -2177,7 +2177,7 @@ def jump_to_latest(self) -> None: async def select_block(self) -> None: cursor = self.navigation.cursor for block in cursor.selected_widgets: - commands = [*standard_commands(cursor), *cursor.get_block_menu()] + commands = Menu.block_commands(cursor, cursor.get_block_menu()) menu = Menu(self, block, commands, focus_owner=self.window) menu.offset = Offset(1, cursor.region.top(self.window.region.y)) await self.mount(menu) diff --git a/src/toad/widgets/history_anchor.py b/src/toad/widgets/history_anchor.py index 64d74cf82..49d401ec9 100644 --- a/src/toad/widgets/history_anchor.py +++ b/src/toad/widgets/history_anchor.py @@ -21,7 +21,7 @@ from toad.block_navigation import ConversationBlock from toad.frame_presentation import FollowsUnrisenRows, UnrisenRows -from toad.history_jump import JumpsToLatest, ReaderWindow +from toad.history_jump import FollowsTail, JumpsToLatest, ReaderWindow from toad.core.projection import MroProjection from toad.no_worker import NO_TIMER, NoTimer from toad.widget_view import WorkspaceHosted @@ -58,7 +58,7 @@ -class HistoryWindow(NativeMethodKeys, WorkspaceHosted, MroProjection[tuple[MessageRowOwner, ...]], +class HistoryWindow(FollowsTail, NativeMethodKeys, WorkspaceHosted, MroProjection[tuple[MessageRowOwner, ...]], ReaderPlacement, ReaderWindow, FollowsUnrisenRows, VerticalScroll, PagingWindow, actions=(ReaderAction,)): """A document owns reader intent and ends its pointer-scroll route. @@ -418,10 +418,7 @@ def follows_tail(self) -> bool: # `can_jump_to_latest` body (returns `not self.follows_tail`) is shared on JumpsToLatest. - def anchor(self, anchor: bool = True) -> None: - changed = self.follows_tail != anchor - if not self._restoring and changed: - self.scroll_revision += 1 + def apply_anchor(self, anchor: bool) -> None: if anchor: # Tail intent replaces earlier motion even while a publication has # no scrollable rows. Native cancellation depends on the scrollbar. @@ -431,11 +428,10 @@ def anchor(self, anchor: bool = True) -> None: # A reader cannot move a window they cannot see: a parked place stays. if self.shown: self.reader_position = self.reader_position.joined_tail() - super().anchor(anchor) + # Textual's own anchor: the next one after the shared step in this window's MRO. + super(FollowsTail, self).anchor(anchor) if not anchor and self.shown and not self._restoring: self.reader_position = self.reader_position.left_tail(self) - if changed: - self.tail_follow_changed() def release_anchor(self) -> None: if not self.follows_tail: diff --git a/src/toad/widgets/session_tabs.py b/src/toad/widgets/session_tabs.py index 2901b543f..ec4dc495d 100644 --- a/src/toad/widgets/session_tabs.py +++ b/src/toad/widgets/session_tabs.py @@ -13,6 +13,8 @@ ) from toad.native_style import KeepsFocusOnClick from toad.widget_actions import ActivationKeys +from toad.widgets.comms_menu import ActionMenu +from toad.session_navigation import TabElement from textual.color import TRANSPARENT from textual.content import Content from textual.css.scalar import Scalar, ScalarOffset, Unit @@ -43,7 +45,7 @@ from textual import on -class SessionLabel(WidgetView, PrimaryActivation, ViewLabel, ChangingText, widgets.Label): +class SessionLabel(TabElement, WidgetView, PrimaryActivation, ViewLabel, ChangingText, widgets.Label): ALLOW_SELECT = False width = AUTO height = Scalar.from_number(1) @@ -107,7 +109,13 @@ def select_session(self) -> None: @on(events.Click) def on_click(self, event: events.Click) -> None: - if event.button == 2: + if event.button == 3: + # The shared tab menu (`SessionNavigation.tab_menu`): Qt's tab offers the same + # entries on a right-click or a held finger. + event.stop() + ActionMenu.offer(self.screen, Region.from_offset(event.screen_offset, (0, 0)), + self.content.plain, self.menu_entries()) + elif event.button == 2: event.stop() self.app.session_navigation.events.publish(session_requests.SessionClose(self.mode_name)) elif event.button == 1: diff --git a/src/toad/widgets/side_bar.py b/src/toad/widgets/side_bar.py index bd4ed3248..acba2702a 100644 --- a/src/toad/widgets/side_bar.py +++ b/src/toad/widgets/side_bar.py @@ -998,13 +998,25 @@ def new_shell(self) -> None: compact=True) self.panels_viewport: SidebarViewport = SidebarViewport() self.layout_controls = SidebarControls() + self.shell_lead, self.shell_tail = self.lead_parts(), self.tail_parts() + + def lead_parts(self) -> tuple[Widget, ...]: + """Widgets above the search box: none, unless a sidebar shows more while it holds the + window alone (`ChannelsSidebar`).""" + return () + + def tail_parts(self) -> tuple[Widget, ...]: + """Widgets below the panels and controls, as `lead_parts`.""" + return () def _compose_shell(self) -> ComposeResult: + yield from self.shell_lead yield self.search_input with self.panels_viewport: yield from self._compose_panels() with self.layout_controls: yield from self._compose_controls() + yield from self.shell_tail @cached_property def toggle_control(self) -> SideBarToggle: @@ -1019,8 +1031,24 @@ def heading(self) -> str: @handles(core_events.SessionSelected, core_events.OpenTabsChanged) async def viewed_changed(self, event: core_events.SessionSelected | core_events.OpenTabsChanged) -> None: + self.present_alone() self.toggle_control.show_heading(self.heading, self.collapsed, self.placement.side) + def validate_collapsed(self, collapsed: bool) -> bool: + """A bar holding the window alone is open whatever its kept fold + (`SidebarLayout.is_collapsed` says the same for Qt's bars).""" + return collapsed and not self.holds_alone + + def present_alone(self) -> None: + """The selected view changed: a bar that holds the window now opens, and one that no + longer does takes its kept fold again (the sole role's fold is the saved + `sidebar.hide`; a bar that never holds the window keeps its own).""" + if self.placement_identity is not self.sidebar_layout.sole_role: + return + self.collapsed = SETTINGS.sidebar.hide.bind(self.app.saved_settings.state).value + self.invalidate_controls() + self.app.workspace_chrome.refresh_layout() + @cached_property def resize_handle(self) -> SidebarResizeHandle: return SidebarResizeHandle(self.placement.side) @@ -1087,7 +1115,8 @@ async def _hydrate_panels(self) -> None: # it finds midway: stopping left panels mounted without their controls and no # state that would ever finish them. Leaving the view cancels this worker. await self.content_stack.mount_all( - (self.search_input, self.panels_viewport, self.layout_controls)) + (*self.shell_lead, self.search_input, self.panels_viewport, self.layout_controls, + *self.shell_tail)) await self.panels_viewport.mount_all(self._compose_panels()) await self.layout_controls.mount_all(self._compose_controls()) self.panel_state = LoadedPanels() @@ -1154,12 +1183,17 @@ def present_controls(self) -> bool: slider = self.extent_slider if previous.controls_changed(current): edge = placement.side - self.content_stack.styles.padding = edge.content_padding() + self.content_stack.styles.padding = self.content_padding() self.toggle_control.set_collapsed(self.collapsed, edge) + # Holding the window alone there is nothing beside the bar to fold it for or to + # grip: only its content shows. + alone = self.holds_alone + self.toggle_control.display = not alone + self.layout_controls.display = self.controls_wanted and not alone handle = self.resize_handle edge.size_handle(handle) handle.styles.dock = edge.opposite().dock - handle.display = not self.collapsed + handle.display = not self.collapsed and not alone self.split_handle.display = current.presentation.leads_band if self.panels_loaded: self.present_extent_track(slider) @@ -1175,7 +1209,8 @@ def sidebar_layout(self) -> SidebarLayout: return self.app.sidebar_layout def toggle_controls(self) -> None: - self.layout_controls.display = not self.layout_controls.display + self.controls_wanted = not self.controls_wanted + self.layout_controls.display = self.controls_wanted and not self.holds_alone @property def client(self) -> ToadApp: diff --git a/src/toad/widgets/sidebar_tree.py b/src/toad/widgets/sidebar_tree.py index aa859f1b5..cb7165b38 100644 --- a/src/toad/widgets/sidebar_tree.py +++ b/src/toad/widgets/sidebar_tree.py @@ -5,7 +5,7 @@ import asyncio from abc import ABC, abstractmethod from collections import Counter -from collections.abc import Iterable +from collections.abc import Callable, Iterable from contextlib import contextmanager from functools import ( partial, @@ -48,8 +48,6 @@ from textual.worker import Worker from textual.widgets import Static -from toad.client.commands import ViewLocalCommand -from toad.command_catalog import CommandCatalog from toad.core.events import SessionSelected from toad.native_style import EllipsisOverflow, NoWrap, PointerCursor, TwoRows from toad.no_worker import NoWorker @@ -65,7 +63,7 @@ from toad.widgets.comms_menu import ActionMenu from toad.tone_paint import AlternatingTone from toad.widget_actions import OpenSelectedAction, OpensSelected -from toad.client.sidebar_lines import DetailedLine, HeaderLine, MemberGroupLine, RowTree, TargetLine +from toad.client.sidebar_lines import DetailedLine, HeaderLine, LineMenuTree, MemberGroupLine, RowTree, TargetLine class TargetTreeMember(HiddenActions): @@ -522,8 +520,8 @@ def _apply_search(self, value: str) -> None: group.sync_members(frozenset(group.member_keys)) -class TargetTree(RowTree, HiddenActions, VisibleActions, StepsVerticalCursor, MovesHorizontalCursor, Vertical, - scopes={HiddenActions: (CursorCommand,)}): +class TargetTree(LineMenuTree, RowTree, HiddenActions, VisibleActions, StepsVerticalCursor, MovesHorizontalCursor, + Vertical, scopes={HiddenActions: (CursorCommand,)}): """Common row keyboard mechanics; specialized trees own data and state.""" navigation_groups: Iterable[SidebarGroup] @@ -571,9 +569,31 @@ def reconcile_members(self): def reconciliation_tree(self): return self - @abstractmethod def show_row_menu(self, row: CommsRow, offset: Offset) -> None: - ... + """Draw the line's own menu (`TargetLine.menu_entries`) at the pointer: Qt's menu + panel draws the same entries for the same line.""" + self.pointer_select(row, menu=True) + title, screen, source = self.menu_title(row), self.app.screen, self.app.selected_session + current = self.menu_still_current(row) + + async def read(): + entries = await row.menu_entries() + if (not self.is_attached or self.app.selected_session is not source + or self.app.screen is not screen or not current()): + return + ActionMenu.offer(screen, Region.from_offset(offset, (0, 0)), title, entries) + + self.run_worker(read(), name='target-menu', group='target-menu', exclusive=True) + + def menu_title(self, row: CommsRow) -> str: + return row.target_name + + def menu_still_current(self, row: CommsRow) -> Callable[[], bool]: + """Whether the menu read for `row` may still be shown once it is read.""" + return lambda: True + + def copy_name(self, name: str) -> None: + self.app.copy_to_clipboard(name) def row_selected(self, row: CommsRow) -> bool: """A tree that keeps no selected set selects no row.""" @@ -679,6 +699,10 @@ def show_menu(self, sidebar: TargetTree, offset: Offset) -> None: def context_activation(self, offset: Offset) -> None: self.show_menu(self.navigation_tree, offset) + @property + def menu_tree(self) -> TargetTree: + return self.navigation_tree + can_focus = True @@ -751,23 +775,12 @@ class TargetMenuTree(SidebarModelView, TargetTree): def row_menu_context(self, row: CommsRow): raise NotImplementedError - def show_row_menu(self, row: CommsRow, offset: Offset) -> None: - self.pointer_select(row, menu=True) - ctx = self.row_menu_context(row) - selected_screen = self.app.screen - source = self.app.selected_session - - async def read(): - choices = (await CommandCatalog.read(ctx.app, (), ctx.acquired(), ViewLocalCommand)).target_choices - if (not self.is_attached or self.app.selected_session is not source - or not self.model_state.serves(ctx.observed.root) - or self.app.screen is not selected_screen): - return - ActionMenu.show(selected_screen, Region.from_offset(offset, (0, 0)), ctx.title, - [(partial(ctx.execute_command, command), command.label(ctx)) - for command in choices]) + def menu_title(self, row: CommsRow) -> str: + return self.row_menu_context(row).title - self.run_worker(read(), name='target-menu', group='target-menu', exclusive=True) + def menu_still_current(self, row: CommsRow) -> Callable[[], bool]: + root = self.row_menu_context(row).observed.root + return lambda: self.model_state.serves(root) class SelectsTargets(TargetTree): diff --git a/src/toad/widgets/thread_comms.py b/src/toad/widgets/thread_comms.py index 2a3bd3a66..3a51d4a3f 100644 --- a/src/toad/widgets/thread_comms.py +++ b/src/toad/widgets/thread_comms.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from collections.abc import Callable from agent_comms.display_order import ThreadSort from agent_comms.registry.relationships import ( @@ -19,12 +20,13 @@ from textual.content import Content from textual.events import Mount, Show, Unmount -from textual.geometry import Offset, Region + from textual.widgets import Static from toad.category_filter import CategoryFilterView from toad.client.connection import Observing -from toad.client.relationship_row_menu import entry_target, menu_entries_for_row +from toad.client.relationship_row_menu import entry_target +from toad.client.sidebar_lines import RelationshipLine from toad.core import events as core_events from toad.native_style import ( AutoHeight, @@ -45,7 +47,6 @@ from toad.thread_identity import SessionIdentity, ThreadIdentity from toad.widget_actions import OpensSelected, WidgetAction from toad.widgets.checkbox import Checkbox -from toad.widgets.comms_menu import ActionMenu from toad.widgets.comms_sidebar import ThreadStatusRow from toad.client.sort_control import RelationshipOrder from toad.client.sort_control import ThreadSortForm @@ -119,7 +120,7 @@ def apply(self, context: RelationshipRow) -> None: context.app.copy_to_clipboard(context.target_name) -class RelationshipRow(ThreadStatusRow, actions=(CopyIdentityAction,)): +class RelationshipRow(RelationshipLine, ThreadStatusRow, actions=(CopyIdentityAction,)): available = True entry: RelationshipEntry | None = None @@ -576,9 +577,8 @@ async def _navigate_current(self, group_key, expected, generation): return self.open_target(entry_target(current)) - def show_row_menu(self, row: RelationshipRow, offset: Offset) -> None: - self.pointer_select(row, menu=True) - target, entry, generation = row.target_name, row.entry, self._generation + def relationship_opener(self, row: RelationshipRow) -> Callable[[], object]: + entry, generation = row.entry, self._generation def open_selected(): # Menus hold an identity, not a row index that live sorting or @@ -586,10 +586,4 @@ def open_selected(): if generation == self._generation and row.is_attached and row.available: self.request_navigation(row, entry=entry, generation=generation) - entries = menu_entries_for_row( - target_name=target, - copy=self.app.copy_to_clipboard, - open_callback=open_selected if row.available else None, - ) - items = [(e.run, e.label) for e in entries] - ActionMenu.show(self.screen, Region.from_offset(offset, (0, 0)), target, items) + return open_selected diff --git a/tests/model/test_menu_owners.py b/tests/model/test_menu_owners.py new file mode 100644 index 000000000..0a732162a --- /dev/null +++ b/tests/model/test_menu_owners.py @@ -0,0 +1,108 @@ +"""Each element's context menu is declared once, on the shared parent both frontends' +elements inherit, and a toolkit only draws it (Tristan, 2026-11-18: "they shouldn't EVEN +BE ABLE TO DRIFT APART"). + +| element | declared by | Textual | Qt | +|---------------------------|--------------------------------------|--------------------|----------------------| +| channel / thread line | `TargetLine.menu_entries` | `CommsRow` | `ConversationRow` | +| Comms relationship line | `RelationshipLine.menu_entries` | `RelationshipRow` | `QtRelationshipItem` | +| open tab | `TabElement.menu_entries` | `SessionLabel` | `QtTabAt` | +| history block | `BlockMenu.block_commands` | `Menu` | `QtMenu` | + +A toolkit that built its own list instead fails here: it either calls an owner's +ingredients itself, defines the contract method, spells a declared entry, or its element +stops inheriting the declaring parent. +""" + +import ast +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[2] / "src" / "toad" +TOOLKITS = ("qt", "widgets", "screens") + +# The ingredients of a declared menu: only its declaring owner calls them. +INGREDIENTS = {"standard_commands", "menu_entries_for_row", "pointer_menu", "tab_menu"} +# The contract method a toolkit element inherits and never defines. +CONTRACT = "menu_entries" +# Entries a declared menu spells; a toolkit spelling one is a parallel list. +DECLARED_LABELS = {"Open", "Copy name", "Move left", "Move right", "Close tab"} +# Each frontend element and the parent that declares its menu. +ELEMENTS = { + ("widgets/sidebar_tree.py", "CommsRow"): "TargetLine", + ("qt/window.py", "ConversationRow"): "TargetLine", + ("widgets/thread_comms.py", "RelationshipRow"): "RelationshipLine", + ("qt/thread_comms_panel.py", "QtRelationshipItem"): "RelationshipLine", + ("widgets/session_tabs.py", "SessionLabel"): "TabElement", + ("qt/window.py", "QtTabAt"): "TabElement", + ("widgets/menu.py", "Menu"): "BlockMenu", + ("qt/menu.py", "QtMenu"): "BlockMenu", +} + + +def toolkit_modules(): + for toolkit in TOOLKITS: + for path in sorted((SOURCE / toolkit).rglob("*.py")): + yield path, ast.parse(path.read_text(), str(path)) + + +def called_name(call: ast.Call) -> str: + function = call.func + return function.attr if isinstance(function, ast.Attribute) else getattr(function, "id", "") + + +def test_no_toolkit_assembles_a_declared_menu() -> None: + found = [ + f"{path.relative_to(SOURCE)}:{node.lineno} calls {called_name(node)}" + for path, tree in toolkit_modules() + for node in ast.walk(tree) + if isinstance(node, ast.Call) and called_name(node) in INGREDIENTS + ] + assert not found, "a toolkit builds a menu its element's parent declares:\n" + "\n".join(found) + + +def test_no_toolkit_element_defines_the_menu_contract() -> None: + found = [ + f"{path.relative_to(SOURCE)}:{node.lineno} {owner.name}.{CONTRACT}" + for path, tree in toolkit_modules() + for owner in ast.walk(tree) if isinstance(owner, ast.ClassDef) + for node in owner.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == CONTRACT + ] + assert not found, "a toolkit element overrides its declared menu:\n" + "\n".join(found) + + +def test_no_toolkit_spells_a_declared_entry() -> None: + found = [ + f"{path.relative_to(SOURCE)}:{node.lineno} {node.value!r}" + for path, tree in toolkit_modules() + for call in ast.walk(tree) + if isinstance(call, ast.Call) and called_name(call) == "MenuEntry" + for node in ast.walk(call) + if isinstance(node, ast.Constant) and node.value in DECLARED_LABELS + ] + assert not found, "a toolkit spells an entry a shared parent declares:\n" + "\n".join(found) + + +def test_every_element_inherits_its_declared_menu() -> None: + missing = [] + for (module, name), parent in ELEMENTS.items(): + tree = ast.parse((SOURCE / module).read_text()) + cls = next((node for node in ast.walk(tree) if isinstance(node, ast.ClassDef) and node.name == name), None) + bases = {getattr(base, "id", getattr(base, "attr", "")) for base in (cls.bases if cls else ())} + if cls is None or parent not in bases | indirect_bases(tree, bases): + missing.append(f"{module}:{name} does not inherit {parent}") + assert not missing, "\n".join(missing) + + +def indirect_bases(tree: ast.Module, bases: set[str]) -> set[str]: + """Bases of bases declared in the same module (CommsRow's subclasses inherit through it).""" + classes = {node.name: node for node in ast.walk(tree) if isinstance(node, ast.ClassDef)} + seen, pending = set(), list(bases) + while pending: + name = pending.pop() + if name in seen or name not in classes: + continue + seen.add(name) + pending.extend(getattr(base, "id", getattr(base, "attr", "")) for base in classes[name].bases) + return {getattr(base, "id", getattr(base, "attr", "")) + for name in seen for base in classes[name].bases} diff --git a/tests/support/driver_effect_frame_app.py b/tests/support/driver_effect_frame_app.py index 7fb099279..b6b3336ed 100644 --- a/tests/support/driver_effect_frame_app.py +++ b/tests/support/driver_effect_frame_app.py @@ -18,7 +18,6 @@ from toad.cli import main from toad.constants import WELCOME from toad.frame_presentation import AnimationEffects, EffectRunning -from toad.screens.welcome import WelcomeEntries from toad.widgets.comms_sidebar import ThreadStatusRow from ui_theme.effects import NAME_WAVE @@ -33,10 +32,11 @@ async def exercise(options, lifetime: ApplicationLifetime) -> None: await app.wait_operations(ApplicationStart) await app.select_session(WELCOME) pilot = Pilot(app) - entries = app.selected_session.query_one(WelcomeEntries) - while not entries.model_state.shows_model() or entries.model_state.shown.observation.shows_status(): + # No tab: the comms sidebar holds the window and lists the threads. + roster = app.workspace_chrome.channels.roster + while not roster.model_state.shows_model() or roster.model_state.shown.observation.shows_status(): await pilot.pause() - rows = tuple(app.selected_session.query(ThreadStatusRow)) + rows = tuple(roster.query(ThreadStatusRow)) remaining = max((fade.remaining(0) for row in rows for fade in row.text_fades), default=0) assert remaining is not None await asyncio.sleep(remaining + 1) diff --git a/tests/support/keymap_discovery.py b/tests/support/keymap_discovery.py index d3c7c21f4..618c9d19e 100644 --- a/tests/support/keymap_discovery.py +++ b/tests/support/keymap_discovery.py @@ -1,4 +1,5 @@ -"""Run as its own interpreter: keymap discovery imports a screen nothing in it has opened. +"""Run as its own interpreter: keymap discovery catalogues the keys of a view nothing in it +has opened, once the frontend has imported its views. tests/textual/test_keymap_discovery.py starts it with `python -m`, because the app test template imports every toad module before it forks a test. @@ -9,11 +10,13 @@ from toad.key_modes import KeyMode, Standard from toad.keymap import KeymapCatalog, KeymapRow -assert "toad.screens.welcome" not in sys.modules +assert "toad.widgets.channels_sidebar" not in sys.modules +# The frontend imports the views it keys before reading the keymap (`KeymapCatalog.capture`): +# the comms sidebar's keys while it holds the window are catalogued though nothing opened it. +import toad.app # noqa: E402,F401 +from toad.widgets.channels_sidebar import SoleNewSessionAction # noqa: E402 catalog = KeymapCatalog.capture(tuple(KeyMode.members_with(KeyMode))) -assert "toad.screens.welcome" in sys.modules -from toad.screens.welcome import WelcomeStartSession # noqa: E402 - discovery imported it -row = KeymapRow.of(WelcomeStartSession(), Standard) -assert catalog.require(row.declaration).key_title() == WelcomeStartSession().key_title() -assert catalog.defaults(row) == WelcomeStartSession.keys[Standard.binding_mode()] +row = KeymapRow.of(SoleNewSessionAction(), Standard) +assert catalog.require(row.declaration).key_title() == SoleNewSessionAction().key_title() +assert catalog.defaults(row) == SoleNewSessionAction.keys[Standard.binding_mode()] diff --git a/tests/textual/test_menu_parity.py b/tests/textual/test_menu_parity.py new file mode 100644 index 000000000..f59b3814c --- /dev/null +++ b/tests/textual/test_menu_parity.py @@ -0,0 +1,66 @@ +"""Textual-facing: a right-click draws exactly the element's declared menu, and nothing of its +own (`TargetLine.menu_entries`, `TabElement.menu_entries`). Qt's `menu_parity` drive checks +Qt draws the same declared entries for the same elements; `tests/model/test_menu_owners.py` +keeps either toolkit from building its own.""" +from toad.widgets.comms_menu import ContextMenu +from toad.widgets.comms_sidebar import CommsSidebar +from toad.widgets.session_tabs import SessionLabel, SessionsTabs + + +def drawn(app) -> list[str]: + options = app.screen.options + return [str(options.get_option_at_index(index).prompt) for index in range(options.option_count)] + + +async def right_click_menu(ui, widget) -> list[str]: + app, pilot = ui.textual + widget.scroll_visible(animate=False) + await ui.step() + assert await pilot.click(widget, button=3) + await ui.until(lambda: isinstance(app.screen, ContextMenu), why="the element's menu") + labels = drawn(app) + await pilot.press("escape") + await ui.until(lambda: not isinstance(app.screen, ContextMenu), why="the menu to close") + return labels + + +async def test_sidebar_lines_and_tabs_draw_their_declared_menus(workspace): + workspace.thread("owner", "team", title="Menu parity") + async with workspace.app() as ui: + app, _pilot = ui.textual + sidebar = app.workspace_chrome.channels + if sidebar.collapsed: + sidebar.toggle() + tree = sidebar.query_one(CommsSidebar) + await ui.until(lambda: "#team" in tree.groups and tree.groups["#team"].member_container.is_mounted, + why="the #team group") + group = tree.groups["#team"] + if not group.expanded: + group.toggle_members() + await ui.until(lambda: "owner" in group.rows and group.rows["owner"].is_mounted, why="the owner line") + + thread = group.rows["owner"] + thread_menu = await right_click_menu(ui, thread) + assert thread_menu == [entry.label for entry in await thread.menu_entries()] + # The target's own commands, not the relationship row's Open / Copy name. + assert thread_menu and thread_menu != ["Open", "Copy name"] + + channel = group.row + channel_menu = await right_click_menu(ui, channel) + assert channel_menu == [entry.label for entry in await channel.menu_entries()] + assert channel_menu + + # A tab: the thread opened. The home view is no tab (the sidebar holds the window). + thread.scroll_visible(animate=False) + await ui.step() + assert await _pilot.click(thread) + + def selected_label(): + tabs = app.screen.query(SessionsTabs) + return tabs.first().query_one_optional(f"#{ui.selected_tab}", SessionLabel) if tabs else None + + await ui.until(lambda: selected_label() is not None, why="the thread's tab") + tab = selected_label() + tab_menu = await right_click_menu(ui, tab) + assert tab_menu == [entry.label for entry in tab.menu_entries()] + assert tab_menu[-1] == "Close tab" diff --git a/tests/textual/test_screen_geometry.py b/tests/textual/test_screen_geometry.py index fb6ce9906..bdba2c582 100644 --- a/tests/textual/test_screen_geometry.py +++ b/tests/textual/test_screen_geometry.py @@ -22,7 +22,7 @@ from toad.screens.modal import ModalPanel from toad.screens.queue import QueueActions, QueueInspection, QueuePanel from toad.screens.team import HudRows, TeamClose, TeamPage, TeamPanel -from toad.screens.welcome import WelcomeColumn, WelcomeScreen +from toad.screens.welcome import WelcomeScreen from toad.widgets.history_anchor import HistoryWindow SIZE = WIDTH, HEIGHT = 100, 40 @@ -115,14 +115,13 @@ async def test_goal_history_is_a_centred_95_percent_panel_with_close_docked_unde assert document.region.bottom < close.region.y, facts -async def test_welcome_column_is_64_wide_and_centred_beside_the_sidebar(workspace): +async def test_with_no_tab_the_comms_sidebar_is_the_whole_row_and_the_home_view_takes_none(workspace): async with workspace.app(size=(120, 40), session=False) as ui: await ui.until_shows("n new session") welcome = ui.app.screen.query_one(WelcomeScreen) - column, sidebar = welcome.query_one(WelcomeColumn), ui.app.workspace_chrome.channels - space, region = welcome.content_region, column.region - facts = {"welcome": space, "column": region, "sidebar": sidebar.region} - assert region.x >= sidebar.region.right, facts - assert region.width == 64, facts - assert abs((region.x - space.x) - (space.right - region.right)) <= 1, facts - assert abs((region.y - space.y) - (space.bottom - region.bottom)) <= 1, facts + sidebar = ui.app.workspace_chrome.channels + await ui.until(lambda: sidebar.region.width == 120, why="the sidebar to take the whole row") + facts = {"home": welcome.region, "sidebar": sidebar.region} + assert sidebar.region.x == 0 and sidebar.region.width == 120, facts + # The home view is placed past the sidebar's right edge: off the screen. + assert welcome.region.x >= sidebar.region.right == ui.app.screen.size.width, facts diff --git a/tests/textual/test_send_never_vanishes.py b/tests/textual/test_send_never_vanishes.py new file mode 100644 index 000000000..482377175 --- /dev/null +++ b/tests/textual/test_send_never_vanishes.py @@ -0,0 +1,82 @@ +"""A sent message is on screen at every frame from Send until the history draws it: in the +delivery preview above the prompt, then in the history. Tristan, 2026-11-18: "the queue shows +up and then the message gets submitted and the queue disappears, but then there's a gap where +I don't see the queue and I don't see the message on the screen".""" + +from types import MethodType + +from toad.prompt_actions import SubmitAction + + +def region_text(lines: list[str], region) -> str: + return "\n".join(line[region.x:region.right] for line in lines[region.y:region.bottom]) + + +async def test_every_frame_shows_a_sent_message_in_the_preview_or_the_history(workspace): + from toad.widgets.comms_chat import CommsChatView + from toad.widgets.conversation import Window + from toad.widgets.prompt import QueueSummary + + workspace.thread("peer") + async with workspace.app(size=(110, 32)) as ui: + await ui.open_direct("peer", actor=workspace.viewer) + chat = ui.app.selected_session.query_one(CommsChatView) + window, summary = chat.query_one(Window), chat.query_one(QueueSummary) + editor = chat.prompt.prompt_text_area + app, _pilot = ui.textual + sent: list[str] = [] + frames: dict[str, list[tuple[bool, bool]]] = {} + shown = type(app)._display + + def display(self, screen, renderable) -> None: + shown(self, screen, renderable) + lines = ui.visible_lines() + history = region_text(lines, window.region) + preview = region_text(lines, summary.region) if summary.display else "" + for marker in sent: + track = frames.setdefault(marker, []) + if not (track and track[-1][1]): + track.append((marker in preview, marker in history)) + + app._display = MethodType(display, app) + try: + for index in range(10): + marker = f"NEVER_VANISHES_{index}" + await ui.write_draft(marker) + sent.append(marker) + editor.schedule_submission(SubmitAction()) + await ui.until(lambda: frames.get(marker) and frames[marker][-1][1], + why=f"{marker} drawn in the history") + finally: + del app._display + gaps = {marker: sum(1 for preview, history in track if not (preview or history)) + for marker, track in frames.items()} + assert not any(gaps.values()), f"frames showing a sent message nowhere: {gaps}" + await ui.until(lambda: not chat.submissions.previewed, why="every drawn message retired from the preview") + + +async def test_a_sent_message_scrolled_past_by_a_long_reply_leaves_the_preview(workspace): + """Shown means the history drew it, above the window's bottom edge: a long reply landing in + the same read pushes it off the top, and it still leaves the preview.""" + from unittest.mock import patch + + from toad.client.bus_submission import BusSubmissionExecution + from toad.core.input_events import UserInputSubmitted + from toad.widgets.comms_chat import CommsChatView + + comms = workspace.comms + workspace.thread("peer") + commit = BusSubmissionExecution.commit + + async def commit_then_reply(execution, *args, **kwargs): + sent = await commit(execution, *args, **kwargs) + comms.messaging.send("peer", workspace.viewer, "\n\n".join(f"reply line {n}" for n in range(80))) + return sent + + async with workspace.app(size=(110, 24)) as ui: + await ui.open_direct("peer", actor=workspace.viewer) + chat = ui.app.selected_session.query_one(CommsChatView) + with patch.object(BusSubmissionExecution, "commit", commit_then_reply): + await chat.submissions.received(UserInputSubmitted("SCROLLED_PAST_PREVIEW"))() + await ui.until(lambda: ui.shows("reply line 79") and not chat.submissions.previewed, + why="the long reply drawn and the sent message gone from the preview") diff --git a/tests/textual/test_sidebar_layout_policy.py b/tests/textual/test_sidebar_layout_policy.py index 7e49e2afc..81520f543 100644 --- a/tests/textual/test_sidebar_layout_policy.py +++ b/tests/textual/test_sidebar_layout_policy.py @@ -229,3 +229,21 @@ def test_the_thread_bar_names_the_viewed_tab_and_the_channels_bar_its_scope(): for edge in EDGES: text = edge.toggle_text(False, "#comms") assert "#comms" in text.replace("\n", "") and text.count(edge.toggle_symbol(False)) >= 2 + + +def test_with_no_tab_the_comms_bar_is_open_and_keeps_the_fold_it_returns_to(): + """While no tab is shown the comms bar holds the window: open whatever its kept fold, the + only bar placed, the content given nothing. A fold kept meanwhile (a frontend applying its + saved setting at start) is what the first tab shows.""" + alone = [True] + layout = SidebarLayout(SavedSettings(), LocalTerminal, alone=lambda: alone[0]) + assert layout.holds_alone(ChannelsSidebarPlacement) + assert not layout.holds_alone(ThreadSidebarPlacement) + assert not layout.is_collapsed(ChannelsSidebarPlacement) + assert not layout.set_collapsed(ChannelsSidebarPlacement, False), "nothing shown changed" + assert layout.kept_collapsed(ChannelsSidebarPlacement) is False, "the kept fold was recorded" + layout.set_collapsed(ChannelsSidebarPlacement, True) + assert not layout.is_collapsed(ChannelsSidebarPlacement) + alone[0] = False + assert layout.is_collapsed(ChannelsSidebarPlacement) + assert not layout.holds_alone(ChannelsSidebarPlacement) diff --git a/tests/textual/test_sole_sidebar.py b/tests/textual/test_sole_sidebar.py new file mode 100644 index 000000000..e09407b42 --- /dev/null +++ b/tests/textual/test_sole_sidebar.py @@ -0,0 +1,255 @@ +"""Toad starts with no tab open, and while none is the comms sidebar holds the whole window, +carrying what the welcome page did: Toad's banner, the project, the buses and the key hints. +The first tab gives it back its placement, and closing the last tab gives it the window again. +Qt's `sole_sidebar` drive walks the same three states.""" + +import os +from dataclasses import replace + +from agent_comms.messaging.channel_targets import CommandTarget +from agent_comms.messaging.read_basis import NamedViewer +from agent_comms.projects.checkouts import Checkout +from agent_comms.registry.thread_model import DeclaredModel +from agent_comms.registry.threads import ExternalThread, NativeThread +from agent_comms.transport.connector_store import HeldUiProfiles +from agent_comms.transport.tailnet_buses import TailnetPeer +from support.agents import peer +from support.roots import Roots +from support.ui import TextualUi + +from toad.client.application import BusDiscovery +from toad.client.bus_selection import LocalBus +from toad.constants import ALL_COMMS_TARGET +from toad.launch_binding import AgentAttached +from toad.screens.bus_choice import BusRows +from toad.widgets.channels_sidebar import ( + ChannelsSidebar, + SidebarBanner, + SidebarBuses, + SidebarHeading, + SidebarHints, + SidebarLocationNote, +) +from toad.widgets.sidebar_tree import CommsRow + +HINT = "n new session" +PARTS = (SidebarBanner, SidebarLocationNote, SidebarBuses, SidebarHints) + + +def shot(ui: TextualUi, name: str) -> None: + """Save the frame where TOAD_SHOTS names, for a side-by-side with Qt's drive.""" + folder = os.environ.get("TOAD_SHOTS") + if folder: + app, _ = ui.textual + app.save_screenshot(filename=f"{name}.svg", path=folder) + + +def parts_shown(sidebar: ChannelsSidebar) -> dict[str, bool]: + """Whether each part is displayed, its containers up to the sidebar included.""" + def shown(widget) -> bool: + lineage = [widget, *widget.ancestors] + return all(node.display for node in lineage[:lineage.index(sidebar)]) + return {part.__name__: shown(sidebar.query_one(part)) for part in PARTS} + + +def row(sidebar: ChannelsSidebar, name: str) -> CommsRow | None: + return next((row for row in sidebar.roster.query(CommsRow) if row.target_name == name), None) + + +async def alone(ui: TextualUi, *names: str) -> ChannelsSidebar: + """The comms sidebar holds the window with the welcome's parts, listing ``names``.""" + app, _ = ui.textual + sidebar = app.workspace_chrome.channels + await ui.until_shows(HINT) + await ui.until(lambda: sidebar.holds_alone and not sidebar.collapsed + and sidebar.region.width == app.screen.size.width + and all(row(sidebar, name) is not None for name in (ALL_COMMS_TARGET, *names)), + why="the comms sidebar to hold the whole window with its rows") + assert all(parts_shown(sidebar).values()), parts_shown(sidebar) + await ui.until(lambda: "██" in ui.painted(sidebar.query_one(SidebarBanner)), + why="the banner to be painted at the sidebar's head") + assert not sidebar.toggle_control.display and not sidebar.resize_handle.display + # The buses are in the first screen, above the rows however many threads they list, and + # nothing is drawn over the rows. + screen, rows = app.screen.region, sidebar.panels_viewport.region + buses = sidebar.query_one(SidebarBuses).query_one(BusRows).region + assert screen.contains_region(buses) and buses.bottom <= rows.y, (buses, rows) + assert not sidebar.query_one(SidebarHints).region.overlaps(rows), (sidebar.query_one(SidebarHints).region, rows) + return sidebar + + +async def test_starting_opens_no_tab_and_starts_no_agent(workspace): + workspace.thread("alpha", "team") + async with workspace.app(session=False, binding=AgentAttached(peer("echo"))) as ui: + sidebar = await alone(ui, "alpha") + assert ui.tabs() == () + app, _ = ui.textual + assert not app.workspace_sessions.source.view.matches_launch( + peer("echo").identity, "unopened-session" + ) + assert "Buses" in ui.painted(sidebar.query_one(SidebarBuses)) + assert not workspace.child_processes("echo.py"), "starting Toad started its agent" + assert not workspace.received() + assert workspace.project.name not in workspace.comms.registry.snapshot().threads + shot(ui, "tui-1-alone") + + +async def test_the_first_tab_gives_the_sidebar_its_placement_and_closing_it_gives_the_window_back(workspace): + async with workspace.app(session=False) as ui: + app, _ = ui.textual + sidebar = await alone(ui) + await ui.click(ALL_COMMS_TARGET) + await ui.until(lambda: len(ui.tabs()) == 1 and not sidebar.holds_alone, + why="the first tab to open") + await ui.until(lambda: not any(parts_shown(sidebar).values()), + why="the welcome's parts to leave the sidebar") + assert ui.selected_tab == ui.tabs()[0].identity + assert not ui.shows(HINT) + assert sidebar.toggle_control.display + assert sidebar.region.width < app.screen.size.width + shot(ui, "tui-2-tab") + await ui.close_tab(ui.selected_tab) + await ui.until(lambda: ui.tabs() == (), why="the last tab to close") + sidebar = await alone(ui) + banner = sidebar.query_one(SidebarBanner) + await ui.until(lambda: banner not in app.colours.clock.running.values(), + why="the banner's sweep to finish") + shot(ui, "tui-3-closed") + + +async def test_opening_a_thread_run_elsewhere_opens_its_history_read_as_the_user(workspace): + workspace.comms.registry.declare( + ExternalThread("scribe", frozenset({"team"}), Checkout(workspace.project)) + ) + async with workspace.app(session=False) as ui: + await alone(ui, "scribe") + await ui.click("scribe") + app, _ = ui.textual + await ui.until(lambda: app.selected_session.thread_identity.thread_name() == "scribe", + why="the thread's tab selected") + assert len(ui.tabs()) == 1 + await ui.write_draft("hello scribe") + await ui.press("enter") + + def sent_messages(): + return tuple(message for message in workspace.comms.views.history_page( + CommandTarget.named("scribe"), viewer=NamedViewer(workspace.viewer), + ).messages if message.body == "hello scribe" and message.target == "scribe") + + await ui.until(sent_messages, why="the message on the wire") + assert sent_messages()[0].sender == workspace.viewer + assert not ui.shows(HINT) + + +async def test_closing_the_last_tab_gives_the_window_back_and_stops_its_agent(workspace): + async with workspace.app(session=False, binding=AgentAttached(peer("echo"))) as ui: + await alone(ui) + await ui.new_session() + await ui.until(lambda: len(ui.tabs()) == 1, why="the new session's tab") + await ui.until_agent_ready() + assert not ui.shows(HINT) + await ui.close_tab(ui.selected_tab) + await alone(ui) + assert ui.tabs() == () + await ui.until(lambda: not workspace.child_processes("echo.py"), + why="the closed session's agent to be gone") + + +async def test_going_back_from_the_only_tab_stays_on_it(workspace): + async with workspace.app(session=False) as ui: + await alone(ui) + await ui.click(ALL_COMMS_TARGET) + await ui.until(lambda: len(ui.tabs()) == 1, why="the channel's tab") + channel = ui.selected_tab + await ui.return_to_owner() + assert ui.selected_tab == channel and not ui.shows(HINT) + + +async def test_a_launch_that_names_a_session_opens_it(workspace): + workspace.thread("saved-session", "team") + async with workspace.app(session=False, resume="saved-session") as ui: + await ui.until(lambda: len(ui.tabs()) == 1, why="the named session's tab") + assert ui.selected_tab == ui.tabs()[0].identity + assert not ui.shows(HINT) + + +async def test_a_thread_row_tooltip_names_its_model_by_text(workspace): + thread = NativeThread("alpha", frozenset({"team"}), Checkout(workspace.project)) + workspace.comms.registry.declare(replace(thread, model=DeclaredModel("openai-codex/gpt-6.1-sol"))) + async with workspace.app(session=False) as ui: + sidebar = await alone(ui, "alpha") + assert "openai-codex/gpt-6.1-sol" in str(row(sidebar, "alpha").tooltip).splitlines() + + +async def test_the_sidebar_lists_the_tailnets_buses_and_asks_once_per_window( + workspace, monkeypatch, tmp_path): + """Tristan: "I would like it to show the buses as well so that it would list out the + buses that are available", then "It also didn't list the other buses on the tailnet". + + The section inherits the Open-bus dialog's own listing: this machine's own bus at once, + then the peers the window's one ask of the tailnet found. The sidebar holds the window + whenever no tab is open, so listing them again shows that answer instead of sweeping.""" + + monkeypatch.setattr(HeldUiProfiles, "directory", classmethod(lambda cls: tmp_path)) + tailnet = Roots.of_this_process().tailnet + tailnet.hold(TailnetPeer("desktop", "100.124.133.120", True), 247) + tailnet.held.touch() + + async with workspace.app(session=False) as ui: + app, _ = ui.textual + sidebar = await alone(ui) + buses = sidebar.query_one(SidebarBuses) + # This machine's own bus is listed without asking anyone, so the section is never + # an empty box while the tailnet is still answering. + assert [type(row).__name__ for row in buses.rows] == ["LocalBus"] + assert "Buses" in ui.painted(buses.query_one(SidebarHeading)) + assert LocalBus().label() in ui.painted(buses.query_one(BusRows)) + + tailnet.held.unlink() + await ui.until(lambda: len(buses.rows) == 2, why="the window's ask to answer") + assert buses.rows[-1].label() == "desktop · 247 threads" + assert "desktop · 247 threads" in ui.painted(buses.query_one(BusRows)) + + # Listed again, the buses are what the window found, and nobody is asked. + tailnet.hold(TailnetPeer("laptop", "100.64.0.7", True), 62) + again = SidebarBuses() + await sidebar.content_stack.mount(again) + assert [row.label() for row in again.rows] == ["This machine", "desktop · 247 threads"] + for _ in range(6): + await ui.step() + assert not any(worker.group == BusDiscovery.group and not worker.is_finished + for worker in app.workers), "listing the buses again starts no sweep" + assert len(again.rows) == 2 + + +async def test_the_banner_sweeps_only_while_the_sidebar_holds_a_focused_window(workspace): + async with workspace.app(session=False) as ui: + app, _ = ui.textual + sidebar = await alone(ui) + banner, clock = sidebar.query_one(SidebarBanner), app.colours.clock + await ui.until(lambda: banner.played in banner.effects, why="the banner's sweep to start") + animation = banner.effects[banner.played].animation + assert clock.running.get(animation) is banner and animation.effect is banner.played + + session = await ui.new_session() + await ui.until(lambda: not sidebar.holds_alone, why="the first tab") + await ui.step() + assert banner.played not in banner.effects and banner not in clock.running.values() + + built = banner.played + await ui.close_tab(session) + await ui.until(lambda: banner.played in banner.effects, why="the banner's sweep to play again") + assert banner.played is built, "the frames were built again for the same colour scheme" + + app.app_focus = False + await ui.step() + assert banner.played not in banner.effects and banner not in clock.running.values() + + +async def test_a_finished_sweep_leaves_the_clock(workspace): + async with workspace.app(session=False) as ui: + app, _ = ui.textual + banner = (await alone(ui)).query_one(SidebarBanner) + await ui.until(lambda: banner.played in banner.effects, why="the banner's sweep to start") + await ui.until(lambda: banner not in app.colours.clock.running.values(), why="the sweep to finish") + assert banner.render() == app.colours.paint_text(banner.played.final, None) diff --git a/tests/textual/test_welcome_title_effect.py b/tests/textual/test_welcome_title_effect.py deleted file mode 100644 index fa09eb370..000000000 --- a/tests/textual/test_welcome_title_effect.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Textual-facing: the welcome title's effect is on the animation clock only while the view shows in a focused terminal, and the view's lists observe the sidebar model only then.""" - -from toad.screens.welcome import WelcomeEntries, WelcomeTitle - - -async def test_title_effect_and_list_observation_stop_while_the_view_is_hidden(workspace): - async with workspace.app(session=False) as ui: - app, _ = ui.textual - title, entries = app.screen.query_one(WelcomeTitle), app.screen.query_one(WelcomeEntries) - clock, access = app.colours.clock, app.coordination_access - await ui.until(lambda: title.played in title.effects, why="the title's effect to start") - animation = title.effects[title.played].animation - assert clock.running.get(animation) is title and animation.effect is title.played - assert entries in access.showing_sidebar() - - session = await ui.new_session() - assert title.played not in title.effects and title not in clock.running.values() - assert entries not in access.showing_sidebar() - # The built frames stay; the hidden title shows the last one without a timer. - assert title.render() == app.colours.paint_text(title.played.final, None) - - built = title.played - await ui.close_tab(session) - await ui.until(lambda: title.played in title.effects, why="the title's effect to play again") - assert title.played is built, "the frames were built again for the same colour scheme" - assert entries in access.showing_sidebar() - - app.app_focus = False - await ui.step() - assert title.played not in title.effects and title not in clock.running.values() - - -async def test_finished_title_effect_leaves_the_clock(workspace): - async with workspace.app(session=False) as ui: - app, _ = ui.textual - title = app.screen.query_one(WelcomeTitle) - await ui.until(lambda: title.played in title.effects, why="the title's effect to start") - await ui.until(lambda: title not in app.colours.clock.running.values(), why="the effect to finish") - assert title.render() == app.colours.paint_text(title.played.final, None) diff --git a/tests/textual/test_welcome_view.py b/tests/textual/test_welcome_view.py deleted file mode 100644 index e6f821efa..000000000 --- a/tests/textual/test_welcome_view.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Toad starts with no tab open and shows the welcome view until one is opened.""" - -from dataclasses import replace - -from agent_comms.messaging.channel_targets import CommandTarget -from agent_comms.messaging.read_basis import NamedViewer -from agent_comms.projects.checkouts import Checkout -from agent_comms.registry.thread_model import DeclaredModel -from agent_comms.registry.threads import ExternalThread, NativeThread -from agent_comms.transport.connector_store import HeldUiProfiles -from agent_comms.transport.tailnet_buses import TailnetPeer -from support.agents import peer -from support.roots import Roots -from support.ui import TextualUi - -from toad.client.application import BusDiscovery -from toad.client.bus_selection import LocalBus -from toad.constants import ALL_COMMS_TARGET -from toad.launch_binding import AgentAttached -from toad.screens.bus_choice import BusRows -from toad.screens.welcome import ( - WelcomeBuses, - WelcomeChannels, - WelcomeEntries, - WelcomeHeading, - WelcomeScreen, - WelcomeThreads, -) -from toad.widgets.sidebar_tree import CommsRow - -HINT = "n new session" - - -async def welcome_entries(ui: TextualUi, *threads: str) -> WelcomeEntries: - """Wait for the welcome view's own published rows, not matching sidebar text.""" - app, _ = ui.textual - await ui.until_shows(HINT) - entries = app.screen.query_one(WelcomeEntries) - channels = entries.query_one(WelcomeChannels) - listed_threads = entries.query_one(WelcomeThreads) - await ui.until( - lambda: entries.query_ancestor(WelcomeScreen).is_current - and entries.is_on_screen - and entries.model_state.shows_model() - and ALL_COMMS_TARGET in channels.rows - and channels.rows[ALL_COMMS_TARGET].is_on_screen - and all(name in listed_threads.rows and listed_threads.rows[name].is_on_screen - for name in threads), - why="the welcome channel and requested thread rows to be shown", - ) - assert ui.shows(HINT) - assert WelcomeChannels.TITLE in ui.painted(channels.row) - assert ALL_COMMS_TARGET in ui.painted(channels.rows[ALL_COMMS_TARGET]) - if threads: - assert WelcomeThreads.TITLE in ui.painted(listed_threads.row) - return entries - - -async def focus_row(ui: TextualUi, row: CommsRow) -> None: - """Reach this welcome row with keys, preserving the real navigation path.""" - app, _ = ui.textual - - # Rows mount a step per frame, so the list can still grow while the cursor walks it. - async def reached() -> bool: - if app.focused is row: - return True - await ui.press("down") - return False - - await ui.until(reached, why=f"welcome row {row.target_name!r} reached with Down") - - -async def test_starting_opens_no_tab_and_starts_no_agent(workspace): - workspace.thread("alpha", "team") - async with workspace.app(session=False, binding=AgentAttached(peer("echo"))) as ui: - await welcome_entries(ui, "alpha") - assert ui.tabs() == () - app, _ = ui.textual - assert not app.workspace_sessions.source.view.matches_launch( - peer("echo").identity, "unopened-session" - ) - assert ui.shows(HINT) - assert not workspace.child_processes( - "echo.py" - ), "starting Toad started its agent" - assert not workspace.received() - assert workspace.project.name not in workspace.comms.registry.snapshot().threads - - -async def test_opening_a_channel_opens_its_tab_in_place_of_the_view(workspace): - workspace.thread("alpha", "team") - async with workspace.app(session=False) as ui: - entries = await welcome_entries(ui, "alpha") - await focus_row(ui, entries.query_one(WelcomeChannels).rows[ALL_COMMS_TARGET]) - await ui.press("enter") - await ui.until(lambda: len(ui.tabs()) == 1, why="the channel's tab") - assert ui.selected_tab == ui.tabs()[0].identity - assert not ui.shows(HINT) - - -async def test_opening_a_thread_run_elsewhere_opens_its_history_read_as_the_user( - workspace, -): - - workspace.comms.registry.declare( - ExternalThread( - "scribe", - frozenset({"team"}), - Checkout(workspace.project)) - ) - async with workspace.app(session=False) as ui: - entries = await welcome_entries(ui, "scribe") - await focus_row(ui, entries.query_one(WelcomeThreads).rows["scribe"]) - await ui.press("enter") - app, _ = ui.textual - await ui.until(lambda: app.selected_session.thread_identity.thread_name() == "scribe", - why="the thread's tab selected") - assert len(ui.tabs()) == 1 - await ui.write_draft("hello scribe") - await ui.press("enter") - - def sent_messages(): - return tuple(message for message in workspace.comms.views.history_page( - CommandTarget.named("scribe"), viewer=NamedViewer(workspace.viewer), - ).messages if message.body == "hello scribe" and message.target == "scribe") - - await ui.until(sent_messages, why="the message on the wire") - assert sent_messages()[0].sender == workspace.viewer - assert not ui.shows(HINT) - - -async def test_closing_the_last_tab_shows_the_view_again_and_starts_no_agent(workspace): - async with workspace.app(session=False, binding=AgentAttached(peer("echo"))) as ui: - await welcome_entries(ui) - await ui.new_session() - await ui.until(lambda: len(ui.tabs()) == 1, why="the new session's tab") - await ui.until_agent_ready() - assert not ui.shows(HINT) - await ui.close_tab(ui.selected_tab) - await welcome_entries(ui) - assert ui.tabs() == () - await ui.until( - lambda: not workspace.child_processes("echo.py"), - why="the closed session's agent to be gone", - ) - - -async def test_going_back_from_the_only_tab_stays_on_it(workspace): - async with workspace.app(session=False) as ui: - entries = await welcome_entries(ui) - await focus_row(ui, entries.query_one(WelcomeChannels).rows[ALL_COMMS_TARGET]) - await ui.press("enter") - await ui.until(lambda: len(ui.tabs()) == 1, why="the channel's tab") - channel = ui.selected_tab - await ui.return_to_owner() - assert ui.selected_tab == channel and not ui.shows(HINT) - - -async def test_a_launch_that_names_a_session_opens_it(workspace): - workspace.thread("saved-session", "team") - async with workspace.app(session=False, resume="saved-session") as ui: - await ui.until(lambda: len(ui.tabs()) == 1, why="the named session's tab") - assert ui.selected_tab == ui.tabs()[0].identity - assert not ui.shows(HINT) - - -async def test_a_thread_row_tooltip_names_its_model_by_text(workspace): - - - thread = NativeThread("alpha", frozenset({"team"}), Checkout(workspace.project)) - workspace.comms.registry.declare(replace(thread, model=DeclaredModel("openai-codex/gpt-6.1-sol"))) - async with workspace.app(session=False) as ui: - entries = await welcome_entries(ui, "alpha") - row = entries.query_one(WelcomeThreads).rows["alpha"] - assert "openai-codex/gpt-6.1-sol" in str(row.tooltip).splitlines() - - -async def test_the_splash_lists_the_tailnets_buses_and_asks_once_per_window( - workspace, monkeypatch, tmp_path): - """Tristan: "I would like it to show the buses as well so that it would list out the - buses that are available", then "It also didn't list the other buses on the tailnet". - - The section inherits the Open-bus dialog's own listing: this machine's own bus at once, - then the peers the window's one ask of the tailnet found. The splash shows whenever no - tab is open, so showing it again lists that answer instead of sweeping again. - """ - - monkeypatch.setattr(HeldUiProfiles, "directory", classmethod(lambda cls: tmp_path)) - tailnet = Roots.of_this_process().tailnet - tailnet.hold(TailnetPeer("desktop", "100.124.133.120", True), 247) - tailnet.held.touch() - - # session=False, like every other splash case here: the splash is what shows when no - # tab is open, and workspace.app() opens one. - async with workspace.app(session=False) as ui: - app, _ = ui.textual - entries = await welcome_entries(ui) - buses = entries.query_one(WelcomeBuses) - # This machine's own bus is listed without asking anyone, so the section is never - # an empty box while the tailnet is still answering. - assert [type(row).__name__ for row in buses.rows] == ["LocalBus"] - assert "Buses" in ui.painted(buses.query_one(WelcomeHeading)) - assert LocalBus().label() in ui.painted(buses.query_one(BusRows)) - - tailnet.held.unlink() - await ui.until(lambda: len(buses.rows) == 2, why="the window's ask to answer") - assert buses.rows[-1].label() == "desktop · 247 threads" - assert "desktop · 247 threads" in ui.painted(buses.query_one(BusRows)) - - # Shown again, the splash lists what the window found and asks nobody. - tailnet.hold(TailnetPeer("laptop", "100.64.0.7", True), 62) - again = WelcomeBuses() - await entries.mount(again) - assert [row.label() for row in again.rows] == ["This machine", "desktop · 247 threads"] - for _ in range(6): - await ui.step() - assert not any(worker.group == BusDiscovery.group and not worker.is_finished - for worker in app.workers), "showing the splash starts no sweep" - assert len(again.rows) == 2 diff --git a/tools/android/keepalive/java/org/qtproject/qt/android/QtActivityResults.java b/tools/android/keepalive/java/org/qtproject/qt/android/QtActivityResults.java new file mode 100644 index 000000000..9c961bd53 --- /dev/null +++ b/tools/android/keepalive/java/org/qtproject/qt/android/QtActivityResults.java @@ -0,0 +1,21 @@ +package org.qtproject.qt.android; + +import android.content.Intent; + +/** + * Qt's activity-result entry for the APK's activity. QtActivityBase.onActivityResult hands + * each result to Qt (QtNative.onActivityResult, package-private) after Activity's own; + * python-for-android's PythonActivity overrides it to notify only its own listeners and never + * calls super, so Qt's receivers (the native file dialog's among them) never heard an answer. + * ToadActivity calls this in its place. It lives in Qt's package because that entry is + * package-private. + */ +public final class QtActivityResults { + + private QtActivityResults() { + } + + public static void deliver(int requestCode, int resultCode, Intent data) { + QtNative.onActivityResult(requestCode, resultCode, data); + } +} diff --git a/tools/android/keepalive/java/org/toadcomms/AttachChooser.java b/tools/android/keepalive/java/org/toadcomms/AttachChooser.java new file mode 100644 index 000000000..6e333c1c5 --- /dev/null +++ b/tools/android/keepalive/java/org/toadcomms/AttachChooser.java @@ -0,0 +1,106 @@ +package org.toadcomms; + +import android.app.Activity; +import android.content.ClipData; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.MediaStore; +import android.util.Log; +import android.util.SparseArray; + +/** + * What a composer's Attach opens on the phone: Android's own chooser - the apps that give a + * file (Files, Photos, Drive) and the camera - in place of the document picker alone. + * + * Attach opens Qt's file dialog (toad.qt.file_pickers); on Android Qt answers it with an + * ACTION_OPEN_DOCUMENT intent through the activity. ToadActivity offers that intent here: it + * becomes ACTION_GET_CONTENT for the same types in a chooser, with a camera capture into a + * new MediaStore photo as the chooser's first choice. The answer goes back to Qt's dialog as + * a content URI either way: the app's own, or the photo the camera wrote, which it returns no + * URI for. Qt's dialog reads it as it reads any picked file. + */ +final class AttachChooser { + + private static final String TAG = "toadcomms"; + + private final Activity activity; + /** The photo each offered request's camera would write, by request code. */ + private final SparseArray photos = new SparseArray<>(); + + AttachChooser(Activity activity) { + this.activity = activity; + } + + /** The intent to start for `intent`: a file dialog's document request becomes the chooser. */ + Intent offered(Intent intent, int requestCode) { + if (intent == null || !Intent.ACTION_OPEN_DOCUMENT.equals(intent.getAction()) + || !intent.hasCategory(Intent.CATEGORY_OPENABLE)) { + return intent; + } + Intent content = new Intent(Intent.ACTION_GET_CONTENT) + .addCategory(Intent.CATEGORY_OPENABLE) + .setType(intent.getType() != null ? intent.getType() : "*/*"); + if (intent.hasExtra(Intent.EXTRA_MIME_TYPES)) { + content.putExtra(Intent.EXTRA_MIME_TYPES, intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)); + } + content.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)); + Intent chooser = Intent.createChooser(content, "Attach"); + Uri photo = newPhoto(); + if (photo != null) { + Intent capture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE) + .putExtra(MediaStore.EXTRA_OUTPUT, photo) + .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); + capture.setClipData(ClipData.newRawUri("", photo)); + chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {capture}); + photos.put(requestCode, photo); + } + return chooser; + } + + /** The answer Qt's dialog reads for an offered request: the camera's photo when it was the camera. */ + Intent answered(int requestCode, int resultCode, Intent data) { + Uri photo = photos.get(requestCode); + if (photo == null) { + return data; + } + photos.remove(requestCode); + ContentResolver resolver = activity.getContentResolver(); + boolean picked = data != null && (data.getData() != null || data.getClipData() != null); + try { + if (resultCode == Activity.RESULT_OK && !picked) { + // The camera wrote the photo and answers with no URI of its own. + ContentValues taken = new ContentValues(); + taken.put(MediaStore.MediaColumns.IS_PENDING, 0); + resolver.update(photo, taken, null, null); + return new Intent().setData(photo).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + } + resolver.delete(photo, null, null); + } catch (RuntimeException failure) { + Log.e(TAG, "could not settle the camera's photo " + photo, failure); + } + return data; + } + + /** A pending photo in Pictures/Toad for the camera to write, or null where it cannot be made. */ + private Uri newPhoto() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + return null; // RELATIVE_PATH and IS_PENDING arrived in Android 10. + } + ContentValues photo = new ContentValues(); + photo.put(MediaStore.MediaColumns.DISPLAY_NAME, "Toad " + System.currentTimeMillis() + ".jpg"); + photo.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg"); + photo.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/Toad"); + photo.put(MediaStore.MediaColumns.IS_PENDING, 1); + try { + return activity.getContentResolver().insert( + MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), photo); + } catch (RuntimeException failure) { + Log.e(TAG, "could not make a photo for the camera", failure); + return null; + } + } +} diff --git a/tools/android/keepalive/java/org/toadcomms/ToadActivity.java b/tools/android/keepalive/java/org/toadcomms/ToadActivity.java index 6094052de..6de3a57b9 100644 --- a/tools/android/keepalive/java/org/toadcomms/ToadActivity.java +++ b/tools/android/keepalive/java/org/toadcomms/ToadActivity.java @@ -8,6 +8,7 @@ import android.system.ErrnoException; import android.system.Os; import org.kivy.android.PythonActivity; +import org.qtproject.qt.android.QtActivityResults; /** * The APK's activity (buildozer.spec's android.entrypoint): python-for-android's Qt activity, @@ -19,6 +20,9 @@ public class ToadActivity extends PythonActivity { private static final int NOTIFICATIONS_ASKED = 1; + /** Attach's chooser: what Qt's file dialog asks the activity for becomes Android's own. */ + private final AttachChooser attachChooser = new AttachChooser(this); + /** * The optimization level the app's Python runs at: 1 drops asserts and keeps docstrings, * which name every menu action and key (MenuDeclaration.key_summary, @@ -60,4 +64,20 @@ && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager } startForegroundService(new Intent(this, ConnectedService.class)); } + + /** Every activity start passes here (the two-argument form calls this one); a file + * dialog's document request is offered Android's chooser in its place. */ + @Override + public void startActivityForResult(Intent intent, int requestCode, Bundle options) { + super.startActivityForResult(attachChooser.offered(intent, requestCode), requestCode, options); + } + + /** python-for-android's override notifies its own listeners and never calls super, so Qt's + * receivers heard no result; each result reaches both here, as QtActivityBase would. */ + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + Intent answered = attachChooser.answered(requestCode, resultCode, data); + super.onActivityResult(requestCode, resultCode, answered); + QtActivityResults.deliver(requestCode, resultCode, answered); + } } diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 4ef38a90c..f80c98dc0 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -86,12 +86,13 @@ from toad.message_rows import IrcMessageStyle, MarkdownMessageStyle from toad.client.input_modality import KeyboardInput, TouchInput from toad.qt.float_layer import QtFloatLayer, QtNoticeCard +from toad.client.menu_entry import strip_menu_markup from toad.qt.menu import QtMenu, QtMenuRow from toad.qt.activity import ChannelActivity from toad import paths -from toad.qt.thread_comms_panel import QtThreadCommsPanel +from toad.qt.thread_comms_panel import QtRelationshipItem, QtThreadCommsPanel from toad.qt.channel_sort import QtChannelListSort -from toad.qt.window import ConversationRow, ConversationView, MenuActionRun, QtToadApp +from toad.qt.window import ChannelLine, ConversationRow, ConversationView, MenuActionRun, QtTabAt, QtToadApp from toad.conversation_turn import LocalTurnBinding from toad.core.events import TextAgentFail, UnsupportedResumeAgentFail from toad.live_output import ResponseStream, ThoughtStream @@ -271,9 +272,10 @@ def offered(self, count: int) -> list[str]: return [offer.layout.name.text for offer in self.page.composer.offers.offers[:count]] async def listed(self) -> None: - """The bus has answered: the welcome lists at least one row.""" - await until(lambda: sum(section.childCount() for section in self.app.workspace_sessions.home.rows.items()) > 0, - "welcome rows") + """The bus has answered: the comms sidebar lists at least one channel or thread.""" + # Its top lines are the channels (a scenario may name its own `rows`). + await until(lambda: any(isinstance(row, ConversationRow) for row in self.app.sidebar.items()), + "sidebar rows") @abstractmethod async def run(self) -> None: ... @@ -938,6 +940,28 @@ async def run(self) -> None: assert not facts["shown"], "the message's own header is on the top row, yet a copy is pinned" +class JumpBackScenario(Scenario): + summary = ("open JUMP_TARGET (#comms by default), scroll a screen above the end and report the " + "back-to-bottom bar shown; tap it, touch nothing else, and fail unless the view is at the " + "end and the bar is gone (it stayed until the next scroll, Tristan, Android, 2026-11-18)") + + async def run(self) -> None: + self.app.resize(int(os.environ.get("WIDTH", 412)), 915) + await self.open_named(os.environ.get("JUMP_TARGET", "#comms")) + window = self.page.messages + await until(lambda: window.scroll_y > 0, "a history taller than the window") + window.scroll_y = max(0, window.scroll_y - window.viewport().height() * 2) + await asyncio.sleep(0.8) + self.report("1-scrolled-up", bar=window.jump_bar.jump_shown, following=window.follows_tail) + assert window.jump_bar.jump_shown, "scrolled above the end, the back-to-bottom bar is not shown" + QTest.mouseClick(window.jump_bar, Qt.MouseButton.LeftButton) + await asyncio.sleep(1.2) + self.report("2-jumped", bar=window.jump_bar.jump_shown, following=window.follows_tail, + at_end=window.at_end) + assert window.follows_tail and window.at_end, "the jump did not put the view at the end" + assert not window.jump_bar.jump_shown, "at the end after a jump, the back-to-bottom bar is still shown" + + class TallArrivalScenario(StickyScenario): summary = ("open TARGET (#scratch) following its end; SENDER (scratch-live-pipeline) posts one " "message taller than the window; once the window glides down into it, its header " @@ -1013,20 +1037,91 @@ async def run(self) -> None: class WelcomeScenario(Scenario): - summary = "print the welcome's listings, then open its first row" + summary = "print what the comms sidebar lists while it holds the window, then open its first channel" async def run(self) -> None: await self.listed() - welcome = self.app.workspace_sessions.home - sections = list(welcome.rows.items()) - self.report("1-welcome", **{section.text(0): [section.child(index).key for index in range(section.childCount())] - for section in sections}) - welcome.rows.activate(sections[0].child(0)) - await until(lambda: self.page is not welcome, "opened") + home = self.app.workspace_sessions.home + lines = list(self.app.sidebar.items()) + self.report("1-welcome", **{line.text(0) or line.key: [line.child(index).key for index in range(line.childCount())] + for line in lines}) + self.app.open_row(next(row for row in lines if isinstance(row, ConversationRow))) + await until(lambda: self.page is not home, "opened") await asyncio.sleep(1.0) self.report("2-opened") +class SoleSidebarScenario(Scenario): + summary = ("with no tab open the comms sidebar holds the window (banner, bus, search, channels, threads, " + "buses, hints); opening a row gives one tab and the sidebar returns to its placement beside " + "the conversation; closing that tab gives the window back to the sidebar") + + def shown(self) -> dict[str, object]: + app = self.app + side, pages = app.channels_side, app.workspace_sessions.pages + visible = lambda widget: widget.isVisibleTo(app) + on_app = lambda widget: QRect(widget.mapTo(app, QPoint(0, 0)), widget.size()) + tree = on_app(app.sidebar.viewport()) + buses = app.sidebar_buses + bus_lines = list(self.rows(buses.items())) + first_bus = next((line for line in bus_lines if line.parent() is not None), bus_lines[0] if bus_lines else None) + bus_seen = None + if first_bus is not None and visible(buses): + rect = buses.visualItemRect(first_bus) + bus_seen = (buses.viewport().rect().contains(rect) + and app.rect().contains(QRect(buses.viewport().mapTo(app, rect.topLeft()), rect.size()))) + return dict(sidebar=side.geometry().getRect(), pages=pages.geometry().getRect(), + window=(app.width(), app.height()), tabs=self.tabs(), + banner=visible(app.banner), bus=visible(app.bus_label), hints=visible(app.hints), + address=visible(app.bus_address), search=visible(app.sidebar_search), + strip=visible(side.toggle), buses=visible(buses), + bus_rows=[line.key for line in bus_lines], bus_seen=bus_seen, + channels=sum(isinstance(row, ConversationRow) for row in app.sidebar.items()), + over_tree=[type(part).__name__ for part in (app.hints, app.bus_address, buses, app.bus_label, app.banner) + if visible(part) and on_app(part).intersects(tree)], + tree=tree.getRect(), + parts={type(part).__name__: on_app(part).getRect() for part in + (app.banner, app.bus_label, buses, app.sidebar_search, app.hints, app.bus_address)}) + + async def run(self) -> None: + app = self.app + app.resize(int(os.environ.get("WIDTH", 412)), 915) + await self.listed() + await asyncio.sleep(1.0) + alone = self.shown() + self.report("1-alone", **alone) + chrome = app.chrome.rect() + assert alone["sidebar"][2:] == (chrome.width(), chrome.height()), f"the sidebar is not the whole window: {alone}" + assert alone["pages"][2] == 0, f"the pages still take room: {alone}" + assert all(alone[part] for part in ("banner", "bus", "hints", "address", "search", "buses")), alone + assert not alone["strip"] and alone["channels"], alone + assert not alone["over_tree"], f"drawn over the comms rows: {alone['over_tree']} {alone['parts']} tree={alone['tree']}" + # The buses are in the first screen, unscrolled: a bus row, or the Buses line when none + # is held. + assert alone["bus_seen"], f"no bus line inside the window: {alone}" + # 2. A row opens the first tab: the sidebar returns to its placement beside it. + await self.expand("#comms") + home = app.workspace_sessions.home + app.open_row(await self.channel_row("#comms")) + await until(lambda: self.page is not home and self.page.content_ready.is_set(), "#comms") + await asyncio.sleep(1.0) + beside = self.shown() + self.report("2-tab", **beside) + assert len(beside["tabs"]) == 1, beside + assert beside["pages"][2] > 0, f"the conversation got no room: {beside}" + assert not any(beside[part] for part in ("banner", "bus", "hints", "address", "buses")), beside + # Its kept placement: its strip, and its rows only if it was kept open. + assert beside["strip"] and beside["search"] == (not app.channels_side.collapsed), beside + # 3. Closing the last tab gives the window back to the sidebar. + app.close_index(0) + await until(lambda: self.page is home, "home") + await asyncio.sleep(1.0) + again = self.shown() + self.report("3-closed", **again) + assert again["sidebar"][2:] == (chrome.width(), chrome.height()) and again["banner"] and again["buses"], again + assert not again["over_tree"] and again["bus_seen"], again + + class MenuScenario(Scenario): summary = "list the menu's actions and run each one but Quit" @@ -1699,7 +1794,7 @@ async def run(self) -> None: self.report("1-welcome", window=self.app.width(), too_wide=self.too_wide()) # Android's style lays pages out with wider margins than desktop; a widget sized # from its page's width grows the page by the difference on every resize. - self.app.workspace_sessions.home.layout().setContentsMargins(20, 20, 20, 20) + self.app.channels_column.layout().setContentsMargins(20, 20, 20, 20) widths = [] for _ in range(4): self.app.resize(self.width, 915) @@ -2877,6 +2972,105 @@ def setting(shown: bool) -> None: raise AssertionError("; ".join(faults)) +class SendGapScenario(Scenario): + summary = ("open TARGET (#scratch) and send SENDS (10) messages one after another; every 16 ms " + "read whether each sent message is in the delivery preview or drawn in the history's " + "viewport, and fail when any message is in neither for a frame between its Send and " + "its row on screen (Tristan: the queue showed it, then a gap, then the message)") + + async def run(self) -> None: + app = self.app + app.resize(412, 915) + await self.open_named(os.environ.get("TARGET", "#scratch")) + view = self.page + composer = view.composer + history = view.messages + sends = int(os.environ.get("SENDS", "10")) + stamp = time.strftime("%H%M%S") + markers = [f"gap{index}-{stamp}" for index in range(sends)] + sent: dict[str, float] = {} + frames: dict[str, list[tuple[float, bool, bool]]] = {marker: [] for marker in markers} + + def in_preview(marker: str) -> bool: + return composer.submitting.isVisible() and marker in composer.submitting.text() + + def drawn(marker: str) -> bool: + rows = history.model_rows + seen = history.viewport().rect() + for row, fragment in enumerate(rows.fragments): + if fragment is not None and marker in fragment.clipboard_text: + return history.visualRect(rows.index(row, 0)).intersects(seen) + return False + + def sample() -> None: + now = time.monotonic() + for marker, at in sent.items(): + track = frames[marker] + if track and track[-1][2]: + continue # drawn already: the handoff is over + track.append((now - at, in_preview(marker), drawn(marker))) + painted: dict[str, list[tuple[float, bool, bool]]] = {marker: [] for marker in markers} + + def sample_painted() -> None: + now = time.monotonic() + for marker, at in sent.items(): + track = painted[marker] + if track and track[-1][2]: + continue + track.append((now - at, in_preview(marker), drawn(marker))) + + class PaintSampler(QObject): + """Reads both places just before each repaint of the window: what a frame shows.""" + + def eventFilter(self, watched, event) -> bool: # noqa: N802 - Qt virtual method name + if event.type() == QEvent.Type.UpdateRequest: + sample_painted() + return False + paint_sampler = PaintSampler() + app.installEventFilter(paint_sampler) + from PySide6.QtCore import QTimer + timer = QTimer() + timer.setInterval(16) + timer.timeout.connect(sample) + timer.start() + try: + for marker in markers: + composer.editor.setPlainText(marker) + sent[marker] = time.monotonic() + composer.submit() + await until(lambda marker=marker: frames[marker] and frames[marker][-1][2], f"{marker} drawn", + tenths=600) + await asyncio.sleep(0.3) + finally: + timer.stop() + app.removeEventFilter(paint_sampler) + await asyncio.sleep(1.5) + lingering = [marker for marker in markers if in_preview(marker)] + self.report("after-sends", preview_shown=composer.submitting.isVisible(), preview_text=composer.submitting.text()[:160], lingering=lingering) + if lingering: + raise AssertionError(f"drawn messages stayed in the delivery preview: {lingering}") + painted_gaps = {marker: sum(1 for _, preview, shown in track if not (preview or shown)) + for marker, track in painted.items()} + print(f"SEND_GAP painted frames per message={ {m: len(t) for m, t in painted.items()} } " + f"painted gap frames={painted_gaps}", flush=True) + worst: dict[str, int] = {} + for marker, track in frames.items(): + run = longest = 0 + for _, preview, shown in track: + run = 0 if preview or shown else run + 1 + longest = max(longest, run) + worst[marker] = longest + first_drawn = next((at for at, _, shown in track if shown), None) + gaps = [index for index, (_, preview, shown) in enumerate(track) if not (preview or shown)] + self.report(f"send-{marker}", frames=len(track), longest_gap_frames=longest, + drawn_after_s=None if first_drawn is None else round(first_drawn, 2), + gap_frames_at=gaps, gap_times=[round(track[index][0], 3) for index in gaps]) + print(f"SEND_GAP worst={max(worst.values())} frames per message={worst}", flush=True) + if any(worst.values()) or any(painted_gaps.values()): + raise AssertionError(f"a sent message was in neither the preview nor the history: sampled " + f"{worst}, painted {painted_gaps}") + + class FrameScenario(Scenario): summary = ("frame budget: the GUI thread's stalls and key-to-paint latency (toad.qt.frame_probe) " "while idle with the sidebar's waves running, while scrolling #comms, and while typing " @@ -2917,7 +3111,6 @@ def wrapper(*args, **kwargs): timed(qt_window.Sidebar, "redraw", "sidebar.redraw") timed(qt_window.Sidebar, "sync", "sidebar.sync") timed(type(app), "paint_tabs", "paint_tabs") - timed(type(app.workspace_sessions.home), "present", "home.present") timed(type(app.thread_pane), "bind", "thread_pane.bind") timed(type(app.thread_pane), "setting_entries", "thread_pane.setting_entries") timed(type(app), "present_panes", "present_panes") @@ -3404,6 +3597,16 @@ def menu(self) -> list[str]: def close_menu(self) -> None: self.app.menu_panel.hide() + async def opened_menu(self, tenths: int = 50) -> list[str]: + """The menu once it shows: a line's menu is read off the UI thread (its target's + commands come from Core), so it opens a moment after the press. Nothing when none + opens within the wait.""" + for _ in range(tenths): + if shown := self.menu(): + return shown + await asyncio.sleep(0.1) + return [] + async def right_click(self, widget: QWidget, point: QPoint) -> list[str]: """A mouse's right button at `point`, through the window, where Qt turns it into the context-menu request (a widget-level click skips that).""" @@ -3411,8 +3614,7 @@ async def right_click(self, widget: QWidget, point: QPoint) -> list[str]: handle, at = window.windowHandle(), widget.mapTo(window, point) await self.dispatched(lambda: QTest.mouseClick(handle, Qt.MouseButton.RightButton, Qt.KeyboardModifier.NoModifier, at)) - await asyncio.sleep(0.4) - clicked = self.menu() + clicked = await self.opened_menu() self.close_menu() return clicked @@ -3432,7 +3634,7 @@ async def held_menu(self, step: str, widget: QWidget, point: QPoint) -> None: # only once it is gone. await asyncio.sleep(0.4) await self.touch(widget, point, 1100) - held = self.menu() + held = await self.opened_menu() self.report(step, menu=held) self.close_menu() await asyncio.sleep(0.4) @@ -3522,6 +3724,88 @@ def entry_rows(): raise AssertionError("\n".join(self.faults)) +class MenuParityScenario(HoldScenario): + summary = ("at a Pixel 8a's size on #scratch: a right-click on a channel line, a thread line, a " + "tab, a message and a Comms relationship draws exactly that element's declared menu " + "(TargetLine, TabElement, BlockMenu, RelationshipLine), which tests/textual/" + "test_menu_parity.py checks Textual draws for the same elements") + + @staticmethod + def labels(entries) -> list[str]: + return [strip_menu_markup(entry.label) for entry in entries] + + async def parity(self, step: str, widget: QWidget, point: QPoint, declared: list[str]) -> list[str]: + drawn = await self.right_click(widget, point) + self.report(step, drawn=drawn, declared=declared) + self.expect(step, bool(declared), "the element declares no menu") + self.expect(step, drawn == declared, f"drew {drawn}, the element declares {declared}") + await asyncio.sleep(0.3) + return drawn + + async def run(self) -> None: + app = self.app + app.resize(412, 915) + await self.open_named("#scratch") + tree = app.sidebar + await self.expand("#scratch") + # 1. The #scratch channel line: its target's commands. + channel = await self.found(lambda row: isinstance(row, ChannelLine) and row.target.name == "#scratch", + "the #scratch line") + tree.scrollToItem(channel) + await asyncio.sleep(0.3) + drawn = await self.parity("1-channel-line", tree.viewport(), tree.visualItemRect(channel).center(), + self.labels(await channel.menu_entries())) + self.expect("1-channel-line", drawn != ["Open", "Copy name"], "the hand-rolled Open / Copy name") + # 2. A thread line listed under #scratch: its target's commands, in #scratch. + thread = await self.found(lambda row: isinstance(row, ConversationRow) and row.parent() is channel, + "a thread listed under #scratch") + tree.scrollToItem(thread) + await asyncio.sleep(0.3) + drawn = await self.parity("2-thread-line", tree.viewport(), tree.visualItemRect(thread).center(), + self.labels(await thread.menu_entries())) + self.expect("2-thread-line", drawn != ["Open", "Copy name"], "the hand-rolled Open / Copy name") + # 3. The #scratch tab: the shared tab menu. + tabs = app.tabs + index = tabs.currentIndex() + await self.parity("3-tab", tabs, tabs.tabRect(index).center(), + self.labels(QtTabAt(app, app.session_navigation.tabs[index].mode_name).menu_entries())) + # 4. A message: the block menu, for the fragment the press asked it of. + history = self.page.messages + viewport = history.viewport() + on_row = QPoint(viewport.width() // 4, viewport.height() // 3) + asked: list = [] + history.block_menu_requested.connect(lambda fragment, pressed: asked.append(fragment)) + drawn = await self.right_click(viewport, on_row) + self.expect("4-message", bool(asked), "no message was asked for its menu") + if asked: + fragment = asked[-1] + declared = self.labels(QtMenu.command_entries(QtMenu.block_commands(fragment, fragment.block_menu), + app.settings, lambda command: None)) + self.report("4-message", drawn=drawn, declared=declared) + self.expect("4-message", drawn == declared, f"drew {drawn}, the block declares {declared}") + # 5. A Comms relationship of scratch-live-pipeline: Open / Copy name, declared once. + await self.open_named("scratch-live-pipeline") + app.resize(412, 1600) + app.thread_side.toggle_pane() + await asyncio.sleep(1.0) + picker = app.thread_pane.menu.picker + picker.setCurrentIndex([picker.itemText(index) for index in range(picker.count())].index("Comms")) + panel: QtThreadCommsPanel = app.thread_pane._comms_panel + comms = panel._tree + + def relationship_items() -> list[QtRelationshipItem]: + return [item for item in comms.findItems("", Qt.MatchFlag.MatchContains | Qt.MatchFlag.MatchRecursive) + if panel._row_entry(item) is not None + and comms.viewport().rect().contains(comms.visualItemRect(item).center())] + + await until(lambda: comms.isVisible() and relationship_items(), "a Comms relationship row") + item = relationship_items()[0] + await self.parity("5-relationship", comms.viewport(), comms.visualItemRect(item).center(), + self.labels(await item.menu_entries())) + if self.faults: + raise AssertionError("\n".join(self.faults)) + + class FingerScenario(Scenario): summary = ("at a Pixel 8a's width with the phone's touch-as-mouse gesture: drag every visible " "scroll area by finger on the welcome, sidebar, #comms, the multi-line composer, the " diff --git a/tools/qt_inherit_ratchet.py b/tools/qt_inherit_ratchet.py index a1b4d44df..8392bfc4d 100644 --- a/tools/qt_inherit_ratchet.py +++ b/tools/qt_inherit_ratchet.py @@ -73,18 +73,16 @@ "toad.qt.channel_sort.QtChannelListSort": "toad.widgets.session_sort.ChannelListSort", "toad.qt.channel_sort.QtChannelSortControl": "toad.widgets.comms_sidebar.ChannelSortChoice", "toad.qt.window.NewSessionRow": "toad.widgets.comms_sidebar.NewSessionButton", - "toad.qt.window.QtStartSessionButton": "toad.screens.welcome.StartSessionButton", # channel tree lines (toad.client.sidebar_lines) and the welcome "toad.qt.window.SidebarItem": "toad.widgets.sidebar_tree.DetailedRow", "toad.qt.window.SidebarSection": "toad.widgets.sidebar_tree.SidebarGroup", - "toad.qt.window.OpenSection": "toad.screens.welcome.WelcomeSection", "toad.qt.window.StatusSection": "toad.sidebar_model_view.SidebarStatus", - "toad.qt.window.UnavailableSection": "toad.sidebar_model_view.SidebarStatus", "toad.qt.window.ConversationRow": "toad.widgets.sidebar_tree.CommsRow", "toad.qt.window.ConversationRows": "toad.widgets.sidebar_tree.TargetTree", "toad.qt.window.HeaderLineControl": "toad.widgets.sidebar_tree.GroupHeaderLine", "toad.qt.window.BusRow": "toad.screens.bus_choice.BusOption", - "toad.qt.window.BusLabel": "toad.screens.welcome.WelcomeLocationNote", + "toad.qt.window.BusLabel": "toad.widgets.channels_sidebar.SidebarLocationNote", + "toad.qt.banner.Banner": "toad.widgets.channels_sidebar.SidebarBanner", } # Same name, different concept: not a frontend pair. Each entry says what the sibling really is. diff --git a/tools/qt_scroll_profile.py b/tools/qt_scroll_profile.py index 5f718ddda..5462c0df0 100644 --- a/tools/qt_scroll_profile.py +++ b/tools/qt_scroll_profile.py @@ -82,9 +82,8 @@ def page(self): return self.app.workspace_sessions.pages.currentWidget() async def open_comms(self) -> None: - await until(lambda: sum(section.childCount() - for section in self.app.workspace_sessions.home.rows.items()) > 0, - "welcome rows") + await until(lambda: any(isinstance(row, ConversationRow) for row in self.app.sidebar.items()), + "sidebar rows") self.app.resize(WIDTH, HEIGHT) for item in self.app.sidebar.items(): item.setExpanded(item.key == "#comms" or item.isExpanded())