Репозитории /
AiRouter /
airouter/tui/screens.py
screens.py
| 1 | """Modal screens for the AiRouter TUI.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from typing import Any |
| 6 | |
| 7 | from rich.markdown import Markdown |
| 8 | from rich.panel import Panel |
| 9 | from rich.text import Text |
| 10 | from textual.app import ComposeResult |
| 11 | from textual.binding import Binding |
| 12 | from textual.containers import Horizontal, Vertical, VerticalScroll |
| 13 | from textual.screen import ModalScreen |
| 14 | from textual.widgets import Button, Collapsible, RichLog, Select, Static |
| 15 | |
| 16 | from ..models import ModelInfo |
| 17 | from ..session import Session |
| 18 | from ..utils import format_duration, truncate |
| 19 | from ..worker import Worker |
| 20 | |
| 21 | |
| 22 | def _model_options(models: list[ModelInfo], current: str) -> list[tuple[str, str]]: |
| 23 | ids = [model.id for model in models] |
| 24 | if current and current not in ids: |
| 25 | ids.append(current) |
| 26 | if not ids: |
| 27 | ids = [current] if current else ["deepseek-v4.1-flash"] |
| 28 | return [(model_id, model_id) for model_id in sorted(set(ids))] |
| 29 | |
| 30 | |
| 31 | class SettingsScreen(ModalScreen[dict[str, Any]]): |
| 32 | BINDINGS = [Binding("escape", "cancel", "Отмена")] |
| 33 | |
| 34 | CSS = """ |
| 35 | SettingsScreen { |
| 36 | align: center middle; |
| 37 | background: #050608 55%; |
| 38 | } |
| 39 | #settings-dialog { |
| 40 | width: 80; |
| 41 | height: 80%; |
| 42 | border: solid #343945; |
| 43 | background: #14171d; |
| 44 | padding: 1 2; |
| 45 | } |
| 46 | #settings-head { |
| 47 | height: 3; |
| 48 | layout: horizontal; |
| 49 | } |
| 50 | #settings-title { |
| 51 | width: 1fr; |
| 52 | content-align: left middle; |
| 53 | text-style: bold; |
| 54 | color: #f0a35e; |
| 55 | } |
| 56 | #settings-close { |
| 57 | width: 3; |
| 58 | height: 3; |
| 59 | min-width: 0; |
| 60 | background: transparent; |
| 61 | border: none; |
| 62 | color: #8b909b; |
| 63 | } |
| 64 | #settings-close:hover { |
| 65 | color: #f0a35e; |
| 66 | background: #1b1e25; |
| 67 | } |
| 68 | #settings-scroll { |
| 69 | height: 1fr; |
| 70 | padding-right: 1; |
| 71 | scrollbar-color: #343945; |
| 72 | scrollbar-background: #14171d; |
| 73 | scrollbar-size-vertical: 1; |
| 74 | scrollbar-visibility: hidden; |
| 75 | } |
| 76 | .section-label { |
| 77 | height: 2; |
| 78 | content-align: left bottom; |
| 79 | color: #f0a35e; |
| 80 | text-style: bold; |
| 81 | margin-top: 1; |
| 82 | } |
| 83 | .field { |
| 84 | height: 2; |
| 85 | layout: horizontal; |
| 86 | align-vertical: middle; |
| 87 | } |
| 88 | .field-label { |
| 89 | width: 27; |
| 90 | height: 2; |
| 91 | content-align: left middle; |
| 92 | color: #9a9fa9; |
| 93 | } |
| 94 | .field Select { |
| 95 | width: 42; |
| 96 | height: 1; |
| 97 | } |
| 98 | #settings-hint { |
| 99 | height: auto; |
| 100 | color: #7f8490; |
| 101 | padding: 1 0; |
| 102 | } |
| 103 | Collapsible { |
| 104 | background: #171a21; |
| 105 | border: solid #262b35; |
| 106 | margin: 1 0; |
| 107 | } |
| 108 | #settings-buttons { |
| 109 | height: 3; |
| 110 | align-horizontal: right; |
| 111 | margin-top: 1; |
| 112 | } |
| 113 | #settings-buttons Button { |
| 114 | margin-left: 1; |
| 115 | } |
| 116 | #settings-save { |
| 117 | background: #f0a35e; |
| 118 | color: #14161b; |
| 119 | border: none; |
| 120 | text-style: bold; |
| 121 | } |
| 122 | #settings-save:hover { |
| 123 | background: #ffbd7a; |
| 124 | } |
| 125 | #settings-cancel { |
| 126 | background: transparent; |
| 127 | border: solid #2a2f39; |
| 128 | color: #9a9fa9; |
| 129 | } |
| 130 | """ |
| 131 | def __init__(self, session: Session, models: list[ModelInfo]) -> None: |
| 132 | super().__init__() |
| 133 | self.session = session |
| 134 | self.models = models |
| 135 | self.role_names = list(session.config.roles) |
| 136 | |
| 137 | def compose(self) -> ComposeResult: |
| 138 | config = self.session.config |
| 139 | max_options = list(range(1, 17)) |
| 140 | if config.limits.max_workers > 16: |
| 141 | max_options.append(config.limits.max_workers) |
| 142 | with Vertical(id="settings-dialog"): |
| 143 | with Horizontal(id="settings-head"): |
| 144 | yield Static("НАСТРОЙКИ СЕССИИ", id="settings-title") |
| 145 | yield Button("x", id="settings-close", compact=True) |
| 146 | with VerticalScroll(id="settings-scroll"): |
| 147 | yield Static("МОДЕЛИ", classes="section-label") |
| 148 | with Horizontal(classes="field"): |
| 149 | yield Static("Максимум воркеров", classes="field-label") |
| 150 | yield Select( |
| 151 | [(str(value), value) for value in max_options], |
| 152 | value=config.limits.max_workers, |
| 153 | allow_blank=False, |
| 154 | compact=True, |
| 155 | id="setting-max-workers", |
| 156 | ) |
| 157 | with Horizontal(classes="field"): |
| 158 | yield Static("Главная модель", classes="field-label") |
| 159 | yield Select( |
| 160 | _model_options(self.models, config.orchestrator_model), |
| 161 | value=config.orchestrator_model, |
| 162 | allow_blank=False, |
| 163 | compact=True, |
| 164 | id="setting-main-model", |
| 165 | ) |
| 166 | with Horizontal(classes="field"): |
| 167 | yield Static("Модель воркеров", classes="field-label") |
| 168 | yield Select( |
| 169 | _model_options(self.models, config.worker_model), |
| 170 | value=config.worker_model, |
| 171 | allow_blank=False, |
| 172 | compact=True, |
| 173 | id="setting-worker-model", |
| 174 | ) |
| 175 | yield Static( |
| 176 | "Главная модель сама решает, сколько воркеров создать " |
| 177 | f"(в пределах {config.limits.max_workers}) и какой уровень сложности " |
| 178 | "назначить каждой задаче.\nПрокрутите вниз, чтобы настроить модели ролей.", |
| 179 | id="settings-hint", |
| 180 | ) |
| 181 | yield Static("МАРШРУТИЗАЦИЯ ПО СЛОЖНОСТИ", classes="section-label") |
| 182 | for level, label in ( |
| 183 | ("low", "Низкий — механический"), |
| 184 | ("medium", "Средний — обычная работа"), |
| 185 | ("high", "Высокий — архитектура/баг"), |
| 186 | ): |
| 187 | with Horizontal(classes="field"): |
| 188 | yield Static(label, classes="field-label") |
| 189 | yield Select( |
| 190 | _model_options( |
| 191 | self.models, |
| 192 | config.intelligence.get(level, config.worker_model), |
| 193 | ), |
| 194 | value=config.intelligence.get(level, config.worker_model), |
| 195 | allow_blank=False, |
| 196 | compact=True, |
| 197 | id=f"setting-intel-{level}", |
| 198 | ) |
| 199 | with Collapsible(title="МОДЕЛИ РОЛЕЙ", collapsed=True): |
| 200 | for index, name in enumerate(self.role_names): |
| 201 | role = config.roles[name] |
| 202 | options = [("auto", "")] + _model_options( |
| 203 | self.models, role.model or "" |
| 204 | ) |
| 205 | with Horizontal(classes="field"): |
| 206 | yield Static( |
| 207 | f"{name} — {role.description[:24]}", |
| 208 | classes="field-label", |
| 209 | ) |
| 210 | yield Select( |
| 211 | options, |
| 212 | value=role.model or "", |
| 213 | allow_blank=False, |
| 214 | compact=True, |
| 215 | id=f"setting-role-{index}", |
| 216 | ) |
| 217 | with Horizontal(id="settings-buttons"): |
| 218 | yield Button("Сохранить", id="settings-save", variant="primary") |
| 219 | yield Button("Отмена", id="settings-cancel") |
| 220 | |
| 221 | def on_button_pressed(self, event: Button.Pressed) -> None: |
| 222 | if event.button.id in {"settings-cancel", "settings-close"}: |
| 223 | self.dismiss(None) |
| 224 | return |
| 225 | if event.button.id != "settings-save": |
| 226 | return |
| 227 | max_select = self.query_one("#setting-max-workers", Select) |
| 228 | main_select = self.query_one("#setting-main-model", Select) |
| 229 | worker_select = self.query_one("#setting-worker-model", Select) |
| 230 | values = { |
| 231 | "max_workers": int(max_select.value), |
| 232 | "orchestrator_model": str(main_select.value), |
| 233 | "worker_model": str(worker_select.value), |
| 234 | "intelligence": { |
| 235 | level: str( |
| 236 | self.query_one(f"#setting-intel-{level}", Select).value |
| 237 | ) |
| 238 | for level in ("low", "medium", "high") |
| 239 | }, |
| 240 | "roles": { |
| 241 | name: str( |
| 242 | self.query_one(f"#setting-role-{index}", Select).value or "" |
| 243 | ) |
| 244 | for index, name in enumerate(self.role_names) |
| 245 | }, |
| 246 | } |
| 247 | self.dismiss(values) |
| 248 | |
| 249 | def action_cancel(self) -> None: |
| 250 | self.dismiss(None) |
| 251 | |
| 252 | |
| 253 | class WorkerDetailScreen(ModalScreen[None]): |
| 254 | BINDINGS = [Binding("escape", "close", "Закрыть")] |
| 255 | |
| 256 | CSS = """ |
| 257 | WorkerDetailScreen { |
| 258 | align: center middle; |
| 259 | background: #050608 55%; |
| 260 | } |
| 261 | #worker-dialog { |
| 262 | width: 88%; |
| 263 | height: 86%; |
| 264 | border: solid #343945; |
| 265 | background: #14171d; |
| 266 | padding: 1 2; |
| 267 | } |
| 268 | #worker-title { |
| 269 | height: 3; |
| 270 | content-align: left middle; |
| 271 | text-style: bold; |
| 272 | color: #f0a35e; |
| 273 | } |
| 274 | #worker-meta { |
| 275 | height: auto; |
| 276 | color: #8b909b; |
| 277 | padding-bottom: 1; |
| 278 | } |
| 279 | #worker-log { |
| 280 | height: 1fr; |
| 281 | border: solid #262b35; |
| 282 | background: #101319; |
| 283 | scrollbar-color: #343945; |
| 284 | scrollbar-background: #101319; |
| 285 | scrollbar-size-vertical: 1; |
| 286 | } |
| 287 | #worker-buttons { |
| 288 | height: 3; |
| 289 | align-horizontal: right; |
| 290 | padding-top: 1; |
| 291 | } |
| 292 | #worker-buttons Button { |
| 293 | margin-left: 1; |
| 294 | } |
| 295 | #worker-close { |
| 296 | background: #f0a35e; |
| 297 | color: #14161b; |
| 298 | border: none; |
| 299 | text-style: bold; |
| 300 | } |
| 301 | #worker-transcript { |
| 302 | background: transparent; |
| 303 | border: solid #2a2f39; |
| 304 | color: #9a9fa9; |
| 305 | } |
| 306 | """ |
| 307 | def __init__(self, worker: Worker) -> None: |
| 308 | super().__init__() |
| 309 | self.worker = worker |
| 310 | |
| 311 | def compose(self) -> ComposeResult: |
| 312 | with Vertical(id="worker-dialog"): |
| 313 | yield Static( |
| 314 | f"{self.worker.id} · {self.worker.name}", id="worker-title" |
| 315 | ) |
| 316 | yield Static(id="worker-meta") |
| 317 | yield RichLog(id="worker-log", min_width=1, wrap=True, markup=False) |
| 318 | with Horizontal(id="worker-buttons"): |
| 319 | yield Button("Транскрипт", id="worker-transcript") |
| 320 | yield Button("Закрыть", id="worker-close", variant="primary") |
| 321 | |
| 322 | def on_mount(self) -> None: |
| 323 | self._write_report() |
| 324 | |
| 325 | def _write_report(self) -> None: |
| 326 | worker = self.worker |
| 327 | meta = Text() |
| 328 | meta.append(f"статус: {worker.status}", style="bold") |
| 329 | meta.append(f" · роль: {worker.role.name}") |
| 330 | meta.append(f" · модель: {worker.model}") |
| 331 | if worker.intelligence: |
| 332 | meta.append(f" · сложность: {worker.intelligence}") |
| 333 | meta.append(f" · время: {format_duration(worker.duration)}") |
| 334 | meta.append(f"\n{worker.workspace_path}") |
| 335 | self.query_one("#worker-meta", Static).update(meta) |
| 336 | log = self.query_one("#worker-log", RichLog) |
| 337 | log.clear() |
| 338 | if worker.result: |
| 339 | log.write( |
| 340 | Panel( |
| 341 | Markdown(worker.result), |
| 342 | title="Отчёт", |
| 343 | border_style="green" if worker.status == "done" else "red", |
| 344 | ) |
| 345 | ) |
| 346 | elif worker.error: |
| 347 | log.write(Panel(Text(worker.error), title="Ошибка", border_style="red")) |
| 348 | else: |
| 349 | log.write(Text("Отчёта пока нет.", style="dim")) |
| 350 | if worker.files_changed: |
| 351 | log.write(Text("Файлы:", style="bold")) |
| 352 | for path in worker.files_changed: |
| 353 | log.write(Text(f" {path}", style="dim")) |
| 354 | if worker.commands: |
| 355 | log.write(Text("Команды:", style="bold")) |
| 356 | for command in worker.commands[-10:]: |
| 357 | log.write( |
| 358 | Text( |
| 359 | f" $ {truncate(str(command.get('command', '')), 140)} " |
| 360 | f"→ {command.get('exit_code')} ({command.get('duration')}s)", |
| 361 | style="dim", |
| 362 | ) |
| 363 | ) |
| 364 | if worker.error and worker.result: |
| 365 | log.write(Panel(Text(worker.error), title="Ошибка", border_style="red")) |
| 366 | |
| 367 | def on_button_pressed(self, event: Button.Pressed) -> None: |
| 368 | if event.button.id == "worker-close": |
| 369 | self.dismiss(None) |
| 370 | elif event.button.id == "worker-transcript": |
| 371 | self.query_one("#worker-log", RichLog).write( |
| 372 | Panel( |
| 373 | Text(self.worker.transcript_tail(60)), |
| 374 | title="Транскрипт (последние сообщения)", |
| 375 | border_style="cyan", |
| 376 | ) |
| 377 | ) |
| 378 | |
| 379 | def action_close(self) -> None: |
| 380 | self.dismiss(None) |