A local-first multi-agent app development platform, built on PenguinHarness
fix(server,web): price the Trace panel's rounds at the tier each request ran in (#659)
Yaowei Zheng85e1f4ed4066
diff --git a/changelog/unreleased/2026-09-10-trace-panel-tiered-cost.md b/changelog/unreleased/2026-09-10-trace-panel-tiered-cost.mdnew file mode 100644index 00000000..cabe8d2c--- /dev/null+++ b/changelog/unreleased/2026-09-10-trace-panel-tiered-cost.md@@ -0,0 +1,17 @@+# The Trace panel prices each request at the tier it ran in++- **Date:** 2026-09-10+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#659](https://github.com/Prism-Shadow/penguin-harness/pull/659)++[中文版](2026-09-10-trace-panel-tiered-cost.zh.md)++The Trace panel's per-turn and per-file costs are now priced by the server with the cost center's own rule, so a Session's Trace files add up to the cost the conversation toolbar and the cost center show for the same requests. Before this change the panel priced every request at the Project's stored rate, while the toolbar and the cost center billed each request at the tier its own timestamp fell in — for a model on a time-based schedule (DeepSeek's off-peak half price) the panel's files therefore added up to more than the toolbar showed, by half the cost of every request that ran off-peak.++## Details++- The Trace analysis response carries a `cost` per turn and a file-level `cost` (USD), each Request priced at the Project's current rates for the file's model, at the tier that Request's timestamp fell in — the same pricing lookup and the same tier rule the cost center applies to the usage row the same `token_usage` produced. A model with no pricing, or a legacy Trace head naming no provider, carries no `cost`.+- The Trace file view reads those figures instead of pricing the turns itself, and no longer fetches the Project's model list.+- The pricing formula and the per-record tier decision are shared helpers of the usage service, so the SQL aggregation and the per-file analysis price one request the same way.+- The docs note that the Trace view and the cost statistics share the pricing rule, not only the data.diff --git a/changelog/unreleased/2026-09-10-trace-panel-tiered-cost.zh.md b/changelog/unreleased/2026-09-10-trace-panel-tiered-cost.zh.mdnew file mode 100644index 00000000..34d7acbc--- /dev/null+++ b/changelog/unreleased/2026-09-10-trace-panel-tiered-cost.zh.md@@ -0,0 +1,17 @@+# 轨迹面板按每次请求实际所处的档位计价++- **Date:** 2026-09-10+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#659](https://github.com/Prism-Shadow/penguin-harness/pull/659)++[English](2026-09-10-trace-panel-tiered-cost.md)++轨迹面板的逐轮成本与单文件成本改由服务端按成本中心的同一口径计价,因此一个 Session 各 Trace 文件的成本之和,与对话页顶部统计、成本中心为同一批请求给出的数字一致。此前面板把每次请求都按 Project 存储的价格计价,而顶部统计与成本中心按每次请求自己的时间戳判定档位——对分时段计费的模型(DeepSeek 空闲时段半价),面板各文件之和会高于顶部统计,差额正是每次空闲时段请求成本的一半。++## 细节++- Trace 分析响应新增逐轮 `cost` 与文件级 `cost`(USD):每次 Request 按 Project 当前为该文件模型配置的价格、以该 Request 自己的时间戳所处档位计价——与成本中心为同一条 `token_usage` 落库行计价时所用的价格查询与档位规则完全相同。模型未配置价格、或旧版 Trace 头部没有 provider 时不带 `cost`。+- Trace 文件视图直接读取这些数字,不再自行计价,也不再拉取 Project 的模型列表。+- 计价公式与逐条记录的档位判定抽为 usage service 的共享函数,SQL 聚合与逐文件分析对同一次请求的计价由此一致。+- 文档补充说明:Trace 视图与成本统计不仅共用数据,也共用计价口径。diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.mdindex 607dcf25..f49e3590 100644--- a/packages/docs/content/sessions-and-traces.en.md+++ b/packages/docs/content/sessions-and-traces.en.md@@ -100,4 +100,4 @@ Each content message's opaque provider `fidelity` payload (thinking signatures,## Observability-Every approval decision (`approval_decision`), abort (`abort`), compaction (`compaction_begin` / `compaction_end`), and `token_usage` lands in the Trace as an event. The Web Trace view and the usage/cost statistics are both derived from this same data — there is no second source of truth; see the [Web App Guide](/web-app). The approval mechanism itself is covered in [Tools & Approval](/tools). Trace files can also be moved across deployments: a conversation's Trace panel exports the selected file (downloaded verbatim as JSONL), and System settings → General imports one back under an Agent — an import whose session id already exists under that Agent is rejected, so an imported file always becomes index 001 of a new Session.+Every approval decision (`approval_decision`), abort (`abort`), compaction (`compaction_begin` / `compaction_end`), and `token_usage` lands in the Trace as an event. The Web Trace view and the usage/cost statistics are both derived from this same data — there is no second source of truth — and priced by the same rule: the Project's current rates for the model, at the tier each request's own timestamp fell in, so a Trace file's per-turn costs add up to what the conversation toolbar and the cost center show for the same requests; see the [Web App Guide](/web-app). The approval mechanism itself is covered in [Tools & Approval](/tools). Trace files can also be moved across deployments: a conversation's Trace panel exports the selected file (downloaded verbatim as JSONL), and System settings → General imports one back under an Agent — an import whose session id already exists under that Agent is rejected, so an imported file always becomes index 001 of a new Session.diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.mdindex 84e356da..34c88011 100644--- a/packages/docs/content/sessions-and-traces.zh.md+++ b/packages/docs/content/sessions-and-traces.zh.md@@ -98,4 +98,4 @@ Web 的 `/model` 命令按 `/agent` 交接的方式换模型:选中模型只## 可观测性-每一次审批决策(`approval_decision`)、中断(`abort`)、压缩(`compaction_begin` / `compaction_end`)与 `token_usage` 都作为事件落入 Trace。Web 的 Trace 视图与用量、成本统计均由这同一份数据派生,不存在第二事实来源;见 [Web App 指南](/web-app)。审批机制本身见[工具与审批](/tools)。Trace 文件还可以在部署之间迁移:在对话的 Trace 面板中可将选中的文件导出(按原样下载为 JSONL),在系统设置的「常规」页可导入到某个 Agent 下——若该 Agent 已存在同名 Session 则导入被拒绝,因此导入文件总是成为一个新 Session 的 001 号文件。+每一次审批决策(`approval_decision`)、中断(`abort`)、压缩(`compaction_begin` / `compaction_end`)与 `token_usage` 都作为事件落入 Trace。Web 的 Trace 视图与用量、成本统计均由这同一份数据派生,不存在第二事实来源,计价口径也相同:按 Project 当前的模型价格、以每次请求自己的时间戳判定分时段档位,因此一个 Trace 文件的逐轮成本之和,就是对话页顶部与成本中心为同一批请求给出的数字;见 [Web App 指南](/web-app)。审批机制本身见[工具与审批](/tools)。Trace 文件还可以在部署之间迁移:在对话的 Trace 面板中可将选中的文件导出(按原样下载为 JSONL),在系统设置的「常规」页可导入到某个 Agent 下——若该 Agent 已存在同名 Session 则导入被拒绝,因此导入文件总是成为一个新 Session 的 001 号文件。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex ed1deed9..0bee8ba2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -2493,6 +2493,16 @@ export interface TraceTaskStats {* must be counted; consistent with the Chat page's tokensByBucket.*/tokens: { cacheRead: number; cacheWrite: number; output: number };+ /**+ * This turn's cost in USD: each Request's three buckets at the Project's current rates for+ * the file's model, at the tier that Request's own timestamp fell in — the rule and the+ * price lookup the cost center applies to the usage row the same `token_usage` produced,+ * so this figure, the toolbar's and the cost center's agree on what a request cost. Present+ * on every turn of a priced file (a turn with no Request reads 0); absent when the model has+ * no pricing or the file's head names no provider, and then absent from the response's+ * total as well.+ */+ cost?: number;/*** Total LLM generation duration for this turn (the denominator for output TPS; human* approval wait already deducted). The numerator is simply `tokens.output`: since@@ -2630,6 +2640,11 @@ export interface TraceAnalysisResponse {* see `TraceTaskStats.toolMs`.*/toolMs: number;+ /**+ * The file's cost in USD: the sum of the turns' `cost` (compaction turns included, the+ * scope every total here shares). Absent exactly when the turns carry no `cost`.+ */+ cost?: number;requests: RequestSpan[];/** Token / duration aggregated per Task (used directly by the Trace page's context ring and per-turn TPS). */tasks: TraceTaskStats[];diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 777ce2a8..474243e6 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -911,6 +911,10 @@ export function buildAppDeps(index: traceIndex,sessions: sessionsRepo,sources: sessionSources,+ // The one price table: the analysis costs a file's Requests with the lookup the cost+ // center prices usage rows with, so the Trace panel and the toolbar never disagree.+ lookupPricing: (projectId, provider, modelId) =>+ projectConfigService.getPricing(projectId, provider, modelId),});const workspaceFiles = new WorkspaceFilesService();// Per-process secret: preview tokens are short-lived, so losing them on restart isdiff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex 685ab131..bcb84a08 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -55,6 +55,8 @@ import type { TraceFileRow, TraceSessionRow } from "../db/repos/trace-index.js";import { HttpError } from "../http/errors.js";import { formatLocalDate } from "../internal/dates.js";import type { SessionSources } from "../runtime/session-sources.js";+import { ratesAt, requestCostUsd } from "./usage-service.js";+import type { PricingLookup, TieredRates } from "./usage-service.js";import {cloneScanState,deserializePrefix,@@ -246,6 +248,13 @@ export interface TraceServiceDeps {sessions?: TraceSessionIndex;/** Optional (narrow tests may omit): the shared in-process Session-origin registry (single source of truth for `source`). */sources?: SessionSources;+ /**+ * Optional (narrow tests may omit): the Project's current price for a paired reference —+ * the same lookup the cost center prices `usage_records` with, so the analysis' per-turn+ * cost and the toolbar's figure come from one price table. Absent, the analysis carries no+ * cost at all.+ */+ lookupPricing?: PricingLookup;/*** Test observability: called with the path of every Trace shard this service reads* from disk (windowed-read tests assert an old-window request never touches the@@ -842,6 +851,32 @@ export class TraceService {};}+ /**+ * The price table the analysis costs a file's Requests against: the Project's current rates+ * for the model named by the file's own `session_meta` head, in both tiers. Null when there+ * is no lookup, when the model has no pricing, and for a head that names no provider — such+ * a Trace is legacy data (core refuses to resume it), and the id alone can exist under+ * several providers at different prices, so nothing is priced rather than a first match.+ */+ private async filePricing(+ projectId: string,+ messages: OmniMessage[],+ ): Promise<{ provider: string; modelId: string; rates: TieredRates } | null> {+ if (this.deps.lookupPricing === undefined) return null;+ const meta = messages.find(+ (m) => isSessionMeta(m) && (m.origin === undefined || m.origin.length === 0),+ );+ if (meta === undefined) return null;+ const { provider, model_id: modelId } = meta.payload as {+ provider?: unknown;+ model_id?: unknown;+ };+ if (typeof provider !== "string" || provider === "") return null;+ if (typeof modelId !== "string" || modelId === "") return null;+ const rates = await this.deps.lookupPricing(projectId, provider, modelId);+ return rates === undefined ? null : { provider, modelId, rates };+ }+/** Performance analysis: derived from a single Trace file. */async analyze(projectId: string,@@ -850,6 +885,7 @@ export class TraceService {index: number,): Promise<TraceAnalysisResponse> {const messages = await this.readFileByIndex(projectId, agentId, sessionId, index);+ const pricing = await this.filePricing(projectId, messages);const requests: RequestSpan[] = [];let openRequest: RequestSpan | null = null;@@ -914,6 +950,9 @@ export class TraceService {startTs: "",endTs: "",tokens: { cacheRead: 0, cacheWrite: 0, output: 0 },+ // A priced file states a cost for every turn, a turn with no Request included: the+ // card then reads $0 rather than "no price", which is what an absent field means.+ ...(pricing !== null ? { cost: 0 } : {}),llmMs: 0,toolMs: 0,};@@ -1192,6 +1231,26 @@ export class TraceService {t.tokens.cacheRead += request?.cache_read ?? 0;t.tokens.cacheWrite += request?.cache_write ?? 0;t.tokens.output += request?.output ?? 0;+ if (pricing !== null) {+ // Priced per Request, at the tier this Request's own timestamp fell in — the+ // rule the cost center applies to the usage row this same event produced, so+ // the two figures for one request are the same figure.+ t.cost =+ (t.cost ?? 0) ++ requestCostUsd(+ {+ cacheRead: request?.cache_read ?? 0,+ cacheWrite: request?.cache_write ?? 0,+ output: request?.output ?? 0,+ },+ ratesAt(+ pricing.rates,+ pricing.provider,+ pricing.modelId,+ new Date(msg.timestamp),+ ),+ );+ }if (!compactionActive) {// The context snapshot only takes non-compaction Requests: tokens// consumed by compaction aren't the post-compaction context@@ -1361,10 +1420,12 @@ export class TraceService {// follows above, so a reader adding up the turn cards lands on the totals.const apiMs = tasks.reduce((sum, t) => sum + t.llmMs, 0);const toolMs = tasks.reduce((sum, t) => sum + t.toolMs, 0);+ const cost = pricing !== null ? tasks.reduce((sum, t) => sum + (t.cost ?? 0), 0) : undefined;return {elapsedMs,apiMs,toolMs,+ ...(cost !== undefined ? { cost } : {}),requests,tasks,toolCalls,diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.tsindex 97479e4c..c691aa17 100644--- a/packages/server/src/services/usage-service.ts+++ b/packages/server/src/services/usage-service.ts@@ -30,7 +30,11 @@ import type {UsageSeriesPoint,} from "../api/types.js";import type { ErrorFilter, ErrorsRepo } from "../db/repos/errors.js";-import { offPeakScheduledRefs } from "@prismshadow/penguin-core/model-catalog";+import {+ catalogEntryFor,+ offPeakAt,+ offPeakScheduledRefs,+} from "@prismshadow/penguin-core/model-catalog";import type {UsageRepo,UsageModelSums,@@ -137,17 +141,45 @@ export interface UsageErrorsClearQuery {includeGlobalErrors?: boolean;}-/** Cost formula: sum of the three buckets at the tier these Tokens ran in, USD per million. */-function costOf(sums: UsageModelSums, tiered: TieredRates): number {- const rates = sums.peak ? tiered.peak : tiered.offPeak;+/** The "model price" formula: the three buckets at the given rates (USD per million Tokens), in USD. */+export function requestCostUsd(+ counts: { cacheRead: number; cacheWrite: number; output: number },+ rates: PricingRates,+): number {return (- (sums.cacheRead * rates.cacheRead +- sums.cacheWrite * rates.cacheWrite +- sums.output * rates.output) /+ (counts.cacheRead * rates.cacheRead ++ counts.cacheWrite * rates.cacheWrite ++ counts.output * rates.output) /1e6);}+/**+ * The rates one usage record is billed at, decided from the record's own timestamp: the+ * off-peak tier when the reference carries a catalog schedule and `at` falls outside its peak+ * windows, the peak tier otherwise. For a reference with no schedule, or whose stored price is+ * no longer the catalog's, the two tiers are the same figure (see project-config-service's+ * `tieredRates`), so the decision changes nothing there. `peakExpr` in the usage repo is this+ * rule written in SQL for the aggregations; the two must agree record for record, which is why+ * an unreadable timestamp — which the repo never stores — takes the peak tier rather than+ * inventing a discount.+ */+export function ratesAt(+ tiered: TieredRates,+ provider: string,+ modelId: string,+ at: Date,+): PricingRates {+ const schedule = catalogEntryFor(provider, modelId)?.offPeakDiscount;+ if (schedule === undefined || Number.isNaN(at.getTime())) return tiered.peak;+ return offPeakAt(schedule, at) ? tiered.offPeak : tiered.peak;+}++/** Cost formula: sum of the three buckets at the tier these Tokens ran in, USD per million. */+function costOf(sums: UsageModelSums, tiered: TieredRates): number {+ return requestCostUsd(sums, sums.peak ? tiered.peak : tiered.offPeak);+}+/** In-process Map key for a paired reference (\0-separated, the same style as session-manager's agentKey; never persisted). */function refKey(provider: string, modelId: string): string {return `${provider}\0${modelId}`;diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex 535e7bd4..8acb4f83 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -16,6 +16,7 @@ import { SessionSources } from "../src/runtime/session-sources.js";import { TraceIndexService } from "../src/services/trace-index.js";import { TraceService } from "../src/services/trace-service.js";import type { TraceSessionIndex } from "../src/services/trace-service.js";+import type { PricingLookup } from "../src/services/usage-service.js";import type { AppEnv } from "../src/auth/middleware.js";import { ADMIN_USER_ID } from "../src/auth/service.js";import type { ServerConfig } from "../src/config.js";@@ -210,7 +211,11 @@ export function apiClient(app: Hono<AppEnv>, cookie: string) {*/export function makeTraceHarness(root: string,- opts: { sessions?: TraceSessionIndex; sources?: SessionSources } = {},+ opts: {+ sessions?: TraceSessionIndex;+ sources?: SessionSources;+ lookupPricing?: PricingLookup;+ } = {},): {traceIndex: TraceIndexService;service: TraceService;@@ -226,6 +231,7 @@ export function makeTraceHarness(const service = new TraceService(root, {index: traceIndex,...(opts.sessions !== undefined ? { sessions: opts.sessions } : {}),+ ...(opts.lookupPricing !== undefined ? { lookupPricing: opts.lookupPricing } : {}),sources,observeShardRead: (p) => shardReads.push(p),});diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.tsindex bd1b8834..cf65d46b 100644--- a/packages/server/test/trace-service.test.ts+++ b/packages/server/test/trace-service.test.ts@@ -37,7 +37,12 @@ import type {const legacyEnd = (status: string) => requestEnd(status as StopReason);import type { TraceService } from "../src/services/trace-service.js";import type { SessionRow } from "../src/db/repos/sessions.js";+import { openDatabase } from "../src/db/database.js";+import { ErrorsRepo } from "../src/db/repos/errors.js";+import { UsageRepo } from "../src/db/repos/usage.js";import { SessionSources } from "../src/runtime/session-sources.js";+import { UsageService } from "../src/services/usage-service.js";+import type { PricingLookup } from "../src/services/usage-service.js";import { makeTempRoot, makeTraceHarness, writeTraceFile } from "./helpers.js";const P = "project-t";@@ -201,6 +206,135 @@ describe("trace-service", () => {]);});+ /** One completed text turn: Prompt, one Request, and its usage stamped at `ts` plus three seconds. */+ const priceTurn = (ts: string, request: TokenCounts): OmniMessage[] => {+ const t = Date.parse(ts);+ const plus = (s: number) => new Date(t + s * 1000).toISOString();+ return [+ at(ts, userText("go")),+ at(plus(1), requestBegin()),+ at(plus(2), assistantText("ok")),+ at(plus(3), requestEnd("completed")),+ at(plus(3), tokenUsage(request, request)),+ ];+ };++ it("prices each Request at the tier its own timestamp ran in, and the file adds up to what the cost center bills the same rows", async () => {+ // A DeepSeek reference carries the catalog's Beijing-hours schedule; the lookup answers+ // both tiers, as project-config-service does for a row still at the catalog's price.+ const REF = { provider: "deepseek", model_id: "deepseek-v4-flash" };+ const lookups: string[] = [];+ const lookup: PricingLookup = async (projectId, provider, modelId) => {+ lookups.push(`${projectId}/${provider}/${modelId}`);+ return {+ peak: { cacheRead: 1, cacheWrite: 2, output: 4 },+ offPeak: { cacheRead: 0.5, cacheWrite: 1, output: 2 },+ };+ };+ const priced = makeTraceHarness(root, { lookupPricing: lookup });+ const usage = buckets(10, 1, 5);+ // Tuesday 10:30 Beijing (peak), Tuesday 21:00 Beijing (off-peak), Sunday 11:00 Beijing+ // (an hour a weekday bills at peak, off-peak on a weekend).+ const stamps = [+ "2026-07-07T02:30:00.000Z",+ "2026-07-07T13:00:00.000Z",+ "2026-07-12T03:00:00.000Z",+ ];+ try {+ await writeTraceFile(root, P, A, "2026-07-07", S, 1, [+ sessionMeta(metaPayload(REF)),+ ...stamps.flatMap((ts) => priceTurn(ts, usage)),+ ]);+ const a = await priced.service.analyze(P, A, S, 1);+ const peakCost = (10 * 1 + 1 * 2 + 5 * 4) / 1e6;+ expect(a.tasks.map((t) => t.cost)).toEqual([peakCost, peakCost / 2, peakCost / 2]);+ expect(a.cost).toBeCloseTo(peakCost * 2, 12);+ expect(lookups).toEqual([`${P}/deepseek/deepseek-v4-flash`]);++ // The same three requests as usage rows, priced by the cost center's session grouping —+ // the figure the conversation toolbar shows — land on the file's total.+ const db = openDatabase(":memory:");+ try {+ const rows = new UsageRepo(db);+ for (const ts of stamps) {+ const at = new Date(Date.parse(ts) + 3000).toISOString();+ rows.insert({+ ts: at,+ date: at.slice(0, 10),+ projectId: P,+ agentId: A,+ sessionId: S,+ originSessionId: null,+ provider: REF.provider,+ modelId: REF.model_id,+ cacheRead: usage.cache_read,+ cacheWrite: usage.cache_write,+ output: usage.output,+ total: usage.total,+ });+ }+ const center = new UsageService(rows, new ErrorsRepo(db), lookup, () => new Date());+ const res = await center.query(P, { groupBy: "session" });+ expect(res.groups.find((g) => g.key === S)?.cost).toBeCloseTo(a.cost!, 12);+ } finally {+ db.close();+ }+ } finally {+ priced.close();+ }+ });++ it("a model with no schedule bills every hour at its one rate; no pricing, or a head naming no provider, means no cost at all", async () => {+ const lookups: string[] = [];+ const priced = makeTraceHarness(root, {+ lookupPricing: async (_projectId, provider, modelId) => {+ lookups.push(`${provider}/${modelId}`);+ // A second tier the schedule gate must never reach for an unscheduled reference.+ return modelId === "m1"+ ? {+ peak: { cacheRead: 1, cacheWrite: 1, output: 1 },+ offPeak: { cacheRead: 0, cacheWrite: 0, output: 0 },+ }+ : undefined;+ },+ });+ try {+ // Sunday 11:00 Beijing: off-peak for a scheduled model, just an hour for this one.+ await writeTraceFile(root, P, A, "2026-07-12", S, 1, [+ sessionMeta(metaPayload()),+ ...priceTurn("2026-07-12T03:00:00.000Z", buckets(10, 1, 5)),+ at("2026-07-12T03:01:00.000Z", userText("interrupted before any request")),+ ]);+ const flat = await priced.service.analyze(P, A, S, 1);+ expect(flat.tasks.map((t) => t.cost)).toEqual([(10 + 1 + 5) / 1e6, 0]);+ expect(flat.cost).toBeCloseTo((10 + 1 + 5) / 1e6, 12);++ await writeTraceFile(root, P, A, "2026-07-12", S, 2, [+ sessionMeta(metaPayload({ model_id: "m-unpriced" })),+ ...priceTurn("2026-07-12T03:10:00.000Z", buckets(10, 1, 5)),+ ]);+ const unpriced = await priced.service.analyze(P, A, S, 2);+ expect(unpriced.tasks.map((t) => t.cost)).toEqual([undefined]);+ expect(unpriced.cost).toBeUndefined();++ const legacy = metaPayload({ model_id: "m1" }) as Partial<SessionMetaPayload>;+ delete legacy.provider;+ await writeTraceFile(root, P, A, "2026-07-12", S, 3, [+ sessionMeta(legacy as SessionMetaPayload),+ ...priceTurn("2026-07-12T03:20:00.000Z", buckets(10, 1, 5)),+ ]);+ const noProvider = await priced.service.analyze(P, A, S, 3);+ expect(noProvider.cost).toBeUndefined();+ expect(lookups).toEqual(["custom/m1", "custom/m-unpriced"]);+ } finally {+ priced.close();+ }+ // The default harness has no lookup: nothing is priced.+ const plain = await service.analyze(P, A, S, 1);+ expect(plain.cost).toBeUndefined();+ expect(plain.tasks.every((t) => t.cost === undefined)).toBe(true);+ });+it("the Task context snapshot takes the turn's last Request, not a sum across its Requests", async () => {// Two Requests within one Task (a tool call triggers another round): each// input **re-carries the entire history**, so 60k → 65k is the contextdiff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsxindex 3a0ade63..61a81490 100644--- a/packages/web/src/features/traces/trace-file-view.tsx+++ b/packages/web/src/features/traces/trace-file-view.tsx@@ -13,7 +13,9 @@* icon, hover shows the hit rate = cache hit ÷ input), this round's output,* plus tool-call count / cost / duration / output TPS. The conversation* page's stats row only gives input/output totals — cache composition and- * this kind of debugging detail belongs here.+ * this kind of debugging detail belongs here. Every figure, cost included, is+ * the server's: the analysis prices each round with the cost center's rule,+ * so the file's total is what the toolbar shows for the same requests.** Task attribution: model segments/tool spans carry their own taskIndex* (computed by the server), and messages fall into a Task's time range by@@ -24,7 +26,6 @@import { useEffect, useMemo, useRef, useState } from "react";import type { OmniMessage } from "@prismshadow/penguin-core/omnimessage";import type {- ModelsResponse,TraceAnalysisResponse,TraceModelSegment,TraceOtherSpan,@@ -213,7 +214,6 @@ export function TraceFileView({/** events' starting index within the file (pagination offset): used to align with analysis.tasks' index ranges. */const [eventsOffset, setEventsOffset] = useState(0);const [total, setTotal] = useState(0);- const [models, setModels] = useState<ModelsResponse | null>(null);const [error, setError] = useState<string | null>(null);const [collapsed, setCollapsed] = useState<ReadonlySet<number>>(new Set());/** Message row pinned highlighted after a bar-click jump; auto-clears when its timer fires (independent of hover highlighting, and can stack with it). */@@ -270,47 +270,11 @@ export function TraceFileView({};}, [projectId, agentId, sessionId, index, reloadSignal]);- // Pricing is a PROJECT-level catalog, so it is fetched per project and deliberately left out- // of the load above: no turn changes it, and riding along there would refetch the whole- // catalog on every settled turn. It is optional and allowed to fail — a project whose models- // cannot be listed simply shows no cost column, and that is not the view's error.- useEffect(() => {- let cancelled = false;- void api- .getModels(projectId)- .then((m) => {- if (!cancelled) setModels(m);- })- .catch(() => undefined);- return () => {- cancelled = true;- };- }, [projectId]);-- // Pricing for the session's Model (main session only; sub-session Tokens- // live in their own Trace and aren't part of this file): session_meta carries a paired- // reference (provider + model_id), matched against model config by that whole pair.- // A Trace whose session_meta has no provider is legacy data (core refuses to resume it- // for the same reason) — the model_id alone identifies nothing, since the same id can- // exist under several providers at different prices, so no pricing is shown rather than- // an arbitrary first match.- const pricing = useMemo(() => {- const meta = events.find((m) => m.type === "session_meta");- const ref = meta ? (meta.payload as { model_id?: string; provider?: string }) : undefined;- if (!ref?.model_id || !ref.provider) return undefined;- return models?.models.find((m) => m.modelId === ref.model_id && m.provider === ref.provider)- ?.pricing;- }, [events, models]);-- const costOf = (b: Buckets): number | null => {- if (!pricing) return null;- return (- (b.cacheRead * pricing.cacheRead +- b.cacheWrite * pricing.cacheWrite +- b.output * pricing.output) /- 1e6- );- };+ // Cost is not priced here: the analysis carries each round's cost (and the file's), priced by+ // the server with the cost center's own rule — the Project's current rates for the file's+ // model, at the tier each Request's timestamp fell in — so what this file adds up to is what+ // the conversation toolbar shows for the same requests. An unpriced model (or a legacy head+ // naming no provider) simply carries no cost, and formatMoney renders that as a dash.// Session context window (the upper bound for each round's donut ring): read once from session_meta, falling back to 128000 if unconfigured.const contextMax = useMemo(() => {@@ -508,7 +472,7 @@ export function TraceFileView({<div><SummaryRowlabel={S.common.cost}- value={formatMoney(costOf(global.buckets), currency)}+ value={formatMoney(analysis.cost ?? null, currency)}/><SummaryRowlabel={S.chat.statElapsed}@@ -584,7 +548,7 @@ export function TraceFileView({/><StatChipicon={STAT_ICONS.cost}- value={formatMoney(costOf(tokens), currency)}+ value={formatMoney(st?.cost ?? null, currency)}label={`${S.common.cost}(${currency})`}/><StatChipdiff --git a/packages/web/test/trace-refresh.test.ts b/packages/web/test/trace-refresh.test.tsindex 2d06eea6..5c72df85 100644--- a/packages/web/test/trace-refresh.test.ts+++ b/packages/web/test/trace-refresh.test.ts@@ -196,16 +196,13 @@ describe("what a settled-turn refresh must leave alone", () => {expect(fileView).toMatch(/\{error !== null && <p /);});- it("leaves the project's model catalog out of the refresh, on an effect of its own", () => {- const load = fileView.slice(- fileView.indexOf("useEffect(() => {", fileView.indexOf("const fileKey")),- );- // Pricing is a project-level catalog no turn produces: refetching it per settled turn was- // waste, and the `?? prev` guard that kept a failed refetch from dropping the cost column- // went with it.- expect(load.slice(0, load.indexOf("\n }, ["))).not.toContain("getModels");- expect(fileView).not.toContain("setModels((prev)");- const pricing = fileView.slice(fileView.indexOf("getModels(projectId)"));- expect(/\n {2}\}, \[([^\]]*)\]/.exec(pricing)?.[1]).toBe("projectId");+ it("prices nothing itself: cost is read off the analysis, and no model catalog is fetched", () => {+ // The server prices each round with the cost center's rule (the Project's rates, at the+ // tier the request's own timestamp fell in); a client-side price table would be a second+ // rule that disagrees with the toolbar as soon as a schedule applies.+ expect(fileView).not.toContain("getModels");+ expect(fileView).not.toContain("pricing.cacheRead");+ expect(fileView).toContain("formatMoney(analysis.cost ?? null, currency)");+ expect(fileView).toContain("formatMoney(st?.cost ?? null, currency)");});});