@lls-a1/dsh-balance-float 1.1.56 → 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 +5 -2
- package/client.js +216 -93
- package/index.js +29 -15
- package/lib/ledger.js +6 -4
- package/lib/snapshot.js +7 -4
- package/lib/tracker.js +40 -14
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -29,9 +29,12 @@ Host 半边在本地记账(按轮记 token 与费用、轮询余额),浏
|
|
|
29
29
|
- 单价表列出 Flash / Pro 的命中、未命中、输出单价,当前生效的一侧高亮;
|
|
30
30
|
- 柱状图看近 7 天用量,点某根柱子看那天明细(总消耗、峰谷拆分、按模型费用)。
|
|
31
31
|
|
|
32
|
-
|
|
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',
|
|
@@ -110,6 +107,7 @@ window.__ModuleLoader__.load({
|
|
|
110
107
|
'price.out': '输出',
|
|
111
108
|
history: '用量趋势',
|
|
112
109
|
'history.window.today': '今天',
|
|
110
|
+
'history.yesterday': '昨天',
|
|
113
111
|
'history.window.7': '近7天',
|
|
114
112
|
'history.window.30': '近30天',
|
|
115
113
|
'history.window.month': '本月',
|
|
@@ -172,13 +170,11 @@ window.__ModuleLoader__.load({
|
|
|
172
170
|
'peak.label': 'Peak',
|
|
173
171
|
valley: 'Off-peak',
|
|
174
172
|
'schedule.title': 'Peak and off-peak windows',
|
|
175
|
-
'tokens.title': 'Token usage',
|
|
176
173
|
'tokens.input': 'Uncached input',
|
|
177
174
|
'tokens.cache': 'Cache read',
|
|
178
175
|
'tokens.output': 'Output',
|
|
179
176
|
'tokens.total': 'Total',
|
|
180
177
|
'tokens.hit': 'Cache hit',
|
|
181
|
-
'tokens.empty': 'Buckets are recorded from this version on; older events only carry the total',
|
|
182
178
|
'day.back': '← Back',
|
|
183
179
|
'day.title': 'Day detail',
|
|
184
180
|
'day.calls': '{count} calls · {tokens} tokens',
|
|
@@ -205,6 +201,7 @@ window.__ModuleLoader__.load({
|
|
|
205
201
|
'price.out': 'Out',
|
|
206
202
|
history: 'Usage trend',
|
|
207
203
|
'history.window.today': 'Today',
|
|
204
|
+
'history.yesterday': 'Yesterday',
|
|
208
205
|
'history.window.7': '7d',
|
|
209
206
|
'history.window.30': '30d',
|
|
210
207
|
'history.window.month': 'Month',
|
|
@@ -268,14 +265,14 @@ window.__ModuleLoader__.load({
|
|
|
268
265
|
'.dbf-dot{width:7px;height:7px;border-radius:50%;flex:0 0 auto}',
|
|
269
266
|
'.dbf-dot.is-peak{background:var(--dsw-alias-state-error-primary)}',
|
|
270
267
|
'.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:
|
|
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)}',
|
|
272
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}',
|
|
273
270
|
'.dbf-dir-up .dbf-card{animation-name:dbf-open-up}',
|
|
274
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}',
|
|
275
272
|
'.dbf-head.is-static{cursor:default}',
|
|
276
273
|
'.dbf-head:active{cursor:grabbing}',
|
|
277
274
|
'.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:
|
|
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}',
|
|
279
276
|
'.dbf-icon svg{display:block}',
|
|
280
277
|
'.dbf-icon:disabled{cursor:default;opacity:.6}',
|
|
281
278
|
'.dbf-spinning svg{animation:dbf-spin .9s linear infinite}',
|
|
@@ -298,24 +295,21 @@ window.__ModuleLoader__.load({
|
|
|
298
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}',
|
|
299
296
|
'.dbf-switch.is-on .dbf-switch-knob{background:#fff}',
|
|
300
297
|
'.dbf-switch.is-on .dbf-switch-knob{transform:translateX(14px)}',
|
|
301
|
-
'.dbf-topup{flex:none;padding:3px 10px;border-radius:
|
|
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}',
|
|
302
299
|
'.dbf-topup:hover{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
|
|
303
300
|
'.dbf-topup:active{transform:translateY(.5px)}',
|
|
304
301
|
'.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:
|
|
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}',
|
|
306
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)}',
|
|
307
304
|
'.dbf-version-glyph{font-size:10px;opacity:.75}',
|
|
308
305
|
'.dbf-version.has-update{color:var(--dsw-alias-state-error-primary)}',
|
|
309
306
|
'.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
307
|
'.dbf-token-row{display:flex;align-items:baseline;justify-content:space-between;gap:8px;padding:1px 0}',
|
|
314
308
|
'.dbf-models{display:flex;flex-direction:column;gap:2px;margin-top:6px}',
|
|
315
309
|
'.dbf-model-row{display:flex;align-items:baseline;gap:8px}',
|
|
316
310
|
'.dbf-model-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}',
|
|
317
311
|
'.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:
|
|
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}',
|
|
319
313
|
'.dbf-help:hover,.dbf-help.is-open{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-brand-primary,#4d6bfe)}',
|
|
320
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}',
|
|
321
315
|
'.dbf-rules{margin-top:4px;display:flex;flex-direction:column;gap:2px}',
|
|
@@ -340,7 +334,17 @@ window.__ModuleLoader__.load({
|
|
|
340
334
|
'.dbf-valley{color:var(--dsw-alias-state-success-primary)}',
|
|
341
335
|
'.dbf-badge.dbf-peak{border-color:currentColor}',
|
|
342
336
|
'.dbf-badge.dbf-valley{border-color:currentColor}',
|
|
343
|
-
'.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}',
|
|
344
348
|
'.dbf-models-window{margin-top:6px}',
|
|
345
349
|
'.dbf-mrow{display:flex;align-items:center;gap:6px;font-size:11px;line-height:16px}',
|
|
346
350
|
'.dbf-mname{min-width:66px;color:var(--dsw-alias-label-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
|
|
@@ -348,7 +352,7 @@ window.__ModuleLoader__.load({
|
|
|
348
352
|
'.dbf-mbar{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-brand-primary,#4d6bfe);opacity:.75}',
|
|
349
353
|
'.dbf-mcost{font-variant-numeric:tabular-nums}',
|
|
350
354
|
'.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:
|
|
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}',
|
|
352
356
|
'.dbf-window:hover{color:var(--dsw-alias-label-primary)}',
|
|
353
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}',
|
|
354
358
|
'.dbf-trend-meta{display:flex;align-items:baseline;gap:8px;margin-top:5px}',
|
|
@@ -384,8 +388,11 @@ window.__ModuleLoader__.load({
|
|
|
384
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)}',
|
|
385
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)))}',
|
|
386
390
|
'.dbf-setting-val{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}',
|
|
387
|
-
'.dbf-textbtn{padding:1px 9px;border
|
|
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}',
|
|
388
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}',
|
|
389
396
|
'.dbf-error{color:var(--dsw-alias-state-error-primary)}',
|
|
390
397
|
'.dbf-skel{color:var(--dsw-alias-label-secondary)}',
|
|
391
398
|
].join('');
|
|
@@ -594,6 +601,8 @@ window.__ModuleLoader__.load({
|
|
|
594
601
|
function BalanceFloat(props) {
|
|
595
602
|
const t = props.t;
|
|
596
603
|
const openPluginPage = typeof props.openPluginPage === 'function' ? props.openPluginPage : () => {};
|
|
604
|
+
const buildDayMenu = (node) =>
|
|
605
|
+
createPortal !== null && typeof document !== 'undefined' ? createPortal(node, document.body) : node;
|
|
597
606
|
const [snapshot, setSnapshot] = useState(null);
|
|
598
607
|
const [failure, setFailure] = useState('');
|
|
599
608
|
const [busy, setBusy] = useState(false);
|
|
@@ -618,13 +627,66 @@ window.__ModuleLoader__.load({
|
|
|
618
627
|
const [hintOpen, setHintOpen] = useState(false);
|
|
619
628
|
// A bar of the chart opens that day's detail view; the chart shows today,
|
|
620
629
|
// 7 or 30 days, or the current month depending on the chosen window.
|
|
621
|
-
const [selectedDay, setSelectedDay] = useState(null);
|
|
622
630
|
const [chartWindow, setChartWindow] = useState('today');
|
|
631
|
+
// Clicking a bar opens that day's detail panel.
|
|
632
|
+
const [selectedDay, setSelectedDay] = useState(null);
|
|
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);
|
|
623
641
|
// Token buckets are collapsed until asked for.
|
|
624
|
-
const [tokensOpen, setTokensOpen] = useState(false);
|
|
625
642
|
// Auto check: null | {phase, latest, current, hasUpdate}
|
|
626
643
|
const [update, setUpdate] = useState(null);
|
|
627
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
|
+
|
|
628
690
|
const flashAtRef = useRef(null);
|
|
629
691
|
const flashTimerRef = useRef(null);
|
|
630
692
|
const leaveTimerRef = useRef(null);
|
|
@@ -737,7 +799,6 @@ window.__ModuleLoader__.load({
|
|
|
737
799
|
setLeaving(true);
|
|
738
800
|
setHintOpen(false);
|
|
739
801
|
setSelectedDay(null);
|
|
740
|
-
setTokensOpen(false);
|
|
741
802
|
leaveTimerRef.current = window.setTimeout(() => {
|
|
742
803
|
leaveTimerRef.current = null;
|
|
743
804
|
setLeaving(false);
|
|
@@ -771,6 +832,8 @@ window.__ModuleLoader__.load({
|
|
|
771
832
|
void checkUpdate();
|
|
772
833
|
}, [open, snapshot?.version, checkUpdate]);
|
|
773
834
|
|
|
835
|
+
const loadSeq = useRef(0);
|
|
836
|
+
const openRef = useRef(false);
|
|
774
837
|
const load = useCallback(async (manual) => {
|
|
775
838
|
// Hold the spinner for at least one full turn: a local read returns in
|
|
776
839
|
// a few milliseconds, which otherwise looks like nothing happened.
|
|
@@ -784,12 +847,28 @@ window.__ModuleLoader__.load({
|
|
|
784
847
|
setBusy(true);
|
|
785
848
|
setRefreshState('refreshing');
|
|
786
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);
|
|
787
853
|
try {
|
|
788
|
-
|
|
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' });
|
|
789
858
|
const body = await response.json();
|
|
790
|
-
if (!aliveRef.current) return;
|
|
859
|
+
if (!aliveRef.current || seq !== loadSeq.current) return;
|
|
791
860
|
if (!response.ok) throw new Error(typeof body?.error === 'string' && body.error !== '' ? body.error : 'HTTP ' + response.status);
|
|
792
|
-
|
|
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
|
+
}
|
|
793
872
|
setOffset(typeof body?.serverNow === 'number' ? body.serverNow - Date.now() : 0);
|
|
794
873
|
setFailure('');
|
|
795
874
|
// A new settled turn (new `turn.at`) gets one bubble; the same turn never re-flashes.
|
|
@@ -842,6 +921,7 @@ window.__ModuleLoader__.load({
|
|
|
842
921
|
|
|
843
922
|
// Expanding the card is also a request for the freshest numbers.
|
|
844
923
|
useEffect(() => {
|
|
924
|
+
openRef.current = open;
|
|
845
925
|
if (open) load();
|
|
846
926
|
}, [open, load]);
|
|
847
927
|
|
|
@@ -1065,8 +1145,12 @@ window.__ModuleLoader__.load({
|
|
|
1065
1145
|
const prices = Array.isArray(snapshot?.prices) ? snapshot.prices : [];
|
|
1066
1146
|
const allHistory = Array.isArray(snapshot?.history) ? snapshot.history : [];
|
|
1067
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 ?? '');
|
|
1068
1152
|
const history = todayWindow
|
|
1069
|
-
?
|
|
1153
|
+
? (trendRow === null ? [] : [trendRow])
|
|
1070
1154
|
: chartWindow === 'month'
|
|
1071
1155
|
? (() => {
|
|
1072
1156
|
const prefix = (snapshot?.today ?? '').slice(0, 7);
|
|
@@ -1076,19 +1160,33 @@ window.__ModuleLoader__.load({
|
|
|
1076
1160
|
// "Today" reads the live counters: the history row is written by the
|
|
1077
1161
|
// ledger and can lag behind the current turn.
|
|
1078
1162
|
const windowTotal = todayWindow
|
|
1079
|
-
? (snapshot?.todayUsed ?? 0)
|
|
1163
|
+
? (isLiveDay ? (snapshot?.todayUsed ?? 0) : (trendRow?.cost ?? 0))
|
|
1080
1164
|
: history.reduce((sum, row) => sum + (row.cost ?? 0), 0);
|
|
1081
1165
|
const windowPeakCost = todayWindow
|
|
1082
|
-
? (snapshot?.todayPeakCost ?? 0)
|
|
1166
|
+
? (isLiveDay ? (snapshot?.todayPeakCost ?? 0) : (trendRow?.peakCost ?? 0))
|
|
1083
1167
|
: history.reduce((sum, row) => sum + (row.peakCost ?? 0), 0);
|
|
1084
1168
|
const windowValleyCost = todayWindow
|
|
1085
|
-
? (snapshot?.todayValleyCost ?? 0)
|
|
1169
|
+
? (isLiveDay ? (snapshot?.todayValleyCost ?? 0) : (trendRow?.valleyCost ?? 0))
|
|
1086
1170
|
: history.reduce((sum, row) => sum + (row.valleyCost ?? 0), 0);
|
|
1087
1171
|
const windowCalls = todayWindow
|
|
1088
|
-
? (snapshot?.todayCalls ?? 0)
|
|
1172
|
+
? (isLiveDay ? (snapshot?.todayCalls ?? 0) : (trendRow?.calls ?? 0))
|
|
1089
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);
|
|
1090
1188
|
const windowModels = todayWindow
|
|
1091
|
-
? (Array.isArray(snapshot?.models) ? snapshot.models : [])
|
|
1189
|
+
? (isLiveDay ? (Array.isArray(snapshot?.models) ? snapshot.models : []) : (trendRow?.models ?? []))
|
|
1092
1190
|
: (() => {
|
|
1093
1191
|
const table = {};
|
|
1094
1192
|
for (const row of history) {
|
|
@@ -1100,7 +1198,6 @@ window.__ModuleLoader__.load({
|
|
|
1100
1198
|
}
|
|
1101
1199
|
return Object.values(table).sort((a, b) => b.cost - a.cost);
|
|
1102
1200
|
})();
|
|
1103
|
-
const models = Array.isArray(snapshot?.models) ? snapshot.models : [];
|
|
1104
1201
|
const turn = snapshot?.turn ?? null;
|
|
1105
1202
|
|
|
1106
1203
|
const liveFrame = dragRef.current !== null && liveRef.current !== null ? liveRef.current : frame;
|
|
@@ -1260,58 +1357,6 @@ window.__ModuleLoader__.load({
|
|
|
1260
1357
|
stale ? h('div', { className: 'dbf-error', style: { marginTop: '4px' } }, t('error.stale')) : null,
|
|
1261
1358
|
);
|
|
1262
1359
|
|
|
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
1360
|
const peakBlock = h(
|
|
1316
1361
|
'div',
|
|
1317
1362
|
{ className: 'dbf-block' },
|
|
@@ -1427,16 +1472,94 @@ window.__ModuleLoader__.load({
|
|
|
1427
1472
|
'span',
|
|
1428
1473
|
{ className: 'dbf-windows' },
|
|
1429
1474
|
['today', '7', '30', 'month'].map((key) =>
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
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
|
+
),
|
|
1440
1563
|
),
|
|
1441
1564
|
),
|
|
1442
1565
|
),
|
|
@@ -1520,7 +1643,7 @@ window.__ModuleLoader__.load({
|
|
|
1520
1643
|
{ className: 'dbf-row' },
|
|
1521
1644
|
h(
|
|
1522
1645
|
'button',
|
|
1523
|
-
{ type: 'button', className: 'dbf-textbtn', onClick: () => setSelectedDay(null) },
|
|
1646
|
+
{ type: 'button', className: 'dbf-textbtn is-ghost', onClick: () => setSelectedDay(null) },
|
|
1524
1647
|
t('day.back'),
|
|
1525
1648
|
),
|
|
1526
1649
|
h('span', { className: 'dbf-sub' }, t('day.title')),
|
|
@@ -1631,7 +1754,7 @@ window.__ModuleLoader__.load({
|
|
|
1631
1754
|
} else if (dayBlock !== null) {
|
|
1632
1755
|
body.push(dayBlock);
|
|
1633
1756
|
} else {
|
|
1634
|
-
body.push(balanceBlock, peakBlock,
|
|
1757
|
+
body.push(balanceBlock, peakBlock, priceTable, historyBlock);
|
|
1635
1758
|
}
|
|
1636
1759
|
|
|
1637
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
|
-
|
|
73
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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;
|
|
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
|
-
|
|
172
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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,
|
|
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
|
|
62
|
-
function
|
|
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 ===
|
|
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
|
-
|
|
98
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
177
|
-
|
|
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.
|
|
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
|
}
|