dsh-skill-eval 0.0.0-stage → 1.20.3

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 (48) hide show
  1. package/CHANGELOG.md +718 -0
  2. package/LICENSE +21 -0
  3. package/README.md +207 -2
  4. package/README.zh.md +164 -0
  5. package/client.js +2791 -0
  6. package/cordis.patch.yml +9 -0
  7. package/docs/ACCEPTANCE.md +71 -0
  8. package/docs/AUDIT.md +82 -0
  9. package/docs/CODE-REVIEW.md +49 -0
  10. package/docs/COMPARISON.md +33 -0
  11. package/docs/DETAIL.md +468 -0
  12. package/docs/DEV-RELOAD.md +114 -0
  13. package/docs/ENTRYPOINTS.md +65 -0
  14. package/docs/RELEASE.md +44 -0
  15. package/docs/RRSI-NOTES.md +129 -0
  16. package/docs/SCENARIOS.md +91 -0
  17. package/docs/UI-REVIEW.md +115 -0
  18. package/docs/WORKFLOW.md +108 -0
  19. package/icon.svg +9 -0
  20. package/index.js +1173 -0
  21. package/lib/accept.js +350 -0
  22. package/lib/advice.js +557 -0
  23. package/lib/critic.js +101 -0
  24. package/lib/dev.js +148 -0
  25. package/lib/history.js +141 -0
  26. package/lib/html.js +17 -0
  27. package/lib/inspect.js +142 -0
  28. package/lib/integrity.js +46 -0
  29. package/lib/loop.js +195 -0
  30. package/lib/random.js +29 -0
  31. package/lib/recorder.js +644 -0
  32. package/lib/render.js +580 -0
  33. package/lib/report.js +689 -0
  34. package/lib/score.js +565 -0
  35. package/lib/settings.js +415 -0
  36. package/lib/snapshot.js +250 -0
  37. package/lib/steps.js +141 -0
  38. package/lib/store.js +240 -0
  39. package/lib/validity.js +125 -0
  40. package/locale/en.json +6 -0
  41. package/locale/zh.json +6 -0
  42. package/package.json +96 -4
  43. package/scripts/accept.mjs +227 -0
  44. package/scripts/build-client.mjs +59 -0
  45. package/scripts/build.mjs +81 -0
  46. package/scripts/doctor.mjs +234 -0
  47. package/scripts/lib.mjs +87 -0
  48. package/scripts/verify-live.mjs +178 -0
package/client.js ADDED
@@ -0,0 +1,2791 @@
1
+ /**
2
+ * GENERATED FILE — do not edit directly.
3
+ * Source: client/*.js · build: node scripts/build-client.mjs
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-skill-eval',
7
+ factory(require) {
8
+
9
+ // client/01-runtime.js
10
+ const React = require('react')
11
+ const h = React.createElement
12
+ const { useEffect, useRef, useState, useSyncExternalStore } = React
13
+
14
+ const env = { locale: null }
15
+
16
+ // ---------------------------------------------------------------- store
17
+ function createStore(initial) {
18
+ let state = initial
19
+ const listeners = new Set()
20
+ return {
21
+ get: () => state,
22
+ set(next) {
23
+ state = typeof next === 'function' ? next(state) : next
24
+ for (const listener of [...listeners]) listener()
25
+ },
26
+ subscribe(listener) {
27
+ listeners.add(listener)
28
+ return () => listeners.delete(listener)
29
+ },
30
+ }
31
+ }
32
+
33
+ const store = createStore({ open: false, view: 'skills', loading: false, error: null, data: null, fetchedAt: 0 })
34
+ const useStore = () => useSyncExternalStore(store.subscribe, store.get, store.get)
35
+
36
+ // The in-conversation turn card is the product surface; the popup is an
37
+ // optional extra. Set `window.__SEV_ENABLE_POPUP__ = true` in the page (or
38
+ // flip the default here) to bring the sidebar button and modal back.
39
+ const ENABLE_POPUP = typeof window !== 'undefined' && window.__SEV_ENABLE_POPUP__ === true
40
+
41
+ // client/02-texts.js
42
+ // --------------------------------------------------------------- locale
43
+ const TEXTS = {
44
+ zh: {
45
+ open: '技能评测',
46
+ title: '技能评测',
47
+ subtitle: '每次 skill 加载之后真实发生了什么:加载成败、后续工具报错、用户有没有推翻、花了多少调用。',
48
+ refresh: '刷新',
49
+ close: '关闭',
50
+ copy: '复制给 agent',
51
+ copied: '已复制',
52
+ copyFailed: '复制失败',
53
+ loading: '正在读取遥测…',
54
+ empty: '还没有记录到技能加载。先用一次 skill 让插件收集数据。',
55
+ failed: '读取失败',
56
+ loads: '加载',
57
+ closed: '已结算',
58
+ corr: '纠正率',
59
+ err: '错误率',
60
+ latency: '加载耗时',
61
+ dims: {
62
+ static: '静态质量',
63
+ reliability: '可靠性',
64
+ effectiveness: '有效性',
65
+ efficiency: '效率',
66
+ lifecycle: '生命周期',
67
+ mcp: 'MCP',
68
+ },
69
+ provisional: '样本不足,分数为临时值',
70
+ noAdvice: '没有需要修的问题',
71
+ footerHint: '也可以直接让 agent 调 skill_eval_report',
72
+ auto: '每 5 秒自动刷新',
73
+ turnLabel: '技能评测',
74
+ kpiSkills: '有遥测的技能',
75
+ kpiLoads: '累计加载',
76
+ kpiFixable: '有待修问题',
77
+ kpiAvg: '平均分',
78
+ searchPlaceholder: '搜索技能…',
79
+ onlyActionable: '仅看待修',
80
+ noMatch: '没有匹配的技能',
81
+ chartScoreDist: '分数分布',
82
+ chartValidity: '证据覆盖',
83
+ chartMcp: 'MCP 延迟',
84
+ chartSessions: '会话活动',
85
+ chartAvg: '均值',
86
+ chartTrend: '趋势',
87
+ chartP50: 'p50',
88
+ chartP95: 'p95',
89
+ chartThreshold: '阈值',
90
+ chartWithCI: '有区间',
91
+ chartProvisional: '临时分',
92
+ chartNoEvidence: '无区间',
93
+ chartActionable: '待修',
94
+ chartLoads: '加载',
95
+ chartCalls: '调用',
96
+ chartErrors: '错误',
97
+ chartSessionsUnit: '次会话',
98
+ noChartData: '暂无数据',
99
+ config: '配置',
100
+ updated: '更新',
101
+ turnCalls: '调用',
102
+ turnErrors: '错误',
103
+ turnNext: '下一步 · 可改',
104
+ tokPerLoad: 'tok/次加载',
105
+ devLoads: '次加载',
106
+ devClosed: '已结算',
107
+ devOpen: '未结算',
108
+ skillsWord: '个技能',
109
+ turnHistory: '改动记录',
110
+ detailSkills: '个技能有遥测',
111
+ detailActionable: '个有待修问题',
112
+ rowConfigSummary: '评分权重、阈值、预算与开关',
113
+ settingsLoading: '正在读取配置…',
114
+ settingsFailed: '读取配置失败',
115
+ settingsSave: '保存',
116
+ settingsSaving: '保存中…',
117
+ settingsSaved: '已保存并立即生效',
118
+ settingsOpenWeb: '在网页里打开',
119
+ settingsNeedsRestart: '当前宿主还是旧版本:重启 DeepSeek Harness 后这里会显示原生设置;也可以先打开网页配置页。',
120
+ storeError: '遥测写入失败',
121
+ turnDetail: '本轮详情',
122
+ noTurnAdvice: '本轮无待修问题',
123
+ tabs: { skills: '按技能', steps: '轨迹', runs: '按运行', mcp: 'MCP', dev: '开发者' },
124
+ stepKpiAvg: '步均分',
125
+ stepKpiLatest: '最近回合',
126
+ stepKpiCount: '已记录步数',
127
+ stepRecent: '近几次回合对比',
128
+ stepFilter: '按技能查看',
129
+ stepAll: '全部',
130
+ stepTurn: '回合',
131
+ stepStep: '步',
132
+ stepCalls: '调用',
133
+ stepErrors: '错误',
134
+ stepDuration: '耗时',
135
+ stepTokens: 'token',
136
+ stepNoData: '还没有逐步遥测:完成一个回合并刷新后自动出现。',
137
+ stepDelta: '较上回合',
138
+ stepFormula: '步分 = 100 − 工具错误×20 − 循环错误×35 − 超量调用×3',
139
+ stepTrace: '查看轨迹',
140
+ stepTurnAvg: '回合均分',
141
+ stepWorst: '最低',
142
+ stepBest: '最高',
143
+ stepFiltered: '只看该技能所在步',
144
+ stepNoSkill: '无技能加载',
145
+ runsHead: ['会话', '评分', '加载', '调用', '报错'],
146
+ mcpHead: ['服务器', '健康', '调用', '错误率', 'p50/p95'],
147
+ emptyRuns: '还没有运行记录',
148
+ emptyMcp: '还没有 MCP 调用记录',
149
+ mcpFailing: '出错的工具',
150
+ mcpFix: 'MCP 修复建议',
151
+ staleTitle: '当前 host 运行的是旧一代插件',
152
+ staleHint:
153
+ '数据里没有 scoring / ranking 字段,说明这个进程还在用升级前的模块。请重启 DeepSeek Harness(退出再打开),然后刷新本页。',
154
+ version: '插件版本',
155
+ devLabels: {
156
+ weights: '评分权重',
157
+ thresholds: '等级线',
158
+ minSamples: '最小样本',
159
+ dataDir: '数据目录',
160
+ api: '数据接口',
161
+ module: '模块 / 磁盘',
162
+ routes: '注册路由',
163
+ tools: '工具',
164
+ skew: '需要重启',
165
+ totals: '记录量',
166
+ store: '存储错误',
167
+ settingsFile: '配置文件',
168
+ warnings: '告警',
169
+ inspect: 'Inspect 提供者',
170
+ ok: '正常',
171
+ },
172
+ },
173
+ en: {
174
+ open: 'Skill eval',
175
+ title: 'Skill eval',
176
+ subtitle:
177
+ 'What really happened after each skill load: load success, follow-up tool errors, user pushback, and cost.',
178
+ refresh: 'Refresh',
179
+ close: 'Close',
180
+ copy: 'Copy for agent',
181
+ copied: 'Copied',
182
+ copyFailed: 'Copy failed',
183
+ loading: 'Reading telemetry…',
184
+ empty: 'No skill loads recorded yet. Load one skill to start collecting.',
185
+ failed: 'Read failed',
186
+ loads: 'loads',
187
+ closed: 'closed',
188
+ corr: 'corr',
189
+ err: 'err',
190
+ latency: 'load',
191
+ dims: {
192
+ static: 'static',
193
+ reliability: 'reliability',
194
+ effectiveness: 'effectiveness',
195
+ efficiency: 'efficiency',
196
+ lifecycle: 'lifecycle',
197
+ mcp: 'mcp',
198
+ },
199
+ provisional: 'provisional score: not enough loads yet',
200
+ noAdvice: 'nothing to fix from recorded evidence',
201
+ footerHint: 'The agent can read the same report through skill_eval_report',
202
+ auto: 'auto-refresh every 5s',
203
+ turnLabel: 'Skill eval',
204
+ kpiSkills: 'skills with data',
205
+ kpiLoads: 'loads recorded',
206
+ kpiFixable: 'with a fix',
207
+ kpiAvg: 'average score',
208
+ searchPlaceholder: 'filter skills…',
209
+ onlyActionable: 'needs a fix',
210
+ noMatch: 'no skill matches the filter',
211
+ chartScoreDist: 'Score distribution',
212
+ chartValidity: 'Evidence coverage',
213
+ chartMcp: 'MCP latency',
214
+ chartSessions: 'Session activity',
215
+ chartAvg: 'avg',
216
+ chartTrend: 'trend',
217
+ chartP50: 'p50',
218
+ chartP95: 'p95',
219
+ chartThreshold: 'threshold',
220
+ chartWithCI: 'with CI',
221
+ chartProvisional: 'provisional',
222
+ chartNoEvidence: 'no interval',
223
+ chartActionable: 'to fix',
224
+ chartLoads: 'loads',
225
+ chartCalls: 'calls',
226
+ chartErrors: 'errors',
227
+ chartSessionsUnit: 'session(s)',
228
+ noChartData: 'no data yet',
229
+ config: 'Configure',
230
+ updated: 'updated',
231
+ turnCalls: 'calls',
232
+ turnErrors: 'err',
233
+ turnNext: 'next fix',
234
+ tokPerLoad: 'tok/load',
235
+ devLoads: 'loads',
236
+ devClosed: 'closed',
237
+ devOpen: 'open',
238
+ skillsWord: 'skills',
239
+ turnHistory: 'edit history',
240
+ detailSkills: 'skill(s) with telemetry',
241
+ detailActionable: 'with an actionable fix',
242
+ rowConfigSummary: 'Weights, thresholds, budgets and switches',
243
+ settingsLoading: 'loading settings…',
244
+ settingsFailed: 'failed to load settings',
245
+ settingsSave: 'Save',
246
+ settingsSaving: 'saving…',
247
+ settingsSaved: 'saved and applied',
248
+ settingsOpenWeb: 'Open in browser',
249
+ settingsNeedsRestart:
250
+ 'This host still runs an older generation: restart DeepSeek Harness to get the native settings page, or use the web page meanwhile.',
251
+ storeError: 'telemetry write failed',
252
+ turnDetail: 'details',
253
+ noTurnAdvice: 'nothing to fix in this turn',
254
+ tabs: { skills: 'Skills', steps: 'Steps', runs: 'Runs', mcp: 'MCP', dev: 'Dev' },
255
+ stepKpiAvg: 'step average',
256
+ stepKpiLatest: 'latest turn',
257
+ stepKpiCount: 'recorded steps',
258
+ stepRecent: 'Recent turns',
259
+ stepFilter: 'by skill',
260
+ stepAll: 'all',
261
+ stepTurn: 'turn',
262
+ stepStep: 'step',
263
+ stepCalls: 'calls',
264
+ stepErrors: 'errors',
265
+ stepDuration: 'duration',
266
+ stepTokens: 'tokens',
267
+ stepNoData: 'No step telemetry yet: finish a turn and refresh.',
268
+ stepDelta: 'vs previous turn',
269
+ stepFormula: 'step = 100 − tool errors×20 − loop errors×35 − call-volume×3',
270
+ stepTrace: 'view steps',
271
+ stepTurnAvg: 'turn average',
272
+ stepWorst: 'lowest',
273
+ stepBest: 'highest',
274
+ stepFiltered: 'steps that loaded this skill',
275
+ stepNoSkill: 'no skill loaded',
276
+ runsHead: ['session', 'score', 'loads', 'calls', 'errors'],
277
+ mcpHead: ['server', 'health', 'calls', 'errors', 'p50/p95'],
278
+ emptyRuns: 'no runs recorded yet',
279
+ emptyMcp: 'no MCP calls recorded yet',
280
+ mcpFailing: 'failing tools',
281
+ mcpFix: 'MCP fixes',
282
+ staleTitle: 'The running host serves an older plugin generation',
283
+ staleHint:
284
+ 'The payload has no scoring/ranking fields, so this process still runs the pre-upgrade module. Quit and reopen DeepSeek Harness, then reload this page.',
285
+ version: 'plugin version',
286
+ devLabels: {
287
+ weights: 'weights',
288
+ thresholds: 'grade bands',
289
+ minSamples: 'min samples',
290
+ dataDir: 'data dir',
291
+ api: 'data api',
292
+ module: 'module / disk',
293
+ routes: 'routes',
294
+ tools: 'tools',
295
+ skew: 'restart',
296
+ totals: 'records',
297
+ store: 'store error',
298
+ settingsFile: 'settings file',
299
+ warnings: 'warnings',
300
+ inspect: 'inspect provider',
301
+ ok: 'ok',
302
+ },
303
+ },
304
+ }
305
+
306
+ // Stable identities: a new subscribe function on every render makes
307
+ // useSyncExternalStore resubscribe each time (one pair per card before this).
308
+ const localeSubscribe = (onChange) =>
309
+ env.locale && typeof env.locale.subscribe === 'function' ? env.locale.subscribe(onChange) : () => {}
310
+ const localeSnapshot = () =>
311
+ env.locale && typeof env.locale.getSnapshot === 'function' ? env.locale.getSnapshot() : null
312
+ const localeServerSnapshot = () => null
313
+
314
+ function useLang() {
315
+ const snapshot = useSyncExternalStore(localeSubscribe, localeSnapshot, localeServerSnapshot)
316
+ const active = snapshot && snapshot.active ? String(snapshot.active) : 'zh'
317
+ const lang = active.toLowerCase().startsWith('zh') ? 'zh' : 'en'
318
+ return { lang, t: TEXTS[lang] }
319
+ }
320
+
321
+ // client/03-data.js
322
+ // ---------------------------------------------------------------- utils
323
+ // Keep in sync with package.json `version` (a test enforces it). The host
324
+ // registers this exact path per release, so a plugin that was hot-reloaded
325
+ // without reclaiming the canonical route still answers here.
326
+ const DATA_VERSION = '1.20.3'
327
+ const DATA_URL = '/skill-eval/data/' + DATA_VERSION
328
+ const DATA_URL_FALLBACK = '/skill-eval/data'
329
+ const SETTINGS_URL = '/skill-eval/settings/' + DATA_VERSION
330
+ const SETTINGS_URL_FALLBACK = '/skill-eval/settings'
331
+
332
+ function fmt(value, digits) {
333
+ return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(digits === undefined ? 1 : digits) : '—'
334
+ }
335
+
336
+ function pct(value) {
337
+ return typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 100) + '%' : '—'
338
+ }
339
+
340
+ function scoreColor(value) {
341
+ if (typeof value !== 'number' || !Number.isFinite(value)) return 'var(--dsw-alias-state-idle-primary, #a1a1aa)'
342
+ // Colour bands follow the configured grade floors, so a 92-point skill can
343
+ // never render green while its letter says B.
344
+ const thresholds = (store.get().data && store.get().data.scoring && store.get().data.scoring.thresholds) || {}
345
+ const excellent = Number(thresholds.excellent) || 90
346
+ const pass = Number(thresholds.pass) || 70
347
+ if (value >= excellent) return 'var(--dsw-alias-state-success-primary, #2f9e44)'
348
+ if (value >= pass) return 'var(--dsw-alias-state-warn-primary, #d97706)'
349
+ return 'var(--dsw-alias-state-error-primary, #c92a2a)'
350
+ }
351
+
352
+ function severityColor(severity) {
353
+ if (severity === 'critical') return 'var(--dsw-alias-state-error-primary, #c92a2a)'
354
+ if (severity === 'warning') return 'var(--dsw-alias-state-warn-primary, #d97706)'
355
+ return 'var(--dsw-alias-brand-primary, #4d6bfe)'
356
+ }
357
+
358
+ async function fetchReport(url) {
359
+ const response = await fetch(url, { headers: { accept: 'application/json' }, cache: 'no-store' })
360
+ if (!response.ok) {
361
+ const error = new Error('HTTP ' + response.status)
362
+ error.status = response.status
363
+ throw error
364
+ }
365
+ const type =
366
+ (response.headers && typeof response.headers.get === 'function' && response.headers.get('content-type')) || ''
367
+ if (type.indexOf('json') === -1) {
368
+ // DSH's prefix route answers 200 HTML for an unclaimed versioned subpath,
369
+ // so a status-only fallback would never fire during a restart-skew.
370
+ const error = new Error(url + ' returned ' + (type || 'no content-type') + ' instead of JSON')
371
+ error.status = response.status
372
+ error.notJson = true
373
+ throw error
374
+ }
375
+ return response.json()
376
+ }
377
+
378
+ let loadInFlight = false
379
+ let loadGeneration = 0
380
+
381
+ function load() {
382
+ // Refresh can be clicked repeatedly and the popup polls; only one
383
+ // request may update the store, and only the newest request wins.
384
+ if (loadInFlight) return
385
+ loadInFlight = true
386
+ const generation = (loadGeneration += 1)
387
+ const finish = (patch) => {
388
+ if (generation !== loadGeneration) return
389
+ store.set((state) => ({ ...state, ...patch }))
390
+ }
391
+ store.set((state) => ({ ...state, loading: true, error: null }))
392
+ fetchReport(DATA_URL)
393
+ .catch((error) => {
394
+ // a host that predates the versioned alias (or a hot reload that kept
395
+ // the canonical route) still answers on the unversioned path
396
+ if (error && (error.status === 404 || error.notJson || error instanceof SyntaxError))
397
+ return fetchReport(DATA_URL_FALLBACK)
398
+ throw error
399
+ })
400
+ .then((data) => {
401
+ finish({ loading: false, data, error: null, fetchedAt: Date.now() })
402
+ })
403
+ .catch((error) => {
404
+ finish({ loading: false, error: error && error.message ? error.message : String(error) })
405
+ })
406
+ .finally(() => {
407
+ if (generation === loadGeneration) loadInFlight = false
408
+ })
409
+ }
410
+
411
+ const REFRESH_MS = 5000
412
+
413
+ function ensureReport() {
414
+ const state = store.get()
415
+ if (state.loading) return
416
+ if (state.data && Date.now() - state.fetchedAt < 10000) return
417
+ load()
418
+ }
419
+
420
+ // Versioned aliases survive hot reloads where the canonical route is still
421
+ // owned by an older generation; both land on the same board.
422
+ const BOARD_URL = '/skill-eval/board/' + DATA_VERSION
423
+ const CONFIG_URL = BOARD_URL + '/config'
424
+
425
+ function pagePath(kind) {
426
+ try {
427
+ const pages = store.get().data && store.get().data.pages
428
+ const value = pages && pages[kind]
429
+ if (typeof value === 'string' && value) return value
430
+ } catch {
431
+ // fall back to the default route
432
+ }
433
+ return kind === 'board' ? BOARD_URL : CONFIG_URL
434
+ }
435
+
436
+ function boardUrl() {
437
+ try {
438
+ return window.location.origin + pagePath('board')
439
+ } catch {
440
+ return pagePath('board')
441
+ }
442
+ }
443
+
444
+ function configUrl() {
445
+ try {
446
+ return window.location.origin + pagePath('config')
447
+ } catch {
448
+ return pagePath('config')
449
+ }
450
+ }
451
+
452
+ function openBoard() {
453
+ try {
454
+ window.open(boardUrl(), '_blank', 'noopener')
455
+ } catch {
456
+ // opening a tab is best effort; the link in the tooltip still works
457
+ }
458
+ }
459
+
460
+ function openReport() {
461
+ if (!ENABLE_POPUP) {
462
+ openBoard()
463
+ return
464
+ }
465
+ store.set((state) => ({ ...state, open: true }))
466
+ load()
467
+ }
468
+
469
+ function setView(view) {
470
+ store.set((state) => ({ ...state, view }))
471
+ }
472
+
473
+ function closeReport() {
474
+ store.set((state) => ({ ...state, open: false }))
475
+ }
476
+
477
+ function buildMarkdown(data) {
478
+ if (!data || !Array.isArray(data.skills) || data.skills.length === 0) return '# skill eval: no data'
479
+ const lines = ['# Skill eval report', '']
480
+ for (const skill of data.skills) {
481
+ const score = skill.score || {}
482
+ const dims = score.dimensions || {}
483
+ lines.push('## ' + skill.skill + ' — ' + fmt(score.total) + '/100 (' + (score.grade || '?') + ')')
484
+ lines.push(
485
+ '- static ' +
486
+ fmt(dims.static) +
487
+ ' · reliability ' +
488
+ fmt(dims.reliability) +
489
+ ' · effectiveness ' +
490
+ fmt(dims.effectiveness) +
491
+ ' · efficiency ' +
492
+ fmt(dims.efficiency),
493
+ )
494
+ const stats = skill.stats || {}
495
+ lines.push(
496
+ '- loads ' +
497
+ (stats.loads || 0) +
498
+ ' · closed ' +
499
+ (stats.closed || 0) +
500
+ ' · corrections ' +
501
+ pct(stats.correctionRate) +
502
+ ' · tool errors ' +
503
+ pct(stats.errRate) +
504
+ ' · load ' +
505
+ fmt(stats.p50LoadMs, 0) +
506
+ 'ms',
507
+ )
508
+ for (const item of (skill.advice || []).slice(0, 4)) {
509
+ lines.push('- [' + item.severity + '] ' + item.title + ' — ' + item.evidence)
510
+ lines.push(' fix: ' + item.fix)
511
+ }
512
+ lines.push('')
513
+ }
514
+ return lines.join('\n')
515
+ }
516
+
517
+ // client/04-components.js
518
+ // ------------------------------------------------------------- components
519
+ function GaugeIcon(props) {
520
+ const size = props?.size || 16
521
+ return h(
522
+ 'svg',
523
+ { viewBox: '0 0 24 24', width: size, height: size, fill: 'none', 'aria-hidden': true, style: { display: 'block' } },
524
+ h('path', {
525
+ d: 'M4 17a8 8 0 0 1 16 0',
526
+ stroke: 'currentColor',
527
+ strokeWidth: 2,
528
+ strokeLinecap: 'round',
529
+ }),
530
+ h('path', { d: 'M12 17l4.5-5.5', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round' }),
531
+ h('circle', { cx: 12, cy: 17, r: 1.6, fill: 'currentColor' }),
532
+ )
533
+ }
534
+
535
+ // client/05-settings.js
536
+ // ------------------------------------------------------------ settings
537
+ // Units ship in English from the settings API; the Chinese form localizes them.
538
+ const UNIT_ZH = { loads: '次加载', tokens: 'token', edits: '次修改' }
539
+ const unitLabel = (unit, lang) => (!unit ? '' : lang === 'zh' ? UNIT_ZH[unit] || unit : unit)
540
+
541
+ const settingsStore = createStore({ loading: false, saving: false, data: null, error: null, savedAt: 0 })
542
+ const useSettings = () => useSyncExternalStore(settingsStore.subscribe, settingsStore.get, settingsStore.get)
543
+
544
+ // One generation counter for reads and writes: a slow GET must not overwrite
545
+ // the values a newer save just persisted.
546
+ let settingsGeneration = 0
547
+
548
+ async function fetchSettingsPayload(url) {
549
+ const response = await fetch(url, { headers: { accept: 'application/json' } })
550
+ const type =
551
+ (response.headers && typeof response.headers.get === 'function' && response.headers.get('content-type')) || ''
552
+ if (!response.ok || type.indexOf('json') === -1) {
553
+ // DSH's stale prefix route answers 200 HTML for an unclaimed subpath, so
554
+ // treat "not JSON" the same as 404 and try the canonical route.
555
+ const error = new Error(!response.ok ? 'HTTP ' + response.status : 'host-too-old')
556
+ error.status = response.status
557
+ error.notJson = type.indexOf('json') === -1
558
+ throw error
559
+ }
560
+ return response.json()
561
+ }
562
+
563
+ async function fetchSettings() {
564
+ const generation = (settingsGeneration += 1)
565
+ const update = (patch) => {
566
+ if (generation === settingsGeneration) settingsStore.set((state) => ({ ...state, ...patch }))
567
+ }
568
+ update({ loading: true, error: null })
569
+ let data
570
+ try {
571
+ data = await fetchSettingsPayload(SETTINGS_URL)
572
+ } catch (error) {
573
+ const retry = error && (error.status === 404 || error.notJson)
574
+ if (!retry) throw error
575
+ try {
576
+ data = await fetchSettingsPayload(SETTINGS_URL_FALLBACK)
577
+ } catch (fallbackError) {
578
+ if (fallbackError && (fallbackError.status === 404 || fallbackError.notJson))
579
+ throw new Error('host-too-old', { cause: fallbackError })
580
+ throw fallbackError
581
+ }
582
+ }
583
+ update({ loading: false, data })
584
+ return data
585
+ }
586
+
587
+ async function saveSettings(values) {
588
+ // Invalidate any in-flight GET; its snapshot predates this save.
589
+ settingsGeneration += 1
590
+ settingsStore.set((state) => ({ ...state, saving: true, error: null, savedAt: 0 }))
591
+ try {
592
+ const post = (url) =>
593
+ fetch(url, {
594
+ method: 'POST',
595
+ headers: { 'content-type': 'application/json', accept: 'application/json', 'x-skill-eval-config': '1' },
596
+ body: JSON.stringify(values),
597
+ })
598
+ let response = await post(SETTINGS_URL)
599
+ if (response.status === 404) response = await post(SETTINGS_URL_FALLBACK)
600
+ const payload = await response.json()
601
+ if (!response.ok || payload.saved !== true) {
602
+ settingsStore.set((state) => ({
603
+ ...state,
604
+ saving: false,
605
+ savedAt: 0,
606
+ error: payload.errors?.[0]?.message ?? 'HTTP ' + response.status,
607
+ }))
608
+ return false
609
+ }
610
+ settingsStore.set((state) => ({
611
+ ...state,
612
+ saving: false,
613
+ data: { ...(state.data ?? {}), values: payload.values },
614
+ savedAt: Date.now(),
615
+ }))
616
+ return true
617
+ } catch (error) {
618
+ settingsStore.set((state) => ({
619
+ ...state,
620
+ saving: false,
621
+ savedAt: 0,
622
+ error: error instanceof Error ? error.message : String(error),
623
+ }))
624
+ return false
625
+ }
626
+ }
627
+
628
+ function SettingsForm(props) {
629
+ const { lang, t } = useLang()
630
+ // The web config page is a second surface; inside the desktop shell
631
+ // window.open is denied, so the in-panel dialog hides the link it cannot honour.
632
+ const webOpen = !props || props.webOpen !== false
633
+ const state = useSettings()
634
+ const [draft, setDraft] = useState(null)
635
+ useEffect(() => {
636
+ let alive = true
637
+ // A success banner from a previous mount must not reappear on reopen.
638
+ settingsStore.set((current) => (current.savedAt ? { ...current, savedAt: 0 } : current))
639
+ fetchSettings().catch((error) => {
640
+ if (alive) settingsStore.set((current) => ({ ...current, loading: false, error: error.message }))
641
+ })
642
+ return () => {
643
+ alive = false
644
+ }
645
+ }, [])
646
+ const data = state.data
647
+ const values = draft ?? (data && data.values) ?? {}
648
+ const groups = data && data.fields ? groupSettingsFields(data.fields, lang) : []
649
+ const set = (key, value) => setDraft({ ...values, [key]: value })
650
+ const save = async () => {
651
+ const submitted = values
652
+ const ok = await saveSettings(submitted)
653
+ // Keep edits typed while the POST was in flight instead of discarding them.
654
+ if (ok) setDraft((current) => (current === null || current === submitted ? null : current))
655
+ }
656
+ if (state.loading && !data) return h('div', { className: 'sev-settings' }, t.settingsLoading)
657
+ if (state.error && !data) {
658
+ const restart = state.error === 'host-too-old'
659
+ return h(
660
+ 'div',
661
+ { className: 'sev-settings' },
662
+ h('div', null, restart ? t.settingsNeedsRestart : t.settingsFailed + ': ' + state.error),
663
+ webOpen
664
+ ? h(
665
+ 'button',
666
+ {
667
+ type: 'button',
668
+ className: 'sev-btn',
669
+ onClick: () => window.open(configUrl(), '_blank', 'noopener'),
670
+ },
671
+ t.settingsOpenWeb,
672
+ )
673
+ : null,
674
+ )
675
+ }
676
+ return h(
677
+ 'div',
678
+ { className: 'sev-settings' },
679
+ h('style', { key: 'sev-settings-style' }, STYLES + '\n' + TURN_STYLES),
680
+ h('div', { className: 'sev-settings-heading' }, lang === 'zh' ? '评分配置' : 'Scoring settings'),
681
+ h(
682
+ 'div',
683
+ { className: 'sev-settings-sub' },
684
+ lang === 'zh'
685
+ ? webOpen
686
+ ? '保存后立即生效;网页配置页提供同一组字段。'
687
+ : '保存后立即生效。'
688
+ : webOpen
689
+ ? 'Saved values apply immediately; the web config page exposes the same fields.'
690
+ : 'Saved values apply immediately.',
691
+ ),
692
+ groups.map((group) =>
693
+ h(
694
+ 'div',
695
+ { className: 'sev-settings-group', key: group.title },
696
+ h('h4', null, group.title),
697
+ group.fields.map((field) =>
698
+ h(
699
+ 'div',
700
+ { className: 'sev-settings-row', key: field.key },
701
+ h(
702
+ 'div',
703
+ { className: 'sev-settings-label' },
704
+ h('span', null, lang === 'zh' ? field.labelZh || field.label : field.label),
705
+ (lang === 'zh' ? field.helpZh : field.help)
706
+ ? h('small', null, lang === 'zh' ? field.helpZh : field.help)
707
+ : null,
708
+ ),
709
+ field.type === 'boolean'
710
+ ? h(
711
+ 'label',
712
+ { className: 'sev-switch' },
713
+ h('input', {
714
+ type: 'checkbox',
715
+ checked: values[field.key] === true,
716
+ disabled: state.saving,
717
+ 'aria-label': lang === 'zh' ? field.labelZh || field.label : field.label,
718
+ onChange: (event) => set(field.key, event.currentTarget.checked),
719
+ }),
720
+ h('i', { 'aria-hidden': 'true' }),
721
+ )
722
+ : h(
723
+ 'div',
724
+ { className: 'sev-settings-control' },
725
+ h('input', {
726
+ type: 'number',
727
+ min: field.min,
728
+ max: field.max,
729
+ step: field.step,
730
+ value: values[field.key] ?? '',
731
+ disabled: state.saving,
732
+ 'aria-label': lang === 'zh' ? field.labelZh || field.label : field.label,
733
+ onChange: (event) => set(field.key, event.currentTarget.value),
734
+ }),
735
+ field.unit ? h('em', null, unitLabel(field.unit, lang)) : null,
736
+ ),
737
+ ),
738
+ ),
739
+ ),
740
+ ),
741
+ h(
742
+ 'div',
743
+ { className: 'sev-settings-actions' },
744
+ h(
745
+ 'button',
746
+ { type: 'button', className: 'sev-btn', disabled: state.saving, onClick: save },
747
+ state.saving ? t.settingsSaving : t.settingsSave,
748
+ ),
749
+ webOpen
750
+ ? h(
751
+ 'button',
752
+ {
753
+ type: 'button',
754
+ className: 'sev-btn sev-btn--ghost',
755
+ onClick: () => window.open(configUrl(), '_blank', 'noopener'),
756
+ },
757
+ t.settingsOpenWeb,
758
+ )
759
+ : null,
760
+ ),
761
+ state.savedAt ? h('div', { className: 'sev-settings-status' }, t.settingsSaved) : null,
762
+ state.error && data ? h('div', { className: 'sev-settings-status sev-error' }, state.error) : null,
763
+ )
764
+ }
765
+
766
+ function groupSettingsFields(fields, lang = 'zh') {
767
+ // The host ships group metadata with every field; the local classifier is
768
+ // only a fallback for an older payload (versioned routes keep old hosts
769
+ // alive after a hot reload).
770
+ const fallbackTitles =
771
+ lang === 'zh'
772
+ ? ['评分权重与阈值', '成本', '建议与生命周期', 'MCP', '输出']
773
+ : ['Scoring', 'Cost', 'Advice & lifecycle', 'MCP', 'Output']
774
+ const fallbackTitle = (field) =>
775
+ field.key.indexOf('weights.') === 0 || field.key.indexOf('thresholds.') === 0
776
+ ? fallbackTitles[0]
777
+ : ['tokenBudgetPerLoad', 'cacheReadWeight', 'countTokens'].includes(field.key)
778
+ ? fallbackTitles[1]
779
+ : ['mcpErrorRatePercent', 'mcpP95Ms'].includes(field.key)
780
+ ? fallbackTitles[3]
781
+ : ['promptHint', 'reportOnTurnEnd'].includes(field.key)
782
+ ? fallbackTitles[4]
783
+ : fallbackTitles[2]
784
+ const groups = new Map()
785
+ for (const field of fields) {
786
+ const title = field.group ? (lang === 'zh' ? field.groupZh || field.group : field.group) : fallbackTitle(field)
787
+ const list = groups.get(title) ?? []
788
+ list.push(field)
789
+ groups.set(title, list)
790
+ }
791
+ return [...groups.entries()].map(([title, list]) => ({ title, fields: list }))
792
+ }
793
+
794
+ /** Native seat: this plugin's row in Settings → Plugins gains a configure page. */
795
+ function RowConfig(props) {
796
+ const { t } = useLang()
797
+ const view = props && props.view
798
+ if (view === 'summary') return h('span', null, t.rowConfigSummary)
799
+ return h(SettingsForm, null)
800
+ }
801
+
802
+ // client/06-advice.js
803
+ // Chinese copy for rule-generated advice (host attaches titleZh/fixZh).
804
+ const adviceView = (item, lang) =>
805
+ item && lang === 'zh' && item.titleZh ? { ...item, title: item.titleZh, fix: item.fixZh || item.fix } : item
806
+
807
+ // Copy JSON/markdown for the agent. The async Clipboard API needs a real
808
+ // user gesture and can be missing on plain-http hosts, so fall back to the
809
+ // hidden-textarea + execCommand path before reporting failure.
810
+ async function copyText(text) {
811
+ try {
812
+ if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
813
+ await navigator.clipboard.writeText(text)
814
+ return true
815
+ }
816
+ } catch {
817
+ // fall through to the execCommand path
818
+ }
819
+ try {
820
+ if (typeof document !== 'undefined' && typeof document.execCommand === 'function') {
821
+ const area = document.createElement('textarea')
822
+ area.value = text
823
+ area.setAttribute('readonly', '')
824
+ area.style.position = 'fixed'
825
+ area.style.top = '-1000px'
826
+ area.style.opacity = '0'
827
+ document.body.appendChild(area)
828
+ try {
829
+ area.select()
830
+ return Boolean(document.execCommand('copy'))
831
+ } finally {
832
+ area.remove()
833
+ }
834
+ }
835
+ } catch {
836
+ // no clipboard available
837
+ }
838
+ return false
839
+ }
840
+
841
+ // client/06b-charts.js
842
+ // Pure-SVG charts for the board panel. No chart library: the bundle stays a
843
+ // single self-contained file, and every chart gets an aria-label with its data.
844
+ const CHART_COLORS = { green: '#2f9e44', yellow: '#d97706', amber: '#c9a227', red: '#c92a2a', blue: '#4d6bfe' }
845
+
846
+ function ChartCard(props) {
847
+ return h(
848
+ 'section',
849
+ { className: props.solo ? 'sev-chart sev-chart--solo' : 'sev-chart' },
850
+ h(
851
+ 'header',
852
+ { className: 'sev-chart-head' },
853
+ h('b', null, props.title),
854
+ props.hint ? h('span', null, props.hint) : null,
855
+ ),
856
+ props.children,
857
+ )
858
+ }
859
+
860
+ function chartEmpty(t) {
861
+ return h('div', { className: 'sev-chart-empty' }, t.noChartData)
862
+ }
863
+
864
+ function ScoreHistogram(props) {
865
+ const { skills, t } = props
866
+ const values = (skills || []).map((entry) => entry.score?.total).filter((value) => Number.isFinite(value))
867
+ if (values.length === 0) return h(ChartCard, { title: t.chartScoreDist }, chartEmpty(t))
868
+ const buckets = [
869
+ { label: '0–59', min: 0, max: 59.999 },
870
+ { label: '60–69', min: 60, max: 69.999 },
871
+ { label: '70–79', min: 70, max: 79.999 },
872
+ { label: '80–89', min: 80, max: 89.999 },
873
+ { label: '90–100', min: 90, max: 100 },
874
+ ]
875
+ const counts = buckets.map((bucket) => values.filter((value) => value >= bucket.min && value <= bucket.max).length)
876
+ const max = Math.max(1, ...counts)
877
+ const average = values.reduce((sum, value) => sum + value, 0) / values.length
878
+ const width = 300
879
+ const height = 124
880
+ const pad = 22
881
+ const barWidth = (width - pad * 2) / buckets.length
882
+ const plotHeight = height - pad - 18
883
+ const averageY = height - pad - (Math.max(0, Math.min(100, average)) / 100) * plotHeight
884
+ return h(
885
+ ChartCard,
886
+ { title: t.chartScoreDist, hint: `${values.length} ${t.skillsWord}` },
887
+ h(
888
+ 'svg',
889
+ {
890
+ className: 'sev-chart-svg',
891
+ viewBox: `0 0 ${width} ${height}`,
892
+ role: 'img',
893
+ 'aria-label': `${t.chartScoreDist}: ${buckets.map((bucket, index) => `${bucket.label} ${counts[index]}`).join(', ')}`,
894
+ },
895
+ counts.map((count, index) => {
896
+ const barHeight = count === 0 ? 0 : Math.max(2, (count / max) * plotHeight)
897
+ const x = pad + index * barWidth + 6
898
+ return h(
899
+ 'g',
900
+ { key: buckets[index].label },
901
+ h('rect', {
902
+ x,
903
+ y: height - pad - barHeight,
904
+ width: Math.max(4, barWidth - 12),
905
+ height: barHeight,
906
+ rx: 3,
907
+ fill: scoreColor(buckets[index].max),
908
+ opacity: count === 0 ? 0.18 : 0.9,
909
+ }),
910
+ count > 0
911
+ ? h(
912
+ 'text',
913
+ {
914
+ x: x + Math.max(4, barWidth - 12) / 2,
915
+ y: height - pad - barHeight - 4,
916
+ textAnchor: 'middle',
917
+ fontSize: 9,
918
+ fill: 'currentColor',
919
+ },
920
+ String(count),
921
+ )
922
+ : null,
923
+ h(
924
+ 'text',
925
+ {
926
+ x: x + Math.max(4, barWidth - 12) / 2,
927
+ y: height - 6,
928
+ textAnchor: 'middle',
929
+ fontSize: 8,
930
+ fill: 'currentColor',
931
+ opacity: 0.65,
932
+ },
933
+ buckets[index].label,
934
+ ),
935
+ )
936
+ }),
937
+ h('line', {
938
+ x1: pad,
939
+ x2: width - pad,
940
+ y1: averageY,
941
+ y2: averageY,
942
+ stroke: CHART_COLORS.blue,
943
+ strokeWidth: 1.5,
944
+ strokeDasharray: '4 3',
945
+ }),
946
+ h(
947
+ 'text',
948
+ { x: width - pad, y: Math.max(10, averageY - 4), textAnchor: 'end', fontSize: 9, fill: CHART_COLORS.blue },
949
+ `${t.chartAvg} ${fmt(average)}`,
950
+ ),
951
+ ),
952
+ )
953
+ }
954
+
955
+ function TrendSparkline(props) {
956
+ const { trend, t } = props
957
+ const points = (trend || []).filter((point) => Number.isFinite(point?.total)).slice(-12)
958
+ if (points.length < 2) return null
959
+ const width = 88
960
+ const height = 24
961
+ const values = points.map((point) => point.total)
962
+ const min = Math.min(...values)
963
+ const max = Math.max(...values)
964
+ const span = Math.max(1, max - min)
965
+ const coords = values.map((value, index) => [
966
+ 2 + (index * (width - 4)) / (values.length - 1),
967
+ height - 3 - ((value - min) / span) * (height - 6),
968
+ ])
969
+ const first = values[0]
970
+ const last = values[values.length - 1]
971
+ const color = last > first + 1 ? CHART_COLORS.green : last < first - 1 ? CHART_COLORS.red : CHART_COLORS.yellow
972
+ return h(
973
+ 'svg',
974
+ {
975
+ className: 'sev-spark',
976
+ viewBox: `0 0 ${width} ${height}`,
977
+ role: 'img',
978
+ 'aria-label': `${t.chartTrend}: ${values.map((value) => Math.round(value)).join(' → ')}`,
979
+ },
980
+ h('polyline', {
981
+ points: coords.map((point) => point.join(',')).join(' '),
982
+ fill: 'none',
983
+ stroke: color,
984
+ strokeWidth: 2,
985
+ strokeLinejoin: 'round',
986
+ strokeLinecap: 'round',
987
+ }),
988
+ h('circle', { cx: coords.at(-1)[0], cy: coords.at(-1)[1], r: 2.5, fill: color }),
989
+ )
990
+ }
991
+
992
+ function ValidityDonut(props) {
993
+ const { validity, t } = props
994
+ const coverage = (validity && validity.coverage) || {}
995
+ const total = Number(coverage.skills) || 0
996
+ if (total === 0) return h(ChartCard, { title: t.chartValidity }, chartEmpty(t))
997
+ const withCI = Math.min(total, Number(coverage.withCI) || 0)
998
+ const provisional = Math.min(total - withCI, Number(coverage.provisional) || 0)
999
+ const rest = Math.max(0, total - withCI - provisional)
1000
+ const segments = [
1001
+ { value: withCI, color: CHART_COLORS.green, label: t.chartWithCI },
1002
+ { value: provisional, color: CHART_COLORS.yellow, label: t.chartProvisional },
1003
+ { value: rest, color: 'var(--dsw-alias-border-l2, #d4d4d8)', label: t.chartNoEvidence },
1004
+ ].filter((segment) => segment.value > 0)
1005
+ const radius = 30
1006
+ const circumference = 2 * Math.PI * radius
1007
+ let offset = 0
1008
+ return h(
1009
+ ChartCard,
1010
+ { title: t.chartValidity, hint: `${withCI}/${total} ${t.chartWithCI}` },
1011
+ h(
1012
+ 'div',
1013
+ { className: 'sev-donut-wrap' },
1014
+ h(
1015
+ 'svg',
1016
+ {
1017
+ className: 'sev-donut',
1018
+ viewBox: '0 0 84 84',
1019
+ role: 'img',
1020
+ 'aria-label': segments.map((segment) => `${segment.label} ${segment.value}`).join(', '),
1021
+ },
1022
+ h('circle', { cx: 42, cy: 42, r: radius, fill: 'none', stroke: '#e4e4e7', strokeWidth: 9, opacity: 0.45 }),
1023
+ segments.map((segment) => {
1024
+ const length = (segment.value / total) * circumference
1025
+ const circle = h('circle', {
1026
+ key: segment.label,
1027
+ cx: 42,
1028
+ cy: 42,
1029
+ r: radius,
1030
+ fill: 'none',
1031
+ stroke: segment.color,
1032
+ strokeWidth: 9,
1033
+ strokeDasharray: `${length} ${circumference - length}`,
1034
+ strokeDashoffset: -offset,
1035
+ transform: 'rotate(-90 42 42)',
1036
+ strokeLinecap: 'butt',
1037
+ })
1038
+ offset += length
1039
+ return circle
1040
+ }),
1041
+ h(
1042
+ 'text',
1043
+ { x: 42, y: 39, textAnchor: 'middle', fontSize: 15, fontWeight: 700, fill: 'currentColor' },
1044
+ String(withCI),
1045
+ ),
1046
+ h(
1047
+ 'text',
1048
+ { x: 42, y: 52, textAnchor: 'middle', fontSize: 8, fill: 'currentColor', opacity: 0.65 },
1049
+ `${t.chartWithCI}`,
1050
+ ),
1051
+ ),
1052
+ h(
1053
+ 'ul',
1054
+ { className: 'sev-chart-legend' },
1055
+ segments.map((segment) =>
1056
+ h(
1057
+ 'li',
1058
+ { key: segment.label },
1059
+ h('i', { style: { background: segment.color } }),
1060
+ segment.label,
1061
+ h('b', null, ` ${segment.value}`),
1062
+ ),
1063
+ ),
1064
+ h(
1065
+ 'li',
1066
+ null,
1067
+ h('i', { style: { background: CHART_COLORS.blue } }),
1068
+ `${t.chartActionable} ${coverage.actionable ?? 0}`,
1069
+ ),
1070
+ ),
1071
+ ),
1072
+ )
1073
+ }
1074
+
1075
+ function fmtMs(value) {
1076
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
1077
+ if (value >= 1000) {
1078
+ const seconds = value / 1000
1079
+ return (Number.isInteger(seconds) ? String(seconds) : seconds.toFixed(1)) + 's'
1080
+ }
1081
+ return Math.round(value) + 'ms'
1082
+ }
1083
+
1084
+ function McpLatencyChart(props) {
1085
+ const { servers, t, solo } = props
1086
+ const rows = (servers || []).filter((row) => (row.calls || 0) > 0).slice(0, 8)
1087
+ if (rows.length === 0) return h(ChartCard, { title: t.chartMcp }, chartEmpty(t))
1088
+ // The alert line follows the configured MCP p95 threshold; 3000 is only the
1089
+ // fallback for an older host payload that predates the `mcp` block.
1090
+ const configured = Number(props.thresholdMs)
1091
+ const threshold = Number.isFinite(configured) && configured > 0 ? configured : 3000
1092
+ const peak = Math.max(threshold, ...rows.map((row) => Math.max(row.p50Ms || 0, row.p95Ms || 0)))
1093
+ const scale = peak * 1.05
1094
+ const width = (value) => Math.max(1.5, Math.min(100, ((value || 0) / scale) * 100)) + '%'
1095
+ return h(
1096
+ ChartCard,
1097
+ { title: t.chartMcp, hint: t.chartThreshold + ' ' + fmtMs(threshold), solo },
1098
+ h(
1099
+ 'div',
1100
+ { className: 'sev-lat' },
1101
+ rows.map((row) =>
1102
+ h(
1103
+ 'div',
1104
+ {
1105
+ key: row.server,
1106
+ className: 'sev-lat-row',
1107
+ role: 'img',
1108
+ 'aria-label':
1109
+ row.server +
1110
+ ': ' +
1111
+ t.chartP50 +
1112
+ ' ' +
1113
+ fmtMs(row.p50Ms) +
1114
+ ', ' +
1115
+ t.chartP95 +
1116
+ ' ' +
1117
+ fmtMs(row.p95Ms) +
1118
+ ', ' +
1119
+ t.chartThreshold +
1120
+ ' ' +
1121
+ fmtMs(threshold),
1122
+ },
1123
+ h(
1124
+ 'div',
1125
+ { className: 'sev-lat-head' },
1126
+ h('b', null, row.server),
1127
+ h('span', null, t.chartP50 + ' ' + fmtMs(row.p50Ms) + ' · ' + t.chartP95 + ' ' + fmtMs(row.p95Ms)),
1128
+ ),
1129
+ h(
1130
+ 'div',
1131
+ { className: 'sev-meter' },
1132
+ h('i', { className: 'sev-meter-fill sev-meter-fill--p95', style: { width: width(row.p95Ms) } }),
1133
+ h('i', { className: 'sev-meter-fill sev-meter-fill--p50', style: { width: width(row.p50Ms) } }),
1134
+ h('span', { className: 'sev-meter-threshold', style: { left: width(threshold) } }),
1135
+ ),
1136
+ ),
1137
+ ),
1138
+ h(
1139
+ 'ul',
1140
+ { className: 'sev-chart-legend' },
1141
+ h('li', null, h('i', { style: { background: CHART_COLORS.blue } }), t.chartP50),
1142
+ h('li', null, h('i', { style: { background: CHART_COLORS.yellow } }), t.chartP95),
1143
+ h('li', null, h('i', { style: { background: CHART_COLORS.red } }), t.chartThreshold + ' ' + fmtMs(threshold)),
1144
+ ),
1145
+ ),
1146
+ )
1147
+ }
1148
+
1149
+ function SessionActivityChart(props) {
1150
+ const { runs, t, solo } = props
1151
+ const rows = [...(runs || [])]
1152
+ .filter((run) => Number.isFinite(run.lastAt))
1153
+ .sort((a, b) => a.lastAt - b.lastAt)
1154
+ .slice(-12)
1155
+ if (rows.length === 0) return h(ChartCard, { title: t.chartSessions }, chartEmpty(t))
1156
+ const width = 300
1157
+ const height = 104
1158
+ const pad = 18
1159
+ const plot = height - pad - 14
1160
+ const max = Math.max(1, ...rows.map((run) => (run.toolCalls || 0) + (run.loads || 0)))
1161
+ const barWidth = (width - pad * 2) / rows.length
1162
+ const totals = rows.reduce(
1163
+ (sum, run) => ({
1164
+ loads: sum.loads + (run.loads || 0),
1165
+ calls: sum.calls + (run.toolCalls || 0),
1166
+ errors: sum.errors + (run.errors || 0),
1167
+ }),
1168
+ { loads: 0, calls: 0, errors: 0 },
1169
+ )
1170
+ return h(
1171
+ ChartCard,
1172
+ { title: t.chartSessions, hint: `${rows.length} ${t.chartSessionsUnit}`, solo },
1173
+ h(
1174
+ 'svg',
1175
+ {
1176
+ className: 'sev-chart-svg',
1177
+ viewBox: `0 0 ${width} ${height}`,
1178
+ role: 'img',
1179
+ 'aria-label': rows
1180
+ .map(
1181
+ (run) =>
1182
+ `${new Date(run.lastAt).toLocaleTimeString()}: ${run.loads || 0} ${t.chartLoads}, ${run.errors || 0} ${t.chartErrors}`,
1183
+ )
1184
+ .join('; '),
1185
+ },
1186
+ rows.map((run, index) => {
1187
+ const calls = run.toolCalls || 0
1188
+ const loads = run.loads || 0
1189
+ const errors = run.errors || 0
1190
+ const barHeight = Math.max(2, ((calls + loads) / max) * plot)
1191
+ const x = pad + index * barWidth + 2
1192
+ return h(
1193
+ 'g',
1194
+ { key: `${run.sessionId}-${index}` },
1195
+ h('rect', {
1196
+ x,
1197
+ y: height - pad - barHeight,
1198
+ width: Math.max(3, barWidth - 4),
1199
+ height: barHeight,
1200
+ rx: 2,
1201
+ fill: CHART_COLORS.blue,
1202
+ opacity: 0.8,
1203
+ }),
1204
+ errors > 0
1205
+ ? h('rect', {
1206
+ x,
1207
+ y: height - pad - barHeight,
1208
+ width: Math.max(3, barWidth - 4),
1209
+ height: Math.max(2, Math.min(barHeight, (errors / Math.max(1, calls + loads)) * barHeight)),
1210
+ rx: 2,
1211
+ fill: CHART_COLORS.red,
1212
+ })
1213
+ : null,
1214
+ )
1215
+ }),
1216
+ h(
1217
+ 'text',
1218
+ { x: pad, y: height - 3, fontSize: 8, fill: 'currentColor', opacity: 0.7 },
1219
+ `${totals.loads} ${t.chartLoads} · ${totals.calls} ${t.chartCalls} · ${totals.errors} ${t.chartErrors}`,
1220
+ ),
1221
+ ),
1222
+ )
1223
+ }
1224
+
1225
+ function SkillsCharts(props) {
1226
+ const { data, skills, t } = props
1227
+ return h(
1228
+ 'div',
1229
+ { className: 'sev-charts' },
1230
+ h(ScoreHistogram, { skills, t }),
1231
+ h(ValidityDonut, { validity: data && data.validity, t }),
1232
+ h(McpLatencyChart, { servers: data && data.mcpServers, t, thresholdMs: data && data.mcp && data.mcp.p95Ms }),
1233
+ h(SessionActivityChart, { runs: data && data.runs, t }),
1234
+ )
1235
+ }
1236
+
1237
+ // client/06c-steps.js
1238
+ // Per-turn loop trajectory. The host records one scored row per agent step;
1239
+ // this view shows the overall picture, a skill-filtered drill-down, and the
1240
+ // recent-turn comparison the panel was missing.
1241
+ function stepClock(at) {
1242
+ return Number.isFinite(at) ? new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '—'
1243
+ }
1244
+
1245
+ function stepDeltaTone(delta) {
1246
+ if (!Number.isFinite(delta) || Math.abs(delta) < 0.05) return 'flat'
1247
+ return delta > 0 ? 'up' : 'down'
1248
+ }
1249
+
1250
+ function StepKpi(props) {
1251
+ return h('div', { className: 'sev-kpi' }, h('b', null, props.value), h('span', null, props.label))
1252
+ }
1253
+
1254
+ function StepRow(props) {
1255
+ const { step, previous, t } = props
1256
+ const score = step.score || {}
1257
+ const delta =
1258
+ previous && Number.isFinite(previous.score?.total)
1259
+ ? Math.round((score.total - previous.score.total) * 10) / 10
1260
+ : null
1261
+ const meta = [
1262
+ `${step.toolCalls} ${t.stepCalls}`,
1263
+ step.errors > 0 ? `${step.errors} ${t.stepErrors}` : null,
1264
+ step.durationMs > 0 ? `${Math.round(step.durationMs / 100) / 10}s` : null,
1265
+ step.tokens?.calls > 0 ? `${step.tokens.input + step.tokens.output} ${t.stepTokens}` : null,
1266
+ ].filter(Boolean)
1267
+ return h(
1268
+ 'li',
1269
+ { className: 'sev-step' },
1270
+ h(
1271
+ 'span',
1272
+ {
1273
+ className: 'sev-step-score',
1274
+ style: { color: scoreColor(score.total), borderColor: scoreColor(score.total) },
1275
+ title: (score.penalties || []).map((item) => `${item.id} −${item.penalty}`).join(', '),
1276
+ },
1277
+ fmt(score.total),
1278
+ ),
1279
+ h(
1280
+ 'div',
1281
+ { className: 'sev-step-main' },
1282
+ h(
1283
+ 'div',
1284
+ { className: 'sev-step-title' },
1285
+ `${t.stepStep} ${step.step ?? '?'} · ${meta.join(' · ')}`,
1286
+ delta !== null
1287
+ ? h(
1288
+ 'span',
1289
+ { className: 'sev-step-delta sev-step-delta--' + stepDeltaTone(delta) },
1290
+ (delta > 0 ? '+' : '') + delta,
1291
+ )
1292
+ : null,
1293
+ ),
1294
+ h(
1295
+ 'div',
1296
+ { className: 'sev-step-sub' },
1297
+ (step.skills || []).length > 0
1298
+ ? step.skills.map((skill) =>
1299
+ h(
1300
+ 'button',
1301
+ {
1302
+ key: skill,
1303
+ type: 'button',
1304
+ className: 'sev-step-skill',
1305
+ onClick: () => props.onFilter(skill),
1306
+ title: t.stepFiltered,
1307
+ },
1308
+ skill,
1309
+ ),
1310
+ )
1311
+ : h('span', { className: 'sev-muted' }, t.stepNoSkill),
1312
+ (step.errorNames || []).length > 0
1313
+ ? h('span', { className: 'sev-step-err' }, step.errorNames.join(', '))
1314
+ : null,
1315
+ ),
1316
+ ),
1317
+ )
1318
+ }
1319
+
1320
+ function StepTurn(props) {
1321
+ const { turn, t, previousAverage, onFilter } = props
1322
+ const delta =
1323
+ Number.isFinite(previousAverage) && Number.isFinite(turn.average) ? turn.average - previousAverage : null
1324
+ const trend = turn.steps.map((step) => ({ total: step.score?.total }))
1325
+ return h(
1326
+ 'section',
1327
+ { className: 'sev-turn' },
1328
+ h(
1329
+ 'header',
1330
+ { className: 'sev-turn-head' },
1331
+ h('b', null, `${t.stepTurn} ${turn.turn ?? '?'} · ${stepClock(turn.lastAt)}`),
1332
+ h(
1333
+ 'span',
1334
+ { className: 'sev-turn-meta' },
1335
+ `${turn.steps.length} ${t.stepStep} · ${turn.skills.join(', ') || '—'}`,
1336
+ ),
1337
+ h(TrendSparkline, { trend, t }),
1338
+ h(
1339
+ 'span',
1340
+ { className: 'sev-turn-avg', style: { color: scoreColor(turn.average) } },
1341
+ `${t.stepTurnAvg} ${fmt(turn.average)}`,
1342
+ ),
1343
+ delta !== null
1344
+ ? h(
1345
+ 'span',
1346
+ { className: 'sev-turn-delta sev-step-delta--' + stepDeltaTone(Math.round(delta * 10) / 10) },
1347
+ `${t.stepDelta} ${delta > 0 ? '+' : ''}${Math.round(delta * 10) / 10}`,
1348
+ )
1349
+ : null,
1350
+ ),
1351
+ h(
1352
+ 'ol',
1353
+ { className: 'sev-steplist' },
1354
+ turn.steps.map((step, index) =>
1355
+ h(StepRow, { key: `${step.step}-${step.at}`, step, previous: turn.steps[index - 1], t, onFilter }),
1356
+ ),
1357
+ ),
1358
+ )
1359
+ }
1360
+
1361
+ function StepsView(props) {
1362
+ const { data, t } = props
1363
+ const filter = props.filter || ''
1364
+ const allSteps = (data && Array.isArray(data.steps) ? data.steps : [])
1365
+ .slice()
1366
+ .sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
1367
+ const filterSkills = [...new Set(allSteps.flatMap((step) => step.skills || []))].sort()
1368
+ const steps = filter ? allSteps.filter((step) => (step.skills || []).includes(filter)) : allSteps
1369
+ const allTurns = data && Array.isArray(data.stepTurns) ? data.stepTurns : []
1370
+ const stepKey = (step) => `${step.sessionId}#${step.turn}#${step.step}#${step.at}`
1371
+ const visibleKeys = new Set(steps.map(stepKey))
1372
+ const turns = allTurns
1373
+ .map((turn) => ({ ...turn, steps: (turn.steps || []).filter((step) => visibleKeys.has(stepKey(step))) }))
1374
+ .filter((turn) => turn.steps.length > 0)
1375
+ const scores = steps.map((step) => step.score?.total).filter((value) => Number.isFinite(value))
1376
+ const average = scores.length > 0 ? scores.reduce((sum, value) => sum + value, 0) / scores.length : null
1377
+ const latest = turns[0] || null
1378
+ const previous = turns[1] || null
1379
+ const delta =
1380
+ latest && previous && Number.isFinite(latest.average) && Number.isFinite(previous.average)
1381
+ ? Math.round((latest.average - previous.average) * 10) / 10
1382
+ : null
1383
+ const recent = turns.slice(0, 5)
1384
+ const maxRecent = Math.max(1, ...recent.map((turn) => turn.average || 0))
1385
+ return h(
1386
+ 'div',
1387
+ { className: 'sev-steps' },
1388
+ steps.length === 0
1389
+ ? h('div', { className: 'sev-empty' }, t.stepNoData)
1390
+ : h(
1391
+ React.Fragment,
1392
+ null,
1393
+ h(
1394
+ 'div',
1395
+ { className: 'sev-steps-kpis' },
1396
+ h(StepKpi, { label: t.stepKpiAvg, value: average === null ? '—' : fmt(average) }),
1397
+ h(StepKpi, {
1398
+ label: t.stepKpiLatest,
1399
+ value:
1400
+ latest && latest.average !== null
1401
+ ? `${t.stepTurn} ${latest.turn ?? '?'} · ${fmt(latest.average)}` +
1402
+ (delta !== null ? ` (${delta > 0 ? '+' : ''}${delta})` : '')
1403
+ : '—',
1404
+ }),
1405
+ h(StepKpi, {
1406
+ label: t.stepKpiCount,
1407
+ value: `${scores.length} ${t.stepStep} / ${allTurns.length} ${t.stepTurn}`,
1408
+ }),
1409
+ ),
1410
+ h(
1411
+ 'div',
1412
+ { className: 'sev-recent' },
1413
+ h('b', null, t.stepRecent),
1414
+ recent.map((turn) =>
1415
+ h(
1416
+ 'div',
1417
+ { key: `${turn.sessionId}-${turn.turn}`, className: 'sev-recent-turn' },
1418
+ h('span', null, `${t.stepTurn} ${turn.turn ?? '?'}`),
1419
+ h('i', {
1420
+ style: {
1421
+ width: `${Math.max(4, ((turn.average || 0) / maxRecent) * 100)}%`,
1422
+ background: scoreColor(turn.average),
1423
+ },
1424
+ }),
1425
+ h('em', null, fmt(turn.average)),
1426
+ ),
1427
+ ),
1428
+ ),
1429
+ h(
1430
+ 'div',
1431
+ { className: 'sev-step-filters' },
1432
+ h('b', null, t.stepFilter),
1433
+ h(
1434
+ 'button',
1435
+ {
1436
+ type: 'button',
1437
+ className: 'sev-chip' + (filter === '' ? ' sev-chip--on' : ''),
1438
+ onClick: () => props.onFilter(''),
1439
+ },
1440
+ t.stepAll,
1441
+ ),
1442
+ filterSkills.map((skill) =>
1443
+ h(
1444
+ 'button',
1445
+ {
1446
+ key: skill,
1447
+ type: 'button',
1448
+ className: 'sev-chip' + (filter === skill ? ' sev-chip--on' : ''),
1449
+ onClick: () => props.onFilter(skill),
1450
+ },
1451
+ skill,
1452
+ ),
1453
+ ),
1454
+ ),
1455
+ h('div', { className: 'sev-step-formula' }, t.stepFormula),
1456
+ turns.length === 0
1457
+ ? h('div', { className: 'sev-empty' }, filter ? t.noMatch : t.stepNoData)
1458
+ : turns.map((turn, index) =>
1459
+ h(StepTurn, {
1460
+ key: `${turn.sessionId}-${turn.turn}`,
1461
+ turn,
1462
+ t,
1463
+ previousAverage: turns[index + 1]?.average ?? null,
1464
+ onFilter: props.onFilter,
1465
+ }),
1466
+ ),
1467
+ ),
1468
+ )
1469
+ }
1470
+
1471
+ // client/07-board.js
1472
+ // ------------------------------------------------------------- main panel
1473
+ // Same placement as the context plugin: a sidebar panel icon + a main panel
1474
+ // keyed by the same id. This is the board's primary home inside DSH.
1475
+ function PanelIcon(props) {
1476
+ const size = props && Number(props.size) > 0 ? Number(props.size) : 18
1477
+ const active = props && props.active === true
1478
+ return h('span', { style: { display: 'inline-flex', opacity: active ? 1 : 0.72 } }, h(GaugeIcon, { size }))
1479
+ }
1480
+
1481
+ function BoardPanel() {
1482
+ const state = useStore()
1483
+ const { lang, t } = useLang()
1484
+ const copyTimer = useRef(null)
1485
+ const mounted = useRef(true)
1486
+ const [configOpen, setConfigOpen] = useState(false)
1487
+ useEffect(() => {
1488
+ ensureReport()
1489
+ return () => {
1490
+ mounted.current = false
1491
+ if (copyTimer.current) clearTimeout(copyTimer.current)
1492
+ }
1493
+ }, [])
1494
+ // Escape closes the in-panel settings dialog; the web config page stays as a
1495
+ // second surface but is unreachable from the desktop shell (window.open is
1496
+ // denied there), so the dialog is the entry point that always works.
1497
+ useEffect(() => {
1498
+ if (!configOpen) return undefined
1499
+ const opener = typeof document !== 'undefined' ? document.activeElement : null
1500
+ const onKey = (event) => {
1501
+ if (event.key === 'Escape') setConfigOpen(false)
1502
+ }
1503
+ window.addEventListener('keydown', onKey)
1504
+ return () => {
1505
+ window.removeEventListener('keydown', onKey)
1506
+ if (opener && typeof opener.focus === 'function') opener.focus()
1507
+ }
1508
+ }, [configOpen])
1509
+ const data = state.data
1510
+ const skills = (data && data.skills) || []
1511
+ const [copyState, setCopyState] = useState('idle')
1512
+ const [query, setQuery] = useState('')
1513
+ const [onlyActionable, setOnlyActionable] = useState(false)
1514
+ const copy = async () => {
1515
+ // Before the first load there is nothing to hand over; copying "{}" and
1516
+ // reporting success is worse than a disabled button.
1517
+ if (!data) return
1518
+ const ok = await copyText(JSON.stringify(data, null, 2))
1519
+ if (!mounted.current) return
1520
+ setCopyState(ok ? 'copied' : 'failed')
1521
+ if (copyTimer.current) clearTimeout(copyTimer.current)
1522
+ copyTimer.current = setTimeout(() => setCopyState('idle'), 1600)
1523
+ }
1524
+ // The dialog declares aria-modal, so Tab must not walk into the board behind it.
1525
+ const trapFocus = (event) => {
1526
+ if (event.key !== 'Tab') return
1527
+ const focusable = [
1528
+ ...event.currentTarget.querySelectorAll('button,[href],input,select,textarea,[tabindex]:not([tabindex="-1"])'),
1529
+ ].filter((node) => !node.disabled && node.offsetParent !== null)
1530
+ if (focusable.length === 0) return
1531
+ const first = focusable[0]
1532
+ const last = focusable[focusable.length - 1]
1533
+ if (event.shiftKey && document.activeElement === first) {
1534
+ event.preventDefault()
1535
+ last.focus()
1536
+ } else if (!event.shiftKey && document.activeElement === last) {
1537
+ event.preventDefault()
1538
+ first.focus()
1539
+ }
1540
+ }
1541
+ const actionable = (data && data.validity && data.validity.coverage && data.validity.coverage.actionable) || 0
1542
+ const hasFix = (entry) =>
1543
+ (entry.advice || []).some((item) => item.severity === 'critical' || item.severity === 'warning')
1544
+ const fixable = skills.filter(hasFix).length
1545
+ const loads = skills.reduce((total, entry) => total + (entry.stats?.loads || 0), 0)
1546
+ const scored = skills.map((entry) => entry.score?.total).filter((value) => Number.isFinite(value))
1547
+ const average = scored.length > 0 ? scored.reduce((a, b) => a + b, 0) / scored.length : null
1548
+ const needle = query.trim().toLowerCase()
1549
+ const visibleSkills = skills.filter(
1550
+ (entry) =>
1551
+ (!onlyActionable || hasFix(entry)) &&
1552
+ (needle.length === 0 ||
1553
+ String(entry.skill ?? '')
1554
+ .toLowerCase()
1555
+ .includes(needle)),
1556
+ )
1557
+ const updated =
1558
+ data && data.generatedAt && Number.isFinite(Date.parse(data.generatedAt))
1559
+ ? new Date(data.generatedAt).toLocaleTimeString()
1560
+ : null
1561
+ const rankingNote =
1562
+ data && data.ranking ? (lang === 'zh' && data.ranking.noteZh ? data.ranking.noteZh : data.ranking.note) : null
1563
+ return h(
1564
+ 'div',
1565
+ { className: 'sev-panel' },
1566
+ h('style', { key: 'sev-panel-style' }, STYLES + '\n' + PANEL_STYLES.join('\n')),
1567
+ h(
1568
+ 'div',
1569
+ { className: 'sev-head', style: { borderBottom: 'none', padding: '0 0 6px' } },
1570
+ h(
1571
+ 'div',
1572
+ { className: 'sev-head-text' },
1573
+ h('div', { className: 'sev-title' }, t.title),
1574
+ h(
1575
+ 'div',
1576
+ { className: 'sev-sub' },
1577
+ skills.length +
1578
+ ' ' +
1579
+ t.detailSkills +
1580
+ ' · ' +
1581
+ actionable +
1582
+ ' ' +
1583
+ t.detailActionable +
1584
+ (updated ? ' · ' + t.updated + ' ' + updated : ''),
1585
+ ),
1586
+ h(
1587
+ 'div',
1588
+ { className: 'sev-tabs', role: 'tablist' },
1589
+ ['skills', 'steps', 'runs', 'mcp', 'dev'].map((view) =>
1590
+ h(
1591
+ 'button',
1592
+ {
1593
+ key: view,
1594
+ type: 'button',
1595
+ role: 'tab',
1596
+ id: 'sev-board-tab-' + view,
1597
+ 'aria-controls': 'sev-board-view',
1598
+ 'aria-selected': state.view === view,
1599
+ tabIndex: state.view === view ? 0 : -1,
1600
+ className: 'sev-tab' + (state.view === view ? ' sev-tab--on' : ''),
1601
+ onClick: () => setView(view),
1602
+ onKeyDown: (event) => {
1603
+ if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return
1604
+ event.preventDefault()
1605
+ const views = ['skills', 'steps', 'runs', 'mcp', 'dev']
1606
+ const index = views.indexOf(view)
1607
+ const next = views[(index + (event.key === 'ArrowRight' ? 1 : views.length - 1)) % views.length]
1608
+ setView(next)
1609
+ const target =
1610
+ typeof document !== 'undefined' ? document.getElementById('sev-board-tab-' + next) : null
1611
+ if (target) target.focus()
1612
+ },
1613
+ },
1614
+ t.tabs[view],
1615
+ ),
1616
+ ),
1617
+ ),
1618
+ ),
1619
+ h(
1620
+ 'div',
1621
+ { className: 'sev-head-actions' },
1622
+ h(
1623
+ 'button',
1624
+ {
1625
+ type: 'button',
1626
+ className: 'sev-btn',
1627
+ title: t.rowConfigSummary,
1628
+ onClick: () => setConfigOpen(true),
1629
+ },
1630
+ t.config,
1631
+ ),
1632
+ h('button', { type: 'button', className: 'sev-btn', onClick: load, disabled: state.loading }, t.refresh),
1633
+ h(
1634
+ 'button',
1635
+ { type: 'button', className: 'sev-btn', onClick: copy, disabled: !data },
1636
+ h(
1637
+ 'span',
1638
+ { role: 'status', 'aria-live': 'polite' },
1639
+ copyState === 'copied' ? t.copied : copyState === 'failed' ? t.copyFailed : t.copy,
1640
+ ),
1641
+ ),
1642
+ ),
1643
+ ),
1644
+ h(
1645
+ 'div',
1646
+ { className: 'sev-kpis' },
1647
+ [
1648
+ [t.kpiSkills, skills.length],
1649
+ [t.kpiLoads, loads],
1650
+ [t.kpiFixable, fixable],
1651
+ [t.kpiAvg, average === null ? '—' : fmt(average)],
1652
+ ].map(([label, value]) =>
1653
+ h('div', { className: 'sev-kpi', key: label }, h('b', null, String(value)), h('span', null, label)),
1654
+ ),
1655
+ ),
1656
+ state.loading && !data ? h('div', { className: 'sev-empty' }, t.loading) : null,
1657
+ state.view === 'skills' && data ? h(SkillsCharts, { data, skills, t }) : null,
1658
+ data && !data.scoring
1659
+ ? h('div', { className: 'sev-stale' }, h('b', null, t.staleTitle), h('span', null, t.staleHint))
1660
+ : null,
1661
+ state.error ? h('div', { className: 'sev-error' }, t.failed + ': ' + state.error + ' — ' + DATA_URL) : null,
1662
+ data && data.totals && data.totals.storeError
1663
+ ? h('div', { className: 'sev-error' }, t.storeError + ': ' + data.totals.storeError)
1664
+ : null,
1665
+ state.view === 'skills' && rankingNote ? h('div', { className: 'sev-note' }, rankingNote) : null,
1666
+ state.view === 'skills'
1667
+ ? h(
1668
+ 'div',
1669
+ { className: 'sev-filterbar' },
1670
+ h('input', {
1671
+ type: 'search',
1672
+ className: 'sev-search',
1673
+ value: query,
1674
+ placeholder: t.searchPlaceholder,
1675
+ 'aria-label': t.searchPlaceholder,
1676
+ onChange: (event) => setQuery(event.target.value),
1677
+ }),
1678
+ h(
1679
+ 'button',
1680
+ {
1681
+ type: 'button',
1682
+ className: 'sev-chip' + (onlyActionable ? ' sev-chip--on' : ''),
1683
+ 'aria-pressed': onlyActionable,
1684
+ onClick: () => setOnlyActionable((value) => !value),
1685
+ },
1686
+ t.onlyActionable + ' (' + fixable + ')',
1687
+ ),
1688
+ )
1689
+ : null,
1690
+ h(
1691
+ 'div',
1692
+ { role: 'tabpanel', id: 'sev-board-view', 'aria-labelledby': 'sev-board-tab-' + state.view },
1693
+ state.view === 'skills'
1694
+ ? !state.loading && !state.error && skills.length === 0
1695
+ ? h('div', { className: 'sev-empty' }, t.empty)
1696
+ : visibleSkills.length === 0
1697
+ ? h('div', { className: 'sev-empty' }, t.noMatch)
1698
+ : visibleSkills.map((skill) =>
1699
+ h(SkillCard, {
1700
+ key: skill.skill,
1701
+ skill,
1702
+ t,
1703
+ lang,
1704
+ onTrace: (name) => store.set((current) => ({ ...current, view: 'steps', stepFilter: name })),
1705
+ }),
1706
+ )
1707
+ : state.view === 'steps'
1708
+ ? h(StepsView, {
1709
+ data,
1710
+ t,
1711
+ filter: state.stepFilter || '',
1712
+ onFilter: (name) => store.set((current) => ({ ...current, stepFilter: name })),
1713
+ })
1714
+ : state.view === 'runs'
1715
+ ? h(RunsView, { data, t })
1716
+ : state.view === 'mcp'
1717
+ ? h(McpView, { data, t, lang })
1718
+ : h(DevView, { data, t }),
1719
+ ),
1720
+ configOpen
1721
+ ? h(
1722
+ 'div',
1723
+ {
1724
+ className: 'sev-backdrop',
1725
+ role: 'presentation',
1726
+ onMouseDown: (event) => {
1727
+ if (event.target === event.currentTarget) setConfigOpen(false)
1728
+ },
1729
+ },
1730
+ h(
1731
+ 'div',
1732
+ {
1733
+ className: 'sev-dialog',
1734
+ role: 'dialog',
1735
+ 'aria-modal': 'true',
1736
+ 'aria-label': t.config,
1737
+ onKeyDown: trapFocus,
1738
+ },
1739
+ h(
1740
+ 'header',
1741
+ { className: 'sev-head' },
1742
+ h(
1743
+ 'div',
1744
+ { className: 'sev-head-text' },
1745
+ h('div', { className: 'sev-title' }, t.config),
1746
+ h('div', { className: 'sev-sub' }, t.rowConfigSummary),
1747
+ ),
1748
+ h(
1749
+ 'div',
1750
+ { className: 'sev-head-actions' },
1751
+ h(
1752
+ 'button',
1753
+ {
1754
+ type: 'button',
1755
+ className: 'sev-btn sev-btn--icon',
1756
+ onClick: () => setConfigOpen(false),
1757
+ 'aria-label': t.close,
1758
+ title: t.close,
1759
+ autoFocus: true,
1760
+ },
1761
+ '✕',
1762
+ ),
1763
+ ),
1764
+ ),
1765
+ h('div', { className: 'sev-body' }, h(SettingsForm, { webOpen: false })),
1766
+ ),
1767
+ )
1768
+ : null,
1769
+ )
1770
+ }
1771
+
1772
+ const PANEL_STYLES = [
1773
+ '.sev-panel{height:100%;overflow:auto;box-sizing:border-box;padding:22px 26px 32px;display:flex;flex-direction:column;gap:14px;color:var(--dsw-alias-label-primary, #18181b);font-size:13px;line-height:1.5;background:var(--dsw-alias-bg-layer-1, transparent)}',
1774
+ '.sev-panel .sev-head{display:flex;align-items:flex-start;gap:12px}',
1775
+ '.sev-kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}',
1776
+ '.sev-kpi{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:10px;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
1777
+ '.sev-kpi b{font-size:18px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary, #18181b)}',
1778
+ '.sev-kpi span{font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
1779
+ '.sev-filterbar{display:flex;align-items:center;gap:10px}',
1780
+ '.sev-search{flex:1;min-width:0;padding:6px 10px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:8px;background:var(--dsw-alias-bg-layer-1, #fff);color:inherit;font:inherit}',
1781
+ '.sev-search:focus-visible{outline:2px solid var(--dsw-alias-brand-primary, #4d6bfe);outline-offset:1px}',
1782
+ '.sev-chip{padding:6px 10px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:999px;background:transparent;color:var(--dsw-alias-label-secondary, #71717a);font:inherit;cursor:pointer;white-space:nowrap}',
1783
+ '.sev-chip--on{border-color:var(--dsw-alias-brand-primary, #4d6bfe);color:var(--dsw-alias-brand-primary, #4d6bfe);background:var(--dsw-alias-bg-layer-2, #f4f4f5);font-weight:600}',
1784
+ ]
1785
+
1786
+ function FooterAction(props) {
1787
+ const { t } = useLang()
1788
+ const wide = props && props.wide !== false
1789
+ return h(
1790
+ 'button',
1791
+ {
1792
+ type: 'button',
1793
+ className: wide ? 'sev-btn' : 'sev-btn sev-btn--icon',
1794
+ title: t.open,
1795
+ 'aria-label': t.open,
1796
+ onClick: openReport,
1797
+ },
1798
+ h(GaugeIcon, { size: 16 }),
1799
+ wide ? h('span', null, t.open) : null,
1800
+ )
1801
+ }
1802
+
1803
+ function DimensionBar(props) {
1804
+ const value = props.value
1805
+ const width = typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0
1806
+ return h(
1807
+ 'div',
1808
+ { className: 'sev-dim' },
1809
+ h('span', { className: 'sev-dim-label' }, props.label),
1810
+ h('span', { className: 'sev-dim-track' }, h('i', { style: { width: width + '%', background: scoreColor(value) } })),
1811
+ h('b', null, fmt(value)),
1812
+ )
1813
+ }
1814
+
1815
+ const SkillCard = React.memo(function SkillCard(props) {
1816
+ const skill = props.skill
1817
+ const t = props.t
1818
+ const lang = props.lang || 'zh'
1819
+ const score = skill.score || {}
1820
+ const dims = score.dimensions || {}
1821
+ const stats = skill.stats || {}
1822
+ const advice = (skill.topAdvice && skill.topAdvice.length ? skill.topAdvice : skill.advice || []).slice(0, 3)
1823
+ return h(
1824
+ 'article',
1825
+ { className: 'sev-card' },
1826
+ h(
1827
+ 'div',
1828
+ { className: 'sev-card-head' },
1829
+ h('div', { className: 'sev-name' }, skill.skill),
1830
+ h(TrendSparkline, { trend: skill.trend, t }),
1831
+ h('div', { className: 'sev-grade', style: { color: scoreColor(score.total) } }, score.grade || '?'),
1832
+ h('div', { className: 'sev-total', style: { color: scoreColor(score.total) } }, fmt(score.total)),
1833
+ h(
1834
+ 'button',
1835
+ {
1836
+ type: 'button',
1837
+ className: 'sev-trace',
1838
+ title: t.stepTrace,
1839
+ 'aria-label': t.stepTrace + ': ' + skill.skill,
1840
+ onClick: () => props.onTrace && props.onTrace(skill.skill),
1841
+ },
1842
+ t.stepTrace,
1843
+ ),
1844
+ ),
1845
+ score.provisional ? h('div', { className: 'sev-provisional' }, t.provisional) : null,
1846
+ score.ci
1847
+ ? h(
1848
+ 'div',
1849
+ { className: 'sev-ci' },
1850
+ '95% CI ' + fmt(score.ci.low) + ' – ' + fmt(score.ci.high) + ' · n=' + (score.samples || 0),
1851
+ )
1852
+ : null,
1853
+ h(
1854
+ 'div',
1855
+ { className: 'sev-dims' },
1856
+ h(DimensionBar, { label: t.dims.static, value: dims.static }),
1857
+ h(DimensionBar, { label: t.dims.reliability, value: dims.reliability }),
1858
+ h(DimensionBar, { label: t.dims.effectiveness, value: dims.effectiveness }),
1859
+ h(DimensionBar, { label: t.dims.efficiency, value: dims.efficiency }),
1860
+ ),
1861
+ h(
1862
+ 'div',
1863
+ { className: 'sev-meta' },
1864
+ (stats.loads || 0) +
1865
+ ' ' +
1866
+ t.loads +
1867
+ ' · ' +
1868
+ (stats.closed || 0) +
1869
+ ' ' +
1870
+ t.closed +
1871
+ ' · ' +
1872
+ t.corr +
1873
+ ' ' +
1874
+ pct(stats.correctionRate) +
1875
+ ' · ' +
1876
+ t.err +
1877
+ ' ' +
1878
+ pct(stats.errRate) +
1879
+ ' · ' +
1880
+ t.latency +
1881
+ ' ' +
1882
+ fmt(stats.p50LoadMs, 0) +
1883
+ 'ms' +
1884
+ (typeof stats.tokensPerLoad === 'number'
1885
+ ? ' · ≈' + stats.tokensPerLoad.toLocaleString() + ' ' + t.tokPerLoad
1886
+ : ''),
1887
+ ),
1888
+ advice.length
1889
+ ? h(
1890
+ 'ul',
1891
+ { className: 'sev-advice' },
1892
+ advice.map((raw, index) => {
1893
+ const item = adviceView(raw, lang)
1894
+ return h(
1895
+ 'li',
1896
+ { key: item.id || String(index), style: { borderLeftColor: severityColor(item.severity) } },
1897
+ h(
1898
+ 'b',
1899
+ null,
1900
+ (item.severity === 'critical' ? '🛑 ' : item.severity === 'warning' ? '⚠️ ' : 'ℹ️ ') + item.title,
1901
+ ),
1902
+ h('span', null, item.evidence),
1903
+ h('em', null, '↳ ' + item.fix),
1904
+ )
1905
+ }),
1906
+ )
1907
+ : h('div', { className: 'sev-meta' }, t.noAdvice),
1908
+ )
1909
+ })
1910
+
1911
+ function DataTable(props) {
1912
+ const { head, rows, empty, variant } = props
1913
+ if (rows.length === 0) return h('div', { className: 'sev-empty' }, empty)
1914
+ return h(
1915
+ 'div',
1916
+ { className: 'sev-table' + (variant ? ' sev-table--' + variant : '') },
1917
+ h(
1918
+ 'div',
1919
+ { className: 'sev-tr sev-th' },
1920
+ head.map((label) => h('span', { key: label }, label)),
1921
+ ),
1922
+ rows.map((cells, index) =>
1923
+ h(
1924
+ 'div',
1925
+ { className: 'sev-tr', key: String(index) },
1926
+ cells.map((cell, cellIndex) =>
1927
+ h('span', { key: String(cellIndex), className: cellIndex === 0 ? 'sev-strong' : undefined }, cell),
1928
+ ),
1929
+ ),
1930
+ ),
1931
+ )
1932
+ }
1933
+
1934
+ function RunsView(props) {
1935
+ const t = props.t
1936
+ const runs = props.data && Array.isArray(props.data.runs) ? props.data.runs : []
1937
+ return h(
1938
+ React.Fragment,
1939
+ null,
1940
+ h(SessionActivityChart, { runs, t, solo: true }),
1941
+ h(DataTable, {
1942
+ head: t.runsHead,
1943
+ empty: t.emptyRuns,
1944
+ rows: runs
1945
+ .slice(0, 12)
1946
+ .map((run) => [
1947
+ String(run.sessionId || '').slice(-8),
1948
+ h(
1949
+ 'b',
1950
+ { style: { color: scoreColor(run.score && run.score.total) } },
1951
+ fmt(run.score && run.score.total) +
1952
+ ' ' +
1953
+ ((run.score && run.score.grade) || '') +
1954
+ (run.score && run.score.ci ? ' [' + fmt(run.score.ci.low) + '–' + fmt(run.score.ci.high) + ']' : ''),
1955
+ ),
1956
+ String(run.loads || 0),
1957
+ String(run.toolCalls || 0),
1958
+ String(run.errors || 0),
1959
+ ]),
1960
+ }),
1961
+ )
1962
+ }
1963
+
1964
+ function McpView(props) {
1965
+ const t = props.t
1966
+ const lang = props.lang || 'zh'
1967
+ const data = props.data || {}
1968
+ const servers = Array.isArray(data.mcpServers) ? data.mcpServers : []
1969
+ const advice = (Array.isArray(data.mcpAdvice) ? data.mcpAdvice : []).slice(0, 6)
1970
+ const failing = []
1971
+ for (const row of servers) {
1972
+ for (const tool of row.tools || []) {
1973
+ if ((tool.errors || 0) > 0) failing.push({ server: row.server, ...tool })
1974
+ }
1975
+ }
1976
+ const calls = servers.reduce((total, row) => total + (row.calls || 0), 0)
1977
+ const errors = servers.reduce((total, row) => total + (row.errors || 0), 0)
1978
+ // With nothing recorded, a chart card plus an empty table card reads as two
1979
+ // broken panels; one honest empty card is the whole state.
1980
+ if (servers.length === 0 || calls === 0) {
1981
+ return h(
1982
+ 'div',
1983
+ { className: 'sev-card' },
1984
+ h('header', { className: 'sev-card-head' }, h('b', null, t.tabs.mcp)),
1985
+ h('div', { className: 'sev-empty' }, t.emptyMcp),
1986
+ )
1987
+ }
1988
+ const latency = (row) =>
1989
+ row.p50Ms === null || row.p50Ms === undefined
1990
+ ? '—'
1991
+ : fmtMs(row.p50Ms) + ' / ' + (row.p95Ms === null || row.p95Ms === undefined ? '—' : fmtMs(row.p95Ms))
1992
+ return h(
1993
+ React.Fragment,
1994
+ null,
1995
+ // No `solo` here: the chart card must line up with the table card below it,
1996
+ // and `.sev-chart--solo` caps the width at 560px.
1997
+ h(McpLatencyChart, {
1998
+ servers,
1999
+ t,
2000
+ thresholdMs: data.mcp && data.mcp.p95Ms,
2001
+ }),
2002
+ h(
2003
+ 'div',
2004
+ { className: 'sev-card' },
2005
+ h(
2006
+ 'header',
2007
+ { className: 'sev-card-head' },
2008
+ h('b', null, t.mcpHead[0]),
2009
+ h('span', null, servers.length + ' · ' + calls + ' ' + t.chartCalls + ' · ' + errors + ' ' + t.chartErrors),
2010
+ ),
2011
+ h(DataTable, {
2012
+ variant: 'mcp',
2013
+ head: t.mcpHead,
2014
+ empty: t.emptyMcp,
2015
+ rows: servers.map((row) => [
2016
+ row.server,
2017
+ h(
2018
+ 'span',
2019
+ { className: 'sev-health' },
2020
+ h('i', { className: 'sev-grade', style: { color: scoreColor(row.health) } }, row.grade || '—'),
2021
+ fmt(row.health),
2022
+ ),
2023
+ String(row.calls || 0),
2024
+ pct(row.errorRate),
2025
+ latency(row),
2026
+ ]),
2027
+ }),
2028
+ ),
2029
+ advice.length > 0
2030
+ ? h(
2031
+ 'div',
2032
+ { className: 'sev-card' },
2033
+ h('header', { className: 'sev-card-head' }, h('b', null, t.mcpFix)),
2034
+ h(
2035
+ 'div',
2036
+ { className: 'sev-advice-list' },
2037
+ advice.map((raw, index) => {
2038
+ const item = adviceView(raw, lang)
2039
+ return h(
2040
+ 'div',
2041
+ { className: 'sev-advice-row', key: item.id + '-' + index },
2042
+ h(
2043
+ 'b',
2044
+ { style: { color: severityColor(item.severity) } },
2045
+ (item.severity === 'critical' ? '🛑 ' : item.severity === 'warning' ? '⚠️ ' : 'ℹ️ ') + item.title,
2046
+ ),
2047
+ h('em', null, '↳ ' + item.fix),
2048
+ )
2049
+ }),
2050
+ ),
2051
+ )
2052
+ : null,
2053
+ failing.length > 0
2054
+ ? h(
2055
+ 'div',
2056
+ { className: 'sev-card' },
2057
+ h('header', { className: 'sev-card-head' }, h('b', null, t.mcpFailing)),
2058
+ h(
2059
+ 'div',
2060
+ { className: 'sev-advice-list' },
2061
+ failing
2062
+ .slice(0, 8)
2063
+ .map((tool) =>
2064
+ h(
2065
+ 'div',
2066
+ { className: 'sev-sub-row', key: tool.server + '/' + tool.tool },
2067
+ h('span', null, tool.server + '/' + tool.tool),
2068
+ h('b', null, (tool.errors || 0) + '/' + (tool.calls || 0)),
2069
+ ),
2070
+ ),
2071
+ ),
2072
+ )
2073
+ : null,
2074
+ )
2075
+ }
2076
+
2077
+ function DevView(props) {
2078
+ const t = props.t
2079
+ const data = props.data || {}
2080
+ const scoring = data.scoring || {}
2081
+ const totals = data.totals || {}
2082
+ const weights = scoring.weightsPercent || {}
2083
+ const th = scoring.thresholds || {}
2084
+ const dev = data.dev || {}
2085
+ const rows = [
2086
+ [
2087
+ t.devLabels.weights,
2088
+ ['static', 'reliability', 'effectiveness', 'efficiency']
2089
+ .map((key) => key + ' ' + (weights[key] ?? '—'))
2090
+ .join(' · '),
2091
+ ],
2092
+ [
2093
+ t.devLabels.thresholds,
2094
+ 'A≥' + (th.excellent ?? '—') + ' · B≥' + (th.good ?? '—') + ' · C≥' + (th.pass ?? '—') + ' · D≥60',
2095
+ ],
2096
+ [t.devLabels.minSamples, String(scoring.minSamples ?? '—')],
2097
+ [
2098
+ t.devLabels.totals,
2099
+ (totals.invocations ?? 0) +
2100
+ ' ' +
2101
+ t.devLoads +
2102
+ ' · ' +
2103
+ (totals.closed ?? 0) +
2104
+ ' ' +
2105
+ t.devClosed +
2106
+ ' · ' +
2107
+ (totals.open ?? 0) +
2108
+ ' ' +
2109
+ t.devOpen,
2110
+ ],
2111
+ [t.devLabels.dataDir, data.dataDir || '—'],
2112
+ [t.devLabels.api, DATA_URL],
2113
+ [
2114
+ t.devLabels.module,
2115
+ (dev.moduleVersion ?? '—') + ' / ' + (dev.diskVersion ?? '—') + (dev.skew ? ' ⚠ ' + t.devLabels.skew : ''),
2116
+ ],
2117
+ [t.devLabels.routes, String(dev.routes ?? '—') + ' · ' + t.devLabels.tools + ' ' + String(dev.tools ?? '—')],
2118
+ [t.devLabels.settingsFile, dev.settingsFile || '—'],
2119
+ [t.devLabels.warnings, String(dev.warnings ?? 0)],
2120
+ [t.devLabels.inspect, dev.inspectProvider ? t.devLabels.ok : '—'],
2121
+ [t.devLabels.store, totals.storeError ? String(totals.storeError) : t.devLabels.ok],
2122
+ [t.version, DATA_VERSION],
2123
+ ]
2124
+ return h(
2125
+ 'div',
2126
+ { className: 'sev-kv' },
2127
+ rows.map(([label, value]) =>
2128
+ h('div', { className: 'sev-kv-row', key: label }, h('span', null, label), h('b', null, String(value))),
2129
+ ),
2130
+ )
2131
+ }
2132
+
2133
+ // client/08-turn.js
2134
+ function scoreOf(data, skill) {
2135
+ const entry = ((data && data.skills) || []).find((item) => item.skill === skill)
2136
+ return entry ? entry.score || {} : null
2137
+ }
2138
+
2139
+ /**
2140
+ * The completed-turn strip: it reads the durable per-turn skill loads from
2141
+ * the report and renders only under turns that actually loaded a skill.
2142
+ */
2143
+ // The slot owner supplies `useChat` as a prop. Split it into two wrapper
2144
+ // components so the hook is never called conditionally: React compares the
2145
+ // returned element type, so a host that stops passing the hook remounts the
2146
+ // plain wrapper instead of changing this component's hook count.
2147
+ function TurnSkillCard(props) {
2148
+ return typeof props.useChat === 'function' ? h(TurnSkillCardWithChat, props) : h(TurnSkillCardPlain, { ...props })
2149
+ }
2150
+
2151
+ function TurnSkillCardWithChat(props) {
2152
+ const nodesSnapshot = props.useChat((snapshot) => snapshot.nodes)
2153
+ return h(TurnSkillCardBody, { ...props, nodesSnapshot })
2154
+ }
2155
+
2156
+ function TurnSkillCardPlain(props) {
2157
+ return h(TurnSkillCardBody, props)
2158
+ }
2159
+
2160
+ function TurnSkillCardBody(props) {
2161
+ const { sessionId, turn, nodesSnapshot } = props
2162
+ const { lang, t } = useLang()
2163
+ const state = useStore()
2164
+
2165
+ const retryRef = useRef({ key: '', count: 0 })
2166
+ useEffect(() => {
2167
+ ensureReport()
2168
+ }, [sessionId, turn && turn.turn])
2169
+ // ensureReport() has a 10 s warm-cache window; a turn that settles inside it
2170
+ // has no turnLoads row yet and would render nothing forever. Retry twice.
2171
+ useEffect(() => {
2172
+ const turnNumber =
2173
+ typeof turn?.turn === 'number' ? turn.turn : typeof turn?.number === 'number' ? turn.number : null
2174
+ if (turnNumber === null) return undefined
2175
+ const data = state.data
2176
+ if (!data || !Array.isArray(data.turnLoads)) return undefined
2177
+ if (data.turnLoads.some((row) => row.sessionId === sessionId && row.turn === turnNumber)) return undefined
2178
+ const key = sessionId + ':' + turnNumber
2179
+ if (retryRef.current.key !== key) retryRef.current = { key, count: 0 }
2180
+ if (retryRef.current.count >= 2) return undefined
2181
+ retryRef.current.count += 1
2182
+ const timer = setTimeout(() => load(), 1200)
2183
+ return () => clearTimeout(timer)
2184
+ }, [sessionId, turn, state.data, state.fetchedAt])
2185
+
2186
+ if (!turn) return null
2187
+ // `status` is 'closed' on current hosts; older/other builds may omit it or
2188
+ // use a different word, so only a clearly in-flight turn is skipped.
2189
+ const status = typeof turn.status === 'string' ? turn.status.toLowerCase() : ''
2190
+ if (status && /run|stream|pending|activ|progress/.test(status)) return null
2191
+ const turnNumber =
2192
+ typeof turn.turn === 'number'
2193
+ ? turn.turn
2194
+ : typeof turn.number === 'number'
2195
+ ? turn.number
2196
+ : typeof turn.index === 'number'
2197
+ ? turn.index
2198
+ : null
2199
+ if (turnNumber === null) return null
2200
+ const data = state.data
2201
+ const rows = ((data && data.turnLoads) || []).filter((row) => row.sessionId === sessionId && row.turn === turnNumber)
2202
+ if (rows.length === 0) return null
2203
+
2204
+ let toolCalls = null
2205
+ let errors = null
2206
+ if (nodesSnapshot && typeof nodesSnapshot.values === 'function') {
2207
+ const inTurn = [...nodesSnapshot.values()].filter(
2208
+ (node) => node && node.location && node.location.turn && node.location.turn.turn === turnNumber,
2209
+ )
2210
+ toolCalls = inTurn.filter((node) => node.kind === 'tool-call').length
2211
+ // DSH's tool-call node payload is ToolChatData { root: ToolCallBlock }; the
2212
+ // error flag lives on the settled root block, not on data.isError.
2213
+ errors = inTurn.filter((node) => node?.kind === 'tool-call' && node.data?.root?.isError === true).length
2214
+ }
2215
+
2216
+ const skills = [...new Set(rows.flatMap((row) => row.skills))]
2217
+ const skillEntries = ((data && data.skills) || []).filter((entry) => skills.includes(entry.skill))
2218
+ // One next fix per loaded skill: a turn can load several skills, and the
2219
+ // strip should surface each skill's own next move instead of a single
2220
+ // global winner. Cap at three so the strip stays readable.
2221
+ const nextSteps = skillEntries
2222
+ .map((entry) => {
2223
+ const first = (entry.advice || [])
2224
+ .filter((item) => item.severity === 'critical' || item.severity === 'warning')
2225
+ .sort((a, b) => (a.severity === 'critical' ? 0 : 1) - (b.severity === 'critical' ? 0 : 1))[0]
2226
+ return first ? { ...adviceView(first, lang), skill: entry.skill } : null
2227
+ })
2228
+ .filter(Boolean)
2229
+ .slice(0, 3)
2230
+ return h(
2231
+ React.Fragment,
2232
+ null,
2233
+ h('style', { key: 'sev-turn-style' }, TURN_STYLES),
2234
+ h(
2235
+ 'div',
2236
+ { className: 'sev-turn' },
2237
+ h('span', { className: 'sev-turn-label' }, t.turnLabel),
2238
+ ...skills.map((skill) => {
2239
+ const score = scoreOf(data, skill)
2240
+ return h(
2241
+ 'span',
2242
+ { className: 'sev-turn-chip', key: skill },
2243
+ h('b', null, skill),
2244
+ score && typeof score.total === 'number'
2245
+ ? h('i', { style: { color: scoreColor(score.total) } }, fmt(score.total) + ' ' + (score.grade || ''))
2246
+ : null,
2247
+ )
2248
+ }),
2249
+ toolCalls !== null
2250
+ ? h(
2251
+ 'span',
2252
+ { className: 'sev-turn-meta' },
2253
+ toolCalls + ' ' + t.turnCalls + (errors ? ' · ' + errors + ' ' + t.turnErrors : ''),
2254
+ )
2255
+ : null,
2256
+ ...nextSteps.map((nextStep) =>
2257
+ h(
2258
+ 'span',
2259
+ { className: 'sev-turn-next', key: 'next-' + nextStep.skill },
2260
+ t.turnNext + ' ',
2261
+ h('b', null, nextStep.skill),
2262
+ ' · ' + (t.dims[nextStep.dimension] || nextStep.dimension || 'static') + ' · ' + nextStep.title,
2263
+ ),
2264
+ ),
2265
+ h(
2266
+ 'details',
2267
+ { className: 'sev-turn-detail' },
2268
+ h('summary', null, t.turnDetail),
2269
+ ...skills.map((skill) => {
2270
+ const entry = ((data && data.skills) || []).find((item) => item.skill === skill)
2271
+ const advice = ((entry && entry.advice) || []).slice(0, 3)
2272
+ const history = ((data && data.edits) || []).filter((edit) => edit.skill === skill).slice(0, 3)
2273
+ return h(
2274
+ 'div',
2275
+ { className: 'sev-turn-advice', key: 'advice-' + skill },
2276
+ h('b', null, skill),
2277
+ advice.length === 0
2278
+ ? h('span', null, t.noTurnAdvice)
2279
+ : advice.map((raw, index) => {
2280
+ const item = adviceView(raw, lang)
2281
+ return h(
2282
+ 'span',
2283
+ { key: item.id || String(index) },
2284
+ (item.severity === 'critical' ? '🛑 ' : item.severity === 'warning' ? '⚠️ ' : 'ℹ️ ') + item.title,
2285
+ )
2286
+ }),
2287
+ history.length > 0
2288
+ ? h(
2289
+ 'div',
2290
+ { className: 'sev-turn-history', key: 'history-' + skill },
2291
+ h('span', null, t.turnHistory + ' '),
2292
+ ...history.map((edit, index) =>
2293
+ h(
2294
+ 'span',
2295
+ { key: (edit.at || '') + '-' + index },
2296
+ (edit.verdict === 'accept' ? '✅ ' : edit.verdict === 'reject' ? '🚫 ' : '⚠️ ') +
2297
+ (edit.dimension || 'static') +
2298
+ (edit.hypothesis ? ' · ' + String(edit.hypothesis).slice(0, 60) : ''),
2299
+ ),
2300
+ ),
2301
+ )
2302
+ : null,
2303
+ )
2304
+ }),
2305
+ ),
2306
+ ),
2307
+ )
2308
+ }
2309
+
2310
+ const TURN_STYLES = [
2311
+ '.sev-turn{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:8px 0 2px;padding:7px 10px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:10px;background:var(--dsw-alias-bg-layer-1, #ffffff);font-size:11.5px;color:var(--dsw-alias-label-secondary, #71717a)}',
2312
+ '.sev-turn-label{font-weight:600;color:var(--dsw-alias-label-primary, #18181b)}',
2313
+ '.sev-turn-chip{display:inline-flex;align-items:center;gap:5px;padding:2px 8px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:999px;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2314
+ '.sev-turn-chip b{font-weight:600;color:var(--dsw-alias-label-primary, #18181b)}',
2315
+ '.sev-turn-chip i{font-style:normal;font-variant-numeric:tabular-nums}',
2316
+ '.sev-turn-meta{font-variant-numeric:tabular-nums}',
2317
+ '.sev-turn-next{display:inline-flex;align-items:center;gap:4px;padding:2px 7px;border-radius:999px;background:var(--dsw-alias-bg-layer-2, #f4f4f5);color:var(--dsw-alias-label-secondary, #52525b);max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
2318
+ '.sev-turn-next b{font-weight:600;color:var(--dsw-alias-label-primary, #18181b)}',
2319
+ '.sev-turn-history{display:flex;flex-direction:column;gap:2px;margin-top:4px;padding-top:4px;border-top:1px dashed var(--dsw-alias-border-l1, #e4e4e7)}',
2320
+ '.sev-turn-history span{opacity:.85}',
2321
+ '.sev-settings{display:flex;flex-direction:column;gap:14px;padding:4px 0;font-size:12px;max-width:760px}',
2322
+ '.sev-settings-group h4{margin:12px 0 2px;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary, #71717a)}',
2323
+ '.sev-settings-row{display:grid;grid-template-columns:minmax(220px,1fr) auto;align-items:center;gap:14px;padding:9px 0;border-bottom:1px solid var(--dsw-alias-border-l1, #f0f0f2)}',
2324
+ '.sev-settings-label{display:flex;flex-direction:column;gap:2px}',
2325
+ '.sev-settings-label small{font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2326
+ '.sev-settings-control{display:flex;align-items:center;gap:6px;justify-content:flex-end}',
2327
+ '.sev-settings-control em{font-style:normal;font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2328
+ '.sev-settings-row input[type=number]{width:120px;padding:5px 8px;border:1px solid var(--dsw-alias-border-l1, #d4d4d8);border-radius:7px;font:inherit;background:transparent;color:inherit;text-align:right}',
2329
+ '.sev-switch{position:relative;display:inline-flex;align-items:center;cursor:pointer}',
2330
+ '.sev-switch input{position:absolute;opacity:0;width:1px;height:1px}',
2331
+ '.sev-switch i{display:block;width:34px;height:20px;border-radius:999px;background:var(--dsw-alias-border-l2, #d4d4d8);transition:background .15s}',
2332
+ '.sev-switch i::after{content:"";display:block;width:16px;height:16px;margin:2px;border-radius:50%;background:#fff;transition:transform .15s}',
2333
+ '.sev-switch input:checked + i{background:var(--dsw-alias-brand-primary, #4d6bfe)}',
2334
+ '.sev-switch input:checked + i::after{transform:translateX(14px)}',
2335
+ '.sev-switch input:focus-visible + i{outline:2px solid var(--dsw-alias-brand-primary, #4d6bfe);outline-offset:2px}',
2336
+ '.sev-settings-actions{display:flex;gap:8px}',
2337
+ '.sev-settings-status{color:#16a34a;font-size:11.5px}',
2338
+ '.sev-settings-status.sev-error{color:#c92a2a}',
2339
+ '.sev-settings-heading{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary, #18181b);margin-bottom:2px}',
2340
+ '.sev-turn-detail{flex-basis:100%;width:100%;margin:6px 0 0;padding-top:6px;border-top:1px dashed var(--dsw-alias-border-l1, #e4e4e7)}',
2341
+ '.sev-turn-detail summary{cursor:pointer;color:var(--dsw-alias-brand-primary, #4d6bfe);font-weight:500}',
2342
+ '.sev-turn-detail[open] summary{margin-bottom:4px}',
2343
+ '.sev-turn-advice{display:grid;gap:3px;margin:6px 0 0;padding:6px 9px;border-left:2px solid var(--dsw-alias-border-l2, #d4d4d8);border-radius:0 8px 8px 0;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2344
+ '.sev-turn-advice + .sev-turn-advice{margin-top:8px}',
2345
+ '.sev-turn-advice b{display:block;margin-bottom:2px;color:var(--dsw-alias-label-primary, #18181b)}',
2346
+ ].join('\n')
2347
+
2348
+ // client/09-overlay.js
2349
+ function ReportOverlay() {
2350
+ const state = useStore()
2351
+ const { lang, t } = useLang()
2352
+ const [copyState, setCopyState] = useState('idle')
2353
+ const copyTimer = useRef(null)
2354
+ const mounted = useRef(true)
2355
+ const dialogRef = useRef(null)
2356
+ const openerRef = useRef(null)
2357
+
2358
+ // Restore keyboard focus to whatever opened the popup, and keep Tab inside
2359
+ // the dialog while it is open (it declares aria-modal, so focus must not
2360
+ // wander behind the backdrop).
2361
+ useEffect(() => {
2362
+ if (!state.open) return undefined
2363
+ openerRef.current = typeof document !== 'undefined' ? document.activeElement : null
2364
+ return () => {
2365
+ const opener = openerRef.current
2366
+ openerRef.current = null
2367
+ if (opener && typeof opener.focus === 'function') {
2368
+ try {
2369
+ opener.focus()
2370
+ } catch {
2371
+ // the opener may have unmounted
2372
+ }
2373
+ }
2374
+ }
2375
+ }, [state.open])
2376
+
2377
+ const trapTab = (event) => {
2378
+ if (event.key !== 'Tab') return
2379
+ const root = dialogRef.current
2380
+ if (!root) return
2381
+ const nodes = [
2382
+ ...root.querySelectorAll('button,[href],input,select,textarea,[tabindex]:not([tabindex="-1"])'),
2383
+ ].filter((node) => !node.disabled && node.offsetParent !== null)
2384
+ if (nodes.length === 0) return
2385
+ const first = nodes[0]
2386
+ const last = nodes[nodes.length - 1]
2387
+ if (event.shiftKey && document.activeElement === first) {
2388
+ event.preventDefault()
2389
+ last.focus()
2390
+ } else if (!event.shiftKey && document.activeElement === last) {
2391
+ event.preventDefault()
2392
+ first.focus()
2393
+ }
2394
+ }
2395
+
2396
+ useEffect(() => {
2397
+ if (!state.open) return undefined
2398
+ const onKey = (event) => {
2399
+ if (event.key === 'Escape') closeReport()
2400
+ }
2401
+ window.addEventListener('keydown', onKey)
2402
+ // Keep the numbers moving while a run is in progress. Windows only land
2403
+ // at turn end, so a live view shows new loads immediately and their
2404
+ // statistics right after the turn settles.
2405
+ const timer = setInterval(() => {
2406
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
2407
+ load()
2408
+ }, REFRESH_MS)
2409
+ return () => {
2410
+ window.removeEventListener('keydown', onKey)
2411
+ clearInterval(timer)
2412
+ }
2413
+ }, [state.open])
2414
+
2415
+ useEffect(
2416
+ () => () => {
2417
+ mounted.current = false
2418
+ if (copyTimer.current) clearTimeout(copyTimer.current)
2419
+ },
2420
+ [],
2421
+ )
2422
+
2423
+ const copy = async () => {
2424
+ const text = buildMarkdown(state.data)
2425
+ const ok = await copyText(text)
2426
+ if (!mounted.current) return
2427
+ setCopyState(ok ? 'copied' : 'failed')
2428
+ if (copyTimer.current) clearTimeout(copyTimer.current)
2429
+ copyTimer.current = setTimeout(() => setCopyState('idle'), 1500)
2430
+ }
2431
+
2432
+ const data = state.data
2433
+ const skills = data && Array.isArray(data.skills) ? data.skills : []
2434
+ const totals = (data && data.totals) || {}
2435
+
2436
+ return h(
2437
+ React.Fragment,
2438
+ null,
2439
+ h('style', { key: 'sev-style' }, STYLES),
2440
+ state.open
2441
+ ? h(
2442
+ 'div',
2443
+ {
2444
+ className: 'sev-backdrop',
2445
+ role: 'presentation',
2446
+ onMouseDown: (event) => {
2447
+ if (event.target === event.currentTarget) closeReport()
2448
+ },
2449
+ },
2450
+ h(
2451
+ 'div',
2452
+ {
2453
+ className: 'sev-dialog',
2454
+ role: 'dialog',
2455
+ 'aria-modal': 'true',
2456
+ 'aria-label': t.title,
2457
+ ref: dialogRef,
2458
+ onKeyDown: trapTab,
2459
+ },
2460
+ h(
2461
+ 'header',
2462
+ { className: 'sev-head' },
2463
+ h(
2464
+ 'div',
2465
+ { className: 'sev-head-text' },
2466
+ h('div', { className: 'sev-title' }, t.title),
2467
+ h('div', { className: 'sev-sub' }, t.subtitle),
2468
+ h(
2469
+ 'div',
2470
+ { className: 'sev-tabs', role: 'tablist' },
2471
+ ['skills', 'steps', 'runs', 'mcp', 'dev'].map((view) =>
2472
+ h(
2473
+ 'button',
2474
+ {
2475
+ key: view,
2476
+ type: 'button',
2477
+ role: 'tab',
2478
+ id: 'sev-overlay-tab-' + view,
2479
+ 'aria-controls': 'sev-overlay-view',
2480
+ 'aria-selected': state.view === view,
2481
+ tabIndex: state.view === view ? 0 : -1,
2482
+ className: 'sev-tab' + (state.view === view ? ' sev-tab--on' : ''),
2483
+ onClick: () => setView(view),
2484
+ onKeyDown: (event) => {
2485
+ if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return
2486
+ event.preventDefault()
2487
+ const views = ['skills', 'steps', 'runs', 'mcp', 'dev']
2488
+ const index = views.indexOf(view)
2489
+ const next =
2490
+ views[(index + (event.key === 'ArrowRight' ? 1 : views.length - 1)) % views.length]
2491
+ setView(next)
2492
+ const target =
2493
+ typeof document !== 'undefined' ? document.getElementById('sev-overlay-tab-' + next) : null
2494
+ if (target) target.focus()
2495
+ },
2496
+ },
2497
+ t.tabs[view],
2498
+ ),
2499
+ ),
2500
+ ),
2501
+ ),
2502
+ h(
2503
+ 'div',
2504
+ { className: 'sev-head-actions' },
2505
+ h(
2506
+ 'button',
2507
+ { type: 'button', className: 'sev-btn', onClick: load, disabled: state.loading },
2508
+ t.refresh,
2509
+ ),
2510
+ h(
2511
+ 'button',
2512
+ { type: 'button', className: 'sev-btn', onClick: copy },
2513
+ h(
2514
+ 'span',
2515
+ { role: 'status', 'aria-live': 'polite' },
2516
+ copyState === 'copied' ? t.copied : copyState === 'failed' ? t.copyFailed : t.copy,
2517
+ ),
2518
+ ),
2519
+ h(
2520
+ 'button',
2521
+ {
2522
+ type: 'button',
2523
+ className: 'sev-btn sev-btn--icon',
2524
+ onClick: closeReport,
2525
+ 'aria-label': t.close,
2526
+ title: t.close,
2527
+ autoFocus: true,
2528
+ },
2529
+ '✕',
2530
+ ),
2531
+ ),
2532
+ ),
2533
+ h(
2534
+ 'div',
2535
+ {
2536
+ className: 'sev-body',
2537
+ role: 'tabpanel',
2538
+ id: 'sev-overlay-view',
2539
+ 'aria-labelledby': 'sev-overlay-tab-' + state.view,
2540
+ },
2541
+ state.loading && !data ? h('div', { className: 'sev-empty' }, t.loading) : null,
2542
+ data && !data.scoring
2543
+ ? h('div', { className: 'sev-stale' }, h('b', null, t.staleTitle), h('span', null, t.staleHint))
2544
+ : null,
2545
+ state.error
2546
+ ? h('div', { className: 'sev-error' }, t.failed + ': ' + state.error + ' — ' + DATA_URL)
2547
+ : null,
2548
+ state.view === 'skills'
2549
+ ? data && data.ranking
2550
+ ? h(
2551
+ 'div',
2552
+ { className: 'sev-note' },
2553
+ lang === 'zh' && data.ranking.noteZh ? data.ranking.noteZh : data.ranking.note,
2554
+ )
2555
+ : null
2556
+ : null,
2557
+ state.view === 'skills'
2558
+ ? !state.loading && !state.error && skills.length === 0
2559
+ ? h('div', { className: 'sev-empty' }, t.empty)
2560
+ : skills.map((skill) =>
2561
+ h(SkillCard, {
2562
+ key: skill.skill,
2563
+ skill,
2564
+ t,
2565
+ lang,
2566
+ onTrace: (name) => store.set((current) => ({ ...current, view: 'steps', stepFilter: name })),
2567
+ }),
2568
+ )
2569
+ : state.view === 'steps'
2570
+ ? h(StepsView, {
2571
+ data,
2572
+ t,
2573
+ filter: state.stepFilter || '',
2574
+ onFilter: (name) => store.set((current) => ({ ...current, stepFilter: name })),
2575
+ })
2576
+ : state.view === 'runs'
2577
+ ? h(RunsView, { data, t })
2578
+ : state.view === 'mcp'
2579
+ ? h(McpView, { data, t, lang })
2580
+ : h(DevView, { data, t }),
2581
+ ),
2582
+ h(
2583
+ 'footer',
2584
+ { className: 'sev-foot' },
2585
+ h(
2586
+ 'span',
2587
+ null,
2588
+ (totals.invocations || 0) + ' ' + t.loads + ' · ' + (totals.skills || 0) + ' ' + t.skillsWord,
2589
+ ),
2590
+ h(
2591
+ 'span',
2592
+ { className: 'sev-foot-hint' },
2593
+ (data && data.scoring
2594
+ ? Object.entries(data.scoring.weightsPercent || {})
2595
+ .map(([key, value]) => key + ' ' + value)
2596
+ .join('/') +
2597
+ ' · A≥' +
2598
+ ((data.scoring.thresholds || {}).excellent ?? 90) +
2599
+ ' — '
2600
+ : '') +
2601
+ t.footerHint +
2602
+ ' · ' +
2603
+ t.auto,
2604
+ ),
2605
+ h('span', { className: 'sev-foot-dir' }, (data && data.dataDir) || ''),
2606
+ ),
2607
+ ),
2608
+ )
2609
+ : null,
2610
+ )
2611
+ }
2612
+
2613
+ // client/10-styles.js
2614
+ const STYLES = [
2615
+ '.sev-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:30px;padding:0 10px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:9px;background:var(--dsw-alias-bg-layer-1, #ffffff);color:var(--dsw-alias-label-secondary, #71717a);font-size:12px;line-height:1;cursor:pointer;white-space:nowrap;font-family:inherit}',
2616
+ '.sev-btn:hover{color:var(--dsw-alias-label-primary, #18181b);border-color:var(--dsw-alias-border-l2, #d4d4d8)}',
2617
+ '.sev-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary, #4d6bfe);outline-offset:1px}',
2618
+ '.sev-btn--icon{width:30px;padding:0}',
2619
+ '.sev-btn--ghost{background:transparent}',
2620
+ '.sev-backdrop{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:28px;background:rgba(9,9,11,.44);pointer-events:auto}',
2621
+ '.sev-dialog{display:flex;flex-direction:column;width:min(780px,94vw);max-height:84vh;overflow:hidden;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:16px;background:var(--dsw-alias-bg-overlay, #ffffff);color:var(--dsw-alias-label-primary, #18181b);box-shadow:0 26px 70px rgba(0,0,0,.34);font-size:13px;line-height:1.5}',
2622
+ '.sev-head{display:flex;align-items:flex-start;gap:12px;padding:16px 18px 12px;border-bottom:1px solid var(--dsw-alias-border-l1, #e4e4e7)}',
2623
+ '.sev-head-text{flex:1;min-width:0}',
2624
+ '.sev-title{font-size:15px;font-weight:600}',
2625
+ '.sev-sub{margin-top:3px;color:var(--dsw-alias-label-secondary, #71717a);font-size:11.5px;line-height:1.45}',
2626
+ '.sev-head-actions{display:flex;gap:6px;flex:none}',
2627
+ '.sev-body{flex:1;overflow:auto;padding:14px 18px 18px;display:flex;flex-direction:column;gap:12px}',
2628
+ '.sev-empty{padding:26px 0;text-align:center;color:var(--dsw-alias-label-secondary, #71717a)}',
2629
+ '.sev-error{margin:0;padding:10px 12px;border-radius:10px;border:1px solid var(--dsw-alias-state-error-primary, #c92a2a);color:var(--dsw-alias-state-error-primary, #c92a2a);font-size:12px;word-break:break-all}',
2630
+ '.sev-card{border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:12px;background:var(--dsw-alias-bg-layer-1, #ffffff);padding:12px 14px}',
2631
+ '.sev-card-head{display:flex;align-items:baseline;gap:10px}',
2632
+ '.sev-name{flex:1;font-weight:600;font-size:13.5px;word-break:break-word}',
2633
+ '.sev-grade{font-weight:700;font-size:17px;font-variant-numeric:tabular-nums}',
2634
+ '.sev-total{font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}',
2635
+ '.sev-provisional{margin-top:2px;font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2636
+ '.sev-ci{margin-top:2px;font-size:11px;color:var(--dsw-alias-label-secondary, #71717a);font-variant-numeric:tabular-nums}',
2637
+ '.sev-note{margin-bottom:10px;padding:8px 10px;border-radius:9px;border:1px solid var(--dsw-alias-state-warn-primary, #d97706);color:var(--dsw-alias-label-primary, #18181b);font-size:11.5px;line-height:1.45}',
2638
+ '.sev-stale{display:grid;gap:3px;margin-bottom:10px;padding:10px 12px;border-radius:10px;border:1px solid var(--dsw-alias-state-error-primary, #c92a2a);background:var(--dsw-alias-bg-layer-1, #ffffff);font-size:11.5px;line-height:1.5}',
2639
+ '.sev-stale b{color:var(--dsw-alias-state-error-primary, #c92a2a);font-size:12px}',
2640
+ '.sev-stale span{color:var(--dsw-alias-label-secondary, #71717a)}',
2641
+ '.sev-dims{display:grid;gap:4px;margin:9px 0 8px}',
2642
+ '.sev-dim{display:grid;grid-template-columns:96px 1fr 40px;align-items:center;gap:8px}',
2643
+ '.sev-dim-label{font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2644
+ '.sev-dim-track{display:block;height:6px;border-radius:4px;background:var(--dsw-alias-bg-layer-2, #f4f4f5);overflow:hidden}',
2645
+ '.sev-dim-track i{display:block;height:100%;border-radius:4px;min-width:2px}',
2646
+ '.sev-dim b{font-size:11px;font-weight:600;text-align:right;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary, #71717a)}',
2647
+ '.sev-meta{font-size:11px;color:var(--dsw-alias-label-secondary, #71717a);font-variant-numeric:tabular-nums}',
2648
+ '.sev-advice{list-style:none;margin:9px 0 0;padding:0;display:grid;gap:7px}',
2649
+ '.sev-advice li{border-left:3px solid var(--dsw-alias-border-l2, #d4d4d8);padding-left:9px}',
2650
+ '.sev-advice b{display:block;font-size:12px;font-weight:600}',
2651
+ '.sev-advice span{display:block;font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2652
+ '.sev-advice em{display:block;margin-top:2px;font-size:11px;font-style:normal;color:var(--dsw-alias-label-primary, #18181b);opacity:.86}',
2653
+ '.sev-tabs{display:flex;gap:4px;margin-top:8px}',
2654
+ '.sev-tab{border:1px solid transparent;background:transparent;color:var(--dsw-alias-label-secondary, #71717a);font-size:12px;padding:3px 9px;border-radius:7px;cursor:pointer;font-family:inherit}',
2655
+ '.sev-tab:hover{color:var(--dsw-alias-label-primary, #18181b);background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2656
+ '.sev-tab--on{color:var(--dsw-alias-label-primary, #18181b);background:var(--dsw-alias-bg-layer-2, #f4f4f5);font-weight:600}',
2657
+ '.sev-table{display:grid;gap:2px;font-size:12px}',
2658
+ '.sev-kv{display:grid;gap:6px;font-size:12px}',
2659
+ // NOTE: '.sev-sub' belongs to the panel subtitle; the advice container used to
2660
+ // reuse that class and silently restyled the header. It is now its own class.
2661
+ '.sev-advice-list{display:grid;gap:4px;margin-top:8px;font-size:12px}',
2662
+ '.sev-sub-row{display:flex;justify-content:space-between;gap:10px;padding:4px 8px;border-radius:7px;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2663
+ '.sev-sub-row b{font-variant-numeric:tabular-nums;color:var(--dsw-alias-state-error-primary, #c92a2a)}',
2664
+ '.sev-advice-row{display:grid;gap:2px;padding:6px 8px;border-radius:7px;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2665
+ '.sev-card{border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:12px;padding:10px 12px;background:var(--dsw-alias-bg-layer-1, #fff);min-width:0}',
2666
+ '.sev-card-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:4px;font-size:12px}',
2667
+ '.sev-card-head b{font-weight:600}',
2668
+ '.sev-card-head span{color:var(--dsw-alias-label-secondary, #71717a);font-size:10.5px;font-variant-numeric:tabular-nums}',
2669
+ '.sev-table--mcp .sev-tr{grid-template-columns:1.5fr .8fr .5fr .6fr 1fr}',
2670
+ '.sev-health{display:inline-flex;align-items:center;gap:5px;font-variant-numeric:tabular-nums}',
2671
+ '.sev-grade{display:inline-flex;align-items:center;justify-content:center;min-width:16px;height:16px;padding:0 4px;border-radius:5px;font-style:normal;font-size:10px;font-weight:700;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2672
+ '.sev-lat{display:grid;gap:10px;padding:4px 0 2px}',
2673
+ '.sev-lat-row{display:grid;gap:4px}',
2674
+ '.sev-lat-head{display:flex;justify-content:space-between;gap:10px;font-size:11.5px}',
2675
+ '.sev-lat-head b{font-weight:600}',
2676
+ '.sev-lat-head span{color:var(--dsw-alias-label-secondary, #71717a);font-variant-numeric:tabular-nums}',
2677
+ '.sev-meter{position:relative;height:8px;border-radius:999px;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2678
+ '.sev-meter-fill{position:absolute;left:0;top:0;height:100%;border-radius:999px}',
2679
+ '.sev-meter-fill--p95{background:var(--dsw-alias-state-warn-primary, #d97706);opacity:.35}',
2680
+ '.sev-meter-fill--p50{background:var(--dsw-alias-brand-primary, #4d6bfe)}',
2681
+ '.sev-meter-threshold{position:absolute;top:-4px;bottom:-4px;width:0;border-left:1px dashed var(--dsw-alias-state-error-primary, #c92a2a);opacity:.75}',
2682
+ '.sev-advice-row b{font-size:12px;font-weight:600}',
2683
+ '.sev-advice-row em{font-style:normal;font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2684
+ '.sev-kv-row{display:grid;grid-template-columns:120px 1fr;gap:10px;padding:5px 8px;border-radius:7px;background:var(--dsw-alias-bg-layer-1, #ffffff)}',
2685
+ '.sev-kv-row span{color:var(--dsw-alias-label-secondary, #71717a);font-size:11px}',
2686
+ '.sev-kv-row b{font-weight:500;word-break:break-all;font-variant-numeric:tabular-nums}',
2687
+ '.sev-tr{display:grid;grid-template-columns:1.4fr .6fr .6fr .6fr .6fr;gap:8px;padding:6px 8px;border-radius:7px}',
2688
+ '.sev-tr:nth-child(odd){background:var(--dsw-alias-bg-layer-1, #ffffff)}',
2689
+ '.sev-th{color:var(--dsw-alias-label-secondary, #71717a);font-size:11px;text-transform:none}',
2690
+ '.sev-tr span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-variant-numeric:tabular-nums}',
2691
+ '.sev-strong{font-weight:600}',
2692
+ '.sev-foot{display:flex;align-items:center;gap:10px;padding:9px 18px;border-top:1px solid var(--dsw-alias-border-l1, #e4e4e7);font-size:11px;color:var(--dsw-alias-label-secondary, #71717a)}',
2693
+ '.sev-foot-hint{flex:1;text-align:center}',
2694
+ '.sev-foot-dir{max-width:36%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;direction:rtl}',
2695
+ '.sev-trace{padding:2px 7px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:999px;background:transparent;color:var(--dsw-alias-label-secondary, #71717a);font:inherit;font-size:10.5px;cursor:pointer;white-space:nowrap}',
2696
+ '.sev-trace:hover{color:var(--dsw-alias-brand-primary, #4d6bfe);border-color:var(--dsw-alias-brand-primary, #4d6bfe)}',
2697
+ '.sev-steps{display:flex;flex-direction:column;gap:12px}',
2698
+ '.sev-steps-kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}',
2699
+ '.sev-recent{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:8px 12px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:10px;font-size:11px}',
2700
+ '.sev-recent b{font-weight:600}',
2701
+ '.sev-recent-turn{display:flex;flex-direction:column;gap:3px;min-width:92px;font-size:10px;color:var(--dsw-alias-label-secondary, #71717a)}',
2702
+ '.sev-recent-turn i{display:block;height:5px;border-radius:3px;background:var(--dsw-alias-brand-primary, #4d6bfe)}',
2703
+ '.sev-recent-turn em{font-style:normal;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary, #18181b)}',
2704
+ '.sev-step-filters{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11px}',
2705
+ '.sev-step-formula{font-size:10.5px;color:var(--dsw-alias-label-secondary, #71717a)}',
2706
+ '.sev-turn{border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:12px;overflow:hidden;background:var(--dsw-alias-bg-layer-1, #fff)}',
2707
+ '.sev-turn-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:8px 12px;border-bottom:1px solid var(--dsw-alias-border-l1, #e4e4e7);font-size:11.5px;background:var(--dsw-alias-bg-layer-2, #f4f4f5)}',
2708
+ '.sev-turn-meta{flex:1;min-width:120px;font-size:10.5px;color:var(--dsw-alias-label-secondary, #71717a)}',
2709
+ '.sev-turn-avg{font-weight:600;font-variant-numeric:tabular-nums}',
2710
+ '.sev-turn-delta,.sev-step-delta{font-size:10.5px;font-variant-numeric:tabular-nums}',
2711
+ '.sev-step-delta--up{color:#2f9e44}',
2712
+ '.sev-step-delta--down{color:#c92a2a}',
2713
+ '.sev-step-delta--flat{color:var(--dsw-alias-label-secondary, #71717a)}',
2714
+ '.sev-steplist{list-style:none;margin:0;padding:2px 0;display:grid}',
2715
+ '.sev-step{display:flex;align-items:center;gap:10px;padding:5px 12px}',
2716
+ '.sev-step:nth-child(odd){background:color-mix(in srgb, var(--dsw-alias-bg-layer-2, #f4f4f5) 55%, transparent)}',
2717
+ '.sev-step-score{flex:none;width:44px;height:26px;display:inline-flex;align-items:center;justify-content:center;border:1px solid;border-radius:7px;font-weight:700;font-size:12px;font-variant-numeric:tabular-nums}',
2718
+ '.sev-step-main{flex:1;min-width:0}',
2719
+ '.sev-step-title{display:flex;align-items:center;gap:8px;font-size:11.5px;flex-wrap:wrap}',
2720
+ '.sev-step-sub{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:1px;font-size:10px;color:var(--dsw-alias-label-secondary, #71717a)}',
2721
+ '.sev-step-skill{padding:0 6px;border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:999px;background:transparent;color:inherit;font:inherit;font-size:9.5px;cursor:pointer}',
2722
+ '.sev-step-skill:hover{color:var(--dsw-alias-brand-primary, #4d6bfe);border-color:var(--dsw-alias-brand-primary, #4d6bfe)}',
2723
+ '.sev-step-err{color:#c92a2a}',
2724
+ '.sev-muted{color:var(--dsw-alias-label-secondary, #71717a)}',
2725
+ '.sev-charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}',
2726
+ '.sev-chart{border:1px solid var(--dsw-alias-border-l1, #e4e4e7);border-radius:12px;padding:10px 12px;background:var(--dsw-alias-bg-layer-1, #fff);min-width:0}',
2727
+ '.sev-chart-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:6px;font-size:12px}',
2728
+ '.sev-chart-head b{font-weight:600}',
2729
+ '.sev-chart-head span{color:var(--dsw-alias-label-secondary, #71717a);font-size:10.5px;font-variant-numeric:tabular-nums}',
2730
+ '.sev-chart-svg{display:block;width:100%;height:auto;color:var(--dsw-alias-label-secondary, #71717a);overflow:visible}',
2731
+ '.sev-chart-empty{padding:22px 0;text-align:center;color:var(--dsw-alias-label-secondary, #71717a);font-size:11px}',
2732
+ '.sev-chart--solo{max-width:560px}',
2733
+ '.sev-chart-legend{list-style:none;margin:0;padding:0;display:grid;gap:3px;font-size:10.5px;color:var(--dsw-alias-label-secondary, #71717a)}',
2734
+ '.sev-chart-legend li{display:flex;align-items:center;gap:5px}',
2735
+ '.sev-chart-legend i{width:8px;height:8px;border-radius:2px;display:inline-block;flex:none}',
2736
+ '.sev-chart-legend b{color:var(--dsw-alias-label-primary, #18181b);font-variant-numeric:tabular-nums}',
2737
+ '.sev-donut-wrap{display:flex;align-items:center;gap:12px}',
2738
+ '.sev-donut{width:84px;height:84px;flex:none}',
2739
+ '.sev-spark{width:64px;height:18px;flex:none;opacity:0.9}',
2740
+ '@media(max-width:720px){.sev-charts{grid-template-columns:1fr}}',
2741
+ ].join('\n')
2742
+
2743
+ // client/11-apply.js
2744
+ return {
2745
+ inject: ['slots', 'locale'],
2746
+ apply(ctx) {
2747
+ env.locale = ctx.locale
2748
+ ctx.slots.inject('conversation.chat.turnTail', () =>
2749
+ ctx.slots.register({ name: 'conversation.chat.turnTail', id: 'skill-eval-turn', order: 30 }, TurnSkillCard),
2750
+ )
2751
+ // Board: sidebar panel icon + the main panel it addresses (same pattern
2752
+ // as the context plugin). The icon label follows the page language.
2753
+ const panelLabel = () => {
2754
+ let active
2755
+ try {
2756
+ const snapshot = ctx.locale && typeof ctx.locale.getSnapshot === 'function' ? ctx.locale.getSnapshot() : null
2757
+ active = snapshot && snapshot.active ? String(snapshot.active) : ''
2758
+ } catch {
2759
+ // fall back to the browser language below
2760
+ }
2761
+ if (!active && typeof navigator !== 'undefined') active = String(navigator.language || '')
2762
+ return /^zh/i.test(active) ? '技能评测' : 'Skill eval'
2763
+ }
2764
+ ctx.slots.inject('sidebar.panellist', () =>
2765
+ ctx.slots.register({ name: 'sidebar.panellist', id: 'skill-eval', order: 40, label: panelLabel }, PanelIcon),
2766
+ )
2767
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: 'skill-eval' }, BoardPanel))
2768
+ // Two human entry points by design: the in-conversation strip (below)
2769
+ // and one board row in the session header's More menu. Settings live in
2770
+ // the plugin's own row config page, not a separate section.
2771
+ if (ENABLE_POPUP) {
2772
+ ctx.slots.inject('sidebar.footer.action', () =>
2773
+ ctx.slots.register(
2774
+ { name: 'sidebar.footer.action', id: 'skill-eval-open', order: 30, label: panelLabel },
2775
+ FooterAction,
2776
+ ),
2777
+ )
2778
+ ctx.slots.inject('shell.overlay', () =>
2779
+ ctx.slots.register({ name: 'shell.overlay', id: 'skill-eval-modal', order: 900 }, ReportOverlay),
2780
+ )
2781
+ }
2782
+ // Settings: the bundle's own config page (Settings → Plugins → this
2783
+ // bundle), keyed by the package name — the same seat the context plugin
2784
+ // uses for its settings.
2785
+ ctx.slots.inject('plugins.bundle.config', () =>
2786
+ ctx.slots.register({ name: 'plugins.bundle.config', key: 'dsh-skill-eval' }, RowConfig),
2787
+ )
2788
+ },
2789
+ }
2790
+ },
2791
+ })