@ssamurias/dsh-fish 1.0.8 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/AGENTS.md +368 -338
  2. package/CHANGELOG.md +113 -0
  3. package/README.md +377 -352
  4. package/RELEASE-NOTES-1.0.9.md +79 -0
  5. package/RELEASE-NOTES-1.1.0.md +55 -0
  6. package/docs//350/256/244/344/272/272/345/210/244/346/215/256.md +112 -0
  7. package/lib/appoint.js +106 -22
  8. package/lib/ask.js +2 -1
  9. package/lib/autobackup.js +4 -0
  10. package/lib/capture.js +16 -0
  11. package/lib/claim.js +103 -0
  12. package/lib/client/00-shell.js +630 -0
  13. package/lib/client/01-state-load.js +901 -0
  14. package/lib/client/02-actions.js +670 -0
  15. package/lib/client/03-widgets-header.js +721 -0
  16. package/lib/client/04-pressure-lab.js +891 -0
  17. package/lib/client/05-pressure-charts.js +431 -0
  18. package/lib/client/06-tab-status-grow.js +468 -0
  19. package/lib/client/07-tab-home-bili.js +610 -0
  20. package/lib/client/08-tab-memory-plugins.js +756 -0
  21. package/lib/client/09-tab-outing.js +710 -0
  22. package/lib/client/10-data-handlers.js +519 -0
  23. package/lib/client/11-tab-data-frame.js +749 -0
  24. package/lib/client/12-pressure-chip-mount.js +565 -0
  25. package/lib/client.js +477 -47
  26. package/lib/comment.js +18 -3
  27. package/lib/derive.js +262 -22
  28. package/lib/doing.js +31 -15
  29. package/lib/env.d.ts +224 -0
  30. package/lib/events.js +5 -2
  31. package/lib/guess.js +29 -0
  32. package/lib/health.js +75 -0
  33. package/lib/hear.js +67 -0
  34. package/lib/herpeople.js +159 -0
  35. package/lib/history.js +27 -5
  36. package/lib/home.js +12 -1
  37. package/lib/identity.js +23 -0
  38. package/lib/index.js +34 -18
  39. package/lib/look.js +3 -2
  40. package/lib/make.js +60 -12
  41. package/lib/markup.js +61 -23
  42. package/lib/observe-bili.js +334 -0
  43. package/lib/observe-config.js +223 -0
  44. package/lib/observe-data.js +522 -0
  45. package/lib/observe-home.js +384 -0
  46. package/lib/observe-http.js +250 -0
  47. package/lib/observe-outing.js +650 -0
  48. package/lib/observe-state.js +419 -0
  49. package/lib/observe-trip.js +286 -0
  50. package/lib/observe.js +99 -3574
  51. package/lib/people.js +514 -0
  52. package/lib/peopledoc.js +112 -0
  53. package/lib/persona.js +324 -42
  54. package/lib/restrict.js +74 -3
  55. package/lib/say.js +71 -1
  56. package/lib/scheduler.js +23 -3
  57. package/lib/schedules.js +97 -0
  58. package/lib/schema.js +11 -4
  59. package/lib/scrub.js +3 -3
  60. package/lib/selfdoc.js +19 -2
  61. package/lib/settings.js +112 -11
  62. package/lib/stance.js +47 -3
  63. package/lib/status.js +14 -5
  64. package/lib/sub.js +1 -1
  65. package/lib/tenant.js +35 -7
  66. package/lib/turns.js +51 -4
  67. package/lib/types.d.ts +515 -0
  68. package/lib/voices.js +3 -0
  69. package/lib/watch.js +1 -1
  70. package/lib/wiki.js +131 -25
  71. package/lib/works.js +120 -45
  72. package/package.json +1 -1
  73. package/scripts/build-client.mjs +83 -0
  74. package/scripts/sync-pressure-formulas.mjs +12 -15
@@ -0,0 +1,565 @@
1
+ // ---------------------------------------------------------------- 会话压力(对话页)
2
+ // 2026-11-17(用户 m02719):压力入口从设置页搬到对话页——会话头部一个小胶囊,
3
+ // 点开是迷你面板;另有「压力」页签放稍微完整一点的表。按工作区过滤由服务端做,
4
+ // 不是她这间房的会话返回 not-fish,这里什么都不渲染。
5
+ function pressureK(value) {
6
+ const n = Number(value)
7
+ if (!Number.isFinite(n)) return '—'
8
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
9
+ if (n >= 1e3) return `${Math.round(n / 1e3)}k`
10
+ return String(Math.round(n))
11
+ }
12
+
13
+ function pressureTone(score) {
14
+ const n = Number(score)
15
+ if (!Number.isFinite(n)) return 'var(--dsh-text-dim, #8a8a8a)'
16
+ if (n >= 85) return 'var(--dsh-danger, #d9534f)'
17
+ if (n >= 70) return 'var(--dsh-warning, #c9973f)'
18
+ return 'var(--dsh-success, #3f9e63)'
19
+ }
20
+
21
+ // 逐轮曲线的分要在浏览器里现算:服务端 live 只给当前这一轮的总分。
22
+ // 公式与 lib/session-pressure.js 的 pressureScore 保持一致(2026-11-18 真机点开胶囊消失)。
23
+ function pressureScore(tokens, threshold) {
24
+ if (!Number.isFinite(tokens) || tokens < 0 || !Number.isFinite(threshold) || threshold <= 0) return null
25
+ return Math.min(100, 100 * tokens / threshold)
26
+ }
27
+
28
+ // 不再定时轮询(2026-11-18 用户 m03880):挂载取一次、打开弹层取一次(带 composite)、
29
+ // 页面重新可见时取一次;房外会话在服务端就是 not-fish,前端也不会去问别的房间。
30
+ function usePressure(sessionId, active) {
31
+ const [data, setData] = useState(null)
32
+ const [failed, setFailed] = useState(false)
33
+ const [tick, setTick] = useState(0)
34
+ useEffect(() => {
35
+ if (!sessionId) return undefined
36
+ let alive = true
37
+ let timer = null
38
+ let attempts = 0
39
+ const run = async () => {
40
+ try {
41
+ const q = `session=${encodeURIComponent(sessionId)}${active ? '&composite=1' : '&light=1'}`
42
+ const next = await jget(`/session-pressure?${q}`)
43
+ if (!alive) return
44
+ setData(next)
45
+ setFailed(false)
46
+ // 服务端第一次常常还在算(availability=pending)。只在这段时间里短轮询,
47
+ // 算完就停;不做常驻定时器(2026-11-18 用户反馈胶囊要等点击才出现)。
48
+ if (next?.availability === 'pending' && attempts < 8) {
49
+ attempts += 1
50
+ timer = setTimeout(() => { void run() }, 1500)
51
+ }
52
+ } catch {
53
+ if (alive) setFailed(true)
54
+ }
55
+ }
56
+ void run()
57
+ const onVisible = () => { if (typeof document !== 'undefined' && document.visibilityState === 'visible') void run() }
58
+ if (typeof document !== 'undefined') document.addEventListener?.('visibilitychange', onVisible)
59
+ return () => {
60
+ alive = false
61
+ if (timer) clearTimeout(timer)
62
+ if (typeof document !== 'undefined') document.removeEventListener?.('visibilitychange', onVisible)
63
+ }
64
+ }, [sessionId, active, tick])
65
+ return [data, failed, () => setTick(n => n + 1)]
66
+ }
67
+
68
+ function pressureMiniRows(data) {
69
+ const rows = data?.usage?.roundDiagnostics ?? []
70
+ return rows.slice(-6).map(row => h('div', {
71
+ key: String(row.turn),
72
+ style: { display: 'flex', justifyContent: 'space-between', gap: '8px', fontSize: '12px', opacity: 0.85 },
73
+ },
74
+ h('span', null, `第 ${row.turn} 轮`),
75
+ h('span', null, `输入 ${pressureK(row.input)} · 输出 ${pressureK(row.output)}`)))
76
+ }
77
+
78
+ // 宿主的主题变量不保证凑齐(深色下 --dsh-surface 有、--dsh-text 未必有),
79
+ // 这里看页面正文文字颜色的明暗判断深浅,再把一整套面板颜色从根上传下去。
80
+ function pressurePalette(el) {
81
+ let dark = false
82
+ try {
83
+ const probe = (typeof document !== 'undefined' && document.body) || el
84
+ const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(String(getComputedStyle(probe).color || ''))
85
+ if (m) dark = (0.2126 * Number(m[1]) + 0.7152 * Number(m[2]) + 0.0722 * Number(m[3])) / 255 > 0.5
86
+ } catch { /* 取不到样式就按浅色面板兜底 */ }
87
+ return dark
88
+ ? { surface: '#1f2023', text: '#ececef', dim: '#a1a1aa', border: 'rgba(255,255,255,.14)', chip: 'rgba(255,255,255,.07)' }
89
+ : { surface: '#ffffff', text: '#1d1d1f', dim: '#6b7280', border: 'rgba(0,0,0,.12)', chip: 'rgba(0,0,0,.045)' }
90
+ }
91
+
92
+ function PressureChip(props) {
93
+ const sessionId = props?.sessionId ?? props?.session?.id ?? props?.session?.header?.id
94
+ const [open, setOpen] = useState(false)
95
+ const [data, failed, reload] = usePressure(sessionId, open)
96
+ const [anchor, setAnchor] = useState(null)
97
+ const [palette, setPalette] = useState(pressurePalette(null))
98
+ const [tab, setTab] = useState('current')
99
+ const [hidden, setHidden] = useState([])
100
+ // 手动换房(2026-11-18,用户 m02113 / m02215):先点「换一间…」,就地问一遍,
101
+ // 把后果写清再动手;误触只会停在问这一句,不会真的换。
102
+ const [rotateAsk, setRotateAsk] = useState(false)
103
+ const [rotateBusy, setRotateBusy] = useState(false)
104
+ const [rotateNote, setRotateNote] = useState('')
105
+ const [rotateErr, setRotateErr] = useState('')
106
+ const boxRef = useRef(null)
107
+ const dlgRef = useRef(null)
108
+ // 用原生 dialog 的 top layer:标题栏的祖先可能 overflow:hidden 或有 transform,
109
+ // 弹层挂在里面会被裁掉(2026-11-17 真机只看到一个阴影框)。
110
+ useEffect(() => {
111
+ const dlg = dlgRef.current
112
+ if (!dlg) return
113
+ if (open && !dlg.open) { try { dlg.showModal() } catch { /* 老内核没有 showModal 就退回普通定位 */ } }
114
+ if (!open && dlg.open) dlg.close()
115
+ }, [open])
116
+ // 自己的遮罩自己定:宿主可能给所有 dialog 配了深色 backdrop,会盖住弹层。
117
+ useEffect(() => {
118
+ if (!open) return
119
+ const id = 'dsh-fish-pressure-dialog-css'
120
+ if (!document.getElementById(id)) {
121
+ const st = document.createElement('style')
122
+ st.id = id
123
+ st.textContent = '.pressure-dialog::backdrop{background:transparent}'
124
+ document.head.appendChild(st)
125
+ }
126
+ }, [open])
127
+ if (!sessionId) return null
128
+ const availability = data?.availability
129
+ // 房外/无会话才隐藏(用户 m02888)。还在算(pending)也要先把胶囊摆出来,
130
+ // 否则切进对话时看起来「默认不显示」,得等一次点击触发重渲染才冒出来(2026-11-18 用户反馈)。
131
+ if (availability === 'not-fish' || availability === 'no-session') return null
132
+ const score = pressureScoreOf(data)
133
+ const label = Number.isFinite(score) ? String(Math.round(score)) : (failed ? '压力 —' : '压力 …')
134
+ const toggle = (ev) => {
135
+ if (open) { setOpen(false); return }
136
+ const rect = ev.currentTarget.getBoundingClientRect()
137
+ setPalette(pressurePalette(ev.currentTarget))
138
+ setAnchor({
139
+ top: Math.round(rect.bottom + 6),
140
+ right: Math.max(8, Math.round(window.innerWidth - rect.right)),
141
+ })
142
+ setOpen(true)
143
+ }
144
+ // 换房的后果就这几条,说清再让他点第二个按钮。她正在说话时服务端会回 409,
145
+ // 这里把那句话直接摆出来(不吞掉,也不假装换好了)。
146
+ const doRotate = async () => {
147
+ if (rotateBusy) return
148
+ setRotateBusy(true)
149
+ setRotateErr('')
150
+ try {
151
+ const r = await jpost('/home/rotate', { confirm: 'rotate', from: sessionId })
152
+ setRotateAsk(false)
153
+ setRotateNote(String(r?.note ?? S('换好了。')))
154
+ } catch (e) {
155
+ setRotateErr(String(e?.message || e || S('没换成。')))
156
+ } finally {
157
+ setRotateBusy(false)
158
+ }
159
+ }
160
+ const rotateAskBox = rotateAsk ? h('div', {
161
+ style: {
162
+ border: '1px solid ' + palette.border, borderRadius: '8px',
163
+ padding: '10px 12px', marginBottom: '10px', background: 'var(--pf-chip)',
164
+ fontSize: '12.5px', lineHeight: '19px',
165
+ },
166
+ },
167
+ h('div', { style: { fontWeight: 500, marginBottom: '4px' } }, S('要换一间吗?先看清会发生什么:')),
168
+ h('div', null, S('· 现在这一间会改名留档(叫「跟大肥鱼说话·…之前」),不删,侧栏里还能翻到。')),
169
+ h('div', null, S('· 新的一间是空的,只带一页「上次停在这」——她记的事、便条、日记都还在,不跟着换。')),
170
+ h('div', null, S('· 轮数从 0 重新数;她这轮还没说完的话不会丢,会留在旧的那一间里。')),
171
+ h('div', null, S('· 换完会叫她一声;侧栏里等她说出第一句才出现。')),
172
+ rotateErr ? h('div', { style: { marginTop: '6px', color: '#d9534f' } }, rotateErr) : null,
173
+ h('div', { style: { display: 'flex', gap: '8px', marginTop: '8px' } },
174
+ h('button', {
175
+ type: 'button',
176
+ onClick: doRotate,
177
+ disabled: rotateBusy,
178
+ style: {
179
+ fontSize: '12px', padding: '4px 12px', borderRadius: '6px', cursor: rotateBusy ? 'default' : 'pointer',
180
+ border: '1px solid ' + palette.border, background: 'transparent', color: palette.text,
181
+ },
182
+ }, rotateBusy ? S('换着…') : S('换一间')),
183
+ h('button', {
184
+ type: 'button',
185
+ onClick: () => { setRotateAsk(false); setRotateErr('') },
186
+ style: { fontSize: '12px', padding: '4px 12px', borderRadius: '6px', border: 'none', background: 'transparent', color: palette.dim, cursor: 'pointer' },
187
+ }, S('先不换'))))
188
+ : null
189
+ const rotateDoneBox = rotateNote ? h('div', {
190
+ style: {
191
+ border: '1px solid ' + palette.border, borderRadius: '8px', padding: '9px 12px',
192
+ marginBottom: '10px', fontSize: '12.5px', lineHeight: '19px',
193
+ },
194
+ },
195
+ h('div', null, rotateNote),
196
+ h('button', {
197
+ type: 'button',
198
+ onClick: () => { setRotateNote(''); setOpen(false) },
199
+ style: { marginTop: '6px', fontSize: '12px', padding: '3px 10px', borderRadius: '6px', border: '1px solid ' + palette.border, background: 'transparent', color: palette.text, cursor: 'pointer' },
200
+ }, S('知道了'))) : null
201
+ return h('div', { ref: boxRef, style: { position: 'relative', display: 'inline-flex' } },
202
+ h('button', {
203
+ type: 'button',
204
+ title: S('这间对话的上下文占用;点一下看细一点'),
205
+ onClick: toggle,
206
+ style: {
207
+ display: 'inline-flex', alignItems: 'center', gap: '5px',
208
+ padding: '2px 9px', borderRadius: '999px', fontSize: '12px', lineHeight: '18px',
209
+ border: '1px solid var(--dsh-border, #3a3a3a)', background: 'transparent',
210
+ color: pressureTone(score), cursor: 'pointer',
211
+ },
212
+ },
213
+ h('span', { style: { width: '6px', height: '6px', borderRadius: '999px', background: pressureTone(score) } }),
214
+ label),
215
+ open && anchor ? h('dialog', {
216
+ ref: dlgRef,
217
+ className: 'pressure-dialog',
218
+ onClose: () => setOpen(false),
219
+ onPointerDown: (ev) => { if (ev.target === ev.currentTarget) setOpen(false) },
220
+ style: {
221
+ position: 'fixed', top: anchor.top + 'px', right: anchor.right + 'px', left: 'auto', bottom: 'auto',
222
+ margin: 0, padding: 0, border: 'none', background: 'transparent', color: 'inherit',
223
+ maxWidth: 'none', maxHeight: 'none', width: '520px', overflow: 'visible',
224
+ },
225
+ }, h('div', {
226
+ style: {
227
+ width: '520px', maxWidth: 'calc(100vw - 32px)', maxHeight: '80vh', overflowY: 'auto',
228
+ padding: '14px 16px', borderRadius: '10px', textAlign: 'left',
229
+ background: palette.surface, color: palette.text,
230
+ border: '1px solid ' + palette.border,
231
+ boxShadow: '0 12px 32px rgba(0,0,0,.35)',
232
+ // 面板内部的 .hint / 边框等继续读宿主变量,这里把它们固定成当前主题的一套值。
233
+ '--dsh-surface': palette.surface,
234
+ '--dsh-text': palette.text,
235
+ '--dsh-text-dim': palette.dim,
236
+ '--dsh-border': palette.border,
237
+ '--pf-surface': palette.surface, '--pf-text': palette.text, '--pf-dim': palette.dim,
238
+ '--pf-line': palette.border, '--pf-chip': palette.chip,
239
+ },
240
+ }, rotateAskBox, rotateDoneBox, pressureReport({
241
+ data: data, failed: failed, reload: reload, tab: tab, setTab: setTab, hidden: hidden, setHidden: setHidden,
242
+ // 只有胶囊弹层里给这个入口;「压力」页签是另一处渲染,不带换房按钮。
243
+ onRotate: () => { setRotateAsk(true); setRotateNote(''); setRotateErr('') },
244
+ }))) : null)
245
+ }
246
+
247
+ // 综合分:A/B/C 三种加权公式的平均(PR #148,2026-11-18 用户 m04025)。
248
+ // 缺了才退回上下文占用,保证老数据也能显示。
249
+ function pressureScoreOf(data) {
250
+ // Number(null) 是 0:空值必须先挡掉,否则「还没算出来」会被显示成 0 分(2026-11-18 用户报 0 分)。
251
+ const raw = data?.compositeAverage
252
+ const average = raw == null ? NaN : Number(raw)
253
+ if (Number.isFinite(average)) return average
254
+ const live = data?.live?.score
255
+ return live == null ? NaN : (Number.isFinite(Number(live)) ? Number(live) : NaN)
256
+ }
257
+
258
+ function pressureAdvice(data) {
259
+ const score = pressureScoreOf(data)
260
+ if (!Number.isFinite(score)) return null
261
+ if (score >= 95) return S('这一段快到顶了:聊完这轮就换个房间吧。')
262
+ if (score >= 85) return S('还能再聊几轮,但可以开始想换房间了。')
263
+ if (score >= 70) return S('还够用,不过已经过半,别把一整个长任务都堆在这一间。')
264
+ return S('还很空,这间房可以继续用。')
265
+ }
266
+
267
+ // 第一屏的结论:只看综合分落点,说人话(用户 m03303 要「直观告诉要不要换对话」)。
268
+ function pressureVerdict(score) {
269
+ const n = Number(score)
270
+ if (!Number.isFinite(n)) return { title: S('数据还不够'), tone: '#8a8a8a', hint: S('再聊几轮才有对照。') }
271
+ if (n >= 95) return { title: S('该换房间了'), tone: '#d9534f', hint: S('这一段基本装满,换一间接着聊。') }
272
+ if (n >= 85) return { title: S('准备换房'), tone: '#e08a1e', hint: S('还能再聊几轮,可以先想好下一句在哪儿说。') }
273
+ if (n >= 70) return { title: S('还够用,但过半了'), tone: '#b58a00', hint: S('别把一整个长任务都堆在这一间。') }
274
+ return { title: S('还很空'), tone: '#3a9d5d', hint: S('这间房可以继续用。') }
275
+ }
276
+
277
+ function pressureBar(pct, tone) {
278
+ const width = Math.max(0, Math.min(100, Number(pct) || 0))
279
+ return h('div', { style: { height: '6px', borderRadius: '999px', background: 'rgba(128,128,128,.22)', overflow: 'hidden' } },
280
+ h('div', { style: { width: width + '%', height: '100%', background: tone, borderRadius: '999px' } }))
281
+ }
282
+
283
+ // 分页式完整报表(用户 m03375):当前 / 历史 / 指标 / 计算 四个页签。
284
+ function pressureReport(props) {
285
+ const { data, failed, reload, tab, setTab, hidden, setHidden, onRotate } = props
286
+ // 一套自己的排版尺度:正文 12.5、次要说明 11.5、标题 13、数字 15;不再混用 11/12/15 的随机组合。
287
+ const section = (title, extra) => h('div', {
288
+ style: {
289
+ display: 'flex', alignItems: 'center', gap: '8px',
290
+ padding: '7px 10px', borderRadius: '7px',
291
+ background: 'var(--pf-chip)', marginBottom: '6px',
292
+ },
293
+ },
294
+ h('span', { style: { fontSize: '12px', fontWeight: 500, letterSpacing: '.01em' } }, title),
295
+ extra != null ? h('span', { style: { marginLeft: 'auto', fontSize: '11px', color: 'var(--pf-dim)' } }, extra) : null)
296
+ const table = (headers, list) => h('div', { style: { overflowX: 'auto' } },
297
+ h('table', { style: { width: '100%', borderCollapse: 'collapse' } },
298
+ h('thead', null, h('tr', null, ...headers.map(name => h('th', {
299
+ key: name,
300
+ style: {
301
+ textAlign: 'left', padding: '6px 8px', fontSize: '11.5px', fontWeight: 500,
302
+ color: 'var(--pf-dim)', background: 'var(--pf-chip)',
303
+ whiteSpace: 'nowrap', borderBottom: '1px solid var(--pf-line)',
304
+ },
305
+ }, name)))),
306
+ h('tbody', null, ...list.map((row, i) => h('tr', { key: String(i) },
307
+ ...row.map((cell, j) => h('td', {
308
+ key: String(j),
309
+ style: {
310
+ padding: '6px 8px', fontSize: '12.5px', borderBottom: '1px solid var(--pf-line)',
311
+ whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums',
312
+ },
313
+ }, cell)))))))
314
+ const stat = (label, value) => h('div', {
315
+ key: label,
316
+ style: { padding: '8px 10px', borderRadius: '8px', background: 'var(--pf-chip)' },
317
+ },
318
+ h('div', { style: { fontSize: '11px', color: 'var(--pf-dim)' } }, label),
319
+ h('div', { style: { fontSize: '15px', fontWeight: 600, marginTop: '2px', fontVariantNumeric: 'tabular-nums' } }, value))
320
+ if (failed || data?.availability === 'unavailable') {
321
+ return h('div', null,
322
+ h('p', { className: 'hint' }, S('这次没读到压力数据。不是坏了,再试一次。')),
323
+ h('button', { onClick: () => reload() }, S('重新读')))
324
+ }
325
+ if (!data) return h('div', { className: 'hint' }, S('正在算这一轮的压力……'))
326
+ const score = pressureScoreOf(data)
327
+ const tone = pressureTone(score)
328
+ const verdict = pressureVerdict(score)
329
+ const windowSize = Number(data?.live?.contextWindow)
330
+ const tokens = Number(data?.live?.tokens)
331
+ const ratio = windowSize > 0 && Number.isFinite(tokens) ? Math.max(0, Math.min(100, tokens / windowSize * 100)) : null
332
+ const usage = data?.usage ?? {}
333
+ const usageRows = usage.roundDiagnostics ?? []
334
+ const last = usageRows.at(-1)
335
+ const history = usage.history ?? []
336
+ const tools = (data?.tools ?? []).slice(0, 8)
337
+ const growth = (data?.growth ?? []).slice(0, 8)
338
+ const allFactors = data?.load?.factors ?? []
339
+ const ref = usage.reference ?? {}
340
+ const requestsTotal = usageRows.reduce((sum, row) => sum + (Number(row.requests) || 0), 0)
341
+ const toolErrorsTotal = usageRows.reduce((sum, row) => sum + (Number(row.toolErrors) || 0), 0)
342
+ const completedRounds = usageRows.filter(row => Number(row.requests) > 0).length
343
+ // 走势用每轮开头那一次请求的输入量 ÷ 当轮窗口:这才是「聊到这一轮时上下文占了多少」。
344
+ const series = usageRows.map(row => {
345
+ // 老会话不一定记着当轮窗口/首请求输入(2026-11-18 用户反馈图一直空):
346
+ // 窗口退回当前 live 的 contextWindow,首请求退回该轮总输入,保证曲线能画出来。
347
+ const liveWindow = Number(data?.live?.contextWindow)
348
+ const win = Number(row.window) || (liveWindow > 0 ? liveWindow : NaN)
349
+ const firstRaw = Number(row.first)
350
+ const first = Number.isFinite(firstRaw) ? firstRaw : Number(row.input)
351
+ if (!Number.isFinite(win) || win <= 0 || !Number.isFinite(first)) return null
352
+ return { turn: row.turn, pct: Math.max(0, Math.min(100, first / win * 100)) }
353
+ }).filter(Boolean)
354
+ const chartH = 88
355
+ const chartW = 260
356
+ const plot = series.length > 1
357
+ ? h('svg', {
358
+ viewBox: `0 0 ${chartW} ${chartH}`, preserveAspectRatio: 'none',
359
+ style: { width: '100%', height: chartH + 'px', display: 'block', color: tone },
360
+ },
361
+ [70, 85, 100].map(level => h('line', {
362
+ key: String(level), x1: 0, x2: chartW,
363
+ y1: 78 - level / 100 * 68, y2: 78 - level / 100 * 68,
364
+ stroke: 'currentColor', opacity: 0.16, strokeDasharray: '3 3',
365
+ })),
366
+ h('path', {
367
+ fill: 'currentColor', opacity: 0.1,
368
+ d: `M0,78 L${series.map((row, i) => `${(i / (series.length - 1)) * chartW},${78 - row.pct / 100 * 68}`).join(' L')} L${chartW},78 Z`,
369
+ }),
370
+ h('polyline', {
371
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinejoin: 'round', strokeLinecap: 'round',
372
+ points: series.map((row, i) => `${(i / (series.length - 1)) * chartW},${78 - row.pct / 100 * 68}`).join(' '),
373
+ }),
374
+ h('circle', {
375
+ cx: chartW, cy: 78 - series.at(-1).pct / 100 * 68, r: 2.4, fill: 'currentColor',
376
+ }))
377
+ : h('div', { style: { fontSize: '12px', color: 'var(--pf-dim)' } },
378
+ series.length ? S('只有一轮,够画一个点,还不够成走势。') : S('还没有留下每轮的上下文记录。'))
379
+ const headline = h('div', { style: { display: 'grid', gap: '10px' } },
380
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '10px' } },
381
+ h('div', { style: { display: 'flex', alignItems: 'baseline', gap: '6px' } },
382
+ h('span', { style: { fontSize: '30px', lineHeight: '32px', fontWeight: 600, color: tone } },
383
+ Number.isFinite(score) ? String(Math.round(score)) : '—'),
384
+ h('span', { style: { fontSize: '12px', color: 'var(--pf-dim)' } }, S('分 · 越高越重'))),
385
+ h('span', {
386
+ style: {
387
+ marginLeft: 'auto', padding: '3px 10px', borderRadius: '999px',
388
+ fontSize: '11.5px', color: verdict.tone, background: 'var(--pf-chip)',
389
+ border: '1px solid ' + verdict.tone, whiteSpace: 'nowrap',
390
+ },
391
+ }, verdict.title),
392
+ h('button', {
393
+ onClick: () => reload(),
394
+ style: {
395
+ fontSize: '11.5px', background: 'transparent', border: '1px solid var(--pf-line)',
396
+ color: 'var(--pf-dim)', borderRadius: '6px', padding: '3px 8px', cursor: 'pointer',
397
+ },
398
+ }, S('刷新')),
399
+ // 手动换房(2026-11-18,用户 m02113 / m02215):入口就在「这间装到哪了」旁边,
400
+ // 因为「该换房间了」这句提示本来就出现在这里。点开的是就地确认,不是 native confirm:
401
+ // 弹层本身已经是 native dialog,再叠一层系统框在深色主题里很难看,也说不清后果。
402
+ onRotate ? h('button', {
403
+ onClick: onRotate,
404
+ title: S('换一条新会话接着聊;旧的那条改名留档,不删'),
405
+ style: {
406
+ fontSize: '11.5px',
407
+ background: 'transparent',
408
+ border: '1px solid ' + (Number(score) >= 85 ? tone : 'var(--pf-line)'),
409
+ color: Number(score) >= 85 ? tone : 'var(--pf-dim)',
410
+ borderRadius: '6px', padding: '3px 8px', cursor: 'pointer',
411
+ },
412
+ }, S('换一间…')) : null),
413
+ h('div', { style: { fontSize: '13px', fontWeight: 400, lineHeight: '19px' } }, verdict.hint),
414
+ h('div', { style: { display: 'grid', gap: '5px' } },
415
+ h('div', { style: { height: '6px', borderRadius: '999px', background: 'var(--pf-chip)', overflow: 'hidden' } },
416
+ h('div', { style: { width: Math.round(ratio ?? 0) + '%', height: '100%', background: tone, borderRadius: '999px' } })),
417
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: 'var(--pf-dim)' } },
418
+ h('span', null, ratio === null ? S('上下文占用未知') : `上下文已用 ${Math.round(ratio)}%`),
419
+ h('span', null, `${pressureK(tokens)} / ${pressureK(windowSize)} Token`))),
420
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: '6px' } },
421
+ stat(S('轮数'), String(completedRounds || usageRows.length)),
422
+ stat(S('样本'), ref.count ? String(ref.count) : S('不足')),
423
+ stat(S('请求'), String(requestsTotal)),
424
+ stat(S('报错'), String(toolErrorsTotal))))
425
+ // 第一屏给「历史同轮中位数」(2026-11-18 用户 m03803):直接回答「这一轮比过去同轮重还是轻」。
426
+ const medianLine = (() => {
427
+ const mp = data?.medianPoint
428
+ if (!mp) return h('div', { style: { fontSize: '12px', color: 'var(--pf-dim)' } },
429
+ S('历史同轮中位数还没有样本:这版开始每轮记录,攒几轮就能对照。'))
430
+ const nowPct = ratio === null ? null : Math.round(ratio)
431
+ const diff = nowPct === null ? null : nowPct - Math.round(mp.pct)
432
+ const kind = mp.n >= 10 ? S('中位数') : S('参考')
433
+ const tail = nowPct === null ? ''
434
+ : diff === 0 ? S(',和它差不多')
435
+ : diff > 0 ? `,比它高 ${diff} 个百分点`
436
+ : `,比它低 ${-diff} 个百分点`
437
+ return h('div', { style: { fontSize: '12px', color: 'var(--pf-text)', lineHeight: '19px' } },
438
+ `第 ${mp.turn} 轮历史${kind} ${mp.pct}%(样本 ${mp.n} 次)· 你现在 ${nowPct === null ? '—' : nowPct + '%'}${tail}`)
439
+ })()
440
+ // 被中断的轮不记用量,但明说一句,别让人以为漏数了(2026-11-18 用户 m03880)。
441
+ const interrupted = Number(data?.interruptedRounds) || 0
442
+ const interruptedLine = interrupted
443
+ ? h('div', { style: { fontSize: '12px', color: 'var(--pf-dim)' } },
444
+ `其中 ${interrupted} 轮被中断,没有记录。`)
445
+ : null
446
+ const currentView = h('div', { style: { display: 'grid', gap: '14px' } },
447
+ medianLine,
448
+ interruptedLine,
449
+ h('div', null,
450
+ section(S('上下文占用走势'), S('虚线 70 / 85 / 100')),
451
+ plot,
452
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: 'var(--pf-dim)', marginTop: '2px' } },
453
+ h('span', null, series.length ? `第 ${series[0].turn} 轮` : ''),
454
+ h('span', null, series.length ? `第 ${series.at(-1).turn} 轮` : ''))),
455
+ growth.length ? h('div', null,
456
+ section(S('增长最大的轮次')),
457
+ table([S('轮次'), S('净增长'), S('轮末 Token'), S('请求')],
458
+ growth.map(row => [`第 ${row.turn} 轮`, row.delta != null ? '+' + pressureK(row.delta) : '—', pressureK(row.tokens), String(row.requests ?? '—')]))) : null,
459
+ tools.length ? h('div', null,
460
+ section(S('工具结果长期残留')),
461
+ table([S('工具'), S('累计 Token'), S('调用')],
462
+ tools.map(row => [row.name, pressureK(row.tokens), String(row.calls ?? '—')]))) : null,
463
+ usageRows.length ? h('div', null,
464
+ section(S('逐轮明细'), S('最近 12 轮')),
465
+ table([S('轮次'), S('输入'), S('输出'), S('请求'), S('重试')],
466
+ usageRows.slice(-12).reverse().map(row => [`第 ${row.turn} 轮`, pressureK(row.input), pressureK(row.output), String(row.requests ?? '—'), String(row.attempts ?? '—')]))) : null)
467
+ const historyView = h('div', { style: { display: 'grid', gap: '12px' } },
468
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: '6px' } },
469
+ stat(S('参考样本'), ref.count ? String(ref.count) : S('不足')),
470
+ stat('P90', ref.p90 != null ? pressureK(ref.p90) : '—'),
471
+ stat(S('历史会话'), String(history.length))),
472
+ ref.count && ref.count >= 10 ? null
473
+ : h('div', { className: 'hint' }, S('历史样本要凑够 10 个完整用量的轮次才给对照;现在还不够,所以只报这间房自己的数。')),
474
+ history.length ? table([S('会话'), S('状态'), S('轮数')],
475
+ history.slice(0, 10).map(row => [row.title || S('未命名会话'), row.status ?? '—', String(row.count ?? row.turns ?? '—')]))
476
+ : h('div', { className: 'hint' }, S('还没有可以对照的历史会话。')),
477
+ h('div', { className: 'hint' }, S('只统计这间房的会话;别的房间与子代理不参与。')))
478
+ const factorsView = h('div', { style: { display: 'grid', gap: '10px' } },
479
+ h('div', { className: 'hint' }, S('勾选只影响这张表显示哪几项;分数仍按七项固定权重算。')),
480
+ ...allFactors.map(factor => {
481
+ const on = !hidden.includes(factor.id)
482
+ const cur = Number(factor.current)
483
+ const base = Number(factor.baseline)
484
+ const span = Math.max(1, Number.isFinite(cur) ? cur : 0, Number.isFinite(base) ? base : 0)
485
+ return h('div', { key: factor.id, style: { display: 'grid', gap: '5px', opacity: factor.available ? 1 : 0.55 } },
486
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12.5px' } },
487
+ h('input', {
488
+ type: 'checkbox', checked: on,
489
+ onChange: () => setHidden(prev => on ? [...prev, factor.id] : prev.filter(id => id !== factor.id)),
490
+ }),
491
+ h('span', { style: { fontWeight: 500 } }, `${factor.label ?? factor.id} · ${factor.weight}%`),
492
+ h('span', { style: { marginLeft: 'auto', fontSize: '11.5px', color: 'var(--pf-dim)' } },
493
+ `${Number.isFinite(cur) ? Math.round(cur) : '—'} / ${Number.isFinite(base) ? Math.round(base) : '—'}${factor.provisional ? S(' · 样本少') : ''}`)),
494
+ on ? h('div', { style: { position: 'relative', height: '5px', borderRadius: '999px', background: 'var(--pf-chip)' } },
495
+ h('div', { style: { width: Math.min(100, (Number.isFinite(cur) ? cur : 0) / span * 100) + '%', height: '100%', borderRadius: '999px', background: tone, opacity: 0.85 } }),
496
+ Number.isFinite(base) ? h('div', {
497
+ style: {
498
+ position: 'absolute', top: '-2px', bottom: '-2px',
499
+ left: Math.min(100, base / span * 100) + '%', width: '1px',
500
+ background: 'currentColor', opacity: 0.5,
501
+ },
502
+ }) : null) : null)
503
+ }))
504
+ const calcView = h('div', { style: { display: 'grid', gap: '9px', fontSize: '12.5px', lineHeight: '1.7', color: 'var(--pf-dim)' } },
505
+ h('p', null, S('最上面那个分数是综合负担:容量、请求、结构三项各算一遍。A 按固定权重相加;B 把三项当风险相乘;C 以容量为主、再用请求和结构修正。三种取平均,0 最轻、100 满格。')),
506
+ h('p', null, S('三项看什么:容量是窗口现在占了多少;请求是每轮重放相对窗口有多重、缓存省了多少、输出占多少;结构是工具结果堆了多少、重复可见多少、重试报错多不多。')),
507
+ h('p', null, S('分数段:20 以下很轻,随便聊;20–50 正常、还能装;50–75 开始变重,长任务最好拆开;85 以上该准备换房间;95 以上聊完这轮就换。')),
508
+ h('p', null, S('这个分不跟历史比。指标页那七项才跟历史同轮中位数比;样本不到 10 个只当参考,不到 3 个不报。')),
509
+ h('p', null, S('数据来自每轮模型实报的 Token;压缩次数只统计宿主事件流里能看到的,别的压缩插件不对外暴露。')),
510
+ h('p', null, S('只读统计:不改对话,也不写事件流。')))
511
+ const tabs = [['current', S('当前')], ['history', S('历史')], ['factors', S('指标')], ['calc', S('计算')]]
512
+ return h('div', { style: { display: 'grid', gap: '14px' } },
513
+ headline,
514
+ h('div', { style: { display: 'flex', gap: '18px', borderBottom: '1px solid var(--pf-line)' } },
515
+ ...tabs.map(([id, label]) => h('button', {
516
+ key: id, type: 'button', onClick: () => setTab(id),
517
+ style: {
518
+ padding: '6px 0 7px', fontSize: '12.5px', background: 'transparent', cursor: 'pointer',
519
+ color: 'inherit', border: 'none',
520
+ borderBottom: tab === id ? '2px solid ' + tone : '2px solid transparent',
521
+ color: tab === id ? tone : 'var(--pf-dim)',
522
+ fontWeight: tab === id ? 500 : 400,
523
+ },
524
+ }, label))),
525
+ tab === 'current' ? currentView : tab === 'history' ? historyView : tab === 'factors' ? factorsView : calcView)
526
+ }
527
+ // ---------------------------------------------------------------- 挂载
528
+ const inject = ['slots']
529
+ const NAMES = { nav: '大肥鱼' }
530
+
531
+ function apply(ctx) {
532
+ ctx.effect(
533
+ () =>
534
+ ctx.slots.inject('settings.section', () =>
535
+ ctx.slots.register(
536
+ { name: 'settings.section', id: NS, order: 7, label: () => NAMES.nav },
537
+ FishSection,
538
+ ),
539
+ 'dsh-fish: settings section',
540
+ ),
541
+ 'dsh-fish: settings section',
542
+ )
543
+ // 对话页的常驻入口(2026-11-17,用户 m02719):会话头部小胶囊 + 压力页签。
544
+ // 两边共用同一份 /session-pressure?session=… 数据;非她这间房的会话服务端返回 not-fish,组件直接不渲染。
545
+ ctx.effect(
546
+ () =>
547
+ ctx.slots.inject('conversation.session.header.actions', () =>
548
+ ctx.slots.register(
549
+ { name: 'conversation.session.header.actions', id: 'pressure-chip', order: 20 },
550
+ PressureChip,
551
+ ),
552
+ 'dsh-fish: pressure chip',
553
+ ),
554
+ 'dsh-fish: pressure chip',
555
+ )
556
+ // 没有页签:页签会被宿主给每个会话都列出来,没法按会话隐藏(用户 m02888)。
557
+ // 压力入口只留小胶囊,点开的弹层里是完整内容;非她这间房时胶囊本身不渲染。
558
+ }
559
+
560
+ exports.apply = apply
561
+ exports.inject = inject
562
+ exports.FishSection = FishSection
563
+ return module.exports
564
+ },
565
+ })