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
16 changes: 8 additions & 8 deletions src/toad/acp/agent_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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())
Expand Down
43 changes: 33 additions & 10 deletions src/toad/client/structured_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 (<ctx>)", streaming=streaming),)
return AbsentDecodedStructuredBlock()
return HeldDecodedStructuredBlock(LiveContextPart.from_text(inner, title="Context (<ctx>)", 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(
Expand Down
9 changes: 3 additions & 6 deletions src/toad/core/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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."""
Expand Down Expand Up @@ -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))

Expand Down
4 changes: 2 additions & 2 deletions src/toad/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/toad/prompt_cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion tools/physical_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
8 changes: 4 additions & 4 deletions tools/qt_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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))
Expand Down
5 changes: 3 additions & 2 deletions tools/qt_inherit_ratchet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
}

Expand Down Expand Up @@ -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))
Expand Down
Loading