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
2 changes: 2 additions & 0 deletions src/toad/client/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ def active_members(self, model: SidebarModel):
def activity_title(members) -> str:
"""The collapsed activity line under the composer: how many members are active and
the first two of them."""
if not members:
return "0 active"
names = ", ".join(row.name for row in members[:2])
remaining = f" +{len(members) - 2}" if len(members) > 2 else ""
return f"{len(members)} active · {names}{remaining}"
Expand Down
21 changes: 13 additions & 8 deletions src/toad/client/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,19 +148,24 @@ def show_info(self, text: str, title: str) -> None:
self.notify(text, title=title)

def show_warning(self, text: str, title: str) -> None:
"""Native warning notice of plain text; no Core state change."""
"""Native warning notice of plain text; no Core state change. The notice puts itself
away, so its text is saved with the stack that reported it (paths.save_warning, in
logs/warnings): a warning the reader saw and could not keep can still be read back."""
paths.save_warning(text, title)
self.notify(text, title=title, severity="warning", markup=False)

def show_error(self, error: Exception | str, title: str,
severity: Severity = "error") -> None:
"""Native error notice with the original exception.

A refusal is transient: ResultShower's text, or a Core refusal (ToolRefusedError: an
unknown channel, a refused goal action) — an intentional answer, not a failure, so
nothing is saved to disk. Any other exception is saved under a timestamped name in
Toad's state folder (paths.save_error) and posted to the dev crash sink; the notice
itself puts itself away after notice_seconds."""
"""Native error notice with the original exception; every one is saved under a
timestamped name in Toad's state folder (paths.save_error).

A refusal (ResultShower's text, or a Core refusal, ToolRefusedError: an unknown
channel, a refused goal action) is an intentional answer, not a failure: its notice
stays one line and it is not posted to the dev crash sink. Any other exception's
notice names its saved log and is posted there. Either notice puts itself away
after notice_seconds."""
if isinstance(error, (str, ToolRefusedError)):
paths.save_error(error, f"Refused {title}")
self.notify(str(error), title=title, severity=severity, markup=False)
return
path = paths.save_error(error, title)
Expand Down
14 changes: 14 additions & 0 deletions src/toad/client/session_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,20 @@ def agent_for_opening[Binding](self, default: Binding) -> Binding:
"""A project origin with no launch of its own opens views with the app's binding."""
return default

def opening_standing(self, selected_mode: str) -> str:
"""What must not change while a thread opened from here is prepared: a view opens
what it was asked for only while it is still the tab shown."""
return selected_mode


class HomeSessionOrigin(ProjectSessionOrigin):
"""Home, the welcome: every row and link opens from here whichever tab is shown
(`TargetOpen`), so another tab being selected meanwhile, as a second tap's opening is,
leaves its openings current. Textual's `WelcomeScreen` and Qt's `QtWelcomeOrigin`."""

def opening_standing(self, selected_mode: str) -> str:
return ""


class NoConversationView(SessionScope):
"""The view the thread sidebar follows while no conversation is open: the welcome, as
Expand Down
26 changes: 22 additions & 4 deletions src/toad/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,19 +72,37 @@ def generate_datetime_filename(prefix: str, suffix: str) -> str:


def save_error(error: BaseException | str, prefix: str) -> Path:
"""Persist an error under a timestamped name: an exception's traceback and chained causes,
or an error given as text with the stack that reported it."""
"""Persist an error under a timestamped name in logs/errors."""
return _save_report(error, prefix, get_errors())


def save_warning(text: str, prefix: str) -> Path:
"""Persist a warning the reader was shown under a timestamped name in logs/warnings:
a warning is not a failure (logs/errors stays the failures), but its notice puts itself
away, so it is kept to be read back."""
return _save_report(text, prefix, get_warnings())


def _save_report(error: BaseException | str, prefix: str, directory: Path) -> Path:
"""An exception's traceback and chained causes, or text with the stack that reported it."""
if isinstance(error, BaseException):
report = traceback.format_exception(error)
else:
report = [f"{error}\n\nReported from:\n", *traceback.format_stack()[:-1]]
path = get_errors() / generate_datetime_filename(prefix, ".txt")
report = [f"{error}\n\nReported from:\n", *traceback.format_stack()[:-2]]
path = directory / generate_datetime_filename(prefix, ".txt")
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
stream.writelines(report)
return path


def get_warnings() -> Path:
"""The directory holding the warnings the reader was shown."""
path = get_log() / "warnings"
path.mkdir(0o700, exist_ok=True)
return path


def get_errors() -> Path:
"""The directory holding saved exception tracebacks, apart from agent logs."""
path = get_log() / "errors"
Expand Down
6 changes: 3 additions & 3 deletions src/toad/qt/window.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
from toad.core.events import CoordinationObserved, TabHistoryChanged
from toad.launch_binding import AgentBinding, NoAgent
from toad.navigation_context import NoNavigationOwner
from toad.client.session_scope import ProjectSessionOrigin
from toad.client.session_scope import HomeSessionOrigin
from toad.client.sidebar_filter import SidebarFilter
from toad.client.sidebar_panels import PanelSpec
from toad.navigation_context import ConversationViewNavigation
Expand Down Expand Up @@ -574,13 +574,13 @@ def offer(self, point: QPoint) -> None:
self.listing.host.offer_entries(entries)


class QtWelcomeOrigin(ProjectSessionOrigin):
class QtWelcomeOrigin(HomeSessionOrigin):
"""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
hands to `thread_navigation.open` through `QtWorkspaceViews.origin(WELCOME)`.

Textual's `WelcomeScreen` (`screens/welcome.py:234`) inherits `ProjectSessionOrigin`
Textual's `WelcomeScreen` (`screens/welcome.py:234`) inherits `HomeSessionOrigin`
directly because its widget metaclass does not clash."""

is_attached: bool = True
Expand Down
4 changes: 2 additions & 2 deletions src/toad/screens/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
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 ProjectSessionOrigin
from toad.client.session_scope import HomeSessionOrigin
from toad.thread_identity import ThreadIdentity
from toad.widgets.comms_sidebar import (
ChannelRow,
Expand Down Expand Up @@ -255,7 +255,7 @@ class WelcomeScreen(
NativeMethodKeys,
TogglesIrc,
NavigationOwner,
ProjectSessionOrigin,
HomeSessionOrigin,
CenteredChildren,
SessionView,
ToadNode,
Expand Down
4 changes: 2 additions & 2 deletions src/toad/thread_navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@
@dataclass(frozen=True)
class ThreadOrigin:
source: ProjectSessionOrigin
selected_mode: str
standing: str
root: str | None
identity: str

@classmethod
def capture(cls, app: NavigationHost, source: ProjectSessionOrigin) -> ThreadOrigin:
return cls(
source,
app.selected_mode,
source.opening_standing(app.selected_mode),
source.coordination_root,
source.thread_identity.thread_name(),
)
Expand Down
2 changes: 1 addition & 1 deletion src/toad/widgets/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1386,7 +1386,7 @@ async def on_agent_fail(self, event: AgentFail) -> None:
self.prompt.sync_session()
for details in self.query(OperationalSessionDetails):
details.sync_turn()
self.app.notify(event.message, title="Agent failure", severity="error", markup=False)
self.app.show_error(event.message, "Agent failure")

self.launch.publish_usage(
self.app.application.usage.publish,
Expand Down
122 changes: 119 additions & 3 deletions tools/qt_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import qasync
from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, Qt
from PySide6.QtGui import QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent
from PySide6.QtGui import QInputMethodEvent, QKeyEvent, QKeySequence, QMouseEvent, QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QAbstractButton, QAbstractScrollArea, QDialog, QLabel, QScroller, QStyleOptionViewItem, QApplication, QPushButton, QWidget

Expand All @@ -37,6 +37,7 @@
from agent_comms.ui_model.message_category import MessageCategory
from objectstate import DottedFieldPath
from toad.qt.frame_probe import FrameProbe, ProbedApplication
from toad.client.application import BusDiscovery
from toad.client.application_actions import (
ApplicationAction, NewSessionAction, NewThreadAction, QuitAction, SettingsAction,
)
Expand Down Expand Up @@ -81,8 +82,10 @@
from toad.setting_choices import CenterColumnAlignment
from toad.message_rows import IrcMessageStyle, MarkdownMessageStyle
from toad.client.input_modality import KeyboardInput, TouchInput
from toad.qt.float_layer import QtNoticeCard
from toad.qt.float_layer import QtFloatLayer, QtNoticeCard
from toad.qt.menu import QtMenuRow
from toad.qt.activity import ChannelActivity
from toad import paths
from toad.qt.window import ConversationRow, ConversationView, MenuActionRun, QtToadApp
from toad.conversation_turn import LocalTurnBinding
from toad.core.events import TextAgentFail, UnsupportedResumeAgentFail
Expand Down Expand Up @@ -135,6 +138,10 @@ def finger_gesture(cls) -> FingerScrollGesture:
phone's."""
return FingerScrollGesture.of_platform()

@classmethod
def before_open(cls) -> None:
"""Run before the client opens, to watch what it does from its first frame."""

def __init__(self, app: QtToadApp, out: Path) -> None:
self.app = app
self.out = out
Expand Down Expand Up @@ -316,6 +323,103 @@ async def run(self) -> None:
SurroundScenario.report_surround(self, "1-opened", peer=peer.key)


class ParticipantSteps(Scenario, declared_name=None):
"""A finger tapping a channel's `N active` line and a thread row the way a phone can,
and every notice the client posts from its first frame, so a step can fail on one."""

notices: ClassVar[list[tuple[str, str]]]

@classmethod
def before_open(cls) -> None:
cls.notices = []
posted = QtFloatLayer.post

def recorded(layer, text: str, role, seconds: float) -> None:
cls.notices.append((role.name, text))
posted(layer, text, role, seconds)
QtFloatLayer.post = recorded

def failures_since(self, count: int) -> list[str]:
"""The warning and error notices posted after the first ``count``."""
return [f"{role}: {text}" for role, text in self.notices[count:] if role in ("WARNING", "ERROR")]

def activity(self) -> ChannelActivity:
found = self.page.findChildren(ChannelActivity)
if not found:
raise LookupError(f"{type(self.page).__name__} shows no channel activity line")
return found[0]

async def finger_tap(self, widget: QWidget, point: QPoint) -> None:
FingerScenario.press(widget, QEvent.Type.MouseButtonPress, point, True)
await asyncio.sleep(0.05)
FingerScenario.press(widget, QEvent.Type.MouseButtonRelease, point, False)
await asyncio.sleep(0.8)

async def tap_activity(self, label: str) -> None:
"""Open the channel's activity line, tap a listed member, and close it again."""
line = self.activity()
heading = QPoint(line.width() // 3, line.fontMetrics().height() // 2)
self.report(f"{label}-shown", text=self.activity_text(line), height=line.height())
await self.finger_tap(line, heading)
self.report(f"{label}-opened", open=line.shown.details_open, members=len(line.members),
height=line.height())
if line.members:
await self.finger_tap(line, QPoint(heading.x(), line.height() - heading.y()))
self.report(f"{label}-member-tapped", open=line.shown.details_open)
if line.shown.details_open:
await self.finger_tap(line, heading)
self.report(f"{label}-closed", open=line.shown.details_open)

@staticmethod
def activity_text(line: ChannelActivity) -> str:
document = QTextDocument()
document.setHtml(line.text())
return document.toPlainText()

async def open_twice(self, row: ConversationRow) -> None:
"""A row tapped twice, as a phone can deliver one tap, or a second tap while the
first opening mounts: both open from home, and the second lands on the same tab."""
self.app.open_row(row)
await asyncio.sleep(0.05)
self.app.open_row(row)
await until(lambda: getattr(self.page, "thread_identity", None) is not None
and self.page.thread_identity.thread_name() == row.target.name, row.target.name)
await asyncio.sleep(3.0)
named = sum(row.target.name in tab for tab in self.tabs())
if named != 1:
raise AssertionError(f"{row.target.name} is open in {named} tabs after a double tap")


class ParticipantsScenario(ParticipantSteps):
summary = ("at a Pixel 8a's width, by finger: tap #comms' and a second channel's `N active` "
"line open, a listed member, and closed; open a thread, then tap a thread row twice "
"as a phone can; fails on any warning or error notice, and on one that saved no file")

@classmethod
def finger_gesture(cls) -> FingerScrollGesture:
return TouchAsMouse()

async def run(self) -> None:
await self.open_named("#comms")
await self.tap_activity("1-comms")
other = await self.found(lambda row: isinstance(row, ConversationRow) and row.target.name.startswith("#")
and row.target.name != "#comms", "a second channel", rows=self.app.sidebar.items)
await self.open(other, other.target.name)
await self.tap_activity("2-channel")
peer = await self.thread_row()
await self.open(peer, peer.target.name)
await self.open_named("#comms")
await self.open_twice(peer)
self.report("3-double-tap", tabs=self.tabs())
saved = [*paths.get_errors().iterdir(), *paths.get_warnings().iterdir()]
print("notices:", self.notices, "saved:", sorted(path.name for path in saved), flush=True)
failures = self.failures_since(0)
if len(saved) < len(failures):
raise AssertionError(f"{len(failures)} warning/error notice(s) but {len(saved)} saved: {failures}")
if failures:
raise AssertionError(f"{len(failures)} warning/error notice(s): {failures}")


class SurroundScenario(Scenario):
summary = ("open a thread (PEER env, else the first working one) on a Pixel 8a and print every "
"row between its transcript and the tab bar, in Textual's PromptStack order")
Expand Down Expand Up @@ -900,7 +1004,7 @@ def first_row_y() -> tuple[int, int, int]:
app.menu_panel.hide()


class ShippedScenario(Scenario):
class ShippedScenario(ParticipantSteps):
summary = ("open every view kind the phone has and press every bound key, failing on any "
"exception: tools/android/shipped_run.py runs it on the shipped bundle")

Expand Down Expand Up @@ -995,7 +1099,12 @@ async def run(self) -> None:
self.close_dialogs()
await self.step("3-channel", lambda: self.open_named("#comms"))
await self.press_bound_keys("3-channel-keys")
await self.noticeless("3-channel-activity", lambda: self.tap_activity("3-channel-activity"))
await self.step("4-thread", lambda: self.open_named("scratch-live-pipeline"))
thread = await self.found(lambda row: isinstance(row, ConversationRow)
and row.target.name == "scratch-live-pipeline", "thread scratch-live-pipeline")
await self.step("4-thread-from-channel", lambda: self.open_named("#comms"))
await self.noticeless("4-thread-tapped-twice", lambda: self.open_twice(thread))
await self.step("4-thread-details", self.open_details)
await self.press_bound_keys("4-thread-keys")
# The reader keys (ctrl+d, ctrl+u, G) are declared for the vim modes only: press every
Expand Down Expand Up @@ -1024,6 +1133,12 @@ async def apply_offered_themes(self) -> None:
settings.set(SETTINGS.ui.theme, started)
self.report("1-themes", started=started, applied=applied)

async def noticeless(self, label: str, run) -> None:
"""A step that must post no warning or error notice."""
posted = len(self.notices)
await self.step(label, run)
self.faults.extend(f"{label}: {failure}" for failure in self.failures_since(posted))

async def open_details(self) -> None:
self.page.thread_activity.toggle()
await asyncio.sleep(0.3)
Expand Down Expand Up @@ -2757,6 +2872,7 @@ def main(arguments: list[str]) -> None:
FingerScrolling.install(application, scenario.finger_gesture())
watch = StrayWindows()
application.installEventFilter(watch)
scenario.before_open()
qasync.run(drive(scenario, connection, Path(own[1])))


Expand Down
Loading