dsh-injection-manager 1.10.4 → 2.0.1

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 (49) hide show
  1. package/CHANGELOG.md +290 -0
  2. package/CONTRIBUTING.md +2 -2
  3. package/README.md +286 -94
  4. package/README.zh.md +238 -97
  5. package/client.js +3325 -295
  6. package/docs/ARCHITECTURE.md +123 -25
  7. package/docs/COMPATIBILITY.md +31 -7
  8. package/docs/DETAIL.md +148 -0
  9. package/docs/DETAIL.zh.md +105 -1
  10. package/docs/FAQ.md +53 -7
  11. package/docs/PERFORMANCE.md +60 -6
  12. package/docs/images/demo.gif +0 -0
  13. package/docs/images/dock.png +0 -0
  14. package/docs/images/panel-dark.png +0 -0
  15. package/docs/images/panel-drawer.png +0 -0
  16. package/docs/images/panel-insights.png +0 -0
  17. package/docs/images/panel-manage-expanded.png +0 -0
  18. package/docs/images/panel-manage.png +0 -0
  19. package/docs/images/panel-settings.png +0 -0
  20. package/docs/images/panel-sidebar.png +0 -0
  21. package/docs/preview.svg +177 -23
  22. package/icon.svg +19 -5
  23. package/index.js +107 -16
  24. package/lib/actions.js +12 -4
  25. package/lib/apply.js +14 -2
  26. package/lib/compaction.js +126 -0
  27. package/lib/content.js +360 -0
  28. package/lib/events.js +216 -0
  29. package/lib/health.js +210 -0
  30. package/lib/pressure.js +146 -0
  31. package/lib/routes.js +355 -9
  32. package/lib/snapshot.js +256 -29
  33. package/lib/stats.js +394 -0
  34. package/lib/text.js +160 -0
  35. package/lib/trend.js +168 -0
  36. package/locale/de.json +251 -6
  37. package/locale/en.json +251 -6
  38. package/locale/es.json +251 -6
  39. package/locale/fr.json +251 -6
  40. package/locale/ja.json +251 -6
  41. package/locale/pt.json +251 -6
  42. package/locale/ru.json +252 -7
  43. package/locale/zh.json +249 -4
  44. package/package.json +16 -3
  45. package/screenshots.json +7 -5
  46. package/docs/images/panel-about.png +0 -0
  47. package/docs/images/panel-budget.png +0 -0
  48. package/docs/images/panel-policy.png +0 -0
  49. package/docs/images/panel-suites.png +0 -0
package/client.js CHANGED
@@ -19,8 +19,20 @@
19
19
  verify: BASE + '/verify',
20
20
  boot: BASE + '/boot',
21
21
  registrations: BASE + '/registrations',
22
+ stats: BASE + '/stats',
23
+ // v2 read-only surfaces. All GET + JSON, same origin; the host owns every
24
+ // number and every byte these return.
25
+ content: BASE + '/content',
26
+ trend: BASE + '/trend',
27
+ events: BASE + '/events',
28
+ health: BASE + '/health',
22
29
  }
23
30
 
31
+ // v2 API version the browser half expects. /summary reports it; a v1 host
32
+ // keeps working with the old surfaces and never sees these requests.
33
+ const API_V2 = 2
34
+ const RESOURCE_TTL = 30000
35
+
24
36
  const CHANNELS = ['sections', 'contexts', 'skills', 'tools', 'instructions']
25
37
  const MANAGED = ['sections', 'contexts', 'skills', 'tools']
26
38
  const COLOR = {
@@ -31,9 +43,21 @@
31
43
  instructions: '#94a3b8',
32
44
  }
33
45
 
46
+ // The window bar answers a different question than the injection bar, so it
47
+ // gets one blue ramp instead of the channel hues: three parts of one request,
48
+ // not five independent channels. The ramp is themed so the deepest step still
49
+ // separates from the track in dark mode.
50
+ const WINDOW_COLOR = {
51
+ system: 'var(--ci-win1)',
52
+ tools: 'var(--ci-win2)',
53
+ messages: 'var(--ci-win3)',
54
+ used: 'var(--ci-win2)',
55
+ free: 'transparent',
56
+ }
57
+
34
58
  // Minimal Chinese fallback so controls still read when /locale fails.
35
59
  const FALLBACK = {
36
- panelLabel: '注入',
60
+ panelLabel: '上下文注入',
37
61
  panelTitle: '上下文注入',
38
62
  pageTitle: '上下文注入管理',
39
63
  subtitle: '新会话的第一轮请求会带上这些内容;开关只影响之后新建的会话',
@@ -100,6 +124,80 @@
100
124
  shareOf: '占首轮注入',
101
125
  applied: '已写入',
102
126
  actionFailed: '操作失败',
127
+ window: '上下文窗口',
128
+ windowHint: '占用率来自宿主自己的测量:下一次请求的预计占用 ÷ 模型窗口。',
129
+ noWindow: '窗口未知',
130
+ noWindowHint: '本会话还没有测量数据;发一条消息后就会出现。',
131
+ windowUsedOf: '{used} / {window}',
132
+ remain: '剩余',
133
+ windowBarLabel: '上下文窗口已用 {pct}%',
134
+ systemPart: '系统',
135
+ toolsPart: '工具',
136
+ messagesPart: '消息',
137
+ windowBreakdownHint: '构成是估算值,含对话历史,不只是首轮注入。',
138
+ compactionLine: '已压缩 {count} 次 · 释放 {saved}',
139
+ compactionHint: '压缩回执只统计本插件装载之后的事件,之前的压缩不在内。',
140
+ compactionFailed: '失败 {count} 次',
141
+ trendLabel: '首轮注入趋势,{min} ~ {max} token',
142
+ requestComposition: '本次请求构成',
143
+ injectionComposition: '首轮注入构成',
144
+ noTrim: '策略未裁剪',
145
+ mixedOff: '部分关闭',
146
+ skillsCallout: '收藏的技能会出现在每一个请求里',
147
+ skillsLine: '{tokens} token · 占首轮 {share}% · 平均每个 {avg} · {providers} 个来源',
148
+ skillsUnit: '个技能',
149
+ skillsManage: '去管理',
150
+ skillsJump: '只看技能通道',
151
+ truncatedHint: '{count} 条描述超过目录长度上限,会被截断',
152
+ heaviestSkill: '最大:{name}({tokens})',
153
+ scopeLabel: '查看范围',
154
+ scopeGlobal: '默认策略',
155
+ scopeGlobalHint: '现在新建一个会话会收到什么',
156
+ scopeSession: '本会话',
157
+ scopeSessionHint: '屏幕上这段对话此刻实际在发什么',
158
+ closedBadge: '已关闭',
159
+ closedRestoreHint: '对新会话已关闭;在这里可以重新打开',
160
+ filterLabel: '按通道筛选',
161
+ activeFilters: '筛选:',
162
+ tabManage: '管理',
163
+ tabStats: '统计',
164
+ tabSettings: '设置',
165
+ statsEmpty: '还没有历史记录。打开面板任意会话都会留下一条;这里汇总所有被测量过的对话。',
166
+ statsSessions: '对话数',
167
+ statsSessionsSub: '本插件测量过',
168
+ statsAvg: '平均首轮',
169
+ statsAvgSub: '每个对话的 token',
170
+ statsSkills: '平均技能',
171
+ statsSkillsSub: '每个对话的 token',
172
+ statsPeak: '最大一次',
173
+ statsSkillsShort: '技能',
174
+ statsPeakShort: '峰值',
175
+ statsWhen: '最近测量',
176
+ statsByDay: '每天的首轮均值',
177
+ statsSessionsTitle: '每一个测量过的对话',
178
+ statsCoverage: '本机 {known} 个对话中,已记录 {recorded} 个',
179
+ statsUnmeasured: '未测量',
180
+ statsSubagent: '子智能体',
181
+ statsBackfilled: '刚补齐 {count} 个历史会话',
182
+ statsCurrent: '当前会话',
183
+ statsHistory: '历史记录',
184
+ // v2 chrome. The full v2 dictionary ships in locale/*.json and arrives with
185
+ // /summary; these few keep degraded states readable when it does not.
186
+ 'v2.tabInsights': '洞察',
187
+ 'v2.tabsLabel': '面板分区',
188
+ 'v2.apiOld': '宿主接口还是 v1:洞察、内容透视、健康检查需要 v2 宿主插件;升级后自动出现。',
189
+ 'v2.openContent': '查看内容',
190
+ 'v2.health': '健康检查',
191
+ 'v2.retry': '重试',
192
+ 'content.close': '关闭',
193
+ 'content.retry': '重试',
194
+ 'content.copy': '复制全文',
195
+ 'content.search': '在内容里搜索',
196
+ 'trend.title': '首轮注入趋势',
197
+ 'trend.empty': '还没有可画的记录。打开一次面板或新建会话后就会留下数据。',
198
+ 'trend.retry': '重试',
199
+ 'v2.eventsTitle': '本会话事件时间线',
200
+ 'v2.sessions': '会话',
103
201
  }
104
202
 
105
203
  const NAMES_ZH = {
@@ -158,6 +256,51 @@
158
256
  return parsed
159
257
  }
160
258
 
259
+ // v2 reads: abortable, and a failure carries the host's error code when it
260
+ // sent one. The cached copy below is only ever a *display* convenience; the
261
+ // host stays the single source of truth when the next read lands.
262
+ async function getJsonSignal(url, signal) {
263
+ const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal })
264
+ let payload = null
265
+ try {
266
+ payload = await response.json()
267
+ } catch {
268
+ payload = null
269
+ }
270
+ if (!response.ok) {
271
+ const error = new Error((payload && (payload.message || payload.error)) || `HTTP ${response.status}`)
272
+ error.status = response.status
273
+ error.code = payload && typeof payload.error === 'string' ? payload.error : undefined
274
+ throw error
275
+ }
276
+ if (payload !== null && typeof payload === 'object' && payload.ok === false) {
277
+ const error = new Error(payload.message || payload.error || 'request-failed')
278
+ error.code = typeof payload.error === 'string' ? payload.error : undefined
279
+ throw error
280
+ }
281
+ return payload
282
+ }
283
+
284
+ // 30s cache shared by every instance of the panel. A tab switch re-renders
285
+ // but does not re-hit the host; an explicit refresh/reload bypasses it.
286
+ const RESOURCE_CACHE = new Map()
287
+ function cachePeek(url) {
288
+ const row = RESOURCE_CACHE.get(url)
289
+ return row === undefined ? undefined : row.data
290
+ }
291
+ function cacheFresh(url, ttl) {
292
+ const row = RESOURCE_CACHE.get(url)
293
+ if (row === undefined) return undefined
294
+ return Date.now() - row.at < ttl ? row.data : undefined
295
+ }
296
+ function cacheSet(url, data) {
297
+ RESOURCE_CACHE.set(url, { at: Date.now(), data })
298
+ if (RESOURCE_CACHE.size > 48) {
299
+ const oldest = RESOURCE_CACHE.keys().next()
300
+ if (oldest.done !== true) RESOURCE_CACHE.delete(oldest.value)
301
+ }
302
+ }
303
+
161
304
  const token = (value) => {
162
305
  const number = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0
163
306
  if (number < 1000) return String(number)
@@ -165,7 +308,11 @@
165
308
  return `${Math.round((number / 1000000) * 10) / 10}M`
166
309
  }
167
310
  const digits = (value) => String(Math.round(Number(value) || 0)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
311
+ // pct() stays numeric: three call sites do arithmetic with it (budget bar
312
+ // width, drawer share data). Display-only interpolation uses pctText so one
313
+ // column never mixes "3%" with "3.6%".
168
314
  const pct = (part, whole) => (whole > 0 ? Math.round((part / whole) * 1000) / 10 : 0)
315
+ const pctText = (part, whole) => (whole > 0 ? (Math.round((part / whole) * 1000) / 10).toFixed(1) + '%' : '0.0%')
169
316
 
170
317
  const DOCK_STYLE = `
171
318
  .ci-dock-wrap{display:inline-flex;align-items:center;gap:0}
@@ -174,52 +321,162 @@
174
321
  .ci-dock:focus-visible{outline:2px solid var(--ci-accent,#4d6bfe);outline-offset:2px}
175
322
  .ci-dock b{color:var(--ci-fg2,#5f6470);font-weight:600;font-variant-numeric:tabular-nums}
176
323
  .ci-dock i{width:5px;height:5px;border-radius:50%;background:var(--ci-accent,#4d6bfe);opacity:.75;display:block}
177
- .ci-dock em{font-style:normal;color:var(--ci-fg3,#8a8f99);font-size:10.5px}
324
+ .ci-dock em{font-style:normal;color:var(--ci-fg3,#8a8f99);font-size:10px}
325
+ .ci-dock.warn i{background:var(--ci-danger,#b91c1c);opacity:.9}
178
326
  .ci-dock-x{width:15px;height:15px;border:0;background:transparent;color:var(--ci-fg3,#8a8f99);cursor:pointer;font-size:12px;line-height:1;padding:0;opacity:0;transition:opacity .12s}
179
327
  .ci-dock-wrap:hover .ci-dock-x,.ci-dock-x:focus-visible{opacity:.55}
180
328
  .ci-dock-x:hover{opacity:1}
181
329
  `
182
330
 
183
331
  const STYLE = `
184
- .ci-root{--ci-fg:var(--dsw-alias-content-primary,#18181b);--ci-fg2:var(--dsw-alias-content-secondary,#52525b);--ci-fg3:var(--dsw-alias-content-tertiary,#8a8a93);--ci-line:var(--dsw-alias-border-secondary,rgba(0,0,0,.09));--ci-line2:var(--dsw-alias-border-tertiary,rgba(0,0,0,.055));--ci-bg:var(--dsw-alias-bg-primary,#fff);--ci-card:var(--dsw-alias-bg-secondary,#fafafa);--ci-accent:var(--dsw-alias-brand-primary,#4d6bfe);--ci-warn:var(--dsw-alias-warning-primary,#b45309);color:var(--ci-fg);font-size:13px;line-height:1.55;display:flex;flex-direction:column;height:100%;min-height:0;container-type:inline-size}
185
- body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8b95;--ci-line:rgba(255,255,255,.12);--ci-line2:rgba(255,255,255,.07);--ci-bg:#161619;--ci-card:#1d1d21;--ci-accent:#7c8dff;--ci-warn:#fbbf24}
332
+ .ci-root{--ci-fg:var(--dsw-alias-content-primary,#18181b);--ci-fg2:var(--dsw-alias-content-secondary,#52525b);--ci-fg3:var(--dsw-alias-content-tertiary,#8a8a93);--ci-line:var(--dsw-alias-border-secondary,rgba(0,0,0,.09));--ci-line2:var(--dsw-alias-border-tertiary,rgba(0,0,0,.055));--ci-bg:var(--dsw-alias-bg-primary,#fff);--ci-card:var(--dsw-alias-bg-secondary,#fafafa);--ci-accent:var(--dsw-alias-brand-primary,#4d6bfe);--ci-warn:var(--dsw-alias-warning-primary,#b45309);--ci-danger:var(--dsw-alias-danger-primary,#b91c1c);--ci-win1:#2f4bd8;--ci-win2:#5f7bff;--ci-win3:#a8bcff;color:var(--ci-fg);font-size:12px;line-height:1.55;display:flex;flex-direction:column;height:100%;min-height:0;container-type:inline-size}
333
+ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8b95;--ci-line:rgba(255,255,255,.12);--ci-line2:rgba(255,255,255,.07);--ci-bg:#161619;--ci-card:#1d1d21;--ci-accent:#7c8dff;--ci-warn:#fbbf24;--ci-danger:#f87171;--ci-win1:#5f7bff;--ci-win2:#8fa6ff;--ci-win3:#c9d6ff}
186
334
  .ci-scroll{overflow:auto;min-height:0}
187
335
  .ci-scroll::-webkit-scrollbar{width:8px;height:8px}
188
336
  .ci-scroll::-webkit-scrollbar-thumb{background:var(--ci-line);border-radius:8px}
189
337
  .ci-head{display:flex;align-items:flex-start;gap:12px;padding:16px 20px 12px;border-bottom:1px solid var(--ci-line2);flex:0 0 auto}
190
- .ci-head h1{font-size:16px;font-weight:600;margin:0;letter-spacing:.01em}
338
+ .ci-head h1{font-size:15px;font-weight:600;margin:0;letter-spacing:.01em}
191
339
  .ci-head p{margin:2px 0 0;color:var(--ci-fg2);font-size:12px}
192
340
  .ci-head .ci-spacer{flex:1}
193
341
  .ci-btn{border:1px solid var(--ci-line);background:var(--ci-bg);color:var(--ci-fg);border-radius:8px;padding:5px 11px;font-size:12px;cursor:pointer;line-height:1.5;white-space:nowrap}
194
342
  .ci-btn:hover{background:var(--ci-card)}
195
343
  .ci-btn[disabled]{opacity:.5;cursor:default}
196
344
  .ci-btn.ci-primary{background:var(--ci-accent);border-color:transparent;color:#fff}
197
- .ci-body{padding:16px 20px 24px;display:flex;flex-direction:column;gap:16px;flex:0 0 auto}
345
+ .ci-body{padding:14px 20px 14px;display:flex;flex-direction:column;gap:14px;flex:0 0 auto}
198
346
  .ci-body.grow{flex:1 1 auto;min-height:0;overflow:auto;padding-top:12px}
347
+ .ci-manage{display:flex;flex-direction:column;gap:10px;min-height:0;flex:1 1 auto}
348
+ .ci-history{display:flex;flex-direction:column;gap:5px}
349
+ .ci-history-row{display:grid;grid-template-columns:46px minmax(0,1fr) auto;gap:8px;align-items:center;font-size:11px;color:var(--ci-fg3)}
350
+ .ci-history-row .d{font-variant-numeric:tabular-nums}
351
+ .ci-history-row .t{font-variant-numeric:tabular-nums;white-space:nowrap}
352
+ .ci-current{display:flex;flex-direction:column;gap:10px}
353
+ .ci-section-title{font-size:12px;font-weight:600;color:var(--ci-fg2);padding:2px 0}
354
+ .ci-stathead,.ci-statrow{display:grid;grid-template-columns:minmax(0,90px) 130px 88px 96px 72px minmax(0,1fr);gap:8px;align-items:center;font-size:11px}
355
+ .ci-stathead{color:var(--ci-fg3);padding-bottom:4px;border-bottom:1px solid var(--ci-line2)}
356
+ .ci-statrow{padding:4px 0;border-bottom:1px solid var(--ci-line2);color:var(--ci-fg2)}
357
+ .ci-statrow:last-child{border-bottom:0}
358
+ .ci-statrow .n{font-variant-numeric:tabular-nums;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
359
+ .ci-statrow .w{color:var(--ci-fg3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
360
+ .ci-statrow .r{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
361
+ .ci-statrow .b{color:var(--ci-fg);font-weight:600}
362
+ .ci-statrow.unmeasured{color:var(--ci-fg3)}
363
+ .ci-statrow.unmeasured .b{color:var(--ci-fg3);font-weight:400}
364
+ .ci-stathead .r{text-align:right}
365
+ .ci-bar-track.mini{height:6px;min-width:0}
366
+ @container (max-width:900px){.ci-stathead,.ci-statrow{grid-template-columns:minmax(0,80px) 1fr 74px 76px minmax(0,0.6fr)}.ci-statrow .w,.ci-stathead :nth-child(2){display:none}}
367
+ .ci-card.ci-overview{display:grid;grid-template-columns:minmax(0,340px) minmax(0,1fr);gap:18px;align-items:start}
368
+ .ci-donut{display:flex;align-items:center;gap:14px;min-width:0}
369
+ .ci-donut-svg{flex:0 0 auto}
370
+ .ci-donut-v{font-size:18px;font-weight:600;fill:var(--ci-fg)}
371
+ .ci-donut-k{font-size:10px;fill:var(--ci-fg3)}
372
+ .ci-donut-legend{display:flex;flex-direction:column;gap:5px;min-width:0;flex:1 1 auto}
373
+ .ci-donut-row{display:grid;grid-template-columns:10px minmax(0,1fr) minmax(52px,auto) 44px;gap:6px;align-items:center;font-size:11px}
374
+ .ci-donut-row b{text-align:right}
375
+ .ci-donut-row .n{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ci-fg2)}
376
+ .ci-donut-row b{font-weight:600;font-variant-numeric:tabular-nums}
377
+ .ci-donut-row .p{color:var(--ci-fg3);text-align:right;font-variant-numeric:tabular-nums}
378
+ .ci-bars{display:flex;flex-direction:column;gap:7px;min-width:0}
379
+ .ci-bars-title{font-size:11px;color:var(--ci-fg3);margin-bottom:1px}
380
+ .ci-barrow{display:grid;grid-template-columns:minmax(0,120px) minmax(0,1fr) auto;gap:8px;align-items:center;font-size:11px;min-width:0}
381
+ .ci-barrow .ci-bar-track{min-width:0}
382
+ .ci-barrow.off .n,.ci-barrow.off .t{color:var(--ci-fg3)}
383
+ .ci-barrow .n{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
384
+ .ci-barrow .t{color:var(--ci-fg3);font-variant-numeric:tabular-nums;white-space:nowrap}
385
+ .ci-bar-track{height:8px;border-radius:5px;background:var(--ci-line2);overflow:hidden;display:flex;min-width:3px}
386
+ .ci-bar-fill{display:block;height:100%;border-radius:5px}
387
+ .ci-bar-closed{display:block;height:100%;border-radius:5px;opacity:.28;min-width:3px}
388
+ .ci-spark{display:block;width:100%;height:18px;margin:4px 0 2px;opacity:.9}
199
389
  .ci-kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}
200
390
  @container (max-width:560px){.ci-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}}
201
- .ci-kpi{border:1px solid var(--ci-line2);background:var(--ci-card);border-radius:10px;padding:10px 12px;min-width:0}
391
+ .ci-kpi{border:1px solid var(--ci-line2);background:var(--ci-card);border-radius:8px;padding:8px 10px;min-width:0}
202
392
  .ci-kpi .k{font-size:11px;color:var(--ci-fg2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
203
- .ci-kpi .v{font-size:19px;font-weight:600;letter-spacing:-.01em;margin-top:2px;white-space:nowrap}
204
- .ci-kpi .s{font-size:11px;color:var(--ci-fg3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
393
+ .ci-kpi .v{font-size:18px;font-weight:600;letter-spacing:-.01em;margin-top:0;white-space:nowrap;font-variant-numeric:tabular-nums;line-height:1.35}
394
+ .ci-kpi .s{font-size:11px;color:var(--ci-fg3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
395
+ .ci-kpi.tone-warn .v{color:var(--ci-warn)}
396
+ .ci-kpi.tone-danger .v{color:var(--ci-danger)}
397
+ .ci-window-head{display:flex;align-items:baseline;gap:8px;min-width:0}
398
+ .ci-window-head h2{font-size:12px;font-weight:600;margin:0;color:var(--ci-fg2);white-space:nowrap}
399
+ .ci-window-bar{display:flex;height:8px;border-radius:4px;overflow:hidden;background:var(--ci-line2);gap:1px}
400
+ .ci-window-bar span{display:block;height:100%;min-width:0}
401
+ .ci-skills{display:flex;flex-direction:column;gap:8px}
402
+ .ci-skills-head{display:flex;align-items:center;gap:12px;min-width:0}
403
+ .ci-skills-num{display:flex;align-items:baseline;gap:3px;flex:0 0 auto}
404
+ .ci-skills-num b{font-size:20px;font-weight:600;letter-spacing:-.02em;font-variant-numeric:tabular-nums}
405
+ .ci-skills-num span{font-size:11px;color:var(--ci-fg3)}
406
+ .ci-skills-text{flex:1 1 auto;min-width:0}
407
+ .ci-skills-text .k{font-size:12px;font-weight:600}
408
+ .ci-skills-text .s{font-size:11px;color:var(--ci-fg3);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
409
+ .ci-skills-providers{display:flex;flex-wrap:wrap;gap:4px 14px}
410
+ .ci-skills-provider{display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;color:var(--ci-fg2);font-size:11px;cursor:pointer;padding:2px 0;min-width:0}
411
+ .ci-skills-provider:hover{color:var(--ci-fg)}
412
+ .ci-skills-provider .n{max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
413
+ .ci-skills-provider .ci-bar-track{width:56px;height:6px;flex:0 0 56px}
414
+ .ci-skills-provider .t{color:var(--ci-fg3);font-variant-numeric:tabular-nums;white-space:nowrap}
415
+ @container (max-width:430px){
416
+ .ci-skills-head{flex-wrap:wrap;gap:8px}
417
+ .ci-skills-text{flex:1 1 100%;order:2}
418
+ .ci-skills-head .ci-btn{order:1;margin-left:auto}
419
+ .ci-skills-provider{flex:0 0 100%}
420
+ .ci-skills-provider .n{max-width:none;flex:1 1 auto}
421
+ }
422
+ .ci-skills-note{font-size:11px;color:var(--ci-fg3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
423
+ .ci-kinds{display:flex;flex-wrap:wrap;align-items:center;gap:6px}
424
+ .ci-kinds .lbl{font-size:11px;color:var(--ci-fg3);margin-right:2px}
425
+ .ci-kind{display:inline-flex;align-items:baseline;gap:5px;border:1px solid var(--ci-line2);background:var(--ci-bg);color:var(--ci-fg2);border-radius:999px;padding:2px 9px;font-size:11px;cursor:pointer}
426
+ .ci-kind:hover{border-color:var(--ci-line);color:var(--ci-fg)}
427
+ .ci-kind b{font-weight:600;font-variant-numeric:tabular-nums;color:var(--ci-fg)}
428
+ .ci-kind .p{color:var(--ci-fg3);font-variant-numeric:tabular-nums}
429
+ .ci-kind.on{border-color:var(--ci-accent);color:var(--ci-accent)}
430
+ .ci-kind.on b{color:var(--ci-accent)}
431
+ .ci-strip{display:flex;align-items:center;gap:6px 12px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);min-width:0}
432
+ .ci-strip .k{color:var(--ci-fg2);font-weight:600;white-space:nowrap}
433
+ .ci-strip .ci-window-bar{flex:1 1 220px;min-width:110px}
434
+ .ci-strip .lg{display:flex;gap:4px 12px;flex-wrap:wrap;min-width:0}
435
+ .ci-strip .lg .item{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
436
+ .ci-strip .lg i{width:8px;height:8px;border-radius:3px;display:block}
437
+ .ci-strip .lg b{font-weight:600;font-variant-numeric:tabular-nums;color:var(--ci-fg2)}
438
+ .ci-strip .rt{white-space:nowrap;font-variant-numeric:tabular-nums}
439
+ .ci-strip .rt.warn{color:var(--ci-warn)}
440
+ .ci-strip.tone-warn .rt{color:var(--ci-warn)}
441
+ .ci-strip.tone-danger .rt{color:var(--ci-danger)}
442
+ @container (max-width:430px){
443
+ .ci-strip .ci-window-bar{order:2;flex:1 1 100%}
444
+ .ci-strip .k{order:1}
445
+ .ci-strip .rt{order:1}
446
+ .ci-strip .lg{order:4}
447
+ }
205
448
  .ci-bar{display:flex;height:10px;border-radius:6px;overflow:hidden;background:var(--ci-line2)}
449
+ .ci-composition{display:flex;flex-direction:column;gap:6px}
206
450
  .ci-bar span{display:block;height:100%;min-width:2px}
207
451
  .ci-legend{display:flex;flex-wrap:wrap;gap:6px 14px;margin-top:8px}
208
452
  .ci-legend button{display:flex;align-items:center;gap:6px;border:0;background:transparent;color:var(--ci-fg2);font-size:11px;cursor:pointer;padding:2px 0}
209
453
  .ci-legend i{width:8px;height:8px;border-radius:3px;display:block}
210
454
  .ci-legend b{color:var(--ci-fg);font-weight:600}
211
- .ci-tabs{display:flex;gap:4px;border-bottom:1px solid var(--ci-line2);padding:0 20px;flex:0 0 auto}
212
- .ci-tabs button{border:0;background:transparent;color:var(--ci-fg2);padding:8px 10px;font-size:13px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px}
213
- .ci-tabs button.on{color:var(--ci-fg);border-bottom-color:var(--ci-accent);font-weight:600}
455
+ .ci-tabs{display:inline-flex;gap:2px;padding:2px;border:1px solid var(--ci-line2);background:var(--ci-card);border-radius:8px;align-self:flex-start;margin:0 20px 10px;flex:0 0 auto}
456
+ .ci-tabs button{border:0;background:transparent;color:var(--ci-fg2);padding:5px 13px;font-size:12px;cursor:pointer;border-radius:6px;line-height:1.6}
457
+ .ci-tabs button:hover{color:var(--ci-fg)}
458
+ .ci-tabs button.on{background:var(--ci-bg);color:var(--ci-fg);font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.07)}
459
+ body[data-ds-dark-theme] .ci-tabs button.on{background:rgba(255,255,255,.1);box-shadow:none}
214
460
  .ci-toolbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;flex:0 0 auto}
461
+ .ci-select{border:1px solid var(--ci-line);border-radius:8px;background:var(--ci-bg);color:var(--ci-fg);font:inherit;font-size:12px;padding:4px 8px;cursor:pointer;max-width:150px}
462
+ .ci-select:focus-visible{outline:2px solid var(--ci-accent);outline-offset:1px}
463
+ .ci-viewopts button{font-size:11px;padding:4px 9px}
464
+ @media (max-width:1220px){.ci-select{display:none}}
465
+ @media (max-width:1040px){.ci-viewopts{display:none}}
466
+ .ci-activefilters{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);flex:0 0 auto}
467
+ .ci-activefilters .lbl{white-space:nowrap}
215
468
  .ci-input{flex:1;min-width:120px;border:1px solid var(--ci-line);border-radius:8px;padding:5px 10px;font-size:12px;background:var(--ci-bg);color:var(--ci-fg);outline:none}
216
469
  .ci-input:focus{border-color:var(--ci-accent)}
217
470
  .ci-chip{border:1px solid var(--ci-line);background:transparent;color:var(--ci-fg2);border-radius:999px;padding:3px 10px;font-size:11px;cursor:pointer}
218
471
  .ci-chip.on{background:var(--ci-fg);color:var(--ci-bg);border-color:transparent}
219
- .ci-table{border:1px solid var(--ci-line2);border-radius:10px;overflow:auto;background:var(--ci-bg);min-height:0}
472
+ .ci-table{border:1px solid var(--ci-line2);border-radius:8px;overflow:auto;background:var(--ci-bg);min-height:0}
220
473
  .ci-thead,.ci-row{display:grid;grid-template-columns:minmax(0,1fr) 96px 72px 58px 52px;gap:8px;align-items:center;padding:7px 12px}
221
474
  .ci-thead{font-size:11px;color:var(--ci-fg3);background:var(--ci-card);border-bottom:1px solid var(--ci-line2);position:sticky;top:0;z-index:1}
222
- .ci-row{border-bottom:1px solid var(--ci-line2);font-size:12.5px}
475
+ .ci-sort{width:100%;background:none;border:0;padding:0;font:inherit;color:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:4px;text-align:inherit}
476
+ .ci-sort:hover{color:var(--ci-fg2)}
477
+ .ci-sort.active{color:var(--ci-fg)}
478
+ .ci-arrow{font-size:10px;opacity:.55;line-height:1}
479
+ .ci-row{border-bottom:1px solid var(--ci-line2);font-size:12px}
223
480
  .ci-row:last-child{border-bottom:0}
224
481
  .ci-row:hover{background:var(--ci-card)}
225
482
  .ci-row .n{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@@ -231,8 +488,9 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
231
488
  .ci-btn:focus-visible,.ci-chip:focus-visible,.ci-switch:focus-visible,.ci-seg button:focus-visible,.ci-tabs button:focus-visible,.ci-legend button:focus-visible,.ci-grouphead:focus-visible,.ci-input:focus-visible,.ci-dock:focus-visible{outline:2px solid var(--ci-accent);outline-offset:2px}
232
489
  @media (prefers-reduced-motion: reduce){.ci-root *{transition:none!important;animation:none!important}}
233
490
  .ci-tag{font-size:10px;line-height:1.6;padding:0 5px;border-radius:999px;border:1px solid var(--ci-line);color:var(--ci-fg3);margin-left:6px;white-space:nowrap}
234
- .ci-lock{justify-self:end;font-size:10.5px;color:var(--ci-fg2);border:1px solid var(--ci-line);border-radius:999px;padding:1px 7px;white-space:nowrap}
491
+ .ci-lock{justify-self:end;font-size:10px;color:var(--ci-fg2);border:1px solid var(--ci-line);border-radius:999px;padding:1px 7px;white-space:nowrap}
235
492
  .ci-row.locked .n{color:var(--ci-fg2)}
493
+ .ci-row-off .n,.ci-row-off .num{color:var(--ci-fg3)}
236
494
  .ci-switch{position:relative;width:34px;height:20px;border-radius:999px;border:0;background:var(--ci-line);cursor:pointer;padding:0;justify-self:end;transition:background .15s}
237
495
  .ci-switch span{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.2);transition:transform .15s}
238
496
  .ci-switch.on{background:var(--ci-accent)}
@@ -247,13 +505,14 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
247
505
  .ci-row-nested .n{font-weight:400}
248
506
  .ci-note{color:var(--ci-fg2);font-size:12px}
249
507
  .ci-note.warn{color:var(--ci-warn)}
250
- .ci-card{border:1px solid var(--ci-line2);border-radius:10px;padding:12px 14px;background:var(--ci-card);display:flex;flex-direction:column;gap:8px}
508
+ .ci-card{border:1px solid var(--ci-line2);border-radius:8px;padding:12px 14px;background:var(--ci-card);display:flex;flex-direction:column;gap:8px}
251
509
  .ci-card h2{font-size:12px;font-weight:600;margin:0;color:var(--ci-fg2)}
252
510
  .ci-rowline{display:flex;align-items:center;justify-content:space-between;gap:12px}
253
- .ci-rowline .lbl{font-size:12.5px}
511
+ .ci-rowline .lbl{font-size:12px}
254
512
  .ci-rowline .hint{font-size:11px;color:var(--ci-fg3)}
255
513
  .ci-seg{display:inline-flex;border:1px solid var(--ci-line);border-radius:8px;overflow:hidden}
256
- .ci-seg button{border:0;background:transparent;color:var(--ci-fg2);padding:4px 10px;font-size:11.5px;cursor:pointer}
514
+ .ci-tag-closed{border-color:var(--ci-warn);color:var(--ci-warn)}
515
+ .ci-seg button{border:0;background:transparent;color:var(--ci-fg2);padding:4px 10px;font-size:11px;cursor:pointer}
257
516
  .ci-seg button.on{background:var(--ci-fg);color:var(--ci-bg)}
258
517
  .ci-empty{padding:26px 12px;text-align:center;color:var(--ci-fg3);font-size:12px}
259
518
  .ci-skel{height:56px;border-radius:10px;background:var(--ci-card);border:1px solid var(--ci-line2)}
@@ -267,7 +526,7 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
267
526
  .ci-dock:hover{opacity:1;border-color:var(--ci-line);background:var(--ci-bg)}
268
527
  .ci-dock b{color:var(--ci-fg2);font-weight:600;font-variant-numeric:tabular-nums}
269
528
  .ci-dock i{width:5px;height:5px;border-radius:50%;background:var(--ci-accent);opacity:.75;display:block}
270
- .ci-dock em{font-style:normal;color:var(--ci-fg3);font-size:10.5px}
529
+ .ci-dock em{font-style:normal;color:var(--ci-fg3);font-size:10px}
271
530
  .ci-dock-x{width:15px;height:15px;border:0;background:transparent;color:var(--ci-fg3);cursor:pointer;font-size:12px;line-height:1;padding:0;opacity:0;transition:opacity .12s}
272
531
  .ci-dock-wrap:hover .ci-dock-x,.ci-dock-x:focus-visible{opacity:.55}
273
532
  .ci-dock-x:hover{opacity:1}
@@ -276,14 +535,292 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
276
535
  .ci-toast .ci-btn{padding:2px 8px;font-size:11px}
277
536
  .ci-side{display:flex;flex-direction:column;min-height:0;height:100%}
278
537
  .ci-side .ci-body{padding:12px 12px 16px;gap:10px;flex:1 1 auto;min-height:0;overflow:auto}
538
+ /* ============================================================ v2 surfaces
539
+ Everything below is new in 2.0: KPI budget tone, health strip, inline
540
+ previews, the content drawer, the hand-written trend chart, insights grids
541
+ and the settings preferences. Tokens follow the host contract: 8px spacing
542
+ grid, 11/12/13/15/20 type, 8/10/12 radii, --dsw-alias-* first. */
543
+ .ci-badge{display:inline-flex;align-items:center;gap:4px;font-size:11px;line-height:1.7;padding:0 7px;border-radius:999px;border:1px solid var(--ci-line);color:var(--ci-fg3);white-space:nowrap;background:transparent}
544
+ .ci-badge.accent{border-color:var(--ci-accent);color:var(--ci-accent)}
545
+ .ci-badge.warn{border-color:var(--ci-warn);color:var(--ci-warn)}
546
+ .ci-badge.danger{border-color:var(--ci-danger);color:var(--ci-danger)}
547
+ .ci-btn.ci-sm{padding:2px 8px;font-size:11px;border-radius:8px}
548
+ .ci-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
549
+ .ci-errorbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;border:1px solid var(--ci-warn);background:var(--ci-card);color:var(--ci-warn);border-radius:8px;padding:6px 10px;font-size:12px;min-width:0}
550
+ .ci-errorbar .ci-btn{color:var(--ci-fg)}
551
+ .ci-stale{font-size:11px;color:var(--ci-warn)}
552
+ .ci-inline-meta{display:flex;align-items:center;gap:6px 10px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);min-width:0}
553
+ .ci-inline-meta b{font-weight:600;color:var(--ci-fg2);font-variant-numeric:tabular-nums}
554
+ /* ---- manage: health strip ---- */
555
+ .ci-health{display:flex;flex-direction:column;gap:0;border:1px solid var(--ci-line2);border-radius:10px;background:var(--ci-card);padding:7px 12px 8px;font-size:12px;min-width:0}
556
+ .ci-health-head{display:flex;align-items:center;gap:8px 12px;flex-wrap:wrap;min-width:0}
557
+ .ci-health-title{font-weight:600;font-size:12px;color:var(--ci-fg2);white-space:nowrap}
558
+ .ci-health-counts{display:flex;gap:10px;color:var(--ci-fg3);font-size:11px;flex-wrap:wrap}
559
+ .ci-health-counts b{font-variant-numeric:tabular-nums;color:var(--ci-fg2);font-weight:600;margin-right:2px}
560
+ .ci-health-counts .high b{color:var(--ci-danger)}
561
+ .ci-health-counts .warn b{color:var(--ci-warn)}
562
+ .ci-health-counts .sep{color:var(--ci-line);padding:0 1px}
563
+ .ci-health-row{display:grid;grid-template-columns:8px minmax(0,1fr) auto;gap:10px;align-items:center;padding:5px 0 0;margin-top:5px;border-top:1px solid var(--ci-line2)}
564
+ .ci-health-row .sev{width:8px;height:8px;border-radius:50%;display:block;background:var(--ci-fg3)}
565
+ .ci-health-row .sev.high{background:var(--ci-danger)}
566
+ .ci-health-row .sev.warn{background:var(--ci-warn)}
567
+ .ci-health-row .sev.info{background:var(--ci-fg3)}
568
+ .ci-health-text{min-width:0;color:var(--ci-fg2);font-size:12px;overflow:hidden;text-overflow:ellipsis}
569
+ .ci-health-allclear{font-size:11px;color:var(--ci-fg3);padding-top:3px}
570
+ .ci-health .ci-btn{align-self:center}
571
+ /* ---- manage: inline preview row ---- */
572
+ .ci-caret-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex:0 0 16px;padding:0;margin-right:4px;border:0;border-radius:4px;background:transparent;color:var(--ci-fg3);font-size:10px;line-height:1;cursor:pointer;vertical-align:-3px;transition:transform .12s}
573
+ .ci-caret-btn:hover{color:var(--ci-fg);background:var(--ci-line2)}
574
+ .ci-caret-btn[aria-expanded="true"]{transform:rotate(90deg)}
575
+ .ci-row-preview{padding:6px 12px 9px 34px;background:var(--ci-card);border-bottom:1px solid var(--ci-line2);box-shadow:inset 2px 0 0 var(--ci-line2);display:flex;flex-direction:column;gap:6px;min-width:0}
576
+ .ci-row-preview .pv{margin:0;font-size:12px;line-height:1.55;color:var(--ci-fg2);white-space:pre-wrap;word-break:break-word;font-family:inherit}
577
+ .ci-row-preview .meta{display:flex;align-items:center;gap:6px 10px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);min-width:0}
578
+ .ci-row-preview .actions{display:flex;gap:6px;flex-wrap:wrap}
579
+ /* ---- content drawer ---- */
580
+ .ci-drawer-backdrop{position:fixed;inset:0;z-index:60;background:rgba(15,15,20,.38)}
581
+ .ci-drawer{position:fixed;top:0;right:0;bottom:0;z-index:61;width:min(520px,92%);max-width:100%;display:flex;flex-direction:column;min-height:0;background:var(--ci-bg);color:var(--ci-fg);border-left:1px solid var(--ci-line);box-shadow:-10px 0 34px rgba(0,0,0,.2);outline:none}
582
+ .ci-drawer-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px 10px;border-bottom:1px solid var(--ci-line2);flex:0 0 auto;min-width:0}
583
+ .ci-drawer-title{flex:1 1 auto;min-width:0}
584
+ .ci-drawer-title h2{font-size:15px;font-weight:600;margin:0;letter-spacing:.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
585
+ .ci-breadcrumb{display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);margin-bottom:2px;min-width:0}
586
+ .ci-breadcrumb .sep{opacity:.5}
587
+ .ci-breadcrumb .last{color:var(--ci-fg2);max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
588
+ .ci-drawer-tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap;padding:8px 16px;border-bottom:1px solid var(--ci-line2);flex:0 0 auto;font-size:11px;min-width:0}
589
+ .ci-drawer-source{display:flex;align-items:center;gap:6px;padding:6px 16px;border-bottom:1px solid var(--ci-line2);flex:0 0 auto;font-size:11px;color:var(--ci-fg3);min-width:0;flex-wrap:wrap}
590
+ .ci-drawer-path{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace;font-size:11px;color:var(--ci-fg2);word-break:break-all;min-width:0;flex:1 1 auto}
591
+ .ci-drawer-search{flex:1 1 130px;min-width:110px}
592
+ .ci-drawer-body{flex:1 1 auto;min-height:0;overflow:auto;padding:8px 0 24px}
593
+ .ci-drawer-note{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:8px 16px 0;border:1px solid var(--ci-warn);border-radius:8px;padding:6px 10px;font-size:11px;color:var(--ci-warn)}
594
+ .ci-content-lines{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace;font-size:12px;line-height:1.6;min-width:0}
595
+ .ci-content-line{display:flex;gap:10px;padding:0 16px;min-width:0}
596
+ .ci-content-line:hover{background:var(--ci-card)}
597
+ .ci-content-line .ln{flex:0 0 44px;text-align:right;color:var(--ci-fg3);user-select:none;font-variant-numeric:tabular-nums;font-size:11px}
598
+ .ci-content-line .tx{flex:1 1 auto;min-width:0;white-space:pre-wrap;word-break:break-word}
599
+ .ci-content-plain{padding:4px 16px;white-space:pre-wrap;word-break:break-word;font-size:12px;line-height:1.6;font-family:inherit}
600
+ .ci-content-hit{background:rgba(77,107,254,.24);border-radius:2px;color:inherit}
601
+ body[data-ds-dark-theme] .ci-content-hit{background:rgba(124,141,255,.34)}
602
+ .ci-drawer-empty{padding:28px 16px;text-align:center;color:var(--ci-fg3);font-size:12px}
603
+ .ci-drawer-foot{flex:0 0 auto;display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:space-between;padding:6px 16px;border-top:1px solid var(--ci-line2);font-size:11px;color:var(--ci-fg3)}
604
+ /* ---- insights ---- */
605
+ .ci-insights{display:flex;flex-direction:column;gap:12px;min-width:0}
606
+ .ci-grid2{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.2fr);gap:10px;align-items:start;min-width:0}
607
+ @container (max-width:900px){.ci-grid2{grid-template-columns:minmax(0,1fr)}}
608
+ .ci-card.ci-pad0{padding:0;overflow:hidden}
609
+ .ci-cardhead{display:flex;align-items:center;gap:8px 12px;flex-wrap:wrap;min-width:0}
610
+ .ci-cardhead h2{font-size:12px;font-weight:600;margin:0;color:var(--ci-fg2);white-space:nowrap}
611
+ .ci-cardhead .sp{flex:1 1 auto}
612
+ .ci-cardhead .hint{font-size:11px;color:var(--ci-fg3);min-width:0}
613
+ .ci-seg.ci-small button{padding:2px 9px;font-size:11px}
614
+ /* trend chart */
615
+ .ci-trend{display:flex;flex-direction:column;gap:8px;min-width:0}
616
+ .ci-trend-wrap{position:relative;min-width:0}
617
+ .ci-trend-svg{display:block;width:100%;height:auto}
618
+ .ci-trend-axis text{fill:var(--ci-fg3);font-size:10px;font-variant-numeric:tabular-nums}
619
+ .ci-trend-grid line{stroke:var(--ci-line2)}
620
+ .ci-trend-bar{cursor:pointer;outline:none}
621
+ .ci-trend-bar .ci-trend-hit{fill:transparent}
622
+ .ci-trend-bar:hover .ci-trend-hit,.ci-trend-bar:focus .ci-trend-hit{fill:var(--ci-line2);opacity:.6}
623
+ .ci-trend-bar:focus-visible .ci-trend-focus{stroke:var(--ci-accent);stroke-width:2}
624
+ .ci-trend-tip{position:absolute;z-index:4;pointer-events:none;min-width:176px;max-width:var(--ci-tip-w,220px);background:var(--ci-bg);border:1px solid var(--ci-line);border-radius:var(--ci-radius-row,6px);box-shadow:var(--ci-shadow-pop);padding:8px 10px;font-size:var(--ci-fs-body,12px);color:var(--ci-fg2);display:flex;flex-direction:column;gap:4px;animation:ci-tip-in .2s ease}
625
+ .ci-trend-tip .t{font-weight:600;color:var(--ci-fg);font-size:12px}
626
+ .ci-trend-tip .r{display:flex;align-items:center;gap:8px;justify-content:space-between;min-width:0}
627
+ .ci-trend-tip .r .l{display:flex;align-items:center;gap:5px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
628
+ .ci-trend-tip .r b{font-variant-numeric:tabular-nums;font-weight:600;color:var(--ci-fg);white-space:nowrap}
629
+ .ci-trend-tip .sw{width:8px;height:8px;border-radius:2px;display:block;flex:0 0 8px}
630
+ .ci-trend-tip .sep{height:1px;background:var(--ci-line2);margin:2px 0}
631
+ .ci-trend-legend{display:flex;flex-wrap:wrap;gap:2px 6px;font-size:11px;color:var(--ci-fg3);min-width:0}
632
+ .ci-trend-legend button{display:inline-flex;align-items:center;gap:5px;border:1px solid transparent;background:transparent;color:inherit;font:inherit;padding:1px 6px;border-radius:999px;cursor:pointer;min-width:0}
633
+ .ci-trend-legend button:hover{color:var(--ci-fg2)}
634
+ .ci-trend-legend button[aria-pressed="false"]{opacity:.42;text-decoration:line-through}
635
+ .ci-trend-legend i{width:8px;height:8px;border-radius:2px;display:block;flex:0 0 8px}
636
+ .ci-trend-legend .unknown i{background:repeating-linear-gradient(45deg,var(--ci-fg3) 0 1.5px,transparent 1.5px 4px)}
637
+ .ci-trend-agg{display:flex;align-items:baseline;gap:8px 20px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);min-width:0}
638
+ .ci-trend-agg .cell{display:inline-flex;align-items:baseline;gap:5px;white-space:nowrap}
639
+ .ci-trend-agg b{font-size:15px;font-weight:600;color:var(--ci-fg);font-variant-numeric:tabular-nums;letter-spacing:-.01em}
640
+ .ci-trend-empty{padding:26px 12px;text-align:center;color:var(--ci-fg3);font-size:12px}
641
+ .ci-trend-note{font-size:11px;color:var(--ci-fg3);line-height:1.5}
642
+ .ci-trend-note .hatch{display:inline-block;width:16px;height:8px;border-radius:2px;vertical-align:-1px;margin-right:3px;background:repeating-linear-gradient(45deg,var(--ci-fg3) 0 1.5px,transparent 1.5px 4px);border:1px solid var(--ci-line2)}
643
+ /* sessions */
644
+ .ci-session-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;min-width:0}
645
+ .ci-session-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(216px,1fr));gap:8px;min-width:0}
646
+ .ci-session{border:1px solid var(--ci-line2);border-radius:10px;background:var(--ci-bg);padding:8px 10px 9px;display:flex;flex-direction:column;gap:5px;min-width:0}
647
+ .ci-session.live{border-color:var(--ci-accent)}
648
+ .ci-session .top{display:flex;align-items:center;gap:6px;min-width:0;font-size:11px;color:var(--ci-fg3)}
649
+ .ci-session .top .sid{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;color:var(--ci-fg2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:0 1 auto}
650
+ .ci-session .top .when{margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}
651
+ .ci-session .big{font-size:20px;font-weight:600;letter-spacing:-.015em;line-height:1.2;font-variant-numeric:tabular-nums}
652
+ .ci-session .big small{font-size:11px;font-weight:400;color:var(--ci-fg3);margin-left:5px;letter-spacing:0}
653
+ .ci-session .sub{font-size:11px;color:var(--ci-fg3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
654
+ .ci-session .mini-bar{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--ci-line2);gap:1px}
655
+ .ci-session .mini-bar span{display:block;min-width:1px}
656
+ .ci-session .mini-bar.unknown{background:repeating-linear-gradient(45deg,var(--ci-line2) 0 3px,transparent 3px 6px)}
657
+ .ci-session .badges{display:flex;gap:4px;flex-wrap:wrap;min-width:0}
658
+ /* events */
659
+ .ci-events{display:flex;flex-direction:column;min-width:0}
660
+ .ci-events-list{display:flex;flex-direction:column;max-height:300px;overflow:auto;min-width:0;padding-right:2px}
661
+ .ci-event{display:grid;grid-template-columns:8px minmax(0,1fr) auto;gap:10px;align-items:start;padding:6px 0;min-width:0;border-top:1px solid var(--ci-line2)}
662
+ .ci-event:first-child{border-top:0}
663
+ .ci-event .dot{width:8px;height:8px;border-radius:50%;display:block;margin-top:5px;background:var(--ci-line)}
664
+ .ci-event .dot.k-switch,.ci-event .dot.k-policy-saved,.ci-event .dot.k-preset{background:var(--ci-accent)}
665
+ .ci-event .dot.k-budget,.ci-event .dot.k-import{background:var(--ci-warn)}
666
+ .ci-event .dot.k-compaction,.ci-event .dot.k-prune{background:var(--ci-fg3)}
667
+ .ci-event .body{min-width:0;display:flex;flex-direction:column;gap:2px}
668
+ .ci-event .lbl{font-size:12px;color:var(--ci-fg);font-weight:500;line-height:1.45}
669
+ .ci-event .prm{display:flex;align-items:center;gap:4px 8px;flex-wrap:wrap;font-size:11px;color:var(--ci-fg3);min-width:0}
670
+ .ci-event .when{font-size:11px;color:var(--ci-fg3);white-space:nowrap;font-variant-numeric:tabular-nums;text-align:right}
671
+ .ci-event .delta{color:var(--ci-fg2);font-variant-numeric:tabular-nums}
672
+ .ci-event .delta.neg{color:var(--ci-fg3)}
673
+ /* settings prefs / version */
674
+ .ci-prefs{display:flex;flex-direction:column;gap:8px}
675
+ .ci-prefrow{display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}
676
+ .ci-prefrow .lbl{font-size:12px;min-width:0}
677
+ .ci-prefrow .hint{font-size:11px;color:var(--ci-fg3);margin-left:8px}
678
+ .ci-kv{display:grid;grid-template-columns:auto minmax(0,1fr);gap:4px 14px;font-size:11px;color:var(--ci-fg3);align-items:baseline}
679
+ .ci-kv b{color:var(--ci-fg2);font-weight:500;font-variant-numeric:tabular-nums;word-break:break-all}
680
+ .ci-kv .k{white-space:nowrap}
681
+ @container (max-width:560px){
682
+ .ci-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}
683
+ .ci-kpi .v{font-size:18px}
684
+ .ci-session-grid{grid-template-columns:minmax(0,1fr)}
685
+ .ci-trend-tip{max-width:212px}
686
+ }
687
+ /* ---- design tokens (self-owned, host variables first) ---------------------
688
+ The 20-token set from _research/v2-bench.md §7. Values are applied below so
689
+ every new surface reads from --ci-*; a host variable wins when present. */
690
+ .ci-root{
691
+ --ci-space-1:2px;--ci-space-2:4px;--ci-space-3:6px;--ci-space-4:8px;--ci-space-5:12px;--ci-space-6:16px;--ci-space-7:24px;
692
+ --ci-radius-chip:4px;--ci-radius-row:6px;--ci-radius-card:10px;--ci-radius-pill:999px;
693
+ --ci-fs-micro:10px;--ci-fs-label:11px;--ci-fs-body:12px;--ci-fs-title:13px;--ci-fs-kpi:20px;--ci-fs-stat:18px;
694
+ --ci-hairline:1px;
695
+ --ci-shadow-card:0 1px 2px rgba(0,0,0,.05);
696
+ --ci-shadow-pop:0 8px 24px rgba(0,0,0,.16);
697
+ --ci-motion:.2s ease;
698
+ --ci-chart-bar:14px;--ci-chart-gap:2px;--ci-chart-h:150px;--ci-tip-w:220px;
699
+ --ci-good:var(--dsw-alias-success-primary,#15803d);
700
+ --ci-track:rgba(0,0,0,.06);
701
+ font-size:var(--ci-fs-body);
702
+ }
703
+ body[data-ds-dark-theme] .ci-root{
704
+ --ci-hairline:1px;
705
+ --ci-shadow-card:none;
706
+ --ci-shadow-pop:0 8px 24px rgba(0,0,0,.5);
707
+ --ci-good:var(--dsw-alias-success-primary,#4ade80);
708
+ --ci-track:rgba(255,255,255,.1);
709
+ }
710
+ .ci-card{border-radius:var(--ci-radius-card);padding:var(--ci-space-4) var(--ci-space-5);box-shadow:var(--ci-shadow-card)}
711
+ .ci-card h2{font-size:var(--ci-fs-title);font-weight:600}
712
+ .ci-btn{border-radius:var(--ci-radius-row)}
713
+ .ci-badge{border-radius:var(--ci-radius-chip)}
714
+ .ci-kpi{border-radius:var(--ci-radius-card);padding:var(--ci-space-4)}
715
+ .ci-kpi .v{font-size:var(--ci-fs-kpi)}
716
+ .ci-kpis{gap:var(--ci-space-4)}
717
+ .ci-block-gap{gap:var(--ci-space-5)}
718
+ /* range pills — a third control tier next to Segmented and FilterChip */
719
+ .ci-pills{display:inline-flex;align-items:center;gap:var(--ci-space-2);flex-wrap:wrap}
720
+ .ci-pills button{border:1px solid var(--ci-line);background:transparent;color:var(--ci-fg2);border-radius:var(--ci-radius-pill);padding:3px 11px;font-size:var(--ci-fs-label);line-height:1.6;cursor:pointer;transition:background var(--ci-motion),border-color var(--ci-motion)}
721
+ .ci-pills button:hover{border-color:var(--ci-fg3);color:var(--ci-fg)}
722
+ .ci-pills button.on{background:var(--ci-fg);border-color:transparent;color:var(--ci-bg);font-weight:600}
723
+ .ci-pills button:focus-visible{outline:2px solid var(--ci-accent);outline-offset:2px}
724
+ /* persistent filter bar */
725
+ .ci-filterbar{display:flex;align-items:center;gap:var(--ci-space-2);flex-wrap:wrap;font-size:var(--ci-fs-label);color:var(--ci-fg3);min-height:24px;flex:0 0 auto}
726
+ .ci-filterbar .lbl{white-space:nowrap;color:var(--ci-fg2)}
727
+ .ci-filterchip{display:inline-flex;align-items:center;gap:4px;border:1px solid var(--ci-line);background:var(--ci-card);color:var(--ci-fg2);border-radius:var(--ci-radius-chip);padding:1px 4px 1px 8px;font-size:var(--ci-fs-label);line-height:1.7;max-width:220px}
728
+ .ci-filterchip .t{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
729
+ .ci-filterchip button{border:0;background:transparent;color:var(--ci-fg3);cursor:pointer;font-size:12px;line-height:1;padding:2px 4px;border-radius:3px}
730
+ .ci-filterchip button:hover{color:var(--ci-fg);background:var(--ci-line2)}
731
+ .ci-filterchip:focus-within{border-color:var(--ci-accent)}
732
+ .ci-filterclear{border:0;background:transparent;color:var(--ci-accent);font-size:var(--ci-fs-label);cursor:pointer;padding:1px 4px}
733
+ .ci-filterclear:hover{text-decoration:underline}
734
+ /* signed delta badge: relative to an all-on policy */
735
+ .ci-delta{display:inline-flex;align-items:center;font-size:var(--ci-fs-micro);line-height:1.6;padding:0 5px;border-radius:var(--ci-radius-chip);border:1px solid var(--ci-line);color:var(--ci-good);font-variant-numeric:tabular-nums;white-space:nowrap;margin-left:6px}
736
+ .ci-delta.zero{color:var(--ci-fg3)}
737
+ /* gate card for apiVersion < 2 */
738
+ .ci-gate{display:flex;flex-direction:column;gap:var(--ci-space-3);border:1px solid var(--ci-warn);border-left-width:3px;border-radius:var(--ci-radius-card);background:var(--ci-card);padding:var(--ci-space-4) var(--ci-space-5)}
739
+ .ci-gate h2{font-size:var(--ci-fs-title);font-weight:600;margin:0;color:var(--ci-fg)}
740
+ .ci-gate p{margin:0;font-size:var(--ci-fs-body);color:var(--ci-fg2);line-height:1.55}
741
+ .ci-gate .kv{display:flex;gap:var(--ci-space-5);flex-wrap:wrap;font-size:var(--ci-fs-label);color:var(--ci-fg3)}
742
+ .ci-gate .kv b{color:var(--ci-fg2);font-weight:600;font-variant-numeric:tabular-nums;margin-left:4px}
743
+ .ci-gate .actions{display:flex;gap:var(--ci-space-3);flex-wrap:wrap}
744
+ /* layout-shaped skeletons: same boxes as the real surfaces, aria-hidden */
745
+ .ci-skel-kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:var(--ci-space-4)}
746
+ .ci-skel-kpis .ci-skel{height:78px;border-radius:var(--ci-radius-card)}
747
+ .ci-skel-strip{height:28px;border-radius:var(--ci-radius-row)}
748
+ .ci-skel-table{display:flex;flex-direction:column;gap:1px;border:1px solid var(--ci-line2);border-radius:var(--ci-radius-card);overflow:hidden;background:var(--ci-bg)}
749
+ .ci-skel-table .head{height:30px;background:var(--ci-card)}
750
+ .ci-skel-table .row{height:34px;border-top:1px solid var(--ci-line2)}
751
+ .ci-skel-chart{height:var(--ci-chart-h);border-radius:var(--ci-radius-row);background:linear-gradient(180deg,var(--ci-card),transparent);border:1px solid var(--ci-line2);display:flex;align-items:flex-end;gap:6px;padding:8px 10px}
752
+ .ci-skel-chart span{flex:1;border-radius:3px 3px 0 0;background:var(--ci-line2);min-height:8px}
753
+ .ci-skel-lines{display:flex;flex-direction:column;gap:8px;padding:4px 0}
754
+ .ci-skel-lines .line{height:12px;border-radius:3px;background:var(--ci-card);border:1px solid var(--ci-line2)}
755
+ .ci-skel-lines .line:nth-child(2n){width:72%}
756
+ .ci-skel-lines .line:nth-child(3n){width:88%}
757
+ @container (max-width:560px){.ci-skel-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}}
758
+ /* tools content: description / parameter table / raw JSON */
759
+ .ci-drawer-desc{margin:0;font-size:var(--ci-fs-body);line-height:1.6;color:var(--ci-fg2);white-space:pre-wrap;word-break:break-word}
760
+ .ci-drawer-sect{padding:0 16px;display:flex;flex-direction:column;gap:var(--ci-space-3)}
761
+ .ci-drawer-sect h3{font-size:var(--ci-fs-title);font-weight:600;margin:var(--ci-space-4) 0 var(--ci-space-2);color:var(--ci-fg)}
762
+ .ci-param-table{width:calc(100% - 32px);margin:0 16px;border-collapse:collapse;font-size:var(--ci-fs-body)}
763
+ .ci-param-table th{font-size:var(--ci-fs-label);font-weight:600;color:var(--ci-fg3);text-align:left;padding:6px 8px 4px;border-bottom:1px solid var(--ci-line2);background:transparent}
764
+ .ci-param-table td{padding:6px 8px;border-bottom:1px solid var(--ci-line2);vertical-align:top;color:var(--ci-fg2)}
765
+ .ci-param-table td.name{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;color:var(--ci-fg);white-space:nowrap}
766
+ .ci-param-table td.type{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:var(--ci-fs-label);color:var(--ci-fg3);white-space:nowrap}
767
+ .ci-param-table td.req{text-align:center;color:var(--ci-good)}
768
+ .ci-param-table td.desc{line-height:1.5}
769
+ .ci-empty-next{display:flex;flex-direction:column;gap:var(--ci-space-3);align-items:flex-start;padding:20px 12px;color:var(--ci-fg3);font-size:var(--ci-fs-body);text-align:left}
770
+ .ci-empty-next .ci-btn{align-self:flex-start}
771
+ .ci-suitename{border:0;background:transparent;color:inherit;font:inherit;font-weight:600;cursor:pointer;padding:0;margin:0;margin-right:4px;text-align:left;border-radius:3px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
772
+ .ci-suitename:hover{color:var(--ci-accent);text-decoration:underline;text-underline-offset:2px}
773
+ .ci-suitename:focus-visible{outline:2px solid var(--ci-accent);outline-offset:2px}
774
+ .ci-trend-tip-hint{font-size:var(--ci-fs-micro);color:var(--ci-fg3);border-top:1px solid var(--ci-line2);padding-top:3px;margin-top:2px}
775
+ @keyframes ci-tip-in{from{opacity:0}to{opacity:1}}
776
+ @media (prefers-reduced-motion: reduce){.ci-trend-tip{animation:none}}
777
+ /* manage overview: two peer cards instead of one mixed card */
778
+ .ci-manage-overview{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px;align-items:stretch}
779
+ @container (max-width:900px){.ci-manage-overview{grid-template-columns:minmax(0,1fr)}}
780
+ .ci-overview-card{padding:10px 12px;gap:6px}
781
+ .ci-overview-card .ci-cardhead .hint{font-variant-numeric:tabular-nums}
782
+ .ci-barrow-btn{border:0;background:transparent;font:inherit;color:inherit;padding:2px 4px;border-radius:var(--ci-radius-chip);cursor:pointer;text-align:left;width:100%}
783
+ .ci-barrow-btn:hover{background:var(--ci-card)}
784
+ .ci-barrow-btn:focus-visible{outline:2px solid var(--ci-accent);outline-offset:1px}
785
+ /* insights first screen: trend 2fr + events 1fr */
786
+ .ci-insight-top{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr);gap:10px;align-items:stretch}
787
+ @container (max-width:1000px){.ci-insight-top{grid-template-columns:minmax(0,1fr)}}
788
+ .ci-events-card{display:flex;flex-direction:column;min-height:0}
789
+ .ci-events-card .ci-events{flex:1 1 auto;display:flex;flex-direction:column;gap:8px;min-height:0}
790
+ .ci-events-card .ci-events-list{flex:1 1 auto;max-height:none}
791
+ .ci-insight-current{display:flex;align-items:center;gap:8px 14px;flex-wrap:wrap;font-size:var(--ci-fs-label);color:var(--ci-fg3);min-width:0}
792
+ .ci-insight-current b{color:var(--ci-fg);font-weight:600;font-variant-numeric:tabular-nums}
793
+ .ci-insight-current .ci-btn{margin-left:auto}
794
+ .ci-events.ci-card{padding:10px 12px}
795
+ /* density pass: KPI 10-12px padding, 20/700 numbers, 10px units */
796
+ .ci-kpi{padding:10px 12px;gap:1px}
797
+ .ci-kpi .v{font-weight:700;line-height:1.3}
798
+ .ci-kpi .s{font-size:var(--ci-fs-micro)}
799
+ .ci-body{gap:12px}
800
+ .ci-manage{gap:8px}
801
+ .ci-insights{gap:10px}
802
+ /* 5 channel colours stay the single source; unknown reads as hatching */
803
+ .ci-donut-row b,.ci-barrow .t{font-variant-numeric:tabular-nums}
804
+ /* KPI value hierarchy: 20px number, 10px denominator/unit (design review #2) */
805
+ .ci-kpi .v{display:flex;align-items:baseline;gap:var(--ci-space-1);min-width:0}
806
+ .ci-kpi .v .u{font-size:var(--ci-fs-micro);font-weight:500;color:var(--ci-fg3);letter-spacing:0}
807
+ .ci-kpi-num{display:inline-flex;align-items:baseline;gap:var(--ci-space-1)}
808
+ /* Items table gains a description column only when the panel is wide (#5) */
809
+ .ci-about{display:none}
810
+ @container (min-width:1100px){
811
+ .ci-thead,.ci-row{grid-template-columns:minmax(0,1.6fr) minmax(0,1.2fr) 96px 72px 58px 52px}
812
+ .ci-about{display:block;font-size:12px;color:var(--ci-fg3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
813
+ .ci-row:hover .ci-about{color:var(--ci-fg2)}
814
+ }
279
815
  `
280
816
 
281
817
  function createTranslator(dictionary, language) {
282
818
  const dict = dictionary || {}
283
- const zh = language === 'zh'
284
819
  return function t(key, vars) {
285
820
  let value = dict[key]
286
- if (typeof value !== 'string' || value === key) value = zh ? FALLBACK[key] : undefined
821
+ // Degraded first paint (no /summary locale yet) still shows readable
822
+ // Chinese chrome instead of raw keys such as `pageTitle`.
823
+ if (typeof value !== 'string' || value === key) value = FALLBACK[key]
287
824
  if (typeof value !== 'string') return key
288
825
  if (vars === undefined) return value
289
826
  return value.replace(/\{(\w+)\}/g, (match, name) => (vars[name] === undefined ? match : String(vars[name])))
@@ -301,7 +838,7 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
301
838
  factory(require) {
302
839
  const React = require('react')
303
840
  const h = React.createElement
304
- const { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } = React
841
+ const { useCallback, useDeferredValue, useEffect, useId, useMemo, useRef, useState } = React
305
842
 
306
843
  const ctxRef = { current: null }
307
844
  const reportedStages = new Set()
@@ -342,6 +879,35 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
342
879
  return [value, setValue]
343
880
  }
344
881
 
882
+ // Sparkline history of the first-turn total, kept in localStorage. This
883
+ // is a local decoration; the cross-session trend lives in useTrend below.
884
+ function useSparkTrend(value) {
885
+ const [trend, setTrend] = useState(() => {
886
+ try {
887
+ const raw = localStorage.getItem(STORAGE_PREFIX + 'trend')
888
+ const parsed = raw === null ? [] : JSON.parse(raw)
889
+ return Array.isArray(parsed) ? parsed : []
890
+ } catch {
891
+ return []
892
+ }
893
+ })
894
+ useEffect(() => {
895
+ if (!Number.isFinite(value) || value <= 0) return
896
+ setTrend((previous) => {
897
+ const last = previous[previous.length - 1]
898
+ if (last !== undefined && Math.abs(last.v - value) < 1 && Date.now() - last.t < 60000) return previous
899
+ const next = previous.concat({ t: Date.now(), v: value }).slice(-40)
900
+ try {
901
+ localStorage.setItem(STORAGE_PREFIX + 'trend', JSON.stringify(next))
902
+ } catch {
903
+ /* private mode */
904
+ }
905
+ return next
906
+ })
907
+ }, [value])
908
+ return trend
909
+ }
910
+
345
911
  function useSnapshot(sessionId, pollMs = 5000) {
346
912
  const [state, setState] = useState({ status: 'loading', data: null, error: null })
347
913
  const [nonce, setNonce] = useState(0)
@@ -392,6 +958,176 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
392
958
  return { ...state, reload }
393
959
  }
394
960
 
961
+ // --------------------------------------------------------- v2 data hooks
962
+ //
963
+ // One abortable, 30s-cached reader shared by all four v2 surfaces. Rules
964
+ // the panel relies on:
965
+ // - a failed read never blanks the panel: the last good payload stays
966
+ // rendered and the surface shows a retry bar;
967
+ // - an in-flight read is aborted on unmount / URL change, so switching
968
+ // the trend range cannot land an older response on top of a newer one;
969
+ // - apiVersion < 2 means the hook is disabled and no request is made.
970
+ function useResource(url, { enabled = true, ttl = RESOURCE_TTL } = {}) {
971
+ const [state, setState] = useState(() => {
972
+ const cached = enabled && url ? cachePeek(url) : undefined
973
+ return {
974
+ status: cached === undefined ? (enabled && url ? 'loading' : 'idle') : 'ready',
975
+ data: cached === undefined ? null : cached,
976
+ error: null,
977
+ }
978
+ })
979
+ const [nonce, setNonce] = useState(0)
980
+ useEffect(() => {
981
+ if (enabled !== true || !url) {
982
+ setState((previous) => ({ ...previous, status: previous.data === null ? 'idle' : previous.status }))
983
+ return undefined
984
+ }
985
+ if (nonce === 0) {
986
+ const fresh = cacheFresh(url, ttl)
987
+ if (fresh !== undefined) {
988
+ setState({ status: 'ready', data: fresh, error: null })
989
+ return undefined
990
+ }
991
+ }
992
+ const stale = cachePeek(url)
993
+ const controller = new AbortController()
994
+ let live = true
995
+ setState((previous) => ({
996
+ status: stale === undefined && previous.data === null ? 'loading' : 'refreshing',
997
+ data: stale === undefined ? previous.data : stale,
998
+ error: null,
999
+ }))
1000
+ getJsonSignal(url, controller.signal)
1001
+ .then((data) => {
1002
+ if (!live) return
1003
+ cacheSet(url, data)
1004
+ setState({ status: 'ready', data, error: null })
1005
+ })
1006
+ .catch((error) => {
1007
+ if (!live || (error && error.name === 'AbortError')) return
1008
+ setState((previous) => ({
1009
+ status: 'failed',
1010
+ data: previous.data,
1011
+ error: String((error && error.message) || error),
1012
+ errorCode: error && typeof error.code === 'string' ? error.code : null,
1013
+ }))
1014
+ })
1015
+ return () => {
1016
+ live = false
1017
+ controller.abort()
1018
+ }
1019
+ }, [url, enabled, nonce, ttl])
1020
+ const reload = useCallback(() => setNonce((value) => value + 1), [])
1021
+ return { ...state, reload }
1022
+ }
1023
+
1024
+ function useTrend(range, enabled) {
1025
+ const url = ROUTES.trend + `?range=${encodeURIComponent(range || 'all')}&limit=120`
1026
+ return useResource(url, { enabled })
1027
+ }
1028
+
1029
+ function useEvents(sessionId, enabled) {
1030
+ const url = ROUTES.events + `?limit=60` + (sessionId ? `&session=${encodeURIComponent(sessionId)}` : '')
1031
+ return useResource(url, { enabled })
1032
+ }
1033
+
1034
+ function useHealth(sessionId, enabled) {
1035
+ const url = ROUTES.health + (sessionId ? `?session=${encodeURIComponent(sessionId)}` : '')
1036
+ return useResource(url, { enabled })
1037
+ }
1038
+
1039
+ function useContent(target, sessionId) {
1040
+ const enabled = target !== null && target !== undefined && typeof target.channel === 'string' && typeof target.id === 'string'
1041
+ const url = enabled
1042
+ ? ROUTES.content + `?channel=${encodeURIComponent(target.channel)}&id=${encodeURIComponent(target.id)}` + (sessionId ? `&session=${encodeURIComponent(sessionId)}` : '')
1043
+ : null
1044
+ return useResource(url, { enabled })
1045
+ }
1046
+
1047
+ const isV2 = (snapshot) => snapshot !== null && snapshot !== undefined && Number(snapshot.apiVersion) >= API_V2
1048
+
1049
+ // `scope` is a free string since the contract revision; only the three
1050
+ // known values have labels, everything else falls back to "unknown source"
1051
+ // instead of rendering a raw i18n key.
1052
+ function scopeLabel(t, scope) {
1053
+ const text = typeof scope === 'string' ? scope : ''
1054
+ if (text.length === 0) return '—'
1055
+ return ['startup', 'clear', 'backfill'].indexOf(text) >= 0 ? t('v2.scope.' + text) : t('v2.scopeUnknown')
1056
+ }
1057
+
1058
+ // Error surfaces carry the host's machine code when it sent one, so a
1059
+ // user can quote it in a bug report instead of screenshotting a sentence.
1060
+ function errorText(result) {
1061
+ if (result === null || result === undefined) return ''
1062
+ const code = typeof result.errorCode === 'string' && result.errorCode.length > 0 ? '[' + result.errorCode + '] ' : ''
1063
+ return code + String(result.error || '')
1064
+ }
1065
+
1066
+ function FilterChip({ label, onClear, title }) {
1067
+ return h(
1068
+ 'span',
1069
+ { className: 'ci-filterchip', title: title || label },
1070
+ h('span', { className: 't' }, label),
1071
+ h('button', { type: 'button', onClick: onClear, 'aria-label': `${label} ×` }, '×'),
1072
+ )
1073
+ }
1074
+
1075
+ // --------------------------------------------------------- small helpers
1076
+
1077
+ // "3m" / "2h" / "5d" — timestamps in the trend and event feeds are
1078
+ // relative because absolute dates there are noise.
1079
+ function ago(ms) {
1080
+ const value = Number(ms)
1081
+ if (!Number.isFinite(value) || value <= 0) return '—'
1082
+ const diff = Math.max(0, Date.now() - value)
1083
+ const minute = 60000
1084
+ const hour = 3600000
1085
+ const day = 86400000
1086
+ if (diff < minute) return 'now'
1087
+ if (diff < hour) return `${Math.round(diff / minute)}m`
1088
+ if (diff < day) return `${Math.round(diff / hour)}h`
1089
+ if (diff < day * 30) return `${Math.round(diff / day)}d`
1090
+ return new Date(value).toLocaleDateString()
1091
+ }
1092
+
1093
+ function dayLabel(ms) {
1094
+ const value = Number(ms)
1095
+ if (!Number.isFinite(value) || value <= 0) return '—'
1096
+ try {
1097
+ return new Date(value).toLocaleDateString(undefined, { month: '2-digit', day: '2-digit' })
1098
+ } catch {
1099
+ return new Date(value).toLocaleDateString()
1100
+ }
1101
+ }
1102
+
1103
+ function fullTime(ms) {
1104
+ const value = Number(ms)
1105
+ if (!Number.isFinite(value) || value <= 0) return '—'
1106
+ try {
1107
+ return new Date(value).toLocaleString()
1108
+ } catch {
1109
+ return '—'
1110
+ }
1111
+ }
1112
+
1113
+ function useElementWidth(ref, fallback) {
1114
+ const [width, setWidth] = useState(fallback)
1115
+ useEffect(() => {
1116
+ const node = ref.current
1117
+ if (!node) return undefined
1118
+ const read = () => {
1119
+ const next = node.getBoundingClientRect().width
1120
+ if (Number.isFinite(next) && next > 0) setWidth(Math.round(next))
1121
+ }
1122
+ read()
1123
+ if (typeof ResizeObserver === 'undefined') return undefined
1124
+ const observer = new ResizeObserver(read)
1125
+ observer.observe(node)
1126
+ return () => observer.disconnect()
1127
+ }, [ref, fallback])
1128
+ return width
1129
+ }
1130
+
395
1131
  const SUPPORTED = ['zh', 'en', 'ja', 'es', 'fr', 'de', 'ru', 'pt']
396
1132
 
397
1133
  function useLocale(payload) {
@@ -498,69 +1234,371 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
498
1234
 
499
1235
  // ------------------------------------------------------------ atoms
500
1236
 
501
- function Switch({ on, disabled, onChange, title }) {
1237
+ function Dot({ channel }) {
1238
+ return h('i', { style: { background: COLOR[channel] || '#94a3b8' }, 'aria-hidden': 'true' })
1239
+ }
1240
+
1241
+ // A trend line is decoration unless it says what it ranges over: the
1242
+ // title carries min/max and the SVG carries an accessible label.
1243
+ function Sparkline({ values, width, height, label }) {
1244
+ if (!Array.isArray(values) || values.length < 2) return null
1245
+ const max = Math.max(...values)
1246
+ const min = Math.min(...values)
1247
+ const span = max - min || 1
1248
+ const step = width / (values.length - 1)
1249
+ const points = values
1250
+ .map((value, index) => `${(index * step).toFixed(1)},${(height - ((value - min) / span) * (height - 4) - 2).toFixed(1)}`)
1251
+ .join(' ')
502
1252
  return h(
503
- 'button',
1253
+ 'svg',
504
1254
  {
505
- type: 'button',
506
- className: 'ci-switch' + (on ? ' on' : ''),
507
- role: 'switch',
508
- 'aria-checked': on ? 'true' : 'false',
509
- 'aria-label': title || '',
510
- title: title || '',
511
- disabled: disabled === true,
512
- onClick: () => {
513
- if (disabled !== true) onChange(!on)
514
- },
1255
+ className: 'ci-spark',
1256
+ viewBox: `0 0 ${width} ${height}`,
1257
+ preserveAspectRatio: 'none',
1258
+ role: 'img',
1259
+ 'aria-label': label || '',
515
1260
  },
516
- h('span', null),
1261
+ h('polyline', {
1262
+ points,
1263
+ fill: 'none',
1264
+ stroke: 'var(--ci-accent)',
1265
+ strokeWidth: 1.5,
1266
+ strokeLinejoin: 'round',
1267
+ strokeLinecap: 'round',
1268
+ vectorEffect: 'non-scaling-stroke',
1269
+ }),
517
1270
  )
518
1271
  }
519
1272
 
520
- function Dot({ channel }) {
521
- return h('i', { style: { background: COLOR[channel] || '#94a3b8' }, 'aria-hidden': 'true' })
1273
+ function Donut({ rows, t, size, centerLabel, centerSub, ariaLabel }) {
1274
+ const list = Array.isArray(rows) ? rows : []
1275
+ const total = list.reduce((sum, row) => sum + (Number(row.tokens) || 0), 0)
1276
+ const safe = total || 1
1277
+ const radius = 52
1278
+ const circumference = 2 * Math.PI * radius
1279
+ let offset = 0
1280
+ const segments = list
1281
+ .filter((row) => (Number(row.tokens) || 0) > 0)
1282
+ .map((row) => {
1283
+ const length = ((Number(row.tokens) || 0) / safe) * circumference
1284
+ const segment = h('circle', {
1285
+ key: row.id,
1286
+ cx: 66,
1287
+ cy: 66,
1288
+ r: radius,
1289
+ fill: 'none',
1290
+ stroke: COLOR[row.id] || 'var(--ci-fg3)',
1291
+ strokeWidth: 13,
1292
+ strokeDasharray: `${Math.max(0, length - 1.5)} ${circumference - Math.max(0, length - 1.5)}`,
1293
+ strokeDashoffset: -offset,
1294
+ transform: 'rotate(-90 66 66)',
1295
+ })
1296
+ offset += length
1297
+ return segment
1298
+ })
1299
+ return h(
1300
+ 'svg',
1301
+ {
1302
+ className: 'ci-donut-svg',
1303
+ viewBox: '0 0 132 132',
1304
+ width: size || 120,
1305
+ height: size || 120,
1306
+ role: 'img',
1307
+ 'aria-label': ariaLabel || `${t('total')} ${token(total)}`,
1308
+ },
1309
+ h('title', null, ariaLabel || `${t('total')} ${token(total)}`),
1310
+ h('circle', { cx: 66, cy: 66, r: radius, fill: 'none', stroke: 'var(--ci-line2)', strokeWidth: 13 }),
1311
+ segments,
1312
+ h('text', { x: 66, y: centerSub === undefined ? 64 : 62, textAnchor: 'middle', className: 'ci-donut-v' }, token(total)),
1313
+ h('text', { x: 66, y: centerSub === undefined ? 81 : 79, textAnchor: 'middle', className: 'ci-donut-k' }, centerLabel || t('total')),
1314
+ centerSub === undefined ? null : h('text', { x: 66, y: 94, textAnchor: 'middle', className: 'ci-donut-k' }, centerSub),
1315
+ )
1316
+ }
1317
+
1318
+ // Skills are the reason people end up needing this plugin: a collected
1319
+ // catalog sits in every request. This card is the "why is my prompt so
1320
+ // big" answer, and its button jumps straight to that channel.
1321
+ function SkillsFocus({ snapshot, t, onFilter }) {
1322
+ const state = snapshot.skillsState
1323
+ if (state === undefined || state === null || !Number.isFinite(state.catalogTokens)) return null
1324
+ if ((state.total ?? 0) === 0) return null
1325
+ const heaviest = state.heaviest
1326
+ const rows = (state.topProviders ?? []).slice(0, 3)
1327
+ const providerMax = rows.reduce((max, row) => Math.max(max, row.tokens), 1)
1328
+ // Skills are one kind of line item; tool schemas are another. Saying
1329
+ // both on the same card is what stops "my skills are only 3k, so why is
1330
+ // the prompt 84k" from being a question in the first place.
1331
+ const kinds = (state.kinds ?? []).filter((kind) => kind.tokens > 0)
1332
+ // "tool schemas" is not a skill: say it on the card so a 3k skill block
1333
+ // next to a 84k prompt does not read as a contradiction.
1334
+ const labels = { skills: t('skills'), tools: t('tools'), prompts: t('sections'), rules: t('instructions') }
1335
+ const toolsKind = (state.kinds ?? []).find((kind) => kind.id === 'tools')
1336
+ const topTools = (snapshot.groups ?? []).filter((group) => group.channel === 'tools')[0]
1337
+ return h(
1338
+ 'div',
1339
+ { className: 'ci-card ci-skills' },
1340
+ h(
1341
+ 'div',
1342
+ { className: 'ci-skills-head' },
1343
+ h('div', { className: 'ci-skills-num' }, h('b', null, String(state.total)), h('span', null, t('skillsUnit'))),
1344
+ h(
1345
+ 'div',
1346
+ { className: 'ci-skills-text' },
1347
+ h('div', { className: 'k' }, t('skillsCallout')),
1348
+ h(
1349
+ 'div',
1350
+ { className: 's' },
1351
+ t('skillsLine', {
1352
+ tokens: token(state.catalogTokens),
1353
+ share: state.catalogShare,
1354
+ avg: token(state.averageTokens ?? 0),
1355
+ providers: state.providers ?? 0,
1356
+ }),
1357
+ ),
1358
+ ),
1359
+ h(
1360
+ 'button',
1361
+ { type: 'button', className: 'ci-btn', onClick: () => onFilter('skills'), title: t('skillsJump') },
1362
+ t('skillsManage'),
1363
+ ),
1364
+ ),
1365
+ kinds.length > 0
1366
+ ? h(
1367
+ 'div',
1368
+ { className: 'ci-kinds' },
1369
+ h('span', { className: 'lbl' }, t('kindsLabel')),
1370
+ kinds.map((kind) =>
1371
+ h(
1372
+ 'button',
1373
+ {
1374
+ key: kind.id,
1375
+ type: 'button',
1376
+ className: 'ci-kind' + (kind.id === 'skills' ? ' on' : ''),
1377
+ 'aria-pressed': kind.id === 'skills' ? 'true' : 'false',
1378
+ title: `${labels[kind.id] ?? kind.id} · ${kind.count} ${t('items')} · ${digits(kind.tokens)} token`,
1379
+ onClick: () => onFilter(kind.id),
1380
+ },
1381
+ labels[kind.id] ?? t(kind.id),
1382
+ h('b', null, token(kind.tokens)),
1383
+ h('span', { className: 'p' }, `${kind.share}%`),
1384
+ ),
1385
+ ),
1386
+ )
1387
+ : null,
1388
+ rows.length > 0
1389
+ ? h(
1390
+ 'div',
1391
+ { className: 'ci-skills-providers' },
1392
+ rows.map((row) =>
1393
+ h(
1394
+ 'button',
1395
+ {
1396
+ type: 'button',
1397
+ className: 'ci-skills-provider',
1398
+ key: row.provider,
1399
+ title: `${row.provider} · ${row.count} ${t('items')} · ${digits(row.tokens)} token`,
1400
+ onClick: () => onFilter('skills'),
1401
+ },
1402
+ h('span', { className: 'n' }, row.provider),
1403
+ h('span', { className: 'ci-bar-track' }, h('span', { className: 'ci-bar-fill', style: { width: `${Math.max(3, (row.tokens / providerMax) * 100)}%`, background: COLOR.skills } })),
1404
+ h('span', { className: 't' }, `${row.count} · ${token(row.tokens)}`),
1405
+ ),
1406
+ ),
1407
+ )
1408
+ : null,
1409
+ state.truncated > 0
1410
+ ? h('div', { className: 'ci-skills-note' }, t('truncatedHint', { count: state.truncated }))
1411
+ : null,
1412
+ heaviest !== null && heaviest !== undefined
1413
+ ? h('div', { className: 'ci-skills-note' }, t('heaviestSkill', { name: heaviest.name, tokens: token(heaviest.tokens) }))
1414
+ : null,
1415
+ toolsKind !== undefined && toolsKind.tokens > state.catalogTokens
1416
+ ? h(
1417
+ 'div',
1418
+ { className: 'ci-skills-note' },
1419
+ t('kindsNote', {
1420
+ tools: token(toolsKind.tokens),
1421
+ top: topTools === undefined ? '—' : topTools.label,
1422
+ topTokens: topTools === undefined ? '—' : token(topTools.tokens),
1423
+ }),
1424
+ )
1425
+ : null,
1426
+ )
522
1427
  }
523
1428
 
524
- function Kpis({ snapshot, t }) {
1429
+ function Kpis({ snapshot, t, trend }) {
525
1430
  const totals = snapshot.totals
526
1431
  const policy = snapshot.policy
1432
+ const view = snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals : totals
1433
+ const context = snapshot.context || null
1434
+ const trendValues = (trend || []).map((point) => point.v)
1435
+ const windowKnown = context !== null && context.window !== null && context.used !== null
1436
+ const budget = Number(policy.budget && policy.budget.tokens) || 0
1437
+ const overBudget = budget > 0 && view.tokens > budget
527
1438
  const rows = [
528
- { key: 'total', value: token(totals.tokens), sub: `${digits(totals.chars)} ${t('chars')} · ${snapshot.items.length} ${t('items')}` },
529
- { key: 'savable', value: token(totals.savableTokens), sub: `${totals.savablePercent}% · ${t('shareOf')}` },
530
- { key: 'after', value: token(policy.preview.after), sub: `${policy.preview.savedPercent > 0 ? `−${policy.preview.savedPercent}% · ` : ''}${presetLabel(t, policy.preset)}` },
531
1439
  {
532
- key: 'anchor',
533
- value: totals.anchor === null ? '—' : token(totals.anchor.tokens),
1440
+ key: 'total',
1441
+ value: token(view.tokens),
1442
+ sub: `${digits(view.chars)} ${t('chars')} · ${view.count === undefined ? snapshot.items.length : view.count} ${t('items')}`,
1443
+ spark: true,
1444
+ },
1445
+ {
1446
+ key: 'window',
1447
+ value: windowKnown
1448
+ ? h(
1449
+ 'span',
1450
+ { className: 'ci-kpi-num' },
1451
+ h('span', null, token(context.used)),
1452
+ h('span', { className: 'u' }, '/'),
1453
+ h('span', { className: 'u' }, token(context.window)),
1454
+ )
1455
+ : '—',
1456
+ sub: windowKnown ? `${context.occupancy}% · ${t('remain')} ${token(context.remaining)}` : t('noWindow'),
1457
+ tone: windowKnown && context.tone !== undefined ? context.tone : 'unknown',
1458
+ title: windowKnown ? t('v2.windowHint2') : t('noWindowHint'),
1459
+ },
1460
+ {
1461
+ key: 'savable',
1462
+ value: token(view.savableTokens),
1463
+ sub: `${view.savablePercent}% · ${t('shareOf')}`,
1464
+ },
1465
+ {
1466
+ key: 'budget',
1467
+ value: budget > 0 ? token(budget) : '—',
534
1468
  sub:
535
- totals.anchor === null
536
- ? t('anchorHint')
537
- : t('ofSession', { pct: pct(totals.tokens, totals.anchor.tokens) }),
1469
+ budget > 0
1470
+ ? overBudget
1471
+ ? t('v2.budgetOver', { tokens: token(view.tokens - budget) })
1472
+ : t('v2.budgetUnder', { tokens: token(budget - view.tokens) })
1473
+ : t('v2.noBudget'),
1474
+ tone: overBudget ? 'danger' : undefined,
1475
+ title: t('budgetHint'),
538
1476
  },
539
1477
  ]
1478
+ const sparkLabel = trendValues.length > 1 ? t('trendLabel', { min: token(Math.min(...trendValues)), max: token(Math.max(...trendValues)) }) : ''
540
1479
  return h(
541
1480
  'div',
542
1481
  { className: 'ci-kpis' },
543
1482
  rows.map((row) =>
544
1483
  h(
545
1484
  'div',
546
- { className: 'ci-kpi', key: row.key },
1485
+ { className: 'ci-kpi' + (row.tone && row.tone !== 'ok' && row.tone !== 'unknown' ? ` tone-${row.tone}` : ''), key: row.key, title: row.title || null },
547
1486
  h('div', { className: 'k' }, t(row.key)),
548
1487
  h('div', { className: 'v' }, row.value),
1488
+ row.spark ? h(Sparkline, { values: trendValues, width: 200, height: 18, label: sparkLabel }) : null,
549
1489
  h('div', { className: 's', title: row.sub }, row.sub),
550
1490
  ),
551
1491
  ),
552
1492
  )
553
1493
  }
554
1494
 
1495
+ // Where the money actually goes: the next request measured against the
1496
+ // model's window, split the way the host splits it. One line, not a card:
1497
+ // the headline percentage already lives in the KPI above it, and a nearly
1498
+ // empty bar inside a tall card read as wasted space.
1499
+ function RequestStrip({ snapshot, t }) {
1500
+ const context = snapshot.context
1501
+ if (context === undefined || context === null) return null
1502
+ const windowKnown = context.window !== null && context.used !== null
1503
+ const breakdown = context.breakdown
1504
+ const compaction = context.compaction || null
1505
+ const hasCompaction = compaction !== null && (compaction.count > 0 || compaction.prunes > 0)
1506
+ if (!windowKnown && breakdown === null && !hasCompaction) return null
1507
+
1508
+ const window = windowKnown ? context.window : 0
1509
+ const segments = []
1510
+ if (windowKnown && breakdown !== null) {
1511
+ const parts = [
1512
+ ['system', breakdown.system],
1513
+ ['tools', breakdown.tools],
1514
+ ['messages', breakdown.messages],
1515
+ ]
1516
+ let usedByParts = 0
1517
+ for (const [key, value] of parts) {
1518
+ usedByParts += value
1519
+ segments.push({ key, value: Math.min(value, window) })
1520
+ }
1521
+ // The breakdown is a heuristic and can exceed or fall short of the
1522
+ // provider figure; the leftover stays visible as unaccounted space.
1523
+ const leftover = Math.max(0, window - Math.min(window, usedByParts))
1524
+ if (leftover > 0) segments.push({ key: 'free', value: leftover })
1525
+ } else if (windowKnown) {
1526
+ segments.push({ key: 'used', value: context.used })
1527
+ segments.push({ key: 'free', value: Math.max(0, window - context.used) })
1528
+ } else if (breakdown !== null) {
1529
+ // No capacity yet, but the composition is still measured: scale the
1530
+ // bar to the request itself instead of drawing an empty window.
1531
+ segments.push({ key: 'system', value: breakdown.system })
1532
+ segments.push({ key: 'tools', value: breakdown.tools })
1533
+ segments.push({ key: 'messages', value: breakdown.messages })
1534
+ }
1535
+ const sum = segments.reduce((total, segment) => total + segment.value, 0) || 1
1536
+
1537
+ return h(
1538
+ 'div',
1539
+ { className: 'ci-strip' + (context.tone && context.tone !== 'ok' && context.tone !== 'unknown' ? ` tone-${context.tone}` : '') },
1540
+ h('span', { className: 'k' }, t('requestComposition')),
1541
+ segments.length > 1
1542
+ ? h(
1543
+ 'span',
1544
+ { className: 'ci-window-bar', role: 'img', 'aria-label': windowKnown ? t('windowBarLabel', { pct: context.occupancy }) : t('requestComposition') },
1545
+ segments.map((segment) =>
1546
+ h('span', {
1547
+ key: segment.key,
1548
+ style: { width: `${Math.max(1, (segment.value / sum) * 100)}%`, background: WINDOW_COLOR[segment.key] || 'var(--ci-line2)' },
1549
+ }),
1550
+ ),
1551
+ )
1552
+ : null,
1553
+ h(
1554
+ 'span',
1555
+ { className: 'rt', title: windowKnown ? t('windowHint') : t('noWindowHint') },
1556
+ windowKnown ? `${t('remain')} ${token(context.remaining)} (${context.occupancy}%)` : t('noWindow'),
1557
+ ),
1558
+ breakdown !== null
1559
+ ? h(
1560
+ 'span',
1561
+ { className: 'lg' },
1562
+ [
1563
+ ['system', t('systemPart'), breakdown.system],
1564
+ ['tools', t('toolsPart'), breakdown.tools],
1565
+ ['messages', t('messagesPart'), breakdown.messages],
1566
+ ].map(([key, label, value]) =>
1567
+ h(
1568
+ 'span',
1569
+ { className: 'item', key, title: `${label} · ${digits(value)} token` },
1570
+ h('i', { 'aria-hidden': 'true', style: { background: WINDOW_COLOR[key] } }),
1571
+ label,
1572
+ ' ',
1573
+ h('b', null, token(value)),
1574
+ ),
1575
+ ),
1576
+ )
1577
+ : null,
1578
+ hasCompaction
1579
+ ? h(
1580
+ 'span',
1581
+ { className: 'rt', title: t('compactionHint') },
1582
+ t('compactionLine', { count: compaction.count + compaction.prunes, saved: token(compaction.saved) }),
1583
+ )
1584
+ : null,
1585
+ compaction !== null && compaction.failures > 0 ? h('span', { className: 'rt warn' }, t('compactionFailed', { count: compaction.failures })) : null,
1586
+ )
1587
+ }
1588
+
1589
+ // First-turn injection by channel. Labelled, because the window card
1590
+ // above it is also a bar and two unlabelled bars read as one control.
555
1591
  function Composition({ snapshot, t, filter, onFilter }) {
556
- const total = snapshot.totals.tokens || 1
1592
+ const channels = snapshot.effective && snapshot.effective.channels ? snapshot.effective.channels : snapshot.channels
1593
+ const total = (snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals.tokens : snapshot.totals.tokens) || 1
557
1594
  return h(
558
1595
  'div',
559
- null,
1596
+ { className: 'ci-composition' },
1597
+ h('div', { className: 'ci-window-head' }, h('h2', null, t('injectionComposition'))),
560
1598
  h(
561
1599
  'div',
562
1600
  { className: 'ci-bar' },
563
- snapshot.channels
1601
+ channels
564
1602
  .filter((channel) => channel.tokens > 0)
565
1603
  .map((channel) =>
566
1604
  h('span', {
@@ -573,7 +1611,7 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
573
1611
  h(
574
1612
  'div',
575
1613
  { className: 'ci-legend' },
576
- snapshot.channels.map((channel) =>
1614
+ channels.map((channel) =>
577
1615
  h(
578
1616
  'button',
579
1617
  {
@@ -586,7 +1624,7 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
586
1624
  t(channel.id),
587
1625
  ' ',
588
1626
  h('b', null, token(channel.tokens)),
589
- ` · ${pct(channel.tokens, snapshot.totals.tokens)}%`,
1627
+ ` · ${pctText(channel.tokens, total)}`,
590
1628
  ),
591
1629
  ),
592
1630
  ),
@@ -703,37 +1741,136 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
703
1741
  return [value.slice(0, at), h('mark', { className: 'ci-hit', key: 'hit' }, value.slice(at, at + needle.length)), value.slice(at + needle.length)]
704
1742
  }
705
1743
 
706
- function ItemRow({ item, t, snapshot, isOn, onToggle, busy, nested, needle, planned }) {
1744
+ // Shares are always of the injection that will actually happen: the
1745
+ // effective total, not the all-on one. Under an old policy the two differ
1746
+ // by 5×, and a percentage of the wrong denominator is how "REA 79.6%"
1747
+ // ended up sitting next to a 17k total.
1748
+ function effectiveTotalOf(snapshot) {
1749
+ return Math.max(1, (snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals.tokens : snapshot.totals.tokens) || 1)
1750
+ }
1751
+
1752
+ function ItemRow({ item, t, snapshot, isOn, onToggle, busy, nested, needle, planned, previewOpen, onPreview }) {
707
1753
  const label = nameOf(t, item)
708
1754
  const locked = item.locked === true
709
1755
  const showRaw = !snapshot.settings || snapshot.settings.showRawNames !== false
1756
+ const on = isOn(item)
710
1757
  return h(
711
1758
  'div',
712
- { className: 'ci-row' + (locked ? ' locked' : '') + (nested === true ? ' ci-row-nested' : ''), key: itemKey(item) },
1759
+ { className: 'ci-row' + (locked ? ' locked' : '') + (nested === true ? ' ci-row-nested' : '') + (on ? '' : ' ci-row-off'), key: itemKey(item) },
713
1760
  h(
714
1761
  'div',
715
1762
  { className: 'n', title: `${item.name} · ${item.tokens} token` },
1763
+ onPreview === undefined
1764
+ ? null
1765
+ : h(
1766
+ 'button',
1767
+ {
1768
+ type: 'button',
1769
+ className: 'ci-caret-btn',
1770
+ 'aria-expanded': previewOpen === true ? 'true' : 'false',
1771
+ 'aria-label': previewOpen === true ? t('v2.collapsePreview') : t('v2.expandPreview'),
1772
+ title: previewOpen === true ? t('v2.collapsePreview') : t('v2.expandPreview'),
1773
+ onClick: (event) => {
1774
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1775
+ onPreview(item)
1776
+ },
1777
+ },
1778
+ '▸',
1779
+ ),
716
1780
  h(HitMark, { text: label, needle }),
717
1781
  planned ? h('span', { className: 'ci-tag', title: t('outsideBudgetHint') }, t('outsideBudget')) : null,
1782
+ !on && !locked ? h('span', { className: 'ci-tag' }, t('turnedOff')) : null,
1783
+ item.offClosed === true ? h('span', { className: 'ci-tag ci-tag-closed', title: t('closedRestoreHint') }, t('closedBadge')) : null,
718
1784
  showRaw && label !== item.name ? h('span', { className: 'id' }, item.name) : null,
719
1785
  ),
1786
+ h('div', { className: 'ci-about', title: typeof item.preview === 'string' ? item.preview : '' }, typeof item.preview === 'string' ? item.preview : ''),
720
1787
  h('div', { className: 'badge' }, h(Dot, { channel: item.channel }), t(item.channel)),
721
1788
  h('div', { className: 'num' }, digits(item.tokens)),
722
- h('div', { className: 'num' }, `${pct(item.tokens, snapshot.totals.tokens)}%`),
1789
+ h('div', { className: 'num' }, on ? `${pctText(item.tokens, effectiveTotalOf(snapshot))}` : '—'),
723
1790
  locked
724
1791
  ? h('span', { className: 'ci-lock', title: t('lockedHint') }, t('locked'))
725
- : h(Switch, { on: isOn(item), disabled: busy, onChange: (next) => onToggle(item, next), title: item.name }),
1792
+ : h(Switch, { on, disabled: busy, onChange: (next) => onToggle(item, next), title: item.name }),
1793
+ )
1794
+ }
1795
+
1796
+ // The inline preview answers "what is this row" before the drawer has to
1797
+ // load 200KB over the wire; the drawer is still the only place with the
1798
+ // full text. Pure text, never HTML.
1799
+ function ItemPreview({ item, snapshot, t, onOpenContent }) {
1800
+ const preview = typeof item.preview === 'string' && item.preview.trim().length > 0 ? item.preview : null
1801
+ return h(
1802
+ 'div',
1803
+ { className: 'ci-row-preview', role: 'group', 'aria-label': `${t('v2.previewLabel')} · ${item.name}` },
1804
+ h('p', { className: 'pv' }, preview === null ? t('v2.noPreview') : preview),
1805
+ h(
1806
+ 'div',
1807
+ { className: 'meta' },
1808
+ h(Dot, { channel: item.channel }),
1809
+ h('span', null, t(item.channel)),
1810
+ h('span', null, `${digits(item.tokens)} ${t('tokens')}`),
1811
+ h('span', null, `${pctText(item.tokens, effectiveTotalOf(snapshot))}`),
1812
+ item.locked === true ? h('span', { className: 'ci-badge' }, t('locked')) : null,
1813
+ ),
1814
+ onOpenContent === undefined
1815
+ ? null
1816
+ : h('div', { className: 'actions' }, h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: () => onOpenContent(item) }, t('v2.openContent'))),
726
1817
  )
727
1818
  }
728
1819
 
729
- function ItemsTable({ snapshot, t, filter, setFilter, onToggle, onGroup, onUndo, busy, act }) {
1820
+ // Where a list entry comes from. The policy is a *default for new
1821
+ // sessions*, not the state of the running one: an already-open session
1822
+ // keeps injecting everything until it is recreated (the host never
1823
+ // rewrites a live assembly), which is exactly what the user sees in the
1824
+ // transcript. Two scopes, two questions, no guessing:
1825
+ // 默认策略 — what a session created now would receive (classic view)
1826
+ // 本会话 — what the session on screen is actually sending right now
1827
+ function buildItems(snapshot, filter, scope) {
1828
+ const policyOn = (item) => {
1829
+ const channel = snapshot.policy.channels[item.channel]
1830
+ if (channel === undefined || channel.mode === 'all') return true
1831
+ if (channel.mode === 'only') return channel.names.indexOf(item.name) >= 0
1832
+ return channel.names.indexOf(item.name) < 0
1833
+ }
1834
+
1835
+ const rows = snapshot.items.map((item) => ({
1836
+ ...item,
1837
+ // The host now stamps items[].on; prefer it when present so the list
1838
+ // and the ranking agree with the effective projection exactly.
1839
+ on: scope === 'session' ? true : typeof item.on === 'boolean' ? item.on : policyOn(item),
1840
+ used: true,
1841
+ }))
1842
+ // A closed item keeps its remembered size so it can be switched back
1843
+ // from the same list instead of from a separate card — the classic
1844
+ // "I closed REA and now I cannot open it again" trap.
1845
+ for (const item of snapshot.closed || []) {
1846
+ if (item.unknown === true) continue
1847
+ rows.push({ ...item, locked: false, on: scope === 'session' ? true : false, used: false, offClosed: true })
1848
+ }
1849
+ return rows.filter((item) => filter === 'all' || item.channel === filter)
1850
+ }
1851
+
1852
+ function ItemsTable({ snapshot, t, filter, setFilter, onToggle, onGroup, onUndo, busy, act, v2, onOpenContent }) {
730
1853
  const [query, setQuery] = useState('')
731
1854
  const [view, setView] = useStoredState('view', 'group')
1855
+ const [scope, setScope] = useStoredState('scope', 'global')
732
1856
  const [onlySwitchable, setOnlySwitchable] = useStoredState('onlySwitchable', false)
733
- const [sort, setSort] = useStoredState('itemSort', 'tokens')
1857
+ const [sort, setSort] = useStoredState('itemSort', 'tokens:desc')
1858
+ const [sortKey, sortDir] = String(sort).split(':')
734
1859
  const [expanded, setExpanded] = useState({})
1860
+ const [peek, setPeek] = useState({})
1861
+ const [suite, setSuite] = useState(null)
735
1862
  const deferredQuery = useDeferredValue(query)
736
1863
  const searchRef = useRef(null)
1864
+ const clearAllFilters = () => {
1865
+ setQuery('')
1866
+ setFilter('all')
1867
+ setOnlySwitchable(false)
1868
+ setSuite(null)
1869
+ }
1870
+ const togglePeek = (item) => {
1871
+ const key = itemKey(item)
1872
+ setPeek((previous) => ({ ...previous, [key]: previous[key] !== true }))
1873
+ }
737
1874
 
738
1875
  // "/" jumps to search unless the user is already typing somewhere.
739
1876
  useEffect(() => {
@@ -757,48 +1894,66 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
757
1894
  const items = useMemo(() => {
758
1895
  const needle = deferredQuery.trim().toLowerCase()
759
1896
  const names = t.names || {}
760
- return snapshot.items
761
- .filter((item) => filter === 'all' || item.channel === filter)
1897
+ return buildItems(snapshot, filter, scope)
762
1898
  .filter((item) => (onlySwitchable ? item.locked !== true : true))
1899
+ .filter((item) => (suite === null ? true : String(item.groupLabel !== undefined && item.groupLabel !== null ? item.groupLabel : item.group) === suite))
763
1900
  .filter((item) => {
764
1901
  if (needle.length === 0) return true
765
1902
  const label = names[item.name] || NAMES_ZH[item.name] || ''
766
1903
  return item.name.toLowerCase().indexOf(needle) >= 0 || label.toLowerCase().indexOf(needle) >= 0
767
1904
  })
768
1905
  .slice()
769
- .sort((left, right) =>
770
- sort === 'name' ? left.name.localeCompare(right.name) : right.tokens - left.tokens || left.name.localeCompare(right.name),
771
- )
772
- }, [snapshot.items, filter, onlySwitchable, deferredQuery, t])
1906
+ .sort((left, right) => {
1907
+ const compare =
1908
+ sortKey === 'name'
1909
+ ? left.name.localeCompare(right.name)
1910
+ : sortKey === 'channel'
1911
+ ? left.channel.localeCompare(right.channel) || left.name.localeCompare(right.name)
1912
+ : left.tokens - right.tokens || left.name.localeCompare(right.name)
1913
+ return sortDir === 'asc' ? compare : -compare
1914
+ })
1915
+ }, [snapshot, filter, scope, onlySwitchable, deferredQuery, t, sortKey, sortDir, suite])
773
1916
 
774
- const isOn = (item) => {
775
- const channel = snapshot.policy.channels[item.channel]
776
- if (channel === undefined || channel.mode === 'all') return true
777
- if (channel.mode === 'only') return channel.names.indexOf(item.name) >= 0
778
- return channel.names.indexOf(item.name) < 0
779
- }
1917
+ // In the session scope nothing is blocked by the policy: the running
1918
+ // session already has it all, so every row reads as on.
1919
+ const isOn = (item) => (scope === 'session' ? true : item.on === true)
780
1920
 
781
1921
  const groups = useMemo(() => {
782
1922
  const map = new Map()
783
1923
  for (const item of items) {
784
- const entry = map.get(item.group) ?? {
785
- id: item.group,
1924
+ // Same suite may own items in several channels (REA's tools plus its
1925
+ // prompt section); merge by label so it reads as one switch.
1926
+ const key = String(item.groupLabel ?? item.group).toLowerCase()
1927
+ const entry = map.get(key) ?? {
1928
+ id: key,
786
1929
  channel: item.channel,
787
1930
  label: item.groupLabel,
1931
+ channels: [],
1932
+ parts: [],
788
1933
  items: [],
789
1934
  tokens: 0,
790
1935
  savableTokens: 0,
791
1936
  }
1937
+ if (!entry.channels.includes(item.channel)) entry.channels.push(item.channel)
1938
+ if (!entry.parts.some((part) => part.channel === item.channel && part.group === item.group)) {
1939
+ entry.parts.push({ channel: item.channel, group: item.group })
1940
+ }
792
1941
  entry.items.push(item)
793
1942
  entry.tokens += item.tokens
794
1943
  if (!item.locked) entry.savableTokens += item.tokens
795
- map.set(item.group, entry)
1944
+ map.set(key, entry)
796
1945
  }
797
1946
  const rows = [...map.values()]
798
- return rows.sort((left, right) =>
799
- sort === 'name' ? String(left.label).localeCompare(String(right.label)) : right.tokens - left.tokens,
800
- )
801
- }, [items, sort])
1947
+ return rows.sort((left, right) => {
1948
+ const compare =
1949
+ sortKey === 'name'
1950
+ ? String(left.label).localeCompare(String(right.label))
1951
+ : sortKey === 'channel'
1952
+ ? String(left.channel).localeCompare(String(right.channel)) || left.tokens - right.tokens
1953
+ : left.tokens - right.tokens || String(left.label).localeCompare(String(right.label))
1954
+ return sortDir === 'asc' ? compare : -compare
1955
+ })
1956
+ }, [items, sortKey, sortDir, sort])
802
1957
 
803
1958
  const groupState = (group) => {
804
1959
  const unlocked = group.items.filter((item) => !item.locked)
@@ -807,6 +1962,24 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
807
1962
  return { on: onCount === unlocked.length, mixed: onCount > 0 && onCount < unlocked.length, disabled: false }
808
1963
  }
809
1964
 
1965
+ // In each scope, a suite whose rows are mixed or missing needs a
1966
+ // different repair: the session scope can add back a suite the policy
1967
+ // closed, but only by the exact channel:name rows the policy excludes —
1968
+ // so the restore reads the excluded names back from the policy itself
1969
+ // instead of guessing from labels.
1970
+ function closedNamesFor(snapshot, label) {
1971
+ const wanted = String(label).toLowerCase()
1972
+ const out = []
1973
+ for (const [channel, state] of Object.entries(snapshot.policy.channels || {})) {
1974
+ if (state.mode !== 'except') continue
1975
+ for (const name of state.names) {
1976
+ const labelOf = (name) => (/^mcp:([^:]+)$/.exec(name) || /^mcp__([^_]+(?:_[^_]+)*?)__/.exec(name) || []).at(1)
1977
+ if (String(labelOf(name) || name).toLowerCase() === wanted) out.push({ channel, name })
1978
+ }
1979
+ }
1980
+ return out
1981
+ }
1982
+
810
1983
  const toggleGroup = (group) => {
811
1984
  const state = groupState(group)
812
1985
  if (state.disabled) return
@@ -815,216 +1988,1844 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
815
1988
 
816
1989
  const toggleExpanded = (id) => setExpanded((previous) => ({ ...previous, [id]: previous[id] !== true }))
817
1990
 
1991
+ const sortHeader = (key, label, alignRight) => {
1992
+ const active = sortKey === key
1993
+ const nextDir = active ? (sortDir === 'asc' ? 'desc' : 'asc') : key === 'name' || key === 'channel' ? 'asc' : 'desc'
1994
+ return h(
1995
+ 'button',
1996
+ {
1997
+ type: 'button',
1998
+ className: 'ci-sort' + (active ? ' active' : ''),
1999
+ style: alignRight ? { justifyContent: 'flex-end' } : null,
2000
+ 'aria-sort': active ? (sortDir === 'asc' ? 'ascending' : 'descending') : 'none',
2001
+ title: `${label} · ${t('sortHint')}`,
2002
+ onClick: () => setSort(key + ':' + nextDir),
2003
+ },
2004
+ label,
2005
+ h('span', { className: 'ci-arrow', 'aria-hidden': 'true' }, active ? (sortDir === 'asc' ? '▲' : '▼') : '↕'),
2006
+ )
2007
+ }
2008
+
2009
+ const effective = snapshot.effective && snapshot.effective.channels ? snapshot.effective.channels : snapshot.channels
2010
+ const effectiveTotal = Math.max(1, (snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals.tokens : snapshot.totals.tokens) || 1)
2011
+ const viewSavablePercent = snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals.savablePercent : snapshot.totals.savablePercent
2012
+ // The ranking above the list is about the whole snapshot, never about
2013
+ // the current filter: filtering the table must not hide the big suites.
2014
+ const topSuites = (() => {
2015
+ const map = new Map()
2016
+ for (const group of snapshot.groups) {
2017
+ const label = String(group.label !== undefined && group.label !== null ? group.label : group.id)
2018
+ const key = label.toLowerCase()
2019
+ const entry = map.get(key) || { id: key, label, channel: group.channel, tokens: 0, effectiveTokens: 0, items: [] }
2020
+ entry.tokens += Number(group.tokens) || 0
2021
+ map.set(key, entry)
2022
+ }
2023
+ for (const item of snapshot.items) {
2024
+ const key = String(item.groupLabel !== undefined && item.groupLabel !== null ? item.groupLabel : item.group).toLowerCase()
2025
+ const entry = map.get(key)
2026
+ if (entry === undefined) continue
2027
+ // Prefer the host's stamped on; fall back to the policy projection so
2028
+ // the ranking still works on a v1 snapshot without the field.
2029
+ const on = typeof item.on === 'boolean' ? item.on : policyItemOn(snapshot, item)
2030
+ if (on) entry.effectiveTokens += item.tokens
2031
+ }
2032
+ return [...map.values()].sort((left, right) => right.tokens - left.tokens).slice(0, 6)
2033
+ })()
2034
+ const suiteMax = topSuites.reduce((max, group) => Math.max(max, group.tokens), 1)
2035
+
818
2036
  return h(
819
2037
  'div',
820
2038
  { style: { display: 'flex', flexDirection: 'column', gap: 8, minHeight: 0, flex: '1 1 auto' } },
2039
+ // Two peer cards, not one mixed card: composition is a "what is in
2040
+ // here" question, the suite ranking is a "what should I switch off"
2041
+ // question. Each gets its own header and its own column.
821
2042
  h(
822
2043
  'div',
823
- { className: 'ci-toolbar' },
824
- h('input', {
825
- ref: searchRef,
826
- className: 'ci-input',
827
- placeholder: t('search'),
828
- value: query,
829
- onChange: (event) => setQuery(event.target.value),
830
- 'aria-label': t('search'),
831
- }),
832
- h(
833
- 'div',
834
- { className: 'ci-seg' },
835
- [
836
- ['group', t('group')],
837
- ['flat', t('flat')],
838
- ].map(([key, label]) => h('button', { key, type: 'button', className: view === key ? 'on' : '', onClick: () => setView(key) }, label)),
839
- ),
2044
+ { className: 'ci-manage-overview' },
840
2045
  h(
841
2046
  'div',
842
- { style: { display: 'flex', gap: 4, flexWrap: 'wrap' } },
843
- ['all'].concat(CHANNELS).map((channel) =>
2047
+ { className: 'ci-card ci-overview-card' },
2048
+ h(
2049
+ 'div',
2050
+ { className: 'ci-cardhead' },
2051
+ h('h2', null, t('v2.overviewComposition')),
2052
+ h('span', { className: 'sp' }),
2053
+ h('span', { className: 'hint' }, `${t('total')} ${token(effectiveTotal)}`),
2054
+ ),
2055
+ h(
2056
+ 'div',
2057
+ { className: 'ci-donut' },
2058
+ h(Donut, { rows: effective, t, size: 124, centerSub: `${viewSavablePercent}% ${t('savable')}` }),
844
2059
  h(
845
- 'button',
846
- { key: channel, type: 'button', className: 'ci-chip' + (filter === channel ? ' on' : ''), onClick: () => setFilter(channel) },
847
- channel === 'all' ? t('all') : t(channel),
2060
+ 'div',
2061
+ { className: 'ci-donut-legend' },
2062
+ effective
2063
+ .filter((channel) => channel.tokens > 0)
2064
+ .map((channel) =>
2065
+ h(
2066
+ 'div',
2067
+ { className: 'ci-donut-row', key: channel.id },
2068
+ h(Dot, { channel: channel.id }),
2069
+ h('span', { className: 'n' }, t(channel.id)),
2070
+ h('b', null, token(channel.tokens)),
2071
+ h('span', { className: 'p' }, `${pctText(channel.tokens, effectiveTotal)}`),
2072
+ ),
2073
+ ),
848
2074
  ),
849
2075
  ),
850
2076
  ),
2077
+ h(
2078
+ 'div',
2079
+ { className: 'ci-card ci-overview-card' },
2080
+ h(
2081
+ 'div',
2082
+ { className: 'ci-cardhead' },
2083
+ h('h2', null, t('v2.heaviestTitle')),
2084
+ h('span', { className: 'sp' }),
2085
+ h('span', { className: 'hint' }, `${t('topSuites')} · ${topSuites.length} · ${t('v2.closedLight')}`),
2086
+ ),
2087
+ h(
2088
+ 'div',
2089
+ { className: 'ci-bars' },
2090
+ topSuites.map((group, index) => {
2091
+ const closedTokens = Math.max(0, group.tokens - group.effectiveTokens)
2092
+ const onPercent = group.tokens > 0 ? Math.max(0, Math.min(100, (group.effectiveTokens / group.tokens) * 100)) : 0
2093
+ return h(
2094
+ 'button',
2095
+ {
2096
+ type: 'button',
2097
+ className: 'ci-barrow ci-barrow-btn' + (group.effectiveTokens === 0 ? ' off' : ''),
2098
+ key: group.id,
2099
+ title: `${groupLabelOf(t, group)} · ${t('total')} ${digits(group.tokens)} · ${t('after')} ${digits(group.effectiveTokens)} · ${t('v2.closedLight')}`,
2100
+ onClick: () => setSuite(groupLabelOf(t, group)),
2101
+ },
2102
+ h(
2103
+ 'span',
2104
+ { className: 'n' },
2105
+ groupLabelOf(t, group),
2106
+ ),
2107
+ // The track spans the suite's full (all-on) size; the solid
2108
+ // part is what stays on and the faded part is what the
2109
+ // policy switched off, so an all-off suite still reads as a
2110
+ // long bar instead of an empty rail.
2111
+ h(
2112
+ 'span',
2113
+ { className: 'ci-bar-track', style: { width: `${Math.max(2, (group.tokens / suiteMax) * 100)}%`, minWidth: 3 } },
2114
+ onPercent > 0
2115
+ ? h('span', { className: 'ci-bar-fill', style: { width: `${onPercent}%`, background: COLOR[group.channel] } })
2116
+ : null,
2117
+ closedTokens > 0
2118
+ ? h('span', { className: 'ci-bar-closed', style: { width: `${Math.max(3, 100 - onPercent)}%`, background: COLOR[group.channel] } })
2119
+ : null,
2120
+ ),
2121
+ h(
2122
+ 'span',
2123
+ { className: 't' },
2124
+ group.effectiveTokens === 0
2125
+ ? `${token(group.tokens)} · ${t('turnedOff')}`
2126
+ : `${token(group.effectiveTokens)} · ${pctText(group.effectiveTokens, effectiveTotal)}`,
2127
+ ),
2128
+ )
2129
+ }),
2130
+ ),
2131
+ ),
2132
+ ),
2133
+ // Two rows, not one: scope + search + view + the filter menu on top,
2134
+ // the active filters (when any) on a second line. Eight chips in a row
2135
+ // was the densest thing in the panel and none of them was the primary
2136
+ // action.
2137
+ h(
2138
+ 'div',
2139
+ { className: 'ci-toolbar' },
2140
+ h(
2141
+ // The default view answers "what does a new session get"; the
2142
+ // session view answers "what is this conversation actually
2143
+ // sending". A policy never rewrites a live session, so both are
2144
+ // true at once and the user must be able to see which is which.
2145
+ 'div',
2146
+ { className: 'ci-seg', role: 'tablist', 'aria-label': t('scopeLabel') },
2147
+ [
2148
+ ['global', t('scopeGlobal'), t('scopeGlobalHint')],
2149
+ ['session', t('scopeSession'), t('scopeSessionHint')],
2150
+ ].map(([key, label, hint]) =>
2151
+ h(
2152
+ 'button',
2153
+ {
2154
+ key,
2155
+ type: 'button',
2156
+ role: 'tab',
2157
+ 'aria-selected': scope === key ? 'true' : 'false',
2158
+ className: scope === key ? 'on' : '',
2159
+ title: hint,
2160
+ onClick: () => setScope(key),
2161
+ },
2162
+ label,
2163
+ ),
2164
+ ),
2165
+ ),
2166
+ h('input', {
2167
+ ref: searchRef,
2168
+ className: 'ci-input',
2169
+ placeholder: t('search'),
2170
+ value: query,
2171
+ onChange: (event) => setQuery(event.target.value),
2172
+ 'aria-label': t('search'),
2173
+ }),
2174
+ h(
2175
+ 'div',
2176
+ { className: 'ci-seg' },
2177
+ [
2178
+ ['group', t('group')],
2179
+ ['flat', t('flat')],
2180
+ ].map(([key, label]) => h('button', { key, type: 'button', className: view === key ? 'on' : '', onClick: () => setView(key) }, label)),
2181
+ ),
2182
+ h('select', {
2183
+ className: 'ci-select',
2184
+ value: filter,
2185
+ 'aria-label': t('filterLabel'),
2186
+ title: t('filterLabel'),
2187
+ onChange: (event) => setFilter(event.target.value),
2188
+ }, ['all'].concat(CHANNELS).map((channel) => h('option', { key: channel, value: channel }, channel === 'all' ? t('all') : t(channel)))),
2189
+ h(
2190
+ 'div',
2191
+ { className: 'ci-seg ci-viewopts' },
2192
+ [
2193
+ ['only', onlySwitchable, t('onlySwitchable'), t('onlySwitchableHint'), () => setOnlySwitchable(!onlySwitchable), onlySwitchable ? 'true' : 'false'],
2194
+ ['expand', false, t('expandAll'), t('expandAll'), () => {
2195
+ const next = {}
2196
+ for (const group of groups) next[group.id] = true
2197
+ setExpanded(next)
2198
+ }, 'false', view === 'group'],
2199
+ ['collapse', false, t('collapseAll'), t('collapseAll'), () => setExpanded({}), 'false', view === 'group'],
2200
+ ].filter(([key, , , , , , visible]) => key === 'only' || visible !== false).map(([key, on, label, hint, onClick, pressed]) =>
2201
+ h(
2202
+ 'button',
2203
+ { key, type: 'button', className: on ? 'on' : '', title: hint || label, 'aria-pressed': pressed, onClick },
2204
+ label,
2205
+ ),
2206
+ ),
2207
+ ),
2208
+ ),
2209
+ // The filter bar is always visible: every active exclusion is a chip
2210
+ // with an ×, and one control clears the whole set. Clicking a suite
2211
+ // name adds its chip here, so "why is this list short" is answerable.
2212
+ h(
2213
+ 'div',
2214
+ { className: 'ci-filterbar', role: 'group', 'aria-label': t('v2.filters') },
2215
+ h('span', { className: 'lbl' }, t('activeFilters')),
2216
+ filter === 'all' ? null : h(FilterChip, { label: t(filter), onClear: () => setFilter('all') }),
2217
+ suite === null ? null : h(FilterChip, { label: suite, title: t('v2.filterSuite', { label: suite }), onClear: () => setSuite(null) }),
2218
+ onlySwitchable ? h(FilterChip, { label: t('onlySwitchable'), onClear: () => setOnlySwitchable(false) }) : null,
2219
+ query.trim().length > 0 ? h(FilterChip, { label: `「${query.trim()}」`, onClear: () => setQuery('') }) : null,
2220
+ filter === 'all' && suite === null && !onlySwitchable && query.trim().length === 0
2221
+ ? h('span', { className: 'hint' }, t('v2.noFilters'))
2222
+ : h('button', { type: 'button', className: 'ci-filterclear', onClick: clearAllFilters }, t('v2.clearAll')),
2223
+ ),
2224
+ h(
2225
+ 'div',
2226
+ { className: 'ci-table', role: 'group', 'aria-label': t('items') + ' · ' + items.length },
2227
+ h(
2228
+ 'div',
2229
+ { className: 'ci-thead' },
2230
+ h('div', null, sortHeader('name', t('name'))),
2231
+ h('div', { className: 'ci-about' }, t('about')),
2232
+ h('div', null, sortHeader('channel', t('channel'))),
2233
+ h('div', { style: { textAlign: 'right' } }, sortHeader('tokens', t('tokens'), true)),
2234
+ h('div', { style: { textAlign: 'right' } }, sortHeader('share', t('share'), true)),
2235
+ h('div', { style: { textAlign: 'right' } }, t('switch')),
2236
+ ),
2237
+ items.length === 0
2238
+ ? h(
2239
+ 'div',
2240
+ { className: 'ci-empty' },
2241
+ h('div', null, query.trim().length > 0 ? t('noMatch') : t('empty')),
2242
+ query.trim().length > 0 || filter !== 'all' || onlySwitchable || suite !== null
2243
+ ? h(
2244
+ 'button',
2245
+ {
2246
+ type: 'button',
2247
+ className: 'ci-btn',
2248
+ style: { marginTop: 8 },
2249
+ onClick: clearAllFilters,
2250
+ },
2251
+ t('clearFilters'),
2252
+ )
2253
+ : null,
2254
+ )
2255
+ : view === 'group'
2256
+ ? groups.map((group) => {
2257
+ const state = groupState(group)
2258
+ const open = expanded[group.id] === true
2259
+ const groupEffective = group.items.reduce((sum, item) => (isOn(item) ? sum + item.tokens : sum), 0)
2260
+ const groupSaved = Math.max(0, group.tokens - groupEffective)
2261
+ const suiteLabel = groupLabelOf(t, group)
2262
+ return h(
2263
+ 'div',
2264
+ { className: 'ci-group', key: group.id },
2265
+ h(
2266
+ 'div',
2267
+ {
2268
+ className: 'ci-row ci-grouphead',
2269
+ role: 'button',
2270
+ tabIndex: 0,
2271
+ 'aria-expanded': open ? 'true' : 'false',
2272
+ onClick: () => toggleExpanded(group.id),
2273
+ onKeyDown: (event) => {
2274
+ if (event.key === 'Enter' || event.key === ' ') {
2275
+ event.preventDefault()
2276
+ toggleExpanded(group.id)
2277
+ }
2278
+ },
2279
+ },
2280
+ h(
2281
+ 'div',
2282
+ { className: 'n' },
2283
+ h('span', { className: 'ci-caret' + (open ? ' open' : '') }, open ? '▾' : '▸'),
2284
+ h(
2285
+ 'button',
2286
+ {
2287
+ type: 'button',
2288
+ className: 'ci-suitename',
2289
+ title: t('v2.filterSuite', { label: suiteLabel }),
2290
+ onClick: (event) => {
2291
+ event.stopPropagation()
2292
+ setSuite((previous) => (previous === suiteLabel ? null : suiteLabel))
2293
+ },
2294
+ },
2295
+ h(HitMark, { text: suiteLabel, needle }),
2296
+ ),
2297
+ h('span', { className: 'id' }, `${group.items.length} ${t('items')}`),
2298
+ groupSaved > 0 ? h('span', { className: 'ci-delta', title: t('v2.savedHint', { tokens: digits(groupSaved) }) }, '−' + token(groupSaved)) : null,
2299
+ plannedKeys.size > 0 && group.items.filter((item) => plannedKeys.has(item.channel + ':' + item.name)).length > 0
2300
+ ? h(
2301
+ 'span',
2302
+ { className: 'ci-tag' },
2303
+ `${group.items.filter((item) => plannedKeys.has(item.channel + ':' + item.name)).length} ${t('outsideBudget')}`,
2304
+ )
2305
+ : null,
2306
+ state.on ? null : h('span', { className: 'ci-tag' }, state.mixed ? t('mixedOff') : t('turnedOff')),
2307
+ ),
2308
+ h(
2309
+ 'div',
2310
+ { className: 'ci-about', title: `${group.items.length} ${t('items')} · ${(group.channels || [group.channel]).length > 1 ? t('mixed') : t(group.channel)}` },
2311
+ `${group.items.length} ${t('items')} · ${(group.channels || [group.channel]).length > 1 ? t('mixed') : t(group.channel)}`,
2312
+ ),
2313
+ h(
2314
+ 'div',
2315
+ { className: 'badge' },
2316
+ (group.channels || [group.channel]).map((channel) => h(Dot, { key: channel, channel })),
2317
+ (group.channels || [group.channel]).length > 1 ? t('mixed') : t(group.channel),
2318
+ ),
2319
+ h('div', { className: 'num' }, digits(group.tokens)),
2320
+ h('div', { className: 'num' }, state.on ? `${pctText(group.tokens, effectiveTotal)}` : '—'),
2321
+ h(Switch, { on: state.on, mixed: state.mixed, disabled: busy || state.disabled, onChange: () => toggleGroup(group), title: group.label }),
2322
+ ),
2323
+ open
2324
+ ? group.items.flatMap((item) => {
2325
+ const key = itemKey(item)
2326
+ const openPeek = peek[key] === true
2327
+ const rows = [
2328
+ h(ItemRow, {
2329
+ key,
2330
+ item,
2331
+ t,
2332
+ snapshot,
2333
+ isOn,
2334
+ onToggle,
2335
+ busy,
2336
+ nested: true,
2337
+ needle,
2338
+ planned: plannedKeys.has(item.channel + ':' + item.name),
2339
+ previewOpen: openPeek,
2340
+ onPreview: v2 === true ? togglePeek : undefined,
2341
+ }),
2342
+ ]
2343
+ if (v2 === true && openPeek) rows.push(h(ItemPreview, { key: key + ':preview', item, snapshot, t, onOpenContent }))
2344
+ return rows
2345
+ })
2346
+ : null,
2347
+ )
2348
+ })
2349
+ : items.flatMap((item) => {
2350
+ const key = itemKey(item)
2351
+ const openPeek = peek[key] === true
2352
+ const rows = [
2353
+ h(ItemRow, {
2354
+ key,
2355
+ item,
2356
+ t,
2357
+ snapshot,
2358
+ isOn,
2359
+ onToggle,
2360
+ busy,
2361
+ needle,
2362
+ planned: plannedKeys.has(item.channel + ':' + item.name),
2363
+ previewOpen: openPeek,
2364
+ onPreview: v2 === true ? togglePeek : undefined,
2365
+ }),
2366
+ ]
2367
+ if (v2 === true && openPeek) rows.push(h(ItemPreview, { key: key + ':preview', item, snapshot, t, onOpenContent }))
2368
+ return rows
2369
+ }),
2370
+ ),
2371
+ snapshot.closedGroups && snapshot.closedGroups.length > 0
2372
+ ? h(
2373
+ 'div',
2374
+ { className: 'ci-card' },
2375
+ h('h2', null, `${t('closedTitle')} · ${snapshot.closed.length} ${t('items')}`),
2376
+ h('div', { className: 'hint' }, t('closedHint')),
2377
+ h(
2378
+ 'div',
2379
+ { className: 'ci-list' },
2380
+ snapshot.closedGroups.map((group) =>
2381
+ h(
2382
+ 'div',
2383
+ { className: 'ci-mini', key: group.id },
2384
+ h(Dot, { channel: group.channel }),
2385
+ h('span', { className: 'n', title: group.label }, group.label),
2386
+ h('span', { className: 't' }, `${group.items.length} ${t('items')}`),
2387
+ h('span', { className: 't' }, group.tokens > 0 ? digits(group.tokens) : '—'),
2388
+ h(
2389
+ 'button',
2390
+ {
2391
+ type: 'button',
2392
+ className: 'ci-btn',
2393
+ onClick: () =>
2394
+ act(
2395
+ { kind: 'names', channel: group.channel, names: group.items.map((item) => item.name), enabled: true },
2396
+ `${t('restoreGroup')} ${group.label}`,
2397
+ ),
2398
+ },
2399
+ t('restoreGroup'),
2400
+ ),
2401
+ ),
2402
+ ),
2403
+ ),
2404
+ )
2405
+ : null,
2406
+ h(
2407
+ 'div',
2408
+ { className: 'ci-note', style: { display: 'flex', alignItems: 'center', gap: 10 } },
2409
+ h(
2410
+ 'span',
2411
+ null,
2412
+ (() => {
2413
+ const view = snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals : snapshot.totals
2414
+ const shown = groups.length
2415
+ const totalGroups = snapshot.groups.length
2416
+ return `${t('total')} ${digits(view.tokens)} · ${t('savable')} ${digits(view.savableTokens)} (${view.savablePercent}%) · ${shown !== totalGroups ? `${shown}/${totalGroups}` : String(shown)} ${t('groups')} · ${t('locked')} ${snapshot.locks.length}`
2417
+ })(),
2418
+ ),
2419
+ snapshot.undo && snapshot.undo.available
2420
+ ? h(
2421
+ 'button',
2422
+ {
2423
+ type: 'button',
2424
+ className: 'ci-btn',
2425
+ disabled: busy,
2426
+ title: snapshot.undo.last || '',
2427
+ style: { maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
2428
+ onClick: () => onUndo(),
2429
+ },
2430
+ `${t('undo')}${snapshot.undo.last ? ` · ${snapshot.undo.last}` : ''}`,
2431
+ )
2432
+ : null,
2433
+ ),
2434
+ )
2435
+ }
2436
+
2437
+ // ------------------------------------------------------------ v2 surfaces
2438
+
2439
+ // Resolve a health check's "switch this suite" action to the exact
2440
+ // (channel, group id) pairs /action expects. A suite can span channels,
2441
+ // so the resolution returns every matching part rather than guessing one.
2442
+ function resolveGroupParts(snapshot, channel, key) {
2443
+ const wanted = String(key === undefined || key === null ? '' : key).toLowerCase()
2444
+ if (wanted.length === 0) return []
2445
+ const parts = []
2446
+ for (const item of snapshot.items) {
2447
+ if (item.channel !== channel) continue
2448
+ const group = String(item.group === undefined || item.group === null ? '' : item.group)
2449
+ if (group.length === 0) continue
2450
+ const lower = group.toLowerCase()
2451
+ const label = String(item.groupLabel === undefined || item.groupLabel === null ? group : item.groupLabel).toLowerCase()
2452
+ const tail = lower.slice(lower.lastIndexOf(':') + 1)
2453
+ if (label === wanted || lower === wanted || tail === wanted || lower.endsWith(':' + wanted)) {
2454
+ if (!parts.some((entry) => entry.group === group)) parts.push({ channel, group })
2455
+ }
2456
+ }
2457
+ return parts
2458
+ }
2459
+
2460
+ function HealthStrip({ health, t, v2, snapshot, act, onOpenContent, onOpenTab }) {
2461
+ if (v2 !== true) return null
2462
+ const data = health && health.data !== null && health.data !== undefined ? health.data : null
2463
+ const checks = data !== null && Array.isArray(data.checks) ? data.checks : []
2464
+ const summary = (data !== null && data.summary) || (snapshot !== null && snapshot.healthSummary) || null
2465
+ const counts = {
2466
+ high: Number(summary && summary.high) || 0,
2467
+ warn: Number(summary && summary.warn) || 0,
2468
+ info: Number(summary && summary.info) || 0,
2469
+ }
2470
+ const failed = health !== null && health.status === 'failed'
2471
+ const loading = (health === null || health.status === 'loading' || health.status === 'refreshing') && data === null
2472
+ const visible = checks.filter((check) => check !== null && typeof check === 'object').slice(0, 6)
2473
+ const rest = checks.length - visible.length
2474
+
2475
+ const runAction = (check) => {
2476
+ const action = check.action
2477
+ if (action === null || action === undefined || typeof action !== 'object') return
2478
+ const payload = action.payload !== null && typeof action.payload === 'object' ? action.payload : {}
2479
+ if (action.kind === 'switch-group') {
2480
+ const channel = String(payload.channel || '')
2481
+ const parts = resolveGroupParts(snapshot, channel, payload.group !== undefined ? payload.group : payload.key !== undefined ? payload.key : payload.name)
2482
+ if (parts.length === 0) return
2483
+ const enabled = payload.op !== 'off' && payload.enabled !== false
2484
+ act({ kind: 'groups', groups: parts, enabled }, `${enabled ? t('turnedOn') : t('turnedOff')} ${payload.key || ''}`)
2485
+ return
2486
+ }
2487
+ if (action.kind === 'set-budget') {
2488
+ onOpenTab('settings')
2489
+ return
2490
+ }
2491
+ if (action.kind === 'open-content') {
2492
+ if (payload.channel !== undefined && (payload.id !== undefined || payload.itemId !== undefined)) {
2493
+ onOpenContent({ channel: String(payload.channel), id: String(payload.id !== undefined ? payload.id : payload.itemId), name: payload.name })
2494
+ }
2495
+ return
2496
+ }
2497
+ if (action.kind === 'open-tab') {
2498
+ const raw = typeof payload.tab === 'string' ? payload.tab : ''
2499
+ const tab = raw === 'settings' ? 'settings' : raw === 'insights' || raw === 'stats' ? 'insights' : 'manage'
2500
+ onOpenTab(tab, payload.channel)
2501
+ }
2502
+ }
2503
+
2504
+ const actionLabel = (action) => {
2505
+ if (action === null || action === undefined) return ''
2506
+ const known = ['switch-group', 'set-budget', 'open-content', 'open-tab'].indexOf(action.kind) >= 0
2507
+ return known ? t('health.action.' + action.kind) : t('v2.openContent')
2508
+ }
2509
+
2510
+ return h(
2511
+ 'div',
2512
+ { className: 'ci-health', role: 'group', 'aria-label': t('v2.health') },
2513
+ h(
2514
+ 'div',
2515
+ { className: 'ci-health-head' },
2516
+ h('span', { className: 'ci-health-title' }, t('v2.health')),
2517
+ h(
2518
+ 'span',
2519
+ { className: 'ci-health-counts' },
2520
+ // Zero levels are noise: only render severities that actually
2521
+ // have checks, joined with a middot (design review optional #9).
2522
+ [
2523
+ ['high', 'high', counts.high],
2524
+ ['warn', 'warn', counts.warn],
2525
+ ['info', 'info', counts.info],
2526
+ ]
2527
+ .filter(([, , value]) => Number(value) > 0)
2528
+ .map(([key, className, value], index) => [
2529
+ index === 0 ? null : h('span', { key: key + ':sep', className: 'sep' }, '·'),
2530
+ h('span', { key, className }, h('b', null, String(value)), key === 'high' ? t('v2.sevHigh') : key === 'warn' ? t('v2.sevWarn') : t('v2.sevInfo')),
2531
+ ])
2532
+ .flat(),
2533
+ ),
2534
+ data !== null && Number.isFinite(Number(data.checkedAt))
2535
+ ? h('span', { className: 'ci-inline-meta', style: { marginLeft: 'auto' } }, t('v2.healthChecked', { time: fullTime(data.checkedAt) }))
2536
+ : null,
2537
+ ),
2538
+ failed
2539
+ ? h(
2540
+ 'div',
2541
+ { className: 'ci-errorbar', style: { marginTop: 6 } },
2542
+ h('span', null, `${t('health.failed')}:${errorText(health)}`),
2543
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: health.reload }, t('v2.retry')),
2544
+ )
2545
+ : null,
2546
+ loading
2547
+ ? h('div', { className: 'ci-health-allclear' }, t('loading'))
2548
+ : null,
2549
+ !loading && data !== null && checks.length === 0
2550
+ ? h('div', { className: 'ci-health-allclear' }, t('v2.healthAllClear'))
2551
+ : null,
2552
+ visible.map((check, index) => {
2553
+ const severity = check.severity === 'high' ? 'high' : check.severity === 'warn' ? 'warn' : 'info'
2554
+ const params = check.params !== null && typeof check.params === 'object' ? check.params : {}
2555
+ // Different codes carry different params; fill the placeholders the
2556
+ // copy expects so a missing field reads as "—" and never as `{count}`.
2557
+ const text = t('health.' + String(check.code || ''), {
2558
+ label: params.label !== undefined ? params.label : '—',
2559
+ count: params.count !== undefined ? params.count : '—',
2560
+ share: params.share !== undefined ? params.share : '—',
2561
+ tokens: Number.isFinite(Number(params.tokens)) && Number(params.tokens) > 0 ? token(params.tokens) : '—',
2562
+ })
2563
+ return h(
2564
+ 'div',
2565
+ { className: 'ci-health-row', key: `${check.code || 'check'}:${index}` },
2566
+ h('span', { className: 'sev ' + severity, 'aria-hidden': 'true' }),
2567
+ h(
2568
+ 'span',
2569
+ { className: 'ci-health-text', title: text },
2570
+ text,
2571
+ severity !== 'info' && Number.isFinite(Number(params.tokens)) && Number(params.tokens) > 0
2572
+ ? h('span', { className: 'ci-delta', title: t('v2.savedHint', { tokens: digits(params.tokens) }) }, '−' + token(params.tokens))
2573
+ : null,
2574
+ ),
2575
+ check.action !== null && check.action !== undefined && typeof check.action === 'object'
2576
+ ? h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: () => runAction(check) }, actionLabel(check.action))
2577
+ : null,
2578
+ )
2579
+ }),
2580
+ rest > 0 ? h('div', { className: 'ci-health-allclear' }, t('v2.moreChecks', { count: rest })) : null,
2581
+ )
2582
+ }
2583
+
2584
+ // apiVersion < 2 is not hidden silently: the card says what the host
2585
+ // returns, what the panel needs, and lets the user dismiss it.
2586
+ function V2Gate({ snapshot, t }) {
2587
+ const [dismissed, setDismissed] = useStoredState('v2GateDismissed', false)
2588
+ if (dismissed === true) return null
2589
+ const api = Number(snapshot !== null && snapshot !== undefined ? snapshot.apiVersion : 1) || 1
2590
+ return h(
2591
+ 'div',
2592
+ { className: 'ci-gate', role: 'status' },
2593
+ h('h2', null, t('v2.gateTitle')),
2594
+ h('p', null, t('v2.gateBody')),
2595
+ h(
2596
+ 'div',
2597
+ { className: 'kv' },
2598
+ h('span', null, t('v2.gateCurrent'), h('b', null, `v${api}`)),
2599
+ h('span', null, t('v2.gateMin'), h('b', null, `v${API_V2}`)),
2600
+ ),
2601
+ h('div', { className: 'actions' }, h('button', { type: 'button', className: 'ci-btn ci-primary', onClick: () => setDismissed(true) }, t('v2.gateDismiss'))),
2602
+ )
2603
+ }
2604
+
2605
+ // The manage page mounts the health strip through this thin shell so the
2606
+ // /health request only happens while that tab is actually visible.
2607
+ function ManageHealth({ snapshot, t, sessionId, v2, act, onOpenContent, onOpenTab }) {
2608
+ const health = useHealth(sessionId, v2 === true)
2609
+ return h(HealthStrip, { health, t, v2, snapshot, act, onOpenContent, onOpenTab })
2610
+ }
2611
+
2612
+ // Third control tier: range pills. Pills = "which slice of time", the seg
2613
+ // control = "which ordering/view", filter chips = "what is excluded".
2614
+ function RangePills({ value, options, onChange, label }) {
2615
+ return h(
2616
+ 'div',
2617
+ { className: 'ci-pills', role: 'group', 'aria-label': label },
2618
+ options.map(([key, text]) =>
851
2619
  h(
852
2620
  'button',
853
2621
  {
2622
+ key,
854
2623
  type: 'button',
855
- className: 'ci-chip' + (onlySwitchable ? ' on' : ''),
856
- 'aria-pressed': onlySwitchable,
857
- title: t('onlySwitchableHint'),
858
- onClick: () => setOnlySwitchable(!onlySwitchable),
2624
+ className: value === key ? 'on' : '',
2625
+ 'aria-pressed': value === key ? 'true' : 'false',
2626
+ title: text,
2627
+ onClick: () => onChange(key),
859
2628
  },
860
- t('onlySwitchable'),
2629
+ text,
2630
+ ),
2631
+ ),
2632
+ )
2633
+ }
2634
+
2635
+ // A trend with more than 40 points would compress bars into hairlines, so
2636
+ // range=all folds equal-count buckets into one overview screen instead of
2637
+ // scrolling horizontally. Channels stay null when no bucket row was
2638
+ // measured, so the striped "unknown" state is never faked as zero.
2639
+ function bucketTrend(points, limit) {
2640
+ if (points.length <= limit) return { rows: points, buckets: 0 }
2641
+ const size = Math.ceil(points.length / limit)
2642
+ const rows = []
2643
+ for (let index = 0; index < points.length; index += size) {
2644
+ const slice = points.slice(index, index + size)
2645
+ const total = slice.reduce((sum, point) => sum + (Number(point.total) || 0), 0)
2646
+ const effective = slice.reduce((sum, point) => sum + (Number(point.effective) || 0), 0)
2647
+ const saved = slice.reduce((sum, point) => sum + (Number(point.saved) || 0), 0)
2648
+ const measured = slice.filter((point) => point.channels !== null && point.channels !== undefined && typeof point.channels === 'object')
2649
+ let channels = null
2650
+ if (measured.length > 0) {
2651
+ channels = {}
2652
+ for (const channel of CHANNELS) channels[channel] = measured.reduce((sum, point) => sum + (Number(point.channels[channel]) || 0), 0)
2653
+ }
2654
+ const samples = slice.reduce((sum, point) => sum + (Number(point.samples) || 0), 0)
2655
+ const compactions = slice.reduce(
2656
+ (accumulator, point) => {
2657
+ const source = point.compactions || {}
2658
+ return { count: accumulator.count + (Number(source.count) || 0), freed: accumulator.freed + (Number(source.freed) || 0) }
2659
+ },
2660
+ { count: 0, freed: 0 },
2661
+ )
2662
+ rows.push({
2663
+ sessionId: 'bucket:' + index,
2664
+ at: Number(slice[slice.length - 1].at) || 0,
2665
+ firstAt: Number(slice[0].firstAt || slice[0].at) || 0,
2666
+ cwd: slice[slice.length - 1].cwd,
2667
+ scope: slice[slice.length - 1].scope,
2668
+ total,
2669
+ effective,
2670
+ saved,
2671
+ channels,
2672
+ source: slice.every((point) => point.source === 'log') ? 'log' : 'measured',
2673
+ samples,
2674
+ compactions,
2675
+ policy: slice[slice.length - 1].policy,
2676
+ bucketCount: slice.length,
2677
+ })
2678
+ }
2679
+ return { rows, buckets: rows.length }
2680
+ }
2681
+
2682
+ function TrendChart({ points, t, range }) {
2683
+ const wrapRef = useRef(null)
2684
+ const width = useElementWidth(wrapRef, 720)
2685
+ const hatchId = useId()
2686
+ const source = Array.isArray(points) ? points : []
2687
+ const [hidden, setHidden] = useState([])
2688
+ const [hover, setHover] = useState(-1)
2689
+ const [pinned, setPinned] = useState(-1)
2690
+ const barRefs = useRef([])
2691
+ const bucketed = useMemo(() => bucketTrend(source, 40), [source])
2692
+ const data = bucketed.rows
2693
+ const overview = bucketed.buckets > 0
2694
+ const { useEffect: useEffectLocal } = React
2695
+ useEffectLocal(() => {
2696
+ if (pinned >= 0 && pinned >= data.length) setPinned(-1)
2697
+ }, [data.length, pinned])
2698
+ useEffectLocal(() => {
2699
+ if (pinned < 0) return undefined
2700
+ const onKey = (event) => {
2701
+ if (event.key === 'Escape') setPinned(-1)
2702
+ }
2703
+ window.addEventListener('keydown', onKey, true)
2704
+ return () => window.removeEventListener('keydown', onKey, true)
2705
+ }, [pinned])
2706
+
2707
+ const W = Math.max(320, Math.min(width, 1400))
2708
+ const pad = { l: 40, r: 10, t: 10, b: 24 }
2709
+ const plotH = 150
2710
+ const H = plotH + pad.t + pad.b
2711
+ const plotW = W - pad.l - pad.r
2712
+ const hiddenSet = new Set(hidden)
2713
+ const series = CHANNELS.filter((channel) => !hiddenSet.has(channel))
2714
+ const pointTotal = (point) => Math.max(0, Number(point.total) || 0)
2715
+ const maxTotal = data.reduce((max, point) => Math.max(max, pointTotal(point)), 1)
2716
+ const niceMax = (() => {
2717
+ const exponent = Math.pow(10, Math.floor(Math.log10(Math.max(1, maxTotal))))
2718
+ for (const step of [1, 2, 2.5, 5, 10]) {
2719
+ const candidate = step * exponent
2720
+ if (candidate >= maxTotal) return Math.round(candidate)
2721
+ }
2722
+ return Math.round(10 * exponent)
2723
+ })()
2724
+ const yMax = Math.max(1, niceMax)
2725
+ const slot = plotW / Math.max(1, data.length)
2726
+ const gap = 2
2727
+ const barW = Math.max(2, Math.min(14, slot - gap))
2728
+ const yOf = (value) => pad.t + plotH - (value / yMax) * plotH
2729
+ const xOf = (index) => pad.l + slot * index + slot / 2
2730
+ const segmentsOf = (point) => {
2731
+ const channels = point.channels
2732
+ if (channels === null || channels === undefined || typeof channels !== 'object') return [{ id: 'unknown', value: pointTotal(point) }]
2733
+ const out = []
2734
+ let sum = 0
2735
+ for (const channel of series) {
2736
+ const value = Math.max(0, Number(channels[channel]) || 0)
2737
+ if (value > 0) {
2738
+ out.push({ id: channel, value })
2739
+ sum += value
2740
+ }
2741
+ }
2742
+ const leftover = pointTotal(point) - sum
2743
+ if (leftover > 0) out.push({ id: 'unknown', value: leftover })
2744
+ return out
2745
+ }
2746
+ const unknown = data.some((point) => point.channels === null || point.channels === undefined)
2747
+ const hiddenCount = CHANNELS.length - series.length
2748
+ const gridValues = [0.25, 0.5, 0.75, 1].map((ratio) => yMax * ratio)
2749
+ const step = Math.max(1, Math.ceil(data.length / 6))
2750
+ const xTicks = data
2751
+ .map((point, index) => ({ index, point }))
2752
+ .filter(({ index }, position, list) => {
2753
+ if (index === 0) return true
2754
+ if (index === data.length - 1) {
2755
+ // The last tick owns the right edge; drop a neighbour that would
2756
+ // overlap it when the final bucket sits one step away.
2757
+ const previous = list[position - 1]
2758
+ return previous === undefined || index - previous.index >= Math.max(2, Math.ceil(step / 2))
2759
+ }
2760
+ return index % step === 0
2761
+ })
2762
+ const active = pinned >= 0 && pinned < data.length ? pinned : hover
2763
+ const tooltip = active >= 0 ? data[active] : null
2764
+ const labelOf = (point) => {
2765
+ const at = Number(point.firstAt || point.at) || 0
2766
+ return at > 0 ? fullTime(at) : '—'
2767
+ }
2768
+
2769
+ if (data.length === 0) {
2770
+ return h(
2771
+ 'div',
2772
+ { className: 'ci-empty-next' },
2773
+ h('span', null, t('trend.empty')),
2774
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: () => window.location.reload() }, t('refresh')),
2775
+ )
2776
+ }
2777
+
2778
+ const summaryLabel = t('trend.summary', {
2779
+ count: source.length,
2780
+ avg: token(source.reduce((sum, point) => sum + pointTotal(point), 0) / Math.max(1, source.length)),
2781
+ max: token(maxTotal),
2782
+ })
2783
+
2784
+ return h(
2785
+ 'div',
2786
+ { className: 'ci-trend' },
2787
+ h(
2788
+ 'div',
2789
+ { className: 'ci-trend-wrap', ref: wrapRef, onClick: () => setPinned(-1) },
2790
+ h(
2791
+ 'svg',
2792
+ {
2793
+ className: 'ci-trend-svg',
2794
+ viewBox: `0 0 ${W} ${H}`,
2795
+ width: W,
2796
+ height: H,
2797
+ role: 'group',
2798
+ 'aria-label': summaryLabel,
2799
+ },
2800
+ h('title', null, t('trend.title')),
2801
+ h(
2802
+ 'defs',
2803
+ null,
2804
+ h(
2805
+ 'pattern',
2806
+ { id: hatchId, patternUnits: 'userSpaceOnUse', width: 6, height: 6, patternTransform: 'rotate(45)' },
2807
+ h('rect', { width: 6, height: 6, fill: 'var(--ci-line2)' }),
2808
+ h('line', { x1: 0, y1: 0, x2: 0, y2: 6, stroke: 'var(--ci-fg3)', strokeWidth: 1.5, opacity: 0.55 }),
2809
+ ),
2810
+ ),
2811
+ h(
2812
+ 'g',
2813
+ { className: 'ci-trend-grid' },
2814
+ gridValues.map((tick) =>
2815
+ h('line', { key: 'g' + tick, x1: pad.l, y1: yOf(tick), x2: W - pad.r, y2: yOf(tick), strokeDasharray: '2 4', strokeWidth: 0.5 }),
2816
+ ),
2817
+ h('line', { x1: pad.l, y1: yOf(0), x2: W - pad.r, y2: yOf(0), strokeWidth: 1 }),
2818
+ ),
2819
+ h(
2820
+ 'g',
2821
+ { className: 'ci-trend-axis' },
2822
+ gridValues.map((tick) =>
2823
+ h('text', { key: 'y' + tick, x: pad.l - 8, y: yOf(tick) + 3, textAnchor: 'end' }, token(tick)),
2824
+ ),
2825
+ h('text', { x: pad.l - 8, y: yOf(0) + 3, textAnchor: 'end' }, '0'),
2826
+ ),
2827
+ data.map((point, index) => {
2828
+ const segments = segmentsOf(point)
2829
+ let cursor = 0
2830
+ const center = xOf(index)
2831
+ const resolved = point.channels !== null && point.channels !== undefined
2832
+ const label = `${labelOf(point)} · ${digits(pointTotal(point))} token${resolved ? '' : ' · ' + t('trend.unknown')}`
2833
+ const dimmed = (pinned >= 0 || hover >= 0) && active !== index
2834
+ return h(
2835
+ 'g',
2836
+ {
2837
+ key: point.sessionId || 'p' + index,
2838
+ ref: (node) => {
2839
+ barRefs.current[index] = node
2840
+ },
2841
+ className: 'ci-trend-bar',
2842
+ tabIndex: 0,
2843
+ role: 'img',
2844
+ 'aria-label': label,
2845
+ 'aria-pressed': pinned === index ? 'true' : 'false',
2846
+ onMouseEnter: () => setHover(index),
2847
+ onMouseLeave: () => setHover(-1),
2848
+ onFocus: () => setHover(index),
2849
+ onBlur: () => setHover(-1),
2850
+ onClick: (event) => {
2851
+ event.stopPropagation()
2852
+ setPinned((previous) => (previous === index ? -1 : index))
2853
+ },
2854
+ onKeyDown: (event) => {
2855
+ if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
2856
+ event.preventDefault()
2857
+ const next = event.key === 'ArrowRight' ? index + 1 : index - 1
2858
+ const node = barRefs.current[next]
2859
+ if (node && typeof node.focus === 'function') node.focus()
2860
+ } else if (event.key === 'Enter' || event.key === ' ') {
2861
+ event.preventDefault()
2862
+ setPinned((previous) => (previous === index ? -1 : index))
2863
+ } else if (event.key === 'Escape') {
2864
+ setPinned(-1)
2865
+ if (event.target && typeof event.target.blur === 'function') event.target.blur()
2866
+ }
2867
+ },
2868
+ },
2869
+ h('rect', { className: 'ci-trend-hit', x: pad.l + slot * index, y: pad.t, width: slot, height: plotH }),
2870
+ segments.map((segment) => {
2871
+ const bottom = cursor
2872
+ cursor += segment.value
2873
+ const yTop = yOf(bottom + segment.value)
2874
+ const height = Math.max(segment.value > 0 ? 1 : 0, yOf(bottom) - yTop)
2875
+ const top = segment === segments[segments.length - 1]
2876
+ return h('rect', {
2877
+ key: segment.id,
2878
+ x: center - barW / 2,
2879
+ y: yTop,
2880
+ width: barW,
2881
+ height,
2882
+ rx: top ? 2 : 0,
2883
+ fill: segment.id === 'unknown' ? `url(#${hatchId})` : COLOR[segment.id],
2884
+ opacity: dimmed ? 0.4 : 1,
2885
+ })
2886
+ }),
2887
+ pinned === index ? h('rect', { x: center - barW / 2 - 2, y: pad.t, width: barW + 4, height: plotH, fill: 'none', stroke: 'var(--ci-accent)', strokeWidth: 2, rx: 3 }) : null,
2888
+ )
2889
+ }),
2890
+ h(
2891
+ 'g',
2892
+ { className: 'ci-trend-axis' },
2893
+ xTicks.map(({ index, point }) =>
2894
+ h(
2895
+ 'text',
2896
+ {
2897
+ key: 'x' + index,
2898
+ x: xOf(index),
2899
+ y: H - 6,
2900
+ textAnchor: index === 0 ? 'start' : index === data.length - 1 ? 'end' : 'middle',
2901
+ },
2902
+ dayLabel(Number(point.firstAt || point.at)),
2903
+ ),
2904
+ ),
2905
+ ),
2906
+ ),
2907
+ tooltip === null
2908
+ ? null
2909
+ : h(
2910
+ 'div',
2911
+ { className: 'ci-trend-tip', style: { left: Math.max(6, Math.min(W - 206, xOf(active) - 100)), top: 6 } },
2912
+ h('div', { className: 't' }, labelOf(tooltip)),
2913
+ Number(tooltip.bucketCount) > 1 ? h('div', { className: 'r' }, h('span', { className: 'l' }, t('trend.bucketCount', { count: tooltip.bucketCount })), h('b', null, '')) : null,
2914
+ h('div', { className: 'r' }, h('span', { className: 'l' }, t('total')), h('b', null, `${digits(pointTotal(tooltip))} token`)),
2915
+ h('div', { className: 'r' }, h('span', { className: 'l' }, t('trend.effective')), h('b', null, token(Number(tooltip.effective) || 0))),
2916
+ h('div', { className: 'r' }, h('span', { className: 'l' }, t('savable')), h('b', null, token(Math.max(0, Number(tooltip.saved) || 0)))),
2917
+ h('div', { className: 'sep' }),
2918
+ segmentsOf(tooltip).map((segment) =>
2919
+ h(
2920
+ 'div',
2921
+ { className: 'r', key: segment.id },
2922
+ h(
2923
+ 'span',
2924
+ { className: 'l' },
2925
+ h('i', {
2926
+ className: 'sw',
2927
+ style: segment.id === 'unknown' ? { background: 'repeating-linear-gradient(45deg,var(--ci-fg3) 0 1.5px,transparent 1.5px 4px)' } : { background: COLOR[segment.id] },
2928
+ }),
2929
+ segment.id === 'unknown' ? t('trend.unknown') : t(segment.id),
2930
+ ),
2931
+ h('b', null, token(segment.value)),
2932
+ ),
2933
+ ),
2934
+ h(
2935
+ 'div',
2936
+ { className: 'r' },
2937
+ h('span', { className: 'l' }, tooltip.source === 'log' ? t('v2.badgeLog') : t('v2.badgeMeasured')),
2938
+ h('b', null, tooltip.scope ? scopeLabel(t, tooltip.scope) : '—'),
2939
+ ),
2940
+ Number(tooltip.samples) > 1 ? h('div', { className: 'r' }, h('span', { className: 'l' }, t('v2.samples', { count: tooltip.samples })), h('b', null, '')) : null,
2941
+ tooltip.compactions !== null && tooltip.compactions !== undefined && Number(tooltip.compactions.count) > 0
2942
+ ? h('div', { className: 'r' }, h('span', { className: 'l' }, t('v2.compactions', { count: tooltip.compactions.count, saved: token(tooltip.compactions.freed) })), h('b', null, ''))
2943
+ : null,
2944
+ h('div', { className: 'ci-trend-tip-hint' }, pinned >= 0 ? t('trend.pinned') : t('trend.pinHint')),
2945
+ ),
2946
+ ),
2947
+ h(
2948
+ 'div',
2949
+ { className: 'ci-trend-legend', role: 'group', 'aria-label': t('trend.legendHint') },
2950
+ CHANNELS.map((channel) =>
2951
+ h(
2952
+ 'button',
2953
+ {
2954
+ key: channel,
2955
+ type: 'button',
2956
+ 'aria-pressed': hiddenSet.has(channel) ? 'false' : 'true',
2957
+ title: t('trend.legendHint'),
2958
+ onClick: () => setHidden((previous) => (previous.indexOf(channel) >= 0 ? previous.filter((entry) => entry !== channel) : previous.concat(channel))),
2959
+ },
2960
+ h('i', { style: { background: COLOR[channel] } }),
2961
+ t(channel),
2962
+ ),
2963
+ ),
2964
+ unknown ? h('span', { className: 'unknown', title: t('trend.logHint'), style: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '1px 6px' } }, h('i', null), t('trend.unknown')) : null,
2965
+ hiddenCount > 0 ? h('button', { type: 'button', onClick: () => setHidden([]), title: t('trend.legendHint') }, '×') : null,
2966
+ ),
2967
+ h('div', { className: 'ci-trend-note' }, h('span', { className: 'hatch' }), t('trend.striped'), ' · ', t('trend.keyboardHint')),
2968
+ overview
2969
+ ? h('div', { className: 'ci-trend-note' }, t('trend.overviewNote', { count: source.length, buckets: data.length }))
2970
+ : range === 'all'
2971
+ ? h('div', { className: 'ci-trend-note' }, t('trend.allHint'))
2972
+ : null,
2973
+ )
2974
+ }
2975
+
2976
+ function CrossComposition({ aggregate, t }) {
2977
+ const avg = aggregate !== null && aggregate !== undefined && aggregate.avgChannels !== null && typeof aggregate.avgChannels === 'object' ? aggregate.avgChannels : null
2978
+ const rows = avg === null ? [] : CHANNELS.filter((channel) => Number(avg[channel]) > 0).map((channel) => ({ id: channel, tokens: Number(avg[channel]) }))
2979
+ const total = rows.reduce((sum, row) => sum + row.tokens, 0)
2980
+ return h(
2981
+ 'div',
2982
+ { className: 'ci-card' },
2983
+ h('div', { className: 'ci-cardhead' }, h('h2', null, t('v2.crossTitle'))),
2984
+ rows.length === 0
2985
+ ? h('div', { className: 'ci-note' }, t('v2.crossEmpty'))
2986
+ : h(
2987
+ 'div',
2988
+ { className: 'ci-donut' },
2989
+ h(Donut, { rows, t, size: 116, centerLabel: t('trend.avg'), ariaLabel: t('v2.crossTitle') }),
2990
+ h(
2991
+ 'div',
2992
+ { className: 'ci-donut-legend' },
2993
+ rows.map((row) =>
2994
+ h(
2995
+ 'div',
2996
+ { className: 'ci-donut-row', key: row.id },
2997
+ h(Dot, { channel: row.id }),
2998
+ h('span', { className: 'n' }, t(row.id)),
2999
+ h('b', null, token(row.tokens)),
3000
+ h('span', { className: 'p' }, `${pctText(row.tokens, total)}`),
3001
+ ),
3002
+ ),
3003
+ ),
3004
+ ),
3005
+ h('div', { className: 'ci-trend-note' }, t('v2.crossNote')),
3006
+ )
3007
+ }
3008
+
3009
+ function HeaviestSuites({ snapshot, t }) {
3010
+ const groups = Array.isArray(snapshot.groups) ? snapshot.groups : []
3011
+ const itemsByGroup = new Map()
3012
+ for (const item of snapshot.items) {
3013
+ const list = itemsByGroup.get(item.group) || []
3014
+ list.push(item)
3015
+ itemsByGroup.set(item.group, list)
3016
+ }
3017
+ // One suite can own rows in several channels (REA's tools plus its
3018
+ // prompt section); the ranking merges by label so it reads as one suite.
3019
+ const merged = new Map()
3020
+ for (const group of groups) {
3021
+ const label = String(group.label !== undefined && group.label !== null ? group.label : group.id)
3022
+ const key = label.toLowerCase()
3023
+ const items = itemsByGroup.get(group.id) || []
3024
+ const effective = items.reduce((sum, item) => (policyItemOn(snapshot, item) ? sum + item.tokens : sum), 0)
3025
+ const entry = merged.get(key) || { id: key, label, channel: group.channel, channels: [], tokens: 0, effective: 0 }
3026
+ if (entry.channels.indexOf(group.channel) < 0) entry.channels.push(group.channel)
3027
+ entry.tokens += Number(group.tokens) || 0
3028
+ entry.effective += effective
3029
+ merged.set(key, entry)
3030
+ }
3031
+ const rows = [...merged.values()]
3032
+ .sort((left, right) => right.tokens - left.tokens)
3033
+ .slice(0, 8)
3034
+ const max = rows.reduce((value, row) => Math.max(value, Number(row.tokens) || 0), 1)
3035
+ const total = Math.max(1, effectiveTotalOf(snapshot))
3036
+ return h(
3037
+ 'div',
3038
+ { className: 'ci-card' },
3039
+ h('div', { className: 'ci-cardhead' }, h('h2', null, t('v2.heaviestTitle')), h('span', { className: 'sp' }), h('span', { className: 'hint' }, t('v2.heaviestHint'))),
3040
+ rows.length === 0
3041
+ ? h('div', { className: 'ci-note' }, t('v2.heaviestEmpty'))
3042
+ : h(
3043
+ 'div',
3044
+ { className: 'ci-bars' },
3045
+ rows.map((group) =>
3046
+ h(
3047
+ 'div',
3048
+ {
3049
+ className: 'ci-barrow' + (group.effective === 0 ? ' off' : ''),
3050
+ key: group.id,
3051
+ title: `${group.label} · ${t('total')} ${digits(group.tokens)} · ${t('after')} ${digits(group.effective)}`,
3052
+ },
3053
+ h('span', { className: 'n' }, groupLabelOf(t, group)),
3054
+ h(
3055
+ 'span',
3056
+ { className: 'ci-bar-track', style: { width: `${Math.max(2, ((Number(group.tokens) || 0) / max) * 100)}%` } },
3057
+ h('span', {
3058
+ className: 'ci-bar-fill',
3059
+ style: {
3060
+ width: `${group.tokens === 0 ? 0 : Math.max(0, Math.min(100, (group.effective / group.tokens) * 100))}%`,
3061
+ background: COLOR[group.channel],
3062
+ },
3063
+ }),
3064
+ ),
3065
+ h('span', { className: 't', style: { textAlign: 'right' } }, `${token(group.effective)} · ${pctText(group.effective, total)}`),
3066
+ ),
3067
+ ),
3068
+ ),
3069
+ )
3070
+ }
3071
+
3072
+ function EventsFeed({ events, t, limit, initial, bare }) {
3073
+ const [showAll, setShowAll] = useState(false)
3074
+ const data = events !== null && events.data !== null && events.data !== undefined ? events.data : null
3075
+ const list = data !== null && Array.isArray(data.events) ? data.events : []
3076
+ const coverage = data !== null && data.coverage !== null && typeof data.coverage === 'object' ? data.coverage : null
3077
+ const max = limit || 60
3078
+ const first = initial || 12
3079
+ const sliced = showAll ? list.slice(0, max) : list.slice(0, first)
3080
+ const failed = events !== null && events.status === 'failed'
3081
+ const loading = events !== null && (events.status === 'loading' || events.status === 'refreshing') && data === null
3082
+
3083
+ const paramsOf = (event) => {
3084
+ const params = event.params !== null && typeof event.params === 'object' ? event.params : {}
3085
+ const chips = []
3086
+ for (const key of ['group', 'name', 'scope', 'mode', 'preset', 'detail']) {
3087
+ const value = params[key]
3088
+ if (typeof value === 'string' && value.length > 0) chips.push(value.length > 60 ? value.slice(0, 60) + '…' : value)
3089
+ }
3090
+ if (typeof params.channel === 'string' && params.channel.length > 0) chips.push(t(params.channel))
3091
+ if (typeof params.op === 'string' && params.op.length > 0) {
3092
+ if (typeof params.channel === 'string') chips.push(params.op === 'off' ? t('turnedOff') : t('turnedOn'))
3093
+ else chips.push(params.op)
3094
+ }
3095
+ if (Number.isFinite(Number(params.count)) && Number(params.count) > 0) chips.push(`${params.count} ${t('items')}`)
3096
+ return chips
3097
+ }
3098
+
3099
+ return h(
3100
+ 'div',
3101
+ { className: (bare === true ? '' : 'ci-card ') + 'ci-events' },
3102
+ h(
3103
+ 'div',
3104
+ { className: 'ci-cardhead' },
3105
+ h('h2', null, t('v2.eventsTitle')),
3106
+ h('span', { className: 'sp' }),
3107
+ coverage !== null && Number.isFinite(Number(coverage.count))
3108
+ ? h('span', { className: 'hint' }, t('v2.eventsCoverage', { count: coverage.count, limit: coverage.limit || max }))
3109
+ : null,
3110
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: events.reload, title: t('refresh') }, t('refresh')),
3111
+ ),
3112
+ failed
3113
+ ? h(
3114
+ 'div',
3115
+ { className: 'ci-errorbar' },
3116
+ h('span', null, `${t('v2.eventsFailed')}:${errorText(events)}`),
3117
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: events.reload }, t('v2.retry')),
3118
+ )
3119
+ : null,
3120
+ loading
3121
+ ? h(
3122
+ 'div',
3123
+ { className: 'ci-skel-lines', 'aria-hidden': 'true' },
3124
+ [0, 1, 2, 3, 4, 5].map((index) => h('div', { className: 'line', key: index })),
3125
+ )
3126
+ : null,
3127
+ !loading && list.length === 0 && !failed ? h('div', { className: 'ci-note' }, t('v2.eventsEmpty')) : null,
3128
+ sliced.length === 0
3129
+ ? null
3130
+ : h(
3131
+ 'div',
3132
+ { className: 'ci-events-list', role: 'list', 'aria-label': t('v2.eventsTitle') },
3133
+ sliced.map((event, index) => {
3134
+ const kind = typeof event.kind === 'string' ? event.kind : 'unknown'
3135
+ const known = ['session-created', 'policy-saved', 'preset', 'budget', 'switch', 'undo', 'import', 'compaction', 'prune', 'model-switch', 'mode-toggle', 'diagnostic']
3136
+ const label = known.indexOf(kind) >= 0 ? t('ev.' + kind) : t('ev.unknown')
3137
+ const delta = Number(event.tokensDelta)
3138
+ const chips = paramsOf(event)
3139
+ return h(
3140
+ 'div',
3141
+ { className: 'ci-event', key: event.id || 'e' + index, role: 'listitem' },
3142
+ h('span', { className: 'dot k-' + kind, 'aria-hidden': 'true' }),
3143
+ h(
3144
+ 'div',
3145
+ { className: 'body' },
3146
+ h(
3147
+ 'div',
3148
+ { className: 'lbl' },
3149
+ label,
3150
+ Number.isFinite(delta) && delta !== 0
3151
+ ? h('span', { className: 'delta' }, ` ${delta < 0 ? '−' : '+'}${token(Math.abs(delta))}`)
3152
+ : null,
3153
+ ),
3154
+ chips.length === 0 ? null : h('div', { className: 'prm' }, chips.map((chip, chipIndex) => h('span', { key: chipIndex }, chip))),
3155
+ ),
3156
+ h('time', { className: 'when', dateTime: Number(event.at) > 0 ? new Date(event.at).toISOString() : undefined, title: fullTime(event.at) }, ago(event.at)),
3157
+ )
3158
+ }),
3159
+ ),
3160
+ !showAll && list.length > first
3161
+ ? h('button', { type: 'button', className: 'ci-btn ci-sm', style: { alignSelf: 'flex-start' }, onClick: () => setShowAll(true) }, t('v2.eventsMore', { count: Math.min(list.length, max) - first }))
3162
+ : null,
3163
+ )
3164
+ }
3165
+
3166
+ function SessionCards({ trend, t, sessionId, onRangeAll }) {
3167
+ const [query, setQuery] = useState('')
3168
+ const [sort, setSort] = useStoredState('insightsSort', 'recent')
3169
+ const [shown, setShown] = useState(24)
3170
+ const deferredQuery = useDeferredValue(query)
3171
+ const points = trend !== null && trend.data !== null && trend.data !== undefined && Array.isArray(trend.data.points) ? trend.data.points : []
3172
+ const needle = deferredQuery.trim().toLowerCase()
3173
+ const filtered = points.filter((point) => {
3174
+ if (needle.length === 0) return true
3175
+ const haystack = `${point.sessionId || ''} ${point.title || ''} ${point.cwd || ''}`.toLowerCase()
3176
+ return haystack.indexOf(needle) >= 0
3177
+ })
3178
+ const sorted = filtered.slice().sort((left, right) => {
3179
+ if (sort === 'heavy') return (Number(right.total) || 0) - (Number(left.total) || 0)
3180
+ if (sort === 'saved') return (Number(right.saved) || 0) - (Number(left.saved) || 0)
3181
+ return (Number(right.firstAt || right.at) || 0) - (Number(left.firstAt || left.at) || 0)
3182
+ })
3183
+ const visible = sorted.slice(0, shown)
3184
+ const miniBar = (point) => {
3185
+ const channels = point.channels
3186
+ if (channels === null || channels === undefined || typeof channels !== 'object') return h('span', { className: 'mini-bar unknown', 'aria-hidden': 'true' })
3187
+ const total = Math.max(1, Number(point.total) || 0)
3188
+ return h(
3189
+ 'span',
3190
+ { className: 'mini-bar', 'aria-hidden': 'true', title: t('v2.crossTitle') },
3191
+ CHANNELS.filter((channel) => Number(channels[channel]) > 0).map((channel) =>
3192
+ h('span', { key: channel, style: { width: `${Math.max(1, (Number(channels[channel]) / total) * 100)}%`, background: COLOR[channel] } }),
3193
+ ),
3194
+ )
3195
+ }
3196
+ return h(
3197
+ 'div',
3198
+ { className: 'ci-card' },
3199
+ h(
3200
+ 'div',
3201
+ { className: 'ci-cardhead' },
3202
+ h('h2', null, t('v2.sessions')),
3203
+ h('span', { className: 'hint' }, t('v2.sessionsCount', { count: sorted.length })),
3204
+ ),
3205
+ h(
3206
+ 'div',
3207
+ { className: 'ci-session-toolbar' },
3208
+ h('input', {
3209
+ className: 'ci-input',
3210
+ placeholder: t('v2.sessionSearch'),
3211
+ value: query,
3212
+ onChange: (event) => setQuery(event.target.value),
3213
+ 'aria-label': t('v2.sessionSearch'),
3214
+ }),
3215
+ h(
3216
+ 'div',
3217
+ { className: 'ci-seg ci-small', role: 'group', 'aria-label': t('v2.sortLabel') },
3218
+ [
3219
+ ['recent', t('v2.sortRecent')],
3220
+ ['heavy', t('v2.sortHeavy')],
3221
+ ['saved', t('v2.sortSaved')],
3222
+ ].map(([key, label]) =>
3223
+ h('button', { key, type: 'button', className: sort === key ? 'on' : '', 'aria-pressed': sort === key ? 'true' : 'false', onClick: () => setSort(key) }, label),
3224
+ ),
3225
+ ),
3226
+ ),
3227
+ sorted.length === 0
3228
+ ? h(
3229
+ 'div',
3230
+ { className: 'ci-empty-next' },
3231
+ h('span', null, t('v2.noSessions')),
3232
+ onRangeAll === undefined ? null : h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: onRangeAll }, t('trend.rangeAll')),
3233
+ )
3234
+ : h(
3235
+ 'div',
3236
+ { className: 'ci-session-grid' },
3237
+ visible.map((point) => {
3238
+ const live = sessionId !== undefined && sessionId !== '' && point.sessionId === sessionId
3239
+ return h(
3240
+ 'div',
3241
+ { className: 'ci-session' + (live ? ' live' : ''), key: point.sessionId || String(point.at), title: `${point.sessionId || ''}${point.cwd ? ' · ' + point.cwd : ''}` },
3242
+ h(
3243
+ 'div',
3244
+ { className: 'top' },
3245
+ h('span', { className: 'sid' }, shortId(point.sessionId)),
3246
+ live ? h('span', { className: 'ci-badge accent' }, t('v2.currentSession')) : null,
3247
+ h('span', { className: 'when' }, dayLabel(Number(point.firstAt || point.at))),
3248
+ ),
3249
+ h('div', { className: 'big' }, token(Number(point.total) || 0), h('small', null, t('tokens'))),
3250
+ h('div', { className: 'sub' }, `${t('trend.effective')} ${token(Number(point.effective) || 0)} · ${t('savable')} ${token(Number(point.saved) || 0)}`),
3251
+ miniBar(point),
3252
+ h(
3253
+ 'div',
3254
+ { className: 'badges' },
3255
+ point.source === 'log' ? h('span', { className: 'ci-badge' }, t('v2.badgeLog')) : h('span', { className: 'ci-badge' }, t('v2.badgeMeasured')),
3256
+ Number(point.samples) > 1 ? h('span', { className: 'ci-badge' }, t('v2.samples', { count: point.samples })) : null,
3257
+ point.compactions !== null && point.compactions !== undefined && Number(point.compactions.count) > 0
3258
+ ? h('span', { className: 'ci-badge' }, t('v2.compactions', { count: point.compactions.count, saved: token(point.compactions.freed) }))
3259
+ : null,
3260
+ point.channels === null || point.channels === undefined ? h('span', { className: 'ci-badge' }, t('v2.channelsUnknown')) : null,
3261
+ ),
3262
+ )
3263
+ }),
3264
+ ),
3265
+ sorted.length > visible.length
3266
+ ? h(
3267
+ 'button',
3268
+ {
3269
+ type: 'button',
3270
+ className: 'ci-btn ci-sm',
3271
+ style: { alignSelf: 'flex-start' },
3272
+ onClick: () => setShown((previous) => previous + 24),
3273
+ },
3274
+ t('v2.showMore', { count: Math.min(24, sorted.length - visible.length) }),
3275
+ )
3276
+ : null,
3277
+ )
3278
+ }
3279
+
3280
+ // Cross-session KPI row: the insights page answers "how big has this been
3281
+ // over time", not "what is on screen". The current session's numbers move
3282
+ // to one compact line so the trend card owns the first screen.
3283
+ function InsightKpis({ aggregate, coverage, t }) {
3284
+ const rows = [
3285
+ {
3286
+ key: 'v2.kpiMeasured',
3287
+ value: aggregate === null ? '—' : `${aggregate.measured ?? '—'}/${aggregate.sessions ?? '—'}`,
3288
+ sub: t('v2.kpiMeasuredSub'),
3289
+ title: coverage === null ? '' : t('trend.coverage', { recorded: coverage.recorded ?? '—', known: coverage.known ?? '—' }),
3290
+ },
3291
+ { key: 'trend.avg', value: aggregate === null ? '—' : token(aggregate.avgTotal), sub: t('trend.avgSub'), title: t('trend.avgSub') },
3292
+ { key: 'trend.max', value: aggregate === null ? '—' : token(aggregate.maxTotal), sub: t('trend.maxSub'), title: t('trend.maxSub') },
3293
+ { key: 'trend.saved', value: aggregate === null ? '—' : token(aggregate.totalSaved), sub: t('trend.savedSub'), title: t('trend.savedSub') },
3294
+ ]
3295
+ return h(
3296
+ 'div',
3297
+ { className: 'ci-kpis' },
3298
+ rows.map((row) =>
3299
+ h(
3300
+ 'div',
3301
+ { className: 'ci-kpi', key: row.key, title: row.title || null },
3302
+ h('div', { className: 'k' }, t(row.key)),
3303
+ h('div', { className: 'v' }, row.value),
3304
+ h('div', { className: 's' }, row.sub),
3305
+ ),
3306
+ ),
3307
+ )
3308
+ }
3309
+
3310
+ function InsightsTab({ snapshot, t, sessionId, onOpenContent, onOpenTab, act }) {
3311
+ const [range, setRange] = useStoredState('trendRange', 'all')
3312
+ const trend = useTrend(range, true)
3313
+ const events = useEvents(sessionId, true)
3314
+ const data = trend.data !== null && trend.data !== undefined ? trend.data : null
3315
+ const aggregate = data !== null && data.aggregate !== null && typeof data.aggregate === 'object' ? data.aggregate : null
3316
+ const coverage = data !== null && data.coverage !== null && typeof data.coverage === 'object' ? data.coverage : null
3317
+ const backfilling = data !== null && data.backfilling === true
3318
+ const points = data !== null && Array.isArray(data.points) ? data.points : []
3319
+ const currentTotals = snapshot.effective && snapshot.effective.totals ? snapshot.effective.totals : snapshot.totals
3320
+ const context = snapshot.context !== null && snapshot.context !== undefined ? snapshot.context : null
3321
+ const windowKnown = context !== null && context.window !== null && context.used !== null
3322
+ const aggCells = aggregate === null ? [] : [
3323
+ { key: 'v2.sessionsCount', value: aggregate.sessions, label: t('v2.sessionsCount', { count: aggregate.sessions }) },
3324
+ { key: 'trend.measured', value: aggregate.measured, label: t('trend.measured', { count: aggregate.measured }) },
3325
+ { key: 'trend.avg', value: token(aggregate.avgTotal), label: t('trend.avg') },
3326
+ { key: 'trend.max', value: token(aggregate.maxTotal), label: t('trend.max') },
3327
+ { key: 'trend.saved', value: token(aggregate.totalSaved), label: t('trend.saved') },
3328
+ ]
3329
+ return h(
3330
+ 'div',
3331
+ { className: 'ci-insights' },
3332
+ h(
3333
+ 'div',
3334
+ { className: 'ci-inline-meta' },
3335
+ h('span', null, t('v2.insightsSub')),
3336
+ h('span', { style: { flex: '1 1 auto' } }),
3337
+ h(RangePills, {
3338
+ value: range,
3339
+ label: t('trend.rangeLabel'),
3340
+ options: [
3341
+ ['7d', t('trend.range7')],
3342
+ ['30d', t('trend.range30')],
3343
+ ['all', t('trend.rangeAll')],
3344
+ ],
3345
+ onChange: setRange,
3346
+ }),
3347
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: () => Promise.all([trend.reload(), events.reload()]).catch(() => {}) }, t('refresh')),
3348
+ ),
3349
+ h(InsightKpis, { aggregate, coverage, t }),
3350
+ h(
3351
+ 'div',
3352
+ { className: 'ci-insight-current' },
3353
+ h('span', null, t('v2.currentSession')),
3354
+ h('span', null, `${t('total')} `, h('b', null, token(currentTotals.tokens))),
3355
+ h('span', null, `${t('window')} `, h('b', null, windowKnown ? `${token(context.used)} / ${token(context.window)}` : t('noWindow'))),
3356
+ h('span', null, `${t('savable')} `, h('b', null, token(currentTotals.savableTokens))),
3357
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: () => onOpenTab('manage') }, t('v2.goManage')),
3358
+ ),
3359
+ h(RequestStrip, { snapshot, t }),
3360
+ h(
3361
+ 'div',
3362
+ { className: 'ci-insight-top' },
3363
+ h(
3364
+ 'div',
3365
+ { className: 'ci-card' },
3366
+ h(
3367
+ 'div',
3368
+ { className: 'ci-cardhead' },
3369
+ h('h2', null, t('trend.title')),
3370
+ h('span', { className: 'sp' }),
3371
+ h('span', { className: 'hint' }, t('trend.legendHint')),
3372
+ ),
3373
+ aggCells.length === 0
3374
+ ? null
3375
+ : h(
3376
+ 'div',
3377
+ { className: 'ci-trend-agg' },
3378
+ aggCells.map((cell) =>
3379
+ h('span', { className: 'cell', key: cell.key }, cell.label, h('b', null, cell.value === undefined || cell.value === null ? '—' : String(cell.value))),
3380
+ ),
3381
+ ),
3382
+ trend.status === 'failed'
3383
+ ? h(
3384
+ 'div',
3385
+ { className: 'ci-errorbar' },
3386
+ h('span', null, `${t('trend.loadFailed')}:${errorText(trend)}`),
3387
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: trend.reload }, t('trend.retry')),
3388
+ )
3389
+ : null,
3390
+ trend.status === 'loading' && data === null
3391
+ ? h(
3392
+ 'div',
3393
+ { className: 'ci-skel-lines', 'aria-hidden': 'true' },
3394
+ h('div', { className: 'ci-skel-chart' }, [38, 62, 44, 71, 55, 83, 49, 66, 40, 74].map((height, index) => h('span', { key: index, style: { height: height + '%' } }))),
3395
+ h('div', { className: 'line' }),
3396
+ h('div', { className: 'line' }),
3397
+ )
3398
+ : h(TrendChart, { points, t, range }),
3399
+ coverage !== null
3400
+ ? h('div', { className: 'ci-trend-note' }, t('trend.coverage', { recorded: coverage.recorded ?? '—', known: coverage.known ?? '—' }), ' · ', t('trend.coverageFootnote'))
3401
+ : null,
3402
+ backfilling ? h('div', { className: 'ci-trend-note' }, t('trend.backfilling')) : null,
3403
+ ),
3404
+ h('div', { className: 'ci-card ci-events-card' }, h(EventsFeed, { events, t, limit: 60, initial: 4, bare: true })),
3405
+ ),
3406
+ h('div', { className: 'ci-grid2' }, h(CrossComposition, { aggregate, t }), h(HeaviestSuites, { snapshot, t })),
3407
+ h(SessionCards, { trend, t, sessionId, onRangeAll: () => setRange('all') }),
3408
+ h('div', { className: 'ci-foot' }, t('v2.aboutHonesty')),
3409
+ )
3410
+ }
3411
+
3412
+ // ------------------------------------------------------- content drawer
3413
+ //
3414
+ // A right-hand overlay that shows one item's raw content. Everything here
3415
+ // is plain React text: no raw-HTML injection anywhere, so a tool
3416
+ // description or an AGENTS.md that contains HTML reads as text.
3417
+ function ContentDrawer({ target, sessionId, t, onClose }) {
3418
+ const open = target !== null && target !== undefined
3419
+ const content = useContent(open ? target : null, sessionId)
3420
+ const [query, setQuery] = useState('')
3421
+ const [linesOn, setLinesOn] = useStoredState('contentLines', true)
3422
+ const [copied, setCopied] = useState('')
3423
+ const [view, setView] = useState('desc')
3424
+ const deferredQuery = useDeferredValue(query)
3425
+ const panelRef = useRef(null)
3426
+ const copyTimer = useRef(null)
3427
+ const restoreRef = useRef(null)
3428
+ const closeRef = useRef(null)
3429
+
3430
+ useEffect(() => {
3431
+ if (open !== true) return undefined
3432
+ restoreRef.current = typeof document !== 'undefined' ? document.activeElement : null
3433
+ const timer = setTimeout(() => {
3434
+ if (closeRef.current && typeof closeRef.current.focus === 'function') closeRef.current.focus()
3435
+ }, 30)
3436
+ return () => {
3437
+ clearTimeout(timer)
3438
+ const previous = restoreRef.current
3439
+ if (previous && typeof previous.focus === 'function') {
3440
+ try {
3441
+ previous.focus()
3442
+ } catch {
3443
+ /* the trigger may be gone after a re-render */
3444
+ }
3445
+ }
3446
+ }
3447
+ }, [open])
3448
+
3449
+ useEffect(() => {
3450
+ if (open !== true) return undefined
3451
+ setQuery('')
3452
+ setCopied('')
3453
+ setView('desc')
3454
+ return undefined
3455
+ }, [open, target === null || target === undefined ? '' : target.id])
3456
+
3457
+ useEffect(() => () => { if (copyTimer.current !== null) clearTimeout(copyTimer.current) }, [])
3458
+
3459
+ // Focus trap + Escape. Capture phase so the host's own Escape handlers
3460
+ // (e.g. closing the side panel) do not fight the drawer.
3461
+ useEffect(() => {
3462
+ if (open !== true) return undefined
3463
+ const onKeyDown = (event) => {
3464
+ if (event.key === 'Escape') {
3465
+ event.preventDefault()
3466
+ event.stopPropagation()
3467
+ onClose()
3468
+ return
3469
+ }
3470
+ if (event.key !== 'Tab') return
3471
+ const root = panelRef.current
3472
+ if (!root) return
3473
+ const nodes = root.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
3474
+ const list = []
3475
+ for (const node of nodes) {
3476
+ if (node.disabled === true) continue
3477
+ if (node.getAttribute('aria-hidden') === 'true') continue
3478
+ if (node.offsetParent === null && node !== document.activeElement) continue
3479
+ list.push(node)
3480
+ }
3481
+ if (list.length === 0) return
3482
+ const first = list[0]
3483
+ const last = list[list.length - 1]
3484
+ if (event.shiftKey === true && document.activeElement === first) {
3485
+ event.preventDefault()
3486
+ last.focus()
3487
+ } else if (event.shiftKey !== true && document.activeElement === last) {
3488
+ event.preventDefault()
3489
+ first.focus()
3490
+ }
3491
+ }
3492
+ window.addEventListener('keydown', onKeyDown, true)
3493
+ return () => window.removeEventListener('keydown', onKeyDown, true)
3494
+ }, [open, onClose])
3495
+
3496
+ if (open !== true) return null
3497
+
3498
+ const data = content.data !== null && content.data !== undefined ? content.data : null
3499
+ const body = data !== null && typeof data.content === 'string' ? data.content : ''
3500
+ const info = data !== null && data.item !== null && typeof data.item === 'object' ? data.item : { name: target.name, channel: target.channel, tokens: target.tokens, chars: target.chars }
3501
+ const name = typeof info.name === 'string' && info.name.length > 0 ? info.name : String(target.name || target.id || '')
3502
+ const channel = typeof info.channel === 'string' ? info.channel : String(target.channel || '')
3503
+ const contentType = data !== null && typeof data.contentType === 'string' ? data.contentType : 'text'
3504
+ const sourcePath = data !== null && typeof data.sourcePath === 'string' ? data.sourcePath : ''
3505
+ const truncated = data !== null && data.truncated === true
3506
+ const limit = data !== null && Number(data.limit) > 0 ? data.limit : 262144
3507
+ const note = data !== null && typeof data.note === 'string' ? data.note : ''
3508
+ const bytes = data !== null && Number.isFinite(Number(data.bytes)) ? Number(data.bytes) : Number(info.chars) || body.length
3509
+ const chars = Number.isFinite(Number(info.chars)) ? Number(info.chars) : body.length
3510
+ const tokens = Number.isFinite(Number(info.tokens)) ? Number(info.tokens) : Math.round(chars / 3.5)
3511
+ const groupLabel = target.group !== undefined && target.group !== null ? String(target.group) : ''
3512
+
3513
+ const allLines = body.length === 0 ? [] : body.split('\n')
3514
+ const maxLines = 4000
3515
+ const shownLines = allLines.length > maxLines ? allLines.slice(0, maxLines) : allLines
3516
+ const needle = deferredQuery.trim()
3517
+ const lowerNeedle = needle.toLowerCase()
3518
+ const matchInfo = (() => {
3519
+ if (needle.length === 0 || body.length === 0) return { count: 0, lines: 0 }
3520
+ const lower = body.toLowerCase()
3521
+ let count = 0
3522
+ let at = 0
3523
+ while (count < 5000) {
3524
+ const found = lower.indexOf(lowerNeedle, at)
3525
+ if (found < 0) break
3526
+ count += 1
3527
+ at = found + lowerNeedle.length
3528
+ }
3529
+ let lines = 0
3530
+ for (const line of shownLines) if (line.toLowerCase().indexOf(lowerNeedle) >= 0) lines += 1
3531
+ return { count, lines }
3532
+ })()
3533
+
3534
+ const markLine = (text, index) => {
3535
+ if (needle.length === 0) return text
3536
+ const lower = text.toLowerCase()
3537
+ if (lower.indexOf(lowerNeedle) < 0) return text
3538
+ const out = []
3539
+ let at = 0
3540
+ let count = 0
3541
+ while (count < 400) {
3542
+ const found = lower.indexOf(lowerNeedle, at)
3543
+ if (found < 0) break
3544
+ if (found > at) out.push(text.slice(at, found))
3545
+ out.push(h('mark', { className: 'ci-content-hit', key: 'm' + index + ':' + count }, text.slice(found, found + needle.length)))
3546
+ at = found + needle.length
3547
+ count += 1
3548
+ }
3549
+ if (at < text.length) out.push(text.slice(at))
3550
+ return out
3551
+ }
3552
+
3553
+ const copyText = async (value, key) => {
3554
+ try {
3555
+ if (!navigator.clipboard || typeof navigator.clipboard.writeText !== 'function') throw new Error('clipboard-unavailable')
3556
+ await navigator.clipboard.writeText(value)
3557
+ setCopied(key)
3558
+ } catch {
3559
+ setCopied('error')
3560
+ }
3561
+ if (copyTimer.current !== null) clearTimeout(copyTimer.current)
3562
+ copyTimer.current = setTimeout(() => setCopied(''), 1800)
3563
+ }
3564
+
3565
+ const knownNotes = ['catalog', 'file', 'assemble', 'snapshot']
3566
+
3567
+ // Tools arrive as pretty-printed JSON. A raw dump is hard to scan, so
3568
+ // the drawer splits it the way a reader needs it: description, a
3569
+ // parameter table, and the untouched JSON as the audit view. Non-JSON
3570
+ // content has no tabs — it is already text.
3571
+ const isJson = contentType === 'json'
3572
+ let parsed = null
3573
+ if (isJson && body.length > 0) {
3574
+ try {
3575
+ parsed = JSON.parse(body)
3576
+ } catch {
3577
+ parsed = null
3578
+ }
3579
+ }
3580
+ const parameters = parsed !== null && parsed.parameters !== null && typeof parsed.parameters === 'object' ? parsed.parameters : null
3581
+ const properties = parameters !== null && parameters.properties !== null && typeof parameters.properties === 'object' ? parameters.properties : null
3582
+ const requiredNames = parameters !== null && Array.isArray(parameters.required) ? parameters.required.map(String) : []
3583
+ const hasStructured = isJson && parsed !== null && typeof parsed === 'object'
3584
+ const mode = hasStructured ? view : 'raw'
3585
+ const sharePct = target !== null && target !== undefined && Number.isFinite(Number(target.share)) ? Number(target.share) : null
3586
+ const savedTokens = target !== null && target !== undefined && Number.isFinite(Number(target.saved)) ? Math.max(0, Number(target.saved)) : 0
3587
+ const propertyRows = properties === null ? [] : Object.keys(properties).map((key) => {
3588
+ const spec = properties[key] !== null && typeof properties[key] === 'object' ? properties[key] : {}
3589
+ const type = typeof spec.type === 'string' ? spec.type : spec.type !== undefined ? String(spec.type) : '—'
3590
+ return {
3591
+ name: key,
3592
+ type,
3593
+ required: requiredNames.indexOf(key) >= 0,
3594
+ desc: typeof spec.description === 'string' && spec.description.length > 0 ? spec.description : '—',
3595
+ }
3596
+ })
3597
+ const copyLabel = isJson ? t('content.copyJson') : t('content.copy')
3598
+ const bodyLines = () =>
3599
+ h(
3600
+ 'div',
3601
+ { className: 'ci-content-lines' },
3602
+ shownLines.map((line, index) =>
3603
+ h(
3604
+ 'div',
3605
+ { className: 'ci-content-line', key: index },
3606
+ linesOn ? h('span', { className: 'ln', 'aria-hidden': 'true' }, String(index + 1)) : null,
3607
+ h('span', { className: 'tx' }, markLine(line, index)),
3608
+ ),
861
3609
  ),
3610
+ )
3611
+
3612
+ return h(
3613
+ React.Fragment,
3614
+ null,
3615
+ h('style', null, STYLE),
3616
+ h('div', {
3617
+ className: 'ci-drawer-backdrop',
3618
+ 'aria-hidden': 'true',
3619
+ onClick: onClose,
3620
+ }),
3621
+ h(
3622
+ 'section',
3623
+ {
3624
+ className: 'ci-drawer',
3625
+ ref: panelRef,
3626
+ role: 'dialog',
3627
+ 'aria-modal': 'true',
3628
+ 'aria-labelledby': 'ci-drawer-title',
3629
+ tabIndex: -1,
3630
+ },
862
3631
  h(
863
3632
  'div',
864
- { className: 'ci-seg' },
865
- [
866
- ['tokens', t('sortTokens')],
867
- ['name', t('sortByName')],
868
- ].map(([key, label]) => h('button', { key, type: 'button', className: sort === key ? 'on' : '', onClick: () => setSort(key) }, label)),
3633
+ { className: 'ci-drawer-head' },
3634
+ h(
3635
+ 'div',
3636
+ { className: 'ci-drawer-title' },
3637
+ h(
3638
+ 'div',
3639
+ { className: 'ci-breadcrumb' },
3640
+ h('span', null, t('tabManage')),
3641
+ h('span', { className: 'sep' }, '/'),
3642
+ h(Dot, { channel }),
3643
+ h('span', null, t(channel)),
3644
+ groupLabel.length > 0 ? h('span', { className: 'sep' }, '/') : null,
3645
+ groupLabel.length > 0 ? h('span', null, groupLabel) : null,
3646
+ h('span', { className: 'sep' }, '/'),
3647
+ h('span', { className: 'last', title: name }, name),
3648
+ ),
3649
+ h('h2', { id: 'ci-drawer-title' }, name),
3650
+ h(
3651
+ 'div',
3652
+ { className: 'ci-inline-meta', style: { marginTop: 2 } },
3653
+ h('span', { title: t('content.tokensHint') }, `≈${token(tokens)} token`),
3654
+ sharePct === null ? null : h('span', null, `${Number(sharePct).toFixed(1)}% ${t('shareOf')}`),
3655
+ savedTokens > 0 ? h('span', { className: 'ci-delta', title: t('v2.savedHint', { tokens: digits(savedTokens) }) }, '−' + token(savedTokens)) : null,
3656
+ ),
3657
+ ),
3658
+ h(
3659
+ 'button',
3660
+ {
3661
+ type: 'button',
3662
+ className: 'ci-btn',
3663
+ ref: closeRef,
3664
+ 'data-autofocus': 'true',
3665
+ onClick: onClose,
3666
+ 'aria-label': t('content.close'),
3667
+ title: t('content.escHint'),
3668
+ },
3669
+ '×',
3670
+ ),
869
3671
  ),
870
- view === 'group'
871
- ? h(
872
- 'button',
873
- {
874
- type: 'button',
875
- className: 'ci-chip',
876
- onClick: () => {
877
- const next = {}
878
- for (const group of groups) next[group.id] = true
879
- setExpanded(next)
880
- },
881
- },
882
- t('expandAll'),
883
- )
884
- : null,
885
- view === 'group' && Object.keys(expanded).length > 0
886
- ? h('button', { type: 'button', className: 'ci-chip', onClick: () => setExpanded({}) }, t('collapseAll'))
887
- : null,
888
- ),
889
- h(
890
- 'div',
891
- { className: 'ci-table', role: 'group', 'aria-label': t('items') + ' · ' + items.length },
892
3672
  h(
893
3673
  'div',
894
- { className: 'ci-thead' },
895
- h('div', null, t('name')),
896
- h('div', null, t('channel')),
897
- h('div', { style: { textAlign: 'right' } }, t('tokens')),
898
- h('div', { style: { textAlign: 'right' } }, t('share')),
899
- h('div', { style: { textAlign: 'right' } }, t('switch')),
3674
+ { className: 'ci-drawer-tools' },
3675
+ h('span', { className: 'ci-badge' }, t('content.type.' + (['json', 'markdown', 'text'].indexOf(contentType) >= 0 ? contentType : 'text'))),
3676
+ h('span', { className: 'ci-badge' }, h(Dot, { channel }), t(channel)),
3677
+ note.length > 0 ? h('span', { className: 'ci-badge' }, knownNotes.indexOf(note) >= 0 ? t('content.note.' + note) : note) : null,
3678
+ h('span', { style: { flex: '1 1 auto' } }),
3679
+ h(
3680
+ 'button',
3681
+ {
3682
+ type: 'button',
3683
+ className: 'ci-btn ci-sm',
3684
+ disabled: body.length === 0,
3685
+ onClick: () => copyText(body, 'content'),
3686
+ },
3687
+ copied === 'content' ? t('content.copied') : copied === 'error' ? t('content.copyFailed') : copyLabel,
3688
+ ),
900
3689
  ),
901
- items.length === 0
3690
+ hasStructured || mode === 'raw'
902
3691
  ? h(
903
3692
  'div',
904
- { className: 'ci-empty' },
905
- h('div', null, query.trim().length > 0 ? t('noMatch') : t('empty')),
906
- query.trim().length > 0 || filter !== 'all' || onlySwitchable
3693
+ { className: 'ci-drawer-tools' },
3694
+ h('span', { className: 'ci-inline-meta' }, t('content.meta', { bytes: digits(bytes), chars: digits(chars), tokens: token(tokens) })),
3695
+ hasStructured
907
3696
  ? h(
908
- 'button',
909
- {
910
- type: 'button',
911
- className: 'ci-btn',
912
- style: { marginTop: 8 },
913
- onClick: () => {
914
- setQuery('')
915
- setFilter('all')
916
- setOnlySwitchable(false)
917
- },
918
- },
919
- t('clearFilters'),
3697
+ 'div',
3698
+ { className: 'ci-seg ci-small', role: 'group', 'aria-label': t('content.viewLabel') },
3699
+ [
3700
+ ['desc', t('content.viewDesc')],
3701
+ ['params', t('content.viewParams')],
3702
+ ['raw', t('content.viewRaw')],
3703
+ ].map(([key, label]) =>
3704
+ h('button', { key, type: 'button', className: mode === key ? 'on' : '', 'aria-pressed': mode === key ? 'true' : 'false', onClick: () => setView(key) }, label),
3705
+ ),
3706
+ )
3707
+ : null,
3708
+ h('span', { style: { flex: '1 1 auto' } }),
3709
+ mode === 'raw'
3710
+ ? h(
3711
+ React.Fragment,
3712
+ null,
3713
+ h('span', { className: 'ci-inline-meta' }, t('content.lines')),
3714
+ h(Switch, { on: linesOn, onChange: (next) => setLinesOn(next), title: t('content.lines') }),
920
3715
  )
921
3716
  : null,
922
3717
  )
923
- : view === 'group'
924
- ? groups.map((group) => {
925
- const state = groupState(group)
926
- const open = expanded[group.id] === true
927
- return h(
928
- 'div',
929
- { className: 'ci-group', key: group.id },
930
- h(
931
- 'div',
932
- {
933
- className: 'ci-row ci-grouphead',
934
- role: 'button',
935
- tabIndex: 0,
936
- 'aria-expanded': open ? 'true' : 'false',
937
- onClick: () => toggleExpanded(group.id),
938
- onKeyDown: (event) => {
939
- if (event.key === 'Enter' || event.key === ' ') {
940
- event.preventDefault()
941
- toggleExpanded(group.id)
942
- }
943
- },
944
- },
945
- h(
946
- 'div',
947
- { className: 'n' },
948
- h('span', { className: 'ci-caret' + (open ? ' open' : '') }, open ? '▾' : '▸'),
949
- h(HitMark, { text: groupLabelOf(t, group), needle }),
950
- h('span', { className: 'id' }, `${group.items.length} ${t('items')}`),
951
- plannedKeys.size > 0 && group.items.filter((item) => plannedKeys.has(item.channel + ':' + item.name)).length > 0
952
- ? h(
953
- 'span',
954
- { className: 'ci-tag' },
955
- `${group.items.filter((item) => plannedKeys.has(item.channel + ':' + item.name)).length} ${t('outsideBudget')}`,
956
- )
957
- : null,
958
- ),
959
- h('div', { className: 'badge' }, h(Dot, { channel: group.channel }), t(group.channel)),
960
- h('div', { className: 'num' }, digits(group.tokens)),
961
- h('div', { className: 'num' }, `${pct(group.tokens, snapshot.totals.tokens)}%`),
962
- h(Switch, { on: state.on, mixed: state.mixed, disabled: busy || state.disabled, onChange: () => toggleGroup(group), title: group.label }),
963
- ),
964
- open
965
- ? group.items.map((item) => h(ItemRow, { key: itemKey(item), item, t, snapshot, isOn, onToggle, busy, nested: true, needle, planned: plannedKeys.has(item.channel + ":" + item.name) }))
966
- : null,
967
- )
968
- })
969
- : items.map((item) => h(ItemRow, { key: itemKey(item), item, t, snapshot, isOn, onToggle, busy, needle, planned: plannedKeys.has(item.channel + ":" + item.name) })),
970
- ),
971
- snapshot.closedGroups && snapshot.closedGroups.length > 0
972
- ? h(
973
- 'div',
974
- { className: 'ci-card' },
975
- h('h2', null, `${t('closedTitle')} · ${snapshot.closed.length} ${t('items')}`),
976
- h('div', { className: 'hint' }, t('closedHint')),
977
- h(
3718
+ : null,
3719
+ sourcePath.length > 0
3720
+ ? h(
978
3721
  'div',
979
- { className: 'ci-list' },
980
- snapshot.closedGroups.map((group) =>
981
- h(
982
- 'div',
983
- { className: 'ci-mini', key: group.id },
984
- h(Dot, { channel: group.channel }),
985
- h('span', { className: 'n', title: group.label }, group.label),
986
- h('span', { className: 't' }, `${group.items.length} ${t('items')}`),
987
- h('span', { className: 't' }, group.tokens > 0 ? digits(group.tokens) : '—'),
988
- h(
989
- 'button',
990
- {
991
- type: 'button',
992
- className: 'ci-btn',
993
- onClick: () =>
994
- act(
995
- { kind: 'names', channel: group.channel, names: group.items.map((item) => item.name), enabled: true },
996
- `${t('restoreGroup')} ${group.label}`,
997
- ),
998
- },
999
- t('restoreGroup'),
1000
- ),
1001
- ),
3722
+ { className: 'ci-drawer-source' },
3723
+ h('span', null, t('content.source')),
3724
+ h('span', { className: 'ci-drawer-path', title: sourcePath }, sourcePath),
3725
+ h(
3726
+ 'button',
3727
+ { type: 'button', className: 'ci-btn ci-sm', onClick: () => copyText(sourcePath, 'path') },
3728
+ copied === 'path' ? t('content.pathCopied') : t('content.copyPath'),
1002
3729
  ),
1003
- ),
1004
- )
1005
- : null,
1006
- h(
1007
- 'div',
1008
- { className: 'ci-note', style: { display: 'flex', alignItems: 'center', gap: 10 } },
1009
- h(
1010
- 'span',
1011
- null,
1012
- `${t('total')} ${digits(snapshot.totals.tokens)} · ${t('savable')} ${digits(snapshot.totals.savableTokens)} (${snapshot.totals.savablePercent}%) · ${onlySwitchable ? `${groups.length}/${snapshot.groups.length}` : String(snapshot.groups.length)} ${t('groups')} · ${t('locked')} ${snapshot.locks.length}`,
1013
- ),
1014
- snapshot.undo && snapshot.undo.available
3730
+ )
3731
+ : null,
3732
+ mode === 'raw' && body.length > 0
1015
3733
  ? h(
1016
- 'button',
1017
- {
1018
- type: 'button',
1019
- className: 'ci-btn',
1020
- disabled: busy,
1021
- title: snapshot.undo.last || '',
1022
- style: { maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
1023
- onClick: () => onUndo(),
1024
- },
1025
- `${t('undo')}${snapshot.undo.last ? ` · ${snapshot.undo.last}` : ''}`,
3734
+ 'div',
3735
+ { className: 'ci-drawer-tools' },
3736
+ h('input', {
3737
+ className: 'ci-input ci-drawer-search',
3738
+ placeholder: t('content.search'),
3739
+ value: query,
3740
+ onChange: (event) => setQuery(event.target.value),
3741
+ 'aria-label': t('content.search'),
3742
+ }),
3743
+ needle.length > 0 ? h('span', { className: 'ci-inline-meta' }, t('content.matchSummary', { lines: matchInfo.lines, count: matchInfo.count })) : null,
3744
+ h('span', { className: 'ci-inline-meta' }, t('content.linesMeta', { count: allLines.length })),
1026
3745
  )
1027
3746
  : null,
3747
+ truncated
3748
+ ? h('div', { className: 'ci-drawer-note' }, t('content.truncated', { limit: digits(limit) }))
3749
+ : null,
3750
+ h(
3751
+ 'div',
3752
+ { className: 'ci-drawer-body' },
3753
+ content.status === 'failed' && data === null
3754
+ ? h(
3755
+ 'div',
3756
+ { className: 'ci-drawer-empty' },
3757
+ h('div', { style: { marginBottom: 8 } }, `${t('content.failed')}:${errorText(content)}`),
3758
+ h('button', { type: 'button', className: 'ci-btn', onClick: content.reload }, t('content.retry')),
3759
+ )
3760
+ : content.status === 'loading' && data === null
3761
+ ? h(
3762
+ 'div',
3763
+ { className: 'ci-skel-lines', 'aria-hidden': 'true', style: { padding: '0 16px' } },
3764
+ [0, 1, 2, 3, 4, 5, 6, 7].map((index) => h('div', { className: 'line', key: index })),
3765
+ )
3766
+ : content.status === 'failed'
3767
+ ? h(
3768
+ 'div',
3769
+ { className: 'ci-errorbar', style: { margin: '0 16px 8px' } },
3770
+ h('span', null, t('content.failed')),
3771
+ h('button', { type: 'button', className: 'ci-btn ci-sm', onClick: content.reload }, t('content.retry')),
3772
+ )
3773
+ : null,
3774
+ content.status === 'failed' && data === null
3775
+ ? null
3776
+ : body.length === 0 && (content.status === 'ready' || content.status === 'failed')
3777
+ ? content.status === 'ready'
3778
+ ? h('div', { className: 'ci-drawer-empty' }, t('content.empty'))
3779
+ : null
3780
+ : mode === 'desc'
3781
+ ? h(
3782
+ 'div',
3783
+ { className: 'ci-drawer-sect' },
3784
+ h('h3', null, name),
3785
+ h('p', { className: 'ci-drawer-desc' }, parsed !== null && typeof parsed.description === 'string' && parsed.description.length > 0 ? parsed.description : t('content.noDesc')),
3786
+ )
3787
+ : mode === 'params'
3788
+ ? propertyRows.length === 0
3789
+ ? h('div', { className: 'ci-drawer-empty' }, t('content.noParams'))
3790
+ : h(
3791
+ 'table',
3792
+ { className: 'ci-param-table' },
3793
+ h(
3794
+ 'thead',
3795
+ null,
3796
+ h(
3797
+ 'tr',
3798
+ null,
3799
+ h('th', null, t('content.paramName')),
3800
+ h('th', null, t('content.paramType')),
3801
+ h('th', { style: { textAlign: 'center' } }, t('content.paramRequired')),
3802
+ h('th', null, t('content.paramDesc')),
3803
+ ),
3804
+ ),
3805
+ h(
3806
+ 'tbody',
3807
+ null,
3808
+ propertyRows.map((row) =>
3809
+ h(
3810
+ 'tr',
3811
+ { key: row.name },
3812
+ h('td', { className: 'name' }, row.name),
3813
+ h('td', { className: 'type' }, row.type),
3814
+ h('td', { className: 'req' }, row.required ? '✓' : '—'),
3815
+ h('td', { className: 'desc' }, row.desc),
3816
+ ),
3817
+ ),
3818
+ ),
3819
+ )
3820
+ : bodyLines(),
3821
+ allLines.length > maxLines ? h('div', { className: 'ci-drawer-note' }, t('content.clipped', { count: digits(maxLines) })) : null,
3822
+ ),
3823
+ h(
3824
+ 'div',
3825
+ { className: 'ci-drawer-foot' },
3826
+ h('span', null, t('content.escHint')),
3827
+ h('span', null, t('content.readonly')),
3828
+ ),
1028
3829
  ),
1029
3830
  )
1030
3831
  }
@@ -1179,7 +3980,7 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1179
3980
  h('h2', null, t('promptPrefix')),
1180
3981
  h('textarea', {
1181
3982
  className: 'ci-input',
1182
- style: { height: 72, resize: 'vertical', fontFamily: 'inherit' },
3983
+ style: { height: 72, resize: 'vertical', fontFamily: 'inherit', maxWidth: 720 },
1183
3984
  value: prefix,
1184
3985
  onChange: (event) => {
1185
3986
  setPrefix(event.target.value)
@@ -1191,7 +3992,7 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1191
3992
  h('h2', { style: { marginTop: 6 } }, t('promptSuffix')),
1192
3993
  h('textarea', {
1193
3994
  className: 'ci-input',
1194
- style: { height: 56, resize: 'vertical', fontFamily: 'inherit' },
3995
+ style: { height: 56, resize: 'vertical', fontFamily: 'inherit', maxWidth: 720 },
1195
3996
  value: suffix,
1196
3997
  onChange: (event) => {
1197
3998
  setSuffix(event.target.value)
@@ -1507,14 +4308,110 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1507
4308
 
1508
4309
  // ------------------------------------------------------------ panel
1509
4310
 
4311
+
4312
+ function shortId(id) {
4313
+ const text = String(id ?? '')
4314
+ const match = /([0-9a-f]{8})-[0-9a-f]{4}/.exec(text)
4315
+ return match === null ? text.slice(0, 12) : match[1]
4316
+ }
4317
+
4318
+ // Browser-local preferences. They never touch policy.json — they only
4319
+ // change how this panel renders for this user.
4320
+ function PreferencesCard({ t }) {
4321
+ const [linesOn, setLinesOn] = useStoredState('contentLines', true)
4322
+ const [range, setRange] = useStoredState('trendRange', 'all')
4323
+ return h(
4324
+ 'div',
4325
+ { className: 'ci-card' },
4326
+ h('h2', null, t('v2.prefs')),
4327
+ h(
4328
+ 'div',
4329
+ { className: 'ci-prefs' },
4330
+ h(
4331
+ 'div',
4332
+ { className: 'ci-prefrow' },
4333
+ h('span', { className: 'lbl' }, t('v2.prefLines'), h('span', { className: 'hint' }, t('v2.prefNote'))),
4334
+ h(Switch, { on: linesOn, onChange: (next) => setLinesOn(next), title: t('v2.prefLines') }),
4335
+ ),
4336
+ h(
4337
+ 'div',
4338
+ { className: 'ci-prefrow' },
4339
+ h('span', { className: 'lbl' }, t('v2.prefRange')),
4340
+ h(RangePills, {
4341
+ value: range,
4342
+ label: t('v2.prefRange'),
4343
+ options: [
4344
+ ['7d', t('trend.range7')],
4345
+ ['30d', t('trend.range30')],
4346
+ ['all', t('trend.rangeAll')],
4347
+ ],
4348
+ onChange: setRange,
4349
+ }),
4350
+ ),
4351
+ ),
4352
+ )
4353
+ }
4354
+
4355
+ // Everything the panel knows about versions, and the honest limits of the
4356
+ // v2 data set. No plugin version is invented: the host snapshot does not
4357
+ // carry one, so this card says what is actually known.
4358
+ function VersionCard({ snapshot, t }) {
4359
+ const host = snapshot.host !== null && snapshot.host !== undefined ? snapshot.host : {}
4360
+ const api = Number(snapshot.apiVersion) || 1
4361
+ return h(
4362
+ 'div',
4363
+ { className: 'ci-card' },
4364
+ h('h2', null, t('v2.version')),
4365
+ host.supported === false ? h('div', { className: 'ci-note warn' }, t('hostOld', { version: host.version, tested: host.tested })) : null,
4366
+ h(
4367
+ 'div',
4368
+ { className: 'ci-kv' },
4369
+ h('span', { className: 'k' }, t('v2.versionHost')),
4370
+ h('b', null, host.version ? t('v2.versionLine', { version: host.version, tested: host.tested }) : t('v2.versionUnknown')),
4371
+ h('span', { className: 'k' }, t('v2.apiVersionLabel')),
4372
+ h('b', null, `v${api}`),
4373
+ h('span', { className: 'k' }, t('v2.languageLabel')),
4374
+ h('b', null, t.language || '—'),
4375
+ ),
4376
+ h('div', { className: 'ci-note' }, t('v2.aboutV2')),
4377
+ h('div', { className: 'ci-note' }, t('v2.aboutData')),
4378
+ h('div', { className: 'ci-note' }, t('v2.aboutHonesty')),
4379
+ h('div', { className: 'ci-foot' }, t('v2.docsHint')),
4380
+ )
4381
+ }
4382
+
4383
+ // 设置 is everything about the plugin itself and the policy document, so
4384
+ // it stacks the three former tabs instead of hiding them behind another
4385
+ // level of tabs.
4386
+ function SettingsPage({ snapshot, t, act, sessionId, notify }) {
4387
+ return h(
4388
+ 'div',
4389
+ { className: 'ci-list' },
4390
+ h(SettingsTab, { snapshot, t, act, sessionId, notify }),
4391
+ h(BudgetTab, { snapshot, t, act }),
4392
+ h(PreferencesCard, { t }),
4393
+ h(AboutTab, { snapshot, t, sessionId }),
4394
+ h(VersionCard, { snapshot, t }),
4395
+ )
4396
+ }
4397
+
1510
4398
  function Panel({ props, compact }) {
1511
4399
  const sessionId = pickSessionId(props)
1512
4400
  const { status, data, error, reload } = useSnapshot(sessionId)
1513
4401
  const t = useLocale(data)
1514
- const [tab, setTab] = useStoredState('tab', 'list')
4402
+ // Migrate the old two-word tab ids: a stored 'list'/'budget'/'about'
4403
+ // would otherwise land on an empty body after this release.
4404
+ const [storedTab, setTab] = useStoredState('tab', 'manage')
4405
+ const tab = storedTab === 'list' ? 'manage' : storedTab === 'budget' || storedTab === 'about' ? 'settings' : storedTab === 'stats' ? 'insights' : storedTab
1515
4406
  const [filter, setFilter] = useState('all')
1516
4407
  const [busy, setBusy] = useState(false)
1517
4408
  const [notice, setNotice] = useState(null)
4409
+ const [drawer, setDrawer] = useState(null)
4410
+ const v2 = isV2(data)
4411
+ // A v1 host hides the new tab; a stored 'insights' falls back instead of
4412
+ // rendering an empty body.
4413
+ const activeTab = tab === 'insights' && v2 !== true ? 'manage' : tab
4414
+ const trend = useSparkTrend(data ? (data.effective && data.effective.totals ? data.effective.totals.tokens : data.totals.tokens) : 0)
1518
4415
  const noticeTimer = useRef(null)
1519
4416
 
1520
4417
  const showNotice = useCallback((next, ttl) => {
@@ -1554,6 +4451,9 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1554
4451
  setBusy(true)
1555
4452
  try {
1556
4453
  await postJson(ROUTES.action, Object.assign({ session: sessionId, label: message }, action))
4454
+ // A switch changes health/trend computations, so the 30s read
4455
+ // cache must not keep serving the pre-switch health strip.
4456
+ RESOURCE_CACHE.clear()
1557
4457
  reload()
1558
4458
  try {
1559
4459
  window.dispatchEvent(new CustomEvent('injection-manager:changed'))
@@ -1583,12 +4483,55 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1583
4483
  (group, enabled) => {
1584
4484
  const verb = enabled ? t('turnedOn') : t('turnedOff')
1585
4485
  const count = group.items ? group.items.length : group.count
1586
- act({ kind: 'group', channel: group.channel, group: group.id, enabled }, `${verb} ${groupLabelOf(t, group)} · ${count} ${t('items')}`)
4486
+ const label = `${verb} ${groupLabelOf(t, group)} · ${count} ${t('items')}`
4487
+ if (Array.isArray(group.parts) && group.parts.length > 1) {
4488
+ act({ kind: 'groups', groups: group.parts, enabled }, label)
4489
+ } else {
4490
+ act({ kind: 'group', channel: group.channel, group: group.id, enabled }, label)
4491
+ }
1587
4492
  },
1588
4493
  [act, t],
1589
4494
  )
1590
4495
  const onUndo = useCallback(() => act({ kind: 'undo' }, t('undone')), [act, t])
1591
4496
 
4497
+ // Cross-tab jumps: the insights page and health checks need to land the
4498
+ // reader on a tab (and sometimes a channel filter).
4499
+ const openTab = useCallback(
4500
+ (next, channel) => {
4501
+ if (typeof next === 'string' && next.length > 0) setTab(next === 'stats' ? 'insights' : next)
4502
+ if (typeof channel === 'string' && channel.length > 0) setFilter(channel)
4503
+ },
4504
+ [setFilter, setTab],
4505
+ )
4506
+ const openContent = useCallback(
4507
+ (item) => {
4508
+ if (item === null || item === undefined || typeof item !== 'object') return
4509
+ const source = data !== null && data !== undefined ? data : null
4510
+ const wantedId = typeof item.id === 'string' ? item.id : ''
4511
+ const wantedName = typeof item.name === 'string' ? item.name : ''
4512
+ const found = source !== null && wantedId.length > 0 && Array.isArray(source.items) ? source.items.find((entry) => entry.id === wantedId) : undefined
4513
+ const row = item.tokens === undefined && found !== undefined ? Object.assign({}, found, item) : item
4514
+ const channel = String(row.channel || (found !== undefined && found.channel) || '')
4515
+ const name = typeof row.name === 'string' && row.name.length > 0 ? row.name : wantedName
4516
+ const id = typeof row.id === 'string' && row.id.length > 0 ? row.id : wantedId.length > 0 ? wantedId : `${channel}:${name}`
4517
+ if (id.length === 0) return
4518
+ const tokens = Number(row.tokens) || 0
4519
+ const on = source !== null && typeof policyItemOn === 'function' ? policyItemOn(source, row) : true
4520
+ setDrawer({
4521
+ channel,
4522
+ id,
4523
+ name: name.length > 0 ? name : id,
4524
+ group: row.groupLabel !== undefined && row.groupLabel !== null ? String(row.groupLabel) : row.group !== undefined && row.group !== null ? String(row.group) : '',
4525
+ tokens,
4526
+ chars: Number(row.chars) || 0,
4527
+ share: source !== null ? pct(tokens, effectiveTotalOf(source)) : null,
4528
+ saved: on ? 0 : tokens,
4529
+ })
4530
+ },
4531
+ [data],
4532
+ )
4533
+ const closeDrawer = useCallback(() => setDrawer(null), [])
4534
+
1592
4535
  const close = () => {
1593
4536
  try {
1594
4537
  const layout = ctxRef.current && ctxRef.current.get && ctxRef.current.get('layout')
@@ -1604,7 +4547,23 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1604
4547
  { className: 'ci-root' },
1605
4548
  h('style', null, STYLE),
1606
4549
  h('div', { className: 'ci-head' }, h('h1', null, t(compact ? 'panelTitle' : 'pageTitle'))),
1607
- h('div', { className: 'ci-body' }, h('div', { className: 'ci-skel' }), h('div', { className: 'ci-skel' }), h('div', { className: 'ci-note' }, t('loading'))),
4550
+ h(
4551
+ 'div',
4552
+ { className: 'ci-body grow' },
4553
+ h('span', { className: 'ci-sr' }, t('loading')),
4554
+ h(
4555
+ 'div',
4556
+ { className: 'ci-skel-kpis', 'aria-hidden': 'true' },
4557
+ [0, 1, 2, 3].map((index) => h('div', { className: 'ci-skel', key: index })),
4558
+ ),
4559
+ h('div', { className: 'ci-skel-strip', 'aria-hidden': 'true' }),
4560
+ h(
4561
+ 'div',
4562
+ { className: 'ci-skel-table', 'aria-hidden': 'true' },
4563
+ h('div', { className: 'head' }),
4564
+ [0, 1, 2, 3, 4, 5].map((index) => h('div', { className: 'row', key: index })),
4565
+ ),
4566
+ ),
1608
4567
  )
1609
4568
  }
1610
4569
 
@@ -1641,7 +4600,9 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1641
4600
  snapshot.host && snapshot.host.supported === false
1642
4601
  ? h('div', { className: 'ci-note warn' }, t('hostOld', { version: snapshot.host.version, tested: snapshot.host.tested }))
1643
4602
  : null,
1644
- h(Kpis, { snapshot, t }),
4603
+ h(Kpis, { snapshot, t, trend }),
4604
+ h(RequestStrip, { snapshot, t }),
4605
+ h(SkillsFocus, { snapshot, t, onFilter: setFilter }),
1645
4606
  h(Composition, { snapshot, t, filter, onFilter: setFilter }),
1646
4607
  snapshot.policy.appliedToThisAgent === false && snapshot.policy.preview && snapshot.policy.preview.savedTokens > 0
1647
4608
  ? h('div', { className: 'ci-note warn' }, t('sessionNotApplied'))
@@ -1652,17 +4613,37 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1652
4613
  { className: 'ci-list' },
1653
4614
  groups.map((group) => {
1654
4615
  const state = policyGroupState(snapshot, group)
4616
+ // Does the policy keep this suite out of a new session? If so,
4617
+ // the row says 已关闭 and its switch is the way back.
1655
4618
  return h(
1656
4619
  'div',
1657
4620
  { className: 'ci-mini', key: group.id },
1658
4621
  h(Dot, { channel: group.channel }),
1659
- h('span', { className: 'n', title: `${group.label} · ${group.count} ${t('items')}` }, `${groupLabelOf(t, group)} · ${group.count}`),
4622
+ h(
4623
+ 'span',
4624
+ { className: 'n', title: `${group.label} · ${group.count} ${t('items')}` },
4625
+ `${groupLabelOf(t, group)} · ${group.count}`,
4626
+ state.on ? null : h('span', { className: 'ci-tag' }, t('closedBadge')),
4627
+ ),
1660
4628
  h('span', { className: 't' }, token(group.tokens)),
1661
4629
  h(Switch, {
1662
4630
  on: state.on,
1663
4631
  mixed: state.mixed,
1664
4632
  disabled: busy || state.disabled,
1665
- onChange: () => onGroupToggle(group, !state.on),
4633
+ onChange: () => {
4634
+ // Turning a suite back on has to also restore the rows
4635
+ // the policy had removed, or it reads as "on" while
4636
+ // half of it is still closed.
4637
+ const closed = state.on ? [] : closedNamesFor(snapshot, group.label)
4638
+ if (closed.length === 0) {
4639
+ onGroupToggle(group, !state.on)
4640
+ return
4641
+ }
4642
+ for (const channel of new Set(closed.map((entry) => entry.channel))) {
4643
+ const names = closed.filter((entry) => entry.channel === channel).map((entry) => entry.name)
4644
+ act({ kind: 'names', channel, names, enabled: true }, `${t('turnedOn')} ${groupLabelOf(t, group)}`)
4645
+ }
4646
+ },
1666
4647
  title: group.label,
1667
4648
  }),
1668
4649
  )
@@ -1681,38 +4662,77 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1681
4662
  head,
1682
4663
  h(
1683
4664
  'div',
1684
- { className: 'ci-body' },
1685
- snapshot.host && snapshot.host.supported === false
1686
- ? h('div', { className: 'ci-note warn' }, t('hostOld', { version: snapshot.host.version, tested: snapshot.host.tested }))
1687
- : null,
1688
- h(Kpis, { snapshot, t }),
1689
- h(Composition, { snapshot, t, filter, onFilter: setFilter }),
1690
- snapshot.policy.appliedToThisAgent !== true && snapshot.policy.preview && snapshot.policy.preview.savedTokens > 0
1691
- ? h('div', { className: 'ci-note warn' }, t('sessionNotApplied'))
1692
- : null,
1693
- ),
1694
- h(
1695
- 'div',
1696
- { className: 'ci-tabs' },
1697
- [
1698
- ['list', t('list')],
1699
- ['settings', t('settings')],
1700
- ['budget', t('budget')],
1701
- ['about', t('about')],
1702
- ].map(([key, label]) => h('button', { key, type: 'button', className: tab === key ? 'on' : '', onClick: () => setTab(key) }, label)),
4665
+ { className: 'ci-tabs', role: 'tablist', 'aria-label': t('v2.tabsLabel') },
4666
+ (v2 === true
4667
+ ? [
4668
+ ['manage', t('tabManage'), t('v2.tabManageHint')],
4669
+ ['insights', t('v2.tabInsights'), t('v2.tabInsightsHint')],
4670
+ ['settings', t('tabSettings'), t('v2.tabSettingsHint')],
4671
+ ]
4672
+ : [
4673
+ ['manage', t('tabManage'), t('v2.tabManageHint')],
4674
+ ['settings', t('tabSettings'), t('v2.tabSettingsHint')],
4675
+ ]
4676
+ ).map(([key, label, hint]) =>
4677
+ h(
4678
+ 'button',
4679
+ {
4680
+ key,
4681
+ type: 'button',
4682
+ role: 'tab',
4683
+ id: 'ci-tab-' + key,
4684
+ 'aria-selected': activeTab === key ? 'true' : 'false',
4685
+ 'aria-controls': 'ci-tabpanel-' + key,
4686
+ tabIndex: activeTab === key ? 0 : -1,
4687
+ className: activeTab === key ? 'on' : '',
4688
+ title: hint,
4689
+ onClick: () => setTab(key),
4690
+ onKeyDown: (event) => {
4691
+ if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return
4692
+ const keys = v2 === true ? ['manage', 'insights', 'settings'] : ['manage', 'settings']
4693
+ const index = keys.indexOf(activeTab)
4694
+ const next = keys[(index + (event.key === 'ArrowRight' ? 1 : keys.length - 1)) % keys.length]
4695
+ event.preventDefault()
4696
+ setTab(next)
4697
+ const node = document.getElementById('ci-tab-' + next)
4698
+ if (node && typeof node.focus === 'function') node.focus()
4699
+ },
4700
+ },
4701
+ label,
4702
+ ),
4703
+ ),
1703
4704
  ),
1704
4705
  h(
1705
4706
  'div',
1706
- { className: 'ci-body grow' },
1707
- tab === 'list'
1708
- ? h(ItemsTable, { snapshot, t, filter, setFilter, onToggle, onGroup: onGroupToggle, onUndo, busy, act })
1709
- : tab === 'settings'
1710
- ? h(SettingsTab, { snapshot, t, act, sessionId, notify: showNotice })
1711
- : tab === 'budget'
1712
- ? h(BudgetTab, { snapshot, t, act })
1713
- : h(AboutTab, { snapshot, t, sessionId }),
4707
+ {
4708
+ className: 'ci-body grow',
4709
+ role: 'tabpanel',
4710
+ id: 'ci-tabpanel-' + activeTab,
4711
+ 'aria-labelledby': 'ci-tab-' + activeTab,
4712
+ tabIndex: -1,
4713
+ },
4714
+ activeTab === 'manage'
4715
+ ? h(
4716
+ 'div',
4717
+ { className: 'ci-manage' },
4718
+ snapshot.host && snapshot.host.supported === false
4719
+ ? h('div', { className: 'ci-note warn' }, t('hostOld', { version: snapshot.host.version, tested: snapshot.host.tested }))
4720
+ : null,
4721
+ v2 !== true ? h(V2Gate, { snapshot, t }) : null,
4722
+ h(Kpis, { snapshot, t, trend }),
4723
+ h(RequestStrip, { snapshot, t }),
4724
+ h(ManageHealth, { snapshot, t, sessionId, v2, act, onOpenContent: openContent, onOpenTab: openTab }),
4725
+ snapshot.policy.appliedToThisAgent !== true && snapshot.policy.preview && snapshot.policy.preview.savedTokens > 0
4726
+ ? h('div', { className: 'ci-note warn' }, t('sessionNotApplied'))
4727
+ : null,
4728
+ h(ItemsTable, { snapshot, t, filter, setFilter, onToggle, onGroup: onGroupToggle, onUndo, busy, act, v2, onOpenContent: openContent }),
4729
+ )
4730
+ : activeTab === 'insights'
4731
+ ? h(InsightsTab, { snapshot, t, sessionId, onOpenContent: openContent, onOpenTab: openTab, act })
4732
+ : h(SettingsPage, { snapshot, t, act, sessionId, notify: showNotice }),
1714
4733
  ),
1715
4734
  h(Toast, { notice, t, onUndo: () => { setNotice(null); act({ kind: 'undo' }, t('undone')) } }),
4735
+ h(ContentDrawer, { target: drawer, sessionId, t, onClose: closeDrawer }),
1716
4736
  )
1717
4737
  }
1718
4738
 
@@ -1751,6 +4771,8 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1751
4771
  if (hidden) return null
1752
4772
 
1753
4773
  const tokens = data ? data.totals.tokens : null
4774
+ const context = data ? data.context : null
4775
+ const windowKnown = context !== null && context !== undefined && context.window !== null && context.used !== null
1754
4776
  const open = () => {
1755
4777
  try {
1756
4778
  const layout = ctxRef.current && ctxRef.current.get && ctxRef.current.get('layout')
@@ -1763,6 +4785,12 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1763
4785
  setHidden(true)
1764
4786
  window.dispatchEvent(new CustomEvent('injection-manager:dock', { detail: { hidden: true } }))
1765
4787
  }
4788
+ // The ambient number is the one that decides when a session gets
4789
+ // compacted: how much of the window the next request will take. The
4790
+ // injected total stays first because it is what this plugin controls.
4791
+ const hint = windowKnown
4792
+ ? `${t('dockHint')} · ${t('windowUsedOf', { used: token(context.used), window: token(context.window) })}`
4793
+ : t('dockHint')
1766
4794
 
1767
4795
  return h(
1768
4796
  'span',
@@ -1770,10 +4798,10 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1770
4798
  h('style', null, DOCK_STYLE),
1771
4799
  h(
1772
4800
  'button',
1773
- { type: 'button', className: 'ci-dock', onClick: open, title: t('dockHint') },
4801
+ { type: 'button', className: 'ci-dock' + (windowKnown && context.tone === 'danger' ? ' warn' : ''), onClick: open, title: hint },
1774
4802
  h('i', null),
1775
4803
  h('b', null, tokens === null ? '…' : token(tokens)),
1776
- data && data.totals.savableTokens > 0 ? h('em', null, `${data.totals.savablePercent}%`) : null,
4804
+ windowKnown ? h('em', null, `${context.occupancy}%`) : data && data.totals.savableTokens > 0 ? h('em', null, `${data.totals.savablePercent}%`) : null,
1777
4805
  ),
1778
4806
  h(
1779
4807
  'button',
@@ -1785,14 +4813,16 @@ body[data-ds-dark-theme] .ci-root{--ci-fg:#ececf1;--ci-fg2:#b9b9c3;--ci-fg3:#8b8
1785
4813
 
1786
4814
  function PanelIcon() {
1787
4815
  // The sidebar panellist renders one icon per panel, so this is the
1788
- // entry point: three stacked source bands narrowing into one line.
4816
+ // entry point. Same funnel as icon.svg, drawn in currentColor so it
4817
+ // follows the host's selected/unselected state; only the terminus dot
4818
+ // keeps the brand blue.
1789
4819
  return h(
1790
4820
  'svg',
1791
4821
  { viewBox: '0 0 20 20', width: 18, height: 18, fill: 'none', 'aria-hidden': 'true' },
1792
- h('rect', { x: 2.5, y: 3, width: 15, height: 2.6, rx: 1.3, fill: 'currentColor', opacity: 0.85 }),
1793
- h('rect', { x: 2.5, y: 8.2, width: 11, height: 2.6, rx: 1.3, fill: 'currentColor', opacity: 0.6 }),
1794
- h('rect', { x: 2.5, y: 13.4, width: 7, height: 2.6, rx: 1.3, fill: 'currentColor', opacity: 0.35 }),
1795
- h('circle', { cx: 16.4, cy: 14.7, r: 2.1, fill: '#4d6bfe' }),
4822
+ h('rect', { x: 2, y: 3.2, width: 16, height: 3.1, rx: 1.55, fill: 'currentColor', opacity: 0.9 }),
4823
+ h('rect', { x: 2, y: 8.4, width: 11.5, height: 3.1, rx: 1.55, fill: 'currentColor', opacity: 0.62 }),
4824
+ h('rect', { x: 2, y: 13.6, width: 7, height: 3.1, rx: 1.55, fill: 'currentColor', opacity: 0.34 }),
4825
+ h('circle', { cx: 15.6, cy: 15.1, r: 2.2, fill: '#4d6bfe' }),
1796
4826
  )
1797
4827
  }
1798
4828