Репозитории / AiRouter / airouter/tui/widgets.py

widgets.py

К файлам Скачать / raw
1"""Widgets for the AiRouter TUI."""
2
3from __future__ import annotations
4
5import json
6from pathlib import Path
7
8from rich.text import Text
9from textual.app import ComposeResult
10from textual.containers import Horizontal, Vertical
11from textual.widgets import ListItem, ListView, ProgressBar, Static
12
13from ..session import Session
14from ..utils import format_cost, format_duration, format_tokens, truncate
15from ..worker import Worker
16from .anim import spinner_frame
17
18STATUS_ICON = {
19 "pending": ("[ ]", "#6f747e"),
20 "in_progress": ("[~]", "#f0a35e"),
21 "done": ("[x]", "#7fbf9f"),
22 "blocked": ("[!]", "#e06c75"),
23 "skipped": ("[-]", "#5f6470"),
24}
25WORKER_STATUS_STYLE = {
26 "pending": "yellow",
27 "running": "cyan",
28 "done": "green",
29 "failed": "red",
30 "cancelled": "yellow",
31 "interrupted": "yellow",
32}
33def status_icon(status: str, frame: str = "⣾") -> tuple[str, str]:
34 if status == "in_progress":
35 return frame, "#f0a35e"
36 return STATUS_ICON.get(status, ("[ ]", "#6f747e"))
37
38
39class ClickListView(ListView):
40 """ListView that activates a row on the first mouse click (focus or not)."""
41
42 def on_mouse_down(self, event: object) -> None:
43 try:
44 widget, _ = self.app.get_widget_at(
45 int(getattr(event, "screen_x", 0)), int(getattr(event, "screen_y", 0))
46 )
47 except Exception:
48 return
49 node = widget
50 while node is not None and node is not self:
51 if isinstance(node, WorkerRow):
52 self.app.open_worker(node.worker_id) # type: ignore[attr-defined]
53 getattr(event, "stop", lambda: None)()
54 return
55 if isinstance(node, TodoRow):
56 self.app.open_task(node.task_data) # type: ignore[attr-defined]
57 getattr(event, "stop", lambda: None)()
58 return
59 node = node.parent
60
61
62class TodoRow(ListItem):
63 def __init__(self, task: dict, frame: str = "⣾") -> None:
64 super().__init__()
65 self.task_data = task
66 self.frame = frame
67
68 def compose(self) -> ComposeResult:
69 yield Static(self._render_text(), classes="todo-body")
70
71 def _render_text(self) -> Text:
72 task = self.task_data
73 icon, style = status_icon(str(task.get("status", "pending")), self.frame)
74 text = Text()
75 text.append(f" {icon} ", style=f"bold {style}")
76 title_style = "bold #e6e8ed" if task.get("status") == "in_progress" else "#d7dae0"
77 if task.get("status") in {"done", "skipped"}:
78 title_style = "#7f8490"
79 text.append(str(task.get("title", "")), style=title_style)
80 meta: list[str] = []
81 if task.get("worker_id"):
82 meta.append(str(task["worker_id"]))
83 if meta:
84 text.append(" " + " · ".join(meta), style="dim")
85 for sub in task.get("subtasks") or []:
86 sub_icon, sub_style = status_icon(str(sub.get("status", "pending")), self.frame)
87 text.append("\n ")
88 text.append(sub_icon + " ", style=sub_style)
89 sub_style_text = "#6f747e" if sub.get("status") in {"done", "skipped"} else "#9a9fa9"
90 text.append(str(sub.get("title", "")), style=sub_style_text)
91 return text
92
93 def render_task(self) -> None:
94 try:
95 self.query_one(Static).update(self._render_text())
96 except Exception:
97 pass
98
99
100class WorkerRow(ListItem):
101 def __init__(self, worker: Worker) -> None:
102 super().__init__(id=f"worker-{worker.id}")
103 self.worker_id = worker.id
104 self.worker_obj = worker
105
106 def compose(self) -> ComposeResult:
107 yield Static(self._render_text(self.worker_obj), classes="worker-body")
108
109 def _render_text(self, worker: Worker, tick: int = 0) -> Text:
110 frame = spinner_frame(tick)
111 style = WORKER_STATUS_STYLE.get(worker.status, "white")
112 icon = "[x]" if worker.status == "done" else (
113 "[!]" if worker.status == "failed" else (
114 "[-]" if worker.status in {"cancelled", "interrupted"} else frame
115 )
116 )
117 text = Text()
118 text.append(f" {icon} ", style=f"bold {style}")
119 text.append(worker.id, style="bold magenta")
120 text.append(f" {worker.name}", style="white")
121 text.append(f" {worker.status}", style=style)
122 if worker.intelligence:
123 text.append(f" {worker.intelligence}", style="magenta")
124 if worker.duration is not None:
125 text.append(f" {format_duration(worker.duration)}", style="dim")
126 text.append("\n ", style="dim")
127 text.append(f"{worker.role.name} · {worker.model}", style="dim")
128 if worker.last_action:
129 text.append(f" · {truncate(worker.last_action, 54)}", style="dim")
130 if worker.files_changed:
131 text.append(f" · файлов: {len(worker.files_changed)}", style="dim")
132 return text
133
134 def render_worker(self, worker: Worker, tick: int = 0) -> None:
135 try:
136 self.query_one(Static).update(self._render_text(worker, tick))
137 except Exception:
138 pass
139
140
141class PlanPanel(Vertical):
142 def compose(self) -> ComposeResult:
143 with Horizontal(classes="panel-head"):
144 yield Static("ПЛАН", classes="panel-title")
145 yield Static("0/0", id="plan-count", classes="panel-meta")
146 yield ProgressBar(total=1, show_eta=False, id="plan-progress")
147 yield Static(
148 "План появится, когда главная модель разобьёт задачу.",
149 id="plan-empty",
150 classes="empty-state",
151 )
152 yield ClickListView(id="plan-list")
153
154 def on_mount(self) -> None:
155 self.query_one("#plan-list", ListView).display = False
156 self._rows: dict[str, TodoRow] = {}
157
158 async def update_plan(self, tasks: list[dict], session_id: str | None = None) -> None:
159 if session_id and getattr(self, "_session_id", None) != session_id:
160 self._session_id = session_id
161 self._signature = None
162 self._rows = {}
163 signature = json.dumps(tasks, ensure_ascii=False, sort_keys=True)
164 if getattr(self, "_signature", None) == signature and getattr(self, "_rows", None):
165 self._tasks = tasks
166 return
167 self._signature = signature
168 self._tasks = tasks
169 list_view = self.query_one("#plan-list", ListView)
170 empty = self.query_one("#plan-empty", Static)
171 count = self.query_one("#plan-count", Static)
172 progress = self.query_one("#plan-progress", ProgressBar)
173 done = sum(1 for task in tasks if task.get("status") == "done")
174 total = len(tasks)
175 subtasks = [sub for task in tasks for sub in task.get("subtasks") or []]
176 done_sub = sum(1 for sub in subtasks if sub.get("status") == "done")
177 count.update(Text(f"{done}/{total} · {done_sub}/{len(subtasks)}"))
178 progress.display = bool(tasks)
179 progress.update(total=total or 1, progress=done)
180 if not tasks:
181 empty.display = True
182 list_view.display = False
183 await list_view.clear()
184 self._rows = {}
185 return
186 empty.display = False
187 list_view.display = True
188 await list_view.clear()
189 rows = [TodoRow(task) for task in tasks]
190 self._rows = {task.get("id", str(i)): row for i, (task, row) in enumerate(zip(tasks, rows))}
191 await list_view.extend(rows)
192
193 def tick(self, tick: int) -> None:
194 frame = spinner_frame(tick)
195 for task, row in zip(getattr(self, "_tasks", []), self._rows.values()):
196 if task.get("status") == "in_progress" or any(
197 sub.get("status") == "in_progress" for sub in task.get("subtasks") or []
198 ):
199 row.frame = frame
200 row.render_task()
201
202
203class WorkersPanel(Vertical):
204 def compose(self) -> ComposeResult:
205 with Horizontal(classes="panel-head"):
206 yield Static("ВОРКЕРЫ", classes="panel-title")
207 yield Static("0", id="workers-count", classes="panel-meta")
208 yield Static("Воркеров пока нет.", id="workers-empty", classes="empty-state")
209 yield ClickListView(id="workers-list")
210
211 def on_mount(self) -> None:
212 self.query_one("#workers-list", ListView).display = False
213 self._rows: dict[str, WorkerRow] = {}
214
215 async def sync(self, session: Session) -> None:
216 list_view = self.query_one("#workers-list", ListView)
217 empty = self.query_one("#workers-empty", Static)
218 count = self.query_one("#workers-count", Static)
219 if getattr(self, "_session_id", None) != session.id:
220 self._session_id = session.id
221 self._rows = {}
222 await list_view.clear()
223 count.update(Text(str(len(session.workers))))
224 if not session.workers:
225 empty.display = True
226 list_view.display = False
227 await list_view.clear()
228 self._rows = {}
229 return
230 empty.display = False
231 list_view.display = True
232 new_rows = [
233 WorkerRow(worker)
234 for worker_id, worker in session.workers.items()
235 if worker_id not in self._rows
236 ]
237 if new_rows:
238 await list_view.extend(new_rows)
239 for row in new_rows:
240 self._rows[row.worker_id] = row
241 for row in self._rows.values():
242 if row.worker_id in session.workers and row.is_mounted:
243 row.render_worker(session.workers[row.worker_id])
244
245 def tick(self, session: Session, tick: int) -> None:
246 for worker_id, row in self._rows.items():
247 worker = session.workers.get(worker_id)
248 if worker:
249 row.render_worker(worker, tick)
250
251
252class ContextPanel(Vertical):
253 def compose(self) -> ComposeResult:
254 with Horizontal(classes="panel-head"):
255 yield Static("КОНТЕКСТ", classes="panel-title")
256 yield Static("0%", id="context-percent", classes="panel-meta")
257 yield ProgressBar(total=1000, show_eta=False, id="context-progress")
258 yield Static("0 tokens", id="context-label", classes="context-label")
259
260 def update_context(self, tokens: int, limit: int) -> None:
261 limit = max(1, limit)
262 percent = min(100.0, tokens * 100.0 / limit)
263 progress = self.query_one("#context-progress", ProgressBar)
264 progress.update(total=1000, progress=percent * 10)
265 self.query_one("#context-percent", Static).update(
266 Text(f"{percent:.0f}% used")
267 )
268 self.query_one("#context-label", Static).update(
269 Text(f"{format_tokens(tokens)} / {format_tokens(limit)} tokens", style="dim")
270 )
271
272
273class StatsLine(Static):
274 def update_stats(self, session: Session | None, limit: int = 128_000) -> None:
275 if not session:
276 self.update(Text(" загрузка…", style="#6f747e"))
277 return
278 stats = session.stats()
279 main = stats["main_usage"]
280 cwd = str(session.cwd)
281 home = str(Path.home())
282 if cwd == home:
283 cwd = "~"
284 elif cwd.startswith(home + "/"):
285 cwd = "~" + cwd[len(home):]
286 done = sum(1 for task in session.todos if task.get("status") == "done")
287 percent = min(100, int(stats["context_tokens_estimate"] * 100 / max(1, limit)))
288 text = Text()
289 text.append(f" {cwd}", style="#8b909b")
290 text.append(" · ", style="#3a3f49")
291 text.append(session.config.orchestrator_model, style="#f0a35e")
292 text.append(" · ", style="#3a3f49")
293 text.append(
294 f"{format_tokens(stats['context_tokens_estimate'])} tokens ({percent}%)",
295 style="#7f8490",
296 )
297 text.append(" · ", style="#3a3f49")
298 text.append(f"план {done}/{len(session.todos)}", style="#7f8490")
299 text.append(" · ", style="#3a3f49")
300 text.append(f"{format_cost(main['cost'])}", style="#7f8490")
301 text.append(" · ", style="#3a3f49")
302 text.append("ctrl+s · ctrl+q", style="#4f545e")
303 self.update(text)