From 5ec538b8c294a6395715648e96d6a311fb4ef042 Mon Sep 17 00:00:00 2001 From: Heewon Oh Date: Sun, 15 Nov 2026 07:09:18 +0900 Subject: [PATCH] refactor(web): split the Supervisor script under the 1500 code LOC cap (AGT-4868) dashboardHtml.ts itself was removed in #830, but its successor web/static/js/supervisor.js carried ~1720 code LOC. The secondary panels (repo picker, scan paths, folder browser, monitors, processes, coordination) move verbatim to supervisorPanels.js, loaded before supervisor.js in the same global scope. Concatenating the two reproduces the original byte for byte. The jsdom page tests now inline both scripts in load order and fail with a ReferenceError when the order is reversed; a size test pins both files under the cap. --- tests/web/supervisorActions.test.ts | 21 +- tests/web/supervisorSize.test.ts | 43 +++ tests/web/tokens.test.ts | 2 +- web/static/js/supervisor.js | 397 +-------------------------- web/static/js/supervisorPanels.js | 406 ++++++++++++++++++++++++++++ web/static/supervisor.html | 1 + 6 files changed, 468 insertions(+), 402 deletions(-) create mode 100644 tests/web/supervisorSize.test.ts create mode 100644 web/static/js/supervisorPanels.js diff --git a/tests/web/supervisorActions.test.ts b/tests/web/supervisorActions.test.ts index a3838dd3..9eea9a22 100644 --- a/tests/web/supervisorActions.test.ts +++ b/tests/web/supervisorActions.test.ts @@ -1,4 +1,5 @@ -// The Supervisor page runs one classic script (web/static/js/supervisor.js), +// The Supervisor page runs classic scripts (web/static/js/supervisor.js and +// supervisorPanels.js), // so a source-shape assertion cannot tell whether a failed Stop still reads as // sent. Run the real page and script in jsdom with a scripted fetch and a // hand-driven clock. @@ -9,13 +10,19 @@ import { join } from 'node:path'; import { JSDOM } from 'jsdom'; const STATIC = join(__dirname, '..', '..', 'web', 'static'); -const SCRIPT_TAG = ''; -/** The page with its script inlined: jsdom does not fetch /static/ assets. */ +// Both classic scripts, in load order: the panels declare what supervisor.js's +// init code calls (AGT-4868). +const SCRIPTS = ['supervisorPanels.js', 'supervisor.js']; +/** The page with its scripts inlined: jsdom does not fetch /static/ assets. */ function pageSource(): string { - const html = readFileSync(join(STATIC, 'supervisor.html'), 'utf8'); - if (!html.includes(SCRIPT_TAG)) throw new Error('supervisor.html no longer loads supervisor.js'); - const script = readFileSync(join(STATIC, 'js', 'supervisor.js'), 'utf8'); - return html.replace(SCRIPT_TAG, () => ``); + let html = readFileSync(join(STATIC, 'supervisor.html'), 'utf8'); + for (const name of SCRIPTS) { + const tag = ``; + if (!html.includes(tag)) throw new Error(`supervisor.html no longer loads ${name}`); + const script = readFileSync(join(STATIC, 'js', name), 'utf8'); + html = html.replace(tag, () => ``); + } + return html; } const PROVIDERS = ['codex', 'openrouter']; diff --git a/tests/web/supervisorSize.test.ts b/tests/web/supervisorSize.test.ts new file mode 100644 index 00000000..2ecc6056 --- /dev/null +++ b/tests/web/supervisorSize.test.ts @@ -0,0 +1,43 @@ +// The Supervisor's classic scripts stay under book.md Art. III's 1500 code LOC +// cap per file (AGT-4868). Code LOC = lines that are neither blank nor comment. + +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const JS = join(__dirname, '..', '..', 'web', 'static', 'js'); +const CAP = 1500; + +function codeLoc(source: string): number { + let inBlock = false; + let count = 0; + for (const raw of source.split('\n')) { + const line = raw.trim(); + if (inBlock) { + if (line.includes('*/')) inBlock = false; + continue; + } + if (line === '' || line.startsWith('//')) continue; + if (line.startsWith('/*')) { + if (!line.includes('*/')) inBlock = true; + continue; + } + count++; + } + return count; +} + +describe('Supervisor script size', () => { + it.each(['supervisor.js', 'supervisorPanels.js'])('%s is under the code LOC cap', (name) => { + expect(codeLoc(readFileSync(join(JS, name), 'utf8'))).toBeLessThan(CAP); + }); + + it('supervisorPanels.js only declares, so loading it before supervisor.js is safe', () => { + const topLevel = readFileSync(join(JS, 'supervisorPanels.js'), 'utf8') + .split('\n') + .filter((l) => /^[^\s}/)]/.test(l)); + for (const line of topLevel) { + expect(line, line).toMatch(/^(?:async function|function|let|var|const) /); + } + }); +}); diff --git a/tests/web/tokens.test.ts b/tests/web/tokens.test.ts index c4b1dd98..f58c8a56 100644 --- a/tests/web/tokens.test.ts +++ b/tests/web/tokens.test.ts @@ -203,7 +203,7 @@ describe('server-rendered legacy pages (AGT-4201)', () => { const pages = [ join(__dirname, '..', '..', 'src', 'issues', 'issueBoardHtml.ts'), ]; - const markupSources = [...pages, join(ROOT, 'js', 'supervisor.js')]; + const markupSources = [...pages, join(ROOT, 'js', 'supervisor.js'), join(ROOT, 'js', 'supervisorPanels.js')]; it('link tokens.css, boot the theme first, and offer a toggle', () => { for (const file of pages) { diff --git a/web/static/js/supervisor.js b/web/static/js/supervisor.js index b6cb127f..bb80f712 100644 --- a/web/static/js/supervisor.js +++ b/web/static/js/supervisor.js @@ -6,6 +6,9 @@ // running right now (the board). References sit beside it, each naming its // source. It is a classic script because its markup calls these functions from // inline `onclick` attributes, which is also why the linter sees them as unused. +// The secondary panels (repo picker, scan paths, folder browser, monitors, +// processes, coordination) live in supervisorPanels.js, which loads first and +// shares this global scope (AGT-4868). /* eslint-disable no-unused-vars */ const MAX_LOG = 200; @@ -1227,400 +1230,6 @@ function escapeJsArgAttr(text) { return escapeAttr(JSON.stringify(String(text || ""))); } -// ---- Repo Picker ---- -let allLocalProjects = []; -let pickerOpen = false; - -async function openRepoPicker() { - if (pickerOpen) return; - pickerOpen = true; - const overlay = document.getElementById("repo-picker"); - overlay.style.display = "flex"; - document.getElementById("repo-search").value = ""; - document.getElementById("repo-picker-list").innerHTML = - "
loading...
"; - document.getElementById("repo-search").focus(); - - try { - fetchScanPaths(); - const res = await fetch("/api/local-projects"); - allLocalProjects = await res.json(); - filterRepos(""); - } catch(e) { - document.getElementById("repo-picker-list").innerHTML = - "
failed to load: " + escapeHtml(e.message) + "
"; - } -} - -function closeRepoPicker() { - pickerOpen = false; - document.getElementById("repo-picker").style.display = "none"; -} - -function filterRepos(q) { - const list = document.getElementById("repo-picker-list"); - const filtered = q - ? allLocalProjects.filter(p => - p.name.toLowerCase().includes(q.toLowerCase()) || - p.path.toLowerCase().includes(q.toLowerCase())) - : allLocalProjects; - - if (!filtered.length) { - list.innerHTML = "
no results
"; - return; - } - list.innerHTML = filtered.slice(0, 80).map(p => { - const badge = p.pinned ? "pinned" : ""; - return ( - "
" + - "
" + - "
" + escapeHtml(p.name) + "
" + - "
" + escapeHtml(p.path) + "
" + - "
" + - badge + - "
" - ); - }).join(""); -} - -async function pickRepo(el) { - const path = el.getAttribute("data-path"); - if (!path) return; - el.style.opacity = "0.4"; - try { - await fetch("/api/projects/pin", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ projectPath: path }), - }); - // Refresh project list - const res = await fetch("/api/projects"); - projects = await res.json(); - renderProjects(); - // Mark as pinned in local picker list - const item = allLocalProjects.find(p => p.path === path); - if (item) item.pinned = true; - filterRepos(document.getElementById("repo-search").value); - } catch(e) { - console.error("Pin failed:", e); - } - el.style.opacity = "1"; -} - -// ---- Scan Paths ---- -async function fetchScanPaths() { - try { - const res = await fetch("/api/scan-paths"); - if (res.ok) { - const data = await res.json(); - renderScanPaths(data); - } - } catch(e) { - console.error("fetchScanPaths error:", e); - } -} - -function renderScanPaths(data) { - const list = document.getElementById("scan-paths-list"); - if (!list) return; - const rows = []; - for (const p of (data.configPaths || [])) { - rows.push( - "
" + - "" + escapeHtml(p) + "" + - "" + - "
" - ); - } - for (const p of (data.customPaths || [])) { - rows.push( - "
" + - "" + escapeHtml(p) + "" + - "" + - "
" - ); - } - list.innerHTML = rows.length > 0 ? rows.join("") : "
no scan paths configured
"; -} - -async function addScanPath(explicitPath) { - const input = document.getElementById("scan-path-input"); - const path = (explicitPath ?? input.value).trim(); - if (!path) return; - if (!explicitPath) input.value = ""; - try { - await fetch("/api/scan-paths", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ path }), - }); - await fetchScanPaths(); - // Refresh project list in picker - const res = await fetch("/api/local-projects"); - allLocalProjects = await res.json(); - filterRepos(document.getElementById("repo-search").value); - } catch(e) { - console.error("addScanPath error:", e); - } -} - -function toggleManualPathInput() { - const row = document.getElementById("manual-path-row"); - if (!row) return; - if (row.style.display === "none" || row.style.display === "") { - row.style.display = "flex"; - const input = document.getElementById("scan-path-input"); - if (input) input.focus(); - } else { - row.style.display = "none"; - } -} - -// ---- Folder Browser (native-style picker via /api/fs/list) ---- -var folderBrowserCurrent = null; -var folderBrowserParent = null; - -async function openFolderBrowser(startPath) { - const modal = document.getElementById("folder-browser"); - if (!modal) return; - modal.style.display = "flex"; - await loadFolderBrowser(startPath || "~/dev"); -} - -function closeFolderBrowser() { - const modal = document.getElementById("folder-browser"); - if (modal) modal.style.display = "none"; -} - -async function loadFolderBrowser(path) { - const list = document.getElementById("fb-list"); - const pathEl = document.getElementById("fb-path"); - const upBtn = document.getElementById("fb-up"); - const selectBtn = document.getElementById("fb-select"); - if (!list || !pathEl) return; - list.innerHTML = "
Loading…
"; - try { - const res = await fetch("/api/fs/list?path=" + encodeURIComponent(path)); - if (!res.ok) { - const err = await res.json().catch(() => ({})); - list.innerHTML = "
" + escapeHtml(err.error || ("HTTP " + res.status)) + "
"; - return; - } - const data = await res.json(); - folderBrowserCurrent = data.path; - folderBrowserParent = data.parent; - pathEl.value = data.path; - if (upBtn) upBtn.disabled = !data.parent; - if (selectBtn) selectBtn.textContent = "Select \"" + (data.name || data.path) + "\""; - - const dirs = (data.entries || []).filter(function(e) { return e.isDir; }); - if (dirs.length === 0) { - list.innerHTML = "
No subfolders
"; - return; - } - list.innerHTML = dirs.map(function(e) { - return "
" + - "" + escapeHtml(e.name) + "/" + - "
"; - }).join(""); - } catch (e) { - list.innerHTML = "
" + escapeHtml(String(e)) + "
"; - } -} - -function folderBrowserEnter(name) { - if (!folderBrowserCurrent || !name) return; - // Join via the server side by sending the absolute path of the child - const sep = folderBrowserCurrent.endsWith("/") ? "" : "/"; - loadFolderBrowser(folderBrowserCurrent + sep + name); -} - -function folderBrowserUp() { - if (folderBrowserParent) loadFolderBrowser(folderBrowserParent); -} - -async function folderBrowserSelect() { - if (!folderBrowserCurrent) return; - const picked = folderBrowserCurrent; - closeFolderBrowser(); - await addScanPath(picked); -} - -async function removeScanPath(path) { - try { - await fetch("/api/scan-paths/" + encodeURIComponent(path), { - method: "DELETE", - }); - await fetchScanPaths(); - // Refresh project list in picker - const res = await fetch("/api/local-projects"); - allLocalProjects = await res.json(); - filterRepos(document.getElementById("repo-search").value); - } catch(e) { - console.error("removeScanPath error:", e); - } -} - -// ---- Monitors ---- -var monitorsData = []; -async function fetchMonitors() { - try { - const res = await fetch("/api/monitors"); - if (res.ok) { monitorsData = await res.json(); renderMonitors(); } - } catch {} -} -function renderMonitors() { - renderMonitorsAndProcesses(); -} -function fmtDur(ms) { - var s = Math.floor(ms / 1000); - var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60); - if (h >= 24) return Math.floor(h / 24) + "d " + (h % 24) + "h"; - if (h > 0) return h + "h " + m + "m"; - return m + "m"; -} - -// ---- Processes ---- -var processesData = []; -async function fetchProcesses() { - try { - const res = await fetch("/api/processes"); - if (res.ok) { processesData = await res.json(); renderMonitorsAndProcesses(); } - } catch {} -} -async function stopProcess(btn, id, isPipeline) { - if (armButton(btn, isPipeline ? "Cancel " + id + "?" : "Kill " + id + "?")) return; - try { - await fetch("/api/processes/" + encodeURIComponent(id), { method: "DELETE" }); - processesData = processesData.filter(p => String(p.id) !== String(id)); - renderMonitorsAndProcesses(); - } catch(e) { - addLogLine({ taskId: "system", stage: "error", line: "Stop failed: " + e.message }); - } -} -function procActivityIcon(lastActivityAt) { - var ago = (Date.now() - lastActivityAt) / 1000; - if (ago < 10) return "\u26A1"; - if (ago < 60) return "\u23F8"; - return "\u2757"; -} -function renderMonitorsAndProcesses() { - var panel = document.getElementById("monitor-panel"); - var el = document.getElementById("monitor-list"); - var countEl = document.getElementById("monitor-count"); - var hasMonitors = monitorsData.length > 0; - var hasProcesses = processesData.length > 0; - if (!hasMonitors && !hasProcesses) { - el.innerHTML = "
no monitors or processes
"; - var counts = []; - if (countEl) countEl.textContent = "process table"; - return; - } - var parts = []; - if (processesData.length) parts.push(processesData.length + " process" + (processesData.length === 1 ? "" : "es")); - if (monitorsData.length) parts.push(monitorsData.length + " monitor" + (monitorsData.length === 1 ? "" : "s")); - if (countEl) countEl.textContent = "process table · " + parts.join(" · "); - var html = ""; - // Processes section - if (hasProcesses) { - html += "
processes
"; - html += processesData.map(function(p) { - var dur = fmtDur(Date.now() - p.spawnedAt); - var isPipeline = p.kind === "pipeline"; - var act = isPipeline ? "\u2699" : procActivityIcon(p.lastActivityAt); - var modelStr = p.model ? shortModel(p.model) : ""; - var projName = p.project || (p.projectPath ? p.projectPath.split("/").pop() : ""); - // In-process pipeline tasks have no OS PID — show the issue id instead, and - // a CANCEL button (aborts the pipeline + its in-flight adapter call). - var lead = isPipeline ? escapeHtml(p.taskId || "task") : p.pid; - var btn = isPipeline - ? '' - : ''; - return '
' + - '' + lead + '' + - '' + escapeHtml(p.stage) + '' + - '' + escapeHtml(modelStr) + '' + - '' + escapeHtml(projName) + '' + - '' + act + '' + - '' + dur + '' + - btn + - '
'; - }).join(""); - } - // Monitors section - if (hasMonitors) { - html += "
monitors
"; - html += monitorsData.map(function(m) { - var stateColor = m.state === "running" ? "var(--accent)" : m.state === "completed" ? "var(--info)" : m.state === "failed" || m.state === "timeout" ? "var(--danger)" : "var(--fg-muted)"; - var elapsed = m.registeredAt ? fmtDur(Date.now() - m.registeredAt) : "-"; - var lastOut = m.lastOutput ? escapeHtml(m.lastOutput.slice(0, 80)) : "-"; - return '
' + - '
' + - '[' + m.state.toUpperCase() + ']' + - '' + escapeHtml(m.name) + '' + - '' + elapsed + '' + - '
' + - '
' + lastOut + '
' + - (m.issueId ? '
' + escapeHtml(m.issueId) + ' | checks: ' + m.checkCount + '
' : '') + - '
'; - }).join(""); - } - el.innerHTML = html; -} - -function addCoordinationEvent(event) { - if (!event || typeof event.id !== "string") return; - const previous = coordinationById.get(event.id); - if (!previous || Number(event.seq || 0) >= Number(previous.seq || 0)) coordinationById.set(event.id, event); - renderCoordination(); -} - -function renderCoordination() { - // The per-event list lives on /orchestration now; this card answers one - // question at a glance — how many agents are placed and what is waiting. - var el = document.getElementById("coordination-summary"); - var events = Array.from(coordinationById.values()); - setText("coordination-count", "coordination board" + (events.length ? " · " + events.length + " events" : "")); - renderNotice(); - if (!events.length) { el.innerHTML = '
no coordination events
'; return; } - var agents = {}; - var latestByCorrelation = {}; - events.forEach(function(ev) { - if (ev.actor && ev.actor !== 'human') agents[ev.actor] = ev.actorRole || 'agent'; - var prev = latestByCorrelation[ev.correlationId]; - if (!prev || Number(ev.seq || 0) > Number(prev.seq || 0)) latestByCorrelation[ev.correlationId] = ev; - }); - var pending = Object.values(latestByCorrelation).filter(function(ev) { return ["open", "waiting", "running"].includes(ev.status); }); - var questions = pending.filter(function(ev) { return ev.kind === "human-question"; }).length; - var roles = {}; - Object.values(agents).forEach(function(role) { roles[role] = (roles[role] || 0) + 1; }); - var roleLine = Object.keys(roles).sort().map(function(role) { return roles[role] + " " + escapeHtml(role); }).join(" · "); - el.innerHTML = - '
' + - '
' + Object.keys(agents).length + ' agents placed (' + roleLine + ')
' + - // Questions are the one thing here that waits on the operator: a yellow - // fill, never yellow text (Yellow Means You). - '
' + - (questions > 0 ? '' + plural(questions, 'question') + ' waiting on you' : '0 questions waiting on you') + - ' · ' + plural(pending.length, 'open exchange') + '
' + - '
'; -} - -function plural(count, noun) { - return count + ' ' + noun + (count === 1 ? '' : 's'); -} - -async function fetchCoordination() { - try { - const response = await fetch("/api/coordination"); - if (!response.ok) return; - const snapshot = await response.json(); - for (const event of snapshot.events || []) addCoordinationEvent(event); - } catch {} -} - // ---- Init ---- async function loadInitial() { try { diff --git a/web/static/js/supervisorPanels.js b/web/static/js/supervisorPanels.js new file mode 100644 index 00000000..343f420f --- /dev/null +++ b/web/static/js/supervisorPanels.js @@ -0,0 +1,406 @@ +// The Supervisor page's secondary panels: the repo picker, scan paths, the +// folder browser, monitors, processes and the coordination feed. +// +// Split out of supervisor.js (AGT-4868) to keep each file under the 1500 code +// LOC cap. It is a classic script like supervisor.js and shares its global +// scope, so it must load BEFORE supervisor.js: supervisor.js's init code at the +// bottom calls fetchMonitors/fetchProcesses/fetchCoordination synchronously. +// This file only declares; it runs nothing at load, so it may reference +// supervisor.js's globals (escapeHtml, coordinationById, ...) from function +// bodies. Its functions are called from inline `onclick` attributes, which is +// why the linter sees them as unused. +/* eslint-disable no-unused-vars */ + +// ---- Repo Picker ---- +let allLocalProjects = []; +let pickerOpen = false; + +async function openRepoPicker() { + if (pickerOpen) return; + pickerOpen = true; + const overlay = document.getElementById("repo-picker"); + overlay.style.display = "flex"; + document.getElementById("repo-search").value = ""; + document.getElementById("repo-picker-list").innerHTML = + "
loading...
"; + document.getElementById("repo-search").focus(); + + try { + fetchScanPaths(); + const res = await fetch("/api/local-projects"); + allLocalProjects = await res.json(); + filterRepos(""); + } catch(e) { + document.getElementById("repo-picker-list").innerHTML = + "
failed to load: " + escapeHtml(e.message) + "
"; + } +} + +function closeRepoPicker() { + pickerOpen = false; + document.getElementById("repo-picker").style.display = "none"; +} + +function filterRepos(q) { + const list = document.getElementById("repo-picker-list"); + const filtered = q + ? allLocalProjects.filter(p => + p.name.toLowerCase().includes(q.toLowerCase()) || + p.path.toLowerCase().includes(q.toLowerCase())) + : allLocalProjects; + + if (!filtered.length) { + list.innerHTML = "
no results
"; + return; + } + list.innerHTML = filtered.slice(0, 80).map(p => { + const badge = p.pinned ? "pinned" : ""; + return ( + "
" + + "
" + + "
" + escapeHtml(p.name) + "
" + + "
" + escapeHtml(p.path) + "
" + + "
" + + badge + + "
" + ); + }).join(""); +} + +async function pickRepo(el) { + const path = el.getAttribute("data-path"); + if (!path) return; + el.style.opacity = "0.4"; + try { + await fetch("/api/projects/pin", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ projectPath: path }), + }); + // Refresh project list + const res = await fetch("/api/projects"); + projects = await res.json(); + renderProjects(); + // Mark as pinned in local picker list + const item = allLocalProjects.find(p => p.path === path); + if (item) item.pinned = true; + filterRepos(document.getElementById("repo-search").value); + } catch(e) { + console.error("Pin failed:", e); + } + el.style.opacity = "1"; +} + +// ---- Scan Paths ---- +async function fetchScanPaths() { + try { + const res = await fetch("/api/scan-paths"); + if (res.ok) { + const data = await res.json(); + renderScanPaths(data); + } + } catch(e) { + console.error("fetchScanPaths error:", e); + } +} + +function renderScanPaths(data) { + const list = document.getElementById("scan-paths-list"); + if (!list) return; + const rows = []; + for (const p of (data.configPaths || [])) { + rows.push( + "
" + + "" + escapeHtml(p) + "" + + "" + + "
" + ); + } + for (const p of (data.customPaths || [])) { + rows.push( + "
" + + "" + escapeHtml(p) + "" + + "" + + "
" + ); + } + list.innerHTML = rows.length > 0 ? rows.join("") : "
no scan paths configured
"; +} + +async function addScanPath(explicitPath) { + const input = document.getElementById("scan-path-input"); + const path = (explicitPath ?? input.value).trim(); + if (!path) return; + if (!explicitPath) input.value = ""; + try { + await fetch("/api/scan-paths", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ path }), + }); + await fetchScanPaths(); + // Refresh project list in picker + const res = await fetch("/api/local-projects"); + allLocalProjects = await res.json(); + filterRepos(document.getElementById("repo-search").value); + } catch(e) { + console.error("addScanPath error:", e); + } +} + +function toggleManualPathInput() { + const row = document.getElementById("manual-path-row"); + if (!row) return; + if (row.style.display === "none" || row.style.display === "") { + row.style.display = "flex"; + const input = document.getElementById("scan-path-input"); + if (input) input.focus(); + } else { + row.style.display = "none"; + } +} + +// ---- Folder Browser (native-style picker via /api/fs/list) ---- +var folderBrowserCurrent = null; +var folderBrowserParent = null; + +async function openFolderBrowser(startPath) { + const modal = document.getElementById("folder-browser"); + if (!modal) return; + modal.style.display = "flex"; + await loadFolderBrowser(startPath || "~/dev"); +} + +function closeFolderBrowser() { + const modal = document.getElementById("folder-browser"); + if (modal) modal.style.display = "none"; +} + +async function loadFolderBrowser(path) { + const list = document.getElementById("fb-list"); + const pathEl = document.getElementById("fb-path"); + const upBtn = document.getElementById("fb-up"); + const selectBtn = document.getElementById("fb-select"); + if (!list || !pathEl) return; + list.innerHTML = "
Loading…
"; + try { + const res = await fetch("/api/fs/list?path=" + encodeURIComponent(path)); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + list.innerHTML = "
" + escapeHtml(err.error || ("HTTP " + res.status)) + "
"; + return; + } + const data = await res.json(); + folderBrowserCurrent = data.path; + folderBrowserParent = data.parent; + pathEl.value = data.path; + if (upBtn) upBtn.disabled = !data.parent; + if (selectBtn) selectBtn.textContent = "Select \"" + (data.name || data.path) + "\""; + + const dirs = (data.entries || []).filter(function(e) { return e.isDir; }); + if (dirs.length === 0) { + list.innerHTML = "
No subfolders
"; + return; + } + list.innerHTML = dirs.map(function(e) { + return "
" + + "" + escapeHtml(e.name) + "/" + + "
"; + }).join(""); + } catch (e) { + list.innerHTML = "
" + escapeHtml(String(e)) + "
"; + } +} + +function folderBrowserEnter(name) { + if (!folderBrowserCurrent || !name) return; + // Join via the server side by sending the absolute path of the child + const sep = folderBrowserCurrent.endsWith("/") ? "" : "/"; + loadFolderBrowser(folderBrowserCurrent + sep + name); +} + +function folderBrowserUp() { + if (folderBrowserParent) loadFolderBrowser(folderBrowserParent); +} + +async function folderBrowserSelect() { + if (!folderBrowserCurrent) return; + const picked = folderBrowserCurrent; + closeFolderBrowser(); + await addScanPath(picked); +} + +async function removeScanPath(path) { + try { + await fetch("/api/scan-paths/" + encodeURIComponent(path), { + method: "DELETE", + }); + await fetchScanPaths(); + // Refresh project list in picker + const res = await fetch("/api/local-projects"); + allLocalProjects = await res.json(); + filterRepos(document.getElementById("repo-search").value); + } catch(e) { + console.error("removeScanPath error:", e); + } +} + +// ---- Monitors ---- +var monitorsData = []; +async function fetchMonitors() { + try { + const res = await fetch("/api/monitors"); + if (res.ok) { monitorsData = await res.json(); renderMonitors(); } + } catch {} +} +function renderMonitors() { + renderMonitorsAndProcesses(); +} +function fmtDur(ms) { + var s = Math.floor(ms / 1000); + var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60); + if (h >= 24) return Math.floor(h / 24) + "d " + (h % 24) + "h"; + if (h > 0) return h + "h " + m + "m"; + return m + "m"; +} + +// ---- Processes ---- +var processesData = []; +async function fetchProcesses() { + try { + const res = await fetch("/api/processes"); + if (res.ok) { processesData = await res.json(); renderMonitorsAndProcesses(); } + } catch {} +} +async function stopProcess(btn, id, isPipeline) { + if (armButton(btn, isPipeline ? "Cancel " + id + "?" : "Kill " + id + "?")) return; + try { + await fetch("/api/processes/" + encodeURIComponent(id), { method: "DELETE" }); + processesData = processesData.filter(p => String(p.id) !== String(id)); + renderMonitorsAndProcesses(); + } catch(e) { + addLogLine({ taskId: "system", stage: "error", line: "Stop failed: " + e.message }); + } +} +function procActivityIcon(lastActivityAt) { + var ago = (Date.now() - lastActivityAt) / 1000; + if (ago < 10) return "\u26A1"; + if (ago < 60) return "\u23F8"; + return "\u2757"; +} +function renderMonitorsAndProcesses() { + var panel = document.getElementById("monitor-panel"); + var el = document.getElementById("monitor-list"); + var countEl = document.getElementById("monitor-count"); + var hasMonitors = monitorsData.length > 0; + var hasProcesses = processesData.length > 0; + if (!hasMonitors && !hasProcesses) { + el.innerHTML = "
no monitors or processes
"; + var counts = []; + if (countEl) countEl.textContent = "process table"; + return; + } + var parts = []; + if (processesData.length) parts.push(processesData.length + " process" + (processesData.length === 1 ? "" : "es")); + if (monitorsData.length) parts.push(monitorsData.length + " monitor" + (monitorsData.length === 1 ? "" : "s")); + if (countEl) countEl.textContent = "process table · " + parts.join(" · "); + var html = ""; + // Processes section + if (hasProcesses) { + html += "
processes
"; + html += processesData.map(function(p) { + var dur = fmtDur(Date.now() - p.spawnedAt); + var isPipeline = p.kind === "pipeline"; + var act = isPipeline ? "\u2699" : procActivityIcon(p.lastActivityAt); + var modelStr = p.model ? shortModel(p.model) : ""; + var projName = p.project || (p.projectPath ? p.projectPath.split("/").pop() : ""); + // In-process pipeline tasks have no OS PID — show the issue id instead, and + // a CANCEL button (aborts the pipeline + its in-flight adapter call). + var lead = isPipeline ? escapeHtml(p.taskId || "task") : p.pid; + var btn = isPipeline + ? '' + : ''; + return '
' + + '' + lead + '' + + '' + escapeHtml(p.stage) + '' + + '' + escapeHtml(modelStr) + '' + + '' + escapeHtml(projName) + '' + + '' + act + '' + + '' + dur + '' + + btn + + '
'; + }).join(""); + } + // Monitors section + if (hasMonitors) { + html += "
monitors
"; + html += monitorsData.map(function(m) { + var stateColor = m.state === "running" ? "var(--accent)" : m.state === "completed" ? "var(--info)" : m.state === "failed" || m.state === "timeout" ? "var(--danger)" : "var(--fg-muted)"; + var elapsed = m.registeredAt ? fmtDur(Date.now() - m.registeredAt) : "-"; + var lastOut = m.lastOutput ? escapeHtml(m.lastOutput.slice(0, 80)) : "-"; + return '
' + + '
' + + '[' + m.state.toUpperCase() + ']' + + '' + escapeHtml(m.name) + '' + + '' + elapsed + '' + + '
' + + '
' + lastOut + '
' + + (m.issueId ? '
' + escapeHtml(m.issueId) + ' | checks: ' + m.checkCount + '
' : '') + + '
'; + }).join(""); + } + el.innerHTML = html; +} + +function addCoordinationEvent(event) { + if (!event || typeof event.id !== "string") return; + const previous = coordinationById.get(event.id); + if (!previous || Number(event.seq || 0) >= Number(previous.seq || 0)) coordinationById.set(event.id, event); + renderCoordination(); +} + +function renderCoordination() { + // The per-event list lives on /orchestration now; this card answers one + // question at a glance — how many agents are placed and what is waiting. + var el = document.getElementById("coordination-summary"); + var events = Array.from(coordinationById.values()); + setText("coordination-count", "coordination board" + (events.length ? " · " + events.length + " events" : "")); + renderNotice(); + if (!events.length) { el.innerHTML = '
no coordination events
'; return; } + var agents = {}; + var latestByCorrelation = {}; + events.forEach(function(ev) { + if (ev.actor && ev.actor !== 'human') agents[ev.actor] = ev.actorRole || 'agent'; + var prev = latestByCorrelation[ev.correlationId]; + if (!prev || Number(ev.seq || 0) > Number(prev.seq || 0)) latestByCorrelation[ev.correlationId] = ev; + }); + var pending = Object.values(latestByCorrelation).filter(function(ev) { return ["open", "waiting", "running"].includes(ev.status); }); + var questions = pending.filter(function(ev) { return ev.kind === "human-question"; }).length; + var roles = {}; + Object.values(agents).forEach(function(role) { roles[role] = (roles[role] || 0) + 1; }); + var roleLine = Object.keys(roles).sort().map(function(role) { return roles[role] + " " + escapeHtml(role); }).join(" · "); + el.innerHTML = + '
' + + '
' + Object.keys(agents).length + ' agents placed (' + roleLine + ')
' + + // Questions are the one thing here that waits on the operator: a yellow + // fill, never yellow text (Yellow Means You). + '
' + + (questions > 0 ? '' + plural(questions, 'question') + ' waiting on you' : '0 questions waiting on you') + + ' · ' + plural(pending.length, 'open exchange') + '
' + + '
'; +} + +function plural(count, noun) { + return count + ' ' + noun + (count === 1 ? '' : 's'); +} + +async function fetchCoordination() { + try { + const response = await fetch("/api/coordination"); + if (!response.ok) return; + const snapshot = await response.json(); + for (const event of snapshot.events || []) addCoordinationEvent(event); + } catch {} +} diff --git a/web/static/supervisor.html b/web/static/supervisor.html index 6aebc8ae..b1fca09f 100644 --- a/web/static/supervisor.html +++ b/web/static/supervisor.html @@ -226,6 +226,7 @@

Choose folder to scan

+