@laoyuehanni/dsh-token-usage 0.4.14 → 0.4.15
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/lib/client/CostPill.d.ts +3 -4
- package/lib/client/CostPill.d.ts.map +1 -1
- package/lib/client/CostPill.js +5 -7
- package/lib/client/CostPill.js.map +1 -1
- package/lib/client/cost-inflate-motion.d.ts +0 -4
- package/lib/client/cost-inflate-motion.d.ts.map +1 -1
- package/lib/client/cost-inflate-motion.js +0 -19
- package/lib/client/cost-inflate-motion.js.map +1 -1
- package/lib/client/cost-inflate.d.ts +4 -6
- package/lib/client/cost-inflate.d.ts.map +1 -1
- package/lib/client/cost-inflate.js +3 -5
- package/lib/client/cost-inflate.js.map +1 -1
- package/lib/client/use-cost-inflate.d.ts +5 -15
- package/lib/client/use-cost-inflate.d.ts.map +1 -1
- package/lib/client/use-cost-inflate.js +11 -51
- package/lib/client/use-cost-inflate.js.map +1 -1
- package/lib/client.js +69 -177
- package/lib/client.js.map +1 -1
- package/package.json +1 -1
- package/lib/client/CostDeltaFlyLabel.d.ts +0 -8
- package/lib/client/CostDeltaFlyLabel.d.ts.map +0 -1
- package/lib/client/CostDeltaFlyLabel.js +0 -24
- package/lib/client/CostDeltaFlyLabel.js.map +0 -1
package/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["useState","useRef","useCallback","totalTokens","styles","useRef","useRef","createContext","useState","useRef","useContext","styles","shared","Tooltip","useId","useState","useRef","styles","totalTokens","useRef","useState","useCallback","REFRESH_DEBOUNCE_MS","PANEL_VIEWPORT_MARGIN","totalTokens","useRef","useState","useMemo","fetchSummary","useCallback","styles","MenuItemButton","IconGaugeOutlineRegular","IconGaugeOutlineRegular","useRef","useState","useCallback","styles","Tooltip","useState","useRef","css","useCallback","IconChevronDownOutlineMedium","useRef","useState","styles","useRef","useState","styles","useState","styles","list","totalTokens","styles","useState","useRef","useMemo","totalTokens","Tooltip","styles","styles","Tooltip","useId","useState","useRef","styles","bands","styles","totalTokens","styles","useRef","useState","useMemo","shared","Fragment","styles","useRef","useState","useCallback","Toast","IconWarningOutlineRegular","css","styles","Tooltip","useRef","useRef","useState","useMemo","styles","totalTokens"],"sources":["../src/wire.ts","../src/client/card-form.ts","../src/client/async-resource.ts","../src/client/day.ts","../src/provider-label.ts","../src/client/format.ts","../src/client/PricingStatus.tsx","../src/model-resolution.ts","../src/client/PricingDialog.tsx","../src/client/pricing-associations.ts","../src/client/PricingAssociations.tsx","../src/client/session-stats.ts","../src/client/use-color-scheme.ts","../src/client/cost-inflate-motion.ts","../src/client/CostDeltaFlyLabel.tsx","../src/client/cost-inflate.ts","../src/client/use-cost-inflate.ts","../src/client/CostPill.tsx","../src/client/PanellistMoreEntry.tsx","../src/client/PanellistPinEntry.tsx","../src/client/quota-format.ts","../src/client/QuotaButton.tsx","../src/client/TokenUsageCard.tsx","../src/client/DateRangePicker.tsx","../src/client/MenuSelect.tsx","../src/client/OverheadRows.tsx","../src/project-rows.ts","../src/client/UsageRows.tsx","../src/client/DashboardCards.tsx","../src/client/StatCard.tsx","../src/client/trend-chart/axis.ts","../src/client/trend-chart/path.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/HitRateText.tsx","../src/client/OverviewBoard.tsx","../src/client/pricing-search.ts","../src/client/PricingOverviewDialog.tsx","../src/client/TokenUsageSection.tsx","../src/client/UsagePanelPage.tsx","../src/client/RequestPool.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 { AuxKind, UsageRecord } from './usage-record.ts'\nimport type { CompactionAttributionItem } from './compaction-attribution.ts'\n\nexport type { AuxKind, UsageFields, UsageRecord } from './usage-record.ts'\nexport type { CompactionAttributionItem, CompactionSourceKind } from './compaction-attribution.ts'\n\n/** The stats endpoint path, served by the host half's webServer route. */\nexport const STATS_PATH = '/token-usage/stats'\n\n/** The pricing-overview endpoint path: the full cloud-mirror model list,\n * filter-free by design — the overview is not a filtered usage view. */\nexport const PRICING_PATH = '/token-usage/pricing'\nexport const PRICING_SYNC_PATH = '/token-usage/pricing-sync'\nexport const ASSOCIATIONS_PATH = '/token-usage/pricing-associations'\n\n/** Returned only after a validated pricing mirror has been saved. */\nexport interface PricingSyncResult {\n version: number\n updatedAt: number\n models: number\n aliasPatterns: number\n usdExchangeRate: number\n}\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 + read + 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; removed: number; failedSessions: number }\n | { status: 'done'; processed: number; total: number; added: number; skipped: number; removed: number; failedSessions: number }\n | { status: 'failed'; error: string }\n\n/** Aggregated token counts over one group of records. */\nexport interface UsageTotals {\n /** Number of recorded provider-billed calls: plain requests plus\n * compaction summarize requests (records without provider usage count\n * here). Failed requests never join this count — see {@link failures}. */\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 /** Compaction summarize requests in this group; absent on legacy rollups\n * (reads as 0). Plain requests = `requests - (compactions ?? 0)`. */\n compactions?: number\n /** Failed model requests in this group (`turn/end` LLM errors plus\n * `llm/retry` scheduled after a failed attempt); absent on legacy\n * rollups and pre-failure shapes (reads as 0). Success rate =\n * requests / (requests + failures) is attempt-level, not turn-level. */\n failures?: number\n /** Failure counts by the provider-neutral `LlmFailure.code`\n * (`{ RATE_LIMIT: 16, TRANSPORT: 2, … }`); absent when the\n * group holds no failures or the shape predates the key (reads as an\n * empty map). Sums to `failures` when present. Codes are an open set:\n * unknown future codes read verbatim. */\n failuresByCode?: Record<string, number>\n /** Internal accumulators behind the model card's performance view: the\n * streaming samples' tokens-per-second and first-token-latency sums with\n * their count, plus the end-to-end latency sum and valid timing count.\n * Requests without timing never contribute to a performance mean.\n * Absent on legacy rollups and\n * pre-timing shapes (reads as no samples) — the means are derived at the\n * cost layer, never stored. Timing figures follow the records' own\n * `latencyMs` / `firstTokenLatencyMs`; a streaming sample is one whose\n * generation span (latency − first token) reached the recorder's\n * streaming threshold, so non-streaming one-shot responses never poison\n * the speed mean. */\n perfStreamTpsSum?: number\n perfStreamFirstMsSum?: number\n perfStreamCount?: number\n perfLatencyMsSum?: number\n perfLatencyCount?: number\n}\n\n/** Per-model performance means the model card's performance view renders.\n * Derived at the cost layer from the totals' timing accumulators — never\n * persisted itself, so a filter/merge re-derivation stays exact. */\nexport interface ModelPerf {\n /** Mean output speed over the streaming samples, tokens per second. */\n tokensPerSec: number\n /** Mean first-token latency over the same streaming samples, ms. */\n firstTokenMs: number\n /** Mean end-to-end latency over successful requests with valid timing, ms. */\n latencyMs: number\n /** Successful requests with valid latency; untimed requests are excluded. */\n timedRequests: number\n /** Streaming sample count the speed/first-token means fold from; below\n * {@link MIN_PERF_SAMPLES} the row reads 「样本不足」 instead of a full\n * figures cell. */\n samples: number\n}\n\n/** Smallest streaming sample count a performance figures cell trusts; below\n * it the row still shows its mean speed but annotated 「样本不足」. */\nexport const MIN_PERF_SAMPLES = 5\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 costState?: CostState\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/**\n * One per-provider aggregation row, keyed by the route key (`provider`) the\n * records carried. `''` is the unattributed group — pre-field history and\n * auxiliary rows whose route never landed in a session log. It is listed as\n * its own row (never folded into a named provider, never dropped), so the\n * dimension's totals reconcile with the top line.\n */\nexport interface UsageProviderRow {\n /** Route key; `''` groups every unattributed record. */\n provider: 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 /** ISO weekdays (1=Monday … 7=Sunday) the slot applies to, as validated at\n * coercion; absent or empty = every day. */\n daysOfWeek?: number[]\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.\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 pricing table: model id → full rule set, loaded from\n * `<data dir>/pricing.ccsa.json` (the cloud mirror; 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\nexport type CostState = 'ready' | 'pricing-unavailable' | 'history-incomplete'\nexport type PricingUnavailableReason = 'missing' | 'unreadable' | 'invalid-json' | 'invalid-feed'\nexport type AssociationStorageError = 'unreadable' | 'invalid-json' | 'invalid-file'\n\nexport interface PricingAssociation {\n sourceModel: string\n targetModelId: string\n}\n\nexport interface PricingAssociationStatus extends PricingAssociation {\n state: 'active' | 'automatic-takeover' | 'target-missing' | 'pricing-unavailable'\n resolvedTargetModelId?: string\n automaticModelId?: string\n targetDiffers?: boolean\n}\n\nexport interface PricingAssociationsPayload {\n feedVersion?: number\n directoryToken: string\n revision: number | null\n storageState: 'ready' | 'unavailable'\n storageError?: AssociationStorageError\n pricingAvailable: boolean\n pricingUnavailableReason?: PricingUnavailableReason\n writesPaused: boolean\n associations: PricingAssociationStatus[]\n resolution?: ModelResolution\n}\n\nexport interface SavePricingAssociation extends PricingAssociation {\n revision: number\n directoryToken: string\n}\n\nexport interface DeletePricingAssociation {\n sourceModel: string\n revision: number\n directoryToken: string\n}\n\nexport interface ModelResolution {\n rawName: string\n status: 'matched' | 'unmatched' | 'ambiguous'\n modelId?: string\n method?: 'id' | 'normalized-id' | 'pattern' | 'manual'\n strippedPrefix: boolean\n candidates: string[]\n association?: PricingAssociationStatus\n /** Preserves the unmatched/ambiguous reason when a manual choice is active. */\n automatic?: ModelResolution\n}\n\n/**\n * One model row of the pricing overview: the shape the cloud feed carries\n * (modelId + alias patterns + upstream family) plus the full rule set.\n * The overview keeps one row per model rather than enumerating aliases.\n */\nexport interface PricingOverviewModel {\n modelId: string\n /** Validated full-name regexes; empty when the feed carries none. */\n aliasPatterns: readonly string[]\n /** The feed's upstream family grouping; absent rows group under `other`. */\n family?: string\n rules: ModelRates\n}\n\n/** The payload served at {@link PRICING_PATH}: every cloud-mirror model row\n * plus the display-currency stamps the settings page converts with (same\n * region source as the stats payload). */\nexport interface PricingOverviewPayload {\n feedVersion?: number\n pricingUnavailableReason?: PricingUnavailableReason\n costState?: CostState\n models: readonly PricingOverviewModel[]\n /** The display currency the page converts rate figures into. Amounts on\n * the wire (rules 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}\n\n/** One per-day × per-model × per-rate × per-provider aggregation row. The\n * route re-aggregates any filter from these cells and re-prices history\n * under the current table; `provider` is the route key the record carried\n * (absent/empty = pre-field history that could not be attributed). */\nexport interface UsageRateRow {\n day: string\n model: string\n rate: RateKey\n /** Route key of the requests in this cell; absent when unattributed. */\n provider?: string\n totals: UsageTotals\n}\n\n/**\n * One per-(kind, day, model, rate) aggregation row of the auxiliary (bypass)\n * model requests: Auto review, session-title generation, and translation.\n * These calls are not part of any conversation turn. The auxiliary dimension\n * intentionally stays keyed only by kind/day/model/rate even when a newer\n * host supplies an owning session id; that keeps the settings page's\n * \"runtime overhead\" breakdown independent of the per-session table. They\n * still fold into `rateRows` / `byModel` / the totals as provider-billed\n * requests of a concrete model.\n */\nexport interface UsageAuxRow {\n /** Which bypass call produced the rows folded into this cell. */\n auxKind: AuxKind\n day: string\n model: string\n rate: RateKey\n totals: UsageTotals\n}\n\n/** One per-model row nested under an auxiliary kind: the model's share of one\n * bypass-request kind, keyed by the canonical id (a priced alias family folds\n * onto its modelId, unpriced names keep their spelling). The runtime-overhead\n * tab renders these one line each beneath their kind's aggregate row. */\nexport interface UsageAuxModelRow {\n model: string\n totals: UsageTotals\n /** Billed cost (¥) of this model's requests of the kind; 0 when unpriced. */\n cost: number\n}\n\n/** One per-kind aggregate of the auxiliary requests, priced at the rate\n * identities its cells resolved through. */\nexport interface UsageAuxKindRow {\n auxKind: AuxKind\n totals: UsageTotals\n /** Billed cost (¥) of this kind; 0 when its model is unpriced. */\n cost: number\n /** Per-model rows of this kind, request-count descending then model name. */\n byModel: UsageAuxModelRow[]\n}\n\n/**\n * The auxiliary-request layer of the stats payload: the settings page's\n * \"runtime overhead\" block renders the per-kind rows, and the total reconciles\n * with the share of the top-line totals those bypass calls contributed.\n */\nexport interface AuxSummary {\n /** Totals over every recorded auxiliary request. */\n total: UsageTotals\n /** Billed cost (¥) of the auxiliary requests under the current table. */\n cost: number\n /** Per-kind rows in the fixed display order, kinds without data omitted. */\n byKind: UsageAuxKindRow[]\n}\n\n/**\n * One per-session × per-day × per-model × per-rate aggregation row: the\n * session dimension the settings page's cross-session table folds from.\n * Every granule pulls its weight — a session usually spans days (the day\n * key keeps a date-filtered row to the window's share), the model key keeps\n * a model-filtered row honest, the rate identity keeps cost re-pricing\n * free, and `lastTime` sorts the table by recent activity. Failure rows\n * (`model === ''`) fold in like every other record: the session dimension\n * keeps the same totals semantics as rateRows, so request counts reconcile.\n */\nexport interface UsageSessionRow {\n sessionId: string\n day: string\n model: string\n rate: RateKey\n /** Route key of the requests in this cell; absent when unattributed.\n * Keeps the session dimension at the same granule width rateRows carry,\n * so a session-scoped read rebuilds the provider dimension from cells. */\n provider?: string\n /** Newest record time folded into this cell (max over the fold); the\n * session table's \"last active\" column. */\n lastTime: number\n totals: UsageTotals\n}\n\n/**\n * One final row of the settings page's session table: the server-side fold\n * of {@link UsageSessionRow} cells over one top-level session plus its\n * whole subtree, sorted by cost and truncated top-N before it crosses the\n * wire. Subagents never surface as rows of their own — the row's\n * `childCount` badge is their only visibility here. Identity fields ride\n * in the row — the server folds, sorts, and truncates, so the client never\n * reassembles titles or directories.\n */\nexport interface SessionUsageRow {\n sessionId: string\n /** Log-backed latest-wins title; omitted when no `session/title` event\n * ever landed (the client falls back to a short session id + times). */\n title?: string\n /** The session header's working directory, verbatim; omitted when the\n * header carried none. The client derives the tail segment and grouping. */\n cwd?: string\n /** How many descendant sessions folded into this row (the subagent\n * badge); omitted when the subtree holds none. */\n childCount?: number\n totals: UsageTotals\n /** Billed cost (¥) over the row's cells under the current table. */\n cost: number\n /** Start of the local day of the row's earliest cell — the fallback\n * identity's \"from\" bound (day granularity; titles cover the rest). */\n firstTime: number\n /** Newest record time in the row (max over every folded cell). */\n lastTime: number\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-provider rows (route key → totals; `''` = unattributed), descending\n * by request count. Rebuilt from the same granules rateRows carry. */\n byProvider: UsageProviderRow[]\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 /** Per-(kind, day, model, rate) rows of the auxiliary bypass requests\n * (Auto review / session title / translation / other). Their usage also\n * folds into the totals, byDay, byHour, byModel, rateRows, and recent\n * window; this dimension only backs the runtime-overhead breakdown.\n * A summary read without raw history carries an empty list. */\n auxRows: UsageAuxRow[]\n /** Per-session × per-day × per-model × per-rate rows, session then day\n * then model then rate ascending; the settings page's session table folds\n * from these (see {@link UsageSessionRow}). */\n bySession: UsageSessionRow[]\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; perf?: ModelPerf }\n\n/** A per-provider row carrying its billed cost (¥), folded from the rate\n * rows that carry the same provider key; the unattributed group keeps its\n * own row so the provider table's cost column reconciles with the summary\n * card for free. */\nexport type CostedProviderRow = UsageProviderRow & { cost: number }\n\n/** A per-session aggregation cell carrying its billed cost (¥); 0 when the\n * model is unpriced — priced from the same rate identity the per-model cost\n * folds from, so the session table's cost column reconciles with the\n * summary card for free. */\nexport type CostedSessionCell = UsageSessionRow & { cost: number }\n\n/** One project fold over all root-session rows, before the session list's\n * top-N cut. Directory tails remain the display grouping key. */\nexport interface ProjectUsageRow {\n name: string\n cwd?: string\n sessionCount: number\n totals: UsageTotals\n cost: number\n}\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 feedVersion?: number\n associationStorageError?: AssociationStorageError\n pricingUnavailableReason?: PricingUnavailableReason\n costState: CostState\n modelResolutions: ModelResolution[]\n /** Absolute data directory the summary was computed from. */\n dataDir: string\n /** Billed cost (¥); unpriced models count 0. Trust only when costState is ready. */\n totalCost: number\n /** Models with usage but no entry in the pricing table, byModel order. */\n unpricedModels: string[]\n /** The snapshot pricing dictionary, including resolved names for details. */\n pricing: PricingTable\n /** Per-model rows with their billed cost attached. */\n byModel: CostedModelRow[]\n /** Per-provider rows with their billed cost attached (see\n * {@link CostedProviderRow}); the unattributed group (`''`) included. */\n byProvider: CostedProviderRow[]\n /** Per-session cells with their billed cost attached (see\n * {@link CostedSessionCell}); the route folds these into\n * {@link SessionUsageRow}s for the session table. */\n bySession: CostedSessionCell[]\n /** The auxiliary (bypass) request layer: the settings page's runtime-overhead\n * block. Its usage is already included in the totals above; this field only\n * splits it out by kind and prices it for display. */\n aux: AuxSummary\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. The session table reads\n * `sessionRows` — the server-side folded, sorted, truncated final\n * rows (always folded over subagent subtrees); the granular\n * `bySession` cells stay behind the route (sending them would only\n * duplicate the fold on the wire).\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 except the\n * granular `bySession` (stripped from the wire) plus the\n * display-currency metadata, so a consumer can read `total` /\n * `totalCost` / `pricing` without narrowing first.\n */\ntype CostedSummaryWire = Omit<CostedSummary, 'bySession'>\nexport type StatsPayload = (CostedSummaryWire & {\n scope: 'whole'\n /** The session table's final rows: folded over subagent subtrees,\n * cost-sorted, top-N truncated, metadata attached. */\n sessionRows: readonly SessionUsageRow[]\n /** Complete project aggregates, independent of the session top-N cut. */\n projectRows: readonly ProjectUsageRow[]\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 /** Route key → latest display name for the provider dimension; absent\n * when the host has no registry seam (the client falls back to keys). */\n providerNames?: Readonly<Record<string, string>>\n}) | (CostedSummaryWire & {\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 /** Route key → latest display name for the provider dimension; absent\n * when the host has no registry seam (the client falls back to keys). */\n providerNames?: Readonly<Record<string, string>>\n /** Direct-child breakdown keyed by child id, when the request named `childId`. */\n children?: Readonly<Record<string, ChildUsageSummary>>\n})\n\n/**\n * 会话用量页「最新请求 / 实时请求」区的请求池上限。池包含顶部最新一条与\n * 下方最多 19 条历史;上限只约束展示,从不截断日志、汇总或趋势。\n */\nexport const REQUEST_POOL_LIMIT = 20\n\n/** 一次 provider 请求尝试的生命周期状态。`interrupted` 是取消时已交付部分\n * 用量的结算(宿主 `assistant/message` 的 `interrupted` 事实);`cancelled`\n * 是未结算任何用量的取消。 */\nexport type RequestDetailState = 'waiting' | 'streaming' | 'completed' | 'failed' | 'cancelled' | 'interrupted'\n\n/**\n * 「缓存过低」标签的低命中启发式为何不适用于该请求。稳定枚举值,客户端\n * 本地化;绝不携带 prompt 或正文。优先级即评估顺序:状态排除 → 数据有效性\n * → 序列排除 → 输入资格。\n * - `cold-start`:该会话的首条请求(全量记录序列判定,不看 20 条窗口行号)。\n * - `model-switch`:同会话相邻前一条请求的模型不同(切回旧模型同样保守排除)。\n * - `in-flight`:等待首 token 或生成中,尚未完成。\n * - `not-success`:失败 / 取消 / 中断,终态并非成功完成。\n * - `compaction`:压缩 summarize 请求,输入特征特殊,不做性能诊断。\n * - `auxiliary`:已归属会话的辅助请求(如标题生成 / 审查),用途开销\n * 与主请求不同,不做缓存性能诊断。\n * - `cache-unreported`:provider 未显式报告缓存读(缺失不当 0%)。\n * - `insufficient-input`:输入不满足该路由的缓存条件(按适配语义推导)。\n * - `invalid-data`:分母为零、负值、NaN/Infinity 或计数矛盾。\n */\nexport type RequestCacheExclusion =\n | 'cold-start'\n | 'model-switch'\n | 'in-flight'\n | 'not-success'\n | 'compaction'\n | 'auxiliary'\n | 'cache-unreported'\n | 'insufficient-input'\n | 'invalid-data'\n\n/** 单次请求的缓存命中评估。`rate` 是原始精度 [0,1](绝不传格式化字符串);\n * band 是请求区域专用的三档策略(<50% loss / <80% low / 其余 normal),\n * 排除与未知分别落 `excluded` / `unknown`,不改全局色阶。 */\nexport interface RequestDetailCache {\n rate?: number\n /** Whether valid reported data is available, not a provider allowlist. */\n eligibility: 'eligible' | 'ineligible' | 'unknown'\n band: 'normal' | 'low' | 'loss' | 'excluded' | 'unknown'\n reason?: RequestCacheExclusion\n}\n\n/** 一次真实 provider 请求尝试的展示明细:会话用量页请求池的一行。列表单位\n * 是「一次尝试」,不是一条消息或一个 turn;自动重试的失败尝试与重试成功的\n * 尝试各自成行。运行态与持久化记录原位合并(`durableRequestId` 关联),\n * 终态不被迟到的进度降级。 */\nexport interface RequestDetailView {\n /** 一次真实尝试的稳定 UI 身份(process epoch + session + turn/step +\n * attempt,或持久化 request id),从不用数组下标。 */\n id: string\n /** 对应持久化 UsageRecord 的 request id;合并锚点,缺失时该行只存在于\n * 运行态。 */\n durableRequestId?: string\n sessionId: string\n state: RequestDetailState\n kind: 'request' | 'compaction' | 'failure' | 'aux'\n /** Auxiliary subtype when the host proved this request belongs to the\n * current session (for example `session-title`). */\n auxKind?: AuxKind\n /** Plain-request rows only: the compaction events (prune clusters and\n * summaries) that landed since the session's previous plain request — the\n * hit-cell tooltip's rewrite explanation. Annotation only: it never enters\n * {@link RequestDetailCache} or moves any cache band. Absent on legacy\n * rows and unattributed requests. */\n compactionAttribution?: readonly CompactionAttributionItem[]\n /** Canonical model id after the pricing table's alias / regex resolution. */\n modelId?: string\n /** 请求路由的模型(计费身份)。 */\n requestedModel: string\n /** provider 实际响应的模型(别名路由可不同);缺失时以请求模型展示。 */\n responseModel?: string\n /** 实时观察到的尝试开始时刻(epoch ms);历史行缺失。 */\n startedAt?: number\n /** 实时观察到的结算时刻(epoch ms);历史行缺失。 */\n settledAt?: number\n /** 持久化记录的会话事件时间;旧记录只有它时保留其原义(非启动时刻)。 */\n recordTime?: number\n /** 展示排序锚点:实时行取 startedAt,历史行取 recordTime。 */\n orderAt: number\n orderBasis: 'start' | 'record'\n /** 未缓存输入 token;绝不改写成总 prompt。 */\n inputTokens?: number\n outputTokens?: number\n /** 缓存读;显式 0 保留为 0,未报告时缺失(与 0 严格区分)。 */\n cacheReadTokens?: number\n cacheWriteTokens?: number\n /** 请求发出至结算的耗时(成功/失败尝试的独立计时;step 级历史计时时为\n * 该记录的原口径)。 */\n latencyMs?: number\n /** 首个非空模型增量(含推理/工具参数)距开始的毫秒;整包返回或缺失时无。 */\n firstTokenLatencyMs?: number\n /** 运行中请求的已耗时,锚定服务端快照(asOf - startedAt),客户端不跑秒表。 */\n elapsedMs?: number\n /** 结算后的单次解码速度(tokens/s,服务端按生成时长 ≥500ms 的可信流式\n * 样本门计算);整包返回、output 为 0、计时无效或缺失时缺失——客户端\n * 绝不用会话均值、字符数或 chunk 数补位。 */\n speed?: number\n /** 失败行 provider 中立的失败码(LlmFailure.code)。 */\n failureCode?: string\n /** 本请求计费(¥,wire 币种不变);未定价时缺失。 */\n cost?: number\n pricingStatus: 'priced' | 'unpriced' | 'unknown'\n cache: RequestDetailCache\n}\n\n/**\n * 会话级对话状态:最新一轮 turn 的收尾情况。它描述「对话现在走到哪了」,\n * 而不是某一次请求的生命周期。\n * - `awaiting-tool`:模型已发起工具调用、结果尚未回来(对话未完,正在等工具)。\n * - `turn-complete`:本轮 turn 已正常结束且没有待返回的工具结果(本轮对话已完成)。\n * - `retrying`:上一次请求失败,系统正在退避后重试(对话未完,还在重试)。\n */\nexport type ConversationState = 'awaiting-tool' | 'turn-complete' | 'retrying'\n\n/**\n * 会话级对话状态及其细节。状态是稳定枚举,细节只带计数与失败码这类\n * 无载荷事实,绝不携带 prompt 或正文。\n */\nexport interface ConversationStatus {\n state: ConversationState\n /** 仅 `retrying`:第几次重试、共几次、退避时长与失败码。 */\n retry?: {\n count: number\n max: number\n delayMs: number\n code?: string\n }\n}\n\n/** 会话用量页请求池快照:已按范围过滤、去重后选取的最多 20 条请求。\n * `items[0]` 优先取当前范围最新发起的活动请求(waiting / streaming),\n * 无活动请求时取最新发起的一条;选取在截断前完成。\n * `items.slice(1)` 按开始时间倒序,且不重复顶部请求。\n * `activeCount` 是当前范围全部进行中的请求数,可能超过展示窗。 */\nexport interface SessionRequestDetails {\n items: readonly RequestDetailView[]\n limit: number\n /** 本次快照的服务端时间(epoch ms),不是请求发起时间。 */\n asOf: number\n activeCount: number\n /** 实时能力档位:`lifecycle` = 可见等待/生成中生命周期与完成后可信单次\n * 速度;`token-progress` = 另有生成中可信累计 token 计数(当前协议无此\n * 路由,运行中行恒无 token/速度);`settled-only` = 仅结算记录。 */\n liveCapability: 'lifecycle' | 'token-progress' | 'settled-only'\n /** 头条请求(`items[0]`)所属会话的对话状态;缺失表示没有结论(本轮仍在\n * 进行中,或插件进程尚未观察到该会话的事件)。 */\n conversation?: ConversationStatus\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 Omit<CostedSummary, 'bySession'> {\n currency: DisplayCurrency\n usdExchangeRate: number\n /** Route key → latest display name from the data directory's\n * `providers.json` registry; a key with no entry (or a missing registry)\n * displays as the key itself. Absent on older host payloads. */\n providerNames?: Readonly<Record<string, string>>\n /** Whole-scope payloads only: the settings page's session table rows\n * (see {@link SessionUsageRow}); absent on session-scoped reads. */\n sessionRows?: readonly SessionUsageRow[]\n /** Whole-scope complete projects; absent on older host payloads. */\n projectRows?: readonly ProjectUsageRow[]\n requestSeries?: readonly RequestPoint[]\n children?: Readonly<Record<string, ChildUsageSummary>>\n sessionIds?: readonly string[]\n /** Session-scoped `fields=session` reads only: the live request pool\n * (最新请求 / 实时请求). Absent on `chip` and whole-log `full` reads —\n * the pool is the usage tab's view, never a settings-page concern. */\n requestDetails?: SessionRequestDetails\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. `other` carries a window whose name fits no known period (a\n * gateway's open window vocabulary: \"Credits\", \"Allowance\") — display\n * leans on {@link QuotaWindow.name}, and only the granularity rank treats\n * it generically. Display adapts by tier (progress bar vs amount). */\nexport type QuotaTier = 'five_hour' | 'weekly' | 'monthly' | 'other' | '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 /** Which DeepSeek account purse a balance window came from. Absent on\n * API-key balances, which stay a single unlabeled amount. */\n balanceKind?: 'recharge' | 'bonus'\n /** The vendor's own name of the window (\"Credits\", \"Allowance\"), when it\n * fits no known period tier; the panel's column label prefers it over\n * the generic `other` copy. Absent on windows a tier already names. */\n name?: string\n /** The quota CARD a window belongs to when one payload aggregates\n * several (a gateway summarizing its whole upstream fleet): the card's\n * display title (vendor · plan · account), which the panel renders as a\n * section heading. Absent on single-source payloads. */\n card?: string\n /** The quota POOL a window belongs to: windows sharing a pool draw on\n * interchangeable budgets of ONE vendor family (a gateway's several keys\n * of the same account family, each with its own meter but serving the\n * same traffic). Only same-pool windows may be pooled into one water\n * level — two vendors' same-named windows are not the same budget.\n * Absent on single-source payloads (nothing to pool). */\n pool?: string\n}\n\n/** Why a quota query failed, normalized so the panel can pick friendly copy. */\nexport type QuotaErrorKind = 'auth' | 'no-credential' | 'signed-out' | '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 { DirectoryGuardView } from '../wire.ts'\nimport { DIR_GUARD_PATH, MIGRATION_PATH } from '../wire.ts'\n\n/**\n * Minimal snapshot contract of a configuration form (the host's\n * ConfigFormSnapshot shape, as this package consumes it).\n */\nexport interface CardFormTargetSnapshot<T = SectionValue> {\n /** Loading, ready, or unavailable state. */\n status: 'loading' | 'ready' | 'unavailable'\n /** Resolved section value. */\n value?: T\n /** Raw user override layer, if present. */\n user?: unknown\n /** Whether the scope accepts writes. */\n writable: boolean\n}\n\n/**\n * The configuration source backing the card: the host's `ConfigForm<T>` for\n * the `token-usage` namespace.\n */\nexport interface CardFormTarget<T = SectionValue> {\n /** Current snapshot view. */\n getSnapshot(): CardFormTargetSnapshot<T>\n /** Subscribe to snapshot changes. Returns disposer. */\n subscribe(listener: () => void): () => void\n /** Write one scalar field. */\n set(field: string, value: unknown): Promise<boolean>\n /** Clear one scalar field back to inherited configuration. */\n unset(field: string): Promise<boolean>\n}\n\n/** Placeholder target while the configForms service has not mounted (or its\n * describe mirror does not serve this namespace yet); the card renders\n * nothing and never throws. */\nexport function createFallbackTarget(): CardFormTarget<SectionValue> {\n return {\n getSnapshot: () => ({\n status: 'unavailable',\n writable: false,\n }),\n subscribe: () => () => {},\n set: async () => false,\n unset: async () => false,\n }\n}\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 sidebarPinned?: boolean\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 /** Whether the usage entry is pinned as a resident sidebar row: the\n * effective (resolved) value the checkbox shows when untouched. */\n sidebarPinned: boolean\n /** Staged pin toggle; undefined while untouched. A staged edit shows in\n * the checkbox and commits only on save. */\n pinnedDraft: boolean | undefined\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 TEXT field holds an unsaved edit. The pricing-sync gate reads\n * this, not `dirty`: the staged pin toggle has no say over the pricing\n * source, so it must not block a sync. */\n textDirty: 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 the sidebar-pin toggle; it commits only on save. */\n editPinned: (value: boolean) => 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 /** Staged sidebar-pin toggle; undefined while untouched. */\n private draftPinned: boolean | undefined\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 target - the configuration source backing the card (a ConfigForm).\n */\n constructor(private readonly target: CardFormTarget<SectionValue>) {\n this.snapshotValue = this.project()\n target.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 editPinned: (value) => {\n this.draftPinned = value\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.draftPinned === undefined && !this.failed) return\n this.drafts = {}\n this.draftPinned = undefined\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 // The staged pin toggle rides the same save; it writes an explicit\n // true/false (never unset) so a composition-layer `true` can still be\n // switched off from the card.\n const pinEdit = this.draftPinned\n if ((edited.length === 0 && pinEdit === undefined) || 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.target.unset(field)\n else await this.target.set(field, text)\n }\n if (pinEdit !== undefined) await this.target.set('sidebarPinned', pinEdit)\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 if (pinEdit !== undefined && this.storedValue('sidebarPinned') !== pinEdit) landed = false\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 this.draftPinned = undefined\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(): CardFormTargetSnapshot<SectionValue> {\n return this.target.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: string): 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 pinnedEffective = snapshot.value?.sidebarPinned === true\n const fields = {} as Record<CardField, string>\n const overridden = {} as Record<CardField, boolean>\n let textDirty = 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 textDirty = true\n }\n }\n return {\n available: snapshot.status === 'ready',\n writable: snapshot.writable,\n sidebarPinned: pinnedEffective,\n pinnedDraft: this.draftPinned,\n fields,\n overridden,\n dirty: textDirty || (this.draftPinned !== undefined && this.draftPinned !== pinnedEffective),\n textDirty,\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.scopeKey - the data range the on-screen snapshot belongs\n * to (e.g. the scoped session ids). A snapshot is only kept WITHIN the\n * range that produced it: while a new range's fetch is in flight the old\n * figures stay on screen (no flash), but if that fetch FAILS the kept value\n * belongs to another range — the hook lands in `error` instead of showing\n * the old range's rows as if they were the current one's. Same-key refresh\n * failures keep the silent semantics.\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; scopeKey?: string },\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 // The kept snapshot belongs to the range captured by its own request.\n const valueScopeRef = useRef(options.scopeKey)\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 // Capture the range for this request. A later render may switch scope\n // while the fetch is pending; its result must never be attributed to the\n // newer range through a mutable ref.\n const requestScope = options.scopeKey\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. A range switch keeps the old figures visible\n // while the new range's fetch runs — and silently drops them if that\n // fetch fails (see the catch below).\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 valueScopeRef.current = requestScope\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 — but\n // only data of the range on screen. Another range's snapshot would\n // misattribute its rows (and its stale stamp) to the new range.\n if (silent && loadedRef.current && valueScopeRef.current === requestScope) 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, options.scopeKey])\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 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/** A month the calendar panel shows (month is 0-based like Date). */\nexport interface MonthView {\n year: number\n month: number\n}\n\n/** The month view holding one day key. */\nexport function monthViewOf(dayKey: string): MonthView {\n return { year: Number(dayKey.slice(0, 4)), month: Number(dayKey.slice(5, 7)) - 1 }\n}\n\n/** The month view shifted by whole months (year overflow normalized). */\nexport function shiftMonth(view: MonthView, deltaMonths: number): MonthView {\n const total = view.year * 12 + view.month + deltaMonths\n return { year: Math.floor(total / 12), month: ((total % 12) + 12) % 12 }\n}\n\n/** One cell of a month grid: a day key plus whether it belongs to the shown month. */\nexport interface MonthCell {\n day: string\n inMonth: boolean\n}\n\n/**\n * The month grid of one month view: Monday-first whole weeks covering the\n * month, so every column aligns under its weekday header. Days of the\n * neighbouring months carry `inMonth: false` — the caller renders them as\n * blank placeholders, keeping the shown month's date texts unique (for\n * tests and screen readers).\n */\nexport function monthGrid(view: MonthView): MonthCell[] {\n // Local-time constructors only: string parsing would drag UTC offsets in.\n const leading = (new Date(view.year, view.month, 1).getDay() + 6) % 7\n const daysInMonth = new Date(view.year, view.month + 1, 0).getDate()\n const total = Math.ceil((leading + daysInMonth) / 7) * 7\n const cells: MonthCell[] = []\n for (let index = 0; index < total; index++) {\n const cursor = new Date(view.year, view.month, 1 - leading + index)\n cells.push({\n day: dayKeyOf(cursor),\n inMonth: cursor.getFullYear() === view.year && cursor.getMonth() === view.month,\n })\n }\n return cells\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 * The provider display-label rule, shared by the host side and the browser\n * side. It is a pure function with no IO, so both halves can import it\n * without dragging a registry along.\n *\n * @module token-usage/provider-label\n */\n\n/** Route key → latest display name. Absent keys are not stored as empty strings. */\nexport type ProviderNameIndex = Record<string, string>\n\n/**\n * Label for a route key. The name registry wins; a missing or empty entry\n * falls back to the key itself, so a route the registry never saw still\n * displays. A route without a name is not an error — the registry is a\n * convenience, the route key is the identity.\n * @param id - the route key.\n * @param names - the name registry, when the caller has one.\n * @returns the display name, or the route key itself.\n */\nexport function providerLabel(id: string, names?: Readonly<ProviderNameIndex>): string {\n const name = names?.[id]\n return name !== undefined && name !== '' ? name : id\n}\n","/**\n * Browser-side display formatting of the token-usage settings page: token\n * abbreviation (K/M/B), the cache hit rate, 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 $), and the failure-pill\n * tooltip labels. Pure functions only, shared by the section and the\n * trend chart.\n *\n * @module token-usage/client/format\n */\n\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { UsageAuxKindRow, UsageSummary, UsageTotals } from '../wire.ts'\nimport type { TokenUsageKey } from './locales.ts'\n\n/** Known `LlmFailure.code`s that have a `fail.*` locale label. An unknown\n * future code is not in this map and the tooltip renders it verbatim. */\nconst FAILURE_CODE_LABEL_KEYS = {\n ABORTED: 'fail.ABORTED',\n AUTH: 'fail.AUTH',\n CONTEXT_WINDOW_EXCEEDED: 'fail.CONTEXT_WINDOW_EXCEEDED',\n EMPTY_RESPONSE: 'fail.EMPTY_RESPONSE',\n FILES_API: 'fail.FILES_API',\n INVALID_CREDENTIAL: 'fail.INVALID_CREDENTIAL',\n INVALID_REQUEST: 'fail.INVALID_REQUEST',\n MALFORMED_RESPONSE: 'fail.MALFORMED_RESPONSE',\n MISSING_CREDENTIAL: 'fail.MISSING_CREDENTIAL',\n QUOTA: 'fail.QUOTA',\n RATE_LIMIT: 'fail.RATE_LIMIT',\n REQUEST_EXTENSION: 'fail.REQUEST_EXTENSION',\n SERVER: 'fail.SERVER',\n STREAM_CLOSED: 'fail.STREAM_CLOSED',\n TIMEOUT: 'fail.TIMEOUT',\n TRANSPORT: 'fail.TRANSPORT',\n UNKNOWN: 'fail.UNKNOWN',\n} as const satisfies Record<string, TokenUsageKey>\n\n/** Display label of a provider route key: the payload's name registry\n * (route key → latest display name) wins; a missing or empty entry falls\n * back to the key itself, so a route the registry never saw still shows.\n * The rule is shared with the host side (`src/provider-label.ts`). */\nexport { providerLabel } from '../provider-label.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. The CNY sign is the\n * fullwidth ¥ (U+FFE5) — the standard RMB glyph in a Chinese UI, and the\n * suffix the number-first cost idiom reads naturally with. */\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: two decimals plus the view's symbol SUFFIXED —\n * `1.25¥` — matching the dock row's number-first unit idiom (`12.2M tok`,\n * `98%`), where every reading leads with its magnitude. USD divides the\n * wire's RMB amount by the exchange rate (`0.18$` under a rate-7 view).\n * A cost is always shown, never omitted.\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 `${(cost / view.rate).toFixed(2)}${view.symbol}`\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/**\n * One request's cache-hit rate as display text, for the usage tab's request\n * pool ONLY: at most one decimal (`49.96%` → `50%` — the rounding that the\n * raw-value-first policy must see through). Undefined renders `—` (unknown,\n * never 0%). The global `hitRateDisplay` keeps summarizing whole sessions.\n * @param rate - the raw [0,1] rate, or undefined when unknown.\n */\nexport function formatRequestRate(rate: number | undefined): string {\n if (rate === undefined || !Number.isFinite(rate)) return '—'\n return `${percent(rate * 100)}%`\n}\n\n/**\n * A full-precision rate text for tooltips: two decimals (`49.96%`), so a\n * displayed `50%` that is actually below the threshold can explain itself.\n */\nexport function formatRequestRateExact(rate: number): string {\n return `${(rate * 100).toFixed(2)}%`\n}\n\n/**\n * Time-of-day text for a request-pool row (`15:45:08`, locale-independent\n * zero-padded) — the compact column form the 11-column table needs.\n * @param ms - epoch milliseconds.\n */\nexport function formatTimeOfDay(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())}:${pad(date.getSeconds())}`\n}\n\n/**\n * The failure pill's hover tooltip text: one `label ×count` line per failure\n * class, largest count first (code name ascending breaks ties), newline-joined —\n * the shell Tooltip renders `pre-line`, so each line lands on its own row.\n * Known `LlmFailure.code`s map through `fail.*` locale keys (限流 / Rate\n * limited); an unknown future code renders verbatim. A legacy shape without\n * the breakdown, or an empty map, yields '' and the caller suppresses the\n * tooltip.\n * @param byCode - the per-code failure counts from the totals (may be undefined).\n * @param t - locale lookup; codes without a `fail.*` key stay verbatim.\n * @returns the multi-line tooltip label, or '' when there is nothing to show.\n */\nexport function failuresTooltip(\n byCode: Record<string, number> | undefined,\n t: TranslateNS<'token-usage'>,\n): string {\n if (byCode === undefined) return ''\n return Object.entries(byCode)\n .filter(([, count]) => count > 0)\n .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))\n .map(([code, count]) => `${failureCodeLabel(code, t)} ×${count}`)\n .join('\\n')\n}\n\n/** Locale label for one failure code; unknown codes stay verbatim. */\nfunction failureCodeLabel(code: string, t: TranslateNS<'token-usage'>): string {\n if (Object.hasOwn(FAILURE_CODE_LABEL_KEYS, code)) {\n return t(FAILURE_CODE_LABEL_KEYS[code as keyof typeof FAILURE_CODE_LABEL_KEYS])\n }\n return code\n}\n\n/**\n * The overhead pill's hover tooltip text: one `label ×count` line per\n * auxiliary kind, count descending, newline-joined — the same shape as\n * {@link failuresTooltip}. An absent breakdown yields '' and the caller\n * suppresses the tooltip (the pill itself still shows its count).\n * @param byKind - the per-kind rows of the aux summary (may be undefined).\n * @param t - locale lookup (`aux.kind.*`; the kind is a closed union, so\n * every value has a key).\n * @returns the multi-line tooltip label, or '' when there is nothing to show.\n */\nexport function overheadTooltip(\n byKind: readonly UsageAuxKindRow[] | undefined,\n t: TranslateNS<'token-usage'>,\n): string {\n if (byKind === undefined) return ''\n return byKind\n .filter(row => row.totals.requests > 0)\n .sort((left, right) => right.totals.requests - left.totals.requests)\n .map(row => `${t(`aux.kind.${row.auxKind}`)} ×${row.totals.requests.toLocaleString()}`)\n .join('\\n')\n}\n","import type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AssociationStorageError, CostState, PricingUnavailableReason } from '../wire.ts'\n\nexport function costsAvailable(state?: CostState): boolean {\n return state === undefined || state === 'ready'\n}\n\n/** Shared failure reasons; matching and prices remain entirely on the host. */\nexport function PricingStatus({ costState, pricingUnavailableReason, associationStorageError, t }: {\n costState?: CostState | undefined\n pricingUnavailableReason?: PricingUnavailableReason | undefined\n associationStorageError?: AssociationStorageError | undefined\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const storageWarning = associationStorageError !== undefined\n ? <p role=\"status\">{t('pricing.associationStorageUnavailable')}</p> : null\n const costWarning = !costsAvailable(costState)\n ? <p role=\"status\">{t(costState === 'history-incomplete' ? 'pricing.historyIncomplete' : 'pricing.unavailable')}\n {costState === 'pricing-unavailable' && pricingUnavailableReason !== undefined ? ` ${t(`pricing.reason.${pricingUnavailableReason}`)}` : ''}\n </p> : null\n return <>{storageWarning}{costWarning}</>\n}\n","import type { ModelResolution } from './wire.ts'\n\nexport interface ModelIdentity {\n modelId: string\n aliasPatterns?: readonly string[]\n}\n\n/** Full-name comparison only: spelling remains intact in records and displays. */\nexport const modelKey = (name: string): string => name.toLowerCase()\n\nexport function providerSuffix(name: string): string | undefined {\n const parts = name.split('/')\n return parts.length > 1 && parts.every(part => part !== '') ? parts.at(-1) : undefined\n}\n\n/** Parse the upstream portable subset rather than accepting arbitrary JS regex. */\nexport function compileAliasPattern(pattern: string): RegExp {\n if (!pattern.startsWith('^') || !pattern.endsWith('$')) throw new Error('alias pattern requires ^ and $')\n const body = pattern.slice(1, -1)\n let offset = 0\n function expression(depth: number): void {\n if (depth > 32) throw new Error('alias pattern nesting is too deep')\n let atoms = 0\n while (offset < body.length && body[offset] !== ')') {\n const char = body[offset++]!\n if (char === '|') {\n if (atoms === 0) throw new Error('empty alias pattern branch')\n atoms = 0\n continue\n }\n if (char === '(') {\n expression(depth + 1)\n if (body[offset++] !== ')') throw new Error('unclosed alias pattern group')\n } else if (char === '\\\\') {\n const literal = body[offset++]\n if (literal === undefined || /[A-Za-z0-9\\s]/.test(literal)) throw new Error('alias patterns allow escaped punctuation only')\n } else if (!/[A-Za-z0-9_/:\\-]/.test(char)) {\n throw new Error('unsupported alias pattern syntax')\n }\n atoms++\n if (body[offset] === '?') offset++\n }\n if (atoms === 0) throw new Error('empty alias pattern branch')\n }\n expression(0)\n if (offset !== body.length) throw new Error('unbalanced alias pattern group')\n return new RegExp(pattern, 'i')\n}\n\n/** `$` also accepts a trailing newline in JS; require a full-span match. */\nexport function matchesAliasPattern(regex: RegExp, name: string): boolean {\n const match = regex.exec(name)\n return match !== null && match.index === 0 && match[0].length === name.length\n}\n\nexport function validateModelIdentities(models: readonly ModelIdentity[]): void {\n const ids = new Set<string>()\n for (const model of models) {\n const key = modelKey(model.modelId)\n if (ids.has(key)) throw new Error(`duplicate modelId: ${model.modelId}`)\n ids.add(key)\n const patterns = model.aliasPatterns ?? []\n if (new Set(patterns).size !== patterns.length) throw new Error(`duplicate aliasPatterns: ${model.modelId}`)\n for (const pattern of patterns) compileAliasPattern(pattern)\n }\n}\n\nexport function createModelResolver(models: readonly ModelIdentity[]): (name: string) => ModelResolution {\n validateModelIdentities(models)\n const ids = new Map<string, Set<string>>()\n const patterns: Array<{ modelId: string; regex: RegExp }> = []\n const add = (index: Map<string, Set<string>>, name: string, id: string): void => {\n const key = modelKey(name)\n const hits = index.get(key) ?? new Set<string>()\n hits.add(id)\n index.set(key, hits)\n }\n for (const model of models) {\n add(ids, model.modelId, model.modelId)\n for (const pattern of model.aliasPatterns ?? []) patterns.push({ modelId: model.modelId, regex: compileAliasPattern(pattern) })\n }\n const cache = new Map<string, ModelResolution>()\n return (rawName): ModelResolution => {\n const cached = cache.get(rawName)\n if (cached !== undefined) return cached\n const suffix = providerSuffix(rawName)\n const resultOf = (hits: Set<string>, method: NonNullable<ModelResolution['method']>, strippedPrefix: boolean): ModelResolution => {\n const candidates = [...hits].sort()\n return candidates.length === 1\n ? { rawName, status: 'matched', modelId: candidates[0]!, method, strippedPrefix, candidates: [] }\n : { rawName, status: 'ambiguous', method, strippedPrefix, candidates }\n }\n let result: ModelResolution | undefined\n for (const [candidate, normalized] of [[rawName, false], ...(suffix === undefined ? [] : [[suffix, true]])] as Array<[string, boolean]>) {\n const idHits = ids.get(modelKey(candidate))\n if (idHits !== undefined) result = resultOf(idHits, normalized ? 'normalized-id' : 'id', normalized)\n if (result !== undefined) break\n }\n if (result === undefined && rawName !== '') {\n const hits = new Set<string>()\n let strippedPrefix = false\n for (const { modelId, regex } of patterns) {\n for (const candidate of suffix === undefined ? [rawName] : [rawName, suffix]) {\n if (matchesAliasPattern(regex, candidate)) {\n hits.add(modelId)\n if (candidate !== rawName) strippedPrefix = true\n }\n }\n }\n if (hits.size > 0) result = resultOf(hits, 'pattern', strippedPrefix)\n }\n result ??= { rawName, status: 'unmatched', strippedPrefix: false, candidates: [] }\n cache.set(rawName, result)\n return result\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) holding that model's full price table — billing\n * conditions (default / context tiers / peak slots / time rules) × the four\n * per-million rates, converted for a USD view. Shared by the settings\n * page's per-model “定价” affordance and the pricing-overview dialog's\n * drill-in rows; a native showModal naturally stacks a second instance\n * above the overview.\n *\n * @module token-usage/client/PricingDialog\n */\n\nimport { useEffect, useRef } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ContextTier, DailySlot, ModelPricing, ModelRates, RateWindow } from '../wire.ts'\nimport { dayKeyOf } from './day.ts'\nimport { formatRate, formatRateWithSymbol, formatTokens } from './format.ts'\nimport type { CurrencyView } from './format.ts'\nimport styles from './PricingDialog.module.css'\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. */\nexport function 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). */\nexport function 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. The structure mirrors\n * {@link resolveRate}'s node chain.\n */\nexport function 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 (the current era)\n // first, then each time rule as an isolated price world, newest era\n // first (descending rule end), regardless of the feed's listing order.\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]\n .sort((a, b) => b.endTime - a.endTime)\n .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. Mounts only while a model is selected;\n * every close path funnels through the dialog's `close` event, which clears\n * the selection and unmounts it.\n */\nexport function 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 // The backdrop-close press guard: a text-selection drag released outside\n // the dialog lands its click on the dialog element (the click fires on\n // the press/release targets' common ancestor, and outside a top-layer\n // dialog every point resolves to the dialog) — the same target a real\n // backdrop click produces. Only a press that began on the backdrop may\n // close; see the overview dialog's backdropPress for the full story.\n const backdropPress = useRef(false)\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 // but only when the press started there too: a selection drag\n // released outside produces the same click target.\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => {\n if (event.target === dialogRef.current && backdropPress.current) dialogRef.current?.close()\n }}\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","import { useEffect, useRef } from 'react'\nimport type { ModelResolution, PricingAssociationsPayload } from '../wire.ts'\n\nconst CHANGED_EVENT = 'token-usage:pricing-associations-changed'\nconst TABLE_CHANGED_EVENT = 'token-usage:pricing-table-changed'\n\n/** All mounted usage views refresh their existing query after a real commit. */\nexport function pricingAssociationsChanged(): void { window.dispatchEvent(new Event(CHANGED_EVENT)) }\nexport function pricingTableChanged(): void { window.dispatchEvent(new Event(TABLE_CHANGED_EVENT)) }\n\nexport function usePricingAssociationRefresh(refresh: () => void): void {\n const latest = useRef(refresh)\n latest.current = refresh\n useEffect(() => {\n const changed = (): void => { latest.current() }\n window.addEventListener(CHANGED_EVENT, changed)\n window.addEventListener(TABLE_CHANGED_EVENT, changed)\n return () => {\n window.removeEventListener(CHANGED_EVENT, changed)\n window.removeEventListener(TABLE_CHANGED_EVENT, changed)\n }\n }, [])\n}\n\nexport class AssociationRequestError extends Error {\n constructor(readonly code: string, readonly current?: PricingAssociationsPayload) { super(code) }\n}\n\n/** Optional pricing references and the current feed version; no usage or credentials. */\nexport function pricingIssueUrl(resolution: ModelResolution, version?: number): string {\n const lines = [\n '1. Pricing reference (optional)',\n ' - Currency:',\n ' - Input price per 1 million tokens:',\n ' - Output price per 1 million tokens:',\n ' - Cache read price per 1 million tokens:',\n ' - Cache write price per 1 million tokens:',\n ' - Context window (tokens):',\n '',\n '2. Official pricing URL (optional)',\n ' - URL:',\n '',\n '3. Current pricing table version',\n ` - ${version ?? 'Unknown'}`,\n ]\n const url = new URL('https://github.com/LaoYueHanNi/model-price-table/issues/new')\n url.searchParams.set('title', `Add model pricing: ${resolution.rawName}`)\n url.searchParams.set('body', lines.join('\\n'))\n return url.href\n}\n","import { createContext, useContext, useEffect, useId, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { ASSOCIATIONS_PATH, PRICING_PATH } from '../wire.ts'\nimport type { ModelResolution, PricingAssociationStatus, PricingAssociationsPayload, PricingOverviewModel, PricingOverviewPayload } from '../wire.ts'\nimport { modelKey } from '../model-resolution.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport type { CurrencyView } from './format.ts'\nimport { currencyViewOf } from './format.ts'\nimport { PricingDialog } from './PricingDialog.tsx'\nimport { AssociationRequestError, pricingAssociationsChanged, pricingIssueUrl } from './pricing-associations.ts'\nimport shared from './PricingDialog.module.css'\nimport styles from './PricingAssociations.module.css'\n\ninterface AssociationUi { open(source?: string): void; showUnpriced(resolution: ModelResolution): void; resolutions: readonly ModelResolution[]; feedVersion?: number }\nconst AssociationUiContext = createContext<AssociationUi | null>(null)\n\nexport function PricingAssociationProvider({ resolutions = [], feedVersion, view, t, children }: {\n resolutions?: readonly ModelResolution[] | undefined; feedVersion?: number | undefined\n view: CurrencyView; t: TranslateNS<'token-usage'>; children: ReactNode\n}): ReactNode {\n const [source, setSource] = useState<string | null | undefined>(undefined)\n const [unpriced, setUnpriced] = useState<ModelResolution | null>(null)\n const opener = useRef<HTMLElement | null>(null)\n const rememberOpener = (): void => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null }\n return <AssociationUiContext.Provider value={{ open: name => { rememberOpener(); setSource(name ?? null) },\n showUnpriced: resolution => { rememberOpener(); setUnpriced(resolution) }, resolutions,\n ...(feedVersion !== undefined ? { feedVersion } : {}) }}>\n {children}\n {unpriced !== null && <UnpricedModelDialog resolution={unpriced} version={feedVersion} t={t}\n onClose={() => setUnpriced(null)} onAssociate={() => { setUnpriced(null); setSource(unpriced.rawName) }} />}\n {source !== undefined && <PricingAssociationDialog initialSource={source} returnFocus={opener.current} view={view} t={t} onClose={() => setSource(undefined)} />}\n </AssociationUiContext.Provider>\n}\n\n/** Entry remains available even when the usage filter has no rows. */\nexport function PricingAssociationManagerButton({ t, onOpen }: { t: TranslateNS<'token-usage'>; onOpen?: () => void }): ReactNode {\n const ui = useContext(AssociationUiContext)\n const open = onOpen ?? (ui === null ? undefined : () => ui.open())\n return open === undefined ? null : <button type=\"button\" data-pricing-association-manager className={styles.button} onClick={open}>{t('association.manage')}</button>\n}\n\nexport function PricingIssueLink({ resolution, version, t }: { resolution: ModelResolution; version?: number | undefined; t: TranslateNS<'token-usage'> }): ReactNode {\n return <a className={styles.link} href={pricingIssueUrl(resolution, version)} target=\"_blank\" rel=\"noopener noreferrer\">{t('association.issue')}</a>\n}\n\nexport function UnpricedModelTag({ model, t }: { model: string; t: TranslateNS<'token-usage'> }): ReactNode {\n const ui = useContext(AssociationUiContext)\n const resolution = ui?.resolutions.find(row => modelKey(row.rawName) === modelKey(model))\n ?? { rawName: model, status: 'unmatched' as const, strippedPrefix: false, candidates: [] }\n return <button type=\"button\" className={styles.unpricedTag} aria-haspopup=\"dialog\"\n disabled={ui === null || model === ''} onClick={() => ui?.showUnpriced(resolution)}>{t('pricing.unpriced')}</button>\n}\n\nfunction UnpricedModelDialog({ resolution, version, t, onClose, onAssociate }: {\n resolution: ModelResolution; version?: number | undefined; t: TranslateNS<'token-usage'>\n onClose: () => void; onAssociate: () => void\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n const backdropPress = useRef(false)\n const opener = useRef<HTMLElement | null>(document.activeElement instanceof HTMLElement ? document.activeElement : null)\n useEffect(() => {\n dialogRef.current?.showModal()\n return () => { if (opener.current?.isConnected) opener.current.focus() }\n }, [])\n const automatic = resolution.automatic ?? resolution\n return <dialog ref={dialogRef} className={`${shared.dialog} ${styles.unpricedDialog}`} aria-label={t('association.unpricedTitle')}\n onClose={event => { if (event.target === dialogRef.current) onClose() }}\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => { if (event.target === dialogRef.current && backdropPress.current) dialogRef.current?.close() }}\n onKeyDown={event => { if (event.key === 'Escape') event.stopPropagation() }}>\n <div className={shared.dialogHead}>\n <h2 className={shared.dialogTitle}>{t('association.unpricedTitle')}</h2>\n <button type=\"button\" className={shared.dialogClose} aria-label={t('association.close')} onClick={() => dialogRef.current?.close()}>✕</button>\n </div>\n <p className={styles.name}>{resolution.rawName}</p>\n {automatic.status === 'ambiguous' && <p className={styles.note}>{t('pricing.ambiguous', { models: automatic.candidates.join(', ') })}</p>}\n <div className={styles.actions}>\n <button type=\"button\" className={styles.button} onClick={onAssociate}>{t('association.choose')}</button>\n <PricingIssueLink resolution={resolution} version={version} t={t} />\n </div>\n </dialog>\n}\n\n/** Show original associated IDs on hover without expanding the statistics row. */\nexport function ModelAssociationBadge({ model, t }: { model: string; t: TranslateNS<'token-usage'> }): ReactNode {\n const ui = useContext(AssociationUiContext)\n if (ui === null || model === '') return null\n const names = ui.resolutions.filter(row => modelKey(row.modelId ?? row.rawName) === modelKey(model))\n const associated = names.filter(row => row.association !== undefined)\n if (associated.length === 0) return null\n const label = t('association.tooltip', { models: associated.map(row => row.rawName).join(', ') })\n return <span className={styles.badgeWrap}><Tooltip label={label} side=\"top\" delayMs={100}>\n <span className={styles.badge} role=\"img\" aria-label={label} tabIndex={0}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"6\" stroke=\"currentColor\" />\n <path d=\"M6.5 6a1.5 1.5 0 0 1 3 0c0 1-1.5 1-1.5 2.5\" stroke=\"currentColor\" strokeLinecap=\"round\" />\n <circle cx=\"8\" cy=\"10.5\" r=\".7\" fill=\"currentColor\" />\n </svg>\n </span>\n </Tooltip></span>\n}\n\nfunction AssociationStatus({ row, t }: { row: PricingAssociationStatus; t: TranslateNS<'token-usage'> }): ReactNode {\n return <p className={styles.note}>\n {t(`association.state.${row.state}`)}\n {row.state === 'automatic-takeover' && <>{' '}{t('association.automaticTarget', { model: row.automaticModelId ?? '' })}\n {row.targetDiffers && <>{' '}{t('association.targetDiffers', { model: row.targetModelId })}</>}\n {' '}{t('association.reactivate')}</>}\n </p>\n}\n\nasync function readJson<T>(url: string, signal: AbortSignal): Promise<T> {\n const response = await fetch(url, { signal, cache: 'no-store' })\n if (!response.ok) throw new Error(`HTTP ${response.status}`)\n return response.json() as Promise<T>\n}\n\nfunction checkAssociations(value: PricingAssociationsPayload): PricingAssociationsPayload {\n if (value === null || typeof value !== 'object' || typeof value.directoryToken !== 'string'\n || !['ready', 'unavailable'].includes(value.storageState) || !Array.isArray(value.associations)\n || typeof value.pricingAvailable !== 'boolean' || typeof value.writesPaused !== 'boolean'\n || (value.storageState === 'ready' && (!Number.isSafeInteger(value.revision) || value.revision! < 0))\n || value.associations.some(row => row === null || typeof row.sourceModel !== 'string' || typeof row.targetModelId !== 'string')) {\n throw new Error('unexpected association response')\n }\n return value\n}\n\nfunction checkPricing(value: PricingOverviewPayload): PricingOverviewPayload {\n if (value === null || typeof value !== 'object' || !Array.isArray(value.models)\n || value.models.some(row => row === null || typeof row.modelId !== 'string'\n || !Array.isArray(row.aliasPatterns) || !row.aliasPatterns.every((pattern: unknown) => typeof pattern === 'string') || row.rules?.base === undefined)) {\n throw new Error('unexpected pricing response')\n }\n return value\n}\n\nfunction requestMessage(error: unknown, t: TranslateNS<'token-usage'>): string {\n if (!(error instanceof AssociationRequestError)) return t('association.writeFailed')\n switch (error.code) {\n case 'revision-conflict': case 'directory-conflict': return t('association.conflict')\n case 'migration-in-progress': return t('association.migrating')\n case 'source-automatically-priced': return t('association.automaticOnly')\n case 'target-unavailable': return t('association.targetUnavailable')\n case 'pricing-unavailable': return t('pricing.unavailable')\n case 'association-storage-unavailable': return t('pricing.associationStorageUnavailable')\n default: return t('association.writeFailed')\n }\n}\n\nexport function PricingAssociationDialog({ initialSource, view, t, onClose, returnFocus }: {\n initialSource: string | null; view: CurrencyView; t: TranslateNS<'token-usage'>; onClose: () => void\n returnFocus?: HTMLElement | null\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n const searchId = useId()\n const backdropPress = useRef(false)\n const mounted = useRef(true)\n const writing = useRef(false)\n const opener = useRef<HTMLElement | null>(returnFocus ?? (document.activeElement instanceof HTMLElement ? document.activeElement : null))\n const source = initialSource\n const [query, setQuery] = useState('')\n const [target, setTarget] = useState<string | null>(null)\n const [detail, setDetail] = useState<PricingOverviewModel | null>(null)\n const [pending, setPending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n const [notice, setNotice] = useState<string | null>(null)\n const [confirmRevoke, setConfirmRevoke] = useState<string | null>(null)\n const [override, setOverride] = useState<PricingAssociationsPayload | null>(null)\n const [state, retry] = useAsyncResource<{ associations: PricingAssociationsPayload; pricing: PricingOverviewPayload | null; source: string | null }>(async signal => {\n const [associations, pricing] = await Promise.all([\n readJson<PricingAssociationsPayload>(ASSOCIATIONS_PATH + (source !== null ? `?sourceModel=${encodeURIComponent(source)}` : ''), signal).then(checkAssociations),\n readJson<PricingOverviewPayload>(PRICING_PATH, signal).then(checkPricing).catch(() => null),\n ])\n return { associations, pricing, source }\n }, [source], { retryToken: 0 })\n\n useEffect(() => {\n const dialog = dialogRef.current\n dialog?.showModal()\n const parent = dialog?.parentElement\n mounted.current = true\n return () => {\n mounted.current = false\n if (opener.current?.isConnected) opener.current.focus()\n else (parent?.querySelector<HTMLButtonElement>('[data-pricing-association-manager]')\n ?? parent?.querySelector<HTMLButtonElement>('[data-pricing-overview-trigger]')\n ?? parent?.querySelector<HTMLButtonElement>('button'))?.focus()\n }\n }, [])\n\n const ready = state.status === 'ready' && state.value.source === source\n const snapshot = override ?? (ready ? state.value.associations : null)\n const models = ready ? state.value.pricing?.models ?? [] : []\n const candidateView = ready && state.value.pricing !== null ? currencyViewOf(state.value.pricing) : view\n const selected = models.find(model => modelKey(model.modelId) === modelKey(target ?? ''))\n const currentChoice = snapshot?.associations.find(row => modelKey(row.sourceModel) === modelKey(source ?? ''))\n const savedTarget = models.find(model => modelKey(model.modelId) === modelKey(currentChoice?.targetModelId ?? ''))\n const automatic = snapshot?.resolution?.automatic ?? snapshot?.resolution\n const writable = ready && snapshot?.storageState === 'ready' && !snapshot.writesPaused && !pending\n const canSave = writable && snapshot?.pricingAvailable && ready && state.value.pricing !== null && state.value.pricing.costState !== 'pricing-unavailable'\n && automatic !== undefined && automatic.status !== 'matched' && selected !== undefined && source !== null\n const searchModelId = modelKey(query.trim())\n const candidates = searchModelId === '' ? [] : models.filter(model => modelKey(model.modelId).includes(searchModelId))\n\n const reload = (): void => { setOverride(null); setError(null); retry() }\n\n const mutate = async (operation: 'save' | 'delete', name: string): Promise<void> => {\n if (writing.current || snapshot === null || snapshot.revision === null) return\n writing.current = true; setPending(true); setError(null); setNotice(null)\n try {\n const response = await fetch(ASSOCIATIONS_PATH, { method: operation === 'save' ? 'POST' : 'DELETE', cache: 'no-store',\n headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sourceModel: name,\n ...(operation === 'save' ? { targetModelId: selected?.modelId } : {}), revision: snapshot.revision, directoryToken: snapshot.directoryToken }) })\n const result = await response.json() as PricingAssociationsPayload & { error?: string; current?: PricingAssociationsPayload }\n if (!response.ok) throw new AssociationRequestError(result.error ?? 'write-failed', result.current)\n checkAssociations(result)\n pricingAssociationsChanged()\n if (!mounted.current) return\n if (operation === 'save') { dialogRef.current?.close(); return }\n setOverride(result); setConfirmRevoke(null); setNotice(t('association.revoked'))\n } catch (failure) {\n if (!mounted.current) return\n if (failure instanceof AssociationRequestError && failure.current !== undefined) {\n setOverride(failure.current)\n if (failure.code === 'directory-conflict') {\n setTarget(null); setDetail(null); setOverride(null); retry(); pricingAssociationsChanged()\n }\n }\n setError(requestMessage(failure, t))\n } finally { writing.current = false; if (mounted.current) setPending(false) }\n }\n\n const revokeButtons = (name: string): ReactNode => <>\n {confirmRevoke === name ? <span className={`${styles.actions} ${styles.revokeConfirmation}`}>\n <span className={styles.note}>{t('association.revokeImpact')}</span>\n <button type=\"button\" className={styles.button} disabled={!writable} onClick={() => { void mutate('delete', name) }}>{t('association.confirmRevoke')}</button>\n <button type=\"button\" className={styles.button} disabled={pending} onClick={() => setConfirmRevoke(null)}>{t('association.cancel')}</button>\n </span> : <button type=\"button\" className={styles.button} disabled={!writable} onClick={() => setConfirmRevoke(name)}>{t('association.revoke')}</button>}\n </>\n\n return <dialog ref={dialogRef} className={`${shared.dialog} ${styles.dialog}`} aria-label={t('association.title')}\n onClose={event => { if (event.target === dialogRef.current) onClose() }}\n onCancel={event => { if (event.target === dialogRef.current && writing.current) event.preventDefault() }}\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => { if (event.target === dialogRef.current && backdropPress.current && !writing.current) dialogRef.current?.close() }}\n onKeyDown={event => { if (event.key === 'Escape') event.stopPropagation() }}>\n <div className={shared.dialogHead}><h2 className={shared.dialogTitle}>{t('association.title')}</h2>\n <button type=\"button\" className={shared.dialogClose} aria-label={t('association.close')} disabled={pending} onClick={() => dialogRef.current?.close()}>✕</button>\n </div>\n {state.status === 'loading' && <p>{t('loading')}</p>}\n {state.status === 'error' && <><p role=\"alert\">{t('association.loadFailed')}</p><button type=\"button\" className={styles.button} onClick={reload}>{t('retry')}</button></>}\n {source !== null && ready && state.value.pricing === null && <><p role=\"alert\">{t('association.candidatesUnavailable')}</p><button type=\"button\" className={styles.button} disabled={pending} onClick={reload}>{t('retry')}</button></>}\n {error !== null && <p role=\"alert\" className={styles.error}>{error} <button type=\"button\" className={styles.button} disabled={pending} onClick={reload}>{t('association.refresh')}</button></p>}\n {notice !== null && <p role=\"status\">{notice}</p>}\n {snapshot !== null && <>\n {snapshot.storageState !== 'ready' && <p role=\"alert\">{t('pricing.associationStorageUnavailable')}</p>}\n {snapshot.writesPaused && <p role=\"status\">{t('association.migrating')}</p>}\n {!snapshot.pricingAvailable && <p role=\"status\">{t('pricing.unavailable')}</p>}\n {source === null ? <>\n <p className={styles.note}>{t('association.allHint')}</p>\n {snapshot.associations.length === 0 && <p className={styles.note}>{t('association.empty')}</p>}\n {snapshot.associations.map(row => <section key={modelKey(row.sourceModel)} className={`${styles.entry} ${styles.mappingRow}`}>\n <div className={styles.name}>{row.sourceModel} → {row.resolvedTargetModelId ?? row.targetModelId}</div>\n {revokeButtons(row.sourceModel)}\n </section>)}\n </> : <>\n <p className={`${styles.name} ${styles.source}`}>{source}</p>\n {automatic?.status === 'ambiguous' && <p>{t('pricing.ambiguous', { models: automatic.candidates.join(', ') })}</p>}\n {currentChoice !== undefined && <section className={styles.entry}>\n <div className={styles.name}>{source} → {currentChoice.resolvedTargetModelId ?? currentChoice.targetModelId}</div>\n <AssociationStatus row={currentChoice} t={t} />\n {savedTarget !== undefined && <button type=\"button\" className={styles.button} onClick={() => setDetail(savedTarget)}>{t('association.preview')}</button>}\n {revokeButtons(source)}\n </section>}\n {automatic?.status === 'matched' ? <p>{t('association.automaticOnly')} {automatic.modelId}</p> : <>\n <label className={styles.label} htmlFor={searchId}>{t('association.search')}</label>\n <input id={searchId} className={styles.search} type=\"search\" placeholder={t('association.searchHint')}\n value={query} disabled={pending} onChange={event => { setQuery(event.target.value); setTarget(null) }} />\n {candidates.length > 0 && <div className={styles.candidates} role=\"group\" aria-label={t('association.candidates')}>\n {candidates.map(model => <label key={model.modelId} className={styles.candidate}>\n <input type=\"radio\" name={searchId + '-target'} checked={target !== null && modelKey(target) === modelKey(model.modelId)} disabled={!writable || !snapshot.pricingAvailable}\n onChange={() => { setTarget(model.modelId); setNotice(null) }} />\n <span>{model.modelId}</span><small>{model.family}</small>\n </label>)}\n </div>}\n {query.trim() !== '' && candidates.length === 0 && <p className={styles.note}>{t('association.noResults')}</p>}\n {selected !== undefined && <div className={styles.selection}>\n <span className={styles.name}>{t('association.target', { model: selected.modelId })}</span>\n <button type=\"button\" className={styles.button} onClick={() => setDetail(selected)}>{t('association.preview')}</button>\n </div>}\n <p className={styles.note}>{t('association.impact')}</p>\n <button type=\"button\" className={`${styles.button} ${styles.save}`} disabled={!canSave} onClick={() => { void mutate('save', source) }}>{t(pending ? 'association.saving' : 'association.save')}</button>\n </>}\n </>}\n </>}\n {detail !== null && <PricingDialog model={detail.modelId} rules={detail.rules} view={candidateView} t={t} onClose={() => setDetail(null)} />}\n </dialog>\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 * 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, useState } 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\n/**\n * Hook reporting whether the current shell/page environment is in light mode.\n * Evaluates `document.documentElement.style.colorScheme` first (the DSH shell\n * rewrites this on every theme switch), falling back to `(prefers-color-scheme: light)`.\n */\nexport function useIsLightMode(): boolean {\n const [isLight, setIsLight] = useState<boolean>(() => {\n if (typeof document === 'undefined') return false\n const rootScheme = document.documentElement.style.colorScheme\n if (rootScheme === 'light') return true\n if (rootScheme === 'dark') return false\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(prefers-color-scheme: light)').matches\n : false\n })\n\n useEffect(() => {\n if (typeof document === 'undefined') return\n const root = document.documentElement\n const media = typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(prefers-color-scheme: light)')\n : null\n\n const check = (): void => {\n const scheme = root.style.colorScheme\n if (scheme === 'light') {\n setIsLight(true)\n } else if (scheme === 'dark') {\n setIsLight(false)\n } else {\n setIsLight(media?.matches ?? false)\n }\n }\n\n check()\n const observer = new MutationObserver(check)\n observer.observe(root, { attributes: true, attributeFilter: ['style'] })\n if (media?.addEventListener) {\n media.addEventListener('change', check)\n }\n return () => {\n observer.disconnect()\n if (media?.removeEventListener) {\n media.removeEventListener('change', check)\n }\n }\n }, [])\n\n return isLight\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`). The mix base is the pill's\n * resting tertiary (NOT label-primary): the pill reads tertiary beside the\n * official pills, and a primary-tinted final frame would leave the figure\n * permanently highlighted after the animation's fill. */\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-tertiary)' },\n {\n transform: `scale(${String(popScale)})`,\n color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-tertiary))`,\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-tertiary))`,\n offset: 0.70,\n },\n { transform: 'scale(1)', color: 'var(--dsw-alias-label-tertiary)' },\n ], {\n duration: v.inflateMs,\n easing: 'cubic-bezier(0.25, 0.85, 0.35, 1)',\n })\n}\n\n/** +Δ label fall (`deltaFall`). Caller must position the element (absolute,\n * below the pill — the dock sits under the composer, so the label falls\n * away from the message scrollport rather than climbing into it). */\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 './CostPill.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-figure inflate animation for the composer-dock usage\n * pill: detects new usage from summary deltas and drives WAAPI motion on\n * the cost figure 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 { costsAvailable } from './PricingStatus.tsx'\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 pill uses to play costPop + deltaFall 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 if (!costsAvailable(summary.costState)) { reset(); return }\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 = `+${(wireDeltaCost / view.rate).toFixed(2)}${view.symbol}`\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, reset])\n\n return { flies, flyOverflow, onSummary, reset }\n}\n","/**\n * Composer-dock usage pill (browser half): a cost trigger registered into\n * the `conversation.composer.dock` slot (`order: 10`, after the official\n * stats pills at `order: 0`), rendered as one capsule in the official\n * StatsPills skin. The figure is the WITH-SUBAGENTS fold — the one number\n * no official surface carries — suffixed with a quiet \"with subagents\"\n * badge only when the scope actually spans a subtree; a solo session's\n * cost renders bare, same scope as the official pills beside it.\n *\n * Clicking opens a detail panel (harness menu chrome, upward of the dock)\n * that explains the total: the folded token figure and cache-hit rate next\n * to it (official pills carry only the single-session token count, so the\n * subtree share has no home but here), the session / subagents split, and\n * a per-model breakdown with the unpriced-models footnote. Panel data is\n * LAZY: the trigger polls `fields=chip` (totals only, subtree scope); the\n * two richer reads (`fields=session` for byModel, a solo-session `chip`\n * read for the split) fire when the panel first opens and again whenever\n * request churn debounces through.\n *\n * The pill refreshes at REQUEST granularity (the header chip's former\n * cadence, inherited whole): `sessionStats` projection churn plus mirror\n * `updatedAt` is debounced 250 ms into one fetch, a failed FIRST fetch\n * retries itself on a 3 s cadence, and later failures keep the prior\n * figures. When cost rises on a new request the figure plays `costPop`\n * and a +Δ label FALLS below the pill (the dock sits under the composer;\n * the header chip's upward rise would climb into the message scrollport).\n * Reduced-motion users get silent figure updates.\n *\n * Visibility contract: a session with no recorded requests renders\n * nothing; a transient fetch miss keeps the previous render.\n *\n * @module token-usage/client/CostPill\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } 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 composer-dock runtime kit.\nimport type {} from '@deepseek-ai/dsh-client-ui-session/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.composer.dock` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { CostedModelRow, UsageSummary } from '../wire.ts'\nimport { STATS_PATH, encodeStatsQuery } from '../wire.ts'\nimport { useAsyncResource, useDebouncedValue } from './async-resource.ts'\nimport { totalTokens } from './day.ts'\nimport { currencyViewOf, formatCost, formatTokens, hitRateDisplay } from './format.ts'\nimport { PricingStatus, costsAvailable } from './PricingStatus.tsx'\nimport { ModelAssociationBadge, PricingAssociationProvider, UnpricedModelTag } from './PricingAssociations.tsx'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\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 './CostPill.module.css'\n\n/** Refresh debounce: bursts of session-mirror updates (one request's events)\n * collapse into a single fetch — the header chip's request-scale cadence. */\nconst REFRESH_DEBOUNCE_MS = 250\n\n/** Self-heal cadence after a failed first fetch: refresh failures after the\n * first land keep the prior figures (silent mode) and self-heal on the next\n * request churn, so they never reach the error state. */\nexport const FETCH_FAILURE_RETRY_MS = 3_000\n\n/** Detail panel width (px); the viewport-clamped centering uses it. */\nconst PANEL_WIDTH = 300\nconst PANEL_VIEWPORT_MARGIN = 16\n\n/** Props the pill binds for the composer-dock slot: the framework's session\n * kit (`sessionId` + the global `useSessions` mirror used to walk the\n * subagent tree) plus the locale seat from the registration's `locale:`\n * declaration. The dock slot declares no owner share. */\nexport type CostPillProps =\n PropsRuntime<'conversation.composer.dock'>\n & PropsLocale<'token-usage'>\n\n/**\n * The session / subagents split of one folded summary. Subagent figures are\n * derived by subtraction (folded minus solo) and clamped at zero — a stale\n * solo read against a fresher fold must never paint a negative share.\n */\nexport interface UsageSplit {\n selfCost: number\n subsCost: number\n selfTokens: number\n subsTokens: number\n}\n\n/**\n * Subtract a solo-session summary from its subtree fold.\n * @param tree - the subtree-scoped folded summary.\n * @param self - the solo-session summary (same session, no children).\n * @returns the two shares; costs and tokens are additive so subtraction is\n * exact, and the hit rate is NEVER split (a ratio is not subtractable — the\n * panel recomputes the folded rate from the tree totals instead).\n */\nexport function splitUsage(tree: UsageSummary, self: UsageSummary): UsageSplit {\n const sub = (whole: number, part: number): number => (whole - part > 0 ? whole - part : 0)\n return {\n selfCost: self.totalCost,\n subsCost: sub(tree.totalCost, self.totalCost),\n selfTokens: totalTokens(self.total),\n subsTokens: sub(totalTokens(tree.total), totalTokens(self.total)),\n }\n}\n\n/**\n * Render the composer-dock usage pill for the active session. Renders\n * nothing when the session has no recorded usage or while the first fetch\n * is in flight — the \"data has no value, the block does not render\" rule.\n * @param props - framework session id, the session-list mirror, and the locale seat.\n * @returns the pill (plus its open detail panel), or null when empty/unavailable.\n */\nexport function CostPill({ sessionId, useSessions, useProjection, t }: CostPillProps): ReactNode | null {\n const rootRef = useRef<HTMLDivElement>(null)\n const costRef = useRef<HTMLSpanElement>(null)\n useColorSchemeMirror(rootRef)\n const [open, setOpen] = useState(false)\n const [associationTick, setAssociationTick] = useState(0)\n usePricingAssociationRefresh(() => setAssociationTick(tick => tick + 1))\n\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 byId = useSessions(state => state.byId)\n const childIndex = useMemo(() => buildChildIndex(byId), [byId])\n const scopeIds = useMemo(\n () => (sessionId === '' ? [] : subtreeIds(byId, sessionId, childIndex)),\n [byId, sessionId, childIndex],\n )\n const hasSubs = scopeIds.length > 1\n const liveStats = useProjection('sessionStats')\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 { flies, onSummary } = useCostInflate(scopeResetKey, costRef)\n\n // The trigger's poll: subtree totals only (`fields=chip`), the lightest\n // read that feeds cost / tokens / hit rate.\n const [treeRes, retryTree] = useAsyncResource<UsageSummary | null>(\n signal => {\n const [idsPart] = debouncedKey.split('\\n\\t')\n const ids = (idsPart ?? '').split('\\n').filter(id => id !== '')\n return fetchSummary(ids, 'chip', signal)\n },\n [debouncedKey, associationTick],\n { silentAfterFirst: true, retryToken: 0 },\n )\n const summary = treeRes.status === 'ready' ? treeRes.value : null\n\n useEffect(() => {\n if (summary !== null) onSummary(summary)\n }, [summary, onSummary])\n\n // A failed first fetch renders nothing and self-heals on the retry\n // cadence; later failures keep the prior render (silent mode).\n useEffect(() => {\n if (treeRes.status !== 'error') return\n const timer = window.setTimeout(retryTree, FETCH_FAILURE_RETRY_MS)\n return () => { window.clearTimeout(timer) }\n }, [treeRes, retryTree])\n\n // Panel reads, LAZY: nothing flies while the panel is closed. The detail\n // read (`fields=session`) carries byModel; the solo read splits the fold.\n // Both re-fire when request churn debounces through while open.\n const [detailRes] = useAsyncResource<UsageSummary | null>(\n signal => {\n if (!open) return Promise.resolve(null)\n const [idsPart] = debouncedKey.split('\\n\\t')\n const ids = (idsPart ?? '').split('\\n').filter(id => id !== '')\n return fetchSummary(ids, 'session', signal)\n },\n [open, debouncedKey, associationTick],\n { silentAfterFirst: true, retryToken: 0 },\n )\n const [selfRes] = useAsyncResource<UsageSummary | null>(\n signal => {\n if (!open || sessionId === '') return Promise.resolve(null)\n return fetchSummary([sessionId], 'chip', signal)\n },\n [open, sessionId, debouncedKey, associationTick],\n { silentAfterFirst: true, retryToken: 0 },\n )\n\n // Session switches close the panel — the split it explains no longer holds.\n useEffect(() => {\n setOpen(false)\n }, [sessionId])\n\n // Outside pointer / Escape close — the harness popup pattern (ContextMeter\n // and the quota button share it), anchored 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 // Center the panel on the pill, clamped to the viewport's margins (the\n // dock row is full-width, but a bare left:0 could still skew off-screen\n // on narrow windows). Measured at open, refreshed on resize while open.\n const [panelLeft, setPanelLeft] = useState<number | undefined>(undefined)\n const measurePanelLeft = useCallback((): void => {\n const wrapper = rootRef.current\n if (wrapper === null) return\n const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect()\n const panelWidth = Math.min(PANEL_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 useEffect(() => {\n if (!open) return\n measurePanelLeft()\n window.addEventListener('resize', measurePanelLeft)\n return () => { window.removeEventListener('resize', measurePanelLeft) }\n }, [open, measurePanelLeft])\n\n if (summary === null || summary.total.requests === 0) return null\n\n const view = currencyViewOf(summary)\n const costText = costsAvailable(summary.costState) ? formatCost(summary.totalCost, view) : '—'\n const tokensValue = formatTokens(totalTokens(summary.total))\n const hit = hitRateDisplay(summary.total)\n const ariaLabel = hasSubs\n ? t('pill.costWithSubs', { value: costText })\n : t('pill.cost', { value: costText })\n\n // Panel shares: the split waits on the solo read; per-model waits on the\n // detail read. While either is in flight its block shows a quiet ellipsis.\n const selfSummary = selfRes.status === 'ready' ? selfRes.value : null\n const detail = detailRes.status === 'ready' ? detailRes.value : null\n const split = selfSummary !== null ? splitUsage(summary, selfSummary) : null\n const subCount = scopeIds.length - 1\n\n return (\n <div ref={rootRef} className={styles.root}>\n <PricingAssociationProvider resolutions={detail?.modelResolutions} feedVersion={summary.feedVersion} view={view} t={t}>\n <button\n type=\"button\"\n className={styles.pill}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n aria-label={`${ariaLabel},${t('panel.openHint')}`}\n onClick={() => { setOpen(!open) }}\n >\n <svg className={styles.glyph} viewBox=\"0 0 14 14\" width=\"14\" height=\"14\" aria-hidden>\n <circle cx=\"7\" cy=\"7\" r=\"5.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.2\" />\n <path\n d=\"M4.8 4.5 L7 7.2 L9.2 4.5 M7 7.2 V10 M5.2 8 H8.8 M5.2 9.4 H8.8\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.2\"\n />\n </svg>\n <span ref={costRef} className={styles.cost}>{costText}</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 </button>\n {open && (\n <div className={styles.panel} role=\"dialog\" aria-label={t('panel.title')} style={{ left: panelLeft }}>\n <span className={styles.panelHead}>\n <span className={styles.panelTitle}>\n {t('panel.title')}\n {hasSubs && <span className={styles.scopeTag}>{t('pill.scopeTag')}</span>}\n </span>\n <span className={styles.panelTotal}>{costText}</span>\n </span>\n <span className={styles.usageLine}>\n <span>{t('panel.tokens', { value: tokensValue })}</span>\n <span className={styles.dot}>·</span>\n <span>{t('panel.hitRate', { value: hit.text })}</span>\n </span>\n <div className={styles.rows}>\n <PricingStatus costState={summary.costState} pricingUnavailableReason={summary.pricingUnavailableReason} associationStorageError={summary.associationStorageError} t={t} />\n <span className={styles.row}>\n <span className={styles.rowLabel}>{t('panel.self')}</span>\n <span className={styles.rowValue}>\n {split === null\n ? <span className={styles.pending}>…</span>\n : <>{costsAvailable(summary.costState) && costsAvailable(selfSummary?.costState) ? formatCost(split.selfCost, view) : '—'}<span className={styles.tok}>{t('panel.tokens', { value: formatTokens(split.selfTokens) })}</span></>}\n </span>\n </span>\n {hasSubs && (\n <span className={`${styles.row} ${styles.rowSub}`}>\n <span className={styles.rowLabel}>{t('panel.subs', { count: subCount })}</span>\n <span className={styles.rowValue}>\n {split === null\n ? <span className={styles.pending}>…</span>\n : <>{costsAvailable(summary.costState) && costsAvailable(selfSummary?.costState) ? formatCost(split.subsCost, view) : '—'}<span className={styles.tok}>{t('panel.tokens', { value: formatTokens(split.subsTokens) })}</span></>}\n </span>\n </span>\n )}\n </div>\n <span className={styles.groupLabel}>{t('panel.byModel')}</span>\n <span className={styles.rows}>\n {detail === null\n ? (\n <span className={styles.row}>\n <span className={styles.pending}>…</span>\n </span>\n )\n : (\n <>\n {detail.byModel.map(row => (\n <ModelRow key={row.model} row={row} view={view} t={t} unpriced={detail.unpricedModels.includes(row.model)} available={costsAvailable(detail.costState) && !detail.unpricedModels.includes(row.model)} />\n ))}\n {costsAvailable(detail.costState) && detail.unpricedModels.length > 0 && (\n <span className={`${styles.row} ${styles.unpriced}`}>\n <span className={styles.rowLabel}>{t('panel.unpriced', { count: detail.unpricedModels.length })}</span>\n <span className={styles.rowValue}>{t('panel.unpricedNote')}</span>\n </span>\n )}\n </>\n )}\n </span>\n </div>\n )}\n </PricingAssociationProvider>\n </div>\n )\n}\n\n/** One per-model breakdown row: model id + request count, billed cost, tokens. */\nfunction ModelRow({ row, view, available, unpriced, t }: { row: CostedModelRow; view: ReturnType<typeof currencyViewOf>; available: boolean; unpriced: boolean; t: TranslateNS<'token-usage'> }): ReactNode {\n return (\n <span className={styles.row}>\n <span className={styles.rowLabel}>\n {row.model}\n {unpriced && <UnpricedModelTag model={row.model} t={t} />}\n <ModelAssociationBadge model={row.model} t={t} />\n <span className={styles.requests}>× {row.totals.requests}</span>\n </span>\n <span className={styles.rowValue}>\n {available ? formatCost(row.cost, view) : '—'}\n <span className={styles.tok}>{formatTokens(totalTokens(row.totals))}</span>\n </span>\n </span>\n )\n}\n\n/** Defensive shape check: an older host build or a misrouted response\n * would otherwise paint the pill 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 one stats summary. Throws on transport failure (network, abort,\n * non-2xx response, or a payload that doesn't look like a stats summary) so\n * the hook can keep the previous render in place.\n * @param sessionIds - the scope's session ids; an empty list skips the\n * fetch (returning null rather than throwing, so the hook's first-load\n * gate stays at \"loading\").\n * @param fields - `chip` for totals-only reads, `session` when byModel is\n * needed (the detail panel's per-model block).\n * @param signal - the cancellation signal from the hook.\n */\nasync function fetchSummary(\n sessionIds: readonly string[],\n fields: 'chip' | 'session',\n signal: AbortSignal,\n): Promise<UsageSummary | null> {\n if (sessionIds.length === 0) return null\n const response = await fetch(STATS_PATH + encodeStatsQuery({ sessionIds, fields }), {\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 sidebar panel list's \"More\" menu row (browser half): one entry that\n * opens the Token Usage main panel, registered into\n * `sidebar.panellist.actions` (declared by ui-sidebar since dsh\n * 0.2.1-rc.3). The row rides the region's own Menu — the owner supplies\n * `onDismiss` (close the menu before navigating) — and the registered\n * `inject` closure supplies the panel-opening callback, so this component\n * stays declarative. The label reuses the settings nav copy so the entry\n * reads as the same feature across surfaces.\n *\n * On a shell older than 0.2.1-rc.3 the slot is never declared: the inject\n * callback never runs and the row simply never appears — the settings\n * section stays the only entry.\n *\n * @module token-usage/client/PanellistMoreEntry\n */\n\nimport type { ReactNode } from 'react'\nimport { IconGaugeOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the `sidebar.panellist.actions` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'\n\nexport type PanellistMoreEntryProps =\n PropsRuntime<'sidebar.panellist.actions'>\n & PropsLocale<'token-usage'>\n & { openPanel: () => void }\n\n/**\n * Render the More-menu row that opens the Token Usage panel.\n * @param props - the owner's dismissal callback, the injected open\n * callback, and the framework translate seat.\n * @returns one MenuItemButton row.\n */\nexport function PanellistMoreEntry({ onDismiss, openPanel, t }: PanellistMoreEntryProps): ReactNode {\n return (\n <MenuItemButton icon={<IconGaugeOutlineRegular size={16} />}\n onSelect={() => { onDismiss(); openPanel() }}>\n {t('nav.label')}\n </MenuItemButton>\n )\n}\n","/**\n * Decorative occupant for the pinned Token Usage sidebar row (browser\n * half): registered into `sidebar.panellist` while the `sidebarPinned`\n * setting is on, so the shell renders the row the same way it renders its\n * official panel launchers — the shell owns the button and the accessible\n * label (resolved from the registration's `label` thunk); this component\n * supplies only the glyph.\n *\n * @module token-usage/client/PanellistPinEntry\n */\n\nimport { IconGaugeOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the `sidebar.panellist` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'\n\n/**\n * Render the gauge glyph at the size the sidebar asks for. The glyph sits\n * directly in the row's glyph slot, exactly as the official panel icons do —\n * an inline wrapper would lift it above the label line. Selection highlight\n * is the shell row's own class, so `active` stays unused here.\n * @param props - the sidebar's icon share: the requested edge and whether the panel is selected.\n * @returns decorative gauge icon.\n */\nexport function PanellistPinEntry({ size }: PropsRuntime<'sidebar.panellist'>) {\n return <IconGaugeOutlineRegular size={size} />\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 * POOLING: a gateway may hold several keys of ONE vendor family, each\n * with its own meter but serving the same traffic. The trigger reads the\n * POOL's level (the mean of the pool's remaining shares) instead of\n * whichever window it happens to meet first, and colors it by the pool's\n * availability — one dead key no longer paints the whole vendor red,\n * while a pool with nothing left still does.\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, an `other` window (a gateway's open-named meter:\n * \"Credits\", \"Allowance\") ranking with the coarser pools it usually is.\n * The trigger icon reads this one, not the worst across windows: the\n * finest unit is the constraint the session is currently acting inside\n * (a calm 5-hour window carries the icon even when the weekly pool runs\n * low). Undefined when there is no window at all.\n */\nexport function finestQuotaWindow<T extends QuotaWindow>(windows: readonly T[]): T | undefined {\n const rank: Record<QuotaWindow['tier'], number> = { five_hour: 0, weekly: 1, other: 2, monthly: 3, balance: 4 }\n let pick: T | 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 * A quota window after POOLING: the windows one quota pool spends at one\n * tier collapsed into a single water level (the mean of their remaining\n * shares), plus the bookkeeping the severity band needs to tell a pool's\n * overall level from its weakest member.\n */\nexport interface PooledQuotaWindow extends QuotaWindow {\n /** Windows behind this level (1 = a lone window, nothing pooled). */\n peerCount: number\n /** How many of those windows sit below the red line (remaining < 20%). */\n exhaustedPeerCount: number\n}\n\n/**\n * Pool the windows of a payload: windows that NAME the same quota POOL\n * and spend the same tier (an `other` window pools only with its own\n * name) collapse into one level — their budgets are interchangeable\n * (a gateway's several keys of one vendor family), so the pool's mean\n * remaining share is the level the traffic actually feels.\n *\n * Two boundaries keep the collapse honest:\n *\n * - A window WITHOUT a pool stands alone. Single-source payloads name\n * no pool, and a lone window pools with nothing — the mean of one\n * window is that window.\n * - BALANCE windows never pool. Amounts are not shares: summing two\n * purses of different currencies (or averaging them) states nothing\n * true about either, so every balance keeps its own row.\n *\n * The order of first appearance is preserved, so the trigger still reads\n * the first (finest) level of the payload.\n */\nexport function poolQuotaWindows(windows: readonly QuotaWindow[]): readonly PooledQuotaWindow[] {\n const groups = new Map<string, QuotaWindow[]>()\n windows.forEach((window, index) => {\n // Pool-less windows get a key of their own (never shared).\n const key = window.pool === undefined\n ? `solo:${String(index)}`\n : `${window.pool}|${window.tier}|${window.name ?? ''}`\n const group = groups.get(key)\n if (group === undefined) groups.set(key, [window])\n else group.push(window)\n })\n const pooled: PooledQuotaWindow[] = []\n for (const group of groups.values()) {\n const ratios = group\n .map(window => quotaRemainingPercent(window))\n .filter((value): value is number => value !== undefined)\n // A lone window, a balance group (amounts are not shares), or a group\n // with no computable share stays as it is.\n if (group.length === 1 || group[0]?.tier === 'balance' || ratios.length === 0) {\n for (const window of group) {\n const remaining = quotaRemainingPercent(window)\n pooled.push({\n ...window,\n peerCount: 1,\n exhaustedPeerCount: remaining !== undefined && remaining < REMAIN_RED ? 1 : 0,\n })\n }\n continue\n }\n const mean = ratios.reduce((sum, value) => sum + value, 0) / ratios.length\n const exhausted = ratios.filter(value => value < REMAIN_RED).length\n const first = group[0] as QuotaWindow\n pooled.push({\n tier: first.tier,\n remainingPercent: mean,\n ...(first.name !== undefined ? { name: first.name } : {}),\n ...(first.pool !== undefined ? { pool: first.pool } : {}),\n peerCount: group.length,\n exhaustedPeerCount: exhausted,\n })\n }\n return pooled\n}\n\n/**\n * The severity of a POOLED window — the traffic light of a pool, not of\n * a single meter:\n *\n * - red only when EVERY window of the pool is exhausted (the pool has\n * nothing left to route to);\n * - yellow when the pool is low (mean at or below the yellow line) or\n * when SOME window is exhausted while others still have room (one\n * account died, the pool still serves);\n * - green otherwise.\n *\n * A lone window keeps the plain per-window band, so single-source\n * providers read exactly as before.\n */\nexport function quotaPoolSeverityOf(window: PooledQuotaWindow): QuotaSeverity {\n if (window.peerCount <= 1) return quotaSeverityOf(window)\n const remaining = quotaRemainingPercent(window)\n if (remaining === undefined) return quotaSeverityOf(window)\n if (window.exhaustedPeerCount >= window.peerCount) return 'exhausted'\n if (window.exhaustedPeerCount > 0) return 'warn'\n if (remaining <= REMAIN_YELLOW) return 'warn'\n return 'ok'\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 * 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's POOL level —\n * a gateway's several keys of one vendor share one budget, so the ring\n * reads that pool's mean share and its availability. 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 (the kit's SessionStandardProps declaration\n// lives in ui-session since dsh-client-runtime was removed).\nimport type {} from '@deepseek-ai/dsh-client-ui-session/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 poolQuotaWindows, quotaIconFillShare, quotaPoolSeverityOf, quotaRemainingPercent, quotaSeverityOf,\n 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/** 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.other' | 'quota.tier.balance'> = {\n five_hour: 'quota.tier.fiveHour',\n weekly: 'quota.tier.weekly',\n monthly: 'quota.tier.monthly',\n other: 'quota.tier.other',\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; model?: 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 [panelHeight, setPanelHeight] = useState<number | undefined>(undefined)\n const [panelBelow, setPanelBelow] = useState(false)\n const measurePanelLeft = useCallback((width: number): void => {\n const wrapper = rootRef.current\n if (wrapper === null) return\n const { left: wrapperLeft, width: wrapperWidth, top, bottom } = 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 // The shell's scroll body clips above its header, inside the viewport.\n let clipTop = 0\n let clipBottom = window.innerHeight\n for (let parent = wrapper.parentElement; parent !== null; parent = parent.parentElement) {\n if (!/^(auto|scroll|hidden|clip)$/u.test(getComputedStyle(parent).overflowY)) continue\n const rect = parent.getBoundingClientRect()\n clipTop = Math.max(clipTop, rect.top)\n clipBottom = Math.min(clipBottom, rect.bottom)\n }\n const above = top - clipTop - 8 - PANEL_VIEWPORT_MARGIN\n const below = clipBottom - bottom - 8 - PANEL_VIEWPORT_MARGIN\n setPanelBelow(below > above)\n setPanelHeight(Math.max(0, above, below))\n }, [])\n\n // The provider + model the 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, else\n // the default provider).\n const modelService = modelDirectory?.service\n const readChipSelection = (): { provider: string; model?: string } | undefined => {\n if (sessionId === '' || modelService === undefined) return undefined\n try {\n return modelService.directoryFor(sessionId).store.getSnapshot().current ?? 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 [chipSelection, setChipSelection] = useState(readChipSelection)\n useEffect(() => {\n // Re-seed on session/service change, then subscribe for chip switches.\n setChipSelection(readChipSelection())\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(() => { setChipSelection(readChipSelection()) })\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, chipSelection?.provider, chipSelection?.model, signal),\n [sessionId, chipSelection?.provider, chipSelection?.model],\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 trigger reads the POOLED level of the finest tier. A gateway\n // holding several keys of ONE vendor family serves them\n // interchangeably (it routes to whichever key still has room), so the\n // pool's mean remaining share is the level the traffic actually\n // feels — one exhausted key no longer paints the whole vendor red.\n // Cross-vendor pools stay apart (each keeps its own level), and a\n // payload without pools reads exactly as before.\n const pooled = poolQuotaWindows(windows)\n const finest = finestQuotaWindow(pooled)\n const severity = finest === undefined ? 'ok' : quotaPoolSeverityOf(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. A pooled level says so — the mean of several keys' shares is\n // not any single key's share.\n const figure = quotaTriggerFigure(finest)\n const triggerTip = figure === undefined\n ? t('quota.trigger')\n : finest !== undefined && finest.peerCount > 1\n ? t('quota.triggerSummaryPooled', {\n name: payload.providerName ?? payload.provider,\n figure,\n count: finest.peerCount,\n })\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 ...(panelHeight === undefined ? {} : { maxHeight: `${String(panelHeight)}px` }),\n ...(panelBelow ? { top: 'calc(100% + 8px)', bottom: 'auto' } : {}),\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 : <QuotaCardGroups windows={payload.windows} t={t} />}\n </div>\n )}\n </span>\n )\n}\n\n/**\n * The panel's window body: one group per quota CARD (a gateway payload\n * aggregates several upstream accounts — each window carries its card's\n * title), a card title heading each; a single-card (or card-less) payload\n * renders the flat grid as before, so the plain providers' panels do not\n * change shape.\n */\nfunction QuotaCardGroups({ windows, t }: { windows: readonly QuotaWindow[]; t: QuotaButtonProps['t'] }): ReactNode {\n const groups: Array<{ card?: string; windows: QuotaWindow[] }> = []\n for (const window of windows) {\n const last = groups[groups.length - 1]\n if (last !== undefined && (last.card ?? '') === (window.card ?? '')) {\n last.windows.push(window)\n } else {\n groups.push({ ...(window.card !== undefined ? { card: window.card } : {}), windows: [window] })\n }\n }\n if (groups.length <= 1) {\n const flat = groups[0]?.windows ?? []\n return (\n <div\n className={styles.grid}\n style={{ '--cols': String(Math.min(flat.length, 3)) } as CSSProperties}\n >\n {flat.map((window, index) =>\n <QuotaColumn key={`${window.tier}:${String(index)}`} window={window} t={t} />)}\n </div>\n )\n }\n return (\n <>\n {groups.map((group, gi) => (\n <div key={group.card ?? String(gi)} className={styles.cardGroup}>\n <div className={styles.cardTitle}>{group.card}</div>\n <div\n className={styles.grid}\n style={{ '--cols': String(Math.min(group.windows.length, 3)) } as CSSProperties}\n >\n {group.windows.map((window, index) =>\n <QuotaColumn key={`${window.tier}:${String(index)}`} window={window} t={t} />)}\n </div>\n </div>\n ))}\n </>\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 // An `other` window keeps the vendor's own name (\"Credits\",\n // \"Allowance\"); the known tiers read the localized period label.\n const label = window.balanceKind === 'recharge'\n ? t('quota.tier.recharge')\n : window.balanceKind === 'bonus'\n ? t('quota.tier.bonus')\n : window.name !== undefined && window.tier === 'other'\n ? window.name\n : 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 API-key DeepSeek shape) reads at\n * the minimal plate, two amount purses (account recharge + bonus) the\n * full 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 * A multi-card gateway payload (several upstream accounts) always reads\n * the full plate — the card headings need the room. Errors and payloads\n * without windows read the full plate (their copy runs long). */\nfunction panelWidthOf(payload: QuotaPayload | null): number {\n if (payload === null || payload.status !== 'ok') return PANEL_WIDTH_FULL\n if (new Set(payload.windows.map(window => window.card ?? '')).size > 1) return PANEL_WIDTH_FULL\n const bars = payload.windows.filter(window => quotaUsedPercent(window) !== undefined).length\n if (bars === 0) {\n // One amount (the API-key DeepSeek shape) stays the minimal plate.\n // Two purses (recharge + bonus) need the full plate so both labels fit.\n if (payload.windows.length === 1) return PANEL_WIDTH_BALANCE\n return PANEL_WIDTH_FULL\n }\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 'signed-out':\n return t('quota.error.signedOut')\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 and model when 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, model: 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 if (provider !== undefined && provider !== '' && model !== undefined && model !== '') params.set('model', model)\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 * 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, useRef, useState } from 'react'\nimport { IconChevronDownOutlineMedium } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { InjectFace, PropsLocale, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { CardActions, CardStore } from './card-form.ts'\nimport { FULL_SYNC_PATH, PRICING_SYNC_PATH, type FullSyncView, type PricingSyncResult } from '../wire.ts'\nimport { pricingTableChanged } from './pricing-associations.ts'\nimport css from './TokenUsageCard.module.css'\n\n/** The view the Plugins page asks for under `plugins.bundle.config`. */\nexport interface PluginConfigViewProps {\n /** `summary` renders the one-liner; `page` renders the form. */\n readonly view?: 'summary' | 'page'\n}\n\n/** Props the renderer binds for the token-usage settings card. */\nexport type TokenUsageCardProps =\n PluginConfigViewProps\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(props.view === 'page')\n const [picking, setPicking] = useState(false)\n const { t } = props\n const state = props.useTokenUsageCard(snapshot => snapshot)\n\n // Discard unstaged changes when navigating away from the page.\n const discardRef = useRef(props.discard)\n discardRef.current = props.discard\n useEffect(() => () => { discardRef.current() }, [])\n\n if (!state.available) return null\n if (props.view === 'summary') {\n return <span className={css.description}>{t('card.description')}</span>\n }\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 {\n status: body.status,\n processed: body.processed,\n total: body.total,\n added: body.added,\n skipped: body.skipped,\n removed: typeof body.removed === 'number' ? body.removed : 0,\n failedSessions: typeof body.failedSessions === 'number' ? body.failedSessions : 0,\n }\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, removed: 0, failedSessions: 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 <IconChevronDownOutlineMedium 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 <div className={css.field}>\n <label className={css.fieldLabel} htmlFor=\"token-usage-card-region\">{t('card.regionLabel')}</label>\n <div className={css.regionRow}>\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 <PricingSyncButton disabled={lockInput || state.saving || state.textDirty} dirty={state.textDirty} t={t} />\n </div>\n </div>\n <p className={css.hint}>\n {t('card.hint')}\n {state.overridden.pricingRegion ? ` ${t('card.overridden')}` : ''}\n </p>\n <div className={css.field}>\n <label className={css.pinRow} htmlFor=\"token-usage-card-pin\">\n <input\n id=\"token-usage-card-pin\"\n type=\"checkbox\"\n className={css.pinCheck}\n checked={state.pinnedDraft ?? state.sidebarPinned}\n disabled={lockInput}\n onChange={event => { props.editPinned(event.target.checked) }}\n />\n <span className={css.fieldLabel}>{t('card.sidebarPinned.label')}</span>\n </label>\n <p className={css.hint}>{t('card.sidebarPinned.hint')}</p>\n </div>\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 removed: String(fullSync.removed),\n })}\n {fullSync.failedSessions > 0\n ? t('card.fullSync.failuresNote', { count: String(fullSync.failedSessions) })\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 removed: String(fullSync.removed),\n })}\n {fullSync.failedSessions > 0\n ? t('card.fullSync.failuresNote', { count: String(fullSync.failedSessions) })\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\nfunction PricingSyncButton({ disabled, dirty, t }: {\n disabled: boolean; dirty: boolean; t: TranslateNS<'token-usage'>\n}) {\n const [status, setStatus] = useState<'idle' | 'running' | 'done' | 'failed' | 'changed' | 'migrating'>('idle')\n const [result, setResult] = useState<PricingSyncResult | null>(null)\n const running = useRef(false)\n const mounted = useRef(true)\n useEffect(() => {\n mounted.current = true\n return () => { mounted.current = false }\n }, [])\n\n const sync = async (): Promise<void> => {\n if (running.current || disabled || dirty) return\n running.current = true\n setStatus('running'); setResult(null)\n try {\n const response = await fetch(PRICING_SYNC_PATH, { method: 'POST', cache: 'no-store' })\n if (!response.ok) {\n const body = await response.json() as { error?: string }\n if (mounted.current) setStatus(body.error === 'migration-in-progress' ? 'migrating'\n : body.error === 'directory-conflict' || body.error === 'pricing-source-changed' ? 'changed' : 'failed')\n return\n }\n const body = await response.json() as PricingSyncResult\n if (body === null || typeof body !== 'object'\n || ![body.version, body.updatedAt, body.models, body.aliasPatterns, body.usdExchangeRate].every(value => typeof value === 'number' && Number.isFinite(value))) {\n throw new Error('unexpected pricing sync response')\n }\n pricingTableChanged()\n if (mounted.current) { setResult(body); setStatus('done') }\n } catch {\n if (mounted.current) setStatus('failed')\n } finally { running.current = false }\n }\n\n return <>\n <button type=\"button\" className={css.browse} disabled={disabled || dirty || status === 'running'}\n onClick={() => { void sync() }}>{t(status === 'running' ? 'card.pricingSync.running' : 'card.pricingSync.button')}</button>\n {dirty ? <p className={`${css.hint} ${css.syncFeedback}`}>{t('card.pricingSync.unsaved')}</p>\n : status === 'done' && result !== null ? <p className={`${css.note} ${css.syncFeedback}`} role=\"status\">\n {t('card.pricingSync.done', { version: String(result.version), models: String(result.models) })}</p>\n : status === 'failed' || status === 'changed' || status === 'migrating' ? <p className={`${css.failed} ${css.syncFeedback}`} role=\"alert\">\n {t(`card.pricingSync.${status}`)}</p> : null}\n </>\n}\n","/**\n * Range date picker (browser half): the filter bar's single date control —\n * one trigger showing the active day range plus a lightweight calendar\n * popover. The range is picked with two clicks: the first lands an anchor\n * (start or end, order does not matter), the second settles the range\n * (min/max sorted); month navigation keeps the anchor, so a range may span\n * months (navigate, click, navigate back, click). While an anchor is live,\n * hovering previews the pending range; Escape or an outside pointerdown\n * closes the popover and DISCARDS the unfinished anchor (the committed\n * filters never change on cancel). A clear affordance releases the range\n * back to unconstrained — the capability the two native date inputs it\n * replaces carried.\n *\n * The popover interaction copies QuotaButton's pattern verbatim (click\n * toggles, document pointerdown outside closes, Escape closes); the plate\n * styling mirrors its panel (menu background, inverted border, shadow,\n * z-index 100).\n *\n * @module token-usage/client/DateRangePicker\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { dayKeyOf, monthGrid, monthViewOf, shiftMonth } from './day.ts'\nimport type { MonthView } from './day.ts'\nimport styles from './DateRangePicker.module.css'\n\n/** Monday-first weekday header keys (index 0 = Monday). */\nconst WEEKDAY_KEYS = [\n 'calendar.weekday.0', 'calendar.weekday.1', 'calendar.weekday.2', 'calendar.weekday.3',\n 'calendar.weekday.4', 'calendar.weekday.5', 'calendar.weekday.6',\n] as const\n\n/** Props: the committed range ('' = unconstrained) and the change lift. */\nexport interface DateRangePickerProps {\n from: string\n to: string\n onChange: (next: { from: string; to: string }) => void\n t: TranslateNS<'token-usage'>\n}\n\n/** The month view the popover opens on: the range end, else its start, else today. */\nfunction initialView(from: string, to: string): MonthView {\n const focus = to !== '' ? to : from !== '' ? from : dayKeyOf(new Date())\n return monthViewOf(focus)\n}\n\n/**\n * Render the trigger + calendar popover.\n * @param props - the committed range, the change lift, and the locale seat.\n * @returns the inline wrapper holding the trigger and, while open, the panel.\n */\nexport function DateRangePicker({ from, to, onChange, t }: DateRangePickerProps): ReactNode {\n const rootRef = useRef<HTMLSpanElement>(null)\n const [open, setOpen] = useState(false)\n const [view, setView] = useState<MonthView>(() => initialView(from, to))\n // The first click's day key; null until it lands, cleared on close.\n const [anchor, setAnchor] = useState<string | null>(null)\n // The hovered day key while an anchor is live (range preview); else null.\n const [hovered, setHovered] = useState<string | null>(null)\n\n // Every close path funnels here: cancel discards the unfinished anchor\n // (only a second click or the clear button commits anything).\n const closePanel = (): void => {\n setOpen(false)\n setAnchor(null)\n setHovered(null)\n }\n\n // Opening resets the selection progress and lands on the focused month.\n const openPanel = (): void => {\n setView(initialView(from, to))\n setAnchor(null)\n setHovered(null)\n setOpen(true)\n }\n\n // Outside click / Escape close — QuotaButton'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 closePanel()\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') closePanel()\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 // The two-click state machine: first click anchors, second settles the\n // sorted range, commits it, and closes. Clicking an EARLIER day second\n // still yields from <= to (the order of the two clicks never matters).\n const pickDay = (day: string): void => {\n if (anchor === null) {\n setAnchor(day)\n return\n }\n const lo = anchor < day ? anchor : day\n const hi = anchor < day ? day : anchor\n closePanel()\n onChange({ from: lo, to: hi })\n }\n\n const clear = (): void => {\n closePanel()\n onChange({ from: '', to: '' })\n }\n\n // What the grid highlights: the pending anchor (previewing through the\n // hover when one is live) while selecting, else the committed range.\n const shown = anchor !== null\n ? {\n from: hovered !== null && hovered < anchor ? hovered : anchor,\n to: hovered !== null && hovered > anchor ? hovered : anchor,\n }\n : { from, to }\n const today = dayKeyOf(new Date())\n const summary = from !== '' && to !== ''\n ? `${from} ${t('filter.separator')} ${to}`\n : from !== ''\n ? from\n : to !== ''\n ? to\n : t('filter.allDates')\n\n return (\n <span ref={rootRef} className={styles['wrapper']}>\n <button\n type=\"button\"\n className={styles['trigger']}\n aria-label={t('filter.dateRange')}\n aria-expanded={open}\n onClick={() => { (open ? closePanel : openPanel)() }}\n >\n {summary}\n </button>\n {open\n ? (\n <div className={styles['panel']} role=\"dialog\" aria-label={t('filter.dateRange')}>\n <div className={styles['head']}>\n <button\n type=\"button\"\n className={styles['nav']}\n aria-label={t('calendar.prevMonth')}\n onClick={() => { setView(shiftMonth(view, -1)) }}\n >\n ‹\n </button>\n <span className={styles['monthTitle']}>\n {t('calendar.monthTitle', { year: String(view.year), month: String(view.month + 1) })}\n </span>\n <button\n type=\"button\"\n className={styles['nav']}\n aria-label={t('calendar.nextMonth')}\n onClick={() => { setView(shiftMonth(view, 1)) }}\n >\n ›\n </button>\n </div>\n <div className={styles['weekdays']}>\n {WEEKDAY_KEYS.map(key => <span key={key} className={styles['weekday']}>{t(key)}</span>)}\n </div>\n <div className={styles['grid']}>\n {monthGrid(view).map(cell => {\n if (!cell.inMonth) {\n // Neighbouring-month days render as blank placeholders so\n // the shown month's date texts stay unique.\n return <span key={`blank-${cell.day}`} className={styles['blank']} aria-hidden=\"true\" />\n }\n const classes = [styles['day']]\n if (cell.day === shown.from || cell.day === shown.to) classes.push(styles['daySelected'])\n else if (shown.from !== '' && cell.day > shown.from && cell.day < shown.to) classes.push(styles['dayInRange'])\n if (cell.day === today) classes.push(styles['dayToday'])\n return (\n <button\n key={cell.day}\n type=\"button\"\n className={classes.join(' ')}\n aria-label={cell.day}\n aria-pressed={cell.day === shown.from || cell.day === shown.to}\n aria-current={cell.day === today ? 'date' : undefined}\n onMouseEnter={() => { setHovered(cell.day) }}\n onMouseLeave={() => { setHovered(null) }}\n onClick={() => { pickDay(cell.day) }}\n >\n {Number(cell.day.slice(8))}\n </button>\n )\n })}\n </div>\n <div className={styles['foot']}>\n <button type=\"button\" className={styles['clear']} onClick={clear}>\n {t('filter.clear')}\n </button>\n </div>\n </div>\n )\n : null}\n </span>\n )\n}\n","/**\n * Menu select (browser half): the filter bar's themed dropdown — one\n * trigger button plus a menu popover. It replaces the native `<select>`,\n * whose UA-painted option list ignores every design token (the shell sets\n * no color-scheme on plugin content, so it renders unthemed), and pairs\n * with the DateRangePicker so all three filter controls share one popover\n * language.\n *\n * Keyboard follows the listbox idiom: opening (trigger click, Enter, or\n * its arrow keys) lands focus on the SELECTED option — scrolled to the\n * center like the native select — or the first one; ArrowUp/Down and\n * Home/End roam (options are tabIndex -1, so Tab skips the list);\n * Enter/Space commits the focused row; Escape closes and returns focus\n * to the trigger; committing closes and refocuses the trigger too. An\n * outside pointerdown closes without stealing focus. The option list\n * carries listbox/option semantics with the selection marked\n * (aria-selected plus a check).\n *\n * The popover interaction copies QuotaButton's pattern verbatim (click\n * toggles, document pointerdown outside closes, Escape closes); the plate\n * styling mirrors the date-range picker's panel.\n *\n * @module token-usage/client/MenuSelect\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'\nimport styles from './MenuSelect.module.css'\n\n/** One selectable entry of the menu. */\nexport interface MenuOption {\n value: string\n label: string\n}\n\n/** Props: the committed value, the option list, and the change lift. */\nexport interface MenuSelectProps {\n value: string\n options: readonly MenuOption[]\n /** Accessible name for the trigger and the listbox popup. */\n ariaLabel: string\n onChange: (next: string) => void\n /** Stretch variant: shrinkable, capped, ellipsized (the model menu). */\n grow?: boolean\n}\n\n/**\n * Render the trigger + menu popover.\n * @param props - the committed value, options, name, and change lift.\n * @returns the inline wrapper holding the trigger and, while open, the list.\n */\nexport function MenuSelect({ value, options, ariaLabel, onChange, grow = false }: MenuSelectProps): ReactNode {\n const rootRef = useRef<HTMLSpanElement>(null)\n const triggerRef = useRef<HTMLButtonElement>(null)\n // One ref per option row; index-aligned with the options prop.\n const optionRefs = useRef<(HTMLButtonElement | null)[]>([])\n const [open, setOpen] = useState(false)\n // The row focus roams over (index into options); a ref, not state — the\n // DOM focus itself is the source of truth, this only remembers it for\n // Enter/Space and re-opening.\n const focusIndexRef = useRef(0)\n\n const close = (): void => {\n setOpen(false)\n triggerRef.current?.focus()\n }\n\n // Opening lands focus on the selected option (or the first), centered\n // in the list — native-select parity, so a long model list opens with\n // the current choice in view.\n const openMenu = (): void => {\n const selected = options.findIndex(option => option.value === value)\n focusIndexRef.current = selected >= 0 ? selected : 0\n setOpen(true)\n }\n\n // Outside pointerdown / Escape close — QuotaButton's pattern, one\n // document listener pair while open. The outside path does NOT steal\n // focus (the user is already interacting elsewhere); Escape refocuses\n // the trigger.\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') close()\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 // After the panel renders: focus the remembered row without scrolling,\n // then center it explicitly (a bare focus() would only kiss the edge).\n // scrollIntoView is guarded — jsdom does not implement it.\n useEffect(() => {\n if (!open) return\n const button = optionRefs.current[focusIndexRef.current]\n if (button === undefined || button === null) return\n button.focus({ preventScroll: true })\n if (typeof button.scrollIntoView === 'function') button.scrollIntoView({ block: 'center' })\n }, [open])\n\n const commit = (index: number): void => {\n const option = options[index]\n if (option === undefined) return\n close()\n onChange(option.value)\n }\n\n const moveFocus = (index: number): void => {\n const next = Math.max(0, Math.min(options.length - 1, index))\n focusIndexRef.current = next\n // A plain focus: the browser scrolls the newly focused row into view\n // with minimal movement, which is what roaming wants.\n optionRefs.current[next]?.focus()\n }\n\n // Roving keys on the panel (events bubble from the option buttons).\n // Enter/Space are handled here with preventDefault so the UA does not\n // synthesize a second click on the focused button.\n const onPanelKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>): void => {\n if (event.key === 'ArrowDown') {\n event.preventDefault()\n moveFocus(focusIndexRef.current + 1)\n } else if (event.key === 'ArrowUp') {\n event.preventDefault()\n moveFocus(focusIndexRef.current - 1)\n } else if (event.key === 'Home') {\n event.preventDefault()\n moveFocus(0)\n } else if (event.key === 'End') {\n event.preventDefault()\n moveFocus(options.length - 1)\n } else if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault()\n commit(focusIndexRef.current)\n }\n }\n\n // The trigger's arrow keys open the menu too (Enter/Space come for free\n // as button clicks).\n const onTriggerKeyDown = (event: ReactKeyboardEvent<HTMLButtonElement>): void => {\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n if (!open) openMenu()\n }\n }\n\n const selected = options.find(option => option.value === value)\n const triggerClass = [styles['trigger'], grow === true ? styles['grow'] : ''].join(' ').trim()\n\n return (\n <span ref={rootRef} className={styles['wrapper']}>\n <button\n type=\"button\"\n ref={triggerRef}\n className={triggerClass}\n aria-label={ariaLabel}\n aria-expanded={open}\n aria-haspopup=\"listbox\"\n onClick={() => { (open ? close() : openMenu()) }}\n onKeyDown={onTriggerKeyDown}\n >\n {selected?.label ?? value}\n </button>\n {open\n ? (\n <div\n className={styles['panel']}\n role=\"listbox\"\n aria-label={ariaLabel}\n onKeyDown={onPanelKeyDown}\n >\n {options.map((option, index) => {\n const isSelected = option.value === value\n const optionClass = [styles['option'], isSelected ? styles['optionSelected'] : ''].join(' ').trim()\n return (\n <button\n key={option.value}\n type=\"button\"\n role=\"option\"\n // Roving focus: only code moves focus into the list, so\n // the rows stay out of the Tab ring.\n tabIndex={-1}\n ref={element => { optionRefs.current[index] = element }}\n className={optionClass}\n aria-selected={isSelected}\n onClick={() => { commit(index) }}\n >\n <span className={styles['optionLabel']}>{option.label}</span>\n {isSelected ? <span className={styles['check']} aria-hidden=\"true\">✓</span> : null}\n </button>\n )\n })}\n </div>\n )\n : null}\n </span>\n )\n}\n","/**\n * The runtime-overhead card's row shape (browser half): one expanded-by-\n * default row per auxiliary kind — the row carries the kind's aggregate\n * (calls · cost · tokens) and discloses its per-model lines on toggle; the\n * total line sits beneath the list. The semantics are the retired table's\n * (same fold, same empty hints, same defensive read of a payload without\n * `aux`); only the shape moved from columns to rows.\n *\n * @module token-usage/client/OverheadRows\n */\n\nimport { useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AuxKind, AuxSummary, CostState } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { totalTokens } from './day.ts'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatTokens } from './format.ts'\nimport list from './UsageRows.module.css'\nimport styles from './OverheadRows.module.css'\n\n/**\n * Render the overhead rows: one disclosure row per kind, then the total\n * line. A summary without auxiliary requests — including an older host\n * payload with no `aux` field at all — renders the empty hint instead, so\n * the card keeps a stable body.\n * @param props - the aux layer of the summary (possibly absent), the cost\n * state, the display currency view, and the locale translator.\n */\nexport function OverheadRows({ aux, costState, view, t }: {\n aux: AuxSummary | undefined\n costState: CostState\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n // Which kinds are collapsed — inverted so the default is every kind\n // expanded (the user's pick): the aggregate row AND its per-model lines\n // show at once, a toggle folds the drill-in away. Each kind toggles\n // independently; switching tabs unmounts the section, which is the\n // natural reset. New kinds arriving on a refresh default to expanded.\n const [collapsedKinds, setCollapsedKinds] = useState<ReadonlySet<AuxKind>>(() => new Set())\n const toggleKind = (auxKind: AuxKind): void => {\n setCollapsedKinds(previous => {\n const next = new Set(previous)\n if (next.has(auxKind)) next.delete(auxKind)\n else next.add(auxKind)\n return next\n })\n }\n if (aux === undefined || aux.total.requests === 0) {\n return <p className={styles['muted']}>{t('aux.empty')}</p>\n }\n const costText = (cost: number): string =>\n costsAvailable(costState) ? formatCost(cost, view) : '—'\n /** One drill-in line: model name ↔ calls · cost · tokens. */\n const modelLine = (model: string, requests: number, cost: number, tokens: number): ReactNode => (\n <span className={styles['dline']}>\n <span className={styles['dmodelName']}>{model}</span>\n <span>\n {t('aux.requestCount', { count: requests.toLocaleString() })}\n {' · '}\n {costText(cost)}\n {' · '}\n {formatTokens(tokens)}\n </span>\n </span>\n )\n const content = (\n <>\n <div className={list['rows']} role=\"list\" aria-label={t('aux.tab')}>\n {(aux.byKind ?? []).map(kindRow => {\n const expanded = !collapsedKinds.has(kindRow.auxKind)\n return (\n <div className={styles['orow']} role=\"listitem\" key={kindRow.auxKind}>\n <div className={styles['orowTop']}>\n {/* The kind row is the parent aggregate AND its own\n * disclosure toggle: chevron + category name in one\n * button (`aria-expanded` carries the state). */}\n <button\n type=\"button\"\n className={styles['kindToggle']}\n aria-expanded={expanded}\n onClick={() => toggleKind(kindRow.auxKind)}\n >\n <span className={styles['chevron']} aria-hidden=\"true\">▸</span>\n {t(`aux.kind.${kindRow.auxKind}`)}\n </button>\n <span className={styles['onums']}>\n {t('aux.requestCount', { count: kindRow.totals.requests.toLocaleString() })}\n {' · '}\n <span className={styles['onumsCost']}>{costText(kindRow.cost)}</span>\n {' · '}\n {formatTokens(totalTokens(kindRow.totals))}\n </span>\n </div>\n {expanded\n ? (\n <div className={styles['adetail']}>\n {(kindRow.byModel ?? []).map(modelRow => (\n <span key={`${kindRow.auxKind}:${modelRow.model}`}>\n {modelLine(modelRow.model, modelRow.totals.requests, modelRow.cost, totalTokens(modelRow.totals))}\n </span>\n ))}\n </div>\n )\n : null}\n </div>\n )\n })}\n </div>\n <div className={styles['asum']}>\n <span>{t('aux.totalCount', { count: aux.total.requests.toLocaleString() })}</span>\n <span>\n <span className={styles['onumsCost']}>{costText(aux.cost)}</span>\n {' · '}\n {formatTokens(totalTokens(aux.total))}\n </span>\n </div>\n </>\n )\n return content\n}\n","/**\n * Project aggregation over root-session rows, shared by the host's full\n * project dimension and the browser's older-host compatibility fallback.\n * The host folds before truncating the session list.\n *\n * @module token-usage/project-rows\n */\n\nimport type { ProjectUsageRow, SessionUsageRow, UsageTotals } from './wire.ts'\n\nfunction totalTokens(totals: UsageTotals): number {\n return totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens\n}\n\n/** The last path segment of a directory, on either separator. */\nexport function dirTailOf(cwd: string): string {\n const parts = cwd.split(/[\\\\/]/u).filter(part => part !== '')\n return parts[parts.length - 1] ?? cwd\n}\n\n/** Element-wise totals sum: the counted fields add, the optional ones\n * treat absence as 0 and stay absent only while both sides lack them. */\nfunction addTotals(left: UsageTotals, right: UsageTotals): UsageTotals {\n const sum: UsageTotals = {\n requests: left.requests + right.requests,\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n cacheReadTokens: left.cacheReadTokens + right.cacheReadTokens,\n cacheWriteTokens: left.cacheWriteTokens + right.cacheWriteTokens,\n }\n const compactions = (left.compactions ?? 0) + (right.compactions ?? 0)\n if (compactions > 0 || left.compactions !== undefined || right.compactions !== undefined) {\n sum.compactions = compactions\n }\n const failures = (left.failures ?? 0) + (right.failures ?? 0)\n if (failures > 0 || left.failures !== undefined || right.failures !== undefined) {\n sum.failures = failures\n }\n if (left.failuresByCode !== undefined || right.failuresByCode !== undefined) {\n const byCode: Record<string, number> = {}\n for (const [code, count] of Object.entries(left.failuresByCode ?? {})) byCode[code] = count\n for (const [code, count] of Object.entries(right.failuresByCode ?? {})) {\n byCode[code] = (byCode[code] ?? 0) + count\n }\n sum.failuresByCode = byCode\n }\n for (const key of ['perfLatencyMsSum', 'perfLatencyCount', 'perfStreamTpsSum', 'perfStreamFirstMsSum', 'perfStreamCount'] as const) {\n if (left[key] !== undefined || right[key] !== undefined) sum[key] = (left[key] ?? 0) + (right[key] ?? 0)\n }\n return sum\n}\n\n/**\n * Fold session rows into one row per directory tail, token-descending (the\n * dashboard's relative bars take the first row as their 100%). The tail is\n * the bucket key — two different full paths ending in the same segment read\n * as one project here, matching the demo's semantics. Within a bucket the\n * first-seen cwd rides along as the representative full path. The input\n * order is preserved inside a bucket (the served rows arrive cost-sorted).\n * @param rows - subtree-folded root sessions; the host supplies the full\n * set, not the truncated session list.\n */\nexport function projectRowsOf(rows: readonly SessionUsageRow[]): ProjectUsageRow[] {\n const buckets = new Map<string, ProjectUsageRow>()\n for (const row of rows) {\n const name = row.cwd === undefined ? '' : dirTailOf(row.cwd)\n const bucket = buckets.get(name)\n if (bucket === undefined) {\n buckets.set(name, {\n name,\n ...(row.cwd === undefined ? {} : { cwd: row.cwd }),\n sessionCount: 1,\n totals: { ...row.totals },\n cost: row.cost,\n })\n continue\n }\n if (bucket.cwd === undefined && row.cwd !== undefined) bucket.cwd = row.cwd\n bucket.sessionCount += 1\n bucket.totals = addTotals(bucket.totals, row.totals)\n bucket.cost += row.cost\n }\n return [...buckets.values()].sort((left, right) => totalTokens(right.totals) - totalTokens(left.totals))\n}\n","/**\n * The dashboards' flat row lists (browser half): one component, four\n * shapes — `project` (directory-tail folds), `model` (the priced rows),\n * `session` (two-line rows) and `provider` (the per-route rows with the\n * unattributed remainder sunk to the bottom). All four read the same\n * single-line grammar of the v3 demo: name | relative bar (projects /\n * models / providers only) | total tokens · cache share | cost; sessions\n * swap the bar for a second identity line (directory · activity) under the\n * same figures cells, all four lists rendering one figures style everywhere\n * (no hover affordance — a former four-bucket popup read as clutter and\n * went).\n *\n * The relative bar scales to\n * the active sort's own measure — tokens while sorted by tokens, billed cost\n * while sorted by cost — so the bars never contradict the order they sit\n * in. Rows arrive FINAL from the host route (folded, sorted, truncated);\n * this component only re-organizes presentation. The Ctrl affordances move\n * with the rows: Ctrl+click on a listed session opens it (dashed\n * underline), Ctrl+click on a model toggles the section's model filter to\n * just that model.\n *\n * @module token-usage/client/UsageRows\n */\n\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { CostState, CostedModelRow, CostedProviderRow, ModelPerf, PricingTable, SessionUsageRow, UsageTotals } from '../wire.ts'\nimport { MIN_PERF_SAMPLES } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { dayKeyOf, totalTokens } from './day.ts'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatSpeed, formatTokens, formatTtft, hitRateDisplay, providerLabel } from './format.ts'\nimport { ModelAssociationBadge, UnpricedModelTag } from './PricingAssociations.tsx'\nimport type { ProjectUsageRow } from './project-rows.ts'\nimport { dirTailOf } from './project-rows.ts'\nimport styles from './UsageRows.module.css'\n\n/** Which row shape the list renders. */\nexport type UsageRowsKind = 'project' | 'model' | 'session' | 'provider'\n\n/** The row lists' controlled sort. `tokens` on projects passes the fold's\n * native order through; `cost` on sessions passes the served order\n * through; models re-sort under both picks (they arrive request-count\n * descending), ties broken by name. Sorting never carries the performance\n * view — that is a content switch ({@link UsageRowsProps.perfView}), not\n * a third pick. */\nexport type RowSort = 'tokens' | 'cost' | 'recent'\n\n/** The label of one sort pick. */\nfunction sortLabelOf(sort: RowSort, t: TranslateNS<'token-usage'>): string {\n return sort === 'tokens' ? t('sort.tokens') : sort === 'cost' ? t('stat.cost') : t('session.lastActive')\n}\n\n/** Sort toggle rendered in a card head / above a tab's list. Controlled —\n * the section owns the state, so the page and the panel keep independent\n * picks. */\nexport function RowSortControl({ value, options, onChange, ariaLabel, t, compact = false }: {\n value: RowSort\n options: readonly RowSort[]\n onChange: (next: RowSort) => void\n ariaLabel: string\n t: TranslateNS<'token-usage'>\n compact?: boolean\n}): ReactNode {\n return (\n <div className={compact ? `${styles['segmented']} ${styles['controlCompact']}` : styles['segmented']} role=\"group\" aria-label={ariaLabel}>\n {options.map(option => (\n <button\n key={option}\n type=\"button\"\n className={value === option ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={value === option}\n onClick={() => onChange(option)}\n >\n {sortLabelOf(option, t)}\n </button>\n ))}\n </div>\n )\n}\n\n/** The performance view toggle (model card head): a view switch, not a\n * third sort pick — pressed, the card shows the speed rows and the sort\n * control yields (the performance order is its own definition: ranked\n * rows by mean speed, the dimmed ones sunk; there is no second way to\n * order them). */\nexport function PerfToggle({ pressed, onToggle, t, compact = false }: {\n pressed: boolean\n onToggle: (next: boolean) => void\n t: TranslateNS<'token-usage'>\n compact?: boolean\n}): ReactNode {\n return (\n <button\n type=\"button\"\n className={[styles['perfToggle'], pressed ? styles['perfOn'] : '', compact ? styles['perfCompact'] : ''].filter(Boolean).join(' ')}\n aria-pressed={pressed}\n aria-label={t('perf.toggle')}\n onClick={() => onToggle(!pressed)}\n >\n <span className={styles['perfGauge']} aria-hidden={true}>◷</span>\n {t('perf.toggle')}\n </button>\n )\n}\n\n/** Whether Ctrl (or ⌘) is held right now: the jump affordances exist only\n * while it is, so plain clicks keep the rows inert. `blur` resets — a focus\n * loss can swallow the keyup and strand the state on. */\nfunction useCtrlHeld(): boolean {\n const [ctrlHeld, setCtrlHeld] = useState(false)\n useEffect(() => {\n const down = (event: KeyboardEvent): void => { if (event.key === 'Control' || event.key === 'Meta') setCtrlHeld(true) }\n const up = (event: KeyboardEvent): void => { if (event.key === 'Control' || event.key === 'Meta') setCtrlHeld(false) }\n const move = (event: MouseEvent): void => {\n const active = event.ctrlKey || event.metaKey\n setCtrlHeld(previous => (previous === active ? previous : active))\n }\n const blur = (): void => setCtrlHeld(false)\n window.addEventListener('keydown', down)\n window.addEventListener('keyup', up)\n window.addEventListener('mousemove', move)\n window.addEventListener('blur', blur)\n return () => {\n window.removeEventListener('keydown', down)\n window.removeEventListener('keyup', up)\n window.removeEventListener('mousemove', move)\n window.removeEventListener('blur', blur)\n }\n }, [])\n return ctrlHeld\n}\n\n/** A short session-id fallback: the leading chunk is usually enough to\n * tell sessions apart when no title ever landed. */\nfunction shortIdOf(sessionId: string): string {\n return sessionId.length > 8 ? `${sessionId.slice(0, 8)}…` : sessionId\n}\n\n/** The unattributed row's hover tooltip: an intro line, then the known\n * reasons a record can carry no route key as a numbered list, each line\n * indented by two spaces (the bubble renders `pre`, so the indent shows).\n * The list is the full closed set — deleted logs, pre-field history, and\n * bypass calls the host never gives a route key — so the reader sees this\n * row is expected, not a bug. */\nfunction unattributedTooltip(t: TranslateNS<'token-usage'>): string {\n const causes = [\n t('byProvider.cause.deletedLog'),\n t('byProvider.cause.preField'),\n t('byProvider.cause.bypass'),\n ]\n return [t('byProvider.cause.intro'), ...causes.map((cause, index) => ` ${index + 1}. ${cause}`)].join('\\n')\n}\n\n/** Relative last-active label (「3 小时前」): minutes inside the first hour,\n * hours inside the first day, days beyond. */\nfunction relativeTimeOf(time: number, t: TranslateNS<'token-usage'>): string {\n const minutes = Math.max(1, Math.floor((Date.now() - time) / 60_000))\n if (minutes < 60) return t('time.minutesAgo', { count: String(minutes) })\n const hours = Math.floor(minutes / 60)\n if (hours < 24) return t('time.hoursAgo', { count: String(hours) })\n return t('time.daysAgo', { count: String(Math.floor(hours / 24)) })\n}\n\n/** Props for the flat row list. Only the array matching `kind` is read;\n * the optional seats (session jump, model filter, price dialog) are absent\n * on tests and hosts without them, and the rows then render inert. */\nexport interface UsageRowsProps {\n kind: UsageRowsKind\n /** `kind: 'project'` — the directory-tail folds. */\n projectRows?: readonly ProjectUsageRow[] | undefined\n /** `kind: 'model'` — the priced per-model rows. */\n modelRows?: readonly CostedModelRow[] | undefined\n /** `kind: 'session'` — the served per-session rows (final order = cost). */\n sessionRows?: readonly SessionUsageRow[] | undefined\n /** `kind: 'provider'` — the priced per-provider rows; `''` is the\n * unattributed remainder row. */\n providerRows?: readonly CostedProviderRow[] | undefined\n /** Provider rows only: the route-key → display-name registry; a key\n * without an entry falls back to the key itself. */\n providerNames?: Readonly<Record<string, string>> | undefined\n /** The controlled sort pick (see {@link RowSort}); the default depends\n * on the kind — `tokens` on project/model, `cost` on session. Ignored\n * while `perfView` is set. */\n sort?: RowSort | undefined\n /** Model rows only: the performance view is up — the figures cells read\n * the speed means, the order is speed-fixed (ranked rows first, the\n * dimmed ones sunk), and the sort pick yields until toggled off. */\n perfView?: boolean | undefined\n /** The pricing table: which models are priced (name is the price\n * affordance) and the rates a model row's cost splits against. */\n pricing?: PricingTable | undefined\n /** The cost layer's state; not `ready`, every cost cell reads `—`. */\n costState?: CostState | undefined\n /** Currency display view (symbol + rate). */\n view: CurrencyView\n /** Locale function. */\n t: TranslateNS<'token-usage'>\n /** Session jump seats: whether the controller lists a session, and the\n * open callback (the parent closes its panel on success). */\n sessionListed?: ((id: string) => boolean) | undefined\n onSessionOpen?: ((id: string) => void) | undefined\n /** Ctrl+click on a model row: toggle the section's model filter. */\n onToggleModel?: ((model: string) => void) | undefined\n /** Plain click on a priced model's name: open the price dialog. */\n onModelName?: ((model: string) => void) | undefined\n}\n\n/**\n * Render one flat row list. The list is the height-capped scroll container\n * (scrollbar appears while scrolling, fades 800ms after it stops).\n */\nexport function UsageRows({\n kind,\n projectRows,\n modelRows,\n sessionRows,\n providerRows,\n providerNames,\n sort,\n perfView,\n pricing,\n costState,\n view,\n t,\n sessionListed,\n onSessionOpen,\n onToggleModel,\n onModelName,\n}: UsageRowsProps): ReactNode {\n const ctrlHeld = useCtrlHeld()\n // Scrollbar fade: add the class on scroll, drop it 800ms after the last\n // event; the timer dies with the component.\n const scrollRef = useRef<HTMLDivElement | null>(null)\n const scrollTimer = useRef<number | undefined>(undefined)\n useEffect(() => () => window.clearTimeout(scrollTimer.current), [])\n const handleScroll = (): void => {\n const box = scrollRef.current\n const cls = styles['scrolling']\n if (box === null || cls === undefined) return\n box.classList.add(cls)\n window.clearTimeout(scrollTimer.current)\n scrollTimer.current = window.setTimeout(() => {\n box.classList.remove(cls)\n }, 800)\n }\n\n // The rendered set for this kind under the active pick. Straight-through\n // where the native order already matches (projects ship tokens-desc,\n // sessions cost-desc); models always re-sort (they arrive request-count\n // descending), ties broken by name for a stable order. The performance\n // view replaces the pick entirely — its order is speed-fixed.\n const perfMode = perfView === true && kind === 'model'\n const active = sort ?? (kind === 'session' ? 'cost' : 'tokens')\n const rows = useMemo<readonly (ProjectUsageRow | CostedModelRow | SessionUsageRow | CostedProviderRow)[]>(() => {\n const base = kind === 'project' ? projectRows : kind === 'model' ? modelRows : kind === 'session' ? sessionRows : providerRows\n if (base === undefined) return []\n if (kind === 'session') {\n if (active === 'cost') return base\n const sessions = [...base] as SessionUsageRow[]\n return sessions.sort(active === 'recent'\n ? (left, right) => right.lastTime - left.lastTime || (left.sessionId < right.sessionId ? -1 : 1)\n : (left, right) => totalTokens(right.totals) - totalTokens(left.totals) || (left.sessionId < right.sessionId ? -1 : 1))\n }\n if (kind === 'project') {\n if (active === 'tokens') return base\n return [...(base as readonly ProjectUsageRow[])].sort((left, right) => right.cost - left.cost || (left.name < right.name ? -1 : 1))\n }\n if (kind === 'provider') {\n // Providers arrive request-count descending with the unattributed\n // remainder sunk; both picks re-sort by their own measure and keep\n // that sink — the remainder is a reconciliation row, not a provider.\n const unattributedLast = (row: CostedProviderRow): number => row.provider === '' ? 1 : 0\n return [...(base as readonly CostedProviderRow[])].sort((left, right) =>\n unattributedLast(left) - unattributedLast(right)\n || (active === 'cost'\n ? right.cost - left.cost\n : totalTokens(right.totals) - totalTokens(left.totals))\n || (left.provider < right.provider ? -1 : 1))\n }\n const models = [...base] as CostedModelRow[]\n if (perfMode) {\n // Speed ranking over the streaming samples. A row without enough\n // samples (or any timing) cannot rank honestly, so it sinks below\n // the ranked ones, name-ordered — the same rows drop their bar.\n const ranked = (row: CostedModelRow): boolean =>\n row.perf !== undefined && row.perf.samples >= MIN_PERF_SAMPLES\n return models.sort((left, right) => {\n const leftRanked = ranked(left)\n const rightRanked = ranked(right)\n if (leftRanked !== rightRanked) return leftRanked ? -1 : 1\n if (leftRanked && rightRanked) {\n return right.perf!.tokensPerSec - left.perf!.tokensPerSec || (left.model < right.model ? -1 : 1)\n }\n return left.model < right.model ? -1 : 1\n })\n }\n return models.sort(active === 'tokens'\n ? (left, right) => totalTokens(right.totals) - totalTokens(left.totals) || (left.model < right.model ? -1 : 1)\n : (left, right) => right.cost - left.cost || (left.model < right.model ? -1 : 1))\n }, [kind, projectRows, modelRows, sessionRows, providerRows, active, perfMode])\n\n // The bar scale: the tallest row of the *rendered* set is 100%,\n // measured in the active unit — a cost-sorted list bars by cost, the\n // performance view by mean speed (ranked rows only: the dimmed\n // low-sample rows drop their bar and must not stretch the scale), or\n // the bars would contradict the order they sit in. Zero renders\n // zero-width bars (never NaN). The provider list follows the same\n // rule for its unattributed remainder: it is the difference between\n // the named routes and the top line, not a route — it drops its bar\n // and must not stretch the scale the named routes are drawn against.\n const barValueOf = (row: ProjectUsageRow | CostedModelRow | SessionUsageRow | CostedProviderRow): number =>\n perfMode ? ('perf' in row && row.perf !== undefined && row.perf.samples >= MIN_PERF_SAMPLES ? row.perf.tokensPerSec : 0)\n : kind === 'provider' && (row as CostedProviderRow).provider === '' ? 0\n : active === 'cost' ? row.cost\n : totalTokens(row.totals)\n const barMax = useMemo(() => {\n let max = 0\n for (const row of rows) {\n const value = barValueOf(row)\n if (value > max) max = value\n }\n return max\n }, [rows, active])\n\n const costText = (cost: number): string =>\n costsAvailable(costState) ? formatCost(cost, view) : '—'\n\n /** The figures cell: total tokens · cache share, right-aligned in its\n * fixed column. No hover affordance — the user read the popup as\n * clutter on every list, so the cell is plain. */\n const numsCell = (totals: UsageTotals): ReactNode => {\n const hit = hitRateDisplay(totals)\n return (\n <span className={styles['rowNums']}>\n {formatTokens(totalTokens(totals))}\n {' · '}\n {t('stat.cacheRead')}\n {' '}\n {hit.text}\n </span>\n )\n }\n\n /** The performance figures cell: mean speed (bold) · first token · mean\n * request latency · timed request count over one compact line, the grammar\n * every figures cell reads. Below the streaming-sample threshold the\n * cell dims to speed + 「样本不足」, and no timing at all renders its\n * own dim label. Untimed requests never count as performance samples.\n * No hover affordance. */\n const perfCell = (perf: ModelPerf | undefined): ReactNode => {\n const count = t('perf.requestCount', { count: String(perf?.timedRequests ?? 0) })\n if (perf === undefined) {\n return <span className={`${styles['perfNums']} ${styles['perfDim']}`}>{t('perf.noTiming')} · {count}</span>\n }\n const speed = `${formatSpeed(perf.tokensPerSec)} tok/s`\n if (perf.samples < MIN_PERF_SAMPLES) {\n return (\n <span className={`${styles['perfNums']} ${styles['perfDim']}`}>\n <b>{speed}</b>\n {' · '}\n {t('perf.lowSamples')}\n {' · '}\n {count}\n </span>\n )\n }\n return (\n <span className={styles['perfNums']}>\n <b>{speed}</b>\n {' · '}\n {t('perf.first')}\n {' '}\n {formatTtft(perf.firstTokenMs)}\n {' · '}\n {t('perf.avgLatency')}\n {' '}\n {formatTtft(perf.latencyMs)}\n {' · '}\n {count}\n </span>\n )\n }\n\n const ariaLabel = kind === 'project' ? t('byProject.title')\n : kind === 'model' ? t('byModel.title')\n : kind === 'session' ? t('bySession.title') : t('byProvider.title')\n\n return (\n <div className={styles['rows']} ref={scrollRef} onScroll={handleScroll} role=\"list\" aria-label={ariaLabel}>\n {rows.length === 0\n ? <div className={styles['empty']}>{t('chart.empty')}</div>\n : rows.map(row => {\n if (kind === 'project') {\n const project = row as ProjectUsageRow\n return (\n <div className={styles['row']} role=\"listitem\" key={project.name === '' ? '\\u0000' : project.name}>\n <span className={styles['rowName']} title={project.cwd ?? project.name}>\n {project.name === '' ? t('session.untitledDir') : project.name}\n </span>\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(project) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n {numsCell(project.totals)}\n <span className={styles['rowCost']}>{costText(project.cost)}</span>\n </div>\n )\n }\n if (kind === 'model') {\n const model = row as CostedModelRow\n const rules = pricing?.[model.model]\n const filterJump = ctrlHeld && onToggleModel !== undefined\n // Under the performance view a row that cannot rank honestly\n // (too few streaming samples, or no timing) drops its bar and\n // lets the name take the width.\n const perfRanked = model.perf !== undefined && model.perf.samples >= MIN_PERF_SAMPLES\n return (\n <div className={styles['row']} role=\"listitem\" key={model.model}>\n <span className={perfMode && !perfRanked ? `${styles['rowName']} ${styles['nameGrow']}` : styles['rowName']}>\n <span className={styles['nameLine']}>\n {rules !== undefined\n ? (\n // Same affordance as the per-model table: the\n // name opens the price dialog — unless Ctrl is\n // held, when it toggles the model filter instead.\n <button\n type=\"button\"\n className={filterJump ? `${styles['nameText']} ${styles['jumpable']}` : styles['nameText']}\n title={filterJump ? t('model.ctrlHint') : undefined}\n aria-label={filterJump ? t('model.ctrlHint') : t('pricing.view', { model: model.model })}\n onClick={filterJump\n ? event => {\n event.preventDefault()\n onToggleModel?.(model.model)\n }\n : () => onModelName?.(model.model)}\n >\n {model.model}\n </button>\n )\n : <span className={styles['nameText']}>{model.model}</span>}\n {rules !== undefined ? null : <UnpricedModelTag model={model.model} t={t} />}\n <ModelAssociationBadge model={model.model} t={t} />\n </span>\n </span>\n {perfMode\n ? (perfRanked\n ? (\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(model) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n )\n : null)\n : (\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(model) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n )}\n {/* The performance view swaps the figures cell for the\n * speed means and drops the cost column — the row ends at\n * its figures, the same shape the demo pinned. */}\n {perfMode ? perfCell(model.perf) : numsCell(model.totals)}\n {perfMode\n ? null\n : <span className={styles['rowCost']}>{rules !== undefined ? costText(model.cost) : '—'}</span>}\n </div>\n )\n }\n if (kind === 'provider') {\n const provider = row as CostedProviderRow\n const unattributed = provider.provider === ''\n return (\n <div className={styles['row']} role=\"listitem\" key={unattributed ? '\\u0000' : provider.provider}>\n <span\n className={unattributed ? `${styles['rowName']} ${styles['nameDim']}` : styles['rowName']}\n title={unattributed ? undefined : provider.provider}\n >\n <span className={styles['nameLine']}>\n {unattributed\n ? (\n <span className={styles['hintWrap']}>\n <Tooltip label={unattributedTooltip(t)} side=\"bottom\" delayMs={100}>\n <span\n className={styles['nameText']}\n aria-label={t('byProvider.unattributed')}\n tabIndex={0}\n >\n {t('byProvider.unattributed')}\n <span className={styles['nameHint']} aria-hidden={true}>?</span>\n </span>\n </Tooltip>\n </span>\n )\n : <span className={styles['nameText']}>{providerLabel(provider.provider, providerNames)}</span>}\n </span>\n </span>\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(provider) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n {numsCell(provider.totals)}\n <span className={styles['rowCost']}>{costText(provider.cost)}</span>\n </div>\n )\n }\n const session = row as SessionUsageRow\n // A session row is jumpable when the controller lists it; the\n // click re-checks through onSessionOpen (the list may have moved\n // between hover and click).\n const jump = ctrlHeld && sessionListed !== undefined && onSessionOpen !== undefined && sessionListed(session.sessionId)\n return (\n <div className={`${styles['row']} ${styles['srow']}`} role=\"listitem\" key={session.sessionId}>\n {/* The top line reads like every other row: name | total\n * tokens · cache share | cost (the same figures cell, same\n * hover tooltip — no cost row, no model mix to apportion\n * against). The second line keeps directory · activity. */}\n <div className={styles['rowTop']}>\n <span className={styles['rowName']}>\n <span className={styles['nameLine']}>\n <button\n type=\"button\"\n className={jump ? `${styles['nameText']} ${styles['jumpable']}` : styles['nameText']}\n title={jump ? t('session.openHint') : undefined}\n onClick={jump || (ctrlHeld && onSessionOpen !== undefined)\n ? event => {\n event.preventDefault()\n onSessionOpen?.(session.sessionId)\n }\n : undefined}\n >\n {session.title !== undefined\n ? session.title\n : `${shortIdOf(session.sessionId)} · ${dayKeyOf(new Date(session.firstTime))} – ${dayKeyOf(new Date(session.lastTime))}`}\n </button>\n {session.childCount !== undefined && session.childCount > 0\n ? (\n <span\n className={styles['badge']}\n aria-label={t('view.subagents.nested', { count: String(session.childCount) })}\n >\n {t('view.subagents.nested', { count: String(session.childCount) })}\n </span>\n )\n : null}\n </span>\n </span>\n {numsCell(session.totals)}\n <span className={styles['rowCost']}>{costText(session.cost)}</span>\n </div>\n <div className={styles['rowSub']}>\n {session.cwd === undefined ? t('session.untitledDir') : dirTailOf(session.cwd)}\n {' · '}\n {relativeTimeOf(session.lastTime, t)}\n </div>\n </div>\n )\n })}\n </div>\n )\n}\n","/**\n * The main page's dashboard (browser half): the equal-height cards in a\n * two-column grid — projects | sessions, models | providers, runtime\n * overhead on the last row — each a card head (title + count, the session\n * head carrying the sort) over the same flat row lists the settings\n * panel's tabs use. The runtime-overhead card is the scroll/flash target\n * of the composite metric card's overhead pill.\n *\n * @module token-usage/client/DashboardCards\n */\n\nimport type { RefObject } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AuxSummary, CostState, CostedModelRow, CostedProviderRow, PricingTable, SessionUsageRow } from '../wire.ts'\nimport { OverheadRows } from './OverheadRows.tsx'\nimport { UsageRows, RowSortControl, PerfToggle } from './UsageRows.tsx'\nimport type { RowSort } from './UsageRows.tsx'\nimport type { ProjectUsageRow } from './project-rows.ts'\nimport type { CurrencyView } from './format.ts'\nimport styles from './DashboardCards.module.css'\n\n/** The cards' fixed sort options: projects, models and providers pick\n * between token size and billed cost; sessions add last activity. The\n * models' performance view is a separate head toggle, not a sort pick. */\nconst SORT_PROJECT: readonly RowSort[] = ['tokens', 'cost']\nconst SORT_SESSION: readonly RowSort[] = ['tokens', 'cost', 'recent']\nconst SORT_MODEL: readonly RowSort[] = ['tokens', 'cost']\nconst SORT_PROVIDER: readonly RowSort[] = ['tokens', 'cost']\n\n/** Props for the four-card dashboard. Every list arrives final from the\n * section; the seats (session jump, model filter, price dialog) pass\n * through to the rows. */\nexport interface DashboardCardsProps {\n /** The directory-tail folds (projects card). */\n projectRows: readonly ProjectUsageRow[]\n /** The priced per-model rows (models card). */\n modelRows: readonly CostedModelRow[]\n /** The served per-session rows (sessions card). */\n sessionRows: readonly SessionUsageRow[]\n /** The three lists' controlled sorts (tokens/cost; sessions add last\n * activity). */\n projectSort: RowSort\n onProjectSortChange: (next: RowSort) => void\n modelSort: RowSort\n onModelSortChange: (next: RowSort) => void\n /** The models card's performance view (a content switch next to the\n * sort control, not a sort pick); up, the card reads the speed rows\n * and the sort control yields its seat. */\n modelPerfView: boolean\n onModelPerfToggle: (next: boolean) => void\n /** The priced per-provider rows (providers card); `''` is the\n * unattributed remainder row. */\n providerRows: readonly CostedProviderRow[]\n /** Route key → display name for the provider rows. */\n providerNames: Readonly<Record<string, string>> | undefined\n providerSort: RowSort\n onProviderSortChange: (next: RowSort) => void\n sessionSort: RowSort\n onSessionSortChange: (next: RowSort) => void\n /** The auxiliary layer (overhead card; absent renders the empty hint). */\n aux: AuxSummary | undefined\n pricing: PricingTable\n costState: CostState\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n /** Seats passed through to the row lists (absent on bare hosts). */\n sessionListed?: ((id: string) => boolean) | undefined\n onSessionOpen?: ((id: string) => void) | undefined\n onToggleModel?: ((model: string) => void) | undefined\n onModelName?: ((model: string) => void) | undefined\n /** The overhead card's ref: the metric card's pill scrolls here. */\n overheadCardRef: RefObject<HTMLDivElement>\n /** True while the overhead card flashes (pill just clicked). */\n overheadFlash: boolean\n}\n\n/**\n * Render the dashboard: projects | sessions on the first row, models |\n * providers on the second, runtime overhead on the last. The lists cap\n * their own height and scroll inside the cards.\n */\nexport function DashboardCards({\n projectRows,\n modelRows,\n sessionRows,\n projectSort,\n onProjectSortChange,\n modelSort,\n onModelSortChange,\n modelPerfView,\n onModelPerfToggle,\n providerRows,\n providerNames,\n providerSort,\n onProviderSortChange,\n sessionSort,\n onSessionSortChange,\n aux,\n pricing,\n costState,\n view,\n t,\n sessionListed,\n onSessionOpen,\n onToggleModel,\n onModelName,\n overheadCardRef,\n overheadFlash,\n}: DashboardCardsProps): ReactNode {\n // The unattributed remainder is the difference between the named routes\n // and the top line, not a route: it never counts as a provider.\n const namedProviderCount = providerRows.filter(row => row.provider !== '').length\n return (\n <div className={styles['grid2']}>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('board.projects')}\n <span className={styles['panelCount']}>\n {projectSort === 'cost'\n ? t('board.byCost', { count: projectRows.length.toLocaleString() })\n : t('board.byTokens', { count: projectRows.length.toLocaleString() })}\n </span>\n </span>\n <RowSortControl\n value={projectSort}\n options={SORT_PROJECT}\n onChange={onProjectSortChange}\n ariaLabel={t('board.projects')}\n t={t}\n />\n </div>\n <UsageRows\n kind=\"project\"\n projectRows={projectRows}\n sort={projectSort}\n pricing={pricing}\n costState={costState}\n view={view}\n t={t}\n />\n </div>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('board.sessions')}\n <span className={styles['panelCount']}>\n {t('board.sessionsCount', { count: sessionRows.length.toLocaleString() })}\n </span>\n </span>\n <RowSortControl\n value={sessionSort}\n options={SORT_SESSION}\n onChange={onSessionSortChange}\n ariaLabel={t('board.sessions')}\n t={t}\n />\n </div>\n <UsageRows\n kind=\"session\"\n sessionRows={sessionRows}\n sort={sessionSort}\n costState={costState}\n view={view}\n t={t}\n sessionListed={sessionListed}\n onSessionOpen={onSessionOpen}\n />\n </div>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelHeadLeft']}>\n <span className={styles['panelTitle']}>\n {t('board.models')}\n <span className={styles['panelCount']}>\n {modelPerfView\n ? t('board.bySpeed', { count: modelRows.length.toLocaleString() })\n : modelSort === 'cost'\n ? t('board.byCost', { count: modelRows.length.toLocaleString() })\n : t('board.byTokens', { count: modelRows.length.toLocaleString() })}\n </span>\n </span>\n </span>\n <span className={styles['panelHeadRight']}>\n <span className={modelPerfView ? styles['headHidden'] : undefined}>\n <RowSortControl\n value={modelSort}\n options={SORT_MODEL}\n onChange={onModelSortChange}\n ariaLabel={t('board.models')}\n t={t}\n />\n </span>\n <PerfToggle pressed={modelPerfView} onToggle={onModelPerfToggle} t={t} />\n </span>\n </div>\n <UsageRows\n kind=\"model\"\n modelRows={modelRows}\n sort={modelSort}\n perfView={modelPerfView}\n pricing={pricing}\n costState={costState}\n view={view}\n t={t}\n onToggleModel={onToggleModel}\n onModelName={onModelName}\n />\n </div>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('board.providers')}\n <span className={styles['panelCount']}>\n {/* The unattributed remainder is the difference between the\n named routes and the top line, not a route: it never\n counts towards the number of providers. */}\n {providerSort === 'cost'\n ? t('board.byCost', { count: namedProviderCount.toLocaleString() })\n : t('board.byTokens', { count: namedProviderCount.toLocaleString() })}\n </span>\n </span>\n <RowSortControl\n value={providerSort}\n options={SORT_PROVIDER}\n onChange={onProviderSortChange}\n ariaLabel={t('board.providers')}\n t={t}\n />\n </div>\n <UsageRows\n kind=\"provider\"\n providerRows={providerRows}\n providerNames={providerNames}\n sort={providerSort}\n costState={costState}\n view={view}\n t={t}\n />\n </div>\n <div ref={overheadCardRef} className={overheadFlash ? `${styles['panel']} ${styles['flash']}` : styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('aux.tab')}\n <span className={styles['panelCount']}>{t('aux.subtitle')}</span>\n </span>\n </div>\n <OverheadRows aux={aux} costState={costState} view={view} t={t} />\n </div>\n </div>\n )\n}\n","/**\n * Shared \"stat card\" primitive: label on top, value underneath. Used by the\n * settings section (primary cards + four token-bucket cards) and the Usage\n * view tab (six cards: requests-with-failure-pill / cost / total tokens /\n * hit rate / TTFT / token speed). Centralising the markup + styling means\n * the two surfaces read as one family without each one carrying its own\n * copy of the label-on-top / value-below rule.\n *\n * {@link FailurePill} is the compact failed-count chip the requests card\n * uses; {@link OverheadPill} is its neutral sibling for the recorded\n * auxiliary-request count, wired to jump to the runtime-overhead section.\n * Per-model tables use {@link RequestsCell} (`A/B`, B in the error\n * color) instead — a pill is too much chrome for a numeric column.\n *\n * @module token-usage/client/StatCard\n */\n\nimport type { ReactNode } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { UsageAuxKindRow } from '../wire.ts'\nimport { failuresTooltip, overheadTooltip } from './format.ts'\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 /** Settings uses `'sm'` for a fixed four-by-two overview (16px figures).\n * The wide-column variant (`'lg'`): the v3 demo's figures — 20px\n * value over a 12px label in a roomier tile. The page's nine-track\n * row renders it; the Usage view keeps the default figures. */\n size?: 'sm' | 'lg' | undefined\n /** A node riding beside the label (not below it): the compact lead\n * card's overhead pill. The narrow tile would wrap a pill on the\n * value line and stretch the whole grid row; up here it fits. */\n labelExtra?: ReactNode | undefined\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, size, labelExtra }: StatCardProps): ReactNode {\n const card = size === 'lg' ? `${styles['card']} ${styles['cardLg']}`\n : size === 'sm' ? `${styles['card']} ${styles['cardSm']}` : styles['card']\n return (\n <div className={card}>\n {labelExtra === undefined\n ? <span className={styles['cardLabel']}>{label}</span>\n : (\n <span className={styles['cardLabelRow']}>\n <span className={styles['cardLabel']}>{label}</span>\n {labelExtra}\n </span>\n )}\n <span className={styles['cardValue']}>{value}</span>\n </div>\n )\n}\n\n/** Props for the shared failure-count pill. */\nexport interface FailurePillProps {\n /** Failed provider attempts; 0 renders nothing. */\n failures: number\n /** Per-code breakdown driving the tooltip. */\n failuresByCode: Record<string, number> | undefined\n /** Locale function (`stat.failuresPill` / `fail.*`). */\n t: TranslateNS<'token-usage'>\n /** Render as bare red text instead of the capsule: the compact lead\n * card's value line fits a six-digit count plus the breakdown only\n * without the pill chrome — a capsule there wraps to a third line and\n * stretches the whole grid row. Same tooltip and keyboard focus. */\n bare?: boolean | undefined\n}\n\n/**\n * Compact \"失败 n\" chip for the requests **card** only. Hovering or focusing\n * it lists `限流 ×count` per class. Zero failures render nothing. Per-model\n * tables do not use this — they print `A/B` via {@link RequestsCell}.\n */\nexport function FailurePill({\n failures,\n failuresByCode,\n t,\n bare = false,\n}: FailurePillProps): ReactNode {\n if (failures === 0) return null\n return (\n <span className={styles['pillWrap']}>\n <Tooltip\n label={failuresTooltip(failuresByCode, t)}\n side=\"bottom\"\n delayMs={200}\n >\n {bare\n ? (\n <span\n className={styles['failBare']}\n tabIndex={0}\n aria-label={t('stat.failuresPill', { count: failures.toLocaleString() })}\n >\n {t('stat.failuresPill', { count: failures.toLocaleString() })}\n </span>\n )\n : (\n <span className={styles['pill']} tabIndex={0}>\n {t('stat.failuresPill', { count: failures.toLocaleString() })}\n </span>\n )}\n </Tooltip>\n </span>\n )\n}\n\n/** Props for the shared successful-requests card with a failure pill. */\nexport interface RequestsStatCardProps {\n /** Successful (billed) request count. */\n requests: number\n /** Failed provider attempts. */\n failures: number\n /** Per-code breakdown driving the pill tooltip. */\n failuresByCode: Record<string, number> | undefined\n /** Locale function (zh/en `stat.requests` / `stat.failuresPill`). */\n t: TranslateNS<'token-usage'>\n /** Recorded auxiliary request count; > 0 shows the neutral pill. */\n overheadRequests?: number | undefined\n /** Per-kind split driving the overhead pill's tooltip. */\n overheadByKind?: readonly UsageAuxKindRow[] | undefined\n /** Click on the overhead pill: the dashboards scroll to / switch to the\n * runtime-overhead section. Omitted hosts keep the pill inert. */\n onOverheadActivate?: (() => void) | undefined\n /** Stat-card pass-throughs: the page's `'lg'` figures, and a node on\n * the label row (the compact lead card parks the overhead pill there —\n * on the value line it would wrap and stretch the grid row). */\n size?: 'sm' | 'lg' | undefined\n labelExtra?: ReactNode | undefined\n /** Bare-text failure count (no capsule): the compact lead card's value\n * line — a six-digit count plus a capsule overruns the narrow tile. */\n failureBare?: boolean | undefined\n}\n\n/**\n * The requests tile both dashboards share: hero figure is the successful\n * count; a compact pill to its right carries the failure count, and — when\n * auxiliary requests were recorded — a neutral pill carries the runtime-\n * overhead count (hover for the per-kind split, click to jump there).\n */\nexport function RequestsStatCard({\n requests,\n failures,\n failuresByCode,\n t,\n overheadRequests,\n overheadByKind,\n onOverheadActivate,\n size,\n labelExtra,\n failureBare = false,\n}: RequestsStatCardProps): ReactNode {\n return (\n <StatCard\n label={t('stat.requests')}\n size={size}\n labelExtra={labelExtra}\n value={(\n <>\n <span className={styles['cardValueMain']}>{requests.toLocaleString()}</span>\n <FailurePill failures={failures} failuresByCode={failuresByCode} t={t} {...(failureBare ? { bare: true } : {})} />\n <OverheadPill\n requests={overheadRequests}\n byKind={overheadByKind}\n onActivate={onOverheadActivate}\n t={t}\n />\n </>\n )}\n />\n )\n}\n\n/** Props for the shared overhead pill: a neutral count chip that lists the\n * per-kind split on hover and activates the overhead section on click. */\nexport interface OverheadPillProps {\n /** Recorded auxiliary request count; 0 or undefined renders nothing. */\n requests: number | undefined\n /** Per-kind breakdown driving the tooltip. */\n byKind: readonly UsageAuxKindRow[] | undefined\n /** Click callback (scroll-to on the page, tab-switch on the panel). */\n onActivate?: (() => void) | undefined\n /** Locale function (`stat.overheadPill` / `aux.kind.*`). */\n t: TranslateNS<'token-usage'>\n}\n\n/**\n * Compact \"开销 n\" chip beside the hero request count. Mirrors\n * {@link FailurePill} in neutral ink and is a real button — the dashboards\n * wire it to scroll-to (page) or switch-to (panel) the runtime-overhead\n * section. Zero recorded overhead renders nothing.\n */\nexport function OverheadPill({\n requests,\n byKind,\n onActivate,\n t,\n}: OverheadPillProps): ReactNode {\n if (requests === undefined || requests === 0) return null\n return (\n <span className={styles['pillWrap']}>\n <Tooltip\n label={overheadTooltip(byKind, t)}\n side=\"bottom\"\n delayMs={200}\n >\n <button\n type=\"button\"\n className={styles['pillNeutral']}\n onClick={onActivate}\n >\n {t('stat.overheadPill', { count: requests.toLocaleString() })}\n </button>\n </Tooltip>\n </span>\n )\n}\n\n/** Props for the per-model requests cell: `success/fail` as `A/B`.\n * Tables pass the row's own totals so a session-scoped or date-filtered\n * summary cannot leak another row's failures into this cell. */\nexport interface RequestsCellProps {\n requests: number\n failures: number\n failuresByCode: Record<string, number> | undefined\n t: TranslateNS<'token-usage'>\n}\n\n/** One table cell: the successful count, and when failures > 0 the\n * failure count after a slash, in the error color and hoverable for the\n * per-code breakdown.\n *\n * The column is ONE plain column: the figures are plain inline text, so\n * the head above them inherits the same alignment and the two share one\n * edge — no tracks, no grid, no placeholder. Zero failures print only\n * the successful count (no slash, no `0`). */\nexport function RequestsCell({\n requests,\n failures,\n failuresByCode,\n t,\n}: RequestsCellProps): ReactNode {\n const ok = requests.toLocaleString()\n if (failures === 0) {\n return <span>{ok}</span>\n }\n const fail = failures.toLocaleString()\n return (\n <span>\n <span>{ok}</span>\n <span className={styles['splitSep']} aria-hidden>/</span>\n <span className={styles['failWrap']}>\n <Tooltip\n label={failuresTooltip(failuresByCode, t)}\n side=\"bottom\"\n delayMs={200}\n >\n <span\n className={styles['splitFail']}\n tabIndex={0}\n aria-label={t('stat.failuresPill', { count: fail })}\n >\n {fail}\n </span>\n </Tooltip>\n </span>\n </span>\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 * Trend-chart SVG path geometry: a polyline, optionally patched across\n * temporal gaps. Pure functions, no React.\n *\n * @module token-usage/client/trend-chart/path\n */\n\n/** How consecutive points are joined. */\nexport type PathStyle = 'polyline' | 'gap'\n\n/**\n * Per-segment gap flags: `flags[i]` is true when the next bucket starts\n * after this bucket's exclusive `end`. Adjacent uniform buckets have\n * `next.time === prev.end` and are not gaps.\n */\nexport function gapAfter(points: readonly { time: number; end: number }[]): boolean[] {\n const flags: boolean[] = []\n for (let index = 0; index < points.length - 1; index += 1) {\n flags.push(points[index + 1]!.time > points[index]!.end)\n }\n return flags\n}\n\n/**\n * SVG `d` for already-scaled coordinates. Empty → `''`; one point → `M`.\n *\n * `gap` is the original polyline plus a patch: adjacent buckets stay a\n * straight `L`; a gap holds `hold` (`zero` = axis, `previous` = last y)\n * from the previous bucket's end until one bucket-width before the next\n * start, then slants in — so idle is not interpolated and dense hours\n * keep the polyline.\n */\nexport function seriesPath(input: {\n xs: readonly number[]\n ys: readonly number[]\n yZero: number\n style: PathStyle\n hold?: 'zero' | 'previous'\n gaps?: readonly boolean[]\n xEnds?: readonly number[]\n}): string {\n const { xs, ys, yZero, style, hold, gaps, xEnds } = input\n if (xs.length === 0) return ''\n const cmd = (letter: 'M' | 'L', x: number, y: number): string =>\n `${letter}${x.toFixed(1)},${y.toFixed(1)}`\n const parts: string[] = [cmd('M', xs[0]!, ys[0]!)]\n for (let index = 0; index < xs.length - 1; index += 1) {\n const xNext = xs[index + 1]!\n const yNext = ys[index + 1]!\n if (style === 'gap' && gaps?.[index] === true) {\n const ends = xEnds ?? xs\n const xEnd = ends[index]!\n const nextWidth = Math.max(ends[index + 1]! - xNext, 0)\n const xHold = Math.max(xEnd, xNext - nextWidth)\n const holdY = hold === 'previous' ? ys[index]! : yZero\n parts.push(cmd('L', xEnd, holdY), cmd('L', xHold, holdY), cmd('L', xNext, yNext))\n } else {\n parts.push(cmd('L', xNext, yNext))\n }\n }\n return parts.join(' ')\n}\n\n/**\n * Generate a smooth cubic Bezier path using Fritsch-Carlson monotone cubic\n * Hermite interpolation. Preserves monotonicity so zero-filled plateaus stay\n * strictly flat at baseline without undershooting, and peaks round smoothly.\n *\n * @param xs - scaled x coordinates (monotonic ascending).\n * @param ys - scaled y coordinates.\n * @returns SVG `d` string containing M, L, and C commands.\n */\nexport function monotoneSplinePath(xs: readonly number[], ys: readonly number[]): string {\n const n = xs.length\n if (n === 0) return ''\n if (n === 1) return `M${xs[0]!.toFixed(1)},${ys[0]!.toFixed(1)}`\n if (n === 2) {\n return `M${xs[0]!.toFixed(1)},${ys[0]!.toFixed(1)} L${xs[1]!.toFixed(1)},${ys[1]!.toFixed(1)}`\n }\n\n // 1. Calculate secant slopes between adjacent points.\n const dx: number[] = []\n const slopes: number[] = []\n for (let i = 0; i < n - 1; i += 1) {\n const dX = xs[i + 1]! - xs[i]!\n const dY = ys[i + 1]! - ys[i]!\n dx.push(dX)\n slopes.push(dX === 0 ? 0 : dY / dX)\n }\n\n // 2. Initialize tangent slopes at each point.\n const m: number[] = new Array(n)\n m[0] = slopes[0]!\n m[n - 1] = slopes[n - 2]!\n for (let i = 1; i < n - 1; i += 1) {\n const s0 = slopes[i - 1]!\n const s1 = slopes[i]!\n if (s0 * s1 <= 0) {\n m[i] = 0\n } else {\n m[i] = (s0 + s1) / 2\n }\n }\n\n // 3. Fritsch-Carlson bounds: eliminate overshoot / undershoot.\n for (let i = 0; i < n - 1; i += 1) {\n const slope = slopes[i]!\n if (slope === 0) {\n m[i] = 0\n m[i + 1] = 0\n } else {\n const alpha = m[i]! / slope\n const beta = m[i + 1]! / slope\n const dist = alpha * alpha + beta * beta\n if (dist > 9) {\n const tau = 3 / Math.sqrt(dist)\n m[i] = tau * alpha * slope\n m[i + 1] = tau * beta * slope\n }\n }\n }\n\n // 4. Construct cubic Bezier commands.\n const parts: string[] = [`M${xs[0]!.toFixed(1)},${ys[0]!.toFixed(1)}`]\n for (let i = 0; i < n - 1; i += 1) {\n const dX = dx[i]!\n const x0 = xs[i]!\n const y0 = ys[i]!\n const x1 = xs[i + 1]!\n const y1 = ys[i + 1]!\n const cp1x = x0 + dX / 3\n const cp1y = y0 + m[i]! * (dX / 3)\n const cp2x = x1 - dX / 3\n const cp2y = y1 - m[i + 1]! * (dX / 3)\n parts.push(\n `C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${x1.toFixed(1)},${y1.toFixed(1)}`,\n )\n }\n return parts.join(' ')\n}\n\n/**\n * Close a line/curve path down to the baseline (`yZero`) to form an area polygon.\n * Returns an empty string when the input path is empty or has fewer than 2 points.\n *\n * @param linePath - the line or curve `d` string.\n * @param xs - the plotted x coordinates.\n * @param yZero - the baseline y coordinate.\n * @returns SVG `d` string closed with Z for fill.\n */\nexport function areaPath(linePath: string, xs: readonly number[], yZero: number): string {\n if (linePath === '' || xs.length < 2) return ''\n const firstX = xs[0]!.toFixed(1)\n const lastX = xs[xs.length - 1]!.toFixed(1)\n const baseY = yZero.toFixed(1)\n return `${linePath} L${lastX},${baseY} L${firstX},${baseY} Z`\n}\n\n/**\n * Return coordinates with gap hold points inserted so temporal series can be\n * smoothly interpolated with monotonic cubic splines without smearing idle spans.\n */\nexport function gapPatchedPoints(input: {\n xs: readonly number[]\n ys: readonly number[]\n yZero: number\n hold?: 'zero' | 'previous' | undefined\n gaps?: readonly boolean[] | undefined\n xEnds?: readonly number[] | undefined\n}): { xs: number[]; ys: number[] } {\n const { xs, ys, yZero, hold, gaps, xEnds } = input\n if (xs.length === 0) return { xs: [], ys: [] }\n const outXs: number[] = [xs[0]!]\n const outYs: number[] = [ys[0]!]\n for (let index = 0; index < xs.length - 1; index += 1) {\n const xNext = xs[index + 1]!\n const yNext = ys[index + 1]!\n if (gaps?.[index] === true) {\n const ends = xEnds ?? xs\n const xEnd = ends[index]!\n const nextWidth = Math.max(ends[index + 1]! - xNext, 0)\n const xHold = Math.max(xEnd, xNext - nextWidth)\n const holdY = hold === 'previous' ? ys[index]! : yZero\n if (xEnd > outXs[outXs.length - 1]!) {\n outXs.push(xEnd)\n outYs.push(holdY)\n }\n if (xHold > xEnd) {\n outXs.push(xHold)\n outYs.push(holdY)\n }\n outXs.push(xNext)\n outYs.push(yNext)\n } else {\n outXs.push(xNext)\n outYs.push(yNext)\n }\n }\n return { xs: outXs, ys: outYs }\n}\n\n/**\n * Generate a smooth spline path for either equidistant or gap-patched temporal series.\n */\nexport function smoothSeriesPath(input: {\n xs: readonly number[]\n ys: readonly number[]\n yZero: number\n gaps?: readonly boolean[] | undefined\n xEnds?: readonly number[] | undefined\n hold?: 'zero' | 'previous' | undefined\n}): string {\n const { xs, ys, yZero, gaps, xEnds, hold } = input\n if (gaps !== undefined && gaps.some(g => g)) {\n const patched = gapPatchedPoints({ xs, ys, yZero, hold, gaps, xEnds })\n return monotoneSplinePath(patched.xs, patched.ys)\n }\n return monotoneSplinePath(xs, ys)\n}\n\n\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; end: 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 end: bucket.end,\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/**\n * The cumulative view of a series: every point's `tokens` replaced by the\n * running total up to and including that point (a prefix sum), so the chart\n * reads as a monotonic rise. Orthogonal to the mode — all three input\n * shapes are time-ascending, so a plain forward fold is order-correct. The\n * input series is left untouched; each point is copied with only `tokens`\n * rewritten, so the renderer's shape probes (`'time' in point`) keep working.\n * @param series - the series from {@link buildChartPoints}.\n * @returns a new series of the same mode and shape.\n */\nexport function cumulateSeries(series: ChartSeries): ChartSeries {\n let running = 0\n const fold = <T extends { tokens: number }>(points: readonly T[]): T[] =>\n points.map(point => {\n running += point.tokens\n return { ...point, tokens: running }\n })\n if (series.mode === 'equidistant') return { mode: 'equidistant', points: fold(series.points) }\n return { mode: 'temporal', points: fold(series.points) }\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 /** Temporal only: each bucket's exclusive `end` on the same scale as\n * `xs`, clamped to `[leftEdge, rightEdge]`. Gap paths use\n * `xEnds[i] − xs[i]` as the bucket width so the hold ends one bucket\n * before the next cluster. */\n xEnds?: 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\nfunction clampX(value: number, leftEdge: number, rightEdge: number): number {\n return Math.min(Math.max(value, leftEdge), rightEdge)\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-start to last-start span and adds `leftEdge` to the result.\n * A zero span (one point, or every start equal) pins to the centerline.\n * Temporal results include `xEnds` for the gap-path bucket width.\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: wall time into the first-start to last-start span. `end`\n // uses the same domain; an end past the last start clamps to the right edge.\n const temporal = series.points\n const first = temporal[0]!.time\n const lastStart = temporal[temporal.length - 1]!.time\n if (temporal.length === 1 || first === lastStart) {\n const mid = (leftEdge + rightEdge) / 2\n const xs = temporal.map(() => mid)\n return { xs, xEnds: [...xs], innerWidth }\n }\n const xs: number[] = []\n const xEnds: number[] = []\n for (const point of temporal) {\n const x = clampX(leftEdge + scaleToSpan(first, lastStart, point.time, innerWidth), leftEdge, rightEdge)\n const xEnd = clampX(leftEdge + scaleToSpan(first, lastStart, point.end, innerWidth), leftEdge, rightEdge)\n xs.push(x)\n xEnds.push(Math.max(x, xEnd))\n }\n return { xs, xEnds, 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 { useEffect, useId, useRef, useState } from 'react'\nimport type { MouseEvent, 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 { areaPath, gapAfter, smoothSeriesPath } from './trend-chart/path.ts'\nimport { buildChartPoints, cumulateSeries } from './trend-chart/points.ts'\nimport { dotRadius, labelIndices, scaleSeries } from './trend-chart/scale.ts'\nimport { useIsLightMode } from './use-color-scheme.ts'\nimport styles from './TrendChart.module.css'\n\n/** Re-export the chart's pure helpers for the test suite. */\nexport {\n MAX_BUCKETS, areaPath, bucketSeries, bucketWidth, buildChartPoints, cumulateSeries, dotRadius, gapAfter,\n gapPatchedPoints, labelIndices, monotoneSplinePath, niceStep, scaleSeries, scaleToSpan, seriesPath,\n smoothSeriesPath, 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\n/** SVG canvas metrics. The viewBox width tracks the element's measured\n * width (ResizeObserver; WIDTH is the fallback where measuring is\n * unavailable), so the chart fills wide columns at its real scale — a\n * fixed viewBox would stretch a 1200px column 1.5×, blowing up the\n * height and the 11px type with it. The height and the type stay fixed. */\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 * The chart's y-axis reading: each point's own interval total (the\n * default), or the running cumulative total up to that point — a\n * monotonic rise over the same x axis.\n */\nexport type TrendChartMode = 'interval' | 'cumulative'\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. Cumulative mode\n * swaps in its own phrasing so \"total\" never reads ambiguous next to a\n * running sum.\n * @param t - the locale seat.\n * @param point - the pre-shaped point.\n * @param mode - the active y-axis mode.\n * @returns the tooltip / aria-label text.\n */\nfunction tipOf(t: TranslateNS<'token-usage'>, point: PlottedPoint, mode: TrendChartMode): string {\n if (point.time !== undefined) {\n const params = { window: point.full, count: String(point.count ?? 0), tokens: formatTokens(point.tokens) }\n return mode === 'cumulative' ? t('chart.cumulativeBucket', params) : t('chart.bucket', params)\n }\n const params = { day: point.full, tokens: formatTokens(point.tokens) }\n return mode === 'cumulative' ? t('chart.cumulativePoint', params) : t('chart.pointLabel', params)\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), the\n * optional y-axis mode (interval totals, or their running cumulative sum),\n * 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, mode = 'interval', height = HEIGHT, t }: {\n rows: readonly UsageDayRow[]\n hours?: readonly UsageHourRow[]\n requests?: readonly RequestPoint[]\n from?: string\n to?: string\n mode?: TrendChartMode\n height?: number\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const isLight = useIsLightMode()\n const gradientId = useId()\n const [active, setActive] = useState<number | null>(null)\n // The measured canvas width: the viewBox matches it 1:1, so the fixed\n // 11px type and 190px height render at their true size on any surface.\n const svgRef = useRef<SVGSVGElement | null>(null)\n const [width, setWidth] = useState(WIDTH)\n useEffect(() => {\n const el = svgRef.current\n // jsdom has no ResizeObserver; the 800-wide fallback stands there.\n if (el === null || typeof ResizeObserver === 'undefined') return\n const observer = new ResizeObserver(entries => {\n const next = Math.round(entries[0]?.contentRect.width ?? 0)\n // Ignore sub-pixel churn; a 0 (display:none) measurement keeps the last width.\n setWidth(current => (next > 0 && Math.abs(next - current) > 1 ? next : current))\n })\n observer.observe(el)\n return () => observer.disconnect()\n }, [])\n\n const base = buildChartPoints({ rows, hours, requests, from, to })\n if (base === null) {\n return <p className={styles.empty}>{t('chart.empty')}</p>\n }\n // Cumulative mode is a pure y-axis transform on the built points (a\n // prefix sum); the x axis, bucketing, and point count are untouched.\n const series = mode === 'cumulative' ? cumulateSeries(base) : base\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 canvas 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, xEnds, innerWidth } = scaleSeries(series, LEFT, width - RIGHT)\n const radius = dotRadius(points.length)\n const activePoint = active === null ? null : points[active] ?? null\n const y = (tokens: number): number => TOP + innerHeight - (tokens / top) * innerHeight\n const ys = points.map(point => y(point.tokens))\n const yZero = y(0)\n // Generate a smooth monotonic cubic spline across either equidistant\n // days/hours or gap-patched temporal buckets (so request idle stays idle).\n const path = smoothSeriesPath({\n xs,\n ys,\n yZero,\n gaps: series.mode === 'temporal' ? gapAfter(series.points) : undefined,\n xEnds: series.mode === 'temporal' ? (xEnds ?? xs) : undefined,\n hold: mode === 'cumulative' ? 'previous' : 'zero',\n })\n const area = areaPath(path, xs, yZero)\n\n // Cumulative reads one aria regardless of granularity: the per-mode\n // phrasing (\"daily\" / \"hourly\" / \"request-bucketed\") describes interval\n // totals and would mislabel a running sum; the tooltip carries the detail.\n const chartAria = mode === 'cumulative'\n ? t('chart.ariaCumulative')\n : 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 const handleMouseMove = (event: MouseEvent<SVGSVGElement>): void => {\n if (points.length <= 1) return\n const rect = event.currentTarget.getBoundingClientRect()\n if (rect.width <= 0) return\n const svgX = ((event.clientX - rect.left) / rect.width) * width\n let closest = 0\n let minDiff = Math.abs(xs[0]! - svgX)\n for (let i = 1; i < xs.length; i += 1) {\n const diff = Math.abs(xs[i]! - svgX)\n if (diff < minDiff) {\n minDiff = diff\n closest = i\n }\n }\n setActive(closest)\n }\n\n return (\n <svg\n role=\"img\"\n aria-label={chartAria}\n viewBox={`0 0 ${width} ${height}`}\n ref={svgRef}\n className={`${styles.chart} ${isLight ? styles.chartLight : ''}`.trim()}\n data-theme={isLight ? 'light' : 'dark'}\n onMouseMove={handleMouseMove}\n onMouseLeave={() => setActive(null)}\n >\n {isLight ? (\n <defs>\n <linearGradient id={gradientId} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n <stop\n offset=\"0%\"\n stopColor=\"var(--dsw-alias-label-primary)\"\n stopOpacity=\"0.045\"\n />\n <stop\n offset=\"55%\"\n stopColor=\"var(--dsw-alias-label-primary)\"\n stopOpacity=\"0.012\"\n />\n <stop\n offset=\"100%\"\n stopColor=\"var(--dsw-alias-label-primary)\"\n stopOpacity=\"0.0\"\n />\n </linearGradient>\n </defs>\n ) : null}\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 {isLight && area !== '' ? <path d={area} fill={`url(#${gradientId})`} className={styles.area} /> : null}\n <path d={path} className={styles.line} />\n {/* Declutter: render dots only when focused/hovered, or for a lone point */}\n {activePoint !== null && active !== null ? (\n <g pointerEvents=\"none\">\n <circle\n cx={xs[active]}\n cy={y(activePoint.tokens)}\n r={radius + 3.5}\n className={styles.dotHalo}\n />\n <circle\n cx={xs[active]}\n cy={y(activePoint.tokens)}\n r={radius}\n className={styles.dotActive}\n />\n </g>\n ) : points.length === 1 ? (\n <circle\n cx={xs[0]}\n cy={y(points[0]!.tokens)}\n r={radius}\n className={styles.dot}\n />\n ) : null}\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, mode)}\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, mode)\n const charWidth = 6.2\n const labelWidth = label.length * charWidth + 14\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 - 14} width={labelWidth} height={22} rx={6} />\n <text x={left + labelWidth / 2} y={labelY + 1} 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","/**\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 * The dashboards' shared overview board (browser half): the metric cards\n * (the composite first card「请求数 · 运行开销」spanning two grid\n * tracks, then cost / total / hit rate and the four buckets), the pricing\n * status line, and the trend card — titled 趋势, plotting the day's 24\n * hours on a single-day window (fixed; no plot pick) and the daily rows\n * on any wider window. Both the main page and the settings panel render\n * this same board, so the two surfaces read as one.\n *\n * @module token-usage/client/OverviewBoard\n */\n\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AssociationStorageError, AuxSummary, CostState, PricingUnavailableReason, UsageDayRow, UsageHourRow, UsageTotals } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { PricingStatus } from './PricingStatus.tsx'\nimport { StatCard, RequestsStatCard, OverheadPill } from './StatCard.tsx'\nimport { TrendChart } from './TrendChart.tsx'\nimport { HitRateText } from './HitRateText.tsx'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatTokens } from './format.ts'\nimport { totalTokens } from './day.ts'\nimport styles from './OverviewBoard.module.css'\n\n/** Props for the overview board — every field is derived data the section\n * (which owns the fetch and the filter state) passes down; the board never\n * requests. */\nexport interface OverviewBoardProps {\n /** The window's totals (the top-line aggregate). */\n total: UsageTotals\n /** Billed cost (¥) of the window; dashed when the cost layer is out. */\n totalCost: number\n costState: CostState\n pricingUnavailableReason?: PricingUnavailableReason | undefined\n associationStorageError?: AssociationStorageError | undefined\n /** The auxiliary layer driving the composite card's overhead pill\n * (absent / zero renders no pill). */\n aux?: AuxSummary | undefined\n /** The trend's daily points (always present). */\n byDay: readonly UsageDayRow[]\n /** The trend's hourly points (a single-day window only). */\n byHour: readonly UsageHourRow[]\n /** The active window bounds ('' = whole range). A single-day selection\n * (from === to, both non-empty) offers the hourly toggle. */\n from: string\n to: string\n /** Overhead pill click: scroll to / switch to the overhead section. */\n onOverheadActivate: () => void\n /** The settings panel's narrow body: the metric cards fall back to the\n * section's old two-rows-of-four layout (the composite card keeps its\n * pills but reads the short label), while the page's wide column keeps\n * the demo's single nine-track row. */\n compact?: boolean | undefined\n /** Currency display view (symbol + rate). */\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n}\n\n/**\n * Render the overview board: one metric row (the composite lead card\n * spans two tracks), the pricing status, and the trend card.\n */\nexport function OverviewBoard({\n total,\n totalCost,\n costState,\n pricingUnavailableReason,\n associationStorageError,\n aux,\n byDay,\n byHour,\n from,\n to,\n onOverheadActivate,\n compact = false,\n view,\n t,\n}: OverviewBoardProps): ReactNode {\n // A single-day window plots the day's 24 hours (the section's old\n // semantics, fixed — no plot pick); any other window plots the daily rows.\n const singleDay = from !== '' && from === to\n // The page's wide column renders the demo's 20px figures; the panel's\n // narrow grid keeps the compact ones.\n const cardSize = compact ? ('sm' as const) : ('lg' as const)\n return (\n <div className={styles['board']}>\n <div className={compact ? styles['metricGridCompact'] : styles['metricGrid']}>\n {/* display: contents — the composite card itself becomes the grid\n * item (spanning two tracks on the page's wide row), so its tile\n * keeps the family chrome. The pill seats differ: the page's wide\n * lead card parks both pills on the value line; the panel's narrow\n * one would wrap them there and stretch the whole row, so its\n * overhead pill rides the label row instead. */}\n <div className={compact ? styles['leadSpanCompact'] : styles['leadSpan']}>\n <RequestsStatCard\n requests={total.requests}\n failures={total.failures ?? 0}\n failuresByCode={total.failuresByCode}\n {...(compact\n ? {\n labelExtra: (\n <OverheadPill\n requests={aux?.total.requests}\n byKind={aux?.byKind}\n onActivate={onOverheadActivate}\n t={t}\n />\n ),\n // The narrow tile fits the count plus the failure\n // breakdown only as bare text — a capsule wraps to a\n // third line and stretches the whole grid row.\n failureBare: true,\n }\n : {\n overheadRequests: aux?.total.requests,\n overheadByKind: aux?.byKind,\n onOverheadActivate,\n })}\n size={cardSize}\n t={t}\n />\n </div>\n <StatCard size={cardSize} label={t('stat.cost')} value={costsAvailable(costState) ? formatCost(totalCost, view) : '—'} />\n <StatCard size={cardSize} label={t('stat.totalTokens')} value={formatTokens(totalTokens(total))} />\n <StatCard size={cardSize} label={t('stat.hitRate')} value={<HitRateText totals={total} />} />\n <StatCard size={cardSize} label={t('stat.input')} value={formatTokens(total.inputTokens)} />\n <StatCard size={cardSize} label={t('stat.output')} value={formatTokens(total.outputTokens)} />\n <StatCard size={cardSize} label={t('stat.cacheRead')} value={formatTokens(total.cacheReadTokens)} />\n <StatCard size={cardSize} label={t('stat.cacheWrite')} value={formatTokens(total.cacheWriteTokens)} />\n </div>\n <PricingStatus costState={costState} pricingUnavailableReason={pricingUnavailableReason} associationStorageError={associationStorageError} t={t} />\n <div className={styles['trendCard']}>\n <span className={styles['trendTitle']}>{t('trend.title')}</span>\n <TrendChart\n rows={byDay}\n t={t}\n {...from !== '' ? { from } : {}}\n {...to !== '' ? { to } : {}}\n {...(singleDay ? { hours: byHour } : {})}\n />\n </div>\n </div>\n )\n}\n","import type { PricingOverviewModel } from '../wire.ts'\nimport { compileAliasPattern, matchesAliasPattern } from '../model-resolution.ts'\n\nconst patternCache = new WeakMap<PricingOverviewModel, RegExp[]>()\n\nfunction patternsOf(model: PricingOverviewModel): RegExp[] {\n let patterns = patternCache.get(model)\n if (patterns === undefined) {\n patterns = model.aliasPatterns.map(compileAliasPattern)\n patternCache.set(model, patterns)\n }\n return patterns\n}\n\nexport function sortPricingModels(models: readonly PricingOverviewModel[]): PricingOverviewModel[] {\n return [...models].sort((a, b) => {\n const familyA = a.family ?? 'other', familyB = b.family ?? 'other'\n if (familyA !== familyB) return familyA < familyB ? -1 : 1\n return a.modelId < b.modelId ? -1 : a.modelId > b.modelId ? 1 : 0\n })\n}\n\n/** Substrings are a search aid only; server resolution determines identity. */\nexport function matchesPricingSearch(model: PricingOverviewModel, query: string): boolean {\n if (query === '') return true\n const needle = query.toLowerCase()\n return model.modelId.toLowerCase().includes(needle) || (model.family ?? 'other').toLowerCase().includes(needle)\n || patternsOf(model).some(regex => matchesAliasPattern(regex, query))\n}\n","/**\n * The pricing-overview dialog of the settings page: the full cloud-mirror\n * model list served by the filter-free `/token-usage/pricing` route — one\n * flat row per model, sorted by the feed's upstream `family` field (zero\n * client-side mapping) then by modelId, each row's four base rates in the\n * page's display currency. Families drive order and search only — there is\n * no grouping UI, every row is directly visible. Rows the page's filters\n * have used carry a “已用” tag; clicking a row opens that model's full\n * price table as a second native dialog stacked above.\n *\n * Above the table, four token-bucket inputs drive a simulated-cost column:\n * what the buckets would bill at each model's base rates. Each bucket is\n * an amount under a picked K/M/B unit — switching converts the amount, the\n * token count stands still. Preset case buttons (「案例1」, hover-titled\n * with the workload picture) refill the buckets compact in one click; the\n * first case is prefilled on open, and the pressed highlight tracks exact\n * token matches, so a manual edit un-presses. The column sorts by a\n * three-state header cycle (family order → cost desc → cost asc → family);\n * the header's glyph never disappears: a dim ⇅ in the default family\n * order, then ▾ desc and ▴ asc.\n *\n * Aliases never render — they stay a search dimension only (a hit on an\n * alias surfaces the model, whose id then reads as the result).\n *\n * @module token-usage/client/PricingOverviewDialog\n */\n\nimport { Fragment, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ContextTier, DailySlot, ModelPricing, ModelRates, PricingOverviewModel, PricingOverviewPayload } from '../wire.ts'\nimport { PRICING_PATH } from '../wire.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { PricingAssociationDialog, PricingAssociationManagerButton } from './PricingAssociations.tsx'\nimport { PricingStatus, costsAvailable } from './PricingStatus.tsx'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatRate, formatTokens } from './format.ts'\nimport { billedRates, PricingDialog, windowText } from './PricingDialog.tsx'\nimport shared from './PricingDialog.module.css'\nimport styles from './PricingOverviewDialog.module.css'\n\nimport { matchesPricingSearch, sortPricingModels } from './pricing-search.ts'\nexport { matchesPricingSearch, sortPricingModels } from './pricing-search.ts'\n\n/** One preset usage case of the simulated-cost column: raw token buckets.\n * A case button's hover title derives from the data (input-side total,\n * cache-hit share, output), so adding a case is one array entry and\n * nothing else. */\ninterface SimScenario {\n inputTokens: number\n cacheReadTokens: number\n outputTokens: number\n cacheWriteTokens: number\n}\n\n/** The preset cases the buttons fill the inputs with (maintainer-curated\n * classic workloads). The first prefills the inputs on open. */\nconst SIM_SCENARIOS: readonly SimScenario[] = [\n // 「输入 100M(缓存 98%)输出 457K」: an input side of 100M tokens, 98%\n // of it served from cache, 457K generated.\n { inputTokens: 2_000_000, cacheReadTokens: 98_000_000, outputTokens: 457_000, cacheWriteTokens: 0 },\n // 「输入 100M(缓存 95%)输出 600K」: the same 100M input side at a 95%\n // cache hit, 600K generated.\n { inputTokens: 5_000_000, cacheReadTokens: 95_000_000, outputTokens: 600_000, cacheWriteTokens: 0 },\n // 「输入 100M(缓存 0%)输出 100M」: translation at corpus scale — fresh\n // text both ways, no cache in play, the output roughly as long as the\n // input.\n { inputTokens: 100_000_000, cacheReadTokens: 0, outputTokens: 100_000_000, cacheWriteTokens: 0 },\n]\n\n/** The four bucket fields of a case, in table order. */\ntype BucketKey = 'inputTokens' | 'cacheReadTokens' | 'outputTokens' | 'cacheWriteTokens'\n\n/** The units a bucket's amount can carry. */\nconst BUCKET_UNITS = ['K', 'M', 'B'] as const\ntype BucketUnit = typeof BUCKET_UNITS[number]\n\nconst UNIT_MULT: Record<BucketUnit, number> = { K: 1e3, M: 1e6, B: 1e9 }\n\n/** One bucket as typed: the amount string (free-form while editing) under\n * the picked unit — the whole-token count derives from the pair. */\ninterface Bucket {\n amount: string\n unit: BucketUnit\n}\n\n/** The whole-token count a bucket stands for: amount × unit, float fuzz\n * rounded off; empty, negative, or non-numeric amounts read as zero. */\nfunction tokensOf(bucket: Bucket): number {\n const parsed = Number(bucket.amount)\n if (!Number.isFinite(parsed) || parsed <= 0) return 0\n return Math.round(parsed * UNIT_MULT[bucket.unit])\n}\n\n/** The amount string for the same tokens under a new unit — converting so\n * the token count stands still (98M reads 98000K). Trims float fuzz to\n * six decimals so 0.457M ↔ 457K round-trips cleanly. */\nfunction convertBucketAmount(bucket: Bucket, unit: BucketUnit): string {\n const parsed = Number(bucket.amount)\n if (!Number.isFinite(parsed)) return ''\n const converted = parsed * UNIT_MULT[bucket.unit] / UNIT_MULT[unit]\n return String(Math.round(converted * 1e6) / 1e6)\n}\n\n/** The compact refill shape of one token count: a short amount under the\n * fitting unit (98M, 457K), K as the floor for the sub-1K tail. */\nfunction compactBucket(tokens: number): Bucket {\n if (tokens >= UNIT_MULT.B) return { amount: String(tokens / UNIT_MULT.B), unit: 'B' }\n if (tokens >= UNIT_MULT.M) return { amount: String(tokens / UNIT_MULT.M), unit: 'M' }\n return { amount: String(tokens / UNIT_MULT.K), unit: 'K' }\n}\n\n/** The refill shape of a whole case: every bucket compact. */\nfunction bucketsOfCase(scenario: SimScenario): Record<BucketKey, Bucket> {\n return {\n inputTokens: compactBucket(scenario.inputTokens),\n cacheReadTokens: compactBucket(scenario.cacheReadTokens),\n outputTokens: compactBucket(scenario.outputTokens),\n cacheWriteTokens: compactBucket(scenario.cacheWriteTokens),\n }\n}\n\n/**\n * The simulated cost (¥) of one scenario under a model's base rates —\n * the same arithmetic as the host half's `costOf` (a missing cache rate\n * bills at the input rate), re-implemented here because pricing.ts lives\n * on the node side of the bundle boundary.\n */\nfunction simCostOf(scenario: SimScenario, rates: ModelPricing): number {\n const M = 1_000_000\n const cacheRead = rates.cacheReadPerMillion ?? rates.inputPerMillion\n const cacheWrite = rates.cacheWritePerMillion ?? rates.inputPerMillion\n return (scenario.inputTokens * rates.inputPerMillion\n + scenario.outputTokens * rates.outputPerMillion\n + scenario.cacheReadTokens * cacheRead\n + scenario.cacheWriteTokens * cacheWrite) / M\n}\n\n/**\n * The effective world of one model at `nowMs`: the time rule whose date\n * window contains the current date (rules are mutually exclusive — at most\n * one matches; bounds are Unix seconds, `startTime` 0 reads as \"since\n * forever\"), else the model root. The world's default rates are the main\n * row (the root's prices are NOT shown while a rule owns the present);\n * its slots and tiers are the expandable special rows — never the root's.\n */\nexport interface EffectiveNode {\n /** The world's default rates: the main row's four prices and cost. */\n baseRates: ModelPricing\n /** Slot rows of this world: shown whenever defined, regardless of the\n * current minute (peaks recur daily — hiding them at off-peak hours\n * would hide the information). */\n slots: DailySlot[]\n /** The one tier this world's input side clears (largest threshold at or\n * below the context), if any. */\n tier: ContextTier | undefined\n}\n\n/** The largest tier whose threshold the context clears. */\nfunction hitTier(tiers: ContextTier[], ctxTokens: number): ContextTier | undefined {\n let hit: ContextTier | undefined\n for (const tier of tiers) {\n if (ctxTokens >= tier.threshold && (hit === undefined || tier.threshold > hit.threshold)) hit = tier\n }\n return hit\n}\n\nexport function hitNodeOf(rules: ModelRates, ctxTokens: number, nowMs: number): EffectiveNode {\n const nowSec = Math.floor(nowMs / 1000)\n const rule = rules.timeRules.find(candidate => candidate.startTime <= nowSec && nowSec <= candidate.endTime)\n if (rule !== undefined) {\n return { baseRates: rule.rates, slots: rule.dailySlots ?? [], tier: hitTier(rule.contextTiers ?? [], ctxTokens) }\n }\n return { baseRates: rules.base, slots: rules.dailySlots, tier: hitTier(rules.contextTiers, ctxTokens) }\n}\n\n/** The workload picture of one case — the input line (input-side total\n * with its cache-hit share) and the output line — joined into the case\n * button's hover title. */\nfunction scenarioLabel(scenario: SimScenario, t: TranslateNS<'token-usage'>): { inputLine: string; outputLine: string } {\n const total = scenario.inputTokens + scenario.cacheReadTokens\n const pct = Math.round((scenario.cacheReadTokens / total) * 100)\n return {\n inputLine: `${t('pricing.simInput', { tokens: formatTokens(total) })}${t('pricing.simCache', { pct: String(pct) })}`,\n outputLine: t('pricing.simOutput', { tokens: formatTokens(scenario.outputTokens) }),\n }\n}\n\n/** One bucket's K/M/B unit segment. Switching converts the amount so the\n * token count stands still. */\nfunction UnitPicker({ t, bucket, unit, onPick }: {\n t: TranslateNS<'token-usage'>\n bucket: string\n unit: BucketUnit\n onPick: (unit: BucketUnit) => void\n}): ReactNode {\n return (\n <div className={styles['unitGroup']}>\n {BUCKET_UNITS.map(candidate => (\n <button\n key={candidate}\n type=\"button\"\n className={styles['unit']}\n aria-pressed={candidate === unit}\n aria-label={t('pricing.simUnitOf', { bucket, unit: candidate })}\n onClick={() => { if (candidate !== unit) onPick(candidate) }}\n >\n {candidate}\n </button>\n ))}\n </div>\n )\n}\n\n/**\n * Fetch the pricing overview from the local route — deliberately without\n * any query parameters: the overview is not a filtered view, so changing\n * the page's filters never changes what this dialog shows. An empty model\n * list (a first startup whose sync has not landed a mirror yet) reads as\n * the same failure the fetch error does: nothing to show, retry offered.\n */\nfunction fetchPricingOverview(signal: AbortSignal): Promise<PricingOverviewPayload> {\n return fetch(PRICING_PATH, { signal })\n .then(response => {\n if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)\n return response.json() as Promise<PricingOverviewPayload>\n })\n .then(value => {\n if (typeof value !== 'object' || value === null || !Array.isArray(value.models)) {\n throw new Error('unexpected pricing response')\n }\n if (value.costState === 'pricing-unavailable') return value\n if (value.models.length === 0) throw new Error('pricing mirror is empty')\n return value\n })\n}\n\n/**\n * The pricing-overview dialog. `usedModels` is the open-time snapshot of\n * the page's filtered model selection (the modal's backdrop covers the\n * filter row, so it cannot change while the dialog is open); `view` is the\n * page's display currency. Mounts only while open; every close path\n * funnels through the dialog's `close` event, which unmounts it.\n */\nexport function PricingOverviewDialog({ usedModels, view, onClose, t }: {\n usedModels: ReadonlySet<string>\n view: CurrencyView\n onClose: () => void\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n // Whether the press that precedes a dialog-targeting click started on\n // the backdrop itself. A text-selection drag that starts inside the\n // content and releases outside lands its click on the dialog element\n // (the click fires on the press/release targets' common ancestor, and\n // outside a top-layer dialog every point resolves to the dialog) — the\n // same target a real backdrop click produces. Only a press that began\n // on the backdrop may close.\n const backdropPress = useRef(false)\n useEffect(() => {\n const dialog = dialogRef.current\n if (dialog !== null && !dialog.open) dialog.showModal()\n }, [])\n // One fetch per dialog session: no filter deps, and the hook's own\n // retry() is the failure state's retry button (a fresh local fetch).\n const [state, retry] = useAsyncResource<PricingOverviewPayload>(fetchPricingOverview, [], { retryToken: 0 })\n usePricingAssociationRefresh(retry)\n const [search, setSearch] = useState('')\n // The token buckets driving the simulated-cost column, as typed: an\n // amount under a picked K/M/B unit each. The first preset case prefills\n // them on open; case buttons refill them compact, any edit just retypes.\n const [buckets, setBuckets] = useState<Record<BucketKey, Bucket>>(() => bucketsOfCase(SIM_SCENARIOS[0]!))\n // The simulated-cost column's sort: default family order, then a\n // three-state cycle (desc → asc → back to family) on header clicks.\n const [sortMode, setSortMode] = useState<'family' | 'cost-desc' | 'cost-asc'>('family')\n // The drilled-in model whose full price table is open above the overview.\n const [detail, setDetail] = useState<PricingOverviewModel | null>(null)\n const [associationsOpen, setAssociationsOpen] = useState(false)\n // The wall clock the effective-world hits are judged at: taken once on\n // mount so a dialog left open never reshuffles itself at a rule boundary.\n const [nowMs] = useState(() => Date.now())\n // The one model whose special-rate rows are expanded under its main row.\n const [expandedId, setExpandedId] = useState<string | null>(null)\n\n const sorted = useMemo(\n () => sortPricingModels(state.status === 'ready' ? state.value.models : []),\n [state],\n )\n // The whole-token counts the buckets stand for — what the cost column\n // bills and the case match compares.\n const scenario = useMemo<SimScenario>(() => ({\n inputTokens: tokensOf(buckets.inputTokens),\n cacheReadTokens: tokensOf(buckets.cacheReadTokens),\n outputTokens: tokensOf(buckets.outputTokens),\n cacheWriteTokens: tokensOf(buckets.cacheWriteTokens),\n }), [buckets])\n // The context a tier is hit against: the whole input side (fresh + cache\n // reads) reads as the request's context length.\n const ctxTokens = scenario.inputTokens + scenario.cacheReadTokens\n // A case button reads pressed while the inputs exactly match it — the\n // highlight follows the data, not the last click.\n const pressedCase = SIM_SCENARIOS.find(candidate => candidate.inputTokens === scenario.inputTokens\n && candidate.cacheReadTokens === scenario.cacheReadTokens\n && candidate.outputTokens === scenario.outputTokens\n && candidate.cacheWriteTokens === scenario.cacheWriteTokens)\n // Search filters rows and keeps the family sort order; the cost sort\n // (a stable sort) reorders afterwards, so equal-cost rows keep the\n // family order and the search never fights the sort. Cost = the main\n // row's (the effective world's default rates).\n const query = search.trim()\n const rows = useMemo(() => {\n const withCost = sorted.map(model => {\n const node = hitNodeOf(model.rules, ctxTokens, nowMs)\n return {\n model,\n node,\n cost: simCostOf(scenario, node.baseRates),\n specials: [\n ...(node.tier !== undefined\n ? [{ kind: 'tier' as const, tier: node.tier, slot: undefined as DailySlot | undefined, cost: simCostOf(scenario, node.tier.rates) }]\n : []),\n ...node.slots.map(slot => ({ kind: 'slot' as const, tier: undefined as ContextTier | undefined, slot, cost: simCostOf(scenario, slot.rates) })),\n ],\n }\n })\n .filter(({ model }) => query === '' || matchesPricingSearch(model, query))\n if (sortMode === 'family') return withCost\n return [...withCost].sort((a, b) => (sortMode === 'cost-desc' ? b.cost - a.cost : a.cost - b.cost))\n }, [sorted, scenario, query, sortMode, ctxTokens, nowMs])\n\n return (\n <dialog\n ref={dialogRef}\n className={`${shared['dialog']} ${styles['overview']}`}\n aria-label={t('pricing.table')}\n // The stacked detail dialog is a DOM child of this one, and React\n // simulates the close event's propagation up the tree — so a close\n // that targeted the detail reaches this handler too. Only a close of\n // this dialog itself ends the overview.\n onClose={event => { if (event.target === dialogRef.current) 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 // but only when the press started there too (see backdropPress): a\n // selection drag released outside produces the same click target.\n // With the detail dialog stacked above, its own backdrop click\n // never reaches this handler.\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => {\n if (event.target === dialogRef.current && backdropPress.current) dialogRef.current?.close()\n }}\n >\n <div className={shared['dialogHead']}>\n <div className={styles.titleActions}>\n <span className={shared['dialogTitle']}>{t('pricing.table')}</span>\n <PricingAssociationManagerButton t={t} onOpen={() => setAssociationsOpen(true)} />\n </div>\n <button\n type=\"button\"\n className={shared['dialogClose']}\n aria-label={t('pricing.close')}\n onClick={() => dialogRef.current?.close()}\n >\n ✕\n </button>\n </div>\n {associationsOpen && <PricingAssociationDialog initialSource={null} view={view} t={t} onClose={() => setAssociationsOpen(false)} />}\n {state.status === 'loading'\n ? <p className={styles['note']}>{t('loading')}</p>\n : null}\n {state.status === 'error'\n ? (\n <div className={styles['failRow']}>\n <p className={styles['note']}>{t('pricing.overviewFailed')}</p>\n <button type=\"button\" className={styles['retryButton']} onClick={retry}>{t('retry')}</button>\n </div>\n )\n : null}\n {state.status === 'ready' && !costsAvailable(state.value.costState)\n ? <div className={styles['failRow']}>\n <PricingStatus costState={state.value.costState} {...state.value.pricingUnavailableReason !== undefined ? { pricingUnavailableReason: state.value.pricingUnavailableReason } : {}} t={t} />\n <button type=\"button\" className={styles['retryButton']} onClick={retry}>{t('retry')}</button>\n </div> : null}\n {state.status === 'ready' && costsAvailable(state.value.costState)\n ? (\n <>\n <input\n type=\"search\"\n className={styles['search']}\n placeholder={t('pricing.search')}\n aria-label={t('pricing.search')}\n value={search}\n onChange={event => setSearch(event.target.value)}\n />\n <div className={styles['buckets']}>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketInput')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketInput')}\n value={buckets.inputTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n inputTokens: { ...previous.inputTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketInput')}\n unit={buckets.inputTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n inputTokens: { amount: convertBucketAmount(previous.inputTokens, unit), unit },\n }))}\n />\n </div>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketCacheRead')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketCacheRead')}\n value={buckets.cacheReadTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n cacheReadTokens: { ...previous.cacheReadTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketCacheRead')}\n unit={buckets.cacheReadTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n cacheReadTokens: { amount: convertBucketAmount(previous.cacheReadTokens, unit), unit },\n }))}\n />\n </div>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketOutput')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketOutput')}\n value={buckets.outputTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n outputTokens: { ...previous.outputTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketOutput')}\n unit={buckets.outputTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n outputTokens: { amount: convertBucketAmount(previous.outputTokens, unit), unit },\n }))}\n />\n </div>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketCacheWrite')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketCacheWrite')}\n value={buckets.cacheWriteTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n cacheWriteTokens: { ...previous.cacheWriteTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketCacheWrite')}\n unit={buckets.cacheWriteTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n cacheWriteTokens: { amount: convertBucketAmount(previous.cacheWriteTokens, unit), unit },\n }))}\n />\n </div>\n </div>\n <div className={styles['scenarios']}>\n {SIM_SCENARIOS.map((candidate, index) => {\n const label = scenarioLabel(candidate, t)\n return (\n <button\n key={index}\n type=\"button\"\n className={styles['scenario']}\n aria-pressed={pressedCase === candidate}\n title={`${label.inputLine} ${label.outputLine}`}\n onClick={() => { setBuckets(bucketsOfCase(candidate)) }}\n >\n {t('pricing.simCase', { index: String(index + 1) })}\n </button>\n )\n })}\n </div>\n <div className={styles['tableWrap']}>\n <table className={styles['table']} aria-label={t('pricing.table')}>\n <thead>\n <tr>\n <th className={styles['modelHead']}>{t('filter.model')}</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 <th>\n <button\n type=\"button\"\n className={styles['sortHead']}\n onClick={() => {\n setSortMode(previous =>\n previous === 'family' ? 'cost-desc' : previous === 'cost-desc' ? 'cost-asc' : 'family')\n }}\n >\n {t('pricing.simCost')}\n {/* The glyph always shows, so the default family\n * order still reads as \"this column sorts\" — dimmed\n * there, full-strength once a direction is active. */}\n <span\n className={sortMode === 'family' ? `${styles['sortArrow']} ${styles['sortArrowIdle']}` : styles['sortArrow']}\n aria-hidden\n >\n {sortMode === 'family' ? ' ⇅' : sortMode === 'cost-desc' ? ' ▾' : ' ▴'}\n </span>\n </button>\n </th>\n </tr>\n </thead>\n <tbody>\n {rows.map(({ model, node, cost, specials }) => {\n const billed = billedRates(node.baseRates, view)\n const expanded = expandedId === model.modelId\n return (\n <Fragment key={model.modelId}>\n <tr\n className={styles['modelRow']}\n role=\"button\"\n tabIndex={0}\n aria-label={t('pricing.view', { model: model.modelId })}\n onClick={() => setDetail(model)}\n onKeyDown={event => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault()\n setDetail(model)\n }\n }}\n >\n <td className={styles['modelCell']}>\n <span className={styles['cellInner']}>\n {specials.length > 0\n ? (\n <button\n type=\"button\"\n className={styles['expandArrow']}\n aria-expanded={expanded}\n aria-label={t('pricing.expand')}\n onClick={event => {\n event.stopPropagation()\n setExpandedId(previous => (previous === model.modelId ? null : model.modelId))\n }}\n >\n {expanded ? '▾' : '▸'}\n </button>\n )\n : <span className={styles['arrowGap']} aria-hidden />}\n <span className={styles['modelName']}>{model.modelId}</span>\n {usedModels.has(model.modelId)\n ? <span className={styles['usedTag']}>{t('pricing.used')}</span>\n : null}\n </span>\n </td>\n <td>{billed.input}</td>\n <td>{billed.output}</td>\n <td>{billed.cacheRead}</td>\n <td>{billed.cacheWrite}</td>\n <td>{formatCost(cost, view)}</td>\n </tr>\n {expanded\n ? (\n <tr className={styles['expansionRow']}>\n <td colSpan={6}>\n <div className={styles['specialRows']}>\n {specials.map((special, index) => {\n const specialBilled = billedRates(special.tier?.rates ?? special.slot!.rates, view)\n const label = special.kind === 'tier'\n ? t('pricing.tier', { threshold: formatTokens(special.tier!.threshold) })\n : `${special.slot!.label ?? t('pricing.peak')} ${special.slot!.windows.map(windowText).join(t('pricing.windowSep'))}`\n return (\n <div key={index} className={styles['specialRow']}>\n <span className={styles['specialLabel']}>{label}</span>\n <span className={styles['specialRate']}>{specialBilled.input}</span>\n <span className={styles['specialRate']}>{specialBilled.output}</span>\n <span className={styles['specialRate']}>{specialBilled.cacheRead}</span>\n <span className={styles['specialRate']}>{specialBilled.cacheWrite}</span>\n <span className={styles['specialRate']}>{formatCost(special.cost, view)}</span>\n </div>\n )\n })}\n </div>\n </td>\n </tr>\n )\n : null}\n </Fragment>\n )\n })}\n </tbody>\n </table>\n {view.symbol === '$'\n ? <p className={shared['rateNote']}>{t('pricing.exchangeRateNote', { rate: formatRate(view.rate) })}</p>\n : null}\n </div>\n </>\n )\n : null}\n {detail !== null\n ? (\n <PricingDialog\n model={detail.modelId}\n rules={detail.rules}\n view={view}\n onClose={() => setDetail(null)}\n t={t}\n />\n )\n : null}\n </dialog>\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, and the per-model detail\n * table with the hit rate last — all following the active filters. A\n * priced model name is the row's price affordance (one click opens\n * PricingDialog.tsx); unpriced rows keep the in-cell tag. The filter\n * row's tail link opens the filter-free pricing-overview dialog\n * (PricingOverviewDialog.tsx). There is no refresh\n * button: entering the page or changing a filter refetches (the route\n * answers no-store); only 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 { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { UsageSummary } from '../wire.ts'\nimport { STATS_PATH } from '../wire.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport { DateRangePicker } from './DateRangePicker.tsx'\nimport { shiftedDayKey } from './day.ts'\nimport { currencyViewOf } from './format.ts'\nimport { MenuSelect } from './MenuSelect.tsx'\nimport { DashboardCards } from './DashboardCards.tsx'\nimport { OverheadRows } from './OverheadRows.tsx'\nimport { OverviewBoard } from './OverviewBoard.tsx'\nimport { PricingDialog } from './PricingDialog.tsx'\nimport { PricingOverviewDialog } from './PricingOverviewDialog.tsx'\nimport { PricingAssociationProvider } from './PricingAssociations.tsx'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { UsageRows, RowSortControl, PerfToggle } from './UsageRows.tsx'\nimport type { RowSort } from './UsageRows.tsx'\nimport { projectRowsOf } from './project-rows.ts'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport styles from './TokenUsageSection.module.css'\n\n/** The detail tabs' fixed sort options: projects, models and providers pick\n * between token size and billed cost; sessions add last activity. */\nconst PROJECT_SORT: readonly RowSort[] = ['tokens', 'cost']\nconst MODEL_SORT: readonly RowSort[] = ['tokens', 'cost']\nconst PROVIDER_SORT: readonly RowSort[] = ['tokens', 'cost']\nconst SESSION_SORT: readonly RowSort[] = ['tokens', 'cost', 'recent']\n\n/** The detail switch's tab labels, one per mode. */\nconst DETAIL_MODES = ['project', 'model', 'session', 'provider', 'aux'] as const\ntype DetailMode = (typeof DETAIL_MODES)[number]\n\n/** One detail mode's label key. */\nfunction detailLabelOf(mode: DetailMode): 'byProject.title' | 'byModel.title' | 'bySession.title' | 'byProvider.title' | 'aux.tab' {\n return mode === 'project' ? 'byProject.title'\n : mode === 'model' ? 'byModel.title'\n : mode === 'session' ? 'bySession.title'\n : mode === 'provider' ? 'byProvider.title' : 'aux.tab'\n}\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/** 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/** Quick-range menu entries (labels are locale-free day counts). */\nconst QUICK_OPTIONS = [\n { value: '1', label: '1d' },\n { value: '7', label: '7d' },\n { value: '30', label: '30d' },\n] as const\n\n/** The filter bar: quick range menu, day-range picker popover, model\n * menu — one row, one popover language. The row's tail link is an action,\n * not a selector: it opens the filter-free pricing overview. */\nfunction FilterBar({ filters, models, onChange, onPricingTable, t }: {\n filters: Filters\n models: readonly string[]\n onChange: (next: Filters) => void\n onPricingTable: () => void\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n // 'all' when the range is unconstrained, 'custom' when it no longer\n // holds one of the quick ranges.\n const quickValue = QUICK_OPTIONS.find(option => isQuickActive(Number(option.value), filters))?.value\n ?? (filters.from === '' && filters.to === '' ? 'all' : 'custom')\n return (\n <div className={styles['filters']}>\n <MenuSelect\n ariaLabel={t('filter.quickRange')}\n value={quickValue}\n options={[\n ...QUICK_OPTIONS,\n { value: 'all', label: t('filter.allDates') },\n { value: 'custom', label: t('filter.custom') },\n ]}\n onChange={value => {\n // 'all' releases the range back to unconstrained; the 'custom'\n // entry is informational: it mirrors the day range and never\n // rewrites it.\n if (value === 'all') onChange({ ...filters, from: '', to: '' })\n const days = Number(value)\n if (days > 0) onChange({ ...filters, ...quickRange(days) })\n }}\n />\n <DateRangePicker\n from={filters.from}\n to={filters.to}\n onChange={next => onChange({ ...filters, ...next })}\n t={t}\n />\n <MenuSelect\n ariaLabel={t('filter.model')}\n grow\n value={filters.model}\n options={[{ value: '', label: t('filter.allModels') }, ...models.map(model => ({ value: model, label: model }))]}\n onChange={model => onChange({ ...filters, model })}\n />\n {/* The tail action of the tool row: opens the pricing overview, a\n * view independent of the three selectors (it never takes filters).\n * A link-styled label, not a bordered button — bordered reads as a\n * fourth selector of the same family. */}\n <button type=\"button\" data-pricing-overview-trigger className={styles['pricingLink']} onClick={onPricingTable}>\n {t('pricing.table')}\n </button>\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 * The session jump seats (`sessionListed` / `openSession`) come from the\n * registration's `inject:` — the session table's Ctrl+click affordance\n * reads the controller's list and opens the target session.\n * @param props - the framework-injected translate seat, the optional\n * injected jump seats, and the optional `close` the hosting surface hands\n * in (the settings panel closes itself on a jump; the main page returns\n * to the conversation). Absent `close` just skips the dismiss step.\n * @returns the section, one of loading / error / ready.\n */\nexport function TokenUsageSection({ t, close, sessionListed, openSession, variant }: {\n t: TranslateNS<'token-usage'>\n /** Dismiss the hosting surface after a successful session jump. */\n close?: (() => void) | undefined\n sessionListed?: ((id: string) => boolean) | undefined\n openSession?: ((id: string) => boolean | { ok: boolean; reason?: string }) | undefined\n /** Hosting surface: the settings panel (default) or the main-column page,\n * which only restyles the title step and lifts the table's height cap. */\n variant?: ('panel' | 'page') | undefined\n}): ReactNode {\n const rootClass = variant === 'page' ? `${styles['section']} ${styles['pageVariant']}` : styles['section']\n const rootRef = useRef<HTMLDivElement>(null)\n useColorSchemeMirror(rootRef)\n const [toastText, setToastText] = useState<string | null>(null)\n const [toastSeq, setToastSeq] = useState(0)\n const showToast = useCallback((text: string) => {\n setToastSeq(previous => previous + 1)\n setToastText(text)\n }, [])\n const dismissToast = useCallback(() => {\n setToastText(null)\n }, [])\n\n const handleOpenSession = useCallback((id: string) => {\n if (!openSession) return\n const result = openSession(id)\n if (result && typeof result === 'object' && 'ok' in result) {\n if (result.ok) {\n close?.()\n } else if (result.reason === 'workspaceDeleted') {\n showToast(t('session.workspaceDeleted'))\n }\n return\n }\n if (result === true) {\n close?.()\n }\n }, [openSession, close, showToast, t])\n\n // Entering the page starts on today's window (the 1d quick range).\n const [filters, setFilters] = useState<Filters>(() => ({ model: '', ...quickRange(1) }))\n // The detail-table block's mode: by project (default — the dashboards'\n // first tab), by model, by session, by provider, or the runtime-overhead\n // breakdown of the auxiliary (bypass) model requests. Pure presentation\n // state — every row set arrives on the SAME summary response, so\n // switching never refetches (session-local, not persisted, the usage\n // tab's scope-switch tradeoff).\n const [detailMode, setDetailMode] = useState<DetailMode>('project')\n // The lists' sorts, each its own state (the page's cards and the panel's\n // tabs render the same lists, so one state drives both): projects,\n // models and providers pick token size vs billed cost, sessions add last\n // activity. A pick matching the native order passes it straight through.\n const [projectSort, setProjectSort] = useState<RowSort>('tokens')\n const [modelSort, setModelSort] = useState<RowSort>('tokens')\n // The models' performance view — a content switch next to the sort\n // control (shared by the page card and the panel tab, like the sorts).\n const [modelPerfView, setModelPerfView] = useState(false)\n const [providerSort, setProviderSort] = useState<RowSort>('tokens')\n const [sessionSort, setSessionSort] = useState<RowSort>('cost')\n // Ctrl+click on a model row toggles the model filter to just that model\n // (a single pick — clicking the filtered model again clears it).\n const handleToggleModel = useCallback((model: string) => {\n setFilters(previous => ({ ...previous, model: previous.model === model ? '' : model }))\n }, [])\n // The overhead pill's destination: the page scrolls to (and flashes) the\n // dashboard's overhead card; the panel switches to the overhead tab.\n const overheadCardRef = useRef<HTMLDivElement | null>(null)\n const [overheadFlash, setOverheadFlash] = useState(false)\n const flashTimer = useRef<number | undefined>(undefined)\n useEffect(() => () => window.clearTimeout(flashTimer.current), [])\n const activateOverhead = useCallback(() => {\n if (variant === 'page') {\n overheadCardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })\n setOverheadFlash(true)\n window.clearTimeout(flashTimer.current)\n flashTimer.current = window.setTimeout(() => setOverheadFlash(false), 1200)\n } else {\n setDetailMode('aux')\n }\n }, [variant])\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 // The pricing-overview dialog (opened by the filter row's tail link).\n // `usedSnapshot` is taken at open time: the modal's backdrop covers the\n // filter row, so the filters cannot change while it is open and the\n // snapshot stays stable for the whole dialog session. The link renders\n // only in the ready branch, so the summary is always at hand here.\n const [pricingTableOpen, setPricingTableOpen] = useState(false)\n const [usedSnapshot, setUsedSnapshot] = useState<ReadonlySet<string>>(() => new Set())\n const [retryToken, setRetryToken] = useState(0)\n const lastSummary = useRef<UsageSummary | null>(null)\n const retry = useCallback(() => { setRetryToken(previous => previous + 1) }, [])\n usePricingAssociationRefresh(retry)\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 === 'ready') lastSummary.current = state.value\n const retainedView = lastSummary.current !== null ? currencyViewOf(lastSummary.current) : { symbol: '¥' as const, rate: 1 }\n const pricingOverview = pricingTableOpen ? <PricingOverviewDialog usedModels={usedSnapshot} view={retainedView}\n onClose={() => setPricingTableOpen(false)} t={t} /> : null\n if (state.status === 'loading') {\n return (\n <div ref={rootRef} className={rootClass}>\n <PricingAssociationProvider resolutions={lastSummary.current?.modelResolutions} feedVersion={lastSummary.current?.feedVersion} view={retainedView} t={t}>\n {pricingOverview}\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <p className={styles['muted']}>{t('loading')}</p>\n </PricingAssociationProvider>\n </div>\n )\n }\n if (state.status === 'error') {\n return (\n <div ref={rootRef} className={rootClass}>\n <PricingAssociationProvider resolutions={lastSummary.current?.modelResolutions} feedVersion={lastSummary.current?.feedVersion} view={retainedView} t={t}>\n {pricingOverview}\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 </PricingAssociationProvider>\n </div>\n )\n }\n\n const { total } = state.value\n const view = currencyViewOf(state.value)\n // New hosts aggregate before the session top-N cut. Older payloads retain\n // the former client-side fold as a compatibility fallback only.\n const projectRows = state.value.projectRows ?? projectRowsOf(state.value.sessionRows ?? [])\n // The auxiliary (bypass) request count: the runtime-overhead tab is part of\n // the detail switch whenever any dimension has rows, and the tab content\n // renders its own empty hint when this stays 0 (or an older host payload\n // carries no auxiliary layer at all).\n const auxRequests = state.value.aux?.total.requests ?? 0\n return (\n <div ref={rootRef} className={rootClass}>\n <PricingAssociationProvider resolutions={state.value.modelResolutions} feedVersion={state.value.feedVersion} view={view} t={t}>\n {pricingOverview}\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <p className={styles['muted']}>{t('dataDir', { path: state.value.dataDir })}</p>\n <FilterBar\n filters={filters}\n models={models}\n onChange={setFilters}\n onPricingTable={() => {\n setUsedSnapshot(new Set(state.value.byModel.map(row => row.model)))\n setPricingTableOpen(true)\n }}\n t={t}\n />\n {total.requests === 0 && (total.failures ?? 0) === 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 <OverviewBoard\n total={total}\n totalCost={state.value.totalCost}\n costState={state.value.costState}\n pricingUnavailableReason={state.value.pricingUnavailableReason}\n associationStorageError={state.value.associationStorageError}\n aux={state.value.aux}\n byDay={state.value.byDay}\n byHour={state.value.byHour}\n from={filters.from}\n to={filters.to}\n onOverheadActivate={activateOverhead}\n {...variant === 'page' ? {} : { compact: true }}\n view={view}\n t={t}\n />\n {variant === 'page'\n ? (\n // The main page's dashboard: the four equal-height cards,\n // no dimension switch — everything is on show at once.\n <DashboardCards\n projectRows={projectRows}\n modelRows={state.value.byModel}\n sessionRows={state.value.sessionRows ?? []}\n projectSort={projectSort}\n onProjectSortChange={setProjectSort}\n modelSort={modelSort}\n onModelSortChange={setModelSort}\n modelPerfView={modelPerfView}\n onModelPerfToggle={setModelPerfView}\n providerRows={state.value.byProvider ?? []}\n providerNames={state.value.providerNames}\n providerSort={providerSort}\n onProviderSortChange={setProviderSort}\n sessionSort={sessionSort}\n onSessionSortChange={setSessionSort}\n aux={state.value.aux}\n pricing={state.value.pricing}\n costState={state.value.costState}\n view={view}\n t={t}\n {...sessionListed !== undefined && openSession !== undefined\n ? { sessionListed, onSessionOpen: handleOpenSession }\n : {}}\n onToggleModel={handleToggleModel}\n onModelName={setDetailModel}\n overheadCardRef={overheadCardRef}\n overheadFlash={overheadFlash}\n />\n )\n : state.value.byModel.length > 0 || (state.value.sessionRows?.length ?? 0) > 0 || auxRequests > 0\n ? (\n <section className={styles['detailPanel']}>\n <div className={styles['detailToolbar']}>\n <div className={styles['segmented']} role=\"group\" aria-label={t('detail.switch.label')}>\n {DETAIL_MODES.map(mode => (\n <button\n key={mode}\n type=\"button\"\n className={detailMode === mode ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={detailMode === mode}\n onClick={() => setDetailMode(mode)}\n >\n {t(detailLabelOf(mode))}\n </button>\n ))}\n </div>\n {detailMode !== 'aux' && (\n <div className={styles['sortRow']}>\n <span className={detailMode === 'model' && modelPerfView ? styles['sortHidden'] : undefined}>\n <RowSortControl\n compact\n value={detailMode === 'project' ? projectSort : detailMode === 'model' ? modelSort : detailMode === 'provider' ? providerSort : sessionSort}\n options={detailMode === 'project' ? PROJECT_SORT : detailMode === 'model' ? MODEL_SORT : detailMode === 'provider' ? PROVIDER_SORT : SESSION_SORT}\n onChange={detailMode === 'project' ? setProjectSort : detailMode === 'model' ? setModelSort : detailMode === 'provider' ? setProviderSort : setSessionSort}\n ariaLabel={t(detailLabelOf(detailMode))}\n t={t}\n />\n </span>\n {detailMode === 'model' && <PerfToggle compact pressed={modelPerfView} onToggle={setModelPerfView} t={t} />}\n </div>\n )}\n </div>\n <div className={styles['detailBody']}>\n {detailMode === 'aux'\n ? <OverheadRows aux={state.value.aux} costState={state.value.costState} view={view} t={t} />\n : <UsageRows\n key={detailMode}\n kind={detailMode}\n projectRows={projectRows}\n modelRows={state.value.byModel}\n sessionRows={state.value.sessionRows ?? []}\n providerRows={state.value.byProvider ?? []}\n providerNames={state.value.providerNames}\n sort={detailMode === 'project' ? projectSort : detailMode === 'model' ? modelSort : detailMode === 'provider' ? providerSort : sessionSort}\n perfView={detailMode === 'model' && modelPerfView}\n pricing={state.value.pricing}\n costState={state.value.costState}\n view={view}\n t={t}\n onToggleModel={handleToggleModel}\n onModelName={setDetailModel}\n {...sessionListed !== undefined && openSession !== undefined\n ? { sessionListed, onSessionOpen: handleOpenSession }\n : {}}\n />}\n </div>\n </section>\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 {toastText !== null && (\n <Toast\n key={toastSeq}\n text={toastText}\n icon={<IconWarningOutlineRegular />}\n onDone={dismissToast}\n />\n )}\n </PricingAssociationProvider>\n </div>\n )\n}\n","/**\n * The Token Usage main panel (browser half): the full-width page the\n * sidebar \"More\" menu row opens, registered into the `main` keyed slot\n * under key `token-usage` (declared by ui-layout). It wraps the\n * settings-section component unchanged — same stats route, same filters —\n * and adapts only the session-jump epilogue: the settings panel's `close`\n * becomes the page's return-to-conversation (selectPanel(null)), so a\n * Ctrl+click session jump lands on the target session.\n *\n * The registration waits on the shell's `main` declaration through\n * ctx.slots.inject; a shell that never declares it never runs the\n * callback, and the plugin's other surfaces are unaffected.\n *\n * @module token-usage/client/UsagePanelPage\n */\n\nimport type { ReactNode } from 'react'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the `main` keyed SlotMap key (declared by ui-layout).\nimport type {} from '@deepseek-ai/dsh-client-ui-layout/client'\nimport { TokenUsageSection } from './TokenUsageSection.tsx'\nimport css from './UsagePanelPage.module.css'\n\nexport type UsagePanelPageProps =\n PropsRuntime<'main'>\n & PropsLocale<'token-usage'>\n & {\n sessionListed?: (id: string) => boolean\n openSession?: (id: string) => { ok: boolean; reason?: string } | boolean\n /** Return the main column to the conversation (the page's \"close\"). */\n returnToConversation?: () => void\n }\n\n/**\n * Render the Token Usage page for the main column: the official\n * first-level-page shell (full-height scroll pane, centered 960px column)\n * wrapping the section in its `page` variant — the settings panel keeps its\n * own layout untouched.\n * @param props - the locale seat, the injected session-jump seats, and the\n * framework's (empty) main-panel owner share.\n * @returns the shelled section content.\n */\nexport function UsagePanelPage({ t, sessionListed, openSession, returnToConversation }: UsagePanelPageProps): ReactNode {\n return (\n <div className={css.page}>\n <div className={css.pageScroll}>\n <div className={css.pageContent}>\n <TokenUsageSection t={t} variant=\"page\" close={returnToConversation} sessionListed={sessionListed} openSession={openSession} />\n </div>\n </div>\n </div>\n )\n}\n","/**\n * The conversation usage tab's request pool (最新请求 / 实时请求): the\n * active-first request panel (items[0], six fixed metrics in order: cache hit,\n * input, output, first token, latency, speed — with cost / cache read /\n * cache write demoted to the footer) plus the history table of up to 19\n * earlier rows (columns frozen in order: origin, state, time, model, cache\n * hit, input, output, cache read, cache write, first token, latency, speed,\n * cost). The cache-write column is omitted when every visible request lacks\n * a reported write bucket.\n *\n * Every figure comes from the server snapshot (`requestDetails`) — the\n * component never re-derives rates or speeds, never runs its own clock\n * (in-flight elapsed is server-anchored), and never fills an unknown with a\n * zero or a session mean. The 「缓存过低」 label is a low-hit heuristic the\n * server already gated through every exclusion; its tooltip says so.\n *\n * @module token-usage/client/RequestPool\n */\n\nimport { useEffect, useRef } from 'react'\nimport type { ReactNode } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { CurrencyView } from './format.ts'\nimport { bandOf, formatCost, formatRequestRate, formatRequestRateExact, formatTimeOfDay, formatTokens, formatTtft } from './format.ts'\nimport { bandClassOf } from './HitRateText.tsx'\nimport type { CompactionAttributionItem, RequestDetailCache, RequestDetailView, SessionRequestDetails } from '../wire.ts'\nimport type { ConversationStatus } from '../wire.ts'\nimport styles from './UsageView.module.css'\n\nexport interface RequestPoolProps {\n details: SessionRequestDetails\n /** The focused session: rows from it are 「本会话」, from its descendants\n * 「子会话」— the same mapping the subagent table's drill-in uses. */\n focusId: string\n view: CurrencyView\n /** Epoch ms of the last successful refresh; set while the latest refresh\n * failed and the panel kept its previous snapshot (the stale notice). */\n staleAt?: number\n t: TranslateNS<'token-usage'>\n}\n\n/** The state pill's color class (state is never color-only — the label text\n * and the metrics columns carry the same facts). */\nfunction stateClassOf(state: RequestDetailView['state']): string {\n switch (state) {\n case 'failed': return styles['stateFailed'] ?? ''\n case 'cancelled':\n case 'interrupted':\n case 'waiting': return styles['statePending'] ?? ''\n case 'streaming': return styles['stateStreaming'] ?? ''\n default: return styles['stateDone'] ?? ''\n }\n}\n\n/** Numeric colour follows the summary cards, independently of label eligibility. */\nfunction hitClassOf(cache: RequestDetailCache): string | undefined {\n if (cache.rate === undefined) return styles['zeroDim'] ?? ''\n return bandClassOf(bandOf(cache.rate))\n}\n\n/** The hit cell's tooltip: the low-hit explanation (with the raw-precision\n * note when rounding would hide a sub-threshold rate) or the exclusion\n * reason. Unknown figures explain their unknown instead of going silent.\n * The compaction attribution (when the row carries one) rides the same\n * tooltip as its closing section — real-world feedback dropped the standalone\n * badge as redundant next to the 缓存过低 marker, and the causal chain reads\n * exactly where the rate is questioned. The wording says the prefix WAS\n * rewritten and cache behaviour MAY be affected — never that compaction\n * caused a cache loss, because a high-hit row can carry the same attribution\n * (the miss severity depends on the earliest rewritten position, which the\n * plugin cannot see). */\nfunction hitTooltipOf(cache: RequestDetailCache, t: TranslateNS<'token-usage'>, attribution?: readonly CompactionAttributionItem[]): string {\n const lines: string[] = []\n if (cache.rate === undefined) {\n if (cache.reason !== undefined) lines.push(t(`pool.excluded.${cache.reason}`))\n } else {\n const display = formatRequestRate(cache.rate)\n if (cache.band === 'loss') {\n lines.push(t('pool.cache.tooltip', { rate: display }))\n // Show raw precision when rounding hides why the loss label applies.\n if (Number.parseFloat(display) >= 50) {\n lines.push(t('pool.cache.roundedDown', { rate: formatRequestRateExact(cache.rate) }))\n }\n } else if (cache.reason !== undefined) {\n lines.push(t(`pool.excluded.${cache.reason}`))\n }\n }\n if (attribution !== undefined) {\n lines.push(t('pool.attribution.prefix'))\n for (const item of attribution) {\n lines.push(item.kind === 'prune'\n ? t('pool.attribution.prune', { count: String(item.count), tokens: formatTokens(item.shadowedTokenCount) })\n : t('pool.attribution.summary', { tokens: formatTokens(item.shadowedTokenCount) }))\n }\n }\n return lines.join('\\n')\n}\n\n/** The hit cell keeps request precision, shared numeric colours, and its explanation. */\nfunction HitCell({ cache, attribution, t }: { cache: RequestDetailCache; attribution?: readonly CompactionAttributionItem[] | undefined; t: TranslateNS<'token-usage'> }): ReactNode {\n const text = formatRequestRate(cache.rate)\n const tooltip = hitTooltipOf(cache, t, attribution)\n const content = <span className={hitClassOf(cache)}>{text}</span>\n return tooltip === ''\n ? content\n : <Tooltip label={tooltip} side=\"top\" delayMs={100}><span tabIndex={0}>{content}</span></Tooltip>\n}\n\n/** The model + kind-badge pair as one non-breaking inline group: the model\n * name compresses first, the kind badge (auxiliary subtype or compaction)\n * never wraps onto its own line. Kind is always the model cell's badge —\n * the origin column states only whose session issued the request. */\nfunction ModelCell({ detail, cache, t }: { detail: RequestDetailView; cache: RequestDetailCache; t: TranslateNS<'token-usage'> }): ReactNode {\n const rawModel = detail.responseModel ?? detail.requestedModel\n const model = detail.modelId ?? rawModel\n const modelTooltip = model !== rawModel\n ? `${rawModel} → ${model}`\n : detail.responseModel !== undefined && detail.responseModel !== detail.requestedModel\n ? `${detail.requestedModel} → ${detail.responseModel}`\n : model\n const name = (\n <Tooltip label={modelTooltip} side=\"top\" delayMs={100}>\n <span className={styles['modelName']} tabIndex={0}>{model}</span>\n </Tooltip>\n )\n const kindLabel = detail.kind === 'aux' && detail.auxKind !== undefined\n ? t(`pool.kind.${detail.auxKind}`)\n : detail.kind === 'compaction'\n ? t('pool.kind.compaction')\n : undefined\n // No attribution badge of its own: the rewrite's causal chain lives in the\n // hit cell's tooltip (real-world feedback found a standalone pill redundant\n // next to the 缓存过低 marker). The loss marker shares the same tooltip, so\n // it explains the attribution too.\n if (cache.band !== 'loss') {\n return <span className={styles['modelInline']}>\n {name}\n {kindLabel !== undefined && <span className={styles['auxKind']} aria-label={kindLabel}>{kindLabel}</span>}\n </span>\n }\n return (\n <span className={styles['modelInline']}>\n {name}\n {kindLabel !== undefined && <span className={styles['auxKind']} aria-label={kindLabel}>{kindLabel}</span>}\n <Tooltip label={hitTooltipOf(cache, t, detail.compactionAttribution)} side=\"top\" delayMs={100}>\n <span className={styles['cacheLoss']} tabIndex={0}>\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"m10.3 3.8-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3.2l-8-14a2 2 0 0 0-3.4 0Z\" /><path d=\"M12 9v4m0 4h.01\" /></svg>\n {t('pool.cache.label')}\n </span>\n </Tooltip>\n </span>\n )\n}\n\n/** The status cell carries the lifecycle state only: kind is the model\n * cell's badge, origin stays in the origin column — no dimension doubles\n * as another. */\nfunction stateTextOf(detail: RequestDetailView, t: TranslateNS<'token-usage'>): string {\n return t(`pool.state.${detail.state}`)\n}\n\n/** Latency column: settled rows show their measured latency; in-flight rows\n * show the server-anchored elapsed (已耗时); untimed rows stay —. */\nfunction latencyTextOf(detail: RequestDetailView): string {\n if (detail.state === 'waiting' || detail.state === 'streaming') {\n return detail.elapsedMs !== undefined ? formatTtft(detail.elapsedMs) : '—'\n }\n return detail.latencyMs !== undefined ? formatTtft(detail.latencyMs) : '—'\n}\n\n/** Speed column: the server's settled gate only — in-flight rows read —\n * (the lifecycle contract: no live token counts exist to average over; the\n * component double-checks the state so a stale field can never read as a\n * live speed). */\nfunction speedTextOf(detail: RequestDetailView): string {\n return detail.state === 'completed' && detail.speed !== undefined\n ? `${String(Math.round(detail.speed))} tok/s`\n : '—'\n}\n\n/** Cost column: priced figures render through the view; unpriced and\n * usage-less rows show — (never a fabricated zero). */\nfunction costTextOf(detail: RequestDetailView, view: CurrencyView): string {\n return detail.cost !== undefined && detail.pricingStatus === 'priced' ? formatCost(detail.cost, view) : '—'\n}\n\n/** Token-bucket text: a present count formats; an absent one stays —\n * (explicit 0 is a count and renders 0). */\nfunction tokenTextOf(value: number | undefined): string {\n return value !== undefined ? formatTokens(value) : '—'\n}\n\nfunction MetricValue({ text, unit = '' }: { text: string; unit?: string }): ReactNode {\n // Units stay visually quiet; the full text remains one accessible value.\n const match = text.match(/^(.*?)(tok\\/s|s)$/)\n const value = match?.[1] ?? text\n const suffix = text === '—' ? '' : match?.[2] ?? unit\n return <span>{value}{suffix !== '' && <span className={styles['metricUnit']}>{suffix}</span>}</span>\n}\n\n/** The panel's one-line notice: what it shows, how it reads, and the full\n * text behind the tooltip. `text` is the slot's line; `full` never drops a\n * fact the reader would otherwise lose. */\ninterface PanelNotice {\n /** 页脚右槽显示的一行文本。 */\n text: string\n /** Tooltip 的完整说明(可能比显示的长:会话状态 + 请求自身的诊断)。 */\n full: string\n /** 语气:`pending` 进行中(琥珀)、`error` 失败(红)、`neutral` 已结算(灰)。 */\n tone: 'pending' | 'error' | 'neutral'\n}\n\n/** 已结算请求自身的诊断说明:辅助请求不重复解释(紧凑标记已经说明),\n * 缓存排除与计时/用量/定价的缺口各自说明自己。 */\nfunction diagnosticOf(detail: RequestDetailView, t: TranslateNS<'token-usage'>): string {\n if (detail.kind === 'aux') return ''\n if (detail.pricingStatus === 'unpriced') return t('pool.note.unpriced')\n if (detail.inputTokens === undefined || detail.outputTokens === undefined) return t('pool.note.noUsage')\n if (detail.latencyMs === undefined || detail.firstTokenLatencyMs === undefined) return t('pool.note.untimed')\n if (detail.cache.band === 'excluded' || detail.cache.band === 'unknown') {\n return detail.cache.reason !== undefined ? t(`pool.excluded.${detail.cache.reason}`) : ''\n }\n return ''\n}\n\n/** The panel's notice: the conversation's state first (waiting for a tool\n * result / this turn is done / retrying after a failure), then the request's\n * own lifecycle, then the settled request's diagnostic. A lower-priority\n * fact never disappears — it moves into the tooltip instead, so both stay\n * reachable. */\nfunction noticeOf(\n detail: RequestDetailView,\n conversation: ConversationStatus | undefined,\n t: TranslateNS<'token-usage'>,\n): PanelNotice | undefined {\n const one = (text: string, tone: PanelNotice['tone']): PanelNotice => ({ text, full: text, tone })\n // The request's own lifecycle note. A settled (successful) row has none.\n const own = ((): PanelNotice | undefined => {\n switch (detail.state) {\n case 'waiting': return one(t('pool.note.waiting'), 'pending')\n case 'streaming': return one(t('pool.note.streaming'), 'pending')\n case 'cancelled': return one(t('pool.note.cancelled'), 'pending')\n case 'interrupted': return one(t('pool.note.interrupted'), 'pending')\n case 'failed': return one(t('pool.note.failed', { code: detail.failureCode ?? '' }), 'error')\n default: return undefined\n }\n })()\n // The settled request's own diagnostic — only a successful row carries one\n // (a failed attempt explains itself in its own note).\n const diagnostic = detail.state === 'completed' ? diagnosticOf(detail, t) : ''\n // The conversation's state is the headline; everything it outranks follows\n // it into the tooltip.\n const conversationNotice = (text: string, tone: PanelNotice['tone'], rest: string): PanelNotice => ({\n text,\n full: [text, rest, own?.text ?? '', diagnostic].filter(part => part !== '').join(' · '),\n tone,\n })\n if (conversation?.state === 'retrying') {\n const retry = conversation.retry\n const count = String(retry?.count ?? 1)\n const text = retry !== undefined && retry.max > 0\n ? t('pool.note.retrying', { count, max: String(retry.max) })\n : t('pool.note.retryingAlways', { count })\n const wait = retry === undefined\n ? ''\n : t('pool.note.retryWait', {\n seconds: String(Math.max(1, Math.round(retry.delayMs / 1000))),\n code: retry.code ?? '—',\n })\n return conversationNotice(text, 'pending', wait)\n }\n if (conversation?.state === 'awaiting-tool') {\n return conversationNotice(t('pool.note.awaitingTool'), 'pending', '')\n }\n if (conversation?.state === 'turn-complete') {\n return conversationNotice(t('pool.note.turnComplete'), 'neutral', '')\n }\n if (own !== undefined) {\n return diagnostic === '' ? own : { ...own, full: `${own.full} · ${diagnostic}` }\n }\n return diagnostic === '' ? undefined : one(diagnostic, 'neutral')\n}\n\n/** Fixed-layout column floors in px, in table order (origin, state, time,\n * model, cache hit, input, output, cache read, first token, latency, speed,\n * cost): each is the smallest width that column's content ever needs, so\n * `table-layout: fixed` can treat them as true floors — the pane shares\n * whatever surplus remains equally across all columns, and once the pane\n * can no longer fit the floors the table scrolls. The optional cache-write\n * column carries its own floor. */\nconst POOL_COL_FLOORS: readonly number[] = [52, 52, 64, 120, 56, 52, 52, 56, 44, 52, 72, 60]\nconst POOL_COL_FLOOR_CACHE_WRITE = 56\n\n/** One history row: the metrics stay in the visible order cache hit, input,\n * output, cache read, optional cache write, first token, latency, speed, cost.\n * Numbers right-aligned via the shared table CSS. */\nfunction PoolRow({ detail, focusId, view, showCacheWrite, t }: { detail: RequestDetailView; focusId: string; view: CurrencyView; showCacheWrite: boolean; t: TranslateNS<'token-usage'> }): ReactNode {\n const origin = detail.sessionId === focusId\n const time = detail.orderBasis === 'record'\n ? detail.recordTime ?? detail.orderAt\n : detail.startedAt ?? detail.orderAt\n return (\n <tr>\n <td data-label={t('pool.col.origin')} className={styles['poolOrigin']}>{t(origin ? 'pool.origin.self' : 'pool.origin.child')}</td>\n <td data-label={t('pool.col.state')} className={`${styles['poolState']} ${stateClassOf(detail.state)}`}>{stateTextOf(detail, t)}</td>\n <td data-label={t('pool.col.time')} className={styles['poolTime']}><time dateTime={new Date(time).toISOString()}>{formatTimeOfDay(time)}</time></td>\n <td data-label={t('pool.col.model')} className={styles['poolModel']}><ModelCell detail={detail} cache={detail.cache} t={t} /></td>\n <td data-label={t('pool.col.hit')}><HitCell cache={detail.cache} attribution={detail.compactionAttribution} t={t} /></td>\n <td data-label={t('pool.col.input')} title={t('pool.metric.hitInput')}>{tokenTextOf(detail.inputTokens)}</td>\n <td data-label={t('pool.col.output')}>{tokenTextOf(detail.outputTokens)}</td>\n <td data-label={t('pool.col.cacheRead')}>{tokenTextOf(detail.cacheReadTokens)}</td>\n {showCacheWrite && <td data-label={t('pool.col.cacheWrite')}>{tokenTextOf(detail.cacheWriteTokens)}</td>}\n <td data-label={t('pool.col.ttft')}>{detail.firstTokenLatencyMs !== undefined ? formatTtft(detail.firstTokenLatencyMs) : '—'}</td>\n <td data-label={t('pool.col.latency')}>{latencyTextOf(detail)}</td>\n <td data-label={t('pool.col.speed')} title={detail.state === 'waiting' || detail.state === 'streaming' ? t('pool.metric.speedSettled') : undefined}>{speedTextOf(detail)}</td>\n <td data-label={t('pool.col.cost')} className={styles['costCol']}>{costTextOf(detail, view)}</td>\n </tr>\n )\n}\n\n/**\n * Both request-pool sections: the latest panel and the history table. The\n * panel renders even for an empty pool (the empty prompt) — a session with\n * zero completed requests but one waiting must still show the area, with\n * the waiting row in it.\n */\nexport function RequestPoolSections({ details, focusId, view, staleAt, t }: RequestPoolProps): ReactNode {\n const { items, limit, activeCount } = details\n const latest = items[0]\n const history = items.slice(1)\n const showCacheWrite = items.some(item => item.cacheWriteTokens !== undefined)\n const colFloors = showCacheWrite ? [...POOL_COL_FLOORS, POOL_COL_FLOOR_CACHE_WRITE] : POOL_COL_FLOORS\n const beyond = Math.max(0, activeCount - items.filter(item => item.state === 'waiting' || item.state === 'streaming').length)\n // Scrollbar fade: the wrapper's thumb tints in only while the pane is\n // being scrolled, then fades back 800ms after the last event (the timer\n // dies with the component). Direct classList writes — no re-render.\n const wrapRef = useRef<HTMLDivElement | null>(null)\n const wrapTimer = useRef<number | undefined>(undefined)\n useEffect(() => () => window.clearTimeout(wrapTimer.current), [])\n const handleWrapScroll = (): void => {\n const box = wrapRef.current\n const cls = styles['scrolling']\n if (box === null || cls === undefined) return\n box.classList.add(cls)\n window.clearTimeout(wrapTimer.current)\n wrapTimer.current = window.setTimeout(() => {\n box.classList.remove(cls)\n }, 800)\n }\n\n const latestPanel = (\n <section className={styles['poolSection']} aria-label={t('pool.latest.title')}>\n <div className={styles['poolHead']}>\n <h3 className={styles['subtitle']}>{t('pool.latest.title')}</h3>\n <span className={styles['poolContext']}>{t('pool.latest.context')}</span>\n </div>\n {latest === undefined\n ? <div className={styles['latestPanel']}><div className={styles['poolEmpty']}>{t('pool.empty')}</div></div>\n : (\n (() => {\n const inFlight = latest.state === 'waiting' || latest.state === 'streaming'\n const origin = latest.sessionId === focusId\n const time = latest.orderBasis === 'record'\n ? latest.recordTime ?? latest.orderAt\n : latest.startedAt ?? latest.orderAt\n const notice = noticeOf(latest, details.conversation, t)\n // The note's colour follows its tone: failed reads as an error,\n // a settled note as quiet text, an in-flight / awaiting-tool note\n // as the amber 「still running」 voice.\n const noteClass = `${styles['requestNote']} ${notice?.tone === 'error'\n ? styles['requestNoteError'] ?? ''\n : notice?.tone === 'neutral'\n ? styles['requestNoteNeutral'] ?? ''\n : ''}`\n return (\n <div className={styles['latestPanel']}>\n <div className={styles['requestIdentity']}>\n <span className={styles['poolBadge']}>{t(origin ? 'pool.origin.self' : 'pool.origin.child')}</span>\n <span className={`${styles['poolState']} ${stateClassOf(latest.state)}`}><span className={styles['statusDot']} aria-hidden=\"true\" />{stateTextOf(latest, t)}</span>\n <ModelCell detail={latest} cache={latest.cache} t={t} />\n <span className={styles['poolContext']}><time dateTime={new Date(time).toISOString()}>{formatTimeOfDay(time)}</time></span>\n </div>\n <div className={styles['requestMetrics']}>\n <div>\n <div className={styles['metricValue']}><HitCell cache={latest.cache} attribution={latest.compactionAttribution} t={t} /></div>\n <div className={styles['metricLabel']}>{t('pool.col.hit')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={tokenTextOf(latest.inputTokens)} unit=\"tok\" /></div>\n <div className={styles['metricLabel']}>{t('pool.col.input')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={tokenTextOf(latest.outputTokens)} unit=\"tok\" /></div>\n <div className={styles['metricLabel']}>{t('pool.col.output')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={latest.firstTokenLatencyMs !== undefined ? formatTtft(latest.firstTokenLatencyMs) : '—'} /></div>\n <div className={styles['metricLabel']}>{t('pool.col.ttft')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={latencyTextOf(latest)} /></div>\n <div className={styles['metricLabel']} title={inFlight ? t('pool.metric.elapsed') : undefined}>{inFlight ? t('pool.metric.elapsedShort') : t('pool.col.latency')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={speedTextOf(latest)} /></div>\n <div className={styles['metricLabel']}>{t('pool.col.speed')}</div>\n </div>\n </div>\n <div className={styles['requestFooter']}>\n <div className={styles['requestBuckets']}>\n <span>{t('pool.metric.cost')} <b>{costTextOf(latest, view)}</b></span>\n <span>{t('pool.metric.cacheRead')} <b>{tokenTextOf(latest.cacheReadTokens)}</b></span>\n {showCacheWrite && <span>{t('pool.metric.cacheWrite')} <b>{tokenTextOf(latest.cacheWriteTokens)}</b></span>}\n </div>\n {/* The note lives in the footer's right slot — the same\n * slot the buckets mirror — so the panel keeps one\n * height whether a note exists or not. It is one line with\n * an ellipsis; the full text is in the tooltip. */}\n {notice !== undefined\n ? (\n <Tooltip label={notice.full} side=\"top\" delayMs={100}>\n <span className={noteClass} tabIndex={0}>{notice.text}</span>\n </Tooltip>\n )\n : staleAt !== undefined\n ? <span className={styles['poolContext']}>{t('pool.asOf', { time: formatTimeOfDay(staleAt) })}</span>\n : null}\n </div>\n </div>\n )\n })()\n )}\n </section>\n )\n\n const poolTable = (\n <section className={styles['poolSection']} aria-label={t('pool.title')}>\n <div className={styles['poolHead']}>\n <h3 className={styles['subtitle']}>\n {t('pool.title')}\n <span className={styles['poolContext']}> {t('pool.historyCount', { count: String(history.length) })}</span>\n </h3>\n <span className={styles['poolContext']}>\n <span>{t('pool.newest')}</span>{' · '}<span>{t('pool.count', { count: String(items.length), limit: String(limit) })}</span>\n {beyond > 0 ? ` · ${t('pool.activeBeyond', { count: String(beyond) })}` : ''}\n </span>\n </div>\n {staleAt !== undefined && (\n <div className={styles['poolNotice']} role=\"status\">\n {t('pool.stale', { time: formatTimeOfDay(staleAt) })}\n </div>\n )}\n {history.length === 0\n ? <div className={styles['poolEmpty']}>{items.length > 0 ? t('pool.emptyHistory') : t('pool.empty')}</div>\n : (\n <div ref={wrapRef} onScroll={handleWrapScroll} className={styles['poolTableWrap']} tabIndex={0} role=\"region\" aria-label={t('pool.history.scroll')}>\n <table className={styles['poolTable']} aria-label={t('pool.title')} style={{ minWidth: `${colFloors.reduce((sum, width) => sum + width, 0)}px` }}>\n <colgroup>\n {colFloors.map((width, index) => <col key={index} style={{ width }} />)}\n </colgroup>\n <thead>\n <tr>\n <th className={styles['poolModelHead']}>{t('pool.col.origin')}</th>\n <th>{t('pool.col.state')}</th>\n <th>{t('pool.col.time')}</th>\n <th className={styles['poolModelHead']}>{t('pool.col.model')}</th>\n <th>{t('pool.col.hit')}</th>\n <th>{t('pool.col.input')}</th>\n <th>{t('pool.col.output')}</th>\n <th>{t('pool.col.cacheRead')}</th>\n {showCacheWrite && <th>{t('pool.col.cacheWrite')}</th>}\n <th>{t('pool.col.ttft')}</th>\n <th>{t('pool.col.latency')}</th>\n <th>{t('pool.col.speed')}</th>\n <th>{t('pool.col.cost')}</th>\n </tr>\n </thead>\n <tbody>\n {history.map(detail => <PoolRow key={detail.id} detail={detail} focusId={focusId} view={view} showCacheWrite={showCacheWrite} t={t} />)}\n </tbody>\n </table>\n </div>\n )}\n </section>\n )\n\n return (\n <>\n {latestPanel}\n {poolTable}\n </>\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 (successful requests with a failure\n * pill, 4 token buckets, cost, hit rate, TTFT average, decode throughput) with a\n * scope switch between the session alone and its whole subagent subtree, a\n * per-hour trend chart and the per-model table from the host stats route\n * (`sessionId`-scoped), and a subagent table below — each row drill-in\n * 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 * The root declares `data-conversation-composer-overlay` — the same host\n * opt-in Trajectory uses. ConversationRoot hides the chat-column width\n * handles when that attribute is present, and the view owns its own\n * scroller instead of sharing the transcript's constrained column.\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 { SessionListState, UseProjection } from '@deepseek-ai/dsh-api-session-controller/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 { PricingStatus, costsAvailable } from './PricingStatus.tsx'\nimport { ModelAssociationBadge, PricingAssociationProvider, UnpricedModelTag } from './PricingAssociations.tsx'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { HitRateText } from './HitRateText.tsx'\nimport { RequestPoolSections } from './RequestPool.tsx'\nimport { aggregateProjections, buildChildIndex, directSubagentIds, subagentParentOf, subtreeIds, buildStatsFreshnessKey } from './session-stats.ts'\nimport { RequestsCell, RequestsStatCard, StatCard } from './StatCard.tsx'\nimport { TrendChart } from './TrendChart.tsx'\nimport type { TrendChartMode } 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/** Host contract (ui-conversation ConversationRoot): views that own a\n * full-bleed scroller set this so the chat-column width handles hide and\n * the composer seat overlays instead of stealing clicks over the dashboard. */\nconst COMPOSER_OVERLAY = { 'data-conversation-composer-overlay': '' } as const\n\n/** Props: the conversation-view runtime seat (standard kit) plus the locale\n * seat. The kit's `useSession` covers the Session lifecycle snapshot only;\n * the Conversation snapshot is not part of it — and this view never read it,\n * so the seat is simply dropped. */\nexport interface UsageViewProps {\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 trend chart's y-axis reading: per-interval totals or their running\n // cumulative sum. Session-local like the scope switch (no persistence).\n const [chartMode, setChartMode] = useState<TrendChartMode>('interval')\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 usePricingAssociationRefresh(retry)\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\n // Visibility fallback polling for the request pool: the event-driven\n // freshness key already refreshes on settled requests, but a WAITING row\n // produces no events between dispatch and first token. The poll is\n // SERIALIZED — the next tick is scheduled only after the previous fetch\n // settles — so a slow response is never cancelled mid-flight by the next\n // interval: with an active request the next poll runs 1s after the last\n // one finished, 5s idle, and a hidden tab schedules nothing (returning to\n // visibility refreshes once immediately).\n const [pollTick, setPollTick] = useState(0)\n const [pollSettle, setPollSettle] = useState(0)\n const [staleAt, setStaleAt] = useState<number | undefined>(undefined)\n const lastOkAtRef = useRef<number | undefined>(undefined)\n const pollTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const fetchingRef = useRef(false)\n const fetchVersionRef = useRef(0)\n // Scope changes are immediate; only event freshness is debounced. The\n // request and its cache identity must always describe the same range.\n const scopeKey = `${scopeIds.join('\\n')}\\n\\t${childGroups.map(group => group.join(',')).join(';')}`\n\n const [summaryState] = useAsyncResource<UsageSummary>(\n signal => {\n clearTimeout(pollTimerRef.current)\n fetchingRef.current = true\n const version = ++fetchVersionRef.current\n const [idsPart, groupsPart] = scopeKey.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 // Stale-snapshot honesty: a failed refresh keeps the previous\n // snapshot on screen (silentAfterFirst) and stamps the failure so the\n // pool shows \"数据截至 …\" instead of pretending to be live. A new\n // scope's first failure still lands in `error` (no snapshot to keep —\n // the scopeKey switch resets both the kept value and this stamp).\n return fetchSessionSummary(sessionIds, childGroups, signal)\n .then(value => {\n if (!signal.aborted) {\n lastOkAtRef.current = Date.now()\n setStaleAt(undefined)\n }\n return value\n })\n .catch((error: unknown) => {\n if (!signal.aborted && lastOkAtRef.current !== undefined) setStaleAt(lastOkAtRef.current)\n throw error\n })\n .finally(() => {\n // The scheduler's heartbeat: only a SETTLED fetch schedules the\n // next one (an aborted superseded attempt stays silent).\n if (version === fetchVersionRef.current) {\n fetchingRef.current = false\n if (!signal.aborted) setPollSettle(value => value + 1)\n }\n })\n },\n [debouncedKey.split('\\n\\t')[2], retryToken, pollTick],\n { silentAfterFirst: true, retryToken, scopeKey },\n )\n // A range switch also drops the freshness stamp — it belonged to the\n // previous range's last successful fetch, not to what is on screen now.\n useEffect(() => {\n lastOkAtRef.current = undefined\n setStaleAt(undefined)\n }, [scopeKey])\n\n const activeCount = summaryState.status === 'ready' ? summaryState.value.requestDetails?.activeCount ?? 0 : 0\n const hasActive = activeCount > 0\n useEffect(() => {\n if (document.visibilityState !== 'visible' || fetchingRef.current) return\n const timer = setTimeout(() => {\n if (document.visibilityState === 'visible') setPollTick(value => value + 1)\n }, hasActive ? 1_000 : 5_000)\n pollTimerRef.current = timer\n return () => { clearTimeout(timer) }\n }, [pollSettle, hasActive])\n useEffect(() => {\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible' && !fetchingRef.current) setPollTick(value => value + 1)\n }\n document.addEventListener('visibilitychange', onVisibility)\n return () => { document.removeEventListener('visibilitychange', onVisibility) }\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']} {...COMPOSER_OVERLAY}>\n <PricingAssociationProvider view={{ symbol: '¥', rate: 1 }} t={t}>\n {header}\n <p className={styles['muted']}>{t('loading')}</p>\n </PricingAssociationProvider>\n </div>\n )\n }\n if (summaryState.status === 'error') {\n return (\n <div ref={rootRef} className={styles['root']} {...COMPOSER_OVERLAY}>\n <PricingAssociationProvider view={{ symbol: '¥', rate: 1 }} t={t}>\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 </PricingAssociationProvider>\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']} {...COMPOSER_OVERLAY}>\n <PricingAssociationProvider resolutions={summary.modelResolutions} feedVersion={summary.feedVersion} view={view} t={t}>\n {header}\n {total.requests === 0 && (total.failures ?? 0) === 0\n // The session has no recorded requests (successful or failed); the\n // stat band is skipped but the subagent table below still renders\n // (children may hold usage even when this session's scoped summary\n // is empty).\n ? <p className={styles['empty']}>{t('view.empty')}</p>\n : (\n <>\n <div className={styles['cards']}>\n <RequestsStatCard\n requests={total.requests}\n failures={total.failures ?? 0}\n failuresByCode={total.failuresByCode}\n t={t}\n />\n <StatCard label={t('stat.cost')} value={costsAvailable(summary.costState) ? 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 <PricingStatus costState={summary.costState} pricingUnavailableReason={summary.pricingUnavailableReason} associationStorageError={summary.associationStorageError} t={t} />\n {costsAvailable(summary.costState) && 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 <div className={styles['chartHead']}>\n <h3 className={styles['subtitle']}>{t('view.chart.title')}</h3>\n <div className={styles['segmented']} role=\"group\" aria-label={t('chart.mode.label')}>\n <button\n type=\"button\"\n className={chartMode === 'interval' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={chartMode === 'interval'}\n onClick={() => setChartMode('interval')}\n >\n {t('chart.mode.interval')}\n </button>\n <button\n type=\"button\"\n className={chartMode === 'cumulative' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={chartMode === 'cumulative'}\n onClick={() => setChartMode('cumulative')}\n >\n {t('chart.mode.cumulative')}\n </button>\n </div>\n </div>\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 height={150}\n rows={summary.byDay}\n mode={chartMode}\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 title={t('stat.successFail')}>{t('stat.requestColumn')}</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']}>\n <span className={styles.modelIdentity}><span className={styles.modelName}>{row.model}</span>\n {summary.unpricedModels.includes(row.model) && <UnpricedModelTag model={row.model} t={t} />}\n <ModelAssociationBadge model={row.model} t={t} />\n </span>\n </td>\n <td>\n <RequestsCell\n requests={row.totals.requests}\n failures={row.totals.failures ?? 0}\n failuresByCode={row.totals.failuresByCode}\n t={t}\n />\n </td>\n <td className={row.totals.inputTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.inputTokens)}</td>\n <td className={row.totals.outputTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.outputTokens)}</td>\n <td className={row.totals.cacheReadTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.cacheReadTokens)}</td>\n <td className={row.totals.cacheWriteTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.cacheWriteTokens)}</td>\n <td><HitRateText totals={row.totals} /></td>\n <td className={styles['costCol']}>{costsAvailable(summary.costState) && !summary.unpricedModels.includes(row.model) ? 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 {summary.requestDetails !== undefined && (\n <RequestPoolSections\n details={summary.requestDetails}\n focusId={focusId}\n view={view}\n {...staleAt !== undefined ? { staleAt } : {}}\n t={t}\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 className={styles['costCol']}>\n {row !== undefined && costsAvailable(summary.costState) && costsAvailable(row.costState) ? 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 || (total.failures ?? 0) > 0) && <p className={styles['note']}>{t('view.note')}</p>}\n </PricingAssociationProvider>\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 'association.manage': '模型别名关联',\n 'association.title': '模型别名关联',\n 'association.unpricedTitle': '模型未定价',\n 'association.close': '关闭模型关联',\n 'association.choose': '关联现有模型',\n 'association.issue': '增加模型定价',\n 'association.tooltip': '此模型含手动关联:[{models}]',\n 'association.allHint': '模型别名与模型的本地映射',\n 'association.empty': '无数据',\n 'association.details': '查看/修改',\n 'association.state.active': '手动关联正在生效。',\n 'association.state.automatic-takeover': '已由自动识别接管,保存的关联未生效。',\n 'association.state.target-missing': '关联目标已失效,可重新选择或撤销。',\n 'association.state.pricing-unavailable': '定价表不可用,关联暂未生效。',\n 'association.automaticTarget': '自动目标:{model}。',\n 'association.targetDiffers': '与保存的目标 {model} 不同。',\n 'association.reactivate': '以后自动识别失败且原目标仍有效时,保存的关联会重新生效;可撤销以停止此行为。',\n 'association.automaticOnly': '该名称已有唯一自动识别结果,不能用手动关联覆盖。',\n 'association.search': '搜索模型',\n 'association.searchHint': '搜索模型 ID',\n 'association.candidates': '定价模型候选',\n 'association.noResults': '未找到模型,请调整搜索词',\n 'association.target': '所选目标:{model}',\n 'association.preview': '查看定价',\n 'association.impact': '绑定后,此别名的历史及后续用量将按所选模型计费。',\n 'association.save': '绑定模型',\n 'association.saving': '正在保存…',\n 'association.saved': '关联已保存,正在刷新用量与费用。',\n 'association.revoke': '撤销关联',\n 'association.confirmRevoke': '确认撤销',\n 'association.revokeImpact': '撤销将重新计算全部历史与后续用量;仍有自动匹配时继续定价,否则恢复未定价。',\n 'association.cancel': '取消',\n 'association.revoked': '关联已撤销,正在刷新用量与费用。',\n 'association.loadFailed': '无法加载模型关联与定价候选,请重试。',\n 'association.candidatesUnavailable': '定价候选加载失败,请重试;已保存的关联仍可查看和撤销。',\n 'association.writeFailed': '操作失败,尚未确认生效;请刷新真实状态后重试。',\n 'association.conflict': '关联或数据目录已变化,已读取当前状态;请核对后重新选择并提交。',\n 'association.migrating': '数据目录正在迁移,暂时不能修改关联。',\n 'association.targetUnavailable': '所选目标已不在当前定价表中,请刷新并重新选择。',\n 'association.refresh': '刷新当前状态',\n 'pricing.unavailable': '定价表不可用,费用暂不可计算;用量统计仍可查看。',\n 'pricing.reason.missing': '本机尚无定价镜像,请重试定价同步。',\n 'pricing.reason.unreadable': '本机定价镜像无法读取。',\n 'pricing.reason.invalid-json': '本机定价镜像不是有效 JSON。',\n 'pricing.reason.invalid-feed': '本机定价镜像未通过格式、模型 ID 或别名正则校验。',\n 'pricing.historyIncomplete': '历史源记录不完整,无法可靠重算费用;已保留可用用量统计。',\n 'pricing.associationStorageUnavailable': '本地模型关联文件无法读取或格式损坏,手动关联暂不生效;自动识别仍可使用。请先检查数据目录中的 pricing-associations.json。',\n 'pricing.identificationDetails': '查看模型识别详情',\n 'pricing.ambiguous': '模型识别存在歧义:{models}',\n 'pricing.unmatched': '未找到对应定价模型',\n 'nav.label': 'Token 用量',\n 'filter.quickRange': '快捷区间',\n 'filter.custom': '自定义',\n 'filter.dateRange': '日期范围',\n 'filter.allDates': '全部日期',\n 'filter.clear': '清除范围',\n 'filter.separator': '至',\n 'filter.model': '模型',\n 'filter.allModels': '全部模型',\n 'calendar.monthTitle': '{year}年{month}月',\n 'calendar.prevMonth': '上个月',\n 'calendar.nextMonth': '下个月',\n 'calendar.weekday.0': '一',\n 'calendar.weekday.1': '二',\n 'calendar.weekday.2': '三',\n 'calendar.weekday.3': '四',\n 'calendar.weekday.4': '五',\n 'calendar.weekday.5': '六',\n 'calendar.weekday.6': '日',\n 'stat.requests': '请求数',\n 'stat.requestColumn': '请求',\n 'stat.successFail': '成功/失败',\n 'stat.failuresPill': '失败 {count}',\n 'fail.RATE_LIMIT': '限流',\n 'fail.SERVER': '服务异常',\n 'fail.TIMEOUT': '超时',\n 'fail.TRANSPORT': '网络异常',\n 'fail.EMPTY_RESPONSE': '空响应',\n 'fail.QUOTA': '配额耗尽',\n 'fail.CONTEXT_WINDOW_EXCEEDED': '上下文超限',\n 'fail.INVALID_CREDENTIAL': '凭证无效',\n 'fail.AUTH': '鉴权失败',\n 'fail.INVALID_REQUEST': '请求无效',\n 'fail.MISSING_CREDENTIAL': '缺少凭证',\n 'fail.ABORTED': '已中止',\n 'fail.REQUEST_EXTENSION': '请求扩展失败',\n 'fail.FILES_API': '文件接口异常',\n 'fail.STREAM_CLOSED': '流中断',\n 'fail.MALFORMED_RESPONSE': '响应异常',\n 'fail.UNKNOWN': '未知错误',\n 'stat.totalTokens': '总 token',\n 'stat.hitRate': '命中率',\n 'stat.cost': '费用',\n 'stat.input': '入',\n 'stat.output': '出',\n 'stat.cacheRead': '缓',\n 'stat.cacheWrite': '写',\n 'stat.overheadPill': '开销 {count}',\n 'sort.tokens': 'token',\n 'perf.toggle': '性能',\n 'perf.first': '首',\n 'perf.avgLatency': '耗时',\n 'perf.noTiming': '无计时数据',\n 'perf.lowSamples': '样本不足',\n 'perf.requestCount': '{count} 次',\n 'byModel.title': '按模型',\n 'byProvider.title': '按供应商',\n 'byProvider.unattributed': '缺失供应商',\n 'byProvider.cause.intro': '可能是:',\n 'byProvider.cause.deletedLog': '会话日志已删除的历史会话',\n 'byProvider.cause.preField': '路由键字段加入前的旧会话',\n 'byProvider.cause.bypass': '不带路由键的运行开销',\n 'bySession.title': '按会话',\n 'byProject.title': '按项目',\n 'aux.tab': '运行开销',\n 'aux.kind': '类别',\n 'aux.kind.auto-review': '自动审查',\n 'aux.kind.session-title': '标题生成',\n 'aux.kind.translation': '推理翻译',\n 'aux.kind.other': '其他',\n 'aux.requests': '次数',\n 'aux.total': '合计',\n 'aux.empty': '暂无运行开销记录。',\n 'aux.subtitle': '辅助模型请求',\n 'aux.totalCount': '合计 · {count} 次',\n 'aux.requestCount': '{count} 次',\n 'aux.tooltipTotal': '运行开销 · 合计',\n 'board.projects': '项目',\n 'board.sessions': '会话',\n 'board.models': '模型',\n 'board.providers': '供应商',\n 'board.byTokens': '{count} 个 · 按总 token',\n 'board.byCost': '{count} 个 · 按费用',\n 'board.bySpeed': '{count} 个 · 按输出速度',\n 'board.sessionsCount': '共 {count} 条',\n 'trend.title': '趋势',\n 'time.minutesAgo': '{count} 分钟前',\n 'time.hoursAgo': '{count} 小时前',\n 'time.daysAgo': '{count} 天前',\n 'model.ctrlHint': '按住 Ctrl 点击:仅展示该模型',\n 'detail.switch.label': '明细维度',\n 'session.titleCol': '会话',\n 'session.group.label': '目录分组',\n 'session.group.on': '分组',\n 'session.group.off': '列表',\n 'session.untitledDir': '未指定目录',\n 'session.subagentBadge': '子会话',\n 'session.lastActive': '最近活跃',\n 'session.openHint': '按住 Ctrl 点击打开该会话(用量页签跟随该会话上次的选择)',\n 'session.workspaceDeleted': '该会话所属工作区已删除,无法跳转',\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 'pricing.table': '定价表',\n 'pricing.search': '搜索模型',\n 'pricing.used': '已用',\n 'pricing.overviewFailed': '模型定价获取失败',\n 'pricing.simCost': '模拟费用',\n 'pricing.simInput': '输入 {tokens}',\n 'pricing.simCache': '(缓存 {pct}%)',\n 'pricing.simOutput': '输出 {tokens}',\n 'pricing.simBucketInput': '输入',\n 'pricing.simBucketCacheRead': '缓存读',\n 'pricing.simBucketOutput': '输出',\n 'pricing.simBucketCacheWrite': '缓存写',\n 'pricing.simCase': '案例{index}',\n 'pricing.simUnitOf': '{bucket}({unit})',\n 'pricing.expand': '展开定价条件',\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.pricingSync.button': '同步定价表',\n 'card.pricingSync.running': '同步中…',\n 'card.pricingSync.done': '定价表已同步:版本 {version},共 {models} 个模型。',\n 'card.pricingSync.failed': '定价表同步失败,已保留原有定价表,请重试。',\n 'card.pricingSync.changed': '定价区域或数据目录已变更,请重新同步。',\n 'card.pricingSync.migrating': '数据目录正在迁移,请稍后再同步。',\n 'card.pricingSync.unsaved': '请先保存或放弃设置修改,再同步定价表。',\n 'card.hint': '切换到「全球」后从 GitHub 镜像拉取定价表,费用按美元展示(RMB ÷ 汇率);保存后立即重新同步,失败沿用旧镜像。',\n 'card.overridden': '已覆盖默认值',\n 'card.sidebarPinned.label': '常驻侧边栏',\n 'card.sidebarPinned.hint': '开启后「Token 用量」固定为左侧边栏的一行,「更多」菜单中的入口随之移除;关闭后从「更多」菜单进入。更改随「保存」生效。',\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} 条,删除 {removed} 条',\n 'card.fullSync.failuresNote': ',无法读取 {count} 个 session 已跳过',\n 'card.fullSync.done': '扫描完成:新增 {added} 条,跳过 {skipped} 条,删除 {removed} 条',\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 'chart.mode.label': '趋势模式',\n 'chart.mode.interval': '分时',\n 'chart.mode.cumulative': '累计',\n 'chart.ariaCumulative': '累计 token 曲线',\n 'chart.cumulativePoint': '{day} 累计 {tokens}',\n 'chart.cumulativeBucket': '{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 'pool.latest.title': '最新请求',\n 'pool.latest.context': '单次请求 · 非会话均值',\n 'pool.title': '实时请求',\n 'pool.count': '请求池 {count} / {limit}',\n 'pool.newest': '最新优先',\n 'pool.history.scroll': '请求历史,可滚动查看',\n 'pool.pending': '请求进行中',\n 'pool.ended': '请求已结束',\n 'pool.asOf': '数据截至 {time}',\n 'pool.metric.elapsedShort': '已耗时',\n 'pool.historyCount': '{count} 条历史',\n 'pool.empty': '暂无请求 · 发起第一条请求后,速度与缓存信息将在这里展示',\n 'pool.emptyHistory': '还没有上一条请求 · 下一条到来后,当前请求会移入这里',\n 'pool.loading': '正在加载…',\n 'pool.activeBeyond': '还有 {count} 条进行中的请求不在最近窗口内',\n 'pool.stale': '刷新失败 · 保留截至 {time} 的数据',\n 'pool.origin.self': '本会话',\n 'pool.origin.child': '子会话',\n 'pool.kind.compaction': '压缩',\n 'pool.kind.auto-review': '审查',\n 'pool.kind.session-title': '标题',\n 'pool.kind.translation': '翻译',\n 'pool.kind.other': '辅助',\n 'pool.attribution.prefix': '此请求发出前,宿主的压缩操作改写了上下文前缀,缓存表现可能受影响:',\n 'pool.attribution.prune': '工具结果剪枝改写了请求前缀({count} 条,剪除消息的影子 token 合计 {tokens})',\n 'pool.attribution.summary': 'LLM 摘要替换了会话历史(影子 token {tokens})',\n 'pool.state.waiting': '等待首 token',\n 'pool.state.streaming': '生成中',\n 'pool.state.completed': '已完成',\n 'pool.state.failed': '失败',\n 'pool.state.cancelled': '已取消',\n 'pool.state.interrupted': '连接中断',\n 'pool.state.recordTime': '记录时间',\n 'pool.col.origin': '来源',\n 'pool.col.state': '状态',\n 'pool.col.time': '时间',\n 'pool.col.model': '模型',\n 'pool.col.hit': '缓存命中',\n 'pool.col.cacheRead': '缓存读',\n 'pool.col.cacheWrite': '缓存写',\n 'pool.col.input': '输入',\n 'pool.col.output': '输出',\n 'pool.col.ttft': '首字',\n 'pool.col.latency': '耗时',\n 'pool.col.speed': '速度',\n 'pool.col.cost': '费用',\n 'pool.metric.cost': '本次费用',\n 'pool.metric.cacheRead': '缓存读',\n 'pool.metric.cacheWrite': '缓存写',\n 'pool.metric.hitInput': '未缓存输入(缓存读另列,不计入输入)',\n 'pool.metric.ttft': '首个非空模型增量(含推理/工具参数),非仅可见正文首字',\n 'pool.metric.speedSettled': '输出 token ÷ 生成时长(首字后),生成时长不足 500ms 或计时缺失时不显示',\n 'pool.metric.elapsed': '已耗时(按服务端时间锚定)',\n 'pool.cache.label': '缓存过低',\n 'pool.cache.tooltip': '本次缓存命中 {rate}。这是低命中提示,不代表已确认服务端缓存失效。',\n 'pool.cache.roundedDown': '显示值经四舍五入,原始命中率为 {rate}。',\n 'pool.excluded.cold-start': '会话首条请求(冷启动),不判断缓存过低',\n 'pool.excluded.model-switch': '切换模型或路由后的首条请求,不判断缓存过低',\n 'pool.excluded.in-flight': '请求尚未完成,暂不评估缓存',\n 'pool.excluded.not-success': '请求未成功完成,不贴缓存性能诊断标签',\n 'pool.excluded.compaction': '压缩请求,不做缓存性能诊断',\n 'pool.excluded.auxiliary': '辅助请求,不做缓存性能诊断',\n 'pool.excluded.cache-unreported': '服务商未报告缓存读,缺失值不当作 0',\n 'pool.excluded.insufficient-input': '输入未满足该路由的缓存条件(不足一个缓存块),不判断缓存过低',\n 'pool.excluded.invalid-data': '缓存计数缺失或矛盾,无法计算命中率',\n 'pool.note.waiting': '首 token 尚未到达;暂不计算输出速度',\n 'pool.note.streaming': '生成中 · 服务商未提供实时 token 计数,速度待结束后结算',\n 'pool.note.awaitingTool': '等待tool结果',\n 'pool.note.turnComplete': '本轮对话已完成',\n 'pool.note.retrying': '请求失败,正在重试({count}/{max})',\n 'pool.note.retryingAlways': '请求失败,正在重试(第 {count} 次)',\n 'pool.note.retryWait': '{seconds} 秒后重试 · 失败码 {code}',\n 'pool.note.cancelled': '请求被取消 · 已交付的部分用量按记录展示,不估算缺失数据',\n 'pool.note.interrupted': '连接中断 · 无法确认请求的结束状态',\n 'pool.note.unpriced': '模型未定价 · 保留 token、缓存与性能,费用显示 —',\n 'pool.note.noUsage': '服务商未报告 token 用量 · 不显示为 0',\n 'pool.note.untimed': '历史记录无完整计时 · 不以 0 或会话平均值代替',\n 'pool.note.failed': '{code} · 失败尝试独立成行,未报告用量,不计为成功请求',\n 'pool.speed.pending': '待结束后结算',\n 'pill.cost': '费用 {value}',\n 'pill.costWithSubs': '费用(含子会话){value}',\n 'pill.scopeTag': '含子会话',\n 'panel.title': '用量明细',\n 'panel.openHint': '点击展开用量明细',\n 'panel.tokens': '{value} tok',\n 'panel.hitRate': '缓存命中 {value}',\n 'panel.self': '本会话',\n 'panel.subs': '子会话 ×{count}',\n 'panel.byModel': '按模型',\n 'panel.unpriced': '未定价模型 ×{count}',\n 'panel.unpricedNote': '仅计 token',\n 'quota.trigger': '供应商配额',\n 'quota.triggerSummary': '{name} · {figure}',\n 'quota.triggerSummaryPooled': '{name} · {figure}({count} 个额度均值)',\n 'quota.panel': '供应商配额面板',\n 'quota.tier.fiveHour': '5 小时',\n 'quota.tier.weekly': '每周',\n 'quota.tier.monthly': '每月',\n 'quota.tier.other': '额度',\n 'quota.tier.balance': '余额',\n 'quota.tier.recharge': '充值余额',\n 'quota.tier.bonus': '赠金余额',\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.signedOut': '未登录 DeepSeek 账号,登录后可查看余额。',\n 'quota.error.parse': '响应解析失败({message})。',\n} as const\n\n/** English dictionary (same key set). */\nexport const en: Record<TokenUsageKey, string> = {\n 'association.manage': 'Model alias associations',\n 'association.title': 'Model alias associations',\n 'association.unpricedTitle': 'Unpriced model',\n 'association.close': 'Close model associations',\n 'association.choose': 'Associate an existing model',\n 'association.issue': 'Add model pricing',\n 'association.tooltip': 'This model includes manual associations: [{models}]',\n 'association.allHint': 'Local mappings between model aliases and models',\n 'association.empty': 'No data',\n 'association.details': 'View / edit',\n 'association.state.active': 'Manual association is active.',\n 'association.state.automatic-takeover': 'Automatic identification takes priority; the saved choice is inactive.',\n 'association.state.target-missing': 'The target is no longer available. Choose another model or revoke.',\n 'association.state.pricing-unavailable': 'Pricing is unavailable; the association is inactive.',\n 'association.automaticTarget': 'Automatic target: {model}.',\n 'association.targetDiffers': 'It differs from the saved target {model}.',\n 'association.reactivate': 'The saved choice will reactivate if automatic identification fails and the original target is still valid. Revoke to stop this behavior.',\n 'association.automaticOnly': 'This name has a unique automatic match. Manual associations cannot override it.',\n 'association.search': 'Search models',\n 'association.searchHint': 'Search model IDs',\n 'association.candidates': 'Pricing model candidates',\n 'association.noResults': 'No models found. Try another search.',\n 'association.target': 'Selected target: {model}',\n 'association.preview': 'View pricing',\n 'association.impact': 'Past and future usage of this alias will use the selected model’s pricing.',\n 'association.save': 'Bind model',\n 'association.saving': 'Saving…',\n 'association.saved': 'Association saved. Refreshing usage and costs.',\n 'association.revoke': 'Revoke association',\n 'association.confirmRevoke': 'Confirm revocation',\n 'association.revokeImpact': 'Recalculates all past and future usage. Automatic matches remain priced; otherwise the name becomes unpriced.',\n 'association.cancel': 'Cancel',\n 'association.revoked': 'Association revoked. Refreshing usage and costs.',\n 'association.loadFailed': 'Could not load associations and pricing candidates. Please retry.',\n 'association.candidatesUnavailable': 'Pricing candidates could not be loaded. Retry; saved associations can still be viewed and revoked.',\n 'association.writeFailed': 'The operation was not confirmed. Refresh the actual state before retrying.',\n 'association.conflict': 'Associations or the data directory changed. Current state was retrieved; review, choose again and submit.',\n 'association.migrating': 'The data directory is migrating. Associations cannot be changed yet.',\n 'association.targetUnavailable': 'The selected target is no longer in the current pricing table. Refresh and choose again.',\n 'association.refresh': 'Refresh current state',\n 'pricing.unavailable': 'Pricing is unavailable. Costs cannot be calculated; usage remains available.',\n 'pricing.reason.missing': 'No local pricing mirror exists yet. Retry pricing sync.',\n 'pricing.reason.unreadable': 'The local pricing mirror cannot be read.',\n 'pricing.reason.invalid-json': 'The local pricing mirror is not valid JSON.',\n 'pricing.reason.invalid-feed': 'The local mirror failed schema, model ID, or alias pattern validation.',\n 'pricing.historyIncomplete': 'Historical source records are incomplete. Reliable costs cannot be recalculated; available usage is retained.',\n 'pricing.associationStorageUnavailable': 'Local model associations are unreadable or malformed. Manual choices are inactive; automatic identification remains available. Check pricing-associations.json in the data directory.',\n 'pricing.identificationDetails': 'Model identification details',\n 'pricing.ambiguous': 'Ambiguous model identification: {models}',\n 'pricing.unmatched': 'No matching pricing model',\n 'nav.label': 'Token Usage',\n 'filter.quickRange': 'Quick range',\n 'filter.custom': 'Custom',\n 'filter.dateRange': 'Date range',\n 'filter.allDates': 'All dates',\n 'filter.clear': 'Clear range',\n 'filter.separator': 'to',\n 'filter.model': 'Model',\n 'filter.allModels': 'All models',\n 'calendar.monthTitle': '{month} {year}',\n 'calendar.prevMonth': 'Previous month',\n 'calendar.nextMonth': 'Next month',\n 'calendar.weekday.0': 'Mo',\n 'calendar.weekday.1': 'Tu',\n 'calendar.weekday.2': 'We',\n 'calendar.weekday.3': 'Th',\n 'calendar.weekday.4': 'Fr',\n 'calendar.weekday.5': 'Sa',\n 'calendar.weekday.6': 'Su',\n 'stat.requests': 'Requests',\n 'stat.requestColumn': 'Requests',\n 'stat.successFail': 'OK/Fail',\n 'stat.failuresPill': 'Failed {count}',\n 'fail.RATE_LIMIT': 'Rate limited',\n 'fail.SERVER': 'Server error',\n 'fail.TIMEOUT': 'Timed out',\n 'fail.TRANSPORT': 'Network error',\n 'fail.EMPTY_RESPONSE': 'Empty response',\n 'fail.QUOTA': 'Quota exceeded',\n 'fail.CONTEXT_WINDOW_EXCEEDED': 'Context exceeded',\n 'fail.INVALID_CREDENTIAL': 'Invalid credential',\n 'fail.AUTH': 'Auth failed',\n 'fail.INVALID_REQUEST': 'Invalid request',\n 'fail.MISSING_CREDENTIAL': 'Missing credential',\n 'fail.ABORTED': 'Aborted',\n 'fail.REQUEST_EXTENSION': 'Request extension failed',\n 'fail.FILES_API': 'Files API error',\n 'fail.STREAM_CLOSED': 'Stream closed',\n 'fail.MALFORMED_RESPONSE': 'Malformed response',\n 'fail.UNKNOWN': 'Unknown error',\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 'stat.overheadPill': 'Overhead {count}',\n 'sort.tokens': 'Tokens',\n 'perf.toggle': 'Performance',\n 'perf.first': 'first',\n 'perf.avgLatency': 'avg',\n 'perf.noTiming': 'No timing data',\n 'perf.lowSamples': 'Low samples',\n 'perf.requestCount': '{count} reqs',\n 'byModel.title': 'By model',\n 'byProvider.title': 'By provider',\n 'byProvider.unattributed': 'Missing provider',\n 'byProvider.cause.intro': 'Could be:',\n 'byProvider.cause.deletedLog': 'History sessions whose logs were deleted',\n 'byProvider.cause.preField': 'Sessions older than the route-key field',\n 'byProvider.cause.bypass': 'Bypass calls that carry no route key',\n 'bySession.title': 'By session',\n 'byProject.title': 'By project',\n 'aux.tab': 'Runtime overhead',\n 'aux.kind': 'Category',\n 'aux.kind.auto-review': 'Auto review',\n 'aux.kind.session-title': 'Session titles',\n 'aux.kind.translation': 'Translation',\n 'aux.kind.other': 'Other',\n 'aux.requests': 'Calls',\n 'aux.total': 'Total',\n 'aux.empty': 'No runtime overhead recorded.',\n 'aux.subtitle': 'Auxiliary requests',\n 'aux.totalCount': 'Total · {count}',\n 'aux.requestCount': '{count} calls',\n 'aux.tooltipTotal': 'Overhead · total',\n 'board.projects': 'Projects',\n 'board.sessions': 'Sessions',\n 'board.models': 'Models',\n 'board.providers': 'Providers',\n 'board.byTokens': '{count} · by tokens',\n 'board.byCost': '{count} · by cost',\n 'board.bySpeed': '{count} · by speed',\n 'board.sessionsCount': '{count} sessions',\n 'trend.title': 'Trend',\n 'time.minutesAgo': '{count}m ago',\n 'time.hoursAgo': '{count}h ago',\n 'time.daysAgo': '{count}d ago',\n 'model.ctrlHint': 'Ctrl+click to show only this model',\n 'detail.switch.label': 'Detail dimension',\n 'session.titleCol': 'Session',\n 'session.group.label': 'Directory grouping',\n 'session.group.on': 'Grouped',\n 'session.group.off': 'List',\n 'session.untitledDir': 'No directory',\n 'session.subagentBadge': 'Subagent',\n 'session.lastActive': 'Last active',\n 'session.openHint': 'Ctrl+click to open this session (the usage tab follows its last selection)',\n 'session.workspaceDeleted': 'The workspace for this session has been deleted and cannot be opened',\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 'pricing.table': 'Pricing',\n 'pricing.search': 'Search models',\n 'pricing.used': 'Used',\n 'pricing.overviewFailed': 'Failed to load model pricing',\n 'pricing.simCost': 'Est. cost',\n 'pricing.simInput': 'In {tokens}',\n 'pricing.simCache': ' (cache {pct}%)',\n 'pricing.simOutput': 'Out {tokens}',\n 'pricing.simBucketInput': 'Input',\n 'pricing.simBucketCacheRead': 'Cache read',\n 'pricing.simBucketOutput': 'Output',\n 'pricing.simBucketCacheWrite': 'Cache write',\n 'pricing.simCase': 'Case {index}',\n 'pricing.simUnitOf': '{bucket} ({unit})',\n 'pricing.expand': 'Show rate conditions',\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.pricingSync.button': 'Sync pricing table',\n 'card.pricingSync.running': 'Syncing…',\n 'card.pricingSync.done': 'Pricing synced: version {version}, {models} models.',\n 'card.pricingSync.failed': 'Pricing sync failed. The previous table is retained; try again.',\n 'card.pricingSync.changed': 'The pricing region or data directory changed. Sync again.',\n 'card.pricingSync.migrating': 'The data directory is moving. Try syncing later.',\n 'card.pricingSync.unsaved': 'Save or discard your settings changes before syncing pricing.',\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.sidebarPinned.label': 'Pin to sidebar',\n 'card.sidebarPinned.hint': 'Shows Token Usage as a resident sidebar row and removes it from the More menu; when off, the entry lives in the sidebar More menu. Changes apply on save.',\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}, removed {removed}',\n 'card.fullSync.failuresNote': ', {count} unreadable sessions skipped',\n 'card.fullSync.done': 'Scan complete: added {added}, skipped {skipped}, removed {removed}',\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 'chart.mode.label': 'Trend mode',\n 'chart.mode.interval': 'Interval',\n 'chart.mode.cumulative': 'Cumulative',\n 'chart.ariaCumulative': 'Cumulative token trend',\n 'chart.cumulativePoint': '{day} cumulative {tokens}',\n 'chart.cumulativeBucket': '{window} · {count} requests · cumulative {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 'pool.latest.title': 'Latest request',\n 'pool.latest.context': 'single request · not a session mean',\n 'pool.title': 'Live requests',\n 'pool.count': 'pool {count} / {limit}',\n 'pool.newest': 'Newest first',\n 'pool.history.scroll': 'Request history, scroll to see more',\n 'pool.pending': 'Request in progress',\n 'pool.ended': 'Request ended',\n 'pool.asOf': 'Data as of {time}',\n 'pool.metric.elapsedShort': 'Elapsed',\n 'pool.historyCount': '{count} in history',\n 'pool.empty': 'No requests yet · speed and cache figures appear here after the first request',\n 'pool.emptyHistory': 'No earlier request yet · the current one moves here when the next arrives',\n 'pool.loading': 'Loading…',\n 'pool.activeBeyond': '{count} more in-flight requests outside the recent window',\n 'pool.stale': 'Refresh failed · showing data as of {time}',\n 'pool.origin.self': 'This session',\n 'pool.origin.child': 'Subagent',\n 'pool.kind.compaction': 'Compaction',\n 'pool.kind.auto-review': 'Review',\n 'pool.kind.session-title': 'Title',\n 'pool.kind.translation': 'Translation',\n 'pool.kind.other': 'Auxiliary',\n 'pool.attribution.prefix': 'Before this request, host compaction rewrote the context prefix; cache behaviour may be affected:',\n 'pool.attribution.prune': 'Tool-result pruning rewrote the request prefix ({count} event(s), shadow tokens of pruned messages {tokens})',\n 'pool.attribution.summary': 'An LLM summary replaced the conversation history (shadow tokens {tokens})',\n 'pool.state.waiting': 'Waiting for first token',\n 'pool.state.streaming': 'Generating',\n 'pool.state.completed': 'Completed',\n 'pool.state.failed': 'Failed',\n 'pool.state.cancelled': 'Cancelled',\n 'pool.state.interrupted': 'Connection lost',\n 'pool.state.recordTime': 'recorded',\n 'pool.col.origin': 'Origin',\n 'pool.col.state': 'State',\n 'pool.col.time': 'Time',\n 'pool.col.model': 'Model',\n 'pool.col.hit': 'Cache hit',\n 'pool.col.cacheRead': 'Cache read',\n 'pool.col.cacheWrite': 'Cache write',\n 'pool.col.input': 'Input',\n 'pool.col.output': 'Output',\n 'pool.col.ttft': 'First tok',\n 'pool.col.latency': 'Latency',\n 'pool.col.speed': 'Speed',\n 'pool.col.cost': 'Cost',\n 'pool.metric.cost': 'Request cost',\n 'pool.metric.cacheRead': 'Cache read',\n 'pool.metric.cacheWrite': 'Cache write',\n 'pool.metric.hitInput': 'Uncached input (cache reads listed separately, never folded in)',\n 'pool.metric.ttft': 'First non-empty model delta (reasoning / tool args included), not just visible text',\n 'pool.metric.speedSettled': 'Output tokens ÷ generation span (after first token); hidden when the span is under 500ms or timing is missing',\n 'pool.metric.elapsed': 'Elapsed (anchored to server time)',\n 'pool.cache.label': 'Low cache hit',\n 'pool.cache.tooltip': 'Cache hit {rate}. This is a low-hit hint, not confirmed server-side cache failure.',\n 'pool.cache.roundedDown': 'The displayed figure is rounded; the raw cache hit rate is {rate}.',\n 'pool.excluded.cold-start': 'First request of the session (cold start), not assessed',\n 'pool.excluded.model-switch': 'First request after a model or route switch, not assessed',\n 'pool.excluded.in-flight': 'Request not finished yet; cache not assessed',\n 'pool.excluded.not-success': 'Request did not complete successfully; no cache diagnostics label',\n 'pool.excluded.compaction': 'Compaction request; no cache diagnostics',\n 'pool.excluded.auxiliary': 'Auxiliary request; no cache diagnostics',\n 'pool.excluded.cache-unreported': 'Provider did not report cache reads; a missing value is never treated as 0',\n 'pool.excluded.insufficient-input': 'Input below this route\\'s cache minimum (under one cache block), not assessed',\n 'pool.excluded.invalid-data': 'Cache counts missing or contradictory; no hit rate computed',\n 'pool.note.waiting': 'First token not arrived; output speed not computed',\n 'pool.note.streaming': 'Generating · the provider reports no live token counts; speed settles after completion',\n 'pool.note.awaitingTool': 'Waiting for tool result',\n 'pool.note.turnComplete': 'This turn is complete',\n 'pool.note.retrying': 'Request failed, retrying ({count}/{max})',\n 'pool.note.retryingAlways': 'Request failed, retrying (attempt {count})',\n 'pool.note.retryWait': 'next attempt in {seconds}s · failure {code}',\n 'pool.note.cancelled': 'Cancelled · delivered partial usage shown as recorded, nothing estimated',\n 'pool.note.interrupted': 'Connection lost · the request\\'s final state cannot be confirmed',\n 'pool.note.unpriced': 'Model unpriced · tokens, cache and timing kept, cost shows —',\n 'pool.note.noUsage': 'Provider reported no token usage · never shown as 0',\n 'pool.note.untimed': 'Historical record without complete timing · never filled with 0 or session means',\n 'pool.note.failed': '{code} · the failed attempt is its own row; unreported usage, not counted as a success',\n 'pool.speed.pending': 'settles after completion',\n 'pill.cost': 'Cost {value}',\n 'pill.costWithSubs': 'Cost with subagents {value}',\n 'pill.scopeTag': 'with subagents',\n 'panel.title': 'Usage details',\n 'panel.openHint': 'click to open usage details',\n 'panel.tokens': '{value} tok',\n 'panel.hitRate': 'cache hit {value}',\n 'panel.self': 'This session',\n 'panel.subs': 'Subagents ×{count}',\n 'panel.byModel': 'By model',\n 'panel.unpriced': 'Unpriced model ×{count}',\n 'panel.unpricedNote': 'tokens only',\n 'quota.trigger': 'Provider quota',\n 'quota.triggerSummary': '{name} · {figure}',\n 'quota.triggerSummaryPooled': '{name} · {figure} (mean of {count} quota meters)',\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.other': 'Quota',\n 'quota.tier.balance': 'Balance',\n 'quota.tier.recharge': 'Topped-up balance',\n 'quota.tier.bonus': 'Granted 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.signedOut': 'Sign in to DeepSeek to view the account balance.',\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 navigation service (`ctx.uiWorkspace.pickDirectory`), the same\n * native directory picker the workspace flows use. Export discipline: the\n * /client entry exposes only what cordis loading needs.\n *\n * @module token-usage/client\n */\n\n// dsh-client-runtime is long gone; its ClientContext was a plain alias of\n// the cordis Context, so the type comes from cordis directly.\n// Type-only: pulls the ctx.slots declaration merge (owned by ui-renderer,\n// whose published types no longer re-declare it through ui-session).\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\n// Type-only: pulls ctx.uiWorkspace (directory picker) into this program.\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/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-sidebar SlotMap merge ('sidebar.panellist.actions',\n// dsh 0.2.1-rc.3+) into this program.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'\n// Type-only: pulls the ui-layout SlotMap merge ('main' keyed) and the\n// MainPanelId brand the layout service's selectPanel takes.\nimport type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface SlotMap {\n /**\n * A bundle's own configuration on the Plugins page, keyed by package name.\n */\n 'plugins.bundle.config': { kind: 'keyed'; scope: 'root'; owner: { readonly view: 'summary' | 'page' } }\n }\n}\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 type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { UiWorkspace } from '@deepseek-ai/dsh-client-ui-workspace/client'\nimport type { SessionId } from '@deepseek-ai/dsh-client-connection/client'\n\ninterface WorkspaceItemLike {\n readonly workspaceId: string\n readonly sessionIds: readonly SessionId[]\n}\n\ninterface WorkspaceSnapshotLike {\n readonly items: readonly WorkspaceItemLike[]\n readonly phase?: 'pending' | 'ready'\n}\n\ninterface WorkspacesLike {\n readonly list?: {\n getSnapshot(): WorkspaceSnapshotLike\n }\n}\nimport { CardForm, createFallbackTarget, type CardFormTarget, type SectionValue } from './card-form.ts'\nimport { CostPill } from './CostPill.tsx'\nimport { PanellistMoreEntry } from './PanellistMoreEntry.tsx'\nimport { PanellistPinEntry } from './PanellistPinEntry.tsx'\nimport { QuotaButton, type ModelSelectionSource } from './QuotaButton.tsx'\nimport { TokenUsageCard } from './TokenUsageCard.tsx'\nimport { TokenUsageSection } from './TokenUsageSection.tsx'\nimport { UsagePanelPage } from './UsagePanelPage.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/**\n * Main-panel id shared by the sidebar \"More\" menu row and the page it\n * opens. The `main` slot's key domain is open (keyed); the branded\n * assertion names the panel for the layout service's selectPanel.\n */\nconst USAGE_PANEL_ID = 'token-usage' as MainPanelId\n\n/**\n * Candidate keys under which the Host may serve this plugin's settings\n * form: the entry id (the namespace) first, the full package name as a\n * fallback for a host that keyed it by package instead.\n */\nconst CONFIG_FORM_KEYS = [TOKEN_USAGE_NS, '@laoyuehanni/dsh-token-usage'] as const\n\n/** Minimal describe-mirror face: the served namespaces, subscription, first read. */\ninterface DescribeMirrorLike {\n getSnapshot(): { view?: { namespaces?: ReadonlyArray<{ ns: string }> } }\n subscribe(listener: () => void): () => void\n ensure?(): Promise<void>\n}\n\n/** The `configForms` service face as this plugin consumes it. */\ninterface ConfigFormsLike {\n /** Entry-id keyed form controller; the host NEVER returns undefined. */\n get<T>(entryId: string): CardFormTarget<T>\n /** The shared describe mirror the forms derive from. */\n describe?(): DescribeMirrorLike | undefined\n}\n\n/**\n * Resolve the form target from the describe mirror's LIVE namespace list.\n * `ConfigForms.get()` unconditionally creates and caches a controller for\n * ANY key — it never returns undefined — so key validity must come from the\n * namespaces the mirror actually serves. A `get()` on a key the mirror does\n * not list yields a controller stuck at 'unavailable' forever, and the card\n * renders nothing. No view yet (mirror still loading) answers undefined so\n * the caller keeps its current target.\n */\nconst resolveConfigFormsTarget = (forms: ConfigFormsLike): CardFormTarget<SectionValue> | undefined => {\n const namespaces = typeof forms.describe === 'function'\n ? forms.describe()?.getSnapshot()?.view?.namespaces\n : undefined\n if (namespaces === undefined) return undefined\n const served = CONFIG_FORM_KEYS.find(key => namespaces.some(row => row.ns === key))\n return served === undefined ? undefined : forms.get<SectionValue>(served)\n}\n\n/** Required services: the slot registry, the locale dictionaries, the\n * workspace navigation service (its native directory picker backs the card's\n * browse button), and the session controller (the stats page's Ctrl+click\n * session jump reads the list and opens the target). The configuration\n * source (`configForms`) attaches dynamically. */\nexport const inject = ['slots', 'locale', 'connection', 'remote', 'uiWorkspace', 'sessions', '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 // The stats page's session jump: the pure predicate drives the Ctrl-hover\n // affordance (a session outside the controller's list — archived, or a\n // pre-install log row the list never saw — renders no dashed underline and\n // refuses the click), and the jump closes the settings panel and opens the\n // session via uiWorkspace.openSession.\n const getSessions = (): ISessions | undefined =>\n (ctx.get?.('sessions') as ISessions | undefined) ?? (ctx as unknown as { sessions?: ISessions }).sessions\n const getUiWorkspace = (): UiWorkspace | undefined =>\n (ctx.get?.('uiWorkspace') as UiWorkspace | undefined) ?? (ctx as unknown as { uiWorkspace?: UiWorkspace }).uiWorkspace\n const getWorkspaces = (): WorkspacesLike | undefined =>\n (ctx.get?.('workspaces') as WorkspacesLike | undefined) ?? (ctx as unknown as { workspaces?: WorkspacesLike }).workspaces\n\n const isSessionInController = (id: string): boolean => {\n const list = getSessions()?.list?.getSnapshot()\n return list?.byId?.[id as SessionId] !== undefined\n }\n\n const isWorkspaceAlive = (id: string): boolean => {\n const ws = getWorkspaces()?.list?.getSnapshot()\n if (!ws || ws.phase === 'pending') return true\n const sid = id as SessionId\n return ws.items.some(item => item.sessionIds.includes(sid))\n }\n\n const sessionListed = (id: string): boolean => {\n return isSessionInController(id) && isWorkspaceAlive(id)\n }\n\n const openSession = (id: string): { ok: boolean; reason?: 'workspaceDeleted' | 'sessionNotFound' } => {\n if (!isSessionInController(id)) return { ok: false, reason: 'sessionNotFound' }\n if (!isWorkspaceAlive(id)) return { ok: false, reason: 'workspaceDeleted' }\n getUiWorkspace()?.openSession(id as SessionId)\n return { ok: true }\n }\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 inject: () => ({ sessionListed, openSession }),\n }, TokenUsageSection))\n\n // The main panel the sidebar entries open (the `main` keyed slot, an older\n // shell declaration than the sidebar regions). It rides ctx.slots.inject\n // WAITING on the shell's declaration — a shell without it never runs the\n // callback, so the page degrades silently and the settings section above\n // stays the only entry. The layout seat is resolved at click time (dynamic\n // like configForms below, never a top-level inject dependency): the sidebar\n // entries open this panel, and the page's session jump returns to the\n // conversation. The two sidebar entries themselves (the More-menu row and\n // the resident pinned row) register further down in syncEntries — the two\n // are mutually exclusive, so their registrations come and go with the\n // `sidebarPinned` setting.\n const selectMainPanel = (id: MainPanelId | null): void => {\n ;(ctx.get?.('layout') as { selectPanel?: (id: MainPanelId | null) => void } | undefined)?.selectPanel?.(id)\n }\n ctx.slots.inject('main', () => ctx.slots.register({\n name: 'main',\n key: USAGE_PANEL_ID,\n locale: NS,\n inject: () => ({ sessionListed, openSession, returnToConversation: () => selectMainPanel(null) }),\n }, UsagePanelPage))\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 composer-dock usage pill: one entry of the\n // `conversation.composer.dock` slot list (`order: 10`, after the\n // official stats pills' `order: 0`), wearing the official pill skin so\n // the row reads as one family. The figure is the WITH-SUBAGENTS fold —\n // the one number no official surface carries; a solo session renders it\n // bare, and a subtree scope adds a quiet \"with subagents\" badge. The\n // click-open detail panel carries the folded token figure and cache-hit\n // rate (official pills show only the single-session token count), the\n // session / subagents split, and the per-model breakdown. The component\n // self-gates: a session with zero recorded requests renders nothing; a\n // transient fetch miss keeps the previous render.\n ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({\n name: 'conversation.composer.dock',\n id: 'token-usage-cost',\n order: 10,\n locale: NS,\n }, CostPill))\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 // Configuration source resolution: ctx.configForms provides the ConfigForm\n // (keyed by the entry id the describe mirror actually serves; see\n // resolveConfigFormsTarget). Before the service mounts, the placeholder\n // target keeps the card inert instead of throwing.\n const lookupCurrentTarget = (): CardFormTarget<SectionValue> | undefined => {\n const configForms = ctx.get('configForms') as ConfigFormsLike | undefined\n if (configForms && typeof configForms.get === 'function') {\n return resolveConfigFormsTarget(configForms)\n }\n return undefined\n }\n\n const initialTarget = lookupCurrentTarget()\n let activeTarget: CardFormTarget<SectionValue> = initialTarget ?? createFallbackTarget()\n const targetListeners = new Set<() => void>()\n let unsubActive: (() => void) | undefined = activeTarget.subscribe(() => {\n for (const listener of targetListeners) listener()\n })\n\n const switchTarget = (next: CardFormTarget<SectionValue>): void => {\n if (next === activeTarget) return\n unsubActive?.()\n activeTarget = next\n unsubActive = activeTarget.subscribe(() => {\n for (const listener of targetListeners) listener()\n })\n for (const listener of targetListeners) listener()\n }\n\n ctx.inject(['configForms'], (configCtx) => {\n configCtx.effect(() => {\n const forms = configCtx.get('configForms') as ConfigFormsLike | undefined\n if (!forms || typeof forms.get !== 'function') return () => {}\n // The describe mirror loads asynchronously (its first snapshot holds no\n // view), so besides resolving now, follow the mirror: the moment the\n // namespace appears — or the host re-keys it — re-resolve and bind.\n const mirror = typeof forms.describe === 'function' ? forms.describe() : undefined\n const resolve = (): void => {\n const target = resolveConfigFormsTarget(forms)\n if (target !== undefined) switchTarget(target)\n }\n resolve()\n void mirror?.ensure?.()\n const unsubscribe = mirror?.subscribe(() => { resolve() })\n return () => { unsubscribe?.() }\n }, 'token-usage: configForms dynamic target')\n })\n\n const dynamicTarget: CardFormTarget<SectionValue> = {\n getSnapshot: () => activeTarget.getSnapshot(),\n subscribe: (listener) => {\n targetListeners.add(listener)\n return () => { targetListeners.delete(listener) }\n },\n set: (field, value) => activeTarget.set(field, value),\n unset: (field) => activeTarget.unset(field),\n }\n\n // The two sidebar entries are mutually exclusive — exactly one exists at\n // any time. The `sidebarPinned` volatile setting picks which: while it\n // reads true the usage entry is a resident `sidebar.panellist` row, and the\n // More-menu row is gone; while it reads false the More-menu row is back and\n // the resident row is gone (the shell's pin store is in-memory, so\n // registration alone IS the durable pin — no shell API is driven). Both\n // registrations wait on their shell declarations via slots.inject (old\n // shells never run those callbacks, so the entry degrades silently to the\n // settings section); a rejected cell (a same-priority occupant) likewise\n // just means that entry stays absent.\n let residentDisposer: (() => void) | undefined\n let moreDisposer: (() => void) | undefined\n const syncEntries = (): void => {\n const pinned = activeTarget.getSnapshot().value?.sidebarPinned === true\n if (pinned && residentDisposer === undefined) {\n try {\n residentDisposer = ctx.slots.register({\n name: 'sidebar.panellist',\n id: USAGE_PANEL_ID,\n order: 50,\n locale: NS,\n label: () => t('nav.label'),\n }, PanellistPinEntry)\n } catch {\n residentDisposer = undefined\n }\n } else if (!pinned && residentDisposer !== undefined) {\n const dispose = residentDisposer\n residentDisposer = undefined\n dispose()\n }\n if (!pinned && moreDisposer === undefined) {\n try {\n moreDisposer = ctx.slots.register({\n name: 'sidebar.panellist.actions',\n id: 'token-usage-more',\n order: 50,\n locale: NS,\n inject: () => ({ openPanel: () => selectMainPanel(USAGE_PANEL_ID) }),\n }, PanellistMoreEntry)\n } catch {\n moreDisposer = undefined\n }\n } else if (pinned && moreDisposer !== undefined) {\n const dispose = moreDisposer\n moreDisposer = undefined\n dispose()\n }\n }\n ctx.slots.inject('sidebar.panellist', () => { syncEntries(); return () => {} })\n ctx.slots.inject('sidebar.panellist.actions', () => { syncEntries(); return () => {} })\n ctx.effect(() => {\n targetListeners.add(syncEntries)\n syncEntries()\n return () => {\n targetListeners.delete(syncEntries)\n if (residentDisposer !== undefined) {\n const dispose = residentDisposer\n residentDisposer = undefined\n dispose()\n }\n if (moreDisposer !== undefined) {\n const dispose = moreDisposer\n moreDisposer = undefined\n dispose()\n }\n }\n }, 'token-usage: sidebar entries sync')\n\n // The Plugins page dispatches keyed configuration for bundles through\n // `plugins.bundle.config` (keyed by the bundle's package name).\n const form = new CardForm(dynamicTarget)\n const store = form.bind()\n ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({\n name: 'plugins.bundle.config',\n key: '@laoyuehanni/dsh-token-usage',\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.get('uiWorkspace') as {\n pickDirectory?: () => Promise<string | null>\n } | undefined)?.pickDirectory?.() ?? Promise.resolve(null),\n }),\n }, TokenUsageCard))\n}\n"],"mappings":";;;;;;;;;;;EAgBA,MAAa,aAAa;;;EAI1B,MAAa,eAAe;EAC5B,MAAa,oBAAoB;EACjC,MAAa,oBAAoB;;EAiBjC,SAAgB,oBAAoB,KAAa,QAAmC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AAQ;IACV;IACA,IAAI,CAAC,UAAU,iBAAiB,KAAA,GAC9B,IAAI;KACF,eAAe,IAAI,MAAM,SAAS;MAChC,MAAM;MACN,IAAI;MACJ,OAAO;MACP,QAAQ;MACR,eAAe,EAAE,iBAAiB,gBAAgB,cAAc,EAAE;KACpE,GAAG,kBAAkB;IACvB,QAAQ;KACN,eAAe,KAAA;IACjB;SACK,IAAI,UAAU,iBAAiB,KAAA,GAAW;KAC/C,MAAM,UAAU;KAChB,eAAe,KAAA;KACf,QAAQ;IACV;GACF;GACA,IAAI,MAAM,OAAO,2BAA2B;IAAE,YAAY;IAAG,aAAa,CAAC;GAAE,CAAC;GAC9E,IAAI,MAAM,OAAO,mCAAmC;IAAE,YAAY;IAAG,aAAa,CAAC;GAAE,CAAC;GACtF,IAAI,aAAa;IACf,gBAAgB,IAAI,WAAW;IAC/B,YAAY;IACZ,aAAa;KACX,gBAAgB,OAAO,WAAW;KAClC,IAAI,qBAAqB,KAAA,GAAW;MAClC,MAAM,UAAU;MAChB,mBAAmB,KAAA;MACnB,QAAQ;KACV;KACA,IAAI,iBAAiB,KAAA,GAAW;MAC9B,MAAM,UAAU;MAChB,eAAe,KAAA;MACf,QAAQ;KACV;IACF;GACF,GAAG,mCAAmC;GAItC,MAAM,OAAO,IAAI,SAAS,aAAa;GACvC,MAAM,QAAQ,KAAK,KAAK;GACxB,IAAI,MAAM,OAAO,+BAA+B,IAAI,MAAM,SAAS;IACjE,MAAM;IACN,KAAK;IACL,QAAQ;IACR,eAAe;KACb,OAAO,EAAE,gBAAgB,MAAM;KAC/B,GAAG,KAAK,QAAQ;KAGhB,qBAAsB,IAAI,IAAI,aAAa,CAAC,EAE5B,gBAAgB,KAAK,QAAQ,QAAQ,IAAI;IAC3D;GACF,GAAG,cAAc,CAAC;EACpB"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["useState","useRef","useCallback","totalTokens","styles","useRef","useRef","createContext","useState","useRef","useContext","styles","shared","Tooltip","useId","useState","totalTokens","useRef","useCallback","REFRESH_DEBOUNCE_MS","PANEL_VIEWPORT_MARGIN","totalTokens","useRef","useState","useMemo","fetchSummary","useCallback","styles","MenuItemButton","IconGaugeOutlineRegular","IconGaugeOutlineRegular","useRef","useState","useCallback","styles","Tooltip","useState","useRef","css","useCallback","IconChevronDownOutlineMedium","useRef","useState","styles","useRef","useState","styles","useState","styles","list","totalTokens","styles","useState","useRef","useMemo","totalTokens","Tooltip","styles","styles","Tooltip","useId","useState","useRef","styles","bands","styles","totalTokens","styles","useRef","useState","useMemo","shared","Fragment","styles","useRef","useState","useCallback","Toast","IconWarningOutlineRegular","css","styles","Tooltip","useRef","useRef","useState","useMemo","styles","totalTokens"],"sources":["../src/wire.ts","../src/client/card-form.ts","../src/client/async-resource.ts","../src/client/day.ts","../src/provider-label.ts","../src/client/format.ts","../src/client/PricingStatus.tsx","../src/model-resolution.ts","../src/client/PricingDialog.tsx","../src/client/pricing-associations.ts","../src/client/PricingAssociations.tsx","../src/client/session-stats.ts","../src/client/use-color-scheme.ts","../src/client/cost-inflate-motion.ts","../src/client/cost-inflate.ts","../src/client/use-cost-inflate.ts","../src/client/CostPill.tsx","../src/client/PanellistMoreEntry.tsx","../src/client/PanellistPinEntry.tsx","../src/client/quota-format.ts","../src/client/QuotaButton.tsx","../src/client/TokenUsageCard.tsx","../src/client/DateRangePicker.tsx","../src/client/MenuSelect.tsx","../src/client/OverheadRows.tsx","../src/project-rows.ts","../src/client/UsageRows.tsx","../src/client/DashboardCards.tsx","../src/client/StatCard.tsx","../src/client/trend-chart/axis.ts","../src/client/trend-chart/path.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/HitRateText.tsx","../src/client/OverviewBoard.tsx","../src/client/pricing-search.ts","../src/client/PricingOverviewDialog.tsx","../src/client/TokenUsageSection.tsx","../src/client/UsagePanelPage.tsx","../src/client/RequestPool.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 { AuxKind, UsageRecord } from './usage-record.ts'\nimport type { CompactionAttributionItem } from './compaction-attribution.ts'\n\nexport type { AuxKind, UsageFields, UsageRecord } from './usage-record.ts'\nexport type { CompactionAttributionItem, CompactionSourceKind } from './compaction-attribution.ts'\n\n/** The stats endpoint path, served by the host half's webServer route. */\nexport const STATS_PATH = '/token-usage/stats'\n\n/** The pricing-overview endpoint path: the full cloud-mirror model list,\n * filter-free by design — the overview is not a filtered usage view. */\nexport const PRICING_PATH = '/token-usage/pricing'\nexport const PRICING_SYNC_PATH = '/token-usage/pricing-sync'\nexport const ASSOCIATIONS_PATH = '/token-usage/pricing-associations'\n\n/** Returned only after a validated pricing mirror has been saved. */\nexport interface PricingSyncResult {\n version: number\n updatedAt: number\n models: number\n aliasPatterns: number\n usdExchangeRate: number\n}\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 + read + 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; removed: number; failedSessions: number }\n | { status: 'done'; processed: number; total: number; added: number; skipped: number; removed: number; failedSessions: number }\n | { status: 'failed'; error: string }\n\n/** Aggregated token counts over one group of records. */\nexport interface UsageTotals {\n /** Number of recorded provider-billed calls: plain requests plus\n * compaction summarize requests (records without provider usage count\n * here). Failed requests never join this count — see {@link failures}. */\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 /** Compaction summarize requests in this group; absent on legacy rollups\n * (reads as 0). Plain requests = `requests - (compactions ?? 0)`. */\n compactions?: number\n /** Failed model requests in this group (`turn/end` LLM errors plus\n * `llm/retry` scheduled after a failed attempt); absent on legacy\n * rollups and pre-failure shapes (reads as 0). Success rate =\n * requests / (requests + failures) is attempt-level, not turn-level. */\n failures?: number\n /** Failure counts by the provider-neutral `LlmFailure.code`\n * (`{ RATE_LIMIT: 16, TRANSPORT: 2, … }`); absent when the\n * group holds no failures or the shape predates the key (reads as an\n * empty map). Sums to `failures` when present. Codes are an open set:\n * unknown future codes read verbatim. */\n failuresByCode?: Record<string, number>\n /** Internal accumulators behind the model card's performance view: the\n * streaming samples' tokens-per-second and first-token-latency sums with\n * their count, plus the end-to-end latency sum and valid timing count.\n * Requests without timing never contribute to a performance mean.\n * Absent on legacy rollups and\n * pre-timing shapes (reads as no samples) — the means are derived at the\n * cost layer, never stored. Timing figures follow the records' own\n * `latencyMs` / `firstTokenLatencyMs`; a streaming sample is one whose\n * generation span (latency − first token) reached the recorder's\n * streaming threshold, so non-streaming one-shot responses never poison\n * the speed mean. */\n perfStreamTpsSum?: number\n perfStreamFirstMsSum?: number\n perfStreamCount?: number\n perfLatencyMsSum?: number\n perfLatencyCount?: number\n}\n\n/** Per-model performance means the model card's performance view renders.\n * Derived at the cost layer from the totals' timing accumulators — never\n * persisted itself, so a filter/merge re-derivation stays exact. */\nexport interface ModelPerf {\n /** Mean output speed over the streaming samples, tokens per second. */\n tokensPerSec: number\n /** Mean first-token latency over the same streaming samples, ms. */\n firstTokenMs: number\n /** Mean end-to-end latency over successful requests with valid timing, ms. */\n latencyMs: number\n /** Successful requests with valid latency; untimed requests are excluded. */\n timedRequests: number\n /** Streaming sample count the speed/first-token means fold from; below\n * {@link MIN_PERF_SAMPLES} the row reads 「样本不足」 instead of a full\n * figures cell. */\n samples: number\n}\n\n/** Smallest streaming sample count a performance figures cell trusts; below\n * it the row still shows its mean speed but annotated 「样本不足」. */\nexport const MIN_PERF_SAMPLES = 5\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 costState?: CostState\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/**\n * One per-provider aggregation row, keyed by the route key (`provider`) the\n * records carried. `''` is the unattributed group — pre-field history and\n * auxiliary rows whose route never landed in a session log. It is listed as\n * its own row (never folded into a named provider, never dropped), so the\n * dimension's totals reconcile with the top line.\n */\nexport interface UsageProviderRow {\n /** Route key; `''` groups every unattributed record. */\n provider: 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 /** ISO weekdays (1=Monday … 7=Sunday) the slot applies to, as validated at\n * coercion; absent or empty = every day. */\n daysOfWeek?: number[]\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.\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 pricing table: model id → full rule set, loaded from\n * `<data dir>/pricing.ccsa.json` (the cloud mirror; 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\nexport type CostState = 'ready' | 'pricing-unavailable' | 'history-incomplete'\nexport type PricingUnavailableReason = 'missing' | 'unreadable' | 'invalid-json' | 'invalid-feed'\nexport type AssociationStorageError = 'unreadable' | 'invalid-json' | 'invalid-file'\n\nexport interface PricingAssociation {\n sourceModel: string\n targetModelId: string\n}\n\nexport interface PricingAssociationStatus extends PricingAssociation {\n state: 'active' | 'automatic-takeover' | 'target-missing' | 'pricing-unavailable'\n resolvedTargetModelId?: string\n automaticModelId?: string\n targetDiffers?: boolean\n}\n\nexport interface PricingAssociationsPayload {\n feedVersion?: number\n directoryToken: string\n revision: number | null\n storageState: 'ready' | 'unavailable'\n storageError?: AssociationStorageError\n pricingAvailable: boolean\n pricingUnavailableReason?: PricingUnavailableReason\n writesPaused: boolean\n associations: PricingAssociationStatus[]\n resolution?: ModelResolution\n}\n\nexport interface SavePricingAssociation extends PricingAssociation {\n revision: number\n directoryToken: string\n}\n\nexport interface DeletePricingAssociation {\n sourceModel: string\n revision: number\n directoryToken: string\n}\n\nexport interface ModelResolution {\n rawName: string\n status: 'matched' | 'unmatched' | 'ambiguous'\n modelId?: string\n method?: 'id' | 'normalized-id' | 'pattern' | 'manual'\n strippedPrefix: boolean\n candidates: string[]\n association?: PricingAssociationStatus\n /** Preserves the unmatched/ambiguous reason when a manual choice is active. */\n automatic?: ModelResolution\n}\n\n/**\n * One model row of the pricing overview: the shape the cloud feed carries\n * (modelId + alias patterns + upstream family) plus the full rule set.\n * The overview keeps one row per model rather than enumerating aliases.\n */\nexport interface PricingOverviewModel {\n modelId: string\n /** Validated full-name regexes; empty when the feed carries none. */\n aliasPatterns: readonly string[]\n /** The feed's upstream family grouping; absent rows group under `other`. */\n family?: string\n rules: ModelRates\n}\n\n/** The payload served at {@link PRICING_PATH}: every cloud-mirror model row\n * plus the display-currency stamps the settings page converts with (same\n * region source as the stats payload). */\nexport interface PricingOverviewPayload {\n feedVersion?: number\n pricingUnavailableReason?: PricingUnavailableReason\n costState?: CostState\n models: readonly PricingOverviewModel[]\n /** The display currency the page converts rate figures into. Amounts on\n * the wire (rules 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}\n\n/** One per-day × per-model × per-rate × per-provider aggregation row. The\n * route re-aggregates any filter from these cells and re-prices history\n * under the current table; `provider` is the route key the record carried\n * (absent/empty = pre-field history that could not be attributed). */\nexport interface UsageRateRow {\n day: string\n model: string\n rate: RateKey\n /** Route key of the requests in this cell; absent when unattributed. */\n provider?: string\n totals: UsageTotals\n}\n\n/**\n * One per-(kind, day, model, rate) aggregation row of the auxiliary (bypass)\n * model requests: Auto review, session-title generation, and translation.\n * These calls are not part of any conversation turn. The auxiliary dimension\n * intentionally stays keyed only by kind/day/model/rate even when a newer\n * host supplies an owning session id; that keeps the settings page's\n * \"runtime overhead\" breakdown independent of the per-session table. They\n * still fold into `rateRows` / `byModel` / the totals as provider-billed\n * requests of a concrete model.\n */\nexport interface UsageAuxRow {\n /** Which bypass call produced the rows folded into this cell. */\n auxKind: AuxKind\n day: string\n model: string\n rate: RateKey\n totals: UsageTotals\n}\n\n/** One per-model row nested under an auxiliary kind: the model's share of one\n * bypass-request kind, keyed by the canonical id (a priced alias family folds\n * onto its modelId, unpriced names keep their spelling). The runtime-overhead\n * tab renders these one line each beneath their kind's aggregate row. */\nexport interface UsageAuxModelRow {\n model: string\n totals: UsageTotals\n /** Billed cost (¥) of this model's requests of the kind; 0 when unpriced. */\n cost: number\n}\n\n/** One per-kind aggregate of the auxiliary requests, priced at the rate\n * identities its cells resolved through. */\nexport interface UsageAuxKindRow {\n auxKind: AuxKind\n totals: UsageTotals\n /** Billed cost (¥) of this kind; 0 when its model is unpriced. */\n cost: number\n /** Per-model rows of this kind, request-count descending then model name. */\n byModel: UsageAuxModelRow[]\n}\n\n/**\n * The auxiliary-request layer of the stats payload: the settings page's\n * \"runtime overhead\" block renders the per-kind rows, and the total reconciles\n * with the share of the top-line totals those bypass calls contributed.\n */\nexport interface AuxSummary {\n /** Totals over every recorded auxiliary request. */\n total: UsageTotals\n /** Billed cost (¥) of the auxiliary requests under the current table. */\n cost: number\n /** Per-kind rows in the fixed display order, kinds without data omitted. */\n byKind: UsageAuxKindRow[]\n}\n\n/**\n * One per-session × per-day × per-model × per-rate aggregation row: the\n * session dimension the settings page's cross-session table folds from.\n * Every granule pulls its weight — a session usually spans days (the day\n * key keeps a date-filtered row to the window's share), the model key keeps\n * a model-filtered row honest, the rate identity keeps cost re-pricing\n * free, and `lastTime` sorts the table by recent activity. Failure rows\n * (`model === ''`) fold in like every other record: the session dimension\n * keeps the same totals semantics as rateRows, so request counts reconcile.\n */\nexport interface UsageSessionRow {\n sessionId: string\n day: string\n model: string\n rate: RateKey\n /** Route key of the requests in this cell; absent when unattributed.\n * Keeps the session dimension at the same granule width rateRows carry,\n * so a session-scoped read rebuilds the provider dimension from cells. */\n provider?: string\n /** Newest record time folded into this cell (max over the fold); the\n * session table's \"last active\" column. */\n lastTime: number\n totals: UsageTotals\n}\n\n/**\n * One final row of the settings page's session table: the server-side fold\n * of {@link UsageSessionRow} cells over one top-level session plus its\n * whole subtree, sorted by cost and truncated top-N before it crosses the\n * wire. Subagents never surface as rows of their own — the row's\n * `childCount` badge is their only visibility here. Identity fields ride\n * in the row — the server folds, sorts, and truncates, so the client never\n * reassembles titles or directories.\n */\nexport interface SessionUsageRow {\n sessionId: string\n /** Log-backed latest-wins title; omitted when no `session/title` event\n * ever landed (the client falls back to a short session id + times). */\n title?: string\n /** The session header's working directory, verbatim; omitted when the\n * header carried none. The client derives the tail segment and grouping. */\n cwd?: string\n /** How many descendant sessions folded into this row (the subagent\n * badge); omitted when the subtree holds none. */\n childCount?: number\n totals: UsageTotals\n /** Billed cost (¥) over the row's cells under the current table. */\n cost: number\n /** Start of the local day of the row's earliest cell — the fallback\n * identity's \"from\" bound (day granularity; titles cover the rest). */\n firstTime: number\n /** Newest record time in the row (max over every folded cell). */\n lastTime: number\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-provider rows (route key → totals; `''` = unattributed), descending\n * by request count. Rebuilt from the same granules rateRows carry. */\n byProvider: UsageProviderRow[]\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 /** Per-(kind, day, model, rate) rows of the auxiliary bypass requests\n * (Auto review / session title / translation / other). Their usage also\n * folds into the totals, byDay, byHour, byModel, rateRows, and recent\n * window; this dimension only backs the runtime-overhead breakdown.\n * A summary read without raw history carries an empty list. */\n auxRows: UsageAuxRow[]\n /** Per-session × per-day × per-model × per-rate rows, session then day\n * then model then rate ascending; the settings page's session table folds\n * from these (see {@link UsageSessionRow}). */\n bySession: UsageSessionRow[]\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; perf?: ModelPerf }\n\n/** A per-provider row carrying its billed cost (¥), folded from the rate\n * rows that carry the same provider key; the unattributed group keeps its\n * own row so the provider table's cost column reconciles with the summary\n * card for free. */\nexport type CostedProviderRow = UsageProviderRow & { cost: number }\n\n/** A per-session aggregation cell carrying its billed cost (¥); 0 when the\n * model is unpriced — priced from the same rate identity the per-model cost\n * folds from, so the session table's cost column reconciles with the\n * summary card for free. */\nexport type CostedSessionCell = UsageSessionRow & { cost: number }\n\n/** One project fold over all root-session rows, before the session list's\n * top-N cut. Directory tails remain the display grouping key. */\nexport interface ProjectUsageRow {\n name: string\n cwd?: string\n sessionCount: number\n totals: UsageTotals\n cost: number\n}\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 feedVersion?: number\n associationStorageError?: AssociationStorageError\n pricingUnavailableReason?: PricingUnavailableReason\n costState: CostState\n modelResolutions: ModelResolution[]\n /** Absolute data directory the summary was computed from. */\n dataDir: string\n /** Billed cost (¥); unpriced models count 0. Trust only when costState is ready. */\n totalCost: number\n /** Models with usage but no entry in the pricing table, byModel order. */\n unpricedModels: string[]\n /** The snapshot pricing dictionary, including resolved names for details. */\n pricing: PricingTable\n /** Per-model rows with their billed cost attached. */\n byModel: CostedModelRow[]\n /** Per-provider rows with their billed cost attached (see\n * {@link CostedProviderRow}); the unattributed group (`''`) included. */\n byProvider: CostedProviderRow[]\n /** Per-session cells with their billed cost attached (see\n * {@link CostedSessionCell}); the route folds these into\n * {@link SessionUsageRow}s for the session table. */\n bySession: CostedSessionCell[]\n /** The auxiliary (bypass) request layer: the settings page's runtime-overhead\n * block. Its usage is already included in the totals above; this field only\n * splits it out by kind and prices it for display. */\n aux: AuxSummary\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. The session table reads\n * `sessionRows` — the server-side folded, sorted, truncated final\n * rows (always folded over subagent subtrees); the granular\n * `bySession` cells stay behind the route (sending them would only\n * duplicate the fold on the wire).\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 except the\n * granular `bySession` (stripped from the wire) plus the\n * display-currency metadata, so a consumer can read `total` /\n * `totalCost` / `pricing` without narrowing first.\n */\ntype CostedSummaryWire = Omit<CostedSummary, 'bySession'>\nexport type StatsPayload = (CostedSummaryWire & {\n scope: 'whole'\n /** The session table's final rows: folded over subagent subtrees,\n * cost-sorted, top-N truncated, metadata attached. */\n sessionRows: readonly SessionUsageRow[]\n /** Complete project aggregates, independent of the session top-N cut. */\n projectRows: readonly ProjectUsageRow[]\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 /** Route key → latest display name for the provider dimension; absent\n * when the host has no registry seam (the client falls back to keys). */\n providerNames?: Readonly<Record<string, string>>\n}) | (CostedSummaryWire & {\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 /** Route key → latest display name for the provider dimension; absent\n * when the host has no registry seam (the client falls back to keys). */\n providerNames?: Readonly<Record<string, string>>\n /** Direct-child breakdown keyed by child id, when the request named `childId`. */\n children?: Readonly<Record<string, ChildUsageSummary>>\n})\n\n/**\n * 会话用量页「最新请求 / 实时请求」区的请求池上限。池包含顶部最新一条与\n * 下方最多 19 条历史;上限只约束展示,从不截断日志、汇总或趋势。\n */\nexport const REQUEST_POOL_LIMIT = 20\n\n/** 一次 provider 请求尝试的生命周期状态。`interrupted` 是取消时已交付部分\n * 用量的结算(宿主 `assistant/message` 的 `interrupted` 事实);`cancelled`\n * 是未结算任何用量的取消。 */\nexport type RequestDetailState = 'waiting' | 'streaming' | 'completed' | 'failed' | 'cancelled' | 'interrupted'\n\n/**\n * 「缓存过低」标签的低命中启发式为何不适用于该请求。稳定枚举值,客户端\n * 本地化;绝不携带 prompt 或正文。优先级即评估顺序:状态排除 → 数据有效性\n * → 序列排除 → 输入资格。\n * - `cold-start`:该会话的首条请求(全量记录序列判定,不看 20 条窗口行号)。\n * - `model-switch`:同会话相邻前一条请求的模型不同(切回旧模型同样保守排除)。\n * - `in-flight`:等待首 token 或生成中,尚未完成。\n * - `not-success`:失败 / 取消 / 中断,终态并非成功完成。\n * - `compaction`:压缩 summarize 请求,输入特征特殊,不做性能诊断。\n * - `auxiliary`:已归属会话的辅助请求(如标题生成 / 审查),用途开销\n * 与主请求不同,不做缓存性能诊断。\n * - `cache-unreported`:provider 未显式报告缓存读(缺失不当 0%)。\n * - `insufficient-input`:输入不满足该路由的缓存条件(按适配语义推导)。\n * - `invalid-data`:分母为零、负值、NaN/Infinity 或计数矛盾。\n */\nexport type RequestCacheExclusion =\n | 'cold-start'\n | 'model-switch'\n | 'in-flight'\n | 'not-success'\n | 'compaction'\n | 'auxiliary'\n | 'cache-unreported'\n | 'insufficient-input'\n | 'invalid-data'\n\n/** 单次请求的缓存命中评估。`rate` 是原始精度 [0,1](绝不传格式化字符串);\n * band 是请求区域专用的三档策略(<50% loss / <80% low / 其余 normal),\n * 排除与未知分别落 `excluded` / `unknown`,不改全局色阶。 */\nexport interface RequestDetailCache {\n rate?: number\n /** Whether valid reported data is available, not a provider allowlist. */\n eligibility: 'eligible' | 'ineligible' | 'unknown'\n band: 'normal' | 'low' | 'loss' | 'excluded' | 'unknown'\n reason?: RequestCacheExclusion\n}\n\n/** 一次真实 provider 请求尝试的展示明细:会话用量页请求池的一行。列表单位\n * 是「一次尝试」,不是一条消息或一个 turn;自动重试的失败尝试与重试成功的\n * 尝试各自成行。运行态与持久化记录原位合并(`durableRequestId` 关联),\n * 终态不被迟到的进度降级。 */\nexport interface RequestDetailView {\n /** 一次真实尝试的稳定 UI 身份(process epoch + session + turn/step +\n * attempt,或持久化 request id),从不用数组下标。 */\n id: string\n /** 对应持久化 UsageRecord 的 request id;合并锚点,缺失时该行只存在于\n * 运行态。 */\n durableRequestId?: string\n sessionId: string\n state: RequestDetailState\n kind: 'request' | 'compaction' | 'failure' | 'aux'\n /** Auxiliary subtype when the host proved this request belongs to the\n * current session (for example `session-title`). */\n auxKind?: AuxKind\n /** Plain-request rows only: the compaction events (prune clusters and\n * summaries) that landed since the session's previous plain request — the\n * hit-cell tooltip's rewrite explanation. Annotation only: it never enters\n * {@link RequestDetailCache} or moves any cache band. Absent on legacy\n * rows and unattributed requests. */\n compactionAttribution?: readonly CompactionAttributionItem[]\n /** Canonical model id after the pricing table's alias / regex resolution. */\n modelId?: string\n /** 请求路由的模型(计费身份)。 */\n requestedModel: string\n /** provider 实际响应的模型(别名路由可不同);缺失时以请求模型展示。 */\n responseModel?: string\n /** 实时观察到的尝试开始时刻(epoch ms);历史行缺失。 */\n startedAt?: number\n /** 实时观察到的结算时刻(epoch ms);历史行缺失。 */\n settledAt?: number\n /** 持久化记录的会话事件时间;旧记录只有它时保留其原义(非启动时刻)。 */\n recordTime?: number\n /** 展示排序锚点:实时行取 startedAt,历史行取 recordTime。 */\n orderAt: number\n orderBasis: 'start' | 'record'\n /** 未缓存输入 token;绝不改写成总 prompt。 */\n inputTokens?: number\n outputTokens?: number\n /** 缓存读;显式 0 保留为 0,未报告时缺失(与 0 严格区分)。 */\n cacheReadTokens?: number\n cacheWriteTokens?: number\n /** 请求发出至结算的耗时(成功/失败尝试的独立计时;step 级历史计时时为\n * 该记录的原口径)。 */\n latencyMs?: number\n /** 首个非空模型增量(含推理/工具参数)距开始的毫秒;整包返回或缺失时无。 */\n firstTokenLatencyMs?: number\n /** 运行中请求的已耗时,锚定服务端快照(asOf - startedAt),客户端不跑秒表。 */\n elapsedMs?: number\n /** 结算后的单次解码速度(tokens/s,服务端按生成时长 ≥500ms 的可信流式\n * 样本门计算);整包返回、output 为 0、计时无效或缺失时缺失——客户端\n * 绝不用会话均值、字符数或 chunk 数补位。 */\n speed?: number\n /** 失败行 provider 中立的失败码(LlmFailure.code)。 */\n failureCode?: string\n /** 本请求计费(¥,wire 币种不变);未定价时缺失。 */\n cost?: number\n pricingStatus: 'priced' | 'unpriced' | 'unknown'\n cache: RequestDetailCache\n}\n\n/**\n * 会话级对话状态:最新一轮 turn 的收尾情况。它描述「对话现在走到哪了」,\n * 而不是某一次请求的生命周期。\n * - `awaiting-tool`:模型已发起工具调用、结果尚未回来(对话未完,正在等工具)。\n * - `turn-complete`:本轮 turn 已正常结束且没有待返回的工具结果(本轮对话已完成)。\n * - `retrying`:上一次请求失败,系统正在退避后重试(对话未完,还在重试)。\n */\nexport type ConversationState = 'awaiting-tool' | 'turn-complete' | 'retrying'\n\n/**\n * 会话级对话状态及其细节。状态是稳定枚举,细节只带计数与失败码这类\n * 无载荷事实,绝不携带 prompt 或正文。\n */\nexport interface ConversationStatus {\n state: ConversationState\n /** 仅 `retrying`:第几次重试、共几次、退避时长与失败码。 */\n retry?: {\n count: number\n max: number\n delayMs: number\n code?: string\n }\n}\n\n/** 会话用量页请求池快照:已按范围过滤、去重后选取的最多 20 条请求。\n * `items[0]` 优先取当前范围最新发起的活动请求(waiting / streaming),\n * 无活动请求时取最新发起的一条;选取在截断前完成。\n * `items.slice(1)` 按开始时间倒序,且不重复顶部请求。\n * `activeCount` 是当前范围全部进行中的请求数,可能超过展示窗。 */\nexport interface SessionRequestDetails {\n items: readonly RequestDetailView[]\n limit: number\n /** 本次快照的服务端时间(epoch ms),不是请求发起时间。 */\n asOf: number\n activeCount: number\n /** 实时能力档位:`lifecycle` = 可见等待/生成中生命周期与完成后可信单次\n * 速度;`token-progress` = 另有生成中可信累计 token 计数(当前协议无此\n * 路由,运行中行恒无 token/速度);`settled-only` = 仅结算记录。 */\n liveCapability: 'lifecycle' | 'token-progress' | 'settled-only'\n /** 头条请求(`items[0]`)所属会话的对话状态;缺失表示没有结论(本轮仍在\n * 进行中,或插件进程尚未观察到该会话的事件)。 */\n conversation?: ConversationStatus\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 Omit<CostedSummary, 'bySession'> {\n currency: DisplayCurrency\n usdExchangeRate: number\n /** Route key → latest display name from the data directory's\n * `providers.json` registry; a key with no entry (or a missing registry)\n * displays as the key itself. Absent on older host payloads. */\n providerNames?: Readonly<Record<string, string>>\n /** Whole-scope payloads only: the settings page's session table rows\n * (see {@link SessionUsageRow}); absent on session-scoped reads. */\n sessionRows?: readonly SessionUsageRow[]\n /** Whole-scope complete projects; absent on older host payloads. */\n projectRows?: readonly ProjectUsageRow[]\n requestSeries?: readonly RequestPoint[]\n children?: Readonly<Record<string, ChildUsageSummary>>\n sessionIds?: readonly string[]\n /** Session-scoped `fields=session` reads only: the live request pool\n * (最新请求 / 实时请求). Absent on `chip` and whole-log `full` reads —\n * the pool is the usage tab's view, never a settings-page concern. */\n requestDetails?: SessionRequestDetails\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. `other` carries a window whose name fits no known period (a\n * gateway's open window vocabulary: \"Credits\", \"Allowance\") — display\n * leans on {@link QuotaWindow.name}, and only the granularity rank treats\n * it generically. Display adapts by tier (progress bar vs amount). */\nexport type QuotaTier = 'five_hour' | 'weekly' | 'monthly' | 'other' | '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 /** Which DeepSeek account purse a balance window came from. Absent on\n * API-key balances, which stay a single unlabeled amount. */\n balanceKind?: 'recharge' | 'bonus'\n /** The vendor's own name of the window (\"Credits\", \"Allowance\"), when it\n * fits no known period tier; the panel's column label prefers it over\n * the generic `other` copy. Absent on windows a tier already names. */\n name?: string\n /** The quota CARD a window belongs to when one payload aggregates\n * several (a gateway summarizing its whole upstream fleet): the card's\n * display title (vendor · plan · account), which the panel renders as a\n * section heading. Absent on single-source payloads. */\n card?: string\n /** The quota POOL a window belongs to: windows sharing a pool draw on\n * interchangeable budgets of ONE vendor family (a gateway's several keys\n * of the same account family, each with its own meter but serving the\n * same traffic). Only same-pool windows may be pooled into one water\n * level — two vendors' same-named windows are not the same budget.\n * Absent on single-source payloads (nothing to pool). */\n pool?: string\n}\n\n/** Why a quota query failed, normalized so the panel can pick friendly copy. */\nexport type QuotaErrorKind = 'auth' | 'no-credential' | 'signed-out' | '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 { DirectoryGuardView } from '../wire.ts'\nimport { DIR_GUARD_PATH, MIGRATION_PATH } from '../wire.ts'\n\n/**\n * Minimal snapshot contract of a configuration form (the host's\n * ConfigFormSnapshot shape, as this package consumes it).\n */\nexport interface CardFormTargetSnapshot<T = SectionValue> {\n /** Loading, ready, or unavailable state. */\n status: 'loading' | 'ready' | 'unavailable'\n /** Resolved section value. */\n value?: T\n /** Raw user override layer, if present. */\n user?: unknown\n /** Whether the scope accepts writes. */\n writable: boolean\n}\n\n/**\n * The configuration source backing the card: the host's `ConfigForm<T>` for\n * the `token-usage` namespace.\n */\nexport interface CardFormTarget<T = SectionValue> {\n /** Current snapshot view. */\n getSnapshot(): CardFormTargetSnapshot<T>\n /** Subscribe to snapshot changes. Returns disposer. */\n subscribe(listener: () => void): () => void\n /** Write one scalar field. */\n set(field: string, value: unknown): Promise<boolean>\n /** Clear one scalar field back to inherited configuration. */\n unset(field: string): Promise<boolean>\n}\n\n/** Placeholder target while the configForms service has not mounted (or its\n * describe mirror does not serve this namespace yet); the card renders\n * nothing and never throws. */\nexport function createFallbackTarget(): CardFormTarget<SectionValue> {\n return {\n getSnapshot: () => ({\n status: 'unavailable',\n writable: false,\n }),\n subscribe: () => () => {},\n set: async () => false,\n unset: async () => false,\n }\n}\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 sidebarPinned?: boolean\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 /** Whether the usage entry is pinned as a resident sidebar row: the\n * effective (resolved) value the checkbox shows when untouched. */\n sidebarPinned: boolean\n /** Staged pin toggle; undefined while untouched. A staged edit shows in\n * the checkbox and commits only on save. */\n pinnedDraft: boolean | undefined\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 TEXT field holds an unsaved edit. The pricing-sync gate reads\n * this, not `dirty`: the staged pin toggle has no say over the pricing\n * source, so it must not block a sync. */\n textDirty: 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 the sidebar-pin toggle; it commits only on save. */\n editPinned: (value: boolean) => 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 /** Staged sidebar-pin toggle; undefined while untouched. */\n private draftPinned: boolean | undefined\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 target - the configuration source backing the card (a ConfigForm).\n */\n constructor(private readonly target: CardFormTarget<SectionValue>) {\n this.snapshotValue = this.project()\n target.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 editPinned: (value) => {\n this.draftPinned = value\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.draftPinned === undefined && !this.failed) return\n this.drafts = {}\n this.draftPinned = undefined\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 // The staged pin toggle rides the same save; it writes an explicit\n // true/false (never unset) so a composition-layer `true` can still be\n // switched off from the card.\n const pinEdit = this.draftPinned\n if ((edited.length === 0 && pinEdit === undefined) || 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.target.unset(field)\n else await this.target.set(field, text)\n }\n if (pinEdit !== undefined) await this.target.set('sidebarPinned', pinEdit)\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 if (pinEdit !== undefined && this.storedValue('sidebarPinned') !== pinEdit) landed = false\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 this.draftPinned = undefined\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(): CardFormTargetSnapshot<SectionValue> {\n return this.target.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: string): 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 pinnedEffective = snapshot.value?.sidebarPinned === true\n const fields = {} as Record<CardField, string>\n const overridden = {} as Record<CardField, boolean>\n let textDirty = 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 textDirty = true\n }\n }\n return {\n available: snapshot.status === 'ready',\n writable: snapshot.writable,\n sidebarPinned: pinnedEffective,\n pinnedDraft: this.draftPinned,\n fields,\n overridden,\n dirty: textDirty || (this.draftPinned !== undefined && this.draftPinned !== pinnedEffective),\n textDirty,\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.scopeKey - the data range the on-screen snapshot belongs\n * to (e.g. the scoped session ids). A snapshot is only kept WITHIN the\n * range that produced it: while a new range's fetch is in flight the old\n * figures stay on screen (no flash), but if that fetch FAILS the kept value\n * belongs to another range — the hook lands in `error` instead of showing\n * the old range's rows as if they were the current one's. Same-key refresh\n * failures keep the silent semantics.\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; scopeKey?: string },\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 // The kept snapshot belongs to the range captured by its own request.\n const valueScopeRef = useRef(options.scopeKey)\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 // Capture the range for this request. A later render may switch scope\n // while the fetch is pending; its result must never be attributed to the\n // newer range through a mutable ref.\n const requestScope = options.scopeKey\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. A range switch keeps the old figures visible\n // while the new range's fetch runs — and silently drops them if that\n // fetch fails (see the catch below).\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 valueScopeRef.current = requestScope\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 — but\n // only data of the range on screen. Another range's snapshot would\n // misattribute its rows (and its stale stamp) to the new range.\n if (silent && loadedRef.current && valueScopeRef.current === requestScope) 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, options.scopeKey])\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 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/** A month the calendar panel shows (month is 0-based like Date). */\nexport interface MonthView {\n year: number\n month: number\n}\n\n/** The month view holding one day key. */\nexport function monthViewOf(dayKey: string): MonthView {\n return { year: Number(dayKey.slice(0, 4)), month: Number(dayKey.slice(5, 7)) - 1 }\n}\n\n/** The month view shifted by whole months (year overflow normalized). */\nexport function shiftMonth(view: MonthView, deltaMonths: number): MonthView {\n const total = view.year * 12 + view.month + deltaMonths\n return { year: Math.floor(total / 12), month: ((total % 12) + 12) % 12 }\n}\n\n/** One cell of a month grid: a day key plus whether it belongs to the shown month. */\nexport interface MonthCell {\n day: string\n inMonth: boolean\n}\n\n/**\n * The month grid of one month view: Monday-first whole weeks covering the\n * month, so every column aligns under its weekday header. Days of the\n * neighbouring months carry `inMonth: false` — the caller renders them as\n * blank placeholders, keeping the shown month's date texts unique (for\n * tests and screen readers).\n */\nexport function monthGrid(view: MonthView): MonthCell[] {\n // Local-time constructors only: string parsing would drag UTC offsets in.\n const leading = (new Date(view.year, view.month, 1).getDay() + 6) % 7\n const daysInMonth = new Date(view.year, view.month + 1, 0).getDate()\n const total = Math.ceil((leading + daysInMonth) / 7) * 7\n const cells: MonthCell[] = []\n for (let index = 0; index < total; index++) {\n const cursor = new Date(view.year, view.month, 1 - leading + index)\n cells.push({\n day: dayKeyOf(cursor),\n inMonth: cursor.getFullYear() === view.year && cursor.getMonth() === view.month,\n })\n }\n return cells\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 * The provider display-label rule, shared by the host side and the browser\n * side. It is a pure function with no IO, so both halves can import it\n * without dragging a registry along.\n *\n * @module token-usage/provider-label\n */\n\n/** Route key → latest display name. Absent keys are not stored as empty strings. */\nexport type ProviderNameIndex = Record<string, string>\n\n/**\n * Label for a route key. The name registry wins; a missing or empty entry\n * falls back to the key itself, so a route the registry never saw still\n * displays. A route without a name is not an error — the registry is a\n * convenience, the route key is the identity.\n * @param id - the route key.\n * @param names - the name registry, when the caller has one.\n * @returns the display name, or the route key itself.\n */\nexport function providerLabel(id: string, names?: Readonly<ProviderNameIndex>): string {\n const name = names?.[id]\n return name !== undefined && name !== '' ? name : id\n}\n","/**\n * Browser-side display formatting of the token-usage settings page: token\n * abbreviation (K/M/B), the cache hit rate, 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 $), and the failure-pill\n * tooltip labels. Pure functions only, shared by the section and the\n * trend chart.\n *\n * @module token-usage/client/format\n */\n\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { UsageAuxKindRow, UsageSummary, UsageTotals } from '../wire.ts'\nimport type { TokenUsageKey } from './locales.ts'\n\n/** Known `LlmFailure.code`s that have a `fail.*` locale label. An unknown\n * future code is not in this map and the tooltip renders it verbatim. */\nconst FAILURE_CODE_LABEL_KEYS = {\n ABORTED: 'fail.ABORTED',\n AUTH: 'fail.AUTH',\n CONTEXT_WINDOW_EXCEEDED: 'fail.CONTEXT_WINDOW_EXCEEDED',\n EMPTY_RESPONSE: 'fail.EMPTY_RESPONSE',\n FILES_API: 'fail.FILES_API',\n INVALID_CREDENTIAL: 'fail.INVALID_CREDENTIAL',\n INVALID_REQUEST: 'fail.INVALID_REQUEST',\n MALFORMED_RESPONSE: 'fail.MALFORMED_RESPONSE',\n MISSING_CREDENTIAL: 'fail.MISSING_CREDENTIAL',\n QUOTA: 'fail.QUOTA',\n RATE_LIMIT: 'fail.RATE_LIMIT',\n REQUEST_EXTENSION: 'fail.REQUEST_EXTENSION',\n SERVER: 'fail.SERVER',\n STREAM_CLOSED: 'fail.STREAM_CLOSED',\n TIMEOUT: 'fail.TIMEOUT',\n TRANSPORT: 'fail.TRANSPORT',\n UNKNOWN: 'fail.UNKNOWN',\n} as const satisfies Record<string, TokenUsageKey>\n\n/** Display label of a provider route key: the payload's name registry\n * (route key → latest display name) wins; a missing or empty entry falls\n * back to the key itself, so a route the registry never saw still shows.\n * The rule is shared with the host side (`src/provider-label.ts`). */\nexport { providerLabel } from '../provider-label.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. The CNY sign is the\n * fullwidth ¥ (U+FFE5) — the standard RMB glyph in a Chinese UI, and the\n * suffix the number-first cost idiom reads naturally with. */\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: two decimals plus the view's symbol SUFFIXED —\n * `1.25¥` — matching the dock row's number-first unit idiom (`12.2M tok`,\n * `98%`), where every reading leads with its magnitude. USD divides the\n * wire's RMB amount by the exchange rate (`0.18$` under a rate-7 view).\n * A cost is always shown, never omitted.\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 `${(cost / view.rate).toFixed(2)}${view.symbol}`\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/**\n * One request's cache-hit rate as display text, for the usage tab's request\n * pool ONLY: at most one decimal (`49.96%` → `50%` — the rounding that the\n * raw-value-first policy must see through). Undefined renders `—` (unknown,\n * never 0%). The global `hitRateDisplay` keeps summarizing whole sessions.\n * @param rate - the raw [0,1] rate, or undefined when unknown.\n */\nexport function formatRequestRate(rate: number | undefined): string {\n if (rate === undefined || !Number.isFinite(rate)) return '—'\n return `${percent(rate * 100)}%`\n}\n\n/**\n * A full-precision rate text for tooltips: two decimals (`49.96%`), so a\n * displayed `50%` that is actually below the threshold can explain itself.\n */\nexport function formatRequestRateExact(rate: number): string {\n return `${(rate * 100).toFixed(2)}%`\n}\n\n/**\n * Time-of-day text for a request-pool row (`15:45:08`, locale-independent\n * zero-padded) — the compact column form the 11-column table needs.\n * @param ms - epoch milliseconds.\n */\nexport function formatTimeOfDay(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())}:${pad(date.getSeconds())}`\n}\n\n/**\n * The failure pill's hover tooltip text: one `label ×count` line per failure\n * class, largest count first (code name ascending breaks ties), newline-joined —\n * the shell Tooltip renders `pre-line`, so each line lands on its own row.\n * Known `LlmFailure.code`s map through `fail.*` locale keys (限流 / Rate\n * limited); an unknown future code renders verbatim. A legacy shape without\n * the breakdown, or an empty map, yields '' and the caller suppresses the\n * tooltip.\n * @param byCode - the per-code failure counts from the totals (may be undefined).\n * @param t - locale lookup; codes without a `fail.*` key stay verbatim.\n * @returns the multi-line tooltip label, or '' when there is nothing to show.\n */\nexport function failuresTooltip(\n byCode: Record<string, number> | undefined,\n t: TranslateNS<'token-usage'>,\n): string {\n if (byCode === undefined) return ''\n return Object.entries(byCode)\n .filter(([, count]) => count > 0)\n .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))\n .map(([code, count]) => `${failureCodeLabel(code, t)} ×${count}`)\n .join('\\n')\n}\n\n/** Locale label for one failure code; unknown codes stay verbatim. */\nfunction failureCodeLabel(code: string, t: TranslateNS<'token-usage'>): string {\n if (Object.hasOwn(FAILURE_CODE_LABEL_KEYS, code)) {\n return t(FAILURE_CODE_LABEL_KEYS[code as keyof typeof FAILURE_CODE_LABEL_KEYS])\n }\n return code\n}\n\n/**\n * The overhead pill's hover tooltip text: one `label ×count` line per\n * auxiliary kind, count descending, newline-joined — the same shape as\n * {@link failuresTooltip}. An absent breakdown yields '' and the caller\n * suppresses the tooltip (the pill itself still shows its count).\n * @param byKind - the per-kind rows of the aux summary (may be undefined).\n * @param t - locale lookup (`aux.kind.*`; the kind is a closed union, so\n * every value has a key).\n * @returns the multi-line tooltip label, or '' when there is nothing to show.\n */\nexport function overheadTooltip(\n byKind: readonly UsageAuxKindRow[] | undefined,\n t: TranslateNS<'token-usage'>,\n): string {\n if (byKind === undefined) return ''\n return byKind\n .filter(row => row.totals.requests > 0)\n .sort((left, right) => right.totals.requests - left.totals.requests)\n .map(row => `${t(`aux.kind.${row.auxKind}`)} ×${row.totals.requests.toLocaleString()}`)\n .join('\\n')\n}\n","import type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AssociationStorageError, CostState, PricingUnavailableReason } from '../wire.ts'\n\nexport function costsAvailable(state?: CostState): boolean {\n return state === undefined || state === 'ready'\n}\n\n/** Shared failure reasons; matching and prices remain entirely on the host. */\nexport function PricingStatus({ costState, pricingUnavailableReason, associationStorageError, t }: {\n costState?: CostState | undefined\n pricingUnavailableReason?: PricingUnavailableReason | undefined\n associationStorageError?: AssociationStorageError | undefined\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const storageWarning = associationStorageError !== undefined\n ? <p role=\"status\">{t('pricing.associationStorageUnavailable')}</p> : null\n const costWarning = !costsAvailable(costState)\n ? <p role=\"status\">{t(costState === 'history-incomplete' ? 'pricing.historyIncomplete' : 'pricing.unavailable')}\n {costState === 'pricing-unavailable' && pricingUnavailableReason !== undefined ? ` ${t(`pricing.reason.${pricingUnavailableReason}`)}` : ''}\n </p> : null\n return <>{storageWarning}{costWarning}</>\n}\n","import type { ModelResolution } from './wire.ts'\n\nexport interface ModelIdentity {\n modelId: string\n aliasPatterns?: readonly string[]\n}\n\n/** Full-name comparison only: spelling remains intact in records and displays. */\nexport const modelKey = (name: string): string => name.toLowerCase()\n\nexport function providerSuffix(name: string): string | undefined {\n const parts = name.split('/')\n return parts.length > 1 && parts.every(part => part !== '') ? parts.at(-1) : undefined\n}\n\n/** Parse the upstream portable subset rather than accepting arbitrary JS regex. */\nexport function compileAliasPattern(pattern: string): RegExp {\n if (!pattern.startsWith('^') || !pattern.endsWith('$')) throw new Error('alias pattern requires ^ and $')\n const body = pattern.slice(1, -1)\n let offset = 0\n function expression(depth: number): void {\n if (depth > 32) throw new Error('alias pattern nesting is too deep')\n let atoms = 0\n while (offset < body.length && body[offset] !== ')') {\n const char = body[offset++]!\n if (char === '|') {\n if (atoms === 0) throw new Error('empty alias pattern branch')\n atoms = 0\n continue\n }\n if (char === '(') {\n expression(depth + 1)\n if (body[offset++] !== ')') throw new Error('unclosed alias pattern group')\n } else if (char === '\\\\') {\n const literal = body[offset++]\n if (literal === undefined || /[A-Za-z0-9\\s]/.test(literal)) throw new Error('alias patterns allow escaped punctuation only')\n } else if (!/[A-Za-z0-9_/:\\-]/.test(char)) {\n throw new Error('unsupported alias pattern syntax')\n }\n atoms++\n if (body[offset] === '?') offset++\n }\n if (atoms === 0) throw new Error('empty alias pattern branch')\n }\n expression(0)\n if (offset !== body.length) throw new Error('unbalanced alias pattern group')\n return new RegExp(pattern, 'i')\n}\n\n/** `$` also accepts a trailing newline in JS; require a full-span match. */\nexport function matchesAliasPattern(regex: RegExp, name: string): boolean {\n const match = regex.exec(name)\n return match !== null && match.index === 0 && match[0].length === name.length\n}\n\nexport function validateModelIdentities(models: readonly ModelIdentity[]): void {\n const ids = new Set<string>()\n for (const model of models) {\n const key = modelKey(model.modelId)\n if (ids.has(key)) throw new Error(`duplicate modelId: ${model.modelId}`)\n ids.add(key)\n const patterns = model.aliasPatterns ?? []\n if (new Set(patterns).size !== patterns.length) throw new Error(`duplicate aliasPatterns: ${model.modelId}`)\n for (const pattern of patterns) compileAliasPattern(pattern)\n }\n}\n\nexport function createModelResolver(models: readonly ModelIdentity[]): (name: string) => ModelResolution {\n validateModelIdentities(models)\n const ids = new Map<string, Set<string>>()\n const patterns: Array<{ modelId: string; regex: RegExp }> = []\n const add = (index: Map<string, Set<string>>, name: string, id: string): void => {\n const key = modelKey(name)\n const hits = index.get(key) ?? new Set<string>()\n hits.add(id)\n index.set(key, hits)\n }\n for (const model of models) {\n add(ids, model.modelId, model.modelId)\n for (const pattern of model.aliasPatterns ?? []) patterns.push({ modelId: model.modelId, regex: compileAliasPattern(pattern) })\n }\n const cache = new Map<string, ModelResolution>()\n return (rawName): ModelResolution => {\n const cached = cache.get(rawName)\n if (cached !== undefined) return cached\n const suffix = providerSuffix(rawName)\n const resultOf = (hits: Set<string>, method: NonNullable<ModelResolution['method']>, strippedPrefix: boolean): ModelResolution => {\n const candidates = [...hits].sort()\n return candidates.length === 1\n ? { rawName, status: 'matched', modelId: candidates[0]!, method, strippedPrefix, candidates: [] }\n : { rawName, status: 'ambiguous', method, strippedPrefix, candidates }\n }\n let result: ModelResolution | undefined\n for (const [candidate, normalized] of [[rawName, false], ...(suffix === undefined ? [] : [[suffix, true]])] as Array<[string, boolean]>) {\n const idHits = ids.get(modelKey(candidate))\n if (idHits !== undefined) result = resultOf(idHits, normalized ? 'normalized-id' : 'id', normalized)\n if (result !== undefined) break\n }\n if (result === undefined && rawName !== '') {\n const hits = new Set<string>()\n let strippedPrefix = false\n for (const { modelId, regex } of patterns) {\n for (const candidate of suffix === undefined ? [rawName] : [rawName, suffix]) {\n if (matchesAliasPattern(regex, candidate)) {\n hits.add(modelId)\n if (candidate !== rawName) strippedPrefix = true\n }\n }\n }\n if (hits.size > 0) result = resultOf(hits, 'pattern', strippedPrefix)\n }\n result ??= { rawName, status: 'unmatched', strippedPrefix: false, candidates: [] }\n cache.set(rawName, result)\n return result\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) holding that model's full price table — billing\n * conditions (default / context tiers / peak slots / time rules) × the four\n * per-million rates, converted for a USD view. Shared by the settings\n * page's per-model “定价” affordance and the pricing-overview dialog's\n * drill-in rows; a native showModal naturally stacks a second instance\n * above the overview.\n *\n * @module token-usage/client/PricingDialog\n */\n\nimport { useEffect, useRef } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ContextTier, DailySlot, ModelPricing, ModelRates, RateWindow } from '../wire.ts'\nimport { dayKeyOf } from './day.ts'\nimport { formatRate, formatRateWithSymbol, formatTokens } from './format.ts'\nimport type { CurrencyView } from './format.ts'\nimport styles from './PricingDialog.module.css'\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. */\nexport function 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). */\nexport function 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. The structure mirrors\n * {@link resolveRate}'s node chain.\n */\nexport function 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 (the current era)\n // first, then each time rule as an isolated price world, newest era\n // first (descending rule end), regardless of the feed's listing order.\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]\n .sort((a, b) => b.endTime - a.endTime)\n .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. Mounts only while a model is selected;\n * every close path funnels through the dialog's `close` event, which clears\n * the selection and unmounts it.\n */\nexport function 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 // The backdrop-close press guard: a text-selection drag released outside\n // the dialog lands its click on the dialog element (the click fires on\n // the press/release targets' common ancestor, and outside a top-layer\n // dialog every point resolves to the dialog) — the same target a real\n // backdrop click produces. Only a press that began on the backdrop may\n // close; see the overview dialog's backdropPress for the full story.\n const backdropPress = useRef(false)\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 // but only when the press started there too: a selection drag\n // released outside produces the same click target.\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => {\n if (event.target === dialogRef.current && backdropPress.current) dialogRef.current?.close()\n }}\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","import { useEffect, useRef } from 'react'\nimport type { ModelResolution, PricingAssociationsPayload } from '../wire.ts'\n\nconst CHANGED_EVENT = 'token-usage:pricing-associations-changed'\nconst TABLE_CHANGED_EVENT = 'token-usage:pricing-table-changed'\n\n/** All mounted usage views refresh their existing query after a real commit. */\nexport function pricingAssociationsChanged(): void { window.dispatchEvent(new Event(CHANGED_EVENT)) }\nexport function pricingTableChanged(): void { window.dispatchEvent(new Event(TABLE_CHANGED_EVENT)) }\n\nexport function usePricingAssociationRefresh(refresh: () => void): void {\n const latest = useRef(refresh)\n latest.current = refresh\n useEffect(() => {\n const changed = (): void => { latest.current() }\n window.addEventListener(CHANGED_EVENT, changed)\n window.addEventListener(TABLE_CHANGED_EVENT, changed)\n return () => {\n window.removeEventListener(CHANGED_EVENT, changed)\n window.removeEventListener(TABLE_CHANGED_EVENT, changed)\n }\n }, [])\n}\n\nexport class AssociationRequestError extends Error {\n constructor(readonly code: string, readonly current?: PricingAssociationsPayload) { super(code) }\n}\n\n/** Optional pricing references and the current feed version; no usage or credentials. */\nexport function pricingIssueUrl(resolution: ModelResolution, version?: number): string {\n const lines = [\n '1. Pricing reference (optional)',\n ' - Currency:',\n ' - Input price per 1 million tokens:',\n ' - Output price per 1 million tokens:',\n ' - Cache read price per 1 million tokens:',\n ' - Cache write price per 1 million tokens:',\n ' - Context window (tokens):',\n '',\n '2. Official pricing URL (optional)',\n ' - URL:',\n '',\n '3. Current pricing table version',\n ` - ${version ?? 'Unknown'}`,\n ]\n const url = new URL('https://github.com/LaoYueHanNi/model-price-table/issues/new')\n url.searchParams.set('title', `Add model pricing: ${resolution.rawName}`)\n url.searchParams.set('body', lines.join('\\n'))\n return url.href\n}\n","import { createContext, useContext, useEffect, useId, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { ASSOCIATIONS_PATH, PRICING_PATH } from '../wire.ts'\nimport type { ModelResolution, PricingAssociationStatus, PricingAssociationsPayload, PricingOverviewModel, PricingOverviewPayload } from '../wire.ts'\nimport { modelKey } from '../model-resolution.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport type { CurrencyView } from './format.ts'\nimport { currencyViewOf } from './format.ts'\nimport { PricingDialog } from './PricingDialog.tsx'\nimport { AssociationRequestError, pricingAssociationsChanged, pricingIssueUrl } from './pricing-associations.ts'\nimport shared from './PricingDialog.module.css'\nimport styles from './PricingAssociations.module.css'\n\ninterface AssociationUi { open(source?: string): void; showUnpriced(resolution: ModelResolution): void; resolutions: readonly ModelResolution[]; feedVersion?: number }\nconst AssociationUiContext = createContext<AssociationUi | null>(null)\n\nexport function PricingAssociationProvider({ resolutions = [], feedVersion, view, t, children }: {\n resolutions?: readonly ModelResolution[] | undefined; feedVersion?: number | undefined\n view: CurrencyView; t: TranslateNS<'token-usage'>; children: ReactNode\n}): ReactNode {\n const [source, setSource] = useState<string | null | undefined>(undefined)\n const [unpriced, setUnpriced] = useState<ModelResolution | null>(null)\n const opener = useRef<HTMLElement | null>(null)\n const rememberOpener = (): void => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null }\n return <AssociationUiContext.Provider value={{ open: name => { rememberOpener(); setSource(name ?? null) },\n showUnpriced: resolution => { rememberOpener(); setUnpriced(resolution) }, resolutions,\n ...(feedVersion !== undefined ? { feedVersion } : {}) }}>\n {children}\n {unpriced !== null && <UnpricedModelDialog resolution={unpriced} version={feedVersion} t={t}\n onClose={() => setUnpriced(null)} onAssociate={() => { setUnpriced(null); setSource(unpriced.rawName) }} />}\n {source !== undefined && <PricingAssociationDialog initialSource={source} returnFocus={opener.current} view={view} t={t} onClose={() => setSource(undefined)} />}\n </AssociationUiContext.Provider>\n}\n\n/** Entry remains available even when the usage filter has no rows. */\nexport function PricingAssociationManagerButton({ t, onOpen }: { t: TranslateNS<'token-usage'>; onOpen?: () => void }): ReactNode {\n const ui = useContext(AssociationUiContext)\n const open = onOpen ?? (ui === null ? undefined : () => ui.open())\n return open === undefined ? null : <button type=\"button\" data-pricing-association-manager className={styles.button} onClick={open}>{t('association.manage')}</button>\n}\n\nexport function PricingIssueLink({ resolution, version, t }: { resolution: ModelResolution; version?: number | undefined; t: TranslateNS<'token-usage'> }): ReactNode {\n return <a className={styles.link} href={pricingIssueUrl(resolution, version)} target=\"_blank\" rel=\"noopener noreferrer\">{t('association.issue')}</a>\n}\n\nexport function UnpricedModelTag({ model, t }: { model: string; t: TranslateNS<'token-usage'> }): ReactNode {\n const ui = useContext(AssociationUiContext)\n const resolution = ui?.resolutions.find(row => modelKey(row.rawName) === modelKey(model))\n ?? { rawName: model, status: 'unmatched' as const, strippedPrefix: false, candidates: [] }\n return <button type=\"button\" className={styles.unpricedTag} aria-haspopup=\"dialog\"\n disabled={ui === null || model === ''} onClick={() => ui?.showUnpriced(resolution)}>{t('pricing.unpriced')}</button>\n}\n\nfunction UnpricedModelDialog({ resolution, version, t, onClose, onAssociate }: {\n resolution: ModelResolution; version?: number | undefined; t: TranslateNS<'token-usage'>\n onClose: () => void; onAssociate: () => void\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n const backdropPress = useRef(false)\n const opener = useRef<HTMLElement | null>(document.activeElement instanceof HTMLElement ? document.activeElement : null)\n useEffect(() => {\n dialogRef.current?.showModal()\n return () => { if (opener.current?.isConnected) opener.current.focus() }\n }, [])\n const automatic = resolution.automatic ?? resolution\n return <dialog ref={dialogRef} className={`${shared.dialog} ${styles.unpricedDialog}`} aria-label={t('association.unpricedTitle')}\n onClose={event => { if (event.target === dialogRef.current) onClose() }}\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => { if (event.target === dialogRef.current && backdropPress.current) dialogRef.current?.close() }}\n onKeyDown={event => { if (event.key === 'Escape') event.stopPropagation() }}>\n <div className={shared.dialogHead}>\n <h2 className={shared.dialogTitle}>{t('association.unpricedTitle')}</h2>\n <button type=\"button\" className={shared.dialogClose} aria-label={t('association.close')} onClick={() => dialogRef.current?.close()}>✕</button>\n </div>\n <p className={styles.name}>{resolution.rawName}</p>\n {automatic.status === 'ambiguous' && <p className={styles.note}>{t('pricing.ambiguous', { models: automatic.candidates.join(', ') })}</p>}\n <div className={styles.actions}>\n <button type=\"button\" className={styles.button} onClick={onAssociate}>{t('association.choose')}</button>\n <PricingIssueLink resolution={resolution} version={version} t={t} />\n </div>\n </dialog>\n}\n\n/** Show original associated IDs on hover without expanding the statistics row. */\nexport function ModelAssociationBadge({ model, t }: { model: string; t: TranslateNS<'token-usage'> }): ReactNode {\n const ui = useContext(AssociationUiContext)\n if (ui === null || model === '') return null\n const names = ui.resolutions.filter(row => modelKey(row.modelId ?? row.rawName) === modelKey(model))\n const associated = names.filter(row => row.association !== undefined)\n if (associated.length === 0) return null\n const label = t('association.tooltip', { models: associated.map(row => row.rawName).join(', ') })\n return <span className={styles.badgeWrap}><Tooltip label={label} side=\"top\" delayMs={100}>\n <span className={styles.badge} role=\"img\" aria-label={label} tabIndex={0}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <circle cx=\"8\" cy=\"8\" r=\"6\" stroke=\"currentColor\" />\n <path d=\"M6.5 6a1.5 1.5 0 0 1 3 0c0 1-1.5 1-1.5 2.5\" stroke=\"currentColor\" strokeLinecap=\"round\" />\n <circle cx=\"8\" cy=\"10.5\" r=\".7\" fill=\"currentColor\" />\n </svg>\n </span>\n </Tooltip></span>\n}\n\nfunction AssociationStatus({ row, t }: { row: PricingAssociationStatus; t: TranslateNS<'token-usage'> }): ReactNode {\n return <p className={styles.note}>\n {t(`association.state.${row.state}`)}\n {row.state === 'automatic-takeover' && <>{' '}{t('association.automaticTarget', { model: row.automaticModelId ?? '' })}\n {row.targetDiffers && <>{' '}{t('association.targetDiffers', { model: row.targetModelId })}</>}\n {' '}{t('association.reactivate')}</>}\n </p>\n}\n\nasync function readJson<T>(url: string, signal: AbortSignal): Promise<T> {\n const response = await fetch(url, { signal, cache: 'no-store' })\n if (!response.ok) throw new Error(`HTTP ${response.status}`)\n return response.json() as Promise<T>\n}\n\nfunction checkAssociations(value: PricingAssociationsPayload): PricingAssociationsPayload {\n if (value === null || typeof value !== 'object' || typeof value.directoryToken !== 'string'\n || !['ready', 'unavailable'].includes(value.storageState) || !Array.isArray(value.associations)\n || typeof value.pricingAvailable !== 'boolean' || typeof value.writesPaused !== 'boolean'\n || (value.storageState === 'ready' && (!Number.isSafeInteger(value.revision) || value.revision! < 0))\n || value.associations.some(row => row === null || typeof row.sourceModel !== 'string' || typeof row.targetModelId !== 'string')) {\n throw new Error('unexpected association response')\n }\n return value\n}\n\nfunction checkPricing(value: PricingOverviewPayload): PricingOverviewPayload {\n if (value === null || typeof value !== 'object' || !Array.isArray(value.models)\n || value.models.some(row => row === null || typeof row.modelId !== 'string'\n || !Array.isArray(row.aliasPatterns) || !row.aliasPatterns.every((pattern: unknown) => typeof pattern === 'string') || row.rules?.base === undefined)) {\n throw new Error('unexpected pricing response')\n }\n return value\n}\n\nfunction requestMessage(error: unknown, t: TranslateNS<'token-usage'>): string {\n if (!(error instanceof AssociationRequestError)) return t('association.writeFailed')\n switch (error.code) {\n case 'revision-conflict': case 'directory-conflict': return t('association.conflict')\n case 'migration-in-progress': return t('association.migrating')\n case 'source-automatically-priced': return t('association.automaticOnly')\n case 'target-unavailable': return t('association.targetUnavailable')\n case 'pricing-unavailable': return t('pricing.unavailable')\n case 'association-storage-unavailable': return t('pricing.associationStorageUnavailable')\n default: return t('association.writeFailed')\n }\n}\n\nexport function PricingAssociationDialog({ initialSource, view, t, onClose, returnFocus }: {\n initialSource: string | null; view: CurrencyView; t: TranslateNS<'token-usage'>; onClose: () => void\n returnFocus?: HTMLElement | null\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n const searchId = useId()\n const backdropPress = useRef(false)\n const mounted = useRef(true)\n const writing = useRef(false)\n const opener = useRef<HTMLElement | null>(returnFocus ?? (document.activeElement instanceof HTMLElement ? document.activeElement : null))\n const source = initialSource\n const [query, setQuery] = useState('')\n const [target, setTarget] = useState<string | null>(null)\n const [detail, setDetail] = useState<PricingOverviewModel | null>(null)\n const [pending, setPending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n const [notice, setNotice] = useState<string | null>(null)\n const [confirmRevoke, setConfirmRevoke] = useState<string | null>(null)\n const [override, setOverride] = useState<PricingAssociationsPayload | null>(null)\n const [state, retry] = useAsyncResource<{ associations: PricingAssociationsPayload; pricing: PricingOverviewPayload | null; source: string | null }>(async signal => {\n const [associations, pricing] = await Promise.all([\n readJson<PricingAssociationsPayload>(ASSOCIATIONS_PATH + (source !== null ? `?sourceModel=${encodeURIComponent(source)}` : ''), signal).then(checkAssociations),\n readJson<PricingOverviewPayload>(PRICING_PATH, signal).then(checkPricing).catch(() => null),\n ])\n return { associations, pricing, source }\n }, [source], { retryToken: 0 })\n\n useEffect(() => {\n const dialog = dialogRef.current\n dialog?.showModal()\n const parent = dialog?.parentElement\n mounted.current = true\n return () => {\n mounted.current = false\n if (opener.current?.isConnected) opener.current.focus()\n else (parent?.querySelector<HTMLButtonElement>('[data-pricing-association-manager]')\n ?? parent?.querySelector<HTMLButtonElement>('[data-pricing-overview-trigger]')\n ?? parent?.querySelector<HTMLButtonElement>('button'))?.focus()\n }\n }, [])\n\n const ready = state.status === 'ready' && state.value.source === source\n const snapshot = override ?? (ready ? state.value.associations : null)\n const models = ready ? state.value.pricing?.models ?? [] : []\n const candidateView = ready && state.value.pricing !== null ? currencyViewOf(state.value.pricing) : view\n const selected = models.find(model => modelKey(model.modelId) === modelKey(target ?? ''))\n const currentChoice = snapshot?.associations.find(row => modelKey(row.sourceModel) === modelKey(source ?? ''))\n const savedTarget = models.find(model => modelKey(model.modelId) === modelKey(currentChoice?.targetModelId ?? ''))\n const automatic = snapshot?.resolution?.automatic ?? snapshot?.resolution\n const writable = ready && snapshot?.storageState === 'ready' && !snapshot.writesPaused && !pending\n const canSave = writable && snapshot?.pricingAvailable && ready && state.value.pricing !== null && state.value.pricing.costState !== 'pricing-unavailable'\n && automatic !== undefined && automatic.status !== 'matched' && selected !== undefined && source !== null\n const searchModelId = modelKey(query.trim())\n const candidates = searchModelId === '' ? [] : models.filter(model => modelKey(model.modelId).includes(searchModelId))\n\n const reload = (): void => { setOverride(null); setError(null); retry() }\n\n const mutate = async (operation: 'save' | 'delete', name: string): Promise<void> => {\n if (writing.current || snapshot === null || snapshot.revision === null) return\n writing.current = true; setPending(true); setError(null); setNotice(null)\n try {\n const response = await fetch(ASSOCIATIONS_PATH, { method: operation === 'save' ? 'POST' : 'DELETE', cache: 'no-store',\n headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sourceModel: name,\n ...(operation === 'save' ? { targetModelId: selected?.modelId } : {}), revision: snapshot.revision, directoryToken: snapshot.directoryToken }) })\n const result = await response.json() as PricingAssociationsPayload & { error?: string; current?: PricingAssociationsPayload }\n if (!response.ok) throw new AssociationRequestError(result.error ?? 'write-failed', result.current)\n checkAssociations(result)\n pricingAssociationsChanged()\n if (!mounted.current) return\n if (operation === 'save') { dialogRef.current?.close(); return }\n setOverride(result); setConfirmRevoke(null); setNotice(t('association.revoked'))\n } catch (failure) {\n if (!mounted.current) return\n if (failure instanceof AssociationRequestError && failure.current !== undefined) {\n setOverride(failure.current)\n if (failure.code === 'directory-conflict') {\n setTarget(null); setDetail(null); setOverride(null); retry(); pricingAssociationsChanged()\n }\n }\n setError(requestMessage(failure, t))\n } finally { writing.current = false; if (mounted.current) setPending(false) }\n }\n\n const revokeButtons = (name: string): ReactNode => <>\n {confirmRevoke === name ? <span className={`${styles.actions} ${styles.revokeConfirmation}`}>\n <span className={styles.note}>{t('association.revokeImpact')}</span>\n <button type=\"button\" className={styles.button} disabled={!writable} onClick={() => { void mutate('delete', name) }}>{t('association.confirmRevoke')}</button>\n <button type=\"button\" className={styles.button} disabled={pending} onClick={() => setConfirmRevoke(null)}>{t('association.cancel')}</button>\n </span> : <button type=\"button\" className={styles.button} disabled={!writable} onClick={() => setConfirmRevoke(name)}>{t('association.revoke')}</button>}\n </>\n\n return <dialog ref={dialogRef} className={`${shared.dialog} ${styles.dialog}`} aria-label={t('association.title')}\n onClose={event => { if (event.target === dialogRef.current) onClose() }}\n onCancel={event => { if (event.target === dialogRef.current && writing.current) event.preventDefault() }}\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => { if (event.target === dialogRef.current && backdropPress.current && !writing.current) dialogRef.current?.close() }}\n onKeyDown={event => { if (event.key === 'Escape') event.stopPropagation() }}>\n <div className={shared.dialogHead}><h2 className={shared.dialogTitle}>{t('association.title')}</h2>\n <button type=\"button\" className={shared.dialogClose} aria-label={t('association.close')} disabled={pending} onClick={() => dialogRef.current?.close()}>✕</button>\n </div>\n {state.status === 'loading' && <p>{t('loading')}</p>}\n {state.status === 'error' && <><p role=\"alert\">{t('association.loadFailed')}</p><button type=\"button\" className={styles.button} onClick={reload}>{t('retry')}</button></>}\n {source !== null && ready && state.value.pricing === null && <><p role=\"alert\">{t('association.candidatesUnavailable')}</p><button type=\"button\" className={styles.button} disabled={pending} onClick={reload}>{t('retry')}</button></>}\n {error !== null && <p role=\"alert\" className={styles.error}>{error} <button type=\"button\" className={styles.button} disabled={pending} onClick={reload}>{t('association.refresh')}</button></p>}\n {notice !== null && <p role=\"status\">{notice}</p>}\n {snapshot !== null && <>\n {snapshot.storageState !== 'ready' && <p role=\"alert\">{t('pricing.associationStorageUnavailable')}</p>}\n {snapshot.writesPaused && <p role=\"status\">{t('association.migrating')}</p>}\n {!snapshot.pricingAvailable && <p role=\"status\">{t('pricing.unavailable')}</p>}\n {source === null ? <>\n <p className={styles.note}>{t('association.allHint')}</p>\n {snapshot.associations.length === 0 && <p className={styles.note}>{t('association.empty')}</p>}\n {snapshot.associations.map(row => <section key={modelKey(row.sourceModel)} className={`${styles.entry} ${styles.mappingRow}`}>\n <div className={styles.name}>{row.sourceModel} → {row.resolvedTargetModelId ?? row.targetModelId}</div>\n {revokeButtons(row.sourceModel)}\n </section>)}\n </> : <>\n <p className={`${styles.name} ${styles.source}`}>{source}</p>\n {automatic?.status === 'ambiguous' && <p>{t('pricing.ambiguous', { models: automatic.candidates.join(', ') })}</p>}\n {currentChoice !== undefined && <section className={styles.entry}>\n <div className={styles.name}>{source} → {currentChoice.resolvedTargetModelId ?? currentChoice.targetModelId}</div>\n <AssociationStatus row={currentChoice} t={t} />\n {savedTarget !== undefined && <button type=\"button\" className={styles.button} onClick={() => setDetail(savedTarget)}>{t('association.preview')}</button>}\n {revokeButtons(source)}\n </section>}\n {automatic?.status === 'matched' ? <p>{t('association.automaticOnly')} {automatic.modelId}</p> : <>\n <label className={styles.label} htmlFor={searchId}>{t('association.search')}</label>\n <input id={searchId} className={styles.search} type=\"search\" placeholder={t('association.searchHint')}\n value={query} disabled={pending} onChange={event => { setQuery(event.target.value); setTarget(null) }} />\n {candidates.length > 0 && <div className={styles.candidates} role=\"group\" aria-label={t('association.candidates')}>\n {candidates.map(model => <label key={model.modelId} className={styles.candidate}>\n <input type=\"radio\" name={searchId + '-target'} checked={target !== null && modelKey(target) === modelKey(model.modelId)} disabled={!writable || !snapshot.pricingAvailable}\n onChange={() => { setTarget(model.modelId); setNotice(null) }} />\n <span>{model.modelId}</span><small>{model.family}</small>\n </label>)}\n </div>}\n {query.trim() !== '' && candidates.length === 0 && <p className={styles.note}>{t('association.noResults')}</p>}\n {selected !== undefined && <div className={styles.selection}>\n <span className={styles.name}>{t('association.target', { model: selected.modelId })}</span>\n <button type=\"button\" className={styles.button} onClick={() => setDetail(selected)}>{t('association.preview')}</button>\n </div>}\n <p className={styles.note}>{t('association.impact')}</p>\n <button type=\"button\" className={`${styles.button} ${styles.save}`} disabled={!canSave} onClick={() => { void mutate('save', source) }}>{t(pending ? 'association.saving' : 'association.save')}</button>\n </>}\n </>}\n </>}\n {detail !== null && <PricingDialog model={detail.modelId} rules={detail.rules} view={candidateView} t={t} onClose={() => setDetail(null)} />}\n </dialog>\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 * 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, useState } 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\n/**\n * Hook reporting whether the current shell/page environment is in light mode.\n * Evaluates `document.documentElement.style.colorScheme` first (the DSH shell\n * rewrites this on every theme switch), falling back to `(prefers-color-scheme: light)`.\n */\nexport function useIsLightMode(): boolean {\n const [isLight, setIsLight] = useState<boolean>(() => {\n if (typeof document === 'undefined') return false\n const rootScheme = document.documentElement.style.colorScheme\n if (rootScheme === 'light') return true\n if (rootScheme === 'dark') return false\n return typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(prefers-color-scheme: light)').matches\n : false\n })\n\n useEffect(() => {\n if (typeof document === 'undefined') return\n const root = document.documentElement\n const media = typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(prefers-color-scheme: light)')\n : null\n\n const check = (): void => {\n const scheme = root.style.colorScheme\n if (scheme === 'light') {\n setIsLight(true)\n } else if (scheme === 'dark') {\n setIsLight(false)\n } else {\n setIsLight(media?.matches ?? false)\n }\n }\n\n check()\n const observer = new MutationObserver(check)\n observer.observe(root, { attributes: true, attributeFilter: ['style'] })\n if (media?.addEventListener) {\n media.addEventListener('change', check)\n }\n return () => {\n observer.disconnect()\n if (media?.removeEventListener) {\n media.removeEventListener('change', check)\n }\n }\n }, [])\n\n return isLight\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`). The mix base is the pill's\n * resting tertiary (NOT label-primary): the pill reads tertiary beside the\n * official pills, and a primary-tinted final frame would leave the figure\n * permanently highlighted after the animation's fill. */\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-tertiary)' },\n {\n transform: `scale(${String(popScale)})`,\n color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-tertiary))`,\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-tertiary))`,\n offset: 0.70,\n },\n { transform: 'scale(1)', color: 'var(--dsw-alias-label-tertiary)' },\n ], {\n duration: v.inflateMs,\n easing: 'cubic-bezier(0.25, 0.85, 0.35, 1)',\n })\n}\n","/**\n * Composer-dock usage pill cost-figure inflate animation: per-request\n * intensity from token deltas and the parameters for `costPop`. Pure\n * functions only — the 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` for one request step. */\nexport interface CostInflateVars {\n inflateMs: number\n popScale: string\n warnMix: 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 }\n}\n","/**\n * Request-driven cost-figure inflate animation for the composer-dock usage\n * pill: detects new usage from summary deltas and drives the WAAPI motion on\n * the cost figure (a scale + colour pop whose amplitude follows the step's\n * token intensity).\n *\n * @module token-usage/client/use-cost-inflate\n */\n\nimport { useCallback, useEffect, useRef, type RefObject } from 'react'\nimport type { UsageSummary } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { totalTokens } from './day.ts'\nimport { motionAllowed, runCostPop } from './cost-inflate-motion.ts'\nimport {\n animVars,\n computeIntensityFromDelta,\n deltaTotals,\n} from './cost-inflate.ts'\n\ninterface PrevChipSnapshot {\n totals: UsageSummary['total']\n totalCost: number\n}\n\nexport interface UseCostInflateResult {\n /** Call when a fresh chip summary lands (after first paint baseline). */\n onSummary: (summary: UsageSummary) => void\n /** Clear baseline and the in-flight pop (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 pill uses to play the costPop 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 popAnimRef = useRef<Animation | null>(null)\n\n const reset = useCallback(() => {\n popAnimRef.current?.cancel()\n popAnimRef.current = null\n prevRef.current = null\n }, [])\n\n useEffect(() => {\n reset()\n }, [scopeKey, reset])\n\n useEffect(() => () => { popAnimRef.current?.cancel() }, [])\n\n const playCostPop = useCallback((v: ReturnType<typeof animVars>) => {\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 if (!costsAvailable(summary.costState)) { reset(); return }\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 figure\n // repaints silently — no pop.\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 window.requestAnimationFrame(() => { playCostPop(v) })\n }, [playCostPop, reset])\n\n return { onSummary, reset }\n}\n","/**\n * Composer-dock usage pill (browser half): a cost trigger registered into\n * the `conversation.composer.dock` slot (`order: 10`, after the official\n * stats pills at `order: 0`), rendered as one capsule in the official\n * StatsPills skin. The figure is the WITH-SUBAGENTS fold — the one number\n * no official surface carries — suffixed with a quiet \"with subagents\"\n * badge only when the scope actually spans a subtree; a solo session's\n * cost renders bare, same scope as the official pills beside it.\n *\n * Clicking opens a detail panel (harness menu chrome, upward of the dock)\n * that explains the total: the folded token figure and cache-hit rate next\n * to it (official pills carry only the single-session token count, so the\n * subtree share has no home but here), the session / subagents split, and\n * a per-model breakdown with the unpriced-models footnote. Panel data is\n * LAZY: the trigger polls `fields=chip` (totals only, subtree scope); the\n * two richer reads (`fields=session` for byModel, a solo-session `chip`\n * read for the split) fire when the panel first opens and again whenever\n * request churn debounces through.\n *\n * The pill refreshes at REQUEST granularity (the header chip's former\n * cadence, inherited whole): `sessionStats` projection churn plus mirror\n * `updatedAt` is debounced 250 ms into one fetch, a failed FIRST fetch\n * retries itself on a 3 s cadence, and later failures keep the prior\n * figures. When usage grows on a new request the figure plays `costPop` —\n * a scale + colour pop whose amplitude follows that step's token\n * intensity. Reduced-motion users get silent figure updates.\n *\n * Visibility contract: a session with no recorded requests renders\n * nothing; a transient fetch miss keeps the previous render.\n *\n * @module token-usage/client/CostPill\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } 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 composer-dock runtime kit.\nimport type {} from '@deepseek-ai/dsh-client-ui-session/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.composer.dock` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { CostedModelRow, UsageSummary } from '../wire.ts'\nimport { STATS_PATH, encodeStatsQuery } from '../wire.ts'\nimport { useAsyncResource, useDebouncedValue } from './async-resource.ts'\nimport { totalTokens } from './day.ts'\nimport { currencyViewOf, formatCost, formatTokens, hitRateDisplay } from './format.ts'\nimport { PricingStatus, costsAvailable } from './PricingStatus.tsx'\nimport { ModelAssociationBadge, PricingAssociationProvider, UnpricedModelTag } from './PricingAssociations.tsx'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { buildChildIndex, buildStatsFreshnessKey, subtreeIds } from './session-stats.ts'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport { useCostInflate } from './use-cost-inflate.ts'\nimport styles from './CostPill.module.css'\n\n/** Refresh debounce: bursts of session-mirror updates (one request's events)\n * collapse into a single fetch — the header chip's request-scale cadence. */\nconst REFRESH_DEBOUNCE_MS = 250\n\n/** Self-heal cadence after a failed first fetch: refresh failures after the\n * first land keep the prior figures (silent mode) and self-heal on the next\n * request churn, so they never reach the error state. */\nexport const FETCH_FAILURE_RETRY_MS = 3_000\n\n/** Detail panel width (px); the viewport-clamped centering uses it. */\nconst PANEL_WIDTH = 300\nconst PANEL_VIEWPORT_MARGIN = 16\n\n/** Props the pill binds for the composer-dock slot: the framework's session\n * kit (`sessionId` + the global `useSessions` mirror used to walk the\n * subagent tree) plus the locale seat from the registration's `locale:`\n * declaration. The dock slot declares no owner share. */\nexport type CostPillProps =\n PropsRuntime<'conversation.composer.dock'>\n & PropsLocale<'token-usage'>\n\n/**\n * The session / subagents split of one folded summary. Subagent figures are\n * derived by subtraction (folded minus solo) and clamped at zero — a stale\n * solo read against a fresher fold must never paint a negative share.\n */\nexport interface UsageSplit {\n selfCost: number\n subsCost: number\n selfTokens: number\n subsTokens: number\n}\n\n/**\n * Subtract a solo-session summary from its subtree fold.\n * @param tree - the subtree-scoped folded summary.\n * @param self - the solo-session summary (same session, no children).\n * @returns the two shares; costs and tokens are additive so subtraction is\n * exact, and the hit rate is NEVER split (a ratio is not subtractable — the\n * panel recomputes the folded rate from the tree totals instead).\n */\nexport function splitUsage(tree: UsageSummary, self: UsageSummary): UsageSplit {\n const sub = (whole: number, part: number): number => (whole - part > 0 ? whole - part : 0)\n return {\n selfCost: self.totalCost,\n subsCost: sub(tree.totalCost, self.totalCost),\n selfTokens: totalTokens(self.total),\n subsTokens: sub(totalTokens(tree.total), totalTokens(self.total)),\n }\n}\n\n/**\n * Render the composer-dock usage pill for the active session. Renders\n * nothing when the session has no recorded usage or while the first fetch\n * is in flight — the \"data has no value, the block does not render\" rule.\n * @param props - framework session id, the session-list mirror, and the locale seat.\n * @returns the pill (plus its open detail panel), or null when empty/unavailable.\n */\nexport function CostPill({ sessionId, useSessions, useProjection, t }: CostPillProps): ReactNode | null {\n const rootRef = useRef<HTMLDivElement>(null)\n const costRef = useRef<HTMLSpanElement>(null)\n useColorSchemeMirror(rootRef)\n const [open, setOpen] = useState(false)\n const [associationTick, setAssociationTick] = useState(0)\n usePricingAssociationRefresh(() => setAssociationTick(tick => tick + 1))\n\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 byId = useSessions(state => state.byId)\n const childIndex = useMemo(() => buildChildIndex(byId), [byId])\n const scopeIds = useMemo(\n () => (sessionId === '' ? [] : subtreeIds(byId, sessionId, childIndex)),\n [byId, sessionId, childIndex],\n )\n const hasSubs = scopeIds.length > 1\n const liveStats = useProjection('sessionStats')\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 { onSummary } = useCostInflate(scopeResetKey, costRef)\n\n // The trigger's poll: subtree totals only (`fields=chip`), the lightest\n // read that feeds cost / tokens / hit rate.\n const [treeRes, retryTree] = useAsyncResource<UsageSummary | null>(\n signal => {\n const [idsPart] = debouncedKey.split('\\n\\t')\n const ids = (idsPart ?? '').split('\\n').filter(id => id !== '')\n return fetchSummary(ids, 'chip', signal)\n },\n [debouncedKey, associationTick],\n { silentAfterFirst: true, retryToken: 0 },\n )\n const summary = treeRes.status === 'ready' ? treeRes.value : null\n\n useEffect(() => {\n if (summary !== null) onSummary(summary)\n }, [summary, onSummary])\n\n // A failed first fetch renders nothing and self-heals on the retry\n // cadence; later failures keep the prior render (silent mode).\n useEffect(() => {\n if (treeRes.status !== 'error') return\n const timer = window.setTimeout(retryTree, FETCH_FAILURE_RETRY_MS)\n return () => { window.clearTimeout(timer) }\n }, [treeRes, retryTree])\n\n // Panel reads, LAZY: nothing flies while the panel is closed. The detail\n // read (`fields=session`) carries byModel; the solo read splits the fold.\n // Both re-fire when request churn debounces through while open.\n const [detailRes] = useAsyncResource<UsageSummary | null>(\n signal => {\n if (!open) return Promise.resolve(null)\n const [idsPart] = debouncedKey.split('\\n\\t')\n const ids = (idsPart ?? '').split('\\n').filter(id => id !== '')\n return fetchSummary(ids, 'session', signal)\n },\n [open, debouncedKey, associationTick],\n { silentAfterFirst: true, retryToken: 0 },\n )\n const [selfRes] = useAsyncResource<UsageSummary | null>(\n signal => {\n if (!open || sessionId === '') return Promise.resolve(null)\n return fetchSummary([sessionId], 'chip', signal)\n },\n [open, sessionId, debouncedKey, associationTick],\n { silentAfterFirst: true, retryToken: 0 },\n )\n\n // Session switches close the panel — the split it explains no longer holds.\n useEffect(() => {\n setOpen(false)\n }, [sessionId])\n\n // Outside pointer / Escape close — the harness popup pattern (ContextMeter\n // and the quota button share it), anchored 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 // Center the panel on the pill, clamped to the viewport's margins (the\n // dock row is full-width, but a bare left:0 could still skew off-screen\n // on narrow windows). Measured at open, refreshed on resize while open.\n const [panelLeft, setPanelLeft] = useState<number | undefined>(undefined)\n const measurePanelLeft = useCallback((): void => {\n const wrapper = rootRef.current\n if (wrapper === null) return\n const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect()\n const panelWidth = Math.min(PANEL_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 useEffect(() => {\n if (!open) return\n measurePanelLeft()\n window.addEventListener('resize', measurePanelLeft)\n return () => { window.removeEventListener('resize', measurePanelLeft) }\n }, [open, measurePanelLeft])\n\n if (summary === null || summary.total.requests === 0) return null\n\n const view = currencyViewOf(summary)\n const costText = costsAvailable(summary.costState) ? formatCost(summary.totalCost, view) : '—'\n const tokensValue = formatTokens(totalTokens(summary.total))\n const hit = hitRateDisplay(summary.total)\n const ariaLabel = hasSubs\n ? t('pill.costWithSubs', { value: costText })\n : t('pill.cost', { value: costText })\n\n // Panel shares: the split waits on the solo read; per-model waits on the\n // detail read. While either is in flight its block shows a quiet ellipsis.\n const selfSummary = selfRes.status === 'ready' ? selfRes.value : null\n const detail = detailRes.status === 'ready' ? detailRes.value : null\n const split = selfSummary !== null ? splitUsage(summary, selfSummary) : null\n const subCount = scopeIds.length - 1\n\n return (\n <div ref={rootRef} className={styles.root}>\n <PricingAssociationProvider resolutions={detail?.modelResolutions} feedVersion={summary.feedVersion} view={view} t={t}>\n <button\n type=\"button\"\n className={styles.pill}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n aria-label={`${ariaLabel},${t('panel.openHint')}`}\n onClick={() => { setOpen(!open) }}\n >\n <svg className={styles.glyph} viewBox=\"0 0 14 14\" width=\"14\" height=\"14\" aria-hidden>\n <circle cx=\"7\" cy=\"7\" r=\"5.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.2\" />\n <path\n d=\"M4.8 4.5 L7 7.2 L9.2 4.5 M7 7.2 V10 M5.2 8 H8.8 M5.2 9.4 H8.8\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.2\"\n />\n </svg>\n <span ref={costRef} className={styles.cost}>{costText}</span>\n </button>\n {open && (\n <div className={styles.panel} role=\"dialog\" aria-label={t('panel.title')} style={{ left: panelLeft }}>\n <span className={styles.panelHead}>\n <span className={styles.panelTitle}>\n {t('panel.title')}\n {hasSubs && <span className={styles.scopeTag}>{t('pill.scopeTag')}</span>}\n </span>\n <span className={styles.panelTotal}>{costText}</span>\n </span>\n <span className={styles.usageLine}>\n <span>{t('panel.tokens', { value: tokensValue })}</span>\n <span className={styles.dot}>·</span>\n <span>{t('panel.hitRate', { value: hit.text })}</span>\n </span>\n <div className={styles.rows}>\n <PricingStatus costState={summary.costState} pricingUnavailableReason={summary.pricingUnavailableReason} associationStorageError={summary.associationStorageError} t={t} />\n <span className={styles.row}>\n <span className={styles.rowLabel}>{t('panel.self')}</span>\n <span className={styles.rowValue}>\n {split === null\n ? <span className={styles.pending}>…</span>\n : <>{costsAvailable(summary.costState) && costsAvailable(selfSummary?.costState) ? formatCost(split.selfCost, view) : '—'}<span className={styles.tok}>{t('panel.tokens', { value: formatTokens(split.selfTokens) })}</span></>}\n </span>\n </span>\n {hasSubs && (\n <span className={`${styles.row} ${styles.rowSub}`}>\n <span className={styles.rowLabel}>{t('panel.subs', { count: subCount })}</span>\n <span className={styles.rowValue}>\n {split === null\n ? <span className={styles.pending}>…</span>\n : <>{costsAvailable(summary.costState) && costsAvailable(selfSummary?.costState) ? formatCost(split.subsCost, view) : '—'}<span className={styles.tok}>{t('panel.tokens', { value: formatTokens(split.subsTokens) })}</span></>}\n </span>\n </span>\n )}\n </div>\n <span className={styles.groupLabel}>{t('panel.byModel')}</span>\n <span className={styles.rows}>\n {detail === null\n ? (\n <span className={styles.row}>\n <span className={styles.pending}>…</span>\n </span>\n )\n : (\n <>\n {detail.byModel.map(row => (\n <ModelRow key={row.model} row={row} view={view} t={t} unpriced={detail.unpricedModels.includes(row.model)} available={costsAvailable(detail.costState) && !detail.unpricedModels.includes(row.model)} />\n ))}\n {costsAvailable(detail.costState) && detail.unpricedModels.length > 0 && (\n <span className={`${styles.row} ${styles.unpriced}`}>\n <span className={styles.rowLabel}>{t('panel.unpriced', { count: detail.unpricedModels.length })}</span>\n <span className={styles.rowValue}>{t('panel.unpricedNote')}</span>\n </span>\n )}\n </>\n )}\n </span>\n </div>\n )}\n </PricingAssociationProvider>\n </div>\n )\n}\n\n/** One per-model breakdown row: model id + request count, billed cost, tokens. */\nfunction ModelRow({ row, view, available, unpriced, t }: { row: CostedModelRow; view: ReturnType<typeof currencyViewOf>; available: boolean; unpriced: boolean; t: TranslateNS<'token-usage'> }): ReactNode {\n return (\n <span className={styles.row}>\n <span className={styles.rowLabel}>\n {row.model}\n {unpriced && <UnpricedModelTag model={row.model} t={t} />}\n <ModelAssociationBadge model={row.model} t={t} />\n <span className={styles.requests}>× {row.totals.requests}</span>\n </span>\n <span className={styles.rowValue}>\n {available ? formatCost(row.cost, view) : '—'}\n <span className={styles.tok}>{formatTokens(totalTokens(row.totals))}</span>\n </span>\n </span>\n )\n}\n\n/** Defensive shape check: an older host build or a misrouted response\n * would otherwise paint the pill 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 one stats summary. Throws on transport failure (network, abort,\n * non-2xx response, or a payload that doesn't look like a stats summary) so\n * the hook can keep the previous render in place.\n * @param sessionIds - the scope's session ids; an empty list skips the\n * fetch (returning null rather than throwing, so the hook's first-load\n * gate stays at \"loading\").\n * @param fields - `chip` for totals-only reads, `session` when byModel is\n * needed (the detail panel's per-model block).\n * @param signal - the cancellation signal from the hook.\n */\nasync function fetchSummary(\n sessionIds: readonly string[],\n fields: 'chip' | 'session',\n signal: AbortSignal,\n): Promise<UsageSummary | null> {\n if (sessionIds.length === 0) return null\n const response = await fetch(STATS_PATH + encodeStatsQuery({ sessionIds, fields }), {\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 sidebar panel list's \"More\" menu row (browser half): one entry that\n * opens the Token Usage main panel, registered into\n * `sidebar.panellist.actions` (declared by ui-sidebar since dsh\n * 0.2.1-rc.3). The row rides the region's own Menu — the owner supplies\n * `onDismiss` (close the menu before navigating) — and the registered\n * `inject` closure supplies the panel-opening callback, so this component\n * stays declarative. The label reuses the settings nav copy so the entry\n * reads as the same feature across surfaces.\n *\n * On a shell older than 0.2.1-rc.3 the slot is never declared: the inject\n * callback never runs and the row simply never appears — the settings\n * section stays the only entry.\n *\n * @module token-usage/client/PanellistMoreEntry\n */\n\nimport type { ReactNode } from 'react'\nimport { IconGaugeOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the `sidebar.panellist.actions` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'\n\nexport type PanellistMoreEntryProps =\n PropsRuntime<'sidebar.panellist.actions'>\n & PropsLocale<'token-usage'>\n & { openPanel: () => void }\n\n/**\n * Render the More-menu row that opens the Token Usage panel.\n * @param props - the owner's dismissal callback, the injected open\n * callback, and the framework translate seat.\n * @returns one MenuItemButton row.\n */\nexport function PanellistMoreEntry({ onDismiss, openPanel, t }: PanellistMoreEntryProps): ReactNode {\n return (\n <MenuItemButton icon={<IconGaugeOutlineRegular size={16} />}\n onSelect={() => { onDismiss(); openPanel() }}>\n {t('nav.label')}\n </MenuItemButton>\n )\n}\n","/**\n * Decorative occupant for the pinned Token Usage sidebar row (browser\n * half): registered into `sidebar.panellist` while the `sidebarPinned`\n * setting is on, so the shell renders the row the same way it renders its\n * official panel launchers — the shell owns the button and the accessible\n * label (resolved from the registration's `label` thunk); this component\n * supplies only the glyph.\n *\n * @module token-usage/client/PanellistPinEntry\n */\n\nimport { IconGaugeOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the `sidebar.panellist` SlotMap key.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'\n\n/**\n * Render the gauge glyph at the size the sidebar asks for. The glyph sits\n * directly in the row's glyph slot, exactly as the official panel icons do —\n * an inline wrapper would lift it above the label line. Selection highlight\n * is the shell row's own class, so `active` stays unused here.\n * @param props - the sidebar's icon share: the requested edge and whether the panel is selected.\n * @returns decorative gauge icon.\n */\nexport function PanellistPinEntry({ size }: PropsRuntime<'sidebar.panellist'>) {\n return <IconGaugeOutlineRegular size={size} />\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 * POOLING: a gateway may hold several keys of ONE vendor family, each\n * with its own meter but serving the same traffic. The trigger reads the\n * POOL's level (the mean of the pool's remaining shares) instead of\n * whichever window it happens to meet first, and colors it by the pool's\n * availability — one dead key no longer paints the whole vendor red,\n * while a pool with nothing left still does.\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, an `other` window (a gateway's open-named meter:\n * \"Credits\", \"Allowance\") ranking with the coarser pools it usually is.\n * The trigger icon reads this one, not the worst across windows: the\n * finest unit is the constraint the session is currently acting inside\n * (a calm 5-hour window carries the icon even when the weekly pool runs\n * low). Undefined when there is no window at all.\n */\nexport function finestQuotaWindow<T extends QuotaWindow>(windows: readonly T[]): T | undefined {\n const rank: Record<QuotaWindow['tier'], number> = { five_hour: 0, weekly: 1, other: 2, monthly: 3, balance: 4 }\n let pick: T | 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 * A quota window after POOLING: the windows one quota pool spends at one\n * tier collapsed into a single water level (the mean of their remaining\n * shares), plus the bookkeeping the severity band needs to tell a pool's\n * overall level from its weakest member.\n */\nexport interface PooledQuotaWindow extends QuotaWindow {\n /** Windows behind this level (1 = a lone window, nothing pooled). */\n peerCount: number\n /** How many of those windows sit below the red line (remaining < 20%). */\n exhaustedPeerCount: number\n}\n\n/**\n * Pool the windows of a payload: windows that NAME the same quota POOL\n * and spend the same tier (an `other` window pools only with its own\n * name) collapse into one level — their budgets are interchangeable\n * (a gateway's several keys of one vendor family), so the pool's mean\n * remaining share is the level the traffic actually feels.\n *\n * Two boundaries keep the collapse honest:\n *\n * - A window WITHOUT a pool stands alone. Single-source payloads name\n * no pool, and a lone window pools with nothing — the mean of one\n * window is that window.\n * - BALANCE windows never pool. Amounts are not shares: summing two\n * purses of different currencies (or averaging them) states nothing\n * true about either, so every balance keeps its own row.\n *\n * The order of first appearance is preserved, so the trigger still reads\n * the first (finest) level of the payload.\n */\nexport function poolQuotaWindows(windows: readonly QuotaWindow[]): readonly PooledQuotaWindow[] {\n const groups = new Map<string, QuotaWindow[]>()\n windows.forEach((window, index) => {\n // Pool-less windows get a key of their own (never shared).\n const key = window.pool === undefined\n ? `solo:${String(index)}`\n : `${window.pool}|${window.tier}|${window.name ?? ''}`\n const group = groups.get(key)\n if (group === undefined) groups.set(key, [window])\n else group.push(window)\n })\n const pooled: PooledQuotaWindow[] = []\n for (const group of groups.values()) {\n const ratios = group\n .map(window => quotaRemainingPercent(window))\n .filter((value): value is number => value !== undefined)\n // A lone window, a balance group (amounts are not shares), or a group\n // with no computable share stays as it is.\n if (group.length === 1 || group[0]?.tier === 'balance' || ratios.length === 0) {\n for (const window of group) {\n const remaining = quotaRemainingPercent(window)\n pooled.push({\n ...window,\n peerCount: 1,\n exhaustedPeerCount: remaining !== undefined && remaining < REMAIN_RED ? 1 : 0,\n })\n }\n continue\n }\n const mean = ratios.reduce((sum, value) => sum + value, 0) / ratios.length\n const exhausted = ratios.filter(value => value < REMAIN_RED).length\n const first = group[0] as QuotaWindow\n pooled.push({\n tier: first.tier,\n remainingPercent: mean,\n ...(first.name !== undefined ? { name: first.name } : {}),\n ...(first.pool !== undefined ? { pool: first.pool } : {}),\n peerCount: group.length,\n exhaustedPeerCount: exhausted,\n })\n }\n return pooled\n}\n\n/**\n * The severity of a POOLED window — the traffic light of a pool, not of\n * a single meter:\n *\n * - red only when EVERY window of the pool is exhausted (the pool has\n * nothing left to route to);\n * - yellow when the pool is low (mean at or below the yellow line) or\n * when SOME window is exhausted while others still have room (one\n * account died, the pool still serves);\n * - green otherwise.\n *\n * A lone window keeps the plain per-window band, so single-source\n * providers read exactly as before.\n */\nexport function quotaPoolSeverityOf(window: PooledQuotaWindow): QuotaSeverity {\n if (window.peerCount <= 1) return quotaSeverityOf(window)\n const remaining = quotaRemainingPercent(window)\n if (remaining === undefined) return quotaSeverityOf(window)\n if (window.exhaustedPeerCount >= window.peerCount) return 'exhausted'\n if (window.exhaustedPeerCount > 0) return 'warn'\n if (remaining <= REMAIN_YELLOW) return 'warn'\n return 'ok'\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 * 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's POOL level —\n * a gateway's several keys of one vendor share one budget, so the ring\n * reads that pool's mean share and its availability. 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 (the kit's SessionStandardProps declaration\n// lives in ui-session since dsh-client-runtime was removed).\nimport type {} from '@deepseek-ai/dsh-client-ui-session/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 poolQuotaWindows, quotaIconFillShare, quotaPoolSeverityOf, quotaRemainingPercent, quotaSeverityOf,\n 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/** 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.other' | 'quota.tier.balance'> = {\n five_hour: 'quota.tier.fiveHour',\n weekly: 'quota.tier.weekly',\n monthly: 'quota.tier.monthly',\n other: 'quota.tier.other',\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; model?: 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 [panelHeight, setPanelHeight] = useState<number | undefined>(undefined)\n const [panelBelow, setPanelBelow] = useState(false)\n const measurePanelLeft = useCallback((width: number): void => {\n const wrapper = rootRef.current\n if (wrapper === null) return\n const { left: wrapperLeft, width: wrapperWidth, top, bottom } = 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 // The shell's scroll body clips above its header, inside the viewport.\n let clipTop = 0\n let clipBottom = window.innerHeight\n for (let parent = wrapper.parentElement; parent !== null; parent = parent.parentElement) {\n if (!/^(auto|scroll|hidden|clip)$/u.test(getComputedStyle(parent).overflowY)) continue\n const rect = parent.getBoundingClientRect()\n clipTop = Math.max(clipTop, rect.top)\n clipBottom = Math.min(clipBottom, rect.bottom)\n }\n const above = top - clipTop - 8 - PANEL_VIEWPORT_MARGIN\n const below = clipBottom - bottom - 8 - PANEL_VIEWPORT_MARGIN\n setPanelBelow(below > above)\n setPanelHeight(Math.max(0, above, below))\n }, [])\n\n // The provider + model the 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, else\n // the default provider).\n const modelService = modelDirectory?.service\n const readChipSelection = (): { provider: string; model?: string } | undefined => {\n if (sessionId === '' || modelService === undefined) return undefined\n try {\n return modelService.directoryFor(sessionId).store.getSnapshot().current ?? 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 [chipSelection, setChipSelection] = useState(readChipSelection)\n useEffect(() => {\n // Re-seed on session/service change, then subscribe for chip switches.\n setChipSelection(readChipSelection())\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(() => { setChipSelection(readChipSelection()) })\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, chipSelection?.provider, chipSelection?.model, signal),\n [sessionId, chipSelection?.provider, chipSelection?.model],\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 trigger reads the POOLED level of the finest tier. A gateway\n // holding several keys of ONE vendor family serves them\n // interchangeably (it routes to whichever key still has room), so the\n // pool's mean remaining share is the level the traffic actually\n // feels — one exhausted key no longer paints the whole vendor red.\n // Cross-vendor pools stay apart (each keeps its own level), and a\n // payload without pools reads exactly as before.\n const pooled = poolQuotaWindows(windows)\n const finest = finestQuotaWindow(pooled)\n const severity = finest === undefined ? 'ok' : quotaPoolSeverityOf(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. A pooled level says so — the mean of several keys' shares is\n // not any single key's share.\n const figure = quotaTriggerFigure(finest)\n const triggerTip = figure === undefined\n ? t('quota.trigger')\n : finest !== undefined && finest.peerCount > 1\n ? t('quota.triggerSummaryPooled', {\n name: payload.providerName ?? payload.provider,\n figure,\n count: finest.peerCount,\n })\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 ...(panelHeight === undefined ? {} : { maxHeight: `${String(panelHeight)}px` }),\n ...(panelBelow ? { top: 'calc(100% + 8px)', bottom: 'auto' } : {}),\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 : <QuotaCardGroups windows={payload.windows} t={t} />}\n </div>\n )}\n </span>\n )\n}\n\n/**\n * The panel's window body: one group per quota CARD (a gateway payload\n * aggregates several upstream accounts — each window carries its card's\n * title), a card title heading each; a single-card (or card-less) payload\n * renders the flat grid as before, so the plain providers' panels do not\n * change shape.\n */\nfunction QuotaCardGroups({ windows, t }: { windows: readonly QuotaWindow[]; t: QuotaButtonProps['t'] }): ReactNode {\n const groups: Array<{ card?: string; windows: QuotaWindow[] }> = []\n for (const window of windows) {\n const last = groups[groups.length - 1]\n if (last !== undefined && (last.card ?? '') === (window.card ?? '')) {\n last.windows.push(window)\n } else {\n groups.push({ ...(window.card !== undefined ? { card: window.card } : {}), windows: [window] })\n }\n }\n if (groups.length <= 1) {\n const flat = groups[0]?.windows ?? []\n return (\n <div\n className={styles.grid}\n style={{ '--cols': String(Math.min(flat.length, 3)) } as CSSProperties}\n >\n {flat.map((window, index) =>\n <QuotaColumn key={`${window.tier}:${String(index)}`} window={window} t={t} />)}\n </div>\n )\n }\n return (\n <>\n {groups.map((group, gi) => (\n <div key={group.card ?? String(gi)} className={styles.cardGroup}>\n <div className={styles.cardTitle}>{group.card}</div>\n <div\n className={styles.grid}\n style={{ '--cols': String(Math.min(group.windows.length, 3)) } as CSSProperties}\n >\n {group.windows.map((window, index) =>\n <QuotaColumn key={`${window.tier}:${String(index)}`} window={window} t={t} />)}\n </div>\n </div>\n ))}\n </>\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 // An `other` window keeps the vendor's own name (\"Credits\",\n // \"Allowance\"); the known tiers read the localized period label.\n const label = window.balanceKind === 'recharge'\n ? t('quota.tier.recharge')\n : window.balanceKind === 'bonus'\n ? t('quota.tier.bonus')\n : window.name !== undefined && window.tier === 'other'\n ? window.name\n : 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 API-key DeepSeek shape) reads at\n * the minimal plate, two amount purses (account recharge + bonus) the\n * full 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 * A multi-card gateway payload (several upstream accounts) always reads\n * the full plate — the card headings need the room. Errors and payloads\n * without windows read the full plate (their copy runs long). */\nfunction panelWidthOf(payload: QuotaPayload | null): number {\n if (payload === null || payload.status !== 'ok') return PANEL_WIDTH_FULL\n if (new Set(payload.windows.map(window => window.card ?? '')).size > 1) return PANEL_WIDTH_FULL\n const bars = payload.windows.filter(window => quotaUsedPercent(window) !== undefined).length\n if (bars === 0) {\n // One amount (the API-key DeepSeek shape) stays the minimal plate.\n // Two purses (recharge + bonus) need the full plate so both labels fit.\n if (payload.windows.length === 1) return PANEL_WIDTH_BALANCE\n return PANEL_WIDTH_FULL\n }\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 'signed-out':\n return t('quota.error.signedOut')\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 and model when 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, model: 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 if (provider !== undefined && provider !== '' && model !== undefined && model !== '') params.set('model', model)\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 * 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, useRef, useState } from 'react'\nimport { IconChevronDownOutlineMedium } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { InjectFace, PropsLocale, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { CardActions, CardStore } from './card-form.ts'\nimport { FULL_SYNC_PATH, PRICING_SYNC_PATH, type FullSyncView, type PricingSyncResult } from '../wire.ts'\nimport { pricingTableChanged } from './pricing-associations.ts'\nimport css from './TokenUsageCard.module.css'\n\n/** The view the Plugins page asks for under `plugins.bundle.config`. */\nexport interface PluginConfigViewProps {\n /** `summary` renders the one-liner; `page` renders the form. */\n readonly view?: 'summary' | 'page'\n}\n\n/** Props the renderer binds for the token-usage settings card. */\nexport type TokenUsageCardProps =\n PluginConfigViewProps\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(props.view === 'page')\n const [picking, setPicking] = useState(false)\n const { t } = props\n const state = props.useTokenUsageCard(snapshot => snapshot)\n\n // Discard unstaged changes when navigating away from the page.\n const discardRef = useRef(props.discard)\n discardRef.current = props.discard\n useEffect(() => () => { discardRef.current() }, [])\n\n if (!state.available) return null\n if (props.view === 'summary') {\n return <span className={css.description}>{t('card.description')}</span>\n }\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 {\n status: body.status,\n processed: body.processed,\n total: body.total,\n added: body.added,\n skipped: body.skipped,\n removed: typeof body.removed === 'number' ? body.removed : 0,\n failedSessions: typeof body.failedSessions === 'number' ? body.failedSessions : 0,\n }\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, removed: 0, failedSessions: 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 <IconChevronDownOutlineMedium 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 <div className={css.field}>\n <label className={css.fieldLabel} htmlFor=\"token-usage-card-region\">{t('card.regionLabel')}</label>\n <div className={css.regionRow}>\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 <PricingSyncButton disabled={lockInput || state.saving || state.textDirty} dirty={state.textDirty} t={t} />\n </div>\n </div>\n <p className={css.hint}>\n {t('card.hint')}\n {state.overridden.pricingRegion ? ` ${t('card.overridden')}` : ''}\n </p>\n <div className={css.field}>\n <label className={css.pinRow} htmlFor=\"token-usage-card-pin\">\n <input\n id=\"token-usage-card-pin\"\n type=\"checkbox\"\n className={css.pinCheck}\n checked={state.pinnedDraft ?? state.sidebarPinned}\n disabled={lockInput}\n onChange={event => { props.editPinned(event.target.checked) }}\n />\n <span className={css.fieldLabel}>{t('card.sidebarPinned.label')}</span>\n </label>\n <p className={css.hint}>{t('card.sidebarPinned.hint')}</p>\n </div>\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 removed: String(fullSync.removed),\n })}\n {fullSync.failedSessions > 0\n ? t('card.fullSync.failuresNote', { count: String(fullSync.failedSessions) })\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 removed: String(fullSync.removed),\n })}\n {fullSync.failedSessions > 0\n ? t('card.fullSync.failuresNote', { count: String(fullSync.failedSessions) })\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\nfunction PricingSyncButton({ disabled, dirty, t }: {\n disabled: boolean; dirty: boolean; t: TranslateNS<'token-usage'>\n}) {\n const [status, setStatus] = useState<'idle' | 'running' | 'done' | 'failed' | 'changed' | 'migrating'>('idle')\n const [result, setResult] = useState<PricingSyncResult | null>(null)\n const running = useRef(false)\n const mounted = useRef(true)\n useEffect(() => {\n mounted.current = true\n return () => { mounted.current = false }\n }, [])\n\n const sync = async (): Promise<void> => {\n if (running.current || disabled || dirty) return\n running.current = true\n setStatus('running'); setResult(null)\n try {\n const response = await fetch(PRICING_SYNC_PATH, { method: 'POST', cache: 'no-store' })\n if (!response.ok) {\n const body = await response.json() as { error?: string }\n if (mounted.current) setStatus(body.error === 'migration-in-progress' ? 'migrating'\n : body.error === 'directory-conflict' || body.error === 'pricing-source-changed' ? 'changed' : 'failed')\n return\n }\n const body = await response.json() as PricingSyncResult\n if (body === null || typeof body !== 'object'\n || ![body.version, body.updatedAt, body.models, body.aliasPatterns, body.usdExchangeRate].every(value => typeof value === 'number' && Number.isFinite(value))) {\n throw new Error('unexpected pricing sync response')\n }\n pricingTableChanged()\n if (mounted.current) { setResult(body); setStatus('done') }\n } catch {\n if (mounted.current) setStatus('failed')\n } finally { running.current = false }\n }\n\n return <>\n <button type=\"button\" className={css.browse} disabled={disabled || dirty || status === 'running'}\n onClick={() => { void sync() }}>{t(status === 'running' ? 'card.pricingSync.running' : 'card.pricingSync.button')}</button>\n {dirty ? <p className={`${css.hint} ${css.syncFeedback}`}>{t('card.pricingSync.unsaved')}</p>\n : status === 'done' && result !== null ? <p className={`${css.note} ${css.syncFeedback}`} role=\"status\">\n {t('card.pricingSync.done', { version: String(result.version), models: String(result.models) })}</p>\n : status === 'failed' || status === 'changed' || status === 'migrating' ? <p className={`${css.failed} ${css.syncFeedback}`} role=\"alert\">\n {t(`card.pricingSync.${status}`)}</p> : null}\n </>\n}\n","/**\n * Range date picker (browser half): the filter bar's single date control —\n * one trigger showing the active day range plus a lightweight calendar\n * popover. The range is picked with two clicks: the first lands an anchor\n * (start or end, order does not matter), the second settles the range\n * (min/max sorted); month navigation keeps the anchor, so a range may span\n * months (navigate, click, navigate back, click). While an anchor is live,\n * hovering previews the pending range; Escape or an outside pointerdown\n * closes the popover and DISCARDS the unfinished anchor (the committed\n * filters never change on cancel). A clear affordance releases the range\n * back to unconstrained — the capability the two native date inputs it\n * replaces carried.\n *\n * The popover interaction copies QuotaButton's pattern verbatim (click\n * toggles, document pointerdown outside closes, Escape closes); the plate\n * styling mirrors its panel (menu background, inverted border, shadow,\n * z-index 100).\n *\n * @module token-usage/client/DateRangePicker\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { dayKeyOf, monthGrid, monthViewOf, shiftMonth } from './day.ts'\nimport type { MonthView } from './day.ts'\nimport styles from './DateRangePicker.module.css'\n\n/** Monday-first weekday header keys (index 0 = Monday). */\nconst WEEKDAY_KEYS = [\n 'calendar.weekday.0', 'calendar.weekday.1', 'calendar.weekday.2', 'calendar.weekday.3',\n 'calendar.weekday.4', 'calendar.weekday.5', 'calendar.weekday.6',\n] as const\n\n/** Props: the committed range ('' = unconstrained) and the change lift. */\nexport interface DateRangePickerProps {\n from: string\n to: string\n onChange: (next: { from: string; to: string }) => void\n t: TranslateNS<'token-usage'>\n}\n\n/** The month view the popover opens on: the range end, else its start, else today. */\nfunction initialView(from: string, to: string): MonthView {\n const focus = to !== '' ? to : from !== '' ? from : dayKeyOf(new Date())\n return monthViewOf(focus)\n}\n\n/**\n * Render the trigger + calendar popover.\n * @param props - the committed range, the change lift, and the locale seat.\n * @returns the inline wrapper holding the trigger and, while open, the panel.\n */\nexport function DateRangePicker({ from, to, onChange, t }: DateRangePickerProps): ReactNode {\n const rootRef = useRef<HTMLSpanElement>(null)\n const [open, setOpen] = useState(false)\n const [view, setView] = useState<MonthView>(() => initialView(from, to))\n // The first click's day key; null until it lands, cleared on close.\n const [anchor, setAnchor] = useState<string | null>(null)\n // The hovered day key while an anchor is live (range preview); else null.\n const [hovered, setHovered] = useState<string | null>(null)\n\n // Every close path funnels here: cancel discards the unfinished anchor\n // (only a second click or the clear button commits anything).\n const closePanel = (): void => {\n setOpen(false)\n setAnchor(null)\n setHovered(null)\n }\n\n // Opening resets the selection progress and lands on the focused month.\n const openPanel = (): void => {\n setView(initialView(from, to))\n setAnchor(null)\n setHovered(null)\n setOpen(true)\n }\n\n // Outside click / Escape close — QuotaButton'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 closePanel()\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') closePanel()\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 // The two-click state machine: first click anchors, second settles the\n // sorted range, commits it, and closes. Clicking an EARLIER day second\n // still yields from <= to (the order of the two clicks never matters).\n const pickDay = (day: string): void => {\n if (anchor === null) {\n setAnchor(day)\n return\n }\n const lo = anchor < day ? anchor : day\n const hi = anchor < day ? day : anchor\n closePanel()\n onChange({ from: lo, to: hi })\n }\n\n const clear = (): void => {\n closePanel()\n onChange({ from: '', to: '' })\n }\n\n // What the grid highlights: the pending anchor (previewing through the\n // hover when one is live) while selecting, else the committed range.\n const shown = anchor !== null\n ? {\n from: hovered !== null && hovered < anchor ? hovered : anchor,\n to: hovered !== null && hovered > anchor ? hovered : anchor,\n }\n : { from, to }\n const today = dayKeyOf(new Date())\n const summary = from !== '' && to !== ''\n ? `${from} ${t('filter.separator')} ${to}`\n : from !== ''\n ? from\n : to !== ''\n ? to\n : t('filter.allDates')\n\n return (\n <span ref={rootRef} className={styles['wrapper']}>\n <button\n type=\"button\"\n className={styles['trigger']}\n aria-label={t('filter.dateRange')}\n aria-expanded={open}\n onClick={() => { (open ? closePanel : openPanel)() }}\n >\n {summary}\n </button>\n {open\n ? (\n <div className={styles['panel']} role=\"dialog\" aria-label={t('filter.dateRange')}>\n <div className={styles['head']}>\n <button\n type=\"button\"\n className={styles['nav']}\n aria-label={t('calendar.prevMonth')}\n onClick={() => { setView(shiftMonth(view, -1)) }}\n >\n ‹\n </button>\n <span className={styles['monthTitle']}>\n {t('calendar.monthTitle', { year: String(view.year), month: String(view.month + 1) })}\n </span>\n <button\n type=\"button\"\n className={styles['nav']}\n aria-label={t('calendar.nextMonth')}\n onClick={() => { setView(shiftMonth(view, 1)) }}\n >\n ›\n </button>\n </div>\n <div className={styles['weekdays']}>\n {WEEKDAY_KEYS.map(key => <span key={key} className={styles['weekday']}>{t(key)}</span>)}\n </div>\n <div className={styles['grid']}>\n {monthGrid(view).map(cell => {\n if (!cell.inMonth) {\n // Neighbouring-month days render as blank placeholders so\n // the shown month's date texts stay unique.\n return <span key={`blank-${cell.day}`} className={styles['blank']} aria-hidden=\"true\" />\n }\n const classes = [styles['day']]\n if (cell.day === shown.from || cell.day === shown.to) classes.push(styles['daySelected'])\n else if (shown.from !== '' && cell.day > shown.from && cell.day < shown.to) classes.push(styles['dayInRange'])\n if (cell.day === today) classes.push(styles['dayToday'])\n return (\n <button\n key={cell.day}\n type=\"button\"\n className={classes.join(' ')}\n aria-label={cell.day}\n aria-pressed={cell.day === shown.from || cell.day === shown.to}\n aria-current={cell.day === today ? 'date' : undefined}\n onMouseEnter={() => { setHovered(cell.day) }}\n onMouseLeave={() => { setHovered(null) }}\n onClick={() => { pickDay(cell.day) }}\n >\n {Number(cell.day.slice(8))}\n </button>\n )\n })}\n </div>\n <div className={styles['foot']}>\n <button type=\"button\" className={styles['clear']} onClick={clear}>\n {t('filter.clear')}\n </button>\n </div>\n </div>\n )\n : null}\n </span>\n )\n}\n","/**\n * Menu select (browser half): the filter bar's themed dropdown — one\n * trigger button plus a menu popover. It replaces the native `<select>`,\n * whose UA-painted option list ignores every design token (the shell sets\n * no color-scheme on plugin content, so it renders unthemed), and pairs\n * with the DateRangePicker so all three filter controls share one popover\n * language.\n *\n * Keyboard follows the listbox idiom: opening (trigger click, Enter, or\n * its arrow keys) lands focus on the SELECTED option — scrolled to the\n * center like the native select — or the first one; ArrowUp/Down and\n * Home/End roam (options are tabIndex -1, so Tab skips the list);\n * Enter/Space commits the focused row; Escape closes and returns focus\n * to the trigger; committing closes and refocuses the trigger too. An\n * outside pointerdown closes without stealing focus. The option list\n * carries listbox/option semantics with the selection marked\n * (aria-selected plus a check).\n *\n * The popover interaction copies QuotaButton's pattern verbatim (click\n * toggles, document pointerdown outside closes, Escape closes); the plate\n * styling mirrors the date-range picker's panel.\n *\n * @module token-usage/client/MenuSelect\n */\n\nimport { useEffect, useRef, useState } from 'react'\nimport type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'\nimport styles from './MenuSelect.module.css'\n\n/** One selectable entry of the menu. */\nexport interface MenuOption {\n value: string\n label: string\n}\n\n/** Props: the committed value, the option list, and the change lift. */\nexport interface MenuSelectProps {\n value: string\n options: readonly MenuOption[]\n /** Accessible name for the trigger and the listbox popup. */\n ariaLabel: string\n onChange: (next: string) => void\n /** Stretch variant: shrinkable, capped, ellipsized (the model menu). */\n grow?: boolean\n}\n\n/**\n * Render the trigger + menu popover.\n * @param props - the committed value, options, name, and change lift.\n * @returns the inline wrapper holding the trigger and, while open, the list.\n */\nexport function MenuSelect({ value, options, ariaLabel, onChange, grow = false }: MenuSelectProps): ReactNode {\n const rootRef = useRef<HTMLSpanElement>(null)\n const triggerRef = useRef<HTMLButtonElement>(null)\n // One ref per option row; index-aligned with the options prop.\n const optionRefs = useRef<(HTMLButtonElement | null)[]>([])\n const [open, setOpen] = useState(false)\n // The row focus roams over (index into options); a ref, not state — the\n // DOM focus itself is the source of truth, this only remembers it for\n // Enter/Space and re-opening.\n const focusIndexRef = useRef(0)\n\n const close = (): void => {\n setOpen(false)\n triggerRef.current?.focus()\n }\n\n // Opening lands focus on the selected option (or the first), centered\n // in the list — native-select parity, so a long model list opens with\n // the current choice in view.\n const openMenu = (): void => {\n const selected = options.findIndex(option => option.value === value)\n focusIndexRef.current = selected >= 0 ? selected : 0\n setOpen(true)\n }\n\n // Outside pointerdown / Escape close — QuotaButton's pattern, one\n // document listener pair while open. The outside path does NOT steal\n // focus (the user is already interacting elsewhere); Escape refocuses\n // the trigger.\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') close()\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 // After the panel renders: focus the remembered row without scrolling,\n // then center it explicitly (a bare focus() would only kiss the edge).\n // scrollIntoView is guarded — jsdom does not implement it.\n useEffect(() => {\n if (!open) return\n const button = optionRefs.current[focusIndexRef.current]\n if (button === undefined || button === null) return\n button.focus({ preventScroll: true })\n if (typeof button.scrollIntoView === 'function') button.scrollIntoView({ block: 'center' })\n }, [open])\n\n const commit = (index: number): void => {\n const option = options[index]\n if (option === undefined) return\n close()\n onChange(option.value)\n }\n\n const moveFocus = (index: number): void => {\n const next = Math.max(0, Math.min(options.length - 1, index))\n focusIndexRef.current = next\n // A plain focus: the browser scrolls the newly focused row into view\n // with minimal movement, which is what roaming wants.\n optionRefs.current[next]?.focus()\n }\n\n // Roving keys on the panel (events bubble from the option buttons).\n // Enter/Space are handled here with preventDefault so the UA does not\n // synthesize a second click on the focused button.\n const onPanelKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>): void => {\n if (event.key === 'ArrowDown') {\n event.preventDefault()\n moveFocus(focusIndexRef.current + 1)\n } else if (event.key === 'ArrowUp') {\n event.preventDefault()\n moveFocus(focusIndexRef.current - 1)\n } else if (event.key === 'Home') {\n event.preventDefault()\n moveFocus(0)\n } else if (event.key === 'End') {\n event.preventDefault()\n moveFocus(options.length - 1)\n } else if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault()\n commit(focusIndexRef.current)\n }\n }\n\n // The trigger's arrow keys open the menu too (Enter/Space come for free\n // as button clicks).\n const onTriggerKeyDown = (event: ReactKeyboardEvent<HTMLButtonElement>): void => {\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n if (!open) openMenu()\n }\n }\n\n const selected = options.find(option => option.value === value)\n const triggerClass = [styles['trigger'], grow === true ? styles['grow'] : ''].join(' ').trim()\n\n return (\n <span ref={rootRef} className={styles['wrapper']}>\n <button\n type=\"button\"\n ref={triggerRef}\n className={triggerClass}\n aria-label={ariaLabel}\n aria-expanded={open}\n aria-haspopup=\"listbox\"\n onClick={() => { (open ? close() : openMenu()) }}\n onKeyDown={onTriggerKeyDown}\n >\n {selected?.label ?? value}\n </button>\n {open\n ? (\n <div\n className={styles['panel']}\n role=\"listbox\"\n aria-label={ariaLabel}\n onKeyDown={onPanelKeyDown}\n >\n {options.map((option, index) => {\n const isSelected = option.value === value\n const optionClass = [styles['option'], isSelected ? styles['optionSelected'] : ''].join(' ').trim()\n return (\n <button\n key={option.value}\n type=\"button\"\n role=\"option\"\n // Roving focus: only code moves focus into the list, so\n // the rows stay out of the Tab ring.\n tabIndex={-1}\n ref={element => { optionRefs.current[index] = element }}\n className={optionClass}\n aria-selected={isSelected}\n onClick={() => { commit(index) }}\n >\n <span className={styles['optionLabel']}>{option.label}</span>\n {isSelected ? <span className={styles['check']} aria-hidden=\"true\">✓</span> : null}\n </button>\n )\n })}\n </div>\n )\n : null}\n </span>\n )\n}\n","/**\n * The runtime-overhead card's row shape (browser half): one expanded-by-\n * default row per auxiliary kind — the row carries the kind's aggregate\n * (calls · cost · tokens) and discloses its per-model lines on toggle; the\n * total line sits beneath the list. The semantics are the retired table's\n * (same fold, same empty hints, same defensive read of a payload without\n * `aux`); only the shape moved from columns to rows.\n *\n * @module token-usage/client/OverheadRows\n */\n\nimport { useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AuxKind, AuxSummary, CostState } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { totalTokens } from './day.ts'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatTokens } from './format.ts'\nimport list from './UsageRows.module.css'\nimport styles from './OverheadRows.module.css'\n\n/**\n * Render the overhead rows: one disclosure row per kind, then the total\n * line. A summary without auxiliary requests — including an older host\n * payload with no `aux` field at all — renders the empty hint instead, so\n * the card keeps a stable body.\n * @param props - the aux layer of the summary (possibly absent), the cost\n * state, the display currency view, and the locale translator.\n */\nexport function OverheadRows({ aux, costState, view, t }: {\n aux: AuxSummary | undefined\n costState: CostState\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n // Which kinds are collapsed — inverted so the default is every kind\n // expanded (the user's pick): the aggregate row AND its per-model lines\n // show at once, a toggle folds the drill-in away. Each kind toggles\n // independently; switching tabs unmounts the section, which is the\n // natural reset. New kinds arriving on a refresh default to expanded.\n const [collapsedKinds, setCollapsedKinds] = useState<ReadonlySet<AuxKind>>(() => new Set())\n const toggleKind = (auxKind: AuxKind): void => {\n setCollapsedKinds(previous => {\n const next = new Set(previous)\n if (next.has(auxKind)) next.delete(auxKind)\n else next.add(auxKind)\n return next\n })\n }\n if (aux === undefined || aux.total.requests === 0) {\n return <p className={styles['muted']}>{t('aux.empty')}</p>\n }\n const costText = (cost: number): string =>\n costsAvailable(costState) ? formatCost(cost, view) : '—'\n /** One drill-in line: model name ↔ calls · cost · tokens. */\n const modelLine = (model: string, requests: number, cost: number, tokens: number): ReactNode => (\n <span className={styles['dline']}>\n <span className={styles['dmodelName']}>{model}</span>\n <span>\n {t('aux.requestCount', { count: requests.toLocaleString() })}\n {' · '}\n {costText(cost)}\n {' · '}\n {formatTokens(tokens)}\n </span>\n </span>\n )\n const content = (\n <>\n <div className={list['rows']} role=\"list\" aria-label={t('aux.tab')}>\n {(aux.byKind ?? []).map(kindRow => {\n const expanded = !collapsedKinds.has(kindRow.auxKind)\n return (\n <div className={styles['orow']} role=\"listitem\" key={kindRow.auxKind}>\n <div className={styles['orowTop']}>\n {/* The kind row is the parent aggregate AND its own\n * disclosure toggle: chevron + category name in one\n * button (`aria-expanded` carries the state). */}\n <button\n type=\"button\"\n className={styles['kindToggle']}\n aria-expanded={expanded}\n onClick={() => toggleKind(kindRow.auxKind)}\n >\n <span className={styles['chevron']} aria-hidden=\"true\">▸</span>\n {t(`aux.kind.${kindRow.auxKind}`)}\n </button>\n <span className={styles['onums']}>\n {t('aux.requestCount', { count: kindRow.totals.requests.toLocaleString() })}\n {' · '}\n <span className={styles['onumsCost']}>{costText(kindRow.cost)}</span>\n {' · '}\n {formatTokens(totalTokens(kindRow.totals))}\n </span>\n </div>\n {expanded\n ? (\n <div className={styles['adetail']}>\n {(kindRow.byModel ?? []).map(modelRow => (\n <span key={`${kindRow.auxKind}:${modelRow.model}`}>\n {modelLine(modelRow.model, modelRow.totals.requests, modelRow.cost, totalTokens(modelRow.totals))}\n </span>\n ))}\n </div>\n )\n : null}\n </div>\n )\n })}\n </div>\n <div className={styles['asum']}>\n <span>{t('aux.totalCount', { count: aux.total.requests.toLocaleString() })}</span>\n <span>\n <span className={styles['onumsCost']}>{costText(aux.cost)}</span>\n {' · '}\n {formatTokens(totalTokens(aux.total))}\n </span>\n </div>\n </>\n )\n return content\n}\n","/**\n * Project aggregation over root-session rows, shared by the host's full\n * project dimension and the browser's older-host compatibility fallback.\n * The host folds before truncating the session list.\n *\n * @module token-usage/project-rows\n */\n\nimport type { ProjectUsageRow, SessionUsageRow, UsageTotals } from './wire.ts'\n\nfunction totalTokens(totals: UsageTotals): number {\n return totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens\n}\n\n/** The last path segment of a directory, on either separator. */\nexport function dirTailOf(cwd: string): string {\n const parts = cwd.split(/[\\\\/]/u).filter(part => part !== '')\n return parts[parts.length - 1] ?? cwd\n}\n\n/** Element-wise totals sum: the counted fields add, the optional ones\n * treat absence as 0 and stay absent only while both sides lack them. */\nfunction addTotals(left: UsageTotals, right: UsageTotals): UsageTotals {\n const sum: UsageTotals = {\n requests: left.requests + right.requests,\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n cacheReadTokens: left.cacheReadTokens + right.cacheReadTokens,\n cacheWriteTokens: left.cacheWriteTokens + right.cacheWriteTokens,\n }\n const compactions = (left.compactions ?? 0) + (right.compactions ?? 0)\n if (compactions > 0 || left.compactions !== undefined || right.compactions !== undefined) {\n sum.compactions = compactions\n }\n const failures = (left.failures ?? 0) + (right.failures ?? 0)\n if (failures > 0 || left.failures !== undefined || right.failures !== undefined) {\n sum.failures = failures\n }\n if (left.failuresByCode !== undefined || right.failuresByCode !== undefined) {\n const byCode: Record<string, number> = {}\n for (const [code, count] of Object.entries(left.failuresByCode ?? {})) byCode[code] = count\n for (const [code, count] of Object.entries(right.failuresByCode ?? {})) {\n byCode[code] = (byCode[code] ?? 0) + count\n }\n sum.failuresByCode = byCode\n }\n for (const key of ['perfLatencyMsSum', 'perfLatencyCount', 'perfStreamTpsSum', 'perfStreamFirstMsSum', 'perfStreamCount'] as const) {\n if (left[key] !== undefined || right[key] !== undefined) sum[key] = (left[key] ?? 0) + (right[key] ?? 0)\n }\n return sum\n}\n\n/**\n * Fold session rows into one row per directory tail, token-descending (the\n * dashboard's relative bars take the first row as their 100%). The tail is\n * the bucket key — two different full paths ending in the same segment read\n * as one project here, matching the demo's semantics. Within a bucket the\n * first-seen cwd rides along as the representative full path. The input\n * order is preserved inside a bucket (the served rows arrive cost-sorted).\n * @param rows - subtree-folded root sessions; the host supplies the full\n * set, not the truncated session list.\n */\nexport function projectRowsOf(rows: readonly SessionUsageRow[]): ProjectUsageRow[] {\n const buckets = new Map<string, ProjectUsageRow>()\n for (const row of rows) {\n const name = row.cwd === undefined ? '' : dirTailOf(row.cwd)\n const bucket = buckets.get(name)\n if (bucket === undefined) {\n buckets.set(name, {\n name,\n ...(row.cwd === undefined ? {} : { cwd: row.cwd }),\n sessionCount: 1,\n totals: { ...row.totals },\n cost: row.cost,\n })\n continue\n }\n if (bucket.cwd === undefined && row.cwd !== undefined) bucket.cwd = row.cwd\n bucket.sessionCount += 1\n bucket.totals = addTotals(bucket.totals, row.totals)\n bucket.cost += row.cost\n }\n return [...buckets.values()].sort((left, right) => totalTokens(right.totals) - totalTokens(left.totals))\n}\n","/**\n * The dashboards' flat row lists (browser half): one component, four\n * shapes — `project` (directory-tail folds), `model` (the priced rows),\n * `session` (two-line rows) and `provider` (the per-route rows with the\n * unattributed remainder sunk to the bottom). All four read the same\n * single-line grammar of the v3 demo: name | relative bar (projects /\n * models / providers only) | total tokens · cache share | cost; sessions\n * swap the bar for a second identity line (directory · activity) under the\n * same figures cells, all four lists rendering one figures style everywhere\n * (no hover affordance — a former four-bucket popup read as clutter and\n * went).\n *\n * The relative bar scales to\n * the active sort's own measure — tokens while sorted by tokens, billed cost\n * while sorted by cost — so the bars never contradict the order they sit\n * in. Rows arrive FINAL from the host route (folded, sorted, truncated);\n * this component only re-organizes presentation. The Ctrl affordances move\n * with the rows: Ctrl+click on a listed session opens it (dashed\n * underline), Ctrl+click on a model toggles the section's model filter to\n * just that model.\n *\n * @module token-usage/client/UsageRows\n */\n\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { CostState, CostedModelRow, CostedProviderRow, ModelPerf, PricingTable, SessionUsageRow, UsageTotals } from '../wire.ts'\nimport { MIN_PERF_SAMPLES } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { dayKeyOf, totalTokens } from './day.ts'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatSpeed, formatTokens, formatTtft, hitRateDisplay, providerLabel } from './format.ts'\nimport { ModelAssociationBadge, UnpricedModelTag } from './PricingAssociations.tsx'\nimport type { ProjectUsageRow } from './project-rows.ts'\nimport { dirTailOf } from './project-rows.ts'\nimport styles from './UsageRows.module.css'\n\n/** Which row shape the list renders. */\nexport type UsageRowsKind = 'project' | 'model' | 'session' | 'provider'\n\n/** The row lists' controlled sort. `tokens` on projects passes the fold's\n * native order through; `cost` on sessions passes the served order\n * through; models re-sort under both picks (they arrive request-count\n * descending), ties broken by name. Sorting never carries the performance\n * view — that is a content switch ({@link UsageRowsProps.perfView}), not\n * a third pick. */\nexport type RowSort = 'tokens' | 'cost' | 'recent'\n\n/** The label of one sort pick. */\nfunction sortLabelOf(sort: RowSort, t: TranslateNS<'token-usage'>): string {\n return sort === 'tokens' ? t('sort.tokens') : sort === 'cost' ? t('stat.cost') : t('session.lastActive')\n}\n\n/** Sort toggle rendered in a card head / above a tab's list. Controlled —\n * the section owns the state, so the page and the panel keep independent\n * picks. */\nexport function RowSortControl({ value, options, onChange, ariaLabel, t, compact = false }: {\n value: RowSort\n options: readonly RowSort[]\n onChange: (next: RowSort) => void\n ariaLabel: string\n t: TranslateNS<'token-usage'>\n compact?: boolean\n}): ReactNode {\n return (\n <div className={compact ? `${styles['segmented']} ${styles['controlCompact']}` : styles['segmented']} role=\"group\" aria-label={ariaLabel}>\n {options.map(option => (\n <button\n key={option}\n type=\"button\"\n className={value === option ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={value === option}\n onClick={() => onChange(option)}\n >\n {sortLabelOf(option, t)}\n </button>\n ))}\n </div>\n )\n}\n\n/** The performance view toggle (model card head): a view switch, not a\n * third sort pick — pressed, the card shows the speed rows and the sort\n * control yields (the performance order is its own definition: ranked\n * rows by mean speed, the dimmed ones sunk; there is no second way to\n * order them). */\nexport function PerfToggle({ pressed, onToggle, t, compact = false }: {\n pressed: boolean\n onToggle: (next: boolean) => void\n t: TranslateNS<'token-usage'>\n compact?: boolean\n}): ReactNode {\n return (\n <button\n type=\"button\"\n className={[styles['perfToggle'], pressed ? styles['perfOn'] : '', compact ? styles['perfCompact'] : ''].filter(Boolean).join(' ')}\n aria-pressed={pressed}\n aria-label={t('perf.toggle')}\n onClick={() => onToggle(!pressed)}\n >\n <span className={styles['perfGauge']} aria-hidden={true}>◷</span>\n {t('perf.toggle')}\n </button>\n )\n}\n\n/** Whether Ctrl (or ⌘) is held right now: the jump affordances exist only\n * while it is, so plain clicks keep the rows inert. `blur` resets — a focus\n * loss can swallow the keyup and strand the state on. */\nfunction useCtrlHeld(): boolean {\n const [ctrlHeld, setCtrlHeld] = useState(false)\n useEffect(() => {\n const down = (event: KeyboardEvent): void => { if (event.key === 'Control' || event.key === 'Meta') setCtrlHeld(true) }\n const up = (event: KeyboardEvent): void => { if (event.key === 'Control' || event.key === 'Meta') setCtrlHeld(false) }\n const move = (event: MouseEvent): void => {\n const active = event.ctrlKey || event.metaKey\n setCtrlHeld(previous => (previous === active ? previous : active))\n }\n const blur = (): void => setCtrlHeld(false)\n window.addEventListener('keydown', down)\n window.addEventListener('keyup', up)\n window.addEventListener('mousemove', move)\n window.addEventListener('blur', blur)\n return () => {\n window.removeEventListener('keydown', down)\n window.removeEventListener('keyup', up)\n window.removeEventListener('mousemove', move)\n window.removeEventListener('blur', blur)\n }\n }, [])\n return ctrlHeld\n}\n\n/** A short session-id fallback: the leading chunk is usually enough to\n * tell sessions apart when no title ever landed. */\nfunction shortIdOf(sessionId: string): string {\n return sessionId.length > 8 ? `${sessionId.slice(0, 8)}…` : sessionId\n}\n\n/** The unattributed row's hover tooltip: an intro line, then the known\n * reasons a record can carry no route key as a numbered list, each line\n * indented by two spaces (the bubble renders `pre`, so the indent shows).\n * The list is the full closed set — deleted logs, pre-field history, and\n * bypass calls the host never gives a route key — so the reader sees this\n * row is expected, not a bug. */\nfunction unattributedTooltip(t: TranslateNS<'token-usage'>): string {\n const causes = [\n t('byProvider.cause.deletedLog'),\n t('byProvider.cause.preField'),\n t('byProvider.cause.bypass'),\n ]\n return [t('byProvider.cause.intro'), ...causes.map((cause, index) => ` ${index + 1}. ${cause}`)].join('\\n')\n}\n\n/** Relative last-active label (「3 小时前」): minutes inside the first hour,\n * hours inside the first day, days beyond. */\nfunction relativeTimeOf(time: number, t: TranslateNS<'token-usage'>): string {\n const minutes = Math.max(1, Math.floor((Date.now() - time) / 60_000))\n if (minutes < 60) return t('time.minutesAgo', { count: String(minutes) })\n const hours = Math.floor(minutes / 60)\n if (hours < 24) return t('time.hoursAgo', { count: String(hours) })\n return t('time.daysAgo', { count: String(Math.floor(hours / 24)) })\n}\n\n/** Props for the flat row list. Only the array matching `kind` is read;\n * the optional seats (session jump, model filter, price dialog) are absent\n * on tests and hosts without them, and the rows then render inert. */\nexport interface UsageRowsProps {\n kind: UsageRowsKind\n /** `kind: 'project'` — the directory-tail folds. */\n projectRows?: readonly ProjectUsageRow[] | undefined\n /** `kind: 'model'` — the priced per-model rows. */\n modelRows?: readonly CostedModelRow[] | undefined\n /** `kind: 'session'` — the served per-session rows (final order = cost). */\n sessionRows?: readonly SessionUsageRow[] | undefined\n /** `kind: 'provider'` — the priced per-provider rows; `''` is the\n * unattributed remainder row. */\n providerRows?: readonly CostedProviderRow[] | undefined\n /** Provider rows only: the route-key → display-name registry; a key\n * without an entry falls back to the key itself. */\n providerNames?: Readonly<Record<string, string>> | undefined\n /** The controlled sort pick (see {@link RowSort}); the default depends\n * on the kind — `tokens` on project/model, `cost` on session. Ignored\n * while `perfView` is set. */\n sort?: RowSort | undefined\n /** Model rows only: the performance view is up — the figures cells read\n * the speed means, the order is speed-fixed (ranked rows first, the\n * dimmed ones sunk), and the sort pick yields until toggled off. */\n perfView?: boolean | undefined\n /** The pricing table: which models are priced (name is the price\n * affordance) and the rates a model row's cost splits against. */\n pricing?: PricingTable | undefined\n /** The cost layer's state; not `ready`, every cost cell reads `—`. */\n costState?: CostState | undefined\n /** Currency display view (symbol + rate). */\n view: CurrencyView\n /** Locale function. */\n t: TranslateNS<'token-usage'>\n /** Session jump seats: whether the controller lists a session, and the\n * open callback (the parent closes its panel on success). */\n sessionListed?: ((id: string) => boolean) | undefined\n onSessionOpen?: ((id: string) => void) | undefined\n /** Ctrl+click on a model row: toggle the section's model filter. */\n onToggleModel?: ((model: string) => void) | undefined\n /** Plain click on a priced model's name: open the price dialog. */\n onModelName?: ((model: string) => void) | undefined\n}\n\n/**\n * Render one flat row list. The list is the height-capped scroll container\n * (scrollbar appears while scrolling, fades 800ms after it stops).\n */\nexport function UsageRows({\n kind,\n projectRows,\n modelRows,\n sessionRows,\n providerRows,\n providerNames,\n sort,\n perfView,\n pricing,\n costState,\n view,\n t,\n sessionListed,\n onSessionOpen,\n onToggleModel,\n onModelName,\n}: UsageRowsProps): ReactNode {\n const ctrlHeld = useCtrlHeld()\n // Scrollbar fade: add the class on scroll, drop it 800ms after the last\n // event; the timer dies with the component.\n const scrollRef = useRef<HTMLDivElement | null>(null)\n const scrollTimer = useRef<number | undefined>(undefined)\n useEffect(() => () => window.clearTimeout(scrollTimer.current), [])\n const handleScroll = (): void => {\n const box = scrollRef.current\n const cls = styles['scrolling']\n if (box === null || cls === undefined) return\n box.classList.add(cls)\n window.clearTimeout(scrollTimer.current)\n scrollTimer.current = window.setTimeout(() => {\n box.classList.remove(cls)\n }, 800)\n }\n\n // The rendered set for this kind under the active pick. Straight-through\n // where the native order already matches (projects ship tokens-desc,\n // sessions cost-desc); models always re-sort (they arrive request-count\n // descending), ties broken by name for a stable order. The performance\n // view replaces the pick entirely — its order is speed-fixed.\n const perfMode = perfView === true && kind === 'model'\n const active = sort ?? (kind === 'session' ? 'cost' : 'tokens')\n const rows = useMemo<readonly (ProjectUsageRow | CostedModelRow | SessionUsageRow | CostedProviderRow)[]>(() => {\n const base = kind === 'project' ? projectRows : kind === 'model' ? modelRows : kind === 'session' ? sessionRows : providerRows\n if (base === undefined) return []\n if (kind === 'session') {\n if (active === 'cost') return base\n const sessions = [...base] as SessionUsageRow[]\n return sessions.sort(active === 'recent'\n ? (left, right) => right.lastTime - left.lastTime || (left.sessionId < right.sessionId ? -1 : 1)\n : (left, right) => totalTokens(right.totals) - totalTokens(left.totals) || (left.sessionId < right.sessionId ? -1 : 1))\n }\n if (kind === 'project') {\n if (active === 'tokens') return base\n return [...(base as readonly ProjectUsageRow[])].sort((left, right) => right.cost - left.cost || (left.name < right.name ? -1 : 1))\n }\n if (kind === 'provider') {\n // Providers arrive request-count descending with the unattributed\n // remainder sunk; both picks re-sort by their own measure and keep\n // that sink — the remainder is a reconciliation row, not a provider.\n const unattributedLast = (row: CostedProviderRow): number => row.provider === '' ? 1 : 0\n return [...(base as readonly CostedProviderRow[])].sort((left, right) =>\n unattributedLast(left) - unattributedLast(right)\n || (active === 'cost'\n ? right.cost - left.cost\n : totalTokens(right.totals) - totalTokens(left.totals))\n || (left.provider < right.provider ? -1 : 1))\n }\n const models = [...base] as CostedModelRow[]\n if (perfMode) {\n // Speed ranking over the streaming samples. A row without enough\n // samples (or any timing) cannot rank honestly, so it sinks below\n // the ranked ones, name-ordered — the same rows drop their bar.\n const ranked = (row: CostedModelRow): boolean =>\n row.perf !== undefined && row.perf.samples >= MIN_PERF_SAMPLES\n return models.sort((left, right) => {\n const leftRanked = ranked(left)\n const rightRanked = ranked(right)\n if (leftRanked !== rightRanked) return leftRanked ? -1 : 1\n if (leftRanked && rightRanked) {\n return right.perf!.tokensPerSec - left.perf!.tokensPerSec || (left.model < right.model ? -1 : 1)\n }\n return left.model < right.model ? -1 : 1\n })\n }\n return models.sort(active === 'tokens'\n ? (left, right) => totalTokens(right.totals) - totalTokens(left.totals) || (left.model < right.model ? -1 : 1)\n : (left, right) => right.cost - left.cost || (left.model < right.model ? -1 : 1))\n }, [kind, projectRows, modelRows, sessionRows, providerRows, active, perfMode])\n\n // The bar scale: the tallest row of the *rendered* set is 100%,\n // measured in the active unit — a cost-sorted list bars by cost, the\n // performance view by mean speed (ranked rows only: the dimmed\n // low-sample rows drop their bar and must not stretch the scale), or\n // the bars would contradict the order they sit in. Zero renders\n // zero-width bars (never NaN). The provider list follows the same\n // rule for its unattributed remainder: it is the difference between\n // the named routes and the top line, not a route — it drops its bar\n // and must not stretch the scale the named routes are drawn against.\n const barValueOf = (row: ProjectUsageRow | CostedModelRow | SessionUsageRow | CostedProviderRow): number =>\n perfMode ? ('perf' in row && row.perf !== undefined && row.perf.samples >= MIN_PERF_SAMPLES ? row.perf.tokensPerSec : 0)\n : kind === 'provider' && (row as CostedProviderRow).provider === '' ? 0\n : active === 'cost' ? row.cost\n : totalTokens(row.totals)\n const barMax = useMemo(() => {\n let max = 0\n for (const row of rows) {\n const value = barValueOf(row)\n if (value > max) max = value\n }\n return max\n }, [rows, active])\n\n const costText = (cost: number): string =>\n costsAvailable(costState) ? formatCost(cost, view) : '—'\n\n /** The figures cell: total tokens · cache share, right-aligned in its\n * fixed column. No hover affordance — the user read the popup as\n * clutter on every list, so the cell is plain. */\n const numsCell = (totals: UsageTotals): ReactNode => {\n const hit = hitRateDisplay(totals)\n return (\n <span className={styles['rowNums']}>\n {formatTokens(totalTokens(totals))}\n {' · '}\n {t('stat.cacheRead')}\n {' '}\n {hit.text}\n </span>\n )\n }\n\n /** The performance figures cell: mean speed (bold) · first token · mean\n * request latency · timed request count over one compact line, the grammar\n * every figures cell reads. Below the streaming-sample threshold the\n * cell dims to speed + 「样本不足」, and no timing at all renders its\n * own dim label. Untimed requests never count as performance samples.\n * No hover affordance. */\n const perfCell = (perf: ModelPerf | undefined): ReactNode => {\n const count = t('perf.requestCount', { count: String(perf?.timedRequests ?? 0) })\n if (perf === undefined) {\n return <span className={`${styles['perfNums']} ${styles['perfDim']}`}>{t('perf.noTiming')} · {count}</span>\n }\n const speed = `${formatSpeed(perf.tokensPerSec)} tok/s`\n if (perf.samples < MIN_PERF_SAMPLES) {\n return (\n <span className={`${styles['perfNums']} ${styles['perfDim']}`}>\n <b>{speed}</b>\n {' · '}\n {t('perf.lowSamples')}\n {' · '}\n {count}\n </span>\n )\n }\n return (\n <span className={styles['perfNums']}>\n <b>{speed}</b>\n {' · '}\n {t('perf.first')}\n {' '}\n {formatTtft(perf.firstTokenMs)}\n {' · '}\n {t('perf.avgLatency')}\n {' '}\n {formatTtft(perf.latencyMs)}\n {' · '}\n {count}\n </span>\n )\n }\n\n const ariaLabel = kind === 'project' ? t('byProject.title')\n : kind === 'model' ? t('byModel.title')\n : kind === 'session' ? t('bySession.title') : t('byProvider.title')\n\n return (\n <div className={styles['rows']} ref={scrollRef} onScroll={handleScroll} role=\"list\" aria-label={ariaLabel}>\n {rows.length === 0\n ? <div className={styles['empty']}>{t('chart.empty')}</div>\n : rows.map(row => {\n if (kind === 'project') {\n const project = row as ProjectUsageRow\n return (\n <div className={styles['row']} role=\"listitem\" key={project.name === '' ? '\\u0000' : project.name}>\n <span className={styles['rowName']} title={project.cwd ?? project.name}>\n {project.name === '' ? t('session.untitledDir') : project.name}\n </span>\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(project) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n {numsCell(project.totals)}\n <span className={styles['rowCost']}>{costText(project.cost)}</span>\n </div>\n )\n }\n if (kind === 'model') {\n const model = row as CostedModelRow\n const rules = pricing?.[model.model]\n const filterJump = ctrlHeld && onToggleModel !== undefined\n // Under the performance view a row that cannot rank honestly\n // (too few streaming samples, or no timing) drops its bar and\n // lets the name take the width.\n const perfRanked = model.perf !== undefined && model.perf.samples >= MIN_PERF_SAMPLES\n return (\n <div className={styles['row']} role=\"listitem\" key={model.model}>\n <span className={perfMode && !perfRanked ? `${styles['rowName']} ${styles['nameGrow']}` : styles['rowName']}>\n <span className={styles['nameLine']}>\n {rules !== undefined\n ? (\n // Same affordance as the per-model table: the\n // name opens the price dialog — unless Ctrl is\n // held, when it toggles the model filter instead.\n <button\n type=\"button\"\n className={filterJump ? `${styles['nameText']} ${styles['jumpable']}` : styles['nameText']}\n title={filterJump ? t('model.ctrlHint') : undefined}\n aria-label={filterJump ? t('model.ctrlHint') : t('pricing.view', { model: model.model })}\n onClick={filterJump\n ? event => {\n event.preventDefault()\n onToggleModel?.(model.model)\n }\n : () => onModelName?.(model.model)}\n >\n {model.model}\n </button>\n )\n : <span className={styles['nameText']}>{model.model}</span>}\n {rules !== undefined ? null : <UnpricedModelTag model={model.model} t={t} />}\n <ModelAssociationBadge model={model.model} t={t} />\n </span>\n </span>\n {perfMode\n ? (perfRanked\n ? (\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(model) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n )\n : null)\n : (\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(model) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n )}\n {/* The performance view swaps the figures cell for the\n * speed means and drops the cost column — the row ends at\n * its figures, the same shape the demo pinned. */}\n {perfMode ? perfCell(model.perf) : numsCell(model.totals)}\n {perfMode\n ? null\n : <span className={styles['rowCost']}>{rules !== undefined ? costText(model.cost) : '—'}</span>}\n </div>\n )\n }\n if (kind === 'provider') {\n const provider = row as CostedProviderRow\n const unattributed = provider.provider === ''\n return (\n <div className={styles['row']} role=\"listitem\" key={unattributed ? '\\u0000' : provider.provider}>\n <span\n className={unattributed ? `${styles['rowName']} ${styles['nameDim']}` : styles['rowName']}\n title={unattributed ? undefined : provider.provider}\n >\n <span className={styles['nameLine']}>\n {unattributed\n ? (\n <span className={styles['hintWrap']}>\n <Tooltip label={unattributedTooltip(t)} side=\"bottom\" delayMs={100}>\n <span\n className={styles['nameText']}\n aria-label={t('byProvider.unattributed')}\n tabIndex={0}\n >\n {t('byProvider.unattributed')}\n <span className={styles['nameHint']} aria-hidden={true}>?</span>\n </span>\n </Tooltip>\n </span>\n )\n : <span className={styles['nameText']}>{providerLabel(provider.provider, providerNames)}</span>}\n </span>\n </span>\n <span className={styles['track']}>\n {barMax > 0\n ? (\n <span\n className={styles['fill']}\n style={{ width: `${(barValueOf(provider) / barMax) * 100}%` }}\n />\n )\n : null}\n </span>\n {numsCell(provider.totals)}\n <span className={styles['rowCost']}>{costText(provider.cost)}</span>\n </div>\n )\n }\n const session = row as SessionUsageRow\n // A session row is jumpable when the controller lists it; the\n // click re-checks through onSessionOpen (the list may have moved\n // between hover and click).\n const jump = ctrlHeld && sessionListed !== undefined && onSessionOpen !== undefined && sessionListed(session.sessionId)\n return (\n <div className={`${styles['row']} ${styles['srow']}`} role=\"listitem\" key={session.sessionId}>\n {/* The top line reads like every other row: name | total\n * tokens · cache share | cost (the same figures cell, same\n * hover tooltip — no cost row, no model mix to apportion\n * against). The second line keeps directory · activity. */}\n <div className={styles['rowTop']}>\n <span className={styles['rowName']}>\n <span className={styles['nameLine']}>\n <button\n type=\"button\"\n className={jump ? `${styles['nameText']} ${styles['jumpable']}` : styles['nameText']}\n title={jump ? t('session.openHint') : undefined}\n onClick={jump || (ctrlHeld && onSessionOpen !== undefined)\n ? event => {\n event.preventDefault()\n onSessionOpen?.(session.sessionId)\n }\n : undefined}\n >\n {session.title !== undefined\n ? session.title\n : `${shortIdOf(session.sessionId)} · ${dayKeyOf(new Date(session.firstTime))} – ${dayKeyOf(new Date(session.lastTime))}`}\n </button>\n {session.childCount !== undefined && session.childCount > 0\n ? (\n <span\n className={styles['badge']}\n aria-label={t('view.subagents.nested', { count: String(session.childCount) })}\n >\n {t('view.subagents.nested', { count: String(session.childCount) })}\n </span>\n )\n : null}\n </span>\n </span>\n {numsCell(session.totals)}\n <span className={styles['rowCost']}>{costText(session.cost)}</span>\n </div>\n <div className={styles['rowSub']}>\n {session.cwd === undefined ? t('session.untitledDir') : dirTailOf(session.cwd)}\n {' · '}\n {relativeTimeOf(session.lastTime, t)}\n </div>\n </div>\n )\n })}\n </div>\n )\n}\n","/**\n * The main page's dashboard (browser half): the equal-height cards in a\n * two-column grid — projects | sessions, models | providers, runtime\n * overhead on the last row — each a card head (title + count, the session\n * head carrying the sort) over the same flat row lists the settings\n * panel's tabs use. The runtime-overhead card is the scroll/flash target\n * of the composite metric card's overhead pill.\n *\n * @module token-usage/client/DashboardCards\n */\n\nimport type { RefObject } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AuxSummary, CostState, CostedModelRow, CostedProviderRow, PricingTable, SessionUsageRow } from '../wire.ts'\nimport { OverheadRows } from './OverheadRows.tsx'\nimport { UsageRows, RowSortControl, PerfToggle } from './UsageRows.tsx'\nimport type { RowSort } from './UsageRows.tsx'\nimport type { ProjectUsageRow } from './project-rows.ts'\nimport type { CurrencyView } from './format.ts'\nimport styles from './DashboardCards.module.css'\n\n/** The cards' fixed sort options: projects, models and providers pick\n * between token size and billed cost; sessions add last activity. The\n * models' performance view is a separate head toggle, not a sort pick. */\nconst SORT_PROJECT: readonly RowSort[] = ['tokens', 'cost']\nconst SORT_SESSION: readonly RowSort[] = ['tokens', 'cost', 'recent']\nconst SORT_MODEL: readonly RowSort[] = ['tokens', 'cost']\nconst SORT_PROVIDER: readonly RowSort[] = ['tokens', 'cost']\n\n/** Props for the four-card dashboard. Every list arrives final from the\n * section; the seats (session jump, model filter, price dialog) pass\n * through to the rows. */\nexport interface DashboardCardsProps {\n /** The directory-tail folds (projects card). */\n projectRows: readonly ProjectUsageRow[]\n /** The priced per-model rows (models card). */\n modelRows: readonly CostedModelRow[]\n /** The served per-session rows (sessions card). */\n sessionRows: readonly SessionUsageRow[]\n /** The three lists' controlled sorts (tokens/cost; sessions add last\n * activity). */\n projectSort: RowSort\n onProjectSortChange: (next: RowSort) => void\n modelSort: RowSort\n onModelSortChange: (next: RowSort) => void\n /** The models card's performance view (a content switch next to the\n * sort control, not a sort pick); up, the card reads the speed rows\n * and the sort control yields its seat. */\n modelPerfView: boolean\n onModelPerfToggle: (next: boolean) => void\n /** The priced per-provider rows (providers card); `''` is the\n * unattributed remainder row. */\n providerRows: readonly CostedProviderRow[]\n /** Route key → display name for the provider rows. */\n providerNames: Readonly<Record<string, string>> | undefined\n providerSort: RowSort\n onProviderSortChange: (next: RowSort) => void\n sessionSort: RowSort\n onSessionSortChange: (next: RowSort) => void\n /** The auxiliary layer (overhead card; absent renders the empty hint). */\n aux: AuxSummary | undefined\n pricing: PricingTable\n costState: CostState\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n /** Seats passed through to the row lists (absent on bare hosts). */\n sessionListed?: ((id: string) => boolean) | undefined\n onSessionOpen?: ((id: string) => void) | undefined\n onToggleModel?: ((model: string) => void) | undefined\n onModelName?: ((model: string) => void) | undefined\n /** The overhead card's ref: the metric card's pill scrolls here. */\n overheadCardRef: RefObject<HTMLDivElement>\n /** True while the overhead card flashes (pill just clicked). */\n overheadFlash: boolean\n}\n\n/**\n * Render the dashboard: projects | sessions on the first row, models |\n * providers on the second, runtime overhead on the last. The lists cap\n * their own height and scroll inside the cards.\n */\nexport function DashboardCards({\n projectRows,\n modelRows,\n sessionRows,\n projectSort,\n onProjectSortChange,\n modelSort,\n onModelSortChange,\n modelPerfView,\n onModelPerfToggle,\n providerRows,\n providerNames,\n providerSort,\n onProviderSortChange,\n sessionSort,\n onSessionSortChange,\n aux,\n pricing,\n costState,\n view,\n t,\n sessionListed,\n onSessionOpen,\n onToggleModel,\n onModelName,\n overheadCardRef,\n overheadFlash,\n}: DashboardCardsProps): ReactNode {\n // The unattributed remainder is the difference between the named routes\n // and the top line, not a route: it never counts as a provider.\n const namedProviderCount = providerRows.filter(row => row.provider !== '').length\n return (\n <div className={styles['grid2']}>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('board.projects')}\n <span className={styles['panelCount']}>\n {projectSort === 'cost'\n ? t('board.byCost', { count: projectRows.length.toLocaleString() })\n : t('board.byTokens', { count: projectRows.length.toLocaleString() })}\n </span>\n </span>\n <RowSortControl\n value={projectSort}\n options={SORT_PROJECT}\n onChange={onProjectSortChange}\n ariaLabel={t('board.projects')}\n t={t}\n />\n </div>\n <UsageRows\n kind=\"project\"\n projectRows={projectRows}\n sort={projectSort}\n pricing={pricing}\n costState={costState}\n view={view}\n t={t}\n />\n </div>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('board.sessions')}\n <span className={styles['panelCount']}>\n {t('board.sessionsCount', { count: sessionRows.length.toLocaleString() })}\n </span>\n </span>\n <RowSortControl\n value={sessionSort}\n options={SORT_SESSION}\n onChange={onSessionSortChange}\n ariaLabel={t('board.sessions')}\n t={t}\n />\n </div>\n <UsageRows\n kind=\"session\"\n sessionRows={sessionRows}\n sort={sessionSort}\n costState={costState}\n view={view}\n t={t}\n sessionListed={sessionListed}\n onSessionOpen={onSessionOpen}\n />\n </div>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelHeadLeft']}>\n <span className={styles['panelTitle']}>\n {t('board.models')}\n <span className={styles['panelCount']}>\n {modelPerfView\n ? t('board.bySpeed', { count: modelRows.length.toLocaleString() })\n : modelSort === 'cost'\n ? t('board.byCost', { count: modelRows.length.toLocaleString() })\n : t('board.byTokens', { count: modelRows.length.toLocaleString() })}\n </span>\n </span>\n </span>\n <span className={styles['panelHeadRight']}>\n <span className={modelPerfView ? styles['headHidden'] : undefined}>\n <RowSortControl\n value={modelSort}\n options={SORT_MODEL}\n onChange={onModelSortChange}\n ariaLabel={t('board.models')}\n t={t}\n />\n </span>\n <PerfToggle pressed={modelPerfView} onToggle={onModelPerfToggle} t={t} />\n </span>\n </div>\n <UsageRows\n kind=\"model\"\n modelRows={modelRows}\n sort={modelSort}\n perfView={modelPerfView}\n pricing={pricing}\n costState={costState}\n view={view}\n t={t}\n onToggleModel={onToggleModel}\n onModelName={onModelName}\n />\n </div>\n <div className={styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('board.providers')}\n <span className={styles['panelCount']}>\n {/* The unattributed remainder is the difference between the\n named routes and the top line, not a route: it never\n counts towards the number of providers. */}\n {providerSort === 'cost'\n ? t('board.byCost', { count: namedProviderCount.toLocaleString() })\n : t('board.byTokens', { count: namedProviderCount.toLocaleString() })}\n </span>\n </span>\n <RowSortControl\n value={providerSort}\n options={SORT_PROVIDER}\n onChange={onProviderSortChange}\n ariaLabel={t('board.providers')}\n t={t}\n />\n </div>\n <UsageRows\n kind=\"provider\"\n providerRows={providerRows}\n providerNames={providerNames}\n sort={providerSort}\n costState={costState}\n view={view}\n t={t}\n />\n </div>\n <div ref={overheadCardRef} className={overheadFlash ? `${styles['panel']} ${styles['flash']}` : styles['panel']}>\n <div className={styles['panelHead']}>\n <span className={styles['panelTitle']}>\n {t('aux.tab')}\n <span className={styles['panelCount']}>{t('aux.subtitle')}</span>\n </span>\n </div>\n <OverheadRows aux={aux} costState={costState} view={view} t={t} />\n </div>\n </div>\n )\n}\n","/**\n * Shared \"stat card\" primitive: label on top, value underneath. Used by the\n * settings section (primary cards + four token-bucket cards) and the Usage\n * view tab (six cards: requests-with-failure-pill / cost / total tokens /\n * hit rate / TTFT / token speed). Centralising the markup + styling means\n * the two surfaces read as one family without each one carrying its own\n * copy of the label-on-top / value-below rule.\n *\n * {@link FailurePill} is the compact failed-count chip the requests card\n * uses; {@link OverheadPill} is its neutral sibling for the recorded\n * auxiliary-request count, wired to jump to the runtime-overhead section.\n * Per-model tables use {@link RequestsCell} (`A/B`, B in the error\n * color) instead — a pill is too much chrome for a numeric column.\n *\n * @module token-usage/client/StatCard\n */\n\nimport type { ReactNode } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { UsageAuxKindRow } from '../wire.ts'\nimport { failuresTooltip, overheadTooltip } from './format.ts'\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 /** Settings uses `'sm'` for a fixed four-by-two overview (16px figures).\n * The wide-column variant (`'lg'`): the v3 demo's figures — 20px\n * value over a 12px label in a roomier tile. The page's nine-track\n * row renders it; the Usage view keeps the default figures. */\n size?: 'sm' | 'lg' | undefined\n /** A node riding beside the label (not below it): the compact lead\n * card's overhead pill. The narrow tile would wrap a pill on the\n * value line and stretch the whole grid row; up here it fits. */\n labelExtra?: ReactNode | undefined\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, size, labelExtra }: StatCardProps): ReactNode {\n const card = size === 'lg' ? `${styles['card']} ${styles['cardLg']}`\n : size === 'sm' ? `${styles['card']} ${styles['cardSm']}` : styles['card']\n return (\n <div className={card}>\n {labelExtra === undefined\n ? <span className={styles['cardLabel']}>{label}</span>\n : (\n <span className={styles['cardLabelRow']}>\n <span className={styles['cardLabel']}>{label}</span>\n {labelExtra}\n </span>\n )}\n <span className={styles['cardValue']}>{value}</span>\n </div>\n )\n}\n\n/** Props for the shared failure-count pill. */\nexport interface FailurePillProps {\n /** Failed provider attempts; 0 renders nothing. */\n failures: number\n /** Per-code breakdown driving the tooltip. */\n failuresByCode: Record<string, number> | undefined\n /** Locale function (`stat.failuresPill` / `fail.*`). */\n t: TranslateNS<'token-usage'>\n /** Render as bare red text instead of the capsule: the compact lead\n * card's value line fits a six-digit count plus the breakdown only\n * without the pill chrome — a capsule there wraps to a third line and\n * stretches the whole grid row. Same tooltip and keyboard focus. */\n bare?: boolean | undefined\n}\n\n/**\n * Compact \"失败 n\" chip for the requests **card** only. Hovering or focusing\n * it lists `限流 ×count` per class. Zero failures render nothing. Per-model\n * tables do not use this — they print `A/B` via {@link RequestsCell}.\n */\nexport function FailurePill({\n failures,\n failuresByCode,\n t,\n bare = false,\n}: FailurePillProps): ReactNode {\n if (failures === 0) return null\n return (\n <span className={styles['pillWrap']}>\n <Tooltip\n label={failuresTooltip(failuresByCode, t)}\n side=\"bottom\"\n delayMs={200}\n >\n {bare\n ? (\n <span\n className={styles['failBare']}\n tabIndex={0}\n aria-label={t('stat.failuresPill', { count: failures.toLocaleString() })}\n >\n {t('stat.failuresPill', { count: failures.toLocaleString() })}\n </span>\n )\n : (\n <span className={styles['pill']} tabIndex={0}>\n {t('stat.failuresPill', { count: failures.toLocaleString() })}\n </span>\n )}\n </Tooltip>\n </span>\n )\n}\n\n/** Props for the shared successful-requests card with a failure pill. */\nexport interface RequestsStatCardProps {\n /** Successful (billed) request count. */\n requests: number\n /** Failed provider attempts. */\n failures: number\n /** Per-code breakdown driving the pill tooltip. */\n failuresByCode: Record<string, number> | undefined\n /** Locale function (zh/en `stat.requests` / `stat.failuresPill`). */\n t: TranslateNS<'token-usage'>\n /** Recorded auxiliary request count; > 0 shows the neutral pill. */\n overheadRequests?: number | undefined\n /** Per-kind split driving the overhead pill's tooltip. */\n overheadByKind?: readonly UsageAuxKindRow[] | undefined\n /** Click on the overhead pill: the dashboards scroll to / switch to the\n * runtime-overhead section. Omitted hosts keep the pill inert. */\n onOverheadActivate?: (() => void) | undefined\n /** Stat-card pass-throughs: the page's `'lg'` figures, and a node on\n * the label row (the compact lead card parks the overhead pill there —\n * on the value line it would wrap and stretch the grid row). */\n size?: 'sm' | 'lg' | undefined\n labelExtra?: ReactNode | undefined\n /** Bare-text failure count (no capsule): the compact lead card's value\n * line — a six-digit count plus a capsule overruns the narrow tile. */\n failureBare?: boolean | undefined\n}\n\n/**\n * The requests tile both dashboards share: hero figure is the successful\n * count; a compact pill to its right carries the failure count, and — when\n * auxiliary requests were recorded — a neutral pill carries the runtime-\n * overhead count (hover for the per-kind split, click to jump there).\n */\nexport function RequestsStatCard({\n requests,\n failures,\n failuresByCode,\n t,\n overheadRequests,\n overheadByKind,\n onOverheadActivate,\n size,\n labelExtra,\n failureBare = false,\n}: RequestsStatCardProps): ReactNode {\n return (\n <StatCard\n label={t('stat.requests')}\n size={size}\n labelExtra={labelExtra}\n value={(\n <>\n <span className={styles['cardValueMain']}>{requests.toLocaleString()}</span>\n <FailurePill failures={failures} failuresByCode={failuresByCode} t={t} {...(failureBare ? { bare: true } : {})} />\n <OverheadPill\n requests={overheadRequests}\n byKind={overheadByKind}\n onActivate={onOverheadActivate}\n t={t}\n />\n </>\n )}\n />\n )\n}\n\n/** Props for the shared overhead pill: a neutral count chip that lists the\n * per-kind split on hover and activates the overhead section on click. */\nexport interface OverheadPillProps {\n /** Recorded auxiliary request count; 0 or undefined renders nothing. */\n requests: number | undefined\n /** Per-kind breakdown driving the tooltip. */\n byKind: readonly UsageAuxKindRow[] | undefined\n /** Click callback (scroll-to on the page, tab-switch on the panel). */\n onActivate?: (() => void) | undefined\n /** Locale function (`stat.overheadPill` / `aux.kind.*`). */\n t: TranslateNS<'token-usage'>\n}\n\n/**\n * Compact \"开销 n\" chip beside the hero request count. Mirrors\n * {@link FailurePill} in neutral ink and is a real button — the dashboards\n * wire it to scroll-to (page) or switch-to (panel) the runtime-overhead\n * section. Zero recorded overhead renders nothing.\n */\nexport function OverheadPill({\n requests,\n byKind,\n onActivate,\n t,\n}: OverheadPillProps): ReactNode {\n if (requests === undefined || requests === 0) return null\n return (\n <span className={styles['pillWrap']}>\n <Tooltip\n label={overheadTooltip(byKind, t)}\n side=\"bottom\"\n delayMs={200}\n >\n <button\n type=\"button\"\n className={styles['pillNeutral']}\n onClick={onActivate}\n >\n {t('stat.overheadPill', { count: requests.toLocaleString() })}\n </button>\n </Tooltip>\n </span>\n )\n}\n\n/** Props for the per-model requests cell: `success/fail` as `A/B`.\n * Tables pass the row's own totals so a session-scoped or date-filtered\n * summary cannot leak another row's failures into this cell. */\nexport interface RequestsCellProps {\n requests: number\n failures: number\n failuresByCode: Record<string, number> | undefined\n t: TranslateNS<'token-usage'>\n}\n\n/** One table cell: the successful count, and when failures > 0 the\n * failure count after a slash, in the error color and hoverable for the\n * per-code breakdown.\n *\n * The column is ONE plain column: the figures are plain inline text, so\n * the head above them inherits the same alignment and the two share one\n * edge — no tracks, no grid, no placeholder. Zero failures print only\n * the successful count (no slash, no `0`). */\nexport function RequestsCell({\n requests,\n failures,\n failuresByCode,\n t,\n}: RequestsCellProps): ReactNode {\n const ok = requests.toLocaleString()\n if (failures === 0) {\n return <span>{ok}</span>\n }\n const fail = failures.toLocaleString()\n return (\n <span>\n <span>{ok}</span>\n <span className={styles['splitSep']} aria-hidden>/</span>\n <span className={styles['failWrap']}>\n <Tooltip\n label={failuresTooltip(failuresByCode, t)}\n side=\"bottom\"\n delayMs={200}\n >\n <span\n className={styles['splitFail']}\n tabIndex={0}\n aria-label={t('stat.failuresPill', { count: fail })}\n >\n {fail}\n </span>\n </Tooltip>\n </span>\n </span>\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 * Trend-chart SVG path geometry: a polyline, optionally patched across\n * temporal gaps. Pure functions, no React.\n *\n * @module token-usage/client/trend-chart/path\n */\n\n/** How consecutive points are joined. */\nexport type PathStyle = 'polyline' | 'gap'\n\n/**\n * Per-segment gap flags: `flags[i]` is true when the next bucket starts\n * after this bucket's exclusive `end`. Adjacent uniform buckets have\n * `next.time === prev.end` and are not gaps.\n */\nexport function gapAfter(points: readonly { time: number; end: number }[]): boolean[] {\n const flags: boolean[] = []\n for (let index = 0; index < points.length - 1; index += 1) {\n flags.push(points[index + 1]!.time > points[index]!.end)\n }\n return flags\n}\n\n/**\n * SVG `d` for already-scaled coordinates. Empty → `''`; one point → `M`.\n *\n * `gap` is the original polyline plus a patch: adjacent buckets stay a\n * straight `L`; a gap holds `hold` (`zero` = axis, `previous` = last y)\n * from the previous bucket's end until one bucket-width before the next\n * start, then slants in — so idle is not interpolated and dense hours\n * keep the polyline.\n */\nexport function seriesPath(input: {\n xs: readonly number[]\n ys: readonly number[]\n yZero: number\n style: PathStyle\n hold?: 'zero' | 'previous'\n gaps?: readonly boolean[]\n xEnds?: readonly number[]\n}): string {\n const { xs, ys, yZero, style, hold, gaps, xEnds } = input\n if (xs.length === 0) return ''\n const cmd = (letter: 'M' | 'L', x: number, y: number): string =>\n `${letter}${x.toFixed(1)},${y.toFixed(1)}`\n const parts: string[] = [cmd('M', xs[0]!, ys[0]!)]\n for (let index = 0; index < xs.length - 1; index += 1) {\n const xNext = xs[index + 1]!\n const yNext = ys[index + 1]!\n if (style === 'gap' && gaps?.[index] === true) {\n const ends = xEnds ?? xs\n const xEnd = ends[index]!\n const nextWidth = Math.max(ends[index + 1]! - xNext, 0)\n const xHold = Math.max(xEnd, xNext - nextWidth)\n const holdY = hold === 'previous' ? ys[index]! : yZero\n parts.push(cmd('L', xEnd, holdY), cmd('L', xHold, holdY), cmd('L', xNext, yNext))\n } else {\n parts.push(cmd('L', xNext, yNext))\n }\n }\n return parts.join(' ')\n}\n\n/**\n * Generate a smooth cubic Bezier path using Fritsch-Carlson monotone cubic\n * Hermite interpolation. Preserves monotonicity so zero-filled plateaus stay\n * strictly flat at baseline without undershooting, and peaks round smoothly.\n *\n * @param xs - scaled x coordinates (monotonic ascending).\n * @param ys - scaled y coordinates.\n * @returns SVG `d` string containing M, L, and C commands.\n */\nexport function monotoneSplinePath(xs: readonly number[], ys: readonly number[]): string {\n const n = xs.length\n if (n === 0) return ''\n if (n === 1) return `M${xs[0]!.toFixed(1)},${ys[0]!.toFixed(1)}`\n if (n === 2) {\n return `M${xs[0]!.toFixed(1)},${ys[0]!.toFixed(1)} L${xs[1]!.toFixed(1)},${ys[1]!.toFixed(1)}`\n }\n\n // 1. Calculate secant slopes between adjacent points.\n const dx: number[] = []\n const slopes: number[] = []\n for (let i = 0; i < n - 1; i += 1) {\n const dX = xs[i + 1]! - xs[i]!\n const dY = ys[i + 1]! - ys[i]!\n dx.push(dX)\n slopes.push(dX === 0 ? 0 : dY / dX)\n }\n\n // 2. Initialize tangent slopes at each point.\n const m: number[] = new Array(n)\n m[0] = slopes[0]!\n m[n - 1] = slopes[n - 2]!\n for (let i = 1; i < n - 1; i += 1) {\n const s0 = slopes[i - 1]!\n const s1 = slopes[i]!\n if (s0 * s1 <= 0) {\n m[i] = 0\n } else {\n m[i] = (s0 + s1) / 2\n }\n }\n\n // 3. Fritsch-Carlson bounds: eliminate overshoot / undershoot.\n for (let i = 0; i < n - 1; i += 1) {\n const slope = slopes[i]!\n if (slope === 0) {\n m[i] = 0\n m[i + 1] = 0\n } else {\n const alpha = m[i]! / slope\n const beta = m[i + 1]! / slope\n const dist = alpha * alpha + beta * beta\n if (dist > 9) {\n const tau = 3 / Math.sqrt(dist)\n m[i] = tau * alpha * slope\n m[i + 1] = tau * beta * slope\n }\n }\n }\n\n // 4. Construct cubic Bezier commands.\n const parts: string[] = [`M${xs[0]!.toFixed(1)},${ys[0]!.toFixed(1)}`]\n for (let i = 0; i < n - 1; i += 1) {\n const dX = dx[i]!\n const x0 = xs[i]!\n const y0 = ys[i]!\n const x1 = xs[i + 1]!\n const y1 = ys[i + 1]!\n const cp1x = x0 + dX / 3\n const cp1y = y0 + m[i]! * (dX / 3)\n const cp2x = x1 - dX / 3\n const cp2y = y1 - m[i + 1]! * (dX / 3)\n parts.push(\n `C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${x1.toFixed(1)},${y1.toFixed(1)}`,\n )\n }\n return parts.join(' ')\n}\n\n/**\n * Close a line/curve path down to the baseline (`yZero`) to form an area polygon.\n * Returns an empty string when the input path is empty or has fewer than 2 points.\n *\n * @param linePath - the line or curve `d` string.\n * @param xs - the plotted x coordinates.\n * @param yZero - the baseline y coordinate.\n * @returns SVG `d` string closed with Z for fill.\n */\nexport function areaPath(linePath: string, xs: readonly number[], yZero: number): string {\n if (linePath === '' || xs.length < 2) return ''\n const firstX = xs[0]!.toFixed(1)\n const lastX = xs[xs.length - 1]!.toFixed(1)\n const baseY = yZero.toFixed(1)\n return `${linePath} L${lastX},${baseY} L${firstX},${baseY} Z`\n}\n\n/**\n * Return coordinates with gap hold points inserted so temporal series can be\n * smoothly interpolated with monotonic cubic splines without smearing idle spans.\n */\nexport function gapPatchedPoints(input: {\n xs: readonly number[]\n ys: readonly number[]\n yZero: number\n hold?: 'zero' | 'previous' | undefined\n gaps?: readonly boolean[] | undefined\n xEnds?: readonly number[] | undefined\n}): { xs: number[]; ys: number[] } {\n const { xs, ys, yZero, hold, gaps, xEnds } = input\n if (xs.length === 0) return { xs: [], ys: [] }\n const outXs: number[] = [xs[0]!]\n const outYs: number[] = [ys[0]!]\n for (let index = 0; index < xs.length - 1; index += 1) {\n const xNext = xs[index + 1]!\n const yNext = ys[index + 1]!\n if (gaps?.[index] === true) {\n const ends = xEnds ?? xs\n const xEnd = ends[index]!\n const nextWidth = Math.max(ends[index + 1]! - xNext, 0)\n const xHold = Math.max(xEnd, xNext - nextWidth)\n const holdY = hold === 'previous' ? ys[index]! : yZero\n if (xEnd > outXs[outXs.length - 1]!) {\n outXs.push(xEnd)\n outYs.push(holdY)\n }\n if (xHold > xEnd) {\n outXs.push(xHold)\n outYs.push(holdY)\n }\n outXs.push(xNext)\n outYs.push(yNext)\n } else {\n outXs.push(xNext)\n outYs.push(yNext)\n }\n }\n return { xs: outXs, ys: outYs }\n}\n\n/**\n * Generate a smooth spline path for either equidistant or gap-patched temporal series.\n */\nexport function smoothSeriesPath(input: {\n xs: readonly number[]\n ys: readonly number[]\n yZero: number\n gaps?: readonly boolean[] | undefined\n xEnds?: readonly number[] | undefined\n hold?: 'zero' | 'previous' | undefined\n}): string {\n const { xs, ys, yZero, gaps, xEnds, hold } = input\n if (gaps !== undefined && gaps.some(g => g)) {\n const patched = gapPatchedPoints({ xs, ys, yZero, hold, gaps, xEnds })\n return monotoneSplinePath(patched.xs, patched.ys)\n }\n return monotoneSplinePath(xs, ys)\n}\n\n\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; end: 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 end: bucket.end,\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/**\n * The cumulative view of a series: every point's `tokens` replaced by the\n * running total up to and including that point (a prefix sum), so the chart\n * reads as a monotonic rise. Orthogonal to the mode — all three input\n * shapes are time-ascending, so a plain forward fold is order-correct. The\n * input series is left untouched; each point is copied with only `tokens`\n * rewritten, so the renderer's shape probes (`'time' in point`) keep working.\n * @param series - the series from {@link buildChartPoints}.\n * @returns a new series of the same mode and shape.\n */\nexport function cumulateSeries(series: ChartSeries): ChartSeries {\n let running = 0\n const fold = <T extends { tokens: number }>(points: readonly T[]): T[] =>\n points.map(point => {\n running += point.tokens\n return { ...point, tokens: running }\n })\n if (series.mode === 'equidistant') return { mode: 'equidistant', points: fold(series.points) }\n return { mode: 'temporal', points: fold(series.points) }\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 /** Temporal only: each bucket's exclusive `end` on the same scale as\n * `xs`, clamped to `[leftEdge, rightEdge]`. Gap paths use\n * `xEnds[i] − xs[i]` as the bucket width so the hold ends one bucket\n * before the next cluster. */\n xEnds?: 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\nfunction clampX(value: number, leftEdge: number, rightEdge: number): number {\n return Math.min(Math.max(value, leftEdge), rightEdge)\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-start to last-start span and adds `leftEdge` to the result.\n * A zero span (one point, or every start equal) pins to the centerline.\n * Temporal results include `xEnds` for the gap-path bucket width.\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: wall time into the first-start to last-start span. `end`\n // uses the same domain; an end past the last start clamps to the right edge.\n const temporal = series.points\n const first = temporal[0]!.time\n const lastStart = temporal[temporal.length - 1]!.time\n if (temporal.length === 1 || first === lastStart) {\n const mid = (leftEdge + rightEdge) / 2\n const xs = temporal.map(() => mid)\n return { xs, xEnds: [...xs], innerWidth }\n }\n const xs: number[] = []\n const xEnds: number[] = []\n for (const point of temporal) {\n const x = clampX(leftEdge + scaleToSpan(first, lastStart, point.time, innerWidth), leftEdge, rightEdge)\n const xEnd = clampX(leftEdge + scaleToSpan(first, lastStart, point.end, innerWidth), leftEdge, rightEdge)\n xs.push(x)\n xEnds.push(Math.max(x, xEnd))\n }\n return { xs, xEnds, 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 { useEffect, useId, useRef, useState } from 'react'\nimport type { MouseEvent, 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 { areaPath, gapAfter, smoothSeriesPath } from './trend-chart/path.ts'\nimport { buildChartPoints, cumulateSeries } from './trend-chart/points.ts'\nimport { dotRadius, labelIndices, scaleSeries } from './trend-chart/scale.ts'\nimport { useIsLightMode } from './use-color-scheme.ts'\nimport styles from './TrendChart.module.css'\n\n/** Re-export the chart's pure helpers for the test suite. */\nexport {\n MAX_BUCKETS, areaPath, bucketSeries, bucketWidth, buildChartPoints, cumulateSeries, dotRadius, gapAfter,\n gapPatchedPoints, labelIndices, monotoneSplinePath, niceStep, scaleSeries, scaleToSpan, seriesPath,\n smoothSeriesPath, 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\n/** SVG canvas metrics. The viewBox width tracks the element's measured\n * width (ResizeObserver; WIDTH is the fallback where measuring is\n * unavailable), so the chart fills wide columns at its real scale — a\n * fixed viewBox would stretch a 1200px column 1.5×, blowing up the\n * height and the 11px type with it. The height and the type stay fixed. */\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 * The chart's y-axis reading: each point's own interval total (the\n * default), or the running cumulative total up to that point — a\n * monotonic rise over the same x axis.\n */\nexport type TrendChartMode = 'interval' | 'cumulative'\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. Cumulative mode\n * swaps in its own phrasing so \"total\" never reads ambiguous next to a\n * running sum.\n * @param t - the locale seat.\n * @param point - the pre-shaped point.\n * @param mode - the active y-axis mode.\n * @returns the tooltip / aria-label text.\n */\nfunction tipOf(t: TranslateNS<'token-usage'>, point: PlottedPoint, mode: TrendChartMode): string {\n if (point.time !== undefined) {\n const params = { window: point.full, count: String(point.count ?? 0), tokens: formatTokens(point.tokens) }\n return mode === 'cumulative' ? t('chart.cumulativeBucket', params) : t('chart.bucket', params)\n }\n const params = { day: point.full, tokens: formatTokens(point.tokens) }\n return mode === 'cumulative' ? t('chart.cumulativePoint', params) : t('chart.pointLabel', params)\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), the\n * optional y-axis mode (interval totals, or their running cumulative sum),\n * 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, mode = 'interval', height = HEIGHT, t }: {\n rows: readonly UsageDayRow[]\n hours?: readonly UsageHourRow[]\n requests?: readonly RequestPoint[]\n from?: string\n to?: string\n mode?: TrendChartMode\n height?: number\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const isLight = useIsLightMode()\n const gradientId = useId()\n const [active, setActive] = useState<number | null>(null)\n // The measured canvas width: the viewBox matches it 1:1, so the fixed\n // 11px type and 190px height render at their true size on any surface.\n const svgRef = useRef<SVGSVGElement | null>(null)\n const [width, setWidth] = useState(WIDTH)\n useEffect(() => {\n const el = svgRef.current\n // jsdom has no ResizeObserver; the 800-wide fallback stands there.\n if (el === null || typeof ResizeObserver === 'undefined') return\n const observer = new ResizeObserver(entries => {\n const next = Math.round(entries[0]?.contentRect.width ?? 0)\n // Ignore sub-pixel churn; a 0 (display:none) measurement keeps the last width.\n setWidth(current => (next > 0 && Math.abs(next - current) > 1 ? next : current))\n })\n observer.observe(el)\n return () => observer.disconnect()\n }, [])\n\n const base = buildChartPoints({ rows, hours, requests, from, to })\n if (base === null) {\n return <p className={styles.empty}>{t('chart.empty')}</p>\n }\n // Cumulative mode is a pure y-axis transform on the built points (a\n // prefix sum); the x axis, bucketing, and point count are untouched.\n const series = mode === 'cumulative' ? cumulateSeries(base) : base\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 canvas 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, xEnds, innerWidth } = scaleSeries(series, LEFT, width - RIGHT)\n const radius = dotRadius(points.length)\n const activePoint = active === null ? null : points[active] ?? null\n const y = (tokens: number): number => TOP + innerHeight - (tokens / top) * innerHeight\n const ys = points.map(point => y(point.tokens))\n const yZero = y(0)\n // Generate a smooth monotonic cubic spline across either equidistant\n // days/hours or gap-patched temporal buckets (so request idle stays idle).\n const path = smoothSeriesPath({\n xs,\n ys,\n yZero,\n gaps: series.mode === 'temporal' ? gapAfter(series.points) : undefined,\n xEnds: series.mode === 'temporal' ? (xEnds ?? xs) : undefined,\n hold: mode === 'cumulative' ? 'previous' : 'zero',\n })\n const area = areaPath(path, xs, yZero)\n\n // Cumulative reads one aria regardless of granularity: the per-mode\n // phrasing (\"daily\" / \"hourly\" / \"request-bucketed\") describes interval\n // totals and would mislabel a running sum; the tooltip carries the detail.\n const chartAria = mode === 'cumulative'\n ? t('chart.ariaCumulative')\n : 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 const handleMouseMove = (event: MouseEvent<SVGSVGElement>): void => {\n if (points.length <= 1) return\n const rect = event.currentTarget.getBoundingClientRect()\n if (rect.width <= 0) return\n const svgX = ((event.clientX - rect.left) / rect.width) * width\n let closest = 0\n let minDiff = Math.abs(xs[0]! - svgX)\n for (let i = 1; i < xs.length; i += 1) {\n const diff = Math.abs(xs[i]! - svgX)\n if (diff < minDiff) {\n minDiff = diff\n closest = i\n }\n }\n setActive(closest)\n }\n\n return (\n <svg\n role=\"img\"\n aria-label={chartAria}\n viewBox={`0 0 ${width} ${height}`}\n ref={svgRef}\n className={`${styles.chart} ${isLight ? styles.chartLight : ''}`.trim()}\n data-theme={isLight ? 'light' : 'dark'}\n onMouseMove={handleMouseMove}\n onMouseLeave={() => setActive(null)}\n >\n {isLight ? (\n <defs>\n <linearGradient id={gradientId} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n <stop\n offset=\"0%\"\n stopColor=\"var(--dsw-alias-label-primary)\"\n stopOpacity=\"0.045\"\n />\n <stop\n offset=\"55%\"\n stopColor=\"var(--dsw-alias-label-primary)\"\n stopOpacity=\"0.012\"\n />\n <stop\n offset=\"100%\"\n stopColor=\"var(--dsw-alias-label-primary)\"\n stopOpacity=\"0.0\"\n />\n </linearGradient>\n </defs>\n ) : null}\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 {isLight && area !== '' ? <path d={area} fill={`url(#${gradientId})`} className={styles.area} /> : null}\n <path d={path} className={styles.line} />\n {/* Declutter: render dots only when focused/hovered, or for a lone point */}\n {activePoint !== null && active !== null ? (\n <g pointerEvents=\"none\">\n <circle\n cx={xs[active]}\n cy={y(activePoint.tokens)}\n r={radius + 3.5}\n className={styles.dotHalo}\n />\n <circle\n cx={xs[active]}\n cy={y(activePoint.tokens)}\n r={radius}\n className={styles.dotActive}\n />\n </g>\n ) : points.length === 1 ? (\n <circle\n cx={xs[0]}\n cy={y(points[0]!.tokens)}\n r={radius}\n className={styles.dot}\n />\n ) : null}\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, mode)}\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, mode)\n const charWidth = 6.2\n const labelWidth = label.length * charWidth + 14\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 - 14} width={labelWidth} height={22} rx={6} />\n <text x={left + labelWidth / 2} y={labelY + 1} 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","/**\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 * The dashboards' shared overview board (browser half): the metric cards\n * (the composite first card「请求数 · 运行开销」spanning two grid\n * tracks, then cost / total / hit rate and the four buckets), the pricing\n * status line, and the trend card — titled 趋势, plotting the day's 24\n * hours on a single-day window (fixed; no plot pick) and the daily rows\n * on any wider window. Both the main page and the settings panel render\n * this same board, so the two surfaces read as one.\n *\n * @module token-usage/client/OverviewBoard\n */\n\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { AssociationStorageError, AuxSummary, CostState, PricingUnavailableReason, UsageDayRow, UsageHourRow, UsageTotals } from '../wire.ts'\nimport { costsAvailable } from './PricingStatus.tsx'\nimport { PricingStatus } from './PricingStatus.tsx'\nimport { StatCard, RequestsStatCard, OverheadPill } from './StatCard.tsx'\nimport { TrendChart } from './TrendChart.tsx'\nimport { HitRateText } from './HitRateText.tsx'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatTokens } from './format.ts'\nimport { totalTokens } from './day.ts'\nimport styles from './OverviewBoard.module.css'\n\n/** Props for the overview board — every field is derived data the section\n * (which owns the fetch and the filter state) passes down; the board never\n * requests. */\nexport interface OverviewBoardProps {\n /** The window's totals (the top-line aggregate). */\n total: UsageTotals\n /** Billed cost (¥) of the window; dashed when the cost layer is out. */\n totalCost: number\n costState: CostState\n pricingUnavailableReason?: PricingUnavailableReason | undefined\n associationStorageError?: AssociationStorageError | undefined\n /** The auxiliary layer driving the composite card's overhead pill\n * (absent / zero renders no pill). */\n aux?: AuxSummary | undefined\n /** The trend's daily points (always present). */\n byDay: readonly UsageDayRow[]\n /** The trend's hourly points (a single-day window only). */\n byHour: readonly UsageHourRow[]\n /** The active window bounds ('' = whole range). A single-day selection\n * (from === to, both non-empty) offers the hourly toggle. */\n from: string\n to: string\n /** Overhead pill click: scroll to / switch to the overhead section. */\n onOverheadActivate: () => void\n /** The settings panel's narrow body: the metric cards fall back to the\n * section's old two-rows-of-four layout (the composite card keeps its\n * pills but reads the short label), while the page's wide column keeps\n * the demo's single nine-track row. */\n compact?: boolean | undefined\n /** Currency display view (symbol + rate). */\n view: CurrencyView\n t: TranslateNS<'token-usage'>\n}\n\n/**\n * Render the overview board: one metric row (the composite lead card\n * spans two tracks), the pricing status, and the trend card.\n */\nexport function OverviewBoard({\n total,\n totalCost,\n costState,\n pricingUnavailableReason,\n associationStorageError,\n aux,\n byDay,\n byHour,\n from,\n to,\n onOverheadActivate,\n compact = false,\n view,\n t,\n}: OverviewBoardProps): ReactNode {\n // A single-day window plots the day's 24 hours (the section's old\n // semantics, fixed — no plot pick); any other window plots the daily rows.\n const singleDay = from !== '' && from === to\n // The page's wide column renders the demo's 20px figures; the panel's\n // narrow grid keeps the compact ones.\n const cardSize = compact ? ('sm' as const) : ('lg' as const)\n return (\n <div className={styles['board']}>\n <div className={compact ? styles['metricGridCompact'] : styles['metricGrid']}>\n {/* display: contents — the composite card itself becomes the grid\n * item (spanning two tracks on the page's wide row), so its tile\n * keeps the family chrome. The pill seats differ: the page's wide\n * lead card parks both pills on the value line; the panel's narrow\n * one would wrap them there and stretch the whole row, so its\n * overhead pill rides the label row instead. */}\n <div className={compact ? styles['leadSpanCompact'] : styles['leadSpan']}>\n <RequestsStatCard\n requests={total.requests}\n failures={total.failures ?? 0}\n failuresByCode={total.failuresByCode}\n {...(compact\n ? {\n labelExtra: (\n <OverheadPill\n requests={aux?.total.requests}\n byKind={aux?.byKind}\n onActivate={onOverheadActivate}\n t={t}\n />\n ),\n // The narrow tile fits the count plus the failure\n // breakdown only as bare text — a capsule wraps to a\n // third line and stretches the whole grid row.\n failureBare: true,\n }\n : {\n overheadRequests: aux?.total.requests,\n overheadByKind: aux?.byKind,\n onOverheadActivate,\n })}\n size={cardSize}\n t={t}\n />\n </div>\n <StatCard size={cardSize} label={t('stat.cost')} value={costsAvailable(costState) ? formatCost(totalCost, view) : '—'} />\n <StatCard size={cardSize} label={t('stat.totalTokens')} value={formatTokens(totalTokens(total))} />\n <StatCard size={cardSize} label={t('stat.hitRate')} value={<HitRateText totals={total} />} />\n <StatCard size={cardSize} label={t('stat.input')} value={formatTokens(total.inputTokens)} />\n <StatCard size={cardSize} label={t('stat.output')} value={formatTokens(total.outputTokens)} />\n <StatCard size={cardSize} label={t('stat.cacheRead')} value={formatTokens(total.cacheReadTokens)} />\n <StatCard size={cardSize} label={t('stat.cacheWrite')} value={formatTokens(total.cacheWriteTokens)} />\n </div>\n <PricingStatus costState={costState} pricingUnavailableReason={pricingUnavailableReason} associationStorageError={associationStorageError} t={t} />\n <div className={styles['trendCard']}>\n <span className={styles['trendTitle']}>{t('trend.title')}</span>\n <TrendChart\n rows={byDay}\n t={t}\n {...from !== '' ? { from } : {}}\n {...to !== '' ? { to } : {}}\n {...(singleDay ? { hours: byHour } : {})}\n />\n </div>\n </div>\n )\n}\n","import type { PricingOverviewModel } from '../wire.ts'\nimport { compileAliasPattern, matchesAliasPattern } from '../model-resolution.ts'\n\nconst patternCache = new WeakMap<PricingOverviewModel, RegExp[]>()\n\nfunction patternsOf(model: PricingOverviewModel): RegExp[] {\n let patterns = patternCache.get(model)\n if (patterns === undefined) {\n patterns = model.aliasPatterns.map(compileAliasPattern)\n patternCache.set(model, patterns)\n }\n return patterns\n}\n\nexport function sortPricingModels(models: readonly PricingOverviewModel[]): PricingOverviewModel[] {\n return [...models].sort((a, b) => {\n const familyA = a.family ?? 'other', familyB = b.family ?? 'other'\n if (familyA !== familyB) return familyA < familyB ? -1 : 1\n return a.modelId < b.modelId ? -1 : a.modelId > b.modelId ? 1 : 0\n })\n}\n\n/** Substrings are a search aid only; server resolution determines identity. */\nexport function matchesPricingSearch(model: PricingOverviewModel, query: string): boolean {\n if (query === '') return true\n const needle = query.toLowerCase()\n return model.modelId.toLowerCase().includes(needle) || (model.family ?? 'other').toLowerCase().includes(needle)\n || patternsOf(model).some(regex => matchesAliasPattern(regex, query))\n}\n","/**\n * The pricing-overview dialog of the settings page: the full cloud-mirror\n * model list served by the filter-free `/token-usage/pricing` route — one\n * flat row per model, sorted by the feed's upstream `family` field (zero\n * client-side mapping) then by modelId, each row's four base rates in the\n * page's display currency. Families drive order and search only — there is\n * no grouping UI, every row is directly visible. Rows the page's filters\n * have used carry a “已用” tag; clicking a row opens that model's full\n * price table as a second native dialog stacked above.\n *\n * Above the table, four token-bucket inputs drive a simulated-cost column:\n * what the buckets would bill at each model's base rates. Each bucket is\n * an amount under a picked K/M/B unit — switching converts the amount, the\n * token count stands still. Preset case buttons (「案例1」, hover-titled\n * with the workload picture) refill the buckets compact in one click; the\n * first case is prefilled on open, and the pressed highlight tracks exact\n * token matches, so a manual edit un-presses. The column sorts by a\n * three-state header cycle (family order → cost desc → cost asc → family);\n * the header's glyph never disappears: a dim ⇅ in the default family\n * order, then ▾ desc and ▴ asc.\n *\n * Aliases never render — they stay a search dimension only (a hit on an\n * alias surfaces the model, whose id then reads as the result).\n *\n * @module token-usage/client/PricingOverviewDialog\n */\n\nimport { Fragment, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ContextTier, DailySlot, ModelPricing, ModelRates, PricingOverviewModel, PricingOverviewPayload } from '../wire.ts'\nimport { PRICING_PATH } from '../wire.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { PricingAssociationDialog, PricingAssociationManagerButton } from './PricingAssociations.tsx'\nimport { PricingStatus, costsAvailable } from './PricingStatus.tsx'\nimport type { CurrencyView } from './format.ts'\nimport { formatCost, formatRate, formatTokens } from './format.ts'\nimport { billedRates, PricingDialog, windowText } from './PricingDialog.tsx'\nimport shared from './PricingDialog.module.css'\nimport styles from './PricingOverviewDialog.module.css'\n\nimport { matchesPricingSearch, sortPricingModels } from './pricing-search.ts'\nexport { matchesPricingSearch, sortPricingModels } from './pricing-search.ts'\n\n/** One preset usage case of the simulated-cost column: raw token buckets.\n * A case button's hover title derives from the data (input-side total,\n * cache-hit share, output), so adding a case is one array entry and\n * nothing else. */\ninterface SimScenario {\n inputTokens: number\n cacheReadTokens: number\n outputTokens: number\n cacheWriteTokens: number\n}\n\n/** The preset cases the buttons fill the inputs with (maintainer-curated\n * classic workloads). The first prefills the inputs on open. */\nconst SIM_SCENARIOS: readonly SimScenario[] = [\n // 「输入 100M(缓存 98%)输出 457K」: an input side of 100M tokens, 98%\n // of it served from cache, 457K generated.\n { inputTokens: 2_000_000, cacheReadTokens: 98_000_000, outputTokens: 457_000, cacheWriteTokens: 0 },\n // 「输入 100M(缓存 95%)输出 600K」: the same 100M input side at a 95%\n // cache hit, 600K generated.\n { inputTokens: 5_000_000, cacheReadTokens: 95_000_000, outputTokens: 600_000, cacheWriteTokens: 0 },\n // 「输入 100M(缓存 0%)输出 100M」: translation at corpus scale — fresh\n // text both ways, no cache in play, the output roughly as long as the\n // input.\n { inputTokens: 100_000_000, cacheReadTokens: 0, outputTokens: 100_000_000, cacheWriteTokens: 0 },\n]\n\n/** The four bucket fields of a case, in table order. */\ntype BucketKey = 'inputTokens' | 'cacheReadTokens' | 'outputTokens' | 'cacheWriteTokens'\n\n/** The units a bucket's amount can carry. */\nconst BUCKET_UNITS = ['K', 'M', 'B'] as const\ntype BucketUnit = typeof BUCKET_UNITS[number]\n\nconst UNIT_MULT: Record<BucketUnit, number> = { K: 1e3, M: 1e6, B: 1e9 }\n\n/** One bucket as typed: the amount string (free-form while editing) under\n * the picked unit — the whole-token count derives from the pair. */\ninterface Bucket {\n amount: string\n unit: BucketUnit\n}\n\n/** The whole-token count a bucket stands for: amount × unit, float fuzz\n * rounded off; empty, negative, or non-numeric amounts read as zero. */\nfunction tokensOf(bucket: Bucket): number {\n const parsed = Number(bucket.amount)\n if (!Number.isFinite(parsed) || parsed <= 0) return 0\n return Math.round(parsed * UNIT_MULT[bucket.unit])\n}\n\n/** The amount string for the same tokens under a new unit — converting so\n * the token count stands still (98M reads 98000K). Trims float fuzz to\n * six decimals so 0.457M ↔ 457K round-trips cleanly. */\nfunction convertBucketAmount(bucket: Bucket, unit: BucketUnit): string {\n const parsed = Number(bucket.amount)\n if (!Number.isFinite(parsed)) return ''\n const converted = parsed * UNIT_MULT[bucket.unit] / UNIT_MULT[unit]\n return String(Math.round(converted * 1e6) / 1e6)\n}\n\n/** The compact refill shape of one token count: a short amount under the\n * fitting unit (98M, 457K), K as the floor for the sub-1K tail. */\nfunction compactBucket(tokens: number): Bucket {\n if (tokens >= UNIT_MULT.B) return { amount: String(tokens / UNIT_MULT.B), unit: 'B' }\n if (tokens >= UNIT_MULT.M) return { amount: String(tokens / UNIT_MULT.M), unit: 'M' }\n return { amount: String(tokens / UNIT_MULT.K), unit: 'K' }\n}\n\n/** The refill shape of a whole case: every bucket compact. */\nfunction bucketsOfCase(scenario: SimScenario): Record<BucketKey, Bucket> {\n return {\n inputTokens: compactBucket(scenario.inputTokens),\n cacheReadTokens: compactBucket(scenario.cacheReadTokens),\n outputTokens: compactBucket(scenario.outputTokens),\n cacheWriteTokens: compactBucket(scenario.cacheWriteTokens),\n }\n}\n\n/**\n * The simulated cost (¥) of one scenario under a model's base rates —\n * the same arithmetic as the host half's `costOf` (a missing cache rate\n * bills at the input rate), re-implemented here because pricing.ts lives\n * on the node side of the bundle boundary.\n */\nfunction simCostOf(scenario: SimScenario, rates: ModelPricing): number {\n const M = 1_000_000\n const cacheRead = rates.cacheReadPerMillion ?? rates.inputPerMillion\n const cacheWrite = rates.cacheWritePerMillion ?? rates.inputPerMillion\n return (scenario.inputTokens * rates.inputPerMillion\n + scenario.outputTokens * rates.outputPerMillion\n + scenario.cacheReadTokens * cacheRead\n + scenario.cacheWriteTokens * cacheWrite) / M\n}\n\n/**\n * The effective world of one model at `nowMs`: the time rule whose date\n * window contains the current date (rules are mutually exclusive — at most\n * one matches; bounds are Unix seconds, `startTime` 0 reads as \"since\n * forever\"), else the model root. The world's default rates are the main\n * row (the root's prices are NOT shown while a rule owns the present);\n * its slots and tiers are the expandable special rows — never the root's.\n */\nexport interface EffectiveNode {\n /** The world's default rates: the main row's four prices and cost. */\n baseRates: ModelPricing\n /** Slot rows of this world: shown whenever defined, regardless of the\n * current minute (peaks recur daily — hiding them at off-peak hours\n * would hide the information). */\n slots: DailySlot[]\n /** The one tier this world's input side clears (largest threshold at or\n * below the context), if any. */\n tier: ContextTier | undefined\n}\n\n/** The largest tier whose threshold the context clears. */\nfunction hitTier(tiers: ContextTier[], ctxTokens: number): ContextTier | undefined {\n let hit: ContextTier | undefined\n for (const tier of tiers) {\n if (ctxTokens >= tier.threshold && (hit === undefined || tier.threshold > hit.threshold)) hit = tier\n }\n return hit\n}\n\nexport function hitNodeOf(rules: ModelRates, ctxTokens: number, nowMs: number): EffectiveNode {\n const nowSec = Math.floor(nowMs / 1000)\n const rule = rules.timeRules.find(candidate => candidate.startTime <= nowSec && nowSec <= candidate.endTime)\n if (rule !== undefined) {\n return { baseRates: rule.rates, slots: rule.dailySlots ?? [], tier: hitTier(rule.contextTiers ?? [], ctxTokens) }\n }\n return { baseRates: rules.base, slots: rules.dailySlots, tier: hitTier(rules.contextTiers, ctxTokens) }\n}\n\n/** The workload picture of one case — the input line (input-side total\n * with its cache-hit share) and the output line — joined into the case\n * button's hover title. */\nfunction scenarioLabel(scenario: SimScenario, t: TranslateNS<'token-usage'>): { inputLine: string; outputLine: string } {\n const total = scenario.inputTokens + scenario.cacheReadTokens\n const pct = Math.round((scenario.cacheReadTokens / total) * 100)\n return {\n inputLine: `${t('pricing.simInput', { tokens: formatTokens(total) })}${t('pricing.simCache', { pct: String(pct) })}`,\n outputLine: t('pricing.simOutput', { tokens: formatTokens(scenario.outputTokens) }),\n }\n}\n\n/** One bucket's K/M/B unit segment. Switching converts the amount so the\n * token count stands still. */\nfunction UnitPicker({ t, bucket, unit, onPick }: {\n t: TranslateNS<'token-usage'>\n bucket: string\n unit: BucketUnit\n onPick: (unit: BucketUnit) => void\n}): ReactNode {\n return (\n <div className={styles['unitGroup']}>\n {BUCKET_UNITS.map(candidate => (\n <button\n key={candidate}\n type=\"button\"\n className={styles['unit']}\n aria-pressed={candidate === unit}\n aria-label={t('pricing.simUnitOf', { bucket, unit: candidate })}\n onClick={() => { if (candidate !== unit) onPick(candidate) }}\n >\n {candidate}\n </button>\n ))}\n </div>\n )\n}\n\n/**\n * Fetch the pricing overview from the local route — deliberately without\n * any query parameters: the overview is not a filtered view, so changing\n * the page's filters never changes what this dialog shows. An empty model\n * list (a first startup whose sync has not landed a mirror yet) reads as\n * the same failure the fetch error does: nothing to show, retry offered.\n */\nfunction fetchPricingOverview(signal: AbortSignal): Promise<PricingOverviewPayload> {\n return fetch(PRICING_PATH, { signal })\n .then(response => {\n if (!response.ok) throw new Error(`HTTP ${String(response.status)}`)\n return response.json() as Promise<PricingOverviewPayload>\n })\n .then(value => {\n if (typeof value !== 'object' || value === null || !Array.isArray(value.models)) {\n throw new Error('unexpected pricing response')\n }\n if (value.costState === 'pricing-unavailable') return value\n if (value.models.length === 0) throw new Error('pricing mirror is empty')\n return value\n })\n}\n\n/**\n * The pricing-overview dialog. `usedModels` is the open-time snapshot of\n * the page's filtered model selection (the modal's backdrop covers the\n * filter row, so it cannot change while the dialog is open); `view` is the\n * page's display currency. Mounts only while open; every close path\n * funnels through the dialog's `close` event, which unmounts it.\n */\nexport function PricingOverviewDialog({ usedModels, view, onClose, t }: {\n usedModels: ReadonlySet<string>\n view: CurrencyView\n onClose: () => void\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n const dialogRef = useRef<HTMLDialogElement>(null)\n // Whether the press that precedes a dialog-targeting click started on\n // the backdrop itself. A text-selection drag that starts inside the\n // content and releases outside lands its click on the dialog element\n // (the click fires on the press/release targets' common ancestor, and\n // outside a top-layer dialog every point resolves to the dialog) — the\n // same target a real backdrop click produces. Only a press that began\n // on the backdrop may close.\n const backdropPress = useRef(false)\n useEffect(() => {\n const dialog = dialogRef.current\n if (dialog !== null && !dialog.open) dialog.showModal()\n }, [])\n // One fetch per dialog session: no filter deps, and the hook's own\n // retry() is the failure state's retry button (a fresh local fetch).\n const [state, retry] = useAsyncResource<PricingOverviewPayload>(fetchPricingOverview, [], { retryToken: 0 })\n usePricingAssociationRefresh(retry)\n const [search, setSearch] = useState('')\n // The token buckets driving the simulated-cost column, as typed: an\n // amount under a picked K/M/B unit each. The first preset case prefills\n // them on open; case buttons refill them compact, any edit just retypes.\n const [buckets, setBuckets] = useState<Record<BucketKey, Bucket>>(() => bucketsOfCase(SIM_SCENARIOS[0]!))\n // The simulated-cost column's sort: default family order, then a\n // three-state cycle (desc → asc → back to family) on header clicks.\n const [sortMode, setSortMode] = useState<'family' | 'cost-desc' | 'cost-asc'>('family')\n // The drilled-in model whose full price table is open above the overview.\n const [detail, setDetail] = useState<PricingOverviewModel | null>(null)\n const [associationsOpen, setAssociationsOpen] = useState(false)\n // The wall clock the effective-world hits are judged at: taken once on\n // mount so a dialog left open never reshuffles itself at a rule boundary.\n const [nowMs] = useState(() => Date.now())\n // The one model whose special-rate rows are expanded under its main row.\n const [expandedId, setExpandedId] = useState<string | null>(null)\n\n const sorted = useMemo(\n () => sortPricingModels(state.status === 'ready' ? state.value.models : []),\n [state],\n )\n // The whole-token counts the buckets stand for — what the cost column\n // bills and the case match compares.\n const scenario = useMemo<SimScenario>(() => ({\n inputTokens: tokensOf(buckets.inputTokens),\n cacheReadTokens: tokensOf(buckets.cacheReadTokens),\n outputTokens: tokensOf(buckets.outputTokens),\n cacheWriteTokens: tokensOf(buckets.cacheWriteTokens),\n }), [buckets])\n // The context a tier is hit against: the whole input side (fresh + cache\n // reads) reads as the request's context length.\n const ctxTokens = scenario.inputTokens + scenario.cacheReadTokens\n // A case button reads pressed while the inputs exactly match it — the\n // highlight follows the data, not the last click.\n const pressedCase = SIM_SCENARIOS.find(candidate => candidate.inputTokens === scenario.inputTokens\n && candidate.cacheReadTokens === scenario.cacheReadTokens\n && candidate.outputTokens === scenario.outputTokens\n && candidate.cacheWriteTokens === scenario.cacheWriteTokens)\n // Search filters rows and keeps the family sort order; the cost sort\n // (a stable sort) reorders afterwards, so equal-cost rows keep the\n // family order and the search never fights the sort. Cost = the main\n // row's (the effective world's default rates).\n const query = search.trim()\n const rows = useMemo(() => {\n const withCost = sorted.map(model => {\n const node = hitNodeOf(model.rules, ctxTokens, nowMs)\n return {\n model,\n node,\n cost: simCostOf(scenario, node.baseRates),\n specials: [\n ...(node.tier !== undefined\n ? [{ kind: 'tier' as const, tier: node.tier, slot: undefined as DailySlot | undefined, cost: simCostOf(scenario, node.tier.rates) }]\n : []),\n ...node.slots.map(slot => ({ kind: 'slot' as const, tier: undefined as ContextTier | undefined, slot, cost: simCostOf(scenario, slot.rates) })),\n ],\n }\n })\n .filter(({ model }) => query === '' || matchesPricingSearch(model, query))\n if (sortMode === 'family') return withCost\n return [...withCost].sort((a, b) => (sortMode === 'cost-desc' ? b.cost - a.cost : a.cost - b.cost))\n }, [sorted, scenario, query, sortMode, ctxTokens, nowMs])\n\n return (\n <dialog\n ref={dialogRef}\n className={`${shared['dialog']} ${styles['overview']}`}\n aria-label={t('pricing.table')}\n // The stacked detail dialog is a DOM child of this one, and React\n // simulates the close event's propagation up the tree — so a close\n // that targeted the detail reaches this handler too. Only a close of\n // this dialog itself ends the overview.\n onClose={event => { if (event.target === dialogRef.current) 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 // but only when the press started there too (see backdropPress): a\n // selection drag released outside produces the same click target.\n // With the detail dialog stacked above, its own backdrop click\n // never reaches this handler.\n onMouseDown={event => { backdropPress.current = event.target === dialogRef.current }}\n onClick={event => {\n if (event.target === dialogRef.current && backdropPress.current) dialogRef.current?.close()\n }}\n >\n <div className={shared['dialogHead']}>\n <div className={styles.titleActions}>\n <span className={shared['dialogTitle']}>{t('pricing.table')}</span>\n <PricingAssociationManagerButton t={t} onOpen={() => setAssociationsOpen(true)} />\n </div>\n <button\n type=\"button\"\n className={shared['dialogClose']}\n aria-label={t('pricing.close')}\n onClick={() => dialogRef.current?.close()}\n >\n ✕\n </button>\n </div>\n {associationsOpen && <PricingAssociationDialog initialSource={null} view={view} t={t} onClose={() => setAssociationsOpen(false)} />}\n {state.status === 'loading'\n ? <p className={styles['note']}>{t('loading')}</p>\n : null}\n {state.status === 'error'\n ? (\n <div className={styles['failRow']}>\n <p className={styles['note']}>{t('pricing.overviewFailed')}</p>\n <button type=\"button\" className={styles['retryButton']} onClick={retry}>{t('retry')}</button>\n </div>\n )\n : null}\n {state.status === 'ready' && !costsAvailable(state.value.costState)\n ? <div className={styles['failRow']}>\n <PricingStatus costState={state.value.costState} {...state.value.pricingUnavailableReason !== undefined ? { pricingUnavailableReason: state.value.pricingUnavailableReason } : {}} t={t} />\n <button type=\"button\" className={styles['retryButton']} onClick={retry}>{t('retry')}</button>\n </div> : null}\n {state.status === 'ready' && costsAvailable(state.value.costState)\n ? (\n <>\n <input\n type=\"search\"\n className={styles['search']}\n placeholder={t('pricing.search')}\n aria-label={t('pricing.search')}\n value={search}\n onChange={event => setSearch(event.target.value)}\n />\n <div className={styles['buckets']}>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketInput')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketInput')}\n value={buckets.inputTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n inputTokens: { ...previous.inputTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketInput')}\n unit={buckets.inputTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n inputTokens: { amount: convertBucketAmount(previous.inputTokens, unit), unit },\n }))}\n />\n </div>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketCacheRead')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketCacheRead')}\n value={buckets.cacheReadTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n cacheReadTokens: { ...previous.cacheReadTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketCacheRead')}\n unit={buckets.cacheReadTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n cacheReadTokens: { amount: convertBucketAmount(previous.cacheReadTokens, unit), unit },\n }))}\n />\n </div>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketOutput')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketOutput')}\n value={buckets.outputTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n outputTokens: { ...previous.outputTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketOutput')}\n unit={buckets.outputTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n outputTokens: { amount: convertBucketAmount(previous.outputTokens, unit), unit },\n }))}\n />\n </div>\n <div className={styles['bucket']}>\n <span className={styles['bucketLabel']}>{t('pricing.simBucketCacheWrite')}</span>\n <input\n type=\"number\"\n min={0}\n step=\"any\"\n className={styles['bucketInput']}\n aria-label={t('pricing.simBucketCacheWrite')}\n value={buckets.cacheWriteTokens.amount}\n onChange={event => setBuckets(previous => ({\n ...previous,\n cacheWriteTokens: { ...previous.cacheWriteTokens, amount: event.target.value },\n }))}\n />\n <UnitPicker\n t={t}\n bucket={t('pricing.simBucketCacheWrite')}\n unit={buckets.cacheWriteTokens.unit}\n onPick={unit => setBuckets(previous => ({\n ...previous,\n cacheWriteTokens: { amount: convertBucketAmount(previous.cacheWriteTokens, unit), unit },\n }))}\n />\n </div>\n </div>\n <div className={styles['scenarios']}>\n {SIM_SCENARIOS.map((candidate, index) => {\n const label = scenarioLabel(candidate, t)\n return (\n <button\n key={index}\n type=\"button\"\n className={styles['scenario']}\n aria-pressed={pressedCase === candidate}\n title={`${label.inputLine} ${label.outputLine}`}\n onClick={() => { setBuckets(bucketsOfCase(candidate)) }}\n >\n {t('pricing.simCase', { index: String(index + 1) })}\n </button>\n )\n })}\n </div>\n <div className={styles['tableWrap']}>\n <table className={styles['table']} aria-label={t('pricing.table')}>\n <thead>\n <tr>\n <th className={styles['modelHead']}>{t('filter.model')}</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 <th>\n <button\n type=\"button\"\n className={styles['sortHead']}\n onClick={() => {\n setSortMode(previous =>\n previous === 'family' ? 'cost-desc' : previous === 'cost-desc' ? 'cost-asc' : 'family')\n }}\n >\n {t('pricing.simCost')}\n {/* The glyph always shows, so the default family\n * order still reads as \"this column sorts\" — dimmed\n * there, full-strength once a direction is active. */}\n <span\n className={sortMode === 'family' ? `${styles['sortArrow']} ${styles['sortArrowIdle']}` : styles['sortArrow']}\n aria-hidden\n >\n {sortMode === 'family' ? ' ⇅' : sortMode === 'cost-desc' ? ' ▾' : ' ▴'}\n </span>\n </button>\n </th>\n </tr>\n </thead>\n <tbody>\n {rows.map(({ model, node, cost, specials }) => {\n const billed = billedRates(node.baseRates, view)\n const expanded = expandedId === model.modelId\n return (\n <Fragment key={model.modelId}>\n <tr\n className={styles['modelRow']}\n role=\"button\"\n tabIndex={0}\n aria-label={t('pricing.view', { model: model.modelId })}\n onClick={() => setDetail(model)}\n onKeyDown={event => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault()\n setDetail(model)\n }\n }}\n >\n <td className={styles['modelCell']}>\n <span className={styles['cellInner']}>\n {specials.length > 0\n ? (\n <button\n type=\"button\"\n className={styles['expandArrow']}\n aria-expanded={expanded}\n aria-label={t('pricing.expand')}\n onClick={event => {\n event.stopPropagation()\n setExpandedId(previous => (previous === model.modelId ? null : model.modelId))\n }}\n >\n {expanded ? '▾' : '▸'}\n </button>\n )\n : <span className={styles['arrowGap']} aria-hidden />}\n <span className={styles['modelName']}>{model.modelId}</span>\n {usedModels.has(model.modelId)\n ? <span className={styles['usedTag']}>{t('pricing.used')}</span>\n : null}\n </span>\n </td>\n <td>{billed.input}</td>\n <td>{billed.output}</td>\n <td>{billed.cacheRead}</td>\n <td>{billed.cacheWrite}</td>\n <td>{formatCost(cost, view)}</td>\n </tr>\n {expanded\n ? (\n <tr className={styles['expansionRow']}>\n <td colSpan={6}>\n <div className={styles['specialRows']}>\n {specials.map((special, index) => {\n const specialBilled = billedRates(special.tier?.rates ?? special.slot!.rates, view)\n const label = special.kind === 'tier'\n ? t('pricing.tier', { threshold: formatTokens(special.tier!.threshold) })\n : `${special.slot!.label ?? t('pricing.peak')} ${special.slot!.windows.map(windowText).join(t('pricing.windowSep'))}`\n return (\n <div key={index} className={styles['specialRow']}>\n <span className={styles['specialLabel']}>{label}</span>\n <span className={styles['specialRate']}>{specialBilled.input}</span>\n <span className={styles['specialRate']}>{specialBilled.output}</span>\n <span className={styles['specialRate']}>{specialBilled.cacheRead}</span>\n <span className={styles['specialRate']}>{specialBilled.cacheWrite}</span>\n <span className={styles['specialRate']}>{formatCost(special.cost, view)}</span>\n </div>\n )\n })}\n </div>\n </td>\n </tr>\n )\n : null}\n </Fragment>\n )\n })}\n </tbody>\n </table>\n {view.symbol === '$'\n ? <p className={shared['rateNote']}>{t('pricing.exchangeRateNote', { rate: formatRate(view.rate) })}</p>\n : null}\n </div>\n </>\n )\n : null}\n {detail !== null\n ? (\n <PricingDialog\n model={detail.modelId}\n rules={detail.rules}\n view={view}\n onClose={() => setDetail(null)}\n t={t}\n />\n )\n : null}\n </dialog>\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, and the per-model detail\n * table with the hit rate last — all following the active filters. A\n * priced model name is the row's price affordance (one click opens\n * PricingDialog.tsx); unpriced rows keep the in-cell tag. The filter\n * row's tail link opens the filter-free pricing-overview dialog\n * (PricingOverviewDialog.tsx). There is no refresh\n * button: entering the page or changing a filter refetches (the route\n * answers no-store); only 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 { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { UsageSummary } from '../wire.ts'\nimport { STATS_PATH } from '../wire.ts'\nimport { useAsyncResource } from './async-resource.ts'\nimport { DateRangePicker } from './DateRangePicker.tsx'\nimport { shiftedDayKey } from './day.ts'\nimport { currencyViewOf } from './format.ts'\nimport { MenuSelect } from './MenuSelect.tsx'\nimport { DashboardCards } from './DashboardCards.tsx'\nimport { OverheadRows } from './OverheadRows.tsx'\nimport { OverviewBoard } from './OverviewBoard.tsx'\nimport { PricingDialog } from './PricingDialog.tsx'\nimport { PricingOverviewDialog } from './PricingOverviewDialog.tsx'\nimport { PricingAssociationProvider } from './PricingAssociations.tsx'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { UsageRows, RowSortControl, PerfToggle } from './UsageRows.tsx'\nimport type { RowSort } from './UsageRows.tsx'\nimport { projectRowsOf } from './project-rows.ts'\nimport { useColorSchemeMirror } from './use-color-scheme.ts'\nimport styles from './TokenUsageSection.module.css'\n\n/** The detail tabs' fixed sort options: projects, models and providers pick\n * between token size and billed cost; sessions add last activity. */\nconst PROJECT_SORT: readonly RowSort[] = ['tokens', 'cost']\nconst MODEL_SORT: readonly RowSort[] = ['tokens', 'cost']\nconst PROVIDER_SORT: readonly RowSort[] = ['tokens', 'cost']\nconst SESSION_SORT: readonly RowSort[] = ['tokens', 'cost', 'recent']\n\n/** The detail switch's tab labels, one per mode. */\nconst DETAIL_MODES = ['project', 'model', 'session', 'provider', 'aux'] as const\ntype DetailMode = (typeof DETAIL_MODES)[number]\n\n/** One detail mode's label key. */\nfunction detailLabelOf(mode: DetailMode): 'byProject.title' | 'byModel.title' | 'bySession.title' | 'byProvider.title' | 'aux.tab' {\n return mode === 'project' ? 'byProject.title'\n : mode === 'model' ? 'byModel.title'\n : mode === 'session' ? 'bySession.title'\n : mode === 'provider' ? 'byProvider.title' : 'aux.tab'\n}\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/** 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/** Quick-range menu entries (labels are locale-free day counts). */\nconst QUICK_OPTIONS = [\n { value: '1', label: '1d' },\n { value: '7', label: '7d' },\n { value: '30', label: '30d' },\n] as const\n\n/** The filter bar: quick range menu, day-range picker popover, model\n * menu — one row, one popover language. The row's tail link is an action,\n * not a selector: it opens the filter-free pricing overview. */\nfunction FilterBar({ filters, models, onChange, onPricingTable, t }: {\n filters: Filters\n models: readonly string[]\n onChange: (next: Filters) => void\n onPricingTable: () => void\n t: TranslateNS<'token-usage'>\n}): ReactNode {\n // 'all' when the range is unconstrained, 'custom' when it no longer\n // holds one of the quick ranges.\n const quickValue = QUICK_OPTIONS.find(option => isQuickActive(Number(option.value), filters))?.value\n ?? (filters.from === '' && filters.to === '' ? 'all' : 'custom')\n return (\n <div className={styles['filters']}>\n <MenuSelect\n ariaLabel={t('filter.quickRange')}\n value={quickValue}\n options={[\n ...QUICK_OPTIONS,\n { value: 'all', label: t('filter.allDates') },\n { value: 'custom', label: t('filter.custom') },\n ]}\n onChange={value => {\n // 'all' releases the range back to unconstrained; the 'custom'\n // entry is informational: it mirrors the day range and never\n // rewrites it.\n if (value === 'all') onChange({ ...filters, from: '', to: '' })\n const days = Number(value)\n if (days > 0) onChange({ ...filters, ...quickRange(days) })\n }}\n />\n <DateRangePicker\n from={filters.from}\n to={filters.to}\n onChange={next => onChange({ ...filters, ...next })}\n t={t}\n />\n <MenuSelect\n ariaLabel={t('filter.model')}\n grow\n value={filters.model}\n options={[{ value: '', label: t('filter.allModels') }, ...models.map(model => ({ value: model, label: model }))]}\n onChange={model => onChange({ ...filters, model })}\n />\n {/* The tail action of the tool row: opens the pricing overview, a\n * view independent of the three selectors (it never takes filters).\n * A link-styled label, not a bordered button — bordered reads as a\n * fourth selector of the same family. */}\n <button type=\"button\" data-pricing-overview-trigger className={styles['pricingLink']} onClick={onPricingTable}>\n {t('pricing.table')}\n </button>\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 * The session jump seats (`sessionListed` / `openSession`) come from the\n * registration's `inject:` — the session table's Ctrl+click affordance\n * reads the controller's list and opens the target session.\n * @param props - the framework-injected translate seat, the optional\n * injected jump seats, and the optional `close` the hosting surface hands\n * in (the settings panel closes itself on a jump; the main page returns\n * to the conversation). Absent `close` just skips the dismiss step.\n * @returns the section, one of loading / error / ready.\n */\nexport function TokenUsageSection({ t, close, sessionListed, openSession, variant }: {\n t: TranslateNS<'token-usage'>\n /** Dismiss the hosting surface after a successful session jump. */\n close?: (() => void) | undefined\n sessionListed?: ((id: string) => boolean) | undefined\n openSession?: ((id: string) => boolean | { ok: boolean; reason?: string }) | undefined\n /** Hosting surface: the settings panel (default) or the main-column page,\n * which only restyles the title step and lifts the table's height cap. */\n variant?: ('panel' | 'page') | undefined\n}): ReactNode {\n const rootClass = variant === 'page' ? `${styles['section']} ${styles['pageVariant']}` : styles['section']\n const rootRef = useRef<HTMLDivElement>(null)\n useColorSchemeMirror(rootRef)\n const [toastText, setToastText] = useState<string | null>(null)\n const [toastSeq, setToastSeq] = useState(0)\n const showToast = useCallback((text: string) => {\n setToastSeq(previous => previous + 1)\n setToastText(text)\n }, [])\n const dismissToast = useCallback(() => {\n setToastText(null)\n }, [])\n\n const handleOpenSession = useCallback((id: string) => {\n if (!openSession) return\n const result = openSession(id)\n if (result && typeof result === 'object' && 'ok' in result) {\n if (result.ok) {\n close?.()\n } else if (result.reason === 'workspaceDeleted') {\n showToast(t('session.workspaceDeleted'))\n }\n return\n }\n if (result === true) {\n close?.()\n }\n }, [openSession, close, showToast, t])\n\n // Entering the page starts on today's window (the 1d quick range).\n const [filters, setFilters] = useState<Filters>(() => ({ model: '', ...quickRange(1) }))\n // The detail-table block's mode: by project (default — the dashboards'\n // first tab), by model, by session, by provider, or the runtime-overhead\n // breakdown of the auxiliary (bypass) model requests. Pure presentation\n // state — every row set arrives on the SAME summary response, so\n // switching never refetches (session-local, not persisted, the usage\n // tab's scope-switch tradeoff).\n const [detailMode, setDetailMode] = useState<DetailMode>('project')\n // The lists' sorts, each its own state (the page's cards and the panel's\n // tabs render the same lists, so one state drives both): projects,\n // models and providers pick token size vs billed cost, sessions add last\n // activity. A pick matching the native order passes it straight through.\n const [projectSort, setProjectSort] = useState<RowSort>('tokens')\n const [modelSort, setModelSort] = useState<RowSort>('tokens')\n // The models' performance view — a content switch next to the sort\n // control (shared by the page card and the panel tab, like the sorts).\n const [modelPerfView, setModelPerfView] = useState(false)\n const [providerSort, setProviderSort] = useState<RowSort>('tokens')\n const [sessionSort, setSessionSort] = useState<RowSort>('cost')\n // Ctrl+click on a model row toggles the model filter to just that model\n // (a single pick — clicking the filtered model again clears it).\n const handleToggleModel = useCallback((model: string) => {\n setFilters(previous => ({ ...previous, model: previous.model === model ? '' : model }))\n }, [])\n // The overhead pill's destination: the page scrolls to (and flashes) the\n // dashboard's overhead card; the panel switches to the overhead tab.\n const overheadCardRef = useRef<HTMLDivElement | null>(null)\n const [overheadFlash, setOverheadFlash] = useState(false)\n const flashTimer = useRef<number | undefined>(undefined)\n useEffect(() => () => window.clearTimeout(flashTimer.current), [])\n const activateOverhead = useCallback(() => {\n if (variant === 'page') {\n overheadCardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })\n setOverheadFlash(true)\n window.clearTimeout(flashTimer.current)\n flashTimer.current = window.setTimeout(() => setOverheadFlash(false), 1200)\n } else {\n setDetailMode('aux')\n }\n }, [variant])\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 // The pricing-overview dialog (opened by the filter row's tail link).\n // `usedSnapshot` is taken at open time: the modal's backdrop covers the\n // filter row, so the filters cannot change while it is open and the\n // snapshot stays stable for the whole dialog session. The link renders\n // only in the ready branch, so the summary is always at hand here.\n const [pricingTableOpen, setPricingTableOpen] = useState(false)\n const [usedSnapshot, setUsedSnapshot] = useState<ReadonlySet<string>>(() => new Set())\n const [retryToken, setRetryToken] = useState(0)\n const lastSummary = useRef<UsageSummary | null>(null)\n const retry = useCallback(() => { setRetryToken(previous => previous + 1) }, [])\n usePricingAssociationRefresh(retry)\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 === 'ready') lastSummary.current = state.value\n const retainedView = lastSummary.current !== null ? currencyViewOf(lastSummary.current) : { symbol: '¥' as const, rate: 1 }\n const pricingOverview = pricingTableOpen ? <PricingOverviewDialog usedModels={usedSnapshot} view={retainedView}\n onClose={() => setPricingTableOpen(false)} t={t} /> : null\n if (state.status === 'loading') {\n return (\n <div ref={rootRef} className={rootClass}>\n <PricingAssociationProvider resolutions={lastSummary.current?.modelResolutions} feedVersion={lastSummary.current?.feedVersion} view={retainedView} t={t}>\n {pricingOverview}\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <p className={styles['muted']}>{t('loading')}</p>\n </PricingAssociationProvider>\n </div>\n )\n }\n if (state.status === 'error') {\n return (\n <div ref={rootRef} className={rootClass}>\n <PricingAssociationProvider resolutions={lastSummary.current?.modelResolutions} feedVersion={lastSummary.current?.feedVersion} view={retainedView} t={t}>\n {pricingOverview}\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 </PricingAssociationProvider>\n </div>\n )\n }\n\n const { total } = state.value\n const view = currencyViewOf(state.value)\n // New hosts aggregate before the session top-N cut. Older payloads retain\n // the former client-side fold as a compatibility fallback only.\n const projectRows = state.value.projectRows ?? projectRowsOf(state.value.sessionRows ?? [])\n // The auxiliary (bypass) request count: the runtime-overhead tab is part of\n // the detail switch whenever any dimension has rows, and the tab content\n // renders its own empty hint when this stays 0 (or an older host payload\n // carries no auxiliary layer at all).\n const auxRequests = state.value.aux?.total.requests ?? 0\n return (\n <div ref={rootRef} className={rootClass}>\n <PricingAssociationProvider resolutions={state.value.modelResolutions} feedVersion={state.value.feedVersion} view={view} t={t}>\n {pricingOverview}\n <h2 className={styles['title']}>{t('nav.label')}</h2>\n <p className={styles['muted']}>{t('dataDir', { path: state.value.dataDir })}</p>\n <FilterBar\n filters={filters}\n models={models}\n onChange={setFilters}\n onPricingTable={() => {\n setUsedSnapshot(new Set(state.value.byModel.map(row => row.model)))\n setPricingTableOpen(true)\n }}\n t={t}\n />\n {total.requests === 0 && (total.failures ?? 0) === 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 <OverviewBoard\n total={total}\n totalCost={state.value.totalCost}\n costState={state.value.costState}\n pricingUnavailableReason={state.value.pricingUnavailableReason}\n associationStorageError={state.value.associationStorageError}\n aux={state.value.aux}\n byDay={state.value.byDay}\n byHour={state.value.byHour}\n from={filters.from}\n to={filters.to}\n onOverheadActivate={activateOverhead}\n {...variant === 'page' ? {} : { compact: true }}\n view={view}\n t={t}\n />\n {variant === 'page'\n ? (\n // The main page's dashboard: the four equal-height cards,\n // no dimension switch — everything is on show at once.\n <DashboardCards\n projectRows={projectRows}\n modelRows={state.value.byModel}\n sessionRows={state.value.sessionRows ?? []}\n projectSort={projectSort}\n onProjectSortChange={setProjectSort}\n modelSort={modelSort}\n onModelSortChange={setModelSort}\n modelPerfView={modelPerfView}\n onModelPerfToggle={setModelPerfView}\n providerRows={state.value.byProvider ?? []}\n providerNames={state.value.providerNames}\n providerSort={providerSort}\n onProviderSortChange={setProviderSort}\n sessionSort={sessionSort}\n onSessionSortChange={setSessionSort}\n aux={state.value.aux}\n pricing={state.value.pricing}\n costState={state.value.costState}\n view={view}\n t={t}\n {...sessionListed !== undefined && openSession !== undefined\n ? { sessionListed, onSessionOpen: handleOpenSession }\n : {}}\n onToggleModel={handleToggleModel}\n onModelName={setDetailModel}\n overheadCardRef={overheadCardRef}\n overheadFlash={overheadFlash}\n />\n )\n : state.value.byModel.length > 0 || (state.value.sessionRows?.length ?? 0) > 0 || auxRequests > 0\n ? (\n <section className={styles['detailPanel']}>\n <div className={styles['detailToolbar']}>\n <div className={styles['segmented']} role=\"group\" aria-label={t('detail.switch.label')}>\n {DETAIL_MODES.map(mode => (\n <button\n key={mode}\n type=\"button\"\n className={detailMode === mode ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={detailMode === mode}\n onClick={() => setDetailMode(mode)}\n >\n {t(detailLabelOf(mode))}\n </button>\n ))}\n </div>\n {detailMode !== 'aux' && (\n <div className={styles['sortRow']}>\n <span className={detailMode === 'model' && modelPerfView ? styles['sortHidden'] : undefined}>\n <RowSortControl\n compact\n value={detailMode === 'project' ? projectSort : detailMode === 'model' ? modelSort : detailMode === 'provider' ? providerSort : sessionSort}\n options={detailMode === 'project' ? PROJECT_SORT : detailMode === 'model' ? MODEL_SORT : detailMode === 'provider' ? PROVIDER_SORT : SESSION_SORT}\n onChange={detailMode === 'project' ? setProjectSort : detailMode === 'model' ? setModelSort : detailMode === 'provider' ? setProviderSort : setSessionSort}\n ariaLabel={t(detailLabelOf(detailMode))}\n t={t}\n />\n </span>\n {detailMode === 'model' && <PerfToggle compact pressed={modelPerfView} onToggle={setModelPerfView} t={t} />}\n </div>\n )}\n </div>\n <div className={styles['detailBody']}>\n {detailMode === 'aux'\n ? <OverheadRows aux={state.value.aux} costState={state.value.costState} view={view} t={t} />\n : <UsageRows\n key={detailMode}\n kind={detailMode}\n projectRows={projectRows}\n modelRows={state.value.byModel}\n sessionRows={state.value.sessionRows ?? []}\n providerRows={state.value.byProvider ?? []}\n providerNames={state.value.providerNames}\n sort={detailMode === 'project' ? projectSort : detailMode === 'model' ? modelSort : detailMode === 'provider' ? providerSort : sessionSort}\n perfView={detailMode === 'model' && modelPerfView}\n pricing={state.value.pricing}\n costState={state.value.costState}\n view={view}\n t={t}\n onToggleModel={handleToggleModel}\n onModelName={setDetailModel}\n {...sessionListed !== undefined && openSession !== undefined\n ? { sessionListed, onSessionOpen: handleOpenSession }\n : {}}\n />}\n </div>\n </section>\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 {toastText !== null && (\n <Toast\n key={toastSeq}\n text={toastText}\n icon={<IconWarningOutlineRegular />}\n onDone={dismissToast}\n />\n )}\n </PricingAssociationProvider>\n </div>\n )\n}\n","/**\n * The Token Usage main panel (browser half): the full-width page the\n * sidebar \"More\" menu row opens, registered into the `main` keyed slot\n * under key `token-usage` (declared by ui-layout). It wraps the\n * settings-section component unchanged — same stats route, same filters —\n * and adapts only the session-jump epilogue: the settings panel's `close`\n * becomes the page's return-to-conversation (selectPanel(null)), so a\n * Ctrl+click session jump lands on the target session.\n *\n * The registration waits on the shell's `main` declaration through\n * ctx.slots.inject; a shell that never declares it never runs the\n * callback, and the plugin's other surfaces are unaffected.\n *\n * @module token-usage/client/UsagePanelPage\n */\n\nimport type { ReactNode } from 'react'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: pulls the `main` keyed SlotMap key (declared by ui-layout).\nimport type {} from '@deepseek-ai/dsh-client-ui-layout/client'\nimport { TokenUsageSection } from './TokenUsageSection.tsx'\nimport css from './UsagePanelPage.module.css'\n\nexport type UsagePanelPageProps =\n PropsRuntime<'main'>\n & PropsLocale<'token-usage'>\n & {\n sessionListed?: (id: string) => boolean\n openSession?: (id: string) => { ok: boolean; reason?: string } | boolean\n /** Return the main column to the conversation (the page's \"close\"). */\n returnToConversation?: () => void\n }\n\n/**\n * Render the Token Usage page for the main column: the official\n * first-level-page shell (full-height scroll pane, centered 960px column)\n * wrapping the section in its `page` variant — the settings panel keeps its\n * own layout untouched.\n * @param props - the locale seat, the injected session-jump seats, and the\n * framework's (empty) main-panel owner share.\n * @returns the shelled section content.\n */\nexport function UsagePanelPage({ t, sessionListed, openSession, returnToConversation }: UsagePanelPageProps): ReactNode {\n return (\n <div className={css.page}>\n <div className={css.pageScroll}>\n <div className={css.pageContent}>\n <TokenUsageSection t={t} variant=\"page\" close={returnToConversation} sessionListed={sessionListed} openSession={openSession} />\n </div>\n </div>\n </div>\n )\n}\n","/**\n * The conversation usage tab's request pool (最新请求 / 实时请求): the\n * active-first request panel (items[0], six fixed metrics in order: cache hit,\n * input, output, first token, latency, speed — with cost / cache read /\n * cache write demoted to the footer) plus the history table of up to 19\n * earlier rows (columns frozen in order: origin, state, time, model, cache\n * hit, input, output, cache read, cache write, first token, latency, speed,\n * cost). The cache-write column is omitted when every visible request lacks\n * a reported write bucket.\n *\n * Every figure comes from the server snapshot (`requestDetails`) — the\n * component never re-derives rates or speeds, never runs its own clock\n * (in-flight elapsed is server-anchored), and never fills an unknown with a\n * zero or a session mean. The 「缓存过低」 label is a low-hit heuristic the\n * server already gated through every exclusion; its tooltip says so.\n *\n * @module token-usage/client/RequestPool\n */\n\nimport { useEffect, useRef } from 'react'\nimport type { ReactNode } from 'react'\nimport { Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { CurrencyView } from './format.ts'\nimport { bandOf, formatCost, formatRequestRate, formatRequestRateExact, formatTimeOfDay, formatTokens, formatTtft } from './format.ts'\nimport { bandClassOf } from './HitRateText.tsx'\nimport type { CompactionAttributionItem, RequestDetailCache, RequestDetailView, SessionRequestDetails } from '../wire.ts'\nimport type { ConversationStatus } from '../wire.ts'\nimport styles from './UsageView.module.css'\n\nexport interface RequestPoolProps {\n details: SessionRequestDetails\n /** The focused session: rows from it are 「本会话」, from its descendants\n * 「子会话」— the same mapping the subagent table's drill-in uses. */\n focusId: string\n view: CurrencyView\n /** Epoch ms of the last successful refresh; set while the latest refresh\n * failed and the panel kept its previous snapshot (the stale notice). */\n staleAt?: number\n t: TranslateNS<'token-usage'>\n}\n\n/** The state pill's color class (state is never color-only — the label text\n * and the metrics columns carry the same facts). */\nfunction stateClassOf(state: RequestDetailView['state']): string {\n switch (state) {\n case 'failed': return styles['stateFailed'] ?? ''\n case 'cancelled':\n case 'interrupted':\n case 'waiting': return styles['statePending'] ?? ''\n case 'streaming': return styles['stateStreaming'] ?? ''\n default: return styles['stateDone'] ?? ''\n }\n}\n\n/** Numeric colour follows the summary cards, independently of label eligibility. */\nfunction hitClassOf(cache: RequestDetailCache): string | undefined {\n if (cache.rate === undefined) return styles['zeroDim'] ?? ''\n return bandClassOf(bandOf(cache.rate))\n}\n\n/** The hit cell's tooltip: the low-hit explanation (with the raw-precision\n * note when rounding would hide a sub-threshold rate) or the exclusion\n * reason. Unknown figures explain their unknown instead of going silent.\n * The compaction attribution (when the row carries one) rides the same\n * tooltip as its closing section — real-world feedback dropped the standalone\n * badge as redundant next to the 缓存过低 marker, and the causal chain reads\n * exactly where the rate is questioned. The wording says the prefix WAS\n * rewritten and cache behaviour MAY be affected — never that compaction\n * caused a cache loss, because a high-hit row can carry the same attribution\n * (the miss severity depends on the earliest rewritten position, which the\n * plugin cannot see). */\nfunction hitTooltipOf(cache: RequestDetailCache, t: TranslateNS<'token-usage'>, attribution?: readonly CompactionAttributionItem[]): string {\n const lines: string[] = []\n if (cache.rate === undefined) {\n if (cache.reason !== undefined) lines.push(t(`pool.excluded.${cache.reason}`))\n } else {\n const display = formatRequestRate(cache.rate)\n if (cache.band === 'loss') {\n lines.push(t('pool.cache.tooltip', { rate: display }))\n // Show raw precision when rounding hides why the loss label applies.\n if (Number.parseFloat(display) >= 50) {\n lines.push(t('pool.cache.roundedDown', { rate: formatRequestRateExact(cache.rate) }))\n }\n } else if (cache.reason !== undefined) {\n lines.push(t(`pool.excluded.${cache.reason}`))\n }\n }\n if (attribution !== undefined) {\n lines.push(t('pool.attribution.prefix'))\n for (const item of attribution) {\n lines.push(item.kind === 'prune'\n ? t('pool.attribution.prune', { count: String(item.count), tokens: formatTokens(item.shadowedTokenCount) })\n : t('pool.attribution.summary', { tokens: formatTokens(item.shadowedTokenCount) }))\n }\n }\n return lines.join('\\n')\n}\n\n/** The hit cell keeps request precision, shared numeric colours, and its explanation. */\nfunction HitCell({ cache, attribution, t }: { cache: RequestDetailCache; attribution?: readonly CompactionAttributionItem[] | undefined; t: TranslateNS<'token-usage'> }): ReactNode {\n const text = formatRequestRate(cache.rate)\n const tooltip = hitTooltipOf(cache, t, attribution)\n const content = <span className={hitClassOf(cache)}>{text}</span>\n return tooltip === ''\n ? content\n : <Tooltip label={tooltip} side=\"top\" delayMs={100}><span tabIndex={0}>{content}</span></Tooltip>\n}\n\n/** The model + kind-badge pair as one non-breaking inline group: the model\n * name compresses first, the kind badge (auxiliary subtype or compaction)\n * never wraps onto its own line. Kind is always the model cell's badge —\n * the origin column states only whose session issued the request. */\nfunction ModelCell({ detail, cache, t }: { detail: RequestDetailView; cache: RequestDetailCache; t: TranslateNS<'token-usage'> }): ReactNode {\n const rawModel = detail.responseModel ?? detail.requestedModel\n const model = detail.modelId ?? rawModel\n const modelTooltip = model !== rawModel\n ? `${rawModel} → ${model}`\n : detail.responseModel !== undefined && detail.responseModel !== detail.requestedModel\n ? `${detail.requestedModel} → ${detail.responseModel}`\n : model\n const name = (\n <Tooltip label={modelTooltip} side=\"top\" delayMs={100}>\n <span className={styles['modelName']} tabIndex={0}>{model}</span>\n </Tooltip>\n )\n const kindLabel = detail.kind === 'aux' && detail.auxKind !== undefined\n ? t(`pool.kind.${detail.auxKind}`)\n : detail.kind === 'compaction'\n ? t('pool.kind.compaction')\n : undefined\n // No attribution badge of its own: the rewrite's causal chain lives in the\n // hit cell's tooltip (real-world feedback found a standalone pill redundant\n // next to the 缓存过低 marker). The loss marker shares the same tooltip, so\n // it explains the attribution too.\n if (cache.band !== 'loss') {\n return <span className={styles['modelInline']}>\n {name}\n {kindLabel !== undefined && <span className={styles['auxKind']} aria-label={kindLabel}>{kindLabel}</span>}\n </span>\n }\n return (\n <span className={styles['modelInline']}>\n {name}\n {kindLabel !== undefined && <span className={styles['auxKind']} aria-label={kindLabel}>{kindLabel}</span>}\n <Tooltip label={hitTooltipOf(cache, t, detail.compactionAttribution)} side=\"top\" delayMs={100}>\n <span className={styles['cacheLoss']} tabIndex={0}>\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"m10.3 3.8-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.7-3.2l-8-14a2 2 0 0 0-3.4 0Z\" /><path d=\"M12 9v4m0 4h.01\" /></svg>\n {t('pool.cache.label')}\n </span>\n </Tooltip>\n </span>\n )\n}\n\n/** The status cell carries the lifecycle state only: kind is the model\n * cell's badge, origin stays in the origin column — no dimension doubles\n * as another. */\nfunction stateTextOf(detail: RequestDetailView, t: TranslateNS<'token-usage'>): string {\n return t(`pool.state.${detail.state}`)\n}\n\n/** Latency column: settled rows show their measured latency; in-flight rows\n * show the server-anchored elapsed (已耗时); untimed rows stay —. */\nfunction latencyTextOf(detail: RequestDetailView): string {\n if (detail.state === 'waiting' || detail.state === 'streaming') {\n return detail.elapsedMs !== undefined ? formatTtft(detail.elapsedMs) : '—'\n }\n return detail.latencyMs !== undefined ? formatTtft(detail.latencyMs) : '—'\n}\n\n/** Speed column: the server's settled gate only — in-flight rows read —\n * (the lifecycle contract: no live token counts exist to average over; the\n * component double-checks the state so a stale field can never read as a\n * live speed). */\nfunction speedTextOf(detail: RequestDetailView): string {\n return detail.state === 'completed' && detail.speed !== undefined\n ? `${String(Math.round(detail.speed))} tok/s`\n : '—'\n}\n\n/** Cost column: priced figures render through the view; unpriced and\n * usage-less rows show — (never a fabricated zero). */\nfunction costTextOf(detail: RequestDetailView, view: CurrencyView): string {\n return detail.cost !== undefined && detail.pricingStatus === 'priced' ? formatCost(detail.cost, view) : '—'\n}\n\n/** Token-bucket text: a present count formats; an absent one stays —\n * (explicit 0 is a count and renders 0). */\nfunction tokenTextOf(value: number | undefined): string {\n return value !== undefined ? formatTokens(value) : '—'\n}\n\nfunction MetricValue({ text, unit = '' }: { text: string; unit?: string }): ReactNode {\n // Units stay visually quiet; the full text remains one accessible value.\n const match = text.match(/^(.*?)(tok\\/s|s)$/)\n const value = match?.[1] ?? text\n const suffix = text === '—' ? '' : match?.[2] ?? unit\n return <span>{value}{suffix !== '' && <span className={styles['metricUnit']}>{suffix}</span>}</span>\n}\n\n/** The panel's one-line notice: what it shows, how it reads, and the full\n * text behind the tooltip. `text` is the slot's line; `full` never drops a\n * fact the reader would otherwise lose. */\ninterface PanelNotice {\n /** 页脚右槽显示的一行文本。 */\n text: string\n /** Tooltip 的完整说明(可能比显示的长:会话状态 + 请求自身的诊断)。 */\n full: string\n /** 语气:`pending` 进行中(琥珀)、`error` 失败(红)、`neutral` 已结算(灰)。 */\n tone: 'pending' | 'error' | 'neutral'\n}\n\n/** 已结算请求自身的诊断说明:辅助请求不重复解释(紧凑标记已经说明),\n * 缓存排除与计时/用量/定价的缺口各自说明自己。 */\nfunction diagnosticOf(detail: RequestDetailView, t: TranslateNS<'token-usage'>): string {\n if (detail.kind === 'aux') return ''\n if (detail.pricingStatus === 'unpriced') return t('pool.note.unpriced')\n if (detail.inputTokens === undefined || detail.outputTokens === undefined) return t('pool.note.noUsage')\n if (detail.latencyMs === undefined || detail.firstTokenLatencyMs === undefined) return t('pool.note.untimed')\n if (detail.cache.band === 'excluded' || detail.cache.band === 'unknown') {\n return detail.cache.reason !== undefined ? t(`pool.excluded.${detail.cache.reason}`) : ''\n }\n return ''\n}\n\n/** The panel's notice: the conversation's state first (waiting for a tool\n * result / this turn is done / retrying after a failure), then the request's\n * own lifecycle, then the settled request's diagnostic. A lower-priority\n * fact never disappears — it moves into the tooltip instead, so both stay\n * reachable. */\nfunction noticeOf(\n detail: RequestDetailView,\n conversation: ConversationStatus | undefined,\n t: TranslateNS<'token-usage'>,\n): PanelNotice | undefined {\n const one = (text: string, tone: PanelNotice['tone']): PanelNotice => ({ text, full: text, tone })\n // The request's own lifecycle note. A settled (successful) row has none.\n const own = ((): PanelNotice | undefined => {\n switch (detail.state) {\n case 'waiting': return one(t('pool.note.waiting'), 'pending')\n case 'streaming': return one(t('pool.note.streaming'), 'pending')\n case 'cancelled': return one(t('pool.note.cancelled'), 'pending')\n case 'interrupted': return one(t('pool.note.interrupted'), 'pending')\n case 'failed': return one(t('pool.note.failed', { code: detail.failureCode ?? '' }), 'error')\n default: return undefined\n }\n })()\n // The settled request's own diagnostic — only a successful row carries one\n // (a failed attempt explains itself in its own note).\n const diagnostic = detail.state === 'completed' ? diagnosticOf(detail, t) : ''\n // The conversation's state is the headline; everything it outranks follows\n // it into the tooltip.\n const conversationNotice = (text: string, tone: PanelNotice['tone'], rest: string): PanelNotice => ({\n text,\n full: [text, rest, own?.text ?? '', diagnostic].filter(part => part !== '').join(' · '),\n tone,\n })\n if (conversation?.state === 'retrying') {\n const retry = conversation.retry\n const count = String(retry?.count ?? 1)\n const text = retry !== undefined && retry.max > 0\n ? t('pool.note.retrying', { count, max: String(retry.max) })\n : t('pool.note.retryingAlways', { count })\n const wait = retry === undefined\n ? ''\n : t('pool.note.retryWait', {\n seconds: String(Math.max(1, Math.round(retry.delayMs / 1000))),\n code: retry.code ?? '—',\n })\n return conversationNotice(text, 'pending', wait)\n }\n if (conversation?.state === 'awaiting-tool') {\n return conversationNotice(t('pool.note.awaitingTool'), 'pending', '')\n }\n if (conversation?.state === 'turn-complete') {\n return conversationNotice(t('pool.note.turnComplete'), 'neutral', '')\n }\n if (own !== undefined) {\n return diagnostic === '' ? own : { ...own, full: `${own.full} · ${diagnostic}` }\n }\n return diagnostic === '' ? undefined : one(diagnostic, 'neutral')\n}\n\n/** Fixed-layout column floors in px, in table order (origin, state, time,\n * model, cache hit, input, output, cache read, first token, latency, speed,\n * cost): each is the smallest width that column's content ever needs, so\n * `table-layout: fixed` can treat them as true floors — the pane shares\n * whatever surplus remains equally across all columns, and once the pane\n * can no longer fit the floors the table scrolls. The optional cache-write\n * column carries its own floor. */\nconst POOL_COL_FLOORS: readonly number[] = [52, 52, 64, 120, 56, 52, 52, 56, 44, 52, 72, 60]\nconst POOL_COL_FLOOR_CACHE_WRITE = 56\n\n/** One history row: the metrics stay in the visible order cache hit, input,\n * output, cache read, optional cache write, first token, latency, speed, cost.\n * Numbers right-aligned via the shared table CSS. */\nfunction PoolRow({ detail, focusId, view, showCacheWrite, t }: { detail: RequestDetailView; focusId: string; view: CurrencyView; showCacheWrite: boolean; t: TranslateNS<'token-usage'> }): ReactNode {\n const origin = detail.sessionId === focusId\n const time = detail.orderBasis === 'record'\n ? detail.recordTime ?? detail.orderAt\n : detail.startedAt ?? detail.orderAt\n return (\n <tr>\n <td data-label={t('pool.col.origin')} className={styles['poolOrigin']}>{t(origin ? 'pool.origin.self' : 'pool.origin.child')}</td>\n <td data-label={t('pool.col.state')} className={`${styles['poolState']} ${stateClassOf(detail.state)}`}>{stateTextOf(detail, t)}</td>\n <td data-label={t('pool.col.time')} className={styles['poolTime']}><time dateTime={new Date(time).toISOString()}>{formatTimeOfDay(time)}</time></td>\n <td data-label={t('pool.col.model')} className={styles['poolModel']}><ModelCell detail={detail} cache={detail.cache} t={t} /></td>\n <td data-label={t('pool.col.hit')}><HitCell cache={detail.cache} attribution={detail.compactionAttribution} t={t} /></td>\n <td data-label={t('pool.col.input')} title={t('pool.metric.hitInput')}>{tokenTextOf(detail.inputTokens)}</td>\n <td data-label={t('pool.col.output')}>{tokenTextOf(detail.outputTokens)}</td>\n <td data-label={t('pool.col.cacheRead')}>{tokenTextOf(detail.cacheReadTokens)}</td>\n {showCacheWrite && <td data-label={t('pool.col.cacheWrite')}>{tokenTextOf(detail.cacheWriteTokens)}</td>}\n <td data-label={t('pool.col.ttft')}>{detail.firstTokenLatencyMs !== undefined ? formatTtft(detail.firstTokenLatencyMs) : '—'}</td>\n <td data-label={t('pool.col.latency')}>{latencyTextOf(detail)}</td>\n <td data-label={t('pool.col.speed')} title={detail.state === 'waiting' || detail.state === 'streaming' ? t('pool.metric.speedSettled') : undefined}>{speedTextOf(detail)}</td>\n <td data-label={t('pool.col.cost')} className={styles['costCol']}>{costTextOf(detail, view)}</td>\n </tr>\n )\n}\n\n/**\n * Both request-pool sections: the latest panel and the history table. The\n * panel renders even for an empty pool (the empty prompt) — a session with\n * zero completed requests but one waiting must still show the area, with\n * the waiting row in it.\n */\nexport function RequestPoolSections({ details, focusId, view, staleAt, t }: RequestPoolProps): ReactNode {\n const { items, limit, activeCount } = details\n const latest = items[0]\n const history = items.slice(1)\n const showCacheWrite = items.some(item => item.cacheWriteTokens !== undefined)\n const colFloors = showCacheWrite ? [...POOL_COL_FLOORS, POOL_COL_FLOOR_CACHE_WRITE] : POOL_COL_FLOORS\n const beyond = Math.max(0, activeCount - items.filter(item => item.state === 'waiting' || item.state === 'streaming').length)\n // Scrollbar fade: the wrapper's thumb tints in only while the pane is\n // being scrolled, then fades back 800ms after the last event (the timer\n // dies with the component). Direct classList writes — no re-render.\n const wrapRef = useRef<HTMLDivElement | null>(null)\n const wrapTimer = useRef<number | undefined>(undefined)\n useEffect(() => () => window.clearTimeout(wrapTimer.current), [])\n const handleWrapScroll = (): void => {\n const box = wrapRef.current\n const cls = styles['scrolling']\n if (box === null || cls === undefined) return\n box.classList.add(cls)\n window.clearTimeout(wrapTimer.current)\n wrapTimer.current = window.setTimeout(() => {\n box.classList.remove(cls)\n }, 800)\n }\n\n const latestPanel = (\n <section className={styles['poolSection']} aria-label={t('pool.latest.title')}>\n <div className={styles['poolHead']}>\n <h3 className={styles['subtitle']}>{t('pool.latest.title')}</h3>\n <span className={styles['poolContext']}>{t('pool.latest.context')}</span>\n </div>\n {latest === undefined\n ? <div className={styles['latestPanel']}><div className={styles['poolEmpty']}>{t('pool.empty')}</div></div>\n : (\n (() => {\n const inFlight = latest.state === 'waiting' || latest.state === 'streaming'\n const origin = latest.sessionId === focusId\n const time = latest.orderBasis === 'record'\n ? latest.recordTime ?? latest.orderAt\n : latest.startedAt ?? latest.orderAt\n const notice = noticeOf(latest, details.conversation, t)\n // The note's colour follows its tone: failed reads as an error,\n // a settled note as quiet text, an in-flight / awaiting-tool note\n // as the amber 「still running」 voice.\n const noteClass = `${styles['requestNote']} ${notice?.tone === 'error'\n ? styles['requestNoteError'] ?? ''\n : notice?.tone === 'neutral'\n ? styles['requestNoteNeutral'] ?? ''\n : ''}`\n return (\n <div className={styles['latestPanel']}>\n <div className={styles['requestIdentity']}>\n <span className={styles['poolBadge']}>{t(origin ? 'pool.origin.self' : 'pool.origin.child')}</span>\n <span className={`${styles['poolState']} ${stateClassOf(latest.state)}`}><span className={styles['statusDot']} aria-hidden=\"true\" />{stateTextOf(latest, t)}</span>\n <ModelCell detail={latest} cache={latest.cache} t={t} />\n <span className={styles['poolContext']}><time dateTime={new Date(time).toISOString()}>{formatTimeOfDay(time)}</time></span>\n </div>\n <div className={styles['requestMetrics']}>\n <div>\n <div className={styles['metricValue']}><HitCell cache={latest.cache} attribution={latest.compactionAttribution} t={t} /></div>\n <div className={styles['metricLabel']}>{t('pool.col.hit')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={tokenTextOf(latest.inputTokens)} unit=\"tok\" /></div>\n <div className={styles['metricLabel']}>{t('pool.col.input')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={tokenTextOf(latest.outputTokens)} unit=\"tok\" /></div>\n <div className={styles['metricLabel']}>{t('pool.col.output')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={latest.firstTokenLatencyMs !== undefined ? formatTtft(latest.firstTokenLatencyMs) : '—'} /></div>\n <div className={styles['metricLabel']}>{t('pool.col.ttft')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={latencyTextOf(latest)} /></div>\n <div className={styles['metricLabel']} title={inFlight ? t('pool.metric.elapsed') : undefined}>{inFlight ? t('pool.metric.elapsedShort') : t('pool.col.latency')}</div>\n </div>\n <div>\n <div className={styles['metricValue']}><MetricValue text={speedTextOf(latest)} /></div>\n <div className={styles['metricLabel']}>{t('pool.col.speed')}</div>\n </div>\n </div>\n <div className={styles['requestFooter']}>\n <div className={styles['requestBuckets']}>\n <span>{t('pool.metric.cost')} <b>{costTextOf(latest, view)}</b></span>\n <span>{t('pool.metric.cacheRead')} <b>{tokenTextOf(latest.cacheReadTokens)}</b></span>\n {showCacheWrite && <span>{t('pool.metric.cacheWrite')} <b>{tokenTextOf(latest.cacheWriteTokens)}</b></span>}\n </div>\n {/* The note lives in the footer's right slot — the same\n * slot the buckets mirror — so the panel keeps one\n * height whether a note exists or not. It is one line with\n * an ellipsis; the full text is in the tooltip. */}\n {notice !== undefined\n ? (\n <Tooltip label={notice.full} side=\"top\" delayMs={100}>\n <span className={noteClass} tabIndex={0}>{notice.text}</span>\n </Tooltip>\n )\n : staleAt !== undefined\n ? <span className={styles['poolContext']}>{t('pool.asOf', { time: formatTimeOfDay(staleAt) })}</span>\n : null}\n </div>\n </div>\n )\n })()\n )}\n </section>\n )\n\n const poolTable = (\n <section className={styles['poolSection']} aria-label={t('pool.title')}>\n <div className={styles['poolHead']}>\n <h3 className={styles['subtitle']}>\n {t('pool.title')}\n <span className={styles['poolContext']}> {t('pool.historyCount', { count: String(history.length) })}</span>\n </h3>\n <span className={styles['poolContext']}>\n <span>{t('pool.newest')}</span>{' · '}<span>{t('pool.count', { count: String(items.length), limit: String(limit) })}</span>\n {beyond > 0 ? ` · ${t('pool.activeBeyond', { count: String(beyond) })}` : ''}\n </span>\n </div>\n {staleAt !== undefined && (\n <div className={styles['poolNotice']} role=\"status\">\n {t('pool.stale', { time: formatTimeOfDay(staleAt) })}\n </div>\n )}\n {history.length === 0\n ? <div className={styles['poolEmpty']}>{items.length > 0 ? t('pool.emptyHistory') : t('pool.empty')}</div>\n : (\n <div ref={wrapRef} onScroll={handleWrapScroll} className={styles['poolTableWrap']} tabIndex={0} role=\"region\" aria-label={t('pool.history.scroll')}>\n <table className={styles['poolTable']} aria-label={t('pool.title')} style={{ minWidth: `${colFloors.reduce((sum, width) => sum + width, 0)}px` }}>\n <colgroup>\n {colFloors.map((width, index) => <col key={index} style={{ width }} />)}\n </colgroup>\n <thead>\n <tr>\n <th className={styles['poolModelHead']}>{t('pool.col.origin')}</th>\n <th>{t('pool.col.state')}</th>\n <th>{t('pool.col.time')}</th>\n <th className={styles['poolModelHead']}>{t('pool.col.model')}</th>\n <th>{t('pool.col.hit')}</th>\n <th>{t('pool.col.input')}</th>\n <th>{t('pool.col.output')}</th>\n <th>{t('pool.col.cacheRead')}</th>\n {showCacheWrite && <th>{t('pool.col.cacheWrite')}</th>}\n <th>{t('pool.col.ttft')}</th>\n <th>{t('pool.col.latency')}</th>\n <th>{t('pool.col.speed')}</th>\n <th>{t('pool.col.cost')}</th>\n </tr>\n </thead>\n <tbody>\n {history.map(detail => <PoolRow key={detail.id} detail={detail} focusId={focusId} view={view} showCacheWrite={showCacheWrite} t={t} />)}\n </tbody>\n </table>\n </div>\n )}\n </section>\n )\n\n return (\n <>\n {latestPanel}\n {poolTable}\n </>\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 (successful requests with a failure\n * pill, 4 token buckets, cost, hit rate, TTFT average, decode throughput) with a\n * scope switch between the session alone and its whole subagent subtree, a\n * per-hour trend chart and the per-model table from the host stats route\n * (`sessionId`-scoped), and a subagent table below — each row drill-in\n * 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 * The root declares `data-conversation-composer-overlay` — the same host\n * opt-in Trajectory uses. ConversationRoot hides the chat-column width\n * handles when that attribute is present, and the view owns its own\n * scroller instead of sharing the transcript's constrained column.\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 { SessionListState, UseProjection } from '@deepseek-ai/dsh-api-session-controller/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 { PricingStatus, costsAvailable } from './PricingStatus.tsx'\nimport { ModelAssociationBadge, PricingAssociationProvider, UnpricedModelTag } from './PricingAssociations.tsx'\nimport { usePricingAssociationRefresh } from './pricing-associations.ts'\nimport { HitRateText } from './HitRateText.tsx'\nimport { RequestPoolSections } from './RequestPool.tsx'\nimport { aggregateProjections, buildChildIndex, directSubagentIds, subagentParentOf, subtreeIds, buildStatsFreshnessKey } from './session-stats.ts'\nimport { RequestsCell, RequestsStatCard, StatCard } from './StatCard.tsx'\nimport { TrendChart } from './TrendChart.tsx'\nimport type { TrendChartMode } 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/** Host contract (ui-conversation ConversationRoot): views that own a\n * full-bleed scroller set this so the chat-column width handles hide and\n * the composer seat overlays instead of stealing clicks over the dashboard. */\nconst COMPOSER_OVERLAY = { 'data-conversation-composer-overlay': '' } as const\n\n/** Props: the conversation-view runtime seat (standard kit) plus the locale\n * seat. The kit's `useSession` covers the Session lifecycle snapshot only;\n * the Conversation snapshot is not part of it — and this view never read it,\n * so the seat is simply dropped. */\nexport interface UsageViewProps {\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 trend chart's y-axis reading: per-interval totals or their running\n // cumulative sum. Session-local like the scope switch (no persistence).\n const [chartMode, setChartMode] = useState<TrendChartMode>('interval')\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 usePricingAssociationRefresh(retry)\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\n // Visibility fallback polling for the request pool: the event-driven\n // freshness key already refreshes on settled requests, but a WAITING row\n // produces no events between dispatch and first token. The poll is\n // SERIALIZED — the next tick is scheduled only after the previous fetch\n // settles — so a slow response is never cancelled mid-flight by the next\n // interval: with an active request the next poll runs 1s after the last\n // one finished, 5s idle, and a hidden tab schedules nothing (returning to\n // visibility refreshes once immediately).\n const [pollTick, setPollTick] = useState(0)\n const [pollSettle, setPollSettle] = useState(0)\n const [staleAt, setStaleAt] = useState<number | undefined>(undefined)\n const lastOkAtRef = useRef<number | undefined>(undefined)\n const pollTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const fetchingRef = useRef(false)\n const fetchVersionRef = useRef(0)\n // Scope changes are immediate; only event freshness is debounced. The\n // request and its cache identity must always describe the same range.\n const scopeKey = `${scopeIds.join('\\n')}\\n\\t${childGroups.map(group => group.join(',')).join(';')}`\n\n const [summaryState] = useAsyncResource<UsageSummary>(\n signal => {\n clearTimeout(pollTimerRef.current)\n fetchingRef.current = true\n const version = ++fetchVersionRef.current\n const [idsPart, groupsPart] = scopeKey.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 // Stale-snapshot honesty: a failed refresh keeps the previous\n // snapshot on screen (silentAfterFirst) and stamps the failure so the\n // pool shows \"数据截至 …\" instead of pretending to be live. A new\n // scope's first failure still lands in `error` (no snapshot to keep —\n // the scopeKey switch resets both the kept value and this stamp).\n return fetchSessionSummary(sessionIds, childGroups, signal)\n .then(value => {\n if (!signal.aborted) {\n lastOkAtRef.current = Date.now()\n setStaleAt(undefined)\n }\n return value\n })\n .catch((error: unknown) => {\n if (!signal.aborted && lastOkAtRef.current !== undefined) setStaleAt(lastOkAtRef.current)\n throw error\n })\n .finally(() => {\n // The scheduler's heartbeat: only a SETTLED fetch schedules the\n // next one (an aborted superseded attempt stays silent).\n if (version === fetchVersionRef.current) {\n fetchingRef.current = false\n if (!signal.aborted) setPollSettle(value => value + 1)\n }\n })\n },\n [debouncedKey.split('\\n\\t')[2], retryToken, pollTick],\n { silentAfterFirst: true, retryToken, scopeKey },\n )\n // A range switch also drops the freshness stamp — it belonged to the\n // previous range's last successful fetch, not to what is on screen now.\n useEffect(() => {\n lastOkAtRef.current = undefined\n setStaleAt(undefined)\n }, [scopeKey])\n\n const activeCount = summaryState.status === 'ready' ? summaryState.value.requestDetails?.activeCount ?? 0 : 0\n const hasActive = activeCount > 0\n useEffect(() => {\n if (document.visibilityState !== 'visible' || fetchingRef.current) return\n const timer = setTimeout(() => {\n if (document.visibilityState === 'visible') setPollTick(value => value + 1)\n }, hasActive ? 1_000 : 5_000)\n pollTimerRef.current = timer\n return () => { clearTimeout(timer) }\n }, [pollSettle, hasActive])\n useEffect(() => {\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible' && !fetchingRef.current) setPollTick(value => value + 1)\n }\n document.addEventListener('visibilitychange', onVisibility)\n return () => { document.removeEventListener('visibilitychange', onVisibility) }\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']} {...COMPOSER_OVERLAY}>\n <PricingAssociationProvider view={{ symbol: '¥', rate: 1 }} t={t}>\n {header}\n <p className={styles['muted']}>{t('loading')}</p>\n </PricingAssociationProvider>\n </div>\n )\n }\n if (summaryState.status === 'error') {\n return (\n <div ref={rootRef} className={styles['root']} {...COMPOSER_OVERLAY}>\n <PricingAssociationProvider view={{ symbol: '¥', rate: 1 }} t={t}>\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 </PricingAssociationProvider>\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']} {...COMPOSER_OVERLAY}>\n <PricingAssociationProvider resolutions={summary.modelResolutions} feedVersion={summary.feedVersion} view={view} t={t}>\n {header}\n {total.requests === 0 && (total.failures ?? 0) === 0\n // The session has no recorded requests (successful or failed); the\n // stat band is skipped but the subagent table below still renders\n // (children may hold usage even when this session's scoped summary\n // is empty).\n ? <p className={styles['empty']}>{t('view.empty')}</p>\n : (\n <>\n <div className={styles['cards']}>\n <RequestsStatCard\n requests={total.requests}\n failures={total.failures ?? 0}\n failuresByCode={total.failuresByCode}\n t={t}\n />\n <StatCard label={t('stat.cost')} value={costsAvailable(summary.costState) ? 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 <PricingStatus costState={summary.costState} pricingUnavailableReason={summary.pricingUnavailableReason} associationStorageError={summary.associationStorageError} t={t} />\n {costsAvailable(summary.costState) && 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 <div className={styles['chartHead']}>\n <h3 className={styles['subtitle']}>{t('view.chart.title')}</h3>\n <div className={styles['segmented']} role=\"group\" aria-label={t('chart.mode.label')}>\n <button\n type=\"button\"\n className={chartMode === 'interval' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={chartMode === 'interval'}\n onClick={() => setChartMode('interval')}\n >\n {t('chart.mode.interval')}\n </button>\n <button\n type=\"button\"\n className={chartMode === 'cumulative' ? `${styles['segBtn']} ${styles['segActive']}` : styles['segBtn']}\n aria-pressed={chartMode === 'cumulative'}\n onClick={() => setChartMode('cumulative')}\n >\n {t('chart.mode.cumulative')}\n </button>\n </div>\n </div>\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 height={150}\n rows={summary.byDay}\n mode={chartMode}\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 title={t('stat.successFail')}>{t('stat.requestColumn')}</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']}>\n <span className={styles.modelIdentity}><span className={styles.modelName}>{row.model}</span>\n {summary.unpricedModels.includes(row.model) && <UnpricedModelTag model={row.model} t={t} />}\n <ModelAssociationBadge model={row.model} t={t} />\n </span>\n </td>\n <td>\n <RequestsCell\n requests={row.totals.requests}\n failures={row.totals.failures ?? 0}\n failuresByCode={row.totals.failuresByCode}\n t={t}\n />\n </td>\n <td className={row.totals.inputTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.inputTokens)}</td>\n <td className={row.totals.outputTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.outputTokens)}</td>\n <td className={row.totals.cacheReadTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.cacheReadTokens)}</td>\n <td className={row.totals.cacheWriteTokens === 0 ? styles['zeroDim'] : undefined}>{formatTokens(row.totals.cacheWriteTokens)}</td>\n <td><HitRateText totals={row.totals} /></td>\n <td className={styles['costCol']}>{costsAvailable(summary.costState) && !summary.unpricedModels.includes(row.model) ? 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 {summary.requestDetails !== undefined && (\n <RequestPoolSections\n details={summary.requestDetails}\n focusId={focusId}\n view={view}\n {...staleAt !== undefined ? { staleAt } : {}}\n t={t}\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 className={styles['costCol']}>\n {row !== undefined && costsAvailable(summary.costState) && costsAvailable(row.costState) ? 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 || (total.failures ?? 0) > 0) && <p className={styles['note']}>{t('view.note')}</p>}\n </PricingAssociationProvider>\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 'association.manage': '模型别名关联',\n 'association.title': '模型别名关联',\n 'association.unpricedTitle': '模型未定价',\n 'association.close': '关闭模型关联',\n 'association.choose': '关联现有模型',\n 'association.issue': '增加模型定价',\n 'association.tooltip': '此模型含手动关联:[{models}]',\n 'association.allHint': '模型别名与模型的本地映射',\n 'association.empty': '无数据',\n 'association.details': '查看/修改',\n 'association.state.active': '手动关联正在生效。',\n 'association.state.automatic-takeover': '已由自动识别接管,保存的关联未生效。',\n 'association.state.target-missing': '关联目标已失效,可重新选择或撤销。',\n 'association.state.pricing-unavailable': '定价表不可用,关联暂未生效。',\n 'association.automaticTarget': '自动目标:{model}。',\n 'association.targetDiffers': '与保存的目标 {model} 不同。',\n 'association.reactivate': '以后自动识别失败且原目标仍有效时,保存的关联会重新生效;可撤销以停止此行为。',\n 'association.automaticOnly': '该名称已有唯一自动识别结果,不能用手动关联覆盖。',\n 'association.search': '搜索模型',\n 'association.searchHint': '搜索模型 ID',\n 'association.candidates': '定价模型候选',\n 'association.noResults': '未找到模型,请调整搜索词',\n 'association.target': '所选目标:{model}',\n 'association.preview': '查看定价',\n 'association.impact': '绑定后,此别名的历史及后续用量将按所选模型计费。',\n 'association.save': '绑定模型',\n 'association.saving': '正在保存…',\n 'association.saved': '关联已保存,正在刷新用量与费用。',\n 'association.revoke': '撤销关联',\n 'association.confirmRevoke': '确认撤销',\n 'association.revokeImpact': '撤销将重新计算全部历史与后续用量;仍有自动匹配时继续定价,否则恢复未定价。',\n 'association.cancel': '取消',\n 'association.revoked': '关联已撤销,正在刷新用量与费用。',\n 'association.loadFailed': '无法加载模型关联与定价候选,请重试。',\n 'association.candidatesUnavailable': '定价候选加载失败,请重试;已保存的关联仍可查看和撤销。',\n 'association.writeFailed': '操作失败,尚未确认生效;请刷新真实状态后重试。',\n 'association.conflict': '关联或数据目录已变化,已读取当前状态;请核对后重新选择并提交。',\n 'association.migrating': '数据目录正在迁移,暂时不能修改关联。',\n 'association.targetUnavailable': '所选目标已不在当前定价表中,请刷新并重新选择。',\n 'association.refresh': '刷新当前状态',\n 'pricing.unavailable': '定价表不可用,费用暂不可计算;用量统计仍可查看。',\n 'pricing.reason.missing': '本机尚无定价镜像,请重试定价同步。',\n 'pricing.reason.unreadable': '本机定价镜像无法读取。',\n 'pricing.reason.invalid-json': '本机定价镜像不是有效 JSON。',\n 'pricing.reason.invalid-feed': '本机定价镜像未通过格式、模型 ID 或别名正则校验。',\n 'pricing.historyIncomplete': '历史源记录不完整,无法可靠重算费用;已保留可用用量统计。',\n 'pricing.associationStorageUnavailable': '本地模型关联文件无法读取或格式损坏,手动关联暂不生效;自动识别仍可使用。请先检查数据目录中的 pricing-associations.json。',\n 'pricing.identificationDetails': '查看模型识别详情',\n 'pricing.ambiguous': '模型识别存在歧义:{models}',\n 'pricing.unmatched': '未找到对应定价模型',\n 'nav.label': 'Token 用量',\n 'filter.quickRange': '快捷区间',\n 'filter.custom': '自定义',\n 'filter.dateRange': '日期范围',\n 'filter.allDates': '全部日期',\n 'filter.clear': '清除范围',\n 'filter.separator': '至',\n 'filter.model': '模型',\n 'filter.allModels': '全部模型',\n 'calendar.monthTitle': '{year}年{month}月',\n 'calendar.prevMonth': '上个月',\n 'calendar.nextMonth': '下个月',\n 'calendar.weekday.0': '一',\n 'calendar.weekday.1': '二',\n 'calendar.weekday.2': '三',\n 'calendar.weekday.3': '四',\n 'calendar.weekday.4': '五',\n 'calendar.weekday.5': '六',\n 'calendar.weekday.6': '日',\n 'stat.requests': '请求数',\n 'stat.requestColumn': '请求',\n 'stat.successFail': '成功/失败',\n 'stat.failuresPill': '失败 {count}',\n 'fail.RATE_LIMIT': '限流',\n 'fail.SERVER': '服务异常',\n 'fail.TIMEOUT': '超时',\n 'fail.TRANSPORT': '网络异常',\n 'fail.EMPTY_RESPONSE': '空响应',\n 'fail.QUOTA': '配额耗尽',\n 'fail.CONTEXT_WINDOW_EXCEEDED': '上下文超限',\n 'fail.INVALID_CREDENTIAL': '凭证无效',\n 'fail.AUTH': '鉴权失败',\n 'fail.INVALID_REQUEST': '请求无效',\n 'fail.MISSING_CREDENTIAL': '缺少凭证',\n 'fail.ABORTED': '已中止',\n 'fail.REQUEST_EXTENSION': '请求扩展失败',\n 'fail.FILES_API': '文件接口异常',\n 'fail.STREAM_CLOSED': '流中断',\n 'fail.MALFORMED_RESPONSE': '响应异常',\n 'fail.UNKNOWN': '未知错误',\n 'stat.totalTokens': '总 token',\n 'stat.hitRate': '命中率',\n 'stat.cost': '费用',\n 'stat.input': '入',\n 'stat.output': '出',\n 'stat.cacheRead': '缓',\n 'stat.cacheWrite': '写',\n 'stat.overheadPill': '开销 {count}',\n 'sort.tokens': 'token',\n 'perf.toggle': '性能',\n 'perf.first': '首',\n 'perf.avgLatency': '耗时',\n 'perf.noTiming': '无计时数据',\n 'perf.lowSamples': '样本不足',\n 'perf.requestCount': '{count} 次',\n 'byModel.title': '按模型',\n 'byProvider.title': '按供应商',\n 'byProvider.unattributed': '缺失供应商',\n 'byProvider.cause.intro': '可能是:',\n 'byProvider.cause.deletedLog': '会话日志已删除的历史会话',\n 'byProvider.cause.preField': '路由键字段加入前的旧会话',\n 'byProvider.cause.bypass': '不带路由键的运行开销',\n 'bySession.title': '按会话',\n 'byProject.title': '按项目',\n 'aux.tab': '运行开销',\n 'aux.kind': '类别',\n 'aux.kind.auto-review': '自动审查',\n 'aux.kind.session-title': '标题生成',\n 'aux.kind.translation': '推理翻译',\n 'aux.kind.other': '其他',\n 'aux.requests': '次数',\n 'aux.total': '合计',\n 'aux.empty': '暂无运行开销记录。',\n 'aux.subtitle': '辅助模型请求',\n 'aux.totalCount': '合计 · {count} 次',\n 'aux.requestCount': '{count} 次',\n 'aux.tooltipTotal': '运行开销 · 合计',\n 'board.projects': '项目',\n 'board.sessions': '会话',\n 'board.models': '模型',\n 'board.providers': '供应商',\n 'board.byTokens': '{count} 个 · 按总 token',\n 'board.byCost': '{count} 个 · 按费用',\n 'board.bySpeed': '{count} 个 · 按输出速度',\n 'board.sessionsCount': '共 {count} 条',\n 'trend.title': '趋势',\n 'time.minutesAgo': '{count} 分钟前',\n 'time.hoursAgo': '{count} 小时前',\n 'time.daysAgo': '{count} 天前',\n 'model.ctrlHint': '按住 Ctrl 点击:仅展示该模型',\n 'detail.switch.label': '明细维度',\n 'session.titleCol': '会话',\n 'session.group.label': '目录分组',\n 'session.group.on': '分组',\n 'session.group.off': '列表',\n 'session.untitledDir': '未指定目录',\n 'session.subagentBadge': '子会话',\n 'session.lastActive': '最近活跃',\n 'session.openHint': '按住 Ctrl 点击打开该会话(用量页签跟随该会话上次的选择)',\n 'session.workspaceDeleted': '该会话所属工作区已删除,无法跳转',\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 'pricing.table': '定价表',\n 'pricing.search': '搜索模型',\n 'pricing.used': '已用',\n 'pricing.overviewFailed': '模型定价获取失败',\n 'pricing.simCost': '模拟费用',\n 'pricing.simInput': '输入 {tokens}',\n 'pricing.simCache': '(缓存 {pct}%)',\n 'pricing.simOutput': '输出 {tokens}',\n 'pricing.simBucketInput': '输入',\n 'pricing.simBucketCacheRead': '缓存读',\n 'pricing.simBucketOutput': '输出',\n 'pricing.simBucketCacheWrite': '缓存写',\n 'pricing.simCase': '案例{index}',\n 'pricing.simUnitOf': '{bucket}({unit})',\n 'pricing.expand': '展开定价条件',\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.pricingSync.button': '同步定价表',\n 'card.pricingSync.running': '同步中…',\n 'card.pricingSync.done': '定价表已同步:版本 {version},共 {models} 个模型。',\n 'card.pricingSync.failed': '定价表同步失败,已保留原有定价表,请重试。',\n 'card.pricingSync.changed': '定价区域或数据目录已变更,请重新同步。',\n 'card.pricingSync.migrating': '数据目录正在迁移,请稍后再同步。',\n 'card.pricingSync.unsaved': '请先保存或放弃设置修改,再同步定价表。',\n 'card.hint': '切换到「全球」后从 GitHub 镜像拉取定价表,费用按美元展示(RMB ÷ 汇率);保存后立即重新同步,失败沿用旧镜像。',\n 'card.overridden': '已覆盖默认值',\n 'card.sidebarPinned.label': '常驻侧边栏',\n 'card.sidebarPinned.hint': '开启后「Token 用量」固定为左侧边栏的一行,「更多」菜单中的入口随之移除;关闭后从「更多」菜单进入。更改随「保存」生效。',\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} 条,删除 {removed} 条',\n 'card.fullSync.failuresNote': ',无法读取 {count} 个 session 已跳过',\n 'card.fullSync.done': '扫描完成:新增 {added} 条,跳过 {skipped} 条,删除 {removed} 条',\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 'chart.mode.label': '趋势模式',\n 'chart.mode.interval': '分时',\n 'chart.mode.cumulative': '累计',\n 'chart.ariaCumulative': '累计 token 曲线',\n 'chart.cumulativePoint': '{day} 累计 {tokens}',\n 'chart.cumulativeBucket': '{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 'pool.latest.title': '最新请求',\n 'pool.latest.context': '单次请求 · 非会话均值',\n 'pool.title': '实时请求',\n 'pool.count': '请求池 {count} / {limit}',\n 'pool.newest': '最新优先',\n 'pool.history.scroll': '请求历史,可滚动查看',\n 'pool.pending': '请求进行中',\n 'pool.ended': '请求已结束',\n 'pool.asOf': '数据截至 {time}',\n 'pool.metric.elapsedShort': '已耗时',\n 'pool.historyCount': '{count} 条历史',\n 'pool.empty': '暂无请求 · 发起第一条请求后,速度与缓存信息将在这里展示',\n 'pool.emptyHistory': '还没有上一条请求 · 下一条到来后,当前请求会移入这里',\n 'pool.loading': '正在加载…',\n 'pool.activeBeyond': '还有 {count} 条进行中的请求不在最近窗口内',\n 'pool.stale': '刷新失败 · 保留截至 {time} 的数据',\n 'pool.origin.self': '本会话',\n 'pool.origin.child': '子会话',\n 'pool.kind.compaction': '压缩',\n 'pool.kind.auto-review': '审查',\n 'pool.kind.session-title': '标题',\n 'pool.kind.translation': '翻译',\n 'pool.kind.other': '辅助',\n 'pool.attribution.prefix': '此请求发出前,宿主的压缩操作改写了上下文前缀,缓存表现可能受影响:',\n 'pool.attribution.prune': '工具结果剪枝改写了请求前缀({count} 条,剪除消息的影子 token 合计 {tokens})',\n 'pool.attribution.summary': 'LLM 摘要替换了会话历史(影子 token {tokens})',\n 'pool.state.waiting': '等待首 token',\n 'pool.state.streaming': '生成中',\n 'pool.state.completed': '已完成',\n 'pool.state.failed': '失败',\n 'pool.state.cancelled': '已取消',\n 'pool.state.interrupted': '连接中断',\n 'pool.state.recordTime': '记录时间',\n 'pool.col.origin': '来源',\n 'pool.col.state': '状态',\n 'pool.col.time': '时间',\n 'pool.col.model': '模型',\n 'pool.col.hit': '缓存命中',\n 'pool.col.cacheRead': '缓存读',\n 'pool.col.cacheWrite': '缓存写',\n 'pool.col.input': '输入',\n 'pool.col.output': '输出',\n 'pool.col.ttft': '首字',\n 'pool.col.latency': '耗时',\n 'pool.col.speed': '速度',\n 'pool.col.cost': '费用',\n 'pool.metric.cost': '本次费用',\n 'pool.metric.cacheRead': '缓存读',\n 'pool.metric.cacheWrite': '缓存写',\n 'pool.metric.hitInput': '未缓存输入(缓存读另列,不计入输入)',\n 'pool.metric.ttft': '首个非空模型增量(含推理/工具参数),非仅可见正文首字',\n 'pool.metric.speedSettled': '输出 token ÷ 生成时长(首字后),生成时长不足 500ms 或计时缺失时不显示',\n 'pool.metric.elapsed': '已耗时(按服务端时间锚定)',\n 'pool.cache.label': '缓存过低',\n 'pool.cache.tooltip': '本次缓存命中 {rate}。这是低命中提示,不代表已确认服务端缓存失效。',\n 'pool.cache.roundedDown': '显示值经四舍五入,原始命中率为 {rate}。',\n 'pool.excluded.cold-start': '会话首条请求(冷启动),不判断缓存过低',\n 'pool.excluded.model-switch': '切换模型或路由后的首条请求,不判断缓存过低',\n 'pool.excluded.in-flight': '请求尚未完成,暂不评估缓存',\n 'pool.excluded.not-success': '请求未成功完成,不贴缓存性能诊断标签',\n 'pool.excluded.compaction': '压缩请求,不做缓存性能诊断',\n 'pool.excluded.auxiliary': '辅助请求,不做缓存性能诊断',\n 'pool.excluded.cache-unreported': '服务商未报告缓存读,缺失值不当作 0',\n 'pool.excluded.insufficient-input': '输入未满足该路由的缓存条件(不足一个缓存块),不判断缓存过低',\n 'pool.excluded.invalid-data': '缓存计数缺失或矛盾,无法计算命中率',\n 'pool.note.waiting': '首 token 尚未到达;暂不计算输出速度',\n 'pool.note.streaming': '生成中 · 服务商未提供实时 token 计数,速度待结束后结算',\n 'pool.note.awaitingTool': '等待tool结果',\n 'pool.note.turnComplete': '本轮对话已完成',\n 'pool.note.retrying': '请求失败,正在重试({count}/{max})',\n 'pool.note.retryingAlways': '请求失败,正在重试(第 {count} 次)',\n 'pool.note.retryWait': '{seconds} 秒后重试 · 失败码 {code}',\n 'pool.note.cancelled': '请求被取消 · 已交付的部分用量按记录展示,不估算缺失数据',\n 'pool.note.interrupted': '连接中断 · 无法确认请求的结束状态',\n 'pool.note.unpriced': '模型未定价 · 保留 token、缓存与性能,费用显示 —',\n 'pool.note.noUsage': '服务商未报告 token 用量 · 不显示为 0',\n 'pool.note.untimed': '历史记录无完整计时 · 不以 0 或会话平均值代替',\n 'pool.note.failed': '{code} · 失败尝试独立成行,未报告用量,不计为成功请求',\n 'pool.speed.pending': '待结束后结算',\n 'pill.cost': '费用 {value}',\n 'pill.costWithSubs': '费用(含子会话){value}',\n 'pill.scopeTag': '含子会话',\n 'panel.title': '用量明细',\n 'panel.openHint': '点击展开用量明细',\n 'panel.tokens': '{value} tok',\n 'panel.hitRate': '缓存命中 {value}',\n 'panel.self': '本会话',\n 'panel.subs': '子会话 ×{count}',\n 'panel.byModel': '按模型',\n 'panel.unpriced': '未定价模型 ×{count}',\n 'panel.unpricedNote': '仅计 token',\n 'quota.trigger': '供应商配额',\n 'quota.triggerSummary': '{name} · {figure}',\n 'quota.triggerSummaryPooled': '{name} · {figure}({count} 个额度均值)',\n 'quota.panel': '供应商配额面板',\n 'quota.tier.fiveHour': '5 小时',\n 'quota.tier.weekly': '每周',\n 'quota.tier.monthly': '每月',\n 'quota.tier.other': '额度',\n 'quota.tier.balance': '余额',\n 'quota.tier.recharge': '充值余额',\n 'quota.tier.bonus': '赠金余额',\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.signedOut': '未登录 DeepSeek 账号,登录后可查看余额。',\n 'quota.error.parse': '响应解析失败({message})。',\n} as const\n\n/** English dictionary (same key set). */\nexport const en: Record<TokenUsageKey, string> = {\n 'association.manage': 'Model alias associations',\n 'association.title': 'Model alias associations',\n 'association.unpricedTitle': 'Unpriced model',\n 'association.close': 'Close model associations',\n 'association.choose': 'Associate an existing model',\n 'association.issue': 'Add model pricing',\n 'association.tooltip': 'This model includes manual associations: [{models}]',\n 'association.allHint': 'Local mappings between model aliases and models',\n 'association.empty': 'No data',\n 'association.details': 'View / edit',\n 'association.state.active': 'Manual association is active.',\n 'association.state.automatic-takeover': 'Automatic identification takes priority; the saved choice is inactive.',\n 'association.state.target-missing': 'The target is no longer available. Choose another model or revoke.',\n 'association.state.pricing-unavailable': 'Pricing is unavailable; the association is inactive.',\n 'association.automaticTarget': 'Automatic target: {model}.',\n 'association.targetDiffers': 'It differs from the saved target {model}.',\n 'association.reactivate': 'The saved choice will reactivate if automatic identification fails and the original target is still valid. Revoke to stop this behavior.',\n 'association.automaticOnly': 'This name has a unique automatic match. Manual associations cannot override it.',\n 'association.search': 'Search models',\n 'association.searchHint': 'Search model IDs',\n 'association.candidates': 'Pricing model candidates',\n 'association.noResults': 'No models found. Try another search.',\n 'association.target': 'Selected target: {model}',\n 'association.preview': 'View pricing',\n 'association.impact': 'Past and future usage of this alias will use the selected model’s pricing.',\n 'association.save': 'Bind model',\n 'association.saving': 'Saving…',\n 'association.saved': 'Association saved. Refreshing usage and costs.',\n 'association.revoke': 'Revoke association',\n 'association.confirmRevoke': 'Confirm revocation',\n 'association.revokeImpact': 'Recalculates all past and future usage. Automatic matches remain priced; otherwise the name becomes unpriced.',\n 'association.cancel': 'Cancel',\n 'association.revoked': 'Association revoked. Refreshing usage and costs.',\n 'association.loadFailed': 'Could not load associations and pricing candidates. Please retry.',\n 'association.candidatesUnavailable': 'Pricing candidates could not be loaded. Retry; saved associations can still be viewed and revoked.',\n 'association.writeFailed': 'The operation was not confirmed. Refresh the actual state before retrying.',\n 'association.conflict': 'Associations or the data directory changed. Current state was retrieved; review, choose again and submit.',\n 'association.migrating': 'The data directory is migrating. Associations cannot be changed yet.',\n 'association.targetUnavailable': 'The selected target is no longer in the current pricing table. Refresh and choose again.',\n 'association.refresh': 'Refresh current state',\n 'pricing.unavailable': 'Pricing is unavailable. Costs cannot be calculated; usage remains available.',\n 'pricing.reason.missing': 'No local pricing mirror exists yet. Retry pricing sync.',\n 'pricing.reason.unreadable': 'The local pricing mirror cannot be read.',\n 'pricing.reason.invalid-json': 'The local pricing mirror is not valid JSON.',\n 'pricing.reason.invalid-feed': 'The local mirror failed schema, model ID, or alias pattern validation.',\n 'pricing.historyIncomplete': 'Historical source records are incomplete. Reliable costs cannot be recalculated; available usage is retained.',\n 'pricing.associationStorageUnavailable': 'Local model associations are unreadable or malformed. Manual choices are inactive; automatic identification remains available. Check pricing-associations.json in the data directory.',\n 'pricing.identificationDetails': 'Model identification details',\n 'pricing.ambiguous': 'Ambiguous model identification: {models}',\n 'pricing.unmatched': 'No matching pricing model',\n 'nav.label': 'Token Usage',\n 'filter.quickRange': 'Quick range',\n 'filter.custom': 'Custom',\n 'filter.dateRange': 'Date range',\n 'filter.allDates': 'All dates',\n 'filter.clear': 'Clear range',\n 'filter.separator': 'to',\n 'filter.model': 'Model',\n 'filter.allModels': 'All models',\n 'calendar.monthTitle': '{month} {year}',\n 'calendar.prevMonth': 'Previous month',\n 'calendar.nextMonth': 'Next month',\n 'calendar.weekday.0': 'Mo',\n 'calendar.weekday.1': 'Tu',\n 'calendar.weekday.2': 'We',\n 'calendar.weekday.3': 'Th',\n 'calendar.weekday.4': 'Fr',\n 'calendar.weekday.5': 'Sa',\n 'calendar.weekday.6': 'Su',\n 'stat.requests': 'Requests',\n 'stat.requestColumn': 'Requests',\n 'stat.successFail': 'OK/Fail',\n 'stat.failuresPill': 'Failed {count}',\n 'fail.RATE_LIMIT': 'Rate limited',\n 'fail.SERVER': 'Server error',\n 'fail.TIMEOUT': 'Timed out',\n 'fail.TRANSPORT': 'Network error',\n 'fail.EMPTY_RESPONSE': 'Empty response',\n 'fail.QUOTA': 'Quota exceeded',\n 'fail.CONTEXT_WINDOW_EXCEEDED': 'Context exceeded',\n 'fail.INVALID_CREDENTIAL': 'Invalid credential',\n 'fail.AUTH': 'Auth failed',\n 'fail.INVALID_REQUEST': 'Invalid request',\n 'fail.MISSING_CREDENTIAL': 'Missing credential',\n 'fail.ABORTED': 'Aborted',\n 'fail.REQUEST_EXTENSION': 'Request extension failed',\n 'fail.FILES_API': 'Files API error',\n 'fail.STREAM_CLOSED': 'Stream closed',\n 'fail.MALFORMED_RESPONSE': 'Malformed response',\n 'fail.UNKNOWN': 'Unknown error',\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 'stat.overheadPill': 'Overhead {count}',\n 'sort.tokens': 'Tokens',\n 'perf.toggle': 'Performance',\n 'perf.first': 'first',\n 'perf.avgLatency': 'avg',\n 'perf.noTiming': 'No timing data',\n 'perf.lowSamples': 'Low samples',\n 'perf.requestCount': '{count} reqs',\n 'byModel.title': 'By model',\n 'byProvider.title': 'By provider',\n 'byProvider.unattributed': 'Missing provider',\n 'byProvider.cause.intro': 'Could be:',\n 'byProvider.cause.deletedLog': 'History sessions whose logs were deleted',\n 'byProvider.cause.preField': 'Sessions older than the route-key field',\n 'byProvider.cause.bypass': 'Bypass calls that carry no route key',\n 'bySession.title': 'By session',\n 'byProject.title': 'By project',\n 'aux.tab': 'Runtime overhead',\n 'aux.kind': 'Category',\n 'aux.kind.auto-review': 'Auto review',\n 'aux.kind.session-title': 'Session titles',\n 'aux.kind.translation': 'Translation',\n 'aux.kind.other': 'Other',\n 'aux.requests': 'Calls',\n 'aux.total': 'Total',\n 'aux.empty': 'No runtime overhead recorded.',\n 'aux.subtitle': 'Auxiliary requests',\n 'aux.totalCount': 'Total · {count}',\n 'aux.requestCount': '{count} calls',\n 'aux.tooltipTotal': 'Overhead · total',\n 'board.projects': 'Projects',\n 'board.sessions': 'Sessions',\n 'board.models': 'Models',\n 'board.providers': 'Providers',\n 'board.byTokens': '{count} · by tokens',\n 'board.byCost': '{count} · by cost',\n 'board.bySpeed': '{count} · by speed',\n 'board.sessionsCount': '{count} sessions',\n 'trend.title': 'Trend',\n 'time.minutesAgo': '{count}m ago',\n 'time.hoursAgo': '{count}h ago',\n 'time.daysAgo': '{count}d ago',\n 'model.ctrlHint': 'Ctrl+click to show only this model',\n 'detail.switch.label': 'Detail dimension',\n 'session.titleCol': 'Session',\n 'session.group.label': 'Directory grouping',\n 'session.group.on': 'Grouped',\n 'session.group.off': 'List',\n 'session.untitledDir': 'No directory',\n 'session.subagentBadge': 'Subagent',\n 'session.lastActive': 'Last active',\n 'session.openHint': 'Ctrl+click to open this session (the usage tab follows its last selection)',\n 'session.workspaceDeleted': 'The workspace for this session has been deleted and cannot be opened',\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 'pricing.table': 'Pricing',\n 'pricing.search': 'Search models',\n 'pricing.used': 'Used',\n 'pricing.overviewFailed': 'Failed to load model pricing',\n 'pricing.simCost': 'Est. cost',\n 'pricing.simInput': 'In {tokens}',\n 'pricing.simCache': ' (cache {pct}%)',\n 'pricing.simOutput': 'Out {tokens}',\n 'pricing.simBucketInput': 'Input',\n 'pricing.simBucketCacheRead': 'Cache read',\n 'pricing.simBucketOutput': 'Output',\n 'pricing.simBucketCacheWrite': 'Cache write',\n 'pricing.simCase': 'Case {index}',\n 'pricing.simUnitOf': '{bucket} ({unit})',\n 'pricing.expand': 'Show rate conditions',\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.pricingSync.button': 'Sync pricing table',\n 'card.pricingSync.running': 'Syncing…',\n 'card.pricingSync.done': 'Pricing synced: version {version}, {models} models.',\n 'card.pricingSync.failed': 'Pricing sync failed. The previous table is retained; try again.',\n 'card.pricingSync.changed': 'The pricing region or data directory changed. Sync again.',\n 'card.pricingSync.migrating': 'The data directory is moving. Try syncing later.',\n 'card.pricingSync.unsaved': 'Save or discard your settings changes before syncing pricing.',\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.sidebarPinned.label': 'Pin to sidebar',\n 'card.sidebarPinned.hint': 'Shows Token Usage as a resident sidebar row and removes it from the More menu; when off, the entry lives in the sidebar More menu. Changes apply on save.',\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}, removed {removed}',\n 'card.fullSync.failuresNote': ', {count} unreadable sessions skipped',\n 'card.fullSync.done': 'Scan complete: added {added}, skipped {skipped}, removed {removed}',\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 'chart.mode.label': 'Trend mode',\n 'chart.mode.interval': 'Interval',\n 'chart.mode.cumulative': 'Cumulative',\n 'chart.ariaCumulative': 'Cumulative token trend',\n 'chart.cumulativePoint': '{day} cumulative {tokens}',\n 'chart.cumulativeBucket': '{window} · {count} requests · cumulative {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 'pool.latest.title': 'Latest request',\n 'pool.latest.context': 'single request · not a session mean',\n 'pool.title': 'Live requests',\n 'pool.count': 'pool {count} / {limit}',\n 'pool.newest': 'Newest first',\n 'pool.history.scroll': 'Request history, scroll to see more',\n 'pool.pending': 'Request in progress',\n 'pool.ended': 'Request ended',\n 'pool.asOf': 'Data as of {time}',\n 'pool.metric.elapsedShort': 'Elapsed',\n 'pool.historyCount': '{count} in history',\n 'pool.empty': 'No requests yet · speed and cache figures appear here after the first request',\n 'pool.emptyHistory': 'No earlier request yet · the current one moves here when the next arrives',\n 'pool.loading': 'Loading…',\n 'pool.activeBeyond': '{count} more in-flight requests outside the recent window',\n 'pool.stale': 'Refresh failed · showing data as of {time}',\n 'pool.origin.self': 'This session',\n 'pool.origin.child': 'Subagent',\n 'pool.kind.compaction': 'Compaction',\n 'pool.kind.auto-review': 'Review',\n 'pool.kind.session-title': 'Title',\n 'pool.kind.translation': 'Translation',\n 'pool.kind.other': 'Auxiliary',\n 'pool.attribution.prefix': 'Before this request, host compaction rewrote the context prefix; cache behaviour may be affected:',\n 'pool.attribution.prune': 'Tool-result pruning rewrote the request prefix ({count} event(s), shadow tokens of pruned messages {tokens})',\n 'pool.attribution.summary': 'An LLM summary replaced the conversation history (shadow tokens {tokens})',\n 'pool.state.waiting': 'Waiting for first token',\n 'pool.state.streaming': 'Generating',\n 'pool.state.completed': 'Completed',\n 'pool.state.failed': 'Failed',\n 'pool.state.cancelled': 'Cancelled',\n 'pool.state.interrupted': 'Connection lost',\n 'pool.state.recordTime': 'recorded',\n 'pool.col.origin': 'Origin',\n 'pool.col.state': 'State',\n 'pool.col.time': 'Time',\n 'pool.col.model': 'Model',\n 'pool.col.hit': 'Cache hit',\n 'pool.col.cacheRead': 'Cache read',\n 'pool.col.cacheWrite': 'Cache write',\n 'pool.col.input': 'Input',\n 'pool.col.output': 'Output',\n 'pool.col.ttft': 'First tok',\n 'pool.col.latency': 'Latency',\n 'pool.col.speed': 'Speed',\n 'pool.col.cost': 'Cost',\n 'pool.metric.cost': 'Request cost',\n 'pool.metric.cacheRead': 'Cache read',\n 'pool.metric.cacheWrite': 'Cache write',\n 'pool.metric.hitInput': 'Uncached input (cache reads listed separately, never folded in)',\n 'pool.metric.ttft': 'First non-empty model delta (reasoning / tool args included), not just visible text',\n 'pool.metric.speedSettled': 'Output tokens ÷ generation span (after first token); hidden when the span is under 500ms or timing is missing',\n 'pool.metric.elapsed': 'Elapsed (anchored to server time)',\n 'pool.cache.label': 'Low cache hit',\n 'pool.cache.tooltip': 'Cache hit {rate}. This is a low-hit hint, not confirmed server-side cache failure.',\n 'pool.cache.roundedDown': 'The displayed figure is rounded; the raw cache hit rate is {rate}.',\n 'pool.excluded.cold-start': 'First request of the session (cold start), not assessed',\n 'pool.excluded.model-switch': 'First request after a model or route switch, not assessed',\n 'pool.excluded.in-flight': 'Request not finished yet; cache not assessed',\n 'pool.excluded.not-success': 'Request did not complete successfully; no cache diagnostics label',\n 'pool.excluded.compaction': 'Compaction request; no cache diagnostics',\n 'pool.excluded.auxiliary': 'Auxiliary request; no cache diagnostics',\n 'pool.excluded.cache-unreported': 'Provider did not report cache reads; a missing value is never treated as 0',\n 'pool.excluded.insufficient-input': 'Input below this route\\'s cache minimum (under one cache block), not assessed',\n 'pool.excluded.invalid-data': 'Cache counts missing or contradictory; no hit rate computed',\n 'pool.note.waiting': 'First token not arrived; output speed not computed',\n 'pool.note.streaming': 'Generating · the provider reports no live token counts; speed settles after completion',\n 'pool.note.awaitingTool': 'Waiting for tool result',\n 'pool.note.turnComplete': 'This turn is complete',\n 'pool.note.retrying': 'Request failed, retrying ({count}/{max})',\n 'pool.note.retryingAlways': 'Request failed, retrying (attempt {count})',\n 'pool.note.retryWait': 'next attempt in {seconds}s · failure {code}',\n 'pool.note.cancelled': 'Cancelled · delivered partial usage shown as recorded, nothing estimated',\n 'pool.note.interrupted': 'Connection lost · the request\\'s final state cannot be confirmed',\n 'pool.note.unpriced': 'Model unpriced · tokens, cache and timing kept, cost shows —',\n 'pool.note.noUsage': 'Provider reported no token usage · never shown as 0',\n 'pool.note.untimed': 'Historical record without complete timing · never filled with 0 or session means',\n 'pool.note.failed': '{code} · the failed attempt is its own row; unreported usage, not counted as a success',\n 'pool.speed.pending': 'settles after completion',\n 'pill.cost': 'Cost {value}',\n 'pill.costWithSubs': 'Cost with subagents {value}',\n 'pill.scopeTag': 'with subagents',\n 'panel.title': 'Usage details',\n 'panel.openHint': 'click to open usage details',\n 'panel.tokens': '{value} tok',\n 'panel.hitRate': 'cache hit {value}',\n 'panel.self': 'This session',\n 'panel.subs': 'Subagents ×{count}',\n 'panel.byModel': 'By model',\n 'panel.unpriced': 'Unpriced model ×{count}',\n 'panel.unpricedNote': 'tokens only',\n 'quota.trigger': 'Provider quota',\n 'quota.triggerSummary': '{name} · {figure}',\n 'quota.triggerSummaryPooled': '{name} · {figure} (mean of {count} quota meters)',\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.other': 'Quota',\n 'quota.tier.balance': 'Balance',\n 'quota.tier.recharge': 'Topped-up balance',\n 'quota.tier.bonus': 'Granted 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.signedOut': 'Sign in to DeepSeek to view the account balance.',\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 navigation service (`ctx.uiWorkspace.pickDirectory`), the same\n * native directory picker the workspace flows use. Export discipline: the\n * /client entry exposes only what cordis loading needs.\n *\n * @module token-usage/client\n */\n\n// dsh-client-runtime is long gone; its ClientContext was a plain alias of\n// the cordis Context, so the type comes from cordis directly.\n// Type-only: pulls the ctx.slots declaration merge (owned by ui-renderer,\n// whose published types no longer re-declare it through ui-session).\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\n// Type-only: pulls ctx.uiWorkspace (directory picker) into this program.\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/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-sidebar SlotMap merge ('sidebar.panellist.actions',\n// dsh 0.2.1-rc.3+) into this program.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'\n// Type-only: pulls the ui-layout SlotMap merge ('main' keyed) and the\n// MainPanelId brand the layout service's selectPanel takes.\nimport type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface SlotMap {\n /**\n * A bundle's own configuration on the Plugins page, keyed by package name.\n */\n 'plugins.bundle.config': { kind: 'keyed'; scope: 'root'; owner: { readonly view: 'summary' | 'page' } }\n }\n}\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 type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { UiWorkspace } from '@deepseek-ai/dsh-client-ui-workspace/client'\nimport type { SessionId } from '@deepseek-ai/dsh-client-connection/client'\n\ninterface WorkspaceItemLike {\n readonly workspaceId: string\n readonly sessionIds: readonly SessionId[]\n}\n\ninterface WorkspaceSnapshotLike {\n readonly items: readonly WorkspaceItemLike[]\n readonly phase?: 'pending' | 'ready'\n}\n\ninterface WorkspacesLike {\n readonly list?: {\n getSnapshot(): WorkspaceSnapshotLike\n }\n}\nimport { CardForm, createFallbackTarget, type CardFormTarget, type SectionValue } from './card-form.ts'\nimport { CostPill } from './CostPill.tsx'\nimport { PanellistMoreEntry } from './PanellistMoreEntry.tsx'\nimport { PanellistPinEntry } from './PanellistPinEntry.tsx'\nimport { QuotaButton, type ModelSelectionSource } from './QuotaButton.tsx'\nimport { TokenUsageCard } from './TokenUsageCard.tsx'\nimport { TokenUsageSection } from './TokenUsageSection.tsx'\nimport { UsagePanelPage } from './UsagePanelPage.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/**\n * Main-panel id shared by the sidebar \"More\" menu row and the page it\n * opens. The `main` slot's key domain is open (keyed); the branded\n * assertion names the panel for the layout service's selectPanel.\n */\nconst USAGE_PANEL_ID = 'token-usage' as MainPanelId\n\n/**\n * Candidate keys under which the Host may serve this plugin's settings\n * form: the entry id (the namespace) first, the full package name as a\n * fallback for a host that keyed it by package instead.\n */\nconst CONFIG_FORM_KEYS = [TOKEN_USAGE_NS, '@laoyuehanni/dsh-token-usage'] as const\n\n/** Minimal describe-mirror face: the served namespaces, subscription, first read. */\ninterface DescribeMirrorLike {\n getSnapshot(): { view?: { namespaces?: ReadonlyArray<{ ns: string }> } }\n subscribe(listener: () => void): () => void\n ensure?(): Promise<void>\n}\n\n/** The `configForms` service face as this plugin consumes it. */\ninterface ConfigFormsLike {\n /** Entry-id keyed form controller; the host NEVER returns undefined. */\n get<T>(entryId: string): CardFormTarget<T>\n /** The shared describe mirror the forms derive from. */\n describe?(): DescribeMirrorLike | undefined\n}\n\n/**\n * Resolve the form target from the describe mirror's LIVE namespace list.\n * `ConfigForms.get()` unconditionally creates and caches a controller for\n * ANY key — it never returns undefined — so key validity must come from the\n * namespaces the mirror actually serves. A `get()` on a key the mirror does\n * not list yields a controller stuck at 'unavailable' forever, and the card\n * renders nothing. No view yet (mirror still loading) answers undefined so\n * the caller keeps its current target.\n */\nconst resolveConfigFormsTarget = (forms: ConfigFormsLike): CardFormTarget<SectionValue> | undefined => {\n const namespaces = typeof forms.describe === 'function'\n ? forms.describe()?.getSnapshot()?.view?.namespaces\n : undefined\n if (namespaces === undefined) return undefined\n const served = CONFIG_FORM_KEYS.find(key => namespaces.some(row => row.ns === key))\n return served === undefined ? undefined : forms.get<SectionValue>(served)\n}\n\n/** Required services: the slot registry, the locale dictionaries, the\n * workspace navigation service (its native directory picker backs the card's\n * browse button), and the session controller (the stats page's Ctrl+click\n * session jump reads the list and opens the target). The configuration\n * source (`configForms`) attaches dynamically. */\nexport const inject = ['slots', 'locale', 'connection', 'remote', 'uiWorkspace', 'sessions', '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 // The stats page's session jump: the pure predicate drives the Ctrl-hover\n // affordance (a session outside the controller's list — archived, or a\n // pre-install log row the list never saw — renders no dashed underline and\n // refuses the click), and the jump closes the settings panel and opens the\n // session via uiWorkspace.openSession.\n const getSessions = (): ISessions | undefined =>\n (ctx.get?.('sessions') as ISessions | undefined) ?? (ctx as unknown as { sessions?: ISessions }).sessions\n const getUiWorkspace = (): UiWorkspace | undefined =>\n (ctx.get?.('uiWorkspace') as UiWorkspace | undefined) ?? (ctx as unknown as { uiWorkspace?: UiWorkspace }).uiWorkspace\n const getWorkspaces = (): WorkspacesLike | undefined =>\n (ctx.get?.('workspaces') as WorkspacesLike | undefined) ?? (ctx as unknown as { workspaces?: WorkspacesLike }).workspaces\n\n const isSessionInController = (id: string): boolean => {\n const list = getSessions()?.list?.getSnapshot()\n return list?.byId?.[id as SessionId] !== undefined\n }\n\n const isWorkspaceAlive = (id: string): boolean => {\n const ws = getWorkspaces()?.list?.getSnapshot()\n if (!ws || ws.phase === 'pending') return true\n const sid = id as SessionId\n return ws.items.some(item => item.sessionIds.includes(sid))\n }\n\n const sessionListed = (id: string): boolean => {\n return isSessionInController(id) && isWorkspaceAlive(id)\n }\n\n const openSession = (id: string): { ok: boolean; reason?: 'workspaceDeleted' | 'sessionNotFound' } => {\n if (!isSessionInController(id)) return { ok: false, reason: 'sessionNotFound' }\n if (!isWorkspaceAlive(id)) return { ok: false, reason: 'workspaceDeleted' }\n getUiWorkspace()?.openSession(id as SessionId)\n return { ok: true }\n }\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 inject: () => ({ sessionListed, openSession }),\n }, TokenUsageSection))\n\n // The main panel the sidebar entries open (the `main` keyed slot, an older\n // shell declaration than the sidebar regions). It rides ctx.slots.inject\n // WAITING on the shell's declaration — a shell without it never runs the\n // callback, so the page degrades silently and the settings section above\n // stays the only entry. The layout seat is resolved at click time (dynamic\n // like configForms below, never a top-level inject dependency): the sidebar\n // entries open this panel, and the page's session jump returns to the\n // conversation. The two sidebar entries themselves (the More-menu row and\n // the resident pinned row) register further down in syncEntries — the two\n // are mutually exclusive, so their registrations come and go with the\n // `sidebarPinned` setting.\n const selectMainPanel = (id: MainPanelId | null): void => {\n ;(ctx.get?.('layout') as { selectPanel?: (id: MainPanelId | null) => void } | undefined)?.selectPanel?.(id)\n }\n ctx.slots.inject('main', () => ctx.slots.register({\n name: 'main',\n key: USAGE_PANEL_ID,\n locale: NS,\n inject: () => ({ sessionListed, openSession, returnToConversation: () => selectMainPanel(null) }),\n }, UsagePanelPage))\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 composer-dock usage pill: one entry of the\n // `conversation.composer.dock` slot list (`order: 10`, after the\n // official stats pills' `order: 0`), wearing the official pill skin so\n // the row reads as one family. The figure is the WITH-SUBAGENTS fold —\n // the one number no official surface carries; a solo session renders it\n // bare, and a subtree scope adds a quiet \"with subagents\" badge. The\n // click-open detail panel carries the folded token figure and cache-hit\n // rate (official pills show only the single-session token count), the\n // session / subagents split, and the per-model breakdown. The component\n // self-gates: a session with zero recorded requests renders nothing; a\n // transient fetch miss keeps the previous render.\n ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({\n name: 'conversation.composer.dock',\n id: 'token-usage-cost',\n order: 10,\n locale: NS,\n }, CostPill))\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 // Configuration source resolution: ctx.configForms provides the ConfigForm\n // (keyed by the entry id the describe mirror actually serves; see\n // resolveConfigFormsTarget). Before the service mounts, the placeholder\n // target keeps the card inert instead of throwing.\n const lookupCurrentTarget = (): CardFormTarget<SectionValue> | undefined => {\n const configForms = ctx.get('configForms') as ConfigFormsLike | undefined\n if (configForms && typeof configForms.get === 'function') {\n return resolveConfigFormsTarget(configForms)\n }\n return undefined\n }\n\n const initialTarget = lookupCurrentTarget()\n let activeTarget: CardFormTarget<SectionValue> = initialTarget ?? createFallbackTarget()\n const targetListeners = new Set<() => void>()\n let unsubActive: (() => void) | undefined = activeTarget.subscribe(() => {\n for (const listener of targetListeners) listener()\n })\n\n const switchTarget = (next: CardFormTarget<SectionValue>): void => {\n if (next === activeTarget) return\n unsubActive?.()\n activeTarget = next\n unsubActive = activeTarget.subscribe(() => {\n for (const listener of targetListeners) listener()\n })\n for (const listener of targetListeners) listener()\n }\n\n ctx.inject(['configForms'], (configCtx) => {\n configCtx.effect(() => {\n const forms = configCtx.get('configForms') as ConfigFormsLike | undefined\n if (!forms || typeof forms.get !== 'function') return () => {}\n // The describe mirror loads asynchronously (its first snapshot holds no\n // view), so besides resolving now, follow the mirror: the moment the\n // namespace appears — or the host re-keys it — re-resolve and bind.\n const mirror = typeof forms.describe === 'function' ? forms.describe() : undefined\n const resolve = (): void => {\n const target = resolveConfigFormsTarget(forms)\n if (target !== undefined) switchTarget(target)\n }\n resolve()\n void mirror?.ensure?.()\n const unsubscribe = mirror?.subscribe(() => { resolve() })\n return () => { unsubscribe?.() }\n }, 'token-usage: configForms dynamic target')\n })\n\n const dynamicTarget: CardFormTarget<SectionValue> = {\n getSnapshot: () => activeTarget.getSnapshot(),\n subscribe: (listener) => {\n targetListeners.add(listener)\n return () => { targetListeners.delete(listener) }\n },\n set: (field, value) => activeTarget.set(field, value),\n unset: (field) => activeTarget.unset(field),\n }\n\n // The two sidebar entries are mutually exclusive — exactly one exists at\n // any time. The `sidebarPinned` volatile setting picks which: while it\n // reads true the usage entry is a resident `sidebar.panellist` row, and the\n // More-menu row is gone; while it reads false the More-menu row is back and\n // the resident row is gone (the shell's pin store is in-memory, so\n // registration alone IS the durable pin — no shell API is driven). Both\n // registrations wait on their shell declarations via slots.inject (old\n // shells never run those callbacks, so the entry degrades silently to the\n // settings section); a rejected cell (a same-priority occupant) likewise\n // just means that entry stays absent.\n let residentDisposer: (() => void) | undefined\n let moreDisposer: (() => void) | undefined\n const syncEntries = (): void => {\n const pinned = activeTarget.getSnapshot().value?.sidebarPinned === true\n if (pinned && residentDisposer === undefined) {\n try {\n residentDisposer = ctx.slots.register({\n name: 'sidebar.panellist',\n id: USAGE_PANEL_ID,\n order: 50,\n locale: NS,\n label: () => t('nav.label'),\n }, PanellistPinEntry)\n } catch {\n residentDisposer = undefined\n }\n } else if (!pinned && residentDisposer !== undefined) {\n const dispose = residentDisposer\n residentDisposer = undefined\n dispose()\n }\n if (!pinned && moreDisposer === undefined) {\n try {\n moreDisposer = ctx.slots.register({\n name: 'sidebar.panellist.actions',\n id: 'token-usage-more',\n order: 50,\n locale: NS,\n inject: () => ({ openPanel: () => selectMainPanel(USAGE_PANEL_ID) }),\n }, PanellistMoreEntry)\n } catch {\n moreDisposer = undefined\n }\n } else if (pinned && moreDisposer !== undefined) {\n const dispose = moreDisposer\n moreDisposer = undefined\n dispose()\n }\n }\n ctx.slots.inject('sidebar.panellist', () => { syncEntries(); return () => {} })\n ctx.slots.inject('sidebar.panellist.actions', () => { syncEntries(); return () => {} })\n ctx.effect(() => {\n targetListeners.add(syncEntries)\n syncEntries()\n return () => {\n targetListeners.delete(syncEntries)\n if (residentDisposer !== undefined) {\n const dispose = residentDisposer\n residentDisposer = undefined\n dispose()\n }\n if (moreDisposer !== undefined) {\n const dispose = moreDisposer\n moreDisposer = undefined\n dispose()\n }\n }\n }, 'token-usage: sidebar entries sync')\n\n // The Plugins page dispatches keyed configuration for bundles through\n // `plugins.bundle.config` (keyed by the bundle's package name).\n const form = new CardForm(dynamicTarget)\n const store = form.bind()\n ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({\n name: 'plugins.bundle.config',\n key: '@laoyuehanni/dsh-token-usage',\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.get('uiWorkspace') as {\n pickDirectory?: () => Promise<string | null>\n } | undefined)?.pickDirectory?.() ?? Promise.resolve(null),\n }),\n }, TokenUsageCard))\n}\n"],"mappings":";;;;;;;;;;;EAgBA,MAAa,aAAa;;;EAI1B,MAAa,eAAe;EAC5B,MAAa,oBAAoB;EACjC,MAAa,oBAAoB;;EAiBjC,SAAgB,oBAAoB,KAAa,QAAmC;GAClF,OAAO,OAAO,KAAI,UAAS,GAAG,IAAI,GAAG,mBAAmB,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;EAC5E;;EA6BA,SAAgB,kBAAkB,QAAgD;GAChF,OAAO,OACJ,QAAO,UAAS,MAAM,SAAS,KAAK,MAAM,OAAO,EAAE,CAAC,CACpD,KAAI,UAAS,WAAW,mBAAmB,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,CAC9D,KAAK,GAAG;EACb;;;;;;EAuBA,SAAgB,iBAAiB,SAItB;GACT,MAAM,QAAkB,CAAC;GACzB,IAAI,QAAQ,eAAe,KAAA,KAAa,QAAQ,WAAW,SAAS,GAClE,MAAM,KAAK,oBAAoB,aAAa,QAAQ,UAAU,CAAC;GAEjE,MAAM,WAAW,QAAQ,gBAAgB,KAAA,IAAY,kBAAkB,QAAQ,WAAW,IAAI;GAC9F,IAAI,aAAa,IAAI,MAAM,KAAK,QAAQ;GACxC,IAAI,QAAQ,WAAW,KAAA,KAAa,QAAQ,WAAW,QACrD,MAAM,KAAK,UAAU,QAAQ,QAAQ;GAEvC,OAAO,MAAM,WAAW,IAAI,KAAK,IAAI,MAAM,KAAK,GAAG;EACrD;;;;;;;EAgC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