Skip to content

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

refactor(ui): W8 — the charts and the command palette move into the UI package (#901)

Yaowei Zhengb8f3cc6820a1
diff --git a/changelog/unreleased/2026-09-30-ui-migration-w8.md b/changelog/unreleased/2026-09-30-ui-migration-w8.md
new file mode 100644
index 00000000..c32435d7
--- /dev/null
+++ b/changelog/unreleased/2026-09-30-ui-migration-w8.md
@@ -0,0 +1,29 @@
+# The charts and the command palette move into the shared UI package
+
+- **Date:** 2026-09-30
+- **Type:** refactor
+- **Scope:** `ui`, `web`, `ui-gallery`
+
+[中文版](2026-09-30-ui-migration-w8.zh.md)
+
+W8 of the UI-package migration moves the chart foundation and the command palette into `@prismshadow/penguin-ui`. The charts that draw app data stay in the Web App and draw through the package's primitives.
+
+## What moved
+
+- **Chart primitives:** the marks (`ChartBar`, `ChartLine`, `ChartArea`, `ChartPoint`, `ChartArc`, grid and axis, `TimelineBar`) with their geometry, `useChartStyle`, `ChartFrame` with its hover helpers, and `TokenDonut` (its words now come in a `labels` prop).
+- **New:** `Sparkline` (the agent activity and benchmark score curves), `Ring` (a gauge of arcs against a budget, now drawing the finance gauge, the spend ring and the context ring), and `Legend` (inline or as a list, with hover, pin and toggle).
+- **Command palette:** `CommandPalette` is the presentation; the Web App keeps the actions and the shortcut binding (the keymap's `palette.toggle`) in `AppPalette`.
+
+## Details
+
+- The Web App's own charts (cost, token and request charts, the score trend, the Trace timeline, the finance card) now use `Legend` and the text rungs.
+- The Trace timeline's open bars hold still and end in a pulsing live dot, instead of pulsing the whole bar.
+- The Costs & usage page and the benchmark detail page take the shared page header; on the benchmark detail page the Benchmark's path moves to its own line under the title.
+- The gallery's charts board shows `Ring` and `Legend`; the dialogs board opens the command palette.
+
+## Visible changes in the default theme (Primer)
+
+- Chart text of 10–11 px (legends, timeline labels, the finance card) becomes 12 px; legend gaps tighten from 16 to 12 px.
+- A few tone inks in light mode are one step darker (the finance arc, the donut's near-limit remainder, the activity sparkline).
+- The context panel has slightly more padding, lighter legend labels and the theme's focus outline.
+- In the command palette, the selected row is a lighter fill and unselected rows are darker ink.
diff --git a/changelog/unreleased/2026-09-30-ui-migration-w8.zh.md b/changelog/unreleased/2026-09-30-ui-migration-w8.zh.md
new file mode 100644
index 00000000..44ea585b
--- /dev/null
+++ b/changelog/unreleased/2026-09-30-ui-migration-w8.zh.md
@@ -0,0 +1,29 @@
+# 统计图与命令面板迁入共享 UI 包
+
+- **Date:** 2026-09-30
+- **Type:** refactor
+- **Scope:** `ui`, `web`, `ui-gallery`
+
+[English](2026-09-30-ui-migration-w8.md)
+
+UI 包迁移的 W8 把统计图基础与命令面板搬进 `@prismshadow/penguin-ui`。绘制应用数据的统计图留在 Web App,经包内的基元绘制。
+
+## 迁入的内容
+
+- **统计图基元**:各类标记(`ChartBar`、`ChartLine`、`ChartArea`、`ChartPoint`、`ChartArc`、网格与坐标轴、`TimelineBar`)及其几何计算、`useChartStyle`、`ChartFrame` 及其悬停辅助,以及 `TokenDonut`(文案改由 `labels` 属性传入)。
+- **新增**:`Sparkline`(智能体活跃度与评估分数两条迷你折线)、`Ring`(按预算绘制的圆环仪表,现用于财务仪表、支出环与上下文圆环)、`Legend`(行内或列表两种形态,支持悬停、固定与切换)。
+- **命令面板**:`CommandPalette` 负责呈现;动作列表与快捷键绑定(快捷键表中的 `palette.toggle`)留在 Web App 的 `AppPalette`。
+
+## 细节
+
+- Web App 自有的统计图(成本、Token 与请求图、分数趋势、Trace 时间线、财务卡片)改用 `Legend` 与字号阶梯。
+- Trace 时间线上进行中的条不再整条脉动,改为静止并在末端显示一个脉动的实时圆点。
+- 成本中心页与评估详情页改用共享页头;评估详情页中 Benchmark 的路径移到标题下方单独一行。
+- 画廊的统计图页展示 `Ring` 与 `Legend`,对话框页可打开命令面板。
+
+## 通用主题下可见的变化
+
+- 统计图中 10–11 px 的文字(图例、时间线标签、财务卡片)改为 12 px;图例间距由 16 px 收紧为 12 px。
+- 浅色下若干色调墨色深一级(财务圆弧、圆环接近上限的剩余部分、活跃度迷你折线)。
+- 上下文面板的内边距略增,图例标签变浅,键盘焦点改用主题的焦点轮廓。
+- 命令面板中选中行的底色变浅,未选中行的文字变深。
diff --git a/packages/ui-gallery/src/library/boards/chart-primitives.tsx b/packages/ui-gallery/src/library/boards/chart-primitives.tsx
index f9388451..95113322 100644
--- a/packages/ui-gallery/src/library/boards/chart-primitives.tsx
+++ b/packages/ui-gallery/src/library/boards/chart-primitives.tsx
@@ -1,5 +1,5 @@
/**
- * The chart primitives on their own (packages/web/src/components/ui/chart), each on a small
+ * The chart primitives on their own (the package's `charts/marks`), each on a small
* stage with demo data: the bar, the line, the area, the point, the arc, the grid and axis
* labels, and the Trace timeline's HTML bar. They read the theme's chart tokens themselves; the
* stages only say where a mark sits and which slot it paints with.
@@ -9,8 +9,6 @@
* primitive uses, as a key to what the token chooses.
*/
import type { ReactNode } from "react";
-import { useChartStyle } from "../../../../web/src/lib/chart-style";
-import type { ChartCurve } from "../../../../web/src/lib/chart-style";
import {
ChartArc,
ChartArea,
@@ -21,7 +19,9 @@ import {
ChartPoint,
TimelineBar,
curvePath,
-} from "../../../../web/src/components/ui/chart";
+ useChartStyle,
+} from "@prismshadow/penguin-ui";
+import type { ChartCurve } from "@prismshadow/penguin-ui";
import { BoardGroup } from "../../foundations/shared";
import { useGallery } from "../../state";
diff --git a/packages/ui-gallery/src/library/boards/charts.tsx b/packages/ui-gallery/src/library/boards/charts.tsx
index a0fa406b..2a9e5fae 100644
--- a/packages/ui-gallery/src/library/boards/charts.tsx
+++ b/packages/ui-gallery/src/library/boards/charts.tsx
@@ -1,9 +1,10 @@
/**
* 图表: the chart foundation's page — first the primitives every chart draws through, then the
* current theme's chart tokens, live, then every chart kind the app draws, on fixed demo data
- * so the themes' chart styles compare: the token donut, the cost trend line, the stacked token
- * bars with their cache-hit curve and legend, the requests-and-success-rate stack, the activity
- * and score sparklines, and the Trace timeline's lanes.
+ * so the themes' chart styles compare: the token donut, the ring gauge, the legend in both
+ * layouts, the cost trend line, the stacked token bars with their cache-hit curve and legend,
+ * the requests-and-success-rate stack, the sparkline at both scales, and the Trace timeline's
+ * lanes.
*
* Every input a chart receives is built once, at module level or memoized: a chart keeps
* effects keyed on its data (the timeline re-measures its scroller whenever its groups change),
@@ -17,9 +18,9 @@ import type {
TraceToolSpan,
UsageSeriesPoint,
} from "@prismshadow/penguin-server/api";
-import { TokenDonut } from "../../../../web/src/components/ui/token-donut";
-import { ActivitySparkline } from "../../../../web/src/features/agents/activity-sparkline";
-import { ScoreSparkline } from "../../../../web/src/features/benchmark/score-sparkline";
+import { Legend, Ring, Sparkline, TokenDonut } from "@prismshadow/penguin-ui";
+import type { LegendItem, RingSegment, ToneName } from "@prismshadow/penguin-ui";
+import { humanizeTokens } from "../../../../web/src/lib/format";
import { TimelineChart } from "../../../../web/src/features/traces/timeline-chart";
import type { TraceHighlight } from "../../../../web/src/features/traces/timeline-chart";
import { TrendChart } from "../../../../web/src/features/usage/trend-chart";
@@ -81,10 +82,49 @@ function agentCounts(
});
}
-const SCORES = [0.62, 0.66, 0.71, 0.69, 0.74, 0.78, 0.77, 0.83];
+const SCORES = [62, 66, 71, 69, 74, 78, 77, 83];
+const LONE_SCORE = SCORES.slice(-1);
const ACTIVITY = [2, 3, 1, 5, 6, 4, 1, 0, 4, 7, 5, 3, 4, 5];
const FLAT = [0, 0, 0, 0, 0, 0, 0];
+/** Usage well under, near and at the limit, then the first again at a larger size. */
+const DONUTS = [
+ { cacheRead: 42_000, cacheWrite: 6_000, output: 9_000, size: 44 },
+ { cacheRead: 120_000, cacheWrite: 14_000, output: 31_000, size: 44 },
+ { cacheRead: 150_000, cacheWrite: 20_000, output: 26_000, size: 44 },
+ { cacheRead: 42_000, cacheWrite: 6_000, output: 9_000, size: 64 },
+];
+
+/** Spend against a budget under, near and over it, each in the tone the finance page gives it. */
+const SPEND: readonly { ratio: number; tone: ToneName }[] = [
+ { ratio: 0.41, tone: "success" },
+ { ratio: 0.86, tone: "attention" },
+ { ratio: 1.2, tone: "danger" },
+];
+
+/** A whole split into shares, each in its series slot. */
+const SHARES: readonly RingSegment[] = [0.34, 0.22, 0.18, 0.12].map((value, series) => ({
+ value,
+ paint: { series },
+}));
+
+/** The list legend's demo figures, one per part: its estimate and its whole percent. */
+const PART_FIGURES = [
+ { tokens: 18_400, percent: 38 },
+ { tokens: 9_100, percent: 19 },
+ { tokens: 6_300, percent: 13 },
+ { tokens: 14_600, percent: 30 },
+] as const;
+
+function Figures({ tokens, percent }: { tokens: number; percent: number }) {
+ return (
+ <>
+ <span className="shrink-0 font-mono font-medium text-fg">~{humanizeTokens(tokens)}</span>
+ <span className="w-8 shrink-0 text-right font-mono text-fg-subtle">{percent}%</span>
+ </>
+ );
+}
+
/** A Task's timeline: seconds after a fixed start, as the trace records them. */
const T0 = Date.UTC(2026, 8, 28, 9, 0, 0);
const at = (seconds: number) => new Date(T0 + seconds * 1000).toISOString();
@@ -155,7 +195,39 @@ export function ChartsBoard() {
const t = S.library.charts;
const [legend, setLegend] = useState<TokenLegendKey | null>(null);
const [highlight, setHighlight] = useState<TraceHighlight | null>(null);
+ const [kind, setKind] = useState<string | null>(null);
+ const [part, setPart] = useState<string | null>(null);
+ const [pinned, setPinned] = useState<string | null>(null);
const entities = useMemo(() => agentCounts(SERIES, t.agents), [t.agents]);
+ const kinds = useMemo<LegendItem[]>(
+ () => [
+ ...(["cacheRead", "cacheWrite", "output"] as const).map((role) => ({
+ key: role,
+ label: t.donutLabels[role],
+ paint: { role },
+ shape: "chip" as const,
+ })),
+ // A line on its own axis, not a fourth kind: its item names the shape and stays still.
+ {
+ key: "hitRate",
+ label: t.legendHitRate,
+ paint: { role: "ref" },
+ shape: "dash",
+ interactive: false,
+ },
+ ],
+ [t],
+ );
+ const parts = useMemo<LegendItem[]>(
+ () =>
+ PART_FIGURES.map((figures, i) => ({
+ key: `part-${i}`,
+ label: t.legendParts[i] ?? "",
+ paint: { series: i },
+ value: <Figures {...figures} />,
+ })),
+ [t],
+ );
return (
<div className="gf-board">
<Part title={t.parts.primitives} hint={t.parts.primitivesHint}>
@@ -167,16 +239,51 @@ export function ChartsBoard() {
<Part title={t.parts.charts} hint={t.parts.chartsHint}>
<BoardGroup title={t.donut} aside={t.donutHint}>
<div className="lib-row">
- <TokenDonut cacheRead={42_000} cacheWrite={6_000} output={9_000} max={200_000} />
- <TokenDonut cacheRead={120_000} cacheWrite={14_000} output={31_000} max={200_000} />
- <TokenDonut cacheRead={150_000} cacheWrite={20_000} output={26_000} max={200_000} />
- <TokenDonut
- cacheRead={42_000}
- cacheWrite={6_000}
- output={9_000}
- max={200_000}
- size={64}
- />
+ {DONUTS.map((donut, i) => (
+ <TokenDonut
+ key={i}
+ {...donut}
+ max={200_000}
+ labels={t.donutLabels}
+ format={humanizeTokens}
+ />
+ ))}
+ </div>
+ </BoardGroup>
+ <BoardGroup title={t.ring} aside={t.ringHint}>
+ <div className="lib-row">
+ {SPEND.map(({ ratio, tone }) => (
+ <Ring
+ key={ratio}
+ segments={[{ value: ratio }]}
+ max={1}
+ size={40}
+ width={4}
+ tone={tone}
+ label={t.ringSpend(Math.round(ratio * 100))}
+ />
+ ))}
+ <Ring segments={[]} max={1} size={40} width={4} label={t.ringNoBudget} />
+ <Ring segments={SHARES} max={1} size={40} width={6} label={t.ringShares} />
+ <span className="lib-cell text-fg-subtle">
+ <Ring segments={[{ value: 0.62 }]} max={1} size={12} width={2} trackOpacity={0.25} />
+ <span className="lib-caption">{t.ringContext}</span>
+ </span>
+ </div>
+ </BoardGroup>
+ <BoardGroup title={t.legend} aside={t.legendHint}>
+ <div className="lib-stack">
+ <Legend items={kinds} active={kind} onHover={setKind} />
+ <div className="lib-box w-72 p-3">
+ <Legend
+ layout="list"
+ items={parts}
+ active={part ?? pinned}
+ pinned={pinned}
+ onHover={setPart}
+ onSelect={(key) => setPinned((current) => (current === key ? null : key))}
+ />
+ </div>
</div>
</BoardGroup>
<BoardGroup title={t.trend} aside={t.trendHint}>
@@ -197,13 +304,24 @@ export function ChartsBoard() {
</BoardGroup>
<BoardGroup title={t.activity} aside={t.activityHint}>
<div className="lib-row">
- <ActivitySparkline data={ACTIVITY} label={t.activity} className="h-8 w-40" />
- <ActivitySparkline data={FLAT} label={t.activity} className="h-8 w-40" />
+ {[ACTIVITY, FLAT].map((values, i) => (
+ <Sparkline
+ key={i}
+ values={values}
+ label={t.activity}
+ area
+ tone="success"
+ width={100}
+ height={30}
+ className="h-8 w-40"
+ />
+ ))}
</div>
</BoardGroup>
<BoardGroup title={t.sparkline} aside={t.sparklineHint}>
<div className="lib-row">
- <ScoreSparkline values={SCORES} label={t.sparkline} />
+ <Sparkline values={SCORES} label={t.sparkline} scale="range" marker />
+ <Sparkline values={LONE_SCORE} label={t.sparkline} scale="range" marker />
</div>
</BoardGroup>
<BoardGroup title={t.timeline} aside={t.timelineHint}>
diff --git a/packages/ui-gallery/src/library/boards/dialogs.tsx b/packages/ui-gallery/src/library/boards/dialogs.tsx
index 635af148..24143c30 100644
--- a/packages/ui-gallery/src/library/boards/dialogs.tsx
+++ b/packages/ui-gallery/src/library/boards/dialogs.tsx
@@ -1,10 +1,13 @@
/**
- * 对话框: Modal, ConfirmModal in both tones, PagedDialog, Drawer, Sheet and the Lightbox, each
- * opened from a button (the lightbox from its thumbnail) and closed as the app closes it.
+ * 对话框: Modal, ConfirmModal in both tones, PagedDialog, Drawer, Sheet, the Lightbox and the
+ * CommandPalette, each opened from a button (the lightbox from its thumbnail) and closed as the app
+ * closes it. The palette's actions open the board's other dialogs, the way an app action opens its
+ * own overlay once the palette has gone.
*/
import { useState } from "react";
import {
Button,
+ CommandPalette,
ConfirmModal,
Drawer,
Input,
@@ -13,7 +16,7 @@ import {
Sheet,
ZoomableImage,
} from "@prismshadow/penguin-ui";
-import type { PagedDialogGroup, SheetSnap } from "@prismshadow/penguin-ui";
+import type { PagedDialogGroup, PaletteAction, SheetSnap } from "@prismshadow/penguin-ui";
import { BoardGroup } from "../../foundations/shared";
import { BASE } from "../../lib/location";
import { useGallery } from "../../state";
@@ -31,6 +34,7 @@ export function DialogsBoard() {
const [drawer, setDrawer] = useState(false);
const [sheet, setSheet] = useState(false);
const [snap, setSnap] = useState<SheetSnap>("half");
+ const [palette, setPalette] = useState(false);
const [name, setName] = useState(t.modalTitle);
const groups: PagedDialogGroup<Page>[] = [
{
@@ -43,6 +47,12 @@ export function DialogsBoard() {
},
{ key: "you", label: t.pagedGroups.you, items: [{ key: "account", label: t.pages.account }] },
];
+ const actions: PaletteAction[] = [
+ { id: "modal", label: t.modalTitle, run: () => setModal(true) },
+ { id: "paged", label: t.openPaged, run: () => setPaged(true) },
+ { id: "drawer", label: t.openDrawer, run: () => setDrawer(true) },
+ { id: "sheet", label: t.openSheet, run: () => setSheet(true) },
+ ];
return (
<div className="gf-board">
<BoardGroup title={t.modal}>
@@ -145,6 +155,20 @@ export function DialogsBoard() {
/>
</div>
</BoardGroup>
+ <BoardGroup title={t.palette} aside={t.paletteAside}>
+ <div className="lib-row">
+ <Button onClick={() => setPalette(true)}>{t.openPalette}</Button>
+ </div>
+ <CommandPalette
+ open={palette}
+ onClose={() => setPalette(false)}
+ actions={actions}
+ title={t.palette}
+ placeholder={t.palettePlaceholder}
+ emptyText={t.paletteEmpty}
+ hint={t.paletteHint}
+ />
+ </BoardGroup>
</div>
);
}
diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.ts
index a1818fd8..ebb28ad2 100644
--- a/packages/ui-gallery/src/strings-en.ts
+++ b/packages/ui-gallery/src/strings-en.ts
@@ -417,7 +417,8 @@ export const en: GalleryStrings = {
},
dialogs: {
title: "Dialogs",
- description: "Modal, confirmation, paged dialog, drawer, bottom sheet and lightbox.",
+ description:
+ "Modal, confirmation, paged dialog, drawer, bottom sheet, lightbox and command palette.",
},
tooltips: {
title: "Tooltips",
@@ -446,7 +447,7 @@ export const en: GalleryStrings = {
charts: {
title: "Charts",
description:
- "The chart foundation: the primitives every chart draws through, the current theme's chart tokens, and every chart built on them — the donut, cost trend and token bars, requests and success rate, the activity and score sparklines, the Trace timeline.",
+ "The chart foundation: the primitives every chart draws through, the current theme's chart tokens, and every chart built on them — the donut, the ring gauge, the legend, cost trend and token bars, requests and success rate, the sparkline, the Trace timeline.",
},
avatars: {
title: "Avatars",
@@ -689,6 +690,12 @@ export const en: GalleryStrings = {
lightbox: "Lightbox",
lightboxHint: "Click the thumbnail to zoom in; Esc or a click outside the image closes it.",
lightboxAlt: "The Penguin logo",
+ palette: "Command palette",
+ paletteAside: "Type to filter; each action opens another dialog on this board.",
+ openPalette: "Open the command palette",
+ palettePlaceholder: "Type to filter commands…",
+ paletteEmpty: "No matching commands",
+ paletteHint: "↑↓ to select · Enter to run · Esc to close",
},
tooltips: {
attribute: "The data-tooltip attribute",
@@ -854,6 +861,24 @@ export const en: GalleryStrings = {
donut: "Token donut",
donutHint:
"Cache reads, cache writes and output; the ring's remainder warns as usage nears the limit.",
+ donutLabels: {
+ usage: "Context usage",
+ cacheRead: "Cache read",
+ cacheWrite: "Cache write",
+ output: "Output",
+ },
+ ring: "Ring gauge",
+ ringHint:
+ "One arc against a budget in the budget's tone (under, near, over); without a budget the track stands alone; the composer's 12 px context ring takes the ink around it; several arcs split a whole into shares.",
+ ringSpend: (percent) => `Spend at ${percent}% of the budget`,
+ ringNoBudget: "No budget set",
+ ringShares: "Shares of a whole",
+ ringContext: "Context ring",
+ legend: "Legend",
+ legendHint:
+ "A row under a chart: pointing at one item fades the others, and an item that explains a line's shape stays out of it. A list legend prints each item's figures after its label and pins a row on click.",
+ legendHitRate: "Cache hit rate",
+ legendParts: ["System prompt", "Tool definitions", "Messages", "Tool results"],
trend: "Cost trend",
trendHint: "Fourteen days of cost as a line; hover a day.",
tokens: "Token usage",
@@ -866,7 +891,8 @@ export const en: GalleryStrings = {
activityHint:
"The agent card's fourteen-day session count curve; relative ups and downs only.",
sparkline: "Score sparkline",
- sparklineHint: "One benchmark's scores over its runs, the newest marked.",
+ sparklineHint:
+ "One benchmark's scores over its runs, the newest marked; a single score is a lone point.",
timeline: "Trace timeline",
timelineHint:
"One Task's model segments and tool calls: thinking, reply, tool-call generation, approval wait and execution, each in its lane.",
diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.ts
index 1d58f5a0..89fd2fb5 100644
--- a/packages/ui-gallery/src/strings.ts
+++ b/packages/ui-gallery/src/strings.ts
@@ -423,7 +423,7 @@ export const zh = {
},
dialogs: {
title: "对话框",
- description: "模态对话框、确认框、分页对话框、抽屉、底部面板与图片放大。",
+ description: "模态对话框、确认框、分页对话框、抽屉、底部面板、图片放大与命令面板。",
},
tooltips: {
title: "悬停提示",
@@ -444,7 +444,7 @@ export const zh = {
charts: {
title: "图表",
description:
- "统计图的基础:所有图表共用的绘图原语、当前主题的图表令牌,以及建立在它们之上的每一种图表——环形图、趋势与用量柱、请求与成功率、活动与评分折线、轨迹时间线。",
+ "统计图的基础:所有图表共用的绘图原语、当前主题的图表令牌,以及建立在它们之上的每一种图表——环形图、环形仪表、图例、趋势与用量柱、请求与成功率、迷你折线、轨迹时间线。",
},
avatars: { title: "头像", description: "用户头像与智能体头像的各个尺寸,以及头像组。" },
files: { title: "文件", description: "文件树与只读文件浏览器。" },
@@ -659,6 +659,12 @@ export const zh = {
lightbox: "图片放大",
lightboxHint: "点击缩略图放大;按 Esc 或点击图片以外的地方关闭。",
lightboxAlt: "企鹅标志",
+ palette: "命令面板",
+ paletteAside: "输入以筛选;每个操作会打开本页的另一个对话框。",
+ openPalette: "打开命令面板",
+ palettePlaceholder: "输入以筛选命令…",
+ paletteEmpty: "没有匹配的命令",
+ paletteHint: "↑↓ 选择 · Enter 执行 · Esc 关闭",
},
tooltips: {
attribute: "data-tooltip 属性",
@@ -820,6 +826,24 @@ export const zh = {
} as Record<ChartToken, string>,
donut: "Token 环形图",
donutHint: "缓存读取、缓存写入与输出的构成,环的余量随接近上限变色。",
+ donutLabels: {
+ usage: "上下文占用",
+ cacheRead: "缓存读取",
+ cacheWrite: "缓存写入",
+ output: "输出",
+ },
+ ring: "环形仪表",
+ ringHint:
+ "一段弧对照预算,按预算状态着色(未超、将超、已超);未设预算只剩底环;输入框的 12 px 上下文圆环沿用所在处的墨色;多段弧表示各部分占比。",
+ ringSpend: (percent: number) => `支出占预算 ${percent}%`,
+ ringNoBudget: "未设预算",
+ ringShares: "各部分占比",
+ ringContext: "上下文圆环",
+ legend: "图例",
+ legendHint:
+ "图表下方的一行图例:指向某项时其余各项淡出;说明线形的一项不参与高亮。列表图例在标签后列出数值,点击可固定一行。",
+ legendHitRate: "缓存命中率",
+ legendParts: ["系统提示词", "工具定义", "对话消息", "工具结果"] as readonly string[],
trend: "成本趋势",
trendHint: "十四天的成本折线,悬停查看某一天。",
tokens: "Token 用量",
@@ -830,7 +854,7 @@ export const zh = {
activity: "活动折线",
activityHint: "智能体卡片上的十四天会话数曲线,只看相对起伏。",
sparkline: "评分折线",
- sparklineHint: "一个评估任务的历次得分,最新一次标出。",
+ sparklineHint: "一个评估任务的历次得分,最新一次标出;只有一次得分时是单独一个点。",
timeline: "轨迹时间线",
timelineHint:
"一次 Task 的模型分段与工具调用:思考、回复、工具调用、等待审批与执行,各占一道。",
diff --git a/packages/ui-gallery/test/library.test.ts b/packages/ui-gallery/test/library.test.ts
index 75c64b96..a78b5985 100644
--- a/packages/ui-gallery/test/library.test.ts
+++ b/packages/ui-gallery/test/library.test.ts
@@ -168,9 +168,10 @@ describe("the charts board", () => {
expect(board).toMatch(/<ChartTokenTable \/>/);
});
- it("shows each primitive on its own, from the app's chart module", () => {
+ it("shows each primitive on its own, from the package and nothing from the app", () => {
const stage = read("../src/library/boards/chart-primitives.tsx");
- expect(stage).toMatch(/from "\.\.\/\.\.\/\.\.\/\.\.\/web\/src\/components\/ui\/chart"/);
+ expect(stage).toMatch(/from "@prismshadow\/penguin-ui";/);
+ expect(stage).not.toMatch(/web\/src/);
for (const primitive of [
"ChartBar",
"ChartLine",
@@ -224,16 +225,20 @@ describe("the charts board", () => {
const board = read("../src/library/boards/charts.tsx");
for (const chart of [
"TokenDonut",
+ "Ring",
+ "Legend",
"TrendChart",
"TokenBarChart",
"TokenLegend",
"RequestsChart",
- "ActivitySparkline",
- "ScoreSparkline",
+ "Sparkline",
"TimelineChart",
]) {
expect(board).toMatch(new RegExp(`<${chart}[\\s/>]`));
}
+ // The package's charts come from the package; the app's domain charts from the app.
+ expect(board).toMatch(/from "@prismshadow\/penguin-ui";/);
+ expect(board).not.toMatch(/token-donut"|-sparkline"/);
expect(board).toMatch(
/from "\.\.\/\.\.\/\.\.\/\.\.\/web\/src\/features\/traces\/timeline-chart"/,
);
diff --git a/packages/web/src/features/usage/chart-svg.tsx b/packages/ui/src/components/charts/chart-frame/chart-frame.tsx
similarity index 96%
rename from packages/web/src/features/usage/chart-svg.tsx
rename to packages/ui/src/components/charts/chart-frame/chart-frame.tsx
index 147053ef..be07f0ee 100644
--- a/packages/web/src/features/usage/chart-svg.tsx
+++ b/packages/ui/src/components/charts/chart-frame/chart-frame.tsx
@@ -1,7 +1,6 @@
/**
- * Shared SVG skeleton for the daily trend charts (extracted from the
- * original TrendChart, reused by both the daily Token stacked bar and the
- * daily cost line): 4 horizontal grid lines + y-axis ticks, x-axis dates, a
+ * The plot frame every time-series chart draws in (the daily Token stacked bar, the cost line,
+ * the requests and score trends): 4 horizontal grid lines + y-axis ticks, x-axis dates, a
* hover vertical indicator line + a transparent hit area + a value bubble
* that follows the cursor at its lower-right (flipping to the other side of
* the pointer near the edges, see chart-geom's bubblePosition). "Data marks" (line / area / bars) are drawn by
@@ -28,6 +27,9 @@
* 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.
+ *
+ * The frame's own ink (the muted one) is what a mark painted with an empty `ink` draws in — the
+ * cost line, a single series with no identity to tell apart.
*/
import {
useEffect,
@@ -45,13 +47,7 @@ import {
sparseLabelIdx,
type ChartGeom,
} from "./chart-geom";
-import {
- ChartAxis,
- ChartAxisBreak,
- ChartCursor,
- ChartGrid,
- ChartHit,
-} from "../../components/ui/chart";
+import { ChartAxis, ChartAxisBreak, ChartCursor, ChartGrid, ChartHit } from "../marks/marks";
/** 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;
@@ -238,7 +234,7 @@ export function ChartFrame({
height={CHART_H}
// ui-chart: a theme may redraw the parts, which carry data-part — the grid, the axis
// labels and breaks here, the series, areas, bars and points in the caller's marks.
- className="ui-chart text-gray-600 dark:text-gray-400"
+ className="ui-chart text-fg-muted"
role="img"
onMouseLeave={() => {
onHover(null);
@@ -315,7 +311,7 @@ export function ChartFrame({
{bubble && hover !== null && dates[hover] && (
<div
ref={bubbleRef}
- className="pointer-events-none absolute rounded border border-gray-200 bg-white px-2 py-1 text-xs whitespace-nowrap shadow-sm dark:border-gray-700 dark:bg-gray-900"
+ className="pointer-events-none absolute rounded border border-line bg-overlay px-2 py-1 text-xs whitespace-nowrap shadow-sm"
// Mounted hidden at the origin; placeBubble moves it to the
// pointer's lower-right (flipping near the right/bottom edges, see
// bubblePosition) and reveals it. The declared style below never
diff --git a/packages/web/src/features/usage/chart-geom.ts b/packages/ui/src/components/charts/chart-frame/chart-geom.ts
similarity index 95%
rename from packages/web/src/features/usage/chart-geom.ts
rename to packages/ui/src/components/charts/chart-frame/chart-geom.ts
index 8f29cf08..5ee11220 100644
--- a/packages/web/src/features/usage/chart-geom.ts
+++ b/packages/ui/src/components/charts/chart-frame/chart-geom.ts
@@ -1,14 +1,14 @@
/**
- * Geometry math for the cost center charts: pure functions, no React / no
- * JSX, easy to unit test (see test/usage-charts.test.ts). The time-series
+ * Geometry math for the plot frame and the charts drawn in it: pure functions, no React / no
+ * JSX, easy to unit test (see test/chart-geom.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,
+ * stack, the cost line, the score trend) share one coordinate system — canvas width, padding,
* the x()/y() mapping, series points, x-axis label indices. Per-segment
* geometry (including per-segment hit bands) is produced by barSegments;
* there's also hover-bubble placement (pointer lower-right, flipping at the
* edges). How a bar fills its band and how a line runs between its points is
- * the theme's, and lives with the chart primitives (components/ui/chart/geom.ts).
- * See chart-svg.tsx for the render skeleton.
+ * the theme's, and lives with the chart primitives (../marks/geom.ts).
+ * See chart-frame.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 —
@@ -17,7 +17,7 @@
* ~495px, a 0.77 factor), while requirements like "at least 25px wide" must
* land on **real display pixels**. So the canvas width is supplied by the caller after measuring the container.
*/
-import { roundCoord as rnd } from "../../components/ui/chart/geom";
+import { roundCoord as rnd } from "../marks/geom";
/** Canvas height and padding (carried over from the original TrendChart constants; width is now measured from the container, see the file header). */
export const CHART_H = 200;
@@ -101,7 +101,6 @@ export interface LinePoint {
value: number;
}
-/** Straight-line path through the given points in order (`M` + `L`s), whatever slots lie between them; a single point yields a bare `M` that strokes nothing, so callers draw its dot instead. */
/** A sparse series' points in the plot's coordinates, rounded like segmentPath's. */
export function segmentPoints(
geom: ChartGeom,
@@ -110,6 +109,7 @@ export function segmentPoints(
return segment.map((p) => [rnd(geom.x(p.index)), rnd(geom.y(p.value))]);
}
+/** Straight-line path through the given points in order (`M` + `L`s), whatever slots lie between them; a single point 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))}`)
@@ -191,7 +191,7 @@ export function bubblePosition(
* chart's core requirement. Widening the bar (≥25px) doesn't help the
* vertical dimension either: a sub-pixel value stays sub-pixel, so this
* floor must be kept.
- * (The hit band's **width** is a separate matter: it spans the full cell horizontally, see TokenBarChart's hitLayer.)
+ * (The hit band's **width** is a separate matter: it spans the full cell horizontally, see the Web App's TokenBarChart hitLayer.)
*/
export const MIN_HIT_H = 8;
@@ -282,7 +282,7 @@ export function stackSegments(geom: ChartGeom, values: readonly number[]): Stack
});
}
-/** Stacking order: bottom-to-top output → cacheWrite → cacheRead (matches TOKEN_COLORS' shading, darkest at the bottom). */
+/** Stacking order: bottom-to-top output → cacheWrite → cacheRead (the Token kinds' own shades, darkest at the bottom). */
const STACK_ORDER: readonly TokenBucketKey[] = ["output", "cacheWrite", "cacheRead"];
/** A Token bar's three-segment stack (see stackSegments), keyed by bucket so the caller can look up color and label. */
diff --git a/packages/web/src/lib/chart-style.ts b/packages/ui/src/components/charts/chart-style.ts
similarity index 81%
rename from packages/web/src/lib/chart-style.ts
rename to packages/ui/src/components/charts/chart-style.ts
index c7d3ed63..6348e4a3 100644
--- a/packages/web/src/lib/chart-style.ts
+++ b/packages/ui/src/components/charts/chart-style.ts
@@ -4,13 +4,14 @@
* corner radius, a line's width and curve, a point's radius, the fill under a line — and the
* series palette those marks paint with.
*
- * Only the chart primitives (components/ui/chart) read it: every chart draws its marks through
- * them, so a token turns into geometry and colour in one place. Components never ask which
- * theme is active. It is read once per
- * theme change, not per render: one MutationObserver on <html> (the attributes the theme
- * provider and the boot script write — class for the mode, data-theme, data-accent, and the
- * root font size in `style`) drops the cached record, and every chart subscribed through
- * `useChartStyle` re-renders with the new one.
+ * Only the chart primitives (`marks/`) read it: every chart draws its marks through them, so a
+ * token turns into geometry and colour in one place. Components never ask which theme is active.
+ * It is read once per theme change, not per render: one MutationObserver on <html> — where the
+ * theme provider and the boot script write the mode class, the theme, the accent and the root
+ * font size — drops the cached record, and every chart subscribed through `useChartStyle`
+ * re-renders with the new one. Reading the tokens is what tells a real change from any other
+ * attribute write, so the observer watches every attribute and a read that finds nothing new
+ * hands back the same record.
*
* Slots are identities, fixed across themes: 1 violet, 2 amber, 3 sky, 4 rose, 5 emerald,
* 6 fuchsia, 7 and 8 spare — each theme picks its own shade of each. A chart's series take the
@@ -49,15 +50,17 @@ export interface ChartStyle {
}
/**
- * What the charts draw with when no theme has answered (a document without the theme sheet,
- * server rendering in tests): the default theme's values, which are today's charts.
+ * What the charts draw with before a theme has answered (server rendering in tests, a first
+ * read with no stylesheet): the default theme's geometry, and colours that name the tokens
+ * themselves, so a mark painted with one still takes the theme's value wherever the theme sheet
+ * is loaded.
*/
export const DEFAULT_CHART_STYLE: ChartStyle = {
- series: ["#8b5cf6", "#f59e0b", "#0ea5e9", "#f43f5e", "#10b981", "#d946ef", "#64748b", "#14b8a6"],
- ref: "#f59e0b",
- cacheRead: "#7dd3fc",
- cacheWrite: "#0ea5e9",
- output: "#0369a1",
+ series: [1, 2, 3, 4, 5, 6, 7, 8].map((slot) => `var(--ui-chart-${slot})`),
+ ref: "var(--ui-chart-ref)",
+ cacheRead: "var(--ui-chart-cache-read)",
+ cacheWrite: "var(--ui-chart-cache-write)",
+ output: "var(--ui-chart-output)",
barFill: 0.6,
barRadius: 0,
barStroke: 0,
@@ -82,8 +85,8 @@ function colourOf(raw: string, fallback: string): string {
/**
* The record, from a reader of custom properties (`getPropertyValue` on the root's computed
- * style). Every value falls back to the default theme's on its own, so a theme that has not
- * defined a token yet draws the way the app always has.
+ * style). Every value falls back to the default record's on its own, so a token a theme has not
+ * defined yet draws the way the default theme does.
*/
export function readChartStyle(read: (name: string) => string): ChartStyle {
const d = DEFAULT_CHART_STYLE;
@@ -159,10 +162,7 @@ function subscribe(listener: () => void): () => void {
cached = next;
for (const l of listeners) l();
});
- observer.observe(document.documentElement, {
- attributes: true,
- attributeFilter: ["class", "data-theme", "data-accent", "style"],
- });
+ observer.observe(document.documentElement, { attributes: true });
}
return () => {
listeners.delete(listener);
diff --git a/packages/ui/src/components/charts/legend/legend.tsx b/packages/ui/src/components/charts/legend/legend.tsx
new file mode 100644
index 00000000..56414614
--- /dev/null
+++ b/packages/ui/src/components/charts/legend/legend.tsx
@@ -0,0 +1,136 @@
+/**
+ * A chart's legend: each item a swatch painted the way its marks are, and its label.
+ *
+ * Two layouts:
+ * - `inline` (the default): a wrapping row of items under or beside a chart. While an item is
+ * singled out (`active`: pointed at here or on the chart's marks) the others fade — the
+ * site-wide highlight.
+ * - `list`: one item per row with its figures after the label (`value`: a count, a share), the
+ * label truncating first. The active row takes a wash, and a pinned one (`pinned`) a ring as
+ * well, so a pin does not read as a hover that happened to stay. A row may leave its swatch
+ * out (a ranking whose rows have no mark) and keeps the same box as the rows that have one.
+ *
+ * `onHover` makes the items answer the pointer; `onSelect` makes each a toggle button, pressed
+ * while pinned — the way a keyboard reaches a highlight, since a chart's marks are pointer-only.
+ * An item that explains a shape rather than naming a series (the dash that says "the lines are
+ * the success rate") passes `interactive: false` and never highlights or fades.
+ *
+ * A swatch is the chart's own (`ChartSwatch`); an item may draw a mark of its own in its place
+ * (`mark`: a state `Dot`, say). Every label is the caller's words.
+ */
+import type { ReactNode } from "react";
+import { ChartSwatch } from "../marks/marks";
+import type { ChartPaint, ChartSwatchShape } from "../marks/marks";
+
+export interface LegendItem {
+ /** Names the item to `active`, `pinned`, `onHover` and `onSelect`. */
+ key: string;
+ label: string;
+ /** The swatch's colour, as the item's marks are painted. No paint and no mark: no swatch. */
+ paint?: ChartPaint;
+ shape?: ChartSwatchShape;
+ /** Drawn in the swatch's place. */
+ mark?: ReactNode;
+ /** The tooltip over a truncated label, when it should say more than the label (a file's path). */
+ title?: string;
+ /** What a `list` row prints after its label. */
+ value?: ReactNode;
+ /** False for an item that explains a shape rather than naming a series. */
+ interactive?: boolean;
+}
+
+export type LegendLayout = "inline" | "list";
+
+export function Legend({
+ items,
+ layout = "inline",
+ label,
+ active = null,
+ pinned = null,
+ onHover,
+ onSelect,
+ mono = false,
+ className = "",
+}: {
+ items: readonly LegendItem[];
+ layout?: LegendLayout;
+ /** The list's accessible name, when no heading beside it names it already. */
+ label?: string;
+ /** The item singled out, by a pointer on the legend or on the chart's marks. */
+ active?: string | null;
+ /** The item a click pinned (with `onSelect`). */
+ pinned?: string | null;
+ onHover?: (key: string | null) => void;
+ onSelect?: (key: string) => void;
+ /** Set the labels in the data face (identifiers: a tool, a file, an agent id). */
+ mono?: boolean;
+ /** Layout only (a margin); the type and the inks are the legend's. */
+ className?: string;
+}) {
+ const list = layout === "list";
+ return (
+ <ul
+ aria-label={label}
+ className={`${list ? "flex flex-col" : "flex flex-wrap items-center gap-x-3 gap-y-1"} text-xs text-fg-muted ${className}`}
+ >
+ {items.map((item) => {
+ const interactive = item.interactive !== false;
+ const lit = active === item.key;
+ const swatch =
+ item.mark ??
+ (item.paint === undefined ? null : (
+ <ChartSwatch paint={item.paint} shape={item.shape ?? "square"} />
+ ));
+ const cells = (
+ <>
+ {swatch}
+ <span
+ data-tooltip={item.title ?? item.label}
+ data-tooltip-content={mono ? "code" : "text"}
+ className={`min-w-0 truncate ${list ? "flex-1" : ""} ${mono ? "font-mono" : ""}`}
+ >
+ {item.label}
+ </span>
+ {list ? item.value : null}
+ </>
+ );
+ // The box carries the highlight: a list row washes (and rings while pinned), an inline
+ // item fades while another one is singled out.
+ const box = list
+ ? `flex items-center gap-1.5 rounded px-1 py-0.5 transition-colors duration-150 ${
+ lit ? "bg-tone-neutral-bg" : ""
+ } ${pinned === item.key ? "inset-ring-1 inset-ring-fg-subtle" : ""}`
+ : `flex min-w-0 items-center gap-1.5 transition-opacity duration-150 ${
+ interactive && active !== null && !lit ? "opacity-30" : ""
+ }`;
+ const hover =
+ interactive && onHover !== undefined
+ ? { onMouseEnter: () => onHover(item.key), onMouseLeave: () => onHover(null) }
+ : {};
+ // A list row's box bleeds past the column by its own padding, so its label lines up
+ // with the text above and below it.
+ const bleed = list ? "-mx-1" : "";
+ if (interactive && onSelect !== undefined) {
+ return (
+ <li key={item.key} className={list ? bleed : "flex min-w-0"}>
+ <button
+ type="button"
+ aria-pressed={pinned === item.key}
+ onClick={() => onSelect(item.key)}
+ {...hover}
+ className={`cursor-pointer text-left ${list ? "w-full" : ""} ${box}`}
+ >
+ {cells}
+ </button>
+ </li>
+ );
+ }
+ return (
+ <li key={item.key} {...hover} className={`${bleed} ${box}`}>
+ {cells}
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/packages/web/src/components/ui/chart/geom.ts b/packages/ui/src/components/charts/marks/geom.ts
similarity index 92%
rename from packages/web/src/components/ui/chart/geom.ts
rename to packages/ui/src/components/charts/marks/geom.ts
index f5f189a3..341e76f6 100644
--- a/packages/web/src/components/ui/chart/geom.ts
+++ b/packages/ui/src/components/charts/marks/geom.ts
@@ -1,10 +1,10 @@
/**
* The geometry the chart primitives draw with — the part of a chart's layout a theme reaches
* through its tokens: how a line runs between its points (`--ui-chart-curve`) and how wide a
- * bar is in its band (`--ui-chart-bar-fill`). Chart-specific layout (a plot's padding and
- * scales, stacked segments, hit bands, the hover bubble) stays with the charts that use it.
+ * bar is in its band (`--ui-chart-bar-fill`). A plot's own layout (its padding and scales,
+ * stacked segments, hit bands, the hover bubble) is the plot frame's (`chart-frame/chart-geom.ts`).
*/
-import type { ChartCurve } from "../../../lib/chart-style";
+import type { ChartCurve } from "../chart-style";
/** Path coordinates keep 2 decimal places: the path string stays short and readable, and is easy to assert on in unit tests. */
export const roundCoord = (v: number): number => Math.round(v * 100) / 100;
diff --git a/packages/web/src/components/ui/chart/marks.tsx b/packages/ui/src/components/charts/marks/marks.tsx
similarity index 85%
rename from packages/web/src/components/ui/chart/marks.tsx
rename to packages/ui/src/components/charts/marks/marks.tsx
index 096c7735..2dc18412 100644
--- a/packages/web/src/components/ui/chart/marks.tsx
+++ b/packages/ui/src/components/charts/marks/marks.tsx
@@ -1,13 +1,13 @@
/**
- * The chart primitives: the one place a theme's chart tokens (lib/chart-style.ts) become marks.
+ * The chart primitives: the one place a theme's chart tokens (../chart-style.ts) become marks.
*
- * Every chart in the app — the cost center's requests, Token and cost charts, the context donut,
- * the score and activity sparklines — draws its bars, lines, areas, points, grid and axis
- * labels through these, and the Trace timeline its lanes through TimelineBar
- * (timeline-bar.tsx). A chart decides WHAT to draw — where a mark sits, which series it
- * belongs to, whether it is dimmed — and never HOW: the width of a bar in its band, its corner
- * radius, outline and fill opacity, a line's width and curve, a point's size, the fill under a
- * line and every colour come from the active theme here. A source guard (chart-marks.test.ts)
+ * Every chart — the cost center's requests, Token and cost charts, the token donut, the
+ * sparklines, the ring gauges — draws its bars, lines, areas, points, arcs, grid and axis labels
+ * through these, and the Trace timeline its lanes through TimelineBar (timeline-bar.tsx). A chart
+ * decides WHAT to draw — where a mark sits, which series it belongs to, whether it is dimmed —
+ * and never HOW: the width of a bar in its band, its corner radius, outline and fill opacity, a
+ * line's width and curve, a point's size, the fill under a line and every colour come from the
+ * active theme here. A source guard (chart-marks.test.ts, in this package and in the Web App)
* holds the charts to that.
*
* Each primitive writes `data-part` (and `data-series` where a series index exists), so a theme
@@ -20,8 +20,8 @@
* series, the cost line, a near-limit ring).
*/
import type { CSSProperties, MouseEventHandler, ReactNode } from "react";
-import { seriesStroke, useChartStyle } from "../../../lib/chart-style";
-import type { ChartStyle } from "../../../lib/chart-style";
+import { seriesStroke, useChartStyle } from "../chart-style";
+import type { ChartStyle } from "../chart-style";
import { curvePath, fitBarWidth } from "./geom";
export type ChartPaint =
@@ -235,9 +235,10 @@ export function ChartPoint({
}
/**
- * An arc of a ring (the context donut): `length` px of the circumference from `offset`, clockwise
- * from twelve o'clock, `width` thick. A series arc takes its paint; the ring's empty track is a
- * `grid` part painted with an ink at `trackOpacity`.
+ * An arc of a ring (the token donut, a ring gauge): `length` px of the circumference from
+ * `offset`, clockwise from twelve o'clock, `width` thick. A series arc takes its paint; the
+ * ring's empty track is a `grid` part painted with an ink at `trackOpacity`. `round` gives the
+ * arc round caps (a gauge's single arc that does not close the ring).
*/
export function ChartArc({
cx,
@@ -249,6 +250,7 @@ export function ChartArc({
offset = 0,
track = false,
trackOpacity,
+ round = false,
}: {
cx: number;
cy: number;
@@ -260,6 +262,7 @@ export function ChartArc({
offset?: number;
track?: boolean;
trackOpacity?: number;
+ round?: boolean;
}) {
const chart = useChartStyle();
const { color, className: ink } = resolvePaint(chart, paint);
@@ -275,6 +278,7 @@ export function ChartArc({
stroke="currentColor"
strokeWidth={width}
{...(trackOpacity !== undefined ? { strokeOpacity: trackOpacity } : {})}
+ {...(round ? { strokeLinecap: "round" as const } : {})}
{...(length !== undefined
? {
strokeDasharray: `${length} ${circumference}`,
@@ -288,7 +292,7 @@ export function ChartArc({
);
}
-/** A horizontal grid line across the plot, in the chart's recessive gray. */
+/** A horizontal grid line across the plot, in the theme's grid ink. */
export function ChartGrid({ x1, x2, y }: { x1: number; x2: number; y: number }) {
return (
<line
@@ -297,7 +301,7 @@ export function ChartGrid({ x1, x2, y }: { x1: number; x2: number; y: number })
x2={x2}
y1={y}
y2={y}
- className="stroke-gray-200 dark:stroke-gray-800"
+ className="stroke-chart-grid"
strokeWidth={1}
/>
);
@@ -305,16 +309,7 @@ export function ChartGrid({ x1, x2, y }: { x1: number; x2: number; y: number })
/** The vertical line under the pointer on a line chart: chrome, not data, so it has no part. */
export function ChartCursor({ x, y1, y2 }: { x: number; y1: number; y2: number }) {
- return (
- <line
- x1={x}
- x2={x}
- y1={y1}
- y2={y2}
- className="stroke-gray-300 dark:stroke-gray-700"
- strokeWidth={1}
- />
- );
+ return <line x1={x} x2={x} y1={y1} y2={y2} className="stroke-line-emphasis" strokeWidth={1} />;
}
/** An axis label (a tick value or a date), in the axis ink at the chart's small size. */
@@ -330,14 +325,7 @@ export function ChartAxis({
children: ReactNode;
}) {
return (
- <text
- data-part="axis"
- x={x}
- y={y}
- textAnchor={anchor}
- className="fill-gray-400 dark:fill-gray-500"
- fontSize={9}
- >
+ <text data-part="axis" x={x} y={y} textAnchor={anchor} className="fill-chart-axis" fontSize={9}>
{children}
</text>
);
@@ -349,11 +337,7 @@ export function ChartAxis({
*/
export function ChartAxisBreak({ x, y }: { x: number; y: number }) {
return (
- <g
- data-part="axis"
- className="pointer-events-none stroke-gray-400 dark:stroke-gray-500"
- strokeWidth={1}
- >
+ <g data-part="axis" className="pointer-events-none stroke-chart-axis" strokeWidth={1}>
{[-2, 2].map((dx) => {
const cx = x + dx / 2;
return <line key={dx} x1={cx - 2} y1={y + 3} x2={cx + 2} y2={y - 3} />;
@@ -427,6 +411,12 @@ export function ChartBarHit({
);
}
+/**
+ * A swatch's shape: square / block a series (sharper or softer corners), chip a wider bar
+ * swatch, dash / tick a line, long or short.
+ */
+export type ChartSwatchShape = "square" | "block" | "dash" | "tick" | "chip";
+
/** A legend or bubble swatch in a paint: a square for a bar series, a dash for a line. */
export function ChartSwatch({
paint,
@@ -434,8 +424,7 @@ export function ChartSwatch({
className = "",
}: {
paint: ChartPaint;
- /** square / block: a series (sharper or softer corners); chip: a wider bar swatch; dash / tick: a line, long or short. */
- shape?: "square" | "block" | "dash" | "tick" | "chip";
+ shape?: ChartSwatchShape;
className?: string;
}) {
const chart = useChartStyle();
diff --git a/packages/web/src/components/ui/chart/timeline-bar.tsx b/packages/ui/src/components/charts/marks/timeline-bar.tsx
similarity index 88%
rename from packages/web/src/components/ui/chart/timeline-bar.tsx
rename to packages/ui/src/components/charts/marks/timeline-bar.tsx
index 78cd2c74..ae9d9dac 100644
--- a/packages/web/src/components/ui/chart/timeline-bar.tsx
+++ b/packages/ui/src/components/charts/marks/timeline-bar.tsx
@@ -6,10 +6,12 @@
* opacity (applied to the fill alone, so a dimmed bar's own opacity class still works).
*
* Everything else a lane needs from a bar — the pointer handlers, the jump on click, the
- * accessible name of a data mark, a ring for a failure, a pulse while it runs — passes through.
+ * accessible name of a data mark, a ring for a failure, a fade while another mark is singled
+ * out — passes through. The bar itself holds still: a bar that is still open is marked by the
+ * chart with a live state dot at its end, not by moving the bar.
*/
import type { CSSProperties, HTMLAttributes } from "react";
-import { useChartStyle } from "../../../lib/chart-style";
+import { useChartStyle } from "../chart-style";
import { resolvePaint } from "./marks";
import type { ChartPaint } from "./marks";
diff --git a/packages/ui/src/components/charts/ring/ring.tsx b/packages/ui/src/components/charts/ring/ring.tsx
new file mode 100644
index 00000000..2964f7a8
--- /dev/null
+++ b/packages/ui/src/components/charts/ring/ring.tsx
@@ -0,0 +1,133 @@
+/**
+ * A ring gauge: arcs clockwise from twelve o'clock over a track, each arc its segment's share of
+ * `max` — one arc for a single reading (spend against a budget, a context's occupancy), several
+ * for a composition. When the segments add up to more than `max` the ring fills and every arc
+ * keeps its share of the total, so no arc wraps past a full circle. A segment at zero draws
+ * nothing, so an empty reading is the track alone.
+ *
+ * The ring's ink is its tone's, or, without one, the ink it sits in (a caller that names the
+ * state on the element around it). An arc paints in that ink unless its segment names a paint
+ * of its own (a Token kind, a series slot). The track is the chart grid's line, or — with
+ * `trackOpacity` — the ring's own ink faded, so a ring that changes colour with its state keeps
+ * its track in step. A lone arc that does not close the ring has round caps.
+ *
+ * With a `label` the ring is an image with that name, which is also its tooltip: it draws no
+ * numbers, so the name carries them. Without one it is decoration inside a control that is
+ * named already.
+ */
+import { ChartArc } from "../marks/marks";
+import type { ChartPaint } from "../marks/marks";
+import type { ToneName } from "../../../tokens";
+
+export interface RingSegment {
+ value: number;
+ /** The arc's colour, as a chart mark is painted; the ring's own ink when omitted. */
+ paint?: ChartPaint;
+}
+
+const TONE_INK: Record<ToneName, string> = {
+ success: "text-tone-success-fg",
+ attention: "text-tone-attention-fg",
+ danger: "text-tone-danger-fg",
+ done: "text-tone-done-fg",
+ neutral: "text-tone-neutral-fg",
+ info: "text-tone-info-fg",
+};
+
+const OWN_INK: ChartPaint = { ink: "" };
+const GRID_INK: ChartPaint = { ink: "text-chart-grid" };
+
+/** A segment's value as the ring counts it: nothing for a negative or unmeasured one. */
+const countOf = (segment: RingSegment) =>
+ Number.isFinite(segment.value) && segment.value > 0 ? segment.value : 0;
+
+/** Where each drawn arc starts and how long it runs, in px of the circumference. */
+export function ringArcs(
+ segments: readonly RingSegment[],
+ max: number,
+ circumference: number,
+): { index: number; length: number; offset: number }[] {
+ const total = segments.reduce((sum, s) => sum + countOf(s), 0);
+ const denom = Math.max(Number.isFinite(max) ? max : 0, total);
+ if (denom <= 0) return [];
+ let acc = 0;
+ return segments.flatMap((segment, index) => {
+ const value = countOf(segment);
+ if (value === 0) return [];
+ const arc = {
+ index,
+ length: (value / denom) * circumference,
+ offset: -(acc / denom) * circumference,
+ };
+ acc += value;
+ return [arc];
+ });
+}
+
+export function Ring({
+ segments,
+ max,
+ size = 44,
+ width = Math.max(2, Math.round(size * 0.12)),
+ tone,
+ trackOpacity,
+ label,
+ className = "",
+}: {
+ segments: readonly RingSegment[];
+ /** The value a full ring stands for. */
+ max: number;
+ /** Outer diameter, px. */
+ size?: number;
+ /** Stroke width, px. */
+ width?: number;
+ /** The ring's ink; the surrounding ink when omitted. */
+ tone?: ToneName;
+ /** Draw the track in the ring's own ink at this opacity instead of the grid's line. */
+ trackOpacity?: number;
+ /** The accessible name and tooltip; the ring is hidden from assistive technology without one. */
+ label?: string;
+ /** Layout only (a margin, an alignment); the colour is the tone's. */
+ className?: string;
+}) {
+ const center = size / 2;
+ const r = (size - width) / 2;
+ const circumference = 2 * Math.PI * r;
+ const arcs = ringArcs(segments, max, circumference);
+ const lone = arcs.length === 1 && arcs[0]!.length < circumference;
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox={`0 0 ${size} ${size}`}
+ {...(label === undefined
+ ? { "aria-hidden": true }
+ : { role: "img" as const, "aria-label": label, "data-tooltip": label })}
+ // ui-chart: a theme may redraw the parts (the track as the grid, each arc a series).
+ className={`ui-chart block shrink-0 ${tone === undefined ? "" : TONE_INK[tone]} ${className}`}
+ >
+ <ChartArc
+ cx={center}
+ cy={center}
+ r={r}
+ width={width}
+ paint={trackOpacity === undefined ? GRID_INK : OWN_INK}
+ track
+ {...(trackOpacity !== undefined ? { trackOpacity } : {})}
+ />
+ {arcs.map((arc) => (
+ <ChartArc
+ key={arc.index}
+ cx={center}
+ cy={center}
+ r={r}
+ width={width}
+ paint={segments[arc.index]!.paint ?? OWN_INK}
+ length={arc.length}
+ offset={arc.offset}
+ round={lone}
+ />
+ ))}
+ </svg>
+ );
+}
diff --git a/packages/ui/src/components/charts/sparkline/sparkline.tsx b/packages/ui/src/components/charts/sparkline/sparkline.tsx
new file mode 100644
index 00000000..09f22593
--- /dev/null
+++ b/packages/ui/src/components/charts/sparkline/sparkline.tsx
@@ -0,0 +1,118 @@
+/**
+ * A sparkline: a series as one small line, with no axes and no ticks — the number beside it is
+ * the value, the line only its ups and downs. Drawn through the chart primitives at a
+ * sparkline's scale (three quarters of the theme's line width, four fifths of its point radius),
+ * so it takes the theme's curve, line width and area fill; its colour is its own ink, the muted
+ * one unless a tone is given.
+ *
+ * Two scales, for the two things a sparkline is asked:
+ * - `zero` (the default): from zero to the largest value (at least 1), so the line shows how
+ * much against nothing — a count of sessions a day. Fewer than two values draw a flat baseline
+ * at the bottom.
+ * - `range`: the observed range, at least `minSpan` wide and centred on the values, so a series
+ * that moved from 60 to 90 fills the box and a flat one draws a level line through its middle
+ * instead of collapsing onto an edge — a score. A single value is a lone point.
+ *
+ * `area` fills under the line (a little stronger than a full chart's fill); `marker` marks the
+ * newest point.
+ */
+import { ChartArea, ChartLine, ChartPoint } from "../marks/marks";
+import type { ChartPaint } from "../marks/marks";
+import type { ToneName } from "../../../tokens";
+
+/** The sparkline's paint: its own ink (a single series, no identity to tell apart). */
+const INK: ChartPaint = { ink: "" };
+/** A sparkline's scale of the theme's line width and point radius. */
+const LINE_SCALE = 0.75;
+const POINT_SCALE = 0.8;
+/** The fill under the line, a little stronger than a full chart's. */
+const AREA_STRENGTH = 1.2;
+/** Room around the line for its stroke, and for the marked point's dot when there is one. */
+const PAD = 2;
+const MARKER_PAD = 2.5;
+
+const TONE_INK: Record<ToneName, string> = {
+ success: "text-tone-success-fg",
+ attention: "text-tone-attention-fg",
+ danger: "text-tone-danger-fg",
+ done: "text-tone-done-fg",
+ neutral: "text-tone-neutral-fg",
+ info: "text-tone-info-fg",
+};
+
+export type SparklineScale = "zero" | "range";
+
+/** The low end of the scale and its span, for `values` on `scale`. */
+export function sparklineDomain(
+ values: readonly number[],
+ scale: SparklineScale,
+ minSpan: number,
+): { low: number; span: number } {
+ if (scale === "zero") return { low: 0, span: Math.max(1, ...values) };
+ if (values.length === 0) return { low: 0, span: minSpan };
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const span = Math.max(max - min, minSpan);
+ return { low: (min + max) / 2 - span / 2, span };
+}
+
+export function Sparkline({
+ values,
+ label,
+ scale = "zero",
+ minSpan = 5,
+ area = false,
+ marker = false,
+ width = 72,
+ height = 22,
+ tone,
+ className = "",
+}: {
+ values: readonly number[];
+ /** The accessible name and tooltip: what the line is of, since it draws no numbers. */
+ label: string;
+ scale?: SparklineScale;
+ /** The smallest span a `range` scale stands for: below it, differences are noise at this size. */
+ minSpan?: number;
+ area?: boolean;
+ marker?: boolean;
+ width?: number;
+ height?: number;
+ /** The line's ink; the muted ink when omitted. */
+ tone?: ToneName;
+ /** Layout only (a size, a margin); the colour is the tone's. */
+ className?: string;
+}) {
+ const pad = marker ? MARKER_PAD : PAD;
+ const { low, span } = sparklineDomain(values, scale, minSpan);
+ const step = values.length > 1 ? (width - 2 * pad) / (values.length - 1) : 0;
+ const points = values.map(
+ (v, i) => [pad + i * step, height - pad - ((v - low) / span) * (height - 2 * pad)] as const,
+ );
+ const baseline = [
+ [pad, height - pad],
+ [width - pad, height - pad],
+ ] as const;
+ const line = points.length > 1 ? points : scale === "zero" ? baseline : null;
+ const last = points[points.length - 1];
+ return (
+ <svg
+ width={width}
+ height={height}
+ viewBox={`0 0 ${width} ${height}`}
+ role="img"
+ aria-label={label}
+ data-tooltip={label}
+ // ui-chart: a theme may redraw the line, the fill under it and the newest point its own way.
+ className={`ui-chart ${tone === undefined ? "text-fg-muted" : TONE_INK[tone]} ${className}`}
+ >
+ {area && points.length > 1 && (
+ <ChartArea points={points} baseY={height - pad} paint={INK} strength={AREA_STRENGTH} />
+ )}
+ {line !== null && <ChartLine points={line} paint={INK} scale={LINE_SCALE} round />}
+ {marker && last !== undefined && (
+ <ChartPoint cx={last[0]} cy={last[1]} paint={INK} scale={POINT_SCALE} />
+ )}
+ </svg>
+ );
+}
diff --git a/packages/web/src/components/ui/token-donut.tsx b/packages/ui/src/components/charts/token-donut/token-donut.tsx
similarity index 58%
rename from packages/web/src/components/ui/token-donut.tsx
rename to packages/ui/src/components/charts/token-donut/token-donut.tsx
index 6b1f1769..19cb964d 100644
--- a/packages/web/src/components/ui/token-donut.tsx
+++ b/packages/ui/src/components/charts/token-donut/token-donut.tsx
@@ -3,22 +3,29 @@
* (Task) card on the Trace page — shows both **usage ratio** (sum of arc lengths
* / limit) and **segment composition** (three segments). Draws, clockwise from
* the top (12 o'clock), the cacheRead, cacheWrite, and output segments in order,
- * with the remainder left as an empty ring; the limit `max` = the model's context
- * window (defaults to 128000 via resolveContextWindow when the caller doesn't
- * supply one). If all three buckets are 0, only the base ring is drawn; when
- * usage exceeds the limit, the ring is filled proportionally to usage and
- * colored by threshold (>80% amber / >95% red) to signal approaching/exceeding
- * the limit; exact values show in the shared tooltip on hover.
- * Segments use the theme's Token-kind colours (useChartStyle); the base
- * ring uses a currentColor gray.
- * The context usage under the chat page's input box is a **single-color,
- * single-value** ring (total only), custom-drawn in context-gauge — it doesn't
- * use this component.
+ * with the remainder left as an empty ring; the limit `max` is the model's context
+ * window, which the caller resolves. If all three buckets are 0, only the base ring
+ * is drawn; when usage exceeds the limit, the ring is filled proportionally to usage
+ * and the remainder is coloured by threshold (>80% attention / >95% danger) to signal
+ * approaching/exceeding the limit; exact values show in the shared tooltip on hover.
+ * Segments use the theme's Token-kind colours; the base ring takes the ring's own ink.
+ *
+ * The words are the caller's: `labels` names the usage and each Token kind, and the
+ * figures come from `format` (the app's own token abbreviation).
+ *
+ * The composer's context usage is a single-colour, single-value ring (total only) — a
+ * `Ring`, not this component.
*/
-import { ChartArc } from "./chart";
-import { humanizeTokens } from "../../lib/format";
-import { S } from "../../lib/strings";
-import { toneInk } from "../../lib/tone";
+import { ChartArc } from "../marks/marks";
+
+/** The words the donut's accessible name and tooltip are built from. */
+export interface TokenDonutLabels {
+ /** What the ratio is ("Context usage"). */
+ usage: string;
+ cacheRead: string;
+ cacheWrite: string;
+ output: string;
+}
export function TokenDonut({
cacheRead,
@@ -26,6 +33,8 @@ export function TokenDonut({
output,
max,
size = 44,
+ labels,
+ format = String,
}: {
cacheRead: number;
cacheWrite: number;
@@ -34,6 +43,9 @@ export function TokenDonut({
max: number;
/** Outer diameter in pixels. */
size?: number;
+ labels: TokenDonutLabels;
+ /** How a Token count is printed in the accessible name and tooltip. */
+ format?: (tokens: number) => string;
}) {
const total = cacheRead + cacheWrite + output;
const strokeWidth = Math.max(2, Math.round(size * 0.16));
@@ -45,31 +57,21 @@ export function TokenDonut({
// completely (arcs never wrap past a full circle).
const denom = Math.max(max, total, 1);
const pct = max > 0 ? total / max : 0;
- // The base ring's (i.e. "empty ring / remainder") color shifts to amber / red as usage approaches the limit, as a warning.
+ // The base ring's (i.e. "empty ring / remainder") colour shifts to attention / danger as usage approaches the limit, as a warning.
const ringTone =
pct > 0.95
- ? toneInk.danger
+ ? "text-tone-danger-fg"
: pct > 0.8
- ? toneInk.attention
- : "text-gray-300 dark:text-gray-700";
+ ? "text-tone-attention-fg"
+ : "text-line-emphasis";
const segs = [
- {
- key: "cacheRead",
- value: cacheRead,
- role: "cacheRead" as const,
- label: S.usage.colCacheRead,
- },
- {
- key: "cacheWrite",
- value: cacheWrite,
- role: "cacheWrite" as const,
- label: S.usage.colCacheWrite,
- },
- { key: "output", value: output, role: "output" as const, label: S.usage.colOutput },
+ { key: "cacheRead", value: cacheRead, role: "cacheRead" as const, label: labels.cacheRead },
+ { key: "cacheWrite", value: cacheWrite, role: "cacheWrite" as const, label: labels.cacheWrite },
+ { key: "output", value: output, role: "output" as const, label: labels.output },
];
const title =
- `${S.chat.contextUsage} ${humanizeTokens(total)}/${humanizeTokens(max)}` +
- segs.map((s) => ` · ${s.label} ${humanizeTokens(s.value)}`).join("");
+ `${labels.usage} ${format(total)}/${format(max)}` +
+ segs.map((s) => ` · ${s.label} ${format(s.value)}`).join("");
let acc = 0;
return (
<svg
diff --git a/packages/ui/src/components/overlays/command-palette/command-palette.tsx b/packages/ui/src/components/overlays/command-palette/command-palette.tsx
new file mode 100644
index 00000000..36dd4103
--- /dev/null
+++ b/packages/ui/src/components/overlays/command-palette/command-palette.tsx
@@ -0,0 +1,182 @@
+/**
+ * The command palette, VS Code-style: a top-centred search box filtering a list of actions; Enter
+ * (or a click) runs the selected one. The palette is mechanism only — the caller decides which
+ * actions exist and what opens it (the app binds a global shortcut), so a new capability registers
+ * an action instead of claiming another shortcut.
+ *
+ * Keyboard model: ArrowUp/ArrowDown move the selection (wrapping) and Enter runs it. Escape closes
+ * the palette only while it is the topmost Escape-consuming layer (the shared stack Modal and
+ * Dropdown use), so a dialog an action opened above it gets its Escape first; Tab stays inside the
+ * panel, and closing hands focus back to where it was. Every opening starts over: an empty query
+ * with the first action selected.
+ *
+ * Rendered via portal to body, like Modal, so no transformed or clipping ancestor captures the
+ * fixed overlay.
+ */
+import { useRef, useState } from "react";
+import type { KeyboardEvent, ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { useDialogLayer } from "../esc-layers/esc-layers";
+
+export interface PaletteAction {
+ id: string;
+ label: string;
+ /** Searchable words beyond the label (an English alias under a Chinese label, say). */
+ keywords?: readonly string[];
+ run: () => void;
+}
+
+/**
+ * Palette filtering, VS Code-style-lite: every whitespace-separated query token must appear
+ * (case-insensitive substring) in the label or a keyword, in any order. Predictable over fuzzy for
+ * a handful of actions; an empty query lists everything in registration order.
+ */
+export function filterPaletteActions<A extends { label: string; keywords?: readonly string[] }>(
+ actions: readonly A[],
+ query: string,
+): A[] {
+ const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);
+ if (tokens.length === 0) return [...actions];
+ return actions.filter((a) => {
+ const hay = [a.label, ...(a.keywords ?? [])].join(" ").toLowerCase();
+ return tokens.every((t) => hay.includes(t));
+ });
+}
+
+export interface CommandPaletteProps {
+ open: boolean;
+ onClose: () => void;
+ actions: readonly PaletteAction[];
+ /** Names the dialog for assistive technology; the palette shows no title. */
+ title: string;
+ /** The search box's placeholder, which is also its accessible name. */
+ placeholder: string;
+ /** Shown in place of the list when the query matches nothing. */
+ emptyText: string;
+ /** A line pinned under the list: the keys that drive the palette. */
+ hint?: ReactNode;
+}
+
+export function CommandPalette({
+ open,
+ onClose,
+ actions,
+ title,
+ placeholder,
+ emptyText,
+ hint,
+}: CommandPaletteProps) {
+ const panelRef = useRef<HTMLDivElement>(null);
+ const { onKeyDown: onPanelKeyDown } = useDialogLayer(open, panelRef, onClose);
+
+ if (!open) return null;
+
+ const run = (action: PaletteAction) => {
+ // Close first: an action may open its own overlay and expects the palette gone.
+ onClose();
+ action.run();
+ };
+
+ return createPortal(
+ <div
+ // ui-scrim: the overlay is the dimmed layer, with the palette inside it. z-50 like Modal's
+ // overlay, so a portaled menu or tooltip (z-[60]) opened from inside still paints above it.
+ className="ui-scrim anim-fade fixed inset-0 z-50 flex justify-center bg-[var(--ui-overlay-backdrop)] px-4 pt-[10vh]"
+ onMouseDown={(e) => {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ >
+ <div
+ ref={panelRef}
+ role="dialog"
+ aria-modal="true"
+ aria-label={title}
+ tabIndex={-1}
+ onKeyDown={onPanelKeyDown}
+ className="anim-pop h-fit w-full max-w-md overflow-hidden rounded-lg border border-line bg-surface shadow-xl"
+ >
+ {/* Mounted per opening, so the query and the selection start over each time. */}
+ <PaletteSearch
+ actions={actions}
+ placeholder={placeholder}
+ emptyText={emptyText}
+ onRun={run}
+ />
+ {hint !== undefined && (
+ <div className="border-t border-line px-4 py-2 text-right text-xs text-fg-subtle">
+ {hint}
+ </div>
+ )}
+ </div>
+ </div>,
+ document.body,
+ );
+}
+
+/** The search box and the filtered list under it, with the keyboard selection. */
+function PaletteSearch({
+ actions,
+ placeholder,
+ emptyText,
+ onRun,
+}: {
+ actions: readonly PaletteAction[];
+ placeholder: string;
+ emptyText: string;
+ onRun: (action: PaletteAction) => void;
+}) {
+ const [query, setQuery] = useState("");
+ const [selected, setSelected] = useState(0);
+ const filtered = filterPaletteActions(actions, query);
+ const sel = Math.min(selected, Math.max(filtered.length - 1, 0));
+
+ const onInputKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ if (filtered.length === 0) return;
+ const delta = e.key === "ArrowDown" ? 1 : -1;
+ setSelected((sel + delta + filtered.length) % filtered.length);
+ } else if (e.key === "Enter") {
+ e.preventDefault();
+ const action = filtered[sel];
+ if (action !== undefined) onRun(action);
+ }
+ };
+
+ return (
+ <>
+ <input
+ autoFocus
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setSelected(0);
+ }}
+ onKeyDown={onInputKeyDown}
+ placeholder={placeholder}
+ aria-label={placeholder}
+ className="w-full border-b border-line bg-transparent px-4 py-3 text-sm outline-none placeholder:text-fg-subtle"
+ />
+ {filtered.length === 0 ? (
+ <p className="px-4 py-3 text-sm text-fg-muted">{emptyText}</p>
+ ) : (
+ <ul className="max-h-[40vh] overflow-y-auto py-1" role="listbox">
+ {filtered.map((action, i) => (
+ <li key={action.id} role="option" aria-selected={i === sel}>
+ <button
+ type="button"
+ className={`w-full px-4 py-2 text-left text-sm text-fg ${
+ i === sel ? "bg-surface-muted" : ""
+ }`}
+ onMouseEnter={() => setSelected(i)}
+ onClick={() => onRun(action)}
+ >
+ {action.label}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </>
+ );
+}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index f4008f0f..2324bf42 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -139,3 +139,20 @@ export * from "./components/data/table/table";
// W4-C — navigation: the nav list and its rows, the rail of a paged dialog or a settings page.
export * from "./components/navigation/nav-list/nav-list";
+
+// W8-A — charts: the theme's chart style, the primitives every mark is drawn through, the plot
+// frame with its geometry, and the charts built on them — the token donut, the sparkline, the
+// ring gauge and the legend.
+export * from "./components/charts/chart-style";
+export * from "./components/charts/marks/geom";
+export * from "./components/charts/marks/marks";
+export * from "./components/charts/marks/timeline-bar";
+export * from "./components/charts/chart-frame/chart-geom";
+export * from "./components/charts/chart-frame/chart-frame";
+export * from "./components/charts/token-donut/token-donut";
+export * from "./components/charts/sparkline/sparkline";
+export * from "./components/charts/ring/ring";
+export * from "./components/charts/legend/legend";
+
+// W8-B — the command palette: the search box over the caller's actions, and its filter.
+export * from "./components/overlays/command-palette/command-palette";
diff --git a/packages/ui/test/chart-frame.test.ts b/packages/ui/test/chart-frame.test.ts
new file mode 100644
index 00000000..d2cc8ffc
--- /dev/null
+++ b/packages/ui/test/chart-frame.test.ts
@@ -0,0 +1,52 @@
+/**
+ * The plot frame (src/components/charts/chart-frame): the `ui-chart` root in the muted ink, its
+ * grid and axis labels as named parts with the caller's formatting, the caller's marks between
+ * them, and no bubble until a point is hovered. The frame's geometry is chart-geom.test.ts.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import { ChartFrame } from "../src/components/charts/chart-frame/chart-frame";
+import { makeGeom } from "../src/components/charts/chart-frame/chart-geom";
+import { classTokens, renderStatic } from "../src/testing";
+
+type Props = Parameters<typeof ChartFrame>[0];
+
+const frame = (props: Partial<Props> = {}) =>
+ renderStatic(
+ createElement(ChartFrame, {
+ geom: makeGeom(3, 100, 640),
+ fmtY: (v: number) => `$${v}`,
+ dates: ["2026-09-01", "2026-09-02", "2026-09-03"],
+ hover: null,
+ onHover: () => {},
+ ...props,
+ }),
+ );
+
+describe("ChartFrame", () => {
+ it("draws an image root carrying the chart hook, in the muted ink", () => {
+ const html = frame();
+ expect(html).toContain('role="img"');
+ expect(classTokens(html)).toEqual(expect.arrayContaining(["ui-chart", "text-fg-muted"]));
+ expect(html).not.toMatch(/gray-|dark:/);
+ });
+
+ it("names its grid and axis parts, and prints the caller's tick and date formats", () => {
+ const html = frame({ fmtX: (d: string) => d.slice(8) });
+ expect(html.match(/data-part="grid"/g)).toHaveLength(5);
+ expect(html).toContain(">$100<");
+ expect(html).toContain(">$0<");
+ expect(html).toContain(">01<");
+ expect(html).toContain(">03<");
+ });
+
+ it("draws the caller's marks, and a bubble only while a point is hovered", () => {
+ const mark = createElement("g", { id: "marks" });
+ expect(frame({ children: mark })).toContain('<g id="marks"></g>');
+ const bubble = (i: number) => `day ${i}`;
+ expect(frame({ bubble })).not.toContain("day ");
+ const hovered = frame({ bubble, hover: 1 });
+ expect(hovered).toContain("day 1");
+ expect(classTokens(hovered)).toEqual(expect.arrayContaining(["border-line", "bg-overlay"]));
+ });
+});
diff --git a/packages/web/test/usage-charts.test.ts b/packages/ui/test/chart-geom.test.ts
similarity index 94%
rename from packages/web/test/usage-charts.test.ts
rename to packages/ui/test/chart-geom.test.ts
index dbcbdc1a..6453cc99 100644
--- a/packages/web/test/usage-charts.test.ts
+++ b/packages/ui/test/chart-geom.test.ts
@@ -1,12 +1,10 @@
/**
- * Cost Center chart pure-function unit tests (chart-geom.ts, and the bar width and path the
- * chart primitives take from components/ui/chart/geom.ts): coordinate mapping, SVG path
- * assembly (straight paths through the points given in the default theme), 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).
+ * The plot frame's geometry (charts/chart-frame/chart-geom.ts), and the bar width and path the
+ * chart primitives take from marks/geom.ts: coordinate mapping, SVG path assembly (straight
+ * paths through the points given in the default theme), 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). 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
@@ -29,8 +27,8 @@ import {
PAD_L,
PAD_R,
PAD_R_AXIS,
-} from "../src/features/usage/chart-geom";
-import { BAR_W, curvePath, fitBarWidth } from "../src/components/ui/chart/geom";
+} from "../src/components/charts/chart-frame/chart-geom";
+import { BAR_W, curvePath, fitBarWidth } from "../src/components/charts/marks/geom";
describe("makeGeom", () => {
it("x takes each slot's midpoint; y runs top-down with max as full scale", () => {
diff --git a/packages/ui/test/chart-marks.test.ts b/packages/ui/test/chart-marks.test.ts
new file mode 100644
index 00000000..35381953
--- /dev/null
+++ b/packages/ui/test/chart-marks.test.ts
@@ -0,0 +1,184 @@
+/**
+ * The chart primitives (src/components/charts/marks): what each draws in the default theme — the
+ * record the server snapshot of useChartStyle hands out — the chart inks they spell as tokens,
+ * and a guard that the package's own charts draw every mark through them.
+ *
+ * The same guard over the Web App's charts is its `chart-marks.test.ts`.
+ */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { createElement, type ReactElement } from "react";
+import { describe, expect, it } from "vitest";
+import {
+ ChartArc,
+ ChartArea,
+ ChartAxis,
+ ChartBar,
+ ChartCursor,
+ ChartGrid,
+ ChartLine,
+ ChartPoint,
+ ChartSwatch,
+ barPath,
+} from "../src/components/charts/marks/marks";
+import { TimelineBar } from "../src/components/charts/marks/timeline-bar";
+import { DEFAULT_CHART_STYLE } from "../src/components/charts/chart-style";
+import { renderStatic } from "../src/testing";
+import { SRC_DIR } from "./helpers/paths";
+
+// Each primitive has its own props; the helper only renders one, so it takes any component.
+const render = (type: (props: any) => ReactElement | null, props: object) =>
+ renderStatic(createElement(type, props));
+
+describe("the chart primitives, in the default theme", () => {
+ it("draw a bar at the theme's share of its band, square, unoutlined, in its slot's colour", () => {
+ const html = render(ChartBar, { cx: 50, band: 20, y: 10, height: 30, paint: { series: 1 } });
+ expect(html).toContain("<rect");
+ expect(html).toContain('width="12"');
+ expect(html).toContain('x="44"');
+ expect(html).toContain('data-part="bar"');
+ expect(html).toContain('data-series="2"');
+ expect(html).toContain(`color:${DEFAULT_CHART_STYLE.series[1]}`);
+ expect(html).not.toContain("stroke");
+ expect(html).not.toContain("fill-opacity");
+ });
+
+ it("round a bar's top corners only when a theme gives a radius, clamped to the bar", () => {
+ expect(barPath(0, 0, 10, 20, 0)).toBeNull();
+ expect(barPath(0, 0, 10, 20, 3)).toBe("M0,20 V3 A3,3 0 0 1 3,0 H7 A3,3 0 0 1 10,3 V20 Z");
+ expect(barPath(0, 0, 4, 20, 9)).toContain("A2,2");
+ });
+
+ it("draw a line straight at the theme's width, and a point as a round rect", () => {
+ const line = render(ChartLine, {
+ points: [
+ [0, 10],
+ [10, 20],
+ ],
+ paint: { role: "ref" },
+ dash: "4 3",
+ });
+ expect(line).toContain('d="M0,10 L10,20"');
+ expect(line).toContain('stroke-width="2"');
+ expect(line).toContain('stroke-dasharray="4 3"');
+ expect(line).toContain('data-part="series"');
+ const point = render(ChartPoint, { cx: 10, cy: 10, paint: { ink: "" }, grow: true });
+ expect(point).toContain('rx="4"');
+ expect(point).toContain('width="8"');
+ expect(point).toContain('data-part="point"');
+ });
+
+ it("fill under a line at the theme's area opacity, scaled by strength", () => {
+ const area = render(ChartArea, {
+ points: [
+ [0, 10],
+ [10, 20],
+ ],
+ baseY: 30,
+ paint: { ink: "text-tone-success-fg" },
+ strength: 0.6,
+ });
+ expect(area).toContain('d="M0,10 L10,20 L10,30 L0,30 Z"');
+ expect(area).toMatch(/opacity="0\.06/);
+ expect(area).toContain("text-tone-success-fg");
+ });
+
+ it("draw an arc from twelve o'clock, round-capped only when asked, its track a grid part", () => {
+ const arc = render(ChartArc, {
+ cx: 10,
+ cy: 10,
+ r: 8,
+ width: 2,
+ paint: { role: "output" },
+ length: 20,
+ offset: -5,
+ });
+ expect(arc).toContain('data-part="series"');
+ expect(arc).toContain('stroke-dasharray="20 ');
+ expect(arc).toContain('stroke-dashoffset="-5"');
+ expect(arc).toContain('transform="rotate(-90 10 10)"');
+ expect(arc).not.toContain("stroke-linecap");
+ const capped = render(ChartArc, {
+ cx: 10,
+ cy: 10,
+ r: 8,
+ width: 2,
+ paint: { ink: "" },
+ length: 20,
+ round: true,
+ });
+ expect(capped).toContain('stroke-linecap="round"');
+ const track = render(ChartArc, {
+ cx: 10,
+ cy: 10,
+ r: 8,
+ width: 2,
+ paint: { ink: "" },
+ track: true,
+ trackOpacity: 0.3,
+ });
+ expect(track).toContain('data-part="grid"');
+ expect(track).toContain('stroke-opacity="0.3"');
+ expect(track).not.toContain("stroke-dasharray");
+ });
+
+ it("place a timeline bar where the chart says, in its slot's colour", () => {
+ const html = render(TimelineBar, {
+ paint: { series: 0 },
+ place: { left: "10%", width: "5%" },
+ className: "cursor-pointer",
+ });
+ expect(html).toContain("left:10%");
+ expect(html).toContain(`background-color:${DEFAULT_CHART_STYLE.series[0]}`);
+ expect(html).toContain('data-part="bar"');
+ expect(html).not.toContain("box-shadow");
+ expect(html).not.toContain("border-radius");
+ });
+
+ it("paint a swatch the way its mark is painted", () => {
+ expect(render(ChartSwatch, { paint: { role: "cacheRead" } })).toContain(
+ `background-color:${DEFAULT_CHART_STYLE.cacheRead}`,
+ );
+ expect(
+ render(ChartSwatch, { paint: { ink: "text-fg-subtle", swatch: "bg-fg-subtle" } }),
+ ).toContain("bg-fg-subtle");
+ });
+
+ it("draw the grid, the axis labels and the cursor in the theme's chart inks", () => {
+ expect(render(ChartGrid, { x1: 0, x2: 10, y: 5 })).toContain('class="stroke-chart-grid"');
+ const axis = render(ChartAxis, { x: 0, y: 0, anchor: "end", children: "12" });
+ expect(axis).toContain('class="fill-chart-axis"');
+ expect(axis).toContain('data-part="axis"');
+ expect(render(ChartCursor, { x: 5, y1: 0, y2: 10 })).toContain('class="stroke-line-emphasis"');
+ });
+});
+
+describe("every chart in the package", () => {
+ const CHARTS = [
+ "components/charts/chart-frame/chart-frame.tsx",
+ "components/charts/token-donut/token-donut.tsx",
+ "components/charts/sparkline/sparkline.tsx",
+ "components/charts/ring/ring.tsx",
+ "components/charts/legend/legend.tsx",
+ ];
+
+ it("draws its marks through the primitives, never with its own shapes, paint or geometry", () => {
+ const found: string[] = [];
+ for (const rel of CHARTS) {
+ const code = readFileSync(join(SRC_DIR, rel), "utf8").replace(
+ /\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,
+ "",
+ );
+ for (const pattern of [
+ /<(?:rect|path|circle|line|polyline|polygon|ellipse|text)\b/,
+ /\b(?:fill|stroke|strokeWidth|strokeDasharray|fillOpacity|strokeOpacity)=/,
+ /backgroundColor/,
+ /useChartStyle\(/,
+ ]) {
+ const hit = code.match(pattern);
+ if (hit) found.push(`${rel}: ${hit[0]}`);
+ }
+ }
+ expect(found).toEqual([]);
+ });
+});
diff --git a/packages/web/test/chart-style.test.ts b/packages/ui/test/chart-style.test.ts
similarity index 83%
rename from packages/web/test/chart-style.test.ts
rename to packages/ui/test/chart-style.test.ts
index c31d7e23..2df30dbc 100644
--- a/packages/web/test/chart-style.test.ts
+++ b/packages/ui/test/chart-style.test.ts
@@ -1,7 +1,8 @@
/**
- * The charts' theme reading (lib/chart-style.ts) and the geometry it drives (chart/geom.ts):
- * tokens parse into the record with the default theme's values as the fallback for each one,
- * and the default values draw exactly what the charts drew before they read tokens.
+ * The charts' theme reading (charts/chart-style.ts) and the geometry it drives (marks/geom.ts):
+ * tokens parse into the record with the default record's values as the fallback for each one,
+ * the fallback colours name the tokens themselves, and the default geometry draws exactly what
+ * the charts drew before they read tokens.
*/
import { describe, expect, it } from "vitest";
import {
@@ -9,9 +10,9 @@ import {
nextChartStyle,
readChartStyle,
seriesStroke,
-} from "../src/lib/chart-style";
-import { makeGeom, seriesPoints } from "../src/features/usage/chart-geom";
-import { curvePath, fitBarWidth } from "../src/components/ui/chart/geom";
+} from "../src/components/charts/chart-style";
+import { makeGeom, seriesPoints } from "../src/components/charts/chart-frame/chart-geom";
+import { curvePath, fitBarWidth } from "../src/components/charts/marks/geom";
const reader = (tokens: Record<string, string>) => (name: string) => tokens[name] ?? "";
@@ -41,8 +42,10 @@ describe("readChartStyle", () => {
});
});
- it("falls back token by token to the default theme's values", () => {
+ it("falls back token by token to the default record, whose colours are the tokens", () => {
expect(readChartStyle(reader({}))).toEqual(DEFAULT_CHART_STYLE);
+ expect(DEFAULT_CHART_STYLE.series[2]).toBe("var(--ui-chart-3)");
+ expect(DEFAULT_CHART_STYLE.cacheRead).toBe("var(--ui-chart-cache-read)");
const odd = readChartStyle(
reader({ "--ui-chart-curve": "wiggly", "--ui-chart-bar-fill": "x" }),
);
diff --git a/packages/ui/test/command-palette.test.ts b/packages/ui/test/command-palette.test.ts
new file mode 100644
index 00000000..614929af
--- /dev/null
+++ b/packages/ui/test/command-palette.test.ts
@@ -0,0 +1,99 @@
+/**
+ * CommandPalette (src/components/overlays/command-palette/command-palette.tsx): a modal dialog
+ * named by the caller, a search box named by its placeholder over a listbox whose first action
+ * starts selected, the caller's empty sentence and hint, and the scrim hook on its host. The
+ * filter is pure and called directly; the portal renders in place.
+ */
+import { createElement } from "react";
+import type { ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import {
+ CommandPalette,
+ filterPaletteActions,
+} from "../src/components/overlays/command-palette/command-palette";
+import type { CommandPaletteProps } from "../src/components/overlays/command-palette/command-palette";
+import { classTokens, renderStatic } from "../src/testing";
+import { stubDialogGlobals } from "./helpers/dialog-env";
+
+vi.mock("react-dom", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-dom")>()),
+ createPortal: (node: ReactNode) => node,
+}));
+stubDialogGlobals();
+
+const noop = () => {};
+const ACTIONS = [
+ { id: "history", label: "Harness history", keywords: ["version", "hmr"], run: noop },
+ { id: "reload", label: "Reload page", run: noop },
+];
+const palette = (props: Partial<CommandPaletteProps> = {}) =>
+ renderStatic(
+ createElement(CommandPalette, {
+ open: true,
+ onClose: noop,
+ actions: ACTIONS,
+ title: "Command palette",
+ placeholder: "Filter commands",
+ emptyText: "Nothing matches",
+ ...props,
+ }),
+ );
+
+describe("filterPaletteActions", () => {
+ it("lists everything for an empty query, in registration order", () => {
+ expect(filterPaletteActions(ACTIONS, " ").map((a) => a.id)).toEqual(["history", "reload"]);
+ });
+
+ it("matches every token, case-insensitively, against the label and the keywords", () => {
+ expect(filterPaletteActions(ACTIONS, "HIST").map((a) => a.id)).toEqual(["history"]);
+ expect(filterPaletteActions(ACTIONS, "harness hist").map((a) => a.id)).toEqual(["history"]);
+ expect(filterPaletteActions(ACTIONS, "hmr").map((a) => a.id)).toEqual(["history"]);
+ expect(filterPaletteActions(ACTIONS, "page harness")).toEqual([]);
+ });
+});
+
+describe("CommandPalette", () => {
+ it("renders nothing while closed", () => {
+ expect(palette({ open: false })).toBe("");
+ });
+
+ it("is a modal dialog named by the caller, its search box named by the placeholder", () => {
+ const html = palette();
+ expect(html).toContain('role="dialog"');
+ expect(html).toContain('aria-modal="true"');
+ expect(html).toContain('aria-label="Command palette"');
+ expect(html).toMatch(
+ /<input[^>]*placeholder="Filter commands"[^>]*aria-label="Filter commands"/,
+ );
+ });
+
+ it("lists the actions as options, the first one selected", () => {
+ const html = palette();
+ expect(html).toContain('role="listbox"');
+ const options = [...html.matchAll(/role="option" aria-selected="(true|false)"/g)].map(
+ (m) => m[1],
+ );
+ expect(options).toEqual(["true", "false"]);
+ expect(html).toContain(">Harness history</button>");
+ });
+
+ it("says the caller's sentence when there is nothing to list, and shows the hint only when given", () => {
+ const empty = palette({ actions: [] });
+ expect(empty).toContain(">Nothing matches</p>");
+ expect(empty).not.toContain('role="listbox"');
+ expect(palette()).not.toContain("border-t");
+ expect(palette({ hint: "Enter to run" })).toMatch(/border-t[^"]*">Enter to run<\/div>/);
+ });
+
+ it("dims the page through the scrim hook, and paints in tokens", () => {
+ expect(classTokens(palette())).toEqual(
+ expect.arrayContaining([
+ "ui-scrim",
+ "bg-[var(--ui-overlay-backdrop)]",
+ "bg-surface",
+ "border-line",
+ "bg-surface-muted",
+ ]),
+ );
+ });
+});
diff --git a/packages/ui/test/hooks.test.ts b/packages/ui/test/hooks.test.ts
index 9e191527..76102c18 100644
--- a/packages/ui/test/hooks.test.ts
+++ b/packages/ui/test/hooks.test.ts
@@ -95,9 +95,9 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {
],
// `Text` carries it for its eyebrow role (W5), the one door a group label takes in new code.
"ui-eyebrow": ["Sidebar", "GroupHeader", "PagedDialog", "Text"],
- // The page titles are `PageHeader`'s; the usage page and the draft view's hero still write
- // their own until their waves (W8, W6).
- "ui-display": ["Heading", "PageHeader", "EmptyState", "UsagePage", "DraftView"],
+ // The page titles are `PageHeader`'s; the draft view's hero still writes its own until its
+ // wave (W6).
+ "ui-display": ["Heading", "PageHeader", "EmptyState", "DraftView"],
"ui-live": ["Spinner", "Dot", "Stepper", "MachineCard", "ProgressBar"],
// The transcript's cards and the code block, and the page-level boxes (W4): the card and a
// table that is its own box.
@@ -119,13 +119,13 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {
"ui-field": ["Field", "PrefRow", "SettingRow"],
"ui-activity": ["WorkGroup", "ToolCallCard", "DisclosureRow"],
// The Web App's notices (2026-09-29): the toast, and the one shared strip every inline notice
- // renders through. The charts: the usage charts' frame (its children — the trend, requests and
- // token-bar charts — carry parts, not the hook), the token donut and the two sparklines.
+ // renders through. The charts: the plot frame (its children — the trend, requests, token-bar
+ // and score charts — carry parts, not the hook), the token donut, the sparkline and the ring.
"ui-notice": ["Toaster", "NoticeStrip"],
// The Trace timeline draws its lanes and spans as HTML (`grid` on a lane track, `bar` on a
// span with a 1-based `data-series`), so the chart recipes carry HTML spellings beside the
// SVG ones.
- "ui-chart": ["ChartFrame", "TokenDonut", "ScoreSparkline", "ActivitySparkline", "TimelineChart"],
+ "ui-chart": ["ChartFrame", "TokenDonut", "Sparkline", "Ring", "TimelineChart"],
// The dimmed backdrop (2026-09-30): a sibling behind a sheet or drawer, or the full-viewport
// overlay a modal, the command palette, the harness overlay and the lightbox sit in.
"ui-scrim": ["Modal", "Sheet", "Drawer", "CommandPalette", "HarnessHistoryOverlay", "Lightbox"],
diff --git a/packages/ui/test/legend.test.ts b/packages/ui/test/legend.test.ts
new file mode 100644
index 00000000..5b93b5ad
--- /dev/null
+++ b/packages/ui/test/legend.test.ts
@@ -0,0 +1,81 @@
+/**
+ * The legend (src/components/charts/legend): a list of the caller's labels, each with the swatch
+ * its marks are painted in, or a mark of its own; inline items fade while another is singled
+ * out, list rows wash and ring, a selectable item is a toggle button, and an item that explains
+ * a shape stays still.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import { Legend } from "../src/components/charts/legend/legend";
+import type { LegendItem } from "../src/components/charts/legend/legend";
+import { classTokens, renderStatic } from "../src/testing";
+
+type Props = Parameters<typeof Legend>[0];
+const legend = (props: Props) => renderStatic(createElement(Legend, props));
+
+const ITEMS: LegendItem[] = [
+ { key: "read", label: "Cache read", paint: { role: "cacheRead" }, shape: "chip" },
+ { key: "out", label: "Output", paint: { role: "output" }, shape: "chip" },
+ {
+ key: "rate",
+ label: "Hit rate",
+ paint: { ink: "text-fg-subtle", swatch: "bg-fg-subtle" },
+ shape: "dash",
+ interactive: false,
+ },
+];
+
+/** The `<li>` markup of each item, in order. */
+const itemsOf = (html: string) => html.match(/<li[\s\S]*?<\/li>/g) ?? [];
+
+describe("Legend", () => {
+ it("lists the caller's labels, named when asked, each with its swatch", () => {
+ const html = legend({ items: ITEMS, label: "Token kinds" });
+ expect(html).toMatch(/^<ul aria-label="Token kinds"/);
+ expect(itemsOf(html)).toHaveLength(3);
+ for (const label of ["Cache read", "Output", "Hit rate"]) expect(html).toContain(label);
+ expect(html).toContain("var(--ui-chart-cache-read)");
+ expect(html).toContain("bg-fg-subtle");
+ expect(html).not.toMatch(/gray-|dark:/);
+ });
+
+ it("fades the other items while one is singled out, never the one that explains a shape", () => {
+ const [read, out, rate] = itemsOf(legend({ items: ITEMS, active: "read" }));
+ expect(read).not.toContain("opacity-30");
+ expect(out).toContain("opacity-30");
+ expect(rate).not.toContain("opacity-30");
+ expect(itemsOf(legend({ items: ITEMS }))[1]).not.toContain("opacity-30");
+ });
+
+ it("makes each item a toggle button with onSelect, pressed while pinned", () => {
+ const html = legend({ items: ITEMS, pinned: "out", onSelect: () => {}, onHover: () => {} });
+ const [read, out, rate] = itemsOf(html);
+ expect(read).toContain('<button type="button" aria-pressed="false"');
+ expect(out).toContain('aria-pressed="true"');
+ expect(rate).not.toContain("<button");
+ });
+
+ it("lays a list out row by row, with the figures after the label, a wash and a pin ring", () => {
+ const rows: LegendItem[] = [
+ { key: "a", label: "read_file", value: createElement("span", null, "~1.2k") },
+ { key: "b", label: "grep", title: "grep in src/", value: createElement("span", null, "~40") },
+ ];
+ const html = legend({ items: rows, layout: "list", mono: true, active: "a", pinned: "b" });
+ const [a, b] = itemsOf(html);
+ expect(a).toContain("<span>~1.2k</span>");
+ expect(classTokens(a!)).toEqual(expect.arrayContaining(["bg-tone-neutral-bg", "font-mono"]));
+ expect(classTokens(b!)).toContain("inset-ring-fg-subtle");
+ expect(b).toContain('data-tooltip="grep in src/"');
+ expect(b).toContain('data-tooltip-content="code"');
+ // No paint and no mark: no swatch.
+ expect(a).not.toContain("inline-block");
+ });
+
+ it("draws an item's own mark in the swatch's place", () => {
+ const html = legend({
+ items: [{ key: "run", label: "Running", mark: createElement("i", { id: "dot" }) }],
+ });
+ expect(html).toContain('<i id="dot"></i>');
+ expect(html).not.toContain("inline-block");
+ });
+});
diff --git a/packages/ui/test/ring.test.ts b/packages/ui/test/ring.test.ts
new file mode 100644
index 00000000..db7900cc
--- /dev/null
+++ b/packages/ui/test/ring.test.ts
@@ -0,0 +1,66 @@
+/**
+ * The ring gauge (src/components/charts/ring): named by its caller or hidden, arcs laid clockwise
+ * from twelve o'clock as shares of `max` and never past a full circle, a lone partial arc
+ * round-capped, the track in the grid's line or the ring's own ink faded, and the tone as a
+ * token ink.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import { Ring, ringArcs } from "../src/components/charts/ring/ring";
+import { classTokens, renderStatic } from "../src/testing";
+
+type Props = Parameters<typeof Ring>[0];
+const ring = (props: Props) => renderStatic(createElement(Ring, props));
+
+describe("Ring", () => {
+ it("is an image named by the caller, or decoration without a name", () => {
+ const named = ring({ segments: [{ value: 0.4 }], max: 1, label: "$4 / $10 · 40%" });
+ expect(named).toContain('role="img"');
+ expect(named).toContain('aria-label="$4 / $10 · 40%"');
+ expect(named).toContain('data-tooltip="$4 / $10 · 40%"');
+ const bare = ring({ segments: [{ value: 0.4 }], max: 1 });
+ expect(bare).toContain('aria-hidden="true"');
+ expect(bare).not.toContain("role=");
+ expect(classTokens(bare)).toContain("ui-chart");
+ });
+
+ it("lays arcs clockwise as shares of max, filling the ring when they add up to more", () => {
+ const c = 80;
+ expect(ringArcs([{ value: 1 }, { value: 2 }], 8, c)).toEqual([
+ { index: 0, length: 10, offset: -0 },
+ { index: 1, length: 20, offset: -10 },
+ ]);
+ const over = ringArcs([{ value: 3 }, { value: 1 }], 2, c);
+ expect(over.map((a) => a.length)).toEqual([60, 20]);
+ // Nothing to draw: an empty reading, a zero segment, a zero max with nothing in it.
+ expect(ringArcs([{ value: 0 }], 1, c)).toEqual([]);
+ expect(ringArcs([], 0, c)).toEqual([]);
+ });
+
+ it("round-caps a lone arc that does not close the ring, and nothing else", () => {
+ expect(ring({ segments: [{ value: 0.5 }], max: 1 })).toContain('stroke-linecap="round"');
+ expect(ring({ segments: [{ value: 1 }], max: 1 })).not.toContain("stroke-linecap");
+ expect(ring({ segments: [{ value: 0.2 }, { value: 0.3 }], max: 1 })).not.toContain(
+ "stroke-linecap",
+ );
+ });
+
+ it("draws its track in the grid's line, or in its own ink faded", () => {
+ const grid = ring({ segments: [], max: 1 });
+ expect(grid).toContain('data-part="grid"');
+ expect(classTokens(grid)).toContain("text-chart-grid");
+ expect(grid).not.toContain('data-part="series"');
+ const faded = ring({ segments: [], max: 1, trackOpacity: 0.25 });
+ expect(faded).toContain('stroke-opacity="0.25"');
+ expect(classTokens(faded)).not.toContain("text-chart-grid");
+ });
+
+ it("inks itself in its tone's token, or in the ink around it", () => {
+ expect(classTokens(ring({ segments: [], max: 1, tone: "danger" }))).toContain(
+ "text-tone-danger-fg",
+ );
+ const own = ring({ segments: [{ value: 0.5, paint: { role: "output" } }], max: 1 });
+ expect(own).toContain("var(--ui-chart-output)");
+ expect(own).not.toMatch(/gray-|red-|dark:/);
+ });
+});
diff --git a/packages/ui/test/sparkline.test.ts b/packages/ui/test/sparkline.test.ts
new file mode 100644
index 00000000..42846382
--- /dev/null
+++ b/packages/ui/test/sparkline.test.ts
@@ -0,0 +1,50 @@
+/**
+ * The sparkline (src/components/charts/sparkline): a named image in its tone's ink, its two
+ * scales — against zero with a flat baseline for too few values, and the observed range with a
+ * floor and a lone point — and the fill and the newest-point marker on request.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import { Sparkline, sparklineDomain } from "../src/components/charts/sparkline/sparkline";
+import { classTokens, renderStatic } from "../src/testing";
+
+type Props = Parameters<typeof Sparkline>[0];
+const spark = (props: Props) => renderStatic(createElement(Sparkline, props));
+
+describe("Sparkline", () => {
+ it("is an image named by the caller, in the muted ink or its tone's", () => {
+ const html = spark({ values: [1, 3, 2], label: "Sessions, 30 days" });
+ expect(html).toContain('role="img"');
+ expect(html).toContain('aria-label="Sessions, 30 days"');
+ expect(html).toContain('data-tooltip="Sessions, 30 days"');
+ expect(classTokens(html)).toEqual(expect.arrayContaining(["ui-chart", "text-fg-muted"]));
+ const toned = spark({ values: [1, 3], label: "x", tone: "success" });
+ expect(classTokens(toned)).toContain("text-tone-success-fg");
+ expect(toned).not.toMatch(/gray-|emerald-|dark:/);
+ });
+
+ it("scales against zero, or to the observed range with a floor centred on the values", () => {
+ expect(sparklineDomain([2, 4], "zero", 5)).toEqual({ low: 0, span: 4 });
+ expect(sparklineDomain([0, 0], "zero", 5)).toEqual({ low: 0, span: 1 });
+ expect(sparklineDomain([60, 90], "range", 5)).toEqual({ low: 60, span: 30 });
+ expect(sparklineDomain([70, 71], "range", 5)).toEqual({ low: 68, span: 5 });
+ });
+
+ it("draws a flat baseline for too few values against zero, a lone point on a range", () => {
+ const flat = spark({ values: [], label: "x", width: 100, height: 30 });
+ expect(flat).toContain('d="M2,28 L98,28"');
+ expect(flat).not.toContain('data-part="area"');
+ const lone = spark({ values: [72], label: "x", scale: "range", marker: true });
+ expect(lone).not.toContain('data-part="series"');
+ expect(lone.match(/data-part="point"/g)).toHaveLength(1);
+ });
+
+ it("fills under the line and marks the newest point only when asked", () => {
+ const plain = spark({ values: [1, 2, 3], label: "x" });
+ expect(plain).not.toContain('data-part="area"');
+ expect(plain).not.toContain('data-part="point"');
+ const full = spark({ values: [1, 2, 3], label: "x", area: true, marker: true });
+ expect(full).toContain('data-part="area"');
+ expect(full.match(/data-part="point"/g)).toHaveLength(1);
+ });
+});
diff --git a/packages/ui/test/token-donut.test.ts b/packages/ui/test/token-donut.test.ts
new file mode 100644
index 00000000..5d38726e
--- /dev/null
+++ b/packages/ui/test/token-donut.test.ts
@@ -0,0 +1,50 @@
+/**
+ * The token donut (src/components/charts/token-donut): its name and tooltip in the caller's
+ * words and figures, three arcs in the Token kinds' colours over a track in the ring's own ink,
+ * and the remainder's warning at 80% and 95% of the limit.
+ */
+import { createElement } from "react";
+import { describe, expect, it } from "vitest";
+import { TokenDonut } from "../src/components/charts/token-donut/token-donut";
+import { classTokens, renderStatic } from "../src/testing";
+
+const LABELS = { usage: "Kontext", cacheRead: "Lesen", cacheWrite: "Schreiben", output: "Ausgabe" };
+
+const donut = (cacheRead: number, cacheWrite: number, output: number, max = 100) =>
+ renderStatic(
+ createElement(TokenDonut, {
+ cacheRead,
+ cacheWrite,
+ output,
+ max,
+ labels: LABELS,
+ format: (n: number) => `${n}t`,
+ }),
+ );
+
+describe("TokenDonut", () => {
+ it("is a named image whose name and tooltip are the caller's words and figures", () => {
+ const html = donut(40, 5, 10);
+ expect(html).toContain('role="img"');
+ const name = "Kontext 55t/100t · Lesen 40t · Schreiben 5t · Ausgabe 10t";
+ expect(html).toContain(`aria-label="${name}"`);
+ expect(html).toContain(`data-tooltip="${name}"`);
+ expect(classTokens(html)).toContain("ui-chart");
+ });
+
+ it("draws one arc per non-empty kind over the track, in the kinds' colours", () => {
+ const html = donut(40, 0, 10);
+ expect(html.match(/data-part="series"/g)).toHaveLength(2);
+ expect(html.match(/data-part="grid"/g)).toHaveLength(1);
+ expect(html).toContain("var(--ui-chart-cache-read)");
+ expect(html).toContain("var(--ui-chart-output)");
+ expect(html).not.toContain("var(--ui-chart-cache-write)");
+ });
+
+ it("inks the remainder by how close usage is to the limit, in tokens", () => {
+ expect(classTokens(donut(40, 0, 10))).toContain("text-line-emphasis");
+ expect(classTokens(donut(80, 0, 5))).toContain("text-tone-attention-fg");
+ expect(classTokens(donut(90, 0, 10))).toContain("text-tone-danger-fg");
+ expect(donut(40, 0, 10)).not.toMatch(/gray-|dark:/);
+ });
+});
diff --git a/packages/web/src/components/ui/chart/index.ts b/packages/web/src/components/ui/chart/index.ts
deleted file mode 100644
index 364906e5..00000000
--- a/packages/web/src/components/ui/chart/index.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * The chart primitives: every chart mark in the app is drawn by one of these (see marks.tsx).
- */
-export {
- ChartArc,
- ChartArea,
- ChartAxis,
- ChartAxisBreak,
- ChartBar,
- ChartBarHit,
- ChartCursor,
- ChartGrid,
- ChartHit,
- ChartLine,
- ChartPoint,
- ChartSwatch,
- resolvePaint,
- useBarWidth,
-} from "./marks";
-export type { ChartPaint } from "./marks";
-export { TimelineBar } from "./timeline-bar";
-export { BAR_W, curvePath, fitBarWidth, roundCoord } from "./geom";
diff --git a/packages/web/src/features/agents/activity-sparkline.tsx b/packages/web/src/features/agents/activity-sparkline.tsx
deleted file mode 100644
index b03ea422..00000000
--- a/packages/web/src/features/agents/activity-sparkline.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Session activity sparkline (Agents list card, GitHub-repo-Pulse-graph style): a
- * polyline + faint fill of daily active Session counts over the last N days,
- * normalized to the max value within the window — shows only relative ups and downs,
- * no scale/ticks. All-zero / empty data renders a flat baseline at the bottom. Drawn
- * through the chart primitives at a sparkline's scale, so it takes the theme's curve, line
- * width and area fill; its colour is its own ink, which follows light and dark.
- */
-import { ChartArea, ChartLine, type ChartPaint } from "../../components/ui/chart";
-
-/** The sparkline's paint: its own ink, the emerald the svg's text class sets. */
-const INK: ChartPaint = { ink: "" };
-/** Three quarters of the theme's line width (1.5px in the default theme). */
-const LINE_SCALE = 0.75;
-/** The fill under the line, a little stronger than a full chart's (0.12 in the default theme). */
-const AREA_STRENGTH = 1.2;
-
-const W = 100;
-const H = 30;
-const PAD = 2;
-
-export function ActivitySparkline({
- data,
- label,
- className = "",
-}: {
- data: number[];
- label: string;
- className?: string;
-}) {
- const max = Math.max(1, ...data);
- const step = data.length > 1 ? (W - 2 * PAD) / (data.length - 1) : 0;
- const pts = data.map((v, i) => [PAD + i * step, H - PAD - (v / max) * (H - 2 * PAD)] as const);
- const baseline = [
- [PAD, H - PAD],
- [W - PAD, H - PAD],
- ] as const;
- const line = pts.length > 1 ? pts : baseline;
- return (
- <svg
- width={W}
- height={H}
- viewBox={`0 0 ${W} ${H}`}
- role="img"
- aria-label={label}
- data-tooltip={label}
- // ui-chart: a theme may redraw the line and the fill under it.
- className={`ui-chart text-emerald-600 dark:text-emerald-500 ${className}`}
- >
- {pts.length > 1 && (
- <ChartArea points={pts} baseY={H - PAD} paint={INK} strength={AREA_STRENGTH} />
- )}
- <ChartLine points={line} paint={INK} scale={LINE_SCALE} round />
- </svg>
- );
-}
diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsx
index c83fd566..12644746 100644
--- a/packages/web/src/features/agents/agents-page.tsx
+++ b/packages/web/src/features/agents/agents-page.tsx
@@ -48,6 +48,7 @@ import {
PageHeader,
Skeleton,
SkeletonCard,
+ Sparkline,
Textarea,
TodoNotice,
UpdatePill,
@@ -70,7 +71,6 @@ import { SemanticIdField } from "../semantic-id/semantic-id-field";
import { STAT_ICONS } from "../../lib/stat-icons";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { prepareNewChatDraft } from "../chat/new-chat";
-import { ActivitySparkline } from "./activity-sparkline";
import {
SNAPSHOT_ACCEPT,
SNAPSHOT_BUTTON_CLASS,
@@ -699,10 +699,17 @@ export function AgentsPage() {
</div>
</div>
- {/* Session activity sparkline (hidden on narrow screens first, giving the horizontal space back to content and buttons) */}
- <ActivitySparkline
- data={a.sessionActivity}
+ {/* Session activity sparkline, GitHub Pulse style: daily active Session counts
+ against zero with a faint fill, in the success ink (an agent in use is a
+ healthy one). Hidden on narrow screens first, giving the horizontal space back
+ to content and buttons. */}
+ <Sparkline
+ values={a.sessionActivity}
label={S.agent.activity(a.sessionActivity.length || 30)}
+ area
+ tone="success"
+ width={100}
+ height={30}
className="hidden shrink-0 md:block"
/>
diff --git a/packages/web/src/features/benchmark/benchmark-detail-page.tsx b/packages/web/src/features/benchmark/benchmark-detail-page.tsx
index 1d0b2639..5278976b 100644
--- a/packages/web/src/features/benchmark/benchmark-detail-page.tsx
+++ b/packages/web/src/features/benchmark/benchmark-detail-page.tsx
@@ -12,9 +12,8 @@ import {
Button,
CopyButton,
EmptyState,
- GlyphIcon,
- ICONS,
- ICON_SIZE,
+ PageFrame,
+ PageHeader,
Skeleton,
} from "@prismshadow/penguin-ui";
import * as api from "../../api/endpoints";
@@ -145,55 +144,50 @@ export function BenchmarkDetailPage() {
}
return (
- <div className="h-full overflow-y-auto p-4 md:p-6">
- <div className="mx-auto max-w-4xl">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => navigate("/benchmark")}
- className="-ml-2 mb-3 text-gray-500 dark:text-gray-400"
- >
- <GlyphIcon d={ICONS.arrowLeft} size={ICON_SIZE.rowLead} />
- {S.benchmark.backToList}
- </Button>
- {/* The Benchmark's name, the directory its files live in, and the Use entry point. The
- case counts and the description are the detail's own, one block below. A Benchmark
- tests whichever Agents its scoreboard names, so no single Agent is named up here. A
- Benchmark that is not published, reached by its address, keeps the path but drops
- Use, and shows the building or creation-failed notice in place of the detail. */}
- <div className="mb-4 flex flex-wrap items-center gap-x-2 gap-y-1">
- <h1 className="min-w-0 truncate text-xl font-semibold">
+ <PageFrame width="md">
+ {/* The Benchmark's name, the directory its files live in under it, and the Use entry
+ point at the end of the title row. The case counts and the description are the
+ detail's own, one block below. A Benchmark tests whichever Agents its scoreboard
+ names, so no single Agent is named up here. A Benchmark that is not published, reached
+ by its address, keeps the path but drops Use, and shows the building or
+ creation-failed notice in place of the detail. A Benchmark that no longer resolves has
+ no directory to name and nothing to use: the title and the way back are all the header
+ keeps. */}
+ <PageHeader
+ back={{ label: S.benchmark.backToList, onClick: () => navigate("/benchmark") }}
+ title={
+ <span className="min-w-0 truncate">
{benchmark === null
? benchmarkId
: onlyMachine !== null
? nameOnMachine(benchmark.title, onlyMachine)
: benchmark.title}
- </h1>
- {/* A Benchmark that no longer resolves has no directory to name and nothing to use:
- the title and the way back are all this row keeps. */}
- {benchmark && (
- <>
- <span className="flex min-w-0 flex-1 items-center gap-1">
- <span className="min-w-0 truncate font-mono text-xs text-gray-400 dark:text-gray-500">
- {benchmarkPath(benchmark.id)}
- </span>
- <CopyButton
- text={benchmarkPath(benchmark.id)}
- label={S.benchmark.copyPath}
- size="sm"
- className="shrink-0"
- />
+ </span>
+ }
+ description={
+ benchmark ? (
+ <span className="flex min-w-0 items-center gap-1">
+ <span className="min-w-0 truncate font-mono text-xs text-gray-400 dark:text-gray-500">
+ {benchmarkPath(benchmark.id)}
</span>
- {!masked && (
- <Button size="sm" variant="primary" onClick={() => setUsing(true)}>
- {S.benchmark.use}
- </Button>
- )}
- </>
- )}
- </div>
- {body}
- </div>
+ <CopyButton
+ text={benchmarkPath(benchmark.id)}
+ label={S.benchmark.copyPath}
+ size="sm"
+ className="shrink-0"
+ />
+ </span>
+ ) : undefined
+ }
+ actions={
+ benchmark && !masked ? (
+ <Button size="sm" variant="primary" onClick={() => setUsing(true)}>
+ {S.benchmark.use}
+ </Button>
+ ) : undefined
+ }
+ />
+ {body}
{using && benchmark !== null && !masked && (
<UseBenchmarkModal
@@ -207,6 +201,6 @@ export function BenchmarkDetailPage() {
initialTab="evaluate"
/>
)}
- </div>
+ </PageFrame>
);
}
diff --git a/packages/web/src/features/benchmark/benchmark-detail.tsx b/packages/web/src/features/benchmark/benchmark-detail.tsx
index dea36e17..4c9137bc 100644
--- a/packages/web/src/features/benchmark/benchmark-detail.tsx
+++ b/packages/web/src/features/benchmark/benchmark-detail.tsx
@@ -15,10 +15,14 @@ import {
AgentAvatar,
Button,
Card,
+ ChartFrame,
+ ChartLine,
+ ChartPoint,
EmptyState,
GlyphIcon,
ICONS,
ICON_SIZE,
+ Legend,
Modal,
Table,
TableBody,
@@ -26,7 +30,11 @@ import {
TableHead,
TableHeaderCell,
TableRow,
+ makeRangeGeom,
+ segmentPoints,
+ useChartWidth,
} from "@prismshadow/penguin-ui";
+import type { ChartPaint } from "@prismshadow/penguin-ui";
import type { MergedBenchmark, MergedCase } from "../../lib/benchmark-merge";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
@@ -35,9 +43,6 @@ import { toneInk } from "../../lib/tone";
import { useTheme } from "../../state/theme";
import type { Currency } from "../../state/theme";
import { NEUTRAL_SERIES } from "../../lib/category-colors";
-import { makeRangeGeom, segmentPoints } from "../usage/chart-geom";
-import { ChartLine, ChartPoint, ChartSwatch, type ChartPaint } from "../../components/ui/chart";
-import { ChartFrame, useChartWidth } from "../usage/chart-svg";
import { AskAiModal } from "./ask-ai-modal";
import { BenchmarkCaseBrowser } from "./benchmark-case-browser";
import { fetchBenchmarkCases } from "./benchmark-sources";
@@ -159,17 +164,16 @@ function TrendSection({ evaluations }: { evaluations: BenchmarkEvaluation[] }) {
{S.benchmark.trendTitle(S.benchmark.colScore)}
</p>
{series.length >= 2 && (
- <div className="mb-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">
- {series.map((s, i) => (
- <span
- key={s.unlabeled ? "unlabeled" : s.key}
- className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400"
- >
- <ChartSwatch paint={scoreSeriesPaint(s, i)} shape="block" />
- <span className="font-mono">{labelOf(s)}</span>
- </span>
- ))}
- </div>
+ <Legend
+ items={series.map((s, i) => ({
+ key: s.unlabeled ? "unlabeled" : s.key,
+ label: labelOf(s),
+ paint: scoreSeriesPaint(s, i),
+ shape: "block" as const,
+ }))}
+ mono
+ className="mb-1.5"
+ />
)}
<ScoreTrendChart evaluations={evaluations} series={series} />
</div>
diff --git a/packages/web/src/features/benchmark/benchmark-metrics.ts b/packages/web/src/features/benchmark/benchmark-metrics.ts
index c6a808b1..98a0bb4c 100644
--- a/packages/web/src/features/benchmark/benchmark-metrics.ts
+++ b/packages/web/src/features/benchmark/benchmark-metrics.ts
@@ -7,7 +7,7 @@
* runtime are the trend the loop exists to show, so they stay on one line, and each point
* carries its version in the chart's hover label and in the evaluation table's own column.
*/
-import type { LinePoint } from "../usage/chart-geom";
+import type { LinePoint } from "@prismshadow/penguin-ui";
/** Minimal Evaluation shape needed to read Score (BenchmarkEvaluation is a superset). */
export interface MetricSourceLike {
diff --git a/packages/web/src/features/benchmark/benchmark-page.tsx b/packages/web/src/features/benchmark/benchmark-page.tsx
index ed2d195d..327f0f90 100644
--- a/packages/web/src/features/benchmark/benchmark-page.tsx
+++ b/packages/web/src/features/benchmark/benchmark-page.tsx
@@ -34,6 +34,7 @@ import {
Select,
Skeleton,
SkeletonCard,
+ Sparkline,
toastError,
toastSuccess,
} from "@prismshadow/penguin-ui";
@@ -56,7 +57,6 @@ import { benchmarkCreateExamples, benchmarkCreateTail } from "./benchmark-prompt
import { benchmarkRoute } from "./benchmark-route";
import { fetchBenchmarks } from "./benchmark-sources";
import { CreateBenchmarkModal } from "./create-benchmark-modal";
-import { ScoreSparkline } from "./score-sparkline";
import { UseBenchmarkModal } from "./use-benchmark-modal";
/** The Skills a design conversation is opened with (see the create modal below). */
@@ -224,7 +224,15 @@ export function BenchmarkCard({
<TestedAgents agentIds={benchmark.agentIds} nameOf={nameOf} />
{series.length > 0 && (
<div className="hidden shrink-0 md:block">
- <ScoreSparkline values={series} label={S.benchmark.sparklineLabel(series.length)} />
+ {/* The scoreboard's Scores in order, the newest marked, on the observed range (the
+ sparkline's default 72×22 box and five-point floor), so a flat series draws a
+ level line through the middle rather than collapsing onto an edge. */}
+ <Sparkline
+ values={series}
+ label={S.benchmark.sparklineLabel(series.length)}
+ scale="range"
+ marker
+ />
</div>
)}
{/* At least a score's width, and as wide as its label beyond that: the label is a phrase
diff --git a/packages/web/src/features/benchmark/score-sparkline.tsx b/packages/web/src/features/benchmark/score-sparkline.tsx
deleted file mode 100644
index 069a09ed..00000000
--- a/packages/web/src/features/benchmark/score-sparkline.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Score sparkline of a Benchmark row: the scoreboard's Scores in order as one polyline, the
- * newest point marked. Normalized to the observed range with a small floor, so a series that
- * moved from 60 to 90 fills the box and a flat one draws a level line through its middle
- * instead of collapsing onto an edge; there are no ticks — the number beside it is the value.
- * A single score is a lone point. Pure SVG, its own geometry (outside the icon family), drawn
- * in the theme's chart style at a sparkline's scale: three quarters of the line width and four
- * fifths of the point radius, and the theme's curve.
- */
-import { ChartLine, ChartPoint, type ChartPaint } from "../../components/ui/chart";
-
-/** The sparkline's paint: its own ink (a single series, no identity to tell apart). */
-const INK: ChartPaint = { ink: "" };
-/** A sparkline's scale of the theme's line width and point radius. */
-const LINE_SCALE = 0.75;
-const POINT_SCALE = 0.8;
-
-const W = 72;
-const H = 22;
-const PAD = 2.5;
-/** The smallest range the box stands for: below this, differences are noise at 72px wide. */
-const MIN_SPAN = 5;
-
-export function ScoreSparkline({
- values,
- label,
- className = "",
-}: {
- values: readonly number[];
- label: string;
- className?: string;
-}) {
- const min = Math.min(...values);
- const max = Math.max(...values);
- const span = Math.max(max - min, MIN_SPAN);
- const low = (min + max) / 2 - span / 2;
- const step = values.length > 1 ? (W - 2 * PAD) / (values.length - 1) : 0;
- const points = values.map(
- (v, i) => [PAD + i * step, H - PAD - ((v - low) / span) * (H - 2 * PAD)] as const,
- );
- const last = points[points.length - 1];
- return (
- <svg
- width={W}
- height={H}
- viewBox={`0 0 ${W} ${H}`}
- role="img"
- aria-label={label}
- data-tooltip={label}
- // ui-chart: a theme may redraw the line and the newest point its own way.
- className={`ui-chart text-gray-500 dark:text-gray-400 ${className}`}
- >
- {points.length > 1 && <ChartLine points={points} paint={INK} scale={LINE_SCALE} round />}
- {last !== undefined && (
- <ChartPoint cx={last[0]} cy={last[1]} paint={INK} scale={POINT_SCALE} />
- )}
- </svg>
- );
-}
diff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsx
index b5e9a39d..5a826892 100644
--- a/packages/web/src/features/chat/context-gauge.tsx
+++ b/packages/web/src/features/chat/context-gauge.tsx
@@ -68,7 +68,7 @@ import { useEffect, useId, useRef, useState } from "react";
import type { RefObject } from "react";
import { createPortal } from "react-dom";
import type { SessionContextResponse } from "@prismshadow/penguin-server/api";
-import { ConfirmModal, Input, usePortalPanel } from "@prismshadow/penguin-ui";
+import { ConfirmModal, Input, Legend, Ring, usePortalPanel } from "@prismshadow/penguin-ui";
import { getSessionContext } from "../../api/endpoints";
import {
MIN_COMPACTION_THRESHOLD,
@@ -226,31 +226,16 @@ export function ContextGauge({
const usageText = unknown
? S.chat.contextUnknown
: `${S.chat.contextUsage} ${Math.round(pct * 100)}% · ${humanizeTokens(now)}/${humanizeTokens(basis)}`;
- const R = 5;
- const C = 2 * Math.PI * R;
+ // A 5px radius under a 2px stroke, in the shell's ink: the track is that ink faded, so the
+ // warning ladder above recolours the whole ring. Decorative — the shell carries the name.
const gauge = (
- <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden className="block shrink-0">
- <circle
- cx="7"
- cy="7"
- r={R}
- fill="none"
- stroke="currentColor"
- strokeOpacity="0.25"
- strokeWidth="2"
- />
- <circle
- cx="7"
- cy="7"
- r={R}
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeDasharray={`${C * pct} ${C}`}
- transform="rotate(-90 7 7)"
- />
- </svg>
+ <Ring
+ segments={pct > 0 ? [{ value: pct }] : []}
+ max={1}
+ size={12}
+ width={2}
+ trackOpacity={0.25}
+ />
);
// Same box as every other icon control on this toolbar (h-8 w-8, matching the model selector
// and the send button): a 14px ring in a 23px hit area sat visibly short of its neighbours.
@@ -296,7 +281,7 @@ export function ContextGauge({
maxWidth: PANEL_MAX_WIDTH,
maxHeight: PANEL_MAX_HEIGHT,
}}
- className="anim-pop z-[60] overflow-y-auto rounded-md border border-gray-200 bg-white p-2.5 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900"
+ className="anim-pop z-[60] overflow-y-auto rounded-md border border-gray-200 bg-white p-3 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900"
>
<ContextPanel
sessionId={sessionId}
@@ -521,21 +506,23 @@ function ContextPanel({
{S.chat.contextWindowIs(humanizeTokens(windowTokens))}
</p>
- <ul className="mt-1.5 space-y-0.5">
- {composition.parts.map((p) => (
- <ShareRow
- key={p.key}
- label={PART_LABELS[p.key]()}
- swatch={p.color}
- tokens={p.tokens}
- percent={p.percent}
- highlighted={lit === p.key}
- pinned={pinned === p.key}
- onHover={(on) => setHovered(on ? p.key : null)}
- onSelect={() => togglePinned(p.key)}
- />
- ))}
- </ul>
+ {/* The bar's segments sit inside its aria-hidden track and stay mouse-only, so this
+ legend is the only surface pinning can be reached from at all: each row is a
+ toggle button carrying the pin's state. */}
+ <Legend
+ layout="list"
+ className="mt-1.5"
+ items={composition.parts.map((p) => ({
+ key: p.key,
+ label: PART_LABELS[p.key](),
+ paint: { ink: "", swatch: p.color },
+ value: <ShareFigures tokens={p.tokens} percent={p.percent} />,
+ }))}
+ active={lit}
+ pinned={pinned}
+ onHover={setHovered}
+ onSelect={togglePinned}
+ />
{composition.tools.length > 0 && (
<>
@@ -556,7 +543,7 @@ function ContextPanel({
<div
role="group"
aria-label={S.chat.contextRankLabel}
- className="flex shrink-0 items-center gap-0.5"
+ className="flex shrink-0 items-center gap-1"
>
{RANKING_VIEWS.map(({ view, label }) => (
<button
@@ -575,41 +562,41 @@ function ContextPanel({
))}
</div>
</div>
+ {/* The rankings share the parts' rows, without a swatch (they have no segment)
+ and without a pin: hovering one only lights its own row. */}
{ranking === "tools" ? (
- <ul className="mt-1 space-y-0.5">
- {composition.tools.map((t) => (
- <ShareRow
- key={t.name}
- label={t.name}
- mono
- tokens={t.tokens}
- percent={t.percent}
- highlighted={hovered === `tool:${t.name}`}
- onHover={(on) => setHovered(on ? `tool:${t.name}` : null)}
- />
- ))}
- </ul>
+ <Legend
+ layout="list"
+ mono
+ className="mt-1"
+ items={composition.tools.map((t) => ({
+ key: `tool:${t.name}`,
+ label: t.name,
+ value: <ShareFigures tokens={t.tokens} percent={t.percent} />,
+ }))}
+ active={hovered}
+ onHover={setHovered}
+ />
) : composition.files.length === 0 ? (
<p className="mt-1 text-gray-400 dark:text-gray-500">
{S.chat.contextNoFileTraffic}
</p>
) : (
- <ul className="mt-1 space-y-0.5">
- {composition.files.map((f) => (
- <ShareRow
- key={f.path}
- label={f.name}
- // Two files can share a name; the path settles which is which on hover
- // rather than trailing after every row.
- title={f.path}
- mono
- tokens={f.tokens}
- percent={f.percent}
- highlighted={hovered === `file:${f.path}`}
- onHover={(on) => setHovered(on ? `file:${f.path}` : null)}
- />
- ))}
- </ul>
+ <Legend
+ layout="list"
+ mono
+ className="mt-1"
+ items={composition.files.map((f) => ({
+ key: `file:${f.path}`,
+ label: f.name,
+ // Two files can share a name; the path settles which is which on hover
+ // rather than trailing after every row.
+ title: f.path,
+ value: <ShareFigures tokens={f.tokens} percent={f.percent} />,
+ }))}
+ active={hovered}
+ onHover={setHovered}
+ />
)}
</>
)}
@@ -851,53 +838,14 @@ const PART_LABELS: Record<ContextPartKey, () => string> = {
toolResults: () => S.chat.contextPartToolResults,
};
-/** One `swatch · label · ~tokens · percent` line, shared by the six parts and both rankings. */
-function ShareRow({
- label,
- title,
- swatch,
- tokens,
- percent,
- mono = false,
- highlighted = false,
- pinned = false,
- onHover,
- onSelect,
-}: {
- label: string;
- /** Tooltip of the label, when it should say more than the label does; the label is its own otherwise. */
- title?: string;
- /** Legend colour of the matching bar segment; absent for the rankings, which have no segment. */
- swatch?: string;
- tokens: number;
- /** Already a whole percent (apportioned for the parts, rounded for the rankings) — not re-rounded here. */
- percent: number;
- mono?: boolean;
- highlighted?: boolean;
- /** Pinned rather than merely hovered — the carrier hover never draws, so `aria-pressed` has something to agree with. */
- pinned?: boolean;
- onHover?: (on: boolean) => void;
- /** A click pins the row's highlight (the six parts); the rankings pass none and stay hover-only. */
- onSelect?: () => void;
-}) {
- // The row's own box: padding, rounding and both highlight carriers. It sits on the <li> for a
- // hover-only row and on the <button> for a selectable one, so the two measure identically and
- // the button's hit area is the whole padded row rather than the text inside it.
- const boxClass = `flex items-center gap-1.5 rounded px-1 py-px transition-colors duration-150 ${
- highlighted ? "bg-gray-100 dark:bg-gray-800" : ""
- } ${pinned ? "inset-ring-1 inset-ring-gray-400 dark:inset-ring-gray-600" : ""}`;
- const cells = (
+/**
+ * A share's figures after its label in the legend rows (the six parts and both rankings): the
+ * estimate, and the whole percent — apportioned for the parts, rounded for the rankings, and not
+ * re-rounded here.
+ */
+function ShareFigures({ tokens, percent }: { tokens: number; percent: number }) {
+ return (
<>
- {swatch !== undefined && (
- <span aria-hidden className={`h-2 w-2 shrink-0 rounded-[2px] ${swatch}`} />
- )}
- <span
- data-tooltip={title ?? label}
- data-tooltip-content="code"
- className={`min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300 ${mono ? "font-mono" : ""}`}
- >
- {label}
- </span>
<span className="shrink-0 font-mono font-medium text-gray-900 dark:text-gray-100">
~{humanizeTokens(tokens)}
</span>
@@ -906,27 +854,4 @@ function ShareRow({
</span>
</>
);
- // The bar's segments sit inside its aria-hidden track and stay mouse-only, so the legend is the
- // only surface pinning can be reached from at all: a selectable row is a real button carrying
- // the toggle's state, and the <li> then keeps nothing but the negative margin.
- return (
- <li
- onMouseEnter={() => onHover?.(true)}
- onMouseLeave={() => onHover?.(false)}
- className={onSelect === undefined ? `-mx-1 ${boxClass}` : "-mx-1"}
- >
- {onSelect === undefined ? (
- cells
- ) : (
- <button
- type="button"
- aria-pressed={pinned}
- onClick={onSelect}
- className={`w-full cursor-pointer text-left outline-none focus-visible:ring-2 focus-visible:ring-gray-400/60 ${boxClass}`}
- >
- {cells}
- </button>
- )}
- </li>
- );
}
diff --git a/packages/web/src/features/company/chart-card.tsx b/packages/web/src/features/company/chart-card.tsx
index a8a39e95..9ea1a51e 100644
--- a/packages/web/src/features/company/chart-card.tsx
+++ b/packages/web/src/features/company/chart-card.tsx
@@ -43,6 +43,7 @@ import {
GlyphIcon,
ICONS,
ICON_SIZE,
+ Legend,
useRowContextMenu,
} from "@prismshadow/penguin-ui";
import type { ToneName } from "@prismshadow/penguin-ui";
@@ -82,16 +83,21 @@ export function ChartStateDot({ state }: { state: OrgEmployeeState }) {
export function ChartLegend() {
return (
- <ul
- aria-label={S.company.chart.legend}
- className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-gray-500 dark:text-gray-400"
- >
- {LEGEND_STATES.map((state) => (
- <li key={state} className="flex items-center">
- <ChartStateDot state={state} />
- </li>
- ))}
- </ul>
+ <Legend
+ label={S.company.chart.legend}
+ items={LEGEND_STATES.map((state) => ({
+ key: state,
+ label: S.company.employeeStates[state] ?? state,
+ // Running and on-desk share one tone (busy and success are one emerald); the running
+ // dot is told apart by its pulse.
+ mark: (
+ <Dot
+ tone={employeeStateTone(state) === "attention" ? "attention" : "success"}
+ pulse={state === "running"}
+ />
+ ),
+ }))}
+ />
);
}
@@ -166,7 +172,7 @@ export function ChartCard({
flagged ? "border-red-300 dark:border-red-800" : "border-gray-200 dark:border-gray-700"
}`}
>
- <span className="flex items-center gap-2.5 pr-6">
+ <span className="flex items-center gap-2 pr-6">
<AgentAvatar
id={employee.agentId}
name={employee.name}
@@ -174,18 +180,16 @@ export function ChartCard({
className="shrink-0 rounded-md"
/>
<span className="min-w-0 flex-1">
- <span className="block truncate text-[13px] leading-4 font-semibold text-gray-900 dark:text-gray-100">
+ <span className="block truncate text-sm leading-4 font-semibold text-fg">
{employee.name}
</span>
- <span className="block truncate text-[11px] leading-4 text-gray-500 dark:text-gray-400">
- {employee.title}
- </span>
+ <span className="block truncate text-xs leading-4 text-fg-muted">{employee.title}</span>
</span>
</span>
- <span className="mt-2 flex items-center gap-1.5 text-[11px] leading-4 text-gray-600 dark:text-gray-300">
+ <span className="mt-2 flex items-center gap-1.5 text-xs leading-4 text-gray-600 dark:text-gray-300">
<ChartStateDot state={state} />
<span
- className="flex min-w-0 flex-1 items-center gap-1 font-mono text-[10px] text-gray-400 dark:text-gray-500"
+ className="flex min-w-0 flex-1 items-center gap-1 font-mono text-fg-subtle"
data-tooltip={flag ?? employee.resolvedWorkspace ?? employee.workspace}
>
{flag !== undefined ? (
diff --git a/packages/web/src/features/company/finance-gauge.tsx b/packages/web/src/features/company/finance-gauge.tsx
index 39736e43..494a02c8 100644
--- a/packages/web/src/features/company/finance-gauge.tsx
+++ b/packages/web/src/features/company/finance-gauge.tsx
@@ -3,14 +3,27 @@
* — success below 80%, attention from 80%, danger from 100% — and both leave the amounts to
* the text beside them, carrying the full statement in the accessible name and the tooltip.
*
- * `FinanceGauge` is the KPI row's ring: one arc from 12 o'clock, filled to the ratio and
- * capped at a full circle when spend is over the budget; without a budget the track stands
- * alone. `SpendMeter` is the spend tree's bar, which carries its own percent.
+ * `FinanceGauge` is the KPI row's ring (the package's `Ring`): one arc from 12 o'clock, filled to
+ * the ratio and capped at a full circle when spend is over the budget; without a budget the track
+ * stands alone. `SpendMeter` is the spend tree's bar, which carries its own percent.
*/
+import { Ring } from "@prismshadow/penguin-ui";
+import type { ToneName } from "@prismshadow/penguin-ui";
import { formatPercent } from "../../lib/format";
import { toneDot, toneInk } from "../../lib/tone";
+import type { Tone } from "../../lib/tone";
import { budgetTone } from "./finance-tree";
+/** The budget tones in the ring's words (a gauge without a budget draws no arc to ink). */
+const RING_TONE: Record<Tone, ToneName> = {
+ busy: "success",
+ success: "success",
+ attention: "attention",
+ danger: "danger",
+ link: "info",
+ muted: "neutral",
+};
+
export function FinanceGauge({
ratio,
label,
@@ -22,54 +35,26 @@ export function FinanceGauge({
label: string;
size?: number;
}) {
- const tone = budgetTone(ratio);
- const strokeWidth = Math.max(3, Math.round(size * 0.11));
- const center = size / 2;
- const r = (size - strokeWidth) / 2;
- const c = 2 * Math.PI * r;
const fraction = ratio === undefined ? 0 : Math.min(1, Math.max(0, ratio));
return (
- <svg
- width={size}
- height={size}
- viewBox={`0 0 ${size} ${size}`}
- role="img"
- aria-label={label}
- data-tooltip={label}
- className={`block shrink-0 ${toneInk[tone]}`}
- >
- <circle
- cx={center}
- cy={center}
- r={r}
- fill="none"
- strokeWidth={strokeWidth}
- className="stroke-gray-200 dark:stroke-gray-800"
- />
- {fraction > 0 && (
- <circle
- cx={center}
- cy={center}
- r={r}
- fill="none"
- stroke="currentColor"
- strokeWidth={strokeWidth}
- strokeLinecap={fraction < 1 ? "round" : "butt"}
- strokeDasharray={`${fraction * c} ${c}`}
- transform={`rotate(-90 ${center} ${center})`}
- />
- )}
- </svg>
+ <Ring
+ segments={fraction > 0 ? [{ value: fraction }] : []}
+ max={1}
+ size={size}
+ width={Math.max(3, Math.round(size * 0.11))}
+ tone={RING_TONE[budgetTone(ratio)]}
+ label={label}
+ />
);
}
/**
* The share of the track a fill needs before the percent can sit inside it. The widest label,
- * "100%" at 10px with its padding, is about 30px, and the bar is 80px wide in the one column
- * that draws it — so 45% of the track holds the label, and below that there is room for it to
- * stand past the fill's end without leaving the track.
+ * "100%" at the small text rung with its padding, is about 38px, and the bar is 80px wide in the
+ * one column that draws it — so half the track holds the label, and below that there is room for
+ * it to stand past the fill's end without leaving the track.
*/
-const PERCENT_INSIDE_MIN = 45;
+const PERCENT_INSIDE_MIN = 50;
/**
* Spend against a budget as a bar with its percent drawn on it: the percent rides inside the
@@ -111,7 +96,7 @@ export function SpendMeter({
{ratio !== undefined && (
<span
aria-hidden
- className={`absolute inset-y-0 flex items-center text-[10px] font-medium tabular-nums ${
+ className={`absolute inset-y-0 flex items-center text-xs font-medium tabular-nums ${
inside ? "pr-1.5 text-gray-900" : `pl-1.5 ${toneInk[tone]}`
}`}
style={inside ? { right: `${100 - width}%` } : { left: `${width}%` }}
diff --git a/packages/web/src/features/company/shared.tsx b/packages/web/src/features/company/shared.tsx
index 93680629..abf56523 100644
--- a/packages/web/src/features/company/shared.tsx
+++ b/packages/web/src/features/company/shared.tsx
@@ -25,6 +25,7 @@ import {
Input,
Notice,
ProgressBar,
+ Ring,
} from "@prismshadow/penguin-ui";
import type { BadgeStyle, ToneName } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
@@ -188,10 +189,10 @@ export function ErrorLine({
}
/**
- * Spend against a budget as a ring: the used share drawn clockwise from the top in the
- * budget's tone (attention from 80%, danger from 100%, the ring full when over), the percent
- * inside; a muted, empty ring with a dash when there is no budget. The exact amounts ride in
- * the accessible name and tooltip.
+ * Spend against a budget as a ring (the package's `Ring`): the used share drawn clockwise from
+ * the top in the budget's tone (attention from 80%, danger from 100%, the ring full when over)
+ * over a track of that tone faded, the percent inside; a muted, empty ring with a dash when there
+ * is no budget. The exact amounts ride in the accessible name and tooltip.
*/
export function SpendRing({
cost,
@@ -207,60 +208,34 @@ export function SpendRing({
size?: number;
}) {
const tone = budgetTone(ratio);
- const strokeWidth = Math.max(3, Math.round(size * 0.1));
- const center = size / 2;
- const r = (size - strokeWidth) / 2;
- const c = 2 * Math.PI * r;
const share = ratio === undefined ? 0 : Math.min(1, Math.max(0, ratio));
const label =
budget === undefined
? `${formatMoney(cost, currency)} · ${S.company.noBudget}`
: `${S.company.spendOfBudget(formatMoney(cost, currency), formatMoney(budget, currency))} · ${formatPercent(ratio)}`;
- const ink = tone === "muted" ? "text-gray-300 dark:text-gray-700" : toneInk[tone];
return (
- <svg
- width={size}
- height={size}
- viewBox={`0 0 ${size} ${size}`}
- role="img"
- aria-label={label}
- data-tooltip={label}
- className={`block shrink-0 ${ink}`}
- >
- <circle
- cx={center}
- cy={center}
- r={r}
- fill="none"
- stroke="currentColor"
- strokeOpacity={0.25}
- strokeWidth={strokeWidth}
+ // Without a budget the ring has no tone and takes this span's line ink, track only.
+ <span className={`relative block shrink-0 ${tone === "muted" ? "text-line-emphasis" : ""}`}>
+ <Ring
+ segments={share > 0 ? [{ value: share }] : []}
+ max={1}
+ size={size}
+ width={Math.max(3, Math.round(size * 0.1))}
+ {...(tone !== "muted" ? { tone } : {})}
+ trackOpacity={0.25}
+ label={label}
/>
- {share > 0 && (
- <circle
- cx={center}
- cy={center}
- r={r}
- fill="none"
- stroke="currentColor"
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeDasharray={`${share * c} ${c}`}
- transform={`rotate(-90 ${center} ${center})`}
- />
- )}
- <text
- x={center}
- y={center}
- textAnchor="middle"
- dominantBaseline="central"
- fontSize={Math.round(size * 0.22)}
- fontWeight="600"
- className="fill-gray-700 dark:fill-gray-200"
+ {/* Sized to the ring rather than to a text rung: at the overview's 40px it must fit
+ "100%" inside the stroke. The ring carries the name, so the figure is hidden from
+ assistive technology and lets the pointer through to the ring's tooltip. */}
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-0 flex items-center justify-center leading-none font-semibold text-gray-700 dark:text-gray-200"
+ style={{ fontSize: Math.round(size * 0.22) }}
>
{budget === undefined ? "—" : formatPercent(ratio)}
- </text>
- </svg>
+ </span>
+ </span>
);
}
diff --git a/packages/web/src/features/palette/app-palette.tsx b/packages/web/src/features/palette/app-palette.tsx
index 8782c667..65d073de 100644
--- a/packages/web/src/features/palette/app-palette.tsx
+++ b/packages/web/src/features/palette/app-palette.tsx
@@ -1,21 +1,41 @@
/**
- * The app's command palette and its actions. Mounted once in AppLayout; the palette is
- * the mechanism, this file is the registry: an action here, never a new global shortcut.
- * An action opens an overlay over the current page rather than navigating — closing it
- * leaves the user exactly where they were.
+ * The app's command palette: which actions exist, the shortcut that opens it (the
+ * `palette.toggle` command, ⌥⌘P / Ctrl+Alt+P by default), and its words. Mounted once in
+ * AppLayout. The UI package's CommandPalette is the mechanism; this file is the registry: an
+ * action here, never a new global shortcut. An action opens an overlay over the current page
+ * rather than navigating — closing it leaves the user exactly where they were.
*/
-import { useMemo, useState } from "react";
-import type { PaletteAction } from "../../lib/command-palette";
+import { useEffect, useMemo, useState } from "react";
+import { CommandPalette } from "@prismshadow/penguin-ui";
+import type { PaletteAction } from "@prismshadow/penguin-ui";
+import { onCommand } from "../../lib/shortcuts/dispatcher";
+import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { S } from "../../lib/strings";
import { HarnessHistoryOverlay } from "../harness/harness-history-overlay";
-import { CommandPalette } from "./command-palette";
+
+/** A mount point with nothing to add shares one empty list, so the action memo stays put. */
+const NO_EXTRA: readonly PaletteAction[] = [];
/**
* `extra` is what the mount point adds ahead of the standing actions — the full-page
* workflow route registers its way out here, which is why it exists at all on that route.
*/
-export function AppPalette({ extra = [] }: { extra?: readonly PaletteAction[] }) {
+export function AppPalette({ extra = NO_EXTRA }: { extra?: readonly PaletteAction[] }) {
+ const [open, setOpen] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
+
+ // The chord is the keymap's (lib/shortcuts): the window dispatcher matches it, calls this
+ // handler and prevents the browser default once it is handled. A functional update reads
+ // the latest `open`, so the handler registers once.
+ useEffect(
+ () =>
+ onCommand("palette.toggle", () => {
+ setOpen((o) => !o);
+ }),
+ [],
+ );
+ const toggleShortcut = useShortcutLabel("palette.toggle");
+
const actions = useMemo<PaletteAction[]>(
() => [
...extra,
@@ -30,7 +50,15 @@ export function AppPalette({ extra = [] }: { extra?: readonly PaletteAction[] })
);
return (
<>
- <CommandPalette actions={actions} />
+ <CommandPalette
+ open={open}
+ onClose={() => setOpen(false)}
+ actions={actions}
+ title={S.commandPalette.title}
+ placeholder={S.commandPalette.placeholder}
+ emptyText={S.commandPalette.noResults}
+ hint={S.commandPalette.hint(toggleShortcut)}
+ />
<HarnessHistoryOverlay open={historyOpen} onClose={() => setHistoryOpen(false)} />
</>
);
diff --git a/packages/web/src/features/palette/command-palette.tsx b/packages/web/src/features/palette/command-palette.tsx
deleted file mode 100644
index a5e8ebcb..00000000
--- a/packages/web/src/features/palette/command-palette.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * The command palette (the `palette.toggle` shortcut, ⌥⌘P / Ctrl+Alt+P by default), VSCode-style:
- * a top-centered input filtering a list of actions; Enter (or click) runs the selected one. The
- * palette is mechanism only — its actions come from the mount point (app-palette.tsx), so a new
- * capability registers an action instead of claiming another global shortcut.
- *
- * Keyboard model: ArrowUp/ArrowDown move the selection (wrapping), Enter runs, Escape
- * closes through the shared esc-layer stack (the UI package's esc-layers), and the shortcut
- * that opened it toggles it closed. Filtering is filterPaletteActions (lib/command-palette.ts).
- */
-import { useEffect, useRef, useState } from "react";
-import { createPortal } from "react-dom";
-import { useDialogLayer } from "@prismshadow/penguin-ui";
-import { filterPaletteActions, type PaletteAction } from "../../lib/command-palette";
-import { onCommand } from "../../lib/shortcuts/dispatcher";
-import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
-import { S } from "../../lib/strings";
-
-export function CommandPalette({ actions }: { actions: readonly PaletteAction[] }) {
- const [open, setOpen] = useState(false);
- const [query, setQuery] = useState("");
- const [selected, setSelected] = useState(0);
-
- // The chord is the keymap's (lib/shortcuts): the window dispatcher matches it, calls this
- // handler and prevents the browser default once it is handled. A functional update reads
- // the latest `open`, so the handler registers once.
- useEffect(
- () =>
- onCommand("palette.toggle", () => {
- setOpen((o) => !o);
- setQuery("");
- setSelected(0);
- }),
- [],
- );
- const toggleShortcut = useShortcutLabel("palette.toggle");
-
- // Escape closes it only while it is the topmost esc-consuming layer (shared with Modal /
- // Dropdown, see the UI package's esc-layers), so an action's own dialog above it gets its
- // Escape first; Tab stays inside the panel, and closing hands focus back to where it was.
- const panelRef = useRef<HTMLDivElement>(null);
- const { onKeyDown: onPanelKeyDown } = useDialogLayer(open, panelRef, () => setOpen(false));
-
- if (!open) return null;
-
- const filtered = filterPaletteActions(actions, query);
- const sel = Math.min(selected, Math.max(filtered.length - 1, 0));
-
- const runAction = (action: PaletteAction) => {
- // Close first: an action may open its own overlay and expects the palette gone.
- setOpen(false);
- action.run();
- };
-
- const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
- if (e.key === "ArrowDown" || e.key === "ArrowUp") {
- e.preventDefault();
- if (filtered.length === 0) return;
- const delta = e.key === "ArrowDown" ? 1 : -1;
- setSelected((sel + delta + filtered.length) % filtered.length);
- } else if (e.key === "Enter") {
- e.preventDefault();
- const action = filtered[sel];
- if (action !== undefined) runAction(action);
- }
- };
-
- return createPortal(
- <div
- // z-50 like Modal's overlay: a portaled menu or tooltip (z-[60]) opened from inside still paints above it.
- // ui-scrim: the overlay is the dimmed layer, with the palette inside it.
- className="ui-scrim anim-fade fixed inset-0 z-50 flex justify-center bg-black/45 px-4 pt-[10vh]"
- onMouseDown={(e) => {
- if (e.target === e.currentTarget) setOpen(false);
- }}
- >
- <div
- ref={panelRef}
- role="dialog"
- aria-modal="true"
- aria-label={S.commandPalette.title}
- tabIndex={-1}
- onKeyDown={onPanelKeyDown}
- className="anim-pop h-fit w-full max-w-md overflow-hidden rounded-lg border border-gray-200 bg-white shadow-xl dark:border-gray-800 dark:bg-gray-900"
- >
- <input
- autoFocus
- value={query}
- onChange={(e) => {
- setQuery(e.target.value);
- setSelected(0);
- }}
- onKeyDown={onInputKeyDown}
- placeholder={S.commandPalette.placeholder}
- aria-label={S.commandPalette.placeholder}
- className="w-full border-b border-gray-200 bg-transparent px-4 py-3 text-sm outline-none placeholder:text-gray-400 dark:border-gray-800 dark:placeholder:text-gray-500"
- />
- {filtered.length === 0 ? (
- <p className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
- {S.commandPalette.noResults}
- </p>
- ) : (
- <ul className="max-h-[40vh] overflow-y-auto py-1" role="listbox">
- {filtered.map((action, i) => (
- <li key={action.id} role="option" aria-selected={i === sel}>
- <button
- type="button"
- className={`w-full px-4 py-2 text-left text-sm ${
- i === sel
- ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
- : "text-gray-700 dark:text-gray-300"
- }`}
- onMouseEnter={() => setSelected(i)}
- onClick={() => runAction(action)}
- >
- {action.label}
- </button>
- </li>
- ))}
- </ul>
- )}
- <div className="border-t border-gray-200 px-4 py-2 text-right text-xs text-gray-400 dark:border-gray-800 dark:text-gray-500">
- {S.commandPalette.hint(toggleShortcut)}
- </div>
- </div>
- </div>,
- document.body,
- );
-}
diff --git a/packages/web/src/features/traces/timeline-chart.tsx b/packages/web/src/features/traces/timeline-chart.tsx
index 6f75a3f0..28d5fcfd 100644
--- a/packages/web/src/features/traces/timeline-chart.tsx
+++ b/packages/web/src/features/traces/timeline-chart.tsx
@@ -29,12 +29,12 @@ import type {
TraceOtherSpan,
TraceToolSpan,
} from "@prismshadow/penguin-server/api";
-import { namedHint } from "@prismshadow/penguin-ui";
+import { Dot, Legend, TimelineBar, namedHint } from "@prismshadow/penguin-ui";
+import type { ChartPaint, LegendItem } from "@prismshadow/penguin-ui";
import { S } from "../../lib/strings";
import { humanizeDuration } from "../../lib/format";
import { packToolLanes, toolSpanBounds } from "./lane-packing";
import type { PackedLane } from "./lane-packing";
-import { ChartSwatch, TimelineBar, type ChartPaint } from "../../components/ui/chart";
/**
* Linked highlighting: `ts` is the anchor shared by both sides; `key` /
@@ -55,8 +55,8 @@ export interface TraceHighlight {
}
/**
- * The theme's palette slot each of the five bar kinds paints with (0-based; see
- * lib/chart-style.ts): thinking violet, model reply sky, tool-call generation amber, approval
+ * The theme's palette slot each of the five bar kinds paints with (0-based; see the UI
+ * package's chart style): thinking violet, model reply sky, tool-call generation amber, approval
* wait rose, tool execution emerald. Identities, not judgements, so every theme keeps them and
* picks its own shade of each.
*/
@@ -87,7 +87,7 @@ const kindPaint = (kind: BarKind): ChartPaint =>
const LABEL_STICKY =
"sticky left-0 z-10 flex h-4 w-[5.5rem] shrink-0 items-center justify-end bg-white pr-2 dark:bg-gray-950";
/** Label text (truncated when too long). */
-const LABEL_TEXT = "truncate font-mono text-[11px]";
+const LABEL_TEXT = "truncate font-mono text-xs";
/** Zoom range (time-axis multiplier). */
const ZOOM_MIN = 0.25;
const ZOOM_MAX = 24;
@@ -297,7 +297,7 @@ function Ticks({ total }: { total: number }) {
{fracs.map((f, i) => (
<span
key={i}
- className={`absolute top-0 font-mono text-[11px] text-gray-400 dark:text-gray-500 ${
+ className={`absolute top-0 font-mono text-xs text-fg-subtle ${
i === 0 ? "" : i === fracs.length - 1 ? "-translate-x-full" : "-translate-x-1/2"
}`}
style={{ left: `${f * 100}%` }}
@@ -310,6 +310,20 @@ function Ticks({ total }: { total: number }) {
);
}
+/**
+ * The mark on a bar that is still open: an approval still pending, a tool still running. An open
+ * bar always runs to its lane's right edge (its end is the chart's "now"), so the mark sits there —
+ * a pulsing state dot, the live signal a theme can re-time, while the bar itself holds still.
+ * `dim` is the bar's fade, so a highlight elsewhere fades the mark with its bar.
+ */
+function LiveEnd({ tone, dim }: { tone: "attention" | "success"; dim: string }) {
+ return (
+ <span className={`pointer-events-none absolute inset-y-0 right-0.5 flex items-center ${dim}`}>
+ <Dot tone={tone} pulse />
+ </span>
+ );
+}
+
/** The default for a caller with no other spans: one shared array, so the grouping memo (and the
* view effect keyed on it) stays put across renders instead of rerunning on a fresh `[]`. */
const NO_OTHER_SPANS: TraceOtherSpan[] = [];
@@ -456,13 +470,19 @@ export function TimelineChart({
return { left: `${left}%`, width: `${width}%` };
};
- const legendChips: Array<{ key: BarKind; label: string }> = [
- { key: "thinking", label: S.traces.kindThinking },
- { key: "text", label: S.traces.kindModelReply },
- { key: "toolgen", label: S.traces.kindToolGen },
- { key: "approvalWait", label: S.traces.legendApprovalWait },
- { key: "exec", label: S.traces.legendToolExec },
- { key: "other", label: S.traces.legendOther },
+ const legendItem = (key: BarKind, label: string): LegendItem => ({
+ key,
+ label,
+ paint: kindPaint(key),
+ shape: "chip",
+ });
+ const legendItems = [
+ legendItem("thinking", S.traces.kindThinking),
+ legendItem("text", S.traces.kindModelReply),
+ legendItem("toolgen", S.traces.kindToolGen),
+ legendItem("approvalWait", S.traces.legendApprovalWait),
+ legendItem("exec", S.traces.legendToolExec),
+ legendItem("other", S.traces.legendOther),
];
// —— Slider (Premiere-style): drag the body to pan, drag either handle to zoom, double-click to reset ——
@@ -557,10 +577,10 @@ export function TimelineChart({
<div key={g.taskIndex} className="space-y-1">
{!hideTaskLabel && (
<div className="flex items-center gap-2 pl-[5.5rem]">
- <span className="rounded bg-gray-100 px-1.5 py-0.5 text-[11px] font-medium text-gray-500 dark:bg-gray-800 dark:text-gray-400">
+ <span className="rounded bg-gray-100 px-1.5 py-0.5 text-xs font-medium text-fg-muted dark:bg-gray-800">
{S.traces.task(g.taskIndex + 1)}
</span>
- <span className="font-mono text-[11px] text-gray-400">
+ <span className="font-mono text-xs text-gray-400">
{humanizeDuration(g.total)}
</span>
</div>
@@ -626,26 +646,28 @@ export function TimelineChart({
place={placeExact(s.callMs, s.approvalMs, g.t0, g.total)}
/>
)}
- {/* Whole-segment pulse while approval is pending / execution segment */}
+ {/* Approval still pending (with its live mark) / execution segment */}
{s.approvalMs === null && open
? (() => {
- // animate-pulse's keyframes override the static opacity: the pulse animation must be removed when fading out.
const dim = dimClass(
isActive(`p-${s.toolCallId}`),
legendKey === null || legendKey === "approvalWait",
);
return (
- <TimelineBar
- onMouseEnter={() => enter(`p-${s.toolCallId}`, s.callTs)}
- onMouseLeave={leave}
- onClick={() => onJump?.(s.callTs)}
- {...namedHint(
- `${s.name} · ${S.traces.legendApprovalWait} · ${S.traces.inProgress}`,
- )}
- className={`cursor-pointer ${dim || "animate-pulse"}`}
- paint={kindPaint("approvalWait")}
- place={placeExact(s.callMs, endMs, g.t0, g.total)}
- />
+ <>
+ <TimelineBar
+ onMouseEnter={() => enter(`p-${s.toolCallId}`, s.callTs)}
+ onMouseLeave={leave}
+ onClick={() => onJump?.(s.callTs)}
+ {...namedHint(
+ `${s.name} · ${S.traces.legendApprovalWait} · ${S.traces.inProgress}`,
+ )}
+ className={`cursor-pointer ${dim}`}
+ paint={kindPaint("approvalWait")}
+ place={placeExact(s.callMs, endMs, g.t0, g.total)}
+ />
+ <LiveEnd tone="attention" dim={dim} />
+ </>
);
})()
: (() => {
@@ -656,23 +678,26 @@ export function TimelineChart({
);
const running = open && !dim;
return (
- <TimelineBar
- onMouseEnter={() => enter(`e-${s.toolCallId}`, execTs)}
- onMouseLeave={leave}
- onClick={() => onJump?.(execTs)}
- {...namedHint(
- `${s.name} · ${S.traces.legendToolExec} · ${
- open
- ? S.traces.inProgress
- : humanizeDuration(endMs - execStart)
- }${s.failed ? ` · ${s.status}` : ""}`,
- )}
- className={`cursor-pointer ${
- s.failed ? "ring-1 ring-red-500" : ""
- } ${running ? "animate-pulse opacity-70" : dim}`}
- paint={kindPaint("exec")}
- place={placeExact(execStart, endMs, g.t0, g.total)}
- />
+ <>
+ <TimelineBar
+ onMouseEnter={() => enter(`e-${s.toolCallId}`, execTs)}
+ onMouseLeave={leave}
+ onClick={() => onJump?.(execTs)}
+ {...namedHint(
+ `${s.name} · ${S.traces.legendToolExec} · ${
+ open
+ ? S.traces.inProgress
+ : humanizeDuration(endMs - execStart)
+ }${s.failed ? ` · ${s.status}` : ""}`,
+ )}
+ className={`cursor-pointer ${
+ s.failed ? "ring-1 ring-red-500" : ""
+ } ${running ? "opacity-70" : dim}`}
+ paint={kindPaint("exec")}
+ place={placeExact(execStart, endMs, g.t0, g.total)}
+ />
+ {open && <LiveEnd tone="success" dim={dim} />}
+ </>
);
})()}
</Fragment>
@@ -725,26 +750,13 @@ export function TimelineChart({
</div>
{/* Legend: hovering highlights matching segments — same convention as the bars, non-matching items fade out, no background color */}
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-gray-100 pt-2.5 dark:border-gray-800">
- {legendChips.map((c) => (
- <button
- key={c.key}
- type="button"
- onMouseEnter={() => setLegendKey(c.key)}
- onMouseLeave={() => setLegendKey(null)}
- className={`flex items-center gap-1 px-1 font-mono text-[11px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${
- legendKey !== null && legendKey !== c.key ? "opacity-30" : ""
- }`}
- >
- <ChartSwatch paint={kindPaint(c.key)} shape="chip" />
- {c.label}
- </button>
- ))}
+ <div className="border-t border-line-muted pt-2.5">
+ <Legend items={legendItems} active={legendKey} onHover={setLegendKey} />
</div>
{/* Premiere-style zoom/pan slider: drag the body to pan, drag either handle to zoom, double-click to reset; −/+ covers the full range from <1 to >1 */}
<div className="flex items-center gap-2">
- <span className="shrink-0 text-[11px] text-gray-400">{S.traces.zoom}</span>
+ <span className="shrink-0 text-xs text-gray-400">{S.traces.zoom}</span>
<button
type="button"
aria-label={S.traces.zoomOut}
@@ -752,7 +764,7 @@ export function TimelineChart({
onClick={() => zoomStep(1 / 1.4)}
className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"
>
- <span className="text-[11px] leading-none">−</span>
+ <span className="text-xs leading-none">−</span>
</button>
<div
ref={trackRef}
@@ -784,15 +796,15 @@ export function TimelineChart({
onClick={() => zoomStep(1.4)}
className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"
>
- <span className="text-[11px] leading-none">+</span>
+ <span className="text-xs leading-none">+</span>
</button>
- <span className="w-9 shrink-0 text-right font-mono text-[11px] tabular-nums text-gray-400">
+ <span className="w-9 shrink-0 text-right font-mono text-xs tabular-nums text-gray-400">
{zoom.toFixed(2)}×
</span>
</div>
{onHighlight && (
- <p className="text-[11px] text-gray-400 dark:text-gray-600">{S.traces.linkHint}</p>
+ <p className="text-xs text-gray-400 dark:text-gray-600">{S.traces.linkHint}</p>
)}
</div>
);
diff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsx
index 30b1103e..f79c0b32 100644
--- a/packages/web/src/features/traces/trace-file-view.tsx
+++ b/packages/web/src/features/traces/trace-file-view.tsx
@@ -40,6 +40,7 @@ import {
GlyphIcon,
Skeleton,
StatChip,
+ TokenDonut,
} from "@prismshadow/penguin-ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
@@ -57,7 +58,6 @@ import {
import { STAT_ICONS } from "../../lib/stat-icons";
import { resolveContextWindow } from "../../lib/context";
import { useTheme } from "../../state/theme";
-import { TokenDonut } from "../../components/ui/token-donut";
import { TRACE_EVENT_PAGE_SIZE, loadTraceEventPages } from "./trace-events-loader";
import { TimelineChart } from "./timeline-chart";
import type { TraceHighlight } from "./timeline-chart";
@@ -641,6 +641,13 @@ export function TraceFileView({
output={ctx.output}
max={contextMax}
size={22}
+ labels={{
+ usage: S.chat.contextUsage,
+ cacheRead: S.usage.colCacheRead,
+ cacheWrite: S.usage.colCacheWrite,
+ output: S.usage.colOutput,
+ }}
+ format={humanizeTokens}
/>
)}
</button>
diff --git a/packages/web/src/features/usage/trend-chart.tsx b/packages/web/src/features/usage/trend-chart.tsx
index e1a1b2b9..f4ea1d08 100644
--- a/packages/web/src/features/usage/trend-chart.tsx
+++ b/packages/web/src/features/usage/trend-chart.tsx
@@ -19,11 +19,18 @@
*/
import { useState } from "react";
import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";
+import {
+ ChartArea,
+ ChartFrame,
+ ChartLine,
+ ChartPoint,
+ makeGeom,
+ seriesPoints,
+ useChartWidth,
+} from "@prismshadow/penguin-ui";
+import type { ChartPaint } from "@prismshadow/penguin-ui";
import { formatMoney } from "../../lib/format";
import type { Currency } from "../../state/theme";
-import { makeGeom, seriesPoints } from "./chart-geom";
-import { ChartFrame, useChartWidth } from "./chart-svg";
-import { ChartArea, ChartLine, ChartPoint, type ChartPaint } from "../../components/ui/chart";
import { bucketAxisLabel, bucketFullLabel } from "./usage-controls";
import { Empty } from "./usage-charts";
diff --git a/packages/web/src/features/usage/usage-charts.tsx b/packages/web/src/features/usage/usage-charts.tsx
index dbd9d3ed..e175ad6b 100644
--- a/packages/web/src/features/usage/usage-charts.tsx
+++ b/packages/web/src/features/usage/usage-charts.tsx
@@ -38,29 +38,29 @@
*/
import { useState } from "react";
import type { UsageGranularity, UsageSeriesPoint } from "@prismshadow/penguin-server/api";
-import { S } from "../../lib/strings";
-import { formatPercent, humanizeTokens } from "../../lib/format";
-import { NEUTRAL_SERIES } from "../../lib/category-colors";
import {
ChartBar,
ChartBarHit,
+ ChartFrame,
ChartHit,
ChartLine,
ChartPoint,
ChartSwatch,
- type ChartPaint,
-} from "../../components/ui/chart";
-import {
- makeGeom,
- makeRangeGeom,
+ Legend,
+ LineHits,
+ PAD_R_AXIS,
autoLabelIdx,
barSegments,
+ makeGeom,
+ makeRangeGeom,
seriesPoints,
stackSegments,
- PAD_R_AXIS,
- type TokenBucketKey,
-} from "./chart-geom";
-import { ChartFrame, LineHits, useChartWidth } from "./chart-svg";
+ useChartWidth,
+} from "@prismshadow/penguin-ui";
+import type { ChartPaint, LegendItem, TokenBucketKey } from "@prismshadow/penguin-ui";
+import { S } from "../../lib/strings";
+import { formatPercent, humanizeTokens } from "../../lib/format";
+import { NEUTRAL_SERIES } from "../../lib/category-colors";
import {
bucketAxisLabel,
bucketFullLabel,
@@ -139,28 +139,26 @@ function RequestsLegend({
active: number | null;
onHover: (i: number | null) => void;
}) {
+ const items: LegendItem[] = [
+ ...entities.map((e, i) => ({ key: String(i), label: e.label, paint: entityPaint(e, i) })),
+ // 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".
+ {
+ key: "successRate",
+ label: S.usage.legendSuccessRate,
+ paint: NEUTRAL_PAINT,
+ shape: "dash",
+ interactive: false,
+ },
+ ];
return (
- <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" : ""
- }`}
- >
- <ChartSwatch paint={entityPaint(e, i)} />
- <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">
- <ChartSwatch paint={NEUTRAL_PAINT} shape="dash" />
- {S.usage.legendSuccessRate}
- </span>
- </div>
+ <Legend
+ items={items}
+ mono
+ active={active === null ? null : String(active)}
+ onHover={(key) => onHover(key === null ? null : Number(key))}
+ className="mt-1.5"
+ />
);
}
@@ -594,36 +592,26 @@ export function TokenLegend({
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 bucket = (key: TokenBucketKey, label: string): LegendItem => ({
+ key,
+ label,
+ paint: tokenPaint(key),
+ shape: "chip",
+ });
+ const items: LegendItem[] = [
+ bucket("cacheRead", S.usage.colCacheRead),
+ bucket("cacheWrite", S.usage.colCacheWrite),
+ bucket("output", S.usage.colOutput),
+ // The curve's item wears a line-shaped swatch: it is a line on its own axis, not a fourth
+ // stack segment.
+ { key: "hitRate", label: S.usage.legendHitRate, paint: HIT_RATE_PAINT, shape: "dash" },
];
- 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]) => (
- <button
- key={key}
- 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 ${dim(key)}`}
- >
- <ChartSwatch paint={tokenPaint(key)} shape="chip" />
- {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")}`}
- >
- <ChartSwatch paint={HIT_RATE_PAINT} shape="dash" />
- {S.usage.legendHitRate}
- </button>
- </div>
+ <Legend
+ items={items}
+ active={active ?? null}
+ // The items' keys are the legend keys, so the key a hover reports is one of them.
+ onHover={onHover && ((key) => onHover(key as TokenLegendKey | null))}
+ />
);
}
diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsx
index af57a8f3..7733630a 100644
--- a/packages/web/src/features/usage/usage-page.tsx
+++ b/packages/web/src/features/usage/usage-page.tsx
@@ -28,7 +28,14 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router";
import type { ModelRefDto, UsageBucket, UsageResponse } from "@prismshadow/penguin-server/api";
-import { Input, Select, Skeleton, TodoNotice } from "@prismshadow/penguin-ui";
+import {
+ Input,
+ PageFrame,
+ PageHeader,
+ Select,
+ Skeleton,
+ TodoNotice,
+} from "@prismshadow/penguin-ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
@@ -94,7 +101,7 @@ function SummaryCard({
return (
<div className="rounded-md border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
<p className="mb-1.5 text-xs font-medium text-gray-500 dark:text-gray-400">{title}</p>
- <div className="space-y-0.5">
+ <div className="space-y-1">
<SummaryRow label={S.usage.tokens} value={humanizeTokens(bucket.total)} />
<SummaryRow label={S.usage.requests} value={String(bucket.requests)} muted />
{/* The unpriced-records asterisk sits on the word "cost" (superscript), keeping the number clean and readable; see the footer for the explanation */}
@@ -275,12 +282,13 @@ export function UsagePage() {
...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">
- {/* Top filters: controls have no external title (the explanation is written into the "all …" option), so they're baseline-centered with the page title */}
- <div className="flex flex-wrap items-center justify-between gap-3">
- <h1 className="ui-display text-xl font-semibold">{S.usage.title}</h1>
- <div className="flex flex-wrap items-center gap-2">
+ <PageFrame contentClassName="space-y-4">
+ {/* The filters are the header's actions: they carry no external title (the explanation is
+ written into the "all …" option), so they sit centred on the title row. */}
+ <PageHeader
+ title={S.usage.title}
+ actions={
+ <>
<div className="w-32">
<Select
size="sm"
@@ -363,110 +371,110 @@ export function UsagePage() {
/>
</div>
)}
- </div>
- </div>
+ </>
+ }
+ />
- {/* Last stop on the Cost Center trail, in the one shape all four dismissible trails
- use: directly under the title, not down against the errors table. It counts the
- probe's own trailing window (use-project-todos.ts), which is not the filters above
- it, so it states what the badge is about rather than what any one panel is showing.
- "Read", not "done" — nothing is being updated here, the user has simply looked, and
- this is the one of the four that offers no bulk action: a past error cannot be
- updated, so the block renders the dismiss control alone. */}
- {todo && (
- <TodoNotice
- text={S.todo.unexpectedErrors(todo.count)}
- dismissLabel={S.todo.markRead}
- onDismiss={() => dismissTodo(projectId, "errors", todo.signature)}
- />
- )}
-
- {/* Summary cards (today / last 7 days / cumulative) */}
- {data ? (
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <SummaryCard title={S.usage.today} bucket={data.summary.today} currency={currency} />
- <SummaryCard title={S.usage.last7d} bucket={data.summary.last7d} currency={currency} />
- <SummaryCard title={S.usage.total} bucket={data.summary.total} currency={currency} />
- </div>
- ) : (
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
- <Skeleton className="h-24" />
- <Skeleton className="h-24" />
- <Skeleton className="h-24" />
- </div>
- )}
+ {/* Last stop on the Cost Center trail, in the one shape all four dismissible trails
+ use: directly under the title, not down against the errors table. It counts the
+ probe's own trailing window (use-project-todos.ts), which is not the filters above
+ it, so it states what the badge is about rather than what any one panel is showing.
+ "Read", not "done" — nothing is being updated here, the user has simply looked, and
+ this is the one of the four that offers no bulk action: a past error cannot be
+ updated, so the block renders the dismiss control alone. */}
+ {todo && (
+ <TodoNotice
+ text={S.todo.unexpectedErrors(todo.count)}
+ dismissLabel={S.todo.markRead}
+ onDismiss={() => dismissTodo(projectId, "errors", todo.signature)}
+ />
+ )}
- {/* 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.chartRequestsByAgent}>
- <RequestsChart
- series={plotted.points}
- entities={agentEntities}
- granularity={data.granularity}
- breaks={plotted.breaks}
- />
- </ChartCard>
- <ChartCard title={S.usage.chartRequestsByModel}>
- <RequestsChart
- series={plotted.points}
- entities={modelEntities}
- granularity={data.granularity}
- breaks={plotted.breaks}
- />
- </ChartCard>
- {/* The Token legend lives in its card header while its marks live inside the card, so that state is lifted to this level */}
- <ChartCard
- title={S.usage.chartTokenTrend}
- extra={<TokenLegend active={tokenBucket} onHover={setTokenBucket} />}
- >
- <TokenBarChart
- series={plotted.points}
- granularity={data.granularity}
- legend={tokenBucket}
- breaks={plotted.breaks}
- />
- </ChartCard>
- <ChartCard title={S.usage.chartCostTrend}>
- <TrendChart
- series={plotted.points}
- granularity={data.granularity}
- currency={currency}
- breaks={plotted.breaks}
- />
- </ChartCard>
- </div>
- ) : (
- <Skeleton className="h-64" />
- )}
+ {/* Summary cards (today / last 7 days / cumulative) */}
+ {data ? (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <SummaryCard title={S.usage.today} bucket={data.summary.today} currency={currency} />
+ <SummaryCard title={S.usage.last7d} bucket={data.summary.last7d} currency={currency} />
+ <SummaryCard title={S.usage.total} bucket={data.summary.total} currency={currency} />
+ </div>
+ ) : (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <Skeleton className="h-24" />
+ <Skeleton className="h-24" />
+ <Skeleton className="h-24" />
+ </div>
+ )}
- {/* Errors (a single full-width panel: stats + a recent-errors table) */}
- {data && (
- <ChartCard title={S.usage.errors}>
- <ErrorsPanel
- errors={data.errors}
- projectId={projectId}
- filters={errorFilters}
- preset={loaded.preset === "custom" ? undefined : loaded.preset}
- // Clearing the log is a Project-level management operation, gated on the owner
- // by the route; a member reads the panel without the action.
- canClear={currentProject?.role === "owner"}
- // The badge and the notice above are gated on a probe cached per Project for the
- // browser session, not on this response — without the re-probe an emptied table
- // would sit under a dot still pointing at the rows that just went.
- onCleared={() => {
- refreshProjectTodos(projectId);
- void load();
- }}
+ {/* 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.chartRequestsByAgent}>
+ <RequestsChart
+ series={plotted.points}
+ entities={agentEntities}
+ granularity={data.granularity}
+ breaks={plotted.breaks}
+ />
+ </ChartCard>
+ <ChartCard title={S.usage.chartRequestsByModel}>
+ <RequestsChart
+ series={plotted.points}
+ entities={modelEntities}
+ granularity={data.granularity}
+ breaks={plotted.breaks}
/>
</ChartCard>
- )}
+ {/* The Token legend lives in its card header while its marks live inside the card, so that state is lifted to this level */}
+ <ChartCard
+ title={S.usage.chartTokenTrend}
+ extra={<TokenLegend active={tokenBucket} onHover={setTokenBucket} />}
+ >
+ <TokenBarChart
+ series={plotted.points}
+ granularity={data.granularity}
+ legend={tokenBucket}
+ breaks={plotted.breaks}
+ />
+ </ChartCard>
+ <ChartCard title={S.usage.chartCostTrend}>
+ <TrendChart
+ series={plotted.points}
+ granularity={data.granularity}
+ currency={currency}
+ breaks={plotted.breaks}
+ />
+ </ChartCard>
+ </div>
+ ) : (
+ <Skeleton className="h-64" />
+ )}
- {hasUncostedRows && <p className="text-xs text-gray-400">{S.usage.uncostedNote}</p>}
- {error && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
- </div>
- </div>
+ {/* Errors (a single full-width panel: stats + a recent-errors table) */}
+ {data && (
+ <ChartCard title={S.usage.errors}>
+ <ErrorsPanel
+ errors={data.errors}
+ projectId={projectId}
+ filters={errorFilters}
+ preset={loaded.preset === "custom" ? undefined : loaded.preset}
+ // Clearing the log is a Project-level management operation, gated on the owner
+ // by the route; a member reads the panel without the action.
+ canClear={currentProject?.role === "owner"}
+ // The badge and the notice above are gated on a probe cached per Project for the
+ // browser session, not on this response — without the re-probe an emptied table
+ // would sit under a dot still pointing at the rows that just went.
+ onCleared={() => {
+ refreshProjectTodos(projectId);
+ void load();
+ }}
+ />
+ </ChartCard>
+ )}
+
+ {hasUncostedRows && <p className="text-xs text-gray-400">{S.usage.uncostedNote}</p>}
+ {error && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
+ </PageFrame>
);
}
diff --git a/packages/web/src/features/workflows/workflow-app-page.tsx b/packages/web/src/features/workflows/workflow-app-page.tsx
index 78412d92..f2042461 100644
--- a/packages/web/src/features/workflows/workflow-app-page.tsx
+++ b/packages/web/src/features/workflows/workflow-app-page.tsx
@@ -12,8 +12,8 @@
*/
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router";
+import type { PaletteAction } from "@prismshadow/penguin-ui";
import * as api from "../../api/endpoints";
-import type { PaletteAction } from "../../lib/command-palette";
import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { S } from "../../lib/strings";
import {
diff --git a/packages/web/src/lib/command-palette.ts b/packages/web/src/lib/command-palette.ts
deleted file mode 100644
index 0219a52d..00000000
--- a/packages/web/src/lib/command-palette.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Command palette pure logic: the action filter, kept apart from the component so it is
- * testable without a DOM. The chord that opens the palette is the registry's `palette.toggle`
- * (lib/shortcuts), matched by the window dispatcher.
- */
-
-export interface PaletteAction {
- id: string;
- label: string;
- /** Searchable words beyond the label (an English alias under a Chinese label, say). */
- keywords?: readonly string[];
- run: () => void;
-}
-
-/**
- * Palette filtering, VSCode-style-lite: every whitespace-separated query token must appear
- * (case-insensitive substring) in the label or a keyword, in any order. Predictable over
- * fuzzy for a handful of actions; an empty query lists everything in registration order.
- */
-export function filterPaletteActions<A extends { label: string; keywords?: readonly string[] }>(
- actions: readonly A[],
- query: string,
-): A[] {
- const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);
- if (tokens.length === 0) return [...actions];
- return actions.filter((a) => {
- const hay = [a.label, ...(a.keywords ?? [])].join(" ").toLowerCase();
- return tokens.every((t) => hay.includes(t));
- });
-}
diff --git a/packages/web/src/lib/stream-style.ts b/packages/web/src/lib/stream-style.ts
index 79706569..66dd1b8d 100644
--- a/packages/web/src/lib/stream-style.ts
+++ b/packages/web/src/lib/stream-style.ts
@@ -8,11 +8,11 @@
* - `--ui-stream-rate`: characters per second of a paced reveal (`fade` paces its words at this
* rate too). Missing, zero or not a number → no pacing.
*
- * Read the way lib/chart-style.ts reads the chart tokens: one MutationObserver on <html> drops
- * the cached record when the theme, mode or accent changes, a subscriber gets the same object
- * while nothing it reads changed, and nothing here ever writes. The record also carries the
- * gallery's reduced-motion switch (`data-motion="reduced"` on <html>), the second of the two
- * signals the theme CSS honours beside the media query.
+ * Read the way the UI package's useChartStyle reads the chart tokens: one MutationObserver on
+ * <html> drops the cached record when the theme, mode or accent changes, a subscriber gets the
+ * same object while nothing it reads changed, and nothing here ever writes. The record also
+ * carries the gallery's reduced-motion switch (`data-motion="reduced"` on <html>), the second of
+ * the two signals the theme CSS honours beside the media query.
*/
import { useSyncExternalStore } from "react";
diff --git a/packages/web/test/benchmark-metrics.test.ts b/packages/web/test/benchmark-metrics.test.ts
index f0791066..072a2f08 100644
--- a/packages/web/test/benchmark-metrics.test.ts
+++ b/packages/web/test/benchmark-metrics.test.ts
@@ -7,6 +7,7 @@
* hold between them (seriesPoints, stroked by chart-geom's segmentPath).
*/
import { describe, expect, it } from "vitest";
+import { makeRangeGeom, segmentPath } from "@prismshadow/penguin-ui";
import {
defaultTargetScore,
evaluationLabel,
@@ -20,7 +21,6 @@ import {
sparklineSeries,
} from "../src/features/benchmark/benchmark-metrics";
import type { EvaluationLabelLike } from "../src/features/benchmark/benchmark-metrics";
-import { makeRangeGeom, segmentPath } from "../src/features/usage/chart-geom";
const evaluations = [{ score: 60 }, { score: 75.25 }, { score: 85.5 }];
diff --git a/packages/web/test/chart-marks.test.ts b/packages/web/test/chart-marks.test.ts
index 940f96fd..de7bb5e4 100644
--- a/packages/web/test/chart-marks.test.ts
+++ b/packages/web/test/chart-marks.test.ts
@@ -1,114 +1,23 @@
/**
- * The chart primitives (components/ui/chart): what each draws in the default theme — the
- * record the server snapshot of useChartStyle hands out, which is today's charts — and a guard
- * that every chart draws its marks through them.
+ * The Web App's charts draw every mark through the package's chart primitives
+ * (`@prismshadow/penguin-ui`: ChartBar, ChartLine, ChartArc, TimelineBar, …) and the charts built
+ * on them (ChartFrame, Ring, Sparkline, TokenDonut), never with shapes, paint or geometry of their
+ * own. What each primitive draws is the package's `chart-marks.test.ts`, which holds the
+ * package's own charts to the same rule.
*/
-import { createElement, type ReactElement } from "react";
-import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
-import {
- ChartArea,
- ChartBar,
- ChartLine,
- ChartPoint,
- ChartSwatch,
- TimelineBar,
-} from "../src/components/ui/chart";
-import { barPath } from "../src/components/ui/chart/marks";
-import { DEFAULT_CHART_STYLE } from "../src/lib/chart-style";
import { scanSources, sourceFile } from "./helpers/roots";
-// Each primitive has its own props; the helper only renders one, so it takes any component.
-const render = (type: (props: any) => ReactElement | null, props: object) =>
- renderToStaticMarkup(createElement(type, props));
-
-describe("the chart primitives, in the default theme", () => {
- it("draw a bar at the theme's share of its band, square, unoutlined, in its slot's colour", () => {
- const html = render(ChartBar, { cx: 50, band: 20, y: 10, height: 30, paint: { series: 1 } });
- expect(html).toContain("<rect");
- expect(html).toContain('width="12"');
- expect(html).toContain('x="44"');
- expect(html).toContain('data-part="bar"');
- expect(html).toContain('data-series="2"');
- expect(html).toContain(`color:${DEFAULT_CHART_STYLE.series[1]}`);
- expect(html).not.toContain("stroke");
- expect(html).not.toContain("fill-opacity");
- });
-
- it("round a bar's top corners only when a theme gives a radius, clamped to the bar", () => {
- expect(barPath(0, 0, 10, 20, 0)).toBeNull();
- expect(barPath(0, 0, 10, 20, 3)).toBe("M0,20 V3 A3,3 0 0 1 3,0 H7 A3,3 0 0 1 10,3 V20 Z");
- expect(barPath(0, 0, 4, 20, 9)).toContain("A2,2");
- });
-
- it("draw a line straight at the theme's width, and a point as a round rect", () => {
- const line = render(ChartLine, {
- points: [
- [0, 10],
- [10, 20],
- ],
- paint: { role: "ref" },
- dash: "4 3",
- });
- expect(line).toContain('d="M0,10 L10,20"');
- expect(line).toContain('stroke-width="2"');
- expect(line).toContain('stroke-dasharray="4 3"');
- expect(line).toContain('data-part="series"');
- const point = render(ChartPoint, { cx: 10, cy: 10, paint: { ink: "" }, grow: true });
- expect(point).toContain('rx="4"');
- expect(point).toContain('width="8"');
- expect(point).toContain('data-part="point"');
- });
-
- it("fill under a line at the theme's area opacity, scaled by strength", () => {
- const area = render(ChartArea, {
- points: [
- [0, 10],
- [10, 20],
- ],
- baseY: 30,
- paint: { ink: "text-emerald-600" },
- strength: 0.6,
- });
- expect(area).toContain('d="M0,10 L10,20 L10,30 L0,30 Z"');
- expect(area).toMatch(/opacity="0\.06/);
- expect(area).toContain("text-emerald-600");
- });
-
- it("place a timeline bar where the chart says, in its slot's colour", () => {
- const html = render(TimelineBar, {
- paint: { series: 0 },
- place: { left: "10%", width: "5%" },
- className: "cursor-pointer",
- });
- expect(html).toContain("left:10%");
- expect(html).toContain(`background-color:${DEFAULT_CHART_STYLE.series[0]}`);
- expect(html).toContain('data-part="bar"');
- expect(html).not.toContain("box-shadow");
- expect(html).not.toContain("border-radius");
- });
-
- it("paint a swatch the way its mark is painted", () => {
- expect(render(ChartSwatch, { paint: { role: "cacheRead" } })).toContain(
- `background-color:${DEFAULT_CHART_STYLE.cacheRead}`,
- );
- expect(
- render(ChartSwatch, { paint: { ink: "text-gray-400", swatch: "bg-gray-400" } }),
- ).toContain("bg-gray-400");
- });
-});
-
describe("every chart", () => {
const scan = scanSources();
const CHARTS = [
"features/usage/usage-charts.tsx",
"features/usage/trend-chart.tsx",
- "features/usage/chart-svg.tsx",
- "components/ui/token-donut.tsx",
- "features/benchmark/score-sparkline.tsx",
- "features/agents/activity-sparkline.tsx",
"features/traces/timeline-chart.tsx",
"features/benchmark/benchmark-detail.tsx",
+ "features/company/finance-gauge.tsx",
+ "features/company/shared.tsx",
+ "features/chat/context-gauge.tsx",
];
it("draws its marks through the primitives, never with its own shapes, paint or geometry", () => {
diff --git a/packages/web/test/command-palette.test.ts b/packages/web/test/command-palette.test.ts
deleted file mode 100644
index 05c2c2fb..00000000
--- a/packages/web/test/command-palette.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { filterPaletteActions } from "../src/lib/command-palette";
-
-// The chord that opens the palette is the registry's `palette.toggle`; its matching per
-// platform is covered by test/shortcuts-match.test.ts.
-
-describe("command palette filter", () => {
- const actions = [
- { id: "history", label: "Harness history", keywords: ["version", "hmr"] },
- { id: "reload", label: "Reload page" },
- ];
- it("lists everything for an empty query, in registration order", () => {
- expect(filterPaletteActions(actions, " ").map((a) => a.id)).toEqual(["history", "reload"]);
- });
- it("matches every token, case-insensitively, against the label and the keywords", () => {
- expect(filterPaletteActions(actions, "HIST").map((a) => a.id)).toEqual(["history"]);
- expect(filterPaletteActions(actions, "harness hist").map((a) => a.id)).toEqual(["history"]);
- expect(filterPaletteActions(actions, "hmr").map((a) => a.id)).toEqual(["history"]);
- expect(filterPaletteActions(actions, "page harness")).toEqual([]);
- });
-});
diff --git a/packages/web/test/deslop.test.ts b/packages/web/test/deslop.test.ts
index 485bc4ef..114aa8ef 100644
--- a/packages/web/test/deslop.test.ts
+++ b/packages/web/test/deslop.test.ts
@@ -63,7 +63,6 @@ const ALLOWLIST: DeslopAllowlist = {
"features/chat/agent-topology-view.tsx": { 12: [1, "W6"], 13: [3, "W6"] },
"features/chat/chat-input.tsx": { 7: [1, "W6"], 12: [7, "W6"], 13: [5, "W6"] },
"features/chat/chat-page.tsx": { 12: [2, "W6"], 13: [3, "W6"] },
- "features/chat/context-gauge.tsx": { 12: [5, "W8"] },
"features/chat/conversation-outline.tsx": { 12: [1, "W6"] },
"features/chat/draft-view.tsx": { 12: [1, "W6"], 13: [1, "W6"] },
"features/chat/drop-zone.tsx": { 18: [1, "W7"] },
@@ -88,8 +87,6 @@ const ALLOWLIST: DeslopAllowlist = {
"features/company/channel-composer.tsx": { 13: [2, "W6"] },
"features/company/channel-header.tsx": { 13: [3, "W6"] },
"features/company/channel-view.tsx": { 12: [1, "W6"], 13: [6, "W6"] },
- "features/company/chart-card.tsx": { 12: [1, "W8"], 13: [5, "W8"] },
- "features/company/finance-gauge.tsx": { 13: [1, "W8"] },
"features/dock/dock-drag.tsx": { 3: [1, "W7"], 12: [1, "W7"] },
"features/dock/dock-launcher.tsx": { 13: [1, "W7"], 18: [3, "W7"], 19: [4, "W7"] },
"features/dock/dock-panel.tsx": { 1: [2, "W7"], 12: [2, "W7"] },
@@ -97,9 +94,6 @@ const ALLOWLIST: DeslopAllowlist = {
"features/settings/shortcuts-section.tsx": { 13: [1, "W10"] },
"features/terminal/terminal-appearance.ts": { 9: [1, "W10"] },
"features/terminal/terminal-keybar.tsx": { 12: [1, "W10"] },
- "features/traces/timeline-chart.tsx": { 6: [2, "W8"], 13: [10, "W8"] },
- "features/usage/usage-charts.tsx": { 13: [3, "W8"] },
- "features/usage/usage-page.tsx": { 12: [1, "W8"] },
};
const WAVES = /^W(?:1a?|1b|10|[2-9])(?:\+W(?:1a?|1b|10|[2-9]))*$/;
diff --git a/packages/web/test/notice-chart-hooks.test.ts b/packages/web/test/notice-chart-hooks.test.ts
index e3944a70..a5838334 100644
--- a/packages/web/test/notice-chart-hooks.test.ts
+++ b/packages/web/test/notice-chart-hooks.test.ts
@@ -12,7 +12,6 @@ import { NOTICE_TONE, NoticeStrip, ToastStack } from "@prismshadow/penguin-ui";
import { expectSingleHome, scanSources, sourceFile } from "./helpers/roots";
const SCAN = scanSources();
-const text = (id: string) => sourceFile(SCAN, `packages/web/src/${id}`).text;
const NOTICE_STRIP = "packages/ui/src/components/feedback/notice/notice-strip.tsx";
const TOASTER = "packages/ui/src/components/overlays/toaster/toaster.tsx";
@@ -138,21 +137,39 @@ describe("a notice's own mark", () => {
});
});
+const CHARTS = "packages/ui/src/components/charts";
+const CHART_MARKS = `${CHARTS}/marks/marks.tsx`;
+const TIMELINE_BAR = `${CHARTS}/marks/timeline-bar.tsx`;
+
describe("charts", () => {
+ it("live in the shared UI package, one copy each", () => {
+ // The primitives' marks.tsx is left out: the icon marks share its file name.
+ for (const id of [
+ TIMELINE_BAR,
+ `${CHARTS}/chart-style.ts`,
+ `${CHARTS}/chart-frame/chart-frame.tsx`,
+ `${CHARTS}/chart-frame/chart-geom.ts`,
+ `${CHARTS}/token-donut/token-donut.tsx`,
+ `${CHARTS}/sparkline/sparkline.tsx`,
+ `${CHARTS}/ring/ring.tsx`,
+ `${CHARTS}/legend/legend.tsx`,
+ ]) {
+ expectSingleHome(SCAN, id);
+ }
+ });
+
it("carry ui-chart on their roots and name their parts", () => {
for (const id of [
- "features/usage/chart-svg.tsx",
- "components/ui/token-donut.tsx",
- "features/benchmark/score-sparkline.tsx",
- "features/traces/timeline-chart.tsx",
- "features/agents/activity-sparkline.tsx",
+ `${CHARTS}/chart-frame/chart-frame.tsx`,
+ `${CHARTS}/token-donut/token-donut.tsx`,
+ `${CHARTS}/sparkline/sparkline.tsx`,
+ `${CHARTS}/ring/ring.tsx`,
+ "packages/web/src/features/traces/timeline-chart.tsx",
]) {
- expect(text(id), id).toContain("ui-chart");
+ expect(sourceFile(SCAN, id).text, id).toContain("ui-chart");
}
// The parts are written by the chart primitives, the one place marks are drawn.
- const parts = ["components/ui/chart/marks.tsx", "components/ui/chart/timeline-bar.tsx"]
- .map(text)
- .join("\n");
+ const parts = [CHART_MARKS, TIMELINE_BAR].map((id) => sourceFile(SCAN, id).text).join("\n");
for (const part of ["series", "area", "bar", "point", "grid", "axis"]) {
expect(parts, part).toMatch(new RegExp(`data-part(?:=|": )"${part}"`));
}
diff --git a/scripts/ui-migrate.json b/scripts/ui-migrate.json
index f3a8a0ce..3151659a 100644
--- a/scripts/ui-migrate.json
+++ b/scripts/ui-migrate.json
@@ -736,6 +736,167 @@
]
}
]
+ },
+ "W8": {
+ "packages/web/src/features/palette/command-palette": [
+ {
+ "owner": "W8-B",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/overlays/command-palette/command-palette.tsx",
+ "names": ["CommandPalette"]
+ }
+ ],
+ "packages/web/src/lib/command-palette": [
+ {
+ "owner": "W8-B",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/overlays/command-palette/command-palette.tsx",
+ "names": ["PaletteAction", "filterPaletteActions"]
+ }
+ ],
+ "packages/web/src/components/ui/chart": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/marks/marks.tsx",
+ "names": [
+ "ChartArc",
+ "ChartArea",
+ "ChartAxis",
+ "ChartAxisBreak",
+ "ChartBar",
+ "ChartBarHit",
+ "ChartCursor",
+ "ChartGrid",
+ "ChartHit",
+ "ChartLine",
+ "ChartPoint",
+ "ChartSwatch",
+ "resolvePaint",
+ "useBarWidth",
+ "ChartPaint"
+ ]
+ },
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/marks/timeline-bar.tsx",
+ "names": ["TimelineBar"]
+ },
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/marks/geom.ts",
+ "names": ["BAR_W", "curvePath", "fitBarWidth", "roundCoord"]
+ }
+ ],
+ "packages/web/src/components/ui/chart/marks": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/marks/marks.tsx",
+ "names": [
+ "ChartPaint",
+ "resolvePaint",
+ "useBarWidth",
+ "barPath",
+ "ChartBar",
+ "ChartLine",
+ "ChartArea",
+ "ChartPoint",
+ "ChartArc",
+ "ChartGrid",
+ "ChartCursor",
+ "ChartAxis",
+ "ChartAxisBreak",
+ "ChartHit",
+ "ChartBarHit",
+ "ChartSwatch"
+ ]
+ }
+ ],
+ "packages/web/src/components/ui/chart/geom": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/marks/geom.ts",
+ "names": ["roundCoord", "curvePath", "BAR_W", "fitBarWidth"]
+ }
+ ],
+ "packages/web/src/components/ui/chart/timeline-bar": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/marks/timeline-bar.tsx",
+ "names": ["TimelineBar"]
+ }
+ ],
+ "packages/web/src/lib/chart-style": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/chart-style.ts",
+ "names": [
+ "ChartCurve",
+ "ChartStyle",
+ "DEFAULT_CHART_STYLE",
+ "readChartStyle",
+ "seriesStroke",
+ "sameChartStyle",
+ "nextChartStyle",
+ "useChartStyle"
+ ]
+ }
+ ],
+ "packages/web/src/features/usage/chart-svg": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/chart-frame/chart-frame.tsx",
+ "names": ["LINE_HIT_H", "LineHits", "useChartWidth", "ChartFrame"]
+ }
+ ],
+ "packages/web/src/features/usage/chart-geom": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/chart-frame/chart-geom.ts",
+ "names": [
+ "CHART_H",
+ "PAD_L",
+ "PAD_R",
+ "PAD_T",
+ "PAD_B",
+ "PAD_R_AXIS",
+ "TokenBucketKey",
+ "ChartGeom",
+ "makeGeom",
+ "makeRangeGeom",
+ "seriesPoints",
+ "LinePoint",
+ "segmentPoints",
+ "segmentPath",
+ "sparseLabelIdx",
+ "autoLabelIdx",
+ "BUBBLE_OFFSET",
+ "BubbleView",
+ "bubblePosition",
+ "MIN_HIT_H",
+ "StackSegment",
+ "BarSegment",
+ "stackSegments",
+ "barSegments"
+ ]
+ }
+ ],
+ "packages/web/src/components/ui/token-donut": [
+ {
+ "owner": "W8-A",
+ "target": "@prismshadow/penguin-ui",
+ "dest": "packages/ui/src/components/charts/token-donut/token-donut.tsx",
+ "names": ["TokenDonut"]
+ }
+ ]
}
}
}