diff --git a/src/toad/client/bus_submission.py b/src/toad/client/bus_submission.py index 402939a08..4b6691a1c 100644 --- a/src/toad/client/bus_submission.py +++ b/src/toad/client/bus_submission.py @@ -109,6 +109,12 @@ def summary(self) -> tuple[str, ...]: def details(self) -> DetailLines: return tuple((Span(f"Submitting: {QueueItem.summarize(text)}", MutedRole),) for text in self.texts) + @staticmethod + def held_hint(count: int) -> str: + """The one-word stand-in for the delivery preview while it is off: how many of the + view's messages are still held, and nothing when none is.""" + return f"⧗ {count} held" if count else "" + class UnboundSubmissionStart(SubmissionStart): def __init__(self, owner: BusSubmissions, submission: SubmittedText, refusal: InputRefused): @@ -377,6 +383,10 @@ def holds_input(self) -> bool: def queue_summary(self) -> str: return " | ".join(self.submitting.summary) + @property + def queue_hint(self) -> str: + return self.submitting.held_hint(len(self.submitting.texts)) + def settle(self) -> None: """The view drew new messages: retire the bus sends they show.""" for execution in tuple(self.active): diff --git a/src/toad/client/prompt_composer.py b/src/toad/client/prompt_composer.py index ae6c2209a..81cc0727b 100644 --- a/src/toad/client/prompt_composer.py +++ b/src/toad/client/prompt_composer.py @@ -9,6 +9,7 @@ from __future__ import annotations from abc import abstractmethod +from typing import ClassVar from metaclass_registry import AbstractHooksMeta @@ -31,11 +32,20 @@ def apply_input_text(self) -> None: """The placeholder or a leading symbol changed: the prompt shows the new text.""" self.update_prompt() + @EachOpenWidget + def apply_delivery_preview(self) -> None: + """The delivery preview was turned on or off: the prompt shows its queue rows, or + drops them for the held count, at once.""" + self.sync_queue() + class PromptComposer(metaclass=AbstractHooksMeta): """A conversation's composer: its submission owner, queue and leading glyph.""" submissions: object | None + queue_summary_lines: ClassVar[int] = 3 + """The queue summary's most lines; a longer one is cut there, so its wrapping never + pushes the history further.""" @property @abstractmethod @@ -69,13 +79,34 @@ def holds_input(self) -> bool: @property def offers_send_now(self) -> bool: - """Delivery controls ("Enter queues · Send now") show while input is held for a - ready agent.""" + """Send now (Ctrl+Enter) sends ahead while input is held for a ready agent.""" return self.agent_ready and self.holds_input + @property + def shows_delivery_preview(self) -> bool: + """The `ui.input.delivery_preview` setting: the queue rows above the prompt, or only + the held count in the info bar.""" + return self.settings.ui.input.delivery_preview + + @property + def shows_delivery_controls(self) -> bool: + """The delivery controls row ("Enter queues · Send now") shows while Send now is + offered and the preview is on; with it off, Ctrl+Enter still sends ahead.""" + return self.shows_delivery_preview and self.offers_send_now + @property def queue_summary(self) -> str: - return self.operational_submissions.queue_summary + """The queue rows' text; while the preview is off nothing is read for them.""" + return self.operational_submissions.queue_summary if self.shows_delivery_preview else "" + + @property + def queue_hint(self) -> str: + """The info bar's held count while the preview is off; nothing while it is on.""" + return "" if self.shows_delivery_preview else self.operational_submissions.queue_hint + + @abstractmethod + def sync_queue(self) -> None: + """Show the queue rows, the delivery controls and the held count as the shared answers say.""" def prompt_symbol(self, text: str, shell_mode: bool) -> str: """The glyph that leads the input: shell, multiline or the agent prompt (``❯``).""" diff --git a/src/toad/conversation_submission.py b/src/toad/conversation_submission.py index ebe680f19..768f8aa15 100644 --- a/src/toad/conversation_submission.py +++ b/src/toad/conversation_submission.py @@ -280,6 +280,10 @@ def holds_input(self) -> bool: def queue_summary(self) -> str: return self.view.queue_source.queue_summary(self.queue_evidence) + @property + def queue_hint(self) -> str: + return self.view.queue_source.queue_hint(self.queue_evidence) + @property def queue_projection(self): return self.view.agent_binding.presentation.queue diff --git a/src/toad/preferences.py b/src/toad/preferences.py index 3923961e8..5ca130afc 100644 --- a/src/toad/preferences.py +++ b/src/toad/preferences.py @@ -91,6 +91,12 @@ class InputSettings(SettingsDeclaration, scopes=(ConversationSettingsOwner,)): ] = "$" """Shown before a shell command.""" + delivery_preview: Annotated[ + bool, FieldLabel("Show delivery preview?"), PromptSettingEffects.apply_delivery_preview, + WireName("delivery-preview"), + ] = True + """The rows above the prompt that list messages still submitting, queued or held at their recipients, with Send now. Disable to keep the history its full height: the info bar then shows only how many are held, and selecting it opens the queue.""" + @dataclass(frozen=True) class ViewUiSettings(SettingsDeclaration, scopes=(ViewSettingsOwner,)): diff --git a/src/toad/qt/composer.py b/src/toad/qt/composer.py index ee5dd3c2b..949ada4f1 100644 --- a/src/toad/qt/composer.py +++ b/src/toad/qt/composer.py @@ -57,7 +57,7 @@ ) from toad.qt.composer_vim import ComposerVimMode, apply_normal_key from toad.qt.lines import QtLineRenderer -from toad.qt.queue_ui import QtDeliveryControls, QtQueueInspection, QtQueueSummary, RowReveal +from toad.qt.queue_ui import QtDeliveryControls, QtQueueHint, QtQueueInspection, QtQueueSummary, RowReveal from toad.qt.prompt_stack import QtInfoBar from toad.slash_command import SlashCommand from toad.slash_command_results import CommandMatch, SlashCommandResults @@ -334,6 +334,10 @@ def __init__(self, host: ComposerHost, renderer: QtLineRenderer, placeholder: st # Textual's QueueSummary + DeliveryControls, reading the shared submissions owner. self.submitting = QtQueueSummary(self) self.delivery_controls = QtDeliveryControls(self) + # Textual's `QueueHint`: the info bar's held count while the delivery preview is off, + # before the status line as Textual composes it. + self.held = QtQueueHint(self) + self.info_bar.layout().insertWidget(self.info_bar.layout().indexOf(self.info_bar.status), self.held) self.failure = self.line(FailureRole) self.receipt = Receipt(host.app, renderer) self.send_button = QPushButton(SubmitAction.title, self) @@ -360,7 +364,7 @@ def __init__(self, host: ComposerHost, renderer: QtLineRenderer, placeholder: st self.place_input_box() self.refresh_glyph() self.fit_height() - self.show_submitting() + self.sync_queue() @property def settings(self): @@ -419,7 +423,7 @@ def focus_changed(self, focused: bool) -> None: def refresh_editing_mode(self) -> None: self.info_bar.badge.present_editing_mode(self.editor.editing_mode, self.editor.hasFocus()) - RowReveal.toggle(self.delivery_controls, self.offers_send_now, self) + RowReveal.toggle(self.delivery_controls, self.shows_delivery_controls, self) @property def offers_send_now(self) -> bool: @@ -562,11 +566,22 @@ def show_failure(self, text: str) -> None: self.failure.setText(text) self.failure.show() - def show_submitting(self) -> None: - """The queue summary and delivery controls from the shared submissions, as Textual's - ``_update_queue_summary`` + ``DeliveryControls`` flip on ``offers_send_now``.""" + queue_sync_pending: bool = False + + def sync_queue(self) -> None: + """The queue summary, the delivery controls and the held count from the shared + submissions, as Textual's ``Prompt.sync_queue`` shows them; once per event-loop turn, + however many changes the turn reports (a send publishes several, and every + notification read reports the queue again).""" + if not self.queue_sync_pending: + self.queue_sync_pending = True + QTimer.singleShot(0, self, self._sync_queue) + + def _sync_queue(self) -> None: + self.queue_sync_pending = False self.submitting.refresh(self.queue_summary) - RowReveal.toggle(self.delivery_controls, self.offers_send_now, self) + RowReveal.toggle(self.delivery_controls, self.shows_delivery_controls, self) + self.held.refresh(self.queue_hint) def open_queue_menu(self) -> None: """Textual's ``Conversation.open_queue_menu`` pushes the ``QueueInspection`` diff --git a/src/toad/qt/queue_ui.py b/src/toad/qt/queue_ui.py index a5e36bee5..3d4afaaf4 100644 --- a/src/toad/qt/queue_ui.py +++ b/src/toad/qt/queue_ui.py @@ -127,10 +127,12 @@ def land(self) -> None: class QtQueueSummary(QtActivatedText): """The queue summary; a press opens the queue inspection, as Textual's ``QueueSummary``. - It wraps as Textual's ``AutoHeight`` summary does. Its height opens, closes and follows its - lines through `RowReveal`: at phone width "Submitting (1): …" and "Delivery (4 visible + It wraps as Textual's ``AutoHeight`` summary does, to the same most lines + (`PromptComposer.queue_summary_lines`). Its height opens, closes and follows its lines + through `RowReveal`: at phone width "Submitting (1): …" and "Delivery (4 visible messages): …" wrap to different line counts, and each send popped the history above by a - line and back in one frame.""" + line and back in one frame. Without the cap every longer preview grew the strip again, and + every frame of that growth resized and repainted the history above.""" def __init__(self, composer: "Composer") -> None: super().__init__(composer) @@ -139,6 +141,11 @@ def __init__(self, composer: "Composer") -> None: self.reveal: RowReveal | None = None self.hide() + def heightForWidth(self, width: int) -> int: # noqa: N802 - Qt virtual method name + margins = self.contentsMargins() + most = self.composer.queue_summary_lines * self.fontMetrics().lineSpacing() + margins.top() + margins.bottom() + return min(super().heightForWidth(width), most) + def refresh(self, text: str) -> None: if text and text != self.text(): # A closing summary keeps its last words while it closes. before = self.height() @@ -151,6 +158,25 @@ def activate(self) -> None: self.composer.open_queue_menu() +class QtQueueHint(QtActivatedText): + """Textual's ``QueueHint``: the held count in the info bar while the delivery preview is + off. A few words in a row that is always there, so the history never moves for it; a + press opens the queue inspection, as the summary's does.""" + + def __init__(self, composer: "Composer") -> None: + super().__init__(composer) + self.setToolTip("Show queued messages and delivery status.") + self.hide() + + def refresh(self, text: str) -> None: + if text != self.text(): + self.setText(text) + self.setVisible(bool(text)) + + def activate(self) -> None: + self.composer.open_queue_menu() + + class QtDeliveryControls(QueueDeliveryControls, QWidget, metaclass=PyQtWidgetMeta): """Textual's ``DeliveryControls`` row; `QueueDeliveryControls` owns its text.""" diff --git a/src/toad/qt/submission_view.py b/src/toad/qt/submission_view.py index a8fed6ff1..259a4bf57 100644 --- a/src/toad/qt/submission_view.py +++ b/src/toad/qt/submission_view.py @@ -38,4 +38,4 @@ def run_submission(self, send: Callable[[], Awaitable[None]]) -> None: def submissions_changed(self) -> None: if self.composer is not None: - self.composer.show_submitting() + self.composer.sync_queue() diff --git a/src/toad/submission_queue.py b/src/toad/submission_queue.py index 990a54966..ebca0b9c4 100644 --- a/src/toad/submission_queue.py +++ b/src/toad/submission_queue.py @@ -88,6 +88,14 @@ async def queue_clear(self, evidence: QueueEvidence, scope: QueueScope) -> None: def queue_summary(self, evidence: QueueEvidence) -> str: return "Queue unavailable" + def held_count(self, evidence: QueueEvidence) -> int: + """How many of the view's messages are still held: its own still submitting.""" + return len(evidence.submitting.texts) + + def queue_hint(self, evidence: QueueEvidence) -> str: + """The summary's stand-in while the delivery preview is off.""" + return evidence.submitting.held_hint(self.held_count(evidence)) + def queue_details(self, evidence: QueueEvidence) -> DetailLines: return ((Span("No queue observation is available for this source.", MutedRole),),) @@ -126,6 +134,11 @@ def queue_summary(self, evidence: QueueEvidence) -> str: parts.append(f"{label} ({len(texts)}{detail}): " + " · ".join(texts[:self.preview_limit])) return " | ".join(parts) + def held_count(self, evidence: QueueEvidence) -> int: + """Also the prompts the agent accepted and has not taken, and those restored to it.""" + projection = evidence.presentation.queue + return super().held_count(evidence) + len(projection.items) + len(projection.restored) + def queue_details(self, evidence: QueueEvidence) -> DetailLines: projection = evidence.presentation.queue lines: list[tuple[Span, ...]] = [(Span("Submitting is local intent; Queued is producer acceptance, not consumption.", MutedRole),)] @@ -196,6 +209,11 @@ def queue_summary(self, evidence: QueueEvidence) -> str: return " | ".join(( *evidence.submitting.summary, coverage + (f": {previews}" if previews else ": unobserved"))) + def held_count(self, evidence: QueueEvidence) -> int: + """Also the visible messages a recipient has not taken yet.""" + return super().held_count(evidence) + sum( + 1 for entry in evidence.entries if entry.status.queued_recipients) + def queue_details(self, evidence: QueueEvidence) -> DetailLines: recipients = evidence.queued_recipients return ( diff --git a/src/toad/widgets/prompt.py b/src/toad/widgets/prompt.py index 68ed33bce..d91ad9a68 100644 --- a/src/toad/widgets/prompt.py +++ b/src/toad/widgets/prompt.py @@ -247,13 +247,22 @@ class QueueSummary( def apply_native_layout(self) -> None: super().apply_native_layout() - self.styles.max_height = 3 + self.styles.max_height = PromptComposer.queue_summary_lines def activate(self) -> None: self.query_ancestor(Prompt).conversation.open_queue_menu() +class QueueHint(Activates, SecondaryText, StartsHidden, SideMargin, AutoWidth, OneRow, NoWrap, Label, + can_focus=True): + """The held count in the info bar while the delivery preview is off; selecting it + opens the queue, as the summary does.""" + + def activate(self) -> None: + self.query_ancestor(Prompt).conversation.open_queue_menu() + + class DeliveryControls(QueueDeliveryControls, ComposedWhenShown, StartsHidden, OneRow, containers.HorizontalGroup): """Shown while Enter queues behind a running turn; `QueueDeliveryControls` owns its text.""" @@ -872,7 +881,7 @@ def sync_turn(self) -> None: if not self.is_mounted: return editor = self.prompt_text_area - self.query_one(DeliveryControls).show(SubmitNowAction().available(editor)) + self.query_one(DeliveryControls).show(self.shows_delivery_preview and SubmitNowAction().available(editor)) editor.refresh_bindings() self.conversation.queue_controls_changed() @@ -895,6 +904,10 @@ def _update_queue_summary(self) -> None: summary.display = bool(text) summary.tooltip = "Show queued messages and delivery status." summary.update(Content(text)) + hint = self.queue_hint + held = self.query_one(QueueHint) + held.display = bool(hint) + held.update(Content(hint)) @on(messages.SendPromptNow) async def on_send_prompt_now(self, event): @@ -1080,6 +1093,7 @@ def compose(self) -> ComposeResult: yield from self.compose_info_popups() with InfoBar(): yield editor.editing_mode_label + yield QueueHint("", markup=False) yield from self.compose_agent_info() yield StatusLine(markup=False).data_bind(status=Prompt.status) yield from self.compose_mode_controls() diff --git a/tests/support/agents.py b/tests/support/agents.py index 04f483bc3..267e62c9c 100644 --- a/tests/support/agents.py +++ b/tests/support/agents.py @@ -138,3 +138,24 @@ async def load_session(self, cwd, session_id, mcp_servers, **metadata): async def close(self): pass + + +def queued_session_response(session: str, *, next_owner: bool = False): + """A session answer whose queue already holds two accepted prompts, as a live agent's + ``QueueChangedUpdate`` reports them.""" + from acp.schema import NewSessionResponse + from agent_comms.acp_extension import AvailableQueueProjection, LiveQueueScope, QueueChangedUpdate, QueueItem + from agent_comms.execution.child_process import ProcessIdentity + from agent_comms.nominal.field_codec import InputId + from agent_comms.registry.thread_identity import ClaimedIdentity, RecordedThreadIncarnation + from agent_comms.text_route_update import encode_updates + + generation = 2 if next_owner else 1 + scope = LiveQueueScope( + session_id=AcpSessionId(session), + claimed_identity=ClaimedIdentity(RecordedThreadIncarnation(session, 1000.0), generation), + owner=ProcessIdentity(1234, 1), + ) + items = (QueueItem(InputId("a" * 32), "same text"), QueueItem(InputId("b" * 32), "same text")) + return NewSessionResponse( + sessionId=session, _meta=encode_updates(QueueChangedUpdate(scope, generation, AvailableQueueProjection(items)))) diff --git a/tests/textual/test_delivery_preview_setting.py b/tests/textual/test_delivery_preview_setting.py new file mode 100644 index 000000000..780a2df3d --- /dev/null +++ b/tests/textual/test_delivery_preview_setting.py @@ -0,0 +1,38 @@ +"""`ui.input.delivery_preview`: the queue rows above the prompt, or only the info bar's held count.""" + +import asyncio + +from support.agents import PendingAnswer, PendingConnection, queued_session_response +from toad.preferences import SETTINGS +from toad.widgets.prompt import DeliveryControls, QueueHint, QueueSummary + + +async def test_turning_the_delivery_preview_off_drops_the_queue_rows_for_the_held_count_live(workspace): + async with workspace.app(size=(115, 38)) as ui: + agent = ui.detached_agent(None) + ui.attach_agent(agent) + await ui.step() + view = ui.conversation + answer = PendingAnswer() + agent.process.connection = PendingConnection([answer], answer) + starting = asyncio.create_task(agent.session.new()) + await answer.started.wait() + answer.result.set_result(queued_session_response("new-session")) + await starting + await ui.until(lambda: view.submissions.queue_projection.status == "available", why="the queue") + app, _pilot = ui.textual + summary, held = view.query_one(QueueSummary), view.query_one(QueueHint) + assert "Queued (2)" in summary.render().plain and summary.display + assert not held.display + + app.saved_settings.set(SETTINGS.ui.input.delivery_preview, False) + await ui.step() + assert not summary.display + assert not view.query_one(DeliveryControls).display + assert held.display and held.render().plain == "⧗ 2 held" + + app.saved_settings.set(SETTINGS.ui.input.delivery_preview, True) + await ui.step() + assert summary.display and "Queued (2)" in summary.render().plain + assert not held.display + await agent.stop() diff --git a/tests/textual/test_queue_request_results.py b/tests/textual/test_queue_request_results.py index ce157e411..7d0d5b59b 100644 --- a/tests/textual/test_queue_request_results.py +++ b/tests/textual/test_queue_request_results.py @@ -4,36 +4,10 @@ import asyncio import pytest -from acp.schema import NewSessionResponse -from agent_comms.acp_extension import ( - AvailableQueueProjection, - QueueChangedUpdate, - QueueItem, - LiveQueueScope, -) -from agent_comms.text_route_update import encode_updates -from agent_comms.nominal.field_codec import AcpSessionId, InputId -from agent_comms.execution.child_process import ProcessIdentity -from agent_comms.registry.thread_identity import ( - ClaimedIdentity, - RecordedThreadIncarnation, -) - -from support.agents import PendingAnswer, PendingConnection -from toad.widgets.prompt import QueueSummary from acp.exceptions import RequestError - -def response(session, next_owner=False): - generation = 2 if next_owner else 1 - scope = LiveQueueScope( - session_id=AcpSessionId(session), - claimed_identity=ClaimedIdentity(RecordedThreadIncarnation(session, 1000.0), generation), - owner=ProcessIdentity(1234, 1), - ) - items = (QueueItem(InputId("a" * 32), "same text"), QueueItem(InputId("b" * 32), "same text")) - return NewSessionResponse( - sessionId=session, _meta=encode_updates(QueueChangedUpdate(scope, generation, AvailableQueueProjection(items)))) +from support.agents import PendingAnswer, PendingConnection, queued_session_response as response +from toad.widgets.prompt import QueueSummary @pytest.mark.parametrize("successor", ["new", "stop"]) diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 784514eec..a0d9493d0 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -2043,6 +2043,74 @@ def wrapper(*arguments, **options): queue_changes=len(toggles), largest_scroll_step=max(map(abs, jumps), default=0)) +class DeliveryPreviewScenario(Scenario): + summary = ("open TARGET (#scratch), send 2 messages with ui.input.delivery_preview on, then 2 with " + "it off, turning it off and on live: the queue rows show only while it is on, the info " + "bar's held count only while it is off, and the history keeps its height while it is off") + + width: ClassVar[int] = 412 + + async def run(self) -> None: + app = self.app + app.resize(self.width, 915) + await self.open_named(os.environ.get("TARGET", "#scratch")) + view = self.page + composer = view.composer + samples: list[tuple[bool, bool, bool, int, str]] = [] + + def sample() -> None: + samples.append((composer.submitting.isVisible(), composer.delivery_controls.isVisible(), + composer.held.isVisible(), view.messages.viewport().height(), composer.held.text())) + from PySide6.QtCore import QTimer + timer = QTimer() + timer.setInterval(16) + timer.timeout.connect(sample) + stamp = time.strftime("%H:%M:%S") + + async def send(phase: str) -> list[tuple[bool, bool, bool, int, str]]: + samples.clear() + timer.start() + for index in range(2): + composer.editor.setPlainText(f"delivery preview {phase} {index} {stamp}") + composer.submit() + await asyncio.sleep(0.1) + await asyncio.sleep(6.0) + timer.stop() + return list(samples) + + def setting(shown: bool) -> None: + app.saved_settings.set(SETTINGS.ui.input.delivery_preview, shown) + faults: list[str] = [] + try: + setting(True) + await asyncio.sleep(0.5) + on = await send("on") + self.report("1-preview-on", summary_shown=any(s for s, *_ in on), + held_shown=any(h for _, _, h, *_ in on)) + if any(h for _, _, h, *_ in on): + faults.append("the held count showed while the preview was on") + setting(False) + await asyncio.sleep(0.5) + off = await send("off") + heights = sorted({height for *_, height, _ in off}) + self.report("2-preview-off", summary_shown=any(s for s, *_ in off), + controls_shown=any(c for _, c, *_ in off), held=sorted({text for *_, text in off} - {""}), + viewport_heights=heights) + if any(s or c for s, c, *_ in off): + faults.append("a queue row showed while the preview was off") + if len(heights) > 1: + faults.append(f"the history changed height while the preview was off: {heights}") + setting(True) + await asyncio.sleep(0.5) + self.report("3-preview-on-again", held_shown=composer.held.isVisible()) + if composer.held.isVisible(): + faults.append("the held count stayed after the preview came back") + finally: + setting(True) + if faults: + raise AssertionError("; ".join(faults)) + + 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 "