@lin0306/dsh-mind 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +220 -3
  3. package/client/index.js +1932 -0
  4. package/cordis.patch.yml +8 -0
  5. package/icon.svg +26 -0
  6. package/lib/index.js +8287 -0
  7. package/lib/index.js.map +1 -0
  8. package/lib/types/.tsbuildinfo +1 -0
  9. package/lib/types/commands.d.ts +92 -0
  10. package/lib/types/commands.d.ts.map +1 -0
  11. package/lib/types/config.d.ts +116 -0
  12. package/lib/types/config.d.ts.map +1 -0
  13. package/lib/types/decide.d.ts +57 -0
  14. package/lib/types/decide.d.ts.map +1 -0
  15. package/lib/types/entries.d.ts +124 -0
  16. package/lib/types/entries.d.ts.map +1 -0
  17. package/lib/types/host.d.ts +184 -0
  18. package/lib/types/host.d.ts.map +1 -0
  19. package/lib/types/index.d.ts +64 -0
  20. package/lib/types/index.d.ts.map +1 -0
  21. package/lib/types/inject.d.ts +58 -0
  22. package/lib/types/inject.d.ts.map +1 -0
  23. package/lib/types/layout.d.ts +115 -0
  24. package/lib/types/layout.d.ts.map +1 -0
  25. package/lib/types/log.d.ts +29 -0
  26. package/lib/types/log.d.ts.map +1 -0
  27. package/lib/types/migrate.d.ts +44 -0
  28. package/lib/types/migrate.d.ts.map +1 -0
  29. package/lib/types/persist.d.ts +57 -0
  30. package/lib/types/persist.d.ts.map +1 -0
  31. package/lib/types/persona-md.d.ts +44 -0
  32. package/lib/types/persona-md.d.ts.map +1 -0
  33. package/lib/types/proactive.d.ts +64 -0
  34. package/lib/types/proactive.d.ts.map +1 -0
  35. package/lib/types/projection.d.ts +245 -0
  36. package/lib/types/projection.d.ts.map +1 -0
  37. package/lib/types/settings-bridge.d.ts +183 -0
  38. package/lib/types/settings-bridge.d.ts.map +1 -0
  39. package/lib/types/store.d.ts +188 -0
  40. package/lib/types/store.d.ts.map +1 -0
  41. package/lib/types/tools.d.ts +109 -0
  42. package/lib/types/tools.d.ts.map +1 -0
  43. package/locale/en.json +6 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +89 -6
@@ -0,0 +1,1932 @@
1
+ // ⚠️ 这个文件由 scripts/build-client.mjs 生成,不要手改。改 client/src/*.ts 后重新构建。
2
+ // DSH 客户端的加载形状:id 必须等于包名,factory 收到 require 并交回 module.exports。
3
+ window.__ModuleLoader__.load({
4
+ id: "@lin0306/dsh-mind",
5
+ factory: (require) => {
6
+ var module = { exports: {} };
7
+ var exports = module.exports;
8
+ "use strict";
9
+ /**
10
+ * dsh-mind 的**客户端半边**:侧栏上方一排里的「心念」入口 + 中间那一栏的状态页。
11
+ *
12
+ * 三条硬规矩(写在最前面,免得以后手滑):
13
+ *
14
+ * 1. 这个文件最后会被包成 **CJS factory**(见 `scripts/build-client.mjs`):
15
+ * `window.__ModuleLoader__.load({ id: 'dsh-mind', factory: (require) => { … } })`。
16
+ * 所以这里**不能用 ESM import、不能用 JSX**,只能 `require('react')`;
17
+ * 2. 面板**不做任何格式化**:把中枢通过会话投影 wire 过来的 `sections` 原样画出来。
18
+ * 这样「中文措辞」只有一处真相(core 里那组 describe / render 函数),不会两端各写一套然后慢慢跑偏。
19
+ * (写注释时注意:不要在块注释里写出星号加斜杠那两个字符,会**提前关闭注释**,报错还指向后面几行。)
20
+ * 3. 拿不到数据就**如实说拿不到**,绝不编一个看起来正常的空面板——那是最难查的一类错。
21
+ *
22
+ * 这里同时挂着**两个座位**:
23
+ * - `sidebar.panellist` + `main`:侧栏那一格与中间的状态页(就是上面说的"侧栏一排 + 中间页");
24
+ * - `settings.section`:DSH **设置**面板里的一页「心念」——用户点名要的那个("设置面板里根本就看不到")。
25
+ * 它通过宿主自己的受围栏路由 `/dsh-mind/api/settings.get|settings.update` 读写配置,
26
+ * 值的真相在宿主那边(这条路由的宿主半边是 `src/settings-bridge.ts`),
27
+ * 客户端**不另存一份**——存一份就是两个真相,改完在别处一看还是旧的。
28
+ *
29
+ * ## 为什么是「侧栏一排 + 中间页」,而不是「底部按钮 + 浮层弹窗」
30
+ *
31
+ * 试过弹窗,结果是错的:侧栏那一排(`sidebar.panellist`)的**点击权在宿主**。
32
+ * 官方目录里写得明明白白——"Global panel icons. Each list id addresses the matching main panel;
33
+ * the sidebar owns the button and resolves its label from list metadata."
34
+ * shell 拥有那一格的按钮、标签、高亮与切换,它把点击翻译成"用同一个 id 打开 `main` 槽里的页面"。
35
+ *
36
+ * 也就是说:**要么进来当一排里的一格(那就开中间页),要么就别进那一排**。
37
+ * 想做弹窗只能挪到 `sidebar.footer.action` + `shell.overlay`,但那个位置在左下角、和"设置"挤在一起,
38
+ * 而且自己画的浮层永远不像宿主自己的东西。所以按平台给的正路走:占一格 + 开一页。
39
+ */
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.inject = void 0;
42
+ exports.apply = apply;
43
+ const react = require('react');
44
+ const h = react.createElement;
45
+ /**
46
+ * 查一个会话的标题。
47
+ *
48
+ * 为什么按 id 当场查、不把标题存进记忆条目:条目可能来自早就删掉的会话,
49
+ * 那会儿的标题在这儿已经查不到了——查不到就如实说"会话 xxxxxx",
50
+ * 不能编一个出来,也不能把当时的标题冻进记忆里(那是新的信息源,会过期)。
51
+ */
52
+ function sessionTitle(ctx, sessionId) {
53
+ if (ctx === undefined || sessionId === undefined || sessionId === '')
54
+ return undefined;
55
+ const row = snapshotOf(ctx)?.byId?.[sessionId];
56
+ const title = row?.displayTitle ?? row?.label;
57
+ return typeof title === 'string' && title.trim() !== '' ? title.trim() : undefined;
58
+ }
59
+ /** 只依赖 `slots`:多声明一个服务就多一次"它不在就不激活"的风险。 */
60
+ exports.inject = ['slots'];
61
+ /**
62
+ * 座位 id:侧栏那一格与 `main` 那一页用同一个 id,宿主就是靠它把两者对上的。
63
+ *
64
+ * 它等于**包名**(`@lin0306/dsh-mind`)——这条是有测试盯着的:
65
+ * 设置页那一栏的 id 必须和侧栏那一格一致,而侧栏那格的 id 又必须与 loader 的 id 同源。
66
+ * 注意它**不参与** HTTP 路由(路由是下面独立的 `SETTINGS_ROUTE`),所以带 `/` 不会破路由。
67
+ */
68
+ const PANEL_ID = '@lin0306/dsh-mind';
69
+ /**
70
+ * 排在哪儿。
71
+ *
72
+ * 现有占位(`sidebar.panellist` 的实测 occupants):宿主自己的 Plugins = 0、Scheduled tasks = 10,
73
+ * 插件们的上下文洞察 = 20、任务看板 = 20。取 30 → 紧挨在那几个之后、仍在**上方这一排**里,
74
+ * 既不在底部,也不去抢宿主自己页面的位置。
75
+ */
76
+ const PANEL_ORDER = 30;
77
+ function apply(ctx) {
78
+ // 钉住的那块说明要能用 Esc 关掉(装一次就够,插件只 apply 一次)
79
+ installTipEscape();
80
+ // ① 侧栏上方那一排里的一格。宿主负责按钮、标签、高亮与切换,我只提供图标与标签文字。
81
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: PANEL_ORDER, label: () => '心念' }, MindIcon));
82
+ // ② 中间那一栏的页面。宿主按 id 找到它;座位上把当前会话 id 交过来(收不到也有兜底)。
83
+ //
84
+ // `inject` 的返回值就是页面的 props——**必须把 ctx 一起交过去**。
85
+ // 只给 `sessionId` 的话,页面里拿不到 `ctx.slots` / `ctx.get`,点开就是一片空(这里栽过一次)。
86
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID, inject: (sessionId) => ({ sessionId, ctx }) }, MindPage));
87
+ // ③ DSH **设置**面板里的一页。用户点名要的就是这一页:
88
+ // "设置面板里根本就看不到"——`sidebar.panellist` 那一格是侧栏,不是设置面板,两者互不相干。
89
+ //
90
+ // `order` 取 40:设置面板里的页是按这个数排的(实测 better-sidebar 用 100、llm-retry-settings 用 15),
91
+ // 放在它们之间,不抢最前面。
92
+ // DSH 0.1.x **不通过这个注册传图标**——宿主给每页画一个通用齿轮,传了也不认。
93
+ ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: PANEL_ID, order: SETTINGS_SECTION_ORDER, label: () => '心念', inject: () => ({}) }, SettingsSection));
94
+ }
95
+ /**
96
+ * 侧栏那一格的图标:一颗心 + 一条穿过它的脉搏(和仓库里的 `icon.svg` 同一个意思,只是缩到十几个像素)。
97
+ *
98
+ * 宿主给的 props 是 `{ size, active }`:`size` 是它要的边长,`active` 表示这一格当前是否被选中。
99
+ * 跟着它走,才不会和相邻那几格的大小、粗细对不齐。
100
+ */
101
+ function MindIcon(props) {
102
+ const size = typeof props?.size === 'number' && props.size > 0 ? props.size : 16;
103
+ const active = props?.active === true;
104
+ return h('svg', {
105
+ width: size,
106
+ height: size,
107
+ viewBox: '0 0 16 16',
108
+ fill: active ? 'currentColor' : 'none',
109
+ fillOpacity: active ? 0.16 : 0,
110
+ stroke: 'currentColor',
111
+ strokeWidth: active ? 1.5 : 1.35,
112
+ strokeLinecap: 'round',
113
+ strokeLinejoin: 'round',
114
+ 'aria-hidden': 'true',
115
+ }, h('path', {
116
+ key: 'heart',
117
+ d: 'M8 13.5C4.3 10.9 2.3 8.9 2.3 6.6 2.3 4.9 3.7 3.7 5.2 3.7c1 0 1.9.5 2.8 1.6.9-1.1 1.8-1.6 2.8-1.6 1.5 0 2.9 1.2 2.9 2.9 0 2.3-2 4.3-5.7 6.9Z',
118
+ }), h('path', { key: 'pulse', d: 'M3.1 7.9h1.6l.6-1.5.9 2.8.7-1.3h1.6' }));
119
+ }
120
+ /** 会话列表快照。 */
121
+ function snapshotOf(ctx) {
122
+ try {
123
+ const sessions = ctx.get('sessions');
124
+ return sessions?.list?.getSnapshot?.() ?? null;
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ /** 订阅快照变化;宿主没给订阅口就返回个空的清理函数(由页面里的轮询兜底)。 */
131
+ function subscribe(ctx, onChange) {
132
+ try {
133
+ const sessions = ctx.get('sessions');
134
+ const off = sessions?.list?.subscribe?.(onChange);
135
+ return typeof off === 'function' ? off : () => { };
136
+ }
137
+ catch {
138
+ return () => { };
139
+ }
140
+ }
141
+ /**
142
+ * 找出该显示哪个会话的状态。
143
+ *
144
+ * 顺序是"从最可信到最兜底":
145
+ * 1. 座位交过来的 `sessionId`(宿主要给了,它就是权威);
146
+ * 2. `ctx.get('sidebarRight').mounted`——DSH 公布的"哪个会话的座位正显示着";
147
+ * 3. 任何**有 mind 投影**的会话(宿主没给会话 id 时,宁可显示一个真会话并**标出是哪个**,
148
+ * 也不假装自己有数据)。
149
+ */
150
+ function resolveSession(ctx, injected) {
151
+ const byId = snapshotOf(ctx)?.byId ?? {};
152
+ const read = (id) => {
153
+ const value = byId[id]?.projectionValues?.['mind'];
154
+ return value ?? undefined;
155
+ };
156
+ if (typeof injected === 'string' && injected !== '') {
157
+ const view = read(injected);
158
+ if (view !== undefined)
159
+ return { sessionId: injected, view };
160
+ }
161
+ try {
162
+ const right = ctx.get('sidebarRight');
163
+ const mounted = right?.mounted?.getSnapshot?.();
164
+ if (typeof mounted === 'string' && mounted !== '') {
165
+ const view = read(mounted);
166
+ if (view !== undefined)
167
+ return { sessionId: mounted, view };
168
+ }
169
+ }
170
+ catch {
171
+ /* 没有这个服务就往下走 */
172
+ }
173
+ for (const id of Object.keys(byId)) {
174
+ const view = read(id);
175
+ if (view !== undefined)
176
+ return { sessionId: id, view };
177
+ }
178
+ return undefined;
179
+ }
180
+ /** 饼图配色:固定一组、循环取用。颜色不跟语义绑定(情绪词多,绑不过来)。 */
181
+ const PIE_COLORS = ['#8ab4ff', '#63e6be', '#b39ddb', '#ffb74d', '#ef6c6c', '#4dd0e1', '#a5d6a7', '#f48fb1'];
182
+ /**
183
+ * 每个情绪一个**专属固定色**:14 个词、14 种颜色,不随机、也不按下标轮换。
184
+ *
185
+ * 为什么必须固定:颜色在这张图里是第二个坐标——扫一眼"那块蓝的又长了"就知道是焦虑,
186
+ * 不必去读标签。轮换配色会让同一个情绪今天蓝明天绿,这份记忆就废了。
187
+ *
188
+ * 配色原则:负向偏深偏冷(闷、压着),正向偏亮偏暖(透气、亮起来)——
189
+ * 与"亮色=正向、深色=负向"的约定一致,同时保证 14 个词彼此分得开。
190
+ */
191
+ const EMOTION_COLORS = {
192
+ // 负向 8(深、冷、闷)
193
+ 挫败: '#6E5470',
194
+ 烦躁: '#C4603C',
195
+ 焦虑: '#4F63A6',
196
+ 疲惫: '#5B6E7C',
197
+ 困惑: '#6B5A93',
198
+ 内疚: '#8C5454',
199
+ 委屈: '#A45F76',
200
+ 无聊: '#6E7379',
201
+ // 正向 6(亮、暖、透)
202
+ 认可: '#4E9FD1',
203
+ 满足: '#3FA98B',
204
+ 好奇: '#79C05A',
205
+ 感激: '#D9A03C',
206
+ 自豪: '#B96BB4',
207
+ 期待: '#E08A4B',
208
+ };
209
+ /**
210
+ * 取一个情绪的固定色。
211
+ *
212
+ * 词表将来加新词时走兜底:按词名哈希从备用色里取一个**稳定的**颜色
213
+ * (同一个名字永远同一个色),绝不随机——随机等于每次刷新换一套配色。
214
+ */
215
+ function emotionColor(word) {
216
+ const known = EMOTION_COLORS[word];
217
+ if (typeof known === 'string')
218
+ return known;
219
+ const pool = ['#7C8AA0', '#9A7C6A', '#6A9A8A', '#8A6A9A'];
220
+ let sum = 0;
221
+ for (let i = 0; i < word.length; i += 1)
222
+ sum = (sum + word.charCodeAt(i) * (i + 1)) % 997;
223
+ return pool[sum % pool.length] ?? '#7C8AA0';
224
+ }
225
+ /** 一个环形扇段的 path:内半径 rIn、外半径 rOut,角度 a0→a1(弧度,顺时针)。 */
226
+ function ringSector(cx, cy, rIn, rOut, a0, a1) {
227
+ const large = a1 - a0 > Math.PI ? 1 : 0;
228
+ const at = (r, a) => `${(cx + r * Math.cos(a)).toFixed(2)} ${(cy + r * Math.sin(a)).toFixed(2)}`;
229
+ return (`M ${at(rIn, a0)} L ${at(rOut, a0)} ` +
230
+ `A ${rOut} ${rOut} 0 ${large} 1 ${at(rOut, a1)} ` +
231
+ `L ${at(rIn, a1)} A ${rIn} ${rIn} 0 ${large} 0 ${at(rIn, a0)} Z`);
232
+ }
233
+ /**
234
+ * 情绪玫瑰图(南丁格尔式):**每个词一个固定槽位**,半径=强度,一个词一种固定颜色。
235
+ *
236
+ * 三条纪律,都是为了"两次刷新能对比":
237
+ * - 槽位按词表全序**固定等分**,不按"当前有几个情绪"重排(否则每次形状都变,等于不能比);
238
+ * - 14 个扇区**全画**:没点亮的那个就是贴着内孔的一小段,槽位留着、不抢眼;
239
+ * - 半径从内孔起算到外缘,`0` 落在内孔、`1` 落在最外——**不按当前最大值归一化**,
240
+ * 否则"全都在衰减"这件事会被归一化吃掉(那正是饼图的老毛病)。
241
+ *
242
+ * 标签只给强度 ≥0.08 的扇区:14 个标签全标会绕成一圈糊。
243
+ */
244
+ function RoseChart(props) {
245
+ // 圆要**顶到画布高度**:半径按高度算(rMax ≈ hgt/2 − 标签边距 28),
246
+ // 宽度只是留给左右两侧的引线和标签。上一次错在"画布加宽了、圆没加",
247
+ // 半径 112 在 560 宽的画布里只占 20%,看着就是缩在中间一小团。
248
+ // 比例按"卡片内宽 ≈ 500、图区高 ≈ 380"来定:圆直径顶到高度的八成,
249
+ // 左右各留 100 给引线和标签。宽高比要贴近卡片,否则 SVG 等比缩放又会留边。
250
+ const w = 500;
251
+ const hgt = 380;
252
+ const cx = w / 2;
253
+ const cy = hgt / 2;
254
+ const r0 = 36;
255
+ const rMax = 150;
256
+ const words = props.words.length > 0 ? props.words : props.points.map((point) => point.word);
257
+ const gap = 0.02;
258
+ const start = -Math.PI / 2;
259
+ const byWord = new Map(props.points.map((point) => [point.word, point]));
260
+ const clamp01 = (value) => Math.max(0, Math.min(1, Number.isFinite(value) ? value : 0));
261
+ /**
262
+ * **角度按数值分配**:谁大谁占得多,合起来正好一整圈,所以环永远是满的。
263
+ *
264
+ * 之前我做的是"角度等分、只让半径变长"——那是另一种图,看着就是每块一样宽、
265
+ * 剩下的槽位空着(用户两次点出这件事:"色块没有铺满整个圆环")。
266
+ * 代价:角度会随数值变化重排,不再有"同一情绪永远在同一格"的可比性,
267
+ * 换来的是他要的观感。
268
+ */
269
+ const total = words.reduce((sum, word) => sum + clamp01(byWord.get(word)?.strength ?? 0), 0);
270
+ /**
271
+ * 一个词的说明文字。扇区与它的标签**共用同一份**——
272
+ * 用户明确说过"悬浮在文字上没有任何显示",所以标签也必须挂同一组说明。
273
+ */
274
+ const linesOf = (word) => {
275
+ const point = byWord.get(word);
276
+ const strength = clamp01(point?.strength ?? 0);
277
+ return [
278
+ `${word} 强度 ${strength.toFixed(2)}`,
279
+ point?.inner === undefined || point.inner === '' ? '' : point.inner,
280
+ strength >= 0.02
281
+ ? point?.because === undefined || point.because === ''
282
+ ? '为什么这么高:这一条是升级前点起来的,当时没记下缘由。'
283
+ : `为什么这么高:最近一次是「${point.because}」。`
284
+ : '这个情绪现在没被点起来。',
285
+ point === undefined
286
+ ? ''
287
+ : `这一段被点起过 ${point.count ?? 0} 次${point.lastAt === undefined ? '' : `,最近一次 ${hhmm(point.lastAt)}`}。`,
288
+ ].filter((line) => line !== '');
289
+ };
290
+ const parts = [];
291
+ // 第一遍:画扇区,同时把"要标标签的"收集起来——标签位置得整体避让,不能边算边放
292
+ const labels = [];
293
+ let cursor = start;
294
+ words.forEach((word, index) => {
295
+ const strength = clamp01(byWord.get(word)?.strength ?? 0);
296
+ const span = total <= 0 ? 0 : (strength / total) * Math.PI * 2;
297
+ // 没数值的情绪不占角度(它没有强度,占一格就等于替它编了一个份额)
298
+ if (span <= 0.0005)
299
+ return;
300
+ const a0 = cursor + gap / 2;
301
+ const a1 = cursor + span - gap / 2;
302
+ cursor += span;
303
+ const end = Math.max(a1, a0 + 0.002); // 极窄的扇区也要留一丝可见的边
304
+ const mid = (a0 + end) / 2;
305
+ parts.push(h('path', {
306
+ key: `s${index}`,
307
+ d: ringSector(cx, cy, r0, rMax, a0, end),
308
+ fill: emotionColor(word),
309
+ ...hoverTip(linesOf(word)),
310
+ }));
311
+ // **每个有数值的都标**:之前砍到"最强 6 个 + 强度 ≥0.12",于是有几块没标签(用户点出来了)
312
+ const side = Math.cos(mid) >= 0 ? 1 : -1;
313
+ labels.push({
314
+ index,
315
+ word,
316
+ strength,
317
+ side,
318
+ x: cx + side * (rMax + 30),
319
+ y: cy + Math.sin(mid) * (rMax + 10),
320
+ from: [cx + Math.cos(mid) * (rMax + 3), cy + Math.sin(mid) * (rMax + 3)],
321
+ });
322
+ });
323
+ // 第二遍:同侧标签按 y 排序后强制最小间距(角度接近的几根不推开会叠成一坨),再画引线
324
+ for (const side of [-1, 1]) {
325
+ const group = labels.filter((label) => label.side === side).sort((a, b) => a.y - b.y);
326
+ const MIN_GAP = 23;
327
+ for (let i = 1; i < group.length; i += 1) {
328
+ const prev = group[i - 1];
329
+ const cur = group[i];
330
+ if (cur.y - prev.y < MIN_GAP)
331
+ cur.y = prev.y + MIN_GAP;
332
+ }
333
+ for (const label of group) {
334
+ const y = Math.max(16, Math.min(hgt - 8, label.y));
335
+ const elbowX = cx + label.side * (rMax + 12);
336
+ // 引线:扇区外缘 → 拐点 → 标签前的一小段横线。没有它,读者不知道这个标签属于哪块
337
+ parts.push(h('path', {
338
+ key: `g${label.index}`,
339
+ d: `M ${label.from[0].toFixed(1)} ${label.from[1].toFixed(1)} ` +
340
+ `L ${elbowX.toFixed(1)} ${y.toFixed(1)} ` +
341
+ `L ${(label.x - label.side * 5).toFixed(1)} ${y.toFixed(1)}`,
342
+ fill: 'none',
343
+ stroke: 'rgba(150,150,160,0.4)',
344
+ strokeWidth: 1,
345
+ }));
346
+ parts.push(h('text', {
347
+ key: `t${label.index}`,
348
+ x: label.x,
349
+ y: y + 3,
350
+ // 字号按 viewBox 单位给:图会被缩放到卡片宽,所以要比"屏幕目标字号"大一号。
351
+ // 15 号 + 深灰(#6b7280 那一档)——原来 13 号配浅灰,视力差一点就糊了。
352
+ fontSize: 15,
353
+ fill: '#6b7280',
354
+ textAnchor: label.side > 0 ? 'start' : 'end',
355
+ ...hoverTip(linesOf(label.word)),
356
+ }, `${label.word} ${label.strength.toFixed(2)}`));
357
+ }
358
+ }
359
+ const top = props.points.reduce((best, point) => (best === null || point.strength > best.strength ? point : best), null);
360
+ // 内孔直径就 44px:只写"词名 + 数值"两行刚好填满;写"最强 焦虑 0.94"会横着顶出孔外
361
+ parts.push(h('text', { key: 'c1', x: cx, y: cy - 3, fontSize: 19, fill: '#4b5563', textAnchor: 'middle' }, top === null ? '平静' : top.word));
362
+ // 中心只写词名:数值在它自己的标签上已经有一次了,同一个数写两遍只是噪音
363
+ if (top !== null) {
364
+ parts.push(h('text', { key: 'c2', x: cx, y: cy + 18, fontSize: 11, fill: '#9ca3af', textAnchor: 'middle' }, '最强'));
365
+ }
366
+ // 外面套一层 `aspect-ratio` 容器:它的高度由宽度和这个比例算出来,
367
+ // 里面的 SVG 用 width/height 100% 填满。之前直接给 svg 设 `height: auto`,
368
+ // 宿主里没按 viewBox 换算,结果图只渲染出 430×260、四周全是空白。
369
+ return h('div', { key: 'rose', style: { width: '100%', aspectRatio: `${w} / ${hgt}`, margin: '4px 0 6px' } }, h('svg', {
370
+ viewBox: `0 0 ${w} ${hgt}`,
371
+ preserveAspectRatio: 'xMidYMid meet',
372
+ style: { display: 'block', width: '100%', height: '100%' },
373
+ }, ...parts));
374
+ }
375
+ /**
376
+ * 三角雷达:三个轴都是 0–1 的独立刻度,画两层——**出厂基线(0.5 的正三角,灰虚线)**与**当前值**。
377
+ *
378
+ * 雷达只在这"固定少数几轴"的场合成立。拿它画 14 个情绪会变成蜘蛛网,
379
+ * 而且闭合多边形会让相邻的词看着"有关联",那是误导。
380
+ */
381
+ function RadarChart(props) {
382
+ // 画布要比圆大一圈:三个轴端外侧都要放"名字 + 数值",按 240 见方的话左右两个标签会出界
383
+ // 同玫瑰图:比例贴近卡片、半径按高度算,别让三角缩在中间
384
+ const w = 500;
385
+ const hgt = 380;
386
+ const cx = w / 2;
387
+ const cy = hgt / 2 + 6;
388
+ const rMax = 132;
389
+ const n = Math.max(3, props.axes.length);
390
+ const angle = (index) => -Math.PI / 2 + (Math.PI * 2 * index) / n;
391
+ const pt = (index, value) => {
392
+ const r = rMax * Math.max(0, Math.min(1, Number.isFinite(value) ? value : 0));
393
+ return [cx + r * Math.cos(angle(index)), cy + r * Math.sin(angle(index))];
394
+ };
395
+ const poly = (values) => values.map((value, index) => pt(index, value).map((v) => v.toFixed(1)).join(',')).join(' ');
396
+ const parts = [];
397
+ // 三层网格 + 外圈:给"0.62 大概在哪"一个参照
398
+ for (const level of [0.25, 0.5, 0.75, 1]) {
399
+ parts.push(h('polygon', {
400
+ key: `g${level}`,
401
+ points: poly(props.axes.map(() => level)),
402
+ fill: 'none',
403
+ stroke: 'rgba(140,140,150,0.18)',
404
+ strokeWidth: 1,
405
+ }));
406
+ }
407
+ props.axes.forEach((_, index) => {
408
+ const [x, y] = pt(index, 1);
409
+ parts.push(h('line', { key: `sp${index}`, x1: cx, y1: cy, x2: x, y2: y, stroke: 'rgba(140,140,150,0.22)', strokeWidth: 1 }));
410
+ });
411
+ // 出厂基线:三个轴都是 0.5
412
+ parts.push(h('polygon', {
413
+ key: 'base',
414
+ points: poly(props.axes.map(() => 0.5)),
415
+ fill: 'none',
416
+ stroke: 'rgba(140,140,150,0.5)',
417
+ strokeWidth: 1,
418
+ strokeDasharray: '4 3',
419
+ }));
420
+ parts.push(h('polygon', {
421
+ key: 'now',
422
+ points: poly(props.axes.map((axis) => axis.value)),
423
+ fill: 'rgba(90,120,200,0.16)',
424
+ stroke: '#5A78C8',
425
+ strokeWidth: 1.8,
426
+ }));
427
+ props.axes.forEach((axis, index) => {
428
+ const [x, y] = pt(index, axis.value);
429
+ const hover = axis.tip === undefined ? {} : hoverTip(axis.tip);
430
+ parts.push(h('circle', { key: `d${index}`, cx: x, cy: y, r: 4.5, fill: '#5A78C8', ...hover }));
431
+ // 3px 的点几乎没有可点面积(用户原话:「右侧这个人设,也没有任何显示」):
432
+ // 给顶点套一个透明的 12px 热区,鼠标扫过就有说明。
433
+ parts.push(h('circle', { key: `h${index}`, cx: x, cy: y, r: 12, fill: 'transparent', ...hover }));
434
+ // 标签摆到轴端外侧,数值直接跟着标签——雷达读不出精确值,只能靠文字补
435
+ const [ex, ey] = pt(index, 1);
436
+ const dx = (ex - cx) / rMax;
437
+ const dy = (ey - cy) / rMax;
438
+ parts.push(h('text', {
439
+ key: `l${index}`,
440
+ x: cx + dx * (rMax + 22),
441
+ y: cy + dy * (rMax + 22) + 3,
442
+ fontSize: 15,
443
+ fill: '#6b7280',
444
+ textAnchor: Math.abs(dx) < 0.2 ? 'middle' : dx > 0 ? 'start' : 'end',
445
+ // 轴端文字也是悬浮热区:文字比圆点大得多,最容易命中
446
+ ...hover,
447
+ }, `${axis.label} ${axis.value.toFixed(2)}`));
448
+ // 第二行写"这一档是什么样"(偏长 / 偏冷 / 偏铺垫 / 只答所问):
449
+ // 光有 0.30 这种数字,读者没法判断它是多是少。
450
+ if (axis.note !== undefined) {
451
+ parts.push(h('text', {
452
+ key: `n${index}`,
453
+ x: cx + dx * (rMax + 22),
454
+ y: cy + dy * (rMax + 22) + 18,
455
+ fontSize: 12,
456
+ fill: '#9ca3af',
457
+ textAnchor: Math.abs(dx) < 0.2 ? 'middle' : dx > 0 ? 'start' : 'end',
458
+ ...hover,
459
+ }, axis.note));
460
+ }
461
+ });
462
+ return h('div', { key: 'radar', style: { width: '100%', aspectRatio: `${w} / ${hgt}`, margin: '4px 0 6px' } }, h('svg', {
463
+ viewBox: `0 0 ${w} ${hgt}`,
464
+ preserveAspectRatio: 'xMidYMid meet',
465
+ style: { display: 'block', width: '100%', height: '100%' },
466
+ }, ...parts));
467
+ }
468
+ /** 时间戳 → `14:32`(不走 toLocaleTimeString:面板不该被运行环境的语言/时区设置改写格式)。 */
469
+ function hhmm(at) {
470
+ if (at === undefined || !Number.isFinite(at) || at <= 0)
471
+ return '';
472
+ const date = new Date(at);
473
+ const pad = (value) => String(value).padStart(2, '0');
474
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
475
+ }
476
+ /**
477
+ * 这个元素(或它内部真正做截断的那一块)**到底有没有被省略号吃掉**。
478
+ *
479
+ * 为什么要实测而不是看配置:`-webkit-line-clamp: 2` 挂在每个条目上,但短的那几条根本
480
+ * 没被裁——配置在、省略没发生。那时还弹浮层,弹出来的是一模一样的内容,纯粹挡视线。
481
+ *
482
+ * 判据用 `scrollWidth/Height` 与 `clientWidth/Height` 的差(留 1px 容差,
483
+ * 有些浏览器会因为舍入差一点点)。SVG 元素没有这两个属性,直接跳过——图表标签的
484
+ * 说明是靠 `hoverTip` 无条件弹的,不归这条规则管。
485
+ */
486
+ function isTruncated(root) {
487
+ const nodes = [root, ...Array.from(root.querySelectorAll('*'))];
488
+ for (const node of nodes) {
489
+ const box = node;
490
+ if (typeof box.scrollWidth !== 'number' || typeof box.clientWidth !== 'number')
491
+ continue;
492
+ if (box.scrollWidth > box.clientWidth + 1)
493
+ return true;
494
+ if (typeof box.scrollHeight === 'number' && typeof box.clientHeight === 'number') {
495
+ if (box.scrollHeight > box.clientHeight + 1)
496
+ return true;
497
+ }
498
+ }
499
+ return false;
500
+ }
501
+ /**
502
+ * 图表元素怎么"悬浮出说明"。
503
+ *
504
+ * 复用 `?` 徽标那套浮层(同一处渲染、同一套"移走立刻消失"),只是把触发点从图标换成
505
+ * 图表元素本身:玫瑰的扇区、雷达的顶点、心境那几条都能挂。
506
+ * 坐标取元素的实时视口位置,靠右往左让、靠下往上让,免得浮层被裁掉。
507
+ */
508
+ function hoverTip(lines) {
509
+ return {
510
+ onMouseEnter: (event) => {
511
+ const target = event?.currentTarget;
512
+ const rect = target?.getBoundingClientRect?.();
513
+ if (rect === undefined)
514
+ return;
515
+ setTip({
516
+ lines,
517
+ x: Math.max(8, Math.min(rect.left, window.innerWidth - 360)),
518
+ y: Math.min(rect.bottom + 6, window.innerHeight - 140),
519
+ pinned: false,
520
+ });
521
+ },
522
+ onMouseLeave: () => {
523
+ if (tipState !== undefined && !tipState.pinned)
524
+ setTip(undefined);
525
+ },
526
+ };
527
+ }
528
+ /**
529
+ * 只在**真的被裁掉**时才弹的悬浮(内容类条目用它)。
530
+ *
531
+ * 规则:配了 `line-clamp` 不等于被裁——短的条目本来就装得下,这时弹出来只是把同一段话
532
+ * 再说一遍,还挡视线。所以进鼠标的那一刻实测一次(见 `isTruncated`),没裁就什么都不弹。
533
+ * 说明类悬浮(图表标签、轴含义、徽标)仍然用 `hoverTip`:它们弹的不是重复内容。
534
+ */
535
+ function hoverTipIfClamped(lines) {
536
+ const base = hoverTip(lines);
537
+ return {
538
+ onMouseEnter: (event) => {
539
+ const target = event?.currentTarget;
540
+ if (!target)
541
+ return;
542
+ if (!isTruncated(target))
543
+ return;
544
+ base.onMouseEnter(event);
545
+ },
546
+ onMouseLeave: base.onMouseLeave,
547
+ };
548
+ }
549
+ /**
550
+ * 把 0–1 的刻度翻成一句人话:0.5 附近算"正常",两侧各给一个方向词。
551
+ *
552
+ * 面板上光有 0.30 / 0.70 这些数字,读者判断不了"这是多还是少、偏哪边"——
553
+ * 所以每根轴都要配一个词(偏长 / 偏冷 / 偏铺垫 / 只答所问)。
554
+ */
555
+ function voiceWord(value, low, high) {
556
+ if (value >= 0.6)
557
+ return high;
558
+ if (value <= 0.4)
559
+ return low;
560
+ return '正常';
561
+ }
562
+ /** 带正负号的数值(效价那种 −1~1 的)。 */
563
+ function signed(value) {
564
+ return `${value >= 0 ? '+' : ''}${value.toFixed(2)}`;
565
+ }
566
+ /** 时间戳 → `2026-11-05`(不用 toLocaleDateString:面板不该被运行环境的语言设置影响)。 */
567
+ function dayOf(at) {
568
+ if (!Number.isFinite(at) || at <= 0)
569
+ return '';
570
+ const date = new Date(at);
571
+ const pad = (value) => (value < 10 ? `0${value}` : String(value));
572
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
573
+ }
574
+ /** 时间戳 → `11-06 13:23`(要的是"它这条是不是刚写的",精确到分钟就够)。 */
575
+ function clockOf(at) {
576
+ if (!Number.isFinite(at) || at <= 0)
577
+ return '';
578
+ const date = new Date(at);
579
+ const pad = (value) => (value < 10 ? `0${value}` : String(value));
580
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
581
+ }
582
+ /**
583
+ * 「当前想法」卡里内心记录那一段的小标题。
584
+ *
585
+ * 说「最近一次」而不是「这一轮」:`state.thought` 存的是它**最近**写下的那一条,
586
+ * 可能已经是几天前的了(原来的小标题写"它这一轮的",等于在骗读者)。
587
+ * 拿不到时间就只说"它写下的"——不知道就说不知道,不编。
588
+ */
589
+ function thoughtTitle(view) {
590
+ const stamp = clockOf(typeof view.thoughtAt === 'number' ? view.thoughtAt : 0);
591
+ return stamp === '' ? '它写下的内心记录' : `它最近一次写下的内心记录(${stamp})`;
592
+ }
593
+ /**
594
+ * 环形图。
595
+ *
596
+ * 用 `stroke-dasharray` 拼弧:每个扇区画成一个圆,只让其中一段显形。
597
+ * 比手算 `path` 的弧线坐标短得多,也不会在 100% 和 0% 这两个极端上画歪。
598
+ */
599
+ function Donut(props) {
600
+ const size = typeof props.size === 'number' ? props.size : 132;
601
+ const stroke = 13;
602
+ const radius = (size - stroke) / 2;
603
+ const circumference = 2 * Math.PI * radius;
604
+ const total = props.slices.reduce((sum, slice) => sum + Math.max(0, slice.value), 0);
605
+ let carried = 0;
606
+ const arcs = props.slices.map((slice, index) => {
607
+ const length = total > 0 ? (Math.max(0, slice.value) / total) * circumference : 0;
608
+ const arc = h('circle', {
609
+ key: `arc${index}`,
610
+ cx: size / 2,
611
+ cy: size / 2,
612
+ r: radius,
613
+ fill: 'none',
614
+ stroke: slice.color,
615
+ strokeWidth: stroke,
616
+ strokeDasharray: `${length} ${Math.max(0, circumference - length)}`,
617
+ strokeDashoffset: -carried,
618
+ });
619
+ carried += length;
620
+ return arc;
621
+ });
622
+ return h('div', { style: { ...S.donutWrap, width: size, height: size } }, h('svg', { key: 'svg', width: size, height: size, viewBox: `0 0 ${size} ${size}`, style: { transform: 'rotate(-90deg)' } }, ...arcs), h('div', { key: 'center', style: S.donutCenter }, props.center ?? ''));
623
+ }
624
+ /**
625
+ * 一根横条:`value` 落在 `[min, max]` 上的位置。
626
+ *
627
+ * `band` 是"允许漂移的带宽"(说话习惯那种 0.5±0.2)——它在轨道里画成一段半透明区间,
628
+ * 于是"现在偏了多少、还能偏多远"一眼能看出来,不用读数字。
629
+ */
630
+ function Bar(props) {
631
+ const min = typeof props.min === 'number' ? props.min : 0;
632
+ const max = typeof props.max === 'number' ? props.max : 1;
633
+ const span = max - min === 0 ? 1 : max - min;
634
+ // 值 → [0,1] 的比例。图里所有位置都从这一个函数算,免得条和刻度各算一套。
635
+ const ratio = (value) => Math.max(0, Math.min(1, (value - min) / span));
636
+ const at = (value) => `${ratio(value) * 100}%`;
637
+ const layers = [h('div', { key: 'track', style: S.barTrack })];
638
+ // 允许漂移的带宽**只画两条边界刻度**,不画成一段色块。
639
+ // 画成色块时,带内(0.3–0.7)比带外更"实",于是填充条看起来像延长到了 0.7,
640
+ // 右边剩下的那点就觉得不够 0.33(用户就是照这个问的);而「此刻」那四条没有带宽,
641
+ // 两张卡于是像两套皮。现在两边共用同一条轨道、同一套填充,带宽只剩两道细刻度。
642
+ if (props.band !== undefined) {
643
+ const lo = ratio(props.band.center - props.band.half);
644
+ const hi = ratio(props.band.center + props.band.half);
645
+ layers.push(h('div', { key: 'lo', style: { ...S.bandTick, left: `${lo * 100}%` } }));
646
+ layers.push(h('div', { key: 'hi', style: { ...S.bandTick, left: `${hi * 100}%` } }));
647
+ }
648
+ // 跨零的量(效价 −1~1)从**中间**往两边长,并画一条零刻度:
649
+ // 否则 −1 那半截看着像"没走完的空档",+0.06 也被画成半个条(用户就是照这个问"最大应该是 1 吧")。
650
+ if (min < 0 && max > 0) {
651
+ const from = ratio(Math.min(0, props.value));
652
+ const to = ratio(Math.max(0, props.value));
653
+ // 值贴着 0 时宽度会小到看不见,给 1.2% 的下限,让它至少还是"零刻度旁边的一点",而不是消失
654
+ layers.push(h('div', { key: 'fill', style: { ...S.barFill, left: `${from * 100}%`, width: `${Math.max((to - from) * 100, 1.2)}%` } }));
655
+ layers.push(h('div', { key: 'mid', style: { ...S.barMid, left: at(0) } }));
656
+ }
657
+ else {
658
+ layers.push(h('div', { key: 'fill', style: { ...S.barFill, width: at(props.value) } }));
659
+ }
660
+ // 额外刻线画在最上层:它要说的是"出厂线在哪",被填充条压住就没意义了
661
+ if (typeof props.tick === 'number') {
662
+ layers.push(h('div', { key: 'tick', style: { ...S.bandTick, left: at(props.tick), background: 'rgba(130,130,140,0.8)' } }));
663
+ }
664
+ return h('div', { style: S.barRow, ...(props.tip === undefined ? {} : hoverTip(props.tip)) }, h('div', { key: 'label', style: S.barLabel }, h('span', { key: 'n' }, props.name), h('span', { key: 'v', style: S.barValue }, props.fmt === undefined ? props.value.toFixed(2) : props.fmt(props.value))), h('div', { key: 'wrap', style: S.barWrap }, ...layers));
665
+ }
666
+ /**
667
+ * 给视图补上缺的字段。
668
+ *
669
+ * 为什么需要:**宿主那半边改了、而会话还没重启**时,客户端拿到的仍是旧视图(没有 mood / longGroups 这些新字段),
670
+ * 页面会直接崩在 `view.longGroups.map` 上。缺字段就按"没有"处理,比让整页白屏好得多。
671
+ */
672
+ function normalizeView(view) {
673
+ return {
674
+ ...view,
675
+ emotions: Array.isArray(view.emotions) ? view.emotions : [],
676
+ sections: Array.isArray(view.sections) ? view.sections : [],
677
+ shortMemory: Array.isArray(view.shortMemory) ? view.shortMemory : [],
678
+ shortGroups: Array.isArray(view.shortGroups) ? view.shortGroups : [],
679
+ longGroups: Array.isArray(view.longGroups) ? view.longGroups : [],
680
+ memoryKinds: Array.isArray(view.memoryKinds) ? view.memoryKinds : [],
681
+ sessionMemory: Array.isArray(view.sessionMemory) ? view.sessionMemory : [],
682
+ };
683
+ }
684
+ /**
685
+ * 旧视图的提示语。
686
+ *
687
+ * 此刻与人设那两张卡的数字来自**后加的**字段(`mood` / `voice`)。宿主那半边换了、而会话没重启时,
688
+ * 客户端拿到的仍是旧视图:这几个字段根本不存在。
689
+ *
690
+ * 第一版在这里填了 0 和 0.5 当兜底,于是页面上出现了一排**看着很正常、其实是编出来的数字**——
691
+ * 用户拿截图来问"这四条是什么",我才发现它骗了人。宁可什么都不画,直说"重启这个会话之后才有"。
692
+ */
693
+ const STALE_HOST = '页面还是旧版本,重启这个会话之后这里才会有数。';
694
+ /** 一条记忆:类型徽标 + 来源 + 正文 + 凭什么记着。 */
695
+ function MemoryRow(props) {
696
+ const entry = props.entry;
697
+ const meta = [];
698
+ // "被翻到"而不是"取回":后者是内部动词(recall 的直译),给人看不像话
699
+ if (entry.hits > 0)
700
+ meta.push(h('span', { key: 'hits', style: S.memMeta }, `被翻到 ${entry.hits} 次`));
701
+ if (dayOf(entry.at) !== '')
702
+ meta.push(h('span', { key: 'day', style: S.memMeta }, dayOf(entry.at)));
703
+ // 三档来源:它自己记的 / 收尾时按规则拼的 / 听来的原话。拼的那一档**不能算它说的**,
704
+ // 也不能混进"听来的原话"里——用户一眼就能认出机器味的句子(v2.2)。
705
+ const src = entry.origin === 'self'
706
+ ? { label: '它自己记的', style: S.srcSelf }
707
+ : entry.origin === 'digest'
708
+ ? { label: '收尾时拼的', style: S.srcHeard }
709
+ : { label: '听来的原话', style: S.srcHeard };
710
+ // "因为什么记着"从常显改成**悬浮**:面板上每条记忆都多一行「因为:它自己记下的」,
711
+ // 四条就把一屏吃掉,而那行几乎从不提供新信息("它自己记的"徽标已经说过一遍)。
712
+ // 内容没删——鼠标移上去还在。
713
+ const tip = [
714
+ entry.text,
715
+ entry.because === '' ? '' : `因为:${entry.because}`,
716
+ ...(entry.hits > 0 ? [`被翻到过 ${entry.hits} 次`] : []),
717
+ ...(dayOf(entry.at) === '' ? [] : [`记于 ${dayOf(entry.at)}`]),
718
+ ].filter((line) => line !== '');
719
+ return h('li',
720
+ // 正文不截断时不弹(弹出来只是把同一段话再说一遍);将来若给它加 clamp,这条自动生效
721
+ { style: S.memRow, ...hoverTipIfClamped(tip) }, h('div', { key: 'top', style: S.memTop }, h('span', { key: 'kind', style: S.badge }, entry.label), h('span', { key: 'src', style: src.style }, src.label),
722
+ // 次数与日期推到行尾:它们不该跟正文抢注意力
723
+ h('span', { key: 'sp', style: { marginLeft: 'auto' } }), ...meta), h('div', { key: 'text', style: S.memText }, entry.text));
724
+ }
725
+ /** 折叠组下面那句说明:同一档含义只在这里说一次。 */
726
+ // 这些是给人看的说明,不是字段解释:一律用"项目/会话/关于你"这些日常说法,
727
+ // 不出现"工作区""老档案""scope"这种内部词。
728
+ const FOLD_NOTE = {
729
+ here: '只在这个项目里成立,换个项目就不带过去。',
730
+ unknown: '很早以前记的,那时候还不分项目,所以哪儿都看得见——但别当成"关于你"的。',
731
+ ungrouped: '来自一个没有选项目的会话,跟别的会话里说过的不是一回事,所以单独列。',
732
+ global: '跟项目无关的事(关于"你"的偏好),在哪个项目里都成立。',
733
+ other: '别的项目里说过的话,看得见,但不带过来。',
734
+ };
735
+ /**
736
+ * 一组记忆的组头该写什么。
737
+ *
738
+ * 用户两次点过同一件事:光看标题不知道这些记忆是哪个工作区的。所以这里的规矩是
739
+ * **每一组都要自己说清出处**:
740
+ * · 绑了工作区的组,标题就是那个项目路径;别的项目再加一个「其他项目」徽标。
741
+ * · 未分组会话的组,标题是**那个会话的名字**(拿 `sessionId` 去会话列表里查),
742
+ * 再挂「会话未分组」徽标说明它凭什么单独成组。查不到标题就写 `会话 xxxxxx`,不编。
743
+ * · 老档案与全局各有自己的徽标,含义见 `FOLD_NOTE`。
744
+ *
745
+ * 标题与徽标都在这里算,调用处只负责传 `ctx`:两处折叠(当前想法 / 记忆)必须一致。
746
+ */
747
+ function groupHeadOf(ctx, group) {
748
+ if (group.scope === 'ungrouped') {
749
+ const id = group.sessionId;
750
+ const title = id === undefined ? group.label : (sessionTitle(ctx, id) ?? `会话 ${id.slice(0, 8)}`);
751
+ return { title, badge: '会话未分组' };
752
+ }
753
+ if (group.scope === 'unknown')
754
+ return { title: group.label, badge: '早于工作区绑定' };
755
+ if (group.scope === 'other')
756
+ return { title: group.label, badge: '其他项目' };
757
+ if (group.scope === 'global')
758
+ return { title: group.label, badge: '跨项目' };
759
+ return { title: group.label };
760
+ }
761
+ /**
762
+ * 可折叠的一段(「当前想法」按项目 / 按会话折叠就是用这个)。
763
+ *
764
+ * 为什么不用 `<details>`:页面每 2 秒重渲染一次,`open` 作为属性会被 React 每次写回原值,
765
+ * 用户刚展开的那一组会被自动合上。折叠状态必须攥在自己手里。
766
+ *
767
+ * `badge` 与 `subtitle` 是给"这一组凭什么算一组"用的:绑了工作区的组,标题就是项目路径;
768
+ * 未分组会话的组,标题是那个会话的名字,再用徽标说明"它是因为会话没选工作区才单独成组的"。
769
+ */
770
+ function Fold(props) {
771
+ const [open, setOpen] = react.useState(props.defaultOpen === true);
772
+ return h('div', { key: props.id, style: S.fold }, h('div', { key: 'head', style: S.foldHead, onClick: () => setOpen(!open) },
773
+ // 三角和标题必须在**同一个** span 里:`foldHead` 是两头布局(space-between),
774
+ // 三个并列的孩子会把标题挤到正中间——用户看到的就是"工作区名字居中"。
775
+ h('span', { key: 'label', style: S.foldLabel }, h('span', { key: 'caret', style: S.foldCaret }, open ? '▾' : '▸'), h('span', { key: 'title', style: S.foldTitle }, props.title), props.badge === undefined ? null : h('span', { key: 'badge', style: S.foldBadge }, props.badge)), h('span', { key: 'count', style: S.foldCount }, `${props.count} 条`)), props.subtitle === undefined ? null : h('p', { key: 'sub', style: S.foldSub }, props.subtitle), open ? h('div', { key: 'body', style: S.foldBody }, ...props.children) : null, props.note === undefined ? null : h('p', { key: 'note', style: S.foldNote }, props.note));
776
+ }
777
+ /**
778
+ * 数值怎么读。
779
+ *
780
+ * 这几行是**刻度说明**(UI 帮助文本),不是它的状态内容,所以放在客户端。
781
+ *
782
+ * 第一版是页面底部一张常驻的"数值怎么读"卡,太长、也没人愿意每次往下翻,
783
+ * 现在改成标题右侧那个小问号,悬浮/点一下才展开,而且**分成两组**:
784
+ * 看「此刻」的时候只解释心情那些数,看「人设」的时候只解释语气那些数。
785
+ *
786
+ * 以后要挪进 core 的视图模型里,让 `/mind` 命令和这个页面共用一份——现在是两处措辞,
787
+ * 迟早会漂。
788
+ */
789
+ /**
790
+ * 「此刻」这块说的是什么。
791
+ *
792
+ * 用户在 m06561 点明过:这两块说明应该是**这个数值系统的介绍**(它由哪些项构成、
793
+ * 每个数的区间与口径),不是评论。所以只写"是什么、有几项、区间多少",
794
+ * 评价性的句子一律不写。
795
+ */
796
+ const TIP_NOW = [
797
+ '环里每一块是一个情绪,**占多大角度=它有多强**,所有块合起来正好一圈。',
798
+ '颜色固定:同一个词永远是同一种颜色。',
799
+ '鼠标放到色块或文字上:它是什么意思、最近因为什么涨起来、这段被点起过几次。',
800
+ '下面四条是心境:效价(难受↔舒服)、唤醒(松↔紧)、支配感、张力。',
801
+ ];
802
+ const TIP_PERSONA = [
803
+ '雷达图:三个轴是说话习惯(简洁 / 温度 / 直给),0–1,出厂都是 0.50。',
804
+ '灰虚线=出厂形状,蓝实线=现在;偏出去多少就是被改了多少。',
805
+ '鼠标放到轴端文字或顶点上:这一轴管什么、偏了多少、还能漂多少。',
806
+ ];
807
+ let tipState;
808
+ const tipWatchers = new Set();
809
+ function setTip(state) {
810
+ tipState = state;
811
+ for (const notify of tipWatchers)
812
+ notify();
813
+ }
814
+ function useTip() {
815
+ // 客户端的 `react` 是运行时 require 来的,类型上只暴露了"直接给值"这一种 setter;
816
+ // 这里要用更新函数(否则闭包里的旧值会让它永远停在 1),所以把类型放宽一下。
817
+ const [, force] = react.useState(0);
818
+ react.useEffect(() => {
819
+ const notify = () => force((n) => n + 1);
820
+ tipWatchers.add(notify);
821
+ return () => {
822
+ tipWatchers.delete(notify);
823
+ };
824
+ }, []);
825
+ return tipState;
826
+ }
827
+ /**
828
+ * 页面根部画一次:没有开着的说明就什么都不画。
829
+ *
830
+ * 参数是页面那边订阅到的值,而不是模块里的 `tipState`——因为**必须有人订阅**才会重画:
831
+ * 第一版只让那张小问号图标订阅,于是鼠标移进/移出只是图标自己重画,浮层得等页面
832
+ * 因为 2 秒轮询或会话事件重画时才跟上,看着就是"要等一会才出来、移走也不立刻消失"。
833
+ */
834
+ function tipLayer(state) {
835
+ if (state === undefined)
836
+ return null;
837
+ return h('div', { key: 'tiplayer', style: { ...S.tipPanel, left: `${state.x}px`, top: `${state.y}px` } }, ...state.lines.map((line, index) => h('div', { key: `t${index}`, style: S.tipLine }, line)));
838
+ }
839
+ /** Esc 关掉钉住的说明。装一次即可,`apply` 里调。 */
840
+ function installTipEscape() {
841
+ const doc = globalThis.document;
842
+ const listen = doc?.addEventListener;
843
+ listen?.('keydown', (event) => {
844
+ if (event?.key === 'Escape' && tipState !== undefined)
845
+ setTip(undefined);
846
+ });
847
+ }
848
+ /**
849
+ * 标题右侧那个小问号:悬浮(或点一下钉住)才把说明展开。
850
+ *
851
+ * 只负责图标本身 —— 浮层在 `tipLayer()` 里画。坐标用按钮的实时视口位置,
852
+ * 靠右时往左让一点,免得浮层跑出屏幕。
853
+ */
854
+ function Tip(props) {
855
+ // 订阅一下,好让"钉住期间点第二次"能正确关掉
856
+ useTip();
857
+ const at = (event) => {
858
+ const target = event?.currentTarget;
859
+ const rect = target?.getBoundingClientRect?.();
860
+ if (rect === undefined)
861
+ return undefined;
862
+ return { x: Math.max(8, Math.min(rect.left, window.innerWidth - 350)), y: rect.bottom + 6 };
863
+ };
864
+ const open = (event, pinned) => {
865
+ const spot = at(event);
866
+ if (spot === undefined)
867
+ return;
868
+ const same = tipState !== undefined && tipState.pinned === pinned && tipState.lines === props.lines;
869
+ // 已经钉住时再点一次 = 关掉
870
+ setTip(same && pinned ? undefined : { lines: props.lines, ...spot, pinned });
871
+ };
872
+ return h('span', {
873
+ key: 'tipWrap',
874
+ style: S.tipWrap,
875
+ onMouseLeave: () => {
876
+ if (tipState !== undefined && !tipState.pinned)
877
+ setTip(undefined);
878
+ },
879
+ }, h('span', {
880
+ key: 'icon',
881
+ style: S.tipIcon,
882
+ onMouseEnter: (event) => open(event, false),
883
+ // 点一下钉住(触屏上 tap 不一定先来 mouseenter;做成"点了就没了"反而更糟)
884
+ onClick: (event) => open(event, true),
885
+ }, '?'));
886
+ }
887
+ /** 中间那一栏的状态页:一句话现状 + 四区,外加"没话说"时的自查线索。 */
888
+ function MindPage(props) {
889
+ // 正常情况下来自座位注入(见 `apply` 里的 `inject`);真拿不到就按"没有状态"如实显示,不编。
890
+ const ctx = props?.ctx;
891
+ const [found, setFound] = react.useState(undefined);
892
+ const [seen, setSeen] = react.useState(false);
893
+ // 页面自己也订阅一遍说明浮层的状态:浮层是这一页画的,不订阅就得等下一次轮询才跟上
894
+ // (用户原话:"不是悬浮后立刻显示的,而是要等一会,而且鼠标移走也不会立刻消失")。
895
+ const tip = useTip();
896
+ react.useEffect(() => {
897
+ let alive = true;
898
+ const refresh = () => {
899
+ if (!alive)
900
+ return;
901
+ setFound(resolveSession(ctx, props?.sessionId));
902
+ setSeen(true);
903
+ };
904
+ refresh();
905
+ const off = subscribe(ctx, refresh);
906
+ // 兜底轮询:万一套位的订阅口以后变了形状,页面也不会僵在那里(2 秒一次,纯本地读,零网络)。
907
+ const timer = window.setInterval(refresh, 2000);
908
+ return () => {
909
+ alive = false;
910
+ off();
911
+ window.clearInterval(timer);
912
+ };
913
+ }, [ctx, props?.sessionId]);
914
+ // 页面顶部只留标题:会话 id 前缀、折叠了多少事件、"不进对话"这类都是内部说明,
915
+ // 不是给读者看的(用户点名删掉)。空状态的说明留在各卡片里,哪儿缺就说哪儿。
916
+ const head = h('header', { key: 'head', style: S.head }, h('h1', { key: 't', style: S.title }, '心念'));
917
+ /**
918
+ * 页面按**用途**分三个 tab:此刻(状态)/ 想法(桌面 + 这段的流水账)/ 记忆(要自己查的那批)。
919
+ *
920
+ * 为什么分:内容一多,一屏同时挤着图表、记忆、日记、内心记录,既扫不出重点也不好找东西。
921
+ * tab 先把用途分开,块内再折叠(`Fold`)——层级只有两级,不玩第三级。
922
+ */
923
+ const [tab, setTab] = react.useState('now');
924
+ const tabNow = [];
925
+ const tabThink = [];
926
+ const tabMemory = [];
927
+ const body = [];
928
+ if (!seen) {
929
+ body.push(h('p', { key: 'reading', style: S.sub }, '正在读…'));
930
+ }
931
+ else if (found === undefined) {
932
+ body.push(h('section', { key: 'none', style: S.card }, h('h2', { key: 'h', style: S.cardTitle }, '这个会话还没有状态'), h('ul', { key: 'u', style: S.list }, h('li', { key: 'a' }, '状态在事件提交之后才折叠出来——还没走完一个回合时它就是空的。'), h('li', { key: 'b' }, '插件刚装上、或者这个会话是装之前开的(旧会话不会补算)。'), h('li', { key: 'c' }, '会话投影没注册上(headless 里看 ~/.dsh/dsh-mind/mind.log 会有记录)。'))));
933
+ }
934
+ else {
935
+ const view = normalizeView(found.view);
936
+ // 四区的**文字**仍然来自中枢(措辞只有一处真相);这里另外把结构化数据画成图。
937
+ const linesOf = (title) => {
938
+ const section = view.sections.find((item) => item.title === title);
939
+ return section === undefined ? [] : section.lines;
940
+ };
941
+ const asLines = (lines, prefix) => lines.map((line, index) => h('li', { key: `${prefix}${index}`, style: S.line }, line));
942
+ // 顶部那行 `view.summary`("焦虑(1.00)、疲惫(1.00)|张力 0.00")不画了:
943
+ // 同样的信息在下面饼图与条里本来就有,重复一遍只是噪声(用户 m06561 点名删掉)。
944
+ // 这里原来有个 `legend()`:饼图旁边那串"颜色 + 名字 + 数值"。
945
+ // 情绪改气泡(标签画在泡泡旁边)、人设改刻度条之后,只剩记忆种类那块还有环图,
946
+ // 那条图例已经没有调用点——留着就是一段走不到的代码,删掉。
947
+ // ── ① 此刻:情绪环散点(位置=哪种、面积=多强)+ 心境与张力(条)──
948
+ //
949
+ // 这里原来是饼图。饼只能表达"份额",而这些强度各自独立、加起来不等于 1——
950
+ // 画成扇区等于编一份不存在的比例;而且环永远画满,"整体在变弱"这件事根本画不出来。
951
+ const points = view.emotions.filter((item) => item.strength > 0.01);
952
+ const strongest = view.emotions.reduce((best, item) => best === null || item.strength > best.strength ? { word: item.word, strength: item.strength } : best, null);
953
+ const nowCard = h('section', { key: 'now', style: { ...S.card, marginTop: 0 } }, h('h2', { key: 'h', style: S.cardTitle }, '此刻', h(Tip, { key: 'tip', lines: TIP_NOW }), strongest === null
954
+ ? null
955
+ : h('span', { key: 'top', style: { ...S.sub, marginLeft: 'auto', fontSize: '11px' } }, `最强 ${strongest.word} ${strongest.strength.toFixed(2)}`)), points.length > 0
956
+ ? h(RoseChart, { key: 'rose', words: view.emotionWords ?? [], points: view.emotions })
957
+ : h('p', { key: 'calm', style: S.sub }, '此刻没有情绪在。'), view.mood === undefined
958
+ ? h('p', { key: 'stale', style: S.hint }, STALE_HOST)
959
+ : h('div', { key: 'bars', style: S.bars }, h(Bar, {
960
+ key: 'v',
961
+ name: '效价',
962
+ value: view.mood.valence,
963
+ min: -1,
964
+ max: 1,
965
+ fmt: signed,
966
+ tip: [
967
+ `效价(−1~1):方向——左边难受、右边舒服。现在是 ${signed(view.mood.valence)}。`,
968
+ '它不是单独记的:所有被点起的情绪各自往一个方向推,合成一个合力。',
969
+ '负向情绪多,它就往左;正向多,往右。',
970
+ ],
971
+ }), h(Bar, {
972
+ key: 'a',
973
+ name: '唤醒',
974
+ value: view.mood.arousal,
975
+ tip: [
976
+ `唤醒(0~1):松 ↔ 紧。现在是 ${view.mood.arousal.toFixed(2)}。`,
977
+ '事情在推着它走的程度:连着来的一串工具调用、报错、催促会把它顶高;',
978
+ '安静下来(长时间没有新信号)会自己回落。',
979
+ ],
980
+ }), h(Bar, {
981
+ key: 'd',
982
+ name: '支配感',
983
+ value: view.mood.dominance,
984
+ tip: [
985
+ `支配感(0~1):使不使得上劲。现在是 ${view.mood.dominance.toFixed(2)}。`,
986
+ '能不能推动局面:连着失败、被驳回会压低它;自己把问题修好、事情推进会抬高它。',
987
+ ],
988
+ }), h(Bar, {
989
+ key: 't',
990
+ name: '张力',
991
+ value: view.tension,
992
+ tip: [
993
+ `张力(0~1):心里搁着没解决的事。现在是 ${view.tension.toFixed(2)}。`,
994
+ '有事悬着它就高;回合正常收束时会自己降一点。它和情绪是两条线——',
995
+ '情绪是"感觉",张力是"还没落地的事"。',
996
+ ],
997
+ })));
998
+ // ── ② 人设:三条刻度条(当前值 + 出厂线 0.5 + 漂移带 ±drift)──
999
+ //
1000
+ // 这里原来也是饼图。三个轴是**各自独立的刻度**(0.30 / 0.62 / 0.70,加起来不等于 1),
1001
+ // 画成扇区同样是在编比例。刻度条还多一层用处:能画出"离出厂线多远、还能漂多远"。
1002
+ // 出厂基线不进档案(见 types.ts:「出厂基线不在档案里」),所以画的是 0.5 这条出厂线
1003
+ // 加允许漂移带,**不编一个"档案基线"**。
1004
+ const voice = view.voice;
1005
+ const personaCard = h('section', { key: 'persona', style: { ...S.card, marginTop: 0 } }, h('h2', { key: 'h', style: S.cardTitle }, '人设', h(Tip, { key: 'tip', lines: TIP_PERSONA }), voice === undefined
1006
+ ? null
1007
+ : h('span', { key: 'drift', style: { ...S.sub, marginLeft: 'auto', fontSize: '11px' } }, `出厂 0.50|可漂 ±${voice.drift.toFixed(2)}`)), voice === undefined
1008
+ ? h('p', { key: 'stale', style: S.hint }, STALE_HOST)
1009
+ : h(RadarChart, {
1010
+ key: 'radar',
1011
+ axes: [
1012
+ {
1013
+ label: '简洁',
1014
+ value: voice.brevity,
1015
+ note: voiceWord(voice.brevity, '偏长', '偏短'),
1016
+ tip: [
1017
+ `简洁:说话**说多少**。现在是 ${voice.brevity.toFixed(2)}(${voiceWord(voice.brevity, '偏长', '偏短')})。`,
1018
+ '低(0.3):背景、权衡、例子都讲一遍;高(0.7):能一句就一句。',
1019
+ '谁在推它:它自己上一轮说了多少字——超过 1200 字往下压,不到 200 字往上抬。',
1020
+ ],
1021
+ },
1022
+ {
1023
+ label: '温度',
1024
+ value: voice.warmth,
1025
+ note: voiceWord(voice.warmth, '偏冷', '偏暖'),
1026
+ tip: [
1027
+ `温度:说话**什么口气**。现在是 ${voice.warmth.toFixed(2)}(${voiceWord(voice.warmth, '偏冷', '偏暖')})。`,
1028
+ '低(0.3):只给事实、不寒暄;高(0.7):先接住你的情绪再说事。',
1029
+ '谁在推它:你道谢/夸它会暖一点;你驳回或打断它会冷一点。',
1030
+ ],
1031
+ },
1032
+ {
1033
+ label: '直给',
1034
+ value: voice.directness,
1035
+ note: voiceWord(voice.directness, '偏铺垫', '偏直接'),
1036
+ tip: [
1037
+ `直给:说话**什么顺序**。现在是 ${voice.directness.toFixed(2)}(${voiceWord(voice.directness, '偏铺垫', '偏直接')})。`,
1038
+ '低(0.3):先铺垫、再给结论;高(0.7):结论第一、理由随后。',
1039
+ '谁在推它:被驳回 → 少绕弯直接改;同一件事被重复说 → 上一遍没讲清,得铺垫。',
1040
+ ],
1041
+ },
1042
+ {
1043
+ label: '主动',
1044
+ // 旧宿主没有这一根:按出厂 0.5 显示,而不是画一个 0
1045
+ value: voice.initiative ?? 0.5,
1046
+ note: voiceWord(voice.initiative ?? 0.5, '只答所问', '会多给一层'),
1047
+ tip: [
1048
+ `主动:说话**给多大范围**。现在是 ${(voice.initiative ?? 0.5).toFixed(2)}(${voiceWord(voice.initiative ?? 0.5, '只答所问', '会多给一层')})。`,
1049
+ '低(0.3):问什么答什么,不多嘴;高(0.7):会多提一层——提醒、追问、给建议。',
1050
+ '谁在推它:你追问 → 多给一层;你打断 → 说明多嘴了,收着点。',
1051
+ ],
1052
+ },
1053
+ ],
1054
+ }),
1055
+ // 四根轴各管一件不同的事,得写出来——否则看着像三个重复的东西
1056
+ voice === undefined
1057
+ ? null
1058
+ : h('p', { key: 'voicenote', style: S.sub }, '四条轴出厂都是 0.50,偏离多少就是最近几轮改了多少:说多少 / 什么口气 / 什么顺序 / 给多大范围。它们之间没有"综合分"。'), (view.voiceTraits ?? []).length === 0
1059
+ ? null
1060
+ : h('div', { key: 'traits' }, h('h3', { key: 'th', style: S.groupTitle }, '候选自我认知'), h('ul', { key: 'tu', style: S.bulletList },
1061
+ // 每条**两行**、带项目符号:一行的话只剩半句,读者会以为这里只有一条
1062
+ //(用户原话:"我还以为是一条或者两条,结果你这一行是一条")。
1063
+ ...(view.voiceTraits ?? []).map((trait, index) => h('li', {
1064
+ key: `tr${index}`,
1065
+ // 圆点是 li 自己的(list-item),两行截断交给里面的 span——
1066
+ // 两者不能塞进同一个元素:`display: list-item` 和 `-webkit-box` 打架。
1067
+ // 所以这里**不套 S.line**(它就是 -webkit-box),只给 list-item。
1068
+ style: { display: 'list-item', listStyleType: 'disc', marginBottom: '5px' },
1069
+ // 两行装得下就不弹:短条目弹出同一段话只是挡视线
1070
+ ...hoverTipIfClamped([
1071
+ trait.label,
1072
+ `它这么表现过 ${trait.hits} 次${trait.spanDays >= 1 ? `,前后跨了 ${trait.spanDays} 天` : ''}——还不足以写进"我是谁"`,
1073
+ ]),
1074
+ }, h('span', { key: 't', style: S.clamp2 }, trait.label), h('span', { key: 'm', style: { ...S.memMeta, marginLeft: '6px' } }, `见过 ${trait.hits} 次${trait.spanDays >= 1 ? ` / 跨 ${trait.spanDays} 天` : ''}`))))), h('ul', { key: 'u', style: S.list },
1075
+ // 「语气:…」那一行在有饼图时不重复画——同一个数两处出现(一处饼、一处文字),
1076
+ // 反而看不出哪个是准的。饼图缺失(旧宿主)时它还是唯一的信息源,照旧显示。
1077
+ ...asLines(linesOf('人设').filter((line) =>
1078
+ // 「语气」那行在雷达已经在画时不重复列
1079
+ !(voice !== undefined && line.startsWith('语气')) &&
1080
+ // 候选列表已经展开时,不再重复那行"N 条"汇总;旧宿主没送列表时它才兜底
1081
+ !((view.voiceTraits ?? []).length > 0 && line.startsWith('候选自我认知'))), 'p')));
1082
+ // 两张卡并排:宽屏一左一右,窄屏自己折成上下(auto-fit)
1083
+ tabNow.push(h('div', { key: 'row1', style: S.row }, nowCard, personaCard));
1084
+ // ── ③ 当前想法:手边搁着的事,**按项目折叠**(折叠标题就是项目路径)+ 它自己写下的 ──
1085
+ //
1086
+ // 为什么把短期记忆从"记忆"那张卡里挪出来:它不是"存下来的东西",而是此刻手上握着的。
1087
+ // 为什么还要按项目折叠:短记忆跟着档案跨会话活下来,别的项目里说过的话也可能躺在这里。
1088
+ // 以前只写「这个项目的 6 条」,用户没法知道是哪个项目——标题直接写路径。
1089
+ const shortFolds = (() => {
1090
+ const groups = view.shortGroups ?? [];
1091
+ if (groups.length === 0) {
1092
+ // 旧宿主(没送 shortGroups):退回平铺,别让这张卡空着
1093
+ return [
1094
+ h('ul', { key: 'u', style: S.memList }, ...view.shortMemory.map((entry, index) => h(MemoryRow, { key: `e${index}`, entry }))),
1095
+ ];
1096
+ }
1097
+ return groups.map((group, index) => {
1098
+ const head = groupHeadOf(ctx, group);
1099
+ return h(Fold, {
1100
+ key: `f${index}`,
1101
+ id: `f${index}`,
1102
+ title: head.title,
1103
+ badge: head.badge,
1104
+ count: group.count,
1105
+ note: FOLD_NOTE[group.scope] ?? FOLD_NOTE.here,
1106
+ defaultOpen: index === 0,
1107
+ }, group.entries.length > 0
1108
+ ? [
1109
+ h('ul', { key: 'u', style: S.memList }, ...group.entries.map((entry, inner) => h(MemoryRow, { key: `e${inner}`, entry }))),
1110
+ ]
1111
+ : [h('p', { key: 'none', style: S.foldNote }, '这组现在空着。')]);
1112
+ });
1113
+ })();
1114
+ tabThink.push(h('section', { key: 'mind', style: S.card }, h('h2', { key: 'h', style: S.cardTitle }, '当前想法'), h('p', { key: 'sub', style: S.sub }, '每次说话都会带上这几条——都是它自己写下来的,不会抄你的原话。' +
1115
+ '够重要的会被收进「记忆」,那之后就不再自动带上,它想用会自己去翻。'), ...shortFolds, h('h3', { key: 'th', style: S.groupTitle }, thoughtTitle(view)), h('ul', { key: 'u', style: S.list }, ...asLines(linesOf('思想'), 't'))));
1116
+ // ── ③b 本会话日记:只增不改(v2.0 新的一层)──
1117
+ //
1118
+ // 为什么单独一张卡:它的更新方式和另外两层不一样——只往后加、永不改写旧条目,
1119
+ // 所以"这条为什么改不了"必须写在它自己身上,混进别的卡就解释不清。
1120
+ const diary = view.sessionMemory ?? [];
1121
+ // 日记默认收起:它是最"流水账"的一层,占地方但不常看
1122
+ tabThink.push(h(Fold, {
1123
+ key: 'diary',
1124
+ id: 'diary',
1125
+ title: '本会话日记',
1126
+ count: diary.length,
1127
+ note: '这段对话的流水账:只往后加、不改旧条目。换个会话就看不到;'
1128
+ + '别的会话的日记它也能翻,但要它主动去查。',
1129
+ defaultOpen: false,
1130
+ children: diary.length > 0
1131
+ ? [
1132
+ h('ul', { key: 'u', style: S.memList }, ...diary.map((entry, index) => h(MemoryRow, { key: `e${index}`, entry }))),
1133
+ ]
1134
+ : [h('p', { key: 'none', style: S.sub }, '它还没写日记。攒够一段、或者这段对话结束时才会写。')],
1135
+ }));
1136
+ // ── ④ 记忆:短期按这个会话、长期按项目分组 ──
1137
+ const kindSlices = view.memoryKinds.map((item, index) => ({
1138
+ label: item.label,
1139
+ value: item.count,
1140
+ color: PIE_COLORS[index % PIE_COLORS.length],
1141
+ }));
1142
+ const kindTotal = kindSlices.reduce((sum, slice) => sum + slice.value, 0);
1143
+ tabMemory.push(h('section', { key: 'memory', style: S.card }, h('h2', { key: 'h', style: S.cardTitle }, '记忆'), h('p', { key: 'sub', style: S.sub }, '这些不会自动带上,它想用会自己去翻。「当前想法」里够重要的会搬到这里——同一条只在一处。'), kindSlices.length > 0
1144
+ ? h('div', { key: 'pie', style: S.pieRow }, h(Donut, { key: 'd', slices: kindSlices, center: `${kindTotal} 条`, size: 116 }), h('ul', { key: 'lg', style: S.pieLegend }, ...kindSlices.map((slice, index) => h('li', { key: `k${index}`, style: S.pieLegendItem }, h('span', { key: 'dot', style: { ...S.dot, background: slice.color } }), h('span', { key: 'name' }, slice.label), h('span', { key: 'val', style: S.pieValue }, String(slice.value))))))
1145
+ : h('p', { key: 'none', style: S.sub }, '还没有记下任何事。'),
1146
+ // 每组一个折叠(默认只展开第一组):库里的分组一多,全铺开就是一屏流水账
1147
+ ...view.longGroups.map((group, index) => {
1148
+ const groupHead = groupHeadOf(ctx, group);
1149
+ return h(Fold, {
1150
+ key: `g${index}`,
1151
+ id: `lg${index}`,
1152
+ title: groupHead.title,
1153
+ count: group.count,
1154
+ ...(groupHead.badge === undefined ? {} : { badge: groupHead.badge }),
1155
+ note: FOLD_NOTE[group.scope],
1156
+ defaultOpen: index === 0,
1157
+ children: [
1158
+ ...(group.count > group.entries.length
1159
+ ? [h('p', { key: 'more', style: S.foldNote }, `下面只列了前 ${group.entries.length} 条`)]
1160
+ : []),
1161
+ h('ul', { key: 'u', style: S.memList }, ...group.entries.map((entry, i) => h(MemoryRow, { key: `e${i}`, entry }))),
1162
+ ],
1163
+ });
1164
+ })));
1165
+ }
1166
+ // 刻度说明改成标题右侧那个小问号了(常驻一张"数值怎么读"卡太长,也没人愿意每次往下翻)。
1167
+ // 浮层必须是**页面根部的最后一个孩子**:留在卡片里会被卡片的层叠上下文压住,
1168
+ // 于是"显示在饼状图下方"(真机上就是这样)。见 `tipLayer` 上面的说明。
1169
+ const TAB_LIST = [
1170
+ { id: 'now', label: '此刻', items: tabNow },
1171
+ { id: 'think', label: '想法', items: tabThink },
1172
+ { id: 'memory', label: '记忆', items: tabMemory },
1173
+ ];
1174
+ const current = TAB_LIST.find((item) => item.id === tab) ?? TAB_LIST[0];
1175
+ return h('div', { style: S.page }, h('div', { key: 'inner', style: S.inner }, head, ...body, h('div', { key: 'tabs', style: S.tabBar }, ...TAB_LIST.map((item) => h('button', {
1176
+ key: item.id,
1177
+ style: { ...S.tab, ...(current.id === item.id ? S.tabOn : {}) },
1178
+ onClick: () => setTab(item.id),
1179
+ }, item.label))), ...current.items), tipLayer(tip));
1180
+ }
1181
+ /** 样式:颜色一律走主题 token(写死的颜色在别的皮肤下会瞎)。 */
1182
+ const S = {
1183
+ page: {
1184
+ // 这一页得**自己滚**。
1185
+ //
1186
+ // 宿主给面板的是一个固定高度的容器,父层并不负责滚动;页面自己不建滚动容器,
1187
+ // 超出的部分就永远看不到(第一版就是这样:内容比屏幕长,但页面滚不动)。
1188
+ // `height:100%` + `minHeight:0` + `overflowY:auto` 是"它自己能滚"的最小集合。
1189
+ height: '100%',
1190
+ minHeight: 0,
1191
+ boxSizing: 'border-box',
1192
+ overflowY: 'auto',
1193
+ overscrollBehavior: 'contain',
1194
+ padding: '22px 26px 40px',
1195
+ fontSize: '13px',
1196
+ lineHeight: 1.75,
1197
+ color: 'var(--dsw-alias-label-primary, inherit)',
1198
+ },
1199
+ // 滚动条挂在 page 上(贴着容器边),内容再居中,免得滚条压在文字上
1200
+ inner: { maxWidth: '760px', margin: '0 auto' },
1201
+ // ── 顶层 tab(此刻 / 想法 / 记忆)────────────────────────────────
1202
+ //
1203
+ // 一条**贯穿的细底线** + 选中项贴底的 2px 实线。第一版给每个 tab 都设了
1204
+ // `borderBottom: 2px solid transparent`,结果浏览器把它渲染成了三条断开的小灰线
1205
+ // (看着像三个各自带下划线的按钮)。现在改用 `boxShadow: inset` 画选中线:
1206
+ // 未选中项**根本不画线**,想画错也没得画。
1207
+ //
1208
+ // 左侧对齐也修了:tab 的左右 padding 改成 0、用 marginRight 拉开间距,
1209
+ // 第一个 tab 的文字才能和标题「心念」左对齐。
1210
+ tabBar: {
1211
+ display: 'flex',
1212
+ margin: '2px 0 16px',
1213
+ borderBottom: '1px solid var(--dsw-alias-border-l1, rgba(128, 128, 128, 0.18))',
1214
+ },
1215
+ tab: {
1216
+ appearance: 'none',
1217
+ background: 'transparent',
1218
+ border: 'none',
1219
+ padding: '7px 0',
1220
+ marginRight: '24px',
1221
+ marginBottom: '-1px',
1222
+ fontSize: '13px',
1223
+ fontFamily: 'inherit',
1224
+ color: 'inherit',
1225
+ opacity: 0.45,
1226
+ cursor: 'pointer',
1227
+ transition: 'opacity 120ms ease',
1228
+ },
1229
+ tabOn: { opacity: 1, boxShadow: 'inset 0 -2px 0 0 currentColor' },
1230
+ // ── 标题右侧的小问号(刻度说明)────────────────────────────────
1231
+ tipWrap: { display: 'inline-flex', verticalAlign: 'middle' },
1232
+ tipIcon: {
1233
+ marginLeft: '6px',
1234
+ width: '14px',
1235
+ height: '14px',
1236
+ lineHeight: '13px',
1237
+ textAlign: 'center',
1238
+ borderRadius: '50%',
1239
+ border: '1px solid var(--dsw-alias-border-l2, rgba(255, 255, 255, 0.25))',
1240
+ fontSize: '10px',
1241
+ fontWeight: 400,
1242
+ opacity: 0.5,
1243
+ cursor: 'help',
1244
+ userSelect: 'none',
1245
+ },
1246
+ // 浮层用 fixed:面板根部是滚动容器,绝对定位会被裁掉
1247
+ tipPanel: {
1248
+ position: 'fixed',
1249
+ zIndex: 9999,
1250
+ width: '330px',
1251
+ maxWidth: 'calc(100vw - 40px)',
1252
+ padding: '9px 11px',
1253
+ borderRadius: '9px',
1254
+ // 浮层背景用 `bg-layer-2`(宿主自己弹面板用的就是这一档,见 dsh-better-sidebar 的
1255
+ // `cm-search.ts`:`layer-2` 背景 + `border-l1` 描边),边界用 `border-l1`。
1256
+ // 原先写过两个错的:`--dsw-alias-bg-elevated`(不存在,退回半透明兜底,深色下等于没背景)
1257
+ // 和 `--dsw-alias-bg-overlay`(存在,但那是**遮罩**那一档,压在卡片上颜色对不上,
1258
+ // 用户原话:"背景色不对,和系统的主题色不一致")。
1259
+ border: '1px solid var(--dsw-alias-border-l1, rgba(255, 255, 255, 0.12))',
1260
+ background: 'var(--dsw-alias-bg-layer-2, #2a2a33)',
1261
+ boxShadow: '0 8px 24px rgba(0, 0, 0, 0.28)',
1262
+ fontSize: '12px',
1263
+ lineHeight: 1.6,
1264
+ fontWeight: 400,
1265
+ opacity: 1,
1266
+ pointerEvents: 'none',
1267
+ textAlign: 'left',
1268
+ },
1269
+ tipLine: { marginBottom: '5px', opacity: 0.85 },
1270
+ head: { margin: '0 0 14px' },
1271
+ title: { margin: '0 0 4px', fontSize: '18px', fontWeight: 600 },
1272
+ sub: { margin: 0, opacity: 0.6, fontSize: '12px' },
1273
+ card: {
1274
+ marginTop: '12px',
1275
+ padding: '14px 16px',
1276
+ borderRadius: '12px',
1277
+ border: '1px solid var(--dsw-alias-border-l1, rgba(255, 255, 255, 0.08))',
1278
+ background: 'var(--dsw-alias-bg-layer-1, rgba(255, 255, 255, 0.02))',
1279
+ },
1280
+ cardTitle: { margin: '0 0 8px', fontSize: '13px', fontWeight: 600, opacity: 0.9 },
1281
+ // 两张卡并排:宽度够就一左一右,不够就自己折成上下(auto-fit,不用管窗口多宽)
1282
+ row: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '12px', marginTop: '12px' },
1283
+ hint: { margin: '12px 0 0', fontSize: '12px', opacity: 0.55 },
1284
+ list: { margin: 0, paddingLeft: '18px', display: 'grid', gap: '5px' },
1285
+ /**
1286
+ * 带圆点的列表。
1287
+ *
1288
+ * 必须用 `block` 而不是 `grid`:**grid 会把子项的 display 强制降级成 block**,
1289
+ * `li` 的 list-item 身份一没,圆点就消失了(用户盯着问"我说的无序列表要的是前面那个点")。
1290
+ * 同理 `li` 自己也不能套 `S.line`(那是 `-webkit-box`,一样会杀掉圆点)。
1291
+ */
1292
+ bulletList: { margin: '2px 0 0', paddingLeft: '20px', display: 'block' },
1293
+ line: {
1294
+ // 两行收口:记忆条目常常很长,铺开来整个页面就没法看了
1295
+ display: '-webkit-box',
1296
+ WebkitLineClamp: 2,
1297
+ WebkitBoxOrient: 'vertical',
1298
+ overflow: 'hidden',
1299
+ },
1300
+ // ── 图表:饼 + 条 ──────────────────────────────────────────────
1301
+ pieRow: { display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap', margin: '4px 0 2px' },
1302
+ donutWrap: { position: 'relative', flex: '0 0 auto' },
1303
+ donutCenter: {
1304
+ position: 'absolute',
1305
+ inset: 0,
1306
+ display: 'flex',
1307
+ alignItems: 'center',
1308
+ justifyContent: 'center',
1309
+ textAlign: 'center',
1310
+ padding: '0 16px',
1311
+ fontSize: '12px',
1312
+ fontWeight: 600,
1313
+ opacity: 0.85,
1314
+ },
1315
+ pieLegend: { listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: '4px', flex: '1 1 150px', fontSize: '12px' },
1316
+ pieLegendItem: { display: 'flex', alignItems: 'center', gap: '7px', opacity: 0.9 },
1317
+ pieValue: { marginLeft: 'auto', opacity: 0.6, fontVariantNumeric: 'tabular-nums' },
1318
+ dot: { width: '9px', height: '9px', borderRadius: '50%', display: 'inline-block', flex: '0 0 auto' },
1319
+ bars: { display: 'grid', gap: '9px', marginTop: '12px' },
1320
+ barRow: { display: 'grid', gap: '4px' },
1321
+ barLabel: { display: 'flex', justifyContent: 'space-between', fontSize: '12px', opacity: 0.85 },
1322
+ barValue: { opacity: 0.6, fontVariantNumeric: 'tabular-nums' },
1323
+ barWrap: {
1324
+ position: 'relative',
1325
+ height: '8px',
1326
+ borderRadius: '4px',
1327
+ // 轨道用边框色而不是"抬升面":`bg-layer-2` 在浅色主题下几乎和卡片同色,
1328
+ // 于是"剩下的那部分"根本看不见,0.67 看着像 0.9。边框色两个主题都够清楚。
1329
+ background: 'var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.10))',
1330
+ // 不能 hidden:零刻度要上下探出轨道才看得见(用户点过一次"高度不够、不明显")
1331
+ overflow: 'visible',
1332
+ },
1333
+ barTrack: { position: 'absolute', inset: 0 },
1334
+ // 允许漂移的带宽:只留两条边界刻度(0.3 与 0.7),不铺色块——
1335
+ // 铺色块会让带内比带外"更实",填充条看起来被拉长,右边的空档就不够数了。
1336
+ bandTick: {
1337
+ position: 'absolute',
1338
+ top: 0,
1339
+ bottom: 0,
1340
+ width: '1px',
1341
+ background: 'var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.28))',
1342
+ },
1343
+ barFill: { position: 'absolute', top: 0, bottom: 0, left: 0, borderRadius: '4px', background: 'var(--dsw-alias-brand-primary, #8ab4ff)' },
1344
+ // 零刻度:跨零的量(效价)从中间长出去,得让人看见那个 0 在哪儿。
1345
+ // 上下各探出轨道 3px、加宽到 2px、颜色提到 label-secondary —— 只在轨道内画一条
1346
+ // 1px 的淡线,用户在原尺寸下根本看不见(他点过一次"高度不够、不明显")。
1347
+ barMid: {
1348
+ position: 'absolute',
1349
+ top: '-3px',
1350
+ bottom: '-3px',
1351
+ width: '2px',
1352
+ borderRadius: '1px',
1353
+ background: 'var(--dsw-alias-label-secondary, rgba(0, 0, 0, 0.55))',
1354
+ },
1355
+ // ── 记忆 ──────────────────────────────────────────────────────
1356
+ memList: { listStyle: 'none', margin: '6px 0 0', padding: 0, display: 'grid', gap: '9px' },
1357
+ memRow: {
1358
+ display: 'grid',
1359
+ gap: '3px',
1360
+ paddingBottom: '8px',
1361
+ borderBottom: '1px solid var(--dsw-alias-border-l1, rgba(255, 255, 255, 0.06))',
1362
+ },
1363
+ memTop: { display: 'flex', alignItems: 'center', gap: '7px', flexWrap: 'wrap' },
1364
+ badge: {
1365
+ fontSize: '11px',
1366
+ padding: '1px 6px',
1367
+ borderRadius: '999px',
1368
+ border: '1px solid var(--dsw-alias-border-l2, rgba(255, 255, 255, 0.14))',
1369
+ opacity: 0.85,
1370
+ },
1371
+ memMeta: { fontSize: '11px', opacity: 0.5 },
1372
+ // 来源标签:它自己记的(品牌色,一眼看出这是它的话)/ 听来的原话(灰的,兜底)
1373
+ srcSelf: {
1374
+ fontSize: '10px',
1375
+ padding: '1px 6px',
1376
+ borderRadius: '999px',
1377
+ whiteSpace: 'nowrap',
1378
+ color: 'var(--dsw-alias-brand-primary, #8ab4ff)',
1379
+ border: '1px solid var(--dsw-alias-brand-primary, #8ab4ff)',
1380
+ opacity: 0.9,
1381
+ },
1382
+ srcHeard: {
1383
+ fontSize: '10px',
1384
+ padding: '1px 6px',
1385
+ borderRadius: '999px',
1386
+ whiteSpace: 'nowrap',
1387
+ color: 'var(--dsw-alias-label-secondary, inherit)',
1388
+ border: '1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.24))',
1389
+ opacity: 0.7,
1390
+ },
1391
+ // 折叠组头右侧的小徽标:说明"这一组凭什么算一组"(其他项目 / 会话未分组 / 跨项目…)
1392
+ foldBadge: {
1393
+ fontSize: '10px',
1394
+ lineHeight: '16px',
1395
+ padding: '0 6px',
1396
+ borderRadius: '999px',
1397
+ whiteSpace: 'nowrap',
1398
+ color: 'var(--dsw-alias-label-secondary, inherit)',
1399
+ border: '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.28))',
1400
+ },
1401
+ // 正文**不截断**:这是"它记着的事",少一个字都可能变意思(用户点名过"怎么还截断了")。
1402
+ // 面板本来就能滚,宁可让一条长一点,也不要让读者猜后半句。
1403
+ memText: { wordBreak: 'break-word', lineHeight: 1.6 },
1404
+ /**
1405
+ * 两行截断(`-webkit-box` 那套)。
1406
+ *
1407
+ * 用两行而不是一行:候选自我认知常是一整段话,压成一行只剩"用户看截图挑细节,说明要的是…",
1408
+ * 读者根本看不出这条到底在说什么(用户就是这么以为"只有一条"的)。
1409
+ */
1410
+ clamp2: {
1411
+ display: '-webkit-box',
1412
+ WebkitBoxOrient: 'vertical',
1413
+ WebkitLineClamp: 2,
1414
+ overflow: 'hidden',
1415
+ wordBreak: 'break-word',
1416
+ lineHeight: 1.6,
1417
+ },
1418
+ groupTitle: { display: 'flex', alignItems: 'baseline', gap: '8px', margin: '0 0 2px', fontSize: '12px', fontWeight: 600, opacity: 0.9 },
1419
+ // 折叠组:标题行整行可点,左边一个小三角;展开后正文再往下排。
1420
+ fold: { margin: '10px 0 0' },
1421
+ // 折叠组的头:做成一张卡片(有底色、有边框、可悬停),这样它一眼就是"能点开的一块",
1422
+ // 而不是一行看不出门道的文字。展开后正文缩进一点,才能看出它是这卡片的里面。
1423
+ foldHead: {
1424
+ display: 'flex',
1425
+ alignItems: 'center',
1426
+ justifyContent: 'space-between',
1427
+ gap: '10px',
1428
+ cursor: 'pointer',
1429
+ userSelect: 'none',
1430
+ padding: '7px 10px',
1431
+ borderRadius: '6px',
1432
+ background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,0.06))',
1433
+ border: '1px solid var(--dsw-alias-border-l1, rgba(0,0,0,0.10))',
1434
+ },
1435
+ foldLabel: { display: 'flex', alignItems: 'center', gap: '7px', minWidth: 0 },
1436
+ foldCaret: { fontSize: '10px', opacity: 0.55, width: '14px', flex: '0 0 14px', textAlign: 'center' },
1437
+ foldTitle: { fontSize: '12px', fontWeight: 600, opacity: 0.92, wordBreak: 'break-all' },
1438
+ // 条数做成右侧的小胶囊,跟标题拉开,眼睛一扫就知道这组有多少
1439
+ foldCount: {
1440
+ fontSize: '11px',
1441
+ fontWeight: 400,
1442
+ opacity: 0.6,
1443
+ flex: '0 0 auto',
1444
+ padding: '1px 7px',
1445
+ borderRadius: '999px',
1446
+ background: 'var(--dsw-alias-bg-layer-1, rgba(127,127,127,0.10))',
1447
+ },
1448
+ foldNote: { margin: '4px 0 0 15px', fontSize: '11px', lineHeight: 1.6, opacity: 0.55 },
1449
+ foldBody: { margin: '2px 0 0 15px' },
1450
+ // ── 设置页(settings.section) ──
1451
+ // 页面比状态页宽一点:一行里要装下"字段名 + 说明 + 控件",760px 会挤成一团
1452
+ setPage: { maxWidth: '860px', margin: '0 auto', padding: '4px 2px 40px' },
1453
+ setBanner: {
1454
+ marginTop: '12px',
1455
+ padding: '12px 14px',
1456
+ borderRadius: '10px',
1457
+ fontSize: '12.5px',
1458
+ lineHeight: 1.7,
1459
+ border: '1px solid var(--dsw-alias-state-warn-primary, rgba(200,140,0,0.45))',
1460
+ background: 'var(--dsw-alias-bg-layer-1, rgba(127,127,127,0.06))',
1461
+ },
1462
+ setBannerBad: {
1463
+ border: '1px solid var(--dsw-alias-state-error-primary, rgba(220,60,60,0.45))',
1464
+ },
1465
+ setBannerQuiet: {
1466
+ border: '1px solid var(--dsw-alias-border-l1, rgba(0,0,0,0.10))',
1467
+ },
1468
+ setBar: { display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap', marginTop: '14px' },
1469
+ setBtn: {
1470
+ padding: '6px 14px',
1471
+ borderRadius: '8px',
1472
+ fontSize: '12.5px',
1473
+ fontFamily: 'inherit',
1474
+ cursor: 'pointer',
1475
+ // 这两个 token 是**实测过的**:`--dsw-alias-button-primary-label` / `-fill` 在主题里**不存在**,
1476
+ // 用了就会回落到 inherit 与半透明灰——深色方块上一个字都看不见(用户就是这么发现 bug 的)。
1477
+ // 主按钮用品牌色 + 白字,跟宿主自己的主按钮一个观感。
1478
+ color: '#fff',
1479
+ background: 'var(--dsw-alias-brand-primary, rgba(90, 120, 255, 0.9))',
1480
+ border: '1px solid transparent',
1481
+ },
1482
+ setBtnGhost: {
1483
+ background: 'transparent',
1484
+ color: 'var(--dsw-alias-label-primary, inherit)',
1485
+ border: '1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.14))',
1486
+ },
1487
+ setNote: { fontSize: '12px', lineHeight: 1.6, flex: '1 1 240px', minWidth: 0 },
1488
+ setNoteOk: { color: 'var(--dsw-alias-state-success-primary, inherit)' },
1489
+ setNoteWarn: { color: 'var(--dsw-alias-state-warn-primary, inherit)' },
1490
+ setNoteBad: { color: 'var(--dsw-alias-state-error-primary, inherit)' },
1491
+ // 分组不套卡片:卡片套卡片是"自己设计一套版式",而用户要的是**和通用设置一样**——
1492
+ // 组标题 + 一行说明 + 若干行字段,行间一条细线就够了。
1493
+ setGroup: { marginTop: '22px' },
1494
+ setGroupTitle: {
1495
+ fontSize: '13px',
1496
+ fontWeight: 600,
1497
+ paddingBottom: '6px',
1498
+ borderBottom: '1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.14))',
1499
+ },
1500
+ setGroupNote: { margin: '4px 0 2px', fontSize: '11.5px', lineHeight: 1.6, opacity: 0.6 },
1501
+ setRow: {
1502
+ display: 'flex',
1503
+ alignItems: 'flex-start',
1504
+ gap: '14px',
1505
+ padding: '9px 0',
1506
+ borderTop: '1px solid var(--dsw-alias-border-l1, rgba(0,0,0,0.08))',
1507
+ },
1508
+ setInfo: { flex: '1 1 auto', minWidth: 0 },
1509
+ setLabel: { fontSize: '12.5px', fontWeight: 600, lineHeight: 1.5 },
1510
+ setDesc: { marginTop: '2px', fontSize: '11.5px', lineHeight: 1.65, opacity: 0.62 },
1511
+ setCtrl: { flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: '7px', paddingTop: '1px' },
1512
+ setInput: {
1513
+ width: '136px',
1514
+ height: '30px',
1515
+ padding: '0 10px',
1516
+ borderRadius: '8px',
1517
+ fontSize: '13px',
1518
+ boxSizing: 'border-box',
1519
+ fontFamily: 'inherit',
1520
+ color: 'inherit',
1521
+ background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,0.10))',
1522
+ border: '1px solid var(--dsw-alias-border-l2, rgba(0,0,0,0.14))',
1523
+ },
1524
+ setInputBad: { border: '1px solid var(--dsw-alias-state-error-primary, rgba(220,60,60,0.6))' },
1525
+ setInputText: { width: '100%', minWidth: '300px', height: '30px' },
1526
+ setRange: { fontSize: '11px', opacity: 0.5, whiteSpace: 'nowrap' },
1527
+ setDirty: { fontSize: '11px', color: 'var(--dsw-alias-brand-primary, inherit)', whiteSpace: 'nowrap' },
1528
+ // 开关自己画:原生 `input[type=checkbox]` 是浏览器那个大方框,和设置面板里其它几页的 pill 开关
1529
+ // 放在一起像两个人做的界面。尺寸按通用设置的观感取(38×22,圆点 16)。
1530
+ setToggle: {
1531
+ position: 'relative',
1532
+ flex: '0 0 auto',
1533
+ width: '40px',
1534
+ height: '22px',
1535
+ padding: 0,
1536
+ margin: 0,
1537
+ borderRadius: '999px',
1538
+ border: '1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.14))',
1539
+ background: 'var(--dsw-alias-state-idle-primary, rgba(127, 127, 127, 0.35))',
1540
+ cursor: 'pointer',
1541
+ appearance: 'none',
1542
+ boxSizing: 'border-box',
1543
+ lineHeight: 0,
1544
+ transition: 'background 120ms ease, border-color 120ms ease',
1545
+ },
1546
+ setToggleOn: {
1547
+ background: 'var(--dsw-alias-brand-primary, rgba(90, 120, 255, 0.9))',
1548
+ borderColor: 'transparent',
1549
+ },
1550
+ setToggleKnob: {
1551
+ position: 'absolute',
1552
+ top: '2px',
1553
+ left: '2px',
1554
+ width: '16px',
1555
+ height: '16px',
1556
+ borderRadius: '50%',
1557
+ background: '#fff',
1558
+ boxShadow: '0 1px 2px rgba(0, 0, 0, 0.30)',
1559
+ transition: 'left 120ms ease',
1560
+ },
1561
+ setToggleKnobOn: { left: '20px' },
1562
+ setFoot: { marginTop: '16px', fontSize: '11px', lineHeight: 1.7, opacity: 0.5 },
1563
+ };
1564
+ /* ───────────────────────── 设置页(settings.section) ───────────────────────── */
1565
+ /**
1566
+ * 设置页在设置面板里的排序。
1567
+ *
1568
+ * 实测到的邻居:better-sidebar 用 100、llm-retry-settings 用 15。取 40 → 排在它们中间,
1569
+ * 既不抢最前面,也不至于沉到看不见。
1570
+ */
1571
+ const SETTINGS_SECTION_ORDER = 40;
1572
+ /**
1573
+ * 插件自己的路由前缀。**必须**与宿主半边 `src/settings-bridge.ts` 的 `SETTINGS_ROUTE_PREFIX` 一字不差。
1574
+ *
1575
+ * 两边写死同一个字符串是刻意的:宿主与客户端是两份独立产物(客户端连 `require` 都只有 `react` 可用),
1576
+ * 没有共享模块这条路可走。改一处就要改另一处——两边的注释里都写了这句。
1577
+ */
1578
+ const SETTINGS_ROUTE = 'dsh-mind/api';
1579
+ /** 一次调用失败。`code` 原样来自宿主,用来分辨"没保存上"是哪种没保存上。 */
1580
+ class SettingsCallError extends Error {
1581
+ constructor(code, message) {
1582
+ super(message);
1583
+ this.name = 'SettingsCallError';
1584
+ this.code = code;
1585
+ }
1586
+ }
1587
+ /**
1588
+ * HTTP 发到哪儿。
1589
+ *
1590
+ * 走**页面自己的 base**:桌面壳的页面是 `dsh-app://app/`,壳把非静态路径同源转发给宿主;
1591
+ * 而插件注册的路由**没有 `Access-Control-Allow-*` 头**,所以不能发到注入进来的
1592
+ * `__DSH_TRANSPORT__.streamBaseUrl`(那是宿主真实 origin,只适合 WebSocket,浏览器会按跨域拦掉)。
1593
+ * 这段等价实现是照 better-sidebar 的 `desktop-env.ts` + `host-route-url.ts` 写的——
1594
+ * 那两个文件在别人的包里,我们不能 import。
1595
+ */
1596
+ function hostHttpBase() {
1597
+ const page = typeof document !== 'undefined' ? document.baseURI : undefined;
1598
+ if (typeof page === 'string' && page !== '')
1599
+ return page;
1600
+ const injected = globalThis.__DSH_TRANSPORT__;
1601
+ const stream = injected?.streamBaseUrl;
1602
+ return typeof stream === 'string' && stream !== '' ? stream : '';
1603
+ }
1604
+ /** 把 base 归一成"目录"(去掉 query/hash,结尾补 `/`),这样相对路径不会把最后一段吃掉。 */
1605
+ function directoryBase(baseUrl) {
1606
+ const placeholder = 'http://dsh.internal/';
1607
+ const url = new URL(baseUrl === '' ? placeholder : baseUrl, placeholder);
1608
+ url.search = '';
1609
+ url.hash = '';
1610
+ if (!url.pathname.endsWith('/'))
1611
+ url.pathname += '/';
1612
+ return url.href;
1613
+ }
1614
+ /** `<插件前缀>/<方法名>` 的完整地址。 */
1615
+ function settingsRouteUrl(method) {
1616
+ return new URL(`${SETTINGS_ROUTE}/${method}`.replace(/^\/+/, ''), directoryBase(hostHttpBase())).href;
1617
+ }
1618
+ /**
1619
+ * 调一次设置路由。
1620
+ *
1621
+ * 信封形状与宿主一致:成功 `{ok:true,value}`、失败 `{ok:false,error:{code,message}}`。
1622
+ * **没有 `value` 就算失败**——宁可报错,也不把"没值"当成"值是空的"画出去。
1623
+ */
1624
+ async function callSettings(method, payload) {
1625
+ let response;
1626
+ try {
1627
+ response = await fetch(settingsRouteUrl(method), {
1628
+ method: 'POST',
1629
+ headers: { 'content-type': 'application/json' },
1630
+ body: JSON.stringify(payload),
1631
+ });
1632
+ }
1633
+ catch (error) {
1634
+ throw new SettingsCallError('network', error instanceof Error ? error.message : String(error));
1635
+ }
1636
+ const parsed = (await response.json().catch(() => null));
1637
+ if (!response.ok || parsed === null || parsed.ok !== true || parsed.value === undefined) {
1638
+ throw new SettingsCallError(parsed?.error?.code ?? 'http', parsed?.error?.message ?? `HTTP ${response.status}`);
1639
+ }
1640
+ return parsed.value;
1641
+ }
1642
+ /** 把一次调用失败翻成给用户看的中文。宿主的 message 已经是中文的,就原样用。 */
1643
+ function describeSettingsError(error) {
1644
+ const code = error?.code;
1645
+ const message = error?.message;
1646
+ const text = typeof message === 'string' && message !== '' ? message : String(error);
1647
+ if (code === 'network')
1648
+ return `连不上宿主:${text}`;
1649
+ if (code === 'unknown-method') {
1650
+ return '宿主没有这条设置路由(这一版 dsh-mind 或宿主需要重新加载)。';
1651
+ }
1652
+ return text;
1653
+ }
1654
+ /** 从事件里取输入框的值(不用 DOM 类型,客户端只用得到这两种)。 */
1655
+ function inputTextOf(event) {
1656
+ const target = event?.target;
1657
+ return typeof target?.value === 'string' ? target.value : '';
1658
+ }
1659
+ /** 某个字段当前显示什么值:**草稿优先**(用户刚敲的不能被一次刷新盖掉)。 */
1660
+ function shownValue(snapshot, draft, field) {
1661
+ if (Object.prototype.hasOwnProperty.call(draft, field.key))
1662
+ return draft[field.key];
1663
+ const value = snapshot?.value;
1664
+ if (value !== null && typeof value === 'object') {
1665
+ const record = value;
1666
+ if (Object.prototype.hasOwnProperty.call(record, field.key))
1667
+ return record[field.key];
1668
+ }
1669
+ return field.fallback;
1670
+ }
1671
+ /** 草稿里这个字段改过没有。 */
1672
+ function isDirty(draft, field) {
1673
+ return Object.prototype.hasOwnProperty.call(draft, field.key);
1674
+ }
1675
+ /**
1676
+ * 这个值能不能交给宿主。
1677
+ *
1678
+ * 为什么在这里挡一道:宿主会把不合规的值退回来(400),但那句话是给开发者看的;
1679
+ * 用户在输入框里看到"不能小于 0"要直接得多。**两边都拦**,不是二选一。
1680
+ */
1681
+ function issueOf(field, raw) {
1682
+ if (field.kind === 'boolean')
1683
+ return typeof raw === 'boolean' ? undefined : '只能是开或关';
1684
+ if (field.kind === 'number') {
1685
+ const text = typeof raw === 'number' ? String(raw) : String(raw ?? '').trim();
1686
+ if (text === '')
1687
+ return '不能留空';
1688
+ const value = Number(text);
1689
+ if (!Number.isFinite(value))
1690
+ return '要填一个数字';
1691
+ if (field.min !== undefined && value < field.min)
1692
+ return `不能小于 ${field.min}`;
1693
+ if (field.max !== undefined && value > field.max)
1694
+ return `不能大于 ${field.max}`;
1695
+ return undefined;
1696
+ }
1697
+ return typeof raw === 'string' ? undefined : '要填一段文字';
1698
+ }
1699
+ /** 把草稿里**改过的**字段拼成 patch(数字转成数字)。没改的字段不出现——省得把整份配置来回写一遍。 */
1700
+ function patchOf(fields, draft) {
1701
+ const patch = {};
1702
+ for (const field of fields) {
1703
+ if (!isDirty(draft, field))
1704
+ continue;
1705
+ const raw = draft[field.key];
1706
+ patch[field.key] = field.kind === 'number' && typeof raw !== 'number' ? Number(String(raw).trim()) : raw;
1707
+ }
1708
+ return patch;
1709
+ }
1710
+ /** 一行控件。 */
1711
+ function SettingsRow(props) {
1712
+ const { field, shown, dirty, issue, disabled } = props;
1713
+ const control = (() => {
1714
+ if (field.kind === 'boolean') {
1715
+ const on = shown === true;
1716
+ return h('button', {
1717
+ key: 'c',
1718
+ type: 'button',
1719
+ role: 'switch',
1720
+ 'aria-checked': on,
1721
+ title: on ? '已开启' : '已关闭',
1722
+ style: Object.assign({}, S.setToggle, on ? S.setToggleOn : {}),
1723
+ disabled,
1724
+ onClick: () => props.onEdit(field.key, !on),
1725
+ }, h('span', { key: 'k', style: Object.assign({}, S.setToggleKnob, on ? S.setToggleKnobOn : {}) }));
1726
+ }
1727
+ if (field.kind === 'number') {
1728
+ return h('input', {
1729
+ key: 'c',
1730
+ type: 'number',
1731
+ style: Object.assign({}, S.setInput, issue === undefined ? {} : S.setInputBad),
1732
+ value: shown === undefined || shown === null ? '' : String(shown),
1733
+ min: field.min,
1734
+ max: field.max,
1735
+ disabled,
1736
+ onChange: (event) => props.onEdit(field.key, inputTextOf(event)),
1737
+ });
1738
+ }
1739
+ return h('input', {
1740
+ key: 'c',
1741
+ type: 'text',
1742
+ style: Object.assign({}, S.setInput, S.setInputText),
1743
+ value: shown === undefined || shown === null ? '' : String(shown),
1744
+ disabled,
1745
+ onChange: (event) => props.onEdit(field.key, inputTextOf(event)),
1746
+ });
1747
+ })();
1748
+ const hint = field.kind === 'number' && !disabled && field.min !== undefined && field.max !== undefined
1749
+ ? h('span', { key: 'h', style: S.setRange }, `${field.min} – ${field.max}`)
1750
+ : null;
1751
+ return h('div', { key: field.key, style: S.setRow }, h('div', { key: 'info', style: S.setInfo }, h('div', { key: 'label', style: S.setLabel }, field.label, dirty ? h('span', { key: 'd', style: S.setDirty }, ' · 待保存') : null), h('div', { key: 'desc', style: S.setDesc }, field.description), issue === undefined ? null : h('div', { key: 'issue', style: Object.assign({}, S.setDesc, S.setNoteBad) }, issue)), h('div', { key: 'ctrl', style: S.setCtrl }, hint, control));
1752
+ }
1753
+ /**
1754
+ * 设置面板里的「心念」页。
1755
+ *
1756
+ * 三条自己在意的:
1757
+ *
1758
+ * 1. **值的真相在宿主**。这一页只存"用户改了但还没保存的草稿",从不把配置存第二份——
1759
+ * 否则改完在别处一看还是旧的,那种错最难查。
1760
+ * 2. **拿不到就如实说**。宿主没提供设置服务时,页面照旧把字段和说明列出来(那是编译期就定下的知识),
1761
+ * 但控件是灰的,并在最上面写清为什么——**不编一份"看起来正常的默认值"当真的值**。
1762
+ * 3. **改的是改过的字段**。保存只发改过的那几个 key,不是把整份配置回写一遍。
1763
+ */
1764
+ function SettingsSection() {
1765
+ const [snapshot, setSnapshot] = react.useState(null);
1766
+ const [draft, setDraft] = react.useState({});
1767
+ const [loadError, setLoadError] = react.useState(null);
1768
+ const [note, setNote] = react.useState(null);
1769
+ const [busy, setBusy] = react.useState(false);
1770
+ // 挂载时读一次。
1771
+ //
1772
+ // `cancelled` 是必须的:这一页可能被用户很快切走,切走之后 setState 会警告(而且那份快照也没人看)。
1773
+ // 读回来的值**不碰草稿**:显示时草稿优先(见 `shownValue`),所以用户挂载后立刻敲的字不会被盖掉。
1774
+ react.useEffect(() => {
1775
+ let cancelled = false;
1776
+ void callSettings('settings.get', {})
1777
+ .then((next) => {
1778
+ if (cancelled)
1779
+ return;
1780
+ setSnapshot(next);
1781
+ setLoadError(null);
1782
+ })
1783
+ .catch((error) => {
1784
+ if (cancelled)
1785
+ return;
1786
+ setLoadError(describeSettingsError(error));
1787
+ });
1788
+ return () => {
1789
+ cancelled = true;
1790
+ };
1791
+ }, []);
1792
+ const edit = (key, value) => {
1793
+ const next = {};
1794
+ for (const existing of Object.keys(draft))
1795
+ next[existing] = draft[existing];
1796
+ next[key] = value;
1797
+ setDraft(next);
1798
+ };
1799
+ const reset = () => {
1800
+ setDraft({});
1801
+ setNote({ kind: 'warn', text: '已丢弃还没保存的改动。' });
1802
+ };
1803
+ const reload = () => {
1804
+ setBusy(true);
1805
+ void callSettings('settings.get', {})
1806
+ .then((next) => {
1807
+ setSnapshot(next);
1808
+ setLoadError(null);
1809
+ setNote({ kind: 'ok', text: '已重新读取宿主上的值。' });
1810
+ })
1811
+ .catch((error) => {
1812
+ setLoadError(describeSettingsError(error));
1813
+ })
1814
+ .finally(() => setBusy(false));
1815
+ };
1816
+ const fields = snapshot?.fields ?? [];
1817
+ const changed = fields.filter((field) => isDirty(draft, field));
1818
+ const available = snapshot?.available === true;
1819
+ // 能写 = 有设置服务。**不**因为「暂时认不出自己那一条记录」就把整页禁掉:
1820
+ // 用户点了没反应,比明说"存不进去"更糟(这是真机上踩出来的)。
1821
+ // 真认不出时,保存会把宿主的原话带回来,横幅也如实写着。
1822
+ const writable = available;
1823
+ const save = () => {
1824
+ if (busy || snapshot === null || !writable)
1825
+ return;
1826
+ if (changed.length === 0) {
1827
+ setNote({ kind: 'warn', text: '还没有改动。' });
1828
+ return;
1829
+ }
1830
+ const broken = changed.filter((field) => issueOf(field, draft[field.key]) !== undefined);
1831
+ if (broken.length > 0) {
1832
+ const first = broken[0];
1833
+ setNote({ kind: 'bad', text: `有 ${broken.length} 项填得不对,先改一下:${first.label}(${issueOf(first, draft[first.key])})` });
1834
+ return;
1835
+ }
1836
+ const patch = patchOf(fields, draft);
1837
+ setBusy(true);
1838
+ setNote(null);
1839
+ void callSettings('settings.update', { patch, expectedRevision: snapshot.revision })
1840
+ .then((next) => {
1841
+ setSnapshot(next);
1842
+ setDraft({});
1843
+ setNote({
1844
+ kind: 'ok',
1845
+ text: `已保存 ${Object.keys(patch).length} 项,现在是第 ${String(next.revision ?? '?')} 版。`,
1846
+ });
1847
+ })
1848
+ .catch((error) => {
1849
+ const code = error?.code;
1850
+ if (code === 'settings-conflict') {
1851
+ // 冲突 = 我们手上的 revision 过期了。**不丢用户的改动**:草稿留着,
1852
+ // 只把底下的值刷成最新的,用户再点一次保存就能写进去(新 revision 会带过去)。
1853
+ setNote({
1854
+ kind: 'warn',
1855
+ text: '这些值刚在别处被改过,这次没写进去。下面的值已经刷成最新的,你的改动还留着——确认后再点一次保存。',
1856
+ });
1857
+ void callSettings('settings.get', {})
1858
+ .then((fresh) => setSnapshot(fresh))
1859
+ .catch(() => undefined);
1860
+ }
1861
+ else {
1862
+ setNote({ kind: 'bad', text: `保存失败:${describeSettingsError(error)}` });
1863
+ }
1864
+ })
1865
+ .finally(() => setBusy(false));
1866
+ };
1867
+ /* ── 页面骨架 ── */
1868
+ // 标题下**不印**命名空间与版本号:那是实现细节(命名空间名字还是宿主按挂载方式给的),
1869
+ // 对用户没有意义,印错了更糟。页面顶部那行内部信息被用户点名过一次了。
1870
+ const header = h('div', { key: 'head', style: S.head }, h('div', { key: 't', style: { ...S.title, display: 'flex', alignItems: 'center', gap: '8px' } },
1871
+ // 左侧导航那一格的图标改不了:`settings.section` 的注册字段只有 id/order/label,
1872
+ // 宿主给每一页画统一的齿轮。所以把自己这枚"心 + 脉搏"画在页面标题旁边。
1873
+ h(MindIcon, { size: 18 }), '心念'), h('div', { key: 'sub', style: S.setFoot }, '决定它开不开、脾气多大、记性多好、以及忘得多快。改完点「保存」就生效,不用重启。'));
1874
+ const banners = [];
1875
+ if (loadError !== null) {
1876
+ banners.push(h('div', { key: 'load', style: Object.assign({}, S.setBanner, S.setBannerBad) }, `读不到设置:${loadError}`));
1877
+ }
1878
+ else if (snapshot === null) {
1879
+ banners.push(h('div', { key: 'loading', style: S.setBanner }, '正在读宿主上的配置……'));
1880
+ }
1881
+ else if (!available) {
1882
+ // 这里用的就是宿主给的那句话(拿不到设置服务时是"这台宿主没有提供设置服务,只能用配置文件改。")
1883
+ banners.push(h('div', { key: 'none', style: S.setBanner }, snapshot.reason ?? '这台宿主没有提供设置服务,只能用配置文件改。', h('div', { key: 'x', style: S.setFoot }, '下面的字段与说明仍然列出来,但控件不可编辑。')));
1884
+ }
1885
+ else if (snapshot.reason !== undefined && snapshot.reason !== '') {
1886
+ // 认不出"我们这一条"时给一句话,但**不用警告色**:它不是错误,是"还没落进这个 profile",
1887
+ // 拿橙色横幅喊它只会让人以为坏了(用户上一版就是这么被误导的)。
1888
+ banners.push(h('div', { key: 'norec', style: Object.assign({}, S.setBanner, S.setBannerQuiet) }, snapshot.reason));
1889
+ }
1890
+ const bar = h('div', { key: 'bar', style: S.setBar }, h('button', {
1891
+ key: 'save',
1892
+ type: 'button',
1893
+ style: Object.assign({}, S.setBtn, busy || !writable || changed.length === 0 ? { opacity: 0.55 } : {}),
1894
+ disabled: busy || !writable || changed.length === 0,
1895
+ onClick: () => save(),
1896
+ }, busy ? '保存中……' : changed.length === 0 ? '保存' : `保存 ${changed.length} 项`), h('button', {
1897
+ key: 'reset',
1898
+ type: 'button',
1899
+ style: Object.assign({}, S.setBtn, S.setBtnGhost),
1900
+ disabled: busy || changed.length === 0,
1901
+ onClick: () => reset(),
1902
+ }, '丢弃改动'), h('button', { key: 'reload', type: 'button', style: Object.assign({}, S.setBtn, S.setBtnGhost), disabled: busy, onClick: () => reload() }, '重新读取'), note === null
1903
+ ? null
1904
+ : h('span', {
1905
+ key: 'note',
1906
+ style: Object.assign({}, S.setNote, note.kind === 'ok' ? S.setNoteOk : note.kind === 'warn' ? S.setNoteWarn : S.setNoteBad),
1907
+ }, note.text));
1908
+ const groups = (snapshot?.groups ?? []).map((group) => {
1909
+ const rows = [];
1910
+ for (const key of group.keys) {
1911
+ const field = fields.find((candidate) => candidate.key === key);
1912
+ if (field === undefined)
1913
+ continue;
1914
+ const shown = shownValue(snapshot, draft, field);
1915
+ rows.push(SettingsRow({
1916
+ field,
1917
+ shown,
1918
+ dirty: isDirty(draft, field),
1919
+ issue: isDirty(draft, field) ? issueOf(field, draft[field.key]) : undefined,
1920
+ disabled: !writable,
1921
+ onEdit: edit,
1922
+ }));
1923
+ }
1924
+ return h('section', { key: group.id, style: S.setGroup }, h('div', { key: 't', style: S.setGroupTitle }, group.title), h('div', { key: 'n', style: S.setGroupNote }, group.note), rows);
1925
+ });
1926
+ const foot = h('div', { key: 'foot', style: S.setFoot }, '改完点「保存」写入宿主,立即生效。这一页不另存一份配置。');
1927
+ return h('div', { style: S.setPage }, header, banners, bar, groups, foot);
1928
+ }
1929
+
1930
+ return module.exports;
1931
+ },
1932
+ });