-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
1300 lines (1119 loc) · 47.2 KB
/
dashboard.py
File metadata and controls
1300 lines (1119 loc) · 47.2 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
"""Terminal monitoring dashboard for llama.cpp Docker wrapper.
Single-process curses TUI with GPU monitoring, system stats, server logs,
model switching, and a management API. Uses only Python stdlib.
Called by start.sh after starting the container:
python3 dashboard.py --compose-file docker-compose.yml \
--model-name "Model Name" --models-conf models.conf \
--current-profile glm-flash-q4
Keyboard controls:
q = stop container & exit
r = stop container & return to start.sh menu
m = model picker (switch models)
Up/Down/PgUp/PgDn = scroll logs
Management API (port 8081):
GET /models — list available model profiles
GET /status — current model and server state
POST /switch — switch model: {"model": "profile-id"}
Exit codes:
0 = stop & exit
2 = stop & return to menu
"""
import argparse
import curses
import json
import os
import re
import subprocess
import sys
import threading
import time
import urllib.request
from collections import deque
from http.server import HTTPServer, BaseHTTPRequestHandler
MIN_WIDTH = 60
MIN_HEIGHT = 20
LOG_BUFFER_SIZE = 2000
API_PORT = 8081
ANSI_RE = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]')
# Color pair IDs
C_HEADER = 1
C_GREEN = 2
C_YELLOW = 3
C_RED = 4
C_BLUE = 5
C_DIM = 6
def strip_ansi(text):
"""Remove ANSI escape sequences from text."""
return ANSI_RE.sub('', text)
def ctx_label(ctx):
"""Format context size for display."""
if ctx >= 1024:
return f"{ctx // 1024}K ctx"
return f"{ctx} ctx"
# =============================================================================
# models.conf parser
# =============================================================================
class ModelProfile:
"""A model profile parsed from models.conf."""
__slots__ = ('id', 'name', 'description', 'speed', 'model', 'ctx_size',
'n_gpu_layers', 'fit', 'fit_target', 'extra_args', 'is_bench')
def __init__(self, profile_id):
self.id = profile_id
self.name = ""
self.description = ""
self.speed = ""
self.model = ""
self.ctx_size = ""
self.n_gpu_layers = ""
self.fit = ""
self.fit_target = ""
self.extra_args = ""
self.is_bench = profile_id.startswith("bench-")
def parse_models_conf(path):
"""Parse models.conf and return list of ModelProfile."""
profiles = []
current = None
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
# Section header
m = re.match(r'^\[([a-zA-Z0-9_-]+)\]$', line)
if m:
current = ModelProfile(m.group(1))
profiles.append(current)
continue
# Key=Value
if current and '=' in line:
key, _, value = line.partition('=')
key = key.strip()
value = value.strip()
if key == 'NAME':
current.name = value
elif key == 'DESCRIPTION':
current.description = value
elif key == 'SPEED':
current.speed = value
elif key == 'MODEL':
current.model = value
elif key == 'CTX_SIZE':
current.ctx_size = value
elif key == 'N_GPU_LAYERS':
current.n_gpu_layers = value
elif key == 'FIT':
current.fit = value
elif key == 'FIT_TARGET':
current.fit_target = value
elif key == 'EXTRA_ARGS':
current.extra_args = value
return profiles
# =============================================================================
# Management API
# =============================================================================
class APIHandler(BaseHTTPRequestHandler):
"""HTTP handler for the management API."""
# Reference to the Dashboard instance, set before server starts
dashboard = None
def log_message(self, format, *args):
"""Suppress default HTTP logging."""
pass
def _send_json(self, data, status=200):
body = json.dumps(data, indent=2).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == '/models':
self._handle_models()
elif self.path == '/status':
self._handle_status()
else:
self._send_json({'error': 'not found'}, 404)
def do_POST(self):
if self.path == '/switch':
self._handle_switch()
else:
self._send_json({'error': 'not found'}, 404)
def _handle_models(self):
db = self.dashboard
models = []
for p in db.profiles:
models.append({
'id': p.id,
'name': p.name,
'speed': p.speed,
'ctx_size': p.ctx_size,
'is_bench': p.is_bench,
'active': p.id == db.current_profile_id,
})
self._send_json({'models': models})
def _handle_status(self):
db = self.dashboard
self._send_json({
'model': db.current_profile_id or None,
'model_name': db.model_name,
'state': db.server_state,
'status': db.status_message,
})
def _handle_switch(self):
db = self.dashboard
try:
length = int(self.headers.get('Content-Length', 0))
body = json.loads(self.rfile.read(length)) if length else {}
except (json.JSONDecodeError, ValueError):
self._send_json({'error': 'invalid JSON'}, 400)
return
profile_id = body.get('model', '')
if not profile_id:
self._send_json({'error': 'missing "model" field'}, 400)
return
# Find profile
profile = None
for p in db.profiles:
if p.id == profile_id:
profile = p
break
if not profile:
self._send_json({'error': f'unknown model: {profile_id}'}, 404)
return
# Start switch
done_event = threading.Event()
success = db.switch_model(profile_id, done_event=done_event)
if not success:
self._send_json({
'error': 'switch already in progress',
'state': db.server_state,
}, 409)
return
# Wait for completion (with timeout)
done_event.wait(timeout=300)
self._send_json({
'success': db.server_state == 'running',
'model': db.current_profile_id,
'model_name': db.model_name,
'state': db.server_state,
})
# =============================================================================
# Dashboard
# =============================================================================
class Dashboard:
def __init__(self, compose_file, model_name, models_conf=None,
current_profile=None):
self.compose_file = compose_file
self.model_name = model_name
self.exit_code = 0
self.running = True
# Project paths (derived from compose file location)
self.project_dir = os.path.dirname(os.path.abspath(compose_file))
self.env_file = os.path.join(self.project_dir, '.env')
self.models_dir = os.path.join(self.project_dir, 'models')
# Model profiles
self.profiles = []
self.prod_profiles = []
self.bench_profiles = []
self.current_profile_id = current_profile
if models_conf and os.path.exists(models_conf):
self.profiles = parse_models_conf(models_conf)
self.prod_profiles = [p for p in self.profiles if not p.is_bench]
self.bench_profiles = [p for p in self.profiles if p.is_bench]
# Server state: idle, starting, running, stopping
self.server_state = "running" if model_name else "idle"
self.status_message = ""
self._switch_lock = threading.Lock()
# Picker state
self.show_picker = False
self.picker_page = "main" # "main" or "bench"
self.picker_sel = 0 # highlighted index in current picker list
# Shared data (protected by lock)
self.lock = threading.Lock()
self.log_lines = deque(maxlen=LOG_BUFFER_SIZE)
self.gpu_data = []
self.cpu_percent = 0
self.load_avg = ""
self.mem_total = 0
self.mem_used = 0
self.mem_actual = 0 # MemTotal - MemFree (includes file cache)
self.swap_total = 0
self.swap_used = 0
self.container_cpu = ""
self.container_mem_bytes = 0 # Container memory in MiB
self.container_mem_limit = 0 # Container memory limit in MiB
# Log scroll state
self.auto_follow = True
self.scroll_pos = 0
# CPU delta tracking
self._prev_cpu = None
# Subprocess handle for log streaming
self._log_proc = None
def run(self):
"""Start threads and curses UI. Returns exit code."""
log_t = threading.Thread(target=self._collect_logs, daemon=True)
data_t = threading.Thread(target=self._collect_data, daemon=True)
log_t.start()
data_t.start()
# Start API server if models are configured
if self.profiles:
api_t = threading.Thread(target=self._run_api_server, daemon=True)
api_t.start()
try:
curses.wrapper(self._ui_main)
except KeyboardInterrupt:
self.exit_code = 0
finally:
self.running = False
self._stop_log_collection()
return self.exit_code
# ── API Server ────────────────────────────────────────────────────────
def _run_api_server(self):
"""Run management API HTTP server in background thread."""
APIHandler.dashboard = self
try:
server = HTTPServer(('127.0.0.1', API_PORT), APIHandler)
server.timeout = 1
while self.running:
server.handle_request()
except OSError:
with self.lock:
self.log_lines.append(
f"(management API failed to start on port {API_PORT})")
# ── Model Switching ───────────────────────────────────────────────────
def switch_model(self, profile_id, done_event=None):
"""Switch to a different model profile. Thread-safe.
Returns True if switch was initiated, False if already switching.
If done_event is provided, it will be set when the switch completes.
"""
if not self._switch_lock.acquire(blocking=False):
return False
t = threading.Thread(
target=self._do_switch,
args=(profile_id, done_event),
daemon=True
)
t.start()
return True
def _do_switch(self, profile_id, done_event=None):
"""Perform the actual model switch. Runs in a background thread."""
try:
profile = None
for p in self.profiles:
if p.id == profile_id:
profile = p
break
if not profile:
self.status_message = f"Unknown profile: {profile_id}"
return
# Check model file exists
if profile.model:
model_path = os.path.join(self.models_dir, profile.model)
# For multi-part models, check the first file
if not os.path.exists(model_path):
self.status_message = f"Model not found: {profile.model}"
self.server_state = "idle"
return
# Stop current container (if running)
if self.server_state in ("running", "starting"):
self.server_state = "stopping"
self.status_message = "Stopping current model..."
self._stop_log_collection()
with self.lock:
self.log_lines.append(
f"--- Switching to {profile.name} ---")
subprocess.run(
["docker", "compose", "-f", self.compose_file, "down"],
capture_output=True, timeout=60
)
# Generate new .env
self._generate_env(profile)
# Start new container
self.server_state = "starting"
self.model_name = profile.name
self.current_profile_id = profile.id
self.status_message = f"Starting {profile.name}..."
subprocess.run(
["docker", "compose", "-f", self.compose_file, "up", "-d"],
capture_output=True, timeout=60
)
# Restart log collection
self._start_log_collection()
# Wait for health
self.status_message = f"Loading {profile.name}..."
healthy = self._wait_for_health(timeout=300)
if healthy:
self.server_state = "running"
self.status_message = ""
else:
self.server_state = "idle"
self.status_message = "Server failed to become healthy"
except subprocess.TimeoutExpired:
self.server_state = "idle"
self.status_message = "Timeout during switch"
except Exception as e:
self.server_state = "idle"
self.status_message = f"Switch failed: {e}"
finally:
self._switch_lock.release()
if done_event:
done_event.set()
def _generate_env(self, profile):
"""Generate .env file for a model profile."""
with open(self.env_file, 'w') as f:
f.write(f"# Generated by dashboard.py — {profile.name}\n")
f.write(f"# Section: [{profile.id}] from models.conf\n\n")
if profile.model:
f.write(f"MODEL={profile.model}\n")
if profile.ctx_size:
f.write(f"CTX_SIZE={profile.ctx_size}\n")
if profile.n_gpu_layers:
f.write(f"N_GPU_LAYERS={profile.n_gpu_layers}\n")
if profile.fit:
f.write(f"FIT={profile.fit}\n")
if profile.fit_target:
f.write(f"FIT_TARGET={profile.fit_target}\n")
if profile.extra_args:
f.write(f"EXTRA_ARGS={profile.extra_args}\n")
def _wait_for_health(self, timeout=300):
"""Poll /health endpoint until server is ready."""
url = "http://localhost:8080/health"
elapsed = 0
while elapsed < timeout and self.running:
try:
req = urllib.request.urlopen(url, timeout=3)
if req.status == 200:
return True
except Exception:
pass
time.sleep(2)
elapsed += 2
return False
def _stop_log_collection(self):
"""Terminate the current log collection process."""
if self._log_proc:
try:
self._log_proc.terminate()
self._log_proc.wait(timeout=5)
except (OSError, subprocess.TimeoutExpired):
try:
self._log_proc.kill()
except OSError:
pass
self._log_proc = None
def _start_log_collection(self):
"""Start a new log collection thread."""
self._stop_log_collection()
t = threading.Thread(target=self._collect_logs, daemon=True)
t.start()
# ── Curses UI ──────────────────────────────────────────────────────────
def _ui_main(self, stdscr):
curses.curs_set(0)
curses.use_default_colors()
self._init_colors()
stdscr.timeout(500)
while self.running:
height, width = stdscr.getmaxyx()
key = self._get_key(stdscr)
if key is not None:
if self.show_picker:
self._handle_picker_key(key)
elif not self._handle_key(key, height):
break
if height < MIN_HEIGHT or width < MIN_WIDTH:
self._draw_too_small(stdscr, height, width)
else:
self._draw(stdscr, height, width)
if self.show_picker:
self._draw_picker(stdscr, height, width)
try:
stdscr.refresh()
except curses.error:
pass
def _init_colors(self):
if not curses.has_colors():
return
curses.init_pair(C_HEADER, curses.COLOR_CYAN, -1)
curses.init_pair(C_GREEN, curses.COLOR_GREEN, -1)
curses.init_pair(C_YELLOW, curses.COLOR_YELLOW, -1)
curses.init_pair(C_RED, curses.COLOR_RED, -1)
curses.init_pair(C_BLUE, curses.COLOR_BLUE, -1)
curses.init_pair(C_DIM, curses.COLOR_WHITE, -1)
def _get_key(self, stdscr):
try:
key = stdscr.getch()
return key if key != -1 else None
except curses.error:
return None
def _handle_key(self, key, height):
"""Handle keypress in normal mode. Returns False to exit."""
if key in (ord('q'), ord('Q')):
self.exit_code = 0
self.running = False
return False
elif key in (ord('r'), ord('R')):
self.exit_code = 2
self.running = False
return False
elif key in (ord('m'), ord('M')):
if self.profiles and self.server_state in ('running', 'idle'):
self.show_picker = True
self.picker_page = "main"
self.picker_sel = 0
elif key == curses.KEY_UP:
self._scroll_up(1)
elif key == curses.KEY_DOWN:
self._scroll_down(1)
elif key == curses.KEY_PPAGE:
self._scroll_up(max(1, height // 3))
elif key == curses.KEY_NPAGE:
self._scroll_down(max(1, height // 3))
elif key == curses.KEY_HOME:
self.scroll_pos = 0
self.auto_follow = False
elif key == curses.KEY_END:
self.auto_follow = True
return True
def _handle_picker_key(self, key):
"""Handle keypress in model picker mode."""
if key == 27: # Esc
self.show_picker = False
return
profiles = (self.prod_profiles if self.picker_page == "main"
else self.bench_profiles)
# Arrow keys and Enter for navigation
if key == curses.KEY_UP:
self.picker_sel = max(0, self.picker_sel - 1)
return
elif key == curses.KEY_DOWN:
self.picker_sel = min(len(profiles) - 1, self.picker_sel + 1)
return
elif key in (10, 13, curses.KEY_ENTER): # Enter
if 0 <= self.picker_sel < len(profiles):
profile = profiles[self.picker_sel]
self.show_picker = False
if profile.id != self.current_profile_id:
self.switch_model(profile.id)
return
if self.picker_page == "main":
if key in (ord('b'), ord('B')) and self.bench_profiles:
self.picker_page = "bench"
self.picker_sel = 0
return
# Number keys for production models
if ord('1') <= key <= ord('9'):
idx = key - ord('1')
if idx < len(self.prod_profiles):
profile = self.prod_profiles[idx]
self.show_picker = False
if profile.id != self.current_profile_id:
self.switch_model(profile.id)
elif self.picker_page == "bench":
if key in (ord('r'), ord('R')):
self.picker_page = "main"
self.picker_sel = 0
return
# Number keys for bench profiles
if ord('1') <= key <= ord('9'):
idx = key - ord('1')
if idx < len(self.bench_profiles):
profile = self.bench_profiles[idx]
self.show_picker = False
if profile.id != self.current_profile_id:
self.switch_model(profile.id)
def _scroll_up(self, n):
self.auto_follow = False
self.scroll_pos = max(0, self.scroll_pos - n)
def _scroll_down(self, n):
with self.lock:
total = len(self.log_lines)
self.scroll_pos += n
# ── Drawing ────────────────────────────────────────────────────────────
def _safe_addstr(self, win, y, x, text, attr=0):
"""Write text to window, silently ignoring out-of-bounds errors."""
try:
max_y, max_x = win.getmaxyx()
if y < 0 or y >= max_y or x < 0 or x >= max_x:
return
win.addnstr(y, x, str(text), max_x - x, attr)
except curses.error:
pass
def _draw_bar(self, win, y, x, width, percent, color_pair):
"""Draw a colored progress bar without the percentage label."""
if width <= 0:
return
filled = max(0, min(width, int(percent * width / 100)))
empty = width - filled
try:
max_y, max_x = win.getmaxyx()
if y >= max_y or x >= max_x:
return
avail = max_x - x
if avail <= 0:
return
bar_f = "#" * min(filled, avail)
win.addnstr(y, x, bar_f, avail,
curses.color_pair(color_pair) | curses.A_BOLD)
if filled < avail:
bar_e = "-" * min(empty, avail - filled)
win.addnstr(bar_e, avail - filled, curses.A_DIM)
except curses.error:
pass
def _vram_color(self, percent):
if percent >= 90:
return C_RED
elif percent >= 70:
return C_YELLOW
return C_GREEN
def _draw_too_small(self, stdscr, height, width):
stdscr.erase()
msg = f"Terminal too small ({width}x{height}). Need {MIN_WIDTH}x{MIN_HEIGHT}."
y = height // 2
x = max(0, (width - len(msg)) // 2)
self._safe_addstr(stdscr, y, x, msg)
def _draw(self, stdscr, height, width):
stdscr.erase()
# Panel sizes
log_h = max(5, int(height * 0.55))
ctrl_h = max(4, min(7, int(height * 0.12)))
mid_h = max(5, height - log_h - ctrl_h - 2)
mid_split = width // 2
# Logs (top)
self._draw_logs_panel(stdscr, 0, 0, log_h, width)
self._draw_hline(stdscr, log_h, width)
# GPU (middle-left) and System (middle-right)
self._draw_gpu_panel(stdscr, log_h + 1, 0, mid_h, mid_split)
self._draw_vline(stdscr, log_h + 1, mid_split, mid_h)
self._draw_sys_panel(stdscr, log_h + 1, mid_split + 1, mid_h,
width - mid_split - 1)
self._draw_hline(stdscr, log_h + 1 + mid_h, width)
# Control bar (bottom)
self._draw_ctrl_panel(stdscr, log_h + 2 + mid_h, 0, ctrl_h, width)
def _draw_hline(self, stdscr, y, width):
try:
stdscr.hline(y, 0, curses.ACS_HLINE, width)
except curses.error:
pass
def _draw_vline(self, stdscr, y, x, height):
try:
stdscr.vline(y, x, curses.ACS_VLINE, height)
except curses.error:
pass
# ── Log Panel ──────────────────────────────────────────────────────────
def _draw_logs_panel(self, stdscr, y, x, height, width):
header = " === Server Logs === "
self._safe_addstr(stdscr, y, x, header,
curses.color_pair(C_HEADER) | curses.A_BOLD)
# Status message (right-aligned in header)
if self.status_message:
if self.server_state in ('starting', 'stopping'):
status_color = C_YELLOW
else:
status_color = C_RED
status_text = f" {self.status_message} "
status_x = width - len(status_text) - 1
if status_x > len(header):
self._safe_addstr(stdscr, y, status_x, status_text,
curses.color_pair(status_color) | curses.A_BOLD)
with self.lock:
lines = list(self.log_lines)
total = len(lines)
view_h = height - 1
if self.auto_follow:
start = max(0, total - view_h)
self.scroll_pos = start
else:
start = max(0, min(self.scroll_pos, max(0, total - view_h)))
self.scroll_pos = start
if total > 0 and start >= total - view_h:
self.auto_follow = True
if not self.auto_follow and total > view_h:
end_line = min(start + view_h, total)
hint = f" [{start + 1}-{end_line}/{total}] "
hint_x = width - len(hint) - 1
if hint_x > len(header):
self._safe_addstr(stdscr, y, hint_x, hint, curses.A_DIM)
for i in range(view_h):
idx = start + i
row = y + 1 + i
if idx < total:
line = strip_ansi(lines[idx])
if '|' in line[:40]:
line = line.split('|', 1)[1].lstrip()
self._safe_addstr(stdscr, row, x, line[:width])
# ── GPU Panel ──────────────────────────────────────────────────────────
def _draw_gpu_panel(self, stdscr, y, x, height, width):
self._safe_addstr(stdscr, y, x + 1, " === GPU Monitor === ",
curses.color_pair(C_HEADER) | curses.A_BOLD)
with self.lock:
gpus = list(self.gpu_data)
if not gpus:
self._safe_addstr(stdscr, y + 2, x + 2,
"Waiting for GPU data...", curses.A_DIM)
return
row = y + 2
for gpu in gpus:
if row >= y + height - 1:
break
mem_pct = 0
if gpu['mem_total'] > 0:
mem_pct = int(gpu['mem_used'] * 100 / gpu['mem_total'])
self._safe_addstr(stdscr, row, x + 2,
f"GPU {gpu['index']}: {gpu['name']}",
curses.A_BOLD)
row += 1
if row < y + height:
self._safe_addstr(stdscr, row, x + 4,
f"VRAM: {gpu['mem_used']}/{gpu['mem_total']} MiB")
row += 1
if row < y + height:
bar_w = min(20, width - 10)
self._draw_bar(stdscr, row, x + 4, bar_w, mem_pct,
self._vram_color(mem_pct))
self._safe_addstr(stdscr, row, x + 4 + bar_w + 1,
f"{mem_pct}%")
row += 1
if row < y + height:
self._safe_addstr(
stdscr, row, x + 4,
f"Util: {gpu['util']}% Power: {gpu['power_draw']}W/{gpu['power_limit']}W")
row += 1
if row < y + height:
self._safe_addstr(stdscr, row, x + 4,
f"Temp: {gpu['temp']}\u00b0C")
row += 1
row += 1 # blank line between GPUs
# ── System Panel ───────────────────────────────────────────────────────
def _draw_sys_panel(self, stdscr, y, x, height, width):
self._safe_addstr(stdscr, y, x + 1, " === System === ",
curses.color_pair(C_HEADER) | curses.A_BOLD)
with self.lock:
cpu_pct = self.cpu_percent
load = self.load_avg
mem_t = self.mem_total
mem_u = self.mem_used
mem_a = self.mem_actual
swap_t = self.swap_total
swap_u = self.swap_used
ccpu = self.container_cpu
cmem_b = self.container_mem_bytes
cmem_l = self.container_mem_limit
row = y + 2
self._safe_addstr(stdscr, row, x + 2, f"CPU: {cpu_pct}%")
row += 1
self._safe_addstr(stdscr, row, x + 2, f"Load: {load}")
row += 2
# RAM — show total actual usage with bar, then breakdown
actual_pct = int(mem_a * 100 / mem_t) if mem_t > 0 else 0
actual_gb = mem_a / 1024
total_gb = mem_t / 1024
self._safe_addstr(stdscr, row, x + 2,
f"RAM: {actual_gb:.1f} / {total_gb:.0f} GiB used")
row += 1
if row < y + height:
bar_w = min(20, width - 6)
# Color: green < 70%, yellow 70-85%, red > 85%
bar_color = C_GREEN if actual_pct < 70 else (
C_YELLOW if actual_pct < 85 else C_RED)
self._draw_bar(stdscr, row, x + 2, bar_w, actual_pct, bar_color)
self._safe_addstr(stdscr, row, x + 2 + bar_w + 1,
f"{actual_pct}%")
row += 1
# Breakdown: OS vs Container
if row < y + height:
os_mib = max(0, mem_a - cmem_b) if cmem_b > 0 else mem_u
os_gb = os_mib / 1024
cmem_gb = cmem_b / 1024
# model cache = container total - programs-only portion
# programs-only ~ mem_used (reclaimable view)
cache_gb = max(0, cmem_gb - mem_u / 1024)
prog_gb = cmem_gb - cache_gb
if cmem_b > 0:
self._safe_addstr(stdscr, row, x + 4,
f"OS: {os_gb:.1f}G"
f" Model: {prog_gb:.1f}G"
f"+{cache_gb:.1f}G cache")
else:
self._safe_addstr(stdscr, row, x + 4,
f"(container not running)")
row += 1
# Swap — only show if swap is being used
if row < y + height:
if swap_u > 100: # only show if >100 MiB used
swap_gb = swap_u / 1024
swap_color = (curses.color_pair(C_YELLOW) if swap_u < 4096
else curses.color_pair(C_RED))
self._safe_addstr(stdscr, row, x + 2,
f"Swap: {swap_gb:.1f} GiB on disk",
swap_color)
else:
self._safe_addstr(stdscr, row, x + 2,
"Swap: none", curses.A_DIM)
row += 1
# Free RAM
if row < y + height:
free_gb = (mem_t - mem_a) / 1024
self._safe_addstr(stdscr, row, x + 2,
f"Free: {free_gb:.1f} GiB",
curses.A_DIM)
# ── Control Bar ────────────────────────────────────────────────────────
def _draw_ctrl_panel(self, stdscr, y, x, height, width):
row = y
# Model name + state
self._safe_addstr(stdscr, row, x + 1, "Model: ", curses.A_BOLD)
self._safe_addstr(stdscr, row, x + 8, self.model_name)
state_str = ""
state_color = C_DIM
if self.server_state == "running":
state_str = " [running]"
state_color = C_GREEN
elif self.server_state == "starting":
state_str = " [starting...]"
state_color = C_YELLOW
elif self.server_state == "stopping":
state_str = " [stopping...]"
state_color = C_YELLOW
elif self.server_state == "idle":
state_str = " [idle]"
state_color = C_DIM
model_end = x + 8 + len(self.model_name)
self._safe_addstr(stdscr, row, model_end, state_str,
curses.color_pair(state_color))
row += 1
if row < y + height:
self._safe_addstr(stdscr, row, x + 1, "Web: ", curses.A_BOLD)
self._safe_addstr(stdscr, row, x + 6, "http://localhost:8080")
row += 1
if row < y + height:
self._safe_addstr(stdscr, row, x + 1, "API: ", curses.A_BOLD)
self._safe_addstr(stdscr, row, x + 6,
"http://localhost:8080/v1/chat/completions")
mgmt_x = max(52, width // 2)
self._safe_addstr(stdscr, row, mgmt_x, "Mgmt: ", curses.A_BOLD)
self._safe_addstr(stdscr, row, mgmt_x + 6,
f"http://localhost:{API_PORT}")
row += 2
if row < y + height:
self._safe_addstr(stdscr, row, x + 1, "[q]",
curses.color_pair(C_YELLOW) | curses.A_BOLD)
self._safe_addstr(stdscr, row, x + 5, "Exit")
self._safe_addstr(stdscr, row, x + 12, "[r]",
curses.color_pair(C_YELLOW) | curses.A_BOLD)
self._safe_addstr(stdscr, row, x + 16, "Menu")
if self.profiles:
self._safe_addstr(stdscr, row, x + 23, "[m]",
curses.color_pair(C_YELLOW) | curses.A_BOLD)
self._safe_addstr(stdscr, row, x + 27, "Switch model")
scroll_x = max(43, width // 2)
self._safe_addstr(stdscr, row, scroll_x, "[",
curses.color_pair(C_YELLOW) | curses.A_BOLD)
self._safe_addstr(stdscr, row, scroll_x + 1, "Up/Dn PgUp/Dn",
curses.color_pair(C_YELLOW) | curses.A_BOLD)
self._safe_addstr(stdscr, row, scroll_x + 15, "]",
curses.color_pair(C_YELLOW) | curses.A_BOLD)
self._safe_addstr(stdscr, row, scroll_x + 17, "Scroll")
# ── Model Picker Overlay ──────────────────────────────────────────────
def _draw_picker(self, stdscr, height, width):
"""Draw model picker overlay centered on screen."""
if self.picker_page == "bench":
profiles = self.bench_profiles
title = "Benchmark Profiles"
footer_hint = "Up/Dn Enter [1-9] [r] Back [Esc] Cancel"
else:
profiles = self.prod_profiles
title = "Switch Model"
if self.bench_profiles:
footer_hint = "Up/Dn Enter [1-9] [b] Benchmarks [Esc] Cancel"
else:
footer_hint = "Up/Dn Enter [1-9] [Esc] Cancel"
if not profiles:
return
# Calculate widest line for overlay width
max_line_len = max(len(title), len(footer_hint))
for i, p in enumerate(profiles):
line_len = len(f" {i+1}) {p.name}")
if p.speed:
line_len += len(f" {p.speed}")
if p.ctx_size:
try:
line_len += len(f" {ctx_label(int(p.ctx_size))}")
except ValueError:
pass
if p.id == self.current_profile_id:
line_len += 3 # " *"
max_line_len = max(max_line_len, line_len)
# Overlay dimensions
overlay_w = min(max_line_len + 6, width - 4)
n_items = len(profiles)
has_bench_link = (self.picker_page == "main" and self.bench_profiles)
# rows: border(1) + title(1) + blank(1) + items(N) + [bench_link(2)] + blank(1) + footer(1) + border(1)
overlay_h = n_items + 6 + (2 if has_bench_link else 0)
overlay_h = min(overlay_h, height - 2)
overlay_y = max(0, (height - overlay_h) // 2)
overlay_x = max(0, (width - overlay_w) // 2)