Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/toad/client/bus_submission.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
37 changes: 34 additions & 3 deletions src/toad/client/prompt_composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import annotations

from abc import abstractmethod
from typing import ClassVar

from metaclass_registry import AbstractHooksMeta

Expand All @@ -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
Expand Down Expand Up @@ -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 (``❯``)."""
Expand Down
4 changes: 4 additions & 0 deletions src/toad/conversation_submission.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions src/toad/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,)):
Expand Down
29 changes: 22 additions & 7 deletions src/toad/qt/composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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``
Expand Down
32 changes: 29 additions & 3 deletions src/toad/qt/queue_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand All @@ -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."""

Expand Down
2 changes: 1 addition & 1 deletion src/toad/qt/submission_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
18 changes: 18 additions & 0 deletions src/toad/submission_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),),)

Expand Down Expand Up @@ -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),)]
Expand Down Expand Up @@ -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 (
Expand Down
18 changes: 16 additions & 2 deletions src/toad/widgets/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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()
Expand All @@ -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):
Expand Down Expand Up @@ -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()
Expand Down
21 changes: 21 additions & 0 deletions tests/support/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))))
38 changes: 38 additions & 0 deletions tests/textual/test_delivery_preview_setting.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading