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: 2 additions & 1 deletion src/toad/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@
from toad.widgets.comms_command_dialog import ScreenCommandOrigin
from toad.widgets.comms_sidebar import CommsSidebar
from toad.widgets.side_bar import SideBar, SideBarCollapsible
from toad.widget_actions import ApplicationAction, DeclaredWidgetActions
from toad.client.application_actions import ApplicationAction
from toad.widget_actions import DeclaredWidgetActions
from toad.widgets import tool_call # noqa: F401 - register widget classes
from toad.widgets.comms_transfer import Transfers
from toad.work_preparation import PreparationRuntime
Expand Down
44 changes: 4 additions & 40 deletions src/toad/application_actions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Textual actions, bindings and palette entries share their declarations."""
"""The application actions whose bodies need Textual, declared after the shared ones in
`toad.client.application_actions`, and the palette that offers the whole family."""

from __future__ import annotations

Expand All @@ -12,13 +13,13 @@
from toad.preferences import SETTINGS
from toad.screens.keymap import KeymapScreen
from toad.keymap import KeyInvocationId
from toad.widget_actions import (
from toad.client.application_actions import (
ApplicationAction,
ReplacesFrameworkAction,
System,
VimWorkspaceAction,
YieldingKey,
)
from toad.widget_actions import VimWorkspaceAction
from toad.widgets.comms_transfer import Transfer, Transfers
from toad.core.session_requests import SessionNavigate
from toad.sidebar_placement import LeftSidebarEdge, RightSidebarEdge, SidebarEdge
Expand All @@ -27,15 +28,6 @@
from toad.app import ToadApp


# Declaration order is the order of the menu and the palette.
class NewThreadAction(ApplicationAction):
"""Start a thread in the selected project."""

async def apply(self, app: ToadApp) -> None:
navigation = app.session_navigation
navigation.open_thread_form(navigation.selected_project())


class OpenBusAction(ApplicationAction):
"""Connect to this machine's bus or choose another machine."""

Expand Down Expand Up @@ -177,25 +169,6 @@ async def apply(self, app: ToadApp) -> None:
app.push_screen(KeymapScreen(focused))


class ChannelsAction(ApplicationAction):
"""Reveal channels and focus the selected session."""

keys = {EditingMode: ("ctrl+s",)}
show = True

async def apply(self, app: ToadApp) -> None:
app.run_worker(app.session_navigation.reveal)


class DirectMessagesAction(ApplicationAction):
"""Open the most recently selected direct conversation."""

keys = {EditingMode: ("ctrl+shift+d",)}

async def apply(self, app: ToadApp) -> None:
app.session_navigation.direct_messages()


class VimCycleTabAction(VimWorkspaceAction, declared_name=None):
direction: Literal[-1, 1]

Expand Down Expand Up @@ -276,15 +249,6 @@ class VimMoveTabRightAction(VimMoveTabAction):
direction = +1


class QuitAction(ReplacesFrameworkAction, ApplicationAction):
"""Save preferences and quit the application."""

keys = {EditingMode: ("ctrl+q",)}

async def apply(self, app: ToadApp) -> None:
app.application.quit()


class ApplicationCommands(Provider):
"""Discovery and search derive the same capability view; no command roster."""

Expand Down
202 changes: 202 additions & 0 deletions src/toad/client/application_actions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"""The action family every client offers: what each action is called, when it is offered,
the keys it declares and what it does through the shared host. A client projects the
declared keys into its own bindings; members whose bodies need one toolkit are declared
in that toolkit's modules, as members of this same family."""

from __future__ import annotations

import inspect
from abc import abstractmethod
from collections.abc import Iterator, Mapping
from types import MappingProxyType
from typing import ClassVar, Generic, Self, TypeVar, cast

from agent_comms.nominal.declared_family import (
DeclaredFamily,
FamilyMeta,
declared_words,
)
from agent_comms.planning.command import Command
from metaclass_registry.key_declarations import InputMode, KeyDeclaration, KeyDeclarationType

from toad.client.application import ClientApplication
from toad.session_navigation import ChannelsReveal


Context = TypeVar("Context")


class KeyFamilyMeta(FamilyMeta, KeyDeclarationType):
"""A named command family whose classes declare native key overlap."""


class DeclaredAction(KeyDeclaration[Context], Command, DeclaredFamily, Generic[Context],
metaclass=KeyFamilyMeta, affix="Action"):
"""Only a client's boundary decodes an external action name. A member declares its
keys, and its title and docstring are the only text any view shows for it."""

keys: ClassVar[Mapping[type[InputMode], tuple[str, ...]]] = MappingProxyType({})
show: ClassVar[bool] = False
priority: ClassVar[bool] = False
key_display: ClassVar[str | None] = None
binding_prefix: ClassVar[str] = ""

@classmethod
def default_title(cls) -> str:
"""The class's own derived name, never its declared_name: views show what a member does."""
return declared_words(cls.__name__.removesuffix(cls._family_affix)).replace("_", " ").capitalize()

@classmethod
def declarations(cls) -> Iterator[type[Self]]:
"""The native registry filters by this class, so each member is one of its own."""
return cast("Iterator[type[Self]]", super().declarations())

@classmethod
def summary(cls) -> str:
"""The nearest docstring a member declares; the family roots document code, not keys."""
root = cls.family_root
return next((inspect.cleandoc(base.__doc__) for base in cls.__mro__
if issubclass(base, root) and base is not root and base.__doc__), "")

@classmethod
def binding_name(cls) -> str:
return cls.binding_prefix + cls.declared_name

@classmethod
def command_for_key(cls, mode: type[InputMode], key: str) -> Self:
return cls()

@classmethod
def refine_binding[Binding](cls, binding: Binding) -> Binding:
"""A family whose bindings carry more of its declaration completes them here."""
return binding

@classmethod
def exclusive_claims[Binding](cls, bindings: tuple[Binding, ...]) -> tuple[Binding, ...]:
"""The keys this member claims against every other scope's: none unless it says so."""
return ()

def __call__(self, context: Context) -> object:
return self.apply(context)

@classmethod
def parse(cls, parameters: tuple[object, ...]):
if parameters:
raise ValueError(f"{cls.declared_name} takes no parameters")
return cls()

@classmethod
def require_unwritten(cls, name: str, writers: tuple[type, ...]) -> None:
"""A generated dispatcher may not replace an action a class wrote: a member whose apply
calls that action would then call itself."""
if writers:
raise TypeError(f"{cls.__qualname__} would replace {writers[0].__qualname__}.{name}")

@classmethod
def offered(cls, context: Context) -> Iterator[Self]:
"""What the menu and the palette offer for this member: itself, where it is available."""
command = cls()
if command.available(context):
yield command

def label(self, context: Context) -> str:
"""A state-dependent title overrides this; every other member shows its title."""
return self.title

def available(self, context: Context) -> bool | None:
return True

def engine_boundary(self, editor: object) -> bool:
"""An external engine offers this action at its key; only an EngineKey member is asked."""
return False

def key_available(self, context: Context) -> bool | None:
"""Keyboard scope may be narrower than menu/palette command availability."""
return self.available(context)

@abstractmethod
def apply(self, context: Context) -> object: ...


class System:
"""Only its key reaches the action: no menu, palette or key panel shows it."""

system: ClassVar[bool] = True

@classmethod
def offered(cls, context: object) -> Iterator[Self]:
return iter(())


class YieldingKey:
"""An application key that any binding closer to the focus replaces: it answers only
where nothing local claims the key, so the claim is no conflict."""

priority = False

@classmethod
def exclusive_claims[Binding](cls, bindings: tuple[Binding, ...]) -> tuple[Binding, ...]:
return ()


class ReplacesFrameworkAction:
"""A member declared to stand in for one of the toolkit's own actions (Screen.action_dismiss,
App.action_quit): replacing that written action is its purpose."""

@classmethod
def require_unwritten(cls, name: str, writers: tuple[type, ...]) -> None:
pass


class ApplicationAction(DeclaredAction[ClientApplication], affix="Action"):
"""Declared application shortcuts resolve before an editor takes the key."""

binding_prefix = "app."
priority = True

@classmethod
def exclusive_claims[Binding](cls, bindings: tuple[Binding, ...]) -> tuple[Binding, ...]:
return bindings

@classmethod
def menu(cls, app: ClientApplication) -> tuple[tuple[ApplicationAction, str], ...]:
"""Every offered member under its label, in declaration order."""
return tuple((command, command.label(app))
for member in cls.members_with(cls) for command in member.offered(app))


# Declaration order is the order of the menu and the palette.
class NewThreadAction(ApplicationAction):
"""Start a thread in the selected project."""

async def apply(self, app: ClientApplication) -> None:
navigation = app.session_navigation
navigation.open_thread_form(navigation.selected_project())


class ChannelsAction(ApplicationAction):
"""Reveal channels and focus the selected session."""

keys = {InputMode: ("ctrl+s",)}
show = True

async def apply(self, app: ClientApplication) -> None:
app.run_operation(ChannelsReveal, app.session_navigation.reveal)


class DirectMessagesAction(ApplicationAction):
"""Open the most recently selected direct conversation."""

keys = {InputMode: ("ctrl+shift+d",)}

async def apply(self, app: ClientApplication) -> None:
app.session_navigation.direct_messages()


class QuitAction(ReplacesFrameworkAction, ApplicationAction):
"""Save preferences and quit the application."""

keys = {InputMode: ("ctrl+q",)}

async def apply(self, app: ClientApplication) -> None:
app.application.quit()
2 changes: 1 addition & 1 deletion src/toad/conversation_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def available(self, conversation):
return True if conversation.agent_binding.cancel_allowed(conversation.turns.owner) else None

async def apply(self, conversation):
conversation.cancel_turn(conversation.app.get_key_display(*self.active_bindings(conversation)))
conversation.cancel_turn(conversation.app.get_key_display(*conversation.active_declared_bindings(type(self))))


class PageFractionAction(ConversationAction):
Expand Down
7 changes: 4 additions & 3 deletions src/toad/keymap.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Stored overrides and views of the keyboard declarations."""
from __future__ import annotations

Expand All @@ -15,14 +15,15 @@
from objectstate import mark_ui_hidden_config
from textual.binding import KeymapClaim
from textual.dom import DOMNode
from textual.keys import KeyInvocation
from metaclass_registry.key_declarations import KeyInvocation
from textual.screen import ModalScreen

import toad
from toad.key_modes import KeyMode
from toad.menus import MenuCommand
from toad.setting_declarations import Effect, FamilyChoices
from toad.widget_actions import ApplicationAction
from toad.client.application_actions import ApplicationAction
from toad.widget_actions import DeclaredWidgetActions

if TYPE_CHECKING:
from formbridge.forms.declared_fields import DeclaredField
Expand Down Expand Up @@ -160,7 +161,7 @@
native_mode = mode.binding_mode()
application = tuple(KeymapClaim.from_bindings(
binding for declaration in actions
for binding in declaration.exclusive_bindings(native_mode)
for binding in DeclaredWidgetActions.exclusive_bindings(declaration, native_mode)
))
owned = [application]
for owner in contexts:
Expand Down
4 changes: 2 additions & 2 deletions src/toad/menus.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Block-menu declarations and their captured native operations."""

from __future__ import annotations
Expand All @@ -11,12 +11,12 @@
from textual._callback import invoke
from textual.binding import ModeBinding
from textual.document._editing import EditingMode
from textual.keys import KeyDeclarationType, KeyInvocation
from metaclass_registry.key_declarations import KeyDeclarationType, KeyInvocation
from textual.widget import Widget

from toad.client.line_blocks import LineLink
from toad.message_rows import MessageRow
from toad.widget_actions import KeyFamilyMeta
from toad.client.application_actions import KeyFamilyMeta


class MenuConversation:
Expand Down
4 changes: 4 additions & 0 deletions src/toad/session_navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ class DirectMessagesOpen(OperationKind):
"""Opens a direct-message conversation through the navigating view."""


class ChannelsReveal(OperationKind):
"""Shows the channels sidebar, opening the newest session first when none is selected."""


class NewThreadForm(OperationKind, ExclusiveKind):
"""Prepares and opens the new-thread form; a newer request supersedes one running."""

Expand Down
Loading
Loading