Files
AgentHub/server/__tests__/server-mode-user-details.test.js
T
nntrivi2001 1c6dfea5b5 feat(health): System Health in three groups, a score that sees lag; admin user detail
Dashboard → System Health is grouped into AgentHub, Machine and Agent
activity. The machine (GET /api/host, every signed-in user) is drawn by
components/health/HostHealth.tsx: host card beside the CPU/memory history,
then CPU (threads as compact cells + temperatures/GPUs), disks & network,
busiest processes, and per-user tiles. Concurrency bars each show their own
agent type on hover.

The Health Score (client/src/lib/healthScore.ts) is now 100 minus what each
check costs, between an amber and a red threshold: event-loop p99
(server/lib/loop-delay.js, shared with /api/metrics), Linux PSI pressure for
CPU, memory and disk I/O (/api/host `pressure`; load per core without PSI),
RAM, the database's disk, V8 heap, hooks silent while agents work, and agent
errors in the last 24 h. All-time success rate, API errors and the transcript
cache hit rate no longer count. /api/settings/info adds server.event_loop and
activity {last_event_at, working_agents, agents_24h}.

Administration: a user row opens its detail in place (GET
/api/users/:id/details — spend, account pool share, live panes, workspaces,
newest sessions); the server panel is gone, member tmux folded into the table;
the Sessions list shows each row's owner in server mode.
2026-10-27 16:39:38 +07:00

164 lines
6.4 KiB
JavaScript

/**
* @file server-mode-user-details.test.js
* @description `GET /api/users/:id/details` — the Administration page's user
* detail: the account, its workspaces and live panes, newest sessions, spend
* per day / AI tool / model, the audit entries naming it, and per pool tool
* the accounts it may run on with its own share of each. Staff only, 404 for
* an unknown user, never a token or a password hash.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");
const path = require("node:path");
const fs = require("node:fs");
const os = require("node:os");
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "server-mode-user-details-"));
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
process.env.CLAUDE_HOME = path.join(TMP, ".claude");
process.env.CODEX_HOME = path.join(TMP, ".codex");
process.env.DASHBOARD_LIVENESS_PROBE = "0";
const { createApp, startServer } = require("../index");
const { db } = require("../db");
const auth = require("../lib/auth");
// The quota read would go to the network.
require("../lib/cc-usage").fetchUsage = async () => ({});
let server;
let BASE;
const BOSS_PASS = "admin-pass-1";
const TOKEN = `sk-ant-oat01-${"a".repeat(40)}`;
const ids = {};
async function call(method, p, { cookie, body } = {}) {
const res = await fetch(BASE + p, {
method,
headers: { "Content-Type": "application/json", ...(cookie ? { cookie } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
return { status: res.status, body: await res.json().catch(() => null) };
}
async function login(username, password) {
const res = await fetch(BASE + "/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
return res.headers.get("set-cookie").split(";")[0];
}
before(async () => {
process.env.AGENTHUB_MODE = "server";
server = await startServer(createApp(), 0);
BASE = `http://127.0.0.1:${server.address().port}`;
ids.boss = (await auth.createUser("boss", BOSS_PASS, "admin")).id;
await auth.createUser("ana", "analyst-pass-1", "analyst");
ids.mia = (await auth.createUser("mia", "member-pass-1", "developer")).id;
const lane = db
.prepare("INSERT INTO lanes (cwd, title, tool, owner_id) VALUES ('/w/mia', 'Mia', 'claude', ?)")
.run(ids.mia).lastInsertRowid;
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('sm', 'mia work', 'active', '/w/mia', ?)"
).run(lane);
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id, tool) VALUES ('sc', 'mia codex', 'completed', '/w/mia', ?, 'codex')"
).run(lane);
const hour = new Date().toISOString().slice(0, 13);
for (const [sid, tokens] of [
["sm", 1000000],
["sc", 500000],
]) {
db.prepare(
`INSERT INTO token_usage (session_id, model, output_tokens)
VALUES (?, 'claude-sonnet-4-5-20250929', ?)`
).run(sid, tokens);
db.prepare(
`INSERT INTO token_usage_hourly (session_id, hour, model, output_tokens)
VALUES (?, ?, 'claude-sonnet-4-5-20250929', ?)`
).run(sid, hour, tokens);
}
const boss = await login("boss", BOSS_PASS);
const add = await call("POST", "/api/accounts", {
cookie: boss,
body: { tool: "claude", name: "team-1", token: TOKEN, currentPassword: BOSS_PASS },
});
assert.equal(add.status, 201);
db.prepare(
`INSERT INTO dashboard_runs (id, session_id, mode, cwd, status, lane_id, tool, account)
VALUES ('agenthub-lane-1', 'sm', 'interactive', '/w/mia', 'running', ?, 'claude', 'team-1')`
).run(lane);
});
after(() => {
delete process.env.AGENTHUB_MODE;
server?.close();
fs.rmSync(TMP, { recursive: true, force: true });
});
describe("GET /api/users/:id/details", () => {
it("shows staff one user's workspaces, panes, sessions, spend and pool share", async () => {
const boss = await login("boss", BOSS_PASS);
const r = await call("GET", `/api/users/${ids.mia}/details`, { cookie: boss });
assert.equal(r.status, 200, JSON.stringify(r.body));
const d = r.body;
assert.equal(d.user.username, "mia");
assert.equal(d.sessions.total, 2);
assert.equal(d.sessions.active, 1);
assert.deepEqual(
d.workspaces.map((w) => [w.title, w.sessions, w.livePanes]),
[["Mia", 2, 1]]
);
assert.deepEqual(
d.panes.map((p) => [p.id, p.account]),
[["agenthub-lane-1", "team-1"]]
);
assert.deepEqual(d.recentSessions.map((s) => s.id).sort(), ["sc", "sm"]);
assert.ok(d.recentSessions.every((s) => s.tokens > 0 && s.cost > 0));
assert.equal(d.usage.last30d.tokens, 1500000);
assert.equal(d.usage.today.tokens, 1500000);
assert.equal(d.usage.daily.length, 30);
assert.equal(d.usage.daily.at(-1).tokens, 1500000, "today is the last bar");
assert.deepEqual(
d.usage.byTool.map((b) => [b.key, b.tokens, b.sessions]),
[
["claude", 1000000, 1],
["codex", 500000, 1],
]
);
assert.deepEqual(
d.usage.byModel.map((b) => b.key),
["claude-sonnet-4-5-20250929"]
);
const team = d.pool.claude.accounts.find((a) => a.name === "team-1");
assert.equal(team.allowed, true);
assert.equal(team.userRuns7d, 1);
assert.equal(team.userLivePanes, 1);
assert.equal(team.userTokens7d, 1000000, "only the hours its run held the session");
assert.equal(d.pool.claude.pin, null);
assert.ok(!JSON.stringify(d).includes(TOKEN), "never a token");
assert.ok(!JSON.stringify(d).includes("scrypt"), "never a password hash");
});
it("lists the audit entries naming the user", async () => {
const boss = await login("boss", BOSS_PASS);
await call("GET", "/api/sessions/sm", { cookie: boss });
const d = (await call("GET", `/api/users/${ids.mia}/details`, { cookie: boss })).body;
assert.ok(d.audit.some((a) => a.reader === "boss" && a.owner === "mia"));
});
it("is staff only and 404s an unknown user", async () => {
const ana = await login("ana", "analyst-pass-1");
assert.equal((await call("GET", `/api/users/${ids.mia}/details`, { cookie: ana })).status, 200);
const mia = await login("mia", "member-pass-1");
assert.equal((await call("GET", `/api/users/${ids.mia}/details`, { cookie: mia })).status, 403);
const boss = await login("boss", BOSS_PASS);
assert.equal((await call("GET", "/api/users/9999/details", { cookie: boss })).status, 404);
});
});