dsh-ta 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +160 -107
  3. package/cordis.patch.yml +5 -35
  4. package/docs/RELEASE.md +62 -49
  5. package/docs/USAGE.md +6 -7
  6. package/docs/presets.example.yml +7 -43
  7. package/index.js +3 -164
  8. package/package.json +5 -28
  9. package/src/client/client.js +3176 -0
  10. package/{config.js → src/host/config.js} +39 -3
  11. package/src/host/constants.js +7 -0
  12. package/src/host/gates.js +34 -0
  13. package/src/host/identity.js +145 -0
  14. package/{im → src/host/im}/bindings.js +1 -1
  15. package/src/host/index.js +173 -0
  16. package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
  17. package/src/host/maintenance/collect.js +362 -0
  18. package/src/host/maintenance/completions.js +56 -0
  19. package/src/host/maintenance/consumption.js +67 -0
  20. package/src/host/maintenance/cursors.js +53 -0
  21. package/src/host/maintenance/engine.js +392 -0
  22. package/src/host/maintenance/llm.js +381 -0
  23. package/src/host/maintenance/lock.js +105 -0
  24. package/src/host/maintenance/prompts.js +255 -0
  25. package/src/host/maintenance/runs.js +47 -0
  26. package/src/host/maintenance/schedule.js +173 -0
  27. package/src/host/maintenance/session-cleanup.js +289 -0
  28. package/src/host/maintenance/session-watcher.js +107 -0
  29. package/src/host/maintenance/sleep.js +3 -0
  30. package/src/host/maintenance/stages.js +241 -0
  31. package/src/host/maintenance/state.js +192 -0
  32. package/src/host/prompts.js +96 -0
  33. package/src/host/records.js +175 -0
  34. package/src/host/runtime-manager.js +287 -0
  35. package/{runtime.js → src/host/runtime.js} +6 -8
  36. package/src/host/settings/defaults.js +55 -0
  37. package/{settings → src/host/settings}/home.js +4 -3
  38. package/{settings/routes.js → src/host/settings/http.js} +5 -137
  39. package/{settings → src/host/settings}/im.js +18 -1
  40. package/{settings → src/host/settings}/lifecycle.js +29 -43
  41. package/src/host/settings/persona.js +113 -0
  42. package/src/host/settings/routes.js +229 -0
  43. package/{settings → src/host/settings}/status.js +70 -42
  44. package/src/host/state/appraisals.js +56 -0
  45. package/src/host/state/feel.js +78 -0
  46. package/src/host/state/index.js +9 -0
  47. package/src/host/state/mood.js +103 -0
  48. package/src/host/state/notes.js +18 -0
  49. package/{life.js → src/host/state/outing.js} +13 -136
  50. package/src/host/state/values.js +9 -0
  51. package/{stickers → src/host/stickers}/tool.js +1 -1
  52. package/src/host/storage/fs.js +29 -0
  53. package/src/host/storage/index.js +8 -0
  54. package/src/host/storage/paths.js +20 -0
  55. package/src/host/storage/revision.js +5 -0
  56. package/src/host/storage/session-state.js +38 -0
  57. package/src/host/storage/time.js +127 -0
  58. package/src/host/tools/index.js +152 -0
  59. package/src/host/tools/read.js +252 -0
  60. package/src/host/tools/shared.js +23 -0
  61. package/src/host/tools/wiki.js +35 -0
  62. package/src/host/tools/write.js +164 -0
  63. package/{usage → src/host/usage}/aggregate.js +4 -1
  64. package/{usage → src/host/usage}/ledger.js +47 -21
  65. package/client.js +0 -2554
  66. package/gates.js +0 -18
  67. package/identity.js +0 -97
  68. package/prompts.js +0 -28
  69. package/runtime-manager.js +0 -153
  70. package/settings/defaults.js +0 -41
  71. package/settings/persona.js +0 -203
  72. package/settings/schedule.js +0 -156
  73. package/storage.js +0 -122
  74. package/tools.js +0 -540
  75. /package/{im → src/host/im}/say.js +0 -0
  76. /package/{memory → src/host/memory}/capture.js +0 -0
  77. /package/{memory → src/host/memory}/messages.js +0 -0
  78. /package/{memory → src/host/memory}/outbox.js +0 -0
  79. /package/{reme.js → src/host/reme.js} +0 -0
  80. /package/{settings → src/host/settings}/errors.js +0 -0
  81. /package/{stickers → src/host/stickers}/load.js +0 -0
  82. /package/{stickers → src/host/stickers}/select.js +0 -0
  83. /package/{stickers → src/host/stickers}/serve.js +0 -0
  84. /package/{usage → src/host/usage}/pricing.js +0 -0
  85. /package/{usage → src/host/usage}/serve.js +0 -0
@@ -0,0 +1,3176 @@
1
+ /**
2
+ * dsh-ta 设置页 client 半边(单文件,对应 package.json exports["./client"])。
3
+ *
4
+ * 顶部 SegmentedTabs 分四个页签:
5
+ * 配置(默认)→ 人设 → 状态 → 高级
6
+ *
7
+ * 信息架构(0.4 四件套):
8
+ * - 配置:折叠的“TA 的家”、每日维护、长期记忆(ReMe)与 IM 检测两列卡片,
9
+ * 服务就绪条置底。
10
+ * - 人设:SOUL 单编辑器、称呼、SOUL 建议队列。
11
+ * - 状态:四件套、维护、连接、日记与花销卡;花销可二次确认清零。
12
+ * - 高级:configForms 捕获、夜间任务、心跳、辖区、时区、表情频率。
13
+ *
14
+ * 文件分区(自上而下,也是建议的阅读/改动顺序):
15
+ * 1. 常量与默认值(含纯函数:格式化 / 校验 / 文案)
16
+ * 2. 样式
17
+ * 3. API 基础
18
+ * 4. 通用 hooks
19
+ * 5. 通用组件
20
+ * 6. 配置页
21
+ * 7. 人设页
22
+ * 8. 状态页
23
+ * 9. 高级页
24
+ * 10. 插件入口 / 注册
25
+ *
26
+ * 约束:
27
+ * - 单文件:DSH 客户端插件只加载 exports["./client"] 这一个资源,
28
+ * 所以这里不得 import / require 任何其它文件,全部实现保持在本文件内。
29
+ * - 只使用 --dsw-alias-* 主题 token,不写死颜色;全部样式 scoped 在 .ta- 前缀。
30
+ * - React 由宿主模块表提供,不 import 任何 Client 包,不用 JSX。
31
+ * - 普通设置不显示、不提交家路径;家路径只由初始化 / 转生写入。
32
+ * - 所有请求都带 AbortController 与超时,组件卸载时终止。
33
+ */
34
+ window.__ModuleLoader__.load({
35
+ id: 'dsh-ta',
36
+ factory(require) {
37
+ const React = require('react')
38
+ const h = React.createElement
39
+
40
+ // ===== 1. 常量与默认值 =====
41
+
42
+ const API_ROOT = '/api/dsh-ta'
43
+ const DEFAULT_HOME_PATH = '~/TATA/home'
44
+ const REQUEST_TIMEOUT_MS = 8000
45
+ const PERSONA_MAX_CHARS = 5000
46
+ const DEFAULT_PERSONA_BUDGETS = { soul: 2500 }
47
+ const ADDRESS_MAX_CHARS = 40
48
+ const MAINTENANCE_POLL_INTERVAL_MS = 2000
49
+ const MAINTENANCE_POLL_LIMIT_MS = 90000
50
+
51
+ const MAINTENANCE_EFFORTS = [
52
+ { value: 'off', label: 'off(关闭推理)' },
53
+ { value: 'low', label: 'low(低)' },
54
+ { value: 'high', label: 'high(高)' },
55
+ { value: 'max', label: 'max(最高)' },
56
+ ]
57
+
58
+ // 配置页维护卡可写字段;addressAs 走专用 /settings/address 接口。
59
+ const MAINTENANCE_CONFIG_FIELDS = [
60
+ 'maintenanceEnabled',
61
+ 'maintenanceTime',
62
+ 'maintenanceReasoningEffort',
63
+ 'maintenanceMaxAttempts',
64
+ 'maintenanceRetryMinutes',
65
+ ]
66
+
67
+ const ADVANCED_DEFAULTS = {
68
+ remeEndpoint: 'http://127.0.0.1:2333',
69
+ jurisdictions: ['~/dsh'],
70
+ captureEnabled: true,
71
+ captureInterval: 5,
72
+ heartbeatEnabled: false,
73
+ heartbeatActiveStart: '08:00',
74
+ heartbeatActiveEnd: '23:00',
75
+ dreamEnabled: true,
76
+ outingCleanupEnabled: true,
77
+ jurisdictionOutingEnabled: true,
78
+ jurisdictionOutingTime: '22:45',
79
+ timezone: 'Asia/Shanghai',
80
+ stickerMinGapMinutes: 30,
81
+ stickerMaxPerDay: 12,
82
+ maintenanceEnabled: true,
83
+ maintenanceTime: '23:00',
84
+ maintenanceReasoningEffort: 'low',
85
+ maintenanceMaxAttempts: 2,
86
+ maintenanceRetryMinutes: 30,
87
+ addressAs: '',
88
+ imOwnerOnly: true,
89
+ }
90
+
91
+ // 高级页可提交字段:明确排除家路径;长期记忆地址在“配置”页的卡片里保存。
92
+ const ADVANCED_FIELDS = [
93
+ 'jurisdictions',
94
+ 'captureEnabled',
95
+ 'captureInterval',
96
+ 'heartbeatEnabled',
97
+ 'heartbeatActiveStart',
98
+ 'heartbeatActiveEnd',
99
+ 'dreamEnabled',
100
+ 'outingCleanupEnabled',
101
+ 'jurisdictionOutingEnabled',
102
+ 'jurisdictionOutingTime',
103
+ 'timezone',
104
+ 'stickerMinGapMinutes',
105
+ 'stickerMaxPerDay',
106
+ 'maintenanceEnabled',
107
+ 'maintenanceTime',
108
+ 'maintenanceReasoningEffort',
109
+ 'maintenanceMaxAttempts',
110
+ 'maintenanceRetryMinutes',
111
+ 'addressAs',
112
+ 'imOwnerOnly',
113
+ ]
114
+
115
+ // 读取配置时需要的全部字段(含 ReMe 地址);ReMe 地址不出现于高级页。
116
+ const CONFIG_FIELDS = ['remeEndpoint', ...ADVANCED_FIELDS]
117
+
118
+ const TAB_ITEMS = [
119
+ { value: 'config', label: '配置', id: 'ta-tab-config', panelId: 'ta-panel-config' },
120
+ { value: 'persona', label: '人设', id: 'ta-tab-persona', panelId: 'ta-panel-persona' },
121
+ { value: 'status', label: '状态', id: 'ta-tab-status', panelId: 'ta-panel-status' },
122
+ { value: 'advanced', label: '高级', id: 'ta-tab-advanced', panelId: 'ta-panel-advanced' },
123
+ ]
124
+
125
+ // --- 纯函数(格式化 / 校验 / 文案) ---
126
+
127
+ function parseJurisdictions(text) {
128
+ return String(text == null ? '' : text).split(/\r?\n/).map(item => item.trim()).filter(Boolean)
129
+ }
130
+
131
+ function isHttpUrl(value) {
132
+ try {
133
+ const url = new URL(String(value))
134
+ return url.protocol === 'http:' || url.protocol === 'https:'
135
+ } catch {
136
+ return false
137
+ }
138
+ }
139
+
140
+ function formatCheckedAt(value) {
141
+ if (!value) return ''
142
+ try {
143
+ const date = new Date(value)
144
+ if (Number.isNaN(date.getTime())) return ''
145
+ return date.toLocaleTimeString('zh-CN', { hour12: false })
146
+ } catch {
147
+ return ''
148
+ }
149
+ }
150
+
151
+ function describeReme(reme) {
152
+ if (!reme) return 'ReMe 状态未知'
153
+ if (reme.state === 'connected') return 'ReMe 已连接'
154
+ if (reme.state === 'error') return 'ReMe 异常'
155
+ return 'ReMe 未连接'
156
+ }
157
+
158
+ function describeRemeShort(reme) {
159
+ if (!reme) return '未检测'
160
+ if (reme.state === 'connected') return '已连接'
161
+ if (reme.state === 'error') return '异常'
162
+ if (reme.state === 'disconnected') return '未连接'
163
+ return '未检测'
164
+ }
165
+
166
+ function remeTone(reme) {
167
+ if (!reme) return 'idle'
168
+ if (reme.state === 'connected') return 'success'
169
+ if (reme.state === 'error') return 'error'
170
+ return 'warn'
171
+ }
172
+
173
+ function imCompatible(im) {
174
+ if (!im) return false
175
+ if (Array.isArray(im.accounts) && im.accounts.some(account => account && account.compatible === true)) return true
176
+ return im.compatible === true
177
+ }
178
+
179
+ function describeIm(im) {
180
+ if (!im) return 'IM 状态未知'
181
+ if (im.installed === false) return 'IM 未安装'
182
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
183
+ if (imCompatible(im)) return 'IM 已连接'
184
+ if (accounts.length > 0) return 'IM 已连接但不匹配'
185
+ return 'IM 未连接'
186
+ }
187
+
188
+ function describeImShort(im) {
189
+ if (!im) return '未检测'
190
+ if (im.installed === false) return '未安装'
191
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
192
+ if (imCompatible(im)) return '已连接'
193
+ if (accounts.length > 0) return '不匹配'
194
+ return '未连接'
195
+ }
196
+
197
+ function imTone(im) {
198
+ if (!im) return 'idle'
199
+ if (im.installed === false) return 'idle'
200
+ if (imCompatible(im)) return 'success'
201
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
202
+ return accounts.length > 0 ? 'warn' : 'idle'
203
+ }
204
+
205
+ function describeRemeDetail(reme) {
206
+ if (!reme) return '尚未检测'
207
+ if (reme.state === 'connected') {
208
+ const checked = formatCheckedAt(reme.checkedAt)
209
+ return checked ? `已连接 · 检查于 ${checked}` : '已连接'
210
+ }
211
+ if (reme.state === 'error') {
212
+ const checked = formatCheckedAt(reme.checkedAt)
213
+ return `${reme.message || '健康检查失败'}${checked ? ` · 检查于 ${checked}` : ''}`
214
+ }
215
+ return reme.message || '未连接;TA 仍可聊天,但不会长期记住以前的事。'
216
+ }
217
+
218
+ function describeImSummary(im) {
219
+ if (!im) return '尚未检测'
220
+ if (im.installed === false) return '未安装 IM Connect'
221
+ if (imCompatible(im)) return '有兼容的私聊账号'
222
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
223
+ return accounts.length > 0 ? '检测到账号,但未全部符合条件' : '还没有 IM 会话'
224
+ }
225
+
226
+ /** 整体生命周期:未初始化 / 可用 / 降级可用 / 需要处理 / 转生中。 */
227
+ function overallStatus(status) {
228
+ const lifecycle = status && status.lifecycle
229
+ if (lifecycle === 'reincarnating') {
230
+ return { label: '转生中', tone: 'business', hint: '正在准备新的家;完成后会自动刷新。' }
231
+ }
232
+ if (!status || !status.initialized) {
233
+ return { label: '未初始化', tone: 'idle', hint: '先创建 TA 的家,再写 SOUL;self、RECENT 和认识会随维护逐步生成。' }
234
+ }
235
+ const core = status.core && typeof status.core === 'object' ? status.core : {}
236
+ const soul = core.soul && typeof core.soul === 'object' ? core.soul : {}
237
+ const soulBudget = Number(soul.cap) || DEFAULT_PERSONA_BUDGETS.soul
238
+ const problems = []
239
+ if (status.writable === false) problems.push('TA 的家当前不可写')
240
+ if ((Number(soul.chars) || 0) > soulBudget) problems.push('SOUL 超出预算,超出部分不会被注入')
241
+ if (problems.length > 0) {
242
+ return { label: '需要处理', tone: 'error', hint: `${problems.join(';')}。` }
243
+ }
244
+ const gaps = []
245
+ if (!status.reme || status.reme.state !== 'connected') gaps.push(describeReme(status.reme))
246
+ if (!imCompatible(status.im)) gaps.push(describeIm(status.im))
247
+ if (gaps.length > 0) {
248
+ return { label: '降级可用', tone: 'warn', hint: `${gaps.join(';')}。补齐后体验更完整,不影响现在聊天。` }
249
+ }
250
+ return { label: '可用', tone: 'success', hint: '本地四件套、ReMe 和 IM 都正常。' }
251
+ }
252
+
253
+ function buildSoulPreview(text, budget) {
254
+ const content = String(text == null ? '' : text).trim()
255
+ if (!content) return '# 我的人格\n(空:实际不会注入这一节)'
256
+ if (content.length > budget) {
257
+ return `# 我的人格\n${content.slice(0, budget)}\n…(超出预算的 ${content.length - budget} 字在注入时被截断)`
258
+ }
259
+ return `# 我的人格\n${content}`
260
+ }
261
+
262
+ /** 称呼只保留单行并截到 40 字,与 Host 的归一化保持一致。 */
263
+ function trimAddress(value) {
264
+ return String(value == null ? '' : value)
265
+ .replace(/[\r\n]+/g, ' ')
266
+ .trim()
267
+ .slice(0, ADDRESS_MAX_CHARS)
268
+ }
269
+
270
+ function formatDateTime(value) {
271
+ if (!value) return ''
272
+ try {
273
+ const date = new Date(value)
274
+ if (Number.isNaN(date.getTime())) return ''
275
+ return date.toLocaleString('zh-CN', { hour12: false })
276
+ } catch {
277
+ return ''
278
+ }
279
+ }
280
+
281
+ function formatMoney(value) {
282
+ if (value == null) return ''
283
+ const number = Number(value)
284
+ return Number.isFinite(number) ? `¥${number.toFixed(3)}` : ''
285
+ }
286
+
287
+ function maintenanceRunLabel(value) {
288
+ if (value === 'ok') return '成功'
289
+ if (value === 'partial') return '部分成功'
290
+ if (value === 'failed') return '失败'
291
+ return value ? String(value) : '未知'
292
+ }
293
+
294
+ function describeImMode(mode) {
295
+ return mode === 'reduced' ? 'reduced(简化注入)' : 'owner(视为本人)'
296
+ }
297
+
298
+ const IM_REASON_LABELS = {
299
+ CWD_MISMATCH: '工作目录不是这个家',
300
+ CWD_NOT_HOME: '工作目录不是这个家',
301
+ PRESET_MISMATCH: '代理预设不是 ta',
302
+ AGENT_PRESET_MISMATCH: '代理预设不是 ta',
303
+ GROUP_ACCESS_ENABLED: '群聊没有关闭',
304
+ GROUP_ACCESS: '群聊没有关闭',
305
+ PRIVATE_ACCESS_DENIED: '私聊没有放行',
306
+ PRIVATE_ACCESS: '私聊没有放行',
307
+ DISABLED: '账号已停用',
308
+ NOT_BOUND: '会话还没有绑定',
309
+ }
310
+
311
+ function imReasonText(reason) {
312
+ if (typeof reason !== 'string' || !reason.trim()) return ''
313
+ const key = reason.trim()
314
+ if (IM_REASON_LABELS[key]) return IM_REASON_LABELS[key]
315
+ return /^[A-Z][A-Z0-9_]*$/.test(key) ? `未满足条件:${key}` : key
316
+ }
317
+
318
+ function imAccountReasons(account, home) {
319
+ if (!account || typeof account !== 'object') return []
320
+ // Host 已经返回中文原因时直接展示,避免和本地推断重复。
321
+ if (Array.isArray(account.reasons)) {
322
+ const hostReasons = account.reasons.map(imReasonText).filter(Boolean)
323
+ if (hostReasons.length > 0) return hostReasons
324
+ }
325
+ const reasons = []
326
+ if (home && account.cwd && account.cwd !== home) reasons.push('工作目录不是 TA 的家')
327
+ if (account.agentPreset !== undefined && account.agentPreset !== 'ta') reasons.push('没有使用 ta 预设')
328
+ if (account.groupAccess !== undefined && account.groupAccess !== 'disabled') reasons.push('群聊权限没有关闭')
329
+ if (account.privateAccess !== undefined && account.privateAccess !== 'approved') reasons.push('私聊权限不是仅批准用户')
330
+ if (account.enabled === false) reasons.push('账号已停用')
331
+ return reasons
332
+ }
333
+
334
+ function imGuidance(im) {
335
+ if (!im) return '尚未检测到 IM Connect。'
336
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
337
+ if (im.installed === false) {
338
+ return '还没有安装 IM Connect。安装后,在 IM Connect 新建一个工作目录为 TA 的家、预设为 ta、只开放私聊的账号,就能在 IM 里找到 TA。'
339
+ }
340
+ if (imCompatible(im)) return '已经有一个兼容的私聊账号,可以在 IM 里直接找 TA。'
341
+ if (accounts.length === 0) {
342
+ return '还没有 IM 会话。在 IM Connect 新建一个工作目录为 TA 的家、预设为 ta、只开放私聊的账号。'
343
+ }
344
+ return '检测到账号,但还没有全部满足条件。下面列出了每项原因;可以在 IM Connect 里调整,或新建一个兼容账号。'
345
+ }
346
+
347
+ // ===== 2. 样式 =====
348
+
349
+ const TA_CSS = `
350
+ .ta-root{position:relative;box-sizing:border-box;width:100%;max-width:900px;margin:0 auto;padding:4px 2px 36px;color:inherit;container-type:inline-size;animation:ta-fade-in .25s ease both}
351
+ .ta-root *,.ta-root *::before,.ta-root *::after{box-sizing:border-box}
352
+ .ta-root button,.ta-root input,.ta-root textarea,.ta-root select{font-family:inherit}
353
+ .ta-root :focus-visible{outline:2px solid var(--dsw-alias-brand-primary,currentColor);outline-offset:2px}
354
+ .ta-panel{display:block}
355
+ .ta-panel[hidden]{display:none}
356
+ .ta-page{display:grid;gap:14px;animation:ta-rise-in .3s cubic-bezier(.22,1,.36,1) both}
357
+
358
+ /* 顶部 SegmentedTabs */
359
+ .ta-tabs{display:flex;gap:3px;padding:3px;margin:0 0 15px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:12px;background:var(--dsw-alias-bg-layer-2,transparent);overflow-x:auto;scrollbar-width:none}
360
+ .ta-tabs::-webkit-scrollbar{display:none}
361
+ .ta-tab{flex:1 0 auto;min-width:78px;height:30px;padding:0 14px;border:1px solid transparent;border-radius:9px;background:transparent;color:var(--dsw-alias-label-tertiary,inherit);font-size:12.5px;font-weight:500;cursor:pointer;white-space:nowrap;transition:background .2s,color .2s,border-color .2s,box-shadow .2s}
362
+ .ta-tab:hover{color:var(--dsw-alias-label-primary,inherit)}
363
+ .ta-tab.is-active{background:var(--dsw-alias-bg-layer-1,var(--dsw-alias-bg-layer-2,transparent));border-color:var(--dsw-alias-border-l2,transparent);color:var(--dsw-alias-label-primary,inherit);font-weight:600;box-shadow:0 2px 8px -4px var(--dsw-alias-border-l2,transparent)}
364
+
365
+ /* 页头 */
366
+ .ta-page-head{margin:2px 0 0}
367
+ .ta-overline{display:block;font-size:10.5px;font-weight:700;letter-spacing:.18em;text-transform:uppercase;color:var(--dsw-alias-brand-primary,var(--dsw-alias-label-secondary,inherit));opacity:.92}
368
+ .ta-h1{margin:5px 0 0;font-size:21px;font-weight:700;letter-spacing:-.01em;line-height:1.25}
369
+ .ta-desc{margin:7px 0 0;font-size:12.5px;line-height:1.6;color:var(--dsw-alias-label-tertiary,var(--dsw-alias-label-secondary,inherit));max-width:62ch}
370
+
371
+ /* 卡片与栅格 */
372
+ .ta-card{min-width:0;padding:18px;border:1px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1,transparent));border-radius:16px;background:var(--dsw-alias-bg-layer-1,transparent)}
373
+ .ta-card-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
374
+ .ta-card-head-main{min-width:0}
375
+ .ta-card-head-side{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
376
+ .ta-card-title{margin:0;font-size:14px;font-weight:650;letter-spacing:.01em;line-height:1.35}
377
+ .ta-card-desc{margin:4px 0 0;font-size:12px;line-height:1.55;color:var(--dsw-alias-label-tertiary,var(--dsw-alias-label-secondary,inherit))}
378
+ .ta-card-body{display:grid;gap:12px;margin-top:14px}
379
+ .ta-grid{display:grid;gap:14px;min-width:0}
380
+ .ta-grid--2{grid-template-columns:repeat(2,minmax(0,1fr))}
381
+ .ta-grid--2 > .ta-card{align-content:start}
382
+ .ta-grid > .ta-card{min-width:0}
383
+ .ta-grid--full{grid-column:1 / -1}
384
+
385
+ /* 服务就绪条 */
386
+ .ta-ready{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;min-width:0}
387
+ .ta-ready-item{display:flex;align-items:center;gap:9px;min-width:0;padding:11px 13px;border:1px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1,transparent));border-radius:12px;background:var(--dsw-alias-bg-layer-1,transparent)}
388
+ .ta-dot{width:8px;height:8px;flex:none;border-radius:50%;background:var(--dsw-alias-label-quaternary,var(--dsw-alias-label-tertiary,currentColor))}
389
+ .ta-ready-item.is-success .ta-dot{background:var(--dsw-alias-state-success-primary,currentColor)}
390
+ .ta-ready-item.is-warn .ta-dot{background:var(--dsw-alias-state-warn-primary,currentColor)}
391
+ .ta-ready-item.is-error .ta-dot{background:var(--dsw-alias-state-error-primary,currentColor)}
392
+ .ta-ready-text{display:grid;gap:1px;min-width:0}
393
+ .ta-ready-label{font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
394
+ .ta-ready-value{font-size:12.5px;font-weight:600}
395
+ .ta-ready-detail{font-size:11px;color:var(--dsw-alias-label-tertiary,inherit);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
396
+
397
+ /* badge */
398
+ .ta-badge{display:inline-flex;align-items:center;gap:5px;padding:2px 9px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:999px;background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-secondary,inherit);font-size:11.5px;font-weight:600;line-height:1.6;white-space:nowrap}
399
+ .ta-badge-dot{width:6px;height:6px;flex:none;border-radius:50%;background:currentColor}
400
+ .ta-badge--success{color:var(--dsw-alias-state-success-primary,inherit);border-color:var(--dsw-alias-state-success-secondary,var(--dsw-alias-border-l2,transparent))}
401
+ .ta-badge--warn{color:var(--dsw-alias-state-warn-primary,inherit);border-color:var(--dsw-alias-state-warn-secondary,var(--dsw-alias-border-l2,transparent))}
402
+ .ta-badge--error{color:var(--dsw-alias-state-error-primary,inherit);border-color:var(--dsw-alias-state-error-secondary,var(--dsw-alias-border-l2,transparent))}
403
+ .ta-badge--business{color:var(--dsw-alias-state-business-primary,inherit);border-color:var(--dsw-alias-border-l2,transparent)}
404
+ .ta-badge--idle{color:var(--dsw-alias-label-tertiary,inherit);border-color:var(--dsw-alias-border-l2,transparent)}
405
+ .ta-file-badge{display:inline-flex;align-items:center;padding:2px 8px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:999px;background:var(--dsw-alias-bg-layer-2,transparent);color:var(--dsw-alias-label-tertiary,inherit);font-size:11px;font-weight:600;letter-spacing:.03em;white-space:nowrap}
406
+
407
+ /* 按钮 */
408
+ .ta-btn{display:inline-flex;align-items:center;justify-content:center;gap:7px;height:34px;padding:0 14px;border:1px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1,transparent));border-radius:10px;background:var(--dsw-alias-button-elevated-fill,var(--dsw-alias-bg-layer-2,transparent));color:inherit;font-size:12.5px;font-weight:550;cursor:pointer;white-space:nowrap;transition:transform .18s ease,box-shadow .18s ease,background .18s ease,border-color .18s ease,opacity .18s ease}
409
+ .ta-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2,transparent);border-color:var(--dsw-alias-border-l1,var(--dsw-alias-border-l2,transparent));transform:translateY(-1px)}
410
+ .ta-btn:active:not(:disabled){transform:none}
411
+ .ta-btn:disabled{opacity:.5;cursor:not-allowed}
412
+ .ta-btn--primary{background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary,transparent));border-color:var(--dsw-alias-brand-primary,transparent);color:var(--dsw-alias-brand-text,var(--dsw-alias-label-primary-foreground,currentColor))}
413
+ .ta-btn--primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary,transparent));border-color:var(--dsw-alias-brand-primary,transparent)}
414
+ .ta-btn--ghost{background:transparent;border-color:transparent;color:var(--dsw-alias-label-secondary,inherit);font-weight:500}
415
+ .ta-btn--ghost:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2,transparent);border-color:transparent}
416
+ .ta-btn--danger{background:var(--dsw-alias-state-error-primary,transparent);border-color:transparent;color:var(--dsw-alias-label-on-color,var(--dsw-alias-label-primary-foreground,currentColor))}
417
+ .ta-spinner{width:12px;height:12px;flex:none;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:ta-spin .7s linear infinite}
418
+ .ta-actions{display:flex;align-items:center;gap:9px;flex-wrap:wrap;min-width:0}
419
+ .ta-actions-end{margin-left:auto}
420
+
421
+ /* notice */
422
+ .ta-notice{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 12px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent);font-size:12px;line-height:1.55;min-width:0}
423
+ .ta-notice-main{min-width:0;flex:1}
424
+ .ta-notice-title{display:block;margin-bottom:2px;font-size:12.5px;font-weight:650;color:var(--dsw-alias-label-primary,inherit)}
425
+ .ta-notice-text{color:var(--dsw-alias-label-secondary,inherit);overflow-wrap:anywhere}
426
+ .ta-notice-action{flex:none}
427
+ .ta-notice--success{border-color:var(--dsw-alias-state-success-secondary,var(--dsw-alias-border-l2,transparent));background:var(--dsw-alias-bg-layer-1,transparent)}
428
+ .ta-notice--success .ta-notice-title{color:var(--dsw-alias-state-success-primary,inherit)}
429
+ .ta-notice--warn{border-color:var(--dsw-alias-state-warn-secondary,var(--dsw-alias-border-l2,transparent));background:var(--dsw-alias-bg-layer-1,transparent)}
430
+ .ta-notice--warn .ta-notice-title{color:var(--dsw-alias-state-warn-primary,inherit)}
431
+ .ta-notice--error{border-color:var(--dsw-alias-state-error-secondary,var(--dsw-alias-border-l2,transparent));background:var(--dsw-alias-bg-layer-1,transparent)}
432
+ .ta-notice--error .ta-notice-title{color:var(--dsw-alias-state-error-primary,inherit)}
433
+ .ta-notice--info{border-color:var(--dsw-alias-border-l2,transparent)}
434
+
435
+ /* 文字 */
436
+ .ta-text{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,inherit)}
437
+ .ta-hint{margin:0;font-size:11px;line-height:1.55;color:var(--dsw-alias-label-tertiary,inherit)}
438
+ .ta-muted{font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-tertiary,inherit)}
439
+ .ta-subtitle{margin:0;font-size:13px;font-weight:650;line-height:1.4}
440
+ .ta-ok-text{color:var(--dsw-alias-state-success-primary,inherit);font-size:11.5px}
441
+ .ta-warn-text{color:var(--dsw-alias-state-warn-primary,inherit);font-size:11.5px}
442
+ .ta-error-text{color:var(--dsw-alias-state-error-primary,inherit);font-size:11.5px}
443
+ .ta-callout{padding:11px 12px;border:1px dashed var(--dsw-alias-border-l2,transparent);border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent);font-size:11.5px;line-height:1.6;color:var(--dsw-alias-label-secondary,inherit);min-width:0}
444
+ .ta-callout strong{display:block;margin-bottom:3px;color:var(--dsw-alias-label-primary,inherit);font-size:12px}
445
+ .ta-callout .ta-hint{overflow-wrap:anywhere}
446
+
447
+ /* 表单 */
448
+ .ta-field{display:grid;gap:6px;min-width:0}
449
+ .ta-label{font-size:12.5px;font-weight:600;color:var(--dsw-alias-label-primary,inherit)}
450
+ .ta-input,.ta-textarea{width:100%;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1,transparent));border-radius:9px;background:var(--dsw-alias-bg-layer-1,transparent);color:inherit;font-size:12.5px;outline:none;transition:border-color .2s}
451
+ .ta-input:focus,.ta-textarea:focus{border-color:var(--dsw-alias-brand-primary,var(--dsw-alias-border-l2,transparent))}
452
+ .ta-input:disabled,.ta-textarea:disabled{opacity:.6;cursor:not-allowed}
453
+ .ta-input::placeholder,.ta-textarea::placeholder{color:var(--dsw-alias-label-quaternary,var(--dsw-alias-label-tertiary,inherit))}
454
+ .ta-input--number{max-width:150px}
455
+ .ta-textarea{min-height:120px;resize:vertical;line-height:1.55}
456
+ .ta-textarea--tall{min-height:200px}
457
+ .ta-counter{display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit);min-width:0}
458
+ .ta-counter-warn{color:var(--dsw-alias-state-warn-primary,inherit)}
459
+ .ta-counter-error{color:var(--dsw-alias-state-error-primary,inherit)}
460
+ .ta-check{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:start;gap:9px;padding:8px 0;cursor:pointer}
461
+ .ta-check input[type="checkbox"]{width:15px;height:15px;margin:3px 0 0;accent-color:var(--dsw-alias-brand-primary,currentColor)}
462
+ .ta-check-copy{display:grid;gap:2px;min-width:0}
463
+ .ta-check-title{font-size:12.5px;font-weight:600}
464
+ .ta-check-hint{font-size:11px;line-height:1.55;color:var(--dsw-alias-label-tertiary,inherit)}
465
+
466
+ /* toggle */
467
+ .ta-toggle-row{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;padding:9px 0;border-bottom:1px solid var(--dsw-alias-border-l1,transparent)}
468
+ .ta-toggle-row:last-child{border-bottom:0}
469
+ .ta-toggle-copy{display:grid;gap:2px;min-width:0}
470
+ .ta-toggle-label{font-size:12.5px;font-weight:550}
471
+ .ta-toggle{position:relative;flex:none;width:40px;height:23px;margin-top:2px;padding:0;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:999px;background:var(--dsw-alias-bg-layer-2,transparent);cursor:pointer;transition:background .24s,border-color .24s}
472
+ .ta-toggle:disabled{opacity:.55;cursor:not-allowed}
473
+ .ta-toggle-knob{position:absolute;top:2px;left:2px;width:17px;height:17px;border-radius:50%;background:var(--dsw-alias-label-secondary,currentColor);transition:transform .24s cubic-bezier(.22,1,.36,1),background .24s}
474
+ .ta-toggle.is-on{background:var(--dsw-alias-brand-primary,transparent);border-color:var(--dsw-alias-brand-primary,transparent)}
475
+ .ta-toggle.is-on .ta-toggle-knob{transform:translateX(17px);background:var(--dsw-alias-brand-text,var(--dsw-alias-label-primary-foreground,currentColor))}
476
+
477
+ /* facts / 统计 */
478
+ .ta-facts{display:grid;gap:8px;margin:0;min-width:0}
479
+ .ta-fact{display:grid;grid-template-columns:82px minmax(0,1fr);gap:10px;align-items:baseline;min-width:0}
480
+ .ta-fact-label{margin:0;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
481
+ .ta-fact-value{margin:0;font-size:12px;line-height:1.55;overflow-wrap:anywhere}
482
+ .ta-status-hero{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:12px 14px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:12px;background:var(--dsw-alias-bg-layer-1,transparent)}
483
+ .ta-status-line{display:flex;align-items:center;gap:9px;flex-wrap:wrap;font-size:12px;min-width:0}
484
+ .ta-usage-bar{display:grid;gap:6px;min-width:0}
485
+ .ta-usage-bar-head{display:flex;align-items:baseline;justify-content:space-between;gap:10px;font-size:12px}
486
+ .ta-bar{height:5px;border-radius:999px;background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,transparent));overflow:hidden}
487
+ .ta-bar-fill{height:100%;border-radius:999px;background:var(--dsw-alias-brand-primary,currentColor)}
488
+ .ta-bar-fill.is-over{background:var(--dsw-alias-state-warn-primary,currentColor)}
489
+
490
+ /* 折叠“TA 的家” */
491
+ .ta-fold{display:grid;gap:0;min-width:0}
492
+ .ta-fold-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;width:100%;padding:12px 14px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:12px;background:var(--dsw-alias-bg-layer-2,transparent);color:inherit;font:inherit;text-align:left;cursor:pointer;transition:border-color .2s,background .2s}
493
+ .ta-fold-head:hover{border-color:var(--dsw-alias-border-l1,var(--dsw-alias-border-l2,transparent));background:var(--dsw-alias-bg-layer-1,transparent)}
494
+ .ta-fold-icon{display:grid;place-items:center;width:16px;height:16px;flex:none;color:var(--dsw-alias-label-tertiary,inherit)}
495
+ .ta-fold-path{flex:1 1 180px;min-width:0;font-size:12.5px;overflow-wrap:anywhere}
496
+ .ta-status-path{display:inline-flex;align-items:flex-start;gap:5px;min-width:0;max-width:100%;color:inherit}
497
+ .ta-status-path > svg{flex:none;margin-top:2px;color:var(--dsw-alias-label-tertiary,inherit)}
498
+ .ta-status-path > span{min-width:0;overflow-wrap:anywhere}
499
+ .ta-fold-action{margin-left:auto;font-size:12px;color:var(--dsw-alias-brand-text,var(--dsw-alias-brand-primary,inherit))}
500
+ .ta-fold-chevron{font-size:10px;color:var(--dsw-alias-label-tertiary,inherit)}
501
+ .ta-fold-body{display:grid;gap:12px;margin-top:12px;animation:ta-rise-in .28s cubic-bezier(.22,1,.36,1) both}
502
+ .ta-lifecycle{display:grid;gap:10px;padding-top:2px}
503
+ .ta-lifecycle + .ta-lifecycle{padding-top:12px;border-top:1px solid var(--dsw-alias-border-l2,transparent)}
504
+ .ta-danger-box{display:grid;gap:8px;padding:11px 12px;border:1px solid var(--dsw-alias-state-error-secondary,var(--dsw-alias-border-l2,transparent));border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent)}
505
+
506
+ /* 人设 */
507
+ .ta-persona-list{display:grid;gap:10px;padding-left:16px;margin:0;font-size:11px;line-height:1.6;color:var(--dsw-alias-label-tertiary,inherit)}
508
+ .ta-preview-box{display:grid;gap:8px;padding:11px 12px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent)}
509
+ .ta-preview{margin:0;max-height:250px;overflow:auto;padding:0;border:0;background:transparent;color:var(--dsw-alias-label-secondary,inherit);font-family:ui-monospace,"Cascadia Mono","SF Mono",Consolas,"Courier New",monospace;font-size:11.5px;line-height:1.6;white-space:pre-wrap;word-break:break-word}
510
+
511
+ /* IM 账号 */
512
+ .ta-accounts{list-style:none;margin:0;padding:0;display:grid;gap:8px;min-width:0}
513
+ .ta-account{display:grid;gap:5px;min-width:0;padding:9px 10px;border:1px solid var(--dsw-alias-border-l1,var(--dsw-alias-border-l2,transparent));border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent)}
514
+ .ta-account-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px}
515
+ .ta-reasons{margin:0;padding-left:16px;font-size:11px;line-height:1.6;color:var(--dsw-alias-state-warn-primary,inherit)}
516
+
517
+ /* 花销卡 */
518
+ .ta-usage-top{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap}
519
+ .ta-usage-money{font-size:18px;font-weight:700;line-height:1.2}
520
+ .ta-usage-meta{font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
521
+ .ta-usage-links{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:8px;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
522
+ .ta-link{color:inherit;text-decoration:underline}
523
+ .ta-link--danger{background:none;border:0;padding:0;font:inherit;cursor:pointer;color:var(--dsw-alias-state-error-primary,inherit)}
524
+ .ta-usage-reset{display:grid;gap:8px;margin-top:10px;padding:10px 12px;border:1px solid var(--dsw-alias-border-l2,transparent);border-radius:10px;background:var(--dsw-alias-bg-layer-2,transparent)}
525
+ .ta-usage-rows{display:grid;gap:4px;margin-top:10px;font-size:11px;color:var(--dsw-alias-label-secondary,inherit)}
526
+ .ta-usage-row{display:flex;justify-content:space-between;gap:12px;min-width:0}
527
+
528
+ /* 窄屏 */
529
+ @container (max-width:760px){
530
+ .ta-grid--2{grid-template-columns:1fr}
531
+ .ta-ready{grid-template-columns:1fr}
532
+ .ta-card{padding:15px;border-radius:14px}
533
+ .ta-h1{font-size:18px}
534
+ .ta-desc{font-size:12px}
535
+ .ta-tab{min-width:72px;padding:0 12px}
536
+ .ta-fact{grid-template-columns:74px minmax(0,1fr)}
537
+ }
538
+ @container (max-width:440px){
539
+ .ta-page{gap:11px}
540
+ .ta-card{padding:13px}
541
+ .ta-toggle-row{gap:10px}
542
+ .ta-notice{align-items:flex-start;flex-direction:column}
543
+ .ta-notice-action{align-self:flex-start}
544
+ }
545
+
546
+ /* 动效 */
547
+ @keyframes ta-fade-in{from{opacity:0}to{opacity:1}}
548
+ @keyframes ta-rise-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
549
+ @keyframes ta-spin{to{transform:rotate(360deg)}}
550
+ @media (prefers-reduced-motion:reduce){
551
+ .ta-root *,.ta-root *::before,.ta-root *::after{animation-duration:.01ms !important;animation-iteration-count:1 !important;transition-duration:.01ms !important}
552
+ }
553
+ `
554
+
555
+ // ===== 3. API 基础 =====
556
+
557
+ class ApiError extends Error {
558
+ constructor(message, options = {}) {
559
+ super(message)
560
+ this.name = 'ApiError'
561
+ this.status = Number(options.status) || 0
562
+ this.code = options.code || ''
563
+ this.cancelled = options.cancelled === true
564
+ this.unavailable = options.unavailable === true
565
+ this.network = options.network === true
566
+ this.timeout = options.timeout === true
567
+ }
568
+ }
569
+
570
+ function errorMessage(cause) {
571
+ if (cause instanceof Error && cause.message) return cause.message
572
+ if (typeof cause === 'string' && cause) return cause
573
+ return '操作失败,请重试'
574
+ }
575
+
576
+ async function requestJson(path, options = {}) {
577
+ const init = {
578
+ method: options.method || 'GET',
579
+ cache: 'no-store',
580
+ credentials: 'same-origin',
581
+ signal: options.signal,
582
+ }
583
+ if (options.body !== undefined) {
584
+ init.headers = { 'content-type': 'application/json' }
585
+ init.body = JSON.stringify(options.body)
586
+ }
587
+ let response
588
+ try {
589
+ response = await fetch(`${API_ROOT}${path}`, init)
590
+ } catch (cause) {
591
+ if (cause && cause.name === 'AbortError') throw new ApiError('请求已取消', { cancelled: true })
592
+ throw new ApiError('网络连接失败,请检查网络或 Host 服务后重试', { network: true })
593
+ }
594
+ let payload = null
595
+ try {
596
+ payload = await response.json()
597
+ } catch {
598
+ payload = null
599
+ }
600
+ if (response.status === 404) {
601
+ throw new ApiError(
602
+ (payload && payload.error && payload.error.message) || '设置接口不可用,请确认 dsh-ta 设置服务已挂载',
603
+ { status: 404, code: 'NOT_FOUND', unavailable: true },
604
+ )
605
+ }
606
+ if (!response.ok || (payload && payload.ok === false)) {
607
+ throw new ApiError(
608
+ (payload && payload.error && payload.error.message) || `请求失败(HTTP ${response.status})`,
609
+ { status: response.status, code: (payload && payload.error && payload.error.code) || '' },
610
+ )
611
+ }
612
+ if (!payload || typeof payload !== 'object') {
613
+ throw new ApiError('设置接口返回了无法识别的响应,请重试', { status: response.status })
614
+ }
615
+ return payload && payload.ok !== undefined ? payload.data : payload
616
+ }
617
+
618
+ // ===== 4. 通用 hooks =====
619
+
620
+ function useAlive() {
621
+ const alive = React.useRef(true)
622
+ React.useEffect(() => {
623
+ alive.current = true
624
+ return () => {
625
+ alive.current = false
626
+ }
627
+ }, [])
628
+ return alive
629
+ }
630
+
631
+ /** 每个请求独立 AbortController + 8s 超时;组件卸载时终止全部请求。 */
632
+ function useApi() {
633
+ const alive = useAlive()
634
+ const controllers = React.useRef(new Set())
635
+ React.useEffect(() => () => {
636
+ for (const controller of controllers.current) controller.abort()
637
+ controllers.current.clear()
638
+ }, [])
639
+
640
+ const call = React.useCallback(async (path, options = {}) => {
641
+ const controller = new AbortController()
642
+ controllers.current.add(controller)
643
+ let timedOut = false
644
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : REQUEST_TIMEOUT_MS
645
+ const timer = setTimeout(() => {
646
+ timedOut = true
647
+ controller.abort()
648
+ }, timeoutMs)
649
+ try {
650
+ return await requestJson(path, { ...options, signal: controller.signal })
651
+ } catch (cause) {
652
+ if (timedOut) throw new ApiError('请求超时,请检查网络后重试', { timeout: true, code: 'TIMEOUT' })
653
+ if (controller.signal.aborted) throw new ApiError('请求已取消', { cancelled: true })
654
+ throw cause
655
+ } finally {
656
+ clearTimeout(timer)
657
+ controllers.current.delete(controller)
658
+ }
659
+ }, [])
660
+
661
+ return { call, alive }
662
+ }
663
+
664
+ /**
665
+ * 一个 GET 资源的 loading / ready / error / unavailable 状态。
666
+ * 刷新失败时保留旧数据,页面不闪空。
667
+ */
668
+ function useResource(path, call, alive) {
669
+ const [state, setState] = React.useState({ phase: 'loading', data: null, error: '', code: '', version: 0 })
670
+ const generation = React.useRef(0)
671
+ const load = React.useCallback(async () => {
672
+ const id = ++generation.current
673
+ setState(previous => previous.data
674
+ ? { ...previous, error: '', code: '' }
675
+ : { phase: 'loading', data: null, error: '', code: '', version: previous.version || 0 })
676
+ try {
677
+ const data = await call(path)
678
+ if (!alive.current || id !== generation.current) return
679
+ setState(previous => ({
680
+ phase: 'ready',
681
+ data,
682
+ error: '',
683
+ code: '',
684
+ version: (previous.version || 0) + 1,
685
+ }))
686
+ } catch (cause) {
687
+ if (!alive.current || id !== generation.current) return
688
+ if (cause && cause.cancelled) return
689
+ setState(previous => ({
690
+ phase: cause && cause.unavailable ? 'unavailable' : 'error',
691
+ data: previous.data,
692
+ error: errorMessage(cause),
693
+ code: cause && cause.code ? cause.code : '',
694
+ version: previous.version || 0,
695
+ }))
696
+ }
697
+ }, [path, call, alive])
698
+ React.useEffect(() => {
699
+ void load()
700
+ }, [load])
701
+ return [state, load]
702
+ }
703
+
704
+ /**
705
+ * configForms 中 dsh-ta 节点的读取 / 编辑 / 保存状态。
706
+ * 配置页的 ReMe / 维护 / IM 字段与高级页各自持有一份 draft,
707
+ * 但共用同一个 configForms 节点;保存时只提交自己负责的字段。
708
+ */
709
+ function useConfigForm(configForms) {
710
+ const alive = useAlive()
711
+ const [form, setForm] = React.useState(null)
712
+ const [phase, setPhase] = React.useState('loading')
713
+ const [message, setMessage] = React.useState('')
714
+ const [error, setError] = React.useState('')
715
+ const [draft, setDraft] = React.useState(null)
716
+ const [baseline, setBaseline] = React.useState(null)
717
+ const [jurisdictionText, setJurisdictionTextState] = React.useState(ADVANCED_DEFAULTS.jurisdictions.join('\n'))
718
+ const [saving, setSaving] = React.useState(false)
719
+ const [reloadToken, setReloadToken] = React.useState(0)
720
+ const savingRef = React.useRef(false)
721
+ const editingRef = React.useRef(false)
722
+
723
+ React.useEffect(() => {
724
+ if (!configForms) {
725
+ setPhase('unavailable')
726
+ setMessage('配置服务不可用。')
727
+ return undefined
728
+ }
729
+ let bound
730
+ try {
731
+ bound = configForms.get('dsh-ta')
732
+ setForm(bound)
733
+ } catch (cause) {
734
+ setPhase('unavailable')
735
+ setMessage(errorMessage(cause))
736
+ return undefined
737
+ }
738
+ if (!bound) {
739
+ setPhase('unavailable')
740
+ setMessage('当前 profile 没有提供 dsh-ta 配置。')
741
+ return undefined
742
+ }
743
+ let ready = false
744
+ const timeout = setTimeout(() => {
745
+ if (!ready) {
746
+ setPhase('unavailable')
747
+ setMessage('读取配置超时,请刷新页面重试。')
748
+ }
749
+ }, 10000)
750
+ const read = () => {
751
+ let snapshot
752
+ try {
753
+ snapshot = bound.getSnapshot()
754
+ } catch {
755
+ return
756
+ }
757
+ if (snapshot.status === 'unavailable') {
758
+ ready = true
759
+ setPhase('unavailable')
760
+ setMessage('当前 profile 没有提供 dsh-ta 配置。')
761
+ return
762
+ }
763
+ if (snapshot.status === 'loading' && !snapshot.value) return
764
+ if (!snapshot.value) return
765
+ if (savingRef.current || editingRef.current) return
766
+ const next = {}
767
+ for (const name of CONFIG_FIELDS) {
768
+ next[name] = snapshot.value[name] !== undefined ? snapshot.value[name] : ADVANCED_DEFAULTS[name]
769
+ }
770
+ setDraft(next)
771
+ setBaseline(next)
772
+ setJurisdictionTextState((Array.isArray(next.jurisdictions)
773
+ ? next.jurisdictions
774
+ : ADVANCED_DEFAULTS.jurisdictions).join('\n'))
775
+ ready = true
776
+ setPhase('ready')
777
+ setError('')
778
+ }
779
+ read()
780
+ const unsubscribe = bound.subscribe(read)
781
+ return () => {
782
+ clearTimeout(timeout)
783
+ unsubscribe()
784
+ }
785
+ }, [configForms, reloadToken])
786
+
787
+ const clearNotices = React.useCallback(() => {
788
+ setMessage('')
789
+ setError('')
790
+ }, [])
791
+
792
+ const showError = React.useCallback(text => {
793
+ setMessage('')
794
+ setError(String(text || '操作失败,请重试'))
795
+ }, [])
796
+
797
+ const showMessage = React.useCallback(text => {
798
+ setError('')
799
+ setMessage(String(text || ''))
800
+ }, [])
801
+
802
+ const update = React.useCallback((name, value) => {
803
+ if (savingRef.current) return
804
+ editingRef.current = true
805
+ setDraft(previous => previous ? { ...previous, [name]: value } : previous)
806
+ setMessage('')
807
+ setError('')
808
+ }, [])
809
+
810
+ const setJurisdictionText = React.useCallback(value => {
811
+ if (savingRef.current) return
812
+ editingRef.current = true
813
+ setJurisdictionTextState(value)
814
+ setMessage('')
815
+ setError('')
816
+ }, [])
817
+
818
+ const replaceDraft = React.useCallback(next => {
819
+ if (!next || savingRef.current) return
820
+ editingRef.current = true
821
+ setDraft({ ...next })
822
+ setMessage('')
823
+ setError('')
824
+ }, [])
825
+
826
+ const reload = React.useCallback(() => {
827
+ editingRef.current = false
828
+ setPhase('loading')
829
+ setMessage('')
830
+ setError('')
831
+ setReloadToken(value => value + 1)
832
+ }, [])
833
+
834
+ const resetAll = React.useCallback(() => {
835
+ if (!baseline || savingRef.current) return
836
+ editingRef.current = false
837
+ setDraft({ ...baseline })
838
+ setJurisdictionTextState((Array.isArray(baseline.jurisdictions)
839
+ ? baseline.jurisdictions
840
+ : ADVANCED_DEFAULTS.jurisdictions).join('\n'))
841
+ setMessage('')
842
+ setError('')
843
+ }, [baseline])
844
+
845
+ const save = React.useCallback(async options => {
846
+ const fields = Array.isArray(options && options.fields) ? options.fields : []
847
+ const target = (options && options.target) || draft
848
+ if (!form || !target || !baseline || savingRef.current) return false
849
+ let snapshot
850
+ try {
851
+ snapshot = form.getSnapshot()
852
+ } catch {
853
+ setError('配置状态不可用,请刷新页面重试。')
854
+ return false
855
+ }
856
+ if (snapshot.writable === false) {
857
+ setError('当前 profile 不允许写入配置。')
858
+ return false
859
+ }
860
+ const changed = fields.filter(name => JSON.stringify(target[name]) !== JSON.stringify(baseline[name]))
861
+ if (changed.length === 0) {
862
+ setMessage('没有修改。')
863
+ setError('')
864
+ return true
865
+ }
866
+ savingRef.current = true
867
+ setSaving(true)
868
+ setMessage('正在保存…')
869
+ setError('')
870
+ try {
871
+ const ops = changed.map(name => ({ op: 'set', path: [name], value: target[name] }))
872
+ const accepted = await form.mutate(ops, snapshot.revision)
873
+ if (!accepted) throw new Error('宿主拒绝了这次配置写入。')
874
+ if (!alive.current) return true
875
+ editingRef.current = false
876
+ const patch = {}
877
+ for (const name of changed) patch[name] = target[name]
878
+ setDraft(previous => previous ? { ...previous, ...patch } : target)
879
+ setBaseline(previous => previous ? { ...previous, ...patch } : target)
880
+ setMessage((options && options.successMessage) || '已保存。配置已即时生效。')
881
+ return true
882
+ } catch (cause) {
883
+ if (alive.current) setError(errorMessage(cause))
884
+ return false
885
+ } finally {
886
+ savingRef.current = false
887
+ if (alive.current) setSaving(false)
888
+ }
889
+ }, [form, draft, baseline, alive])
890
+
891
+ return {
892
+ phase,
893
+ message,
894
+ error,
895
+ draft,
896
+ baseline,
897
+ saving,
898
+ jurisdictionText,
899
+ update,
900
+ setJurisdictionText,
901
+ replaceDraft,
902
+ resetAll,
903
+ reload,
904
+ save,
905
+ clearNotices,
906
+ showError,
907
+ showMessage,
908
+ }
909
+ }
910
+
911
+ // 插件 apply:所有页面组件都定义在这里,只把槽位注册出去。
912
+
913
+ function apply(ctx) {
914
+ const uiWorkspace = ctx.uiWorkspace || ctx.get('uiWorkspace')
915
+ const workspaces = ctx.workspaces || ctx.get('workspaces')
916
+ const configForms = ctx.configForms || ctx.get('configForms')
917
+
918
+ // ===== 5. 通用组件 =====
919
+
920
+ function ActionButton({ variant = 'secondary', busy = false, disabled = false, className, children, ...rest }) {
921
+ const blocked = Boolean(disabled || busy)
922
+ const classes = `ta-btn ta-btn--${variant}${className ? ` ${className}` : ''}`
923
+ return h('button', {
924
+ type: 'button',
925
+ ...rest,
926
+ disabled: blocked,
927
+ 'aria-busy': busy || undefined,
928
+ className: classes,
929
+ },
930
+ busy ? h('span', { className: 'ta-spinner', 'aria-hidden': true }) : null,
931
+ children)
932
+ }
933
+
934
+ function Badge({ tone = 'idle', children }) {
935
+ return h('span', { className: `ta-badge ta-badge--${tone}` },
936
+ h('span', { className: 'ta-badge-dot', 'aria-hidden': true }),
937
+ children)
938
+ }
939
+
940
+ function Notice({ tone = 'info', title, action, children }) {
941
+ return h('div', {
942
+ className: `ta-notice ta-notice--${tone}`,
943
+ role: tone === 'error' ? 'alert' : 'status',
944
+ 'aria-live': tone === 'error' ? 'assertive' : 'polite',
945
+ },
946
+ h('div', { className: 'ta-notice-main' },
947
+ title ? h('strong', { className: 'ta-notice-title' }, title) : null,
948
+ h('div', { className: 'ta-notice-text' }, children)),
949
+ action ? h('div', { className: 'ta-notice-action' }, action) : null)
950
+ }
951
+
952
+ function Card({ title, description, badge, children, className }) {
953
+ const hasHead = Boolean(title || description || badge)
954
+ return h('section', { className: `ta-card${className ? ` ${className}` : ''}` },
955
+ hasHead
956
+ ? h('header', { className: 'ta-card-head' },
957
+ h('div', { className: 'ta-card-head-main' },
958
+ title ? h('h3', { className: 'ta-card-title' }, title) : null,
959
+ description ? h('p', { className: 'ta-card-desc' }, description) : null),
960
+ h('div', { className: 'ta-card-head-side' }, badge || null))
961
+ : null,
962
+ h('div', { className: 'ta-card-body' }, children))
963
+ }
964
+
965
+ function Field({ label, hint, children }) {
966
+ return h('label', { className: 'ta-field' },
967
+ h('span', { className: 'ta-label' }, label),
968
+ children,
969
+ hint ? h('span', { className: 'ta-hint' }, hint) : null)
970
+ }
971
+
972
+ function Toggle({ label, hint, checked, disabled, onChange }) {
973
+ return h('div', { className: 'ta-toggle-row' },
974
+ h('div', { className: 'ta-toggle-copy' },
975
+ h('span', { className: 'ta-toggle-label' }, label),
976
+ hint ? h('span', { className: 'ta-hint' }, hint) : null),
977
+ h('button', {
978
+ type: 'button',
979
+ role: 'switch',
980
+ 'aria-checked': Boolean(checked),
981
+ 'aria-label': label,
982
+ disabled,
983
+ className: `ta-toggle${checked ? ' is-on' : ''}`,
984
+ onClick: () => onChange(!checked),
985
+ }, h('span', { className: 'ta-toggle-knob', 'aria-hidden': true })))
986
+ }
987
+
988
+ function Fact({ label, value }) {
989
+ return h('div', { className: 'ta-fact' },
990
+ h('dt', { className: 'ta-fact-label' }, label),
991
+ h('dd', { className: 'ta-fact-value' }, value))
992
+ }
993
+
994
+ function PageHeader({ overline, title, description }) {
995
+ return h('header', { className: 'ta-page-head' },
996
+ overline ? h('span', { className: 'ta-overline' }, overline) : null,
997
+ h('h2', { className: 'ta-h1' }, title),
998
+ description ? h('p', { className: 'ta-desc' }, description) : null)
999
+ }
1000
+
1001
+ function SegmentedTabs({ items, value, onChange, label }) {
1002
+ return h('div', { className: 'ta-tabs', role: 'tablist', 'aria-label': label },
1003
+ items.map(item => h('button', {
1004
+ key: item.value,
1005
+ type: 'button',
1006
+ role: 'tab',
1007
+ id: item.id,
1008
+ 'aria-selected': item.value === value,
1009
+ 'aria-controls': item.panelId,
1010
+ className: `ta-tab${item.value === value ? ' is-active' : ''}`,
1011
+ onClick: () => onChange(item.value),
1012
+ }, item.label)))
1013
+ }
1014
+
1015
+ function Panel({ id, labelledBy, active, children }) {
1016
+ return h('div', {
1017
+ id,
1018
+ role: 'tabpanel',
1019
+ 'aria-labelledby': labelledBy,
1020
+ className: 'ta-panel',
1021
+ hidden: !active,
1022
+ }, children)
1023
+ }
1024
+
1025
+ function LoadPlaceholder({ overline, title, description, state, onRetry }) {
1026
+ const unavailable = state && state.phase === 'unavailable'
1027
+ const loading = !state || state.phase === 'loading'
1028
+ return h('div', { className: 'ta-page' },
1029
+ h(PageHeader, { overline, title, description }),
1030
+ h(Card, null,
1031
+ loading
1032
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取 TA 的状态…')
1033
+ : h(Notice, {
1034
+ tone: unavailable ? 'warn' : 'error',
1035
+ title: unavailable ? '设置接口不可用' : '状态读取失败',
1036
+ action: h(ActionButton, { onClick: onRetry }, '重试'),
1037
+ }, unavailable
1038
+ ? '暂时无法读取设置数据。请确认 dsh-ta 设置服务已挂载,然后重试。'
1039
+ : `${(state && state.error) || '网络异常'}。请检查网络或 Host 服务后重试。`)))
1040
+ }
1041
+
1042
+ function LockIcon({ size = 14 }) {
1043
+ return h('svg', {
1044
+ 'aria-hidden': true,
1045
+ focusable: 'false',
1046
+ viewBox: '0 0 16 16',
1047
+ width: size,
1048
+ height: size,
1049
+ fill: 'none',
1050
+ stroke: 'currentColor',
1051
+ strokeWidth: 1.3,
1052
+ style: { display: 'block', flex: 'none' },
1053
+ },
1054
+ h('path', {
1055
+ d: 'M5.6 7.4V5.65a2.4 2.4 0 0 1 4.8 0V7.4',
1056
+ vectorEffect: 'non-scaling-stroke',
1057
+ }),
1058
+ h('rect', {
1059
+ x: 3.8,
1060
+ y: 7.4,
1061
+ width: 8.4,
1062
+ height: 6.3,
1063
+ rx: 1.6,
1064
+ vectorEffect: 'non-scaling-stroke',
1065
+ }),
1066
+ h('circle', { cx: 8, cy: 10.2, r: 0.85, fill: 'currentColor', stroke: 'none' }))
1067
+ }
1068
+
1069
+ // ===== 6. 配置页 =====
1070
+
1071
+ // --- 配置页 · 服务就绪条 ---
1072
+
1073
+ function ReadyStrip({ status, reme, im }) {
1074
+ const hasHome = Boolean(status && (status.existing || status.initialized))
1075
+ const items = [
1076
+ {
1077
+ key: 'home',
1078
+ label: '本地档案',
1079
+ tone: hasHome ? 'success' : 'idle',
1080
+ value: hasHome ? '已创建' : '未创建',
1081
+ detail: (status && status.home) || DEFAULT_HOME_PATH,
1082
+ },
1083
+ {
1084
+ key: 'reme',
1085
+ label: '长期记忆 ReMe',
1086
+ tone: remeTone(reme),
1087
+ value: describeRemeShort(reme),
1088
+ detail: (reme && reme.endpoint) || '地址未配置',
1089
+ },
1090
+ {
1091
+ key: 'im',
1092
+ label: 'IM',
1093
+ tone: imTone(im),
1094
+ value: describeImShort(im),
1095
+ detail: describeImSummary(im),
1096
+ },
1097
+ ]
1098
+ return h('div', { className: 'ta-ready', role: 'list', 'aria-label': '服务就绪情况' },
1099
+ items.map(item => h('div', {
1100
+ key: item.key,
1101
+ role: 'listitem',
1102
+ className: `ta-ready-item is-${item.tone}`,
1103
+ },
1104
+ h('span', { className: 'ta-dot', 'aria-hidden': true }),
1105
+ h('div', { className: 'ta-ready-text' },
1106
+ h('span', { className: 'ta-ready-label' }, item.label),
1107
+ h('span', { className: 'ta-ready-value' }, item.value),
1108
+ h('span', { className: 'ta-ready-detail', title: item.detail }, item.detail)))))
1109
+ }
1110
+
1111
+ // --- 配置页 · 长期记忆(ReMe) ---
1112
+
1113
+ function RemeCard({ reme, config, refreshConnections, alive }) {
1114
+ const [testing, setTesting] = React.useState(false)
1115
+ const testingRef = React.useRef(false)
1116
+ const draft = config.draft
1117
+ const endpoint = draft ? String(draft.remeEndpoint == null ? '' : draft.remeEndpoint) : ''
1118
+ const baselineEndpoint = config.baseline ? String(config.baseline.remeEndpoint == null ? '' : config.baseline.remeEndpoint) : ''
1119
+ const dirty = Boolean(draft) && endpoint.trim() !== baselineEndpoint
1120
+ const ready = config.phase === 'ready' && Boolean(draft)
1121
+ const disabled = config.saving
1122
+
1123
+ async function testConnection() {
1124
+ if (testingRef.current) return
1125
+ testingRef.current = true
1126
+ setTesting(true)
1127
+ try {
1128
+ await refreshConnections()
1129
+ } finally {
1130
+ testingRef.current = false
1131
+ if (alive.current) setTesting(false)
1132
+ }
1133
+ }
1134
+
1135
+ async function saveEndpoint() {
1136
+ if (config.saving || !ready) return
1137
+ const value = endpoint.trim()
1138
+ if (!isHttpUrl(value)) {
1139
+ config.showError('ReMe 地址必须是 http(s) URL,例如 http://127.0.0.1:2333。')
1140
+ return
1141
+ }
1142
+ const target = { ...(config.draft || {}), remeEndpoint: value }
1143
+ const saved = await config.save({ fields: ['remeEndpoint'], target, successMessage: 'ReMe 地址已保存。' })
1144
+ if (saved) await refreshConnections()
1145
+ }
1146
+
1147
+ return h(Card, {
1148
+ title: '长期记忆 · ReMe',
1149
+ description: 'ReMe 是独立的长期记忆服务;TA 的家只保存本地文件。',
1150
+ badge: h(Badge, { tone: remeTone(reme) }, describeRemeShort(reme)),
1151
+ },
1152
+ h('p', { className: 'ta-text' },
1153
+ reme && reme.state === 'connected'
1154
+ ? 'ReMe 已连接:TA 会从现在开始把对话写入长期记忆。'
1155
+ : '不接 ReMe 也能正常聊天,但 TA 不会长期记住以前的事。接入后从接入时开始捕获,不会自动回填旧对话。'),
1156
+ config.phase === 'loading'
1157
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取 ReMe 地址…')
1158
+ : null,
1159
+ ready
1160
+ ? h(Field, { label: 'ReMe 地址', hint: '默认 http://127.0.0.1:2333;只建议本机回环地址。' },
1161
+ h('input', {
1162
+ className: 'ta-input',
1163
+ type: 'url',
1164
+ value: endpoint,
1165
+ placeholder: 'http://127.0.0.1:2333',
1166
+ disabled,
1167
+ onChange: event => config.update('remeEndpoint', event.target.value),
1168
+ onKeyDown: event => {
1169
+ if (event.key === 'Enter') {
1170
+ event.preventDefault()
1171
+ void saveEndpoint()
1172
+ }
1173
+ },
1174
+ }))
1175
+ : null,
1176
+ ready
1177
+ ? h('div', { className: 'ta-actions' },
1178
+ h(ActionButton, {
1179
+ variant: 'primary',
1180
+ disabled: !dirty || disabled,
1181
+ busy: disabled,
1182
+ onClick: saveEndpoint,
1183
+ }, disabled ? '保存中…' : '保存地址'),
1184
+ h(ActionButton, { disabled: testing || disabled, busy: testing, onClick: testConnection }, testing ? '检测中…' : '测试连接'),
1185
+ dirty ? h('span', { className: 'ta-muted' }, '地址有未保存修改') : null)
1186
+ : null,
1187
+ h('dl', { className: 'ta-facts' },
1188
+ h(Fact, { label: '当前地址', value: (reme && reme.endpoint) || (ready && endpoint) || '未配置' }),
1189
+ h(Fact, { label: '检测结果', value: describeRemeDetail(reme) })),
1190
+ reme && reme.message ? h('p', { className: 'ta-hint' }, reme.message) : null,
1191
+ h('div', { className: 'ta-callout' },
1192
+ h('strong', null, '重置长期记忆'),
1193
+ h('p', { className: 'ta-hint' },
1194
+ '设置页不提供清空按钮,也不会删除 ReMe 数据。要重置记忆,请在你自己的 ReMe 部署里操作:停止 ReMe 服务 → 备份或删除 workspace → 重启 ReMe。远程部署请到对应服务器操作。')))
1195
+ }
1196
+
1197
+ // --- 配置页 · IM 连接 ---
1198
+
1199
+ function ImCard({ status, im, config, integrationsState, refreshConnections, alive }) {
1200
+ const [testing, setTesting] = React.useState(false)
1201
+ const testingRef = React.useRef(false)
1202
+ const accounts = im && Array.isArray(im.accounts) ? im.accounts : []
1203
+ const home = status && status.home
1204
+ const bindings = Number(im && im.dmBindings) || accounts.filter(account => account && account.bound === true).length
1205
+ const mode = im && im.mode === 'reduced' ? 'reduced' : 'owner'
1206
+ const imWarning = im && typeof im.warning === 'string' && im.warning
1207
+ ? im.warning
1208
+ : bindings > 1
1209
+ ? '检测到多个 IM 私聊绑定;已自动降级为 reduced(IM 不注入 self/RECENT/认识)'
1210
+ : ''
1211
+ const ready = Boolean(config) && config.phase === 'ready' && Boolean(config.draft)
1212
+ const [optimisticOwnerOnly, setOptimisticOwnerOnly] = React.useState(null)
1213
+ const savedOwnerOnly = config && config.draft ? config.draft.imOwnerOnly !== false : true
1214
+ const ownerOnly = optimisticOwnerOnly == null ? savedOwnerOnly : optimisticOwnerOnly
1215
+ const saving = Boolean(config && config.saving)
1216
+
1217
+ async function testConnection() {
1218
+ if (testingRef.current) return
1219
+ testingRef.current = true
1220
+ setTesting(true)
1221
+ try {
1222
+ await refreshConnections()
1223
+ } finally {
1224
+ testingRef.current = false
1225
+ if (alive.current) setTesting(false)
1226
+ }
1227
+ }
1228
+
1229
+ async function changeOwnerOnly(next) {
1230
+ if (!ready || !config || saving) return
1231
+ const target = { ...(config.draft || {}), imOwnerOnly: next }
1232
+ setOptimisticOwnerOnly(next)
1233
+ try {
1234
+ await config.save({
1235
+ fields: ['imOwnerOnly'],
1236
+ target,
1237
+ successMessage: next
1238
+ ? '已切换为 owner:IM 会话按本人注入完整人设。'
1239
+ : '已切换为 reduced:IM 不注入 self/RECENT/认识。',
1240
+ })
1241
+ } finally {
1242
+ if (alive.current) setOptimisticOwnerOnly(null)
1243
+ }
1244
+ }
1245
+
1246
+ return h(Card, {
1247
+ title: 'IM 连接',
1248
+ description: '在飞书等 IM 里找到 TA;设置页只做只读检测,不会修改 IM Connect 的配置。',
1249
+ badge: h(Badge, { tone: imTone(im) }, describeImShort(im)),
1250
+ },
1251
+ h('p', { className: 'ta-text' }, imGuidance(im)),
1252
+ h('dl', { className: 'ta-facts' },
1253
+ h(Fact, { label: '私聊绑定', value: `${bindings} 个` }),
1254
+ h(Fact, { label: '注入模式', value: describeImMode(mode) })),
1255
+ imWarning ? h(Notice, { tone: 'warn' }, imWarning) : null,
1256
+ mode === 'reduced'
1257
+ ? h(Notice, { tone: 'warn' },
1258
+ '当前是 reduced 模式:IM 不注入 self/RECENT/认识,只注入 SOUL。')
1259
+ : null,
1260
+ h(Toggle, {
1261
+ label: '把 IM 里的对方视为本人(owner)',
1262
+ hint: ready
1263
+ ? '关闭后进入 reduced:IM 不注入 self、RECENT-MEMORY 和认识,只注入 SOUL;多人共用一个账号时建议关闭。'
1264
+ : '配置读取后可以修改。',
1265
+ checked: ownerOnly,
1266
+ disabled: !ready || saving,
1267
+ onChange: value => { void changeOwnerOnly(value) },
1268
+ }),
1269
+ saving ? h('p', { className: 'ta-muted', role: 'status' }, '正在保存 IM 注入设置…') : null,
1270
+ h('div', { className: 'ta-callout' },
1271
+ h('strong', null, '新建账号时这样填'),
1272
+ h('p', { className: 'ta-hint' },
1273
+ '在 IM Connect 新建一个会话:工作目录(cwd)= 这个 TA 的家,代理预设(agentPreset)= ta,只允许私聊。设置页不会修改 IM Connect 的配置,旧会话也不会被追溯成 TA。'),
1274
+ home ? h('p', { className: 'ta-hint' }, `当前 TA 的家:${home}`) : null),
1275
+ accounts.length > 0
1276
+ ? h('ul', { className: 'ta-accounts' },
1277
+ accounts.map((account, index) => h('li', {
1278
+ key: (account && account.id) || index,
1279
+ className: 'ta-account',
1280
+ },
1281
+ h('div', { className: 'ta-account-head' },
1282
+ h('strong', null, (account && account.name) || '未命名账号'),
1283
+ account && account.platform ? h('span', { className: 'ta-muted' }, account.platform) : null,
1284
+ h('span', { className: account && account.compatible ? 'ta-ok-text' : 'ta-warn-text' },
1285
+ account && account.compatible ? '兼容' : '不兼容')),
1286
+ account && !account.compatible
1287
+ ? h('ul', { className: 'ta-reasons' },
1288
+ imAccountReasons(account, home).map((reason, reasonIndex) => h('li', { key: reasonIndex }, reason)))
1289
+ : null,
1290
+ account && account.cwd ? h('p', { className: 'ta-hint' }, `工作目录:${account.cwd}`) : null)))
1291
+ : h('p', { className: 'ta-hint' },
1292
+ im && im.installed === false ? '没有安装 IM Connect。' : '还没有可用的 IM 会话。'),
1293
+ integrationsState && integrationsState.error
1294
+ ? h('p', { className: 'ta-hint' }, `上次检测失败:${integrationsState.error}`)
1295
+ : null,
1296
+ h('div', { className: 'ta-actions' },
1297
+ h(ActionButton, { disabled: testing, busy: testing, onClick: testConnection }, testing ? '检测中…' : '重新检测')))
1298
+ }
1299
+
1300
+ // --- 配置页 · 每日维护 ---
1301
+
1302
+ function MaintenanceSettingsCard({ status, config }) {
1303
+ const draft = config.draft
1304
+ const ready = config.phase === 'ready' && Boolean(draft)
1305
+ const saving = Boolean(config.saving)
1306
+ const maintenance = status && status.maintenance && typeof status.maintenance === 'object'
1307
+ ? status.maintenance
1308
+ : null
1309
+ const dirty = Boolean(draft && config.baseline) && MAINTENANCE_CONFIG_FIELDS.some(name =>
1310
+ JSON.stringify(draft[name]) !== JSON.stringify(config.baseline[name]))
1311
+
1312
+ async function saveMaintenance() {
1313
+ if (!ready || saving) return
1314
+ const time = String(draft.maintenanceTime == null ? '' : draft.maintenanceTime)
1315
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(time)) {
1316
+ config.showError(`维护时间格式应为 HH:MM,当前是 ${time || '空'}。`)
1317
+ return
1318
+ }
1319
+ if (!MAINTENANCE_EFFORTS.some(item => item.value === draft.maintenanceReasoningEffort)) {
1320
+ config.showError('维护推理强度必须是 off、low、high 或 max。')
1321
+ return
1322
+ }
1323
+ const attempts = Number(draft.maintenanceMaxAttempts)
1324
+ if (!Number.isInteger(attempts) || attempts < 1 || attempts > 5) {
1325
+ config.showError('每天最多尝试次数必须是 1–5 的整数。')
1326
+ return
1327
+ }
1328
+ const retryMinutes = Number(draft.maintenanceRetryMinutes)
1329
+ if (!Number.isInteger(retryMinutes) || retryMinutes < 1 || retryMinutes > 240) {
1330
+ config.showError('失败后重试间隔必须是 1–240 分钟的整数。')
1331
+ return
1332
+ }
1333
+ await config.save({
1334
+ fields: MAINTENANCE_CONFIG_FIELDS,
1335
+ successMessage: '维护设置已保存。',
1336
+ })
1337
+ }
1338
+
1339
+ return h(Card, {
1340
+ title: '每日维护',
1341
+ description: '插件内定时运行:写日记、更新 RECENT-MEMORY,并逐步积累 self / 认识。',
1342
+ badge: h(Badge, {
1343
+ tone: maintenance && maintenance.running ? 'business' : maintenance && maintenance.enabled ? 'success' : 'idle',
1344
+ }, maintenance && maintenance.running
1345
+ ? '运行中'
1346
+ : maintenance
1347
+ ? maintenance.enabled ? '已开启' : '已关闭'
1348
+ : '未知'),
1349
+ },
1350
+ !maintenance
1351
+ ? h(Notice, { tone: 'warn' }, '暂时无法读取维护状态,请稍后刷新。')
1352
+ : h(Notice, { tone: maintenance.enabled ? 'info' : 'warn' },
1353
+ maintenance.enabled
1354
+ ? `每天 ${maintenance.time || '23:00'} 运行。`
1355
+ : '维护已关闭:日记和四件套不会自动更新。'),
1356
+ ready
1357
+ ? h(React.Fragment, null,
1358
+ h(Toggle, {
1359
+ label: '启用每日维护',
1360
+ hint: '关闭后维护不会自动运行,也不会写日记、RECENT 和认识。',
1361
+ checked: Boolean(draft.maintenanceEnabled),
1362
+ disabled: saving,
1363
+ onChange: value => config.update('maintenanceEnabled', value),
1364
+ }),
1365
+ h(Field, { label: '维护时间', hint: '24 小时制 HH:MM;到点由 DSH Schedule 新建一个空会话触发维护,完成后立即删除该会话。' },
1366
+ h('input', {
1367
+ className: 'ta-input ta-input--number',
1368
+ value: draft.maintenanceTime == null ? '' : draft.maintenanceTime,
1369
+ placeholder: '23:00',
1370
+ disabled: saving,
1371
+ onChange: event => config.update('maintenanceTime', event.target.value),
1372
+ })),
1373
+ h(Field, { label: '维护推理强度', hint: 'off 关闭推理;high / max 更慢但更细致。' },
1374
+ h('select', {
1375
+ className: 'ta-input',
1376
+ value: String(draft.maintenanceReasoningEffort == null ? 'low' : draft.maintenanceReasoningEffort),
1377
+ disabled: saving,
1378
+ onChange: event => config.update('maintenanceReasoningEffort', event.target.value),
1379
+ }, MAINTENANCE_EFFORTS.map(item => h('option', {
1380
+ key: item.value,
1381
+ value: item.value,
1382
+ }, item.label)))),
1383
+ h(Field, { label: '每天最多尝试次数', hint: '1–5;失败后按重试间隔继续。' },
1384
+ h('input', {
1385
+ className: 'ta-input ta-input--number',
1386
+ type: 'number',
1387
+ min: 1,
1388
+ max: 5,
1389
+ value: draft.maintenanceMaxAttempts == null ? 2 : draft.maintenanceMaxAttempts,
1390
+ disabled: saving,
1391
+ onChange: event => config.update('maintenanceMaxAttempts', Number(event.target.value)),
1392
+ })),
1393
+ h(Field, { label: '失败后重试间隔(分钟)', hint: '1–240。' },
1394
+ h('input', {
1395
+ className: 'ta-input ta-input--number',
1396
+ type: 'number',
1397
+ min: 1,
1398
+ max: 240,
1399
+ value: draft.maintenanceRetryMinutes == null ? 30 : draft.maintenanceRetryMinutes,
1400
+ disabled: saving,
1401
+ onChange: event => config.update('maintenanceRetryMinutes', Number(event.target.value)),
1402
+ })),
1403
+ h('div', { className: 'ta-actions' },
1404
+ h(ActionButton, {
1405
+ variant: 'primary',
1406
+ disabled: saving || !dirty,
1407
+ busy: saving,
1408
+ onClick: saveMaintenance,
1409
+ }, saving ? '保存中…' : '保存维护设置'),
1410
+ dirty ? h('span', { className: 'ta-muted ta-actions-end' }, '有未保存修改') : null))
1411
+ : h('p', { className: 'ta-muted', role: 'status' },
1412
+ config.phase === 'loading' ? '正在读取维护设置…' : '配置服务不可用,暂时不能修改维护设置。'))
1413
+ }
1414
+
1415
+ // --- 配置页 · TA 的家(折叠:初始化 / 转生) ---
1416
+
1417
+ function HomeInitPanel({ call, alive, blocked, onBusyChange, onDone }) {
1418
+ const [homePath, setHomePath] = React.useState(DEFAULT_HOME_PATH)
1419
+ const [creating, setCreating] = React.useState(false)
1420
+ const [error, setError] = React.useState('')
1421
+ const [adoptPending, setAdoptPending] = React.useState('')
1422
+ const creatingRef = React.useRef(false)
1423
+
1424
+ async function createHome(confirmAdopt) {
1425
+ if (creatingRef.current || blocked) return
1426
+ const path = String(homePath || '').trim()
1427
+ if (!path) {
1428
+ setError('请填写 TA 家的路径')
1429
+ return
1430
+ }
1431
+ creatingRef.current = true
1432
+ setCreating(true)
1433
+ setError('')
1434
+ if (typeof onBusyChange === 'function') onBusyChange(true)
1435
+ try {
1436
+ const body = { path }
1437
+ if (confirmAdopt) body.confirmAdopt = true
1438
+ const result = await call('/home/init', { method: 'POST', body, timeoutMs: 30000 })
1439
+ if (!alive.current) return
1440
+ setAdoptPending('')
1441
+ if (typeof onDone === 'function') onDone(result)
1442
+ } catch (cause) {
1443
+ if (alive.current && !(cause && cause.cancelled)) {
1444
+ if (cause && cause.code === 'ADOPT_CONFIRM_REQUIRED') {
1445
+ setAdoptPending(path)
1446
+ setError('')
1447
+ } else {
1448
+ setError(errorMessage(cause))
1449
+ }
1450
+ }
1451
+ } finally {
1452
+ creatingRef.current = false
1453
+ if (alive.current) setCreating(false)
1454
+ if (typeof onBusyChange === 'function') onBusyChange(false)
1455
+ }
1456
+ }
1457
+
1458
+ return h('div', { className: 'ta-lifecycle' },
1459
+ h('h4', { className: 'ta-subtitle' }, '创建 TA 的家'),
1460
+ h('p', { className: 'ta-text' },
1461
+ '第一次创建会写入初始模板和目录;已有文件不会被覆盖。创建后路径锁定,之后只能通过转生更换。'),
1462
+ h(Field, {
1463
+ label: '家的位置',
1464
+ hint: `默认 ${DEFAULT_HOME_PATH}。可以输入绝对路径或 ~ 开头的路径。`,
1465
+ },
1466
+ h('input', {
1467
+ className: 'ta-input',
1468
+ value: homePath,
1469
+ placeholder: DEFAULT_HOME_PATH,
1470
+ disabled: creating || blocked,
1471
+ onChange: event => {
1472
+ setHomePath(event.target.value)
1473
+ setError('')
1474
+ setAdoptPending('')
1475
+ },
1476
+ })),
1477
+ h('div', { className: 'ta-actions' },
1478
+ h(ActionButton, {
1479
+ variant: 'primary',
1480
+ busy: creating,
1481
+ disabled: blocked,
1482
+ onClick: () => createHome(false),
1483
+ }, creating ? '正在创建…' : '创建 TA 的家')),
1484
+ adoptPending
1485
+ ? h(Notice, {
1486
+ tone: 'warn',
1487
+ action: h(ActionButton, {
1488
+ variant: 'primary',
1489
+ busy: creating,
1490
+ onClick: () => createHome(true),
1491
+ }, creating ? '接管中…' : '确认接管'),
1492
+ }, '这个目录里已经有内容。继续只会补写 .ta-home、缺失的模板和目录,不会覆盖已有文件;确认后才创建。')
1493
+ : null,
1494
+ error ? h(Notice, { tone: 'error' }, error) : null)
1495
+ }
1496
+
1497
+ function ReincarnatePanel({ status, call, alive, blocked, personaDirty, onBusyChange, onDone }) {
1498
+ const [newHome, setNewHome] = React.useState('')
1499
+ const [reincarnateWord, setReincarnateWord] = React.useState('')
1500
+ const [deleteOldHome, setDeleteOldHome] = React.useState(false)
1501
+ const [deleteWord, setDeleteWord] = React.useState('')
1502
+ const [busy, setBusy] = React.useState(false)
1503
+ const [error, setError] = React.useState('')
1504
+ const busyRef = React.useRef(false)
1505
+
1506
+ const lifecycleBusy = Boolean(status && status.lifecycle === 'reincarnating')
1507
+ const disabled = busy || lifecycleBusy || blocked
1508
+ const deleteReady = !deleteOldHome || deleteWord.trim() === '删除旧家'
1509
+ const canSubmit = String(newHome).trim().length > 0
1510
+ && reincarnateWord.trim() === '转生'
1511
+ && deleteReady
1512
+ && !disabled
1513
+ && !personaDirty
1514
+
1515
+ async function run() {
1516
+ if (busyRef.current || disabled) return
1517
+ if (personaDirty) {
1518
+ setError('人设有未保存的修改:请先在「人设」页保存或撤销,再转生。')
1519
+ return
1520
+ }
1521
+ if (!String(newHome).trim()) {
1522
+ setError('请填写新家的路径')
1523
+ return
1524
+ }
1525
+ if (reincarnateWord.trim() !== '转生') {
1526
+ setError('请输入“转生”两个字确认')
1527
+ return
1528
+ }
1529
+ if (deleteOldHome && deleteWord.trim() !== '删除旧家') {
1530
+ setError('要删除旧家,请输入“删除旧家”确认')
1531
+ return
1532
+ }
1533
+ busyRef.current = true
1534
+ setBusy(true)
1535
+ setError('')
1536
+ if (typeof onBusyChange === 'function') onBusyChange(true)
1537
+ try {
1538
+ const body = { newHome: String(newHome).trim(), confirm: '转生', deleteOldHome }
1539
+ if (deleteOldHome) body.deleteConfirm = '删除旧家'
1540
+ const result = await call('/lifecycle/reincarnate', {
1541
+ method: 'POST',
1542
+ body,
1543
+ timeoutMs: 120000,
1544
+ })
1545
+ if (!alive.current) return
1546
+ busyRef.current = false
1547
+ setBusy(false)
1548
+ if (typeof onDone === 'function') onDone(result)
1549
+ } catch (cause) {
1550
+ if (alive.current) {
1551
+ if (!(cause && cause.cancelled)) setError(errorMessage(cause))
1552
+ busyRef.current = false
1553
+ setBusy(false)
1554
+ }
1555
+ } finally {
1556
+ if (typeof onBusyChange === 'function') onBusyChange(false)
1557
+ }
1558
+ }
1559
+
1560
+ return h('div', { className: 'ta-lifecycle' },
1561
+ h('h4', { className: 'ta-subtitle' }, '转生到新家'),
1562
+ h('p', { className: 'ta-text' },
1563
+ '转生会换一个全新的空家;ReMe 长期记忆保留,旧 DSH 会话和旧 IM 聊天记录不受影响。'),
1564
+ h('p', { className: 'ta-hint' },
1565
+ '旧家的人设、日记、笔记、表情包和待发送记忆默认保留;勾选后才会随转生一起删除。'),
1566
+ busy || lifecycleBusy
1567
+ ? h(Notice, { tone: 'info' },
1568
+ deleteOldHome
1569
+ ? '正在创建新家、切换运行期并删除旧家;请保持页面打开。'
1570
+ : '正在创建新家并切换运行期;旧家会保留。')
1571
+ : null,
1572
+ personaDirty
1573
+ ? h(Notice, { tone: 'warn' }, '人设有未保存的修改。请先在「人设」页保存或撤销,再转生。')
1574
+ : null,
1575
+ h(Field, {
1576
+ label: '新家的路径',
1577
+ hint: '必须是空目录或尚不存在的路径;不能是旧家,也不能在旧家内部。',
1578
+ },
1579
+ h('input', {
1580
+ className: 'ta-input',
1581
+ value: newHome,
1582
+ placeholder: '~/TATA/home-2',
1583
+ disabled,
1584
+ onChange: event => {
1585
+ setNewHome(event.target.value)
1586
+ setError('')
1587
+ },
1588
+ })),
1589
+ h('label', { className: 'ta-check' },
1590
+ h('input', {
1591
+ type: 'checkbox',
1592
+ checked: deleteOldHome,
1593
+ disabled,
1594
+ onChange: event => {
1595
+ setDeleteOldHome(event.target.checked)
1596
+ setDeleteWord('')
1597
+ setError('')
1598
+ },
1599
+ }),
1600
+ h('span', { className: 'ta-check-copy' },
1601
+ h('span', { className: 'ta-check-title' }, '同时删除旧家(本地档案)'),
1602
+ h('span', { className: 'ta-check-hint' },
1603
+ '会删除旧家的人设、日记、笔记、认识、出门记录、本地表情包、待发送记忆和插件状态。不可恢复,默认不勾选。'))),
1604
+ deleteOldHome
1605
+ ? h('div', { className: 'ta-danger-box' },
1606
+ h(Notice, { tone: 'warn' },
1607
+ `删除旧家:${(status && status.home) || '(未知路径)'}。ReMe 长期记忆、旧 DSH 会话和旧 IM 聊天记录不会删除。`),
1608
+ h(Field, { label: '输入“删除旧家”确认' },
1609
+ h('input', {
1610
+ className: 'ta-input',
1611
+ value: deleteWord,
1612
+ placeholder: '删除旧家',
1613
+ disabled,
1614
+ onChange: event => {
1615
+ setDeleteWord(event.target.value)
1616
+ setError('')
1617
+ },
1618
+ })))
1619
+ : null,
1620
+ h(Field, { label: '输入“转生”确认' },
1621
+ h('input', {
1622
+ className: 'ta-input',
1623
+ value: reincarnateWord,
1624
+ placeholder: '转生',
1625
+ disabled,
1626
+ onChange: event => {
1627
+ setReincarnateWord(event.target.value)
1628
+ setError('')
1629
+ },
1630
+ })),
1631
+ h('div', { className: 'ta-actions' },
1632
+ h(ActionButton, {
1633
+ variant: 'primary',
1634
+ disabled: !canSubmit,
1635
+ busy,
1636
+ onClick: run,
1637
+ }, busy ? '正在转生…' : '转生到新家')),
1638
+ error ? h(Notice, { tone: 'error' }, error) : null)
1639
+ }
1640
+
1641
+ function HomeCard({ status, call, alive, refreshAll, blocked, personaDirty, onBusyChange }) {
1642
+ const [open, setOpen] = React.useState(false)
1643
+ const [warnings, setWarnings] = React.useState([])
1644
+ const [notice, setNotice] = React.useState('')
1645
+ const initialized = Boolean(status && status.initialized)
1646
+ const hasHome = Boolean(status && (status.existing || status.initialized))
1647
+ const homePath = (status && status.home) || DEFAULT_HOME_PATH
1648
+
1649
+ function handleDone(kind, result) {
1650
+ setOpen(false)
1651
+ const nextWarnings = result && Array.isArray(result.warnings) ? result.warnings.slice() : []
1652
+ if (kind === 'init') {
1653
+ if (result && result.adopted) nextWarnings.push('接管了已有目录;已有文件没有被覆盖')
1654
+ if (result && result.repairedMarker) nextWarnings.push('修复了损坏的 .ta-home 标记,旧文件已改名保留')
1655
+ }
1656
+ setWarnings(nextWarnings)
1657
+ setNotice(kind === 'init'
1658
+ ? 'TA 的家已创建,可以从侧栏「去找Ta」进入;人设可以稍后在「人设」页继续完善。'
1659
+ : result && result.oldHomeDeleted
1660
+ ? '转生完成。新家已就绪,旧家已删除;ReMe 长期记忆保留。'
1661
+ : '转生完成。新家已就绪,旧家保留;ReMe 长期记忆保留。')
1662
+ refreshAll()
1663
+ }
1664
+
1665
+ return h(Card, {
1666
+ title: 'TA 的家 · 本地档案',
1667
+ description: '人格、日记和文件都保存在这里。路径一旦创建就锁定,换家只能走转生;长期记忆在 ReMe,不在这里。',
1668
+ badge: h(Badge, { tone: initialized ? 'success' : 'idle' },
1669
+ initialized ? '已初始化' : hasHome ? '待填写人设' : '未初始化'),
1670
+ },
1671
+ h('button', {
1672
+ type: 'button',
1673
+ className: 'ta-fold-head',
1674
+ 'aria-expanded': open,
1675
+ onClick: () => setOpen(value => !value),
1676
+ },
1677
+ h('span', { className: 'ta-fold-icon', 'aria-hidden': true }, h(LockIcon, { size: 14 })),
1678
+ h('span', { className: 'ta-fold-path' }, homePath),
1679
+ h('span', { className: 'ta-muted' }, hasHome ? '已初始化' : '未初始化'),
1680
+ h('span', { className: 'ta-fold-action' }, open ? '收起' : '展开'),
1681
+ h('span', { className: 'ta-fold-chevron', 'aria-hidden': true }, open ? '▴' : '▾')),
1682
+ open
1683
+ ? h('div', { className: 'ta-fold-body' },
1684
+ !hasHome
1685
+ ? h(HomeInitPanel, {
1686
+ call,
1687
+ alive,
1688
+ blocked,
1689
+ onBusyChange,
1690
+ onDone: result => handleDone('init', result),
1691
+ })
1692
+ : null,
1693
+ hasHome && !initialized
1694
+ ? h(Notice, { tone: 'info' },
1695
+ 'TA 的家已经创建,可以去侧栏「去找Ta」;SOUL 还是空的,可以稍后在「人设」页填写,self、RECENT 和认识会由维护逐步写入。')
1696
+ : null,
1697
+ initialized
1698
+ ? h(ReincarnatePanel, {
1699
+ status,
1700
+ call,
1701
+ alive,
1702
+ blocked,
1703
+ personaDirty,
1704
+ onBusyChange,
1705
+ onDone: result => handleDone('reincarnate', result),
1706
+ })
1707
+ : null)
1708
+ : null,
1709
+ warnings.length > 0
1710
+ ? h(Notice, { tone: 'warn' }, `请留意:${warnings.join(';')}`)
1711
+ : null,
1712
+ notice ? h(Notice, { tone: 'success' }, notice) : null)
1713
+ }
1714
+
1715
+ // --- 配置页 · 页面组装 ---
1716
+
1717
+ function ConfigPage({
1718
+ status, statusState, integrations, integrationsState,
1719
+ call, alive, refreshAll, refreshConnections,
1720
+ config, blocked, personaDirty, onBusyChange, onRetryStatus,
1721
+ }) {
1722
+ if (!status) {
1723
+ return h(LoadPlaceholder, {
1724
+ overline: 'CONFIG',
1725
+ title: '配置',
1726
+ description: 'TA 的本地档案、长期记忆和 IM 连接。',
1727
+ state: statusState,
1728
+ onRetry: onRetryStatus,
1729
+ })
1730
+ }
1731
+ const reme = (integrations && integrations.reme) || status.reme || null
1732
+ const im = (integrations && integrations.im) || status.im || null
1733
+ return h('div', { className: 'ta-page' },
1734
+ h(PageHeader, {
1735
+ overline: 'CONFIG',
1736
+ title: '配置',
1737
+ description: '本地档案保存 TA 的人格和文件,长期记忆保存在 ReMe;维护由 DSH Schedule 每天新建空会话触发,完成后删除会话,不在对话列表留记录。ReMe 和 IM 都可以稍后再接。',
1738
+ }),
1739
+ config.phase === 'unavailable'
1740
+ ? h(Notice, {
1741
+ tone: 'warn',
1742
+ action: h(ActionButton, { onClick: config.reload }, '重新读取'),
1743
+ }, config.message || '配置服务不可用,暂时不能修改配置。')
1744
+ : null,
1745
+ config.error ? h(Notice, { tone: 'error' }, config.error) : null,
1746
+ config.message
1747
+ ? h(Notice, { tone: config.message.indexOf('已保存') !== -1 ? 'success' : 'info' }, config.message)
1748
+ : null,
1749
+ h(HomeCard, {
1750
+ status,
1751
+ call,
1752
+ alive,
1753
+ refreshAll,
1754
+ blocked,
1755
+ personaDirty,
1756
+ onBusyChange,
1757
+ }),
1758
+ h(MaintenanceSettingsCard, { status, config }),
1759
+ h('div', { className: 'ta-grid ta-grid--2' },
1760
+ h(RemeCard, { reme, config, refreshConnections, alive }),
1761
+ h(ImCard, { status, im, config, integrationsState, refreshConnections, alive })),
1762
+ h(ReadyStrip, { status, reme, im }))
1763
+ }
1764
+
1765
+ // ===== 7. 人设页 =====
1766
+
1767
+ function SoulEditor({
1768
+ status, resource, reload, call, alive, blocked, onDirtyChange, onSaved,
1769
+ }) {
1770
+ const data = resource.data
1771
+ const version = resource.version || 0
1772
+ const [draft, setDraft] = React.useState('')
1773
+ const [baseline, setBaseline] = React.useState({ content: '', revision: '' })
1774
+ const [hydrated, setHydrated] = React.useState(false)
1775
+ const [previewOpen, setPreviewOpen] = React.useState(false)
1776
+ const [saving, setSaving] = React.useState(false)
1777
+ const [saveError, setSaveError] = React.useState('')
1778
+ const [conflict, setConflict] = React.useState(false)
1779
+ const [notice, setNotice] = React.useState('')
1780
+ const [warnings, setWarnings] = React.useState([])
1781
+ const savingRef = React.useRef(false)
1782
+ const syncedRef = React.useRef(-1)
1783
+ const forceReloadRef = React.useRef(false)
1784
+ const draftRef = React.useRef('')
1785
+ const baselineRef = React.useRef({ content: '', revision: '' })
1786
+ draftRef.current = draft
1787
+ baselineRef.current = baseline
1788
+
1789
+ const hasHome = Boolean(status && (status.existing || status.initialized))
1790
+ const budget = Number(data && data.budget) || DEFAULT_PERSONA_BUDGETS.soul
1791
+ const maxChars = Number(data && data.maxChars) || PERSONA_MAX_CHARS
1792
+ const dirty = Boolean(data) && hydrated && draft !== baseline.content
1793
+ const loading = !data && resource.phase === 'loading'
1794
+ const failed = !data && (resource.phase === 'error' || resource.phase === 'unavailable')
1795
+ const disabled = !hasHome || !data || saving || !hydrated || blocked
1796
+ const overBudget = draft.length > budget
1797
+ const overMax = draft.length > maxChars
1798
+
1799
+ React.useEffect(() => {
1800
+ if (typeof onDirtyChange === 'function') onDirtyChange('soul', dirty)
1801
+ }, [dirty, onDirtyChange])
1802
+
1803
+ React.useEffect(() => {
1804
+ if (!data) return
1805
+ if (syncedRef.current === version) return
1806
+ const dirtyNow = hydrated && draftRef.current !== baselineRef.current.content
1807
+ if (dirtyNow && !forceReloadRef.current) {
1808
+ // 外部刷新时不要覆盖用户正在编辑的草稿。
1809
+ syncedRef.current = version
1810
+ return
1811
+ }
1812
+ const content = typeof data.soul === 'string' ? data.soul : ''
1813
+ setDraft(content)
1814
+ setBaseline({ content, revision: String(data.revision || '') })
1815
+ setHydrated(true)
1816
+ setPreviewOpen(false)
1817
+ setSaveError('')
1818
+ setConflict(false)
1819
+ setNotice('')
1820
+ setWarnings(Array.isArray(data.warnings) ? data.warnings.slice() : [])
1821
+ syncedRef.current = version
1822
+ forceReloadRef.current = false
1823
+ }, [data, version, hydrated])
1824
+
1825
+ function update(value) {
1826
+ if (savingRef.current) return
1827
+ setDraft(value)
1828
+ setPreviewOpen(false)
1829
+ setSaveError('')
1830
+ setConflict(false)
1831
+ setNotice('')
1832
+ setWarnings([])
1833
+ }
1834
+
1835
+ function reloadSoul() {
1836
+ if (savingRef.current) return
1837
+ forceReloadRef.current = true
1838
+ setSaveError('')
1839
+ setConflict(false)
1840
+ setPreviewOpen(false)
1841
+ setNotice('')
1842
+ setWarnings([])
1843
+ void reload()
1844
+ }
1845
+
1846
+ function resetDraft() {
1847
+ if (savingRef.current) return
1848
+ setDraft(baseline.content)
1849
+ setPreviewOpen(false)
1850
+ setSaveError('')
1851
+ setConflict(false)
1852
+ setNotice('')
1853
+ setWarnings([])
1854
+ }
1855
+
1856
+ async function save() {
1857
+ if (!hasHome || !data || savingRef.current || blocked) return
1858
+ if (overMax) {
1859
+ setSaveError(`SOUL.md 最多 ${maxChars} 字(当前 ${draft.length} 字),保存会被拒绝。`)
1860
+ return
1861
+ }
1862
+ const submittedContent = draft
1863
+ const submittedRevision = baseline.revision
1864
+ savingRef.current = true
1865
+ setSaving(true)
1866
+ setSaveError('')
1867
+ setConflict(false)
1868
+ setNotice('')
1869
+ setWarnings([])
1870
+ try {
1871
+ const saved = await call('/persona', {
1872
+ method: 'PUT',
1873
+ body: { field: 'soul', content: submittedContent, revision: submittedRevision },
1874
+ })
1875
+ if (!alive.current) return
1876
+ const nextRevision = saved && typeof saved.revision === 'string' && saved.revision
1877
+ ? saved.revision
1878
+ : submittedRevision
1879
+ setBaseline({ content: submittedContent, revision: nextRevision })
1880
+ const savedWarnings = saved && Array.isArray(saved.warnings) ? saved.warnings : []
1881
+ setWarnings(savedWarnings)
1882
+ setPreviewOpen(false)
1883
+ setNotice(savedWarnings.length > 0
1884
+ ? '已保存;请留意预算提示。'
1885
+ : '已保存。之后开始的会话会使用更新后的内容。')
1886
+ if (typeof onSaved === 'function') onSaved('soul')
1887
+ } catch (cause) {
1888
+ if (!alive.current || (cause && cause.cancelled)) return
1889
+ if ((cause && cause.status === 409) || (cause && cause.code === 'PERSONA_CONFLICT')) {
1890
+ setConflict(true)
1891
+ } else {
1892
+ setSaveError(errorMessage(cause))
1893
+ }
1894
+ } finally {
1895
+ savingRef.current = false
1896
+ if (alive.current) setSaving(false)
1897
+ }
1898
+ }
1899
+
1900
+ const placeholder = !hasHome
1901
+ ? '先创建 TA 的家'
1902
+ : loading
1903
+ ? '正在读取 SOUL…'
1904
+ : !hydrated
1905
+ ? '正在载入 SOUL…'
1906
+ : failed
1907
+ ? 'SOUL 读取失败,重新加载后编辑'
1908
+ : ''
1909
+
1910
+ return h(Card, {
1911
+ title: 'SOUL.md · TA 是谁',
1912
+ description: 'SOUL.md:TA 的人格底色、在意的事和说话方式。设置页只编辑 SOUL;认识/USER.md 由维护逐步写入。',
1913
+ badge: h('span', { className: 'ta-file-badge' }, 'SOUL.md'),
1914
+ },
1915
+ !hasHome ? h(Notice, { tone: 'info' }, '先创建 TA 的家,之后才能编辑 SOUL。') : null,
1916
+ data && resource.error
1917
+ ? h(Notice, {
1918
+ tone: 'warn',
1919
+ action: h(ActionButton, { onClick: reloadSoul }, '重新加载'),
1920
+ }, `SOUL 刷新失败:${resource.error}(显示的是上次读取的内容)`)
1921
+ : null,
1922
+ failed
1923
+ ? h(Notice, {
1924
+ tone: resource.phase === 'unavailable' ? 'warn' : 'error',
1925
+ action: h(ActionButton, { onClick: reloadSoul }, '重新加载'),
1926
+ }, `${resource.phase === 'unavailable' ? '人设接口不可用' : 'SOUL 读取失败'}:${resource.error || '请重试。'}`)
1927
+ : null,
1928
+ loading
1929
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取…')
1930
+ : null,
1931
+ h('textarea', {
1932
+ className: 'ta-textarea ta-textarea--tall',
1933
+ rows: 12,
1934
+ value: draft,
1935
+ placeholder,
1936
+ disabled,
1937
+ 'aria-label': 'SOUL.md(TA 是谁)',
1938
+ onChange: event => update(event.target.value),
1939
+ }),
1940
+ h('div', { className: 'ta-counter' },
1941
+ h('span', { className: overBudget ? 'ta-counter-warn' : 'ta-muted' }, `${draft.length} / ${budget} 字`),
1942
+ overBudget
1943
+ ? h('span', { className: 'ta-counter-warn' },
1944
+ `超出预算 ${draft.length - budget} 字,实际注入时只使用前 ${budget} 字;仍可保存`)
1945
+ : null,
1946
+ !draft.length && data && hasHome
1947
+ ? h('span', { className: 'ta-muted' }, '尚未填写(可选)')
1948
+ : null,
1949
+ overMax
1950
+ ? h('span', { className: 'ta-counter-error' }, `超过 ${maxChars} 字硬上限,无法保存`)
1951
+ : null,
1952
+ dirty ? h('span', { className: 'ta-counter-warn' }, '有未保存修改') : null),
1953
+ h('div', { className: 'ta-actions' },
1954
+ h(ActionButton, {
1955
+ variant: 'primary',
1956
+ disabled: !dirty || disabled,
1957
+ busy: saving,
1958
+ onClick: save,
1959
+ }, saving ? '保存中…' : '保存 SOUL.md'),
1960
+ h(ActionButton, {
1961
+ disabled: !data || saving,
1962
+ onClick: () => setPreviewOpen(value => !value),
1963
+ }, previewOpen ? '收起预览' : '预览'),
1964
+ h(ActionButton, {
1965
+ variant: 'ghost',
1966
+ disabled: !dirty || saving,
1967
+ onClick: resetDraft,
1968
+ }, '撤销修改'),
1969
+ h('span', { className: 'ta-muted ta-actions-end' },
1970
+ saving ? '保存中…' : dirty ? '有未保存修改' : hydrated ? '已保存' : '')),
1971
+ blocked
1972
+ ? h(Notice, { tone: 'info' }, 'TA 正在转生中,SOUL 暂时不能保存;操作完成后会自动恢复。')
1973
+ : null,
1974
+ previewOpen
1975
+ ? h('div', { className: 'ta-preview-box' },
1976
+ h('h4', { className: 'ta-subtitle' }, '保存后实际注入内容'),
1977
+ h('p', { className: 'ta-hint' }, `预算 ${budget} 字,硬上限 ${maxChars} 字;超出预算的部分不会注入。`),
1978
+ h('pre', { className: 'ta-preview' }, buildSoulPreview(draft, budget)),
1979
+ h('div', { className: 'ta-actions' },
1980
+ h(ActionButton, {
1981
+ variant: 'primary',
1982
+ busy: saving,
1983
+ disabled,
1984
+ onClick: save,
1985
+ }, saving ? '保存中…' : '保存 SOUL.md'),
1986
+ h(ActionButton, { disabled: saving, onClick: () => setPreviewOpen(false) }, '返回修改')))
1987
+ : null,
1988
+ conflict
1989
+ ? h(Notice, {
1990
+ tone: 'error',
1991
+ action: h(ActionButton, { onClick: reloadSoul }, '重新加载'),
1992
+ }, '这个文件已被其他会话修改。请先重新加载,再保存;当前草稿已保留。')
1993
+ : null,
1994
+ saveError ? h(Notice, { tone: 'error' }, saveError) : null,
1995
+ warnings.length > 0
1996
+ ? h(Notice, { tone: 'warn' }, `预算提示:${warnings.join(';')}`)
1997
+ : null,
1998
+ notice ? h(Notice, { tone: 'success' }, notice) : null)
1999
+ }
2000
+
2001
+ function AddressCard({
2002
+ resource, draft, baseline, saving, error, notice, blocked, onChange, onSave,
2003
+ }) {
2004
+ const dirty = String(draft || '') !== String(baseline || '')
2005
+ const disabled = saving || blocked
2006
+ return h(Card, {
2007
+ title: '称呼',
2008
+ description: 'TA 可以怎么称呼你;留空表示不在人设里注入称呼。',
2009
+ badge: h(Badge, { tone: resource.data ? 'success' : 'idle' }, resource.data ? '已读取' : '未读取'),
2010
+ },
2011
+ resource.error
2012
+ ? h(Notice, {
2013
+ tone: resource.phase === 'unavailable' ? 'warn' : 'error',
2014
+ }, resource.phase === 'unavailable'
2015
+ ? '称呼接口暂时不可用,请稍后重试。'
2016
+ : `读取称呼失败:${resource.error}`)
2017
+ : null,
2018
+ h(Field, { label: '称呼', hint: '单行,最多 40 字;留空表示不注入。' },
2019
+ h('input', {
2020
+ className: 'ta-input',
2021
+ value: draft,
2022
+ maxLength: ADDRESS_MAX_CHARS,
2023
+ placeholder: '例如:小林',
2024
+ disabled,
2025
+ onChange: event => onChange(event.target.value.replace(/[\r\n]+/g, '')),
2026
+ })),
2027
+ h('div', { className: 'ta-counter' },
2028
+ h('span', { className: 'ta-muted' }, `${String(draft || '').length} / ${ADDRESS_MAX_CHARS} 字`),
2029
+ String(draft || '').length === 0 ? h('span', { className: 'ta-muted' }, '空字符串表示不注入') : null,
2030
+ dirty ? h('span', { className: 'ta-counter-warn' }, '有未保存修改') : null),
2031
+ h('div', { className: 'ta-actions' },
2032
+ h(ActionButton, {
2033
+ variant: 'primary',
2034
+ disabled: disabled || !dirty,
2035
+ busy: saving,
2036
+ onClick: onSave,
2037
+ }, saving ? '保存中…' : '保存称呼'),
2038
+ h('span', { className: 'ta-muted ta-actions-end' }, dirty ? '有未保存修改' : '已保存')),
2039
+ error ? h(Notice, { tone: 'error' }, error) : null,
2040
+ notice ? h(Notice, { tone: 'success' }, notice) : null)
2041
+ }
2042
+
2043
+ function SoulProposalsCard({
2044
+ resource, pending, revision, call, alive, blocked, onAccepted, onRejected,
2045
+ }) {
2046
+ const [busy, setBusy] = React.useState('')
2047
+ const [error, setError] = React.useState('')
2048
+ const [notice, setNotice] = React.useState('')
2049
+ const busyRef = React.useRef(false)
2050
+ const data = resource.data
2051
+ const reported = Number(data && data.pending)
2052
+ const pendingCount = Number.isFinite(reported) && reported >= 0 ? reported : pending.length
2053
+
2054
+ async function handle(action, proposal) {
2055
+ if (busyRef.current || blocked) return
2056
+ if (action === 'accept' && !revision) {
2057
+ setError('还没有读到当前 SOUL 版本,请先重新加载人设。')
2058
+ return
2059
+ }
2060
+ busyRef.current = true
2061
+ setBusy(`${action}:${proposal.id}`)
2062
+ setError('')
2063
+ setNotice('')
2064
+ try {
2065
+ const body = action === 'accept' ? { revision } : {}
2066
+ await call(`/soul-proposals/${encodeURIComponent(proposal.id)}/${action}`, {
2067
+ method: 'POST',
2068
+ body,
2069
+ })
2070
+ if (!alive.current) return
2071
+ setNotice(action === 'accept' ? '已接受建议,SOUL 已更新。' : '已拒绝这条建议。')
2072
+ if (action === 'accept') {
2073
+ if (typeof onAccepted === 'function') await onAccepted()
2074
+ } else if (typeof onRejected === 'function') {
2075
+ await onRejected()
2076
+ }
2077
+ } catch (cause) {
2078
+ if (!alive.current || (cause && cause.cancelled)) return
2079
+ if (action === 'accept' && cause && cause.code === 'PROPOSAL_STALE') {
2080
+ setError('SOUL 已变化,请刷新后重新生成')
2081
+ } else if (cause && cause.code === 'PROPOSAL_CLOSED') {
2082
+ setError('这条建议已经处理过了,刷新后查看。')
2083
+ } else {
2084
+ setError(errorMessage(cause))
2085
+ }
2086
+ } finally {
2087
+ busyRef.current = false
2088
+ if (alive.current) setBusy('')
2089
+ }
2090
+ }
2091
+
2092
+ return h(Card, {
2093
+ title: 'SOUL 建议',
2094
+ description: '维护只会把建议写进队列;只有你在这里接受后,才会写进 SOUL.md。',
2095
+ badge: h(Badge, { tone: pendingCount > 0 ? 'warn' : 'idle' }, `${pendingCount} 条待确认`),
2096
+ },
2097
+ resource.error
2098
+ ? h(Notice, { tone: resource.phase === 'unavailable' ? 'warn' : 'error' },
2099
+ resource.phase === 'unavailable'
2100
+ ? 'SOUL 建议接口暂时不可用,请稍后重试。'
2101
+ : `读取 SOUL 建议失败:${resource.error}`)
2102
+ : null,
2103
+ resource.phase === 'loading' && !data
2104
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取 SOUL 建议…')
2105
+ : null,
2106
+ pending.length === 0
2107
+ ? h('p', { className: 'ta-muted' }, '暂时没有待确认的 SOUL 建议。')
2108
+ : h('ul', { className: 'ta-accounts' },
2109
+ pending.map(proposal => h('li', {
2110
+ key: proposal.id,
2111
+ className: 'ta-account',
2112
+ },
2113
+ h('div', { className: 'ta-account-head' },
2114
+ h('strong', null, 'SOUL 建议'),
2115
+ proposal.createdAt ? h('span', { className: 'ta-muted' }, formatDateTime(proposal.createdAt)) : null),
2116
+ h('p', { className: 'ta-text' }, proposal.text || '(空建议)'),
2117
+ proposal.reason ? h('p', { className: 'ta-hint' }, `理由:${proposal.reason}`) : null,
2118
+ h('div', { className: 'ta-actions' },
2119
+ h(ActionButton, {
2120
+ variant: 'primary',
2121
+ busy: busy === `accept:${proposal.id}`,
2122
+ disabled: Boolean(busy) || blocked,
2123
+ onClick: () => { void handle('accept', proposal) },
2124
+ }, '接受'),
2125
+ h(ActionButton, {
2126
+ busy: busy === `reject:${proposal.id}`,
2127
+ disabled: Boolean(busy) || blocked,
2128
+ onClick: () => { void handle('reject', proposal) },
2129
+ }, '拒绝'))))),
2130
+ error ? h(Notice, { tone: 'error' }, error) : null,
2131
+ notice ? h(Notice, { tone: 'success' }, notice) : null)
2132
+ }
2133
+
2134
+ function PersonaPage({
2135
+ status, statusState, resource, reload, call, alive, blocked, onDirtyChange, onSaved, onRetryStatus,
2136
+ }) {
2137
+ const [addressResource] = useResource('/settings/address', call, alive)
2138
+ const [proposalResource, reloadProposals] = useResource('/soul-proposals', call, alive)
2139
+ const [addressDraft, setAddressDraft] = React.useState('')
2140
+ const [addressBaseline, setAddressBaseline] = React.useState('')
2141
+ const [addressSaving, setAddressSaving] = React.useState(false)
2142
+ const [addressError, setAddressError] = React.useState('')
2143
+ const [addressNotice, setAddressNotice] = React.useState('')
2144
+ const addressSyncedRef = React.useRef(-1)
2145
+ const addressSavingRef = React.useRef(false)
2146
+
2147
+ React.useEffect(() => {
2148
+ const data = addressResource.data
2149
+ if (!data || addressSyncedRef.current === addressResource.version) return
2150
+ const value = typeof data.addressAs === 'string' ? data.addressAs : ''
2151
+ setAddressDraft(value)
2152
+ setAddressBaseline(value)
2153
+ addressSyncedRef.current = addressResource.version
2154
+ }, [addressResource.data, addressResource.version])
2155
+
2156
+ async function saveAddress() {
2157
+ if (addressSavingRef.current || blocked) return
2158
+ const value = trimAddress(addressDraft)
2159
+ addressSavingRef.current = true
2160
+ setAddressSaving(true)
2161
+ setAddressError('')
2162
+ setAddressNotice('')
2163
+ try {
2164
+ const saved = await call('/settings/address', {
2165
+ method: 'PUT',
2166
+ body: { addressAs: value },
2167
+ })
2168
+ if (!alive.current) return
2169
+ const next = saved && typeof saved.addressAs === 'string' ? saved.addressAs : value
2170
+ setAddressDraft(next)
2171
+ setAddressBaseline(next)
2172
+ setAddressNotice('称呼已保存。')
2173
+ } catch (cause) {
2174
+ if (alive.current && !(cause && cause.cancelled)) setAddressError(errorMessage(cause))
2175
+ } finally {
2176
+ addressSavingRef.current = false
2177
+ if (alive.current) setAddressSaving(false)
2178
+ }
2179
+ }
2180
+
2181
+ async function handleProposalAccepted() {
2182
+ await Promise.allSettled([reloadProposals(), reload()])
2183
+ if (typeof onSaved === 'function') onSaved('soul')
2184
+ }
2185
+
2186
+ async function handleProposalRejected() {
2187
+ await reloadProposals()
2188
+ }
2189
+
2190
+ if (!status) {
2191
+ return h(LoadPlaceholder, {
2192
+ overline: 'PERSONA',
2193
+ title: '人设',
2194
+ description: 'SOUL、称呼与 SOUL 建议。',
2195
+ state: statusState,
2196
+ onRetry: onRetryStatus,
2197
+ })
2198
+ }
2199
+ const proposalData = proposalResource.data
2200
+ const pendingProposals = proposalData && Array.isArray(proposalData.proposals)
2201
+ ? proposalData.proposals.filter(item => item && item.status === 'pending')
2202
+ : []
2203
+ const soulRevision = resource.data && typeof resource.data.revision === 'string'
2204
+ ? resource.data.revision
2205
+ : ''
2206
+
2207
+ return h('div', { className: 'ta-page' },
2208
+ h(PageHeader, {
2209
+ overline: 'PERSONA',
2210
+ title: '人设',
2211
+ description: 'SOUL 由你编辑;称呼单独保存;self、RECENT-MEMORY 和认识由维护逐步写入。',
2212
+ }),
2213
+ h(SoulEditor, {
2214
+ status,
2215
+ resource,
2216
+ reload,
2217
+ call,
2218
+ alive,
2219
+ blocked,
2220
+ onDirtyChange,
2221
+ onSaved,
2222
+ }),
2223
+ h('div', { className: 'ta-grid ta-grid--2' },
2224
+ h(AddressCard, {
2225
+ resource: addressResource,
2226
+ draft: addressDraft,
2227
+ baseline: addressBaseline,
2228
+ saving: addressSaving,
2229
+ error: addressError,
2230
+ notice: addressNotice,
2231
+ blocked,
2232
+ onChange: value => {
2233
+ setAddressDraft(value)
2234
+ setAddressNotice('')
2235
+ setAddressError('')
2236
+ },
2237
+ onSave: saveAddress,
2238
+ }),
2239
+ h(SoulProposalsCard, {
2240
+ resource: proposalResource,
2241
+ pending: pendingProposals,
2242
+ revision: soulRevision,
2243
+ call,
2244
+ alive,
2245
+ blocked,
2246
+ onAccepted: handleProposalAccepted,
2247
+ onRejected: handleProposalRejected,
2248
+ })))
2249
+ }
2250
+
2251
+ // ===== 8. 状态页 =====
2252
+
2253
+ function UsageBar({ label, value, budget }) {
2254
+ const percent = budget > 0 ? Math.min(100, Math.round((value / budget) * 100)) : 0
2255
+ const over = value > budget
2256
+ return h('div', { className: 'ta-usage-bar' },
2257
+ h('div', { className: 'ta-usage-bar-head' },
2258
+ h('span', { className: 'ta-label' }, label),
2259
+ h('span', { className: over ? 'ta-counter-warn' : 'ta-muted' }, `${value} / ${budget} 字`)),
2260
+ h('div', {
2261
+ className: 'ta-bar',
2262
+ role: 'progressbar',
2263
+ 'aria-label': `${label} 字数`,
2264
+ 'aria-valuenow': value,
2265
+ 'aria-valuemin': 0,
2266
+ 'aria-valuemax': budget,
2267
+ }, h('div', {
2268
+ className: `ta-bar-fill${over ? ' is-over' : ''}`,
2269
+ style: { width: `${percent}%` },
2270
+ })),
2271
+ over ? h('span', { className: 'ta-counter-warn' }, '超出预算的部分不会注入') : null)
2272
+ }
2273
+
2274
+ function CoreFileCard({ title, description, info, fallback }) {
2275
+ const record = info && typeof info === 'object' ? info : null
2276
+ const chars = Number(record && record.chars)
2277
+ const cap = Number(record && record.cap)
2278
+ const hasCounts = Number.isFinite(chars) && Number.isFinite(cap) && cap > 0
2279
+ const exists = Boolean(record && record.exists)
2280
+ return h(Card, {
2281
+ title,
2282
+ description,
2283
+ badge: h(Badge, { tone: exists ? 'success' : 'idle' }, exists ? '已有内容' : '空'),
2284
+ },
2285
+ record
2286
+ ? h(React.Fragment, null,
2287
+ hasCounts
2288
+ ? h(UsageBar, { label: '字数', value: chars, budget: cap })
2289
+ : h('p', { className: 'ta-muted' }, '字数未知'),
2290
+ h('dl', { className: 'ta-facts' },
2291
+ h(Fact, {
2292
+ label: '状态',
2293
+ value: record.truncated
2294
+ ? '超过 cap,注入时会截断'
2295
+ : exists
2296
+ ? '正常注入'
2297
+ : '空文件不注入',
2298
+ }),
2299
+ h(Fact, { label: '路径', value: record.path || title })))
2300
+ : h('p', { className: 'ta-muted' }, fallback || '暂时无法读取。'))
2301
+ }
2302
+
2303
+ function MaintenanceStatusCard({ maintenance, active, call, onRefresh }) {
2304
+ const alive = useAlive()
2305
+ const [starting, setStarting] = React.useState(false)
2306
+ const [tracking, setTracking] = React.useState(false)
2307
+ const [notice, setNotice] = React.useState('')
2308
+ const [error, setError] = React.useState('')
2309
+ const startingRef = React.useRef(false)
2310
+ const watching = Boolean(maintenance && maintenance.running) || tracking
2311
+ const enabled = Boolean(maintenance && maintenance.enabled)
2312
+
2313
+ async function runNow(forceProfile = false) {
2314
+ if (startingRef.current || watching) return
2315
+ startingRef.current = true
2316
+ setStarting(true)
2317
+ setError('')
2318
+ setNotice('')
2319
+ try {
2320
+ const result = await call('/maintenance/run', {
2321
+ method: 'POST',
2322
+ body: forceProfile ? { forceProfile: true } : {},
2323
+ })
2324
+ if (!alive.current) return
2325
+ setNotice(`维护已开始${result && result.runId ? `(${result.runId})` : ''},正在每 2 秒检查进度…`)
2326
+ setTracking(true)
2327
+ } catch (cause) {
2328
+ if (alive.current && !(cause && cause.cancelled)) setError(errorMessage(cause))
2329
+ } finally {
2330
+ startingRef.current = false
2331
+ if (alive.current) setStarting(false)
2332
+ }
2333
+ }
2334
+
2335
+ // Host 对 POST /maintenance/run 立即返回 202;这里每 2s 轮询,最多 90s。
2336
+ // 切换页签或卸载时由 effect cleanup 停止轮询。
2337
+ React.useEffect(() => {
2338
+ if (!tracking || !active) return undefined
2339
+ let cancelled = false
2340
+ const startedAt = Date.now()
2341
+ let timer = null
2342
+ const tick = async () => {
2343
+ if (cancelled) return
2344
+ try {
2345
+ const latest = await call('/runs/latest')
2346
+ if (cancelled) return
2347
+ const state = latest && latest.state && typeof latest.state === 'object' ? latest.state : null
2348
+ const isRunning = state && typeof state.running === 'boolean'
2349
+ ? state.running
2350
+ : Boolean(latest && latest.run && !latest.run.finishedAt)
2351
+ if (!isRunning) {
2352
+ setTracking(false)
2353
+ setNotice('维护已结束,正在刷新状态…')
2354
+ await onRefresh()
2355
+ if (!cancelled) setNotice('维护已结束。')
2356
+ return
2357
+ }
2358
+ } catch (cause) {
2359
+ if (cancelled || (cause && cause.cancelled)) return
2360
+ setTracking(false)
2361
+ setError(`读取维护进度失败:${errorMessage(cause)}。可稍后刷新状态查看结果。`)
2362
+ return
2363
+ }
2364
+ if (Date.now() - startedAt >= MAINTENANCE_POLL_LIMIT_MS) {
2365
+ setTracking(false)
2366
+ setNotice('维护仍在运行,请稍后刷新状态查看结果。')
2367
+ return
2368
+ }
2369
+ timer = setTimeout(tick, MAINTENANCE_POLL_INTERVAL_MS)
2370
+ }
2371
+ timer = setTimeout(tick, MAINTENANCE_POLL_INTERVAL_MS)
2372
+ return () => {
2373
+ cancelled = true
2374
+ if (timer) clearTimeout(timer)
2375
+ }
2376
+ }, [tracking, active, call, onRefresh])
2377
+
2378
+ const lastRun = maintenance && maintenance.lastRun && typeof maintenance.lastRun === 'object'
2379
+ ? maintenance.lastRun
2380
+ : null
2381
+ const lastRunCost = lastRun && lastRun.usage && lastRun.usage.costCny != null
2382
+ ? lastRun.usage.costCny
2383
+ : null
2384
+ const lastRunText = lastRun
2385
+ ? [
2386
+ lastRun.runDate || '未知日期',
2387
+ maintenanceRunLabel(lastRun.status),
2388
+ lastRunCost != null ? formatMoney(lastRunCost) : '',
2389
+ lastRun.model ? String(lastRun.model) : '',
2390
+ ].filter(Boolean).join(' · ')
2391
+ : '还没有运行记录'
2392
+
2393
+ return h(Card, {
2394
+ title: '维护',
2395
+ description: 'DSH Schedule 每天新建空会话触发:日记、RECENT、每周日 self/认识;成功结束后自动删除该会话。schedule 不可用时回退插件内定时器。',
2396
+ badge: h(Badge, { tone: watching ? 'business' : enabled ? 'success' : 'idle' },
2397
+ watching ? '运行中' : enabled ? '已开启' : '已关闭'),
2398
+ },
2399
+ !maintenance
2400
+ ? h(Notice, { tone: 'warn' }, '暂时无法读取维护状态,请稍后刷新。')
2401
+ : null,
2402
+ maintenance
2403
+ ? h('dl', { className: 'ta-facts' },
2404
+ h(Fact, { label: '每日维护', value: enabled ? `开启 · 每天 ${maintenance.time || '23:00'}` : '已关闭' }),
2405
+ h(Fact, {
2406
+ label: '调度方式',
2407
+ value: maintenance.scheduleMode === 'official' ? 'DSH Schedule(空会话)' : '插件内定时器(兜底)',
2408
+ }),
2409
+ h(Fact, { label: '当前', value: watching ? '运行中' : '空闲' }),
2410
+ h(Fact, { label: '上次成功', value: maintenance.lastSuccessDate || '还没有成功记录' }),
2411
+ h(Fact, {
2412
+ label: '每周整理',
2413
+ value: maintenance.weekly && maintenance.weekly.lastSuccessAnchor
2414
+ ? `最近 ${maintenance.weekly.lastSuccessAnchor} 已完成`
2415
+ : '还没整理过',
2416
+ }),
2417
+ h(Fact, { label: '上次运行', value: lastRunText }),
2418
+ h(Fact, {
2419
+ label: '上次尝试',
2420
+ value: maintenance.lastAttemptAt ? formatDateTime(maintenance.lastAttemptAt) : '无',
2421
+ }),
2422
+ h(Fact, {
2423
+ label: '下次重试',
2424
+ value: maintenance.nextRetryAt ? formatDateTime(maintenance.nextRetryAt) : '无',
2425
+ }),
2426
+ h(Fact, { label: '连续失败', value: `${Number(maintenance.consecutiveFailures) || 0} 次` }))
2427
+ : null,
2428
+ tracking
2429
+ ? h(Notice, { tone: 'info' }, '维护正在运行,正在每 2 秒检查进度…')
2430
+ : null,
2431
+ notice ? h(Notice, { tone: 'success' }, notice) : null,
2432
+ error ? h(Notice, { tone: 'error' }, error) : null,
2433
+ h('div', { className: 'ta-actions' },
2434
+ h(ActionButton, {
2435
+ variant: 'primary',
2436
+ busy: starting || watching,
2437
+ disabled: starting || watching || !maintenance,
2438
+ onClick: () => runNow(false),
2439
+ }, watching ? '运行中…' : starting ? '正在启动…' : '立即运行维护'),
2440
+ h(ActionButton, {
2441
+ busy: starting || watching,
2442
+ disabled: starting || watching || !maintenance,
2443
+ onClick: () => runNow(true),
2444
+ }, '立即整理人物与自我'),
2445
+ h('span', { className: 'ta-muted ta-actions-end' },
2446
+ watching ? '运行中' : '手动运行不需要等 8 秒;强制整理会立即跑 self/认识 阶段')))
2447
+ }
2448
+
2449
+ // --- 状态页 · 花销卡 ---
2450
+
2451
+ function UsageCard() {
2452
+ const [report, setReport] = React.useState(null)
2453
+ const [error, setError] = React.useState('')
2454
+ const [reloadKey, setReloadKey] = React.useState(0)
2455
+ const [resetOpen, setResetOpen] = React.useState(false)
2456
+ const [resetting, setResetting] = React.useState(false)
2457
+ const [resetError, setResetError] = React.useState('')
2458
+ const [resetNotice, setResetNotice] = React.useState('')
2459
+ React.useEffect(() => {
2460
+ let alive = true
2461
+ const controller = new AbortController()
2462
+ const timeout = setTimeout(() => controller.abort(), 8000)
2463
+ setError('')
2464
+ fetch('/api/dsh-ta/usage', { cache: 'no-store', signal: controller.signal })
2465
+ .then(response => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`)))
2466
+ .then(value => { if (alive) setReport(value) })
2467
+ .catch(cause => { if (alive) setError(cause instanceof Error ? cause.message : String(cause)) })
2468
+ .finally(() => clearTimeout(timeout))
2469
+ return () => {
2470
+ alive = false
2471
+ clearTimeout(timeout)
2472
+ controller.abort()
2473
+ }
2474
+ }, [reloadKey])
2475
+
2476
+ async function clearUsage() {
2477
+ if (resetting) return
2478
+ setResetting(true)
2479
+ setResetError('')
2480
+ try {
2481
+ const response = await fetch('/api/dsh-ta/usage/reset', {
2482
+ method: 'POST',
2483
+ headers: { 'content-type': 'application/json' },
2484
+ body: JSON.stringify({ confirm: '清零' }),
2485
+ })
2486
+ let payload = null
2487
+ try { payload = await response.json() } catch { /* 非 JSON 错误按 HTTP 状态处理 */ }
2488
+ if (!response.ok || !payload || payload.ok !== true) {
2489
+ throw new Error(payload?.error?.message || `清零失败(HTTP ${response.status})`)
2490
+ }
2491
+ const count = Number(payload.data && payload.data.records) || 0
2492
+ setResetOpen(false)
2493
+ setResetNotice(count > 0
2494
+ ? `已清零 ${count} 条记录。之后的对话会重新累计。`
2495
+ : '花销已经清零。之后的对话会重新累计。')
2496
+ setReport(null)
2497
+ setReloadKey(value => value + 1)
2498
+ } catch (cause) {
2499
+ setResetError(cause instanceof Error ? cause.message : String(cause))
2500
+ } finally {
2501
+ setResetting(false)
2502
+ }
2503
+ }
2504
+
2505
+ if (error) {
2506
+ return h(Card, { title: '花销', description: 'DSH agent 估算;ReMe 自己的调用不在范围内。' },
2507
+ h(Notice, { tone: 'warn' }, `花销接口暂不可用:${error}`))
2508
+ }
2509
+ if (!report) {
2510
+ return h(Card, { title: '花销', description: 'DSH agent 估算;ReMe 自己的调用不在范围内。' },
2511
+ h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取花销…'))
2512
+ }
2513
+ const total = report.total || { tokens: {}, costCny: null }
2514
+ const noTurns = Number(total.turns) === 0
2515
+ const currency = report.currency === 'CNY' || report.currency == null ? '¥' : `${report.currency} `
2516
+ // 零记录显示 0;有记录但完全未定价时才是未知(—)。
2517
+ const money = value => value == null
2518
+ ? (noTurns ? `${currency}0.000` : '—')
2519
+ : `${currency}${Number(value).toFixed(3)}`
2520
+ const tokens = value => Number(value || 0).toLocaleString('zh-CN')
2521
+ const allTokens = (total.tokens.uncachedInput || 0)
2522
+ + (total.tokens.cacheRead || 0)
2523
+ + (total.tokens.cacheWrite || 0)
2524
+ + (total.tokens.output || 0)
2525
+ return h(Card, {
2526
+ title: '花销',
2527
+ description: 'DSH agent 估算;ReMe 自己的 LLM 调用、余额和充值不在统计范围内。',
2528
+ },
2529
+ h('div', { className: 'ta-usage-top' },
2530
+ h('span', { className: 'ta-usage-money' }, money(total.costCny)),
2531
+ h('span', { className: 'ta-usage-meta' },
2532
+ `${tokens(allTokens)} tokens · ${total.turns || 0} 轮${total.unpricedTurns ? ` · ${total.unpricedTurns} 轮未定价` : ''}`)),
2533
+ h('div', { className: 'ta-usage-links' },
2534
+ h('a', { href: '/api/dsh-ta/usage/export.csv', className: 'ta-link' }, '导出 CSV'),
2535
+ h('a', { href: '/api/dsh-ta/usage/export.json', className: 'ta-link' }, '导出 JSON'),
2536
+ h('button', {
2537
+ type: 'button',
2538
+ className: 'ta-link ta-link--danger',
2539
+ 'aria-expanded': resetOpen,
2540
+ onClick: () => {
2541
+ setResetOpen(value => !value)
2542
+ setResetError('')
2543
+ },
2544
+ }, resetOpen ? '收起' : '清零')),
2545
+ resetOpen
2546
+ ? h('div', { className: 'ta-usage-reset' },
2547
+ h(Notice, { tone: 'warn' },
2548
+ '只删除本地花销记录(state/usage/*.jsonl),不会删除 ReMe 记忆、聊天记录或配置。清零后不可恢复。'),
2549
+ h('div', { className: 'ta-actions' },
2550
+ h(ActionButton, {
2551
+ variant: 'danger',
2552
+ busy: resetting,
2553
+ onClick: clearUsage,
2554
+ }, resetting ? '正在清零…' : '确认清零'),
2555
+ h(ActionButton, {
2556
+ disabled: resetting,
2557
+ onClick: () => { setResetOpen(false); setResetError('') },
2558
+ }, '取消')),
2559
+ resetError ? h(Notice, { tone: 'error' }, resetError) : null)
2560
+ : null,
2561
+ resetNotice ? h(Notice, { tone: 'success' }, resetNotice) : null,
2562
+ h('div', { className: 'ta-usage-rows' },
2563
+ ...Object.entries(report.byCategory || {}).map(([name, value]) => h('div', {
2564
+ key: name,
2565
+ className: 'ta-usage-row',
2566
+ },
2567
+ h('span', null, name),
2568
+ h('span', null,
2569
+ `${money(value.costCny)} · ${tokens(Object.values(value.tokens || {}).reduce((a, b) => a + Number(b || 0), 0))} tok`)))))
2570
+ }
2571
+
2572
+ function StatusPage({
2573
+ status, statusState, integrations, active, call, onRetry, onRefresh,
2574
+ }) {
2575
+ if (!status) {
2576
+ return h(LoadPlaceholder, {
2577
+ overline: 'STATUS',
2578
+ title: '状态',
2579
+ description: 'TA 的只读运行状态。',
2580
+ state: statusState,
2581
+ onRetry,
2582
+ })
2583
+ }
2584
+ const overall = overallStatus(status)
2585
+ const core = status.core && typeof status.core === 'object' ? status.core : {}
2586
+ const generated = status.generated || {}
2587
+ const maintenance = status.maintenance && typeof status.maintenance === 'object'
2588
+ ? status.maintenance
2589
+ : null
2590
+ const reme = (integrations && integrations.reme) || status.reme || null
2591
+ const im = (integrations && integrations.im) || status.im || null
2592
+ const diaryCount = Number(generated.diaryCount) || 0
2593
+ const hasHome = Boolean(status.existing || status.initialized)
2594
+ const soulInfo = core.soul || null
2595
+ const coreCards = [
2596
+ { key: 'soul', title: 'SOUL.md', description: 'TA 的人格底色。', info: soulInfo },
2597
+ { key: 'self', title: 'self/ME.md', description: 'TA 对自己的理解。', info: core.self },
2598
+ { key: 'recent', title: 'RECENT-MEMORY.md', description: 'TA 最近记着的事。', info: core.recent },
2599
+ { key: 'user', title: '认识/USER.md', description: 'TA 对对方逐步形成的认识。', info: core.user },
2600
+ ]
2601
+ const imBindings = im ? Number(im.dmBindings) || 0 : 0
2602
+ const imMode = im && im.mode === 'reduced' ? 'reduced' : 'owner'
2603
+ const hostImWarning = im && typeof im.warning === 'string' ? im.warning : ''
2604
+ const imWarning = hostImWarning || (imBindings > 1
2605
+ ? '检测到多个 IM 私聊绑定;已自动降级为 reduced(IM 不注入 self/RECENT/认识)'
2606
+ : '')
2607
+
2608
+ return h('div', { className: 'ta-page' },
2609
+ h(PageHeader, {
2610
+ overline: 'STATUS',
2611
+ title: '状态',
2612
+ description: '四件套、维护与连接情况;除花销清零外,这里不改动任何内容。',
2613
+ }),
2614
+ h(UsageCard, null),
2615
+ h('div', { className: 'ta-status-hero' },
2616
+ h(Badge, { tone: overall.tone }, overall.label),
2617
+ h('span', { className: 'ta-muted' }, overall.hint)),
2618
+ h('div', { className: 'ta-grid ta-grid--2' },
2619
+ coreCards.map(item => h(CoreFileCard, {
2620
+ key: item.key,
2621
+ title: item.title,
2622
+ description: item.description,
2623
+ info: item.info,
2624
+ fallback: '暂时无法读取这个文件的状态。',
2625
+ }))),
2626
+ h(MaintenanceStatusCard, {
2627
+ maintenance,
2628
+ active: Boolean(active),
2629
+ call,
2630
+ onRefresh,
2631
+ }),
2632
+ h('div', { className: 'ta-grid ta-grid--2' },
2633
+ h(Card, { title: '连接', description: 'ReMe 和 IM 都是可选的。' },
2634
+ h('div', { className: 'ta-status-line' },
2635
+ h(Badge, { tone: remeTone(reme) }, describeRemeShort(reme)),
2636
+ h('span', { className: 'ta-muted' }, (reme && reme.endpoint) || '地址未配置')),
2637
+ h('div', { className: 'ta-status-line' },
2638
+ h(Badge, { tone: imTone(im) }, describeImShort(im)),
2639
+ h('span', { className: 'ta-muted' }, describeImSummary(im))),
2640
+ h('dl', { className: 'ta-facts' },
2641
+ h(Fact, { label: 'IM 绑定', value: `${imBindings} 个 · ${imMode}` }),
2642
+ h(Fact, { label: '注入模式', value: describeImMode(imMode) })),
2643
+ imWarning ? h(Notice, { tone: 'warn' }, imWarning) : null,
2644
+ imMode === 'reduced'
2645
+ ? h(Notice, { tone: 'warn' }, '当前是 reduced 模式:IM 不注入 self/RECENT/认识,只注入 SOUL。')
2646
+ : null),
2647
+ h(Card, { title: '本地档案', description: 'TA 的人格、日记和本地文件。' },
2648
+ h('dl', { className: 'ta-facts' },
2649
+ h(Fact, {
2650
+ label: '路径',
2651
+ value: hasHome && status.home
2652
+ ? h('span', { className: 'ta-status-path' },
2653
+ h(LockIcon, { size: 12 }),
2654
+ h('span', null, status.home))
2655
+ : '尚未创建',
2656
+ }),
2657
+ h(Fact, {
2658
+ label: '生命周期',
2659
+ value: status.lifecycle === 'reincarnating'
2660
+ ? '转生中'
2661
+ : status.initialized ? '已初始化' : hasHome ? '待填写人设' : '未初始化',
2662
+ }),
2663
+ h(Fact, {
2664
+ label: '可写',
2665
+ value: status.writable === false ? '不可写' : status.writable === true ? '可写' : '未知',
2666
+ }),
2667
+ h(Fact, {
2668
+ label: '标记',
2669
+ value: status.homeMarked === false ? '缺少 .ta-home(会自动补写)' : '正常',
2670
+ }))),
2671
+ h(Card, { title: '日记', description: '维护生成的日记,只读展示。' },
2672
+ h('dl', { className: 'ta-facts' },
2673
+ h(Fact, { label: '篇数', value: `${diaryCount} 篇` }),
2674
+ h(Fact, { label: '最新', value: generated.latestDiary || '尚无' })))))
2675
+ }
2676
+
2677
+ // ===== 9. 高级页 =====
2678
+
2679
+ function AdvancedPage({ config }) {
2680
+ const draft = config.draft
2681
+ const ready = config.phase === 'ready' && Boolean(draft)
2682
+ const saving = config.saving
2683
+ const jurisdictionArray = parseJurisdictions(config.jurisdictionText)
2684
+ const dirty = Boolean(draft && config.baseline) && (
2685
+ ADVANCED_FIELDS.some(name => JSON.stringify(draft[name]) !== JSON.stringify(config.baseline[name]))
2686
+ || JSON.stringify(jurisdictionArray) !== JSON.stringify(config.baseline.jurisdictions))
2687
+
2688
+ async function saveAdvanced() {
2689
+ if (!ready || saving) return
2690
+ const target = { ...draft, jurisdictions: jurisdictionArray }
2691
+ if (target.jurisdictions.length === 0) {
2692
+ config.showError('至少保留一个只读辖区。')
2693
+ return
2694
+ }
2695
+ if (target.jurisdictions.some(root => root === '/' || root === '~')) {
2696
+ config.showError('辖区不能是 / 或 ~。')
2697
+ return
2698
+ }
2699
+ if (!Number.isInteger(target.captureInterval) || target.captureInterval < 1 || target.captureInterval > 60) {
2700
+ config.showError('捕获间隔必须是 1–60 的整数。')
2701
+ return
2702
+ }
2703
+ if (!Number.isInteger(target.stickerMinGapMinutes) || target.stickerMinGapMinutes < 0 || target.stickerMinGapMinutes > 1440) {
2704
+ config.showError('表情最小间隔必须是 0–1440 的整数(分钟)。')
2705
+ return
2706
+ }
2707
+ if (!Number.isInteger(target.stickerMaxPerDay) || target.stickerMaxPerDay < 1 || target.stickerMaxPerDay > 100) {
2708
+ config.showError('每日表情上限必须是 1–100 的整数。')
2709
+ return
2710
+ }
2711
+ for (const clock of [target.heartbeatActiveStart, target.heartbeatActiveEnd, target.jurisdictionOutingTime]) {
2712
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(String(clock))) {
2713
+ config.showError(`时间格式应为 HH:MM,当前是 ${clock}。`)
2714
+ return
2715
+ }
2716
+ }
2717
+ try {
2718
+ new Intl.DateTimeFormat('en-US', { timeZone: target.timezone })
2719
+ } catch {
2720
+ config.showError(`无效时区:${target.timezone}。`)
2721
+ return
2722
+ }
2723
+ await config.save({ fields: ADVANCED_FIELDS, target, successMessage: '已保存。配置已即时生效。' })
2724
+ }
2725
+
2726
+ function restoreDefaults() {
2727
+ if (!draft || saving) return
2728
+ const next = { ...draft }
2729
+ const configPageOnly = new Set([...MAINTENANCE_CONFIG_FIELDS, 'addressAs', 'imOwnerOnly'])
2730
+ for (const name of ADVANCED_FIELDS) {
2731
+ // 维护/称呼/IM 注入在「配置」「人设」页维护,高级页的“恢复默认值”不覆盖它们。
2732
+ if (configPageOnly.has(name)) continue
2733
+ next[name] = Array.isArray(ADVANCED_DEFAULTS[name])
2734
+ ? ADVANCED_DEFAULTS[name].slice()
2735
+ : ADVANCED_DEFAULTS[name]
2736
+ }
2737
+ config.replaceDraft(next)
2738
+ config.setJurisdictionText(ADVANCED_DEFAULTS.jurisdictions.join('\n'))
2739
+ config.showMessage('已填入默认值;点击「保存配置」后生效。')
2740
+ }
2741
+
2742
+ function textInput(name, placeholder) {
2743
+ return h('input', {
2744
+ className: 'ta-input',
2745
+ value: draft[name] == null ? '' : draft[name],
2746
+ placeholder,
2747
+ disabled: saving,
2748
+ onChange: event => config.update(name, event.target.value),
2749
+ })
2750
+ }
2751
+
2752
+ function numberInput(name, min, max) {
2753
+ return h('input', {
2754
+ className: 'ta-input ta-input--number',
2755
+ type: 'number',
2756
+ min,
2757
+ max,
2758
+ value: draft[name] == null ? '' : draft[name],
2759
+ disabled: saving,
2760
+ onChange: event => config.update(name, Number(event.target.value)),
2761
+ })
2762
+ }
2763
+
2764
+ return h('div', { className: 'ta-page' },
2765
+ h(PageHeader, {
2766
+ overline: 'ADVANCED',
2767
+ title: '高级',
2768
+ description: '通常不需要修改。维护设置在「配置」页;这里的设置写入当前 profile,保存后即时生效;家路径和 ReMe 数据目录不在普通设置里。',
2769
+ }),
2770
+ config.phase === 'unavailable'
2771
+ ? h(Notice, {
2772
+ tone: 'warn',
2773
+ action: h(ActionButton, { onClick: config.reload }, '重新读取'),
2774
+ }, config.message || '配置服务不可用。')
2775
+ : null,
2776
+ config.phase === 'loading'
2777
+ ? h(Card, null, h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取配置…'))
2778
+ : null,
2779
+ ready
2780
+ ? h(React.Fragment, null,
2781
+ h(Card, { title: '对话捕获', description: '控制日常对话送入 ReMe 长期记忆的节奏。' },
2782
+ h(Toggle, {
2783
+ label: '启用对话捕获',
2784
+ hint: '关闭后不把日常对话送入长期记忆。',
2785
+ checked: Boolean(draft.captureEnabled),
2786
+ disabled: saving,
2787
+ onChange: value => config.update('captureEnabled', value),
2788
+ }),
2789
+ h(Field, { label: '每几轮封一批', hint: '1–60 的整数。' },
2790
+ numberInput('captureInterval', 1, 60))),
2791
+ h(Card, { title: '夜间回顾' },
2792
+ h(Toggle, {
2793
+ label: '22:30 ReMe 整理',
2794
+ checked: Boolean(draft.dreamEnabled),
2795
+ disabled: saving,
2796
+ onChange: value => config.update('dreamEnabled', value),
2797
+ }),
2798
+ h(Toggle, {
2799
+ label: '02:00 清理旧出门记录',
2800
+ checked: Boolean(draft.outingCleanupEnabled),
2801
+ disabled: saving,
2802
+ onChange: value => config.update('outingCleanupEnabled', value),
2803
+ }),
2804
+ h(Toggle, {
2805
+ label: '22:45 辖区人格化查看',
2806
+ hint: '由 TA 自己读当天文件和对话,写一份辖区出门记录,供回顾使用。',
2807
+ checked: Boolean(draft.jurisdictionOutingEnabled),
2808
+ disabled: saving,
2809
+ onChange: value => config.update('jurisdictionOutingEnabled', value),
2810
+ }),
2811
+ h(Field, { label: '辖区查看时间', hint: '24 小时制,例如 22:45。' },
2812
+ textInput('jurisdictionOutingTime', '22:45'))),
2813
+ h(Card, { title: '主动消息' },
2814
+ h(Toggle, {
2815
+ label: '启用心跳',
2816
+ hint: '默认关闭。开启后只在活跃时段、inbox 非空时创建 life 会话。',
2817
+ checked: Boolean(draft.heartbeatEnabled),
2818
+ disabled: saving,
2819
+ onChange: value => config.update('heartbeatEnabled', value),
2820
+ }),
2821
+ h(Field, { label: '活跃开始' }, textInput('heartbeatActiveStart', '08:00')),
2822
+ h(Field, { label: '活跃结束' }, textInput('heartbeatActiveEnd', '23:00'))),
2823
+ h(Card, { title: '只读辖区', description: 'TA 可以只读访问的目录。' },
2824
+ h(Field, { label: '辖区列表', hint: '每行一个根目录;不能填 / 或 ~。' },
2825
+ h('textarea', {
2826
+ className: 'ta-textarea',
2827
+ rows: 4,
2828
+ value: config.jurisdictionText,
2829
+ disabled: saving,
2830
+ onChange: event => config.setJurisdictionText(event.target.value),
2831
+ }))),
2832
+ h(Card, { title: '时区' },
2833
+ h(Field, { label: 'IANA 时区', hint: '例如 Asia/Shanghai。' },
2834
+ textInput('timezone', 'Asia/Shanghai'))),
2835
+ h(Card, { title: '表情频率' },
2836
+ h(Field, { label: '两次表情的最小间隔(分钟)', hint: '0–1440。' },
2837
+ numberInput('stickerMinGapMinutes', 0, 1440)),
2838
+ h(Field, { label: '每个会话每天最多几个表情', hint: '1–100。' },
2839
+ numberInput('stickerMaxPerDay', 1, 100))),
2840
+ h('div', { className: 'ta-actions' },
2841
+ h(ActionButton, {
2842
+ variant: 'primary',
2843
+ disabled: saving || !dirty,
2844
+ busy: saving,
2845
+ onClick: saveAdvanced,
2846
+ }, saving ? '保存中…' : '保存配置'),
2847
+ h(ActionButton, { disabled: saving || !dirty, onClick: config.resetAll }, '还原修改'),
2848
+ h(ActionButton, { variant: 'ghost', disabled: saving, onClick: restoreDefaults }, '恢复默认值'),
2849
+ h('span', {
2850
+ className: 'ta-muted ta-actions-end',
2851
+ role: 'status',
2852
+ 'aria-live': 'polite',
2853
+ }, config.message || (dirty ? '有未保存修改' : '已保存'))),
2854
+ config.error ? h(Notice, { tone: 'error' }, config.error) : null)
2855
+ : null)
2856
+ }
2857
+
2858
+ // ===== 10. 插件入口 / 注册 =====
2859
+
2860
+ // --- 宿主服务(仅在 apply 内使用) ---
2861
+
2862
+ function configuredHome() {
2863
+ try {
2864
+ const value = configForms?.get('dsh-ta')?.getSnapshot?.().value
2865
+ return typeof value?.taHome === 'string' && value.taHome ? value.taHome : DEFAULT_HOME_PATH
2866
+ } catch {
2867
+ return DEFAULT_HOME_PATH
2868
+ }
2869
+ }
2870
+
2871
+ function workspaceItems() {
2872
+ try {
2873
+ const items = workspaces?.list?.getSnapshot?.().items
2874
+ return Array.isArray(items) ? items : []
2875
+ } catch {
2876
+ return []
2877
+ }
2878
+ }
2879
+
2880
+ function findWorkspace(home) {
2881
+ const target = String(home == null ? '' : home)
2882
+ const suffix = target.replace(/^~\/?/, '').replace(/\/+$/, '')
2883
+ return workspaceItems().find(item => item && (
2884
+ item.path === target
2885
+ || (suffix && typeof item.path === 'string' && item.path.endsWith(`/${suffix}`))
2886
+ ))
2887
+ }
2888
+
2889
+ async function openTaWorkspace(home) {
2890
+ if (!uiWorkspace || !workspaces) throw new Error('会话服务未就绪')
2891
+ const value = typeof home === 'string' && home.trim() ? home.trim() : configuredHome()
2892
+ let workspace = findWorkspace(value)
2893
+ // 新家可能还没有注册为 DSH 工作区;注册的是已有路径,不创建文件。
2894
+ if (!workspace && typeof workspaces.create === 'function') {
2895
+ workspace = await workspaces.create({ path: value })
2896
+ }
2897
+ if (!workspace) throw new Error(`没有找到 ${value} 工作区,请先把它注册为工作区`)
2898
+ const workspaceId = workspace.workspaceId ?? workspace.id
2899
+ if (!workspaceId) throw new Error(`工作区 ${value} 缺少 id`)
2900
+ await uiWorkspace.openWorkspace(workspaceId, undefined, { agentPreset: 'ta' })
2901
+ return workspace
2902
+ }
2903
+
2904
+ // --- Slot 视图 ---
2905
+
2906
+ function TaStickerCard({ block, phase }) {
2907
+ const text = Array.isArray(block?.content)
2908
+ ? block.content.find(part => part?.type === 'text')?.text
2909
+ : undefined
2910
+ let value
2911
+ try {
2912
+ const marker = typeof text === 'string' ? text.indexOf('STICKER:') : -1
2913
+ value = marker >= 0 ? JSON.parse(text.slice(marker + 'STICKER:'.length)) : undefined
2914
+ } catch {
2915
+ value = undefined
2916
+ }
2917
+ if (phase === 'preparing' || phase === 'start') {
2918
+ return h('span', { style: { fontSize: 12, opacity: 0.65 } }, '正在准备表情…')
2919
+ }
2920
+ if (block?.isError) {
2921
+ return h('span', {
2922
+ role: 'alert',
2923
+ style: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, inherit)' },
2924
+ }, block?.error?.message || '表情发送失败')
2925
+ }
2926
+ return h('span', { style: { fontSize: 12, opacity: 0.7 } },
2927
+ value?.text ? `表情已发送 · ${value.text}` : '表情已发送')
2928
+ }
2929
+
2930
+ function TaEntry({ wide }) {
2931
+ const alive = useAlive()
2932
+ const [busy, setBusy] = React.useState(false)
2933
+ const [error, setError] = React.useState('')
2934
+ const busyRef = React.useRef(false)
2935
+
2936
+ async function openTa() {
2937
+ if (busyRef.current) return
2938
+ if (!uiWorkspace || !workspaces) {
2939
+ setError('会话服务未就绪')
2940
+ return
2941
+ }
2942
+ busyRef.current = true
2943
+ setBusy(true)
2944
+ setError('')
2945
+ try {
2946
+ let initialized
2947
+ try {
2948
+ const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(5000) : undefined
2949
+ const status = await requestJson('/status', { signal })
2950
+ initialized = status && status.initialized
2951
+ } catch {
2952
+ /* 状态接口暂时不可用时继续按工作区查找 */
2953
+ }
2954
+ if (initialized === false) {
2955
+ const message = 'TA 还没有家:请先打开 设置 → TA 的家 完成初始化'
2956
+ if (alive.current) setError(message)
2957
+ return
2958
+ }
2959
+ await openTaWorkspace(configuredHome())
2960
+ } catch (cause) {
2961
+ if (alive.current && !(cause && cause.cancelled)) setError(errorMessage(cause))
2962
+ } finally {
2963
+ busyRef.current = false
2964
+ if (alive.current) setBusy(false)
2965
+ }
2966
+ }
2967
+
2968
+ return h('button', {
2969
+ type: 'button',
2970
+ title: error || '去找Ta',
2971
+ 'aria-label': '去找Ta',
2972
+ disabled: busy,
2973
+ onClick: openTa,
2974
+ style: {
2975
+ display: 'inline-flex',
2976
+ alignItems: 'center',
2977
+ justifyContent: 'center',
2978
+ gap: 6,
2979
+ height: 30,
2980
+ width: wide ? 'auto' : 30,
2981
+ padding: wide ? '0 9px' : 0,
2982
+ border: '1px solid var(--dsw-alias-border-l2, var(--dsw-alias-border-l1, transparent))',
2983
+ borderRadius: 8,
2984
+ background: 'transparent',
2985
+ color: 'inherit',
2986
+ font: 'inherit',
2987
+ fontSize: 12,
2988
+ cursor: busy ? 'default' : 'pointer',
2989
+ opacity: busy ? 0.6 : 1,
2990
+ },
2991
+ },
2992
+ h('span', { 'aria-hidden': true, style: { fontSize: 14, lineHeight: 1 } }, '✦'),
2993
+ wide ? h('span', null, error || '去找Ta') : null)
2994
+ }
2995
+
2996
+ function TaIcon({ size = 16 }) {
2997
+ return h('svg', {
2998
+ 'aria-hidden': true,
2999
+ focusable: 'false',
3000
+ viewBox: '0 0 16 16',
3001
+ width: size,
3002
+ height: size,
3003
+ fill: 'none',
3004
+ stroke: 'currentColor',
3005
+ strokeWidth: 1.3,
3006
+ style: { display: 'block', flex: 'none' },
3007
+ },
3008
+ h('path', {
3009
+ // 房子只描边,视觉重量更接近其他导航图标。
3010
+ d: 'M2.1 7.15 8 2.2l5.9 4.95M3.45 6.65v7.15h9.1V6.65M6.7 13.8v-3.7h2.6v3.7',
3011
+ vectorEffect: 'non-scaling-stroke',
3012
+ }),
3013
+ h('path', {
3014
+ // 右上角实心曲线星,底端轻触屋顶;16px 下约 5.6px,参考设置里的技能图标。
3015
+ d: 'M12.4 0.3C12.65 1.85 13.45 2.65 15.2 3.1C13.45 3.55 12.65 4.35 12.4 5.9C12.15 4.35 11.35 3.55 9.6 3.1C11.35 2.65 12.15 1.85 12.4 0.3Z',
3016
+ fill: 'currentColor',
3017
+ stroke: 'none',
3018
+ }))
3019
+ }
3020
+
3021
+ // --- 设置面板 ---
3022
+
3023
+ function TaSettings(props) {
3024
+ const { call, alive } = useApi()
3025
+ const [statusState, reloadStatus] = useResource('/status', call, alive)
3026
+ const [personaState, reloadPersona] = useResource('/persona', call, alive)
3027
+ const [integrationsState, reloadIntegrations] = useResource('/integrations', call, alive)
3028
+ const [tab, setTab] = React.useState('config')
3029
+ const [operationBusy, setOperationBusy] = React.useState(false)
3030
+ const [dirtyMap, setDirtyMap] = React.useState({ soul: false })
3031
+ const configTabForm = useConfigForm(configForms)
3032
+ const advancedConfig = useConfigForm(configForms)
3033
+
3034
+ const refreshAll = React.useCallback(() => {
3035
+ void reloadStatus()
3036
+ void reloadPersona()
3037
+ void reloadIntegrations()
3038
+ }, [reloadStatus, reloadPersona, reloadIntegrations])
3039
+
3040
+ const refreshConnections = React.useCallback(async () => {
3041
+ await Promise.allSettled([reloadStatus(), reloadIntegrations()])
3042
+ }, [reloadStatus, reloadIntegrations])
3043
+
3044
+ const refreshStatus = React.useCallback(() => {
3045
+ void reloadStatus()
3046
+ }, [reloadStatus])
3047
+
3048
+ const handlePersonaDirty = React.useCallback((field, dirty) => {
3049
+ setDirtyMap(previous => previous[field] === dirty ? previous : { ...previous, [field]: dirty })
3050
+ }, [])
3051
+
3052
+ const handlePersonaSaved = React.useCallback(() => {
3053
+ void reloadStatus()
3054
+ }, [reloadStatus])
3055
+
3056
+ // 已有 TA 缺 .ta-home 标记时自动补写一次;失败忽略,不阻塞页面。
3057
+ const markerFixRef = React.useRef('')
3058
+ React.useEffect(() => {
3059
+ const data = statusState.data
3060
+ if (statusState.phase !== 'ready' || !data || !data.initialized || data.homeMarked !== false) return
3061
+ const home = String(data.home || '')
3062
+ if (!home || markerFixRef.current === home) return
3063
+ markerFixRef.current = home
3064
+ call('/home/init', { method: 'POST', body: { path: home }, timeoutMs: 30000 })
3065
+ .then(() => {
3066
+ if (alive.current) refreshAll()
3067
+ })
3068
+ .catch(() => {
3069
+ /* 补标记失败不阻塞:下次打开设置会再试 */
3070
+ })
3071
+ }, [statusState.phase, statusState.data, call, alive, refreshAll])
3072
+
3073
+ const status = statusState.data
3074
+ const lifecycleBusy = Boolean(status && status.lifecycle === 'reincarnating')
3075
+ const blocked = operationBusy || lifecycleBusy
3076
+ const personaDirty = Boolean(dirtyMap.soul)
3077
+
3078
+ function changeTab(next) {
3079
+ configTabForm.clearNotices()
3080
+ advancedConfig.clearNotices()
3081
+ setTab(next)
3082
+ }
3083
+
3084
+ return h('div', { className: 'ta-root' },
3085
+ h('style', { 'data-dsh-ta-ui': '' }, TA_CSS),
3086
+ h(SegmentedTabs, {
3087
+ items: TAB_ITEMS,
3088
+ value: tab,
3089
+ onChange: changeTab,
3090
+ label: 'TA 设置分区',
3091
+ }),
3092
+ statusState.error && status
3093
+ ? h(Notice, {
3094
+ tone: 'warn',
3095
+ action: h(ActionButton, { onClick: () => { void reloadStatus() } }, '刷新状态'),
3096
+ }, `状态刷新失败:${statusState.error}。页面显示的是上次读取的数据。`)
3097
+ : null,
3098
+ h(Panel, { id: 'ta-panel-config', labelledBy: 'ta-tab-config', active: tab === 'config' },
3099
+ h(ConfigPage, {
3100
+ status,
3101
+ statusState,
3102
+ integrations: integrationsState.data,
3103
+ integrationsState,
3104
+ call,
3105
+ alive,
3106
+ refreshAll,
3107
+ refreshConnections,
3108
+ config: configTabForm,
3109
+ blocked,
3110
+ personaDirty,
3111
+ onBusyChange: setOperationBusy,
3112
+ onRetryStatus: () => { void reloadStatus() },
3113
+ })),
3114
+ h(Panel, { id: 'ta-panel-persona', labelledBy: 'ta-tab-persona', active: tab === 'persona' },
3115
+ h(PersonaPage, {
3116
+ status,
3117
+ statusState,
3118
+ resource: personaState,
3119
+ reload: reloadPersona,
3120
+ call,
3121
+ alive,
3122
+ blocked,
3123
+ onDirtyChange: handlePersonaDirty,
3124
+ onSaved: handlePersonaSaved,
3125
+ onRetryStatus: () => { void reloadStatus() },
3126
+ })),
3127
+ h(Panel, { id: 'ta-panel-status', labelledBy: 'ta-tab-status', active: tab === 'status' },
3128
+ h(StatusPage, {
3129
+ status,
3130
+ statusState,
3131
+ integrations: integrationsState.data,
3132
+ active: tab === 'status',
3133
+ call,
3134
+ onRetry: () => { void reloadStatus() },
3135
+ onRefresh: refreshStatus,
3136
+ })),
3137
+ h(Panel, { id: 'ta-panel-advanced', labelledBy: 'ta-tab-advanced', active: tab === 'advanced' },
3138
+ h(AdvancedPage, { config: advancedConfig })))
3139
+ }
3140
+
3141
+ // --- Slot 注册 ---
3142
+
3143
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
3144
+ name: 'tool.call.toolview',
3145
+ key: 'ta_sticker',
3146
+ }, TaStickerCard))
3147
+
3148
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
3149
+ name: 'sidebar.footer.action',
3150
+ id: 'dsh-ta-entry',
3151
+ order: 20,
3152
+ label: '去找Ta',
3153
+ }, TaEntry))
3154
+
3155
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
3156
+ name: 'settings.section',
3157
+ id: 'dsh-ta',
3158
+ order: 30,
3159
+ label: () => 'TA 的家',
3160
+ }, TaSettings))
3161
+
3162
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
3163
+ name: 'settings.section.icon',
3164
+ id: 'dsh-ta',
3165
+ order: 30,
3166
+ label: () => 'TA 的家',
3167
+ }, TaIcon))
3168
+ }
3169
+
3170
+ // 插件入口:inject 声明依赖的宿主服务,apply 负责注册槽位。
3171
+ return {
3172
+ inject: ['slots', 'conversation', 'uiWorkspace', 'workspaces', 'configForms'],
3173
+ apply,
3174
+ }
3175
+ },
3176
+ })