@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.
- package/LICENSE +21 -0
- package/README.md +178 -0
- package/README.zh.md +182 -0
- package/cordis.patch.yml +7 -0
- package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
- package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
- package/lib/client/CostDeltaFlyLabel.js +24 -0
- package/lib/client/CostDeltaFlyLabel.js.map +1 -0
- package/lib/client/HitRateText.d.ts +21 -0
- package/lib/client/HitRateText.d.ts.map +1 -0
- package/lib/client/HitRateText.js +16 -0
- package/lib/client/HitRateText.js.map +1 -0
- package/lib/client/QuotaButton.d.ts +70 -0
- package/lib/client/QuotaButton.d.ts.map +1 -0
- package/lib/client/QuotaButton.js +346 -0
- package/lib/client/QuotaButton.js.map +1 -0
- package/lib/client/SessionStatsChip.d.ts +47 -0
- package/lib/client/SessionStatsChip.d.ts.map +1 -0
- package/lib/client/SessionStatsChip.js +141 -0
- package/lib/client/SessionStatsChip.js.map +1 -0
- package/lib/client/StatCard.d.ts +26 -0
- package/lib/client/StatCard.d.ts.map +1 -0
- package/lib/client/StatCard.js +10 -0
- package/lib/client/StatCard.js.map +1 -0
- package/lib/client/TokenUsageCard.d.ts +41 -0
- package/lib/client/TokenUsageCard.d.ts.map +1 -0
- package/lib/client/TokenUsageCard.js +164 -0
- package/lib/client/TokenUsageCard.js.map +1 -0
- package/lib/client/TokenUsageSection.d.ts +32 -0
- package/lib/client/TokenUsageSection.d.ts.map +1 -0
- package/lib/client/TokenUsageSection.js +266 -0
- package/lib/client/TokenUsageSection.js.map +1 -0
- package/lib/client/TrendChart.d.ts +53 -0
- package/lib/client/TrendChart.d.ts.map +1 -0
- package/lib/client/TrendChart.js +141 -0
- package/lib/client/TrendChart.js.map +1 -0
- package/lib/client/UsageView.d.ts +42 -0
- package/lib/client/UsageView.d.ts.map +1 -0
- package/lib/client/UsageView.js +158 -0
- package/lib/client/UsageView.js.map +1 -0
- package/lib/client/async-resource.d.ts +54 -0
- package/lib/client/async-resource.d.ts.map +1 -0
- package/lib/client/async-resource.js +90 -0
- package/lib/client/async-resource.js.map +1 -0
- package/lib/client/card-form.d.ts +171 -0
- package/lib/client/card-form.d.ts.map +1 -0
- package/lib/client/card-form.js +300 -0
- package/lib/client/card-form.js.map +1 -0
- package/lib/client/cost-inflate-motion.d.ts +17 -0
- package/lib/client/cost-inflate-motion.d.ts.map +1 -0
- package/lib/client/cost-inflate-motion.js +61 -0
- package/lib/client/cost-inflate-motion.js.map +1 -0
- package/lib/client/cost-inflate.d.ts +28 -0
- package/lib/client/cost-inflate.d.ts.map +1 -0
- package/lib/client/cost-inflate.js +49 -0
- package/lib/client/cost-inflate.js.map +1 -0
- package/lib/client/day.d.ts +49 -0
- package/lib/client/day.d.ts.map +1 -0
- package/lib/client/day.js +84 -0
- package/lib/client/day.js.map +1 -0
- package/lib/client/format.d.ts +120 -0
- package/lib/client/format.d.ts.map +1 -0
- package/lib/client/format.js +163 -0
- package/lib/client/format.js.map +1 -0
- package/lib/client/index.d.ts +26 -0
- package/lib/client/index.d.ts.map +1 -0
- package/lib/client/index.js +131 -0
- package/lib/client/index.js.map +1 -0
- package/lib/client/locales.d.ts +131 -0
- package/lib/client/locales.d.ts.map +1 -0
- package/lib/client/locales.js +230 -0
- package/lib/client/locales.js.map +1 -0
- package/lib/client/quota-format.d.ts +69 -0
- package/lib/client/quota-format.d.ts.map +1 -0
- package/lib/client/quota-format.js +147 -0
- package/lib/client/quota-format.js.map +1 -0
- package/lib/client/session-stats.d.ts +105 -0
- package/lib/client/session-stats.d.ts.map +1 -0
- package/lib/client/session-stats.js +142 -0
- package/lib/client/session-stats.js.map +1 -0
- package/lib/client/trend-chart/axis.d.ts +21 -0
- package/lib/client/trend-chart/axis.d.ts.map +1 -0
- package/lib/client/trend-chart/axis.js +33 -0
- package/lib/client/trend-chart/axis.js.map +1 -0
- package/lib/client/trend-chart/bucket.d.ts +24 -0
- package/lib/client/trend-chart/bucket.d.ts.map +1 -0
- package/lib/client/trend-chart/bucket.js +28 -0
- package/lib/client/trend-chart/bucket.js.map +1 -0
- package/lib/client/trend-chart/index.d.ts +12 -0
- package/lib/client/trend-chart/index.d.ts.map +1 -0
- package/lib/client/trend-chart/index.js +9 -0
- package/lib/client/trend-chart/index.js.map +1 -0
- package/lib/client/trend-chart/points.d.ts +46 -0
- package/lib/client/trend-chart/points.d.ts.map +1 -0
- package/lib/client/trend-chart/points.js +82 -0
- package/lib/client/trend-chart/points.js.map +1 -0
- package/lib/client/trend-chart/scale.d.ts +47 -0
- package/lib/client/trend-chart/scale.d.ts.map +1 -0
- package/lib/client/trend-chart/scale.js +75 -0
- package/lib/client/trend-chart/scale.js.map +1 -0
- package/lib/client/use-color-scheme.d.ts +18 -0
- package/lib/client/use-color-scheme.d.ts.map +1 -0
- package/lib/client/use-color-scheme.js +37 -0
- package/lib/client/use-color-scheme.js.map +1 -0
- package/lib/client/use-cost-inflate.d.ts +33 -0
- package/lib/client/use-cost-inflate.d.ts.map +1 -0
- package/lib/client/use-cost-inflate.js +108 -0
- package/lib/client/use-cost-inflate.js.map +1 -0
- package/lib/client.js +3892 -0
- package/lib/client.js.map +1 -0
- package/lib/index.d.ts +132 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +599 -0
- package/lib/index.js.map +1 -0
- package/lib/migrate.d.ts +60 -0
- package/lib/migrate.d.ts.map +1 -0
- package/lib/migrate.js +126 -0
- package/lib/migrate.js.map +1 -0
- package/lib/pricing.d.ts +212 -0
- package/lib/pricing.d.ts.map +1 -0
- package/lib/pricing.js +492 -0
- package/lib/pricing.js.map +1 -0
- package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
- package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
- package/lib/quota/adapters/deepseek-balance.js +76 -0
- package/lib/quota/adapters/deepseek-balance.js.map +1 -0
- package/lib/quota/adapters/kimi.d.ts +26 -0
- package/lib/quota/adapters/kimi.d.ts.map +1 -0
- package/lib/quota/adapters/kimi.js +91 -0
- package/lib/quota/adapters/kimi.js.map +1 -0
- package/lib/quota/adapters/minimax.d.ts +24 -0
- package/lib/quota/adapters/minimax.d.ts.map +1 -0
- package/lib/quota/adapters/minimax.js +136 -0
- package/lib/quota/adapters/minimax.js.map +1 -0
- package/lib/quota/adapters/opencode-go.d.ts +25 -0
- package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
- package/lib/quota/adapters/opencode-go.js +105 -0
- package/lib/quota/adapters/opencode-go.js.map +1 -0
- package/lib/quota/adapters/openrouter.d.ts +15 -0
- package/lib/quota/adapters/openrouter.d.ts.map +1 -0
- package/lib/quota/adapters/openrouter.js +54 -0
- package/lib/quota/adapters/openrouter.js.map +1 -0
- package/lib/quota/adapters/zhipu.d.ts +38 -0
- package/lib/quota/adapters/zhipu.d.ts.map +1 -0
- package/lib/quota/adapters/zhipu.js +246 -0
- package/lib/quota/adapters/zhipu.js.map +1 -0
- package/lib/quota/credentials.d.ts +79 -0
- package/lib/quota/credentials.d.ts.map +1 -0
- package/lib/quota/credentials.js +130 -0
- package/lib/quota/credentials.js.map +1 -0
- package/lib/quota/http.d.ts +49 -0
- package/lib/quota/http.d.ts.map +1 -0
- package/lib/quota/http.js +114 -0
- package/lib/quota/http.js.map +1 -0
- package/lib/quota/provider-tracking.d.ts +45 -0
- package/lib/quota/provider-tracking.d.ts.map +1 -0
- package/lib/quota/provider-tracking.js +52 -0
- package/lib/quota/provider-tracking.js.map +1 -0
- package/lib/quota/quota-route.d.ts +22 -0
- package/lib/quota/quota-route.d.ts.map +1 -0
- package/lib/quota/quota-route.js +57 -0
- package/lib/quota/quota-route.js.map +1 -0
- package/lib/quota/quota-service.d.ts +54 -0
- package/lib/quota/quota-service.d.ts.map +1 -0
- package/lib/quota/quota-service.js +171 -0
- package/lib/quota/quota-service.js.map +1 -0
- package/lib/quota/registry.d.ts +24 -0
- package/lib/quota/registry.d.ts.map +1 -0
- package/lib/quota/registry.js +38 -0
- package/lib/quota/registry.js.map +1 -0
- package/lib/quota/types.d.ts +79 -0
- package/lib/quota/types.d.ts.map +1 -0
- package/lib/quota/types.js +24 -0
- package/lib/quota/types.js.map +1 -0
- package/lib/record-cache.d.ts +38 -0
- package/lib/record-cache.d.ts.map +1 -0
- package/lib/record-cache.js +143 -0
- package/lib/record-cache.js.map +1 -0
- package/lib/rollup.d.ts +52 -0
- package/lib/rollup.d.ts.map +1 -0
- package/lib/rollup.js +117 -0
- package/lib/rollup.js.map +1 -0
- package/lib/stats-route.d.ts +88 -0
- package/lib/stats-route.d.ts.map +1 -0
- package/lib/stats-route.js +313 -0
- package/lib/stats-route.js.map +1 -0
- package/lib/stats.d.ts +158 -0
- package/lib/stats.d.ts.map +1 -0
- package/lib/stats.js +426 -0
- package/lib/stats.js.map +1 -0
- package/lib/sync-state.d.ts +27 -0
- package/lib/sync-state.d.ts.map +1 -0
- package/lib/sync-state.js +56 -0
- package/lib/sync-state.js.map +1 -0
- package/lib/sync.d.ts +74 -0
- package/lib/sync.d.ts.map +1 -0
- package/lib/sync.js +64 -0
- package/lib/sync.js.map +1 -0
- package/lib/trend-bucket.d.ts +48 -0
- package/lib/trend-bucket.d.ts.map +1 -0
- package/lib/trend-bucket.js +87 -0
- package/lib/trend-bucket.js.map +1 -0
- package/lib/usage-log.d.ts +64 -0
- package/lib/usage-log.d.ts.map +1 -0
- package/lib/usage-log.js +144 -0
- package/lib/usage-log.js.map +1 -0
- package/lib/usage-record.d.ts +59 -0
- package/lib/usage-record.d.ts.map +1 -0
- package/lib/usage-record.js +115 -0
- package/lib/usage-record.js.map +1 -0
- package/lib/wire.d.ts +452 -0
- package/lib/wire.d.ts.map +1 -0
- package/lib/wire.js +144 -0
- package/lib/wire.js.map +1 -0
- package/package.json +100 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","names":["useState","useRef","useCallback","useRef","useState","useCallback","styles","Tooltip","bands","useRef","styles","useRef","useState","useCallback","REFRESH_DEBOUNCE_MS","useRef","useMemo","fetchSessionSummary","styles","useState","useCallback","css","IconChevronDownOutline14","styles","styles","useState","styles","useRef","useState","useCallback","useRef","useState","useMemo","styles"],"sources":["../src/wire.ts","../src/client/card-form.ts","../src/client/async-resource.ts","../src/client/quota-format.ts","../src/client/use-color-scheme.ts","../src/client/QuotaButton.tsx","../src/client/day.ts","../src/client/format.ts","../src/client/HitRateText.tsx","../src/client/session-stats.ts","../src/client/cost-inflate-motion.ts","../src/client/CostDeltaFlyLabel.tsx","../src/client/cost-inflate.ts","../src/client/use-cost-inflate.ts","../src/client/SessionStatsChip.tsx","../src/client/TokenUsageCard.tsx","../src/client/StatCard.tsx","../src/client/trend-chart/axis.ts","../src/trend-bucket.ts","../src/client/trend-chart/bucket.ts","../src/client/trend-chart/points.ts","../src/client/trend-chart/scale.ts","../src/client/TrendChart.tsx","../src/client/TokenUsageSection.tsx","../src/client/UsageView.tsx","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Browser-safe wire vocabulary of the token-usage plugin: the stats endpoint\n * path and the JSON shapes the web settings page consumes. No runtime imports\n * and no I/O, so the host half (route handler) and the browser half (settings\n * page) share one vocabulary, and the client bundle can inline this module.\n *\n * @module token-usage/wire\n */\n\nimport type { UsageRecord } from './usage-record.ts'\n\nexport type { UsageFields, UsageRecord } from './usage-record.ts'\n\n/** The stats endpoint path, served by the host half's webServer route. */\nexport const STATS_PATH = '/token-usage/stats'\n\n/** How much of the stats payload a consumer asked for. `full` is the\n * settings page's whole CostedSummary; `session` is the usage tab; `chip`\n * is the header strip (totals only). */\nexport type StatsFields = 'chip' | 'session' | 'full'\n\n/** Encode one repeated query key (`sessionId=a&sessionId=b`). Empty list yields ''. */\nexport function encodeRepeatedParam(key: string, values: readonly string[]): string {\n return values.map(value => `${key}=${encodeURIComponent(value)}`).join('&')\n}\n\n/**\n * Parse every occurrence of `key` off a URL or `URLSearchParams`, dropping\n * blanks and duplicates, preserving first-seen order.\n */\nexport function decodeRepeatedParam(source: URL | URLSearchParams, key: string): string[] {\n const params = source instanceof URL ? source.searchParams : source\n const seen = new Set<string>()\n const out: string[] = []\n for (const value of params.getAll(key)) {\n if (value === '' || seen.has(value)) continue\n seen.add(value)\n out.push(value)\n }\n return out\n}\n\n/**\n * One child-row group: the row's id (first token) plus every session id\n * folded into that row. Tree scope sends `[child, ...descendants]`; session\n * scope sends `[child]` alone. Tokens are comma-joined on the wire.\n */\nexport interface ChildGroup {\n id: string\n sessionIds: readonly string[]\n}\n\n/** Encode child groups as repeated `childId=<id>[,member…]` parameters. */\nexport function encodeChildGroups(groups: readonly (readonly string[])[]): string {\n return groups\n .filter(group => group.length > 0 && group[0] !== '')\n .map(group => `childId=${encodeURIComponent(group.join(','))}`)\n .join('&')\n}\n\n/** Parse `childId=` groups; the first comma-separated token is the row id. */\nexport function decodeChildGroups(source: URL | URLSearchParams): ChildGroup[] {\n const params = source instanceof URL ? source.searchParams : source\n const seen = new Set<string>()\n const out: ChildGroup[] = []\n for (const value of params.getAll('childId')) {\n if (value === '') continue\n const sessionIds = value.split(',').filter(id => id !== '')\n const id = sessionIds[0]\n if (id === undefined || seen.has(id)) continue\n seen.add(id)\n out.push({ id, sessionIds })\n }\n return out\n}\n\n/**\n * Build the stats query string (including the leading `?`, or '' when\n * unconstrained). `fields: 'full'` is omitted — that is the default the\n * settings page already hits.\n */\nexport function encodeStatsQuery(options: {\n sessionIds?: readonly string[]\n childGroups?: readonly (readonly string[])[]\n fields?: StatsFields\n}): string {\n const parts: string[] = []\n if (options.sessionIds !== undefined && options.sessionIds.length > 0) {\n parts.push(encodeRepeatedParam('sessionId', options.sessionIds))\n }\n const children = options.childGroups !== undefined ? encodeChildGroups(options.childGroups) : ''\n if (children !== '') parts.push(children)\n if (options.fields !== undefined && options.fields !== 'full') {\n parts.push(`fields=${options.fields}`)\n }\n return parts.length === 0 ? '' : `?${parts.join('&')}`\n}\n\n/**\n * Encode a session-scope id list as a `sessionId=` query fragment pair:\n * every id becomes its own `sessionId=<encoded>` parameter (RFC-style\n * `?a=1&a=2`), so a parent-and-children fetch aggregates the whole subtree\n * in one request. The empty list yields '' (no query string at all).\n * @param ids - the session ids to filter by.\n */\nexport function encodeSessionScope(ids: readonly string[]): string {\n return encodeStatsQuery({ sessionIds: ids })\n}\n\n/**\n * Parse the `sessionId=` parameters off a URL or a parsed `URLSearchParams`:\n * every occurrence of the key becomes one entry, in URL order (so a parent\n * + children fetch preserves the caller-supplied order). Empty values are\n * dropped (defensive: a `?sessionId=` blank yields no entry) and duplicates\n * are deduped.\n * @param source - the URL or its parsed params.\n * @returns the deduplicated id list.\n */\nexport function decodeSessionScope(source: URL | URLSearchParams): string[] {\n return decodeRepeatedParam(source, 'sessionId')\n}\n\n/**\n * The quota endpoint path: the input-bar quota button polls this for the\n * current provider's rate-limit / balance snapshot. Served by the host\n * half's quota route; the query carries `?session=<id>` so the host can\n * resolve the provider the ACTIVE session is using.\n */\nexport const QUOTA_PATH = '/token-usage/quota'\n\n/** The migration-progress endpoint path, polled by the browser card. */\nexport const MIGRATION_PATH = '/token-usage/migration'\n\n/**\n * The directory-guard endpoint path, consulted by the browser card before a\n * staged directory save commits. The settings wire swallows a refused write\n * (the bound scope recovers silently and never rejects), so this route is the\n * one channel that can tell the card WHY a save would not land.\n */\nexport const DIR_GUARD_PATH = '/token-usage/dir-guard'\n\n/**\n * The full-sync endpoint path: the card's manual \"scan again\" affordance.\n * `POST` starts one full scan over every session log (the same scan the\n * one-shot startup sync ran on first install — list + inspect + dedupe), and\n * `GET` returns the live progress. The scan is fire-and-forget on the host\n * side, so the card polls while it runs.\n */\nexport const FULL_SYNC_PATH = '/token-usage/full-sync'\n\n/** The guard's verdict for one would-be directory save. */\nexport interface DirectoryGuardView {\n /** True when the Host's section validator would refuse the save right now. */\n blocked: boolean\n /** Sessions mid-conversation (an open turn) at verdict time, for the notice's number. */\n interactingSessions: number\n}\n\n/**\n * The view of one full-sync run: what the route returns to a poll, and what\n * the card's section reads. `idle` means no run has been triggered (or the\n * last one settled and the card cleared it); `running` carries the live\n * counts the card renders as a progress bar; `done` and `failed` are the\n * terminal states the card holds on screen until the next run.\n */\nexport type FullSyncView =\n | { status: 'idle' }\n | { status: 'running'; processed: number; total: number; added: number; skipped: number }\n | { status: 'done'; processed: number; total: number; added: number; skipped: number }\n | { status: 'failed'; error: string }\n\n/** Aggregated token counts over one group of records. */\nexport interface UsageTotals {\n /** Number of recorded requests (records without provider usage count here). */\n requests: number\n /** Uncached input tokens; billed input = input + cacheRead + cacheWrite. */\n inputTokens: number\n /** Output tokens. */\n outputTokens: number\n /** Cache-hit input tokens. */\n cacheReadTokens: number\n /** Cache-write input tokens. */\n cacheWriteTokens: number\n}\n\n/** One per-day aggregation row, keyed by local date `YYYY-MM-DD`. */\nexport interface UsageDayRow {\n day: string\n totals: UsageTotals\n}\n\n/** One per-request token total in time order (session-scoped reads only).\n * The usage tab's `fields=session` response is already time-bucketed: `count`\n * and `end` are set, and the chart plots the points without folding again.\n * A raw (unbucketed) point has only `time` + `tokens`. */\nexport interface RequestPoint {\n /** Session-event wall time, or the bucket start when `count` is set. */\n time: number\n /** Total tokens across the four buckets (0 for a request without usage). */\n tokens: number\n /** Requests folded into this bucket; absent on a raw per-request point. */\n count?: number\n /** Bucket end (exclusive), epoch ms; absent on a raw per-request point. */\n end?: number\n}\n\n/** Per-child row the usage tab's subagent table reads (no chart / pricing). */\nexport interface ChildUsageSummary {\n total: UsageTotals\n totalCost: number\n unpricedModels: string[]\n}\n\n/** One per-hour × per-model aggregation row, keyed by local `YYYY-MM-DDTHH`. */\nexport interface UsageHourRow {\n hour: string\n model: string\n totals: UsageTotals\n}\n\n/** One per-model aggregation row (token counts only; see the cost layer below). */\nexport interface UsageModelRow {\n model: string\n totals: UsageTotals\n}\n\n/** Per-million-token prices of one rate node, in ¥ (RMB). */\nexport interface ModelPricing {\n /** Uncached input price, ¥ per million tokens. */\n inputPerMillion: number\n /** Output price, ¥ per million tokens. */\n outputPerMillion: number\n /** Cache-hit input price, ¥ per million tokens. */\n cacheReadPerMillion?: number\n /** Cache-write input price, ¥ per million tokens. */\n cacheWritePerMillion?: number\n}\n\n/** One peak window of a day, half-open [startMinute, endMinute) in local minutes. */\nexport interface RateWindow {\n startMinute: number\n endMinute: number\n}\n\n/** A peak-pricing slot: the rates that apply inside its windows. */\nexport interface DailySlot {\n /** Optional display label. */\n label?: string\n windows: RateWindow[]\n rates: ModelPricing\n}\n\n/** A context tier: the rates that apply once the context reaches the threshold. */\nexport interface ContextTier {\n /** Context size (tokens) at and above which this tier applies. */\n threshold: number\n rates: ModelPricing\n /** Tiers may carry their own peak slots (mirrors the analyzer's node chain). */\n dailySlots?: DailySlot[]\n}\n\n/** A time rule: the container whose rates (and tiers/slots) apply inside its window. */\nexport interface TimeRule {\n /** Optional display label. */\n label?: string\n /** Inclusive window bounds, Unix seconds. */\n startTime: number\n endTime: number\n rates: ModelPricing\n contextTiers?: ContextTier[]\n dailySlots?: DailySlot[]\n}\n\n/**\n * The full pricing of one model: the base rates plus the rule chain the\n * analyzer resolves per request — time-rule container first, then context\n * tier, then peak slot. A hand-edited entry contributes only `base` (manual\n * overrides replace the model's cloud rules wholesale).\n */\nexport interface ModelRates {\n base: ModelPricing\n contextTiers: ContextTier[]\n dailySlots: DailySlot[]\n timeRules: TimeRule[]\n}\n\n/** True when any rule dimension exists beyond the flat base rates. */\nexport function hasRateRules(rates: ModelRates): boolean {\n return rates.contextTiers.length > 0 || rates.dailySlots.length > 0 || rates.timeRules.length > 0\n}\n\n/**\n * The identity of the rate one record was billed at: which time rule (by its\n * window), which context tier (by its threshold), and which peak slot (by\n * its index into the node's slots). Holds rule identity, never price\n * numbers, so a price update re-prices history without a rollup rebuild.\n */\nexport interface RateKey {\n /** Time-rule window start (Unix seconds); 0 when no rule matched. */\n ruleStart: number\n /** Time-rule window end (Unix seconds); 0 when no rule matched. */\n ruleEnd: number\n /** Context-tier threshold; 0 when no tier matched. */\n tier: number\n /** Peak-slot index into the resolved node's slots; -1 when off-peak. */\n slot: number\n}\n\n/** The neutral key of an unpriced model's rows. */\nexport const UNPRICED_KEY: RateKey = { ruleStart: 0, ruleEnd: 0, tier: 0, slot: -1 }\n\n/** Whether a key is the neutral unpriced one. */\nexport function isUnpricedKey(key: RateKey): boolean {\n return key.ruleStart === 0 && key.ruleEnd === 0 && key.tier === 0 && key.slot === -1\n}\n\n/**\n * The merged pricing table: model id → full rule set, loaded from\n * `<data dir>/pricing.ccsa.json` (cloud mirror, full rules) layered under\n * `<data dir>/pricing.json` (hand-edited flat overrides; see pricing.ts).\n * Models absent from the table are unpriced: their cost counts as 0 and they\n * surface in {@link UsageSummary.unpricedModels}.\n */\nexport type PricingTable = Record<string, ModelRates>\n\n/** One per-day × per-model × per-rate aggregation row. */\nexport interface UsageRateRow {\n day: string\n model: string\n rate: RateKey\n totals: UsageTotals\n}\n\n/**\n * The token-only aggregation shape: what the aggregation functions produce\n * and the rollup persists. No currency — cost is an additive layer computed\n * from the pricing table when the route serves the summary (attachCosts),\n * re-priced from the rate identities on every read.\n */\nexport interface TokenSummary {\n /** Totals over every recorded request. */\n total: UsageTotals\n /** Per-local-day rows, ascending by day. */\n byDay: UsageDayRow[]\n /** Per-hour × per-model rows, ascending by hour then model; the web page\n * folds them by hour to draw the single-day trend chart. */\n byHour: UsageHourRow[]\n /** Per-model rows, descending by request count. */\n byModel: UsageModelRow[]\n /** Per-day × per-model × per-rate rows, day then model then rate ascending;\n * lets the route re-aggregate any day range × model filter without\n * rereading files, and re-price history under the current table. */\n rateRows: UsageRateRow[]\n /** The most recent records, descending by time. */\n recent: UsageRecord[]\n}\n\n/** A per-model row carrying its billed cost (¥); 0 when the model is unpriced. */\nexport type CostedModelRow = UsageModelRow & { cost: number }\n\n/** The currency the stats page renders cost figures in. The amounts on the\n * wire stay RMB — this only names the display convention. */\nexport type DisplayCurrency = 'CNY' | 'USD'\n\n/**\n * The display currency a mirror region implies: `overseas` (GitHub) shows\n * USD, `domestic` (Gitee) and the unset default show CNY. Only the region\n * pick decides — an explicit `pricingUrl` never changes the display.\n * @param region - the effective `pricingRegion` (undefined when unset).\n * @returns the display currency of the stats page.\n */\nexport function currencyOfRegion(region: 'domestic' | 'overseas' | undefined): DisplayCurrency {\n return region === 'overseas' ? 'USD' : 'CNY'\n}\n\n/**\n * The token aggregation plus the cost layer — what {@link attachCosts}\n * produces before the route stamps the display-currency metadata.\n */\nexport interface CostedSummary extends TokenSummary {\n /** Absolute data directory the summary was computed from. */\n dataDir: string\n /** Billed cost over every recorded request (¥); unpriced models count 0. */\n totalCost: number\n /** Models with usage but no entry in the pricing table, byModel order. */\n unpricedModels: string[]\n /** The active pricing table (user-maintained; empty when none is configured). */\n pricing: PricingTable\n /** Per-model rows with their billed cost attached. */\n byModel: CostedModelRow[]\n}\n\n/** The full stats payload served at {@link STATS_PATH}. A discriminated\n * union over the two scope modes the route serves:\n * - `'whole'`: the settings page's whole-log read. The `requestSeries`\n * field is absent (the page plots hours/days), so its `TrendChart`\n * falls back to the `byDay` / `byHour` rows.\n * - `'session'`: the conversation view tab's session-scoped read. The\n * `sessionIds` field lists every requested id (the parent + its\n * subagent children when the scope is \"tree\"), and `requestSeries`\n * is the per-request series the chart plots at request granularity.\n *\n * Both branches share every {@link CostedSummary} field plus the\n * display-currency metadata, so a consumer can read `total` /\n * `totalCost` / `pricing` without narrowing first.\n */\nexport type StatsPayload = (CostedSummary & {\n scope: 'whole'\n /** The display currency the page converts cost figures into. Amounts on\n * the wire (totalCost, byModel[].cost, pricing rates) remain RMB. */\n currency: DisplayCurrency\n /** Effective RMB-per-USD rate (feed value, else the built-in default);\n * the divisor when `currency` is USD. */\n usdExchangeRate: number\n}) | (CostedSummary & {\n scope: 'session'\n /** The session ids aggregated to produce this payload, in URL order. */\n sessionIds: readonly string[]\n /** Per-request token totals in time order; session-scoped reads always\n * include this, so the trend chart can plot request granularity. */\n requestSeries: readonly RequestPoint[]\n /** The display currency the page converts cost figures into. */\n currency: DisplayCurrency\n /** Effective RMB-per-USD rate (the divisor when `currency` is USD). */\n usdExchangeRate: number\n /** Direct-child breakdown keyed by child id, when the request named `childId`. */\n children?: Readonly<Record<string, ChildUsageSummary>>\n})\n\n/**\n * Default shape for code that doesn't need to discriminate the scope —\n * mostly test fixtures and the `chip` and `section` summary readers.\n * Adds `requestSeries?` as an optional field so legacy callers can read\n * either branch without narrowing first. Uses a base cost layer plus the\n * display metadata; for new code, narrow on `StatsPayload` instead.\n */\nexport interface UsageSummary extends CostedSummary {\n currency: DisplayCurrency\n usdExchangeRate: number\n requestSeries?: readonly RequestPoint[]\n children?: Readonly<Record<string, ChildUsageSummary>>\n sessionIds?: readonly string[]\n}\n\n/** One normalized quota window tier, mirroring the tier vocabulary the\n * cc-switch research normalized providers onto: time-boxed windows for\n * coding-plan subscriptions, an open-ended balance tier for pay-as-you-go\n * accounts. Display adapts by tier (progress bar vs amount). */\nexport type QuotaTier = 'five_hour' | 'weekly' | 'monthly' | 'balance'\n\n/**\n * One provider quota window as the panel renders it. Percent fields carry\n * the two directions providers report (most coding plans report used,\n * MiniMax reports remaining); the panel derives whichever is missing.\n * Absolute amounts are balance semantics: `remainingValue` is what the\n * user cares about, `maxValue` (when known) enables a spend-progress bar.\n */\nexport interface QuotaWindow {\n tier: QuotaTier\n /** Used share of the window, 0–100; preferred over `remainingPercent`. */\n usedPercent?: number\n /** Remaining share of the window, 0–100. */\n remainingPercent?: number\n /** When the window resets, epoch ms; absent for balances. */\n resetAt?: number\n /** Remaining absolute amount (a balance, or a USD-metered quota). */\n remainingValue?: number\n /** Total absolute amount, when the provider reports one. */\n maxValue?: number\n /** Currency of the absolute fields. */\n unit?: 'usd' | 'cny'\n}\n\n/** Why a quota query failed, normalized so the panel can pick friendly copy. */\nexport type QuotaErrorKind = 'auth' | 'no-credential' | 'http' | 'network' | 'parse'\n\n/** The error face of a quota response. */\nexport interface QuotaError {\n kind: QuotaErrorKind\n /** Technical detail (status code, thrown message); the panel wraps it in\n * kind-specific locale copy. */\n message: string\n}\n\n/** The poll cadence the host asks the client to follow (seconds); stamped\n * on every payload variant so the button adapts to the plugin config. */\ninterface QuotaCadence {\n intervalSec: number\n}\n\n/** A successful quota read: the normalized windows of the current\n * provider, ready for the panel's adaptive grid. */\nexport interface QuotaSnapshot extends QuotaCadence {\n status: 'ok'\n /** Provider route key, exactly as session events carry it. */\n provider: string\n /** Human-readable provider name when one is resolvable. */\n providerName?: string\n /** Which adapter produced the windows (diagnostics). */\n adapterId: string\n /** When the snapshot was fetched, epoch ms. */\n fetchedAt: number\n /** Plan tier label when the provider reports one (e.g. Zhipu `data.level`). */\n planTier?: string\n windows: QuotaWindow[]\n}\n\n/** A failed quota read: the provider matched an adapter but the query\n * failed. The button stays visible (the provider IS supported) and the\n * panel shows the error with a retry. */\nexport interface QuotaFailure extends QuotaCadence {\n status: 'error'\n provider: string\n providerName?: string\n adapterId: string\n fetchedAt: number\n error: QuotaError\n}\n\n/** The full quota endpoint vocabulary. The hidden variants:\n * - `no-provider` — no provider in use is determinable yet (no activity,\n * no default selection); the button hides until one appears.\n * - `unsupported` — the provider in use has no quota adapter; the button\n * hides (switching providers brings it back).\n * - `disabled` — the quota feature is off in plugin config.\n */\nexport type QuotaPayload =\n | QuotaSnapshot\n | QuotaFailure\n | (QuotaCadence & { status: 'no-provider' })\n | (QuotaCadence & { status: 'unsupported'; provider: string; providerName?: string })\n | (QuotaCadence & { status: 'disabled' })\n\n/** The windows of a payload, empty for every non-ok variant — the helper\n * the panel reuses for the trigger icon's color. */\nexport function quotaWindowsOf(payload: QuotaPayload): readonly QuotaWindow[] {\n return payload.status === 'ok' ? payload.windows : []\n}\n","/**\n * Staged form over the `token-usage` settings namespace's fields: the data\n * directory and the mirror region pick.\n *\n * A settings write is a durable, revision-fenced document mutation, so the\n * controls stage what the user picks and commit them only on save: what is on\n * screen is exactly what a save would store. Each field shows its effective\n * value (user layer over composition layer over schema default) and whether\n * the user layer carries it — key presence, not a value comparison, marks an\n * override. The namespace has no secret fields, so there is no write-only\n * control here.\n *\n * Self-contained on purpose: the client bundle-purity rule forbids value\n * imports across plugins, so this package stages and fences its own form\n * (and its own snapshot store) rather than importing the settings section's\n * shared model.\n *\n * @module token-usage/client/card-form\n */\n\nimport type { SettingsScope, SettingsScopeSnapshot } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { DirectoryGuardView } from '../wire.ts'\nimport { DIR_GUARD_PATH, MIGRATION_PATH } from '../wire.ts'\n\n/** The fields this card edits. */\nexport const CARD_FIELDS = ['path', 'pricingRegion'] as const\n\n/** One editable field of the token-usage settings section. */\nexport type CardField = typeof CARD_FIELDS[number]\n\n/** The resolved user-facing section this card edits. */\nexport interface SectionValue {\n path?: string\n pricingRegion?: string\n}\n\n/** Live migration progress the card polls after saving a directory change. */\nexport interface MigrationView {\n /** Files finished so far. */\n done: number\n /** Total files this migration touches. */\n total: number\n /** Phase label for the progress line. */\n phase: 'copying' | 'cleaning'\n}\n\n/**\n * Minimal observable snapshot source: the stable-reference discipline the\n * shell's stores follow (same snapshot object until the fact moves), with\n * nothing the multi-field form does not use.\n */\nexport interface CardStore {\n /** @returns the current snapshot (stable reference until the next change). */\n getSnapshot(): CardState\n /** @param listener - invoked after each snapshot change. @returns the disposer. */\n subscribe(listener: () => void): () => void\n /** @param next - the new snapshot; replaces the reference only on a real change. */\n set(next: CardState): void\n}\n\n/**\n * Why the Host refused the last save, in a shape the card's locale renders.\n * The settings wire never delivers a refused write's reason (the bound scope\n * recovers silently and resolves), so the form asks the plugin's own guard\n * route and reports the verdict itself.\n */\nexport interface SaveRefusal {\n /** The mid-conversation veto on a directory change. */\n kind: 'sessions-interacting'\n /** Sessions mid-conversation at refusal time, for the notice's number. */\n interactingSessions: number\n}\n\n/** What the token-usage settings card renders. */\nexport interface CardState {\n /** False while the namespace is not served to this client; the card renders nothing. */\n available: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Draft text per field ('' marks the inherited/default option). */\n fields: Record<CardField, string>\n /** Whether saving each field would leave a user-layer entry. */\n overridden: Record<CardField, boolean>\n /** Whether the form holds an edit that a save would write. */\n dirty: boolean\n /** Whether a save is crossing the wire. */\n saving: boolean\n /** Whether the last save did not land as staged; cleared by the next edit or save. */\n failed: boolean\n /** The Host's refusal of the last save, when the guard named one; cleared\n * by the next edit or save. */\n refusal: SaveRefusal | undefined\n /** Migration progress while the Host relocates the data directory. */\n migration: MigrationView | undefined\n}\n\n/** The form actions the card's slot entry injects. */\nexport interface CardActions {\n /** Stage draft text for one field. */\n editField: (field: CardField, text: string) => void\n /** Stage a clear for one field, so saving lets it re-inherit the composition layer. */\n clearField: (field: CardField) => void\n /** Write every staged edit, then re-seed from what the Host accepted. */\n save: () => void\n /** Drop every staged edit. */\n discard: () => void\n}\n\n/**\n * Stages the settings edits over the `token-usage` scope.\n *\n * The form publishes through a snapshot store because the slot component\n * reads through a snapshot selector while both the scope and the local drafts\n * change underneath; every projection is rebuilt from the two together. Only\n * fields the user touched are staged, so a save writes a sparse patch and\n * never restates fields it did not see.\n */\nexport class CardForm {\n private snapshotValue: CardState\n private readonly listeners = new Set<() => void>()\n private drafts: Partial<Record<CardField, string>> = {}\n private saving = false\n private failed = false\n private refusal: SaveRefusal | undefined\n private migrationView: MigrationView | undefined\n private pollTimer: ReturnType<typeof setInterval> | undefined\n\n /**\n * @param scope - the bound settings scope for the `token-usage` namespace.\n */\n constructor(private readonly scope: SettingsScope<SectionValue>) {\n this.snapshotValue = this.project()\n scope.subscribe(() => { this.publish() })\n // A relocation another surface started (or one left over from a boot)\n // shows its progress here too.\n void this.pollMigration()\n }\n\n /** @returns the store the card's component reads through its bound selector. */\n bind(): CardStore {\n return {\n getSnapshot: () => this.snapshotValue,\n subscribe: (listener) => {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n },\n set: (next) => { this.store(next) },\n }\n }\n\n /** @returns the edit, clear, save, and discard actions bound to this form. */\n actions(): CardActions {\n return {\n editField: (field, text) => {\n this.drafts[field] = text\n this.failed = false\n this.refusal = undefined\n this.publish()\n },\n clearField: (field) => {\n this.drafts[field] = ''\n this.failed = false\n this.refusal = undefined\n this.publish()\n },\n save: () => { void this.save() },\n discard: () => {\n if (Object.keys(this.drafts).length === 0 && !this.failed) return\n this.drafts = {}\n this.failed = false\n this.refusal = undefined\n this.publish()\n },\n }\n }\n\n /**\n * Write the staged edits, then re-seed from what the Host accepted.\n *\n * The Host is the only authority on acceptance — an empty draft clears the\n * field, anything else stores the trimmed text (so blanking a control and\n * saving is the same gesture as clearing it). A save that did not land keeps\n * its drafts so the user can correct it instead of retyping. A landed save\n * that moved the data directory starts the migration poll: the Host\n * relocates as a two-phase commit and the card shows the file progress\n * until it settles.\n *\n * A staged directory edit is vetted through the plugin's guard route\n * before anything writes, and re-checked when the write did not land: the\n * settings wire swallows a refused write (the bound scope recovers\n * silently), so the guard is the only channel that can name the refusal —\n * otherwise the card could only say \"did not land\".\n */\n private async save(): Promise<void> {\n const edited = CARD_FIELDS.filter(field => this.drafts[field] !== undefined)\n if (edited.length === 0 || this.saving) return\n // Snapshot the intended writes: a keystroke mid-await must not change what\n // this save commits.\n const intended = edited.map(field => [field, this.drafts[field]!.trim()] as const)\n this.saving = true\n this.failed = false\n this.refusal = undefined\n this.publish()\n const pathEdit = intended.find(([field]) => field === 'path')\n if (pathEdit !== undefined) {\n const blocked = await this.guard(pathEdit[1])\n if (blocked !== undefined) {\n // Refused up front: nothing writes, the drafts stay staged, and the\n // notice says exactly what to end before saving again.\n this.saving = false\n this.failed = true\n this.refusal = blocked\n this.publish()\n return\n }\n }\n let landed = true\n try {\n for (const [field, text] of intended) {\n if (text === '') await this.scope.unset(field)\n else await this.scope.set(field, text)\n }\n // Read back: the Host's validators own the constraints no schema\n // expresses, so acceptance is judged from the stored layers.\n for (const [field, text] of intended) {\n if (text === '' ? this.stored(field) : this.storedValue(field) !== text) {\n landed = false\n break\n }\n }\n } catch (_settingsWriteFailure) {\n landed = false\n }\n // A directory write that did not land is usually the Host's validator\n // refusing between the pre-check and the write (a session started\n // mid-save); ask the guard again so the notice still names it.\n if (!landed && pathEdit !== undefined) {\n const blocked = await this.guard(pathEdit[1])\n if (blocked !== undefined) this.refusal = blocked\n }\n if (landed) {\n for (const [field, _text] of intended) delete this.drafts[field]\n }\n this.saving = false\n this.failed = !landed\n if (landed && intended.some(([field]) => field === 'path')) void this.pollMigration()\n this.publish()\n }\n\n /**\n * Ask the Host's guard route whether saving this directory would be refused\n * right now; a transport failure stays advisory (the write path's own\n * read-back still governs acceptance).\n * @param path - the staged path text ('' for the clear-to-default gesture).\n * @returns the refusal to show, or undefined when the save may proceed.\n */\n private async guard(path: string): Promise<SaveRefusal | undefined> {\n try {\n const response = await fetch(`${DIR_GUARD_PATH}?path=${encodeURIComponent(path)}`)\n if (!response.ok) return undefined\n const body = await response.json() as DirectoryGuardView\n if (body.blocked === true && typeof body.interactingSessions === 'number' && body.interactingSessions > 0) {\n return { kind: 'sessions-interacting', interactingSessions: body.interactingSessions }\n }\n } catch (_guardFailure) {\n // Unreachable guard: proceed to the write and let acceptance speak.\n }\n return undefined\n }\n\n /**\n * Poll the Host's migration endpoint until it answers null (no migration\n * running), publishing each progress step.\n */\n private async pollMigration(): Promise<void> {\n if (this.pollTimer !== undefined) return\n const tick = async (): Promise<void> => {\n let view: MigrationView | undefined\n try {\n const response = await fetch(MIGRATION_PATH)\n if (response.ok) {\n const body = await response.json() as MigrationView | null\n if (body !== null\n && (body.phase === 'copying' || body.phase === 'cleaning')\n && typeof body.done === 'number' && typeof body.total === 'number') {\n view = body\n }\n }\n } catch (_migrationPollFailure) {\n // The next tick retries; a transient read must not end the poll.\n }\n if (view === undefined && this.migrationView === undefined) {\n this.stopPolling()\n return\n }\n const settled = view === undefined\n if (settled) this.stopPolling()\n this.migrationView = view\n this.publish()\n }\n await tick()\n if (this.pollTimer === undefined && this.migrationView !== undefined) {\n this.pollTimer = setInterval(() => { void tick() }, 300)\n }\n }\n\n /** Stop the poll timer; the progress line leaves with the next publish. */\n private stopPolling(): void {\n if (this.pollTimer !== undefined) {\n clearInterval(this.pollTimer)\n this.pollTimer = undefined\n }\n }\n\n private snapshot(): SettingsScopeSnapshot<SectionValue> {\n return this.scope.getSnapshot()\n }\n\n /** The raw user layer narrowed to a record; the wire answer is `unknown`. */\n private userLayer(): Record<string, unknown> | undefined {\n const user = this.snapshot().user\n return typeof user === 'object' && user !== null ? user as Record<string, unknown> : undefined\n }\n\n private storedValue(field: CardField): unknown {\n return this.userLayer()?.[field]\n }\n\n private stored(field: CardField): boolean {\n const user = this.userLayer()\n return user !== undefined && Object.hasOwn(user, field)\n }\n\n /** The resolved (draft-free) text of one field; '' means inherited. */\n private effectiveOf(field: CardField): string {\n const value = this.snapshot().value?.[field]\n return typeof value === 'string' ? value : ''\n }\n\n /** The effective (draft-or-resolved) text of one field; '' means inherited. */\n private textOf(field: CardField): string {\n return this.drafts[field] ?? this.effectiveOf(field)\n }\n\n private project(): CardState {\n const snapshot = this.snapshot()\n const fields = {} as Record<CardField, string>\n const overridden = {} as Record<CardField, boolean>\n let dirty = false\n for (const field of CARD_FIELDS) {\n fields[field] = this.textOf(field)\n // A staged edit answers for itself, so the override badge previews the\n // save rather than reporting a state the pending edit contradicts.\n overridden[field] = this.drafts[field] !== undefined\n ? this.drafts[field]!.trim() !== ''\n : this.stored(field)\n if (this.drafts[field] !== undefined && this.drafts[field] !== this.effectiveOf(field)) {\n dirty = true\n }\n }\n return {\n available: snapshot.status === 'ready',\n writable: snapshot.writable,\n fields,\n overridden,\n dirty,\n saving: this.saving,\n failed: this.failed,\n refusal: this.refusal,\n migration: this.migrationView,\n }\n }\n\n /** Replace the snapshot reference and notify, only when the fact moved. */\n private store(next: CardState): void {\n if (next === this.snapshotValue) return\n this.snapshotValue = next\n for (const listener of this.listeners) listener()\n }\n\n private publish(): void {\n this.store(this.project())\n }\n}\n","/**\n * Shared async-resource state machine for the conversation-view consumers.\n * Every fetch-driven component repeats the same shape — three states\n * (`loading` / `error` / `ready`), a retry counter, and cancellation on\n * dependency change. Centralising the pattern here means a regression in\n * the cancellation logic lands in one spot instead of three.\n *\n * @module token-usage/client/async-resource\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\n/** The discriminated union a fetch-driven component exposes to its renderer. */\nexport type AsyncResource<T> =\n | { status: 'loading' }\n | { status: 'error'; message: string }\n | { status: 'ready'; value: T }\n\n/**\n * Drive one fetcher's lifecycle: reruns on dependency change, cancels the\n * previous attempt on a new fetch, and on retry-bump refetches even with\n * the same deps. `silentAfterFirst` keeps the previous value on screen —\n * the dashboard never blanks during a refresh once data is up.\n *\n * @param fetcher - the async loader; receives an `AbortSignal` for\n * cancellation. Throwing aborts the fetch (the next effect run triggers\n * a fresh attempt).\n * @param deps - the dependency list that retriggers a fetch (passed\n * through to React's effect; the retry counter joins the list).\n * @param options.silentAfterFirst - when true, the first fetch goes to\n * `loading` and subsequent refreshes keep the prior `value` on screen\n * until the new one lands.\n * @param options.retryToken - bumping this value triggers a refetch even\n * with unchanged deps (the consumer wires a \"retry\" button to it).\n * @returns `[state, retry]` — the current state plus a stable `retry()`\n * callback that bumps the internal counter and re-runs the effect.\n */\nexport function useAsyncResource<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n deps: ReadonlyArray<unknown>,\n options: { silentAfterFirst?: boolean; retryToken: number },\n): [AsyncResource<T>, () => void] {\n const silent = options.silentAfterFirst === true\n const [state, setState] = useState<AsyncResource<T>>({ status: 'loading' })\n // Tracking whether the first fetch has ever completed keeps silent mode\n // from blanking the UI on a transient refresh failure.\n const loadedRef = useRef(false)\n // Internal retry counter — kept in state so a stable callback can bump\n // it via React's setter and trigger a re-run through the effect's deps.\n const [retryTick, setRetryTick] = useState(0)\n const retry = useCallback(() => {\n setRetryTick(tick => tick + 1)\n }, [])\n\n useEffect(() => {\n const controller = new AbortController()\n // Silent mode: keep the prior value on screen while refetching. The\n // very first attempt still flashes loading so the user sees that the\n // fetch is in flight.\n if (!silent || !loadedRef.current) setState({ status: 'loading' })\n fetcher(controller.signal)\n .then(value => {\n if (controller.signal.aborted) return\n loadedRef.current = true\n setState({ status: 'ready', value })\n })\n .catch((error: unknown) => {\n if (controller.signal.aborted) return\n // Silent mode: don't blank the dashboard if we ever had data.\n if (silent && loadedRef.current) return\n setState({ status: 'error', message: error instanceof Error ? error.message : String(error) })\n })\n return () => { controller.abort() }\n // The fetcher itself is intentionally not in the dep list — every\n // caller passes a fresh closure each render, and the token counters\n // are the only legitimate triggers for a refetch.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps, options.retryToken, retryTick, silent])\n\n return [state, retry]\n}\n\n/**\n * Return a value that lags behind its source by `delayMs` — a debounced\n * snapshot. The initial render already holds `value` (no null sentinel), so\n * a consumer can fetch immediately on mount without a second shot when the\n * first debounce window closes on the same value.\n *\n * @param value - the source value to debounce.\n * @param delayMs - the lag window in milliseconds.\n * @returns the debounced value.\n */\nexport function useDebouncedValue<T>(value: T, delayMs: number): T {\n const [debounced, setDebounced] = useState(value)\n useEffect(() => {\n const timer = setTimeout(() => { setDebounced(value) }, delayMs)\n return () => { clearTimeout(timer) }\n }, [value, delayMs])\n return debounced\n}\n","/**\n * Browser-side display formatting of the quota panel: the derived\n * remaining share, the three-stop severity band, the trigger-ring fill\n * share, the trigger tooltip figure, the reset countdown, and the money /\n * percent figures. Pure functions, shared by the button (the trigger icon\n * reads the finest-granularity window) and the panel's window columns.\n *\n * @module token-usage/client/quota-format\n */\n\nimport type { QuotaWindow } from '../wire.ts'\n\n/** The three color stops the quota surfaces use, best → worst. */\nexport type QuotaSeverity = 'ok' | 'warn' | 'exhausted'\n\n/** Severity thresholds on the REMAINING share (percent) — the traffic-light\n * standard: above 60 reads green (plenty left), 20–60 yellow (watch it),\n * below 20 red (effectively gone). */\nconst REMAIN_YELLOW = 60\nconst REMAIN_RED = 20\n\n/** Whole-number percent, one decimal kept when it exists (`62%`, `87.5%`). */\nexport function formatQuotaPercent(value: number): string {\n const rounded = Math.round(value * 10) / 10\n return `${Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1)}%`\n}\n\n/** A money figure with its symbol: `$6.80` / `¥110.00`. */\nexport function formatQuotaMoney(value: number, unit: 'usd' | 'cny'): string {\n return `${unit === 'usd' ? '$' : '¥'}${value.toFixed(2)}`\n}\n\n/**\n * The used share of one window, 0–100, whichever direction the provider\n * reported: the explicit `usedPercent`, else `remainingPercent` inverted,\n * else the balance fraction (`1 - remaining/max`). Undefined when the\n * window carries no computable ratio (a balance without a total).\n */\nexport function quotaUsedPercent(window: QuotaWindow): number | undefined {\n if (window.usedPercent !== undefined) return clampPercent(window.usedPercent)\n if (window.remainingPercent !== undefined) return clampPercent(100 - window.remainingPercent)\n if (window.remainingValue !== undefined && window.maxValue !== undefined && window.maxValue > 0) {\n return clampPercent((1 - window.remainingValue / window.maxValue) * 100)\n }\n return undefined\n}\n\n/**\n * The remaining share of one window, 0–100 — the severity input (severity\n * reads what is LEFT, not what is spent). Mirrors {@link quotaUsedPercent}'s\n * fallback chain in the opposite direction.\n */\nexport function quotaRemainingPercent(window: QuotaWindow): number | undefined {\n if (window.remainingPercent !== undefined) return clampPercent(window.remainingPercent)\n if (window.usedPercent !== undefined) return clampPercent(100 - window.usedPercent)\n if (window.remainingValue !== undefined && window.maxValue !== undefined && window.maxValue > 0) {\n return clampPercent((window.remainingValue / window.maxValue) * 100)\n }\n return undefined\n}\n\n/** Map a remaining share (percent) to the traffic-light band: green above\n * 60, yellow 20–60, red below 20. A window with no computable ratio reads\n * by its absolute amount: an overdrawn/empty balance (≤ 0) is red,\n * anything else uncolored — a plain balance never paints alarm just for\n * lacking a total. */\nexport function quotaSeverityOf(window: QuotaWindow): QuotaSeverity {\n const remaining = quotaRemainingPercent(window)\n if (remaining === undefined) {\n return window.remainingValue !== undefined && window.remainingValue <= 0 ? 'exhausted' : 'ok'\n }\n if (remaining < REMAIN_RED) return 'exhausted'\n if (remaining <= REMAIN_YELLOW) return 'warn'\n return 'ok'\n}\n\n/**\n * The FINEST-granularity window of a payload — 5-hour over weekly over\n * monthly over balance. The trigger icon reads this one, not the worst\n * across windows: the finest unit is the constraint the session is\n * currently acting inside (a calm 5-hour window carries the icon even when\n * the weekly pool runs low). Undefined when there is no window at all.\n */\nexport function finestQuotaWindow(windows: readonly QuotaWindow[]): QuotaWindow | undefined {\n const rank: Record<QuotaWindow['tier'], number> = { five_hour: 0, weekly: 1, monthly: 2, balance: 3 }\n let pick: QuotaWindow | undefined\n for (const window of windows) {\n if (pick === undefined || rank[window.tier] < rank[pick.tier]) pick = window\n }\n return pick\n}\n\n/**\n * Fill share of the trigger ring, 0–1. Ratio windows map the remaining\n * percent; a funded balance without a total paints a full ring (the color\n * stays neutral — amounts tint only at ≤ 0); empty / overdrawn / missing\n * windows leave the track only.\n */\nexport function quotaIconFillShare(window: QuotaWindow | undefined): number {\n if (window === undefined) return 0\n const remaining = quotaRemainingPercent(window)\n if (remaining !== undefined) return remaining / 100\n if (window.remainingValue !== undefined && window.remainingValue > 0) return 1\n return 0\n}\n\n/**\n * The trigger tooltip's figure for one window: the remaining share as a\n * percent when a ratio exists (any direction, or the balance fraction),\n * else the remaining amount (a ratio-less balance, the DeepSeek shape);\n * undefined when the window carries neither (nothing to show beyond the\n * plain label).\n */\nexport function quotaTriggerFigure(window: QuotaWindow | undefined): string | undefined {\n if (window === undefined) return undefined\n const remaining = quotaRemainingPercent(window)\n if (remaining !== undefined) return formatQuotaPercent(remaining)\n if (window.remainingValue !== undefined) {\n return formatQuotaMoney(window.remainingValue, window.unit ?? 'cny')\n }\n return undefined\n}\n\n/**\n * The reset countdown in the shell's compact shape: `2h 14m` under a day,\n * `48m` under an hour, `1d 3h` above; a non-positive remainder reads `0m`\n * (the next poll refreshes the stale window).\n * @param resetAt - epoch ms of the window's reset.\n * @param now - epoch ms the countdown is taken at.\n */\nexport function formatResetCountdown(resetAt: number, now: number): string {\n const minutes = Math.max(0, Math.floor((resetAt - now) / 60_000))\n if (minutes < 60) return `${String(minutes)}m`\n const hours = Math.floor(minutes / 60)\n if (hours < 24) return `${String(hours)}h ${String(minutes % 60)}m`\n return `${String(Math.floor(hours / 24))}d ${String(hours % 24)}h`\n}\n\n/** A wall-clock `HH:MM` stamp of an epoch-ms time (the \"updated at\" figure). */\nexport function formatQuotaClock(ms: number): string {\n const date = new Date(ms)\n const pad = (value: number): string => String(value).padStart(2, '0')\n return `${pad(date.getHours())}:${pad(date.getMinutes())}`\n}\n\n/** Clamp into 0–100. */\nfunction clampPercent(value: number): number {\n return Math.min(100, Math.max(0, value))\n}\n","/**\n * Shared browser-half hook: mirror the shell's root `color-scheme` onto a\n * plugin-owned root element. The shell sets the property on\n * `document.documentElement` only, so form controls inside plugin surfaces\n * render with the UA default (white) in dark mode; scoping the property to\n * the surface's root fixes selects, inputs, and dialogs without touching\n * anything outside it. Used by the settings section and the conversation\n * view tab.\n *\n * @module token-usage/client/use-color-scheme\n */\n\nimport { useEffect } from 'react'\nimport type { RefObject } from 'react'\n\n/**\n * Mirror the shell's `color-scheme` inline style onto the given root element.\n * @param rootRef - the surface's root element ref.\n */\nexport function useColorSchemeMirror(rootRef: RefObject<HTMLElement | null>): void {\n useEffect(() => {\n const root = document.documentElement\n const element = rootRef.current\n if (element === null) return\n const sync = (): void => {\n const scheme = root.style.colorScheme\n if (scheme !== '') element.style.colorScheme = scheme\n else element.style.removeProperty('color-scheme')\n }\n sync()\n // The shell rewrites the inline style on every theme switch.\n const observer = new MutationObserver(sync)\n observer.observe(root, { attributes: true, attributeFilter: ['style'] })\n return () => observer.disconnect()\n }, [rootRef])\n}","/**\n * Input-bar quota button (browser half): a 28×28 round trigger registered\n * into the `conversation.input.right` slot (it renders left of the model\n * chip — the host's fixed tool-row order). The glyph is a remaining-share\n * ring (ContextMeter family) colored by the finest window. Clicking opens a\n * width-tiered popup (amount-only 200px / one progress bar 232px / two\n * bars 320px) centered on the button with the current provider's quota\n * windows: progress columns (5 小时 / 每周) for coding-plan providers, an\n * amount row for balance providers.\n *\n * The provider follows the model CHIP's live selection (the shell's\n * model-selection service reports the host's next selection before any\n * request is sent); without that service the host falls back to the last\n * request's provider, else the default selection.\n *\n * The button SELF-GATES: it renders nothing while the host cannot\n * determine a provider (`no-provider`), the provider has no quota adapter\n * (`unsupported`), or the feature is off (`disabled`) — switching\n * providers makes it appear again. A supported provider whose query fails\n * KEEPS the button and shows the error with a retry inside the panel.\n *\n * The hover tooltip reads provider name + the finest window's exact\n * remaining figure (percent, or the amount when no ratio exists).\n *\n * The interaction copies ContextMeter verbatim (click toggles, document\n * pointerdown outside closes, Escape closes); mutual exclusion with the\n * ContextMeter panel falls out of both components' outside-close\n * handlers — opening one closes the other on its next pointerdown.\n *\n * @module token-usage/client/QuotaButton\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { CSSProperties, ReactNode } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: merges the standard session kit into the input-right runtime\n// props this component binds.\nimport type {} from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the `conversation.input.right` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { QuotaError, QuotaPayload, QuotaTier, QuotaWindow } from '../wire.ts'\nimport { QUOTA_PATH } from '../wire.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport {\n finestQuotaWindow, formatQuotaClock, formatQuotaMoney, formatQuotaPercent, formatResetCountdown,\n quotaIconFillShare, quotaRemainingPercent, quotaSeverityOf, quotaTriggerFigure, quotaUsedPercent,\n} from './quota-format.ts'\nimport type { QuotaSeverity } from './quota-format.ts'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport styles from './QuotaButton.module.css'\n\n/** The poll cadence fallback (seconds) while no payload has named one. */\nconst DEFAULT_POLL_SEC = 60\n\n/** Panel width tiers (px), by how much the windows paint: a lone amount\n * reads at a glance, one progress bar needs breathing room, two bars (the\n * 5-hour + weekly coding plans, or a long error body) the full plate. Kept\n * in sync with the CSS max-width clamp. */\nconst PANEL_WIDTH_BALANCE = 200\nconst PANEL_WIDTH_SINGLE = 232\nconst PANEL_WIDTH_FULL = 320\nconst PANEL_VIEWPORT_MARGIN = 16\n\n/** Tier → label key; the locale dictionaries carry both languages. */\nconst TIER_LABEL_KEYS: Record<QuotaTier, 'quota.tier.fiveHour' | 'quota.tier.weekly' | 'quota.tier.monthly' | 'quota.tier.balance'> = {\n five_hour: 'quota.tier.fiveHour',\n weekly: 'quota.tier.weekly',\n monthly: 'quota.tier.monthly',\n balance: 'quota.tier.balance',\n}\n\n/**\n * Structural view of the shell's model-selection service\n * (`ctx.modelDirectories`, owned by ui-model-selection) — the same shared\n * per-session directory the model chip renders from. Structural on\n * purpose: no value import across plugins, and no compile-time tie to a\n * package version the shell may or may not carry.\n */\nexport interface ModelSelectionSource {\n /** The session's shared directory (throws when the session resolves no scope). */\n directoryFor(sessionId: string): {\n /** The host-reported selection for the NEXT assembled step; null before the first load. */\n store: {\n getSnapshot(): { current: { provider: string } | null }\n subscribe(fn: () => void): () => void\n }\n }\n}\n\n/** Stable holder the registration injects; the service attaches late (optional inject). */\nexport interface ModelDirectoryHandle {\n readonly service: ModelSelectionSource | undefined\n}\n\n/** Props the quota button binds for the conversation input-right slot. */\nexport type QuotaButtonProps =\n PropsRuntime<'conversation.input.right'>\n & PropsLocale<'token-usage'>\n & { modelDirectory?: ModelDirectoryHandle }\n\n/**\n * Render the input-bar quota button for the active session's provider.\n * @param props - the framework session id, the locale seat, and the\n * optional model-directory holder (the chip's live selection).\n * @returns the trigger + panel, or null while hidden (see the module note).\n */\nexport function QuotaButton({ sessionId, t, modelDirectory }: QuotaButtonProps): ReactNode | null {\n const rootRef = useRef<HTMLSpanElement>(null)\n useColorSchemeMirror(rootRef)\n const [open, setOpen] = useState(false)\n\n // The panel centers on the button rather than corner-anchoring to it:\n // the harness's own popups sit flush right because their triggers own the\n // row's right end, but this one renders left of the model chip, where a\n // right-aligned panel would skew up-left. The slot exposes no positioned\n // ancestor to lean on, so the offset is measured from the wrapper (whose\n // position: relative hosts the panel) — panel center on button center,\n // nudged to stay inside the viewport's 16px margins (the button sits in\n // the right cluster, where a bare centering could push the panel\n // off-screen on narrow windows). Set at open time, refreshed on resize\n // and any ancestor scroll while open.\n const [panelLeft, setPanelLeft] = useState<number | undefined>(undefined)\n const measurePanelLeft = useCallback((width: number): void => {\n const wrapper = rootRef.current\n if (wrapper === null) return\n const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect()\n const panelWidth = Math.min(width, window.innerWidth - 2 * PANEL_VIEWPORT_MARGIN)\n const desired = (wrapperWidth - panelWidth) / 2\n const minLeft = PANEL_VIEWPORT_MARGIN - wrapperLeft\n const maxLeft = window.innerWidth - PANEL_VIEWPORT_MARGIN - panelWidth - wrapperLeft\n setPanelLeft(Math.min(Math.max(desired, minLeft), Math.max(minLeft, maxLeft)))\n }, [])\n\n // The provider the model chip currently selects — the host-reported NEXT\n // selection, live before any request is sent. Seeded synchronously (the\n // chip's directory has usually loaded by the time this button mounts),\n // then kept live through the store subscription; absent when the shell's\n // model-selection service is unavailable or has not loaded yet, in which\n // case the host falls back to its own resolution (last request's\n // provider, else the default model selection).\n const modelService = modelDirectory?.service\n const readChipProvider = (): string | undefined => {\n if (sessionId === '' || modelService === undefined) return undefined\n try {\n return modelService.directoryFor(sessionId).store.getSnapshot().current?.provider ?? undefined\n } catch {\n // An unresolvable session scope (e.g. a transient subagent address)\n // simply contributes no hint.\n return undefined\n }\n }\n const [chipProvider, setChipProvider] = useState<string | undefined>(readChipProvider)\n useEffect(() => {\n // Re-seed on session/service change, then subscribe for chip switches.\n setChipProvider(readChipProvider())\n if (sessionId === '' || modelService === undefined) return\n let directory: ReturnType<ModelSelectionSource['directoryFor']> | undefined\n try {\n directory = modelService.directoryFor(sessionId)\n } catch {\n return\n }\n return directory.store.subscribe(() => { setChipProvider(readChipProvider()) })\n // The synchronous reader is intentionally not a dep: it closes over the\n // two deps below and would re-run the effect on every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sessionId, modelService])\n\n const [resource, retry] = useAsyncResource<QuotaPayload | null>(\n signal => fetchQuotaPayload(sessionId, chipProvider, signal),\n [sessionId, chipProvider],\n { silentAfterFirst: true, retryToken: 0 },\n )\n const payload = resource.status === 'ready' ? resource.value : null\n // The width tier follows what the windows paint (amount-only / one bar /\n // two bars — see {@link panelWidthOf}); errors read the full plate.\n const panelWidth = panelWidthOf(payload)\n // The cadence follows the host's config (stamped on every payload); the\n // fallback only covers the very first polls.\n const pollMs = (payload?.intervalSec ?? DEFAULT_POLL_SEC) * 1000\n useEffect(() => {\n const timer = setInterval(retry, pollMs)\n return () => { clearInterval(timer) }\n }, [pollMs, retry])\n\n // Visible only for a determinable, adapter-backed provider; errors keep\n // the button (the panel carries them).\n const visible = payload !== null && (payload.status === 'ok' || payload.status === 'error')\n // A provider switch (or a turn to unsupported) mid-panel closes it.\n useEffect(() => {\n if (!visible && open) setOpen(false)\n }, [visible, open])\n\n // Outside click / Escape close — ContextMeter's pattern, one document\n // listener pair while open.\n useEffect(() => {\n if (!open) return\n const onPointerDown = (event: PointerEvent): void => {\n if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return\n setOpen(false)\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') setOpen(false)\n }\n document.addEventListener('pointerdown', onPointerDown)\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('pointerdown', onPointerDown)\n document.removeEventListener('keydown', onKeyDown)\n }\n }, [open])\n\n // While open, a viewport resize or any ancestor scroll moves the button\n // — re-measure so the panel keeps following its center. Re-running on a\n // width-tier change (a provider switch mid-panel) re-centers too.\n useEffect(() => {\n if (!open) return\n const onViewportChange = (): void => { measurePanelLeft(panelWidth) }\n measurePanelLeft(panelWidth)\n window.addEventListener('resize', onViewportChange)\n window.addEventListener('scroll', onViewportChange, true)\n return () => {\n window.removeEventListener('resize', onViewportChange)\n window.removeEventListener('scroll', onViewportChange, true)\n }\n }, [open, panelWidth, measurePanelLeft])\n\n if (!visible || payload === null) return null\n\n const windows = payload.status === 'ok' ? payload.windows : []\n // The icon reads the FINEST-granularity window (5-hour over weekly over\n // balance), not the worst across them — the finest unit is the constraint\n // the session currently acts inside.\n const finest = finestQuotaWindow(windows)\n const severity = finest === undefined ? 'ok' : quotaSeverityOf(finest)\n const triggerClass = [styles.trigger]\n if (severity === 'warn') triggerClass.push(styles['icon-warn'])\n else if (severity === 'exhausted') triggerClass.push(styles['icon-exhausted'])\n else if (finest !== undefined && quotaRemainingPercent(finest) !== undefined) {\n // A healthy ratio window (or an amount WITH a total, ratio-colored the\n // same way) reads green, completing the traffic light; an absolute\n // amount without a total stays neutral — it colors only at ≤ 0 (red).\n triggerClass.push(styles['icon-ok'])\n }\n const triggerClassName = triggerClass.join(' ').trim()\n\n // The hover tooltip carries the exact figure the ring approximates:\n // provider name + the finest window's remaining share (its amount when\n // no ratio exists); errors and window-less payloads keep the plain\n // label.\n const figure = quotaTriggerFigure(finest)\n const triggerTip = figure === undefined\n ? t('quota.trigger')\n : t('quota.triggerSummary', { name: payload.providerName ?? payload.provider, figure })\n\n return (\n <span ref={rootRef} className={styles.root}>\n <Tooltip label={triggerTip} side=\"top\" delayMs={200} disabled={open}>\n <button\n type=\"button\"\n className={triggerClassName}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n aria-label={t('quota.trigger')}\n // Opening refreshes (the host's TTL cache keeps it cheap) and\n // measures the centered placement before the panel's first paint;\n // closing does neither — the poll cadence covers the data.\n onClick={() => { if (!open) { retry(); measurePanelLeft(panelWidth) } setOpen(!open) }}\n >\n <QuotaGlyph share={quotaIconFillShare(finest)} />\n </button>\n </Tooltip>\n {open && (\n <div\n className={styles.panel}\n role=\"dialog\"\n aria-label={t('quota.panel')}\n style={{\n width: `${String(panelWidth)}px`,\n ...(panelLeft === undefined ? {} : { left: `${String(panelLeft)}px` }),\n }}\n >\n <div className={styles.header}>\n <span className={styles.title}>\n {payload.providerName ?? payload.provider}\n {payload.status === 'ok' && payload.planTier !== undefined\n ? <span className={styles.plan}> · {payload.planTier}</span>\n : null}\n </span>\n <span className={styles.updated}>\n {t('quota.updatedAt', { time: formatQuotaClock(payload.fetchedAt) })}\n </span>\n </div>\n {payload.status === 'error'\n ? (\n <div className={styles.error}>\n <span className={styles.errorText}>{errorText(payload.error, t)}</span>\n <button type=\"button\" className={styles.retry} onClick={retry}>\n {t('quota.retry')}\n </button>\n </div>\n )\n : (\n <div\n className={styles.grid}\n style={{ '--cols': String(Math.min(payload.windows.length, 3)) } as CSSProperties}\n >\n {payload.windows.map((window, index) =>\n <QuotaColumn key={`${window.tier}:${String(index)}`} window={window} t={t} />)}\n </div>\n )}\n </div>\n )}\n </span>\n )\n}\n\n/** Ring geometry matches ContextMeter: 14px viewBox, r 5.5, 2px stroke.\n * Circumference feeds the remaining-share dasharray, starting at 12\n * o'clock. A 0 share omits the fill stroke — a round cap at 0 would still\n * paint a dot. */\nconst RING_R = 5.5\nconst RING_C = 2 * Math.PI * RING_R\n/** Round caps paint half a stroke width beyond each dash end; their\n * combined reach is what the dash compensation subtracts, so the painted\n * arc (dash + caps) equals the nominal share and the caps cannot seal the\n * 12-o'clock gap. */\nconst RING_CAP_REACH = 2\n\n/** The trigger glyph: a ContextMeter-family donut whose fill arc is the\n * remaining share of the finest window. Color comes from the button's\n * severity class (`currentColor`); this only draws the arc. */\nfunction QuotaGlyph({ share }: { share: number }): ReactNode {\n const clamped = Math.min(1, Math.max(0, share))\n // Cap compensation: round caps extend the painted arc by RING_CAP_REACH,\n // which sealed any gap under ~5.8% of the ring (a 1% gap rendered\n // pixel-identical to a full one). Shortening the dash keeps the gap open\n // at the ring's rims — any nonzero usage stays visible — while the\n // centerline gap stays linear in the remaining share. A full share keeps\n // the entire circumference (compensated caps would only touch at one\n // point, leaving a rim notch that reads as ~98%); an arc no longer than\n // the cap reach skips the compensation (a dash ≤ 0 paints nothing and\n // would drop the nub).\n const nominal = clamped * RING_C\n const dashLen = clamped >= 1 ? RING_C\n : nominal <= RING_CAP_REACH ? nominal\n : nominal - RING_CAP_REACH\n return (\n <svg viewBox=\"0 0 14 14\" width=\"14\" height=\"14\" aria-hidden=\"true\">\n <circle cx=\"7\" cy=\"7\" r={RING_R} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" opacity=\"0.22\" />\n {clamped > 0\n ? (\n <circle\n cx=\"7\"\n cy=\"7\"\n r={RING_R}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap={clamped < 1 ? 'round' : 'butt'}\n strokeDasharray={`${dashLen.toFixed(3)} ${RING_C.toFixed(3)}`}\n transform=\"rotate(-90 7 7)\"\n />\n )\n : null}\n </svg>\n )\n}\n\n/** One progress column: label / value / bar / aux. The value and the bar\n * both carry the REMAINING share (the traffic-light standard reads what is\n * left), colored by severity. */\nfunction QuotaColumn({ window, t }: { window: QuotaWindow; t: QuotaButtonProps['t'] }): ReactNode {\n const remaining = quotaRemainingPercent(window)\n const severity: QuotaSeverity = quotaSeverityOf(window)\n const label = t(TIER_LABEL_KEYS[window.tier])\n\n // Balance windows lead with the amount (the figure the user manages\n // against); ratio windows with the remaining share. The `meta` suffix\n // carries the balance's total.\n let value: string\n let meta: string | undefined\n if (window.tier === 'balance' && window.remainingValue !== undefined) {\n const unit = window.unit ?? 'cny'\n value = formatQuotaMoney(window.remainingValue, unit)\n if (window.maxValue !== undefined) meta = `/ ${formatQuotaMoney(window.maxValue, unit)}`\n } else {\n value = remaining !== undefined ? formatQuotaPercent(remaining) : '—'\n }\n const aux = window.resetAt !== undefined\n ? t('quota.resetIn', { time: formatResetCountdown(window.resetAt, Date.now()) })\n : undefined\n\n return (\n <div className={styles.col}>\n <div className={styles.label}>{label}</div>\n <div className={styles.value}>\n {value}\n {meta !== undefined ? <span className={styles.meta}> {meta}</span> : null}\n </div>\n {remaining !== undefined && (\n <div className={styles.bar}>\n <div\n className={`${styles.fill} ${styles[severity]}`}\n style={{ width: `${String(Math.round(remaining))}%` }}\n />\n </div>\n )}\n {aux !== undefined && (\n <div className={styles.aux}>\n <span className={`${styles.dot} ${styles[severity]}`} />\n {aux}\n </div>\n )}\n </div>\n )\n}\n\n/** The panel's width tier for one payload: what the windows PAINT decides —\n * a lone amount (no computable bar, the DeepSeek shape) reads at the\n * minimal plate, one bar (a weekly-only plan, or a balance with a spend\n * total like OpenRouter) the middle one, two or more bars the full plate.\n * Errors and payloads without windows read the full plate (their copy\n * runs long). */\nfunction panelWidthOf(payload: QuotaPayload | null): number {\n if (payload === null || payload.status !== 'ok') return PANEL_WIDTH_FULL\n const bars = payload.windows.filter(window => quotaUsedPercent(window) !== undefined).length\n if (bars === 0) return payload.windows.length > 0 ? PANEL_WIDTH_BALANCE : PANEL_WIDTH_FULL\n return bars === 1 ? PANEL_WIDTH_SINGLE : PANEL_WIDTH_FULL\n}\n\n/** Friendly locale copy for one normalized query error. */\nfunction errorText(error: QuotaError, t: QuotaButtonProps['t']): string {\n switch (error.kind) {\n case 'auth':\n return t('quota.error.auth', { message: error.message })\n case 'no-credential':\n return t('quota.error.noCredential', { ref: error.message })\n case 'http':\n return t('quota.error.http', { message: error.message })\n case 'network':\n return t('quota.error.network', { message: error.message })\n case 'parse':\n return t('quota.error.parse', { message: error.message })\n }\n}\n\n/** Defensive shape check: a misrouted response must not paint the button. */\nfunction looksLikeQuotaPayload(value: unknown): value is QuotaPayload {\n return typeof value === 'object' && value !== null\n && typeof (value as { status?: unknown }).status === 'string'\n && typeof (value as { intervalSec?: unknown }).intervalSec === 'number'\n}\n\n/**\n * Fetch the quota payload for the active session, naming the chip-selected\n * provider when one is known. Throws on transport failure or a payload that\n * does not look like one, so the hook can keep the previous render\n * (silentAfterFirst) or stay hidden (first failure).\n */\nasync function fetchQuotaPayload(sessionId: string, provider: string | undefined, signal: AbortSignal): Promise<QuotaPayload | null> {\n const params = new URLSearchParams()\n if (sessionId !== '') params.set('session', sessionId)\n if (provider !== undefined && provider !== '') params.set('provider', provider)\n const encoded = params.toString()\n const query = encoded === '' ? '' : `?${encoded}`\n const response = await fetch(QUOTA_PATH + query, {\n headers: { accept: 'application/json' },\n signal,\n })\n if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)\n const value: unknown = await response.json()\n if (!looksLikeQuotaPayload(value)) throw new Error('unexpected quota response')\n return value\n}\n","/**\n * Browser-side day vocabulary of the token-usage settings page: local day\n * keys, quick-range arithmetic, and the zero-filled per-day series backing\n * the trend chart. Pure functions only, so the chart and its tests share one\n * implementation.\n *\n * @module token-usage/client/day\n */\n\nimport type { UsageDayRow, UsageHourRow, UsageTotals } from '../wire.ts'\n\n/** Total tokens across the four buckets (billed input = input + cacheRead + cacheWrite). */\nexport function totalTokens(totals: UsageTotals): number {\n return totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens\n}\n\n/** Local `YYYY-MM-DD` key of a date, matching the host's day-file convention. */\nexport function dayKeyOf(date: Date): string {\n const month = String(date.getMonth() + 1).padStart(2, '0')\n const day = String(date.getDate()).padStart(2, '0')\n return `${date.getFullYear()}-${month}-${day}`\n}\n\n/** Local day key of today shifted by whole days (test seam on `now`). */\nexport function shiftedDayKey(deltaDays: number, now: () => Date = () => new Date()): string {\n const date = now()\n date.setDate(date.getDate() + deltaDays)\n return dayKeyOf(date)\n}\n\n/** One plotted day of the trend chart. */\nexport interface DayPoint {\n day: string\n tokens: number\n}\n\n/**\n * The zero-filled daily token series over a day range: every calendar day of\n * the range appears once (days without records plot as zero). Absent bounds\n * fall back to the first/last row day; no rows and no range yield [].\n * @param rows - the (already filtered) per-day rows.\n * @param from - first day key, inclusive.\n * @param to - last day key, inclusive.\n */\nexport function daySeries(rows: readonly UsageDayRow[], from?: string, to?: string): DayPoint[] {\n const first = from ?? rows[0]?.day\n const last = to ?? (rows.length > 0 ? rows[rows.length - 1]!.day : undefined)\n if (first === undefined || last === undefined || first > last) return []\n const tokens = new Map(rows.map(row => [row.day, totalTokens(row.totals)]))\n const points: DayPoint[] = []\n const cursor = new Date(`${first}T00:00:00`)\n const end = new Date(`${last}T00:00:00`)\n while (cursor <= end) {\n const day = dayKeyOf(cursor)\n points.push({ day, tokens: tokens.get(day) ?? 0 })\n cursor.setDate(cursor.getDate() + 1)\n }\n return points\n}\n\n/** One plotted hour of the single-day trend chart. */\nexport interface HourPoint {\n hour: string\n tokens: number\n}\n\n/** Local `YYYY-MM-DDTHH` key of a date, matching the host's hour convention. */\nexport function hourKeyOf(date: Date): string {\n const hour = String(date.getHours()).padStart(2, '0')\n return `${dayKeyOf(date)}T${hour}`\n}\n\n/**\n * The zero-filled hourly token series over a day range: every whole hour of\n * the range appears once (hours without records plot as zero), so a single\n * day yields the full 00:00–23:00 sequence and future hours of today read\n * zero. The per-(hour, model) rows fold by hour. Absent bounds fall back to\n * the first/last row hour; no rows and no range yield [].\n * @param rows - the (already filtered) per-hour × per-model rows.\n * @param from - first day key (`YYYY-MM-DD`), inclusive; the series starts\n * at that day's 00:00.\n * @param to - last day key, inclusive; the series ends at that day's 23:00.\n */\nexport function hourSeries(rows: readonly UsageHourRow[], from?: string, to?: string): HourPoint[] {\n const first = from !== undefined ? `${from}T00` : rows[0]?.hour\n const last = to !== undefined ? `${to}T23` : rows.length > 0 ? rows[rows.length - 1]!.hour : undefined\n if (first === undefined || last === undefined || first > last) return []\n const tokens = new Map<string, number>()\n for (const row of rows) {\n tokens.set(row.hour, (tokens.get(row.hour) ?? 0) + totalTokens(row.totals))\n }\n const points: HourPoint[] = []\n const cursor = new Date(`${first.slice(0, 10)}T${first.slice(11)}:00:00`)\n const end = new Date(`${last.slice(0, 10)}T${last.slice(11)}:00:00`)\n while (cursor <= end) {\n const hour = hourKeyOf(cursor)\n points.push({ hour, tokens: tokens.get(hour) ?? 0 })\n cursor.setHours(cursor.getHours() + 1)\n }\n return points\n}\n","/**\n * Browser-side display formatting of the token-usage settings page: token\n * abbreviation (K/M/B), the cache hit rate, and the cost/rate figures of the\n * pricing layer (wire amounts are RMB; the currency view converts them to\n * the region-picked display currency, ¥ or $). Pure functions only, shared\n * by the section and the trend chart.\n *\n * @module token-usage/client/format\n */\n\nimport type { UsageSummary, UsageTotals } from '../wire.ts'\n\n/** One decimal below 10, integer otherwise, trailing `.0` stripped. */\nfunction scale(value: number): string {\n if (value >= 10) return String(Math.round(value))\n const oneDecimal = value.toFixed(1)\n return oneDecimal.endsWith('.0') ? oneDecimal.slice(0, -2) : oneDecimal\n}\n\n/**\n * Abbreviate a token count: raw below 1K, `xxK` below 1M, `xxM` below 10 亿\n * (1e9) — 1 亿 is `100M`, 2.5 亿 is `250M`, 9.5 亿 is `950M` — and `xxB`\n * only from 10 亿 up (B = 10 亿, no fractional-B tier): `1B`, `1.5B`, `3B`.\n * One decimal while the scaled value is below 10, integer otherwise —\n * `950K`, `1.5M`, `950M`, `3B`.\n * @param count - a non-negative token count.\n * @returns the compact display string.\n */\nexport function formatTokens(count: number): string {\n if (count < 1_000) return String(count)\n if (count < 1_000_000) return scale(count / 1_000) + 'K'\n if (count < 1_000_000_000) return scale(count / 1_000_000) + 'M'\n return scale(count / 1_000_000_000) + 'B'\n}\n\n/** Always one decimal (stripped when `.0`), unlike {@link scale}: percentages keep their precision. */\nfunction percent(value: number): string {\n const oneDecimal = value.toFixed(1)\n return oneDecimal.endsWith('.0') ? oneDecimal.slice(0, -2) : oneDecimal\n}\n\n/**\n * Cache hit rate as display text: cache reads over served input\n * (missed input + cache reads). `—` when nothing was served.\n * @param totals - the aggregated totals.\n * @returns e.g. `87.5%`, or `—` for an empty denominator.\n */\nexport function formatHitRate(totals: UsageTotals): string {\n return hitRateDisplay(totals).text\n}\n\n/**\n * The threshold bucket the chip color picks from. Four levels (worst →\n * best) along one warm→cool traffic-light arc:\n * <60% `critical` (red)\n * 60–80% `amber` (orange-yellow — \"needs attention\")\n * 80–95% `lime` (yellow-green — \"almost there\")\n * ≥95% `healthy` (green)\n *\n * Violet/teal were tried earlier to dodge the cost cell's warn accent,\n * but they sit on opposite sides of the hue wheel so the middle two\n * stops never read as a progression. Cost figures are now uncolored,\n * so the classic red→amber→lime→green scale is free again.\n *\n * The empty-denominator path lands in `amber` so a brand-new session\n * neither alarms (`critical`) nor celebrates (`healthy`).\n */\nexport type HitRateBand = 'critical' | 'amber' | 'lime' | 'healthy'\n\n/** Hit-rate thresholds (inclusive lower bound, exclusive upper). Boundary\n * values sit in the higher tier: 0.60 is `amber`, 0.80 is `lime`, 0.95\n * is `healthy`. The numbers are guideposts, not hard cutoffs — a 78%\n * cache hit rate is still in `amber`, exactly because cache misses at\n * ~1/5 of requests is worth flagging. */\nconst HIT_RATE_AMBER = 0.60\nconst HIT_RATE_LIME = 0.80\nconst HIT_RATE_HEALTHY = 0.95\n\n/** Map a 0-1 fraction to one of the four chip color buckets. */\nexport function bandOf(hitRate: number): HitRateBand {\n if (hitRate >= HIT_RATE_HEALTHY) return 'healthy'\n if (hitRate >= HIT_RATE_LIME) return 'lime'\n if (hitRate >= HIT_RATE_AMBER) return 'amber'\n return 'critical'\n}\n\n/** Cache hit rate broken out into a display shape: the text the user sees\n * plus the color bucket the UI maps onto it. Sessions with no served input\n * read `—` in the `amber` bucket so a fresh session never paints cold. */\nexport interface HitRateDisplay {\n text: string\n band: HitRateBand\n}\n\n/**\n * Compute the cache hit rate's display shape in one pass.\n * @param totals - the aggregated totals.\n * @returns `{ text, band }` — `text` is `—` for an empty denominator,\n * `band` defaults to `amber` so an unused session reads as a mild\n * \"no signal yet\" (neither alarming nor celebratory).\n */\nexport function hitRateDisplay(totals: UsageTotals): HitRateDisplay {\n const served = totals.inputTokens + totals.cacheReadTokens\n if (served === 0) return { text: '—', band: 'amber' }\n const rate = totals.cacheReadTokens / served\n return {\n text: `${percent(rate * 100)}%`,\n band: bandOf(rate),\n }\n}\n\n/**\n * How cost figures render: the symbol plus, for USD, the RMB-per-USD\n * divisor every wire amount (always RMB) divides by for display.\n */\nexport interface CurrencyView {\n symbol: '¥' | '$'\n /** RMB per USD; 1 in the CNY view (amounts pass through untouched). */\n rate: number\n}\n\n/** The RMB display view: amounts render as stored. */\nconst CNY_VIEW: CurrencyView = { symbol: '¥', rate: 1 }\n\n/**\n * The display view of one stats summary: USD when the region pick says so\n * (amounts ÷ `usdExchangeRate`, `$` prefix), else RMB as stored.\n * @param summary - the stats payload (its `currency`/`usdExchangeRate` fields).\n * @returns the view the format functions render through.\n */\nexport function currencyViewOf(summary: Pick<UsageSummary, 'currency' | 'usdExchangeRate'>): CurrencyView {\n return summary.currency === 'USD' ? { symbol: '$', rate: summary.usdExchangeRate } : CNY_VIEW\n}\n\n/**\n * Cost as display text: the view's symbol plus two decimals, following the\n * analyzer's cost formatting (`¥1.25`, `$0.18`). A cost is always shown,\n * never omitted. USD divides the wire's RMB amount by the exchange rate.\n * @param cost - a non-negative cost in ¥ (as carried on the wire).\n * @param view - the display currency view.\n * @returns e.g. `¥1.25`, or `$0.18` under a rate-7 USD view.\n */\nexport function formatCost(cost: number, view: CurrencyView = CNY_VIEW): string {\n return `${view.symbol}${(cost / view.rate).toFixed(2)}`\n}\n\n/**\n * A per-million-token rate as display text, converted through the view:\n * integral rates stay bare (`8`, `$1.14`-style conversion applied first for\n * USD), fractional ones keep up to four decimals with trailing zeros\n * stripped and a two-decimal minimum (`0.50`, `0.25`, `0.025`). The caller\n * appends the `/M` unit and the view's symbol where needed.\n * @param rate - a non-negative rate in ¥ per million tokens.\n * @param view - the display currency view.\n * @returns the display string (symbol-less, converted for USD).\n */\nexport function formatRate(rate: number, view: CurrencyView = CNY_VIEW): string {\n const converted = rate / view.rate\n if (Number.isInteger(converted)) return String(converted)\n let s = converted.toFixed(4)\n const dot = s.indexOf('.')\n s = s.replace(/0+$/u, '')\n if (s.endsWith('.')) s += '00'\n const minEnd = dot + 3\n while (s.length < minEnd) s += '0'\n return s\n}\n\n/**\n * A per-million-token rate as complete display text: the view's symbol plus\n * {@link formatRate}'s converted number — what the pricing table cells render.\n * @param rate - a non-negative rate in ¥ per million tokens.\n * @param view - the display currency view.\n * @returns e.g. `¥8`, or `$1.1429` under a rate-7 USD view.\n */\nexport function formatRateWithSymbol(rate: number, view: CurrencyView = CNY_VIEW): string {\n return `${view.symbol}${formatRate(rate, view)}`\n}\n\n/**\n * Average first-token latency in the shell's compact duration shape:\n * one decimal under a minute (`45.2s`), `2m42s` from there on.\n * @param ms - total first-token latency.\n * @returns the display string.\n */\nexport function formatTtft(ms: number): string {\n const s = ms / 1000\n if (s < 60) return `${String(Math.round(s * 10) / 10)}s`\n const whole = Math.round(s)\n return `${Math.floor(whole / 60)}m${whole % 60}s`\n}\n\n/**\n * Decode-throughput display figure in the shell's shape: whole tokens from\n * ten up, one decimal below (the `tok/s` unit lives in the locale template).\n * @param tokensPerSecond - tokens per second.\n * @returns the display number.\n */\nexport function formatSpeed(tokensPerSecond: number): string {\n const clamped = Math.max(0, tokensPerSecond)\n return clamped >= 10 ? String(Math.round(clamped)) : String(Math.round(clamped * 10) / 10)\n}\n","/**\n * Coloured cache-hit-rate figure: the same four-bucket mapping the\n * session-header chip uses (`format.hitRateDisplay`), so every surface\n * that shows a hit rate — the chip, the Usage-tab / settings stat\n * cards, the per-model and subagent tables — paints one gradient.\n *\n * @module token-usage/client/HitRateText\n */\n\nimport type { ReactNode } from 'react'\nimport type { UsageTotals } from '../wire.ts'\nimport { hitRateDisplay, type HitRateBand } from './format.ts'\nimport bands from './hit-rate-band.module.css'\n\n/** CSS-module class for one hit-rate colour bucket. */\nexport function bandClassOf(band: HitRateBand): string {\n return bands[`band_${band}`] ?? ''\n}\n\n/**\n * Render a hit-rate percentage (or `—`) in its threshold colour.\n * @param totals - the aggregated token buckets the rate is computed from.\n */\nexport function HitRateText({ totals }: { totals: UsageTotals }): ReactNode {\n const { text, band } = hitRateDisplay(totals)\n return <span className={bandClassOf(band)}>{text}</span>\n}\n","/**\n * Pure session-scope helpers of the conversation view tab (browser half):\n * subagent-tree traversal over the runtime's session-list mirror\n * (parentId + origin), the whole-subtree projection aggregation for TTFT\n * and decode throughput, and the parent lookup the back control uses.\n * No runtime imports beyond types, so the view tab and its tests share one\n * implementation.\n *\n * @module token-usage/client/session-stats\n */\n\nimport type { SessionStatsProjection } from '@deepseek-ai/dsh-session-stats/client'\n\n/** The session-summary shape this module reads (a structural slice of the\n * runtime's `SessionSummary` — parent linkage, origin, and the retained\n * host-projection values). */\nexport interface SessionRowLike {\n parentId?: string | undefined\n origin?: 'subagent' | undefined\n updatedAt?: number | undefined\n projectionValues?: Readonly<Partial<{ sessionStats?: SessionStatsProjection }>> | undefined\n}\n\n/** The session-summary map this module reads (keyed by session id). */\nexport type SessionRows = Readonly<Record<string, SessionRowLike>>\n\n/** A parent → direct-subagent-children index, one O(n) build over {@link\n * SessionRows}. An absent key means \"no subagent children under that id\";\n * an ordinary fork does not contribute to its parent. */\nexport type ChildIndex = ReadonlyMap<string, readonly string[]>\n\n/** Build a session-parent → direct-subagent-children index in one O(n) pass:\n * every session whose `origin === 'subagent'` lands in its `parentId`'s\n * bucket, in iteration order (so the result matches {@link directSubagentIds}).\n * @param rows - the retained session-summary mirror.\n * @returns the immutable child index.\n */\nexport function buildChildIndex(rows: SessionRows): ChildIndex {\n const index = new Map<string, string[]>()\n for (const [id, summary] of Object.entries(rows)) {\n if (summary.origin !== 'subagent' || summary.parentId === undefined) continue\n const bucket = index.get(summary.parentId)\n if (bucket === undefined) index.set(summary.parentId, [id])\n else bucket.push(id)\n }\n return index\n}\n\n/** Look up the direct subagent children of one session. Falls back to a\n * fresh {@link buildChildIndex} when the caller has no cached index. */\nexport function directSubagentIds(\n rows: SessionRows,\n parentId: string,\n index?: ChildIndex,\n): readonly string[] {\n if (index !== undefined) return index.get(parentId) ?? []\n return buildChildIndex(rows).get(parentId) ?? []\n}\n\n/**\n * The whole subagent subtree of one session, including the root itself,\n * using the parent → children index for an O(n) walk regardless of depth.\n * Cycles are bounded by a `seen` set (a depth-first traversal visits each\n * id once), so a self-referential or cyclic record set returns the root\n * alone. Stacks are reversed after pushing so siblings come back out in\n * insertion order, matching the runtime's lineage index.\n * @param rows - the retained session-summary mirror (unused when the\n * caller already built an index).\n * @param rootId - the scope's root session id.\n * @param index - optional precomputed index from {@link buildChildIndex}.\n * @returns the root and its subagent descendants, depth-first.\n */\nexport function subtreeIds(\n rows: SessionRows,\n rootId: string,\n index: ChildIndex = buildChildIndex(rows),\n): string[] {\n const out: string[] = [rootId]\n if (!index.has(rootId) && rows[rootId] === undefined) return out\n const seen = new Set<string>([rootId])\n const stack: string[] = []\n const seedChildren = index.get(rootId) ?? []\n for (let i = seedChildren.length - 1; i >= 0; i -= 1) stack.push(seedChildren[i]!)\n while (stack.length > 0) {\n const current = stack.pop()!\n if (seen.has(current)) continue\n seen.add(current)\n out.push(current)\n const children = index.get(current) ?? []\n for (let i = children.length - 1; i >= 0; i -= 1) stack.push(children[i]!)\n }\n return out\n}\n\n/**\n * The immediate subagent parent of one session, when the record names one.\n * The check is on `parentId` rather than `origin` so a mirrored summary that\n * lost its origin tag still answers its lineage — the index is built once\n * per render and shared across all three helpers via {@link ChildIndex}.\n * @param rows - the retained session-summary mirror.\n * @param id - the current focus session id.\n * @returns the parent session id, or undefined when the record has no\n * parent link (a top-level session or an ordinary fork).\n */\nexport function subagentParentOf(rows: SessionRows, id: string): string | undefined {\n const parent = rows[id]?.parentId\n return parent === undefined || parent === id ? undefined : parent\n}\n\n/** The session-stats fold the view renders (summed wall-time buckets). */\nexport interface StatsAggregate {\n /** Summed first-token latency over `ttftSteps`. */\n ttftMs: number\n /** Steps carrying a recorded first token. */\n ttftSteps: number\n /** Summed decode wall time (first token → message) over decode-timed steps. */\n decodeMs: number\n /** Summed provider output tokens over the same decode-timed steps. */\n decodeTokens: number\n /** Number of scoped sessions that contributed a `sessionStats` projection\n * value; the rest had no retained projection. Lets the view distinguish\n * \"scope had no recorded projections\" from \"scope is empty\". */\n contributing: number\n}\n\n/**\n * Sum one or more `SessionStatsProjection` values over a scope. A scope with\n * no value at all yields `undefined` — the view renders an em-dash for an\n * absent capability. The `contributing` count lets the caller tell\n * \"every scope session was empty\" apart from \"the scope itself was empty\".\n * @param values - the per-session projection values (typically drawn from\n * the mirror + the live hook).\n * @returns the summed buckets plus the contributing count, or undefined\n * when no projection was present.\n */\nexport function aggregateProjections(\n values: Iterable<SessionStatsProjection | undefined>,\n): StatsAggregate | undefined {\n let ttftMs = 0\n let ttftSteps = 0\n let decodeMs = 0\n let decodeTokens = 0\n let contributing = 0\n for (const stats of values) {\n if (stats === undefined) continue\n contributing += 1\n ttftMs += stats.ttftMs\n ttftSteps += stats.ttftSteps\n decodeMs += stats.decodeMs\n decodeTokens += stats.decodeTokens\n }\n if (contributing === 0) return undefined\n return { ttftMs, ttftSteps, decodeMs, decodeTokens, contributing }\n}\n\n/**\n * Compact fingerprint of one session's retained stats projection — bumps on\n * every finished request step (same signal that drives TTFT / throughput).\n */\nexport function sessionStatsFingerprint(stats: SessionStatsProjection | undefined): string {\n if (stats === undefined) return '-'\n return [\n stats.steps,\n stats.ttftSteps,\n stats.decodeTokens,\n stats.turns,\n ].join('.')\n}\n\n/**\n * Build a debounce key from mirror `updatedAt` plus `sessionStats` churn.\n * The active session reads live projection values from `useProjection`; every\n * other scoped id reads the mirror copy.\n */\nexport function buildStatsFreshnessKey(\n ids: readonly string[],\n options: {\n activeSessionId: string\n rows: SessionRows\n liveSessionStats?: SessionStatsProjection | undefined\n },\n): string {\n return ids.map(id => {\n const row = options.rows[id]\n const stats = id === options.activeSessionId\n ? options.liveSessionStats ?? row?.projectionValues?.sessionStats\n : row?.projectionValues?.sessionStats\n return `${id}:${String(row?.updatedAt ?? 0)}:${sessionStatsFingerprint(stats)}`\n }).join(',')\n}\n","/**\n * Imperative cost-cell motion (Web Animations API). Avoids CSS `@keyframes`\n * + custom-property bugs in some embedded hosts; runs on the actual DOM node.\n *\n * @module token-usage/client/cost-inflate-motion\n */\n\nimport type { CostInflateVars } from './cost-inflate.ts'\n\n/** The user's motion preference: both runners refuse to animate (returning\n * null) when the OS asks for reduced motion. Exported so the chip hook can\n * skip spawning the DOM for flies that would never animate — a static +Δ\n * flash reads as a glitch, not information. */\nexport function motionAllowed(): boolean {\n return typeof window.matchMedia !== 'function'\n || !window.matchMedia('(prefers-reduced-motion: reduce)').matches\n}\n\nfunction waapiAvailable(el: HTMLElement): boolean {\n return typeof el.animate === 'function'\n}\n\n/** Scale bounce on the cost figure (`costPop`). */\nexport function runCostPop(el: HTMLElement, v: CostInflateVars): Animation | null {\n if (!motionAllowed() || !waapiAvailable(el)) return null\n const popScale = Number(v.popScale)\n const echo = 1 + (popScale - 1) * 0.28\n const warnMix = v.warnMix\n return el.animate([\n { transform: 'scale(1)', color: 'var(--dsw-alias-label-primary)' },\n {\n transform: `scale(${String(popScale)})`,\n color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-primary))`,\n offset: 0.35,\n },\n {\n transform: `scale(${String(echo)})`,\n color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-primary))`,\n offset: 0.70,\n },\n { transform: 'scale(1)', color: 'var(--dsw-alias-label-primary)' },\n ], {\n duration: v.inflateMs,\n easing: 'cubic-bezier(0.25, 0.85, 0.35, 1)',\n fill: 'both',\n })\n}\n\n/** +Δ label rise (`deltaRise`). Caller must position the element (absolute). */\nexport function runDeltaFly(el: HTMLElement, v: CostInflateVars): Animation | null {\n if (!motionAllowed() || !waapiAvailable(el)) return null\n return el.animate([\n { opacity: 0, transform: 'translate(-50%, -20%)' },\n { opacity: 1, transform: 'translate(-50%, -20%)', offset: 0.15 },\n {\n opacity: 0,\n transform: `translate(calc(-50% + ${v.flyX}), calc(-100% - ${v.flyY}))`,\n },\n ], {\n duration: v.inflateMs,\n easing: 'cubic-bezier(0.22, 0.55, 0.25, 1)',\n fill: 'both',\n })\n}\n","import { useLayoutEffect, useRef } from 'react'\nimport type { ReactNode } from 'react'\nimport { runDeltaFly } from './cost-inflate-motion.ts'\nimport type { CostInflateVars } from './cost-inflate.ts'\nimport styles from './SessionStatsChip.module.css'\n\n/** One +Δ fly label; animation starts on mount via WAAPI. */\nexport function CostDeltaFlyLabel({ text, vars }: { text: string; vars: CostInflateVars }): ReactNode {\n const ref = useRef<HTMLSpanElement>(null)\n\n useLayoutEffect(() => {\n const el = ref.current\n if (el === null) return\n const anim = runDeltaFly(el, vars)\n if (anim === null) {\n // Motion is allowed but this host has no WAAPI: without the animation\n // the label would sit statically for the whole inflate window — hide\n // it and let the number update be the only signal.\n el.style.visibility = 'hidden'\n return\n }\n return () => { anim.cancel() }\n }, [vars])\n\n return (\n <span ref={ref} className={styles['deltaFly']}>\n {text}\n </span>\n )\n}\n","/**\n * SessionStatsChip cost-cell inflate animation: per-request intensity from\n * token deltas and parameters for `costPop` / `deltaRise`. Pure functions\n * only — the chip hook owns timers and DOM.\n *\n * @module token-usage/client/cost-inflate\n */\n\nimport type { UsageTotals } from '../wire.ts'\n\nconst MISS_RATE_CAP = 0.55\nconst OUT_CAP = 32_000\n\n/** Clamp to the unit interval. */\nexport function clamp01(n: number): number {\n return Math.max(0, Math.min(1, n))\n}\n\n/** Token totals of one refresh minus the previous snapshot (non-negative). */\nexport function deltaTotals(prev: UsageTotals, next: UsageTotals): UsageTotals {\n return {\n requests: Math.max(0, next.requests - prev.requests),\n inputTokens: Math.max(0, next.inputTokens - prev.inputTokens),\n outputTokens: Math.max(0, next.outputTokens - prev.outputTokens),\n cacheReadTokens: Math.max(0, next.cacheReadTokens - prev.cacheReadTokens),\n cacheWriteTokens: Math.max(0, next.cacheWriteTokens - prev.cacheWriteTokens),\n }\n}\n\n/**\n * Single-step intensity from the latest request's token delta (not session\n * cumulative hit rate): `I = clamp01(0.55·norm(miss) + 0.45·norm(output))`.\n */\nexport function computeIntensityFromDelta(delta: UsageTotals): number {\n const served = delta.inputTokens + delta.cacheReadTokens\n const hitRate = served > 0 ? delta.cacheReadTokens / served : 0.5\n const miss = clamp01((1 - hitRate) / MISS_RATE_CAP)\n const out = clamp01(delta.outputTokens / OUT_CAP)\n return clamp01(0.55 * miss + 0.45 * out)\n}\n\n/** Parameters driving `costPop` and `deltaRise` for one request step. */\nexport interface CostInflateVars {\n inflateMs: number\n popScale: string\n warnMix: string\n flyY: string\n flyX: string\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t\n}\n\n/** Map step intensity I to animation parameters. */\nexport function animVars(I: number): CostInflateVars {\n const inflateMs = Math.round(lerp(1000, 1800, I))\n return {\n inflateMs,\n popScale: lerp(1.08, 1.32, I).toFixed(3),\n warnMix: `${Math.round(lerp(0, 55, I))}%`,\n flyY: `${lerp(22, 38, I).toFixed(1)}px`,\n flyX: `${((Math.random() - 0.5) * 10).toFixed(1)}px`,\n }\n}\n","/**\n * Request-driven cost-cell inflate animation for SessionStatsChip: detects\n * new usage from summary deltas and drives WAAPI motion on the cost figure\n * and ephemeral +Δ fly labels.\n *\n * @module token-usage/client/use-cost-inflate\n */\n\nimport { useCallback, useEffect, useRef, useState, type RefObject } from 'react'\nimport type { UsageSummary } from '../wire.ts'\nimport { currencyViewOf } from './format.ts'\nimport { totalTokens } from './day.ts'\nimport { motionAllowed, runCostPop } from './cost-inflate-motion.ts'\nimport {\n animVars,\n computeIntensityFromDelta,\n deltaTotals,\n type CostInflateVars,\n} from './cost-inflate.ts'\n\n/** One +Δ label mid-flight. */\nexport interface CostDeltaFly {\n id: number\n text: string\n vars: CostInflateVars\n}\n\ninterface PrevChipSnapshot {\n totals: UsageSummary['total']\n totalCost: number\n}\n\nexport interface UseCostInflateResult {\n /** Active +Δ fly labels (removed after their animation). */\n flies: readonly CostDeltaFly[]\n /** Strip gets `overflow: visible` while a fly or pop may extend outside. */\n flyOverflow: boolean\n /** Call when a fresh chip summary lands (after first paint baseline). */\n onSummary: (summary: UsageSummary) => void\n /** Clear baseline and in-flight flies (session / scope change). */\n reset: () => void\n}\n\nconst MIN_WIRE_DELTA_COST = 0.000_5\n\nfunction hasUsageChurn(prev: PrevChipSnapshot, summary: UsageSummary): boolean {\n const delta = deltaTotals(prev.totals, summary.total)\n if (delta.requests > 0) return true\n if (summary.totalCost - prev.totalCost > MIN_WIRE_DELTA_COST) return true\n return totalTokens(delta) > 0\n}\n\n/**\n * Hook the chip uses to play costPop + deltaRise on each new request.\n * @param scopeKey - changes reset the diff baseline.\n * @param costRef - the live cost figure span (WAAPI target).\n */\nexport function useCostInflate(\n scopeKey: string,\n costRef: RefObject<HTMLElement | null>,\n): UseCostInflateResult {\n const prevRef = useRef<PrevChipSnapshot | null>(null)\n const flyIdRef = useRef(0)\n const timersRef = useRef<number[]>([])\n const flyCountRef = useRef(0)\n const popAnimRef = useRef<Animation | null>(null)\n\n const [flies, setFlies] = useState<CostDeltaFly[]>([])\n const [flyOverflow, setFlyOverflow] = useState(false)\n\n const clearTimers = useCallback(() => {\n for (const id of timersRef.current) window.clearTimeout(id)\n timersRef.current = []\n }, [])\n\n const schedule = useCallback((fn: () => void, ms: number) => {\n const id = window.setTimeout(fn, ms)\n timersRef.current.push(id)\n }, [])\n\n const reset = useCallback(() => {\n clearTimers()\n popAnimRef.current?.cancel()\n popAnimRef.current = null\n prevRef.current = null\n flyIdRef.current = 0\n flyCountRef.current = 0\n setFlies([])\n setFlyOverflow(false)\n }, [clearTimers])\n\n useEffect(() => {\n reset()\n }, [scopeKey, reset])\n\n useEffect(() => () => { clearTimers() }, [clearTimers])\n\n const maybeClearOverflow = useCallback(() => {\n if (flyCountRef.current <= 0) setFlyOverflow(false)\n }, [])\n\n const playCostPop = useCallback((v: CostInflateVars) => {\n const el = costRef.current\n if (el === null) return\n popAnimRef.current?.cancel()\n popAnimRef.current = runCostPop(el, v)\n }, [costRef])\n\n const onSummary = useCallback((summary: UsageSummary) => {\n const nextSnapshot: PrevChipSnapshot = {\n totals: summary.total,\n totalCost: summary.totalCost,\n }\n const prev = prevRef.current\n prevRef.current = nextSnapshot\n if (prev === null) return\n if (!hasUsageChurn(prev, summary)) return\n // Reduced motion: the baseline is already stored above, so the figures\n // repaint silently — no pop, no fly, no overflow churn.\n if (!motionAllowed()) return\n\n const delta = deltaTotals(prev.totals, summary.total)\n const I = computeIntensityFromDelta(delta)\n const v = animVars(I)\n\n setFlyOverflow(true)\n window.requestAnimationFrame(() => { playCostPop(v) })\n\n const wireDeltaCost = summary.totalCost - prev.totalCost\n if (wireDeltaCost > MIN_WIRE_DELTA_COST) {\n const view = currencyViewOf(summary)\n const text = `+${view.symbol}${(wireDeltaCost / view.rate).toFixed(2)}`\n const id = ++flyIdRef.current\n flyCountRef.current += 1\n setFlies(current => [...current, { id, text, vars: v }])\n schedule(() => {\n flyCountRef.current -= 1\n setFlies(current => current.filter(fly => fly.id !== id))\n maybeClearOverflow()\n }, v.inflateMs + 40)\n } else {\n schedule(maybeClearOverflow, v.inflateMs + 40)\n }\n }, [maybeClearOverflow, playCostPop, schedule])\n\n return { flies, flyOverflow, onSummary, reset }\n}\n","/**\n * Session-header stats chip (browser half): a one-line compact strip rendered\n * into the `conversation.session.header.utilities` slot — three sub-chips\n * (total tokens / cache hit rate / session cost) beside the Session log\n * button. Data comes from `/token-usage/stats?fields=chip` scoped to the\n * active session and its subagent subtree (the Usage tab's \"with\n * subagents\" range), so a parent that spawned children shows the same\n * folded numbers the header is meant to summarise. Numbers refresh at\n * REQUEST granularity (same cadence as the Usage tab): `sessionStats`\n * projection churn (plus mirror `updatedAt` when present) is debounced\n * into one fetch, so idle sessions do not poll and a finished request\n * updates the header within ~250 ms. When cost\n * rises on a new request, the cost cell plays `costPop` (scale bounce) and\n * `deltaRise` (+Δ fly); reduced-motion users get silent figure updates\n * instead. A failed FIRST fetch retries itself on a 3 s cadence — the old\n * poll's safety net — so an idle-but-used session still gets its chip.\n *\n * Visibility contract: a session with no recorded requests renders nothing\n * (an empty header strip is worse than no strip; the chip never blanks to\n * \"—\"). Hit-rate colour is the four-bucket mapping in `format.hitRateDisplay`:\n * ≥95% healthy (green), 80–95% lime, 60–80% amber, below 60% critical (red).\n * Amber/lime fill the warm→cool gap so the four stops read as one progression.\n *\n * @module token-usage/client/SessionStatsChip\n */\n\nimport { useEffect, useMemo, useRef } from 'react'\nimport type { ReactNode } from 'react'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: merges SessionStandardProps / GlobalStandardProps (`sessionId`,\n// `useSessions`, `useProjection`) into the header-utilities runtime kit.\nimport type {} from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: merges the sessionStats key into SessionProjectionMap.\nimport type {} from '@deepseek-ai/dsh-session-stats/client'\n// Type-only: pulls the `conversation.session.header.utilities` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { UsageSummary } from '../wire.ts'\nimport { encodeStatsQuery, STATS_PATH } from '../wire.ts'\nimport { useAsyncResource, useDebouncedValue } from './async-resource.ts'\nimport { totalTokens } from './day.ts'\nimport { currencyViewOf, formatCost, formatTokens, hitRateDisplay } from './format.ts'\nimport { HitRateText } from './HitRateText.tsx'\nimport { buildChildIndex, buildStatsFreshnessKey, subtreeIds } from './session-stats.ts'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport { CostDeltaFlyLabel } from './CostDeltaFlyLabel.tsx'\nimport { useCostInflate } from './use-cost-inflate.ts'\nimport styles from './SessionStatsChip.module.css'\n\n/** Refresh debounce: bursts of session-mirror updates (one request's events)\n * collapse into a single fetch, matching the Usage tab's request-scale\n * cadence instead of a steady poll. */\nconst REFRESH_DEBOUNCE_MS = 250\n\n/** Self-heal cadence after a failed first fetch. With the poll gone, this\n * retry is the only thing that recovers an idle session's chip: refresh\n * failures after the first land keep the prior figures (silent mode) and\n * self-heal on the next request churn, so they never reach the error state. */\nexport const FETCH_FAILURE_RETRY_MS = 3_000\n\n/** Props the chip binds for the conversation-session header utilities slot:\n * the framework's session kit (`sessionId` + the global `useSessions`\n * mirror used to walk the subagent tree) plus the locale seat from the\n * registration's `locale:` declaration. */\nexport type SessionStatsChipProps =\n PropsRuntime<'conversation.session.header.utilities'>\n & PropsLocale<'token-usage'>\n\n/**\n * Render the session-header stats chip for the active session. Renders\n * nothing when the session has no recorded usage, when the fetch fails, or\n * while the first fetch is in flight — the spec's \"data has no value, the\n * block does not render\" rule.\n * @param props - framework session id, the session-list mirror, and the locale seat.\n * @returns the chip strip, or null when the data is empty/unavailable.\n */\nexport function SessionStatsChip({ sessionId, useSessions, useProjection, t }: SessionStatsChipProps): ReactNode | null {\n const rootRef = useRef<HTMLDivElement>(null)\n const costRef = useRef<HTMLSpanElement>(null)\n useColorSchemeMirror(rootRef)\n const byId = useSessions(state => state.byId)\n const childIndex = useMemo(() => buildChildIndex(byId), [byId])\n // Same membership as the Usage tab's \"with subagents\" scope: the active\n // session plus every origin=subagent descendant. An ordinary fork is not\n // a subagent and does not join the fold.\n const scopeIds = useMemo(\n () => (sessionId === '' ? [] : subtreeIds(byId, sessionId, childIndex)),\n [byId, sessionId, childIndex],\n )\n const liveStats = useProjection('sessionStats')\n // Debounce on scope membership + sessionStats churn (and updatedAt when\n // present). sessionStats bumps every finished request; updatedAt alone\n // does not — same fix as the Usage tab's token/cost refresh.\n const freshnessKey = buildStatsFreshnessKey(scopeIds, {\n activeSessionId: sessionId,\n rows: byId,\n liveSessionStats: liveStats,\n })\n const requestKey = `${scopeIds.join('\\n')}\\n\\t${freshnessKey}`\n const debouncedKey = useDebouncedValue(requestKey, REFRESH_DEBOUNCE_MS)\n const scopeResetKey = scopeIds.join('\\n')\n const {\n flies,\n flyOverflow,\n onSummary,\n } = useCostInflate(scopeResetKey, costRef)\n const [resource, retry] = useAsyncResource<UsageSummary | null>(\n signal => {\n const [idsPart] = debouncedKey.split('\\n\\t')\n const sessionIds = (idsPart ?? '').split('\\n').filter(id => id !== '')\n return fetchSessionSummary(sessionIds, signal)\n },\n [debouncedKey],\n { silentAfterFirst: true, retryToken: 0 },\n )\n\n // The spec's empty rule: a session with no fetched summary, with zero\n // requests, or still on the first attempt renders nothing.\n const summary = resource.status === 'ready' ? resource.value : null\n\n useEffect(() => {\n if (summary !== null) onSummary(summary)\n }, [summary, onSummary])\n\n // A failed first fetch renders nothing and, unlike the old poll, no later\n // tick re-triggers it — schedule the resource hook's retry until data\n // lands. Keyed on the resource object: each fresh error reschedules.\n useEffect(() => {\n if (resource.status !== 'error') return\n const timer = window.setTimeout(retry, FETCH_FAILURE_RETRY_MS)\n return () => { window.clearTimeout(timer) }\n }, [resource, retry])\n\n if (summary === null || summary.total.requests === 0) return null\n\n const view = currencyViewOf(summary)\n const { total } = summary\n const tokensText = formatTokens(totalTokens(total))\n const hitText = hitRateDisplay(total).text\n const costText = formatCost(summary.totalCost, view)\n\n return (\n <div\n ref={rootRef}\n className={`${styles['strip']}${flyOverflow ? ` ${styles['stripFlyOverflow']}` : ''}`}\n role=\"group\"\n aria-label={t('view.usage')}\n >\n <span\n className={styles['cell']}\n aria-label={t('chip.tokens', { value: tokensText })}\n >\n {tokensText}\n </span>\n {/* Hit-rate colour lives on an INNER span (`HitRateText`), not on the\n cell itself: `.cell` sets `color: label-primary`, and after the\n band classes moved into a shared CSS module the cell rule can\n land later in the bundle and override a same-element band class.\n Nesting keeps the bucket colour winning the same way the Usage /\n settings cards do. */}\n <span\n className={`${styles['cell']} ${styles['cellHit']}`}\n aria-label={t('chip.hitRate', { value: hitText })}\n >\n <HitRateText totals={total} />\n </span>\n <span\n className={`${styles['cell']} ${styles['costCell']}`}\n aria-label={t('chip.cost', { value: costText })}\n >\n <span ref={costRef} className={styles['costInner']}>\n {costText}\n </span>\n <span className={styles['deltaLayer']} aria-hidden=\"true\">\n {flies.map(fly => (\n <CostDeltaFlyLabel key={fly.id} text={fly.text} vars={fly.vars} />\n ))}\n </span>\n </span>\n </div>\n )\n}\n\n/** Defensive shape check: an older host build or a misrouted response\n * would otherwise paint the header chip with garbage. */\nfunction looksLikeUsageSummary(value: unknown): value is UsageSummary {\n return typeof value === 'object' && value !== null\n && typeof (value as { total?: unknown }).total === 'object'\n && (value as { total?: unknown }).total !== null\n}\n\n/**\n * Fetch the summary scoped to one session and its subagent subtree. Throws\n * on transport failure (network, abort, non-2xx response, or a payload\n * that doesn't look like a stats summary) so the hook can keep the\n * previous render in place — a transient miss never blanks the chip. The\n * hook's `silentAfterFirst` flag is what suppresses the resulting error\n * state.\n * @param sessionIds - the active session plus its subagent descendants;\n * an empty list skips the fetch (returning null rather than throwing, so\n * the hook's first-load gate stays at \"loading\").\n * @param signal - the cancellation signal from the hook.\n */\nasync function fetchSessionSummary(\n sessionIds: readonly string[],\n signal: AbortSignal,\n): Promise<UsageSummary | null> {\n if (sessionIds.length === 0) return null\n const response = await fetch(STATS_PATH + encodeStatsQuery({ sessionIds, fields: 'chip' }), {\n headers: { accept: 'application/json' },\n signal,\n })\n if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)\n const value: unknown = await response.json()\n if (!looksLikeUsageSummary(value)) throw new Error('unexpected stats response')\n return value\n}\n","/**\n * The token-usage card on the Plugins configuration tab: a collapsible row\n * whose header names the plugin over a one-line description of what its\n * settings govern, disclosing the data-directory control and the mirror\n * region pick (`domestic` gitee / `overseas` github) when open. The card owns\n * everything inside it — chrome, controls, and copy — per the keyed-slot\n * contract; the tab only dispatches it under the `token-usage` namespace key.\n *\n * Renders nothing while the namespace is unavailable: a deployment that did\n * not compose the host half shows no trace of the card. A region change takes\n * effect live (the host re-syncs the pricing mirror); a directory change the\n * guard refuses while conversations run shows the wait-for-them notice on the\n * failure line, and one that lands migrates the data across under a live\n * progress bar that locks the controls until it settles.\n *\n * @module token-usage/client/TokenUsageCard\n */\n\nimport { useCallback, useEffect, useState } from 'react'\nimport { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { CardActions, CardStore } from './card-form.ts'\nimport { FULL_SYNC_PATH, type FullSyncView } from '../wire.ts'\nimport css from './TokenUsageCard.module.css'\n\n/** Props the renderer binds for the token-usage settings card. */\nexport type TokenUsageCardProps =\n PropsRuntime<'settings.plugin.item'>\n & PropsLocale<'token-usage'>\n & InjectFace<TokenUsageCardFace>\n\n/** The registration-side face this card's slot entry injects. */\nexport interface TokenUsageCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as useTokenUsageCard. */\n tokenUsageCard: CardStore\n }\n /**\n * The shell's native directory picker (the workspace flows' chooser):\n * resolves the chosen absolute path, or null when the user dismisses the\n * dialog.\n */\n pickDirectory: () => Promise<string | null>\n}\n\n/**\n * Render the token-usage settings card.\n * @param props - locale copy, the card snapshot, and its form actions.\n * @returns the card, or nothing when the namespace is unavailable.\n */\nexport function TokenUsageCard(props: TokenUsageCardProps) {\n const [open, setOpen] = useState(false)\n const [picking, setPicking] = useState(false)\n const { t } = props\n const state = props.useTokenUsageCard(snapshot => snapshot)\n if (!state.available) return null\n const migrating = state.migration !== undefined\n const lockInput = !state.writable || migrating\n const lockActions = !state.dirty || state.saving || migrating\n\n /**\n * Open the shell's native folder dialog and stage the chosen path — the\n * same picker the workspace flows use, driven through the injected\n * workspace service. A dismissal leaves the staged draft exactly as it\n * was; the text input stays the fallback either way.\n */\n const browse = async (): Promise<void> => {\n if (picking || lockInput) return\n setPicking(true)\n try {\n const picked = await props.pickDirectory()\n if (picked !== null && picked !== '') props.editField('path', picked)\n } catch (_pickFailure) {\n // Leave the draft untouched; typing the path remains available.\n } finally {\n setPicking(false)\n }\n }\n\n // Manual full-sync state, polled from the host route while a scan runs.\n // The default `idle` matches the host's default; a card opening with a\n // terminal `done` / `failed` keeps it on screen until the next click.\n const [fullSync, setFullSync] = useState<FullSyncView>({ status: 'idle' })\n const fullSyncRunning = fullSync.status === 'running'\n\n /**\n * Fetch the current full-sync status from the host. A transport failure\n * keeps the previous view (a transient miss never blanks the bar).\n */\n const fetchFullSync = useCallback(async (): Promise<FullSyncView | null> => {\n try {\n const response = await fetch(FULL_SYNC_PATH, { headers: { accept: 'application/json' } })\n if (!response.ok) return null\n const body = (await response.json()) as FullSyncView\n // Trust nothing that does not match the typed shape — a host running an\n // older build may answer a different status set.\n if (body.status === 'idle') return { status: 'idle' }\n if (body.status === 'running' || body.status === 'done') {\n if (typeof body.processed === 'number' && typeof body.total === 'number'\n && typeof body.added === 'number' && typeof body.skipped === 'number') {\n return { status: body.status, processed: body.processed, total: body.total, added: body.added, skipped: body.skipped }\n }\n return null\n }\n if (body.status === 'failed' && typeof body.error === 'string') {\n return { status: 'failed', error: body.error }\n }\n return null\n } catch (_pollFailure) {\n return null\n }\n }, [])\n\n // Poll while a scan is in flight; the route answers 200 + status, and the\n // poll tears itself down the moment the status leaves `running`.\n useEffect(() => {\n if (!fullSyncRunning) return\n let cancelled = false\n const tick = async (): Promise<void> => {\n const next = await fetchFullSync()\n if (cancelled || next === null) return\n setFullSync(next)\n }\n void tick()\n const timer = setInterval(() => { void tick() }, 300)\n return () => { cancelled = true; clearInterval(timer) }\n }, [fullSyncRunning, fetchFullSync])\n\n /**\n * Kick off one full scan. The button shows the request as soon as the\n * POST returns 202; the polling effect above then drives the bar until\n * the host settles into `done` or `failed`. A 409 (already running) is\n * a no-op — the polling will already see the running state.\n */\n const startFullSync = useCallback(async (): Promise<void> => {\n try {\n const response = await fetch(FULL_SYNC_PATH, { method: 'POST' })\n if (response.status === 202) {\n setFullSync({ status: 'running', processed: 0, total: 0, added: 0, skipped: 0 })\n return\n }\n if (response.status === 409) {\n // A scan is already running on the host; the next poll will pick it\n // up. The button is disabled while running, so this branch only\n // fires on a race the host already accepted.\n const next = await fetchFullSync()\n if (next !== null) setFullSync(next)\n }\n } catch (_triggerFailure) {\n // The next open of the section re-tries; a transient POST failure\n // does not need its own error line.\n }\n }, [fetchFullSync])\n\n return (\n <li className={open ? `${css.card} ${css.cardOpen}` : css.card}>\n <button\n type=\"button\"\n className={css.header}\n aria-expanded={open}\n aria-label={`${t(open ? 'card.collapse' : 'card.expand')}: ${t('card.title')}`}\n onClick={() => { setOpen(!open) }}\n >\n <span className={css.headText}>\n <span className={css.name}>{t('card.title')}</span>\n <span className={css.description}>{t('card.description')}</span>\n </span>\n {state.dirty ? <span className={css.pending}>{t('card.unsaved')}</span> : null}\n <IconChevronDownOutline14 className={open ? `${css.chevron} ${css.chevronOpen}` : css.chevron} />\n </button>\n {open\n ? (\n <div className={css.body}>\n {!state.writable ? <p className={css.note} role=\"status\">{t('card.readOnly')}</p> : null}\n <label className={css.field} htmlFor=\"token-usage-card-path\">\n <span className={css.fieldLabel}>{t('card.pathLabel')}</span>\n <span className={css.inputRow}>\n <input\n id=\"token-usage-card-path\"\n className={css.input}\n type=\"text\"\n spellCheck={false}\n value={state.fields.path}\n disabled={lockInput}\n onChange={event => { props.editField('path', event.target.value) }}\n />\n <button\n type=\"button\"\n className={css.browse}\n disabled={lockInput || picking}\n onClick={() => { void browse() }}\n >\n {t(picking ? 'card.picking' : 'card.browse')}\n </button>\n </span>\n </label>\n <p className={css.hint}>{t('card.pathHint')}</p>\n <label className={css.field} htmlFor=\"token-usage-card-region\">\n <span className={css.fieldLabel}>{t('card.regionLabel')}</span>\n <select\n id=\"token-usage-card-region\"\n className={css.input}\n value={state.fields.pricingRegion}\n disabled={lockInput}\n onChange={event => { props.editField('pricingRegion', event.target.value) }}\n >\n <option value=\"\">{t('card.regionDefault')}</option>\n <option value=\"domestic\">{t('card.region.domestic')}</option>\n <option value=\"overseas\">{t('card.region.overseas')}</option>\n </select>\n </label>\n <p className={css.hint}>\n {t('card.hint')}\n {state.overridden.pricingRegion ? ` ${t('card.overridden')}` : ''}\n </p>\n {state.migration !== undefined\n ? (\n <div className={css.migration} role=\"status\">\n <span className={css.migrationLabel}>\n {t(state.migration.phase === 'copying' ? 'card.migratingCopy' : 'card.migratingClean')\n .replace('{done}', String(state.migration.done))\n .replace('{total}', String(state.migration.total))}\n </span>\n <span className={css.migrationBar}>\n <span\n className={css.migrationFill}\n style={{ width: `${String(Math.round((state.migration.done / Math.max(state.migration.total, 1)) * 100))}%` }}\n />\n </span>\n </div>\n )\n : null}\n <div className={css.fullSync}>\n <div className={css.fullSyncHeader}>\n <span className={css.fullSyncTitle}>{t('card.fullSync.title')}</span>\n <span className={css.fullSyncHint}>{t('card.fullSync.hint')}</span>\n </div>\n <button\n type=\"button\"\n className={css.fullSyncButton}\n disabled={fullSyncRunning}\n onClick={() => { void startFullSync() }}\n >\n {t(fullSyncRunning ? 'card.fullSync.running' : 'card.fullSync.button')}\n </button>\n {fullSync.status === 'running'\n ? (\n <div className={css.fullSyncProgress} role=\"status\">\n <span className={css.fullSyncProgressLabel}>\n {t('card.fullSync.progress', {\n processed: String(fullSync.processed),\n total: String(fullSync.total),\n added: String(fullSync.added),\n skipped: String(fullSync.skipped),\n })}\n </span>\n <span className={css.fullSyncBar}>\n <span\n className={css.fullSyncFill}\n style={{ width: `${String(Math.round((fullSync.processed / Math.max(fullSync.total, 1)) * 100))}%` }}\n />\n </span>\n </div>\n )\n : null}\n {fullSync.status === 'done'\n ? (\n <p className={css.fullSyncResult} role=\"status\">\n {t('card.fullSync.done', {\n added: String(fullSync.added),\n skipped: String(fullSync.skipped),\n })}\n </p>\n )\n : null}\n {fullSync.status === 'failed'\n ? (\n <p className={css.fullSyncError} role=\"status\">\n {t('card.fullSync.failed', { error: fullSync.error })}\n </p>\n )\n : null}\n </div>\n <div className={css.footer}>\n {state.failed\n ? (\n <p className={css.failed} role=\"status\">\n {state.refusal !== undefined\n ? t('card.saveBlockedSessions').replace('{count}', String(state.refusal.interactingSessions))\n : t('card.saveFailed')}\n </p>\n )\n : null}\n <button\n type=\"button\"\n className={css.discard}\n disabled={lockActions}\n onClick={props.discard}\n >\n {t('card.discard')}\n </button>\n <button\n type=\"button\"\n className={css.save}\n disabled={lockActions}\n onClick={props.save}\n >\n {t(state.saving ? 'card.saving' : 'card.save')}\n </button>\n </div>\n </div>\n )\n : null}\n </li>\n )\n}\n","/**\n * Shared \"stat card\" primitive: label on top, value underneath. Used by the\n * settings section (four primary cards + four token-bucket cards) and the\n * Usage view tab (six cards: requests / cost / total tokens / hit rate /\n * TTFT / token speed). Centralising the markup + styling means the two\n * surfaces read as one family without each one carrying its own copy of the\n * label-on-top / value-below rule.\n *\n * @module token-usage/client/StatCard\n */\n\nimport type { ReactNode } from 'react'\nimport styles from './StatCard.module.css'\n\n/** One labelled figure inside a card. */\nexport interface StatCardProps {\n /** The small secondary line (\"token cost\", \"hit rate\", \"总 token\"). */\n label: string\n /** The bold tabular-numeric value (`1.5M`, `¥12.34`, `0.5s`). A\n * node is accepted so the hit-rate card can wrap {@link HitRateText}\n * and inherit the four-bucket colour without a second card variant. */\n value: ReactNode\n}\n\n/**\n * Render one stat card. The value uses the standard label-primary color.\n * The label clamps to one line and ellipsizes if the column is squeezed.\n */\nexport function StatCard({ label, value }: StatCardProps): ReactNode {\n return (\n <div className={styles['card']}>\n <span className={styles['cardLabel']}>{label}</span>\n <span className={styles['cardValue']}>{value}</span>\n </div>\n )\n}\n","/**\n * Trend-chart axis helpers: the roundest step from 1/2/2.5/5 × 10ⁿ not\n * below a rough target, and the y-axis tick values (one nice step apart,\n * inclusive of the chart top). Pure functions, no React, no I/O.\n *\n * @module token-usage/client/trend-chart/axis\n */\n\n/**\n * The roundest step from {1, 2, 2.5, 5, 10} × 10ⁿ not below `rough`.\n * A `niceStep(0)` returns 1; a `niceStep(80)` returns 100 (the next nice\n * step above 80 in the same decade).\n * @param rough - the target value (positive).\n * @returns the nice step.\n */\nexport function niceStep(rough: number): number {\n const base = 10 ** Math.floor(Math.log10(rough))\n const fraction = rough / base\n const nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 2.5 ? 2.5 : fraction <= 5 ? 5 : 10\n return nice * base\n}\n\n/** The y-axis tick values from one step up to the chart top (inclusive). */\nexport function tickValues(max: number): { top: number; ticks: number[] } {\n if (max === 0) return { top: 1, ticks: [] }\n const step = niceStep(max / 4)\n const top = Math.ceil(max / step) * step\n const ticks: number[] = []\n for (let value = step; value < top; value += step) ticks.push(value)\n ticks.push(top)\n return { top, ticks }\n}\n","/**\n * Request-series time bucketing shared by the host stats route (wire\n * downsample) and the conversation-view chart. Pure functions, no React,\n * no I/O — the client bundle can inline this module.\n *\n * @module token-usage/trend-bucket\n */\n\nimport type { RequestPoint } from './wire.ts'\n\n/** One time bucket of the request-mode trend: requests folded by time span. */\nexport interface TrendBucket {\n /** Bucket start, wall time. */\n start: number\n /** Bucket end (exclusive). */\n end: number\n /** Summed token totals of the requests inside the bucket. */\n tokens: number\n /** Requests folded into the bucket. */\n count: number\n}\n\n/**\n * Bucket widths tried from fine to coarse (ms); the first whose bucket count\n * stays at or under {@link MAX_BUCKETS} wins, so a short session gets\n * fine-grained 5-second buckets and a multi-day session one per several\n * hours — always within the render cap.\n */\nconst BUCKET_STEPS_MS = [\n 5_000, 15_000, 60_000, 300_000, 900_000,\n 3_600_000, 10_800_000, 21_600_000, 43_200_000, 86_400_000,\n] as const\n\n/** Render / wire cap: the request trend never draws more points than this. */\nexport const MAX_BUCKETS = 60\n\n/** The bucket width for one span: the finest step whose count fits the cap. */\nexport function bucketWidth(spanMs: number): number {\n for (const step of BUCKET_STEPS_MS) {\n if (Math.ceil(spanMs / step) <= MAX_BUCKETS) return step\n }\n // Beyond the coarsest step (multi-month sessions): keep the cap by\n // aligning a custom width up to the next whole hour.\n return Math.ceil(spanMs / MAX_BUCKETS / 3_600_000) * 3_600_000\n}\n\n/**\n * Fold a request series into uniformly sized time buckets spanning the\n * series' own first-to-last window. The axis starts at the series' first\n * record, ends at its latest, and the middle is evenly divided — the chart\n * shows the trend over TIME, not one point per request. Buckets align to\n * the window's first record, not to wall-clock round hours.\n *\n * Implementation note: the buckets are tracked in a `Map` keyed by their\n * 0-based index, not in a sparse array. A multi-month session could\n * otherwise blow past V8's sparse-array bounds (the indices approach\n * `spanMs / 5_000` which is unbounded); the Map collapses absent keys\n * cleanly.\n *\n * @param requests - the per-request series, time-ascending.\n * @returns the buckets in time order (empty for an empty series; only\n * buckets holding at least one request are emitted).\n */\nexport function bucketSeries(requests: readonly RequestPoint[]): TrendBucket[] {\n if (requests.length === 0) return []\n const first = requests[0]!.time\n const last = requests[requests.length - 1]!.time\n const width = bucketWidth(Math.max(last - first, 1))\n const buckets = new Map<number, TrendBucket>()\n for (const request of requests) {\n const index = Math.floor((request.time - first) / width)\n const existing = buckets.get(index)\n if (existing === undefined) {\n buckets.set(index, {\n start: first + index * width,\n end: first + (index + 1) * width,\n tokens: request.tokens,\n count: 1,\n })\n } else {\n existing.tokens += request.tokens\n existing.count += 1\n }\n }\n return [...buckets.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, bucket]) => bucket)\n}\n\n/**\n * Project buckets back onto the wire {@link RequestPoint} shape: `time` is\n * the bucket start, `end` / `count` mark a pre-bucketed point so the chart\n * can plot it without folding again.\n */\nexport function pointsOfBuckets(buckets: readonly TrendBucket[]): RequestPoint[] {\n return buckets.map(bucket => ({\n time: bucket.start,\n end: bucket.end,\n tokens: bucket.tokens,\n count: bucket.count,\n }))\n}\n","/**\n * Trend-chart bucket folding and temporal x scaling (browser half).\n * Folding lives in the shared `trend-bucket` module so the host route can\n * downsample the request series onto the wire; this file re-exports it and\n * keeps the SVG-only `scaleToSpan`.\n *\n * @module token-usage/client/trend-chart/bucket\n */\n\nexport { MAX_BUCKETS, bucketSeries, bucketWidth, pointsOfBuckets } from '../../trend-bucket.ts'\nexport type { TrendBucket } from '../../trend-bucket.ts'\n\n/**\n * Scale one wall time into an x offset across the series' actual span —\n * the first and last points pin the axis ends, and everything in between\n * lands at its real proportion of that span (a 55-request session\n * spreads across the full width, a burst inside one minute bunches up).\n * @param firstTime - the series' first record time.\n * @param lastTime - the series' last record time.\n * @param time - the record's wall time.\n * @param innerWidth - the plottable width in pixels.\n * @returns the x offset from the left edge; the center when every record\n * shares one timestamp (a zero span cannot scale).\n */\nexport function scaleToSpan(firstTime: number, lastTime: number, time: number, innerWidth: number): number {\n const span = lastTime - firstTime\n if (span <= 0) return innerWidth / 2\n return (time - firstTime) / span * innerWidth\n}\n","/**\n * Trend-chart point series: fold the three render-mode inputs (per-day\n * rows, per-hour rows, per-request series) into one discriminated-union\n * series with the mode decided at the top. Pure functions, no React.\n *\n * @module token-usage/client/trend-chart/points\n */\n\nimport type { RequestPoint, UsageDayRow, UsageHourRow } from '../../wire.ts'\nimport { daySeries, hourSeries } from '../day.ts'\nimport type { DayPoint, HourPoint } from '../day.ts'\nimport { bucketSeries } from './bucket.ts'\nimport type { TrendBucket } from './bucket.ts'\n\n/**\n * The chart series, normalised over the three render modes. Equidistant\n * modes (days, hours) advance `index` one step per point; temporal mode\n * (request buckets) attaches the wall time so the renderer scales each\n * point at its real temporal proportion of the span.\n */\nexport type ChartSeries =\n | { mode: 'equidistant'; points: { key: string; label: string; full: string; tokens: number }[] }\n | { mode: 'temporal'; points: { key: string; label: string; full: string; tokens: number; time: number; count: number }[] }\n\ninterface BuildPointsInput {\n rows: readonly UsageDayRow[]\n hours?: readonly UsageHourRow[] | undefined\n requests?: readonly RequestPoint[] | undefined\n from?: string | undefined\n to?: string | undefined\n}\n\n/** Render-mode priority: request buckets outrank per-hour, which\n * outranks per-day. A session-scoped read passes `requests`; the settings\n * page passes `hours` for a single-day range; everything else plots days. */\nexport function buildChartPoints(input: BuildPointsInput): ChartSeries | null {\n if (input.requests !== undefined && input.requests.length > 0) {\n const buckets = bucketsOf(input.requests)\n if (buckets.length > 0) {\n const firstDate = new Date(buckets[0]!.start).toDateString()\n const lastDate = new Date(buckets[buckets.length - 1]!.start).toDateString()\n const crossDay = firstDate !== lastDate\n return {\n mode: 'temporal',\n points: buckets.map((bucket, index) => ({\n key: `b${index}`,\n label: bucketLabel(bucket.start, crossDay),\n full: `${bucketLabel(bucket.start, crossDay)}–${bucketLabel(bucket.end, crossDay)}`,\n tokens: bucket.tokens,\n time: bucket.start,\n count: bucket.count,\n })),\n }\n }\n }\n if (input.hours !== undefined) {\n const points = hourSeries(input.hours, input.from, input.to)\n if (points.length > 0) {\n return { mode: 'equidistant', points: points.map(hourToPoint) }\n }\n }\n const points = daySeries(input.rows, input.from, input.to)\n if (points.length > 0) {\n return { mode: 'equidistant', points: points.map(dayToPoint) }\n }\n return null\n}\n\n/** A series that already carries `count` (the host's `fields=session`\n * downsample) is plotted as-is; a raw per-request series is folded here. */\nfunction bucketsOf(requests: readonly RequestPoint[]): TrendBucket[] {\n if (requests[0]?.count !== undefined) {\n return requests.map(point => ({\n start: point.time,\n end: point.end ?? point.time,\n tokens: point.tokens,\n count: point.count ?? 1,\n }))\n }\n return bucketSeries(requests)\n}\n\nfunction dayToPoint(point: DayPoint): { key: string; label: string; full: string; tokens: number } {\n return { key: point.day, label: point.day.slice(5), full: point.day, tokens: point.tokens }\n}\n\nfunction hourToPoint(point: HourPoint): { key: string; label: string; full: string; tokens: number } {\n return {\n key: point.hour,\n label: `${point.hour.slice(11)}:00`,\n full: `${point.hour.slice(0, 10)} ${point.hour.slice(11)}:00`,\n tokens: point.tokens,\n }\n}\n\n/** Zero-padded HH:mm of one wall time, local-time. */\nfunction clockOf(time: number): string {\n const d = new Date(time)\n return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`\n}\n\n/** The x-axis label of one bucket start: HH:mm within one day,\n * MM-DD HH:mm once the session crosses midnight. */\nfunction bucketLabel(time: number, crossDay: boolean): string {\n if (!crossDay) return clockOf(time)\n const d = new Date(time)\n return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${clockOf(time)}`\n}\n","/**\n * Trend-chart x scaling: pick the right scale for a series mode and\n * return the per-point offsets in one pass. Pure functions, no React.\n *\n * @module token-usage/client/trend-chart/scale\n */\n\nimport type { ChartSeries } from './points.ts'\nimport { scaleToSpan } from './bucket.ts'\n\n/** A scale decision plus the per-point x offsets, expressed as **absolute\n * SVG viewBox coordinates** (already offset by `leftEdge`). Returning\n * absolute coords prevents the \"renderer forgot to add `LEFT`\" bug that\n * shows up as a line hugging the very-left edge of the chart area. */\nexport interface ScaleResult {\n /** The x offset of every point in SVG viewBox coordinates (range\n * `[leftEdge, rightEdge]`). */\n xs: number[]\n /** The plottable width (rightEdge − leftEdge); the renderer can use it\n * for hit-target extents and label clamps. */\n innerWidth: number\n}\n\n/**\n * Pick the right x scale for a {@link ChartSeries} and produce the\n * per-point offsets in absolute viewBox coordinates. Equidistant modes\n * lay points one stride apart across the `[leftEdge, rightEdge]` span;\n * temporal mode uses each point's wall time against the series' own\n * first-to-last span and adds `leftEdge` to the result. Single-point\n * series pin to the centerline of the span (a zero stride would not\n * scale, and temporal scale would divide by zero).\n *\n * @param series - the discriminated-union series from {@link buildChartPoints}.\n * @param leftEdge - the absolute SVG x of the chart's left edge (the\n * y-axis line in the renderer).\n * @param rightEdge - the absolute SVG x of the chart's right edge\n * (typically `viewBox.width − RIGHT.margin`).\n * @returns the per-point x offsets plus `innerWidth = rightEdge − leftEdge`.\n */\nexport function scaleSeries(series: ChartSeries, leftEdge: number, rightEdge: number): ScaleResult {\n const innerWidth = rightEdge - leftEdge\n const { points } = series\n if (series.mode === 'equidistant') {\n const xs: number[] = []\n if (points.length === 1) {\n xs.push((leftEdge + rightEdge) / 2)\n } else {\n const stride = innerWidth / (points.length - 1)\n for (let i = 0; i < points.length; i += 1) xs.push(leftEdge + i * stride)\n }\n return { xs, innerWidth }\n }\n // Temporal: each point's wall time scaled into the first-to-last span,\n // then anchored to the chart's left edge.\n const temporal = points as { time: number; key: string }[]\n const first = temporal[0]!.time\n const last = temporal[temporal.length - 1]!.time\n const xs: number[] = []\n if (temporal.length === 1 || first === last) {\n xs.push((leftEdge + rightEdge) / 2)\n } else {\n for (const point of temporal) xs.push(leftEdge + scaleToSpan(first, last, point.time, innerWidth))\n }\n return { xs, innerWidth }\n}\n\n/**\n * The x-axis label positions: first, middle, and last point for long\n * ranges. Short ranges (≤3 points) label every point so a 1- or 2- day\n * window does not skip the only \"middle\" data.\n */\nexport function labelIndices(length: number): number[] {\n if (length <= 3) return Array.from({ length }, (_, index) => index)\n const middle = Math.floor((length - 1) / 2)\n return [...new Set([0, middle, length - 1])]\n}\n\n/** Choose a dot radius that survives dense point clouds without\n * overlapping but stays visible for sparse ones. Three tiers, picked by\n * point count. */\nexport function dotRadius(pointCount: number): number {\n if (pointCount > 90) return 1.5\n if (pointCount > 30) return 2\n return 3\n}\n","/**\n * Daily / hourly / request-bucketed token trend chart (browser half):\n * a dependency-free SVG line chart over the already-filtered summary.\n * The renderer is pure presentation; the bucketing, scaling, and\n * point-shape decisions live in `./trend-chart/*` so each piece can be\n * tested in isolation.\n *\n * Two granularities share one renderer — per-day rows (x axis spans\n * every calendar day of the active range, days without records plot as\n * zero) and per-hour rows (a single-day window plots every whole hour of\n * that day, 00:00–23:00, future hours of today reading zero). The\n * third mode — request buckets — folds the request series into uniformly\n * sized time buckets spanning the session's actual first-to-last window\n * and scales each bucket at its real temporal proportion of the span.\n *\n * Hovering (or keyboard-focusing) a point highlights it and floats a\n * label with that point's date/time and total tokens.\n *\n * @module token-usage/client/TrendChart\n */\n\nimport { useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { RequestPoint, UsageDayRow, UsageHourRow } from '../wire.ts'\nimport { formatTokens } from './format.ts'\nimport { tickValues } from './trend-chart/axis.ts'\nimport { buildChartPoints } from './trend-chart/points.ts'\nimport { dotRadius, labelIndices, scaleSeries } from './trend-chart/scale.ts'\nimport styles from './TrendChart.module.css'\n\n/** Re-export the chart's pure helpers for the test suite. */\nexport {\n MAX_BUCKETS, bucketSeries, bucketWidth, buildChartPoints, dotRadius, labelIndices,\n niceStep, scaleSeries, scaleToSpan, tickValues,\n} from './trend-chart/index.ts'\nexport type { TrendBucket } from './trend-chart/bucket.ts'\nexport type { ChartSeries, ScaleResult } from './trend-chart/index.ts'\n\n/** SVG canvas metrics; the element scales to the section width via viewBox. */\nconst WIDTH = 800\nconst HEIGHT = 190\nconst TOP = 12\nconst BOTTOM = 16\nconst LEFT = 44\nconst RIGHT = 16\nconst X_LABELS = 22\nconst HIT_TARGET_FLOOR = 6\n\n/**\n * One plotted point and the i18n strings the renderer needs. `time` is\n * required on temporal-series points (carried here so the renderer's\n * `tip` function doesn't need to thread back into the series).\n */\ninterface PlottedPoint {\n key: string\n label: string\n /** Pre-shape phase: request-mode `full` is the bucket window (`HH:mm–HH:mm`);\n * hour/day mode is the point's date/hour label. The renderer localises. */\n full: string\n tokens: number\n /** Wall time of the bucket start (request mode only). */\n time?: number | undefined\n /** Requests folded into this bucket (request mode only). */\n count?: number | undefined\n}\n\n/**\n * Apply the `t`-based localisation to a point's `full` tooltip. The pre-shape\n * labels live in points.ts; the chart's aria-label and the floating tooltip\n * both use this single source so the two stay consistent.\n * @param t - the locale seat.\n * @param point - the pre-shaped point.\n * @returns the tooltip / aria-label text.\n */\nfunction tipOf(t: TranslateNS<'token-usage'>, point: PlottedPoint): string {\n if (point.time !== undefined) {\n return t('chart.bucket', {\n window: point.full,\n count: String(point.count ?? 0),\n tokens: formatTokens(point.tokens),\n })\n }\n return t('chart.pointLabel', { day: point.full, tokens: formatTokens(point.tokens) })\n}\n\n/**\n * Render the daily / hourly / request-bucketed token line chart. Pure\n * presentation: every data-driven decision (bucketing, axis scaling,\n * point ordering) lives in `./trend-chart/*`; this component picks the\n * right `chartAria` string for screen readers and forwards hover /\n * focus state to the dot + label.\n *\n * Empty ranges (no data on any branch) render a placeholder instead of an\n * axis so the layout does not collapse to an empty SVG.\n *\n * @param props - the filtered per-day rows plus the optional per-hour rows\n * (when present the chart plots hours instead of days), the optional\n * per-request series (session-scoped reads), the active range bounds\n * (absent when unfiltered; the chart then spans first to last row), and\n * the `t` seat for the empty hint and chart aria-label.\n * @returns the SVG chart, or a placeholder for an empty range.\n */\nexport function TrendChart({ rows, hours, requests, from, to, t }: {\n rows: readonly UsageDayRow[]\n hours?: readonly UsageHourRow[]\n requests?: readonly RequestPoint[]\n from?: string\n to?: string\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const series = buildChartPoints({ rows, hours, requests, from, to })\n if (series === null) {\n return <p className={styles.empty}>{t('chart.empty')}</p>\n }\n // Materialise the points (and apply t() through `tipOf` at render time).\n const points: PlottedPoint[] = series.points.map(point => ({\n key: point.key,\n label: point.label,\n full: point.full,\n tokens: point.tokens,\n time: 'time' in point ? point.time : undefined,\n count: 'count' in point ? point.count : undefined,\n }))\n const { top, ticks } = tickValues(Math.max(...points.map(p => p.tokens)))\n const innerHeight = HEIGHT - TOP - BOTTOM - X_LABELS\n // scaleSeries returns absolute viewBox coordinates already offset by LEFT,\n // so the dots / path / x-axis labels can plug xs[i] straight into the\n // SVG `cx`/`x` attributes without re-adding the y-axis margin.\n const { xs, innerWidth } = scaleSeries(series, LEFT, WIDTH - RIGHT)\n const radius = dotRadius(points.length)\n const [active, setActive] = useState<number | null>(null)\n const activePoint = active === null ? null : points[active] ?? null\n const y = (tokens: number): number => TOP + innerHeight - (tokens / top) * innerHeight\n const path = points\n .map((point, index) => `${index === 0 ? 'M' : 'L'}${xs[index]!.toFixed(1)},${y(point.tokens).toFixed(1)}`)\n .join(' ')\n\n const chartAria = series.mode === 'temporal'\n ? t('chart.ariaRequests')\n : hours !== undefined ? t('chart.ariaHour') : t('chart.aria')\n\n // The hit target around each point spans to the midpoint of each\n // neighbour (the full width for a single point), with a floor so\n // bunched-up request-mode points stay individually reachable — no\n // fixed grid width survives a temporal scale.\n const hitExtent = (index: number): { start: number; width: number } => {\n if (points.length === 1) return { start: LEFT, width: innerWidth }\n const center = xs[index]!\n const before = index === 0 ? undefined : xs[index - 1]!\n const after = index === points.length - 1 ? undefined : xs[index + 1]!\n const toPrev = before === undefined ? innerWidth : (center - before) / 2\n const toNext = after === undefined ? innerWidth : (after - center) / 2\n const half = Math.max(Math.min(toPrev, toNext), HIT_TARGET_FLOOR)\n return { start: center - half, width: half * 2 }\n }\n\n return (\n <svg\n role=\"img\"\n aria-label={chartAria}\n viewBox={`0 0 ${WIDTH} ${HEIGHT}`}\n className={styles.chart}\n onMouseLeave={() => setActive(null)}\n >\n {ticks.map(tick => (\n <g key={tick}>\n <line x1={LEFT} y1={y(tick)} x2={WIDTH - RIGHT} y2={y(tick)} className={styles.grid} />\n <text x={LEFT - 6} y={y(tick) + 3} textAnchor=\"end\" className={styles.tick}>\n {formatTokens(tick)}\n </text>\n </g>\n ))}\n <line x1={LEFT} y1={y(0)} x2={WIDTH - RIGHT} y2={y(0)} className={styles.axis} />\n <path d={path} className={styles.line} />\n {points.map((point, index) => (\n <circle\n key={point.key}\n cx={xs[index]}\n cy={y(point.tokens)}\n r={active === index ? radius + 2.5 : radius}\n className={active === index ? styles.dotActive : styles.dot}\n />\n ))}\n {activePoint !== null\n ? (\n // The guide line drops from the active point to the x axis.\n <line\n x1={xs[active!]} y1={y(activePoint.tokens)} x2={xs[active!]} y2={y(0)}\n className={styles.guide}\n />\n )\n : null}\n {points.map((point, index) => {\n const hit = hitExtent(index)\n return (\n <rect\n key={point.key}\n x={hit.start}\n y={TOP}\n width={hit.width}\n height={innerHeight}\n fill=\"transparent\"\n aria-label={tipOf(t, point)}\n role=\"button\"\n tabIndex={0}\n className={styles.hit}\n onMouseEnter={() => setActive(index)}\n onFocus={() => setActive(index)}\n onBlur={() => setActive(current => current === index ? null : current)}\n />\n )\n })}\n {activePoint !== null\n ? (() => {\n // Floating label: kept inside the canvas horizontally (near\n // the edges it flips toward the center), above the point with\n // a ceiling at the canvas top.\n const label = tipOf(t, activePoint)\n const charWidth = 6.2\n const labelWidth = label.length * charWidth + 12\n const center = xs[active!]!\n const left = Math.min(Math.max(center - labelWidth / 2, LEFT), WIDTH - RIGHT - labelWidth)\n const labelY = Math.max(y(activePoint.tokens) - 12, TOP + 8)\n return (\n <g className={styles.pointLabel} pointerEvents=\"none\">\n <rect x={left} y={labelY - 13} width={labelWidth} height={20} rx={5} />\n <text x={left + labelWidth / 2} y={labelY} textAnchor=\"middle\">{label}</text>\n </g>\n )\n })()\n : null}\n {labelIndices(points.length).map(index => (\n <text\n key={index}\n x={xs[index]}\n y={HEIGHT - 6}\n textAnchor={index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'middle'}\n className={styles.tick}\n >\n {points[index]!.label}\n </text>\n ))}\n </svg>\n )\n}\n","/**\n * Token-usage settings page (browser half): fetches the stats summary from\n * the host route and renders the filter bar (inclusive day range, model\n * select, 1d/7d/30d quick ranges where 1d spans today 00:00–23:59), the\n * total-usage strip, the daily-token trend chart, the per-model detail\n * table with the hit rate last, and — opened by each priced model row's\n * “定价” affordance — a dialog with that model's full price table — all\n * following the active filters. There is no refresh button: entering the\n * page or changing a filter refetches (the route answers no-store); only\n * the error state keeps a retry.\n *\n * @module token-usage/client/TokenUsageSection\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { SettingsSectionOwnerProps } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type { ContextTier, DailySlot, ModelPricing, ModelRates, RateWindow, UsageSummary } from '../wire.ts'\nimport { STATS_PATH } from '../wire.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport { dayKeyOf, shiftedDayKey, totalTokens } from './day.ts'\nimport { currencyViewOf, formatCost, formatRate, formatRateWithSymbol, formatTokens } from './format.ts'\nimport type { CurrencyView } from './format.ts'\nimport { HitRateText } from './HitRateText.tsx'\nimport { StatCard } from './StatCard.tsx'\nimport { TrendChart } from './TrendChart.tsx'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport styles from './TokenUsageSection.module.css'\n\n/** Re-export so existing section tests and consumers keep importing\n * `StatCard` from this module (the file moved to `./StatCard.tsx`). */\nexport { StatCard } from './StatCard.tsx'\n\n// Re-exported for tests and sibling consumers; the implementations live in\n// the leaf modules (day / format) so the chart can share them without a cycle.\nexport { totalTokens } from './day.ts'\nexport { formatTokens, formatHitRate } from './format.ts'\n\n/** The active filter selection; '' means unconstrained. */\ninterface Filters {\n from: string\n to: string\n model: string\n}\n\n/** Fetch the summary for one query string; the caller owns the failure\n * presentation. The AbortSignal wires into the request so a filter change\n * cancels the in-flight fetch instead of letting its response overwrite\n * the next filter's data. */\nfunction fetchSummary(query: string, signal: AbortSignal): Promise<UsageSummary> {\n return fetch(STATS_PATH + query, { signal })\n .then(response => {\n if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)\n return response.json() as Promise<UsageSummary>\n })\n .then(value => {\n if (typeof value !== 'object' || value === null || typeof value.total !== 'object') {\n throw new Error('unexpected stats response')\n }\n return value\n })\n}\n\n/**\n * The query string of one filter selection ('' when unconstrained), or null\n * while the range is mid-edit (`from > to`): editing the two date inputs\n * one at a time passes through inverted ranges, and fetching those would\n * only flash an HTTP 400 — the request waits until the range settles.\n */\nfunction filterQuery(filters: Filters): string | null {\n if (filters.from !== '' && filters.to !== '' && filters.from > filters.to) return null\n const params = new URLSearchParams()\n if (filters.from !== '') params.set('from', filters.from)\n if (filters.to !== '') params.set('to', filters.to)\n if (filters.model !== '') params.set('model', filters.model)\n return Array.from(params).length > 0 ? `?${params.toString()}` : ''\n}\n\n/** Quick-range day span in days (1 = today only, inclusive on both ends). */\nconst QUICK_DAYS = [1, 7, 30] as const\n\n/** The day keys of one quick range: today minus (days - 1) through today. */\nfunction quickRange(days: number): { from: string; to: string } {\n return { from: shiftedDayKey(-(days - 1)), to: shiftedDayKey(0) }\n}\n\n/** Whether the filters exactly hold one quick range. */\nfunction isQuickActive(days: number, filters: Filters): boolean {\n const range = quickRange(days)\n return filters.from === range.from && filters.to === range.to\n}\n\n/** The four base rates of one model as display text (symbol included,\n * converted for a USD view); a missing cache rate bills at the input rate. */\nfunction billedRates(rates: ModelPricing, view: CurrencyView): { input: string; output: string; cacheRead: string; cacheWrite: string } {\n return {\n input: formatRateWithSymbol(rates.inputPerMillion, view),\n output: formatRateWithSymbol(rates.outputPerMillion, view),\n cacheRead: formatRateWithSymbol(rates.cacheReadPerMillion ?? rates.inputPerMillion, view),\n cacheWrite: formatRateWithSymbol(rates.cacheWritePerMillion ?? rates.inputPerMillion, view),\n }\n}\n\n/** `HH:MM-HH:MM` of one peak window (half-open, local minutes). */\nfunction windowText(window: RateWindow): string {\n const clock = (minute: number): string =>\n `${String(Math.floor(minute / 60)).padStart(2, '0')}:${String(minute % 60).padStart(2, '0')}`\n return `${clock(window.startMinute)}-${clock(window.endMinute)}`\n}\n\n/** The when-it-applies text of one peak slot: its label plus its windows. */\nfunction slotCondition(slot: DailySlot, t: TranslateNS<'token-usage'>): string {\n return `${slot.label ?? t('pricing.peak')} ${slot.windows.map(windowText).join(t('pricing.windowSep'))}`\n}\n\n/**\n * One price row of the pricing table: the condition that bills at these\n * rates, and the four rates themselves. The condition text is complete —\n * a peak row inside a tier carries both the threshold and the windows —\n * so the row order never carries meaning on its own.\n */\ninterface PriceRow {\n condition: string\n rates: ModelPricing\n}\n\n/**\n * The price rows of one rate node (a time rule's or the model root's): the\n * node's own base rates, then its peak slots, then its context tiers\n * (ascending), each tier followed by the peak slots hanging on that tier —\n * mirroring {@link resolveRate}'s node chain, where a matching tier's slots\n * replace the node's and peak rates replace the node's rates wholesale.\n */\nfunction nodePriceRows(node: { rates: ModelPricing; tiers?: ContextTier[] | undefined; slots?: DailySlot[] | undefined }, t: TranslateNS<'token-usage'>): PriceRow[] {\n const rows: PriceRow[] = [{ condition: t('pricing.default'), rates: node.rates }]\n const tiers = [...node.tiers ?? []].sort((a, b) => a.threshold - b.threshold)\n for (const tier of tiers) {\n const tierCondition = t('pricing.tier', { threshold: formatTokens(tier.threshold) })\n rows.push({ condition: tierCondition, rates: tier.rates })\n for (const slot of tier.dailySlots ?? []) {\n rows.push({ condition: `${tierCondition} · ${slotCondition(slot, t)}`, rates: slot.rates })\n }\n }\n for (const slot of node.slots ?? []) {\n rows.push({ condition: slotCondition(slot, t), rates: slot.rates })\n }\n return rows\n}\n\n/**\n * One model's price table: rows are billing conditions — grouped into the\n * model root (“常规”, omitted when it is the only group) and one group per\n * time rule with its date window — so tier, peak, and time-rule pricing\n * each show when they apply and what they bill. Shared by the pricing\n * dialog; the structure mirrors {@link resolveRate}'s node chain.\n */\nfunction ModelPriceTable({ rules, view, t }: {\n rules: ModelRates\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n // Groups follow resolveRate's chain: the model root, then each time rule\n // with its own tiers/slots as an isolated price world.\n const groups = [\n {\n title: rules.timeRules.length > 0 ? t('pricing.regular') : null,\n rows: nodePriceRows({ rates: rules.base, tiers: rules.contextTiers, slots: rules.dailySlots }, t),\n },\n ...rules.timeRules.map(rule => ({\n // A zero start (the “since forever” rules some feeds carry) drops\n // the bogus 1970 date and reads as “through <end>”.\n title: `${rule.label !== undefined ? `${rule.label} ` : ''}${rule.startTime > 0 ? `${dayKeyOf(new Date(rule.startTime * 1000))} ~ ` : '~ '}${dayKeyOf(new Date(rule.endTime * 1000))}`,\n rows: nodePriceRows({ rates: rule.rates, tiers: rule.contextTiers, slots: rule.dailySlots }, t),\n })),\n ]\n return (\n <div className={styles['tableWrap']}>\n <table className={styles['table']} aria-label={t('pricing.title')}>\n <thead>\n <tr>\n <th className={styles['conditionHead']}>{t('pricing.condition')}</th>\n <th>{t('pricing.input')}{t('pricing.perMillion')}</th>\n <th>{t('pricing.output')}{t('pricing.perMillion')}</th>\n <th>{t('pricing.cacheRead')}{t('pricing.perMillion')}</th>\n <th>{t('pricing.cacheWrite')}{t('pricing.perMillion')}</th>\n </tr>\n </thead>\n <tbody>\n {groups.flatMap(group => [\n ...(group.title !== null\n ? [\n <tr key={group.title} className={styles['groupRow']}>\n <td colSpan={5}>{group.title}</td>\n </tr>,\n ]\n : []),\n ...group.rows.map((row, index) => {\n const billed = billedRates(row.rates, view)\n return (\n <tr key={`${group.title ?? ''}-${index}-${row.condition}`}>\n <td className={styles['conditionCell']}>{row.condition}</td>\n <td>{billed.input}</td>\n <td>{billed.output}</td>\n <td>{billed.cacheRead}</td>\n <td>{billed.cacheWrite}</td>\n </tr>\n )\n }),\n ])}\n </tbody>\n </table>\n {view.symbol === '$'\n ? <p className={styles['rateNote']}>{t('pricing.exchangeRateNote', { rate: formatRate(view.rate) })}</p>\n : null}\n </div>\n )\n}\n\n/**\n * The pricing dialog of one model: a native `<dialog>` (Esc closes, focus\n * is trapped, the backdrop dims, and the top layer renders it above the\n * table's scroll shell) opened by the “定价” affordance in a model row.\n * Mounts only while a model is selected; every close path funnels through\n * the dialog's `close` event, which clears the selection and unmounts it.\n */\nfunction PricingDialog({ model, rules, view, onClose, t }: {\n model: string\n rules: ModelRates\n view: CurrencyView\n onClose: () => void\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n useEffect(() => {\n const dialog = dialogRef.current\n if (dialog !== null && !dialog.open) dialog.showModal()\n }, [])\n return (\n <dialog\n ref={dialogRef}\n className={styles['dialog']}\n aria-label={t('pricing.title')}\n onClose={onClose}\n // A click that landed on the dialog element itself hit the backdrop\n // (the content sits in child elements), which closes like Esc does.\n onClick={event => { if (event.target === dialogRef.current) dialogRef.current?.close() }}\n >\n <div className={styles['dialogHead']}>\n <span className={styles['dialogTitle']}>{model}</span>\n <button\n type=\"button\"\n className={styles['dialogClose']}\n aria-label={t('pricing.close')}\n onClick={() => dialogRef.current?.close()}\n >\n ✕\n </button>\n </div>\n <ModelPriceTable rules={rules} view={view} t={t} />\n </dialog>\n )\n}\n\n/** The filter bar: quick range select, day range, model select — one row. */\nfunction FilterBar({ filters, models, onChange, t }: {\n filters: Filters\n models: readonly string[]\n onChange: (next: Filters) => void\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n // 'custom' when the day inputs no longer hold one of the quick ranges.\n const quickValue = QUICK_DAYS.find(days => isQuickActive(days, filters)) ?? 'custom'\n return (\n <div className={styles['filters']}>\n <select\n aria-label={t('filter.quickRange')}\n className={styles['control']}\n value={quickValue}\n onChange={event => {\n const days = Number(event.target.value)\n if (days > 0) onChange({ ...filters, ...quickRange(days) })\n }}\n >\n <option value=\"1\">1d</option>\n <option value=\"7\">7d</option>\n <option value=\"30\">30d</option>\n <option value=\"custom\">{t('filter.custom')}</option>\n </select>\n <input\n type=\"date\"\n aria-label={t('filter.from')}\n className={styles['dateControl']}\n value={filters.from}\n onChange={event => onChange({ ...filters, from: event.target.value })}\n />\n <span className={styles['rangeSeparator']}>{t('filter.separator')}</span>\n <input\n type=\"date\"\n aria-label={t('filter.to')}\n className={styles['dateControl']}\n value={filters.to}\n onChange={event => onChange({ ...filters, to: event.target.value })}\n />\n <select\n aria-label={t('filter.model')}\n className={styles['modelControl']}\n value={filters.model}\n onChange={event => onChange({ ...filters, model: event.target.value })}\n >\n <option value=\"\">{t('filter.allModels')}</option>\n {models.map(model => <option key={model} value={model}>{model}</option>)}\n </select>\n </div>\n )\n}\n\n/**\n * Render the Token Usage section content column. The `t` seat arrives from\n * the registration's `locale:` declaration and follows the active locale.\n * @param props - the settings shell's owner share (close is unused: the nav\n * rail owns leaving the panel) plus the framework-injected translate seat.\n * @returns the section, one of loading / error / ready.\n */\nexport function TokenUsageSection({ t }: SettingsSectionOwnerProps & { t: TranslateNS<'token-usage'> }): ReactNode {\n const rootRef = useRef<HTMLDivElement>(null)\n useColorSchemeMirror(rootRef)\n // Entering the page starts on today's window (the 1d quick range).\n const [filters, setFilters] = useState<Filters>(() => ({ model: '', ...quickRange(1) }))\n const [models, setModels] = useState<string[]>([])\n // The model whose pricing dialog is open (null = none). Refetched\n // summaries keep the dialog's rules in sync with the latest pricing.\n const [detailModel, setDetailModel] = useState<string | null>(null)\n const [retryToken, setRetryToken] = useState(0)\n const retry = useCallback(() => { setRetryToken(previous => previous + 1) }, [])\n\n const query = filterQuery(filters)\n // A mid-edit inverted range (`query === null`) is fed to the hook as the\n // last valid query — the ref remembers the most recent non-null string\n // and stays stable while the user types a bad range, so the hook does\n // neither fire a fetch nor flash its loading state. The test pins this\n // contract: bad ranges must not produce a network round-trip.\n const lastValidQueryRef = useRef<string>(query ?? '')\n if (query !== null) lastValidQueryRef.current = query\n const fetchQuery = query ?? lastValidQueryRef.current\n const [state] = useAsyncResource<UsageSummary>(\n signal => fetchSummary(fetchQuery, signal),\n [fetchQuery, retryToken],\n { silentAfterFirst: false, retryToken },\n )\n\n // While every model is shown, keep the option list from collapsing to\n // the filtered selection. The side effect runs when the ready-state\n // summary lands, not on every render.\n useEffect(() => {\n if (state.status !== 'ready') return\n if (filters.model !== '') return\n const next = state.value.byModel.map(row => row.model)\n if (next.length === models.length && next.every((m, i) => m === models[i])) return\n setModels(next)\n }, [state, filters.model, models])\n\n if (state.status === 'loading') {\n return (\n <div ref={rootRef} className={styles['section']}>\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <p className={styles['muted']}>{t('loading')}</p>\n </div>\n )\n }\n if (state.status === 'error') {\n return (\n <div ref={rootRef} className={styles['section']}>\n <div className={styles['head']}>\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <button type=\"button\" className={styles['button']} onClick={retry}>{t('retry')}</button>\n </div>\n <p className={styles['error']}>{t('loadFailed', { message: state.message })}</p>\n </div>\n )\n }\n\n const { total } = state.value\n const view = currencyViewOf(state.value)\n return (\n <div ref={rootRef} className={styles['section']}>\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <p className={styles['muted']}>{t('dataDir', { path: state.value.dataDir })}</p>\n <FilterBar filters={filters} models={models} onChange={setFilters} t={t} />\n {total.requests === 0\n ? (\n // One hint covers both an empty log and an empty filtered window:\n // the page opens on today (1d), so the two are indistinguishable\n // from the filtered response alone. The pricing block follows the\n // filter selection, so an empty selection renders none of it.\n <p className={styles['empty']}>\n {t('empty')}\n </p>\n )\n : (\n <>\n <div className={styles['cards']}>\n <StatCard label={t('stat.requests')} value={total.requests.toLocaleString()} />\n <StatCard label={t('stat.cost')} value={formatCost(state.value.totalCost, view)} />\n <StatCard label={t('stat.totalTokens')} value={formatTokens(totalTokens(total))} />\n <StatCard label={t('stat.hitRate')} value={<HitRateText totals={total} />} />\n </div>\n <div className={styles['cards']}>\n <StatCard label={t('stat.input')} value={formatTokens(total.inputTokens)} />\n <StatCard label={t('stat.output')} value={formatTokens(total.outputTokens)} />\n <StatCard label={t('stat.cacheRead')} value={formatTokens(total.cacheReadTokens)} />\n <StatCard label={t('stat.cacheWrite')} value={formatTokens(total.cacheWriteTokens)} />\n </div>\n {state.value.unpricedModels.length > 0\n ? (\n <p className={styles['warning']} role=\"status\">\n {t('unpriced.warning', {\n count: String(state.value.unpricedModels.length),\n models: state.value.unpricedModels.join(', '),\n zero: formatCost(0, view),\n })}\n </p>\n )\n : null}\n <TrendChart\n rows={state.value.byDay}\n t={t}\n {...filters.from !== '' ? { from: filters.from } : {}}\n {...filters.to !== '' ? { to: filters.to } : {}}\n // A single-day window (the 1d quick range or a same-day custom\n // selection) plots the day's 24 hours instead of one point.\n {...filters.from !== '' && filters.from === filters.to ? { hours: state.value.byHour } : {}}\n />\n {state.value.byModel.length > 0\n ? (\n <>\n <h3 className={styles['subtitle']}>{t('byModel.title')}</h3>\n <div className={styles['tableWrap']}>\n <table className={styles['table']} aria-label={t('byModel.title')}>\n <thead>\n <tr>\n <th className={styles['modelHead']}>{t('filter.model')}</th>\n <th>{t('stat.requests')}</th>\n <th>{t('stat.cost')}</th>\n <th>{t('stat.totalTokens')}</th>\n <th>{t('stat.input')}</th>\n <th>{t('stat.output')}</th>\n <th>{t('stat.cacheRead')}</th>\n <th>{t('stat.cacheWrite')}</th>\n <th>{t('stat.hitRate')}</th>\n </tr>\n </thead>\n <tbody>\n {state.value.byModel.map(row => {\n const rules = state.value.pricing[row.model]\n return (\n <tr key={row.model}>\n <td className={styles['modelCol']}>\n <span className={styles['modelCell']}>\n <span className={styles['modelName']}>{row.model}</span>\n {rules !== undefined\n ? (\n // The pricing affordance: one click opens\n // the model's detail-price dialog.\n <button\n type=\"button\"\n className={styles['pricingButton']}\n aria-label={t('pricing.view', { model: row.model })}\n onClick={() => setDetailModel(row.model)}\n >\n {t('pricing.viewShort')}\n </button>\n )\n : (\n // The unpriced tag explains the em-dash\n // cost cell in place.\n <span className={styles['unpricedTag']}>{t('pricing.unpriced')}</span>\n )}\n </span>\n </td>\n <td>{row.totals.requests.toLocaleString()}</td>\n <td>\n {rules !== undefined ? formatCost(row.cost, view) : '—'}\n </td>\n <td>{formatTokens(totalTokens(row.totals))}</td>\n <td>{formatTokens(row.totals.inputTokens)}</td>\n <td>{formatTokens(row.totals.outputTokens)}</td>\n <td>{formatTokens(row.totals.cacheReadTokens)}</td>\n <td>{formatTokens(row.totals.cacheWriteTokens)}</td>\n <td><HitRateText totals={row.totals} /></td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n </>\n )\n : null}\n {detailModel !== null && state.value.pricing[detailModel] !== undefined\n ? (\n <PricingDialog\n model={detailModel}\n rules={state.value.pricing[detailModel]!}\n view={view}\n onClose={() => setDetailModel(null)}\n t={t}\n />\n )\n : null}\n </>\n )}\n </div>\n )\n}\n","/**\n * The conversation view tab \"Usage\" (browser half): one entry of the\n * `conversation.view` slot ring (beside Chat / Trajectory), rendering the\n * per-session token & cost dashboard for the ACTIVE conversation. The tab\n * shows the focused session's totals (4 token buckets, cost, hit rate,\n * TTFT average, decode throughput) with a scope switch between the session\n * alone and its whole subagent subtree, a per-hour trend chart and the\n * per-model table from the host stats route (`sessionId`-scoped), and a\n * subagent table below — each row drill-in switches the focus to that child.\n *\n * Data sources: token/cost figures come from the host route (the pricing\n * rule chain's authority); TTFT and throughput come from the framework's\n * retained `sessionStats` projection values (`useProjection` for the current\n * session, `byId[].projectionValues` for every other session), which cover\n * the whole log including history written before this plugin was installed.\n * A footnote states the two scopes so the difference is not a surprise.\n *\n * @module token-usage/client/UsageView\n */\n\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { SnapshotSelectorHook, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ConversationSnapshot, SessionListState, UseProjection } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { SessionId } from '@deepseek-ai/dsh-client-connection/client'\nimport type { SessionStatsProjection } from '@deepseek-ai/dsh-session-stats/client'\n// Type-only: merges the sessionStats key into SessionProjectionMap so\n// useProjection('sessionStats') reads its real type.\nimport type {} from '@deepseek-ai/dsh-session-stats/client'\nimport type { UsageSummary } from '../wire.ts'\nimport { encodeStatsQuery, STATS_PATH } from '../wire.ts'\nimport { useAsyncResource, useDebouncedValue } from './async-resource.ts'\nimport { totalTokens } from './day.ts'\nimport { currencyViewOf, formatCost, formatSpeed, formatTokens, formatTtft } from './format.ts'\nimport { HitRateText } from './HitRateText.tsx'\nimport { aggregateProjections, buildChildIndex, directSubagentIds, subagentParentOf, subtreeIds, buildStatsFreshnessKey } from './session-stats.ts'\nimport { StatCard } from './StatCard.tsx'\nimport { TrendChart } from './TrendChart.tsx'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport styles from './UsageView.module.css'\n\n/** The view's scope switch: the session alone, or its whole subagent subtree. */\nexport type UsageScope = 'session' | 'tree'\n\n/** Refresh debounce: bursts of session-mirror updates (one request's events)\n * collapse into a single fetch, so the dashboard refreshes at REQUEST\n * granularity instead of per event or per turn. */\nconst REFRESH_DEBOUNCE_MS = 250\n\n/** Props: the conversation-view runtime seat (standard kit) plus the locale seat. */\nexport interface UsageViewProps {\n useSession: SnapshotSelectorHook<ConversationSnapshot>\n useSessions: SnapshotSelectorHook<SessionListState>\n useProjection: UseProjection\n sessionId: SessionId\n t: TranslateNS<'token-usage'>\n}\n\n/** One fetch of the session-scoped summary from the host stats route,\n * including the direct-child breakdown for the subagent table. */\nfunction fetchSessionSummary(\n sessionIds: readonly string[],\n childGroups: readonly (readonly string[])[],\n signal: AbortSignal,\n): Promise<UsageSummary> {\n return fetch(STATS_PATH + encodeStatsQuery({ sessionIds, childGroups, fields: 'session' }), { signal })\n .then(response => {\n if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)\n return response.json() as Promise<unknown>\n })\n .then(value => {\n if (typeof value !== 'object' || value === null || typeof (value as { total?: unknown }).total !== 'object') {\n throw new Error('unexpected stats response')\n }\n return value as UsageSummary\n })\n}\n\n/**\n * Render the Usage view tab for the active conversation.\n * @param props - the framework session kit, the session mirror, and the\n * locale seat (from the registration's `locale:` declaration).\n * @returns the dashboard: header (title, scope switch, back), stat cards\n * and the 4-token strip, the chart/model columns, and the subagent table.\n */\nexport function UsageView({ useSessions, useProjection, sessionId, t }: UsageViewProps): ReactNode {\n const rootRef = useRef<HTMLDivElement>(null)\n useColorSchemeMirror(rootRef)\n const [scope, setScope] = useState<UsageScope>('session')\n // The dashboard focus: the active conversation until a subagent row is\n // drilled into. Reset when the conversation itself changes — the pane\n // may reuse this instance across session switches.\n const [focusId, setFocusId] = useState<SessionId>(sessionId)\n useEffect(() => { setFocusId(sessionId) }, [sessionId])\n const [retryToken, setRetryToken] = useState(0)\n const retry = (): void => { setRetryToken(token => token + 1) }\n\n const byId = useSessions(state => state.byId)\n // Build the child index once per mirror churn and share it across the\n // three tree helpers — directSubagentIds / subtreeIds / per-row nested\n // counts — so a heavy subagent subtree doesn't pay O(n) per call.\n const childIndex = useMemo(() => buildChildIndex(byId), [byId])\n // The scoped session ids: the focus alone, or the focus plus its subtree.\n const scopeIds = useMemo(\n () => scope === 'tree' ? subtreeIds(byId, focusId, childIndex) : [focusId],\n [byId, scope, focusId, childIndex],\n )\n const children = useMemo(() => directSubagentIds(byId, focusId, childIndex), [byId, focusId, childIndex])\n // Tree scope folds each direct child with its own descendants so the\n // subagent-table numbers add back up to the header total.\n const childGroups = useMemo(\n () => children.map(id => (scope === 'tree' ? subtreeIds(byId, id, childIndex) : [id])),\n [children, scope, byId, childIndex],\n )\n const backParent = subagentParentOf(byId, focusId)\n // Live sessionStats updates every request step; mirror updatedAt alone\n // does not — fold both into the debounce key (same cadence as TTFT).\n const liveStats = useProjection('sessionStats')\n const freshnessKey = buildStatsFreshnessKey(\n [...new Set([...scopeIds, ...children])],\n { activeSessionId: sessionId, rows: byId, liveSessionStats: liveStats },\n )\n const requestKey = `${scopeIds.join('\\n')}\\n\\t${childGroups.map(group => group.join(',')).join(';')}\\n\\t${freshnessKey}`\n const debouncedKey = useDebouncedValue(requestKey, REFRESH_DEBOUNCE_MS)\n const [summaryState] = useAsyncResource<UsageSummary>(\n signal => {\n const [idsPart, groupsPart] = debouncedKey.split('\\n\\t')\n const sessionIds = (idsPart ?? '').split('\\n').filter(id => id !== '')\n const childGroups = (groupsPart ?? '').split(';').filter(group => group !== '').map(group => group.split(','))\n return fetchSessionSummary(sessionIds, childGroups, signal)\n },\n [debouncedKey, retryToken],\n { silentAfterFirst: true, retryToken },\n )\n\n const stats = useMemo(() => {\n const values: Array<SessionStatsProjection | undefined> = scopeIds.map((id) => {\n if (id === sessionId) return liveStats\n return byId[id as SessionId]?.projectionValues?.sessionStats\n })\n return aggregateProjections(values)\n }, [scopeIds, sessionId, liveStats, byId])\n const ttftText = stats !== undefined && stats.ttftSteps > 0\n ? formatTtft(stats.ttftMs / stats.ttftSteps)\n : '—'\n const speedText = stats !== undefined && stats.decodeMs > 0\n ? formatSpeed(stats.decodeTokens / (stats.decodeMs / 1_000))\n : '—'\n\n const header = (\n <header className={styles['head']}>\n <div className={styles['headRight']}>\n <div className={styles['segmented']} role=\"group\" aria-label={t('view.scope.label')}>\n <button\n type=\"button\"\n className={scope === 'session' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={scope === 'session'}\n onClick={() => setScope('session')}\n >\n {t('view.scope.session')}\n </button>\n <button\n type=\"button\"\n className={scope === 'tree' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={scope === 'tree'}\n onClick={() => setScope('tree')}\n >\n {t('view.scope.tree')}\n </button>\n </div>\n </div>\n </header>\n )\n\n if (summaryState.status === 'loading') {\n return (\n <div ref={rootRef} className={styles['root']}>\n {header}\n <p className={styles['muted']}>{t('loading')}</p>\n </div>\n )\n }\n if (summaryState.status === 'error') {\n return (\n <div ref={rootRef} className={styles['root']}>\n {header}\n <p className={styles['error']}>{t('loadFailed', { message: summaryState.message })}</p>\n <button type=\"button\" className={styles['button']} onClick={retry}>{t('retry')}</button>\n </div>\n )\n }\n\n const summary = summaryState.value\n const view = currencyViewOf(summary)\n const { total } = summary\n return (\n <div ref={rootRef} className={styles['root']}>\n {header}\n {total.requests === 0\n // The session has no recorded requests; the stat band is skipped\n // but the subagent table below still renders (children may hold\n // usage even when this session's scoped summary is empty).\n ? <p className={styles['empty']}>{t('view.empty')}</p>\n : (\n <>\n <div className={styles['cards']}>\n <StatCard label={t('stat.requests')} value={total.requests.toLocaleString()} />\n <StatCard label={t('stat.cost')} value={formatCost(summary.totalCost, view)} />\n <StatCard label={t('stat.totalTokens')} value={formatTokens(totalTokens(total))} />\n <StatCard label={t('stat.hitRate')} value={<HitRateText totals={total} />} />\n <StatCard label={t('view.ttft')} value={ttftText} />\n <StatCard label={t('view.speed')} value={`${speedText} tok/s`} />\n </div>\n <div className={styles['tokenStrip']}>\n <span>{t('stat.input')} <b>{formatTokens(total.inputTokens)}</b></span>\n <span>{t('stat.output')} <b>{formatTokens(total.outputTokens)}</b></span>\n <span>{t('stat.cacheRead')} <b>{formatTokens(total.cacheReadTokens)}</b></span>\n <span>{t('stat.cacheWrite')} <b>{formatTokens(total.cacheWriteTokens)}</b></span>\n </div>\n {summary.unpricedModels.length > 0\n ? (\n <p className={styles['warning']} role=\"status\">\n {t('unpriced.warning', {\n count: String(summary.unpricedModels.length),\n models: summary.unpricedModels.join(', '),\n zero: formatCost(0, view),\n })}\n </p>\n )\n : null}\n <div className={styles['mid']}>\n <section className={styles['chartCol']}>\n <h3 className={styles['subtitle']}>{t('view.chart.title')}</h3>\n {/* Session-scoped reads carry the per-request series: the\n trend plots one point per request. The whole-log settings\n read has no series and falls back to the day/hour rows. */}\n <TrendChart\n rows={summary.byDay}\n t={t}\n {...summary.requestSeries !== undefined ? { requests: summary.requestSeries } : {}}\n {...summary.byDay.length === 1 ? { hours: summary.byHour } : {}}\n />\n </section>\n <section className={styles['modelCol']}>\n <h3 className={styles['subtitle']}>{t('byModel.title')}</h3>\n {summary.byModel.length > 0\n ? (\n <div className={styles['tableWrap']}>\n <table className={styles['table']} aria-label={t('byModel.title')}>\n <thead>\n <tr>\n <th className={styles['modelHead']}>{t('filter.model')}</th>\n <th>{t('stat.requests')}</th>\n <th>{t('stat.input')}</th>\n <th>{t('stat.output')}</th>\n <th>{t('stat.cacheRead')}</th>\n <th>{t('stat.cacheWrite')}</th>\n <th>{t('stat.hitRate')}</th>\n <th>{t('stat.cost')}</th>\n </tr>\n </thead>\n <tbody>\n {summary.byModel.map(row => (\n <tr key={row.model}>\n <td className={styles['modelCell']}>{row.model}</td>\n <td>{row.totals.requests.toLocaleString()}</td>\n <td>{formatTokens(row.totals.inputTokens)}</td>\n <td>{formatTokens(row.totals.outputTokens)}</td>\n <td>{formatTokens(row.totals.cacheReadTokens)}</td>\n <td>{formatTokens(row.totals.cacheWriteTokens)}</td>\n <td><HitRateText totals={row.totals} /></td>\n <td>{formatCost(row.cost, view)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )\n : <p className={styles['muted']}>{t('chart.empty')}</p>}\n </section>\n </div>\n </>\n )}\n <section className={styles['subagents']}>\n <div className={styles['subagentsHead']}>\n <h3 className={styles['subtitle']}>\n {t('view.subagents.title', { count: String(children.length) })}\n </h3>\n {(() => {\n // The up-navigation control sits with the subagent section it\n // returns from: the drill-in entry point is the row below.\n if (backParent === undefined) return null\n const parentSummary = byId[backParent as SessionId]\n if (parentSummary === undefined) return null\n const parentId = backParent as SessionId\n return (\n <button\n type=\"button\"\n className={styles['back']}\n onClick={() => setFocusId(parentId)}\n >\n {t('view.back', { title: parentSummary.displayTitle ?? parentId })}\n </button>\n )\n })()}\n </div>\n {children.length === 0\n ? <p className={styles['muted']}>{t('view.subagents.none')}</p>\n : (\n <div className={styles['tableWrap']}>\n <table className={styles['table']} aria-label={t('view.subagents.title', { count: String(children.length) })}>\n <thead>\n <tr>\n <th className={styles['modelHead']}>{t('view.subagents.titleCol')}</th>\n <th>{t('stat.requests')}</th>\n <th>{t('stat.totalTokens')}</th>\n <th>{t('stat.cost')}</th>\n <th>{t('stat.hitRate')}</th>\n <th>{t('view.ttft')}</th>\n <th>{t('view.speed')}</th>\n </tr>\n </thead>\n <tbody>\n {children.map(id => {\n const child = byId[id as SessionId]\n const row = summary.children?.[id]\n const childStats = aggregateProjections([\n byId[id as SessionId]?.projectionValues?.sessionStats,\n ])\n // A nested-subagent marker: the count of THIS child's own\n // direct subagents, so the table signals before the\n // drill-in that the row has a subtree of its own.\n const nestedCount = directSubagentIds(byId, id, childIndex).length\n return (\n <tr key={id}>\n <td className={styles['modelCell']}>\n <button\n type=\"button\"\n className={styles['childLink']}\n onClick={() => setFocusId(id as SessionId)}\n >\n {child?.displayTitle ?? id}\n </button>\n {nestedCount > 0\n ? (\n <span\n className={styles['nestedBadge']}\n aria-label={t('view.subagents.nested', { count: String(nestedCount) })}\n >\n ({nestedCount})\n </span>\n )\n : null}\n </td>\n <td>{row?.total.requests.toLocaleString() ?? '—'}</td>\n <td>{row !== undefined ? formatTokens(totalTokens(row.total)) : '—'}</td>\n <td>\n {row !== undefined ? formatCost(row.totalCost, view) : '—'}\n </td>\n <td>{row !== undefined ? <HitRateText totals={row.total} /> : '—'}</td>\n <td>{childStats !== undefined && childStats.ttftSteps > 0 ? formatTtft(childStats.ttftMs / childStats.ttftSteps) : '—'}</td>\n <td>{childStats !== undefined && childStats.decodeMs > 0 ? `${formatSpeed(childStats.decodeTokens / (childStats.decodeMs / 1_000))} tok/s` : '—'}</td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )}\n </section>\n {total.requests > 0 && <p className={styles['note']}>{t('view.note')}</p>}\n </div>\n )\n}\n","/**\n * `token-usage` locale namespace dictionaries (browser half). zh is the\n * key-set source of truth; en is checked complete against it — the typed\n * `ctx.locale.register(NS, { zh, en })` call enforces both at compile time\n * and the `t` standard seat narrows its key domain to this union plus the\n * shared common vocabulary.\n *\n * @module token-usage/client/locales\n */\n\n/** Dictionary namespace owned by this plugin. */\nexport const NS = 'token-usage'\n\n/** Simplified Chinese dictionary (the key-set source of truth). */\nexport const zh = {\n 'nav.label': 'Token 用量',\n 'filter.quickRange': '快捷区间',\n 'filter.custom': '自定义',\n 'filter.from': '开始日期',\n 'filter.to': '结束日期',\n 'filter.separator': '至',\n 'filter.model': '模型',\n 'filter.allModels': '全部模型',\n 'stat.requests': '请求数',\n 'stat.totalTokens': '总 token',\n 'stat.hitRate': '命中率',\n 'stat.cost': '费用',\n 'stat.input': '入',\n 'stat.output': '出',\n 'stat.cacheRead': '缓',\n 'stat.cacheWrite': '写',\n 'byModel.title': '按模型',\n 'pricing.title': '模型定价',\n 'pricing.view': '查看 {model} 定价',\n 'pricing.viewShort': '定价',\n 'pricing.close': '关闭',\n 'pricing.condition': '计费条件',\n 'pricing.default': '默认',\n 'pricing.regular': '常规(规则期外)',\n 'pricing.tier': '上下文 ≥{threshold}',\n 'pricing.peak': '峰时',\n 'pricing.input': '入',\n 'pricing.output': '出',\n 'pricing.cacheRead': '缓',\n 'pricing.cacheWrite': '写',\n 'pricing.perMillion': '/M',\n 'pricing.exchangeRateNote': '按 1 USD = {rate} CNY 换算',\n 'pricing.unpriced': '未定价',\n 'pricing.windowSep': '、',\n 'unpriced.warning': '{count} 个模型未定价:{models}(费用按 {zero} 计)',\n 'dataDir': '数据目录:{path}',\n 'card.title': 'Token 用量',\n 'card.description': '数据目录与定价数据源',\n 'card.expand': '展开',\n 'card.collapse': '折叠',\n 'card.unsaved': '未保存',\n 'card.readOnly': '设置文档当前为只读,本次无法修改。',\n 'card.pathLabel': '数据目录',\n 'card.pathHint': '留空使用默认位置(~/.dsh/token-usage)。',\n 'card.browse': '浏览…',\n 'card.picking': '选择中…',\n 'card.migratingCopy': '正在复制数据 {done}/{total} 个文件…',\n 'card.migratingClean': '正在清理旧目录 {done}/{total} 个文件…',\n 'card.regionLabel': '定价区域',\n 'card.regionDefault': '默认(国内 Gitee)',\n 'card.region.domestic': '国内(Gitee)',\n 'card.region.overseas': '全球(GitHub)',\n 'card.hint': '切换到「全球」后从 GitHub 镜像拉取定价表,费用按美元展示(RMB ÷ 汇率);保存后立即重新同步,失败沿用旧镜像。',\n 'card.overridden': '已覆盖默认值',\n 'card.save': '保存',\n 'card.saving': '保存中…',\n 'card.saveFailed': '保存未生效,请重试。',\n 'card.saveBlockedSessions': '有会话正在进行对话,无法保存目录修改;请等待对话结束(当前 {count} 个)。',\n 'card.discard': '放弃',\n 'card.fullSync.title': '全量扫描同步',\n 'card.fullSync.hint': '手动扫一遍所有 session 日志,把可能漏掉的历史请求补进来(已记录的会跳过)。',\n 'card.fullSync.button': '开始扫描',\n 'card.fullSync.running': '扫描中…',\n 'card.fullSync.progress': '已处理 {processed}/{total} 个 session,新增 {added} 条,跳过 {skipped} 条',\n 'card.fullSync.done': '扫描完成:新增 {added} 条,跳过 {skipped} 条',\n 'card.fullSync.failed': '扫描失败:{error}',\n 'loadFailed': '统计加载失败:{message}',\n 'empty': '暂无数据。可调整筛选条件;模型请求成功后会自动写入,安装前已发生的历史记录会在首次启动时自动补齐。',\n 'chart.empty': '区间内暂无数据',\n 'chart.aria': '每日总 token 曲线',\n 'chart.ariaHour': '单日分时 token 曲线',\n 'chart.ariaRequests': '按时间分段的 token 曲线',\n 'chart.pointLabel': '{day} 总量 {tokens}',\n 'chart.bucket': '{window} · {count} 请求 · {tokens}',\n 'view.usage': '用量',\n 'view.scope.label': '统计范围',\n 'view.scope.session': '本会话',\n 'view.scope.tree': '含子会话',\n 'view.back': '← 返回 {title}',\n 'view.ttft': '平均首token',\n 'view.speed': 'token速度',\n 'view.empty': '该会话暂无用量记录。',\n 'view.chart.title': '趋势',\n 'view.subagents.title': '子会话({count})',\n 'view.subagents.none': '无子会话',\n 'view.subagents.titleCol': '会话',\n 'view.subagents.nested': '含 {count} 个子会话',\n 'view.note': '注:token 与费用来自本插件的请求记录(安装后);平均首token 与 token速度来自 DSH 会话投影(含安装前历史)。',\n 'chip.tokens': '含子会话 token 用量 {value}',\n 'chip.hitRate': '含子会话缓存命中率 {value}',\n 'chip.cost': '含子会话费用 {value}',\n 'quota.trigger': '供应商配额',\n 'quota.triggerSummary': '{name} · {figure}',\n 'quota.panel': '供应商配额面板',\n 'quota.tier.fiveHour': '5 小时',\n 'quota.tier.weekly': '每周',\n 'quota.tier.monthly': '每月',\n 'quota.tier.balance': '余额',\n 'quota.resetIn': '{time} 后重置',\n 'quota.updatedAt': '更新于 {time}',\n 'quota.retry': '重试',\n 'quota.error.auth': '鉴权失败({message});请检查该供应商的 API Key。',\n 'quota.error.noCredential': '未解析到 API Key({ref});请先在供应商设置中配置密钥。',\n 'quota.error.http': '供应商接口返回错误({message})。',\n 'quota.error.network': '网络错误({message})。',\n 'quota.error.parse': '响应解析失败({message})。',\n} as const\n\n/** English dictionary (same key set). */\nexport const en: Record<TokenUsageKey, string> = {\n 'nav.label': 'Token Usage',\n 'filter.quickRange': 'Quick range',\n 'filter.custom': 'Custom',\n 'filter.from': 'Start date',\n 'filter.to': 'End date',\n 'filter.separator': 'to',\n 'filter.model': 'Model',\n 'filter.allModels': 'All models',\n 'stat.requests': 'Requests',\n 'stat.totalTokens': 'Total',\n 'stat.hitRate': 'Hit %',\n 'stat.cost': 'Cost',\n 'stat.input': 'In',\n 'stat.output': 'Out',\n 'stat.cacheRead': 'Cache',\n 'stat.cacheWrite': 'Write',\n 'byModel.title': 'By model',\n 'pricing.title': 'Model pricing',\n 'pricing.view': 'View rates for {model}',\n 'pricing.viewShort': 'Rates',\n 'pricing.close': 'Close',\n 'pricing.condition': 'Condition',\n 'pricing.default': 'Default',\n 'pricing.regular': 'Regular (outside rule windows)',\n 'pricing.tier': 'context ≥{threshold}',\n 'pricing.peak': 'Peak',\n 'pricing.input': 'In',\n 'pricing.output': 'Out',\n 'pricing.cacheRead': 'Cache',\n 'pricing.cacheWrite': 'Write',\n 'pricing.perMillion': '/M',\n 'pricing.exchangeRateNote': 'Converted at 1 USD = {rate} CNY',\n 'pricing.unpriced': 'Unpriced',\n 'pricing.windowSep': ', ',\n 'unpriced.warning': '{count} models unpriced: {models} (cost counts as {zero})',\n 'dataDir': 'Data directory: {path}',\n 'card.title': 'Token Usage',\n 'card.description': 'Data directory and pricing source',\n 'card.expand': 'Expand',\n 'card.collapse': 'Collapse',\n 'card.unsaved': 'Unsaved',\n 'card.readOnly': 'The settings document is read-only right now; changes are disabled.',\n 'card.pathLabel': 'Data directory',\n 'card.pathHint': 'Leave empty for the default location (~/.dsh/token-usage).',\n 'card.browse': 'Browse…',\n 'card.picking': 'Picking…',\n 'card.migratingCopy': 'Copying data {done}/{total} files…',\n 'card.migratingClean': 'Cleaning the old directory {done}/{total} files…',\n 'card.regionLabel': 'Pricing region',\n 'card.regionDefault': 'Default (Gitee)',\n 'card.region.domestic': 'CN (Gitee)',\n 'card.region.overseas': 'Global (GitHub)',\n 'card.hint': 'Switching to Global pulls the pricing table from the GitHub mirror and shows costs in USD (RMB ÷ rate); saving re-syncs immediately, falling back to the previous mirror on failure.',\n 'card.overridden': 'Overriding the default',\n 'card.save': 'Save',\n 'card.saving': 'Saving…',\n 'card.saveFailed': 'The save did not land; try again.',\n 'card.saveBlockedSessions': 'A conversation is still in progress, so the directory change was not saved; wait for it to end first ({count} active).',\n 'card.discard': 'Discard',\n 'card.fullSync.title': 'Full scan sync',\n 'card.fullSync.hint': 'Walk every session log once and fold any historical requests the log does not yet hold (rows already recorded are skipped).',\n 'card.fullSync.button': 'Start scan',\n 'card.fullSync.running': 'Scanning…',\n 'card.fullSync.progress': 'Processed {processed}/{total} sessions, added {added}, skipped {skipped}',\n 'card.fullSync.done': 'Scan complete: added {added}, skipped {skipped}',\n 'card.fullSync.failed': 'Scan failed: {error}',\n 'loadFailed': 'Failed to load stats: {message}',\n 'empty': 'No data yet. Adjust the filters; requests are written automatically after each successful model call, and pre-install history is backfilled automatically on the first startup.',\n 'chart.empty': 'No data in range',\n 'chart.aria': 'Daily total token trend',\n 'chart.ariaHour': 'Single-day hourly token trend',\n 'chart.ariaRequests': 'Time-bucketed token trend',\n 'chart.pointLabel': '{day} total {tokens}',\n 'chart.bucket': '{window} · {count} requests · {tokens}',\n 'view.usage': 'Usage',\n 'view.scope.label': 'Scope',\n 'view.scope.session': 'Session',\n 'view.scope.tree': 'With subagents',\n 'view.back': '← Back to {title}',\n 'view.ttft': 'Avg TTFT',\n 'view.speed': 'Token speed',\n 'view.empty': 'No usage recorded for this session.',\n 'view.chart.title': 'Trend',\n 'view.subagents.title': 'Subagents ({count})',\n 'view.subagents.none': 'No subagents',\n 'view.subagents.titleCol': 'Session',\n 'view.subagents.nested': 'With {count} subagents',\n 'view.note': 'Note: tokens and cost come from this plugin\\'s request log (post-install); average TTFT and token speed come from the DSH session projection (includes pre-install history).',\n 'chip.tokens': 'Tokens with subagents {value}',\n 'chip.hitRate': 'Cache hit rate with subagents {value}',\n 'chip.cost': 'Cost with subagents {value}',\n 'quota.trigger': 'Provider quota',\n 'quota.triggerSummary': '{name} · {figure}',\n 'quota.panel': 'Provider quota panel',\n 'quota.tier.fiveHour': '5-hour',\n 'quota.tier.weekly': 'Weekly',\n 'quota.tier.monthly': 'Monthly',\n 'quota.tier.balance': 'Balance',\n 'quota.resetIn': 'resets in {time}',\n 'quota.updatedAt': 'Updated {time}',\n 'quota.retry': 'Retry',\n 'quota.error.auth': 'Authentication failed ({message}); check this provider\\'s API key.',\n 'quota.error.noCredential': 'No API key resolved ({ref}); configure the provider\\'s key first.',\n 'quota.error.http': 'The provider endpoint returned an error ({message}).',\n 'quota.error.network': 'Network error ({message}).',\n 'quota.error.parse': 'Failed to parse the response ({message}).',\n}\n\n/** Union of this namespace's dictionary keys. */\nexport type TokenUsageKey = keyof typeof zh\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** Copy of this plugin's settings nav label and stats page. */\n 'token-usage': TokenUsageKey\n }\n}\n","/**\n * Browser half of the token-usage plugin. Two registrations share one\n * dictionary pair: the Token Usage stats page on the settings surface (data\n * from the host half's stats route, `/token-usage/stats`), and the plugin\n * configuration card on the Plugins tab (the `token-usage` settings\n * namespace — the data directory and the pricing region — edited through\n * the settings scope, with the relocation progress polled from\n * `/token-usage/migration`). The card's browse button rides the shell's\n * workspace service (`ctx.workspaces.pickDirectory`), the same native\n * directory picker the workspace flows use. Export discipline: the /client\n * entry exposes only what cordis loading needs.\n *\n * @module token-usage/client\n */\n\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the ui-settings SlotMap merge ('settings.section') and the\n// owner-share type into this program.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\n// Type-only: pulls the ui-settings-plugins keyed-slot declaration\n// ('settings.plugin.item') into this program. The value face stays\n// uncompromised: cross-plugin collaboration goes through the slot system.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings-plugins/client'\n// Type-only: pulls the ui-conversation SlotMap merge ('conversation.view')\n// so the Usage view tab registers against the same slot the Chat and\n// Trajectory tabs live in. No runtime import — the slot service provides\n// the standard kit (useSession/useSessions/useProjection/sessionId).\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\n// Type-only: pulls the locale service's Context merge (ctx.locale) and the\n// shared `common` vocabulary into the `t` seat's key domain.\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport { CardForm, type SectionValue } from './card-form.ts'\nimport { QuotaButton, type ModelSelectionSource } from './QuotaButton.tsx'\nimport { SessionStatsChip } from './SessionStatsChip.tsx'\nimport { TokenUsageCard } from './TokenUsageCard.tsx'\nimport { TokenUsageSection } from './TokenUsageSection.tsx'\nimport { UsageView } from './UsageView.tsx'\nimport { en, NS, zh } from './locales.ts'\n\n/**\n * Namespace of the token-usage settings section. Spelled here rather than\n * imported: a client package must not depend on a Host package.\n */\nconst TOKEN_USAGE_NS = 'token-usage'\n\n/** Required services: the slot registry, the locale dictionaries, the\n * settings scope, and the workspace service (its native directory picker\n * backs the card's browse button). */\nexport const inject = ['slots', 'locale', 'connection', 'remote', 'settingsScope', 'workspaces']\n\n/**\n * Register the dictionary pair, then the settings page and the plugin\n * configuration card once the shell's declarations are on the ledger.\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'token-usage: dictionaries')\n // Stable per-namespace translate reading the active locale at call time;\n // the label thunk re-evaluates it per read, so the nav row follows switches.\n const t = ctx.locale.bind(NS)\n ctx.slots.inject('settings.section', () => ctx.slots.register({\n name: 'settings.section',\n id: 'token-usage',\n order: 50,\n label: () => t('nav.label'),\n locale: NS,\n }, TokenUsageSection))\n\n // The Usage view tab: one entry of the conversation view ring (beside the\n // built-in Chat tab and the Trajectory tab from ui-trajectory, rendered\n // by the session header's tab ring, one at a time). Registration is the\n // same trajectory pattern — a label thunk follows the active locale, and\n // the component reads the session through the standard kit.\n ctx.slots.inject('conversation.view', () => ctx.slots.register({\n name: 'conversation.view',\n id: 'usage',\n order: 20,\n label: () => t('view.usage'),\n locale: NS,\n }, UsageView))\n\n // The session-header stats chip: one entry of the\n // `conversation.session.header.utilities` slot list (right-aligned\n // utilities kept outside the title-adjacent action group). The chip\n // reads the active session id and the session-list mirror from the\n // standard kit, walks the subagent subtree, and fetches the folded\n // summary from the host's `/token-usage/stats` route — the same\n // \"with subagents\" range the Usage view tab offers. The component\n // self-gates: a session with zero recorded requests renders nothing\n // (the spec's empty rule); a transient fetch miss keeps the previous\n // render so the chip never blanks to \"—\" mid-conversation.\n //\n // Position: the chip sits IMMEDIATELY LEFT of the Session log button\n // (`session-log-download` registers with no explicit `order`, defaulting\n // to 0). A negative order puts the chip ahead of every positive-order\n // utility, mirroring the convention `ui-agent-preset` uses for static\n // session context in `conversation.session.header.actions`.\n ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({\n name: 'conversation.session.header.utilities',\n id: 'session-stats',\n order: -10,\n locale: NS,\n }, SessionStatsChip))\n\n // The input-bar quota button: one entry of the `conversation.input.right`\n // slot list (the tool row's right end, before the send button — the host\n // renders slot entries left of the model chip). The button polls the\n // host's `/token-usage/quota` route for the ACTIVE session's provider and\n // self-gates: it renders nothing while the provider is undeterminable or\n // has no quota adapter, so the toolbar stays clean on unsupported\n // providers and the button reappears when a supported one takes over.\n // `order: 10` keeps it after any future lower-order utilities in the\n // same slot.\n //\n // Provider resolution follows the model CHIP: the shell's model-selection\n // service (`ctx.modelDirectories`, from ui-model-selection — the same\n // shared per-session directory the chip renders from) reports the host's\n // NEXT selection live, so the button appears the moment the user picks a\n // provider, before any request is sent. The service attaches through an\n // OPTIONAL inject — a shell without it falls back to the host's own\n // resolution (last request's provider, else the default selection).\n const modelDirectory: { service: ModelSelectionSource | undefined } = { service: undefined }\n ctx.inject(['modelDirectories'], (modelCtx) => {\n modelCtx.effect(() => {\n modelDirectory.service = (modelCtx as unknown as { modelDirectories?: ModelSelectionSource }).modelDirectories\n return () => { modelDirectory.service = undefined }\n }, 'token-usage: model directory seam')\n })\n ctx.slots.inject('conversation.input.right', () => ctx.slots.register({\n name: 'conversation.input.right',\n id: 'token-usage-quota',\n order: 10,\n locale: NS,\n inject: () => ({ modelDirectory }),\n }, QuotaButton))\n\n // The Plugins configuration tab dispatches keyed cards for the namespaces\n // the Host serves; the token-usage host half registers this key, so the\n // pricing card pairs with it without any upstream change.\n const form = new CardForm(ctx.settingsScope.bind<SectionValue>({ namespace: TOKEN_USAGE_NS }))\n const store = form.bind()\n ctx.slots.inject('settings.plugin.item', () => ctx.slots.register({\n name: 'settings.plugin.item',\n key: TOKEN_USAGE_NS,\n locale: NS,\n inject: () => ({\n hooks: { tokenUsageCard: store },\n ...form.actions(),\n // The shell's own directory picker (the workspace flows' chooser):\n // resolves the chosen absolute path, or null when the user dismisses.\n pickDirectory: () => ctx.workspaces.pickDirectory(),\n }),\n }, TokenUsageCard))\n}\n"],"mappings":";;;;;;;;;;;EAcA,MAAa,aAAa;;EAQ1B,SAAgB,oBAAoB,KAAa,QAAmC;GAClF,OAAO,OAAO,KAAI,UAAS,GAAG,IAAI,GAA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