diff --git a/.scratch/usage-redesign/DECISION.md b/.scratch/usage-redesign/DECISION.md new file mode 100644 index 00000000..09ae4c6f --- /dev/null +++ b/.scratch/usage-redesign/DECISION.md @@ -0,0 +1,27 @@ +# Usage 页重构 — 决策记录 + +日期:2026-09-17 · 来源:`/proto/usage` 两轮原型(emil-prototype 流程) + +## 选定:Cockpit + Rhythm + +- 骨架:周期选择(7D / 30D / 90D / All)→ 4 个 KPI 卡(Cost / Tokens / Sessions / Avg cost per session,各带火花线与环比)→ 日成本折线(悬停十字线,tooltip 给项目拆分)→ **Rhythm 热力图(星期 × 小时,本地时间,当前周期)** → By project / By model 排行 → Tools / Skills 排行。 +- 主口径为 **USD 成本**,token 降为次要指标。 +- 热力图分档按**排名**而非线性比例(离群日不再把全年压平);顺序色由 `--pigui-data-blue` 经 `color-mix` 向 `--surface` 推五档,不新增 token。 +- 图表为手写 SVG 原语,不引入图表库。 + +## 否决 + +- **Baseline(现状)**:token / 成本双口径混杂,长项目路径撑破图例。 +- **Ledger(行优先 + 会话表)**:偏账单明细工具,作为主页面缺分布与趋势;会话表可能后续作为 Cockpit 底部区块回归。 +- **Digest(编辑式月报 + 月历)**:只有月粒度,作为唯一 Usage 视图偏窄。 +- **Calendar(全年日历热力图)**:52 列在页面里太短,右侧空荡;只读。 +- **Drill(可点击日历 + 会话表)**:交互最重,选中某天后 KPI 与热力图两套口径并存。 + +## 前提修正 + +Pace 已是完整桌面 Agent,不再以"观测台账"作为唯一页面语言评判 UI;标准分析仪表盘形状的通用性是优点。README / AGENTS.md 的观测定位描述待更新(另开)。 + +## 待办 / 已知问题 + +- 日分桶用 UTC、Rhythm 用本地时间,口径需统一(沿用自旧 `usage-aggregation`)。 +- 后续按需要再加图表(用户原话:"后面再看看到底需要什么图表,再加")。 diff --git a/apps/desktop/src/dev/mock/scenarios.ts b/apps/desktop/src/dev/mock/scenarios.ts index 721add49..94453357 100644 --- a/apps/desktop/src/dev/mock/scenarios.ts +++ b/apps/desktop/src/dev/mock/scenarios.ts @@ -5,6 +5,7 @@ import type { SessionChanges, SessionDirectoryListing, SessionFileContent, + SessionSummary, } from "@pace/core"; import { invokeBrowserFallback, type PaceRendererApi } from "@/shared/runtime"; @@ -59,6 +60,29 @@ const projections: PersistedSessionProjection[] = definitions.map( }), ); +// Usage page input: one summary per projection, spread over the same days +// with a deterministic cost/token ramp so the dashboard has a shape. +const sessionSummaries: SessionSummary[] = projections.map((item, index) => { + const tokens = summary.totalTokens * (1 + (index % 5)) * (index % 3 === 0 ? 4 : 1); + const costUsd = (tokens / summary.totalTokens) * summary.totalCostUsd; + return { + id: item.sessionId, + timestamp: item.updatedAt, + project: item.projectId, + title: { kind: "text", sentence: item.title ?? item.sessionId }, + totalCostUsd: costUsd, + totalTokens: tokens, + primaryModel: summary.model, + modelBreakdown: [{ model: summary.model, costUsd, tokens }], + toolCounts: [ + { name: "Read", count: 3 + index }, + { name: "Edit", count: 1 + (index % 4) }, + ], + skillCounts: index % 4 === 0 ? [{ name: "code-review", count: 1 }] : [], + presence: item.status === "archived" ? "archived" : "active", + }; +}); + const source = "export const greeting = '你好,Pace';\n"; const files: Record< string, @@ -379,6 +403,9 @@ export function createMockApi(): PaceRendererApi { case "list_session_projections": result = projections; break; + case "list_sessions": + result = sessionSummaries; + break; case "resume_session": case "get_runtime_snapshot": if (!record) throw new Error(`Mock session not found: ${sessionId}`); diff --git a/apps/desktop/src/entities/session/usage-aggregation.test.ts b/apps/desktop/src/entities/session/usage-aggregation.test.ts index 636d2c08..2a5911eb 100644 --- a/apps/desktop/src/entities/session/usage-aggregation.test.ts +++ b/apps/desktop/src/entities/session/usage-aggregation.test.ts @@ -1,477 +1,217 @@ import { describe, expect, it } from "vitest"; +import type { SessionSummary } from "@/entities/session/sessions"; import { - aggregateCostByModel, - aggregateDailyCostByProject, - aggregateDailyTokens, - aggregateDailyTokensByProject, - buildAnnualTokenHeatmap, - buildTrailingAnnualTokenHeatmap, - bucketCostByProject, - bucketTokenUsageByProject, - aggregateModelDistribution, + aggregateDailyCost, aggregateSkillCounts, aggregateToolCounts, + aggregateWeekdayHourCost, + rankLevels, + rankModelsByCost, + rankProjectsByCost, + splitUsagePeriod, + summarizeUsage, + usageDelta, } from "@/entities/session/usage-aggregation"; -import type { SessionSummary } from "@/entities/session/sessions"; -function session( - id: string, - timestamp: string, - project: string, - totalCostUsd: number, - totalTokens: number, - options: Partial> = {}, -): SessionSummary { +function session(overrides: Partial = {}): SessionSummary { return { - id, - timestamp, - project, - totalCostUsd, - totalTokens, - title: { kind: "raw", text: id }, - modelBreakdown: options.modelBreakdown ?? [], - toolCounts: options.toolCounts ?? [], - skillCounts: options.skillCounts ?? [], + id: "s", + timestamp: "2026-06-26T10:00:00.000Z", + project: "alpha", + title: { kind: "raw", text: "s" }, + totalCostUsd: 1, + totalTokens: 1000, + primaryModel: "m", + modelBreakdown: [{ model: "m", costUsd: 1, tokens: 1000 }], + toolCounts: [], + skillCounts: [], presence: "external", + ...overrides, }; } -describe("aggregateDailyCostByProject", () => { - it("returns an empty range for no sessions", () => { - expect(aggregateDailyCostByProject([])).toEqual([]); - }); +describe("splitUsagePeriod", () => { + const sessions = [ + session({ id: "old", timestamp: "2026-05-20T10:00:00.000Z", totalCostUsd: 5 }), + session({ id: "prev", timestamp: "2026-06-18T10:00:00.000Z", totalCostUsd: 2 }), + session({ id: "edge", timestamp: "2026-06-20T00:30:00.000Z", totalCostUsd: 3 }), + session({ id: "latest", timestamp: "2026-06-26T23:00:00.000Z", totalCostUsd: 1 }), + ]; - it("groups cost by UTC day and project, filling sparse days", () => { - const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.5, 200), - session("c", "2026-01-03T12:00:00.000Z", "alpha", 0.75, 300), - ]; + it("anchors the window on the latest UTC day and includes the boundary day", () => { + const { current, previous } = splitUsagePeriod(sessions, "7d"); - expect(aggregateDailyCostByProject(sessions)).toEqual([ - { - date: "2026-01-01", - totalCostUsd: 0.25, - projects: [{ project: "alpha", costUsd: 0.25 }], - }, - { - date: "2026-01-02", - totalCostUsd: 0, - projects: [], - }, - { - date: "2026-01-03", - totalCostUsd: 1.25, - projects: [ - { project: "alpha", costUsd: 0.75 }, - { project: "beta", costUsd: 0.5 }, - ], - }, - ]); + expect(current.start).toBe("2026-06-20"); + expect(current.end).toBe("2026-06-26"); + expect(current.sessions.map((s) => s.id)).toEqual(["edge", "latest"]); + expect(previous?.start).toBe("2026-06-13"); + expect(previous?.end).toBe("2026-06-19"); + expect(previous?.sessions.map((s) => s.id)).toEqual(["prev"]); }); -}); -describe("aggregateDailyTokens", () => { - it("returns an empty range for no sessions", () => { - expect(aggregateDailyTokens([])).toEqual([]); + it("uses the whole history with no previous window for `all`", () => { + const { current, previous } = splitUsagePeriod(sessions, "all"); + + expect(current.start).toBe("2026-05-20"); + expect(current.sessions).toHaveLength(4); + expect(previous).toBeNull(); }); - it("groups tokens by UTC day, filling sparse days", () => { - const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.5, 200), - session("c", "2026-01-03T12:00:00.000Z", "alpha", 0.75, 300), - ]; + it("returns an empty window for no sessions", () => { + const { current, previous } = splitUsagePeriod([], "30d"); - expect(aggregateDailyTokens(sessions)).toEqual([ - { date: "2026-01-01", totalTokens: 100 }, - { date: "2026-01-02", totalTokens: 0 }, - { date: "2026-01-03", totalTokens: 500 }, - ]); + expect(current.sessions).toEqual([]); + expect(previous?.sessions).toEqual([]); }); }); -describe("aggregateDailyTokensByProject", () => { - it("groups tokens by UTC day and project, filling sparse days", () => { - const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.5, 200), - session("c", "2026-01-03T12:00:00.000Z", "alpha", 0.75, 300), - ]; - - expect(aggregateDailyTokensByProject(sessions)).toEqual([ - { - date: "2026-01-01", - totalTokens: 100, - projects: [{ project: "alpha", tokens: 100 }], - }, - { - date: "2026-01-02", - totalTokens: 0, - projects: [], - }, - { - date: "2026-01-03", - totalTokens: 500, - projects: [ - { project: "alpha", tokens: 300 }, - { project: "beta", tokens: 200 }, - ], - }, - ]); +describe("summarizeUsage", () => { + it("totals cost, tokens, sessions and distinct projects", () => { + expect( + summarizeUsage([ + session({ totalCostUsd: 1.5, totalTokens: 10 }), + session({ totalCostUsd: 0.5, totalTokens: 5, project: "beta" }), + session({ totalCostUsd: 0, totalTokens: 0, project: "beta" }), + ]), + ).toEqual({ costUsd: 2, tokens: 15, sessions: 3, projects: 2 }); }); }); -describe("bucketTokenUsageByProject", () => { - const days = [ - { - date: "2026-03-20", - totalTokens: 100, - projects: [{ project: "alpha", tokens: 100 }], - }, - { - date: "2026-03-21", - totalTokens: 0, - projects: [], - }, - { - date: "2026-03-22", - totalTokens: 500, - projects: [ - { project: "alpha", tokens: 300 }, - { project: "beta", tokens: 200 }, - ], - }, - ]; - - it("keeps the 30-day trend at exactly 30 daily buckets", () => { - const buckets = bucketTokenUsageByProject(days, "30d"); - - expect(buckets).toHaveLength(30); - expect(buckets[0]).toMatchObject({ - key: "2026-02-21", - startDate: "2026-02-21", - endDate: "2026-02-21", - totalTokens: 0, - }); - expect(buckets[buckets.length - 1]).toEqual({ - key: "2026-03-22", - startDate: "2026-03-22", - endDate: "2026-03-22", - totalTokens: 500, - projects: [ - { project: "alpha", tokens: 300 }, - { project: "beta", tokens: 200 }, - ], - }); +describe("usageDelta", () => { + it("reports a signed ratio against the previous value", () => { + expect(usageDelta(150, 100)).toEqual({ ratio: 0.5, kind: "up" }); + expect(usageDelta(50, 100)).toEqual({ ratio: -0.5, kind: "down" }); + expect(usageDelta(100.1, 100)).toEqual({ ratio: expect.closeTo(0.001, 5), kind: "flat" }); }); - it("keeps weekly and monthly trends at 12 aggregated buckets", () => { - const weeks = bucketTokenUsageByProject(days, "12w"); - const months = bucketTokenUsageByProject(days, "12m"); + it("distinguishes 'no previous data' from 'no change'", () => { + expect(usageDelta(10, 0)).toEqual({ ratio: null, kind: "new" }); + expect(usageDelta(0, 0)).toEqual({ ratio: 0, kind: "flat" }); + expect(usageDelta(10, null)).toBeNull(); + }); +}); - expect(weeks).toHaveLength(12); - expect(weeks[0]).toMatchObject({ - startDate: "2025-12-29", - endDate: "2026-01-04", - }); - expect(weeks[weeks.length - 1]).toEqual({ - key: "2026-03-16", - startDate: "2026-03-16", - endDate: "2026-03-22", - totalTokens: 600, - projects: [ - { project: "alpha", tokens: 400 }, - { project: "beta", tokens: 200 }, +describe("aggregateDailyCost", () => { + it("fills every day of the window and splits cost by project", () => { + const days = aggregateDailyCost({ + start: "2026-06-25", + end: "2026-06-27", + sessions: [ + session({ timestamp: "2026-06-25T01:00:00.000Z", totalCostUsd: 1, project: "alpha" }), + session({ timestamp: "2026-06-25T02:00:00.000Z", totalCostUsd: 3, project: "beta" }), + session({ timestamp: "2026-06-27T02:00:00.000Z", totalCostUsd: 0.25, project: "alpha", totalTokens: 7 }), + session({ timestamp: "2026-06-30T02:00:00.000Z", totalCostUsd: 99 }), ], }); - expect(months).toHaveLength(12); - expect(months[0]).toMatchObject({ - key: "2025-04", - startDate: "2025-04-01", - endDate: "2025-04-30", - }); - expect(months[months.length - 1]).toEqual({ - key: "2026-03", - startDate: "2026-03-01", - endDate: "2026-03-22", - totalTokens: 600, + expect(days.map((d) => d.date)).toEqual(["2026-06-25", "2026-06-26", "2026-06-27"]); + expect(days[0]).toMatchObject({ + costUsd: 4, + sessions: 2, projects: [ - { project: "alpha", tokens: 400 }, - { project: "beta", tokens: 200 }, + { project: "beta", costUsd: 3 }, + { project: "alpha", costUsd: 1 }, ], }); + expect(days[1]).toMatchObject({ costUsd: 0, tokens: 0, sessions: 0, projects: [] }); + expect(days[2]).toMatchObject({ costUsd: 0.25, tokens: 7, sessions: 1 }); }); }); -describe("buildAnnualTokenHeatmap", () => { - it("expands sparse token days to a full calendar year", () => { - const heatmap = buildAnnualTokenHeatmap([ - { date: "2026-03-20", totalTokens: 100 }, - { date: "2026-06-24", totalTokens: 250 }, +describe("rankProjectsByCost / rankModelsByCost", () => { + it("ranks projects by cost with share of total", () => { + const ranks = rankProjectsByCost([ + session({ project: "alpha", totalCostUsd: 3, totalTokens: 30 }), + session({ project: "beta", totalCostUsd: 1, totalTokens: 10 }), + session({ project: "alpha", totalCostUsd: 1, totalTokens: 10 }), ]); - expect(heatmap).toMatchObject({ - year: 2026, - weekCount: 53, - }); - expect(heatmap?.days).toHaveLength(365); - expect(heatmap?.days[0]).toMatchObject({ - date: "2026-01-01", - totalTokens: 0, - weekdayIndex: 4, - weekIndex: 0, - }); - expect(heatmap?.days.find((day) => day.date === "2026-03-20")).toMatchObject({ - totalTokens: 100, - }); - expect(heatmap?.days[heatmap.days.length - 1]).toMatchObject({ - date: "2026-12-31", - totalTokens: 0, - }); - expect(heatmap?.monthLabels.map((month) => month.label)).toEqual([ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", + expect(ranks).toEqual([ + { name: "alpha", costUsd: 4, tokens: 40, sessions: 2, share: 0.8 }, + { name: "beta", costUsd: 1, tokens: 10, sessions: 1, share: 0.2 }, ]); }); - it("uses the latest data year when more than one year is present", () => { - const heatmap = buildAnnualTokenHeatmap([ - { date: "2025-12-31", totalTokens: 100 }, - { date: "2026-01-02", totalTokens: 200 }, + it("ranks models from the per-session breakdown, not the primary model", () => { + const ranks = rankModelsByCost([ + session({ + modelBreakdown: [ + { model: "big", costUsd: 3, tokens: 300 }, + { model: "small", costUsd: 1, tokens: 700 }, + ], + }), + session({ modelBreakdown: [{ model: "small", costUsd: 1, tokens: 100 }] }), ]); - expect(heatmap?.year).toBe(2026); - expect(heatmap?.days.find((day) => day.date === "2026-01-02")).toMatchObject({ - totalTokens: 200, - }); - expect(heatmap?.days.some((day) => day.date === "2025-12-31")).toBe(false); - }); -}); - -describe("buildTrailingAnnualTokenHeatmap", () => { - it("expands sparse token days to the latest twelve calendar months", () => { - const heatmap = buildTrailingAnnualTokenHeatmap([ - { date: "2026-03-20", totalTokens: 100 }, - { date: "2026-06-24", totalTokens: 250 }, + expect(ranks).toEqual([ + { name: "big", costUsd: 3, tokens: 300, sessions: 1, share: 0.6 }, + { name: "small", costUsd: 2, tokens: 800, sessions: 2, share: 0.4 }, ]); + }); - expect(heatmap).toMatchObject({ - year: 2026, - startDate: "2025-07-01", - endDate: "2026-06-30", - }); - expect(heatmap?.days[0]).toMatchObject({ - date: "2025-07-01", - totalTokens: 0, - }); - expect(heatmap?.days.find((day) => day.date === "2026-03-20")).toMatchObject({ - totalTokens: 100, - }); - expect(heatmap?.days[heatmap.days.length - 1]).toMatchObject({ - date: "2026-06-30", - totalTokens: 0, - }); - expect(heatmap?.monthLabels.map((month) => month.label)).toEqual([ - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - ]); + it("returns zero shares when total cost is zero", () => { + expect(rankProjectsByCost([session({ totalCostUsd: 0 })])[0].share).toBe(0); }); }); -describe("bucketCostByProject", () => { - const days = [ - { - date: "2026-03-20", - totalCostUsd: 1, - projects: [{ project: "alpha", costUsd: 1 }], - }, - { - date: "2026-03-21", - totalCostUsd: 0, - projects: [], - }, - { - date: "2026-03-22", - totalCostUsd: 2, - projects: [{ project: "beta", costUsd: 2 }], - }, - { - date: "2026-04-01", - totalCostUsd: 3, - projects: [{ project: "alpha", costUsd: 3 }], - }, - ]; - - it("groups daily project costs by month without keeping daily ticks", () => { - expect(bucketCostByProject(days, "month")).toEqual([ - { - key: "2026-03", - startDate: "2026-03-20", - endDate: "2026-03-22", - totalCostUsd: 3, - projects: [ - { project: "beta", costUsd: 2 }, - { project: "alpha", costUsd: 1 }, - ], - }, - { - key: "2026-04", - startDate: "2026-04-01", - endDate: "2026-04-01", - totalCostUsd: 3, - projects: [{ project: "alpha", costUsd: 3 }], +describe("aggregateWeekdayHourCost", () => { + it("buckets by weekday (Monday first) and hour using the supplied clock", () => { + const grid = aggregateWeekdayHourCost( + [ + // 2026-06-26 is a Friday. + session({ timestamp: "2026-06-26T09:10:00.000Z", totalCostUsd: 1 }), + session({ timestamp: "2026-06-26T09:50:00.000Z", totalCostUsd: 2 }), + // 2026-06-28 is a Sunday. + session({ timestamp: "2026-06-28T23:59:00.000Z", totalCostUsd: 4 }), + ], + (timestamp) => { + const date = new Date(timestamp); + return { weekday: date.getUTCDay(), hour: date.getUTCHours() }; }, - ]); - }); + ); - it("groups daily project costs by UTC week and cumulative total", () => { - expect(bucketCostByProject(days, "week").map((bucket) => bucket.key)).toEqual([ - "2026-03-16", - "2026-03-30", - ]); - expect(bucketCostByProject(days, "cumulative")).toEqual([ - { - key: "cumulative", - startDate: "2026-03-20", - endDate: "2026-04-01", - totalCostUsd: 6, - projects: [ - { project: "alpha", costUsd: 4 }, - { project: "beta", costUsd: 2 }, - ], - }, - ]); + expect(grid).toHaveLength(7); + expect(grid.every((row) => row.length === 24)).toBe(true); + expect(grid[4][9]).toEqual({ costUsd: 3, sessions: 2 }); + expect(grid[6][23]).toEqual({ costUsd: 4, sessions: 1 }); + expect(grid[0][0]).toEqual({ costUsd: 0, sessions: 0 }); }); }); -describe("aggregateCostByModel", () => { - it("groups model cost and tokens across sessions", () => { - const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100, { - modelBreakdown: [ - { model: "gpt-5-codex", costUsd: 0.2, tokens: 80 }, - { model: "gpt-5-mini", costUsd: 0.05, tokens: 20 }, - ], - }), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.5, 200, { - modelBreakdown: [{ model: "gpt-5-mini", costUsd: 0.5, tokens: 200 }], - }), - ]; +describe("rankLevels", () => { + it("assigns levels by rank so one outlier does not flatten the rest", () => { + const level = rankLevels([1, 2, 3, 4, 1000], 5); - expect(aggregateCostByModel(sessions)).toEqual([ - { model: "gpt-5-mini", costUsd: 0.55, tokens: 220 }, - { model: "gpt-5-codex", costUsd: 0.2, tokens: 80 }, - ]); + expect(level(0)).toBe(0); + expect(level(1)).toBe(1); + expect(level(4)).toBe(4); + expect(level(1000)).toBe(5); }); -}); -describe("aggregateModelDistribution", () => { - it("returns cost and token shares for each model", () => { - const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100, { - modelBreakdown: [ - { model: "gpt-5-codex", costUsd: 0.2, tokens: 80 }, - { model: "gpt-5-mini", costUsd: 0.05, tokens: 20 }, - ], - }), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.75, 300, { - modelBreakdown: [{ model: "gpt-5-mini", costUsd: 0.75, tokens: 300 }], - }), - ]; + it("gives tied maxima the top level", () => { + const level = rankLevels([3, 3, 1], 5); - expect(aggregateModelDistribution(sessions)).toEqual([ - { - model: "gpt-5-mini", - costUsd: 0.8, - tokens: 320, - costShare: 0.8, - tokenShare: 0.8, - }, - { - model: "gpt-5-codex", - costUsd: 0.2, - tokens: 80, - costShare: 0.2, - tokenShare: 0.2, - }, - ]); + expect(level(3)).toBe(5); + expect(level(1)).toBe(1); }); -}); - -describe("aggregateToolCounts", () => { - it("groups tool counts across sessions and returns the top results", () => { - const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100, { - toolCounts: [ - { name: "read_file", count: 2 }, - { name: "list_files", count: 1 }, - ], - }), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.75, 300, { - toolCounts: [ - { name: "read_file", count: 3 }, - { name: "run_command", count: 4 }, - ], - }), - ]; - expect(aggregateToolCounts(sessions, 2)).toEqual([ - { name: "read_file", count: 5 }, - { name: "run_command", count: 4 }, - ]); + it("handles an all-zero input", () => { + expect(rankLevels([0, 0], 5)(0)).toBe(0); }); }); -describe("aggregateSkillCounts", () => { - it("groups skill counts across sessions and returns the top results", () => { +describe("aggregateToolCounts / aggregateSkillCounts", () => { + it("sums counts across sessions and returns the top results", () => { const sessions = [ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100, { - skillCounts: [ - { name: "kami", count: 2 }, - { name: "review", count: 1 }, - ], - }), - session("b", "2026-01-03T01:00:00.000Z", "beta", 0.75, 300, { - skillCounts: [ - { name: "review", count: 4 }, - { name: "summarize", count: 1 }, - ], - }), + session({ toolCounts: [{ name: "Read", count: 3 }, { name: "Edit", count: 1 }], skillCounts: [{ name: "tdd", count: 1 }] }), + session({ toolCounts: [{ name: "Read", count: 2 }, { name: "Bash", count: 4 }], skillCounts: [] }), ]; - expect(aggregateSkillCounts(sessions, 2)).toEqual([ - { name: "review", count: 5 }, - { name: "kami", count: 2 }, + expect(aggregateToolCounts(sessions, 2)).toEqual([ + { name: "Read", count: 5 }, + { name: "Bash", count: 4 }, ]); - }); - - it("returns an empty list when sessions have no skill usage", () => { - expect( - aggregateSkillCounts([ - session("a", "2026-01-01T23:00:00.000Z", "alpha", 0.25, 100), - ]), - ).toEqual([]); + expect(aggregateSkillCounts(sessions)).toEqual([{ name: "tdd", count: 1 }]); + expect(aggregateSkillCounts(sessions, 0)).toEqual([]); }); }); diff --git a/apps/desktop/src/entities/session/usage-aggregation.ts b/apps/desktop/src/entities/session/usage-aggregation.ts index 4fc184a3..61fe291a 100644 --- a/apps/desktop/src/entities/session/usage-aggregation.ts +++ b/apps/desktop/src/entities/session/usage-aggregation.ts @@ -1,518 +1,256 @@ import type { NamedCount, SessionSummary } from "@/entities/session/sessions"; -export type ModelCost = { - model: string; - costUsd: number; - tokens: number; -}; - -export type ModelDistribution = ModelCost & { - costShare: number; - tokenShare: number; -}; +// Usage page read model. Cost (USD) is the primary axis; tokens ride along. +// Days are UTC calendar days everywhere except the weekday × hour grid, +// which takes a clock so the page can bucket in the user's local time. -export type DailyProjectCost = { - project: string; - costUsd: number; -}; +export type UsagePeriod = "7d" | "30d" | "90d" | "all"; -export type DailyCostByProject = { - date: string; - totalCostUsd: number; - projects: DailyProjectCost[]; -}; - -export type CostTrendGranularity = "day" | "week" | "month" | "year" | "cumulative"; +export const usagePeriods: ReadonlyArray<{ id: UsagePeriod; label: string; days: number | null }> = [ + { id: "7d", label: "7D", days: 7 }, + { id: "30d", label: "30D", days: 30 }, + { id: "90d", label: "90D", days: 90 }, + { id: "all", label: "All", days: null }, +]; -export type CostByProjectBucket = { - key: string; - startDate: string; - endDate: string; - totalCostUsd: number; - projects: DailyProjectCost[]; +export type UsageWindow = { + /** Inclusive UTC day, YYYY-MM-DD. */ + start: string; + /** Inclusive UTC day, YYYY-MM-DD. */ + end: string; + sessions: SessionSummary[]; }; -export type DailyTokenUsage = { - date: string; - totalTokens: number; -}; - -export type DailyProjectTokens = { - project: string; +export type UsageSummary = { + costUsd: number; tokens: number; + sessions: number; + projects: number; }; -export type DailyTokensByProject = DailyTokenUsage & { - projects: DailyProjectTokens[]; -}; +export type UsageDelta = + | { ratio: number; kind: "up" | "down" | "flat" } + | { ratio: null; kind: "new" }; -export type UsageTrendPreset = "30d" | "12w" | "12m"; +export type DailyProjectCost = { project: string; costUsd: number }; -export type TokenUsageBucket = { - key: string; - startDate: string; - endDate: string; - totalTokens: number; - projects: DailyProjectTokens[]; +export type DailyCost = { + date: string; + costUsd: number; + tokens: number; + sessions: number; + /** Sorted by cost, descending. */ + projects: DailyProjectCost[]; }; -export type AnnualTokenUsageDay = DailyTokenUsage & { - weekIndex: number; - weekdayIndex: number; +export type UsageRank = { + name: string; + costUsd: number; + tokens: number; + sessions: number; + /** Share of total cost across all ranks, 0..1. */ + share: number; }; -export type AnnualTokenMonthLabel = { - label: string; - weekIndex: number; -}; +export type WeekdayHourCell = { costUsd: number; sessions: number }; -export type AnnualTokenHeatmap = { - year: number; - startDate: string; - endDate: string; - days: AnnualTokenUsageDay[]; - weekCount: number; - monthLabels: AnnualTokenMonthLabel[]; -}; +export type LocalClock = (timestamp: string) => { weekday: number; hour: number }; -const shortMonthLabels = [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", -]; +const dayMs = 86_400_000; function toUtcDay(timestamp: string) { return new Date(timestamp).toISOString().slice(0, 10); } -function addUtcDays(date: Date, days: number) { - const next = new Date(date); - next.setUTCDate(next.getUTCDate() + days); - return next; -} - -function addUtcMonths(date: Date, months: number) { - return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, 1)); +function shiftUtcDay(day: string, days: number) { + return new Date(new Date(`${day}T00:00:00.000Z`).getTime() + days * dayMs).toISOString().slice(0, 10); } -function toUtcWeekStart(date: string) { - const value = new Date(`${date}T00:00:00.000Z`); - const mondayOffset = (value.getUTCDay() + 6) % 7; - value.setUTCDate(value.getUTCDate() - mondayOffset); - return value.toISOString().slice(0, 10); +function dayRange(start: string, end: string) { + const days: string[] = []; + for (let day = start; day <= end; day = shiftUtcDay(day, 1)) days.push(day); + return days; } -function utcDateFromDay(date: string) { - return new Date(`${date}T00:00:00.000Z`); +function latestUtcDay(sessions: SessionSummary[]) { + return sessions.reduce((latest, s) => { + const day = toUtcDay(s.timestamp); + return latest === null || day > latest ? day : latest; + }, null); } -function toUtcDateOnly(date: Date) { - return date.toISOString().slice(0, 10); +function earliestUtcDay(sessions: SessionSummary[], fallback: string) { + return sessions.reduce((earliest, s) => { + const day = toUtcDay(s.timestamp); + return day < earliest ? day : earliest; + }, fallback); } -function daysInUtcYear(year: number) { - const start = Date.UTC(year, 0, 1); - const end = Date.UTC(year + 1, 0, 1); - return Math.round((end - start) / 86_400_000); -} - -function utcDayOffset(start: Date, date: Date) { - const startTime = Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()); - return Math.floor((date.getTime() - startTime) / 86_400_000); -} - -function latestTokenYear(days: DailyTokenUsage[]) { - return days.reduce((latestYear, day) => { - const year = utcDateFromDay(day.date).getUTCFullYear(); - return latestYear === undefined ? year : Math.max(latestYear, year); - }, undefined); -} - -function latestTokenDate(days: DailyTokenUsage[]) { - return days.reduce((latestDate, day) => { - return latestDate === undefined ? day.date : latestDate > day.date ? latestDate : day.date; - }, undefined); -} - -function costBucketKey(date: string, granularity: CostTrendGranularity) { - if (granularity === "day") { - return date; - } - if (granularity === "week") { - return toUtcWeekStart(date); - } - if (granularity === "month") { - return date.slice(0, 7); - } - if (granularity === "year") { - return date.slice(0, 4); - } - return "cumulative"; -} +/** + * The selected window anchored on the latest recorded day, plus the + * equally long window right before it (null for `all`). + */ +export function splitUsagePeriod( + sessions: SessionSummary[], + period: UsagePeriod, +): { current: UsageWindow; previous: UsageWindow | null } { + const end = latestUtcDay(sessions) ?? "1970-01-01"; + const spec = usagePeriods.find((p) => p.id === period) ?? usagePeriods[1]; -function dayRange(sessions: SessionSummary[]) { - if (sessions.length === 0) { - return []; + if (spec.days === null) { + return { current: { start: earliestUtcDay(sessions, end), end, sessions }, previous: null }; } - const days = sessions.map((session) => toUtcDay(session.timestamp)).sort(); - const start = new Date(`${days[0]}T00:00:00.000Z`); - const end = new Date(`${days[days.length - 1]}T00:00:00.000Z`); - const range: string[] = []; - - for (let cursor = start; cursor <= end; cursor = addUtcDays(cursor, 1)) { - range.push(cursor.toISOString().slice(0, 10)); - } + const start = shiftUtcDay(end, -(spec.days - 1)); + const previousEnd = shiftUtcDay(start, -1); + const previousStart = shiftUtcDay(previousEnd, -(spec.days - 1)); + const within = (a: string, b: string) => + sessions.filter((s) => { + const day = toUtcDay(s.timestamp); + return day >= a && day <= b; + }); - return range; + return { + current: { start, end, sessions: within(start, end) }, + previous: { start: previousStart, end: previousEnd, sessions: within(previousStart, previousEnd) }, + }; } -export function aggregateDailyCostByProject(sessions: SessionSummary[]): DailyCostByProject[] { - const totals = new Map>(); - - for (const session of sessions) { - const day = toUtcDay(session.timestamp); - const projectTotals = totals.get(day) ?? new Map(); - projectTotals.set( - session.project, - (projectTotals.get(session.project) ?? 0) + session.totalCostUsd, - ); - totals.set(day, projectTotals); - } - - return dayRange(sessions).map((date) => { - const projects = Array.from(totals.get(date)?.entries() ?? []) - .map(([project, costUsd]) => ({ project, costUsd })) - .sort((left, right) => right.costUsd - left.costUsd || left.project.localeCompare(right.project)); - - return { - date, - totalCostUsd: projects.reduce((sum, project) => sum + project.costUsd, 0), - projects, - }; - }); +export function summarizeUsage(sessions: SessionSummary[]): UsageSummary { + return { + costUsd: sessions.reduce((sum, s) => sum + s.totalCostUsd, 0), + tokens: sessions.reduce((sum, s) => sum + s.totalTokens, 0), + sessions: sessions.length, + projects: new Set(sessions.map((s) => s.project)).size, + }; } -export function bucketCostByProject( - days: DailyCostByProject[], - granularity: CostTrendGranularity, -): CostByProjectBucket[] { - const buckets = new Map }>(); - - for (const day of days) { - const key = costBucketKey(day.date, granularity); - const bucket = buckets.get(key) ?? { - startDate: day.date, - endDate: day.date, - projects: new Map(), - }; - - bucket.startDate = bucket.startDate < day.date ? bucket.startDate : day.date; - bucket.endDate = bucket.endDate > day.date ? bucket.endDate : day.date; - - for (const project of day.projects) { - bucket.projects.set( - project.project, - (bucket.projects.get(project.project) ?? 0) + project.costUsd, - ); - } - - buckets.set(key, bucket); - } - - return Array.from(buckets.entries()).map(([key, bucket]) => { - const projects = Array.from(bucket.projects.entries()) - .map(([project, costUsd]) => ({ project, costUsd })) - .sort((left, right) => right.costUsd - left.costUsd || left.project.localeCompare(right.project)); - - return { - key, - startDate: bucket.startDate, - endDate: bucket.endDate, - totalCostUsd: projects.reduce((sum, project) => sum + project.costUsd, 0), - projects, - }; - }); +/** Period-over-period change. `null` previous means "no comparison window". */ +export function usageDelta(current: number, previous: number | null): UsageDelta | null { + if (previous === null) return null; + if (previous === 0) return current === 0 ? { ratio: 0, kind: "flat" } : { ratio: null, kind: "new" }; + const ratio = current / previous - 1; + if (Math.abs(ratio) < 0.005) return { ratio, kind: "flat" }; + return { ratio, kind: ratio > 0 ? "up" : "down" }; } -export function aggregateDailyTokens(sessions: SessionSummary[]): DailyTokenUsage[] { - const totals = new Map(); - - for (const session of sessions) { - const day = toUtcDay(session.timestamp); - totals.set(day, (totals.get(day) ?? 0) + session.totalTokens); +export function aggregateDailyCost(window: UsageWindow): DailyCost[] { + const byDay = new Map }>(); + for (const date of dayRange(window.start, window.end)) { + byDay.set(date, { costUsd: 0, tokens: 0, sessions: 0, projects: new Map() }); } - - return dayRange(sessions).map((date) => ({ + for (const s of window.sessions) { + const day = byDay.get(toUtcDay(s.timestamp)); + if (!day) continue; + day.costUsd += s.totalCostUsd; + day.tokens += s.totalTokens; + day.sessions += 1; + day.projects.set(s.project, (day.projects.get(s.project) ?? 0) + s.totalCostUsd); + } + return Array.from(byDay.entries()).map(([date, day]) => ({ date, - totalTokens: totals.get(date) ?? 0, + costUsd: day.costUsd, + tokens: day.tokens, + sessions: day.sessions, + projects: Array.from(day.projects.entries()) + .map(([project, costUsd]) => ({ project, costUsd })) + .sort((a, b) => b.costUsd - a.costUsd || a.project.localeCompare(b.project)), })); } -export function aggregateDailyTokensByProject( - sessions: SessionSummary[], -): DailyTokensByProject[] { - const totals = new Map>(); - - for (const session of sessions) { - const day = toUtcDay(session.timestamp); - const projectTotals = totals.get(day) ?? new Map(); - projectTotals.set( - session.project, - (projectTotals.get(session.project) ?? 0) + session.totalTokens, - ); - totals.set(day, projectTotals); - } - - return dayRange(sessions).map((date) => { - const projects = Array.from(totals.get(date)?.entries() ?? []) - .map(([project, tokens]) => ({ project, tokens })) - .sort( - (left, right) => right.tokens - left.tokens || left.project.localeCompare(right.project), - ); - - return { - date, - totalTokens: projects.reduce((sum, project) => sum + project.tokens, 0), - projects, - }; - }); +function finishRanks(map: Map>): UsageRank[] { + const total = Array.from(map.values()).reduce((sum, r) => sum + r.costUsd, 0); + return Array.from(map.values()) + .map((r) => ({ ...r, share: total === 0 ? 0 : r.costUsd / total })) + .sort((a, b) => b.costUsd - a.costUsd || a.name.localeCompare(b.name)); } -function tokenTrendRanges( - latestDate: string, - preset: UsageTrendPreset, -): Array> { - const latest = utcDateFromDay(latestDate); - - if (preset === "30d") { - return Array.from({ length: 30 }, (_, index) => { - const date = toUtcDateOnly(addUtcDays(latest, index - 29)); - return { key: date, startDate: date, endDate: date }; - }); +export function rankProjectsByCost(sessions: SessionSummary[]): UsageRank[] { + const map = new Map>(); + for (const s of sessions) { + const row = map.get(s.project) ?? { name: s.project, costUsd: 0, tokens: 0, sessions: 0 }; + row.costUsd += s.totalCostUsd; + row.tokens += s.totalTokens; + row.sessions += 1; + map.set(s.project, row); } - - if (preset === "12w") { - const firstWeekStart = addUtcDays(latest, -(12 * 7 - 1)); - return Array.from({ length: 12 }, (_, index) => { - const start = addUtcDays(firstWeekStart, index * 7); - const end = addUtcDays(start, 6); - const startDate = toUtcDateOnly(start); - - return { - key: startDate, - startDate, - endDate: toUtcDateOnly(end), - }; - }); - } - - const firstMonth = new Date( - Date.UTC(latest.getUTCFullYear(), latest.getUTCMonth() - 11, 1), - ); - - return Array.from({ length: 12 }, (_, index) => { - const start = addUtcMonths(firstMonth, index); - const monthEnd = new Date( - Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0), - ); - const end = monthEnd > latest ? latest : monthEnd; - const startDate = toUtcDateOnly(start); - - return { - key: startDate.slice(0, 7), - startDate, - endDate: toUtcDateOnly(end), - }; - }); -} - -export function bucketTokenUsageByProject( - days: DailyTokensByProject[], - preset: UsageTrendPreset, -): TokenUsageBucket[] { - const latestDate = latestTokenDate(days); - if (latestDate === undefined) { - return []; - } - - return tokenTrendRanges(latestDate, preset).map((range) => { - const projectTotals = new Map(); - - for (const day of days) { - if (day.date < range.startDate || day.date > range.endDate) { - continue; - } - for (const project of day.projects) { - projectTotals.set( - project.project, - (projectTotals.get(project.project) ?? 0) + project.tokens, - ); - } - } - - const projects = Array.from(projectTotals.entries()) - .map(([project, tokens]) => ({ project, tokens })) - .sort( - (left, right) => right.tokens - left.tokens || left.project.localeCompare(right.project), - ); - - return { - ...range, - totalTokens: projects.reduce((sum, project) => sum + project.tokens, 0), - projects, - }; - }); + return finishRanks(map); } -function buildTokenHeatmapForRange( - days: DailyTokenUsage[], - start: Date, - end: Date, -): AnnualTokenHeatmap { - const totals = new Map(); - const startDate = toUtcDateOnly(start); - const endDate = toUtcDateOnly(end); - - for (const day of days) { - if (day.date < startDate || day.date > endDate) { - continue; +export function rankModelsByCost(sessions: SessionSummary[]): UsageRank[] { + const map = new Map>(); + for (const s of sessions) { + for (const m of s.modelBreakdown) { + const row = map.get(m.model) ?? { name: m.model, costUsd: 0, tokens: 0, sessions: 0 }; + row.costUsd += m.costUsd; + row.tokens += m.tokens; + row.sessions += 1; + map.set(m.model, row); } - totals.set(day.date, (totals.get(day.date) ?? 0) + day.totalTokens); - } - - const firstWeekday = start.getUTCDay(); - const dayCount = utcDayOffset(start, end) + 1; - const weekCount = Math.ceil((dayCount + firstWeekday) / 7); - const heatmapDays: AnnualTokenUsageDay[] = []; - - for (let dayIndex = 0; dayIndex < dayCount; dayIndex += 1) { - const date = addUtcDays(start, dayIndex); - const dateKey = toUtcDateOnly(date); - - heatmapDays.push({ - date: dateKey, - totalTokens: totals.get(dateKey) ?? 0, - weekdayIndex: date.getUTCDay(), - weekIndex: Math.floor((dayIndex + firstWeekday) / 7), - }); } - - const monthLabels: AnnualTokenMonthLabel[] = []; - for ( - let month = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), 1)); - month <= end; - month = addUtcMonths(month, 1) - ) { - monthLabels.push({ - label: shortMonthLabels[month.getUTCMonth()], - weekIndex: Math.floor((utcDayOffset(start, month) + firstWeekday) / 7), - }); - } - - return { - year: end.getUTCFullYear(), - startDate, - endDate, - days: heatmapDays, - weekCount, - monthLabels, - }; + return finishRanks(map); } -export function buildAnnualTokenHeatmap( - days: DailyTokenUsage[], - year = latestTokenYear(days), -): AnnualTokenHeatmap | null { - if (year === undefined) { - return null; - } - - const start = new Date(Date.UTC(year, 0, 1)); - const end = addUtcDays(start, daysInUtcYear(year) - 1); - - return buildTokenHeatmapForRange(days, start, end); -} - -export function buildTrailingAnnualTokenHeatmap( - days: DailyTokenUsage[], - latestDate = latestTokenDate(days), -): AnnualTokenHeatmap | null { - if (latestDate === undefined) { - return null; - } - - const latest = utcDateFromDay(latestDate); - const start = new Date(Date.UTC(latest.getUTCFullYear(), latest.getUTCMonth() - 11, 1)); - const end = new Date(Date.UTC(latest.getUTCFullYear(), latest.getUTCMonth() + 1, 0)); - - return buildTokenHeatmapForRange(days, start, end); -} - -export function aggregateCostByModel(sessions: SessionSummary[]): ModelCost[] { - const totals = new Map(); +export const localClock: LocalClock = (timestamp) => { + const date = new Date(timestamp); + return { weekday: date.getDay(), hour: date.getHours() }; +}; - for (const session of sessions) { - for (const model of session.modelBreakdown) { - const current = totals.get(model.model) ?? { costUsd: 0, tokens: 0 }; - current.costUsd += model.costUsd; - current.tokens += model.tokens; - totals.set(model.model, current); - } +/** 7 rows (Monday first) × 24 hours. */ +export function aggregateWeekdayHourCost( + sessions: SessionSummary[], + clock: LocalClock = localClock, +): WeekdayHourCell[][] { + const grid = Array.from({ length: 7 }, () => + Array.from({ length: 24 }, (): WeekdayHourCell => ({ costUsd: 0, sessions: 0 })), + ); + for (const s of sessions) { + const { weekday, hour } = clock(s.timestamp); + const cell = grid[(weekday + 6) % 7][hour]; + cell.costUsd += s.totalCostUsd; + cell.sessions += 1; } - - return Array.from(totals.entries()) - .map(([model, usage]) => ({ model, costUsd: usage.costUsd, tokens: usage.tokens })) - .sort((left, right) => right.costUsd - left.costUsd || left.model.localeCompare(right.model)); + return grid; } -export function aggregateModelDistribution(sessions: SessionSummary[]): ModelDistribution[] { - const models = aggregateCostByModel(sessions); - const totalCostUsd = models.reduce((sum, model) => sum + model.costUsd, 0); - const totalTokens = models.reduce((sum, model) => sum + model.tokens, 0); - - return models.map((model) => ({ - ...model, - costShare: totalCostUsd === 0 ? 0 : model.costUsd / totalCostUsd, - tokenShare: totalTokens === 0 ? 0 : model.tokens / totalTokens, - })); +/** + * Rank-based level assignment for sequential colour: level 0 for zero, + * otherwise 1..levels by percentile among the non-zero values. A single + * outlier therefore does not push everything else into the lowest band. + */ +export function rankLevels(values: number[], levels = 5): (value: number) => number { + const sorted = values.filter((v) => v > 0).sort((a, b) => a - b); + return (value) => { + if (value <= 0 || sorted.length === 0) return 0; + // Upper rank: ties share the level of their last occurrence, so equal + // maxima all read as the top band instead of the bottom one. + let index = sorted.findIndex((v) => v > value) - 1; + if (index < -1) index = sorted.length - 1; + const percentile = Math.max(0, index) / Math.max(1, sorted.length - 1); + return Math.min(levels, Math.max(1, Math.ceil(percentile * levels))); + }; } function aggregateNamedCounts( sessions: SessionSummary[], - selectCounts: (session: SessionSummary) => NamedCount[], + select: (session: SessionSummary) => NamedCount[], limit: number, ): NamedCount[] { - if (limit <= 0) { - return []; - } - + if (limit <= 0) return []; const totals = new Map(); - for (const session of sessions) { - for (const item of selectCounts(session)) { - totals.set(item.name, (totals.get(item.name) ?? 0) + item.count); - } + for (const s of sessions) { + for (const item of select(s)) totals.set(item.name, (totals.get(item.name) ?? 0) + item.count); } - return Array.from(totals.entries()) .map(([name, count]) => ({ name, count })) - .sort((left, right) => right.count - left.count || left.name.localeCompare(right.name)) + .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)) .slice(0, limit); } export function aggregateToolCounts(sessions: SessionSummary[], limit = 8): NamedCount[] { - return aggregateNamedCounts(sessions, (session) => session.toolCounts, limit); + return aggregateNamedCounts(sessions, (s) => s.toolCounts, limit); } export function aggregateSkillCounts(sessions: SessionSummary[], limit = 8): NamedCount[] { - return aggregateNamedCounts(sessions, (session) => session.skillCounts, limit); + return aggregateNamedCounts(sessions, (s) => s.skillCounts, limit); } diff --git a/apps/desktop/src/pages/design-catalog.test.tsx b/apps/desktop/src/pages/design-catalog.test.tsx index 35d757ab..58180d5a 100644 --- a/apps/desktop/src/pages/design-catalog.test.tsx +++ b/apps/desktop/src/pages/design-catalog.test.tsx @@ -46,10 +46,10 @@ describe("Component catalog navigation", () => { await user.click(within(screen.getByRole("navigation", { name: "Component catalog" })).getByRole("button", { name: "PiKpi" })); const variant = screen.getByRole("group", { name: "layout=stacked" }); expect(variant.firstElementChild).toHaveTextContent("layout=stacked"); - const target = within(screen.getByRole("navigation", { name: "Component catalog" })).getByRole("button", { name: "PiBarChart" }); + const target = within(screen.getByRole("navigation", { name: "Component catalog" })).getByRole("button", { name: "PiLineChart" }); target.focus(); await user.keyboard("{Enter}"); - expect(screen.getByRole("region", { name: "PiBarChart" })).toBeInTheDocument(); + expect(screen.getByRole("region", { name: "PiLineChart" })).toBeInTheDocument(); expect(target).toHaveAttribute("aria-current", "page"); }); }); diff --git a/apps/desktop/src/pages/design-components.test.tsx b/apps/desktop/src/pages/design-components.test.tsx index 7461d504..b4b69f5e 100644 --- a/apps/desktop/src/pages/design-components.test.tsx +++ b/apps/desktop/src/pages/design-components.test.tsx @@ -30,7 +30,8 @@ describe("Design components layer", () => { for (const name of [ "PiKpi", - "PiBarChart", + "PiLineChart", + "PiHeatmap", "TerminalView", "BrowserSurface", "PiTrajectoryLedger", @@ -62,7 +63,7 @@ describe("Design components layer", () => { } }); - it("shows PiKpi in stacked, inline, delta and empty variants", () => { + it("shows PiKpi in stacked, inline, delta, empty and footer variants", () => { render(); const section = screen.getByRole("region", { name: "PiKpi" }); @@ -71,6 +72,19 @@ describe("Design components layer", () => { expect(within(section).getByText("layout=inline")).toBeInTheDocument(); expect(within(section).getByText("with delta")).toBeInTheDocument(); expect(within(section).getByText("no value")).toBeInTheDocument(); + expect(within(section).getByText("with footer sparkline")).toBeInTheDocument(); + }); + + it("shows the chart primitives with data, empty and tooltip states", () => { + render(); + + const line = screen.getByRole("region", { name: "PiLineChart" }); + expect(within(line).getByText("No usage in this range")).toBeInTheDocument(); + expect(within(line).getByRole("img", { name: "Daily cost demo" })).toBeInTheDocument(); + + const heat = screen.getByRole("region", { name: "PiHeatmap" }); + expect(heat.querySelectorAll('[data-slot="heatmap-cell"][data-level="5"]').length).toBeGreaterThan(0); + expect(within(heat).getByText("all empty")).toBeInTheDocument(); }); it("shows the Cockpit ledger: run headers, row states, focus dim, and empty variant", () => { diff --git a/apps/desktop/src/pages/design-components.tsx b/apps/desktop/src/pages/design-components.tsx index 340957ee..f9917207 100644 --- a/apps/desktop/src/pages/design-components.tsx +++ b/apps/desktop/src/pages/design-components.tsx @@ -5,8 +5,9 @@ import { HStack, VStack } from "@astryxdesign/core/Stack"; import { Text } from "@astryxdesign/core/Text"; import { PaceWordmark } from "@/shared/ui/pace-wordmark"; import { DotMatrix } from "@/shared/ui/dot-matrix"; -import { PiBarChart } from "@/shared/ui/pi-bar-chart"; +import { PiHeatmap } from "@/shared/ui/pi-heatmap"; import { PiKpi } from "@/shared/ui/pi-kpi"; +import { PiLineChart, PiSparkline } from "@/shared/ui/pi-line-chart"; import { SessionDock, SessionDockTrigger, @@ -157,57 +158,103 @@ function PiKpiGallery() { + +
+ } + formatOptions={{ style: "currency", currency: "USD" }} + label="Cost" + value={129.88} + /> +
+
); } -const barChartSeries = [ - { key: "input", label: "Input", color: "var(--pigui-data-blue)" }, - { key: "output", label: "Output", color: "var(--pigui-data-orange)" }, -]; - -const barChartData = ["Mon", "Tue", "Wed", "Thu", "Fri"].map((label, index) => ({ - key: label.toLowerCase(), +const lineChartPoints = ["Jun 1", "Jun 2", "Jun 3", "Jun 4", "Jun 5", "Jun 6", "Jun 7"].map((label, index) => ({ + key: label, label, - values: { input: (index + 1) * 8, output: (index + 1) * 3 }, + value: [1.2, 0, 3.4, 2.1, 0.6, 8.9, 2.4][index], })); -function PiBarChartGallery() { +function PiLineChartGallery() { return ( - + - -
- +
+ ( + + {point.label}: ${point.value.toFixed(2)} + + )} + valueFormatter={(value) => `$${value}`} />
- -
- +
+ +
+ + +
+ +
+
+ + + ); +} + +const heatmapRows = ["Mon", "Tue", "Wed"].map((label) => ({ key: label.toLowerCase(), label })); +const heatmapColumns = Array.from({ length: 12 }, (_, hour) => ({ + key: String(hour), + label: hour % 6 === 0 ? `${String(hour).padStart(2, "0")}:00` : undefined, +})); +const heatmapValues = [ + [0, 0, 1, 3, 5, 2, 0, 0, 4, 9, 1, 0], + [1, 0, 0, 2, 2, 6, 7, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +]; + +function PiHeatmapGallery() { + return ( + + + +
+ `${row.label} ${column.key}:00: ${value}`} + columns={heatmapColumns} + levelOf={(value) => (value === 0 ? 0 : Math.min(5, Math.ceil(value / 2)))} + renderTooltip={(row, column, value) => ( + + {row.label} {column.key}:00 · {value} + + )} + rows={heatmapRows} + values={heatmapValues} />
- -
- - +
+ `${row.label} ${column.key}:00: none`} + columns={heatmapColumns} + levelOf={() => 0} + rows={heatmapRows} + values={heatmapRows.map(() => heatmapColumns.map(() => 0))} />
@@ -2384,7 +2431,8 @@ function ModelSelectorControlGallery() { export const componentExamples: ComponentExample[] = [ { name: "PaceWordmark", category: "Visual primitives", description: "Separated Pace brand lettering with theme-aware color.", Preview: PaceWordmarkGallery }, { name: "PiKpi", category: "Data & metrics", description: "At-a-glance metrics, totals, deltas, and missing values.", Preview: PiKpiGallery }, - { name: "PiBarChart", category: "Data & metrics", description: "Compare usage across time with single or stacked series.", Preview: PiBarChartGallery }, + { name: "PiLineChart", category: "Data & metrics", description: "Single-series trend with crosshair hover, plus the decorative PiSparkline.", Preview: PiLineChartGallery }, + { name: "PiHeatmap", category: "Data & metrics", description: "Row × column grid on one sequential hue; levels come from the caller.", Preview: PiHeatmapGallery }, { name: "ChatRunFailure", category: "Conversation", description: "Readable failures, provider settings, model changes, and request retries.", Preview: ChatRunFailureGallery }, { name: "ChatMessage", category: "Conversation", description: "User and assistant messages with attachments and actions.", Preview: ChatMessageGallery }, { name: "ChatConversation", category: "Conversation", description: "Scrollable conversation history with automatic bottom pinning.", Preview: ChatConversationGallery }, diff --git a/apps/desktop/src/pages/usage-tooltip.test.tsx b/apps/desktop/src/pages/usage-tooltip.test.tsx deleted file mode 100644 index b5ac6110..00000000 --- a/apps/desktop/src/pages/usage-tooltip.test.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { render } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; -import { UsageTrendChart } from "@/pages/usage"; - -describe("UsageTrendChart tooltip", () => { - it("does not render a tooltip for zero-total buckets", () => { - const { container } = render( - , - ); - - expect(container.querySelector('[data-slot="bar-chart-tooltip"]')).toBeNull(); - }); - - it("keeps only non-zero projects for an active bucket", () => { - const { container } = render( - , - ); - - const tooltip = container.querySelector( - '[data-bucket-key="2026-06-26"] [data-slot="bar-chart-tooltip"]', - ); - - expect(tooltip).not.toBeNull(); - expect(tooltip).toHaveTextContent("Jun 26"); - expect(tooltip).toHaveTextContent("alpha"); - expect(tooltip).toHaveTextContent("120 tokens"); - expect(tooltip).not.toHaveTextContent("beta"); - // Only one bucket has activity, so only one tooltip exists at all. - expect( - container.querySelectorAll('[data-slot="bar-chart-tooltip"]'), - ).toHaveLength(1); - }); -}); diff --git a/apps/desktop/src/pages/usage.test.tsx b/apps/desktop/src/pages/usage.test.tsx index bfe6f0c1..61bf959b 100644 --- a/apps/desktop/src/pages/usage.test.tsx +++ b/apps/desktop/src/pages/usage.test.tsx @@ -1,292 +1,98 @@ -import { render, screen } from "@testing-library/react"; +import { render, screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import type { SessionSummary } from "@/entities/session/sessions"; -import { - ModelMixCard, - TokenHeatmap, - UsageTrendChart, - UsageTrendSection, - UsageSecondLayer, - UsageSummaryPanel, -} from "@/pages/usage"; +import { UsageDashboard } from "@/pages/usage"; function session(overrides: Partial = {}): SessionSummary { return { id: "usage-fixture", - timestamp: "2026-01-01T10:00:00.000Z", - project: "alpha", + timestamp: "2026-06-26T10:00:00.000Z", + project: "/Users/void/code/alpha", title: { kind: "raw", text: "usage-fixture" }, totalCostUsd: 1, totalTokens: 1000, primaryModel: "gpt-5-codex", - modelBreakdown: [], - toolCounts: [], + modelBreakdown: [{ model: "gpt-5-codex", costUsd: 1, tokens: 1000 }], + toolCounts: [{ name: "Read", count: 2 }], skillCounts: [], presence: "external", ...overrides, }; } -describe("UsageSecondLayer", () => { - it("renders model, tool, and skill usage sections from session summaries", () => { - const { container } = render( - , - ); - - expect(screen.getByRole("heading", { name: "Tool calls" })).toBeInTheDocument(); - expect(screen.getByRole("heading", { name: "Skill usage" })).toBeInTheDocument(); - expect(screen.getByText("read_file")).toBeInTheDocument(); - expect(screen.getByText("run_command")).toBeInTheDocument(); - expect(screen.queryByText("long_tail_tool")).not.toBeInTheDocument(); - expect(screen.getByText("review")).toBeInTheDocument(); - expect(container.querySelectorAll(".astryx-card")).toHaveLength(2); - expect(screen.getAllByTestId("rank-card-content")).toHaveLength(2); - expect( - screen.getAllByTestId("rank-card-content").every((content) => content.classList.contains("p-5")), - ).toBe(true); - }); - - it("renders an empty skill state for sparse skill usage", () => { - render(); +const sessions = [ + session({ id: "a", timestamp: "2026-06-26T10:00:00.000Z", totalCostUsd: 3 }), + session({ id: "b", timestamp: "2026-06-24T10:00:00.000Z", totalCostUsd: 1, project: "/Users/void/code/beta" }), + session({ id: "c", timestamp: "2026-06-10T10:00:00.000Z", totalCostUsd: 2 }), + session({ id: "d", timestamp: "2026-05-01T10:00:00.000Z", totalCostUsd: 40 }), +]; - expect(screen.getByText("No skill usage yet.")).toBeInTheDocument(); - }); -}); - -describe("UsageTrendChart", () => { - it("renders a stable set of project token buckets with a fixed bar width", () => { - const { container } = render( - , - ); +const utcClock = (timestamp: string) => { + const date = new Date(timestamp); + return { weekday: date.getUTCDay(), hour: date.getUTCHours() }; +}; - const viewport = screen.getByTestId("usage-trend-chart-viewport"); - const chart = container.querySelector('[data-slot="bar-chart"]'); +describe("UsageDashboard", () => { + it("defaults to the last 30 days with four KPI tiles and a period-over-period delta", () => { + const { container } = render(); - expect(viewport).toHaveAttribute("data-preset", "30d"); - expect(viewport).toHaveAttribute("data-bucket-count", "30"); - expect(viewport).toHaveAttribute("data-bar-size", "14"); - expect(chart).toHaveAttribute("aria-label", "Token usage trend by project chart"); - expect(viewport).toContainElement(chart); + expect(screen.getByRole("radio", { name: "30D" })).toBeChecked(); + expect(container.querySelectorAll('[data-slot="kpi"]')).toHaveLength(4); + const cost = screen.getByText("Cost").closest('[data-slot="kpi"]')!; + expect(within(cost).getByText("$6.00")).toBeInTheDocument(); + // Window is May 28 – Jun 26 ($6); the previous 30 days hold the $40 session. + expect(within(cost).getByText("-85% vs previous 30 days")).toBeInTheDocument(); + expect(container.querySelectorAll('[data-slot="kpi-footer"] polyline')).toHaveLength(4); }); -}); -describe("UsageTrendSection", () => { - it("offers stable trend presets and defaults to 30 daily buckets", async () => { + it("re-scopes every section when the period changes", async () => { const user = userEvent.setup(); + render(); - render( - , - ); - - expect(screen.getByRole("heading", { name: "Usage trend" })).toBeInTheDocument(); - expect(screen.getByText("30D")).toBeInTheDocument(); - expect(screen.getByText("12W")).toBeInTheDocument(); - expect(screen.getByText("12M")).toBeInTheDocument(); - expect(screen.queryByText("Today")).not.toBeInTheDocument(); - expect(screen.getByTestId("usage-trend-chart-viewport")).toHaveAttribute( - "data-preset", - "30d", - ); - expect(screen.getByTestId("usage-trend-card-content")).toHaveClass("p-5"); + await user.click(screen.getByRole("radio", { name: "7D" })); - await user.click(screen.getByText("12W")); + const cost = screen.getByText("Cost").closest('[data-slot="kpi"]')!; + expect(within(cost).getByText("$4.00")).toBeInTheDocument(); + const byProject = screen.getByRole("region", { name: "By project" }); + expect(within(byProject).getByText("alpha")).toBeInTheDocument(); + expect(within(byProject).getByText("beta")).toBeInTheDocument(); - expect(screen.getByTestId("usage-trend-chart-viewport")).toHaveAttribute( - "data-preset", - "12w", - ); - expect(screen.getByTestId("usage-trend-chart-viewport")).toHaveAttribute( - "data-bucket-count", - "12", - ); + await user.click(screen.getByRole("radio", { name: "All" })); + expect(within(cost).getByText("$46.00")).toBeInTheDocument(); + expect(within(cost).queryByText(/vs previous/)).toBeNull(); }); -}); -describe("ModelMixCard", () => { - it("renders a colorful token distribution with model cost context", () => { - const { container } = render( - , - ); + it("renders the weekday × hour rhythm grid in the supplied clock", () => { + render(); - expect(screen.getByRole("heading", { name: "Model mix" })).toBeInTheDocument(); - expect(screen.getByRole("img", { name: "Model token distribution" })).toBeInTheDocument(); - expect(screen.getByText("gpt-5-codex")).toBeInTheDocument(); - expect(screen.getByText("gpt-5-mini")).toBeInTheDocument(); - expect(screen.getByText("80%")).toBeInTheDocument(); - expect(screen.getByText("20%")).toBeInTheDocument(); - expect(container.innerHTML).toContain("--pigui-data-orange"); - expect(screen.getByTestId("model-mix-card-content")).toHaveClass("p-5"); + const rhythm = screen.getByRole("region", { name: "Rhythm" }); + expect(within(rhythm).getAllByRole("img")).toHaveLength(7 * 24); + // 2026-06-26 10:00Z is a Friday. + expect(within(rhythm).getByRole("img", { name: /Fri 10:00.*\$3\.00/ })).toHaveAttribute("data-level", "5"); }); -}); - -describe("TokenHeatmap", () => { - it("renders the latest full year as daily cells", () => { - const { container } = render( - , - ); - const grid = screen.getByTestId("token-heatmap-grid"); - const calendar = screen.getByTestId("token-heatmap-calendar"); - const firstCell = container.querySelector("[data-token-day]"); - const monthHeader = grid.previousElementSibling; - const layout = screen.getByTestId("token-heatmap-layout"); - const summary = screen.getByTestId("token-heatmap-summary"); - const legendDots = summary.querySelectorAll("[aria-hidden].size-3"); + it("explains the empty state and how to get data", () => { + render(); - expect(screen.getByRole("heading", { name: "Token activity" })).toBeInTheDocument(); - expect(container.querySelector('[data-slot="tabs"]')).not.toBeInTheDocument(); - expect(screen.queryByText("Weekly")).not.toBeInTheDocument(); - expect(screen.queryByText("Cumulative")).not.toBeInTheDocument(); - expect(screen.getByTestId("token-heatmap-card-content")).toHaveClass("p-5"); - expect(layout).toHaveClass("xl:grid-cols-[max-content_minmax(7rem,1fr)]"); - expect(layout).toContainElement(calendar); - expect(layout).toContainElement(summary); - expect(summary).toHaveClass("xl:border-l", "xl:border-t-0"); - expect(calendar).toHaveClass("w-max"); - expect(calendar).not.toHaveClass("w-full"); - expect(grid).toHaveAttribute("data-year", "2026"); - expect(grid).not.toHaveAttribute("data-mode"); - expect(grid).toHaveAttribute("data-day-count", "365"); - expect(grid).toHaveStyle({ - gridTemplateColumns: "repeat(53, 0.75rem)", - }); - expect(monthHeader).toHaveStyle({ - gridTemplateColumns: "repeat(53, 0.75rem)", - }); - expect(grid).toHaveClass("gap-0.5"); - expect(monthHeader).toHaveClass("gap-0.5"); - expect(container.querySelectorAll("[data-token-day]")).toHaveLength(365); - expect(firstCell).toHaveClass("size-3", "justify-self-center", "rounded-full"); - expect(firstCell).not.toHaveClass("border", "border-border"); - expect(firstCell).not.toHaveClass("rounded-[4px]"); - expect(firstCell).toHaveStyle({ backgroundColor: "var(--surface-secondary)" }); - expect(firstCell).toHaveAttribute("data-tokens", "0"); - expect(firstCell).toHaveAttribute("data-activity-value", "0"); - expect(firstCell).toHaveAttribute("data-date", "2025-07-01"); - expect(container.querySelector('[data-date="2026-03-20"]')).toHaveAttribute( - "data-tokens", - "100", - ); - expect(container.querySelector('[data-date="2026-03-20"]')).toHaveStyle({ - backgroundColor: "var(--pigui-data-coral)", - }); - expect(container.innerHTML).not.toContain("--pigui-color-"); - expect(container.querySelector('[data-date="2026-06-30"]')).toHaveAttribute( - "data-tokens", - "0", - ); - expect(container.querySelectorAll("[data-month-label]")).toHaveLength(12); - expect(container.querySelector('[data-month-label="Jul"]')).toHaveStyle({ - gridColumnStart: "1", - }); - expect(container.querySelector('[data-month-label="Jun"]')).toBeInTheDocument(); - expect(container.querySelector("[data-weekday-label]")).not.toBeInTheDocument(); - expect(screen.getByText("Less")).toBeInTheDocument(); - expect(screen.getByText("More")).toBeInTheDocument(); - expect(legendDots).toHaveLength(5); - expect(Array.from(legendDots).every((dot) => !dot.classList.contains("border"))).toBe(true); - expect(screen.getByLabelText("2 active days")).toBeInTheDocument(); - expect(screen.getByLabelText("250 peak day")).toBeInTheDocument(); + expect(screen.getByRole("heading", { name: "No sessions recorded yet" })).toBeInTheDocument(); + expect(screen.getByText(/Start one from Trajectory/)).toBeInTheDocument(); }); -}); -describe("UsageSummaryPanel", () => { - it("starts with KPI cards instead of repeating the current route", () => { - const source = readFileSync(join(process.cwd(), "apps/desktop/src/pages/usage.tsx"), "utf8"); + it("keeps the refresh action wrapped in a tooltip trigger", () => { + render( {}} />); - expect(source).not.toContain(">Usage
"); - expect(source).not.toContain("Analyze / Usage"); - expect(source).not.toContain("Cost and token trends"); - expect(source).not.toContain("Cost is shown as API list price"); - expect(source).toContain("max-w-5xl"); - expect(source).not.toContain("max-w-6xl"); - }); - - it("keeps summary KPI cards visually aligned without repeated pricing copy", () => { - const { container } = render( - {}} />, + expect(screen.getByTestId("usage-refresh-tooltip-trigger")).toContainElement( + screen.getByRole("button", { name: "Refresh usage" }), ); - - const summary = screen.getByTestId("usage-summary"); - - expect(summary.classList.contains("astryx-card")).toBe(false); - expect(summary.closest(".astryx-card")).toBeNull(); - expect(container.querySelector('[data-slot="kpi-footer"]')).not.toBeInTheDocument(); - expect(container.querySelectorAll('[data-slot="kpi"]')).toHaveLength(4); - expect(screen.getByText("Sessions")).toBeInTheDocument(); - expect(screen.queryByText("Usage summary")).not.toBeInTheDocument(); - expect(screen.queryByText("All sessions")).not.toBeInTheDocument(); - expect(screen.queryByText("API list price")).not.toBeInTheDocument(); }); - it("wraps the icon-only refresh action with a tooltip trigger", () => { - render( {}} />); - - const refreshButton = screen.getByRole("button", { name: "Refresh usage" }); - const tooltipTrigger = screen.getByTestId("usage-refresh-tooltip-trigger"); + it("uses only data tokens for series colour", () => { + const source = readFileSync(join(process.cwd(), "apps/desktop/src/pages/usage.tsx"), "utf8"); - expect(tooltipTrigger).toContainElement(refreshButton); + expect(source).not.toMatch(/#[0-9a-f]{3,6}\b/i); + expect(source).not.toMatch(/var\(--(success|warning|danger)\)/); }); }); diff --git a/apps/desktop/src/pages/usage.tsx b/apps/desktop/src/pages/usage.tsx index f3415796..94627e9b 100644 --- a/apps/desktop/src/pages/usage.tsx +++ b/apps/desktop/src/pages/usage.tsx @@ -2,23 +2,16 @@ import { useQuery } from "@tanstack/react-query"; import { Card } from "@astryxdesign/core/Card"; import { EmptyState } from "@astryxdesign/core/EmptyState"; import { IconButton } from "@astryxdesign/core/IconButton"; -import { - SegmentedControl, - SegmentedControlItem, -} from "@astryxdesign/core/SegmentedControl"; -import { useMemo, useState } from "react"; -import { Cell, Pie, PieChart, Tooltip as RechartsTooltip } from "recharts"; +import { SegmentedControl, SegmentedControlItem } from "@astryxdesign/core/SegmentedControl"; +import { Heading, Text } from "@astryxdesign/core/Text"; +import { useMemo, useState, type ReactNode } from "react"; import { AppFrame } from "@/app/app-shell"; import { RefreshCw } from "@/shared/ui/icons"; -import { - PiBarChart, - type PiBarChartDatum, - type PiBarChartSeries, -} from "@/shared/ui/pi-bar-chart"; +import { PiHeatmap } from "@/shared/ui/pi-heatmap"; import { PiKpi } from "@/shared/ui/pi-kpi"; +import { PiLineChart, PiSparkline, type PiLinePoint } from "@/shared/ui/pi-line-chart"; import { useRefreshOnWindowFocus } from "@/shared/refresh"; import { - formatCost, formatDateLabel, formatTokens, listSessions, @@ -26,623 +19,462 @@ import { type SessionSummary, } from "@/entities/session/sessions"; import { - aggregateDailyTokens, - aggregateDailyTokensByProject, - aggregateModelDistribution, + aggregateDailyCost, aggregateSkillCounts, aggregateToolCounts, - bucketTokenUsageByProject, - buildTrailingAnnualTokenHeatmap, - type DailyTokensByProject, - type DailyTokenUsage, - type ModelDistribution, - type TokenUsageBucket, - type UsageTrendPreset, + aggregateWeekdayHourCost, + localClock, + rankLevels, + rankModelsByCost, + rankProjectsByCost, + splitUsagePeriod, + summarizeUsage, + usageDelta, + usagePeriods, + type DailyCost, + type LocalClock, + type UsageDelta, + type UsagePeriod, + type UsageRank, } from "@/entities/session/usage-aggregation"; -const chartColorCount = 5; -const defaultRankLimit = 8; -const usageCardContentClass = "p-5"; -const usageTrendBarSize = 14; -const usageKpiValueClass = "tabular-nums text-[var(--pigui-data-blue)]"; -const usageChartColors = [ +// Cost is the page's primary axis. Categorical series colours are assigned +// in this fixed order by rank and never cycled; a sixth entity folds into +// "Other" (slate). Series colour is only ever a `--pigui-data-*` token. +const seriesColors = [ "var(--pigui-data-blue)", "var(--pigui-data-orange)", + "var(--pigui-data-green)", "var(--pigui-data-amber)", "var(--pigui-data-coral)", - "var(--pigui-data-slate)", -]; -const usageTrendPresetOptions: Array<{ - id: UsageTrendPreset; - label: string; - description: string; -}> = [ - { id: "30d", label: "30D", description: "Daily buckets · last 30 days" }, - { id: "12w", label: "12W", description: "Weekly buckets · last 12 weeks" }, - { id: "12m", label: "12M", description: "Monthly buckets · last 12 months" }, ] as const; - -function projectColor(project: string, projects: string[]) { - const index = Math.max(0, projects.indexOf(project)); - return chartColor(index); +const otherColor = "var(--pigui-data-slate)"; +const trendColor = seriesColors[0]; +const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const; +const hours = Array.from({ length: 24 }, (_, hour) => ({ + key: String(hour), + label: hour % 6 === 0 ? `${String(hour).padStart(2, "0")}:00` : undefined, +})); + +function colorByRank(names: string[]) { + const map = new Map(names.map((name, index) => [name, seriesColors[index] ?? otherColor])); + return (name: string) => map.get(name) ?? otherColor; } -function heatColor(level: number) { - return [ - "var(--surface-secondary)", - "var(--pigui-data-peach)", - "var(--pigui-data-coral)", - "var(--pigui-data-orange)", - "var(--pigui-data-orange-strong)", - ][level]; -} - -function chartColor(index: number) { - return usageChartColors[index % chartColorCount]; -} - -function formatPercent(value: number) { +function money(value: number, digits = 2) { return new Intl.NumberFormat(undefined, { - style: "percent", - maximumFractionDigits: 0, + style: "currency", + currency: "USD", + minimumFractionDigits: digits, + maximumFractionDigits: digits, }).format(value); } -function isUsageTrendPreset(value: string): value is UsageTrendPreset { - return usageTrendPresetOptions.some((option) => option.id === value); +/** Two decimals for headlines; sub-cent costs read as "<$0.01" instead of "$0.00". */ +function moneyAuto(value: number) { + return value > 0 && value < 0.01 ? `<${money(0.01)}` : money(value); } -function summarizeSessions(sessions: SessionSummary[]) { - return sessions.reduce( - (summary, session) => ({ - totalCostUsd: summary.totalCostUsd + session.totalCostUsd, - totalTokens: summary.totalTokens + session.totalTokens, - projects: summary.projects.add(session.project), - }), - { totalCostUsd: 0, totalTokens: 0, projects: new Set() }, - ); +function percent(value: number) { + return new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 0 }).format(value); } -function EmptyUsageState({ children }: { children: string }) { - return ; +function shortProject(path: string) { + const parts = path.split("/").filter(Boolean); + return parts[parts.length - 1] ?? path; } -/** - * Chart-adjacent rank bar with a per-item palette color. Astryx ProgressBar - * only exposes semantic variants, so the track/fill pair is hand-rolled on - * tokenized utilities instead. - */ -function RankBar({ label, value, color }: { label: string; value: number; color: string }) { +function deltaLabel(delta: UsageDelta | null, days: number | null) { + if (!delta || days === null) return null; + if (delta.kind === "new") return `no usage in previous ${days} days`; + if (delta.kind === "flat") return `no change vs previous ${days} days`; + return `${delta.ratio > 0 ? "+" : ""}${percent(delta.ratio)} vs previous ${days} days`; +} + +function Swatch({ color }: { color: string }) { return ( -
- -
+ ); } -function NamedRankList({ +function UsageWidget({ title, meta, - items, - emptyLabel, + actions, + children, }: { title: string; meta: string; - items: NamedCount[]; - emptyLabel: string; + actions?: ReactNode; + children: ReactNode; }) { - const maxCount = Math.max(...items.map((item) => item.count), 0); - return ( - -
-
-
-

{title}

-

{meta}

+ +
+
+
+ {title} + + {meta} +
- - Top {Math.min(defaultRankLimit, items.length || defaultRankLimit)} - + {actions}
- {items.length === 0 ? ( - {emptyLabel} - ) : ( -
- {items.map((item, index) => { - const width = maxCount === 0 ? 0 : Math.max(2, (item.count / maxCount) * 100); - - return ( -
-
- - {item.name} - - {item.count} -
- -
- ); - })} -
- )} -
+ {children} + ); } -export function UsageSecondLayer({ - sessions, - rankLimit = defaultRankLimit, +function UsageKpi({ + label, + value, + delta, + spark, }: { - sessions: SessionSummary[]; - rankLimit?: number; + label: string; + value: string; + delta: string | null; + spark: number[]; }) { - const toolCounts = useMemo(() => aggregateToolCounts(sessions, rankLimit), [sessions, rankLimit]); - const skillCounts = useMemo(() => aggregateSkillCounts(sessions, rankLimit), [sessions, rankLimit]); - return ( -
- - -
+ } + label={label} + > + {value} + ); } -export function UsageSummaryPanel({ - sessions, - isFetching, - onRefresh, -}: { - sessions: SessionSummary[]; - isFetching: boolean; - onRefresh: () => void; -}) { - const summary = summarizeSessions(sessions); - +function CostTrendTooltip({ day, colorFor }: { day: DailyCost; colorFor: (project: string) => string }) { return ( -
-
- } - isDisabled={isFetching} - label="Refresh usage" - size="sm" - tooltip="Refresh usage data" - variant="secondary" - onClick={onRefresh} - /> -
- -
- - - - -
-
+ <> + + {formatDateLabel(day.date)} · {day.sessions} {day.sessions === 1 ? "session" : "sessions"} + + + {money(day.costUsd)} + + {day.projects.slice(0, 4).map((project) => ( +
+ + + + {shortProject(project.project)} + + + + {money(project.costUsd)} + +
+ ))} + ); } -function usageTrendLabel(bucket: TokenUsageBucket, preset: UsageTrendPreset) { - if (preset === "12m") { - return new Intl.DateTimeFormat(undefined, { month: "short" }).format( - new Date(`${bucket.startDate}T00:00:00.000Z`), - ); - } - return formatDateLabel(bucket.startDate); -} - -function usageTrendTooltipLabel(bucket: TokenUsageBucket) { - if (bucket.startDate === bucket.endDate) { - return formatDateLabel(bucket.startDate); - } - return `${formatDateLabel(bucket.startDate)} – ${formatDateLabel(bucket.endDate)}`; -} - -export function UsageTrendChart({ - days, - projects, - preset, +/** Edge-to-edge rank rows: name, proportional bar, value. Never card-wrapped. */ +function RankRows({ + rows, + colorFor, + label = (row) => row.name, + meta, + emptyLabel, }: { - days: DailyTokensByProject[]; - projects: string[]; - preset: UsageTrendPreset; + rows: UsageRank[]; + colorFor: (name: string) => string; + label?: (row: UsageRank) => string; + meta: (row: UsageRank) => string; + emptyLabel: string; }) { - const buckets = useMemo(() => bucketTokenUsageByProject(days, preset), [days, preset]); - const series = useMemo( - () => - projects.map((project, index) => ({ - color: projectColor(project, projects), - key: `project_${index}`, - label: project, - })), - [projects], - ); - const data = useMemo( - () => - buckets.map((bucket) => { - const tokensByProject = new Map( - bucket.projects.map((project) => [project.project, project.tokens]), - ); - - return { - key: bucket.key, - label: usageTrendLabel(bucket, preset), - tooltipLabel: usageTrendTooltipLabel(bucket), - values: Object.fromEntries( - series.map((item) => [item.key, tokensByProject.get(item.label) ?? 0]), - ), - }; - }), - [buckets, preset, series], - ); - const tickInterval = preset === "30d" ? 4 : 0; - - if (buckets.length === 0) { - return No sessions found.; + if (rows.length === 0) { + return ; } + const max = Math.max(...rows.map((row) => row.costUsd), 0); return ( -
- `${formatTokens(value)} tokens`} - /> -
+
    + {rows.map((row) => ( +
  • + + + + {label(row)} + + + + {moneyAuto(row.costUsd)} + + + + + + + {meta(row)} + + +
  • + ))} +
); } -export function UsageTrendSection({ - days, - projects, -}: { - days: DailyTokensByProject[]; - projects: string[]; -}) { - const [preset, setPreset] = useState("30d"); - const description = - usageTrendPresetOptions.find((option) => option.id === preset)?.description ?? - usageTrendPresetOptions[0].description; +function CountRows({ items, emptyLabel }: { items: NamedCount[]; emptyLabel: string }) { + if (items.length === 0) { + return ; + } + const max = Math.max(...items.map((item) => item.count), 0); return ( -
- -
-
-
-

Usage trend

-

{description}

-
- { - setPreset(isUsageTrendPreset(value) ? value : "30d"); - }} - > - {usageTrendPresetOptions.map((option) => ( - - ))} - -
- - {projects.length > 0 ? ( -
- {projects.slice(0, chartColorCount).map((project, index) => ( - - - {project} - - ))} -
- ) : null} -
-
-
+
    + {items.map((item) => ( +
  • + + {item.name} + + + + + + {item.count} + +
  • + ))} +
); } -type ModelMixRow = ModelDistribution & { color: string }; - -function modelMixRows(models: ModelDistribution[]): ModelMixRow[] { - const sorted = [...models].sort( - (left, right) => right.tokens - left.tokens || left.model.localeCompare(right.model), +export function UsageDashboard({ + sessions, + clock = localClock, + isFetching = false, + onRefresh, +}: { + sessions: SessionSummary[]; + /** Weekday/hour resolver for the rhythm grid; defaults to the local clock. */ + clock?: LocalClock; + isFetching?: boolean; + onRefresh?: () => void; +}) { + const [period, setPeriod] = useState("30d"); + const spec = usagePeriods.find((item) => item.id === period) ?? usagePeriods[1]; + const { current, previous } = useMemo(() => splitUsagePeriod(sessions, period), [sessions, period]); + const summary = summarizeUsage(current.sessions); + const previousSummary = previous ? summarizeUsage(previous.sessions) : null; + const days = useMemo(() => aggregateDailyCost(current), [current]); + const projects = useMemo(() => rankProjectsByCost(current.sessions), [current]); + const models = useMemo(() => rankModelsByCost(current.sessions), [current]); + const tools = useMemo(() => aggregateToolCounts(current.sessions), [current]); + const skills = useMemo(() => aggregateSkillCounts(current.sessions), [current]); + const rhythm = useMemo(() => aggregateWeekdayHourCost(current.sessions, clock), [current, clock]); + const rhythmLevel = useMemo(() => rankLevels(rhythm.flat().map((cell) => cell.costUsd)), [rhythm]); + const projectColor = useMemo(() => colorByRank(projects.map((row) => row.name)), [projects]); + const modelColor = useMemo(() => colorByRank(models.map((row) => row.name)), [models]); + const trend = useMemo( + () => days.map((day) => ({ key: day.date, label: formatDateLabel(day.date), value: day.costUsd })), + [days], ); - const visible = sorted.length > 4 ? sorted.slice(0, 3) : sorted; - const hidden = sorted.length > 4 ? sorted.slice(3) : []; - const rows: ModelDistribution[] = [...visible]; - - if (hidden.length > 0) { - rows.push({ - model: "Other", - costUsd: hidden.reduce((sum, model) => sum + model.costUsd, 0), - tokens: hidden.reduce((sum, model) => sum + model.tokens, 0), - costShare: hidden.reduce((sum, model) => sum + model.costShare, 0), - tokenShare: hidden.reduce((sum, model) => sum + model.tokenShare, 0), - }); + const dayByKey = useMemo(() => new Map(days.map((day) => [day.date, day])), [days]); + const averageCost = summary.sessions === 0 ? 0 : summary.costUsd / summary.sessions; + const previousAverage = + previousSummary === null ? null : previousSummary.sessions === 0 ? 0 : previousSummary.costUsd / previousSummary.sessions; + const scope = spec.days === null ? "all time" : "this period"; + + if (sessions.length === 0) { + return ( + + ); } - return rows.map((model, index) => ({ ...model, color: chartColor(index) })); -} - -export function ModelMixCard({ sessions }: { sessions: SessionSummary[] }) { - const models = useMemo(() => modelMixRows(aggregateModelDistribution(sessions)), [sessions]); - const totalTokens = models.reduce((sum, model) => sum + model.tokens, 0); - return ( - -
-
-

Model mix

-

Share of total tokens

+
+
+ + {current.start === current.end + ? formatDateLabel(current.start) + : `${formatDateLabel(current.start)} – ${formatDateLabel(current.end)}`} + +
+ setPeriod(usagePeriods.some((item) => item.id === value) ? (value as UsagePeriod) : "30d")} + > + {usagePeriods.map((item) => ( + + ))} + + {onRefresh ? ( + + } + isDisabled={isFetching} + label="Refresh usage" + size="sm" + tooltip="Refresh usage data" + variant="ghost" + onClick={onRefresh} + /> + + ) : null}
- {models.length === 0 ? ( -
- No model distribution yet. -
- ) : ( -
-
- - - {models.map((model) => ( - - ))} - - [`${formatTokens(Number(value))} tokens`, "Usage"]} - /> - -
- - {formatTokens(totalTokens)} - - tokens -
-
-
- {models.map((model) => ( -
-
-
- - - {model.model} - -
-

- {formatTokens(model.tokens)} · {formatCost(model.costUsd)} -

-
- - {formatPercent(model.tokenShare)} - -
- ))} -
-
- )}
- - ); -} - -function heatLevel(tokens: number, maxTokens: number) { - if (tokens === 0 || maxTokens === 0) { - return 0; - } - - return Math.min(4, Math.max(1, Math.ceil((tokens / maxTokens) * 4))); -} -export function TokenHeatmap({ days }: { days: DailyTokenUsage[] }) { - const heatmap = useMemo(() => buildTrailingAnnualTokenHeatmap(days), [days]); - - if (!heatmap) { - return No token usage yet.; - } - - const activeDays = heatmap.days.filter((day) => day.totalTokens > 0).length; - const peakDayTokens = Math.max(...heatmap.days.map((day) => day.totalTokens), 0); - const maxTokens = peakDayTokens; - - return ( - -
-
-

Token activity

-

Daily total tokens over the last year

-
-
-
-
-
-
- {heatmap.monthLabels.map((month, index) => { - const nextMonth = heatmap.monthLabels[index + 1]; - - return ( - - {month.label} - - ); - })} -
-
- {heatmap.days.map((day) => { - const activityValue = day.totalTokens; - const level = heatLevel(activityValue, maxTokens); +
+ day.costUsd)} + value={money(summary.costUsd)} + /> + day.tokens)} + value={formatTokens(summary.tokens)} + /> + day.sessions)} + value={String(summary.sessions)} + /> + (day.sessions === 0 ? 0 : day.costUsd / day.sessions))} + value={moneyAuto(averageCost)} + /> +
- return ( -
- ); - })} -
-
-
+ + { + const day = dayByKey.get(point.key); + return day ? : null; + }} + valueFormatter={(value) => money(value, value >= 10 ? 0 : 1)} + /> + {projects.length > 0 ? ( +
+ {projects.slice(0, seriesColors.length).map((project) => ( + + + {shortProject(project.name)} + + ))} + {projects.length > seriesColors.length ? ( + + + Other ({projects.length - seriesColors.length}) + + ) : null}
-
-
-
Active days
-
- {activeDays} -
-
-
-
Peak day
-
- {formatTokens(peakDayTokens)} -
-
-
-
- Less - More -
-
- {[0, 1, 2, 3, 4].map((level) => ( - - ))} -
-
+ ) : null} + + + + + Less + + {[0, 1, 2, 3, 4, 5].map((level) => ( + + ))} + + More +
-
+ } + meta={`Cost by weekday and hour, local time, ${scope}`} + title="Rhythm" + > + + `${row.label} ${String(column.key).padStart(2, "0")}:00: ${ + value === 0 ? "no sessions" : `${money(value)}, ${rhythm[row.index][Number(column.key)].sessions} sessions` + }` + } + columns={hours} + levelOf={rhythmLevel} + renderTooltip={(row, column, value) => { + const hour = Number(column.key); + const cell = rhythm[row.index][hour]; + return ( + <> + + {row.label} · {String(hour).padStart(2, "0")}:00–{String((hour + 1) % 24).padStart(2, "0")}:00 + + + {cell.sessions === 0 ? "No sessions" : `${money(value)} · ${cell.sessions} ${cell.sessions === 1 ? "session" : "sessions"}`} + + + ); + }} + rows={weekdays.map((label, index) => ({ key: label.toLowerCase(), label, index }))} + values={rhythm.map((row) => row.map((cell) => cell.costUsd))} + /> + + +
+ + shortProject(row.name)} + meta={(row) => `${percent(row.share)} · ${row.sessions} ${row.sessions === 1 ? "session" : "sessions"}`} + rows={projects} + /> + + + `${percent(row.share)} · ${formatTokens(row.tokens)} tokens`} + rows={models} + /> +
- + +
+ + + + + + +
+
); } @@ -651,49 +483,23 @@ export function UsagePage() { queryKey: ["sessions"], queryFn: listSessions, }); - const allSessions = sessions.data ?? []; - const tokenDays = useMemo(() => aggregateDailyTokens(allSessions), [allSessions]); - const tokenProjectDays = useMemo( - () => aggregateDailyTokensByProject(allSessions), - [allSessions], - ); - const projects = useMemo( - () => Array.from(new Set(allSessions.map((session) => session.project))).sort(), - [allSessions], - ); useRefreshOnWindowFocus(sessions.refetch); return (
-
+
{sessions.isError ? ( - + ) : sessions.isLoading ? ( ) : ( - <> - sessions.refetch()} - /> - -
- - -
- -
- -
- - - + sessions.refetch()} + /> )}
diff --git a/apps/desktop/src/shared/ui/contract.test.tsx b/apps/desktop/src/shared/ui/contract.test.tsx index 7b2d620b..f2a630b2 100644 --- a/apps/desktop/src/shared/ui/contract.test.tsx +++ b/apps/desktop/src/shared/ui/contract.test.tsx @@ -29,8 +29,9 @@ import { ContextUsageMeter } from "@/shared/ui/context-usage-meter"; import { DotMatrix } from "@/shared/ui/dot-matrix"; import { Activity, AnimatedHistory } from "@/shared/ui/icons"; import { ModelSelectorControl } from "@/shared/ui/model-selector/model-selector-control"; -import { PiBarChart } from "@/shared/ui/pi-bar-chart"; +import { PiHeatmap } from "@/shared/ui/pi-heatmap"; import { PiKpi } from "@/shared/ui/pi-kpi"; +import { PiLineChart, PiSparkline } from "@/shared/ui/pi-line-chart"; import { PiTrajectoryInspector } from "@/shared/ui/pi-trajectory-inspector"; import { PiTrajectoryLedger, TrajectoryStepBadge } from "@/shared/ui/pi-trajectory-ledger"; import { PiTrajectoryStrip } from "@/shared/ui/pi-trajectory-strip"; @@ -116,9 +117,11 @@ const cases: Array<{ { name: "Activity", ui: }, { name: "DotMatrix", ui: }, { name: "PiKpi", ui: }, + { name: "PiLineChart", ui: }, + { name: "PiSparkline", ui: }, { - name: "PiBarChart", - ui: , + name: "PiHeatmap", + ui: "cell"} columns={[{ key: "0" }]} levelOf={() => 0} rows={[{ key: "r" }]} values={[[0]]} />, }, { name: "ContextUsageMeter", ui: }, { diff --git a/apps/desktop/src/shared/ui/pi-bar-chart.test.tsx b/apps/desktop/src/shared/ui/pi-bar-chart.test.tsx deleted file mode 100644 index 53c06bd6..00000000 --- a/apps/desktop/src/shared/ui/pi-bar-chart.test.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; -import { PiBarChart } from "@/shared/ui/pi-bar-chart"; - -const series = [ - { key: "project_0", label: "alpha", color: "var(--pigui-data-blue)" }, - { key: "project_1", label: "beta", color: "var(--pigui-data-orange)" }, -]; - -const data = [ - { - key: "2026-06-25", - label: "Jun 25", - tooltipLabel: "Jun 25", - values: { project_0: 100, project_1: 0 }, - }, - { - key: "2026-06-26", - label: "Jun 26", - tooltipLabel: "Jun 26", - values: { project_0: 120, project_1: 80 }, - }, - { - key: "2026-06-27", - label: "Jun 27", - tooltipLabel: "Jun 27", - values: { project_0: 0, project_1: 0 }, - }, -]; - -describe("PiBarChart", () => { - it("renders a labeled chart image with one stacked bar per bucket", () => { - const { container } = render( - , - ); - - const chart = screen.getByRole("img", { - name: "Token usage trend by project chart", - }); - - expect(chart).toHaveAttribute("data-slot", "bar-chart"); - expect(container.querySelectorAll("[data-bucket-key]")).toHaveLength(3); - - const segments = container.querySelectorAll( - '[data-bucket-key="2026-06-26"] [data-series-key]', - ); - - expect(segments).toHaveLength(2); - expect(segments[0]).toHaveStyle({ - backgroundColor: "var(--pigui-data-blue)", - }); - }); - - it("sizes stacked segments relative to the tallest bucket", () => { - const { container } = render( - , - ); - - // Tallest bucket totals 200 tokens; alpha on Jun 25 is 100 → 50%. - const segment = container.querySelector( - '[data-bucket-key="2026-06-25"] [data-series-key="project_0"]', - ); - - expect(segment).toHaveStyle({ height: "50%" }); - }); - - it("skips intermediate axis labels per tick interval", () => { - const { container } = render( - , - ); - - const ticks = Array.from( - container.querySelectorAll("[data-tick]"), - (tick) => tick.textContent, - ); - - expect(ticks).toEqual(["Jun 25", "Jun 27"]); - }); - - it("lists only non-zero series in a bucket tooltip", () => { - const { container } = render( - `${value} tokens`} - />, - ); - - const tooltip = container.querySelector( - '[data-bucket-key="2026-06-25"] [data-slot="bar-chart-tooltip"]', - ); - - expect(tooltip).toHaveTextContent("Jun 25"); - expect(tooltip).toHaveTextContent("alpha"); - expect(tooltip).toHaveTextContent("100 tokens"); - expect(tooltip).not.toHaveTextContent("beta"); - }); - - it("renders no tooltip for zero-total buckets", () => { - const { container } = render( - , - ); - - expect( - container.querySelector( - '[data-bucket-key="2026-06-27"] [data-slot="bar-chart-tooltip"]', - ), - ).toBeNull(); - }); -}); - -describe("PiBarChart empty state", () => { - it("renders a teaching empty state when there is no data", () => { - const { container } = render( - , - ); - - const empty = container.querySelector('[data-slot="bar-chart-empty"]'); - expect(empty).toBeInTheDocument(); - expect(empty).toHaveTextContent("No data yet"); - expect(container.querySelectorAll('[data-bucket-key]')).toHaveLength(0); - }); - - it("uses the provided emptyLabel", () => { - const { container } = render( - , - ); - - expect( - container.querySelector('[data-slot="bar-chart-empty"]'), - ).toHaveTextContent("No usage in this range"); - }); - - it("does not show the empty state when buckets exist", () => { - const { container } = render( - , - ); - - expect(container.querySelector('[data-slot="bar-chart-empty"]')).toBeNull(); - }); -}); diff --git a/apps/desktop/src/shared/ui/pi-bar-chart.tsx b/apps/desktop/src/shared/ui/pi-bar-chart.tsx deleted file mode 100644 index f7b38d0c..00000000 --- a/apps/desktop/src/shared/ui/pi-bar-chart.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import type { ComponentProps } from "react"; - -export type PiBarChartSeries = { - /** Key into each datum's `values` record. */ - key: string; - /** Human-readable series name shown in tooltips. */ - label: string; - /** CSS color (token var) for this series' segments. */ - color: string; -}; - -export type PiBarChartDatum = { - key: string; - /** Axis tick label. */ - label: string; - /** Tooltip heading; falls back to `label`. */ - tooltipLabel?: string; - values: Record; -}; - -/** - * Hand-rolled stacked bar chart on Astryx tokens for the Usage trend — - * deliberately not a charting library. Layout divs are intentional and - * contained to this component. Tooltips are rendered per bucket and revealed - * on hover/focus via primitives.css. - */ -type PiBarChartOwnProps = { - "aria-label": string; - data: PiBarChartDatum[]; - series: PiBarChartSeries[]; - /** Plot area height in pixels. */ - height?: number; - /** Bar width in pixels. */ - barSize?: number; - /** Recharts-style interval: n ticks are skipped between rendered labels. */ - tickInterval?: number; - valueFormatter?: (value: number) => string; - /** Shown inside the plot when `data` is empty. */ - emptyLabel?: string; -}; - -export type PiBarChartProps = Omit, keyof PiBarChartOwnProps | "children"> & - PiBarChartOwnProps; - -export function PiBarChart({ - "aria-label": ariaLabel, - data, - series, - height = 200, - barSize = 14, - tickInterval = 0, - valueFormatter = (value: number) => String(value), - emptyLabel = "No data yet", - className = "", - ...rest -}: PiBarChartProps) { - const bucketTotals = data.map((datum) => - series.reduce((total, item) => total + (datum.values[item.key] ?? 0), 0), - ); - const maxTotal = Math.max(...bucketTotals, 0); - - return ( -
-
- {data.length === 0 ? ( - - {emptyLabel} - - ) : null} - {data.map((datum, index) => { - const total = bucketTotals[index]; - const nonZeroSeries = series.filter( - (item) => (datum.values[item.key] ?? 0) > 0, - ); - - return ( -
0 ? 0 : undefined} - > -
- {nonZeroSeries.map((item) => { - const value = datum.values[item.key] ?? 0; - const share = maxTotal === 0 ? 0 : (value / maxTotal) * 100; - - return ( - - ); - })} -
- {total > 0 ? ( -
- - {datum.tooltipLabel ?? datum.label} - - {nonZeroSeries.map((item) => ( - - - ))} -
- ) : null} -
- ); - })} -
- -
- ); -} diff --git a/apps/desktop/src/shared/ui/pi-heatmap.test.tsx b/apps/desktop/src/shared/ui/pi-heatmap.test.tsx new file mode 100644 index 00000000..45791758 --- /dev/null +++ b/apps/desktop/src/shared/ui/pi-heatmap.test.tsx @@ -0,0 +1,57 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import { PiHeatmap } from "@/shared/ui/pi-heatmap"; + +const rows = [ + { key: "mon", label: "Mon" }, + { key: "tue", label: "Tue" }, +]; +const columns = [{ key: "0", label: "00:00" }, { key: "1" }, { key: "2", label: "02:00" }]; + +describe("PiHeatmap", () => { + it("renders one cell per row × column with its level and accessible label", () => { + const { container } = render( + `${row.label} ${column.key}: ${value}`} + columns={columns} + levelOf={(value) => (value === 0 ? 0 : value > 5 ? 5 : 1)} + rows={rows} + values={[ + [0, 1, 9], + [2, 0, 0], + ]} + />, + ); + + const cells = container.querySelectorAll('[data-slot="heatmap-cell"]'); + expect(cells).toHaveLength(6); + expect(screen.getByRole("img", { name: "Mon 2: 9" })).toHaveAttribute("data-level", "5"); + expect(screen.getByRole("img", { name: "Tue 1: 0" })).toHaveAttribute("data-level", "0"); + expect(screen.getByText("Mon")).toBeInTheDocument(); + expect(screen.getByText("02:00")).toBeInTheDocument(); + }); + + it("shows the tooltip for the hovered cell only", () => { + const { container } = render( + `${row.key}-${column.key}`} + columns={columns} + levelOf={() => 1} + renderTooltip={(row, column, value) => {`${row.label} ${column.key} = ${value}`}} + rows={rows} + values={[ + [1, 2, 3], + [4, 5, 6], + ]} + />, + ); + + expect(container.querySelector('[data-slot="heatmap-tooltip"]')).toBeNull(); + fireEvent.mouseEnter(screen.getByRole("img", { name: "tue-2" })); + expect(container.querySelector('[data-slot="heatmap-tooltip"]')).toHaveTextContent("Tue 2 = 6"); + fireEvent.mouseLeave(screen.getByRole("img", { name: "tue-2" })); + expect(container.querySelector('[data-slot="heatmap-tooltip"]')).toBeNull(); + }); +}); diff --git a/apps/desktop/src/shared/ui/pi-heatmap.tsx b/apps/desktop/src/shared/ui/pi-heatmap.tsx new file mode 100644 index 00000000..045e2828 --- /dev/null +++ b/apps/desktop/src/shared/ui/pi-heatmap.tsx @@ -0,0 +1,105 @@ +import { useState, type ComponentProps, type ReactNode } from "react"; + +export type PiHeatmapAxisItem = { key: string; label?: string }; + +type PiHeatmapOwnProps = { + "aria-label": string; + rows: R[]; + columns: C[]; + /** `values[rowIndex][columnIndex]`. */ + values: number[][]; + /** Maps a value to a sequential level 0..5 (0 = empty). */ + levelOf: (value: number) => number; + /** Accessible name for each cell. */ + cellLabel: (row: R, column: C, value: number) => string; + /** Tooltip body for the hovered cell; omit for no tooltip. */ + renderTooltip?: (row: R, column: C, value: number) => ReactNode; +}; + +export type PiHeatmapProps = Omit< + ComponentProps<"div">, + keyof PiHeatmapOwnProps | "children" +> & + PiHeatmapOwnProps; + +/** + * Row × column grid with one sequential hue (levels 0..5, colour derived + * from `--pigui-data-blue` in primitives.css). Cells stretch to the + * container width; row labels sit in a leading column, column labels in a + * trailing row. + */ +export function PiHeatmap({ + "aria-label": ariaLabel, + rows, + columns, + values, + levelOf, + cellLabel, + renderTooltip, + className = "", + ...rest +}: PiHeatmapProps) { + const [hover, setHover] = useState<{ row: number; column: number; x: number; y: number } | null>(null); + const active = hover ? { row: rows[hover.row], column: columns[hover.column], value: values[hover.row]?.[hover.column] ?? 0 } : null; + + return ( +
+
+ {rows.map((row, rowIndex) => ( +
+ + {row.label ?? ""} + + {columns.map((column, columnIndex) => { + const value = values[rowIndex]?.[columnIndex] ?? 0; + return ( + { + const cell = event.currentTarget.getBoundingClientRect(); + const root = event.currentTarget.closest('[data-slot="heatmap"]')!.getBoundingClientRect(); + setHover({ row: rowIndex, column: columnIndex, x: cell.left - root.left + cell.width / 2, y: cell.top - root.top }); + }} + onMouseLeave={() => setHover(null)} + /> + ); + })} +
+ ))} +
+ + {columns.map((column) => ( + + {column.label ?? ""} + + ))} +
+
+ {active && renderTooltip ? ( +
columns.length * 0.66 ? "translate(calc(-100% - var(--spacing-2)), calc(-100% - var(--spacing-2)))" : "translate(var(--spacing-2), calc(-100% - var(--spacing-2)))", + }} + > + {renderTooltip(active.row, active.column, active.value)} +
+ ) : null} +
+ ); +} diff --git a/apps/desktop/src/shared/ui/pi-kpi.test.tsx b/apps/desktop/src/shared/ui/pi-kpi.test.tsx index 26865391..33eef9b2 100644 --- a/apps/desktop/src/shared/ui/pi-kpi.test.tsx +++ b/apps/desktop/src/shared/ui/pi-kpi.test.tsx @@ -59,3 +59,14 @@ describe("PiKpi", () => { expect(screen.getByText("+12%")).toHaveAttribute("data-slot", "kpi-delta"); }); }); + +describe("PiKpi footer", () => { + it("renders an optional footer slot below the value row", () => { + const { container, rerender } = render(spark} label="Cost" value={1} />); + + expect(container.querySelector('[data-slot="kpi-footer"]')).toHaveTextContent("spark"); + + rerender(); + expect(container.querySelector('[data-slot="kpi-footer"]')).toBeNull(); + }); +}); diff --git a/apps/desktop/src/shared/ui/pi-kpi.tsx b/apps/desktop/src/shared/ui/pi-kpi.tsx index a8e13cf0..affc60c4 100644 --- a/apps/desktop/src/shared/ui/pi-kpi.tsx +++ b/apps/desktop/src/shared/ui/pi-kpi.tsx @@ -11,6 +11,8 @@ type PiKpiOwnProps = { formatOptions?: Intl.NumberFormatOptions; /** Optional trend/delta annotation rendered after the value. */ delta?: ReactNode; + /** Optional slot below the value row, e.g. a PiSparkline. */ + footer?: ReactNode; /** stacked = label above value (dashboard tile); inline = label and value on one row. */ layout?: "stacked" | "inline"; /** Custom value node; replaces the formatted `value`. */ @@ -29,6 +31,7 @@ export function PiKpi({ value, formatOptions, delta, + footer, layout = "stacked", children, valueClassName = "", @@ -61,6 +64,11 @@ export function PiKpi({ ) : null} + {footer !== undefined && footer !== null ? ( +
+ {footer} +
+ ) : null} ); diff --git a/apps/desktop/src/shared/ui/pi-line-chart.test.tsx b/apps/desktop/src/shared/ui/pi-line-chart.test.tsx new file mode 100644 index 00000000..b3815676 --- /dev/null +++ b/apps/desktop/src/shared/ui/pi-line-chart.test.tsx @@ -0,0 +1,61 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import { PiLineChart, PiSparkline } from "@/shared/ui/pi-line-chart"; + +const points = [ + { key: "2026-06-25", label: "Jun 25", value: 4 }, + { key: "2026-06-26", label: "Jun 26", value: 0 }, + { key: "2026-06-27", label: "Jun 27", value: 2.5 }, +]; + +describe("PiLineChart", () => { + it("renders a labeled image with one path and axis labels once measured", async () => { + const { container } = render( + `$${v}`} />, + ); + + expect(screen.getByRole("img", { name: "Daily cost" })).toBeInTheDocument(); + await waitFor(() => expect(container.querySelector('[data-slot="line-chart-line"]')).toBeInTheDocument()); + expect(screen.getByText("Jun 25")).toBeInTheDocument(); + expect(screen.getByText("Jun 27")).toBeInTheDocument(); + }); + + it("shows the empty label instead of a plot when there are no points", () => { + const { container } = render( + , + ); + + expect(screen.getByText("No usage in this range")).toHaveAttribute("data-slot", "line-chart-empty"); + expect(container.querySelector('[data-slot="line-chart-line"]')).toBeNull(); + }); + + it("reveals the nearest point's tooltip on hover and hides it on leave", async () => { + const { container } = render( + {point.label} tooltip} + />, + ); + const root = container.querySelector('[data-slot="line-chart"]')!; + await waitFor(() => expect(container.querySelector('[data-slot="line-chart-line"]')).toBeInTheDocument()); + + expect(container.querySelector('[data-slot="line-chart-tooltip"]')).toBeNull(); + fireEvent.mouseMove(root, { clientX: 10_000, clientY: 10 }); + expect(container.querySelector('[data-slot="line-chart-tooltip"]')).toHaveTextContent("Jun 27 tooltip"); + fireEvent.mouseLeave(root); + expect(container.querySelector('[data-slot="line-chart-tooltip"]')).toBeNull(); + }); +}); + +describe("PiSparkline", () => { + it("renders a decorative polyline for two or more values and nothing for fewer", () => { + const { container, rerender } = render(); + + expect(container.querySelector("polyline")).toBeInTheDocument(); + expect(container.querySelector("svg")).toHaveAttribute("aria-hidden", "true"); + + rerender(); + expect(container.querySelector("polyline")).toBeNull(); + }); +}); diff --git a/apps/desktop/src/shared/ui/pi-line-chart.tsx b/apps/desktop/src/shared/ui/pi-line-chart.tsx new file mode 100644 index 00000000..bd50e392 --- /dev/null +++ b/apps/desktop/src/shared/ui/pi-line-chart.tsx @@ -0,0 +1,196 @@ +import { useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from "react"; + +export type PiLinePoint = { + key: string; + /** Axis tick label. */ + label: string; + value: number; +}; + +type PiLineChartOwnProps = { + "aria-label": string; + points: PiLinePoint[]; + /** Plot height in pixels; the width follows the container. */ + height?: number; + /** Series colour; only `--pigui-data-*` tokens. */ + color?: string; + valueFormatter?: (value: number) => string; + /** Tooltip body for the hovered point; omit for no tooltip. */ + renderTooltip?: (point: PiLinePoint) => ReactNode; + /** Shown instead of the plot when `points` is empty. */ + emptyLabel?: string; +}; + +export type PiLineChartProps = Omit, keyof PiLineChartOwnProps | "children"> & + PiLineChartOwnProps; + +const pad = { top: 12, right: 12, bottom: 24, left: 44 }; + +function niceCeil(value: number) { + if (value <= 0) return 1; + const power = 10 ** Math.floor(Math.log10(value)); + const unit = value / power; + return (unit <= 1 ? 1 : unit <= 2 ? 2 : unit <= 5 ? 5 : 10) * power; +} + +/** Container width via ResizeObserver so the SVG can use real pixel geometry. */ +function useWidth() { + const ref = useRef(null); + const [width, setWidth] = useState(0); + useLayoutEffect(() => { + const element = ref.current; + if (!element) return; + setWidth(element.getBoundingClientRect().width); + const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width)); + observer.observe(element); + return () => observer.disconnect(); + }, []); + return [ref, width] as const; +} + +/** + * Single-series line with crosshair hover, hand-rolled on Astryx tokens. + * Layout divs are intentional and contained to this component. + */ +export function PiLineChart({ + "aria-label": ariaLabel, + points, + height = 220, + color = "var(--pigui-data-blue)", + valueFormatter = (value) => String(value), + renderTooltip, + emptyLabel = "No data yet", + className = "", + ...rest +}: PiLineChartProps) { + const [ref, width] = useWidth(); + const [hover, setHover] = useState(null); + const count = points.length; + const plotWidth = Math.max(0, width - pad.left - pad.right); + const plotHeight = height - pad.top - pad.bottom; + const max = niceCeil(Math.max(...points.map((p) => p.value), 0)); + const x = (index: number) => pad.left + (count <= 1 ? plotWidth / 2 : (index / (count - 1)) * plotWidth); + const y = (value: number) => pad.top + plotHeight - (value / max) * plotHeight; + const line = points.map((p, i) => `${i === 0 ? "M" : "L"}${x(i).toFixed(1)},${y(p.value).toFixed(1)}`).join(" "); + const area = + count > 1 + ? `${line} L${x(count - 1).toFixed(1)},${(pad.top + plotHeight).toFixed(1)} L${x(0).toFixed(1)},${(pad.top + plotHeight).toFixed(1)} Z` + : ""; + const labelEvery = Math.max(1, Math.ceil(count / 6)); + const active = hover === null ? null : points[hover]; + + return ( +
setHover(null)} + onMouseMove={(event) => { + if (count === 0 || plotWidth <= 0) return; + const rect = event.currentTarget.getBoundingClientRect(); + const ratio = (event.clientX - rect.left - pad.left) / plotWidth; + setHover(Math.min(count - 1, Math.max(0, Math.round(ratio * (count - 1))))); + }} + {...rest} + > + {count === 0 ? ( + + {emptyLabel} + + ) : null} + {count > 0 && width > 0 ? ( + + {[0, max / 2, max].map((tick) => ( + + + + {valueFormatter(tick)} + + + ))} + {points.map((point, index) => + index % labelEvery === 0 || index === count - 1 ? ( + + {point.label} + + ) : null, + )} + {count > 1 ? : null} + + {hover !== null && active ? ( + + + + + ) : null} + + ) : null} + {active && renderTooltip ? ( +
width * 0.65 ? "translateX(calc(-100% - var(--spacing-3)))" : "translateX(var(--spacing-3))", + }} + > + {renderTooltip(active)} +
+ ) : null} +
+ ); +} + +export type PiSparklineProps = Omit, "children"> & { + values: number[]; + color?: string; + height?: number; +}; + +/** Decorative trend line for KPI tiles; no axes, no tooltip, aria-hidden. */ +export function PiSparkline({ + values, + color = "var(--pigui-data-blue)", + height = 36, + className = "", + ...rest +}: PiSparklineProps) { + const [ref, width] = useWidth(); + const max = Math.max(...values, 0); + const count = values.length; + // Without a measured width (first paint, jsdom) draw in a 100-unit box + // and let preserveAspectRatio stretch it; the line is decorative. + const drawWidth = width || 100; + const points = values.map((value, index) => { + const px = count === 1 ? drawWidth / 2 : (index / (count - 1)) * drawWidth; + const py = max === 0 ? height - 1 : height - 1 - (value / max) * (height - 2); + return `${px.toFixed(1)},${py.toFixed(1)}`; + }); + + return ( +
+ {count > 1 ? ( + + ) : null} +
+ ); +} diff --git a/apps/desktop/src/shared/ui/primitives.css b/apps/desktop/src/shared/ui/primitives.css index b8602502..3e3fb4af 100644 --- a/apps/desktop/src/shared/ui/primitives.css +++ b/apps/desktop/src/shared/ui/primitives.css @@ -30,6 +30,13 @@ gap: var(--spacing-2); } +/* Stacked tiles let a long delta wrap under the value instead of squeezing + the number into an ellipsis; inline tiles keep the single row. */ +.pi-kpi:not(.pi-kpi--inline) .pi-kpi__value-row { + flex-wrap: wrap; + row-gap: var(--spacing-0-5); +} + .pi-kpi--inline .pi-kpi__value-row { justify-content: flex-end; } @@ -56,125 +63,150 @@ } -/* —— PiBarChart —— */ +/* —— PiKpi footer —— */ -.pi-bar-chart { +.pi-kpi__footer { + margin: 0; min-width: 0; } -.pi-bar-chart__plot { +/* —— Chart tooltip (PiLineChart / PiHeatmap) —— */ + +.pi-chart-tooltip { + position: absolute; + z-index: 30; display: flex; - align-items: flex-end; + min-width: max-content; + flex-direction: column; + gap: var(--spacing-1); + padding: var(--spacing-2) var(--spacing-3); + border: var(--border-width) solid var(--color-border); + border-radius: var(--radius-element); + background: var(--color-background-popover); + box-shadow: var(--shadow-med); + pointer-events: none; } -.pi-bar-chart__bucket { +/* —— PiLineChart —— */ + +.pi-line-chart { position: relative; - display: flex; - height: 100%; min-width: 0; - flex: 1; - align-items: flex-end; - justify-content: center; - outline: none; + width: 100%; } -.pi-bar-chart__stack { - display: flex; - height: 100%; - flex-direction: column-reverse; - justify-content: flex-start; +.pi-line-chart__svg { + display: block; + overflow: visible; } -.pi-bar-chart__segment { - flex-shrink: 0; +.pi-line-chart__grid { + stroke: var(--color-border); } -.pi-bar-chart__stack .pi-bar-chart__segment:last-child { - border-start-start-radius: var(--radius-inner); - border-start-end-radius: var(--radius-inner); +.pi-line-chart__tick { + font-size: var(--font-size-sm); + fill: var(--color-text-secondary); } -.pi-bar-chart__bucket:is(:hover, :focus-visible) .pi-bar-chart__segment { - filter: brightness(0.92); +.pi-line-chart__area { + fill-opacity: 0.08; } -.pi-bar-chart__tooltip { - position: absolute; - bottom: 100%; - left: 50%; - z-index: 30; - display: none; - min-width: max-content; - flex-direction: column; - gap: var(--spacing-1); - padding: var(--spacing-2) var(--spacing-3); - border: var(--border-width) solid var(--color-border); - border-radius: var(--radius-element); - background: var(--color-background-popover); - box-shadow: var(--shadow-med); - pointer-events: none; - transform: translateX(-50%); +.pi-line-chart__line { + stroke-width: 2; + stroke-linejoin: round; } -.pi-bar-chart__bucket:is(:hover, :focus-visible) .pi-bar-chart__tooltip { - display: flex; +.pi-line-chart__crosshair { + stroke: var(--color-text-secondary); + stroke-dasharray: 2 3; } -.pi-bar-chart__tooltip-label { - font-size: var(--font-size-sm); - font-weight: var(--font-weight-medium); - color: var(--color-text-primary); +.pi-line-chart__marker { + stroke: var(--surface); + stroke-width: 2; } -.pi-bar-chart__tooltip-row { +/* Empty state keeps the plot's dimensions so data arriving later causes no + layout shift; copy explains instead of leaving a blank rectangle. */ +.pi-line-chart__empty { + position: absolute; + inset: 0; display: flex; align-items: center; - gap: var(--spacing-2); + justify-content: center; font-size: var(--font-size-sm); color: var(--color-text-secondary); + user-select: none; } -.pi-bar-chart__tooltip-swatch { - width: var(--spacing-2); - height: var(--spacing-2); - flex-shrink: 0; - border-radius: var(--radius-full); +.pi-sparkline { + width: 100%; + min-width: 0; } -.pi-bar-chart__tooltip-value { - font-variant-numeric: tabular-nums; - color: var(--color-text-primary); +.pi-sparkline svg { + display: block; + overflow: visible; } -.pi-bar-chart__axis { - display: flex; - margin-top: var(--spacing-2); +.pi-sparkline__line { + stroke-width: 2; + stroke-linejoin: round; + vector-effect: non-scaling-stroke; } -.pi-bar-chart__tick-slot { - display: flex; +/* —— PiHeatmap —— + One hue, light → dark: each level mixes --pigui-data-blue into the surface + so the ramp holds in both themes without new tokens. */ + +.pi-heatmap { + position: relative; min-width: 0; - flex: 1; - justify-content: center; } -.pi-bar-chart__tick { - overflow: hidden; +.pi-heatmap__grid { + display: flex; + flex-direction: column; + gap: var(--spacing-0-5); +} + +.pi-heatmap__row { + display: grid; + grid-template-columns: var(--spacing-10) repeat(var(--pi-heatmap-columns), minmax(0, 1fr)); + gap: var(--spacing-0-5); + align-items: center; +} + +.pi-heatmap__row-label, +.pi-heatmap__column-label { font-size: var(--font-size-sm); + line-height: 1; color: var(--color-text-secondary); - text-overflow: ellipsis; white-space: nowrap; } -/* Empty state keeps the plot's dimensions so data arriving later causes no - layout shift; copy explains instead of leaving a blank rectangle. */ -.pi-bar-chart__empty { - align-self: center; - margin-inline: auto; - font-size: var(--font-size-sm); - color: var(--color-text-disabled); - user-select: none; +.pi-heatmap__cell { + display: block; + height: var(--spacing-4); + border-radius: var(--radius-inner); + /* Overlay alpha rather than the muted surface: the latter equals the card + surface in the dark theme and empty cells would disappear. */ + background: var(--surface-hover); } + +.pi-heatmap__cell[data-level="1"] { background: color-mix(in oklch, var(--pigui-data-blue) 22%, var(--surface)); } +.pi-heatmap__cell[data-level="2"] { background: color-mix(in oklch, var(--pigui-data-blue) 40%, var(--surface)); } +.pi-heatmap__cell[data-level="3"] { background: color-mix(in oklch, var(--pigui-data-blue) 58%, var(--surface)); } +.pi-heatmap__cell[data-level="4"] { background: color-mix(in oklch, var(--pigui-data-blue) 78%, var(--surface)); } +.pi-heatmap__cell[data-level="5"] { background: var(--pigui-data-blue); } + +.pi-heatmap__cell:hover { + outline: var(--border-width) solid var(--color-text-secondary); + outline-offset: calc(-1 * var(--border-width)); +} + /* SVG motion is opt-in at the icon; its existing button owns the hit area. */ .pigui-animated-icon { overflow: visible; diff --git a/docs/design/astryx.md b/docs/design/astryx.md index 258dbcbf..c819ef41 100644 --- a/docs/design/astryx.md +++ b/docs/design/astryx.md @@ -90,7 +90,7 @@ Astryx 的 props 以 `bunx astryx component ` 输出为准,本文只记 只有这几种形态,别引入 `Skeleton` / `Spinner` / `ProgressBar`(仓库 0 调用): -- **内容区还没数据**:``,窄处加 `isCompact`(`session-list.tsx:398`、`usage.tsx:677`)。 +- **内容区还没数据**:``,窄处加 `isCompact`(`session-list.tsx:398`、`usage.tsx` 的排行空态)。 - **一个区块内部在加载**:一行 `Loading…`(`settings.tsx:335`)。按钮触发的异步用按钮自己的 `isDisabled={mutation.isPending}`。 - **区块内错误**:``(`settings.tsx:340`)。 - **一次 run 失败**:`ChatRunFailure`(见 chat.md),它是仓库里唯一的 `Banner status="error"`。 diff --git a/docs/design/tokens.md b/docs/design/tokens.md index 47b2b25d..a8f9ac4b 100644 --- a/docs/design/tokens.md +++ b/docs/design/tokens.md @@ -7,11 +7,11 @@ 组件代码只能引用**上两层**:语义桥(`var(--foreground)` 或类名 `text-foreground`)和 Astryx 一级 token(`var(--color-text-secondary)`)。原因:桥和一级 token 都会随主题解析,字面量不会;Tailwind 自带调色板(`text-gray-500`、`bg-zinc-900`)不经过 Astryx,明暗模式下必错。 ```tsx -// 正确 — pages/usage.tsx:47 -const usageKpiValueClass = "tabular-nums text-[var(--pigui-data-blue)]"; +// 正确 — pages/usage.tsx 顶部的序列色表 +const seriesColors = ["var(--pigui-data-blue)", "var(--pigui-data-orange)", /* … */]; -// 错误 — 调色板类不随主题走 -const usageKpiValueClass = "tabular-nums text-blue-600"; +// 错误 — 字面量与调色板类都不随主题走 +const seriesColors = ["#1677e8", "text-blue-600"]; ``` ## 语义桥(`styles.css:59-76`,就这 15 个) diff --git a/docs/design/workspace.md b/docs/design/workspace.md index 79f8c68b..8c8be4e9 100644 --- a/docs/design/workspace.md +++ b/docs/design/workspace.md @@ -94,8 +94,9 @@ Live Chat 中的本地文件链接由会话页面处理,流式与已完成回 ## 数据与指标 -- `PiKpi`:`layout: "stacked" | "inline"`,默认 `stacked`;仪表盘卡片用 stacked,紧凑行 / 侧栏用 inline。值传数字走 `formatOptions`(内部 `Intl.NumberFormat`);自定义展示才传 `children`,它会整个替换格式化结果。 -- `PiBarChart`:`aria-label` 必填;`series` 的 `color` 只取 `--pigui-data-*`,页面里的顺序表见 `usage.tsx:48`。刻意不是图表库;折线 / 面积 / 热力等 #87 等需求驱动,不要临时引入 recharts。 +- `PiKpi`:`layout: "stacked" | "inline"`,默认 `stacked`;仪表盘卡片用 stacked,紧凑行 / 侧栏用 inline。值传数字走 `formatOptions`(内部 `Intl.NumberFormat`);自定义展示才传 `children`,它会整个替换格式化结果。`footer` 槽放值行下方的装饰内容,目前只放 `PiSparkline`。 +- `PiLineChart`:`aria-label` 必填;单序列,`color` 只取 `--pigui-data-*`;`renderTooltip` 给了才有悬停 tooltip;空数据显示 `emptyLabel` 并保持高度。`PiSparkline` 是它的装饰版:无坐标轴、无 tooltip、`aria-hidden`。 +- `PiHeatmap`:行 × 列网格,只有一种色相(`--pigui-data-blue` 经 `color-mix` 推六档,档位 0..5 由 `levelOf` 决定,页面用 `rankLevels` 按排名分档以免离群值压平其余);`cellLabel` 必填,是每格的可访问名。刻意不是图表库;面积 / 日历热力等 #87 等需求驱动,不要临时引入 recharts。分类色在页面里按排名固定分配、不循环,第六个实体折入 `--pigui-data-slate` 的 Other(`usage.tsx` 顶部的 `seriesColors`)。 - `ContextUsageMeter`:`usage` 为 null 只画空轨道;阈值 70% / 90% 在组件内,页面不算颜色。footer 行右侧一枚 14px 圆环,是它唯一的家。 ## 视觉原语 diff --git a/docs/self-built-ui.md b/docs/self-built-ui.md index 33a668b1..1a6e23af 100644 --- a/docs/self-built-ui.md +++ b/docs/self-built-ui.md @@ -28,7 +28,7 @@ | chat-prompt-suggestion | `shared/ui/chat/` | **在用**(agent-workspace 空 draft 建议卡;2026-08-09 核实,此前误判候删) | | chat-queued-message | `shared/ui/chat/` | 等待区 item(queue-first composer,2026-08-12 原型探索胜出);Astryx 无队列概念;决策记录 `.scratch/composer-redesign/PRD.md` | | use-presence-list | `shared/ui/chat/use-presence-list.ts` | 列表行进出场的 presence hook(2026-09-06 动效打磨):首帧不播进场(已排队的行在页面加载时静止),之后插入标 `enter`、移除标 `exit` 并保留到 `transitionend`(带超时兜底),减动效下立即增删;重新加回正在退场的行取消退场而不重播进场。`ChatQueuedMessage` 与 `SessionSurfaceTabs` 共用;不引入 Motion 库(决策:项目无手势驱动交互,纯 CSS transition 已可中断) | -| pi-kpi / pi-bar-chart / dot-matrix | `shared/ui/` | KPI/图表原语,Astryx 无 chart 系 | +| pi-kpi / pi-line-chart / pi-heatmap / dot-matrix | `shared/ui/` | KPI/图表原语,Astryx 无 chart 系。2026-09-17 Usage 重构(决策见 `.scratch/usage-redesign/DECISION.md`):`pi-bar-chart` 随旧 token 趋势图一起删除;新增 `PiLineChart`(单序列折线 + 十字线 tooltip)与 `PiSparkline`(KPI 卡装饰线,进 `PiKpi` 新增的 `footer` 槽)、`PiHeatmap`(行×列网格,单色相六档,档位由调用方给,页面用 `rankLevels` 按排名分档) | | pi-trajectory-ledger | `shared/ui/` | Trajectory Cockpit 台账(2026-08-18 原型重构):Run 顶层分组 + Turn 边界圆点 + 徽章行(`名称 {请求} → 结果`),行永不内联展开;读模型在 `entities/session/trajectory-model.ts`(Run>Turn>Step,见 CONTEXT.md);USER/ASSISTANT/TOOL/CONTEXT 四徽章一律取自 `--pigui-data-*` 数据调色板,CONTEXT 用 [#106](https://github.com/BubblePtr/pace/issues/106) 新增的 `--pigui-data-green`(不再借语义色 `--success`)。选中态 / 过滤 / step·turn ref 放在根上经 context 下发,`.Run` 只传 `run`(外加可选 `isDimmed`) | | pi-trajectory-strip | `shared/ui/` | Trajectory Cockpit 概览带:Input/Model/Tools 三泳道、段粒度、游标竖线、单击选中该泳道块 / 拖拽框选连续段;选区外列与台账行置灰(不过滤)、Steps/Time 双宽度模式;密集轨迹的最小列宽与间距随容器压缩,完整保留尾部且不溢出;Time 模式模型段用 Pi 记录的模型调用起止真实时长([#108](https://github.com/BubblePtr/pace/issues/108)),input 段用「用户提交 → 该 run 首次模型调用开始」的等待([#126](https://github.com/BubblePtr/pace/issues/126) 修掉了原先取尾随间隙、与后续模型/工具段重复计算同一段墙钟的语义),各段区间互不重叠;推不出真实区间的(旧 session 缺起止、缺时间戳、时钟倒挂)退回估算并以斜纹+弱化标出,估算不伪装成实测 | | pi-trajectory-inspector | `shared/ui/` | Trajectory Cockpit 检视器:Summary/Payload/Result/Schema/Timing;大 payload 只在此挂载;Schema 待 Gateway 解析能力 [#107](https://github.com/BubblePtr/pace/issues/107)(现为 unavailable 诚实态)。tintinweb `Agent` 步骤可带 “Open child session”(子 JSONL 未索引时禁用)。记录广告 `send`/`stop` 时同一区域显示 “Send to child” / “Stop child”(已结束则隐藏 Stop) | @@ -47,7 +47,7 @@ | --- | --- | --- | | Plugin surfaces 面板宿主(渲染侧) | [#85](https://github.com/BubblePtr/pace/issues/85) | 被 ADR-0018 协议阻塞 | | Embedded browser annotation 覆盖层/工具条 | [#86](https://github.com/BubblePtr/pace/issues/86) | S1 宿主与 surface、S2 标注层与 design mode 工具条、S3 载荷回传 composer([#151](https://github.com/BubblePtr/pace/issues/151))均已落地(见上表 browser-surface);覆盖层在页内 Shadow DOM,不是 `shared/ui/` 组件。S4 ADR-0029 已落地([#152](https://github.com/BubblePtr/pace/issues/152)) | -| 图表原语扩展(折线/面积/热力) | [#87](https://github.com/BubblePtr/pace/issues/87) | 等 usage 需求驱动 | +| 图表原语扩展(面积/日历热力/会话表) | [#87](https://github.com/BubblePtr/pace/issues/87) | 折线与星期×小时热力已随 Usage 重构落地;其余等需求驱动 | | Dynamic workflow visualization(图/DAG/时间线) | [#84](https://github.com/BubblePtr/pace/issues/84) | **future,远期**(2026-08-09 降级) | | 思维链样式可选项(Compact/Timeline) | [#81](https://github.com/BubblePtr/pace/issues/81) | **future,后置**(被 Appearance 设置页阻塞) | | Composer 队列拖拽重排 | [#97](https://github.com/BubblePtr/pace/issues/97) | 被 runtime gateway reorder 能力阻塞 |