dsh-usage-bar 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js ADDED
@@ -0,0 +1,1155 @@
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
+ * 颜色分档(进度条本体 + 两个数字同色):
13
+ * 0–40% 绿
14
+ * 40–60% 白
15
+ * 60–80% 黄
16
+ * 80–100% 红
17
+ * 轨道上叠了 60–80% 黄斜纹、80–100% 红斜纹的警示区,超过 500M 按 100% 显示。
18
+ */
19
+ window.__ModuleLoader__.load({
20
+ id: 'dsh-usage-bar',
21
+ factory(require) {
22
+ const React = require('react')
23
+ const h = React.createElement
24
+
25
+ /** 满刻度:500M(十进制,token 计数口径)。 */
26
+ const LIMIT = 500 * 1000 * 1000
27
+ /** AGENTS 里的两档预警点位。 */
28
+ const WARN_TOKENS = 400 * 1000 * 1000
29
+ const DANGER_TOKENS = 500 * 1000 * 1000
30
+ const POLL_MS = 4000
31
+ const ROUTE = '/context-meter/stats'
32
+ const HANDOFF_ROUTE = '/context-meter/handoff'
33
+ /** 交接请求轮询间隔。 */
34
+ const HANDOFF_POLL_MS = 1500
35
+
36
+ const CSS = `
37
+ .__cm-host{display:inline-flex;align-items:center;min-width:0}
38
+ .__cm-pill{display:inline-flex;align-items:center;gap:8px;max-width:100%;
39
+ padding:3px 10px;border-radius:999px;background:rgba(128,128,128,.08);
40
+ font-size:12px;line-height:16px;white-space:nowrap;cursor:default;
41
+ transition:background .15s ease}
42
+ .__cm-pill:hover{background:rgba(128,128,128,.16)}
43
+ .__cm-label{color:inherit;opacity:.72;flex:none}
44
+ .__cm-track{position:relative;flex:none;width:180px;height:10px;border-radius:5px;
45
+ background:rgba(128,128,128,.30);overflow:hidden;
46
+ box-shadow:inset 0 0 0 1px rgba(128,128,128,.18)}
47
+ .__cm-zone{position:absolute;top:0;bottom:0;pointer-events:none}
48
+ .__cm-zone-warn{left:60%;width:20%;
49
+ background-image:repeating-linear-gradient(45deg,rgba(230,167,0,.55) 0 3px,transparent 3px 7px)}
50
+ .__cm-zone-danger{left:80%;width:20%;
51
+ background-image:repeating-linear-gradient(45deg,rgba(229,83,75,.55) 0 3px,transparent 3px 7px)}
52
+ .__cm-fill{position:absolute;top:0;bottom:0;left:0;border-radius:5px 0 0 5px;
53
+ transition:width .35s ease,background-color .35s ease}
54
+ .__cm-num{font-variant-numeric:tabular-nums;flex:none}
55
+ .__cm-sep{opacity:.55;flex:none}
56
+ .__cm-idle{opacity:.55}
57
+ .__cm-off{display:inline-flex;align-items:center;justify-content:center;
58
+ width:20px;height:20px;padding:0;margin:0 2px 0 0;border:0;border-radius:4px;
59
+ background:transparent;color:inherit;opacity:.55;cursor:pointer;
60
+ line-height:0;font-family:inherit;
61
+ order:-1;flex:none}
62
+ .__cm-off svg{display:block;width:15px;height:15px}
63
+ .__cm-off:hover{opacity:1;background:rgba(128,128,128,.2)}
64
+ .__cm-off-on{opacity:.95;color:#c9a227}
65
+ .__cm-off-on:hover{opacity:1;color:#e0b62e}
66
+ `
67
+
68
+
69
+ /** apply 时的 ctx,供组件里的交接动作使用。 */
70
+ let runtimeCtx = null
71
+ // host 通过 /context-meter/stats 带回来的真实路径(避免在这里写死用户名)
72
+ const globalPaths = { globalAgents: '' }
73
+
74
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
75
+
76
+ /** 20261128-001234 */
77
+ function formatStamp(d) {
78
+ const pad = (n) => String(n).padStart(2, '0')
79
+ return (
80
+ String(d.getFullYear()) +
81
+ pad(d.getMonth() + 1) +
82
+ pad(d.getDate()) +
83
+ '-' +
84
+ pad(d.getHours()) +
85
+ pad(d.getMinutes()) +
86
+ pad(d.getSeconds())
87
+ )
88
+ }
89
+
90
+ /**
91
+ * 下一个标题:Create -> Create #2;Create #1 -> Create #2;Create #2 -> Create #3。
92
+ */
93
+ function nextTitle(title) {
94
+ const base = String(title || '').trim()
95
+ const m = /^(.*?)\s*#(\d+)$/.exec(base)
96
+ if (m) return m[1].trim() + ' #' + (Number(m[2]) + 1)
97
+ return (base || '对话') + ' #2'
98
+ }
99
+
100
+ /** 读会话标题:projection 优先,其次 summary 上的兼容字段。 */
101
+ function readTitle(ctx, sessionId) {
102
+ try {
103
+ const sessions = ctx.get('sessions')
104
+ const snap = sessions.list.getSnapshot()
105
+ const proj = snap.projectionsBySession && snap.projectionsBySession[sessionId]
106
+ if (proj) {
107
+ if (typeof proj.title === 'string') return proj.title
108
+ if (proj.title && typeof proj.title === 'object' && typeof proj.title.value === 'string') {
109
+ return proj.title.value
110
+ }
111
+ }
112
+ const row = snap.byId && snap.byId[sessionId]
113
+ if (row) {
114
+ if (typeof row.title === 'string') return row.title
115
+ if (typeof row.displayTitle === 'string') return row.displayTitle
116
+ }
117
+ } catch {
118
+ // 拿不到标题时退回空串
119
+ }
120
+ return ''
121
+ }
122
+
123
+ /** 借一个已 retain 的 binding;没有就临时 retain,用完 release。 */
124
+ async function withBinding(ctx, sessionId, fn) {
125
+ const sessions = ctx.get('sessions')
126
+ const direct = sessions.binding(sessionId)
127
+ if (direct && direct.session) return fn(direct)
128
+ let ref = null
129
+ try {
130
+ ref = sessions.retain(sessionId, { source: 'controllerOperation' })
131
+ const binding = ref && ref.ready ? await ref.ready : ref
132
+ return await fn(binding)
133
+ } finally {
134
+ if (ref && typeof ref.release === 'function') ref.release()
135
+ }
136
+ }
137
+
138
+ /** 等会话不再 running(最多 timeoutMs),用于等模型把交接文件写完。 */
139
+ async function waitIdle(ctx, sessionId, timeoutMs) {
140
+ const deadline = Date.now() + timeoutMs
141
+ await sleep(400)
142
+ while (Date.now() < deadline) {
143
+ try {
144
+ const binding = ctx.get('sessions').binding(sessionId)
145
+ if (binding && !binding.session.getSnapshot().running) return true
146
+ } catch {
147
+ return false
148
+ }
149
+ await sleep(600)
150
+ }
151
+ return false
152
+ }
153
+
154
+ /** 调 startSession 之后等列表里冒出新的会话 id。 */
155
+ async function waitNewSession(ctx, before, timeoutMs) {
156
+ const deadline = Date.now() + timeoutMs
157
+ while (Date.now() < deadline) {
158
+ await sleep(150)
159
+ try {
160
+ const ids = ctx.get('sessions').list.getSnapshot().ids || []
161
+ for (const id of ids) if (!before.has(id)) return id
162
+ } catch {
163
+ return ''
164
+ }
165
+ }
166
+ return ''
167
+ }
168
+
169
+ function buildWritePrompt(filePath) {
170
+ return [
171
+ '请把本次对话的工作交接内容写成一份 Markdown 文档,保存到这个绝对路径:',
172
+ filePath,
173
+ '',
174
+ '要求:',
175
+ '1. 正文用中文,Markdown 格式;第一行写成「# 工作交接:<本次对话的标题>」。',
176
+ '2. 至少包含:当前任务与目标、已完成的工作、修改过的文件(写完整绝对路径)、关键决策与原因、未完成事项与下一步、需要注意的约定或风险。',
177
+ '3. 只写确实发生在本次对话里的内容;不确定的标成「未确认」,不要编造。',
178
+ '4. 如果目标目录还不存在,请先创建。',
179
+ '5. 文件写完后,在你的回复最后单独一行输出:交接文件已生成:<完整路径>',
180
+ ].join('\n')
181
+ }
182
+
183
+ function buildBootstrapPrompt(filePath, cwd, globalAgents) {
184
+ const lines = [
185
+ '这是一个从上一个对话接续的新对话。请先读取下面这些文件,了解当前状态,再开始工作:',
186
+ '1. ' + (globalAgents || '~/.dsh/AGENTS.md'),
187
+ ]
188
+ if (cwd) {
189
+ lines.push('2. ' + cwd.replace(/[\\/]+$/, '') + '/AGENTS.md')
190
+ lines.push('3. ' + cwd.replace(/[\\/]+$/, '') + '/Config/AGENTS.md')
191
+ lines.push('4. ' + cwd.replace(/[\\/]+$/, '') + '/Config/MEMORY/MEMORY.md')
192
+ }
193
+ lines.push('')
194
+ lines.push('交接文件(上一个对话的工作总结):')
195
+ lines.push(filePath)
196
+ lines.push('')
197
+ lines.push('读完后用两三句话概括你理解的当前状态和下一步,然后等我的指令。')
198
+ return lines.join('\n')
199
+ }
200
+
201
+ /**
202
+ * 执行一次交接请求。
203
+ * kind === 'file' 只让模型写交接文件;
204
+ * kind === 'full' 写完之后新建「原名 #N」对话,并在新对话草稿里预填读取清单。
205
+ */
206
+ async function runHandoff(ctx, sessionId, kind) {
207
+ const sessions = ctx.get('sessions')
208
+ const ui = ctx.get('uiWorkspace')
209
+ const title = readTitle(ctx, sessionId)
210
+ let cwd = ''
211
+ try {
212
+ const row = sessions.list.getSnapshot().byId[sessionId]
213
+ cwd = (row && row.cwd) || ''
214
+ } catch {
215
+ cwd = ''
216
+ }
217
+
218
+ const dir = (cwd ? cwd.replace(/[\\/]+$/, '') + '/' : '') + 'Handoff'
219
+ const filePath = dir + '/handoff-' + formatStamp(new Date()) + '.md'
220
+
221
+ await withBinding(ctx, sessionId, async (binding) => {
222
+ await binding.session.prompt([{ type: 'text', text: buildWritePrompt(filePath) }], 'queue')
223
+ })
224
+
225
+ if (kind !== 'full') return
226
+
227
+ await waitIdle(ctx, sessionId, 300000)
228
+
229
+ const before = new Set(sessions.list.getSnapshot().ids || [])
230
+ ui.startSession(undefined, {
231
+ prompt: buildBootstrapPrompt(filePath, cwd, globalPaths.globalAgents),
232
+ whenDraftExists: 'replace',
233
+ })
234
+
235
+ const newId = await waitNewSession(ctx, before, 10000)
236
+ if (!newId) return
237
+
238
+ const wanted = nextTitle(title)
239
+ try {
240
+ await withBinding(ctx, newId, async (binding) => {
241
+ await binding.session.rename(wanted)
242
+ })
243
+ } catch {
244
+ // 改名失败不影响交接本身
245
+ }
246
+ }
247
+
248
+ function format(n) {
249
+ if (!Number.isFinite(n) || n < 0) return '--'
250
+ const m = n / 1e6
251
+ if (m >= 100) return String(Math.round(m)) + 'M'
252
+ if (m >= 10) return (Math.round(m * 10) / 10).toFixed(1).replace(/\.0$/, '') + 'M'
253
+ if (m >= 1) return m.toFixed(1) + 'M'
254
+ if (n >= 1e3) return Math.round(n / 1e3) + 'K'
255
+ return String(Math.round(n))
256
+ }
257
+
258
+ /** 进度条本体与数字共用的颜色。 */
259
+ function bodyColor(pct) {
260
+ if (pct >= 80) return '#e5534b'
261
+ if (pct >= 60) return '#e6a700'
262
+ if (pct >= 40) return '#ffffff'
263
+ return '#3fb950'
264
+ }
265
+
266
+ const SOURCE_LABEL = {
267
+ 'cost-meter-ledger': 'cost-meter 账本',
268
+ 'billion-context': 'billion-context 实时统计',
269
+ }
270
+
271
+ function Meter(props) {
272
+ const sessionId = props.sessionId
273
+ const [state, setState] = React.useState({ status: 'loading', data: null, meta: null })
274
+
275
+ React.useEffect(() => {
276
+ let alive = true
277
+ let timer = 0
278
+
279
+ async function load() {
280
+ if (!sessionId) {
281
+ if (alive) setState({ status: 'nodata', data: null, meta: { reason: 'no-session-id' } })
282
+ return
283
+ }
284
+ try {
285
+ const url = ROUTE + '?sessionId=' + encodeURIComponent(sessionId)
286
+ const res = await fetch(url, { cache: 'no-store', headers: { accept: 'application/json' } })
287
+ const body = await res.json()
288
+ if (!alive) return
289
+ if (body && body.ok && body.session) {
290
+ setState({ status: 'ok', data: body.session, meta: body })
291
+ } else if (body && body.ok === false) {
292
+ setState({ status: 'unavailable', data: null, meta: body })
293
+ } else {
294
+ setState({ status: 'nodata', data: null, meta: body })
295
+ }
296
+ } catch {
297
+ if (alive) setState({ status: 'unavailable', data: null, meta: { error: '网络请求失败' } })
298
+ }
299
+ }
300
+
301
+ load()
302
+ timer = window.setInterval(load, POLL_MS)
303
+ return () => {
304
+ alive = false
305
+ window.clearInterval(timer)
306
+ }
307
+ }, [sessionId])
308
+
309
+ // 交接请求轮询:/handoff 或 /handoff-file 在 host 端登记后由这里执行。
310
+ React.useEffect(() => {
311
+ if (!sessionId || !runtimeCtx) return undefined
312
+ let alive = true
313
+ let busy = false
314
+
315
+ async function tick() {
316
+ if (!alive || busy) return
317
+ try {
318
+ const res = await fetch(
319
+ HANDOFF_ROUTE + '?sessionId=' + encodeURIComponent(sessionId),
320
+ { cache: 'no-store', headers: { accept: 'application/json' } },
321
+ )
322
+ const body = await res.json()
323
+ if (!alive || !body || !body.ok) return
324
+ const list = Array.isArray(body.requests) ? body.requests : []
325
+ for (const req of list) {
326
+ if (!alive) return
327
+ busy = true
328
+ try {
329
+ await runHandoff(runtimeCtx, sessionId, req.kind)
330
+ } catch (err) {
331
+ // 交接失败不打断进度条
332
+ console.warn('[context-meter] handoff failed', err)
333
+ } finally {
334
+ busy = false
335
+ }
336
+ }
337
+ } catch {
338
+ // 轮询失败静默
339
+ }
340
+ }
341
+
342
+ const timer = window.setInterval(tick, HANDOFF_POLL_MS)
343
+ return () => {
344
+ alive = false
345
+ window.clearInterval(timer)
346
+ }
347
+ }, [sessionId])
348
+
349
+ const data = state.data
350
+ if (state.status !== 'ok' || !data) {
351
+ const reasons = {
352
+ 'no-session-id': '拿不到本会话 id',
353
+ unavailable: '统计来源不可用(billion-context 未运行,cost-meter 账本不可读)',
354
+ nodata: '两个来源都还没有这个会话的用量记录',
355
+ }
356
+ const tip =
357
+ '累计输入统计暂不可用:' +
358
+ (reasons[state.status] || reasons.nodata) +
359
+ (state.meta && state.meta.error ? '\n' + state.meta.error : '') +
360
+ '\n新对话在跑完第一轮之前没有记录,属正常。'
361
+ return h(
362
+ 'span',
363
+ { className: '__cm-host' },
364
+ h(
365
+ 'span',
366
+ { className: '__cm-pill __cm-idle', title: tip },
367
+ h('span', { className: '__cm-label' }, '累计计费输入Tokens'),
368
+ h('span', { className: '__cm-track' }),
369
+ h('span', { className: '__cm-num' }, '-- / 500M'),
370
+ ),
371
+ )
372
+ }
373
+
374
+ const input = Number(data.inputTokens) || 0
375
+ const pctRaw = LIMIT > 0 ? (input / LIMIT) * 100 : 0
376
+ const pct = Math.max(0, Math.min(100, pctRaw))
377
+ const color = bodyColor(pct)
378
+ const ctx = Number(data.contextTokens) || 0
379
+ const win = Number(data.contextWindow) || 0
380
+ const ctxPct = win > 0 ? ((ctx / win) * 100).toFixed(0) : '--'
381
+ const sources = (data.source || '')
382
+ .split('+')
383
+ .filter(Boolean)
384
+ .map((s) => SOURCE_LABEL[s] || s)
385
+ .join(' + ')
386
+
387
+ const tip = [
388
+ '累计计费输入:' + input.toLocaleString('en-US') + ' tokens(' + pctRaw.toFixed(1) + '% / 500M)',
389
+ win > 0
390
+ ? '上下文窗口占用:' + format(ctx) + ' / ' + format(win) + '(' + ctxPct + '%)'
391
+ : '上下文窗口占用:本来源不提供',
392
+ '本会话请求:' + (data.requests ?? 0) + ' 轮 · 折叠块:' + (data.blocks ?? 0),
393
+ input >= DANGER_TOKENS
394
+ ? '已达 500M:对话质量可能继续下降,建议把结论写进文件、新开对话续做。'
395
+ : input >= WARN_TOKENS
396
+ ? '已达 400M 预警点:每轮在回复开头报用量,每再涨 50M 报一次。'
397
+ : '',
398
+ '数据源:' + (sources || '未知') + '(每 ' + POLL_MS / 1000 + ' 秒刷新)',
399
+ ]
400
+ .filter(Boolean)
401
+ .join('\n')
402
+
403
+ return h(
404
+ 'span',
405
+ { className: '__cm-host' },
406
+ h(
407
+ 'span',
408
+ { className: '__cm-pill', title: tip },
409
+ h('span', { className: '__cm-label' }, '累计计费输入Tokens'),
410
+ h(
411
+ 'span',
412
+ { className: '__cm-track' },
413
+ h('span', { className: '__cm-zone __cm-zone-warn' }),
414
+ h('span', { className: '__cm-zone __cm-zone-danger' }),
415
+ h('span', { className: '__cm-fill', style: { width: pct + '%', backgroundColor: color } }),
416
+ ),
417
+ h('span', { className: '__cm-num', style: { color } }, format(input) + ' / 500M'),
418
+ h('span', { className: '__cm-sep', style: { color } }, '·'),
419
+ h('span', { className: '__cm-num', style: { color } }, pctRaw.toFixed(1) + '%'),
420
+ ),
421
+ )
422
+ }
423
+
424
+ // ---------------------------------------------------------------
425
+ // 左侧栏会话标题着色
426
+ //
427
+ // 按上下文窗口占用率给左侧会话列表的标题上色:
428
+ // 0–60% 保持原色
429
+ // 60–80% 黄
430
+ // 80%+ 红(含 100% 以上)
431
+ //
432
+ // 侧栏没有可替换「标题」的槽位,只能在 sidebar.session.row.leading
433
+ // 挂一个 display:none 的探针,再沿 DOM 向上找到行容器、给标题碎片
434
+ // 设内联 color(带 !important)。占用率回落时把 color 还原。
435
+ // ---------------------------------------------------------------
436
+
437
+ const SIDEBAR_SLOT = 'sidebar.session.row.leading'
438
+ const SIDEBAR_POLL_MS = 2500
439
+ const SIDEBAR_STORE_MS = 6000
440
+ const DEBUG_ROUTE = '/context-meter/debug'
441
+ const CONTEXTS_ROUTE = '/context-meter/contexts'
442
+
443
+ const TINT_ROUTE = '/context-meter/tint'
444
+ const TINT_POLL_MS = 5000
445
+
446
+ /** 「标记停用」状态:只是视觉标记,不碰会话内容。 */
447
+ const DISABLED_ROUTE = '/context-meter/disabled'
448
+ const DISABLED_POLL_MS = 5000
449
+ const ROW_ACTION_SLOT = 'sidebar.workspaces.session.row.action'
450
+
451
+ /** normalize 后的会话 id 集合;按钮与行着色共用。 */
452
+ const disabledSet = new Set()
453
+
454
+ /** 标记变化后通知所有按钮重渲染(同一会话可能有多个渲染实例)。 */
455
+ const disabledListeners = new Set()
456
+
457
+ function notifyDisabled() {
458
+ for (const fn of disabledListeners) {
459
+ try {
460
+ fn()
461
+ } catch {
462
+ // 单个监听器异常不影响其它
463
+ }
464
+ }
465
+ }
466
+
467
+ async function toggleDisabled(sid) {
468
+ if (!sid) return
469
+ const next = !disabledSet.has(sid)
470
+ if (next) disabledSet.add(sid)
471
+ else disabledSet.delete(sid)
472
+ notifyDisabled()
473
+ try {
474
+ const res = await fetch(DISABLED_ROUTE, {
475
+ method: 'POST',
476
+ headers: { 'content-type': 'application/json' },
477
+ body: JSON.stringify({ id: sid, disabled: next }),
478
+ })
479
+ const body = await res.json()
480
+ if (body && body.ok && Array.isArray(body.ids)) {
481
+ disabledSet.clear()
482
+ for (const id of body.ids) disabledSet.add(normId(id))
483
+ notifyDisabled()
484
+ }
485
+ } catch {
486
+ // 写失败就保留本地状态,下一次轮询会以 host 为准
487
+ }
488
+ }
489
+
490
+ /**
491
+ * 阈值配置。默认就是需求里的 60% / 80%;
492
+ * 想临时验证效果可以改项目目录的 tint.json(例如降到 10 / 20),
493
+ * 5 秒内就会生效,不需要重启 DSH。
494
+ */
495
+ const tintConfig = { warn: 60, danger: 80, window: LIMIT }
496
+ const COLOR_WARN = '#e6a700'
497
+ const COLOR_DANGER = '#e5534b'
498
+
499
+ /** 全量会话用量缓存:normalize 后的 id -> 会话摘要。 */
500
+ const sidebarStore = { byId: {}, at: 0 }
501
+
502
+ /** 会话文件算出来的上下文占用:normalize 后的 id -> {used, window, pct}。 */
503
+ const contextStore = { byId: {} }
504
+
505
+ /** 需要向 host 拉取上下文占用的会话 id。 */
506
+ const pendingIds = new Set()
507
+
508
+ /** 统一 id:去掉 billion-context 的 session- 前缀并小写。 */
509
+ const normId = (id) => String(id || '').trim().toLowerCase().replace(/^session-/, '')
510
+
511
+ function lookupSession(id) {
512
+ const key = normId(id)
513
+ return key ? sidebarStore.byId[key] || null : null
514
+ }
515
+
516
+ /** 上过色的元素 -> 原始内联 color(空串表示原本没有内联色)。 */
517
+ const tintedElements = new Map()
518
+
519
+ /** 每个会话的行着色结果只上报一次,避免刷爆 debug.log。 */
520
+ const tintDebugged = new Set()
521
+
522
+ function sendDebug(payload) {
523
+ try {
524
+ fetch(DEBUG_ROUTE, {
525
+ method: 'POST',
526
+ headers: { 'content-type': 'application/json' },
527
+ body: JSON.stringify(payload),
528
+ }).catch(() => {})
529
+ } catch {
530
+ // 调试上报失败静默
531
+ }
532
+ }
533
+
534
+ let rowProbed = false
535
+
536
+ /** 首次挂载时把 DOM 祖先链上报一次,便于在没有 devtools 时定位结构。 */
537
+ function probeRow(el, sid, props) {
538
+ if (rowProbed || !el) return
539
+ rowProbed = true
540
+ const chain = []
541
+ let node = el
542
+ for (let i = 0; i < 10 && node; i += 1) {
543
+ chain.push({
544
+ i,
545
+ tag: node.tagName,
546
+ cls: String(node.className || '').slice(0, 100),
547
+ kids: node.childElementCount,
548
+ text: String(node.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 48),
549
+ })
550
+ node = node.parentElement
551
+ }
552
+ sendDebug({
553
+ kind: 'row-probe',
554
+ sid: sid || '',
555
+ propKeys: Object.keys(props || {}),
556
+ chain,
557
+ })
558
+ }
559
+
560
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-/i
561
+
562
+ /** 从槽位 props 里取 sessionId。 */
563
+ function sidOf(props) {
564
+ if (!props) return ''
565
+ const cands = [
566
+ props.sessionId,
567
+ props.session && props.session.sessionId,
568
+ props.session && props.session.id,
569
+ props.row && props.row.sessionId,
570
+ props.item && props.item.sessionId,
571
+ props.id,
572
+ ]
573
+ for (const c of cands) {
574
+ if (typeof c === 'string' && UUID_RE.test(normId(c))) return normId(c)
575
+ }
576
+ return ''
577
+ }
578
+
579
+ /** 兜底:从 React fiber 的 props 上取 sessionId。 */
580
+ function sidFromDom(el) {
581
+ let node = el
582
+ for (let i = 0; i < 8 && node; i += 1) {
583
+ const keys = Object.keys(node).filter((k) => k.indexOf('__reactProps$') === 0)
584
+ for (const k of keys) {
585
+ const p = node[k]
586
+ if (!p || typeof p !== 'object') continue
587
+ const cands = [p.sessionId, p.session && p.session.sessionId, p.session && p.session.id]
588
+ for (const c of cands) {
589
+ if (typeof c === 'string' && UUID_RE.test(normId(c))) return normId(c)
590
+ }
591
+ }
592
+ node = node.parentElement
593
+ }
594
+ return ''
595
+ }
596
+
597
+ /** 最后兜底:用行文本在已缓存的会话标题里找最长匹配。 */
598
+ function sidByRowText(text) {
599
+ const raw = String(text || '')
600
+ if (!raw) return ''
601
+ let best = ''
602
+ let bestLen = 0
603
+ for (const key of Object.keys(sidebarStore.byId)) {
604
+ const title = sidebarStore.byId[key].title
605
+ if (typeof title !== 'string' || title.length < 3) continue
606
+ if (raw.indexOf(title) < 0) continue
607
+ if (title.length > bestLen) {
608
+ best = key
609
+ bestLen = title.length
610
+ }
611
+ }
612
+ return best
613
+ }
614
+
615
+ function clearUnder(root) {
616
+ for (const [el, prev] of tintedElements) {
617
+ // DOM 被 React 重建成新节点后,旧引用直接丢弃,避免无限增长
618
+ if (!el.isConnected) {
619
+ tintedElements.delete(el)
620
+ continue
621
+ }
622
+ if (!root.contains(el)) continue
623
+ if (prev) el.style.setProperty('color', prev)
624
+ else el.style.removeProperty('color')
625
+ tintedElements.delete(el)
626
+ }
627
+ }
628
+
629
+ function setTint(el, color) {
630
+ if (!tintedElements.has(el)) tintedElements.set(el, el.style.color || '')
631
+ el.style.setProperty('color', color, 'important')
632
+ }
633
+
634
+ // ---- 「标记停用」的删除线 ----------------------------------------
635
+ //
636
+ // 需求:标题整条加删除线,但结尾的 "#N" 编号不划、只跟着变灰。
637
+ // 不改 React 管理的文本节点结构(宿主重渲染会打乱 fiber),
638
+ // 改用 background 渐变画线,再用 calc(100% - Npx) 把编号那截收回来,
639
+ // N 由 canvas 按标题元素的实际字体量出来。
640
+
641
+ /** 画过删除线/压暗的元素 -> 需要还原的 style 属性名。 */
642
+ const struckElements = new Map()
643
+
644
+ /** 把改过的属性名记到元素上,取消停用时逐个还原。 */
645
+ function recordStyle(el, props) {
646
+ const prev = struckElements.get(el)
647
+ if (!prev) {
648
+ struckElements.set(el, props.slice())
649
+ return
650
+ }
651
+ const merged = prev.slice()
652
+ for (const p of props) {
653
+ if (merged.indexOf(p) < 0) merged.push(p)
654
+ }
655
+ struckElements.set(el, merged)
656
+ }
657
+
658
+ /**
659
+ * 停用状态的「压暗」:直接把颜色乘一个系数,而不是用 filter。
660
+ * 用 color 是为了让编号那一截可以完全不压暗——filter 会作用整个元素。
661
+ */
662
+ function darkenRgb(color, factor) {
663
+ const m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(color || ''))
664
+ if (!m) return null
665
+ const to = (v) => Math.max(0, Math.min(255, Math.round(Number(v) * factor)))
666
+ return 'rgb(' + to(m[1]) + ',' + to(m[2]) + ',' + to(m[3]) + ')'
667
+ }
668
+
669
+ function dimNow(el) {
670
+ const dim = darkenRgb(window.getComputedStyle(el).color, 0.62)
671
+ if (dim) setTint(el, dim)
672
+ }
673
+
674
+ // ---- 编号 "#N" 保持原样 ------------------------------------------
675
+ //
676
+ // 需求:停用时正文压暗 + 加删除线,但结尾的 "#N" 保持原色、不划线。
677
+ // 正文和编号原本在同一个文本节点里,没法分别设样式,所以在停用期间
678
+ // 把标题临时拆成两个 span:.__cm-body(正文)和 .__cm-idx(编号)。
679
+ // 取消停用时再合并回一个文本节点。
680
+ // 这层 DOM 改动每轮都会自愈:React 重建标题后,下一个 tick 重新拆。
681
+
682
+ const IDX_CLASS = '__cm-idx'
683
+ const BODY_CLASS = '__cm-body'
684
+
685
+ function unsplitTitles(root) {
686
+ const nodes = root.querySelectorAll('.' + IDX_CLASS)
687
+ for (const idx of nodes) {
688
+ const parent = idx.parentElement
689
+ if (!parent) continue
690
+ parent.textContent = parent.textContent || ''
691
+ }
692
+ }
693
+
694
+ /** 把 "xxx #1" 拆成两个 span;不含编号则返回 null。 */
695
+ function splitTitle(el) {
696
+ try {
697
+ const text = el.textContent || ''
698
+ const m = /^(.*?)(\s*#\d+)\s*$/.exec(text)
699
+ if (!m || !String(m[1] || '').trim()) return null
700
+
701
+ el.textContent = ''
702
+ const body = document.createElement('span')
703
+ body.className = BODY_CLASS
704
+ body.textContent = m[1]
705
+ const idx = document.createElement('span')
706
+ idx.className = IDX_CLASS
707
+ idx.textContent = m[2]
708
+ el.appendChild(body)
709
+ el.appendChild(idx)
710
+ return { body, idx }
711
+ } catch {
712
+ return null
713
+ }
714
+ }
715
+
716
+ function strike(el) {
717
+ el.style.setProperty('text-decoration', 'line-through', 'important')
718
+ recordStyle(el, ['text-decoration'])
719
+ }
720
+
721
+ function clearStrikesUnder(root) {
722
+ for (const [el, props] of struckElements) {
723
+ if (!el.isConnected) {
724
+ struckElements.delete(el)
725
+ continue
726
+ }
727
+ if (!root.contains(el)) continue
728
+ for (const p of props) el.style.removeProperty(p)
729
+ struckElements.delete(el)
730
+ }
731
+ }
732
+
733
+ /** 行内的相对时间/状态文本,不上色。 */
734
+ const TIME_RE = /^\d+\s*(秒|分钟|小时|天|周|个月|年)$|^(刚刚|今天|昨天|前天)$/
735
+
736
+ /** 从探针向上找会话行容器:debug.log 的 row-probe 记录显示 class 里带 sessionRow。 */
737
+ function rowRoot(el) {
738
+ if (el && typeof el.closest === 'function') {
739
+ const direct = el.closest('[class*="sessionRow"]')
740
+ if (direct) return direct
741
+ }
742
+ let node = el
743
+ for (let i = 0; i < 8 && node; i += 1) {
744
+ if (node.nodeType === 1 && /sessionRow/.test(String(node.className || ''))) return node
745
+ node = node.parentElement
746
+ }
747
+ return null
748
+ }
749
+
750
+ /**
751
+ * 给一行会话标题上色。
752
+ * 每轮都先把本行还原成原色再按需重画,避免「一次上色后再也清不掉」的残留。
753
+ */
754
+ function paintRow(el, title, pct, disabled) {
755
+ if (!el) return null
756
+
757
+ let target = rowRoot(el)
758
+ if (!target) {
759
+ const needle = String(title || '').trim()
760
+ if (!needle) return null
761
+ let node = el
762
+ for (let i = 0; i < 10 && node; i += 1) {
763
+ if (String(node.textContent || '').indexOf(needle) >= 0) {
764
+ if (node.querySelectorAll('*').length > 80) return null
765
+ target = node
766
+ break
767
+ }
768
+ node = node.parentElement
769
+ }
770
+ }
771
+ if (!target) return null
772
+
773
+ // 先还原本行所有曾上色的元素,保证是「从干净状态重画」
774
+ // 拆过的标题也先合并回去,避免每轮重复拆
775
+ unsplitTitles(target)
776
+ clearUnder(target)
777
+ clearStrikesUnder(target)
778
+
779
+ // 停用状态:正文压暗 + 删除线;编号 "#N" 保持原色、不压暗、不划线。
780
+ if (disabled) {
781
+ const offHits = []
782
+ for (const item of target.querySelectorAll('*')) {
783
+ if (item.childElementCount > 0) continue
784
+ const text = String(item.textContent || '').trim()
785
+ if (!text) continue
786
+ if (TIME_RE.test(text)) continue
787
+ offHits.push(item)
788
+ }
789
+ const baseColor =
790
+ pct >= tintConfig.danger ? COLOR_DANGER : pct >= tintConfig.warn ? COLOR_WARN : ''
791
+ for (const item of offHits) {
792
+ const parts = splitTitle(item)
793
+ if (parts) {
794
+ if (baseColor) setTint(parts.body, baseColor)
795
+ dimNow(parts.body)
796
+ strike(parts.body)
797
+ // 编号保持原样
798
+ if (baseColor) setTint(parts.idx, baseColor)
799
+ } else {
800
+ if (baseColor) setTint(item, baseColor)
801
+ dimNow(item)
802
+ strike(item)
803
+ }
804
+ }
805
+ return { pct, hits: offHits.length, disabled: true, color: baseColor || 'inherit' }
806
+ }
807
+
808
+ if (!(pct >= tintConfig.warn)) {
809
+ return { pct, hits: 0, cleared: true }
810
+ }
811
+
812
+ const color = pct >= tintConfig.danger ? COLOR_DANGER : COLOR_WARN
813
+ const hits = []
814
+ for (const item of target.querySelectorAll('*')) {
815
+ if (item.childElementCount > 0) continue
816
+ const text = String(item.textContent || '').trim()
817
+ if (!text) continue
818
+ if (TIME_RE.test(text)) continue
819
+ hits.push(item)
820
+ }
821
+
822
+ for (const item of hits) setTint(item, color)
823
+ return { pct, hits: hits.length, color, kids: target.querySelectorAll('*').length }
824
+ }
825
+
826
+ function RowTint(props) {
827
+ const ref = React.useRef(null)
828
+ const latest = React.useRef(props)
829
+ const tickRef = React.useRef(null)
830
+ latest.current = props
831
+ const sidProp = sidOf(props)
832
+
833
+ // 停用标记一变就立刻重画,不必等下一个 2.5 秒轮询。
834
+ React.useEffect(() => {
835
+ const bump = () => {
836
+ if (tickRef.current) tickRef.current()
837
+ }
838
+ disabledListeners.add(bump)
839
+ return () => {
840
+ disabledListeners.delete(bump)
841
+ }
842
+ }, [])
843
+
844
+ React.useEffect(() => {
845
+ let alive = true
846
+
847
+ const tick = () => {
848
+ if (!alive) return
849
+ const el = ref.current
850
+ if (!el) return
851
+
852
+ let sid = sidOf(latest.current) || sidProp
853
+ if (!sid) sid = sidFromDom(el)
854
+ if (!sid) {
855
+ let node = el
856
+ for (let i = 0; i < 4 && node; i += 1) {
857
+ const text = String(node.textContent || '').replace(/\s+/g, ' ').trim()
858
+ if (text && text.length < 160) {
859
+ const guess = sidByRowText(text)
860
+ if (guess) {
861
+ sid = guess
862
+ break
863
+ }
864
+ }
865
+ node = node.parentElement
866
+ }
867
+ }
868
+
869
+ probeRow(el, sid, latest.current)
870
+ if (!sid) return
871
+
872
+ // 与顶部进度条同一口径:累计计费输入 / 上限(默认 500M)。
873
+ // 不是模型窗口占用率——窗口占用普遍只有 15%~50%,永远到不了 60%。
874
+ const entry = lookupSession(sid)
875
+ const used = entry ? Number(entry.inputTokens) || 0 : 0
876
+ const win = tintConfig.window > 0 ? tintConfig.window : LIMIT
877
+ const pct = win > 0 ? (used / win) * 100 : 0
878
+ const title = (entry && entry.title) || readTitle(runtimeCtx, sid) || ''
879
+ const result = paintRow(el, title, pct, disabledSet.has(sid))
880
+
881
+ if (!tintDebugged.has(sid)) {
882
+ tintDebugged.add(sid)
883
+ sendDebug({
884
+ kind: 'tint',
885
+ sid,
886
+ title,
887
+ used,
888
+ window: win,
889
+ pct: Math.round(pct * 10) / 10,
890
+ warn: tintConfig.warn,
891
+ danger: tintConfig.danger,
892
+ result: result || null,
893
+ })
894
+ }
895
+ }
896
+
897
+ tick()
898
+ tickRef.current = tick
899
+ const timer = window.setInterval(tick, SIDEBAR_POLL_MS)
900
+ return () => {
901
+ alive = false
902
+ window.clearInterval(timer)
903
+ }
904
+ }, [sidProp])
905
+
906
+ return h('span', { ref, style: { display: 'none' }, 'aria-hidden': 'true' })
907
+ }
908
+
909
+ /**
910
+ * 会话行尾的「∅」按钮:切换该对话的「标记停用」状态。
911
+ * 只改视觉,不碰会话内容。
912
+ */
913
+ function DisableToggle(props) {
914
+ const ref = React.useRef(null)
915
+ const probedRef = React.useRef(false)
916
+ const [, force] = React.useReducer((n) => n + 1, 0)
917
+ const [fallbackSid, setFallbackSid] = React.useState('')
918
+
919
+ React.useEffect(() => {
920
+ disabledListeners.add(force)
921
+ return () => {
922
+ disabledListeners.delete(force)
923
+ }
924
+ }, [])
925
+
926
+ const sid = sidOf(props) || fallbackSid
927
+
928
+ React.useEffect(() => {
929
+ if (sid) return
930
+ const el = ref.current
931
+ if (!el) return
932
+ const guess = sidFromDom(el)
933
+ if (guess) setFallbackSid(guess)
934
+ })
935
+
936
+ // 首次挂载上报一次行尾按钮区的结构,便于确认「…」和本按钮的相对位置。
937
+ React.useEffect(() => {
938
+ if (probedRef.current) return
939
+ const el = ref.current
940
+ if (!el || !el.parentElement) return
941
+ probedRef.current = true
942
+ const parent = el.parentElement
943
+ sendDebug({
944
+ kind: 'action-probe',
945
+ parent: {
946
+ tag: parent.tagName,
947
+ cls: String(parent.className || '').slice(0, 120),
948
+ kids: parent.childElementCount,
949
+ },
950
+ siblings: Array.from(parent.children).map((c) => ({
951
+ tag: c.tagName,
952
+ cls: String(c.className || '').slice(0, 90),
953
+ text: String(c.textContent || '').trim().slice(0, 16),
954
+ title: String((c.getAttribute && c.getAttribute('title')) || '').slice(0, 16),
955
+ self: c === el,
956
+ })),
957
+ })
958
+ }, [])
959
+
960
+ if (!sid) return h('span', { ref, style: { display: 'none' }, 'aria-hidden': 'true' })
961
+
962
+ const on = disabledSet.has(sid)
963
+ const label = on ? '取消停用' : '标记停用'
964
+ return h(
965
+ 'button',
966
+ {
967
+ ref,
968
+ type: 'button',
969
+ className: '__cm-off' + (on ? ' __cm-off-on' : ''),
970
+ title: label,
971
+ 'aria-label': label,
972
+ 'aria-pressed': on ? 'true' : 'false',
973
+ 'data-cm-off': sid,
974
+ onClick: (e) => {
975
+ e.preventDefault()
976
+ e.stopPropagation()
977
+ toggleDisabled(sid)
978
+ },
979
+ },
980
+ // 「禁止」符号:圆圈 + 斜杠,和 ∅ 同一个意思但画得更大更清楚。
981
+ h(
982
+ 'svg',
983
+ {
984
+ viewBox: '0 0 16 16',
985
+ fill: 'none',
986
+ stroke: 'currentColor',
987
+ strokeWidth: 1.7,
988
+ strokeLinecap: 'round',
989
+ 'aria-hidden': 'true',
990
+ focusable: 'false',
991
+ },
992
+ h('circle', { cx: 8, cy: 8, r: 6.1 }),
993
+ h('line', { x1: 3.7, y1: 12.3, x2: 12.3, y2: 3.7 }),
994
+ ),
995
+ )
996
+ }
997
+
998
+ // 测试钩子:让冒烟脚本能直接验证标题递增规则。
999
+ Meter.nextTitle = nextTitle
1000
+ RowTint.derive = { sidOf, normId, paintRow }
1001
+ DisableToggle.derive = { sidOf, toggleDisabled, disabledSet }
1002
+
1003
+ return {
1004
+ inject: ['slots'],
1005
+ apply(ctx) {
1006
+ runtimeCtx = ctx
1007
+ ctx.effect(() => {
1008
+ const el = document.createElement('style')
1009
+ el.setAttribute('data-context-meter', '')
1010
+ el.textContent = CSS
1011
+ document.head.appendChild(el)
1012
+ return () => el.remove()
1013
+ }, 'context-meter: styles')
1014
+
1015
+ // order 2:紧跟 cost-meter-statistics(1) 之后、subagent-catalog(10) 之前,
1016
+ // 即「费用明细」右侧、「x 个子智能体」左侧。
1017
+ ctx.slots.inject('conversation.session.header.actions', () =>
1018
+ ctx.slots.register(
1019
+ { name: 'conversation.session.header.actions', id: 'context-meter', order: 2 },
1020
+ Meter,
1021
+ ),
1022
+ )
1023
+
1024
+ // 左侧栏标题着色需要全量会话的窗口占用率,单独维护一份缓存。
1025
+ ctx.effect(() => {
1026
+ let alive = true
1027
+ const refresh = async () => {
1028
+ try {
1029
+ const res = await fetch(ROUTE, {
1030
+ cache: 'no-store',
1031
+ headers: { accept: 'application/json' },
1032
+ })
1033
+ const body = await res.json()
1034
+ if (!alive || !body || !Array.isArray(body.sessions)) return
1035
+ if (body.paths && body.paths.globalAgents) globalPaths.globalAgents = body.paths.globalAgents
1036
+ const byId = {}
1037
+ for (const item of body.sessions) {
1038
+ if (!item || !item.id) continue
1039
+ byId[normId(item.id)] = item
1040
+ }
1041
+ sidebarStore.byId = byId
1042
+ sidebarStore.at = Date.now()
1043
+ } catch {
1044
+ // 刷新失败保留旧缓存
1045
+ }
1046
+ }
1047
+ refresh()
1048
+ const timer = window.setInterval(refresh, SIDEBAR_STORE_MS)
1049
+ return () => {
1050
+ alive = false
1051
+ window.clearInterval(timer)
1052
+ }
1053
+ }, 'context-meter: sidebar stats')
1054
+
1055
+ // 阈值配置:改项目目录的 tint.json 即可热调,不必重启 DSH。
1056
+ ctx.effect(() => {
1057
+ let alive = true
1058
+ const refresh = async () => {
1059
+ try {
1060
+ const res = await fetch(TINT_ROUTE, {
1061
+ cache: 'no-store',
1062
+ headers: { accept: 'application/json' },
1063
+ })
1064
+ const body = await res.json()
1065
+ if (!alive || !body || !body.ok) return
1066
+ if (Number.isFinite(Number(body.warn))) tintConfig.warn = Number(body.warn)
1067
+ if (Number.isFinite(Number(body.danger))) tintConfig.danger = Number(body.danger)
1068
+ if (Number.isFinite(Number(body.window)) && Number(body.window) > 0) {
1069
+ tintConfig.window = Number(body.window)
1070
+ }
1071
+ } catch {
1072
+ // 拉不到就沿用当前阈值
1073
+ }
1074
+ }
1075
+ refresh()
1076
+ const timer = window.setInterval(refresh, TINT_POLL_MS)
1077
+ return () => {
1078
+ alive = false
1079
+ window.clearInterval(timer)
1080
+ }
1081
+ }, 'context-meter: tint config')
1082
+
1083
+ ctx.slots.inject(SIDEBAR_SLOT, () =>
1084
+ ctx.slots.register(
1085
+ { name: SIDEBAR_SLOT, id: 'context-meter-sidebar', order: 999 },
1086
+ RowTint,
1087
+ ),
1088
+ )
1089
+
1090
+ // 行尾的「∅ 标记停用」按钮。该槽位的按钮渲染在「…」之后,
1091
+ // 用 CSS 负向偏移把它挪到「…」左侧。
1092
+ ctx.slots.inject(ROW_ACTION_SLOT, () =>
1093
+ ctx.slots.register(
1094
+ { name: ROW_ACTION_SLOT, id: 'context-meter-disable', order: -100 },
1095
+ DisableToggle,
1096
+ ),
1097
+ )
1098
+
1099
+ // 停用标记:启动拉一次,之后定时同步(host 侧 /handoff 也会写)。
1100
+ ctx.effect(() => {
1101
+ let alive = true
1102
+ const refresh = async () => {
1103
+ try {
1104
+ const res = await fetch(DISABLED_ROUTE, {
1105
+ cache: 'no-store',
1106
+ headers: { accept: 'application/json' },
1107
+ })
1108
+ const body = await res.json()
1109
+ if (!alive || !body || !body.ok || !Array.isArray(body.ids)) return
1110
+ disabledSet.clear()
1111
+ for (const id of body.ids) disabledSet.add(normId(id))
1112
+ notifyDisabled()
1113
+ } catch {
1114
+ // 拉不到就保留当前状态
1115
+ }
1116
+ }
1117
+ refresh()
1118
+ const timer = window.setInterval(refresh, DISABLED_POLL_MS)
1119
+ return () => {
1120
+ alive = false
1121
+ window.clearInterval(timer)
1122
+ }
1123
+ }, 'context-meter: disabled state')
1124
+
1125
+ // 行组件登记需要的 sessionId,这里统一批量向 host 取上下文占用。
1126
+ ctx.effect(() => {
1127
+ let alive = true
1128
+ const pull = async () => {
1129
+ const ids = [...pendingIds]
1130
+ pendingIds.clear()
1131
+ if (ids.length === 0) return
1132
+ try {
1133
+ const res = await fetch(
1134
+ CONTEXTS_ROUTE + '?ids=' + encodeURIComponent(ids.join(',')),
1135
+ { cache: 'no-store', headers: { accept: 'application/json' } },
1136
+ )
1137
+ const body = await res.json()
1138
+ if (!alive || !body || !body.ok || !body.items) return
1139
+ for (const key of Object.keys(body.items)) {
1140
+ contextStore.byId[key] = body.items[key]
1141
+ }
1142
+ } catch {
1143
+ // 拉取失败保留旧值,下一轮再试
1144
+ }
1145
+ }
1146
+ const timer = window.setInterval(pull, SIDEBAR_POLL_MS)
1147
+ return () => {
1148
+ alive = false
1149
+ window.clearInterval(timer)
1150
+ }
1151
+ }, 'context-meter: sidebar contexts')
1152
+ },
1153
+ }
1154
+ },
1155
+ })