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
18 changes: 1 addition & 17 deletions src/toad/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import os
import signal
import sys
from enum import IntEnum
from functools import cached_property
from inspect import isabstract
from pathlib import Path
Expand All @@ -23,7 +22,6 @@
from rich.console import RenderableType
from textual import events, on
from textual.await_complete import AwaitComplete
from textual.css.scalar import Scalar, Unit
from textual.notifications import Notify
from textual.reactive import Required, var
from textual.signal import Signal
Expand All @@ -32,6 +30,7 @@
from textual.widgets._footer import KeyGroup
from textual.widgets.markdown import Markdown

from toad.screen_width import ScreenWidth
from toad.app_core import CorePrewarm
from toad.application_actions import ApplicationCommands
from toad.application_outcome import ApplicationOutcome, Ended, Succeeded
Expand Down Expand Up @@ -112,21 +111,6 @@ class ApplicationNotRunningError(RuntimeError):
"""The application has no event loop to accept cross-thread work."""


class ScreenWidth(IntEnum):
"""Native sizing modes; legacy breakpoint classes are derived from them."""

side_panel_width: Scalar | None

def __new__(cls, minimum_width: int, side_panel_width: Scalar | None):
mode = int.__new__(cls, minimum_width)
mode._value_ = minimum_width
mode.side_panel_width = side_panel_width
return mode

NARROW = (0, None)
WIDE = (100, Scalar(50, Unit.PERCENT, Unit.WIDTH))


class ToadApp(DeclaredWidgetActions, WorkspaceSessionShutdown, WorkspaceHost, ClientApplication, CorePrewarm, Transfers, HostsNeovim, actions=(ApplicationAction,), inherit_bindings=False):
"""The top level app."""

Expand Down
18 changes: 13 additions & 5 deletions src/toad/client/application_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,14 @@ def menu(cls, app: ClientApplication) -> tuple[tuple[ApplicationAction, str], ..
for command in member.offered(app))



class OpensWindow:
"""An application action whose `apply` opens a window over the app: Settings, the team
board, the keymap, a transfer, the bus switcher. Each frontend presents every such window
through its one presentation owner (Qt's `PresentedWindow`), so the windows a reader can
open are this family's members, read wherever all of them must be checked."""


# Declaration order is the order of the menu and the palette.
class NewSessionAction(ApplicationAction):
"""Start this launch's session: its attached agent's, or a native thread."""
Expand Down Expand Up @@ -300,7 +308,7 @@ async def apply(self, app: ClientApplication) -> None:
app.session_navigation.direct_messages()


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

title = "Switch bus (local or remote)"
Expand All @@ -311,7 +319,7 @@ async def apply(self, app: ClientApplication) -> None:
app.open_bus_switcher()


class SettingsAction(ApplicationAction):
class SettingsAction(OpensWindow, ApplicationAction):
"""Edit persistent application preferences."""

keys = {TextEntryMode: ("ctrl+comma",)}
Expand All @@ -321,7 +329,7 @@ async def apply(self, app: ClientApplication) -> None:
await app.edit_settings()


class TeamAction(ApplicationAction, declared_name="team"):
class TeamAction(OpensWindow, ApplicationAction, declared_name="team"):
"""Open the live team board, including teammates' orders and original evidence."""

keys = {TextEntryMode: ("f2",)}
Expand All @@ -331,7 +339,7 @@ async def apply(self, app: ClientApplication) -> None:
await app.open_team_board()


class KeymapAction(ApplicationAction):
class KeymapAction(OpensWindow, ApplicationAction):
"""Browse keyboard shortcuts and change their keys for each editing mode."""

keys = {TextEntryMode: ("f1",)}
Expand All @@ -341,7 +349,7 @@ async def apply(self, app: ClientApplication) -> None:
await app.open_keymap_browser()


class TransferMenuAction(ApplicationAction):
class TransferMenuAction(OpensWindow, ApplicationAction):
"""Export wire history or import a thread through Core."""

show = True
Expand Down
15 changes: 10 additions & 5 deletions src/toad/client/bus_submission.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from toad.client.prompt_composer import PromptComposer
from toad.client.submission import (
BusDestination,
ComposeAccess,
MessageDestination,
SubmissionOwner,
SubmissionStart,
Expand Down Expand Up @@ -79,8 +80,9 @@ def delivery_unknown(self, description: str, draft: SubmittedText) -> None:
self.show_send_failure(self.unknown_notice(description))

@abstractmethod
async def refresh_composer(self, read_only: bool) -> None:
"""Draw compose from the caller's Core answer."""
async def refresh_composer(self, access: ComposeAccess) -> None:
"""Draw compose from the caller's Core answer: held or open, and whether it offers
files."""

@abstractmethod
def draws_user_message(self, reference: MessageReference) -> bool: ...
Expand Down Expand Up @@ -313,11 +315,14 @@ async def deliver(self) -> DeliveryOutcome:
try:
await self.after.wait()
observed = await preparation.run_thread(access.observing, destination.root)
read_only = await preparation.run_thread(destination.conversation.read_only, observed.core)
await view.refresh_composer(read_only)
if read_only:
compose = await preparation.run_thread(destination.conversation.compose_access, observed.core)
await view.refresh_composer(compose)
if compose.read_only:
view.delivery_refused(MessageDestination.read_only_reason, draft)
return RefusedMessage()
if compose.refuses(draft):
view.delivery_refused(compose.files_refused_reason, draft)
return RefusedMessage()
route_current = await preparation.run_thread(lambda: access.current(destination.root))
if not route_current or not self.current:
raise HumanSendRefusedError(RelationViolationError("Message route changed; reopen this view"))
Expand Down
6 changes: 6 additions & 0 deletions src/toad/client/fragments.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
shows and its line blocks. Each frontend adds how it draws and measures those blocks."""

from abc import ABC, abstractmethod
from collections.abc import Iterable
from dataclasses import dataclass, field, replace
from functools import cached_property
from typing import ClassVar
Expand Down Expand Up @@ -299,6 +300,11 @@ def source_identity(self) -> EventSourceKey | ToolCallId:
def key(self) -> FragmentKey:
return FragmentKey(self.source_identity, self.part_position.index)

def message_head(self, fragments: Iterable["HistoryFragment"]) -> "HistoryFragment":
"""The first part of this fragment's message among ``fragments`` in order: where a
tap on any of its parts brings the reader (both frontends' clicked-head reveal)."""
return next((part for part in fragments if part.source_identity == self.source_identity), self)

@property
def pinned_dividers(self) -> tuple[Divider, ...]:
"""The header a top row in this fragment pins, and an arrival burst stacks: none for a
Expand Down
5 changes: 3 additions & 2 deletions src/toad/client/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from toad.client.source_resumption import ResumesSource
from toad.client.submission import (
BusDestination,
ComposeAccess,
SubmissionOwner,
SubmissionStart,
SubmittedText,
Expand Down Expand Up @@ -617,8 +618,8 @@ async def mark_page(self, page: MessagePage) -> None:
await asyncio.to_thread(
self.loader.core.call, CommsMarkPageReadTool(page=page, worktree=self.loader.project))

async def read_only(self) -> bool:
return await self.runtime.run_thread(self.loader.conversation.read_only, self.loader.core)
async def compose_access(self) -> ComposeAccess:
return await self.runtime.run_thread(self.loader.conversation.compose_access, self.loader.core)

async def update_mentions(self, view: WireView) -> None:
await self.loader.conversation.update_mentions(view, self.loader)
Expand Down
19 changes: 18 additions & 1 deletion src/toad/client/message_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from toad.client.input_decision import InputAccepted, InputDecision
from toad.client.message_file_links import file_size
from toad.client.prompt_composer import PromptComposer
from toad.client.submission import ComposeAccess


class FilePicker(DeclaredChoice, affix="FilePicker"):
Expand Down Expand Up @@ -88,6 +89,9 @@ class MessagePromptComposer(PromptComposer):
sends with the text."""

attached_files: tuple[FileUpload, ...] = ()
takes_files: bool = True
"""Whether this composer's bus takes files, as its Core last answered (`ComposeAccess`);
open until it answers, as every bus that takes files is."""

@property
def input_decision(self) -> InputDecision:
Expand All @@ -98,8 +102,21 @@ def input_decision(self) -> InputDecision:
def prompt_symbol(self, text: str, shell_mode: bool) -> str:
return self.settings.ui.input.agent_symbol

def offer_files(self, takes_files: bool) -> None:
if self.takes_files != takes_files:
self.takes_files = takes_files
self.show_files_offered()

@abstractmethod
def show_files_offered(self) -> None:
"""Offer Attach only while `takes_files`."""

def attach_file(self) -> None:
"""The attach action: the picker this composer's settings name opens."""
"""The attach action: the picker this composer's settings name opens, on a bus that
takes files. A key pressed before the bus answered meets the reason instead."""
if not self.takes_files:
self.show_failure(ComposeAccess.files_refused_reason)
return
self.settings.ui.input.file_picker.open(self)

@abstractmethod
Expand Down
7 changes: 4 additions & 3 deletions src/toad/client/prepared_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from toad.client.history_reads import NothingToRead, PaintedRead
from toad.client.history_state import DEFERRED_WORK, SourceWork
from toad.client.input_decision import TranscriptNotReady
from toad.client.submission import SubmissionOwner, SubmissionStart, SubmittedText
from toad.client.submission import ComposeAccess, SubmissionOwner, SubmissionStart, SubmittedText
from toad.commit_claims import RETAINED_SOURCE_CLAIM, CommitClaim, RetainedBlockClaim
from toad.status_thread import NoStatusThread
from toad.work_preparation import (
Expand Down Expand Up @@ -655,8 +655,9 @@ def seen_page(self, history, seen: tuple[HistoryFragment, ...]):
async def mark_page(self, page: MessagePage) -> None:
raise ValueError("This transcript has no saved-source reader")

async def read_only(self) -> bool:
return True
async def compose_access(self) -> ComposeAccess:
"""A source not yet ready holds compose, and takes nothing."""
return ComposeAccess(read_only=True, takes_files=False)

async def update_mentions(self, view) -> None:
return
Expand Down
4 changes: 4 additions & 0 deletions src/toad/client/prompt_composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ def prompt_symbol(self, text: str, shell_mode: bool) -> str:
return symbols.shell_symbol
return symbols.multiline_symbol if "\n" in text or "```" in text else symbols.agent_symbol

def offer_files(self, takes_files: bool) -> None:
"""Whether this composer's bus takes files. A prompt to an agent attaches none, so it
offers none either way; a message composer offers Attach while its bus takes them."""

@abstractmethod
def show_failure(self, text: str) -> None:
"""Say, under the input, why something typed or attached did not go."""
Expand Down
29 changes: 29 additions & 0 deletions src/toad/client/submission.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from agent_comms.messaging.message_files import FileUpload
from agent_comms.messaging.message_reference import MessageReference
from agent_comms.transport.request import CoreAccess
from agent_comms.transport.tools.sidebar import CommsMessageFilesTool

from toad.client.input_decision import InputDecision, InputRefused

Expand All @@ -35,12 +36,40 @@ def text(self) -> str:
return self.source_text.strip()


@dataclass(frozen=True)
class ComposeAccess:
"""What compose may do in one conversation, as its Core answered: whether it is held
(a read-only saved view), and whether its messages may carry files. A bus older than
message files takes none: files and the read that lists them shipped together, so a
Core that does not serve that read takes no upload either."""

read_only: bool
takes_files: bool

files_refused_reason: ClassVar[str] = "This bus takes no files (its agent-comms predates them)"
"""Why a message carrying files is not sent here."""

@property
def block_reason(self) -> str:
"""Why compose is held here; empty while it is open."""
return MessageDestination.read_only_reason if self.read_only else ""

def refuses(self, draft: SubmittedText) -> bool:
"""A draft carrying files to a bus that takes none is refused before it is sent."""
return bool(draft.files) and not self.takes_files


class MessageDestination(ABC):
"""What a bus send asks of the conversation it writes to; every conversation kind is one."""

read_only_reason: ClassVar[str] = "Read-only saved view"
"""Why compose is held when read_only answers True."""

def compose_access(self, core: CoreAccess) -> ComposeAccess:
"""What compose may do here, from this destination's Core; reads Core, so off the UI
thread."""
return ComposeAccess(self.read_only(core), core.serves(CommsMessageFilesTool))

@abstractmethod
def send_target(self) -> NamedTarget: ...

Expand Down
7 changes: 4 additions & 3 deletions src/toad/delivery_failure_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from toad.app_node import ToadNode
from toad.client.bus_submission import ConversationSubmission, SubmissionView
from toad.client.prompt_composer import ComposerStatus
from toad.client.submission import MessageDestination
from toad.client.submission import ComposeAccess
from toad.widgets.flash import Flash
from toad.widgets.prompt import Prompt
from toad.worker_group import InputHistoryRecord
Expand All @@ -43,11 +43,12 @@ def draws_user_message(self, reference: MessageReference) -> bool: ...
def compute_status(self) -> str | Content | RichText:
return self.composed_status()

async def refresh_composer(self, read_only: bool) -> None:
async def refresh_composer(self, access: ComposeAccess) -> None:
"""Draw compose from the caller's Core answer."""
if not self.is_attached:
return
reason = MessageDestination.read_only_reason if read_only else ""
self.prompt.offer_files(access.takes_files)
reason = access.block_reason
area = self.prompt.prompt_text_area
area.disabled = bool(reason)
area.tooltip = reason or None
Expand Down
30 changes: 29 additions & 1 deletion src/toad/forms/presentation.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""Native form geometry and paint, supplied directly to Textual's owners."""
from __future__ import annotations

from abc import abstractmethod

from textual.color import Color, TRANSPARENT
from textual.css._style_properties import Edges
from textual.css.scalar import Scalar
from textual.css.scalar import Scalar, Unit
from textual.geometry import Spacing
from textual.layouts.horizontal import HorizontalLayout
from textual.screen import ModalScreen
Expand All @@ -16,6 +18,7 @@
from textual.widgets import Input
from toad.app_node import FollowsTheme
from toad.widget_view import CenteredView
from toad.window_presentation import BesideApp, FillsApp, WindowPresentation
from toad.widgets.checkbox import Checkbox
from ui_theme.scheme import BackgroundColour, ErrorColour, ForegroundColour, PrimaryColour, SurfaceColour

Expand Down Expand Up @@ -91,3 +94,28 @@ def paint_background(self) -> Color:
def theme_changed(self) -> None:
# A theme changes the entire visible modal, not each offscreen field.
self.refresh()


class PanelPresentation(WindowPresentation):
"""How Textual lays a panel over the app for one screen width class: its width."""

@classmethod
@abstractmethod
def panel_width(cls) -> Scalar | None:
"""The panel's width, or None to take the screen's whole width."""


class FilledPanel(PanelPresentation, FillsApp):
"""A narrow terminal's panel: the whole screen, as Qt's window fills a phone's app window."""

@classmethod
def panel_width(cls) -> Scalar | None:
return None


class SidePanel(PanelPresentation, BesideApp):
"""A wide terminal's panel: half the screen, its right side, the conversation still in view."""

@classmethod
def panel_width(cls) -> Scalar | None:
return Scalar(50, Unit.PERCENT, Unit.WIDTH)
Loading
Loading