diff --git a/src/toad/acp/agent_controller.py b/src/toad/acp/agent_controller.py index 78a65464a..ab2400ca4 100644 --- a/src/toad/acp/agent_controller.py +++ b/src/toad/acp/agent_controller.py @@ -32,8 +32,15 @@ from toad.acp.terminal_owner import OperationalTerminalOwner from toad.client.transcript_reader import CoordinationTranscriptReader from toad.core import events as core_events -from toad.core.events import LogAgentFail +from toad.core.events import ( + AgentFail, + AvailableCommandsUpdate, + LogAgentFail, + McpClientStopped, + Plan, +) from toad.plan import PlanDisplayState, PlanItem +from toad.render_backend import Renderer, RenderTask from toad.surface_binding import DetachedSurfaceBinding, SurfaceBinding if TYPE_CHECKING: @@ -44,8 +51,6 @@ from agent_comms.acp_extension import QueueScope, TranscriptSnapshotUpdate from toad.acp.agent import Agent - from toad.core.events import AgentFail - from toad.render_backend import Renderer, RenderTask class SourceIdentity: @@ -137,7 +142,6 @@ def detach(self, target) -> None: self.terminals.detach() async def restore(self, binding: SurfaceBinding) -> None: - from toad.core.events import AvailableCommandsUpdate if self.surface is not binding: return @@ -148,7 +152,6 @@ async def restore(self, binding: SurfaceBinding) -> None: agent.update_status_line() agent.events.publish(AvailableCommandsUpdate()) if self.plan_display.entries: - from toad.core.events import Plan agent.events.publish(Plan(self.plan_display.entries)) agent._post_queue_view() @@ -162,7 +165,6 @@ async def publish_transcript_snapshot( await binding.publish_transcript_snapshot(session, update, self) def connection_closed(self) -> None: - from toad.core.events import McpClientStopped agent = self.agent agent.session.closed() @@ -182,13 +184,11 @@ def publish_plan(self, entries: list[PlanItem]) -> None: replacing the entries, so any frontend can ask `plan_display.newly_complete(entry)` to drive the same completion-transition decision — one owner, both frontends agree on which rows just transitioned.""" - from toad.core.events import Plan self.plan_display.update(entries) self.agent.events.publish(Plan(entries)) def publish_commands(self, commands: list[AvailableCommand]) -> None: - from toad.core.events import AvailableCommandsUpdate self.commands = commands self.agent.events.publish(AvailableCommandsUpdate()) diff --git a/src/toad/client/structured_context.py b/src/toad/client/structured_context.py index ff2827ad0..2d8aced96 100644 --- a/src/toad/client/structured_context.py +++ b/src/toad/client/structured_context.py @@ -14,6 +14,7 @@ import json import re from abc import ABC, abstractmethod +from collections.abc import Iterator from dataclasses import dataclass from typing import ClassVar @@ -452,36 +453,58 @@ def _split_context_sections(text: str) -> tuple[ContextSectionPart, ...]: return () +class DecodedStructuredBlock(ABC): + """Present or absent structured part decoded from an inline tag block.""" + + def __iter__(self) -> Iterator[StructuredPart]: + return iter(()) + + +@dataclass(frozen=True) +class AbsentDecodedStructuredBlock(DecodedStructuredBlock): + """Absent `DecodedStructuredBlock` carrying no value.""" + + +@dataclass(frozen=True) +class HeldDecodedStructuredBlock(DecodedStructuredBlock): + """Held `DecodedStructuredBlock` carrying its present value.""" + + value: StructuredPart + + def __iter__(self) -> Iterator[StructuredPart]: + yield self.value + + class StructuredTag(DeclaredFamily, affix="Tag"): """Inline XML-style tag emitted by reasoning/context models; decoded once at the tag boundary.""" @classmethod @abstractmethod - def decode_block(cls, inner: str, *, streaming: bool) -> tuple[StructuredPart, ...]: ... + def decode_block(cls, inner: str, *, streaming: bool) -> DecodedStructuredBlock: ... class ThinkTag(StructuredTag): @classmethod - def decode_block(cls, inner: str, *, streaming: bool) -> tuple[StructuredPart, ...]: + def decode_block(cls, inner: str, *, streaming: bool) -> DecodedStructuredBlock: if not inner.strip() and not streaming: - return () - return (ThinkingPart.from_text(inner, streaming=streaming),) + return AbsentDecodedStructuredBlock() + return HeldDecodedStructuredBlock(ThinkingPart.from_text(inner, streaming=streaming)) class CtxTag(StructuredTag): @classmethod - def decode_block(cls, inner: str, *, streaming: bool) -> tuple[StructuredPart, ...]: + def decode_block(cls, inner: str, *, streaming: bool) -> DecodedStructuredBlock: if not inner.strip() and not streaming: - return () - return (LiveContextPart.from_text(inner, title="Context ()", streaming=streaming),) + return AbsentDecodedStructuredBlock() + return HeldDecodedStructuredBlock(LiveContextPart.from_text(inner, title="Context ()", streaming=streaming)) class ToolCallTag(StructuredTag): @classmethod - def decode_block(cls, inner: str, *, streaming: bool) -> tuple[StructuredPart, ...]: + def decode_block(cls, inner: str, *, streaming: bool) -> DecodedStructuredBlock: if not inner.strip(): - return () - return (ToolCallPart.from_tag(inner),) + return AbsentDecodedStructuredBlock() + return HeldDecodedStructuredBlock(ToolCallPart.from_tag(inner)) _TAG_OPEN = re.compile( diff --git a/src/toad/core/events.py b/src/toad/core/events.py index 2ab524f23..f478952ed 100644 --- a/src/toad/core/events.py +++ b/src/toad/core/events.py @@ -6,7 +6,7 @@ from dataclasses import dataclass, field from functools import cached_property from pathlib import Path -from typing import TYPE_CHECKING, Annotated, ClassVar +from typing import Annotated, ClassVar from weakref import WeakSet, WeakValueDictionary from formbridge.publications import ( @@ -33,10 +33,8 @@ from toad.plan import PlanItem from toad.client.tab_identity import TabIdentity from formbridge.operations import ExclusiveKind, OperationKind - -if TYPE_CHECKING: - from toad.turn_presentation import TurnPresentation - +from toad.project_link import AcpLogLink +from toad.turn_presentation import TurnPresentation class ThreadInterestUpdate(OperationKind, ExclusiveKind): """Tells Core which threads the open views are interested in; a newer update supersedes one running.""" @@ -398,7 +396,6 @@ class FailureLog: log_path: Path async def show_log(self, view: TurnPresentation) -> None: - from toad.project_link import AcpLogLink await view.present_log_link(AcpLogLink.markdown(self.log_path)) diff --git a/src/toad/preferences.py b/src/toad/preferences.py index 61c104e5c..7f2534868 100644 --- a/src/toad/preferences.py +++ b/src/toad/preferences.py @@ -28,6 +28,8 @@ from toad import atomic, paths from toad import setting_effects as effects from formbridge.forms.declared_fields import DeclaredField, FieldPath, FormPage, Multiline +from toad.core.events import CoreEventStream +from toad.core.preference_events import PreferenceChanged from toad.hint_labels import HintLabels, NextLetterHintLabels from toad.key_modes import KeyMode, Standard from toad.keymap import Keymap @@ -459,7 +461,6 @@ def __init__( applied: Callable[[DeclaredField], None] = no_effect, report_error: Callable[[atomic.AtomicWriteError], None] = raise_save_error, ) -> None: - from toad.core.events import CoreEventStream raw = {} if raw is None else raw self.root = FieldPath(root) @@ -507,7 +508,6 @@ def _apply_fields(self, fields: Iterable[DeclaredField]) -> None: self.applied(setting) def changed(self, changed: builtins.set[str]) -> None: - from toad.core.preference_events import PreferenceChanged matched = [ DeclaredField(self.state, path) diff --git a/src/toad/prompt_cursor.py b/src/toad/prompt_cursor.py index 11f9d79eb..0b9d563a2 100644 --- a/src/toad/prompt_cursor.py +++ b/src/toad/prompt_cursor.py @@ -15,6 +15,7 @@ from toad.client.line_blocks import Span from toad.core.input_events import HistoryMove from toad.slash_command import SlashCommand +from toad.widgets.prompt_popup import CompletionPopup if TYPE_CHECKING: from toad.widgets.prompt import PromptTextArea @@ -134,7 +135,6 @@ def __init__(self, editor: PromptTextArea): self._editor = ref(editor) def changed(self, previous: Selection, current: Selection) -> None: - from toad.widgets.prompt_popup import CompletionPopup editor = self._editor() if editor is None: diff --git a/tools/physical_ui.py b/tools/physical_ui.py index b4a13c326..d11024a7d 100644 --- a/tools/physical_ui.py +++ b/tools/physical_ui.py @@ -52,6 +52,7 @@ from rich.segment import Segment from textual.geometry import Region, Size from textual.strip import Strip +from toad.preferences import INTERFACE, SETTINGS, SavedSettings, ToadSettings from ui_theme.wal import WalFile from tools import physical_ui_remote @@ -355,7 +356,6 @@ def prepare_target(cls, root: Path, runtime: LaunchRuntime) -> RunResources: Only presentation settings travel. Saved Toad databases/tabs never do. Existing installer acceptance and copied-history runs share this setup. """ - from toad.preferences import INTERFACE, SETTINGS, SavedSettings, ToadSettings root = root.resolve(strict=True) runtime.require_available() diff --git a/tools/qt_drive.py b/tools/qt_drive.py index 9c47a80c7..d1ed99f09 100644 --- a/tools/qt_drive.py +++ b/tools/qt_drive.py @@ -21,7 +21,7 @@ import os import sys import traceback -from abc import ABC, abstractmethod +from abc import abstractmethod from pathlib import Path from collections.abc import Callable from typing import ClassVar @@ -97,7 +97,7 @@ from toad.thread_sidebar_declarations import ThreadSidebarPanel from toad.client.bus_submission import ConversationSubmission from toad.setting_choices import CenterColumnAlignment, HiddenScrollbar, TransientScrollbar -from toad.message_rows import IrcMessageStyle, MarkdownMessageStyle +from toad.message_rows import IrcMessageStyle, MarkdownMessageStyle, Divider 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 @@ -155,7 +155,7 @@ def require_none(cls, step: str) -> None: raise AssertionError(f"{step}: widgets shown as their own top-level windows: {sorted(set(cls.seen))}") -class Scenario(DeclaredFamily, ABC, affix="Scenario"): +class Scenario(DeclaredFamily, affix="Scenario"): """One walk through the client; its declared name is the command-line word.""" summary: ClassVar[str] @@ -771,7 +771,7 @@ async def run(self) -> None: # The newest message whose header names TOAD_DRIVE_HEADER (any header by default). named = os.environ.get("TOAD_DRIVE_HEADER", "") headed = max(row for row, fragment in enumerate(fragments) - if any(type(block).__name__ == "Divider" and named in block.label for block in fragment.line_blocks)) + if any(type(block).__name__ == Divider.__name__ and named in block.label for block in fragment.line_blocks)) window.scroll_to_row(headed) await asyncio.sleep(1.5) self.report("3-newest-header", rows=len(fragments)) diff --git a/tools/qt_inherit_ratchet.py b/tools/qt_inherit_ratchet.py index 603cff4d4..34db153dd 100644 --- a/tools/qt_inherit_ratchet.py +++ b/tools/qt_inherit_ratchet.py @@ -37,6 +37,9 @@ from functools import cache from pathlib import Path +from PySide6.QtWidgets import QDialog +from toad.qt.presented_window import PresentedWindow + KNOWN_COPIES = { } @@ -326,8 +329,6 @@ def unpresented() -> frozenset[str]: """Qt windows opened over the app that do not inherit its one presentation owner. Every Qt dialog is presented by `toad.qt.presented_window.PresentedWindow` (a phone fills the app window, a desktop floats), so one that lays itself out has no ratchet baseline: zero.""" - from PySide6.QtWidgets import QDialog - from toad.qt.presented_window import PresentedWindow return frozenset(path for path, cls in classes_under("toad").items() if path.startswith("toad.qt.") and issubclass(cls, QDialog) and not issubclass(cls, PresentedWindow))