app.js
58.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
// U-008: hash-based client-side router (no History API / server catch-all
// needed). U-022 adds the first real page, #/setup (v_project_setup, 02-V
// §2.1); U-023 adds #/goals/new and #/bugs/new; U-025 adds the real #/
// (v_dashboard), #/tasks (v_task_board), #/tasks/:task_id (v_task_detail).
// 02-V's console has no multi-project switcher UI (decision 2), but
// c_task_create/c_bug_report_create both require project_id (03-C §3.1;
// §3.1.1 doesn't list it, but needs it too -- see bug_record.py's
// create_bug_report docstring). Until v_dashboard carries "current project"
// state through some richer UI, the id picked/created in v_project_setup is
// stashed here and read back by the pages that need it.
const CURRENT_PROJECT_KEY = "graphlemon_project_id";
function getCurrentProjectId() {
return localStorage.getItem(CURRENT_PROJECT_KEY);
}
function setCurrentProjectId(projectId) {
localStorage.setItem(CURRENT_PROJECT_KEY, projectId);
}
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text == null ? "" : String(text);
return div.innerHTML;
}
// c_ws_subscribe (03-C §3.14, U-024): opens a live event feed for a project
// (optionally scoped to one task_id) and auto-reconnects on drop -- 02-V
// §2.2's "实时连接已断开,正在重连" exception state. REQ-12's deeper
// reconnect-catch-up semantics are U-024.5's job (03-C §3.14 itself routes
// that through REST snapshots, not WS replay); this only re-opens the
// socket and reports connection status back to the caller.
function connectEventSocket(projectId, taskId, { onEvent, onStatusChange }) {
const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
let url = wsProtocol + "//" + window.location.host + "/api/ws/projects/" + encodeURIComponent(projectId);
if (taskId) url += "?task_id=" + encodeURIComponent(taskId);
let closedByCaller = false;
let socket = null;
function open() {
socket = new WebSocket(url);
socket.onopen = () => onStatusChange("connected");
socket.onmessage = (event) => onEvent(JSON.parse(event.data));
socket.onclose = () => {
if (closedByCaller) return;
onStatusChange("disconnected");
setTimeout(open, 2000);
};
socket.onerror = () => socket.close();
}
open();
return {
close: () => {
closedByCaller = true;
if (socket) socket.close();
},
};
}
// c_ws_log_tail (03-C §3.6.2, U-027): live tail for one Work Node's raw log.
// No auto-reconnect here, unlike connectEventSocket -- 03-C is explicit that
// the server closes this connection on purpose once the node reaches a
// terminal status, and the caller (mountLogViewer) is expected to switch to
// c_execution_log_get's static mode on close, not treat it as a dropped
// connection to retry.
function connectLogTailSocket(nodeExecId, { onChunk, onClose }) {
const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const url = wsProtocol + "//" + window.location.host + "/api/ws/work-nodes/" + encodeURIComponent(nodeExecId) + "/log";
const socket = new WebSocket(url);
socket.onmessage = (event) => onChunk(JSON.parse(event.data).appended_content);
socket.onclose = () => onClose();
socket.onerror = () => socket.close();
return { close: () => socket.close() };
}
const routes = {
"#/": { render: renderDashboard, mount: mountDashboard },
"#/tasks": { render: renderTaskBoard, mount: mountTaskBoard },
"#/artifacts": { render: renderArtifactBrowser, mount: mountArtifactBrowser },
"#/skills": { render: renderSkillLibrary, mount: mountSkillLibrary },
"#/settings/concurrency": { render: renderConcurrencySettings, mount: mountConcurrencySettings },
"#/settings/budget": { render: renderBudgetSettings, mount: mountBudgetSettings },
"#/settings/log-retention": { render: renderLogRetentionSettings, mount: mountLogRetentionSettings },
"#/setup": { render: renderProjectSetup, mount: mountProjectSetup },
"#/goals/new": { render: renderGoalComposer, mount: mountGoalComposer },
"#/bugs/new": { render: renderBugFeedback, mount: mountBugFeedback },
};
// #/tasks/:task_id (v_task_detail) and #/skills/:skill_id/audit
// (v_skill_audit_log) are the only dynamic routes -- not worth a full
// path-matching router for two patterns.
const TASK_DETAIL_RE = /^#\/tasks\/([^/]+)$/;
const SKILL_AUDIT_RE = /^#\/skills\/([^/]+)\/audit$/;
let currentRouteCleanup = null;
function registerRouteCleanup(fn) {
currentRouteCleanup = fn;
}
function render() {
if (currentRouteCleanup) {
currentRouteCleanup();
currentRouteCleanup = null;
}
const hash = window.location.hash || "#/";
let route = routes[hash];
let routeArgs = [];
if (!route) {
const taskMatch = hash.match(TASK_DETAIL_RE);
const skillMatch = hash.match(SKILL_AUDIT_RE);
if (taskMatch) {
route = { render: renderTaskDetail, mount: mountTaskDetail };
routeArgs = [taskMatch[1]];
} else if (skillMatch) {
route = { render: renderSkillAuditLog, mount: mountSkillAuditLog };
routeArgs = [skillMatch[1]];
}
}
if (!route) route = { render: () => "<h1>Not found</h1><p>" + hash + "</p>" };
document.getElementById("app").innerHTML = route.render(...routeArgs);
if (route.mount) route.mount(...routeArgs);
for (const a of document.querySelectorAll("#nav a")) {
a.classList.toggle("active", a.getAttribute("href") === hash);
}
}
window.addEventListener("hashchange", render);
window.addEventListener("DOMContentLoaded", render);
// ---- v_project_setup (02-V §2.1): create/switch project ----
function renderProjectSetup() {
return `
<div class="top-back"><a href="#/">← 返回仪表盘</a></div>
<div class="page">
<h1>创建 / 切换项目</h1>
<div class="page-sub">选择一个本地文件夹作为目标项目的代码空间</div>
<div class="panel">
<div id="setup_error" class="error-banner" style="display:none;"></div>
<div class="field">
<label>目标文件夹(folder_path)</label>
<input type="text" id="folder_path" readonly value="">
<div class="hint" id="folder_path_hint">点击"选择文件夹"会由后端代为弹出系统原生对话框,不支持手动输入路径(除非返回 DIALOG_UNAVAILABLE)</div>
</div>
<button class="btn" id="btn_pick_folder" type="button">📁 选择文件夹</button>
<div class="field" style="margin-top:20px;">
<label>项目名称(project_name,非必填)</label>
<input type="text" id="project_name" placeholder="留空则取文件夹名">
</div>
<div class="btn-row">
<button class="btn btn-primary" id="btn_create" type="button">创建项目</button>
</div>
<div class="confirm-banner" id="confirm_banner" style="display:none;">
该文件夹还不是 Git 仓库,是否代为初始化(<code>git init</code>)?确认前不写入任何文件。
<div class="btn-row" style="margin-top:10px;">
<button class="btn" id="btn_cancel_init" type="button">取消</button>
<button class="btn btn-primary" id="btn_confirm_init" type="button">确认初始化并创建项目</button>
</div>
</div>
</div>
</div>
`;
}
function mountProjectSetup() {
const folderInput = document.getElementById("folder_path");
const folderHint = document.getElementById("folder_path_hint");
const nameInput = document.getElementById("project_name");
const errorBox = document.getElementById("setup_error");
const confirmBanner = document.getElementById("confirm_banner");
function showError(message) {
errorBox.textContent = message;
errorBox.style.display = "block";
}
function clearError() {
errorBox.style.display = "none";
}
document.getElementById("btn_pick_folder").addEventListener("click", async () => {
clearError();
const resp = await fetch("/api/system/pick-folder", { method: "POST", body: "{}" });
const body = await resp.json();
if (resp.status === 422 && body.error === "DIALOG_UNAVAILABLE") {
folderInput.removeAttribute("readonly");
folderHint.textContent = "当前环境不支持弹窗选择,请手动输入路径";
return;
}
if (body.selected_path) {
folderInput.value = body.selected_path;
}
// user canceled the native dialog -> folder_path stays as it was (02-V §2.1)
});
async function createProject(initGitIfMissing) {
clearError();
confirmBanner.style.display = "none";
const folderPath = folderInput.value.trim();
if (!folderPath) {
showError("请先选择目标文件夹");
return;
}
const resp = await fetch("/api/projects", {
method: "POST",
body: JSON.stringify({
target_folder_path: folderPath,
name: nameInput.value.trim() || undefined,
init_git_if_missing: initGitIfMissing,
}),
});
const body = await resp.json();
if (resp.status === 200) {
setCurrentProjectId(body.project_id);
window.location.hash = "#/";
return;
}
if (body.error === "GIT_INIT_DECLINED") {
confirmBanner.style.display = "block";
return;
}
showError(body.error + (body.detail ? ":" + body.detail : ""));
}
document.getElementById("btn_create").addEventListener("click", () => createProject(false));
document.getElementById("btn_confirm_init").addEventListener("click", () => createProject(true));
document.getElementById("btn_cancel_init").addEventListener("click", () => {
confirmBanner.style.display = "none";
});
}
// ---- shared: pages that need a "current project" to already exist ----
function renderNoProjectSelected() {
return `
<div class="page">
<div class="error-banner" style="display:block;">
还没有选择项目。请先<a href="#/setup">创建或切换项目</a>。
</div>
</div>
`;
}
// ---- v_goal_composer (02-V §2.3): propose a new goal ----
const GOAL_TEXT_MAX_LEN = 4000;
function renderGoalComposer() {
if (!getCurrentProjectId()) return renderNoProjectSelected();
return `
<div class="top-back"><a href="#/">← 返回仪表盘</a></div>
<div class="page">
<h1>提出新目标</h1>
<div class="page-sub">用自然语言描述你想让 graphlemon 完成的目标</div>
<div class="panel">
<div id="goal_error" class="error-banner" style="display:none;"></div>
<div class="field" id="goal_form">
<label>目标描述(goal_text,必填,最长 ${GOAL_TEXT_MAX_LEN} 字)</label>
<textarea id="goal_text" rows="6" maxlength="${GOAL_TEXT_MAX_LEN}"></textarea>
<div class="btn-row">
<button class="btn btn-primary" id="btn_submit_goal" type="button">创建任务</button>
</div>
</div>
<div class="confirm-banner" id="goal_confirm_banner" style="display:none;">
<div id="goal_confirm_summary"></div>
<div class="btn-row" style="margin-top:10px;">
<button class="btn" id="btn_edit_goal" type="button">返回编辑</button>
<button class="btn btn-primary" id="btn_confirm_goal" type="button">确认创建</button>
</div>
</div>
</div>
</div>
`;
}
function mountGoalComposer() {
if (!getCurrentProjectId()) return;
const textArea = document.getElementById("goal_text");
const errorBox = document.getElementById("goal_error");
const form = document.getElementById("goal_form");
const confirmBanner = document.getElementById("goal_confirm_banner");
const confirmSummary = document.getElementById("goal_confirm_summary");
document.getElementById("btn_submit_goal").addEventListener("click", () => {
errorBox.style.display = "none";
const goalText = textArea.value.trim();
if (!goalText) {
errorBox.textContent = "目标描述不能为空";
errorBox.style.display = "block";
return;
}
confirmSummary.textContent = "即将创建任务:" + goalText;
form.style.display = "none";
confirmBanner.style.display = "block";
});
document.getElementById("btn_edit_goal").addEventListener("click", () => {
confirmBanner.style.display = "none";
form.style.display = "block";
});
document.getElementById("btn_confirm_goal").addEventListener("click", async () => {
const resp = await fetch("/api/tasks", {
method: "POST",
body: JSON.stringify({
project_id: getCurrentProjectId(),
goal_text: textArea.value.trim(),
task_type: "goal",
created_via: "human_console",
}),
});
const body = await resp.json();
if (resp.status !== 200) {
confirmBanner.style.display = "none";
form.style.display = "block";
errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
errorBox.style.display = "block";
return;
}
// 02-V §2.3: 成功跳转 v_task_detail
window.location.hash = "#/tasks/" + body.task_id;
});
}
// ---- v_bug_feedback (02-V §2.4): report a bug ----
function renderBugFeedback() {
if (!getCurrentProjectId()) return renderNoProjectSelected();
return `
<div class="top-back"><a href="#/">← 返回仪表盘</a></div>
<div class="page">
<h1>反馈 Bug</h1>
<div class="page-sub">人工反馈,与 Validator 自动生成的 bug_record 复用同一张表(source=human)</div>
<div class="panel">
<div id="bug_error" class="error-banner" style="display:none;"></div>
<div id="bug_success" class="success-banner" style="display:none;"></div>
<div id="bug_form">
<div class="field">
<label>问题描述(description,必填)</label>
<textarea id="bug_description" rows="4"></textarea>
</div>
<div class="field">
<label>复现步骤(repro_steps,非必填)</label>
<textarea id="bug_repro_steps" rows="3"></textarea>
</div>
<div class="field">
<label>关联任务(related_task_id,非必填)</label>
<select id="bug_related_task_id">
<option value="">— 不关联,视为新发现的独立问题 —</option>
</select>
</div>
<div class="btn-row">
<button class="btn btn-primary" id="btn_submit_bug" type="button">提交反馈</button>
</div>
</div>
</div>
</div>
`;
}
function mountBugFeedback() {
if (!getCurrentProjectId()) return;
const descriptionArea = document.getElementById("bug_description");
const reproStepsArea = document.getElementById("bug_repro_steps");
const relatedTaskIdSelect = document.getElementById("bug_related_task_id");
const errorBox = document.getElementById("bug_error");
const successBox = document.getElementById("bug_success");
const form = document.getElementById("bug_form");
fetch("/api/tasks?project_id=" + encodeURIComponent(getCurrentProjectId()))
.then((resp) => resp.json())
.then((tasks) => {
for (const task of tasks) {
const option = document.createElement("option");
option.value = task.task_id;
option.textContent = task.goal_text.slice(0, 40) + " (" + task.task_id.slice(0, 8) + ")";
relatedTaskIdSelect.appendChild(option);
}
});
document.getElementById("btn_submit_bug").addEventListener("click", async () => {
errorBox.style.display = "none";
const description = descriptionArea.value.trim();
if (!description) {
errorBox.textContent = "问题描述不能为空";
errorBox.style.display = "block";
return;
}
const relatedTaskId = relatedTaskIdSelect.value || undefined;
const resp = await fetch("/api/bug-reports", {
method: "POST",
body: JSON.stringify({
project_id: getCurrentProjectId(),
description: description,
repro_steps: reproStepsArea.value.trim() || undefined,
related_task_id: relatedTaskId,
}),
});
const body = await resp.json();
if (resp.status !== 200) {
errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
errorBox.style.display = "block";
return;
}
// 02-V §2.4: 跳转到该 bug 的详情视图,MVP 复用 v_task_detail 的 bug 展示区
// -- only possible when the report was tied to a task; otherwise there's
// no task detail page to land on, so show the confirmation inline.
if (relatedTaskId) {
window.location.hash = "#/tasks/" + relatedTaskId;
return;
}
form.style.display = "none";
successBox.innerHTML = "已提交,Validator 将进行归因确认(bug <code>" + body.bug_id + "</code>)。"
+ '<a href="#/">返回仪表盘</a>';
successBox.style.display = "block";
});
}
// ---- v_dashboard (02-V §2.2): real-time landing page ----
const ORG_NODE_ORDER = ["planner", "coder", "validator"];
function renderDashboard() {
if (!getCurrentProjectId()) return renderNoProjectSelected();
return `
<div class="page page-wide">
<h1>仪表盘</h1>
<div id="quota_info_banner" class="info-banner" style="display:none;"></div>
<div id="ws_disconnected_banner" class="error-banner" style="display:none;">实时连接已断开,正在重连…</div>
<div class="grid">
<div>
<div class="panel">
<h2>Org Graph 三节点状态</h2>
<div class="org-strip" id="org_strip"></div>
</div>
<div class="panel">
<h2>当前任务概要</h2>
<div class="task-summary" id="task_summary"></div>
</div>
<div class="actions">
<a class="btn btn-primary" href="#/goals/new">+ 提出新目标</a>
<a class="btn" href="#/bugs/new">反馈 Bug</a>
</div>
</div>
<div>
<div class="panel">
<h2>预算用量</h2>
<div id="budget_summary"></div>
</div>
<div class="panel">
<h2>最近事件</h2>
<div id="event_timeline"></div>
</div>
</div>
</div>
</div>
`;
}
function mountDashboard() {
const projectId = getCurrentProjectId();
if (!projectId) return;
const orgStrip = document.getElementById("org_strip");
const taskSummary = document.getElementById("task_summary");
const budgetSummary = document.getElementById("budget_summary");
const eventTimeline = document.getElementById("event_timeline");
const quotaBanner = document.getElementById("quota_info_banner");
const wsBanner = document.getElementById("ws_disconnected_banner");
const recentEvents = [];
function renderOrgStrip(activeOrgNode, runStatusByOrgNode) {
orgStrip.innerHTML = ORG_NODE_ORDER.map((node, i) => {
const isActive = activeOrgNode === node;
const runStatus = runStatusByOrgNode[node];
const hint = isActive ? "当前节点" : runStatus === "done" ? "已完成" : runStatus || "未开始";
const arrow = i < ORG_NODE_ORDER.length - 1 ? '<div class="org-arrow">→</div>' : "";
return '<div class="org-node' + (isActive ? " active" : "") + '"><div class="role">'
+ node + '</div><div class="hint">' + escapeHtml(hint) + "</div></div>" + arrow;
}).join("");
}
async function refreshTasksAndOrgGraph() {
const resp = await fetch("/api/tasks?project_id=" + encodeURIComponent(projectId));
const tasks = await resp.json();
const active = tasks.find((t) => t.status !== "done") || tasks[0];
if (!active) {
orgStrip.innerHTML = '<div class="hint">暂无运行中任务</div>';
taskSummary.innerHTML = '<div class="hint">暂无运行中任务 · <a href="#/goals/new">提出第一个目标 →</a></div>';
quotaBanner.style.display = "none";
return;
}
taskSummary.innerHTML = (
'<div class="row"><span>Goal</span><span>' + escapeHtml(active.goal_text) + "</span></div>"
+ '<div class="row"><span>Loop Round</span><span>' + active.loop_round + "</span></div>"
+ '<div class="row"><span>Status</span><span><a href="#/tasks/' + active.task_id + '">'
+ escapeHtml(active.status) + "</a></span></div>"
);
const detailResp = await fetch("/api/tasks/" + active.task_id);
const detail = await detailResp.json();
const runStatusByOrgNode = {};
let waitingNode = null;
for (const run of detail.work_graph_runs) {
runStatusByOrgNode[run.org_node] = run.status;
if (!waitingNode) waitingNode = run.nodes.find((n) => n.status === "waiting_for_quota");
}
renderOrgStrip(active.assigned_org_node, runStatusByOrgNode);
if (waitingNode) {
quotaBanner.innerHTML = "🕐 有任务正在等待 Claude Code 额度恢复 · "
+ '<a href="#/tasks/' + active.task_id + '">查看详情</a>';
quotaBanner.style.display = "flex";
} else {
quotaBanner.style.display = "none";
}
}
async function refreshBudget() {
const resp = await fetch("/api/settings/budget");
const configs = await resp.json();
if (configs.length === 0) {
budgetSummary.innerHTML = '<div class="hint">预算护栏未配置</div>';
return;
}
const c = configs[0];
const pct = c.limit_value > 0 ? Math.min(100, Math.round((c.current_usage / c.limit_value) * 100)) : 0;
budgetSummary.innerHTML = (
'<div style="font-size:13px;">' + c.current_usage.toLocaleString() + " / "
+ c.limit_value.toLocaleString() + " " + escapeHtml(c.limit_type) + "</div>"
+ '<div class="progress"><div class="fill" style="width:' + pct + '%"></div></div>'
);
}
function prependEvent(event) {
recentEvents.unshift(event);
recentEvents.length = Math.min(recentEvents.length, 20);
eventTimeline.innerHTML = recentEvents.map((e) =>
'<div class="event-item"><div>' + escapeHtml(e.event_type) + '</div><div class="t">'
+ escapeHtml(e.created_at || "") + "</div></div>"
).join("") || '<div class="hint">暂无事件</div>';
}
refreshTasksAndOrgGraph();
refreshBudget();
eventTimeline.innerHTML = '<div class="hint">暂无事件</div>';
let wasDisconnected = false;
const socket = connectEventSocket(projectId, null, {
onEvent: (event) => {
prependEvent(event);
refreshTasksAndOrgGraph();
if (event.event_type === "budget_updated") refreshBudget();
},
onStatusChange: (status) => {
wsBanner.style.display = status === "disconnected" ? "block" : "none";
if (status === "disconnected") {
wasDisconnected = true;
} else if (status === "connected" && wasDisconnected) {
// REQ-12 boundary: reconnect doesn't replay every missed event, but
// must at least catch up on current state via a fresh snapshot
// fetch (03-C §3.14's own documented reconnect story).
wasDisconnected = false;
refreshTasksAndOrgGraph();
refreshBudget();
}
},
});
registerRouteCleanup(() => socket.close());
}
// ---- v_task_board (02-V §2.5): task list with filters ----
const TASK_STATUSES = [
"queued", "planning_brd_prd_sdd", "planning_failed", "coding", "coding_failed",
"validating", "routed_fast_lane", "routed_full_replan", "blocked_pending_human", "done",
];
function renderTaskBoard() {
if (!getCurrentProjectId()) return renderNoProjectSelected();
return `
<div class="page page-wide">
<h1>任务看板</h1>
<div class="filters">
<input type="text" id="tb_keyword" placeholder="搜索 goal_text" maxlength="128">
<select id="tb_status">
<option value="">全部状态</option>
${TASK_STATUSES.map((s) => '<option value="' + s + '">' + s + "</option>").join("")}
</select>
<select id="tb_org_node">
<option value="">全部 Org 节点</option>
<option value="planner">planner</option>
<option value="coder">coder</option>
<option value="validator">validator</option>
</select>
</div>
<table class="data-table">
<thead>
<tr><th>task_id</th><th>goal_text</th><th>status</th><th>assigned_org_node</th><th>loop_round</th><th>updated_at</th></tr>
</thead>
<tbody id="tb_rows"></tbody>
</table>
</div>
`;
}
function mountTaskBoard() {
const projectId = getCurrentProjectId();
if (!projectId) return;
const rowsEl = document.getElementById("tb_rows");
const keywordEl = document.getElementById("tb_keyword");
const statusEl = document.getElementById("tb_status");
const orgNodeEl = document.getElementById("tb_org_node");
async function refresh() {
const params = new URLSearchParams({ project_id: projectId });
if (keywordEl.value.trim()) params.set("keyword", keywordEl.value.trim());
if (statusEl.value) params.set("status", statusEl.value);
if (orgNodeEl.value) params.set("org_node", orgNodeEl.value);
const resp = await fetch("/api/tasks?" + params.toString());
const tasks = await resp.json();
if (tasks.length === 0) {
rowsEl.innerHTML = '<tr><td colspan="6">暂无任务</td></tr>';
return;
}
rowsEl.innerHTML = tasks.map((t) => (
'<tr data-task-id="' + t.task_id + '">'
+ "<td>" + t.task_id + "</td>"
+ "<td>" + escapeHtml(t.goal_text) + "</td>"
+ '<td><span class="badge ' + t.status + '">' + t.status + "</span></td>"
+ "<td>" + t.assigned_org_node + "</td>"
+ "<td>" + t.loop_round + "</td>"
+ "<td>" + escapeHtml(t.updated_at) + "</td>"
+ "</tr>"
)).join("");
for (const row of rowsEl.querySelectorAll("tr[data-task-id]")) {
row.addEventListener("click", () => {
window.location.hash = "#/tasks/" + row.dataset.taskId;
});
}
}
keywordEl.addEventListener("input", refresh);
statusEl.addEventListener("change", refresh);
orgNodeEl.addEventListener("change", refresh);
refresh();
let wasDisconnected = false;
const socket = connectEventSocket(projectId, null, {
onEvent: (event) => {
if (event.event_type === "task_status_changed") refresh();
},
onStatusChange: (status) => {
if (status === "disconnected") {
wasDisconnected = true;
} else if (status === "connected" && wasDisconnected) {
// REQ-12 boundary: catch up via a fresh snapshot on reconnect.
wasDisconnected = false;
refresh();
}
},
});
registerRouteCleanup(() => socket.close());
}
// ---- v_graph_visualizer (02-V §2.7): embedded Work Graph DAG, layered by
// execution depth (computed from graph_manifest's depends_on edges) and
// colored by work_node_execution.status. Not an independent route --
// embedded into v_task_detail below. The Org Graph layer from the same
// spec section is skipped here since v_task_detail already renders an
// equivalent org-strip panel just above (same classes/data); duplicating
// it a second time immediately below would just be redundant scroll.
function computeGraphLayers(manifestNodes) {
const nodesById = {};
for (const n of manifestNodes) nodesById[n.node_id] = n;
const layerById = {};
function layerOf(nodeId, seen) {
if (nodeId in layerById) return layerById[nodeId];
if (seen.has(nodeId)) return 0; // dependency cycle -- shouldn't happen, don't loop forever
seen.add(nodeId);
const deps = (nodesById[nodeId] && nodesById[nodeId].depends_on) || [];
const layer = deps.length === 0 ? 0 : 1 + Math.max(...deps.map((d) => layerOf(d, seen)));
layerById[nodeId] = layer;
return layer;
}
for (const n of manifestNodes) layerOf(n.node_id, new Set());
const maxLayer = manifestNodes.length ? Math.max(...manifestNodes.map((n) => layerById[n.node_id])) : -1;
const rows = Array.from({ length: maxLayer + 1 }, () => []);
for (const n of manifestNodes) rows[layerById[n.node_id]].push(n);
return rows;
}
const GRAPH_LEGEND_HTML = [
["pending", "status-pending"], ["running", "status-running"],
["reflecting / retrying", "status-reflecting"], ["waiting_for_quota(信息态,非告警)", "status-waiting_for_quota"],
["blocked / failed", "status-blocked"], ["done", "status-done"],
].map(([label, cls]) =>
'<div class="legend-item"><span class="legend-swatch ' + cls + '"></span>' + label + "</div>"
).join("");
function renderGraphVisualizerPanel(run) {
if (!run.graph_manifest || run.graph_manifest.nodes.length === 0) return "";
const nodesById = {};
for (const n of run.nodes) nodesById[n.node_id] = n;
const rowsHtml = computeGraphLayers(run.graph_manifest.nodes).map((row) => {
const cellsHtml = row.map((gn) => {
const wn = nodesById[gn.node_id];
const status = wn ? wn.status : "pending";
const quotaAttrs = wn && wn.status === "waiting_for_quota"
? ' data-quota-limit-type="' + escapeHtml(wn.quota_limit_type || "")
+ '" data-quota-wait-since="' + escapeHtml(wn.quota_wait_started_at || "") + '"'
: "";
return (
'<div class="work-node status-' + status + '" data-node-exec-id="' + (wn ? wn.node_exec_id : "") + '"'
+ quotaAttrs + ">"
+ '<div class="node-id">' + escapeHtml(gn.node_id) + "</div>"
+ '<div class="node-skill">' + escapeHtml(wn ? wn.subagent_type : "尚未开始") + "</div>"
+ "</div>"
);
}).join("");
return '<div class="work-row">' + cellsHtml + "</div>";
}).join("");
return (
'<div class="panel"><h2>' + run.org_node + " Work Graph DAG 视图(v_graph_visualizer,run_id=" + run.run_id + ")</h2>"
+ '<div class="work-graph">' + rowsHtml + "</div>"
+ '<div class="legend" style="margin-top:14px;">' + GRAPH_LEGEND_HTML + "</div>"
+ "</div>"
);
}
function mountGraphVisualizerTooltips(container) {
const tooltip = document.getElementById("graph-tooltip");
if (!tooltip) return;
for (const node of container.querySelectorAll(".work-node")) {
node.addEventListener("mousemove", (evt) => {
const lines = ["skill: " + (node.querySelector(".node-skill").textContent || "")];
if (node.dataset.quotaLimitType) {
lines.push("quota_limit_type: " + node.dataset.quotaLimitType);
lines.push("已等待:" + formatWaitDuration(node.dataset.quotaWaitSince));
}
tooltip.innerHTML = "<b>" + escapeHtml(node.dataset.nodeExecId || node.querySelector(".node-id").textContent) + "</b><br>"
+ lines.map(escapeHtml).join("<br>");
tooltip.style.left = evt.pageX + 12 + "px";
tooltip.style.top = evt.pageY + 12 + "px";
tooltip.classList.add("show");
});
node.addEventListener("mouseout", () => tooltip.classList.remove("show"));
}
}
function formatWaitDuration(sqliteTimestamp) {
if (!sqliteTimestamp) return "未知时长";
const startedAt = new Date(sqliteTimestamp.replace(" ", "T") + "Z").getTime();
const minutes = Math.max(0, Math.round((Date.now() - startedAt) / 60000));
return minutes < 60 ? minutes + " 分钟" : Math.round(minutes / 60) + " 小时";
}
// ---- v_log_viewer (02-V §2.7.1): embedded raw execution log ----
// Non-terminal node status -> realtime scroll mode via c_ws_log_tail;
// terminal status -> one-shot static fetch via c_execution_log_get.
// Embedded per node_exec_id inside v_task_detail's to-do tree, mounted
// lazily the first time a to-do row is expanded (mountTaskDetail wires the
// click handler and tracks cleanup for whichever ones got opened).
function renderLogViewerHtml(nodeExecId) {
return (
'<div class="log-toolbar">'
+ '<label><input type="checkbox" class="log-autoscroll" checked> 自动滚动到最新</label>'
+ '<a class="btn" href="/api/work-nodes/' + encodeURIComponent(nodeExecId) + '/log?download=true">下载完整日志</a>'
+ "</div>"
+ '<div class="log-viewer" id="log-viewer-' + nodeExecId + '"><div class="hint">加载中…</div></div>'
);
}
function mountLogViewer(nodeExecId, initialStatus) {
const viewerEl = document.getElementById("log-viewer-" + nodeExecId);
const autoScrollEl = document.querySelector('#todo-detail-' + nodeExecId + " .log-autoscroll");
if (!viewerEl) return () => {};
function appendLine(text) {
const line = document.createElement("div");
line.className = "line";
line.textContent = text;
viewerEl.appendChild(line);
if (autoScrollEl && autoScrollEl.checked) viewerEl.scrollTop = viewerEl.scrollHeight;
}
async function loadStatic() {
try {
const resp = await fetch("/api/work-nodes/" + encodeURIComponent(nodeExecId) + "/log");
if (resp.status === 404) {
viewerEl.innerHTML = '<div class="hint">日志暂不可用</div>';
return;
}
if (resp.status === 410) {
viewerEl.innerHTML = '<div class="hint">该日志已超过保留期限被清理,保留天数可在设置中调整</div>';
return;
}
const body = await resp.json();
viewerEl.innerHTML = "";
if (!body.content) {
viewerEl.innerHTML = '<div class="hint">暂无日志内容</div>';
return;
}
for (const line of body.content.split("\n")) appendLine(line);
} catch (e) {
viewerEl.innerHTML = '<div class="hint">日志暂不可用</div>';
}
}
if (isTerminalNodeStatus(initialStatus)) {
loadStatic();
return () => {};
}
// live mode still needs to show everything written so far, not just
// chunks appended after this connection opens -- backfill via the same
// static read before tailing new content (mounting is re-triggered on
// every task-level refresh, e.g. from v_task_detail's own WS feed, so
// this also re-populates content a reconnect would otherwise have wiped)
loadStatic();
const socket = connectLogTailSocket(nodeExecId, {
onChunk: (chunk) => { for (const line of chunk.split("\n")) if (line) appendLine(line); },
onClose: () => loadStatic(), // server closes on terminal status (03-C §3.6.2) -- switch to static mode
});
return () => socket.close();
}
const TERMINAL_NODE_STATUSES = new Set(["done", "blocked", "failed"]);
function isTerminalNodeStatus(status) {
return TERMINAL_NODE_STATUSES.has(status);
}
// ---- v_task_detail (02-V §2.6): task detail / process inspection ----
// Embeds a to-do tree built from graph_manifest (01-M 1.3's "补充说明")
// and the v_graph_visualizer DAG view above. The raw-log v_log_viewer is a
// separate Unit (U-027) and shows as a clearly-labeled placeholder here
// until it lands, rather than faking its content.
function renderTaskDetail(taskId) {
if (!getCurrentProjectId()) return renderNoProjectSelected();
return `
<div class="page page-wide">
<div class="breadcrumb"><a href="#/tasks">任务</a> / ${taskId}</div>
<div id="td_content"><div class="hint">加载中…</div></div>
</div>
`;
}
function mountTaskDetail(taskId) {
const projectId = getCurrentProjectId();
if (!projectId) return;
const content = document.getElementById("td_content");
// v_log_viewer instances (02-V §2.7.1) mounted lazily on first to-do
// expand -- tracked here so a re-render (WS-triggered refresh) or leaving
// the page closes any live c_ws_log_tail connections instead of leaking them.
const activeLogViewers = new Map();
function closeAllLogViewers() {
for (const close of activeLogViewers.values()) close();
activeLogViewers.clear();
}
function renderTodoTree(run) {
if (!run.graph_manifest) return "";
const nodesById = {};
for (const n of run.nodes) nodesById[n.node_id] = n;
const items = run.graph_manifest.nodes.map((gn) => {
const wn = nodesById[gn.node_id];
const status = wn ? wn.status : "pending";
const detail = wn ? (
'<div class="todo-detail" id="todo-detail-' + wn.node_exec_id + '" data-status="' + status + '">'
+ "retry_count: " + wn.retry_count
+ (wn.reflection_notes ? "<br>reflection_notes: " + escapeHtml(wn.reflection_notes) : "")
+ '<div class="log-viewer-slot" id="log-slot-' + wn.node_exec_id + '"></div>'
+ "</div>"
) : "";
return (
'<li class="status-' + status + '">'
+ '<div class="todo-row" data-node-exec-id="' + (wn ? wn.node_exec_id : "") + '">'
+ '<span class="dot"></span>'
+ '<span class="todo-id">to-do: ' + escapeHtml(gn.node_id) + "</span>"
+ '<span class="todo-status">' + status + (wn ? " · node_exec_id=" + wn.node_exec_id : "") + "</span>"
+ "</div>" + detail + "</li>"
);
}).join("");
return (
'<div class="panel"><h2>' + run.org_node + " Work Graph 的 to-do 树(run_id=" + run.run_id + ")</h2>"
+ '<ul class="todo-tree">' + items + "</ul>"
+ '<div class="see-more">DAG 视图(同一份 graph_manifest 的另一种呈现)见下方 v_graph_visualizer</div>'
+ "</div>"
);
}
function renderDetail(task) {
closeAllLogViewers();
const activeSet = new Set([task.assigned_org_node]);
for (const run of task.work_graph_runs) {
if (run.status !== "done" && run.status !== "failed") activeSet.add(run.org_node);
}
const orgStripHtml = ORG_NODE_ORDER.map((node, i) => {
const arrow = i < ORG_NODE_ORDER.length - 1 ? '<div class="org-arrow">→</div>' : "";
return '<div class="org-node' + (activeSet.has(node) ? " active" : "") + '">' + node + "</div>" + arrow;
}).join("");
const alertHtml = task.status !== "blocked_pending_human" ? "" : (
'<div class="alert-banner">⚠ 已阻塞(' + escapeHtml(task.blocked_reason || "") + '),需要人工干预'
+ '<button class="btn btn-danger" id="btn_manual_resume" type="button">人工干预(manual_resume)</button></div>'
);
const todoTreesHtml = task.work_graph_runs.map(renderTodoTree).join("");
const graphVisualizerHtml = task.work_graph_runs.map(renderGraphVisualizerPanel).join("");
const artifactsHtml = task.artifacts.length ? (
'<ul class="simple-list">' + task.artifacts.map((a) =>
"<li><span>" + escapeHtml(a.file_path) + "</span><span>"
+ escapeHtml(a.artifact_type) + " · " + escapeHtml(a.validation_status) + "</span></li>"
).join("") + "</ul>"
) : '<div class="hint">暂无 Artifact</div>';
const bugsHtml = task.bug_records.length ? (
'<ul class="simple-list">' + task.bug_records.map((b) =>
"<li><span>" + escapeHtml(b.description) + "</span><span>"
+ escapeHtml(b.root_cause_category || "待归因") + " · " + escapeHtml(b.status) + "</span></li>"
).join("") + "</ul>"
) : '<div class="hint">暂无 Bug 记录</div>';
content.innerHTML = (
"<h1>" + escapeHtml(task.goal_text) + "</h1>"
+ alertHtml
+ '<div class="meta-row">'
+ "<div><b>STATUS</b>" + escapeHtml(task.status) + "</div>"
+ "<div><b>LOOP_ROUND</b>" + task.loop_round + "</div>"
+ "<div><b>ASSIGNED_ORG_NODE</b>" + task.assigned_org_node + "</div>"
+ "<div><b>CREATED_VIA</b>" + escapeHtml(task.created_via) + "</div>"
+ "</div>"
+ '<div class="panel"><h2>Org Graph</h2><div class="org-strip">' + orgStripHtml + "</div></div>"
+ todoTreesHtml
+ graphVisualizerHtml
+ '<div class="tooltip" id="graph-tooltip"></div>'
+ '<div class="panel"><h2>关联 Artifact</h2>' + artifactsHtml + "</div>"
+ '<div class="panel"><h2>关联 Bug 记录</h2>' + bugsHtml + "</div>"
);
for (const row of content.querySelectorAll(".todo-row[data-node-exec-id]")) {
row.addEventListener("click", () => {
const nodeExecId = row.dataset.nodeExecId;
if (!nodeExecId) return;
const detail = document.getElementById("todo-detail-" + nodeExecId);
if (!detail) return;
detail.classList.toggle("open");
if (detail.classList.contains("open") && !activeLogViewers.has(nodeExecId)) {
const slot = document.getElementById("log-slot-" + nodeExecId);
slot.innerHTML = renderLogViewerHtml(nodeExecId);
activeLogViewers.set(nodeExecId, mountLogViewer(nodeExecId, detail.dataset.status));
}
});
}
mountGraphVisualizerTooltips(content);
const resumeBtn = document.getElementById("btn_manual_resume");
if (resumeBtn) {
resumeBtn.addEventListener("click", async () => {
resumeBtn.disabled = true;
await fetch("/api/tasks/" + taskId + "/route", {
method: "POST",
body: JSON.stringify({ decided_route: "manual_resume" }),
});
refresh();
});
}
}
async function refresh() {
const resp = await fetch("/api/tasks/" + taskId);
if (resp.status === 404) {
content.innerHTML = '<div class="error-banner" style="display:block;">任务不存在</div>';
return;
}
renderDetail(await resp.json());
}
refresh();
let wasDisconnected = false;
const socket = connectEventSocket(projectId, taskId, {
onEvent: () => refresh(),
onStatusChange: (status) => {
if (status === "disconnected") {
wasDisconnected = true;
} else if (status === "connected" && wasDisconnected) {
// REQ-12 boundary: catch up via a fresh snapshot on reconnect.
wasDisconnected = false;
refresh();
}
},
});
registerRouteCleanup(() => {
socket.close();
closeAllLogViewers();
});
}
// ---- v_artifact_browser (02-V §2.8): artifact list + read-only preview ----
// Preview renders content in a plain <pre> block for every artifact_type --
// 02-V asks for Markdown rendering / syntax highlighting, but pulling in a
// markdown/highlighting library would be this frontend's first external
// dependency (05 §5.7's "no build step" ethos extends to keeping the
// console vanilla-JS-only); a monospace raw-text preview is a deliberate,
// documented simplification, not a missed requirement.
const ARTIFACT_TYPES = ["brd", "prd", "sdd", "benchmark", "bug_record", "code_diff", "test_report"];
function renderArtifactBrowser() {
if (!getCurrentProjectId()) return renderNoProjectSelected();
return `
<div class="page page-wide">
<h1>Artifact 浏览器</h1>
<div class="filters">
<select id="ab_type_filter">
<option value="">全部类型(artifact_type_filter)</option>
${ARTIFACT_TYPES.map((t) => '<option value="' + t + '">' + t + "</option>").join("")}
</select>
<select id="ab_task_filter">
<option value="">全部任务(task_id_filter)</option>
</select>
</div>
<div class="artifact-browser-grid">
<ul class="artifact-list" id="ab_list"></ul>
<div class="preview" id="ab_preview"><div class="hint">选择左侧一个 Artifact 查看预览</div></div>
</div>
</div>
`;
}
function mountArtifactBrowser() {
const projectId = getCurrentProjectId();
if (!projectId) return;
const listEl = document.getElementById("ab_list");
const previewEl = document.getElementById("ab_preview");
const typeFilterEl = document.getElementById("ab_type_filter");
const taskFilterEl = document.getElementById("ab_task_filter");
let selectedArtifactId = null;
fetch("/api/tasks?project_id=" + encodeURIComponent(projectId))
.then((resp) => resp.json())
.then((tasks) => {
for (const task of tasks) {
const option = document.createElement("option");
option.value = task.task_id;
option.textContent = task.goal_text.slice(0, 40) + " (" + task.task_id.slice(0, 8) + ")";
taskFilterEl.appendChild(option);
}
});
async function showPreview(artifactId) {
selectedArtifactId = artifactId;
for (const li of listEl.querySelectorAll("li")) {
li.classList.toggle("active", li.dataset.artifactId === artifactId);
}
previewEl.innerHTML = '<div class="hint">加载中…</div>';
const artifact = await fetch("/api/artifacts/" + encodeURIComponent(artifactId)).then((r) => r.json());
const lineageHtml = artifact.lineage.map((a, i) => {
const isCurrent = a.artifact_id === artifactId;
const label = escapeHtml(a.artifact_type) + (isCurrent ? "(当前)" : "");
const arrow = i < artifact.lineage.length - 1 ? " → " : "";
return '<span class="node">' + label + "</span>" + arrow;
}).join("");
previewEl.innerHTML = (
'<div class="lineage">血缘链:' + lineageHtml + "</div>"
+ '<pre class="code">' + (artifact.content == null ? "(文件不可用)" : escapeHtml(artifact.content)) + "</pre>"
);
}
async function refreshList() {
const params = new URLSearchParams({ project_id: projectId });
if (typeFilterEl.value) params.set("artifact_type", typeFilterEl.value);
if (taskFilterEl.value) params.set("task_id", taskFilterEl.value);
const artifacts = await fetch("/api/artifacts?" + params.toString()).then((r) => r.json());
if (artifacts.length === 0) {
listEl.innerHTML = '<li class="hint" style="cursor:default;">暂无产物</li>';
previewEl.innerHTML = '<div class="hint">暂无产物</div>';
return;
}
listEl.innerHTML = artifacts.map((a) =>
'<li data-artifact-id="' + a.artifact_id + '"><div class="type">' + escapeHtml(a.artifact_type) + "</div>"
+ escapeHtml(a.file_path.split("/").pop()) + "</li>"
).join("");
for (const li of listEl.querySelectorAll("li[data-artifact-id]")) {
li.addEventListener("click", () => showPreview(li.dataset.artifactId));
}
if (selectedArtifactId && artifacts.some((a) => a.artifact_id === selectedArtifactId)) {
showPreview(selectedArtifactId);
} else {
showPreview(artifacts[0].artifact_id);
}
}
typeFilterEl.addEventListener("change", refreshList);
taskFilterEl.addEventListener("change", refreshList);
refreshList();
const socket = connectEventSocket(projectId, null, {
onEvent: (event) => { if (event.event_type === "artifact_created") refreshList(); },
onStatusChange: () => {},
});
registerRouteCleanup(() => socket.close());
}
// ---- v_skill_library (02-V §2.9) + v_skill_audit_log (02-V §2.10) ----
// Skills are a platform-wide asset living in graphlemon's own repo (see
// skill_query.py), not scoped to any target project -- these two pages
// deliberately don't check getCurrentProjectId(), unlike every other real
// page in this console.
const SOURCE_TAG_LABELS = {
migrated_from_hermes: "migrated_from_hermes", new: "new", auto_iterated: "auto_iterated",
};
function renderSkillLibrary() {
return `
<div class="page page-wide">
<h1>技能库</h1>
<div id="skill_groups"><div class="hint">加载中…</div></div>
</div>
`;
}
function mountSkillLibrary() {
const groupsEl = document.getElementById("skill_groups");
fetch("/api/skills").then((r) => r.json()).then((skills) => {
if (skills.length === 0) {
groupsEl.innerHTML = '<div class="hint">暂无 Skill</div>';
return;
}
const byOrgNode = { planner: [], coder: [], validator: [] };
for (const s of skills) (byOrgNode[s.owner_org_node] || []).push(s);
groupsEl.innerHTML = ORG_NODE_ORDER.map((node) => {
const rows = byOrgNode[node];
if (!rows || rows.length === 0) return "";
const rowsHtml = rows.map((s) =>
'<div class="skill-row" data-skill-id="' + s.skill_id + '">'
+ '<span class="name">' + escapeHtml(s.skill_id) + "</span>"
+ '<span class="tag' + (s.source === "auto_iterated" ? " auto" : "") + '">'
+ escapeHtml(SOURCE_TAG_LABELS[s.source] || s.source) + "</span>"
+ "</div>"
).join("");
return (
'<div class="group"><h2>' + node.charAt(0).toUpperCase() + node.slice(1) + "</h2>"
+ '<div class="skill-list">' + rowsHtml + "</div></div>"
);
}).join("");
for (const row of groupsEl.querySelectorAll(".skill-row")) {
row.addEventListener("click", () => {
window.location.hash = "#/skills/" + row.dataset.skillId + "/audit";
});
}
});
}
function renderSkillAuditLog(skillId) {
return `
<div class="page page-wide">
<div class="breadcrumb"><a href="#/skills">技能库</a> / ${escapeHtml(skillId)}</div>
<h1>${escapeHtml(skillId)} 变更审计</h1>
<div id="skill_audit_error" class="error-banner" style="display:none;"></div>
<div id="skill_audit_list"><div class="hint">加载中…</div></div>
</div>
`;
}
function mountSkillAuditLog(skillId) {
const listEl = document.getElementById("skill_audit_list");
const errorEl = document.getElementById("skill_audit_error");
async function refresh() {
const resp = await fetch("/api/skills/" + encodeURIComponent(skillId) + "/audit");
if (resp.status === 404) {
listEl.innerHTML = "";
errorEl.textContent = "该 Skill 不存在";
errorEl.style.display = "block";
return;
}
const iterations = await resp.json();
if (iterations.length === 0) {
listEl.innerHTML = '<div class="hint">该 Skill 尚无自主迭代记录</div>';
return;
}
// newest first for display, oldest-first order from the API gives each its #N
listEl.innerHTML = iterations.slice().reverse().map((it, i) => {
const number = iterations.length - i;
return (
'<div class="iteration" data-iteration-id="' + it.iteration_id + '" '
+ 'data-before="' + it.before_git_commit_sha + '" data-after="' + it.after_git_commit_sha + '">'
+ '<div class="top"><b>迭代 #' + number + "</b><span class=\"t\">applied_at: " + escapeHtml(it.applied_at) + "</span></div>"
+ '<div class="summary">triggered_by_bug_id: ' + escapeHtml(it.triggered_by_bug_id) + " · " + escapeHtml(it.change_summary) + "</div>"
+ '<div class="actions">'
+ '<button class="btn btn-diff" type="button">查看 diff</button>'
+ '<button class="btn btn-rollback" type="button">回滚到此版本前</button>'
+ "</div>"
+ '<pre class="code diff-output" style="display:none;"></pre>'
+ "</div>"
);
}).join("");
for (const el of listEl.querySelectorAll(".iteration")) {
const diffOutput = el.querySelector(".diff-output");
el.querySelector(".btn-diff").addEventListener("click", async () => {
if (diffOutput.style.display === "block") {
diffOutput.style.display = "none";
return;
}
diffOutput.textContent = "加载中…";
diffOutput.style.display = "block";
const resp = await fetch(
"/api/skills/diff?before=" + encodeURIComponent(el.dataset.before) + "&after=" + encodeURIComponent(el.dataset.after)
);
const body = await resp.json();
diffOutput.textContent = body.diff_text || "(无差异)";
});
el.querySelector(".btn-rollback").addEventListener("click", async () => {
const resp = await fetch("/api/skills/" + encodeURIComponent(skillId) + "/rollback", {
method: "POST",
body: JSON.stringify({ iteration_id: el.dataset.iterationId }),
});
if (resp.status !== 200) {
const body = await resp.json();
errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
errorEl.style.display = "block";
return;
}
errorEl.style.display = "none";
refresh();
});
}
}
refresh();
}
// ---- v_concurrency_settings / v_budget_settings / v_log_retention_settings
// (02-V §2.11/§2.12/§2.13) -- three small config pages, none of them
// project-scoped (all three tables are platform-wide singletons, config_id
// ='default'), so like the Skill pages they skip the getCurrentProjectId()
// guard. renderSettingsSubnav() stands in for 02-V's nav-dropdown, which
// this shell's single-level #nav bar doesn't have room for.
function renderSettingsSubnav(active) {
const items = [["concurrency", "并发数"], ["budget", "预算护栏"], ["log-retention", "日志保留"]];
return '<div class="filters">' + items.map(([key, label]) =>
'<a class="btn' + (key === active ? " btn-primary" : "") + '" href="#/settings/' + key + '">' + label + "</a>"
).join("") + "</div>";
}
function renderConcurrencySettings() {
return `
<div class="page">
<h1>并发数配置</h1>
${renderSettingsSubnav("concurrency")}
<div id="cs_error" class="error-banner" style="display:none;"></div>
<div id="cs_success" class="success-banner" style="display:none;"></div>
<div class="panel">
<div class="field">
<label>最大并发 Goal 数(max_concurrent_goals,1-50)</label>
<input type="number" id="cs_max_concurrent_goals" min="1" max="50" value="1">
<div class="hint">调大后下一个新 Goal 起生效</div>
</div>
<button class="btn btn-primary" id="btn_save_concurrency" type="button">保存</button>
</div>
</div>
`;
}
function mountConcurrencySettings() {
const input = document.getElementById("cs_max_concurrent_goals");
const errorEl = document.getElementById("cs_error");
const successEl = document.getElementById("cs_success");
fetch("/api/settings/concurrency").then((r) => r.json()).then((config) => {
if (config) input.value = config.max_concurrent_goals;
});
document.getElementById("btn_save_concurrency").addEventListener("click", async () => {
errorEl.style.display = "none";
successEl.style.display = "none";
const resp = await fetch("/api/settings/concurrency", {
method: "PUT",
body: JSON.stringify({ max_concurrent_goals: Number(input.value) }),
});
const body = await resp.json();
if (resp.status !== 200) {
errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
errorEl.style.display = "block";
return;
}
successEl.textContent = "已更新,下一个新 Goal 起生效";
successEl.style.display = "block";
});
}
function renderBudgetSettings() {
return `
<div class="page">
<h1>预算护栏配置</h1>
${renderSettingsSubnav("budget")}
<div class="page-sub">人工配置层,与 Claude Code plan 额度耗尽是两套独立机制</div>
<div id="bs_error" class="error-banner" style="display:none;"></div>
<div id="bs_success" class="success-banner" style="display:none;"></div>
<div class="panel">
<div class="field">
<label>作用范围(scope)</label>
<select id="bs_scope">
<option value="global">global</option>
<option value="per_task">per_task</option>
<option value="per_day">per_day</option>
</select>
</div>
<div class="field">
<label>限额类型(limit_type)</label>
<select id="bs_limit_type">
<option value="token_count">token_count</option>
<option value="call_count">call_count</option>
</select>
</div>
<div class="field">
<label>限额值(limit_value)</label>
<input type="number" id="bs_limit_value" value="100000">
</div>
<div id="bs_usage" class="hint"></div>
<div class="progress"><div class="fill" id="bs_usage_fill" style="width:0%"></div></div>
<div id="bs_alert" class="alert-banner" style="display:none; margin-top:14px;"></div>
<button class="btn btn-primary" id="btn_save_budget" type="button" style="margin-top:16px;">保存</button>
</div>
</div>
`;
}
function mountBudgetSettings() {
const scopeEl = document.getElementById("bs_scope");
const limitTypeEl = document.getElementById("bs_limit_type");
const limitValueEl = document.getElementById("bs_limit_value");
const usageEl = document.getElementById("bs_usage");
const usageFillEl = document.getElementById("bs_usage_fill");
const alertEl = document.getElementById("bs_alert");
const errorEl = document.getElementById("bs_error");
const successEl = document.getElementById("bs_success");
async function refresh() {
const configs = await fetch("/api/settings/budget").then((r) => r.json());
const config = configs[0];
if (config) {
scopeEl.value = config.scope;
limitTypeEl.value = config.limit_type;
limitValueEl.value = config.limit_value;
usageEl.textContent = "当前用量:" + config.current_usage.toLocaleString() + " / " + config.limit_value.toLocaleString();
const pct = config.limit_value > 0 ? Math.min(100, Math.round((config.current_usage / config.limit_value) * 100)) : 0;
usageFillEl.style.width = pct + "%";
} else {
usageEl.textContent = "尚未配置";
}
const projectId = getCurrentProjectId();
const blocked = projectId
? await fetch("/api/tasks?project_id=" + encodeURIComponent(projectId) + "&status=blocked_pending_human")
.then((r) => (r.ok ? r.json() : []))
: [];
if (blocked.length > 0) {
alertEl.innerHTML = "已有 " + blocked.length + " 个任务处于 blocked_pending_human · " + '<a href="#/tasks">查看已暂停任务</a>';
alertEl.style.display = "flex";
} else {
alertEl.style.display = "none";
}
}
document.getElementById("btn_save_budget").addEventListener("click", async () => {
errorEl.style.display = "none";
successEl.style.display = "none";
const resp = await fetch("/api/settings/budget", {
method: "PUT",
body: JSON.stringify({ scope: scopeEl.value, limit_type: limitTypeEl.value, limit_value: Number(limitValueEl.value) }),
});
const body = await resp.json();
if (resp.status !== 200) {
errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
errorEl.style.display = "block";
return;
}
successEl.textContent = "已更新" + (body.resumed_task_ids.length ? ",已恢复 " + body.resumed_task_ids.length + " 个因超限阻塞的任务" : "");
successEl.style.display = "block";
refresh();
});
refresh();
}
function renderLogRetentionSettings() {
return `
<div class="page">
<h1>日志保留策略配置</h1>
${renderSettingsSubnav("log-retention")}
<div id="lrs_error" class="error-banner" style="display:none;"></div>
<div id="lrs_success" class="success-banner" style="display:none;"></div>
<div class="panel">
<div class="field">
<label>保留天数(retention_days,>0)</label>
<input type="number" id="lrs_retention_days" value="14">
</div>
<div class="field">
<label>总大小上限(max_total_size_mb,非必填)</label>
<input type="number" id="lrs_max_total_size_mb" placeholder="不限制">
<div class="hint">超过该天数的 closed 状态日志会被清理任务标记 purged 并删除物理文件;清理任务触发频率本身不可配</div>
</div>
<button class="btn btn-primary" id="btn_save_log_retention" type="button">保存</button>
</div>
</div>
`;
}
function mountLogRetentionSettings() {
const daysEl = document.getElementById("lrs_retention_days");
const sizeEl = document.getElementById("lrs_max_total_size_mb");
const errorEl = document.getElementById("lrs_error");
const successEl = document.getElementById("lrs_success");
fetch("/api/settings/log-retention").then((r) => r.json()).then((config) => {
if (config) {
daysEl.value = config.retention_days;
if (config.max_total_size_mb != null) sizeEl.value = config.max_total_size_mb;
}
});
document.getElementById("btn_save_log_retention").addEventListener("click", async () => {
errorEl.style.display = "none";
successEl.style.display = "none";
const resp = await fetch("/api/settings/log-retention", {
method: "PUT",
body: JSON.stringify({
retention_days: Number(daysEl.value),
max_total_size_mb: sizeEl.value ? Number(sizeEl.value) : undefined,
}),
});
const body = await resp.json();
if (resp.status !== 200) {
errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
errorEl.style.display = "block";
return;
}
successEl.textContent = "已更新";
successEl.style.display = "block";
});
}