dsh-token-dash 2.4.0 → 2.5.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.en.md +2 -2
- package/README.md +3 -2
- package/client.js +257 -100
- package/index.js +65 -9
- package/package.json +8 -3
- package/src/adapters.js +45 -5
- package/src/collect.js +39 -12
- package/src/core.js +39 -10
package/README.en.md
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
12
12
|
See today's model spend, monthly budget headroom, and subscription windows for 8 providers right next to the DSH input box.<br />
|
|
13
|
-
|
|
14
|
-
export the current month and import it back after switching machines or reinstalling.
|
|
13
|
+
Pill for the current model, floating panel for budget and usage, full dashboard for every provider card; cache hit rate, usage trends and a dual-currency cost chart in one view.<br />
|
|
14
|
+
Paste a key and the billing mode is detected automatically; cost, Tokens and cache hits are estimated locally; export the current month and import it back after switching machines or reinstalling.
|
|
15
15
|
</p>
|
|
16
16
|
|
|
17
17
|
<p align="center">
|
package/README.md
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
12
12
|
在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及 8 家供应商的订阅窗口。<br />
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
Pill 看当前模型,浮层看预算与用量,整页看全量卡片;缓存命中率、用量趋势与双币种双轴成本曲线一屏读完。<br />
|
|
14
|
+
填 Key 自动识别订阅或 API 用量;费用、Tokens、缓存命中全部在本地估算;当月数据可导出备份,换机或重装后一键导入恢复。
|
|
15
15
|
</p>
|
|
16
16
|
|
|
17
17
|
<p align="center">
|
|
@@ -156,6 +156,7 @@ npm run logs -- --module provider,route # 缓存 / 路由异常
|
|
|
156
156
|
```bash
|
|
157
157
|
npm test # 单元测试(80 通过)
|
|
158
158
|
npm run e2e # 端到端(临时 DSH_HOME + web profile + Playwright)
|
|
159
|
+
npm run stats # npm 下载量、版本分布与装机估算(只读公开接口,按 UTC 日统计)
|
|
159
160
|
npm run shots # 用假数据重新生成 docs/pic 的 P1/P2/P3 截图
|
|
160
161
|
npm run pack # 发布 tarball 生成到 build/
|
|
161
162
|
```
|
package/client.js
CHANGED
|
@@ -94,9 +94,9 @@ window.__ModuleLoader__.load({
|
|
|
94
94
|
'API 用量(按供应商)': 'API usage (by provider)',
|
|
95
95
|
'订阅套餐(按供应商)': 'Subscription plans (by provider)',
|
|
96
96
|
'名称': 'Name', '已用': 'Used', '已用 / 预算': 'Used / budget', '计划余额': 'Planned left', '真实余额': 'Real balance',
|
|
97
|
-
'
|
|
97
|
+
'本月已花': 'Spent this month',
|
|
98
98
|
'今日': 'Today', '总费用': 'Total cost', '重试': 'Retry',
|
|
99
|
-
'模型用量明细': 'Model usage details', '模型': 'Model', '共 {n} 个模型': 'Total {n} models', '窗': 'windows', '数据来源': 'Data source', '数据来自本机会话记录,费用与 Tokens 均在本地估算': 'Estimated locally from local session records', '范围与明细': 'Range & details', '输入': 'In', '缓存': 'Cache', '输出': 'Out', '费用': 'Cost',
|
|
99
|
+
'模型用量明细': 'Model usage details', '模型': 'Model', '共 {n} 个模型': 'Total {n} models', '窗': 'windows', '数据待更新': 'Data may be stale', '探测失败,暂用上次数据': 'Probe failed; showing last data', '数据来源': 'Data source', '数据来自本机会话记录,费用与 Tokens 均在本地估算': 'Estimated locally from local session records', '范围与明细': 'Range & details', '输入': 'In', '缓存': 'Cache', '输出': 'Out', '费用': 'Cost',
|
|
100
100
|
'费用(API 计价估算)': 'Cost (API estimate)',
|
|
101
101
|
'重新检测订阅配额': 'Recheck subscription quota',
|
|
102
102
|
'未检测到已配置供应商': 'No configured provider detected',
|
|
@@ -463,7 +463,11 @@ window.__ModuleLoader__.load({
|
|
|
463
463
|
|
|
464
464
|
const styles = {
|
|
465
465
|
pill: {
|
|
466
|
+
// 字数与行高必须显式声明:pill 挂在宿主底栏,不声明会继承宿主的 16px,
|
|
467
|
+
// 导致前缀/数值/分隔符比标签大出一档,并让同一行出现多条文字基线(P1 排版对齐)。
|
|
468
|
+
// 12px / 16px 行高与 ui-design.md §2.6 的 --td-fs-pill、§3「P1 字号 12px」一致。
|
|
466
469
|
display: 'inline-flex', alignItems: 'center', gap: 6, height: 24, padding: '0 8px',
|
|
470
|
+
boxSizing: 'border-box', fontSize: 12, lineHeight: '16px',
|
|
467
471
|
borderRadius: 999, cursor: 'pointer', maxWidth: '100%', fontVariantNumeric: 'tabular-nums',
|
|
468
472
|
border: `1px solid ${T.border}`, color: T.text,
|
|
469
473
|
},
|
|
@@ -487,6 +491,14 @@ window.__ModuleLoader__.load({
|
|
|
487
491
|
header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 28 },
|
|
488
492
|
headerTabs: { flex: 1, minWidth: 0 },
|
|
489
493
|
headerActions: { display: 'flex', alignItems: 'center', gap: 4, flex: '0 0 auto' },
|
|
494
|
+
// 失败态「重试」:实红描边而非淡色,与蓝色关闭按钮区分(Issue #4)
|
|
495
|
+
retryChip: {
|
|
496
|
+
display: 'inline-flex', alignItems: 'center', gap: 4, height: 22, minHeight: 22, padding: '0 7px',
|
|
497
|
+
boxSizing: 'border-box', borderRadius: 6, font: 'inherit', fontSize: 11, fontWeight: 600,
|
|
498
|
+
cursor: 'pointer', color: T.over,
|
|
499
|
+
border: `1px solid ${T.over}`,
|
|
500
|
+
background: `color-mix(in srgb, ${T.over} 14%, transparent)`,
|
|
501
|
+
},
|
|
490
502
|
row: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 },
|
|
491
503
|
rowStart: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
|
|
492
504
|
muted: { color: T.muted, fontSize: 11 },
|
|
@@ -540,12 +552,18 @@ window.__ModuleLoader__.load({
|
|
|
540
552
|
card: { background: T.section, borderRadius: 10, padding: 10, marginTop: 10, display: 'grid', gap: 8 },
|
|
541
553
|
link: { color: T.text, textDecoration: 'underline', cursor: 'pointer' },
|
|
542
554
|
status: { minHeight: 15, fontSize: 10.5, color: T.muted, textAlign: 'right' },
|
|
543
|
-
|
|
555
|
+
// 三栏制(Issue #2):左(环)贴左 / 中(已用·预算)居中 / 右(真实余额)贴右。
|
|
556
|
+
// 中栏内容最长(¥91.90 / ¥100.00),给 1.5fr 避免换行;左右两栏内容短,1fr 仍可贴边。
|
|
557
|
+
summaryRow: { display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.5fr) minmax(0,1fr)', alignItems: 'center', columnGap: 12, minHeight: 24, fontSize: 12 },
|
|
544
558
|
summaryCell: { display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0, whiteSpace: 'nowrap' },
|
|
559
|
+
// P1 专用标签:summaryLabel 的 11px 被 P2 共用(ui-design.md §4.3 要求 P2 标签 11px),
|
|
560
|
+
// P1 需要 12px,故单独一份,避免改一处把 P2 也带过去。
|
|
561
|
+
pillLabel: { color: T.muted, fontSize: 12, lineHeight: '16px' },
|
|
545
562
|
summaryLabel: { color: T.muted, fontSize: 11 },
|
|
546
563
|
summaryValue: { fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
|
|
547
564
|
providerLine: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0, minHeight: 24 },
|
|
548
565
|
providerChip: { color: T.muted, fontSize: 12, whiteSpace: 'nowrap' },
|
|
566
|
+
staleBadge: { color: T.weak, fontSize: 11, whiteSpace: 'nowrap', border: `1px solid ${T.border}`, borderRadius: 4, padding: '0 4px' },
|
|
549
567
|
windowRow: { display: 'grid', gridTemplateColumns: 'auto 1fr 1fr 1fr', columnGap: 8, alignItems: 'center', minHeight: 24, fontSize: 13 },
|
|
550
568
|
windowKey: { display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' },
|
|
551
569
|
table: { display: 'grid', minWidth: 0 },
|
|
@@ -603,6 +621,8 @@ window.__ModuleLoader__.load({
|
|
|
603
621
|
display: 'inline-flex', alignItems: 'center', gap: 4, height: 24, padding: '0 8px', borderRadius: 999,
|
|
604
622
|
border: `1px solid ${T.border}`, color: T.text, textDecoration: 'none', fontSize: 12, whiteSpace: 'nowrap',
|
|
605
623
|
},
|
|
624
|
+
// P1 订阅段容器:窗口组之间单侧视觉留白 = gap 4 + 分隔符盒宽/2 − 墨迹宽/2 = 7px(Issue #1)
|
|
625
|
+
pillGroup: { display: 'inline-flex', alignItems: 'center', gap: 4 },
|
|
606
626
|
inlineWrap: { display: 'inline-flex', alignItems: 'center', gap: 4 },
|
|
607
627
|
gaugeMeta: { color: T.muted, fontSize: 11, lineHeight: '15px', whiteSpace: 'nowrap' },
|
|
608
628
|
apiCards: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 12 },
|
|
@@ -968,29 +988,65 @@ window.__ModuleLoader__.load({
|
|
|
968
988
|
}))
|
|
969
989
|
}
|
|
970
990
|
|
|
971
|
-
/**
|
|
972
|
-
|
|
991
|
+
/**
|
|
992
|
+
* 百分比文本:只负责格式化与状态色,不管排版。
|
|
993
|
+
*
|
|
994
|
+
* 垂直对齐(Issue #6):字形盒在行盒里并非垂直居中——上半部分是 ascender 空间,
|
|
995
|
+
* 数字实际贴着基线落在偏上位置。只压 line-height 无改善(实测仍差 1.50px),
|
|
996
|
+
* 因此在底部补 2px:把字形整体顶回环心,实测残差 0.50px(三档尺寸一致)。
|
|
997
|
+
* 这是字形度量的补偿,不是视觉微调;改字号时该值需按 font-size 等比复核。
|
|
998
|
+
*/
|
|
999
|
+
/**
|
|
1000
|
+
* `lineHeight` 只接受带单位的字符串:React 把 lineHeight 视作无单位属性,
|
|
1001
|
+
* 传数字 16 会被当作「16 倍」而算出 16 × fontSize(实测 192px),故入口统一归一化。
|
|
1002
|
+
*/
|
|
1003
|
+
function PercentValue({ percent, state = stateOf(percent), size = 12, lineHeight, testid }) {
|
|
1004
|
+
const lineHeightCss = lineHeight === undefined
|
|
1005
|
+
? undefined
|
|
1006
|
+
: (typeof lineHeight === 'number' ? `${lineHeight}px` : lineHeight)
|
|
1007
|
+
// P1 传 lineHeight 与 pill 的 16px 行盒统一,且此时不再补 paddingBottom:
|
|
1008
|
+
// 全行同字号时补偿会把该文本整体上移 1px,反而与相邻标签错开(实测基线 17→16)。
|
|
973
1009
|
return h('b', {
|
|
974
1010
|
'data-testid': testid,
|
|
975
|
-
style: {
|
|
1011
|
+
style: {
|
|
1012
|
+
fontSize: size, fontWeight: 600, color: stateColor(state),
|
|
1013
|
+
fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
|
|
1014
|
+
...(lineHeightCss === undefined ? { lineHeight: 1, paddingBottom: 2 } : { lineHeight: lineHeightCss }),
|
|
1015
|
+
},
|
|
976
1016
|
}, percentText(percent))
|
|
977
1017
|
}
|
|
978
1018
|
|
|
979
|
-
/**
|
|
980
|
-
|
|
1019
|
+
/**
|
|
1020
|
+
* 内联组合:环 + 右侧数字,P1 14/2、P2 20/2.5。
|
|
1021
|
+
*
|
|
1022
|
+
* `fontSize` 是 P1 排版对齐的入参:P1 需要环内数字与 pill 其余文字同为 12px,
|
|
1023
|
+
* 且**不带** PercentValue 那 2px 字形补偿——补偿会把该文本框整体上移 1px,
|
|
1024
|
+
* 在「全行同字号」时反而制造基线差。不传该参数时保持原有行为,P2 / P3 不受影响。
|
|
1025
|
+
*/
|
|
1026
|
+
function InlineRing({ percent, state = stateOf(percent), size = 14, stroke = 2, text, fontSize, percentLineHeight, ringShift, testid, percentTestid }) {
|
|
981
1027
|
return h('span', {
|
|
982
1028
|
'data-testid': testid,
|
|
983
1029
|
style: { display: 'inline-flex', alignItems: 'center', gap: 4, minWidth: 0 },
|
|
984
1030
|
},
|
|
985
|
-
h(
|
|
1031
|
+
h('span', {
|
|
1032
|
+
// P1 传 ringShift:环下移 0.75px,让环墨迹中心对齐同一行文字的墨迹中心(Issue #1)。
|
|
1033
|
+
// 移的是 SVG 图形,不涉及字体度量,换字体后依然成立。
|
|
1034
|
+
style: ringShift === undefined ? undefined : { display: 'inline-flex', position: 'relative', top: ringShift, flex: 'none' },
|
|
1035
|
+
}, h(ProgressRing, { percent, state, size, stroke })),
|
|
986
1036
|
text !== undefined
|
|
987
|
-
? h('b', {
|
|
988
|
-
|
|
1037
|
+
? h('b', {
|
|
1038
|
+
'data-testid': percentTestid,
|
|
1039
|
+
style: {
|
|
1040
|
+
fontWeight: 600, color: stateColor(state), lineHeight: 1,
|
|
1041
|
+
...(fontSize === undefined ? { paddingBottom: 2 } : { fontSize }),
|
|
1042
|
+
},
|
|
1043
|
+
}, text)
|
|
1044
|
+
: h(PercentValue, { percent, state, size: 12, lineHeight: percentLineHeight, testid: percentTestid }))
|
|
989
1045
|
}
|
|
990
1046
|
|
|
991
|
-
/** P3 组合:环心标签 + 环下百分比 +
|
|
992
|
-
function QuotaGauge({ label, percent, state = stateOf(percent),
|
|
993
|
-
const aria = [label, percentText(percent),
|
|
1047
|
+
/** P3 组合:环心标签 + 环下百分比 + 两行辅助(倒计时 / 绝对时间)。 */
|
|
1048
|
+
function QuotaGauge({ label, percent, state = stateOf(percent), relative, absolute, size = 40, stroke = 4, testid, labelTestid, percentTestid, relativeTestid, absoluteTestid }) {
|
|
1049
|
+
const aria = [label, percentText(percent), relative].filter((part) => part !== undefined && part !== null && part !== '').join(',')
|
|
994
1050
|
return h('div', {
|
|
995
1051
|
'data-testid': testid, role: 'group', 'aria-label': aria,
|
|
996
1052
|
style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, minWidth: 0 },
|
|
@@ -1004,13 +1060,14 @@ window.__ModuleLoader__.load({
|
|
|
1004
1060
|
style: {
|
|
1005
1061
|
position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
|
1006
1062
|
fontSize: 12, fontWeight: 600, color: T.muted, letterSpacing: '.2px',
|
|
1063
|
+
// 与 PercentValue 同源的字形补偿:字形在行盒内偏上,补 2px 才光学居中(Issue #6)
|
|
1064
|
+
lineHeight: 1, paddingBottom: 2,
|
|
1007
1065
|
},
|
|
1008
1066
|
}, label)),
|
|
1009
1067
|
h('span', {
|
|
1010
1068
|
'data-testid': percentTestid,
|
|
1011
1069
|
style: { fontSize: 16, fontWeight: 600, lineHeight: '20px', color: stateColor(state), fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
|
|
1012
1070
|
}, percentText(percent)),
|
|
1013
|
-
remaining === undefined ? null : h('span', { 'data-testid': remainingTestid, style: styles.gaugeMeta }, remaining),
|
|
1014
1071
|
relative === undefined ? null : h('span', { 'data-testid': relativeTestid, style: styles.gaugeMeta }, relative),
|
|
1015
1072
|
absolute === undefined ? null : h('span', { 'data-testid': absoluteTestid, style: styles.gaugeMeta }, absolute))
|
|
1016
1073
|
}
|
|
@@ -1022,11 +1079,14 @@ window.__ModuleLoader__.load({
|
|
|
1022
1079
|
|
|
1023
1080
|
function TokenTable({ rows, maxRows = 5, empty = tr('范围内暂无消耗') }) {
|
|
1024
1081
|
if (rows.length === 0) return h('div', { style: styles.empty }, empty)
|
|
1082
|
+
// 分隔线不能画在每个 cell 上:grid 的 columnGap 处没有元素,
|
|
1083
|
+
// 逐 cell 画边框会把一条线切成 4 段并各留断口,数据行断口位置又不同,
|
|
1084
|
+
// 表头线与数据线因此不等长(Issue #3)。改由跨列行承载。
|
|
1025
1085
|
const headCell = (text, align = 'right') => h('span', {
|
|
1026
1086
|
role: 'columnheader',
|
|
1027
|
-
style: { color: T.weak, fontSize: 12, textAlign: align, paddingBottom: 6
|
|
1087
|
+
style: { color: T.weak, fontSize: 12, textAlign: align, paddingBottom: 6 },
|
|
1028
1088
|
}, text)
|
|
1029
|
-
const cell = { padding: '5px 0',
|
|
1089
|
+
const cell = { padding: '5px 0', fontSize: 12, minWidth: 0, borderBottom: TABLE_BORDER }
|
|
1030
1090
|
return h('div', {
|
|
1031
1091
|
'data-testid': 'token-dash-usage-table',
|
|
1032
1092
|
role: 'table',
|
|
@@ -1034,6 +1094,11 @@ window.__ModuleLoader__.load({
|
|
|
1034
1094
|
},
|
|
1035
1095
|
h('div', { style: { display: 'contents' } },
|
|
1036
1096
|
headCell(tr('模型'), 'left'), headCell('Tokens'), headCell(tr('请求')), headCell(tr('命中'))),
|
|
1097
|
+
// 表头分隔线:跨满全部列,不受 columnGap 影响
|
|
1098
|
+
h('span', {
|
|
1099
|
+
'aria-hidden': true,
|
|
1100
|
+
style: { gridColumn: '1 / -1', display: 'block', height: 1, background: T.border, marginBottom: 4 },
|
|
1101
|
+
}),
|
|
1037
1102
|
...rows.map((row) => h('div', {
|
|
1038
1103
|
key: `${row.providerId}:${row.modelId}`,
|
|
1039
1104
|
role: 'row',
|
|
@@ -1531,22 +1596,22 @@ window.__ModuleLoader__.load({
|
|
|
1531
1596
|
return windows.slice(0, 3).map((plan) => `${windowLabel(plan.key)} ${fmtPercent(plan.usedPercent)}`).join(' · ')
|
|
1532
1597
|
}
|
|
1533
1598
|
|
|
1534
|
-
/** P1
|
|
1599
|
+
/** P1 订阅窗口:复用 P0 的 SubWindow(横排、不显示时间),最多三窗。 */
|
|
1535
1600
|
function subscriptionNodes(provider) {
|
|
1536
1601
|
const windows = Array.isArray(provider.windows) ? provider.windows : []
|
|
1537
1602
|
if (windows.length === 0) return [h('span', { key: 'fail', style: styles.muted }, tr('套餐查询失败'))]
|
|
1538
1603
|
const nodes = []
|
|
1539
1604
|
for (const [index, plan] of windows.slice(0, 3).entries()) {
|
|
1540
|
-
|
|
1541
|
-
|
|
1605
|
+
// 分隔符用 U+30FB(片假名中点)且**不带两侧空格**(Issue #1):
|
|
1606
|
+
// 旧写法 ' ・ ' 每侧多出一个半角空格(约 3px 盒宽),会把单侧视觉留白从 7px 撑到 12px,
|
|
1607
|
+
// 三个窗口因此散成三块,看不出同属一条套餐。
|
|
1608
|
+
if (index > 0) nodes.push(h('span', { key: `sep-${plan.key}`, style: { color: T.weak } }, '・'))
|
|
1542
1609
|
nodes.push(h('span', { key: plan.key, style: styles.inlineWrap },
|
|
1543
|
-
h(
|
|
1544
|
-
h(InlineRing, {
|
|
1545
|
-
percent, state: stateOf(percent, SUB_CRITICAL), size: 14, stroke: 2,
|
|
1546
|
-
testid: `token-dash-pill-ring-${plan.key}`,
|
|
1547
|
-
})))
|
|
1610
|
+
h(SubWindow, { plan, showTime: false, ringSize: 14, ringStroke: 2, labelFontSize: 12, ringTestId: `token-dash-pill-ring-${plan.key}` })))
|
|
1548
1611
|
}
|
|
1549
|
-
|
|
1612
|
+
// 包进 gap:4 的容器:窗口组之间的间距由它决定,pill 的 gap:6 只发生一次
|
|
1613
|
+
// (否则每个窗口与分隔符都各吃一份 6px,API 段又会跟着被改成 4)。
|
|
1614
|
+
return [h('span', { key: 'subgroup', style: styles.pillGroup }, nodes)]
|
|
1550
1615
|
}
|
|
1551
1616
|
|
|
1552
1617
|
function LocaleRoot(props) {
|
|
@@ -1562,27 +1627,31 @@ window.__ModuleLoader__.load({
|
|
|
1562
1627
|
? `/summary?active=${encodeURIComponent(active)}`
|
|
1563
1628
|
: '/summary')
|
|
1564
1629
|
|
|
1565
|
-
/**
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1630
|
+
/**
|
|
1631
|
+
* 从投影取「用户当前选中」的 provider。
|
|
1632
|
+
* 宿主 modelSelection 投影对客户端输出的是 { lastUsed, next },其中 next = pending ?? lastUsed
|
|
1633
|
+
* (pending 是「已切换、尚未发出请求」的最新选择),所以必须读 next。
|
|
1634
|
+
* 必须作为 hook 在组件顶层无条件调用:放进 try/条件会破坏 React hook 顺序,更新会被丢弃。
|
|
1635
|
+
*/
|
|
1636
|
+
function useActiveProvider(props) {
|
|
1637
|
+
const projection = typeof props?.useProjection === 'function' ? props.useProjection('modelSelection') : null
|
|
1638
|
+
const picked = projection?.next ?? projection?.lastUsed
|
|
1639
|
+
const raw = typeof picked === 'string' ? picked : (picked?.provider ?? picked?.providerId ?? null)
|
|
1640
|
+
if (typeof raw === 'string' && raw !== '') return raw
|
|
1641
|
+
// 兜底:宿主默认模型(全局配置,非会话选择,仅保证有值可渲染)
|
|
1573
1642
|
try {
|
|
1574
1643
|
const service = typeof ctxRef?.get === 'function' ? ctxRef.get('agentDefaultModel') : null
|
|
1575
|
-
const
|
|
1576
|
-
const
|
|
1577
|
-
if (typeof
|
|
1578
|
-
} catch { /*
|
|
1644
|
+
const fallback = service?.currentSelection?.()
|
|
1645
|
+
const value = typeof fallback === 'string' ? fallback : (fallback?.provider ?? fallback?.providerId ?? null)
|
|
1646
|
+
if (typeof value === 'string' && value !== '') return value
|
|
1647
|
+
} catch { /* ignore */ }
|
|
1579
1648
|
return null
|
|
1580
1649
|
}
|
|
1581
1650
|
|
|
1582
1651
|
function Pill(props) {
|
|
1583
1652
|
const updateState = useUpdateSnapshot()
|
|
1584
1653
|
const hasUpdate = updateState.phase === 'available' || updateState.phase === 'confirm'
|
|
1585
|
-
const active =
|
|
1654
|
+
const active = useActiveProvider(props)
|
|
1586
1655
|
const [summary, setSummary] = useState(null)
|
|
1587
1656
|
const [open, setOpen] = useState(false)
|
|
1588
1657
|
const [error, setError] = useState(false)
|
|
@@ -1600,33 +1669,49 @@ window.__ModuleLoader__.load({
|
|
|
1600
1669
|
try { if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true) } catch { /* ignore */ }
|
|
1601
1670
|
}, [])
|
|
1602
1671
|
|
|
1672
|
+
// active 放进 ref:轮询定时器只建立一次,回调里读 ref 才能始终拿到最新选中项。
|
|
1673
|
+
// 若把 active 放进 load 的依赖,load 会随切换重建、usePolling 却只依赖 refreshMs 不会重排,
|
|
1674
|
+
// 结果是定时器一直跑旧闭包 —— 这正是此前「切换后不发请求」的成因。
|
|
1675
|
+
const activeRef = useRef(active)
|
|
1676
|
+
activeRef.current = active
|
|
1677
|
+
const refreshMsRef = useRef(refreshMs)
|
|
1678
|
+
refreshMsRef.current = refreshMs
|
|
1679
|
+
|
|
1603
1680
|
const load = useCallback(async () => {
|
|
1604
1681
|
lastLoadAt.current = Date.now()
|
|
1605
1682
|
setRefreshing(true)
|
|
1606
1683
|
try {
|
|
1607
|
-
const data = await getJson(summaryPath(
|
|
1684
|
+
const data = await getJson(summaryPath(activeRef.current))
|
|
1608
1685
|
setSummary(data)
|
|
1609
1686
|
setError(false)
|
|
1610
|
-
if (Number.isFinite(data?.refreshMs) && data.refreshMs !==
|
|
1687
|
+
if (Number.isFinite(data?.refreshMs) && data.refreshMs !== refreshMsRef.current) setRefreshMs(data.refreshMs)
|
|
1611
1688
|
} catch {
|
|
1612
1689
|
setError(true)
|
|
1613
1690
|
} finally {
|
|
1614
1691
|
setRefreshing(false)
|
|
1615
1692
|
}
|
|
1616
|
-
}, [
|
|
1693
|
+
}, [])
|
|
1617
1694
|
|
|
1618
1695
|
useEffect(() => {
|
|
1619
1696
|
getJson('/prefs').then((prefs) => setRefreshMs(prefs.refreshMs ?? 60000)).catch(() => {})
|
|
1620
1697
|
}, [])
|
|
1621
1698
|
|
|
1622
1699
|
useEffect(() => { load() }, [load])
|
|
1623
|
-
//
|
|
1700
|
+
// active 变化时立刻取数(不依赖轮询或投影推送的时序)。
|
|
1701
|
+
// load 本身不再随 active 重建,这里显式监听 active:切换供应商后立即发一次请求。
|
|
1702
|
+
useEffect(() => {
|
|
1703
|
+
if (active === null || active === undefined) return
|
|
1704
|
+
if (Date.now() - lastLoadAt.current < 1500) return
|
|
1705
|
+
void load()
|
|
1706
|
+
}, [active, load])
|
|
1707
|
+
// 展开即刷新:距上次拉取超过 2s 才发,避免开合抖动与 refreshMs 变化引起的重跑
|
|
1624
1708
|
useEffect(() => {
|
|
1625
1709
|
if (!open) return
|
|
1626
1710
|
if (Date.now() - lastLoadAt.current < 2000) return
|
|
1627
1711
|
void load()
|
|
1628
1712
|
}, [open, load])
|
|
1629
|
-
|
|
1713
|
+
// 定时轮询兜底:不依赖投影变化,只要可见就按周期取数(与 dsh-quota 同构)。
|
|
1714
|
+
usePolling(load, { refreshMs: Math.min(open ? 10_000 : 30_000, refreshMs) })
|
|
1630
1715
|
|
|
1631
1716
|
const refreshSubs = useCallback(async () => {
|
|
1632
1717
|
try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* fall through */ }
|
|
@@ -1678,7 +1763,13 @@ window.__ModuleLoader__.load({
|
|
|
1678
1763
|
}
|
|
1679
1764
|
|
|
1680
1765
|
const providers = summary?.providers ?? []
|
|
1681
|
-
|
|
1766
|
+
// 选卡三级:服务端归一化的 activeProviderId → 本地 active 直比 → 记账口径 → 首卡。
|
|
1767
|
+
// 宿主的 active 是路由名(deepseek-account),与 providers[].id(deepseek-official)不同字,
|
|
1768
|
+
// 因此优先用服务端回显的归一化值;本地直比只作兜底,不让 UI 承担别名知识。
|
|
1769
|
+
const current = providers.find((provider) => provider.id === summary?.activeProviderId)
|
|
1770
|
+
?? providers.find((provider) => provider.id === active)
|
|
1771
|
+
?? providers.find((provider) => provider.id === summary?.currentProviderId)
|
|
1772
|
+
?? providers[0]
|
|
1682
1773
|
let prefix = '[API]'
|
|
1683
1774
|
let bodyNodes = [h('span', { key: 'unknown' }, '--')]
|
|
1684
1775
|
let ariaText = tr('API 用量')
|
|
@@ -1693,19 +1784,19 @@ window.__ModuleLoader__.load({
|
|
|
1693
1784
|
const balance = balanceText(current, summary?.showBalance)
|
|
1694
1785
|
bodyNodes = [
|
|
1695
1786
|
h('span', { key: 'budget', style: styles.inlineWrap },
|
|
1696
|
-
h('span', { 'data-td-label': true, style: styles.
|
|
1787
|
+
h('span', { 'data-td-label': true, style: styles.pillLabel }, tr('预算')),
|
|
1697
1788
|
h(InlineRing, {
|
|
1698
1789
|
percent: hasBudget ? percent : null,
|
|
1699
1790
|
state: hasBudget ? stateOf(percent, API_CRITICAL) : 'empty',
|
|
1700
|
-
size: 14, stroke: 2,
|
|
1791
|
+
size: 14, stroke: 2, fontSize: 12, ringShift: 0.75,
|
|
1701
1792
|
text: hasBudget ? fmtRatio(budget.percent) : tr('未设置'),
|
|
1702
1793
|
testid: 'token-dash-pill-ring-budget',
|
|
1703
1794
|
})),
|
|
1704
1795
|
h('span', { key: 'today', style: styles.inlineWrap },
|
|
1705
|
-
h('span', { 'data-td-label': true, style: styles.
|
|
1796
|
+
h('span', { 'data-td-label': true, style: styles.pillLabel }, tr('今日')),
|
|
1706
1797
|
h('span', { style: styles.num }, fmtMoney(current.usage?.todayCost, current.currency))),
|
|
1707
1798
|
balance === null ? null : h('span', { key: 'balance', style: styles.inlineWrap },
|
|
1708
|
-
h('span', { 'data-td-label': true, style: styles.
|
|
1799
|
+
h('span', { 'data-td-label': true, style: styles.pillLabel }, tr('余额')),
|
|
1709
1800
|
h('span', { style: styles.num }, balance)),
|
|
1710
1801
|
].filter(Boolean)
|
|
1711
1802
|
ariaText = tr('{name},API 用量,{budget},今日 {today}{balance}', { name: current.name, budget: hasBudget ? tr('预算已用 {value}', { value: fmtRatio(budget.percent) }) : tr('预算未设置'), today: fmtMoney(current.usage?.todayCost, current.currency), balance: balance === null ? '' : `,${tr('余额 {value}', { value: balance })}` })
|
|
@@ -1732,21 +1823,30 @@ window.__ModuleLoader__.load({
|
|
|
1732
1823
|
}) : null)
|
|
1733
1824
|
}
|
|
1734
1825
|
|
|
1735
|
-
|
|
1826
|
+
/**
|
|
1827
|
+
* P2 标题栏:仅刷新与关闭。
|
|
1828
|
+
* 原有一个 ⓘ 提示「支持哪些 API Key」,文案停留在 5 家 provider 的旧表述,
|
|
1829
|
+
* 且对已配置完成的用户无操作价值,故移除(Issue #3)。
|
|
1830
|
+
* headerActions 不再需要 marginInlineEnd 负偏移——那是为抵消 ⓘ 的视觉留白。
|
|
1831
|
+
*/
|
|
1832
|
+
function PanelHeader({ onRefresh, refreshing, onClose, stale = false, failed = false }) {
|
|
1736
1833
|
return h('div', { style: styles.header },
|
|
1737
1834
|
h('b', { style: styles.title }, tr('当前模型')),
|
|
1738
|
-
h('div', { style:
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1835
|
+
h('div', { style: styles.headerActions },
|
|
1836
|
+
// 任一接口失败时,刷新位换成带文字的「重试」:全屏只保留这一个入口,
|
|
1837
|
+
// 表体内不再插入错误条按钮(Issue #4)
|
|
1838
|
+
failed
|
|
1839
|
+
? h('button', {
|
|
1840
|
+
type: 'button', 'data-testid': 'token-dash-retry',
|
|
1841
|
+
style: styles.retryChip, disabled: refreshing, onClick: onRefresh,
|
|
1842
|
+
}, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 12 }), tr('重试'))
|
|
1843
|
+
: h(IconButton, {
|
|
1844
|
+
label: tr('刷新'), testid: 'token-dash-refresh', disabled: refreshing, onClick: onRefresh, dot: stale,
|
|
1845
|
+
}, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 13 })),
|
|
1746
1846
|
h(IconButton, { label: tr('关闭'), testid: 'token-dash-close', onClick: onClose }, h(Icon, { name: 'close', size: 13 }))))
|
|
1747
1847
|
}
|
|
1748
1848
|
|
|
1749
|
-
function Panel({ summary, error, refreshing, maxHeight, left = 0, panelRef, onRefresh, onClose }) {
|
|
1849
|
+
function Panel({ summary, error, refreshing, maxHeight, left = 0, active, panelRef, onRefresh, onClose }) {
|
|
1750
1850
|
const [range, setRange] = useState('today')
|
|
1751
1851
|
const [usage, setUsage] = useState(null)
|
|
1752
1852
|
const [usageLoading, setUsageLoading] = useState(false)
|
|
@@ -1765,12 +1865,16 @@ window.__ModuleLoader__.load({
|
|
|
1765
1865
|
} catch {
|
|
1766
1866
|
if (seq !== usageSeq.current) return
|
|
1767
1867
|
setUsageError(true)
|
|
1868
|
+
// 失败即清空:保留旧数据会让用户把陈旧数字当成当前值(Issue #4)
|
|
1869
|
+
setUsage(null)
|
|
1768
1870
|
} finally {
|
|
1769
1871
|
if (seq === usageSeq.current) setUsageLoading(false)
|
|
1770
1872
|
}
|
|
1771
1873
|
}, [range])
|
|
1772
1874
|
|
|
1773
1875
|
useEffect(() => { loadUsage() }, [loadUsage])
|
|
1876
|
+
// P2 展开期 usage 随轮询自动更新(对齐 P3 看板口径),聊天中不再依赖手动点击
|
|
1877
|
+
usePolling(loadUsage, { refreshMs: Math.min(10_000, Number(summary?.refreshMs) || 60_000) })
|
|
1774
1878
|
useEffect(() => { setPanelError(error === true) }, [error])
|
|
1775
1879
|
|
|
1776
1880
|
useEffect(() => {
|
|
@@ -1797,7 +1901,11 @@ window.__ModuleLoader__.load({
|
|
|
1797
1901
|
}, [onRefresh, loadUsage])
|
|
1798
1902
|
|
|
1799
1903
|
const providers = summary?.providers ?? []
|
|
1800
|
-
|
|
1904
|
+
// 与 Pill 同口径:归一化 active 优先,本地直比与记账口径兜底
|
|
1905
|
+
const current = providers.find((provider) => provider.id === summary?.activeProviderId)
|
|
1906
|
+
?? providers.find((provider) => provider.id === active)
|
|
1907
|
+
?? providers.find((provider) => provider.id === summary?.currentProviderId)
|
|
1908
|
+
?? providers[0]
|
|
1801
1909
|
const models = Array.isArray(usage?.models) ? usage.models : []
|
|
1802
1910
|
const scoped = models.filter((model) => model.providerId === current?.id)
|
|
1803
1911
|
const rows = scoped.length > 0 ? scoped : models
|
|
@@ -1807,12 +1915,6 @@ window.__ModuleLoader__.load({
|
|
|
1807
1915
|
// 布局服务可用就显示入口;注册时序可能导致 hasMainPanel 暂时为 false,点击时再判。
|
|
1808
1916
|
const canOpen = layoutRef !== null
|
|
1809
1917
|
|
|
1810
|
-
const strip = error || usageError
|
|
1811
|
-
? h('div', { style: styles.errorStrip, role: 'alert' },
|
|
1812
|
-
h('span', null, error ? tr('刷新失败,保留上次数据') : tr('范围数据加载失败')),
|
|
1813
|
-
h('button', { type: 'button', style: styles.button, onClick: refreshAll }, tr('重试')))
|
|
1814
|
-
: null
|
|
1815
|
-
|
|
1816
1918
|
let body
|
|
1817
1919
|
if (summary === null) {
|
|
1818
1920
|
body = h('div', { style: styles.empty }, panelError ? tr('Token 数据不可用') : tr('Token 数据加载中…'))
|
|
@@ -1830,7 +1932,6 @@ window.__ModuleLoader__.load({
|
|
|
1830
1932
|
value: range, onChange: setRange, label: tr('时间范围'),
|
|
1831
1933
|
options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
|
|
1832
1934
|
})),
|
|
1833
|
-
strip,
|
|
1834
1935
|
usage === null && usageLoading
|
|
1835
1936
|
? h('div', { style: styles.empty }, tr('范围数据加载中…'))
|
|
1836
1937
|
: h(TokenTable, { rows }),
|
|
@@ -1850,7 +1951,10 @@ window.__ModuleLoader__.load({
|
|
|
1850
1951
|
'data-testid': 'token-dash-panel',
|
|
1851
1952
|
style: { ...styles.panel, maxHeight, left },
|
|
1852
1953
|
},
|
|
1853
|
-
h(PanelHeader, {
|
|
1954
|
+
h(PanelHeader, {
|
|
1955
|
+
onRefresh: refreshAll, refreshing: refreshing || usageLoading, onClose, stale,
|
|
1956
|
+
failed: error || usageError,
|
|
1957
|
+
}),
|
|
1854
1958
|
body)
|
|
1855
1959
|
}
|
|
1856
1960
|
|
|
@@ -1864,6 +1968,16 @@ window.__ModuleLoader__.load({
|
|
|
1864
1968
|
}, suffix === '' ? text : `${text} ${suffix}`)
|
|
1865
1969
|
}
|
|
1866
1970
|
|
|
1971
|
+
/** 降级角标:探测失败但仍有旧快照时提示「数据待更新」。 */
|
|
1972
|
+
function StaleBadge({ provider }) {
|
|
1973
|
+
if (provider?.stale !== true) return null
|
|
1974
|
+
return h('span', {
|
|
1975
|
+
'data-testid': 'token-dash-stale-badge',
|
|
1976
|
+
style: styles.staleBadge,
|
|
1977
|
+
title: tr('探测失败,暂用上次数据'),
|
|
1978
|
+
}, tr('数据待更新'))
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1867
1981
|
/** P2 API 主区:环+% / 已用·预算 / 真实余额;第四格留空。 */
|
|
1868
1982
|
function P2Summary({ provider, summary }) {
|
|
1869
1983
|
const budget = provider.budget
|
|
@@ -1873,16 +1987,18 @@ window.__ModuleLoader__.load({
|
|
|
1873
1987
|
return h(React.Fragment, null,
|
|
1874
1988
|
h('div', { style: styles.providerLine },
|
|
1875
1989
|
h('span', { style: styles.title, title: provider.name }, provider.name),
|
|
1876
|
-
h('span', { style:
|
|
1990
|
+
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 } },
|
|
1991
|
+
h(StaleBadge, { provider }),
|
|
1992
|
+
h('span', { style: styles.providerChip }, `[ ${tr('API 用量')} ]`))),
|
|
1877
1993
|
h('div', { 'data-testid': 'token-dash-summary-row', style: styles.summaryRow },
|
|
1878
|
-
h('span', { style: styles.summaryCell },
|
|
1994
|
+
h('span', { style: { ...styles.summaryCell, alignItems: 'flex-start' } },
|
|
1879
1995
|
h(InlineRing, {
|
|
1880
1996
|
percent: hasBudget ? percent : null,
|
|
1881
1997
|
state: hasBudget ? stateOf(percent, API_CRITICAL) : 'empty',
|
|
1882
1998
|
size: 20, stroke: 2.5,
|
|
1883
1999
|
testid: 'token-dash-summary-ring',
|
|
1884
2000
|
})),
|
|
1885
|
-
h('span', { 'data-testid': 'token-dash-summary-used', style: styles.summaryCell },
|
|
2001
|
+
h('span', { 'data-testid': 'token-dash-summary-used', style: { ...styles.summaryCell, alignItems: 'center' } },
|
|
1886
2002
|
h('span', { style: styles.summaryLabel }, tr('已用 / 预算')),
|
|
1887
2003
|
h('span', { style: styles.summaryValue },
|
|
1888
2004
|
hasBudget ? `${fmtMoney(budget.used, provider.currency)} / ${fmtMoney(budget.amount, provider.currency)}` : '—')),
|
|
@@ -1890,8 +2006,7 @@ window.__ModuleLoader__.load({
|
|
|
1890
2006
|
'data-testid': 'token-dash-summary-balance',
|
|
1891
2007
|
style: {
|
|
1892
2008
|
...styles.summaryCell,
|
|
1893
|
-
|
|
1894
|
-
justifySelf: 'end',
|
|
2009
|
+
// 两行共用同一条右缘,与标题行 [ API 用量 ] 对齐(Issue #2)
|
|
1895
2010
|
alignItems: 'flex-end',
|
|
1896
2011
|
textAlign: 'right',
|
|
1897
2012
|
},
|
|
@@ -1901,47 +2016,91 @@ window.__ModuleLoader__.load({
|
|
|
1901
2016
|
h('span', { style: styles.summaryValue }, balance ?? '—'))))
|
|
1902
2017
|
}
|
|
1903
2018
|
|
|
1904
|
-
/**
|
|
1905
|
-
|
|
2019
|
+
/**
|
|
2020
|
+
* P0 公共控件:单个订阅窗口。
|
|
2021
|
+
*
|
|
2022
|
+
* 结构:第一行「标签 + 环 + 数字」作为一个整体横向居中;第二行时间可选,与第一行同心。
|
|
2023
|
+
* 为什么封装:P1 与 P2 曾各写一套,P2 用 position:absolute 把时间钉在圆环中心,
|
|
2024
|
+
* 偏移量随标签字数漂移(标签越长越偏)。这里改用正常流 + align-items:center,
|
|
2025
|
+
* 时间天然与「环 + 数字」这段整体居中对齐,与标签宽度、百分比宽度均无关。
|
|
2026
|
+
*
|
|
2027
|
+
* @param {object} props.plan 订阅窗口(key / usedPercent / resetAt)
|
|
2028
|
+
* @param {boolean} props.showTime 是否显示倒计时(P1 横排不显示,P2 显示)
|
|
2029
|
+
* @param {'start'|'center'|'end'} props.place 控件在所在列内的摆放位置
|
|
2030
|
+
* @param {string} props.testKey 测试 id 后缀
|
|
2031
|
+
* @param {number} props.labelFontSize 周期标签字号;P1 传 12 让标签与 pill 其余文字同字号,
|
|
2032
|
+
* 此时不再使用「锁高 + 上移 0.5px」那套补偿(它只在 P2 的多字号场景下有意义)。不传则沿用旧行为。
|
|
2033
|
+
*/
|
|
2034
|
+
function SubWindow({ plan, showTime = true, place = 'center', testKey, ringTestId, ringSize = 20, ringStroke = 2.5, labelFontSize }) {
|
|
1906
2035
|
const percent = plan === undefined || plan === null ? null : Number(plan.usedPercent)
|
|
1907
2036
|
const hasValue = Number.isFinite(percent)
|
|
1908
2037
|
const parts = hasValue ? resetParts(plan.resetAt) : { relative: null, absolute: null }
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
'data-testid': `token-dash-sub-window-${testKey}`,
|
|
1913
|
-
title: parts.absolute ?? undefined,
|
|
2038
|
+
return h('span', {
|
|
2039
|
+
'data-testid': testKey === undefined ? undefined : `token-dash-sub-window-${testKey}`,
|
|
2040
|
+
title: showTime ? (parts.absolute ?? undefined) : undefined,
|
|
1914
2041
|
style: {
|
|
1915
|
-
display: 'flex', flexDirection: 'column',
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
justifySelf: align === 'right' ? 'end' : align === 'center' ? 'center' : 'start',
|
|
2042
|
+
display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 3,
|
|
2043
|
+
minWidth: 0, whiteSpace: 'nowrap',
|
|
2044
|
+
justifySelf: place === 'end' ? 'end' : place === 'start' ? 'start' : 'center',
|
|
1919
2045
|
},
|
|
1920
2046
|
},
|
|
1921
|
-
|
|
1922
|
-
|
|
2047
|
+
// 第一行:标签 + 环 + 数字,作为整体居中
|
|
2048
|
+
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
|
|
2049
|
+
// 标签对齐(Issue #8,方案 B + D):
|
|
2050
|
+
// B — 行盒高度锁成圆环直径(按 ringSize 取值,P1 14 / P2 20),
|
|
2051
|
+
// 避免行高把标签盒子撑得比环高,align-items 才对得准;
|
|
2052
|
+
// D — 再整体上移 0.5px,补偿汉字字形(周 / 月)相对拉丁(5h)的视觉重心。
|
|
2053
|
+
// 两者不冲突:B 定盒子、D 定位置。不可写死 20px,否则 P1 pill 行高会被撑大。
|
|
2054
|
+
//
|
|
2055
|
+
// P1 例外:传入 labelFontSize 时标签与百分比同为 12px、共用 16px 行高,
|
|
2056
|
+
// 全行单一字号已能自然共基线,再叠加 height/top 补偿反而会造成 1px 偏差,故一并关闭。
|
|
2057
|
+
h('span', {
|
|
2058
|
+
style: labelFontSize === undefined
|
|
2059
|
+
? {
|
|
2060
|
+
...styles.summaryLabel,
|
|
2061
|
+
display: 'inline-flex', alignItems: 'center', lineHeight: 1,
|
|
2062
|
+
height: ringSize, position: 'relative', top: -0.5,
|
|
2063
|
+
}
|
|
2064
|
+
: { color: T.muted, fontSize: labelFontSize, lineHeight: '16px' },
|
|
2065
|
+
}, plan?.key ? windowLabel(plan.key) : '—'),
|
|
1923
2066
|
h(InlineRing, {
|
|
1924
|
-
percent, state: hasValue ? stateOf(percent, SUB_CRITICAL) : 'empty', size:
|
|
2067
|
+
percent, state: hasValue ? stateOf(percent, SUB_CRITICAL) : 'empty', size: ringSize, stroke: ringStroke,
|
|
2068
|
+
// P1:百分比与标签同为 12px / 16px 行盒,且不带 2px 补偿,三者共基线
|
|
2069
|
+
fontSize: labelFontSize === undefined ? undefined : 12,
|
|
2070
|
+
percentLineHeight: labelFontSize === undefined ? undefined : 16,
|
|
2071
|
+
ringShift: labelFontSize === undefined ? undefined : 0.75,
|
|
2072
|
+
testid: ringTestId ?? (testKey === undefined ? undefined : `token-dash-sub-ring-${testKey}`),
|
|
1925
2073
|
})),
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
2074
|
+
// 第二行:时间,与第一行同心(父级 align-items:center 保证)
|
|
2075
|
+
showTime
|
|
2076
|
+
? h('span', {
|
|
2077
|
+
'data-testid': testKey === undefined ? undefined : `token-dash-sub-rel-${testKey}`,
|
|
2078
|
+
style: { fontSize: 11, color: T.muted, lineHeight: '13px' },
|
|
2079
|
+
}, parts.relative ?? '—')
|
|
2080
|
+
: null)
|
|
1933
2081
|
}
|
|
1934
2082
|
|
|
2083
|
+
/** P2 订阅窗口行:复用 P0 的 SubWindow,按 align 决定列内摆放。 */
|
|
2084
|
+
function WindowRow({ providerId, plan, align = 'left' }) {
|
|
2085
|
+
const testKey = `${providerId}-${plan?.key ?? 'none'}`
|
|
2086
|
+
const place = align === 'right' ? 'end' : align === 'center' ? 'center' : 'start'
|
|
2087
|
+
// 传 labelFontSize 走单字号分支(Issue #6):标签与百分比同 12px / 16px 行盒,
|
|
2088
|
+
// 去掉 height:环径 + top:-0.5 的旧补偿,环下移 0.75px 贴合文字墨迹。
|
|
2089
|
+
return h(SubWindow, { plan, showTime: true, place, testKey, labelFontSize: 12 })
|
|
2090
|
+
}
|
|
1935
2091
|
function P2Windows({ provider }) {
|
|
1936
2092
|
const windows = Array.isArray(provider.windows) ? provider.windows : []
|
|
1937
2093
|
return h(React.Fragment, null,
|
|
1938
2094
|
h('div', { style: styles.providerLine },
|
|
1939
2095
|
h('span', { style: styles.title, title: provider.name }, provider.name),
|
|
1940
|
-
h('span', { style:
|
|
2096
|
+
h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 } },
|
|
2097
|
+
h(StaleBadge, { provider }),
|
|
2098
|
+
h('span', { style: styles.providerChip }, `[ ${tr('订阅')} ]`))),
|
|
1941
2099
|
windows.length === 0
|
|
1942
2100
|
? h('div', { style: styles.empty }, tr('套餐查询失败'))
|
|
2101
|
+
// 倒计时是绝对定位(锚在圆环下方),故用 grid 分列 + 底部内边距容纳第二行
|
|
1943
2102
|
: h('div', {
|
|
1944
|
-
style: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12 },
|
|
2103
|
+
style: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12, paddingBottom: 15 },
|
|
1945
2104
|
}, windows.map((plan, index) => h(WindowRow, {
|
|
1946
2105
|
key: plan.key,
|
|
1947
2106
|
providerId: provider.id,
|
|
@@ -2264,17 +2423,15 @@ window.__ModuleLoader__.load({
|
|
|
2264
2423
|
const percent = plan === undefined ? null : Number(plan.usedPercent)
|
|
2265
2424
|
const hasValue = Number.isFinite(percent)
|
|
2266
2425
|
const parts = hasValue ? resetParts(plan.resetAt) : { relative: null, absolute: null }
|
|
2267
|
-
const left = hasValue ? Math.max(0, Math.round(100 - percent)) : null
|
|
2268
2426
|
const testKey = `${providerId}-${windowKey}`
|
|
2427
|
+
// 不传 remaining:「剩余 x%」与环上已用百分比互为补数,可自行推算(与 P2 同口径)
|
|
2269
2428
|
return h(QuotaGauge, {
|
|
2270
2429
|
testid: `token-dash-quota-cell-${testKey}`,
|
|
2271
2430
|
label: windowLabel(windowKey),
|
|
2272
2431
|
percent,
|
|
2273
2432
|
state: hasValue ? stateOf(percent, SUB_CRITICAL) : 'empty',
|
|
2274
|
-
remaining: left === null ? '—' : tr('剩余 {value}', { value: `${left}%` }),
|
|
2275
2433
|
relative: parts.relative ?? '—',
|
|
2276
2434
|
absolute: parts.absolute ?? '—',
|
|
2277
|
-
remainingTestid: `token-dash-quota-left-${testKey}`,
|
|
2278
2435
|
relativeTestid: `token-dash-quota-rel-${testKey}`,
|
|
2279
2436
|
absoluteTestid: `token-dash-quota-abs-${testKey}`,
|
|
2280
2437
|
})
|
|
@@ -2344,7 +2501,7 @@ window.__ModuleLoader__.load({
|
|
|
2344
2501
|
|
|
2345
2502
|
/** P3 整页:自取数 + 两表 + 两格卡与明细 + 底部设置胶囊。 */
|
|
2346
2503
|
function BoardPage(props) {
|
|
2347
|
-
const active =
|
|
2504
|
+
const active = useActiveProvider(props)
|
|
2348
2505
|
const [summary, setSummary] = useState(null)
|
|
2349
2506
|
const [usage, setUsage] = useState(null)
|
|
2350
2507
|
const [prefs, setPrefs] = useState(null)
|
package/index.js
CHANGED
|
@@ -233,10 +233,19 @@ export function apply(ctx) {
|
|
|
233
233
|
let state
|
|
234
234
|
let providerCache = new Map()
|
|
235
235
|
let providerCacheMeta = { at: 0, hadProviders: false, degraded: false, missSignature: null }
|
|
236
|
+
// /summary 与 /usage 共用的最小探测间隔:超过后触发一轮探测(不再阻塞响应)
|
|
237
|
+
const PROBE_MIN_INTERVAL_MS = 5000
|
|
238
|
+
// 面板一次打开会并发多个 range 请求:同 range 5s 内复用结果,避免重复全量聚合
|
|
239
|
+
const usageCache = new Map()
|
|
240
|
+
const USAGE_TTL_MS = 5000
|
|
241
|
+
// 最近一次由前端上报的 provider(切换供应商时即更新,不等记账);仅用于 VM 兜底选卡,不写 state
|
|
242
|
+
let lastSeenProvider = null
|
|
236
243
|
const cacheData = () => [...providerCache.values()].map((entry) => entry.data).filter((item) => item !== null && item !== undefined)
|
|
237
244
|
const clearProviderCache = () => {
|
|
238
245
|
providerCache.clear()
|
|
239
246
|
providerCacheMeta = { at: 0, hadProviders: false, degraded: false, missSignature: null }
|
|
247
|
+
// 快照失效时用量缓存同步失效(provider 形态/币种可能变化)
|
|
248
|
+
usageCache.clear()
|
|
240
249
|
}
|
|
241
250
|
const metaOf = (id) => cacheData().find((item) => item.id === id)
|
|
242
251
|
/** 形态判定:把当前快照交给 core,prefs / registry 的优先级由 core 决定。 */
|
|
@@ -361,7 +370,20 @@ export function apply(ctx) {
|
|
|
361
370
|
if (state === undefined) return
|
|
362
371
|
const sessionId = session?.id ?? session?.header?.id ?? 'live'
|
|
363
372
|
const record = ingest(state, sessionId, event, num(session?.header?.seedLength), kindOf)
|
|
364
|
-
if (record !== undefined)
|
|
373
|
+
if (record !== undefined) {
|
|
374
|
+
// 归属走回退层时必须留痕:跨模型会话里这是唯一能证明「有没有串到相邻模型」的证据
|
|
375
|
+
if (record.attribution === 'fallback') {
|
|
376
|
+
logger.info('collect', 'usage.attr-fallback', {
|
|
377
|
+
sessionId: record.sessionId,
|
|
378
|
+
provider: record.provider,
|
|
379
|
+
model: record.model,
|
|
380
|
+
from: record.attributionSource,
|
|
381
|
+
})
|
|
382
|
+
}
|
|
383
|
+
// 新记录改变用量口径,缓存的 usage 结果需要重算
|
|
384
|
+
usageCache.clear()
|
|
385
|
+
flushReady?.schedule?.()
|
|
386
|
+
}
|
|
365
387
|
})
|
|
366
388
|
},
|
|
367
389
|
{ global: true },
|
|
@@ -371,11 +393,16 @@ export function apply(ctx) {
|
|
|
371
393
|
const webServer = scoped.webServer
|
|
372
394
|
if (webServer === undefined) return
|
|
373
395
|
let providerRefresh = null
|
|
396
|
+
// 冷启动标记:首轮探测必须同步等待(否则空面板);完成之后一律 stale-while-revalidate
|
|
397
|
+
let providerBootstrapped = false
|
|
374
398
|
const refreshProviderCache = async () => {
|
|
375
399
|
if (providerRefresh !== null) return providerRefresh
|
|
376
400
|
providerRefresh = (async () => {
|
|
377
401
|
const probeStartedAt = Date.now()
|
|
378
402
|
const data = await readProviders(scoped, prefs, providerCache)
|
|
403
|
+
providerBootstrapped = true
|
|
404
|
+
// 探测可能改变 provider 形态/币种,用量结果需要重算
|
|
405
|
+
usageCache.clear()
|
|
379
406
|
const probeElapsed = Date.now() - probeStartedAt
|
|
380
407
|
// 慢刷新:一次探测超过 5s 会连带阻塞排队中的请求,单独留痕便于定位是哪一轮、哪些源拖慢
|
|
381
408
|
if (probeElapsed > 5000) {
|
|
@@ -383,6 +410,7 @@ export function apply(ctx) {
|
|
|
383
410
|
probeMs: probeElapsed,
|
|
384
411
|
misses: (data.misses ?? []).length,
|
|
385
412
|
failures: (data.failures ?? []).map((item) => item.id),
|
|
413
|
+
slowest: data.slowest ?? null,
|
|
386
414
|
})
|
|
387
415
|
}
|
|
388
416
|
const hadProviders = providerCacheMeta.hadProviders === true || data.length > 0
|
|
@@ -423,6 +451,20 @@ export function apply(ctx) {
|
|
|
423
451
|
})().finally(() => { providerRefresh = null })
|
|
424
452
|
return providerRefresh
|
|
425
453
|
}
|
|
454
|
+
const cachedUsage = (range, now) => {
|
|
455
|
+
const hit = usageCache.get(range)
|
|
456
|
+
return hit !== undefined && now - hit.at < USAGE_TTL_MS ? hit.data : null
|
|
457
|
+
}
|
|
458
|
+
// 三态门卫:fresh 缓存新鲜 / bootstrap 冷启动同步等待 / background 后台去重刷新
|
|
459
|
+
const ensureProviderCache = async () => {
|
|
460
|
+
if (Date.now() - providerCacheMeta.at <= PROBE_MIN_INTERVAL_MS) return 'fresh'
|
|
461
|
+
if (providerBootstrapped === true) {
|
|
462
|
+
void refreshProviderCache().catch(() => { /* 后台探测异常不进请求链 */ })
|
|
463
|
+
return 'background'
|
|
464
|
+
}
|
|
465
|
+
await refreshProviderCache().catch(() => { /* 首轮失败按空缓存构建,UI 既有重试兜底 */ })
|
|
466
|
+
return 'bootstrap'
|
|
467
|
+
}
|
|
426
468
|
const off = webServer.register({
|
|
427
469
|
kind: 'prefix',
|
|
428
470
|
path: ROUTE_PREFIX,
|
|
@@ -447,13 +489,17 @@ export function apply(ctx) {
|
|
|
447
489
|
await ready
|
|
448
490
|
if (url.pathname === `${ROUTE_PREFIX}/summary` && req.method === 'GET') {
|
|
449
491
|
const startedAt = Date.now()
|
|
492
|
+
// active 是前端当前选中的 provider:只用于选卡口径,不写回 state(记账语义不动)
|
|
493
|
+
const activeParam = url.searchParams.get('active')
|
|
494
|
+
if (typeof activeParam === 'string' && activeParam !== '') lastSeenProvider = activeParam
|
|
450
495
|
let probeMs = 0
|
|
451
|
-
|
|
496
|
+
let probeMode = 'fresh'
|
|
497
|
+
if (Date.now() - providerCacheMeta.at > PROBE_MIN_INTERVAL_MS) {
|
|
452
498
|
const probeStartedAt = Date.now()
|
|
453
|
-
await
|
|
454
|
-
probeMs = Date.now() - probeStartedAt
|
|
499
|
+
probeMode = await ensureProviderCache()
|
|
500
|
+
if (probeMode !== 'background') probeMs = Date.now() - probeStartedAt
|
|
455
501
|
}
|
|
456
|
-
const summary = buildSummary(state, prefs, Date.now(), cacheData())
|
|
502
|
+
const summary = buildSummary(state, prefs, Date.now(), cacheData(), activeParam, lastSeenProvider)
|
|
457
503
|
summary.version = CURRENT_VERSION
|
|
458
504
|
summary.refreshMs = prefs.refreshMs
|
|
459
505
|
summary.providersDegraded = providerCacheMeta.degraded === true
|
|
@@ -463,6 +509,10 @@ export function apply(ctx) {
|
|
|
463
509
|
api: summary.providers.filter((item) => item.kind === 'api').length,
|
|
464
510
|
subscription: summary.providers.filter((item) => item.kind === 'subscription').length,
|
|
465
511
|
probeMs,
|
|
512
|
+
probe: probeMode,
|
|
513
|
+
// 诊断:前端上报的 active 与最终选中的 provider,用于定位切换不生效的层级
|
|
514
|
+
active: activeParam ?? null,
|
|
515
|
+
currentProviderId: summary.currentProviderId ?? null,
|
|
466
516
|
durationMs: Date.now() - startedAt,
|
|
467
517
|
})
|
|
468
518
|
json(res, 200, { ok: true, data: summary })
|
|
@@ -476,12 +526,16 @@ export function apply(ctx) {
|
|
|
476
526
|
}
|
|
477
527
|
const startedAt = Date.now()
|
|
478
528
|
let probeMs = 0
|
|
479
|
-
|
|
529
|
+
let probeMode = 'fresh'
|
|
530
|
+
if (Date.now() - providerCacheMeta.at > PROBE_MIN_INTERVAL_MS) {
|
|
480
531
|
const probeStartedAt = Date.now()
|
|
481
|
-
await
|
|
482
|
-
probeMs = Date.now() - probeStartedAt
|
|
532
|
+
probeMode = await ensureProviderCache()
|
|
533
|
+
if (probeMode !== 'background') probeMs = Date.now() - probeStartedAt
|
|
483
534
|
}
|
|
484
|
-
|
|
535
|
+
// 同 range 5s 内复用结果:面板打开时的重复请求不再重复全量聚合
|
|
536
|
+
const hit = cachedUsage(range, Date.now())
|
|
537
|
+
const usage = hit ?? buildUsage(state, prefs, range, Date.now(), cacheData())
|
|
538
|
+
if (hit === null) usageCache.set(range, { at: Date.now(), data: usage })
|
|
485
539
|
logger.info('vm', 'usage', {
|
|
486
540
|
range,
|
|
487
541
|
models: usage.models.length,
|
|
@@ -492,6 +546,8 @@ export function apply(ctx) {
|
|
|
492
546
|
points: usage.series.length,
|
|
493
547
|
seriesCurrencies: Object.keys(usage.series.reduce((acc, point) => Object.assign(acc, point.cost), {})).length,
|
|
494
548
|
probeMs,
|
|
549
|
+
probe: probeMode,
|
|
550
|
+
cached: hit !== null,
|
|
495
551
|
durationMs: Date.now() - startedAt,
|
|
496
552
|
})
|
|
497
553
|
json(res, 200, { ok: true, data: usage })
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-token-dash",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"description": "DeepSeek Harness Token
|
|
3
|
+
"version": "2.5.1",
|
|
4
|
+
"description": "DeepSeek Harness Token 与费用看板:8 家供应商开箱即用,按供应商查看预算、订阅配额(GLM / Kimi / OpenCode Go / Command Code)与账户余额;Pill、浮层、整页三处呈现费用与真实 Tokens、缓存命中率与用量趋势,成本趋势双币种双轴;填第三方 API Key 的自建 / 中转 / 本地兼容服务同样能记账,未定价模型不按 0 元计,可导出 / 导入本地 JSON 备份。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
7
7
|
"exports": {
|
|
@@ -27,9 +27,13 @@
|
|
|
27
27
|
"deepseek",
|
|
28
28
|
"deepseek-harness",
|
|
29
29
|
"dsh",
|
|
30
|
+
"dsh-plugin",
|
|
30
31
|
"token",
|
|
31
32
|
"usage",
|
|
32
|
-
"
|
|
33
|
+
"cost",
|
|
34
|
+
"budget",
|
|
35
|
+
"quota",
|
|
36
|
+
"dashboard"
|
|
33
37
|
],
|
|
34
38
|
"license": "MIT",
|
|
35
39
|
"repository": {
|
|
@@ -44,6 +48,7 @@
|
|
|
44
48
|
"test": "node --test test/unit/*.test.mjs",
|
|
45
49
|
"e2e": "node scripts/e2e.mjs",
|
|
46
50
|
"logs": "node tools/logs.mjs",
|
|
51
|
+
"stats": "node scripts/npm-stats.mjs",
|
|
47
52
|
"shots": "node tools/mock/shots.mjs",
|
|
48
53
|
"preview": "node tools/preview/render.mjs",
|
|
49
54
|
"preview:publish": "node tools/preview/render.mjs --publish",
|
package/src/adapters.js
CHANGED
|
@@ -6,6 +6,28 @@ import { normalizeProvider, providerCurrency, providerLabel } from './providers.
|
|
|
6
6
|
import { PROVIDER_SOURCES } from './quota-sources.js'
|
|
7
7
|
|
|
8
8
|
const TIMEOUT = 6000
|
|
9
|
+
// 宿主服务调用没有内置超时(2026-11-23:deepseekAccount.getBalance 曾挂起 30s)。
|
|
10
|
+
// 超时抛 HostTimeoutError,由 errorDetail 归类 host-timeout;不吞宿主真实异常。
|
|
11
|
+
const HOST_TIMEOUT = 5000
|
|
12
|
+
class HostTimeoutError extends Error {
|
|
13
|
+
constructor(label) {
|
|
14
|
+
super(`host-timeout:${label}`)
|
|
15
|
+
this.name = 'HostTimeout'
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function withHostTimeout(promise, label) {
|
|
19
|
+
let timer = null
|
|
20
|
+
try {
|
|
21
|
+
return await Promise.race([
|
|
22
|
+
promise,
|
|
23
|
+
new Promise((_, reject) => {
|
|
24
|
+
timer = setTimeout(() => reject(new HostTimeoutError(label)), HOST_TIMEOUT)
|
|
25
|
+
}),
|
|
26
|
+
])
|
|
27
|
+
} finally {
|
|
28
|
+
clearTimeout(timer)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
9
31
|
const GLM_QUOTA = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
|
|
10
32
|
const KIMI_USAGES = 'https://api.kimi.com/coding/v1/usages'
|
|
11
33
|
const KIMI_BALANCE = 'https://api.moonshot.cn/v1/users/me/balance'
|
|
@@ -91,7 +113,7 @@ async function resolveKey(ctx, names) {
|
|
|
91
113
|
if (credentials === undefined || typeof credentials.resolve !== 'function') return undefined
|
|
92
114
|
for (const name of names) {
|
|
93
115
|
try {
|
|
94
|
-
const hit = await credentials.resolve(name)
|
|
116
|
+
const hit = await withHostTimeout(credentials.resolve(name), 'credentials.resolve')
|
|
95
117
|
const value = hit?.value
|
|
96
118
|
if (typeof value === 'string' && value.trim() !== '') return { value: value.trim(), name }
|
|
97
119
|
} catch {
|
|
@@ -127,6 +149,7 @@ function errorDetail(error) {
|
|
|
127
149
|
}
|
|
128
150
|
}
|
|
129
151
|
const name = `${error?.name ?? ''} ${error?.message ?? ''}`
|
|
152
|
+
if (error?.name === 'HostTimeout') return { kind: 'host-timeout' }
|
|
130
153
|
if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
|
|
131
154
|
return { kind: 'network' }
|
|
132
155
|
}
|
|
@@ -135,7 +158,7 @@ async function deepseek(ctx) {
|
|
|
135
158
|
const account = ctx.get?.('deepseekAccount')
|
|
136
159
|
if (account !== undefined && typeof account.getBalance === 'function') {
|
|
137
160
|
try {
|
|
138
|
-
const data = await account.getBalance({ version: '1.0.2', locale: 'zh-CN', timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 })
|
|
161
|
+
const data = await withHostTimeout(account.getBalance({ version: '1.0.2', locale: 'zh-CN', timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 }), 'deepseekAccount.getBalance')
|
|
139
162
|
if (data?.status === 'ready') {
|
|
140
163
|
const wallets = [...(Array.isArray(data.value) ? data.value : Object.values(data.value ?? {})), ...(data.bonusWallets ?? [])]
|
|
141
164
|
const amount = wallets.filter((wallet) => wallet?.currency === undefined || wallet.currency === 'CNY')
|
|
@@ -363,12 +386,16 @@ async function readCachedSource(ctx, prefs, source, cache) {
|
|
|
363
386
|
const promise = readSource(ctx, prefs, source, cached?.data ?? null)
|
|
364
387
|
.then((data) => {
|
|
365
388
|
const at = Date.now()
|
|
366
|
-
|
|
389
|
+
// null 且有旧值时降级沿用旧快照(保留 _stale 标记),TTL 仍按失败档 10s 重试;
|
|
390
|
+
// 无旧值的确定性 :none 维持 data=null,避免掩盖"Key 真被删除"。
|
|
391
|
+
const stored = data === null && cached?.data != null ? { ...cached.data, _stale: true } : data
|
|
392
|
+
cache.set(source.id, { at, ok: data !== null && data?._rateLimited !== true, data: stored, promise: null, until: cacheExpiry(data, at) })
|
|
367
393
|
return data
|
|
368
394
|
})
|
|
369
395
|
.catch((error) => {
|
|
370
396
|
const at = Date.now()
|
|
371
|
-
|
|
397
|
+
const stored = cached?.data != null ? { ...cached.data, _stale: true } : null
|
|
398
|
+
cache.set(source.id, { at, ok: false, data: stored, promise: null, until: at + TTL_FAIL })
|
|
372
399
|
throw error
|
|
373
400
|
})
|
|
374
401
|
cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise, until: cached?.until ?? null })
|
|
@@ -402,6 +429,7 @@ export function toSnapshot(entry) {
|
|
|
402
429
|
...(entry.channel === undefined ? {} : { channel: entry.channel }),
|
|
403
430
|
...(entry._channelError === undefined ? {} : { channelError: entry._channelError }),
|
|
404
431
|
rateLimited: entry._rateLimited === true,
|
|
432
|
+
stale: entry._stale === true,
|
|
405
433
|
mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
|
|
406
434
|
windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
|
|
407
435
|
error,
|
|
@@ -417,7 +445,15 @@ export function toSnapshot(entry) {
|
|
|
417
445
|
* 缓存按源保存在调用方传入的 Map 中:成功 60s、失败 10s,并发复用 promise。
|
|
418
446
|
*/
|
|
419
447
|
export async function readProviders(ctx, prefs, cache = new Map()) {
|
|
420
|
-
const
|
|
448
|
+
const timings = []
|
|
449
|
+
const results = await Promise.allSettled(PROVIDER_SOURCES.map(async (source) => {
|
|
450
|
+
const startedAt = Date.now()
|
|
451
|
+
try {
|
|
452
|
+
return await readCachedSource(ctx, prefs, source, cache)
|
|
453
|
+
} finally {
|
|
454
|
+
timings.push({ id: source.id, ms: Date.now() - startedAt })
|
|
455
|
+
}
|
|
456
|
+
}))
|
|
421
457
|
const out = []
|
|
422
458
|
const misses = []
|
|
423
459
|
const failures = []
|
|
@@ -442,6 +478,8 @@ export async function readProviders(ctx, prefs, cache = new Map()) {
|
|
|
442
478
|
})
|
|
443
479
|
out.misses = misses
|
|
444
480
|
out.failures = failures
|
|
481
|
+
// 缓存命中的源计时趋近 0,最慢者即真实拖慢探测的源
|
|
482
|
+
out.slowest = timings.length === 0 ? null : timings.reduce((a, b) => (b.ms > a.ms ? b : a))
|
|
445
483
|
return out
|
|
446
484
|
}
|
|
447
485
|
|
|
@@ -566,3 +604,5 @@ export function logAdapterFailures(log, failures = []) {
|
|
|
566
604
|
}
|
|
567
605
|
|
|
568
606
|
export { KIMI_USAGES, GLM_QUOTA, KIMI_BALANCE, OPENROUTER_CREDITS }
|
|
607
|
+
// 内部工具导出:仅用于单元测试验证超时与降级行为
|
|
608
|
+
export { HostTimeoutError, withHostTimeout, errorDetail }
|
package/src/collect.js
CHANGED
|
@@ -20,14 +20,28 @@ export function recordFromEvent(event) {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* #43:message.source 缺失时的归属回退层(形状参考 dsh-ui-usage-billing aggregate)。
|
|
25
|
+
* 两级信号:`request/header` 是「这次请求实际用的模型」,`model/selection` 是用户的模型选择;
|
|
26
|
+
* 后者只在前者尚未出现时兜底,避免宿主漏发请求头时整段用量落空。
|
|
27
|
+
* 返回值带 `source`,供 `ingest` 标记回退来源并落日志。
|
|
28
|
+
*/
|
|
24
29
|
export function headerFromEvent(event) {
|
|
25
|
-
if (event?.type
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
if (event?.type === 'request/header') {
|
|
31
|
+
const config = event.data?.header?.config ?? event.data?.config
|
|
32
|
+
const provider = typeof config?.provider === 'string' && config.provider !== '' ? config.provider : undefined
|
|
33
|
+
const model = typeof config?.model === 'string' && config.model !== '' ? config.model : undefined
|
|
34
|
+
if (provider === undefined && model === undefined) return undefined
|
|
35
|
+
return { provider, model, source: 'request-header' }
|
|
36
|
+
}
|
|
37
|
+
if (event?.type === 'model/selection') {
|
|
38
|
+
const data = event.data ?? {}
|
|
39
|
+
const provider = typeof data.provider === 'string' && data.provider !== '' ? data.provider : undefined
|
|
40
|
+
const model = typeof data.model === 'string' && data.model !== '' ? data.model : undefined
|
|
41
|
+
if (provider === undefined && model === undefined) return undefined
|
|
42
|
+
return { provider, model, source: 'model-selection' }
|
|
43
|
+
}
|
|
44
|
+
return undefined
|
|
31
45
|
}
|
|
32
46
|
|
|
33
47
|
/** 入账一条事件;返回记录或 undefined。`kindOf` 缺省时 `addRecord` 走 registry 兜底。 */
|
|
@@ -47,12 +61,20 @@ export function ingest(state, sessionId, event, seedFloor = 0, kindOf) {
|
|
|
47
61
|
return undefined
|
|
48
62
|
}
|
|
49
63
|
record.sessionId = sessionId
|
|
50
|
-
// #43:usage 事件无 message.source
|
|
64
|
+
// #43:usage 事件无 message.source 时,回退最近一次归属信号(请求头优先,其次模型选择)。
|
|
65
|
+
// 回退命中的记录带 attribution='fallback',调用方据此落 usage.attr-fallback 日志,
|
|
66
|
+
// 让「跨模型会话是否串行归因」可以被日志直接回答,而不是靠目录复算反推。
|
|
51
67
|
if (record.provider === 'unknown' || record.model === '') {
|
|
52
68
|
const fallback = state.headers[sessionId]
|
|
53
69
|
if (fallback !== undefined) {
|
|
54
|
-
|
|
55
|
-
|
|
70
|
+
const providerMissing = record.provider === 'unknown' && fallback.provider !== undefined
|
|
71
|
+
const modelMissing = record.model === '' && fallback.model !== undefined
|
|
72
|
+
if (providerMissing) record.provider = fallback.provider
|
|
73
|
+
if (modelMissing) record.model = fallback.model
|
|
74
|
+
if (providerMissing || modelMissing) {
|
|
75
|
+
record.attribution = 'fallback'
|
|
76
|
+
record.attributionSource = fallback.source ?? 'request-header'
|
|
77
|
+
}
|
|
56
78
|
}
|
|
57
79
|
}
|
|
58
80
|
addRecord(state, record, kindOf)
|
|
@@ -67,6 +89,7 @@ export async function backfill(ctx, state, kindOf) {
|
|
|
67
89
|
}
|
|
68
90
|
let sessions = 0
|
|
69
91
|
let records = 0
|
|
92
|
+
let fallbacks = 0
|
|
70
93
|
const providerByModel = new Map()
|
|
71
94
|
const list = await persistence.list()
|
|
72
95
|
for (const header of Array.isArray(list) ? list : []) {
|
|
@@ -86,7 +109,11 @@ export async function backfill(ctx, state, kindOf) {
|
|
|
86
109
|
providers.add(source.provider)
|
|
87
110
|
providerByModel.set(model, providers)
|
|
88
111
|
}
|
|
89
|
-
|
|
112
|
+
const record = ingest(state, id, event, seed, kindOf)
|
|
113
|
+
if (record !== undefined) {
|
|
114
|
+
records += 1
|
|
115
|
+
if (record.attribution === 'fallback') fallbacks += 1
|
|
116
|
+
}
|
|
90
117
|
}
|
|
91
118
|
} catch {
|
|
92
119
|
// 单个会话失败不影响其余会话
|
|
@@ -99,5 +126,5 @@ export async function backfill(ctx, state, kindOf) {
|
|
|
99
126
|
}
|
|
100
127
|
}
|
|
101
128
|
reattributeUnknown(state, providerByModel)
|
|
102
|
-
return { sessions, records, degraded: null }
|
|
129
|
+
return { sessions, records, fallbacks, degraded: null }
|
|
103
130
|
}
|
package/src/core.js
CHANGED
|
@@ -644,7 +644,7 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
|
|
|
644
644
|
}
|
|
645
645
|
}
|
|
646
646
|
|
|
647
|
-
export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
647
|
+
export function buildSummary(state, prefs, now, providerInfoInput, activeProvider = null, recentProvider = null) {
|
|
648
648
|
const month = localMonthKey(now)
|
|
649
649
|
const todayKey = localDayKey(now)
|
|
650
650
|
const providerMap = new Map()
|
|
@@ -659,7 +659,8 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
659
659
|
|
|
660
660
|
for (const item of providerInfo) {
|
|
661
661
|
// mode 是快照内部字段,剥离后不进入 VM
|
|
662
|
-
|
|
662
|
+
// _stale 是快照内部字段:剥离后以只读 stale 进 VM(与 mode 同口径)
|
|
663
|
+
const { plans: legacyPlans, mode: _mode, _stale: _rawStale, ...info } = item
|
|
663
664
|
const id = normalizeProvider(info.id ?? info.provider)
|
|
664
665
|
if (id === 'unknown' || hidden.has(id)) continue
|
|
665
666
|
const kind = resolveProviderKind(state, prefs, id, item)
|
|
@@ -669,6 +670,7 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
669
670
|
...base,
|
|
670
671
|
...info,
|
|
671
672
|
id,
|
|
673
|
+
stale: _rawStale === true,
|
|
672
674
|
name: info.name ?? providerLabel(id),
|
|
673
675
|
kind,
|
|
674
676
|
canSubscribe: canBeSubscription(id),
|
|
@@ -682,7 +684,7 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
682
684
|
|
|
683
685
|
// #41/#42:unknown 行按模型名前缀视图层归因(不改 daily.json);models 与 provider.usage 均为当月口径(#42 回退跨月累计)
|
|
684
686
|
const unpriced = []
|
|
685
|
-
const accumulate = (providerId, modelId, row, isToday) => {
|
|
687
|
+
const accumulate = (providerId, modelId, row, isToday, dayTs) => {
|
|
686
688
|
const meta = providerInfo.find((item) => normalizeProvider(item.id ?? item.provider) === providerId)
|
|
687
689
|
const kind = resolveProviderKind(state, prefs, providerId, meta)
|
|
688
690
|
const provider = providerMap.get(providerId) ?? providerEmpty(providerId, kind)
|
|
@@ -737,8 +739,18 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
737
739
|
const tokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
|
|
738
740
|
provider.usage.monthTokens += tokens
|
|
739
741
|
provider.usage.monthCost += billable ? num(row.cost) : 0
|
|
740
|
-
// 订阅行的目录价不算支出,但按「本月估算」单独累计,供订阅卡展示(D-02
|
|
741
|
-
|
|
742
|
+
// 订阅行的目录价不算支出,但按「本月估算」单独累计,供订阅卡展示(D-02)。
|
|
743
|
+
// Issue #3:订阅行存量 cost 恒 0(REQ-12),不能再读 row.cost;
|
|
744
|
+
// 改为与 buildUsage · add 完全同口径——按当日 ts 现算估算,缺价行跳过不计。
|
|
745
|
+
if (!billable) {
|
|
746
|
+
const estimatePrice = resolvePrice(modelId, providerId, dayTs)
|
|
747
|
+
if (estimatePrice !== null) {
|
|
748
|
+
provider.usage.monthEstimate += costOf({
|
|
749
|
+
ts: dayTs, provider: providerId, model: modelId,
|
|
750
|
+
input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
|
|
751
|
+
})
|
|
752
|
+
}
|
|
753
|
+
}
|
|
742
754
|
provider.usage.requests += num(row.requests)
|
|
743
755
|
if (isToday) {
|
|
744
756
|
provider.usage.todayTokens += tokens
|
|
@@ -757,13 +769,13 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
757
769
|
for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
|
|
758
770
|
const owner = providerFromModel(rawModel)
|
|
759
771
|
if (owner === null || hidden.has(owner)) continue
|
|
760
|
-
accumulate(owner, normalizeModel(rawModel), row, isToday)
|
|
772
|
+
accumulate(owner, normalizeModel(rawModel), row, isToday, Date.parse(dayKey))
|
|
761
773
|
}
|
|
762
774
|
continue
|
|
763
775
|
}
|
|
764
776
|
if (hidden.has(providerId)) continue
|
|
765
777
|
for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
|
|
766
|
-
accumulate(providerId, normalizeModel(rawModel), row, isToday)
|
|
778
|
+
accumulate(providerId, normalizeModel(rawModel), row, isToday, Date.parse(dayKey))
|
|
767
779
|
}
|
|
768
780
|
}
|
|
769
781
|
}
|
|
@@ -831,11 +843,25 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
831
843
|
}
|
|
832
844
|
provider.usage.todayCost = round2(provider.usage.todayCost)
|
|
833
845
|
provider.usage.monthCost = round2(provider.usage.monthCost)
|
|
846
|
+
// 估算值与 monthCost 同步收敛到分位,保证与 /usage 明细口径逐位可对账(Issue #3)
|
|
847
|
+
provider.usage.monthEstimate = round2(provider.usage.monthEstimate ?? 0)
|
|
834
848
|
return { ...provider, budget }
|
|
835
849
|
})
|
|
850
|
+
// 选卡口径三级回退:前端显式选择 → 最近观测 → 记账口径 → 首卡。
|
|
851
|
+
// 记账口径 state.currentProvider 只在记账时更新(切供应商未发消息则仍是旧值),不能单独作为依据。
|
|
852
|
+
// 必须比 providers.sort 先算:后面排序要用 current 作为首卡基准。
|
|
853
|
+
// 必须先经 normalizeProvider 归一:宿主路由名与快照 id 不一定同字面
|
|
854
|
+
// (如宿主报 deepseek-account,快照里是 deepseek-official),直接字面比对会落空。
|
|
855
|
+
const pick = (id) => {
|
|
856
|
+
const normalized = normalizeProvider(id)
|
|
857
|
+
if (normalized === 'unknown') return null
|
|
858
|
+
return providers.some((p) => p.id === normalized) ? normalized : null
|
|
859
|
+
}
|
|
860
|
+
// 记账口径也要校验:provider 可能已从配置移除(历史 daily.json 仍留着旧 id)
|
|
861
|
+
const current = pick(activeProvider) ?? pick(recentProvider) ?? pick(state.currentProvider) ?? providers[0]?.id ?? null
|
|
836
862
|
providers.sort((a, b) => {
|
|
837
|
-
if (a.id ===
|
|
838
|
-
if (b.id ===
|
|
863
|
+
if (a.id === current) return -1
|
|
864
|
+
if (b.id === current) return 1
|
|
839
865
|
return b.usage.todayCost - a.usage.todayCost
|
|
840
866
|
})
|
|
841
867
|
|
|
@@ -888,7 +914,6 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
888
914
|
cost: sum.cost + provider.usage.todayCost,
|
|
889
915
|
requests: sum.requests + provider.usage.requests,
|
|
890
916
|
}), { tokens: 0, cost: 0, requests: 0 })
|
|
891
|
-
const current = state.currentProvider ?? providers[0]?.id ?? null
|
|
892
917
|
|
|
893
918
|
return {
|
|
894
919
|
month,
|
|
@@ -906,6 +931,10 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
|
|
|
906
931
|
providers,
|
|
907
932
|
apiTotals,
|
|
908
933
|
currentProviderId: current,
|
|
934
|
+
// 归一化后的「前端当前选中」:宿主上报的是路由名(如 deepseek-account),
|
|
935
|
+
// 而 providers[].id 是内部 id(deepseek-official)。回显归一化值,
|
|
936
|
+
// 让 UI 无需知道别名规则即可选卡(保持「UI 不认识 provider」的边界)。
|
|
937
|
+
activeProviderId: pick(activeProvider),
|
|
909
938
|
breakdown: { models },
|
|
910
939
|
pricingLinks: pricingLinks(),
|
|
911
940
|
showBalance: prefs?.showBalance !== false,
|