-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickrobot_webui.py
More file actions
3042 lines (2699 loc) · 146 KB
/
Copy pathquickrobot_webui.py
File metadata and controls
3042 lines (2699 loc) · 146 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
# Copyright 2026 comchris quickrobot .de project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#!/usr/bin/env python3
"""Quickrobot v0.02 -- Minimal Web UI Server.
Flask app providing a lightweight web interface for the quickrobot LAN controller.
Binds to 0.0.0.0 (LAN accessible) for remote access from managed nodes.
Routes:
/webui/ Main dashboard with nav sidebar
/webui/hosts List of all managed hosts/nodes
/webui/engines List of all engine types
/webui/instances List of all instances
/webui/instances/<id> Instance detail page
/webui/nodes/<id> Node detail page
/api/<path> Reverse proxy to quickrobot API server
Usage:
python3 webui_server.py --port 8041
"""
import os
import argparse
import json
import socket
import sys
from datetime import datetime
from lib.qr_engine_ids import (
QR_DEFAULT_LOCALHOST,
QR_ENGINE_API_NAME, QR_ENGINE_LLAMA_SERVER, QR_ENGINE_LLAMA_RPC,
QR_ENGINE_LLAMA_SERVER_NAME, QR_ENGINE_LLAMA_RPC_NAME,
QR_ENGINE_MCP_NAME, QR_ENGINE_SCHEDULER_NAME, QR_ENGINE_SUBPROCESS_NAME,
QR_ENGINE_UNIVERSAL_NAME, QR_ENGINE_WEBUI, QR_ENGINE_WEBUI_NAME,
QR_FORBIDDEN_HOSTS,
_QR_NAV_DISPLAY_NAMES, _QR_NAV_LLAMA_NAMES, _QR_NAV_NO_CONFIG,
_QR_NAV_SHORT_ALIASES, _QR_NAV_SECTION_MAP, _QR_SYSTEM_NAMES,
_QR_EMPTY,
get_id_by_name, is_llamacpp_engine,
)
# Root guard — same as main process, refuse to run as root
if os.getuid() == 0:
print("this robot won't run as root", file=sys.stderr)
sys.exit(1)
from flask import Flask, request, Response, jsonify, redirect, url_for, render_template, send_from_directory
from markupsafe import Markup
from lib.lib_constants import DEFAULT_ANSIBLE_USER, VERSION, DEFAULT_TIMEZONE
from lib.qr_engine_registry import is_system_engine, get_engine_by_name, get_display_name
from qr_api.lib_nodes import find_system_instance as _find_sys_inst
from db.sqlite import pool
from db.adapters.configs import get_polling_intervals
import math
_project_root = os.path.dirname(os.path.abspath(__file__))
if _project_root not in sys.path:
sys.path.insert(0, _project_root)
app = Flask(__name__, template_folder='webui')
# Register Jinja2 template filters for badge rendering
def _format_bytes_py(bytes_val):
"""Format bytes to human-readable string (Jinja2 global)."""
if bytes_val is None or bytes_val == '':
return '\u2014'
try:
b = int(bytes_val)
except (ValueError, TypeError):
return '\u2014'
if b == 0:
return '0 B'
k = 1024
sizes = ['B', 'KB', 'MB']
i = min(int(math.log(b) / math.log(k)), len(sizes) - 1)
return '{:.1f} {}'.format(b / math.pow(k, i), sizes[i])
@app.context_processor
def utility_processor():
"""Make helper functions and global vars available in all templates."""
from flask import g
tz_name = getattr(g, "tz_name", DEFAULT_TIMEZONE)
app_status = get_app_status()
is_dev = app_status.get("data", {}).get("mode", "prod") == "dev"
# Extract instance summary for global status indicator
qr_data = app_status.get("data", {})
return dict(
status_badge=status_badge,
node_status_badge=node_status_badge,
system_badge=system_badge,
gpu_device_badge=gpu_device_badge,
version=VERSION,
tz_name=tz_name,
qr_is_dev=is_dev,
qr_status_global=qr_data.get("global_state", "idle"),
qr_status_rgb=qr_data.get("global_state_rgb", "rgb(255, 255, 255)"),
qr_status_counts_json=json.dumps(qr_data.get("instance_counts", {})),
qr_status_tooltip=qr_data.get("global_state_tooltip", ""),
formatBytes=_format_bytes_py,
)
@app.before_request
def _load_webui_timezone():
"""Read web_ui_timezone from engine_configs table directly (no API call).
Skips /api/v1/webui/config itself to avoid recursion.
Falls back to 'Europe/Berlin' if the DB is unavailable or the key is missing.
"""
from flask import g
if request.path == "/api/v1/webui/config":
return
if hasattr(g, "tz_name"):
return
# Engine ID for quickrobot-webui (system-managed)
_WEBUI_ENGINE_ID = QR_ENGINE_WEBUI
tz_name = DEFAULT_TIMEZONE
try:
with pool(os.path.join(os.getcwd(), "data", "quickrobot.db")) as conn:
row = conn.execute(
"SELECT value FROM engine_configs WHERE engine_type_id = ? AND key = ?",
(_WEBUI_ENGINE_ID, "web_ui_timezone"),
).fetchone()
if row and isinstance(row["value"], str) and row["value"].strip():
tz_name = row["value"]
except Exception:
pass # fallback stays as 'Europe/Berlin'
g.tz_name = tz_name
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
import json as _json
def _fromjson(s):
"""Parse a JSON string to Python object (for Jinja2 templates)."""
if isinstance(s, str):
return _json.loads(s)
return s
app.jinja_env.filters['fromjson'] = _fromjson
# Configuration — resolved at runtime from environment, no hardcoded defaults
def _resolve_api_base():
"""Resolve API base URL from environment or crash if not set."""
custom = os.environ.get("QR_API_BASE")
if custom:
return custom
host = os.environ.get("QUICKROBOT_API_HOST")
port = os.environ.get("QUICKROBOT_API_PORT")
if host and port:
return f"http://{host}:{port}/api/v1"
raise RuntimeError(
"API base URL not set: set QR_API_BASE env var, or define "
"QUICKROBOT_API_HOST + QUICKROBOT_API_PORT in .quickrobot.env"
)
CONFIG = {
"api_base": _resolve_api_base(),
}
# Load engine registry for is_system_engine() filtering
try:
_db_path_wui = os.path.join(os.getcwd(), "data", "quickrobot.db")
from lib.qr_engine_registry import load_and_verify_registry as _load_reg
_load_reg(_db_path_wui)
except Exception:
pass # Non-critical — will fall back gracefully
# ---------------------------------------------------------------------------
# API client helper
# ---------------------------------------------------------------------------
def api_get(path, params=None):
"""Fetch JSON data from the quickrobot API server.
Args:
path: API path (e.g., 'instances' for /api/v1/instances).
params: Optional query parameters dict.
Returns:
dict with API response, or None on error.
"""
import urllib.request
import urllib.error
url = f"{CONFIG['api_base']}/{path}"
if params:
qs = "&".join(f"{k}={v}" for k, v in params.items())
url += f"?{qs}"
try:
req = urllib.request.Request(url)
req.add_header("Accept", "application/json")
with urllib.request.urlopen(req, timeout=60) as resp:
import json
return json.loads(resp.read().decode())
except Exception as exc:
return {"error": str(exc)}
def api_post(path, data=None):
"""POST JSON data to the quickrobot API server.
Args:
path: API path (e.g., 'instances' for /api/v1/instances).
data: Dict of JSON body to send.
Returns:
dict with API response, or {"error": str} on failure.
"""
import urllib.request
import json as _json
url = f"{CONFIG['api_base']}/{path}"
body = _json.dumps(data).encode() if data else b'{}'
try:
req = urllib.request.Request(url, data=body, method="POST")
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
with urllib.request.urlopen(req, timeout=120) as resp:
return _json.loads(resp.read().decode())
except Exception as exc:
return {"error": str(exc)}
def api_delete(path):
"""DELETE a resource via the quickrobot API server.
Args:
path: API path (e.g., 'instances/5' for DELETE /api/v1/instances/5).
Returns:
dict with API response, or {"error": str} on failure.
"""
import urllib.request
import json as _json
url = f"{CONFIG['api_base']}/{path}"
try:
req = urllib.request.Request(url, method="DELETE")
req.add_header("Accept", "application/json")
with urllib.request.urlopen(req, timeout=120) as resp:
return _json.loads(resp.read().decode())
except Exception as exc:
return {"error": str(exc)}
# ---------------------------------------------------------------------------
# Jinja2 inline templates (rendered from strings)
# ---------------------------------------------------------------------------
BASE_LAYOUT = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quickrobot v0.02 -- {title}</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
display: flex; min-height: 100vh; background: #f5f5f5; color: #333; }}
/* Nav sidebar */
nav {{ width: 220px; background: #1a1a2e; color: #eee; padding: 0; flex-shrink: 0; }}
nav .nav-header {{ padding: 20px 16px; border-bottom: 1px solid #333; font-size: 1.1em; font-weight: bold; }}
nav .nav-header span {{ color: #4fc3f7; }}
nav ul {{ list-style: none; padding: 8px 0; }}
nav li a {{ display: block; padding: 10px 16px; color: #bbb; text-decoration: none;
border-left: 3px solid transparent; transition: all 0.2s; }}
nav li a:hover {{ background: #16213e; color: #fff; }}
nav li a.active {{ background: #16213e; color: #4fc3f7; border-left-color: #4fc3f7; }}
nav .nav-section-header {{ padding: 12px 16px 4px; font-size: 0.75em; text-transform: uppercase;
color: #666; letter-spacing: 1px; font-weight: 600; }}
/* Main content */
main {{ flex: 1; padding: 24px 32px; overflow-y: auto; }}
main h1 {{ font-size: 1.5em; margin-bottom: 16px; color: #1a1a2e; }}
main h2 {{ font-size: 1.2em; margin: 16px 0 8px; color: #333; }}
/* Tables */
table {{ width: 100%; border-collapse: collapse; background: #fff;
box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 16px; }}
th {{ text-align: left; padding: 10px 12px; background: #f8f9fa;
border-bottom: 2px solid #dee2e6; font-size: 0.85em; color: #666;
text-transform: uppercase; letter-spacing: 0.5px; }}
td {{ padding: 10px 12px; border-bottom: 1px solid #eee; font-size: 0.9em; }}
tr:hover td {{ background: #f0f7ff; }}
a.row-link {{ color: #4fc3f7; text-decoration: none; cursor: pointer; }}
a.row-link:hover {{ text-decoration: underline; }}
/* Status badges */
.badge {{ display: inline-block; padding: 2px 8px; border-radius: 10px;
font-size: 0.8em; font-weight: 600; }}
.badge-running {{ background: #d4edda; color: #155724; }}
.badge-stopped {{ background: #f8d7da; color: #721c24; }}
.badge-error {{ background: #fff3cd; color: #856404; }}
.badge-other {{ background: #e2e3e5; color: #383d41; }}
.badge-system {{ background: #cce5ff; color: #004085; }}
.badge-active {{ background: #d4edda; color: #155724; }}
.badge-unknown {{ background: #fff3cd; color: #856404; }}
.badge-failed {{ background: #f8d7da; color: #721c24; }}
/* Detail cards */
.detail-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px; margin-bottom: 16px; }}
.detail-card {{ background: #fff; border-radius: 6px; padding: 16px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1); }}
.detail-card label {{ font-size: 0.8em; color: #888; text-transform: uppercase; display: block; margin-bottom: 4px; }}
.detail-card value {{ font-size: 1.1em; font-weight: 600; color: #1a1a2e; }}
/* Log output */
.log-output {{ background: #1a1a2e; color: #d4d4d4; padding: 12px; border-radius: 6px;
font-family: 'Consolas', 'Monaco', monospace; font-size: 0.85em;
max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-all; }}
.log-line {{ line-height: 1.6; }}
.log-success {{ color: #4caf50; }}
.log-failed {{ color: #f44336; }}
.log-processing {{ color: #ff9800; }}
.log-received {{ color: #9e9e9e; }}
.ansible-log-deploy {{ color: #4caf50; }}
.ansible-log-failed {{ color: #f44336; }}
.ansible-log-validate {{ color: #2196f3; }}
.ansible-log-scan {{ color: #ff9800; }}
/* Action buttons */
.actions {{ margin: 12px 0; }}
.btn {{ display: inline-block; padding: 6px 16px; border: none; border-radius: 4px;
cursor: pointer; font-size: 0.85em; text-decoration: none; color: #fff; }}
.btn-primary {{ background: #4fc3f7; color: #1a1a2e; }}
.btn-danger {{ background: #f44336; }}
.btn-success {{ background: #4caf50; }}
.btn:hover {{ opacity: 0.85; }}
/* Create instance form */
.form-group {{ margin-bottom: 14px; }}
.form-group label {{ display: block; font-size: 0.85em; color: #666; margin-bottom: 4px; font-weight: 500; }}
.form-group input[type="text"], .form-group input[type="number"], .form-group select {{ width: 100%; padding: 7px 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 0.9em; }}
.form-group select:focus, .form-group input:focus {{ outline: none; border-color: #4fc3f7; box-shadow: 0 0 0 2px rgba(79,195,247,0.15); }}
.form-group small {{ display: block; color: #888; font-size: 0.8em; margin-top: 3px; }}
.form-row {{ display: flex; gap: 16px; }}
.form-row .form-group {{ flex: 1; }}
.form-actions {{ margin-top: 16px; display: flex; gap: 8px; }}
.engine-card {{ border: 2px solid #e0e0e0; border-radius: 6px; padding: 14px; cursor: pointer; transition: all 0.2s; margin-bottom: 8px; }}
.engine-card:hover {{ border-color: #4fc3f7; background: #f8fbff; }}
.engine-card.selected {{ border-color: #4fc3f7; background: #e8f4fd; }}
.engine-card-name {{ font-weight: 600; color: #1a1a2e; }}
.engine-card-desc {{ font-size: 0.85em; color: #666; margin-top: 2px; }}
.preview-panel {{ background: #1a1a2e; color: #d4d4d4; padding: 12px; border-radius: 6px; font-family: 'Consolas', 'Monaco', monospace; font-size: 0.85em; max-height: 300px; overflow-y: auto; white-space: pre-wrap; word-break: break-all; }}
.engine-fields {{ display: none; }}
.engine-fields.visible {{ display: block; }}
/* Back link */
.back-link {{ display: inline-block; margin-bottom: 16px; color: #4fc3f7;
text-decoration: none; font-size: 0.9em; }}
.back-link:hover {{ text-decoration: underline; }}
</style>
</head>
<body>
<nav>
<div class="nav-header"><span>Quickrobot</span> v0.02</div>
<ul>
<li><a href="/webui/" {dashboard}>Dashboard</a></li>
<li><a href="/webui/hosts" {hosts}>Hosts</a></li>
{engines_nav}
<li><a href="/webui/instances" {instances}>Instances</a></li>
<li><a href="/webui/ansible-logs" {logs}>Ansible Logs</a></li>
<li><a href="{{ tasks_href }}" {tasks}>Running Tasks</a></li>
</ul>
</nav>
<main>
{content}
</main>
</body>
</html>
"""
DASHBOARD_CONTENT = """\
<h1>Quickrobot v0.02 -- Dashboard</h1>
<div class="detail-grid">
<div class="detail-card">
<label>Total Nodes</label><value>{total_nodes}</value>
</div>
<div class="detail-card">
<label>Active Nodes</label><value>{active_nodes}</value>
</div>
<div class="detail-card">
<label>Total Instances</label><value>{total_instances}</value>
</div>
<div class="detail-card">
<label>Running Instances</label><value>{running_instances}</value>
</div>
<div class="detail-card">
<label>Engine Types</label><value>{engine_types_count}</value>
</div>
</div>
"""
TABLE_HEADER = """\
<table>
<thead><tr>{headers}</tr></thead>
<tbody>{rows}</tbody>
</table>
"""
# Engine config metadata: descriptions and input types per engine type
# Used by the generic engine config page renderer
ENGINE_CONFIG_META = {
"llama_rpc": {
"display_title": "LLAMA.cpp RPC Server Global Engine Config",
"fields": {
"base_port": {"description": "Default port for first instance on the remote Host"},
"binary_path": {"description": "Absolute path to ggml-rpc-server binary on remote host (e.g. /opt/quickrobot/llama.cpp/build/bin/ggml-rpc-server)"},
"default_timeout": {"description": "Default runtime to be used in seconds for the benchmark"},
"restart_policy": {"description": "Systemd unit restart policy (always/on-failure/no)"},
"start_on_boot": {"description": "Enable systemd unit on boot (true/false)"},
"skip_build": {"description": "Skip cmake rebuild during deploy if binary already exists on remote host"},
"polling_interval_local_sec": {"description": "Action log polling interval for local instances in seconds (minimum 10)"},
"polling_interval_remote_sec": {"description": "Action log polling interval for remote nodes in seconds (minimum 10)"},
"playbook_dir": {"description": "Subdirectory under playbooks/ for custom deploy/undeploy scripts (e.g. 'custom', 'llama')"},
},
"dropdowns": ["restart_policy", "start_on_boot", "skip_build"],
},
"iperf3": {
"display_title": "Iperf3 Global Engine Config",
"fields": {
"base_port": {"description": "Base port for iperf3 server instance allocation (range 9900-9904)"},
"restart_policy": {"description": "Systemd restart policy"},
"start_on_boot": {"description": "Enable systemd unit on boot (true/false)"},
"target_host": {"description": "Server hostname/IP for client mode (used as target_host in CLI)"},
"target_port": {"description": "Server port for client mode (used as target_port in CLI)"},
"polling_interval_local_sec": {"description": "Action log polling interval for local instances in seconds (minimum 10)"},
"polling_interval_remote_sec": {"description": "Action log polling interval for remote nodes in seconds (minimum 10)"},
},
"dropdowns": ["restart_policy", "start_on_boot"],
},
"llama_server": {
"display_title": "LLAMA.cpp Server Global Engine Config",
"fields": {
"base_port": {"description": "Default port for first instance on the remote Host"},
"binary_path": {"description": "Path to llama-server binary on remote Host"},
"model_root_path": {"description": "Root path searched by model scan playbook (default: /mnt/llama/gguf/models)"},
"restart_policy": {"description": "Systemd unit restart policy"},
"start_on_boot": {"description": "Enable systemd unit on boot"},
"skip_build": {"description": "Skip cmake rebuild if binary already exists"},
"polling_interval_local_sec": {"description": "Action log polling interval for local instances in seconds (minimum 10)"},
"polling_interval_remote_sec": {"description": "Action log polling interval for remote nodes in seconds (minimum 10)"},
"llama_seed": {"description": "Random seed value passed as LLAMA_ARG_SEED to llama-server (default: 1337)"},
"playbook_dir": {"description": "Subdirectory under playbooks/ for custom deploy/undeploy scripts (e.g. 'custom', 'llama')"},
},
"dropdowns": ["restart_policy", "start_on_boot", "skip_build"],
},
"quickrobot-api": {
"display_title": "Quickrobot API Service Global Config",
"fields": {
"db_path": {"description": "SQLite database file path", "input_type": "text", "editable": True},
"api_host": {"description": "API server bind address (from .quickrobot.env QUICKROBOT_API_HOST)", "input_type": "text", "editable": False},
"api_port": {"description": "API server port (from .quickrobot.env QUICKROBOT_API_PORT)", "input_type": "number", "editable": False},
"ansible_user": {"description": "SSH user for ansible (from .quickrobot.env QUICKROBOT_API_ANSIBLE_SSHUSER)", "input_type": "text", "editable": False},
"ansible_key_path": {"description": "Path to SSH private key for ansible (from .quickrobot.env QUICKROBOT_API_ANSIBLE_SSHKEY; empty=ssh-agent)", "input_type": "text", "editable": False},
"playbook_root_dir": {"description": "Playbook root directory (from .quickrobot.env QUICKROBOT_API_PLAYBOOKDIR)", "input_type": "text", "editable": False},
"ping_command": {"description": "Host reachability ping command template (from .quickrobot.env QUICKROBOT_API_PING_COMMAND)", "input_type": "text", "editable": False},
"ping_interval": {"description": "Host reachability check interval seconds (min 10, overrides .env QUICKROBOT_API_PING_INTERVAL)", "input_type": "number", "editable": True},
"polling_interval_local_sec": {"description": "Action log polling interval for local instances (sec, min 10)", "input_type": "number", "editable": True},
"polling_interval_remote_sec": {"description": "Action log polling interval for remote nodes (sec, min 10)", "input_type": "number", "editable": True},
"refresh_interval_default_sec": {"description": "Default auto-refresh interval for instance status polling (sec, min 10)", "input_type": "number", "editable": True},
},
"dropdowns": [],
"save_endpoint": "/api/v1/engine/quickrobot-api/config",
},
"quickrobot-mcp": {
"display_title": "Quickrobot MCP Server Global Engine Config",
"fields": {
"mcp_port": {"description": "MCP SSE server bind port"},
"mcp_autostart": {"description": "Auto-start MCP on API boot (false=manual start only)"},
"mcp_python_interpreter": {"description": "Python interpreter binary for MCP server subprocess (e.g. pipx venv python path; empty=auto-detect)", "input_type": "text", "editable": True},
"mcp_allow_reads": {"description": "Expose read-only tools (list_instances, list_nodes, etc.)"},
"mcp_allow_writes": {"description": "Expose write tools (create_instance, deploy, start, stop)"},
"mcp_allow_proxy": {"description": "Expose raw API proxy tool for direct path access"},
"mcp_detach": {"description": "Run MCP in detached process group (survives API death; false=attached, dies with API)"},
"polling_interval_local_sec": {"description": "Action log polling interval for local instances in seconds (minimum 10)"},
"polling_interval_remote_sec": {"description": "Action log polling interval for remote nodes in seconds (minimum 10)"},
"allow_reads": {"description": "Expose read-only tools (list_instances, list_nodes, etc.)", "input_type": "dropdown", "editable": True},
"allow_writes": {"description": "Expose write tools (create_instance, deploy, start, stop)", "input_type": "dropdown", "editable": True},
"allow_proxy": {"description": "Expose raw API proxy tool for direct path access", "input_type": "dropdown", "editable": True},
},
"dropdowns": ["mcp_autostart", "mcp_allow_reads", "mcp_allow_writes", "mcp_allow_proxy", "mcp_detach", "allow_reads", "allow_writes", "allow_proxy"],
"save_endpoint": "/api/v1/engines/quickrobot-mcp/settings",
},
"quickrobot-webui": {
"display_title": "Dry Nose Ape Control Interface",
"fields": {
"web_ui_timezone": {"description": "Display timezone (IANA TZ name)", "input_type": "select", "editable": True},
"webui_autostart": {"description": "Auto-start WebUI on API start (true/false)", "input_type": "dropdown", "editable": True},
"webui_detach": {"description": "Run WebUI in detached process group (survives API death)", "input_type": "dropdown", "editable": True},
"polling_interval_local_sec": {"description": "Polling interval for local instances (sec, min 10)", "input_type": "number", "editable": True},
"polling_interval_remote_sec": {"description": "Polling interval for remote nodes (sec, min 10)", "input_type": "number", "editable": True},
},
"dropdowns": ["webui_autostart", "webui_detach"],
"save_endpoint": "/api/v1/engines/quickrobot-webui/settings",
},
}
def get_app_status():
"""Fetch app-level status from main API (dev mode, version)."""
try:
return api_get("app/status")
except Exception:
return {}
def render_nav(active, engine_types=None):
"""Return nav dict and structured engines section data.
Args:
active: Current page identifier (dashboard/hosts/instances/logs).
engine_types: Optional list of engine type dicts from the API.
Returns:
tuple of (nav_dict, engines_nav_data) where engines_nav_data is a
list of section dicts {header, items} for use in Jinja2 templates.
"""
pages = ["dashboard", "hosts", "instances", "models", "logs", "tasks", "engines"]
nav = {p: ' class="active"' if p == active else "" for p in pages}
# Preserve query params on Tasks nav link so filters persist across navigation
_qs = request.query_string.decode() if request.query_string else ""
nav["tasks_href"] = "/webui/qr-tasks" + ("?" + _qs if _qs else "")
# Build engine sections: 3 groups (LLAMA.cpp, Misc, System)
llama_section = {"header": "LLAMA.cpp", "items": []}
misc_section = {"header": "Misc", "items": []}
system_section = {"header": "System", "items": []}
section_objs = {"llama": llama_section, "misc": misc_section, "system": system_section}
if engine_types and len(engine_types) > 0:
for et in engine_types:
et_name = et.get("name", "?")
# Skip short-name aliases — they'll render via their canonical long-name route
if et_name in _QR_NAV_SHORT_ALIASES:
continue
# Skip engines without a config nav item (from SSOT)
if et_name in _QR_NAV_NO_CONFIG:
continue
# Display name + suffix: LLaMA overrides first (explicit None check for empty string),
# then display-name dict, then registry fallback.
_llama_data = _QR_NAV_LLAMA_NAMES.get(et_name)
if _llama_data is not None:
_raw_display, _raw_suffix = _llama_data
et_display = "" if _raw_display == _QR_EMPTY else _raw_display
suffix = "" if _raw_suffix == _QR_EMPTY else " Config"
else:
et_display = _QR_NAV_DISPLAY_NAMES.get(et_name) or get_display_name(et_name)
suffix = "" if et_name in _QR_SYSTEM_NAMES or et_name == QR_ENGINE_SUBPROCESS_NAME else " Config"
caps = et.get("capabilities", {})
if isinstance(caps, str):
try:
import json as _j
caps = _j.loads(caps)
except Exception:
caps = {}
_section_key = _QR_NAV_SECTION_MAP.get(et_name, "system")
section = section_objs[_section_key]
has_presets = caps.get("supports_presets") if isinstance(caps, dict) else False
item = f'<li><a href="/webui/engine/{et_name}/config">{et_display}{suffix}</a></li>'
section["items"].append(item)
if has_presets:
preset_label = "Presets" if not et_display else f"{et_display} Presets"
section["items"].append(f'<li><a href="/webui/engine/{et_name}/presets">{preset_label}</a></li>')
# Models moved to top-level nav (no longer in a section)
if et_name == QR_ENGINE_LLAMA_SERVER_NAME:
misc_section["items"].append('<li><a href="/webui/benchmarks">Bench</a></li>')
llama_section["items"].append('<li><a href="/webui/rpccluster">Herd</a></li>')
# Static misc nav items
if "iperf3" in [e.get("name") for e in engine_types or []]:
misc_section["items"].append('<li><a href="/webui/iperf3">iperf;3</a></li>')
# Static LLAMA.cpp section items (merged pages)
if "llama_rpc" in [e.get("name") for e in engine_types or []]:
llama_section["items"].append('<li><a href="/webui/rpc">RPC</a></li>')
# Static system nav items (Tasks before Playbooks)
_tasks_qs = request.query_string.decode() if request.query_string else ""
_tasks_href = "/webui/qr-tasks" + ("?" + _tasks_qs if _tasks_qs else "")
system_section["items"].append(f'<li><a href="{_tasks_href}">Tasks</a></li>')
if "quickrobot-api" in [e.get("name") for e in engine_types or []] or \
"quickrobot-webui" in [e.get("name") for e in engine_types or []] or \
"quickrobot-mcp" in [e.get("name") for e in engine_types or []]:
system_section["items"].append('<li><a href="/webui/playbooks">Playbooks</a></li>')
engines_nav_data = []
for s in [llama_section, misc_section, system_section]:
if s["items"]:
engines_nav_data.append(s)
return nav, engines_nav_data
def get_engine_types():
"""Fetch engine types from the API for navigation display.
Returns:
list of engine type dicts, or empty list on error.
"""
data = api_get("engines")
if "error" in data:
return []
return data.get("items", [])
def status_badge(state):
"""Render a CSS badge for instance/node state.
Returns Markup-wrapped HTML so Jinja2 does not auto-escape it.
"""
# SSOT state -> (css_class, display_label) mapping
# All states covered here must also have a --badge-* CSS variable in base.html :root
_STATE_MAP = {
"running": ("badge-running", "running"),
"stopped": ("badge-stopped", "stopped"),
"error": ("badge-error", "error"),
# Transition states — all map to loading (blue) for visual consistency
"deploying": ("badge-loading", "deploying"),
"configuring": ("badge-loading", "configuring"),
"loading": ("badge-loading", "loading"),
"updating": ("badge-loading", "updating"),
"compiling": ("badge-loading", "compiling"),
"starting": ("badge-loading", "starting"),
"stopping": ("badge-loading", "stopping"),
# Terminal/specific states
"deployed": ("badge-success", "deployed"),
"build_error": ("badge-error", "build_error"),
"timeout": ("badge-other", "timeout"),
}
entry = _STATE_MAP.get(state)
if entry is not None:
cls, label = entry
return Markup(f'<span class="badge {cls}">{label}</span>')
# Unknown state — fall back to generic badge
return Markup(f'<span class="badge badge-other">{state}</span>')
def gpu_device_badge(device):
"""Render a color-coded badge for GPU device value."""
if not device or device == "none":
return Markup('<span style="color:#888;font-size:0.85em;">─</span>')
elif "Vulkan" in str(device):
return Markup(f'<span class="badge badge-loading" style="font-size:0.8em;">{device}</span>')
elif "CUDA" in str(device):
return Markup(f'<span class="badge badge-running" style="font-size:0.8em;">{device}</span>')
else:
return Markup(f'<span style="color:#888;font-size:0.85em;">{device}</span>')
def node_status_badge(status):
"""Render a CSS badge for node status.
Returns Markup-wrapped HTML so Jinja2 does not auto-escape it.
"""
if status == "active":
return Markup('<span class="badge badge-active">active</span>')
elif status == "unknown":
return Markup('<span class="badge badge-unknown">unknown</span>')
elif status == "failed":
return Markup('<span class="badge badge-failed">failed</span>')
else:
return Markup(f'<span class="badge badge-other">{status or "unknown"}</span>')
def system_badge(is_system):
"""Render a system-managed indicator.
Returns Markup-wrapped HTML so Jinja2 does not auto-escape it.
"""
if is_system:
return Markup(' <span class="badge badge-system">system</span>')
return ""
def make_html(title, nav_state, content, engine_types=None):
"""Wrap content in the base layout using Jinja2 template.
Args:
title: Page title string.
nav_state: Navigation state identifier (dashboard/hosts/instances/logs).
content: HTML content string (will be marked safe for render_template).
engine_types: Optional list of engine type dicts for nav display.
Returns:
Complete HTML page string.
"""
nav, engines_nav_data = render_nav(nav_state, engine_types)
return render_template('base.html',
title=title,
dashboard=nav["dashboard"],
hosts=nav["hosts"],
instances=nav["instances"],
logs=nav.get("logs", ""),
tasks=nav.get("tasks", ""),
engines_nav=engines_nav_data,
content=Markup(content),
)
# ---------------------------------------------------------------------------
# Cache control — prevent stale HTML on page requests
# ---------------------------------------------------------------------------
@app.after_request
def _set_page_headers(response):
"""Add no-cache headers to HTML page responses (not API/static)."""
if response.content_type and "text/html" in response.content_type:
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
# ---------------------------------------------------------------------------
# Static files (JS, CSS)
# ---------------------------------------------------------------------------
@app.route("/_static/<path:filename>")
def webui_static(filename):
"""Serve static files from the webui/ directory."""
return send_from_directory(_project_root + "/webui", filename)
# ---------------------------------------------------------------------------
# Page routes
# ---------------------------------------------------------------------------
@app.route("/")
def webui_root():
"""Root redirect to dashboard for health checks and direct visits."""
return redirect("/webui/", code=302)
@app.route("/webui/")
def webui_dashboard():
"""Main dashboard showing overview stats."""
data = api_get("")
if "error" in data:
content = f'<p style="color:#f44336;">API unavailable: {data["error"]}</p>'
eng_types = get_engine_types()
return make_html("Dashboard", "dashboard", content, engine_types=eng_types)
d = data.get("data", {})
content = render_template('dashboard.html',
total_nodes=d.get("total_nodes", 0),
active_nodes=d.get("active_nodes", 0),
total_instances=d.get("total_instances", 0),
running_instances=d.get("running_instances", 0),
engine_types_count=d.get("engine_types_count", 0),
)
eng_types = get_engine_types()
return make_html("Dashboard", "dashboard", content, engine_types=eng_types)
@app.route("/webui/hosts")
def webui_hosts():
"""List all managed nodes/hosts with client-side column sorting and actions."""
# Check URL param first, then cookie (set by JS on filter toggle), default to false
include_inactive = request.args.get("include_inactive", "false").lower() == "true"
if not include_inactive:
cookie_val = request.cookies.get("qr_hosts_show_inactive", "")
include_inactive = cookie_val.lower() == "true"
data = api_get("nodes?include_inactive=" + str(include_inactive).lower())
if "error" in data:
content = f'<p style="color:#f44336;">API unavailable: {data["error"]}</p>'
return make_html("Hosts", "hosts", content, engine_types=get_engine_types())
nodes = data.get("items", [])
# Count instances per node from all instances
inst_data = api_get("instances")
inst_counts = {}
compiling_instances = {} # node_id -> list of compiling instance names
if "error" not in inst_data:
for inst in inst_data.get("items", []):
nid = inst.get("node_id")
if nid:
inst_counts[nid] = inst_counts.get(nid, 0) + 1
# Track compiling instances per node for Build column
if inst.get("state") == "compiling" and nid:
if nid not in compiling_instances:
compiling_instances[nid] = []
compiling_instances[nid].append(inst.get("name", str(inst.get("id"))))
# Build state map from nodes data (node_build_state column)
build_states = {}
for n in nodes:
nid = n.get("id")
if nid:
build_states[nid] = {
"state": n.get("node_build_state", "idle"),
"compiling": compiling_instances.get(nid, []),
}
eng_types = get_engine_types()
nav, engines_nav = render_nav("hosts", eng_types)
content = render_template('hosts.html', nodes=nodes, instance_counts=inst_counts, build_states=build_states)
return render_template('base.html', title="Hosts", engines_nav=engines_nav, **nav, content=Markup(content))
@app.route("/webui/nodes/new", methods=["GET", "POST"])
def webui_nodes_new():
"""Add a new node page with form and validation."""
if request.method == "POST":
body, is_err = require_json() if False else (request.form, False)
name = body.get("name", "").strip()
hostname = body.get("hostname", "").strip()
ansible_user = body.get("ansible_user", "").strip() or DEFAULT_ANSIBLE_USER
ansible_key_path = body.get("ansible_key_path", "").strip() or ""
ssh_port = int(body.get("ssh_port", 22))
if not name or not hostname:
content = '<div style="color:#f44336;padding:12px;">Name and hostname are required.</div>'
return make_html("Add Node", "hosts", content, engine_types=get_engine_types())
# Step 1: Create node
create_data = {"name": name, "hostname": hostname, "ssh_port": ssh_port}
if ansible_user:
create_data["ansible_user"] = ansible_user
if ansible_key_path:
create_data["ansible_key_path"] = ansible_key_path
result = api_post("nodes", create_data)
if "error" in result:
content = f"""
<div style="color:#f44336;padding:12px;margin-bottom:12px;">Failed to create node: {result["error"]}</div>
<a href="/webui/nodes/new" style="color:#007bff;">Retry</a>"""
return make_html("Add Node", "hosts", content, engine_types=get_engine_types())
node_id = result.get("data", {}).get("id") or result.get("data", {}).get("node_id")
if not node_id:
content = f'<div style="color:#f44336;">Node created but ID unknown. <a href="/webui/hosts">Go to hosts</a></div>'
return make_html("Add Node", "hosts", content, engine_types=get_engine_types())
# Check for stale qr files on remote node
stale = result.get("data", {}).get("stale_files", {})
stale_warning = ""
if stale and stale.get("has_stale"):
total = stale.get("total", 0)
svc_list = "<br>".join(f" - {f}" for f in stale.get("service_files", []))
env_list = "<br>".join(f" - {f}" for f in stale.get("env_files", []))
stale_warning = f"""<div style="color:#856404;padding:12px;background:#fff3cd;border-radius:4px;margin-bottom:12px;">
<strong>⚠ {total} pre-existing qr file(s) found on this node:</strong><br>{svc_list}{env_list}
</div>"""
# Step 2: Run discovery (validation)
val_result = api_post(f"nodes/{node_id}/discover")
if "error" in val_result:
# Discover endpoint error — delete the node (not added)
api_delete(f"nodes/{node_id}")
content = f"""
<h1>Add Node</h1>
<p>Failed to reach <strong>{name}</strong> at {hostname}:</p>
<div style="color:#f44336;padding:12px;background:#fff3cd;border-radius:4px;margin-bottom:12px;">{val_result["error"]}</div>
<a href="/webui/nodes/new" style="color:#007bff;">Try again</a>"""
return make_html("Add Node", "hosts", content, engine_types=get_engine_types())
# Step 3: Check if discovery succeeded (active = reachable)
node_status = val_result.get("data", {}).get("status", "") or \
(api_get(f"nodes/{node_id}/status").get("data", {}).get("node_status", "") if isinstance(api_get(f"nodes/{node_id}/status"), dict) else "")
if node_status == "active":
return make_html("Add Node", "hosts",
f'{stale_warning}<p style="color:#28a745;padding:12px;">Node <strong>{name}</strong> added and validated successfully! <a href="/webui/hosts">Go to hosts</a></p>',
engine_types=get_engine_types())
# Discovery didn't succeed — delete the node (it's not reachable)
api_delete(f"nodes/{node_id}")
status_detail = val_result.get("data", {}).get("result", {}).get("plays", [{}])[0].get("play", {}).get("name", "") if isinstance(val_result.get("data", {}), dict) else ""
content = f"""
<h1>Add Node</h1>
<p><strong>{name}</strong> at {hostname} is not reachable.</p>
<div style="color:#f44336;padding:12px;background:#fff3cd;border-radius:4px;margin-bottom:12px;">
Cannot connect via SSH — the host was not added.<br>
Check that the hostname resolves and SSH (port {{ ssh_port }}) is accessible.
</div>
<a href="/webui/nodes/new" style="color:#007bff;">Try again with different hostname</a>"""
return make_html("Add Node", "hosts", content, engine_types=get_engine_types())
# GET: render form from template
nav, engines_nav = render_nav("hosts", get_engine_types())
return render_template('base.html', title="Add Node", engines_nav=engines_nav, **nav, content=Markup(render_template('nodes_new.html')))
@app.route("/webui/engines")
def webui_engines():
"""List all engine types."""
data = api_get("engines")
if "error" in data:
content = f'<p style="color:#f44336;">API unavailable: {data["error"]}</p>'
return make_html("Engines", "engines", content, engine_types=get_engine_types())
engines = data.get("items", [])
nav, engines_nav = render_nav("engines", get_engine_types())
content = render_template('engines.html', engines=engines)
return render_template('base.html', title="Engines", engines_nav=engines_nav, **nav, content=Markup(content))
@app.route("/webui/iperf3")
def webui_iperf3():
"""Merged iperf3 page: engine config + presets list on one page."""
data = api_get("engines")
eng_types = get_engine_types() if "error" not in data else []
nav, engines_nav = render_nav("instances", eng_types)
content = render_template('iperf3.html', **nav)
return render_template('base.html', title="Iperf3", engines_nav=engines_nav, **nav, content=Markup(content))
@app.route("/webui/rpc")
def webui_rpc():
"""Merged RPC page: engine config + presets list on one page."""
data = api_get("engines")
eng_types = get_engine_types() if "error" not in data else []
nav, engines_nav = render_nav("instances", eng_types)
content = render_template('rpc.html', **nav)
return render_template('base.html', title="RPC Server", engines_nav=engines_nav, **nav, content=Markup(content))
@app.route("/webui/models")
def webui_models():
"""Unified models page — single hub for all engine models."""
from flask import request as _request
params = {}
q = _request.args.get("q", "").strip()
if q:
params["q"] = q
engine = _request.args.get("engine", "").strip()
if engine:
params["engine"] = engine
data = api_get("models", params if params else None)
if "error" in data:
content = f'<p style="color:#f44336;">API unavailable: {data["error"]}</p>'
nav, engines_nav = render_nav("engines", get_engine_types())
return render_template('base.html', title="Models",
engines_nav=engines_nav, **nav, content=Markup(content))
models = data.get("items", [])
# Pre-format size strings for template
for m in models:
size = m.get("size_bytes", 0)
if size and isinstance(size, (int, float)):
if size >= 1024**3:
m["size_str"] = f"{size / (1024**3):.1f} GB"
elif size >= 1024**2:
m["size_str"] = f"{size / (1024**2):.1f} MB"
else:
m["size_str"] = f"{size} B"
else:
m["size_str"] = "N/A"
nodes_data = api_get("nodes")
nodes = nodes_data.get("items", []) if "error" not in nodes_data else []
nav, engines_nav = render_nav("engines", get_engine_types())
content = render_template('models.html', models=models, nodes=nodes)
return render_template('base.html', title="Models", engines_nav=engines_nav, **nav, content=Markup(content))
@app.route("/webui/models/<int:model_id>/edit")
def webui_model_edit(model_id):
"""Edit a model entry (global, not per-engine)."""
data = api_get(f"models/{model_id}")
if "error" in data or not data.get("data"):
content = f'<p style="color:#f44336;">Model {model_id} not found</p>'
nav, engines_nav = render_nav("engines", get_engine_types())
return render_template('base.html', title=f"Edit Model -- {model_id}",
engines_nav=engines_nav, **nav, content=Markup(content))
m = data["data"]
# Collect existing categories for datalist suggestions
all_models = api_get("models").get("items", [])
cats_set = set()
for other_m in all_models:
c = other_m.get("category")
if c:
cats_set.add(str(c))
categories = sorted(cats_set)
nav, engines_nav = render_nav("engines", get_engine_types())
content = render_template('models_edit.html', model=m, model_id=model_id, categories=categories)
return render_template('base.html', title=f"Edit Model -- {m.get('name', model_id)}",
engines_nav=engines_nav, **nav, content=Markup(content))
@app.route("/webui/models/create", methods=["GET"])
def webui_model_create():
"""Create a new global model entry."""
nav, engines_nav = render_nav("engines", get_engine_types())
# Collect existing categories for datalist suggestions
all_models = api_get("models").get("items", [])