@laoyuehanni/dsh-token-usage 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -0
  3. package/README.zh.md +182 -0
  4. package/cordis.patch.yml +7 -0
  5. package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
  6. package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
  7. package/lib/client/CostDeltaFlyLabel.js +24 -0
  8. package/lib/client/CostDeltaFlyLabel.js.map +1 -0
  9. package/lib/client/HitRateText.d.ts +21 -0
  10. package/lib/client/HitRateText.d.ts.map +1 -0
  11. package/lib/client/HitRateText.js +16 -0
  12. package/lib/client/HitRateText.js.map +1 -0
  13. package/lib/client/QuotaButton.d.ts +70 -0
  14. package/lib/client/QuotaButton.d.ts.map +1 -0
  15. package/lib/client/QuotaButton.js +346 -0
  16. package/lib/client/QuotaButton.js.map +1 -0
  17. package/lib/client/SessionStatsChip.d.ts +47 -0
  18. package/lib/client/SessionStatsChip.d.ts.map +1 -0
  19. package/lib/client/SessionStatsChip.js +141 -0
  20. package/lib/client/SessionStatsChip.js.map +1 -0
  21. package/lib/client/StatCard.d.ts +26 -0
  22. package/lib/client/StatCard.d.ts.map +1 -0
  23. package/lib/client/StatCard.js +10 -0
  24. package/lib/client/StatCard.js.map +1 -0
  25. package/lib/client/TokenUsageCard.d.ts +41 -0
  26. package/lib/client/TokenUsageCard.d.ts.map +1 -0
  27. package/lib/client/TokenUsageCard.js +164 -0
  28. package/lib/client/TokenUsageCard.js.map +1 -0
  29. package/lib/client/TokenUsageSection.d.ts +32 -0
  30. package/lib/client/TokenUsageSection.d.ts.map +1 -0
  31. package/lib/client/TokenUsageSection.js +266 -0
  32. package/lib/client/TokenUsageSection.js.map +1 -0
  33. package/lib/client/TrendChart.d.ts +53 -0
  34. package/lib/client/TrendChart.d.ts.map +1 -0
  35. package/lib/client/TrendChart.js +141 -0
  36. package/lib/client/TrendChart.js.map +1 -0
  37. package/lib/client/UsageView.d.ts +42 -0
  38. package/lib/client/UsageView.d.ts.map +1 -0
  39. package/lib/client/UsageView.js +158 -0
  40. package/lib/client/UsageView.js.map +1 -0
  41. package/lib/client/async-resource.d.ts +54 -0
  42. package/lib/client/async-resource.d.ts.map +1 -0
  43. package/lib/client/async-resource.js +90 -0
  44. package/lib/client/async-resource.js.map +1 -0
  45. package/lib/client/card-form.d.ts +171 -0
  46. package/lib/client/card-form.d.ts.map +1 -0
  47. package/lib/client/card-form.js +300 -0
  48. package/lib/client/card-form.js.map +1 -0
  49. package/lib/client/cost-inflate-motion.d.ts +17 -0
  50. package/lib/client/cost-inflate-motion.d.ts.map +1 -0
  51. package/lib/client/cost-inflate-motion.js +61 -0
  52. package/lib/client/cost-inflate-motion.js.map +1 -0
  53. package/lib/client/cost-inflate.d.ts +28 -0
  54. package/lib/client/cost-inflate.d.ts.map +1 -0
  55. package/lib/client/cost-inflate.js +49 -0
  56. package/lib/client/cost-inflate.js.map +1 -0
  57. package/lib/client/day.d.ts +49 -0
  58. package/lib/client/day.d.ts.map +1 -0
  59. package/lib/client/day.js +84 -0
  60. package/lib/client/day.js.map +1 -0
  61. package/lib/client/format.d.ts +120 -0
  62. package/lib/client/format.d.ts.map +1 -0
  63. package/lib/client/format.js +163 -0
  64. package/lib/client/format.js.map +1 -0
  65. package/lib/client/index.d.ts +26 -0
  66. package/lib/client/index.d.ts.map +1 -0
  67. package/lib/client/index.js +131 -0
  68. package/lib/client/index.js.map +1 -0
  69. package/lib/client/locales.d.ts +131 -0
  70. package/lib/client/locales.d.ts.map +1 -0
  71. package/lib/client/locales.js +230 -0
  72. package/lib/client/locales.js.map +1 -0
  73. package/lib/client/quota-format.d.ts +69 -0
  74. package/lib/client/quota-format.d.ts.map +1 -0
  75. package/lib/client/quota-format.js +147 -0
  76. package/lib/client/quota-format.js.map +1 -0
  77. package/lib/client/session-stats.d.ts +105 -0
  78. package/lib/client/session-stats.d.ts.map +1 -0
  79. package/lib/client/session-stats.js +142 -0
  80. package/lib/client/session-stats.js.map +1 -0
  81. package/lib/client/trend-chart/axis.d.ts +21 -0
  82. package/lib/client/trend-chart/axis.d.ts.map +1 -0
  83. package/lib/client/trend-chart/axis.js +33 -0
  84. package/lib/client/trend-chart/axis.js.map +1 -0
  85. package/lib/client/trend-chart/bucket.d.ts +24 -0
  86. package/lib/client/trend-chart/bucket.d.ts.map +1 -0
  87. package/lib/client/trend-chart/bucket.js +28 -0
  88. package/lib/client/trend-chart/bucket.js.map +1 -0
  89. package/lib/client/trend-chart/index.d.ts +12 -0
  90. package/lib/client/trend-chart/index.d.ts.map +1 -0
  91. package/lib/client/trend-chart/index.js +9 -0
  92. package/lib/client/trend-chart/index.js.map +1 -0
  93. package/lib/client/trend-chart/points.d.ts +46 -0
  94. package/lib/client/trend-chart/points.d.ts.map +1 -0
  95. package/lib/client/trend-chart/points.js +82 -0
  96. package/lib/client/trend-chart/points.js.map +1 -0
  97. package/lib/client/trend-chart/scale.d.ts +47 -0
  98. package/lib/client/trend-chart/scale.d.ts.map +1 -0
  99. package/lib/client/trend-chart/scale.js +75 -0
  100. package/lib/client/trend-chart/scale.js.map +1 -0
  101. package/lib/client/use-color-scheme.d.ts +18 -0
  102. package/lib/client/use-color-scheme.d.ts.map +1 -0
  103. package/lib/client/use-color-scheme.js +37 -0
  104. package/lib/client/use-color-scheme.js.map +1 -0
  105. package/lib/client/use-cost-inflate.d.ts +33 -0
  106. package/lib/client/use-cost-inflate.d.ts.map +1 -0
  107. package/lib/client/use-cost-inflate.js +108 -0
  108. package/lib/client/use-cost-inflate.js.map +1 -0
  109. package/lib/client.js +3892 -0
  110. package/lib/client.js.map +1 -0
  111. package/lib/index.d.ts +132 -0
  112. package/lib/index.d.ts.map +1 -0
  113. package/lib/index.js +599 -0
  114. package/lib/index.js.map +1 -0
  115. package/lib/migrate.d.ts +60 -0
  116. package/lib/migrate.d.ts.map +1 -0
  117. package/lib/migrate.js +126 -0
  118. package/lib/migrate.js.map +1 -0
  119. package/lib/pricing.d.ts +212 -0
  120. package/lib/pricing.d.ts.map +1 -0
  121. package/lib/pricing.js +492 -0
  122. package/lib/pricing.js.map +1 -0
  123. package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
  124. package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
  125. package/lib/quota/adapters/deepseek-balance.js +76 -0
  126. package/lib/quota/adapters/deepseek-balance.js.map +1 -0
  127. package/lib/quota/adapters/kimi.d.ts +26 -0
  128. package/lib/quota/adapters/kimi.d.ts.map +1 -0
  129. package/lib/quota/adapters/kimi.js +91 -0
  130. package/lib/quota/adapters/kimi.js.map +1 -0
  131. package/lib/quota/adapters/minimax.d.ts +24 -0
  132. package/lib/quota/adapters/minimax.d.ts.map +1 -0
  133. package/lib/quota/adapters/minimax.js +136 -0
  134. package/lib/quota/adapters/minimax.js.map +1 -0
  135. package/lib/quota/adapters/opencode-go.d.ts +25 -0
  136. package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
  137. package/lib/quota/adapters/opencode-go.js +105 -0
  138. package/lib/quota/adapters/opencode-go.js.map +1 -0
  139. package/lib/quota/adapters/openrouter.d.ts +15 -0
  140. package/lib/quota/adapters/openrouter.d.ts.map +1 -0
  141. package/lib/quota/adapters/openrouter.js +54 -0
  142. package/lib/quota/adapters/openrouter.js.map +1 -0
  143. package/lib/quota/adapters/zhipu.d.ts +38 -0
  144. package/lib/quota/adapters/zhipu.d.ts.map +1 -0
  145. package/lib/quota/adapters/zhipu.js +246 -0
  146. package/lib/quota/adapters/zhipu.js.map +1 -0
  147. package/lib/quota/credentials.d.ts +79 -0
  148. package/lib/quota/credentials.d.ts.map +1 -0
  149. package/lib/quota/credentials.js +130 -0
  150. package/lib/quota/credentials.js.map +1 -0
  151. package/lib/quota/http.d.ts +49 -0
  152. package/lib/quota/http.d.ts.map +1 -0
  153. package/lib/quota/http.js +114 -0
  154. package/lib/quota/http.js.map +1 -0
  155. package/lib/quota/provider-tracking.d.ts +45 -0
  156. package/lib/quota/provider-tracking.d.ts.map +1 -0
  157. package/lib/quota/provider-tracking.js +52 -0
  158. package/lib/quota/provider-tracking.js.map +1 -0
  159. package/lib/quota/quota-route.d.ts +22 -0
  160. package/lib/quota/quota-route.d.ts.map +1 -0
  161. package/lib/quota/quota-route.js +57 -0
  162. package/lib/quota/quota-route.js.map +1 -0
  163. package/lib/quota/quota-service.d.ts +54 -0
  164. package/lib/quota/quota-service.d.ts.map +1 -0
  165. package/lib/quota/quota-service.js +171 -0
  166. package/lib/quota/quota-service.js.map +1 -0
  167. package/lib/quota/registry.d.ts +24 -0
  168. package/lib/quota/registry.d.ts.map +1 -0
  169. package/lib/quota/registry.js +38 -0
  170. package/lib/quota/registry.js.map +1 -0
  171. package/lib/quota/types.d.ts +79 -0
  172. package/lib/quota/types.d.ts.map +1 -0
  173. package/lib/quota/types.js +24 -0
  174. package/lib/quota/types.js.map +1 -0
  175. package/lib/record-cache.d.ts +38 -0
  176. package/lib/record-cache.d.ts.map +1 -0
  177. package/lib/record-cache.js +143 -0
  178. package/lib/record-cache.js.map +1 -0
  179. package/lib/rollup.d.ts +52 -0
  180. package/lib/rollup.d.ts.map +1 -0
  181. package/lib/rollup.js +117 -0
  182. package/lib/rollup.js.map +1 -0
  183. package/lib/stats-route.d.ts +88 -0
  184. package/lib/stats-route.d.ts.map +1 -0
  185. package/lib/stats-route.js +313 -0
  186. package/lib/stats-route.js.map +1 -0
  187. package/lib/stats.d.ts +158 -0
  188. package/lib/stats.d.ts.map +1 -0
  189. package/lib/stats.js +426 -0
  190. package/lib/stats.js.map +1 -0
  191. package/lib/sync-state.d.ts +27 -0
  192. package/lib/sync-state.d.ts.map +1 -0
  193. package/lib/sync-state.js +56 -0
  194. package/lib/sync-state.js.map +1 -0
  195. package/lib/sync.d.ts +74 -0
  196. package/lib/sync.d.ts.map +1 -0
  197. package/lib/sync.js +64 -0
  198. package/lib/sync.js.map +1 -0
  199. package/lib/trend-bucket.d.ts +48 -0
  200. package/lib/trend-bucket.d.ts.map +1 -0
  201. package/lib/trend-bucket.js +87 -0
  202. package/lib/trend-bucket.js.map +1 -0
  203. package/lib/usage-log.d.ts +64 -0
  204. package/lib/usage-log.d.ts.map +1 -0
  205. package/lib/usage-log.js +144 -0
  206. package/lib/usage-log.js.map +1 -0
  207. package/lib/usage-record.d.ts +59 -0
  208. package/lib/usage-record.d.ts.map +1 -0
  209. package/lib/usage-record.js +115 -0
  210. package/lib/usage-record.js.map +1 -0
  211. package/lib/wire.d.ts +452 -0
  212. package/lib/wire.d.ts.map +1 -0
  213. package/lib/wire.js +144 -0
  214. package/lib/wire.js.map +1 -0
  215. package/package.json +100 -0
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Daily / hourly / request-bucketed token trend chart (browser half):
3
+ * a dependency-free SVG line chart over the already-filtered summary.
4
+ * The renderer is pure presentation; the bucketing, scaling, and
5
+ * point-shape decisions live in `./trend-chart/*` so each piece can be
6
+ * tested in isolation.
7
+ *
8
+ * Two granularities share one renderer — per-day rows (x axis spans
9
+ * every calendar day of the active range, days without records plot as
10
+ * zero) and per-hour rows (a single-day window plots every whole hour of
11
+ * that day, 00:00–23:00, future hours of today reading zero). The
12
+ * third mode — request buckets — folds the request series into uniformly
13
+ * sized time buckets spanning the session's actual first-to-last window
14
+ * and scales each bucket at its real temporal proportion of the span.
15
+ *
16
+ * Hovering (or keyboard-focusing) a point highlights it and floats a
17
+ * label with that point's date/time and total tokens.
18
+ *
19
+ * @module token-usage/client/TrendChart
20
+ */
21
+ import type { ReactNode } from 'react';
22
+ import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
23
+ import type { RequestPoint, UsageDayRow, UsageHourRow } from '../wire.ts';
24
+ /** Re-export the chart's pure helpers for the test suite. */
25
+ export { MAX_BUCKETS, bucketSeries, bucketWidth, buildChartPoints, dotRadius, labelIndices, niceStep, scaleSeries, scaleToSpan, tickValues, } from './trend-chart/index.ts';
26
+ export type { TrendBucket } from './trend-chart/bucket.ts';
27
+ export type { ChartSeries, ScaleResult } from './trend-chart/index.ts';
28
+ /**
29
+ * Render the daily / hourly / request-bucketed token line chart. Pure
30
+ * presentation: every data-driven decision (bucketing, axis scaling,
31
+ * point ordering) lives in `./trend-chart/*`; this component picks the
32
+ * right `chartAria` string for screen readers and forwards hover /
33
+ * focus state to the dot + label.
34
+ *
35
+ * Empty ranges (no data on any branch) render a placeholder instead of an
36
+ * axis so the layout does not collapse to an empty SVG.
37
+ *
38
+ * @param props - the filtered per-day rows plus the optional per-hour rows
39
+ * (when present the chart plots hours instead of days), the optional
40
+ * per-request series (session-scoped reads), the active range bounds
41
+ * (absent when unfiltered; the chart then spans first to last row), and
42
+ * the `t` seat for the empty hint and chart aria-label.
43
+ * @returns the SVG chart, or a placeholder for an empty range.
44
+ */
45
+ export declare function TrendChart({ rows, hours, requests, from, to, t }: {
46
+ rows: readonly UsageDayRow[];
47
+ hours?: readonly UsageHourRow[];
48
+ requests?: readonly RequestPoint[];
49
+ from?: string;
50
+ to?: string;
51
+ t: TranslateNS<'token-usage'>;
52
+ }): ReactNode;
53
+ //# sourceMappingURL=TrendChart.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TrendChart.d.ts","sourceRoot":"","sources":["../../src/client/TrendChart.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AACtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAA;AACnE,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAOzE,6DAA6D;AAC7D,OAAO,EACL,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,YAAY,EACjF,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,GAC/C,MAAM,wBAAwB,CAAA;AAC/B,YAAY,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAiDtE;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE;IACjE,IAAI,EAAE,SAAS,WAAW,EAAE,CAAA;IAC5B,KAAK,CAAC,EAAE,SAAS,YAAY,EAAE,CAAA;IAC/B,QAAQ,CAAC,EAAE,SAAS,YAAY,EAAE,CAAA;IAClC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,CAAC,EAAE,WAAW,CAAC,aAAa,CAAC,CAAA;CAC9B,GAAG,SAAS,CAuIZ"}
@@ -0,0 +1,141 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * Daily / hourly / request-bucketed token trend chart (browser half):
4
+ * a dependency-free SVG line chart over the already-filtered summary.
5
+ * The renderer is pure presentation; the bucketing, scaling, and
6
+ * point-shape decisions live in `./trend-chart/*` so each piece can be
7
+ * tested in isolation.
8
+ *
9
+ * Two granularities share one renderer — per-day rows (x axis spans
10
+ * every calendar day of the active range, days without records plot as
11
+ * zero) and per-hour rows (a single-day window plots every whole hour of
12
+ * that day, 00:00–23:00, future hours of today reading zero). The
13
+ * third mode — request buckets — folds the request series into uniformly
14
+ * sized time buckets spanning the session's actual first-to-last window
15
+ * and scales each bucket at its real temporal proportion of the span.
16
+ *
17
+ * Hovering (or keyboard-focusing) a point highlights it and floats a
18
+ * label with that point's date/time and total tokens.
19
+ *
20
+ * @module token-usage/client/TrendChart
21
+ */
22
+ import { useState } from 'react';
23
+ import { formatTokens } from "./format.js";
24
+ import { tickValues } from "./trend-chart/axis.js";
25
+ import { buildChartPoints } from "./trend-chart/points.js";
26
+ import { dotRadius, labelIndices, scaleSeries } from "./trend-chart/scale.js";
27
+ import styles from './TrendChart.module.css';
28
+ /** Re-export the chart's pure helpers for the test suite. */
29
+ export { MAX_BUCKETS, bucketSeries, bucketWidth, buildChartPoints, dotRadius, labelIndices, niceStep, scaleSeries, scaleToSpan, tickValues, } from "./trend-chart/index.js";
30
+ /** SVG canvas metrics; the element scales to the section width via viewBox. */
31
+ const WIDTH = 800;
32
+ const HEIGHT = 190;
33
+ const TOP = 12;
34
+ const BOTTOM = 16;
35
+ const LEFT = 44;
36
+ const RIGHT = 16;
37
+ const X_LABELS = 22;
38
+ const HIT_TARGET_FLOOR = 6;
39
+ /**
40
+ * Apply the `t`-based localisation to a point's `full` tooltip. The pre-shape
41
+ * labels live in points.ts; the chart's aria-label and the floating tooltip
42
+ * both use this single source so the two stay consistent.
43
+ * @param t - the locale seat.
44
+ * @param point - the pre-shaped point.
45
+ * @returns the tooltip / aria-label text.
46
+ */
47
+ function tipOf(t, point) {
48
+ if (point.time !== undefined) {
49
+ return t('chart.bucket', {
50
+ window: point.full,
51
+ count: String(point.count ?? 0),
52
+ tokens: formatTokens(point.tokens),
53
+ });
54
+ }
55
+ return t('chart.pointLabel', { day: point.full, tokens: formatTokens(point.tokens) });
56
+ }
57
+ /**
58
+ * Render the daily / hourly / request-bucketed token line chart. Pure
59
+ * presentation: every data-driven decision (bucketing, axis scaling,
60
+ * point ordering) lives in `./trend-chart/*`; this component picks the
61
+ * right `chartAria` string for screen readers and forwards hover /
62
+ * focus state to the dot + label.
63
+ *
64
+ * Empty ranges (no data on any branch) render a placeholder instead of an
65
+ * axis so the layout does not collapse to an empty SVG.
66
+ *
67
+ * @param props - the filtered per-day rows plus the optional per-hour rows
68
+ * (when present the chart plots hours instead of days), the optional
69
+ * per-request series (session-scoped reads), the active range bounds
70
+ * (absent when unfiltered; the chart then spans first to last row), and
71
+ * the `t` seat for the empty hint and chart aria-label.
72
+ * @returns the SVG chart, or a placeholder for an empty range.
73
+ */
74
+ export function TrendChart({ rows, hours, requests, from, to, t }) {
75
+ const series = buildChartPoints({ rows, hours, requests, from, to });
76
+ if (series === null) {
77
+ return _jsx("p", { className: styles.empty, children: t('chart.empty') });
78
+ }
79
+ // Materialise the points (and apply t() through `tipOf` at render time).
80
+ const points = series.points.map(point => ({
81
+ key: point.key,
82
+ label: point.label,
83
+ full: point.full,
84
+ tokens: point.tokens,
85
+ time: 'time' in point ? point.time : undefined,
86
+ count: 'count' in point ? point.count : undefined,
87
+ }));
88
+ const { top, ticks } = tickValues(Math.max(...points.map(p => p.tokens)));
89
+ const innerHeight = HEIGHT - TOP - BOTTOM - X_LABELS;
90
+ // scaleSeries returns absolute viewBox coordinates already offset by LEFT,
91
+ // so the dots / path / x-axis labels can plug xs[i] straight into the
92
+ // SVG `cx`/`x` attributes without re-adding the y-axis margin.
93
+ const { xs, innerWidth } = scaleSeries(series, LEFT, WIDTH - RIGHT);
94
+ const radius = dotRadius(points.length);
95
+ const [active, setActive] = useState(null);
96
+ const activePoint = active === null ? null : points[active] ?? null;
97
+ const y = (tokens) => TOP + innerHeight - (tokens / top) * innerHeight;
98
+ const path = points
99
+ .map((point, index) => `${index === 0 ? 'M' : 'L'}${xs[index].toFixed(1)},${y(point.tokens).toFixed(1)}`)
100
+ .join(' ');
101
+ const chartAria = series.mode === 'temporal'
102
+ ? t('chart.ariaRequests')
103
+ : hours !== undefined ? t('chart.ariaHour') : t('chart.aria');
104
+ // The hit target around each point spans to the midpoint of each
105
+ // neighbour (the full width for a single point), with a floor so
106
+ // bunched-up request-mode points stay individually reachable — no
107
+ // fixed grid width survives a temporal scale.
108
+ const hitExtent = (index) => {
109
+ if (points.length === 1)
110
+ return { start: LEFT, width: innerWidth };
111
+ const center = xs[index];
112
+ const before = index === 0 ? undefined : xs[index - 1];
113
+ const after = index === points.length - 1 ? undefined : xs[index + 1];
114
+ const toPrev = before === undefined ? innerWidth : (center - before) / 2;
115
+ const toNext = after === undefined ? innerWidth : (after - center) / 2;
116
+ const half = Math.max(Math.min(toPrev, toNext), HIT_TARGET_FLOOR);
117
+ return { start: center - half, width: half * 2 };
118
+ };
119
+ return (_jsxs("svg", { role: "img", "aria-label": chartAria, viewBox: `0 0 ${WIDTH} ${HEIGHT}`, className: styles.chart, onMouseLeave: () => setActive(null), children: [ticks.map(tick => (_jsxs("g", { children: [_jsx("line", { x1: LEFT, y1: y(tick), x2: WIDTH - RIGHT, y2: y(tick), className: styles.grid }), _jsx("text", { x: LEFT - 6, y: y(tick) + 3, textAnchor: "end", className: styles.tick, children: formatTokens(tick) })] }, tick))), _jsx("line", { x1: LEFT, y1: y(0), x2: WIDTH - RIGHT, y2: y(0), className: styles.axis }), _jsx("path", { d: path, className: styles.line }), points.map((point, index) => (_jsx("circle", { cx: xs[index], cy: y(point.tokens), r: active === index ? radius + 2.5 : radius, className: active === index ? styles.dotActive : styles.dot }, point.key))), activePoint !== null
120
+ ? (
121
+ // The guide line drops from the active point to the x axis.
122
+ _jsx("line", { x1: xs[active], y1: y(activePoint.tokens), x2: xs[active], y2: y(0), className: styles.guide }))
123
+ : null, points.map((point, index) => {
124
+ const hit = hitExtent(index);
125
+ return (_jsx("rect", { x: hit.start, y: TOP, width: hit.width, height: innerHeight, fill: "transparent", "aria-label": tipOf(t, point), role: "button", tabIndex: 0, className: styles.hit, onMouseEnter: () => setActive(index), onFocus: () => setActive(index), onBlur: () => setActive(current => current === index ? null : current) }, point.key));
126
+ }), activePoint !== null
127
+ ? (() => {
128
+ // Floating label: kept inside the canvas horizontally (near
129
+ // the edges it flips toward the center), above the point with
130
+ // a ceiling at the canvas top.
131
+ const label = tipOf(t, activePoint);
132
+ const charWidth = 6.2;
133
+ const labelWidth = label.length * charWidth + 12;
134
+ const center = xs[active];
135
+ const left = Math.min(Math.max(center - labelWidth / 2, LEFT), WIDTH - RIGHT - labelWidth);
136
+ const labelY = Math.max(y(activePoint.tokens) - 12, TOP + 8);
137
+ return (_jsxs("g", { className: styles.pointLabel, pointerEvents: "none", children: [_jsx("rect", { x: left, y: labelY - 13, width: labelWidth, height: 20, rx: 5 }), _jsx("text", { x: left + labelWidth / 2, y: labelY, textAnchor: "middle", children: label })] }));
138
+ })()
139
+ : null, labelIndices(points.length).map(index => (_jsx("text", { x: xs[index], y: HEIGHT - 6, textAnchor: index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'middle', className: styles.tick, children: points[index].label }, index)))] }));
140
+ }
141
+ //# sourceMappingURL=TrendChart.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TrendChart.js","sourceRoot":"","sources":["../../src/client/TrendChart.tsx"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAIhC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAC7E,OAAO,MAAM,MAAM,yBAAyB,CAAA;AAE5C,6DAA6D;AAC7D,OAAO,EACL,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,YAAY,EACjF,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,GAC/C,MAAM,wBAAwB,CAAA;AAI/B,+EAA+E;AAC/E,MAAM,KAAK,GAAG,GAAG,CAAA;AACjB,MAAM,MAAM,GAAG,GAAG,CAAA;AAClB,MAAM,GAAG,GAAG,EAAE,CAAA;AACd,MAAM,MAAM,GAAG,EAAE,CAAA;AACjB,MAAM,IAAI,GAAG,EAAE,CAAA;AACf,MAAM,KAAK,GAAG,EAAE,CAAA;AAChB,MAAM,QAAQ,GAAG,EAAE,CAAA;AACnB,MAAM,gBAAgB,GAAG,CAAC,CAAA;AAoB1B;;;;;;;GAOG;AACH,S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C,EAAE,MAAM,GAAG,CAAC,EACb,UAAU,EAAE,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,EAClF,SAAS,EAAE,MAAM,CAAC,IAAI,YAErB,MAAM,CAAC,KAAK,CAAE,CAAC,KAAK,IANhB,KAAK,CAOL,CACR,CAAC,IACE,CACP,CAAA;AACH,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The conversation view tab "Usage" (browser half): one entry of the
3
+ * `conversation.view` slot ring (beside Chat / Trajectory), rendering the
4
+ * per-session token & cost dashboard for the ACTIVE conversation. The tab
5
+ * shows the focused session's totals (4 token buckets, cost, hit rate,
6
+ * TTFT average, decode throughput) with a scope switch between the session
7
+ * alone and its whole subagent subtree, a per-hour trend chart and the
8
+ * per-model table from the host stats route (`sessionId`-scoped), and a
9
+ * subagent table below — each row drill-in switches the focus to that child.
10
+ *
11
+ * Data sources: token/cost figures come from the host route (the pricing
12
+ * rule chain's authority); TTFT and throughput come from the framework's
13
+ * retained `sessionStats` projection values (`useProjection` for the current
14
+ * session, `byId[].projectionValues` for every other session), which cover
15
+ * the whole log including history written before this plugin was installed.
16
+ * A footnote states the two scopes so the difference is not a surprise.
17
+ *
18
+ * @module token-usage/client/UsageView
19
+ */
20
+ import type { ReactNode } from 'react';
21
+ import type { SnapshotSelectorHook, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
22
+ import type { ConversationSnapshot, SessionListState, UseProjection } from '@deepseek-ai/dsh-client-runtime/client';
23
+ import type { SessionId } from '@deepseek-ai/dsh-client-connection/client';
24
+ /** The view's scope switch: the session alone, or its whole subagent subtree. */
25
+ export type UsageScope = 'session' | 'tree';
26
+ /** Props: the conversation-view runtime seat (standard kit) plus the locale seat. */
27
+ export interface UsageViewProps {
28
+ useSession: SnapshotSelectorHook<ConversationSnapshot>;
29
+ useSessions: SnapshotSelectorHook<SessionListState>;
30
+ useProjection: UseProjection;
31
+ sessionId: SessionId;
32
+ t: TranslateNS<'token-usage'>;
33
+ }
34
+ /**
35
+ * Render the Usage view tab for the active conversation.
36
+ * @param props - the framework session kit, the session mirror, and the
37
+ * locale seat (from the registration's `locale:` declaration).
38
+ * @returns the dashboard: header (title, scope switch, back), stat cards
39
+ * and the 4-token strip, the chart/model columns, and the subagent table.
40
+ */
41
+ export declare function UsageView({ useSessions, useProjection, sessionId, t }: UsageViewProps): ReactNode;
42
+ //# sourceMappingURL=UsageView.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageView.d.ts","sourceRoot":"","sources":["../../src/client/UsageView.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AACtC,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAA;AACzF,OAAO,KAAK,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AACnH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,2CAA2C,CAAA;AAiB1E,iFAAiF;AACjF,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,MAAM,CAAA;AAO3C,qFAAqF;AACrF,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,oBAAoB,CAAC,oBAAoB,CAAC,CAAA;IACtD,WAAW,EAAE,oBAAoB,CAAC,gBAAgB,CAAC,CAAA;IACnD,aAAa,EAAE,aAAa,CAAA;IAC5B,SAAS,EAAE,SAAS,CAAA;IACpB,CAAC,EAAE,WAAW,CAAC,aAAa,CAAC,CAAA;CAC9B;AAsBD;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,cAAc,GAAG,SAAS,CAgSjG"}
@@ -0,0 +1,158 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * The conversation view tab "Usage" (browser half): one entry of the
4
+ * `conversation.view` slot ring (beside Chat / Trajectory), rendering the
5
+ * per-session token & cost dashboard for the ACTIVE conversation. The tab
6
+ * shows the focused session's totals (4 token buckets, cost, hit rate,
7
+ * TTFT average, decode throughput) with a scope switch between the session
8
+ * alone and its whole subagent subtree, a per-hour trend chart and the
9
+ * per-model table from the host stats route (`sessionId`-scoped), and a
10
+ * subagent table below — each row drill-in switches the focus to that child.
11
+ *
12
+ * Data sources: token/cost figures come from the host route (the pricing
13
+ * rule chain's authority); TTFT and throughput come from the framework's
14
+ * retained `sessionStats` projection values (`useProjection` for the current
15
+ * session, `byId[].projectionValues` for every other session), which cover
16
+ * the whole log including history written before this plugin was installed.
17
+ * A footnote states the two scopes so the difference is not a surprise.
18
+ *
19
+ * @module token-usage/client/UsageView
20
+ */
21
+ import { useEffect, useMemo, useRef, useState } from 'react';
22
+ import { encodeStatsQuery, STATS_PATH } from "../wire.js";
23
+ import { useAsyncResource, useDebouncedValue } from "./async-resource.js";
24
+ import { totalTokens } from "./day.js";
25
+ import { currencyViewOf, formatCost, formatSpeed, formatTokens, formatTtft } from "./format.js";
26
+ import { HitRateText } from "./HitRateText.js";
27
+ import { aggregateProjections, buildChildIndex, directSubagentIds, subagentParentOf, subtreeIds, buildStatsFreshnessKey } from "./session-stats.js";
28
+ import { StatCard } from "./StatCard.js";
29
+ import { TrendChart } from "./TrendChart.js";
30
+ import { useColorSchemeMirror } from "./use-color-scheme.js";
31
+ import styles from './UsageView.module.css';
32
+ /** Refresh debounce: bursts of session-mirror updates (one request's events)
33
+ * collapse into a single fetch, so the dashboard refreshes at REQUEST
34
+ * granularity instead of per event or per turn. */
35
+ const REFRESH_DEBOUNCE_MS = 250;
36
+ /** One fetch of the session-scoped summary from the host stats route,
37
+ * including the direct-child breakdown for the subagent table. */
38
+ function fetchSessionSummary(sessionIds, childGroups, signal) {
39
+ return fetch(STATS_PATH + encodeStatsQuery({ sessionIds, childGroups, fields: 'session' }), { signal })
40
+ .then(response => {
41
+ if (!response.ok)
42
+ throw new Error(`HTTP ${String(response.status)}`);
43
+ return response.json();
44
+ })
45
+ .then(value => {
46
+ if (typeof value !== 'object' || value === null || typeof value.total !== 'object') {
47
+ throw new Error('unexpected stats response');
48
+ }
49
+ return value;
50
+ });
51
+ }
52
+ /**
53
+ * Render the Usage view tab for the active conversation.
54
+ * @param props - the framework session kit, the session mirror, and the
55
+ * locale seat (from the registration's `locale:` declaration).
56
+ * @returns the dashboard: header (title, scope switch, back), stat cards
57
+ * and the 4-token strip, the chart/model columns, and the subagent table.
58
+ */
59
+ export function UsageView({ useSessions, useProjection, sessionId, t }) {
60
+ const rootRef = useRef(null);
61
+ useColorSchemeMirror(rootRef);
62
+ const [scope, setScope] = useState('session');
63
+ // The dashboard focus: the active conversation until a subagent row is
64
+ // drilled into. Reset when the conversation itself changes — the pane
65
+ // may reuse this instance across session switches.
66
+ const [focusId, setFocusId] = useState(sessionId);
67
+ useEffect(() => { setFocusId(sessionId); }, [sessionId]);
68
+ const [retryToken, setRetryToken] = useState(0);
69
+ const retry = () => { setRetryToken(token => token + 1); };
70
+ const byId = useSessions(state => state.byId);
71
+ // Build the child index once per mirror churn and share it across the
72
+ // three tree helpers — directSubagentIds / subtreeIds / per-row nested
73
+ // counts — so a heavy subagent subtree doesn't pay O(n) per call.
74
+ const childIndex = useMemo(() => buildChildIndex(byId), [byId]);
75
+ // The scoped session ids: the focus alone, or the focus plus its subtree.
76
+ const scopeIds = useMemo(() => scope === 'tree' ? subtreeIds(byId, focusId, childIndex) : [focusId], [byId, scope, focusId, childIndex]);
77
+ const children = useMemo(() => directSubagentIds(byId, focusId, childIndex), [byId, focusId, childIndex]);
78
+ // Tree scope folds each direct child with its own descendants so the
79
+ // subagent-table numbers add back up to the header total.
80
+ const childGroups = useMemo(() => children.map(id => (scope === 'tree' ? subtreeIds(byId, id, childIndex) : [id])), [children, scope, byId, childIndex]);
81
+ const backParent = subagentParentOf(byId, focusId);
82
+ // Live sessionStats updates every request step; mirror updatedAt alone
83
+ // does not — fold both into the debounce key (same cadence as TTFT).
84
+ const liveStats = useProjection('sessionStats');
85
+ const freshnessKey = buildStatsFreshnessKey([...new Set([...scopeIds, ...children])], { activeSessionId: sessionId, rows: byId, liveSessionStats: liveStats });
86
+ const requestKey = `${scopeIds.join('\n')}\n\t${childGroups.map(group => group.join(',')).join(';')}\n\t${freshnessKey}`;
87
+ const debouncedKey = useDebouncedValue(requestKey, REFRESH_DEBOUNCE_MS);
88
+ const [summaryState] = useAsyncResource(signal => {
89
+ const [idsPart, groupsPart] = debouncedKey.split('\n\t');
90
+ const sessionIds = (idsPart ?? '').split('\n').filter(id => id !== '');
91
+ const childGroups = (groupsPart ?? '').split(';').filter(group => group !== '').map(group => group.split(','));
92
+ return fetchSessionSummary(sessionIds, childGroups, signal);
93
+ }, [debouncedKey, retryToken], { silentAfterFirst: true, retryToken });
94
+ const stats = useMemo(() => {
95
+ const values = scopeIds.map((id) => {
96
+ if (id === sessionId)
97
+ return liveStats;
98
+ return byId[id]?.projectionValues?.sessionStats;
99
+ });
100
+ return aggregateProjections(values);
101
+ }, [scopeIds, sessionId, liveStats, byId]);
102
+ const ttftText = stats !== undefined && stats.ttftSteps > 0
103
+ ? formatTtft(stats.ttftMs / stats.ttftSteps)
104
+ : '—';
105
+ const speedText = stats !== undefined && stats.decodeMs > 0
106
+ ? formatSpeed(stats.decodeTokens / (stats.decodeMs / 1_000))
107
+ : '—';
108
+ const header = (_jsx("header", { className: styles['head'], children: _jsx("div", { className: styles['headRight'], children: _jsxs("div", { className: styles['segmented'], role: "group", "aria-label": t('view.scope.label'), children: [_jsx("button", { type: "button", className: scope === 'session' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn'], "aria-pressed": scope === 'session', onClick: () => setScope('session'), children: t('view.scope.session') }), _jsx("button", { type: "button", className: scope === 'tree' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn'], "aria-pressed": scope === 'tree', onClick: () => setScope('tree'), children: t('view.scope.tree') })] }) }) }));
109
+ if (summaryState.status === 'loading') {
110
+ return (_jsxs("div", { ref: rootRef, className: styles['root'], children: [header, _jsx("p", { className: styles['muted'], children: t('loading') })] }));
111
+ }
112
+ if (summaryState.status === 'error') {
113
+ return (_jsxs("div", { ref: rootRef, className: styles['root'], children: [header, _jsx("p", { className: styles['error'], children: t('loadFailed', { message: summaryState.message }) }), _jsx("button", { type: "button", className: styles['button'], onClick: retry, children: t('retry') })] }));
114
+ }
115
+ const summary = summaryState.value;
116
+ const view = currencyViewOf(summary);
117
+ const { total } = summary;
118
+ return (_jsxs("div", { ref: rootRef, className: styles['root'], children: [header, total.requests === 0
119
+ // The session has no recorded requests; the stat band is skipped
120
+ // but the subagent table below still renders (children may hold
121
+ // usage even when this session's scoped summary is empty).
122
+ ? _jsx("p", { className: styles['empty'], children: t('view.empty') })
123
+ : (_jsxs(_Fragment, { children: [_jsxs("div", { className: styles['cards'], children: [_jsx(StatCard, { label: t('stat.requests'), value: total.requests.toLocaleString() }), _jsx(StatCard, { label: t('stat.cost'), value: formatCost(summary.totalCost, view) }), _jsx(StatCard, { label: t('stat.totalTokens'), value: formatTokens(totalTokens(total)) }), _jsx(StatCard, { label: t('stat.hitRate'), value: _jsx(HitRateText, { totals: total }) }), _jsx(StatCard, { label: t('view.ttft'), value: ttftText }), _jsx(StatCard, { label: t('view.speed'), value: `${speedText} tok/s` })] }), _jsxs("div", { className: styles['tokenStrip'], children: [_jsxs("span", { children: [t('stat.input'), " ", _jsx("b", { children: formatTokens(total.inputTokens) })] }), _jsxs("span", { children: [t('stat.output'), " ", _jsx("b", { children: formatTokens(total.outputTokens) })] }), _jsxs("span", { children: [t('stat.cacheRead'), " ", _jsx("b", { children: formatTokens(total.cacheReadTokens) })] }), _jsxs("span", { children: [t('stat.cacheWrite'), " ", _jsx("b", { children: formatTokens(total.cacheWriteTokens) })] })] }), summary.unpricedModels.length > 0
124
+ ? (_jsx("p", { className: styles['warning'], role: "status", children: t('unpriced.warning', {
125
+ count: String(summary.unpricedModels.length),
126
+ models: summary.unpricedModels.join(', '),
127
+ zero: formatCost(0, view),
128
+ }) }))
129
+ : null, _jsxs("div", { className: styles['mid'], children: [_jsxs("section", { className: styles['chartCol'], children: [_jsx("h3", { className: styles['subtitle'], children: t('view.chart.title') }), _jsx(TrendChart, { rows: summary.byDay, t: t, ...summary.requestSeries !== undefined ? { requests: summary.requestSeries } : {}, ...summary.byDay.length === 1 ? { hours: summary.byHour } : {} })] }), _jsxs("section", { className: styles['modelCol'], children: [_jsx("h3", { className: styles['subtitle'], children: t('byModel.title') }), summary.byModel.length > 0
130
+ ? (_jsx("div", { className: styles['tableWrap'], children: _jsxs("table", { className: styles['table'], "aria-label": t('byModel.title'), children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { className: styles['modelHead'], children: t('filter.model') }), _jsx("th", { children: t('stat.requests') }), _jsx("th", { children: t('stat.input') }), _jsx("th", { children: t('stat.output') }), _jsx("th", { children: t('stat.cacheRead') }), _jsx("th", { children: t('stat.cacheWrite') }), _jsx("th", { children: t('stat.hitRate') }), _jsx("th", { children: t('stat.cost') })] }) }), _jsx("tbody", { children: summary.byModel.map(row => (_jsxs("tr", { children: [_jsx("td", { className: styles['modelCell'], children: row.model }), _jsx("td", { children: row.totals.requests.toLocaleString() }), _jsx("td", { children: formatTokens(row.totals.inputTokens) }), _jsx("td", { children: formatTokens(row.totals.outputTokens) }), _jsx("td", { children: formatTokens(row.totals.cacheReadTokens) }), _jsx("td", { children: formatTokens(row.totals.cacheWriteTokens) }), _jsx("td", { children: _jsx(HitRateText, { totals: row.totals }) }), _jsx("td", { children: formatCost(row.cost, view) })] }, row.model))) })] }) }))
131
+ : _jsx("p", { className: styles['muted'], children: t('chart.empty') })] })] })] })), _jsxs("section", { className: styles['subagents'], children: [_jsxs("div", { className: styles['subagentsHead'], children: [_jsx("h3", { className: styles['subtitle'], children: t('view.subagents.title', { count: String(children.length) }) }), (() => {
132
+ // The up-navigation control sits with the subagent section it
133
+ // returns from: the drill-in entry point is the row below.
134
+ if (backParent === undefined)
135
+ return null;
136
+ const parentSummary = byId[backParent];
137
+ if (parentSummary === undefined)
138
+ return null;
139
+ const parentId = backParent;
140
+ return (_jsx("button", { type: "button", className: styles['back'], onClick: () => setFocusId(parentId), children: t('view.back', { title: parentSummary.displayTitle ?? parentId }) }));
141
+ })()] }), children.length === 0
142
+ ? _jsx("p", { className: styles['muted'], children: t('view.subagents.none') })
143
+ : (_jsx("div", { className: styles['tableWrap'], children: _jsxs("table", { className: styles['table'], "aria-label": t('view.subagents.title', { count: String(children.length) }), children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { className: styles['modelHead'], children: t('view.subagents.titleCol') }), _jsx("th", { children: t('stat.requests') }), _jsx("th", { children: t('stat.totalTokens') }), _jsx("th", { children: t('stat.cost') }), _jsx("th", { children: t('stat.hitRate') }), _jsx("th", { children: t('view.ttft') }), _jsx("th", { children: t('view.speed') })] }) }), _jsx("tbody", { children: children.map(id => {
144
+ const child = byId[id];
145
+ const row = summary.children?.[id];
146
+ const childStats = aggregateProjections([
147
+ byId[id]?.projectionValues?.sessionStats,
148
+ ]);
149
+ // A nested-subagent marker: the count of THIS child's own
150
+ // direct subagents, so the table signals before the
151
+ // drill-in that the row has a subtree of its own.
152
+ const nestedCount = directSubagentIds(byId, id, childIndex).length;
153
+ return (_jsxs("tr", { children: [_jsxs("td", { className: styles['modelCell'], children: [_jsx("button", { type: "button", className: styles['childLink'], onClick: () => setFocusId(id), children: child?.displayTitle ?? id }), nestedCount > 0
154
+ ? (_jsxs("span", { className: styles['nestedBadge'], "aria-label": t('view.subagents.nested', { count: String(nestedCount) }), children: ["(", nestedCount, ")"] }))
155
+ : null] }), _jsx("td", { children: row?.total.requests.toLocaleString() ?? '—' }), _jsx("td", { children: row !== undefined ? formatTokens(totalTokens(row.total)) : '—' }), _jsx("td", { children: row !== undefined ? formatCost(row.totalCost, view) : '—' }), _jsx("td", { children: row !== undefined ? _jsx(HitRateText, { totals: row.total }) : '—' }), _jsx("td", { children: childStats !== undefined && childStats.ttftSteps > 0 ? formatTtft(childStats.ttftMs / childStats.ttftSteps) : '—' }), _jsx("td", { children: childStats !== undefined && childStats.decodeMs > 0 ? `${formatSpeed(childStats.decodeTokens / (childStats.decodeMs / 1_000))} tok/s` : '—' })] }, id));
156
+ }) })] }) }))] }), total.requests > 0 && _jsx("p", { className: styles['note'], children: t('view.note') })] }));
157
+ }
158
+ //# sourceMappingURL=UsageView.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageView.js","sourceRoot":"","sources":["../../src/client/UsageView.tsx"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAU5D,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACzD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AACtC,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAmB,CAAA;AAC/C,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AACnJ,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAgB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAkB,CAAA;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAA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AC,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,GAAM,EAC5H,uBAAK,UAAU,KAAK,SAAS,IAAI,UAAU,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,UAAU,CAAC,YAAY,GAAG,CAAC,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,GAAM,KA3B/I,EAAE,CA4BN,CACN,CAAA;wCACH,CAAC,CAAC,GACI,IACF,GACJ,CACP,IACK,EACT,KAAK,CAAC,QAAQ,GAAG,CAAC,IAAI,YAAG,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,YAAG,CAAC,CAAC,WAAW,CAAC,GAAK,IACrE,CACP,CAAA;AACH,CAAC"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Shared async-resource state machine for the conversation-view consumers.
3
+ * Every fetch-driven component repeats the same shape — three states
4
+ * (`loading` / `error` / `ready`), a retry counter, and cancellation on
5
+ * dependency change. Centralising the pattern here means a regression in
6
+ * the cancellation logic lands in one spot instead of three.
7
+ *
8
+ * @module token-usage/client/async-resource
9
+ */
10
+ /** The discriminated union a fetch-driven component exposes to its renderer. */
11
+ export type AsyncResource<T> = {
12
+ status: 'loading';
13
+ } | {
14
+ status: 'error';
15
+ message: string;
16
+ } | {
17
+ status: 'ready';
18
+ value: T;
19
+ };
20
+ /**
21
+ * Drive one fetcher's lifecycle: reruns on dependency change, cancels the
22
+ * previous attempt on a new fetch, and on retry-bump refetches even with
23
+ * the same deps. `silentAfterFirst` keeps the previous value on screen —
24
+ * the dashboard never blanks during a refresh once data is up.
25
+ *
26
+ * @param fetcher - the async loader; receives an `AbortSignal` for
27
+ * cancellation. Throwing aborts the fetch (the next effect run triggers
28
+ * a fresh attempt).
29
+ * @param deps - the dependency list that retriggers a fetch (passed
30
+ * through to React's effect; the retry counter joins the list).
31
+ * @param options.silentAfterFirst - when true, the first fetch goes to
32
+ * `loading` and subsequent refreshes keep the prior `value` on screen
33
+ * until the new one lands.
34
+ * @param options.retryToken - bumping this value triggers a refetch even
35
+ * with unchanged deps (the consumer wires a "retry" button to it).
36
+ * @returns `[state, retry]` — the current state plus a stable `retry()`
37
+ * callback that bumps the internal counter and re-runs the effect.
38
+ */
39
+ export declare function useAsyncResource<T>(fetcher: (signal: AbortSignal) => Promise<T>, deps: ReadonlyArray<unknown>, options: {
40
+ silentAfterFirst?: boolean;
41
+ retryToken: number;
42
+ }): [AsyncResource<T>, () => void];
43
+ /**
44
+ * Return a value that lags behind its source by `delayMs` — a debounced
45
+ * snapshot. The initial render already holds `value` (no null sentinel), so
46
+ * a consumer can fetch immediately on mount without a second shot when the
47
+ * first debounce window closes on the same value.
48
+ *
49
+ * @param value - the source value to debounce.
50
+ * @param delayMs - the lag window in milliseconds.
51
+ * @returns the debounced value.
52
+ */
53
+ export declare function useDebouncedValue<T>(value: T, delayMs: number): T;
54
+ //# sourceMappingURL=async-resource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-resource.d.ts","sourceRoot":"","sources":["../../src/client/async-resource.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,gFAAgF;AAChF,MAAM,MAAM,aAAa,CAAC,CAAC,IACvB;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACpC;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAA;AAEjC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAChC,OAAO,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,EAC5C,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,EAC5B,OAAO,EAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAC1D,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,MAAM,IAAI,CAAC,CAuChC;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,CAAC,CAOjE"}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Shared async-resource state machine for the conversation-view consumers.
3
+ * Every fetch-driven component repeats the same shape — three states
4
+ * (`loading` / `error` / `ready`), a retry counter, and cancellation on
5
+ * dependency change. Centralising the pattern here means a regression in
6
+ * the cancellation logic lands in one spot instead of three.
7
+ *
8
+ * @module token-usage/client/async-resource
9
+ */
10
+ import { useCallback, useEffect, useRef, useState } from 'react';
11
+ /**
12
+ * Drive one fetcher's lifecycle: reruns on dependency change, cancels the
13
+ * previous attempt on a new fetch, and on retry-bump refetches even with
14
+ * the same deps. `silentAfterFirst` keeps the previous value on screen —
15
+ * the dashboard never blanks during a refresh once data is up.
16
+ *
17
+ * @param fetcher - the async loader; receives an `AbortSignal` for
18
+ * cancellation. Throwing aborts the fetch (the next effect run triggers
19
+ * a fresh attempt).
20
+ * @param deps - the dependency list that retriggers a fetch (passed
21
+ * through to React's effect; the retry counter joins the list).
22
+ * @param options.silentAfterFirst - when true, the first fetch goes to
23
+ * `loading` and subsequent refreshes keep the prior `value` on screen
24
+ * until the new one lands.
25
+ * @param options.retryToken - bumping this value triggers a refetch even
26
+ * with unchanged deps (the consumer wires a "retry" button to it).
27
+ * @returns `[state, retry]` — the current state plus a stable `retry()`
28
+ * callback that bumps the internal counter and re-runs the effect.
29
+ */
30
+ export function useAsyncResource(fetcher, deps, options) {
31
+ const silent = options.silentAfterFirst === true;
32
+ const [state, setState] = useState({ status: 'loading' });
33
+ // Tracking whether the first fetch has ever completed keeps silent mode
34
+ // from blanking the UI on a transient refresh failure.
35
+ const loadedRef = useRef(false);
36
+ // Internal retry counter — kept in state so a stable callback can bump
37
+ // it via React's setter and trigger a re-run through the effect's deps.
38
+ const [retryTick, setRetryTick] = useState(0);
39
+ const retry = useCallback(() => {
40
+ setRetryTick(tick => tick + 1);
41
+ }, []);
42
+ useEffect(() => {
43
+ const controller = new AbortController();
44
+ // Silent mode: keep the prior value on screen while refetching. The
45
+ // very first attempt still flashes loading so the user sees that the
46
+ // fetch is in flight.
47
+ if (!silent || !loadedRef.current)
48
+ setState({ status: 'loading' });
49
+ fetcher(controller.signal)
50
+ .then(value => {
51
+ if (controller.signal.aborted)
52
+ return;
53
+ loadedRef.current = true;
54
+ setState({ status: 'ready', value });
55
+ })
56
+ .catch((error) => {
57
+ if (controller.signal.aborted)
58
+ return;
59
+ // Silent mode: don't blank the dashboard if we ever had data.
60
+ if (silent && loadedRef.current)
61
+ return;
62
+ setState({ status: 'error', message: error instanceof Error ? error.message : String(error) });
63
+ });
64
+ return () => { controller.abort(); };
65
+ // The fetcher itself is intentionally not in the dep list — every
66
+ // caller passes a fresh closure each render, and the token counters
67
+ // are the only legitimate triggers for a refetch.
68
+ // eslint-disable-next-line react-hooks/exhaustive-deps
69
+ }, [...deps, options.retryToken, retryTick, silent]);
70
+ return [state, retry];
71
+ }
72
+ /**
73
+ * Return a value that lags behind its source by `delayMs` — a debounced
74
+ * snapshot. The initial render already holds `value` (no null sentinel), so
75
+ * a consumer can fetch immediately on mount without a second shot when the
76
+ * first debounce window closes on the same value.
77
+ *
78
+ * @param value - the source value to debounce.
79
+ * @param delayMs - the lag window in milliseconds.
80
+ * @returns the debounced value.
81
+ */
82
+ export function useDebouncedValue(value, delayMs) {
83
+ const [debounced, setDebounced] = useState(value);
84
+ useEffect(() => {
85
+ const timer = setTimeout(() => { setDebounced(value); }, delayMs);
86
+ return () => { clearTimeout(timer); };
87
+ }, [value, delayMs]);
88
+ return debounced;
89
+ }
90
+ //# sourceMappingURL=async-resource.js.map
@@ -0,0 +1 @@
1
+ {"version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