@lls-a1/dsh-balance-float 1.1.55 → 1.2.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/README.md CHANGED
@@ -29,9 +29,12 @@ Host 半边在本地记账(按轮记 token 与费用、轮询余额),浏
29
29
  - 单价表列出 Flash / Pro 的命中、未命中、输出单价,当前生效的一侧高亮;
30
30
  - 柱状图看近 7 天用量,点某根柱子看那天明细(总消耗、峰谷拆分、按模型费用)。
31
31
 
32
- **Token 用量**(默认折叠)
32
+ **用量趋势**
33
33
 
34
- 标题右侧显示合计,展开后逐行看缓存命中率、未缓存输入、缓存读取、输出。
34
+ - 四档窗口:**今天 / 近7天 / 近30天 / 本月**,默认今天;
35
+ - 「今天」是个下拉,可回看昨天及更早 6 天;在其它档位点「今天」只切回今天,再点一次才展开下拉;
36
+ - 每档都给出:总额、调用次数、**峰段/谷段花费**(红/绿)、按模型的金额与占比条;
37
+ - 点柱状图任意一根柱子,打开那天的明细面板(含缓存命中率与 Token 分项)。
35
38
 
36
39
  ## 操作
37
40
 
package/client.js CHANGED
@@ -31,7 +31,6 @@ window.__ModuleLoader__.load({
31
31
  const PACKAGE_NAME = '@lls-a1/dsh-balance-float';
32
32
  const ROUTE = '/balance-float/snapshot';
33
33
  const ROUTE_UPDATE = '/balance-float/update';
34
- const REPO_URL = 'https://github.com/ming-a1/dsh-balance-float';
35
34
  const POS_KEY = 'dsh.balance-float.position';
36
35
  // Official top-up page; the balance endpoint has no recharge API, so the
37
36
  // panel only links out to the console.
@@ -77,13 +76,11 @@ window.__ModuleLoader__.load({
77
76
  'peak.label': '峰价',
78
77
  valley: '谷价',
79
78
  'schedule.title': '峰谷计费时段',
80
- 'tokens.title': 'Token 用量',
81
79
  'tokens.input': '未缓存输入',
82
80
  'tokens.cache': '缓存读取',
83
81
  'tokens.output': '输出',
84
82
  'tokens.total': '合计',
85
83
  'tokens.hit': '缓存命中',
86
- 'tokens.empty': '分项从本版本开始记录,历史事件只有合计',
87
84
  'day.back': '← 返回',
88
85
  'day.title': '当日明细',
89
86
  'day.calls': '{count} 次调用 · {tokens} tokens',
@@ -109,6 +106,8 @@ window.__ModuleLoader__.load({
109
106
  'price.miss': '未命中',
110
107
  'price.out': '输出',
111
108
  history: '用量趋势',
109
+ 'history.window.today': '今天',
110
+ 'history.yesterday': '昨天',
112
111
  'history.window.7': '近7天',
113
112
  'history.window.30': '近30天',
114
113
  'history.window.month': '本月',
@@ -171,13 +170,11 @@ window.__ModuleLoader__.load({
171
170
  'peak.label': 'Peak',
172
171
  valley: 'Off-peak',
173
172
  'schedule.title': 'Peak and off-peak windows',
174
- 'tokens.title': 'Token usage',
175
173
  'tokens.input': 'Uncached input',
176
174
  'tokens.cache': 'Cache read',
177
175
  'tokens.output': 'Output',
178
176
  'tokens.total': 'Total',
179
177
  'tokens.hit': 'Cache hit',
180
- 'tokens.empty': 'Buckets are recorded from this version on; older events only carry the total',
181
178
  'day.back': '← Back',
182
179
  'day.title': 'Day detail',
183
180
  'day.calls': '{count} calls · {tokens} tokens',
@@ -203,6 +200,8 @@ window.__ModuleLoader__.load({
203
200
  'price.miss': 'Miss',
204
201
  'price.out': 'Out',
205
202
  history: 'Usage trend',
203
+ 'history.window.today': 'Today',
204
+ 'history.yesterday': 'Yesterday',
206
205
  'history.window.7': '7d',
207
206
  'history.window.30': '30d',
208
207
  'history.window.month': 'Month',
@@ -266,14 +265,14 @@ window.__ModuleLoader__.load({
266
265
  '.dbf-dot{width:7px;height:7px;border-radius:50%;flex:0 0 auto}',
267
266
  '.dbf-dot.is-peak{background:var(--dsw-alias-state-error-primary)}',
268
267
  '.dbf-dot.is-valley{background:var(--dsw-alias-state-success-primary)}',
269
- '.dbf-badge{display:inline-flex;align-items:center;gap:5px;padding:1px 7px;border-radius:999px;border:.5px solid var(--dsw-alias-border-l1);background:transparent;font-size:11px;line-height:18px;color:var(--dsw-alias-label-secondary)}',
268
+ '.dbf-badge{display:inline-flex;align-items:center;gap:5px;padding:1px 7px;border-radius:4px;border:.5px solid var(--dsw-alias-border-l1);background:transparent;font-size:11px;line-height:18px;color:var(--dsw-alias-label-secondary)}',
270
269
  '.dbf-card{user-select:none;-webkit-user-select:none;width:316px;border-radius:calc(var(--dbf-radius,16) * 1px);background:transparent;box-shadow:0 12px 36px rgba(0,0,0,calc(.22 * var(--dbf-shadow,1)));overflow:hidden;font-size:12px;line-height:18px;animation:dbf-open-down .24s cubic-bezier(.22,.61,.36,1) both;display:flex;flex-direction:column;will-change:transform,opacity}',
271
270
  '.dbf-dir-up .dbf-card{animation-name:dbf-open-up}',
272
271
  '.dbf-head{display:flex;align-items:center;gap:8px;padding:9px 11px;background:transparent;border-bottom:.5px solid var(--dsw-alias-border-l1);cursor:grab;user-select:none;touch-action:none}',
273
272
  '.dbf-head.is-static{cursor:default}',
274
273
  '.dbf-head:active{cursor:grabbing}',
275
274
  '.dbf-head-title{flex:1;min-width:0;font-weight:600}',
276
- '.dbf-icon{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;line-height:1;transition:background .12s ease,color .12s ease}',
275
+ '.dbf-icon{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;border:0;border-radius:4px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;line-height:1;transition:background .12s ease,color .12s ease}',
277
276
  '.dbf-icon svg{display:block}',
278
277
  '.dbf-icon:disabled{cursor:default;opacity:.6}',
279
278
  '.dbf-spinning svg{animation:dbf-spin .9s linear infinite}',
@@ -296,24 +295,21 @@ window.__ModuleLoader__.load({
296
295
  '.dbf-switch-knob{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:var(--dsw-alias-label-primary,#111);box-shadow:0 1px 2px rgba(0,0,0,.18);transition:transform .15s ease,background-color .15s ease}',
297
296
  '.dbf-switch.is-on .dbf-switch-knob{background:#fff}',
298
297
  '.dbf-switch.is-on .dbf-switch-knob{transform:translateX(14px)}',
299
- '.dbf-topup{flex:none;padding:3px 10px;border-radius:999px;border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l2,currentColor));background:var(--dsw-alias-button-primary-dimmed,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-label-primary);font:inherit;font-size:11px;font-weight:600;line-height:16px;cursor:pointer;transition:background-color .15s ease,border-color .15s ease}',
298
+ '.dbf-topup{flex:none;padding:3px 10px;border-radius:4px;border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l2,currentColor));background:var(--dsw-alias-button-primary-dimmed,var(--dsw-alias-bg-layer-2));color:var(--dsw-alias-label-primary);font:inherit;font-size:11px;font-weight:600;line-height:16px;cursor:pointer;transition:background-color .15s ease,border-color .15s ease}',
300
299
  '.dbf-topup:hover{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
301
300
  '.dbf-topup:active{transform:translateY(.5px)}',
302
301
  '.dbf-countdown{margin-top:8px;margin-bottom:4px;font-size:15px;line-height:22px;letter-spacing:.01em}',
303
- '.dbf-version{display:inline-flex;align-items:center;gap:4px;margin-left:-5px;padding:1px 6px;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;line-height:16px;cursor:pointer;transition:background-color .15s ease,border-color .15s ease,color .15s ease}',
302
+ '.dbf-version{display:inline-flex;align-items:center;gap:4px;margin-left:-5px;padding:1px 6px;border:1px solid transparent;border-radius:4px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;line-height:16px;cursor:pointer;transition:background-color .15s ease,border-color .15s ease,color .15s ease}',
304
303
  '.dbf-version:hover{border-color:var(--dsw-alias-border-l2,var(--dsw-alias-border-l1));background:color-mix(in srgb,var(--dsw-alias-label-primary) 9%,transparent);color:var(--dsw-alias-label-primary)}',
305
304
  '.dbf-version-glyph{font-size:10px;opacity:.75}',
306
305
  '.dbf-version.has-update{color:var(--dsw-alias-state-error-primary)}',
307
306
  '.dbf-version.has-update .dbf-version-glyph{opacity:1}',
308
- '.dbf-fold-head{cursor:pointer;user-select:none}',
309
- '.dbf-fold-arrow{display:inline-block;width:10px;margin-right:3px;color:var(--dsw-alias-label-tertiary);font-size:9px}',
310
- '.dbf-fold-head:hover .dbf-row-title{color:var(--dsw-alias-label-primary)}',
311
307
  '.dbf-token-row{display:flex;align-items:baseline;justify-content:space-between;gap:8px;padding:1px 0}',
312
308
  '.dbf-models{display:flex;flex-direction:column;gap:2px;margin-top:6px}',
313
309
  '.dbf-model-row{display:flex;align-items:baseline;gap:8px}',
314
310
  '.dbf-model-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}',
315
311
  '.dbf-bar{cursor:pointer}',
316
- '.dbf-help{flex:none;display:inline-flex;align-items:center;justify-content:center;width:15px;height:15px;margin-left:5px;padding:0;border-radius:50%;border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l2));background:transparent;color:var(--dsw-alias-label-secondary);font-size:10px;line-height:1;font-weight:600;cursor:pointer}',
312
+ '.dbf-help{flex:none;display:inline-flex;align-items:center;justify-content:center;width:15px;height:15px;margin-left:5px;padding:0;border-radius:4px;border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l2));background:transparent;color:var(--dsw-alias-label-secondary);font-size:10px;line-height:1;font-weight:600;cursor:pointer}',
317
313
  '.dbf-help:hover,.dbf-help.is-open{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
318
314
  '.dbf-hint{margin-top:6px;padding:7px 9px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-overlay));display:flex;flex-direction:column;gap:3px}',
319
315
  '.dbf-rules{margin-top:4px;display:flex;flex-direction:column;gap:2px}',
@@ -338,7 +334,17 @@ window.__ModuleLoader__.load({
338
334
  '.dbf-valley{color:var(--dsw-alias-state-success-primary)}',
339
335
  '.dbf-badge.dbf-peak{border-color:currentColor}',
340
336
  '.dbf-badge.dbf-valley{border-color:currentColor}',
341
- '.dbf-windows{display:inline-flex;gap:2px}',
337
+ '.dbf-windows{display:inline-flex;gap:2px;align-items:center}',
338
+ '.dbf-daypick{position:relative;display:inline-flex}',
339
+ '.dbf-daymenu.is-floating{position:fixed;margin-top:0;z-index:2147483000}',
340
+ '.dbf-daymenu{position:absolute;top:100%;right:0;margin-top:6px;z-index:20;min-width:116px;max-height:216px;overflow:auto;padding:4px;border-radius:8px;background:transparent;border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l2,var(--dsw-alias-border-l1)));color:var(--dsw-alias-label-primary,CanvasText);box-shadow:0 8px 22px rgba(0,0,0,calc(.16 * var(--dbf-shadow,1)));overscroll-behavior:contain;scrollbar-width:none}',
341
+ '.dbf-dayitem{display:flex;align-items:center;gap:6px;width:100%;padding:5px 8px;border:0;border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:12px;line-height:18px;text-align:left;cursor:pointer;white-space:nowrap}',
342
+ '.dbf-dayitem:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent)}',
343
+ '.dbf-dayitem.is-active{background:color-mix(in srgb,var(--dsw-alias-brand-primary,#4d6bfe) 12%,transparent);color:var(--dsw-alias-brand-primary,#4d6bfe);font-weight:600}',
344
+ '.dbf-dayitem.is-group-start{margin-top:3px;border-top:1px solid var(--dsw-alias-border-l1);padding-top:7px}',
345
+ '.dbf-dayitem-label{flex:1 1 auto}',
346
+ '.dbf-dayitem-sub{flex:none;font-size:10.5px;font-weight:400;color:var(--dsw-alias-label-secondary);opacity:.85}',
347
+ '.dbf-dayitem-check{flex:none;font-size:11px}',
342
348
  '.dbf-models-window{margin-top:6px}',
343
349
  '.dbf-mrow{display:flex;align-items:center;gap:6px;font-size:11px;line-height:16px}',
344
350
  '.dbf-mname{min-width:66px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
@@ -346,7 +352,7 @@ window.__ModuleLoader__.load({
346
352
  '.dbf-mbar{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-brand-primary,#4d6bfe);opacity:.75}',
347
353
  '.dbf-mcost{font-variant-numeric:tabular-nums}',
348
354
  '.dbf-mshare{min-width:30px;text-align:right;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}',
349
- '.dbf-window{padding:0 8px;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;line-height:20px;cursor:pointer}',
355
+ '.dbf-window{padding:0 8px;border:0;border-radius:4px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;line-height:20px;cursor:pointer}',
350
356
  '.dbf-window:hover{color:var(--dsw-alias-label-primary)}',
351
357
  '.dbf-window.is-active{background:color-mix(in srgb,var(--dsw-alias-brand-primary,#4d6bfe) 16%,transparent);color:var(--dsw-alias-label-primary);font-weight:600}',
352
358
  '.dbf-trend-meta{display:flex;align-items:baseline;gap:8px;margin-top:5px}',
@@ -382,8 +388,11 @@ window.__ModuleLoader__.load({
382
388
  '.dbf-track-fill{position:absolute;left:0;top:50%;height:4px;transform:translateY(-50%);border-radius:2px;background:var(--dsw-alias-brand-primary,#4d6bfe)}',
383
389
  '.dbf-track-thumb{position:absolute;top:50%;width:14px;height:14px;margin-left:-7px;transform:translateY(-50%);border-radius:50%;background:var(--dsw-alias-bg-overlay);border:2px solid var(--dsw-alias-brand-primary,#4d6bfe);box-shadow:0 1px 3px rgba(0,0,0,calc(.3 * var(--dbf-shadow,1)))}',
384
390
  '.dbf-setting-val{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}',
385
- '.dbf-textbtn{padding:1px 9px;border:.5px solid var(--dsw-alias-border-l1);border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;line-height:18px}',
391
+ '.dbf-textbtn{padding:1px 9px;border:1px solid var(--dsw-alias-border-l3,var(--dsw-alias-border-l2,var(--dsw-alias-border-l1)));border-radius:4px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;line-height:18px}',
386
392
  '.dbf-textbtn:hover{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}',
393
+ '.dbf-textbtn.is-ghost{padding:1px 8px;border-color:var(--dsw-alias-border-l3,var(--dsw-alias-border-l2,var(--dsw-alias-border-l1)));border-radius:4px;background:transparent;font-weight:600}',
394
+ '.dbf-textbtn.is-ghost:hover{background:transparent;color:var(--dsw-alias-label-primary)}',
395
+ '.dbf-textbtn.is-ghost:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:2px}',
387
396
  '.dbf-error{color:var(--dsw-alias-state-error-primary)}',
388
397
  '.dbf-skel{color:var(--dsw-alias-label-secondary)}',
389
398
  ].join('');
@@ -592,6 +601,8 @@ window.__ModuleLoader__.load({
592
601
  function BalanceFloat(props) {
593
602
  const t = props.t;
594
603
  const openPluginPage = typeof props.openPluginPage === 'function' ? props.openPluginPage : () => {};
604
+ const buildDayMenu = (node) =>
605
+ createPortal !== null && typeof document !== 'undefined' ? createPortal(node, document.body) : node;
595
606
  const [snapshot, setSnapshot] = useState(null);
596
607
  const [failure, setFailure] = useState('');
597
608
  const [busy, setBusy] = useState(false);
@@ -614,15 +625,68 @@ window.__ModuleLoader__.load({
614
625
  const [bubbleUp, setBubbleUp] = useState(false);
615
626
  // «?» next to the current billing period: reveals the peak/valley windows.
616
627
  const [hintOpen, setHintOpen] = useState(false);
617
- // A bar of the chart opens that day's detail view; the chart shows 7 or
618
- // 30 days (or the current month) depending on the chosen window.
628
+ // A bar of the chart opens that day's detail view; the chart shows today,
629
+ // 7 or 30 days, or the current month depending on the chosen window.
630
+ const [chartWindow, setChartWindow] = useState('today');
631
+ // Clicking a bar opens that day's detail panel.
619
632
  const [selectedDay, setSelectedDay] = useState(null);
620
- const [chartWindow, setChartWindow] = useState('7');
633
+ // In the day window the user can step back to earlier days via the picker.
634
+ const [trendDay, setTrendDay] = useState('');
635
+ const [dayMenuOpen, setDayMenuOpen] = useState(false);
636
+ // The card body scrolls, so the menu is rendered into <body> and placed
637
+ // next to the button; an in-flow absolute menu would be clipped.
638
+ const [dayMenuPos, setDayMenuPos] = useState(null);
639
+ const dayButtonRef = useRef(null);
640
+ const dayMenuRef = useRef(null);
621
641
  // Token buckets are collapsed until asked for.
622
- const [tokensOpen, setTokensOpen] = useState(false);
623
642
  // Auto check: null | {phase, latest, current, hasUpdate}
624
643
  const [update, setUpdate] = useState(null);
625
644
  const updateCheckedAt = useRef(0);
645
+ // A new day invalidates a picked "yesterday": fall back to today.
646
+ const todayKeyRef = useRef('');
647
+ useEffect(() => {
648
+ const key = snapshot?.today ?? '';
649
+ if (key === '') return;
650
+ if (todayKeyRef.current !== '' && todayKeyRef.current !== key) setTrendDay('');
651
+ todayKeyRef.current = key;
652
+ }, [snapshot?.today]);
653
+
654
+ // The menu is fixed-positioned, so scroll/resize would leave it behind.
655
+ useEffect(() => {
656
+ if (!dayMenuOpen) return undefined;
657
+ const closeOnResize = () => setDayMenuOpen(false);
658
+ // Scrolling the menu itself must not close it; only scrolls of the
659
+ // page behind it would leave the fixed menu behind.
660
+ const closeOnScroll = (event) => {
661
+ if (dayMenuRef.current?.contains(event.target)) return;
662
+ setDayMenuOpen(false);
663
+ };
664
+ window.addEventListener('resize', closeOnResize);
665
+ window.addEventListener('scroll', closeOnScroll, true);
666
+ return () => {
667
+ window.removeEventListener('resize', closeOnResize);
668
+ window.removeEventListener('scroll', closeOnScroll, true);
669
+ };
670
+ }, [dayMenuOpen]);
671
+
672
+ useEffect(() => {
673
+ if (!dayMenuOpen) return undefined;
674
+ const onDown = (event) => {
675
+ if (dayMenuRef.current?.contains(event.target)) return;
676
+ if (dayButtonRef.current?.contains(event.target)) return;
677
+ setDayMenuOpen(false);
678
+ };
679
+ const onKey = (event) => {
680
+ if (event.key === 'Escape') setDayMenuOpen(false);
681
+ };
682
+ window.addEventListener('pointerdown', onDown, true);
683
+ window.addEventListener('keydown', onKey, true);
684
+ return () => {
685
+ window.removeEventListener('pointerdown', onDown, true);
686
+ window.removeEventListener('keydown', onKey, true);
687
+ };
688
+ }, [dayMenuOpen]);
689
+
626
690
  const flashAtRef = useRef(null);
627
691
  const flashTimerRef = useRef(null);
628
692
  const leaveTimerRef = useRef(null);
@@ -735,7 +799,6 @@ window.__ModuleLoader__.load({
735
799
  setLeaving(true);
736
800
  setHintOpen(false);
737
801
  setSelectedDay(null);
738
- setTokensOpen(false);
739
802
  leaveTimerRef.current = window.setTimeout(() => {
740
803
  leaveTimerRef.current = null;
741
804
  setLeaving(false);
@@ -769,6 +832,8 @@ window.__ModuleLoader__.load({
769
832
  void checkUpdate();
770
833
  }, [open, snapshot?.version, checkUpdate]);
771
834
 
835
+ const loadSeq = useRef(0);
836
+ const openRef = useRef(false);
772
837
  const load = useCallback(async (manual) => {
773
838
  // Hold the spinner for at least one full turn: a local read returns in
774
839
  // a few milliseconds, which otherwise looks like nothing happened.
@@ -782,12 +847,28 @@ window.__ModuleLoader__.load({
782
847
  setBusy(true);
783
848
  setRefreshState('refreshing');
784
849
  }
850
+ // Only the newest request may write state: a slow poll that lands after
851
+ // a fresh refresh must not overwrite it.
852
+ const seq = (loadSeq.current += 1);
785
853
  try {
786
- const response = await fetch(ROUTE, { headers: { accept: 'application/json' }, cache: 'no-store' });
854
+ // The closed pill never draws the history rows, so skip them.
855
+ const light = !openRef.current;
856
+ const url = light ? ROUTE + '?days=0' : ROUTE;
857
+ const response = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' });
787
858
  const body = await response.json();
788
- if (!aliveRef.current) return;
859
+ if (!aliveRef.current || seq !== loadSeq.current) return;
789
860
  if (!response.ok) throw new Error(typeof body?.error === 'string' && body.error !== '' ? body.error : 'HTTP ' + response.status);
790
- setSnapshot(body);
861
+ if (light) {
862
+ // Keep the last full day rows: the card can open before the next
863
+ // full poll lands, and rendering zeros in between reads as a bug.
864
+ setSnapshot((previous) => ({
865
+ ...body,
866
+ history: Array.isArray(previous?.history) ? previous.history : [],
867
+ historyTotal: previous?.historyTotal ?? 0,
868
+ }));
869
+ } else {
870
+ setSnapshot(body);
871
+ }
791
872
  setOffset(typeof body?.serverNow === 'number' ? body.serverNow - Date.now() : 0);
792
873
  setFailure('');
793
874
  // A new settled turn (new `turn.at`) gets one bubble; the same turn never re-flashes.
@@ -840,6 +921,7 @@ window.__ModuleLoader__.load({
840
921
 
841
922
  // Expanding the card is also a request for the freshest numbers.
842
923
  useEffect(() => {
924
+ openRef.current = open;
843
925
  if (open) load();
844
926
  }, [open, load]);
845
927
 
@@ -1062,17 +1144,50 @@ window.__ModuleLoader__.load({
1062
1144
  const stale = typeof snapshot?.today === 'string' && snapshot.today !== new Date(now + 8 * 3600 * 1000).toISOString().slice(0, 10);
1063
1145
  const prices = Array.isArray(snapshot?.prices) ? snapshot.prices : [];
1064
1146
  const allHistory = Array.isArray(snapshot?.history) ? snapshot.history : [];
1065
- const history =
1066
- chartWindow === 'month'
1067
- ? (() => {
1068
- const prefix = (snapshot?.today ?? '').slice(0, 7);
1069
- return allHistory.filter((row) => row.day.startsWith(prefix));
1070
- })()
1071
- : allHistory.slice(-Number(chartWindow));
1072
- const windowTotal = history.reduce((sum, row) => sum + (row.cost ?? 0), 0);
1073
- const windowPeakCost = history.reduce((sum, row) => sum + (row.peakCost ?? 0), 0);
1074
- const windowValleyCost = history.reduce((sum, row) => sum + (row.valleyCost ?? 0), 0);
1075
- const windowModels = (() => {
1147
+ const todayWindow = chartWindow === 'today';
1148
+ // The day window defaults to today; picking an earlier day swaps the row.
1149
+ const trendDayValue = trendDay !== '' ? trendDay : (snapshot?.today ?? '');
1150
+ const trendRow = allHistory.find((row) => row.day === trendDayValue) ?? null;
1151
+ const isLiveDay = trendDayValue === (snapshot?.today ?? '');
1152
+ const history = todayWindow
1153
+ ? (trendRow === null ? [] : [trendRow])
1154
+ : chartWindow === 'month'
1155
+ ? (() => {
1156
+ const prefix = (snapshot?.today ?? '').slice(0, 7);
1157
+ return allHistory.filter((row) => row.day.startsWith(prefix));
1158
+ })()
1159
+ : allHistory.slice(-Number(chartWindow));
1160
+ // "Today" reads the live counters: the history row is written by the
1161
+ // ledger and can lag behind the current turn.
1162
+ const windowTotal = todayWindow
1163
+ ? (isLiveDay ? (snapshot?.todayUsed ?? 0) : (trendRow?.cost ?? 0))
1164
+ : history.reduce((sum, row) => sum + (row.cost ?? 0), 0);
1165
+ const windowPeakCost = todayWindow
1166
+ ? (isLiveDay ? (snapshot?.todayPeakCost ?? 0) : (trendRow?.peakCost ?? 0))
1167
+ : history.reduce((sum, row) => sum + (row.peakCost ?? 0), 0);
1168
+ const windowValleyCost = todayWindow
1169
+ ? (isLiveDay ? (snapshot?.todayValleyCost ?? 0) : (trendRow?.valleyCost ?? 0))
1170
+ : history.reduce((sum, row) => sum + (row.valleyCost ?? 0), 0);
1171
+ const windowCalls = todayWindow
1172
+ ? (isLiveDay ? (snapshot?.todayCalls ?? 0) : (trendRow?.calls ?? 0))
1173
+ : history.reduce((sum, row) => sum + (row.calls ?? 0), 0);
1174
+ const todayKey = snapshot?.today ?? '';
1175
+ // Pure calendar arithmetic in UTC: the day key is already a Beijing date,
1176
+ // so shifting it with a +08:00 timestamp would land a day early.
1177
+ const yesterdayKey =
1178
+ todayKey === '' ? '' : new Date(Date.parse(todayKey + 'T00:00:00Z') - 86400000).toISOString().slice(0, 10);
1179
+ const dayOptions = [...new Set([todayKey, ...allHistory.map((row) => row.day)])]
1180
+ .filter((day) => /^\d{4}-\d{2}-\d{2}$/.test(day) && day <= todayKey)
1181
+ .sort()
1182
+ .reverse()
1183
+ .slice(0, 7);
1184
+ // First plain date in the list: the divider goes above it only.
1185
+ const firstDatedDay = dayOptions.find((day) => day !== todayKey && day !== yesterdayKey) ?? '';
1186
+ const dayLabel = (day) =>
1187
+ day === todayKey ? t('history.window.today') : day === yesterdayKey ? t('history.yesterday') : day.slice(5);
1188
+ const windowModels = todayWindow
1189
+ ? (isLiveDay ? (Array.isArray(snapshot?.models) ? snapshot.models : []) : (trendRow?.models ?? []))
1190
+ : (() => {
1076
1191
  const table = {};
1077
1192
  for (const row of history) {
1078
1193
  for (const model of row.models ?? []) {
@@ -1083,7 +1198,6 @@ window.__ModuleLoader__.load({
1083
1198
  }
1084
1199
  return Object.values(table).sort((a, b) => b.cost - a.cost);
1085
1200
  })();
1086
- const models = Array.isArray(snapshot?.models) ? snapshot.models : [];
1087
1201
  const turn = snapshot?.turn ?? null;
1088
1202
 
1089
1203
  const liveFrame = dragRef.current !== null && liveRef.current !== null ? liveRef.current : frame;
@@ -1243,58 +1357,6 @@ window.__ModuleLoader__.load({
1243
1357
  stale ? h('div', { className: 'dbf-error', style: { marginTop: '4px' } }, t('error.stale')) : null,
1244
1358
  );
1245
1359
 
1246
- const inputTokens = typeof snapshot?.todayInput === 'number' ? snapshot.todayInput : 0;
1247
- const cacheTokens = typeof snapshot?.todayCacheRead === 'number' ? snapshot.todayCacheRead : 0;
1248
- const outputTokens = typeof snapshot?.todayOutput === 'number' ? snapshot.todayOutput : 0;
1249
- const tokenSum = inputTokens + cacheTokens + outputTokens;
1250
- const promptSum = inputTokens + cacheTokens;
1251
- const hitRate = promptSum > 0 ? (cacheTokens / promptSum) * 100 : null;
1252
- const tokenLine = (label, value) =>
1253
- h(
1254
- 'div',
1255
- { className: 'dbf-token-row' },
1256
- h('span', { className: 'dbf-sub' }, label),
1257
- h('span', { className: 'dbf-num' }, value),
1258
- );
1259
- const tokenBlock = h(
1260
- 'div',
1261
- { className: 'dbf-block' },
1262
- h(
1263
- 'div',
1264
- {
1265
- className: 'dbf-row dbf-fold-head',
1266
- role: 'button',
1267
- tabIndex: 0,
1268
- 'aria-expanded': tokensOpen ? 'true' : 'false',
1269
- onClick: () => setTokensOpen((value) => !value),
1270
- onKeyDown: (event) => {
1271
- if (event.key === 'Enter' || event.key === ' ') {
1272
- event.preventDefault();
1273
- setTokensOpen((value) => !value);
1274
- }
1275
- },
1276
- },
1277
- h(
1278
- 'span',
1279
- { className: 'dbf-row-title' },
1280
- h('span', { className: 'dbf-fold-arrow', 'aria-hidden': true }, tokensOpen ? '▾' : '▸'),
1281
- t('tokens.title'),
1282
- ),
1283
- h('span', { className: 'dbf-sub' }, tokens(tokenSum)),
1284
- ),
1285
- tokensOpen
1286
- ? h(
1287
- 'div',
1288
- null,
1289
- tokenLine(t('tokens.hit'), hitRate === null ? '—' : hitRate.toFixed(1) + '%'),
1290
- tokenLine(t('tokens.input'), tokens(inputTokens)),
1291
- tokenLine(t('tokens.cache'), tokens(cacheTokens)),
1292
- tokenLine(t('tokens.output'), tokens(outputTokens)),
1293
- tokenSum > 0 ? null : h('div', { className: 'dbf-sub', style: { marginTop: '2px' } }, t('tokens.empty')),
1294
- )
1295
- : null,
1296
- );
1297
-
1298
1360
  const peakBlock = h(
1299
1361
  'div',
1300
1362
  { className: 'dbf-block' },
@@ -1409,17 +1471,95 @@ window.__ModuleLoader__.load({
1409
1471
  h(
1410
1472
  'span',
1411
1473
  { className: 'dbf-windows' },
1412
- ['7', '30', 'month'].map((key) =>
1413
- h(
1414
- 'button',
1415
- {
1416
- key,
1417
- type: 'button',
1418
- className: 'dbf-window' + (chartWindow === key ? ' is-active' : ''),
1419
- onClick: () => setChartWindow(key),
1420
- },
1421
- t('history.window.' + key),
1422
- ),
1474
+ ['today', '7', '30', 'month'].map((key) =>
1475
+ key === 'today'
1476
+ ? h(
1477
+ 'span',
1478
+ { key, className: 'dbf-daypick' },
1479
+ h(
1480
+ 'button',
1481
+ {
1482
+ type: 'button',
1483
+ className: 'dbf-window' + (chartWindow === key ? ' is-active' : ''),
1484
+ ref: dayButtonRef,
1485
+ 'aria-haspopup': 'listbox',
1486
+ 'aria-expanded': dayMenuOpen,
1487
+ onClick: (event) => {
1488
+ // Coming from another tab only switches back to today;
1489
+ // the picker opens when this tab is already active.
1490
+ if (chartWindow !== key) {
1491
+ setChartWindow(key);
1492
+ setTrendDay('');
1493
+ setDayMenuOpen(false);
1494
+ return;
1495
+ }
1496
+ const rect = event.currentTarget.getBoundingClientRect();
1497
+ setDayMenuPos({ top: rect.bottom + 4, right: Math.max(8, window.innerWidth - rect.right) });
1498
+ setDayMenuOpen((prev) => !prev);
1499
+ },
1500
+ },
1501
+ dayLabel(trendDayValue) + ' ▾',
1502
+ ),
1503
+ dayMenuOpen
1504
+ ? buildDayMenu(h(
1505
+ 'div',
1506
+ {
1507
+ ref: dayMenuRef,
1508
+ className: 'dbf-daymenu is-floating dbf-surface',
1509
+ role: 'listbox',
1510
+ style: {
1511
+ ...(dayMenuPos === null ? {} : { top: dayMenuPos.top + 'px', right: dayMenuPos.right + 'px' }),
1512
+ // The menu lives in <body>, outside the root that
1513
+ // carries the appearance variables.
1514
+ '--dbf-bg': String((100 - appearance.bg) / 100),
1515
+ '--dbf-border': String(appearance.border / 100),
1516
+ '--dbf-shadow': String(appearance.shadow / 100),
1517
+ },
1518
+ },
1519
+ dayOptions.map((day) =>
1520
+ h(
1521
+ 'button',
1522
+ {
1523
+ key: day,
1524
+ type: 'button',
1525
+ role: 'option',
1526
+ 'aria-selected': day === trendDayValue,
1527
+ className:
1528
+ 'dbf-dayitem' +
1529
+ (day === trendDayValue ? ' is-active' : '') +
1530
+ (day === firstDatedDay ? ' is-group-start' : ''),
1531
+ onClick: () => {
1532
+ setTrendDay(day === todayKey ? '' : day);
1533
+ setChartWindow('today');
1534
+ setDayMenuOpen(false);
1535
+ },
1536
+ },
1537
+ h('span', { className: 'dbf-dayitem-label' }, dayLabel(day)),
1538
+ h(
1539
+ 'span',
1540
+ { className: 'dbf-dayitem-sub' },
1541
+ t('weekday.' + new Date(day + 'T00:00:00Z').getUTCDay()),
1542
+ ),
1543
+ day === trendDayValue ? h('span', { className: 'dbf-dayitem-check', 'aria-hidden': true }, '✓') : null,
1544
+ ),
1545
+ ),
1546
+ ))
1547
+ : null,
1548
+ )
1549
+ : h(
1550
+ 'button',
1551
+ {
1552
+ key,
1553
+ type: 'button',
1554
+ className: 'dbf-window' + (chartWindow === key ? ' is-active' : ''),
1555
+ 'aria-pressed': chartWindow === key,
1556
+ onClick: () => {
1557
+ setChartWindow(key);
1558
+ setDayMenuOpen(false);
1559
+ },
1560
+ },
1561
+ t('history.window.' + key),
1562
+ ),
1423
1563
  ),
1424
1564
  ),
1425
1565
  ),
@@ -1430,7 +1570,7 @@ window.__ModuleLoader__.load({
1430
1570
  h(
1431
1571
  'span',
1432
1572
  { className: 'dbf-trend-calls' },
1433
- t('history.calls', { calls: history.reduce((sum, row) => sum + (row.calls ?? 0), 0) }),
1573
+ t('history.calls', { calls: windowCalls }),
1434
1574
  ),
1435
1575
  ),
1436
1576
  h(
@@ -1458,36 +1598,38 @@ window.__ModuleLoader__.load({
1458
1598
  }),
1459
1599
  )
1460
1600
  : null,
1461
- h(
1462
- 'div',
1463
- { className: 'dbf-bars' },
1464
- history.map((row) => {
1465
- const value = typeof row.cost === 'number' ? row.cost : 0;
1466
- const windowMax = Math.max(...history.map((entry) => entry.cost ?? 0), 0);
1467
- const ratio = windowMax > 0 ? Math.max(2, Math.round((value / windowMax) * 38)) : 2;
1468
- const isToday = typeof snapshot?.today === 'string' && row.day === snapshot.today;
1469
- return h(
1470
- 'div',
1471
- {
1472
- key: row.day,
1473
- className: 'dbf-bar' + (isToday ? ' is-today' : ''),
1474
- role: 'button',
1475
- tabIndex: 0,
1476
- title: row.day + ' ¥' + money(value),
1477
- onClick: () => setSelectedDay(row.day),
1478
- onKeyDown: (event) => {
1479
- if (event.key === 'Enter' || event.key === ' ') {
1480
- event.preventDefault();
1481
- setSelectedDay(row.day);
1482
- }
1601
+ todayWindow
1602
+ ? null
1603
+ : h(
1604
+ 'div',
1605
+ { className: 'dbf-bars' },
1606
+ history.map((row) => {
1607
+ const value = typeof row.cost === 'number' ? row.cost : 0;
1608
+ const windowMax = Math.max(...history.map((entry) => entry.cost ?? 0), 0);
1609
+ const ratio = windowMax > 0 ? Math.max(2, Math.round((value / windowMax) * 38)) : 2;
1610
+ const isToday = typeof snapshot?.today === 'string' && row.day === snapshot.today;
1611
+ return h(
1612
+ 'div',
1613
+ {
1614
+ key: row.day,
1615
+ className: 'dbf-bar' + (isToday ? ' is-today' : ''),
1616
+ role: 'button',
1617
+ tabIndex: 0,
1618
+ title: row.day + ' ¥' + money(value),
1619
+ onClick: () => setSelectedDay(row.day),
1620
+ onKeyDown: (event) => {
1621
+ if (event.key === 'Enter' || event.key === ' ') {
1622
+ event.preventDefault();
1623
+ setSelectedDay(row.day);
1624
+ }
1625
+ },
1483
1626
  },
1484
- },
1485
- h('div', { className: 'dbf-bar-fill', style: { height: ratio + 'px' } }),
1486
- h('div', { className: 'dbf-bar-day' }, row.day.slice(8).replace(/^0/, '')),
1487
- );
1488
- }),
1489
- ),
1490
- );
1627
+ h('div', { className: 'dbf-bar-fill', style: { height: ratio + 'px' } }),
1628
+ h('div', { className: 'dbf-bar-day' }, row.day.slice(8).replace(/^0/, '')),
1629
+ );
1630
+ }),
1631
+ ),
1632
+ );
1491
1633
 
1492
1634
  const selected = selectedDay === null ? null : history.find((row) => row.day === selectedDay) ?? null;
1493
1635
  const dayBlock =
@@ -1501,7 +1643,7 @@ window.__ModuleLoader__.load({
1501
1643
  { className: 'dbf-row' },
1502
1644
  h(
1503
1645
  'button',
1504
- { type: 'button', className: 'dbf-textbtn', onClick: () => setSelectedDay(null) },
1646
+ { type: 'button', className: 'dbf-textbtn is-ghost', onClick: () => setSelectedDay(null) },
1505
1647
  t('day.back'),
1506
1648
  ),
1507
1649
  h('span', { className: 'dbf-sub' }, t('day.title')),
@@ -1612,7 +1754,7 @@ window.__ModuleLoader__.load({
1612
1754
  } else if (dayBlock !== null) {
1613
1755
  body.push(dayBlock);
1614
1756
  } else {
1615
- body.push(balanceBlock, peakBlock, tokenBlock, priceTable, historyBlock);
1757
+ body.push(balanceBlock, peakBlock, priceTable, historyBlock);
1616
1758
  }
1617
1759
 
1618
1760
  card = h(
package/index.js CHANGED
@@ -62,6 +62,7 @@ const UPDATE_TTL_MS = 5 * 60 * 1000
62
62
  // Only the published version is cached; `current` is re-read every call so a
63
63
  // locally bumped version is compared against the fresh one.
64
64
  let updateCache = { at: 0, latest: null }
65
+ let updateInFlight = null
65
66
 
66
67
  async function checkUpdate({ fresh = false } = {}) {
67
68
  const now = Date.now()
@@ -69,23 +70,33 @@ async function checkUpdate({ fresh = false } = {}) {
69
70
  if (!fresh && updateCache.latest !== null && now - updateCache.at < UPDATE_TTL_MS) {
70
71
  return { ok: true, current, latest: updateCache.latest, hasUpdate: isNewer(updateCache.latest, current) }
71
72
  }
72
- const controller = new AbortController()
73
- const timer = setTimeout(() => controller.abort(), 10000)
73
+ // Collapse concurrent calls (several tabs, or a card opened twice).
74
+ if (updateInFlight !== null) return updateInFlight
75
+ const request = (async () => {
76
+ const controller = new AbortController()
77
+ const timer = setTimeout(() => controller.abort(), 10000)
78
+ try {
79
+ const response = await fetch('https://registry.npmjs.org/@lls-a1/dsh-balance-float/latest', {
80
+ signal: controller.signal,
81
+ headers: { accept: 'application/json', 'user-agent': 'dsh-balance-float' },
82
+ })
83
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
84
+ const pkg = JSON.parse(await response.text())
85
+ const latest = typeof pkg?.version === 'string' ? pkg.version : ''
86
+ if (latest !== '') updateCache = { at: Date.now(), latest }
87
+ return { ok: true, current, latest, hasUpdate: latest !== '' && isNewer(latest, current) }
88
+ } catch (error) {
89
+ // Do not cache failures: the next check retries.
90
+ return { ok: false, current, latest: '', hasUpdate: false, error: error instanceof Error ? error.message : String(error) }
91
+ } finally {
92
+ clearTimeout(timer)
93
+ }
94
+ })()
95
+ updateInFlight = request
74
96
  try {
75
- const response = await fetch('https://registry.npmjs.org/@lls-a1/dsh-balance-float/latest', {
76
- signal: controller.signal,
77
- headers: { accept: 'application/json', 'user-agent': 'dsh-balance-float' },
78
- })
79
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
80
- const pkg = JSON.parse(await response.text())
81
- const latest = typeof pkg?.version === 'string' ? pkg.version : ''
82
- if (latest !== '') updateCache = { at: now, latest }
83
- return { ok: true, current, latest, hasUpdate: latest !== '' && isNewer(latest, current) }
84
- } catch (error) {
85
- // Do not cache failures: the next check retries.
86
- return { ok: false, current, latest: '', hasUpdate: false, error: error instanceof Error ? error.message : String(error) }
97
+ return await request
87
98
  } finally {
88
- clearTimeout(timer)
99
+ updateInFlight = null
89
100
  }
90
101
  }
91
102
 
@@ -228,12 +239,15 @@ export function apply(ctx, config) {
228
239
  return
229
240
  }
230
241
  try {
242
+ const daysParam = new URL(req.url ?? '/', 'http://localhost').searchParams.get('days')
243
+ const requested = daysParam === null ? Number.NaN : Number(daysParam)
231
244
  const snapshot = buildSnapshot({
232
245
  ledger: tracker.state,
233
246
  sourcePath: paths.store,
234
247
  mtimeMs: tracker.lastSavedAt > 0 ? tracker.lastSavedAt : seededAt,
235
248
  serverNow: Date.now(),
236
249
  version: packageVersion(),
250
+ days: Number.isFinite(requested) ? requested : 31,
237
251
  })
238
252
  respondJson(res, 200, snapshot)
239
253
  } catch (error) {
package/lib/ledger.js CHANGED
@@ -14,8 +14,8 @@ import os from 'node:os'
14
14
  import path from 'node:path'
15
15
  import { LEGACY_UNIT, beijingDay } from './pricing.js'
16
16
 
17
- /** Keep the ledger bounded; the widget only shows the last 7 days anyway. */
18
- const MAX_EVENTS = 1200
17
+ /** Keep the ledger bounded; older events only feed the daily totals. */
18
+ export const MAX_EVENTS = 1200
19
19
 
20
20
  /** DSH home, with the documented fallback when the env var is absent. */
21
21
  function dshHome() {
@@ -168,8 +168,10 @@ export function loadState(config, now = Date.now()) {
168
168
  export function saveState(file, state) {
169
169
  try {
170
170
  fs.mkdirSync(path.dirname(file), { recursive: true })
171
- state.updatedAt = new Date().toISOString()
172
- const text = JSON.stringify(state)
171
+ // Persist a shallow copy: saving must not mutate the caller's object, and
172
+ // `updatedAt` belongs to the file, not to the in-memory ledger.
173
+ const snapshot = { ...state, updatedAt: new Date().toISOString() }
174
+ const text = JSON.stringify(snapshot)
173
175
  const temp = file + '.tmp-' + process.pid
174
176
  fs.writeFileSync(temp, text, 'utf8')
175
177
  fs.renameSync(temp, file)
package/lib/snapshot.js CHANGED
@@ -112,7 +112,7 @@ function lastTurn(events) {
112
112
  * @param options.serverNow - epoch milliseconds, injectable for tests.
113
113
  * @returns JSON-serializable snapshot.
114
114
  */
115
- export function buildSnapshot({ ledger, sourcePath, mtimeMs, serverNow = Date.now(), version = '' } = {}) {
115
+ export function buildSnapshot({ ledger, sourcePath, mtimeMs, serverNow = Date.now(), version = '', days = 31 } = {}) {
116
116
  const nowSec = Math.floor(serverNow / 1000)
117
117
  const peakActive = isPeak(nowSec)
118
118
  const nextChange = nextPeakChange(nowSec)
@@ -142,13 +142,16 @@ export function buildSnapshot({ ledger, sourcePath, mtimeMs, serverNow = Date.no
142
142
  },
143
143
  }
144
144
 
145
- const days = Object.keys(history)
145
+ // 31 keeps a whole calendar month (some months have 31 days); `days = 0`
146
+ // asks for a light snapshot that carries no day rows at all.
147
+ const dayKeys = Object.keys(history)
146
148
  .filter((day) => /^\d{4}-\d{2}-\d{2}$/.test(day))
147
149
  .sort()
148
- .slice(-30)
150
+ const window = Number.isFinite(days) ? Math.max(0, Math.min(31, Math.floor(days))) : 31
151
+ const kept = window === 0 ? [] : dayKeys.slice(-window)
149
152
  // Each bar carries its own breakdown (folded from the stored events); old
150
153
  // days whose events rolled out of MAX_EVENTS fall back to the stored total.
151
- const recent = days.map((day) => {
154
+ const recent = kept.map((day) => {
152
155
  const detail = todayBreakdown(events, day)
153
156
  const fromEvents = money((detail.peakCost ?? 0) + (detail.valleyCost ?? 0)) ?? 0
154
157
  const stored = money(numberOr(history[day], 0)) ?? 0
package/lib/tracker.js CHANGED
@@ -9,10 +9,7 @@
9
9
  * - persists on a short debounce so a busy turn does not rewrite per message.
10
10
  */
11
11
  import { beijingDay, costOf } from './pricing.js'
12
- import { saveState } from './ledger.js'
13
-
14
- /** Ledger cap; older events only feed the 7-day chart. */
15
- const MAX_EVENTS = 1200
12
+ import { MAX_EVENTS, saveState } from './ledger.js'
16
13
 
17
14
  /** Round to the ledger's 1e-6 CNY resolution. */
18
15
  function round(value) {
@@ -43,7 +40,7 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
43
40
  function scheduleSave() {
44
41
  dirty = true
45
42
  if (saveTimer !== null) return
46
- saveTimer = setTimeout(flush, 700)
43
+ saveTimer = setTimeout(flush, 1200)
47
44
  if (typeof saveTimer.unref === 'function') saveTimer.unref()
48
45
  }
49
46
 
@@ -58,11 +55,11 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
58
55
  state.history[today] = 0
59
56
  }
60
57
 
61
- /** Sum of today's appended events. */
62
- function eventsTodaySum() {
58
+ /** Sum of the appended events that belong to one day. */
59
+ function eventsDaySum(day) {
63
60
  let sum = 0
64
61
  for (const event of state.events) {
65
- if (event && event.day === state.date) sum += Number(event.cost) || 0
62
+ if (event && event.day === day) sum += Number(event.cost) || 0
66
63
  }
67
64
  return sum
68
65
  }
@@ -94,8 +91,11 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
94
91
  }
95
92
  if (total <= 0) return
96
93
  if (state.events.length > MAX_EVENTS) state.events = state.events.slice(-MAX_EVENTS)
97
- if (day === state.date) state.todayUsage = round(Math.max(state.todayUsage, eventsTodaySum()))
98
- state.history[day] = round(Math.max(Number(state.history[day]) || 0, state.todayUsage))
94
+ // A turn that settles after midnight belongs to its own day: never mix in
95
+ // the current day's running total.
96
+ const dayTotal = eventsDaySum(day)
97
+ state.history[day] = round(Math.max(Number(state.history[day]) || 0, dayTotal))
98
+ if (day === state.date) state.todayUsage = round(Math.max(state.todayUsage, dayTotal))
99
99
  state.updatedAt = new Date(now).toISOString()
100
100
  scheduleSave()
101
101
  onTurn?.(total, tokens)
@@ -108,6 +108,21 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
108
108
  settle(agg, now)
109
109
  }
110
110
 
111
+ /**
112
+ * Epoch seconds of one event: the message's own clock when present, so a
113
+ * reply that streams across a peak/valley edge is still priced correctly.
114
+ *
115
+ * @param event - session event (`time` is epoch ms per the session format).
116
+ */
117
+ function messageSec(event) {
118
+ const candidates = [event?.data?.message?.createdAt, event?.time]
119
+ for (const value of candidates) {
120
+ const n = Number(value)
121
+ if (Number.isFinite(n) && n > 0) return Math.floor(n > 1e12 ? n / 1000 : n)
122
+ }
123
+ return Math.floor(Date.now() / 1000)
124
+ }
125
+
111
126
  /**
112
127
  * Fold one session event.
113
128
  *
@@ -133,7 +148,7 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
133
148
  }
134
149
  const model = String(data.message?.source?.model || 'unknown')
135
150
  const usage = data.usage
136
- const cost = costOf(model, usage, Math.floor(Date.now() / 1000))
151
+ const cost = costOf(model, usage, messageSec(event))
137
152
  agg.byModel[model] = (agg.byModel[model] || 0) + cost
138
153
  agg.byModelTokens[model] =
139
154
  (agg.byModelTokens[model] || 0) +
@@ -144,7 +159,9 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
144
159
  buckets.input += Number(usage.inputTokens) || 0
145
160
  buckets.cacheRead += Number(usage.cacheReadTokens) || 0
146
161
  buckets.output += Number(usage.outputTokens) || 0
147
- agg.lastTs = Date.now()
162
+ // The turn belongs to the day of its last message: a request that finishes
163
+ // after midnight must not be booked into the new day.
164
+ agg.lastTs = messageSec(event) * 1000
148
165
  }
149
166
 
150
167
  /**
@@ -157,6 +174,7 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
157
174
  function applyBalance(balance, source = 'apikey', now = Date.now()) {
158
175
  const value = Number(balance)
159
176
  if (!Number.isFinite(value)) return false
177
+ const before = { date: state.date, dayStart: state.dayStart, last: state.lastBalance, usage: state.todayUsage }
160
178
  rollover(now)
161
179
  if (state.dayStart === null) state.dayStart = value
162
180
  state.lastBalance = round(value)
@@ -173,8 +191,16 @@ export function createTracker({ state, storePath, onTurn, logger } = {}) {
173
191
  state.dayStart = value
174
192
  }
175
193
  state.history[state.date] = round(state.todayUsage)
176
- state.updatedAt = new Date(now).toISOString()
177
- scheduleSave()
194
+ // A poll that changed nothing must not rewrite the whole ledger file.
195
+ const changed =
196
+ before.date !== state.date ||
197
+ before.dayStart !== state.dayStart ||
198
+ before.last !== state.lastBalance ||
199
+ before.usage !== state.todayUsage
200
+ if (changed) {
201
+ state.updatedAt = new Date(now).toISOString()
202
+ scheduleSave()
203
+ }
178
204
  return true
179
205
  }
180
206
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lls-a1/dsh-balance-float",
3
- "version": "1.1.55",
3
+ "version": "1.2.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -48,5 +48,8 @@
48
48
  "platform": "web",
49
49
  "immediately": true
50
50
  }
51
+ },
52
+ "scripts": {
53
+ "test": "node --test \"test/*.test.js\""
51
54
  }
52
55
  }