@lingda-ai/dsh-plugin-ledger 0.1.9 → 0.1.11

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 CHANGED
@@ -242,6 +242,16 @@ token 只是 `measures` 里的一种单位。计划中的第二个来源(Trae
242
242
 
243
243
  ---
244
244
 
245
+ ### 8.0 面板默认开启(0.1.11 起)
246
+
247
+ `panel.enabled` 的默认值从 `false` 改成 `true`。这不是"顺手改个默认值",而是一次真机教训:
248
+ 默认关时,用户装完插件、打开右栏,看到的是"没有快照"——功能存在却像坏了,而修复它需要
249
+ 用户自己去改 profile 的 YAML。代价(工作区多一个 ≤256KB 的只读 JSON、原子写、会话结束删除、
250
+ 不含对话内容)远小于收益(装上就能看见数)。
251
+
252
+ 写盘目录与浏览器读路径必须一致(`<session cwd>/.dsh/ledger`)。自定义 `panel.dir` 时
253
+ Host 会显式告警"面板读不到",而不是让用户对着空面板猜。
254
+
245
255
  ### 8.1 文案口径(改面板前必读)
246
256
 
247
257
  面板的所有文案都对应过一次真实误读,别再改回去:
@@ -256,6 +266,10 @@ token 只是 `measures` 里的一种单位。计划中的第二个来源(Trae
256
266
  | `工具结果 1,208 字符` | 光秃秃的 `↑1,208` 没人知道箭头指什么 |
257
267
  | `本次 180,000 tok` | 没有主语的 `180,000 tok` 会被当成累计上下文 |
258
268
  | `共 5 个有金额来源` | 过滤掉零金额来源后必须说明,否则像渲染 bug |
269
+ | `修复账本面板崩溃`(标题) | `sessio…affe8` 对用户没有区别度,他记的是对话不是 UUID |
270
+ | `约 4.8 分` | `¥0.0479` 是机器精度;1 元以下才补这一句,1 元以上别啰嗦 |
271
+ | `· 3 分钟前` | 成本是持续读数,新鲜度本身就是信息;绝对时间要用户自己做减法 |
272
+ | `¥0.5 ≈ 93 次调用` | 只给 `limit: 0.5` 是抽象建议,用户不知道 0.5 元是多少次 |
259
273
 
260
274
  ## 9. 验证手段
261
275
 
package/lib/client.js CHANGED
@@ -343,6 +343,52 @@ window.__ModuleLoader__.load({
343
343
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
344
344
  }
345
345
 
346
+ /**
347
+ * 相对时间:让"这个数有多旧"一眼可见。
348
+ *
349
+ * 绝对时间(22:32:42)需要用户自己做减法才知道是不是刚更新过;
350
+ * 成本是持续读数,新鲜度本身就是信息。
351
+ * @param {number|string|null|undefined} at 时间戳或 ISO 串
352
+ * @param {number} [now]
353
+ */
354
+ function formatRelative(at, now = Date.now()) {
355
+ const t = typeof at === 'string' ? Date.parse(at) : at
356
+ if (typeof t !== 'number' || !Number.isFinite(t)) return ''
357
+ const diff = Math.max(0, now - t)
358
+ if (diff < 10_000) return '刚刚'
359
+ if (diff < 60_000) return `${Math.round(diff / 1000)} 秒前`
360
+ if (diff < 3_600_000) return `${Math.round(diff / 60_000)} 分钟前`
361
+ if (diff < 86_400_000) return `${Math.round(diff / 3_600_000)} 小时前`
362
+ return `${Math.round(diff / 86_400_000)} 天前`
363
+ }
364
+
365
+ /**
366
+ * 小额人民币的"人话"换算:0.0113 → 1.1 分。
367
+ *
368
+ * ¥0.0113 这种 4 位小数对人类太细了("到底是几分钱?"),
369
+ * 只在 1 元以下时才补一句,1 元以上没有必要。
370
+ */
371
+ function formatCents(amount, currency) {
372
+ if (currency !== 'CNY') return null
373
+ if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) return null
374
+ if (amount >= 1) return null
375
+ const cents = amount * 100
376
+ return cents < 1 ? '不足 1 分' : `约 ${cents.toFixed(1)} 分`
377
+ }
378
+
379
+ /**
380
+ * 面板头部的会话标识:标题优先,没有标题就退回短 id。
381
+ *
382
+ * "sessio…affe8" 对用户没有意义——他记的是"哪段对话",不是会话 UUID。
383
+ * @param {any} view
384
+ * @param {string|null} sessionId
385
+ */
386
+ function headerLabelOf(view, sessionId) {
387
+ const title = view?.sessionTitle
388
+ if (typeof title === 'string' && title.length > 0) return title
389
+ return `会话 ${shortId(sessionId)}`
390
+ }
391
+
346
392
  /** 占比:0.362 → 36.2%。 */
347
393
  function formatShare(share) {
348
394
  return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
@@ -375,6 +421,26 @@ window.__ModuleLoader__.load({
375
421
  /** 挂载时刻:用来判断"这次读取是不是慢得反常" */
376
422
  const mountedAt = React.useRef(Date.now())
377
423
 
424
+ // 复制摘要:用户真实动作是把它贴进周报/工单,截图不能复制数字
425
+ const [copyState, setCopyState] = React.useState('idle') // idle | ok | fail
426
+ const copySummary = React.useCallback(() => {
427
+ if (view === undefined || view === null || typeof view.error === 'string') return
428
+ const done = (ok) => {
429
+ setCopyState(ok ? 'ok' : 'fail')
430
+ setTimeout(() => setCopyState('idle'), 1500)
431
+ }
432
+ try {
433
+ const clip = typeof navigator === 'undefined' ? null : navigator.clipboard
434
+ if (clip !== null && typeof clip.writeText === 'function') {
435
+ clip.writeText(summaryTextOf(view)).then(() => done(true), () => done(false))
436
+ return
437
+ }
438
+ done(false)
439
+ } catch {
440
+ done(false)
441
+ }
442
+ }, [view])
443
+
378
444
  const refresh = React.useCallback(async () => {
379
445
  if (sessionId === null) return
380
446
  if (inFlight.current) return
@@ -421,7 +487,35 @@ window.__ModuleLoader__.load({
421
487
  },
422
488
  },
423
489
  h('span', { style: { fontSize: 13, fontWeight: 600, color: INK } }, '账本'),
424
- h('span', { style: { fontSize: 11, color: INK3 } }, `会话 ${shortId(sessionId)}`),
490
+ // 标题优先:用户认得"修复面板崩溃",不认得 "sessio…affe8"
491
+ h(
492
+ 'span',
493
+ {
494
+ style: { fontSize: 11, color: INK3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 180 },
495
+ title: typeof sessionId === 'string' ? sessionId : undefined,
496
+ },
497
+ headerLabelOf(view, sessionId),
498
+ ),
499
+ h(
500
+ 'button',
501
+ {
502
+ type: 'button',
503
+ onClick: copySummary,
504
+ disabled: view === undefined || view === null || typeof view?.error === 'string',
505
+ title: '把本次会话的成本摘要复制为文本(可以直接贴进周报)',
506
+ style: {
507
+ marginLeft: 'auto',
508
+ border: '1px solid #d8dee7',
509
+ background: '#fff',
510
+ borderRadius: 7,
511
+ padding: '3px 9px',
512
+ fontSize: 11.5,
513
+ color: copyState === 'fail' ? '#a03a2a' : copyState === 'ok' ? GOOD : INK2,
514
+ cursor: 'pointer',
515
+ },
516
+ },
517
+ copyState === 'ok' ? '已复制' : copyState === 'fail' ? '复制失败' : '复制摘要',
518
+ ),
425
519
  h(
426
520
  'button',
427
521
  {
@@ -429,7 +523,6 @@ window.__ModuleLoader__.load({
429
523
  onClick: () => void refresh(),
430
524
  disabled: busy || sessionId === null,
431
525
  style: {
432
- marginLeft: 'auto',
433
526
  border: '1px solid #d8dee7',
434
527
  background: '#fff',
435
528
  borderRadius: 7,
@@ -503,6 +596,50 @@ window.__ModuleLoader__.load({
503
596
  }
504
597
  }
505
598
 
599
+ /**
600
+ * 一屏能看懂的纯文本摘要,供"复制"按钮使用。
601
+ *
602
+ * 用户真实的动作是:把这次会话花了多少钱贴进周报/工单/群里。
603
+ * 让人截图是下策(别人没法复制数字),给一段结构化文本才是正解。
604
+ * @param {any} view - 快照 payload
605
+ * @returns {string}
606
+ */
607
+ function summaryTextOf(view) {
608
+ const t = view?.totals ?? {}
609
+ const cost = t.cost ?? {}
610
+ const lines = []
611
+ lines.push(`账本 · ${typeof view?.sessionId === 'string' ? view.sessionId : '(未知会话)'}`)
612
+ const amount = typeof cost.amount === 'number' ? formatAmount(cost.amount, cost.currency) : '未计价'
613
+ const cents = typeof cost.amount === 'number' ? formatCents(cost.amount, cost.currency) : null
614
+ lines.push(`累计 ${amount}${cents === null ? '' : `(${cents})`} · ${t.entries ?? 0} 次调用`)
615
+ if (cost.unknownEntries > 0) lines.push(`其中 ${cost.unknownEntries} 条费率未知,合计偏低`)
616
+ const saved = t.saved?.amount
617
+ if (typeof saved === 'number' && saved > 0) {
618
+ lines.push(
619
+ `缓存已省 ${formatAmount(saved, t.saved.currency)}${
620
+ typeof t.savedShare === 'number' ? `(少花 ${formatShare(t.savedShare)})` : ''
621
+ }`,
622
+ )
623
+ }
624
+ if (cost.parts !== null && cost.parts !== undefined) {
625
+ lines.push(
626
+ `四档:未命中 ${formatAmount(cost.parts.input, cost.currency)} / 命中 ${formatAmount(cost.parts.cacheRead, cost.currency)}`
627
+ + ` / 写 ${formatAmount(cost.parts.cacheWrite, cost.currency)} / 输出 ${formatAmount(cost.parts.output, cost.currency)}`,
628
+ )
629
+ }
630
+ const peak = view?.peak
631
+ if (peak !== null && peak !== undefined && typeof peak.amount === 'number') {
632
+ const share = typeof cost.amount === 'number' && cost.amount > 0 ? ` · 占 ${formatShare(peak.amount / cost.amount)}` : ''
633
+ lines.push(
634
+ `最贵一步 ${typeof peak.turn === 'number' ? `T${peak.turn}·S${peak.step ?? '—'} ` : ''}`
635
+ + `${formatAmount(peak.amount, cost.currency)}${share}`,
636
+ )
637
+ }
638
+ const note = pricingNoteOf(view?.pricing)
639
+ lines.push(`快照 ${formatLocalTime(view?.generatedAt)} · ${note.text}`)
640
+ return lines.join('\n')
641
+ }
642
+
506
643
  /**
507
644
  * 副标题:调用次数 + 未归因次数。
508
645
  *
@@ -523,6 +660,24 @@ window.__ModuleLoader__.load({
523
660
  return `${entries} 次调用 · ${lost} 次未归因`
524
661
  }
525
662
 
663
+ /**
664
+ * 没配预算时的一句话:示例配置 + 按本次均价换算的"大概能问几次"。
665
+ *
666
+ * 只给 `limit: 0.5` 这种抽象建议没有意义——用户不知道 0.5 元是多少次调用。
667
+ * 用本次会话的均价换算,就是一个他能自己判断的锚。
668
+ * @param {object} totals
669
+ */
670
+ function buildBudgetHint(totals) {
671
+ const spent = totals?.cost?.amount
672
+ const entries = totals?.entries
673
+ const base = '未设预算 · 加 budget: { limit: 0.5 } 可显示"还能问几次"'
674
+ if (typeof spent !== 'number' || typeof entries !== 'number' || entries <= 0 || spent <= 0) return base
675
+ const perCall = spent / entries
676
+ const calls = Math.floor(0.5 / perCall)
677
+ if (!Number.isFinite(calls) || calls <= 0) return base
678
+ return `${base}(¥0.5 ≈ ${calls} 次调用)`
679
+ }
680
+
526
681
  /** "还能问几次":Host 已按均价算好,这里只加一句人话,面板不做除法以外的推断 */
527
682
  function callsLeftOf(budget) {
528
683
  const left = budget?.callsLeft
@@ -574,7 +729,14 @@ window.__ModuleLoader__.load({
574
729
  h(
575
730
  'div',
576
731
  { style: { padding: '14px 14px 6px' } },
577
- h('div', { style: { fontSize: 16, fontWeight: 600, color: INK } }, '本会话还没有模型调用'),
732
+ h(
733
+ 'div',
734
+ { style: { fontSize: 16, fontWeight: 600, color: INK } },
735
+ view?.sessionTitle ? String(view.sessionTitle) : '本会话还没有模型调用',
736
+ ),
737
+ view?.sessionTitle
738
+ ? h('div', { style: { fontSize: 11, color: INK3, marginTop: 4 } }, '这个会话还没有模型调用,发一条消息就开始记账。')
739
+ : null,
578
740
  h(
579
741
  'div',
580
742
  { style: { fontSize: 11.5, lineHeight: 1.7, color: INK2, marginTop: 6 } },
@@ -655,6 +817,10 @@ window.__ModuleLoader__.load({
655
817
  formatAmount(cost.amount, cost.currency),
656
818
  ),
657
819
  h('span', { style: { fontSize: 11, color: INK3 } }, summaryOf(totals, list)),
820
+ // 4 位小数对人类太细:"到底是几分钱?"——小额时补一句人话
821
+ formatCents(cost.amount, cost.currency) === null
822
+ ? null
823
+ : h('span', { style: { fontSize: 11, color: INK3 } }, formatCents(cost.amount, cost.currency)),
658
824
  ),
659
825
  // 合计偏低必须说:有未知费率的条目时,这个数字就是下限,不能摆得像确定值
660
826
  unknownCount > 0
@@ -686,8 +852,9 @@ window.__ModuleLoader__.load({
686
852
  ? h(
687
853
  'div',
688
854
  { style: { padding: '0 14px 8px', fontSize: 11, color: INK3 } },
689
- // 静默消失会被读成"这个面板没有这个功能";说清是配置项,用户才知道怎么开
690
- '未设预算 · 配 budget.limit 后这里显示"还能问几次"',
855
+ // 静默消失会被读成"这个面板没有这个功能"。给一句能直接抄的配置 +
856
+ // 按本次均价换算的次数,用户才知道"填多少算合理"。
857
+ buildBudgetHint(totals),
691
858
  )
692
859
  : h(
693
860
  'div',
@@ -906,7 +1073,14 @@ window.__ModuleLoader__.load({
906
1073
  key: `o-${index}`,
907
1074
  style: { display: 'flex', justifyContent: 'space-between', gap: 8, padding: '3px 0', fontSize: 11.5 },
908
1075
  },
909
- h('span', { style: { color: INK2 } }, shortId(row.sessionId)),
1076
+ h(
1077
+ 'span',
1078
+ { style: { color: INK2 } },
1079
+ typeof row.title === 'string' && row.title.length > 0 ? row.title : shortId(row.sessionId),
1080
+ row.lastAt === undefined || row.lastAt === null
1081
+ ? null
1082
+ : h('span', { style: { fontSize: 11, color: INK3, marginLeft: 6 } }, formatRelative(row.lastAt)),
1083
+ ),
910
1084
  h(
911
1085
  'span',
912
1086
  { style: { color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
@@ -916,15 +1090,23 @@ window.__ModuleLoader__.load({
916
1090
  ),
917
1091
  )
918
1092
  : null,
919
- // 页脚:快照时间 + 费率来源合成一行,省 20px 且不会出现"两个日期像两个时间戳"
920
- h(
921
- 'div',
922
- {
923
- // 费率无效时整行转警示色:这是"金额不可信"的信号,不能和普通脚注同色
924
- style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn ? WARN : INK3 },
925
- },
926
- `快照 ${formatLocalTime(view.generatedAt)} · ${note.text}`,
927
- ),
1093
+ // 页脚:快照时间 + 距今 + 费率来源合成一行。
1094
+ // "距今"是产品信息:成本是持续读数,12 秒前和 5 分钟前的可信度不同。
1095
+ (() => {
1096
+ const age = formatRelative(view.generatedAt)
1097
+ const stale = (() => {
1098
+ const t = typeof view.generatedAt === 'string' ? Date.parse(view.generatedAt) : view.generatedAt
1099
+ return typeof t === 'number' && Date.now() - t > 60_000
1100
+ })()
1101
+ return h(
1102
+ 'div',
1103
+ {
1104
+ // 费率无效 / 快照过期 都是"金额可信度"信号,整行转警示色,不与普通脚注同色
1105
+ style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn || stale ? WARN : INK3 },
1106
+ },
1107
+ `快照 ${formatLocalTime(view.generatedAt)}${age === '' ? '' : ` · ${age}`}${stale ? '(可能已过期)' : ''} · ${note.text}`,
1108
+ )
1109
+ })(),
928
1110
  )
929
1111
  }
930
1112
 
@@ -1112,7 +1294,7 @@ window.__ModuleLoader__.load({
1112
1294
  function createFetchView(ctx) {
1113
1295
  return async function fetchView(sessionId, opts = {}) {
1114
1296
  if (typeof sessionId !== 'string' || sessionId.length === 0) return null
1115
- const files = optionalService(ctx, 'remote')?.workspaceFiles
1297
+ const files = workspaceFilesOf(ctx)
1116
1298
  if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
1117
1299
  return { error: '宿主未提供 workspaceFiles 通道' }
1118
1300
  }
@@ -1168,6 +1350,43 @@ window.__ModuleLoader__.load({
1168
1350
  }
1169
1351
  }
1170
1352
 
1353
+ /**
1354
+ * 取 workspaceFiles remote。
1355
+ *
1356
+ * 真机报错:`cannot get property "remote.workspaceFiles" without inject`。
1357
+ * 原因:remote 是按 `remote.<name>` 为 key 注册的服务,`ctx.remote.workspaceFiles`
1358
+ * 这种点号访问最终会落到 ctx 代理上做 inject 校验——没声明就抛,而它在 apply 之后、
1359
+ * 面板读取时才第一次触发(所以表现为"面板读取失败",不是启动失败)。
1360
+ *
1361
+ * 正确姿势是用 `ctx.get('remote.workspaceFiles')` 这条**不受 inject 约束**的通道
1362
+ * (cordis 自己在服务目录里就把 ctx.get 标成 optional access)。
1363
+ * 逐级兜底,任何一层抛错都当作"没有这条通道"。
1364
+ * @param {any} ctx
1365
+ * @returns {any|null}
1366
+ */
1367
+ function workspaceFilesOf(ctx) {
1368
+ if (typeof ctx?.get === 'function') {
1369
+ try {
1370
+ const direct = ctx.get('remote.workspaceFiles')
1371
+ if (direct) return direct
1372
+ } catch {
1373
+ // 某些版本只注册了命名空间,继续往下试
1374
+ }
1375
+ try {
1376
+ const namespace = ctx.get('remote')
1377
+ const files = namespace?.workspaceFiles
1378
+ if (files) return files
1379
+ } catch {
1380
+ // 命名空间访问同样可能被代理拦,忽略
1381
+ }
1382
+ }
1383
+ try {
1384
+ return ctx?.remote?.workspaceFiles ?? null
1385
+ } catch {
1386
+ return null
1387
+ }
1388
+ }
1389
+
1171
1390
  /** 把任意抛出物变成一句话。 */
1172
1391
  function stringifyError(error) {
1173
1392
  if (error instanceof Error) return error.message
package/lib/client.src.js CHANGED
@@ -142,7 +142,7 @@ import {
142
142
  export function createFetchView(ctx) {
143
143
  return async function fetchView(sessionId, opts = {}) {
144
144
  if (typeof sessionId !== 'string' || sessionId.length === 0) return null
145
- const files = optionalService(ctx, 'remote')?.workspaceFiles
145
+ const files = workspaceFilesOf(ctx)
146
146
  if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
147
147
  return { error: '宿主未提供 workspaceFiles 通道' }
148
148
  }
@@ -198,6 +198,43 @@ export function createFetchView(ctx) {
198
198
  }
199
199
  }
200
200
 
201
+ /**
202
+ * 取 workspaceFiles remote。
203
+ *
204
+ * 真机报错:`cannot get property "remote.workspaceFiles" without inject`。
205
+ * 原因:remote 是按 `remote.<name>` 为 key 注册的服务,`ctx.remote.workspaceFiles`
206
+ * 这种点号访问最终会落到 ctx 代理上做 inject 校验——没声明就抛,而它在 apply 之后、
207
+ * 面板读取时才第一次触发(所以表现为"面板读取失败",不是启动失败)。
208
+ *
209
+ * 正确姿势是用 `ctx.get('remote.workspaceFiles')` 这条**不受 inject 约束**的通道
210
+ * (cordis 自己在服务目录里就把 ctx.get 标成 optional access)。
211
+ * 逐级兜底,任何一层抛错都当作"没有这条通道"。
212
+ * @param {any} ctx
213
+ * @returns {any|null}
214
+ */
215
+ function workspaceFilesOf(ctx) {
216
+ if (typeof ctx?.get === 'function') {
217
+ try {
218
+ const direct = ctx.get('remote.workspaceFiles')
219
+ if (direct) return direct
220
+ } catch {
221
+ // 某些版本只注册了命名空间,继续往下试
222
+ }
223
+ try {
224
+ const namespace = ctx.get('remote')
225
+ const files = namespace?.workspaceFiles
226
+ if (files) return files
227
+ } catch {
228
+ // 命名空间访问同样可能被代理拦,忽略
229
+ }
230
+ }
231
+ try {
232
+ return ctx?.remote?.workspaceFiles ?? null
233
+ } catch {
234
+ return null
235
+ }
236
+ }
237
+
201
238
  /** 把任意抛出物变成一句话。 */
202
239
  function stringifyError(error) {
203
240
  if (error instanceof Error) return error.message
package/lib/config.js CHANGED
@@ -41,9 +41,14 @@ export const DEFAULT_CONFIG = Object.freeze({
41
41
  toolOwners: {}, // 工具名 → 所属插件(唯一可得的归因依据,见 docs/spikes.md)
42
42
  },
43
43
  // 右侧栏面板的数据通道:Host 把只读快照落成 JSON,浏览器半用 workspace 文件 remote 读回。
44
- // 默认关闭——写盘是外部副作用,不该由观测默认产生。
44
+ //
45
+ // 默认**开启**(0.1.11 起)。早先默认关闭的理由是"写盘是外部副作用",但真机验证下来,
46
+ // 默认关闭的实际后果是:用户装完插件、打开右栏面板,看到的是"没有快照"——
47
+ // 功能存在却像坏了,而修复它需要用户自己去改 profile 的 YAML。
48
+ // 代价是每个会话在工作区多一个 ≤256KB 的 .dsh/ledger/<session>.json(原子写、会话结束删除、
49
+ // 不含任何对话内容)。不想留文件就显式关:panel.enabled: false。
45
50
  panel: {
46
- enabled: false,
51
+ enabled: true,
47
52
  dir: '.dsh/ledger', // 相对 process.cwd();也可给绝对路径
48
53
  intervalMs: 3000, // 同一会话两次落盘的最小间隔
49
54
  maxBytes: 262144, // 超过则只写 totals + topSources
package/lib/index.js CHANGED
@@ -145,9 +145,15 @@ export function apply(ctx, rawConfig) {
145
145
  sources: (sessionId, opts) => store.sources(sessionId, opts),
146
146
  // 面板必须知道"这些金额是拿哪套价算的",否则数字不可信
147
147
  pricing: pricingMeta,
148
+ // 标题:让面板能说"这笔钱是哪段对话花的"
149
+ titleOf: (sessionId) => titles.get(sessionId) ?? null,
148
150
  })
149
151
  : null
150
152
 
153
+ // 会话标题:右栏只显示 "sessio…affe8" 时用户没法把它和对话对上。
154
+ // 标题通过 session/event 的 session/title 事件到达(数据在 data 里,与其它事件一致)。
155
+ const titles = new Map()
156
+
151
157
  // 身份线索(actor/project/deviceId):解析只发生在会话第一条事件上,热路径零成本。
152
158
  // 读的是 .git/config 与 ~/.gitconfig 两个小文件,**不起 git 子进程**。
153
159
  const identity = createIdentity()
@@ -167,6 +173,10 @@ export function apply(ctx, rawConfig) {
167
173
  if (typeof sid === 'string' && !sessionRoots.has(sid) && typeof session?.header?.cwd === 'string') {
168
174
  sessionRoots.set(sid, session.header.cwd)
169
175
  }
176
+ if (event?.type === 'session/title' && typeof sid === 'string') {
177
+ const payload = event?.data ?? event
178
+ if (typeof payload?.title === 'string' && payload.title.length > 0) titles.set(sid, payload.title)
179
+ }
170
180
  ledger.onSessionEvent(session, event)
171
181
  // 节流落盘在 publisher 内部完成:热路径只多一次 Map 读 + 比较
172
182
  if (publisher !== null) publisher.schedule(session?.id)
@@ -190,6 +200,7 @@ export function apply(ctx, rawConfig) {
190
200
  ledger.forget(id)
191
201
  traceSink?.remove(id)
192
202
  sessionRoots.delete(id)
203
+ titles.delete(id)
193
204
  store.drop(id)
194
205
  })
195
206
 
package/lib/panel-view.js CHANGED
@@ -260,6 +260,52 @@ function formatClock(at) {
260
260
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
261
261
  }
262
262
 
263
+ /**
264
+ * 相对时间:让"这个数有多旧"一眼可见。
265
+ *
266
+ * 绝对时间(22:32:42)需要用户自己做减法才知道是不是刚更新过;
267
+ * 成本是持续读数,新鲜度本身就是信息。
268
+ * @param {number|string|null|undefined} at 时间戳或 ISO 串
269
+ * @param {number} [now]
270
+ */
271
+ export function formatRelative(at, now = Date.now()) {
272
+ const t = typeof at === 'string' ? Date.parse(at) : at
273
+ if (typeof t !== 'number' || !Number.isFinite(t)) return ''
274
+ const diff = Math.max(0, now - t)
275
+ if (diff < 10_000) return '刚刚'
276
+ if (diff < 60_000) return `${Math.round(diff / 1000)} 秒前`
277
+ if (diff < 3_600_000) return `${Math.round(diff / 60_000)} 分钟前`
278
+ if (diff < 86_400_000) return `${Math.round(diff / 3_600_000)} 小时前`
279
+ return `${Math.round(diff / 86_400_000)} 天前`
280
+ }
281
+
282
+ /**
283
+ * 小额人民币的"人话"换算:0.0113 → 1.1 分。
284
+ *
285
+ * ¥0.0113 这种 4 位小数对人类太细了("到底是几分钱?"),
286
+ * 只在 1 元以下时才补一句,1 元以上没有必要。
287
+ */
288
+ export function formatCents(amount, currency) {
289
+ if (currency !== 'CNY') return null
290
+ if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) return null
291
+ if (amount >= 1) return null
292
+ const cents = amount * 100
293
+ return cents < 1 ? '不足 1 分' : `约 ${cents.toFixed(1)} 分`
294
+ }
295
+
296
+ /**
297
+ * 面板头部的会话标识:标题优先,没有标题就退回短 id。
298
+ *
299
+ * "sessio…affe8" 对用户没有意义——他记的是"哪段对话",不是会话 UUID。
300
+ * @param {any} view
301
+ * @param {string|null} sessionId
302
+ */
303
+ export function headerLabelOf(view, sessionId) {
304
+ const title = view?.sessionTitle
305
+ if (typeof title === 'string' && title.length > 0) return title
306
+ return `会话 ${shortId(sessionId)}`
307
+ }
308
+
263
309
  /** 占比:0.362 → 36.2%。 */
264
310
  function formatShare(share) {
265
311
  return typeof share === 'number' && Number.isFinite(share) ? `${(share * 100).toFixed(1)}%` : '—'
@@ -292,6 +338,26 @@ function makeLedgerBody(React, fetchView) {
292
338
  /** 挂载时刻:用来判断"这次读取是不是慢得反常" */
293
339
  const mountedAt = React.useRef(Date.now())
294
340
 
341
+ // 复制摘要:用户真实动作是把它贴进周报/工单,截图不能复制数字
342
+ const [copyState, setCopyState] = React.useState('idle') // idle | ok | fail
343
+ const copySummary = React.useCallback(() => {
344
+ if (view === undefined || view === null || typeof view.error === 'string') return
345
+ const done = (ok) => {
346
+ setCopyState(ok ? 'ok' : 'fail')
347
+ setTimeout(() => setCopyState('idle'), 1500)
348
+ }
349
+ try {
350
+ const clip = typeof navigator === 'undefined' ? null : navigator.clipboard
351
+ if (clip !== null && typeof clip.writeText === 'function') {
352
+ clip.writeText(summaryTextOf(view)).then(() => done(true), () => done(false))
353
+ return
354
+ }
355
+ done(false)
356
+ } catch {
357
+ done(false)
358
+ }
359
+ }, [view])
360
+
295
361
  const refresh = React.useCallback(async () => {
296
362
  if (sessionId === null) return
297
363
  if (inFlight.current) return
@@ -338,7 +404,35 @@ function makeLedgerBody(React, fetchView) {
338
404
  },
339
405
  },
340
406
  h('span', { style: { fontSize: 13, fontWeight: 600, color: INK } }, '账本'),
341
- h('span', { style: { fontSize: 11, color: INK3 } }, `会话 ${shortId(sessionId)}`),
407
+ // 标题优先:用户认得"修复面板崩溃",不认得 "sessio…affe8"
408
+ h(
409
+ 'span',
410
+ {
411
+ style: { fontSize: 11, color: INK3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 180 },
412
+ title: typeof sessionId === 'string' ? sessionId : undefined,
413
+ },
414
+ headerLabelOf(view, sessionId),
415
+ ),
416
+ h(
417
+ 'button',
418
+ {
419
+ type: 'button',
420
+ onClick: copySummary,
421
+ disabled: view === undefined || view === null || typeof view?.error === 'string',
422
+ title: '把本次会话的成本摘要复制为文本(可以直接贴进周报)',
423
+ style: {
424
+ marginLeft: 'auto',
425
+ border: '1px solid #d8dee7',
426
+ background: '#fff',
427
+ borderRadius: 7,
428
+ padding: '3px 9px',
429
+ fontSize: 11.5,
430
+ color: copyState === 'fail' ? '#a03a2a' : copyState === 'ok' ? GOOD : INK2,
431
+ cursor: 'pointer',
432
+ },
433
+ },
434
+ copyState === 'ok' ? '已复制' : copyState === 'fail' ? '复制失败' : '复制摘要',
435
+ ),
342
436
  h(
343
437
  'button',
344
438
  {
@@ -346,7 +440,6 @@ function makeLedgerBody(React, fetchView) {
346
440
  onClick: () => void refresh(),
347
441
  disabled: busy || sessionId === null,
348
442
  style: {
349
- marginLeft: 'auto',
350
443
  border: '1px solid #d8dee7',
351
444
  background: '#fff',
352
445
  borderRadius: 7,
@@ -420,6 +513,50 @@ function makeLedgerBody(React, fetchView) {
420
513
  }
421
514
  }
422
515
 
516
+ /**
517
+ * 一屏能看懂的纯文本摘要,供"复制"按钮使用。
518
+ *
519
+ * 用户真实的动作是:把这次会话花了多少钱贴进周报/工单/群里。
520
+ * 让人截图是下策(别人没法复制数字),给一段结构化文本才是正解。
521
+ * @param {any} view - 快照 payload
522
+ * @returns {string}
523
+ */
524
+ export function summaryTextOf(view) {
525
+ const t = view?.totals ?? {}
526
+ const cost = t.cost ?? {}
527
+ const lines = []
528
+ lines.push(`账本 · ${typeof view?.sessionId === 'string' ? view.sessionId : '(未知会话)'}`)
529
+ const amount = typeof cost.amount === 'number' ? formatAmount(cost.amount, cost.currency) : '未计价'
530
+ const cents = typeof cost.amount === 'number' ? formatCents(cost.amount, cost.currency) : null
531
+ lines.push(`累计 ${amount}${cents === null ? '' : `(${cents})`} · ${t.entries ?? 0} 次调用`)
532
+ if (cost.unknownEntries > 0) lines.push(`其中 ${cost.unknownEntries} 条费率未知,合计偏低`)
533
+ const saved = t.saved?.amount
534
+ if (typeof saved === 'number' && saved > 0) {
535
+ lines.push(
536
+ `缓存已省 ${formatAmount(saved, t.saved.currency)}${
537
+ typeof t.savedShare === 'number' ? `(少花 ${formatShare(t.savedShare)})` : ''
538
+ }`,
539
+ )
540
+ }
541
+ if (cost.parts !== null && cost.parts !== undefined) {
542
+ lines.push(
543
+ `四档:未命中 ${formatAmount(cost.parts.input, cost.currency)} / 命中 ${formatAmount(cost.parts.cacheRead, cost.currency)}`
544
+ + ` / 写 ${formatAmount(cost.parts.cacheWrite, cost.currency)} / 输出 ${formatAmount(cost.parts.output, cost.currency)}`,
545
+ )
546
+ }
547
+ const peak = view?.peak
548
+ if (peak !== null && peak !== undefined && typeof peak.amount === 'number') {
549
+ const share = typeof cost.amount === 'number' && cost.amount > 0 ? ` · 占 ${formatShare(peak.amount / cost.amount)}` : ''
550
+ lines.push(
551
+ `最贵一步 ${typeof peak.turn === 'number' ? `T${peak.turn}·S${peak.step ?? '—'} ` : ''}`
552
+ + `${formatAmount(peak.amount, cost.currency)}${share}`,
553
+ )
554
+ }
555
+ const note = pricingNoteOf(view?.pricing)
556
+ lines.push(`快照 ${formatLocalTime(view?.generatedAt)} · ${note.text}`)
557
+ return lines.join('\n')
558
+ }
559
+
423
560
  /**
424
561
  * 副标题:调用次数 + 未归因次数。
425
562
  *
@@ -440,6 +577,24 @@ function summaryOf(totals, list) {
440
577
  return `${entries} 次调用 · ${lost} 次未归因`
441
578
  }
442
579
 
580
+ /**
581
+ * 没配预算时的一句话:示例配置 + 按本次均价换算的"大概能问几次"。
582
+ *
583
+ * 只给 `limit: 0.5` 这种抽象建议没有意义——用户不知道 0.5 元是多少次调用。
584
+ * 用本次会话的均价换算,就是一个他能自己判断的锚。
585
+ * @param {object} totals
586
+ */
587
+ function buildBudgetHint(totals) {
588
+ const spent = totals?.cost?.amount
589
+ const entries = totals?.entries
590
+ const base = '未设预算 · 加 budget: { limit: 0.5 } 可显示"还能问几次"'
591
+ if (typeof spent !== 'number' || typeof entries !== 'number' || entries <= 0 || spent <= 0) return base
592
+ const perCall = spent / entries
593
+ const calls = Math.floor(0.5 / perCall)
594
+ if (!Number.isFinite(calls) || calls <= 0) return base
595
+ return `${base}(¥0.5 ≈ ${calls} 次调用)`
596
+ }
597
+
443
598
  /** "还能问几次":Host 已按均价算好,这里只加一句人话,面板不做除法以外的推断 */
444
599
  function callsLeftOf(budget) {
445
600
  const left = budget?.callsLeft
@@ -491,7 +646,14 @@ function renderEmptyState(React, view, sessionId, head, options = {}) {
491
646
  h(
492
647
  'div',
493
648
  { style: { padding: '14px 14px 6px' } },
494
- h('div', { style: { fontSize: 16, fontWeight: 600, color: INK } }, '本会话还没有模型调用'),
649
+ h(
650
+ 'div',
651
+ { style: { fontSize: 16, fontWeight: 600, color: INK } },
652
+ view?.sessionTitle ? String(view.sessionTitle) : '本会话还没有模型调用',
653
+ ),
654
+ view?.sessionTitle
655
+ ? h('div', { style: { fontSize: 11, color: INK3, marginTop: 4 } }, '这个会话还没有模型调用,发一条消息就开始记账。')
656
+ : null,
495
657
  h(
496
658
  'div',
497
659
  { style: { fontSize: 11.5, lineHeight: 1.7, color: INK2, marginTop: 6 } },
@@ -572,6 +734,10 @@ function renderPayload(React, view, sessionId, head, options = {}) {
572
734
  formatAmount(cost.amount, cost.currency),
573
735
  ),
574
736
  h('span', { style: { fontSize: 11, color: INK3 } }, summaryOf(totals, list)),
737
+ // 4 位小数对人类太细:"到底是几分钱?"——小额时补一句人话
738
+ formatCents(cost.amount, cost.currency) === null
739
+ ? null
740
+ : h('span', { style: { fontSize: 11, color: INK3 } }, formatCents(cost.amount, cost.currency)),
575
741
  ),
576
742
  // 合计偏低必须说:有未知费率的条目时,这个数字就是下限,不能摆得像确定值
577
743
  unknownCount > 0
@@ -603,8 +769,9 @@ function renderPayload(React, view, sessionId, head, options = {}) {
603
769
  ? h(
604
770
  'div',
605
771
  { style: { padding: '0 14px 8px', fontSize: 11, color: INK3 } },
606
- // 静默消失会被读成"这个面板没有这个功能";说清是配置项,用户才知道怎么开
607
- '未设预算 · 配 budget.limit 后这里显示"还能问几次"',
772
+ // 静默消失会被读成"这个面板没有这个功能"。给一句能直接抄的配置 +
773
+ // 按本次均价换算的次数,用户才知道"填多少算合理"。
774
+ buildBudgetHint(totals),
608
775
  )
609
776
  : h(
610
777
  'div',
@@ -823,7 +990,14 @@ function renderPayload(React, view, sessionId, head, options = {}) {
823
990
  key: `o-${index}`,
824
991
  style: { display: 'flex', justifyContent: 'space-between', gap: 8, padding: '3px 0', fontSize: 11.5 },
825
992
  },
826
- h('span', { style: { color: INK2 } }, shortId(row.sessionId)),
993
+ h(
994
+ 'span',
995
+ { style: { color: INK2 } },
996
+ typeof row.title === 'string' && row.title.length > 0 ? row.title : shortId(row.sessionId),
997
+ row.lastAt === undefined || row.lastAt === null
998
+ ? null
999
+ : h('span', { style: { fontSize: 11, color: INK3, marginLeft: 6 } }, formatRelative(row.lastAt)),
1000
+ ),
827
1001
  h(
828
1002
  'span',
829
1003
  { style: { color: INK, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
@@ -833,15 +1007,23 @@ function renderPayload(React, view, sessionId, head, options = {}) {
833
1007
  ),
834
1008
  )
835
1009
  : null,
836
- // 页脚:快照时间 + 费率来源合成一行,省 20px 且不会出现"两个日期像两个时间戳"
837
- h(
838
- 'div',
839
- {
840
- // 费率无效时整行转警示色:这是"金额不可信"的信号,不能和普通脚注同色
841
- style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn ? WARN : INK3 },
842
- },
843
- `快照 ${formatLocalTime(view.generatedAt)} · ${note.text}`,
844
- ),
1010
+ // 页脚:快照时间 + 距今 + 费率来源合成一行。
1011
+ // "距今"是产品信息:成本是持续读数,12 秒前和 5 分钟前的可信度不同。
1012
+ (() => {
1013
+ const age = formatRelative(view.generatedAt)
1014
+ const stale = (() => {
1015
+ const t = typeof view.generatedAt === 'string' ? Date.parse(view.generatedAt) : view.generatedAt
1016
+ return typeof t === 'number' && Date.now() - t > 60_000
1017
+ })()
1018
+ return h(
1019
+ 'div',
1020
+ {
1021
+ // 费率无效 / 快照过期 都是"金额可信度"信号,整行转警示色,不与普通脚注同色
1022
+ style: { padding: '6px 14px 12px', fontSize: 11, lineHeight: 1.65, color: note.warn || stale ? WARN : INK3 },
1023
+ },
1024
+ `快照 ${formatLocalTime(view.generatedAt)}${age === '' ? '' : ` · ${age}`}${stale ? '(可能已过期)' : ''} · ${note.text}`,
1025
+ )
1026
+ })(),
845
1027
  )
846
1028
  }
847
1029
 
@@ -38,11 +38,13 @@ function isoOf(at) {
38
38
  return null
39
39
  }
40
40
 
41
- export function buildPanelPayload(snapshot, sources, { maxBytes = 262144, budget = null, overview = null, pricing = null } = {}) {
41
+ export function buildPanelPayload(snapshot, sources, { maxBytes = 262144, budget = null, overview = null, pricing = null, title = null, titleOf = null } = {}) {
42
42
  const base = {
43
43
  version: SNAPSHOT_VERSION,
44
44
  generatedAt: isoOf(snapshot?.generatedAt),
45
45
  sessionId: snapshot?.sessionId ?? null,
46
+ // 会话标题:面板用它代替 "sessio…affe8",用户才认得出是哪段对话
47
+ sessionTitle: typeof title === 'string' && title.length > 0 ? title : null,
46
48
  // 面板口径的派生字段集中在这里算一次,避免浏览器半各算一套
47
49
  totals: withPanelTotals(snapshot?.totals ?? null),
48
50
  topSources: snapshot?.topSources ?? [],
@@ -51,7 +53,17 @@ export function buildPanelPayload(snapshot, sources, { maxBytes = 262144, budget
51
53
  // 最贵一步:只从"最近这段"里挑,面板会明说是"最近最贵",不冒充全程最贵
52
54
  peak: peakOf((snapshot?.recent ?? []).map(compactEntry)),
53
55
  // 跨会话对比:只给数字,不给别的内容(面板按 lastAt 排序取前几条)
54
- overview: Array.isArray(overview) ? overview.slice(0, 8).map(compactSession) : null,
56
+ overview: Array.isArray(overview)
57
+ ? overview.slice(0, 8).map((row) => {
58
+ const compact = compactSession(row)
59
+ // 其他会话也尽量给标题:一排 sessio…910 对用户没有区别度
60
+ if (compact !== null && typeof titleOf === 'function') {
61
+ const t = titleOf(row?.sessionId)
62
+ if (typeof t === 'string' && t.length > 0) compact.title = t
63
+ }
64
+ return compact
65
+ })
66
+ : null,
55
67
  // 预算只给面板读数用:limit 为 null 表示未启用,面板不画进度条
56
68
  budget: normalizeBudget(budget, snapshot?.totals),
57
69
  // 费率来源:面板必须能说出"这些钱是按哪套价算的"。
@@ -242,6 +254,8 @@ export function createSnapshotPublisher(options) {
242
254
  budget,
243
255
  overview: ov?.sessions ?? ov,
244
256
  pricing: options.pricing ?? null,
257
+ title: typeof options.titleOf === 'function' ? options.titleOf(sessionId) : null,
258
+ titleOf: options.titleOf,
245
259
  })
246
260
  // 多行写:浏览器侧 read 是按行取页的,单行超长 JSON 会被页宽截断
247
261
  const body = JSON.stringify(payload, null, 2)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingda-ai/dsh-plugin-ledger",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "DSH 插件搜索入口:运行时账本(成本/用量观测)。自包含单包,不依赖其他 npm 包,便于从镜像源安装。",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [