-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtui.py
More file actions
1334 lines (1160 loc) · 51.9 KB
/
Copy pathtui.py
File metadata and controls
1334 lines (1160 loc) · 51.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
CosySim TUI
===========
Interactive terminal launcher and system dashboard built on Textual. Provides
a three-panel interface (target list, details/logs, external services health)
with real-time port monitoring, HAR import wizard, and priority-sorted autostart.
Usage:
python tui.py # full TUI
python tui.py --no-autostart # open TUI without auto-launching
Keyboard shortcuts:
↑ / ↓ — navigate target list (or services table when focused)
← / → — move focus: target list ⇄ center panel
Space / Enter — launch selected target (works in list AND services table)
S — stop selected target (terminates subprocess; port goes down)
A — launch all auto-start targets
O — open selected in browser
C — open Nexus Canvas in browser
I — HAR import wizard (scans all HAR directories)
R — refresh all port statuses
H — show system health summary
L — show log panel
Q / Ctrl+C — quit (stops launched subprocesses)
Version: v1.58.0 [2026-06-11]
Author: CosySim Team
Change Log:
v1.58.0 [2026-06-11] — Arrow-key navigation overhaul: ←/→ panel focus,
focus-aware ↑/↓, Enter/Space launch from services
table, clickable+focusable TargetRows. Launch path
switched from in-process daemon threads to
launcher.py subprocesses (isolated, stoppable —
fixes GridScene/LabBreakScene host= crash and makes
S work for every target type).
v1.52.0 [2026-03-25] — Version stamp sync with audit remediation
v1.49.1 [2026-03-22] — Version stamp sync, HAR_REAL_ROOT via env var
v1.42.1 [2026-03-21] — External type handler in _start_one, priority-sorted
autostart via start_priority field
v1.42.0 [2026-03-21] — Three-pillar architecture (game/service/creation)
v1.41.0 [2026-03-20] — ARGUS Deep Polish, HAR import wizard
"""
from __future__ import annotations
import json as _json_mod
import os
import socket
import subprocess
import sys
import threading
import time
import webbrowser
from pathlib import Path
from typing import Any, ClassVar, Dict, List, Optional
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))
for _s in (sys.stdout, sys.stderr):
try:
_s.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, OSError):
pass
# v1.58.0 [2026-06-11] — PYTHON + _kill_port imported so TUI launches use the
# same venv interpreter + zombie-port cleanup as the CLI launcher.
from launcher import ( # noqa: E402
SERVICES, SCENES, ALL_TARGETS, VERSION, PYTHON, _kill_port, _port_up,
)
from engine.control_plane_registry import PILLAR_IDS # noqa: E402
from engine.port_registry import TUI_EXTERNAL_TARGETS, build_target_listing # noqa: E402
from textual import on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical, ScrollableContainer
from textual.css.query import NoMatches
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import (
DataTable, Footer, Header, Label, ListItem, ListView,
Log, ProgressBar, RichLog, Rule, Static, TabbedContent, TabPane,
)
from textual.timer import Timer
# ──── HAR Directory Roots ─────────────────────────────────────────────────
# v1.49.1 [2026-03-22] — Use env var instead of hardcoded Windows path
HAR_REAL_ROOT = Path(os.environ.get("COSYSIM_HAR_ROOT", r"C:\Files\Models\HAR_Files"))
HAR_LOCAL_ROOT = PROJECT_ROOT / "data" / "har_files"
ACCOUNTS_COOKIES_DIR = PROJECT_ROOT / "data" / "accounts" # {acct}_cookies.json
ACCOUNTS_LEGACY_DIR = PROJECT_ROOT / "data" / "google_accounts" # {acct}/cookies.json
# ──── External Services (Health Panel) ────────────────────────────────────
EXTERNAL_SERVICES = [
(target["label"], target["port"], target["health_url"])
for target in build_target_listing(TUI_EXTERNAL_TARGETS)
] + [("GitHub Copilot", 0, "")]
# ──── Colour Scheme ───────────────────────────────────────────────────────
# v1.52.0 [2026-03-22] — Cyberpunk TUI theme: deeper void, cyan/magenta accents,
# neon borders, color-coded pillar sections
TUI_CSS = """
Screen {
background: #050710;
color: #c0c8d8;
}
Header {
background: #0a0e18;
color: #06b6d4;
text-style: bold;
height: 3;
}
Footer {
background: #0a0e18;
color: #4a5568;
height: 1;
}
#left-panel {
width: 42;
background: #080a12;
border-right: tall #162032;
overflow-y: auto;
}
#center-panel {
background: #050710;
}
#right-panel {
width: 36;
background: #080a12;
border-left: tall #162032;
}
.panel-title {
background: #0a1628;
color: #06b6d4;
text-style: bold;
padding: 0 1;
height: 1;
}
.section-title {
color: #a855f7;
text-style: bold;
padding: 0 1;
height: 1;
}
TargetRow {
height: 1;
padding: 0 1;
}
TargetRow:hover {
background: #0f1724;
}
/* v1.58.0 [2026-06-11] — Focused row gets a visible neon edge so keyboard
users can see where ←/↑/↓ focus currently sits. */
TargetRow:focus {
background: #102036;
border-left: thick #06b6d4;
}
TargetRow.-selected {
background: #0c1a2e;
color: #06b6d4;
text-style: bold;
}
TargetRow.-running {
color: #22c55e;
}
TargetRow.-stopped {
color: #4a5568;
}
TargetRow.-autostart {
color: #a855f7;
}
ServiceStatus {
height: 1;
padding: 0 1;
}
.status-up {
color: #22c55e;
}
.status-down {
color: #ef4444;
}
#log-panel {
border: tall #162032;
margin: 0 1;
height: 1fr;
}
#account-list {
height: 1fr;
padding: 0 1;
}
.account-row {
height: 1;
padding: 0 1;
color: #64748b;
}
#details-bar {
height: 3;
background: #080a12;
border-top: tall #162032;
padding: 0 1;
color: #64748b;
}
TabbedContent {
height: 1fr;
}
TabPane {
padding: 0;
}
Rule {
color: #162032;
}
DataTable {
background: #050710;
}
DataTable > .datatable--header {
background: #0a0e18;
color: #06b6d4;
text-style: bold;
}
DataTable > .datatable--cursor {
background: #0c1a2e;
color: #06b6d4;
}
"""
# ──── Target Row Widget ───────────────────────────────────────────────────
class TargetRow(Static):
"""One row per scene/service in the left panel.
v1.58.0 [2026-06-11] — Rows are now focusable + clickable so arrow keys
and the mouse both drive selection (CONNECTS: CosySimTUI._select).
"""
can_focus = True # v1.58.0 — keyboard focus lands directly on rows
COMPONENT_CLASSES: ClassVar[set[str]] = {
"selected", "running", "stopped", "autostart",
}
def __init__(self, name: str, info: Dict[str, Any], group: str) -> None:
super().__init__()
self.target_name = name
self.info = info
self.group = group
self._is_up = False
self._selected = False
# v1.58.0 [2026-06-11] — Mouse + focus drive app-level selection
# CALLED BY: Textual event dispatch · CONNECTS: CosySimTUI._select_row
def on_click(self) -> None:
self.app._select_row(self) # type: ignore[attr-defined]
self.focus()
def on_focus(self) -> None:
self.app._select_row(self) # type: ignore[attr-defined]
def render_row(self) -> str:
# v1.52.0 — Enhanced status indicators with color hints
icon = "[green]●[/]" if self._is_up else "[dim]○[/]"
auto = "[magenta]★[/]" if self.info.get("auto_start") else " "
label = self.info["label"][:20]
port = self.info["port"]
port_str = f"[dim]:{port}[/]"
return f" {icon} {auto} {label:<20} {port_str}"
def render(self) -> str:
return self.render_row()
def refresh_status(self) -> None:
self._is_up = _port_up(self.info["port"])
if self._is_up:
self.remove_class("-stopped")
self.add_class("-running")
else:
self.remove_class("-running")
self.add_class("-stopped")
self.refresh()
def select(self) -> None:
self._selected = True
self.add_class("-selected")
def deselect(self) -> None:
self._selected = False
self.remove_class("-selected")
# ──── Main TUI App ────────────────────────────────────────────────────────
class CosySimTUI(App[None]):
"""CosySim interactive TUI launcher."""
TITLE = f"CosySim v{VERSION} — NEXUS CONTROL"
SUB_TITLE = "Terminal Launcher & System Dashboard"
CSS = TUI_CSS
BINDINGS = [
Binding("space", "launch_selected", "Launch", show=True, priority=True),
Binding("enter", "launch_selected", "Launch", show=False, priority=True),
Binding("s", "stop_selected", "Stop", show=True, priority=True),
Binding("a", "launch_autostart", "Auto-start", show=True, priority=True),
Binding("o", "open_browser", "Open", show=True, priority=True),
Binding("c", "open_canvas", "Canvas", show=True, priority=True),
Binding("h", "show_health", "Health", show=True, priority=True),
Binding("l", "show_log", "Log", show=True, priority=True),
Binding("r", "refresh_status", "Refresh", show=True, priority=True),
Binding("g", "launch_game", "Game", show=True, priority=True),
Binding("v", "launch_services", "Services", show=False, priority=True),
Binding("k", "launch_creation", "Creation", show=False, priority=True),
Binding("i", "import_har", "Import HAR", show=False, priority=True),
# v1.58.0 [2026-06-11] — Arrow-key panel navigation: ↑/↓ are focus-aware
# (target list vs services table) and ←/→ hop between panels.
Binding("up", "cursor_up", "Up", show=False, priority=True),
Binding("down", "cursor_down", "Down", show=False, priority=True),
Binding("left", "focus_targets", "Targets", show=False, priority=True),
Binding("right", "focus_center", "Panel", show=False, priority=True),
Binding("q", "quit", "Quit", show=True, priority=True),
]
selected_index: reactive[int] = reactive(0)
def __init__(self, autostart: bool = True, pillar_filter: str | None = None) -> None:
super().__init__()
self._autostart = autostart
self._pillar_filter = pillar_filter # v1.50.0 — optional pillar filter
self._rows: List[TargetRow] = []
# v1.58.0 [2026-06-11] — All launches are subprocesses now (no threads)
self._launched_procs: Dict[str, subprocess.Popen] = {}
self._refresh_timer: Optional[Timer] = None
self._log_lines: List[str] = []
# ── Layout ────────────────────────────────────────────────────────────
def compose(self) -> ComposeResult:
yield Header()
with Horizontal():
# Left panel — target list
with Vertical(id="left-panel"):
# Three pillar sections (filtered if --pillar is set)
# v1.50.0 [2026-03-22] — Pillar filter support
all_pillars = [
(" NEONCITY", "game"),
(" SERVICES", "service"),
(" CREATION KIT", "creation"),
]
pillar_sections = (
[(l, p) for l, p in all_pillars if p == self._pillar_filter]
if self._pillar_filter else all_pillars
)
for idx, (section_label, pillar) in enumerate(pillar_sections):
if idx > 0:
yield Rule()
yield Static(section_label, classes="section-title")
for tid in PILLAR_IDS.get(pillar, ()):
info = ALL_TARGETS.get(tid)
if not info:
continue
group = "service" if tid in SERVICES else "scene"
row = TargetRow(tid, info, group)
self._rows.append(row)
yield row
# Center panel — tabbed content
with Vertical(id="center-panel"):
with TabbedContent():
with TabPane("🌐 Services", id="tab-services"):
yield self._build_services_table()
with TabPane("📋 Log", id="tab-log"):
yield RichLog(id="log-panel", highlight=True, markup=True,
wrap=True, auto_scroll=True)
with TabPane("🔑 Accounts", id="tab-accounts"):
with ScrollableContainer(id="account-list"):
yield from self._accounts_widgets()
with TabPane("📡 HAR Files", id="tab-har"):
with ScrollableContainer(id="har-list"):
yield from self._har_widgets()
yield Static(id="details-bar")
# Right panel — external services + system health
with Vertical(id="right-panel"):
yield Static(
f" [bold]CosySim[/] [cyan]v{VERSION}[/]",
classes="panel-title",
)
yield Rule()
yield Static(" EXTERNAL SERVICES", classes="section-title")
for label, port, url in EXTERNAL_SERVICES:
yield self._ext_row(label, port, url)
yield Rule()
yield Static(" SYSTEM HEALTH", classes="section-title")
yield Static(id="nexus-health", classes="account-row")
yield Static(id="lmstudio-health", classes="account-row")
yield Static(id="lmstudio-model", classes="account-row")
yield Rule()
yield Static(" QUICK STATS", classes="section-title")
yield Static(id="stats-label", classes="account-row")
yield Footer()
def _ext_row(self, label: str, port: int, url: str) -> Static:
if port == 0:
# Token-based service — check for ANY account cookies file
ok = any(ACCOUNTS_COOKIES_DIR.glob("*_cookies.json")) if ACCOUNTS_COOKIES_DIR.exists() else False
icon = "[green]●[/]" if ok else "[yellow]○[/]"
suffix = "[dim](cookie)[/]"
return Static(
f" {icon} [bold]{label}[/] {suffix}",
id=f"ext-copilot",
classes="ServiceStatus",
)
up = _port_up(port)
icon = "[green]●[/]" if up else "[red]○[/]"
return Static(
f" {icon} [bold]{label}[/] [dim]:{port}[/]",
id=f"ext-{port}",
classes="ServiceStatus",
)
def _build_services_table(self) -> DataTable:
"""Return a DataTable of all services/scenes (status populated async)."""
table = DataTable(id="svc-table")
table.add_columns("Name", "Port", "Status", "Label")
for name, info in {**SERVICES, **SCENES}.items():
table.add_row(
name,
str(info["port"]),
"[dim]…[/]", # filled in by first background refresh
info["label"],
)
return table
def _accounts_widgets(self):
"""Yield account row widgets for the Accounts tab."""
account_names: List[str] = []
for har_root in (HAR_REAL_ROOT, HAR_LOCAL_ROOT):
if har_root.exists():
for d in sorted(har_root.iterdir()):
if d.is_dir() and not d.name.startswith(".") and d.name not in account_names:
account_names.append(d.name)
if ACCOUNTS_COOKIES_DIR.exists():
for f in sorted(ACCOUNTS_COOKIES_DIR.glob("*_cookies.json")):
acct = f.stem.removesuffix("_cookies")
if acct not in account_names:
account_names.append(acct)
if not account_names:
yield Static(
" No accounts found. Press [bold]I[/] to import a HAR.",
classes="account-row",
)
return
for acct in account_names:
new_cookies = ACCOUNTS_COOKIES_DIR / f"{acct}_cookies.json"
legacy_cookies = ACCOUNTS_LEGACY_DIR / acct / "cookies.json"
has_cookies = new_cookies.exists() or legacy_cookies.exists()
icon = "[green]✓[/]" if has_cookies else "[yellow]○[/]"
har_count = 0
for har_root in (HAR_REAL_ROOT, HAR_LOCAL_ROOT):
har_dir = har_root / acct
if har_dir.exists():
har_count += sum(1 for _ in har_dir.glob("*.har"))
services: List[str] = []
if new_cookies.exists():
try:
import json as _json
data = _json.loads(new_cookies.read_text(encoding="utf-8"))
if any("github" in k for k in data):
services.append("github")
if any("google" in k for k in data):
services.append("google")
except Exception:
pass
svc_label = (" [dim]" + ",".join(services) + "[/]") if services else ""
yield Static(
f" {icon} [bold]{acct}[/]{svc_label} [dim]({har_count} HARs)[/]",
classes="account-row",
)
def _har_widgets(self):
"""Yield HAR file list widgets for the HAR Files tab."""
all_files: Dict[str, List[Path]] = {}
for har_root in (HAR_REAL_ROOT, HAR_LOCAL_ROOT):
if not har_root.exists():
continue
for d in sorted(har_root.iterdir()):
if not d.is_dir() or d.name.startswith("."):
continue
hars = sorted(d.glob("*.har"))
if hars:
all_files.setdefault(d.name, []).extend(hars)
if not all_files:
yield Static(
" No HAR files found. Capture via Canvas browser or press I to import.",
classes="account-row",
)
return
total = sum(len(v) for v in all_files.values())
yield Static(
f" [bold cyan]{total} HAR files[/] across [bold]{len(all_files)}[/] accounts"
f" [dim]Press I to import[/]",
classes="account-row",
)
yield Static("", classes="account-row")
for acct, files in sorted(all_files.items()):
total_mb = sum(f.stat().st_size for f in files) / (1024 * 1024)
yield Static(
f" [bold]{acct}[/] [dim]({len(files)} files · {total_mb:.1f} MB)[/]",
classes="account-row",
)
for f in files:
size_mb = f.stat().st_size / (1024 * 1024)
yield Static(
f" [dim]└ {f.name} ({size_mb:.1f} MB)[/]",
classes="account-row",
)
# ── On mount ──────────────────────────────────────────────────────────
def on_mount(self) -> None:
# v1.50.0 [2026-03-22] — Set subtitle based on pillar filter
if self._pillar_filter:
pillar_labels = {"game": "Game Scenes", "service": "System Services", "creation": "Creation Kit"}
self.sub_title = pillar_labels.get(self._pillar_filter, self._pillar_filter.title())
self._select(0)
self._do_refresh()
self._refresh_timer = self.set_interval(10, self._do_refresh)
total = len(self._rows)
scenes = sum(1 for r in self._rows if r.group == "scene")
svcs = sum(1 for r in self._rows if r.group == "service")
self._log(
f"[bold cyan]CosySim v{VERSION}[/] ready — "
f"[dim]{scenes} scenes · {svcs} services · {total} targets[/]"
)
self._log(
"[dim]Keys:[/] [bold]↑↓[/]=nav [bold]←→[/]=panel "
"[bold]Space/Enter[/]=launch "
"[bold]A[/]=autostart [bold]S[/]=stop [bold]O[/]=open "
"[bold]C[/]=canvas [bold]H[/]=health [bold]R[/]=refresh "
"[bold]I[/]=HAR [bold]Q[/]=quit"
)
if self._autostart:
self.call_after_refresh(self.action_launch_autostart)
# ── Status refresh ────────────────────────────────────────────────────
def _refresh_all_status(self) -> None:
"""Called from timer — dispatches threaded refresh to avoid blocking event loop."""
self._do_refresh()
@work(thread=True)
def _do_refresh(self) -> None:
"""All socket checks run in a worker thread — never blocks the UI."""
# Check CosySim rows
results: Dict[str, bool] = {}
for row in self._rows:
results[row.target_name] = _port_up(row.info["port"])
def _apply_rows() -> None:
for row in self._rows:
up = results.get(row.target_name, False)
row._is_up = up
if up:
row.remove_class("-stopped"); row.add_class("-running")
else:
row.remove_class("-running"); row.add_class("-stopped")
row.refresh()
self.call_from_thread(_apply_rows)
# Check external services
ext_results: Dict[str, tuple[str, bool]] = {}
for label, port, _ in EXTERNAL_SERVICES:
if port == 0:
ok = any(ACCOUNTS_COOKIES_DIR.glob("*_cookies.json")) if ACCOUNTS_COOKIES_DIR.exists() else False
ext_results[label] = ("copilot", ok)
else:
ext_results[label] = (str(port), _port_up(port))
def _apply_ext() -> None:
for label, (key, ok) in ext_results.items():
icon = "[green]●[/]" if ok else "[red]○[/]"
try:
if key == "copilot":
w = self.query_one("#ext-copilot", Static)
w.update(f" {icon} [bold]{label}[/] [dim](cookie)[/]")
else:
w = self.query_one(f"#ext-{key}", Static)
w.update(f" {icon} [bold]{label}[/] [dim]:{key}[/]")
except NoMatches:
pass
self._update_stats()
self.call_from_thread(_apply_ext)
# Fetch system health (Nexus + LMStudio)
health_info = self._fetch_system_health()
def _apply_health() -> None:
try:
nexus_w = self.query_one("#nexus-health", Static)
nexus_w.update(health_info.get("nexus_line", " [dim]Nexus: unknown[/]"))
except NoMatches:
pass
try:
lms_w = self.query_one("#lmstudio-health", Static)
lms_w.update(health_info.get("lmstudio_line", " [dim]LMStudio: unknown[/]"))
except NoMatches:
pass
try:
model_w = self.query_one("#lmstudio-model", Static)
model_w.update(health_info.get("model_line", ""))
except NoMatches:
pass
self.call_from_thread(_apply_health)
def _fetch_system_health(self) -> Dict[str, str]:
"""Probe Nexus and LMStudio for health info (runs in worker thread)."""
import urllib.request
info: Dict[str, str] = {}
# Nexus health
try:
from engine.port_registry import get_service_url
req = urllib.request.Request(
get_service_url("nexus", "/api/health"),
headers={"Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=3) as resp:
data = _json_mod.loads(resp.read())
entries = data.get("entries", data.get("entry_count", "?"))
qa = data.get("qa_pairs", data.get("qa_count", "?"))
rules = data.get("rules", data.get("rule_count", "?"))
info["nexus_line"] = (
f" [green]●[/] [bold]Nexus[/] "
f"[cyan]{entries}[/] entries "
f"[cyan]{qa}[/] Q&A "
f"[cyan]{rules}[/] rules"
)
except Exception:
info["nexus_line"] = " [red]○[/] [bold]Nexus[/] [dim]offline[/]"
# LMStudio health + loaded model (with bearer auth)
try:
headers: Dict[str, str] = {"Accept": "application/json"}
try:
from engine.config import get_config
token = get_config().get("lmstudio.api_token", "")
if token:
headers["Authorization"] = f"Bearer {token}"
except Exception:
pass
from engine.port_registry import get_service_url
req = urllib.request.Request(
get_service_url("lmstudio", "/api/v1/models"),
headers=headers,
)
with urllib.request.urlopen(req, timeout=3) as resp:
data = _json_mod.loads(resp.read())
models = data.get("data", [])
if models:
model_id = models[0].get("id", "unknown")
short = model_id.split("/")[-1] if "/" in model_id else model_id
if len(short) > 30:
short = short[:27] + "…"
info["lmstudio_line"] = (
f" [green]●[/] [bold]LMStudio[/] "
f"[cyan]{len(models)}[/] model(s)"
)
info["model_line"] = f" [dim]└ {short}[/]"
else:
info["lmstudio_line"] = " [yellow]●[/] [bold]LMStudio[/] [dim]no models[/]"
info["model_line"] = ""
except Exception:
info["lmstudio_line"] = " [red]○[/] [bold]LMStudio[/] [dim]offline[/]"
info["model_line"] = ""
return info
def _update_stats(self) -> None:
try:
widget = self.query_one("#stats-label", Static)
up_scenes = sum(1 for r in self._rows if r.group == "scene" and r._is_up)
up_svcs = sum(1 for r in self._rows if r.group == "service" and r._is_up)
total_scenes = sum(1 for r in self._rows if r.group == "scene")
total_svcs = sum(1 for r in self._rows if r.group == "service")
auto_count = sum(1 for r in self._rows if r.info.get("auto_start"))
widget.update(
f" [green]{up_svcs}[/][dim]/{total_svcs}[/] services "
f"[green]{up_scenes}[/][dim]/{total_scenes}[/] scenes\n"
f" [dim]{auto_count} auto-start targets[/]"
)
except NoMatches:
pass
# ── Selection navigation ──────────────────────────────────────────────
def _select(self, index: int) -> None:
if not self._rows:
return
index = max(0, min(index, len(self._rows) - 1))
for i, row in enumerate(self._rows):
if i == index:
row.select()
else:
row.deselect()
self.selected_index = index
self._update_details()
def _update_details(self) -> None:
try:
bar = self.query_one("#details-bar", Static)
except NoMatches:
return
if not self._rows:
return
row = self._rows[self.selected_index]
info = row.info
up = row._is_up
status = "[green]● UP[/]" if up else "[red]○ DOWN[/]"
auto = "[yellow]★ auto-start[/]" if info.get("auto_start") else ""
bar.update(
f" {status} [bold]{info['label']}[/] [dim]:{info['port']}[/] {auto}\n"
f" [dim]http://localhost:{info['port']}[/]"
)
# v1.58.0 [2026-06-11] — Focus-aware arrow navigation
# CONNECTS: TargetRow, DataTable(#svc-table) · CALLED BY: ↑/↓/←/→ bindings
def _select_row(self, row: TargetRow) -> None:
"""Select a row object directly (mouse click / focus event)."""
try:
self._select(self._rows.index(row))
except ValueError:
pass
def _focused_svc_table(self) -> Optional[DataTable]:
"""Return the services DataTable iff it currently has focus."""
focused = self.focused
if isinstance(focused, DataTable) and focused.id == "svc-table":
return focused
return None
def action_cursor_up(self) -> None:
table = self._focused_svc_table()
if table is not None:
table.action_cursor_up()
return
self._select(self.selected_index - 1)
self._focus_selected_row()
def action_cursor_down(self) -> None:
table = self._focused_svc_table()
if table is not None:
table.action_cursor_down()
return
self._select(self.selected_index + 1)
self._focus_selected_row()
def _focus_selected_row(self) -> None:
"""Keep keyboard focus glued to the selected TargetRow (if any)."""
if self._rows:
try:
self._rows[self.selected_index].focus()
except Exception:
pass # row may not be mounted yet during startup
def action_focus_targets(self) -> None:
"""← — move focus back to the left target list at the current selection."""
self._focus_selected_row()
def action_focus_center(self) -> None:
"""→ — move focus to the center panel (active tab's content)."""
try:
tc = self.query_one(TabbedContent)
except NoMatches:
return
# Focus the services table when its tab is active, else the tab content
if tc.active == "tab-services":
try:
self.query_one("#svc-table", DataTable).focus()
return
except NoMatches:
pass
tc.focus()
def action_show_log(self) -> None:
"""Switch the center panel to the Log tab."""
try:
tc = self.query_one(TabbedContent)
tc.active = "tab-log"
except NoMatches:
pass
def action_show_health(self) -> None:
"""Log a system health summary to the log panel."""
try:
tc = self.query_one(TabbedContent)
tc.active = "tab-log"
except NoMatches:
pass
self._log("[bold cyan]───── System Health Summary ─────[/]")
up_scenes = sum(1 for r in self._rows if r.group == "scene" and r._is_up)
up_svcs = sum(1 for r in self._rows if r.group == "service" and r._is_up)
total_scenes = sum(1 for r in self._rows if r.group == "scene")
total_svcs = sum(1 for r in self._rows if r.group == "service")
auto_count = sum(1 for r in self._rows if r.info.get("auto_start"))
self._log(
f" Services: [green]{up_svcs}[/]/{total_svcs} "
f"Scenes: [green]{up_scenes}[/]/{total_scenes} "
f"Auto-start: {auto_count}"
)
for label, port, _ in EXTERNAL_SERVICES:
if port == 0:
ok = any(ACCOUNTS_COOKIES_DIR.glob("*_cookies.json")) if ACCOUNTS_COOKIES_DIR.exists() else False
icon = "[green]●[/]" if ok else "[red]○[/]"
self._log(f" {icon} {label}")
else:
up = _port_up(port)
icon = "[green]●[/]" if up else "[red]○[/]"
self._log(f" {icon} {label} :{port}")
# Show up/down scenes
down_scenes = [r.info["label"] for r in self._rows if r.group == "scene" and not r._is_up]
if down_scenes and len(down_scenes) < total_scenes:
self._log(f" [dim]Down: {', '.join(down_scenes[:8])}{'…' if len(down_scenes) > 8 else ''}[/]")
self._log(f" Version: [bold]{VERSION}[/]")
self._log("[bold cyan]────────────────────────────────[/]")
# ── Launch / Stop ─────────────────────────────────────────────────────
# v1.58.0 [2026-06-11] — Resolve the launch/stop target from whichever
# panel has focus: services DataTable cursor row, else the selected row.
def _current_target(self) -> Optional[tuple[str, Dict[str, Any]]]:
table = self._focused_svc_table()
if table is not None and table.row_count:
try:
name = str(table.get_row_at(table.cursor_row)[0])
info = ALL_TARGETS.get(name)
if info:
return name, info
except Exception:
pass # fall through to list selection
if not self._rows:
return None
row = self._rows[self.selected_index]
return row.target_name, row.info
def action_launch_selected(self) -> None:
target = self._current_target()
if target is None:
return
name, info = target
self._launch_target(name, info)
def action_launch_autostart(self) -> None:
"""Trigger auto-start in a background thread (never blocks the event loop)."""
# Switch to log tab so user sees startup progress
self.action_show_log()
threading.Thread(target=self._autostart_worker, daemon=True, name="cosysim-autostart").start()
def action_launch_game(self) -> None:
"""Launch all game pillar targets."""
self._launch_pillar("game")
def action_launch_services(self) -> None:
"""Launch all service pillar targets."""
self._launch_pillar("service")
def action_launch_creation(self) -> None:
"""Launch all creation pillar targets."""
self._launch_pillar("creation")
def _launch_pillar(self, pillar: str) -> None:
"""Launch all targets in a pillar via background thread."""
self.action_show_log()
threading.Thread(
target=self._pillar_worker, args=(pillar,),
daemon=True, name=f"cosysim-{pillar}",
).start()
def _pillar_worker(self, pillar: str) -> None:
"""Worker: start all targets in the given pillar."""
target_ids = PILLAR_IDS.get(pillar, ())
self._log_ts(f"[{pillar}] launching {len(target_ids)} targets")
for tid in target_ids:
info = ALL_TARGETS.get(tid)
if not info:
continue
if _port_up(info["port"]):
self._log_ts(f"[{pillar}] {tid} already up")
continue
try:
self._start_one(tid, info)
self._log_ts(f"[{pillar}] started {tid}")
except Exception as exc:
self._log_ts(f"[{pillar}] FAILED {tid}: {exc}")
time.sleep(0.5)
time.sleep(5)
self.call_from_thread(self._refresh_all_status)
def _autostart_worker(self) -> None:
"""Worker: start all auto_start targets sequentially with stagger."""
import traceback as _tb
_dbg = open(PROJECT_ROOT / "tui_autostart.log", "w", buffering=1)
def dbg(msg: str) -> None:
_dbg.write(msg + "\n")
self._log_ts(msg)
dbg("[autostart] worker started")
try:
# v1.42.1 [2026-03-21] — Priority-sorted autostart (external deps first)
# Targets with start_priority=0 (e.g. Nexus KMS) launch before scenes
sorted_targets = sorted(
ALL_TARGETS.items(),
key=lambda kv: kv[1].get("start_priority", 50),
)
for name, info in sorted_targets:
if not info.get("auto_start"):
continue
port = info["port"]
label = info["label"]
dbg(f"[autostart] checking {name} ({label}) port={port}")
if _port_up(port):
dbg(f"[autostart] {name} already up")
continue
dbg(f"[autostart] starting {name} type={info['type']}")
try:
self._start_one(name, info)
dbg(f"[autostart] _start_one({name}) returned OK")
except Exception as exc:
dbg(f"[autostart] _start_one({name}) FAILED: {exc}\n{_tb.format_exc()}")
time.sleep(0.5)
# v1.51.0 [2026-03-22] — Start world daemons after services, before checking
dbg("[autostart] starting world infrastructure...")
for d_label, d_mod, d_getter, d_method in [
("WorldSim", "engine.world.world_sim", "get_world_sim", "start"),
("CrossSceneRelay","engine.events.cross_scene_relay", "get_cross_scene_relay", "start"),
("EventCascade", "engine.world.event_cascade", "get_event_cascade", "start"),
]:
try:
import importlib as _il
_m = _il.import_module(d_mod)
getattr(getattr(_m, d_getter)(), d_method)()
dbg(f"[autostart] {d_label} OK")
except Exception as _exc:
dbg(f"[autostart] {d_label}: {_exc}")
for d_label, d_mod, d_getter, d_setup in [
("Scheduler", "engine.nexus.scheduler_daemon", "get_scheduler_daemon", "start"),
("AutoLoop", "engine.nexus.auto_loop", "get_auto_loop", "register_tasks"),
("ConvSync", "engine.nexus.conversation_sync", "get_conversation_sync", "register_task"),
]:
try:
import importlib as _il
_m = _il.import_module(d_mod)
getattr(getattr(_m, d_getter)(), d_setup)()