@laoyuehanni/dsh-token-usage 0.4.4-rc.1 → 0.4.6

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.js CHANGED
@@ -5,8 +5,8 @@ window.__ModuleLoader__.load({
5
5
  var exports = module.exports;
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
7
  let react = require("react");
8
- let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
9
8
  let react_jsx_runtime = require("react/jsx-runtime");
9
+ let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
10
10
  //#region src/wire.ts
11
11
  /** The stats endpoint path, served by the host half's webServer route. */
12
12
  const STATS_PATH = "/token-usage/stats";
@@ -402,741 +402,157 @@ window.__ModuleLoader__.load({
402
402
  return debounced;
403
403
  }
404
404
  //#endregion
405
- //#region src/client/quota-format.ts
406
- /** Severity thresholds on the REMAINING share (percent) — the traffic-light
407
- * standard: above 60 reads green (plenty left), 20–60 yellow (watch it),
408
- * below 20 red (effectively gone). */
409
- const REMAIN_YELLOW = 60;
410
- const REMAIN_RED = 20;
411
- /** Whole-number percent, one decimal kept when it exists (`62%`, `87.5%`). */
412
- function formatQuotaPercent(value) {
413
- const rounded = Math.round(value * 10) / 10;
414
- return `${Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1)}%`;
415
- }
416
- /** A money figure with its symbol: `$6.80` / `¥110.00`. */
417
- function formatQuotaMoney(value, unit) {
418
- return `${unit === "usd" ? "$" : "¥"}${value.toFixed(2)}`;
405
+ //#region src/client/day.ts
406
+ /** Total tokens across the four buckets (billed input = input + cacheRead + cacheWrite). */
407
+ function totalTokens(totals) {
408
+ return totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens;
419
409
  }
420
- /**
421
- * The used share of one window, 0–100, whichever direction the provider
422
- * reported: the explicit `usedPercent`, else `remainingPercent` inverted,
423
- * else the balance fraction (`1 - remaining/max`). Undefined when the
424
- * window carries no computable ratio (a balance without a total).
425
- */
426
- function quotaUsedPercent(window) {
427
- if (window.usedPercent !== void 0) return clampPercent(window.usedPercent);
428
- if (window.remainingPercent !== void 0) return clampPercent(100 - window.remainingPercent);
429
- if (window.remainingValue !== void 0 && window.maxValue !== void 0 && window.maxValue > 0) return clampPercent((1 - window.remainingValue / window.maxValue) * 100);
410
+ /** Local `YYYY-MM-DD` key of a date, matching the host's day-file convention. */
411
+ function dayKeyOf(date) {
412
+ const month = String(date.getMonth() + 1).padStart(2, "0");
413
+ const day = String(date.getDate()).padStart(2, "0");
414
+ return `${date.getFullYear()}-${month}-${day}`;
430
415
  }
431
- /**
432
- * The remaining share of one window, 0–100 — the severity input (severity
433
- * reads what is LEFT, not what is spent). Mirrors {@link quotaUsedPercent}'s
434
- * fallback chain in the opposite direction.
435
- */
436
- function quotaRemainingPercent(window) {
437
- if (window.remainingPercent !== void 0) return clampPercent(window.remainingPercent);
438
- if (window.usedPercent !== void 0) return clampPercent(100 - window.usedPercent);
439
- if (window.remainingValue !== void 0 && window.maxValue !== void 0 && window.maxValue > 0) return clampPercent(window.remainingValue / window.maxValue * 100);
416
+ /** Local day key of today shifted by whole days (test seam on `now`). */
417
+ function shiftedDayKey(deltaDays, now = () => /* @__PURE__ */ new Date()) {
418
+ const date = now();
419
+ date.setDate(date.getDate() + deltaDays);
420
+ return dayKeyOf(date);
440
421
  }
441
- /** Map a remaining share (percent) to the traffic-light band: green above
442
- * 60, yellow 20–60, red below 20. A window with no computable ratio reads
443
- * by its absolute amount: an overdrawn/empty balance (≤ 0) is red,
444
- * anything else uncolored — a plain balance never paints alarm just for
445
- * lacking a total. */
446
- function quotaSeverityOf(window) {
447
- const remaining = quotaRemainingPercent(window);
448
- if (remaining === void 0) return window.remainingValue !== void 0 && window.remainingValue <= 0 ? "exhausted" : "ok";
449
- if (remaining < REMAIN_RED) return "exhausted";
450
- if (remaining <= REMAIN_YELLOW) return "warn";
451
- return "ok";
422
+ /** The month view holding one day key. */
423
+ function monthViewOf(dayKey) {
424
+ return {
425
+ year: Number(dayKey.slice(0, 4)),
426
+ month: Number(dayKey.slice(5, 7)) - 1
427
+ };
452
428
  }
453
- /**
454
- * The FINEST-granularity window of a payload — 5-hour over weekly over
455
- * monthly over balance. The trigger icon reads this one, not the worst
456
- * across windows: the finest unit is the constraint the session is
457
- * currently acting inside (a calm 5-hour window carries the icon even when
458
- * the weekly pool runs low). Undefined when there is no window at all.
459
- */
460
- function finestQuotaWindow(windows) {
461
- const rank = {
462
- five_hour: 0,
463
- weekly: 1,
464
- monthly: 2,
465
- balance: 3
429
+ /** The month view shifted by whole months (year overflow normalized). */
430
+ function shiftMonth(view, deltaMonths) {
431
+ const total = view.year * 12 + view.month + deltaMonths;
432
+ return {
433
+ year: Math.floor(total / 12),
434
+ month: (total % 12 + 12) % 12
466
435
  };
467
- let pick;
468
- for (const window of windows) if (pick === void 0 || rank[window.tier] < rank[pick.tier]) pick = window;
469
- return pick;
470
436
  }
471
437
  /**
472
- * Fill share of the trigger ring, 0–1. Ratio windows map the remaining
473
- * percent; a funded balance without a total paints a full ring (the color
474
- * stays neutral — amounts tint only at ≤ 0); empty / overdrawn / missing
475
- * windows leave the track only.
438
+ * The month grid of one month view: Monday-first whole weeks covering the
439
+ * month, so every column aligns under its weekday header. Days of the
440
+ * neighbouring months carry `inMonth: false` — the caller renders them as
441
+ * blank placeholders, keeping the shown month's date texts unique (for
442
+ * tests and screen readers).
476
443
  */
477
- function quotaIconFillShare(window) {
478
- if (window === void 0) return 0;
479
- const remaining = quotaRemainingPercent(window);
480
- if (remaining !== void 0) return remaining / 100;
481
- if (window.remainingValue !== void 0 && window.remainingValue > 0) return 1;
482
- return 0;
444
+ function monthGrid(view) {
445
+ const leading = (new Date(view.year, view.month, 1).getDay() + 6) % 7;
446
+ const daysInMonth = new Date(view.year, view.month + 1, 0).getDate();
447
+ const total = Math.ceil((leading + daysInMonth) / 7) * 7;
448
+ const cells = [];
449
+ for (let index = 0; index < total; index++) {
450
+ const cursor = new Date(view.year, view.month, 1 - leading + index);
451
+ cells.push({
452
+ day: dayKeyOf(cursor),
453
+ inMonth: cursor.getFullYear() === view.year && cursor.getMonth() === view.month
454
+ });
455
+ }
456
+ return cells;
483
457
  }
484
458
  /**
485
- * The trigger tooltip's figure for one window: the remaining share as a
486
- * percent when a ratio exists (any direction, or the balance fraction),
487
- * else the remaining amount (a ratio-less balance, the DeepSeek shape);
488
- * undefined when the window carries neither (nothing to show beyond the
489
- * plain label).
459
+ * The zero-filled daily token series over a day range: every calendar day of
460
+ * the range appears once (days without records plot as zero). Absent bounds
461
+ * fall back to the first/last row day; no rows and no range yield [].
462
+ * @param rows - the (already filtered) per-day rows.
463
+ * @param from - first day key, inclusive.
464
+ * @param to - last day key, inclusive.
490
465
  */
491
- function quotaTriggerFigure(window) {
492
- if (window === void 0) return void 0;
493
- const remaining = quotaRemainingPercent(window);
494
- if (remaining !== void 0) return formatQuotaPercent(remaining);
495
- if (window.remainingValue !== void 0) return formatQuotaMoney(window.remainingValue, window.unit ?? "cny");
466
+ function daySeries(rows, from, to) {
467
+ const first = from ?? rows[0]?.day;
468
+ const last = to ?? (rows.length > 0 ? rows[rows.length - 1].day : void 0);
469
+ if (first === void 0 || last === void 0 || first > last) return [];
470
+ const tokens = new Map(rows.map((row) => [row.day, totalTokens(row.totals)]));
471
+ const points = [];
472
+ const cursor = /* @__PURE__ */ new Date(`${first}T00:00:00`);
473
+ const end = /* @__PURE__ */ new Date(`${last}T00:00:00`);
474
+ while (cursor <= end) {
475
+ const day = dayKeyOf(cursor);
476
+ points.push({
477
+ day,
478
+ tokens: tokens.get(day) ?? 0
479
+ });
480
+ cursor.setDate(cursor.getDate() + 1);
481
+ }
482
+ return points;
483
+ }
484
+ /** Local `YYYY-MM-DDTHH` key of a date, matching the host's hour convention. */
485
+ function hourKeyOf(date) {
486
+ const hour = String(date.getHours()).padStart(2, "0");
487
+ return `${dayKeyOf(date)}T${hour}`;
496
488
  }
497
489
  /**
498
- * The reset countdown in the shell's compact shape: `2h 14m` under a day,
499
- * `48m` under an hour, `1d 3h` above; a non-positive remainder reads `0m`
500
- * (the next poll refreshes the stale window).
501
- * @param resetAt - epoch ms of the window's reset.
502
- * @param now - epoch ms the countdown is taken at.
490
+ * The zero-filled hourly token series over a day range: every whole hour of
491
+ * the range appears once (hours without records plot as zero), so a single
492
+ * day yields the full 00:00–23:00 sequence and future hours of today read
493
+ * zero. The per-(hour, model) rows fold by hour. Absent bounds fall back to
494
+ * the first/last row hour; no rows and no range yield [].
495
+ * @param rows - the (already filtered) per-hour × per-model rows.
496
+ * @param from - first day key (`YYYY-MM-DD`), inclusive; the series starts
497
+ * at that day's 00:00.
498
+ * @param to - last day key, inclusive; the series ends at that day's 23:00.
503
499
  */
504
- function formatResetCountdown(resetAt, now) {
505
- const minutes = Math.max(0, Math.floor((resetAt - now) / 6e4));
506
- if (minutes < 60) return `${String(minutes)}m`;
507
- const hours = Math.floor(minutes / 60);
508
- if (hours < 24) return `${String(hours)}h ${String(minutes % 60)}m`;
509
- return `${String(Math.floor(hours / 24))}d ${String(hours % 24)}h`;
510
- }
511
- /** A wall-clock `HH:MM` stamp of an epoch-ms time (the "updated at" figure). */
512
- function formatQuotaClock(ms) {
513
- const date = new Date(ms);
514
- const pad = (value) => String(value).padStart(2, "0");
515
- return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
516
- }
517
- /** Clamp into 0–100. */
518
- function clampPercent(value) {
519
- return Math.min(100, Math.max(0, value));
500
+ function hourSeries(rows, from, to) {
501
+ const first = from !== void 0 ? `${from}T00` : rows[0]?.hour;
502
+ const last = to !== void 0 ? `${to}T23` : rows.length > 0 ? rows[rows.length - 1].hour : void 0;
503
+ if (first === void 0 || last === void 0 || first > last) return [];
504
+ const tokens = /* @__PURE__ */ new Map();
505
+ for (const row of rows) tokens.set(row.hour, (tokens.get(row.hour) ?? 0) + totalTokens(row.totals));
506
+ const points = [];
507
+ const cursor = /* @__PURE__ */ new Date(`${first.slice(0, 10)}T${first.slice(11)}:00:00`);
508
+ const end = /* @__PURE__ */ new Date(`${last.slice(0, 10)}T${last.slice(11)}:00:00`);
509
+ while (cursor <= end) {
510
+ const hour = hourKeyOf(cursor);
511
+ points.push({
512
+ hour,
513
+ tokens: tokens.get(hour) ?? 0
514
+ });
515
+ cursor.setHours(cursor.getHours() + 1);
516
+ }
517
+ return points;
520
518
  }
521
519
  //#endregion
522
- //#region src/client/use-color-scheme.ts
523
- /**
524
- * Shared browser-half hook: mirror the shell's root `color-scheme` onto a
525
- * plugin-owned root element. The shell sets the property on
526
- * `document.documentElement` only, so form controls inside plugin surfaces
527
- * render with the UA default (white) in dark mode; scoping the property to
528
- * the surface's root fixes selects, inputs, and dialogs without touching
529
- * anything outside it. Used by the settings section and the conversation
530
- * view tab.
531
- *
532
- * @module token-usage/client/use-color-scheme
533
- */
520
+ //#region src/client/format.ts
521
+ /** Known `LlmFailure.code`s that have a `fail.*` locale label. An unknown
522
+ * future code is not in this map and the tooltip renders it verbatim. */
523
+ const FAILURE_CODE_LABEL_KEYS = {
524
+ ABORTED: "fail.ABORTED",
525
+ AUTH: "fail.AUTH",
526
+ CONTEXT_WINDOW_EXCEEDED: "fail.CONTEXT_WINDOW_EXCEEDED",
527
+ EMPTY_RESPONSE: "fail.EMPTY_RESPONSE",
528
+ FILES_API: "fail.FILES_API",
529
+ INVALID_CREDENTIAL: "fail.INVALID_CREDENTIAL",
530
+ INVALID_REQUEST: "fail.INVALID_REQUEST",
531
+ MALFORMED_RESPONSE: "fail.MALFORMED_RESPONSE",
532
+ MISSING_CREDENTIAL: "fail.MISSING_CREDENTIAL",
533
+ QUOTA: "fail.QUOTA",
534
+ RATE_LIMIT: "fail.RATE_LIMIT",
535
+ REQUEST_EXTENSION: "fail.REQUEST_EXTENSION",
536
+ SERVER: "fail.SERVER",
537
+ STREAM_CLOSED: "fail.STREAM_CLOSED",
538
+ TIMEOUT: "fail.TIMEOUT",
539
+ TRANSPORT: "fail.TRANSPORT",
540
+ UNKNOWN: "fail.UNKNOWN"
541
+ };
542
+ /** One decimal below 10, integer otherwise, trailing `.0` stripped. */
543
+ function scale(value) {
544
+ if (value >= 10) return String(Math.round(value));
545
+ const oneDecimal = value.toFixed(1);
546
+ return oneDecimal.endsWith(".0") ? oneDecimal.slice(0, -2) : oneDecimal;
547
+ }
534
548
  /**
535
- * Mirror the shell's `color-scheme` inline style onto the given root element.
536
- * @param rootRef - the surface's root element ref.
537
- */
538
- function useColorSchemeMirror(rootRef) {
539
- (0, react.useEffect)(() => {
540
- const root = document.documentElement;
541
- const element = rootRef.current;
542
- if (element === null) return;
543
- const sync = () => {
544
- const scheme = root.style.colorScheme;
545
- if (scheme !== "") element.style.colorScheme = scheme;
546
- else element.style.removeProperty("color-scheme");
547
- };
548
- sync();
549
- const observer = new MutationObserver(sync);
550
- observer.observe(root, {
551
- attributes: true,
552
- attributeFilter: ["style"]
553
- });
554
- return () => observer.disconnect();
555
- }, [rootRef]);
556
- }
557
- /**
558
- * Hook reporting whether the current shell/page environment is in light mode.
559
- * Evaluates `document.documentElement.style.colorScheme` first (the DSH shell
560
- * rewrites this on every theme switch), falling back to `(prefers-color-scheme: light)`.
561
- */
562
- function useIsLightMode() {
563
- const [isLight, setIsLight] = (0, react.useState)(() => {
564
- if (typeof document === "undefined") return false;
565
- const rootScheme = document.documentElement.style.colorScheme;
566
- if (rootScheme === "light") return true;
567
- if (rootScheme === "dark") return false;
568
- return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: light)").matches : false;
569
- });
570
- (0, react.useEffect)(() => {
571
- if (typeof document === "undefined") return;
572
- const root = document.documentElement;
573
- const media = typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: light)") : null;
574
- const check = () => {
575
- const scheme = root.style.colorScheme;
576
- if (scheme === "light") setIsLight(true);
577
- else if (scheme === "dark") setIsLight(false);
578
- else setIsLight(media?.matches ?? false);
579
- };
580
- check();
581
- const observer = new MutationObserver(check);
582
- observer.observe(root, {
583
- attributes: true,
584
- attributeFilter: ["style"]
585
- });
586
- if (media?.addEventListener) media.addEventListener("change", check);
587
- return () => {
588
- observer.disconnect();
589
- if (media?.removeEventListener) media.removeEventListener("change", check);
590
- };
591
- }, []);
592
- return isLight;
593
- }
594
- //#endregion
595
- //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\QuotaButton.module.css.mjs
596
- const css$12 = ".jYASuG_root{flex:none;display:inline-flex;position:relative}.jYASuG_trigger{width:28px;height:28px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:999px;flex:none;place-items:center;padding:0;display:grid}.jYASuG_trigger svg{display:block}.jYASuG_trigger:hover,.jYASuG_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.jYASuG_trigger.jYASuG_icon-ok:hover,.jYASuG_trigger.jYASuG_icon-ok[aria-expanded=true]{color:var(--dsw-alias-state-success-primary)}.jYASuG_trigger.jYASuG_icon-warn:hover,.jYASuG_trigger.jYASuG_icon-warn[aria-expanded=true]{color:var(--dsw-alias-state-warn-primary)}.jYASuG_trigger.jYASuG_icon-exhausted:hover,.jYASuG_trigger.jYASuG_icon-exhausted[aria-expanded=true]{color:var(--dsw-alias-state-error-primary)}.jYASuG_icon-ok{color:var(--dsw-alias-state-success-primary)}.jYASuG_icon-warn{color:var(--dsw-alias-state-warn-primary)}.jYASuG_icon-exhausted{color:var(--dsw-alias-state-error-primary)}.jYASuG_panel{z-index:100;box-sizing:border-box;border:1px solid var(--dsw-alias-border-inverted);background:var(--dsw-specific-menu);width:320px;max-width:calc(100vw - 32px);backdrop-filter:var(--dsw-menu-backdrop-filter);box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-secondary);text-align:left;cursor:default;border-radius:12px;padding:12px;font-size:12px;line-height:20px;position:absolute;bottom:calc(100% + 8px)}.jYASuG_header{justify-content:space-between;align-items:baseline;gap:8px;margin-bottom:10px;display:flex}.jYASuG_title{color:var(--dsw-alias-label-primary);white-space:nowrap;text-overflow:ellipsis;font-size:13px;font-weight:500;overflow:hidden}.jYASuG_plan{color:var(--dsw-alias-label-tertiary);font-weight:400}.jYASuG_updated{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;flex:none;font-size:11px}.jYASuG_grid{grid-template-columns:repeat(var(--cols,3), 1fr);gap:14px;display:grid}.jYASuG_col{min-width:0}.jYASuG_label{color:var(--dsw-alias-label-tertiary);white-space:nowrap;text-overflow:ellipsis;margin-bottom:2px;font-size:11px;line-height:16px;overflow:hidden}.jYASuG_value{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;white-space:nowrap;margin-bottom:6px;font-size:13px;font-weight:600;line-height:18px}.jYASuG_meta{color:var(--dsw-alias-label-tertiary);font-size:11px;font-weight:400}.jYASuG_bar{background:var(--dsw-alias-interactive-bg-hover);border-radius:999px;height:4px;overflow:hidden}.jYASuG_fill{border-radius:999px;height:100%;transition:width .3s}.jYASuG_ok{background:var(--dsw-alias-state-success-primary)}.jYASuG_warn{background:var(--dsw-alias-state-warn-primary)}.jYASuG_exhausted{background:var(--dsw-alias-state-error-primary)}.jYASuG_aux{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;white-space:nowrap;margin-top:4px;font-size:11px;line-height:14px}.jYASuG_dot{vertical-align:middle;border-radius:50%;width:5px;height:5px;margin-right:3px;display:inline-block}.jYASuG_error{flex-direction:column;gap:8px;display:flex}.jYASuG_errorText{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;font-size:12px;line-height:18px}.jYASuG_retry{color:var(--dsw-alias-label-primary);cursor:pointer;text-underline-offset:2px;background:0 0;border:none;align-self:flex-start;padding:0;font-size:12px;text-decoration:underline}.jYASuG_retry:hover{color:var(--dsw-alias-brand-primary)}";
597
- const tagId$12 = "@laoyuehanni/dsh-token-usage/QuotaButton.module.css";
598
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$12) + "]") === null) {
599
- const tag = document.createElement("style");
600
- tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
601
- tag.dataset.pluginCss = tagId$12;
602
- tag.textContent = css$12;
603
- document.head.appendChild(tag);
604
- }
605
- var QuotaButton_module_css_default = {
606
- "aux": "jYASuG_aux",
607
- "bar": "jYASuG_bar",
608
- "col": "jYASuG_col",
609
- "dot": "jYASuG_dot",
610
- "error": "jYASuG_error",
611
- "errorText": "jYASuG_errorText",
612
- "exhausted": "jYASuG_exhausted",
613
- "fill": "jYASuG_fill",
614
- "grid": "jYASuG_grid",
615
- "header": "jYASuG_header",
616
- "icon-exhausted": "jYASuG_icon-exhausted",
617
- "icon-ok": "jYASuG_icon-ok",
618
- "icon-warn": "jYASuG_icon-warn",
619
- "label": "jYASuG_label",
620
- "meta": "jYASuG_meta",
621
- "ok": "jYASuG_ok",
622
- "panel": "jYASuG_panel",
623
- "plan": "jYASuG_plan",
624
- "retry": "jYASuG_retry",
625
- "root": "jYASuG_root",
626
- "title": "jYASuG_title",
627
- "trigger": "jYASuG_trigger",
628
- "updated": "jYASuG_updated",
629
- "value": "jYASuG_value",
630
- "warn": "jYASuG_warn"
631
- };
632
- //#endregion
633
- //#region src/client/QuotaButton.tsx
634
- /**
635
- * Input-bar quota button (browser half): a 28×28 round trigger registered
636
- * into the `conversation.input.right` slot (it renders left of the model
637
- * chip — the host's fixed tool-row order). The glyph is a remaining-share
638
- * ring (ContextMeter family) colored by the finest window. Clicking opens a
639
- * width-tiered popup (amount-only 200px / one progress bar 232px / two
640
- * bars 320px) centered on the button with the current provider's quota
641
- * windows: progress columns (5 小时 / 每周) for coding-plan providers, an
642
- * amount row for balance providers.
643
- *
644
- * The provider follows the model CHIP's live selection (the shell's
645
- * model-selection service reports the host's next selection before any
646
- * request is sent); without that service the host falls back to the last
647
- * request's provider, else the default selection.
648
- *
649
- * The button SELF-GATES: it renders nothing while the host cannot
650
- * determine a provider (`no-provider`), the provider has no quota adapter
651
- * (`unsupported`), or the feature is off (`disabled`) — switching
652
- * providers makes it appear again. A supported provider whose query fails
653
- * KEEPS the button and shows the error with a retry inside the panel.
654
- *
655
- * The hover tooltip reads provider name + the finest window's exact
656
- * remaining figure (percent, or the amount when no ratio exists).
657
- *
658
- * The interaction copies ContextMeter verbatim (click toggles, document
659
- * pointerdown outside closes, Escape closes); mutual exclusion with the
660
- * ContextMeter panel falls out of both components' outside-close
661
- * handlers — opening one closes the other on its next pointerdown.
662
- *
663
- * @module token-usage/client/QuotaButton
664
- */
665
- /** The poll cadence fallback (seconds) while no payload has named one. */
666
- const DEFAULT_POLL_SEC = 60;
667
- /** Panel width tiers (px), by how much the windows paint: a lone amount
668
- * reads at a glance, one progress bar needs breathing room, two bars (the
669
- * 5-hour + weekly coding plans, or a long error body) the full plate. Kept
670
- * in sync with the CSS max-width clamp. */
671
- const PANEL_WIDTH_BALANCE = 200;
672
- const PANEL_WIDTH_SINGLE = 232;
673
- const PANEL_WIDTH_FULL = 320;
674
- const PANEL_VIEWPORT_MARGIN = 16;
675
- /** Tier → label key; the locale dictionaries carry both languages. */
676
- const TIER_LABEL_KEYS = {
677
- five_hour: "quota.tier.fiveHour",
678
- weekly: "quota.tier.weekly",
679
- monthly: "quota.tier.monthly",
680
- balance: "quota.tier.balance"
681
- };
682
- /**
683
- * Render the input-bar quota button for the active session's provider.
684
- * @param props - the framework session id, the locale seat, and the
685
- * optional model-directory holder (the chip's live selection).
686
- * @returns the trigger + panel, or null while hidden (see the module note).
687
- */
688
- function QuotaButton({ sessionId, t, modelDirectory }) {
689
- const rootRef = (0, react.useRef)(null);
690
- useColorSchemeMirror(rootRef);
691
- const [open, setOpen] = (0, react.useState)(false);
692
- const [panelLeft, setPanelLeft] = (0, react.useState)(void 0);
693
- const measurePanelLeft = (0, react.useCallback)((width) => {
694
- const wrapper = rootRef.current;
695
- if (wrapper === null) return;
696
- const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect();
697
- const panelWidth = Math.min(width, window.innerWidth - 32);
698
- const desired = (wrapperWidth - panelWidth) / 2;
699
- const minLeft = PANEL_VIEWPORT_MARGIN - wrapperLeft;
700
- const maxLeft = window.innerWidth - PANEL_VIEWPORT_MARGIN - panelWidth - wrapperLeft;
701
- setPanelLeft(Math.min(Math.max(desired, minLeft), Math.max(minLeft, maxLeft)));
702
- }, []);
703
- const modelService = modelDirectory?.service;
704
- const readChipProvider = () => {
705
- if (sessionId === "" || modelService === void 0) return void 0;
706
- try {
707
- return modelService.directoryFor(sessionId).store.getSnapshot().current?.provider ?? void 0;
708
- } catch {
709
- return;
710
- }
711
- };
712
- const [chipProvider, setChipProvider] = (0, react.useState)(readChipProvider);
713
- (0, react.useEffect)(() => {
714
- setChipProvider(readChipProvider());
715
- if (sessionId === "" || modelService === void 0) return;
716
- let directory;
717
- try {
718
- directory = modelService.directoryFor(sessionId);
719
- } catch {
720
- return;
721
- }
722
- return directory.store.subscribe(() => {
723
- setChipProvider(readChipProvider());
724
- });
725
- }, [sessionId, modelService]);
726
- const [resource, retry] = useAsyncResource((signal) => fetchQuotaPayload(sessionId, chipProvider, signal), [sessionId, chipProvider], {
727
- silentAfterFirst: true,
728
- retryToken: 0
729
- });
730
- const payload = resource.status === "ready" ? resource.value : null;
731
- const panelWidth = panelWidthOf(payload);
732
- const pollMs = (payload?.intervalSec ?? DEFAULT_POLL_SEC) * 1e3;
733
- (0, react.useEffect)(() => {
734
- const timer = setInterval(retry, pollMs);
735
- return () => {
736
- clearInterval(timer);
737
- };
738
- }, [pollMs, retry]);
739
- const visible = payload !== null && (payload.status === "ok" || payload.status === "error");
740
- (0, react.useEffect)(() => {
741
- if (!visible && open) setOpen(false);
742
- }, [visible, open]);
743
- (0, react.useEffect)(() => {
744
- if (!open) return;
745
- const onPointerDown = (event) => {
746
- if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return;
747
- setOpen(false);
748
- };
749
- const onKeyDown = (event) => {
750
- if (event.key === "Escape") setOpen(false);
751
- };
752
- document.addEventListener("pointerdown", onPointerDown);
753
- document.addEventListener("keydown", onKeyDown);
754
- return () => {
755
- document.removeEventListener("pointerdown", onPointerDown);
756
- document.removeEventListener("keydown", onKeyDown);
757
- };
758
- }, [open]);
759
- (0, react.useEffect)(() => {
760
- if (!open) return;
761
- const onViewportChange = () => {
762
- measurePanelLeft(panelWidth);
763
- };
764
- measurePanelLeft(panelWidth);
765
- window.addEventListener("resize", onViewportChange);
766
- window.addEventListener("scroll", onViewportChange, true);
767
- return () => {
768
- window.removeEventListener("resize", onViewportChange);
769
- window.removeEventListener("scroll", onViewportChange, true);
770
- };
771
- }, [
772
- open,
773
- panelWidth,
774
- measurePanelLeft
775
- ]);
776
- if (!visible || payload === null) return null;
777
- const finest = finestQuotaWindow(payload.status === "ok" ? payload.windows : []);
778
- const severity = finest === void 0 ? "ok" : quotaSeverityOf(finest);
779
- const triggerClass = [QuotaButton_module_css_default.trigger];
780
- if (severity === "warn") triggerClass.push(QuotaButton_module_css_default["icon-warn"]);
781
- else if (severity === "exhausted") triggerClass.push(QuotaButton_module_css_default["icon-exhausted"]);
782
- else if (finest !== void 0 && quotaRemainingPercent(finest) !== void 0) triggerClass.push(QuotaButton_module_css_default["icon-ok"]);
783
- const triggerClassName = triggerClass.join(" ").trim();
784
- const figure = quotaTriggerFigure(finest);
785
- const triggerTip = figure === void 0 ? t("quota.trigger") : t("quota.triggerSummary", {
786
- name: payload.providerName ?? payload.provider,
787
- figure
788
- });
789
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
790
- ref: rootRef,
791
- className: QuotaButton_module_css_default.root,
792
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
793
- label: triggerTip,
794
- side: "top",
795
- delayMs: 200,
796
- disabled: open,
797
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
798
- type: "button",
799
- className: triggerClassName,
800
- "aria-haspopup": "dialog",
801
- "aria-expanded": open,
802
- "aria-label": t("quota.trigger"),
803
- onClick: () => {
804
- if (!open) {
805
- retry();
806
- measurePanelLeft(panelWidth);
807
- }
808
- setOpen(!open);
809
- },
810
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuotaGlyph, { share: quotaIconFillShare(finest) })
811
- })
812
- }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
813
- className: QuotaButton_module_css_default.panel,
814
- role: "dialog",
815
- "aria-label": t("quota.panel"),
816
- style: {
817
- width: `${String(panelWidth)}px`,
818
- ...panelLeft === void 0 ? {} : { left: `${String(panelLeft)}px` }
819
- },
820
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
821
- className: QuotaButton_module_css_default.header,
822
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
823
- className: QuotaButton_module_css_default.title,
824
- children: [payload.providerName ?? payload.provider, payload.status === "ok" && payload.planTier !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
825
- className: QuotaButton_module_css_default.plan,
826
- children: [" · ", payload.planTier]
827
- }) : null]
828
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
829
- className: QuotaButton_module_css_default.updated,
830
- children: t("quota.updatedAt", { time: formatQuotaClock(payload.fetchedAt) })
831
- })]
832
- }), payload.status === "error" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
833
- className: QuotaButton_module_css_default.error,
834
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
835
- className: QuotaButton_module_css_default.errorText,
836
- children: errorText(payload.error, t)
837
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
838
- type: "button",
839
- className: QuotaButton_module_css_default.retry,
840
- onClick: retry,
841
- children: t("quota.retry")
842
- })]
843
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
844
- className: QuotaButton_module_css_default.grid,
845
- style: { "--cols": String(Math.min(payload.windows.length, 3)) },
846
- children: payload.windows.map((window, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuotaColumn, {
847
- window,
848
- t
849
- }, `${window.tier}:${String(index)}`))
850
- })]
851
- })]
852
- });
853
- }
854
- /** Ring geometry matches ContextMeter: 14px viewBox, r 5.5, 2px stroke.
855
- * Circumference feeds the remaining-share dasharray, starting at 12
856
- * o'clock. A 0 share omits the fill stroke — a round cap at 0 would still
857
- * paint a dot. */
858
- const RING_R = 5.5;
859
- const RING_C = 2 * Math.PI * RING_R;
860
- /** Round caps paint half a stroke width beyond each dash end; their
861
- * combined reach is what the dash compensation subtracts, so the painted
862
- * arc (dash + caps) equals the nominal share and the caps cannot seal the
863
- * 12-o'clock gap. */
864
- const RING_CAP_REACH = 2;
865
- /** The trigger glyph: a ContextMeter-family donut whose fill arc is the
866
- * remaining share of the finest window. Color comes from the button's
867
- * severity class (`currentColor`); this only draws the arc. */
868
- function QuotaGlyph({ share }) {
869
- const clamped = Math.min(1, Math.max(0, share));
870
- const nominal = clamped * RING_C;
871
- const dashLen = clamped >= 1 ? RING_C : nominal <= RING_CAP_REACH ? nominal : nominal - RING_CAP_REACH;
872
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
873
- viewBox: "0 0 14 14",
874
- width: "14",
875
- height: "14",
876
- "aria-hidden": "true",
877
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
878
- cx: "7",
879
- cy: "7",
880
- r: RING_R,
881
- fill: "none",
882
- stroke: "currentColor",
883
- strokeWidth: "2",
884
- opacity: "0.22"
885
- }), clamped > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
886
- cx: "7",
887
- cy: "7",
888
- r: RING_R,
889
- fill: "none",
890
- stroke: "currentColor",
891
- strokeWidth: "2",
892
- strokeLinecap: clamped < 1 ? "round" : "butt",
893
- strokeDasharray: `${dashLen.toFixed(3)} ${RING_C.toFixed(3)}`,
894
- transform: "rotate(-90 7 7)"
895
- }) : null]
896
- });
897
- }
898
- /** One progress column: label / value / bar / aux. The value and the bar
899
- * both carry the REMAINING share (the traffic-light standard reads what is
900
- * left), colored by severity. */
901
- function QuotaColumn({ window, t }) {
902
- const remaining = quotaRemainingPercent(window);
903
- const severity = quotaSeverityOf(window);
904
- const label = t(TIER_LABEL_KEYS[window.tier]);
905
- let value;
906
- let meta;
907
- if (window.tier === "balance" && window.remainingValue !== void 0) {
908
- const unit = window.unit ?? "cny";
909
- value = formatQuotaMoney(window.remainingValue, unit);
910
- if (window.maxValue !== void 0) meta = `/ ${formatQuotaMoney(window.maxValue, unit)}`;
911
- } else value = remaining !== void 0 ? formatQuotaPercent(remaining) : "—";
912
- const aux = window.resetAt !== void 0 ? t("quota.resetIn", { time: formatResetCountdown(window.resetAt, Date.now()) }) : void 0;
913
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
914
- className: QuotaButton_module_css_default.col,
915
- children: [
916
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
917
- className: QuotaButton_module_css_default.label,
918
- children: label
919
- }),
920
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
921
- className: QuotaButton_module_css_default.value,
922
- children: [value, meta !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
923
- className: QuotaButton_module_css_default.meta,
924
- children: [" ", meta]
925
- }) : null]
926
- }),
927
- remaining !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
928
- className: QuotaButton_module_css_default.bar,
929
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
930
- className: `${QuotaButton_module_css_default.fill} ${QuotaButton_module_css_default[severity]}`,
931
- style: { width: `${String(Math.round(remaining))}%` }
932
- })
933
- }),
934
- aux !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
935
- className: QuotaButton_module_css_default.aux,
936
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `${QuotaButton_module_css_default.dot} ${QuotaButton_module_css_default[severity]}` }), aux]
937
- })
938
- ]
939
- });
940
- }
941
- /** The panel's width tier for one payload: what the windows PAINT decides —
942
- * a lone amount (no computable bar, the DeepSeek shape) reads at the
943
- * minimal plate, one bar (a weekly-only plan, or a balance with a spend
944
- * total like OpenRouter) the middle one, two or more bars the full plate.
945
- * Errors and payloads without windows read the full plate (their copy
946
- * runs long). */
947
- function panelWidthOf(payload) {
948
- if (payload === null || payload.status !== "ok") return PANEL_WIDTH_FULL;
949
- const bars = payload.windows.filter((window) => quotaUsedPercent(window) !== void 0).length;
950
- if (bars === 0) return payload.windows.length > 0 ? PANEL_WIDTH_BALANCE : PANEL_WIDTH_FULL;
951
- return bars === 1 ? PANEL_WIDTH_SINGLE : PANEL_WIDTH_FULL;
952
- }
953
- /** Friendly locale copy for one normalized query error. */
954
- function errorText(error, t) {
955
- switch (error.kind) {
956
- case "auth": return t("quota.error.auth", { message: error.message });
957
- case "no-credential": return t("quota.error.noCredential", { ref: error.message });
958
- case "http": return t("quota.error.http", { message: error.message });
959
- case "network": return t("quota.error.network", { message: error.message });
960
- case "parse": return t("quota.error.parse", { message: error.message });
961
- }
962
- }
963
- /** Defensive shape check: a misrouted response must not paint the button. */
964
- function looksLikeQuotaPayload(value) {
965
- return typeof value === "object" && value !== null && typeof value.status === "string" && typeof value.intervalSec === "number";
966
- }
967
- /**
968
- * Fetch the quota payload for the active session, naming the chip-selected
969
- * provider when one is known. Throws on transport failure or a payload that
970
- * does not look like one, so the hook can keep the previous render
971
- * (silentAfterFirst) or stay hidden (first failure).
972
- */
973
- async function fetchQuotaPayload(sessionId, provider, signal) {
974
- const params = new URLSearchParams();
975
- if (sessionId !== "") params.set("session", sessionId);
976
- if (provider !== void 0 && provider !== "") params.set("provider", provider);
977
- const encoded = params.toString();
978
- const query = encoded === "" ? "" : `?${encoded}`;
979
- const response = await fetch(QUOTA_PATH + query, {
980
- headers: { accept: "application/json" },
981
- signal
982
- });
983
- if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
984
- const value = await response.json();
985
- if (!looksLikeQuotaPayload(value)) throw new Error("unexpected quota response");
986
- return value;
987
- }
988
- //#endregion
989
- //#region src/client/day.ts
990
- /** Total tokens across the four buckets (billed input = input + cacheRead + cacheWrite). */
991
- function totalTokens(totals) {
992
- return totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens;
993
- }
994
- /** Local `YYYY-MM-DD` key of a date, matching the host's day-file convention. */
995
- function dayKeyOf(date) {
996
- const month = String(date.getMonth() + 1).padStart(2, "0");
997
- const day = String(date.getDate()).padStart(2, "0");
998
- return `${date.getFullYear()}-${month}-${day}`;
999
- }
1000
- /** Local day key of today shifted by whole days (test seam on `now`). */
1001
- function shiftedDayKey(deltaDays, now = () => /* @__PURE__ */ new Date()) {
1002
- const date = now();
1003
- date.setDate(date.getDate() + deltaDays);
1004
- return dayKeyOf(date);
1005
- }
1006
- /** The month view holding one day key. */
1007
- function monthViewOf(dayKey) {
1008
- return {
1009
- year: Number(dayKey.slice(0, 4)),
1010
- month: Number(dayKey.slice(5, 7)) - 1
1011
- };
1012
- }
1013
- /** The month view shifted by whole months (year overflow normalized). */
1014
- function shiftMonth(view, deltaMonths) {
1015
- const total = view.year * 12 + view.month + deltaMonths;
1016
- return {
1017
- year: Math.floor(total / 12),
1018
- month: (total % 12 + 12) % 12
1019
- };
1020
- }
1021
- /**
1022
- * The month grid of one month view: Monday-first whole weeks covering the
1023
- * month, so every column aligns under its weekday header. Days of the
1024
- * neighbouring months carry `inMonth: false` — the caller renders them as
1025
- * blank placeholders, keeping the shown month's date texts unique (for
1026
- * tests and screen readers).
1027
- */
1028
- function monthGrid(view) {
1029
- const leading = (new Date(view.year, view.month, 1).getDay() + 6) % 7;
1030
- const daysInMonth = new Date(view.year, view.month + 1, 0).getDate();
1031
- const total = Math.ceil((leading + daysInMonth) / 7) * 7;
1032
- const cells = [];
1033
- for (let index = 0; index < total; index++) {
1034
- const cursor = new Date(view.year, view.month, 1 - leading + index);
1035
- cells.push({
1036
- day: dayKeyOf(cursor),
1037
- inMonth: cursor.getFullYear() === view.year && cursor.getMonth() === view.month
1038
- });
1039
- }
1040
- return cells;
1041
- }
1042
- /**
1043
- * The zero-filled daily token series over a day range: every calendar day of
1044
- * the range appears once (days without records plot as zero). Absent bounds
1045
- * fall back to the first/last row day; no rows and no range yield [].
1046
- * @param rows - the (already filtered) per-day rows.
1047
- * @param from - first day key, inclusive.
1048
- * @param to - last day key, inclusive.
1049
- */
1050
- function daySeries(rows, from, to) {
1051
- const first = from ?? rows[0]?.day;
1052
- const last = to ?? (rows.length > 0 ? rows[rows.length - 1].day : void 0);
1053
- if (first === void 0 || last === void 0 || first > last) return [];
1054
- const tokens = new Map(rows.map((row) => [row.day, totalTokens(row.totals)]));
1055
- const points = [];
1056
- const cursor = /* @__PURE__ */ new Date(`${first}T00:00:00`);
1057
- const end = /* @__PURE__ */ new Date(`${last}T00:00:00`);
1058
- while (cursor <= end) {
1059
- const day = dayKeyOf(cursor);
1060
- points.push({
1061
- day,
1062
- tokens: tokens.get(day) ?? 0
1063
- });
1064
- cursor.setDate(cursor.getDate() + 1);
1065
- }
1066
- return points;
1067
- }
1068
- /** Local `YYYY-MM-DDTHH` key of a date, matching the host's hour convention. */
1069
- function hourKeyOf(date) {
1070
- const hour = String(date.getHours()).padStart(2, "0");
1071
- return `${dayKeyOf(date)}T${hour}`;
1072
- }
1073
- /**
1074
- * The zero-filled hourly token series over a day range: every whole hour of
1075
- * the range appears once (hours without records plot as zero), so a single
1076
- * day yields the full 00:00–23:00 sequence and future hours of today read
1077
- * zero. The per-(hour, model) rows fold by hour. Absent bounds fall back to
1078
- * the first/last row hour; no rows and no range yield [].
1079
- * @param rows - the (already filtered) per-hour × per-model rows.
1080
- * @param from - first day key (`YYYY-MM-DD`), inclusive; the series starts
1081
- * at that day's 00:00.
1082
- * @param to - last day key, inclusive; the series ends at that day's 23:00.
1083
- */
1084
- function hourSeries(rows, from, to) {
1085
- const first = from !== void 0 ? `${from}T00` : rows[0]?.hour;
1086
- const last = to !== void 0 ? `${to}T23` : rows.length > 0 ? rows[rows.length - 1].hour : void 0;
1087
- if (first === void 0 || last === void 0 || first > last) return [];
1088
- const tokens = /* @__PURE__ */ new Map();
1089
- for (const row of rows) tokens.set(row.hour, (tokens.get(row.hour) ?? 0) + totalTokens(row.totals));
1090
- const points = [];
1091
- const cursor = /* @__PURE__ */ new Date(`${first.slice(0, 10)}T${first.slice(11)}:00:00`);
1092
- const end = /* @__PURE__ */ new Date(`${last.slice(0, 10)}T${last.slice(11)}:00:00`);
1093
- while (cursor <= end) {
1094
- const hour = hourKeyOf(cursor);
1095
- points.push({
1096
- hour,
1097
- tokens: tokens.get(hour) ?? 0
1098
- });
1099
- cursor.setHours(cursor.getHours() + 1);
1100
- }
1101
- return points;
1102
- }
1103
- //#endregion
1104
- //#region src/client/format.ts
1105
- /** Known `LlmFailure.code`s that have a `fail.*` locale label. An unknown
1106
- * future code is not in this map and the tooltip renders it verbatim. */
1107
- const FAILURE_CODE_LABEL_KEYS = {
1108
- ABORTED: "fail.ABORTED",
1109
- AUTH: "fail.AUTH",
1110
- CONTEXT_WINDOW_EXCEEDED: "fail.CONTEXT_WINDOW_EXCEEDED",
1111
- EMPTY_RESPONSE: "fail.EMPTY_RESPONSE",
1112
- FILES_API: "fail.FILES_API",
1113
- INVALID_CREDENTIAL: "fail.INVALID_CREDENTIAL",
1114
- INVALID_REQUEST: "fail.INVALID_REQUEST",
1115
- MALFORMED_RESPONSE: "fail.MALFORMED_RESPONSE",
1116
- MISSING_CREDENTIAL: "fail.MISSING_CREDENTIAL",
1117
- QUOTA: "fail.QUOTA",
1118
- RATE_LIMIT: "fail.RATE_LIMIT",
1119
- REQUEST_EXTENSION: "fail.REQUEST_EXTENSION",
1120
- SERVER: "fail.SERVER",
1121
- STREAM_CLOSED: "fail.STREAM_CLOSED",
1122
- TIMEOUT: "fail.TIMEOUT",
1123
- TRANSPORT: "fail.TRANSPORT",
1124
- UNKNOWN: "fail.UNKNOWN"
1125
- };
1126
- /** One decimal below 10, integer otherwise, trailing `.0` stripped. */
1127
- function scale(value) {
1128
- if (value >= 10) return String(Math.round(value));
1129
- const oneDecimal = value.toFixed(1);
1130
- return oneDecimal.endsWith(".0") ? oneDecimal.slice(0, -2) : oneDecimal;
1131
- }
1132
- /**
1133
- * Abbreviate a token count: raw below 1K, `xxK` below 1M, `xxM` below 10 亿
1134
- * (1e9) — 1 亿 is `100M`, 2.5 亿 is `250M`, 9.5 亿 is `950M` — and `xxB`
1135
- * only from 10 亿 up (B = 10 亿, no fractional-B tier): `1B`, `1.5B`, `3B`.
1136
- * One decimal while the scaled value is below 10, integer otherwise —
1137
- * `950K`, `1.5M`, `950M`, `3B`.
1138
- * @param count - a non-negative token count.
1139
- * @returns the compact display string.
549
+ * Abbreviate a token count: raw below 1K, `xxK` below 1M, `xxM` below 10 亿
550
+ * (1e9) — 1 亿 is `100M`, 2.5 亿 is `250M`, 9.5 亿 is `950M` — and `xxB`
551
+ * only from 10 亿 up (B = 10 亿, no fractional-B tier): `1B`, `1.5B`, `3B`.
552
+ * One decimal while the scaled value is below 10, integer otherwise —
553
+ * `950K`, `1.5M`, `950M`, `3B`.
554
+ * @param count - a non-negative token count.
555
+ * @returns the compact display string.
1140
556
  */
1141
557
  function formatTokens(count) {
1142
558
  if (count < 1e3) return String(count);
@@ -1183,9 +599,11 @@ window.__ModuleLoader__.load({
1183
599
  band: bandOf(rate)
1184
600
  };
1185
601
  }
1186
- /** The RMB display view: amounts render as stored. */
602
+ /** The RMB display view: amounts render as stored. The CNY sign is the
603
+ * fullwidth ¥ (U+FFE5) — the standard RMB glyph in a Chinese UI, and the
604
+ * suffix the number-first cost idiom reads naturally with. */
1187
605
  const CNY_VIEW = {
1188
- symbol: "¥",
606
+ symbol: "¥",
1189
607
  rate: 1
1190
608
  };
1191
609
  /**
@@ -1201,15 +619,17 @@ window.__ModuleLoader__.load({
1201
619
  } : CNY_VIEW;
1202
620
  }
1203
621
  /**
1204
- * Cost as display text: the view's symbol plus two decimals, following the
1205
- * analyzer's cost formatting (`¥1.25`, `$0.18`). A cost is always shown,
1206
- * never omitted. USD divides the wire's RMB amount by the exchange rate.
622
+ * Cost as display text: two decimals plus the view's symbol SUFFIXED —
623
+ * `1.25¥` — matching the dock row's number-first unit idiom (`12.2M tok`,
624
+ * `98%`), where every reading leads with its magnitude. USD divides the
625
+ * wire's RMB amount by the exchange rate (`0.18$` under a rate-7 view).
626
+ * A cost is always shown, never omitted.
1207
627
  * @param cost - a non-negative cost in ¥ (as carried on the wire).
1208
628
  * @param view - the display currency view.
1209
- * @returns e.g. `¥1.25`, or `$0.18` under a rate-7 USD view.
629
+ * @returns e.g. `1.25¥`, or `0.18$` under a rate-7 USD view.
1210
630
  */
1211
631
  function formatCost(cost, view = CNY_VIEW) {
1212
- return `${view.symbol}${(cost / view.rate).toFixed(2)}`;
632
+ return `${(cost / view.rate).toFixed(2)}${view.symbol}`;
1213
633
  }
1214
634
  /**
1215
635
  * A per-million-token rate as display text, converted through the view:
@@ -1286,40 +706,6 @@ window.__ModuleLoader__.load({
1286
706
  return code;
1287
707
  }
1288
708
  //#endregion
1289
- //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\hit-rate-band.module.css.mjs
1290
- const css$11 = ".t6JM8a_band_critical{color:var(--dsw-alias-state-error-primary,#dc2626)}.t6JM8a_band_amber{color:#f59e0b}.t6JM8a_band_lime{color:#84cc16}.t6JM8a_band_healthy{color:var(--dsw-alias-state-success-primary,#16a34a)}";
1291
- const tagId$11 = "@laoyuehanni/dsh-token-usage/hit-rate-band.module.css";
1292
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$11) + "]") === null) {
1293
- const tag = document.createElement("style");
1294
- tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
1295
- tag.dataset.pluginCss = tagId$11;
1296
- tag.textContent = css$11;
1297
- document.head.appendChild(tag);
1298
- }
1299
- var hit_rate_band_module_css_default = {
1300
- "band_amber": "t6JM8a_band_amber",
1301
- "band_critical": "t6JM8a_band_critical",
1302
- "band_healthy": "t6JM8a_band_healthy",
1303
- "band_lime": "t6JM8a_band_lime"
1304
- };
1305
- //#endregion
1306
- //#region src/client/HitRateText.tsx
1307
- /** CSS-module class for one hit-rate colour bucket. */
1308
- function bandClassOf(band) {
1309
- return hit_rate_band_module_css_default[`band_${band}`] ?? "";
1310
- }
1311
- /**
1312
- * Render a hit-rate percentage (or `—`) in its threshold colour.
1313
- * @param totals - the aggregated token buckets the rate is computed from.
1314
- */
1315
- function HitRateText({ totals }) {
1316
- const { text, band } = hitRateDisplay(totals);
1317
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1318
- className: bandClassOf(band),
1319
- children: text
1320
- });
1321
- }
1322
- //#endregion
1323
709
  //#region src/client/session-stats.ts
1324
710
  /** Build a session-parent → direct-subagent-children index in one O(n) pass:
1325
711
  * every session whose `origin === 'subagent'` lands in its `parentId`'s
@@ -1446,6 +832,79 @@ window.__ModuleLoader__.load({
1446
832
  }).join(",");
1447
833
  }
1448
834
  //#endregion
835
+ //#region src/client/use-color-scheme.ts
836
+ /**
837
+ * Shared browser-half hook: mirror the shell's root `color-scheme` onto a
838
+ * plugin-owned root element. The shell sets the property on
839
+ * `document.documentElement` only, so form controls inside plugin surfaces
840
+ * render with the UA default (white) in dark mode; scoping the property to
841
+ * the surface's root fixes selects, inputs, and dialogs without touching
842
+ * anything outside it. Used by the settings section and the conversation
843
+ * view tab.
844
+ *
845
+ * @module token-usage/client/use-color-scheme
846
+ */
847
+ /**
848
+ * Mirror the shell's `color-scheme` inline style onto the given root element.
849
+ * @param rootRef - the surface's root element ref.
850
+ */
851
+ function useColorSchemeMirror(rootRef) {
852
+ (0, react.useEffect)(() => {
853
+ const root = document.documentElement;
854
+ const element = rootRef.current;
855
+ if (element === null) return;
856
+ const sync = () => {
857
+ const scheme = root.style.colorScheme;
858
+ if (scheme !== "") element.style.colorScheme = scheme;
859
+ else element.style.removeProperty("color-scheme");
860
+ };
861
+ sync();
862
+ const observer = new MutationObserver(sync);
863
+ observer.observe(root, {
864
+ attributes: true,
865
+ attributeFilter: ["style"]
866
+ });
867
+ return () => observer.disconnect();
868
+ }, [rootRef]);
869
+ }
870
+ /**
871
+ * Hook reporting whether the current shell/page environment is in light mode.
872
+ * Evaluates `document.documentElement.style.colorScheme` first (the DSH shell
873
+ * rewrites this on every theme switch), falling back to `(prefers-color-scheme: light)`.
874
+ */
875
+ function useIsLightMode() {
876
+ const [isLight, setIsLight] = (0, react.useState)(() => {
877
+ if (typeof document === "undefined") return false;
878
+ const rootScheme = document.documentElement.style.colorScheme;
879
+ if (rootScheme === "light") return true;
880
+ if (rootScheme === "dark") return false;
881
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: light)").matches : false;
882
+ });
883
+ (0, react.useEffect)(() => {
884
+ if (typeof document === "undefined") return;
885
+ const root = document.documentElement;
886
+ const media = typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: light)") : null;
887
+ const check = () => {
888
+ const scheme = root.style.colorScheme;
889
+ if (scheme === "light") setIsLight(true);
890
+ else if (scheme === "dark") setIsLight(false);
891
+ else setIsLight(media?.matches ?? false);
892
+ };
893
+ check();
894
+ const observer = new MutationObserver(check);
895
+ observer.observe(root, {
896
+ attributes: true,
897
+ attributeFilter: ["style"]
898
+ });
899
+ if (media?.addEventListener) media.addEventListener("change", check);
900
+ return () => {
901
+ observer.disconnect();
902
+ if (media?.removeEventListener) media.removeEventListener("change", check);
903
+ };
904
+ }, []);
905
+ return isLight;
906
+ }
907
+ //#endregion
1449
908
  //#region src/client/cost-inflate-motion.ts
1450
909
  /** The user's motion preference: both runners refuse to animate (returning
1451
910
  * null) when the OS asks for reduced motion. Exported so the chip hook can
@@ -1457,7 +916,10 @@ window.__ModuleLoader__.load({
1457
916
  function waapiAvailable(el) {
1458
917
  return typeof el.animate === "function";
1459
918
  }
1460
- /** Scale bounce on the cost figure (`costPop`). */
919
+ /** Scale bounce on the cost figure (`costPop`). The mix base is the pill's
920
+ * resting tertiary (NOT label-primary): the pill reads tertiary beside the
921
+ * official pills, and a primary-tinted final frame would leave the figure
922
+ * permanently highlighted after the animation's fill. */
1461
923
  function runCostPop(el, v) {
1462
924
  if (!motionAllowed() || !waapiAvailable(el)) return null;
1463
925
  const popScale = Number(v.popScale);
@@ -1466,44 +928,45 @@ window.__ModuleLoader__.load({
1466
928
  return el.animate([
1467
929
  {
1468
930
  transform: "scale(1)",
1469
- color: "var(--dsw-alias-label-primary)"
931
+ color: "var(--dsw-alias-label-tertiary)"
1470
932
  },
1471
933
  {
1472
934
  transform: `scale(${String(popScale)})`,
1473
- color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-primary))`,
935
+ color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-tertiary))`,
1474
936
  offset: .35
1475
937
  },
1476
938
  {
1477
939
  transform: `scale(${String(echo)})`,
1478
- color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-primary))`,
940
+ color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-tertiary))`,
1479
941
  offset: .7
1480
942
  },
1481
943
  {
1482
944
  transform: "scale(1)",
1483
- color: "var(--dsw-alias-label-primary)"
945
+ color: "var(--dsw-alias-label-tertiary)"
1484
946
  }
1485
947
  ], {
1486
948
  duration: v.inflateMs,
1487
- easing: "cubic-bezier(0.25, 0.85, 0.35, 1)",
1488
- fill: "both"
949
+ easing: "cubic-bezier(0.25, 0.85, 0.35, 1)"
1489
950
  });
1490
951
  }
1491
- /** +Δ label rise (`deltaRise`). Caller must position the element (absolute). */
952
+ /** +Δ label fall (`deltaFall`). Caller must position the element (absolute,
953
+ * below the pill — the dock sits under the composer, so the label falls
954
+ * away from the message scrollport rather than climbing into it). */
1492
955
  function runDeltaFly(el, v) {
1493
956
  if (!motionAllowed() || !waapiAvailable(el)) return null;
1494
957
  return el.animate([
1495
958
  {
1496
959
  opacity: 0,
1497
- transform: "translate(-50%, -20%)"
960
+ transform: "translate(-50%, 20%)"
1498
961
  },
1499
962
  {
1500
963
  opacity: 1,
1501
- transform: "translate(-50%, -20%)",
964
+ transform: "translate(-50%, 20%)",
1502
965
  offset: .15
1503
966
  },
1504
967
  {
1505
968
  opacity: 0,
1506
- transform: `translate(calc(-50% + ${v.flyX}), calc(-100% - ${v.flyY}))`
969
+ transform: `translate(calc(-50% + ${v.flyX}), calc(100% + ${v.flyY}))`
1507
970
  }
1508
971
  ], {
1509
972
  duration: v.inflateMs,
@@ -1512,25 +975,40 @@ window.__ModuleLoader__.load({
1512
975
  });
1513
976
  }
1514
977
  //#endregion
1515
- //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\SessionStatsChip.module.css.mjs
1516
- const css$10 = ".d5ISLa_strip{border:1px solid var(--dsw-alias-border-l2);font-variant-numeric:tabular-nums;background:0 0;border-radius:14px;flex:none;align-items:stretch;min-width:0;height:28px;font-size:12px;line-height:18px;display:inline-flex;overflow:hidden}.d5ISLa_stripFlyOverflow{z-index:2;position:relative;overflow:visible}.d5ISLa_cell{color:var(--dsw-alias-label-primary);white-space:nowrap;align-items:center;padding:0 10px;display:inline-flex}.d5ISLa_cell+.d5ISLa_cell{border-left:1px solid var(--dsw-alias-border-l1)}.d5ISLa_cellHit{font-weight:500}.d5ISLa_costCell{z-index:1;position:relative;overflow:visible}.d5ISLa_costInner{transform-origin:50%;z-index:2;justify-content:center;align-items:center;display:inline-flex;position:relative}.d5ISLa_deltaLayer{pointer-events:none;z-index:3;position:absolute;inset:0;overflow:visible}.d5ISLa_deltaFly{color:var(--dsw-alias-state-warn-primary);font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none;text-shadow:0 0 8px color-mix(in srgb, var(--dsw-alias-state-warn-primary) 35%, transparent);font-size:11px;font-weight:600;position:absolute;top:0;left:50%;transform:translate(-50%,-100%)}@media (prefers-reduced-motion:reduce){.d5ISLa_deltaFly{display:none}}@media (width<=560px){.d5ISLa_strip{font-size:11px}.d5ISLa_cell{padding:0 7px}}";
1517
- const tagId$10 = "@laoyuehanni/dsh-token-usage/SessionStatsChip.module.css";
1518
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$10) + "]") === null) {
978
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\CostPill.module.css.mjs
979
+ const css$12 = ".RmjJ5q_root{min-width:0;display:inline-flex;position:relative}.RmjJ5q_pill{box-sizing:border-box;max-width:100%;color:var(--dsw-alias-label-tertiary);font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));font-variant-numeric:tabular-nums;white-space:nowrap;background:0 0;border:none;border-radius:999px;align-items:center;gap:6px;padding:1px 8px;display:inline-flex}.RmjJ5q_glyph{flex:none;width:14px;height:14px}button.RmjJ5q_pill{cursor:pointer}button.RmjJ5q_pill:hover,button.RmjJ5q_pill[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}.RmjJ5q_cost{transform-origin:50%;z-index:2;display:inline-flex;position:relative}.RmjJ5q_deltaLayer{pointer-events:none;z-index:3;position:absolute;inset:0;overflow:visible}.RmjJ5q_deltaFly{color:var(--dsw-alias-state-warn-primary);font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none;text-shadow:0 0 8px color-mix(in srgb, var(--dsw-alias-state-warn-primary) 35%, transparent);margin-top:2px;font-size:11px;font-weight:600;position:absolute;top:100%;left:50%}@media (prefers-reduced-motion:reduce){.RmjJ5q_deltaFly{display:none}}.RmjJ5q_panel{background:var(--dsw-specific-menu);width:300px;backdrop-filter:var(--dsw-menu-backdrop-filter);border:1px solid var(--dsw-alias-border-inverted);box-shadow:var(--dsw-shadow-lv3);z-index:30;font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);color:var(--dsw-alias-label-primary);border-radius:12px;padding:12px 14px;position:absolute;bottom:calc(100% + 8px)}.RmjJ5q_panelHead{border-bottom:1px solid var(--dsw-alias-border-l1);justify-content:space-between;align-items:baseline;padding-bottom:8px;display:flex}.RmjJ5q_panelTitle{align-items:center;gap:6px;font-weight:600;display:inline-flex}.RmjJ5q_scopeTag{color:var(--dsw-alias-label-secondary);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:1px 5px;font-size:10px;font-weight:400}.RmjJ5q_panelTotal{font-variant-numeric:tabular-nums;font-size:14px;font-weight:600}.RmjJ5q_usageLine{font-variant-numeric:tabular-nums;align-items:center;gap:6px;margin-top:8px;display:flex}.RmjJ5q_dot{color:var(--dsw-alias-separator-primary)}.RmjJ5q_rows{flex-direction:column;margin-top:8px;display:flex}.RmjJ5q_row{font-variant-numeric:tabular-nums;justify-content:space-between;padding:4px 0;display:flex}.RmjJ5q_rowLabel{color:var(--dsw-alias-label-secondary);align-items:center;gap:6px;display:inline-flex}.RmjJ5q_rowValue{color:var(--dsw-alias-label-primary)}.RmjJ5q_rowSub .RmjJ5q_rowValue{color:var(--dsw-alias-label-secondary)}.RmjJ5q_tok{color:var(--dsw-alias-label-tertiary);margin-left:6px;font-size:11px}.RmjJ5q_groupLabel{color:var(--dsw-alias-label-tertiary);letter-spacing:.06em;margin-top:10px;font-size:10px}.RmjJ5q_requests{color:var(--dsw-alias-label-tertiary);font-size:11px}.RmjJ5q_unpriced .RmjJ5q_rowLabel,.RmjJ5q_unpriced .RmjJ5q_rowValue{color:var(--dsw-alias-label-tertiary);font-style:italic}.RmjJ5q_pending{color:var(--dsw-alias-label-tertiary)}";
980
+ const tagId$12 = "@laoyuehanni/dsh-token-usage/CostPill.module.css";
981
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$12) + "]") === null) {
1519
982
  const tag = document.createElement("style");
1520
983
  tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
1521
- tag.dataset.pluginCss = tagId$10;
1522
- tag.textContent = css$10;
984
+ tag.dataset.pluginCss = tagId$12;
985
+ tag.textContent = css$12;
1523
986
  document.head.appendChild(tag);
1524
987
  }
1525
- var SessionStatsChip_module_css_default = {
1526
- "cell": "d5ISLa_cell",
1527
- "cellHit": "d5ISLa_cellHit",
1528
- "costCell": "d5ISLa_costCell",
1529
- "costInner": "d5ISLa_costInner",
1530
- "deltaFly": "d5ISLa_deltaFly",
1531
- "deltaLayer": "d5ISLa_deltaLayer",
1532
- "strip": "d5ISLa_strip",
1533
- "stripFlyOverflow": "d5ISLa_stripFlyOverflow"
988
+ var CostPill_module_css_default = {
989
+ "cost": "RmjJ5q_cost",
990
+ "deltaFly": "RmjJ5q_deltaFly",
991
+ "deltaLayer": "RmjJ5q_deltaLayer",
992
+ "dot": "RmjJ5q_dot",
993
+ "glyph": "RmjJ5q_glyph",
994
+ "groupLabel": "RmjJ5q_groupLabel",
995
+ "panel": "RmjJ5q_panel",
996
+ "panelHead": "RmjJ5q_panelHead",
997
+ "panelTitle": "RmjJ5q_panelTitle",
998
+ "panelTotal": "RmjJ5q_panelTotal",
999
+ "pending": "RmjJ5q_pending",
1000
+ "pill": "RmjJ5q_pill",
1001
+ "requests": "RmjJ5q_requests",
1002
+ "root": "RmjJ5q_root",
1003
+ "row": "RmjJ5q_row",
1004
+ "rowLabel": "RmjJ5q_rowLabel",
1005
+ "rowSub": "RmjJ5q_rowSub",
1006
+ "rowValue": "RmjJ5q_rowValue",
1007
+ "rows": "RmjJ5q_rows",
1008
+ "scopeTag": "RmjJ5q_scopeTag",
1009
+ "tok": "RmjJ5q_tok",
1010
+ "unpriced": "RmjJ5q_unpriced",
1011
+ "usageLine": "RmjJ5q_usageLine"
1534
1012
  };
1535
1013
  //#endregion
1536
1014
  //#region src/client/CostDeltaFlyLabel.tsx
@@ -1551,7 +1029,7 @@ window.__ModuleLoader__.load({
1551
1029
  }, [vars]);
1552
1030
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1553
1031
  ref,
1554
- className: SessionStatsChip_module_css_default["deltaFly"],
1032
+ className: CostPill_module_css_default["deltaFly"],
1555
1033
  children: text
1556
1034
  });
1557
1035
  }
@@ -1599,9 +1077,9 @@ window.__ModuleLoader__.load({
1599
1077
  //#endregion
1600
1078
  //#region src/client/use-cost-inflate.ts
1601
1079
  /**
1602
- * Request-driven cost-cell inflate animation for SessionStatsChip: detects
1603
- * new usage from summary deltas and drives WAAPI motion on the cost figure
1604
- * and ephemeral +Δ fly labels.
1080
+ * Request-driven cost-figure inflate animation for the composer-dock usage
1081
+ * pill: detects new usage from summary deltas and drives WAAPI motion on
1082
+ * the cost figure and ephemeral +Δ fly labels.
1605
1083
  *
1606
1084
  * @module token-usage/client/use-cost-inflate
1607
1085
  */
@@ -1613,7 +1091,7 @@ window.__ModuleLoader__.load({
1613
1091
  return totalTokens(delta) > 0;
1614
1092
  }
1615
1093
  /**
1616
- * Hook the chip uses to play costPop + deltaRise on each new request.
1094
+ * Hook the pill uses to play costPop + deltaFall on each new request.
1617
1095
  * @param scopeKey - changes reset the diff baseline.
1618
1096
  * @param costRef - the live cost figure span (WAAPI target).
1619
1097
  */
@@ -1679,7 +1157,7 @@ window.__ModuleLoader__.load({
1679
1157
  const wireDeltaCost = summary.totalCost - prev.totalCost;
1680
1158
  if (wireDeltaCost > MIN_WIRE_DELTA_COST) {
1681
1159
  const view = currencyViewOf(summary);
1682
- const text = `+${view.symbol}${(wireDeltaCost / view.rate).toFixed(2)}`;
1160
+ const text = `+${(wireDeltaCost / view.rate).toFixed(2)}${view.symbol}`;
1683
1161
  const id = ++flyIdRef.current;
1684
1162
  flyCountRef.current += 1;
1685
1163
  setFlies((current) => [...current, {
@@ -1702,166 +1180,889 @@ window.__ModuleLoader__.load({
1702
1180
  };
1703
1181
  }
1704
1182
  //#endregion
1705
- //#region src/client/SessionStatsChip.tsx
1183
+ //#region src/client/CostPill.tsx
1184
+ /**
1185
+ * Composer-dock usage pill (browser half): a cost trigger registered into
1186
+ * the `conversation.composer.dock` slot (`order: 10`, after the official
1187
+ * stats pills at `order: 0`), rendered as one capsule in the official
1188
+ * StatsPills skin. The figure is the WITH-SUBAGENTS fold — the one number
1189
+ * no official surface carries — suffixed with a quiet "with subagents"
1190
+ * badge only when the scope actually spans a subtree; a solo session's
1191
+ * cost renders bare, same scope as the official pills beside it.
1192
+ *
1193
+ * Clicking opens a detail panel (harness menu chrome, upward of the dock)
1194
+ * that explains the total: the folded token figure and cache-hit rate next
1195
+ * to it (official pills carry only the single-session token count, so the
1196
+ * subtree share has no home but here), the session / subagents split, and
1197
+ * a per-model breakdown with the unpriced-models footnote. Panel data is
1198
+ * LAZY: the trigger polls `fields=chip` (totals only, subtree scope); the
1199
+ * two richer reads (`fields=session` for byModel, a solo-session `chip`
1200
+ * read for the split) fire when the panel first opens and again whenever
1201
+ * request churn debounces through.
1202
+ *
1203
+ * The pill refreshes at REQUEST granularity (the header chip's former
1204
+ * cadence, inherited whole): `sessionStats` projection churn plus mirror
1205
+ * `updatedAt` is debounced 250 ms into one fetch, a failed FIRST fetch
1206
+ * retries itself on a 3 s cadence, and later failures keep the prior
1207
+ * figures. When cost rises on a new request the figure plays `costPop`
1208
+ * and a +Δ label FALLS below the pill (the dock sits under the composer;
1209
+ * the header chip's upward rise would climb into the message scrollport).
1210
+ * Reduced-motion users get silent figure updates.
1211
+ *
1212
+ * Visibility contract: a session with no recorded requests renders
1213
+ * nothing; a transient fetch miss keeps the previous render.
1214
+ *
1215
+ * @module token-usage/client/CostPill
1216
+ */
1217
+ /** Refresh debounce: bursts of session-mirror updates (one request's events)
1218
+ * collapse into a single fetch — the header chip's request-scale cadence. */
1219
+ const REFRESH_DEBOUNCE_MS$1 = 250;
1220
+ /** Self-heal cadence after a failed first fetch: refresh failures after the
1221
+ * first land keep the prior figures (silent mode) and self-heal on the next
1222
+ * request churn, so they never reach the error state. */
1223
+ const FETCH_FAILURE_RETRY_MS = 3e3;
1224
+ /** Detail panel width (px); the viewport-clamped centering uses it. */
1225
+ const PANEL_WIDTH = 300;
1226
+ const PANEL_VIEWPORT_MARGIN$1 = 16;
1227
+ /**
1228
+ * Subtract a solo-session summary from its subtree fold.
1229
+ * @param tree - the subtree-scoped folded summary.
1230
+ * @param self - the solo-session summary (same session, no children).
1231
+ * @returns the two shares; costs and tokens are additive so subtraction is
1232
+ * exact, and the hit rate is NEVER split (a ratio is not subtractable — the
1233
+ * panel recomputes the folded rate from the tree totals instead).
1234
+ */
1235
+ function splitUsage(tree, self) {
1236
+ const sub = (whole, part) => whole - part > 0 ? whole - part : 0;
1237
+ return {
1238
+ selfCost: self.totalCost,
1239
+ subsCost: sub(tree.totalCost, self.totalCost),
1240
+ selfTokens: totalTokens(self.total),
1241
+ subsTokens: sub(totalTokens(tree.total), totalTokens(self.total))
1242
+ };
1243
+ }
1244
+ /**
1245
+ * Render the composer-dock usage pill for the active session. Renders
1246
+ * nothing when the session has no recorded usage or while the first fetch
1247
+ * is in flight — the "data has no value, the block does not render" rule.
1248
+ * @param props - framework session id, the session-list mirror, and the locale seat.
1249
+ * @returns the pill (plus its open detail panel), or null when empty/unavailable.
1250
+ */
1251
+ function CostPill({ sessionId, useSessions, useProjection, t }) {
1252
+ const rootRef = (0, react.useRef)(null);
1253
+ const costRef = (0, react.useRef)(null);
1254
+ useColorSchemeMirror(rootRef);
1255
+ const [open, setOpen] = (0, react.useState)(false);
1256
+ const byId = useSessions((state) => state.byId);
1257
+ const childIndex = (0, react.useMemo)(() => buildChildIndex(byId), [byId]);
1258
+ const scopeIds = (0, react.useMemo)(() => sessionId === "" ? [] : subtreeIds(byId, sessionId, childIndex), [
1259
+ byId,
1260
+ sessionId,
1261
+ childIndex
1262
+ ]);
1263
+ const hasSubs = scopeIds.length > 1;
1264
+ const freshnessKey = buildStatsFreshnessKey(scopeIds, {
1265
+ activeSessionId: sessionId,
1266
+ rows: byId,
1267
+ liveSessionStats: useProjection("sessionStats")
1268
+ });
1269
+ const debouncedKey = useDebouncedValue(`${scopeIds.join("\n")}\n\t${freshnessKey}`, REFRESH_DEBOUNCE_MS$1);
1270
+ const { flies, onSummary } = useCostInflate(scopeIds.join("\n"), costRef);
1271
+ const [treeRes, retryTree] = useAsyncResource((signal) => {
1272
+ const [idsPart] = debouncedKey.split("\n ");
1273
+ return fetchSummary$1((idsPart ?? "").split("\n").filter((id) => id !== ""), "chip", signal);
1274
+ }, [debouncedKey], {
1275
+ silentAfterFirst: true,
1276
+ retryToken: 0
1277
+ });
1278
+ const summary = treeRes.status === "ready" ? treeRes.value : null;
1279
+ (0, react.useEffect)(() => {
1280
+ if (summary !== null) onSummary(summary);
1281
+ }, [summary, onSummary]);
1282
+ (0, react.useEffect)(() => {
1283
+ if (treeRes.status !== "error") return;
1284
+ const timer = window.setTimeout(retryTree, FETCH_FAILURE_RETRY_MS);
1285
+ return () => {
1286
+ window.clearTimeout(timer);
1287
+ };
1288
+ }, [treeRes, retryTree]);
1289
+ const [detailRes] = useAsyncResource((signal) => {
1290
+ if (!open) return Promise.resolve(null);
1291
+ const [idsPart] = debouncedKey.split("\n ");
1292
+ return fetchSummary$1((idsPart ?? "").split("\n").filter((id) => id !== ""), "session", signal);
1293
+ }, [open, debouncedKey], {
1294
+ silentAfterFirst: true,
1295
+ retryToken: 0
1296
+ });
1297
+ const [selfRes] = useAsyncResource((signal) => {
1298
+ if (!open || sessionId === "") return Promise.resolve(null);
1299
+ return fetchSummary$1([sessionId], "chip", signal);
1300
+ }, [
1301
+ open,
1302
+ sessionId,
1303
+ debouncedKey
1304
+ ], {
1305
+ silentAfterFirst: true,
1306
+ retryToken: 0
1307
+ });
1308
+ (0, react.useEffect)(() => {
1309
+ setOpen(false);
1310
+ }, [sessionId]);
1311
+ (0, react.useEffect)(() => {
1312
+ if (!open) return;
1313
+ const onPointerDown = (event) => {
1314
+ if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return;
1315
+ setOpen(false);
1316
+ };
1317
+ const onKeyDown = (event) => {
1318
+ if (event.key === "Escape") setOpen(false);
1319
+ };
1320
+ document.addEventListener("pointerdown", onPointerDown);
1321
+ document.addEventListener("keydown", onKeyDown);
1322
+ return () => {
1323
+ document.removeEventListener("pointerdown", onPointerDown);
1324
+ document.removeEventListener("keydown", onKeyDown);
1325
+ };
1326
+ }, [open]);
1327
+ const [panelLeft, setPanelLeft] = (0, react.useState)(void 0);
1328
+ const measurePanelLeft = (0, react.useCallback)(() => {
1329
+ const wrapper = rootRef.current;
1330
+ if (wrapper === null) return;
1331
+ const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect();
1332
+ const panelWidth = Math.min(PANEL_WIDTH, window.innerWidth - 32);
1333
+ const desired = (wrapperWidth - panelWidth) / 2;
1334
+ const minLeft = PANEL_VIEWPORT_MARGIN$1 - wrapperLeft;
1335
+ const maxLeft = window.innerWidth - PANEL_VIEWPORT_MARGIN$1 - panelWidth - wrapperLeft;
1336
+ setPanelLeft(Math.min(Math.max(desired, minLeft), Math.max(minLeft, maxLeft)));
1337
+ }, []);
1338
+ (0, react.useEffect)(() => {
1339
+ if (!open) return;
1340
+ measurePanelLeft();
1341
+ window.addEventListener("resize", measurePanelLeft);
1342
+ return () => {
1343
+ window.removeEventListener("resize", measurePanelLeft);
1344
+ };
1345
+ }, [open, measurePanelLeft]);
1346
+ if (summary === null || summary.total.requests === 0) return null;
1347
+ const view = currencyViewOf(summary);
1348
+ const costText = formatCost(summary.totalCost, view);
1349
+ const tokensValue = formatTokens(totalTokens(summary.total));
1350
+ const hit = hitRateDisplay(summary.total);
1351
+ const ariaLabel = hasSubs ? t("pill.costWithSubs", { value: costText }) : t("pill.cost", { value: costText });
1352
+ const selfSummary = selfRes.status === "ready" ? selfRes.value : null;
1353
+ const detail = detailRes.status === "ready" ? detailRes.value : null;
1354
+ const split = selfSummary !== null ? splitUsage(summary, selfSummary) : null;
1355
+ const subCount = scopeIds.length - 1;
1356
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1357
+ ref: rootRef,
1358
+ className: CostPill_module_css_default.root,
1359
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1360
+ type: "button",
1361
+ className: CostPill_module_css_default.pill,
1362
+ "aria-haspopup": "dialog",
1363
+ "aria-expanded": open,
1364
+ "aria-label": `${ariaLabel},${t("panel.openHint")}`,
1365
+ onClick: () => {
1366
+ setOpen(!open);
1367
+ },
1368
+ children: [
1369
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
1370
+ className: CostPill_module_css_default.glyph,
1371
+ viewBox: "0 0 14 14",
1372
+ width: "14",
1373
+ height: "14",
1374
+ "aria-hidden": true,
1375
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
1376
+ cx: "7",
1377
+ cy: "7",
1378
+ r: "5.5",
1379
+ fill: "none",
1380
+ stroke: "currentColor",
1381
+ strokeWidth: "1.2"
1382
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
1383
+ 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",
1384
+ fill: "none",
1385
+ stroke: "currentColor",
1386
+ strokeWidth: "1.2"
1387
+ })]
1388
+ }),
1389
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1390
+ ref: costRef,
1391
+ className: CostPill_module_css_default.cost,
1392
+ children: costText
1393
+ }),
1394
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1395
+ className: CostPill_module_css_default.deltaLayer,
1396
+ "aria-hidden": "true",
1397
+ children: flies.map((fly) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CostDeltaFlyLabel, {
1398
+ text: fly.text,
1399
+ vars: fly.vars
1400
+ }, fly.id))
1401
+ })
1402
+ ]
1403
+ }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1404
+ className: CostPill_module_css_default.panel,
1405
+ role: "dialog",
1406
+ "aria-label": t("panel.title"),
1407
+ style: { left: panelLeft },
1408
+ children: [
1409
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1410
+ className: CostPill_module_css_default.panelHead,
1411
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1412
+ className: CostPill_module_css_default.panelTitle,
1413
+ children: [t("panel.title"), hasSubs && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1414
+ className: CostPill_module_css_default.scopeTag,
1415
+ children: t("pill.scopeTag")
1416
+ })]
1417
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1418
+ className: CostPill_module_css_default.panelTotal,
1419
+ children: costText
1420
+ })]
1421
+ }),
1422
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1423
+ className: CostPill_module_css_default.usageLine,
1424
+ children: [
1425
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("panel.tokens", { value: tokensValue }) }),
1426
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1427
+ className: CostPill_module_css_default.dot,
1428
+ children: "·"
1429
+ }),
1430
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("panel.hitRate", { value: hit.text }) })
1431
+ ]
1432
+ }),
1433
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1434
+ className: CostPill_module_css_default.rows,
1435
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1436
+ className: CostPill_module_css_default.row,
1437
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1438
+ className: CostPill_module_css_default.rowLabel,
1439
+ children: t("panel.self")
1440
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1441
+ className: CostPill_module_css_default.rowValue,
1442
+ children: split === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1443
+ className: CostPill_module_css_default.pending,
1444
+ children: "…"
1445
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [formatCost(split.selfCost, view), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1446
+ className: CostPill_module_css_default.tok,
1447
+ children: t("panel.tokens", { value: formatTokens(split.selfTokens) })
1448
+ })] })
1449
+ })]
1450
+ }), hasSubs && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1451
+ className: `${CostPill_module_css_default.row} ${CostPill_module_css_default.rowSub}`,
1452
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1453
+ className: CostPill_module_css_default.rowLabel,
1454
+ children: t("panel.subs", { count: subCount })
1455
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1456
+ className: CostPill_module_css_default.rowValue,
1457
+ children: split === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1458
+ className: CostPill_module_css_default.pending,
1459
+ children: "…"
1460
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [formatCost(split.subsCost, view), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1461
+ className: CostPill_module_css_default.tok,
1462
+ children: t("panel.tokens", { value: formatTokens(split.subsTokens) })
1463
+ })] })
1464
+ })]
1465
+ })]
1466
+ }),
1467
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1468
+ className: CostPill_module_css_default.groupLabel,
1469
+ children: t("panel.byModel")
1470
+ }),
1471
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1472
+ className: CostPill_module_css_default.rows,
1473
+ children: detail === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1474
+ className: CostPill_module_css_default.row,
1475
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1476
+ className: CostPill_module_css_default.pending,
1477
+ children: "…"
1478
+ })
1479
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [detail.byModel.map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelRow, {
1480
+ row,
1481
+ view
1482
+ }, row.model)), detail.unpricedModels.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1483
+ className: `${CostPill_module_css_default.row} ${CostPill_module_css_default.unpriced}`,
1484
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1485
+ className: CostPill_module_css_default.rowLabel,
1486
+ children: t("panel.unpriced", { count: detail.unpricedModels.length })
1487
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1488
+ className: CostPill_module_css_default.rowValue,
1489
+ children: t("panel.unpricedNote")
1490
+ })]
1491
+ })] })
1492
+ })
1493
+ ]
1494
+ })]
1495
+ });
1496
+ }
1497
+ /** One per-model breakdown row: model id + request count, billed cost, tokens. */
1498
+ function ModelRow({ row, view }) {
1499
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1500
+ className: CostPill_module_css_default.row,
1501
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1502
+ className: CostPill_module_css_default.rowLabel,
1503
+ children: [row.model, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1504
+ className: CostPill_module_css_default.requests,
1505
+ children: ["× ", row.totals.requests]
1506
+ })]
1507
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1508
+ className: CostPill_module_css_default.rowValue,
1509
+ children: [formatCost(row.cost, view), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1510
+ className: CostPill_module_css_default.tok,
1511
+ children: formatTokens(totalTokens(row.totals))
1512
+ })]
1513
+ })]
1514
+ });
1515
+ }
1516
+ /** Defensive shape check: an older host build or a misrouted response
1517
+ * would otherwise paint the pill with garbage. */
1518
+ function looksLikeUsageSummary(value) {
1519
+ return typeof value === "object" && value !== null && typeof value.total === "object" && value.total !== null;
1520
+ }
1521
+ /**
1522
+ * Fetch one stats summary. Throws on transport failure (network, abort,
1523
+ * non-2xx response, or a payload that doesn't look like a stats summary) so
1524
+ * the hook can keep the previous render in place.
1525
+ * @param sessionIds - the scope's session ids; an empty list skips the
1526
+ * fetch (returning null rather than throwing, so the hook's first-load
1527
+ * gate stays at "loading").
1528
+ * @param fields - `chip` for totals-only reads, `session` when byModel is
1529
+ * needed (the detail panel's per-model block).
1530
+ * @param signal - the cancellation signal from the hook.
1531
+ */
1532
+ async function fetchSummary$1(sessionIds, fields, signal) {
1533
+ if (sessionIds.length === 0) return null;
1534
+ const response = await fetch(STATS_PATH + encodeStatsQuery({
1535
+ sessionIds,
1536
+ fields
1537
+ }), {
1538
+ headers: { accept: "application/json" },
1539
+ signal
1540
+ });
1541
+ if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
1542
+ const value = await response.json();
1543
+ if (!looksLikeUsageSummary(value)) throw new Error("unexpected stats response");
1544
+ return value;
1545
+ }
1546
+ //#endregion
1547
+ //#region src/client/quota-format.ts
1548
+ /** Severity thresholds on the REMAINING share (percent) — the traffic-light
1549
+ * standard: above 60 reads green (plenty left), 20–60 yellow (watch it),
1550
+ * below 20 red (effectively gone). */
1551
+ const REMAIN_YELLOW = 60;
1552
+ const REMAIN_RED = 20;
1553
+ /** Whole-number percent, one decimal kept when it exists (`62%`, `87.5%`). */
1554
+ function formatQuotaPercent(value) {
1555
+ const rounded = Math.round(value * 10) / 10;
1556
+ return `${Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1)}%`;
1557
+ }
1558
+ /** A money figure with its symbol: `$6.80` / `¥110.00`. */
1559
+ function formatQuotaMoney(value, unit) {
1560
+ return `${unit === "usd" ? "$" : "¥"}${value.toFixed(2)}`;
1561
+ }
1562
+ /**
1563
+ * The used share of one window, 0–100, whichever direction the provider
1564
+ * reported: the explicit `usedPercent`, else `remainingPercent` inverted,
1565
+ * else the balance fraction (`1 - remaining/max`). Undefined when the
1566
+ * window carries no computable ratio (a balance without a total).
1567
+ */
1568
+ function quotaUsedPercent(window) {
1569
+ if (window.usedPercent !== void 0) return clampPercent(window.usedPercent);
1570
+ if (window.remainingPercent !== void 0) return clampPercent(100 - window.remainingPercent);
1571
+ if (window.remainingValue !== void 0 && window.maxValue !== void 0 && window.maxValue > 0) return clampPercent((1 - window.remainingValue / window.maxValue) * 100);
1572
+ }
1573
+ /**
1574
+ * The remaining share of one window, 0–100 — the severity input (severity
1575
+ * reads what is LEFT, not what is spent). Mirrors {@link quotaUsedPercent}'s
1576
+ * fallback chain in the opposite direction.
1577
+ */
1578
+ function quotaRemainingPercent(window) {
1579
+ if (window.remainingPercent !== void 0) return clampPercent(window.remainingPercent);
1580
+ if (window.usedPercent !== void 0) return clampPercent(100 - window.usedPercent);
1581
+ if (window.remainingValue !== void 0 && window.maxValue !== void 0 && window.maxValue > 0) return clampPercent(window.remainingValue / window.maxValue * 100);
1582
+ }
1583
+ /** Map a remaining share (percent) to the traffic-light band: green above
1584
+ * 60, yellow 20–60, red below 20. A window with no computable ratio reads
1585
+ * by its absolute amount: an overdrawn/empty balance (≤ 0) is red,
1586
+ * anything else uncolored — a plain balance never paints alarm just for
1587
+ * lacking a total. */
1588
+ function quotaSeverityOf(window) {
1589
+ const remaining = quotaRemainingPercent(window);
1590
+ if (remaining === void 0) return window.remainingValue !== void 0 && window.remainingValue <= 0 ? "exhausted" : "ok";
1591
+ if (remaining < REMAIN_RED) return "exhausted";
1592
+ if (remaining <= REMAIN_YELLOW) return "warn";
1593
+ return "ok";
1594
+ }
1595
+ /**
1596
+ * The FINEST-granularity window of a payload — 5-hour over weekly over
1597
+ * monthly over balance. The trigger icon reads this one, not the worst
1598
+ * across windows: the finest unit is the constraint the session is
1599
+ * currently acting inside (a calm 5-hour window carries the icon even when
1600
+ * the weekly pool runs low). Undefined when there is no window at all.
1601
+ */
1602
+ function finestQuotaWindow(windows) {
1603
+ const rank = {
1604
+ five_hour: 0,
1605
+ weekly: 1,
1606
+ monthly: 2,
1607
+ balance: 3
1608
+ };
1609
+ let pick;
1610
+ for (const window of windows) if (pick === void 0 || rank[window.tier] < rank[pick.tier]) pick = window;
1611
+ return pick;
1612
+ }
1613
+ /**
1614
+ * Fill share of the trigger ring, 0–1. Ratio windows map the remaining
1615
+ * percent; a funded balance without a total paints a full ring (the color
1616
+ * stays neutral — amounts tint only at ≤ 0); empty / overdrawn / missing
1617
+ * windows leave the track only.
1618
+ */
1619
+ function quotaIconFillShare(window) {
1620
+ if (window === void 0) return 0;
1621
+ const remaining = quotaRemainingPercent(window);
1622
+ if (remaining !== void 0) return remaining / 100;
1623
+ if (window.remainingValue !== void 0 && window.remainingValue > 0) return 1;
1624
+ return 0;
1625
+ }
1626
+ /**
1627
+ * The trigger tooltip's figure for one window: the remaining share as a
1628
+ * percent when a ratio exists (any direction, or the balance fraction),
1629
+ * else the remaining amount (a ratio-less balance, the DeepSeek shape);
1630
+ * undefined when the window carries neither (nothing to show beyond the
1631
+ * plain label).
1632
+ */
1633
+ function quotaTriggerFigure(window) {
1634
+ if (window === void 0) return void 0;
1635
+ const remaining = quotaRemainingPercent(window);
1636
+ if (remaining !== void 0) return formatQuotaPercent(remaining);
1637
+ if (window.remainingValue !== void 0) return formatQuotaMoney(window.remainingValue, window.unit ?? "cny");
1638
+ }
1639
+ /**
1640
+ * The reset countdown in the shell's compact shape: `2h 14m` under a day,
1641
+ * `48m` under an hour, `1d 3h` above; a non-positive remainder reads `0m`
1642
+ * (the next poll refreshes the stale window).
1643
+ * @param resetAt - epoch ms of the window's reset.
1644
+ * @param now - epoch ms the countdown is taken at.
1645
+ */
1646
+ function formatResetCountdown(resetAt, now) {
1647
+ const minutes = Math.max(0, Math.floor((resetAt - now) / 6e4));
1648
+ if (minutes < 60) return `${String(minutes)}m`;
1649
+ const hours = Math.floor(minutes / 60);
1650
+ if (hours < 24) return `${String(hours)}h ${String(minutes % 60)}m`;
1651
+ return `${String(Math.floor(hours / 24))}d ${String(hours % 24)}h`;
1652
+ }
1653
+ /** A wall-clock `HH:MM` stamp of an epoch-ms time (the "updated at" figure). */
1654
+ function formatQuotaClock(ms) {
1655
+ const date = new Date(ms);
1656
+ const pad = (value) => String(value).padStart(2, "0");
1657
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
1658
+ }
1659
+ /** Clamp into 0–100. */
1660
+ function clampPercent(value) {
1661
+ return Math.min(100, Math.max(0, value));
1662
+ }
1663
+ //#endregion
1664
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\QuotaButton.module.css.mjs
1665
+ const css$11 = ".jYASuG_root{flex:none;display:inline-flex;position:relative}.jYASuG_trigger{width:28px;height:28px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:999px;flex:none;place-items:center;padding:0;display:grid}.jYASuG_trigger svg{display:block}.jYASuG_trigger:hover,.jYASuG_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.jYASuG_trigger.jYASuG_icon-ok:hover,.jYASuG_trigger.jYASuG_icon-ok[aria-expanded=true]{color:var(--dsw-alias-state-success-primary)}.jYASuG_trigger.jYASuG_icon-warn:hover,.jYASuG_trigger.jYASuG_icon-warn[aria-expanded=true]{color:var(--dsw-alias-state-warn-primary)}.jYASuG_trigger.jYASuG_icon-exhausted:hover,.jYASuG_trigger.jYASuG_icon-exhausted[aria-expanded=true]{color:var(--dsw-alias-state-error-primary)}.jYASuG_icon-ok{color:var(--dsw-alias-state-success-primary)}.jYASuG_icon-warn{color:var(--dsw-alias-state-warn-primary)}.jYASuG_icon-exhausted{color:var(--dsw-alias-state-error-primary)}.jYASuG_panel{z-index:100;box-sizing:border-box;border:1px solid var(--dsw-alias-border-inverted);background:var(--dsw-specific-menu);width:320px;max-width:calc(100vw - 32px);backdrop-filter:var(--dsw-menu-backdrop-filter);box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-secondary);text-align:left;cursor:default;border-radius:12px;padding:12px;font-size:12px;line-height:20px;position:absolute;bottom:calc(100% + 8px)}.jYASuG_header{justify-content:space-between;align-items:baseline;gap:8px;margin-bottom:10px;display:flex}.jYASuG_title{color:var(--dsw-alias-label-primary);white-space:nowrap;text-overflow:ellipsis;font-size:13px;font-weight:500;overflow:hidden}.jYASuG_plan{color:var(--dsw-alias-label-tertiary);font-weight:400}.jYASuG_updated{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;flex:none;font-size:11px}.jYASuG_grid{grid-template-columns:repeat(var(--cols,3), 1fr);gap:14px;display:grid}.jYASuG_col{min-width:0}.jYASuG_label{color:var(--dsw-alias-label-tertiary);white-space:nowrap;text-overflow:ellipsis;margin-bottom:2px;font-size:11px;line-height:16px;overflow:hidden}.jYASuG_value{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;white-space:nowrap;margin-bottom:6px;font-size:13px;font-weight:600;line-height:18px}.jYASuG_meta{color:var(--dsw-alias-label-tertiary);font-size:11px;font-weight:400}.jYASuG_bar{background:var(--dsw-alias-interactive-bg-hover);border-radius:999px;height:4px;overflow:hidden}.jYASuG_fill{border-radius:999px;height:100%;transition:width .3s}.jYASuG_ok{background:var(--dsw-alias-state-success-primary)}.jYASuG_warn{background:var(--dsw-alias-state-warn-primary)}.jYASuG_exhausted{background:var(--dsw-alias-state-error-primary)}.jYASuG_aux{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;white-space:nowrap;margin-top:4px;font-size:11px;line-height:14px}.jYASuG_dot{vertical-align:middle;border-radius:50%;width:5px;height:5px;margin-right:3px;display:inline-block}.jYASuG_error{flex-direction:column;gap:8px;display:flex}.jYASuG_errorText{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;font-size:12px;line-height:18px}.jYASuG_retry{color:var(--dsw-alias-label-primary);cursor:pointer;text-underline-offset:2px;background:0 0;border:none;align-self:flex-start;padding:0;font-size:12px;text-decoration:underline}.jYASuG_retry:hover{color:var(--dsw-alias-brand-primary)}";
1666
+ const tagId$11 = "@laoyuehanni/dsh-token-usage/QuotaButton.module.css";
1667
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$11) + "]") === null) {
1668
+ const tag = document.createElement("style");
1669
+ tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
1670
+ tag.dataset.pluginCss = tagId$11;
1671
+ tag.textContent = css$11;
1672
+ document.head.appendChild(tag);
1673
+ }
1674
+ var QuotaButton_module_css_default = {
1675
+ "aux": "jYASuG_aux",
1676
+ "bar": "jYASuG_bar",
1677
+ "col": "jYASuG_col",
1678
+ "dot": "jYASuG_dot",
1679
+ "error": "jYASuG_error",
1680
+ "errorText": "jYASuG_errorText",
1681
+ "exhausted": "jYASuG_exhausted",
1682
+ "fill": "jYASuG_fill",
1683
+ "grid": "jYASuG_grid",
1684
+ "header": "jYASuG_header",
1685
+ "icon-exhausted": "jYASuG_icon-exhausted",
1686
+ "icon-ok": "jYASuG_icon-ok",
1687
+ "icon-warn": "jYASuG_icon-warn",
1688
+ "label": "jYASuG_label",
1689
+ "meta": "jYASuG_meta",
1690
+ "ok": "jYASuG_ok",
1691
+ "panel": "jYASuG_panel",
1692
+ "plan": "jYASuG_plan",
1693
+ "retry": "jYASuG_retry",
1694
+ "root": "jYASuG_root",
1695
+ "title": "jYASuG_title",
1696
+ "trigger": "jYASuG_trigger",
1697
+ "updated": "jYASuG_updated",
1698
+ "value": "jYASuG_value",
1699
+ "warn": "jYASuG_warn"
1700
+ };
1701
+ //#endregion
1702
+ //#region src/client/QuotaButton.tsx
1706
1703
  /**
1707
- * Session-header stats chip (browser half): a one-line compact strip rendered
1708
- * into the `conversation.session.header.utilities` slot — three sub-chips
1709
- * (total tokens / cache hit rate / session cost) beside the Session log
1710
- * button. Data comes from `/token-usage/stats?fields=chip` scoped to the
1711
- * active session and its subagent subtree (the Usage tab's "with
1712
- * subagents" range), so a parent that spawned children shows the same
1713
- * folded numbers the header is meant to summarise. Numbers refresh at
1714
- * REQUEST granularity (same cadence as the Usage tab): `sessionStats`
1715
- * projection churn (plus mirror `updatedAt` when present) is debounced
1716
- * into one fetch, so idle sessions do not poll and a finished request
1717
- * updates the header within ~250 ms. When cost
1718
- * rises on a new request, the cost cell plays `costPop` (scale bounce) and
1719
- * `deltaRise` (+Δ fly); reduced-motion users get silent figure updates
1720
- * instead. A failed FIRST fetch retries itself on a 3 s cadence — the old
1721
- * poll's safety net — so an idle-but-used session still gets its chip.
1704
+ * Input-bar quota button (browser half): a 28×28 round trigger registered
1705
+ * into the `conversation.input.right` slot (it renders left of the model
1706
+ * chip — the host's fixed tool-row order). The glyph is a remaining-share
1707
+ * ring (ContextMeter family) colored by the finest window. Clicking opens a
1708
+ * width-tiered popup (amount-only 200px / one progress bar 232px / two
1709
+ * bars 320px) centered on the button with the current provider's quota
1710
+ * windows: progress columns (5 小时 / 每周) for coding-plan providers, an
1711
+ * amount row for balance providers.
1712
+ *
1713
+ * The provider follows the model CHIP's live selection (the shell's
1714
+ * model-selection service reports the host's next selection before any
1715
+ * request is sent); without that service the host falls back to the last
1716
+ * request's provider, else the default selection.
1717
+ *
1718
+ * The button SELF-GATES: it renders nothing while the host cannot
1719
+ * determine a provider (`no-provider`), the provider has no quota adapter
1720
+ * (`unsupported`), or the feature is off (`disabled`) — switching
1721
+ * providers makes it appear again. A supported provider whose query fails
1722
+ * KEEPS the button and shows the error with a retry inside the panel.
1722
1723
  *
1723
- * Visibility contract: a session with no recorded requests renders nothing
1724
- * (an empty header strip is worse than no strip; the chip never blanks to
1725
- * "—"). Hit-rate colour is the four-bucket mapping in `format.hitRateDisplay`:
1726
- * ≥95% healthy (green), 80–95% lime, 60–80% amber, below 60% critical (red).
1727
- * Amber/lime fill the warm→cool gap so the four stops read as one progression.
1724
+ * The hover tooltip reads provider name + the finest window's exact
1725
+ * remaining figure (percent, or the amount when no ratio exists).
1726
+ *
1727
+ * The interaction copies ContextMeter verbatim (click toggles, document
1728
+ * pointerdown outside closes, Escape closes); mutual exclusion with the
1729
+ * ContextMeter panel falls out of both components' outside-close
1730
+ * handlers — opening one closes the other on its next pointerdown.
1728
1731
  *
1729
- * @module token-usage/client/SessionStatsChip
1732
+ * @module token-usage/client/QuotaButton
1730
1733
  */
1731
- /** Refresh debounce: bursts of session-mirror updates (one request's events)
1732
- * collapse into a single fetch, matching the Usage tab's request-scale
1733
- * cadence instead of a steady poll. */
1734
- const REFRESH_DEBOUNCE_MS$1 = 250;
1735
- /** Self-heal cadence after a failed first fetch. With the poll gone, this
1736
- * retry is the only thing that recovers an idle session's chip: refresh
1737
- * failures after the first land keep the prior figures (silent mode) and
1738
- * self-heal on the next request churn, so they never reach the error state. */
1739
- const FETCH_FAILURE_RETRY_MS = 3e3;
1734
+ /** The poll cadence fallback (seconds) while no payload has named one. */
1735
+ const DEFAULT_POLL_SEC = 60;
1736
+ /** Panel width tiers (px), by how much the windows paint: a lone amount
1737
+ * reads at a glance, one progress bar needs breathing room, two bars (the
1738
+ * 5-hour + weekly coding plans, or a long error body) the full plate. Kept
1739
+ * in sync with the CSS max-width clamp. */
1740
+ const PANEL_WIDTH_BALANCE = 200;
1741
+ const PANEL_WIDTH_SINGLE = 232;
1742
+ const PANEL_WIDTH_FULL = 320;
1743
+ const PANEL_VIEWPORT_MARGIN = 16;
1744
+ /** Tier → label key; the locale dictionaries carry both languages. */
1745
+ const TIER_LABEL_KEYS = {
1746
+ five_hour: "quota.tier.fiveHour",
1747
+ weekly: "quota.tier.weekly",
1748
+ monthly: "quota.tier.monthly",
1749
+ balance: "quota.tier.balance"
1750
+ };
1740
1751
  /**
1741
- * Render the session-header stats chip for the active session. Renders
1742
- * nothing when the session has no recorded usage, when the fetch fails, or
1743
- * while the first fetch is in flight — the spec's "data has no value, the
1744
- * block does not render" rule.
1745
- * @param props - framework session id, the session-list mirror, and the locale seat.
1746
- * @returns the chip strip, or null when the data is empty/unavailable.
1752
+ * Render the input-bar quota button for the active session's provider.
1753
+ * @param props - the framework session id, the locale seat, and the
1754
+ * optional model-directory holder (the chip's live selection).
1755
+ * @returns the trigger + panel, or null while hidden (see the module note).
1747
1756
  */
1748
- function SessionStatsChip({ sessionId, useSessions, useProjection, t }) {
1757
+ function QuotaButton({ sessionId, t, modelDirectory }) {
1749
1758
  const rootRef = (0, react.useRef)(null);
1750
- const costRef = (0, react.useRef)(null);
1751
1759
  useColorSchemeMirror(rootRef);
1752
- const byId = useSessions((state) => state.byId);
1753
- const childIndex = (0, react.useMemo)(() => buildChildIndex(byId), [byId]);
1754
- const scopeIds = (0, react.useMemo)(() => sessionId === "" ? [] : subtreeIds(byId, sessionId, childIndex), [
1755
- byId,
1756
- sessionId,
1757
- childIndex
1760
+ const [open, setOpen] = (0, react.useState)(false);
1761
+ const [panelLeft, setPanelLeft] = (0, react.useState)(void 0);
1762
+ const measurePanelLeft = (0, react.useCallback)((width) => {
1763
+ const wrapper = rootRef.current;
1764
+ if (wrapper === null) return;
1765
+ const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect();
1766
+ const panelWidth = Math.min(width, window.innerWidth - 32);
1767
+ const desired = (wrapperWidth - panelWidth) / 2;
1768
+ const minLeft = PANEL_VIEWPORT_MARGIN - wrapperLeft;
1769
+ const maxLeft = window.innerWidth - PANEL_VIEWPORT_MARGIN - panelWidth - wrapperLeft;
1770
+ setPanelLeft(Math.min(Math.max(desired, minLeft), Math.max(minLeft, maxLeft)));
1771
+ }, []);
1772
+ const modelService = modelDirectory?.service;
1773
+ const readChipProvider = () => {
1774
+ if (sessionId === "" || modelService === void 0) return void 0;
1775
+ try {
1776
+ return modelService.directoryFor(sessionId).store.getSnapshot().current?.provider ?? void 0;
1777
+ } catch {
1778
+ return;
1779
+ }
1780
+ };
1781
+ const [chipProvider, setChipProvider] = (0, react.useState)(readChipProvider);
1782
+ (0, react.useEffect)(() => {
1783
+ setChipProvider(readChipProvider());
1784
+ if (sessionId === "" || modelService === void 0) return;
1785
+ let directory;
1786
+ try {
1787
+ directory = modelService.directoryFor(sessionId);
1788
+ } catch {
1789
+ return;
1790
+ }
1791
+ return directory.store.subscribe(() => {
1792
+ setChipProvider(readChipProvider());
1793
+ });
1794
+ }, [sessionId, modelService]);
1795
+ const [resource, retry] = useAsyncResource((signal) => fetchQuotaPayload(sessionId, chipProvider, signal), [sessionId, chipProvider], {
1796
+ silentAfterFirst: true,
1797
+ retryToken: 0
1798
+ });
1799
+ const payload = resource.status === "ready" ? resource.value : null;
1800
+ const panelWidth = panelWidthOf(payload);
1801
+ const pollMs = (payload?.intervalSec ?? DEFAULT_POLL_SEC) * 1e3;
1802
+ (0, react.useEffect)(() => {
1803
+ const timer = setInterval(retry, pollMs);
1804
+ return () => {
1805
+ clearInterval(timer);
1806
+ };
1807
+ }, [pollMs, retry]);
1808
+ const visible = payload !== null && (payload.status === "ok" || payload.status === "error");
1809
+ (0, react.useEffect)(() => {
1810
+ if (!visible && open) setOpen(false);
1811
+ }, [visible, open]);
1812
+ (0, react.useEffect)(() => {
1813
+ if (!open) return;
1814
+ const onPointerDown = (event) => {
1815
+ if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return;
1816
+ setOpen(false);
1817
+ };
1818
+ const onKeyDown = (event) => {
1819
+ if (event.key === "Escape") setOpen(false);
1820
+ };
1821
+ document.addEventListener("pointerdown", onPointerDown);
1822
+ document.addEventListener("keydown", onKeyDown);
1823
+ return () => {
1824
+ document.removeEventListener("pointerdown", onPointerDown);
1825
+ document.removeEventListener("keydown", onKeyDown);
1826
+ };
1827
+ }, [open]);
1828
+ (0, react.useEffect)(() => {
1829
+ if (!open) return;
1830
+ const onViewportChange = () => {
1831
+ measurePanelLeft(panelWidth);
1832
+ };
1833
+ measurePanelLeft(panelWidth);
1834
+ window.addEventListener("resize", onViewportChange);
1835
+ window.addEventListener("scroll", onViewportChange, true);
1836
+ return () => {
1837
+ window.removeEventListener("resize", onViewportChange);
1838
+ window.removeEventListener("scroll", onViewportChange, true);
1839
+ };
1840
+ }, [
1841
+ open,
1842
+ panelWidth,
1843
+ measurePanelLeft
1758
1844
  ]);
1759
- const freshnessKey = buildStatsFreshnessKey(scopeIds, {
1760
- activeSessionId: sessionId,
1761
- rows: byId,
1762
- liveSessionStats: useProjection("sessionStats")
1845
+ if (!visible || payload === null) return null;
1846
+ const finest = finestQuotaWindow(payload.status === "ok" ? payload.windows : []);
1847
+ const severity = finest === void 0 ? "ok" : quotaSeverityOf(finest);
1848
+ const triggerClass = [QuotaButton_module_css_default.trigger];
1849
+ if (severity === "warn") triggerClass.push(QuotaButton_module_css_default["icon-warn"]);
1850
+ else if (severity === "exhausted") triggerClass.push(QuotaButton_module_css_default["icon-exhausted"]);
1851
+ else if (finest !== void 0 && quotaRemainingPercent(finest) !== void 0) triggerClass.push(QuotaButton_module_css_default["icon-ok"]);
1852
+ const triggerClassName = triggerClass.join(" ").trim();
1853
+ const figure = quotaTriggerFigure(finest);
1854
+ const triggerTip = figure === void 0 ? t("quota.trigger") : t("quota.triggerSummary", {
1855
+ name: payload.providerName ?? payload.provider,
1856
+ figure
1857
+ });
1858
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1859
+ ref: rootRef,
1860
+ className: QuotaButton_module_css_default.root,
1861
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
1862
+ label: triggerTip,
1863
+ side: "top",
1864
+ delayMs: 200,
1865
+ disabled: open,
1866
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1867
+ type: "button",
1868
+ className: triggerClassName,
1869
+ "aria-haspopup": "dialog",
1870
+ "aria-expanded": open,
1871
+ "aria-label": t("quota.trigger"),
1872
+ onClick: () => {
1873
+ if (!open) {
1874
+ retry();
1875
+ measurePanelLeft(panelWidth);
1876
+ }
1877
+ setOpen(!open);
1878
+ },
1879
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuotaGlyph, { share: quotaIconFillShare(finest) })
1880
+ })
1881
+ }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1882
+ className: QuotaButton_module_css_default.panel,
1883
+ role: "dialog",
1884
+ "aria-label": t("quota.panel"),
1885
+ style: {
1886
+ width: `${String(panelWidth)}px`,
1887
+ ...panelLeft === void 0 ? {} : { left: `${String(panelLeft)}px` }
1888
+ },
1889
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1890
+ className: QuotaButton_module_css_default.header,
1891
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1892
+ className: QuotaButton_module_css_default.title,
1893
+ children: [payload.providerName ?? payload.provider, payload.status === "ok" && payload.planTier !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1894
+ className: QuotaButton_module_css_default.plan,
1895
+ children: [" · ", payload.planTier]
1896
+ }) : null]
1897
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1898
+ className: QuotaButton_module_css_default.updated,
1899
+ children: t("quota.updatedAt", { time: formatQuotaClock(payload.fetchedAt) })
1900
+ })]
1901
+ }), payload.status === "error" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1902
+ className: QuotaButton_module_css_default.error,
1903
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1904
+ className: QuotaButton_module_css_default.errorText,
1905
+ children: errorText(payload.error, t)
1906
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1907
+ type: "button",
1908
+ className: QuotaButton_module_css_default.retry,
1909
+ onClick: retry,
1910
+ children: t("quota.retry")
1911
+ })]
1912
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1913
+ className: QuotaButton_module_css_default.grid,
1914
+ style: { "--cols": String(Math.min(payload.windows.length, 3)) },
1915
+ children: payload.windows.map((window, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuotaColumn, {
1916
+ window,
1917
+ t
1918
+ }, `${window.tier}:${String(index)}`))
1919
+ })]
1920
+ })]
1763
1921
  });
1764
- const debouncedKey = useDebouncedValue(`${scopeIds.join("\n")}\n\t${freshnessKey}`, REFRESH_DEBOUNCE_MS$1);
1765
- const { flies, flyOverflow, onSummary } = useCostInflate(scopeIds.join("\n"), costRef);
1766
- const [resource, retry] = useAsyncResource((signal) => {
1767
- const [idsPart] = debouncedKey.split("\n ");
1768
- return fetchSessionSummary$1((idsPart ?? "").split("\n").filter((id) => id !== ""), signal);
1769
- }, [debouncedKey], {
1770
- silentAfterFirst: true,
1771
- retryToken: 0
1922
+ }
1923
+ /** Ring geometry matches ContextMeter: 14px viewBox, r 5.5, 2px stroke.
1924
+ * Circumference feeds the remaining-share dasharray, starting at 12
1925
+ * o'clock. A 0 share omits the fill stroke — a round cap at 0 would still
1926
+ * paint a dot. */
1927
+ const RING_R = 5.5;
1928
+ const RING_C = 2 * Math.PI * RING_R;
1929
+ /** Round caps paint half a stroke width beyond each dash end; their
1930
+ * combined reach is what the dash compensation subtracts, so the painted
1931
+ * arc (dash + caps) equals the nominal share and the caps cannot seal the
1932
+ * 12-o'clock gap. */
1933
+ const RING_CAP_REACH = 2;
1934
+ /** The trigger glyph: a ContextMeter-family donut whose fill arc is the
1935
+ * remaining share of the finest window. Color comes from the button's
1936
+ * severity class (`currentColor`); this only draws the arc. */
1937
+ function QuotaGlyph({ share }) {
1938
+ const clamped = Math.min(1, Math.max(0, share));
1939
+ const nominal = clamped * RING_C;
1940
+ const dashLen = clamped >= 1 ? RING_C : nominal <= RING_CAP_REACH ? nominal : nominal - RING_CAP_REACH;
1941
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
1942
+ viewBox: "0 0 14 14",
1943
+ width: "14",
1944
+ height: "14",
1945
+ "aria-hidden": "true",
1946
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
1947
+ cx: "7",
1948
+ cy: "7",
1949
+ r: RING_R,
1950
+ fill: "none",
1951
+ stroke: "currentColor",
1952
+ strokeWidth: "2",
1953
+ opacity: "0.22"
1954
+ }), clamped > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
1955
+ cx: "7",
1956
+ cy: "7",
1957
+ r: RING_R,
1958
+ fill: "none",
1959
+ stroke: "currentColor",
1960
+ strokeWidth: "2",
1961
+ strokeLinecap: clamped < 1 ? "round" : "butt",
1962
+ strokeDasharray: `${dashLen.toFixed(3)} ${RING_C.toFixed(3)}`,
1963
+ transform: "rotate(-90 7 7)"
1964
+ }) : null]
1772
1965
  });
1773
- const summary = resource.status === "ready" ? resource.value : null;
1774
- (0, react.useEffect)(() => {
1775
- if (summary !== null) onSummary(summary);
1776
- }, [summary, onSummary]);
1777
- (0, react.useEffect)(() => {
1778
- if (resource.status !== "error") return;
1779
- const timer = window.setTimeout(retry, FETCH_FAILURE_RETRY_MS);
1780
- return () => {
1781
- window.clearTimeout(timer);
1782
- };
1783
- }, [resource, retry]);
1784
- if (summary === null || summary.total.requests === 0) return null;
1785
- const view = currencyViewOf(summary);
1786
- const { total } = summary;
1787
- const tokensText = formatTokens(totalTokens(total));
1788
- const hitText = hitRateDisplay(total).text;
1789
- const costText = formatCost(summary.totalCost, view);
1966
+ }
1967
+ /** One progress column: label / value / bar / aux. The value and the bar
1968
+ * both carry the REMAINING share (the traffic-light standard reads what is
1969
+ * left), colored by severity. */
1970
+ function QuotaColumn({ window, t }) {
1971
+ const remaining = quotaRemainingPercent(window);
1972
+ const severity = quotaSeverityOf(window);
1973
+ const label = t(TIER_LABEL_KEYS[window.tier]);
1974
+ let value;
1975
+ let meta;
1976
+ if (window.tier === "balance" && window.remainingValue !== void 0) {
1977
+ const unit = window.unit ?? "cny";
1978
+ value = formatQuotaMoney(window.remainingValue, unit);
1979
+ if (window.maxValue !== void 0) meta = `/ ${formatQuotaMoney(window.maxValue, unit)}`;
1980
+ } else value = remaining !== void 0 ? formatQuotaPercent(remaining) : "—";
1981
+ const aux = window.resetAt !== void 0 ? t("quota.resetIn", { time: formatResetCountdown(window.resetAt, Date.now()) }) : void 0;
1790
1982
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1791
- ref: rootRef,
1792
- className: `${SessionStatsChip_module_css_default["strip"]}${flyOverflow ? ` ${SessionStatsChip_module_css_default["stripFlyOverflow"]}` : ""}`,
1793
- role: "group",
1794
- "aria-label": t("view.usage"),
1983
+ className: QuotaButton_module_css_default.col,
1795
1984
  children: [
1796
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1797
- className: SessionStatsChip_module_css_default["cell"],
1798
- "aria-label": t("chip.tokens", { value: tokensText }),
1799
- children: tokensText
1985
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1986
+ className: QuotaButton_module_css_default.label,
1987
+ children: label
1800
1988
  }),
1801
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1802
- className: `${SessionStatsChip_module_css_default["cell"]} ${SessionStatsChip_module_css_default["cellHit"]}`,
1803
- "aria-label": t("chip.hitRate", { value: hitText }),
1804
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: total })
1989
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1990
+ className: QuotaButton_module_css_default.value,
1991
+ children: [value, meta !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1992
+ className: QuotaButton_module_css_default.meta,
1993
+ children: [" ", meta]
1994
+ }) : null]
1805
1995
  }),
1806
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1807
- className: `${SessionStatsChip_module_css_default["cell"]} ${SessionStatsChip_module_css_default["costCell"]}`,
1808
- "aria-label": t("chip.cost", { value: costText }),
1809
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1810
- ref: costRef,
1811
- className: SessionStatsChip_module_css_default["costInner"],
1812
- children: costText
1813
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1814
- className: SessionStatsChip_module_css_default["deltaLayer"],
1815
- "aria-hidden": "true",
1816
- children: flies.map((fly) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CostDeltaFlyLabel, {
1817
- text: fly.text,
1818
- vars: fly.vars
1819
- }, fly.id))
1820
- })]
1996
+ remaining !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1997
+ className: QuotaButton_module_css_default.bar,
1998
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1999
+ className: `${QuotaButton_module_css_default.fill} ${QuotaButton_module_css_default[severity]}`,
2000
+ style: { width: `${String(Math.round(remaining))}%` }
2001
+ })
2002
+ }),
2003
+ aux !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2004
+ className: QuotaButton_module_css_default.aux,
2005
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `${QuotaButton_module_css_default.dot} ${QuotaButton_module_css_default[severity]}` }), aux]
1821
2006
  })
1822
2007
  ]
1823
2008
  });
1824
2009
  }
1825
- /** Defensive shape check: an older host build or a misrouted response
1826
- * would otherwise paint the header chip with garbage. */
1827
- function looksLikeUsageSummary(value) {
1828
- return typeof value === "object" && value !== null && typeof value.total === "object" && value.total !== null;
2010
+ /** The panel's width tier for one payload: what the windows PAINT decides —
2011
+ * a lone amount (no computable bar, the DeepSeek shape) reads at the
2012
+ * minimal plate, one bar (a weekly-only plan, or a balance with a spend
2013
+ * total like OpenRouter) the middle one, two or more bars the full plate.
2014
+ * Errors and payloads without windows read the full plate (their copy
2015
+ * runs long). */
2016
+ function panelWidthOf(payload) {
2017
+ if (payload === null || payload.status !== "ok") return PANEL_WIDTH_FULL;
2018
+ const bars = payload.windows.filter((window) => quotaUsedPercent(window) !== void 0).length;
2019
+ if (bars === 0) return payload.windows.length > 0 ? PANEL_WIDTH_BALANCE : PANEL_WIDTH_FULL;
2020
+ return bars === 1 ? PANEL_WIDTH_SINGLE : PANEL_WIDTH_FULL;
2021
+ }
2022
+ /** Friendly locale copy for one normalized query error. */
2023
+ function errorText(error, t) {
2024
+ switch (error.kind) {
2025
+ case "auth": return t("quota.error.auth", { message: error.message });
2026
+ case "no-credential": return t("quota.error.noCredential", { ref: error.message });
2027
+ case "http": return t("quota.error.http", { message: error.message });
2028
+ case "network": return t("quota.error.network", { message: error.message });
2029
+ case "parse": return t("quota.error.parse", { message: error.message });
2030
+ }
2031
+ }
2032
+ /** Defensive shape check: a misrouted response must not paint the button. */
2033
+ function looksLikeQuotaPayload(value) {
2034
+ return typeof value === "object" && value !== null && typeof value.status === "string" && typeof value.intervalSec === "number";
1829
2035
  }
1830
2036
  /**
1831
- * Fetch the summary scoped to one session and its subagent subtree. Throws
1832
- * on transport failure (network, abort, non-2xx response, or a payload
1833
- * that doesn't look like a stats summary) so the hook can keep the
1834
- * previous render in place — a transient miss never blanks the chip. The
1835
- * hook's `silentAfterFirst` flag is what suppresses the resulting error
1836
- * state.
1837
- * @param sessionIds - the active session plus its subagent descendants;
1838
- * an empty list skips the fetch (returning null rather than throwing, so
1839
- * the hook's first-load gate stays at "loading").
1840
- * @param signal - the cancellation signal from the hook.
2037
+ * Fetch the quota payload for the active session, naming the chip-selected
2038
+ * provider when one is known. Throws on transport failure or a payload that
2039
+ * does not look like one, so the hook can keep the previous render
2040
+ * (silentAfterFirst) or stay hidden (first failure).
1841
2041
  */
1842
- async function fetchSessionSummary$1(sessionIds, signal) {
1843
- if (sessionIds.length === 0) return null;
1844
- const response = await fetch(STATS_PATH + encodeStatsQuery({
1845
- sessionIds,
1846
- fields: "chip"
1847
- }), {
2042
+ async function fetchQuotaPayload(sessionId, provider, signal) {
2043
+ const params = new URLSearchParams();
2044
+ if (sessionId !== "") params.set("session", sessionId);
2045
+ if (provider !== void 0 && provider !== "") params.set("provider", provider);
2046
+ const encoded = params.toString();
2047
+ const query = encoded === "" ? "" : `?${encoded}`;
2048
+ const response = await fetch(QUOTA_PATH + query, {
1848
2049
  headers: { accept: "application/json" },
1849
2050
  signal
1850
2051
  });
1851
2052
  if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
1852
2053
  const value = await response.json();
1853
- if (!looksLikeUsageSummary(value)) throw new Error("unexpected stats response");
2054
+ if (!looksLikeQuotaPayload(value)) throw new Error("unexpected quota response");
1854
2055
  return value;
1855
2056
  }
1856
2057
  //#endregion
1857
2058
  //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\TokenUsageCard.module.css.mjs
1858
- const css$9 = "._1bMeTa_card{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);border-radius:12px;list-style:none;transition:border-color .16s,background .16s}._1bMeTa_card:hover{border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_cardOpen{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_header{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:0 0;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}._1bMeTa_header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}._1bMeTa_headText{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}._1bMeTa_name{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}._1bMeTa_description{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}._1bMeTa_pending{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;flex:none;padding:1px 8px;font-size:11px;font-weight:500;line-height:17px}._1bMeTa_chevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}._1bMeTa_chevronOpen{transform:rotate(180deg)}._1bMeTa_body{border-top:1px solid var(--dsw-alias-border-l2);flex-direction:column;gap:10px;margin:0 16px;padding:12px 0 8px;display:flex}._1bMeTa_note{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}._1bMeTa_field{flex-direction:column;gap:4px;display:flex}._1bMeTa_fieldLabel{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}._1bMeTa_input{box-sizing:border-box;width:100%;font:inherit;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);appearance:none;border-radius:6px;padding:4px 8px;font-size:13px;line-height:20px}._1bMeTa_input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px}._1bMeTa_input:disabled{opacity:.6}._1bMeTa_inputRow{align-items:center;gap:6px;display:flex}._1bMeTa_inputRow ._1bMeTa_input{flex:1;min-width:0}._1bMeTa_browse{appearance:none;border:1px solid var(--dsw-alias-border-l2);font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;background:0 0;border-radius:6px;flex:none;padding:4px 10px;font-size:13px;line-height:20px}._1bMeTa_browse:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_browse:disabled{opacity:.4;cursor:default}._1bMeTa_browse:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_hint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}._1bMeTa_migration{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);border-radius:6px;flex-direction:column;gap:4px;padding:8px 10px;display:flex}._1bMeTa_migrationLabel{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;line-height:1.5}._1bMeTa_migrationBar{background:var(--dsw-alias-bg-multi-select);border-radius:2px;height:4px;display:block;overflow:hidden}._1bMeTa_migrationFill{background:var(--dsw-alias-brand-primary);border-radius:2px;height:100%;transition:width .2s;display:block}._1bMeTa_footer{border-top:1px solid var(--dsw-alias-border-l2);justify-content:flex-end;align-items:center;gap:8px;padding:8px 0 4px;display:flex}._1bMeTa_failed{min-width:0;color:var(--dsw-alias-label-error);flex:1;margin:0;font-size:12px;line-height:1.5}._1bMeTa_discard,._1bMeTa_save{appearance:none;font:inherit;cursor:pointer;border:1px solid #0000;border-radius:8px;padding:5px 14px;font-size:13px;line-height:1.5}._1bMeTa_discard{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:0 0}._1bMeTa_discard:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_save{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}._1bMeTa_discard:disabled,._1bMeTa_save:disabled{opacity:.4;cursor:default}._1bMeTa_discard:focus-visible,._1bMeTa_save:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_fullSync{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);border-radius:8px;flex-direction:column;gap:8px;padding:10px 12px;display:flex}._1bMeTa_fullSyncHeader{flex-direction:column;gap:2px;display:flex}._1bMeTa_fullSyncTitle{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:600;line-height:1.4}._1bMeTa_fullSyncHint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.5}._1bMeTa_fullSyncButton{appearance:none;border:1px solid var(--dsw-alias-border-l2);font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;background:0 0;border-radius:6px;align-self:flex-start;padding:4px 12px;font-size:13px;line-height:20px}._1bMeTa_fullSyncButton:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_fullSyncButton:disabled{opacity:.5;cursor:default}._1bMeTa_fullSyncButton:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_fullSyncProgress{flex-direction:column;gap:4px;display:flex}._1bMeTa_fullSyncProgressLabel{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;line-height:1.5}._1bMeTa_fullSyncBar{background:var(--dsw-alias-bg-multi-select);border-radius:2px;height:4px;display:block;overflow:hidden}._1bMeTa_fullSyncFill{background:var(--dsw-alias-brand-primary);border-radius:2px;height:100%;transition:width .2s;display:block}._1bMeTa_fullSyncResult{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;margin:0;font-size:12px;line-height:1.5}._1bMeTa_fullSyncError{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5}";
1859
- const tagId$9 = "@laoyuehanni/dsh-token-usage/TokenUsageCard.module.css";
1860
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$9) + "]") === null) {
2059
+ const css$10 = "._1bMeTa_card{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);border-radius:12px;list-style:none;transition:border-color .16s,background .16s}._1bMeTa_card:hover{border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_cardOpen{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_header{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:0 0;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}._1bMeTa_header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}._1bMeTa_headText{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}._1bMeTa_name{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}._1bMeTa_description{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}._1bMeTa_pending{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;flex:none;padding:1px 8px;font-size:11px;font-weight:500;line-height:17px}._1bMeTa_chevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}._1bMeTa_chevronOpen{transform:rotate(180deg)}._1bMeTa_body{border-top:1px solid var(--dsw-alias-border-l2);flex-direction:column;gap:10px;margin:0 16px;padding:12px 0 8px;display:flex}._1bMeTa_note{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}._1bMeTa_field{flex-direction:column;gap:4px;display:flex}._1bMeTa_fieldLabel{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}._1bMeTa_input{box-sizing:border-box;width:100%;font:inherit;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);appearance:none;border-radius:6px;padding:4px 8px;font-size:13px;line-height:20px}._1bMeTa_input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px}._1bMeTa_input:disabled{opacity:.6}._1bMeTa_inputRow{align-items:center;gap:6px;display:flex}._1bMeTa_inputRow ._1bMeTa_input{flex:1;min-width:0}._1bMeTa_browse{appearance:none;border:1px solid var(--dsw-alias-border-l2);font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;background:0 0;border-radius:6px;flex:none;padding:4px 10px;font-size:13px;line-height:20px}._1bMeTa_browse:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_browse:disabled{opacity:.4;cursor:default}._1bMeTa_browse:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_hint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}._1bMeTa_migration{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);border-radius:6px;flex-direction:column;gap:4px;padding:8px 10px;display:flex}._1bMeTa_migrationLabel{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;line-height:1.5}._1bMeTa_migrationBar{background:var(--dsw-alias-bg-multi-select);border-radius:2px;height:4px;display:block;overflow:hidden}._1bMeTa_migrationFill{background:var(--dsw-alias-brand-primary);border-radius:2px;height:100%;transition:width .2s;display:block}._1bMeTa_footer{border-top:1px solid var(--dsw-alias-border-l2);justify-content:flex-end;align-items:center;gap:8px;padding:8px 0 4px;display:flex}._1bMeTa_failed{min-width:0;color:var(--dsw-alias-label-error);flex:1;margin:0;font-size:12px;line-height:1.5}._1bMeTa_discard,._1bMeTa_save{appearance:none;font:inherit;cursor:pointer;border:1px solid #0000;border-radius:8px;padding:5px 14px;font-size:13px;line-height:1.5}._1bMeTa_discard{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:0 0}._1bMeTa_discard:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_save{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}._1bMeTa_discard:disabled,._1bMeTa_save:disabled{opacity:.4;cursor:default}._1bMeTa_discard:focus-visible,._1bMeTa_save:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_fullSync{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);border-radius:8px;flex-direction:column;gap:8px;padding:10px 12px;display:flex}._1bMeTa_fullSyncHeader{flex-direction:column;gap:2px;display:flex}._1bMeTa_fullSyncTitle{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:600;line-height:1.4}._1bMeTa_fullSyncHint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.5}._1bMeTa_fullSyncButton{appearance:none;border:1px solid var(--dsw-alias-border-l2);font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;background:0 0;border-radius:6px;align-self:flex-start;padding:4px 12px;font-size:13px;line-height:20px}._1bMeTa_fullSyncButton:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_fullSyncButton:disabled{opacity:.5;cursor:default}._1bMeTa_fullSyncButton:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_fullSyncProgress{flex-direction:column;gap:4px;display:flex}._1bMeTa_fullSyncProgressLabel{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;line-height:1.5}._1bMeTa_fullSyncBar{background:var(--dsw-alias-bg-multi-select);border-radius:2px;height:4px;display:block;overflow:hidden}._1bMeTa_fullSyncFill{background:var(--dsw-alias-brand-primary);border-radius:2px;height:100%;transition:width .2s;display:block}._1bMeTa_fullSyncResult{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;margin:0;font-size:12px;line-height:1.5}._1bMeTa_fullSyncError{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5}";
2060
+ const tagId$10 = "@laoyuehanni/dsh-token-usage/TokenUsageCard.module.css";
2061
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$10) + "]") === null) {
1861
2062
  const tag = document.createElement("style");
1862
2063
  tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
1863
- tag.dataset.pluginCss = tagId$9;
1864
- tag.textContent = css$9;
2064
+ tag.dataset.pluginCss = tagId$10;
2065
+ tag.textContent = css$10;
1865
2066
  document.head.appendChild(tag);
1866
2067
  }
1867
2068
  var TokenUsageCard_module_css_default = {
@@ -2241,13 +2442,13 @@ window.__ModuleLoader__.load({
2241
2442
  }
2242
2443
  //#endregion
2243
2444
  //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\DateRangePicker.module.css.mjs
2244
- const css$8 = ".aSiNOq_wrapper{flex:none;display:inline-flex;position:relative}.aSiNOq_trigger{box-sizing:border-box;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);cursor:pointer;white-space:nowrap;border-radius:6px;flex:none;padding:4px 10px;font-size:13px;line-height:20px}.aSiNOq_trigger:hover,.aSiNOq_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover)}.aSiNOq_panel{z-index:100;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);width:266px;max-width:calc(100vw - 32px);box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-secondary);text-align:left;cursor:default;border-radius:12px;padding:10px;font-size:12px;line-height:20px;position:absolute;top:calc(100% + 6px);left:0}.aSiNOq_head{justify-content:space-between;align-items:center;gap:4px;margin-bottom:6px;display:flex}.aSiNOq_nav{width:24px;height:24px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:6px;flex:none;padding:0;font-size:14px;line-height:1}.aSiNOq_nav:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}.aSiNOq_monthTitle{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;font-size:13px;font-weight:500}.aSiNOq_weekdays,.aSiNOq_grid{grid-template-columns:repeat(7,1fr);gap:2px;display:grid}.aSiNOq_weekday{text-align:center;color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:16px}.aSiNOq_blank{visibility:hidden;height:26px}.aSiNOq_day{font-variant-numeric:tabular-nums;text-align:center;height:26px;color:var(--dsw-alias-label-primary);cursor:pointer;background:0 0;border:none;border-radius:6px;padding:0;font-size:12px;line-height:26px}.aSiNOq_day:hover{background:var(--dsw-alias-interactive-bg-hover)}.aSiNOq_dayToday{box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l2)}.aSiNOq_dayAnchor,.aSiNOq_daySelected{color:var(--dsw-alias-brand-primary);box-shadow:inset 0 0 0 1px var(--dsw-alias-brand-primary);font-weight:600}.aSiNOq_dayInRange{background:var(--dsw-alias-interactive-bg-hover);border-radius:0}.aSiNOq_foot{border-top:1px solid var(--dsw-alias-border-l1);justify-content:flex-end;margin-top:8px;padding-top:8px;display:flex}.aSiNOq_clear{color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:6px;padding:2px 8px;font-size:12px;line-height:18px}.aSiNOq_clear:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}";
2245
- const tagId$8 = "@laoyuehanni/dsh-token-usage/DateRangePicker.module.css";
2246
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$8) + "]") === null) {
2445
+ const css$9 = ".aSiNOq_wrapper{flex:none;display:inline-flex;position:relative}.aSiNOq_trigger{box-sizing:border-box;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);cursor:pointer;white-space:nowrap;border-radius:6px;flex:none;padding:4px 10px;font-size:13px;line-height:20px}.aSiNOq_trigger:hover,.aSiNOq_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover)}.aSiNOq_panel{z-index:100;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);width:266px;max-width:calc(100vw - 32px);box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-secondary);text-align:left;cursor:default;border-radius:12px;padding:10px;font-size:12px;line-height:20px;position:absolute;top:calc(100% + 6px);left:0}.aSiNOq_head{justify-content:space-between;align-items:center;gap:4px;margin-bottom:6px;display:flex}.aSiNOq_nav{width:24px;height:24px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:6px;flex:none;padding:0;font-size:14px;line-height:1}.aSiNOq_nav:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}.aSiNOq_monthTitle{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;font-size:13px;font-weight:500}.aSiNOq_weekdays,.aSiNOq_grid{grid-template-columns:repeat(7,1fr);gap:2px;display:grid}.aSiNOq_weekday{text-align:center;color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:16px}.aSiNOq_blank{visibility:hidden;height:26px}.aSiNOq_day{font-variant-numeric:tabular-nums;text-align:center;height:26px;color:var(--dsw-alias-label-primary);cursor:pointer;background:0 0;border:none;border-radius:6px;padding:0;font-size:12px;line-height:26px}.aSiNOq_day:hover{background:var(--dsw-alias-interactive-bg-hover)}.aSiNOq_dayToday{box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l2)}.aSiNOq_dayAnchor,.aSiNOq_daySelected{color:var(--dsw-alias-brand-primary);box-shadow:inset 0 0 0 1px var(--dsw-alias-brand-primary);font-weight:600}.aSiNOq_dayInRange{background:var(--dsw-alias-interactive-bg-hover);border-radius:0}.aSiNOq_foot{border-top:1px solid var(--dsw-alias-border-l1);justify-content:flex-end;margin-top:8px;padding-top:8px;display:flex}.aSiNOq_clear{color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:6px;padding:2px 8px;font-size:12px;line-height:18px}.aSiNOq_clear:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}";
2446
+ const tagId$9 = "@laoyuehanni/dsh-token-usage/DateRangePicker.module.css";
2447
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$9) + "]") === null) {
2247
2448
  const tag = document.createElement("style");
2248
2449
  tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
2249
- tag.dataset.pluginCss = tagId$8;
2250
- tag.textContent = css$8;
2450
+ tag.dataset.pluginCss = tagId$9;
2451
+ tag.textContent = css$9;
2251
2452
  document.head.appendChild(tag);
2252
2453
  }
2253
2454
  var DateRangePicker_module_css_default = {
@@ -2470,6 +2671,40 @@ window.__ModuleLoader__.load({
2470
2671
  });
2471
2672
  }
2472
2673
  //#endregion
2674
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\hit-rate-band.module.css.mjs
2675
+ const css$8 = ".t6JM8a_band_critical{color:var(--dsw-alias-state-error-primary,#dc2626)}.t6JM8a_band_amber{color:#f59e0b}.t6JM8a_band_lime{color:#84cc16}.t6JM8a_band_healthy{color:var(--dsw-alias-state-success-primary,#16a34a)}";
2676
+ const tagId$8 = "@laoyuehanni/dsh-token-usage/hit-rate-band.module.css";
2677
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$8) + "]") === null) {
2678
+ const tag = document.createElement("style");
2679
+ tag.dataset.plugin = "@laoyuehanni/dsh-token-usage";
2680
+ tag.dataset.pluginCss = tagId$8;
2681
+ tag.textContent = css$8;
2682
+ document.head.appendChild(tag);
2683
+ }
2684
+ var hit_rate_band_module_css_default = {
2685
+ "band_amber": "t6JM8a_band_amber",
2686
+ "band_critical": "t6JM8a_band_critical",
2687
+ "band_healthy": "t6JM8a_band_healthy",
2688
+ "band_lime": "t6JM8a_band_lime"
2689
+ };
2690
+ //#endregion
2691
+ //#region src/client/HitRateText.tsx
2692
+ /** CSS-module class for one hit-rate colour bucket. */
2693
+ function bandClassOf(band) {
2694
+ return hit_rate_band_module_css_default[`band_${band}`] ?? "";
2695
+ }
2696
+ /**
2697
+ * Render a hit-rate percentage (or `—`) in its threshold colour.
2698
+ * @param totals - the aggregated token buckets the rate is computed from.
2699
+ */
2700
+ function HitRateText({ totals }) {
2701
+ const { text, band } = hitRateDisplay(totals);
2702
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2703
+ className: bandClassOf(band),
2704
+ children: text
2705
+ });
2706
+ }
2707
+ //#endregion
2473
2708
  //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\MenuSelect.module.css.mjs
2474
2709
  const css$7 = ".KUIXpG_wrapper{display:inline-flex;position:relative}.KUIXpG_trigger{box-sizing:border-box;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);cursor:pointer;white-space:nowrap;text-overflow:ellipsis;background-image:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12' fill='none'%3E%3Cpath d='M3 4.5L6 7.5L9 4.5' stroke='%2381858C' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E/%3C/svg%3E\");background-position:right 6px center;background-repeat:no-repeat;background-size:12px 12px;border-radius:6px;flex:none;padding:4px 24px 4px 8px;font-size:13px;line-height:20px;overflow:hidden}.KUIXpG_trigger:hover,.KUIXpG_trigger[aria-expanded=true]{background-color:var(--dsw-alias-interactive-bg-hover)}.KUIXpG_grow{flex:0 auto;min-width:0;max-width:220px}.KUIXpG_panel{z-index:100;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);min-width:100%;max-width:260px;max-height:240px;box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-secondary);text-align:left;cursor:default;border-radius:12px;padding:6px;font-size:13px;line-height:20px;position:absolute;top:calc(100% + 6px);left:0;overflow-y:auto}.KUIXpG_option{width:100%;color:var(--dsw-alias-label-primary);cursor:pointer;white-space:nowrap;background:0 0;border:none;border-radius:6px;justify-content:space-between;align-items:center;gap:12px;padding:4px 8px;font-size:13px;line-height:20px;display:flex}.KUIXpG_option:hover{background:var(--dsw-alias-interactive-bg-hover)}.KUIXpG_optionLabel{text-overflow:ellipsis;overflow:hidden}.KUIXpG_optionSelected{color:var(--dsw-alias-brand-primary)}.KUIXpG_check{color:var(--dsw-alias-brand-primary);flex:none}";
2475
2710
  const tagId$7 = "@laoyuehanni/dsh-token-usage/MenuSelect.module.css";
@@ -5827,9 +6062,18 @@ window.__ModuleLoader__.load({
5827
6062
  "view.subagents.titleCol": "会话",
5828
6063
  "view.subagents.nested": "含 {count} 个子会话",
5829
6064
  "view.note": "注:token 与费用来自本插件的请求记录(安装后);平均首token 与 token速度来自 DSH 会话投影(含安装前历史)。",
5830
- "chip.tokens": "含子会话 token 用量 {value}",
5831
- "chip.hitRate": "含子会话缓存命中率 {value}",
5832
- "chip.cost": "含子会话费用 {value}",
6065
+ "pill.cost": "费用 {value}",
6066
+ "pill.costWithSubs": "费用(含子会话){value}",
6067
+ "pill.scopeTag": "含子会话",
6068
+ "panel.title": "用量明细",
6069
+ "panel.openHint": "点击展开用量明细",
6070
+ "panel.tokens": "{value} tok",
6071
+ "panel.hitRate": "缓存命中 {value}",
6072
+ "panel.self": "本会话",
6073
+ "panel.subs": "子会话 ×{count}",
6074
+ "panel.byModel": "按模型",
6075
+ "panel.unpriced": "未定价模型 ×{count}",
6076
+ "panel.unpricedNote": "仅计 token",
5833
6077
  "quota.trigger": "供应商配额",
5834
6078
  "quota.triggerSummary": "{name} · {figure}",
5835
6079
  "quota.panel": "供应商配额面板",
@@ -6001,9 +6245,18 @@ window.__ModuleLoader__.load({
6001
6245
  "view.subagents.titleCol": "Session",
6002
6246
  "view.subagents.nested": "With {count} subagents",
6003
6247
  "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).",
6004
- "chip.tokens": "Tokens with subagents {value}",
6005
- "chip.hitRate": "Cache hit rate with subagents {value}",
6006
- "chip.cost": "Cost with subagents {value}",
6248
+ "pill.cost": "Cost {value}",
6249
+ "pill.costWithSubs": "Cost with subagents {value}",
6250
+ "pill.scopeTag": "with subagents",
6251
+ "panel.title": "Usage details",
6252
+ "panel.openHint": "click to open usage details",
6253
+ "panel.tokens": "{value} tok",
6254
+ "panel.hitRate": "cache hit {value}",
6255
+ "panel.self": "This session",
6256
+ "panel.subs": "Subagents ×{count}",
6257
+ "panel.byModel": "By model",
6258
+ "panel.unpriced": "Unpriced model ×{count}",
6259
+ "panel.unpricedNote": "tokens only",
6007
6260
  "quota.trigger": "Provider quota",
6008
6261
  "quota.triggerSummary": "{name} · {figure}",
6009
6262
  "quota.panel": "Provider quota panel",
@@ -6119,12 +6372,12 @@ window.__ModuleLoader__.load({
6119
6372
  label: () => t("view.usage"),
6120
6373
  locale: NS
6121
6374
  }, UsageView));
6122
- ctx.slots.inject("conversation.session.header.utilities", () => ctx.slots.register({
6123
- name: "conversation.session.header.utilities",
6124
- id: "session-stats",
6125
- order: -10,
6375
+ ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
6376
+ name: "conversation.composer.dock",
6377
+ id: "token-usage-cost",
6378
+ order: 10,
6126
6379
  locale: NS
6127
- }, SessionStatsChip));
6380
+ }, CostPill));
6128
6381
  const modelDirectory = { service: void 0 };
6129
6382
  ctx.inject(["modelDirectories"], (modelCtx) => {
6130
6383
  modelCtx.effect(() => {