From 49169cfdd61c049fa78e73d2592a6d793ef4cb9f Mon Sep 17 00:00:00 2001 From: OrwellVII <56531592+OrwellVII@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:10:03 +0800 Subject: [PATCH 1/4] feat(usage): add a per-conversation breakdown to the usage dashboard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → Usage → Breakdown gets a Conversation tab: one row per session for the selected range and project filter (title, project, models, cost, share, tokens, requests, last activity), most expensive first, top 50 with Show all. Subagent and advisor transcripts stay attributed to their owning session. Rows open the session through AppShell's openSessionById; sessions missing from the session list are labelled deleted and not clickable. The report gains sessionBreakdown, computed with one SQL aggregation over the existing usage_records columns; usage.db's layout is unchanged. --- CHANGELOG.md | 4 + components/AppShell.tsx | 1 + components/SettingsConfig.tsx | 6 +- components/UsageConfig.sessions.test.mjs | 116 +++++++++++ components/UsageConfig.tsx | 240 +++++++++++++++++------ lib/i18n/locales/en.json | 8 + lib/i18n/locales/ja.json | 8 + lib/i18n/locales/zh-CN.json | 8 + lib/omp/session-files.ts | 3 +- lib/usage-db.ts | 91 ++++++++- lib/usage-service.test.mjs | 102 ++++++++++ lib/usage-types.ts | 33 +++- 12 files changed, 554 insertions(+), 66 deletions(-) create mode 100644 components/UsageConfig.sessions.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..9e13ec5cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **See what each conversation cost.** Settings → Usage → Breakdown has a **Conversation** tab next to Model / Day / Project: one row per conversation for the selected time range, with its title, project, the models it used, cost, share, tokens, request count and last activity, most expensive first. Subagent and advisor usage counts toward the conversation that started it. The top 50 are listed, with **Show all** for the rest. Clicking a row opens the conversation; one that has since been deleted is labelled and cannot be opened. + ### Fixes & Improvements - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. diff --git a/components/AppShell.tsx b/components/AppShell.tsx index a0ea786a4..9a43aa598 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -2054,6 +2054,7 @@ export function AppShell({ appName }: { appName: string }) { onOmpUpdateAvailabilityChange={setOmpUpdateAvailable} onRequestAppUpdate={requestAppUpdateFromSettings} onSelectTab={setSettingsTab} + onOpenSession={openSessionById} onClose={() => setSettingsTab(null)} /> ) : ( diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 77f7240db..91eced4f0 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -740,7 +740,7 @@ function CompactionMethodOrder({ value, onChange, ...aria }: { value: readonly C ); } -export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCallsDefaultCollapsedChange, hideToolActivity, onHideToolActivityChange, expandThinkingByDefault, onExpandThinkingByDefaultChange, onHideThinkingBlockChange, providerUsageVisible, onProviderUsageVisibleChange, scopeNativeSelectAll, onScopeNativeSelectAllChange, openUrlAutomatically, onOpenUrlAutomaticallyChange, cwd, sessionId, onModelsSaved, onPluginsReloaded, appUpdate, ompUpdateAvailable, ompUpdatesDisabled, onRefreshAppUpdate, onOmpUpdateAvailabilityChange, onRequestAppUpdate, onSelectTab, onClose }: { +export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCallsDefaultCollapsedChange, hideToolActivity, onHideToolActivityChange, expandThinkingByDefault, onExpandThinkingByDefaultChange, onHideThinkingBlockChange, providerUsageVisible, onProviderUsageVisibleChange, scopeNativeSelectAll, onScopeNativeSelectAllChange, openUrlAutomatically, onOpenUrlAutomaticallyChange, cwd, sessionId, onModelsSaved, onPluginsReloaded, appUpdate, ompUpdateAvailable, ompUpdatesDisabled, onRefreshAppUpdate, onOmpUpdateAvailabilityChange, onRequestAppUpdate, onSelectTab, onOpenSession, onClose }: { activeTab: SettingsTab; toolCallsDefaultCollapsed: boolean; onToolCallsDefaultCollapsedChange: (collapsed: boolean) => void; @@ -766,6 +766,8 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal onOmpUpdateAvailabilityChange: (available: boolean) => void; onRequestAppUpdate: () => void; onSelectTab: (tab: SettingsTab) => void; + /** Open a session by id (Usage → conversation rows). */ + onOpenSession?: (sessionId: string) => void; onClose: () => void; }) { const isMobile = useIsMobile(); @@ -1533,7 +1535,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal padding: isMobile ? "16px 14px 32px" : "32px 24px 64px", }} > - + )} diff --git a/components/UsageConfig.sessions.test.mjs b/components/UsageConfig.sessions.test.mjs new file mode 100644 index 000000000..e1ac84180 --- /dev/null +++ b/components/UsageConfig.sessions.test.mjs @@ -0,0 +1,116 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test, { afterEach } from "node:test"; +import React from "react"; +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react/pure.js"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true }); +const { UsageConfig, SESSION_PREVIEW_LIMIT } = await jiti.import("./UsageConfig.tsx"); + +const originalFetch = globalThis.fetch; +afterEach(() => { + cleanup(); + globalThis.fetch = originalFetch; +}); + +const SESSION_COUNT = SESSION_PREVIEW_LIMIT + 5; + +/** Conversations as the server sends them: most expensive first. `s1` is deleted. */ +function sessionBreakdown() { + return Array.from({ length: SESSION_COUNT }, (_, i) => ({ + sessionId: `s${i}`, + title: `Session ${i}`, + project: `/home/user/project-${i % 3}`, + projectName: `project-${i % 3}`, + models: i === 0 + ? [ + { model: "claude-opus-5-5", provider: "anthropic", cost: 80, tokens: 1000 }, + { model: "claude-haiku-5", provider: "anthropic", cost: 20, tokens: 500 }, + ] + : [{ model: "claude-opus-5-5", provider: "anthropic", cost: SESSION_COUNT - i, tokens: 100 }], + cost: i === 0 ? 100 : SESSION_COUNT - i, + tokens: i === 0 ? 1500 : 100, + share: 1, + requestsCount: 3, + lastActiveAt: Date.UTC(2026, 9, 27, 12, 0), + deleted: i === 1, + })); +} + +function report() { + return { + timeRange: "30d", + granularity: "daily", + summary: { + totalCost: 0, totalTokens: 0, inputTokens: 0, outputTokens: 0, reasoningTokens: 0, cacheReadTokens: 0, + cacheWriteTokens: 0, cacheSavings: 0, activeDays: 0, tokensPerActiveDay: 0, cachePercentage: 0, + costQuality: { providerReported: 100, modelPriced: 0, unpriced: 0 }, + }, + providers: [], + timeSeries: [], + modelBreakdown: [], + dayBreakdown: [], + projectBreakdown: [], + sessionBreakdown: sessionBreakdown(), + scanInfo: { transcriptsScanned: 1, transcriptsOutsideWindow: 0, usageRecordsCount: 1, durationSeconds: 0.1, scannedAt: 0 }, + }; +} + +async function renderSessionsTab(opened) { + const requests = []; + globalThis.fetch = async (url) => { + requests.push(String(url)); + return { ok: true, json: async () => report() }; + }; + const view = render(React.createElement(UsageConfig, { onOpenSession: (id) => opened.push(id) })); + const tab = await waitFor(() => view.getByRole("button", { name: "CONVERSATION" })); + fireEvent.click(tab); + assert.equal(tab.getAttribute("aria-pressed"), "true"); + return { view, requests }; +} + +const rowIds = (container) => [...container.querySelectorAll("tr[data-session-id]")].map((tr) => tr.getAttribute("data-session-id")); + +test("the conversation tab lists the most expensive conversations first and opens one on click", async () => { + const opened = []; + const { view, requests } = await renderSessionsTab(opened); + assert.match(requests[0], /^\/api\/usage\?range=30d&/); + + // Server order (cost descending) is kept, capped at the preview limit. + const ids = rowIds(view.container); + assert.equal(ids.length, SESSION_PREVIEW_LIMIT); + assert.deepEqual(ids.slice(0, 3), ["s0", "s1", "s2"]); + const costs = [...view.container.querySelectorAll("tr[data-session-id] td:nth-child(2)")].map((td) => td.textContent); + assert.deepEqual(costs.slice(0, 3), ["$100.00", "$54.00", "$53.00"]); + + // The row shows its project, main model (+ the others) and request count. + const first = view.container.querySelector('tr[data-session-id="s0"]'); + assert.match(first.textContent, /project-0 · claude-opus-5-5 \+1 · /); + assert.equal(first.querySelector("td:nth-child(5)").textContent, "3"); + + fireEvent.click(view.getByRole("button", { name: "Session 0" })); + assert.deepEqual(opened, ["s0"]); +}); + +test("a deleted conversation is labelled and cannot be opened", async () => { + const opened = []; + const { view } = await renderSessionsTab(opened); + + const deleted = view.container.querySelector('tr[data-session-id="s1"]'); + assert.equal(deleted.querySelector("button"), null); + assert.match(deleted.textContent, /Deleted/); + fireEvent.click(view.getByText("Session 1")); + assert.deepEqual(opened, []); +}); + +test("show all lists every conversation and can collapse back to the top ones", async () => { + const { view } = await renderSessionsTab([]); + + fireEvent.click(view.getByRole("button", { name: `Show all ${SESSION_COUNT} conversations` })); + assert.equal(rowIds(view.container).length, SESSION_COUNT); + assert.equal(rowIds(view.container).at(-1), `s${SESSION_COUNT - 1}`); + + fireEvent.click(view.getByRole("button", { name: `Show top ${SESSION_PREVIEW_LIMIT} only` })); + assert.equal(rowIds(view.container).length, SESSION_PREVIEW_LIMIT); +}); diff --git a/components/UsageConfig.tsx b/components/UsageConfig.tsx index 3cc2a517b..9aaafcfd5 100644 --- a/components/UsageConfig.tsx +++ b/components/UsageConfig.tsx @@ -34,13 +34,27 @@ function formatCurrency(amount: number): string { return `$${amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } -export function UsageConfig() { - const { t } = useI18n(); +/** Conversations listed before "Show all" in the session breakdown. */ +export const SESSION_PREVIEW_LIMIT = 50; + +const BREAKDOWN_VIEWS: Array<{ view: UsageBreakdownView; labelKey: string }> = [ + { view: "model", labelKey: "usageConfig.model" }, + { view: "day", labelKey: "usageConfig.day" }, + { view: "project", labelKey: "usageConfig.project" }, + { view: "session", labelKey: "usageConfig.session" }, +]; + +export function UsageConfig({ onOpenSession }: { + /** Open a conversation by id (the session list's open-session helper). */ + onOpenSession?: (sessionId: string) => void; +} = {}) { + const { t, locale } = useI18n(); const [timeRange, setTimeRange] = useState("30d"); const [granularity, setGranularity] = useState("daily"); const [metricView, setMetricView] = useState("cost"); const [breakdownView, setBreakdownView] = useState("model"); + const [showAllSessions, setShowAllSessions] = useState(false); const [report, setReport] = useState(null); const [loading, setLoading] = useState(true); @@ -291,6 +305,8 @@ export function UsageConfig() { const modelBreakdown = report?.modelBreakdown || []; const dayBreakdown = report?.dayBreakdown || []; const projectBreakdown = report?.projectBreakdown || []; + const sessionBreakdown = report?.sessionBreakdown || []; + const visibleSessions = showAllSessions ? sessionBreakdown : sessionBreakdown.slice(0, SESSION_PREVIEW_LIMIT); const scanInfo = report?.scanInfo; // Active hover point data @@ -929,7 +945,7 @@ export function UsageConfig() { gap: 14, }} > - {/* Left Card: Breakdown Table */} + {/* Left Card: Breakdown Table (full row for conversations, which carry more columns) */}
{/* Breakdown Header & Toggle */} @@ -957,75 +974,43 @@ export function UsageConfig() { border: "1px solid var(--border)", }} > - - - + {BREAKDOWN_VIEWS.map(({ view, labelKey }) => ( + + ))}
{/* Table Container */} -
+
+ {breakdownView === "session" && ( + + )} @@ -1111,9 +1096,144 @@ export function UsageConfig() { )) ))} + + {breakdownView === "session" && + (sessionBreakdown.length === 0 ? ( + + + + ) : ( + visibleSessions.map((s) => { + const openable = !s.deleted && Boolean(onOpenSession); + const mainModel = s.models[0]?.model ?? ""; + const modelsLabel = s.models.length > 1 ? `${mainModel} +${s.models.length - 1}` : mainModel; + const modelsTitle = s.models.map((m) => `${m.model}: ${formatCurrency(m.cost)}`).join("\n"); + const lastActive = new Date(s.lastActiveAt).toLocaleString(locale, { + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }); + return ( + + + + + + + + ); + }) + ))}
- {breakdownView === "model" - ? t("usageConfig.model") - : breakdownView === "day" - ? t("usageConfig.day") - : t("usageConfig.project")} + {t(BREAKDOWN_VIEWS.find((v) => v.view === breakdownView)?.labelKey ?? "usageConfig.model")} {t("usageConfig.cost")} {t("usageConfig.share")} {t("usageConfig.tokens")}{t("usageConfig.requests")}
+ {t("usageConfig.emptyTitle")} +
+
+ {openable ? ( + + ) : ( + + {s.title} + + )} + {s.deleted && ( + + {t("usageConfig.deletedSession")} + + )} +
+
+ {s.projectName} + {" · "} + {modelsLabel} + {" · "} + {lastActive} +
+
+ {formatCurrency(s.cost)} + + {s.share.toFixed(1)}% + + {formatTokens(s.tokens)} + + {s.requestsCount.toLocaleString()} +
+ + {breakdownView === "session" && sessionBreakdown.length > SESSION_PREVIEW_LIMIT && ( + + )}
{/* Right Card: Cost Quality */} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 1ad043f14..df1f6fd88 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1690,6 +1690,14 @@ "usageConfig.model": "Model", "usageConfig.day": "Day", "usageConfig.project": "Project", + "usageConfig.session": "Conversation", + "usageConfig.requests": "Requests", + "usageConfig.lastActive": "Last active", + "usageConfig.openSession": "Open conversation: {title}", + "usageConfig.deletedSession": "Deleted", + "usageConfig.deletedSessionHint": "This conversation has been deleted and can no longer be opened.", + "usageConfig.showAllSessions": "Show all {count} conversations", + "usageConfig.showTopSessions": "Show top {count} only", "usageConfig.share": "Share", "usageConfig.costQuality": "Cost quality", "usageConfig.providerReported": "Provider reported", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index af23a236a..ee2e71a4f 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1649,6 +1649,14 @@ "usageConfig.model": "モデル", "usageConfig.day": "日付", "usageConfig.project": "プロジェクト", + "usageConfig.session": "セッション", + "usageConfig.requests": "リクエスト", + "usageConfig.lastActive": "最終アクティブ", + "usageConfig.openSession": "セッションを開く: {title}", + "usageConfig.deletedSession": "削除済み", + "usageConfig.deletedSessionHint": "このセッションは削除されているため開けません。", + "usageConfig.showAllSessions": "全 {count} 件のセッションを表示", + "usageConfig.showTopSessions": "上位 {count} 件のみ表示", "usageConfig.share": "割合", "usageConfig.costQuality": "コスト品質", "usageConfig.providerReported": "プロバイダー報告", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 75878b912..7cfcda92f 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1649,6 +1649,14 @@ "usageConfig.model": "模型", "usageConfig.day": "日期", "usageConfig.project": "项目", + "usageConfig.session": "会话", + "usageConfig.requests": "请求数", + "usageConfig.lastActive": "最后活跃", + "usageConfig.openSession": "打开会话:{title}", + "usageConfig.deletedSession": "已删除", + "usageConfig.deletedSessionHint": "该会话已删除,无法再打开。", + "usageConfig.showAllSessions": "显示全部 {count} 个会话", + "usageConfig.showTopSessions": "仅显示前 {count} 个", "usageConfig.share": "占比", "usageConfig.costQuality": "费用质量", "usageConfig.providerReported": "提供商报告", diff --git a/lib/omp/session-files.ts b/lib/omp/session-files.ts index 42c7dc49d..5a60060cc 100644 --- a/lib/omp/session-files.ts +++ b/lib/omp/session-files.ts @@ -1087,8 +1087,7 @@ function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { * requests (sidebar poll, page loads) into a single stat. Per-file scanning is * still memoized by scanSessionInfoCached on (size, mtimeMs). */ -export async function listAllSessionInfos(): Promise { - const sessionsRoot = getSessionsDir(); +export async function listAllSessionInfos(sessionsRoot = getSessionsDir()): Promise { const files = await listSessionFiles(sessionsRoot); const sessions: OmpSessionInfo[] = []; diff --git a/lib/usage-db.ts b/lib/usage-db.ts index 128857d28..e85ac960d 100644 --- a/lib/usage-db.ts +++ b/lib/usage-db.ts @@ -3,7 +3,7 @@ import { DatabaseSync } from "node:sqlite"; import { basename, dirname, join } from "path"; import { readModelsConfig, type ModelsFileConfig } from "./omp/models-config"; import { getAgentDir, getSessionsDir } from "./omp/paths"; -import { listSessionArtifactTranscripts, listSessionFiles } from "./omp/session-files"; +import { listAllSessionInfos, listSessionArtifactTranscripts, listSessionFiles } from "./omp/session-files"; import { formatChartDateLabel, formatFullDateLabel, @@ -19,6 +19,8 @@ import type { ModelUsageSummary, ProjectUsageSummary, ProviderUsageSummary, + SessionModelUsage, + SessionUsageSummary, TimeSeriesPoint, UsageQueryOptions, UsageRecord, @@ -380,6 +382,9 @@ function collectUncountedUsage(db: DatabaseSync): void { /** Report filter: rows not listed by {@link collectUncountedUsage}. */ const COUNTED_ROWS = "id NOT IN (SELECT id FROM temp.uncounted_usage)"; +/** A conversation without a title is named by its first message, cut to this length. */ +const SESSION_TITLE_MAX_CHARS = 200; + /** * Execute SQL analytics queries over the SQLite database to generate a full UsageReport. */ @@ -754,6 +759,89 @@ export async function getUsageReportFromDb( sessionsCount: row.sessionsCount, })); + // 7. Session (conversation) Breakdown Query. Artifact transcripts already + // carry their owning session's id, so subagent and advisor usage lands in + // the conversation that spawned it. The bare `session_cwd` columns take the + // newest request's value (SQLite's single-max() rule). + const sessionRows = db + .prepare( + ` + WITH per_model AS ( + SELECT + session_id, + provider, + model, + MAX(timestamp) AS lastActiveAt, + session_cwd, + COALESCE(SUM(cost), 0) AS cost, + COALESCE(SUM(total_tokens), 0) AS tokens, + COUNT(*) AS requestsCount + FROM usage_records + WHERE ${COUNTED_ROWS} AND timestamp >= ? AND timestamp <= ? ${whereProject} + GROUP BY session_id, provider, model + ) + SELECT + session_id AS sessionId, + MAX(lastActiveAt) AS lastActiveAt, + session_cwd AS project, + SUM(cost) AS cost, + SUM(tokens) AS tokens, + SUM(requestsCount) AS requestsCount, + json_group_array(json_object('model', model, 'provider', provider, 'cost', cost, 'tokens', tokens)) AS models + FROM per_model + GROUP BY session_id + ORDER BY cost DESC, tokens DESC, sessionId ASC + `, + ) + .all(...params) as Array<{ + sessionId: string; + lastActiveAt: number; + project: string; + cost: number; + tokens: number; + requestsCount: number; + models: string; + }>; + + // Titles come from the session list; a session missing from it is gone. + // The list stands in "(no messages)" for an empty first message. + const sessionTitleById = new Map(); + if (sessionRows.length > 0) { + for (const info of await listAllSessionInfos(sessionsDir)) { + if (sessionTitleById.has(info.id)) continue; + const firstMessage = info.firstMessage === "(no messages)" ? "" : info.firstMessage; + sessionTitleById.set( + info.id, + info.title?.trim() || firstMessage.replace(/\s+/g, " ").trim().slice(0, SESSION_TITLE_MAX_CHARS), + ); + } + } + + const sessionBreakdown: SessionUsageSummary[] = sessionRows.map((row) => { + const title = sessionTitleById.get(row.sessionId); + const models = (JSON.parse(row.models) as SessionModelUsage[]).sort( + (a, b) => b.cost - a.cost || b.tokens - a.tokens, + ); + return { + sessionId: row.sessionId, + title: title || row.sessionId, + project: row.project || "Default Project", + projectName: basename(row.project || "Default Project") || row.project, + models, + cost: row.cost, + tokens: row.tokens, + share: + totalCost > 0 + ? (row.cost / totalCost) * 100 + : totalTokens > 0 + ? (row.tokens / totalTokens) * 100 + : 0, + requestsCount: row.requestsCount, + lastActiveAt: row.lastActiveAt, + deleted: title === undefined, + }; + }); + // Scan info const totalSyncedRow = db.prepare("SELECT COUNT(*) as c FROM synced_files").get() as { c: number }; const inWindowSyncedRow = db @@ -780,6 +868,7 @@ export async function getUsageReportFromDb( modelBreakdown, dayBreakdown, projectBreakdown, + sessionBreakdown, scanInfo: { transcriptsScanned, transcriptsOutsideWindow, diff --git a/lib/usage-service.test.mjs b/lib/usage-service.test.mjs index 420e9238d..8148b134f 100644 --- a/lib/usage-service.test.mjs +++ b/lib/usage-service.test.mjs @@ -412,6 +412,108 @@ test("a later subagent that reuses an id does not hide an inherited task summary }); }); +test("sessionBreakdown has one row per conversation with its models, subagents included, most expensive first", async () => { + const { getUsageReport } = await loadSubject(); + + await withTempSessionDir(async (dir) => { + const project = join(dir, "sessions", "test-project"); + const artifacts = join(project, "2026_parent"); + mkdirSync(artifacts, { recursive: true }); + const t = Date.now() - 60_000; + const write = (file, lines) => writeFileSync(file, lines.join("\n"), "utf8"); + const userEntry = (text) => JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: text } }); + + // Parent: two models in its own transcript, a foreground subagent and an advisor. + write(join(project, "2026_parent.jsonl"), [ + JSON.stringify({ type: "session", id: "sess-parent", cwd: "/home/user/project-alpha", title: "Parent chat", timestamp: new Date(t - 1000).toISOString() }), + userEntry("hello"), + assistantEntry("p1", t, "claude-opus-5-5", 1000, 2), + assistantEntry("p2", t + 1, "claude-sonnet-5", 100, 0.1), + taskResultEntry("p3", t + 3, [{ id: "Sub1", resolvedModel: "anthropic/claude-haiku-5", usage: { input: 500, output: 0, cost: { total: 0.5 } } }]), + ]); + write(join(artifacts, "Sub1.jsonl"), [sessionHeader("sub-1", "/tmp/wt/sub"), assistantEntry("s1", t + 2, "claude-haiku-5", 500, 0.5)]); + write(join(artifacts, "__advisor.jsonl"), [sessionHeader("advisor", "/home/user/project-alpha"), assistantEntry("a1", t + 9, "claude-sonnet-5", 20, 0.02)]); + // Untitled conversation in another project: named by its first message. + write(join(project, "2026_other.jsonl"), [ + sessionHeader("sess-other", "/home/user/project-beta", t - 500), + userEntry(" Fix the\nflaky test "), + assistantEntry("o1", t + 5, "claude-opus-5-5", 3000, 5), + ]); + + const report = await getUsageReport({ range: "30d", forceRefresh: true }); + const rows = report.sessionBreakdown; + assert.deepEqual(rows.map((s) => s.sessionId), ["sess-other", "sess-parent"], "sorted by cost, helper transcripts are not rows"); + + const [other, parent] = rows; + assert.equal(other.title, "Fix the flaky test"); + assert.equal(other.projectName, "project-beta"); + assert.equal(other.deleted, false); + + assert.equal(parent.title, "Parent chat"); + assert.equal(parent.project, "/home/user/project-alpha", "subagent worktree cwd does not split the row"); + assert.equal(parent.cost.toFixed(2), (2 + 0.1 + 0.5 + 0.02).toFixed(2), "subagent and advisor usage counted once in the parent"); + assert.equal(parent.tokens, 1000 + 100 + 500 + 20); + assert.equal(parent.requestsCount, 4, "the task summary duplicates Sub1's transcript and is not counted"); + assert.equal(parent.lastActiveAt, t + 9); + assert.deepEqual( + parent.models.map((m) => [m.model, m.tokens]), + [["claude-opus-5-5", 1000], ["claude-haiku-5", 500], ["claude-sonnet-5", 120]], + ); + + const total = rows.reduce((sum, s) => sum + s.cost, 0); + assert.equal(total.toFixed(6), report.summary.totalCost.toFixed(6), "conversations add up to the total"); + assert.equal(rows.reduce((sum, s) => sum + s.share, 0).toFixed(6), (100).toFixed(6)); + }); +}); + +test("sessionBreakdown honors the time range and project filter, and marks sessions that are gone", async () => { + const { getUsageReport } = await loadSubject(); + const { getUsageDatabase } = await jiti.import("./usage-db.ts"); + + await withTempSessionDir(async (dir) => { + const project = join(dir, "sessions", "test-project"); + mkdirSync(project, { recursive: true }); + const t = Date.now() - 60_000; + const day = 86_400_000; + writeFileSync(join(project, "2026_a.jsonl"), [ + sessionHeader("sess-a", "/home/user/project-alpha", t - 40 * day), + assistantEntry("a-old", t - 40 * day, "claude-opus-5-5", 9000, 9), + assistantEntry("a-new", t, "claude-opus-5-5", 100, 1), + ].join("\n"), "utf8"); + writeFileSync(join(project, "2026_b.jsonl"), [ + sessionHeader("sess-b", "/home/user/project-beta", t - 1000), + assistantEntry("b1", t, "claude-opus-5-5", 200, 2), + ].join("\n"), "utf8"); + writeFileSync(join(project, "2026_c.jsonl"), [ + sessionHeader("sess-c", "/home/user/project-alpha", t - 50 * day), + assistantEntry("c1", t - 50 * day, "claude-opus-5-5", 300, 3), + ].join("\n"), "utf8"); + + const last30 = await getUsageReport({ range: "30d", forceRefresh: true }); + assert.deepEqual(last30.sessionBreakdown.map((s) => [s.sessionId, s.cost]), [["sess-b", 2], ["sess-a", 1]]); + + const alpha = await getUsageReport({ range: "all", project: "project-alpha" }); + assert.deepEqual(alpha.sessionBreakdown.map((s) => [s.sessionId, s.cost]), [["sess-a", 10], ["sess-c", 3]]); + assert.equal(alpha.sessionBreakdown[0].requestsCount, 2); + + // A usage row whose session the session list no longer has (removed behind + // the report's back) still counts, but cannot be opened. + getUsageDatabase().prepare(` + INSERT INTO usage_records (file_path, session_id, session_cwd, timestamp, provider, model, input_tokens, + output_tokens, reasoning_tokens, cache_read_tokens, cache_write_tokens, total_tokens, cost, cache_savings, + cost_quality, session_started) + VALUES ('/gone/2026_gone.jsonl', 'sess-gone', '/home/user/project-alpha', ?, 'anthropic', 'claude-opus-5-5', + 50, 0, 0, 0, 0, 50, 0.5, 0, 'provider_reported', ?) + `).run(t, t); + const withGone = await getUsageReport({ range: "30d" }); + const gone = withGone.sessionBreakdown.find((s) => s.sessionId === "sess-gone"); + assert.ok(gone); + assert.equal(gone.deleted, true); + assert.equal(gone.title, "sess-gone"); + assert.equal(withGone.sessionBreakdown.filter((s) => s.deleted).length, 1); + }); +}); + test("time range bounds compute valid intervals", async () => { const { computeTimeRangeBounds } = await loadSubject(); diff --git a/lib/usage-types.ts b/lib/usage-types.ts index 33c292f50..2af274375 100644 --- a/lib/usage-types.ts +++ b/lib/usage-types.ts @@ -1,7 +1,7 @@ export type UsageTimeRange = "today" | "7d" | "30d" | "90d" | "month" | "all"; export type UsageGranularity = "daily" | "monthly" | "projects"; export type UsageMetricView = "cost" | "tokens"; -export type UsageBreakdownView = "model" | "day" | "project"; +export type UsageBreakdownView = "model" | "day" | "project" | "session"; export type CostQualityTier = "provider_reported" | "model_priced" | "unpriced"; export interface ModelRates { @@ -118,6 +118,35 @@ export interface ProjectUsageSummary { sessionsCount: number; } +/** One model's slice of a conversation's usage. */ +export interface SessionModelUsage { + model: string; + provider: string; + cost: number; + tokens: number; +} + +/** + * Usage of one conversation (session), including its subagent, advisor and + * other artifact transcripts, which are attributed to the owning session. + */ +export interface SessionUsageSummary { + sessionId: string; + /** Session title, else its first message, else the session id. */ + title: string; + project: string; // session cwd + projectName: string; // display folder name + /** Models used, most expensive first. */ + models: SessionModelUsage[]; + cost: number; + tokens: number; + share: number; // 0-100 percentage + requestsCount: number; + lastActiveAt: number; // ms timestamp of the newest request in the window + /** The session is no longer in the session list (deleted), so it cannot be opened. */ + deleted: boolean; +} + export interface UsageReportScanInfo { transcriptsScanned: number; transcriptsOutsideWindow: number; @@ -135,6 +164,8 @@ export interface UsageReport { modelBreakdown: ModelUsageSummary[]; dayBreakdown: DayUsageSummary[]; projectBreakdown: ProjectUsageSummary[]; + /** Per conversation, most expensive first. */ + sessionBreakdown: SessionUsageSummary[]; scanInfo: UsageReportScanInfo; } From 6a401e17faa57794b4794902a14fdca7aad9cb9e Mon Sep 17 00:00:00 2001 From: OrwellVII <56531592+OrwellVII@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:17:36 +0800 Subject: [PATCH 2/4] fix(usage): read conversation titles from their own files and open rows only when loadable - Resolve each listed conversation's title from its own session file (found through a transcript its usage came from) instead of scanning every session file on each report. - Mark conversations past the session load ceiling as too large: their rows are labelled and cannot be opened, like deleted ones. - Clicking anywhere on an openable row opens the conversation. - Show the year in the last-active time. --- CHANGELOG.md | 2 +- components/UsageConfig.sessions.test.mjs | 26 ++++++++-- components/UsageConfig.tsx | 22 +++++--- lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + lib/omp/session-files.ts | 5 +- lib/usage-db.ts | 55 +++++++++++++------- lib/usage-service.test.mjs | 65 +++++++++++++++++++++++- lib/usage-types.ts | 2 + 10 files changed, 147 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e13ec5cd..8eb7373bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added -- **See what each conversation cost.** Settings → Usage → Breakdown has a **Conversation** tab next to Model / Day / Project: one row per conversation for the selected time range, with its title, project, the models it used, cost, share, tokens, request count and last activity, most expensive first. Subagent and advisor usage counts toward the conversation that started it. The top 50 are listed, with **Show all** for the rest. Clicking a row opens the conversation; one that has since been deleted is labelled and cannot be opened. +- **See what each conversation cost.** Settings → Usage → Breakdown has a **Conversation** tab next to Model / Day / Project: one row per conversation for the selected time range, with its title, project, the models it used, cost, share, tokens, request count and last activity, most expensive first. Subagent and advisor usage counts toward the conversation that started it. The top 50 are listed, with **Show all** for the rest. Clicking a row opens the conversation; one that has since been deleted, or is too large for omp-web to open, is labelled and cannot be opened. ### Fixes & Improvements diff --git a/components/UsageConfig.sessions.test.mjs b/components/UsageConfig.sessions.test.mjs index e1ac84180..47cf79b18 100644 --- a/components/UsageConfig.sessions.test.mjs +++ b/components/UsageConfig.sessions.test.mjs @@ -16,7 +16,7 @@ afterEach(() => { const SESSION_COUNT = SESSION_PREVIEW_LIMIT + 5; -/** Conversations as the server sends them: most expensive first. `s1` is deleted. */ +/** Conversations as the server sends them: most expensive first. `s1` is deleted, `s2` is too large to open. */ function sessionBreakdown() { return Array.from({ length: SESSION_COUNT }, (_, i) => ({ sessionId: `s${i}`, @@ -35,6 +35,7 @@ function sessionBreakdown() { requestsCount: 3, lastActiveAt: Date.UTC(2026, 9, 27, 12, 0), deleted: i === 1, + tooLarge: i === 2, })); } @@ -84,13 +85,18 @@ test("the conversation tab lists the most expensive conversations first and open const costs = [...view.container.querySelectorAll("tr[data-session-id] td:nth-child(2)")].map((td) => td.textContent); assert.deepEqual(costs.slice(0, 3), ["$100.00", "$54.00", "$53.00"]); - // The row shows its project, main model (+ the others) and request count. + // The row shows its project, main model (+ the others), last activity with its year, and request count. const first = view.container.querySelector('tr[data-session-id="s0"]'); assert.match(first.textContent, /project-0 · claude-opus-5-5 \+1 · /); + assert.match(first.querySelector("td:nth-child(1)").textContent, /2026/); assert.equal(first.querySelector("td:nth-child(5)").textContent, "3"); fireEvent.click(view.getByRole("button", { name: "Session 0" })); - assert.deepEqual(opened, ["s0"]); + assert.deepEqual(opened, ["s0"], "the title button opens it once"); + + // Any cell of the row opens it too. + fireEvent.click(view.container.querySelector('tr[data-session-id="s3"] td:nth-child(2)')); + assert.deepEqual(opened, ["s0", "s3"]); }); test("a deleted conversation is labelled and cannot be opened", async () => { @@ -101,6 +107,20 @@ test("a deleted conversation is labelled and cannot be opened", async () => { assert.equal(deleted.querySelector("button"), null); assert.match(deleted.textContent, /Deleted/); fireEvent.click(view.getByText("Session 1")); + fireEvent.click(deleted.querySelector("td:nth-child(2)")); + assert.deepEqual(opened, []); +}); + +test("a conversation too large to load is labelled and cannot be opened", async () => { + const opened = []; + const { view } = await renderSessionsTab(opened); + + const tooLarge = view.container.querySelector('tr[data-session-id="s2"]'); + assert.equal(tooLarge.querySelector("button"), null); + assert.match(tooLarge.textContent, /Too large/); + assert.match(view.getByText("Session 2").getAttribute("title"), /too large to open/); + fireEvent.click(view.getByText("Session 2")); + fireEvent.click(tooLarge.querySelector("td:nth-child(2)")); assert.deepEqual(opened, []); }); diff --git a/components/UsageConfig.tsx b/components/UsageConfig.tsx index 9aaafcfd5..096b29e81 100644 --- a/components/UsageConfig.tsx +++ b/components/UsageConfig.tsx @@ -1106,11 +1106,18 @@ export function UsageConfig({ onOpenSession }: { ) : ( visibleSessions.map((s) => { - const openable = !s.deleted && Boolean(onOpenSession); + const openable = !s.deleted && !s.tooLarge && Boolean(onOpenSession); + // Why a listed conversation cannot be opened, if it cannot. + const unavailable = s.deleted + ? { label: t("usageConfig.deletedSession"), hint: t("usageConfig.deletedSessionHint") } + : s.tooLarge + ? { label: t("usageConfig.tooLargeSession"), hint: t("errors.session_file_too_large") } + : undefined; const mainModel = s.models[0]?.model ?? ""; const modelsLabel = s.models.length > 1 ? `${mainModel} +${s.models.length - 1}` : mainModel; const modelsTitle = s.models.map((m) => `${m.model}: ${formatCurrency(m.cost)}`).join("\n"); const lastActive = new Date(s.lastActiveAt).toLocaleString(locale, { + year: "numeric", month: "short", day: "numeric", hour: "2-digit", @@ -1120,14 +1127,15 @@ export function UsageConfig({ onOpenSession }: { onOpenSession?.(s.sessionId) : undefined} + style={{ borderBottom: "1px solid var(--bg-subtle)", cursor: openable ? "pointer" : undefined }} >
{openable ? ( + // The keyboard target; its click bubbles to the row, which opens the conversation. ) : ( )} - {s.deleted && ( + {unavailable && ( - {t("usageConfig.deletedSession")} + {unavailable.label} )}
diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index df1f6fd88..4a4de0ef1 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1696,6 +1696,7 @@ "usageConfig.openSession": "Open conversation: {title}", "usageConfig.deletedSession": "Deleted", "usageConfig.deletedSessionHint": "This conversation has been deleted and can no longer be opened.", + "usageConfig.tooLargeSession": "Too large", "usageConfig.showAllSessions": "Show all {count} conversations", "usageConfig.showTopSessions": "Show top {count} only", "usageConfig.share": "Share", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index ee2e71a4f..3aefc8c4c 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1655,6 +1655,7 @@ "usageConfig.openSession": "セッションを開く: {title}", "usageConfig.deletedSession": "削除済み", "usageConfig.deletedSessionHint": "このセッションは削除されているため開けません。", + "usageConfig.tooLargeSession": "大きすぎます", "usageConfig.showAllSessions": "全 {count} 件のセッションを表示", "usageConfig.showTopSessions": "上位 {count} 件のみ表示", "usageConfig.share": "割合", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 7cfcda92f..84339a31a 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1655,6 +1655,7 @@ "usageConfig.openSession": "打开会话:{title}", "usageConfig.deletedSession": "已删除", "usageConfig.deletedSessionHint": "该会话已删除,无法再打开。", + "usageConfig.tooLargeSession": "过大", "usageConfig.showAllSessions": "显示全部 {count} 个会话", "usageConfig.showTopSessions": "仅显示前 {count} 个", "usageConfig.share": "占比", diff --git a/lib/omp/session-files.ts b/lib/omp/session-files.ts index 5a60060cc..94b6f6d59 100644 --- a/lib/omp/session-files.ts +++ b/lib/omp/session-files.ts @@ -1045,7 +1045,7 @@ export function invalidateAllSessionScanCaches(): void { /** scanSessionInfo memoized on (path, size, mtimeMs). Callers must treat the * returned info as immutable — cache hits share one object. */ -function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { +export function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { let stat: { size: number; mtime: Date; mtimeMs: number }; try { stat = statSync(filePath); @@ -1087,7 +1087,8 @@ function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { * requests (sidebar poll, page loads) into a single stat. Per-file scanning is * still memoized by scanSessionInfoCached on (size, mtimeMs). */ -export async function listAllSessionInfos(sessionsRoot = getSessionsDir()): Promise { +export async function listAllSessionInfos(): Promise { + const sessionsRoot = getSessionsDir(); const files = await listSessionFiles(sessionsRoot); const sessions: OmpSessionInfo[] = []; diff --git a/lib/usage-db.ts b/lib/usage-db.ts index e85ac960d..adc4b2e7f 100644 --- a/lib/usage-db.ts +++ b/lib/usage-db.ts @@ -3,7 +3,12 @@ import { DatabaseSync } from "node:sqlite"; import { basename, dirname, join } from "path"; import { readModelsConfig, type ModelsFileConfig } from "./omp/models-config"; import { getAgentDir, getSessionsDir } from "./omp/paths"; -import { listAllSessionInfos, listSessionArtifactTranscripts, listSessionFiles } from "./omp/session-files"; +import { + listSessionArtifactTranscripts, + listSessionFiles, + MAX_SESSION_LOAD_BYTES, + scanSessionInfoCached, +} from "./omp/session-files"; import { formatChartDateLabel, formatFullDateLabel, @@ -385,6 +390,19 @@ const COUNTED_ROWS = "id NOT IN (SELECT id FROM temp.uncounted_usage)"; /** A conversation without a title is named by its first message, cut to this length. */ const SESSION_TITLE_MAX_CHARS = 200; +/** + * The session file a synced transcript belongs to: the transcript itself, or + * for a helper transcript the `.jsonl` beside the artifacts directory + * it sits in (see listSessionArtifactTranscripts). + */ +function owningSessionFile(filePath: string, sessionFiles: ReadonlySet): string | undefined { + if (sessionFiles.has(filePath)) return filePath; + for (let dir = dirname(filePath); dir !== dirname(dir); dir = dirname(dir)) { + if (sessionFiles.has(`${dir}.jsonl`)) return `${dir}.jsonl`; + } + return undefined; +} + /** * Execute SQL analytics queries over the SQLite database to generate a full UsageReport. */ @@ -761,8 +779,8 @@ export async function getUsageReportFromDb( // 7. Session (conversation) Breakdown Query. Artifact transcripts already // carry their owning session's id, so subagent and advisor usage lands in - // the conversation that spawned it. The bare `session_cwd` columns take the - // newest request's value (SQLite's single-max() rule). + // the conversation that spawned it. The bare `session_cwd` and `file_path` + // columns take the newest request's values (SQLite's single-max() rule). const sessionRows = db .prepare( ` @@ -773,6 +791,7 @@ export async function getUsageReportFromDb( model, MAX(timestamp) AS lastActiveAt, session_cwd, + file_path AS filePath, COALESCE(SUM(cost), 0) AS cost, COALESCE(SUM(total_tokens), 0) AS tokens, COUNT(*) AS requestsCount @@ -784,6 +803,7 @@ export async function getUsageReportFromDb( session_id AS sessionId, MAX(lastActiveAt) AS lastActiveAt, session_cwd AS project, + filePath, SUM(cost) AS cost, SUM(tokens) AS tokens, SUM(requestsCount) AS requestsCount, @@ -797,28 +817,24 @@ export async function getUsageReportFromDb( sessionId: string; lastActiveAt: number; project: string; + filePath: string; cost: number; tokens: number; requestsCount: number; models: string; }>; - // Titles come from the session list; a session missing from it is gone. - // The list stands in "(no messages)" for an empty first message. - const sessionTitleById = new Map(); - if (sessionRows.length > 0) { - for (const info of await listAllSessionInfos(sessionsDir)) { - if (sessionTitleById.has(info.id)) continue; - const firstMessage = info.firstMessage === "(no messages)" ? "" : info.firstMessage; - sessionTitleById.set( - info.id, - info.title?.trim() || firstMessage.replace(/\s+/g, " ").trim().slice(0, SESSION_TITLE_MAX_CHARS), - ); - } - } - + // Titles and sizes come from each listed conversation's own session file, + // found through a transcript its usage was read from; only those files are + // scanned. A conversation whose file is no longer listed is gone. + const listedSessionFiles = new Set(sessionFiles); const sessionBreakdown: SessionUsageSummary[] = sessionRows.map((row) => { - const title = sessionTitleById.get(row.sessionId); + const sessionFile = owningSessionFile(row.filePath, listedSessionFiles); + const info = sessionFile ? scanSessionInfoCached(sessionFile) : undefined; + // The list stands in "(no messages)" for an empty first message. + const firstMessage = !info || info.firstMessage === "(no messages)" ? "" : info.firstMessage; + const title = + info?.title?.trim() || firstMessage.replace(/\s+/g, " ").trim().slice(0, SESSION_TITLE_MAX_CHARS); const models = (JSON.parse(row.models) as SessionModelUsage[]).sort( (a, b) => b.cost - a.cost || b.tokens - a.tokens, ); @@ -838,7 +854,8 @@ export async function getUsageReportFromDb( : 0, requestsCount: row.requestsCount, lastActiveAt: row.lastActiveAt, - deleted: title === undefined, + deleted: info === undefined, + tooLarge: info !== undefined && info.size > MAX_SESSION_LOAD_BYTES, }; }); diff --git a/lib/usage-service.test.mjs b/lib/usage-service.test.mjs index 8148b134f..32a618763 100644 --- a/lib/usage-service.test.mjs +++ b/lib/usage-service.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, rmSync, statSync, truncateSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -448,6 +448,7 @@ test("sessionBreakdown has one row per conversation with its models, subagents i assert.equal(other.title, "Fix the flaky test"); assert.equal(other.projectName, "project-beta"); assert.equal(other.deleted, false); + assert.equal(other.tooLarge, false); assert.equal(parent.title, "Parent chat"); assert.equal(parent.project, "/home/user/project-alpha", "subagent worktree cwd does not split the row"); @@ -514,6 +515,68 @@ test("sessionBreakdown honors the time range and project filter, and marks sessi }); }); +test("sessionBreakdown reads titles from the reported conversations' own session files only", async () => { + const { getUsageReport } = await loadSubject(); + + await withTempSessionDir(async (dir) => { + const project = join(dir, "sessions", "test-project"); + mkdirSync(join(project, "2026_in"), { recursive: true }); + const t = Date.now() - 60_000; + const day = 86_400_000; + const header = (id, title) => JSON.stringify({ type: "session", id, cwd: "/home/user/project-alpha", title, timestamp: new Date(t - 60 * day).toISOString() }); + // The conversation's own turns are old; only its subagent spent in the window. + writeFileSync(join(project, "2026_in.jsonl"), [header("sess-in", "In window"), assistantEntry("i1", t - 40 * day, "claude-opus-5-5", 100, 1)].join("\n"), "utf8"); + writeFileSync(join(project, "2026_in", "Sub.jsonl"), [sessionHeader("sub", "/tmp/wt"), assistantEntry("s1", t, "claude-haiku-5", 50, 0.5)].join("\n"), "utf8"); + writeFileSync(join(project, "2026_out.jsonl"), [header("sess-out", "Outside window"), assistantEntry("o1", t - 50 * day, "claude-opus-5-5", 300, 3)].join("\n"), "utf8"); + + globalThis.__ompSessionScanCache?.clear(); + const report = await getUsageReport({ range: "30d", forceRefresh: true }); + assert.deepEqual(report.sessionBreakdown.map((s) => [s.sessionId, s.title, s.deleted]), [["sess-in", "In window", false]]); + assert.deepEqual( + [...(globalThis.__ompSessionScanCache?.values() ?? [])].map((entry) => entry.info.id), + ["sess-in"], + "a conversation without usage in the window is not read", + ); + }); +}); + +test("sessionBreakdown marks a conversation past the load ceiling as too large", async () => { + const { getUsageReport, USAGE_PARSER_VERSION } = await loadSubject(); + const { getUsageDatabase } = await jiti.import("./usage-db.ts"); + const { MAX_SESSION_LOAD_BYTES } = await jiti.import("./omp/session-files.ts"); + + await withTempSessionDir(async (dir) => { + const project = join(dir, "sessions", "test-project"); + mkdirSync(project, { recursive: true }); + const t = Date.now() - 60_000; + const file = join(project, "2026_big.jsonl"); + writeFileSync(file, [ + JSON.stringify({ type: "session", id: "sess-big", cwd: "/home/user/project-alpha", title: "Big chat", timestamp: new Date(t - 1000).toISOString() }), + assistantEntry("b1", t, "claude-opus-5-5", 100, 1), + "", + ].join("\n"), "utf8"); + // Sparse past the ceiling; recorded as already synced so the test does not parse a gigabyte. + truncateSync(file, MAX_SESSION_LOAD_BYTES + 1); + const stats = statSync(file); + const db = getUsageDatabase(); + db.prepare("INSERT INTO synced_files (file_path, mtime_ms, file_size, records_count, synced_at, parser_version) VALUES (?, ?, ?, 1, ?, ?)") + .run(file, stats.mtimeMs, stats.size, Date.now(), USAGE_PARSER_VERSION); + db.prepare(` + INSERT INTO usage_records (file_path, session_id, session_cwd, timestamp, provider, model, input_tokens, + output_tokens, reasoning_tokens, cache_read_tokens, cache_write_tokens, total_tokens, cost, cache_savings, + cost_quality, session_started) + VALUES (?, 'sess-big', '/home/user/project-alpha', ?, 'anthropic', 'claude-opus-5-5', + 100, 0, 0, 0, 0, 100, 1, 0, 'provider_reported', ?) + `).run(file, t, t); + + const report = await getUsageReport({ range: "30d" }); + assert.deepEqual( + report.sessionBreakdown.map((s) => [s.sessionId, s.title, s.deleted, s.tooLarge]), + [["sess-big", "Big chat", false, true]], + ); + }); +}); + test("time range bounds compute valid intervals", async () => { const { computeTimeRangeBounds } = await loadSubject(); diff --git a/lib/usage-types.ts b/lib/usage-types.ts index 2af274375..d5a8c8d78 100644 --- a/lib/usage-types.ts +++ b/lib/usage-types.ts @@ -145,6 +145,8 @@ export interface SessionUsageSummary { lastActiveAt: number; // ms timestamp of the newest request in the window /** The session is no longer in the session list (deleted), so it cannot be opened. */ deleted: boolean; + /** The session file is past omp-web's load ceiling (MAX_SESSION_LOAD_BYTES), so it cannot be opened here. */ + tooLarge: boolean; } export interface UsageReportScanInfo { From 854b8b2f7b52d89c639fde575e12a8b66fef369c Mon Sep 17 00:00:00 2001 From: OrwellVII <56531592+OrwellVII@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:36:57 +0800 Subject: [PATCH 3/4] fix(usage): do not open a conversation when a click ends a text selection in its row --- components/UsageConfig.sessions.test.mjs | 17 +++++++++++++++++ components/UsageConfig.tsx | 9 ++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/components/UsageConfig.sessions.test.mjs b/components/UsageConfig.sessions.test.mjs index 47cf79b18..ba26b0e63 100644 --- a/components/UsageConfig.sessions.test.mjs +++ b/components/UsageConfig.sessions.test.mjs @@ -12,6 +12,7 @@ const originalFetch = globalThis.fetch; afterEach(() => { cleanup(); globalThis.fetch = originalFetch; + window.getSelection()?.removeAllRanges(); }); const SESSION_COUNT = SESSION_PREVIEW_LIMIT + 5; @@ -99,6 +100,22 @@ test("the conversation tab lists the most expensive conversations first and open assert.deepEqual(opened, ["s0", "s3"]); }); +test("releasing a text selection in a row does not open it; a selection elsewhere does not block it", async () => { + const opened = []; + const { view } = await renderSessionsTab(opened); + const row = view.container.querySelector('tr[data-session-id="s3"]'); + + // Drag-selecting the title to copy it ends with a click on the row. + window.getSelection().selectAllChildren(row.querySelector("button")); + fireEvent.click(row.querySelector("td:nth-child(2)")); + fireEvent.click(row.querySelector("button")); + assert.deepEqual(opened, []); + + window.getSelection().selectAllChildren(view.container.querySelector('tr[data-session-id="s4"] td')); + fireEvent.click(row.querySelector("button")); + assert.deepEqual(opened, ["s3"], "the title button still opens it"); +}); + test("a deleted conversation is labelled and cannot be opened", async () => { const opened = []; const { view } = await renderSessionsTab(opened); diff --git a/components/UsageConfig.tsx b/components/UsageConfig.tsx index 096b29e81..ba6cc73a3 100644 --- a/components/UsageConfig.tsx +++ b/components/UsageConfig.tsx @@ -1127,7 +1127,14 @@ export function UsageConfig({ onOpenSession }: { onOpenSession?.(s.sessionId) : undefined} + onClick={openable ? (event) => { + // Releasing a drag that selected text in this row (to copy a title) opens nothing. + const selection = window.getSelection(); + const row = event.currentTarget; + if (selection && !selection.isCollapsed + && Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i)).some((range) => range.intersectsNode(row))) return; + onOpenSession?.(s.sessionId); + } : undefined} style={{ borderBottom: "1px solid var(--bg-subtle)", cursor: openable ? "pointer" : undefined }} > From 7b7c7ac21fa8cf19a7301c6836cdf054d056355e Mon Sep 17 00:00:00 2001 From: OrwellVII <56531592+OrwellVII@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:48:23 +0800 Subject: [PATCH 4/4] test(usage): drive the conversation breakdown tests with user-event --- components/UsageConfig.sessions.test.mjs | 49 +++++++++++++----------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/components/UsageConfig.sessions.test.mjs b/components/UsageConfig.sessions.test.mjs index ba26b0e63..4defadf74 100644 --- a/components/UsageConfig.sessions.test.mjs +++ b/components/UsageConfig.sessions.test.mjs @@ -2,7 +2,8 @@ import assert from "node:assert/strict"; import "../tests/setup-dom.mjs"; import test, { afterEach } from "node:test"; import React from "react"; -import { cleanup, fireEvent, render, waitFor } from "@testing-library/react/pure.js"; +import { cleanup, render, waitFor, within } from "@testing-library/react/pure.js"; +import userEvent from "@testing-library/user-event"; import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true }); @@ -65,18 +66,19 @@ async function renderSessionsTab(opened) { requests.push(String(url)); return { ok: true, json: async () => report() }; }; + const user = userEvent.setup(); const view = render(React.createElement(UsageConfig, { onOpenSession: (id) => opened.push(id) })); const tab = await waitFor(() => view.getByRole("button", { name: "CONVERSATION" })); - fireEvent.click(tab); + await user.click(tab); assert.equal(tab.getAttribute("aria-pressed"), "true"); - return { view, requests }; + return { view, requests, user }; } const rowIds = (container) => [...container.querySelectorAll("tr[data-session-id]")].map((tr) => tr.getAttribute("data-session-id")); test("the conversation tab lists the most expensive conversations first and opens one on click", async () => { const opened = []; - const { view, requests } = await renderSessionsTab(opened); + const { view, requests, user } = await renderSessionsTab(opened); assert.match(requests[0], /^\/api\/usage\?range=30d&/); // Server order (cost descending) is kept, capped at the preview limit. @@ -92,62 +94,65 @@ test("the conversation tab lists the most expensive conversations first and open assert.match(first.querySelector("td:nth-child(1)").textContent, /2026/); assert.equal(first.querySelector("td:nth-child(5)").textContent, "3"); - fireEvent.click(view.getByRole("button", { name: "Session 0" })); + await user.click(view.getByRole("button", { name: "Session 0" })); assert.deepEqual(opened, ["s0"], "the title button opens it once"); // Any cell of the row opens it too. - fireEvent.click(view.container.querySelector('tr[data-session-id="s3"] td:nth-child(2)')); + await user.click(view.container.querySelector('tr[data-session-id="s3"] td:nth-child(2)')); assert.deepEqual(opened, ["s0", "s3"]); }); test("releasing a text selection in a row does not open it; a selection elsewhere does not block it", async () => { const opened = []; - const { view } = await renderSessionsTab(opened); + const { view, user } = await renderSessionsTab(opened); const row = view.container.querySelector('tr[data-session-id="s3"]'); + const title = within(row).getByRole("button", { name: "Session 3" }); + const dragSelect = (target) => user.pointer([{ keys: "[MouseLeft>]", target, offset: 0 }, { offset: 3 }, { keys: "[/MouseLeft]" }]); - // Drag-selecting the title to copy it ends with a click on the row. - window.getSelection().selectAllChildren(row.querySelector("button")); - fireEvent.click(row.querySelector("td:nth-child(2)")); - fireEvent.click(row.querySelector("button")); + // Drag-selecting text in the row to copy it ends with a click on the row. + await dragSelect(row.querySelector("td:nth-child(2)")); + assert.equal(String(window.getSelection()), "$52"); assert.deepEqual(opened, []); - window.getSelection().selectAllChildren(view.container.querySelector('tr[data-session-id="s4"] td')); - fireEvent.click(row.querySelector("button")); + // Text selected in another row does not keep this one from opening. + await dragSelect(view.container.querySelector('tr[data-session-id="s4"] td:nth-child(2)')); + assert.equal(String(window.getSelection()), "$51"); + await user.click(title); assert.deepEqual(opened, ["s3"], "the title button still opens it"); }); test("a deleted conversation is labelled and cannot be opened", async () => { const opened = []; - const { view } = await renderSessionsTab(opened); + const { view, user } = await renderSessionsTab(opened); const deleted = view.container.querySelector('tr[data-session-id="s1"]'); assert.equal(deleted.querySelector("button"), null); assert.match(deleted.textContent, /Deleted/); - fireEvent.click(view.getByText("Session 1")); - fireEvent.click(deleted.querySelector("td:nth-child(2)")); + await user.click(view.getByText("Session 1")); + await user.click(deleted.querySelector("td:nth-child(2)")); assert.deepEqual(opened, []); }); test("a conversation too large to load is labelled and cannot be opened", async () => { const opened = []; - const { view } = await renderSessionsTab(opened); + const { view, user } = await renderSessionsTab(opened); const tooLarge = view.container.querySelector('tr[data-session-id="s2"]'); assert.equal(tooLarge.querySelector("button"), null); assert.match(tooLarge.textContent, /Too large/); assert.match(view.getByText("Session 2").getAttribute("title"), /too large to open/); - fireEvent.click(view.getByText("Session 2")); - fireEvent.click(tooLarge.querySelector("td:nth-child(2)")); + await user.click(view.getByText("Session 2")); + await user.click(tooLarge.querySelector("td:nth-child(2)")); assert.deepEqual(opened, []); }); test("show all lists every conversation and can collapse back to the top ones", async () => { - const { view } = await renderSessionsTab([]); + const { view, user } = await renderSessionsTab([]); - fireEvent.click(view.getByRole("button", { name: `Show all ${SESSION_COUNT} conversations` })); + await user.click(view.getByRole("button", { name: `Show all ${SESSION_COUNT} conversations` })); assert.equal(rowIds(view.container).length, SESSION_COUNT); assert.equal(rowIds(view.container).at(-1), `s${SESSION_COUNT - 1}`); - fireEvent.click(view.getByRole("button", { name: `Show top ${SESSION_PREVIEW_LIMIT} only` })); + await user.click(view.getByRole("button", { name: `Show top ${SESSION_PREVIEW_LIMIT} only` })); assert.equal(rowIds(view.container).length, SESSION_PREVIEW_LIMIT); });