diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..8eb7373bf 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, or is too large for omp-web to open, 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..4defadf74 --- /dev/null +++ b/components/UsageConfig.sessions.test.mjs @@ -0,0 +1,158 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test, { afterEach } from "node:test"; +import React from "react"; +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 }); +const { UsageConfig, SESSION_PREVIEW_LIMIT } = await jiti.import("./UsageConfig.tsx"); + +const originalFetch = globalThis.fetch; +afterEach(() => { + cleanup(); + globalThis.fetch = originalFetch; + window.getSelection()?.removeAllRanges(); +}); + +const SESSION_COUNT = SESSION_PREVIEW_LIMIT + 5; + +/** 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}`, + 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, + tooLarge: i === 2, + })); +} + +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 user = userEvent.setup(); + const view = render(React.createElement(UsageConfig, { onOpenSession: (id) => opened.push(id) })); + const tab = await waitFor(() => view.getByRole("button", { name: "CONVERSATION" })); + await user.click(tab); + assert.equal(tab.getAttribute("aria-pressed"), "true"); + 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, user } = 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), 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"); + + 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. + 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, 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 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, []); + + // 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, 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/); + 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, 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/); + 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, user } = await renderSessionsTab([]); + + 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}`); + + await user.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..ba6cc73a3 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,159 @@ export function UsageConfig() { )) ))} + + {breakdownView === "session" && + (sessionBreakdown.length === 0 ? ( + + + + ) : ( + visibleSessions.map((s) => { + 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", + minute: "2-digit", + }); + return ( + { + // 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 }} + > + + + + + + + ); + }) + ))}
- {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 ? ( + // The keyboard target; its click bubbles to the row, which opens the conversation. + + ) : ( + + {s.title} + + )} + {unavailable && ( + + {unavailable.label} + + )} +
+
+ {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..4a4de0ef1 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1690,6 +1690,15 @@ "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.tooLargeSession": "Too large", + "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..3aefc8c4c 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1649,6 +1649,15 @@ "usageConfig.model": "モデル", "usageConfig.day": "日付", "usageConfig.project": "プロジェクト", + "usageConfig.session": "セッション", + "usageConfig.requests": "リクエスト", + "usageConfig.lastActive": "最終アクティブ", + "usageConfig.openSession": "セッションを開く: {title}", + "usageConfig.deletedSession": "削除済み", + "usageConfig.deletedSessionHint": "このセッションは削除されているため開けません。", + "usageConfig.tooLargeSession": "大きすぎます", + "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..84339a31a 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1649,6 +1649,15 @@ "usageConfig.model": "模型", "usageConfig.day": "日期", "usageConfig.project": "项目", + "usageConfig.session": "会话", + "usageConfig.requests": "请求数", + "usageConfig.lastActive": "最后活跃", + "usageConfig.openSession": "打开会话:{title}", + "usageConfig.deletedSession": "已删除", + "usageConfig.deletedSessionHint": "该会话已删除,无法再打开。", + "usageConfig.tooLargeSession": "过大", + "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..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); diff --git a/lib/usage-db.ts b/lib/usage-db.ts index 128857d28..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 { listSessionArtifactTranscripts, listSessionFiles } from "./omp/session-files"; +import { + listSessionArtifactTranscripts, + listSessionFiles, + MAX_SESSION_LOAD_BYTES, + scanSessionInfoCached, +} from "./omp/session-files"; import { formatChartDateLabel, formatFullDateLabel, @@ -19,6 +24,8 @@ import type { ModelUsageSummary, ProjectUsageSummary, ProviderUsageSummary, + SessionModelUsage, + SessionUsageSummary, TimeSeriesPoint, UsageQueryOptions, UsageRecord, @@ -380,6 +387,22 @@ 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; + +/** + * 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. */ @@ -754,6 +777,88 @@ 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` and `file_path` + // columns take the newest request's values (SQLite's single-max() rule). + const sessionRows = db + .prepare( + ` + WITH per_model AS ( + SELECT + session_id, + provider, + 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 + 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, + filePath, + 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; + filePath: string; + cost: number; + tokens: number; + requestsCount: number; + models: string; + }>; + + // 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 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, + ); + 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: info === undefined, + tooLarge: info !== undefined && info.size > MAX_SESSION_LOAD_BYTES, + }; + }); + // Scan info const totalSyncedRow = db.prepare("SELECT COUNT(*) as c FROM synced_files").get() as { c: number }; const inWindowSyncedRow = db @@ -780,6 +885,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..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"; @@ -412,6 +412,171 @@ 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(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"); + 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("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 33c292f50..d5a8c8d78 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,37 @@ 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; + /** 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 { transcriptsScanned: number; transcriptsOutsideWindow: number; @@ -135,6 +166,8 @@ export interface UsageReport { modelBreakdown: ModelUsageSummary[]; dayBreakdown: DayUsageSummary[]; projectBreakdown: ProjectUsageSummary[]; + /** Per conversation, most expensive first. */ + sessionBreakdown: SessionUsageSummary[]; scanInfo: UsageReportScanInfo; }