Skip to content

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

feat(web,server): 左下角菜单能看到正在跑的会话,也能按天查会话花了多少 Token

lmliheng165725081ddc
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 6fb09e72..8d548357 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -697,6 +697,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
| Method | Path | Description |
| --- | --- | --- |
| GET | `/agents/:agentId/sessions` | Lists the agent's Sessions with their run state, whichever client created them, unless `excludeOrg=1` asks for the user's own rows only |
+| GET | `/sessions/running` | The Project's Sessions this server is running or compacting right now: → `{sessions}` (whole rows, running before compacting) |
| POST | `/agents/:agentId/sessions` | Creates a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201 `{session}` |
| GET | `/dirs?path=` | Server-side directory browser behind the Workspace picker |
| POST | `/dirs/access` | Desktop app: has the shell read a folder macOS refused, in the app's own name, so that macOS asks the user: `{path}` → `{granted, packaged}` |
@@ -728,6 +729,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
| --- | --- | --- |
| GET | `/usage` | Usage statistics |
| GET | `/usage/model-totals` | Lifetime Token total per model; takes no filters |
+| GET | `/usage/session-days?days=` | Usage of the last `days` calendar days (today included, 1–90, default 7) by day and by Session: → `{days}` |
| GET | `/usage/errors` | One page of the error detail table, newest first: → `{items, total, rows}` |
| DELETE | `/usage/errors` | Empties the error table for the current filter: → `{deleted}` (Project owner only) |
| GET | `/agents/:agentId/traces` | Trace files as a date → Session drill-down |
@@ -747,6 +749,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
| `agentId`, `provider`, `modelId` | Filters |
- `GET /usage/errors` takes `offset`, `limit`, the same `from` / `to` / `fromTs` / `toTs` / `agentId` filter, and an optional `kind` (`unexpected` or `expected`).
+- `GET /usage/session-days` splits usage by local calendar day and, within a day, by Session: `{days:[{date, total, cost, requests, sessions:[{sessionId, agentId, title?, total, cost, requests}]}]}`, newest day first. Days with no usage are absent, but today is always present (possibly all zeros), so "what did I spend today" always has an answer. `title` comes from the Session index and is omitted for a Session deleted since. A `days` outside 1–90 is a 400.
- The error table folds the records of one day that share a source, code, kind and message into one row, with its `count`, its latest time `ts` and its first time `firstTs`. `offset`, `limit` and `rows` count those rows; `total` and the dashboard's summary figures count records. `GET /usage` and `GET /usage/errors` take an optional `utcOffsetMinutes`, the reader's offset east of UTC (−840 to 840), which decides the day; without it the day is the server's own.
- `DELETE /usage/errors` takes the same filter as the reads, `from` / `to` / `fromTs` / `toTs` / `agentId`, but no `kind`, because the panel offers no such control. `from` and `to` are both required here (400 otherwise), because an open bound would clear the whole history rather than a filtered part. An optional `until` (an ISO-8601 instant) stops the delete at that moment: the cost center re-reads the count when its confirmation opens and passes the **newest record's time** from that read, so the number in the dialog is the number that goes even when a record arrives between the two requests (loading the page itself records one). A malformed `until` is a 400 rather than silently ignored. The clear reaches exactly what the caller's reads reach: an admin's clear also removes the unattributed rows that only an admin's read shows, and a member's clear never does.
- `GET /agents/:agentId/traces` also accepts `limit` and `offset` for paging, and `category` (which requires `limit`) to list one category of Sessions. The paged listing leaves out `company` Sessions, which are in no category; the full drill-down without `limit` lists every Trace.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index e04d643c..bdbdb879 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -697,6 +697,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/agents/:agentId/sessions` | 列出 Agent 的 Session 及运行状态,不论由哪个客户端创建;`excludeOrg=1` 则只要用户自己的那些 |
+| GET | `/sessions/running` | 这个 Project 此刻正在运行或压缩的 Session:→ `{sessions}`(完整行,运行中的排在压缩中的前面) |
| POST | `/agents/:agentId/sessions` | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201 `{session}` |
| GET | `/dirs?path=` | Workspace 选择器背后的服务器端目录浏览器 |
| POST | `/dirs/access` | 桌面端:请 shell 以应用自身的身份读一次 macOS 拒绝的目录,让 macOS 询问用户:`{path}` → `{granted, packaged}` |
@@ -728,6 +729,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| --- | --- | --- |
| GET | `/usage` | 用量统计 |
| GET | `/usage/model-totals` | 每个模型的历史累计 Token 总量;不接受任何过滤参数 |
+| GET | `/usage/session-days?days=` | 最近 `days` 天(含今天,1–90,默认 7)按天、按 Session 拆开的用量:→ `{days}` |
| GET | `/usage/errors` | 错误详情表的一页,按时间倒序:→ `{items, total, rows}` |
| DELETE | `/usage/errors` | 按当前过滤条件清空错误表:→ `{deleted}`(仅限 Project 所有者) |
| GET | `/agents/:agentId/traces` | Trace 文件,按日期 → Session 逐级下钻 |
@@ -747,6 +749,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| `agentId`、`provider`、`modelId` | 过滤条件 |
- `GET /usage/errors` 接受 `offset`、`limit`、同样的 `from` / `to` / `fromTs` / `toTs` / `agentId` 过滤条件,以及可选的 `kind`(`unexpected` 或 `expected`)。
+- `GET /usage/session-days` 按本地日历日拆用量,每天再按 Session 拆开:`{days:[{date, total, cost, requests, sessions:[{sessionId, agentId, title?, total, cost, requests}]}]}`,最新的日子在前。没有用量的日子不出现,但今天总会有一行(可能全为 0),所以「今天花了多少」永远读得到。`title` 取自 Session 索引,会话已删除时省略。`days` 不在 1–90 之间返回 400。
- 错误表把同一天里来源、错误码、分类和消息都相同的记录合为一行,带上次数 `count`、最近一次的时间 `ts` 和首次的时间 `firstTs`。`offset`、`limit` 和 `rows` 按行计;`total` 和仪表盘的汇总数字按记录计。`GET /usage` 与 `GET /usage/errors` 都接受可选的 `utcOffsetMinutes`,即读者所在时区相对 UTC 向东的分钟数(−840 到 840),它决定「同一天」按哪一天算;不传时按服务器自己的日期。
- `DELETE /usage/errors` 接受与读取相同的过滤条件(`from` / `to` / `fromTs` / `toTs` / `agentId`),但不接受 `kind`,因为面板上没有这个控件。这里 `from` 和 `to` 都必填(否则返回 400),因为少一个边界,清空的就是整段历史,而不是过滤后的一部分。可选的 `until`(ISO-8601 时刻)把删除停在那一刻之前:成本中心在确认框打开时重读一次计数,并把这次读到的**最新一条记录的时间**作为 `until` 传来,因此框里写的条数就是真正删掉的条数,即使两次请求之间又有新记录进来(页面自己加载时就会记下一条)。`until` 格式不对返回 400,而不是被悄悄忽略。清空的范围与调用者读取的范围完全一致:管理员清空时,也会删掉只有管理员读取才能看到的未归属行;成员清空时则永远不会。
- `GET /agents/:agentId/traces` 还接受 `limit` 和 `offset` 分页,以及 `category`(必须搭配 `limit`),用于只列出某一类别的 Session。分页列表不含不属于任何类别的 `company` 会话;不带 `limit` 的完整目录列出所有 Trace。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 6eb5372a..ceb3137d 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2253,6 +2253,17 @@ export interface SessionsResponse {
workspaceLatest?: Record<string, string>;
}
+/**
+ * `GET /api/projects/:projectId/sessions/running` — the Sessions of this Project this server
+ * is running (or compacting) right now, as whole rows. The account menu lists them so the user
+ * can see what is running without opening conversations one by one; a live status is enough to
+ * know one is due, and the row carries the title, Agent and Workspace to name it.
+ */
+export interface RunningSessionsResponse {
+ /** Running first, then compacting; most recently active first within each. */
+ sessions: SessionInfo[];
+}
+
/**
* One page request inside POST /api/projects/:p/sessions/batch — the same knobs the
* Agent-level list takes, carried per entry so one call can stand in for a whole sidebar
@@ -4432,6 +4443,53 @@ export interface UsageErrorsClearResponse {
deleted: number;
}
+/**
+ * One Session's usage inside one calendar day — the row a "where did the Tokens go today"
+ * list shows. `sessionId` names it; `title` and `agentId` are what a reader recognises it by
+ * (a deleted Session keeps only its id, so `title` is absent).
+ */
+export interface UsageSessionDayRow {
+ sessionId: string;
+ agentId: string;
+ /** The Session's title, when the row still exists; absent for a Session deleted since. */
+ title?: string;
+ cacheRead: number;
+ cacheWrite: number;
+ output: number;
+ total: number;
+ requests: number;
+ /** Sum of the costs fixed when the Requests completed (USD); null when none had a price. */
+ cost: number | null;
+ /** Some of this Session's Requests ran on a Model with no price, so `cost` is a lower bound. */
+ hasUncosted: boolean;
+}
+
+/** One calendar day's usage, broken down by Session, newest Sessions first within the day. */
+export interface UsageSessionDay {
+ /** Local calendar day the rows were recorded under, `yyyy-mm-dd`. */
+ date: string;
+ cacheRead: number;
+ cacheWrite: number;
+ output: number;
+ total: number;
+ requests: number;
+ cost: number | null;
+ hasUncosted: boolean;
+ sessions: UsageSessionDayRow[];
+}
+
+/**
+ * `GET /api/projects/:projectId/usage/session-days` — usage by calendar day, each day split
+ * by Session: "which conversations spent the Tokens, and how much". Total Token counts match
+ * the cost center's (`cacheRead + cacheWrite + output`); cost sums the figures fixed when the
+ * Requests completed. Days with no usage are absent, except today, which always appears
+ * (possibly at zero) so "today's total" is never missing.
+ */
+export interface UsageSessionDays {
+ /** Newest day first. */
+ days: UsageSessionDay[];
+}
+
export interface UsageResponse {
summary: {
today: UsageBucket;
diff --git a/packages/server/src/db/repos/usage.ts b/packages/server/src/db/repos/usage.ts
index 896b5ba0..4a7c25a5 100644
--- a/packages/server/src/db/repos/usage.ts
+++ b/packages/server/src/db/repos/usage.ts
@@ -75,6 +75,17 @@ export interface UsageGroupModelSums extends UsageModelSums {
key: string;
}
+/**
+ * Raw sums by (calendar day, Session, Agent) x Model: the "which conversations spent the
+ * Tokens on which day" breakdown. The Agent rides along because two Agents' Sessions are
+ * different conversations, and the caller names them without a second lookup.
+ */
+export interface UsageSessionDaySums extends UsageModelSums {
+ date: string;
+ sessionId: string;
+ agentId: string;
+}
+
/** Time-series bucket x Model sums, with the success-rate counts folded in. */
export interface UsageSeriesModelSums extends UsageGroupModelSums {
/** Successful requests in the bucket. */
@@ -308,6 +319,28 @@ export class UsageRepo implements UsageStore {
return rows.map((r) => ({ key: r.key as string, ...toSums(r) }));
}
+ /**
+ * Per-(calendar day, Session, Agent) x paired reference sums: the day-by-day
+ * "which conversations spent the Tokens" view. Same filter and same `date`
+ * column as `groupsByModel`, so a total here adds up to the cost center's.
+ */
+ sessionDayByModel(projectId: string, f: UsageFilter = {}): UsageSessionDaySums[] {
+ const { where, params } = this.conds(projectId, f);
+ const rows = this.db
+ .prepare(
+ `SELECT date, session_id, agent_id, provider, model_id, ${SUM_COLUMNS}
+ FROM usage_records WHERE ${where}
+ GROUP BY date, session_id, agent_id, provider, model_id`,
+ )
+ .all(params);
+ return rows.map((r) => ({
+ date: r.date as string,
+ sessionId: r.session_id as string,
+ agentId: r.agent_id as string,
+ ...toSums(r),
+ }));
+ }
+
/**
* Time-series sums (bucket key x paired reference breakdown) with per-bucket
* success-rate counts riding along: powers the cost center's time-series charts
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 0dd0210f..d60b3e15 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -40,11 +40,13 @@ import type {
SessionProcessesResponse,
SessionResponse,
SessionsResponse,
+ RunningSessionsResponse,
SessionsBatchResponse,
SubagentMessageResponse,
RetryNowResponse,
TaskCreateResponse,
SessionSandbox,
+ SessionInfo,
} from "../../api/types.js";
import { compactionThresholdFor } from "../../services/context-breakdown.js";
import { decodeCursor } from "../../services/message-window.js";
@@ -944,6 +946,42 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
return app;
}
+/**
+ * Project-level entry: GET /api/projects/:p/sessions/running — the Sessions this server is
+ * running (or compacting) right now, as whole rows.
+ *
+ * The sidebar's lists are paged per Agent and category, so "what is running" is not something
+ * any one of them can answer: a conversation running in a group nobody has expanded, or an
+ * archived one, has no row on screen. This walks the runtime's own table instead (every live
+ * Session this process holds) and keeps those of the Project the caller asked about, so the
+ * account menu can name all of them in one cheap request. Rows are projected through the same
+ * `toInfo` the lists use, so a row here carries what a row there carries — title, Agent,
+ * Workspace, live status.
+ */
+export function runningSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.get("/", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
+ const live = deps.manager
+ .liveSessions()
+ .filter((e) => e.projectId === projectId)
+ // Running before compacting (a run waiting on compaction is the second thing to report),
+ // then by id, which is the creation order a Session id encodes.
+ .sort((a, b) => (a.status === b.status ? 0 : a.status === "running" ? -1 : 1));
+ const sessions: SessionInfo[] = [];
+ for (const entry of live) {
+ const row = deps.sessionsRepo.findById(entry.sessionId);
+ if (!row) continue; // The entry outlived its row (deleted mid-run): nothing to name.
+ sessions.push(await deps.sessionService.toInfo(row, await deps.sessionService.hasTrace(row)));
+ }
+ return c.json({ sessions } satisfies RunningSessionsResponse);
+ });
+
+ return app;
+}
+
/** Session-level entry point: /api/sessions/:sessionId/*. */
export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@@ -2050,6 +2088,12 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
auth: "user",
order: 255,
},
+ {
+ id: "session-api.sessions-running",
+ prefix: "/api/projects/:projectId/sessions/running",
+ auth: "user",
+ order: 256,
+ },
{
id: "session-api.usage",
prefix: "/api/projects/:projectId/usage",
@@ -2115,6 +2159,7 @@ export class SessionApiRoutes {
@Bind("session-api.vault") vaultRoutes!: Hono<AppEnv>;
@Bind("session-api.agent-sessions") agentSessionsRoutes!: Hono<AppEnv>;
@Bind("session-api.sessions-batch") sessionsBatchRoutes!: Hono<AppEnv>;
+ @Bind("session-api.sessions-running") runningSessionsRoutes!: Hono<AppEnv>;
@Bind("session-api.usage") usageRoutes!: Hono<AppEnv>;
@Bind("session-api.workspace-files") workspaceFilesRoutes!: Hono<AppEnv>;
@Bind("session-api.sessions") sessionsRoutes!: Hono<AppEnv>;
@@ -2206,7 +2251,8 @@ export class SessionApiRoutes {
});
this.agentSessionsRoutes = agentSessionsRoutes(sessionsDeps);
this.sessionsBatchRoutes = sessionsBatchRoutes(sessionsDeps);
- this.usageRoutes = usageRoutes({ access, usageService: this.usage });
+ this.runningSessionsRoutes = runningSessionsRoutes(sessionsDeps);
+ this.usageRoutes = usageRoutes({ access, usageService: this.usage, sessionsRepo });
this.workspaceFilesRoutes = workspaceFilesRoutes({
access,
workspaceFiles: this.workspaceFiles,
diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.ts
index ad4ad657..be35b9c9 100644
--- a/packages/server/src/http/routes/usage.ts
+++ b/packages/server/src/http/routes/usage.ts
@@ -23,6 +23,8 @@
* DELETE /api/projects/:p/usage/errors/ignores/:id — removes one rule (owner only; 404 when this
* Project has none);
* GET /api/projects/:p/usage/model-totals — lifetime Token total per Model, unfiltered.
+ * GET /api/projects/:p/usage/session-days?days= — usage by calendar day, each day split by
+ * Session (the account menu's run record; days 1..90, default 7).
*/
import { Hono } from "hono";
import type { Context } from "hono";
@@ -33,6 +35,7 @@ import type {
UsageErrorsClearResponse,
UsageGranularity,
UsageGroupBy,
+ UsageSessionDays,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import {
@@ -44,12 +47,15 @@ import {
} from "../validate.js";
import { HttpError } from "../errors.js";
import type { UsageQueries } from "../../mechanisms/observability.js";
+import type { SessionIndex } from "../../mechanisms/sessions.js";
import type { Access } from "../../mechanisms/projects.js";
/** What this route group reaches — bound by its module (src/modules). */
export interface UsageRouteDeps {
access: Access;
usageService: UsageQueries;
+ /** The Session index, read only to name a Session's row in the day-by-Session breakdown (it holds no title of its own). */
+ sessionsRepo: SessionIndex;
}
const GROUP_BYS: readonly UsageGroupBy[] = ["date", "agent", "model", "session"];
@@ -195,6 +201,33 @@ export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
return c.json(deps.usageService.modelTotals(projectId));
});
+ // Usage by calendar day, each day split by Session — the account menu's "会话运行记录": one
+ // request answers "which conversations spent the Tokens these days, and how much". The
+ // Sessions' titles are added here from the Session index (the usage rows carry only ids), so
+ // a reader recognises a conversation instead of decoding a session id; a Session deleted
+ // since keeps its id and no title.
+ app.get("/session-days", (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
+ const raw = c.req.query("days");
+ const parsed = raw === undefined || raw === "" ? 7 : /^\d{1,3}$/.test(raw) ? Number(raw) : NaN;
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 90) {
+ throw badRequest("days must be a whole number between 1 and 90.");
+ }
+ const titles = new Map<string, string | undefined>();
+ const days = deps.usageService.sessionDays(projectId, { days: parsed }).map((day) => ({
+ ...day,
+ sessions: day.sessions.map((row) => {
+ if (!titles.has(row.sessionId)) {
+ titles.set(row.sessionId, deps.sessionsRepo.findById(row.sessionId)?.title ?? undefined);
+ }
+ const title = titles.get(row.sessionId);
+ return { ...row, ...(title !== undefined ? { title } : {}) };
+ }),
+ }));
+ return c.json({ days } satisfies UsageSessionDays);
+ });
+
// One page of the error detail table, newest first. The dashboard response above already
// carries the first page; this serves "show me earlier ones" without refetching the whole
// aggregate. Takes the date/agent filter only — the model filter never applied to errors
diff --git a/packages/server/src/mechanisms/observability.ts b/packages/server/src/mechanisms/observability.ts
index 82b52a6a..ee60d401 100644
--- a/packages/server/src/mechanisms/observability.ts
+++ b/packages/server/src/mechanisms/observability.ts
@@ -22,6 +22,7 @@ import type {
UsageRecordInsert,
UsageSeriesGranularity,
UsageSeriesModelSums,
+ UsageSessionDaySums,
UnsettledUsageRow,
} from "../db/repos/usage.js";
import type {
@@ -32,6 +33,7 @@ import type {
UsageGroupBy,
UsageResponse,
UsageModelTotals,
+ UsageSessionDay,
} from "../api/types.js";
import type { UsageContext } from "../runtime/usage-recorder.js";
import type {
@@ -119,6 +121,7 @@ export abstract class UsageStore {
granularity: UsageSeriesGranularity,
f?: UsageFilter,
): UsageSeriesModelSums[];
+ abstract sessionDayByModel(projectId: string, f?: UsageFilter): UsageSessionDaySums[];
abstract agentSeries(
projectId: string,
granularity: UsageSeriesGranularity,
@@ -139,6 +142,13 @@ export abstract class UsageRecording {
@Interface()
export abstract class UsageQueries {
abstract query(projectId: string, q: UsageQuery): Promise<UsageResponse>;
+ /**
+ * Usage by calendar day, each day split by Session (newest day first, `days` back from
+ * today inclusive). Days with no usage are absent; today is always present, at zero when
+ * nothing ran. The rows carry no Session title — the route that serves them adds it from
+ * the Session index, which this service does not hold.
+ */
+ abstract sessionDays(projectId: string, opts?: { days?: number }): UsageSessionDay[];
abstract queryErrors(projectId: string, q: UsageErrorsQuery): UsageErrorsPage;
abstract clearErrors(projectId: string, q: UsageErrorsClearQuery): number;
abstract errorIgnores(projectId: string): UsageErrorIgnoreRule[];
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index f007eeb4..65f94ceb 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -768,6 +768,36 @@ export class SessionManager {
return this.entries.get(sessionId)?.status ?? "idle";
}
+ /**
+ * Every Session this process holds in a live state — running or compacting — across all
+ * Projects and Agents. `statusOf` answers one id at a time, and a Session nobody is looking
+ * at has no row in any client's list; the account menu's "what is running right now" asks
+ * the whole table instead, which is a walk over the entries this process already keeps.
+ */
+ liveSessions(): Array<{
+ sessionId: string;
+ projectId: string;
+ agentId: string;
+ status: SessionStatus;
+ }> {
+ const out: Array<{
+ sessionId: string;
+ projectId: string;
+ agentId: string;
+ status: SessionStatus;
+ }> = [];
+ for (const e of this.entries.values()) {
+ if (e.status === "idle") continue;
+ out.push({
+ sessionId: e.sessionId,
+ projectId: e.projectId,
+ agentId: e.agentId,
+ status: e.status,
+ });
+ }
+ return out;
+ }
+
pendingApprovalCount(sessionId: string): number {
return this.entries.get(sessionId)?.approvals.size ?? 0;
}
@@ -2554,6 +2584,7 @@ export abstract class Sessions extends Interface<
Pick<
SessionManager,
| "statusOf"
+ | "liveSessions"
| "pendingApprovalCount"
| "pendingApprovals"
| "pendingFollowUpCount"
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index 705ff958..9b90f3ca 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -30,6 +30,7 @@ import type {
UsageModelSeries,
UsageModelTotals,
UsageResponse,
+ UsageSessionDay,
UsageSeriesPoint,
} from "../api/types.js";
import type { ErrorFilter, ErrorIgnoreRule } from "../db/repos/errors.js";
@@ -538,6 +539,87 @@ export class UsageService implements UsageQueries {
};
}
+ /**
+ * Usage by calendar day, each day split by Session — the account menu's "会话运行记录":
+ * which conversations spent the Tokens, day by day. One grouped scan over the last `days`
+ * calendar days (today included), folded here into days and Sessions; both levels sum the
+ * same rows, so a day's figure is the sum of its Sessions' and the window's is the sum of
+ * the days'.
+ *
+ * Days with no records are left out rather than drawn as zeros — a day nobody used the app
+ * is not a row worth reading — but today is always answered, at zero when nothing has run,
+ * because "今天花了多少" is the one figure the list is opened for. Within a day, Sessions
+ * are ordered by Token total, descending.
+ */
+ sessionDays(projectId: string, opts: { days?: number } = {}): UsageSessionDay[] {
+ const days = Math.min(Math.max(opts.days ?? 7, 1), 90);
+ const now = this.clock.now();
+ const today = formatLocalDate(now);
+ const rows = this.usage.sessionDayByModel(projectId, {
+ from: localDateMinusDays(now, days - 1),
+ to: today,
+ });
+ const byDate = new Map<string, UsageSessionDay>();
+ for (const r of rows) {
+ let day = byDate.get(r.date);
+ if (!day) {
+ day = {
+ date: r.date,
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ requests: 0,
+ cost: null,
+ hasUncosted: false,
+ sessions: [],
+ };
+ byDate.set(r.date, day);
+ }
+ let session = day.sessions.find((s) => s.sessionId === r.sessionId);
+ if (!session) {
+ session = {
+ sessionId: r.sessionId,
+ agentId: r.agentId,
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ requests: 0,
+ cost: null,
+ hasUncosted: false,
+ };
+ day.sessions.push(session);
+ }
+ for (const target of [day, session]) {
+ target.cacheRead += r.cacheRead;
+ target.cacheWrite += r.cacheWrite;
+ target.output += r.output;
+ target.total += r.total;
+ target.requests += r.requests;
+ if (r.cost !== null) target.cost = (target.cost ?? 0) + r.cost;
+ if (r.uncosted > 0) target.hasUncosted = true;
+ }
+ }
+ const out = [...byDate.values()];
+ for (const day of out) day.sessions.sort((a, b) => b.total - a.total);
+ out.sort((a, b) => b.date.localeCompare(a.date));
+ if (!byDate.has(today)) {
+ out.unshift({
+ date: today,
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ requests: 0,
+ cost: null,
+ hasUncosted: false,
+ sessions: [],
+ });
+ }
+ return out;
+ }
+
/**
* The Project's lifetime cost — one unfiltered grouped scan, the same one `modelTotals` runs,
* summing the costs fixed when the rows were written. Its consumer is a per-account figure
diff --git a/packages/server/test/session-running.test.ts b/packages/server/test/session-running.test.ts
new file mode 100644
index 00000000..2e62c238
--- /dev/null
+++ b/packages/server/test/session-running.test.ts
@@ -0,0 +1,124 @@
+/**
+ * `GET /api/projects/:projectId/sessions/running` — the account menu's "what is running now".
+ *
+ * The route is the join of two things the shell already keeps apart: the runtime's own table
+ * (every live Session this process holds, across Agents) and the Session index (the row that
+ * names one). So the test mounts the route on a bare Hono app with those two faked, and checks
+ * what the endpoint promises:
+ *
+ * - only the Project's own Sessions come back, whatever else is live on the server;
+ * - running sorts before compacting (a run is the thing to report first);
+ * - a Session whose row is gone is skipped rather than served as a nameless row;
+ * - each answer is a whole row (title, Agent, Workspace, live status), not just an id.
+ */
+import { Hono } from "hono";
+import { describe, expect, it } from "vitest";
+import type { SessionInfo } from "../src/api/types.js";
+import type { AppEnv } from "../src/auth/middleware.js";
+import type { UserRow } from "../src/db/repos/users.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import { runningSessionsRoutes } from "../src/http/routes/sessions.js";
+import type { SessionsRouteDeps } from "../src/http/routes/sessions.js";
+
+type Live = {
+ sessionId: string;
+ projectId: string;
+ agentId: string;
+ status: "running" | "compacting";
+};
+
+function row(sessionId: string, projectId: string, agentId: string): SessionRow {
+ return {
+ sessionId,
+ projectId,
+ agentId,
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ title: `title of ${sessionId}`,
+ createdAt: "2026-11-13T00:00:00.000Z",
+ lastActiveAt: "2026-11-13T00:00:00.000Z",
+ archivedAt: null,
+ client: "web",
+ } as unknown as SessionRow;
+}
+
+function info(r: SessionRow, status: "running" | "compacting"): SessionInfo {
+ return {
+ sessionId: r.sessionId,
+ projectId: r.projectId,
+ agentId: r.agentId,
+ provider: r.provider,
+ modelId: r.modelId,
+ workspace: r.workspace,
+ approvalMode: r.approvalMode,
+ sandbox: {} as SessionInfo["sandbox"],
+ title: r.title ?? undefined,
+ createdAt: r.createdAt,
+ lastActiveAt: r.lastActiveAt,
+ status,
+ hasTrace: true,
+ archived: false,
+ } as SessionInfo;
+}
+
+/** The whole app the route needs: a user on the context and the seven deps it reads. */
+function appFor(live: Live[], rows: SessionRow[]): Hono<AppEnv> {
+ const byId = new Map(rows.map((r) => [r.sessionId, r]));
+ const deps = {
+ access: { requireProjectAccess: () => undefined },
+ manager: { liveSessions: () => live },
+ sessionsRepo: { findById: (id: string) => byId.get(id) ?? null },
+ sessionService: {
+ hasTrace: async () => true,
+ toInfo: async (r: SessionRow) =>
+ info(r, live.find((l) => l.sessionId === r.sessionId)!.status),
+ },
+ } as unknown as SessionsRouteDeps;
+ const app = new Hono<AppEnv>();
+ app.use("*", async (c, next) => {
+ c.set("user", { userId: "u1" } as UserRow);
+ await next();
+ });
+ app.route("/api/projects/:projectId/sessions/running", runningSessionsRoutes(deps));
+ return app;
+}
+
+describe("GET /sessions/running", () => {
+ it("answers this Project's live Sessions as whole rows, running before compacting", async () => {
+ const live: Live[] = [
+ { sessionId: "s2", projectId: "p1", agentId: "a1", status: "compacting" },
+ { sessionId: "s1", projectId: "p1", agentId: "a2", status: "running" },
+ // Another Project's run, live on the same server: not this answer's business.
+ { sessionId: "s9", projectId: "p2", agentId: "a1", status: "running" },
+ ];
+ const res = await appFor(live, [row("s1", "p1", "a2"), row("s2", "p1", "a1")]).request(
+ "/api/projects/p1/sessions/running",
+ );
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { sessions: SessionInfo[] };
+ expect(body.sessions.map((s) => [s.sessionId, s.status])).toEqual([
+ ["s1", "running"],
+ ["s2", "compacting"],
+ ]);
+ expect(body.sessions[0]).toMatchObject({
+ title: "title of s1",
+ agentId: "a2",
+ workspace: "/tmp/w",
+ });
+ });
+
+ it("skips a live Session the index no longer holds", async () => {
+ const live: Live[] = [{ sessionId: "gone", projectId: "p1", agentId: "a1", status: "running" }];
+ const res = await appFor(live, []).request("/api/projects/p1/sessions/running");
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { sessions: SessionInfo[] }).sessions).toEqual([]);
+ });
+
+ it("answers an empty list when nothing is running", async () => {
+ const res = await appFor([], []).request("/api/projects/p1/sessions/running");
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { sessions: SessionInfo[] }).sessions).toEqual([]);
+ });
+});
diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts
index b407ca06..3f518a36 100644
--- a/packages/server/test/usage.test.ts
+++ b/packages/server/test/usage.test.ts
@@ -542,6 +542,89 @@ describe("usage-service model totals (unfiltered, for the models page)", () => {
});
});
+describe("usage-service sessionDays (day x Session breakdown)", () => {
+ let db: DatabaseSync;
+ let repo: UsageRepo;
+ const NOW = new Date("2026-08-20T10:00:00");
+ let service: UsageService;
+
+ beforeEach(() => {
+ db = openDatabase(":memory:");
+ repo = wire(UsageRepo, { db: db });
+ service = wire(UsageService, {
+ usage: repo,
+ errors: wire(ErrorsRepo, { db: db }),
+ lookupPricing: async () => undefined,
+ clock: { now: () => NOW },
+ });
+ });
+ afterEach(() => db.close());
+
+ function insert(date: string, opts: Partial<Parameters<UsageRepo["insert"]>[0]> = {}): void {
+ repo.insert({
+ cost: 0.001,
+ ts: `${date}T00:00:00.000Z`,
+ date,
+ projectId: "p1",
+ agentId: "a1",
+ sessionId: "s1",
+ originSessionId: null,
+ modelId: "m1",
+ provider: "custom",
+ cacheRead: 10,
+ cacheWrite: 1,
+ output: 5,
+ total: 100,
+ ...opts,
+ });
+ }
+
+ it("splits each day by Session, newest day first, with a day's figure the sum of its rows", () => {
+ insert("2026-08-20", { sessionId: "s1", total: 100 });
+ insert("2026-08-20", { sessionId: "s1", total: 100, modelId: "m2" });
+ insert("2026-08-20", { sessionId: "s2", total: 300, agentId: "a2" });
+ insert("2026-08-18", { sessionId: "s1", total: 50 });
+ const days = service.sessionDays("p1", { days: 7 });
+ // One row per (day, Session, model) folds into one row per (day, Session).
+ expect(days.map((d) => d.date)).toEqual(["2026-08-20", "2026-08-18"]);
+ const [today, older] = days as [(typeof days)[number], (typeof days)[number]];
+ expect(today.total).toBe(500);
+ expect(today.requests).toBe(3);
+ expect(today.cost).toBeCloseTo(0.003, 12);
+ // Sessions ordered by Token total, descending.
+ expect(today.sessions.map((s) => [s.sessionId, s.total, s.agentId])).toEqual([
+ ["s2", 300, "a2"],
+ ["s1", 200, "a1"],
+ ]);
+ expect(older.total).toBe(50);
+ });
+
+ it("leaves empty days out but always answers today — at zero when nothing ran", () => {
+ insert("2026-08-18");
+ const days = service.sessionDays("p1", { days: 7 });
+ expect(days.map((d) => d.date)).toEqual(["2026-08-20", "2026-08-18"]);
+ expect(days[0]).toMatchObject({ total: 0, requests: 0, cost: null, sessions: [] });
+ });
+
+ it("is scoped to the window and the Project", () => {
+ insert("2026-08-20");
+ insert("2026-08-13"); // eight days back: outside a 7-day window
+ insert("2026-08-20", { projectId: "p2" });
+ const days = service.sessionDays("p1", { days: 7 });
+ expect(days.map((d) => d.date)).toEqual(["2026-08-20"]);
+ expect(days[0]?.total).toBe(100);
+ });
+
+ it("flags a Session whose Requests ran on an unpriced Model", () => {
+ insert("2026-08-20", { cost: null });
+ insert("2026-08-20", { cost: 0.002 });
+ const [today] = service.sessionDays("p1", { days: 7 });
+ expect(today?.hasUncosted).toBe(true);
+ expect(today?.cost).toBeCloseTo(0.002, 12);
+ expect(today?.sessions[0]?.hasUncosted).toBe(true);
+ });
+});
+
describe("usage-service series (zero-filled time-series buckets)", () => {
let db: DatabaseSync;
let repo: UsageRepo;
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 86a0ac78..79b63816 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -141,6 +141,9 @@ import type {
UsageGroupBy,
UsageModelTotals,
UsageResponse,
+ UsageSessionDay,
+ UsageSessionDays,
+ RunningSessionsResponse,
UserInfo,
VaultResponse,
VersionHistoryResponse,
@@ -1349,6 +1352,14 @@ router
offset: Number(query.get("offset")) || 0,
});
})
+ // The account menu's "what is running now": the demo's live Sessions (four of them run in
+ // the fixtures), running first, matching the real route's ordering rule.
+ .get("/api/projects/:projectId/sessions/running", ({ store }): RunningSessionsResponse => ({
+ sessions: [
+ ...store.f.sessions.filter((s) => s.status === "running"),
+ ...store.f.sessions.filter((s) => s.status === "compacting"),
+ ],
+ }))
// The sidebar's whole reload in one request: each entry answered as the GET route would,
// and an Agent the demo does not have is an answer about that Agent (`absent`), never a
// failure of the batch.
@@ -1996,6 +2007,72 @@ router
}
return { totals: [...totals.values()] };
})
+ // Usage by day, split by Session (the account menu's run record). The fixtures are daily
+ // rows that already name their Session, so this folds the same rows the cost center reads;
+ // today is always answered, at zero when nothing ran.
+ .get("/api/projects/:projectId/usage/session-days", ({ store, query }): UsageSessionDays => {
+ const days = Number(query.get("days") ?? "7");
+ if (!Number.isInteger(days) || days < 1 || days > 90) {
+ fail(400, "bad_request", "days must be a whole number between 1 and 90.");
+ }
+ const today = dayKey(store.f.now);
+ const from = dayKey(store.f.now - (days - 1) * 86_400_000);
+ const byDate = new Map<string, UsageSessionDay>();
+ for (const row of store.f.usage) {
+ if (row.date < from || row.date > today) continue;
+ const day = byDate.get(row.date) ?? {
+ date: row.date,
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ requests: 0,
+ cost: 0,
+ hasUncosted: false,
+ sessions: [],
+ };
+ const title = store.f.sessions.find((s) => s.sessionId === row.sessionId)?.title;
+ const session = day.sessions.find((s) => s.sessionId === row.sessionId) ?? {
+ sessionId: row.sessionId,
+ agentId: row.agentId,
+ ...(title !== undefined ? { title } : {}),
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ requests: 0,
+ cost: 0,
+ hasUncosted: false,
+ };
+ if (!day.sessions.includes(session)) day.sessions.push(session);
+ for (const target of [day, session]) {
+ target.cacheRead += row.cacheRead;
+ target.cacheWrite += row.cacheWrite;
+ target.output += row.output;
+ target.total += row.cacheRead + row.cacheWrite + row.output;
+ target.requests += row.requests;
+ target.cost = (target.cost ?? 0) + costOf(row);
+ }
+ byDate.set(row.date, day);
+ }
+ const out = [...byDate.values()];
+ for (const day of out) day.sessions.sort((a, b) => b.total - a.total);
+ out.sort((a, b) => b.date.localeCompare(a.date));
+ if (!byDate.has(today)) {
+ out.unshift({
+ date: today,
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ requests: 0,
+ cost: 0,
+ hasUncosted: false,
+ sessions: [],
+ });
+ }
+ return { days: out };
+ })
.get("/api/projects/:projectId/usage", ({ store, query }): UsageResponse => {
const groupBy = (query.get("groupBy") ?? "date") as UsageGroupBy;
const granularity = (query.get("granularity") ?? "day") as UsageGranularity;
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 5c10a25d..adce8d9a 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -253,6 +253,8 @@ import type {
UsageGroupBy,
UsageModelTotals,
UsageResponse,
+ UsageSessionDays,
+ RunningSessionsResponse,
VaultResponse,
VaultUpdateRequest,
UserVaultAssignRequest,
@@ -1644,6 +1646,26 @@ export const unignoreUsageErrors = (projectId: string, id: number) =>
export const getUsageModelTotals = (projectId: string) =>
apiFetch<UsageModelTotals>(`/api/projects/${encodeURIComponent(projectId)}/usage/model-totals`);
+/**
+ * Usage by calendar day, each day split by Session — the account menu's run record. One request
+ * for the whole list: the Sessions are named server-side (titles included), so the dialog needs
+ * no follow-up lookup for a conversation the sidebar has not loaded.
+ */
+export const getUsageSessionDays = (projectId: string, days: number) =>
+ apiFetch<UsageSessionDays>(`/api/projects/${encodeURIComponent(projectId)}/usage/session-days`, {
+ query: { days },
+ });
+
+/**
+ * The Sessions this server is running right now in this Project. One project-level read rather
+ * than a per-Agent list filter: the account menu asks "what is running anywhere", and the
+ * sidebar's paged lists cannot answer it for a group nobody expanded.
+ */
+export const getRunningSessions = (projectId: string) =>
+ apiFetch<RunningSessionsResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/sessions/running`,
+ );
+
export const getUsage = (
projectId: string,
params: {
diff --git a/packages/web/src/components/layout/user-menu.tsx b/packages/web/src/components/layout/user-menu.tsx
index 55801401..4fceba39 100644
--- a/packages/web/src/components/layout/user-menu.tsx
+++ b/packages/web/src/components/layout/user-menu.tsx
@@ -8,6 +8,13 @@
* Only the trigger differs, so the trigger is the caller's: it is handed the menu's own open
* state, which is what keeps "what opening means" here rather than in two places.
*
+ * The menu also answers the two questions the rest of the shell leaves unanswered, because the
+ * footer is where a user looks when something is "going on somewhere": what is running right
+ * now (the project-level list at the top, live from the user channel — see
+ * features/account/running-sessions.ts), and what the recent conversations cost (the run log
+ * dialog behind its own row). Both are the Project's, not this account's: they name work the
+ * user started from anywhere.
+ *
* The dialogs are mounted OUTSIDE the panel: the panel's children unmount the moment the menu
* closes, and a row closes the menu as it opens its dialog.
*
@@ -15,21 +22,35 @@
* it once a nickname stands in for it. Both anchors are avatars, and the rail's is nothing but
* an avatar, so without the header the menu never says whose account its rows act on.
*/
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import type { ReactNode } from "react";
import { useNavigate } from "react-router";
-import { ConfirmModal, Dropdown, ICON_GAP, Menu, MenuItem, UserAvatar } from "@adelie/ui";
+import {
+ ActivityIcon,
+ ConfirmModal,
+ Dropdown,
+ ICON_GAP,
+ Menu,
+ MenuItem,
+ MenuLabel,
+ MenuSeparator,
+ UserAvatar,
+} from "@adelie/ui";
import type { DropdownPortal } from "@adelie/ui";
import { S } from "../../lib/strings";
import { useAuth } from "../../state/auth";
import { UpdateRow } from "../account/update-row";
import { UserVaultDialog } from "../account/user-vault-dialog";
+import { SessionLogDialog } from "../../features/account/session-log-dialog";
+import { useRunningSessions } from "../../features/account/running-sessions";
import { FeedbackDialog, useFeedbackChannel } from "../account/feedback-dialog";
import { openFeedbackBoard } from "../../lib/feedback-board";
import { openUpdateModal } from "../../lib/use-update-flow";
import { SettingsDialog } from "../../features/settings/settings-dialog";
import { onSettingsRequest } from "../../features/settings/settings-request";
import type { SettingsSectionKey } from "../../lib/settings-sections";
+import { agentDisplayName, useProject } from "../../state/project";
+import { workspaceLabel } from "../../lib/session-grouping";
export function UserMenu({
trigger,
@@ -54,16 +75,26 @@ export function UserMenu({
}) {
const navigate = useNavigate();
const { user, logout, desktopMode } = useAuth();
+ const { agents, setCurrentAgentId } = useProject();
const [open, setOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
/** The account's own global secrets, the one row here that edits data rather than navigating. */
const [vaultOpen, setVaultOpen] = useState(false);
+ /** The per-conversation usage dialog; mounted outside the panel like the rest. */
+ const [logOpen, setLogOpen] = useState(false);
/** The page a request asked for; the menu's own row asks for none (the viewer's first). */
const [settingsSection, setSettingsSection] = useState<SettingsSectionKey | undefined>(undefined);
const [confirmingLogout, setConfirmingLogout] = useState(false);
/** The feedback row and its dialog; both live here because the row sits inside the panel and
* the dialog must outlive it. */
const feedback = useFeedbackChannel();
+ /** What is running right now, fetched on open and kept in step by the user channel. */
+ const { sessions: running } = useRunningSessions(open);
+ const agentNames = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const a of agents) map.set(a.agentId, agentDisplayName(a));
+ return map;
+ }, [agents]);
// Settings can be asked for from outside this menu (see settings-request.ts): the request
// opens the same dialog, on the page it names.
@@ -115,6 +146,53 @@ export function UserMenu({
section registry rather than by this row. The preference rows that used to
stack here live on its pages now. */}
<Menu>
+ {/* What is running right now, above the navigation rows: this is the one part of the
+ panel that changes without anyone pressing anything, and the empty line is an
+ answer too ("nothing is running"). A row opens its conversation — the Agent
+ follows the Session, the same way the sidebar's own cross-group click does. The
+ list scrolls rather than pushing the rows below it out of the panel. */}
+ <MenuLabel>{S.account.running.title}</MenuLabel>
+ {running.length === 0 ? (
+ <div role="presentation" className="px-3.5 pb-1.5 text-xs text-fg-muted">
+ {S.account.running.empty}
+ </div>
+ ) : (
+ <div role="presentation" className="max-h-48 overflow-y-auto">
+ {running.map((s) => (
+ <MenuItem
+ key={s.sessionId}
+ glyph={
+ <ActivityIcon
+ activity={s.status === "compacting" ? "compacting" : "running"}
+ label={
+ s.status === "compacting" ? S.chat.statusCompacting : S.chat.statusRunning
+ }
+ />
+ }
+ label={s.title ?? S.account.running.untitled}
+ description={`${agentNames.get(s.agentId) ?? s.agentId} · ${workspaceLabel(s.workspace)}`}
+ trailing={
+ s.status === "compacting" ? S.chat.statusCompacting : S.chat.statusRunning
+ }
+ onSelect={() => {
+ setOpen(false);
+ setCurrentAgentId(s.agentId);
+ navigate(`/chat/${s.sessionId}`);
+ }}
+ />
+ ))}
+ </div>
+ )}
+ {/* The run record, right under the live list it explains: days of usage, split by
+ conversation, in a dialog mounted outside this panel. */}
+ <MenuSeparator />
+ <MenuItem
+ label={S.account.sessionLog.row}
+ onSelect={() => {
+ setOpen(false);
+ setLogOpen(true);
+ }}
+ />
<MenuItem
label={S.settings.title}
onSelect={() => {
@@ -204,6 +282,9 @@ export function UserMenu({
{/* The account's own secrets, mounted here like the settings dialog so it outlives the
menu that opened it. */}
<UserVaultDialog open={vaultOpen} onClose={() => setVaultOpen(false)} />
+ {/* The run record, likewise outside the panel — and it survives its own row's menu
+ closing, which is the point of mounting it here. */}
+ <SessionLogDialog open={logOpen} onClose={() => setLogOpen(false)} />
{/* Feedback, likewise outside the panel: its row closes the menu as it opens this. */}
<FeedbackDialog open={feedback.open} onClose={() => feedback.setOpen(false)} />
{/* Signing out is confirmed first: the row sits in a menu of harmless entries, and a
diff --git a/packages/web/src/features/account/running-sessions.ts b/packages/web/src/features/account/running-sessions.ts
new file mode 100644
index 00000000..66267e11
--- /dev/null
+++ b/packages/web/src/features/account/running-sessions.ts
@@ -0,0 +1,96 @@
+/**
+ * "What is running right now" for the account menu: the Project's live Sessions, fetched as a
+ * whole when the menu opens and kept in step with the user channel while it stays open.
+ *
+ * The sidebar's own lists cannot answer this. They are paged per Agent and category, so a
+ * conversation running inside a group nobody expanded — or an archived one — has no row on
+ * screen, and asking every Agent's list would be a fan-out per render. One project-level read
+ * (`GET /sessions/running`) walks the runtime's table instead.
+ *
+ * No timer runs here. The page already follows every `session_state` on the user channel
+ * (`liveStatuses` in state/sessions.tsx), which is what reports a run starting, compacting and
+ * ENDING; the fetch is re-issued only when that live set stops agreeing with what was fetched,
+ * and a row whose Session reports itself idle is dropped immediately rather than at the next
+ * fetch. Closed menu, no requests and no work.
+ */
+import { useEffect, useMemo, useState } from "react";
+import type { SessionInfo, SessionStatus } from "@adelie/server/api";
+import * as api from "../../api/endpoints";
+import { useProject } from "../../state/project";
+import { useSessions } from "../../state/sessions";
+
+/**
+ * The fetched rows with the live status applied: a Session the channel has moved to `idle` is
+ * gone (the fetch is older than that news), and one it reports running/compacting says so even
+ * if the fetch predates the change. Pure, so the merge is testable without a React tree.
+ */
+export function mergeRunningSessions(
+ fetched: readonly SessionInfo[],
+ live: ReadonlyMap<string, SessionStatus>,
+): SessionInfo[] {
+ return fetched
+ .map((session) => {
+ const status = live.get(session.sessionId);
+ return status === undefined ? session : { ...session, status };
+ })
+ .filter((session) => session.status !== "idle");
+}
+
+/**
+ * The key that says "the live set moved": every Session the channel reports as running or
+ * compacting, with its status. A run ending is deliberately not in it — that only removes a
+ * row, which the merge does by itself; a new run or a compaction starting needs the row's
+ * title, which only a fetch can bring.
+ */
+function liveRunningKey(live: ReadonlyMap<string, SessionStatus>): string {
+ const parts: string[] = [];
+ for (const [sessionId, status] of live) {
+ if (status !== "idle") parts.push(`${sessionId}:${status}`);
+ }
+ return parts.sort().join("|");
+}
+
+/** The Project's live Sessions while `open`; the last answer is kept across refetches. */
+export function useRunningSessions(open: boolean): {
+ sessions: SessionInfo[];
+ loading: boolean;
+} {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+ const { liveStatuses } = useSessions();
+ const [fetched, setFetched] = useState<SessionInfo[] | null>(null);
+ const [loading, setLoading] = useState(false);
+ const key = useMemo(() => liveRunningKey(liveStatuses), [liveStatuses]);
+
+ useEffect(() => {
+ if (!open || projectId === null) return;
+ let cancelled = false;
+ setLoading(true);
+ api
+ .getRunningSessions(projectId)
+ .then((res) => {
+ if (!cancelled) setFetched(res.sessions);
+ })
+ // A failed read leaves the last list on screen: the menu is a glance, not a report, and
+ // the next event (or the next open) asks again.
+ .catch(() => undefined)
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, projectId, key]);
+
+ // A Project switch answers nothing about the new one until its fetch lands: the old rows
+ // would name Sessions the menu is no longer about.
+ useEffect(() => {
+ setFetched(null);
+ }, [projectId]);
+
+ const sessions = useMemo(
+ () => mergeRunningSessions(fetched ?? [], liveStatuses),
+ [fetched, liveStatuses],
+ );
+ return { sessions, loading };
+}
diff --git a/packages/web/src/features/account/session-log-dialog.tsx b/packages/web/src/features/account/session-log-dialog.tsx
new file mode 100644
index 00000000..fc03a696
--- /dev/null
+++ b/packages/web/src/features/account/session-log-dialog.tsx
@@ -0,0 +1,223 @@
+/**
+ * The account menu's run record: usage by day, each day split by Session — "which
+ * conversations spent the Tokens this week".
+ *
+ * One request answers the whole dialog (`GET /sessions/usage/session-days`): the days arrive
+ * newest first with each day's Sessions already named (title and Agent), so a day opens with no
+ * second round trip and a conversation the sidebar never loaded is still recognisable. The
+ * cost center answers the same question by Agent and Model; this is the per-conversation view
+ * the account menu needs, in the one place the user looks before asking "what did I spend
+ * today".
+ *
+ * Today's total is read off the head of the list rather than computed separately: the server
+ * always answers today (at zero when nothing ran), so the figure is the same sum the day's row
+ * shows.
+ */
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { UsageSessionDay, UsageSessionDays } from "@adelie/server/api";
+import { Button, Modal, SettingsEmpty, SkeletonList } from "@adelie/ui";
+import * as api from "../../api/endpoints";
+import { Truncated } from "../../components/ui/truncated";
+import { apiErrorText } from "../../lib/api-error";
+import { formatMoney, formatMonthDay, humanizeTokens, localYmd } from "../../lib/format";
+import { S } from "../../lib/strings";
+import { useLocale } from "../../state/locale";
+import { agentDisplayName, useProject } from "../../state/project";
+import { useTheme } from "../../state/theme";
+
+/** The two windows the dialog offers; the server takes 1..90. */
+const RANGES = [7, 30] as const;
+
+export function SessionLogDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
+ const { currentProject, agents } = useProject();
+ const { currency } = useTheme();
+ const { locale } = useLocale();
+ const [days, setDays] = useState<number>(RANGES[0]);
+ const [data, setData] = useState<UsageSessionDays | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
+ /** The day whose Sessions are open under it; one at a time keeps the dialog short. */
+ const [expanded, setExpanded] = useState<string | null>(null);
+
+ const projectId = currentProject?.projectId ?? null;
+
+ const load = useCallback(async () => {
+ if (projectId === null) return;
+ setLoading(true);
+ setError(null);
+ try {
+ setData(await api.getUsageSessionDays(projectId, days));
+ } catch (e) {
+ setError(apiErrorText(e));
+ } finally {
+ setLoading(false);
+ }
+ }, [projectId, days]);
+
+ // Read on every open and whenever the window changes: the numbers move while the dialog is
+ // closed, and the request is one grouped scan.
+ useEffect(() => {
+ if (open) void load();
+ }, [open, load]);
+
+ // Opening lands on today with nothing unfolded, whatever the previous visit left open.
+ useEffect(() => {
+ if (open) setExpanded(null);
+ }, [open]);
+
+ const agentNames = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const a of agents) map.set(a.agentId, agentDisplayName(a));
+ return map;
+ }, [agents]);
+
+ const today = localYmd(new Date());
+ const todayRow = data?.days.find((d) => d.date === today) ?? null;
+
+ const dayLabel = (date: string): string => {
+ if (date === today) return S.account.sessionLog.today;
+ return formatMonthDay(date, locale);
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.account.sessionLog.title}
+ onClose={onClose}
+ widthClass="sm:max-w-2xl"
+ footer={
+ <Button size="sm" onClick={onClose}>
+ {S.common.close}
+ </Button>
+ }
+ >
+ <div className="space-y-3">
+ <p className="text-sm text-fg-muted">{S.account.sessionLog.desc}</p>
+
+ {/* Today's total, before the days: the one figure the dialog is opened for. */}
+ <div className="flex items-baseline justify-between rounded-lg border border-line bg-surface px-3 py-2">
+ <span className="text-sm font-medium">{S.account.sessionLog.today}</span>
+ <span className="flex items-baseline gap-3 font-mono text-sm">
+ <span>
+ {humanizeTokens(todayRow?.total ?? 0)}{" "}
+ <span className="text-xs text-fg-muted">{S.account.sessionLog.tokens}</span>
+ </span>
+ <span>{formatMoney(todayRow?.cost ?? null, currency)}</span>
+ <span>
+ {todayRow?.requests ?? 0}{" "}
+ <span className="text-xs text-fg-muted">{S.account.sessionLog.requests}</span>
+ </span>
+ </span>
+ </div>
+
+ {/* Window switch: two windows are enough to answer "today / this week" and "this month". */}
+ <div className="flex items-center gap-1.5">
+ {RANGES.map((r) => (
+ <Button
+ key={r}
+ size="sm"
+ variant={days === r ? "primary" : "secondary"}
+ onClick={() => setDays(r)}
+ >
+ {S.account.sessionLog.range(r)}
+ </Button>
+ ))}
+ </div>
+
+ {error !== null && (
+ <p className="text-sm text-red-600 dark:text-red-400">
+ {S.account.sessionLog.loadFailed(error)}
+ </p>
+ )}
+
+ {data === null && loading && <SkeletonList rows={4} />}
+
+ {data !== null && data.days.length === 0 && (
+ <SettingsEmpty>{S.account.sessionLog.empty}</SettingsEmpty>
+ )}
+
+ {data !== null && data.days.length > 0 && (
+ <ul className="space-y-2">
+ {data.days.map((day) => (
+ <li key={day.date} className="rounded-lg border border-line">
+ <button
+ type="button"
+ onClick={() => setExpanded(expanded === day.date ? null : day.date)}
+ aria-expanded={expanded === day.date}
+ className="flex w-full items-baseline justify-between gap-3 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/40"
+ >
+ <span className="text-sm font-medium">{dayLabel(day.date)}</span>
+ <span className="flex items-baseline gap-3 font-mono text-xs text-fg-muted">
+ <span>
+ {humanizeTokens(day.total)} {S.account.sessionLog.tokens}
+ </span>
+ <span>{formatMoney(day.cost, currency)}</span>
+ <span>
+ {day.requests} {S.account.sessionLog.requests}
+ </span>
+ <span>{S.account.sessionLog.sessions(day.sessions.length)}</span>
+ </span>
+ </button>
+ {expanded === day.date && (
+ <div className="border-t border-line px-3 py-1">
+ {day.sessions.length === 0 ? (
+ <p className="py-2 text-xs text-fg-muted">{S.account.sessionLog.emptyDay}</p>
+ ) : (
+ <ul>
+ {day.sessions.map((session) => (
+ <SessionRow
+ key={session.sessionId}
+ session={session}
+ agentName={agentNames.get(session.agentId) ?? session.agentId}
+ currency={currency}
+ />
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </Modal>
+ );
+}
+
+/** One conversation inside an unfolded day: its title, its Agent, and what it spent. */
+function SessionRow({
+ session,
+ agentName,
+ currency,
+}: {
+ session: UsageSessionDay["sessions"][number];
+ agentName: string;
+ currency: "USD" | "CNY";
+}) {
+ return (
+ <li className="flex items-baseline justify-between gap-3 border-b border-line py-1.5 last:border-b-0">
+ <span className="min-w-0">
+ <Truncated
+ text={session.title ?? `${S.account.sessionLog.unknownSession} ${session.sessionId}`}
+ className="block text-sm"
+ />
+ <span className="block truncate text-xs text-fg-muted">{agentName}</span>
+ </span>
+ <span className="flex shrink-0 items-baseline gap-3 font-mono text-xs text-fg-muted">
+ <span>
+ {humanizeTokens(session.total)} {S.account.sessionLog.tokens}
+ </span>
+ <span>
+ {formatMoney(session.cost, currency)}
+ {session.hasUncosted ? ` · ${S.account.sessionLog.unpriced}` : ""}
+ </span>
+ <span>
+ {session.requests} {S.account.sessionLog.requests}
+ </span>
+ </span>
+ </li>
+ );
+}
+
+/** A day's heading: "今天" for today, else the localized month and day of that calendar date. */
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 254d3e9e..e07d05d2 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1489,6 +1489,36 @@ export const en: Strings = {
overwriteConfirm: (key: string): string =>
`"${key}" already exists — saving will overwrite its value, which cannot be recovered.`,
},
+ /**
+ * The account menu's live block: which conversations are running at this very moment. The
+ * rows sit above the account's own rows (they change without anyone pressing anything), and
+ * the empty line matters — "nothing is running" is an answer, not a gap.
+ */
+ running: {
+ title: "Running now",
+ empty: "No conversation is running",
+ untitled: "Untitled conversation",
+ },
+ /**
+ * The account menu's run record: usage by day, each day split by Session.
+ */
+ sessionLog: {
+ row: "Session run log",
+ title: "Session run log",
+ desc: "Usage for the last few days — one row per day, and expanding it shows the Tokens, cost and Requests of each conversation.",
+ today: "Today",
+ yesterday: "Yesterday",
+ range: (days: number): string => `Last ${days} days`,
+ tokens: "Tokens",
+ cost: "Cost",
+ requests: "Requests",
+ sessions: (n: number): string => (n === 1 ? "1 conversation" : `${n} conversations`),
+ emptyDay: "No usage recorded on this day",
+ empty: "No usage recorded recently",
+ loadFailed: (reason: string): string => `Could not load: ${reason}`,
+ unknownSession: "Deleted conversation",
+ unpriced: "unpriced",
+ },
},
/**
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 6337eb6e..40f625e5 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1538,6 +1538,38 @@ export const zh = {
overwriteTitle: "覆盖已有全局密钥",
overwriteConfirm: (key: string): string => `「${key}」已存在,保存将覆盖原值且不可恢复。`,
},
+ /**
+ * The account menu's live block: which conversations are running at this very moment. The
+ * rows sit above the account's own rows (they change without anyone pressing anything), and
+ * the empty line matters — "nothing is running" is an answer, not a gap.
+ */
+ running: {
+ title: "正在运行",
+ empty: "没有正在运行的会话",
+ untitled: "未命名会话",
+ },
+ /**
+ * The account menu's run record: usage by day, each day split by Session. The copy names
+ * what a row shows, because the dialog is reached from a menu of pages and has no other
+ * introduction.
+ */
+ sessionLog: {
+ row: "会话运行记录",
+ title: "会话运行记录",
+ desc: "最近几天的用量:每天合计一行,展开能看到每个会话花了多少 Token、多少钱、多少次请求。",
+ today: "今天",
+ yesterday: "昨天",
+ range: (days: number): string => `最近 ${days} 天`,
+ tokens: "Token",
+ cost: "费用",
+ requests: "请求",
+ sessions: (n: number): string => `${n} 个会话`,
+ emptyDay: "这一天没有用量记录",
+ empty: "最近还没有用量记录",
+ loadFailed: (reason: string): string => `读取失败:${reason}`,
+ unknownSession: "已删除的会话",
+ unpriced: "未计价",
+ },
},
/**
diff --git a/packages/web/test/running-sessions.test.ts b/packages/web/test/running-sessions.test.ts
new file mode 100644
index 00000000..71c58e45
--- /dev/null
+++ b/packages/web/test/running-sessions.test.ts
@@ -0,0 +1,58 @@
+/**
+ * The account menu's "running now" merge (features/account/running-sessions.ts): the rows a
+ * project-level fetch brought, reconciled with the live statuses the user channel reports.
+ *
+ * - A Session the channel has moved to another live status says the newer one.
+ * - A Session the channel reports idle is dropped, even though the fetch still lists it: the
+ * fetch is older than that news, and a "running" row for a finished run is the one lie this
+ * list must not tell.
+ * - A Session the channel has never named keeps the status its row carried.
+ * - Order is the fetch's (running first, most recently active first): the merge only relabels
+ * and drops, so a refetch is the only thing that can reorder.
+ */
+import { describe, expect, it } from "vitest";
+import type { SessionInfo, SessionStatus } from "@adelie/server/api";
+import { mergeRunningSessions } from "../src/features/account/running-sessions";
+
+function row(sessionId: string, status: SessionStatus, title = sessionId): SessionInfo {
+ return {
+ sessionId,
+ projectId: "p1",
+ agentId: "a1",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ createdAt: "2026-11-13T00:00:00.000Z",
+ lastActiveAt: "2026-11-13T00:00:00.000Z",
+ status,
+ hasTrace: true,
+ archived: false,
+ title,
+ } as SessionInfo;
+}
+
+describe("mergeRunningSessions", () => {
+ it("applies the live status to a fetched row", () => {
+ const live = new Map<string, SessionStatus>([["s1", "compacting"]]);
+ const [merged] = mergeRunningSessions([row("s1", "running")], live);
+ expect(merged?.status).toBe("compacting");
+ });
+
+ it("drops a row the channel reports idle, whatever the fetch said", () => {
+ const live = new Map<string, SessionStatus>([["s1", "idle"]]);
+ expect(mergeRunningSessions([row("s1", "running")], live)).toEqual([]);
+ });
+
+ it("keeps the row's own status for a Session the channel never named", () => {
+ const [merged] = mergeRunningSessions([row("s1", "running")], new Map());
+ expect(merged?.status).toBe("running");
+ expect(merged?.title).toBe("s1");
+ });
+
+ it("leaves the fetch's order alone", () => {
+ const live = new Map<string, SessionStatus>([["s2", "compacting"]]);
+ const merged = mergeRunningSessions([row("s1", "running"), row("s2", "running")], live);
+ expect(merged.map((s) => s.sessionId)).toEqual(["s1", "s2"]);
+ });
+});