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()