Skip to content

T3Tui

Base classes

Name Children Inherits
App
textual.app
The base class for Textual Applications.

â‹” Inheritance diagram

graph TD
  2303220823["app.T3Tui"]
  3799205450["app.App"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3946681048["dom.DOMNode"]
  53685856["message_pump.MessagePump"]
  3799205450 --> 2303220823
  3481597255 --> 3799205450
  2751680898 --> 3481597255
  3946681048 --> 3799205450
  53685856 --> 3946681048
  2751680898 --> 53685856

🛈 DocStrings

Bases: App[None]

Telegram-like 2-pane TUI for a T3 Code environment.

Source code in src/acptui/t3/app.py
class T3Tui(App[None]):
    """Telegram-like 2-pane TUI for a T3 Code environment."""

    TITLE = "T3 Code"
    CSS = """
    #main-split {
        height: 1fr;
        width: 1fr;
    }
    """

    BINDINGS: ClassVar[list[Binding | tuple[str, str] | tuple[str, str, str]]] = [
        Binding("ctrl+b", "toggle_sidebar", "Sidebar"),
        Binding("slash", "focus_filter", "Filter", show=True),
        Binding("ctrl+n", "new_thread", "New thread"),
        Binding("escape", "stop_or_unfocus", "Stop / Back", show=False),
        Binding("ctrl+q", "quit", "Quit"),
    ]

    def __init__(self, backend: T3Backend, *, env_label: str = "local") -> None:
        super().__init__()
        self.backend = backend
        self._env_label = env_label
        self.workspace = WorkspaceState()
        self.timeline: ThreadTimelineState | None = None

    def compose(self) -> ComposeResult:
        """Build the 2-pane Telegram layout and footer."""
        with Horizontal(id="main-split"):
            yield ThreadSidebar(env_label=self._env_label)
            yield ThreadChatPane()
        yield Footer()

    def on_mount(self) -> None:
        """Start the live workspace shell stream."""
        self._run_shell_stream()

    @work(exclusive=True, group="shell")
    async def _run_shell_stream(self) -> None:
        sidebar = self.query_one(ThreadSidebar)
        after: int | None = None
        while True:
            resubscribe = False
            try:
                async for item in self.backend.subscribe_shell(after_sequence=after):
                    change = self.workspace.apply_shell(item)
                    if change.needs_resubscribe:
                        after = None
                        resubscribe = True
                        break
                    if change.changed:
                        sidebar.refresh_from(self.workspace)
                        self._sync_active_header()
                        if self.workspace.active_thread_id is None:
                            threads = self.workspace.sorted_threads()
                            if threads:
                                self._open_thread(threads[0].id)
                    if change.attention_thread_id and change.attention_reason:
                        self._notify_background(change.attention_thread_id, change.attention_reason)
                if not resubscribe:
                    return
            except asyncio.CancelledError:
                raise
            except Exception as err:  # noqa: BLE001
                self.notify(f"Shell stream disconnected: {err}", severity="error")
                return

    def _notify_background(self, thread_id: str, reason: str) -> None:
        thread = self.workspace.threads.get(thread_id)
        title = thread.title if thread else thread_id
        self.bell()
        if reason == "waiting":
            self.notify(f"Approval needed: {title}", severity="warning")
        elif reason == "failed":
            self.notify(f"Failed: {title}", severity="error")
        else:
            self.notify(f"Done: {title}")

    def _sync_active_header(self) -> None:
        pane = self.query_one(ThreadChatPane)
        tid = self.workspace.active_thread_id
        thread = self.workspace.threads.get(tid) if tid else None
        proj = self.workspace.project_title(thread.project_id) if thread else ""
        running = (self.timeline.is_running if self.timeline else False) or (
            thread_is_running(thread) if thread else False
        )
        pane.set_header(thread, project_title=proj, running=running)

    def _open_thread(self, thread_id: str) -> None:
        if self.workspace.active_thread_id == thread_id and self.timeline is not None:
            return
        self.workspace.select_thread(thread_id)
        self.query_one(ThreadSidebar).refresh_from(self.workspace)
        self.timeline = ThreadTimelineState(thread_id=thread_id)
        self._sync_active_header()
        self._run_thread_stream(thread_id)
        self._mark_visited(thread_id)

    @work(exclusive=True, group="visit")
    async def _mark_visited(self, thread_id: str) -> None:
        with suppress(Exception):
            await self.backend.visit_thread(thread_id)

    @work(exclusive=True, group="thread")
    async def _run_thread_stream(self, thread_id: str) -> None:
        pane = self.query_one(ThreadChatPane)
        timeline = self.timeline
        if timeline is None or timeline.thread_id != thread_id:
            return
        try:
            async for item in self.backend.subscribe_thread(thread_id):
                if self.workspace.active_thread_id != thread_id:
                    return
                changes = timeline.apply(item)
                for change in changes:
                    if change.kind == "reset":
                        await pane.reset_timeline(timeline)
                    elif change.kind in {"item_added", "item_updated"} and change.item_id:
                        turn_item = timeline.items.get(change.item_id)
                        if turn_item is not None:
                            await pane.upsert_item(turn_item)
                    elif change.kind == "status_changed":
                        self._sync_active_header()
                self._sync_active_header()
        except asyncio.CancelledError:
            raise
        except Exception as err:  # noqa: BLE001
            self.notify(f"Thread stream error: {err}", severity="error")

    def on_thread_sidebar_thread_selected(self, event: ThreadSidebar.ThreadSelected) -> None:
        """Switch the right pane to the selected thread."""
        self._open_thread(event.thread_id)
        self.query_one(ThreadChatPane).focus_composer()

    def on_filter_changed(self, event: FilterChanged) -> None:
        """Re-filter the sidebar list."""
        _ = event
        self.query_one(ThreadSidebar).refresh_from(self.workspace)

    def on_thread_sidebar_new_thread_requested(
        self, event: ThreadSidebar.NewThreadRequested
    ) -> None:
        """Open the new-thread dialog."""
        _ = event
        self.action_new_thread()

    def on_thread_chat_pane_send_requested(self, event: ThreadChatPane.SendRequested) -> None:
        """Dispatch the user's message to the active thread."""
        tid = self.workspace.active_thread_id
        if tid is None:
            self.notify("Select or create a thread first.", severity="warning")
            return
        self._send_user_message(tid, event.text)

    @work(group="send")
    async def _send_user_message(self, thread_id: str, text: str) -> None:
        try:
            await self.backend.send_message(thread_id, text)
        except Exception as err:  # noqa: BLE001
            self.notify(f"Send failed: {err}", severity="error")

    def on_thread_chat_pane_stop_requested(self, event: ThreadChatPane.StopRequested) -> None:
        """Stop the active thread's run."""
        _ = event
        tid = self.workspace.active_thread_id
        if tid is not None:
            self._send_stop(tid)

    @work(group="stop")
    async def _send_stop(self, thread_id: str) -> None:
        try:
            await self.backend.stop_thread(thread_id)
        except Exception as err:  # noqa: BLE001
            self.notify(f"Stop failed: {err}", severity="error")

    def on_approval_decision_made(self, event: ApprovalDecisionMade) -> None:
        """Answer an inline approval card."""
        self._send_approval(event.thread_id, event.request_id, event.decision)

    @work(group="approval")
    async def _send_approval(
        self, thread_id: str, request_id: str, decision: ApprovalDecision
    ) -> None:
        try:
            await self.backend.respond_to_request(thread_id, request_id, decision=decision)
        except Exception as err:  # noqa: BLE001
            self.notify(f"Approval failed: {err}", severity="error")

    def on_markdown_link_clicked(self, event: AgentMarkdown.LinkClicked) -> None:
        """Show clicked links safely without auto-executing non-web URLs."""
        if link_is_web(event.href):
            self.open_url(event.href)
        else:
            self.notify(f"Link: {event.href}")

    def action_toggle_sidebar(self) -> None:
        """Show or hide the left thread sidebar."""
        self.query_one(ThreadSidebar).toggle_class("-hidden")

    def action_focus_filter(self) -> None:
        """Focus the sidebar filter box (and ensure sidebar is visible)."""
        sidebar = self.query_one(ThreadSidebar)
        sidebar.remove_class("-hidden")
        sidebar.focus_filter()

    def action_new_thread(self) -> None:
        """Open the New Thread modal."""
        projects = list(self.workspace.projects.values())
        if not projects:
            self.notify("No projects loaded yet.", severity="warning")
            return
        self.push_screen(NewThreadDialog(projects), self._on_new_thread_result)

    def _on_new_thread_result(self, result: tuple[str, str] | None) -> None:
        if result is None:
            return
        project_id, title = result
        self._create_thread(project_id, title)

    @work(group="create")
    async def _create_thread(self, project_id: str, title: str) -> None:
        project = self.workspace.projects.get(project_id)
        model_selection = (
            project.default_model_selection
            if project and project.default_model_selection
            else {"instanceId": "default", "model": "default"}
        )
        try:
            thread_id, _ = await self.backend.create_thread(
                project_id, title, model_selection=model_selection
            )
            self._open_thread(thread_id)
            self.query_one(ThreadChatPane).focus_composer()
        except Exception as err:  # noqa: BLE001
            self.notify(f"Create thread failed: {err}", severity="error")

    def action_stop_or_unfocus(self) -> None:
        """Stop active run if running, otherwise focus the sidebar list."""
        tid = self.workspace.active_thread_id
        thread = self.workspace.threads.get(tid) if tid else None
        if tid and (
            (self.timeline and self.timeline.is_running) or (thread and thread_is_running(thread))
        ):
            self._send_stop(tid)
        else:
            self.query_one(ThreadSidebar).focus_list()

action_focus_filter

action_focus_filter() -> None

Focus the sidebar filter box (and ensure sidebar is visible).

Source code in src/acptui/t3/app.py
def action_focus_filter(self) -> None:
    """Focus the sidebar filter box (and ensure sidebar is visible)."""
    sidebar = self.query_one(ThreadSidebar)
    sidebar.remove_class("-hidden")
    sidebar.focus_filter()

action_new_thread

action_new_thread() -> None

Open the New Thread modal.

Source code in src/acptui/t3/app.py
def action_new_thread(self) -> None:
    """Open the New Thread modal."""
    projects = list(self.workspace.projects.values())
    if not projects:
        self.notify("No projects loaded yet.", severity="warning")
        return
    self.push_screen(NewThreadDialog(projects), self._on_new_thread_result)

action_stop_or_unfocus

action_stop_or_unfocus() -> None

Stop active run if running, otherwise focus the sidebar list.

Source code in src/acptui/t3/app.py
def action_stop_or_unfocus(self) -> None:
    """Stop active run if running, otherwise focus the sidebar list."""
    tid = self.workspace.active_thread_id
    thread = self.workspace.threads.get(tid) if tid else None
    if tid and (
        (self.timeline and self.timeline.is_running) or (thread and thread_is_running(thread))
    ):
        self._send_stop(tid)
    else:
        self.query_one(ThreadSidebar).focus_list()

action_toggle_sidebar

action_toggle_sidebar() -> None

Show or hide the left thread sidebar.

Source code in src/acptui/t3/app.py
def action_toggle_sidebar(self) -> None:
    """Show or hide the left thread sidebar."""
    self.query_one(ThreadSidebar).toggle_class("-hidden")

compose

compose() -> ComposeResult

Build the 2-pane Telegram layout and footer.

Source code in src/acptui/t3/app.py
def compose(self) -> ComposeResult:
    """Build the 2-pane Telegram layout and footer."""
    with Horizontal(id="main-split"):
        yield ThreadSidebar(env_label=self._env_label)
        yield ThreadChatPane()
    yield Footer()

on_approval_decision_made

on_approval_decision_made(event: ApprovalDecisionMade) -> None

Answer an inline approval card.

Source code in src/acptui/t3/app.py
def on_approval_decision_made(self, event: ApprovalDecisionMade) -> None:
    """Answer an inline approval card."""
    self._send_approval(event.thread_id, event.request_id, event.decision)

on_filter_changed

on_filter_changed(event: FilterChanged) -> None

Re-filter the sidebar list.

Source code in src/acptui/t3/app.py
def on_filter_changed(self, event: FilterChanged) -> None:
    """Re-filter the sidebar list."""
    _ = event
    self.query_one(ThreadSidebar).refresh_from(self.workspace)
on_markdown_link_clicked(event: LinkClicked) -> None

Show clicked links safely without auto-executing non-web URLs.

Source code in src/acptui/t3/app.py
def on_markdown_link_clicked(self, event: AgentMarkdown.LinkClicked) -> None:
    """Show clicked links safely without auto-executing non-web URLs."""
    if link_is_web(event.href):
        self.open_url(event.href)
    else:
        self.notify(f"Link: {event.href}")

on_mount

on_mount() -> None

Start the live workspace shell stream.

Source code in src/acptui/t3/app.py
def on_mount(self) -> None:
    """Start the live workspace shell stream."""
    self._run_shell_stream()

on_thread_chat_pane_send_requested

on_thread_chat_pane_send_requested(event: SendRequested) -> None

Dispatch the user's message to the active thread.

Source code in src/acptui/t3/app.py
def on_thread_chat_pane_send_requested(self, event: ThreadChatPane.SendRequested) -> None:
    """Dispatch the user's message to the active thread."""
    tid = self.workspace.active_thread_id
    if tid is None:
        self.notify("Select or create a thread first.", severity="warning")
        return
    self._send_user_message(tid, event.text)

on_thread_chat_pane_stop_requested

on_thread_chat_pane_stop_requested(event: StopRequested) -> None

Stop the active thread's run.

Source code in src/acptui/t3/app.py
def on_thread_chat_pane_stop_requested(self, event: ThreadChatPane.StopRequested) -> None:
    """Stop the active thread's run."""
    _ = event
    tid = self.workspace.active_thread_id
    if tid is not None:
        self._send_stop(tid)

on_thread_sidebar_new_thread_requested

on_thread_sidebar_new_thread_requested(event: NewThreadRequested) -> None

Open the new-thread dialog.

Source code in src/acptui/t3/app.py
def on_thread_sidebar_new_thread_requested(
    self, event: ThreadSidebar.NewThreadRequested
) -> None:
    """Open the new-thread dialog."""
    _ = event
    self.action_new_thread()

on_thread_sidebar_thread_selected

on_thread_sidebar_thread_selected(event: ThreadSelected) -> None

Switch the right pane to the selected thread.

Source code in src/acptui/t3/app.py
def on_thread_sidebar_thread_selected(self, event: ThreadSidebar.ThreadSelected) -> None:
    """Switch the right pane to the selected thread."""
    self._open_thread(event.thread_id)
    self.query_one(ThreadChatPane).focus_composer()

:fa-brands-github: Show source on GitHub