dsh-token-dash 2.2.0 → 2.3.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/AGENTS.md +3 -0
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/client.js +326 -89
- package/index.js +75 -17
- package/locale/en.json +7 -2
- package/locale/zh.json +7 -2
- package/package.json +2 -2
package/AGENTS.md
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
|
|
22
22
|
- **未获明确授权不得改代码**。用户只要求“更新文档 / 记 issue / 完善设计 / 检查文档”时,仅可改 `docs/`、`AGENTS.md`、`README*`;禁止编辑 `client.js`、`index.js`、`src/`、`test/`、`scripts/`、`tools/`、`package.json`、`locale/`,也不得测试、打包或安装插件。
|
|
23
23
|
- 代码实施需明确口令(“开始修改 / 可以改代码 / 执行 / 开始开发”);文档确认与代码实施分轮进行,不混在同一轮。
|
|
24
|
+
- **issue 文档必须先于代码**(强制顺序,无例外):任何带 issue 编号的改动,顺序固定为「先写 / 更新 issue 文档(现象、根因、期望、影响面、验收方式)→ 再改代码」。禁止先改代码再补 issue,也不允许把 issue 与代码写在同一次编辑里。
|
|
25
|
+
- issue 已终态(`[已修复]` / `[已放弃]`)后再次动手,必须先按 plan-workflow 的重开规则恢复非终态,再改代码。
|
|
24
26
|
- plan / checklist 记录不等于实施授权;发现文档与代码不一致时先报告,未获授权不得顺手修。
|
|
25
27
|
|
|
26
28
|
## 3. 代码与架构约束
|
|
@@ -39,6 +41,7 @@
|
|
|
39
41
|
- 同一时间只推进一个主 feature;优先恢复已有 plan,不新建重复计划。
|
|
40
42
|
- 施工与走查用 `checklist` skill 维护 `docs/checklist/active/`(单层,不建项目域子目录);回写完成 + 用户明确指令后才归档。
|
|
41
43
|
- 每次实现完成、测试通过或发布后,回写 plan 的 §3.0/§5 与 checklist 的阶段 / 测试 / 执行日志,避免状态只留在对话里。
|
|
44
|
+
- 固定落地顺序:**issue 文档 → 代码 → 测试 → 回写验收**。issue 段先落定现象 / 根因 / 期望 / 影响面 / 验收方式,代码只实现已写下的结论;实现中发现结论有误,先回改 issue 再继续改代码。
|
|
42
45
|
|
|
43
46
|
### 4.2 预览与原型
|
|
44
47
|
|
package/README.en.md
CHANGED
|
@@ -111,7 +111,7 @@ dsh plugin --profile desktop add github:spartawhy117/dsh-token-dash
|
|
|
111
111
|
dsh plugin --profile desktop add /path/to/dsh-token-dash-x.y.z.tgz
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
-
Update: run `update` with the same name, or use the
|
|
114
|
+
Update: run `update` with the same name, or use the update button on the right of “Pricing & version” in settings. The plugin checks once at every DSH start and every 4 hours while running; when a new version exists the button shows the version number directly, so one click is enough. Remove: run `remove` with the same name; data stays in `$DSH_HOME/dsh-token-dash/`.
|
|
115
115
|
|
|
116
116
|
> If the plugin disappears from the profile after a DSH 0.2.2 upgrade, reinstall the same tarball. The ledger and settings are not deleted with the plugin package.
|
|
117
117
|
|
package/README.md
CHANGED
|
@@ -110,7 +110,7 @@ dsh plugin --profile desktop add github:spartawhy117/dsh-token-dash
|
|
|
110
110
|
dsh plugin --profile desktop add /path/to/dsh-token-dash-x.y.z.tgz
|
|
111
111
|
```
|
|
112
112
|
|
|
113
|
-
更新:`update` 同名命令(npm / github:
|
|
113
|
+
更新:`update` 同名命令(npm / github: 各自同名),或在插件设置页「价格与版本」右侧的更新按钮内完成——每次启动 DSH 与运行中每 4 小时会自动检查,发现新版本时按钮直接显示版本号,点一下即可。卸载:`remove` 同名命令,数据保留在 `$DSH_HOME/dsh-token-dash/`。
|
|
114
114
|
|
|
115
115
|
> DSH 0.2.2 升级后如果插件从 profile 消失,重装同一个 tarball 即可;账本与设置不随插件包删除。
|
|
116
116
|
|
package/client.js
CHANGED
|
@@ -89,7 +89,11 @@ window.__ModuleLoader__.load({
|
|
|
89
89
|
'导入中…': 'Importing…', '数据已导出': 'Data exported', '数据导出失败': 'Data export failed',
|
|
90
90
|
'已导入 {month} 数据': 'Imported {month} data', '导入失败:{reason}': 'Import failed: {reason}',
|
|
91
91
|
'检查失败': 'Check failed', '未发布': 'Not published', '已是最新': 'Up to date',
|
|
92
|
-
'发现 {version}': 'Found {version}', '更新': 'Update',
|
|
92
|
+
'发现 {version}': 'Found {version}', '更新': 'Update',
|
|
93
|
+
'重试': 'Retry', '更新中': 'Updating',
|
|
94
|
+
'更新检查失败': 'Update check failed',
|
|
95
|
+
'版本号不合法': 'Invalid version', '该版本未发布': 'Version not published',
|
|
96
|
+
'版本未变化': 'Version unchanged', '未找到 dsh 命令': 'dsh command not found',
|
|
93
97
|
'复制命令': 'Copy command', '命令已复制': 'Command copied', '复制失败': 'Copy failed',
|
|
94
98
|
'设置加载中…': 'Loading settings…', '检查更新': 'Check for updates',
|
|
95
99
|
'更新失败({reason})': 'Update failed ({reason})',
|
|
@@ -271,18 +275,45 @@ window.__ModuleLoader__.load({
|
|
|
271
275
|
let updateRequest = null
|
|
272
276
|
let updateResetTimer = null
|
|
273
277
|
let autoUpdateChecked = false
|
|
278
|
+
/** 更新检测节奏:UI 稳定 30s 后启动检测(无条件),运行中每 4h 一次。 */
|
|
279
|
+
const UPDATE_STARTUP_DELAY = 30_000
|
|
280
|
+
const UPDATE_INTERVAL_MS = 4 * 60 * 60 * 1000
|
|
281
|
+
/**
|
|
282
|
+
* 启动延迟可被 localStorage 覆盖,仅供 e2e 缩短等待。它只改变「何时开始检测」,
|
|
283
|
+
* 不改变检测内容与判定结果——检测本身仍走真实 registry,因此不构成测试造假。
|
|
284
|
+
*/
|
|
285
|
+
const updateStartupDelay = () => {
|
|
286
|
+
try {
|
|
287
|
+
const override = Number(globalThis.localStorage?.getItem(UPDATE_DELAY_KEY))
|
|
288
|
+
if (Number.isFinite(override) && override >= 0) return override
|
|
289
|
+
} catch { /* 隐私模式忽略 */ }
|
|
290
|
+
return UPDATE_STARTUP_DELAY
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* 更新检测的时间戳存在 localStorage:apply 时看板组件可能还没挂载,
|
|
294
|
+
* 拿不到 /prefs 的结果,用 localStorage 才能保证启动补检不依赖组件渲染顺序。
|
|
295
|
+
*/
|
|
296
|
+
const UPDATE_TS_KEY = 'td:updateCheckedAt'
|
|
297
|
+
const UPDATE_DELAY_KEY = 'td:updateStartupDelay'
|
|
298
|
+
const readStoredTs = () => {
|
|
299
|
+
try { return Number(globalThis.localStorage?.getItem(UPDATE_TS_KEY)) || 0 } catch { return 0 }
|
|
300
|
+
}
|
|
301
|
+
const writeStoredTs = (at) => {
|
|
302
|
+
try { globalThis.localStorage?.setItem(UPDATE_TS_KEY, String(at)) } catch { /* 隐私模式忽略 */ }
|
|
303
|
+
}
|
|
274
304
|
|
|
275
305
|
function emitUpdate(patch) {
|
|
276
306
|
updateSnapshot = { ...updateSnapshot, ...patch }
|
|
277
307
|
for (const listener of updateListeners) listener()
|
|
278
308
|
}
|
|
279
309
|
|
|
280
|
-
function resetUpdateLater() {
|
|
310
|
+
function resetUpdateLater(delayMs = 1600) {
|
|
281
311
|
if (updateResetTimer !== null) clearTimeout(updateResetTimer)
|
|
282
312
|
updateResetTimer = setTimeout(() => {
|
|
283
313
|
updateResetTimer = null
|
|
284
|
-
if (updateSnapshot.phase === 'done') emitUpdate({ phase: 'idle', text: null, latest: null, command: null })
|
|
285
|
-
|
|
314
|
+
if (updateSnapshot.phase === 'done') emitUpdate({ phase: 'idle', text: null, latest: null, command: null, errorKind: null })
|
|
315
|
+
else if (updateSnapshot.phase === 'autoError') emitUpdate({ phase: 'idle', text: null, errorKind: null })
|
|
316
|
+
}, delayMs)
|
|
286
317
|
}
|
|
287
318
|
|
|
288
319
|
function useUpdateSnapshot() {
|
|
@@ -302,43 +333,92 @@ window.__ModuleLoader__.load({
|
|
|
302
333
|
emitUpdate({ phase: 'checking', text: null, command: null })
|
|
303
334
|
updateRequest = (async () => {
|
|
304
335
|
try {
|
|
305
|
-
|
|
336
|
+
// 启动检测与手动点击都强刷:命中宿主 5min 缓存就等于没检查
|
|
337
|
+
const data = await getJson('/update?refresh=1')
|
|
306
338
|
if (data.published === false) {
|
|
307
339
|
if (manual) { emitUpdate({ phase: 'done', text: tr('未发布') }); resetUpdateLater() }
|
|
308
340
|
else emitUpdate({ phase: 'idle', text: null })
|
|
309
341
|
} else if (data.hasUpdate) {
|
|
310
|
-
emitUpdate({ phase:
|
|
342
|
+
emitUpdate({ phase: 'available', latest: data.latest, text: null })
|
|
343
|
+
// 手动检测命中更新:直接开始安装,不再弹二次确认
|
|
344
|
+
if (manual) void installUpdateRequest()
|
|
311
345
|
} else if (manual) {
|
|
312
346
|
emitUpdate({ phase: 'done', text: tr('已是最新') })
|
|
313
347
|
resetUpdateLater()
|
|
314
348
|
} else {
|
|
315
349
|
emitUpdate({ phase: 'idle', text: null })
|
|
316
350
|
}
|
|
317
|
-
} catch {
|
|
318
|
-
|
|
319
|
-
|
|
351
|
+
} catch (error) {
|
|
352
|
+
// 失败分级:手动要强提示(按钮转「重试」),自动只给低强度文字且 5s 自动消失。
|
|
353
|
+
// 自动路径不能让按钮变红——用户没做任何操作,页面不该忽然报警。
|
|
354
|
+
const reason = String(error?.message ?? error)
|
|
355
|
+
const auto = !manual
|
|
356
|
+
emitUpdate({
|
|
357
|
+
phase: auto ? 'autoError' : 'error',
|
|
358
|
+
text: auto ? tr('更新检查失败') : tr('检查失败'),
|
|
359
|
+
command: null,
|
|
360
|
+
errorKind: reason,
|
|
361
|
+
})
|
|
362
|
+
// 自动检测失败提示留 5s:够看清,又不长期占位
|
|
363
|
+
if (auto) resetUpdateLater(5000)
|
|
320
364
|
} finally {
|
|
321
365
|
updateRequest = null
|
|
366
|
+
markUpdateCheckedAt()
|
|
322
367
|
}
|
|
323
368
|
})()
|
|
324
369
|
return updateRequest
|
|
325
370
|
}
|
|
326
371
|
|
|
372
|
+
/** 检测完成(无论成功失败)都记时间戳:失败也计一次,避免失败后立刻又发请求。 */
|
|
373
|
+
function markUpdateCheckedAt() {
|
|
374
|
+
writeStoredTs(Date.now())
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** 调度日志:区分「按周期跳过」与「根本没跑」,否则线上无法判断更新为何不提示。 */
|
|
378
|
+
function logUpdateSchedule(event, meta) {
|
|
379
|
+
try {
|
|
380
|
+
void fetch(`${API}/log`, {
|
|
381
|
+
method: 'POST',
|
|
382
|
+
headers: { 'content-type': 'application/json' },
|
|
383
|
+
body: JSON.stringify({ module: 'update', event, meta }),
|
|
384
|
+
})
|
|
385
|
+
} catch { /* 日志失败不影响调度 */ }
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** 安装失败原因 → 用户可读文案;未知原因保留原文而不是吞成 unknown。 */
|
|
389
|
+
const INSTALL_REASON_TEXT = {
|
|
390
|
+
'invalid-version': '版本号不合法',
|
|
391
|
+
unpublished: '该版本未发布',
|
|
392
|
+
'version-unchanged': '版本未变化',
|
|
393
|
+
'cli-not-found': '未找到 dsh 命令',
|
|
394
|
+
}
|
|
395
|
+
const installReasonText = (reason) => INSTALL_REASON_TEXT[reason] ?? (String(reason ?? '').trim() || 'unknown')
|
|
396
|
+
|
|
327
397
|
async function installUpdateRequest() {
|
|
328
398
|
if (updateSnapshot.phase === 'installing') return
|
|
399
|
+
const target = updateSnapshot.latest
|
|
329
400
|
emitUpdate({ phase: 'installing', text: null })
|
|
330
401
|
try {
|
|
331
|
-
|
|
402
|
+
// 把用户看到的版本原样交给宿主,避免宿主重新查 registry 导致装到别的版本
|
|
403
|
+
const res = await fetch(`${API}/update/install`, {
|
|
404
|
+
method: 'POST',
|
|
405
|
+
headers: { accept: 'application/json', 'content-type': 'application/json' },
|
|
406
|
+
body: JSON.stringify(target === null ? {} : { version: target }),
|
|
407
|
+
})
|
|
332
408
|
const body = await res.json().catch(() => ({}))
|
|
333
409
|
const data = body?.data
|
|
334
|
-
if (body?.ok === true) {
|
|
410
|
+
if (res.ok && body?.ok === true) {
|
|
335
411
|
emitUpdate({ phase: 'done', text: data?.to ? tr('已更新到 {version},重启 DSH 后生效', { version: data.to }) : tr('已更新,重启 DSH 后生效'), latest: null })
|
|
336
412
|
resetUpdateLater()
|
|
337
|
-
|
|
338
|
-
emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: data?.reason ?? 'unknown' }), command: data?.command ?? null })
|
|
413
|
+
return
|
|
339
414
|
}
|
|
415
|
+
emitUpdate({
|
|
416
|
+
phase: 'error',
|
|
417
|
+
text: tr('更新失败({reason})', { reason: installReasonText(body?.reason ?? data?.reason) }),
|
|
418
|
+
command: data?.command ?? null,
|
|
419
|
+
})
|
|
340
420
|
} catch (error) {
|
|
341
|
-
emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: error
|
|
421
|
+
emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: installReasonText(error?.message) }), command: null })
|
|
342
422
|
}
|
|
343
423
|
}
|
|
344
424
|
|
|
@@ -536,12 +616,52 @@ window.__ModuleLoader__.load({
|
|
|
536
616
|
trendPlot: { position: 'relative', height: 132, minWidth: 0 },
|
|
537
617
|
trendGrid: { position: 'absolute', left: 0, right: 0, height: 1, background: T.border, pointerEvents: 'none' },
|
|
538
618
|
trendAxis: { position: 'absolute', left: 0, color: T.weak, fontSize: 11, fontVariantNumeric: 'tabular-nums' },
|
|
539
|
-
trendBars: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'flex-end', gap: 2, paddingLeft: 34 },
|
|
619
|
+
trendBars: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'flex-end', gap: 2, paddingLeft: 34, zIndex: 1 },
|
|
540
620
|
// 每根柱独占一个等分槽并在槽内居中:只对柱体设 maxWidth 会让所有柱挤到一侧
|
|
541
621
|
trendSlot: { flex: '1 1 0', minWidth: 1, height: '100%', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' },
|
|
542
622
|
trendBar: { width: '100%', maxWidth: 36, borderRadius: '3px 3px 0 0', background: T.accent },
|
|
543
623
|
trendTicks: { position: 'absolute', left: 34, right: 0, bottom: 0, height: 18, display: 'flex', alignItems: 'center', gap: 2, color: T.weak, fontSize: 11 },
|
|
624
|
+
// 虚线要压在柱体之上:柱容器 zIndex 1,指示线 zIndex 4,浮层 5
|
|
625
|
+
trendHoverLine: {
|
|
626
|
+
position: 'absolute', top: 0, bottom: 18, width: 1, marginLeft: -0.5, pointerEvents: 'none',
|
|
627
|
+
borderLeft: `1px dashed ${T.accent}`, opacity: 0.9, zIndex: 4,
|
|
628
|
+
},
|
|
629
|
+
trendHoverDot: {
|
|
630
|
+
position: 'absolute', width: 5, height: 5, marginLeft: -2.5, marginBottom: -2.5, borderRadius: 999,
|
|
631
|
+
background: T.accent, pointerEvents: 'none', zIndex: 5,
|
|
632
|
+
},
|
|
633
|
+
trendTip: {
|
|
634
|
+
position: 'absolute', bottom: 'calc(100% - 12px)', transform: 'translateX(-50%)',
|
|
635
|
+
padding: '3px 8px', borderRadius: 6, whiteSpace: 'nowrap', pointerEvents: 'none', zIndex: 6,
|
|
636
|
+
fontSize: 11, lineHeight: '16px',
|
|
637
|
+
background: T.tooltip, color: T.tooltipText, border: `1px solid ${T.border}`,
|
|
638
|
+
boxShadow: 'var(--dsw-shadow-lv2, 0 4px 12px rgba(0,0,0,.24))',
|
|
639
|
+
},
|
|
544
640
|
trendTick: { flex: '1 1 0', minWidth: 0, textAlign: 'center', whiteSpace: 'nowrap' },
|
|
641
|
+
// UpdateButton:8 态矩阵见 docs/ui-design.md §5.7.1;尺寸与既有 ghost 按钮一致,不改变「版本」行排版
|
|
642
|
+
updateBox: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 },
|
|
643
|
+
updateButton: {
|
|
644
|
+
display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,
|
|
645
|
+
height: 22, minWidth: 22, padding: '0 6px', boxSizing: 'border-box',
|
|
646
|
+
borderRadius: 6, border: `1px solid ${T.border}`, background: 'transparent',
|
|
647
|
+
color: T.text, fontSize: 11, font: 'inherit', cursor: 'pointer',
|
|
648
|
+
transition: 'background .15s, border-color .15s, color .15s',
|
|
649
|
+
},
|
|
650
|
+
updateButtonOn: {
|
|
651
|
+
borderColor: `color-mix(in srgb, ${T.accent} 42%, transparent)`,
|
|
652
|
+
background: `color-mix(in srgb, ${T.accent} 16%, transparent)`,
|
|
653
|
+
color: T.accent, fontWeight: 500,
|
|
654
|
+
},
|
|
655
|
+
updateButtonError: {
|
|
656
|
+
borderColor: `color-mix(in srgb, ${T.over} 42%, transparent)`,
|
|
657
|
+
background: 'transparent', color: T.over,
|
|
658
|
+
},
|
|
659
|
+
updateHint: { fontSize: 11, color: T.accent, fontWeight: 500, whiteSpace: 'nowrap' },
|
|
660
|
+
updateHintError: { fontSize: 11, color: T.over, whiteSpace: 'nowrap' },
|
|
661
|
+
updateDismiss: {
|
|
662
|
+
height: 22, padding: '0 8px', boxSizing: 'border-box', borderRadius: 6, font: 'inherit', fontSize: 11,
|
|
663
|
+
cursor: 'pointer', border: '1px solid transparent', background: 'transparent', color: T.muted,
|
|
664
|
+
},
|
|
545
665
|
trendMsg: { position: 'absolute', inset: '0 0 18px 34px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.muted, fontSize: 11 },
|
|
546
666
|
quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
|
|
547
667
|
quotaCard: {
|
|
@@ -904,8 +1024,8 @@ window.__ModuleLoader__.load({
|
|
|
904
1024
|
: `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
|
|
905
1025
|
}
|
|
906
1026
|
|
|
907
|
-
/** P3
|
|
908
|
-
const TREND_METRICS = [['tokens', 'Tokens'], ['
|
|
1027
|
+
/** P3 趋势指标:唯一顺序源——四格摘要带与右侧胶囊都从这里派生,禁止各自维护顺序。 */
|
|
1028
|
+
const TREND_METRICS = [['tokens', 'Tokens'], ['cost', '费用'], ['hitRate', '命中率'], ['requests', '请求']]
|
|
909
1029
|
const METRIC_LABELS = { tokens: 'Tokens', requests: '请求', cost: '费用', hitRate: '命中率' }
|
|
910
1030
|
/** 词典里 '万' 的英文值是 K:据此判断当前是否中文,不依赖 localeService 暴露语言码。 */
|
|
911
1031
|
const isChinese = () => tr('万') === '万'
|
|
@@ -972,53 +1092,124 @@ window.__ModuleLoader__.load({
|
|
|
972
1092
|
}
|
|
973
1093
|
}
|
|
974
1094
|
|
|
975
|
-
/** P3 四格卡:兼作趋势指标选择器;每格 button[role=radio],选中态由 metric 决定。
|
|
1095
|
+
/** P3 四格卡:兼作趋势指标选择器;每格 button[role=radio],选中态由 metric 决定。
|
|
1096
|
+
* 渲染顺序固定取自 TREND_METRICS(与右侧指标胶囊同源),禁止在此手写格子顺序。 */
|
|
976
1097
|
function RangeCards({ usage, metric = 'tokens', onMetricChange }) {
|
|
977
1098
|
const pending = usage === null
|
|
978
1099
|
const costEntries = Object.entries(usage?.totals ?? {})
|
|
979
1100
|
const total = usage?.total ?? null
|
|
1101
|
+
const dash = '—'
|
|
980
1102
|
const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
|
|
981
|
-
const
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
h(
|
|
988
|
-
|
|
989
|
-
|
|
1103
|
+
const tokensLabel = h('span', null,
|
|
1104
|
+
tr('真实 Tokens'),
|
|
1105
|
+
h(InfoTip, {
|
|
1106
|
+
label: tr('Tokens 括号说明'),
|
|
1107
|
+
text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
|
|
1108
|
+
variant: 'inline',
|
|
1109
|
+
}, h(Icon, { name: 'info', size: 11 })))
|
|
1110
|
+
/** 一格一渲染器:长标签 / 主值节点 / 副值文案;主值节点沿用历史 testid。 */
|
|
1111
|
+
const CARDS = {
|
|
1112
|
+
tokens: {
|
|
1113
|
+
label: tokensLabel,
|
|
1114
|
+
main: () => h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV },
|
|
1115
|
+
pending ? dash : fmtTokens(total?.tokens ?? 0)),
|
|
1116
|
+
sub: () => (pending ? dash : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`),
|
|
1117
|
+
},
|
|
1118
|
+
cost: {
|
|
1119
|
+
label: tr('总费用'),
|
|
1120
|
+
main: () => h('div', { style: styles.summaryV },
|
|
1121
|
+
pending ? dash : (costNodes.length === 0 ? dash : costNodes)),
|
|
1122
|
+
sub: () => (pending ? dash : tr('{n} 个币种', { n: costEntries.length })),
|
|
1123
|
+
},
|
|
1124
|
+
hitRate: {
|
|
1125
|
+
label: tr('缓存命中率'),
|
|
1126
|
+
main: () => h('div', { style: styles.summaryV },
|
|
1127
|
+
pending ? dash : (total?.hitRate === null || total?.hitRate === undefined ? dash : fmtRatio(total.hitRate))),
|
|
1128
|
+
sub: () => (pending ? dash : tr('创建 {a} · 命中 {b}', { a: fmtTokens(total?.cacheWrite ?? 0), b: fmtTokens(total?.cacheRead ?? 0) })),
|
|
1129
|
+
},
|
|
1130
|
+
requests: {
|
|
1131
|
+
label: tr('总请求数'),
|
|
1132
|
+
main: () => h('div', { style: styles.summaryV }, pending ? dash : String(total?.requests ?? 0)),
|
|
1133
|
+
sub: () => tr('范围内全部模型'),
|
|
1134
|
+
},
|
|
1135
|
+
}
|
|
990
1136
|
return h('div', {
|
|
991
1137
|
'data-testid': 'token-dash-range-cards', 'data-td-cards': true, role: 'radiogroup',
|
|
992
1138
|
'aria-label': tr('趋势指标'), style: styles.summaryBand,
|
|
993
1139
|
},
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1140
|
+
...TREND_METRICS.map(([key]) => {
|
|
1141
|
+
const card = CARDS[key]
|
|
1142
|
+
return h('button', {
|
|
1143
|
+
key, type: 'button', role: 'radio', 'aria-pressed': metric === key,
|
|
1144
|
+
'data-testid': `token-dash-card-${key}`,
|
|
1145
|
+
onClick: () => onMetricChange?.(key),
|
|
1146
|
+
style: { ...styles.summaryHalf, ...(metric === key ? styles.summaryHalfOn : null) },
|
|
1147
|
+
},
|
|
1148
|
+
h('span', { style: { ...styles.summaryK, ...(metric === key ? { color: T.accent } : null) } }, card.label),
|
|
1149
|
+
card.main(),
|
|
1150
|
+
h('div', { style: styles.summarySub }, card.sub()))
|
|
1151
|
+
}))
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/**
|
|
1155
|
+
* UpdateButton:设置区「版本」行右端的更新控件,8 态矩阵见 docs/ui-design.md §5.7.1。
|
|
1156
|
+
* 有更新时按钮整体转 accent 并常显版本号——不用小圆点,避免「看到点但不知道是什么」。
|
|
1157
|
+
* 失败分级:手动失败按钮转 over 色可重试;自动失败只给低强度文字,不动按钮外观。
|
|
1158
|
+
*/
|
|
1159
|
+
function UpdateButton({ update, onCheck, onInstall, onCopyCommand }) {
|
|
1160
|
+
const phase = update?.phase ?? 'idle'
|
|
1161
|
+
const latest = update?.latest ?? null
|
|
1162
|
+
const busy = phase === 'checking' || phase === 'installing'
|
|
1163
|
+
const available = phase === 'available'
|
|
1164
|
+
const manualError = phase === 'error'
|
|
1165
|
+
const autoError = phase === 'autoError'
|
|
1166
|
+
const done = phase === 'done'
|
|
1167
|
+
const iconName = busy ? 'loader' : (manualError ? 'refresh' : (done ? 'check' : 'download'))
|
|
1168
|
+
const label = available
|
|
1169
|
+
? tr('发现 {version},点击更新', { version: latest })
|
|
1170
|
+
: (manualError ? tr('重试') : tr('检查更新'))
|
|
1171
|
+
const buttonStyle = {
|
|
1172
|
+
...styles.updateButton,
|
|
1173
|
+
...(available ? styles.updateButtonOn : null),
|
|
1174
|
+
...(manualError ? styles.updateButtonError : null),
|
|
1175
|
+
...(busy ? { opacity: 0.55, cursor: 'default' } : null),
|
|
1176
|
+
}
|
|
1177
|
+
const hintText = done ? (update?.text ?? tr('已是最新')) : (autoError ? tr('更新检查失败') : null)
|
|
1178
|
+
const buttonText = phase === 'installing' ? tr('更新中') : (available ? tr('更新') : null)
|
|
1179
|
+
return h('span', { style: styles.updateBox, 'data-testid': 'token-dash-update-box' },
|
|
1180
|
+
manualError && update?.command ? h('button', { type: 'button', style: styles.updateDismiss, onClick: () => onCopyCommand?.() }, tr('复制命令')) : null,
|
|
997
1181
|
h('button', {
|
|
998
|
-
type: 'button',
|
|
999
|
-
'data-testid': 'token-dash-
|
|
1000
|
-
|
|
1001
|
-
|
|
1182
|
+
type: 'button',
|
|
1183
|
+
'data-testid': 'token-dash-update',
|
|
1184
|
+
'data-state': available ? 'available' : (manualError ? 'error' : 'idle'),
|
|
1185
|
+
'aria-label': label,
|
|
1186
|
+
title: label,
|
|
1187
|
+
disabled: busy,
|
|
1188
|
+
style: buttonStyle,
|
|
1189
|
+
onClick: () => { if (available || manualError) onInstall?.(); else onCheck?.() },
|
|
1002
1190
|
},
|
|
1003
|
-
h(
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
h('
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
pending ? '—' : tr('创建 {a} · 命中 {b}', { a: fmtTokens(total?.cacheWrite ?? 0), b: fmtTokens(total?.cacheRead ?? 0) })))
|
|
1191
|
+
h(Icon, { name: iconName, size: 13 }),
|
|
1192
|
+
buttonText !== null ? h('span', null, buttonText) : null),
|
|
1193
|
+
available && latest !== null
|
|
1194
|
+
? h('span', { style: styles.updateHint, 'data-testid': 'token-dash-update-latest' }, latest)
|
|
1195
|
+
: null,
|
|
1196
|
+
hintText !== null
|
|
1197
|
+
// 成功/中性提示用 status 播报;失败用 alert,语义不同不复用同一节点
|
|
1198
|
+
? h('span', {
|
|
1199
|
+
role: autoError ? 'alert' : 'status',
|
|
1200
|
+
'aria-live': autoError ? 'assertive' : 'polite',
|
|
1201
|
+
style: autoError ? styles.updateHintError : { fontSize: 11, color: T.muted },
|
|
1202
|
+
'data-testid': 'token-dash-update-hint',
|
|
1203
|
+
}, hintText)
|
|
1204
|
+
: null)
|
|
1018
1205
|
}
|
|
1019
1206
|
|
|
1207
|
+
|
|
1208
|
+
|
|
1020
1209
|
/** P3 趋势柱:连续日/月序列 → flex 柱 + 绝对定位网格线;悬停走原生 title,无交互状态。 */
|
|
1021
1210
|
function TrendChart({ series, metric, grain = 'day', onMetricChange }) {
|
|
1211
|
+
// 悬停态:{ center: 柱位百分比, ratio: 柱高百分比, text: 浮层文案 };null 表示未悬停
|
|
1212
|
+
const [hover, setHover] = useState(null)
|
|
1022
1213
|
const points = Array.isArray(series) ? series : []
|
|
1023
1214
|
const values = points.map((point) => trendValue(point, metric))
|
|
1024
1215
|
const known = values.filter((value) => value !== null && value > 0)
|
|
@@ -1030,6 +1221,8 @@ window.__ModuleLoader__.load({
|
|
|
1030
1221
|
for (const point of points) for (const currency of Object.keys(point.cost ?? {})) currencies.add(currency)
|
|
1031
1222
|
const costBlocked = metric === 'cost' && currencies.size > 1
|
|
1032
1223
|
const costCurrency = currencies.size === 1 ? [...currencies][0] : 'CNY'
|
|
1224
|
+
// 换指标 / 换范围后旧的柱位与文案都已失效,直接清空悬停态
|
|
1225
|
+
useEffect(() => { setHover(null) }, [metric, series])
|
|
1033
1226
|
const tickOf = (dayKey) => {
|
|
1034
1227
|
if (grain !== 'month') return String(dayKey).slice(5)
|
|
1035
1228
|
return isChinese() ? `${String(dayKey).slice(5)}月` : monthNameOf(dayKey)
|
|
@@ -1050,25 +1243,50 @@ window.__ModuleLoader__.load({
|
|
|
1050
1243
|
options: TREND_METRICS.map(([value, label]) => ({ value, label: tr(label) })),
|
|
1051
1244
|
})),
|
|
1052
1245
|
h('div', { style: styles.trendPlot },
|
|
1053
|
-
h('
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
emptyMessage === null ? h('span', { style: { ...styles.trendAxis, top: '50%', transform: 'translateY(-100%)' } }, fmtAxisMetric(floor + span / 2, metric, costCurrency)) : null,
|
|
1058
|
-
emptyMessage === null ? h('div', { style: styles.trendBars },
|
|
1246
|
+
emptyMessage === null ? h('div', {
|
|
1247
|
+
style: styles.trendBars,
|
|
1248
|
+
onMouseLeave: () => setHover(null),
|
|
1249
|
+
},
|
|
1059
1250
|
...points.map((point, index) => {
|
|
1060
1251
|
const value = values[index]
|
|
1061
1252
|
const ratio = value === null || value <= floor ? 0 : Math.max(0, Math.min(100, ((value - floor) / span) * 100))
|
|
1062
|
-
|
|
1253
|
+
// 悬停即渲染虚线与浮层:不挂原生 title,避免系统 tooltip 的 ~1s 延迟
|
|
1254
|
+
return h('span', {
|
|
1255
|
+
key: point.dayKey,
|
|
1256
|
+
'data-testid': `token-dash-trend-slot-${point.dayKey}`,
|
|
1257
|
+
style: styles.trendSlot,
|
|
1258
|
+
onMouseEnter: () => setHover({
|
|
1259
|
+
center: ((index + 0.5) / points.length) * 100,
|
|
1260
|
+
ratio,
|
|
1261
|
+
text: `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`,
|
|
1262
|
+
}),
|
|
1263
|
+
},
|
|
1063
1264
|
h('span', {
|
|
1064
1265
|
'data-testid': `token-dash-trend-bar-${point.dayKey}`,
|
|
1065
|
-
title: `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`,
|
|
1066
1266
|
style: { ...styles.trendBar, height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
|
|
1067
1267
|
}))
|
|
1068
1268
|
})) : h('div', { 'data-testid': 'token-dash-trend-empty', style: styles.trendMsg }, emptyMessage),
|
|
1269
|
+
emptyMessage === null && hover !== null ? h('span', {
|
|
1270
|
+
'data-testid': 'token-dash-trend-hover-line',
|
|
1271
|
+
'aria-hidden': true,
|
|
1272
|
+
style: { ...styles.trendHoverLine, left: `calc(34px + (100% - 34px) * ${hover.center / 100})` },
|
|
1273
|
+
}) : null,
|
|
1274
|
+
emptyMessage === null && hover !== null ? h('span', {
|
|
1275
|
+
'data-testid': 'token-dash-trend-hover-dot',
|
|
1276
|
+
'aria-hidden': true,
|
|
1277
|
+
style: {
|
|
1278
|
+
...styles.trendHoverDot,
|
|
1279
|
+
left: `calc(34px + (100% - 34px) * ${hover.center / 100})`,
|
|
1280
|
+
bottom: `calc(18px + (132px - 18px) * ${hover.ratio / 100})`,
|
|
1281
|
+
},
|
|
1282
|
+
}) : null,
|
|
1069
1283
|
emptyMessage === null ? h('div', { style: styles.trendTicks },
|
|
1070
1284
|
...points.map((point, index) => h('span', { key: point.dayKey, style: styles.trendTick },
|
|
1071
|
-
index % step === 0 || index === points.length - 1 ? tickOf(point.dayKey) : ''))) : null
|
|
1285
|
+
index % step === 0 || index === points.length - 1 ? tickOf(point.dayKey) : ''))) : null,
|
|
1286
|
+
emptyMessage === null && hover !== null ? h('div', {
|
|
1287
|
+
'data-testid': 'token-dash-trend-hover-tip',
|
|
1288
|
+
style: { ...styles.trendTip, left: `calc(34px + (100% - 34px) * ${hover.center / 100})` },
|
|
1289
|
+
}, hover.text) : null))
|
|
1072
1290
|
}
|
|
1073
1291
|
|
|
1074
1292
|
function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
|
|
@@ -1650,33 +1868,13 @@ window.__ModuleLoader__.load({
|
|
|
1650
1868
|
const version = summary?.version ?? ''
|
|
1651
1869
|
const catalog = summary?.catalog
|
|
1652
1870
|
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
h('button', { type: 'button', style: styles.button, onClick: installUpdate }, tr('更新')),
|
|
1661
|
-
h('button', { type: 'button', style: styles.button, onClick: () => emitUpdate({ phase: 'idle', latest: null }) }, tr('取消')))
|
|
1662
|
-
} else {
|
|
1663
|
-
updateControl = h('span', { style: styles.rowStart },
|
|
1664
|
-
updateError && update.command
|
|
1665
|
-
? h('button', { type: 'button', style: styles.button, onClick: copyCommand }, tr('复制命令'))
|
|
1666
|
-
: null,
|
|
1667
|
-
h(IconButton, {
|
|
1668
|
-
label: updateAvailable ? tr('发现 {version},点击更新', { version: update.latest }) : tr('检查更新'),
|
|
1669
|
-
testid: 'token-dash-update', disabled: updateBusy,
|
|
1670
|
-
dot: updateAvailable || updateError,
|
|
1671
|
-
dotColor: updateError ? T.over : T.accent,
|
|
1672
|
-
onClick: () => {
|
|
1673
|
-
if (updateAvailable) emitUpdate({ phase: 'confirm', latest: update.latest })
|
|
1674
|
-
else checkUpdate()
|
|
1675
|
-
},
|
|
1676
|
-
}, h(Icon, {
|
|
1677
|
-
name: updateBusy ? 'loader' : update.phase === 'done' ? 'check' : 'download', size: 13,
|
|
1678
|
-
})))
|
|
1679
|
-
}
|
|
1871
|
+
const updateControl = h(UpdateButton, {
|
|
1872
|
+
update,
|
|
1873
|
+
onCheck: checkUpdate,
|
|
1874
|
+
onInstall: installUpdate,
|
|
1875
|
+
onCopyCommand: copyCommand,
|
|
1876
|
+
})
|
|
1877
|
+
|
|
1680
1878
|
|
|
1681
1879
|
const statusText = update.text ?? status?.text ?? ''
|
|
1682
1880
|
return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', minWidth: 0 } },
|
|
@@ -1960,7 +2158,7 @@ window.__ModuleLoader__.load({
|
|
|
1960
2158
|
}, [active])
|
|
1961
2159
|
|
|
1962
2160
|
const loadPrefs = useCallback(async () => {
|
|
1963
|
-
try {
|
|
2161
|
+
try { const loaded = await getJson('/prefs'); updatePrefsCache = loaded; setPrefs(loaded) } catch { /* keep previous */ }
|
|
1964
2162
|
}, [])
|
|
1965
2163
|
|
|
1966
2164
|
const loadUsage = useCallback(async () => {
|
|
@@ -1991,6 +2189,7 @@ window.__ModuleLoader__.load({
|
|
|
1991
2189
|
try {
|
|
1992
2190
|
const saved = await putPrefs({ ...prefsRef.current, ...patch })
|
|
1993
2191
|
prefsRef.current = saved
|
|
2192
|
+
updatePrefsCache = saved
|
|
1994
2193
|
setPrefs(saved)
|
|
1995
2194
|
setSummary((current) => (current === null ? current : mergeBudgets(current, saved)))
|
|
1996
2195
|
return { ok: true, prefs: saved }
|
|
@@ -2096,8 +2295,46 @@ window.__ModuleLoader__.load({
|
|
|
2096
2295
|
if (!autoUpdateChecked) {
|
|
2097
2296
|
autoUpdateChecked = true
|
|
2098
2297
|
ctx.effect?.(() => {
|
|
2099
|
-
|
|
2100
|
-
|
|
2298
|
+
// 启动补检:UI 稳定 30s 后检测;距上次检测不足 1h 则跳过,
|
|
2299
|
+
// 避免一天重启多次就反复请求 registry。
|
|
2300
|
+
let timer = null
|
|
2301
|
+
let interval = null
|
|
2302
|
+
let cancelled = false
|
|
2303
|
+
const lastAt = readStoredTs
|
|
2304
|
+
// 周期检测与「恢复可见补检」共用同一个到期判定,避免两处各判一次导致连发
|
|
2305
|
+
const isDue = () => Date.now() - lastAt() >= UPDATE_INTERVAL_MS
|
|
2306
|
+
const runAuto = (source) => {
|
|
2307
|
+
if (cancelled) return
|
|
2308
|
+
logUpdateSchedule(source, { elapsed: Date.now() - lastAt() })
|
|
2309
|
+
void checkForUpdate({ manual: false })
|
|
2310
|
+
}
|
|
2311
|
+
logUpdateSchedule('armed', {
|
|
2312
|
+
delay: updateStartupDelay(), lastAt: lastAt(), interval: UPDATE_INTERVAL_MS,
|
|
2313
|
+
hasLocalStorage: typeof globalThis.localStorage !== 'undefined',
|
|
2314
|
+
})
|
|
2315
|
+
timer = setTimeout(() => {
|
|
2316
|
+
timer = null
|
|
2317
|
+
// 启动检测无条件执行:用户要求「每次启动都检查」,不看缓存也不看上次检测时间
|
|
2318
|
+
runAuto('startup.run')
|
|
2319
|
+
interval = setInterval(() => {
|
|
2320
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
|
|
2321
|
+
if (!isDue()) return
|
|
2322
|
+
runAuto('interval.run')
|
|
2323
|
+
}, UPDATE_INTERVAL_MS)
|
|
2324
|
+
}, updateStartupDelay())
|
|
2325
|
+
|
|
2326
|
+
const onVisible = () => {
|
|
2327
|
+
if (typeof document === 'undefined' || document.visibilityState !== 'visible') return
|
|
2328
|
+
if (!isDue()) return
|
|
2329
|
+
runAuto('visible.run')
|
|
2330
|
+
}
|
|
2331
|
+
if (typeof document !== 'undefined') document.addEventListener?.('visibilitychange', onVisible)
|
|
2332
|
+
return () => {
|
|
2333
|
+
cancelled = true
|
|
2334
|
+
if (timer !== null) clearTimeout(timer)
|
|
2335
|
+
if (interval !== null) clearInterval(interval)
|
|
2336
|
+
if (typeof document !== 'undefined') document.removeEventListener?.('visibilitychange', onVisible)
|
|
2337
|
+
}
|
|
2101
2338
|
}, 'update:startup')
|
|
2102
2339
|
}
|
|
2103
2340
|
ctxRef = typeof ctx === 'object' ? ctx : null
|
|
@@ -2131,4 +2368,4 @@ window.__ModuleLoader__.load({
|
|
|
2131
2368
|
},
|
|
2132
2369
|
}
|
|
2133
2370
|
},
|
|
2134
|
-
})
|
|
2371
|
+
})
|
package/index.js
CHANGED
|
@@ -19,7 +19,16 @@ import { isNewer } from './src/version.js'
|
|
|
19
19
|
export const name = 'dsh-token-dash'
|
|
20
20
|
|
|
21
21
|
const ROUTE_PREFIX = '/token-dash/api'
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* 当前版本:默认取 package.json。TOKEN_DASH_CURRENT_VERSION 可覆盖,
|
|
24
|
+
* 供 e2e 用「真实 GitHub/npm 已发布版本」跑完整更新链路(不必真的装一个旧包)。
|
|
25
|
+
* 但「安装」环节仍走真实 CLI,因此覆盖值只影响比对基准,不影响安装目标。
|
|
26
|
+
*/
|
|
27
|
+
const CURRENT_VERSION = (() => {
|
|
28
|
+
const override = process.env.TOKEN_DASH_CURRENT_VERSION
|
|
29
|
+
if (typeof override === 'string' && override !== '') return override
|
|
30
|
+
return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
|
|
31
|
+
})()
|
|
23
32
|
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
|
|
24
33
|
|
|
25
34
|
/** 宿主版本:优先环境变量,其次 Electron asar 内的 package.json;读不到时写 unknown,避免硬编码过期。 */
|
|
@@ -42,6 +51,8 @@ function hostVersion() {
|
|
|
42
51
|
return 'unknown'
|
|
43
52
|
}
|
|
44
53
|
let updateCache = { at: 0, data: null }
|
|
54
|
+
/** 允许 client 上报日志的模块白名单:只放已知来源,避免任意日志注入。 */
|
|
55
|
+
const CLIENT_LOG_MODULES = new Set(['slot', 'update'])
|
|
45
56
|
|
|
46
57
|
/** Locate the bundled dsh CLI (same layout scripts/e2e.mjs relies on). */
|
|
47
58
|
function findDshCli() {
|
|
@@ -77,12 +88,19 @@ async function fetchLatest() {
|
|
|
77
88
|
const meta = await response.json()
|
|
78
89
|
if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
|
|
79
90
|
return { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true }
|
|
91
|
+
if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
|
|
92
|
+
return { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true, source: 'registry' }
|
|
80
93
|
}
|
|
81
94
|
|
|
82
|
-
/**
|
|
95
|
+
/** 安装 spec:默认按 npm 版本号安装,仍走与真实更新完全相同的 CLI 路径。 */
|
|
96
|
+
function updateSpec(version) {
|
|
97
|
+
return `dsh-token-dash@${version}`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Run `dsh plugin --profile <p> add <spec> --save-exact`; resolves with { ok, reason?, command, output }. */
|
|
83
101
|
function runPluginUpdate(profile, version) {
|
|
84
102
|
return new Promise((resolve) => {
|
|
85
|
-
const spec =
|
|
103
|
+
const spec = updateSpec(version)
|
|
86
104
|
const command = `dsh plugin --profile ${profile} add ${spec} --save-exact`
|
|
87
105
|
const cli = findDshCli()
|
|
88
106
|
if (cli === null) {
|
|
@@ -529,54 +547,94 @@ export function apply(ctx) {
|
|
|
529
547
|
return
|
|
530
548
|
}
|
|
531
549
|
if (url.pathname === `${ROUTE_PREFIX}/log` && req.method === 'POST') {
|
|
532
|
-
//
|
|
550
|
+
// client 端上报落盘:模块白名单(slot 挂载 / update 调度),防日志注入
|
|
533
551
|
const body = JSON.parse((await readBody(req)) || '{}')
|
|
534
|
-
if (body?.module
|
|
552
|
+
if (!CLIENT_LOG_MODULES.has(body?.module) || typeof body?.event !== 'string') {
|
|
535
553
|
json(res, 400, { ok: false, reason: 'invalid-log' })
|
|
536
554
|
return
|
|
537
555
|
}
|
|
538
|
-
logger.info(
|
|
556
|
+
logger.info(body.module, body.event, typeof body.meta === 'object' && body.meta !== null ? body.meta : {})
|
|
539
557
|
json(res, 200, { ok: true, data: { logged: true } })
|
|
540
558
|
return
|
|
541
559
|
}
|
|
542
560
|
if (url.pathname === `${ROUTE_PREFIX}/update/install` && req.method === 'POST') {
|
|
543
561
|
const profile = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE !== '' ? process.env.DSH_PROFILE : 'desktop'
|
|
544
|
-
|
|
545
|
-
|
|
562
|
+
// 优先安装客户端展示过的那个版本:用户看到的与真正装上的必须是同一个,
|
|
563
|
+
// 否则两次查询 registry 之间若发版,会出现「提示 A 装成 B」。
|
|
564
|
+
// 未带 version 时(旧客户端)回退查询 registry,保持向后兼容。
|
|
565
|
+
let target = null
|
|
566
|
+
try {
|
|
567
|
+
const body = JSON.parse((await readBody(req)) || '{}')
|
|
568
|
+
if (typeof body?.version === 'string' && body.version !== '') target = body.version
|
|
569
|
+
} catch { /* 空 body 或非法 JSON 按未指定处理 */ }
|
|
570
|
+
if (target === null) target = (await fetchLatest()).latest
|
|
571
|
+
if (target === null) {
|
|
546
572
|
logger.info('update', 'install.fail', { profile, reason: 'unpublished' })
|
|
547
|
-
json(res,
|
|
573
|
+
json(res, 400, { ok: false, reason: 'unpublished' })
|
|
574
|
+
return
|
|
575
|
+
}
|
|
576
|
+
// 版本号必须是合法 semver:既防注入,也防把任意字符串拼进 CLI 参数
|
|
577
|
+
if (/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(target) === false) {
|
|
578
|
+
logger.info('update', 'install.fail', { profile, reason: 'invalid-version', target })
|
|
579
|
+
json(res, 400, { ok: false, reason: 'invalid-version' })
|
|
548
580
|
return
|
|
549
581
|
}
|
|
550
|
-
if (/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(latest) === false) throw new Error('invalid-latest-version')
|
|
551
582
|
const home = resolveHome(scoped)
|
|
552
583
|
const from = installedVersion(home, profile) ?? CURRENT_VERSION
|
|
553
|
-
const result = await runPluginUpdate(profile,
|
|
584
|
+
const result = await runPluginUpdate(profile, target)
|
|
554
585
|
const to = installedVersion(home, profile)
|
|
555
|
-
const changed = to ===
|
|
586
|
+
const changed = to === target
|
|
556
587
|
const ok = result.ok === true && changed
|
|
557
588
|
const failReason = result.ok === true ? 'version-unchanged' : result.reason ?? 'install-failed'
|
|
558
589
|
logger.info('update', ok ? 'install.ok' : 'install.fail', {
|
|
559
590
|
profile,
|
|
560
591
|
from,
|
|
561
592
|
to,
|
|
593
|
+
target,
|
|
562
594
|
reason: ok ? null : failReason,
|
|
563
595
|
...(ok ? {} : { output: String(result.output ?? '').slice(-500) }),
|
|
564
596
|
})
|
|
565
597
|
updateCache = { at: 0, data: null }
|
|
566
|
-
json(res, 200, {
|
|
598
|
+
json(res, ok ? 200 : 500, {
|
|
567
599
|
ok,
|
|
568
|
-
data: { ...result, from, to, latest, ...(ok ? {} : { reason: failReason }) },
|
|
600
|
+
data: { ...result, from, to, latest: target, ...(ok ? {} : { reason: failReason }) },
|
|
569
601
|
...(ok ? {} : { reason: failReason }),
|
|
570
602
|
})
|
|
571
603
|
return
|
|
572
604
|
}
|
|
573
605
|
if (url.pathname === `${ROUTE_PREFIX}/update` && req.method === 'GET') {
|
|
574
|
-
|
|
606
|
+
// ?refresh=1 跳过 5min 缓存。启动检测与手动点击都带这个参数:
|
|
607
|
+
// 用户要求「每次启动无条件检查」,命中旧缓存就等于没检查。
|
|
608
|
+
const forceRefresh = url.searchParams.get('refresh') === '1'
|
|
609
|
+
if (!forceRefresh && updateCache.data !== null && Date.now() - updateCache.at < 300000) {
|
|
575
610
|
json(res, 200, { ok: true, data: updateCache.data })
|
|
576
611
|
return
|
|
577
612
|
}
|
|
578
|
-
|
|
613
|
+
let data
|
|
614
|
+
try {
|
|
615
|
+
data = await fetchLatest()
|
|
616
|
+
} catch (error) {
|
|
617
|
+
// 失败不吞:带 errorKind / httpStatus 落日志,客户端也能据此显示「更新检查失败」
|
|
618
|
+
const message = String(error?.message ?? error)
|
|
619
|
+
const statusMatch = /registry-(\d+)/.exec(message)
|
|
620
|
+
const errorKind = statusMatch !== null ? 'http' : (message.includes('timeout') || message.includes('abort') ? 'timeout' : 'network')
|
|
621
|
+
logger.error('update', 'check.fail', {
|
|
622
|
+
source: 'registry',
|
|
623
|
+
errorKind,
|
|
624
|
+
httpStatus: statusMatch === null ? null : Number(statusMatch[1]),
|
|
625
|
+
reason: message,
|
|
626
|
+
})
|
|
627
|
+
json(res, 502, { ok: false, reason: errorKind })
|
|
628
|
+
return
|
|
629
|
+
}
|
|
579
630
|
updateCache = { at: Date.now(), data }
|
|
631
|
+
logger.info('update', 'check.ok', {
|
|
632
|
+
source: data.source ?? 'registry',
|
|
633
|
+
current: data.current,
|
|
634
|
+
latest: data.latest,
|
|
635
|
+
hasUpdate: data.hasUpdate,
|
|
636
|
+
published: data.published,
|
|
637
|
+
})
|
|
580
638
|
json(res, 200, { ok: true, data })
|
|
581
639
|
return
|
|
582
640
|
}
|
|
@@ -624,4 +682,4 @@ export function apply(ctx) {
|
|
|
624
682
|
})
|
|
625
683
|
return off
|
|
626
684
|
})
|
|
627
|
-
}
|
|
685
|
+
}
|
package/locale/en.json
CHANGED
|
@@ -91,7 +91,6 @@
|
|
|
91
91
|
"已是最新": "Up to date",
|
|
92
92
|
"发现 {version}": "Found {version}",
|
|
93
93
|
"更新": "Update",
|
|
94
|
-
"取消": "Cancel",
|
|
95
94
|
"复制命令": "Copy command",
|
|
96
95
|
"命令已复制": "Command copied",
|
|
97
96
|
"复制失败": "Copy failed",
|
|
@@ -132,5 +131,11 @@
|
|
|
132
131
|
"命中率": "Hit rate",
|
|
133
132
|
"无数据": "No data",
|
|
134
133
|
"多币种下成本柱不可用,请切换其他指标": "Cost bars unavailable with multiple currencies; switch metric",
|
|
135
|
-
"万": "K"
|
|
134
|
+
"万": "K",
|
|
135
|
+
"更新中": "Updating",
|
|
136
|
+
"更新检查失败": "Update check failed",
|
|
137
|
+
"版本号不合法": "Invalid version",
|
|
138
|
+
"该版本未发布": "Version not published",
|
|
139
|
+
"版本未变化": "Version unchanged",
|
|
140
|
+
"未找到 dsh 命令": "dsh command not found"
|
|
136
141
|
}
|
package/locale/zh.json
CHANGED
|
@@ -91,7 +91,6 @@
|
|
|
91
91
|
"已是最新": "已是最新",
|
|
92
92
|
"发现 {version}": "发现 {version}",
|
|
93
93
|
"更新": "更新",
|
|
94
|
-
"取消": "取消",
|
|
95
94
|
"复制命令": "复制命令",
|
|
96
95
|
"命令已复制": "命令已复制",
|
|
97
96
|
"复制失败": "复制失败",
|
|
@@ -132,5 +131,11 @@
|
|
|
132
131
|
"命中率": "命中率",
|
|
133
132
|
"无数据": "无数据",
|
|
134
133
|
"多币种下成本柱不可用,请切换其他指标": "多币种下成本柱不可用,请切换其他指标",
|
|
135
|
-
"万": "万"
|
|
134
|
+
"万": "万",
|
|
135
|
+
"更新中": "更新中",
|
|
136
|
+
"更新检查失败": "更新检查失败",
|
|
137
|
+
"版本号不合法": "版本号不合法",
|
|
138
|
+
"该版本未发布": "该版本未发布",
|
|
139
|
+
"版本未变化": "版本未变化",
|
|
140
|
+
"未找到 dsh 命令": "未找到 dsh 命令"
|
|
136
141
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-token-dash",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "DeepSeek Harness Token 看板:月度预算与订阅配额、账户余额、时间范围费用与真实 Tokens 明细,支持本地 JSON 导出 / 导入备份。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -66,4 +66,4 @@
|
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"playwright": "1.64.1"
|
|
68
68
|
}
|
|
69
|
-
}
|
|
69
|
+
}
|