opencode-windows-scheduler 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -1
- package/README.md +5 -5
- package/ROADMAP-STRATEGY.md +2 -2
- package/ROADMAP.md +31 -5
- package/dist/core/dry-run.d.ts +5 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +20 -4
- package/dist/core/one-shot.d.ts +62 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +126 -0
- package/dist/core/otel.d.ts +4 -0
- package/dist/core/otel.d.ts.map +1 -0
- package/dist/core/otel.js +98 -0
- package/dist/core/prometheus.d.ts +23 -0
- package/dist/core/prometheus.d.ts.map +1 -0
- package/dist/core/prometheus.js +146 -0
- package/dist/core/ps-wrapper.d.ts +6 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +25 -3
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +9 -0
- package/dist/core/scheduler/linux.d.ts +12 -3
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +80 -3
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +17 -3
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +3 -0
- package/dist/core/scheduler/registry.d.ts +4 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/types.d.ts +5 -3
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +10 -1
- package/dist/core/session.d.ts +34 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +105 -0
- package/dist/core/structured-log.d.ts +84 -0
- package/dist/core/structured-log.d.ts.map +1 -0
- package/dist/core/structured-log.js +137 -0
- package/dist/core/wrappers/bash.d.ts +9 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +27 -3
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +63 -6
- package/dist/db/metrics-repo.d.ts +3 -0
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +16 -8
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +8 -1
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +8 -0
- package/dist/history.d.ts +7 -0
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +13 -0
- package/dist/index.d.ts +22 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +330 -41
- package/dist/integrations.d.ts +64 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +205 -0
- package/dist/rpc.d.ts +81 -4
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +43 -4
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +582 -70
- package/dist/settings.d.ts +38 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +68 -0
- package/dist/shared/jobs-view.d.ts +43 -5
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/shared/jobs-view.js +125 -7
- package/dist/task-transfer.d.ts +19 -3
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +75 -3
- package/docs/FEATURES.md +101 -4
- package/gui-experimental.cjs +4 -4
- package/package.json +11 -2
- package/scripts/demo-dashboard.mjs +12 -2
- package/src/core/dry-run.ts +24 -5
- package/src/core/one-shot.ts +173 -0
- package/src/core/otel.ts +128 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +29 -3
- package/src/core/record-history.ts +13 -0
- package/src/core/scheduler/linux.ts +90 -3
- package/src/core/scheduler/mac.ts +35 -4
- package/src/core/scheduler/posix.ts +3 -0
- package/src/core/scheduler/registry.ts +4 -0
- package/src/core/scheduler/types.ts +5 -3
- package/src/core/scheduler/windows.ts +11 -1
- package/src/core/session.ts +115 -0
- package/src/core/structured-log.ts +205 -0
- package/src/core/wrappers/bash.ts +38 -2
- package/src/db/history-repo.ts +67 -7
- package/src/db/metrics-repo.ts +19 -7
- package/src/db/migrate.ts +7 -1
- package/src/db/schema.ts +11 -0
- package/src/gui.tsx +237 -18
- package/src/history.ts +17 -0
- package/src/index.ts +426 -47
- package/src/integrations.ts +253 -0
- package/src/rpc.ts +43 -4
- package/src/server.ts +622 -69
- package/src/settings.ts +122 -0
- package/src/shared/jobs-view.ts +158 -8
- package/src/task-transfer.ts +107 -5
- package/src/tui.tsx +290 -14
package/src/server.ts
CHANGED
|
@@ -11,6 +11,16 @@ import { checkpointDb, getDbFile, getDbStatus } from "./db/index.js";
|
|
|
11
11
|
import { listWorkspaces } from "./workspaces.js";
|
|
12
12
|
import { getProfileName, getProfilePort } from "./profiles.js";
|
|
13
13
|
import { simulatePipeline } from "./core/dry-run.js";
|
|
14
|
+
import { loadSettings } from "./settings.js";
|
|
15
|
+
import {
|
|
16
|
+
authenticateHookRequest,
|
|
17
|
+
extractHookSignature,
|
|
18
|
+
extractHookToken,
|
|
19
|
+
readRequestBody,
|
|
20
|
+
} from "./integrations.js";
|
|
21
|
+
import { appendStructuredLog, readStructuredLogs } from "./core/structured-log.js";
|
|
22
|
+
import { PROMETHEUS_CONTENT_TYPE, renderPrometheusMetrics } from "./core/prometheus.js";
|
|
23
|
+
import { buildOtlpExport } from "./core/otel.js";
|
|
14
24
|
|
|
15
25
|
/**
|
|
16
26
|
* Локальный веб-дашборд (Спринт 5).
|
|
@@ -29,8 +39,13 @@ const FALLBACK_PORT = 4782;
|
|
|
29
39
|
/** Дополнительный порт, если и 3782, и 4782 заняты чужими процессами. */
|
|
30
40
|
const EXTRA_PORTS = [5782];
|
|
31
41
|
|
|
32
|
-
|
|
33
|
-
|
|
42
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Имена процессов, которые считаем «зомби» от прошлых запусков плагина.
|
|
46
|
+
* На Windows процессы называются node.exe / bun.exe, на POSIX — node / bun.
|
|
47
|
+
*/
|
|
48
|
+
const ZOMBIE_IMAGE_NAMES = new Set(["node", "nodejs", "node.exe", "bun", "bun.exe"]);
|
|
34
49
|
|
|
35
50
|
/** Маркер-заголовок: по нему узнаём «свой» дашборд, уже слушающий порт. */
|
|
36
51
|
const DASHBOARD_HEADER = "x-plugin-dashboard";
|
|
@@ -118,6 +133,8 @@ export interface TaskMetrics {
|
|
|
118
133
|
total: number;
|
|
119
134
|
success: number;
|
|
120
135
|
error: number;
|
|
136
|
+
/** Частичные выполнения: ответ получен, но проверка не прошла. */
|
|
137
|
+
partial: number;
|
|
121
138
|
}
|
|
122
139
|
|
|
123
140
|
/** Агрегированная статистика по одной LLM-модели. */
|
|
@@ -292,15 +309,20 @@ export async function startDashboardServer(
|
|
|
292
309
|
}
|
|
293
310
|
|
|
294
311
|
// Порт занят чужим или старым процессом: пробуем снять зомби
|
|
295
|
-
// (только node/bun этого плагина) и
|
|
312
|
+
// (только node/bun этого плагина) и повторить bind.
|
|
296
313
|
if (port !== 0 && (await tryFreeZombiePort(port))) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
314
|
+
// SIGKILL асинхронный: на POSIX процесс может ещё какое-то время
|
|
315
|
+
// держать сокет, поэтому сначала ждём освобождения порта.
|
|
316
|
+
const freed = await waitForPortFree(port, 3000);
|
|
317
|
+
if (freed) {
|
|
318
|
+
try {
|
|
319
|
+
const server = await listenOn(port, deps);
|
|
320
|
+
running = { server, port };
|
|
321
|
+
console.log(`[windows-scheduler] Веб-дашборд запущен: http://localhost:${port}`);
|
|
322
|
+
return { port };
|
|
323
|
+
} catch {
|
|
324
|
+
// Не вышло — идём к следующему порту.
|
|
325
|
+
}
|
|
304
326
|
}
|
|
305
327
|
}
|
|
306
328
|
// Чужой сервис — пробуем запасной порт.
|
|
@@ -358,7 +380,11 @@ async function tryFreeZombiePort(port: number): Promise<boolean> {
|
|
|
358
380
|
}
|
|
359
381
|
|
|
360
382
|
try {
|
|
361
|
-
|
|
383
|
+
if (IS_WINDOWS) {
|
|
384
|
+
await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
|
|
385
|
+
} else {
|
|
386
|
+
process.kill(pid, "SIGKILL");
|
|
387
|
+
}
|
|
362
388
|
console.log(
|
|
363
389
|
`[windows-scheduler] Снят зомби-процесс ${info.name} (PID ${pid}), державший порт ${port}.`
|
|
364
390
|
);
|
|
@@ -375,8 +401,25 @@ async function tryFreeZombiePort(port: number): Promise<boolean> {
|
|
|
375
401
|
return killed;
|
|
376
402
|
}
|
|
377
403
|
|
|
378
|
-
/**
|
|
404
|
+
/** Ждёт, пока порт освободится (POSIX: убитый процесс отпускает сокет не синхронно). */
|
|
405
|
+
async function waitForPortFree(port: number, timeoutMs: number): Promise<boolean> {
|
|
406
|
+
const deadline = Date.now() + timeoutMs;
|
|
407
|
+
while (Date.now() < deadline) {
|
|
408
|
+
const pids = await findListeningPids(port);
|
|
409
|
+
if (pids.length === 0) return true;
|
|
410
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
411
|
+
}
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Возвращает PID'ы процессов, слушающих указанный TCP-порт. */
|
|
379
416
|
async function findListeningPids(port: number): Promise<number[]> {
|
|
417
|
+
if (IS_WINDOWS) return findListeningPidsWindows(port);
|
|
418
|
+
return findListeningPidsPosix(port);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Windows: netstat -ano, состояния LISTENING. */
|
|
422
|
+
async function findListeningPidsWindows(port: number): Promise<number[]> {
|
|
380
423
|
try {
|
|
381
424
|
const { stdout } = await execFileAsync("netstat", ["-ano", "-p", "TCP"], {
|
|
382
425
|
windowsHide: true,
|
|
@@ -398,8 +441,55 @@ async function findListeningPids(port: number): Promise<number[]> {
|
|
|
398
441
|
}
|
|
399
442
|
}
|
|
400
443
|
|
|
401
|
-
/**
|
|
444
|
+
/**
|
|
445
|
+
* macOS/Linux: lsof (есть в macOS и на большинстве Linux-образов),
|
|
446
|
+
* на Linux — запасной вариант через ss из iproute2.
|
|
447
|
+
*/
|
|
448
|
+
async function findListeningPidsPosix(port: number): Promise<number[]> {
|
|
449
|
+
try {
|
|
450
|
+
const { stdout } = await execFileAsync(
|
|
451
|
+
"lsof",
|
|
452
|
+
["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"],
|
|
453
|
+
{ windowsHide: true }
|
|
454
|
+
);
|
|
455
|
+
const pids = stdout
|
|
456
|
+
.split(/\s+/)
|
|
457
|
+
.map(Number)
|
|
458
|
+
.filter((pid) => Number.isInteger(pid) && pid > 0);
|
|
459
|
+
if (pids.length > 0) return Array.from(new Set(pids));
|
|
460
|
+
} catch {
|
|
461
|
+
// lsof может отсутствовать или не быть в PATH — пробуем ss.
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
if (process.platform === "linux") {
|
|
465
|
+
try {
|
|
466
|
+
const { stdout } = await execFileAsync("ss", ["-ltnp", `sport = :${port}`], {
|
|
467
|
+
windowsHide: true,
|
|
468
|
+
});
|
|
469
|
+
const pids = new Set<number>();
|
|
470
|
+
for (const match of stdout.matchAll(/pid=(\d+)/g)) {
|
|
471
|
+
const pid = Number(match[1]);
|
|
472
|
+
if (Number.isInteger(pid) && pid > 0) pids.add(pid);
|
|
473
|
+
}
|
|
474
|
+
return Array.from(pids);
|
|
475
|
+
} catch {
|
|
476
|
+
// ss тоже недоступен — считаем, что владельца порта не знаем.
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
return [];
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Имя процесса и командная строка. */
|
|
402
484
|
async function getProcessInfo(pid: number): Promise<{ name: string; commandLine: string } | null> {
|
|
485
|
+
if (IS_WINDOWS) return getProcessInfoWindows(pid);
|
|
486
|
+
return getProcessInfoPosix(pid);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Имя процесса и командная строка через CIM (Windows PowerShell). */
|
|
490
|
+
async function getProcessInfoWindows(
|
|
491
|
+
pid: number
|
|
492
|
+
): Promise<{ name: string; commandLine: string } | null> {
|
|
403
493
|
try {
|
|
404
494
|
const script =
|
|
405
495
|
'$p = Get-CimInstance Win32_Process -Filter "ProcessId=' +
|
|
@@ -420,6 +510,36 @@ async function getProcessInfo(pid: number): Promise<{ name: string; commandLine:
|
|
|
420
510
|
}
|
|
421
511
|
}
|
|
422
512
|
|
|
513
|
+
/** Имя процесса и командная строка через ps (macOS/Linux). */
|
|
514
|
+
async function getProcessInfoPosix(
|
|
515
|
+
pid: number
|
|
516
|
+
): Promise<{ name: string; commandLine: string } | null> {
|
|
517
|
+
try {
|
|
518
|
+
// NOTE: на Linux у Node главный поток помечен как "MainThread", поэтому
|
|
519
|
+
// имя берём из argv[0] командной строки (это полный путь к бинарнику),
|
|
520
|
+
// а comm используем только как запасной вариант.
|
|
521
|
+
const { stdout: argsOut } = await execFileAsync("ps", ["-p", String(pid), "-o", "args="], {
|
|
522
|
+
windowsHide: true,
|
|
523
|
+
});
|
|
524
|
+
const args = argsOut.trim();
|
|
525
|
+
const argv0 = args.split(/\s+/)[0]?.replace(/^["']|["']$/g, "") ?? "";
|
|
526
|
+
let name = argv0.split(/[\\/]/).pop() ?? "";
|
|
527
|
+
|
|
528
|
+
if (!name) {
|
|
529
|
+
const { stdout: commOut } = await execFileAsync("ps", ["-p", String(pid), "-o", "comm="], {
|
|
530
|
+
windowsHide: true,
|
|
531
|
+
});
|
|
532
|
+
const comm = commOut.trim();
|
|
533
|
+
if (!comm) return null;
|
|
534
|
+
name = comm.split(/[\\/]/).pop() || comm;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
return { name, commandLine: args };
|
|
538
|
+
} catch {
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
423
543
|
/** Проверяет по маркер-заголовку, что на порту отвечает наш дашборд. */
|
|
424
544
|
async function isOwnDashboardOn(port: number): Promise<boolean> {
|
|
425
545
|
try {
|
|
@@ -495,24 +615,36 @@ async function handleRequest(
|
|
|
495
615
|
pathname === "/api/tasks" ||
|
|
496
616
|
pathname === "/api/history" ||
|
|
497
617
|
pathname === "/api/metrics" ||
|
|
618
|
+
pathname === "/api/summary" ||
|
|
498
619
|
pathname === "/api/models-analysis" ||
|
|
499
620
|
pathname === "/api/analytics" ||
|
|
500
621
|
pathname === "/api/history/export" ||
|
|
501
622
|
pathname === "/api/export-db" ||
|
|
502
623
|
pathname === "/api/workspaces" ||
|
|
503
624
|
pathname === "/api/health" ||
|
|
625
|
+
pathname === "/api/logs" ||
|
|
626
|
+
pathname === "/metrics" ||
|
|
504
627
|
/^\/api\/dry-run\//.test(pathname) ||
|
|
505
628
|
/^\/api\/matrix\//.test(pathname);
|
|
506
629
|
if (knownGet && req.method !== "GET") {
|
|
507
630
|
sendJson(res, 405, { error: "Method not allowed" });
|
|
508
631
|
return;
|
|
509
632
|
}
|
|
510
|
-
const knownPost =
|
|
633
|
+
const knownPost =
|
|
634
|
+
/^\/api\/(run|delete|hooks|cancel-matrix)\//.test(pathname) ||
|
|
635
|
+
pathname === "/api/matrix-cleanup";
|
|
511
636
|
if (knownPost && req.method !== "POST") {
|
|
512
637
|
sendJson(res, 405, { error: "Method not allowed" });
|
|
513
638
|
return;
|
|
514
639
|
}
|
|
515
640
|
|
|
641
|
+
// Браузер всегда просит иконку. Отвечаем 204, чтобы не засорять консоль 404.
|
|
642
|
+
if (req.method === "GET" && pathname === "/favicon.ico") {
|
|
643
|
+
res.writeHead(204);
|
|
644
|
+
res.end();
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
|
|
516
648
|
// Статический HTML-файл — страница дашборда.
|
|
517
649
|
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
518
650
|
send(res, 200, "text/html; charset=utf-8", renderPage());
|
|
@@ -534,6 +666,53 @@ async function handleRequest(
|
|
|
534
666
|
return;
|
|
535
667
|
}
|
|
536
668
|
|
|
669
|
+
if (req.method === "GET" && pathname === "/metrics") {
|
|
670
|
+
send(res, 200, PROMETHEUS_CONTENT_TYPE, renderPrometheusMetrics());
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// Машиночитаемые логи запусков (Спринт 22): JSONL + фильтры.
|
|
675
|
+
if (req.method === "GET" && pathname === "/api/logs") {
|
|
676
|
+
const task = url.searchParams.get("task") ?? undefined;
|
|
677
|
+
const status = url.searchParams.get("status") ?? undefined;
|
|
678
|
+
const event = url.searchParams.get("event") ?? undefined;
|
|
679
|
+
const since = url.searchParams.get("since") ?? undefined;
|
|
680
|
+
const until = url.searchParams.get("until") ?? undefined;
|
|
681
|
+
const limitRaw = Number(url.searchParams.get("limit") ?? 200);
|
|
682
|
+
if (since && Number.isNaN(Date.parse(since))) {
|
|
683
|
+
sendJson(res, 400, { error: "Некорректный параметр since: ожидается ISO-дата." });
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (until && Number.isNaN(Date.parse(until))) {
|
|
687
|
+
sendJson(res, 400, { error: "Некорректный параметр until: ожидается ISO-дата." });
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const limit = Number.isFinite(limitRaw)
|
|
691
|
+
? Math.max(1, Math.min(5000, Math.floor(limitRaw)))
|
|
692
|
+
: 200;
|
|
693
|
+
const result = readStructuredLogs({ task, status, event, since, until, limit });
|
|
694
|
+
if ((url.searchParams.get("format") || "").toLowerCase() === "jsonl") {
|
|
695
|
+
const body = result.records.map((record) => JSON.stringify(record)).join("\n");
|
|
696
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
697
|
+
sendAttachment(
|
|
698
|
+
res,
|
|
699
|
+
200,
|
|
700
|
+
"application/x-ndjson; charset=utf-8",
|
|
701
|
+
body ? `${body}\n` : "",
|
|
702
|
+
`logs-${stamp}.jsonl`
|
|
703
|
+
);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
sendJson(res, 200, {
|
|
707
|
+
records: result.records,
|
|
708
|
+
total: result.total,
|
|
709
|
+
malformed: result.malformed,
|
|
710
|
+
limit,
|
|
711
|
+
filters: { task: task ?? null, status: status ?? null, event: event ?? null, since: since ?? null, until: until ?? null },
|
|
712
|
+
});
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
|
|
537
716
|
if (req.method === "GET" && pathname === "/api/tasks") {
|
|
538
717
|
const tasks = await collectTasksWithMetrics(deps);
|
|
539
718
|
sendJson(res, 200, { tasks });
|
|
@@ -618,8 +797,26 @@ async function handleRequest(
|
|
|
618
797
|
}
|
|
619
798
|
|
|
620
799
|
if (req.method === "GET" && pathname === "/api/history") {
|
|
621
|
-
|
|
622
|
-
|
|
800
|
+
// Фильтры как у RPC get_history: имя задачи и статус. limit — необязательный.
|
|
801
|
+
const taskFilter = (url.searchParams.get("taskName") ?? url.searchParams.get("task") ?? "")
|
|
802
|
+
.trim()
|
|
803
|
+
.toLowerCase();
|
|
804
|
+
const statusFilter = (url.searchParams.get("status") ?? "").trim().toLowerCase();
|
|
805
|
+
const limitRaw = Number(url.searchParams.get("limit") ?? 200);
|
|
806
|
+
const limit = Number.isFinite(limitRaw)
|
|
807
|
+
? Math.max(1, Math.min(10000, Math.floor(limitRaw)))
|
|
808
|
+
: 200;
|
|
809
|
+
let records = await loadHistory();
|
|
810
|
+
if (taskFilter) {
|
|
811
|
+
records = records.filter((record) => record.taskName.toLowerCase() === taskFilter);
|
|
812
|
+
}
|
|
813
|
+
if (statusFilter) {
|
|
814
|
+
records = records.filter(
|
|
815
|
+
(record) => String(record.status).toLowerCase() === statusFilter
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
const total = records.length;
|
|
819
|
+
sendJson(res, 200, { records: records.slice(0, limit), total, limit });
|
|
623
820
|
return;
|
|
624
821
|
}
|
|
625
822
|
|
|
@@ -653,16 +850,26 @@ async function handleRequest(
|
|
|
653
850
|
return;
|
|
654
851
|
}
|
|
655
852
|
|
|
656
|
-
// Экспорт истории: CSV (для Excel)
|
|
853
|
+
// Экспорт истории: CSV (для Excel), JSON (для скриптов) или OTLP/JSON.
|
|
657
854
|
if (req.method === "GET" && pathname === "/api/history/export") {
|
|
658
855
|
const format = (url.searchParams.get("format") || "csv").toLowerCase();
|
|
659
|
-
if (format !== "csv" && format !== "json") {
|
|
660
|
-
sendJson(res, 400, {
|
|
856
|
+
if (format !== "csv" && format !== "json" && format !== "otlp") {
|
|
857
|
+
sendJson(res, 400, {
|
|
858
|
+
error: "Неподдерживаемый формат экспорта. Допустимые: csv, json, otlp.",
|
|
859
|
+
});
|
|
661
860
|
return;
|
|
662
861
|
}
|
|
663
862
|
const records = getHistory(null, 100000);
|
|
664
863
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
665
|
-
if (format === "
|
|
864
|
+
if (format === "otlp") {
|
|
865
|
+
sendAttachment(
|
|
866
|
+
res,
|
|
867
|
+
200,
|
|
868
|
+
"application/json; charset=utf-8",
|
|
869
|
+
JSON.stringify(buildOtlpExport(records), null, 2),
|
|
870
|
+
`history-${stamp}.otlp.json`
|
|
871
|
+
);
|
|
872
|
+
} else if (format === "json") {
|
|
666
873
|
sendAttachment(
|
|
667
874
|
res,
|
|
668
875
|
200,
|
|
@@ -728,6 +935,107 @@ async function handleRequest(
|
|
|
728
935
|
return;
|
|
729
936
|
}
|
|
730
937
|
|
|
938
|
+
// Входящий webhook-триггер (Спринт 22): POST /api/hooks/:task?token=…
|
|
939
|
+
const hookMatch = req.method === "POST" && pathname.match(/^\/api\/hooks\/(.+)$/);
|
|
940
|
+
if (hookMatch) {
|
|
941
|
+
const taskName = hookMatch[1].replace(/\/+$/, "").trim();
|
|
942
|
+
const remote = req.socket.remoteAddress ?? null;
|
|
943
|
+
const declaredBytes = Number(req.headers["content-length"]) || 0;
|
|
944
|
+
const timestampHeader = req.headers["x-scheduler-timestamp"];
|
|
945
|
+
const timestamp = Array.isArray(timestampHeader)
|
|
946
|
+
? timestampHeader[0] ?? null
|
|
947
|
+
: timestampHeader ?? null;
|
|
948
|
+
const logHook = (
|
|
949
|
+
httpStatus: number,
|
|
950
|
+
status: "accepted" | "rejected",
|
|
951
|
+
reason?: string,
|
|
952
|
+
payloadBytes = declaredBytes
|
|
953
|
+
) => {
|
|
954
|
+
appendStructuredLog({
|
|
955
|
+
event: "hook.received",
|
|
956
|
+
task: taskName || undefined,
|
|
957
|
+
status,
|
|
958
|
+
source: "hook",
|
|
959
|
+
httpStatus,
|
|
960
|
+
remote,
|
|
961
|
+
payloadBytes,
|
|
962
|
+
reason,
|
|
963
|
+
});
|
|
964
|
+
};
|
|
965
|
+
|
|
966
|
+
if (!taskName) {
|
|
967
|
+
logHook(400, "rejected", "Не передано имя задачи.");
|
|
968
|
+
sendJson(res, 400, { success: false, error: "Не передано имя задачи." });
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const settings = await loadSettings();
|
|
973
|
+
const hooks = settings.integrations.hooks;
|
|
974
|
+
if (!hooks.enabled) {
|
|
975
|
+
logHook(403, "rejected", "Входящие webhook-триггеры отключены.");
|
|
976
|
+
sendJson(res, 403, { success: false, error: "Входящие webhook-триггеры отключены." });
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
const bodyResult = await readRequestBody(req, hooks.maxBodyBytes);
|
|
981
|
+
if (!bodyResult.ok) {
|
|
982
|
+
logHook(bodyResult.status, "rejected", bodyResult.error, declaredBytes);
|
|
983
|
+
sendJson(res, bodyResult.status, { success: false, error: bodyResult.error });
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
const token = url.searchParams.get("token") ?? extractHookToken(req.headers);
|
|
988
|
+
const signature = extractHookSignature(req.headers);
|
|
989
|
+
const auth = authenticateHookRequest({
|
|
990
|
+
settings: hooks,
|
|
991
|
+
token,
|
|
992
|
+
signature,
|
|
993
|
+
timestamp,
|
|
994
|
+
body: bodyResult.body,
|
|
995
|
+
});
|
|
996
|
+
if (!auth.ok) {
|
|
997
|
+
logHook(auth.status, "rejected", auth.error, bodyResult.body.length);
|
|
998
|
+
sendJson(res, auth.status, { success: false, error: auth.error });
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
let tasks: Awaited<ReturnType<DashboardDeps["getTasks"]>>;
|
|
1003
|
+
try {
|
|
1004
|
+
tasks = await deps.getTasks();
|
|
1005
|
+
} catch (err: any) {
|
|
1006
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1007
|
+
logHook(500, "rejected", `Не удалось получить список задач: ${message}`, bodyResult.body.length);
|
|
1008
|
+
sendJson(res, 500, { success: false, error: message });
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
const key = taskName.toLowerCase();
|
|
1012
|
+
const task = tasks.find((item) => String(item.name).toLowerCase() === key);
|
|
1013
|
+
if (!task) {
|
|
1014
|
+
logHook(404, "rejected", `Задача "${taskName}" не найдена.`, bodyResult.body.length);
|
|
1015
|
+
sendJson(res, 404, { success: false, error: `Задача "${taskName}" не найдена.` });
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
try {
|
|
1020
|
+
const result = await deps.runTask(task.name);
|
|
1021
|
+
const message = result?.alreadyRunning
|
|
1022
|
+
? `Задача "${task.name}" уже выполняется.`
|
|
1023
|
+
: `Задача "${task.name}" запущена по webhook.`;
|
|
1024
|
+
logHook(202, "accepted", undefined, bodyResult.body.length);
|
|
1025
|
+
sendJson(res, 202, {
|
|
1026
|
+
success: true,
|
|
1027
|
+
task: task.name,
|
|
1028
|
+
alreadyRunning: Boolean(result?.alreadyRunning),
|
|
1029
|
+
message,
|
|
1030
|
+
});
|
|
1031
|
+
} catch (err: any) {
|
|
1032
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1033
|
+
logHook(500, "rejected", message, bodyResult.body.length);
|
|
1034
|
+
sendJson(res, 500, { success: false, error: message });
|
|
1035
|
+
}
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
731
1039
|
// Запуск задачи: POST /api/run/:name (имя URL-кодируется на клиенте).
|
|
732
1040
|
const runMatch = req.method === "POST" && pathname.match(/^\/api\/run\/(.+)$/);
|
|
733
1041
|
if (runMatch) {
|
|
@@ -920,16 +1228,22 @@ async function collectTasksWithMetrics(deps: DashboardDeps) {
|
|
|
920
1228
|
for (const r of history) {
|
|
921
1229
|
const key = String(r.taskName || "").toLowerCase();
|
|
922
1230
|
if (!key) continue;
|
|
923
|
-
const m = byTask.get(key) ?? { total: 0, success: 0, error: 0 };
|
|
1231
|
+
const m = byTask.get(key) ?? { total: 0, success: 0, error: 0, partial: 0 };
|
|
924
1232
|
m.total += 1;
|
|
925
1233
|
if (r.status === "success") m.success += 1;
|
|
1234
|
+
else if (r.status === "partial") m.partial += 1;
|
|
926
1235
|
else m.error += 1;
|
|
927
1236
|
byTask.set(key, m);
|
|
928
1237
|
}
|
|
929
1238
|
|
|
930
1239
|
return tasks.map((t) => ({
|
|
931
1240
|
...t,
|
|
932
|
-
metrics: byTask.get(String(t.name).toLowerCase()) ?? {
|
|
1241
|
+
metrics: byTask.get(String(t.name).toLowerCase()) ?? {
|
|
1242
|
+
total: 0,
|
|
1243
|
+
success: 0,
|
|
1244
|
+
error: 0,
|
|
1245
|
+
partial: 0,
|
|
1246
|
+
},
|
|
933
1247
|
}));
|
|
934
1248
|
}
|
|
935
1249
|
|
|
@@ -947,11 +1261,14 @@ function renderPage(): string {
|
|
|
947
1261
|
<title>${getSchedulerTitle()} — Веб-дашборд</title>
|
|
948
1262
|
<style>
|
|
949
1263
|
:root {
|
|
1264
|
+
color-scheme: dark;
|
|
950
1265
|
--bg1: #0f172a; --bg2: #000000; --panel: #141c2b; --panel2: #1b2436;
|
|
951
1266
|
--border: #24314a; --text: #e6ecf5; --muted: #8fa0b8;
|
|
952
1267
|
--accent: #7ec8fa; --ok: #34c759; --err: #ff5a5f; --run: #f5a623;
|
|
953
1268
|
}
|
|
954
1269
|
* { box-sizing: border-box; }
|
|
1270
|
+
/* Фон задаём и на html: иначе при короткой странице снизу видна белая полоса. */
|
|
1271
|
+
html { background: var(--bg2); }
|
|
955
1272
|
html, body { margin: 0; padding: 0; }
|
|
956
1273
|
body {
|
|
957
1274
|
font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, sans-serif;
|
|
@@ -968,16 +1285,20 @@ function renderPage(): string {
|
|
|
968
1285
|
}
|
|
969
1286
|
.wrap { position: relative; z-index: 1; max-width: 1740px; margin: 0 auto; padding: 28px 20px 60px; }
|
|
970
1287
|
.table-scroll { overflow-x: auto; }
|
|
1288
|
+
/* Подсказка о горизонтальном скролле: на широких экранах таблица влезает целиком. */
|
|
1289
|
+
.scroll-hint { display: none; margin-top: 6px; font-size: 11px; color: var(--muted); }
|
|
1290
|
+
@media (max-width: 1000px) { .scroll-hint { display: block; } }
|
|
971
1291
|
header { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 22px; }
|
|
972
1292
|
h1 { margin: 0; font-size: 24px; font-weight: 800; letter-spacing: .2px; }
|
|
973
1293
|
.sub { margin-top: 5px; font-size: 11px; font-weight: 600; letter-spacing: 1.2px; text-transform: uppercase; color: var(--muted); }
|
|
974
1294
|
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 22px; }
|
|
975
|
-
@media (min-width: 900px) { .cards { grid-template-columns: repeat(
|
|
1295
|
+
@media (min-width: 900px) { .cards { grid-template-columns: repeat(4, 1fr); } }
|
|
1296
|
+
@media (min-width: 1200px) { .cards { grid-template-columns: repeat(7, 1fr); } }
|
|
976
1297
|
@media (max-width: 520px) { .cards { grid-template-columns: repeat(2, 1fr); } }
|
|
977
1298
|
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; min-width: 0; }
|
|
978
1299
|
.card .num { font-size: 26px; font-weight: 800; }
|
|
979
1300
|
.card .lbl { margin-top: 2px; font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; }
|
|
980
|
-
.ok { color: var(--ok); } .err { color: var(--err); } .neu { color: var(--accent); }
|
|
1301
|
+
.ok { color: var(--ok); } .err { color: var(--err); } .neu { color: var(--accent); } .run { color: var(--run); }
|
|
981
1302
|
table { width: 100%; border-collapse: collapse; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
|
|
982
1303
|
th, td { padding: 9px 9px; text-align: left; font-size: 13px; border-bottom: 1px solid var(--border); vertical-align: middle; }
|
|
983
1304
|
th { background: var(--panel2); color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .8px; }
|
|
@@ -991,10 +1312,10 @@ function renderPage(): string {
|
|
|
991
1312
|
.badge.okb { background: rgba(52, 199, 89, .14); color: var(--ok); }
|
|
992
1313
|
.badge.errb { background: rgba(255, 90, 95, .14); color: var(--err); }
|
|
993
1314
|
.badge.unk { background: rgba(143, 160, 184, .14); color: var(--muted); }
|
|
994
|
-
.badge.part { background: rgba(255, 159, 10, .14); color:
|
|
1315
|
+
.badge.part { background: rgba(255, 159, 10, .14); color: var(--run); }
|
|
995
1316
|
.matrix-toggle { background: transparent; border: none; color: var(--muted); cursor: pointer; padding: 0 2px; font-size: 12px; }
|
|
996
1317
|
.matrix-toggle:hover { color: var(--accent); }
|
|
997
|
-
.matrix-badge { font-size: 11px; color:
|
|
1318
|
+
.matrix-badge { font-size: 11px; color: var(--run); white-space: nowrap; }
|
|
998
1319
|
.clone-badge { font-size: 11px; color: var(--muted); white-space: nowrap; }
|
|
999
1320
|
tr.clone-row td { background: rgba(126, 200, 250, 0.03); }
|
|
1000
1321
|
tr.clone-row .name { padding-left: 26px; font-weight: 500; color: #cfd7e3; }
|
|
@@ -1011,7 +1332,8 @@ function renderPage(): string {
|
|
|
1011
1332
|
.an-kpis { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 12px; font-size: 12px; color: var(--muted); }
|
|
1012
1333
|
.an-kpis b { color: var(--text); font-size: 14px; }
|
|
1013
1334
|
.an-chart { display: flex; align-items: flex-end; gap: 4px; height: 120px; padding: 6px 0 0; border-bottom: 1px solid var(--border); overflow-x: auto; }
|
|
1014
|
-
|
|
1335
|
+
/* min-width: подпись даты "MM-DD" не наезжает на соседнюю; на узком экране график скроллится. */
|
|
1336
|
+
.an-bar { flex: 1 1 0; min-width: 34px; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%; cursor: default; }
|
|
1015
1337
|
.an-bar-fill { width: 100%; border-radius: 3px 3px 0 0; background: var(--accent); opacity: .85; }
|
|
1016
1338
|
.an-label { font-size: 9px; color: var(--muted); margin-top: 4px; white-space: nowrap; }
|
|
1017
1339
|
.an-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 14px; }
|
|
@@ -1039,6 +1361,17 @@ function renderPage(): string {
|
|
|
1039
1361
|
.wi-table .wi-model { color: #c084fc; }
|
|
1040
1362
|
.graph { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 12px 16px; margin-bottom: 16px; }
|
|
1041
1363
|
.graph-title { font-size: 11px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; color: var(--muted); margin-bottom: 6px; }
|
|
1364
|
+
.graph-hint { font-size: 11px; color: var(--muted); margin-bottom: 8px; }
|
|
1365
|
+
.graph-scroll { overflow-x: auto; overflow-y: hidden; padding-bottom: 4px; }
|
|
1366
|
+
.graph-canvas { position: relative; }
|
|
1367
|
+
.graph-node { position: absolute; box-sizing: border-box; display: flex; flex-direction: column; justify-content: center; gap: 2px; padding: 6px 9px; background: var(--bg2); border: 1px solid var(--border); border-left: 3px solid var(--muted); border-radius: 8px; font-size: 12px; }
|
|
1368
|
+
.graph-node .g-name { color: var(--text); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1369
|
+
.graph-node .g-meta { color: var(--muted); font-size: 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
1370
|
+
.graph-node.okg { border-left-color: #3fb950; }
|
|
1371
|
+
.graph-node.errg { border-left-color: #ff3b30; }
|
|
1372
|
+
.graph-node.partg { border-left-color: #f5a623; }
|
|
1373
|
+
.graph-node.rung { border-left-color: #58a6ff; }
|
|
1374
|
+
.graph-edge { fill: none; stroke: var(--border); stroke-width: 1.5; }
|
|
1042
1375
|
.chain-line { font-size: 13px; padding: 3px 0; }
|
|
1043
1376
|
.chain-line .dep { color: var(--accent); }
|
|
1044
1377
|
.chain-line .arrow { color: var(--muted); margin: 0 6px; }
|
|
@@ -1071,6 +1404,28 @@ function renderPage(): string {
|
|
|
1071
1404
|
.toast { background: var(--panel2); border: 1px solid var(--border); border-radius: 8px; padding: 10px 14px; font-size: 12px; box-shadow: 0 6px 18px rgba(0,0,0,.4); }
|
|
1072
1405
|
.toast.ok2 { border-color: rgba(52,199,89,.5); }
|
|
1073
1406
|
.toast.err2 { border-color: rgba(255,90,95,.5); }
|
|
1407
|
+
/* Светлая тема: переменные темы + точечные правки для цветов, которые
|
|
1408
|
+
заданы не через var(). Тёмная остаётся по умолчанию. */
|
|
1409
|
+
@media (prefers-color-scheme: light) {
|
|
1410
|
+
:root {
|
|
1411
|
+
color-scheme: light;
|
|
1412
|
+
--bg1: #f5f8fc; --bg2: #ffffff; --panel: #ffffff; --panel2: #eef3f9;
|
|
1413
|
+
--border: #cbd6e2; --text: #17202b; --muted: #56667a;
|
|
1414
|
+
--accent: #0b6ea8; --ok: #167a37; --err: #bc2c22; --run: #9a5a00;
|
|
1415
|
+
}
|
|
1416
|
+
html { background: var(--bg2); }
|
|
1417
|
+
.snow { color: #9cc7ea; opacity: .4; }
|
|
1418
|
+
tr.clone-row .name { color: #3c4b5e; }
|
|
1419
|
+
.model, .hist-model, .wi-table .wi-model { color: #7b3fb0; }
|
|
1420
|
+
.graph-node { background: var(--panel2); }
|
|
1421
|
+
.toast { box-shadow: 0 6px 18px rgba(20, 40, 70, .18); }
|
|
1422
|
+
}
|
|
1423
|
+
a:focus-visible, button:focus-visible, [tabindex]:focus-visible {
|
|
1424
|
+
outline: 2px solid var(--accent); outline-offset: 2px;
|
|
1425
|
+
}
|
|
1426
|
+
@media (prefers-reduced-motion: reduce) {
|
|
1427
|
+
.snow { display: none; }
|
|
1428
|
+
}
|
|
1074
1429
|
</style>
|
|
1075
1430
|
</head>
|
|
1076
1431
|
<body>
|
|
@@ -1092,7 +1447,8 @@ function renderPage(): string {
|
|
|
1092
1447
|
<div class="cards">
|
|
1093
1448
|
<div class="card"><div class="num neu" id="m-total">—</div><div class="lbl">Всего запусков</div></div>
|
|
1094
1449
|
<div class="card"><div class="num ok" id="m-success">—</div><div class="lbl">Успешных</div></div>
|
|
1095
|
-
<div class="card"><div class="num err" id="m-error">—</div><div class="lbl"
|
|
1450
|
+
<div class="card" title="Ошибки и таймауты. Частичные выполнения считаются отдельно."><div class="num err" id="m-error">—</div><div class="lbl">Ошибок</div></div>
|
|
1451
|
+
<div class="card" title="Частичные выполнения (partial): ответ получен, но проверка не прошла"><div class="num run" id="m-partial">—</div><div class="lbl">Частичных</div></div>
|
|
1096
1452
|
<div class="card"><div class="num" id="m-tasks">—</div><div class="lbl">Задач в системе</div></div>
|
|
1097
1453
|
<div class="card"><div class="num neu" id="m-tokens">—</div><div class="lbl">Всего токенов</div></div>
|
|
1098
1454
|
<div class="card"><div class="num" id="m-cost">—</div><div class="lbl">Примерная стоимость</div></div>
|
|
@@ -1100,26 +1456,30 @@ function renderPage(): string {
|
|
|
1100
1456
|
|
|
1101
1457
|
<div class="graph" id="graph" style="display:none">
|
|
1102
1458
|
<div class="graph-title">🔗 Граф зависимостей (DAG)</div>
|
|
1103
|
-
<div
|
|
1459
|
+
<div class="graph-hint">Слева — задачи без зависимостей, справа — задачи, которые ждут их успешного завершения. Граф можно прокручивать по горизонтали.</div>
|
|
1460
|
+
<div class="graph-scroll" id="graph-scroll" role="region" aria-label="Граф зависимостей задач" tabindex="0">
|
|
1461
|
+
<div id="graph-lines"></div>
|
|
1462
|
+
</div>
|
|
1104
1463
|
</div>
|
|
1105
1464
|
|
|
1106
1465
|
<div class="ws-summary" id="ws-summary">📦 0 workspace · 0 задач</div>
|
|
1107
|
-
<div class="ws-tabs" id="ws-tabs"></div>
|
|
1466
|
+
<div class="ws-tabs" id="ws-tabs" role="group" aria-label="Фильтр задач по workspace"></div>
|
|
1108
1467
|
|
|
1109
1468
|
<div class="table-scroll">
|
|
1110
|
-
<table>
|
|
1469
|
+
<table aria-label="Задачи планировщика">
|
|
1111
1470
|
<thead>
|
|
1112
1471
|
<tr>
|
|
1113
|
-
<th>Имя</th><th>Статус</th><th>Cron</th><th>📦 Workspace</th><th>Модель</th><th>Приоритет</th><th>Зависимости</th><th>Метрики</th><th>Действия</th>
|
|
1472
|
+
<th scope="col">Имя</th><th scope="col">Статус</th><th scope="col">Cron</th><th scope="col">📦 Workspace</th><th scope="col">Модель</th><th scope="col">Приоритет</th><th scope="col">Зависимости</th><th scope="col">Метрики</th><th scope="col">Действия</th>
|
|
1114
1473
|
</tr>
|
|
1115
1474
|
</thead>
|
|
1116
1475
|
<tbody id="rows"><tr><td colspan="9" class="empty">Загрузка…</td></tr></tbody>
|
|
1117
1476
|
</table>
|
|
1118
1477
|
</div>
|
|
1478
|
+
<div class="scroll-hint">↔ Таблица шире экрана — прокрутите её влево-вправо.</div>
|
|
1119
1479
|
|
|
1120
1480
|
<div class="hist">
|
|
1121
1481
|
<h2>📜 История выполнений</h2>
|
|
1122
|
-
<div id="history"><div class="empty">Загрузка…</div></div>
|
|
1482
|
+
<div id="history" aria-live="polite"><div class="empty">Загрузка…</div></div>
|
|
1123
1483
|
</div>
|
|
1124
1484
|
|
|
1125
1485
|
<div class="hist">
|
|
@@ -1146,7 +1506,7 @@ function renderPage(): string {
|
|
|
1146
1506
|
|
|
1147
1507
|
<footer>Данные обновляются автоматически каждые 5 секунд · <span id="server-url">http://localhost:3782</span> · <span class="db-badge">БД: ✅ SQLite (WAL)</span></footer>
|
|
1148
1508
|
</div>
|
|
1149
|
-
<div id="toast"></div>
|
|
1509
|
+
<div id="toast" role="status" aria-live="polite"></div>
|
|
1150
1510
|
|
|
1151
1511
|
<script>
|
|
1152
1512
|
(function () {
|
|
@@ -1159,6 +1519,14 @@ function renderPage(): string {
|
|
|
1159
1519
|
var activeWorkspace = 'all';
|
|
1160
1520
|
/** Раскрытые родители матриц (имя → true). */
|
|
1161
1521
|
var expandedMatrixParents = {};
|
|
1522
|
+
/** История: последний загруженный список и режим «показать все». */
|
|
1523
|
+
var lastHistory = [];
|
|
1524
|
+
var historyExpanded = false;
|
|
1525
|
+
// /api/metrics и /api/summary отдают один и тот же обработчик. По умолчанию
|
|
1526
|
+
// используем summary: некоторые антивирусы блокируют именно /api/metrics
|
|
1527
|
+
// (HTTP 499), и тогда в консоли появляется ошибка при каждой загрузке.
|
|
1528
|
+
var preferSummaryMetrics = true;
|
|
1529
|
+
var metricsFallbackLogged = false;
|
|
1162
1530
|
|
|
1163
1531
|
function esc(s) {
|
|
1164
1532
|
var d = document.createElement('div');
|
|
@@ -1246,11 +1614,24 @@ function renderPage(): string {
|
|
|
1246
1614
|
});
|
|
1247
1615
|
}
|
|
1248
1616
|
|
|
1249
|
-
function badge(status) {
|
|
1617
|
+
function badge(status, task, historyMode) {
|
|
1618
|
+
if (task && task.orphaned) {
|
|
1619
|
+
return '<span class="badge unk" title="Определение есть в БД, но задачи нет в планировщике ОС">🧟 Нет в планировщике</span>';
|
|
1620
|
+
}
|
|
1621
|
+
if (task && task.paused) {
|
|
1622
|
+
return '<span class="badge unk" title="Задача поставлена на паузу">⏸ Пауза</span>';
|
|
1623
|
+
}
|
|
1250
1624
|
if (status === 'running') return '<span class="badge run">🟡 Выполняется</span>';
|
|
1251
|
-
if (status === 'success')
|
|
1625
|
+
if (status === 'success') {
|
|
1626
|
+
return historyMode
|
|
1627
|
+
? '<span class="badge okb">✅ Успех</span>'
|
|
1628
|
+
: '<span class="badge okb">🟢 Готова</span>';
|
|
1629
|
+
}
|
|
1252
1630
|
if (status === 'error') return '<span class="badge errb">🔴 Ошибка</span>';
|
|
1253
1631
|
if (status === 'partial') return '<span class="badge part">🟠 Частично</span>';
|
|
1632
|
+
if (status === 'idle') {
|
|
1633
|
+
return '<span class="badge unk" title="Задача создана, но ещё ни разу не запускалась">⚪ Не запускалась</span>';
|
|
1634
|
+
}
|
|
1254
1635
|
return '<span class="badge unk">⚪ Неизвестно</span>';
|
|
1255
1636
|
}
|
|
1256
1637
|
|
|
@@ -1260,7 +1641,7 @@ function renderPage(): string {
|
|
|
1260
1641
|
if (!t.isMatrixParent || !s) return '';
|
|
1261
1642
|
var color = s.status === 'success' ? 'var(--ok)'
|
|
1262
1643
|
: s.status === 'error' ? 'var(--err)'
|
|
1263
|
-
: s.status === 'partial' ? '
|
|
1644
|
+
: s.status === 'partial' ? 'var(--run)'
|
|
1264
1645
|
: 'var(--run)';
|
|
1265
1646
|
return '<div class="matrix-badge" style="color:' + color + '" title="' + esc(s.message) + '">' +
|
|
1266
1647
|
'📦 Matrix: ' + s.successCount + '/' + s.totalCount + ' успешных' +
|
|
@@ -1270,8 +1651,10 @@ function renderPage(): string {
|
|
|
1270
1651
|
}
|
|
1271
1652
|
|
|
1272
1653
|
function metricsHtml(m) {
|
|
1273
|
-
var mm = m || { total: 0, success: 0, error: 0 };
|
|
1274
|
-
return 'Всего: <b>' + mm.total + '</b> · ✅ <b>' + mm.success + '</b>
|
|
1654
|
+
var mm = m || { total: 0, success: 0, error: 0, partial: 0 };
|
|
1655
|
+
return 'Всего: <b>' + mm.total + '</b> · ✅ <b>' + mm.success + '</b>' +
|
|
1656
|
+
' · <span title="Частичные выполнения (partial)" style="color:var(--run)">🟠 <b>' + (mm.partial || 0) + '</b></span>' +
|
|
1657
|
+
' · <span title="Ошибки и таймауты" style="color:var(--err)">⚠️ <b>' + mm.error + '</b></span>';
|
|
1275
1658
|
}
|
|
1276
1659
|
|
|
1277
1660
|
function depsHtml(t) {
|
|
@@ -1303,19 +1686,19 @@ function renderPage(): string {
|
|
|
1303
1686
|
function renderHistory(records) {
|
|
1304
1687
|
var box = document.getElementById('history');
|
|
1305
1688
|
if (!box) return;
|
|
1689
|
+
lastHistory = records || [];
|
|
1306
1690
|
if (!records || records.length === 0) {
|
|
1307
1691
|
box.innerHTML = '<div class="empty" style="padding:16px">Запусков пока нет.</div>';
|
|
1308
1692
|
return;
|
|
1309
1693
|
}
|
|
1310
1694
|
var html = '';
|
|
1311
|
-
var limit = Math.min(records.length, 10);
|
|
1695
|
+
var limit = historyExpanded ? records.length : Math.min(records.length, 10);
|
|
1312
1696
|
for (var i = 0; i < limit; i++) {
|
|
1313
1697
|
var r = records[i];
|
|
1314
|
-
var ok = r.status === 'success';
|
|
1315
1698
|
html += '<div class="hist-row">' +
|
|
1316
1699
|
'<span class="hist-time">' + esc(new Date(r.startedAt).toLocaleString('ru-RU')) + '</span>' +
|
|
1317
1700
|
'<span class="hist-task">' + esc(r.taskName) + '</span>' +
|
|
1318
|
-
|
|
1701
|
+
badge(r.status, null, true) +
|
|
1319
1702
|
'<span class="metrics">' + (r.durationMs != null ? r.durationMs + ' мс' : '—') + '</span>' +
|
|
1320
1703
|
(r.model ? '<span class="hist-model" title="Модель">🧠 ' + esc(r.model) + '</span>' : '') +
|
|
1321
1704
|
(r.preFlightStatus && r.preFlightStatus !== 'skipped'
|
|
@@ -1329,6 +1712,11 @@ function renderPage(): string {
|
|
|
1329
1712
|
(r.error ? '<span class="metrics" title="' + esc(r.error) + '">⚠ ' + esc(String(r.error).slice(0, 80)) + '</span>' : '') +
|
|
1330
1713
|
'</div>';
|
|
1331
1714
|
}
|
|
1715
|
+
if (records.length > 10) {
|
|
1716
|
+
html += '<div style="padding:10px 0 2px"><button class="btn" data-act="history-toggle">' +
|
|
1717
|
+
(historyExpanded ? 'Свернуть историю' : 'Показать все (' + records.length + ')') +
|
|
1718
|
+
'</button></div>';
|
|
1719
|
+
}
|
|
1332
1720
|
box.innerHTML = html;
|
|
1333
1721
|
}
|
|
1334
1722
|
|
|
@@ -1385,20 +1773,24 @@ function renderPage(): string {
|
|
|
1385
1773
|
for (var j = 0; j < daily.length; j++) {
|
|
1386
1774
|
var d = daily[j];
|
|
1387
1775
|
var h = d.total > 0 ? Math.max(3, Math.round((d.total / max) * 92)) : 2;
|
|
1388
|
-
var
|
|
1389
|
-
var
|
|
1776
|
+
var isPartialOnly = d.error === 0 && d.partial > 0;
|
|
1777
|
+
var color = d.total === 0 ? 'var(--border)' : (d.error > 0 ? 'var(--err)' : (isPartialOnly ? 'var(--run)' : 'var(--ok)'));
|
|
1778
|
+
var tip = d.date + ': всего ' + d.total + ', успех ' + d.success + ', ошибок ' + d.error + ', частично ' + d.partial + ', ' + money(d.costUsd);
|
|
1390
1779
|
bars += '<div class="an-bar" title="' + esc(tip) + '">' +
|
|
1391
1780
|
'<div class="an-bar-fill" style="height:' + h + '%' + ';background:' + esc(color) + '"></div>' +
|
|
1392
1781
|
'<div class="an-label">' + esc(String(d.date).slice(5)) + '</div>' +
|
|
1393
1782
|
'</div>';
|
|
1394
1783
|
}
|
|
1395
1784
|
chart.innerHTML = bars || '<div class="empty" style="padding:10px">Нет данных за период.</div>';
|
|
1785
|
+
// На узком экране график скроллится по горизонтали: показываем свежие дни,
|
|
1786
|
+
// а не пустую левую часть окна.
|
|
1787
|
+
chart.scrollLeft = chart.scrollWidth;
|
|
1396
1788
|
|
|
1397
1789
|
var topRows = an.topByCost || [];
|
|
1398
1790
|
if (topRows.length === 0) {
|
|
1399
1791
|
top.innerHTML = '<div class="empty" style="padding:10px">Нет запусков за период.</div>';
|
|
1400
1792
|
} else {
|
|
1401
|
-
var html = '<table class="an-table"><thead><tr><th>Задача</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
|
|
1793
|
+
var html = '<table class="an-table"><thead><tr><th scope="col">Задача</th><th scope="col">Запусков</th><th scope="col">Успех</th><th scope="col">Стоимость</th></tr></thead><tbody>';
|
|
1402
1794
|
for (var k = 0; k < topRows.length; k++) {
|
|
1403
1795
|
var row = topRows[k];
|
|
1404
1796
|
html += '<tr>' +
|
|
@@ -1415,7 +1807,7 @@ function renderPage(): string {
|
|
|
1415
1807
|
if (matrixRows.length === 0) {
|
|
1416
1808
|
matrices.innerHTML = '<div class="empty" style="padding:10px">Матриц за период не запускалось.</div>';
|
|
1417
1809
|
} else {
|
|
1418
|
-
var mhtml = '<table class="an-table"><thead><tr><th>Матрица</th><th>Клонов</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
|
|
1810
|
+
var mhtml = '<table class="an-table"><thead><tr><th scope="col">Матрица</th><th scope="col">Клонов</th><th scope="col">Запусков</th><th scope="col">Успех</th><th scope="col">Стоимость</th></tr></thead><tbody>';
|
|
1419
1811
|
for (var q = 0; q < matrixRows.length; q++) {
|
|
1420
1812
|
var m = matrixRows[q];
|
|
1421
1813
|
mhtml += '<tr>' +
|
|
@@ -1444,7 +1836,7 @@ function renderPage(): string {
|
|
|
1444
1836
|
}
|
|
1445
1837
|
|
|
1446
1838
|
var html = '<table class="wi-table"><thead><tr>' +
|
|
1447
|
-
'<th>Модель</th><th>Запусков</th><th>Токенов</th><th>Стоимость</th><th>Средняя длительность</th><th>Успешных</th>' +
|
|
1839
|
+
'<th scope="col">Модель</th><th scope="col">Запусков</th><th scope="col">Токенов</th><th scope="col">Стоимость</th><th scope="col">Средняя длительность</th><th scope="col">Успешных</th>' +
|
|
1448
1840
|
'</tr></thead><tbody>';
|
|
1449
1841
|
for (var i = 0; i < models.length; i++) {
|
|
1450
1842
|
var m = models[i];
|
|
@@ -1482,20 +1874,147 @@ function renderPage(): string {
|
|
|
1482
1874
|
var box = document.getElementById('graph-lines');
|
|
1483
1875
|
if (!graph || !box) return;
|
|
1484
1876
|
if (!tasks || tasks.length === 0) { graph.style.display = 'none'; return; }
|
|
1485
|
-
|
|
1877
|
+
|
|
1878
|
+
var known = {};
|
|
1486
1879
|
for (var i = 0; i < tasks.length; i++) {
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1880
|
+
known[String(tasks[i].name).toLowerCase()] = tasks[i];
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
// В граф включаем только задачи, связанные зависимостями, и все их
|
|
1884
|
+
// транзитивные предки. Одиночные задачи не превращают блок в свалку.
|
|
1885
|
+
var involved = {};
|
|
1886
|
+
function collect(name, depth) {
|
|
1887
|
+
var key = String(name).toLowerCase();
|
|
1888
|
+
if (depth > 40 || involved[key] || !known[key]) return;
|
|
1889
|
+
involved[key] = known[key];
|
|
1890
|
+
var deps = Array.isArray(known[key].dependsOn) ? known[key].dependsOn : [];
|
|
1891
|
+
for (var d = 0; d < deps.length; d++) collect(deps[d], depth + 1);
|
|
1892
|
+
}
|
|
1893
|
+
var hasEdges = false;
|
|
1894
|
+
for (var t = 0; t < tasks.length; t++) {
|
|
1895
|
+
var direct = Array.isArray(tasks[t].dependsOn) ? tasks[t].dependsOn : [];
|
|
1896
|
+
if (direct.length > 0) {
|
|
1897
|
+
hasEdges = true;
|
|
1898
|
+
collect(tasks[t].name, 0);
|
|
1493
1899
|
}
|
|
1494
|
-
html += '<div class="chain-line">' + parts.join(' <span class="arrow">+</span> ') +
|
|
1495
|
-
'<span class="arrow">➔</span><span class="target">[' + esc(t.name) + ']</span></div>';
|
|
1496
1900
|
}
|
|
1497
|
-
if (!
|
|
1498
|
-
|
|
1901
|
+
if (!hasEdges) { graph.style.display = 'none'; return; }
|
|
1902
|
+
|
|
1903
|
+
// Слои: уровень задачи = максимум по уровню зависимостей + 1.
|
|
1904
|
+
// visiting защищает от циклов в ошибочно настроенном DAG.
|
|
1905
|
+
var levels = {};
|
|
1906
|
+
var visiting = {};
|
|
1907
|
+
function levelOf(name) {
|
|
1908
|
+
var key = String(name).toLowerCase();
|
|
1909
|
+
if (levels[key] != null) return levels[key];
|
|
1910
|
+
if (visiting[key]) return 0;
|
|
1911
|
+
visiting[key] = true;
|
|
1912
|
+
var own = 0;
|
|
1913
|
+
var deps = Array.isArray(known[key] && known[key].dependsOn) ? known[key].dependsOn : [];
|
|
1914
|
+
for (var d = 0; d < deps.length; d++) {
|
|
1915
|
+
var depKey = String(deps[d]).toLowerCase();
|
|
1916
|
+
if (!known[depKey]) continue;
|
|
1917
|
+
own = Math.max(own, levelOf(depKey) + 1);
|
|
1918
|
+
}
|
|
1919
|
+
visiting[key] = false;
|
|
1920
|
+
levels[key] = own;
|
|
1921
|
+
return own;
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
var byLevel = {};
|
|
1925
|
+
var maxLevel = 0;
|
|
1926
|
+
for (var key in involved) {
|
|
1927
|
+
if (!Object.prototype.hasOwnProperty.call(involved, key)) continue;
|
|
1928
|
+
var level = levelOf(key);
|
|
1929
|
+
maxLevel = Math.max(maxLevel, level);
|
|
1930
|
+
if (!byLevel[level]) byLevel[level] = [];
|
|
1931
|
+
byLevel[level].push(involved[key]);
|
|
1932
|
+
}
|
|
1933
|
+
for (var l = 0; l <= maxLevel; l++) {
|
|
1934
|
+
if (byLevel[l]) byLevel[l].sort(function (a, b) { return String(a.name).localeCompare(String(b.name)); });
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
var NODE_W = 180;
|
|
1938
|
+
var NODE_H = 46;
|
|
1939
|
+
var GAP_X = 64;
|
|
1940
|
+
var GAP_Y = 18;
|
|
1941
|
+
var PAD = 10;
|
|
1942
|
+
var maxRows = 1;
|
|
1943
|
+
for (var rowLevel in byLevel) {
|
|
1944
|
+
if (byLevel[rowLevel].length > maxRows) maxRows = byLevel[rowLevel].length;
|
|
1945
|
+
}
|
|
1946
|
+
var width = PAD * 2 + (maxLevel + 1) * NODE_W + maxLevel * GAP_X;
|
|
1947
|
+
var height = PAD * 2 + maxRows * (NODE_H + GAP_Y) - GAP_Y;
|
|
1948
|
+
|
|
1949
|
+
var pos = {};
|
|
1950
|
+
for (var lv = 0; lv <= maxLevel; lv++) {
|
|
1951
|
+
var nodes = byLevel[lv] || [];
|
|
1952
|
+
for (var n = 0; n < nodes.length; n++) {
|
|
1953
|
+
pos[String(nodes[n].name).toLowerCase()] = {
|
|
1954
|
+
x: PAD + lv * (NODE_W + GAP_X),
|
|
1955
|
+
y: PAD + n * (NODE_H + GAP_Y),
|
|
1956
|
+
task: nodes[n]
|
|
1957
|
+
};
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
function shortLabel(value, max) {
|
|
1962
|
+
var text = String(value == null ? '' : value);
|
|
1963
|
+
return text.length > max ? text.slice(0, max - 1) + '…' : text;
|
|
1964
|
+
}
|
|
1965
|
+
function attr(value) {
|
|
1966
|
+
return esc(String(value == null ? '' : value)).replace(/"/g, '"');
|
|
1967
|
+
}
|
|
1968
|
+
function statusClass(status) {
|
|
1969
|
+
if (status === 'success') return ' okg';
|
|
1970
|
+
if (status === 'error' || status === 'timeout') return ' errg';
|
|
1971
|
+
if (status === 'partial') return ' partg';
|
|
1972
|
+
if (status === 'running') return ' rung';
|
|
1973
|
+
return '';
|
|
1974
|
+
}
|
|
1975
|
+
|
|
1976
|
+
var svg = '<svg width="' + width + '" height="' + height + '" style="position:absolute;left:0;top:0;pointer-events:none" aria-hidden="true">' +
|
|
1977
|
+
'<defs><marker id="dag-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">' +
|
|
1978
|
+
'<path d="M0,0 L8,4 L0,8 z" fill="#8b949e"></path></marker></defs>';
|
|
1979
|
+
for (var targetKey in pos) {
|
|
1980
|
+
if (!Object.prototype.hasOwnProperty.call(pos, targetKey)) continue;
|
|
1981
|
+
var target = pos[targetKey];
|
|
1982
|
+
var deps = Array.isArray(target.task.dependsOn) ? target.task.dependsOn : [];
|
|
1983
|
+
for (var di = 0; di < deps.length; di++) {
|
|
1984
|
+
var from = pos[String(deps[di]).toLowerCase()];
|
|
1985
|
+
if (!from || from.x >= target.x) continue;
|
|
1986
|
+
var x1 = from.x + NODE_W;
|
|
1987
|
+
var y1 = from.y + NODE_H / 2;
|
|
1988
|
+
var x2 = target.x;
|
|
1989
|
+
var y2 = target.y + NODE_H / 2;
|
|
1990
|
+
var bend = Math.max(24, (x2 - x1) / 2);
|
|
1991
|
+
svg += '<path class="graph-edge" d="M' + x1 + ',' + y1 +
|
|
1992
|
+
' C' + (x1 + bend) + ',' + y1 + ' ' + (x2 - bend) + ',' + y2 + ' ' + x2 + ',' + y2 +
|
|
1993
|
+
'" marker-end="url(#dag-arrow)"></path>';
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
svg += '</svg>';
|
|
1997
|
+
|
|
1998
|
+
var nodesHtml = '';
|
|
1999
|
+
for (var pKey in pos) {
|
|
2000
|
+
if (!Object.prototype.hasOwnProperty.call(pos, pKey)) continue;
|
|
2001
|
+
var node = pos[pKey];
|
|
2002
|
+
var nodeDeps = Array.isArray(node.task.dependsOn) ? node.task.dependsOn : [];
|
|
2003
|
+
var meta = nodeDeps.length > 0
|
|
2004
|
+
? '← ' + shortLabel(nodeDeps.join(', '), 30)
|
|
2005
|
+
: 'начальная задача';
|
|
2006
|
+
nodesHtml += '<div class="graph-node' + statusClass(node.task.status) + '" style="left:' + node.x +
|
|
2007
|
+
'px;top:' + node.y + 'px;width:' + NODE_W + 'px;height:' + NODE_H + 'px" title="' +
|
|
2008
|
+
attr(node.task.name + (nodeDeps.length ? ' · зависит от: ' + nodeDeps.join(', ') : '')) + '">' +
|
|
2009
|
+
'<span class="g-name">' + esc(shortLabel(node.task.name, 26)) + '</span>' +
|
|
2010
|
+
'<span class="g-meta">' + esc(meta) + '</span></div>';
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
var scroll = document.getElementById('graph-scroll');
|
|
2014
|
+
var scrollLeft = scroll ? scroll.scrollLeft : 0;
|
|
2015
|
+
box.innerHTML = '<div class="graph-canvas" style="width:' + width + 'px;height:' + height + 'px">' +
|
|
2016
|
+
svg + nodesHtml + '</div>';
|
|
2017
|
+
if (scroll) scroll.scrollLeft = scrollLeft;
|
|
1499
2018
|
graph.style.display = 'block';
|
|
1500
2019
|
}
|
|
1501
2020
|
|
|
@@ -1531,14 +2050,14 @@ function renderPage(): string {
|
|
|
1531
2050
|
(matrixCount ? ' · 📦 матриц: ' + matrixCount : '');
|
|
1532
2051
|
}
|
|
1533
2052
|
if (!box) return;
|
|
1534
|
-
var html = '<button class="ws-tab' + (activeWorkspace === 'all' ? ' active' : '') + '" data-ws="all">Все</button>';
|
|
2053
|
+
var html = '<button class="ws-tab' + (activeWorkspace === 'all' ? ' active' : '') + '" data-ws="all" aria-pressed="' + (activeWorkspace === 'all') + '">Все</button>';
|
|
1535
2054
|
for (var i = 0; i < workspaces.length; i++) {
|
|
1536
2055
|
var w = workspaces[i];
|
|
1537
2056
|
var color = w.color || '#8b949e';
|
|
1538
|
-
html += '<button class="ws-tab' + (activeWorkspace === w.id ? ' active' : '') + '" data-ws="' + esc(w.id) + '" style="color:' + esc(color) + '">📦 ' + esc(w.name) + '</button>';
|
|
2057
|
+
html += '<button class="ws-tab' + (activeWorkspace === w.id ? ' active' : '') + '" data-ws="' + esc(w.id) + '" aria-pressed="' + (activeWorkspace === w.id) + '" style="color:' + esc(color) + '">📦 ' + esc(w.name) + '</button>';
|
|
1539
2058
|
}
|
|
1540
|
-
html += '<button class="ws-tab' + (activeWorkspace === 'matrix' ? ' active' : '') + '" data-ws="matrix" title="Только родители матриц и их клоны">📦 Матрицы</button>';
|
|
1541
|
-
html += '<button class="ws-tab' + (activeWorkspace === 'none' ? ' active' : '') + '" data-ws="none">Без workspace</button>';
|
|
2059
|
+
html += '<button class="ws-tab' + (activeWorkspace === 'matrix' ? ' active' : '') + '" data-ws="matrix" aria-pressed="' + (activeWorkspace === 'matrix') + '" title="Только родители матриц и их клоны">📦 Матрицы</button>';
|
|
2060
|
+
html += '<button class="ws-tab' + (activeWorkspace === 'none' ? ' active' : '') + '" data-ws="none" aria-pressed="' + (activeWorkspace === 'none') + '">Без workspace</button>';
|
|
1542
2061
|
box.innerHTML = html;
|
|
1543
2062
|
}
|
|
1544
2063
|
|
|
@@ -1600,10 +2119,23 @@ function renderPage(): string {
|
|
|
1600
2119
|
|
|
1601
2120
|
/** Строка таблицы задач; клоны матрицы помечаются ↳ matrix <parent>. */
|
|
1602
2121
|
function taskRow(t, isClone, cloneCount, expanded) {
|
|
2122
|
+
var sessionBadge = t.session === 'reuse' || t.session === 'last'
|
|
2123
|
+
? '<span title="' + (t.session === 'reuse'
|
|
2124
|
+
? 'Переиспользуемая сессия OpenCode' + (t.sessionId ? ': ' + t.sessionId : '')
|
|
2125
|
+
: 'Продолжение последней сессии OpenCode (--continue)') +
|
|
2126
|
+
'" style="margin-left:6px;padding:1px 6px;border-radius:999px;border:1px solid #30d158;color:#30d158;font-size:11px">' +
|
|
2127
|
+
(t.session === 'reuse' ? '⟳ сессия' : '↪ продолжение') + '</span>'
|
|
2128
|
+
: '';
|
|
1603
2129
|
var cron = t.triggerType === 'file'
|
|
1604
2130
|
? '👁️ файл: ' + (t.watchPath || '')
|
|
1605
2131
|
: t.triggerType === 'mcp-event'
|
|
1606
2132
|
? '📡 ' + ((t.mcpEvent && t.mcpEvent.event) || 'MCP Event')
|
|
2133
|
+
: t.triggerType === 'once'
|
|
2134
|
+
? '⏱ ' + (function () {
|
|
2135
|
+
if (!t.runAt) return '—';
|
|
2136
|
+
var d = new Date(t.runAt);
|
|
2137
|
+
return isNaN(d.getTime()) ? t.runAt : d.toLocaleString('ru-RU');
|
|
2138
|
+
})()
|
|
1607
2139
|
: (t.schedule || '—');
|
|
1608
2140
|
var nameHtml = esc(t.name);
|
|
1609
2141
|
var matrixLimit = t.matrix && t.matrix.concurrency
|
|
@@ -1621,14 +2153,14 @@ function renderPage(): string {
|
|
|
1621
2153
|
if (isClone) {
|
|
1622
2154
|
nameHtml = '<span class="clone-badge">↳ matrix ' + esc(t.matrixParentId || '') + '</span><br>' + esc(t.name);
|
|
1623
2155
|
} else if (cloneCount > 0) {
|
|
1624
|
-
nameHtml = '<button class="matrix-toggle" data-matrix="' + esc(t.name) + '" title="Показать/скрыть клоны">' +
|
|
2156
|
+
nameHtml = '<button class="matrix-toggle" data-matrix="' + esc(t.name) + '" title="Показать/скрыть клоны" aria-label="Показать/скрыть клоны матрицы ' + esc(t.name) + '" aria-expanded="' + (!!expanded) + '">' +
|
|
1625
2157
|
(expanded ? '▾' : '▸') + '</button> ' + esc(t.name) +
|
|
1626
2158
|
'<div class="matrix-badge" title="' + esc(matrixTitle) + '">📦 Matrix (' + cloneCount + ')' + matrixLimit + '</div>';
|
|
1627
2159
|
}
|
|
1628
2160
|
return '<tr' + (isClone ? ' class="clone-row"' : '') + '>' +
|
|
1629
2161
|
'<td class="name" title="' + esc(t.name) + '">' + nameHtml + '</td>' +
|
|
1630
|
-
'<td>' + badge(t.status) + matrixSummaryHtml(t) + '</td>' +
|
|
1631
|
-
'<td class="cron">' + esc(cron) + '</td>' +
|
|
2162
|
+
'<td>' + badge(t.status, t) + matrixSummaryHtml(t) + '</td>' +
|
|
2163
|
+
'<td class="cron">' + esc(cron) + sessionBadge + '</td>' +
|
|
1632
2164
|
'<td>' + workspaceHtml(t) + '</td>' +
|
|
1633
2165
|
'<td>' + modelHtml(t) + '</td>' +
|
|
1634
2166
|
'<td>' + priorityHtml(t) + '</td>' +
|
|
@@ -1653,13 +2185,26 @@ function renderPage(): string {
|
|
|
1653
2185
|
// /api/metrics может быть перехвачен антивирусом; /api/summary — тот же
|
|
1654
2186
|
// обработчик на случай, если блокировка привязана к имени URL.
|
|
1655
2187
|
function loadMetricsJson() {
|
|
1656
|
-
|
|
2188
|
+
var primary = preferSummaryMetrics ? '/api/summary' : '/api/metrics';
|
|
2189
|
+
var fallback = preferSummaryMetrics ? '/api/metrics' : '/api/summary';
|
|
2190
|
+
return fetch(primary, { cache: 'no-store' })
|
|
1657
2191
|
.then(readJson)
|
|
1658
2192
|
.catch(function () {
|
|
1659
|
-
|
|
2193
|
+
// Переключаемся на второй URL того же обработчика и запоминаем выбор,
|
|
2194
|
+
// чтобы следующие обновления не повторяли заблокированный запрос.
|
|
2195
|
+
preferSummaryMetrics = !preferSummaryMetrics;
|
|
2196
|
+
if (!metricsFallbackLogged) {
|
|
2197
|
+
metricsFallbackLogged = true;
|
|
2198
|
+
console.info('Дашборд: ' + primary + ' недоступен, использую ' + fallback);
|
|
2199
|
+
}
|
|
2200
|
+
return fetch(fallback, { cache: 'no-store' })
|
|
1660
2201
|
.then(readJson)
|
|
1661
2202
|
.catch(function (err) {
|
|
1662
|
-
|
|
2203
|
+
// Логируем только первый сбой, чтобы не засорять консоль каждые 5 секунд.
|
|
2204
|
+
if (!metricsFallbackLogged) {
|
|
2205
|
+
metricsFallbackLogged = true;
|
|
2206
|
+
console.error('Дашборд: метрики недоступны', err);
|
|
2207
|
+
}
|
|
1663
2208
|
return {};
|
|
1664
2209
|
});
|
|
1665
2210
|
});
|
|
@@ -1685,6 +2230,7 @@ function renderPage(): string {
|
|
|
1685
2230
|
document.getElementById('m-total').textContent = m.total != null ? m.total : '—';
|
|
1686
2231
|
document.getElementById('m-success').textContent = m.success != null ? m.success : '—';
|
|
1687
2232
|
document.getElementById('m-error').textContent = m.error != null ? m.error : '—';
|
|
2233
|
+
document.getElementById('m-partial').textContent = m.partial != null ? m.partial : '—';
|
|
1688
2234
|
document.getElementById('m-tasks').textContent = String(tasks.length);
|
|
1689
2235
|
document.getElementById('m-tokens').textContent = m.tokens != null ? Number(m.tokens).toLocaleString('ru-RU') : '—';
|
|
1690
2236
|
document.getElementById('m-cost').textContent = m.costUsd != null ? '$' + Number(m.costUsd).toFixed(2) : '—';
|
|
@@ -1741,6 +2287,13 @@ function renderPage(): string {
|
|
|
1741
2287
|
return;
|
|
1742
2288
|
}
|
|
1743
2289
|
|
|
2290
|
+
// История: развернуть/свернуть список (по умолчанию показываем последние 10).
|
|
2291
|
+
if (act === 'history-toggle') {
|
|
2292
|
+
historyExpanded = !historyExpanded;
|
|
2293
|
+
renderHistory(lastHistory);
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
|
|
1744
2297
|
if (!name) return;
|
|
1745
2298
|
if (act === 'simulate') {
|
|
1746
2299
|
await showDryRun(name);
|
|
@@ -1820,7 +2373,7 @@ function renderPage(): string {
|
|
|
1820
2373
|
if (report.warnings && report.warnings.length) {
|
|
1821
2374
|
html += '<div class="warn" style="margin-bottom:8px">⚠ Предупреждения:<br>' + report.warnings.map(function (w) { return '· ' + esc(w); }).join('<br>') + '</div>';
|
|
1822
2375
|
}
|
|
1823
|
-
html += '<table class="wi-table"><thead><tr><th>#</th><th>Задача</th><th>Триггер</th><th>Workspace</th><th>cwd</th><th>Команда</th><th>Оценка</th></tr></thead><tbody>';
|
|
2376
|
+
html += '<table class="wi-table"><thead><tr><th scope="col">#</th><th scope="col">Задача</th><th scope="col">Триггер</th><th scope="col">Workspace</th><th scope="col">cwd</th><th scope="col">Команда</th><th scope="col">Оценка</th></tr></thead><tbody>';
|
|
1824
2377
|
for (var i = 0; i < report.tasks.length; i++) {
|
|
1825
2378
|
var t = report.tasks[i];
|
|
1826
2379
|
var est = '—';
|