A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): 用户管理表多一列「最近一次会话」,看得出账号最后在聊什么
lmlihengb5611cc656c5
diff --git a/changelog/unreleased/2026-10-15-admin-last-session.md b/changelog/unreleased/2026-10-15-admin-last-session.mdnew file mode 100644index 00000000..c2c04620--- /dev/null+++ b/changelog/unreleased/2026-10-15-admin-last-session.md@@ -0,0 +1,27 @@+# The user table gains a "Last session" column++- **Date:** 2026-10-15+- **Type:** feat+- **Scope:** `server`, `web`++[中文版](2026-10-15-admin-last-session.zh.md)++The admin user table gains "Last session" beside "Last sign-in": the most recently active+conversation **across every Project the account owns** — the time on the first line (the same figure+the column next to it shows) and that Session's title under it. A Session with no title generated+and no rename yet has only the time to show. An account that never opened a conversation reads `—`,+which is a different state from "Never" signed in.++"Most recent" is by activity, not creation: a conversation started at the beginning of the month and+used today counts as today's. Archived Sessions and subagent Sessions are included — they are rows in+the same index every Session list draws from, and this column does not invent a second rule.+Long titles are truncated with the full text on hover; the title is drawn in the cell rather than+hidden in a tooltip, since a tooltip is unreachable on touch.++The column brings the table to seven of them, which the previous panel width could not hold without+scrolling sideways to reach "Reset password" / "Delete", so the user page's dialog goes from+`max-w-5xl` to `max-w-6xl`: measured, the table wanted 861px inside a 796px pane before, and now fits+in 924px. Every other settings page keeps the narrower panel.++The figure is computed by the server: each entry of `GET /api/admin/users` carries two optional+fields, `lastSessionAt` and `lastSessionTitle`, both omitted for an account with no Session at all.diff --git a/changelog/unreleased/2026-10-15-admin-last-session.zh.md b/changelog/unreleased/2026-10-15-admin-last-session.zh.mdnew file mode 100644index 00000000..a5793f77--- /dev/null+++ b/changelog/unreleased/2026-10-15-admin-last-session.zh.md@@ -0,0 +1,22 @@+# 用户管理表多一列「最近一次会话」++- **Date:** 2026-10-15+- **Type:** feat+- **Scope:** `server`, `web`++[English](2026-10-15-admin-last-session.md)++管理员的用户管理表在「最近登录」旁边多了「最近一次会话」:显示该账号**名下所有项目**里最近活跃的+一次对话——上面一行是时间(和旁边的登录时间同一口径),下面一行是这次对话的标题(还没生成标题、+也没人重命名过的会话只有时间)。一个从来没开过对话的账号显示 `—`,与「从未登录」区分开。++时间取的是**最近活跃**,不是最近创建:一个月初开的对话今天还在用,它算今天的。已归档的会话和+子会话都算在内——它们本来就是会话列表里的行,这一列不另立一套口径。标题过长会截断,悬停可看全文+(移动端看不到悬停,所以标题默认就在格子里,而不是只藏在提示里)。++这一列把表格撑到了七列,原来的面板宽度会横向滚动才够得着「重置密码 / 删除」,所以用户管理这一页+的对话框从 `max-w-5xl` 加宽到 `max-w-6xl`:加宽前实测表格 861px、内容区只有 796px,加宽后内容区+924px、表格 924px,正好放下不再滚动。别的设置页仍是原宽度。++数据由服务端现算:`GET /api/admin/users` 的每一项多带 `lastSessionAt` 与 `lastSessionTitle`+两个可选字段,没有会话时两个都不带。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 77585dd5..ec97a76c 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -91,6 +91,21 @@ export interface UserInfo {* deployment has no price for, so the figure is a lower bound. Omitted when it is exact.*/costUnpriced?: boolean;+ /**+ * Admin user backend (`GET /api/admin/users`): when the most recent Session across the+ * Projects this account owns was last active (ISO) — the same figure the sidebar orders by,+ * so a Session created long ago and used today counts as today's. Omitted while the account+ * has no Session anywhere, which is how an unused account reads as having none rather than+ * as having one at the epoch. Archived Sessions and subagent Sessions are included: they are+ * rows in the same index every other Session list draws from.+ */+ lastSessionAt?: string;+ /**+ * Admin user backend, alongside `lastSessionAt`: that Session's title, i.e. what the account+ * was working on. Omitted while the Session has none yet (no title has been generated, and+ * the account has not renamed it).+ */+ lastSessionTitle?: string;createdAt: string;}diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.tsindex 09063249..a1c97549 100644--- a/packages/server/src/db/repos/sessions.ts+++ b/packages/server/src/db/repos/sessions.ts@@ -257,6 +257,47 @@ export class SessionsRepo implements SessionIndex {return rows.map(mapRow);}+ /**+ * The most recently active row across several Projects at once — the admin user backend asks+ * it per account, whose Sessions are spread over every Project that account owns, so it must+ * be one answer rather than one answer per Project.+ *+ * The ordering key is the activity order's (`lastActiveAt` descending, `sessionId` descending+ * to break ties), computed here as code points like every other activity comparison — no+ * `localeCompare`, whose collation the SQL-side order would not share. `last_active_at` is+ * coalesced to `created_at` for the same reason `mapRow` does it: a row nothing has driven+ * yet is active from its creation.+ *+ * Chunked like `markOrgClient`: how many Projects an account owns is unbounded while SQLite's+ * parameter count is not, so the winners of each chunk are compared against each other.+ */+ latestByProjects(projectIds: readonly string[]): SessionRow | null {+ let best: SessionRow | null = null;+ for (let i = 0; i < projectIds.length; i += 400) {+ const chunk = projectIds.slice(i, i + 400);+ const placeholders = chunk.map(() => "?").join(", ");+ const r = this.db+ .prepare(+ `SELECT * FROM sessions WHERE project_id IN (${placeholders})+ ORDER BY COALESCE(last_active_at, created_at) DESC, session_id DESC LIMIT 1`,+ )+ .get(...chunk) as Record<string, unknown> | undefined;+ if (!r) continue;+ const candidate = mapRow(r);+ if (best === null) {+ best = candidate;+ continue;+ }+ // The candidate wins when it is the more recent of the two under the activity order.+ const moreRecent =+ candidate.lastActiveAt !== best.lastActiveAt+ ? candidate.lastActiveAt > best.lastActiveAt+ : candidate.sessionId > best.sessionId;+ if (moreRecent) best = candidate;+ }+ return best;+ }+updateApprovalMode(sessionId: string, mode: ApprovalMode): void {this.db.prepare("UPDATE sessions SET approval_mode = ? WHERE session_id = ?")diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.tsindex c4a83008..09d2e383 100644--- a/packages/server/src/mechanisms/sessions.ts+++ b/packages/server/src/mechanisms/sessions.ts@@ -24,6 +24,7 @@ export abstract class SessionIndex {abstract findById(sessionId: string): SessionRow | null;abstract listByAgent(projectId: string, agentId: string): SessionRow[];abstract listByProject(projectId: string): SessionRow[];+ abstract latestByProjects(projectIds: readonly string[]): SessionRow | null;abstract updateApprovalMode(sessionId: string, mode: ApprovalMode): void;abstract updateSandbox(sessionId: string, sandbox: SandboxSettings): void;abstract updateThinkingLevel(sessionId: string, level: ThinkingLevelName): void;diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.tsindex df247e0f..199adc4a 100644--- a/packages/server/src/services/admin-service.ts+++ b/packages/server/src/services/admin-service.ts@@ -22,6 +22,7 @@ import { SEMANTIC_ID_RULE, USERNAME_PATTERN } from "./ids.js";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 { SessionIndex } from "../mechanisms/sessions.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";@@ -32,6 +33,7 @@ export class AdminService implements Admin {@Use() private readonly authSessions!: AuthSessions;@Use() private readonly liveStreams!: LiveStreams;@Use() private readonly projects!: Projects;+ @Use() private readonly sessions!: SessionIndex;@Use() private readonly usage!: UsageQueries;@Use() private readonly projectService!: ProjectLifecycle;@Use() private readonly clock!: Clock;@@ -53,19 +55,24 @@ export class AdminService implements Admin {const out: UserInfo[] = [];for (const row of this.users.list()) {const { avatar: _avatar, ...info } = toUserInfo(row);- out.push({ ...info, ...(await this.ownedProjectsCost(row.userId)) });+ const owned = this.projects.listByOwner(row.userId).map((p) => p.projectId);+ out.push({+ ...info,+ ...(await this.ownedProjectsCost(owned)),+ ...this.lastSession(owned),+ });}return out;}/** One account's owned Projects, priced and summed; `totalCostUsd` is omitted while nothing could be priced. */private async ownedProjectsCost(- userId: string,+ projectIds: readonly 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);+ for (const projectId of projectIds) {+ const figure = await this.usage.lifetimeCost(projectId);if (figure.cost !== null) cost = (cost ?? 0) + figure.cost;unpriced = unpriced || figure.unpriced;}@@ -75,6 +82,28 @@ export class AdminService implements Admin {};}+ /**+ * The account's most recent Session across the Projects it owns, as a time plus (when the+ * Session already has one) its title. Ordered by activity, the same figure the sidebar calls+ * 「最近更新」: the question the column answers is "which conversation did this account touch+ * last", so the newest stamp is the one to show, not the newest creation.+ *+ * Sessions are listed as they are stored — no filtering by archive state or by who opened+ * one, and subagent Sessions are rows here like anywhere else. Every other list in the+ * product draws the same set, and an account's own conversation is what an admin is looking+ * at, not a curated subset of it.+ */+ private lastSession(+ projectIds: readonly string[],+ ): Pick<UserInfo, "lastSessionAt" | "lastSessionTitle"> {+ const row = this.sessions.latestByProjects(projectIds);+ if (!row) return {};+ return {+ lastSessionAt: row.lastActiveAt,+ ...(row.title !== null && row.title !== "" ? { lastSessionTitle: row.title } : {}),+ };+ }+async createUser(userId: string, password: string): Promise<UserInfo> {if (!USERNAME_PATTERN.test(userId)) {throw new HttpError(diff --git a/packages/server/test/admin-users.test.ts b/packages/server/test/admin-users.test.tsindex 78abcb7e..37031d6f 100644--- a/packages/server/test/admin-users.test.ts+++ b/packages/server/test/admin-users.test.ts@@ -1,8 +1,8 @@/*** Admin users backend integration tests: permission boundary (non-admin 403), account* 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).+ * deletion (cascading deletion of owned Project), and the list's three read-only+ * columns (last sign-in, last session, owned-Project lifetime cost).*/import fs from "node:fs/promises";import path from "node:path";@@ -232,4 +232,114 @@ describe("admin users backend", () => {expect(bounded.totalCostUsd).toBeCloseTo(priced.totalCostUsd!, 12);expect(bounded.costUnpriced).toBe(true);});++ /**+ * The third read-only column: which conversation the account touched last, taken across every+ * Project it owns. "Last" is by ACTIVITY, not creation — a Session opened early and driven+ * today outranks one created later and left alone.+ */+ it("user list: last session is the newest activity across the Projects the account owns", async () => {+ const kate = await provisionUser(t.app, "kate");+ const kateApi = apiClient(t.app, kate.cookie);+ /**+ * A Session row as the index holds it. Ownership travels through the Project, so the Project+ * id is what decides whose row it lands in.+ */+ const insertSession = (+ sessionId: string,+ projectId: string,+ createdAt: string,+ lastActiveAt: string,+ title: string | null = null,+ ): void => {+ t.deps.sessionsRepo.insert({+ sessionId,+ projectId,+ agentId: "kate_agent",+ provider: "custom",+ modelId: "m-1",+ workspace: "/tmp/workspace",+ approvalMode: "allow-all",+ title,+ createdAt,+ lastActiveAt,+ });+ };+ type Listed = AdminUsersResponse["users"][number];+ const listUsers = async (): Promise<Map<string, Listed>> => {+ const list = (await (await admin.get("/api/admin/users")).json()) as AdminUsersResponse;+ return new Map(list.users.map((u) => [u.userId, u]));+ };++ // Kate signed in but never opened a conversation: no time to show, rather than one the+ // reader would take for a real Session.+ expect((await listUsers()).get("kate")!.lastSessionAt).toBeUndefined();++ // Kate's own Project, plus one the ADMIN owns: the admin's Session must not answer for her.+ insertSession(+ "s-kate-old",+ "kate-default_project",+ "2026-10-01T00:00:00.000Z",+ "2026-10-02T00:00:00.000Z",+ "周报整理",+ );+ insertSession(+ "s-kate-new",+ "kate-default_project",+ "2026-10-03T00:00:00.000Z",+ "2026-10-05T00:00:00.000Z",+ "重构会话索引",+ );+ insertSession(+ "s-admin",+ "default_project",+ "2026-10-09T00:00:00.000Z",+ "2026-10-09T00:00:00.000Z",+ "管理员自己的",+ );++ let users = await listUsers();+ // The older creation with the newer activity wins: the column answers "touched last".+ expect(users.get("kate")!.lastSessionAt).toBe("2026-10-05T00:00:00.000Z");+ expect(users.get("kate")!.lastSessionTitle).toBe("重构会话索引");+ expect(users.get("admin")!.lastSessionTitle).toBe("管理员自己的");++ // A second owned Project counts the same way, and a Session that has no title yet carries+ // the time alone instead of an empty title.+ expect(+ (await kateApi.post("/api/projects", { projectId: "kate-extra", name: "Extra" })).status,+ ).toBe(201);+ insertSession(+ "s-kate-today",+ "kate-extra",+ "2026-10-04T00:00:00.000Z",+ "2026-10-06T00:00:00.000Z",+ );+ users = await listUsers();+ expect(users.get("kate")!.lastSessionAt).toBe("2026-10-06T00:00:00.000Z");+ expect(users.get("kate")!.lastSessionTitle).toBeUndefined();+ });++ /**+ * The query behind that column names an account's Projects in one statement, and an account may+ * own more of them than SQLite takes parameters: a winner sitting past the first chunk still+ * has to be found, and asking about no Projects at all is "no Session", never an error.+ */+ it("last activity is found across more Projects than one query can name", () => {+ t.deps.sessionsRepo.insert({+ sessionId: "s-late",+ projectId: "p-400",+ agentId: "kate_agent",+ provider: "custom",+ modelId: "m-1",+ workspace: "/tmp/workspace",+ approvalMode: "allow-all",+ title: "后排的",+ createdAt: "2026-10-01T00:00:00.000Z",+ lastActiveAt: "2026-10-10T00:00:00.000Z",+ });+ const projectIds = Array.from({ length: 401 }, (_, i) => `p-${i}`);+ expect(t.deps.sessionsRepo.latestByProjects(projectIds)?.sessionId).toBe("s-late");+ expect(t.deps.sessionsRepo.latestByProjects([])).toBeNull();+ });});diff --git a/packages/web/src/features/admin/admin-users-page.tsx b/packages/web/src/features/admin/admin-users-page.tsxindex 10f26552..91787f4c 100644--- a/packages/web/src/features/admin/admin-users-page.tsx+++ b/packages/web/src/features/admin/admin-users-page.tsx@@ -5,10 +5,12 @@* 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.+ * The table's three middle columns are read-only figures off the server's own list: when the+ * account last signed in (`lastLoginAt`, absent until it ever does), which conversation it+ * touched last (`lastSessionAt` / `lastSessionTitle`, absent while it has no Session at all)+ * and what the Projects it owns have cost in total (`totalCostUsd`, absent while nothing of it+ * could be priced). Nothing here computes any of them — the page draws what+ * `GET /api/admin/users` answers.*/import { useCallback, useEffect, useState } from "react";import type { UserInfo } from "@lmliheng/penguin-server/api";@@ -67,9 +69,16 @@ 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. */}+ {/* The three read-only columns: when the account last signed in (so an account+ nobody uses stands out), which conversation it touched last, 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 font-medium"+ data-tooltip={S.admin.lastSessionHint}+ >+ {S.admin.lastSession}+ </th><th className="whitespace-nowrap px-3 py-2 text-right font-medium">{S.admin.totalCost}</th>@@ -108,6 +117,29 @@ export function AdminUsersSection() {? formatDateTime(u.lastLoginAt): S.admin.lastLoginNever}</td>+ {/* Which conversation the account touched last: the time, like the sign-in+ column beside it, with the Session's own title under it the way the id+ carries the nickname — a title alone would not say how recent "last" is,+ and a time alone would not say what was going on. A Session nobody named+ yet has no title to draw, and an account with no Session at all gets a+ dash rather than a time the reader would take for a real one. */}+ <td className="whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400">+ {u.lastSessionAt === undefined ? (+ "—"+ ) : (+ <>+ {formatDateTime(u.lastSessionAt)}+ {u.lastSessionTitle !== undefined && (+ <p+ className="max-w-[10rem] truncate text-xs"+ data-tooltip={u.lastSessionTitle}+ >+ {u.lastSessionTitle}+ </p>+ )}+ </>+ )}+ </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. */}<tddiff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsxindex 7cea2f6d..a7aaf98b 100644--- a/packages/web/src/features/settings/settings-dialog.tsx+++ b/packages/web/src/features/settings/settings-dialog.tsx@@ -144,11 +144,12 @@ 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.+ * The user backend's table carries seven 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+ * (a Session title under its time is what pushed it past the previous 5xl, measured at 861px+ * of table inside a 796px pane). Every other page keeps the default.*/- const panelWidthClass = current === "users" ? "sm:max-w-5xl" : undefined;+ const panelWidthClass = current === "users" ? "sm:max-w-6xl" : undefined;return (<PagedDialogdiff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex f4bf4c94..ae99340f 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1246,10 +1246,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. */+ /** The three read-only columns the user table gained: when the account last signed in, which conversation it touched last, 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",+ lastSession: "Last session",+ /** The session column's tooltip: whose Sessions are counted and which one wins. */+ lastSessionHint:+ "The most recently active Session across every Project this account owns (subagent and archived Sessions included); only the time shows until the Session has a title.",totalCost: "Total cost",/** The cost column's tooltip: what the figure counts, and what an "≥" in front of it means. */costHint:diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 78af7a28..6208d511 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1291,10 +1291,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. */+ /** The three read-only columns the user table gained: when the account last signed in, which conversation it touched last, and what its Projects have cost. */lastLogin: "最近登录",/** Never signed in: the account exists (an admin created it) but has not been used. */lastLoginNever: "从未登录",+ lastSession: "最近一次会话",+ /** The session column's tooltip: whose Sessions are counted and which one wins. */+ lastSessionHint:+ "该用户名下全部项目里最近活跃的一次会话(含子会话与已归档的),标题还没生成时只显示时间。",totalCost: "累计开销",/** The cost column's tooltip: what the figure counts, and what an "≥" in front of it means. */costHint: