A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): usage charts as smooth time series with range and precision controls (#371)
Yaowei Zhenge86a8c29c738
diff --git a/changelog/unreleased/2026-08-20-usage-charts.md b/changelog/unreleased/2026-08-20-usage-charts.mdnew file mode 100644index 00000000..94c775c7--- /dev/null+++ b/changelog/unreleased/2026-08-20-usage-charts.md@@ -0,0 +1,42 @@+# Usage charts rebuilt as time series with range and precision controls++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#371](https://github.com/Prism-Shadow/penguin-harness/pull/371)+- **Breaking:** yes — `GET /usage` no longer returns `trend`, `byAgent` or `success`, and the per-status failure breakdown `success` carried is gone.++[中文版](2026-08-20-usage-charts.zh.md)++Rebuilt the cost center's charts around one shared time axis. The page gained a date-range preset — trailing "last hour" and "last 24 hours" windows, calendar last 7 / 30 / 90 days (7 days is the default), or a custom pair of dates. The range alone decides the precision the series is drawn at — per minute for the last hour, hourly for the last 24 hours, daily for the calendar presets, and week or month for a long custom range — so there is no second control to keep in step with the first. Every chart draws over that range:++- The share pie and the per-model progress bars were replaced by **two requests + success-rate charts**, side by side: one broken down by Agent, one by Model. In each, a bucket's requests are a bar stacked one segment per entity against the left count axis, and every entity's success rate is its own dashed line against the right-hand 0–100% axis in the same hue — dashed for the same reason the Token chart's curve is, to mark a stroke as belonging to the right axis — with the legend underneath. Both breakdowns are on screen at once — there is no dimension toggle, and neither chart opens on an aggregate total. The top four entities are named, one CVD-checked hue each, and the rest fold into a neutral series whose label carries how many it folded. Three ways to single out one entity, all fading the rest: hover one of its bar segments, hover its rate line, or hover its legend item. The lines are drawn above the bars and answer the pointer above them too, so a line is never lost behind a tall segment.+- The Token chart kept its three-segment stacked bars and gained the cache hit rate as a dashed line drawn in front of the bars on its own right-hand 0–100% axis. Hovering anywhere in a column reports the whole bucket (all three Token counts plus the hit rate), hovering one segment singles it out, and hovering the line singles out the line. Bars shrink to fit the card instead of scrolling horizontally.+- Cost stayed a straight polyline with a dot on every point (plus the area fill), over the selected range.++Every line on the page is straight segments between its points, with no smoothing anywhere, and all of them are drawn at the same stroke width — no line is heavier than another because it was written later. Charts never scroll; the only global controls above them are the Agent, model and range selectors. The errors panel dropped its scroll box — height is bounded by pagination alone, and the server-supplied first page shrank from 20 rows to 10.++## Buckets with nothing in them++"Empty" means two different things here, and they get two different answers.++**A bucket with no rate is drawn, not read.** An entity that made no request in a bucket has no success rate there, and a bucket with no cache traffic has no hit rate; the line is carried across at the top of the axis so the stroke stays continuous. That is a drawing choice about a shape, and nothing more — the hover table prints a dash for the same bucket, never a percentage. A real 0% still prints 0%: requests were made and every one of them failed, which is a fact about the data rather than a hole in it.++**A bucket that recorded nothing at all is not drawn.** Every chart plots only the intervals that have values, packed left to right, whatever range is selected — the shape the charts had before the range control existed, and the one that survives a long quiet stretch without turning into a flat line at zero. The axis carries a break mark wherever it skipped, so a compressed axis never reads as a continuous one.++Emptiness is judged per bucket and never per entity: an interval anything at all ran in is kept, and the entities that were idle in it sit at zero there with a dash for their rate. That single rule is what lets all four charts compact through one call and keep one shared x axis — the per-entity counts are re-indexed onto the surviving buckets by the same list the series is, so an entity's history cannot slide onto the wrong intervals.++## Details++- `GET /usage` gained optional query parameters `granularity` (`minute` / `hour` / `day` / `week` / `month`, defaulting to `day`) and `fromTs`/`toTs` (ISO timestamps bounding a trailing window, given together; required for `minute`, and refining every range-scoped aggregate down to instants). The response gained `granularity`, `series` (zero-filled time buckets carrying Token sums, cost, request count, and per-bucket success counts), `byAgentSeries`, and `byModelSeries` (per-entity request and success counts aligned index-for-index with `series`; each ignores its own dimension's filter, so a chart always draws that dimension's whole breakdown). `trend`, `byAgent` and `success` were removed along with the three queries behind them, so the route no longer aggregates a fixed 30-day window, a per-Agent call count and a per-Model status breakdown that nothing displayed. Every other field was left unchanged. A range × precision combination that would materialize an oversized series is rejected with 400.+- Minute and hour buckets follow the server's local clock (the same timezone the daily aggregation key was already recorded in); week buckets key on the ISO week's Monday, month buckets on `yyyy-mm`.++## Compatibility++`GET /usage` dropped three response fields. Where each number lives now:++- `trend` — the last 30 days of Token buckets and cost, one point per day. `series` carries the same points and defaults to exactly that window when no `from`/`to` is given; it also adds `requests`, `completed` and `denominator` per point.+- `byAgent` — request counts per Agent are the sum of `byAgentSeries[].requests`. Token totals per Agent come from `?groupBy=agent`, whose `groups` rows carry `total`, `requests` and `cost`.+- `success` — a Model's successful requests and its non-aborted denominator are the sums of `byModelSeries[].completed` and `byModelSeries[].denominator`. The per-status counts (`aborted`, `failed`, `timeout`, `malformed`) have no replacement: nothing displayed them, and error diagnosis is served by the `errors` panel, which records source and code per failure.++The Web App reads none of the three, so no client change ships with this. A third-party consumer reading them from the HTTP API has to move to the fields above.diff --git a/changelog/unreleased/2026-08-20-usage-charts.zh.md b/changelog/unreleased/2026-08-20-usage-charts.zh.mdnew file mode 100644index 00000000..2e805357--- /dev/null+++ b/changelog/unreleased/2026-08-20-usage-charts.zh.md@@ -0,0 +1,42 @@+# 用量图表重构为带范围与精度控件的时间序列++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#371](https://github.com/Prism-Shadow/penguin-harness/pull/371)+- **Breaking:** yes — `GET /usage` 不再返回 `trend`、`byAgent` 与 `success`,`success` 携带的分状态失败明细一并移除。++[English](2026-08-20-usage-charts.md)++围绕同一条时间轴重构了成本中心的图表。页面新增日期范围档位——「最近一小时」「最近一天」滑动窗口、日历式近 7 / 30 / 90 天(默认近 7 天)、或自定义起止日期。序列以何种精度绘制完全由范围决定——最近一小时按分钟,最近一天按小时,日历档位按天,跨度很长的自定义范围按周或按月——因此不再有第二个需要与之保持一致的控件。所有图表都按所选范围绘制:++- 占比饼图与各模型进度条被并排的**两张请求与成功率图**取代:一张按 Agent 拆分,一张按模型拆分。每张图中,单个时间桶的请求数是一根按对象分段堆叠的柱、走左侧计数轴,每个对象的成功率各自成一条虚线、走右侧 0–100% 轴并沿用该对象的色相——虚线与 Token 图的命中率曲线同理,用来标明这条线属于右轴——图例置于图下方。两个维度同屏可见——不再有维度切换,两张图也都不以合计视图开场。请求数最高的四个对象各占一个经色觉无障碍校验的色相,其余折叠为一条中性色序列,标签写明折叠了多少个。单独突出某个对象有三种方式,都会淡出其余:悬停它的某段柱、悬停它的成功率折线、或悬停它的图例项。折线绘制在柱子上方,响应指针的层级也在柱子上方,因此不会被高柱盖住。+- Token 图保留三段堆叠柱,并新增缓存命中率虚线,绘制在柱子前方、走独立的右侧 0–100% 轴。悬停列内任意位置即给出整桶信息(三段 Token 数与命中率),悬停单段则突出该段,悬停折线则突出折线。柱宽自适应卡片宽度,不再横向滚动。+- 成本保持折线带点(每个数据点一个圆点,外加面积填充),按所选范围绘制。++页面上所有折线都在数据点之间直连、不做任何平滑,且线宽统一——不会因为哪条线后写就画得更粗。图表不出现滚动条;图表区上方只有 Agent、模型与范围三个全局控件。异常面板去掉了滚动容器——高度只由分页限制,服务端返回的首页从 20 行缩减为 10 行。++## 空桶怎么处理++「空」在这里有两种含义,各自的答案也不同。++**没有比率的桶,是画出来的,不是读出来的。** 某个对象在某个桶里一次请求都没发,就没有成功率可言;某个桶没有缓存流量,也就没有命中率。折线沿坐标轴顶部横穿过去,只为让线保持连续。这只是关于线形的绘制选择,仅此而已——悬停表格在同一个桶显示「—」,绝不显示百分比。真正的 0% 仍然显示 0%:发了请求且全部失败,那是数据本身,不是数据的空缺。++**什么都没记录的桶,不画。** 无论选了多大范围,每张图都只画有值的区间、从左往右依次排开——这正是范围控件出现之前的形态,也是一段长期空闲不会被画成一条贴地直线的原因。跳过之处横轴上画有断轴标记,被压缩的横轴因此不会被读成连续的。++空与不空按桶判断、绝不按单个对象判断:只要有任何对象在这个区间跑过,桶就保留,当时空闲的对象在该列停在 0、比率显示「—」。正因为只有这一条规则,四张图才能共用同一次压缩、共用同一条横轴——各对象的计数与序列按同一份下标清单重排到保留下来的桶上,某个对象的历史不会错位到别的区间去。++## 细节++- `GET /usage` 新增可选查询参数 `granularity`(`minute` / `hour` / `day` / `week` / `month`,默认 `day`)与 `fromTs`/`toTs`(ISO 时间戳界定的滑动窗口,须成对给出;`minute` 精度必需,并把所有按范围统计的聚合细化到时刻级)。响应新增 `granularity`、`series`(零值补齐的时间桶,携带 Token 分项、成本、请求数与每桶成功数)、`byAgentSeries` 与 `byModelSeries`(与 `series` 按下标对齐的各对象请求与成功计数;各自忽略本维度的过滤条件,因此图表始终呈现该维度的完整拆分)。`trend`、`byAgent` 与 `success` 连同其背后的三条查询一并移除,该路由不再聚合固定 30 天窗口、各 Agent 调用次数与各模型分状态明细——这些都已无处展示。其余字段保持不变。范围 × 精度过大、会产生超长序列的组合返回 400。+- 分钟与小时桶按服务器本地时钟划分(与既有按日聚合键使用同一时区);周桶以 ISO 周的周一为键,月桶以 `yyyy-mm` 为键。++## 兼容性++`GET /usage` 移除了三个响应字段。对应的数据现在在这里取:++- `trend`——最近 30 天、每天一个点的 Token 分项与成本。`series` 给出同样的点,未指定 `from`/`to` 时默认就是这个窗口,并额外带上每点的 `requests`、`completed` 与 `denominator`。+- `byAgent`——各 Agent 的请求数即 `byAgentSeries[].requests` 之和;各 Agent 的 Token 总量改用 `?groupBy=agent`,其 `groups` 行带有 `total`、`requests` 与 `cost`。+- `success`——某模型的成功请求数与其排除 aborted 的分母,分别是 `byModelSeries[].completed` 与 `byModelSeries[].denominator` 之和。分状态计数(`aborted`、`failed`、`timeout`、`malformed`)没有替代品:此前无处展示,失败诊断由 `errors` 面板承担,它按 source 与 code 记录每一次失败。++Web App 不读取这三个字段,因此本次不含客户端改动。直接消费该 HTTP 接口的第三方需要改用上述字段。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex b6a131af..2becce54 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -174,7 +174,7 @@ On Session creation, `modelId` and `provider` are both-or-neither: send the comp| Method | Path | Description || --- | --- | --- |-| GET | /usage | Usage statistics; query parameters `from`, `to`, `groupBy`, `agentId`, `provider`, `modelId` |+| GET | /usage | Usage statistics; query parameters `from`, `to`, `fromTs`/`toTs` (ISO timestamps bounding a trailing window, given together; required for `minute`), `groupBy`, `granularity` (`minute` / `hour` / `day` / `week` / `month` time-series precision, default `day`; oversized range × precision combinations are rejected), `agentId`, `provider`, `modelId` || GET | /usage/errors | One page of the error detail table (newest first): `offset`, `limit`, plus the same `from` / `to` / `agentId` filter → `{items, total}` || GET | /agents/:agentId/traces | Date → Session drill-down structure of Trace files || GET | /agents/:agentId/traces/:sessionId/:index | Read Trace events (`offset` / `limit` pagination) |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 411ee746..e27ebd11 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -174,7 +174,7 @@ Schedule 写操作仅限 Owner。新建 Session 模式的任务,`modelId` 与| 方法 | 路径 | 说明 || --- | --- | --- |-| GET | /usage | 用量统计,查询参数 `from`、`to`、`groupBy`、`agentId`、`provider`、`modelId` |+| GET | /usage | 用量统计,查询参数 `from`、`to`、`fromTs`/`toTs`(ISO 时间戳界定的滑动窗口,须成对给出;`minute` 精度必需)、`groupBy`、`granularity`(时间序列精度 `minute` / `hour` / `day` / `week` / `month`,默认 `day`;范围 × 精度过大的组合会被拒绝)、`agentId`、`provider`、`modelId` || GET | /usage/errors | 异常明细表分页(按时间倒序):`offset`、`limit`,以及与看板一致的 `from` / `to` / `agentId` 过滤 → `{items, total}` || GET | /agents/:agentId/traces | Trace 文件的日期 → Session 下钻结构 || GET | /agents/:agentId/traces/:sessionId/:index | 读取 Trace 事件(`offset` / `limit` 分页) |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex be892cbc..5c1edc9e 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -109,10 +109,11 @@ A per-Project model table grouped by provider. Models can be added and edited: i## Usage (/usage)-- Filters: Agent, model, date range;+- Filters: Agent, model, and date range (trailing last hour / last 24 hours, last 7 / 30 / 90 days, or a custom pair). The range decides the precision the charts are drawn at — per minute for the last hour, hourly for the last 24 hours, daily for the calendar presets, week or month for a long custom range — so there is no separate precision control;- Summary cards: today / last 7 days / cumulative;-- Charts: per-Agent share, per-model success rates, daily Token and cost trends;-- A server error panel summarizing recent server-side error records.+- Charts, all time series over the selected range: requests + success rate broken down by Agent and, beside it, the same by Model (a bucket's requests stacked one segment per entity on the left axis, each entity's success rate as its own dashed line on a right 0–100% axis, drawn above the bars; the top few entities are named and the rest fold into a neutral series labelled with how many), Token trend (three-segment stacked bars with a dashed cache-hit-rate line in front), and cost trend (line + points + area). Every chart takes the same hovers: a column for its bubble, one bar segment to single that segment out, a line to single the line out. Lines are straight segments, never smoothed, all at the same stroke width. Charts fit their card and never scroll;+- Two things a chart cannot draw. A bucket with **no rate** — an entity that made no request in it, or a bucket with no cache traffic — has its line carried across at the top of the axis so the stroke stays continuous; the hover table prints a dash there, never a percentage, and a real 0% (requests were made and all of them failed) still prints 0%. A bucket that recorded **nothing at all** is not plotted: every chart drops it and packs the rest left to right, so all four share one x axis that skips the quiet intervals and carries a break mark at each skip. Emptiness is judged per bucket, never per entity — an interval anything ran in stays, with the entities that were idle in it showing their zeros and dashes;+- A server error panel: summary stats plus an errors table paged at a fixed page size (no scrolling).## Trace Browser (/traces)diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 9dce659f..380695a8 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -108,10 +108,11 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,## 用量统计(/usage)-- 筛选条件:Agent、模型、日期范围;+- 筛选条件:Agent、模型与日期范围(最近一小时 / 最近一天滑动窗口、近 7 / 30 / 90 天、或自定义起止)。图表以何种精度绘制由范围决定——最近一小时按分钟,最近一天按小时,日历档位按天,跨度很长的自定义范围按周或按月——因此没有单独的精度控件;- 概览卡片:今日 / 近 7 天 / 累计用量;-- 图表:各 Agent 占比、各模型成功率、每日 Token 与费用趋势;-- 服务端错误面板:汇总最近的服务端错误记录。+- 图表,全部按所选范围展示的时间序列:并排的「按 Agent 拆分」与「按模型拆分」的请求与成功率图(单个时间桶的请求数按对象分段堆叠、走左轴,每个对象的成功率各自成一条虚线、走右侧 0–100% 轴并绘制在柱子上方;请求数最高的若干对象具名呈现,其余折叠为一条标注了数量的中性色序列)、Token 变化(三段堆叠柱 + 前置的缓存命中率虚线)、成本变化(折线带点 + 面积)。每张图都支持同样的悬停:悬停整列看气泡、悬停单段柱突出该段、悬停折线突出该线。所有折线都是直连线段、不做平滑,线宽统一。图表自适应卡片宽度,不出现滚动条;+- 有两种情况图画不出来。**没有比率**的桶——该对象在这个桶里一次请求都没发,或该桶没有缓存流量——折线沿坐标轴顶部横穿过去,只为让线保持连续;悬停表格在该处显示「—」而非百分比,而真正的 0%(发了请求且全部失败)仍然显示 0%。**什么都没记录**的桶一律不画:四张图都丢弃它、把其余的从左往右依次排开,因此共用同一条会跳过空闲区间的横轴,跳过处画有断轴标记。空与不空按桶判断、绝不按单个对象判断——只要有任何对象在这个区间跑过,桶就保留,当时空闲的对象在该列显示 0 与「—」;+- 服务端错误面板:汇总统计 + 异常明细表,按固定页大小分页(不滚动)。## Trace 浏览(/traces)diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex ea46b739..018d7e2e 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1869,37 +1869,51 @@ export interface UsageGroupRow {hasUncosted: boolean;}-export interface UsageTrendPoint {- date: string;- total: number;- cost: number | null;- /** Daily Token buckets (for the cost center's "Token Changes" stacked chart: cacheRead/cacheWrite/output). */+/** Time-series precision for the usage series (`granularity` query parameter). `minute` requires the `fromTs`/`toTs` window bounds. */+export type UsageGranularity = "minute" | "hour" | "day" | "week" | "month";++/**+ * One bucket of the usage time series (for the cost center's time-series charts).+ * Buckets are zero-filled across the whole requested range, so consecutive points+ * are always adjacent in time. Bucket keys by granularity: minute+ * `yyyy-mm-ddThh:mm` and hour `yyyy-mm-ddThh:00` (server-local clock), day+ * `yyyy-mm-dd`, week the ISO week's Monday `yyyy-mm-dd`, month `yyyy-mm`.+ */+export interface UsageSeriesPoint {+ bucket: string;cacheRead: number;cacheWrite: number;output: number;+ total: number;+ /** Cost converted at query time (USD); null when no priced Model contributed. */+ cost: number | null;+ requests: number;+ /** Successful requests in the bucket. */+ completed: number;+ /** Success-rate denominator: all requests minus aborted (a user interruption is not a model failure). */+ denominator: number;+}++/**+ * One entity's per-bucket request and success counts, aligned index-for-index+ * with `series` (the requests-and-success-rate chart draws one such entity —+ * or stacks them all). `denominator` excludes aborted, same as elsewhere.+ */+export interface UsageEntitySeriesCounts {+ requests: number[];+ completed: number[];+ denominator: number[];}-/** Invocation count per Agent (for the cost center's "Agent Invocation Count" chart). */-export interface UsageAgentCount {+/** Per-Agent counts per bucket. */+export interface UsageAgentSeries extends UsageEntitySeriesCounts {agentId: string;- requests: number;- total: number;}-/** Request success rate per Model (for the cost center's "Model Success Rate" chart; rows broken down by (provider, modelId)). */-export interface UsageSuccessRate {+/** Per-Model counts per bucket (entity identity is the (provider, modelId) pair). */+export interface UsageModelSeries extends UsageEntitySeriesCounts {provider: string;modelId: string;- /** Number of successful requests. */- completed: number;- /** Success rate denominator = all requests − aborted (user-initiated interruption isn't a model failure and shouldn't lower the success rate). */- total: number;- /** Count of user interruptions (excluded from success rate, shown separately). */- aborted: number;- /** Failure breakdown (shown on hover; unknown statuses count toward total but not these three). */- failed: number;- timeout: number;- malformed: number;}/** Occurrence count of an error for a given source · code (the "most common" metric in the stats center's error panel). */@@ -1957,12 +1971,27 @@ export interface UsageResponse {};groupBy: UsageGroupBy;groups: UsageGroupRow[];- /** Daily trend for the last 30 days (includes Token buckets and cost; affected by agent/model filters). */- trend: UsageTrendPoint[];- /** Invocation count per Agent (affected by date/model filters). */- byAgent: UsageAgentCount[];- /** Raw success rate counts per Model (affected by date/agent filters). */- success: UsageSuccessRate[];+ /** Effective precision of `series` (the validated `granularity` query parameter; defaults to day). */+ granularity: UsageGranularity;+ /**+ * Usage time series over the requested from/to range (defaulting to the last 30+ * days), zero-filled at `granularity`; affected by agent/model filters. Carries+ * everything the time-series charts draw: Token buckets, cost, request count,+ * and per-bucket success counts.+ */+ series: UsageSeriesPoint[];+ /**+ * Per-Agent counts per bucket, aligned index-for-index with `series`, sorted+ * by total requests descending. Unaffected by the agent filter — the by-Agent+ * chart draws the whole breakdown — but affected by date/model filters.+ */+ byAgentSeries: UsageAgentSeries[];+ /**+ * Per-Model counts per bucket, aligned index-for-index with `series`, sorted+ * by total requests descending. Unaffected by the model filter — the by-Model+ * chart draws the whole breakdown — but affected by date/agent filters.+ */+ byModelSeries: UsageModelSeries[];/** Server-side error capture stats (affected by date/agent filters; unaffected by model filter). */errors: UsageErrors;/** List of Agent ids that have appeared in this Project (for the filter dropdown; unaffected by current filters). */diff --git a/packages/server/src/db/repos/usage.ts b/packages/server/src/db/repos/usage.tsindex 9d853f92..506fba95 100644--- a/packages/server/src/db/repos/usage.ts+++ b/packages/server/src/db/repos/usage.ts@@ -31,29 +31,15 @@ export interface UsageRecordInsert {export interface UsageFilter {from?: string;to?: string;+ /** Timestamp window bounds (ISO UTC, compared as strings against the row's `ts`): refine the date range down to instants for the trailing minute/hour windows. */+ fromTs?: string;+ toTs?: string;agentId?: string;/** Provider filter paired with modelId (the frontend dropdown always sends them together). */provider?: string;modelId?: string;}-/**- * Raw request success-rate counts for a single Model (paired reference).- * `total` is **the success-rate denominator**: all requests minus aborted — the user- * clicking "stop" is not a model failure, and counting it would make the success rate- * drop every time stop is pressed. `aborted` is counted separately for display.- */-export interface UsageStatusCount {- provider: string;- modelId: string;- completed: number;- total: number;- aborted: number;- failed: number;- timeout: number;- malformed: number;-}-/** Raw Token sums for a single Model (paired reference) — the smallest unit for cost conversion. */export interface UsageModelSums {provider: string;@@ -70,6 +56,49 @@ export interface UsageGroupModelSums extends UsageModelSums {key: string;}+/** Time-series bucket x Model sums, with the success-rate counts folded in. */+export interface UsageSeriesModelSums extends UsageGroupModelSums {+ /** Successful requests in the bucket. */+ completed: number;+ /**+ * Success-rate denominator: all requests in the bucket minus aborted. The user+ * clicking "stop" is not a model failure, and counting it would drop the success+ * rate every time stop is pressed. Every success-rate denominator in this repo+ * follows this rule.+ */+ denominator: number;+}++/** Per-Agent counts per time bucket (the requests chart's series data). */+export interface UsageAgentBucketCount {+ key: string;+ agentId: string;+ requests: number;+ /** Successful requests in the bucket. */+ completed: number;+ /** Success-rate denominator: all requests minus aborted, same rule as UsageSeriesModelSums. */+ denominator: number;+}++/** Time-series precision (mirrors the API's UsageGranularity). */+export type UsageSeriesGranularity = "minute" | "hour" | "day" | "week" | "month";++/**+ * Bucket-key SQL per granularity. Keys must agree byte-for-byte with+ * internal/dates.ts's enumerateBuckets / enumerateTsBuckets, which zero-fill+ * the same series: minute/hour buckets come from `ts` converted to the+ * server's local clock (the same timezone `date` was recorded in), the rest+ * derive from the `date` column — `date(date, '-6 days', 'weekday 1')` is the+ * ISO week's Monday.+ */+const BUCKET_EXPRS: Record<UsageSeriesGranularity, string> = {+ minute: `strftime('%Y-%m-%dT%H:%M', ts, 'localtime')`,+ hour: `strftime('%Y-%m-%dT%H:00', ts, 'localtime')`,+ day: "date",+ week: `date(date, '-6 days', 'weekday 1')`,+ month: "substr(date, 1, 7)",+};+/** groupBy dimension -> column name allowlist (prevents injection; only these four columns can be group keys). */const GROUP_COLUMNS: Record<UsageGroupBy, string> = {date: "date",@@ -139,6 +168,14 @@ export class UsageRepo {conds.push("date <= :to");params.to = f.to;}+ if (f.fromTs !== undefined) {+ conds.push("ts >= :fromTs");+ params.fromTs = f.fromTs;+ }+ if (f.toTs !== undefined) {+ conds.push("ts <= :toTs");+ params.toTs = f.toTs;+ }if (f.agentId !== undefined) {conds.push("agent_id = :agentId");params.agentId = f.agentId;@@ -186,37 +223,58 @@ export class UsageRepo {}/**- * Raw success-rate counts per Model (paired reference) (completed / non-aborted requests):- * powers the cost center's "Model Success Rate" chart. The denominator excludes aborted- * (user-initiated interruption); failure breakdowns (failed / timeout / malformed) are- * also returned for hover display. Unknown statuses aren't broken out but still count- * toward the denominator (conservative: anything non-completed counts as a failure).+ * Time-series sums (bucket key x paired reference breakdown) with per-bucket+ * success-rate counts riding along: powers the cost center's time-series charts+ * (requests / success rate / Token / cost) at the requested precision. The+ * denominator excludes aborted.*/- statusByModel(projectId: string, f: UsageFilter = {}): UsageStatusCount[] {+ seriesByModel(+ projectId: string,+ granularity: UsageSeriesGranularity,+ f: UsageFilter = {},+ ): UsageSeriesModelSums[] {+ const expr = BUCKET_EXPRS[granularity];const { where, params } = this.conds(projectId, f);- const count = (status: string) =>- `COALESCE(SUM(CASE WHEN status = '${status}' THEN 1 ELSE 0 END), 0) AS ${status}`;const rows = this.db.prepare(- `SELECT provider, model_id,- ${count("completed")},- ${count("aborted")},- ${count("failed")},- ${count("timeout")},- ${count("malformed")},- COALESCE(SUM(CASE WHEN status <> 'aborted' THEN 1 ELSE 0 END), 0) AS total- FROM usage_records WHERE ${where} GROUP BY provider, model_id`,+ `SELECT ${expr} AS key, provider, model_id, ${SUM_COLUMNS},+ COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END), 0) AS completed,+ COALESCE(SUM(CASE WHEN status <> 'aborted' THEN 1 ELSE 0 END), 0) AS denominator+ FROM usage_records WHERE ${where}+ GROUP BY key, provider, model_id`,+ )+ .all(params);+ return rows.map((r) => ({+ key: r.key as string,+ ...toSums(r),+ completed: r.completed as number,+ denominator: r.denominator as number,+ }));+ }++ /** Per-Agent counts per time bucket (the by-Agent requests chart's series; the denominator excludes aborted). */+ agentSeries(+ projectId: string,+ granularity: UsageSeriesGranularity,+ f: UsageFilter = {},+ ): UsageAgentBucketCount[] {+ const expr = BUCKET_EXPRS[granularity];+ const { where, params } = this.conds(projectId, f);+ const rows = this.db+ .prepare(+ `SELECT ${expr} AS key, agent_id, COUNT(*) AS requests,+ COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END), 0) AS completed,+ COALESCE(SUM(CASE WHEN status <> 'aborted' THEN 1 ELSE 0 END), 0) AS denominator+ FROM usage_records WHERE ${where}+ GROUP BY key, agent_id`,).all(params);return rows.map((r) => ({- provider: r.provider as string,- modelId: r.model_id as string,+ key: r.key as string,+ agentId: r.agent_id as string,+ requests: r.requests as number,completed: r.completed as number,- total: r.total as number,- aborted: r.aborted as number,- failed: r.failed as number,- timeout: r.timeout as number,- malformed: r.malformed as number,+ denominator: r.denominator as number,}));}diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.tsindex 62e31d08..6ddc1f63 100644--- a/packages/server/src/http/routes/usage.ts+++ b/packages/server/src/http/routes/usage.ts@@ -1,18 +1,35 @@/*** Usage statistics routes:- * GET /api/projects/:p/usage?from&to&groupBy&agentId&provider&modelId- * (model filter is paired: provider and modelId are given together);+ * GET /api/projects/:p/usage?from&to&fromTs&toTs&groupBy&granularity&agentId&provider&modelId+ * (model filter is paired: provider and modelId are given together; granularity+ * sets the time-series precision, defaulting to day; fromTs/toTs bound a+ * trailing window down to instants — required for minute — and must be given+ * together);* GET /api/projects/:p/usage/errors?offset&limit&from&to&agentId — one page of the error* detail table, for paging back past the first page the dashboard already returns.*/import { Hono } from "hono";-import type { UsageGroupBy } from "../../api/types.js";+import type { UsageGranularity, UsageGroupBy } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { badRequest, optionalDateParam, paginationQuery, requireValidId } from "../validate.js";import type { AppDeps } from "../../app.js";const GROUP_BYS: readonly UsageGroupBy[] = ["date", "agent", "model", "session"];+const GRANULARITIES: readonly UsageGranularity[] = ["minute", "hour", "day", "week", "month"];++/**+ * Parse an optional ISO-8601 timestamp parameter, normalized to the UTC ISO+ * form the usage rows record — string comparison against `usage_records.ts`+ * only works with both sides in that one spelling.+ */+function optionalTsParam(value: string | undefined, label: string): string | undefined {+ if (value === undefined || value === "") return undefined;+ const ms = Date.parse(value);+ if (Number.isNaN(ms)) throw badRequest(`${label} must be an ISO-8601 timestamp.`);+ return new Date(ms).toISOString();+}+export function usageRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -24,14 +41,30 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {if (!(GROUP_BYS as readonly string[]).includes(groupByRaw)) {throw badRequest(`groupBy must be one of ${GROUP_BYS.join(" / ")}.`);}+ const granularityRaw = c.req.query("granularity") ?? "day";+ if (!(GRANULARITIES as readonly string[]).includes(granularityRaw)) {+ throw badRequest(`granularity must be one of ${GRANULARITIES.join(" / ")}.`);+ }+ const granularity = granularityRaw as UsageGranularity;const from = optionalDateParam(c.req.query("from"), "from");const to = optionalDateParam(c.req.query("to"), "to");+ const fromTs = optionalTsParam(c.req.query("fromTs"), "fromTs");+ const toTs = optionalTsParam(c.req.query("toTs"), "toTs");+ if ((fromTs === undefined) !== (toTs === undefined)) {+ throw badRequest("fromTs and toTs must be given together.");+ }+ if (fromTs !== undefined && toTs !== undefined && fromTs > toTs) {+ throw badRequest("fromTs must not be after toTs.");+ }const agentId = c.req.query("agentId");const provider = c.req.query("provider");const modelId = c.req.query("modelId");return c.json(await deps.usageService.query(projectId, {groupBy: groupByRaw as UsageGroupBy,+ granularity,+ ...(fromTs !== undefined ? { fromTs } : {}),+ ...(toTs !== undefined ? { toTs } : {}),// Unattributed errors (login failures, process crashes, etc. with no Project// context) are visible only to admins: requireProjectAccess only guarantees// "is a member of this Project" — a regular member seeing another tenant's errorsdiff --git a/packages/server/src/internal/dates.ts b/packages/server/src/internal/dates.tsindex 08dafb79..771dfebc 100644--- a/packages/server/src/internal/dates.ts+++ b/packages/server/src/internal/dates.ts@@ -18,3 +18,133 @@ export function localDateMinusDays(date: Date, days: number): string {d.setDate(d.getDate() - days);return formatLocalDate(d);}++// —— Time-series bucket keys (usage series aggregation) ——+//+// Bucket keys must agree byte-for-byte between the SQL aggregation (see UsageRepo's+// bucketExpr) and the zero-fill enumeration here, or filled gaps and aggregated rows+// land in different buckets:+// minute → `yyyy-mm-ddThh:mm` (local clock, from the row's ts)+// hour → `yyyy-mm-ddThh:00` (local clock, from the row's ts)+// day → `yyyy-mm-dd` (the row's date column)+// week → `yyyy-mm-dd` of the ISO week's Monday+// month → `yyyy-mm`++/** Time-series precision for the usage series (mirrors the API's UsageGranularity). */+export type BucketGranularity = "minute" | "hour" | "day" | "week" | "month";++/** Parse a local `yyyy-mm-dd` into a local-midnight Date. */+function parseLocalDate(date: string): Date {+ const [y, m, d] = date.split("-").map(Number);+ return new Date(y!, m! - 1, d!);+}++/** Format a local hour bucket key: `yyyy-mm-ddThh:00`. */+export function formatLocalHourKey(date: Date): string {+ const hour = date.getHours().toString().padStart(2, "0");+ return `${formatLocalDate(date)}T${hour}:00`;+}++/** Format a local minute bucket key: `yyyy-mm-ddThh:mm`. */+export function formatLocalMinuteKey(date: Date): string {+ const hour = date.getHours().toString().padStart(2, "0");+ const minute = date.getMinutes().toString().padStart(2, "0");+ return `${formatLocalDate(date)}T${hour}:${minute}`;+}++/**+ * All minute/hour bucket keys covering an inclusive timestamp window, ascending —+ * the zero-fill skeleton behind the "last hour" / "last 24 hours" trailing+ * windows, whose bounds are instants rather than calendar dates. The first key+ * is the window start floored to its unit; enumeration steps real timestamps+ * and stops one key past `cap`, mirroring enumerateBuckets.+ *+ * Keys are deduplicated because a DST fall-back replays a whole local hour:+ * 01:30 happens twice, an hour apart, and both instants aggregate into the one+ * key `strftime(..., 'localtime')` gives them. Emitting that key twice would+ * hand the same bucket to two chart points and leave one of them empty.+ */+export function enumerateTsBuckets(+ fromTs: Date,+ toTs: Date,+ granularity: "minute" | "hour",+ cap = Infinity,+): string[] {+ const keys: string[] = [];+ if (fromTs.getTime() > toTs.getTime()) return keys;+ const start = new Date(fromTs);+ start.setSeconds(0, 0);+ if (granularity === "hour") start.setMinutes(0);+ const stepMs = granularity === "hour" ? 3_600_000 : 60_000;+ const fmt = granularity === "hour" ? formatLocalHourKey : formatLocalMinuteKey;+ const seen = new Set<string>();+ for (let t = start.getTime(); t <= toTs.getTime() && keys.length <= cap; t += stepMs) {+ const key = fmt(new Date(t));+ if (seen.has(key)) continue;+ seen.add(key);+ keys.push(key);+ }+ return keys;+}++/** Monday of the ISO week containing the given local date (`yyyy-mm-dd` in, `yyyy-mm-dd` out). */+export function localWeekStart(date: string): string {+ const d = parseLocalDate(date);+ // getDay: 0=Sunday … 6=Saturday; back up (day+6)%7 days to reach Monday.+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7));+ return formatLocalDate(d);+}++/** Month bucket key: `yyyy-mm`. */+export function localMonthKey(date: string): string {+ return date.slice(0, 7);+}++/**+ * All bucket keys covering the inclusive local-date range, in ascending order —+ * the zero-fill skeleton for the usage series (an empty bucket must still appear+ * as a point, or a line chart would silently connect across the gap).+ * `from > to` yields an empty list. Hour keys are enumerated by stepping real+ * timestamps (not a fixed 24 per day), so a DST-shifted day keeps the same keys+ * SQLite's `localtime` produces; a fall-back's replayed local hour is emitted once.+ * Enumeration stops one key past `cap`, so a caller rejecting oversized ranges+ * (`keys.length > cap`) never materializes an unbounded array first.+ */+export function enumerateBuckets(+ from: string,+ to: string,+ granularity: Exclude<BucketGranularity, "minute">,+ cap = Infinity,+): string[] {+ const keys: string[] = [];+ if (from > to) return keys;+ const full = () => keys.length > cap;+ if (granularity === "hour") {+ const end = parseLocalDate(to);+ end.setHours(23);+ const seen = new Set<string>();+ for (let t = parseLocalDate(from).getTime(); t <= end.getTime() && !full(); t += 3_600_000) {+ const key = formatLocalHourKey(new Date(t));+ if (seen.has(key)) continue;+ seen.add(key);+ keys.push(key);+ }+ return keys;+ }+ if (granularity === "month") {+ const end = localMonthKey(to);+ const d = parseLocalDate(`${localMonthKey(from)}-01`);+ for (;;) {+ const key = localMonthKey(formatLocalDate(d));+ if (key > end || full()) return keys;+ keys.push(key);+ d.setMonth(d.getMonth() + 1);+ }+ }+ const stepDays = granularity === "week" ? 7 : 1;+ const d = parseLocalDate(granularity === "week" ? localWeekStart(from) : from);+ for (; formatLocalDate(d) <= to && !full(); d.setDate(d.getDate() + stepDays)) {+ keys.push(formatLocalDate(d));+ }+ return keys;+}diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.tsindex 4cbacce1..0678a77f 100644--- a/packages/server/src/services/usage-service.ts+++ b/packages/server/src/services/usage-service.ts@@ -9,7 +9,7 @@* pricing, its consumption is excluded from cost and hasUncosted is flagged).* Summary cards (today / last 7 days / cumulative), grouped aggregation (date /* agent / model / session, with the session dimension supporting agentId drill-down- * filtering), and a 30-day trend.+ * filtering), and the zero-filled time series the cost center's charts draw.* Server-side error statistics (error_records) ride along on the same response:* the statistics center fetches everything in one request, and filters are* naturally shared; unattributed errors (login failures, process crashes, and other@@ -17,21 +17,33 @@* file header.*/import type {+ UsageAgentSeries,UsageBucket,UsageErrors,UsageErrorsPage,+ UsageGranularity,UsageGroupBy,UsageGroupRow,+ UsageModelSeries,UsageResponse,+ UsageSeriesPoint,} from "../api/types.js";import type { ErrorFilter, ErrorsRepo } from "../db/repos/errors.js";import type {UsageRepo,UsageModelSums,UsageGroupModelSums,+ UsageSeriesModelSums,+ UsageAgentBucketCount,UsageFilter,} from "../db/repos/usage.js";-import { formatLocalDate, localDateMinusDays } from "../internal/dates.js";+import {+ enumerateBuckets,+ enumerateTsBuckets,+ formatLocalDate,+ localDateMinusDays,+} from "../internal/dates.js";+import { badRequest } from "../http/validate.js";/*** Number of most-recent entries kept in the error detail table. Also the page size the whole@@ -39,7 +51,7 @@ import { formatLocalDate, localDateMinusDays } from "../internal/dates.js";* whenever a second page exists, so the client derives its page size from the response instead* of holding a constant that could drift out of step with this one.*/-const ERROR_RECENT_N = 20;+const ERROR_RECENT_N = 10;/** The three pricing buckets (usd_per_mtok convention), returned by the pricing lookup callback. */export interface PricingRates {@@ -65,6 +77,16 @@ export interface UsageQuery {modelId?: string;/** Whether to include unattributed errors: admin only (the route passes user.isAdmin), defaults to false. */includeGlobalErrors?: boolean;+ /** Time-series precision for `series` / `byAgentSeries` / `byModelSeries`; defaults to day. The route validates the value; the bucket count is capped here. */+ granularity?: UsageGranularity;+ /**+ * Timestamp window bounds (ISO UTC), for the trailing "last hour" / "last 24+ * hours" ranges whose edges are instants rather than calendar dates: they+ * refine every range-scoped aggregate down to the window, and minute/hour+ * series buckets are enumerated between them. `minute` requires them.+ */+ fromTs?: string;+ toTs?: string;}/** One page of the error detail table (see {@link UsageService.queryErrors}). */@@ -115,26 +137,78 @@ export class UsageService {...(to !== undefined ? { to } : {}),});+ // Timestamp window bounds ride alongside the date range wherever the+ // selected range applies; the calendar-fixed today / last-7-days cards+ // deliberately stay date-only.+ const ts: UsageFilter = {+ ...(q.fromTs !== undefined ? { fromTs: q.fromTs } : {}),+ ...(q.toTs !== undefined ? { toTs: q.toTs } : {}),+ };const todayRows = this.usage.bucketByModel(projectId, win(today, today));const last7dRows = this.usage.bucketByModel(projectId, win(localDateMinusDays(this.now(), 6)));- const totalRows = this.usage.bucketByModel(projectId, win(q.from, q.to));- const groupRows = this.usage.groupsByModel(projectId, q.groupBy, win(q.from, q.to));- // Fixed 30-day window; affected by the agent/model filter.- const trendFrom = localDateMinusDays(this.now(), 29);- const trendRows = this.usage.groupsByModel(projectId, "date", win(trendFrom));- // Agent call-count chart: not affected by the agent filter (shows all agents), but still affected by the date + model filter.- const agentRows = this.usage.groupsByModel(projectId, "agent", {+ const totalRows = this.usage.bucketByModel(projectId, { ...win(q.from, q.to), ...ts });+ const groupRows = this.usage.groupsByModel(projectId, q.groupBy, {+ ...win(q.from, q.to),+ ...ts,+ });+ // Time series at the requested precision, zero-filled over the requested+ // range, defaulting to the last 30 days when no range is given.+ const granularity = q.granularity ?? "day";+ const seriesFrom = q.from ?? localDateMinusDays(this.now(), 29);+ const seriesTo = q.to ?? today;+ // The series is zero-filled over the whole effective range: cap the bucket+ // count so an arbitrary range × precision combination cannot materialize an+ // unbounded response. 500 comfortably covers every range the Web App offers+ // (90 days daily = 90, 14 days hourly = 336, a trailing hour by minute = 61).+ // Minute buckets only make sense inside a timestamp window — the trailing+ // ranges — and hour buckets switch to the window when one is given.+ let bucketKeys: string[];+ if (granularity === "minute" || (granularity === "hour" && ts.fromTs !== undefined)) {+ if (ts.fromTs === undefined || ts.toTs === undefined) {+ throw badRequest(+ "fromTs and toTs must be given together, and minute granularity requires them.",+ );+ }+ bucketKeys = enumerateTsBuckets(new Date(ts.fromTs), new Date(ts.toTs), granularity, 500);+ } else {+ bucketKeys = enumerateBuckets(seriesFrom, seriesTo, granularity, 500);+ }+ if (bucketKeys.length > 500) {+ throw badRequest(+ "Date range too wide for this granularity; narrow the range or coarsen the granularity.",+ );+ }+ const seriesRows = this.usage.seriesByModel(projectId, granularity, {+ ...win(seriesFrom, seriesTo),+ ...ts,+ });+ // Per-Agent and per-Model series: each drops its own dimension's filter (its+ // chart draws that dimension's whole breakdown) but honors the other+ // dimension plus the selected range.+ const agentFree: UsageFilter = {...(q.provider !== undefined ? { provider: q.provider } : {}),...(q.modelId !== undefined ? { modelId: q.modelId } : {}),...(q.from !== undefined ? { from: q.from } : {}),...(q.to !== undefined ? { to: q.to } : {}),+ ...ts,+ };+ const agentBucketRows = this.usage.agentSeries(projectId, granularity, {+ ...agentFree,+ from: seriesFrom,+ to: seriesTo,});- // Model success-rate chart: not affected by the model filter (shows all models), but still affected by the date + agent filter.- const statusRows = this.usage.statusByModel(projectId, {- ...(q.agentId !== undefined ? { agentId: q.agentId } : {}),- ...(q.from !== undefined ? { from: q.from } : {}),- ...(q.to !== undefined ? { to: q.to } : {}),- });+ // With no model filter set, dropping the model filter leaves exactly the+ // query `seriesRows` already ran: reuse its rows instead of running the+ // heaviest query on this route (bucket x model) a second time.+ const modelFiltered = q.provider !== undefined || q.modelId !== undefined;+ const modelBucketRows = modelFiltered+ ? this.usage.seriesByModel(projectId, granularity, {+ ...(q.agentId !== undefined ? { agentId: q.agentId } : {}),+ from: seriesFrom,+ to: seriesTo,+ ...ts,+ })+ : seriesRows;// Error statistics: likewise not affected by the model filter (HTTP / process errors have no Model dimension), but still affected by the date + agent filter.const errorFilter: ErrorFilter = {...(q.agentId !== undefined ? { agentId: q.agentId } : {}),@@ -147,21 +221,13 @@ export class UsageService {// Each paired reference that occurs is looked up for its current price only once.const rates = new Map<string, PricingRates | undefined>();const allRefs = new Map<string, { provider: string; modelId: string }>();- for (const r of [...todayRows, ...last7dRows, ...totalRows, ...groupRows, ...trendRows]) {+ for (const r of [...todayRows, ...last7dRows, ...totalRows, ...groupRows, ...seriesRows]) {allRefs.set(refKey(r.provider, r.modelId), { provider: r.provider, modelId: r.modelId });}for (const [key, ref] of allRefs) {rates.set(key, await this.lookupPricing(projectId, ref.provider, ref.modelId));}- const byAgentMap = new Map<string, { requests: number; total: number }>();- for (const r of agentRows) {- const acc = byAgentMap.get(r.key) ?? { requests: 0, total: 0 };- acc.requests += r.requests;- acc.total += r.total;- byAgentMap.set(r.key, acc);- }-return {summary: {today: this.foldBucket(todayRows, rates),@@ -170,11 +236,10 @@ export class UsageService {},groupBy: q.groupBy,groups: this.foldGroups(groupRows, rates, q.groupBy),- trend: this.foldTrend(trendRows, rates),- byAgent: [...byAgentMap.entries()]- .map(([agentId, v]) => ({ agentId, requests: v.requests, total: v.total }))- .sort((a, b) => b.requests - a.requests),- success: statusRows.sort((a, b) => b.total - a.total),+ granularity,+ series: this.foldSeries(bucketKeys, seriesRows, rates),+ byAgentSeries: foldAgentSeries(bucketKeys, agentBucketRows),+ byModelSeries: foldModelSeries(bucketKeys, modelBucketRows),errors: this.foldErrors(projectId, errorFilter),agentIds: this.usage.distinctAgentIds(projectId),models: this.usage.distinctModels(projectId),@@ -276,39 +341,107 @@ export class UsageService {return out;}- private foldTrend(- rows: UsageGroupModelSums[],+ /**+ * Fold the per-Model series rows onto the zero-filled bucket skeleton: every+ * enumerated bucket appears exactly once, in order, so line charts never+ * connect across a silent gap. A row whose key falls outside the skeleton+ * cannot happen for day/week/month (keys derive from the filtered date+ * column) and is dropped defensively for minute/hour, whose keys come from+ * `ts` and can therefore fall outside a skeleton built from `date` if a row+ * was recorded under a different clock.+ */+ private foldSeries(+ keys: string[],+ rows: UsageSeriesModelSums[],rates: Map<string, PricingRates | undefined>,- ): UsageResponse["trend"] {- const byDate = new Map<- string,- { total: number; cacheRead: number; cacheWrite: number; output: number; cost: number | null }- >();+ ): UsageSeriesPoint[] {+ const byKey = new Map<string, UsageSeriesPoint>(+ keys.map((bucket) => [+ bucket,+ {+ bucket,+ cacheRead: 0,+ cacheWrite: 0,+ output: 0,+ total: 0,+ cost: null,+ requests: 0,+ completed: 0,+ denominator: 0,+ },+ ]),+ );for (const r of rows) {- const acc = byDate.get(r.key) ?? {- total: 0,- cacheRead: 0,- cacheWrite: 0,- output: 0,- cost: null,- };- acc.total += r.total;+ const acc = byKey.get(r.key);+ if (!acc) continue;acc.cacheRead += r.cacheRead;acc.cacheWrite += r.cacheWrite;acc.output += r.output;+ acc.total += r.total;+ acc.requests += r.requests;+ acc.completed += r.completed;+ acc.denominator += r.denominator;const rate = rates.get(refKey(r.provider, r.modelId));if (rate) acc.cost = (acc.cost ?? 0) + costOf(r, rate);- byDate.set(r.key, acc);}- return [...byDate.entries()]- .sort((a, b) => a[0].localeCompare(b[0]))- .map(([date, v]) => ({- date,- total: v.total,- cacheRead: v.cacheRead,- cacheWrite: v.cacheWrite,- output: v.output,- cost: v.cost,- }));+ return keys.map((k) => byKey.get(k)!);+ }+}++const sumOf = (a: number[]) => a.reduce((s, v) => s + v, 0);++const zeros = (n: number) => new Array<number>(n).fill(0);++/**+ * Per-Agent counts aligned index-for-index with the bucket skeleton, sorted by+ * total requests descending (the requests chart takes the head and folds the+ * tail into an "other" series client-side).+ */+function foldAgentSeries(keys: string[], rows: UsageAgentBucketCount[]): UsageAgentSeries[] {+ const idx = new Map(keys.map((k, i) => [k, i]));+ const byAgent = new Map<string, UsageAgentSeries>();+ for (const r of rows) {+ const i = idx.get(r.key);+ if (i === undefined) continue;+ let s = byAgent.get(r.agentId);+ if (!s) {+ s = {+ agentId: r.agentId,+ requests: zeros(keys.length),+ completed: zeros(keys.length),+ denominator: zeros(keys.length),+ };+ byAgent.set(r.agentId, s);+ }+ s.requests[i]! += r.requests;+ s.completed[i]! += r.completed;+ s.denominator[i]! += r.denominator;+ }+ return [...byAgent.values()].sort((a, b) => sumOf(b.requests) - sumOf(a.requests));+}++/** Per-Model counts aligned with the bucket skeleton (entity identity is the (provider, modelId) pair), sorted by total requests descending. */+function foldModelSeries(keys: string[], rows: UsageSeriesModelSums[]): UsageModelSeries[] {+ const idx = new Map(keys.map((k, i) => [k, i]));+ const byModel = new Map<string, UsageModelSeries>();+ for (const r of rows) {+ const i = idx.get(r.key);+ if (i === undefined) continue;+ const key = refKey(r.provider, r.modelId);+ let s = byModel.get(key);+ if (!s) {+ s = {+ provider: r.provider,+ modelId: r.modelId,+ requests: zeros(keys.length),+ completed: zeros(keys.length),+ denominator: zeros(keys.length),+ };+ byModel.set(key, s);+ }+ s.requests[i]! += r.requests;+ s.completed[i]! += r.completed;+ s.denominator[i]! += r.denominator;}+ return [...byModel.values()].sort((a, b) => sumOf(b.requests) - sumOf(a.requests));}diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.tsindex 0b1f4835..5aa6b2bf 100644--- a/packages/server/test/usage.test.ts+++ b/packages/server/test/usage.test.ts@@ -1,10 +1,10 @@/*** Unit tests for usage persistence and statistics: origin→model attribution,- * summary buckets / group aggregation / trend queries, cost computed **on the- * fly** (only Tokens are persisted; cost is priced against current pricing at- * query time, no pricing → NULL + hasUncosted; a later price update is- * reflected immediately), and the status → success-rate pipeline (aborted- * doesn't count as a model failure).+ * summary buckets and group aggregation, cost computed **on the fly** (only+ * Tokens are persisted; cost is priced against current pricing at query time,+ * no pricing → NULL + hasUncosted; a later price update is reflected+ * immediately), and the status → success-rate pipeline that rides on the time+ * series (aborted doesn't count as a model failure).*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { sessionMeta, tokenUsage, withOrigin } from "@prismshadow/penguin-core";@@ -15,7 +15,7 @@ import { UsageRepo } from "../src/db/repos/usage.js";import { UsageService } from "../src/services/usage-service.js";import type { PricingRates } from "../src/services/usage-service.js";import { openDatabase } from "../src/db/database.js";-import { formatLocalDate } from "../src/internal/dates.js";+import { enumerateBuckets, enumerateTsBuckets, formatLocalDate } from "../src/internal/dates.js";import type { DatabaseSync } from "node:sqlite";const CTX = {@@ -204,11 +204,36 @@ describe("usage-service (cost computed on the fly)", () => {expect(other.groups).toEqual([]);});- it("from/to filter the groups; the trend is a fixed 30-day window", async () => {+ it("pricing is looked up for every reference the response prices, and only those", async () => {+ const now = new Date("2026-07-06T10:00:00");+ pricing["m-old"] = { cacheRead: 1, cacheWrite: 1, output: 1 };+ insert("2026-07-06", { modelId: "m1" });+ // Inside the last 30 days but outside the requested range: no surviving aggregate+ // covers it, so it must not be priced — and must not perturb the ones that are.+ insert("2026-06-20", { modelId: "m-old" });+ const asked: string[] = [];+ const svc = new UsageService(+ repo,+ new ErrorsRepo(db),+ async (p, provider, modelId) => {+ asked.push(modelId);+ return lookup(p, provider, modelId);+ },+ () => now,+ );+ const res = await svc.query("p1", { groupBy: "date", from: "2026-07-06", to: "2026-07-06" });+ expect(asked).toEqual(["m1"]);+ expect(res.summary.total.cost).toBeCloseTo(ROW_COST, 12);+ expect(res.summary.today.cost).toBeCloseTo(ROW_COST, 12);+ expect(res.groups[0]!.cost).toBeCloseTo(ROW_COST, 12);+ expect(res.series[0]!.cost).toBeCloseTo(ROW_COST, 12);+ });++ it("from/to filter the groups", async () => {const now = new Date("2026-07-06T10:00:00");insert("2026-07-06");insert("2026-06-20");- insert("2026-05-01"); // outside the 30-day window+ insert("2026-05-01");const svc = service(now);const res = await svc.query("p1", {groupBy: "date",@@ -216,29 +241,29 @@ describe("usage-service (cost computed on the fly)", () => {to: "2026-07-31",});expect(res.groups.map((g) => g.key)).toEqual(["2026-07-06"]);- expect(res.trend.map((p) => p.date)).toEqual(["2026-06-20", "2026-07-06"]);- expect(res.trend[1]!.cost).toBeCloseTo(ROW_COST, 12);+ expect(res.groups[0]!.cost).toBeCloseTo(ROW_COST, 12);});- // —— status → success-rate pipeline ——+ // —— status → success-rate pipeline (carried per bucket on the time series) ——- it("success rate: completed / non-aborted requests, with the failure breakdown carried along", async () => {+ it("success counts: completed against a denominator of all non-aborted requests, whatever the failure was", async () => {const now = new Date("2026-07-06T10:00:00");for (let i = 0; i < 7; i++) insert("2026-07-06");insert("2026-07-06", { status: "failed", total: 0 });insert("2026-07-06", { status: "timeout", total: 0 });insert("2026-07-06", { status: "malformed", total: 0 });- const res = await service(now).query("p1", { groupBy: "date" });-- const m1 = res.success.find((s) => s.modelId === "m1")!;- expect(m1).toMatchObject({- completed: 7,- total: 10,- aborted: 0,- failed: 1,- timeout: 1,- malformed: 1,+ const res = await service(now).query("p1", {+ groupBy: "date",+ from: "2026-07-06",+ to: "2026-07-06",});++ // Three different failure statuses, none of them broken out: anything that is+ // not `completed` and not `aborted` counts against the rate, conservatively.+ expect(res.series[0]).toMatchObject({ requests: 10, completed: 7, denominator: 10 });+ const m1 = res.byModelSeries.find((s) => s.modelId === "m1")!;+ expect(m1.completed).toEqual([7]);+ expect(m1.denominator).toEqual([10]);});it('regression: aborted (the user clicked "Stop") is not a model failure — excluded from the denominator, so interrupts never drag the success rate down', async () => {@@ -247,33 +272,312 @@ describe("usage-service (cost computed on the fly)", () => {// The user clicked "Stop" twice: under the old accounting, the success rate would drop to 8/10 = 80%.insert("2026-07-06", { status: "aborted", total: 0 });insert("2026-07-06", { status: "aborted", total: 0 });- const res = await service(now).query("p1", { groupBy: "date" });+ const range = { groupBy: "date", from: "2026-07-06", to: "2026-07-06" } as const;+ const res = await service(now).query("p1", range);- const m1 = res.success.find((s) => s.modelId === "m1")!;- expect(m1.completed).toBe(8);- expect(m1.total).toBe(8); // denominator excludes aborted- expect(m1.aborted).toBe(2); // but the info isn't lost- expect(m1.completed / m1.total).toBe(1); // 100%, no longer dragged down by aborts+ const bucket = res.series[0]!;+ expect(bucket.completed).toBe(8);+ expect(bucket.denominator).toBe(8); // denominator excludes aborted+ expect(bucket.requests).toBe(10); // but the two interrupts are still requests+ expect(bucket.completed / bucket.denominator).toBe(1); // 100%, no longer dragged down by aborts+ // Per-entity counts follow the same rule — they are what the charts' rate lines read.+ expect(res.byAgentSeries[0]!).toMatchObject({ completed: [8], denominator: [8] });// A real failure still counts: add one more failed → 8/9.insert("2026-07-06", { status: "failed", total: 0 });- const after = await service(now).query("p1", { groupBy: "date" });- expect(after.success.find((s) => s.modelId === "m1")!.total).toBe(9);+ const after = await service(now).query("p1", range);+ expect(after.series[0]!.denominator).toBe(9);});- it("the success rate ignores the model filter but still honors agent and date filters (the chart shows all Models)", async () => {+ it("the model filter narrows series but not byModelSeries; the agent filter narrows both", async () => {const now = new Date("2026-07-06T10:00:00");insert("2026-07-06", { modelId: "m1", agentId: "a1" });insert("2026-07-06", { modelId: "m2", agentId: "a2", status: "failed", total: 0 });const svc = service(now);+ const range = { groupBy: "date", from: "2026-07-06", to: "2026-07-06" } as const;++ // Filtering by m1: the by-Model chart still draws m2 (for comparison), while+ // every filter-scoped aggregate — the main series included — narrows to m1.+ const filtered = await svc.query("p1", { ...range, modelId: "m1", provider: "custom" });+ expect(filtered.byModelSeries.map((s) => s.modelId).sort()).toEqual(["m1", "m2"]);+ expect(filtered.series[0]!.requests).toBe(1);++ // Filtering by a1: m2's requests belong to a2, so they leave both.+ const byAgent = await svc.query("p1", { ...range, agentId: "a1" });+ expect(byAgent.byModelSeries.map((s) => s.modelId)).toEqual(["m1"]);+ expect(byAgent.series[0]!.requests).toBe(1);+ });+});- // Filtering by m1: the success-rate chart still lists m2 (for comparison), unaffected by the filter.- const filtered = await svc.query("p1", { groupBy: "date", modelId: "m1" });- expect(filtered.success.map((s) => s.modelId).sort()).toEqual(["m1", "m2"]);+describe("usage-service series (zero-filled time-series buckets)", () => {+ let db: DatabaseSync;+ let repo: UsageRepo;+ let service: (now: Date) => UsageService;+ let pricing: Record<string, PricingRates | undefined>;+ const lookup = async (_p: string, _provider: string, modelId: string) => pricing[modelId];++ beforeEach(() => {+ db = openDatabase(":memory:");+ repo = new UsageRepo(db);+ const errors = new ErrorsRepo(db);+ service = (now: Date) => new UsageService(repo, errors, lookup, () => now);+ pricing = { m1: { cacheRead: 0.3, cacheWrite: 3.75, output: 15 } };+ });+ afterEach(() => db.close());++ const ROW_COST = (10 * 0.3 + 1 * 3.75 + 5 * 15) / 1e6;++ function insert(date: string, opts: Partial<Parameters<UsageRepo["insert"]>[0]> = {}): void {+ repo.insert({+ ts: `${date}T00:00:00.000Z`,+ date,+ projectId: "p1",+ agentId: "a1",+ sessionId: "s1",+ originSessionId: null,+ modelId: "m1",+ provider: "custom",+ cacheRead: 10,+ cacheWrite: 1,+ output: 5,+ total: 100,+ ...opts,+ });+ }++ it("daily series: every bucket in the range appears exactly once, gaps as zeros; sums, cost, and success counts ride per bucket", async () => {+ const now = new Date("2026-07-06T10:00:00");+ insert("2026-07-02");+ insert("2026-07-02", { status: "failed", total: 0, cacheRead: 0, cacheWrite: 0, output: 0 });+ insert("2026-07-02", { status: "aborted", total: 0, cacheRead: 0, cacheWrite: 0, output: 0 });+ insert("2026-07-04");+ const res = await service(now).query("p1", {+ groupBy: "date",+ from: "2026-07-01",+ to: "2026-07-05",+ });+ expect(res.granularity).toBe("day");+ expect(res.series.map((p) => p.bucket)).toEqual([+ "2026-07-01",+ "2026-07-02",+ "2026-07-03",+ "2026-07-04",+ "2026-07-05",+ ]);+ const d2 = res.series[1]!;+ expect(d2).toMatchObject({ total: 100, requests: 3, completed: 1, denominator: 2 });+ expect(d2.cost).toBeCloseTo(ROW_COST, 12);+ // Zero-filled gap: nothing happened, but the bucket exists (a line must not bridge it silently).+ expect(res.series[2]).toMatchObject({+ total: 0,+ requests: 0,+ completed: 0,+ denominator: 0,+ cost: null,+ });+ });++ it("weekly buckets key on the ISO week's Monday and aggregate everything in the week; monthly on yyyy-mm", async () => {+ const now = new Date("2026-07-20T10:00:00");+ insert("2026-07-07"); // Tuesday → week of Monday 2026-07-06+ insert("2026-07-12"); // Sunday → same week+ insert("2026-07-13"); // Monday → next week+ const weekly = await service(now).query("p1", {+ groupBy: "date",+ from: "2026-07-06",+ to: "2026-07-19",+ granularity: "week",+ });+ expect(weekly.granularity).toBe("week");+ expect(weekly.series.map((p) => p.bucket)).toEqual(["2026-07-06", "2026-07-13"]);+ expect(weekly.series[0]!.requests).toBe(2);+ expect(weekly.series[1]!.requests).toBe(1);++ const monthly = await service(now).query("p1", {+ groupBy: "date",+ from: "2026-06-15",+ to: "2026-07-19",+ granularity: "month",+ });+ expect(monthly.series.map((p) => p.bucket)).toEqual(["2026-06", "2026-07"]);+ expect(monthly.series[1]!.requests).toBe(3);+ });++ it("hourly buckets follow the server's local clock (the same timezone the date column records)", async () => {+ // Build ts from a local wall-clock time so the expectation holds in any test timezone.+ const at = (h: number, m: number) => new Date(2026, 6, 6, h, m);+ const dateStr = formatLocalDate(at(9, 0));+ insert(dateStr, { ts: at(9, 15).toISOString() });+ insert(dateStr, { ts: at(9, 45).toISOString() });+ insert(dateStr, { ts: at(11, 5).toISOString() });+ const res = await service(at(12, 0)).query("p1", {+ groupBy: "date",+ from: dateStr,+ to: dateStr,+ granularity: "hour",+ });+ expect(res.series).toHaveLength(24);+ const byBucket = new Map(res.series.map((p) => [p.bucket, p.requests]));+ expect(byBucket.get(`${dateStr}T09:00`)).toBe(2);+ expect(byBucket.get(`${dateStr}T10:00`)).toBe(0);+ expect(byBucket.get(`${dateStr}T11:00`)).toBe(1);+ });++ it("byAgentSeries aligns index-for-index with series, sorts by total descending, and ignores the agent filter (all agents stay visible)", async () => {+ const now = new Date("2026-07-06T10:00:00");+ insert("2026-07-01", { agentId: "small" });+ insert("2026-07-02", { agentId: "big" });+ insert("2026-07-02", { agentId: "big", status: "failed", total: 0 });+ const res = await service(now).query("p1", {+ groupBy: "date",+ from: "2026-07-01",+ to: "2026-07-03",+ agentId: "small",+ });+ expect(res.byAgentSeries.map((s) => s.agentId)).toEqual(["big", "small"]);+ expect(res.byAgentSeries[0]!.requests).toEqual([0, 2, 0]);+ // Per-bucket success counts ride along, per entity (the failed request counts toward the denominator only).+ expect(res.byAgentSeries[0]!.completed).toEqual([0, 1, 0]);+ expect(res.byAgentSeries[0]!.denominator).toEqual([0, 2, 0]);+ expect(res.byAgentSeries[1]!.requests).toEqual([1, 0, 0]);+ // The main series does honor the agent filter, like every other aggregate.+ expect(res.series.map((p) => p.requests)).toEqual([1, 0, 0]);+ });++ it("byModelSeries mirrors byAgentSeries for the model dimension: aligned, sorted, model-filter-free but agent-filtered", async () => {+ const now = new Date("2026-07-06T10:00:00");+ insert("2026-07-01", { modelId: "m1", agentId: "a1" });+ insert("2026-07-02", { modelId: "m2", agentId: "a1" });+ insert("2026-07-02", { modelId: "m2", agentId: "a1", status: "aborted", total: 0 });+ insert("2026-07-02", { modelId: "m2", agentId: "other" });+ const res = await service(now).query("p1", {+ groupBy: "date",+ from: "2026-07-01",+ to: "2026-07-03",+ agentId: "a1",+ modelId: "m1",+ provider: "custom",+ });+ // The model filter does not narrow the list; the agent filter does.+ expect(res.byModelSeries.map((s) => s.modelId)).toEqual(["m2", "m1"]);+ const m2 = res.byModelSeries[0]!;+ expect(m2.provider).toBe("custom");+ expect(m2.requests).toEqual([0, 2, 0]);+ expect(m2.completed).toEqual([0, 1, 0]);+ // Aborted is excluded from the denominator, same as everywhere else.+ expect(m2.denominator).toEqual([0, 1, 0]);+ });++ it("minute buckets: a trailing timestamp window zero-fills by minute and bounds every range-scoped aggregate", async () => {+ // Build everything from local wall-clock times so expectations hold in any test timezone.+ const at = (h: number, m: number, s = 0) => new Date(2026, 6, 6, h, m, s);+ const dateStr = formatLocalDate(at(10, 0));+ insert(dateStr, { ts: at(9, 58, 30).toISOString() }); // inside the window+ insert(dateStr, { ts: at(10, 20, 0).toISOString() }); // inside+ insert(dateStr, { ts: at(8, 30, 0).toISOString() }); // before the window: excluded+ const res = await service(at(10, 30)).query("p1", {+ groupBy: "date",+ from: dateStr,+ to: dateStr,+ granularity: "minute",+ fromTs: at(9, 30).toISOString(),+ toTs: at(10, 30).toISOString(),+ });+ expect(res.granularity).toBe("minute");+ expect(res.series).toHaveLength(61);+ expect(res.series[0]!.bucket).toBe(`${dateStr}T09:30`);+ expect(res.series.at(-1)!.bucket).toBe(`${dateStr}T10:30`);+ const byBucket = new Map(res.series.map((p) => [p.bucket, p.requests]));+ expect(byBucket.get(`${dateStr}T09:58`)).toBe(1);+ expect(byBucket.get(`${dateStr}T10:20`)).toBe(1);+ // The pre-window row is outside the ts bounds everywhere the range applies.+ expect(res.summary.total.requests).toBe(2);+ expect(res.series.reduce((s, p) => s + p.requests, 0)).toBe(2);+ // The per-entity series are index-aligned with the same minute skeleton, so the+ // charts can read entity[i] against series[i] without carrying bucket keys of their own.+ for (const entity of [...res.byAgentSeries, ...res.byModelSeries]) {+ expect(entity.requests).toHaveLength(res.series.length);+ expect(entity.completed).toHaveLength(res.series.length);+ expect(entity.denominator).toHaveLength(res.series.length);+ expect(entity.requests.filter((n) => n > 0)).toHaveLength(2);+ const at = (bucket: string) =>+ entity.requests[res.series.findIndex((p) => p.bucket === bucket)];+ expect(at(`${dateStr}T09:58`)).toBe(1);+ expect(at(`${dateStr}T10:20`)).toBe(1);+ }+ });++ it("minute granularity without a timestamp window is rejected", async () => {+ const now = new Date("2026-07-06T10:00:00");+ await expect(+ service(now).query("p1", { groupBy: "date", granularity: "minute" }),+ ).rejects.toThrow(/fromTs/);+ });++ it("defaults: no from/to serves the last 30 days; no granularity means day", async () => {+ const now = new Date("2026-07-06T10:00:00");+ insert("2026-07-06");+ const res = await service(now).query("p1", { groupBy: "date" });+ expect(res.granularity).toBe("day");+ expect(res.series).toHaveLength(30);+ expect(res.series[0]!.bucket).toBe("2026-06-07");+ expect(res.series.at(-1)!).toMatchObject({ bucket: "2026-07-06", requests: 1 });+ });++ it("rejects a range × precision that would materialize an oversized series", async () => {+ const now = new Date("2026-07-06T10:00:00");+ await expect(+ service(now).query("p1", {+ groupBy: "date",+ from: "2025-07-01",+ to: "2026-07-01",+ granularity: "hour",+ }),+ ).rejects.toThrow(/granularity/);+ });+});++describe("bucket enumeration across a DST transition", () => {+ // The zero-fill skeleton and SQLite's `strftime(..., 'localtime')` must agree key for key.+ // A fall-back replays a whole local hour, so two instants an hour apart share one key;+ // the enumeration has to emit that key once, or one of the two points it feeds stays empty.+ const realTz = process.env.TZ;+ beforeEach(() => {+ process.env.TZ = "America/New_York";+ });+ afterEach(() => {+ if (realTz === undefined) delete process.env.TZ;+ else process.env.TZ = realTz;+ });++ /** 2026-11-01 01:00 EDT (UTC-4) — the hour after this one is replayed as EST (UTC-5). */+ const foldStart = new Date(Date.UTC(2026, 10, 1, 5, 0));+ const foldEnd = new Date(Date.UTC(2026, 10, 1, 7, 0)); // 02:00 EST, past the replay++ it("minute keys over a replayed hour are unique and stay ascending", () => {+ const keys = enumerateTsBuckets(foldStart, foldEnd, "minute");+ expect(new Set(keys).size).toBe(keys.length);+ expect([...keys].sort()).toEqual(keys);+ expect(keys.filter((k) => k === "2026-11-01T01:30")).toEqual(["2026-11-01T01:30"]);+ expect(keys.at(0)).toBe("2026-11-01T01:00");+ expect(keys.at(-1)).toBe("2026-11-01T02:00");+ });++ it("hour keys over the same window collapse the replayed hour to one bucket", () => {+ expect(enumerateTsBuckets(foldStart, foldEnd, "hour")).toEqual([+ "2026-11-01T01:00",+ "2026-11-01T02:00",+ ]);+ // The date-driven path walks the same clock: a 25-hour local day still has 24 hour keys.+ const day = enumerateBuckets("2026-11-01", "2026-11-01", "hour");+ expect(new Set(day).size).toBe(day.length);+ expect(day).toHaveLength(24);+ });- // Filtering by a1: m2's requests belong to a2 and are excluded.- const byAgent = await svc.query("p1", { groupBy: "date", agentId: "a1" });- expect(byAgent.success.map((s) => s.modelId)).toEqual(["m1"]);+ it("a spring-forward day is short a key rather than inventing the hour that never happened", () => {+ const day = enumerateBuckets("2026-03-08", "2026-03-08", "hour");+ expect(day).toHaveLength(23);+ expect(day).not.toContain("2026-03-08T02:00");});});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 206de051..c5468a03 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -96,6 +96,7 @@ import type {UpdateRunResponse,DesktopUpdateStatusResponse,UsageErrorsPage,+ UsageGranularity,UsageGroupBy,UsageResponse,VaultResponse,@@ -657,7 +658,12 @@ export const getUsage = (params: {from?: string;to?: string;+ /** Trailing-window bounds (ISO timestamps, together or not at all): refine the range down to instants; required for minute granularity. */+ fromTs?: string;+ toTs?: string;groupBy: UsageGroupBy;+ /** Time-series precision for the response's `series`; the server defaults to day. */+ granularity?: UsageGranularity;agentId?: string;/** Model filter is always a whole pair — both fields or neither; a model is never referenced by id alone. */provider?: string;@@ -668,7 +674,10 @@ export const getUsage = (query: {from: params.from,to: params.to,+ fromTs: params.fromTs,+ toTs: params.toTs,groupBy: params.groupBy,+ granularity: params.granularity,agentId: params.agentId,provider: params.provider,modelId: params.modelId,diff --git a/packages/web/src/features/benchmark/benchmark-metrics.ts b/packages/web/src/features/benchmark/benchmark-metrics.tsindex c071c75f..ece1fcda 100644--- a/packages/web/src/features/benchmark/benchmark-metrics.ts+++ b/packages/web/src/features/benchmark/benchmark-metrics.ts@@ -52,32 +52,6 @@ export function scoreScale(values: readonly (number | null)[]): ScoreScale {return { min, max, ticks };}-/** A single data point on the chart: original index (x-axis position) + value. */-export interface MetricPoint {- index: number;- value: number;-}--/**- * Splits a value sequence with gaps into **contiguous value-bearing** segments (each segment has- * at least 1 point): points within a segment are connected, segments are broken apart; a- * single-point segment draws only a point, no line.- */-export function lineSegments(values: readonly (number | null)[]): MetricPoint[][] {- const segments: MetricPoint[][] = [];- let current: MetricPoint[] = [];- values.forEach((value, index) => {- if (value === null) {- if (current.length > 0) segments.push(current);- current = [];- return;- }- current.push({ index, value });- });- if (current.length > 0) segments.push(current);- return segments;-}-/** Minimal evaluation shape needed for series grouping (BenchmarkEvaluation is a superset). */export interface ModelRefLike {modelId?: string;diff --git a/packages/web/src/features/benchmark/benchmark-page.tsx b/packages/web/src/features/benchmark/benchmark-page.tsxindex a23a1f1e..7d12fe7d 100644--- a/packages/web/src/features/benchmark/benchmark-page.tsx+++ b/packages/web/src/features/benchmark/benchmark-page.tsx@@ -30,16 +30,10 @@ import { Truncated } from "../../components/ui/truncated";import { EmptyState } from "../../components/ui/empty-state";import { Modal } from "../../components/ui/modal";import { SkeletonList } from "../../components/ui/skeleton";-import { seriesColor } from "../../lib/category-colors";-import { makeRangeGeom } from "../usage/chart-geom";+import { NEUTRAL_SERIES, seriesColor } from "../../lib/category-colors";+import { lineSegments, makeRangeGeom, segmentPath } from "../usage/chart-geom";import { ChartFrame, useChartWidth } from "../usage/chart-svg";-import {- lineSegments,- modelSeries,- scoreScale,- scoreValues,- seriesValues,-} from "./benchmark-metrics";+import { modelSeries, scoreScale, scoreValues, seriesValues } from "./benchmark-metrics";import type { EvaluationSeries } from "./benchmark-metrics";import { BenchmarkCaseBrowser } from "./benchmark-case-browser";@@ -195,17 +189,14 @@ function ScoreTrendChart({return (<gkey={s.key === "" ? "unlabeled" : s.key}- className={s.modelId ? seriesColor(si).text : "text-gray-400 dark:text-gray-500"}+ className={(s.modelId ? seriesColor(si) : NEUTRAL_SERIES).text}>{segments.map((seg, k) => {- const line = seg- .map((p, j) => `${j === 0 ? "M" : "L"}${geom.x(p.index)},${geom.y(p.value)}`)- .join(" ");return (<g key={k}>{seg.length > 1 && (<path- d={line}+ d={segmentPath(geom, seg)}fill="none"stroke="currentColor"strokeWidth={2}@@ -256,9 +247,7 @@ function TrendSection({ evaluations }: { evaluations: BenchmarkEvaluation[] }) {className="flex items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400"><span- className={`inline-block h-2 w-2 shrink-0 rounded-sm ${- s.modelId ? seriesColor(i).swatch : "bg-gray-400 dark:bg-gray-500"- }`}+ className={`inline-block h-2 w-2 shrink-0 rounded-sm ${(s.modelId ? seriesColor(i) : NEUTRAL_SERIES).swatch}`}/><span className="font-mono">{labelOf(s)}</span></span>diff --git a/packages/web/src/features/usage/chart-geom.ts b/packages/web/src/features/usage/chart-geom.tsindex 466c62c0..0f47ebc4 100644--- a/packages/web/src/features/usage/chart-geom.ts+++ b/packages/web/src/features/usage/chart-geom.ts@@ -1,14 +1,17 @@/*** Geometry math for the cost center charts: pure functions, no React / no- * JSX, easy to unit test (see test/usage-charts.test.ts). The two "last 30- * days" charts (the daily Token bar's three-segment stack, the daily cost- * line + area) share one coordinate system — canvas width, padding, the- * x()/y() mapping, SVG paths, x-axis label indices. The stacked bar's- * horizontal layout (fixed 25px bar width, spacing ≥ bar width) is computed- * by tokenBarLayout, and per-segment geometry (including per-segment hit- * bands) is produced by barSegments; there's also pie-slice geometry (each- * Agent's call count), success-rate normalization, and hover-bubble- * placement (pointer lower-right, flipping at the edges). See chart-svg.tsx for the render skeleton.+ * JSX, easy to unit test (see test/usage-charts.test.ts). The time-series+ * charts (the requests + success-rate combo, the Token bar's three-segment+ * stack, the cost line) share one coordinate system — canvas width, padding,+ * the x()/y() mapping, SVG paths, x-axis label indices. Bars fit the+ * container (fitBarWidth — no horizontal scrolling), per-segment geometry+ * (including per-segment hit bands) is produced by barSegments, a series with+ * holes in it is split by lineSegments so no stroke bridges an interval that+ * has no value, and every line on the page — cost, cache hit rate,+ * success rate — is drawn by linePath as straight segments between its points,+ * with no smoothing anywhere; there's also hover-bubble placement (pointer+ * lower-right, flipping at the edges). See chart-svg.tsx for the render+ * skeleton.** **Canvas width = the container's measured pixel width (1 canvas unit = 1* CSS pixel)**: the SVG no longer stretches/scales via a fixed viewBox —@@ -28,6 +31,9 @@ export const PAD_B = 22;/** The daily Token chart's three buckets (bottom-to-top stacking order is output → cacheWrite → cacheRead). */export type TokenBucketKey = "cacheRead" | "cacheWrite" | "output";+/** Right padding for charts that carry a right-hand percentage axis (the Token chart's cache-hit-rate overlay): room for a "100%" tick label. */+export const PAD_R_AXIS = 34;+/** A chart's coordinate system: canvas width w, data point count n, y-axis bounds, and x()/y() mapping "index / value" to canvas coordinates. */export interface ChartGeom {n: number;@@ -35,6 +41,8 @@ export interface ChartGeom {max: number;/** Total canvas width (= viewBox width = CSS pixel width). */w: number;+ /** Right padding (PAD_R by default; PAD_R_AXIS when a right-hand axis needs label room). */+ padR: number;innerW: number;innerH: number;step: number;@@ -48,17 +56,25 @@ export interface ChartGeom {* in pixels. Invalid or zero-height ranges map values to the baseline rather* than producing NaN / Infinity.*/-export function makeGeom(n: number, max: number, w: number): ChartGeom {- return makeRangeGeom(n, 0, max, w);+export function makeGeom(n: number, max: number, w: number, padR = PAD_R): ChartGeom {+ return makeRangeGeom(n, 0, max, w, padR);}/*** Build a coordinate system with an explicit y-axis range. Score charts use* this to zoom into the observed values; zero-baseline usage charts keep- * calling makeGeom above.+ * calling makeGeom above. Geoms sharing n / w / padR share x() exactly — that+ * is how a right-axis overlay (its own y range) stays aligned with the marks+ * under it.*/-export function makeRangeGeom(n: number, min: number, max: number, w: number): ChartGeom {- const innerW = Math.max(0, w - PAD_L - PAD_R);+export function makeRangeGeom(+ n: number,+ min: number,+ max: number,+ w: number,+ padR = PAD_R,+): ChartGeom {+ const innerW = Math.max(0, w - PAD_L - padR);const innerH = CHART_H - PAD_T - PAD_B;const step = n > 0 ? innerW / n : innerW;const range = max - min;@@ -67,6 +83,7 @@ export function makeRangeGeom(n: number, min: number, max: number, w: number): Cmin,max,w,+ padR,innerW,innerH,step,@@ -94,6 +111,43 @@ export function areaPath(geom: ChartGeom, values: number[]): string {return parts.join(" ");}+/** Path coordinates keep 2 decimal places: the path string stays short and readable, and is easy to assert on in unit tests. */+const rnd = (v: number): number => Math.round(v * 100) / 100;++/** A value-bearing point of a gapped series: its index on the shared x axis, and its value. */+export interface LinePoint {+ index: number;+ value: number;+}++/**+ * Split a value sequence with gaps into **contiguous value-bearing** segments+ * (each holding at least one point): points inside a segment are connected,+ * segments are drawn apart, and a segment of one point draws only a point —+ * a line must never bridge an interval where the series has no value.+ */+export function lineSegments(values: readonly (number | null)[]): LinePoint[][] {+ const segments: LinePoint[][] = [];+ let current: LinePoint[] = [];+ values.forEach((value, index) => {+ if (value === null) {+ if (current.length > 0) segments.push(current);+ current = [];+ return;+ }+ current.push({ index, value });+ });+ if (current.length > 0) segments.push(current);+ return segments;+}++/** Straight-line path through one gap-free segment (`M` + `L`s); a one-point segment yields a bare `M` that strokes nothing, so callers draw its dot instead. */+export function segmentPath(geom: ChartGeom, segment: readonly LinePoint[]): string {+ return segment+ .map((p, i) => `${i === 0 ? "M" : "L"}${rnd(geom.x(p.index))},${rnd(geom.y(p.value))}`)+ .join(" ");+}+/** Sparse x-axis label indices: first, middle, last (labeling every point would blur together when cells are narrow and there are many points). */export function sparseLabelIdx(n: number): number[] {if (n <= 0) return [];@@ -119,12 +173,7 @@ export function autoLabelIdx(n: number, step: number): number[] {return idx;}-/** Request success rate: no requests (total=0) is treated as 1 (matches the old bar's convention, avoiding 0/0). */-export function successRate(completed: number, total: number): number {- return total > 0 ? completed / total : 1;-}--// —— Hover bubble placement (shared by both daily charts) ——+// —— Hover bubble placement (shared by every chart) ——/** Gap between the pointer and the bubble's near corner: close enough to read as attached, far enough that the bubble never sits under the pointer. */export const BUBBLE_OFFSET = 12;@@ -167,11 +216,9 @@ export function bubblePosition(// —— Daily Token: bar + three-segment stack ——/**- * Bar width (**real CSS pixels**, since 1 canvas unit = 1 pixel): **a fixed- * value, not a minimum** — it used to be implemented as "no less than 25px",- * which made bars stretch to fill the container when there were few points- * (3 daily points could balloon to ~180px), defeating the intent of "25px- * bar width". Now it's always 25px: scroll when it doesn't fit, and give the extra space to bar spacing when it does.+ * Ceiling on bar width (**real CSS pixels**, since 1 canvas unit = 1 pixel):+ * with few points the bars never balloon past this — the extra space goes to+ * bar spacing.*/export const BAR_W = 25;@@ -187,39 +234,23 @@ export const BAR_W = 25;*/export const MIN_HIT_H = 8;-/** The Token bar chart's horizontal layout: bar width (always BAR_W), total canvas width, and whether the content overflows the container (needing horizontal scroll). */-export interface TokenBarLayout {- /** Bar width (CSS pixels): always BAR_W. */- barW: number;- /** Total canvas width (CSS pixels): fills the container, or overflows it per "bar + equal spacing". */- chartW: number;- /** Canvas is wider than the container: the caller needs horizontal scrolling to see it all. */- scroll: boolean;-}-/**- * Token bar chart horizontal layout: **bar width is always BAR_W (25 real- * pixels), bar spacing ≥ bar width**.- * - Many points (n×2×25px doesn't fit): each cell is exactly 2× the bar- * width, and the canvas overflows the container in real pixels →- * the container scrolls horizontally (no scaling, no squeezing);- * - Few points (fits): the canvas fills the container, and **all the extra- * space goes to bar spacing** — bars no longer stretch (the old- * implementation treated 25px as a floor, letting 3 daily points' bars- * balloon to ~180px), they just stand farther apart.+ * Bar width that always fits the container (**no horizontal scrolling**): 60%+ * of the cell width — leaving ≥ 40% as spacing so adjacent bars never touch —+ * capped at BAR_W (few points must not balloon into slabs) and floored at 1px:+ * a dense range at fine granularity degrades to hairlines, not to overlap+ * (only a degenerate sub-1.7px cell can make the 1px floor fill its cell).*/-export function tokenBarLayout(containerW: number, n: number): TokenBarLayout {- const innerW = Math.max(0, containerW - PAD_L - PAD_R);- const needed = 2 * BAR_W * n; // inner width needed to lay out n bars (bar + equal spacing)- if (needed <= innerW) return { barW: BAR_W, chartW: containerW, scroll: false };- return { barW: BAR_W, chartW: PAD_L + needed + PAD_R, scroll: true };+export function fitBarWidth(step: number): number {+ return Math.max(1, Math.min(BAR_W, Math.floor(step * 0.6)));}-/** One segment within a bar: the visual rectangle is drawn strictly to value, the hit band is computed separately (small segments are raised to be hoverable). */-export interface BarSegment {- key: TokenBucketKey;+/** One segment within a stacked bar: the visual rectangle is drawn strictly to value, the hit band is computed separately (small segments are raised to be hoverable). */+export interface StackSegment {+ /** Position in the values array the segment came from (zero values produce no segment, so this is not the segment's own index). */+ index: number;value: number;- /** Visual rectangle: segments sit flush against each other, total height = the day's total (no visual floor, no inflating the bar's height). */+ /** Visual rectangle: segments sit flush against each other, total height = the bucket's total (no visual floor, no inflating the bar's height). */y: number;h: number;/** Hit band: fills the whole bar bottom-to-top with no overlap, small segments raised to minHit. */@@ -227,6 +258,11 @@ export interface BarSegment {hitH: number;}+/** A Token bar's segment, carrying the bucket key its color and label come from. */+export interface BarSegment extends StackSegment {+ key: TokenBucketKey;+}+/*** Hit-band height allocation (water-filling): segments below minHit are* raised to minHit, the rest share the remaining space proportionally to@@ -251,18 +287,17 @@ function hitHeights(heights: number[], total: number, minHit: number): number[]}}-/** Stacking order: bottom-to-top output → cacheWrite → cacheRead (matches TOKEN_COLORS' shading, darkest at the bottom). */-const STACK_ORDER: readonly TokenBucketKey[] = ["output", "cacheWrite", "cacheRead"];-/**- * A bar's three-segment stack: bottom-to-top output → cacheWrite →- * cacheRead, a zero-value bucket produces no segment (not drawn, and shouldn't be hoverable). The visual rectangle is drawn strictly to value; see hitHeights for the hit band.+ * A stacked bar's segments, bottom-to-top in array order: a zero value+ * produces no segment (nothing is drawn, and nothing should be hoverable).+ * The visual rectangle is drawn strictly to value; the hit band is widened+ * separately so a sub-pixel segment stays reachable — see hitHeights.+ *+ * Shared by every stacked bar on the page: the Token chart stacks its three+ * buckets, the requests charts stack one segment per entity.*/-export function barSegments(- geom: ChartGeom,- p: { cacheRead: number; cacheWrite: number; output: number },-): BarSegment[] {- const stack = STACK_ORDER.map((key) => ({ key, value: p[key] })).filter((b) => b.value > 0);+export function stackSegments(geom: ChartGeom, values: readonly number[]): StackSegment[] {+ const stack = values.map((value, index) => ({ index, value })).filter((b) => b.value > 0);if (stack.length === 0) return [];// Visual rectangles: the top edge is taken from the cumulative value, so segments sit flush against each other.@@ -284,8 +319,8 @@ export function barSegments(let hitBottom = base;return stack.map((b, i) => {const hitH = hits[i]!;- const seg: BarSegment = {- key: b.key,+ const seg: StackSegment = {+ index: b.index,value: b.value,y: rects[i]!.y,h: rects[i]!.h,@@ -297,67 +332,16 @@ export function barSegments(});}-// —— Each Agent's call count: pie chart ——--const TAU = Math.PI * 2;-/** Path coordinates keep 2 decimal places: the path string stays short and readable, and is easy to assert on in unit tests. */-const rnd = (v: number): number => Math.round(v * 100) / 100;--/** Take a point in polar coordinates: angle is measured from 12 o'clock, clockwise-positive (SVG's y-axis points down). */-function polar(cx: number, cy: number, r: number, angle: number): [number, number] {- const a = angle - Math.PI / 2;- return [rnd(cx + r * Math.cos(a)), rnd(cy + r * Math.sin(a))];-}--/** A single pie slice. */-export interface PieSlice {- /** Index within the passed-in values (the caller uses this to look up name and color). */- index: number;- value: number;- /** Fraction of the total [0,1]. */- frac: number;- /** Start/end angle (radians, clockwise from 12 o'clock). */- start: number;- end: number;- /** The slice's path. */- path: string;-}--/**- * Slice path: `M center L start A radius … end Z`; sweep=1 means clockwise,- * large-arc=1 when spanning more than a semicircle.- * At 100% the start and end points coincide and the A command degrades into- * "draws nothing" — split into two semicircular arcs to get a full circle.- */-function slicePath(cx: number, cy: number, r: number, start: number, end: number): string {- if (end - start >= TAU - 1e-9) {- const [tx, ty] = polar(cx, cy, r, 0);- const [bx, by] = polar(cx, cy, r, Math.PI);- return `M${tx},${ty} A${r},${r} 0 1 1 ${bx},${by} A${r},${r} 0 1 1 ${tx},${ty} Z`;- }- const [x0, y0] = polar(cx, cy, r, start);- const [x1, y1] = polar(cx, cy, r, end);- const large = end - start > Math.PI ? 1 : 0;- return `M${rnd(cx)},${rnd(cy)} L${x0},${y0} A${r},${r} 0 ${large} 1 ${x1},${y1} Z`;-}+/** Stacking order: bottom-to-top output → cacheWrite → cacheRead (matches TOKEN_COLORS' shading, darkest at the bottom). */+const STACK_ORDER: readonly TokenBucketKey[] = ["output", "cacheWrite", "cacheRead"];-/**- * Pie slices: laid out clockwise from 12 o'clock in the order passed in,- * each slice's angle = that value's share of the total.- * Non-positive values produce no slice (a 0-degree arc is a degenerate- * path); when the total ≤ 0, returns empty (the caller falls back to an empty state).- */-export function pieSlices(values: number[], cx: number, cy: number, r: number): PieSlice[] {- const total = values.reduce((s, v) => s + Math.max(0, v), 0);- if (total <= 0) return [];- const slices: PieSlice[] = [];- let start = 0;- values.forEach((value, index) => {- if (value <= 0) return;- const frac = value / total;- const end = start + frac * TAU;- slices.push({ index, value, frac, start, end, path: slicePath(cx, cy, r, start, end) });- start = end;- });- return slices;+/** A Token bar's three-segment stack (see stackSegments), keyed by bucket so the caller can look up color and label. */+export function barSegments(+ geom: ChartGeom,+ p: { cacheRead: number; cacheWrite: number; output: number },+): BarSegment[] {+ return stackSegments(+ geom,+ STACK_ORDER.map((key) => p[key]),+ ).map((seg) => ({ ...seg, key: STACK_ORDER[seg.index]! }));}diff --git a/packages/web/src/features/usage/chart-svg.tsx b/packages/web/src/features/usage/chart-svg.tsxindex f0f8d938..1b297968 100644--- a/packages/web/src/features/usage/chart-svg.tsx+++ b/packages/web/src/features/usage/chart-svg.tsx@@ -23,6 +23,11 @@* necessary x-position indicator, while on the bar chart the bar itself* already indicates the x position — an extra vertical line would just be* noise, so the bar chart passes hoverLine={false} to turn it off.+ *+ * The usage charts drop the buckets that recorded nothing before they get+ * here, so their x axis covers unequal spans of time; axisBreaks draws the+ * "//" between two points that are not neighbours, which is what keeps the+ * axis from being read as a continuous one.*/import {useEffect,@@ -36,12 +41,63 @@ import {bubblePosition,CHART_H,PAD_L,- PAD_R,PAD_T,sparseLabelIdx,type ChartGeom,} from "./chart-geom";+/** Height (CSS px) of the invisible band laid over a line series so it can be hovered: a 2px stroke is too thin to aim at. */+export const LINE_HIT_H = 10;++/**+ * Stroke width of every data line on the page — the cost line, the+ * success-rate lines, the cache-hit-rate curve. One weight for all of them,+ * so no line reads as more important than another just because it was written+ * later. Chrome (grid lines, the hover indicator, axis-break marks) stays at+ * 1 and is deliberately not this.+ */+export const DATA_STROKE_W = 2;++/** Cell width (CSS px) below which axis-break marks are dropped: any narrower and successive marks sit closer together than they are wide, smearing into a hatched baseline. */+const AXIS_BREAK_MIN_STEP = 8;++/**+ * Hover bands for a line series, one per bucket: a transparent rect the width+ * of the cell, centred on that bucket's point. Put these in ChartFrame's+ * `hitLayer` **after** the bar hits, so a line stays reachable where it runs+ * across a tall segment — the lines draw above the bars, and they answer the+ * pointer above them too.+ *+ * Per bucket rather than one band along the whole path, so entering anywhere+ * on the line reports which bucket the pointer is over as well as which+ * series it belongs to.+ */+export function LineHits({+ geom,+ values,+ onEnter,+ onLeave,+}: {+ geom: ChartGeom;+ values: readonly number[];+ onEnter: (i: number) => void;+ onLeave?: () => void;+}) {+ return values.map((v, i) => (+ <rect+ key={i}+ x={geom.x(i) - geom.step / 2}+ y={geom.y(v) - LINE_HIT_H / 2}+ width={geom.step}+ height={LINE_HIT_H}+ fill="transparent"+ className="cursor-pointer"+ onMouseEnter={() => onEnter(i)}+ onMouseLeave={onLeave}+ />+ ));+}+/*** Measure the available width inside the chart card (CSS pixels, rounded* down — a few stray tenths of a pixel would otherwise spawn a scrollbar out of nowhere).@@ -76,9 +132,11 @@ export function ChartFrame({bubble,hitLayer,labels,+ fmtX,yTicks,+ rightAxis,hoverLine = true,- scrollToEnd = false,+ axisBreaks,children,}: {geom: ChartGeom;@@ -96,12 +154,16 @@ export function ChartFrame({hitLayer?: ReactNode;/** Indices for x-axis labels (omit for the default first/middle/last sparse labeling): the bar chart's cells are each wide, so it can label more via autoLabelIdx. */labels?: number[];+ /** x-axis label formatting. Defaults to dropping a date's year (`slice(5)` → `mm-dd`); series charts pass their own granularity-aware short form. */+ fmtX?: (d: string) => string;/** Explicit y-axis ticks. Omit to divide the geom's min..max range into four equal intervals. */yTicks?: number[];+ /** Right-hand axis for an overlay drawn on its own scale (the Token chart's cache-hit-rate curve): tick values, their y mapping, and label formatting. Give the geom PAD_R_AXIS so the labels have room. */+ rightAxis?: { y: (v: number) => number; ticks: number[]; fmt: (v: number) => string };/** Hover vertical indicator line (drawn by default): the bar chart turns it off — the bar itself already indicates the x position, so an extra line is just noise. */hoverLine?: boolean;- /** Scroll to the far right by default when the canvas is wider than the container: the daily chart shows the most recent days first (scroll left for earlier ones). */- scrollToEnd?: boolean;+ /** Indices after which the x axis skips at least one interval (the usage charts drop the buckets that recorded nothing): a break mark is drawn between that point and the next, so a compressed axis never reads as a continuous one. */+ axisBreaks?: number[];/** Data marks: bars / line / area, drawn between the grid and the hit area. */children?: ReactNode;}) {@@ -111,15 +173,6 @@ export function ChartFrame({const labelIdx = labels ?? sparseLabelIdx(dates.length);const scrollRef = useRef<HTMLDivElement>(null);- // The daily chart defaults to sitting on the most recent day (there's only- // room to scroll when the canvas is wider than the container). It- // re-snaps whenever the data or canvas width changes, without disturbing a position the user has manually scrolled to in the meantime.- useLayoutEffect(() => {- const el = scrollRef.current;- if (!scrollToEnd || !el) return;- el.scrollLeft = el.scrollWidth - el.clientWidth;- }, [scrollToEnd, w, dates.length]);-// The bubble follows the pointer **imperatively** (lower-right, flipping// at the edges — see chart-geom's bubblePosition): mousemove only records// the client position and schedules a single rAF, whose callback batches@@ -170,9 +223,9 @@ export function ChartFrame({useLayoutEffect(placeBubble, [bubble, hover]);return (- // Horizontal scroll when the canvas is wider than the container (bar- // width has a pixel floor, so 30 days won't fit in a half-width panel);- // the bubble is this container's absolutely-positioned child element and scrolls along with the content, so anchoring it to the pointer in content pixels is enough.+ // The canvas is measured from this container and bars shrink to fit it, so+ // there is nothing to scroll; the box stays scroll-aware because the bubble+ // is its absolutely-positioned child and is anchored in content pixels.<div ref={scrollRef} className="relative overflow-x-auto"><svgref={svgRef}@@ -197,7 +250,7 @@ export function ChartFrame({<g key={i}><linex1={PAD_L}- x2={w - PAD_R}+ x2={w - geom.padR}y1={y(v)}y2={y(v)}className="stroke-gray-200 dark:stroke-gray-800"@@ -215,6 +268,20 @@ export function ChartFrame({</g>))}+ {/* Right-hand axis ticks (an overlay's own scale, e.g. a percentage) */}+ {rightAxis?.ticks.map((v) => (+ <text+ key={`r${v}`}+ x={w - geom.padR + 6}+ y={rightAxis.y(v) + 3}+ textAnchor="start"+ className="fill-gray-400 dark:fill-gray-500"+ fontSize={9}+ >+ {rightAxis.fmt(v)}+ </text>+ ))}+{/* Hover vertical indicator line (line-chart-only: the bar chart's bar itself is the x indicator, see hoverLine) */}{hoverLine && hover !== null && dates[hover] && (<line@@ -230,6 +297,34 @@ export function ChartFrame({{/* Data marks (provided by the caller) */}{children}+ {/* Axis breaks: the "//" that says the two points either side of it are+ not neighbours in time. Drawn over the marks (the cost chart's area+ fill reaches the baseline) but never hoverable — the hit layer below+ owns the pointer. */}+ {step >= AXIS_BREAK_MIN_STEP &&+ axisBreaks?.map((i) =>+ i + 1 < geom.n ? (+ <g+ key={`break-${i}`}+ className="pointer-events-none stroke-gray-400 dark:stroke-gray-500"+ strokeWidth={1}+ >+ {[-2, 2].map((dx) => {+ const cx = (x(i) + x(i + 1)) / 2 + dx / 2;+ return (+ <line+ key={dx}+ x1={cx - 2}+ y1={PAD_T + innerH + 3}+ x2={cx + 2}+ y2={PAD_T + innerH - 3}+ />+ );+ })}+ </g>+ ) : null,+ )}+{/* x-axis dates */}{labelIdx.map((i) => {const d = dates[i];@@ -243,7 +338,7 @@ export function ChartFrame({className="fill-gray-400 dark:fill-gray-500"fontSize={9}>- {d.slice(5)}+ {(fmtX ?? ((v: string) => v.slice(5)))(d)}</text>);})}diff --git a/packages/web/src/features/usage/errors-panel.tsx b/packages/web/src/features/usage/errors-panel.tsxindex 6d1908ad..69b9ec6b 100644--- a/packages/web/src/features/usage/errors-panel.tsx+++ b/packages/web/src/features/usage/errors-panel.tsx@@ -69,7 +69,7 @@ function Stat({);}-/** Header cell: left-aligned, recessive gray; stickiness is handled by thead. */+/** Header cell: left-aligned, recessive gray. */function Th({ children, className = "" }: { children: React.ReactNode; className?: string }) {return <th className={`py-1.5 pr-2 font-medium ${className}`}>{children}</th>;}@@ -80,7 +80,8 @@ function Th({ children, className = "" }: { children: React.ReactNode; className* fill the table); clicking a message expands it in place to the full text (wrapping, newlines* preserved — the upstream detail after the code, e.g. a provider's 402 body, is what matters),* and clicking again collapses it. The full text is also in the hover title. Cells align to the- * top so an expanded multi-line message keeps the row tidy; the table scrolls past max height.+ * top so an expanded multi-line message keeps the row tidy; height is bounded by the page size+ * alone — the table never scrolls (paging is the way past it).*/export function ErrorsPanel({errors,@@ -187,9 +188,9 @@ export function ErrorsPanel({{items.length === 0 ? (<Empty text={S.usage.errorsEmpty} />) : (- <div className="mt-2.5 max-h-72 overflow-y-auto border-t border-gray-200 dark:border-gray-800">+ <div className="mt-2.5 border-t border-gray-200 dark:border-gray-800"><table className="w-full table-fixed text-xs">- <thead className="sticky top-0 bg-white text-left text-gray-400 dark:bg-gray-900 dark:text-gray-500">+ <thead className="text-left text-gray-400 dark:text-gray-500"><tr><Th className="w-32">{S.common.time}</Th>{/* Wide enough to fully fit the longest error code: a tooldiff --git a/packages/web/src/features/usage/trend-chart.tsx b/packages/web/src/features/usage/trend-chart.tsxindex a1cbb0b9..08766b10 100644--- a/packages/web/src/features/usage/trend-chart.tsx+++ b/packages/web/src/features/usage/trend-chart.tsx@@ -1,37 +1,61 @@/**- * Daily cost trend chart (hand-drawn SVG, no chart- * library; a single accent color + gray grid, desaturated in dark mode, no- * clashing red/green): a line + a semi-transparent area layered down to the- * baseline to reinforce the trend over time, with a hover vertical line + whole-column hit area + bubble.- * The coordinate system / grid / hover logic is extracted into chart-svg.tsx's ChartFrame (shared with the daily Token bar chart).+ * Cost trend chart (hand-drawn SVG, no chart library; a single accent color ++ * gray grid, desaturated in dark mode, no clashing red/green): a straight+ * polyline with a dot on every data point + a semi-transparent area layered+ * down to the baseline to reinforce the trend over time, with a hover vertical+ * line + whole-column hit area + bubble. The coordinate system / grid / hover+ * logic is chart-svg.tsx's ChartFrame (shared with the other usage charts).** Canvas width = the container's measured pixels (1 unit = 1 pixel, see- * chart-svg): the line chart itself has no "minimum step" requirement, so it- * simply fills the container and never scrolls horizontally — but once the- * Token bar chart went full-width, this chart shares the same row, and if it- * still stretched a fixed 640-unit viewBox, its height would get capped by max-h and centered with large empty margins on both sides.+ * chart-svg): the chart simply fills the container and never scrolls+ * horizontally.+ *+ * The caller hands over a series whose empty buckets have already been+ * dropped (usage-controls' compactSeries), so the points sit left to right+ * over only the intervals that recorded something and the geometry spreads+ * them across the card. A bucket that ran but has no priced model still+ * counts: it reads as a cost of 0, not a dash. `breaks` marks where the axis+ * skipped an interval.*/import { useState } from "react";-import type { UsageTrendPoint } from "@prismshadow/penguin-server/api";+import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";import { formatMoney } from "../../lib/format";import type { Currency } from "../../state/theme";import { makeGeom, linePath, areaPath } from "./chart-geom";-import { ChartFrame, useChartWidth } from "./chart-svg";+import { ChartFrame, DATA_STROKE_W, useChartWidth } from "./chart-svg";+import { bucketAxisLabel, bucketFullLabel } from "./usage-controls";+import { Empty } from "./usage-charts";++/** Cell width (CSS pixels) below which per-point dots stop being drawn: 2.5px radius plus breathing room. */+const MIN_DOT_STEP = 8;export function TrendChart({- points,+ series,+ granularity,currency = "USD",+ breaks,}: {- points: UsageTrendPoint[];+ series: UsageSeriesPoint[];+ granularity: UsageGranularity;currency?: Currency;+ /** Indices after which the series skipped at least one empty bucket (see compactSeries): ChartFrame marks the axis there. */+ breaks?: number[];}) {const [hover, setHover] = useState<number | null>(null);const [ref, width] = useChartWidth();+ // Nothing was recorded anywhere in the range: an empty grid would read as a+ // flat zero cost, so say there is nothing rather than draw nothing.+ if (series.length === 0) return <Empty />;- const cost = points.map((p) => p.cost ?? 0);+ const cost = series.map((p) => p.cost ?? 0);const max = Math.max(1e-9, ...cost);- const geom = makeGeom(points.length, max, width);- const dates = points.map((p) => p.date);+ const geom = makeGeom(series.length, max, width);+ const buckets = series.map((p) => p.bucket);+ // Dots are drawn only where the cells are wide enough to hold them apart: a+ // 2.5px-radius dot needs roughly this much room or the row fuses into a rope+ // (61 minute buckets in a half-width card sit ~7px apart). Below that the+ // line stands alone and only the hovered point gets its dot.+ const everyDot = geom.step >= MIN_DOT_STEP;return (<div ref={ref}>@@ -39,15 +63,17 @@ export function TrendChart({<ChartFramegeom={geom}fmtY={(v) => formatMoney(v, currency)}- dates={dates}+ dates={buckets}+ fmtX={(b) => bucketAxisLabel(granularity, b)}hover={hover}onHover={setHover}+ axisBreaks={breaks}bubble={(i) => {- const p = points[i]!;+ const p = series[i]!;return (<>- <p className="text-gray-400">{p.date}</p>- <p className="font-mono">{formatMoney(p.cost, currency)}</p>+ <p className="text-gray-400">{bucketFullLabel(granularity, p.bucket)}</p>+ <p className="font-mono">{formatMoney(p.cost ?? 0, currency)}</p></>);}}@@ -64,19 +90,28 @@ export function TrendChart({d={linePath(geom, cost)}fill="none"stroke="currentColor"- strokeWidth={2}+ strokeWidth={DATA_STROKE_W}opacity={hover !== null ? 0.35 : 1}/>- {points.map((p, i) => (+ {everyDot &&+ series.map((p, i) => (+ <circle+ key={p.bucket}+ cx={geom.x(i)}+ cy={geom.y(cost[i] ?? 0)}+ r={hover === i ? 4 : 2.5}+ className="fill-current"+ opacity={hover !== null && hover !== i ? 0.25 : 1}+ />+ ))}+ {!everyDot && hover !== null && (<circle- key={p.date}- cx={geom.x(i)}- cy={geom.y(p.cost ?? 0)}- r={hover === i ? 4 : 2.5}+ cx={geom.x(hover)}+ cy={geom.y(cost[hover] ?? 0)}+ r={4}className="fill-current"- opacity={hover !== null && hover !== i ? 0.25 : 1}/>- ))}+ )}</g></ChartFrame>)}diff --git a/packages/web/src/features/usage/usage-charts.tsx b/packages/web/src/features/usage/usage-charts.tsxindex c32b0c5a..603f3743 100644--- a/packages/web/src/features/usage/usage-charts.tsx+++ b/packages/web/src/features/usage/usage-charts.tsx@@ -1,43 +1,69 @@/**- * Cost center stat charts: hand-drawn SVG- * / flex, no chart library. The form follows the nature of the data —- * - AgentPieChart: each Agent's call count → a pie chart (compositional- * share; each slice's angle is that Agent's share of total calls);- * - SuccessBarChart: each Model's success rate → a horizontal progress bar- * with a 100% track (shows how far from perfect at a glance), filled with- * a single uniform color (the bar's length alone conveys magnitude, not a three-color threshold);- * - TokenBarChart: daily Token buckets → a three-segment stacked bar (one- * bar per day, bottom-to-top output → cacheWrite → cacheRead, same blue- * family, darkest at the bottom and lightest at the top; bar width fixed- * at 25 real pixels, spacing ≥ bar width, scrolls horizontally when it doesn't fit the card).- * Daily cost reuses TrendChart (line + area fill).+ * Cost center stat charts: hand-drawn SVG / flex, no chart library. Every+ * chart is a time series over the page's shared date range and precision —+ * - RequestsChart: one dimension's requests and success rate on one pair of+ * axes — per-bucket requests stacked by entity on the left count axis, one+ * dashed success-rate line per entity on the right-hand 0–100% axis (drawn+ * above the bars), a legend underneath. The page mounts it twice, by Agent+ * and by Model, so both breakdowns are on screen without a toggle. Top+ * entities keep their own CVD-checked hue and the tail folds into a neutral+ * series labelled with how many it swallowed.+ * - TokenBarChart: per-bucket Token buckets as a three-segment stacked bar+ * (bottom-to-top output → cacheWrite → cacheRead, same blue family, darkest+ * at the bottom), with the cache hit rate as a dashed line **in front of the+ * bars** on its own right-hand 0–100% axis. Bars always fit the card+ * (fitBarWidth) — the charts never scroll.+ * Cost reuses TrendChart (straight line + area fill, with a dot per point+ * wherever the cells are wide enough to keep the dots apart).+ *+ * One x axis for the whole page: every chart is handed the same series with+ * its empty buckets already dropped (compactSeries, called once by the page),+ * so all four run left to right over the same intervals and can be read+ * against each other. A bucket only counts as empty when nothing at all was+ * recorded in it, so an entity that was idle while another one worked keeps+ * its place in that column — as a zero and a dash, not as a missing bucket.+ * `breaks` marks where the axis skipped an interval.+ *+ * Every data line is drawn at DATA_STROKE_W, and a bucket with no rate to+ * show is drawn at NO_RATE_PLOT so the stroke stays continuous. Neither is a+ * claim about the data: the hover table prints a dash there.** Unified highlight interaction (a site-wide convention): highlight = fade- * out the rest. Pie slices and the legend are linked both ways; the Token- * bar is **precise down to the segment** — hovering a given day's given- * bucket lights up only that segment, and the bubble reports only that segment's value (not the whole column's total).+ * out the rest, and every chart offers the same three ways in: hover a column+ * for its bubble, hover one bar segment to single that segment out, hover a+ * line's own band to single the line out. A legend item does what hovering+ * its mark does. Line hit bands sit above the bars' in every chart, so a line+ * answers the pointer wherever it runs.*/import { useState } from "react";-import type {- UsageAgentCount,- UsageSuccessRate,- UsageTrendPoint,-} from "@prismshadow/penguin-server/api";-import { catalogEntryFor, providerInfo } from "@prismshadow/penguin-core/model-catalog";+import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";import { S } from "../../lib/strings";-import { cacheHitRate, formatPercent, humanizeTokens } from "../../lib/format";+import { formatPercent, humanizeTokens } from "../../lib/format";import { TOKEN_COLORS } from "../../lib/token-colors";-import { categoryColor } from "../../lib/category-colors";+import { NEUTRAL_SERIES, seriesColor, type SeriesColor } from "../../lib/category-colors";import {makeGeom,+ makeRangeGeom,autoLabelIdx,barSegments,- tokenBarLayout,- pieSlices,- successRate,+ fitBarWidth,+ linePath,+ stackSegments,+ PAD_R_AXIS,type TokenBucketKey,} from "./chart-geom";-import { ChartFrame, useChartWidth } from "./chart-svg";+import { ChartFrame, DATA_STROKE_W, LineHits, useChartWidth } from "./chart-svg";+import {+ bucketAxisLabel,+ bucketFullLabel,+ foldEntitySeries,+ hitRateValues,+ plotRates,+ rateSeries,+ sumCounts,+ type EntityCounts,+ type EntitySeries,+} from "./usage-controls";/** Empty state for a chart card (defaults to "no usage records yet"; the errors chart passes its own copy). */export function Empty({ text }: { text?: string }) {@@ -51,237 +77,393 @@ function bucketLabel(key: TokenBucketKey): string {return S.usage.colOutput;}-/** Highlight = fade out the rest. */-const DIM = "opacity-25";--// —— Each Agent's call count: pie chart ——--/** Pie chart canvas (square viewBox) and radius: leave a 5px margin so slice edges don't get clipped by the viewBox. */-const PIE_SIZE = 160;-const PIE_R = 75;+/** Smallest multiple of 4 that covers the data (at least 4), so quartered gridlines land on integers. */+function niceCountMax(...values: number[]): number {+ return Math.max(4, Math.ceil(Math.max(0, ...values) / 4) * 4);+}/**- * Each Agent's call count → a pie chart: each slice's angle = that Agent's- * share of total calls, laid out clockwise from 12 o'clock sorted by- * requests descending (re-sorted here defensively). Slices and the legend- * on the right link both ways: hovering either side lights up the other and fades out the rest.- * When a single Agent holds 100%, pieSlices degrades to a full circle (see chart-geom).+ * A rate in the hover table. A real 0 prints `0%`; a bucket that had nothing+ * to rate has no number at all and prints formatPercent's dash — the same+ * dash the rest of the app uses for an undefined ratio. The 100 those buckets+ * are *drawn* at (NO_RATE_PLOT) never reaches this table: the line is a shape,+ * the table is the data.*/-export function AgentPieChart({ data }: { data: UsageAgentCount[] }) {- const [hover, setHover] = useState<number | null>(null);- const total = data.reduce((s, d) => s + d.requests, 0);- if (data.length === 0 || total <= 0) return <Empty />;+function rateCell(v: number | null | undefined): string {+ return formatPercent(v == null ? null : v / 100);+}- const rows = [...data].sort((a, b) => b.requests - a.requests);- const slices = pieSlices(- rows.map((d) => d.requests),- PIE_SIZE / 2,- PIE_SIZE / 2,- PIE_R,- );- const pct = (v: number) => `${Math.round((v / total) * 100)}%`;- const dim = (i: number) => (hover !== null && hover !== i ? DIM : "");+/** Text/swatch classes for the i-th drawn entity (the folded tail wears the neutral). */+function entityColor(s: EntitySeries, i: number): SeriesColor {+ return s.other ? NEUTRAL_SERIES : seriesColor(i);+}- return (- <div className="flex items-center gap-3" onMouseLeave={() => setHover(null)}>- <svg- viewBox={`0 0 ${PIE_SIZE} ${PIE_SIZE}`}- className="h-40 w-40 shrink-0"- role="img"- aria-label={S.usage.chartAgentCalls}- >- {slices.map((s) => {- const d = rows[s.index]!;- return (- <path- key={d.agentId}- d={s.path}- onMouseEnter={() => setHover(s.index)}- className={`cursor-pointer ${categoryColor(s.index).fill} transition-opacity duration-150 ${dim(s.index)}`}- >- <title>{`${d.agentId} · ${d.requests} ${S.usage.requests} · ${pct(d.requests)}`}</title>- </path>- );- })}- </svg>+// —— Requests + success rate, broken down by entity ——- {/* Legend: name + count + share (hover links to the pie slice; a long agentId truncates, with the title giving the full name and total Token count) */}- <ul className="flex max-h-40 min-w-0 flex-1 flex-col gap-1 overflow-y-auto">- {rows.map((d, i) => (- <li- key={d.agentId}- onMouseEnter={() => setHover(d.requests > 0 ? i : null)}- title={`${d.agentId} · ${d.requests} ${S.usage.requests} · ${humanizeTokens(d.total)}`}- className={`flex cursor-pointer items-center gap-1.5 text-[10px] transition-opacity duration-150 ${dim(i)}`}- >- <span- className={`inline-block h-2 w-2 shrink-0 rounded-sm ${categoryColor(i).swatch}`}- />- <span className="min-w-0 flex-1 truncate font-mono text-gray-500 dark:text-gray-400">- {d.agentId}- </span>- <span className="shrink-0 font-mono tabular-nums text-gray-500 dark:text-gray-400">- {d.requests}- </span>- <span className="w-8 shrink-0 text-right font-mono tabular-nums text-gray-400 dark:text-gray-500">- {pct(d.requests)}- </span>- </li>- ))}- </ul>- </div>- );+/**+ * What is currently singled out in a requests chart. `entity` is the series;+ * `bucket` narrows it to one column when the pointer is on a specific bar+ * segment, and is null when the whole series is meant (a legend item or the+ * rate line). One shape for all three affordances, so they cannot disagree+ * about what is lit.+ */+interface RequestsMark {+ entity: number;+ bucket: number | null;}-// —— Each Model's success rate: horizontal progress bar ——--/** A progress bar row's shell: label on the left + track/fill in the middle + value on the right. Fades when hovering a different row. */-function BarRow({- dimmed,- onEnter,- title,- label,- value,- children,+/**+ * Legend row under a requests chart: one square swatch per drawn entity —+ * that entity's bar segments and its success-rate line share the hue, so one+ * item covers both — plus a neutral line swatch naming what the lines are.+ * Hovering an item highlights that entity (site-wide convention: highlight =+ * fade out the rest).+ */+function RequestsLegend({+ entities,+ active,+ onHover,}: {- dimmed: boolean;- onEnter: () => void;- title: string;- label: string;- value: string;- children: React.ReactNode;+ entities: EntitySeries[];+ active: number | null;+ onHover: (i: number | null) => void;}) {return (- <div- onMouseEnter={onEnter}- className={`flex cursor-pointer items-center gap-2 transition-opacity duration-150 ${dimmed ? DIM : ""}`}- title={title}- >- <span className="w-24 shrink-0 truncate font-mono text-[10px] text-gray-500 dark:text-gray-400">- {label}- </span>- {children}- <span className="w-10 shrink-0 text-right font-mono text-[10px] tabular-nums text-gray-500 dark:text-gray-400">- {value}+ <div className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] text-gray-500 dark:text-gray-400">+ {entities.map((e, i) => (+ <button+ key={`${e.label}:${i}`}+ type="button"+ onMouseEnter={() => onHover(i)}+ onMouseLeave={() => onHover(null)}+ className={`flex min-w-0 items-center gap-1.5 transition-opacity duration-150 ${+ active != null && active !== i ? "opacity-30" : ""+ }`}+ >+ <span+ className={`inline-block h-2 w-2 shrink-0 rounded-[2px] ${entityColor(e, i).swatch}`}+ />+ <span className="max-w-40 truncate font-mono">{e.label}</span>+ </button>+ ))}+ {/* The lines wear each entity's own hue, so their legend item is about shape, not color: a neutral dash saying "the lines are the success rate, on the right axis". */}+ <span className="flex items-center gap-1.5">+ <span className={`inline-block h-0.5 w-3 shrink-0 rounded-sm ${NEUTRAL_SERIES.swatch}`} />+ {S.usage.legendSuccessRate}</span></div>);}-/** Row label: falls back from the catalog display name to the upstream id ((provider, modelId) paired lookup against the catalog). */-function successLabel(d: UsageSuccessRate): string {- return catalogEntryFor(d.provider, d.modelId)?.displayName ?? d.modelId;-}--/**- * Hover detail: the model's paired reference (upstream id + provider name) +- * `completed/denominator` + a failure breakdown + excluded aborted runs. The- * denominator already excludes aborted (the user clicking "stop" isn't a- * model failure), so aborted is listed as its own item and labeled "not counted".- */-function successTitle(d: UsageSuccessRate): string {- const parts = [`${d.completed}/${d.total}`];- if (d.failed > 0) parts.push(`failed ${d.failed}`);- if (d.timeout > 0) parts.push(`timeout ${d.timeout}`);- if (d.malformed > 0) parts.push(`malformed ${d.malformed}`);- if (d.aborted > 0) parts.push(`${S.usage.successAborted} ${d.aborted}`);- const provider = providerInfo(d.provider)?.label ?? d.provider;- return `${d.modelId} · ${provider} · ${parts.join(" · ")}`;-}-/**- * Each Model's success rate → a horizontal progress bar: the 100% track- * (light gray) makes "how far from perfect" obvious at a glance, with the- * percentage shown on the right. Filled with a **single uniform color**- * (sky, the same primary color family as the Token chart): the bar's length- * alone already conveys magnitude — a three-color threshold (green/yellow/red) would just re-encode the same information and add two more colors to the page unrelated to any site-wide meaning.+ * One dimension's requests and success rate on one pair of axes: per-bucket+ * request counts stacked by entity against the left count axis, and one+ * success-rate line per entity against the right-hand 0-100% axis. The page+ * mounts this twice, once per dimension, so both breakdowns are on screen at+ * once with no toggle between them.+ *+ * Only the top MAX_NAMED_SERIES entities are drawn by name; the rest fold+ * into a neutral tail labelled with how many it swallowed, so the chart never+ * implies the head is everything.+ *+ * The buckets are the page's compacted ones, and `entities` has been moved+ * onto them by the same kept list (compactCounts), so a column's bars and its+ * rate points come from the same interval. A bucket only one entity ran in is+ * still a bucket: the idle ones sit at zero in it with a dash for their rate.+ *+ * A bucket an entity had nothing to rate in has no rate: the line crosses it+ * at the top of the axis (NO_RATE_PLOT) so the stroke stays continuous, and+ * the bubble's table prints a dash there — never a number the bucket does not+ * have, and never the 0% that would read as "failed everything".+ *+ * Three ways to single out a series, all resolving to one RequestsMark: hover+ * a bar segment (that entity in that bucket), hover a rate line, or hover a+ * legend item (that entity everywhere). The lines are drawn above the bars+ * and their hit bands sit above the bars' too, so a line is never lost behind+ * a tall segment.*/-export function SuccessBarChart({ data }: { data: UsageSuccessRate[] }) {+export function RequestsChart({+ series,+ entities,+ granularity,+ breaks,+}: {+ series: UsageSeriesPoint[];+ /** Per-entity counts, already re-indexed onto `series` by compactCounts — the stack and its rate lines read them by position. */+ entities: EntityCounts[];+ granularity: UsageGranularity;+ /** Indices after which the series skipped at least one empty bucket (see compactSeries): ChartFrame marks the axis there. */+ breaks?: number[];+}) {const [hover, setHover] = useState<number | null>(null);- if (data.length === 0) return <Empty />;+ const [mark, setMark] = useState<RequestsMark | null>(null);+ const [ref, width] = useChartWidth();+ const drawn = foldEntitySeries(entities, S.usage.legendOther);+ if (series.length === 0 || drawn.length === 0) return <Empty />;++ const totals = sumCounts(drawn);+ const totalRate = rateSeries(totals);+ // Two readings of the same rates: `rates` keeps the nulls for the table,+ // `lines` gives every bucket a height so the strokes stay unbroken.+ const rates = drawn.map((e) => rateSeries(e));+ const lines = rates.map(plotRates);+ const geom = makeGeom(series.length, niceCountMax(...totals.requests), width, PAD_R_AXIS);+ const rateGeom = makeRangeGeom(series.length, 0, 100, width, PAD_R_AXIS);+ const barW = fitBarWidth(geom.step);+ const buckets = series.map((p) => p.bucket);+ const segs = series.map((_, i) =>+ stackSegments(+ geom,+ drawn.map((e) => e.requests[i] ?? 0),+ ),+ );+ // Highlight = fade out the rest. A mark on a whole series lights all of it; a+ // mark on one segment lights that rect and keeps its own line lit with it, so+ // the bar and the rate it produced are read together.+ const barLit = (entity: number, i: number) =>+ mark === null || (mark.entity === entity && (mark.bucket === null || mark.bucket === i));+ const lineLit = (entity: number) => mark === null || mark.entity === entity;+ const barOpacity = (entity: number, i: number) => {+ if (!barLit(entity, i)) return 0.15;+ return mark === null && hover !== null && hover !== i ? 0.35 : 1;+ };+return (- <div className="flex flex-col gap-1.5" onMouseLeave={() => setHover(null)}>- {data.map((d, i) => {- const rate = successRate(d.completed, d.total);- const pct = Math.round(rate * 100);- return (- <BarRow- // Row key is a pair: the same model_id can coexist under multiple providers, so using modelId alone would collide.- key={`${d.provider}:${d.modelId}`}- dimmed={hover !== null && hover !== i}- onEnter={() => setHover(i)}- title={successTitle(d)}- label={successLabel(d)}- value={`${pct}%`}+ <div ref={ref}>+ {width > 0 && (+ <>+ <ChartFrame+ geom={geom}+ fmtY={(v) => String(Math.round(v))}+ dates={buckets}+ fmtX={(b) => bucketAxisLabel(granularity, b)}+ hover={hover}+ onHover={(i) => {+ if (i === null) {+ setHover(null);+ setMark(null);+ } else setHover(i);+ }}+ labels={autoLabelIdx(series.length, geom.step)}+ hoverLine={false}+ axisBreaks={breaks}+ rightAxis={{ y: rateGeom.y, ticks: [0, 50, 100], fmt: (v) => `${v}%` }}+ bubble={(i) => (+ <>+ <p className="text-gray-400">{bucketFullLabel(granularity, buckets[i]!)}</p>+ {drawn.map((e, si) => (+ <p+ key={`${e.label}:${si}`}+ className={`flex items-center gap-1.5 font-mono ${+ mark?.entity === si ? "font-semibold" : ""+ }`}+ >+ <span+ className={`inline-block h-2 w-2 shrink-0 rounded-[2px] ${entityColor(e, si).swatch}`}+ />+ <span className="max-w-32 truncate">{e.label}</span>+ <span className="ml-auto min-w-8 pl-2 text-right tabular-nums">+ {e.requests[i] ?? 0}+ </span>+ <span className="min-w-10 pl-1.5 text-right tabular-nums">+ {rateCell(rates[si]![i])}+ </span>+ </p>+ ))}+ {drawn.length > 1 && (+ <p className="flex items-center gap-1.5 font-mono text-gray-500 dark:text-gray-400">+ <span className="inline-block h-2 w-2 shrink-0" />+ <span className="max-w-32 truncate">{S.usage.bucketTotal}</span>+ <span className="ml-auto min-w-8 pl-2 text-right tabular-nums">+ {totals.requests[i] ?? 0}+ </span>+ <span className="min-w-10 pl-1.5 text-right tabular-nums">+ {rateCell(totalRate[i])}+ </span>+ </p>+ )}+ </>+ )}+ hitLayer={[+ // Column hits first (underneath): anywhere in the column reports the bucket.+ ...series.map((_, i) => (+ <rect+ key={`col-${buckets[i]}`}+ x={geom.x(i) - geom.step / 2}+ y={0}+ width={geom.step}+ height={geom.y(0)}+ fill="transparent"+ className="cursor-crosshair"+ onMouseEnter={() => {+ setHover(i);+ setMark(null);+ }}+ />+ )),+ // Per-segment hits next: as wide as the bar, split vertically with no+ // overlap and a minimum height, so a one-request segment is still reachable.+ ...series.map((_, i) =>+ segs[i]!.map((seg) => (+ <rect+ key={`seg-${buckets[i]}-${seg.index}`}+ x={geom.x(i) - barW / 2}+ y={seg.hitY}+ width={barW}+ height={seg.hitH}+ fill="transparent"+ className="cursor-pointer"+ onMouseEnter={() => {+ setHover(i);+ setMark({ entity: seg.index, bucket: i });+ }}+ />+ )),+ ),+ // Line hits last, so they win wherever a line crosses a bar.+ ...drawn.map((e, si) => (+ <LineHits+ key={`line-${e.label}:${si}`}+ geom={rateGeom}+ values={lines[si]!}+ onEnter={(i) => {+ setHover(i);+ setMark({ entity: si, bucket: null });+ }}+ />+ )),+ ]}>- <div className="h-3 min-w-0 flex-1 overflow-hidden rounded-sm bg-gray-200 dark:bg-gray-800">- <div- className="h-full rounded-sm bg-sky-500 dark:bg-sky-400"- style={{ width: `${rate * 100}%` }}+ {/* Stacked request bars, bottom-up in list order (1px seams would over-fragment thin bars, so segments sit flush). */}+ {series.map((_, i) =>+ segs[i]!.map((seg) => (+ <rect+ key={`${buckets[i]}-${seg.index}`}+ x={geom.x(i) - barW / 2}+ y={seg.y}+ width={barW}+ height={seg.h}+ className={`${entityColor(drawn[seg.index]!, seg.index).text} transition-opacity duration-150`}+ fill="currentColor"+ opacity={barOpacity(seg.index, i)}+ />+ )),+ )}+ {/* One success-rate line per entity on the right-hand scale, in that entity's hue,+ drawn after the bars so a line is never hidden behind a tall segment. Dashed,+ like the Token chart's hit-rate curve: a dash is what tells the reader a stroke+ belongs to the right-hand percentage axis rather than to the bars — and here the+ lines share their entity's bar color, so shape is the only separator left. */}+ {drawn.map((e, si) => (+ <path+ key={`rate-${e.label}:${si}`}+ d={linePath(rateGeom, lines[si]!)}+ fill="none"+ stroke="currentColor"+ strokeWidth={DATA_STROKE_W}+ strokeDasharray="4 3"+ className={`${entityColor(e, si).text} pointer-events-none transition-opacity duration-150`}+ opacity={lineLit(si) ? 1 : 0.15}/>- </div>- </BarRow>- );- })}+ ))}+ </ChartFrame>+ <RequestsLegend+ entities={drawn}+ active={mark?.bucket == null ? (mark?.entity ?? null) : null}+ onHover={(i) => setMark(i === null ? null : { entity: i, bucket: null })}+ />+ </>+ )}</div>);}-// —— Daily Token: three-segment stacked bar ——+// —— Token buckets: three-segment stacked bars + a cache-hit-rate curve in front ——-/** The currently hovered segment: which day (column index), which bucket. */+/** Legend keys of the Token chart: the three Token buckets plus the hit-rate curve. */+export type TokenLegendKey = TokenBucketKey | "hitRate";++/** The hovered Token column, and within it the hovered mark (null = the column's empty space — the bubble still reports the whole bucket). */interface SegHover {i: number;- key: TokenBucketKey;+ key: TokenLegendKey | null;}+/** The hit-rate curve's color classes (amber — distinct from the bars' blue family, CVD-checked against sky in the series palette). */+const HIT_RATE_TEXT = "text-amber-500 dark:text-amber-600";+const HIT_RATE_SWATCH = "bg-amber-500 dark:bg-amber-600";+/**- * Daily Token buckets → a three-segment stacked bar (SVG, reusing- * TrendChart's coordinate system and grid), bottom-to-top output → cacheWrite → cacheRead.+ * Per-bucket Token buckets → a three-segment stacked bar (SVG, reusing the+ * shared coordinate system and grid), bottom-to-top output → cacheWrite →+ * cacheRead, with the cache hit rate drawn as a dashed line **in front of the+ * bars** on its own right-hand 0–100% axis (same x positions — the two geoms+ * share n / w / padR). A bucket with no cache traffic has no hit rate: the+ * line crosses it at NO_RATE_PLOT rather than dipping to a 0% it did not+ * measure, and the bubble prints a dash for it.*- * **Bar width fixed at 25 real pixels, spacing ≥ bar width** (see- * chart-geom's tokenBarLayout): the canvas renders at real pixels per the- * container's measured width (1 canvas unit = 1 pixel, no scaling); when 30- * days' worth of n×2×25px doesn't fit a half-width card, the canvas- * overflows and ChartFrame's container carries horizontal scroll; with few- * points the bars **never stretch** (25px is a fixed value, not a floor) —- * all the extra space goes to bar spacing, and the canvas still fills the card without a scrollbar.+ * The series arrives with its empty buckets already dropped (compactSeries),+ * so the bars run left to right over only the intervals that recorded+ * something; `breaks` is where the axis skipped one. Bars always fit the+ * card: fitBarWidth caps them at 25px and shrinks them with the cell so the+ * chart never scrolls horizontally.*- * **Each segment is an independent, individually hoverable rect**: the hit- * layer swaps ChartFrame's whole-column hit area for a per-segment hit band- * (see chart-geom's barSegments — the hit band fills the whole bar and small- * segments have a height floor, otherwise a sub-pixel output segment would- * be un-hoverable; widening the bar doesn't help the vertical dimension- * either). Hitting a segment highlights only that segment and fades out- * everything else; the bubble reports only that segment's date/bucket- * name/Token count (the cacheRead segment adds that day's cache hit rate,- * cacheRead / (cacheRead + cacheWrite)). When legend is passed in (legend hover), it highlights all segments of the matching bucket.+ * Hovering anywhere in a column shows the whole bucket's bubble — all three+ * Token counts plus the hit rate; hovering a segment's own rect additionally+ * highlights just that segment, and hovering the curve's own band highlights+ * the curve alone (per-segment hit bands, see chart-geom's barSegments — small+ * segments have a height floor, otherwise a sub-pixel output segment would be+ * un-hoverable). When legend is passed in (legend hover), it highlights all+ * segments of the matching bucket — or the curve alone for `hitRate`.* No hover vertical line is drawn (hoverLine={false}): the bar itself already indicates the x position.*/export function TokenBarChart({- trend,+ series,+ granularity,legend,+ breaks,}: {- trend: UsageTrendPoint[];- /** The bucket currently hovered in the legend (highlights matching segments); null = none. */- legend?: TokenBucketKey | null;+ series: UsageSeriesPoint[];+ granularity: UsageGranularity;+ /** The legend item currently hovered (highlights matching segments / the curve); null = none. */+ legend?: TokenLegendKey | null;+ /** Indices after which the series skipped at least one empty bucket (see compactSeries): ChartFrame marks the axis there. */+ breaks?: number[];}) {const [hover, setHover] = useState<SegHover | null>(null);- // Bar width is a pixel constraint, so the container must be measured- // first (unmeasured on the first frame → width=0, at which point nothing is rendered — see the ref container below).const [ref, width] = useChartWidth();- if (trend.length === 0) return <Empty />;+ if (series.length === 0 || series.every((p) => p.total === 0)) return <Empty />;- const sums = trend.map((p) => p.cacheRead + p.cacheWrite + p.output);+ const sums = series.map((p) => p.cacheRead + p.cacheWrite + p.output);const max = Math.max(1, ...sums);- const { barW, chartW, scroll } = tokenBarLayout(width, trend.length);- const geom = makeGeom(trend.length, max, chartW);- const dates = trend.map((p) => p.date);- const segs = trend.map((p) => barSegments(geom, p));+ const geom = makeGeom(series.length, max, width, PAD_R_AXIS);+ const rateGeom = makeRangeGeom(series.length, 0, 100, width, PAD_R_AXIS);+ const barW = fitBarWidth(geom.step);+ const buckets = series.map((p) => p.bucket);+ const segs = series.map((p) => barSegments(geom, p));+ // As in the requests charts: `rates` keeps the nulls for the bubble, `line`+ // gives every bucket a height so the curve stays unbroken.+ const rates = hitRateValues(series);+ const line = plotRates(rates);- // Highlight = fade out the rest: segment-level hover leaves only "that day's that bucket", legend hover leaves all segments of the matching bucket.+ // Highlight = fade out the rest: segment-level hover leaves only "that bucket's that segment" (column-level hover highlights nothing), legend hover leaves all segments of the matching bucket (or the curve alone).const dimmed = (i: number, key: TokenBucketKey) =>- (hover !== null && !(hover.i === i && hover.key === key)) || (legend != null && legend !== key);+ (hover?.key != null && !(hover.i === i && hover.key === key)) ||+ (legend != null && legend !== key);+ const curveDim =+ (legend != null && legend !== "hitRate") || (hover?.key != null && hover.key !== "hitRate");++ /** One bubble row: swatch + label + value, shared by the three Token buckets and the hit-rate line. */+ const bubbleRow = (swatch: React.ReactNode, label: string, value: string, strong: boolean) => (+ <p+ key={label}+ className={`flex items-center gap-1.5 font-mono ${strong ? "font-semibold" : ""}`}+ >+ {swatch}+ {label}+ <span className="ml-auto pl-2 tabular-nums">{value}</span>+ </p>+ );return (<div ref={ref}>@@ -289,67 +471,93 @@ export function TokenBarChart({<ChartFramegeom={geom}fmtY={(v) => humanizeTokens(Math.round(v))}- dates={dates}+ dates={buckets}+ fmtX={(b) => bucketAxisLabel(granularity, b)}hover={hover?.i ?? null}- // Each cell ≥ 50px: dates can be labeled every day (autoLabelIdx sets the density by cell width, so they never blur together).- labels={autoLabelIdx(trend.length, geom.step)}+ labels={autoLabelIdx(series.length, geom.step)}// The bar itself indicates x position: no hover vertical line spanning the whole chart.hoverLine={false}- // 30 days doesn't fit a half-width card (bar width fixed at 25px): defaults to sitting on the most recent day, scrolling left for earlier ones.- scrollToEnd={scroll}- // Per-segment hits go through hitLayer below; ChartFrame only calls back when the mouse leaves the whole chart (i=null).+ rightAxis={{ y: rateGeom.y, ticks: [0, 50, 100], fmt: (v) => `${v}%` }}+ axisBreaks={breaks}+ // Hits go through hitLayer below; ChartFrame only calls back when the mouse leaves the whole chart (i=null).onHover={(i) => {if (i === null) setHover(null);}}bubble={(i) => {- const p = trend[i]!;- const key = hover?.key;- if (!key) return null;- // The cacheRead bubble additionally reports that day's cache hit- // rate, via the formula/format/label shared with the Trace page- // (lib/format.ts cacheHitRate + formatPercent, S.traces.hitRate),- // so the metric reads identically everywhere; null (denominator 0) omits the line instead of showing 0/0.- const hitRate = key === "cacheRead" ? cacheHitRate(p.cacheRead, p.cacheWrite) : null;+ const p = series[i]!;+ const key = hover?.key ?? null;+ const sq = (color: string) => (+ <span+ className="inline-block h-2 w-2 shrink-0 rounded-[2px]"+ style={{ backgroundColor: color }}+ />+ );return (<>- <p className="text-gray-400">{p.date}</p>- <p className="font-mono">- {bucketLabel(key)} {humanizeTokens(p[key])}- </p>- {hitRate !== null && (- <p className="font-mono">- {S.traces.hitRate} {formatPercent(hitRate)}- </p>+ <p className="text-gray-400">{bucketFullLabel(granularity, p.bucket)}</p>+ {(["cacheRead", "cacheWrite", "output"] as const).map((k) =>+ bubbleRow(sq(TOKEN_COLORS[k]), bucketLabel(k), humanizeTokens(p[k]), key === k),+ )}+ {bubbleRow(+ <span+ className={`inline-block h-0.5 w-2 shrink-0 rounded-sm ${HIT_RATE_SWATCH}`}+ />,+ S.usage.legendHitRate,+ rateCell(rates[i]),+ key === "hitRate",)}</>);}}- hitLayer={trend.map((p, i) =>- segs[i]!.map((s) => (- // The hit band is as wide as the bar horizontally (empty space- // outside the bar doesn't trigger highlighting), and split by- // segment vertically with no overlap (small segments raised- // to the minimum hit height, see hitHeights). Highlighting- // clears as soon as the pointer leaves the bar — otherwise the- // previous segment's highlight would linger when moving from the bar into the empty space.+ hitLayer={[+ // Column-level hits first (underneath): anywhere in the column — the empty+ // space and the curve included — reports the whole bucket's bubble.+ ...series.map((p, i) => (<rect- key={`hit-${p.date}-${s.key}`}- x={geom.x(i) - barW / 2}- y={s.hitY}- width={barW}- height={s.hitH}+ key={`col-${p.bucket}`}+ x={geom.x(i) - geom.step / 2}+ y={0}+ width={geom.step}+ height={geom.y(0)}fill="transparent"- className="cursor-pointer"- onMouseEnter={() => setHover({ i, key: s.key })}- onMouseLeave={() => setHover(null)}+ className="cursor-crosshair"+ onMouseEnter={() => setHover({ i, key: null })}/>)),- )}+ // Per-segment hits on top: the hit band is as wide as the bar horizontally,+ // split by segment vertically with no overlap (small segments raised to the+ // minimum hit height, see hitHeights). Leaving a segment falls back to the+ // column hit underneath, so the bubble never flickers off inside the chart.+ ...series.map((p, i) =>+ segs[i]!.map((s) => (+ <rect+ key={`hit-${p.bucket}-${s.key}`}+ x={geom.x(i) - barW / 2}+ y={s.hitY}+ width={barW}+ height={s.hitH}+ fill="transparent"+ className="cursor-pointer"+ onMouseEnter={() => setHover({ i, key: s.key })}+ onMouseLeave={() =>+ setHover((h) => (h?.i === i && h.key === s.key ? { i, key: null } : h))+ }+ />+ )),+ ),+ // The hit-rate curve last, so it answers the pointer where it crosses a bar.+ <LineHits+ key="hit-rate-line"+ geom={rateGeom}+ values={line}+ onEnter={(i) => setHover({ i, key: "hitRate" })}+ />,+ ]}>- {trend.map((p, i) =>+ {series.map((p, i) =>segs[i]!.map((s) => (<rect- key={`${p.date}-${s.key}`}+ key={`${p.bucket}-${s.key}`}x={geom.x(i) - barW / 2}y={s.y}width={barW}@@ -360,25 +568,48 @@ export function TokenBarChart({/>)),)}+ {/* Cache-hit-rate curve, dashed, in front of the bars on the right-hand 0–100% scale.+ pointer-events-none: the column/segment hit rects stay hoverable through it. */}+ <g+ className={`${HIT_RATE_TEXT} pointer-events-none transition-opacity duration-150`}+ opacity={curveDim ? 0.3 : 1}+ >+ <path+ d={linePath(rateGeom, line)}+ fill="none"+ stroke="currentColor"+ strokeWidth={DATA_STROKE_W}+ strokeDasharray="5 4"+ />+ {hover !== null && (+ <circle+ cx={rateGeom.x(hover.i)}+ cy={rateGeom.y(line[hover.i] ?? 0)}+ r={2.5}+ className="fill-current"+ />+ )}+ </g></ChartFrame>)}</div>);}-/** Token bar chart legend (cacheRead / cacheWrite / output): hovering an item highlights matching segments (fading out the rest). */+/** Token chart legend (cacheRead / cacheWrite / output + the hit-rate curve): hovering an item highlights the matching marks (fading out the rest). */export function TokenLegend({active,onHover,}: {- active?: TokenBucketKey | null;- onHover?: (key: TokenBucketKey | null) => void;+ active?: TokenLegendKey | null;+ onHover?: (key: TokenLegendKey | null) => void;}) {const items: Array<[TokenBucketKey, string]> = [["cacheRead", S.usage.colCacheRead],["cacheWrite", S.usage.colCacheWrite],["output", S.usage.colOutput],];+ const dim = (key: TokenLegendKey) => (active != null && active !== key ? "opacity-30" : "");return (<div className="flex flex-wrap gap-x-3 gap-y-1">{items.map(([key, label]) => (@@ -387,9 +618,7 @@ export function TokenLegend({type="button"onMouseEnter={() => onHover?.(key)}onMouseLeave={() => onHover?.(null)}- className={`flex items-center gap-1 text-[10px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${- active != null && active !== key ? "opacity-30" : ""- }`}+ className={`flex items-center gap-1 text-[10px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${dim(key)}`}><spanclassName="inline-block h-2 w-3 rounded-sm"@@ -398,6 +627,16 @@ export function TokenLegend({{label}</button>))}+ {/* The curve's legend item wears a line-shaped swatch: it is a line on its own axis, not a fourth stack segment. */}+ <button+ type="button"+ onMouseEnter={() => onHover?.("hitRate")}+ onMouseLeave={() => onHover?.(null)}+ className={`flex items-center gap-1 text-[10px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${dim("hitRate")}`}+ >+ <span className={`inline-block h-0.5 w-3 rounded-sm ${HIT_RATE_SWATCH}`} />+ {S.usage.legendHitRate}+ </button></div>);}diff --git a/packages/web/src/features/usage/usage-controls.ts b/packages/web/src/features/usage/usage-controls.tsnew file mode 100644index 00000000..b5cf56bb--- /dev/null+++ b/packages/web/src/features/usage/usage-controls.ts@@ -0,0 +1,268 @@+/**+ * Pure helpers behind the cost center's global controls (date-range presets ++ * time-series precision) and the series shaping the charts draw — the+ * per-entity counts the requests charts stack, the rate values their lines+ * follow, and the empty-bucket compaction the cost and Token charts apply.+ * No React, unit-tested in test/usage-controls.test.ts.+ *+ * The range picks the precision; there is no separate control for it. The+ * trailing "last hour" window is the only thing that reaches minute buckets (a+ * calendar range cannot — a single day by minute is already 1440 points),+ * "last 24 hours" serves hours, and every calendar range is drawn per day,+ * week or month by its length.+ */+import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";+import { cacheHitRate } from "../../lib/format";+import { SERIES_COLORS } from "../../lib/category-colors";++/** Quick range choices; `1h`/`1d` are trailing timestamp windows, the rest calendar ranges (`custom` reveals the two date inputs). */+export type RangePreset = "1h" | "1d" | "7d" | "30d" | "90d" | "custom";++/** Calendar-preset day counts (today inclusive). */+const PRESET_DAYS: Record<"7d" | "30d" | "90d", number> = {+ "7d": 7,+ "30d": 30,+ "90d": 90,+};++/** Format a Date as a local `yyyy-mm-dd`. */+export function isoDate(d: Date): string {+ const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+}++/** The from/to range a calendar preset stands for (today inclusive). */+export function presetRange(+ preset: "7d" | "30d" | "90d",+ today: Date,+): { from: string; to: string } {+ const from = new Date(today);+ from.setDate(from.getDate() - (PRESET_DAYS[preset] - 1));+ return { from: isoDate(from), to: isoDate(today) };+}++/**+ * The trailing timestamp window a `1h`/`1d` preset stands for, computed at+ * load time so a reload keeps trailing "now": the instant bounds plus the+ * local dates they span (the date pair keeps the server's date-column filter+ * effective; the instants refine it).+ */+export function presetTsWindow(+ preset: "1h" | "1d",+ now: Date,+): { fromTs: string; toTs: string; from: string; to: string } {+ const fromDate = new Date(now.getTime() - (preset === "1h" ? 3_600_000 : 86_400_000));+ return {+ fromTs: fromDate.toISOString(),+ toTs: now.toISOString(),+ from: isoDate(fromDate),+ to: isoDate(now),+ };+}++/** Inclusive day count of a `yyyy-mm-dd` range (UTC arithmetic — plain calendar distance, no DST wobble); invalid or reversed ranges count as 1. */+export function rangeDays(from: string, to: string): number {+ const ms = Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`);+ if (!Number.isFinite(ms) || ms < 0) return 1;+ return Math.round(ms / 86_400_000) + 1;+}++/** The precision a custom range is drawn at: daily up to a quarter, weekly up to half a year, monthly beyond. */+export function defaultGranularity(days: number): UsageGranularity {+ if (days <= 92) return "day";+ if (days <= 190) return "week";+ return "month";+}++/**+ * The precision a range is drawn at. There is no precision control — the range+ * picks it, because only one precision reads well per range and every other+ * choice either fuses into a wall of hairlines or hides the shape.+ *+ * Each result must also be a combination the server accepts: it caps a+ * response at 500 buckets, so the trailing hour goes to minute (61 buckets)+ * and the trailing day to hour (25), while every calendar preset stays on day+ * (90 at the widest). `minute` and window-bounded `hour` additionally require+ * the `fromTs`/`toTs` pair, which is exactly what the two trailing presets send.+ */+export function presetDefaultGranularity(preset: RangePreset, days: number): UsageGranularity {+ if (preset === "1h") return "minute";+ if (preset === "1d") return "hour";+ if (preset === "custom") return defaultGranularity(days);+ return "day";+}++/** Short x-axis form of a bucket key: minute/hour `hh:mm`, day/week `mm-dd`, month `yyyy-mm`. */+export function bucketAxisLabel(g: UsageGranularity, key: string): string {+ if (g === "minute" || g === "hour") return key.slice(11);+ if (g === "month") return key;+ return key.slice(5);+}++/** Full bubble form of a bucket key: the key itself, with a minute/hour key's `T` opened up to a space. */+export function bucketFullLabel(g: UsageGranularity, key: string): string {+ return g === "minute" || g === "hour" ? key.replace("T", " ") : key;+}++/** One entity's per-bucket request and success counts, index-aligned with the chart's buckets. */+export interface EntityCounts {+ label: string;+ requests: number[];+ completed: number[];+ denominator: number[];+}++/** A drawable series of a requests chart: one entity's counts, or the folded tail. */+export interface EntitySeries extends EntityCounts {+ /** The folded tail (drawn in neutral gray, after the named ones). */+ other?: boolean;+}++/**+ * How many entities keep a hue of their own. The palette holds exactly this+ * many distinct, CVD-checked line colors, and past it the stack and the lines+ * would repeat a color — so this is the cap, not a taste setting.+ */+export const MAX_NAMED_SERIES = SERIES_COLORS.length;++/**+ * Shape entity series for stacking: the top `max` entities keep their own+ * color, the rest fold into one neutral tail whose label is built from the+ * number folded — the chart says how many entities it stopped naming instead+ * of quietly presenting the head as the whole picture. Input is already+ * sorted by total requests descending (the server's contract).+ */+export function foldEntitySeries(+ entities: readonly EntityCounts[],+ otherLabel: (folded: number) => string,+ max = MAX_NAMED_SERIES,+): EntitySeries[] {+ const named: EntitySeries[] = entities.slice(0, max).map((s) => ({ ...s }));+ const rest = entities.slice(max);+ if (rest.length === 0) return named;+ // A tail of one is not "other": name it (the color is still the neutral one — a label beats a mystery bucket).+ if (rest.length === 1) return [...named, { ...rest[0]!, other: true }];+ return [...named, { ...sumCounts(rest), label: otherLabel(rest.length), other: true }];+}++/** Column sums over a set of series: the stack's height per bucket, and the counts its combined rate comes from. */+export function sumCounts(series: readonly EntityCounts[]): Omit<EntityCounts, "label"> {+ const buckets = series[0]?.requests.length ?? 0;+ const column = (pick: (e: EntityCounts) => number[]) =>+ Array.from({ length: buckets }, (_, i) => series.reduce((s, e) => s + (pick(e)[i] ?? 0), 0));+ return {+ requests: column((e) => e.requests),+ completed: column((e) => e.completed),+ denominator: column((e) => e.denominator),+ };+}++/**+ * Per-bucket success rate in percent, or **null where there is nothing to+ * rate** (denominator 0 — the entity was idle, or every request it made was+ * aborted). Null is not a number the reader may be shown: the hover table+ * prints a dash for it, and plotRates below turns it into a drawing height so+ * the line still crosses the interval.+ */+export function rateSeries(+ counts: Pick<EntityCounts, "completed" | "denominator">,+): (number | null)[] {+ return counts.denominator.map((d, i) => (d > 0 ? ((counts.completed[i] ?? 0) / d) * 100 : null));+}++/** Per-bucket cache hit rate in percent, null where the bucket had no cache traffic at all — the same "no rate here" as a success rate with an empty denominator. */+export function hitRateValues(series: readonly UsageSeriesPoint[]): (number | null)[] {+ return series.map((p) => {+ const rate = cacheHitRate(p.cacheRead, p.cacheWrite);+ return rate === null ? null : rate * 100;+ });+}++/**+ * The height a rate line is drawn at across a bucket that has no rate. The+ * stroke has to cross the interval at *some* height — a hole reads as a claim+ * of its own, and so does dropping to the floor, which is where "made+ * requests and failed every one" lives. The top of the axis is the one height+ * that invents no failure.+ *+ * It is a drawing choice and nothing more: the hover table prints a dash for+ * the same bucket, so the number the reader takes away is never this 100.+ */+export const NO_RATE_PLOT = 100;++/** Drawing values for a rate line: every bucket gets a height, the ones with no rate at NO_RATE_PLOT. */+export function plotRates(values: readonly (number | null)[]): number[] {+ return values.map((v) => v ?? NO_RATE_PLOT);+}++/** A time series with its empty buckets dropped: the buckets that survived, where they sat, and where the axis now jumps. */+export interface CompactSeries {+ /** The buckets that recorded something, in order. */+ points: UsageSeriesPoint[];+ /**+ * Where each surviving bucket sat in the original series. The per-entity+ * counts arrive aligned index-for-index with that array, so they have to be+ * re-indexed through this to stay aligned with `points` — see compactCounts.+ */+ kept: number[];+ /** Indices in `points` after which at least one bucket was dropped — where the axis jumps in time. */+ breaks: number[];+}++/**+ * Drop the buckets that recorded nothing. The survivors are handed to+ * makeGeom as the entire series, so the coordinate system spreads them evenly+ * over the plot area on its own: one point sits in the middle of the card,+ * two at a quarter and three quarters, and the divisions subdivide as points+ * are added. Left to right, only what happened — the shape the charts had+ * before the range control existed.+ *+ * Emptiness is a property of the **bucket**, never of one entity in it: an+ * interval where anything at all ran stays, and the entities that did not run+ * in it show their zeros and dashes there. That is what lets every chart on+ * the page compact through this one call and keep one shared axis.+ *+ * `breaks` is what the axis is drawn with, since an axis that skips intervals+ * must not read as a continuous one.+ */+export function compactSeries(series: readonly UsageSeriesPoint[]): CompactSeries {+ const points: UsageSeriesPoint[] = [];+ const kept: number[] = [];+ const breaks: number[] = [];+ let dropping = false;+ series.forEach((p, i) => {+ // Nothing was recorded in this bucket: no request, and no tokens either+ // (a request that spent nothing is still a request, and keeps its bucket).+ if (p.requests === 0 && p.total === 0) {+ dropping = true;+ return;+ }+ // A break belongs *between* two drawn points; buckets dropped before the+ // first one (or after the last) shorten the axis without breaking it.+ if (dropping && points.length > 0) breaks.push(points.length - 1);+ dropping = false;+ kept.push(i);+ points.push(p);+ });+ return { points, kept, breaks };+}++/**+ * Re-index one entity's per-bucket counts onto the compacted bucket list.+ * The server aligns these arrays index-for-index with `series`; dropping+ * buckets from the series without dropping the same positions here would+ * shift every entity's history sideways and silently attribute its counts to+ * the wrong intervals. One `kept` list for the series and for every entity is+ * what makes that impossible.+ */+export function compactCounts(+ counts: Omit<EntityCounts, "label">,+ kept: readonly number[],+): Omit<EntityCounts, "label"> {+ const pick = (values: readonly number[]) => kept.map((i) => values[i] ?? 0);+ return {+ requests: pick(counts.requests),+ completed: pick(counts.completed),+ denominator: pick(counts.denominator),+ };+}diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsxindex b1806291..60451118 100644--- a/packages/web/src/features/usage/usage-page.tsx+++ b/packages/web/src/features/usage/usage-page.tsx@@ -1,16 +1,29 @@/*** Cost and usage center:- * top filters for Agent / Model + a date range (controls have no external- * title, the explanation is written into the dropdown options themselves);+ * top filters for Agent / Model + a date-range preset (trailing last hour /+ * last 24 hours, calendar 7/30/90 days, or a custom pair of date inputs);+ * the range alone decides the time-series precision, so there is no second+ * control for it (controls have no external title — the explanation is+ * written into the dropdown options themselves);* three summary cards (today / last 7 days / cumulative, each stat on its own row);- * four business charts arranged two-by-two, each taking half the width — a- * row of compositional charts (each Agent's call count pie chart, each- * Model's success rate progress bar), and a row of time series (daily Token- * three-segment stacked bar, daily cost line + area): Token bar width is- * fixed at 25px, and it scrolls horizontally within the card when 30 days- * doesn't fit the half-width; below that is a full-width "errors" panel- * (stats + a recent-errors table).- * Currency follows the user's settings; a row with unconfigured pricing shows its cost as "—".+ * a 2x2 grid of time-series charts over the shared range and precision —+ * requests + success rate broken down by Agent and, beside it, the same by+ * Model (requests stacked on the left axis, one rate line per entity on a+ * right 0–100% axis), then Token buckets (stacked bars + a dashed+ * cache-hit-rate curve in front) and cost (line + points + area). Charts+ * always fit their card — nothing scrolls; below them is a full-width+ * "errors" panel (stats + a paged errors table). Currency follows the user's+ * settings.+ *+ * Every chart draws the same buckets: compactSeries runs **once**, here, and+ * all four are fed its result, so the grid keeps one shared x axis. It drops+ * only the buckets where nothing at all was recorded — emptiness is a+ * property of the interval, not of one entity in it, so a bucket any entity+ * ran in stays and the idle entities show their zeros and dashes there. The+ * per-entity counts arrive index-aligned with `series`, so they are+ * re-indexed through the same `kept` list (compactCounts); one list for all+ * of them is what keeps an entity's history from sliding onto the wrong+ * intervals. Each chart marks the skipped intervals on its own axis.*/import { useCallback, useEffect, useMemo, useState } from "react";import { useSearchParams } from "react-router";@@ -27,15 +40,19 @@ import { Input } from "../../components/ui/input";import { Select } from "../../components/ui/select";import { Skeleton } from "../../components/ui/skeleton";import { TrendChart } from "./trend-chart";-import type { TokenBucketKey } from "./chart-geom";-import { AgentPieChart, SuccessBarChart, TokenBarChart, TokenLegend } from "./usage-charts";+import { RequestsChart, TokenBarChart, TokenLegend, type TokenLegendKey } from "./usage-charts";+import {+ compactCounts,+ compactSeries,+ presetDefaultGranularity,+ presetRange,+ presetTsWindow,+ rangeDays,+ type EntityCounts,+ type RangePreset,+} from "./usage-controls";import { ErrorsPanel } from "./errors-panel";-function isoDate(d: Date): string {- const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;-}-/** A summary card's stat row: name on the left, value on the right — each item on its own row, so a narrow card no longer crams them into one wrapping line. */function SummaryRow({label,@@ -133,27 +150,39 @@ export function UsagePage() {useEffect(() => {setAgentFilter(paramAgentId ?? "");}, [paramAgentId]);- const [from, setFrom] = useState(() => {- const d = new Date();- d.setDate(d.getDate() - 29);- return isoDate(d);- });- const [to, setTo] = useState(() => isoDate(new Date()));+ // Date range: a trailing window (last hour / last 24 hours), a calendar+ // preset (7/30/90 days), or a custom from/to pair — plus the time-series+ // precision. A range change keeps the precision when the new preset still+ // offers it, otherwise snaps to the preset's default.+ const [preset, setPreset] = useState<RangePreset>("7d");+ const [from, setFrom] = useState(() => presetRange("7d", new Date()).from);+ const [to, setTo] = useState(() => presetRange("7d", new Date()).to);+ const applyRange = (nextPreset: RangePreset, nextFrom: string, nextTo: string) => {+ setPreset(nextPreset);+ setFrom(nextFrom);+ setTo(nextTo);+ };const [data, setData] = useState<UsageResponse | null>(null);const [error, setError] = useState<string | null>(null);- // The bucket currently hovered in the legend: the legend lives in the card- // header (ChartCard's extra) while the bars live inside the card, so this state is lifted to this level.- const [tokenBucket, setTokenBucket] = useState<TokenBucketKey | null>(null);+ // The legend / control state that lives in the card headers (ChartCard's+ // extra) while the marks live inside the cards, lifted to this level.+ const [tokenBucket, setTokenBucket] = useState<TokenLegendKey | null>(null);const load = useCallback(async () => {if (!projectId) return;setError(null);try {+ // The trailing presets recompute their window at load time, so a reload+ // keeps trailing "now"; the calendar presets use the stored date pair.+ const range =+ preset === "1h" || preset === "1d" ? presetTsWindow(preset, new Date()) : { from, to };const res = await api.getUsage(projectId, {- from,- to,+ ...range,// The detail table has been removed, superseded by the charts above; groupBy is still a required query parameter, fixed to group by date.groupBy: "date",+ // The range picks the precision — there is no separate control, and this+ // is the only place the choice is made (see presetDefaultGranularity).+ granularity: presetDefaultGranularity(preset, rangeDays(from, to)),...(agentFilter ? { agentId: agentFilter } : {}),...(modelFilter ? { provider: modelFilter.provider, modelId: modelFilter.modelId } : {}),});@@ -161,7 +190,7 @@ export function UsagePage() {} catch (e) {setError(apiErrorText(e));}- }, [projectId, from, to, agentFilter, modelFilter?.provider, modelFilter?.modelId]);+ }, [projectId, preset, from, to, agentFilter, modelFilter?.provider, modelFilter?.modelId]);useEffect(() => {setData(null);@@ -194,6 +223,22 @@ export function UsagePage() {(summary?.last7d.hasUncosted ?? false) ||(summary?.total.hasUncosted ?? false);+ // One compaction for the whole page (see the file header): every chart draws+ // these buckets, and every per-entity series is re-indexed through the same+ // kept list, so nothing can drift out of alignment with the axis.+ const plotted = compactSeries(data?.series ?? []);+ // The two requests charts each get one dimension's entity list, already+ // sorted by total requests descending and arriving index-aligned with the+ // full `series` (the server's contract) — compactCounts moves it onto the+ // drawn buckets; the charts fold their own tails.+ const agentEntities: EntityCounts[] = (data?.byAgentSeries ?? []).map((s) => ({+ label: s.agentId,+ ...compactCounts(s, plotted.kept),+ }));+ const modelEntities: EntityCounts[] = (data?.byModelSeries ?? []).map((s) => ({+ label: catalogEntryFor(s.provider, s.modelId)?.displayName ?? s.modelId,+ ...compactCounts(s, plotted.kept),+ }));return (<div className="h-full overflow-y-auto p-4 md:p-6"><div className="mx-auto max-w-5xl space-y-4">@@ -236,26 +281,53 @@ export function UsagePage() {))}</Select></div>- {/* Date range: a dash between the two inputs stands in for a "from/to" label */}- <div className="flex items-center gap-1.5">- <Input- size="sm"- type="date"- aria-label={S.usage.from}- value={from}- onChange={(e) => setFrom(e.target.value)}- />- <span className="shrink-0 text-gray-400" aria-hidden>- –- </span>- <Input+ {/* Date range: trailing windows and quick presets, with "custom" revealing the two date inputs */}+ <div className="w-28">+ <Selectsize="sm"- type="date"- aria-label={S.usage.to}- value={to}- onChange={(e) => setTo(e.target.value)}- />+ value={preset}+ aria-label={S.usage.rangeLabel}+ onChange={(e) => {+ const next = e.target.value as RangePreset;+ if (next === "7d" || next === "30d" || next === "90d") {+ const r = presetRange(next, new Date());+ applyRange(next, r.from, r.to);+ } else {+ // Trailing windows compute their bounds at load time; custom keeps the dates already picked.+ applyRange(next, from, to);+ }+ }}+ >+ <option value="1h">{S.usage.rangeHour}</option>+ <option value="1d">{S.usage.rangeDay}</option>+ <option value="7d">{S.usage.range7d}</option>+ <option value="30d">{S.usage.range30d}</option>+ <option value="90d">{S.usage.range90d}</option>+ <option value="custom">{S.usage.rangeCustom}</option>+ </Select></div>+ {preset === "custom" && (+ /* A dash between the two inputs stands in for a "from/to" label */+ <div className="flex items-center gap-1.5">+ <Input+ size="sm"+ type="date"+ aria-label={S.usage.from}+ value={from}+ onChange={(e) => applyRange("custom", e.target.value, to)}+ />+ <span className="shrink-0 text-gray-400" aria-hidden>+ –+ </span>+ <Input+ size="sm"+ type="date"+ aria-label={S.usage.to}+ value={to}+ onChange={(e) => applyRange("custom", from, e.target.value)}+ />+ </div>+ )}</div></div>@@ -274,26 +346,46 @@ export function UsagePage() {</div>)}- {/* Four business charts two-by-two, each taking half width: a row of- compositional charts (pie chart / success rate), a row of time- series (daily Token / daily cost). Token bar width fixed at 25px, scrolls horizontally within the card when 30 days doesn't fit the half-width */}+ {/* Time-series charts, all over the shared range + precision: requests ++ success rate by Agent and by Model on the first row, Token buckets ++ cache hit rate and cost on the second. Charts always fit their card — nothing scrolls. */}{data ? (<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">- <ChartCard title={S.usage.chartAgentCalls}>- <AgentPieChart data={data.byAgent} />+ <ChartCard title={S.usage.chartRequestsByAgent}>+ <RequestsChart+ series={plotted.points}+ entities={agentEntities}+ granularity={data.granularity}+ breaks={plotted.breaks}+ /></ChartCard>- <ChartCard title={S.usage.chartSuccessRate}>- <SuccessBarChart data={data.success} />+ <ChartCard title={S.usage.chartRequestsByModel}>+ <RequestsChart+ series={plotted.points}+ entities={modelEntities}+ granularity={data.granularity}+ breaks={plotted.breaks}+ /></ChartCard>- {/* The legend lives in the card header, the bars live inside the card: the hover-linked bucket state is lifted to this level to be shared */}+ {/* The Token legend lives in its card header while its marks live inside the card, so that state is lifted to this level */}<ChartCardtitle={S.usage.chartTokenTrend}extra={<TokenLegend active={tokenBucket} onHover={setTokenBucket} />}>- <TokenBarChart trend={data.trend} legend={tokenBucket} />+ <TokenBarChart+ series={plotted.points}+ granularity={data.granularity}+ legend={tokenBucket}+ breaks={plotted.breaks}+ /></ChartCard><ChartCard title={S.usage.chartCostTrend}>- <TrendChart points={data.trend} currency={currency} />+ <TrendChart+ series={plotted.points}+ granularity={data.granularity}+ currency={currency}+ breaks={plotted.breaks}+ /></ChartCard></div>) : (diff --git a/packages/web/src/lib/category-colors.ts b/packages/web/src/lib/category-colors.tsindex e9c79610..48ccc5f4 100644--- a/packages/web/src/lib/category-colors.ts+++ b/packages/web/src/lib/category-colors.ts@@ -1,37 +1,15 @@/**- * Category colors (for category-colored charts, e.g. the cost center's- * "calls per Agent" pie chart): reuses the fixed five-color sequence from the- * trace timeline bars — violet / sky / amber / rose / emerald (light shade- * 500, dark shade 400 with reduced saturation) — extending to cyan / fuchsia- * for more categories, then cycling.+ * Fixed color sequences for charts where color carries identity rather than+ * severity — one hue per series, never a judgement about it. Semantic status+ * colors live in lib/tone.ts and must not be borrowed here (and vice versa):+ * a categorical palette has to stay free to grow a hue without that reading as+ * a new state.** Uses Tailwind class names instead of hex: dark mode needs a different shade- * step, and only classes can track the html.dark toggle.- * (TOKEN_COLORS is the same blue hue family shared across light/dark shades,- * so it uses hex — the two serve different purposes and aren't interchangeable.)+ * step, and only classes can track the html.dark toggle. (TOKEN_COLORS is one+ * blue hue family shared across light/dark shades, so it uses hex — the two+ * serve different purposes and aren't interchangeable.)*/-export interface CategoryColor {- /** SVG fill (pie chart slice). */- fill: string;- /** Legend swatch background. */- swatch: string;-}--export const CATEGORY_COLORS: readonly CategoryColor[] = [- { fill: "fill-violet-500 dark:fill-violet-400", swatch: "bg-violet-500 dark:bg-violet-400" },- { fill: "fill-sky-500 dark:fill-sky-400", swatch: "bg-sky-500 dark:bg-sky-400" },- { fill: "fill-amber-500 dark:fill-amber-400", swatch: "bg-amber-500 dark:bg-amber-400" },- { fill: "fill-rose-500 dark:fill-rose-400", swatch: "bg-rose-500 dark:bg-rose-400" },- { fill: "fill-emerald-500 dark:fill-emerald-400", swatch: "bg-emerald-500 dark:bg-emerald-400" },- { fill: "fill-cyan-500 dark:fill-cyan-400", swatch: "bg-cyan-500 dark:bg-cyan-400" },- { fill: "fill-fuchsia-500 dark:fill-fuchsia-400", swatch: "bg-fuchsia-500 dark:bg-fuchsia-400" },-];--/** Color for the i-th category (cycles once past the palette length). */-export function categoryColor(i: number): CategoryColor {- return CATEGORY_COLORS[i % CATEGORY_COLORS.length]!;-}-/** Line series color: text drives stroke/fill="currentColor" for the whole series, swatch is for the legend. */export interface SeriesColor {text: string;@@ -39,14 +17,15 @@ export interface SeriesColor {}/**- * Fixed color sequence for line series (the eval center splits series by model ID and thinking- * level): maintained separately from CATEGORY_COLORS — adjacent line colors- * must pass color-vision-deficiency (CVD) separation checks and dark shades- * must land within the brightness band. The violet / amber / sky / rose+ * Fixed color sequence for chart series — the eval center's model x thinking-level+ * curves, the cost center's per-entity request stacks and rate lines. Adjacent+ * colors must pass color-vision-deficiency (CVD) separation checks and dark+ * shades must land within the brightness band. The violet / amber / sky / rose* ordering passes the dataviz validator in both modes (dark-mode amber / sky* dropped to the 600 step); sky vs. amber falls below 3:1 contrast on white,- * backstopped by legend text and detail tables (identity never relies on- * color alone).+ * backstopped by legend text and hover detail (identity never relies on color+ * alone). Its length is also the cap on how many entities a chart names before+ * folding the rest.*/export const SERIES_COLORS: readonly SeriesColor[] = [{ text: "text-violet-500", swatch: "bg-violet-500" },@@ -59,3 +38,13 @@ export const SERIES_COLORS: readonly SeriesColor[] = [export function seriesColor(i: number): SeriesColor {return SERIES_COLORS[i % SERIES_COLORS.length]!;}++/**+ * The neutral a series wears when it stands for "the rest" rather than one+ * identity — the cost center's folded tail, the eval center's untagged runs.+ * Deliberately outside the sequence: it must not read as a fifth category.+ */+export const NEUTRAL_SERIES: SeriesColor = {+ text: "text-gray-400 dark:text-gray-500",+ swatch: "bg-gray-400 dark:bg-gray-500",+};diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 63da1ce9..fcdea3d2 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1605,12 +1605,22 @@ Scenarios:uncostedNote: "* Only models with configured pricing count toward cost",filterAllAgents: "All agents",filterAllModels: "All models",- chartAgentCalls: "Calls per agent",- chartSuccessRate: "Model success rate",- chartTokenTrend: "Daily token trend",- chartCostTrend: "Daily cost trend",+ rangeLabel: "Date range",+ rangeHour: "Last hour",+ rangeDay: "Last 24 hours",+ range7d: "Last 7 days",+ range30d: "Last 30 days",+ range90d: "Last 90 days",+ rangeCustom: "Custom",+ chartRequestsByAgent: "Requests & success rate by agent",+ chartRequestsByModel: "Requests & success rate by model",+ legendSuccessRate: "Success rate",+ chartTokenTrend: "Token trend",+ chartCostTrend: "Cost trend",+ legendOther: (n: number): string => `Other (${n})`,+ bucketTotal: "Total",+ legendHitRate: "Cache hit rate",empty: "No usage records",- successAborted: "Aborted (excluded)",errors: "Errors",errorsTotal: "Total",errorsUnexpected: "Unexpected",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 9c4eb603..962bf77d 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1557,12 +1557,22 @@ Benchmark:uncostedNote: "* 只计入配置了价格的模型成本",filterAllAgents: "全部 Agent",filterAllModels: "全部模型",- chartAgentCalls: "各 Agent 调用次数",- chartSuccessRate: "各模型成功率",- chartTokenTrend: "Token 逐日变化",- chartCostTrend: "成本逐日变化",+ rangeLabel: "日期范围",+ rangeHour: "最近一小时",+ rangeDay: "最近一天",+ range7d: "近 7 天",+ range30d: "近 30 天",+ range90d: "近 90 天",+ rangeCustom: "自定义",+ chartRequestsByAgent: "各 Agent 请求与成功率",+ chartRequestsByModel: "各模型请求与成功率",+ legendSuccessRate: "成功率",+ chartTokenTrend: "Token 变化",+ chartCostTrend: "成本变化",+ legendOther: (n: number): string => `其他 ${n} 项`,+ bucketTotal: "合计",+ legendHitRate: "缓存命中率",empty: "暂无用量记录",- successAborted: "已中断(不计入)",errors: "异常",errorsTotal: "总数",errorsUnexpected: "未预期",diff --git a/packages/web/test/benchmark-metrics.test.ts b/packages/web/test/benchmark-metrics.test.tsindex e53dfb2c..4a4d7630 100644--- a/packages/web/test/benchmark-metrics.test.ts+++ b/packages/web/test/benchmark-metrics.test.ts@@ -1,10 +1,10 @@/*** Unit tests for the Evaluation center's Score-only chart helpers: Score extraction,- * dynamic y-axis range, gap segmentation across runtime series, and runtime grouping.+ * dynamic y-axis range, and runtime grouping. The gap segmentation these series are drawn+ * with is shared chart geometry (chart-geom's lineSegments, covered in usage-charts.test.ts).*/import { describe, expect, it } from "vitest";import {- lineSegments,modelSeries,scoreScale,scoreValues,@@ -61,37 +61,6 @@ describe("scoreScale (dynamic padded Score axis)", () => {});});-describe("lineSegments (gap segmentation)", () => {- it("no gaps: one segment with everything (consecutive indexes)", () => {- expect(lineSegments([60, 75.25, 85.5])).toEqual([- [- { index: 0, value: 60 },- { index: 1, value: 75.25 },- { index: 2, value: 85.5 },- ],- ]);- });-- it("a middle gap breaks into two segments (a lone point still forms a segment: point drawn, no line)", () => {- expect(lineSegments([0.12, null, 0.2])).toEqual([- [{ index: 0, value: 0.12 }],- [{ index: 2, value: 0.2 }],- ]);- expect(lineSegments([null, 1, 2, null, 3])).toEqual([- [- { index: 1, value: 1 },- { index: 2, value: 2 },- ],- [{ index: 4, value: 3 }],- ]);- });-- it("all missing / empty list: no segments", () => {- expect(lineSegments([null, null])).toEqual([]);- expect(lineSegments([])).toEqual([]);- });-});-describe("modelSeries / seriesValues (curves split by model ID and thinking level)", () => {const mixed = [{diff --git a/packages/web/test/usage-charts.test.ts b/packages/web/test/usage-charts.test.tsindex cde7a40b..a1e33fb2 100644--- a/packages/web/test/usage-charts.test.ts+++ b/packages/web/test/usage-charts.test.ts@@ -1,11 +1,11 @@/*** Cost Center chart pure-function unit tests (chart-geom.ts): coordinate mapping, SVG path- * assembly, Token bar chart horizontal layout (fixed 25px bar width / spacing ≥ bar width /- * whether it scrolls horizontally), stacked-bar segment geometry and per-segment hit bands,- * pie slice arcs, success rate, hover-bubble placement (pointer lower-right, flipping at- * the edges; the cache hit rate shown in the cacheRead bubble is lib/format's shared- * cacheHitRate, tested in format.test.ts). Component interaction isn't covered here- * (vitest runs in a node environment, no DOM).+ * assembly (straight and gap-split paths — every line on the page is straight segments,+ * nothing is smoothed), container-fitting bar width (charts never scroll), stacked-bar+ * segment geometry and per-segment hit bands, and hover-bubble placement (pointer lower-right, flipping at the edges; the cache hit rate+ * shown in the cacheRead bubble is lib/format's shared cacheHitRate, tested in+ * format.test.ts). Component interaction isn't covered here (vitest runs in a node+ * environment, no DOM).** Canvas width is "measured container pixels" (1 canvas unit = 1 CSS pixel), so each case* passes an explicit width; 640 was the original fixed canvas width, and reusing it as the@@ -18,19 +18,20 @@ import {makeRangeGeom,linePath,areaPath,+ lineSegments,+ segmentPath,sparseLabelIdx,autoLabelIdx,- successRate,bubblePosition,- tokenBarLayout,+ fitBarWidth,barSegments,- pieSlices,BAR_W,BUBBLE_OFFSET,CHART_H,MIN_HIT_H,PAD_L,PAD_R,+ PAD_R_AXIS,} from "../src/features/usage/chart-geom";describe("makeGeom", () => {@@ -84,58 +85,82 @@ describe("linePath / areaPath", () => {});});-describe("tokenBarLayout", () => {- /** Bar width is real pixels, so inner width = container width - left/right padding: a 990 container has inner width 936. */- const inner = (containerW: number) => containerW - PAD_L - PAD_R;-- it("fixed 25px bar width: 30 days do not fit a half row (495px) → an extra-wide canvas with horizontal scrolling", () => {- const l = tokenBarLayout(495, 30);- expect(l.barW).toBe(25);- expect(l.barW).toBe(BAR_W);- // 30 slots x (25 bar + 25 gap) = 1500 > inner width 441 -> canvas = 46 + 1500 + 8- expect(l.chartW).toBe(1554);- expect(l.chartW).toBeGreaterThan(495);- expect(l.scroll).toBe(true);+describe("lineSegments / segmentPath (gap segmentation)", () => {+ it("no gaps: one segment with everything (consecutive indexes)", () => {+ expect(lineSegments([60, 75.25, 85.5])).toEqual([+ [+ { index: 0, value: 60 },+ { index: 1, value: 75.25 },+ { index: 2, value: 85.5 },+ ],+ ]);});- it("when they do not fit, bar gap = bar width: each slot = 2× bar width with the bar centered → exactly one bar width of space between bars", () => {- const l = tokenBarLayout(495, 30);- const g = makeGeom(30, 1, l.chartW);- expect(g.step).toBe(2 * l.barW);- // Two adjacent bars: left bar's right edge = x(0)+barW/2, right bar's left edge = x(1)-barW/2- const gap = g.x(1) - l.barW / 2 - (g.x(0) + l.barW / 2);- expect(gap).toBeCloseTo(l.barW);- // Half a gap is left on the first bar's left / last bar's right, so bars don't touch the axis or overflow the canvas- expect(g.x(0) - l.barW / 2).toBeCloseTo(PAD_L + l.barW / 2);- expect(g.x(29) + l.barW / 2).toBeCloseTo(l.chartW - PAD_R - l.barW / 2);+ it("a middle gap breaks into two segments (a lone point still forms a segment: point drawn, no line)", () => {+ expect(lineSegments([0.12, null, 0.2])).toEqual([+ [{ index: 0, value: 0.12 }],+ [{ index: 2, value: 0.2 }],+ ]);+ expect(lineSegments([null, 1, 2, null, 3])).toEqual([+ [+ { index: 1, value: 1 },+ { index: 2, value: 2 },+ ],+ [{ index: 4, value: 3 }],+ ]);});- it("few points: bars do **not** widen (25px is fixed, not a floor); all slack goes into the gaps", () => {- const l = tokenBarLayout(990, 7);- expect(l.barW).toBe(BAR_W); // the old implementation would stretch it to 936/14 = 66.86px- expect(l.chartW).toBe(990); // the canvas still fills the container: the slack goes into the bar gaps, not the right edge- expect(l.scroll).toBe(false);- // Each slot = inner width / 7 = 133.7px: a 25px bar centered, with 108.7px of gap (>= bar width)- const g = makeGeom(7, 1, l.chartW);- expect(g.step).toBeCloseTo(inner(990) / 7);- const gap = g.x(1) - l.barW / 2 - (g.x(0) + l.barW / 2);- expect(gap).toBeCloseTo(inner(990) / 7 - BAR_W);- expect(gap).toBeGreaterThan(BAR_W);+ it("all missing / empty list: no segments", () => {+ expect(lineSegments([null, null])).toEqual([]);+ expect(lineSegments([])).toEqual([]);});- it("boundary: exactly 50px per slot fills without scrolling; one more day means extra width + scrolling (bar width stays 25px)", () => {- const exact = inner(990) / 50; // 18.72 days- const fits = Math.floor(exact); // 18 days: inner width 936 >= 18x50 = 900- expect(tokenBarLayout(990, fits)).toMatchObject({ barW: BAR_W, chartW: 990, scroll: false });- expect(tokenBarLayout(990, fits + 1)).toMatchObject({ barW: BAR_W, scroll: true });- expect(tokenBarLayout(990, fits + 1).chartW).toBe(PAD_L + 2 * BAR_W * 19 + PAD_R);+ it("a segment strokes only its own indexes, so nothing bridges the hole between two segments", () => {+ const g = makeRangeGeom(3, 0, 100, 640);+ /** Path coordinates are rounded to 2 decimals (see chart-geom's rnd). */+ const at = (i: number, v: number) => `${Math.round(g.x(i) * 100) / 100},${g.y(v)}`;+ const [first, second] = lineSegments([100, null, 0]);+ expect(segmentPath(g, first!)).toBe(`M${at(0, 100)}`);+ expect(segmentPath(g, second!)).toBe(`M${at(2, 0)}`);+ expect(segmentPath(g, [])).toBe("");+ // A two-point run is one straight stroke between exactly those two indexes.+ expect(segmentPath(g, lineSegments([100, 0, null])[0]!)).toBe(`M${at(0, 100)} L${at(1, 0)}`);+ });+});++describe("fitBarWidth", () => {+ it("60% of the cell, capped at BAR_W: wide cells keep the 25px ceiling, narrow ones shrink with the cell", () => {+ expect(fitBarWidth(100)).toBe(BAR_W);+ expect(fitBarWidth(50)).toBe(BAR_W);+ expect(fitBarWidth(41)).toBe(24);+ expect(fitBarWidth(20)).toBe(12);+ });++ it("floors at 1px hairlines instead of overlapping: a bar never exceeds a >=1.7px cell", () => {+ expect(fitBarWidth(3)).toBe(1);+ expect(fitBarWidth(1.8)).toBe(1);+ expect(fitBarWidth(0)).toBe(1);+ });++ it("bars centered in their cells never touch: gap = step - barW >= 40% of the cell", () => {+ for (const step of [2, 5, 10, 25, 50, 133]) {+ expect(step - fitBarWidth(step)).toBeGreaterThanOrEqual(step * 0.4 - 1);+ }+ });+});++describe("padR (right-axis room)", () => {+ it("defaults to PAD_R; PAD_R_AXIS widens the right padding and shrinks the inner width", () => {+ expect(makeGeom(2, 100, 640).padR).toBe(PAD_R);+ const g = makeGeom(2, 100, 640, PAD_R_AXIS);+ expect(g.padR).toBe(PAD_R_AXIS);+ expect(g.innerW).toBe(640 - PAD_L - PAD_R_AXIS);});- it("full-row container + few day points: bar width stays 25px (the old implementation fattened to ~180px here)", () => {- const l = tokenBarLayout(990, 3);- expect(l.barW).toBe(25);- expect(l.chartW).toBe(990);- expect(l.scroll).toBe(false);+ it("geoms sharing n / w / padR share x() exactly — an overlay on its own y scale stays aligned with the marks under it", () => {+ const bars = makeGeom(5, 12345, 640, PAD_R_AXIS);+ const rate = makeRangeGeom(5, 0, 100, 640, PAD_R_AXIS);+ for (let i = 0; i < 5; i++) expect(rate.x(i)).toBe(bars.x(i));});});@@ -214,40 +239,6 @@ describe("barSegments", () => {});});-describe("pieSlices", () => {- it("laid out clockwise from 12 o'clock by value share: a half-circle arc starts at the top and ends at the bottom", () => {- const [a, b] = pieSlices([1, 1], 50, 50, 40);- expect(a!.frac).toBe(0.5);- expect(a!.start).toBe(0);- expect(a!.end).toBeCloseTo(Math.PI);- // First slice: center -> 12 o'clock -> clockwise (sweep=1) to 6 o'clock; exactly a- // half-circle, so large-arc=0- expect(a!.path).toBe("M50,50 L50,10 A40,40 0 0 1 50,90 Z");- // The second slice continues to finish the bottom half- expect(b!.path).toBe("M50,50 L50,90 A40,40 0 0 1 50,10 Z");- });-- it("slices spanning more than a half circle set large-arc=1", () => {- const [big] = pieSlices([3, 1], 50, 50, 40);- expect(big!.frac).toBe(0.75);- expect(big!.path).toBe("M50,50 L50,10 A40,40 0 1 1 10,50 Z");- });-- it("a single category at 100% degenerates to a full circle (two half-circle arcs; an A command with coincident endpoints draws nothing)", () => {- const [only] = pieSlices([7], 50, 50, 40);- expect(only!.frac).toBe(1);- expect(only!.path).toBe("M50,10 A40,40 0 1 1 50,90 A40,40 0 1 1 50,10 Z");- });-- it("non-positive values produce no slice (original indexes kept so callers can look up names/colors); empty when the total ≤ 0", () => {- const slices = pieSlices([5, 0, 5], 50, 50, 40);- expect(slices.map((s) => s.index)).toEqual([0, 2]);- expect(slices.map((s) => s.frac)).toEqual([0.5, 0.5]);- expect(pieSlices([], 50, 50, 40)).toEqual([]);- expect(pieSlices([0, 0], 50, 50, 40)).toEqual([]);- });-});-describe("sparseLabelIdx", () => {it("sparse first/middle/last labeling", () => {expect(sparseLabelIdx(0)).toEqual([]);@@ -258,14 +249,6 @@ describe("sparseLabelIdx", () => {});});-describe("successRate", () => {- it("completed/total; no requests counts as 1", () => {- expect(successRate(99, 100)).toBeCloseTo(0.99);- expect(successRate(5, 10)).toBe(0.5);- expect(successRate(0, 0)).toBe(1);- });-});-describe("bubblePosition", () => {// A 640px canvas that fits its card, not scrolled: the visible window is the whole canvas.const view = { left: 0, right: 640, bottom: CHART_H };diff --git a/packages/web/test/usage-controls.test.ts b/packages/web/test/usage-controls.test.tsnew file mode 100644index 00000000..dd971dfb--- /dev/null+++ b/packages/web/test/usage-controls.test.ts@@ -0,0 +1,400 @@+/**+ * Cost center control + series-shaping helper tests (usage-controls.ts): range+ * presets (calendar and trailing timestamp windows), the precision each range+ * derives (there is no precision control) and the bucket counts that keeps+ * inside the server's cap, bucket-key labels, entity+ * folding for the requests chart's stacked bars (top entities + a neutral+ * counted tail), the per-bucket success / cache-hit rates (a bucket with+ * nothing to rate has no rate, and is only given a height when a line has to+ * cross it), and the empty-bucket compaction every chart on the page draws+ * over — including that the per-entity counts stay aligned with the buckets+ * after it.+ */+import { describe, expect, it } from "vitest";+import type { UsageSeriesPoint } from "@prismshadow/penguin-server/api";+import {+ bucketAxisLabel,+ bucketFullLabel,+ compactCounts,+ compactSeries,+ defaultGranularity,+ foldEntitySeries,+ hitRateValues,+ isoDate,+ MAX_NAMED_SERIES,+ NO_RATE_PLOT,+ plotRates,+ presetDefaultGranularity,+ presetRange,+ presetTsWindow,+ rangeDays,+ rateSeries,+ sumCounts,+} from "../src/features/usage/usage-controls";+import { SERIES_COLORS } from "../src/lib/category-colors";++const point = (over: Partial<UsageSeriesPoint>): UsageSeriesPoint => ({+ bucket: "2026-08-20",+ cacheRead: 0,+ cacheWrite: 0,+ output: 0,+ total: 0,+ cost: null,+ requests: 0,+ completed: 0,+ denominator: 0,+ ...over,+});++describe("presetRange / presetTsWindow / rangeDays", () => {+ it("a calendar preset ends today and spans its day count inclusively", () => {+ const today = new Date(2026, 7, 20); // 2026-08-20 local+ expect(presetRange("7d", today)).toEqual({ from: "2026-08-14", to: "2026-08-20" });+ expect(presetRange("30d", today)).toEqual({ from: "2026-07-22", to: "2026-08-20" });+ expect(presetRange("90d", today)).toEqual({ from: "2026-05-23", to: "2026-08-20" });+ expect(isoDate(today)).toBe("2026-08-20");+ });++ it("a trailing preset yields instant bounds plus the local dates they span", () => {+ const now = new Date(2026, 7, 20, 0, 30); // 00:30 local: the trailing day crosses midnight+ const hour = presetTsWindow("1h", now);+ expect(hour.toTs).toBe(now.toISOString());+ expect(Date.parse(hour.toTs) - Date.parse(hour.fromTs)).toBe(3_600_000);+ expect(hour.to).toBe("2026-08-20");+ expect(hour.from).toBe("2026-08-19");+ const day = presetTsWindow("1d", now);+ expect(Date.parse(day.toTs) - Date.parse(day.fromTs)).toBe(86_400_000);+ expect(day.from).toBe("2026-08-19");+ });++ it("rangeDays counts both ends; nonsense ranges count as 1", () => {+ expect(rangeDays("2026-08-14", "2026-08-20")).toBe(7);+ expect(rangeDays("2026-08-20", "2026-08-20")).toBe(1);+ expect(rangeDays("2026-08-21", "2026-08-20")).toBe(1);+ expect(rangeDays("oops", "2026-08-20")).toBe(1);+ });+});++describe("the range picks the precision (there is no precision control)", () => {+ /**+ * How many buckets a preset's own window produces at its derived precision.+ * The server rejects anything over 500 (usage-service caps the zero-fill+ * skeleton), and with the precision control gone the page has to be+ * incapable of asking for a rejected combination in the first place.+ */+ const MAX_BUCKETS = 500;+ const buckets: Record<string, number> = {+ "1h": 61, // 60 minutes, both ends inclusive+ "1d": 25, // 24 hours, both ends inclusive+ "7d": 7,+ "30d": 30,+ "90d": 90,+ };++ it("each preset derives exactly one precision", () => {+ expect(presetDefaultGranularity("1h", 1)).toBe("minute");+ expect(presetDefaultGranularity("1d", 1)).toBe("hour");+ expect(presetDefaultGranularity("7d", 7)).toBe("day");+ expect(presetDefaultGranularity("30d", 30)).toBe("day");+ expect(presetDefaultGranularity("90d", 90)).toBe("day");+ });++ it("a custom range scales with its length: day, then week, then month", () => {+ expect(presetDefaultGranularity("custom", 1)).toBe("day");+ expect(presetDefaultGranularity("custom", 92)).toBe("day");+ expect(presetDefaultGranularity("custom", 93)).toBe("week");+ expect(presetDefaultGranularity("custom", 190)).toBe("week");+ expect(presetDefaultGranularity("custom", 191)).toBe("month");+ expect(defaultGranularity(365)).toBe("month");+ });++ it("no preset can ask the server for more buckets than it will return", () => {+ for (const [preset, count] of Object.entries(buckets)) {+ expect(count).toBeLessThanOrEqual(MAX_BUCKETS);+ }+ // Custom ranges are bounded by their own derivation: day only up to a+ // quarter (92 buckets), then week (a year is 53), then month.+ expect(Math.ceil(92 / 1)).toBeLessThanOrEqual(MAX_BUCKETS);+ expect(Math.ceil(190 / 7) + 1).toBeLessThanOrEqual(MAX_BUCKETS);+ expect(Math.ceil((365 * 5) / 30)).toBeLessThanOrEqual(MAX_BUCKETS);+ });++ it("only the trailing presets reach the precisions that need timestamp bounds", () => {+ // minute always, and hour when a window is given, are enumerated between+ // instants server-side — so exactly the two presets that send fromTs/toTs.+ const needsWindow = (g: string) => g === "minute" || g === "hour";+ expect(needsWindow(presetDefaultGranularity("1h", 1))).toBe(true);+ expect(needsWindow(presetDefaultGranularity("1d", 1))).toBe(true);+ for (const [preset, days] of [+ ["7d", 7],+ ["30d", 30],+ ["90d", 90],+ ["custom", 45],+ ["custom", 400],+ ] as const) {+ expect(needsWindow(presetDefaultGranularity(preset, days))).toBe(false);+ }+ });+});++describe("bucket labels", () => {+ it("axis form is short; bubble form is the full key with a minute/hour key's T opened up", () => {+ expect(bucketAxisLabel("minute", "2026-08-20T09:05")).toBe("09:05");+ expect(bucketAxisLabel("hour", "2026-08-20T09:00")).toBe("09:00");+ expect(bucketAxisLabel("day", "2026-08-20")).toBe("08-20");+ expect(bucketAxisLabel("week", "2026-08-17")).toBe("08-17");+ expect(bucketAxisLabel("month", "2026-08")).toBe("2026-08");+ expect(bucketFullLabel("minute", "2026-08-20T09:05")).toBe("2026-08-20 09:05");+ expect(bucketFullLabel("week", "2026-08-17")).toBe("2026-08-17");+ });+});++describe("foldEntitySeries", () => {+ /** An entity's counts, spelled out per bucket: requests, of which `completed`, over `denominator` rated ones. */+ const e = (label: string, requests: number[], completed = requests, denominator = requests) => ({+ label,+ requests,+ completed,+ denominator,+ });++ it("top entities keep their own series; a tail of two or more folds into one summed, counted tail", () => {+ const folded = foldEntitySeries(+ [+ e("a", [5, 5]),+ e("b", [4, 0]),+ e("c", [1, 2]),+ e("d", [1, 1]),+ e("e", [1, 0]),+ e("f", [0, 1]),+ ],+ (n) => `other:${n}`,+ 4,+ );+ expect(folded.map((x) => x.label)).toEqual(["a", "b", "c", "d", "other:2"]);+ // The label carries the fold count, so the chart never implies the head is everything.+ expect(folded[4]).toEqual({+ label: "other:2",+ requests: [1, 1],+ completed: [1, 1],+ denominator: [1, 1],+ other: true,+ });+ });++ it("the tail sums success counts too, so its line is the combined rate rather than one entity's", () => {+ const folded = foldEntitySeries(+ [+ e("a", [1]),+ e("b", [1]),+ e("c", [1]),+ e("d", [1]),+ e("e", [4], [1], [4]),+ e("f", [4], [3], [4]),+ ],+ (n) => `other:${n}`,+ 4,+ );+ expect(folded[4]!.completed).toEqual([4]);+ expect(folded[4]!.denominator).toEqual([8]);+ expect(rateSeries(folded[4]!)).toEqual([50]);+ });++ it("a tail of exactly one keeps its name (a mystery bucket of one is worse than a fifth label)", () => {+ const folded = foldEntitySeries(+ [e("a", [1]), e("b", [1]), e("c", [1]), e("d", [1]), e("e", [2])],+ (n) => `other:${n}`,+ 4,+ );+ expect(folded[4]).toEqual({+ label: "e",+ requests: [2],+ completed: [2],+ denominator: [2],+ other: true,+ });+ });++ it("no tail, no fold", () => {+ expect(foldEntitySeries([e("a", [1])], (n) => `other:${n}`, 4)).toEqual([+ { label: "a", requests: [1], completed: [1], denominator: [1] },+ ]);+ expect(foldEntitySeries([], (n) => `other:${n}`, 4)).toEqual([]);+ });++ it("the default cap is the palette's length: every named series gets a color of its own", () => {+ expect(MAX_NAMED_SERIES).toBe(SERIES_COLORS.length);+ const many = Array.from({ length: MAX_NAMED_SERIES + 3 }, (_, i) => e(`e${i}`, [1]));+ const folded = foldEntitySeries(many, (n) => `other:${n}`);+ expect(folded).toHaveLength(MAX_NAMED_SERIES + 1);+ expect(folded.at(-1)).toMatchObject({ label: "other:3", other: true });+ });+});++describe("sumCounts", () => {+ it("adds the drawn series column by column: the stack's height and the counts behind its combined rate", () => {+ const totals = sumCounts([+ { label: "a", requests: [2, 0], completed: [1, 0], denominator: [2, 0] },+ { label: "b", requests: [1, 3], completed: [1, 3], denominator: [1, 3] },+ ]);+ expect(totals).toEqual({ requests: [3, 3], completed: [2, 3], denominator: [3, 3] });+ expect(rateSeries(totals)).toEqual([(2 / 3) * 100, 100]);+ });++ it("no series at all sums to nothing (an empty chart, not a crash)", () => {+ expect(sumCounts([])).toEqual({ requests: [], completed: [], denominator: [] });+ });+});++describe("rate values", () => {+ it("per-entity success rate is percent of the non-aborted denominator", () => {+ expect(rateSeries({ completed: [3, 1, 0], denominator: [4, 1, 2] })).toEqual([75, 100, 0]);+ });++ it("a bucket with nothing to rate has no rate at all — null, which is neither the 0 of 'failed everything' nor a number the table may print", () => {+ expect(rateSeries({ completed: [0, 2, 0], denominator: [0, 2, 0] })).toEqual([null, 100, null]);+ // A real 0 survives as 0: requests were made and every one of them failed.+ expect(rateSeries({ completed: [0], denominator: [3] })).toEqual([0]);+ });++ it("cache hit rate is percent of read/(read+write); a bucket with no cache traffic has no rate either", () => {+ expect(+ hitRateValues([+ point({ cacheRead: 3, cacheWrite: 1 }),+ point({}),+ point({ cacheRead: 0, cacheWrite: 5 }),+ ]),+ ).toEqual([75, null, 0]);+ });++ it("plotRates gives every bucket a height so the stroke stays continuous, absent rates at the top of the axis", () => {+ expect(NO_RATE_PLOT).toBe(100);+ expect(plotRates([75, null, 0])).toEqual([75, NO_RATE_PLOT, 0]);+ // Drawing at 100 and reading 0 are different questions: a rated 0 is not lifted.+ expect(plotRates(rateSeries({ completed: [0, 0], denominator: [0, 4] }))).toEqual([+ NO_RATE_PLOT,+ 0,+ ]);+ });+});++describe("compactSeries", () => {+ const at = (bucket: string, over: Partial<UsageSeriesPoint> = {}) =>+ point({ bucket, requests: 1, total: 10, ...over });++ it("drops the buckets that recorded nothing and keeps the rest in order, with where each one sat", () => {+ const c = compactSeries([at("d1"), point({ bucket: "d2" }), at("d3")]);+ expect(c.points.map((p) => p.bucket)).toEqual(["d1", "d3"]);+ expect(c.kept).toEqual([0, 2]);+ });++ it("a request that spent no tokens keeps its bucket; only a bucket with neither is empty", () => {+ const c = compactSeries([+ point({ bucket: "d1", requests: 1, total: 0 }),+ point({ bucket: "d2", requests: 0, total: 5 }),+ point({ bucket: "d3" }),+ ]);+ expect(c.points.map((p) => p.bucket)).toEqual(["d1", "d2"]);+ expect(c.kept).toEqual([0, 1]);+ });++ it("a bucket only one entity ran in is not empty: the bucket is what counts, never one entity's share of it", () => {+ // d2 holds a single request from one entity; the others were idle in it.+ const c = compactSeries([+ at("d1"),+ at("d2", { requests: 1, total: 4 }),+ point({ bucket: "d3" }),+ ]);+ expect(c.points.map((p) => p.bucket)).toEqual(["d1", "d2"]);+ });++ it("breaks mark the drawn point each skip follows, however many buckets it swallowed", () => {+ const c = compactSeries([+ at("d1"),+ point({ bucket: "d2" }),+ point({ bucket: "d3" }),+ at("d4"),+ at("d5"),+ point({ bucket: "d6" }),+ at("d7"),+ ]);+ expect(c.points.map((p) => p.bucket)).toEqual(["d1", "d4", "d5", "d7"]);+ expect(c.breaks).toEqual([0, 2]);+ expect(c.kept).toEqual([0, 3, 4, 6]);+ });++ it("empty buckets before the first point or after the last shorten the axis without breaking it", () => {+ const c = compactSeries([point({ bucket: "d1" }), at("d2"), point({ bucket: "d3" })]);+ expect(c.points.map((p) => p.bucket)).toEqual(["d2"]);+ expect(c.breaks).toEqual([]);+ expect(c.kept).toEqual([1]);+ });++ it("a range that recorded nothing compacts to nothing (the charts show their empty state, not a flat zero line)", () => {+ expect(compactSeries([point({}), point({})])).toEqual({ points: [], kept: [], breaks: [] });+ expect(compactSeries([])).toEqual({ points: [], kept: [], breaks: [] });+ });++ it("nothing to drop leaves the series and its axis exactly as they came", () => {+ const full = [at("d1"), at("d2")];+ const c = compactSeries(full);+ expect(c.points).toEqual(full);+ expect(c.breaks).toEqual([]);+ expect(c.kept).toEqual([0, 1]);+ });+});++describe("compactCounts (per-entity alignment across the compaction)", () => {+ // Five buckets; the server sends every entity one value per bucket, aligned+ // with the series. d2 and d4 recorded nothing at all.+ const series = [+ point({ bucket: "d1", requests: 2, total: 20 }),+ point({ bucket: "d2" }),+ point({ bucket: "d3", requests: 3, total: 30 }),+ point({ bucket: "d4" }),+ point({ bucket: "d5", requests: 1, total: 10 }),+ ];+ const entity = {+ requests: [2, 0, 1, 0, 0],+ completed: [1, 0, 1, 0, 0],+ denominator: [2, 0, 1, 0, 0],+ };++ it("takes exactly the kept positions, so a value stays with the bucket it was recorded in", () => {+ const { points, kept } = compactSeries(series);+ const compacted = compactCounts(entity, kept);+ expect(points.map((p) => p.bucket)).toEqual(["d1", "d3", "d5"]);+ expect(compacted).toEqual({+ requests: [2, 1, 0],+ completed: [1, 1, 0],+ denominator: [2, 1, 0],+ });+ // The invariant the per-entity series are built on, asserted by bucket key+ // rather than by position: value[i] after the compaction is still the value+ // the server sent for points[i].bucket.+ points.forEach((p, i) => {+ const origin = series.findIndex((q) => q.bucket === p.bucket);+ expect(compacted.requests[i]).toBe(entity.requests[origin]);+ expect(compacted.completed[i]).toBe(entity.completed[origin]);+ expect(compacted.denominator[i]).toBe(entity.denominator[origin]);+ });+ });++ it("an entity idle in a kept bucket keeps its zero there, which is what makes it a dash and not a missing column", () => {+ const { kept } = compactSeries(series);+ const idle = compactCounts(+ { requests: [0, 0, 0, 0, 1], completed: [0, 0, 0, 0, 1], denominator: [0, 0, 0, 0, 1] },+ kept,+ );+ expect(idle.requests).toEqual([0, 0, 1]);+ expect(rateSeries(idle)).toEqual([null, null, 100]);+ });++ it("a short or missing array reads as zero rather than undefined (a chart never plots a hole it cannot explain)", () => {+ expect(compactCounts({ requests: [5], completed: [], denominator: [] }, [0, 2])).toEqual({+ requests: [5, 0],+ completed: [0, 0],+ denominator: [0, 0],+ });+ });+});