Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(server,web,ui): 用户管理表加最近登录时间与累计开销两列

lmlihengd3b1f6c9ab80
diff --git a/changelog/unreleased/2026-10-08-user-backend-last-login-and-cost.md b/changelog/unreleased/2026-10-08-user-backend-last-login-and-cost.md
new file mode 100644
index 00000000..d1f8737d
--- /dev/null
+++ b/changelog/unreleased/2026-10-08-user-backend-last-login-and-cost.md
@@ -0,0 +1,46 @@
+# Admin user backend: every account's last sign-in and lifetime cost
+
+- **Date:** 2026-10-08
+- **Type:** feature
+- **Scope:** `server`, `web`
+
+[中文版](2026-10-08-user-backend-last-login-and-cost.zh.md)
+
+The user backend's table showed who exists, what role they hold and when the account was created —
+nothing about whether it is used, or what it has cost. It now carries two read-only columns, both
+figures the server computes:
+
+- **Last sign-in** (`UserInfo.lastLoginAt`, the `users.last_login_at` column): stamped by the one
+ path that verifies a password (`AuthService.login`), so an account an admin created and nobody
+ ever signed into reads as never used rather than as today. The column is added to an existing
+ database by `openDatabase`'s column guard; rows written before it read back as never signed in.
+- **Lifetime cost** (`UserInfo.totalCostUsd`): the total of the Projects the account OWNS, every
+ usage record ever written in them priced at the current rates — the cost center's cumulative
+ figure, summed over the account's Projects. Pricing is per Project, so the sum is taken per
+ Project (`UsageQueries.lifetimeCost`, the unfiltered grouped scan `modelTotals` already ran).
+ A Model with no price makes the figure a lower bound, which the response says (`costUnpriced`)
+ and the table draws as a leading `≥`; with nothing priced at all the field is omitted and the
+ cell shows `—`, rather than a zero the reader cannot tell from "ran for free".
+
+The users page is the only page whose content is a wide table, so it asks `PagedDialog` for a
+wider panel (`PagedDialog.widthClass`, defaulting to the shared width); six columns and two row
+actions otherwise pushed 重置密码 / 删除 off the pane, reachable only by scrolling sideways.
+
+## Server
+
+- `db/schema.ts` / `db/database.ts`: the `users.last_login_at` column and its `ensureColumn` guard.
+- `db/repos/users.ts` / `mechanisms/identity.ts`: `touchLastLogin`, and the column on `UserRow`.
+- `auth/service.ts`: stamps the column on a successful password login and returns it in that
+ login's own DTO.
+- `services/usage-service.ts` / `mechanisms/observability.ts`: `lifetimeCost(projectId)` — one
+ unfiltered grouped scan, folded with the same per-reference rate lookup `query` uses.
+- `services/admin-service.ts`: `listUsers` is now async; it sums each account's owned Projects.
+- `http/routes/admin.ts`: awaits the list.
+
+## Web
+
+- `features/admin/admin-users-page.tsx`: the two columns (currency follows the display preference).
+- `features/settings/settings-dialog.tsx`: the users page's panel width.
+- `lib/strings.ts` / `lib/strings-en.ts`: the column headers, the never-signed-in word and the cost
+ column's tooltip.
+- `packages/ui` `overlays/paged-dialog`: the optional `widthClass`.
diff --git a/changelog/unreleased/2026-10-08-user-backend-last-login-and-cost.zh.md b/changelog/unreleased/2026-10-08-user-backend-last-login-and-cost.zh.md
new file mode 100644
index 00000000..a777cdc2
--- /dev/null
+++ b/changelog/unreleased/2026-10-08-user-backend-last-login-and-cost.zh.md
@@ -0,0 +1,40 @@
+# 用户管理:每个账号的最近登录时间与累计开销
+
+- **Date:** 2026-10-08
+- **Type:** feature
+- **Scope:** `server`, `web`
+
+[English](2026-10-08-user-backend-last-login-and-cost.md)
+
+用户管理表原先只写谁存在、什么角色、账号何时创建 —— 看不出这个账号有没有人在用、花掉了多少。
+现在表上多了两列,都是服务端算出来给人看的只读值:
+
+- **最近登录**(`UserInfo.lastLoginAt`,即 `users.last_login_at` 列):由**校验密码的那一条路径**
+ (`AuthService.login`)写入,所以管理员建好但没人登过的账号显示「从未登录」,而不是显示成今天。
+ 已存在的数据库由 `openDatabase` 的加列保护补上这一列,早于它写入的行读出来就是「从未登录」。
+- **累计开销**(`UserInfo.totalCostUsd`):该账号**名下**项目的全部历史用量,按当前价格折算 ——
+ 就是成本中心那张「累计」卡片,只不过按账号名下的项目汇总。价格是按项目配置的,所以汇总也是
+ 逐个项目的(`UsageQueries.lifetimeCost`,与 `modelTotals` 同一句不带筛选的分组查询)。
+ 其中如有模型没有价格,这个数就只是下限:接口用 `costUnpriced` 说明,表上以 `≥` 前缀显示;
+ 一点都算不出价格时整个字段省略,单元格画 `—`,而不是给一个读者分不清「免费」还是「没数据」的 0。
+
+用户管理页是设置里唯一以宽表格为内容的页,因此它向 `PagedDialog` 要了更宽的版面
+(`PagedDialog.widthClass`,默认仍是共用宽度):六列加两个行内操作,否则会把「重置密码 / 删除」
+挤出面板,只能横向滚动才够得着。
+
+## 服务端
+
+- `db/schema.ts` / `db/database.ts`:`users.last_login_at` 列与它的 `ensureColumn` 保护。
+- `db/repos/users.ts` / `mechanisms/identity.ts`:`touchLastLogin`,以及 `UserRow` 上的这一列。
+- `auth/service.ts`:密码登录成功时写入,并在本次登录返回的用户对象里带上它。
+- `services/usage-service.ts` / `mechanisms/observability.ts`:`lifetimeCost(projectId)` —— 一次
+ 不带筛选的分组扫描,用与 `query` 相同的「按 provider/model 查价」折叠。
+- `services/admin-service.ts`:`listUsers` 改为异步,逐个汇总账号名下项目的开销。
+- `http/routes/admin.ts`:等这个列表。
+
+## 网页端
+
+- `features/admin/admin-users-page.tsx`:两列(金额跟随界面里的货币偏好)。
+- `features/settings/settings-dialog.tsx`:用户管理页的面板宽度。
+- `lib/strings.ts` / `lib/strings-en.ts`:列名、「从未登录」以及开销列的 tooltip。
+- `packages/ui` 的 `overlays/paged-dialog`:可选的 `widthClass`。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 1b733dd9..3b394306 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -68,6 +68,25 @@ export interface UserInfo {
* and a surface with no value draws the letter placeholder instead.
*/
avatar?: string;
+ /**
+ * Most recent successful sign-in (ISO); omitted while the account has never signed in —
+ * created by an admin, not yet used. The admin user backend shows it as a column.
+ */
+ lastLoginAt?: string;
+ /**
+ * Admin user backend only (`GET /api/admin/users`): lifetime cost in USD of the Projects this
+ * account OWNS, priced at the current rates — every account's own usage included, whoever
+ * caused it, since cost is attributed by the Project it ran in. Omitted when none of that
+ * usage could be priced (nothing ran there, or every model it ran on has no price); a real
+ * figure, `0` included, is always sent. Not money that was charged: it is the same estimate
+ * the cost center draws, read off the recorded usage.
+ */
+ totalCostUsd?: number;
+ /**
+ * Admin user backend, alongside `totalCostUsd`: some of that usage ran on a model this
+ * deployment has no price for, so the figure is a lower bound. Omitted when it is exact.
+ */
+ costUnpriced?: boolean;
createdAt: string;
}
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 0379d916..8096bba1 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -57,7 +57,7 @@ export function generateInitialAdminPassword(): string {
*/
export type SessionVia = "password" | "desktop" | "setup" | "token";
-/** Row -> DTO. The two profile columns are omitted rather than sent as null when unset. */
+/** Row -> DTO. The three optional profile/sign-in columns are omitted rather than sent as null when unset. */
export function toUserInfo(row: UserRow): UserInfo {
return {
userId: row.userId,
@@ -65,6 +65,7 @@ export function toUserInfo(row: UserRow): UserInfo {
passwordIsInitial: row.passwordIsInitial,
...(row.displayName !== null ? { displayName: row.displayName } : {}),
...(row.avatar !== null ? { avatar: row.avatar } : {}),
+ ...(row.lastLoginAt !== null ? { lastLoginAt: row.lastLoginAt } : {}),
createdAt: row.createdAt,
};
}
@@ -148,6 +149,7 @@ export class AuthService implements Auth {
passwordIsInitial: true,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt: this.clock.now().toISOString(),
};
this.users.insert(user);
@@ -230,7 +232,14 @@ export class AuthService implements Auth {
}
this.loginFailures.delete(userId);
this.authSessions.deleteExpired(this.clock.now().toISOString());
- return { user: toUserInfo(row), token: this.issueSession(row.userId, "password") };
+ // The account's last sign-in, stamped on the one path that verified a password. Written
+ // before the DTO is built, so the response's own user carries the value this call set.
+ const at = this.clock.now().toISOString();
+ this.users.touchLastLogin(row.userId, at);
+ return {
+ user: toUserInfo({ ...row, lastLoginAt: at }),
+ token: this.issueSession(row.userId, "password"),
+ };
}
/**
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 14338f82..89fee84b 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -69,6 +69,7 @@ export function openDatabase(dbPath: string): DatabaseSync {
// A v0.2.0 web.db has auth_sessions without `via`; CREATE TABLE IF NOT EXISTS never adds a
// column, so every INSERT would fail "no column named via" until this runs.
ensureColumn(db, "auth_sessions", "via", "TEXT");
+ ensureColumn(db, "users", "last_login_at", "TEXT");
ensureColumn(db, "trace_files", "page_stats", "TEXT");
ensureColumn(db, "messaging_bindings", "line_per_message", "INTEGER NOT NULL DEFAULT 0");
ensureColumn(db, "messaging_bindings", "final_reply_only", "INTEGER NOT NULL DEFAULT 0");
diff --git a/packages/server/src/db/repos/users.ts b/packages/server/src/db/repos/users.ts
index f5505147..4866807f 100644
--- a/packages/server/src/db/repos/users.ts
+++ b/packages/server/src/db/repos/users.ts
@@ -16,6 +16,8 @@ export interface UserRow {
displayName: string | null;
/** Avatar as a data URL; null = never set. */
avatar: string | null;
+ /** Most recent successful sign-in (ISO); null = never signed in — an account that exists but has not been used yet. */
+ lastLoginAt: string | null;
createdAt: string;
}
@@ -27,6 +29,7 @@ function mapRow(r: Record<string, unknown>): UserRow {
passwordIsInitial: (r.password_is_initial as number) === 1,
displayName: (r.display_name as string | null) ?? null,
avatar: (r.avatar as string | null) ?? null,
+ lastLoginAt: (r.last_login_at as string | null) ?? null,
createdAt: r.created_at as string,
};
}
@@ -38,8 +41,8 @@ export class UsersRepo implements Users {
insert(row: UserRow): void {
this.db
.prepare(
- "INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, display_name, avatar, created_at)" +
- " VALUES (?, ?, ?, ?, ?, ?, ?)",
+ "INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, display_name, avatar, last_login_at, created_at)" +
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
)
.run(
row.userId,
@@ -48,6 +51,7 @@ export class UsersRepo implements Users {
row.passwordIsInitial ? 1 : 0,
row.displayName,
row.avatar,
+ row.lastLoginAt,
row.createdAt,
);
}
@@ -75,6 +79,14 @@ export class UsersRepo implements Users {
.run(passwordHash, isInitial ? 1 : 0, userId);
}
+ /**
+ * Stamp the account's most recent sign-in, overwriting whatever was there: the column is a
+ * "when did they last get in" fact, not a history (the admin user backend shows the one value).
+ */
+ touchLastLogin(userId: string, at: string): void {
+ this.db.prepare("UPDATE users SET last_login_at = ? WHERE user_id = ?").run(at, userId);
+ }
+
/**
* Writes the profile fields the patch names, leaving the rest as they are: an absent key
* keeps the stored value, `null` clears it, a string replaces it. A patch naming neither
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 7566eba7..1cc2d24a 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -40,6 +40,7 @@ CREATE TABLE IF NOT EXISTS users (
password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it
display_name TEXT, -- nickname shown in place of user_id (1-32 characters); NULL = never set, surfaces show the id
avatar TEXT, -- avatar as a data URL (image/png|jpeg|webp, <= 131072 characters); NULL = never set, surfaces draw the letter placeholder
+ last_login_at TEXT, -- LAST successful sign-in (ISO); NULL = never signed in (an account created but not yet used). Stamped by AuthService, read by the admin user backend
created_at TEXT NOT NULL
);
-- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random
diff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.ts
index b74eb100..c781ff8e 100644
--- a/packages/server/src/http/routes/admin.ts
+++ b/packages/server/src/http/routes/admin.ts
@@ -35,8 +35,8 @@ export function adminUsersRoutes(deps: AdminRouteDeps): Hono<AppEnv> {
await next();
});
- app.get("/", (c) => {
- return c.json({ users: deps.adminService.listUsers() } satisfies AdminUsersResponse);
+ app.get("/", async (c) => {
+ return c.json({ users: await deps.adminService.listUsers() } satisfies AdminUsersResponse);
});
app.post("/", async (c) => {
diff --git a/packages/server/src/mechanisms/identity.ts b/packages/server/src/mechanisms/identity.ts
index 971ed29c..8ca24f00 100644
--- a/packages/server/src/mechanisms/identity.ts
+++ b/packages/server/src/mechanisms/identity.ts
@@ -15,6 +15,8 @@ export abstract class Users {
abstract list(): UserRow[];
abstract count(): number;
abstract updatePassword(userId: string, passwordHash: string, isInitial: boolean): void;
+ /** Stamp the account's most recent successful sign-in (the admin user backend's "last login" column). */
+ abstract touchLastLogin(userId: string, at: string): void;
abstract updateProfile(
userId: string,
patch: { displayName?: string | null; avatar?: string | null },
@@ -67,7 +69,8 @@ export abstract class Auth {
/** Admin: the mechanism AdminService implements. */
@Interface()
export abstract class Admin {
- abstract listUsers(): UserInfo[];
+ /** Every account, with last sign-in and owned-Project cost (see AdminService.listUsers). */
+ abstract listUsers(): Promise<UserInfo[]>;
abstract createUser(userId: string, password: string): Promise<UserInfo>;
abstract resetPassword(userId: string, password: string): Promise<void>;
abstract deleteUser(userId: string): Promise<void>;
diff --git a/packages/server/src/mechanisms/observability.ts b/packages/server/src/mechanisms/observability.ts
index 2da9edcb..9f84ddcc 100644
--- a/packages/server/src/mechanisms/observability.ts
+++ b/packages/server/src/mechanisms/observability.ts
@@ -130,6 +130,14 @@ export abstract class UsageQueries {
abstract queryErrors(projectId: string, q: UsageErrorsQuery): UsageErrorsPage;
abstract clearErrors(projectId: string, q: UsageErrorsClearQuery): number;
abstract modelTotals(projectId: string): UsageModelTotals;
+ /**
+ * The Project's lifetime cost: every usage record it ever wrote, folded with the same
+ * per-reference rate lookup `query` uses (current prices). `unpriced` says some of that usage
+ * ran on a model this Project has no price for, so `cost` is a lower bound.
+ */
+ abstract lifetimeCost(
+ projectId: string,
+ ): Promise<Opaque<"LifetimeCost", { cost: number | null; unpriced: boolean }>>;
abstract costBySession(
projectId: string,
sessionIds: readonly string[],
diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.ts
index 41d793ae..61bd18fd 100644
--- a/packages/server/src/services/admin-service.ts
+++ b/packages/server/src/services/admin-service.ts
@@ -23,6 +23,7 @@ import { Component, Use } from "@lmliheng/penguin-core/kernel";
import type { Clock } from "../hmr/capabilities.js";
import type { LiveStreams } from "../auth/live-streams.js";
import type { Admin, AuthSessions, Users } from "../mechanisms/identity.js";
+import type { UsageQueries } from "../mechanisms/observability.js";
import type { ProjectLifecycle, Projects } from "../mechanisms/projects.js";
@Component()
@@ -31,20 +32,47 @@ export class AdminService implements Admin {
@Use() private readonly authSessions!: AuthSessions;
@Use() private readonly liveStreams!: LiveStreams;
@Use() private readonly projects!: Projects;
+ @Use() private readonly usage!: UsageQueries;
@Use() private readonly projectService!: ProjectLifecycle;
@Use() private readonly clock!: Clock;
@Use() private readonly hasher!: PasswordHasher;
/**
- * Every account, for the admin user backend. The avatar is dropped on the way out: a stored
+ * Every account, for the admin user backend, each with the last sign-in its row carries and
+ * the lifetime cost of the Projects it owns. The avatar is dropped on the way out: a stored
* avatar is a data URL of up to 128 KiB and this list is unpaged, so carrying one per account
* would answer a table that only shows the nickname with megabytes.
+ *
+ * The cost is summed per Project because pricing is per Project (each one carries its own
+ * configured rates), and it is read at the CURRENT rates for every record ever written — the
+ * one figure the cost center's "cumulative" card shows, extended over everything the account
+ * owns. `costUnpriced` travels with it: a Model this deployment has no price for makes the sum
+ * a lower bound, and a table that presented it as exact would overstate its own accuracy.
*/
- listUsers(): UserInfo[] {
- return this.users.list().map((row) => {
+ async listUsers(): Promise<UserInfo[]> {
+ const out: UserInfo[] = [];
+ for (const row of this.users.list()) {
const { avatar: _avatar, ...info } = toUserInfo(row);
- return info;
- });
+ out.push({ ...info, ...(await this.ownedProjectsCost(row.userId)) });
+ }
+ return out;
+ }
+
+ /** One account's owned Projects, priced and summed; `totalCostUsd` is omitted while nothing could be priced. */
+ private async ownedProjectsCost(
+ userId: string,
+ ): Promise<Pick<UserInfo, "totalCostUsd" | "costUnpriced">> {
+ let cost: number | null = null;
+ let unpriced = false;
+ for (const project of this.projects.listByOwner(userId)) {
+ const figure = await this.usage.lifetimeCost(project.projectId);
+ if (figure.cost !== null) cost = (cost ?? 0) + figure.cost;
+ unpriced = unpriced || figure.unpriced;
+ }
+ return {
+ ...(cost !== null ? { totalCostUsd: cost } : {}),
+ ...(unpriced ? { costUnpriced: true } : {}),
+ };
}
async createUser(userId: string, password: string): Promise<UserInfo> {
@@ -68,6 +96,7 @@ export class AdminService implements Admin {
passwordIsInitial: true,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt: this.clock.now().toISOString(),
};
this.users.insert(user);
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index 9af137a2..4946bd6d 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -506,6 +506,26 @@ export class UsageService implements UsageQueries {
};
}
+ /**
+ * The Project's lifetime cost — one unfiltered grouped scan, the same one `modelTotals` runs,
+ * priced at the current rates. Its consumer is a per-account figure (the admin user backend's
+ * cost column), so there is exactly one number: `cost` stays null while nothing could be
+ * priced rather than reporting a zero the caller cannot tell from "ran for free", and
+ * `unpriced` marks a lower bound.
+ */
+ async lifetimeCost(projectId: string): Promise<{ cost: number | null; unpriced: boolean }> {
+ const rows = this.usage.bucketByModel(projectId, {}, this.tiers());
+ const rates = new Map<string, TieredRates | undefined>();
+ for (const r of rows) {
+ const key = refKey(r.provider, r.modelId);
+ if (!rates.has(key)) {
+ rates.set(key, await this.lookupPricing(projectId, r.provider, r.modelId));
+ }
+ }
+ const { cost, hasUncosted } = this.foldBucket(rows, rates);
+ return { cost, unpriced: hasUncosted };
+ }
+
private foldBucket(
rows: UsageModelSums[],
rates: Map<string, TieredRates | undefined>,
diff --git a/packages/server/test/admin-users.test.ts b/packages/server/test/admin-users.test.ts
index e9d145b9..288d2612 100644
--- a/packages/server/test/admin-users.test.ts
+++ b/packages/server/test/admin-users.test.ts
@@ -1,11 +1,13 @@
/**
* Admin users backend integration tests: permission boundary (non-admin 403), account
- * creation validation and rollback, password reset (session invalidation), and user
- * deletion (cascading deletion of owned Project).
+ * creation validation and rollback, password reset (session invalidation), user
+ * deletion (cascading deletion of owned Project), and the list's two read-only
+ * columns (last sign-in, owned-Project lifetime cost).
*/
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { saveProjectConfig } from "@lmliheng/penguin-core";
import type { AdminUsersResponse, MembersResponse } from "../src/api/types.js";
import { apiClient, createTestApp, loginAdmin, loginUser, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -149,4 +151,82 @@ describe("admin users backend", () => {
expect((await admin.delete("/api/admin/users/admin")).status).toBe(409);
expect((await admin.delete("/api/admin/users/ghost")).status).toBe(404);
});
+
+ /**
+ * The two read-only columns the user backend carries. Both are the server's own figures: the
+ * sign-in stamp AuthService writes on a password login, and the lifetime cost of the Projects
+ * the account OWNS, priced at the current rates.
+ */
+ it("user list: last sign-in is stamped by the login that succeeded, absent for an account never used", async () => {
+ const kate = await provisionUser(t.app, "kate");
+ // Kate has signed in (provisionUser logs her in); "dave" was created and never used.
+ expect(
+ (await admin.post("/api/admin/users", { userId: "dave", password: "password-123" })).status,
+ ).toBe(201);
+ expect(kate.user.lastLoginAt).toBeTruthy();
+
+ const list = (await (await admin.get("/api/admin/users")).json()) as AdminUsersResponse;
+ const byId = new Map(list.users.map((u) => [u.userId, u]));
+ expect(byId.get("admin")!.lastLoginAt).toBeTruthy();
+ expect(byId.get("kate")!.lastLoginAt).toBeTruthy();
+ expect(byId.get("dave")!.lastLoginAt).toBeUndefined();
+ // Nothing has run anywhere, so there is no figure to price — the column reports no cost
+ // rather than a zero the reader cannot tell from "ran for free".
+ expect(byId.get("dave")!.totalCostUsd).toBeUndefined();
+ expect(byId.get("admin")!.costUnpriced).toBeUndefined();
+ });
+
+ it("user list: cost sums the Projects the account owns, and says so when a model has no price", async () => {
+ const kate = await provisionUser(t.app, "kate");
+ // Two models in Kate's own Project: `m-priced` costs (10*1 + 1*2 + 5*3)/1e6 per record,
+ // `m-free` carries no pricing block at all.
+ await saveProjectConfig(t.root, "kate-default_project", {
+ default_model: { provider: "custom", model_id: "m-priced" },
+ models: [
+ {
+ provider: "custom",
+ model_id: "m-priced",
+ pricing: { unit: "usd_per_mtok", cache_read: 1, cache_write: 2, output: 3 },
+ },
+ { provider: "custom", model_id: "m-free" },
+ ],
+ });
+ const insertUsage = (modelId: string, date: string): void => {
+ t.deps.db
+ .prepare(
+ "INSERT INTO usage_records (ts, date, project_id, agent_id, session_id, origin_session_id, provider, model_id, cache_read, cache_write, output, total)" +
+ " VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)",
+ )
+ .run(
+ `${date}T00:00:00.000Z`,
+ date,
+ "kate-default_project",
+ "kate_agent",
+ "s-1",
+ "custom",
+ modelId,
+ 10,
+ 1,
+ 5,
+ 16,
+ );
+ };
+ insertUsage("m-priced", "2026-10-01");
+ insertUsage("m-priced", "2026-10-02");
+ // Nobody else's: the admin's own default Project has no usage, and Kate's cost counts only
+ // what her own Project recorded — the figure is per owned Project, not per caller.
+ let list = (await (await admin.get("/api/admin/users")).json()) as AdminUsersResponse;
+ const priced = list.users.find((u) => u.userId === "kate")!;
+ expect(priced.totalCostUsd).toBeCloseTo((2 * (10 * 1 + 1 * 2 + 5 * 3)) / 1e6, 12);
+ expect(priced.costUnpriced).toBeUndefined();
+ expect(list.users.find((u) => u.userId === "admin")!.totalCostUsd).toBeUndefined();
+
+ // A record on a model with no price block makes the sum a lower bound — reported as such
+ // instead of silently dropped.
+ insertUsage("m-free", "2026-10-03");
+ list = (await (await admin.get("/api/admin/users")).json()) as AdminUsersResponse;
+ const bounded = list.users.find((u) => u.userId === "kate")!;
+ expect(bounded.totalCostUsd).toBeCloseTo(priced.totalCostUsd!, 12);
+ expect(bounded.costUnpriced).toBe(true);
+ });
});
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index 83941b3a..e1b1c7b5 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -16,8 +16,9 @@
* Scenarios:
* - Given a web.db formed before a column existed, when it is opened, the column is added, the
* old rows read back with the grandfathered value, and the column takes writes at once
- * (sessions' client / has_trace; each messaging_bindings column added since 0.2.5, with
- * render_markdown the one that starts ON).
+ * (sessions' client / has_trace; users' last_login_at, whose old rows read as "never signed
+ * in"; each messaging_bindings column added since 0.2.5, with render_markdown the one that
+ * starts ON).
* - Given a database this build already formed, a reopen changes nothing.
* - Given sessions formed before last_active_at, the open backfills it once from the last
* request (else created_at); a later open neither re-runs the backfill nor rewrites a row.
@@ -39,6 +40,7 @@ import { openDatabase } from "../src/db/database.js";
import { SCHEMA_SQL } from "../src/db/schema.js";
import { MessagingBindingsRepo } from "../src/db/repos/messaging-bindings.js";
import { SessionsRepo } from "../src/db/repos/sessions.js";
+import { UsersRepo } from "../src/db/repos/users.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import { wire } from "@lmliheng/penguin-core/kernel";
@@ -115,6 +117,41 @@ function rawLastActive(db: DatabaseSync, sessionId: string): unknown {
}
describe("openDatabase column upgrade", () => {
+ it("adds last_login_at to a users table formed before the column existed", () => {
+ const dbPath = path.join(dir, "web.db");
+ // A database formed before the admin user backend reported sign-ins: users without
+ // last_login_at.
+ seedDatabase(dbPath, (old) => {
+ old.exec(`CREATE TABLE users (
+ user_id TEXT PRIMARY KEY,
+ password_hash TEXT NOT NULL,
+ is_admin INTEGER NOT NULL DEFAULT 0,
+ password_is_initial INTEGER NOT NULL DEFAULT 0,
+ display_name TEXT,
+ avatar TEXT,
+ created_at TEXT NOT NULL
+ );`);
+ old
+ .prepare(
+ `INSERT INTO users (user_id, password_hash, created_at)
+ VALUES ('kate', 'x', '2026-01-01T00:00:00.000Z')`,
+ )
+ .run();
+ });
+
+ const db = openDatabase(dbPath);
+ try {
+ const repo = wire(UsersRepo, { db: db });
+ // The account predating the column reads as "never signed in" rather than failing on a
+ // missing column, and the sign-in stamp takes a write at once.
+ expect(repo.findById("kate")!.lastLoginAt).toBeNull();
+ repo.touchLastLogin("kate", "2026-10-08T00:00:00.000Z");
+ expect(repo.findById("kate")!.lastLoginAt).toBe("2026-10-08T00:00:00.000Z");
+ } finally {
+ db.close();
+ }
+ });
+
it("adds client/has_trace to a sessions table formed before the columns existed", () => {
const dbPath = path.join(dir, "web.db");
// A database formed by the pre-#139 schema: sessions without client / has_trace.
diff --git a/packages/server/test/org-harness.ts b/packages/server/test/org-harness.ts
index dcaa93b5..7172e569 100644
--- a/packages/server/test/org-harness.ts
+++ b/packages/server/test/org-harness.ts
@@ -103,6 +103,7 @@ export async function makeOrgHarness(opts: {
passwordIsInitial: false,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt: "2026-08-01T00:00:00Z",
});
const projects = wire(ProjectsRepo, { db });
diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.ts
index 00fac4b5..3620a8d4 100644
--- a/packages/server/test/organization-runtime.test.ts
+++ b/packages/server/test/organization-runtime.test.ts
@@ -131,6 +131,7 @@ describe("organization runtime", () => {
passwordIsInitial: false,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt: "2026-08-01T00:00:00Z",
});
const projects = wire(ProjectsRepo, { db });
diff --git a/packages/server/test/reset-admin-password.test.ts b/packages/server/test/reset-admin-password.test.ts
index 1c0a53c1..8de7e644 100644
--- a/packages/server/test/reset-admin-password.test.ts
+++ b/packages/server/test/reset-admin-password.test.ts
@@ -46,6 +46,7 @@ describe("resetAdminPassword", () => {
passwordIsInitial: false,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt,
});
users.insert({
@@ -55,6 +56,7 @@ describe("resetAdminPassword", () => {
passwordIsInitial: false,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt,
});
const sessions = wire(AuthSessionsRepo, { db: db });
diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.ts
index 8fe15e02..2a375784 100644
--- a/packages/server/test/scheduler.test.ts
+++ b/packages/server/test/scheduler.test.ts
@@ -73,6 +73,7 @@ describe("scheduler", () => {
passwordIsInitial: false,
displayName: null,
avatar: null,
+ lastLoginAt: null,
createdAt: "2026-07-16T00:00:00Z",
});
const projects = wire(ProjectsRepo, { db: db });
diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts
index 471508f8..030ec926 100644
--- a/packages/server/test/usage.test.ts
+++ b/packages/server/test/usage.test.ts
@@ -18,6 +18,8 @@
* - Success counts completed requests over every non-aborted one: a user's Stop is not a model
* failure.
* - Model totals sum every record a model ever wrote, per paired reference, per Project.
+ * - Lifetime cost is that same whole history priced at the current rates, one number per
+ * Project: null while nothing could be priced, and flagged when a Model has no price.
* - Series are zero-filled buckets by minute, hour (local clock), day, ISO week or month, with
* per-Agent and per-model series aligned to them; a minute series needs a timestamp window,
* the range defaults to 30 days, and an oversized series is refused.
@@ -391,6 +393,25 @@ describe("usage-service (cost computed on the fly)", () => {
expect(byAgent.byModelSeries.map((s) => s.modelId)).toEqual(["m1"]);
expect(byAgent.series[0]!.requests).toBe(1);
});
+
+ it("lifetimeCost prices every record the Project wrote, and flags a Model with no price", async () => {
+ insert("2026-01-01");
+ insert("2020-03-02", { agentId: "a2" });
+ expect((await service(new Date()).lifetimeCost("p1")).cost).toBeCloseTo(2 * ROW_COST, 12);
+
+ // A reference no pricing table covers cannot be priced: the number is a lower bound, said
+ // out loud, rather than a total that quietly excluded it.
+ insert("2026-07-06", { modelId: "m-unknown" });
+ const bounded = await service(new Date()).lifetimeCost("p1");
+ expect(bounded.cost).toBeCloseTo(2 * ROW_COST, 12);
+ expect(bounded.unpriced).toBe(true);
+
+ // An empty Project has no figure at all — not a zero.
+ expect(await service(new Date()).lifetimeCost("p-empty")).toEqual({
+ cost: null,
+ unpriced: false,
+ });
+ });
});
describe("usage-service model totals (unfiltered, for the models page)", () => {
diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.ts
index df6972bc..abb2730b 100644
--- a/packages/ui-gallery/src/app/mock/fixtures.ts
+++ b/packages/ui-gallery/src/app/mock/fixtures.ts
@@ -150,12 +150,19 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
passwordIsInitial: false,
displayName: L("演示管理员", "Demo Admin"),
createdAt: iso(ago(120)),
+ // The user table's two read-only columns: this account signed in a little while ago and its
+ // Projects have cost something (some of it on a model with no price, hence the lower bound).
+ lastLoginAt: iso(ago(0.02)),
+ totalCostUsd: 12.4062,
+ costUnpriced: true,
};
const member: UserInfo = {
userId: IDS.users.member,
isAdmin: false,
passwordIsInitial: true,
createdAt: iso(ago(30)),
+ lastLoginAt: iso(ago(2)),
+ totalCostUsd: 0.3187,
};
const project: ProjectSummary = {
diff --git a/packages/ui/src/components/overlays/paged-dialog/paged-dialog.tsx b/packages/ui/src/components/overlays/paged-dialog/paged-dialog.tsx
index f2cfc98c..6981578f 100644
--- a/packages/ui/src/components/overlays/paged-dialog/paged-dialog.tsx
+++ b/packages/ui/src/components/overlays/paged-dialog/paged-dialog.tsx
@@ -47,6 +47,7 @@ export function PagedDialog<K extends string>({
onSelect,
children,
closeLabel,
+ widthClass,
}: {
open: boolean;
onClose: () => void;
@@ -59,13 +60,26 @@ export function PagedDialog<K extends string>({
children: ReactNode;
/** The close cross's accessible name; defaults to the interface's word for "close". */
closeLabel?: string;
+ /**
+ * The panel's width class; defaults to `sm:max-w-3xl`. A page whose content is a wide table
+ * (the user backend's six columns, say) asks for more room — the alternative there is a table
+ * the reader has to scroll sideways to reach its own row actions.
+ */
+ widthClass?: string;
}) {
const showGroupHeadings = groups.length > 1;
const activeItem = groups.flatMap((g) => g.items).find((item) => item.key === active);
const activeLabel = activeItem?.label ?? title;
return (
- <Modal open={open} onClose={onClose} title={title} headerless bare widthClass="sm:max-w-3xl">
+ <Modal
+ open={open}
+ onClose={onClose}
+ title={title}
+ headerless
+ bare
+ widthClass={widthClass ?? "sm:max-w-3xl"}
+ >
<div className="flex h-[min(40rem,85vh)] flex-col sm:flex-row">
{/* Rail: vertical on desktop, a horizontal scroller above the pane on narrow screens. */}
<NavList
diff --git a/packages/web/src/features/admin/admin-users-page.tsx b/packages/web/src/features/admin/admin-users-page.tsx
index dae4cef7..10f26552 100644
--- a/packages/web/src/features/admin/admin-users-page.tsx
+++ b/packages/web/src/features/admin/admin-users-page.tsx
@@ -4,6 +4,11 @@
* Registration is closed: new users are created here, with the initial password set by the admin and
* communicated offline; deleting a user also deletes all their Projects (including data directories),
* with a confirmation dialog.
+ *
+ * The table's two middle columns are read-only figures off the server's own list: when the
+ * account last signed in (`lastLoginAt`, absent until it ever does) and what the Projects it
+ * owns have cost in total (`totalCostUsd`, absent while nothing of it could be priced). Nothing
+ * here computes either — the page draws what `GET /api/admin/users` answers.
*/
import { useCallback, useEffect, useState } from "react";
import type { UserInfo } from "@lmliheng/penguin-server/api";
@@ -13,11 +18,13 @@ import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { USERNAME_PATTERN } from "../../lib/semantic-id";
-import { formatDateTime } from "../../lib/format";
+import { formatDateTime, formatMoney } from "../../lib/format";
import { useAuth } from "../../state/auth";
+import { useTheme } from "../../state/theme";
export function AdminUsersSection() {
const { user, desktopMode } = useAuth();
+ const { currency } = useTheme();
const [users, setUsers] = useState<UserInfo[] | null>(null);
const [listError, setListError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
@@ -60,6 +67,12 @@ export function AdminUsersSection() {
<th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.username}</th>
<th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.role}</th>
<th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.created}</th>
+ {/* The two read-only columns: when the account last signed in (so an account
+ nobody uses stands out) and what its Projects have cost so far. */}
+ <th className="whitespace-nowrap px-3 py-2 font-medium">{S.admin.lastLogin}</th>
+ <th className="whitespace-nowrap px-3 py-2 text-right font-medium">
+ {S.admin.totalCost}
+ </th>
<th className="whitespace-nowrap px-3 py-2 text-right font-medium">
{S.common.actions}
</th>
@@ -90,6 +103,21 @@ export function AdminUsersSection() {
<td className="whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400">
{formatDateTime(u.createdAt)}
</td>
+ <td className="whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400">
+ {u.lastLoginAt !== undefined
+ ? formatDateTime(u.lastLoginAt)
+ : S.admin.lastLoginNever}
+ </td>
+ {/* Read-only, and a lower bound when some usage had no price (`costUnpriced`):
+ the "≥" says so without a second line of copy, and the tooltip spells it out. */}
+ <td
+ className="whitespace-nowrap px-3 py-2 text-right tabular-nums text-gray-500 dark:text-gray-400"
+ data-tooltip={S.admin.costHint}
+ >
+ {u.totalCostUsd === undefined
+ ? "—"
+ : `${u.costUnpriced === true ? "≥ " : ""}${formatMoney(u.totalCostUsd, currency)}`}
+ </td>
<td className="whitespace-nowrap px-3 py-1.5 text-right">
<Button size="sm" variant="ghost" onClick={() => setResetting(u)}>
{S.admin.resetPassword}
diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsx
index e2ab00d6..aada3f19 100644
--- a/packages/web/src/features/settings/settings-dialog.tsx
+++ b/packages/web/src/features/settings/settings-dialog.tsx
@@ -138,6 +138,13 @@ export function SettingsDialog({
}),
);
+ /**
+ * The user backend's table carries six columns and two row actions, and the shared width
+ * leaves it scrolling sideways to reach its own buttons: that page asks for a wider panel.
+ * Every other page keeps the default.
+ */
+ const panelWidthClass = current === "users" ? "sm:max-w-5xl" : undefined;
+
return (
<PagedDialog
open={open}
@@ -146,6 +153,7 @@ export function SettingsDialog({
groups={groups}
active={current}
onSelect={setActive}
+ widthClass={panelWidthClass}
>
{current === "profile" && <ProfileSection />}
{current === "general" && <GeneralSection />}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 43892981..82cbba29 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -974,6 +974,14 @@ export const en: Strings = {
roleAdmin: "Admin",
roleUser: "User",
createUser: "Add user",
+ /** The two read-only columns the user table gained: when the account last signed in, and what its Projects have cost. */
+ lastLogin: "Last sign-in",
+ /** Never signed in: the account exists (an admin created it) but has not been used. */
+ lastLoginNever: "Never",
+ totalCost: "Total cost",
+ /** The cost column's tooltip: what the figure counts, and what an "≥" in front of it means. */
+ costHint:
+ "Every Project this account owns, all of its usage priced at today's rates. A leading ≥ means some of that usage ran on a model with no price, so the figure is a lower bound.",
initialPassword: "Initial password",
initialPasswordFlag: "initial password",
defaultProjectNote: (id: string): string => `A default Project will be created: ${id}`,
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 29628964..e0b0cc7d 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1022,6 +1022,14 @@ export const zh = {
roleAdmin: "管理员",
roleUser: "用户",
createUser: "新增用户",
+ /** The two read-only columns the user table gained: when the account last signed in, and what its Projects have cost. */
+ lastLogin: "最近登录",
+ /** Never signed in: the account exists (an admin created it) but has not been used. */
+ lastLoginNever: "从未登录",
+ totalCost: "累计开销",
+ /** The cost column's tooltip: what the figure counts, and what an "≥" in front of it means. */
+ costHint:
+ "该用户名下全部项目的历史用量,按当前价格折算。带 ≥ 表示其中有用量所在模型没有价格,这是下限。",
initialPassword: "初始密码",
initialPasswordFlag: "初始密码",
defaultProjectNote: (id: string): string => `将自动创建默认项目:${id}`,