@lls-a1/dsh-balance-float 1.1.56 → 1.2.1

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,17 +31,15 @@ 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.
38
37
  const TOPUP_URL = 'https://platform.deepseek.com/top_up';
39
38
  const APPEARANCE_KEY = 'dsh.balance-float.appearance';
40
- // `bg` is transparency in percent (0 = solid token background), the other
41
- // two are strength in percent.
42
- // 16 is the pill's half height: the default keeps the capsule look while the
43
- // card gets a matching 16px corner.
44
- const DEFAULT_APPEARANCE = { bg: 0, border: 100, shadow: 100, radius: 16, dockBall: true };
39
+ // `bg` is transparency in percent (0 = solid token background) and `shadow`
40
+ // is strength in percent; `radius` is the corner in px. Defaults are the
41
+ // flat look: no transparency, no shadow, a 5px corner.
42
+ const DEFAULT_APPEARANCE = { bg: 0, shadow: 0, radius: 5, dockBall: true };
45
43
  // Docking: a drop this close to a side edge turns the pill into a square
46
44
  // ball pinned DOCK_MARGIN px from that edge.
47
45
  const DOCK_ZONE = 56;
@@ -77,13 +75,11 @@ window.__ModuleLoader__.load({
77
75
  'peak.label': '峰价',
78
76
  valley: '谷价',
79
77
  'schedule.title': '峰谷计费时段',
80
- 'tokens.title': 'Token 用量',
81
78
  'tokens.input': '未缓存输入',
82
79
  'tokens.cache': '缓存读取',
83
80
  'tokens.output': '输出',
84
81
  'tokens.total': '合计',
85
82
  'tokens.hit': '缓存命中',
86
- 'tokens.empty': '分项从本版本开始记录,历史事件只有合计',
87
83
  'day.back': '← 返回',
88
84
  'day.title': '当日明细',
89
85
  'day.calls': '{count} 次调用 · {tokens} tokens',
@@ -110,6 +106,7 @@ window.__ModuleLoader__.load({
110
106
  'price.out': '输出',
111
107
  history: '用量趋势',
112
108
  'history.window.today': '今天',
109
+ 'history.yesterday': '昨天',
113
110
  'history.window.7': '近7天',
114
111
  'history.window.30': '近30天',
115
112
  'history.window.month': '本月',
@@ -136,7 +133,6 @@ window.__ModuleLoader__.load({
136
133
  settings: '外观设置',
137
134
  'settings.open': '外观设置',
138
135
  'settings.bg': '背景透明度',
139
- 'settings.border': '边框',
140
136
  'settings.shadow': '阴影',
141
137
  'settings.radius': '圆角',
142
138
  'settings.dock': '贴边收成小球',
@@ -172,13 +168,11 @@ window.__ModuleLoader__.load({
172
168
  'peak.label': 'Peak',
173
169
  valley: 'Off-peak',
174
170
  'schedule.title': 'Peak and off-peak windows',
175
- 'tokens.title': 'Token usage',
176
171
  'tokens.input': 'Uncached input',
177
172
  'tokens.cache': 'Cache read',
178
173
  'tokens.output': 'Output',
179
174
  'tokens.total': 'Total',
180
175
  'tokens.hit': 'Cache hit',
181
- 'tokens.empty': 'Buckets are recorded from this version on; older events only carry the total',
182
176
  'day.back': '← Back',
183
177
  'day.title': 'Day detail',
184
178
  'day.calls': '{count} calls · {tokens} tokens',
@@ -205,6 +199,7 @@ window.__ModuleLoader__.load({
205
199
  'price.out': 'Out',
206
200
  history: 'Usage trend',
207
201
  'history.window.today': 'Today',
202
+ 'history.yesterday': 'Yesterday',
208
203
  'history.window.7': '7d',
209
204
  'history.window.30': '30d',
210
205
  'history.window.month': 'Month',
@@ -231,7 +226,6 @@ window.__ModuleLoader__.load({
231
226
  settings: 'Appearance',
232
227
  'settings.open': 'Appearance',
233
228
  'settings.bg': 'Background transparency',
234
- 'settings.border': 'Border',
235
229
  'settings.shadow': 'Shadow',
236
230
  'settings.radius': 'Corner radius',
237
231
  'settings.dock': 'Ball at the edge',
@@ -250,7 +244,7 @@ window.__ModuleLoader__.load({
250
244
  '.dbf-root{position:fixed;z-index:200;pointer-events:auto;font-family:inherit;color:var(--dsw-alias-label-primary)}',
251
245
  '.dbf-surface{position:relative;isolation:isolate}',
252
246
  '.dbf-surface::before{content:"";position:absolute;inset:0;border-radius:inherit;background:var(--dsw-alias-bg-overlay);opacity:var(--dbf-bg,1);z-index:-1;pointer-events:none}',
253
- '.dbf-surface::after{content:"";position:absolute;inset:0;border-radius:inherit;border:.5px solid var(--dsw-alias-border-l1);opacity:var(--dbf-border,1);pointer-events:none}',
247
+ '.dbf-surface::after{content:"";position:absolute;inset:0;border-radius:inherit;border:.5px solid var(--dsw-alias-border-l1);pointer-events:none}',
254
248
  '@keyframes dbf-open-down{from{opacity:0;transform:translateY(-14px)}to{opacity:1;transform:translateY(0)}}',
255
249
  '@keyframes dbf-open-up{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}',
256
250
  '@keyframes dbf-collapse-down{to{opacity:0;transform:translateY(-14px)}}',
@@ -268,14 +262,14 @@ window.__ModuleLoader__.load({
268
262
  '.dbf-dot{width:7px;height:7px;border-radius:50%;flex:0 0 auto}',
269
263
  '.dbf-dot.is-peak{background:var(--dsw-alias-state-error-primary)}',
270
264
  '.dbf-dot.is-valley{background:var(--dsw-alias-state-success-primary)}',
271
- '.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)}',
265
+ '.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)}',
272
266
  '.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}',
273
267
  '.dbf-dir-up .dbf-card{animation-name:dbf-open-up}',
274
268
  '.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}',
275
269
  '.dbf-head.is-static{cursor:default}',
276
270
  '.dbf-head:active{cursor:grabbing}',
277
271
  '.dbf-head-title{flex:1;min-width:0;font-weight:600}',
278
- '.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}',
272
+ '.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}',
279
273
  '.dbf-icon svg{display:block}',
280
274
  '.dbf-icon:disabled{cursor:default;opacity:.6}',
281
275
  '.dbf-spinning svg{animation:dbf-spin .9s linear infinite}',
@@ -298,24 +292,21 @@ window.__ModuleLoader__.load({
298
292
  '.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}',
299
293
  '.dbf-switch.is-on .dbf-switch-knob{background:#fff}',
300
294
  '.dbf-switch.is-on .dbf-switch-knob{transform:translateX(14px)}',
301
- '.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}',
295
+ '.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}',
302
296
  '.dbf-topup:hover{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
303
297
  '.dbf-topup:active{transform:translateY(.5px)}',
304
298
  '.dbf-countdown{margin-top:8px;margin-bottom:4px;font-size:15px;line-height:22px;letter-spacing:.01em}',
305
- '.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}',
299
+ '.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}',
306
300
  '.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)}',
307
301
  '.dbf-version-glyph{font-size:10px;opacity:.75}',
308
302
  '.dbf-version.has-update{color:var(--dsw-alias-state-error-primary)}',
309
303
  '.dbf-version.has-update .dbf-version-glyph{opacity:1}',
310
- '.dbf-fold-head{cursor:pointer;user-select:none}',
311
- '.dbf-fold-arrow{display:inline-block;width:10px;margin-right:3px;color:var(--dsw-alias-label-tertiary);font-size:9px}',
312
- '.dbf-fold-head:hover .dbf-row-title{color:var(--dsw-alias-label-primary)}',
313
304
  '.dbf-token-row{display:flex;align-items:baseline;justify-content:space-between;gap:8px;padding:1px 0}',
314
305
  '.dbf-models{display:flex;flex-direction:column;gap:2px;margin-top:6px}',
315
306
  '.dbf-model-row{display:flex;align-items:baseline;gap:8px}',
316
307
  '.dbf-model-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}',
317
308
  '.dbf-bar{cursor:pointer}',
318
- '.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}',
309
+ '.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}',
319
310
  '.dbf-help:hover,.dbf-help.is-open{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
320
311
  '.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}',
321
312
  '.dbf-rules{margin-top:4px;display:flex;flex-direction:column;gap:2px}',
@@ -340,7 +331,17 @@ window.__ModuleLoader__.load({
340
331
  '.dbf-valley{color:var(--dsw-alias-state-success-primary)}',
341
332
  '.dbf-badge.dbf-peak{border-color:currentColor}',
342
333
  '.dbf-badge.dbf-valley{border-color:currentColor}',
343
- '.dbf-windows{display:inline-flex;gap:2px}',
334
+ '.dbf-windows{display:inline-flex;gap:2px;align-items:center}',
335
+ '.dbf-daypick{position:relative;display:inline-flex}',
336
+ '.dbf-daymenu.is-floating{position:fixed;margin-top:0;z-index:2147483000}',
337
+ '.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}',
338
+ '.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}',
339
+ '.dbf-dayitem:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 8%,transparent)}',
340
+ '.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}',
341
+ '.dbf-dayitem.is-group-start{margin-top:3px;border-top:1px solid var(--dsw-alias-border-l1);padding-top:7px}',
342
+ '.dbf-dayitem-label{flex:1 1 auto}',
343
+ '.dbf-dayitem-sub{flex:none;font-size:10.5px;font-weight:400;color:var(--dsw-alias-label-secondary);opacity:.85}',
344
+ '.dbf-dayitem-check{flex:none;font-size:11px}',
344
345
  '.dbf-models-window{margin-top:6px}',
345
346
  '.dbf-mrow{display:flex;align-items:center;gap:6px;font-size:11px;line-height:16px}',
346
347
  '.dbf-mname{min-width:66px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
@@ -348,7 +349,7 @@ window.__ModuleLoader__.load({
348
349
  '.dbf-mbar{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-brand-primary,#4d6bfe);opacity:.75}',
349
350
  '.dbf-mcost{font-variant-numeric:tabular-nums}',
350
351
  '.dbf-mshare{min-width:30px;text-align:right;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}',
351
- '.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}',
352
+ '.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}',
352
353
  '.dbf-window:hover{color:var(--dsw-alias-label-primary)}',
353
354
  '.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}',
354
355
  '.dbf-trend-meta{display:flex;align-items:baseline;gap:8px;margin-top:5px}',
@@ -384,8 +385,11 @@ window.__ModuleLoader__.load({
384
385
  '.dbf-track-fill{position:absolute;left:0;top:50%;height:4px;transform:translateY(-50%);border-radius:2px;background:var(--dsw-alias-brand-primary,#4d6bfe)}',
385
386
  '.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)))}',
386
387
  '.dbf-setting-val{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}',
387
- '.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}',
388
+ '.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}',
388
389
  '.dbf-textbtn:hover{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}',
390
+ '.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}',
391
+ '.dbf-textbtn.is-ghost:hover{background:transparent;color:var(--dsw-alias-label-primary)}',
392
+ '.dbf-textbtn.is-ghost:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:2px}',
389
393
  '.dbf-error{color:var(--dsw-alias-state-error-primary)}',
390
394
  '.dbf-skel{color:var(--dsw-alias-label-secondary)}',
391
395
  ].join('');
@@ -527,7 +531,6 @@ window.__ModuleLoader__.load({
527
531
  };
528
532
  return {
529
533
  bg: pick(parsed?.bg, 0, 90, DEFAULT_APPEARANCE.bg),
530
- border: pick(parsed?.border, 0, 100, DEFAULT_APPEARANCE.border),
531
534
  shadow: pick(parsed?.shadow, 0, 100, DEFAULT_APPEARANCE.shadow),
532
535
  radius: pick(parsed?.radius, 0, 20, DEFAULT_APPEARANCE.radius),
533
536
  dockBall: parsed?.dockBall !== false,
@@ -594,6 +597,8 @@ window.__ModuleLoader__.load({
594
597
  function BalanceFloat(props) {
595
598
  const t = props.t;
596
599
  const openPluginPage = typeof props.openPluginPage === 'function' ? props.openPluginPage : () => {};
600
+ const buildDayMenu = (node) =>
601
+ createPortal !== null && typeof document !== 'undefined' ? createPortal(node, document.body) : node;
597
602
  const [snapshot, setSnapshot] = useState(null);
598
603
  const [failure, setFailure] = useState('');
599
604
  const [busy, setBusy] = useState(false);
@@ -618,13 +623,66 @@ window.__ModuleLoader__.load({
618
623
  const [hintOpen, setHintOpen] = useState(false);
619
624
  // A bar of the chart opens that day's detail view; the chart shows today,
620
625
  // 7 or 30 days, or the current month depending on the chosen window.
621
- const [selectedDay, setSelectedDay] = useState(null);
622
626
  const [chartWindow, setChartWindow] = useState('today');
627
+ // Clicking a bar opens that day's detail panel.
628
+ const [selectedDay, setSelectedDay] = useState(null);
629
+ // In the day window the user can step back to earlier days via the picker.
630
+ const [trendDay, setTrendDay] = useState('');
631
+ const [dayMenuOpen, setDayMenuOpen] = useState(false);
632
+ // The card body scrolls, so the menu is rendered into <body> and placed
633
+ // next to the button; an in-flow absolute menu would be clipped.
634
+ const [dayMenuPos, setDayMenuPos] = useState(null);
635
+ const dayButtonRef = useRef(null);
636
+ const dayMenuRef = useRef(null);
623
637
  // Token buckets are collapsed until asked for.
624
- const [tokensOpen, setTokensOpen] = useState(false);
625
638
  // Auto check: null | {phase, latest, current, hasUpdate}
626
639
  const [update, setUpdate] = useState(null);
627
640
  const updateCheckedAt = useRef(0);
641
+ // A new day invalidates a picked "yesterday": fall back to today.
642
+ const todayKeyRef = useRef('');
643
+ useEffect(() => {
644
+ const key = snapshot?.today ?? '';
645
+ if (key === '') return;
646
+ if (todayKeyRef.current !== '' && todayKeyRef.current !== key) setTrendDay('');
647
+ todayKeyRef.current = key;
648
+ }, [snapshot?.today]);
649
+
650
+ // The menu is fixed-positioned, so scroll/resize would leave it behind.
651
+ useEffect(() => {
652
+ if (!dayMenuOpen) return undefined;
653
+ const closeOnResize = () => setDayMenuOpen(false);
654
+ // Scrolling the menu itself must not close it; only scrolls of the
655
+ // page behind it would leave the fixed menu behind.
656
+ const closeOnScroll = (event) => {
657
+ if (dayMenuRef.current?.contains(event.target)) return;
658
+ setDayMenuOpen(false);
659
+ };
660
+ window.addEventListener('resize', closeOnResize);
661
+ window.addEventListener('scroll', closeOnScroll, true);
662
+ return () => {
663
+ window.removeEventListener('resize', closeOnResize);
664
+ window.removeEventListener('scroll', closeOnScroll, true);
665
+ };
666
+ }, [dayMenuOpen]);
667
+
668
+ useEffect(() => {
669
+ if (!dayMenuOpen) return undefined;
670
+ const onDown = (event) => {
671
+ if (dayMenuRef.current?.contains(event.target)) return;
672
+ if (dayButtonRef.current?.contains(event.target)) return;
673
+ setDayMenuOpen(false);
674
+ };
675
+ const onKey = (event) => {
676
+ if (event.key === 'Escape') setDayMenuOpen(false);
677
+ };
678
+ window.addEventListener('pointerdown', onDown, true);
679
+ window.addEventListener('keydown', onKey, true);
680
+ return () => {
681
+ window.removeEventListener('pointerdown', onDown, true);
682
+ window.removeEventListener('keydown', onKey, true);
683
+ };
684
+ }, [dayMenuOpen]);
685
+
628
686
  const flashAtRef = useRef(null);
629
687
  const flashTimerRef = useRef(null);
630
688
  const leaveTimerRef = useRef(null);
@@ -737,7 +795,6 @@ window.__ModuleLoader__.load({
737
795
  setLeaving(true);
738
796
  setHintOpen(false);
739
797
  setSelectedDay(null);
740
- setTokensOpen(false);
741
798
  leaveTimerRef.current = window.setTimeout(() => {
742
799
  leaveTimerRef.current = null;
743
800
  setLeaving(false);
@@ -771,6 +828,8 @@ window.__ModuleLoader__.load({
771
828
  void checkUpdate();
772
829
  }, [open, snapshot?.version, checkUpdate]);
773
830
 
831
+ const loadSeq = useRef(0);
832
+ const openRef = useRef(false);
774
833
  const load = useCallback(async (manual) => {
775
834
  // Hold the spinner for at least one full turn: a local read returns in
776
835
  // a few milliseconds, which otherwise looks like nothing happened.
@@ -784,12 +843,28 @@ window.__ModuleLoader__.load({
784
843
  setBusy(true);
785
844
  setRefreshState('refreshing');
786
845
  }
846
+ // Only the newest request may write state: a slow poll that lands after
847
+ // a fresh refresh must not overwrite it.
848
+ const seq = (loadSeq.current += 1);
787
849
  try {
788
- const response = await fetch(ROUTE, { headers: { accept: 'application/json' }, cache: 'no-store' });
850
+ // The closed pill never draws the history rows, so skip them.
851
+ const light = !openRef.current;
852
+ const url = light ? ROUTE + '?days=0' : ROUTE;
853
+ const response = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' });
789
854
  const body = await response.json();
790
- if (!aliveRef.current) return;
855
+ if (!aliveRef.current || seq !== loadSeq.current) return;
791
856
  if (!response.ok) throw new Error(typeof body?.error === 'string' && body.error !== '' ? body.error : 'HTTP ' + response.status);
792
- setSnapshot(body);
857
+ if (light) {
858
+ // Keep the last full day rows: the card can open before the next
859
+ // full poll lands, and rendering zeros in between reads as a bug.
860
+ setSnapshot((previous) => ({
861
+ ...body,
862
+ history: Array.isArray(previous?.history) ? previous.history : [],
863
+ historyTotal: previous?.historyTotal ?? 0,
864
+ }));
865
+ } else {
866
+ setSnapshot(body);
867
+ }
793
868
  setOffset(typeof body?.serverNow === 'number' ? body.serverNow - Date.now() : 0);
794
869
  setFailure('');
795
870
  // A new settled turn (new `turn.at`) gets one bubble; the same turn never re-flashes.
@@ -842,6 +917,7 @@ window.__ModuleLoader__.load({
842
917
 
843
918
  // Expanding the card is also a request for the freshest numbers.
844
919
  useEffect(() => {
920
+ openRef.current = open;
845
921
  if (open) load();
846
922
  }, [open, load]);
847
923
 
@@ -1065,8 +1141,12 @@ window.__ModuleLoader__.load({
1065
1141
  const prices = Array.isArray(snapshot?.prices) ? snapshot.prices : [];
1066
1142
  const allHistory = Array.isArray(snapshot?.history) ? snapshot.history : [];
1067
1143
  const todayWindow = chartWindow === 'today';
1144
+ // The day window defaults to today; picking an earlier day swaps the row.
1145
+ const trendDayValue = trendDay !== '' ? trendDay : (snapshot?.today ?? '');
1146
+ const trendRow = allHistory.find((row) => row.day === trendDayValue) ?? null;
1147
+ const isLiveDay = trendDayValue === (snapshot?.today ?? '');
1068
1148
  const history = todayWindow
1069
- ? allHistory.filter((row) => row.day === snapshot?.today)
1149
+ ? (trendRow === null ? [] : [trendRow])
1070
1150
  : chartWindow === 'month'
1071
1151
  ? (() => {
1072
1152
  const prefix = (snapshot?.today ?? '').slice(0, 7);
@@ -1076,19 +1156,33 @@ window.__ModuleLoader__.load({
1076
1156
  // "Today" reads the live counters: the history row is written by the
1077
1157
  // ledger and can lag behind the current turn.
1078
1158
  const windowTotal = todayWindow
1079
- ? (snapshot?.todayUsed ?? 0)
1159
+ ? (isLiveDay ? (snapshot?.todayUsed ?? 0) : (trendRow?.cost ?? 0))
1080
1160
  : history.reduce((sum, row) => sum + (row.cost ?? 0), 0);
1081
1161
  const windowPeakCost = todayWindow
1082
- ? (snapshot?.todayPeakCost ?? 0)
1162
+ ? (isLiveDay ? (snapshot?.todayPeakCost ?? 0) : (trendRow?.peakCost ?? 0))
1083
1163
  : history.reduce((sum, row) => sum + (row.peakCost ?? 0), 0);
1084
1164
  const windowValleyCost = todayWindow
1085
- ? (snapshot?.todayValleyCost ?? 0)
1165
+ ? (isLiveDay ? (snapshot?.todayValleyCost ?? 0) : (trendRow?.valleyCost ?? 0))
1086
1166
  : history.reduce((sum, row) => sum + (row.valleyCost ?? 0), 0);
1087
1167
  const windowCalls = todayWindow
1088
- ? (snapshot?.todayCalls ?? 0)
1168
+ ? (isLiveDay ? (snapshot?.todayCalls ?? 0) : (trendRow?.calls ?? 0))
1089
1169
  : history.reduce((sum, row) => sum + (row.calls ?? 0), 0);
1170
+ const todayKey = snapshot?.today ?? '';
1171
+ // Pure calendar arithmetic in UTC: the day key is already a Beijing date,
1172
+ // so shifting it with a +08:00 timestamp would land a day early.
1173
+ const yesterdayKey =
1174
+ todayKey === '' ? '' : new Date(Date.parse(todayKey + 'T00:00:00Z') - 86400000).toISOString().slice(0, 10);
1175
+ const dayOptions = [...new Set([todayKey, ...allHistory.map((row) => row.day)])]
1176
+ .filter((day) => /^\d{4}-\d{2}-\d{2}$/.test(day) && day <= todayKey)
1177
+ .sort()
1178
+ .reverse()
1179
+ .slice(0, 7);
1180
+ // First plain date in the list: the divider goes above it only.
1181
+ const firstDatedDay = dayOptions.find((day) => day !== todayKey && day !== yesterdayKey) ?? '';
1182
+ const dayLabel = (day) =>
1183
+ day === todayKey ? t('history.window.today') : day === yesterdayKey ? t('history.yesterday') : day.slice(5);
1090
1184
  const windowModels = todayWindow
1091
- ? (Array.isArray(snapshot?.models) ? snapshot.models : [])
1185
+ ? (isLiveDay ? (Array.isArray(snapshot?.models) ? snapshot.models : []) : (trendRow?.models ?? []))
1092
1186
  : (() => {
1093
1187
  const table = {};
1094
1188
  for (const row of history) {
@@ -1100,7 +1194,6 @@ window.__ModuleLoader__.load({
1100
1194
  }
1101
1195
  return Object.values(table).sort((a, b) => b.cost - a.cost);
1102
1196
  })();
1103
- const models = Array.isArray(snapshot?.models) ? snapshot.models : [];
1104
1197
  const turn = snapshot?.turn ?? null;
1105
1198
 
1106
1199
  const liveFrame = dragRef.current !== null && liveRef.current !== null ? liveRef.current : frame;
@@ -1115,7 +1208,6 @@ window.__ModuleLoader__.load({
1115
1208
  ...style,
1116
1209
  '--dbf-origin': dir === 'down' ? '50% 0%' : '50% 100%',
1117
1210
  '--dbf-bg': String((100 - appearance.bg) / 100),
1118
- '--dbf-border': String(appearance.border / 100),
1119
1211
  '--dbf-shadow': String(appearance.shadow / 100),
1120
1212
  '--dbf-radius': String(appearance.radius),
1121
1213
  };
@@ -1260,58 +1352,6 @@ window.__ModuleLoader__.load({
1260
1352
  stale ? h('div', { className: 'dbf-error', style: { marginTop: '4px' } }, t('error.stale')) : null,
1261
1353
  );
1262
1354
 
1263
- const inputTokens = typeof snapshot?.todayInput === 'number' ? snapshot.todayInput : 0;
1264
- const cacheTokens = typeof snapshot?.todayCacheRead === 'number' ? snapshot.todayCacheRead : 0;
1265
- const outputTokens = typeof snapshot?.todayOutput === 'number' ? snapshot.todayOutput : 0;
1266
- const tokenSum = inputTokens + cacheTokens + outputTokens;
1267
- const promptSum = inputTokens + cacheTokens;
1268
- const hitRate = promptSum > 0 ? (cacheTokens / promptSum) * 100 : null;
1269
- const tokenLine = (label, value) =>
1270
- h(
1271
- 'div',
1272
- { className: 'dbf-token-row' },
1273
- h('span', { className: 'dbf-sub' }, label),
1274
- h('span', { className: 'dbf-num' }, value),
1275
- );
1276
- const tokenBlock = h(
1277
- 'div',
1278
- { className: 'dbf-block' },
1279
- h(
1280
- 'div',
1281
- {
1282
- className: 'dbf-row dbf-fold-head',
1283
- role: 'button',
1284
- tabIndex: 0,
1285
- 'aria-expanded': tokensOpen ? 'true' : 'false',
1286
- onClick: () => setTokensOpen((value) => !value),
1287
- onKeyDown: (event) => {
1288
- if (event.key === 'Enter' || event.key === ' ') {
1289
- event.preventDefault();
1290
- setTokensOpen((value) => !value);
1291
- }
1292
- },
1293
- },
1294
- h(
1295
- 'span',
1296
- { className: 'dbf-row-title' },
1297
- h('span', { className: 'dbf-fold-arrow', 'aria-hidden': true }, tokensOpen ? '▾' : '▸'),
1298
- t('tokens.title'),
1299
- ),
1300
- h('span', { className: 'dbf-sub' }, tokens(tokenSum)),
1301
- ),
1302
- tokensOpen
1303
- ? h(
1304
- 'div',
1305
- null,
1306
- tokenLine(t('tokens.hit'), hitRate === null ? '—' : hitRate.toFixed(1) + '%'),
1307
- tokenLine(t('tokens.input'), tokens(inputTokens)),
1308
- tokenLine(t('tokens.cache'), tokens(cacheTokens)),
1309
- tokenLine(t('tokens.output'), tokens(outputTokens)),
1310
- tokenSum > 0 ? null : h('div', { className: 'dbf-sub', style: { marginTop: '2px' } }, t('tokens.empty')),
1311
- )
1312
- : null,
1313
- );
1314
-
1315
1355
  const peakBlock = h(
1316
1356
  'div',
1317
1357
  { className: 'dbf-block' },
@@ -1427,16 +1467,93 @@ window.__ModuleLoader__.load({
1427
1467
  'span',
1428
1468
  { className: 'dbf-windows' },
1429
1469
  ['today', '7', '30', 'month'].map((key) =>
1430
- h(
1431
- 'button',
1432
- {
1433
- key,
1434
- type: 'button',
1435
- className: 'dbf-window' + (chartWindow === key ? ' is-active' : ''),
1436
- onClick: () => setChartWindow(key),
1437
- },
1438
- t('history.window.' + key),
1439
- ),
1470
+ key === 'today'
1471
+ ? h(
1472
+ 'span',
1473
+ { key, className: 'dbf-daypick' },
1474
+ h(
1475
+ 'button',
1476
+ {
1477
+ type: 'button',
1478
+ className: 'dbf-window' + (chartWindow === key ? ' is-active' : ''),
1479
+ ref: dayButtonRef,
1480
+ 'aria-haspopup': 'listbox',
1481
+ 'aria-expanded': dayMenuOpen,
1482
+ onClick: (event) => {
1483
+ // Coming from another tab only switches back to today;
1484
+ // the picker opens when this tab is already active.
1485
+ if (chartWindow !== key) {
1486
+ setChartWindow(key);
1487
+ setTrendDay('');
1488
+ setDayMenuOpen(false);
1489
+ return;
1490
+ }
1491
+ const rect = event.currentTarget.getBoundingClientRect();
1492
+ setDayMenuPos({ top: rect.bottom + 4, right: Math.max(8, window.innerWidth - rect.right) });
1493
+ setDayMenuOpen((prev) => !prev);
1494
+ },
1495
+ },
1496
+ dayLabel(trendDayValue) + ' ▾',
1497
+ ),
1498
+ dayMenuOpen
1499
+ ? buildDayMenu(h(
1500
+ 'div',
1501
+ {
1502
+ ref: dayMenuRef,
1503
+ className: 'dbf-daymenu is-floating dbf-surface',
1504
+ role: 'listbox',
1505
+ style: {
1506
+ ...(dayMenuPos === null ? {} : { top: dayMenuPos.top + 'px', right: dayMenuPos.right + 'px' }),
1507
+ // The menu lives in <body>, outside the root that
1508
+ // carries the appearance variables.
1509
+ '--dbf-bg': String((100 - appearance.bg) / 100),
1510
+ '--dbf-shadow': String(appearance.shadow / 100),
1511
+ },
1512
+ },
1513
+ dayOptions.map((day) =>
1514
+ h(
1515
+ 'button',
1516
+ {
1517
+ key: day,
1518
+ type: 'button',
1519
+ role: 'option',
1520
+ 'aria-selected': day === trendDayValue,
1521
+ className:
1522
+ 'dbf-dayitem' +
1523
+ (day === trendDayValue ? ' is-active' : '') +
1524
+ (day === firstDatedDay ? ' is-group-start' : ''),
1525
+ onClick: () => {
1526
+ setTrendDay(day === todayKey ? '' : day);
1527
+ setChartWindow('today');
1528
+ setDayMenuOpen(false);
1529
+ },
1530
+ },
1531
+ h('span', { className: 'dbf-dayitem-label' }, dayLabel(day)),
1532
+ h(
1533
+ 'span',
1534
+ { className: 'dbf-dayitem-sub' },
1535
+ t('weekday.' + new Date(day + 'T00:00:00Z').getUTCDay()),
1536
+ ),
1537
+ day === trendDayValue ? h('span', { className: 'dbf-dayitem-check', 'aria-hidden': true }, '✓') : null,
1538
+ ),
1539
+ ),
1540
+ ))
1541
+ : null,
1542
+ )
1543
+ : h(
1544
+ 'button',
1545
+ {
1546
+ key,
1547
+ type: 'button',
1548
+ className: 'dbf-window' + (chartWindow === key ? ' is-active' : ''),
1549
+ 'aria-pressed': chartWindow === key,
1550
+ onClick: () => {
1551
+ setChartWindow(key);
1552
+ setDayMenuOpen(false);
1553
+ },
1554
+ },
1555
+ t('history.window.' + key),
1556
+ ),
1440
1557
  ),
1441
1558
  ),
1442
1559
  ),
@@ -1520,7 +1637,7 @@ window.__ModuleLoader__.load({
1520
1637
  { className: 'dbf-row' },
1521
1638
  h(
1522
1639
  'button',
1523
- { type: 'button', className: 'dbf-textbtn', onClick: () => setSelectedDay(null) },
1640
+ { type: 'button', className: 'dbf-textbtn is-ghost', onClick: () => setSelectedDay(null) },
1524
1641
  t('day.back'),
1525
1642
  ),
1526
1643
  h('span', { className: 'dbf-sub' }, t('day.title')),
@@ -1631,7 +1748,7 @@ window.__ModuleLoader__.load({
1631
1748
  } else if (dayBlock !== null) {
1632
1749
  body.push(dayBlock);
1633
1750
  } else {
1634
- body.push(balanceBlock, peakBlock, tokenBlock, priceTable, historyBlock);
1751
+ body.push(balanceBlock, peakBlock, priceTable, historyBlock);
1635
1752
  }
1636
1753
 
1637
1754
  card = h(
@@ -1695,7 +1812,6 @@ window.__ModuleLoader__.load({
1695
1812
  'div',
1696
1813
  { className: 'dbf-body' },
1697
1814
  settingsRow('bg', t('settings.bg'), appearance.bg, 90, '%'),
1698
- settingsRow('border', t('settings.border'), appearance.border, 100, '%'),
1699
1815
  settingsRow('shadow', t('settings.shadow'), appearance.shadow, 100, '%'),
1700
1816
  settingsRow('radius', t('settings.radius'), appearance.radius, 20, 'px'),
1701
1817
  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.56",
3
+ "version": "1.2.1",
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
  }