346 lines
13 KiB
Python
346 lines
13 KiB
Python
"""Widgets for the AiRouter TUI."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from rich.text import Text
|
|
from textual.app import ComposeResult
|
|
from textual.containers import Horizontal, Vertical
|
|
from textual.widgets import ListItem, ListView, ProgressBar, RichLog, Static, TabPane
|
|
|
|
from ..session import Session
|
|
from ..utils import format_cost, format_duration, format_tokens, truncate
|
|
from ..worker import Worker
|
|
from .anim import ActivityWave, spinner_frame
|
|
|
|
STATUS_ICON = {
|
|
"pending": ("[ ]", "#6f747e"),
|
|
"in_progress": ("[~]", "#f0a35e"),
|
|
"done": ("[x]", "#7fbf9f"),
|
|
"blocked": ("[!]", "#e06c75"),
|
|
"skipped": ("[-]", "#5f6470"),
|
|
}
|
|
WORKER_STATUS_STYLE = {
|
|
"pending": "yellow",
|
|
"running": "cyan",
|
|
"done": "green",
|
|
"failed": "red",
|
|
"cancelled": "yellow",
|
|
"interrupted": "yellow",
|
|
}
|
|
def status_icon(status: str, frame: str = "⣾") -> tuple[str, str]:
|
|
if status == "in_progress":
|
|
return frame, "#f0a35e"
|
|
return STATUS_ICON.get(status, ("[ ]", "#6f747e"))
|
|
|
|
|
|
class ConversationPane(TabPane):
|
|
"""A chat tab with its own scrollable transcript and live preview."""
|
|
|
|
def __init__(
|
|
self,
|
|
title: str,
|
|
*,
|
|
pane_id: str,
|
|
log_id: str,
|
|
live_id: str,
|
|
disabled: bool = False,
|
|
) -> None:
|
|
super().__init__(title, id=pane_id, disabled=disabled)
|
|
self.log_id = log_id
|
|
self.live_id = live_id
|
|
|
|
def compose(self) -> ComposeResult:
|
|
yield RichLog(
|
|
id=self.log_id,
|
|
min_width=1,
|
|
max_lines=10000,
|
|
wrap=True,
|
|
markup=False,
|
|
auto_scroll=True,
|
|
)
|
|
yield Static("", id=self.live_id)
|
|
|
|
|
|
class ClickListView(ListView):
|
|
"""ListView that activates a row on the first mouse click (focus or not)."""
|
|
|
|
def on_mouse_down(self, event: object) -> None:
|
|
try:
|
|
widget, _ = self.app.get_widget_at(
|
|
int(getattr(event, "screen_x", 0)), int(getattr(event, "screen_y", 0))
|
|
)
|
|
except Exception:
|
|
return
|
|
node = widget
|
|
while node is not None and node is not self:
|
|
if isinstance(node, WorkerRow):
|
|
asyncio.create_task(self.app.open_worker(node.worker_id)) # type: ignore[attr-defined]
|
|
getattr(event, "stop", lambda: None)()
|
|
return
|
|
if isinstance(node, TodoRow):
|
|
self.app.open_task(node.task_data) # type: ignore[attr-defined]
|
|
getattr(event, "stop", lambda: None)()
|
|
return
|
|
node = node.parent
|
|
|
|
|
|
class TodoRow(ListItem):
|
|
def __init__(self, task: dict, frame: str = "⣾") -> None:
|
|
super().__init__()
|
|
self.task_data = task
|
|
self.frame = frame
|
|
|
|
def compose(self) -> ComposeResult:
|
|
yield Static(self._render_text(), classes="todo-body")
|
|
|
|
def _render_text(self) -> Text:
|
|
task = self.task_data
|
|
icon, style = status_icon(str(task.get("status", "pending")), self.frame)
|
|
text = Text()
|
|
text.append(f" {icon} ", style=f"bold {style}")
|
|
title_style = "bold #e6e8ed" if task.get("status") == "in_progress" else "#d7dae0"
|
|
if task.get("status") in {"done", "skipped"}:
|
|
title_style = "#7f8490"
|
|
text.append(str(task.get("title", "")), style=title_style)
|
|
meta: list[str] = []
|
|
if task.get("worker_id"):
|
|
meta.append(str(task["worker_id"]))
|
|
if meta:
|
|
text.append(" " + " · ".join(meta), style="dim")
|
|
for sub in task.get("subtasks") or []:
|
|
sub_icon, sub_style = status_icon(str(sub.get("status", "pending")), self.frame)
|
|
text.append("\n ")
|
|
text.append(sub_icon + " ", style=sub_style)
|
|
sub_style_text = "#6f747e" if sub.get("status") in {"done", "skipped"} else "#9a9fa9"
|
|
text.append(str(sub.get("title", "")), style=sub_style_text)
|
|
return text
|
|
|
|
def render_task(self) -> None:
|
|
try:
|
|
self.query_one(Static).update(self._render_text())
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
class WorkerRow(ListItem):
|
|
def __init__(self, worker: Worker) -> None:
|
|
super().__init__(id=f"worker-{worker.id}")
|
|
self.worker_id = worker.id
|
|
self.worker_obj = worker
|
|
|
|
def compose(self) -> ComposeResult:
|
|
yield Static(self._render_text(self.worker_obj), classes="worker-body")
|
|
|
|
def _render_text(self, worker: Worker, tick: int = 0) -> Text:
|
|
frame = spinner_frame(tick)
|
|
style = WORKER_STATUS_STYLE.get(worker.status, "white")
|
|
icon = "[x]" if worker.status == "done" else (
|
|
"[!]" if worker.status == "failed" else (
|
|
"[-]" if worker.status in {"cancelled", "interrupted"} else frame
|
|
)
|
|
)
|
|
text = Text()
|
|
text.append(f" {icon} ", style=f"bold {style}")
|
|
text.append(worker.id, style="bold magenta")
|
|
text.append(f" {worker.name}", style="white")
|
|
text.append(f" {worker.status}", style=style)
|
|
if worker.intelligence:
|
|
text.append(f" {worker.intelligence}", style="magenta")
|
|
if worker.duration is not None:
|
|
text.append(f" {format_duration(worker.duration)}", style="dim")
|
|
text.append("\n ", style="dim")
|
|
text.append(f"{worker.role.name} · {worker.model}", style="dim")
|
|
if worker.last_action:
|
|
text.append(f" · {truncate(worker.last_action, 54)}", style="dim")
|
|
if worker.files_changed:
|
|
text.append(f" · файлов: {len(worker.files_changed)}", style="dim")
|
|
return text
|
|
|
|
def render_worker(self, worker: Worker, tick: int = 0) -> None:
|
|
try:
|
|
self.query_one(Static).update(self._render_text(worker, tick))
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
class PlanPanel(Vertical):
|
|
def compose(self) -> ComposeResult:
|
|
with Horizontal(classes="panel-head"):
|
|
yield Static("ПЛАН", classes="panel-title")
|
|
yield Static("0/0", id="plan-count", classes="panel-meta")
|
|
yield ProgressBar(total=1, show_eta=False, id="plan-progress")
|
|
yield Static(
|
|
"План появится, когда главная модель разобьёт задачу.",
|
|
id="plan-empty",
|
|
classes="empty-state",
|
|
)
|
|
yield ClickListView(id="plan-list")
|
|
|
|
def on_mount(self) -> None:
|
|
self.query_one("#plan-list", ListView).display = False
|
|
self._rows: dict[str, TodoRow] = {}
|
|
|
|
async def update_plan(self, tasks: list[dict], session_id: str | None = None) -> None:
|
|
if session_id and getattr(self, "_session_id", None) != session_id:
|
|
self._session_id = session_id
|
|
self._signature = None
|
|
self._rows = {}
|
|
signature = json.dumps(tasks, ensure_ascii=False, sort_keys=True)
|
|
if getattr(self, "_signature", None) == signature and getattr(self, "_rows", None):
|
|
self._tasks = tasks
|
|
return
|
|
self._signature = signature
|
|
self._tasks = tasks
|
|
list_view = self.query_one("#plan-list", ListView)
|
|
empty = self.query_one("#plan-empty", Static)
|
|
count = self.query_one("#plan-count", Static)
|
|
progress = self.query_one("#plan-progress", ProgressBar)
|
|
done = sum(1 for task in tasks if task.get("status") == "done")
|
|
total = len(tasks)
|
|
subtasks = [sub for task in tasks for sub in task.get("subtasks") or []]
|
|
done_sub = sum(1 for sub in subtasks if sub.get("status") == "done")
|
|
count.update(Text(f"{done}/{total} · {done_sub}/{len(subtasks)}"))
|
|
progress.display = bool(tasks)
|
|
progress.update(total=total or 1, progress=done)
|
|
if not tasks:
|
|
empty.display = True
|
|
list_view.display = False
|
|
await list_view.clear()
|
|
self._rows = {}
|
|
return
|
|
empty.display = False
|
|
list_view.display = True
|
|
await list_view.clear()
|
|
rows = [TodoRow(task) for task in tasks]
|
|
self._rows = {task.get("id", str(i)): row for i, (task, row) in enumerate(zip(tasks, rows))}
|
|
await list_view.extend(rows)
|
|
|
|
def tick(self, tick: int) -> None:
|
|
frame = spinner_frame(tick)
|
|
for task, row in zip(getattr(self, "_tasks", []), self._rows.values()):
|
|
if task.get("status") == "in_progress" or any(
|
|
sub.get("status") == "in_progress" for sub in task.get("subtasks") or []
|
|
):
|
|
row.frame = frame
|
|
row.render_task()
|
|
|
|
|
|
class WorkersPanel(Vertical):
|
|
def compose(self) -> ComposeResult:
|
|
with Horizontal(classes="panel-head"):
|
|
yield Static("ВОРКЕРЫ", classes="panel-title")
|
|
yield ActivityWave(id="workers-activity", classes="panel-meta")
|
|
yield Static("0", id="workers-count", classes="panel-meta")
|
|
yield Static("Воркеров пока нет.", id="workers-empty", classes="empty-state")
|
|
yield ClickListView(id="workers-list")
|
|
|
|
def on_mount(self) -> None:
|
|
self.query_one("#workers-list", ListView).display = False
|
|
self._rows: dict[str, WorkerRow] = {}
|
|
|
|
async def sync(self, session: Session) -> None:
|
|
list_view = self.query_one("#workers-list", ListView)
|
|
empty = self.query_one("#workers-empty", Static)
|
|
count = self.query_one("#workers-count", Static)
|
|
if getattr(self, "_session_id", None) != session.id:
|
|
self._session_id = session.id
|
|
self._rows = {}
|
|
await list_view.clear()
|
|
count.update(Text(str(len(session.workers))))
|
|
if not session.workers:
|
|
empty.display = True
|
|
list_view.display = False
|
|
await list_view.clear()
|
|
self._rows = {}
|
|
return
|
|
empty.display = False
|
|
list_view.display = True
|
|
new_rows = [
|
|
WorkerRow(worker)
|
|
for worker_id, worker in session.workers.items()
|
|
if worker_id not in self._rows
|
|
]
|
|
if new_rows:
|
|
await list_view.extend(new_rows)
|
|
for row in new_rows:
|
|
self._rows[row.worker_id] = row
|
|
for row in self._rows.values():
|
|
if row.worker_id in session.workers and row.is_mounted:
|
|
row.render_worker(session.workers[row.worker_id])
|
|
|
|
def tick(self, session: Session, tick: int) -> None:
|
|
try:
|
|
self.query_one("#workers-activity", ActivityWave).set_active(
|
|
bool(session.running_workers()),
|
|
reduced=not session.config.ui.animations,
|
|
)
|
|
except Exception:
|
|
pass
|
|
for worker_id, row in self._rows.items():
|
|
worker = session.workers.get(worker_id)
|
|
if worker:
|
|
row.render_worker(worker, tick)
|
|
|
|
|
|
class ContextPanel(Vertical):
|
|
def compose(self) -> ComposeResult:
|
|
with Horizontal(classes="panel-head"):
|
|
yield Static("КОНТЕКСТ", classes="panel-title")
|
|
yield Static("0%", id="context-percent", classes="panel-meta")
|
|
yield ProgressBar(total=1000, show_eta=False, id="context-progress")
|
|
yield Static("0 tokens", id="context-label", classes="context-label")
|
|
|
|
def update_context(self, tokens: int, limit: int) -> None:
|
|
limit = max(1, limit)
|
|
percent = min(100.0, tokens * 100.0 / limit)
|
|
progress = self.query_one("#context-progress", ProgressBar)
|
|
progress.update(total=1000, progress=percent * 10)
|
|
self.query_one("#context-percent", Static).update(
|
|
Text(f"{percent:.0f}% used")
|
|
)
|
|
self.query_one("#context-label", Static).update(
|
|
Text(f"{format_tokens(tokens)} / {format_tokens(limit)} tokens", style="dim")
|
|
)
|
|
|
|
|
|
class StatsLine(Static):
|
|
def update_stats(self, session: Session | None, limit: int = 128_000) -> None:
|
|
if not session:
|
|
self.update(Text(" загрузка…", style="#6f747e"))
|
|
return
|
|
stats = session.stats()
|
|
main = stats["main_usage"]
|
|
cwd = str(session.cwd)
|
|
home = str(Path.home())
|
|
if cwd == home:
|
|
cwd = "~"
|
|
elif cwd.startswith(home + "/"):
|
|
cwd = "~" + cwd[len(home):]
|
|
done = sum(1 for task in session.todos if task.get("status") == "done")
|
|
percent = min(100, int(stats["context_tokens_estimate"] * 100 / max(1, limit)))
|
|
text = Text()
|
|
compact = self.size.width < 100
|
|
if not compact:
|
|
text.append(f" {cwd}", style="#8b909b")
|
|
text.append(" · ", style="#3a3f49")
|
|
else:
|
|
text.append(" ")
|
|
text.append(session.config.orchestrator_model, style="#f0a35e")
|
|
text.append(" · ", style="#3a3f49")
|
|
text.append(
|
|
f"{format_tokens(stats['context_tokens_estimate'])} tokens ({percent}%)",
|
|
style="#7f8490",
|
|
)
|
|
text.append(" · ", style="#3a3f49")
|
|
text.append(f"план {done}/{len(session.todos)}", style="#7f8490")
|
|
text.append(" · ", style="#3a3f49")
|
|
if not compact:
|
|
text.append(f"{format_cost(main['cost'])}", style="#7f8490")
|
|
text.append(" · ", style="#3a3f49")
|
|
text.append("ctrl+s · ctrl+q", style="#4f545e")
|
|
self.update(text)
|