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
3 changes: 1 addition & 2 deletions src/toad/qt/acp_tab.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,7 @@ def show_agent_info(self, text: str) -> None:
"""The identity line and composer name the agent, as Textual's info bar does."""
self.identity_line.setText(f"ACP session #{self._session_pk} · {text}")
self._composer_label = text
if self.composer is not None:
self.composer.labelled(text)
self.on_composer("label", lambda composer: composer.labelled(text))

@property
def agent_title(self) -> str:
Expand Down
116 changes: 107 additions & 9 deletions src/toad/qt/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import asyncio
import inspect
from collections.abc import Callable

import shiboken6
from textual.content import Content
Expand All @@ -23,14 +24,15 @@
from agent_comms.registry.thread_presentation import NoThreadPresentation, ThreadPresentation
from agent_comms.ui_model.message_category import all_categories
from metaclass_registry.mro_dispatch import MroDispatch
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QWidget
from PySide6.QtCore import QEvent, QObject, Qt, QTimer
from PySide6.QtWidgets import QBoxLayout, QWidget
from pyqt_reactive.protocols.widget_adapters import PyQtWidgetMeta

from toad.agent_binding import AgentConnection, NoAgentConnection
from toad.agent_turn_events import AgentTurnEvents
from toad.answer import Ask
from toad.qt.agent_surface import QtSurfaceBinding, subscribe_agent
from toad.qt.metrics import UiGap
from toad.client.agent_bound import ObservedAgentBinding
from toad.client.bus_submission import TypedText
from toad.client.category_selection import CategorySelection
Expand Down Expand Up @@ -67,6 +69,24 @@
from toad.workspace_frame import WorkspaceFrame


class ComposerPlaceholder(QWidget):
"""A view's composer until it is built (`QtConversation.reserve_composer`): as tall as
that kind's composer last was, so nothing moves when it arrives. A tap or the focus on
it builds the composer at once and hands it the focus."""

def __init__(self, view: QtConversation, height: int) -> None:
super().__init__()
self.view = view
self.setFixedHeight(height)
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)

def mousePressEvent(self, event) -> None: # type: ignore[override]
self.view.mount_composer(focus=True)

def focusInEvent(self, event) -> None: # type: ignore[override]
self.view.mount_composer(focus=True)


class QtConversation(
AgentTurnEvents,
QtViewSettings,
Expand Down Expand Up @@ -104,7 +124,12 @@ class QtConversation(
_unpublished_presentation: ThreadPresentation = NoThreadPresentation()
"""An observed presentation whose transcript refresh waits for this view to be shown."""
composer: Composer | None = None
"""Textual's prompt; a thread view mounts it one Qt tick after construction."""
"""Textual's prompt, built just after the view's history first paints
(`reserve_composer`); None until then."""
composer_heights: dict[type, int] = {}
"""Each view kind's composer height when it was last built: the placeholder's height, so
nothing moves when the composer arrives. Shared by every view of the kind."""
_composer_reserved: tuple | None = None
activity: tuple[QWidget, ...]
"""The rows under the transcript that observe Core, each closed with the view."""

Expand All @@ -124,6 +149,9 @@ def _setup_conversation(self, app) -> None:
self.feedback = QtFlash(app, app.renderer)
self.agent_activity = QtObservedSweep(self.working, renderer=app.renderer)
self.submissions = ConversationSubmissions(self)
# What the composer is told before it is built, the latest of each kind, told at
# its mount (`on_composer`).
self._composer_applies: dict[str, Callable[[Composer], None]] = {}
# Every conversation answers the workspace's `ViewAction` keys, as Textual's
# `WorkspaceFrame` does for whichever conversation it shows: each member whose
# declared capability this view has binds through the shared family loop, so
Expand All @@ -137,11 +165,83 @@ def back_to_bottom_windows(self) -> tuple[JumpsToLatest, ...]:
(`JumpsHistory`): `BackToBottomAction.apply(self)` jumps it to its latest row."""
return (self.messages,) if self.messages.can_jump_to_latest else ()

# ---- The composer: built once the view's history has painted ----

def reserve_composer(self, layout: QBoxLayout, build: Callable[[], Composer],
mounted: Callable[[Composer], None]) -> None:
"""The composer's place in `layout`, held by a placeholder as tall as this kind's
composer last was. The composer is built just after the history first paints, so
opening a view draws its history without waiting for the composer (a channel's took
170 ms of a 491 ms open at a phone's speed), and a view never shown (a restored tab
in the background) builds none until it is. On Qt-for-Android this also keeps
``QPlainTextEdit`` out of the first frame's EGL setup, which it deadlocks against
(``QtAndroidAccessibility``). `mounted` places what goes with it."""
placeholder = ComposerPlaceholder(self, self.composer_heights.get(type(self), self.estimated_composer_height()))
layout.addWidget(placeholder)
self._composer_reserved = (layout, placeholder, build, mounted)
self.messages.viewport().installEventFilter(self)

def estimated_composer_height(self) -> int:
"""Before any composer of this kind was built: its editor (one line and the padding
`Composer.fit_height` gives it) over its info bar (a line and its margin)."""
line = self.fontMetrics().lineSpacing()
return (line + 24) + (line + UiGap.tight)

def eventFilter(self, watched: QObject, event: QEvent) -> bool: # type: ignore[override]
if (event.type() == QEvent.Type.Paint and self._composer_reserved is not None
and watched is self.messages.viewport()):
watched.removeEventFilter(self)
QTimer.singleShot(0, self.mount_composer)
return super().eventFilter(watched, event)

def mount_composer(self, focus: bool = False) -> None:
"""Build the reserved composer in its placeholder's place, then tell it what it was
told meanwhile. Touching the placeholder mounts it at once, with the focus, so
typing never waits. A failed mount is loud: a silently missing composer is how the
mailbox view first shipped."""
reserved, self._composer_reserved = self._composer_reserved, None
if reserved is None or not shiboken6.isValid(self):
return
layout, placeholder, build, mounted = reserved
self.messages.viewport().removeEventFilter(self)
try:
composer = build()
except Exception as error:
self.app.show_error(error, "Composer mount failed")
return
layout.replaceWidget(placeholder, composer)
placeholder.deleteLater()
self.composer = composer
mounted(composer)
applies, self._composer_applies = self._composer_applies, {}
for apply in applies.values():
apply(composer)
if focus:
composer.editor.setFocus()
QTimer.singleShot(0, partial(self.remember_composer_height, composer))

def remember_composer_height(self, composer: Composer) -> None:
"""The height the composer asks for, not the room it was given: a view whose
transcript is not laid out yet lets it stretch."""
if shiboken6.isValid(composer):
self.composer_heights[type(self)] = composer.sizeHint().height()

def on_composer(self, kind: str, apply: Callable[[Composer], None]) -> None:
"""Tell the composer something: now once it is built, else at its mount, where only
the latest of each `kind` is told (a label, a status, the mention candidates)."""
if self.composer is not None:
apply(self.composer)
else:
self._composer_applies[kind] = apply

def close_core_events(self) -> None:
"""The view's subscriptions end, the rows under the transcript stop observing, and
a command read in flight is dropped: it would hand its catalog to a deleted
composer. Reads are exclusive across views, so the one running may be another
tab's; that composer asks again on its next keystroke (`Composer.refresh_offers`)."""
tab's; that composer asks again on its next keystroke (`Composer.refresh_offers`).
A composer not built yet never will be."""
self._composer_reserved = None
self._composer_applies.clear()
super().close_core_events()
for row in self.activity:
row.close_activity()
Expand Down Expand Up @@ -172,9 +272,8 @@ def thread_status(self, status) -> None:
self.sync_status()

def sync_status(self) -> None:
"""The info bar shows `ComposerStatus.composed_status()` once the composer exists."""
if self.composer is not None:
self.composer.show_status(self.composed_status())
"""The info bar shows `ComposerStatus.composed_status()`, once the composer exists."""
self.on_composer("status", lambda composer: composer.show_status(self.composed_status()))

def present_thread_status(self) -> None:
"""A native agent reports its configuration through ACP (Textual's
Expand Down Expand Up @@ -239,8 +338,7 @@ def update_slash_commands(self) -> None:

async def read_commands(self) -> None:
catalog = await self.read_command_catalog()
if self.composer is not None:
self.composer.set_commands(catalog.commands)
self.on_composer("commands", lambda composer: composer.set_commands(catalog.commands))

async def read_command_catalog(self) -> CommandCatalog:
"""Textual's `Conversation.read_command_catalog`: the bound agent's advertised
Expand Down
3 changes: 1 addition & 2 deletions src/toad/qt/submission_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ def delivery_unknown(self, description: str, body: str) -> None:
async def refresh_composer(self, read_only: bool) -> None:
"""Hold the composer with the destination's read-only reason, or release it."""
self.composer_block = MessageDestination.read_only_reason if read_only else ""
if self.composer is not None:
self.composer.hold(self.composer_block)
self.on_composer("hold", lambda composer: composer.hold(self.composer_block))

def draws_user_message(self, reference) -> bool:
return self.message_history.draws(reference)
Expand Down
25 changes: 9 additions & 16 deletions src/toad/qt/thread_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
from typing import TYPE_CHECKING

from agent_comms.messaging.channel_targets import CommandTarget
from functools import partial

from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QVBoxLayout, QWidget
from pyqt_reactive.protocols.widget_adapters import PyQtWidgetMeta
Expand Down Expand Up @@ -141,10 +143,8 @@ def _setup_prompt_stack(self, app: "QtToadApp", layout: QVBoxLayout, incarnation
"""Mount, under the transcript, the rows Textual's `Conversation.compose` yields
after its window, in its order: flash, sweep, session status, goal bar, prompt.

The composer mounts one Qt event-loop tick later: on Qt-for-Android, mounting
``QPlainTextEdit`` during ``__init__`` races ``QtAndroidAccessibility`` with the
first-paint EGL setup and deadlocks the window. Its slot is reserved here so it
lands in order."""
The composer is built once the transcript has painted (`reserve_composer`); its
slot is reserved here so it lands in order, with the question under it."""
self.thread_activity = QtSessionDetails(self, app.renderer)
self.goal_bar = None if incarnation is None else QtGoalBar(app, app.renderer, incarnation)
self.activity = tuple(row for row in (self.thread_activity, self.goal_bar) if row is not None)
Expand All @@ -154,22 +154,15 @@ def _setup_prompt_stack(self, app: "QtToadApp", layout: QVBoxLayout, incarnation
layout.addWidget(row)
layout.addLayout(self._composer_slot)
self.refresh_thread_status()
QTimer.singleShot(0, lambda: self._mount_composer(app))

def _mount_composer(self, app: "QtToadApp") -> None:
"""Deferred composer mount; see `_setup_prompt_stack`. A failed mount is loud:
a silently-missing composer is how the mailbox view first shipped."""
try:
self.composer = self.composer_class()(self, app.renderer)
except Exception as error:
app.show_error(error, "Composer mount failed")
return
self._composer_slot.addWidget(self.composer)
self.reserve_composer(self._composer_slot, lambda: self.composer_class()(self, app.renderer),
partial(self._composer_mounted, app))

def _composer_mounted(self, app: "QtToadApp", composer: Composer) -> None:
# Under the composer, as on a channel: the question an agent asks (a permission, a
# confirmation), hidden until asked.
self.question = QtQuestion(app, self)
self._composer_slot.addWidget(self.question)
self.composer.labelled(self.composer_label)
composer.labelled(self.composer_label)
self.sync_status()

async def command_target_context(self) -> TargetContext:
Expand Down
17 changes: 9 additions & 8 deletions src/toad/qt/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -1262,8 +1262,6 @@ def __init__(self, app: QtToadApp, entry: QtHistorySessionEntry) -> None:
# Textual's `CommsChatView.compose`: the flash under the window, the sweep painting
# `working()` (an idle turn, the peer's observed row, or the first page loading),
# the prompt (its info bar carries the thread status), then who is here.
self.composer = self.conversation.prompt(self)
self.composer.labelled(label)
self.activity = tuple(self.conversation.compose_activity(self))
# The inline consent prompt ("did you mean it?", edit/clear confirmations) — hidden
# until the conversation asks, mounted below the composer so the picks sit where
Expand All @@ -1275,7 +1273,8 @@ def __init__(self, app: QtToadApp, entry: QtHistorySessionEntry) -> None:
layout.addWidget(self.messages, 1)
layout.addWidget(self.feedback)
layout.addWidget(self.agent_activity)
layout.addWidget(self.composer)
self.reserve_composer(layout, lambda: self.conversation.prompt(self),
lambda composer: composer.labelled(label))
layout.addWidget(self.question)
# Under the prompt, not over it: who is here is reference (Textual's
# `CommsChatView.compose` yields the kind's activity after the prompt).
Expand Down Expand Up @@ -1306,7 +1305,8 @@ async def wait_content_ready(self) -> None:
def close_core_events(self) -> None:
"""The shared close (its history lets go of the wire), then the receipt stops following."""
super().close_core_events()
self.composer.receipt.stop()
if self.composer is not None:
self.composer.receipt.stop()

async def retire_presentation(self) -> None:
"""The history lets go of its page reader; its rows go with the widgets."""
Expand Down Expand Up @@ -1336,13 +1336,14 @@ async def _refresh_source(self) -> None:
finally:
self.content_ready.set()
self.submissions.settle()
self.composer.receipt.follow(str(source.root), next((
followed = (str(source.root), next((
references for fragment in reversed(history.fragments) if (references := fragment.sent_references)), ()),
history.pages[-1].prepared.page.source.selection.notification_identity)
self.on_composer("receipt", lambda composer: composer.receipt.follow(*followed))
self.refresh_thread_status()
self.sync_working()
label = self.conversation.label(source.references())
self.composer.labelled(label)
self.on_composer("label", lambda composer: composer.labelled(label))
read_only = await asyncio.to_thread(self.conversation.read_only, source.core)
await self.refresh_composer(read_only)
self.thread_status = await self.conversation.status_text(source, read_only=read_only)
Expand Down Expand Up @@ -1377,8 +1378,8 @@ def compose_peer_activity(self, peer: ThreadIncarnation) -> Iterator[QtGoalBar |

async def update_channel_mentions(self, source: ReferencedCore) -> None:
answer = await self.app.coordination_access.current_sidebar()
self.composer.set_mention_candidates(
await self.app.preparation.run_thread(self.conversation.mention_candidates, answer))
candidates = await self.app.preparation.run_thread(self.conversation.mention_candidates, answer)
self.on_composer("mentions", lambda composer: composer.set_mention_candidates(candidates))

# Commands the composer offers after a /

Expand Down
16 changes: 16 additions & 0 deletions tools/qt_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -2154,6 +2154,22 @@ def wrapper(*args, **kwargs):
timed_open(delegate, name, f"rows.{name}")
for name in ("rows_changed", "show_pages"):
timed_open(qt_history.QtHistoryWindow, name, f"window.{name}")
for name in ("new_document", "final_document"):
if name in delegate.__dict__:
timed_open(delegate, name, f"rows.{name}")
for name in ("fragment_height", "block_row"):
timed_open(qt_history.HistoryRowDelegate, name, f"history.{name}")
# The composer's mount after the first paint, and whether its placeholder held its height.
from toad.qt.conversation import QtConversation
timed_open(QtConversation, "mount_composer", "open.composer_mount")
remember = QtConversation.remember_composer_height

def compared(view, composer) -> None:
placeholder = view.composer_heights.get(type(view), view.estimated_composer_height())
print(f" composer {type(view).__name__}: placeholder {placeholder}px, built {composer.sizeHint().height()}px (given {composer.height()}px)",
flush=True)
remember(view, composer)
QtConversation.remember_composer_height = compared
self.timings = timings

def write_timings(self, probe) -> None:
Expand Down
3 changes: 3 additions & 0 deletions tools/qt_inherit_ratchet.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@
}

QT_ONLY = {
'toad.qt.conversation.ComposerPlaceholder': "a Qt composer's place held before it is built: Qt builds a view's widgets in "
"its constructor, so a composer built there holds the view's first frame (and on Android races the first frame's EGL "
"setup); Textual composes a screen's widgets and mounts them after its first frame, so it has no placeholder to hold",
'toad.qt.widget_animation.WidgetAnimation': "a clock target's life bound to its Qt widget's C++ lifetime (destroyed signal, shiboken validity); a Textual widget is a Python object the clock can always ask",
'toad.qt.history.ArrivalFade': "a burst's rows painted at the ARRIVAL cascade's frame as QPainter opacity; Textual paints the same frame into its strips (TranscriptHistory.arrivals_began), and both read the cascade from toad.frame_presentation",
'toad.qt.action_shortcuts.BoundAction': "a live QShortcut and the action it answers: Qt fires neither of two shortcuts sharing a key (activatedAmbiguously), so ActionKeys keeps each to apply the declared binding order; Textual walks its binding chain itself",
Expand Down
Loading