dsh-token-trim 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,6 +52,12 @@ Read those two numbers carefully:
52
52
  measured by replaying 1,518 real tool results), minus rework. It is a replay estimate, not an invoice.
53
53
  - The Savings tab shows the same split: gross, suspected-rework deduction, net — so you can see when the
54
54
  plugin starts to hurt instead of help.
55
+ - **Measured replay (in the tab).** Reads the real session logs and charges each rewrite once at the miss
56
+ price and once per later request until the next compaction; the threshold side replays the measured
57
+ per-step deltas under the current policy (`0.4 / 0.12`) and the shipped default (`0.8 / 0.16`). On the
58
+ author's session this came out at **−30.6% compaction + −5.3% trimming ≈ −35.8% net**; the −41.3% figure
59
+ is the older corpus-level model kept as a comparison. Rewrites from before session ids existed are counted
60
+ but not priced, and the tab says so.
55
61
 
56
62
  ## Safety model
57
63
 
package/client/panel.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // dsh-token-trim 的会话视图(Web 客户端插件)。
2
2
  // 位置:对话上方的 View 标签行(conversation.view),与「对话 / 轨迹 / 统计」并列。
3
- // 数据经 ctx.connection.rpc 调宿主 tokenTrim 服务(方法无参数,筛选在客户端)。
3
+ // 数据:tokenTrim/status + /report + /bill + /replay(均无参数,筛选在客户端)。
4
4
  window.__ModuleLoader__.load({
5
5
  id: 'dsh-token-trim',
6
6
  factory(require) {
@@ -9,124 +9,115 @@ window.__ModuleLoader__.load({
9
9
 
10
10
  const EN = {
11
11
  label: 'Savings',
12
- title: 'Tool savings',
13
- subtitle: 'What token-trim removed before tool results entered the model context.',
14
- here: 'This session',
15
- all: 'All sessions',
16
- allTime: 'All time',
17
- days7: '7 days',
18
- days30: '30 days',
19
- refresh: 'Refresh',
20
- busy: 'Loading…',
21
- error: 'Error',
12
+ title: 'Savings',
13
+ subtitle: 'Measured from real session logs: compaction tuning + tool-result trimming, minus rework.',
14
+ liveTitle: 'Bill saved (measured, net)',
15
+ eq: 'net =',
16
+ compaction: 'compaction tuning',
17
+ rules: 'tool trimming',
18
+ rework: 'suspected rework',
19
+ sample: 'samples',
20
+ aligned: 'aligned',
21
+ legacy: 'legacy rows (no session id)',
22
+ policy: 'policy',
23
+ modelTitle: 'fixed model (historical)',
24
+ modelNote: 'Config-level replay from 2026-11-15: compaction −31% × rules −15% ≈ −41%. Kept for comparison; trust the measured number above.',
25
+ charsTitle: 'Trimming detail',
26
+ charsScope: 'this window',
22
27
  events: 'results rewritten',
23
28
  chars: 'characters',
24
- saved: 'saved',
29
+ savedChars: 'saved',
25
30
  tokens: 'est. tokens',
26
- denom: 'The percentage below is measured only over the tool results token-trim actually rewrote. Small results, the system prompt, and reasoning are outside the hook.',
27
- billNote: 'Bill-level estimate (offline replay, 2026-11-15): compaction tuning ≈ −31%, this rule layer ≈ −15%, multiplied ≈ −41%. Modelled, no rework cost.',
28
- billTitle: 'Bill saved (estimate)',
29
- netTitle: 'Bill saved (net estimate)',
30
- gross: 'gross',
31
- rework: 'rework',
32
- reworkTitle: 'Rework (suspected)',
33
- reworkSignal: 'repeats',
34
- reworkCost: 'cost (hit-equivalents)',
35
- reworkNote: 'Same rewritten result re-run within 30 minutes in one session, charged at the average step cost. This is the deduction applied to the headline.',
36
- reworkDuplicates: 'Bill-wide duplicate calls (not attributed):',
37
- billMeasured: 'Measured usage',
38
- billMeasuredNote: 'Read from the dsh-context-kit session-log cache: hit ×1, miss ×10, output ×15 (DeepSeek price ratio). This is the real usage side, not a projection.',
39
- billSessions: 'sessions',
40
- billSteps: 'steps',
41
- billCompactions: 'compactions',
42
- billHit: 'cache hit',
43
- billMiss: 'miss',
44
- billOut: 'output',
45
- billCost: 'cost (hit-equivalents)',
46
- billUnavailable: 'No measured bill yet — install dsh-context-kit so its session-log cache exists, then this card fills itself.',
47
- billUpdated: 'cache updated',
48
- pluginsTitle: 'This plugin, measured',
49
- tools: 'By tool',
50
- sessions: 'By session',
51
- recent: 'Recent transformations',
52
- count: 'n',
53
- cut: 'cut',
54
- last: 'last seen',
55
- legacy: 'Before session tracking',
56
- empty: 'Nothing rewritten yet in this session. token-trim only records results it actually changed.',
31
+ denom: 'The percentage is measured only over the results this plugin actually rewrote.',
32
+ usageTitle: 'Bill usage (measured)',
33
+ usageNote: 'From the dsh-context-kit session cache: hit ×1, miss ×10, output ×15.',
34
+ usageHit: 'cache hit',
35
+ usageMiss: 'miss',
36
+ usageOut: 'output',
37
+ usageCost: 'cost',
38
+ sessionsTitle: 'By session',
39
+ recentTitle: 'Recent rewrites',
40
+ refresh: 'Refresh',
41
+ busy: 'Loading…',
42
+ auto: 'Live',
43
+ paused: 'Paused',
44
+ updated: 'updated',
45
+ replayBtn: 'Run replay',
46
+ replayBusy: 'Replaying…',
47
+ runAll: 'All sessions',
48
+ runThis: 'This session',
49
+ empty: 'Nothing rewritten yet. token-guard only records results it actually changed.',
57
50
  none: 'No manifest yet — the plugin is idle, or dryRun never wrote anything.',
58
- dry: 'dryRun is ON: nothing is being rewritten, so these numbers are hypothetical.',
59
- where: 'Originals',
51
+ dry: 'dryRun is ON: nothing is being rewritten.',
52
+ error: 'Error',
60
53
  tool: 'tool',
61
- mode: 'mode',
54
+ count: 'n',
55
+ last: 'last',
62
56
  focus: 'Focus',
63
- allFocus: 'clear',
57
+ clear: 'clear',
64
58
  }
65
59
 
66
60
  const ZH = {
67
61
  label: '节省',
68
- title: '工具节省',
69
- subtitle: 'token-trim 在工具结果进入模型上下文之前,替我们砍掉了什么。',
70
- here: '本会话',
71
- all: '全部会话',
72
- allTime: '全部',
73
- days7: '7 天',
74
- days30: '30 天',
75
- refresh: '刷新',
76
- busy: '读取中…',
77
- error: '出错',
62
+ title: '账单节省',
63
+ subtitle: '来自真实会话日志:压缩阈值调优 + 工具结果治理,再扣掉返工。',
64
+ liveTitle: '账单净节省(实测)',
65
+ eq: '即',
66
+ compaction: '压缩阈值调优',
67
+ rules: '工具治理',
68
+ rework: '疑似返工',
69
+ sample: '样本',
70
+ aligned: '已对齐',
71
+ legacy: '条无会话 id(不计价)',
72
+ policy: '策略',
73
+ modelTitle: '固定模型(历史口径)',
74
+ modelNote: '2026-11-15 的语料级回放:压缩 −31% × 规则 −15% ≈ −41%。保留作对照,以上面的实测为准。',
75
+ charsTitle: '工具治理明细',
76
+ charsScope: '本窗口',
78
77
  events: '条结果被改写',
79
78
  chars: '字符',
80
- saved: '省下',
79
+ savedChars: '省下',
81
80
  tokens: '约合 token',
82
- denom: '下面的百分比,分母只是「token-trim 实际改写过的工具结果」。小结果、系统提示、推理都不在钩子里。',
83
- billNote: '账单级估算(离线回放,2026-11-15):压缩阈值调优约 −31%,本规则层约 −15%,相乘约 −41%。是模型,未扣返工。',
84
- billTitle: '账单节省(估算)',
85
- netTitle: '账单净节省(估算)',
86
- gross: '毛节省',
87
- rework: '返工扣减',
88
- reworkTitle: '返工(疑似)',
89
- reworkSignal: '次重跑',
90
- reworkCost: '成本(命中当量)',
91
- reworkNote: '同一会话里,同一条被改写的结果在 30 分钟内又被重跑,按平均步成本计费。这就是上面大字里扣掉的那部分。',
92
- reworkDuplicates: '全账单重复调用(未归因):',
93
- billMeasured: '实测用量',
94
- billMeasuredNote: '来自 dsh-context-kit 的会话日志缓存:命中 ×1、未命中 ×10、输出 ×15(DeepSeek 价格比)。这是真实用量侧,不是推算。',
95
- billSessions: '个会话',
96
- billSteps: '步',
97
- billCompactions: '次压缩',
98
- billHit: '缓存命中',
99
- billMiss: '未命中',
100
- billOut: '输出',
101
- billCost: '成本(命中当量)',
102
- billUnavailable: '还没有实测账单 —— 装上 dsh-context-kit 生成会话日志缓存后,这张卡会自动填上。',
103
- billUpdated: '缓存更新于',
104
- pluginsTitle: '本插件实测',
105
- tools: '按工具',
106
- sessions: '按会话',
107
- recent: '最近变换',
108
- count: '次数',
109
- cut: '削减',
110
- last: '最近',
111
- legacy: '会话统计上线前',
112
- empty: '本会话还没有被改写的工具结果。token-trim 只记录真正改过的结果。',
81
+ denom: '百分比的分母只是本插件实际改写过的工具结果。',
82
+ usageTitle: '账单用量(实测)',
83
+ usageNote: '来自 dsh-context-kit 的会话日志缓存:命中 ×1、未命中 ×10、输出 ×15。',
84
+ usageHit: '缓存命中',
85
+ usageMiss: '未命中',
86
+ usageOut: '输出',
87
+ usageCost: '成本',
88
+ sessionsTitle: '按会话',
89
+ recentTitle: '最近改写',
90
+ refresh: '刷新',
91
+ busy: '读取中…',
92
+ auto: '实时',
93
+ paused: '已暂停',
94
+ updated: '更新于',
95
+ replayBtn: '实测回放',
96
+ replayBusy: '回放中…',
97
+ runAll: '全部会话',
98
+ runThis: '本会话',
99
+ empty: '还没有被改写的工具结果。token-trim 只记录真正改过的结果。',
113
100
  none: '还没有 manifest —— 插件空闲,或 dryRun 从未写过盘。',
114
- dry: 'dryRun 已开启:内容没有被改写,这些数字只是“如果真改会怎样”。',
115
- where: '原文位置',
101
+ dry: 'dryRun 已开启:内容没有被改写。',
102
+ error: '出错',
116
103
  tool: '工具',
117
- mode: '模式',
104
+ count: '次数',
105
+ last: '最近',
118
106
  focus: '聚焦',
119
- allFocus: '取消',
107
+ clear: '取消',
120
108
  }
121
109
 
122
110
  const CSS = [
123
- '.tg_view { display: flex; flex-direction: column; gap: 14px; padding: 18px 22px 40px; max-width: 960px; box-sizing: border-box; }',
111
+ '.tg_view { display: flex; flex-direction: column; gap: 12px; padding: 18px 22px 40px; max-width: 920px; box-sizing: border-box; }',
124
112
  '.tg_head h2 { margin: 0 0 4px; font-size: 16px; }',
125
113
  '.tg_head p { margin: 0; opacity: .7; font-size: 12px; }',
126
114
  '.tg_row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }',
127
- '.tg_card { border: 1px solid rgba(127,127,127,.25); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }',
115
+ '.tg_card { border: 1px solid rgba(127,127,127,.25); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 8px; }',
116
+ '.tg_card.muted { opacity: .72; }',
128
117
  '.tg_cardhead { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }',
129
118
  '.tg_cardhead strong { font-size: 13px; }',
119
+ '.tg_hero { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }',
120
+ '.tg_hero .tg_big { font-size: 30px; }',
130
121
  '.tg_seg { display: inline-flex; border: 1px solid rgba(127,127,127,.35); border-radius: 8px; overflow: hidden; }',
131
122
  '.tg_seg button { border: 0; background: transparent; color: inherit; padding: 4px 10px; font-size: 12px; cursor: pointer; }',
132
123
  '.tg_seg button.on { background: rgba(37,99,235,.18); font-weight: 600; }',
@@ -134,28 +125,28 @@ window.__ModuleLoader__.load({
134
125
  '.tg_btn:disabled { opacity: .5; cursor: default; }',
135
126
  '.tg_big { font-size: 24px; font-weight: 600; font-variant-numeric: tabular-nums; }',
136
127
  '.tg_meta { font-size: 11px; opacity: .65; }',
137
- '.tg_note { font-size: 11px; opacity: .6; line-height: 1.5; }',
128
+ '.tg_note { font-size: 11px; opacity: .55; line-height: 1.5; }',
138
129
  '.tg_warn { font-size: 12px; color: #d97706; }',
139
130
  '.tg_err { font-size: 12px; color: #dc2626; }',
140
131
  '.tg_table { width: 100%; border-collapse: collapse; font-size: 12px; }',
141
- '.tg_table th, .tg_table td { text-align: left; padding: 4px 6px; border-bottom: 1px solid rgba(127,127,127,.18); font-variant-numeric: tabular-nums; }',
142
- '.tg_table th { font-weight: 600; opacity: .75; }',
132
+ '.tg_table th, .tg_table td { text-align: left; padding: 3px 6px; border-bottom: 1px solid rgba(127,127,127,.16); font-variant-numeric: tabular-nums; }',
133
+ '.tg_table th { font-weight: 600; opacity: .7; }',
143
134
  '.tg_table td.num, .tg_table th.num { text-align: right; }',
144
135
  '.tg_table tr.clickable { cursor: pointer; }',
145
136
  '.tg_table tr.clickable:hover td { background: rgba(127,127,127,.08); }',
146
137
  '.tg_table tr.on td { background: rgba(37,99,235,.12); }',
147
- '.tg_ev { display: flex; gap: 8px; align-items: baseline; font-size: 12px; padding: 3px 0; border-bottom: 1px solid rgba(127,127,127,.12); }',
148
- '.tg_ev .t { min-width: 74px; opacity: .65; font-variant-numeric: tabular-nums; }',
149
- '.tg_ev .tg_target { opacity: .8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1 1 140px; }',
138
+ '.tg_ev { display: flex; gap: 8px; align-items: baseline; font-size: 12px; padding: 2px 0; border-bottom: 1px solid rgba(127,127,127,.1); }',
139
+ '.tg_ev .t { min-width: 72px; opacity: .6; font-variant-numeric: tabular-nums; }',
140
+ '.tg_ev .tg_target { opacity: .8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1 1 120px; }',
150
141
  '.tg_chip { font-size: 10px; padding: 1px 6px; border-radius: 999px; background: rgba(127,127,127,.18); }',
151
142
  '.tg_chip.warn { background: rgba(217,119,6,.18); }',
152
143
  ].join('\n')
153
144
 
154
145
  const fmtBig = (value) => {
155
146
  if (!Number.isFinite(value)) return '—'
156
- if (value >= 1e9) return (value / 1e9).toFixed(2) + 'B'
157
- if (value >= 1e6) return (value / 1e6).toFixed(1) + 'M'
158
- if (value >= 1e3) return Math.round(value / 1e3) + 'K'
147
+ if (Math.abs(value) >= 1e9) return (value / 1e9).toFixed(2) + 'B'
148
+ if (Math.abs(value) >= 1e6) return (value / 1e6).toFixed(1) + 'M'
149
+ if (Math.abs(value) >= 1e3) return Math.round(value / 1e3) + 'K'
159
150
  return String(Math.round(value))
160
151
  }
161
152
  const pct = (value) => (Number.isFinite(value) ? value.toFixed(1) + '%' : '—')
@@ -167,7 +158,6 @@ window.__ModuleLoader__.load({
167
158
  }
168
159
  const shortId = (id) => {
169
160
  const s = String(id || '')
170
- if (s === 'legacy') return s
171
161
  return s.length > 10 ? s.slice(0, 8) : s
172
162
  }
173
163
  const meta = (value) => h('div', { className: 'tg_meta' }, value)
@@ -213,7 +203,7 @@ window.__ModuleLoader__.load({
213
203
  function call(method, args) {
214
204
  return ctx.connection.rpc.call('/api', 'tokenTrim/' + method, { args: args || {} }, undefined).then(function (response) {
215
205
  if (response && response.ok) return response.value
216
- const message = response && response.error ? response.error.message : 'token guard remote call failed'
206
+ const message = response && response.error ? response.error.message : 'token trim remote call failed'
217
207
  const error = new Error(message)
218
208
  error.code = response && response.error ? response.error.code : 'REMOTE_FAILED'
219
209
  throw error
@@ -223,6 +213,7 @@ window.__ModuleLoader__.load({
223
213
  report: () => call('report', {}),
224
214
  status: () => call('status', {}),
225
215
  bill: () => call('bill', {}),
216
+ replay: () => call('replay', {}),
226
217
  }
227
218
  }
228
219
 
@@ -282,22 +273,70 @@ window.__ModuleLoader__.load({
282
273
  const sessionId = props.sessionId || ''
283
274
  const [data, setData] = React.useState(null)
284
275
  const [bill, setBill] = React.useState(null)
276
+ const [replay, setReplay] = React.useState(null)
285
277
  const [days, setDays] = React.useState(0)
286
278
  const [focus, setFocus] = React.useState('')
287
279
  const [busy, setBusy] = React.useState(false)
280
+ const [replayBusy, setReplayBusy] = React.useState(false)
288
281
  const [error, setError] = React.useState('')
289
282
  const [status, setStatus] = React.useState(null)
283
+ const [auto, setAuto] = React.useState(true)
284
+ const [updatedAt, setUpdatedAt] = React.useState(0)
285
+ const lastRecords = React.useRef(-1)
290
286
 
291
- const load = React.useCallback(function (force) {
292
- setBusy(true)
293
- setError('')
294
- return Promise.all([loadReport(api, force), api.status().catch(function () { return null }), api.bill().catch(function () { return null })])
295
- .then(function (results) { setData(results[0]); if (results[1]) setStatus(results[1]); if (results[2]) setBill(results[2]) })
287
+ const load = React.useCallback(function (force, silent) {
288
+ if (!silent) setBusy(true)
289
+ return Promise.all([
290
+ loadReport(api, force),
291
+ api.status().catch(function () { return null }),
292
+ api.bill().catch(function () { return null }),
293
+ ])
294
+ .then(function (results) {
295
+ setData(results[0])
296
+ if (results[1]) setStatus(results[1])
297
+ if (results[2]) setBill(results[2])
298
+ setUpdatedAt(Date.now())
299
+ })
296
300
  .catch(function (cause) { setError(String(cause && cause.message ? cause.message : cause)) })
297
- .then(function () { setBusy(false) })
301
+ .then(function () { if (!silent) setBusy(false) })
298
302
  }, [api])
299
303
 
300
- React.useEffect(function () { load(false) }, [load])
304
+ const runReplay = React.useCallback(function (silent) {
305
+ if (!silent) setReplayBusy(true)
306
+ return api.replay()
307
+ .then(function (value) { setReplay(value) })
308
+ .catch(function (cause) { setError(String(cause && cause.message ? cause.message : cause)) })
309
+ .then(function () { setReplayBusy(false) })
310
+ }, [api])
311
+
312
+ React.useEffect(function () { load(false, false) }, [load])
313
+
314
+ // 实时:视图可见时每 5 秒静默重读;切回页面立即补一次。
315
+ React.useEffect(function () {
316
+ if (!auto) return undefined
317
+ const tick = function () {
318
+ if (typeof document !== 'undefined' && document.hidden) return
319
+ load(true, true).catch(function () {})
320
+ }
321
+ const timer = setInterval(tick, 5000)
322
+ const onVisible = function () {
323
+ if (typeof document !== 'undefined' && !document.hidden) load(true, true).catch(function () {})
324
+ }
325
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)
326
+ return function () {
327
+ clearInterval(timer)
328
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisible)
329
+ }
330
+ }, [auto, load])
331
+
332
+ // 每次出现新的改写(manifest 行数变化)就自动跑一次实测回放;解析结果有缓存。
333
+ React.useEffect(function () {
334
+ if (!data) return
335
+ const records = data.records || 0
336
+ if (records === lastRecords.current) return
337
+ lastRecords.current = records
338
+ if (auto || !replay) runReplay(true)
339
+ }, [data, auto, replay, runReplay])
301
340
 
302
341
  const model = data ? viewModel(data, focus, days) : null
303
342
  const rows = []
@@ -307,113 +346,107 @@ window.__ModuleLoader__.load({
307
346
  if (data && !data.available) rows.push(meta(t('none')))
308
347
 
309
348
  if (model) {
310
- const scope = focus ? shortId(focus) : t('all')
311
- const totalPct = bill && Number.isFinite(bill.totalPct) ? bill.totalPct : 41.4
312
- const compactionPct = bill && Number.isFinite(bill.compactionPct) ? bill.compactionPct : 31
313
- const rulesPct = bill && Number.isFinite(bill.rulesPct) ? bill.rulesPct : 15
314
-
315
- // 1) 账单净节省(毛节省 − 疑似返工)
316
- const netPct = bill && Number.isFinite(bill.netPct) ? bill.netPct : totalPct
349
+ const rt = replay && replay.totals ? replay.totals : null
350
+ const netModel = bill && Number.isFinite(bill.netPct) ? bill.netPct : 41.3
317
351
  const reworkPct = bill && bill.rework && Number.isFinite(bill.rework.pctOfBaseline) ? bill.rework.pctOfBaseline : 0
352
+ const netMeasured = rt ? rt.totalPct - reworkPct : 0
353
+
354
+ // 1) 实测净节省(压缩阈值 + 工具治理 − 疑似返工),放首位
318
355
  rows.push(h('div', { className: 'tg_card' },
356
+ h('div', { className: 'tg_hero' },
357
+ h('span', { className: 'tg_big' }, rt ? '−' + pct(netMeasured) : '—'),
358
+ h('span', { className: 'tg_meta' }, t('liveTitle'))),
319
359
  h('div', { className: 'tg_row' },
320
- h('span', { className: 'tg_big' }, '−' + netPct.toFixed(1) + '%'),
321
- h('span', { className: 'tg_meta' }, t('netTitle'))),
360
+ meta(rt ? t('compaction') + ' +' + pct(rt.compactionPct) : t('compaction') + ' …'),
361
+ meta(rt ? t('rules') + ' +' + pct(rt.rulePct) : t('rules') + ' …'),
362
+ meta(t('rework') + ' −' + reworkPct.toFixed(2) + '%')),
322
363
  h('div', { className: 'tg_row' },
323
- meta(t('gross') + ' −' + totalPct.toFixed(1) + '%'),
324
- meta(t('rework') + ' −' + reworkPct.toFixed(2) + '%'),
325
- meta('压缩阈值 −' + compactionPct + '% × 规则层 −' + rulesPct + '%')),
326
- h('div', { className: 'tg_note' }, t('billNote'))))
364
+ meta(rt ? t('eq') + ' +' + pct(rt.totalPct) + ' − ' + reworkPct.toFixed(2) + '%' : ''),
365
+ rt ? meta(t('sample') + ' ' + rt.sessions + ' · ' + t('aligned') + ' ' + rt.aligned + '/' + rt.events) : null,
366
+ rt && rt.legacy ? meta(rt.legacy + ' ' + t('legacy')) : null,
367
+ replay.policy ? meta(t('policy') + ' ' + replay.policy.thresholdRatio + ' / ' + replay.policy.retainRatio) : null),
368
+ h('div', { className: 'tg_note' },
369
+ rt
370
+ ? '反事实回放:压缩按当前策略 vs 出厂 0.8/0.16;工具治理按每条改写结果的实际存活步数计费。'
371
+ : '点「实测回放」按真实会话日志计算。'),
372
+ replayBusy ? h('div', { className: 'tg_note' }, t('replayBusy')) : null))
327
373
 
328
- // 2) 实测用量(来自会话日志缓存)
329
- if (bill && bill.available && bill.totals) {
330
- const bt = bill.totals
331
- rows.push(h('div', { className: 'tg_card' },
332
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('billMeasured'))),
333
- h('div', { className: 'tg_row' },
334
- meta(bt.sessions + ' ' + t('billSessions') + ' · ' + bt.steps + ' ' + t('billSteps') + ' · ' + bt.compactions + ' ' + t('billCompactions')),
335
- meta(t('billCost') + ' ' + fmtBig(bt.cost))),
336
- h('div', { className: 'tg_row' },
337
- meta(t('billHit') + ' ' + fmtBig(bt.hit)),
338
- meta(t('billMiss') + ' ' + fmtBig(bt.miss)),
339
- meta(t('billOut') + ' ' + fmtBig(bt.out))),
340
- h('div', { className: 'tg_note' }, t('billMeasuredNote')),
341
- bill.updatedAt ? meta(t('billUpdated') + ' ' + timeOf(bill.updatedAt)) : null))
342
- } else {
343
- rows.push(h('div', { className: 'tg_card' },
344
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('billMeasured'))),
345
- meta(t('billUnavailable'))))
346
- }
347
-
348
- // 3) 返工(疑似),计入上方扣减
349
- if (bill && bill.rework) {
350
- const rw = bill.rework
351
- rows.push(h('div', { className: 'tg_card' },
352
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('reworkTitle'))),
353
- h('div', { className: 'tg_row' },
354
- meta(rw.suspected + ' ' + t('reworkSignal') + ' · ' + rw.windowMinutes + ' min'),
355
- meta(t('reworkCost') + ' ' + fmtBig(rw.costEquiv)),
356
- meta('−' + Number(rw.pctOfBaseline || 0).toFixed(2) + '%')),
357
- h('div', { className: 'tg_note' }, t('reworkNote')),
358
- bill.totals ? meta(t('reworkDuplicates') + ' ' + fmtBig(bill.totals.duplicates) + ' / ' + fmtBig(bill.totals.distinctCalls)) : null))
359
- }
374
+ // 2) 固定模型(次要,明确标注)
375
+ rows.push(h('div', { className: 'tg_card muted' },
376
+ h('div', { className: 'tg_cardhead' },
377
+ h('strong', null, t('modelTitle')),
378
+ meta('−' + netModel.toFixed(1) + '%')),
379
+ h('div', { className: 'tg_note' }, t('modelNote'))))
360
380
 
361
- // 4) 本插件实测(字符口径)
381
+ // 3) 工具治理明细(字符口径)
362
382
  rows.push(h('div', { className: 'tg_card' },
363
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('pluginsTitle'))),
383
+ h('div', { className: 'tg_cardhead' },
384
+ h('strong', null, t('charsTitle')),
385
+ meta(t('charsScope') + ' · ' + model.totals.events + ' ' + t('events'))),
364
386
  h('div', { className: 'tg_row' },
365
387
  h('span', { className: 'tg_big' }, '−' + pct(model.totals.cutPct)),
366
- h('span', { className: 'tg_meta' }, scope + ' · ' + model.totals.events + ' ' + t('events')),
367
- h('span', { className: 'tg_meta' }, fmtBig(model.totals.orig) + ' → ' + fmtBig(model.totals.vis) + ' ' + t('chars'))),
368
- h('div', { className: 'tg_row' },
369
- meta(t('saved') + ' ' + fmtBig(model.totals.saved) + ' ' + t('chars')),
370
- meta(t('tokens') + ' ~' + fmtBig(model.totals.tokens))),
371
- h('div', { className: 'tg_note' }, t('denom'))))
372
-
373
- rows.push(h('div', { className: 'tg_card' },
374
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('tools'))),
388
+ meta(fmtBig(model.totals.orig) + ' → ' + fmtBig(model.totals.vis) + ' ' + t('chars')),
389
+ meta(t('savedChars') + ' ' + fmtBig(model.totals.saved) + ' ≈ ' + fmtBig(model.totals.tokens) + ' tok')),
375
390
  h('table', { className: 'tg_table' },
376
391
  h('thead', null, h('tr', null,
377
392
  h('th', null, t('tool')),
378
393
  h('th', { className: 'num' }, t('count')),
379
- h('th', { className: 'num' }, t('saved')))),
380
- h('tbody', null, model.tools.slice(0, 8).map((tool) =>
394
+ h('th', { className: 'num' }, t('savedChars')))),
395
+ h('tbody', null, model.tools.slice(0, 6).map((tool) =>
381
396
  h('tr', { key: tool.name },
382
397
  h('td', null, tool.name),
383
398
  h('td', { className: 'num' }, tool.events),
384
- h('td', { className: 'num' }, fmtBig(tool.saved))))))))
399
+ h('td', { className: 'num' }, fmtBig(tool.saved)))))),
400
+ h('div', { className: 'tg_note' }, t('denom'))))
401
+
402
+ // 4) 账单用量
403
+ if (bill && bill.available && bill.totals) {
404
+ const bt = bill.totals
405
+ rows.push(h('div', { className: 'tg_card' },
406
+ h('div', { className: 'tg_cardhead' },
407
+ h('strong', null, t('usageTitle')),
408
+ meta(bt.sessions + ' ' + t('sample') + ' · ' + fmtBig(bt.steps) + ' steps')),
409
+ h('div', { className: 'tg_row' },
410
+ meta(t('usageHit') + ' ' + fmtBig(bt.hit)),
411
+ meta(t('usageMiss') + ' ' + fmtBig(bt.miss)),
412
+ meta(t('usageOut') + ' ' + fmtBig(bt.out)),
413
+ meta(t('usageCost') + ' ' + fmtBig(bt.cost))),
414
+ h('div', { className: 'tg_note' }, t('usageNote')),
415
+ bill.updatedAt ? meta(t('updated') + ' ' + timeOf(bill.updatedAt)) : null))
416
+ }
385
417
 
418
+ // 5) 按会话
386
419
  rows.push(h('div', { className: 'tg_card' },
387
420
  h('div', { className: 'tg_cardhead' },
388
- h('strong', null, t('sessions')),
389
- focus ? h('button', { className: 'tg_btn', type: 'button', onClick: function () { setFocus('') } }, t('allFocus')) : null,
390
- !focus && sessionId ? h('button', { className: 'tg_btn', type: 'button', onClick: function () { setFocus(sessionId) } }, t('here')) : null),
421
+ h('strong', null, t('sessionsTitle')),
422
+ focus ? h('button', { className: 'tg_btn', type: 'button', onClick: function () { setFocus('') } }, t('clear')) : null,
423
+ !focus && sessionId ? h('button', { className: 'tg_btn', type: 'button', onClick: function () { setFocus(sessionId) } }, t('runThis')) : null),
391
424
  h('table', { className: 'tg_table' },
392
425
  h('thead', null, h('tr', null,
393
426
  h('th', null, ''),
394
427
  h('th', { className: 'num' }, t('count')),
395
- h('th', { className: 'num' }, t('saved')),
428
+ h('th', { className: 'num' }, t('savedChars')),
396
429
  h('th', null, t('last')))),
397
- h('tbody', null, model.sessions.slice(0, 12).map((row) =>
430
+ h('tbody', null, model.sessions.slice(0, 10).map((row) =>
398
431
  h('tr', {
399
432
  key: row.id,
400
433
  className: 'clickable' + (model.selected && model.selected.id === row.id ? ' on' : ''),
401
434
  onClick: function () { setFocus(model.selected && model.selected.id === row.id ? '' : row.id) },
402
435
  },
403
- h('td', null, row.id === 'legacy' ? t('legacy') : shortId(row.id)),
436
+ h('td', null, row.id === 'legacy' ? 'legacy' : shortId(row.id)),
404
437
  h('td', { className: 'num' }, row.events),
405
438
  h('td', { className: 'num' }, fmtBig(row.saved)),
406
439
  h('td', { className: 'tg_meta' }, timeOf(row.last))))))))
407
440
 
441
+ // 6) 最近改写
408
442
  rows.push(h('div', { className: 'tg_card' },
409
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('recent'))),
410
- ...model.events.slice(0, 15).map(function (row, index) {
443
+ h('div', { className: 'tg_cardhead' }, h('strong', null, t('recentTitle'))),
444
+ ...model.events.slice(0, 10).map(function (row, index) {
411
445
  return h('div', { className: 'tg_ev', key: index },
412
446
  h('span', { className: 't' }, timeOf(row.ts).slice(5)),
413
447
  h('span', { className: 'tg_chip' }, row.tool + ' · ' + row.mode),
414
448
  h('span', { className: 'tg_meta' }, fmtBig(row.orig) + '→' + fmtBig(row.vis)),
415
449
  h('span', { className: 'tg_target' }, row.target || ''),
416
- row.artifact ? h('span', { className: 'tg_meta' }, row.artifact) : null,
417
450
  row.dryRun ? h('span', { className: 'tg_chip warn' }, 'dry') : null)
418
451
  })))
419
452
 
@@ -421,9 +454,7 @@ window.__ModuleLoader__.load({
421
454
  const where = []
422
455
  if (status.artifactDir) where.push(meta(status.artifactDir))
423
456
  if (status.manifest) where.push(meta(status.manifest))
424
- if (where.length) rows.push(h('div', { className: 'tg_card' },
425
- h('div', { className: 'tg_cardhead' }, h('strong', null, t('where'))),
426
- ...where))
457
+ if (where.length) rows.push(h('div', { className: 'tg_card muted' }, ...where))
427
458
  }
428
459
  }
429
460
 
@@ -433,8 +464,13 @@ window.__ModuleLoader__.load({
433
464
  h('p', null, t('subtitle'))),
434
465
  h('div', { className: 'tg_row' },
435
466
  h(Seg, { t: t, value: days, onChange: setDays }),
436
- h('button', { className: 'tg_btn', type: 'button', disabled: busy, onClick: function () { return load(true) } },
437
- busy ? t('busy') : t('refresh'))),
467
+ h('button', { className: 'tg_btn', type: 'button', disabled: busy, onClick: function () { return load(true, false) } },
468
+ busy ? t('busy') : t('refresh')),
469
+ h('button', { className: 'tg_btn', type: 'button', disabled: replayBusy, onClick: function () { return runReplay(false) } },
470
+ replayBusy ? t('replayBusy') : t('replayBtn')),
471
+ h('button', { className: 'tg_btn', type: 'button', onClick: function () { setAuto(function (value) { return !value }) } },
472
+ auto ? t('auto') : t('paused')),
473
+ updatedAt ? h('span', { className: 'tg_meta' }, t('updated') + ' ' + new Date(updatedAt).toLocaleTimeString()) : null),
438
474
  ...rows)
439
475
  }
440
476
 
@@ -452,7 +488,6 @@ window.__ModuleLoader__.load({
452
488
  const t = makeT(ctx)
453
489
  const api = makeApi(ctx)
454
490
 
455
- // View 标签行:与「对话 / 轨迹 / 统计」并列
456
491
  ctx.slots.inject('conversation.view', function () {
457
492
  return ctx.slots.register({
458
493
  name: 'conversation.view',
package/lib/remote.mjs CHANGED
@@ -7,6 +7,9 @@
7
7
  */
8
8
  import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
9
9
  import { createRequire } from 'node:module'
10
+ import { homedir } from 'node:os'
11
+ import path from 'node:path'
12
+ import { replayAll } from './replay.mjs'
10
13
 
11
14
  const require = createRequire(import.meta.url)
12
15
  const { buildReport, buildBill } = require('./report.cjs')
@@ -65,6 +68,17 @@ export class TokenTrimRemoteService extends TypertRemoteService {
65
68
  bill() {
66
69
  return buildBill({ cache: this.usageCache, manifest: this.manifest })
67
70
  }
71
+
72
+ /**
73
+ * 反事实回放(A 方案,按需触发):读真实会话日志,逐 step 计算"没有本次改写时"的账单。
74
+ * 只对齐有 session id 的改写;legacy 行只计数。耗时与日志量相关(本机约 2s/400 步)。
75
+ */
76
+ async replay() {
77
+ return replayAll({
78
+ manifest: this.manifest,
79
+ sessionsRoot: path.join(homedir(), '.dsh', 'sessions'),
80
+ })
81
+ }
68
82
  }
69
83
 
70
- for (const method of ['status', 'report', 'bill']) markRemoteMethod(TokenTrimRemoteService, method)
84
+ for (const method of ['status', 'report', 'bill', 'replay']) markRemoteMethod(TokenTrimRemoteService, method)