Files
AgentHub/server/lib/dashboard-runs.js
T
nntrivi2001 c507d37baf feat: AI Router per session; Settings at the sidebar's foot; shipped tool icons
AI Router is a session's choice, not a workspace's:
- an AI Router select beside the model picker in the workspace home and a
  pane's run form (RouterPicker.tsx; hidden off Claude/Codex or with only
  Native; last pick remembered in agenthub.session.router)
- `router` on POST /api/lanes/:id/start and POST /api/run; Claude gets
  --settings=<data dir>/router-settings/<name>.json (0600, outranks project
  and user settings, key never in argv), Codex -p <name> + key via tmux -e
- dashboard_runs.router; a resume naming none goes back to it
- profile PATCH rewrites the session files, DELETE removes them
- gone: POST /api/lanes/:id/router/apply, LaneRouterRow, the Add-workspace
  router radio, the claude-/codex-home `routers` answers; clearLaneRouters
  takes the old keys out of each workspace's settings.local.json at start

Sidebar: Settings pinned to the foot, the collapse toggle beside it (stacked
on the rail) instead of in the brand's corner.

Icons: shipped SVG marks for claude, codex, openclaw and hermes (a
black/white pair swapped by theme) in client/public/ai-tools/, used by
AiToolIcon before the server's favicon.
2026-10-02 14:19:02 +07:00

216 lines
7.4 KiB
JavaScript

/**
* @file dashboard-runs.js
* @description Persistence layer for runs spawned via the dashboard's
* /api/run endpoint. The in-memory handle map in run-spawner.js reaps
* handles 5 min after exit, which is fine for live re-attach but loses
* historical data. This module mirrors every spawn / status transition
* into a sqlite row so the Run page can show a full history of what
* the user has spawned and resume any of those sessions.
*
* All db operations are wrapped in try/catch so a failure here can never
* take down a live run — persistence is a side benefit, not a blocker.
*
* A run started through a lane also carries that lane's id (`lane_id`), so the
* Workspace page can list one lane's own run history; runs spawned straight
* from POST /api/run leave it null.
*
* A run's id is its tmux pane name (`agenthub-lane-<id>[-slot]`), which every
* Start in that pane reuses. So a new run first ARCHIVES the row it replaces
* under `<id>@<its started_at>` (flagged `abandoned` if it never said it
* ended) — history is kept, and `getRun(<pane name>)` is always the pane's
* current run. A row is flagged dead only once its tmux session is gone
* (`reconcileOrphans(isAlive)`): panes outlive a server restart.
*
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { db } = require("../db");
const PROMPT_PREVIEW_LIMIT = 500;
const insertStmt = db.prepare(`
INSERT OR REPLACE INTO dashboard_runs (
id, session_id, mode, cwd, model, permission_mode, effort,
resume_session_id, prompt_preview, status, exit_code, started_at, ended_at,
lane_id, tool, worktree, router
) VALUES (
@id, @session_id, @mode, @cwd, @model, @permission_mode, @effort,
@resume_session_id, @prompt_preview, @status, @exit_code, @started_at, @ended_at,
@lane_id, @tool, @worktree, @router
)
`);
const updateStmt = db.prepare(`
UPDATE dashboard_runs
SET session_id = COALESCE(@session_id, session_id),
status = COALESCE(@status, status),
exit_code = COALESCE(@exit_code, exit_code),
ended_at = COALESCE(@ended_at, ended_at)
WHERE id = @id
`);
const RUN_COLUMNS = `id, session_id, mode, cwd, model, permission_mode, effort,
resume_session_id, prompt_preview, status, exit_code,
started_at, ended_at, lane_id, tool, worktree, router`;
const listStmt = db.prepare(`
SELECT ${RUN_COLUMNS}
FROM dashboard_runs
ORDER BY started_at DESC
LIMIT @limit
`);
const listByLaneStmt = db.prepare(`
SELECT ${RUN_COLUMNS}
FROM dashboard_runs
WHERE lane_id = @laneId
ORDER BY started_at DESC
LIMIT @limit
`);
const getStmt = db.prepare(`
SELECT ${RUN_COLUMNS}
FROM dashboard_runs WHERE id = @id
`);
// The row a new run in the same pane replaces, kept under its own id.
const archiveStmt = db.prepare(`
UPDATE dashboard_runs
SET id = id || '@' || started_at,
status = CASE WHEN status IN ('running', 'spawning') THEN 'abandoned' ELSE status END,
ended_at = COALESCE(ended_at, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
WHERE id = ?
`);
/**
* Insert a new run record at spawn time; the pane's previous run, if any, is
* archived first rather than overwritten.
*/
function recordRun(handle) {
try {
try {
archiveStmt.run(handle.id);
} catch (err) {
// An archive id already taken (an imported bundle) — fall back to the
// replace below rather than lose the new run.
console.warn(`[dashboard-runs] could not archive run ${handle?.id}: ${err.message}`);
}
const startedAt = new Date(handle.startedAt || Date.now()).toISOString();
const endedAt = handle.endedAt ? new Date(handle.endedAt).toISOString() : null;
const prompt = typeof handle.prompt === "string" ? handle.prompt : "";
insertStmt.run({
id: handle.id,
session_id: handle.sessionId || null,
mode: handle.mode,
cwd: handle.cwd || "",
model: handle.model || null,
permission_mode: handle.permissionMode || null,
effort: handle.effort || null,
resume_session_id: handle.resumeSessionId || null,
prompt_preview: prompt.slice(0, PROMPT_PREVIEW_LIMIT) || null,
status: handle.status || "spawning",
exit_code: typeof handle.exitCode === "number" ? handle.exitCode : null,
started_at: startedAt,
ended_at: endedAt,
lane_id: typeof handle.laneId === "number" ? handle.laneId : null,
tool: typeof handle.tool === "string" && handle.tool ? handle.tool : "claude",
worktree: handle.worktree ? 1 : 0,
router: handle.router || null,
});
} catch (err) {
// Best-effort by design (a live run must never fail because sqlite did),
// but not silent: a swallowed insert leaves the runs modal showing rows with
// no cwd, model, prompt or start time, which reads as a UI bug rather than a
// persistence one. Say it once, here, where the cause is known.
console.warn(`[dashboard-runs] failed to record run ${handle?.id}: ${err.message}`);
}
}
/**
* Patch an existing run record. Pass null/undefined for fields you don't
* want to overwrite — COALESCE in SQL leaves the existing value untouched.
*/
function patchRun({ id, sessionId, status, exitCode, endedAt }) {
try {
updateStmt.run({
id,
session_id: sessionId ?? null,
status: status ?? null,
exit_code: typeof exitCode === "number" ? exitCode : null,
ended_at: endedAt ? new Date(endedAt).toISOString() : null,
});
} catch {
/* ignore */
}
}
/** @param {{limit?: number, laneId?: number|null}} [opts] laneId narrows to one lane's runs. */
function listRuns({ limit = 50, laneId = null } = {}) {
try {
const safeLimit = Math.max(1, Math.min(500, Math.floor(Number(limit) || 50)));
if (laneId != null) return listByLaneStmt.all({ limit: safeLimit, laneId });
return listStmt.all({ limit: safeLimit });
} catch {
return [];
}
}
function getRun(id) {
try {
return getStmt.get({ id }) || null;
} catch {
return null;
}
}
const sessionRouterStmt = db.prepare(`
SELECT router FROM dashboard_runs
WHERE session_id = @sessionId OR resume_session_id = @sessionId
ORDER BY started_at DESC LIMIT 1
`);
/**
* The AI Router the newest run holding `sessionId` started on (null = native,
* or no run known) — what a resume that names no router goes back to.
*/
function routerForSession(sessionId) {
try {
return sessionRouterStmt.get({ sessionId })?.router || null;
} catch {
return null;
}
}
const runningStmt = db.prepare(
"SELECT id FROM dashboard_runs WHERE status IN ('running', 'spawning')"
);
const abandonStmt = db.prepare(`
UPDATE dashboard_runs
SET status = 'abandoned',
ended_at = COALESCE(ended_at, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
WHERE id = ? AND status IN ('running', 'spawning')
`);
/**
* Flags `abandoned` every row still marked running/spawning whose pane is
* gone — the pane's process quit (Ctrl+C, `exit`), or the machine rebooted.
* A pane is a tmux session, which outlives a server restart, so liveness is
* asked of `isAlive(id)` (tmux), never assumed from the restart. Run at boot
* and on the server's run-heal beat.
*
* Returns the number of rows updated.
*/
function reconcileOrphans(isAlive = () => false) {
try {
let changes = 0;
for (const { id } of runningStmt.all()) {
if (!isAlive(id)) changes += abandonStmt.run(id).changes;
}
return changes;
} catch {
return 0;
}
}
module.exports = { recordRun, patchRun, listRuns, getRun, reconcileOrphans, routerForSession };