Compare commits

..

4 Commits

Author SHA1 Message Date
nntrivi2001 c41114faf8 chore: v2.8.42 — terminal glyphs stay sharp after the WebGL atlas fills up 2026-10-30 10:10:33 +07:00
nntrivi2001 c850f7603a fix(terminal): re-upload the shared WebGL atlas after a page merge
@xterm/addon-webgl 0.19 shares one glyph atlas between every terminal
with the same font. When it fills, four pages are merged into a larger
one and the rest shift down; a GPU texture is re-uploaded only when its
page version differs, and those counters can coincide, so a slot keeps a
stale page of another size and every glyph is drawn squeezed or foreign
(fixed upstream only in the 0.20 betas). On a merge — and when the page
comes back — toggle the font family's trailing space on the next frame,
which makes each renderer re-acquire its atlas and re-upload all pages.

This also drops yesterday's clearTextureAtlas on focus: it emptied the
SHARED atlas but redrew only the calling pane, corrupting its siblings.
2026-10-30 10:09:28 +07:00
nntrivi2001 5463e354fa chore: v2.8.41 — a session outside every workspace counts toward its user's spend 2026-10-30 08:50:58 +07:00
nntrivi2001 783b7f4101 fix(cost): bill a session outside every workspace to its Linux account's user
A script's claude -p in a temp folder (the SG Flow eval runner strips the
pane's env) had no workspace, so its spend reached nobody's Today, the Users
page or a spend quota — ~$57 of a $74 day was missing from the status bar.

sessions.account records the Linux account a session ran as (the hook's
peer uid, else its folder for poller-made and old rows); a session no
workspace owns is owned by that account's user — a member's to them, the
host's to the admin ticked 'Owns this server's host account' (or the only
admin). Workspace ownership still wins.
2026-10-30 08:50:34 +07:00
21 changed files with 387 additions and 28 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
# Claude Code Working Guide
_Last synced: v2.8.40 (2026-10-29) — a Codex profile switch restarts Codex's app-server daemon so sessions follow._ A change that makes any statement in this file, `AGENTS.md`, or a README wrong — a moved path, a new or changed extension point, a retired rule — updates that file in the same change-set and bumps this marker. **Bump = replace the version/date and a ≤ 1-line summary; never append a changelog here** — details belong in the commit message and `docs/`, because this whole file is loaded into every session.
_Last synced: v2.8.41 (2026-10-30) — a session outside every workspace is billed to the user of the Linux account it ran as._ A change that makes any statement in this file, `AGENTS.md`, or a README wrong — a moved path, a new or changed extension point, a retired rule — updates that file in the same change-set and bumps this marker. **Bump = replace the version/date and a ≤ 1-line summary; never append a changelog here** — details belong in the commit message and `docs/`, because this whole file is loaded into every session.
## Project mission
- Maintain a reliable local-first dashboard for Claude Code session monitoring.
@@ -62,7 +62,7 @@ A **workspace** — called a **lane** in the API, CLI, database and code, which
- **Server tests never touch the user's tmux.** Run them through `npm run test:server` (`scripts/test-server.js`), never a bare `node --test server/__tests__/*.test.js` from inside a lane pane — the suites create and kill real `agenthub-lane-<id>` sessions.
- **An artifact is shared as a SNAPSHOT and installed only into the viewer's own account.** `server/lib/artifacts.js` (`/api/artifacts`): a pinned file or a skill is copied once into `<data dir>/artifacts/<random>/` and every viewer reads only that copy (an owner's edit of a skill — in the Hub, or in the skill's source folder, which the server takes when the Hub is listed and an installer's differing copy is then offered **Update** — writes a NEW snapshot and drops the old one — never a write into the one being read; the newer of the two changes wins) — `raw` serves only a file the snapshot recorded, under a `sandbox` CSP + `nosniff`; a `page` is a `https://claude.ai/…` link only. A developer sees their own rows plus shared ones; only the owner or an admin changes one. Install writes a skill into BOTH `~/.claude/skills/` and the cross-tool `~/.agents/skills/` of every account the CALLER's sessions run as (`installAccounts`: their S3 member home, plus the host's for an admin, whose host-folder workspaces run as the host; S3: as them through `write-as`), never over an existing one without `replace` (the old one is moved to `~/.claude/agenthub-replaced-skills/`, never deleted), and runs a plugin's `claude plugin marketplace add`/`install --scope user` as the caller, never with `-y`; Uninstall (`POST /api/artifacts/:id/uninstall`) takes it out of the same accounts — a skill MOVED to `agenthub-replaced-skills/`, never deleted, a plugin `claude plugin uninstall --scope user --keep-data`; an admin's switch (Settings → AI tools, `ArtifactsHubSettings`) turns installs off. An uploaded or written skill is snapshotted under the same checks (paths relative, no `..`, no secret names, zip sizes read before inflating). `POST /api/artifacts/plugin/inspect` clones a user-named https link only to read `marketplace.json`, with every credential helper OFF — never send a login with it. Do not add a route that serves a live file of another user, installs into someone else's account, or takes a plugin command from the request.
- **A workspace's instructions, extra folders and context files are lane facts, and a pane reads them only from the lane's rows.** The one addition is the workspace OWNER's own agent instructions (`user_prefs.instructions`, `PUT /api/me/instructions`, Settings → AI tools), which `launchExtras` puts first — keyed by `lanes.owner_id` (`local` in local mode), never by whoever clicked Start. `lanes.instructions` and `lane_sources` (`server/lib/lane-sources.js`) reach a pane through `launchExtras(laneId, tool)`, which `spawnRun` calls ITSELF — so neither spawn path can take them from a request — and every write is same-origin (`server/routes/lane-sources.js`). A folder must be absolute, exist, be a directory, not be or contain the OS home (`validateHomeDir`) and not be the workspace's own folder; it is the user's, and AgentHub never deletes it. An uploaded file is stored under `<data dir>/workspace-context/<lane id>/` under a name AgentHub derives (never a path from the request), and those copies are the only thing here AgentHub deletes (`ownsFile`): with their row, and with the workspace in `deleteLane`. Claude's `--add-dir` is VARIADIC, so it goes first in the argv where `--permission-mode` ends it, and the text (instructions + context file list + extra folders) is written at every spawn as the ONLY file `CLAUDE.md` of `<data dir>/workspace-prompts/<lane id>/` (a member's: `prompt-<lane id>/` in their handoff dir, via `write-as`), which goes in as one more `--add-dir` with `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` in the pane env — never `--append-system-prompt-file`: a custom system prompt is a launch flag Claude cannot carry over a restart, so it refused `/tui` in every pane with instructions (side effect: a CLAUDE.md in an extra folder is now read too); Codex gets one `--add-dir` per directory and `-c developer_instructions=<JSON string>` — the text itself up to 6 KB, else a line pointing at that file. Only `claude`/`codex` take them. Never write them into the user's repo (CLAUDE.md/AGENTS.md).
- **A workspace's sessions are the ones it OWNS, never the ones that ran in its folder.** `sessions.lane_id` is stamped by `bindRunSession` (`server/routes/hooks.js`) for the session a dashboard pane holds — first writer wins, a nested `claude -p` excluded — and no route sets it. A Codex/Antigravity session (their hooks are opt-in, so a pane may never learn its session) is also stamped by `claimToolSessions` (`server/lib/dashboard-runs.js`, called by both pollers and once at start): the lane of the newest same-tool dashboard run in the session's folder that was live when the session started, never a Claude session. A new Claude pane is started with `--session-id <uuid>` (`spawnRun`), so its `dashboard_runs.session_id` is known before any hook and a hook that carries no `run_id` (a hook handler older than `AGENTHUB_RUN_ID` forwarding) is still stamped from that run (`laneForSession`). Every workspace session list reads `GET /api/sessions?lane=<id>` — which also counts a still-unstamped session one of the lane's `dashboard_runs` holds, because hooks reach only the lowest-port dashboard on a shared DB and that one may be an older build that never stamps — and shows nothing else (no "other sessions in this folder"). Do not go back to listing a workspace by `cwd`, and do not guess ownership for old history.
- **A workspace's sessions are the ones it OWNS, never the ones that ran in its folder.** `sessions.lane_id` is stamped by `bindRunSession` (`server/routes/hooks.js`) for the session a dashboard pane holds — first writer wins, a nested `claude -p` excluded — and no route sets it. A Codex/Antigravity session (their hooks are opt-in, so a pane may never learn its session) is also stamped by `claimToolSessions` (`server/lib/dashboard-runs.js`, called by both pollers and once at start): the lane of the newest same-tool dashboard run in the session's folder that was live when the session started, never a Claude session. A new Claude pane is started with `--session-id <uuid>` (`spawnRun`), so its `dashboard_runs.session_id` is known before any hook and a hook that carries no `run_id` (a hook handler older than `AGENTHUB_RUN_ID` forwarding) is still stamped from that run (`laneForSession`). Every workspace session list reads `GET /api/sessions?lane=<id>` — which also counts a still-unstamped session one of the lane's `dashboard_runs` holds, because hooks reach only the lowest-port dashboard on a shared DB and that one may be an older build that never stamps — and shows nothing else (no "other sessions in this folder"). Do not go back to listing a workspace by `cwd`, and do not guess ownership for old history. Billing has one more owner: a session NO workspace owns belongs to the user of the Linux account it ran as (`sessions.account` — the hook's peer, else its folder; `server/lib/session-account.js`, the host's account → the admin marked `users.host_account`, else the only admin), so a script's `claude -p` counts in Today, the Users page and spend quotas — a workspace's ownership always wins over it.
- **A session's worktree is `claude --worktree`'s, resolved from the session row — and removing it never forces.** A Worktree start passes `--worktree=<server-made name>` (the `=` form: `-w [name]` eats the prompt otherwise) and Claude Code makes, populates and cleans up `<repo>/.claude/worktrees/<name>`; AgentHub only excludes `/.claude/worktrees/` at the repo root. A git route, a resume or a removal may work in a session's worktree only through `sessionWorktree` (`server/lib/session-worktree.js`: the session owned by the lane, its cwd not the lane's folder, registered by `git worktree list`) — `?session=` on the git routes answers `ENOWORKTREE` rather than falling back to the main folder. `POST /api/lanes/:id/session-worktree/remove` (same-origin, `confirm: true`, refused while a live pane holds the session) is the ONE dashboard path that deletes a worktree: `git worktree remove` with no `--force`, `git branch -d` never `-D`, a live-pid lock refused. Do not add a force, and do not let it touch a lane's own folder.
- **Opening a session never resumes it — only SENDING a message to it does.** The sidebar and a workspace home ATTACH pane 0 to a session's live tmux pane (`/workspace?lane=<id>&run=<runId>`, `attachRequest` on `LaneConsolePane`) or, for an ended one, open it in its workspace like Claude Desktop (`/workspace?lane=<id>&session=<id>`, `client/src/components/lanes/SessionReplay.tsx`: its conversation read-only plus a prompt box; the console is only hidden, CSS). A resume re-reads the whole transcript into context, so it happens only on an explicit action: a message SENT from that replay (`resumeSessionId` + `prompt`, first free slot), the transcript page's **Resume**/**Fork** (`SessionResumeButton.tsx`, behind a warning), or the ticked sessions of the **Resume interrupted sessions?** dialog (`InterruptedSessionsPrompt.tsx`, `GET /api/run/interrupted` — runs whose pane died under them; opening it resumes nothing). The analysis page `/sessions/<id>` is reached from the session view's **Analyst** button (beside Files/Changes in the right panel). Do not add a path that resumes on a click. A resume is refused while a live pane holds the session (`409 ESESSIONLIVE` with that pane's `run_id`) — open that pane instead; a fork makes a new session and is allowed.
- **A chat artifact runs in its own sandbox, never on the dashboard's origin.** The artifact panel (`client/src/components/run/ChatFilePreview.tsx`, `client/src/lib/artifactView.ts`) runs model-written HTML/Mermaid/React in an `<iframe srcdoc sandbox="allow-scripts …">` and an SVG in `sandbox=""` — never add `allow-same-origin` (the script would read the dashboard's cookies and call its API as the user), never render one with `dangerouslySetInnerHTML`, and keep its CDN libraries pinned to exact versions. An HTML FILE opened from the Changes panel, a Chat file preview or the File Explorer runs in the same sandbox (`client/src/components/HtmlFrame.tsx`, shown in a modal — `HtmlViewerModal.tsx`, Chat's `FilePreview modal`); its relative CSS/scripts/images are fetched by the DASHBOARD through the existing download routes and inlined (`client/src/lib/htmlInline.ts`) — never add a route that serves a folder to the frame without the login cookie. Versions are rebuilt from Write/Edit inputs (kept up to 256 KB by `server/lib/transcript-message.js`); no copy is stored, and Save to Artifacts uses the Hub's own `pinFile`/upload routes.
+27 -6
View File
@@ -762,13 +762,32 @@ export const TerminalView = memo(function TerminalView({
refit();
};
document.fonts?.addEventListener("loadingdone", onFontLoaded);
// The browser may drop or reuse the WebGL glyph atlas's GPU memory without
// a context-loss event (sleep/resume, a long-backgrounded tab, a display or
// zoom change on macOS): xterm keeps slicing the old coordinates and every
// cell shows a clipped or foreign glyph while the buffer stays correct.
// Rebuilding the atlas when the page comes back is cheap and redraws clean.
// @xterm/addon-webgl 0.19 shares ONE glyph atlas between every terminal
// with the same font, and when it fills up it merges four pages into one
// larger page and shifts the rest down. A GPU texture is re-uploaded only
// when its page's `version` differs from the uploaded one, and after a
// shift those counters can coincide, so a slot keeps a stale page of
// another size: every glyph is sampled squeezed or foreign while the
// buffer stays correct (fixed upstream only in 0.20 betas). Any option
// change makes each renderer re-acquire its atlas and re-upload all pages,
// so this toggles the family's trailing space (as onFontLoaded does) on
// a merge. `clearTextureAtlas` is no fix: it empties the SHARED atlas
// but redraws only this pane, leaving its siblings slicing reused space.
let atlasFrame = 0;
const rebuildAtlas = () => {
if (atlasFrame) return;
// Never inside the render that is rasterizing the merging glyph.
atlasFrame = requestAnimationFrame(() => {
atlasFrame = 0;
const family = term.options.fontFamily ?? "";
term.options.fontFamily = family.endsWith(" ") ? family.trimEnd() : `${family} `;
});
};
const atlasMerged = gpu?.onRemoveTextureAtlasCanvas(rebuildAtlas);
// The browser may also drop the textures without a context-loss event
// (sleep/resume, a long-backgrounded tab): rebuild when the page is back.
const onPageShown = () => {
if (document.visibilityState === "visible") term.clearTextureAtlas();
if (document.visibilityState === "visible") rebuildAtlas();
};
document.addEventListener("visibilitychange", onPageShown);
window.addEventListener("focus", onPageShown);
@@ -790,6 +809,8 @@ export const TerminalView = memo(function TerminalView({
searchRef.current = null;
resizeObserver.disconnect();
document.fonts?.removeEventListener("loadingdone", onFontLoaded);
if (atlasFrame) cancelAnimationFrame(atlasFrame);
atlasMerged?.dispose();
document.removeEventListener("visibilitychange", onPageShown);
window.removeEventListener("focus", onPageShown);
window.removeEventListener(FONT_SIZE_EVENT, onFontPref);
@@ -112,12 +112,15 @@ vi.mock("@xterm/addon-fit", () => ({
FitAddon: vi.fn().mockImplementation(() => ({ fit: vi.fn() })),
}));
// The newest WebGL addon, with the context-loss listener the view gave it.
const gpu: { last: { dispose: ReturnType<typeof vi.fn>; lose: () => void } | null } = {
const gpu: {
last: { dispose: ReturnType<typeof vi.fn>; lose: () => void; merge: () => void } | null;
} = {
last: null,
};
vi.mock("@xterm/addon-webgl", () => ({
WebglAddon: vi.fn().mockImplementation(() => {
let onLoss = () => {};
let onMerge = () => {};
const addon = {
__webgl: true,
dispose: vi.fn(),
@@ -125,8 +128,12 @@ vi.mock("@xterm/addon-webgl", () => ({
onLoss = fn;
return { dispose: vi.fn() };
},
onRemoveTextureAtlasCanvas: (fn: () => void) => {
onMerge = fn;
return { dispose: vi.fn() };
},
};
gpu.last = { dispose: addon.dispose, lose: () => onLoss() };
gpu.last = { dispose: addon.dispose, lose: () => onLoss(), merge: () => onMerge() };
return addon;
}),
}));
@@ -488,6 +495,22 @@ describe("TerminalView", () => {
expect(disposeMock).not.toHaveBeenCalled(); // the terminal itself lives on
});
it("re-acquires the glyph atlas on the next frame after a page merge", () => {
// addon-webgl 0.19 may keep a stale page in a GPU slot after it merges
// atlas pages; any option change makes it re-upload every page.
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation(() => 1);
render(<TerminalView runId="agenthub-lane-1" wsBaseUrl="ws://localhost:4820" />);
const opts = termOptions as { fontFamily?: string };
opts.fontFamily = "JetBrains Mono";
gpu.last!.merge();
gpu.last!.merge(); // coalesced into one frame
expect(raf).toHaveBeenCalledTimes(1);
expect(opts.fontFamily).toBe("JetBrains Mono"); // never inside the render that merged
(raf.mock.calls[0]![0] as FrameRequestCallback)(0);
expect(opts.fontFamily).toBe("JetBrains Mono ");
raf.mockRestore();
});
// xterm 6 dropped its own Alt+arrow → word-move mapping; the pane keeps it.
it("sends Alt+arrow as the word-move keys xterm 5 sent", () => {
expect(altArrowSeq("ArrowLeft", false)).toBe("\x1b[1;5D");
+15 -1
View File
@@ -2,7 +2,8 @@
* @file UserEditDialog.tsx
* @description The Users page's ONE account editor (admin only): profile
* (display name, email), access (role, active/disabled — neither for your own
* account), a new password (typed or generated, copyable — someone else's
* account — and, for an admin, whether they own the host's Linux account, so
* its sessions outside every workspace are billed to them), a new password (typed or generated, copyable — someone else's
* may be anything and makes them choose their own at next sign-in; your own
* must pass every rule of `lib/passwordRules.ts`), the workspaces the
* account owns (remove, add from every workspace), its spend quota (the
@@ -87,6 +88,7 @@ export function UserEditDialog({
const [email, setEmail] = useState(user.email ?? "");
const [role, setRole] = useState<Role>(user.role);
const [active, setActive] = useState(!user.disabled);
const [hostAccount, setHostAccount] = useState(Boolean(user.hostAccount));
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [owned, setOwned] = useState<OwnedWorkspace[] | null>(null);
@@ -139,6 +141,7 @@ export function UserEditDialog({
if (norm(email) !== (user.email ?? null)) patch.email = norm(email);
if (!self && role !== user.role) patch.role = role;
if (!self && active === user.disabled) patch.disabled = !active;
if (role === "admin" && hostAccount !== Boolean(user.hostAccount)) patch.hostAccount = hostAccount;
if (password) patch.password = password;
if (added.length) patch.addWorkspaces = added;
if (removed.size) patch.removeWorkspaces = [...removed];
@@ -364,6 +367,17 @@ export function UserEditDialog({
)}
</div>
</div>
{role === "admin" && (
<div className="mt-3">
<Checkbox
checked={hostAccount}
onChange={setHostAccount}
label={t("edit.hostAccount")}
labelClassName="text-sm text-fg-secondary"
/>
<p className="ml-6 mt-0.5 text-[11px] text-fg-muted">{t("edit.hostAccountHint")}</p>
</div>
)}
</Section>
<Section title={t("edit.password")}>
+2
View File
@@ -112,6 +112,8 @@
"status": "Status",
"active": "Active",
"statusHint": "A disabled user cannot sign in; their workspaces and history stay.",
"hostAccount": "Owns this server's host account",
"hostAccountHint": "Sessions run as the server's own Linux account outside every workspace (a script's claude -p, a CLI in a plain terminal) count toward this admin's spend. At most one admin; with none marked, the only admin.",
"selfRole": "You cannot change your own role.",
"selfDisable": "You cannot disable yourself.",
"password": "Password",
+2
View File
@@ -112,6 +112,8 @@
"status": "Trạng thái",
"active": "Đang hoạt động",
"statusHint": "Người dùng bị vô hiệu hoá không thể đăng nhập; workspace và lịch sử vẫn được giữ.",
"hostAccount": "Sở hữu tài khoản host của máy chủ",
"hostAccountHint": "Session chạy bằng tài khoản Linux của máy chủ nhưng ngoài mọi workspace (claude -p của script, CLI trong terminal thường) được tính vào chi phí của admin này. Tối đa một admin; nếu chưa ai được chọn thì là admin duy nhất.",
"selfRole": "Bạn không thể đổi vai trò của chính mình.",
"selfDisable": "Bạn không thể tự vô hiệu hoá mình.",
"password": "Mật khẩu",
+4
View File
@@ -800,6 +800,8 @@ export type UserPatch = {
addWorkspaces?: number[];
removeWorkspaces?: number[];
signOut?: true;
/** Owns the host's Linux account: its sessions outside every workspace bill to them (admins only). */
hostAccount?: boolean;
/** Their own spend quota (`default` = the default applies). */
quota?: UserQuotaSetting;
};
@@ -983,6 +985,8 @@ export type AuthUser = {
createdAt?: string;
/** An admin gave this password: the user must choose their own before anything else. */
mustChangePassword?: boolean;
/** Owns the host's Linux account (server/lib/session-account.js) — absent from an older server. */
hostAccount?: boolean;
};
export type AuthState = { mode: "local" } | { mode: "server"; user: AuthUser | null };
/** GET /api/me/prefs — the signed-in account's own UI preferences (localStorage keys). */
@@ -7316,7 +7316,7 @@ exports[`screen snapshots > Settings — about 1`] = `
<span
class="text-status-warning/90"
>
UI build v2.8.40 (rebuild client to match)
UI build v2.8.42 (rebuild client to match)
</span>
</p>
</div>
+11 -1
View File
@@ -732,7 +732,17 @@ An admin limits what each user may spend, in dollars, on the Users page
every account change; each one re-applies at once (`sweep`).
Spend is the users page's own figure: the tokens of the sessions the user
OWNS through a workspace, priced by `calculateCost`. The Users table shows
OWNS, priced by `calculateCost`. A session is owned through its workspace;
one no workspace owns — a script's `claude -p` in a temp folder, a CLI in a
plain terminal — is owned by the user of the Linux account it ran as
(`sessions.account`, `server/lib/session-account.js`: the hook's peer uid,
else the session's folder): a member's account bills to that member, the
host's to the admin ticked **Owns this server's host account** in Edit user
(`PATCH /api/users/:id` `{hostAccount: true}`, at most one), or with none
ticked to the only admin. The same rule feeds the status bar's **Today**.
A process that drops the pane's environment also drops
`AGENTHUB_QUOTA_FILE`, so its prompts are not refused by the hook — but its
spend still counts, and stops the user's next session. The Users table shows
each user's spend against their quota; the user sees their own as **Quota N%**
in the status bar (`GET /api/me/quota`).
+7 -1
View File
@@ -3,7 +3,7 @@
openapi: 3.0.3
info:
title: Agent Dashboard for Claude Code API
version: 2.8.30
version: 2.8.40
description: HTTP API for real-time Claude Code session monitoring, agent lifecycle tracking, analytics, pricing, hooks ingestion, and workflow intelligence.
contact:
name: Nguyễn Ngọc Trí Vĩ
@@ -15410,6 +15410,9 @@ paths:
type: boolean
enum:
- true
hostAccount:
type: boolean
description: 'An admin owns the host''s Linux account: its sessions outside every workspace are billed to them (at most one; EBADROLE for a non-admin)'
quota:
$ref: '#/components/schemas/UserQuotaSetting'
currentPassword:
@@ -19932,6 +19935,9 @@ paths:
items:
type: string
description: Files the switch wrote.
following:
type: boolean
description: 'Codex: a running app-server daemon was restarted, so open and new sessions use the new login.'
'400':
description: '`EBADNAME` / `EBADLABEL`.'
content:
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "agenthub",
"version": "2.8.40",
"version": "2.8.42",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "agenthub",
"version": "2.8.40",
"version": "2.8.42",
"hasInstallScript": true,
"license": "UNLICENSED",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "agenthub",
"version": "2.8.40",
"version": "2.8.42",
"bin": {
"agenthub": "bin/agenthub.js"
},
+110
View File
@@ -0,0 +1,110 @@
/**
* @file session-account.test.js
* @description A session no workspace owns is billed to the user of the Linux
* account it ran as (server/lib/session-account.js): a member's account to
* that member, the host's to the admin marked as its owner (or the only
* admin). A workspace's ownership always wins, a pushed session never gets an
* account, and the hook peer is stamped once.
* @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(), "session-account-test-"));
process.env.DASHBOARD_DB_PATH = path.join(TMP, "dashboard.db");
const { db } = require("../db");
const sa = require("../lib/session-account");
const scope = require("../lib/scope");
const { OWNED_SESSIONS } = require("../routes/users");
const own = (id) => {
const w = scope.ownSessionWhere({ user: { id } });
return db
.prepare(`SELECT id FROM sessions WHERE ${w.where} ORDER BY id`)
.all(...w.params)
.map((r) => r.id);
};
before(() => {
const user = db.prepare(
"INSERT INTO users (id, username, role, password_hash) VALUES (?, ?, ?, 'x')"
);
user.run(1, "boss", "admin");
user.run(2, "dev", "developer");
db.prepare("INSERT INTO lanes (id, cwd, tool, owner_id) VALUES (1, '/w/dev', 'claude', 2)").run();
const s = db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id, account, source) VALUES (?, ?, 'active', '/w', ?, ?, ?)"
);
s.run("host-free", "eval", null, "", "local");
s.run("dev-free", "eval", null, "dev", "local");
s.run("host-in-dev-lane", "lane", 1, "", "local");
s.run("unknown", "old", null, null, "local");
s.run("gone-member", "x", null, "ghost", "local");
});
after(() => fs.rmSync(TMP, { recursive: true, force: true }));
describe("session-account", () => {
it("bills a member's account to that member and the host's to the only admin", () => {
assert.equal(sa.hostOwner(), 1);
assert.deepEqual(own(1), ["host-free"]);
assert.deepEqual(own(2), ["dev-free", "host-in-dev-lane"]);
});
it("lets the workspace's owner win over the account", () => {
assert.ok(!own(1).includes("host-in-dev-lane"));
});
it("bills nobody for the host when two admins and none is marked, then the marked one", () => {
db.prepare(
"INSERT INTO users (id, username, role, password_hash) VALUES (3, 'boss2', 'admin', 'x')"
).run();
assert.equal(sa.hostOwner(), null);
assert.deepEqual(own(1), []);
sa.setHostOwner(3);
assert.equal(sa.hostOwner(), 3);
assert.deepEqual(own(3), ["host-free"]);
sa.setHostOwner(1);
assert.deepEqual(own(3), []);
assert.deepEqual(own(1), ["host-free"]);
});
it("lists account-billed sessions in OWNED_SESSIONS (Users page, spend quota)", () => {
const rows = db.prepare(OWNED_SESSIONS).all();
const by = Object.fromEntries(rows.map((r) => [r.session_id, r.uid]));
assert.equal(by["host-free"], 1);
assert.equal(by["dev-free"], 2);
assert.equal(by["host-in-dev-lane"], 2);
assert.equal(by.unknown, undefined);
assert.equal(by["gone-member"], undefined);
});
it("stamps the hook peer once and never a pushed session", () => {
db.prepare("INSERT INTO sessions (id, name, status, cwd) VALUES ('fresh', 'f', 'active', '/w')").run();
db.prepare("INSERT INTO sessions (id, name, status, cwd) VALUES ('pushed', 'p', 'active', '/w')").run();
sa.stampFromPeer("fresh", { kind: "member", name: "dev", home: "/srv/u/dev" });
sa.stampFromPeer("fresh", { kind: "host" });
sa.stampFromPeer("pushed", { kind: "host" }, "push:laptop");
sa.stampFromPeer("pushed", { kind: "refused" });
const acct = (id) => db.prepare("SELECT account FROM sessions WHERE id = ?").get(id).account;
assert.equal(acct("fresh"), "dev");
assert.equal(acct("pushed"), null);
});
it("gives a folder's account to sessions no hook stamped, skipping pushed ones", () => {
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, source) VALUES ('remote', 'r', 'active', '/w', 'push:laptop')"
).run();
sa.stampFromFolders();
const acct = (id) => db.prepare("SELECT account FROM sessions WHERE id = ?").get(id).account;
// Outside S3 every folder is the host's.
assert.equal(acct("unknown"), "");
assert.equal(acct("pushed"), "");
assert.equal(acct("remote"), null);
});
});
+13
View File
@@ -1445,6 +1445,16 @@ try {
db.prepare("ALTER TABLE sessions ADD COLUMN pinned_at TEXT").run();
}
// Migrate: add `account` to sessions — the Linux account a session ran as
// (server/lib/session-account.js): "" = the host's, else the S3 member's name;
// NULL = not known yet. A session no workspace owns is billed to the user of
// that account (server/lib/scope.js), so a script's `claude -p` still counts.
try {
db.prepare("SELECT account FROM sessions LIMIT 1").get();
} catch {
db.prepare("ALTER TABLE sessions ADD COLUMN account TEXT").run();
}
// How far each Codex rollout journal has been read (server/lib/codex-usage.js).
// In the DB, not a side file, so a session the user deleted stays deleted
// until Codex writes to its journal again, while a wiped DB re-imports all.
@@ -1952,6 +1962,9 @@ for (const col of ["display_name", "email", "avatar_at", "avatar_link"]) {
for (const [col, type] of [
["last_login_at", "TEXT"],
["must_change_password", "INTEGER NOT NULL DEFAULT 0"],
// The admin who owns the HOST's Linux account: its sessions outside every
// workspace are billed to them (server/lib/session-account.js). At most one.
["host_account", "INTEGER NOT NULL DEFAULT 0"],
]) {
try {
db.prepare(`SELECT ${col} FROM users LIMIT 1`).get();
+4 -1
View File
@@ -873,7 +873,9 @@ function startBackgroundServices() {
if (poolTimer.unref) poolTimer.unref();
}
// Server mode's spend quotas (user-quota.js): who is over theirs now, the
// flag files their hooks read, the panes no hook can stop. Off with
// flag files their hooks read, the panes no hook can stop — after giving
// the sessions no hook made their Linux account (session-account.js), so a
// poller's session is billed to someone too. Off with
// DASHBOARD_QUOTA_SWEEP_MS=0; a no-op in local mode.
const QUOTA_SWEEP_MS = Number(process.env.DASHBOARD_QUOTA_SWEEP_MS ?? 60_000);
if (
@@ -883,6 +885,7 @@ function startBackgroundServices() {
) {
const quotaSweep = () => {
try {
require("./lib/session-account").stampFromFolders();
require("./lib/user-quota").sweep();
} catch (err) {
console.warn("user quota sweep failed:", err.message);
+7 -1
View File
@@ -213,6 +213,9 @@ const publicUser = (u) =>
createdAt: u.created_at ?? null,
// An admin gave this password: the account must pick its own first.
mustChangePassword: Boolean(u.must_change_password),
// Owns the host's Linux account: its sessions outside every workspace
// are billed to this admin (server/lib/session-account.js).
hostAccount: Boolean(u.host_account),
};
const MAX_DISPLAY_NAME = 100;
@@ -415,7 +418,10 @@ function setRole(username, role) {
if (!ROLES.includes(role)) throw err("EBADROLE", `role: one of ${ROLES.join(", ")}`);
const u = requireUser(username);
if (role !== "admin") assertKeepsAdmin(u, "demoted");
sql("UPDATE users SET role = ? WHERE id = ?").run(role, u.id);
// Only an admin owns the host account (session-account.js): a demotion drops the mark.
sql(
"UPDATE users SET role = ?, host_account = CASE WHEN ? = 'admin' THEN host_account ELSE 0 END WHERE id = ?"
).run(role, role, u.id);
if (role !== "admin") stopHostPanes(u.id);
}
+12 -6
View File
@@ -5,7 +5,9 @@
*
* A workspace (`lanes.owner_id`) belongs to the user who created it. A session
* belongs to its workspace: `sessions.lane_id`, or a `dashboard_runs` row of
* that workspace holding it (a session not stamped yet). Agents, events and
* that workspace holding it (a session not stamped yet). A session no workspace owns
* belongs to the user of the Linux account it ran as (`sessions.account`,
* server/lib/session-account.js) — a script's `claude -p` is its runner's. Agents, events and
* token rows belong to their session. A developer sees and changes only what
* their own workspaces own; an analyst SEES everything but changes only their
* own (every non-GET request is scoped like a developer's); an admin sees and
@@ -17,6 +19,7 @@
*/
const sql = (q) => require("../db").db.prepare(q);
const { ACCOUNT_OWNED } = require("./session-account");
/** The user whose rows this request is limited to, or null for "all". */
function memberId(req) {
@@ -53,8 +56,9 @@ function ownedSessionWhere(uid, col, laneCol) {
return {
where: `(${laneCol} IN (SELECT id FROM lanes WHERE owner_id = ?)
OR ${col} IN (SELECT r.session_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
WHERE l.owner_id = ? AND r.session_id IS NOT NULL))`,
params: [uid, uid],
WHERE l.owner_id = ? AND r.session_id IS NOT NULL)
OR ${col} IN (SELECT session_id FROM (${ACCOUNT_OWNED}) WHERE uid = ?))`,
params: [uid, uid, uid],
};
}
@@ -264,14 +268,16 @@ function ownerStillFits(laneId) {
const STAFF = { staffOnly: true };
/** Owner ids of the workspaces that own a session (stamped or held by a run). */
/** Owner ids of a session: its workspace's (stamped or held by a run), else its account's user. */
function sessionOwners(sessionId) {
if (!sessionId) return new Set();
const rows = sql(
`SELECT l.owner_id FROM sessions s JOIN lanes l ON l.id = s.lane_id WHERE s.id = ?
UNION
SELECT l.owner_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id WHERE r.session_id = ?`
).all(String(sessionId), String(sessionId));
SELECT l.owner_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id WHERE r.session_id = ?
UNION
SELECT uid FROM (${ACCOUNT_OWNED}) WHERE session_id = ?`
).all(String(sessionId), String(sessionId), String(sessionId));
return new Set(rows.map((r) => r.owner_id).filter((x) => x != null));
}
+113
View File
@@ -0,0 +1,113 @@
/**
* @file session-account.js
* @description Which Linux account a session ran as (`sessions.account`: ""
* = the host's, else an S3 member's name), and whose bill a session no
* workspace owns goes on. A workspace owns a session through `lane_id` or a
* `dashboard_runs` row (server/lib/scope.js); a session started OUTSIDE every
* workspace — a script's `claude -p`, a CLI typed in a plain terminal — has
* neither, and without this its spend counted for nobody: not in anyone's
* Today, the Users page or a spend quota.
*
* The account is the hook's PEER (server/lib/hook-auth.js: the uid of the
* loopback connection, never the body) when a hook creates the session; a
* session no hook made (the Codex/Antigravity/Cursor/omp pollers, history)
* gets it from its folder, the S3 rule `accountForPath` already applies to
* every pane. A pushed session (another machine's) never gets one. A member
* account bills to the user of that name; the host account to the admin an
* admin marked as its owner (`users.host_account`), or — with no mark — the
* only enabled admin, if there is exactly one.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const sql = (q) => require("../db").db.prepare(q);
// The user the host account's sessions bill to (null: nobody marked and not exactly one admin).
const HOST_OWNER = `COALESCE(
(SELECT MIN(id) FROM users WHERE host_account = 1 AND role = 'admin'),
(SELECT MIN(id) FROM users WHERE role = 'admin' AND disabled = 0 HAVING COUNT(*) = 1))`;
// A session no workspace owns: neither stamped onto an owned lane nor held by
// a run of one — exactly the complement of scope.js's ownership.
const UNOWNED = `(s.lane_id IS NULL OR s.lane_id NOT IN (SELECT id FROM lanes WHERE owner_id IS NOT NULL))
AND s.id NOT IN (SELECT r.session_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
WHERE r.session_id IS NOT NULL AND l.owner_id IS NOT NULL)`;
/** `session_id` → `uid` for every session billed by its account (no workspace owns it). */
const ACCOUNT_OWNED = `
SELECT s.id AS session_id, u.id AS uid
FROM sessions s JOIN users u
ON u.id = CASE WHEN s.account = '' THEN ${HOST_OWNER}
ELSE (SELECT id FROM users WHERE username = s.account) END
WHERE s.account IS NOT NULL AND ${UNOWNED}`;
/** The account a hook's peer names: "" for the host, a member's name, null otherwise. */
function accountOfPeer(peer) {
if (!peer || peer.kind === "host") return "";
if (peer.kind === "member" && peer.name) return peer.name;
return null;
}
/** Record a hook-created session's account — first writer wins, a pushed hook never writes. */
function stampFromPeer(sessionId, peer, pushSource = null) {
if (pushSource || !sessionId) return;
const account = accountOfPeer(peer);
if (account == null) return;
sql("UPDATE sessions SET account = ? WHERE id = ? AND account IS NULL").run(account, sessionId);
}
/** The account a folder runs as: "" outside the users root, a member's name inside it. */
function accountOfPath(cwd) {
const linux = require("./linux-accounts");
const conf = linux.s3Enabled() ? linux.serverConf() : null;
const root = conf?.usersRoot;
const path = require("path");
if (!root || typeof cwd !== "string" || !path.isAbsolute(cwd)) return "";
const rel = path.relative(root, path.resolve(cwd));
if (rel.startsWith("..") || path.isAbsolute(rel)) return "";
// The users root itself is nobody's.
return rel.split(path.sep)[0] || null;
}
/**
* Give every local session still without an account the one its folder runs
* as (sessions the pollers made, and history from before the column). Cheap
* once caught up: only `account IS NULL` rows are read.
*/
function stampFromFolders() {
const rows = sql(
"SELECT id, cwd FROM sessions WHERE account IS NULL AND source NOT LIKE 'push:%' LIMIT 5000"
).all();
if (!rows.length) return 0;
const set = sql("UPDATE sessions SET account = ? WHERE id = ? AND account IS NULL");
let n = 0;
require("../db").db.transaction(() => {
for (const r of rows) {
const account = accountOfPath(r.cwd);
if (account != null) n += set.run(account, r.id).changes;
}
})();
return n;
}
/** Mark `userId` (an admin) as the host account's owner, or clear the mark with null. */
function setHostOwner(userId) {
require("../db").db.transaction(() => {
sql("UPDATE users SET host_account = 0 WHERE host_account = 1").run();
if (userId != null) sql("UPDATE users SET host_account = 1 WHERE id = ?").run(userId);
})();
}
/** The user id the host account bills to right now, or null. */
function hostOwner() {
return sql(`SELECT ${HOST_OWNER} AS id`).get()?.id ?? null;
}
module.exports = {
ACCOUNT_OWNED,
accountOfPeer,
stampFromPeer,
accountOfPath,
stampFromFolders,
setHostOwner,
hostOwner,
};
+5
View File
@@ -790,6 +790,11 @@ const paths = {
addWorkspaces: { type: "array", items: { type: "integer" } },
removeWorkspaces: { type: "array", items: { type: "integer" } },
signOut: { type: "boolean", enum: [true] },
hostAccount: {
type: "boolean",
description:
"An admin owns the host's Linux account: its sessions outside every workspace are billed to them (at most one; EBADROLE for a non-admin)",
},
quota: { $ref: "#/components/schemas/UserQuotaSetting" },
}),
responses: {
+2
View File
@@ -1643,6 +1643,8 @@ function ingestHook(body, pushSource = null, peer = { kind: "host" }) {
} else {
touchLaneFromHook(hook_type, data, tool, body.run_id, peer);
bindRunSession(body.run_id, data.session_id, hook_type, data.source, tool);
// The Linux account it ran as: whose bill it is when no workspace owns it.
require("../lib/session-account").stampFromPeer(data.session_id, peer);
}
}
} finally {
+22 -3
View File
@@ -54,8 +54,9 @@ const { listAudit, recordAccountChange } = require("../lib/audit");
const router = Router();
// Which account each session belongs to — through its workspace, or a
// dashboard run on one (server/lib/scope.js's sessionWhere, for every user at once).
// Which account each session belongs to — through its workspace, a dashboard
// run on one, or (no workspace owns it) the Linux account it ran as
// (server/lib/scope.js's sessionWhere, for every user at once).
const OWNED_SESSIONS = `
SELECT s.id AS session_id, l.owner_id AS uid
FROM sessions s JOIN lanes l ON l.id = s.lane_id
@@ -63,7 +64,9 @@ const OWNED_SESSIONS = `
UNION
SELECT s.id, l.owner_id
FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id JOIN sessions s ON s.id = r.session_id
WHERE l.owner_id IS NOT NULL`;
WHERE l.owner_id IS NOT NULL
UNION
${require("../lib/session-account").ACCOUNT_OWNED}`;
/**
* Map(user id → {cost, tokens}) per window, each window a UTC hour
@@ -580,6 +583,18 @@ router.patch(
if (self && body.disabled) throw ESELF("you cannot disable yourself");
}
const disabledChange = body.disabled !== undefined && body.disabled !== Boolean(u.disabled);
if (body.hostAccount !== undefined) {
if (typeof body.hostAccount !== "boolean") {
throw Object.assign(new Error("hostAccount: true or false"), { code: "EBADFIELD" });
}
if (body.hostAccount && (body.role ?? u.role) !== "admin") {
throw Object.assign(new Error("only an admin can own the host account"), {
code: "EBADROLE",
});
}
}
const hostChange =
body.hostAccount !== undefined && body.hostAccount !== Boolean(u.host_account);
if (body.password !== undefined) {
// Your own password: every rule. Someone else's: a starting one they replace.
if (self) {
@@ -619,6 +634,10 @@ router.patch(
auth.setRole(u.username, body.role);
done.push(`role ${body.role}`);
}
if (hostChange) {
require("../lib/session-account").setHostOwner(body.hostAccount ? u.id : null);
done.push(body.hostAccount ? "owns the host account" : "no longer owns the host account");
}
for (const id of add) auth.assignWorkspace(id, u.username);
for (const id of remove) auth.unassignWorkspace(id, u.username);
if (add.length) done.push(`workspace ${add.join(", ")}`);