dsh-usage-peak 1.4.1 → 1.6.0

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/client.js CHANGED
@@ -53,6 +53,7 @@ window.__ModuleLoader__.load({
53
53
  'unit.calls': '次',
54
54
  'unit.minute': '分',
55
55
  'warn.unknownModel': '未识别的模型按 Flash 价计算',
56
+ 'warn.pricingInvalid': '自定义价目参数无效,已回退默认价目',
56
57
  'warn.calendarMissing': '以下年份还没有节假日数据,峰谷按周一至周五计算:',
57
58
  'footer.calendar': '峰谷已计入节假日与调休:',
58
59
  'footer.star': '给个 Star',
@@ -116,9 +117,14 @@ window.__ModuleLoader__.load({
116
117
  'export.projectsTitle': '导出项目数据 CSV',
117
118
 
118
119
  'chart.hours': '今日每小时花费',
119
- 'chart.hoursHint': '橙 峰时 · 绿 谷时',
120
+ 'chart.hoursHint': '橙 峰时 · 绿 谷时 · 悬停或聚焦看详情',
120
121
  'chart.days': '每天花费',
121
- 'chart.daysHint': '橙 峰时 · 绿 谷时',
122
+ 'chart.daysHint': '橙 峰时 · 绿 谷时 · 悬停或聚焦看详情',
123
+ 'tip.cost': '花费',
124
+ 'tip.calls': '请求',
125
+ 'tip.tokens': 'tokens',
126
+ 'tip.hit': '缓存命中',
127
+ 'tip.hint': '用 ← → 浏览每小时 / 每天,Esc 关闭',
122
128
 
123
129
  'cost.title': '今日花费构成',
124
130
  'cost.cache': '缓存命中',
@@ -132,7 +138,20 @@ window.__ModuleLoader__.load({
132
138
  'price.hit': '命中',
133
139
  'price.miss': '未命中',
134
140
  'price.out': '输出',
135
- 'price.current': '当前',
141
+ 'price.custom': '自定义价目',
142
+ 'pricing.title': '自定义价目表',
143
+ 'pricing.hint': '仅保存在本机;保存后所有金额与 CSV 立即按新价目重算。',
144
+ 'pricing.cache': '缓存命中',
145
+ 'pricing.input': '输入',
146
+ 'pricing.output': '输出',
147
+ 'pricing.valley': '谷',
148
+ 'pricing.peak': '峰',
149
+ 'pricing.save': '保存价目',
150
+ 'pricing.reset': '恢复默认',
151
+ 'pricing.saved': '已应用自定义价目;当前页面所有面板同步生效。',
152
+ 'pricing.savedMemory': '存储不可用;仅本页生效,关闭页面后会丢失。',
153
+ 'pricing.invalid': '请填写 0 或有限正数价格。',
154
+ 'pricing.resetDone': '已恢复默认价目。',
136
155
  },
137
156
  en: {
138
157
  'settings.title': 'Usage dashboard',
@@ -165,6 +184,7 @@ window.__ModuleLoader__.load({
165
184
  'unit.calls': 'req',
166
185
  'unit.minute': 'm',
167
186
  'warn.unknownModel': 'Unknown models are priced as Flash',
187
+ 'warn.pricingInvalid': 'Invalid custom pricing; reverted to the default price list',
168
188
  'warn.calendarMissing': 'No holiday data for these years, peak hours fall back to Mon-Fri:',
169
189
  'footer.calendar': 'Peak hours include holidays and makeup workdays:',
170
190
  'footer.star': 'Star it',
@@ -228,9 +248,14 @@ window.__ModuleLoader__.load({
228
248
  'export.projectsTitle': 'Export project CSV',
229
249
 
230
250
  'chart.hours': 'Cost per hour today',
231
- 'chart.hoursHint': 'orange peak · green valley',
251
+ 'chart.hoursHint': 'orange peak · green valley · hover or focus for details',
232
252
  'chart.days': 'Spend by day',
233
- 'chart.daysHint': 'orange peak · green valley',
253
+ 'chart.daysHint': 'orange peak · green valley · hover or focus for details',
254
+ 'tip.cost': 'Spend',
255
+ 'tip.calls': 'Requests',
256
+ 'tip.tokens': 'tokens',
257
+ 'tip.hit': 'Cache hit',
258
+ 'tip.hint': 'Use ← → to browse hours or days, Esc to close',
234
259
 
235
260
  'cost.title': 'Today by token type',
236
261
  'cost.cache': 'Cache hits',
@@ -244,7 +269,20 @@ window.__ModuleLoader__.load({
244
269
  'price.hit': 'Hit',
245
270
  'price.miss': 'Miss',
246
271
  'price.out': 'Output',
247
- 'price.current': 'now',
272
+ 'price.custom': 'custom pricing',
273
+ 'pricing.title': 'Custom price list',
274
+ 'pricing.hint': 'Stored only in this browser; saving recalculates every figure and CSV immediately.',
275
+ 'pricing.cache': 'Cache hit',
276
+ 'pricing.input': 'Input',
277
+ 'pricing.output': 'Output',
278
+ 'pricing.valley': 'valley',
279
+ 'pricing.peak': 'peak',
280
+ 'pricing.save': 'Save prices',
281
+ 'pricing.reset': 'Restore defaults',
282
+ 'pricing.saved': 'Custom pricing applied; all panels on this page are synchronized.',
283
+ 'pricing.savedMemory': 'Storage unavailable; applies only to this page until it closes.',
284
+ 'pricing.invalid': 'Enter 0 or a finite positive price.',
285
+ 'pricing.resetDone': 'Default prices restored.',
248
286
  },
249
287
  };
250
288
 
@@ -325,8 +363,99 @@ window.__ModuleLoader__.load({
325
363
  const PREFS_KEY = 'dsh-usage-peak:alerts:v1';
326
364
  const PREFS_EVENT = 'dsh-usage-peak:alerts-change';
327
365
  const DEFAULT_PREFS = { warnDays: 7, lowDays: 3, dailyBudget: null };
366
+ const PRICING_KEY = 'dsh-usage-peak:pricing:v1';
367
+ const PRICING_EVENT = 'dsh-usage-peak:pricing-change';
368
+ const DEFAULT_PRICING = [
369
+ { id: 'flash', label: 'DeepSeek Flash', hit: [0.02, 0.04], miss: [1, 2], out: [4, 8] },
370
+ { id: 'pro', label: 'DeepSeek Pro', hit: [0.15, 0.3], miss: [4.5, 9], out: [13.5, 27] },
371
+ ];
372
+ const PRICING_IDS = DEFAULT_PRICING.map((price) => price.id);
373
+ const PRICING_MAX = 1e7;
328
374
  const tint = (color, amount = 10) => `color-mix(in srgb, ${color} ${amount}%, transparent)`;
329
375
 
376
+ function clonePricing(table) {
377
+ return (table || DEFAULT_PRICING).map((price) => ({
378
+ id: price.id,
379
+ label: price.label,
380
+ hit: [...price.hit],
381
+ miss: [...price.miss],
382
+ out: [...price.out],
383
+ }));
384
+ }
385
+
386
+ function validatePricing(value) {
387
+ if (!Array.isArray(value) || value.length !== PRICING_IDS.length) return null;
388
+ const byId = new Map();
389
+ for (const entry of value) {
390
+ if (!entry || typeof entry !== 'object' || !PRICING_IDS.includes(entry.id) || byId.has(entry.id)) return null;
391
+ const pair = (values) => {
392
+ if (!Array.isArray(values) || values.length !== 2) return null;
393
+ const nums = values.map((v) => {
394
+ if (typeof v === 'number') return v;
395
+ if (typeof v === 'string' && v.trim() !== '') return Number(v);
396
+ return NaN;
397
+ });
398
+ if (!nums.every((n) => Number.isFinite(n) && n >= 0 && n <= PRICING_MAX)) return null;
399
+ return nums;
400
+ };
401
+ const hit = pair(entry.hit);
402
+ const miss = pair(entry.miss);
403
+ const out = pair(entry.out);
404
+ if (!hit || !miss || !out) return null;
405
+ const base = DEFAULT_PRICING.find((price) => price.id === entry.id);
406
+ byId.set(entry.id, { id: entry.id, label: base.label, hit, miss, out });
407
+ }
408
+ return PRICING_IDS.every((id) => byId.has(id)) ? PRICING_IDS.map((id) => byId.get(id)) : null;
409
+ }
410
+
411
+ function encodePricing(table) {
412
+ const normalized = validatePricing(table);
413
+ if (!normalized) return '';
414
+ return normalized
415
+ .map((price) => `${price.id}:${[...price.hit, ...price.miss, ...price.out].join(',')}`)
416
+ .join('|');
417
+ }
418
+
419
+ function pricingParam(table) {
420
+ if (!table) return '';
421
+ const encoded = encodePricing(table);
422
+ return encoded && encoded !== encodePricing(DEFAULT_PRICING) ? encoded : '';
423
+ }
424
+
425
+ let memoryPricing = clonePricing(DEFAULT_PRICING);
426
+ let pricingStorageFailed = false;
427
+ function readPricing() {
428
+ if (pricingStorageFailed) return clonePricing(memoryPricing);
429
+ try {
430
+ const raw = window.localStorage.getItem(PRICING_KEY);
431
+ if (raw !== null) memoryPricing = validatePricing(JSON.parse(raw)) || clonePricing(DEFAULT_PRICING);
432
+ } catch { /* Disabled storage: retain this page's last valid prices. */ }
433
+ return clonePricing(memoryPricing);
434
+ }
435
+ function savePricing(value) {
436
+ const next = validatePricing(value);
437
+ if (!next) return false;
438
+ memoryPricing = next;
439
+ try { window.localStorage.setItem(PRICING_KEY, JSON.stringify(next)); pricingStorageFailed = false; } catch { pricingStorageFailed = true; }
440
+ window.dispatchEvent(new CustomEvent(PRICING_EVENT, { detail: next }));
441
+ return true;
442
+ }
443
+ function usePricing() {
444
+ const [pricing, setPricing] = useState(readPricing);
445
+ useEffect(() => {
446
+ const sync = (event) => {
447
+ if (event.type === 'storage' && event.key !== PRICING_KEY && event.key !== null) return;
448
+ if (event.type === 'storage') pricingStorageFailed = false;
449
+ if (event.type === 'storage' && event.key === PRICING_KEY && event.newValue === null) memoryPricing = clonePricing(DEFAULT_PRICING);
450
+ setPricing(event.type === PRICING_EVENT ? clonePricing(memoryPricing) : readPricing());
451
+ };
452
+ window.addEventListener(PRICING_EVENT, sync);
453
+ window.addEventListener('storage', sync);
454
+ return () => { window.removeEventListener(PRICING_EVENT, sync); window.removeEventListener('storage', sync); };
455
+ }, []);
456
+ return pricing;
457
+ }
458
+
330
459
  function validatePrefs(value) {
331
460
  if (!value || typeof value !== 'object') return null;
332
461
  const positive = (v) => (typeof v === 'number' || typeof v === 'string') && String(v).trim() !== '' && Number.isFinite(Number(v)) && Number(v) > 0;
@@ -384,8 +513,9 @@ window.__ModuleLoader__.load({
384
513
  active: rank[level] > 0, tone: level === 'low' ? C.error : level === 'warn' ? C.peak : C.text3 };
385
514
  }
386
515
 
387
- function feedUrl(base, days, project, fresh = false) {
388
- return `${base}?days=${days || DEFAULT_DAYS}${project ? `&project=${encodeURIComponent(project)}` : ''}${fresh ? '&fresh=1' : ''}`;
516
+ function feedUrl(base, days, project, fresh = false, pricing = '') {
517
+ const pricePart = typeof pricing === 'string' ? pricing : pricingParam(pricing);
518
+ return `${base}?days=${days || DEFAULT_DAYS}${project ? `&project=${encodeURIComponent(project)}` : ''}${pricePart ? `&pricing=${encodeURIComponent(pricePart)}` : ''}${fresh ? '&fresh=1' : ''}`;
389
519
  }
390
520
 
391
521
  // Keep the peak/valley countdown visible in the pill; the warning is an
@@ -394,6 +524,12 @@ window.__ModuleLoader__.load({
394
524
  return alertActive ? `⚠ ${switchText}` : switchText;
395
525
  }
396
526
 
527
+ /** Clamp a tooltip's left edge so it stays inside its chart box. */
528
+ function tipAnchor(center, tipWidth, boxWidth, inset = 4) {
529
+ const limit = Math.max(inset, boxWidth - tipWidth - inset);
530
+ return Math.min(Math.max(center - tipWidth / 2, inset), limit);
531
+ }
532
+
397
533
  // Generation guard rejects old filter responses and older same-filter reloads.
398
534
  function requestGate() {
399
535
  let key = null;
@@ -405,9 +541,10 @@ window.__ModuleLoader__.load({
405
541
  invalidate() { serial += 1; },
406
542
  };
407
543
  }
408
- function useFeed(days, project = '') {
544
+ function useFeed(days, project = '', pricing = null) {
409
545
  const windowDays = days || DEFAULT_DAYS;
410
- const queryKey = JSON.stringify([windowDays, project]);
546
+ const pricingKey = pricingParam(pricing);
547
+ const queryKey = JSON.stringify([windowDays, project, pricingKey]);
411
548
  const guard = useRef(null);
412
549
  if (!guard.current) guard.current = requestGate();
413
550
  guard.current.select(queryKey);
@@ -415,7 +552,7 @@ window.__ModuleLoader__.load({
415
552
  const [tick, setTick] = useState(0);
416
553
  const load = useCallback((fresh) => {
417
554
  const ticket = guard.current.begin(queryKey);
418
- fetch(feedUrl(DATA_URL, windowDays, project, fresh), { headers: { accept: 'application/json' } })
555
+ fetch(feedUrl(DATA_URL, windowDays, project, fresh, pricingKey), { headers: { accept: 'application/json' } })
419
556
  .then((response) => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); })
420
557
  .then((data) => {
421
558
  if (!data || data.ok === false) throw new Error((data && data.error) || 'bad payload');
@@ -424,7 +561,7 @@ window.__ModuleLoader__.load({
424
561
  .catch((error) => {
425
562
  if (guard.current.current(ticket)) setState((previous) => ({ key: queryKey, loading: false, error: String(error && error.message), data: previous.key === queryKey ? previous.data : null }));
426
563
  });
427
- }, [queryKey, windowDays, project]);
564
+ }, [queryKey, windowDays, project, pricingKey]);
428
565
  useEffect(() => {
429
566
  load(false);
430
567
  const timer = setInterval(() => load(false), 60_000);
@@ -497,7 +634,8 @@ window.__ModuleLoader__.load({
497
634
  */
498
635
  function PanelGlyph(props) {
499
636
  const t = props.t;
500
- const { data } = useFeed();
637
+ const pricing = usePricing();
638
+ const { data } = useFeed(DEFAULT_DAYS, '', pricing);
501
639
  const rail = !!props.rail;
502
640
  const open = typeof props.onOpen === 'function' ? props.onOpen : null;
503
641
  const rootProps = { 'data-usage-widget': '', title: '' };
@@ -561,7 +699,17 @@ window.__ModuleLoader__.load({
561
699
  h(Sep),
562
700
  h(
563
701
  'span',
564
- { style: { color: C.text2, flex: 'none', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
702
+ {
703
+ style: {
704
+ color: C.text2,
705
+ flex: '0 1 auto',
706
+ minWidth: 0,
707
+ overflow: 'hidden',
708
+ textOverflow: 'ellipsis',
709
+ fontVariantNumeric: 'tabular-nums',
710
+ whiteSpace: 'nowrap',
711
+ },
712
+ },
565
713
  data && data.today ? shortTokens(data.today.tokens) : '—',
566
714
  h('span', { style: { color: C.text3, marginLeft: 2 } }, 'tok'),
567
715
  ),
@@ -655,81 +803,317 @@ window.__ModuleLoader__.load({
655
803
  );
656
804
  }
657
805
 
658
- function HourChart(props) {
659
- const hours = props.hours || [];
660
- const max = Math.max(0.0001, ...hours.map((entry) => entry.cost));
806
+ /* ------------------------------- chart tips ------------------------------ */
807
+
808
+ const srOnly = {
809
+ position: 'absolute',
810
+ width: 1,
811
+ height: 1,
812
+ margin: -1,
813
+ padding: 0,
814
+ overflow: 'hidden',
815
+ clip: 'rect(0 0 0 0)',
816
+ whiteSpace: 'nowrap',
817
+ border: 0,
818
+ };
819
+
820
+ /** Live width of an element, so dense charts can thin their labels. */
821
+ function useBoxWidth(ref) {
822
+ const [width, setWidth] = useState(0);
823
+ useEffect(() => {
824
+ const node = ref.current;
825
+ if (!node) return undefined;
826
+ const update = () => setWidth(node.clientWidth);
827
+ update();
828
+ if (typeof ResizeObserver === 'undefined') return undefined;
829
+ const observer = new ResizeObserver(update);
830
+ observer.observe(node);
831
+ return () => observer.disconnect();
832
+ }, []);
833
+ return width;
834
+ }
835
+
836
+ /**
837
+ * Hover plus keyboard state for one chart.
838
+ *
839
+ * The tooltip is anchored to the hovered column's centre and clamped to the
840
+ * chart box, so it never spills out of a narrow panel.
841
+ */
842
+ function useChartTip(count) {
843
+ const [active, setActive] = useState(-1);
844
+ const [focused, setFocused] = useState(false);
845
+ const [anchor, setAnchor] = useState(null);
846
+ const boxRef = useRef(null);
847
+ const columns = useRef([]);
848
+ const width = useBoxWidth(boxRef);
849
+ const tipWidth = Math.min(216, Math.max(150, (width || 240) - 8));
850
+
851
+ useEffect(() => {
852
+ const column = active >= 0 ? columns.current[active] : null;
853
+ if (!column || !width) {
854
+ setAnchor(null);
855
+ return;
856
+ }
857
+ setAnchor({ left: tipAnchor(column.offsetLeft + column.offsetWidth / 2, tipWidth, width), width: tipWidth });
858
+ }, [active, width, tipWidth]);
859
+
860
+ const step = (delta) =>
861
+ setActive((current) => {
862
+ const from = current < 0 ? (delta > 0 ? -1 : 0) : current;
863
+ return (from + delta + count) % count;
864
+ });
865
+
866
+ const onKeyDown = (event) => {
867
+ if (!count) return;
868
+ if (event.key === 'ArrowRight') {
869
+ event.preventDefault();
870
+ step(1);
871
+ } else if (event.key === 'ArrowLeft') {
872
+ event.preventDefault();
873
+ step(-1);
874
+ } else if (event.key === 'Home') {
875
+ event.preventDefault();
876
+ setActive(0);
877
+ } else if (event.key === 'End') {
878
+ event.preventDefault();
879
+ setActive(count - 1);
880
+ } else if (event.key === 'Escape') {
881
+ setActive(-1);
882
+ }
883
+ };
884
+
885
+ const onBlur = (event) => {
886
+ if (event.currentTarget.contains(event.relatedTarget)) return;
887
+ setFocused(false);
888
+ setActive(-1);
889
+ };
890
+
891
+ return {
892
+ active,
893
+ anchor,
894
+ boxRef,
895
+ columns,
896
+ width,
897
+ focused,
898
+ tipWidth,
899
+ onKeyDown,
900
+ onBlur,
901
+ onFocus: () => setFocused(true),
902
+ show: setActive,
903
+ clear: () => setActive(-1),
904
+ };
905
+ }
906
+
907
+ function ChartTip(props) {
661
908
  return h(
662
909
  'div',
663
- { style: { display: 'flex', alignItems: 'flex-end', gap: 3, height: 108, marginTop: 2 } },
664
- hours.map((entry) =>
910
+ {
911
+ role: 'tooltip',
912
+ style: {
913
+ position: 'absolute',
914
+ top: 0,
915
+ left: props.left,
916
+ width: props.width,
917
+ zIndex: 3,
918
+ pointerEvents: 'none',
919
+ boxSizing: 'border-box',
920
+ padding: '6px 9px',
921
+ borderRadius: 8,
922
+ border: `1px solid ${C.border}`,
923
+ background: C.layer1,
924
+ boxShadow: '0 8px 24px rgba(0, 0, 0, 0.22)',
925
+ fontSize: 10.5,
926
+ lineHeight: '15px',
927
+ color: C.text2,
928
+ },
929
+ },
930
+ h(
931
+ 'div',
932
+ {
933
+ style: {
934
+ color: C.text,
935
+ fontWeight: 600,
936
+ marginBottom: 3,
937
+ fontVariantNumeric: 'tabular-nums',
938
+ whiteSpace: 'nowrap',
939
+ overflow: 'hidden',
940
+ textOverflow: 'ellipsis',
941
+ },
942
+ },
943
+ props.title,
944
+ ),
945
+ (props.rows || []).map((row, index) =>
665
946
  h(
666
947
  'div',
667
- {
668
- key: entry.hour,
669
- title: `${String(entry.hour).padStart(2, '0')}:00 · ${yuan(entry.cost)} · ${entry.calls} ${props.t('unit.calls')}`,
670
- style: {
671
- flex: 1,
672
- display: 'flex',
673
- flexDirection: 'column',
674
- justifyContent: 'flex-end',
675
- height: '100%',
676
- minWidth: 5,
677
- borderRadius: 4,
678
- outline: entry.hour === props.nowHour ? `1px solid ${C.border}` : 'none',
679
- outlineOffset: 1,
680
- },
681
- },
682
- h('div', {
683
- style: {
684
- height: `${Math.max(entry.cost > 0 ? 3 : 0, (entry.cost / max) * 100)}%`,
685
- background: entry.peak ? C.peak : C.valley,
686
- opacity: entry.cost > 0 ? 0.9 : 0,
687
- borderRadius: 3,
688
- },
689
- }),
948
+ { key: index, style: { display: 'flex', justifyContent: 'space-between', gap: 12 } },
949
+ h('span', { style: { color: C.text3, flex: 'none' } }, row[0]),
950
+ h('span', { style: { color: C.text, fontVariantNumeric: 'tabular-nums', textAlign: 'right' } }, row[1]),
690
951
  ),
691
952
  ),
692
953
  );
693
954
  }
694
955
 
695
- function DayChart(props) {
696
- const days = props.days || [];
697
- const max = Math.max(0.0001, ...days.map((entry) => entry.cost));
956
+ function HourChart(props) {
957
+ const hours = props.hours || [];
958
+ const t = props.t;
959
+ const max = Math.max(0.0001, ...hours.map((entry) => entry.cost));
960
+ const tip = useChartTip(hours.length);
961
+ const active = tip.active >= 0 ? hours[tip.active] : null;
962
+ const label = active ? `${String(active.hour).padStart(2, '0')}:00 · ${active.peak ? t('status.peak') : t('status.valley')}` : '';
963
+ const rows = active
964
+ ? [
965
+ [t('tip.cost'), yuan(active.cost)],
966
+ [t('tip.calls'), `${active.calls} ${t('unit.calls')}`],
967
+ [t('tip.tokens'), tokens(active.tokens || 0, t)],
968
+ [t('tip.hit'), percent(active.hitRate || 0)],
969
+ ]
970
+ : [];
698
971
  return h(
699
972
  'div',
700
- { style: { display: 'flex', alignItems: 'flex-end', gap: 8, height: 128, marginTop: 4 } },
701
- days.map((entry) =>
702
- h(
703
- 'div',
704
- {
705
- key: entry.day,
706
- style: { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, height: '100%' },
707
- },
708
- h(
709
- 'span',
710
- { style: { fontSize: 9.5, color: C.text3, fontVariantNumeric: 'tabular-nums' } },
711
- entry.cost > 0 ? entry.cost.toFixed(1) : '',
712
- ),
973
+ {
974
+ role: 'group',
975
+ tabIndex: 0,
976
+ 'aria-label': t('chart.hours'),
977
+ title: t('tip.hint'),
978
+ onKeyDown: tip.onKeyDown,
979
+ onFocus: tip.onFocus,
980
+ onBlur: tip.onBlur,
981
+ style: {
982
+ position: 'relative',
983
+ marginTop: 2,
984
+ borderRadius: 6,
985
+ outline: tip.focused ? `2px solid ${C.out}` : 'none',
986
+ outlineOffset: 2,
987
+ },
988
+ },
989
+ h(
990
+ 'div',
991
+ {
992
+ ref: tip.boxRef,
993
+ onMouseLeave: tip.clear,
994
+ style: { display: 'flex', alignItems: 'flex-end', gap: 3, height: 108 },
995
+ },
996
+ hours.map((entry, index) =>
713
997
  h(
714
998
  'div',
715
999
  {
716
- title: `${entry.day}${entry.holiday ? ` · ${entry.holiday}` : ''} · ${yuan(entry.cost)} · ${entry.calls} ${props.t('unit.calls')}`,
1000
+ key: entry.hour,
1001
+ ref: (node) => {
1002
+ tip.columns.current[index] = node;
1003
+ },
1004
+ onMouseEnter: () => tip.show(index),
717
1005
  style: {
718
1006
  flex: 1,
719
- width: '100%',
720
1007
  display: 'flex',
721
1008
  flexDirection: 'column',
722
1009
  justifyContent: 'flex-end',
1010
+ height: '100%',
1011
+ minWidth: 3,
723
1012
  borderRadius: 4,
724
- overflow: 'hidden',
1013
+ outline: entry.hour === props.nowHour ? `1px solid ${C.border}` : 'none',
1014
+ outlineOffset: 1,
725
1015
  },
726
1016
  },
727
- h('div', { style: { height: `${(entry.peakCost / max) * 100}%`, background: C.peak, opacity: 0.9 } }),
728
- h('div', { style: { height: `${(entry.valleyCost / max) * 100}%`, background: C.valley, opacity: 0.9 } }),
1017
+ h('div', {
1018
+ style: {
1019
+ height: `${Math.max(entry.cost > 0 ? 3 : 0, (entry.cost / max) * 100)}%`,
1020
+ background: entry.peak ? C.peak : C.valley,
1021
+ opacity: entry.cost > 0 ? (tip.active < 0 || tip.active === index ? 0.9 : 0.4) : 0,
1022
+ borderRadius: 3,
1023
+ transition: 'opacity 120ms',
1024
+ },
1025
+ }),
729
1026
  ),
730
- h('span', { style: { fontSize: 9.5, color: C.text2 } }, entry.day.slice(5)),
731
1027
  ),
732
1028
  ),
1029
+ tip.anchor ? h(ChartTip, { title: label, rows, left: tip.anchor.left, width: tip.anchor.width }) : null,
1030
+ active ? h('span', { 'aria-live': 'polite', style: srOnly }, `${label} · ${rows.map((row) => `${row[0]} ${row[1]}`).join(' · ')}`) : null,
1031
+ );
1032
+ }
1033
+
1034
+ function DayChart(props) {
1035
+ const days = props.days || [];
1036
+ const t = props.t;
1037
+ const max = Math.max(0.0001, ...days.map((entry) => entry.cost));
1038
+ const tip = useChartTip(days.length);
1039
+ const dense = tip.width > 0 && days.length > 0 && tip.width / days.length < 26;
1040
+ const gap = dense ? 2 : 8;
1041
+ const labelStride = dense ? Math.max(1, Math.ceil(days.length / 7)) : 1;
1042
+ const active = tip.active >= 0 ? days[tip.active] : null;
1043
+ const label = active ? `${active.day}${active.holiday ? ` · ${active.holiday}` : ''}` : '';
1044
+ const rows = active
1045
+ ? [
1046
+ [t('tip.cost'), yuan(active.cost)],
1047
+ [t('tip.calls'), `${active.calls} ${t('unit.calls')}`],
1048
+ [t('tip.tokens'), tokens(active.tokens || 0, t)],
1049
+ [t('tip.hit'), percent(active.hitRate || 0)],
1050
+ ]
1051
+ : [];
1052
+ return h(
1053
+ 'div',
1054
+ {
1055
+ role: 'group',
1056
+ tabIndex: 0,
1057
+ 'aria-label': t('chart.days'),
1058
+ title: t('tip.hint'),
1059
+ onKeyDown: tip.onKeyDown,
1060
+ onFocus: tip.onFocus,
1061
+ onBlur: tip.onBlur,
1062
+ style: {
1063
+ position: 'relative',
1064
+ marginTop: 4,
1065
+ borderRadius: 6,
1066
+ outline: tip.focused ? `2px solid ${C.out}` : 'none',
1067
+ outlineOffset: 2,
1068
+ },
1069
+ },
1070
+ h(
1071
+ 'div',
1072
+ {
1073
+ ref: tip.boxRef,
1074
+ onMouseLeave: tip.clear,
1075
+ style: { display: 'flex', alignItems: 'flex-end', gap, height: 128 },
1076
+ },
1077
+ days.map((entry, index) =>
1078
+ h(
1079
+ 'div',
1080
+ {
1081
+ key: entry.day,
1082
+ ref: (node) => {
1083
+ tip.columns.current[index] = node;
1084
+ },
1085
+ onMouseEnter: () => tip.show(index),
1086
+ style: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, height: '100%' },
1087
+ },
1088
+ dense
1089
+ ? null
1090
+ : h('span', { style: { fontSize: 9.5, color: C.text3, fontVariantNumeric: 'tabular-nums' } }, entry.cost > 0 ? entry.cost.toFixed(1) : ''),
1091
+ h(
1092
+ 'div',
1093
+ {
1094
+ style: {
1095
+ flex: 1,
1096
+ width: '100%',
1097
+ display: 'flex',
1098
+ flexDirection: 'column',
1099
+ justifyContent: 'flex-end',
1100
+ borderRadius: 4,
1101
+ overflow: 'hidden',
1102
+ opacity: tip.active < 0 || tip.active === index ? 1 : 0.45,
1103
+ transition: 'opacity 120ms',
1104
+ },
1105
+ },
1106
+ h('div', { style: { height: `${(entry.peakCost / max) * 100}%`, background: C.peak, opacity: 0.9 } }),
1107
+ h('div', { style: { height: `${(entry.valleyCost / max) * 100}%`, background: C.valley, opacity: 0.9 } }),
1108
+ ),
1109
+ index % labelStride === 0
1110
+ ? h('span', { style: { fontSize: dense ? 9 : 9.5, color: C.text2, whiteSpace: 'nowrap' } }, dense ? entry.day.slice(8) : entry.day.slice(5))
1111
+ : h('span', { style: { height: dense ? 11 : 12 } }),
1112
+ ),
1113
+ ),
1114
+ ),
1115
+ tip.anchor ? h(ChartTip, { title: label, rows, left: tip.anchor.left, width: tip.anchor.width }) : null,
1116
+ active ? h('span', { 'aria-live': 'polite', style: srOnly }, `${label} · ${rows.map((row) => `${row[0]} ${row[1]}`).join(' · ')}`) : null,
733
1117
  );
734
1118
  }
735
1119
 
@@ -782,9 +1166,8 @@ window.__ModuleLoader__.load({
782
1166
  h('td', { style: { padding: '4px 8px', color: C.text } }, offset === 0 ? model.label : ''),
783
1167
  h(
784
1168
  'td',
785
- { style: { padding: '4px 8px', color: C.text2 } },
1169
+ { style: { padding: '4px 8px', color: C.text2, fontWeight: current ? 600 : 400 } },
786
1170
  isPeak ? t('status.peak') : t('status.valley'),
787
- current ? ` · ${t('price.current')}` : '',
788
1171
  ),
789
1172
  h('td', { style: { padding: '4px 8px', textAlign: 'right', color: C.text } }, model.hit[offset]),
790
1173
  h('td', { style: { padding: '4px 8px', textAlign: 'right', color: C.text } }, model.miss[offset]),
@@ -794,33 +1177,38 @@ window.__ModuleLoader__.load({
794
1177
  }
795
1178
  }
796
1179
  return h(
797
- 'table',
798
- { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
1180
+ 'div',
1181
+ { style: { overflowX: 'auto', margin: '0 -2px' } },
799
1182
  h(
800
- 'thead',
801
- null,
1183
+ 'table',
1184
+ { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
802
1185
  h(
803
- 'tr',
1186
+ 'thead',
804
1187
  null,
805
- head.map((label, index) =>
806
- h(
807
- 'th',
808
- {
809
- key: label,
810
- style: {
811
- padding: '3px 8px',
812
- textAlign: index >= 2 ? 'right' : 'left',
813
- fontWeight: 500,
814
- color: C.text3,
815
- borderBottom: `1px solid ${C.border}`,
1188
+ h(
1189
+ 'tr',
1190
+ null,
1191
+ head.map((label, index) =>
1192
+ h(
1193
+ 'th',
1194
+ {
1195
+ key: label,
1196
+ style: {
1197
+ padding: '3px 8px',
1198
+ textAlign: index >= 2 ? 'right' : 'left',
1199
+ fontWeight: 500,
1200
+ color: C.text3,
1201
+ whiteSpace: 'nowrap',
1202
+ borderBottom: `1px solid ${C.border}`,
1203
+ },
816
1204
  },
817
- },
818
- label,
1205
+ label,
1206
+ ),
819
1207
  ),
820
1208
  ),
821
1209
  ),
1210
+ h('tbody', null, rows),
822
1211
  ),
823
- h('tbody', null, rows),
824
1212
  );
825
1213
  }
826
1214
 
@@ -906,30 +1294,34 @@ window.__ModuleLoader__.load({
906
1294
  }
907
1295
  const head = [t('price.model'), t('projects.calls'), t('projects.tokens'), t('projects.cost')];
908
1296
  return h(
909
- 'table',
910
- { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
1297
+ 'div',
1298
+ { style: { overflowX: 'auto', margin: '0 -2px' } },
911
1299
  h(
912
- 'thead',
913
- null,
1300
+ 'table',
1301
+ { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
914
1302
  h(
915
- 'tr',
1303
+ 'thead',
916
1304
  null,
917
- head.map((label, index) =>
918
- h('th', { key: label, style: cellHead(index === 0 ? 'left' : 'right') }, label),
919
- ),
920
- ),
921
- ),
922
- h(
923
- 'tbody',
924
- null,
925
- rows.map((model) =>
926
1305
  h(
927
1306
  'tr',
928
- { key: model.id },
929
- h('td', { style: { ...cellBody, color: C.text } }, model.label),
930
- h('td', { style: { ...cellBody, textAlign: 'right' } }, model.calls),
931
- h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(model.tokens, t)),
932
- h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(model.cost)),
1307
+ null,
1308
+ head.map((label, index) =>
1309
+ h('th', { key: label, style: cellHead(index === 0 ? 'left' : 'right') }, label),
1310
+ ),
1311
+ ),
1312
+ ),
1313
+ h(
1314
+ 'tbody',
1315
+ null,
1316
+ rows.map((model) =>
1317
+ h(
1318
+ 'tr',
1319
+ { key: model.id },
1320
+ h('td', { style: { ...cellBody, color: C.text } }, model.label),
1321
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, model.calls),
1322
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(model.tokens, t)),
1323
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(model.cost)),
1324
+ ),
933
1325
  ),
934
1326
  ),
935
1327
  ),
@@ -951,13 +1343,95 @@ window.__ModuleLoader__.load({
951
1343
  message ? h('span', { role: 'status', style: { color: message === 'alerts.invalid' ? C.error : C.valley, fontSize: 11 } }, t(message)) : null);
952
1344
  }
953
1345
 
1346
+ function PricingSettings(props) {
1347
+ const { pricing, t } = props;
1348
+ const pricingKey = encodePricing(pricing);
1349
+ const [draft, setDraft] = useState(() => clonePricing(pricing));
1350
+ const [message, setMessage] = useState('');
1351
+ useEffect(() => { setDraft(clonePricing(pricing)); }, [pricingKey]);
1352
+ const fields = [['hit', 'pricing.cache'], ['miss', 'pricing.input'], ['out', 'pricing.output']];
1353
+ const buttonStyle = { color: C.text, background: C.layer2, border: `1px solid ${C.border}`, padding: '5px 12px', borderRadius: 5, cursor: 'pointer' };
1354
+ const priceInput = (model, modelIndex, field, offset) => h('input', {
1355
+ key: offset,
1356
+ type: 'number',
1357
+ min: 0,
1358
+ step: 'any',
1359
+ inputMode: 'decimal',
1360
+ 'aria-label': `${model.label} ${fields.find(([name]) => name === field)[1]} ${offset ? t('pricing.peak') : t('pricing.valley')}`,
1361
+ value: model[field][offset],
1362
+ onChange: (event) => {
1363
+ const raw = event.target.value;
1364
+ setDraft((previous) => previous.map((entry, index) => (index === modelIndex ? { ...entry, [field]: entry[field].map((value, i) => (i === offset ? raw : value)) } : entry)));
1365
+ setMessage('');
1366
+ },
1367
+ style: { width: '100%', minWidth: 0, padding: '4px 5px', borderRadius: 5, border: `1px solid ${C.border}`, color: C.text, background: C.layer2, fontVariantNumeric: 'tabular-nums', boxSizing: 'border-box' },
1368
+ });
1369
+ const fieldGrid = { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(146px, 1fr))', gap: 8 };
1370
+ const fieldRow = (model, modelIndex, field, key) => h(
1371
+ 'label',
1372
+ { key: field, style: { display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0 } },
1373
+ h('span', { style: { fontSize: 10.5, color: C.text3 } }, `${t(key)} · ${t('pricing.valley')}/${t('pricing.peak')}`),
1374
+ h(
1375
+ 'span',
1376
+ { style: { display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 } },
1377
+ priceInput(model, modelIndex, field, 0),
1378
+ h('span', { key: 'sep', style: { color: C.text3, fontSize: 10, flex: 'none' } }, '/'),
1379
+ priceInput(model, modelIndex, field, 1),
1380
+ ),
1381
+ );
1382
+ const rows = draft.map((model, modelIndex) => h(
1383
+ 'div',
1384
+ {
1385
+ key: model.id,
1386
+ style: {
1387
+ display: 'flex',
1388
+ flexDirection: 'column',
1389
+ gap: 6,
1390
+ paddingBottom: 8,
1391
+ borderBottom: modelIndex === draft.length - 1 ? 'none' : `1px solid ${C.border}`,
1392
+ },
1393
+ },
1394
+ h('span', { key: 'label', style: { fontSize: 11.5, color: C.text, fontWeight: 600 } }, model.label),
1395
+ h('div', { key: 'fields', style: fieldGrid }, fields.map(([field, key]) => fieldRow(model, modelIndex, field, key))),
1396
+ ));
1397
+ return h(Card, null,
1398
+ h(CardTitle, { title: t('pricing.title'), hint: t('pricing.hint') }),
1399
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } }, rows),
1400
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
1401
+ h('button', {
1402
+ type: 'button',
1403
+ onClick: () => {
1404
+ if (savePricing(draft)) {
1405
+ setDraft(clonePricing(readPricing()));
1406
+ setMessage(pricingStorageFailed ? 'pricing.savedMemory' : 'pricing.saved');
1407
+ } else {
1408
+ setMessage('pricing.invalid');
1409
+ }
1410
+ },
1411
+ style: buttonStyle,
1412
+ }, t('pricing.save')),
1413
+ h('button', {
1414
+ type: 'button',
1415
+ onClick: () => {
1416
+ savePricing(clonePricing(DEFAULT_PRICING));
1417
+ setDraft(clonePricing(DEFAULT_PRICING));
1418
+ setMessage('pricing.resetDone');
1419
+ },
1420
+ style: buttonStyle,
1421
+ }, t('pricing.reset')),
1422
+ message ? h('span', { role: 'status', style: { fontSize: 11, color: message === 'pricing.invalid' ? C.error : C.valley } }, t(message)) : null),
1423
+ );
1424
+ }
1425
+
954
1426
  /* -------------------------------- settings ------------------------------- */
955
1427
 
956
1428
  function Dashboard(props) {
957
1429
  const t = props.t;
958
1430
  const [days, setDays] = useState(props.days || 14);
959
1431
  const [project, setProject] = useState('');
960
- const feed = useFeed(days, project);
1432
+ const pricing = usePricing();
1433
+ const pricingKey = pricingParam(pricing);
1434
+ const feed = useFeed(days, project, pricing);
961
1435
  const data = feed.data;
962
1436
  const windowDays = (data && data.windowDays) || days;
963
1437
  const peakNow = data ? data.now.peak : false;
@@ -1067,7 +1541,9 @@ window.__ModuleLoader__.load({
1067
1541
  ? warning
1068
1542
  : warning.code === 'unknown-model'
1069
1543
  ? `${t('warn.unknownModel')}: ${(warning.models || []).join(', ')}`
1070
- : warning.code === 'calendar-missing'
1544
+ : warning.code === 'pricing-invalid'
1545
+ ? t('warn.pricingInvalid')
1546
+ : warning.code === 'calendar-missing'
1071
1547
  ? `${t('warn.calendarMissing')} ${(warning.years || []).join(' / ')}`
1072
1548
  : String(warning.code || warning),
1073
1549
  ),
@@ -1079,7 +1555,7 @@ window.__ModuleLoader__.load({
1079
1555
  body.push(
1080
1556
  h(
1081
1557
  'div',
1082
- { key: 'kpi', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10 } },
1558
+ { key: 'kpi', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 140px), 1fr))', gap: 10 } },
1083
1559
  h(Kpi, {
1084
1560
  label: t('kpi.runway'),
1085
1561
  value: wallet && wallet.runwayDays !== null ? runway(wallet.runwayDays, t) : '—',
@@ -1118,10 +1594,10 @@ window.__ModuleLoader__.load({
1118
1594
  body.push(
1119
1595
  h(
1120
1596
  'div',
1121
- { key: 'charts', style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1.5fr) minmax(0, 1fr)', gap: 10 } },
1597
+ { key: 'charts', style: { display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'stretch' } },
1122
1598
  h(
1123
1599
  Card,
1124
- null,
1600
+ { style: { flex: '1.5 1 340px', minWidth: 0 } },
1125
1601
  h(CardTitle, { title: t('chart.hours'), hint: t('chart.hoursHint') }),
1126
1602
  h(HourChart, { hours: data.hours, nowHour: data.now.hour, t }),
1127
1603
  h(
@@ -1132,7 +1608,7 @@ window.__ModuleLoader__.load({
1132
1608
  ),
1133
1609
  h(
1134
1610
  Card,
1135
- null,
1611
+ { style: { flex: '1 1 220px', minWidth: 0 } },
1136
1612
  h(CardTitle, { title: t('cost.title') }),
1137
1613
  h(CostSplit, {
1138
1614
  t,
@@ -1171,7 +1647,7 @@ window.__ModuleLoader__.load({
1171
1647
  action: h(
1172
1648
  'a',
1173
1649
  {
1174
- href: `${feedUrl(EXPORT_URL, windowDays, project)}&scope=projects`,
1650
+ href: `${feedUrl(EXPORT_URL, windowDays, project, false, pricingKey)}&scope=projects`,
1175
1651
  download: '',
1176
1652
  title: t('export.projectsTitle'),
1177
1653
  style: { color: C.cache, textDecoration: 'none', fontWeight: 500 },
@@ -1194,10 +1670,12 @@ window.__ModuleLoader__.load({
1194
1670
  h(
1195
1671
  Card,
1196
1672
  { key: 'price' },
1197
- h(CardTitle, { title: t('price.title'), hint: t('price.hint') }),
1673
+ h(CardTitle, { title: t('price.title'), hint: `${t('price.hint')}${data.pricingCustom ? ` · ${t('price.custom')}` : ''}` }),
1198
1674
  h(PriceTable, { pricing: data.pricing, peakNow, t }),
1199
1675
  ),
1200
1676
  );
1677
+
1678
+ body.push(h(PricingSettings, { key: 'pricing-settings', pricing, t }));
1201
1679
  }
1202
1680
 
1203
1681
  return h(
@@ -1270,7 +1748,7 @@ window.__ModuleLoader__.load({
1270
1748
  h(
1271
1749
  'a',
1272
1750
  {
1273
- href: feedUrl(EXPORT_URL, windowDays, project),
1751
+ href: feedUrl(EXPORT_URL, windowDays, project, false, pricingKey),
1274
1752
  download: '',
1275
1753
  title: t('export.daysTitle'),
1276
1754
  style: {