From dd14b7bcfb31167e18bfc20dbbc44fec32b1c457 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 14 Nov 2026 10:48:18 -0800 Subject: [PATCH] /open: live browser view of everything Nexus does The dashboard now shows the whole session, live and read-only: - Live: what is running now with its streaming output, last prompt, latest answer, and every tool call newest first (click to jump). - Conversation: prompts, answers, thinking, each tool's input, output and diff; search, toggles for thinking and output, follow newest. - Terminal: every shell command in order with output, agent and !cmd. - Files: files read and changed with each change as a diff; searches and web fetches. - Agents: sub-agents with brief, their own tool calls and result. - Jobs: background commands with their output. - Cost: per-turn tokens, cache reads, time and cost. - Plan & session: plan, cowork, pipelines, tools used. Header shows working/idle, model, mode, prompt-cache countdown. /open lands on a tab (tab-completes); /open and /dashboard list what each tab shows. Heavy detail is fetched only when the session changes. Strict CSP with a per-load nonce, frame-ancestors none, the existing loopback Host/Origin checks, GET only. New pure module lib/nexus/dash-view.js; test/dashboard.test.js (31 checks). --- darknode.js | 43 +++- docs/NEXUS-COMMANDS.md | 4 +- lib/nexus/dash-view.js | 124 +++++++++++ lib/nexus/dashboard.js | 452 +++++++++++++++++++---------------------- package.json | 2 +- test/dashboard.test.js | 88 ++++++++ 6 files changed, 460 insertions(+), 253 deletions(-) create mode 100644 lib/nexus/dash-view.js create mode 100644 test/dashboard.test.js diff --git a/darknode.js b/darknode.js index dcb7b96..6b2426f 100755 --- a/darknode.js +++ b/darknode.js @@ -3059,7 +3059,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { ["/recap", "recap this session now · /recap [on|off] toggles the after-task recap"], ["/title", "name the terminal tab for this session's topic · /title [text|on|off]"], ["/feature", "add/remove your own commands: /feature create · /feature remove "], - ["/open", "launch the live web dashboard in your browser"], + ["/open", "live browser view of everything Nexus does: chat, tool calls, terminal, files, agents, cost · /open "], ["/dashboard", "start/stop the localhost web UI — live pipelines, jobs & cowork agents"], ["/marketplace", "browse, install & publish agents, skills, hooks & pipelines"], ["/cron", "scheduled pipeline runs — /cron add \"0 9 * * *\" · /cron list · /cron remove "], @@ -3070,7 +3070,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { { title: "Session", rows: [["/clear","start a new conversation"],["/chat-clear","clear the screen but keep the conversation in memory"],["/compact","summarize the conversation to free up context"],["/fixshell","repair the engine shell when commands fail with E2BIG, without /clear (check = report only, all = clear every snapshot)"],["/resume","reload the last saved session"],["/export","save the conversation to markdown (/export to pick where)"],["/copy","copy the last reply to the clipboard"],["/undo","revert the last turn's file changes"],["/status","engine, model, tokens & cost"],["/recap","recap the session so far (/recap [on|off] for after-task recaps)"],["/title","name the terminal tab for this topic (/title [text|on|off])"],["/exit","quit Nexus"]] }, { title: "Model & cost", rows: [["/model","pick the model (lists the catalog)"],["/engine","switch AI backend"],["/effort","thinking level: low … max | ultracode"],["/cost","session cost at exact list prices"],["/budget","set a spend cap in USD"],["/cheap","max token savings, zero quality loss"],["/tight","surgical minimal edits (lossless)"],["/cowork","strong model codes, weak model assists"],["/impact","tokens & cost you've saved"]] }, { title: "Code & repo", rows: [["/diff","colored word-level diff of your changes"],["/commit","write a commit message & commit"],["/review","second opinion from another engine"],["/codereview","parallel reviewers + a verifier per finding, ranked by severity (--fix applies, --comment posts to a PR)"],["/test","generate & run tests for a file"],["/explain","explain the diff or a file in plain English"],["/plan","make & run an editable task checklist"],["/scan","quick TCP port scan of a host"],["/secrets","scan the repo for leaked credentials"]] }, - { title: "Extend", rows: [["/feature","add your own command: /feature create "],["/commands","list your custom project commands"],["/open","launch the live web dashboard in your browser"],["/dashboard","start/stop the localhost web UI"],["/settings","all options, neatly arranged"],["/theme","change the color theme"],["/keys","the full keyboard-shortcut list"]] }, + { title: "Extend", rows: [["/feature","add your own command: /feature create "],["/commands","list your custom project commands"],["/open","live browser view of everything Nexus does · /open "],["/dashboard","start/stop the localhost web UI"],["/settings","all options, neatly arranged"],["/theme","change the color theme"],["/keys","the full keyboard-shortcut list"]] }, { title: "Input prefixes", rows: [["/command","run a command (type / to browse)"],["@file","attach a file or image (Tab completes the path)"],["!command","run a shell command (output goes to the AI)"],["#note","save a note to memory"]] }, ]; const KEY_SECTIONS = [ @@ -3613,6 +3613,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { "/color": () => Object.keys(COLORS).map((n) => [n, "\x1b[" + COLORS[n] + "m█████\x1b[0m"]), "/gradient": () => Object.keys(THEMES).map((t) => [t, THEMES[t].grad.map((g) => "\x1b[" + g + "m█\x1b[0m").join("")]), "/style": () => [["default", ""], ["concise", "minimal"], ["explanatory", "detailed"], ["review", "code review"], ["tdd", "test-driven"], ["secure", "security-focused"], ["teacher", "educational"]], + "/open": () => [["live", "what is running now + every tool call"], ["conversation", "full chat with thinking and tool output"], ["terminal", "every shell command and its output"], ["files", "files read and changed, with diffs"], ["agents", "sub-agents and their work"], ["jobs", "background commands"], ["cost", "per-turn cost ledger"], ["session", "plan, cowork, tools used"]], "/cheap": () => [["status", "what each saver did this session"], ["off", "restore your settings from before /cheap"]], "/effort": () => [["low", "fast, less thinking"], ["medium", "balanced"], ["high", "deep reasoning"], ["xhigh", "harder problems"], ["max", "maximum thinking"], ["ultracode", "max + multi-agent workflows"]], "/guard": () => [["enforce", "block destructive commands"], ["warn", "warn but allow"], ["off", "no safety checks"]], @@ -5245,11 +5246,21 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { }; // Ensure the dashboard server is up, then run cb(d) with the live handle. // Shared by /dashboard and /open so there is one start path. + const DASH_TABS_HELP = [ + ["live", "what is running right now, the live output, the latest answer, every tool call"], + ["conversation", "the full chat: prompts, answers, thinking, each tool's input and output, diffs"], + ["terminal", "every shell command in order with its output (running ones stream)"], + ["files", "files read and changed, with each change as a diff; searches and web fetches"], + ["agents", "sub-agents with their brief, their own tool calls and result"], + ["jobs", "background commands and their output"], + ["cost", "per-turn tokens, cache reads, time and cost"], + ["session", "plan, cowork pair, pipelines, tools used"], + ].map(([t, d]) => " " + cyan(t.padEnd(13)) + gray(d)).join("\n"); const ensureDashboard = (blk, cb) => { if (dashServer) { cb(dashServer); return; } try { const { startDashboard } = require("./lib/nexus/dashboard"); - startDashboard({ port: 7979, getState: dashboardState }).then((d) => { dashServer = d; cb(d); render(); }) + startDashboard({ port: 7979, getState: dashboardState, getDetail: dashboardDetail, getJob: (id) => { const out = bgJobs.tail(id, 200000); return out == null ? null : { id, output: out }; } }).then((d) => { dashServer = d; cb(d); render(); }) .catch((e) => { if (blk) { blk.text = red("could not start the dashboard: " + (e && e.message || e)); render(); } }); } catch (e) { if (blk) { blk.text = red("dashboard module failed to load: " + (e && e.message || e)); render(); } } }; @@ -5280,7 +5291,18 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } return out.slice(-18); }; + const DashView = require("./lib/nexus/dash-view"); + const dashboardDetail = () => { + const tail = (t) => Tail.tailText(t); + const conversation = DashView.conversation(transcript, { tail }); + return { conversation, terminal: DashView.terminal(conversation), files: DashView.fileActivity(conversation), agents: DashView.agentsView(agents, tail), turns: turnLog.slice(-300) }; + }; const dashboardState = () => ({ + rev: DashView.revision(transcript, agents), now: Date.now(), + busy: !!busy, busyWord: busyWord || "", busyFor: busy ? Math.round((Date.now() - busyStart) / 1000) : 0, + mode: (MODES[mode] && MODES[mode].k) || "", running: runningShells, + cache: engine === "claude" ? { lastAt: cacheWarm.lastAt || 0, ttl: cacheWarm.ttl || 0 } : null, + toolCalls: Object.keys(toolUse).reduce((a, k) => a + toolUse[k], 0), title: sessionTitle || "", turns: transcript.filter((m) => m.role === "user" && m.text && String(m.text).trim()).length, engine, model: sess.model || engine, paid: !!PAID[engine], @@ -5288,7 +5310,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { ctxUsed: sess.ctxUsed || 0, ctxWindow: sess.ctxWindow || CTXW[engine] || 0, dir: cwd.replace(os.homedir(), "~"), jobs: bgJobs.list(), jobsRunning: bgJobs.running(), - agents: activeAgents, + agents: Math.max(activeAgents, agents.filter((a) => a.status === "run").length), cowork: { on: cowork.on, strong: cowork.strong, weak: cowork.weak, weakKind: cowork.weakKind }, impact: { delegated: impact.delegated, coworkSaved: impact.coworkSaved }, plan: plan.map((p) => ({ text: p.text || p.title || "", done: !!p.done, running: !!p.running })), @@ -5407,16 +5429,19 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { transcript.push({ role: "system", text: "dashboard is live — open " + cyan(dashServer.url) + " in your browser\n /open to launch it · /dashboard stop to shut it down" }); } else { const blk = { role: "system", text: "starting the dashboard…" }; transcript.push(blk); render(); - ensureDashboard(blk, (d) => { blk.text = "dashboard live — " + cyan(d.url) + "\n live: pipelines · background jobs · cowork agents · plan · tokens & cost (updates every second)\n /open to launch it in your browser · /dashboard stop to shut it down"; }); + ensureDashboard(blk, (d) => { blk.text = "dashboard live — " + cyan(d.url) + "\n" + DASH_TABS_HELP + "\n " + gray("/open to launch it in your browser · /dashboard stop to shut it down"); }); } } else if (cmd === "/open") { - // Launch the live localhost dashboard straight in the default browser — - // starts the server first if it is not already running. + // Launch the live localhost dashboard in the default browser (starts it first + // if needed). /open lands on that tab: live, conversation, terminal, ... + const TABS = ["live", "conversation", "terminal", "files", "agents", "jobs", "cost", "session"]; + const want = (arg || "").trim().toLowerCase(), pick = want ? TABS.find((t) => t.startsWith(want)) : "live"; + if (want && !pick) { transcript.push({ role: "system", text: "no dashboard tab '" + want + "' — " + TABS.map(cyan).join(" · ") }); render(); return; } const blk = { role: "system", text: "opening the dashboard in your browser…" }; transcript.push(blk); render(); ensureDashboard(blk, (d) => { - const ok = openUrl(d.url); - blk.text = (ok ? "opened " : "dashboard live at ") + cyan(d.url) + (ok ? " in your browser" : gray(" — couldn't auto-launch; open it manually")) + "\n live: pipelines · background jobs · cowork agents · plan · tokens & cost (updates every second)\n /dashboard stop to shut it down"; + const u = d.url + "/#" + pick, ok = openUrl(u); + blk.text = (ok ? "opened " : "dashboard live at ") + cyan(u) + (ok ? " in your browser" : gray(" — couldn't auto-launch; open it manually")) + "\n" + DASH_TABS_HELP + "\n " + gray("updates every second · read-only · this machine only (127.0.0.1) · /open jumps to a tab · /dashboard stop shuts it down"); }); } else if (cmd === "/trust") { diff --git a/docs/NEXUS-COMMANDS.md b/docs/NEXUS-COMMANDS.md index fb72e3e..128a0bf 100644 --- a/docs/NEXUS-COMMANDS.md +++ b/docs/NEXUS-COMMANDS.md @@ -203,7 +203,7 @@ File tools are confined to the project folder; secrets are blocked from being wr - `/recap` — recap this session now · /recap [on|off] toggles the after-task recap - `/title` — name the terminal tab for this session's topic · /title [text|on|off] - `/feature` — add/remove your own commands: /feature create · /feature remove -- `/open` — launch the live web dashboard in your browser +- `/open` — live browser view of everything Nexus does: chat, tool calls, terminal, files, agents, cost · /open - `/dashboard` — start/stop the localhost web UI — live pipelines, jobs & cowork agents - `/marketplace` — browse, install & publish agents, skills, hooks & pipelines - `/cron` — scheduled pipeline runs — /cron add "0 9 * * *" · /cron list · /cron remove @@ -257,7 +257,7 @@ File tools are confined to the project folder; secrets are blocked from being wr - `/feature` — add your own command: /feature create - `/commands` — list your custom project commands -- `/open` — launch the live web dashboard in your browser +- `/open` — live browser view of everything Nexus does · /open - `/dashboard` — start/stop the localhost web UI - `/settings` — all options, neatly arranged - `/theme` — change the color theme diff --git a/lib/nexus/dash-view.js b/lib/nexus/dash-view.js new file mode 100644 index 0000000..3bbf51c --- /dev/null +++ b/lib/nexus/dash-view.js @@ -0,0 +1,124 @@ +"use strict"; +// Pure builders for the /open dashboard: turn the live TUI transcript and agent +// list into plain JSON the browser can render (full conversation, terminal log, +// file activity). No I/O, so it is unit-tested directly (test/dashboard.test.js). + +const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; +const strip = (s) => String(s == null ? "" : s).replace(ANSI, ""); +const cap = (s, n) => { s = String(s == null ? "" : s); return s.length > n ? s.slice(0, n) + "\n… [" + (s.length - n).toLocaleString("en-US") + " more characters]" : s; }; + +const OUT_CAP = 20000, TEXT_CAP = 60000, INPUT_CAP = 8000, DIFF_ROWS = 400; + +// Any tool result shape (string, content blocks, local-tool object) as text. +function asText(r) { + if (r == null) return ""; + if (typeof r === "string") return r; + if (Array.isArray(r)) return r.map((x) => (x && typeof x.text === "string") ? x.text : typeof x === "string" ? x : (x && x.type === "image") ? "[image]" : "").join("\n"); + if (typeof r === "object" && typeof r.output === "string") return r.output + (r.code ? "\n[exit " + r.code + "]" : ""); + try { return JSON.stringify(r, null, 2); } catch (_) { return String(r); } +} + +const FILE_KEYS = ["file_path", "notebook_path", "path"]; +const fileOf = (input) => { if (!input || typeof input !== "object") return ""; for (const k of FILE_KEYS) if (typeof input[k] === "string" && input[k]) return input[k]; return ""; }; +const commandOf = (name, input) => (input && typeof input === "object" && typeof input.command === "string" && /^(Bash|run_command|run_background|BashOutput)$/.test(name)) ? input.command : ""; + +// What kind of thing a tool call did, for the activity icons and filters. +function kindOf(name) { + const n = String(name || ""); + if (/^(Bash|run_command|run_background|BashOutput|KillShell|check_background)$/.test(n)) return "shell"; + if (/^(Read|read_file|NotebookRead|view_file)$/.test(n)) return "read"; + if (/^(Write|Edit|MultiEdit|NotebookEdit|write_file|edit_file|create_file|apply_patch)$/.test(n)) return "edit"; + if (/^(Glob|Grep|LS|list_dir|search|find_files|grep)$/.test(n)) return "search"; + if (/^(WebFetch|WebSearch|web_fetch|web_search|fetch_url)$/.test(n)) return "web"; + if (/^(Task|Agent|spawn_agents)$/.test(n)) return "agent"; + if (/^mcp__/.test(n)) return "mcp"; + if (/^(TodoWrite|ExitPlanMode)$/.test(n)) return "plan"; + return "tool"; +} + +function toolView(it, tail) { + const out = it.result !== undefined ? asText(it.result) : (it.live && tail ? tail(it.live) : ""); + const v = { + type: "tool", id: String(it.id || ""), name: String(it.name || "tool"), kind: kindOf(it.name), label: strip(it.label || it.name || "tool"), + status: it.interrupted ? "stopped" : it.status === "err" ? "error" : it.status === "run" ? "running" : it.status === "wait" ? "waiting" : "done", + start: it.start || 0, end: it.end || 0, + file: fileOf(it.input), command: commandOf(String(it.name || ""), it.input), + input: it.input == null ? "" : cap(typeof it.input === "string" ? it.input : JSON.stringify(it.input, null, 2), INPUT_CAP), + output: cap(strip(out), OUT_CAP), live: it.result === undefined && !!it.live, + }; + if (it.diff && Array.isArray(it.diff.rows)) v.diff = { added: it.diff.added || 0, removed: it.diff.removed || 0, rows: it.diff.rows.slice(0, DIFF_ROWS).map((r) => [r.t || " ", strip(r.text), r.ln || 0]), more: Math.max(0, it.diff.rows.length - DIFF_ROWS) }; + if (it._agId) v.agent = it._agId; + return v; +} + +function itemsView(items, tail) { + const out = []; + for (const it of items || []) { + if (!it) continue; + if (it.type === "text" && it.full) out.push({ type: "text", text: cap(strip(it.full), TEXT_CAP) }); + else if (it.type === "thinking" && it.full) out.push({ type: "thinking", text: cap(strip(it.full), TEXT_CAP) }); + else if (it.type === "tool") out.push(toolView(it, tail)); + } + return out; +} + +// The whole conversation, newest last. opts.tail(liveTail) -> text of a running command so far. +function conversation(transcript, opts) { + const tail = opts && opts.tail; + const out = []; + (transcript || []).forEach((b, i) => { + if (!b || b.role === "art") return; + if (b.role === "user") out.push({ i, role: "user", text: cap(strip(b.text), TEXT_CAP) }); + else if (b.role === "system") { const t = Array.isArray(b.lines) ? b.lines.map(strip).join("\n") : strip(b.text); if (t.trim()) out.push({ i, role: "system", text: cap(t, OUT_CAP) }); } + else if (b.role === "nexus") out.push({ i, role: "assistant", items: itemsView(b.items, tail) }); + else if (b.role === "diff") out.push({ i, role: "system", text: cap(strip(b.text || "[diff]"), OUT_CAP) }); + }); + return out; +} + +// Every shell command in order, with its output: the "terminal" view. +function terminal(conv, bang) { + const rows = []; + for (const m of conv) { + if (m.role === "system" && /^\$ /.test(m.text)) { const nl = m.text.indexOf("\n"); rows.push({ by: "you", command: m.text.slice(2, nl < 0 ? undefined : nl), output: nl < 0 ? "" : m.text.slice(nl + 1), status: /\nrunning…$/.test(m.text) ? "running" : "done" }); } + if (m.role !== "assistant") continue; + for (const it of m.items) if (it.type === "tool" && it.kind === "shell" && it.command) rows.push({ by: "agent", command: it.command, output: it.output, status: it.status, start: it.start, end: it.end, live: it.live }); + } + return rows; +} + +// Files the agent read, changed and searched, with counts; plus web fetches. +function fileActivity(conv) { + const files = new Map(), searches = [], web = []; + const hit = (p, k, t) => { if (!p) return; const f = files.get(p) || { path: p, read: 0, edit: 0, last: 0, diffs: 0 }; f[k]++; f.last = Math.max(f.last, t || 0); files.set(p, f); }; + for (const m of conv) { + if (m.role !== "assistant") continue; + for (const it of m.items) { + if (it.type !== "tool") continue; + if (it.kind === "read") hit(it.file, "read", it.start); + else if (it.kind === "edit") { hit(it.file, "edit", it.start); if (it.diff && it.file) files.get(it.file).diffs++; } + else if (it.kind === "search") searches.push({ label: it.label, status: it.status }); + else if (it.kind === "web") web.push({ label: it.label, status: it.status }); + } + } + return { files: [...files.values()].sort((a, b) => b.last - a.last), searches: searches.slice(-200), web: web.slice(-200) }; +} + +// Sub-agents with their own conversations. +function agentsView(agents, tail) { + return (agents || []).map((a) => ({ id: a.id, task: strip(a.task), status: a.status, start: a.start || 0, end: a.end || 0, engine: a.engine || "", result: cap(strip(a.result), OUT_CAP), prompt: cap(strip(a.prompt || ""), INPUT_CAP), items: itemsView(a.items, tail) })); +} + +// Cheap change signature, so the browser refetches the heavy detail only when something moved. +function revision(transcript, agents) { + let h = (transcript || []).length + ":" + (agents || []).length; + const tailBlocks = (transcript || []).slice(-3); + for (const b of tailBlocks) { + h += "|" + (b && b.role) + (b && b.text ? String(b.text).length : 0); + for (const it of (b && b.items) || []) h += "," + (it.status || "") + (it.full ? it.full.length : 0) + "." + (it.result !== undefined ? asText(it.result).length : 0) + (it.live ? "L" + ((it.live.bytes || 0) + (it.live.droppedBytes || 0) + String(it.live.partial || "").length) : ""); + } + for (const a of agents || []) h += "|" + a.status + ((a.items || []).length) + (a.result ? String(a.result).length : 0); + return h; +} + +module.exports = { asText, kindOf, conversation, terminal, fileActivity, agentsView, revision, strip }; diff --git a/lib/nexus/dashboard.js b/lib/nexus/dashboard.js index 9ed7b20..ef10045 100644 --- a/lib/nexus/dashboard.js +++ b/lib/nexus/dashboard.js @@ -1,273 +1,252 @@ "use strict"; -// Nexus localhost dashboard — a live web view of the running agent: pipelines, -// background jobs, the cowork pair, the current plan, and token/cost telemetry. +// Nexus localhost dashboard (/open, /dashboard): a live, read-only window onto the +// running agent. It shows everything the TUI knows: the full conversation with +// thinking, every tool call with its input and output, a terminal log of every +// shell command (running ones stream), files read and changed with their diffs, +// sub-agents with their own conversations, background jobs with output, the +// per-turn cost ledger, the plan and the cowork pair. // -// Unlike lib/cli/api-server.js (a separate process that shells out and therefore -// cannot see live state), this server is started FROM INSIDE the TUI process and -// reads a getState() closure, so every request reflects the real in-memory jobs, -// cowork pairing, plan and counters. Bound to 127.0.0.1 only (private, no auth). +// The server runs INSIDE the TUI process and reads closures, so it reflects real +// in-memory state. Bound to 127.0.0.1, Host and Origin checked, never framed. +// Read-only: there is no endpoint that changes anything. const http = require("http"); +const crypto = require("crypto"); -function esc(s) { - return String(s == null ? "" : s).replace(/[&<>"']/g, (c) => - ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); -} - -// ---- the page (self-contained: no external fonts, scripts or network) ---- const PAGE = ` - + -Nexus Dashboard - -
- - - engine— - dir— - - connecting -
- -
-
-
-

Plan

-

Cowork

-

Background jobs

-

Pipelines

-

Files changed

-

Tools used

-

Recent activity

-
-
Nexus dashboard · localhost only
+
+ NEXUS + idle + model- + mode- + dir- + + connecting
- - `; -// Build one SSE data frame. -function sseFrame(obj) { - return "data: " + JSON.stringify(obj).replace(/\n/g, "\\n") + "\n\n"; -} +function sseFrame(obj) { return "data: " + JSON.stringify(obj).replace(/\n/g, "\\n") + "\n\n"; } -// getState(): () => snapshot object (see darknode.js dashboardState()). +// opts.getState(): light snapshot sent every second (must include `rev`). +// opts.getDetail(): heavy snapshot (conversation, terminal, files, agents, turns), +// fetched by the page only when rev changes. +// opts.getJob(id): { id, output } for one background job, or null. // Returns a Promise<{ url, port, server, close }>. function startDashboard(opts) { opts = opts || {}; - const getState = typeof opts.getState === "function" ? opts.getState : () => ({}); - const host = "127.0.0.1"; - const first = opts.port || 7979; - const tries = 25; + const call = (f, d, a) => { try { return (typeof f === "function" ? f(a) : null) || d; } catch (_) { return d; } }; + const host = "127.0.0.1", first = opts.port || 7979, tries = 25; const makeServer = () => http.createServer((req, res) => { - const url = (req.url || "/").split("?")[0]; + const u = new URL(req.url || "/", "http://x"), url = u.pathname; if (req.method !== "GET") { res.writeHead(405); res.end(); return; } - // Loopback binding stops other machines, not the user's own browser: any page - // they visit could read this session (prompts, activity, files, job commands) - // cross-origin, or reach it via DNS rebinding. Serve only requests addressed - // to this loopback port from this origin; no CORS (the page is same-origin). - const port = req.socket.localPort; - const okHosts = ["127.0.0.1:" + port, "localhost:" + port]; + // Loopback stops other machines, not other pages in the user's own browser: any + // site could read this session cross-origin or via DNS rebinding. Serve only + // requests addressed to this loopback port, from this origin; no CORS. + const port = req.socket.localPort, okHosts = ["127.0.0.1:" + port, "localhost:" + port]; if (!okHosts.includes(String(req.headers.host || "").toLowerCase())) { res.writeHead(403); res.end(); return; } const origin = req.headers.origin; if (origin && !okHosts.some((h) => origin.toLowerCase() === "http://" + h)) { res.writeHead(403); res.end(); return; } + const json = (obj) => { res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" }); res.end(JSON.stringify(obj)); }; if (url === "/" || url === "/index.html") { - res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); - res.end(PAGE); + const nonce = crypto.randomBytes(16).toString("base64"); + res.writeHead(200, { + "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", + "Content-Security-Policy": "default-src 'none'; script-src 'nonce-" + nonce + "'; style-src 'nonce-" + nonce + "'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", + }); + res.end(PAGE.replace(/__NONCE__/g, nonce)); return; } if (url === "/favicon.ico") { - // Inline SVG favicon (cyan→violet "N" mark) so the tab has an icon and the - // browser's automatic request doesn't 404 in the console. res.writeHead(200, { "Content-Type": "image/svg+xml", "Cache-Control": "max-age=86400" }); - res.end(''); - return; - } - if (url === "/api/state") { - let state = {}; try { state = getState() || {}; } catch (_) {} - res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); - res.end(JSON.stringify(state)); + res.end(''); return; } + if (url === "/api/state") return json(call(opts.getState, {})); + if (url === "/api/detail") return json(call(opts.getDetail, { conversation: [], terminal: [], files: { files: [], searches: [], web: [] }, agents: [], turns: [] })); + if (url === "/api/job") return json(call(opts.getJob, { output: null }, String(u.searchParams.get("id") || ""))); if (url === "/api/stream") { - res.writeHead(200, { - "Content-Type": "text/event-stream", - "Cache-Control": "no-store", - "Connection": "keep-alive", - }); - const tick = () => { let s = {}; try { s = getState() || {}; } catch (_) {} try { res.write(sseFrame(s)); } catch (_) {} }; + res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-store", "Connection": "keep-alive" }); + const tick = () => { try { res.write(sseFrame(call(opts.getState, {}))); } catch (_) {} }; tick(); const iv = setInterval(tick, 1000); req.on("close", () => clearInterval(iv)); @@ -281,20 +260,11 @@ function startDashboard(opts) { let attempt = 0; const tryListen = (port) => { const server = makeServer(); - server.on("error", (e) => { - if (e && e.code === "EADDRINUSE" && attempt < tries) { attempt++; tryListen(first + attempt); } - else reject(e); - }); - server.listen(port, host, () => { - resolve({ - url: "http://" + host + ":" + port, - port, server, - close: () => { try { server.close(); } catch (_) {} }, - }); - }); + server.on("error", (e) => { if (e && e.code === "EADDRINUSE" && attempt < tries) { attempt++; tryListen(first + attempt); } else reject(e); }); + server.listen(port, host, () => resolve({ url: "http://" + host + ":" + port, port, server, close: () => { try { server.close(); } catch (_) {} } })); }; tryListen(first); }); } -module.exports = { startDashboard }; +module.exports = { startDashboard, PAGE }; diff --git a/package.json b/package.json index 52465f2..60ee423 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "scripts": { "start": "node darknode.js", "build": "pkg . --out-path dist", - "test": "node test/run.js && node test/bg-cutoff.test.js && node test/usage-ping.test.js && node test/authz.test.js && node test/composer.test.js && node test/term.test.js && node test/md-render.test.js && node test/links.test.js && node test/pager.test.js && node test/tool-tail.test.js && node test/os-notify.test.js && node test/repo-map-rank.test.js && node test/bm25.test.js && node test/danger-audit.test.js && node test/url-guard-audit.test.js && node test/edit-audit.test.js && node test/jail-audit.test.js && node test/mcp-audit.test.js && node test/git-search-audit.test.js && node test/state-audit.test.js && node test/exec-audit.test.js && node test/cli-audit.test.js && node test/governance-audit.test.js && node test/toolkit-audit.test.js && node test/devhelpers-audit.test.js && node test/radar-audit.test.js && node test/pentest-audit.test.js && node test/shellfix-audit.test.js && node test/convo-lifecycle-audit.test.js && node test/local-loop-audit.test.js && node test/undo-audit.test.js && node test/at-mentions-audit.test.js && node test/clipboard-audit.test.js && node test/notes-audit.test.js && node test/snippets-audit.test.js && node test/typed-names-audit.test.js && node test/sighup-audit.test.js && node test/tui-stderr-audit.test.js && node test/piped-stdin-audit.test.js && node test/oneshot-escape-audit.test.js && node test/hot-path-speed-audit.test.js && node test/command-help.test.js && node test/session-save.test.js && node test/agents-panel.test.js && node test/tui-layout.test.js && node test/hub.test.js", + "test": "node test/run.js && node test/bg-cutoff.test.js && node test/usage-ping.test.js && node test/authz.test.js && node test/composer.test.js && node test/term.test.js && node test/md-render.test.js && node test/links.test.js && node test/pager.test.js && node test/tool-tail.test.js && node test/os-notify.test.js && node test/repo-map-rank.test.js && node test/bm25.test.js && node test/danger-audit.test.js && node test/url-guard-audit.test.js && node test/edit-audit.test.js && node test/jail-audit.test.js && node test/mcp-audit.test.js && node test/git-search-audit.test.js && node test/state-audit.test.js && node test/exec-audit.test.js && node test/cli-audit.test.js && node test/governance-audit.test.js && node test/toolkit-audit.test.js && node test/devhelpers-audit.test.js && node test/radar-audit.test.js && node test/pentest-audit.test.js && node test/shellfix-audit.test.js && node test/convo-lifecycle-audit.test.js && node test/local-loop-audit.test.js && node test/undo-audit.test.js && node test/at-mentions-audit.test.js && node test/clipboard-audit.test.js && node test/notes-audit.test.js && node test/snippets-audit.test.js && node test/typed-names-audit.test.js && node test/sighup-audit.test.js && node test/tui-stderr-audit.test.js && node test/piped-stdin-audit.test.js && node test/oneshot-escape-audit.test.js && node test/hot-path-speed-audit.test.js && node test/command-help.test.js && node test/session-save.test.js && node test/agents-panel.test.js && node test/tui-layout.test.js && node test/hub.test.js && node test/dashboard.test.js", "postinstall": "node scripts/postinstall.js", "docs": "node scripts/gen-nexus-docs.js" }, diff --git a/test/dashboard.test.js b/test/dashboard.test.js new file mode 100644 index 0000000..bf4abd2 --- /dev/null +++ b/test/dashboard.test.js @@ -0,0 +1,88 @@ +"use strict"; +// /open dashboard suite: the pure view builders (lib/nexus/dash-view.js) and the +// server's guards (lib/nexus/dashboard.js): loopback Host/Origin checks, read-only, +// CSP with a per-load nonce, and the detail/job endpoints. +const http = require("http"); +const V = require("../lib/nexus/dash-view"); +const { startDashboard } = require("../lib/nexus/dashboard"); +const { createTail, pushTail, tailText } = require("../lib/cli/tool-tail"); + +let pass = 0, fail = 0; +const ok = (name, cond) => { if (cond) pass++; else { fail++; console.log(" \x1b[31mFAIL\x1b[0m " + name); } }; +const eq = (name, a, b) => ok(name + " (" + JSON.stringify(a) + " === " + JSON.stringify(b) + ")", JSON.stringify(a) === JSON.stringify(b)); +const group = (t) => console.log("\n\x1b[1m" + t + "\x1b[0m"); +const get = (port, path, headers, method) => new Promise((res) => { + const r = http.request({ host: "127.0.0.1", port, path, method: method || "GET", headers: Object.assign({ Host: "127.0.0.1:" + port }, headers || {}) }, (x) => { let b = ""; x.on("data", (d) => (b += d)); x.on("end", () => res({ status: x.statusCode, headers: x.headers, body: b })); }); + r.on("error", () => res({ status: 0 })); r.end(); +}); + +(async () => { + group("view builders"); + const live = createTail(); pushTail(live, "building...\nstep 2\n"); + const transcript = [ + { role: "user", text: "fix the build" }, + { role: "system", text: "\x1b[36mcache\x1b[0m warm" }, + { role: "nexus", items: [ + { type: "thinking", full: "look at the error first" }, + { type: "tool", id: "t1", name: "Read", input: { file_path: "src/a.js" }, label: "Read(a.js)", status: "ok", start: 1000, end: 1200, result: [{ type: "text", text: "const a = 1;" }] }, + { type: "tool", id: "t2", name: "Edit", input: { file_path: "src/a.js", old_string: "1", new_string: "2" }, label: "Edit(a.js)", status: "ok", start: 1300, end: 1400, result: "ok", diff: { added: 1, removed: 1, rows: [{ t: "-", text: "const a = 1;", ln: 1 }, { t: "+", text: "const a = 2;", ln: 1 }] } }, + { type: "tool", id: "t3", name: "Bash", input: { command: "npm test" }, label: "Bash(npm test)", status: "err", start: 1500, end: 2500, result: "1 failed", isError: true }, + { type: "tool", id: "t4", name: "run_command", input: { command: "make" }, label: "make", status: "run", start: 3000 }, + { type: "tool", id: "t5", name: "Grep", input: { pattern: "foo" }, label: "Grep(foo)", status: "ok", start: 3100, end: 3150, result: "x" }, + { type: "text", full: "Fixed it." }, + ] }, + { role: "system", text: "$ ls\na.js" }, + { role: "art" }, + ]; + Object.defineProperty(transcript[2].items[4], "live", { value: live, configurable: true }); + const conv = V.conversation(transcript, { tail: tailText }); + eq("roles in order, art skipped", conv.map((m) => m.role), ["user", "system", "assistant", "system"]); + eq("ANSI colour codes are stripped", conv[1].text, "cache warm"); + const items = conv[2].items; + eq("item types", items.map((i) => i.type), ["thinking", "tool", "tool", "tool", "tool", "tool", "text"]); + eq("content-block results become text", items[1].output, "const a = 1;"); + eq("tool kinds", items.filter((i) => i.type === "tool").map((i) => i.kind), ["read", "edit", "shell", "shell", "search"]); + eq("statuses", items.filter((i) => i.type === "tool").map((i) => i.status), ["done", "done", "error", "running", "done"]); + ok("a running command shows its live output", items[4].live && /step 2/.test(items[4].output)); + eq("diff rows kept", items[2].diff.rows, [["-", "const a = 1;", 1], ["+", "const a = 2;", 1]]); + eq("shell command extracted", items[3].command, "npm test"); + const term = V.terminal(conv); + eq("terminal: agent commands then your ! command", term.map((r) => [r.by, r.command, r.status]), [["agent", "npm test", "error"], ["agent", "make", "running"], ["you", "ls", "done"]]); + const fa = V.fileActivity(conv); + eq("file activity merges reads and edits", fa.files.map((f) => [f.path, f.read, f.edit, f.diffs]), [["src/a.js", 1, 1, 1]]); + eq("searches listed", fa.searches.length, 1); + const big = V.conversation([{ role: "nexus", items: [{ type: "tool", id: "b", name: "Bash", input: { command: "cat x" }, status: "ok", result: "y".repeat(50000) }] }]); + ok("huge output is capped with a note", big[0].items[0].output.length < 21000 && /more characters/.test(big[0].items[0].output)); + eq("object results (local tools) render", V.asText({ code: 2, output: "boom" }), "boom\n[exit 2]"); + const ag = V.agentsView([{ id: "a1", task: "scan", status: "run", start: 1, prompt: "scan repo", items: [{ type: "text", full: "working" }] }]); + eq("agents carry their own items", ag[0].items, [{ type: "text", text: "working" }]); + const r1 = V.revision(transcript, []); pushTail(live, "step 3\n"); const r2 = V.revision(transcript, []); + ok("revision changes when a running command prints", r1 !== r2); + ok("revision is stable when nothing changes", V.revision(transcript, []) === r2); + const lean = JSON.stringify(transcript[2].items[4]); + ok("the live tail is still not serialized with the card", !/step 2/.test(lean)); + + group("server"); + const d = await startDashboard({ port: 7990, getState: () => ({ rev: "r1", engine: "claude" }), getDetail: () => ({ conversation: conv, terminal: term, files: fa, agents: [], turns: [] }), getJob: (id) => id === "j1" ? { id, output: "job out" } : null }); + const p = d.port; + const page = await get(p, "/"); + ok("page served", page.status === 200 && /NEXUS/.test(page.body)); + const csp = page.headers["content-security-policy"] || "", nonce = (/'nonce-([^']+)'/.exec(csp) || [])[1]; + ok("CSP: script needs the nonce, never framed", nonce && /frame-ancestors 'none'/.test(csp) && /default-src 'none'/.test(csp)); + ok("the nonce is on the inline script", page.body.includes('