dsh-usage-bar 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/Versions/Alpha Release/A-v0.1.0.md +45 -0
  4. package/Versions/Alpha Release/A-v0.1.1.md +45 -0
  5. package/Versions/Alpha Release/A-v0.1.3.md +51 -0
  6. package/Versions/Alpha Release/A-v0.1.4.md +35 -0
  7. package/Versions/Alpha Release/A-v0.1.5.md +42 -0
  8. package/Versions/Alpha Release/A-v0.1.6.md +46 -0
  9. package/Versions/Alpha Release/A-v0.1.7.md +39 -0
  10. package/Versions/Alpha Release/A-v0.1.8.md +37 -0
  11. package/Versions/Beta Release/B-v0.2.0.md +50 -0
  12. package/Versions/Official Release/R-v0.1.0.md +38 -0
  13. package/Versions/README.md +49 -0
  14. package/Versions/_template.md +40 -0
  15. package/cordis.patch.yml +4 -0
  16. package/docs/DETAIL.md +250 -0
  17. package/docs/Development.md +98 -0
  18. package/docs/assets/backfill.png +0 -0
  19. package/docs/assets/handoff.png +0 -0
  20. package/docs/assets/hero.png +0 -0
  21. package/docs/assets/logo.svg +4 -0
  22. package/docs/assets/sidebar.png +0 -0
  23. package/docs/readme/README_zh.md +229 -0
  24. package/docs/releases/B-v0.2.0.md +86 -0
  25. package/docs/releases/_template.md +51 -0
  26. package/icon.svg +4 -0
  27. package/locale/en.json +7 -0
  28. package/locale/zh.json +7 -0
  29. package/package.json +60 -4
  30. package/src/client.js +1529 -0
  31. package/src/index.js +663 -0
  32. package/src/lib/bili-stats.js +69 -0
  33. package/src/lib/ledger-stats.js +162 -0
  34. package/src/lib/session-context.js +185 -0
  35. package/src/lib/usage-backfill.js +81 -0
  36. package/src/lib/usage-migration.js +19 -0
  37. package/src/lib/usage-store.js +232 -0
  38. package/tint.example.json +7 -0
package/src/client.js ADDED
@@ -0,0 +1,1529 @@
1
+ /**
2
+ * ContextMeter — 浏览器半边。
3
+ *
4
+ * 注册到会话头部标题行(conversation.session.header.actions),
5
+ * 排在「费用明细」之后、「x 个子智能体」之前,显示:
6
+ *
7
+ * 累计计费输入 Tokens [▓▓▓▓░░░░░░] 250M / 500M · 50.0%
8
+ *
9
+ * 数据来自 host 的同源路由 /context-meter/stats
10
+ * (host 合并 cost-meter 账本与 billion-context 的统计)。
11
+ *
12
+ * 上限与分档来自 tint.json(host 每 5 秒转发一次):
13
+ * window 计费上限,默认 500M;顶栏百分比、空态上限、预警点都用它
14
+ * warn 黄色起点,默认 60%
15
+ * danger 红色起点,默认 80%
16
+ * 0–40% 绿、40%–warn 白;warn–danger 用 warnColor、danger 以上用 dangerColor
17
+ * 轨道上的黄、红斜纹警示区跟随 warn / danger 阈值移动。
18
+ */
19
+ window.__ModuleLoader__.load({
20
+ id: 'dsh-usage-bar',
21
+ factory(require) {
22
+ const React = require('react')
23
+ const ReactDOM = require('react-dom')
24
+ const h = React.createElement
25
+
26
+ /** 配置拉不到时的兜底上限:500M(十进制,token 计数口径)。 */
27
+ const DEFAULT_WINDOW = 500 * 1000 * 1000
28
+ const POLL_MS = 4000
29
+ const ROUTE = '/context-meter/stats'
30
+ const HANDOFF_ROUTE = '/context-meter/handoff'
31
+ const BACKFILL_ROUTE = '/context-meter/backfill'
32
+ /** 交接请求轮询间隔。 */
33
+ const HANDOFF_POLL_MS = 1500
34
+
35
+ const CSS = `
36
+ .__cm-host{display:inline-flex;align-items:center;min-width:0}
37
+ .__cm-pill{display:inline-flex;align-items:center;gap:8px;max-width:100%;min-width:0;
38
+ padding:3px 10px;border-radius:999px;background:rgba(128,128,128,.08);
39
+ font-size:12px;line-height:16px;white-space:nowrap;cursor:default;
40
+ transition:background .15s ease}
41
+ .__cm-pill:hover{background:rgba(128,128,128,.16)}
42
+ .__cm-label{color:inherit;opacity:.72;flex:none}
43
+ .__cm-track{position:relative;flex:none;width:clamp(96px,16vw,180px);height:10px;border-radius:5px;
44
+ background:rgba(128,128,128,.30);overflow:hidden;
45
+ box-shadow:inset 0 0 0 1px rgba(128,128,128,.18)}
46
+ .__cm-zone{position:absolute;top:0;bottom:0;pointer-events:none}
47
+ .__cm-fill{position:absolute;top:0;bottom:0;left:0;border-radius:5px 0 0 5px;
48
+ transition:width .35s ease,background-color .35s ease}
49
+ .__cm-num{font-variant-numeric:tabular-nums;flex:none}
50
+ .__cm-sep{opacity:.55;flex:none}
51
+ .__cm-idle{opacity:.55}
52
+ .__cm-warn{display:inline-flex;align-items:center;gap:6px;margin-left:6px;padding:2px 8px;
53
+ border-radius:999px;background:rgba(230,167,0,.12);color:#e6a700;
54
+ font-size:12px;line-height:16px;white-space:nowrap;flex:none}
55
+ .__cm-warn-icon{display:block;flex:none}
56
+ .__cm-warn-text{flex:none}
57
+ .__cm-warn-btn{padding:0 6px;border:1px solid rgba(230,167,0,.45);border-radius:4px;
58
+ background:transparent;color:inherit;font:inherit;font-size:11px;line-height:16px;cursor:pointer}
59
+ .__cm-warn-btn:hover{background:rgba(230,167,0,.18)}
60
+ .__cm-progress{display:inline-flex;align-items:center;gap:4px}
61
+ .__cm-progress-track{width:56px;height:4px;border-radius:2px;background:rgba(230,167,0,.25);overflow:hidden}
62
+ .__cm-progress-fill{display:block;height:100%;background:#e6a700;transition:width .2s linear}
63
+ .__cm-progress-pct{font-variant-numeric:tabular-nums}
64
+ .__cm-banner .__cm-progress-track{width:180px}
65
+ .__cm-banner{position:fixed;left:50%;transform:translateX(-50%);z-index:900;
66
+ display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:8px;
67
+ max-width:calc(100vw - 32px);padding:7px 14px;border-radius:8px;
68
+ background:rgba(43,36,24,.96);border:1px solid rgba(230,167,0,.55);
69
+ color:#e6a700;font-size:13px;line-height:20px;white-space:nowrap;
70
+ box-shadow:0 6px 24px rgba(0,0,0,.35);pointer-events:auto}
71
+ .__cm-banner-text{opacity:.92;white-space:normal}
72
+ .__cm-banner-btn{padding:0 8px;border:1px solid rgba(230,167,0,.45);border-radius:4px;
73
+ background:transparent;color:inherit;font:inherit;font-size:11px;line-height:16px;cursor:pointer}
74
+ .__cm-banner-btn:hover{background:rgba(230,167,0,.18)}
75
+ .__cm-banner-busy{opacity:.7;cursor:default}
76
+ .__cm-off{display:inline-flex;align-items:center;justify-content:center;
77
+ width:20px;height:20px;padding:0;margin:0 2px 0 0;border:0;border-radius:4px;
78
+ background:transparent;color:inherit;opacity:.55;cursor:pointer;
79
+ line-height:0;font-family:inherit;
80
+ order:-1;flex:none}
81
+ .__cm-off svg{display:block;width:15px;height:15px}
82
+ .__cm-off:hover{opacity:1;background:rgba(128,128,128,.2)}
83
+ .__cm-off-on{opacity:.95;color:#c9a227}
84
+ .__cm-off-on:hover{opacity:1;color:#e0b62e}
85
+ @media (max-width:1100px){.__cm-label{display:none}.__cm-warn-text{display:none}.__cm-banner-text{display:none}}
86
+ `
87
+
88
+
89
+ /** apply 时的 ctx,供组件里的交接动作使用。 */
90
+ let runtimeCtx = null
91
+ // host 通过 /context-meter/stats 带回来的真实路径(避免在这里写死用户名)
92
+ const globalPaths = { globalAgents: '' }
93
+
94
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
95
+
96
+ /** 20261128-001234 */
97
+ function formatStamp(d) {
98
+ const pad = (n) => String(n).padStart(2, '0')
99
+ return (
100
+ String(d.getFullYear()) +
101
+ pad(d.getMonth() + 1) +
102
+ pad(d.getDate()) +
103
+ '-' +
104
+ pad(d.getHours()) +
105
+ pad(d.getMinutes()) +
106
+ pad(d.getSeconds())
107
+ )
108
+ }
109
+
110
+ /**
111
+ * 下一个标题:Create -> Create #2;Create #1 -> Create #2;Create #2 -> Create #3。
112
+ */
113
+ function nextTitle(title) {
114
+ const base = String(title || '').trim()
115
+ const m = /^(.*?)\s*#(\d+)$/.exec(base)
116
+ if (m) return m[1].trim() + ' #' + (Number(m[2]) + 1)
117
+ return (base || '对话') + ' #2'
118
+ }
119
+
120
+ /** 读会话标题:projection 优先,其次 summary 上的兼容字段。 */
121
+ function readTitle(ctx, sessionId) {
122
+ try {
123
+ const sessions = ctx.get('sessions')
124
+ const snap = sessions.list.getSnapshot()
125
+ const proj = snap.projectionsBySession && snap.projectionsBySession[sessionId]
126
+ if (proj) {
127
+ if (typeof proj.title === 'string') return proj.title
128
+ if (proj.title && typeof proj.title === 'object' && typeof proj.title.value === 'string') {
129
+ return proj.title.value
130
+ }
131
+ }
132
+ const row = snap.byId && snap.byId[sessionId]
133
+ if (row) {
134
+ if (typeof row.title === 'string') return row.title
135
+ if (typeof row.displayTitle === 'string') return row.displayTitle
136
+ }
137
+ } catch {
138
+ // 拿不到标题时退回空串
139
+ }
140
+ return ''
141
+ }
142
+
143
+ /** 借一个已 retain 的 binding;没有就临时 retain,用完 release。 */
144
+ async function withBinding(ctx, sessionId, fn) {
145
+ const sessions = ctx.get('sessions')
146
+ const direct = sessions.binding(sessionId)
147
+ if (direct && direct.session) return fn(direct)
148
+ let ref = null
149
+ try {
150
+ ref = sessions.retain(sessionId, { source: 'controllerOperation' })
151
+ const binding = ref && ref.ready ? await ref.ready : ref
152
+ return await fn(binding)
153
+ } finally {
154
+ if (ref && typeof ref.release === 'function') ref.release()
155
+ }
156
+ }
157
+
158
+ /** 等会话不再 running(最多 timeoutMs),用于等模型把交接文件写完。 */
159
+ async function waitIdle(ctx, sessionId, timeoutMs) {
160
+ const deadline = Date.now() + timeoutMs
161
+ await sleep(400)
162
+ while (Date.now() < deadline) {
163
+ try {
164
+ const binding = ctx.get('sessions').binding(sessionId)
165
+ if (binding && !binding.session.getSnapshot().running) return true
166
+ } catch {
167
+ return false
168
+ }
169
+ await sleep(600)
170
+ }
171
+ return false
172
+ }
173
+
174
+ /** 调 startSession 之后等列表里冒出新的会话 id。 */
175
+ async function waitNewSession(ctx, before, timeoutMs) {
176
+ const deadline = Date.now() + timeoutMs
177
+ while (Date.now() < deadline) {
178
+ await sleep(150)
179
+ try {
180
+ const ids = ctx.get('sessions').list.getSnapshot().ids || []
181
+ for (const id of ids) if (!before.has(id)) return id
182
+ } catch {
183
+ return ''
184
+ }
185
+ }
186
+ return ''
187
+ }
188
+
189
+ function buildWritePrompt(filePath) {
190
+ return [
191
+ '请把本次对话的工作交接内容写成一份 Markdown 文档,保存到这个绝对路径:',
192
+ filePath,
193
+ '',
194
+ '要求:',
195
+ '1. 正文用中文,Markdown 格式;第一行写成「# 工作交接:<本次对话的标题>」。',
196
+ '2. 至少包含:当前任务与目标、已完成的工作、修改过的文件(写完整绝对路径)、关键决策与原因、未完成事项与下一步、需要注意的约定或风险。',
197
+ '3. 只写确实发生在本次对话里的内容;不确定的标成「未确认」,不要编造。',
198
+ '4. 如果目标目录还不存在,请先创建。',
199
+ '5. 文件写完后,在你的回复最后单独一行输出:交接文件已生成:<完整路径>',
200
+ ].join('\n')
201
+ }
202
+
203
+ function buildBootstrapPrompt(filePath, cwd, globalAgents) {
204
+ const lines = [
205
+ '这是一个从上一个对话接续的新对话。请先读取下面这些文件,了解当前状态,再开始工作:',
206
+ '1. ' + (globalAgents || '~/.dsh/AGENTS.md'),
207
+ ]
208
+ if (cwd) {
209
+ lines.push('2. ' + cwd.replace(/[\\/]+$/, '') + '/AGENTS.md(若存在)')
210
+ lines.push('3. ' + cwd.replace(/[\\/]+$/, '') + '/README.md(若存在)')
211
+ lines.push('4. ' + cwd.replace(/[\\/]+$/, '') + '/MEMORY/MEMORY.md(若存在)')
212
+ }
213
+ lines.push('')
214
+ lines.push('交接文件(上一个对话的工作总结):')
215
+ lines.push(filePath)
216
+ lines.push('')
217
+ lines.push('读完后用两三句话概括你理解的当前状态和下一步,然后等我的指令。')
218
+ return lines.join('\n')
219
+ }
220
+
221
+ /**
222
+ * 执行一次交接请求。
223
+ * kind === 'file' 只让模型写交接文件;
224
+ * kind === 'full' 写完之后新建「原名 #N」对话,并在新对话草稿里预填读取清单。
225
+ */
226
+ async function runHandoff(ctx, sessionId, kind) {
227
+ const sessions = ctx.get('sessions')
228
+ const ui = ctx.get('uiWorkspace')
229
+ const title = readTitle(ctx, sessionId)
230
+ let cwd = ''
231
+ try {
232
+ const row = sessions.list.getSnapshot().byId[sessionId]
233
+ cwd = (row && row.cwd) || ''
234
+ } catch {
235
+ cwd = ''
236
+ }
237
+
238
+ const dir = (cwd ? cwd.replace(/[\\/]+$/, '') + '/' : '') + 'Handoff'
239
+ const filePath = dir + '/handoff-' + formatStamp(new Date()) + '.md'
240
+
241
+ await withBinding(ctx, sessionId, async (binding) => {
242
+ await binding.session.prompt([{ type: 'text', text: buildWritePrompt(filePath) }], 'queue')
243
+ })
244
+
245
+ if (kind !== 'full') return
246
+
247
+ await waitIdle(ctx, sessionId, 300000)
248
+
249
+ const before = new Set(sessions.list.getSnapshot().ids || [])
250
+ ui.startSession(undefined, {
251
+ prompt: buildBootstrapPrompt(filePath, cwd, globalPaths.globalAgents),
252
+ whenDraftExists: 'replace',
253
+ })
254
+
255
+ const newId = await waitNewSession(ctx, before, 10000)
256
+ if (!newId) return
257
+
258
+ const wanted = nextTitle(title)
259
+ try {
260
+ await withBinding(ctx, newId, async (binding) => {
261
+ await binding.session.rename(wanted)
262
+ })
263
+ } catch {
264
+ // 改名失败不影响交接本身
265
+ }
266
+ }
267
+
268
+ function format(n) {
269
+ if (!Number.isFinite(n) || n < 0) return '--'
270
+ const m = n / 1e6
271
+ if (m >= 100) return String(Math.round(m)) + 'M'
272
+ if (m >= 10) return (Math.round(m * 10) / 10).toFixed(1).replace(/\.0$/, '') + 'M'
273
+ if (m >= 1) return m.toFixed(1) + 'M'
274
+ if (n >= 1e3) return Math.round(n / 1e3) + 'K'
275
+ return String(Math.round(n))
276
+ }
277
+
278
+ /** 进度条本体与数字共用的颜色:阈值与颜色都来自 tint.json。 */
279
+ function bodyColor(pct) {
280
+ const warn = Number(tintConfig.warn)
281
+ const danger = Number(tintConfig.danger)
282
+ const d = Number.isFinite(danger) ? danger : 80
283
+ const w = Number.isFinite(warn) ? warn : 60
284
+ if (pct >= d) return tintConfig.dangerColor
285
+ if (pct >= w) return tintConfig.warnColor
286
+ if (pct >= 40) return '#ffffff'
287
+ return '#3fb950'
288
+ }
289
+
290
+ /** 把 #rrggbb 转成带透明度的 rgba,给轨道上的斜纹警示区用。 */
291
+ function isHexColor(value) {
292
+ return typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value)
293
+ }
294
+
295
+ function hexToRgba(hex, alpha) {
296
+ const m = /^#([0-9a-f]{6})$/i.exec(String(hex || ''))
297
+ if (!m) return 'rgba(128,128,128,' + alpha + ')'
298
+ const n = parseInt(m[1], 16)
299
+ return 'rgba(' + ((n >> 16) & 255) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + alpha + ')'
300
+ }
301
+
302
+ function clampPct(value, fallback) {
303
+ const n = Number(value)
304
+ if (!Number.isFinite(n)) return fallback
305
+ return Math.max(0, Math.min(100, n))
306
+ }
307
+
308
+ /** 轨道上的一段斜纹警示区:left/right 是百分比位置。 */
309
+ function zoneStyle(left, right, color) {
310
+ return {
311
+ left: left + '%',
312
+ width: Math.max(0, right - left) + '%',
313
+ backgroundImage:
314
+ 'repeating-linear-gradient(45deg,' + hexToRgba(color, 0.55) + ' 0 3px,transparent 3px 7px)',
315
+ }
316
+ }
317
+
318
+ // 绿色档(0–GREEN_ZONE_END)的未覆盖段显示绿色斜纹,和黄色/红色警示区一致。
319
+ // 颜色与 bodyColor 的 <40% 绿保持一致,不单独进 tint.json。
320
+ const GREEN_ZONE_END = 40
321
+ const GREEN_COLOR = '#3fb950'
322
+
323
+ const SOURCE_LABEL = {
324
+ 'cost-meter-ledger': 'cost-meter 账本',
325
+ 'billion-context': 'billion-context 实时统计',
326
+ }
327
+
328
+ const WARN_TEXT = 'dsh-usage-bar'
329
+ const BACKFILL_LABEL = '统计历史Tokens'
330
+
331
+ function progressText(ratio) {
332
+ const pct = Math.max(0, Math.min(100, Math.round((Number(ratio) || 0) * 100)))
333
+ return pct + '%'
334
+ }
335
+
336
+ /**
337
+ * 对话区上方悬浮警告条的 top:以 View tab 行底部为基准再加 10px。
338
+ * 量不到 tab 行(新会话页等)时回退 48px,避免掉到屏幕外。
339
+ */
340
+ function bannerTop(tablistBottom) {
341
+ const bottom = Number(tablistBottom)
342
+ return Math.max(48, Math.round((Number.isFinite(bottom) ? bottom : 0) + 10))
343
+ }
344
+
345
+ function errorText(err) {
346
+ if (err && err.message) return String(err.message)
347
+ return String(err || '回填失败')
348
+ }
349
+
350
+ /** 黄色三角感叹号,不依赖图标库。 */
351
+ function WarnIcon() {
352
+ return h(
353
+ 'svg',
354
+ {
355
+ className: '__cm-warn-icon',
356
+ viewBox: '0 0 16 16',
357
+ width: 14,
358
+ height: 14,
359
+ 'aria-hidden': 'true',
360
+ },
361
+ h('path', { d: 'M8 1.6 15 14H1L8 1.6Z', fill: '#e6a700' }),
362
+ h('path', { d: 'M8 5.6v3.8', stroke: '#1f1f1f', strokeWidth: 1.6, strokeLinecap: 'round' }),
363
+ h('circle', { cx: 8, cy: 11.7, r: 0.9, fill: '#1f1f1f' }),
364
+ )
365
+ }
366
+
367
+ function Meter(props) {
368
+ const sessionId = props.sessionId
369
+ const [state, setState] = React.useState({ status: 'loading', data: null, meta: null })
370
+ const [refresh, setRefresh] = React.useState(0)
371
+ const [backfill, setBackfill] = React.useState(null)
372
+ const backfillTimer = React.useRef(0)
373
+ const hideTimer = React.useRef(0)
374
+ const [bannerTopPx, setBannerTopPx] = React.useState(48)
375
+
376
+ // 警告条挂在对话区上方:测量 View tab 行底部,窗口变化或布局重建时重算。
377
+ React.useEffect(() => {
378
+ const measure = () => {
379
+ const tabs = document.querySelector('[role="tablist"]')
380
+ const rect = tabs ? tabs.getBoundingClientRect() : null
381
+ setBannerTopPx(rect && rect.bottom > 0 ? bannerTop(rect.bottom) : 48)
382
+ }
383
+ measure()
384
+ const timer = window.setInterval(measure, 1000)
385
+ window.addEventListener('resize', measure)
386
+ return () => {
387
+ window.clearInterval(timer)
388
+ window.removeEventListener('resize', measure)
389
+ }
390
+ }, [])
391
+
392
+ React.useEffect(() => {
393
+ setBackfill(null)
394
+ if (backfillTimer.current) {
395
+ window.clearInterval(backfillTimer.current)
396
+ backfillTimer.current = 0
397
+ }
398
+ if (hideTimer.current) {
399
+ window.clearTimeout(hideTimer.current)
400
+ hideTimer.current = 0
401
+ }
402
+ return () => {
403
+ if (backfillTimer.current) {
404
+ window.clearInterval(backfillTimer.current)
405
+ backfillTimer.current = 0
406
+ }
407
+ if (hideTimer.current) {
408
+ window.clearTimeout(hideTimer.current)
409
+ hideTimer.current = 0
410
+ }
411
+ }
412
+ }, [sessionId])
413
+
414
+ React.useEffect(() => {
415
+ let alive = true
416
+ let timer = 0
417
+
418
+ async function load() {
419
+ if (!sessionId) {
420
+ if (alive) setState({ status: 'nodata', data: null, meta: { reason: 'no-session-id' } })
421
+ return
422
+ }
423
+ try {
424
+ const url = ROUTE + '?sessionId=' + encodeURIComponent(sessionId)
425
+ const res = await fetch(url, { cache: 'no-store', headers: { accept: 'application/json' } })
426
+ const body = await res.json()
427
+ if (!alive) return
428
+ if (body && body.ok && body.session) {
429
+ setState({ status: 'ok', data: body.session, meta: body })
430
+ } else if (body && body.ok === false) {
431
+ setState({ status: 'unavailable', data: null, meta: body })
432
+ } else {
433
+ setState({ status: 'nodata', data: null, meta: body })
434
+ }
435
+ } catch {
436
+ if (alive) setState({ status: 'unavailable', data: null, meta: { error: '网络请求失败' } })
437
+ }
438
+ }
439
+
440
+ load()
441
+ timer = window.setInterval(load, POLL_MS)
442
+ return () => {
443
+ alive = false
444
+ window.clearInterval(timer)
445
+ }
446
+ }, [sessionId, refresh])
447
+
448
+ // 交接请求轮询:/handoff 或 /handoff-file 在 host 端登记后由这里执行。
449
+ React.useEffect(() => {
450
+ if (!sessionId || !runtimeCtx) return undefined
451
+ let alive = true
452
+ let busy = false
453
+
454
+ async function tick() {
455
+ if (!alive || busy) return
456
+ try {
457
+ const res = await fetch(
458
+ HANDOFF_ROUTE + '?sessionId=' + encodeURIComponent(sessionId),
459
+ { cache: 'no-store', headers: { accept: 'application/json' } },
460
+ )
461
+ const body = await res.json()
462
+ if (!alive || !body || !body.ok) return
463
+ const list = Array.isArray(body.requests) ? body.requests : []
464
+ for (const req of list) {
465
+ if (!alive) return
466
+ busy = true
467
+ try {
468
+ await runHandoff(runtimeCtx, sessionId, req.kind)
469
+ } catch (err) {
470
+ // 交接失败不打断进度条
471
+ console.warn('[context-meter] handoff failed', err)
472
+ } finally {
473
+ busy = false
474
+ }
475
+ }
476
+ } catch {
477
+ // 轮询失败静默
478
+ }
479
+ }
480
+
481
+ const timer = window.setInterval(tick, HANDOFF_POLL_MS)
482
+ return () => {
483
+ alive = false
484
+ window.clearInterval(timer)
485
+ }
486
+ }, [sessionId])
487
+
488
+ const backfillRunning = Boolean(
489
+ backfill && (backfill.status === 'starting' || backfill.status === 'running'),
490
+ )
491
+ const backfillDone = Boolean(backfill && backfill.status === 'done')
492
+ const showProgress = backfillRunning || backfillDone
493
+
494
+ function cancelBackfill() {
495
+ if (backfillTimer.current) {
496
+ window.clearInterval(backfillTimer.current)
497
+ backfillTimer.current = 0
498
+ }
499
+ if (hideTimer.current) {
500
+ window.clearTimeout(hideTimer.current)
501
+ hideTimer.current = 0
502
+ }
503
+ setBackfill(null)
504
+ }
505
+
506
+ function finishBackfill(jobId) {
507
+ if (backfillTimer.current) {
508
+ window.clearInterval(backfillTimer.current)
509
+ backfillTimer.current = 0
510
+ }
511
+ if (hideTimer.current) {
512
+ window.clearTimeout(hideTimer.current)
513
+ hideTimer.current = 0
514
+ }
515
+ setBackfill({ status: 'done', progress: 1, jobId })
516
+ setRefresh((n) => n + 1)
517
+ // 「完成」停留 1 秒后收起悬浮条。
518
+ hideTimer.current = window.setTimeout(() => {
519
+ hideTimer.current = 0
520
+ setBackfill(null)
521
+ }, 1000)
522
+ }
523
+
524
+ function pollBackfill(jobId) {
525
+ if (backfillTimer.current) window.clearInterval(backfillTimer.current)
526
+ backfillTimer.current = window.setInterval(async () => {
527
+ try {
528
+ const res = await fetch(BACKFILL_ROUTE + '?jobId=' + encodeURIComponent(jobId), {
529
+ cache: 'no-store',
530
+ headers: { accept: 'application/json' },
531
+ })
532
+ const body = await res.json()
533
+ if (!body || !body.ok) throw new Error((body && body.error) || '查询回填状态失败')
534
+ if (body.status === 'done') {
535
+ finishBackfill(jobId)
536
+ } else if (body.status === 'error') {
537
+ window.clearInterval(backfillTimer.current)
538
+ backfillTimer.current = 0
539
+ setBackfill({ status: 'error', progress: 0, error: body.error || '回填失败' })
540
+ } else {
541
+ setBackfill({
542
+ status: body.status || 'running',
543
+ progress: Number(body.progress) || 0,
544
+ jobId,
545
+ })
546
+ }
547
+ } catch (err) {
548
+ window.clearInterval(backfillTimer.current)
549
+ backfillTimer.current = 0
550
+ setBackfill({ status: 'error', progress: 0, error: errorText(err) })
551
+ }
552
+ }, 300)
553
+ }
554
+
555
+ function startBackfill() {
556
+ if (!sessionId || backfillRunning) return
557
+ if (backfillTimer.current) {
558
+ window.clearInterval(backfillTimer.current)
559
+ backfillTimer.current = 0
560
+ }
561
+ setBackfill({ status: 'starting', progress: 0 })
562
+ fetch(BACKFILL_ROUTE, {
563
+ method: 'POST',
564
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
565
+ body: JSON.stringify({ sessionId }),
566
+ })
567
+ .then((res) => res.json())
568
+ .then((body) => {
569
+ if (!body || !body.ok) throw new Error((body && body.error) || '提交回填失败')
570
+ if (body.status === 'done') {
571
+ finishBackfill(body.jobId)
572
+ return
573
+ }
574
+ setBackfill({
575
+ status: body.status || 'running',
576
+ progress: Number(body.progress) || 0,
577
+ jobId: body.jobId,
578
+ })
579
+ pollBackfill(body.jobId)
580
+ })
581
+ .catch((err) => {
582
+ setBackfill({ status: 'error', progress: 0, error: errorText(err) })
583
+ })
584
+ }
585
+
586
+ const data = state.data
587
+ // 只有自采缺历史、并且 cost-meter / billion-context 都没有这个会话数据时才提示。
588
+ const migration = state.meta && state.meta.migration
589
+ const showWarn =
590
+ state.status === 'ok' &&
591
+ Boolean(sessionId) &&
592
+ Boolean(migration && migration.needed)
593
+ if (state.status !== 'ok' || !data) {
594
+ const reasons = {
595
+ 'no-session-id': '拿不到本会话 id',
596
+ unavailable: '统计来源不可用(billion-context 未运行,cost-meter 账本不可读)',
597
+ nodata: '两个来源都还没有这个会话的用量记录',
598
+ }
599
+ const tip =
600
+ '累计输入统计暂不可用:' +
601
+ (reasons[state.status] || reasons.nodata) +
602
+ (state.meta && state.meta.error ? '\n' + state.meta.error : '') +
603
+ '\n新对话在跑完第一轮之前没有记录,属正常。'
604
+ return h(
605
+ 'span',
606
+ { className: '__cm-host' },
607
+ h(
608
+ 'span',
609
+ { className: '__cm-pill __cm-idle', title: tip },
610
+ h('span', { className: '__cm-label' }, '累计计费输入 Tokens'),
611
+ h('span', { className: '__cm-track' }),
612
+ h(
613
+ 'span',
614
+ { className: '__cm-num' },
615
+ '-- / ' + format(tintConfig.window > 0 ? tintConfig.window : DEFAULT_WINDOW),
616
+ ),
617
+ ),
618
+ )
619
+ }
620
+
621
+ const limit = tintConfig.window > 0 ? tintConfig.window : DEFAULT_WINDOW
622
+ const warnPct = clampPct(tintConfig.warn, 60)
623
+ const dangerPct = clampPct(tintConfig.danger, 80)
624
+ const warnTokens = (limit * warnPct) / 100
625
+ const dangerTokens = (limit * dangerPct) / 100
626
+ const input = Number(data.inputTokens) || 0
627
+ const pctRaw = limit > 0 ? (input / limit) * 100 : 0
628
+ const pct = Math.max(0, Math.min(100, pctRaw))
629
+ const color = bodyColor(pct)
630
+ const ctx = Number(data.contextTokens) || 0
631
+ const win = Number(data.contextWindow) || 0
632
+ const ctxPct = win > 0 ? ((ctx / win) * 100).toFixed(0) : '--'
633
+ const sources = (data.source || '')
634
+ .split('+')
635
+ .filter(Boolean)
636
+ .map((s) => SOURCE_LABEL[s] || s)
637
+ .join(' + ')
638
+
639
+ const tip = [
640
+ '累计计费输入:' + input.toLocaleString('en-US') + ' tokens(' + pctRaw.toFixed(1) + '% / ' + format(limit) + ')',
641
+ win > 0
642
+ ? '上下文窗口占用:' + format(ctx) + ' / ' + format(win) + '(' + ctxPct + '%)'
643
+ : '上下文窗口占用:本来源不提供',
644
+ '本会话请求:' + (data.requests ?? 0) + ' 轮 · 折叠块:' + (data.blocks ?? 0),
645
+ input >= dangerTokens
646
+ ? '已达 ' + format(dangerTokens) + ':对话质量可能继续下降,建议把结论写进文件、新开对话续做。'
647
+ : input >= warnTokens
648
+ ? '已达 ' + format(warnTokens) + ' 预警点:每轮在回复开头报用量,每再涨 50M 报一次。'
649
+ : '',
650
+ '数据源:' + (sources || '未知') + '(每 ' + POLL_MS / 1000 + ' 秒刷新)',
651
+ ]
652
+ .filter(Boolean)
653
+ .join('\n')
654
+
655
+ return h(
656
+ 'span',
657
+ { className: '__cm-host' },
658
+ h(
659
+ 'span',
660
+ { className: '__cm-pill', title: tip },
661
+ h('span', { className: '__cm-label' }, '累计计费输入 Tokens'),
662
+ h(
663
+ 'span',
664
+ { className: '__cm-track' },
665
+ h(
666
+ 'span',
667
+ {
668
+ className: '__cm-zone __cm-zone-green',
669
+ style: zoneStyle(0, GREEN_ZONE_END, GREEN_COLOR),
670
+ },
671
+ ),
672
+ h(
673
+ 'span',
674
+ {
675
+ className: '__cm-zone __cm-zone-warn',
676
+ style: zoneStyle(warnPct, dangerPct, tintConfig.warnColor),
677
+ },
678
+ ),
679
+ h(
680
+ 'span',
681
+ {
682
+ className: '__cm-zone __cm-zone-danger',
683
+ style: zoneStyle(dangerPct, 100, tintConfig.dangerColor),
684
+ },
685
+ ),
686
+ h(
687
+ 'span',
688
+ {
689
+ className: '__cm-fill',
690
+ style: { width: pct + '%', backgroundColor: color },
691
+ },
692
+ ),
693
+ ),
694
+ h('span', { className: '__cm-num', style: { color } }, format(input) + ' / ' + format(limit)),
695
+ h('span', { className: '__cm-sep', style: { color } }, '·'),
696
+ h('span', { className: '__cm-num', style: { color } }, pctRaw.toFixed(1) + '%'),
697
+ ),
698
+ showWarn
699
+ ? ReactDOM.createPortal(
700
+ h(
701
+ 'div',
702
+ {
703
+ className: '__cm-banner',
704
+ role: 'status',
705
+ style: { top: bannerTopPx + 'px' },
706
+ title: '当前统计只包含插件启用后新增的 tokens;点击「统计历史Tokens」会扫描该对话历史,把此前的 tokens 补进累计。',
707
+ },
708
+ h(WarnIcon, null),
709
+ h('span', { className: '__cm-banner-text' }, WARN_TEXT + ':当前统计只包含插件启用后新增的 tokens'),
710
+ showProgress
711
+ ? h(
712
+ 'span',
713
+ {
714
+ className: '__cm-progress',
715
+ title: backfillDone ? '回填完成' : '正在扫描该对话的历史日志',
716
+ },
717
+ h('span', { className: '__cm-banner-text' }, backfillDone ? '完成' : '统计中'),
718
+ h(
719
+ 'span',
720
+ { className: '__cm-progress-track' },
721
+ h('span', {
722
+ className: '__cm-progress-fill',
723
+ style: { width: Math.round((Number(backfill.progress) || 0) * 100) + '%' },
724
+ }),
725
+ ),
726
+ h(
727
+ 'span',
728
+ { className: '__cm-progress-pct' },
729
+ progressText(Number(backfill.progress) || 0),
730
+ ),
731
+ )
732
+ : null,
733
+ showProgress
734
+ ? backfillRunning
735
+ ? h(
736
+ 'button',
737
+ {
738
+ type: 'button',
739
+ className: '__cm-banner-btn',
740
+ onClick: cancelBackfill,
741
+ title: '停止等待这次回填(已开始的扫描会在后台继续)',
742
+ },
743
+ '取消',
744
+ )
745
+ : null
746
+ : h(
747
+ 'button',
748
+ {
749
+ type: 'button',
750
+ className: '__cm-banner-btn',
751
+ onClick: startBackfill,
752
+ title:
753
+ backfill && backfill.status === 'error'
754
+ ? backfill.error
755
+ : '扫描该对话历史,把此前的 tokens 补进累计',
756
+ },
757
+ backfill && backfill.status === 'error' ? '重试' : BACKFILL_LABEL,
758
+ ),
759
+ ),
760
+ document.body,
761
+ )
762
+ : null,
763
+ )
764
+ }
765
+
766
+ // ---------------------------------------------------------------
767
+ // 左侧栏会话标题着色
768
+ //
769
+ // 按上下文窗口占用率给左侧会话列表的标题上色:
770
+ // 0–60% 保持原色
771
+ // 60–80% 黄
772
+ // 80%+ 红(含 100% 以上)
773
+ //
774
+ // 侧栏没有可替换「标题」的槽位,只能在 sidebar.session.row.leading
775
+ // 挂一个 display:none 的探针,再沿 DOM 向上找到行容器、给标题碎片
776
+ // 设内联 color(带 !important)。占用率回落时把 color 还原。
777
+ // ---------------------------------------------------------------
778
+
779
+ const SIDEBAR_SLOT = 'sidebar.session.row.leading'
780
+ const SIDEBAR_POLL_MS = 2500
781
+ const SIDEBAR_STORE_MS = 6000
782
+ const DEBUG_ROUTE = '/context-meter/debug'
783
+ const CONTEXTS_ROUTE = '/context-meter/contexts'
784
+
785
+ const TINT_ROUTE = '/context-meter/tint'
786
+ const TINT_POLL_MS = 5000
787
+
788
+ /** 「标记停用」状态:只是视觉标记,不碰会话内容。 */
789
+ const DISABLED_ROUTE = '/context-meter/disabled'
790
+ const DISABLED_POLL_MS = 5000
791
+ const ROW_ACTION_SLOT = 'sidebar.workspaces.session.row.action'
792
+
793
+ /** normalize 后的会话 id 集合;按钮与行着色共用。 */
794
+ const disabledSet = new Set()
795
+
796
+ /** 标记变化后通知所有按钮重渲染(同一会话可能有多个渲染实例)。 */
797
+ const disabledListeners = new Set()
798
+
799
+ function notifyDisabled() {
800
+ for (const fn of disabledListeners) {
801
+ try {
802
+ fn()
803
+ } catch {
804
+ // 单个监听器异常不影响其它
805
+ }
806
+ }
807
+ }
808
+
809
+ async function toggleDisabled(sid) {
810
+ if (!sid) return
811
+ const next = !disabledSet.has(sid)
812
+ if (next) disabledSet.add(sid)
813
+ else disabledSet.delete(sid)
814
+ notifyDisabled()
815
+ try {
816
+ const res = await fetch(DISABLED_ROUTE, {
817
+ method: 'POST',
818
+ headers: { 'content-type': 'application/json' },
819
+ body: JSON.stringify({ id: sid, disabled: next }),
820
+ })
821
+ const body = await res.json()
822
+ if (body && body.ok && Array.isArray(body.ids)) {
823
+ disabledSet.clear()
824
+ for (const id of body.ids) disabledSet.add(normId(id))
825
+ notifyDisabled()
826
+ }
827
+ } catch {
828
+ // 写失败就保留本地状态,下一次轮询会以 host 为准
829
+ }
830
+ }
831
+
832
+ /**
833
+ * 阈值配置。默认就是需求里的 60% / 80%;
834
+ * 想临时验证效果可以改项目目录的 tint.json(例如降到 10 / 20),
835
+ * 5 秒内就会生效,不需要重启 DSH。
836
+ */
837
+ const tintConfig = {
838
+ warn: 60,
839
+ danger: 80,
840
+ window: DEFAULT_WINDOW,
841
+ warnColor: '#e6a700',
842
+ dangerColor: '#e5534b',
843
+ }
844
+
845
+ /** 全量会话用量缓存:normalize 后的 id -> 会话摘要。 */
846
+ const sidebarStore = { byId: {}, at: 0 }
847
+
848
+ /** 会话文件算出来的上下文占用:normalize 后的 id -> {used, window, pct}。 */
849
+ const contextStore = { byId: {} }
850
+
851
+ /** 需要向 host 拉取上下文占用的会话 id。 */
852
+ const pendingIds = new Set()
853
+
854
+ /** 统一 id:去掉 billion-context 的 session- 前缀并小写。 */
855
+ const normId = (id) => String(id || '').trim().toLowerCase().replace(/^session-/, '')
856
+
857
+ function lookupSession(id) {
858
+ const key = normId(id)
859
+ return key ? sidebarStore.byId[key] || null : null
860
+ }
861
+
862
+ /** 上过色的元素 -> 原始内联 color(空串表示原本没有内联色)。 */
863
+ const tintedElements = new Map()
864
+
865
+ /** 每个会话的行着色结果只上报一次,避免刷爆 debug.log。 */
866
+ const tintDebugged = new Set()
867
+
868
+ function sendDebug(payload) {
869
+ try {
870
+ fetch(DEBUG_ROUTE, {
871
+ method: 'POST',
872
+ headers: { 'content-type': 'application/json' },
873
+ body: JSON.stringify(payload),
874
+ }).catch(() => {})
875
+ } catch {
876
+ // 调试上报失败静默
877
+ }
878
+ }
879
+
880
+ let rowProbed = false
881
+
882
+ /** 首次挂载时把 DOM 祖先链上报一次,便于在没有 devtools 时定位结构。 */
883
+ function probeRow(el, sid, props) {
884
+ if (rowProbed || !el) return
885
+ rowProbed = true
886
+ const chain = []
887
+ let node = el
888
+ for (let i = 0; i < 10 && node; i += 1) {
889
+ chain.push({
890
+ i,
891
+ tag: node.tagName,
892
+ cls: String(node.className || '').slice(0, 100),
893
+ kids: node.childElementCount,
894
+ text: String(node.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 48),
895
+ })
896
+ node = node.parentElement
897
+ }
898
+ sendDebug({
899
+ kind: 'row-probe',
900
+ sid: sid || '',
901
+ propKeys: Object.keys(props || {}),
902
+ chain,
903
+ })
904
+ }
905
+
906
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-/i
907
+
908
+ /** 从槽位 props 里取 sessionId。 */
909
+ function sidOf(props) {
910
+ if (!props) return ''
911
+ const cands = [
912
+ props.sessionId,
913
+ props.session && props.session.sessionId,
914
+ props.session && props.session.id,
915
+ props.row && props.row.sessionId,
916
+ props.item && props.item.sessionId,
917
+ props.id,
918
+ ]
919
+ for (const c of cands) {
920
+ if (typeof c === 'string' && UUID_RE.test(normId(c))) return normId(c)
921
+ }
922
+ return ''
923
+ }
924
+
925
+ /** 兜底:从 React fiber 的 props 上取 sessionId。 */
926
+ function sidFromDom(el) {
927
+ let node = el
928
+ for (let i = 0; i < 8 && node; i += 1) {
929
+ const keys = Object.keys(node).filter((k) => k.indexOf('__reactProps$') === 0)
930
+ for (const k of keys) {
931
+ const p = node[k]
932
+ if (!p || typeof p !== 'object') continue
933
+ const cands = [p.sessionId, p.session && p.session.sessionId, p.session && p.session.id]
934
+ for (const c of cands) {
935
+ if (typeof c === 'string' && UUID_RE.test(normId(c))) return normId(c)
936
+ }
937
+ }
938
+ node = node.parentElement
939
+ }
940
+ return ''
941
+ }
942
+
943
+ /** 最后兜底:用行文本在已缓存的会话标题里找最长匹配。 */
944
+ function sidByRowText(text) {
945
+ const raw = String(text || '')
946
+ if (!raw) return ''
947
+ let best = ''
948
+ let bestLen = 0
949
+ for (const key of Object.keys(sidebarStore.byId)) {
950
+ const title = sidebarStore.byId[key].title
951
+ if (typeof title !== 'string' || title.length < 3) continue
952
+ if (raw.indexOf(title) < 0) continue
953
+ if (title.length > bestLen) {
954
+ best = key
955
+ bestLen = title.length
956
+ }
957
+ }
958
+ return best
959
+ }
960
+
961
+ function clearUnder(root) {
962
+ for (const [el, prev] of tintedElements) {
963
+ // DOM 被 React 重建成新节点后,旧引用直接丢弃,避免无限增长
964
+ if (!el.isConnected) {
965
+ tintedElements.delete(el)
966
+ continue
967
+ }
968
+ if (!root.contains(el)) continue
969
+ if (prev) el.style.setProperty('color', prev)
970
+ else el.style.removeProperty('color')
971
+ tintedElements.delete(el)
972
+ }
973
+ }
974
+
975
+ function setTint(el, color) {
976
+ if (!tintedElements.has(el)) tintedElements.set(el, el.style.color || '')
977
+ el.style.setProperty('color', color, 'important')
978
+ }
979
+
980
+ // ---- 「标记停用」的删除线 ----------------------------------------
981
+ //
982
+ // 需求:标题整条加删除线,但结尾的 "#N" 编号不划、只跟着变灰。
983
+ // 不改 React 管理的文本节点结构(宿主重渲染会打乱 fiber),
984
+ // 改用 background 渐变画线,再用 calc(100% - Npx) 把编号那截收回来,
985
+ // N 由 canvas 按标题元素的实际字体量出来。
986
+
987
+ /** 画过删除线/压暗的元素 -> 需要还原的 style 属性名。 */
988
+ const struckElements = new Map()
989
+
990
+ /** 把改过的属性名记到元素上,取消停用时逐个还原。 */
991
+ function recordStyle(el, props) {
992
+ const prev = struckElements.get(el)
993
+ if (!prev) {
994
+ struckElements.set(el, props.slice())
995
+ return
996
+ }
997
+ const merged = prev.slice()
998
+ for (const p of props) {
999
+ if (merged.indexOf(p) < 0) merged.push(p)
1000
+ }
1001
+ struckElements.set(el, merged)
1002
+ }
1003
+
1004
+ /**
1005
+ * 停用状态的「压暗」:直接把颜色乘一个系数,而不是用 filter。
1006
+ * 用 color 是为了让编号那一截可以完全不压暗——filter 会作用整个元素。
1007
+ */
1008
+ function darkenRgb(color, factor) {
1009
+ const m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(color || ''))
1010
+ if (!m) return null
1011
+ const to = (v) => Math.max(0, Math.min(255, Math.round(Number(v) * factor)))
1012
+ return 'rgb(' + to(m[1]) + ',' + to(m[2]) + ',' + to(m[3]) + ')'
1013
+ }
1014
+
1015
+ function dimNow(el) {
1016
+ const dim = darkenRgb(window.getComputedStyle(el).color, 0.62)
1017
+ if (dim) setTint(el, dim)
1018
+ }
1019
+
1020
+ // ---- 编号 "#N" 保持原样 ------------------------------------------
1021
+ //
1022
+ // 需求:停用时正文压暗 + 加删除线,但结尾的 "#N" 保持原色、不划线。
1023
+ // 正文和编号原本在同一个文本节点里,没法分别设样式,所以在停用期间
1024
+ // 把标题临时拆成两个 span:.__cm-body(正文)和 .__cm-idx(编号)。
1025
+ // 取消停用时再合并回一个文本节点。
1026
+ // 这层 DOM 改动每轮都会自愈:React 重建标题后,下一个 tick 重新拆。
1027
+
1028
+ const IDX_CLASS = '__cm-idx'
1029
+ const BODY_CLASS = '__cm-body'
1030
+
1031
+ function unsplitTitles(root) {
1032
+ const nodes = root.querySelectorAll('.' + IDX_CLASS)
1033
+ for (const idx of nodes) {
1034
+ const parent = idx.parentElement
1035
+ if (!parent) continue
1036
+ parent.textContent = parent.textContent || ''
1037
+ }
1038
+ }
1039
+
1040
+ /** 把 "xxx #1" 拆成两个 span;不含编号则返回 null。 */
1041
+ function splitTitle(el) {
1042
+ try {
1043
+ const text = el.textContent || ''
1044
+ const m = /^(.*?)(\s*#\d+)\s*$/.exec(text)
1045
+ if (!m || !String(m[1] || '').trim()) return null
1046
+
1047
+ el.textContent = ''
1048
+ const body = document.createElement('span')
1049
+ body.className = BODY_CLASS
1050
+ body.textContent = m[1]
1051
+ const idx = document.createElement('span')
1052
+ idx.className = IDX_CLASS
1053
+ idx.textContent = m[2]
1054
+ el.appendChild(body)
1055
+ el.appendChild(idx)
1056
+ return { body, idx }
1057
+ } catch {
1058
+ return null
1059
+ }
1060
+ }
1061
+
1062
+ function strike(el) {
1063
+ el.style.setProperty('text-decoration', 'line-through', 'important')
1064
+ recordStyle(el, ['text-decoration'])
1065
+ }
1066
+
1067
+ function clearStrikesUnder(root) {
1068
+ for (const [el, props] of struckElements) {
1069
+ if (!el.isConnected) {
1070
+ struckElements.delete(el)
1071
+ continue
1072
+ }
1073
+ if (!root.contains(el)) continue
1074
+ for (const p of props) el.style.removeProperty(p)
1075
+ struckElements.delete(el)
1076
+ }
1077
+ }
1078
+
1079
+ /** 行内的相对时间/状态文本,不上色。 */
1080
+ const TIME_RE = /^\d+\s*(秒|分钟|小时|天|周|个月|年)$|^(刚刚|今天|昨天|前天)$/
1081
+
1082
+ /**
1083
+ * 行内候选叶子元素缓存。React 复用会话行时行结构通常不变,
1084
+ * 每轮 tick 不必再 querySelectorAll('*') 全量扫描。
1085
+ * 行被重建(旧节点断开)时自动重新收集。
1086
+ */
1087
+ const leafCache = new WeakMap()
1088
+
1089
+ function leavesOf(root) {
1090
+ const cached = leafCache.get(root)
1091
+ if (cached && cached.length > 0 && cached.every((el) => el.isConnected)) return cached
1092
+ const list = []
1093
+ for (const item of root.querySelectorAll('*')) {
1094
+ if (item.childElementCount > 0) continue
1095
+ const text = String(item.textContent || '').trim()
1096
+ if (!text) continue
1097
+ if (TIME_RE.test(text)) continue
1098
+ list.push(item)
1099
+ }
1100
+ leafCache.set(root, list)
1101
+ return list
1102
+ }
1103
+
1104
+ /** 从探针向上找会话行容器:debug.log 的 row-probe 记录显示 class 里带 sessionRow。 */
1105
+ function rowRoot(el) {
1106
+ if (el && typeof el.closest === 'function') {
1107
+ const direct = el.closest('[class*="sessionRow"]')
1108
+ if (direct) return direct
1109
+ }
1110
+ let node = el
1111
+ for (let i = 0; i < 8 && node; i += 1) {
1112
+ if (node.nodeType === 1 && /sessionRow/.test(String(node.className || ''))) return node
1113
+ node = node.parentElement
1114
+ }
1115
+ return null
1116
+ }
1117
+
1118
+ /**
1119
+ * 给一行会话标题上色。
1120
+ * 每轮都先把本行还原成原色再按需重画,避免「一次上色后再也清不掉」的残留。
1121
+ */
1122
+ function paintRow(el, title, pct, disabled) {
1123
+ if (!el) return null
1124
+
1125
+ let target = rowRoot(el)
1126
+ if (!target) {
1127
+ const needle = String(title || '').trim()
1128
+ if (!needle) return null
1129
+ let node = el
1130
+ for (let i = 0; i < 10 && node; i += 1) {
1131
+ if (String(node.textContent || '').indexOf(needle) >= 0) {
1132
+ if (node.querySelectorAll('*').length > 80) return null
1133
+ target = node
1134
+ break
1135
+ }
1136
+ node = node.parentElement
1137
+ }
1138
+ }
1139
+ if (!target) return null
1140
+
1141
+ // 先还原本行所有曾上色的元素,保证是「从干净状态重画」
1142
+ // 拆过的标题也先合并回去,避免每轮重复拆
1143
+ unsplitTitles(target)
1144
+ clearUnder(target)
1145
+ clearStrikesUnder(target)
1146
+
1147
+ // 停用状态:正文压暗 + 删除线;编号 "#N" 保持原色、不压暗、不划线。
1148
+ if (disabled) {
1149
+ const offHits = leavesOf(target)
1150
+ const baseColor =
1151
+ pct >= tintConfig.danger
1152
+ ? tintConfig.dangerColor
1153
+ : pct >= tintConfig.warn
1154
+ ? tintConfig.warnColor
1155
+ : ''
1156
+ for (const item of offHits) {
1157
+ const parts = splitTitle(item)
1158
+ if (parts) {
1159
+ if (baseColor) setTint(parts.body, baseColor)
1160
+ dimNow(parts.body)
1161
+ strike(parts.body)
1162
+ // 编号保持原样
1163
+ if (baseColor) setTint(parts.idx, baseColor)
1164
+ } else {
1165
+ if (baseColor) setTint(item, baseColor)
1166
+ dimNow(item)
1167
+ strike(item)
1168
+ }
1169
+ }
1170
+ return { pct, hits: offHits.length, disabled: true, color: baseColor || 'inherit' }
1171
+ }
1172
+
1173
+ if (!(pct >= tintConfig.warn)) {
1174
+ return { pct, hits: 0, cleared: true }
1175
+ }
1176
+
1177
+ const color = pct >= tintConfig.danger ? tintConfig.dangerColor : tintConfig.warnColor
1178
+ const hits = leavesOf(target)
1179
+
1180
+ for (const item of hits) setTint(item, color)
1181
+ return { pct, hits: hits.length, color, kids: target.querySelectorAll('*').length }
1182
+ }
1183
+
1184
+ function RowTint(props) {
1185
+ const ref = React.useRef(null)
1186
+ const latest = React.useRef(props)
1187
+ const tickRef = React.useRef(null)
1188
+ latest.current = props
1189
+ const sidProp = sidOf(props)
1190
+
1191
+ // 停用标记一变就立刻重画,不必等下一个 2.5 秒轮询。
1192
+ React.useEffect(() => {
1193
+ const bump = () => {
1194
+ if (tickRef.current) tickRef.current()
1195
+ }
1196
+ disabledListeners.add(bump)
1197
+ return () => {
1198
+ disabledListeners.delete(bump)
1199
+ }
1200
+ }, [])
1201
+
1202
+ React.useEffect(() => {
1203
+ let alive = true
1204
+
1205
+ const tick = () => {
1206
+ if (!alive) return
1207
+ const el = ref.current
1208
+ if (!el) return
1209
+
1210
+ let sid = sidOf(latest.current) || sidProp
1211
+ if (!sid) sid = sidFromDom(el)
1212
+ if (!sid) {
1213
+ let node = el
1214
+ for (let i = 0; i < 4 && node; i += 1) {
1215
+ const text = String(node.textContent || '').replace(/\s+/g, ' ').trim()
1216
+ if (text && text.length < 160) {
1217
+ const guess = sidByRowText(text)
1218
+ if (guess) {
1219
+ sid = guess
1220
+ break
1221
+ }
1222
+ }
1223
+ node = node.parentElement
1224
+ }
1225
+ }
1226
+
1227
+ probeRow(el, sid, latest.current)
1228
+ if (!sid) return
1229
+
1230
+ // 与顶部进度条同一口径:累计计费输入 / 上限(默认 500M)。
1231
+ // 不是模型窗口占用率——窗口占用普遍只有 15%~50%,永远到不了 60%。
1232
+ const entry = lookupSession(sid)
1233
+ const used = entry ? Number(entry.inputTokens) || 0 : 0
1234
+ const win = tintConfig.window > 0 ? tintConfig.window : DEFAULT_WINDOW
1235
+ const pct = win > 0 ? (used / win) * 100 : 0
1236
+ const title = (entry && entry.title) || readTitle(runtimeCtx, sid) || ''
1237
+ const result = paintRow(el, title, pct, disabledSet.has(sid))
1238
+
1239
+ if (!tintDebugged.has(sid)) {
1240
+ tintDebugged.add(sid)
1241
+ sendDebug({
1242
+ kind: 'tint',
1243
+ sid,
1244
+ title,
1245
+ used,
1246
+ window: win,
1247
+ pct: Math.round(pct * 10) / 10,
1248
+ warn: tintConfig.warn,
1249
+ danger: tintConfig.danger,
1250
+ result: result || null,
1251
+ })
1252
+ }
1253
+ }
1254
+
1255
+ tick()
1256
+ tickRef.current = tick
1257
+ const timer = window.setInterval(tick, SIDEBAR_POLL_MS)
1258
+ return () => {
1259
+ alive = false
1260
+ window.clearInterval(timer)
1261
+ }
1262
+ }, [sidProp])
1263
+
1264
+ return h('span', { ref, style: { display: 'none' }, 'aria-hidden': 'true' })
1265
+ }
1266
+
1267
+ /**
1268
+ * 会话行尾的「∅」按钮:切换该对话的「标记停用」状态。
1269
+ * 只改视觉,不碰会话内容。
1270
+ */
1271
+ function DisableToggle(props) {
1272
+ const ref = React.useRef(null)
1273
+ const probedRef = React.useRef(false)
1274
+ const [, force] = React.useReducer((n) => n + 1, 0)
1275
+ const [fallbackSid, setFallbackSid] = React.useState('')
1276
+
1277
+ React.useEffect(() => {
1278
+ disabledListeners.add(force)
1279
+ return () => {
1280
+ disabledListeners.delete(force)
1281
+ }
1282
+ }, [])
1283
+
1284
+ const sid = sidOf(props) || fallbackSid
1285
+
1286
+ React.useEffect(() => {
1287
+ if (sid) return
1288
+ const el = ref.current
1289
+ if (!el) return
1290
+ const guess = sidFromDom(el)
1291
+ if (guess) setFallbackSid(guess)
1292
+ })
1293
+
1294
+ // 首次挂载上报一次行尾按钮区的结构,便于确认「…」和本按钮的相对位置。
1295
+ React.useEffect(() => {
1296
+ if (probedRef.current) return
1297
+ const el = ref.current
1298
+ if (!el || !el.parentElement) return
1299
+ probedRef.current = true
1300
+ const parent = el.parentElement
1301
+ sendDebug({
1302
+ kind: 'action-probe',
1303
+ parent: {
1304
+ tag: parent.tagName,
1305
+ cls: String(parent.className || '').slice(0, 120),
1306
+ kids: parent.childElementCount,
1307
+ },
1308
+ siblings: Array.from(parent.children).map((c) => ({
1309
+ tag: c.tagName,
1310
+ cls: String(c.className || '').slice(0, 90),
1311
+ text: String(c.textContent || '').trim().slice(0, 16),
1312
+ title: String((c.getAttribute && c.getAttribute('title')) || '').slice(0, 16),
1313
+ self: c === el,
1314
+ })),
1315
+ })
1316
+ }, [])
1317
+
1318
+ if (!sid) return h('span', { ref, style: { display: 'none' }, 'aria-hidden': 'true' })
1319
+
1320
+ const on = disabledSet.has(sid)
1321
+ const label = on ? '取消停用' : '标记停用'
1322
+ return h(
1323
+ 'button',
1324
+ {
1325
+ ref,
1326
+ type: 'button',
1327
+ className: '__cm-off' + (on ? ' __cm-off-on' : ''),
1328
+ title: label,
1329
+ 'aria-label': label,
1330
+ 'aria-pressed': on ? 'true' : 'false',
1331
+ 'data-cm-off': sid,
1332
+ onClick: (e) => {
1333
+ e.preventDefault()
1334
+ e.stopPropagation()
1335
+ toggleDisabled(sid)
1336
+ },
1337
+ },
1338
+ // 「禁止」符号:圆圈 + 斜杠,和 ∅ 同一个意思但画得更大更清楚。
1339
+ h(
1340
+ 'svg',
1341
+ {
1342
+ viewBox: '0 0 16 16',
1343
+ fill: 'none',
1344
+ stroke: 'currentColor',
1345
+ strokeWidth: 1.7,
1346
+ strokeLinecap: 'round',
1347
+ 'aria-hidden': 'true',
1348
+ focusable: 'false',
1349
+ },
1350
+ h('circle', { cx: 8, cy: 8, r: 6.1 }),
1351
+ h('line', { x1: 3.7, y1: 12.3, x2: 12.3, y2: 3.7 }),
1352
+ ),
1353
+ )
1354
+ }
1355
+
1356
+ // 测试钩子:让冒烟脚本能直接验证标题递增规则。
1357
+ Meter.nextTitle = nextTitle
1358
+ Meter.helpers = {
1359
+ format,
1360
+ clampPct,
1361
+ zoneStyle,
1362
+ isHexColor,
1363
+ hexToRgba,
1364
+ bodyColor,
1365
+ buildBootstrapPrompt,
1366
+ greenZone: () => zoneStyle(0, GREEN_ZONE_END, GREEN_COLOR),
1367
+ warnText: () => WARN_TEXT,
1368
+ backfillLabel: () => BACKFILL_LABEL,
1369
+ progressText,
1370
+ bannerTop,
1371
+ }
1372
+ RowTint.derive = { sidOf, normId, paintRow }
1373
+ DisableToggle.derive = { sidOf, toggleDisabled, disabledSet }
1374
+
1375
+ return {
1376
+ inject: ['slots'],
1377
+ apply(ctx) {
1378
+ runtimeCtx = ctx
1379
+ ctx.effect(() => {
1380
+ const el = document.createElement('style')
1381
+ el.setAttribute('data-context-meter', '')
1382
+ el.textContent = CSS
1383
+ document.head.appendChild(el)
1384
+ return () => el.remove()
1385
+ }, 'context-meter: styles')
1386
+
1387
+ // order 2:紧跟 cost-meter-statistics(1) 之后、subagent-catalog(10) 之前,
1388
+ // 即「费用明细」右侧、「x 个子智能体」左侧。
1389
+ ctx.slots.inject('conversation.session.header.actions', () =>
1390
+ ctx.slots.register(
1391
+ { name: 'conversation.session.header.actions', id: 'context-meter', order: 2 },
1392
+ Meter,
1393
+ ),
1394
+ )
1395
+
1396
+ // 左侧栏标题着色需要全量会话的窗口占用率,单独维护一份缓存。
1397
+ ctx.effect(() => {
1398
+ let alive = true
1399
+ const refresh = async () => {
1400
+ try {
1401
+ const res = await fetch(ROUTE, {
1402
+ cache: 'no-store',
1403
+ headers: { accept: 'application/json' },
1404
+ })
1405
+ const body = await res.json()
1406
+ if (!alive || !body || !Array.isArray(body.sessions)) return
1407
+ if (body.paths && body.paths.globalAgents) globalPaths.globalAgents = body.paths.globalAgents
1408
+ const byId = {}
1409
+ for (const item of body.sessions) {
1410
+ if (!item || !item.id) continue
1411
+ byId[normId(item.id)] = item
1412
+ }
1413
+ sidebarStore.byId = byId
1414
+ sidebarStore.at = Date.now()
1415
+ } catch {
1416
+ // 刷新失败保留旧缓存
1417
+ }
1418
+ }
1419
+ refresh()
1420
+ const timer = window.setInterval(refresh, SIDEBAR_STORE_MS)
1421
+ return () => {
1422
+ alive = false
1423
+ window.clearInterval(timer)
1424
+ }
1425
+ }, 'context-meter: sidebar stats')
1426
+
1427
+ // 阈值配置:改项目目录的 tint.json 即可热调,不必重启 DSH。
1428
+ ctx.effect(() => {
1429
+ let alive = true
1430
+ const refresh = async () => {
1431
+ try {
1432
+ const res = await fetch(TINT_ROUTE, {
1433
+ cache: 'no-store',
1434
+ headers: { accept: 'application/json' },
1435
+ })
1436
+ const body = await res.json()
1437
+ if (!alive || !body || !body.ok) return
1438
+ if (Number.isFinite(Number(body.warn))) tintConfig.warn = Number(body.warn)
1439
+ if (Number.isFinite(Number(body.danger))) tintConfig.danger = Number(body.danger)
1440
+ if (Number.isFinite(Number(body.window)) && Number(body.window) > 0) {
1441
+ tintConfig.window = Number(body.window)
1442
+ }
1443
+ if (isHexColor(body.warnColor)) tintConfig.warnColor = body.warnColor
1444
+ if (isHexColor(body.dangerColor)) tintConfig.dangerColor = body.dangerColor
1445
+ } catch {
1446
+ // 拉不到就沿用当前阈值
1447
+ }
1448
+ }
1449
+ refresh()
1450
+ const timer = window.setInterval(refresh, TINT_POLL_MS)
1451
+ return () => {
1452
+ alive = false
1453
+ window.clearInterval(timer)
1454
+ }
1455
+ }, 'context-meter: tint config')
1456
+
1457
+ ctx.slots.inject(SIDEBAR_SLOT, () =>
1458
+ ctx.slots.register(
1459
+ { name: SIDEBAR_SLOT, id: 'context-meter-sidebar', order: 999 },
1460
+ RowTint,
1461
+ ),
1462
+ )
1463
+
1464
+ // 行尾的「∅ 标记停用」按钮。该槽位的按钮渲染在「…」之后,
1465
+ // 用 CSS 负向偏移把它挪到「…」左侧。
1466
+ ctx.slots.inject(ROW_ACTION_SLOT, () =>
1467
+ ctx.slots.register(
1468
+ { name: ROW_ACTION_SLOT, id: 'context-meter-disable', order: -100 },
1469
+ DisableToggle,
1470
+ ),
1471
+ )
1472
+
1473
+ // 停用标记:启动拉一次,之后定时同步(host 侧 /handoff 也会写)。
1474
+ ctx.effect(() => {
1475
+ let alive = true
1476
+ const refresh = async () => {
1477
+ try {
1478
+ const res = await fetch(DISABLED_ROUTE, {
1479
+ cache: 'no-store',
1480
+ headers: { accept: 'application/json' },
1481
+ })
1482
+ const body = await res.json()
1483
+ if (!alive || !body || !body.ok || !Array.isArray(body.ids)) return
1484
+ disabledSet.clear()
1485
+ for (const id of body.ids) disabledSet.add(normId(id))
1486
+ notifyDisabled()
1487
+ } catch {
1488
+ // 拉不到就保留当前状态
1489
+ }
1490
+ }
1491
+ refresh()
1492
+ const timer = window.setInterval(refresh, DISABLED_POLL_MS)
1493
+ return () => {
1494
+ alive = false
1495
+ window.clearInterval(timer)
1496
+ }
1497
+ }, 'context-meter: disabled state')
1498
+
1499
+ // 行组件登记需要的 sessionId,这里统一批量向 host 取上下文占用。
1500
+ ctx.effect(() => {
1501
+ let alive = true
1502
+ const pull = async () => {
1503
+ const ids = [...pendingIds]
1504
+ pendingIds.clear()
1505
+ if (ids.length === 0) return
1506
+ try {
1507
+ const res = await fetch(
1508
+ CONTEXTS_ROUTE + '?ids=' + encodeURIComponent(ids.join(',')),
1509
+ { cache: 'no-store', headers: { accept: 'application/json' } },
1510
+ )
1511
+ const body = await res.json()
1512
+ if (!alive || !body || !body.ok || !body.items) return
1513
+ for (const key of Object.keys(body.items)) {
1514
+ contextStore.byId[key] = body.items[key]
1515
+ }
1516
+ } catch {
1517
+ // 拉取失败保留旧值,下一轮再试
1518
+ }
1519
+ }
1520
+ const timer = window.setInterval(pull, SIDEBAR_POLL_MS)
1521
+ return () => {
1522
+ alive = false
1523
+ window.clearInterval(timer)
1524
+ }
1525
+ }, 'context-meter: sidebar contexts')
1526
+ },
1527
+ }
1528
+ },
1529
+ })