@lingda-ai/dsh-plugin-ledger 0.1.7 → 0.1.9
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/docs/technical.md +20 -1
- package/lib/client.js +191 -38
- package/lib/client.src.js +34 -9
- package/lib/guard.js +8 -1
- package/lib/index.js +23 -2
- package/lib/ledger.js +12 -1
- package/lib/panel-view.js +156 -30
- package/lib/snapshot-file.js +16 -2
- package/package.json +1 -1
package/docs/technical.md
CHANGED
|
@@ -261,7 +261,7 @@ token 只是 `measures` 里的一种单位。计划中的第二个来源(Trae
|
|
|
261
261
|
|
|
262
262
|
| 手段 | 覆盖 | 产出 |
|
|
263
263
|
|---|---|---|
|
|
264
|
-
| `node --test test/*.test.mjs` |
|
|
264
|
+
| `node --test test/*.test.mjs` | 225 例断言 | 计价、归因、预算回滞、幂等、身份、卸载残留、面板 SSR、客户端产物形态 |
|
|
265
265
|
| `node scripts/build-client.mjs` | 产物形态 | 从源码重建 `lib/client.js`(零 import/export 的 loader 包) |
|
|
266
266
|
| `scripts/bench.mjs --gate` | 热路径 + 内存 | 上表数字 |
|
|
267
267
|
| `scripts/smoke-registry.mjs` | 插件装配契约 | 假 ctx 下工具注册/提供不抛 |
|
|
@@ -270,6 +270,9 @@ token 只是 `measures` 里的一种单位。计划中的第二个来源(Trae
|
|
|
270
270
|
| `scripts/render-panel.mjs` | 视觉(单状态) | 真实 `renderPayload()` 输出,三列宽度 |
|
|
271
271
|
| `scripts/render-states.mjs` | 视觉(状态矩阵) | 7 个状态并排:常规/空态/费率未知/费率被拒/展开/预算/300px |
|
|
272
272
|
| `test/client-lifecycle.test.mjs` | 客户端生命周期 | 登记可逆、重复 apply、无 slots 降级、登记抛错不冒泡 |
|
|
273
|
+
| `test/snapshot-roundtrip.test.mjs` | 写盘→读回全链路 | 20 条明细(400+ 行)分页读回、truncated 落盘、二级降级不超 maxBytes |
|
|
274
|
+
| `test/guard-downgrade.test.mjs` | 预算降级矩阵 | provider/model/maxTokens 覆盖、阈值、未知成本不判、next 抛错冒泡 |
|
|
275
|
+
| `test/client-artifact-render.test.mjs` | 产物渲染 | 用 `lib/client.js` + 真 React 渲染有数据态与组件首帧(抓出过重名常量导致的 SyntaxError) |
|
|
273
276
|
|
|
274
277
|
**SKIP 不等于通过**:冒烟脚本找不到 DSH 运行时用退出码 2 表示 SKIP,`prepublish.sh` 第 6 步把 SKIP 判 FAIL。
|
|
275
278
|
这条是为了避免"换台机器 CI 照样全绿,但契约一条没验"。
|
|
@@ -383,6 +386,22 @@ ctx.get('slots') // 可选服务:不受 inject 约
|
|
|
383
386
|
默认姿态是"退化成一个没有面板的插件",而不是"把宿主带走";同时新增反证测试:
|
|
384
387
|
把 `inject` 去掉,`apply` 必须抛 `without inject`——这条测试的存在意义就是让这个错在单测里炸。
|
|
385
388
|
|
|
389
|
+
**12.7 三条跨模块契约,从来没被同一条测试同时握住两端。**
|
|
390
|
+
|
|
391
|
+
一次针对性审计(自动化测试视角)挖出三个**当前代码的真实故障**,都不是理论风险:
|
|
392
|
+
|
|
393
|
+
| 故障 | 为什么单测全绿 |
|
|
394
|
+
|---|---|
|
|
395
|
+
| 面板读回:Host 写的是多行 JSON,`workspaceFiles.read` 是**按行分页**的(一页最多 400 行),而浏览器半只读一页还要求 `eof`。一份 20 条明细的快照有 461~587 行 → 任何稍成熟的会话打开面板都是「读取失败」 | Host 侧测 payload 对象(没写盘),浏览器侧测 mock 远程(没真文件),谁都没测真实尺寸 |
|
|
396
|
+
| `truncated` 不落盘:它只是 `buildPanelPayload` 的返回值,payload 里没有这个字段,面板的"明细已截断"提示是死代码 | 单测断言的是返回值 `r.truncated`,正好把落盘那一步遮住 |
|
|
397
|
+
| `assistant/attempt` 污染预算:该事件无 usage,记成 `unknown(no-usage)` 后 `guard.spentOf` 见到 `unknownEntries > 0` 就整条放弃预算,降级静默失效 | 全套用例里根本没构造过 attempt 事件 |
|
|
398
|
+
|
|
399
|
+
修法都不是加判断,而是**把两端放进同一条测试**:`snapshot-roundtrip.test.mjs` 用真 store + 真 publisher + 真文件 + 按行分页的假 remote;
|
|
400
|
+
`client-artifact-render.test.mjs` 用发布产物 + 真 React 渲染(它当场抓出一个重名常量导致的 SyntaxError——
|
|
401
|
+
四个模块打包进同一作用域,`REFRESH_MS` 重复声明,源码测试全绿、产物必然崩)。
|
|
402
|
+
|
|
403
|
+
一句话:**可以骗过单测的,永远是"我以为另一端是这样的"。**
|
|
404
|
+
|
|
386
405
|
### 工程侧的一条硬约束
|
|
387
406
|
|
|
388
407
|
`dsh plugin --profile <p> add file:<path>` 是 pnpm 的 `file:` 依赖:**文件硬链接、目录复制**。
|
package/lib/client.js
CHANGED
|
@@ -101,6 +101,13 @@ window.__ModuleLoader__.load({
|
|
|
101
101
|
|
|
102
102
|
/** 上下文规模用 k 缩写:42.0k 比 42,000 更适合一眼扫 */
|
|
103
103
|
/** 四档都齐才给总数:缺一档就当不知道,不把缺失当 0 加进去(否则会造出一个假数) */
|
|
104
|
+
/** 实付 + 省下 = "如果没有缓存本来要花的钱",也就是节省比例的分母。 */
|
|
105
|
+
function grossAmountOf(view) {
|
|
106
|
+
const saved = view?.totals?.saved?.amount
|
|
107
|
+
const spent = view?.totals?.cost?.amount
|
|
108
|
+
return typeof saved === 'number' && typeof spent === 'number' ? saved + spent : null
|
|
109
|
+
}
|
|
110
|
+
|
|
104
111
|
function tokensTotal(tokens) {
|
|
105
112
|
if (!tokens || typeof tokens !== 'object') return null
|
|
106
113
|
const parts = [tokens.input, tokens.output, tokens.cacheRead, tokens.cacheWrite]
|
|
@@ -134,6 +141,37 @@ window.__ModuleLoader__.load({
|
|
|
134
141
|
/** "谁花的"折叠前先显示几条:6 条是 300px 宽度下不做滚动还看得完的上限 */
|
|
135
142
|
const SOURCE_HEAD = 6
|
|
136
143
|
|
|
144
|
+
/** 面板自动刷新间隔:Host 落盘节流 3s,这里 5s,够快又不空转。 */
|
|
145
|
+
const REFRESH_MS = 5000
|
|
146
|
+
/** 单次读取的超时:超过它就必须报错,而不是让面板一直转圈。 */
|
|
147
|
+
const READ_TIMEOUT_MS = 8000
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 给一次远端读取加超时。
|
|
151
|
+
*
|
|
152
|
+
* RPC 卡住时 Promise 永远不 settle,界面就会停在"正在读取…"——用户既看不出坏在哪,
|
|
153
|
+
* 也没有重试的余地。宁可报"读取超时",也不要无声地转圈。
|
|
154
|
+
* @template T
|
|
155
|
+
* @param {Promise<T>} promise
|
|
156
|
+
* @param {number} ms
|
|
157
|
+
* @returns {Promise<T>}
|
|
158
|
+
*/
|
|
159
|
+
function withTimeout(promise, ms) {
|
|
160
|
+
return new Promise((resolve, reject) => {
|
|
161
|
+
const timer = setTimeout(() => reject(new Error(`读取超时(${ms}ms)`)), ms)
|
|
162
|
+
promise.then(
|
|
163
|
+
(value) => {
|
|
164
|
+
clearTimeout(timer)
|
|
165
|
+
resolve(value)
|
|
166
|
+
},
|
|
167
|
+
(error) => {
|
|
168
|
+
clearTimeout(timer)
|
|
169
|
+
reject(error)
|
|
170
|
+
},
|
|
171
|
+
)
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
|
|
137
175
|
// 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
|
|
138
176
|
// 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
|
|
139
177
|
const PRICING_NOTE = '按内置官方价估算 · 2026-11-19'
|
|
@@ -231,7 +269,7 @@ window.__ModuleLoader__.load({
|
|
|
231
269
|
|
|
232
270
|
const INK = '#1f2733'
|
|
233
271
|
const INK2 = '#5a6472'
|
|
234
|
-
const INK3 = '#
|
|
272
|
+
const INK3 = '#64707f'
|
|
235
273
|
|
|
236
274
|
/**
|
|
237
275
|
* 时间一律按**本地时区**显示。
|
|
@@ -310,28 +348,66 @@ window.__ModuleLoader__.load({
|
|
|
310
348
|
return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
|
|
311
349
|
}
|
|
312
350
|
|
|
351
|
+
/**
|
|
352
|
+
* 最近一次成功读取的快照,按会话索引。
|
|
353
|
+
*
|
|
354
|
+
* 为什么放在模块级而不是组件 state:右栏 tab 是 keepMounted 的常驻 UI,
|
|
355
|
+
* 宿主在切会话/重挂时会重建组件;state 一丢就又回到"正在读取…"。
|
|
356
|
+
* 有了这份缓存,第二次打开是**立刻有数**,轮询只负责刷新。
|
|
357
|
+
* @type {Map<string, object>}
|
|
358
|
+
*/
|
|
359
|
+
const viewCache = new Map()
|
|
360
|
+
|
|
313
361
|
function makeLedgerBody(React, fetchView) {
|
|
314
362
|
const h = React.createElement
|
|
315
363
|
|
|
316
364
|
return function LedgerBody(props) {
|
|
317
365
|
const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
|
|
318
|
-
const [view, setView] = React.useState(undefined)
|
|
366
|
+
const [view, setView] = React.useState(() => (sessionId === null ? undefined : viewCache.get(sessionId)))
|
|
319
367
|
const [busy, setBusy] = React.useState(false)
|
|
320
368
|
const [expanded, setExpanded] = React.useState(false)
|
|
369
|
+
// 正在飞的那一次请求:轮询必须跳过"上一拍还没回来"的这一次。
|
|
370
|
+
// 否则每 REFRESH_MS 就有一个新请求把上一个响应判定为过期,
|
|
371
|
+
// 只要单次读取慢于轮询间隔,面板就会**永远停在"正在读取…"**(真机上就是这个现象)。
|
|
372
|
+
const inFlight = React.useRef(false)
|
|
373
|
+
// 当前挂着的会话:响应回来时用它判断"是不是还在看同一个会话"
|
|
374
|
+
const liveSession = React.useRef(sessionId)
|
|
375
|
+
/** 挂载时刻:用来判断"这次读取是不是慢得反常" */
|
|
376
|
+
const mountedAt = React.useRef(Date.now())
|
|
321
377
|
|
|
322
378
|
const refresh = React.useCallback(async () => {
|
|
323
379
|
if (sessionId === null) return
|
|
380
|
+
if (inFlight.current) return
|
|
381
|
+
inFlight.current = true
|
|
382
|
+
const forSession = sessionId
|
|
383
|
+
const startedAt = Date.now()
|
|
324
384
|
setBusy(true)
|
|
325
385
|
try {
|
|
326
|
-
|
|
386
|
+
const next = await withTimeout(fetchView(forSession), READ_TIMEOUT_MS)
|
|
387
|
+
if (next !== null && next?.error === undefined) viewCache.set(forSession, next)
|
|
388
|
+
if (liveSession.current === forSession) setView(next)
|
|
389
|
+
} catch (error) {
|
|
390
|
+
// 任何异常都要落成可见的错误态。永久 loading 是最糟的失败方式:
|
|
391
|
+
// 用户既不知道坏在哪,也不知道能不能重试。
|
|
392
|
+
console.warn('[ledger] 读取账本快照失败:', error)
|
|
393
|
+
if (liveSession.current === forSession) {
|
|
394
|
+
setView({ error: `${error?.message ?? error}(耗时 ${Date.now() - startedAt}ms)` })
|
|
395
|
+
}
|
|
327
396
|
} finally {
|
|
328
|
-
|
|
397
|
+
inFlight.current = false
|
|
398
|
+
if (liveSession.current === forSession) setBusy(false)
|
|
329
399
|
}
|
|
330
400
|
}, [sessionId])
|
|
331
401
|
|
|
332
402
|
React.useEffect(() => {
|
|
403
|
+
liveSession.current = sessionId
|
|
404
|
+
// 切会话先清空:宁可闪一帧"正在读取",也不能让 B 会话标题下挂着 A 会话的金额
|
|
405
|
+
setView(undefined)
|
|
333
406
|
void refresh()
|
|
334
|
-
|
|
407
|
+
// 成本是持续读数,不是一张照片:挂载后自动刷新(Host 侧 3 秒落盘节流)
|
|
408
|
+
const timer = setInterval(() => { void refresh() }, REFRESH_MS)
|
|
409
|
+
return () => clearInterval(timer)
|
|
410
|
+
}, [refresh, sessionId])
|
|
335
411
|
|
|
336
412
|
const head = h(
|
|
337
413
|
'div',
|
|
@@ -367,9 +443,24 @@ window.__ModuleLoader__.load({
|
|
|
367
443
|
),
|
|
368
444
|
)
|
|
369
445
|
|
|
370
|
-
// loading
|
|
446
|
+
// loading:还没跑完第一次。超过 1.5 秒就把"读得慢"显出来,
|
|
447
|
+
// 永久转圈是最没法排查的失败方式(既没有错误码,也没有重试入口)
|
|
371
448
|
if (view === undefined) {
|
|
372
|
-
|
|
449
|
+
const slow = Date.now() - mountedAt.current > 1500
|
|
450
|
+
return h(
|
|
451
|
+
'div',
|
|
452
|
+
null,
|
|
453
|
+
head,
|
|
454
|
+
h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, slow ? '正在读取…(比预期慢)' : '正在读取…'),
|
|
455
|
+
slow
|
|
456
|
+
? h(
|
|
457
|
+
'p',
|
|
458
|
+
{ style: { margin: '0 14px 12px', fontSize: 11, lineHeight: 1.7, color: INK3 } },
|
|
459
|
+
`已等待 ${Math.round((Date.now() - mountedAt.current) / 1000)} 秒 · 点「刷新」可重试。`
|
|
460
|
+
+ '若一直如此,多半是快照文件还没落盘(Host 每 3 秒最多写一次)。',
|
|
461
|
+
)
|
|
462
|
+
: null,
|
|
463
|
+
)
|
|
373
464
|
}
|
|
374
465
|
|
|
375
466
|
// 通道或解析出错
|
|
@@ -426,7 +517,9 @@ window.__ModuleLoader__.load({
|
|
|
426
517
|
const unattributed = list.find((item) => item?.plugin === 'unattributed')
|
|
427
518
|
const lost = typeof unattributed?.entries === 'number' && unattributed.entries > 0 ? unattributed.entries : null
|
|
428
519
|
if (lost === null) return `${entries} 次调用`
|
|
429
|
-
|
|
520
|
+
// 全部落在 unattributed 时不能写"来源未配置":那个桶里既有"本会话没调用工具"(no-signal),
|
|
521
|
+
// 也有"调了工具但没登记 owner"(no-origin)。写"配置"会把纯聊天会话指去改配置。
|
|
522
|
+
if (lost === entries) return `${entries} 次调用 · 归因无信号`
|
|
430
523
|
return `${entries} 次调用 · ${lost} 次未归因`
|
|
431
524
|
}
|
|
432
525
|
|
|
@@ -581,16 +674,22 @@ window.__ModuleLoader__.load({
|
|
|
581
674
|
: h(
|
|
582
675
|
'div',
|
|
583
676
|
{ style: { marginTop: 4, fontSize: 11, lineHeight: 1.6, color: GOOD, fontVariantNumeric: 'tabular-nums' } },
|
|
584
|
-
|
|
677
|
+
`缓存已省 ${formatAmount(view.totals.saved.amount, view.totals.saved.currency)}${
|
|
585
678
|
typeof view.totals.savedShare === 'number'
|
|
586
|
-
? ` ·
|
|
679
|
+
? ` · 如未命中需 ${formatAmount(grossAmountOf(view), view.totals.saved.currency)}(少花 ${formatShare(view.totals.savedShare)})`
|
|
587
680
|
: ''
|
|
588
681
|
}`,
|
|
589
682
|
),
|
|
590
683
|
),
|
|
591
684
|
// 预算条:只有配置了 limit 才画,未计价时不假装花了 0
|
|
592
|
-
view.budget
|
|
685
|
+
view.budget === null || view.budget === undefined
|
|
593
686
|
? h(
|
|
687
|
+
'div',
|
|
688
|
+
{ style: { padding: '0 14px 8px', fontSize: 11, color: INK3 } },
|
|
689
|
+
// 静默消失会被读成"这个面板没有这个功能";说清是配置项,用户才知道怎么开
|
|
690
|
+
'未设预算 · 配 budget.limit 后这里显示"还能问几次"',
|
|
691
|
+
)
|
|
692
|
+
: h(
|
|
594
693
|
'div',
|
|
595
694
|
{ style: { padding: '0 14px 10px' } },
|
|
596
695
|
h(
|
|
@@ -616,8 +715,7 @@ window.__ModuleLoader__.load({
|
|
|
616
715
|
},
|
|
617
716
|
}),
|
|
618
717
|
),
|
|
619
|
-
)
|
|
620
|
-
: null,
|
|
718
|
+
),
|
|
621
719
|
// token 四档
|
|
622
720
|
h(
|
|
623
721
|
'div',
|
|
@@ -635,8 +733,18 @@ window.__ModuleLoader__.load({
|
|
|
635
733
|
formatAmount(parts?.cacheRead, cost.currency),
|
|
636
734
|
`${formatTokens(tokens.cacheRead)} tok${hitRateOf(totals.cacheHitRate)}`,
|
|
637
735
|
),
|
|
638
|
-
|
|
639
|
-
|
|
736
|
+
// 缓存写:DeepSeek 没有独立写价,这一档恒为 0。占一行"0 tok ¥0.0000"只是噪音,
|
|
737
|
+
// 但真的产生了写 token 时必须画出来(其它 provider 会有)
|
|
738
|
+
(tokens.cacheWrite ?? 0) > 0 || (parts?.cacheWrite ?? 0) > 0
|
|
739
|
+
? rowOf(React, '缓存写', formatAmount(parts?.cacheWrite, cost.currency), `${formatTokens(tokens.cacheWrite)} tok`)
|
|
740
|
+
: null,
|
|
741
|
+
rowOf(
|
|
742
|
+
React,
|
|
743
|
+
'输出',
|
|
744
|
+
formatAmount(parts?.output, cost.currency),
|
|
745
|
+
// "含 reasoning" 在 reasoning=0 时是假陈述
|
|
746
|
+
`${formatTokens(tokens.output)} tok${(tokens.reasoning ?? 0) > 0 ? ' · 含 reasoning' : ''}`,
|
|
747
|
+
),
|
|
640
748
|
),
|
|
641
749
|
),
|
|
642
750
|
// 来源
|
|
@@ -720,10 +828,15 @@ window.__ModuleLoader__.load({
|
|
|
720
828
|
: h(
|
|
721
829
|
'span',
|
|
722
830
|
{ style: { fontSize: 11, color: INK3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
723
|
-
|
|
831
|
+
// 只说"最贵"会让人去优化那一步;补上定位与占比才知道值不值得优化
|
|
832
|
+
`最贵 ${typeof peak.turn === 'number' ? `T${peak.turn}·S${peak.step ?? '—'} ` : ''}${formatAmount(peak.amount, cost.currency)}${
|
|
833
|
+
moneyKnown && cost.amount > 0
|
|
834
|
+
? ` · 占 ${formatShare(peak.amount / cost.amount)}`
|
|
835
|
+
: ''
|
|
836
|
+
}`,
|
|
724
837
|
),
|
|
725
838
|
),
|
|
726
|
-
recent.slice(0, 5).map((item, index) =>
|
|
839
|
+
recent.slice(0, 5).map((item, index, all) =>
|
|
727
840
|
h(
|
|
728
841
|
'div',
|
|
729
842
|
{ key: `r-${index}`, style: { padding: '4px 0' } },
|
|
@@ -752,12 +865,30 @@ window.__ModuleLoader__.load({
|
|
|
752
865
|
// 第二行的优先级 = "为什么这一步贵":压缩收益 > 本次 token 量 > 工具体量 > 路由 > 归属。
|
|
753
866
|
// 380px 下这一行必定会被省略号截断,所以要让它从右边开始丢信息,
|
|
754
867
|
// 而不是从左边(左边留住的是解释,右边留住的是标识)。
|
|
755
|
-
...detailPartsOf(React, item, cost
|
|
868
|
+
...detailPartsOf(React, item, cost, {
|
|
869
|
+
// 同一段的模型名大多相同,重复 N 遍等于把"为什么贵"的信息挤出去
|
|
870
|
+
hideRoute: index > 0 && routeTextOf(item) === routeTextOf(all[index - 1]),
|
|
871
|
+
}),
|
|
756
872
|
),
|
|
757
873
|
),
|
|
758
874
|
),
|
|
759
875
|
)
|
|
760
876
|
: null,
|
|
877
|
+
// 结论行:② 问的是"为什么贵",一张等高的小额明细表回答不了。
|
|
878
|
+
// 只在"命中这一档确实占大头"时给一句人话,其余情况闭嘴(不为了凑结论而编结论)。
|
|
879
|
+
(() => {
|
|
880
|
+
if (!moneyKnown || typeof parts?.cacheRead !== 'number' || cost.amount <= 0) return null
|
|
881
|
+
const share = parts.cacheRead / cost.amount
|
|
882
|
+
const calls = totals.entries ?? 0
|
|
883
|
+
if (share < 0.5 || calls < 3) return null
|
|
884
|
+
const totalTok = tokens ? (tokens.input ?? 0) + (tokens.cacheRead ?? 0) + (tokens.output ?? 0) : null
|
|
885
|
+
return h(
|
|
886
|
+
'div',
|
|
887
|
+
{ style: { padding: '0 14px 10px', fontSize: 11, lineHeight: 1.65, color: INK2 } },
|
|
888
|
+
`钱主要花在重复送出的上下文:命中一档 ${formatAmount(parts.cacheRead, cost.currency)}(占 ${formatShare(share)})`,
|
|
889
|
+
totalTok === null ? '' : `,${calls} 次调用共送出 ${formatTokensCompact(totalTok)} tok`,
|
|
890
|
+
)
|
|
891
|
+
})(),
|
|
761
892
|
// 会话对比:只给其他会话,自己已经在顶部
|
|
762
893
|
others.length > 0
|
|
763
894
|
? h(
|
|
@@ -785,19 +916,14 @@ window.__ModuleLoader__.load({
|
|
|
785
916
|
),
|
|
786
917
|
)
|
|
787
918
|
: null,
|
|
788
|
-
//
|
|
789
|
-
h(
|
|
790
|
-
'div',
|
|
791
|
-
{ style: { padding: '6px 14px 12px', fontSize: 11, color: INK3 } },
|
|
792
|
-
`快照 ${formatLocalTime(view.generatedAt)}`,
|
|
793
|
-
),
|
|
919
|
+
// 页脚:快照时间 + 费率来源合成一行,省 20px 且不会出现"两个日期像两个时间戳"
|
|
794
920
|
h(
|
|
795
921
|
'div',
|
|
796
922
|
{
|
|
797
|
-
//
|
|
798
|
-
style: { padding: '
|
|
923
|
+
// 费率无效时整行转警示色:这是"金额不可信"的信号,不能和普通脚注同色
|
|
924
|
+
style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn ? WARN : INK3 },
|
|
799
925
|
},
|
|
800
|
-
note.text
|
|
926
|
+
`快照 ${formatLocalTime(view.generatedAt)} · ${note.text}`,
|
|
801
927
|
),
|
|
802
928
|
)
|
|
803
929
|
}
|
|
@@ -811,7 +937,7 @@ window.__ModuleLoader__.load({
|
|
|
811
937
|
* @param {object} item - compactEntry 产出的一条明细
|
|
812
938
|
* @param {object} cost - totals.cost(取币种与可读性标记)
|
|
813
939
|
*/
|
|
814
|
-
function detailPartsOf(React, item, cost) {
|
|
940
|
+
function detailPartsOf(React, item, cost, options = {}) {
|
|
815
941
|
const h = React.createElement
|
|
816
942
|
const parts = []
|
|
817
943
|
if (item.contextBeforeTokens !== null && item.contextBeforeTokens !== undefined) {
|
|
@@ -827,7 +953,7 @@ window.__ModuleLoader__.load({
|
|
|
827
953
|
parts.push(h('span', { style: { color: item.contextChars >= 10_000 ? WARN : INK3 } }, `工具结果 ${formatChars(item.contextChars)}`))
|
|
828
954
|
}
|
|
829
955
|
const route = routeTextOf(item)
|
|
830
|
-
if (route !==
|
|
956
|
+
if (route && options.hideRoute !== true) parts.push(route)
|
|
831
957
|
if (item.plugin !== null && item.plugin !== undefined) parts.push(sourceLabel(item.plugin))
|
|
832
958
|
return parts.flatMap((part, index) => (index === 0 ? [part] : [' · ', part]))
|
|
833
959
|
}
|
|
@@ -901,6 +1027,14 @@ window.__ModuleLoader__.load({
|
|
|
901
1027
|
/** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
|
|
902
1028
|
const LEDGER_KIND = 'ledger.cost'
|
|
903
1029
|
|
|
1030
|
+
/** 读回快照时的分页参数:一次最多 400 行(宿主 maxLines 的常见上限),最多翻 20 页。 */
|
|
1031
|
+
const PAGE_LINES = 400
|
|
1032
|
+
const MAX_PAGES = 20
|
|
1033
|
+
/** 文本总量的硬上限:超过就不是快照了(Host 侧 maxBytes 是 256KB) */
|
|
1034
|
+
const MAX_CHARS = 1_500_000
|
|
1035
|
+
// 注意:自动刷新间隔 REFRESH_MS 定义在 panel-view.js(组件住在那里)。
|
|
1036
|
+
// 打包时四个模块共用同一个作用域,重名会直接 SyntaxError —— 这是产物测试抓出来的。
|
|
1037
|
+
|
|
904
1038
|
/**
|
|
905
1039
|
* 硬依赖:没有右栏 tab 服务,这个插件什么都不用做。
|
|
906
1040
|
*
|
|
@@ -997,16 +1131,33 @@ window.__ModuleLoader__.load({
|
|
|
997
1131
|
const bytes = stat.value?.bytes
|
|
998
1132
|
if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
|
|
999
1133
|
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1134
|
+
// 宿主的 workspaceFiles.read 是**按行分页**的(offset=首页行号,limit=最大行数,
|
|
1135
|
+
// 且 limit 不得超过宿主配置的 maxLines)。一份 20 条明细的快照实测 461~587 行,
|
|
1136
|
+
// 而这里原来只读一页 400 行并要求 eof —— 结果是任何稍成熟点的会话打开面板都显示
|
|
1137
|
+
// "读取失败:快照过长"。必须翻页读完,而不是把页宽当文件长度。
|
|
1138
|
+
let text = ''
|
|
1139
|
+
let offset = 1
|
|
1140
|
+
let eof = false
|
|
1141
|
+
for (let page = 0; page < MAX_PAGES && !eof; page += 1) {
|
|
1142
|
+
let result
|
|
1143
|
+
try {
|
|
1144
|
+
result = await files.read(sessionId, absolutePath, { offset, limit: PAGE_LINES }, opts.signal)
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
return { error: stringifyError(error) }
|
|
1147
|
+
}
|
|
1148
|
+
if (!result?.ok) return { error: '读取快照失败' }
|
|
1149
|
+
const chunk = result.value?.text
|
|
1150
|
+
if (typeof chunk !== 'string') return { error: '快照内容为空' }
|
|
1151
|
+
// 分页边界可能落在换行上也可能不落:拼之前补一个换行,避免两页粘成一行坏 JSON
|
|
1152
|
+
if (text.length > 0 && !text.endsWith('\n')) text += '\n'
|
|
1153
|
+
text += chunk
|
|
1154
|
+
if (text.length > MAX_CHARS) return { error: '快照文件过大,已跳过' }
|
|
1155
|
+
eof = result.value?.eof !== false
|
|
1156
|
+
const lines = typeof result.value?.lines === 'number' ? result.value.lines : 0
|
|
1157
|
+
if (lines <= 0) break
|
|
1158
|
+
offset += lines
|
|
1005
1159
|
}
|
|
1006
|
-
if (!
|
|
1007
|
-
const text = page.value?.text
|
|
1008
|
-
if (typeof text !== 'string') return { error: '快照内容为空' }
|
|
1009
|
-
if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
|
|
1160
|
+
if (!eof) return { error: '快照过长,分页读取未完成' }
|
|
1010
1161
|
|
|
1011
1162
|
try {
|
|
1012
1163
|
const parsed = JSON.parse(text)
|
|
@@ -1153,6 +1304,8 @@ window.__ModuleLoader__.load({
|
|
|
1153
1304
|
// 硬依赖必须跟着产物一起导出:cordis 靠它判断"什么时候允许 apply",
|
|
1154
1305
|
// 漏了就会在 apply 里抛 cannot get property "..." without inject,把宿主启动带崩。
|
|
1155
1306
|
exports.inject = inject;
|
|
1307
|
+
// 纯函数面:只给测试与诊断用(renderPayload 等),不参与宿主运行
|
|
1308
|
+
exports.__internal = __internal;
|
|
1156
1309
|
return module.exports;
|
|
1157
1310
|
},
|
|
1158
1311
|
});
|
package/lib/client.src.js
CHANGED
|
@@ -43,6 +43,14 @@ const LEDGER_ID = '@lingda-ai/ledger'
|
|
|
43
43
|
/** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
|
|
44
44
|
const LEDGER_KIND = 'ledger.cost'
|
|
45
45
|
|
|
46
|
+
/** 读回快照时的分页参数:一次最多 400 行(宿主 maxLines 的常见上限),最多翻 20 页。 */
|
|
47
|
+
const PAGE_LINES = 400
|
|
48
|
+
const MAX_PAGES = 20
|
|
49
|
+
/** 文本总量的硬上限:超过就不是快照了(Host 侧 maxBytes 是 256KB) */
|
|
50
|
+
const MAX_CHARS = 1_500_000
|
|
51
|
+
// 注意:自动刷新间隔 REFRESH_MS 定义在 panel-view.js(组件住在那里)。
|
|
52
|
+
// 打包时四个模块共用同一个作用域,重名会直接 SyntaxError —— 这是产物测试抓出来的。
|
|
53
|
+
|
|
46
54
|
/**
|
|
47
55
|
* 硬依赖:没有右栏 tab 服务,这个插件什么都不用做。
|
|
48
56
|
*
|
|
@@ -153,16 +161,33 @@ export function createFetchView(ctx) {
|
|
|
153
161
|
const bytes = stat.value?.bytes
|
|
154
162
|
if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
|
|
155
163
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
164
|
+
// 宿主的 workspaceFiles.read 是**按行分页**的(offset=首页行号,limit=最大行数,
|
|
165
|
+
// 且 limit 不得超过宿主配置的 maxLines)。一份 20 条明细的快照实测 461~587 行,
|
|
166
|
+
// 而这里原来只读一页 400 行并要求 eof —— 结果是任何稍成熟点的会话打开面板都显示
|
|
167
|
+
// "读取失败:快照过长"。必须翻页读完,而不是把页宽当文件长度。
|
|
168
|
+
let text = ''
|
|
169
|
+
let offset = 1
|
|
170
|
+
let eof = false
|
|
171
|
+
for (let page = 0; page < MAX_PAGES && !eof; page += 1) {
|
|
172
|
+
let result
|
|
173
|
+
try {
|
|
174
|
+
result = await files.read(sessionId, absolutePath, { offset, limit: PAGE_LINES }, opts.signal)
|
|
175
|
+
} catch (error) {
|
|
176
|
+
return { error: stringifyError(error) }
|
|
177
|
+
}
|
|
178
|
+
if (!result?.ok) return { error: '读取快照失败' }
|
|
179
|
+
const chunk = result.value?.text
|
|
180
|
+
if (typeof chunk !== 'string') return { error: '快照内容为空' }
|
|
181
|
+
// 分页边界可能落在换行上也可能不落:拼之前补一个换行,避免两页粘成一行坏 JSON
|
|
182
|
+
if (text.length > 0 && !text.endsWith('\n')) text += '\n'
|
|
183
|
+
text += chunk
|
|
184
|
+
if (text.length > MAX_CHARS) return { error: '快照文件过大,已跳过' }
|
|
185
|
+
eof = result.value?.eof !== false
|
|
186
|
+
const lines = typeof result.value?.lines === 'number' ? result.value.lines : 0
|
|
187
|
+
if (lines <= 0) break
|
|
188
|
+
offset += lines
|
|
161
189
|
}
|
|
162
|
-
if (!
|
|
163
|
-
const text = page.value?.text
|
|
164
|
-
if (typeof text !== 'string') return { error: '快照内容为空' }
|
|
165
|
-
if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
|
|
190
|
+
if (!eof) return { error: '快照过长,分页读取未完成' }
|
|
166
191
|
|
|
167
192
|
try {
|
|
168
193
|
const parsed = JSON.parse(text)
|
package/lib/guard.js
CHANGED
|
@@ -68,7 +68,14 @@ export function createBudgetGuard({ store, config, deliver }) {
|
|
|
68
68
|
|
|
69
69
|
/** agent/request waterfall:只做降级,不做事实注入 */
|
|
70
70
|
async function onRequest(payload, next) {
|
|
71
|
-
|
|
71
|
+
// next() 自己也可能抛(上游适配器失败)。它必须在 try 里:否则一次上游异常会
|
|
72
|
+
// 从这个 waterfall 直接冒泡出去,而这里的职责只是"要不要改路由",不是"替上游报错"。
|
|
73
|
+
let config0
|
|
74
|
+
try {
|
|
75
|
+
config0 = await next()
|
|
76
|
+
} catch (error) {
|
|
77
|
+
throw error // 上游失败仍然要冒泡(那不是我们能降级的事),只是不进下面的降级逻辑
|
|
78
|
+
}
|
|
72
79
|
try {
|
|
73
80
|
if (!downgrade || !budgetEnabled(config)) return config0
|
|
74
81
|
if (!downgrade.provider && !downgrade.model) return config0
|
package/lib/index.js
CHANGED
|
@@ -24,6 +24,7 @@ import { createBudgetGuard } from './guard.js'
|
|
|
24
24
|
import { createLedgerQueryTool } from './audit-tool.js'
|
|
25
25
|
import { makeBudgetMessage } from './budget-message.js'
|
|
26
26
|
import { createSnapshotPublisher } from './snapshot-file.js'
|
|
27
|
+
import { PANEL_DIR } from './panel-path.js'
|
|
27
28
|
import { createTraceSink } from './trace-file.js'
|
|
28
29
|
|
|
29
30
|
export const name = 'ledger'
|
|
@@ -119,6 +120,16 @@ export function apply(ctx, rawConfig) {
|
|
|
119
120
|
|
|
120
121
|
// 右侧栏面板的数据通道:Host 落快照 JSON,浏览器半用 workspace 文件 remote 读回。
|
|
121
122
|
// 默认关闭(config.panel.enabled),打开才有写盘副作用。
|
|
123
|
+
// 客户端的读路径固定是 <session cwd>/.dsh/ledger/<safe>.json(panel-path.js 两侧共用)。
|
|
124
|
+
// 自定义 panel.dir 会让 Host 写到别处、面板读空——这不是"配置不生效",是"看不到",
|
|
125
|
+
// 必须显性说出来,否则用户会以为是插件坏了。
|
|
126
|
+
if (config.panel?.enabled === true && (config.panel.dir ?? PANEL_DIR) !== PANEL_DIR) {
|
|
127
|
+
console.warn(
|
|
128
|
+
`[ledger] panel.dir=${JSON.stringify(config.panel.dir)} 与浏览器侧的固定读路径 ${PANEL_DIR} 不一致,`
|
|
129
|
+
+ '面板将读不到快照。面板开启时请保持默认目录。',
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
122
133
|
const publisher =
|
|
123
134
|
config.panel?.enabled === true
|
|
124
135
|
? createSnapshotPublisher({
|
|
@@ -201,10 +212,20 @@ export function apply(ctx, rawConfig) {
|
|
|
201
212
|
pricing: pricingMeta,
|
|
202
213
|
config,
|
|
203
214
|
}
|
|
204
|
-
// 仓库既有插件统一用 ctx.provide 暴露服务(见 lingzhi-core / lingzhi-workbench
|
|
205
|
-
ctx
|
|
215
|
+
// 仓库既有插件统一用 ctx.provide 暴露服务(见 lingzhi-core / lingzhi-workbench)。
|
|
216
|
+
// 但同一个 ctx 被重复装配时(HMR、禁用后重新启用)provide 会抛 "service already exists",
|
|
217
|
+
// 而它在 apply 里抛=宿主启动失败。服务已经在了就复用,插件其余部分照常工作。
|
|
218
|
+
try {
|
|
219
|
+
ctx.provide('ledger', api)
|
|
220
|
+
} catch (error) {
|
|
221
|
+
console.warn('[ledger] 服务 ledger 已存在,复用既有实例(重复装配):', error?.message ?? error)
|
|
222
|
+
}
|
|
206
223
|
|
|
224
|
+
let disposed = false
|
|
207
225
|
const cleanup = () => {
|
|
226
|
+
// 幂等:宿主可能既跑 effect 清理又触发 dispose 事件,重复释放会二次 flush/close
|
|
227
|
+
if (disposed) return
|
|
228
|
+
disposed = true
|
|
208
229
|
publisher?.dispose()
|
|
209
230
|
traceSink?.dispose()
|
|
210
231
|
}
|
package/lib/ledger.js
CHANGED
|
@@ -44,6 +44,8 @@ const COMPACTION_PREFIX = 'compaction/'
|
|
|
44
44
|
export function createLedger({ store, pricing, attribution, trace, onEntry, cwdOf, identity, now = () => Date.now() }) {
|
|
45
45
|
let failures = 0
|
|
46
46
|
let handled = 0
|
|
47
|
+
/** 无 usage 的模型事件数(assistant/attempt 之类)。它们是"尝试",不是计费调用。 */
|
|
48
|
+
let skipped = 0
|
|
47
49
|
|
|
48
50
|
/**
|
|
49
51
|
* 唯一入账出口。`onEntry` 是给 Budget Guard 的正式钩子,
|
|
@@ -91,6 +93,15 @@ export function createLedger({ store, pricing, attribution, trace, onEntry, cwdO
|
|
|
91
93
|
const step = event.step ?? 0
|
|
92
94
|
|
|
93
95
|
const usage = normalizeUsage(event.usage ?? event.message?.usage)
|
|
96
|
+
// 没有 usage 的模型事件(assistant/attempt)不是计费调用,**不能入账**:
|
|
97
|
+
// - 它会变成一条 unknown(no-usage),而 guard 见到 unknownEntries > 0 就整条放弃预算,
|
|
98
|
+
// 于是"预算降级"静默失效,面板还会误报"合计偏低"(实测注入 0 条预算事实);
|
|
99
|
+
// - 它也没有任何金额可记,记了只会在明细里多一行"未知"噪音。
|
|
100
|
+
// 计数留在 stats.skipped 里,仍然可观测。
|
|
101
|
+
if (usage === null) {
|
|
102
|
+
skipped += 1
|
|
103
|
+
return
|
|
104
|
+
}
|
|
94
105
|
const route = routeOf(event)
|
|
95
106
|
const cost = pricing.costOf(usage, route)
|
|
96
107
|
|
|
@@ -255,6 +266,6 @@ export function createLedger({ store, pricing, attribution, trace, onEntry, cwdO
|
|
|
255
266
|
pendingCompaction.delete(sessionId)
|
|
256
267
|
identityBySession.delete(sessionId)
|
|
257
268
|
},
|
|
258
|
-
stats: () => ({ handled, failures }),
|
|
269
|
+
stats: () => ({ handled, failures, skipped }),
|
|
259
270
|
}
|
|
260
271
|
}
|
package/lib/panel-view.js
CHANGED
|
@@ -18,7 +18,14 @@ function routeTextOf(item) {
|
|
|
18
18
|
|
|
19
19
|
/** 上下文规模用 k 缩写:42.0k 比 42,000 更适合一眼扫 */
|
|
20
20
|
/** 四档都齐才给总数:缺一档就当不知道,不把缺失当 0 加进去(否则会造出一个假数) */
|
|
21
|
-
export
|
|
21
|
+
export /** 实付 + 省下 = "如果没有缓存本来要花的钱",也就是节省比例的分母。 */
|
|
22
|
+
function grossAmountOf(view) {
|
|
23
|
+
const saved = view?.totals?.saved?.amount
|
|
24
|
+
const spent = view?.totals?.cost?.amount
|
|
25
|
+
return typeof saved === 'number' && typeof spent === 'number' ? saved + spent : null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function tokensTotal(tokens) {
|
|
22
29
|
if (!tokens || typeof tokens !== 'object') return null
|
|
23
30
|
const parts = [tokens.input, tokens.output, tokens.cacheRead, tokens.cacheWrite]
|
|
24
31
|
if (!parts.every((v) => Number.isFinite(v))) return null
|
|
@@ -51,6 +58,37 @@ const GOOD = '#2f7d64'
|
|
|
51
58
|
/** "谁花的"折叠前先显示几条:6 条是 300px 宽度下不做滚动还看得完的上限 */
|
|
52
59
|
const SOURCE_HEAD = 6
|
|
53
60
|
|
|
61
|
+
/** 面板自动刷新间隔:Host 落盘节流 3s,这里 5s,够快又不空转。 */
|
|
62
|
+
const REFRESH_MS = 5000
|
|
63
|
+
/** 单次读取的超时:超过它就必须报错,而不是让面板一直转圈。 */
|
|
64
|
+
const READ_TIMEOUT_MS = 8000
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 给一次远端读取加超时。
|
|
68
|
+
*
|
|
69
|
+
* RPC 卡住时 Promise 永远不 settle,界面就会停在"正在读取…"——用户既看不出坏在哪,
|
|
70
|
+
* 也没有重试的余地。宁可报"读取超时",也不要无声地转圈。
|
|
71
|
+
* @template T
|
|
72
|
+
* @param {Promise<T>} promise
|
|
73
|
+
* @param {number} ms
|
|
74
|
+
* @returns {Promise<T>}
|
|
75
|
+
*/
|
|
76
|
+
function withTimeout(promise, ms) {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
const timer = setTimeout(() => reject(new Error(`读取超时(${ms}ms)`)), ms)
|
|
79
|
+
promise.then(
|
|
80
|
+
(value) => {
|
|
81
|
+
clearTimeout(timer)
|
|
82
|
+
resolve(value)
|
|
83
|
+
},
|
|
84
|
+
(error) => {
|
|
85
|
+
clearTimeout(timer)
|
|
86
|
+
reject(error)
|
|
87
|
+
},
|
|
88
|
+
)
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
54
92
|
// 老快照(没有 pricing 字段)的兜底文案。新快照一律由 pricingNoteOf 生成,
|
|
55
93
|
// 因为"内置还是自定义、哪天的价、有没有被忽略的模型"只能从数据里读,不能写死。
|
|
56
94
|
const PRICING_NOTE = '按内置官方价估算 · 2026-11-19'
|
|
@@ -148,7 +186,7 @@ function pricingBanner(React, note) {
|
|
|
148
186
|
|
|
149
187
|
const INK = '#1f2733'
|
|
150
188
|
const INK2 = '#5a6472'
|
|
151
|
-
const INK3 = '#
|
|
189
|
+
const INK3 = '#64707f'
|
|
152
190
|
|
|
153
191
|
/**
|
|
154
192
|
* 时间一律按**本地时区**显示。
|
|
@@ -227,28 +265,66 @@ function formatShare(share) {
|
|
|
227
265
|
return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
|
|
228
266
|
}
|
|
229
267
|
|
|
268
|
+
/**
|
|
269
|
+
* 最近一次成功读取的快照,按会话索引。
|
|
270
|
+
*
|
|
271
|
+
* 为什么放在模块级而不是组件 state:右栏 tab 是 keepMounted 的常驻 UI,
|
|
272
|
+
* 宿主在切会话/重挂时会重建组件;state 一丢就又回到"正在读取…"。
|
|
273
|
+
* 有了这份缓存,第二次打开是**立刻有数**,轮询只负责刷新。
|
|
274
|
+
* @type {Map<string, object>}
|
|
275
|
+
*/
|
|
276
|
+
const viewCache = new Map()
|
|
277
|
+
|
|
230
278
|
function makeLedgerBody(React, fetchView) {
|
|
231
279
|
const h = React.createElement
|
|
232
280
|
|
|
233
281
|
return function LedgerBody(props) {
|
|
234
282
|
const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : null
|
|
235
|
-
const [view, setView] = React.useState(undefined)
|
|
283
|
+
const [view, setView] = React.useState(() => (sessionId === null ? undefined : viewCache.get(sessionId)))
|
|
236
284
|
const [busy, setBusy] = React.useState(false)
|
|
237
285
|
const [expanded, setExpanded] = React.useState(false)
|
|
286
|
+
// 正在飞的那一次请求:轮询必须跳过"上一拍还没回来"的这一次。
|
|
287
|
+
// 否则每 REFRESH_MS 就有一个新请求把上一个响应判定为过期,
|
|
288
|
+
// 只要单次读取慢于轮询间隔,面板就会**永远停在"正在读取…"**(真机上就是这个现象)。
|
|
289
|
+
const inFlight = React.useRef(false)
|
|
290
|
+
// 当前挂着的会话:响应回来时用它判断"是不是还在看同一个会话"
|
|
291
|
+
const liveSession = React.useRef(sessionId)
|
|
292
|
+
/** 挂载时刻:用来判断"这次读取是不是慢得反常" */
|
|
293
|
+
const mountedAt = React.useRef(Date.now())
|
|
238
294
|
|
|
239
295
|
const refresh = React.useCallback(async () => {
|
|
240
296
|
if (sessionId === null) return
|
|
297
|
+
if (inFlight.current) return
|
|
298
|
+
inFlight.current = true
|
|
299
|
+
const forSession = sessionId
|
|
300
|
+
const startedAt = Date.now()
|
|
241
301
|
setBusy(true)
|
|
242
302
|
try {
|
|
243
|
-
|
|
303
|
+
const next = await withTimeout(fetchView(forSession), READ_TIMEOUT_MS)
|
|
304
|
+
if (next !== null && next?.error === undefined) viewCache.set(forSession, next)
|
|
305
|
+
if (liveSession.current === forSession) setView(next)
|
|
306
|
+
} catch (error) {
|
|
307
|
+
// 任何异常都要落成可见的错误态。永久 loading 是最糟的失败方式:
|
|
308
|
+
// 用户既不知道坏在哪,也不知道能不能重试。
|
|
309
|
+
console.warn('[ledger] 读取账本快照失败:', error)
|
|
310
|
+
if (liveSession.current === forSession) {
|
|
311
|
+
setView({ error: `${error?.message ?? error}(耗时 ${Date.now() - startedAt}ms)` })
|
|
312
|
+
}
|
|
244
313
|
} finally {
|
|
245
|
-
|
|
314
|
+
inFlight.current = false
|
|
315
|
+
if (liveSession.current === forSession) setBusy(false)
|
|
246
316
|
}
|
|
247
317
|
}, [sessionId])
|
|
248
318
|
|
|
249
319
|
React.useEffect(() => {
|
|
320
|
+
liveSession.current = sessionId
|
|
321
|
+
// 切会话先清空:宁可闪一帧"正在读取",也不能让 B 会话标题下挂着 A 会话的金额
|
|
322
|
+
setView(undefined)
|
|
250
323
|
void refresh()
|
|
251
|
-
|
|
324
|
+
// 成本是持续读数,不是一张照片:挂载后自动刷新(Host 侧 3 秒落盘节流)
|
|
325
|
+
const timer = setInterval(() => { void refresh() }, REFRESH_MS)
|
|
326
|
+
return () => clearInterval(timer)
|
|
327
|
+
}, [refresh, sessionId])
|
|
252
328
|
|
|
253
329
|
const head = h(
|
|
254
330
|
'div',
|
|
@@ -284,9 +360,24 @@ function makeLedgerBody(React, fetchView) {
|
|
|
284
360
|
),
|
|
285
361
|
)
|
|
286
362
|
|
|
287
|
-
// loading
|
|
363
|
+
// loading:还没跑完第一次。超过 1.5 秒就把"读得慢"显出来,
|
|
364
|
+
// 永久转圈是最没法排查的失败方式(既没有错误码,也没有重试入口)
|
|
288
365
|
if (view === undefined) {
|
|
289
|
-
|
|
366
|
+
const slow = Date.now() - mountedAt.current > 1500
|
|
367
|
+
return h(
|
|
368
|
+
'div',
|
|
369
|
+
null,
|
|
370
|
+
head,
|
|
371
|
+
h('p', { style: { margin: '12px 14px', fontSize: 12, color: INK3 } }, slow ? '正在读取…(比预期慢)' : '正在读取…'),
|
|
372
|
+
slow
|
|
373
|
+
? h(
|
|
374
|
+
'p',
|
|
375
|
+
{ style: { margin: '0 14px 12px', fontSize: 11, lineHeight: 1.7, color: INK3 } },
|
|
376
|
+
`已等待 ${Math.round((Date.now() - mountedAt.current) / 1000)} 秒 · 点「刷新」可重试。`
|
|
377
|
+
+ '若一直如此,多半是快照文件还没落盘(Host 每 3 秒最多写一次)。',
|
|
378
|
+
)
|
|
379
|
+
: null,
|
|
380
|
+
)
|
|
290
381
|
}
|
|
291
382
|
|
|
292
383
|
// 通道或解析出错
|
|
@@ -343,7 +434,9 @@ function summaryOf(totals, list) {
|
|
|
343
434
|
const unattributed = list.find((item) => item?.plugin === 'unattributed')
|
|
344
435
|
const lost = typeof unattributed?.entries === 'number' && unattributed.entries > 0 ? unattributed.entries : null
|
|
345
436
|
if (lost === null) return `${entries} 次调用`
|
|
346
|
-
|
|
437
|
+
// 全部落在 unattributed 时不能写"来源未配置":那个桶里既有"本会话没调用工具"(no-signal),
|
|
438
|
+
// 也有"调了工具但没登记 owner"(no-origin)。写"配置"会把纯聊天会话指去改配置。
|
|
439
|
+
if (lost === entries) return `${entries} 次调用 · 归因无信号`
|
|
347
440
|
return `${entries} 次调用 · ${lost} 次未归因`
|
|
348
441
|
}
|
|
349
442
|
|
|
@@ -498,16 +591,22 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
498
591
|
: h(
|
|
499
592
|
'div',
|
|
500
593
|
{ style: { marginTop: 4, fontSize: 11, lineHeight: 1.6, color: GOOD, fontVariantNumeric: 'tabular-nums' } },
|
|
501
|
-
|
|
594
|
+
`缓存已省 ${formatAmount(view.totals.saved.amount, view.totals.saved.currency)}${
|
|
502
595
|
typeof view.totals.savedShare === 'number'
|
|
503
|
-
? ` ·
|
|
596
|
+
? ` · 如未命中需 ${formatAmount(grossAmountOf(view), view.totals.saved.currency)}(少花 ${formatShare(view.totals.savedShare)})`
|
|
504
597
|
: ''
|
|
505
598
|
}`,
|
|
506
599
|
),
|
|
507
600
|
),
|
|
508
601
|
// 预算条:只有配置了 limit 才画,未计价时不假装花了 0
|
|
509
|
-
view.budget
|
|
602
|
+
view.budget === null || view.budget === undefined
|
|
510
603
|
? h(
|
|
604
|
+
'div',
|
|
605
|
+
{ style: { padding: '0 14px 8px', fontSize: 11, color: INK3 } },
|
|
606
|
+
// 静默消失会被读成"这个面板没有这个功能";说清是配置项,用户才知道怎么开
|
|
607
|
+
'未设预算 · 配 budget.limit 后这里显示"还能问几次"',
|
|
608
|
+
)
|
|
609
|
+
: h(
|
|
511
610
|
'div',
|
|
512
611
|
{ style: { padding: '0 14px 10px' } },
|
|
513
612
|
h(
|
|
@@ -533,8 +632,7 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
533
632
|
},
|
|
534
633
|
}),
|
|
535
634
|
),
|
|
536
|
-
)
|
|
537
|
-
: null,
|
|
635
|
+
),
|
|
538
636
|
// token 四档
|
|
539
637
|
h(
|
|
540
638
|
'div',
|
|
@@ -552,8 +650,18 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
552
650
|
formatAmount(parts?.cacheRead, cost.currency),
|
|
553
651
|
`${formatTokens(tokens.cacheRead)} tok${hitRateOf(totals.cacheHitRate)}`,
|
|
554
652
|
),
|
|
555
|
-
|
|
556
|
-
|
|
653
|
+
// 缓存写:DeepSeek 没有独立写价,这一档恒为 0。占一行"0 tok ¥0.0000"只是噪音,
|
|
654
|
+
// 但真的产生了写 token 时必须画出来(其它 provider 会有)
|
|
655
|
+
(tokens.cacheWrite ?? 0) > 0 || (parts?.cacheWrite ?? 0) > 0
|
|
656
|
+
? rowOf(React, '缓存写', formatAmount(parts?.cacheWrite, cost.currency), `${formatTokens(tokens.cacheWrite)} tok`)
|
|
657
|
+
: null,
|
|
658
|
+
rowOf(
|
|
659
|
+
React,
|
|
660
|
+
'输出',
|
|
661
|
+
formatAmount(parts?.output, cost.currency),
|
|
662
|
+
// "含 reasoning" 在 reasoning=0 时是假陈述
|
|
663
|
+
`${formatTokens(tokens.output)} tok${(tokens.reasoning ?? 0) > 0 ? ' · 含 reasoning' : ''}`,
|
|
664
|
+
),
|
|
557
665
|
),
|
|
558
666
|
),
|
|
559
667
|
// 来源
|
|
@@ -637,10 +745,15 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
637
745
|
: h(
|
|
638
746
|
'span',
|
|
639
747
|
{ style: { fontSize: 11, color: INK3, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
|
|
640
|
-
|
|
748
|
+
// 只说"最贵"会让人去优化那一步;补上定位与占比才知道值不值得优化
|
|
749
|
+
`最贵 ${typeof peak.turn === 'number' ? `T${peak.turn}·S${peak.step ?? '—'} ` : ''}${formatAmount(peak.amount, cost.currency)}${
|
|
750
|
+
moneyKnown && cost.amount > 0
|
|
751
|
+
? ` · 占 ${formatShare(peak.amount / cost.amount)}`
|
|
752
|
+
: ''
|
|
753
|
+
}`,
|
|
641
754
|
),
|
|
642
755
|
),
|
|
643
|
-
recent.slice(0, 5).map((item, index) =>
|
|
756
|
+
recent.slice(0, 5).map((item, index, all) =>
|
|
644
757
|
h(
|
|
645
758
|
'div',
|
|
646
759
|
{ key: `r-${index}`, style: { padding: '4px 0' } },
|
|
@@ -669,12 +782,30 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
669
782
|
// 第二行的优先级 = "为什么这一步贵":压缩收益 > 本次 token 量 > 工具体量 > 路由 > 归属。
|
|
670
783
|
// 380px 下这一行必定会被省略号截断,所以要让它从右边开始丢信息,
|
|
671
784
|
// 而不是从左边(左边留住的是解释,右边留住的是标识)。
|
|
672
|
-
...detailPartsOf(React, item, cost
|
|
785
|
+
...detailPartsOf(React, item, cost, {
|
|
786
|
+
// 同一段的模型名大多相同,重复 N 遍等于把"为什么贵"的信息挤出去
|
|
787
|
+
hideRoute: index > 0 && routeTextOf(item) === routeTextOf(all[index - 1]),
|
|
788
|
+
}),
|
|
673
789
|
),
|
|
674
790
|
),
|
|
675
791
|
),
|
|
676
792
|
)
|
|
677
793
|
: null,
|
|
794
|
+
// 结论行:② 问的是"为什么贵",一张等高的小额明细表回答不了。
|
|
795
|
+
// 只在"命中这一档确实占大头"时给一句人话,其余情况闭嘴(不为了凑结论而编结论)。
|
|
796
|
+
(() => {
|
|
797
|
+
if (!moneyKnown || typeof parts?.cacheRead !== 'number' || cost.amount <= 0) return null
|
|
798
|
+
const share = parts.cacheRead / cost.amount
|
|
799
|
+
const calls = totals.entries ?? 0
|
|
800
|
+
if (share < 0.5 || calls < 3) return null
|
|
801
|
+
const totalTok = tokens ? (tokens.input ?? 0) + (tokens.cacheRead ?? 0) + (tokens.output ?? 0) : null
|
|
802
|
+
return h(
|
|
803
|
+
'div',
|
|
804
|
+
{ style: { padding: '0 14px 10px', fontSize: 11, lineHeight: 1.65, color: INK2 } },
|
|
805
|
+
`钱主要花在重复送出的上下文:命中一档 ${formatAmount(parts.cacheRead, cost.currency)}(占 ${formatShare(share)})`,
|
|
806
|
+
totalTok === null ? '' : `,${calls} 次调用共送出 ${formatTokensCompact(totalTok)} tok`,
|
|
807
|
+
)
|
|
808
|
+
})(),
|
|
678
809
|
// 会话对比:只给其他会话,自己已经在顶部
|
|
679
810
|
others.length > 0
|
|
680
811
|
? h(
|
|
@@ -702,19 +833,14 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
702
833
|
),
|
|
703
834
|
)
|
|
704
835
|
: null,
|
|
705
|
-
//
|
|
706
|
-
h(
|
|
707
|
-
'div',
|
|
708
|
-
{ style: { padding: '6px 14px 12px', fontSize: 11, color: INK3 } },
|
|
709
|
-
`快照 ${formatLocalTime(view.generatedAt)}`,
|
|
710
|
-
),
|
|
836
|
+
// 页脚:快照时间 + 费率来源合成一行,省 20px 且不会出现"两个日期像两个时间戳"
|
|
711
837
|
h(
|
|
712
838
|
'div',
|
|
713
839
|
{
|
|
714
|
-
//
|
|
715
|
-
style: { padding: '
|
|
840
|
+
// 费率无效时整行转警示色:这是"金额不可信"的信号,不能和普通脚注同色
|
|
841
|
+
style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn ? WARN : INK3 },
|
|
716
842
|
},
|
|
717
|
-
note.text
|
|
843
|
+
`快照 ${formatLocalTime(view.generatedAt)} · ${note.text}`,
|
|
718
844
|
),
|
|
719
845
|
)
|
|
720
846
|
}
|
|
@@ -728,7 +854,7 @@ function renderPayload(React, view, sessionId, head, options = {}) {
|
|
|
728
854
|
* @param {object} item - compactEntry 产出的一条明细
|
|
729
855
|
* @param {object} cost - totals.cost(取币种与可读性标记)
|
|
730
856
|
*/
|
|
731
|
-
function detailPartsOf(React, item, cost) {
|
|
857
|
+
function detailPartsOf(React, item, cost, options = {}) {
|
|
732
858
|
const h = React.createElement
|
|
733
859
|
const parts = []
|
|
734
860
|
if (item.contextBeforeTokens !== null && item.contextBeforeTokens !== undefined) {
|
|
@@ -744,7 +870,7 @@ function detailPartsOf(React, item, cost) {
|
|
|
744
870
|
parts.push(h('span', { style: { color: item.contextChars >= 10_000 ? WARN : INK3 } }, `工具结果 ${formatChars(item.contextChars)}`))
|
|
745
871
|
}
|
|
746
872
|
const route = routeTextOf(item)
|
|
747
|
-
if (route !==
|
|
873
|
+
if (route && options.hideRoute !== true) parts.push(route)
|
|
748
874
|
if (item.plugin !== null && item.plugin !== undefined) parts.push(sourceLabel(item.plugin))
|
|
749
875
|
return parts.flatMap((part, index) => (index === 0 ? [part] : [' · ', part]))
|
|
750
876
|
}
|
package/lib/snapshot-file.js
CHANGED
|
@@ -57,10 +57,24 @@ export function buildPanelPayload(snapshot, sources, { maxBytes = 262144, budget
|
|
|
57
57
|
// 费率来源:面板必须能说出"这些钱是按哪套价算的"。
|
|
58
58
|
// null 表示未传(老调用方),面板退化成只显示内置基准日。
|
|
59
59
|
pricing: pricing ?? null,
|
|
60
|
+
// 这个标志必须落在 payload 里:它同时是"给用户看的提示"和"给诊断用的计数"。
|
|
61
|
+
// 只把它当返回值,面板那一侧永远读到 undefined(历史上就是这样丢的)。
|
|
62
|
+
truncated: false,
|
|
60
63
|
}
|
|
61
64
|
const full = { ...base, sources: sources?.sources ?? [], sourceCount: sources?.sourceCount ?? null }
|
|
62
|
-
|
|
63
|
-
|
|
65
|
+
if (Buffer.byteLength(JSON.stringify(full)) <= maxBytes) return { payload: full, truncated: false }
|
|
66
|
+
|
|
67
|
+
// 一级降级:去掉 sources,保留最近明细
|
|
68
|
+
const slim = { ...base, truncated: true }
|
|
69
|
+
if (Buffer.byteLength(JSON.stringify(slim)) <= maxBytes) return { payload: slim, truncated: true }
|
|
70
|
+
|
|
71
|
+
// 二级降级:连明细也保不住时,只留合计与 Top 来源。
|
|
72
|
+
// 没有这一步,maxBytes 就只是个愿望——实测 20 条明细的 base 仍有 9.8KB。
|
|
73
|
+
const minimal = { ...base, recent: [], peak: null, overview: null, truncated: true }
|
|
74
|
+
if (Buffer.byteLength(JSON.stringify(minimal)) <= maxBytes) return { payload: minimal, truncated: true }
|
|
75
|
+
|
|
76
|
+
// 连合计都超限(maxBytes 配得极小):仍然写,但标明截断,别让"写失败"变成静默
|
|
77
|
+
return { payload: { ...minimal, totals: null }, truncated: true }
|
|
64
78
|
}
|
|
65
79
|
|
|
66
80
|
/**
|