dsh-ta 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -1,11 +1,35 @@
1
+ /**
2
+ * dsh-ta 设置页 client 半边。
3
+ *
4
+ * 顶部 SegmentedTabs 分四个页签:
5
+ * 配置(默认)→ 人设 → 状态 → 高级
6
+ *
7
+ * 信息架构:
8
+ * - 配置:服务就绪条、长期记忆(ReMe)与 IM 检测两列卡片、
9
+ * 折叠的“TA 的家”(初始化 / 转生)置顶,外部服务卡居中,服务就绪条置底。
10
+ * - 人设:SOUL 与 USER 两个独立编辑器,各自预览、保存、409 冲突与重新加载。
11
+ * - 状态:只读统计与花销卡;花销可二次确认清零。
12
+ * - 高级:configForms 捕获、夜间回顾、心跳、辖区、时区、表情频率。
13
+ *
14
+ * 约束:
15
+ * - 只使用 --dsw-alias-* 主题 token,不写死颜色;全部样式 scoped 在 .ta- 前缀。
16
+ * - React 由宿主模块表提供,不 import 任何 Client 包,不用 JSX。
17
+ * - 普通设置不显示、不提交家路径;家路径只由初始化 / 转生写入。
18
+ * - 所有请求都带 AbortController 与超时,组件卸载时终止。
19
+ */
1
20
  window.__ModuleLoader__.load({
2
21
  id: 'dsh-ta',
3
22
  factory(require) {
4
23
  const React = require('react')
5
24
  const h = React.createElement
6
25
 
7
- const DEFAULTS = {
8
- taHome: '~/TATA/home',
26
+ const API_ROOT = '/api/dsh-ta'
27
+ const DEFAULT_HOME_PATH = '~/TATA/home'
28
+ const REQUEST_TIMEOUT_MS = 8000
29
+ const PERSONA_MAX_CHARS = 5000
30
+ const DEFAULT_PERSONA_BUDGETS = { soul: 2000, user: 4000 }
31
+
32
+ const ADVANCED_DEFAULTS = {
9
33
  remeEndpoint: 'http://127.0.0.1:2333',
10
34
  jurisdictions: ['~/dsh'],
11
35
  captureEnabled: true,
@@ -18,11 +42,12 @@ window.__ModuleLoader__.load({
18
42
  jurisdictionOutingEnabled: true,
19
43
  jurisdictionOutingTime: '22:45',
20
44
  timezone: 'Asia/Shanghai',
45
+ stickerMinGapMinutes: 30,
46
+ stickerMaxPerDay: 12,
21
47
  }
22
48
 
23
- const FIELD_KEYS = [
24
- 'taHome',
25
- 'remeEndpoint',
49
+ // 高级页可提交字段:明确排除家路径;长期记忆地址在“配置”页的卡片里保存。
50
+ const ADVANCED_FIELDS = [
26
51
  'jurisdictions',
27
52
  'captureEnabled',
28
53
  'captureInterval',
@@ -34,26 +59,786 @@ window.__ModuleLoader__.load({
34
59
  'jurisdictionOutingEnabled',
35
60
  'jurisdictionOutingTime',
36
61
  'timezone',
62
+ 'stickerMinGapMinutes',
63
+ 'stickerMaxPerDay',
64
+ ]
65
+
66
+ // 读取配置时需要的全部字段(含 ReMe 地址);ReMe 地址不出现于高级页。
67
+ const CONFIG_FIELDS = ['remeEndpoint', ...ADVANCED_FIELDS]
68
+
69
+ const TAB_ITEMS = [
70
+ { value: 'config', label: '配置', id: 'ta-tab-config', panelId: 'ta-panel-config' },
71
+ { value: 'persona', label: '人设', id: 'ta-tab-persona', panelId: 'ta-panel-persona' },
72
+ { value: 'status', label: '状态', id: 'ta-tab-status', panelId: 'ta-panel-status' },
73
+ { value: 'advanced', label: '高级', id: 'ta-tab-advanced', panelId: 'ta-panel-advanced' },
37
74
  ]
38
75
 
39
- const inputStyle = {
40
- width: '100%',
41
- boxSizing: 'border-box',
42
- padding: '7px 9px',
43
- border: '1px solid var(--dsw-alias-border-l4, var(--dsw-alias-border-l1, rgba(127,127,127,.28)))',
44
- borderRadius: 7,
45
- background: 'var(--dsw-alias-bg-layer-1, rgba(127,127,127,.06))',
46
- color: 'inherit',
47
- font: 'inherit',
48
- fontSize: 13,
76
+ /* ------------------------------------------------------------------ *
77
+ * 请求层
78
+ * ------------------------------------------------------------------ */
79
+
80
+ class ApiError extends Error {
81
+ constructor(message, options = {}) {
82
+ super(message)
83
+ this.name = 'ApiError'
84
+ this.status = Number(options.status) || 0
85
+ this.code = options.code || ''
86
+ this.cancelled = options.cancelled === true
87
+ this.unavailable = options.unavailable === true
88
+ this.network = options.network === true
89
+ this.timeout = options.timeout === true
90
+ }
91
+ }
92
+
93
+ function errorMessage(cause) {
94
+ if (cause instanceof Error && cause.message) return cause.message
95
+ if (typeof cause === 'string' && cause) return cause
96
+ return '操作失败,请重试'
97
+ }
98
+
99
+ async function requestJson(path, options = {}) {
100
+ const init = {
101
+ method: options.method || 'GET',
102
+ cache: 'no-store',
103
+ credentials: 'same-origin',
104
+ signal: options.signal,
105
+ }
106
+ if (options.body !== undefined) {
107
+ init.headers = { 'content-type': 'application/json' }
108
+ init.body = JSON.stringify(options.body)
109
+ }
110
+ let response
111
+ try {
112
+ response = await fetch(`${API_ROOT}${path}`, init)
113
+ } catch (cause) {
114
+ if (cause && cause.name === 'AbortError') throw new ApiError('请求已取消', { cancelled: true })
115
+ throw new ApiError('网络连接失败,请检查网络或 Host 服务后重试', { network: true })
116
+ }
117
+ let payload = null
118
+ try {
119
+ payload = await response.json()
120
+ } catch {
121
+ payload = null
122
+ }
123
+ if (response.status === 404) {
124
+ throw new ApiError(
125
+ (payload && payload.error && payload.error.message) || '设置接口不可用,请确认 Host 端 dsh-ta 版本',
126
+ { status: 404, code: 'NOT_FOUND', unavailable: true },
127
+ )
128
+ }
129
+ if (!response.ok || (payload && payload.ok === false)) {
130
+ throw new ApiError(
131
+ (payload && payload.error && payload.error.message) || `请求失败(HTTP ${response.status})`,
132
+ { status: response.status, code: (payload && payload.error && payload.error.code) || '' },
133
+ )
134
+ }
135
+ if (!payload || typeof payload !== 'object') {
136
+ throw new ApiError('设置接口返回了无法识别的响应,请重试', { status: response.status })
137
+ }
138
+ return payload && payload.ok !== undefined ? payload.data : payload
139
+ }
140
+
141
+ /* ------------------------------------------------------------------ *
142
+ * Hooks
143
+ * ------------------------------------------------------------------ */
144
+
145
+ function useAlive() {
146
+ const alive = React.useRef(true)
147
+ React.useEffect(() => {
148
+ alive.current = true
149
+ return () => {
150
+ alive.current = false
151
+ }
152
+ }, [])
153
+ return alive
154
+ }
155
+
156
+ /** 每个请求独立 AbortController + 8s 超时;组件卸载时终止全部请求。 */
157
+ function useApi() {
158
+ const alive = useAlive()
159
+ const controllers = React.useRef(new Set())
160
+ React.useEffect(() => () => {
161
+ for (const controller of controllers.current) controller.abort()
162
+ controllers.current.clear()
163
+ }, [])
164
+
165
+ const call = React.useCallback(async (path, options = {}) => {
166
+ const controller = new AbortController()
167
+ controllers.current.add(controller)
168
+ let timedOut = false
169
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : REQUEST_TIMEOUT_MS
170
+ const timer = setTimeout(() => {
171
+ timedOut = true
172
+ controller.abort()
173
+ }, timeoutMs)
174
+ try {
175
+ return await requestJson(path, { ...options, signal: controller.signal })
176
+ } catch (cause) {
177
+ if (timedOut) throw new ApiError('请求超时,请检查网络后重试', { timeout: true, code: 'TIMEOUT' })
178
+ if (controller.signal.aborted) throw new ApiError('请求已取消', { cancelled: true })
179
+ throw cause
180
+ } finally {
181
+ clearTimeout(timer)
182
+ controllers.current.delete(controller)
183
+ }
184
+ }, [])
185
+
186
+ return { call, alive }
187
+ }
188
+
189
+ /**
190
+ * 一个 GET 资源的 loading / ready / error / unavailable 状态。
191
+ * 刷新失败时保留旧数据,页面不闪空。
192
+ */
193
+ function useResource(path, call, alive) {
194
+ const [state, setState] = React.useState({ phase: 'loading', data: null, error: '', code: '', version: 0 })
195
+ const generation = React.useRef(0)
196
+ const load = React.useCallback(async () => {
197
+ const id = ++generation.current
198
+ setState(previous => previous.data
199
+ ? { ...previous, error: '', code: '' }
200
+ : { phase: 'loading', data: null, error: '', code: '', version: previous.version || 0 })
201
+ try {
202
+ const data = await call(path)
203
+ if (!alive.current || id !== generation.current) return
204
+ setState(previous => ({
205
+ phase: 'ready',
206
+ data,
207
+ error: '',
208
+ code: '',
209
+ version: (previous.version || 0) + 1,
210
+ }))
211
+ } catch (cause) {
212
+ if (!alive.current || id !== generation.current) return
213
+ if (cause && cause.cancelled) return
214
+ setState(previous => ({
215
+ phase: cause && cause.unavailable ? 'unavailable' : 'error',
216
+ data: previous.data,
217
+ error: errorMessage(cause),
218
+ code: cause && cause.code ? cause.code : '',
219
+ version: previous.version || 0,
220
+ }))
221
+ }
222
+ }, [path, call, alive])
223
+ React.useEffect(() => {
224
+ void load()
225
+ }, [load])
226
+ return [state, load]
227
+ }
228
+
229
+ /**
230
+ * configForms 中 dsh-ta 节点的读取 / 编辑 / 保存状态。
231
+ * 配置页的 ReMe 地址与高级页共用同一个 draft;各自只提交自己负责的字段。
232
+ */
233
+ function useConfigForm(configForms) {
234
+ const alive = useAlive()
235
+ const [form, setForm] = React.useState(null)
236
+ const [phase, setPhase] = React.useState('loading')
237
+ const [message, setMessage] = React.useState('')
238
+ const [error, setError] = React.useState('')
239
+ const [draft, setDraft] = React.useState(null)
240
+ const [baseline, setBaseline] = React.useState(null)
241
+ const [jurisdictionText, setJurisdictionTextState] = React.useState(ADVANCED_DEFAULTS.jurisdictions.join('\n'))
242
+ const [saving, setSaving] = React.useState(false)
243
+ const [reloadToken, setReloadToken] = React.useState(0)
244
+ const savingRef = React.useRef(false)
245
+ const editingRef = React.useRef(false)
246
+
247
+ React.useEffect(() => {
248
+ if (!configForms) {
249
+ setPhase('unavailable')
250
+ setMessage('配置服务不可用。')
251
+ return undefined
252
+ }
253
+ let bound
254
+ try {
255
+ bound = configForms.get('dsh-ta')
256
+ setForm(bound)
257
+ } catch (cause) {
258
+ setPhase('unavailable')
259
+ setMessage(errorMessage(cause))
260
+ return undefined
261
+ }
262
+ if (!bound) {
263
+ setPhase('unavailable')
264
+ setMessage('当前 profile 没有提供 dsh-ta 配置。')
265
+ return undefined
266
+ }
267
+ let ready = false
268
+ const timeout = setTimeout(() => {
269
+ if (!ready) {
270
+ setPhase('unavailable')
271
+ setMessage('读取配置超时,请刷新页面重试。')
272
+ }
273
+ }, 10000)
274
+ const read = () => {
275
+ let snapshot
276
+ try {
277
+ snapshot = bound.getSnapshot()
278
+ } catch {
279
+ return
280
+ }
281
+ if (snapshot.status === 'unavailable') {
282
+ ready = true
283
+ setPhase('unavailable')
284
+ setMessage('当前 profile 没有提供 dsh-ta 配置。')
285
+ return
286
+ }
287
+ if (snapshot.status === 'loading' && !snapshot.value) return
288
+ if (!snapshot.value) return
289
+ if (savingRef.current || editingRef.current) return
290
+ const next = {}
291
+ for (const name of CONFIG_FIELDS) {
292
+ next[name] = snapshot.value[name] !== undefined ? snapshot.value[name] : ADVANCED_DEFAULTS[name]
293
+ }
294
+ setDraft(next)
295
+ setBaseline(next)
296
+ setJurisdictionTextState((Array.isArray(next.jurisdictions)
297
+ ? next.jurisdictions
298
+ : ADVANCED_DEFAULTS.jurisdictions).join('\n'))
299
+ ready = true
300
+ setPhase('ready')
301
+ setError('')
302
+ }
303
+ read()
304
+ const unsubscribe = bound.subscribe(read)
305
+ return () => {
306
+ clearTimeout(timeout)
307
+ unsubscribe()
308
+ }
309
+ }, [configForms, reloadToken])
310
+
311
+ const clearNotices = React.useCallback(() => {
312
+ setMessage('')
313
+ setError('')
314
+ }, [])
315
+
316
+ const showError = React.useCallback(text => {
317
+ setMessage('')
318
+ setError(String(text || '操作失败,请重试'))
319
+ }, [])
320
+
321
+ const showMessage = React.useCallback(text => {
322
+ setError('')
323
+ setMessage(String(text || ''))
324
+ }, [])
325
+
326
+ const update = React.useCallback((name, value) => {
327
+ if (savingRef.current) return
328
+ editingRef.current = true
329
+ setDraft(previous => previous ? { ...previous, [name]: value } : previous)
330
+ setMessage('')
331
+ setError('')
332
+ }, [])
333
+
334
+ const setJurisdictionText = React.useCallback(value => {
335
+ if (savingRef.current) return
336
+ editingRef.current = true
337
+ setJurisdictionTextState(value)
338
+ setMessage('')
339
+ setError('')
340
+ }, [])
341
+
342
+ const replaceDraft = React.useCallback(next => {
343
+ if (!next || savingRef.current) return
344
+ editingRef.current = true
345
+ setDraft({ ...next })
346
+ setMessage('')
347
+ setError('')
348
+ }, [])
349
+
350
+ const reload = React.useCallback(() => {
351
+ editingRef.current = false
352
+ setPhase('loading')
353
+ setMessage('')
354
+ setError('')
355
+ setReloadToken(value => value + 1)
356
+ }, [])
357
+
358
+ const resetAll = React.useCallback(() => {
359
+ if (!baseline || savingRef.current) return
360
+ editingRef.current = false
361
+ setDraft({ ...baseline })
362
+ setJurisdictionTextState((Array.isArray(baseline.jurisdictions)
363
+ ? baseline.jurisdictions
364
+ : ADVANCED_DEFAULTS.jurisdictions).join('\n'))
365
+ setMessage('')
366
+ setError('')
367
+ }, [baseline])
368
+
369
+ const save = React.useCallback(async options => {
370
+ const fields = Array.isArray(options && options.fields) ? options.fields : []
371
+ const target = (options && options.target) || draft
372
+ if (!form || !target || !baseline || savingRef.current) return false
373
+ let snapshot
374
+ try {
375
+ snapshot = form.getSnapshot()
376
+ } catch {
377
+ setError('配置状态不可用,请刷新页面重试。')
378
+ return false
379
+ }
380
+ if (snapshot.writable === false) {
381
+ setError('当前 profile 不允许写入配置。')
382
+ return false
383
+ }
384
+ const changed = fields.filter(name => JSON.stringify(target[name]) !== JSON.stringify(baseline[name]))
385
+ if (changed.length === 0) {
386
+ setMessage('没有修改。')
387
+ setError('')
388
+ return true
389
+ }
390
+ savingRef.current = true
391
+ setSaving(true)
392
+ setMessage('正在保存…')
393
+ setError('')
394
+ try {
395
+ const ops = changed.map(name => ({ op: 'set', path: [name], value: target[name] }))
396
+ const accepted = await form.mutate(ops, snapshot.revision)
397
+ if (!accepted) throw new Error('宿主拒绝了这次配置写入。')
398
+ if (!alive.current) return true
399
+ editingRef.current = false
400
+ const patch = {}
401
+ for (const name of changed) patch[name] = target[name]
402
+ setDraft(previous => previous ? { ...previous, ...patch } : target)
403
+ setBaseline(previous => previous ? { ...previous, ...patch } : target)
404
+ setMessage((options && options.successMessage) || '已保存。配置已即时生效。')
405
+ return true
406
+ } catch (cause) {
407
+ if (alive.current) setError(errorMessage(cause))
408
+ return false
409
+ } finally {
410
+ savingRef.current = false
411
+ if (alive.current) setSaving(false)
412
+ }
413
+ }, [form, draft, baseline, alive])
414
+
415
+ return {
416
+ phase,
417
+ message,
418
+ error,
419
+ draft,
420
+ baseline,
421
+ saving,
422
+ jurisdictionText,
423
+ update,
424
+ setJurisdictionText,
425
+ replaceDraft,
426
+ resetAll,
427
+ reload,
428
+ save,
429
+ clearNotices,
430
+ showError,
431
+ showMessage,
432
+ }
49
433
  }
50
434
 
435
+ /* ------------------------------------------------------------------ *
436
+ * Scoped 样式(全部 .ta- 前缀,仅使用 --dsw-alias-* token)
437
+ * ------------------------------------------------------------------ */
438
+
439
+ const TA_CSS = `
440
+ .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}
441
+ .ta-root *,.ta-root *::before,.ta-root *::after{box-sizing:border-box}
442
+ .ta-root button,.ta-root input,.ta-root textarea,.ta-root select{font-family:inherit}
443
+ .ta-root :focus-visible{outline:2px solid var(--dsw-alias-brand-primary,currentColor);outline-offset:2px}
444
+ .ta-panel{display:block}
445
+ .ta-panel[hidden]{display:none}
446
+ .ta-page{display:grid;gap:14px;animation:ta-rise-in .3s cubic-bezier(.22,1,.36,1) both}
447
+
448
+ /* 顶部 SegmentedTabs */
449
+ .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}
450
+ .ta-tabs::-webkit-scrollbar{display:none}
451
+ .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}
452
+ .ta-tab:hover{color:var(--dsw-alias-label-primary,inherit)}
453
+ .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)}
454
+
455
+ /* 页头 */
456
+ .ta-page-head{margin:2px 0 0}
457
+ .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}
458
+ .ta-h1{margin:5px 0 0;font-size:21px;font-weight:700;letter-spacing:-.01em;line-height:1.25}
459
+ .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}
460
+
461
+ /* 卡片与栅格 */
462
+ .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)}
463
+ .ta-card-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}
464
+ .ta-card-head-main{min-width:0}
465
+ .ta-card-head-side{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
466
+ .ta-card-title{margin:0;font-size:14px;font-weight:650;letter-spacing:.01em;line-height:1.35}
467
+ .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))}
468
+ .ta-card-body{display:grid;gap:12px;margin-top:14px}
469
+ .ta-grid{display:grid;gap:14px;min-width:0}
470
+ .ta-grid--2{grid-template-columns:repeat(2,minmax(0,1fr))}
471
+ .ta-grid--2 > .ta-card{align-content:start}
472
+ .ta-grid > .ta-card{min-width:0}
473
+ .ta-grid--full{grid-column:1 / -1}
474
+
475
+ /* 服务就绪条 */
476
+ .ta-ready{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;min-width:0}
477
+ .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)}
478
+ .ta-dot{width:8px;height:8px;flex:none;border-radius:50%;background:var(--dsw-alias-label-quaternary,var(--dsw-alias-label-tertiary,currentColor))}
479
+ .ta-ready-item.is-success .ta-dot{background:var(--dsw-alias-state-success-primary,currentColor)}
480
+ .ta-ready-item.is-warn .ta-dot{background:var(--dsw-alias-state-warn-primary,currentColor)}
481
+ .ta-ready-item.is-error .ta-dot{background:var(--dsw-alias-state-error-primary,currentColor)}
482
+ .ta-ready-text{display:grid;gap:1px;min-width:0}
483
+ .ta-ready-label{font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
484
+ .ta-ready-value{font-size:12.5px;font-weight:600}
485
+ .ta-ready-detail{font-size:11px;color:var(--dsw-alias-label-tertiary,inherit);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
486
+
487
+ /* badge */
488
+ .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}
489
+ .ta-badge-dot{width:6px;height:6px;flex:none;border-radius:50%;background:currentColor}
490
+ .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))}
491
+ .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))}
492
+ .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))}
493
+ .ta-badge--business{color:var(--dsw-alias-state-business-primary,inherit);border-color:var(--dsw-alias-border-l2,transparent)}
494
+ .ta-badge--idle{color:var(--dsw-alias-label-tertiary,inherit);border-color:var(--dsw-alias-border-l2,transparent)}
495
+ .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}
496
+
497
+ /* 按钮 */
498
+ .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}
499
+ .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)}
500
+ .ta-btn:active:not(:disabled){transform:none}
501
+ .ta-btn:disabled{opacity:.5;cursor:not-allowed}
502
+ .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))}
503
+ .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)}
504
+ .ta-btn--ghost{background:transparent;border-color:transparent;color:var(--dsw-alias-label-secondary,inherit);font-weight:500}
505
+ .ta-btn--ghost:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2,transparent);border-color:transparent}
506
+ .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))}
507
+ .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}
508
+ .ta-actions{display:flex;align-items:center;gap:9px;flex-wrap:wrap;min-width:0}
509
+ .ta-actions-end{margin-left:auto}
510
+
511
+ /* notice */
512
+ .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}
513
+ .ta-notice-main{min-width:0;flex:1}
514
+ .ta-notice-title{display:block;margin-bottom:2px;font-size:12.5px;font-weight:650;color:var(--dsw-alias-label-primary,inherit)}
515
+ .ta-notice-text{color:var(--dsw-alias-label-secondary,inherit);overflow-wrap:anywhere}
516
+ .ta-notice-action{flex:none}
517
+ .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)}
518
+ .ta-notice--success .ta-notice-title{color:var(--dsw-alias-state-success-primary,inherit)}
519
+ .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)}
520
+ .ta-notice--warn .ta-notice-title{color:var(--dsw-alias-state-warn-primary,inherit)}
521
+ .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)}
522
+ .ta-notice--error .ta-notice-title{color:var(--dsw-alias-state-error-primary,inherit)}
523
+ .ta-notice--info{border-color:var(--dsw-alias-border-l2,transparent)}
524
+
525
+ /* 文字 */
526
+ .ta-text{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,inherit)}
527
+ .ta-hint{margin:0;font-size:11px;line-height:1.55;color:var(--dsw-alias-label-tertiary,inherit)}
528
+ .ta-muted{font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-tertiary,inherit)}
529
+ .ta-subtitle{margin:0;font-size:13px;font-weight:650;line-height:1.4}
530
+ .ta-ok-text{color:var(--dsw-alias-state-success-primary,inherit);font-size:11.5px}
531
+ .ta-warn-text{color:var(--dsw-alias-state-warn-primary,inherit);font-size:11.5px}
532
+ .ta-error-text{color:var(--dsw-alias-state-error-primary,inherit);font-size:11.5px}
533
+ .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}
534
+ .ta-callout strong{display:block;margin-bottom:3px;color:var(--dsw-alias-label-primary,inherit);font-size:12px}
535
+ .ta-callout .ta-hint{overflow-wrap:anywhere}
536
+
537
+ /* 表单 */
538
+ .ta-field{display:grid;gap:6px;min-width:0}
539
+ .ta-label{font-size:12.5px;font-weight:600;color:var(--dsw-alias-label-primary,inherit)}
540
+ .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}
541
+ .ta-input:focus,.ta-textarea:focus{border-color:var(--dsw-alias-brand-primary,var(--dsw-alias-border-l2,transparent))}
542
+ .ta-input:disabled,.ta-textarea:disabled{opacity:.6;cursor:not-allowed}
543
+ .ta-input::placeholder,.ta-textarea::placeholder{color:var(--dsw-alias-label-quaternary,var(--dsw-alias-label-tertiary,inherit))}
544
+ .ta-input--number{max-width:150px}
545
+ .ta-textarea{min-height:120px;resize:vertical;line-height:1.55}
546
+ .ta-textarea--tall{min-height:200px}
547
+ .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}
548
+ .ta-counter-warn{color:var(--dsw-alias-state-warn-primary,inherit)}
549
+ .ta-counter-error{color:var(--dsw-alias-state-error-primary,inherit)}
550
+ .ta-check{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:start;gap:9px;padding:8px 0;cursor:pointer}
551
+ .ta-check input[type="checkbox"]{width:15px;height:15px;margin:3px 0 0;accent-color:var(--dsw-alias-brand-primary,currentColor)}
552
+ .ta-check-copy{display:grid;gap:2px;min-width:0}
553
+ .ta-check-title{font-size:12.5px;font-weight:600}
554
+ .ta-check-hint{font-size:11px;line-height:1.55;color:var(--dsw-alias-label-tertiary,inherit)}
555
+
556
+ /* toggle */
557
+ .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)}
558
+ .ta-toggle-row:last-child{border-bottom:0}
559
+ .ta-toggle-copy{display:grid;gap:2px;min-width:0}
560
+ .ta-toggle-label{font-size:12.5px;font-weight:550}
561
+ .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}
562
+ .ta-toggle:disabled{opacity:.55;cursor:not-allowed}
563
+ .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}
564
+ .ta-toggle.is-on{background:var(--dsw-alias-brand-primary,transparent);border-color:var(--dsw-alias-brand-primary,transparent)}
565
+ .ta-toggle.is-on .ta-toggle-knob{transform:translateX(17px);background:var(--dsw-alias-brand-text,var(--dsw-alias-label-primary-foreground,currentColor))}
566
+
567
+ /* facts / 统计 */
568
+ .ta-facts{display:grid;gap:8px;margin:0;min-width:0}
569
+ .ta-fact{display:grid;grid-template-columns:82px minmax(0,1fr);gap:10px;align-items:baseline;min-width:0}
570
+ .ta-fact-label{margin:0;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
571
+ .ta-fact-value{margin:0;font-size:12px;line-height:1.55;overflow-wrap:anywhere}
572
+ .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)}
573
+ .ta-status-line{display:flex;align-items:center;gap:9px;flex-wrap:wrap;font-size:12px;min-width:0}
574
+ .ta-usage-bar{display:grid;gap:6px;min-width:0}
575
+ .ta-usage-bar-head{display:flex;align-items:baseline;justify-content:space-between;gap:10px;font-size:12px}
576
+ .ta-bar{height:5px;border-radius:999px;background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,transparent));overflow:hidden}
577
+ .ta-bar-fill{height:100%;border-radius:999px;background:var(--dsw-alias-brand-primary,currentColor)}
578
+ .ta-bar-fill.is-over{background:var(--dsw-alias-state-warn-primary,currentColor)}
579
+
580
+ /* 折叠“TA 的家” */
581
+ .ta-fold{display:grid;gap:0;min-width:0}
582
+ .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}
583
+ .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)}
584
+ .ta-fold-icon{display:grid;place-items:center;width:16px;height:16px;flex:none;color:var(--dsw-alias-label-tertiary,inherit)}
585
+ .ta-fold-path{flex:1 1 180px;min-width:0;font-size:12.5px;overflow-wrap:anywhere}
586
+ .ta-status-path{display:inline-flex;align-items:flex-start;gap:5px;min-width:0;max-width:100%;color:inherit}
587
+ .ta-status-path > svg{flex:none;margin-top:2px;color:var(--dsw-alias-label-tertiary,inherit)}
588
+ .ta-status-path > span{min-width:0;overflow-wrap:anywhere}
589
+ .ta-fold-action{margin-left:auto;font-size:12px;color:var(--dsw-alias-brand-text,var(--dsw-alias-brand-primary,inherit))}
590
+ .ta-fold-chevron{font-size:10px;color:var(--dsw-alias-label-tertiary,inherit)}
591
+ .ta-fold-body{display:grid;gap:12px;margin-top:12px;animation:ta-rise-in .28s cubic-bezier(.22,1,.36,1) both}
592
+ .ta-lifecycle{display:grid;gap:10px;padding-top:2px}
593
+ .ta-lifecycle + .ta-lifecycle{padding-top:12px;border-top:1px solid var(--dsw-alias-border-l2,transparent)}
594
+ .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)}
595
+
596
+ /* 人设 */
597
+ .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)}
598
+ .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)}
599
+ .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}
600
+
601
+ /* IM 账号 */
602
+ .ta-accounts{list-style:none;margin:0;padding:0;display:grid;gap:8px;min-width:0}
603
+ .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)}
604
+ .ta-account-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px}
605
+ .ta-reasons{margin:0;padding-left:16px;font-size:11px;line-height:1.6;color:var(--dsw-alias-state-warn-primary,inherit)}
606
+
607
+ /* 花销卡 */
608
+ .ta-usage-top{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap}
609
+ .ta-usage-money{font-size:18px;font-weight:700;line-height:1.2}
610
+ .ta-usage-meta{font-size:11px;color:var(--dsw-alias-label-tertiary,inherit)}
611
+ .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)}
612
+ .ta-link{color:inherit;text-decoration:underline}
613
+ .ta-link--danger{background:none;border:0;padding:0;font:inherit;cursor:pointer;color:var(--dsw-alias-state-error-primary,inherit)}
614
+ .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)}
615
+ .ta-usage-rows{display:grid;gap:4px;margin-top:10px;font-size:11px;color:var(--dsw-alias-label-secondary,inherit)}
616
+ .ta-usage-row{display:flex;justify-content:space-between;gap:12px;min-width:0}
617
+
618
+ /* 窄屏 */
619
+ @container (max-width:760px){
620
+ .ta-grid--2{grid-template-columns:1fr}
621
+ .ta-ready{grid-template-columns:1fr}
622
+ .ta-card{padding:15px;border-radius:14px}
623
+ .ta-h1{font-size:18px}
624
+ .ta-desc{font-size:12px}
625
+ .ta-tab{min-width:72px;padding:0 12px}
626
+ .ta-fact{grid-template-columns:74px minmax(0,1fr)}
627
+ }
628
+ @container (max-width:440px){
629
+ .ta-page{gap:11px}
630
+ .ta-card{padding:13px}
631
+ .ta-toggle-row{gap:10px}
632
+ .ta-notice{align-items:flex-start;flex-direction:column}
633
+ .ta-notice-action{align-self:flex-start}
634
+ }
635
+
636
+ /* 动效 */
637
+ @keyframes ta-fade-in{from{opacity:0}to{opacity:1}}
638
+ @keyframes ta-rise-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
639
+ @keyframes ta-spin{to{transform:rotate(360deg)}}
640
+ @media (prefers-reduced-motion:reduce){
641
+ .ta-root *,.ta-root *::before,.ta-root *::after{animation-duration:.01ms !important;animation-iteration-count:1 !important;transition-duration:.01ms !important}
642
+ }
643
+ `
644
+
645
+ /* ------------------------------------------------------------------ *
646
+ * 纯计算与文案
647
+ * ------------------------------------------------------------------ */
648
+
51
649
  function parseJurisdictions(text) {
52
- return String(text ?? '').split(/\r?\n/).map(item => item.trim()).filter(Boolean)
650
+ return String(text == null ? '' : text).split(/\r?\n/).map(item => item.trim()).filter(Boolean)
651
+ }
652
+
653
+ function isHttpUrl(value) {
654
+ try {
655
+ const url = new URL(String(value))
656
+ return url.protocol === 'http:' || url.protocol === 'https:'
657
+ } catch {
658
+ return false
659
+ }
660
+ }
661
+
662
+ function formatCheckedAt(value) {
663
+ if (!value) return ''
664
+ try {
665
+ const date = new Date(value)
666
+ if (Number.isNaN(date.getTime())) return ''
667
+ return date.toLocaleTimeString('zh-CN', { hour12: false })
668
+ } catch {
669
+ return ''
670
+ }
671
+ }
672
+
673
+ function describeReme(reme) {
674
+ if (!reme) return 'ReMe 状态未知'
675
+ if (reme.state === 'connected') return 'ReMe 已连接'
676
+ if (reme.state === 'error') return 'ReMe 异常'
677
+ return 'ReMe 未连接'
678
+ }
679
+
680
+ function describeRemeShort(reme) {
681
+ if (!reme) return '未检测'
682
+ if (reme.state === 'connected') return '已连接'
683
+ if (reme.state === 'error') return '异常'
684
+ if (reme.state === 'disconnected') return '未连接'
685
+ return '未检测'
53
686
  }
54
687
 
688
+ function remeTone(reme) {
689
+ if (!reme) return 'idle'
690
+ if (reme.state === 'connected') return 'success'
691
+ if (reme.state === 'error') return 'error'
692
+ return 'warn'
693
+ }
694
+
695
+ function imCompatible(im) {
696
+ if (!im) return false
697
+ if (Array.isArray(im.accounts) && im.accounts.some(account => account && account.compatible === true)) return true
698
+ return im.compatible === true
699
+ }
700
+
701
+ function describeIm(im) {
702
+ if (!im) return 'IM 状态未知'
703
+ if (im.installed === false) return 'IM 未安装'
704
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
705
+ if (imCompatible(im)) return 'IM 已连接'
706
+ if (accounts.length > 0) return 'IM 已连接但不匹配'
707
+ return 'IM 未连接'
708
+ }
709
+
710
+ function describeImShort(im) {
711
+ if (!im) return '未检测'
712
+ if (im.installed === false) return '未安装'
713
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
714
+ if (imCompatible(im)) return '已连接'
715
+ if (accounts.length > 0) return '不匹配'
716
+ return '未连接'
717
+ }
718
+
719
+ function imTone(im) {
720
+ if (!im) return 'idle'
721
+ if (im.installed === false) return 'idle'
722
+ if (imCompatible(im)) return 'success'
723
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
724
+ return accounts.length > 0 ? 'warn' : 'idle'
725
+ }
726
+
727
+ function describeRemeDetail(reme) {
728
+ if (!reme) return '尚未检测'
729
+ if (reme.state === 'connected') {
730
+ const checked = formatCheckedAt(reme.checkedAt)
731
+ return checked ? `已连接 · 检查于 ${checked}` : '已连接'
732
+ }
733
+ if (reme.state === 'error') {
734
+ const checked = formatCheckedAt(reme.checkedAt)
735
+ return `${reme.message || '健康检查失败'}${checked ? ` · 检查于 ${checked}` : ''}`
736
+ }
737
+ return reme.message || '未连接;TA 仍可聊天,但不会长期记住以前的事。'
738
+ }
739
+
740
+ function describeImSummary(im) {
741
+ if (!im) return '尚未检测'
742
+ if (im.installed === false) return '未安装 IM Connect'
743
+ if (imCompatible(im)) return '有兼容的私聊账号'
744
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
745
+ return accounts.length > 0 ? '检测到账号,但未全部符合条件' : '还没有 IM 会话'
746
+ }
747
+
748
+ /** 整体生命周期:未初始化 / 可用 / 降级可用 / 需要处理 / 转生中。 */
749
+ function overallStatus(status) {
750
+ const lifecycle = status && status.lifecycle
751
+ if (lifecycle === 'reincarnating') {
752
+ return { label: '转生中', tone: 'business', hint: '正在准备新的家;完成后会自动刷新。' }
753
+ }
754
+ if (!status || !status.initialized) {
755
+ return { label: '未初始化', tone: 'idle', hint: '先创建 TA 的家,再写 SOUL 和 USER。' }
756
+ }
757
+ const persona = status.persona || {}
758
+ const soulBudget = Number(persona.soulBudget) || DEFAULT_PERSONA_BUDGETS.soul
759
+ const userBudget = Number(persona.userBudget) || DEFAULT_PERSONA_BUDGETS.user
760
+ const overBudget = (Number(persona.soulChars) || 0) > soulBudget
761
+ || (Number(persona.userChars) || 0) > userBudget
762
+ const problems = []
763
+ if (status.writable === false) problems.push('TA 的家当前不可写')
764
+ if (overBudget) problems.push('人设超出预算,超出部分不会被注入')
765
+ if (problems.length > 0) {
766
+ return { label: '需要处理', tone: 'error', hint: `${problems.join(';')}。` }
767
+ }
768
+ const gaps = []
769
+ if (!status.reme || status.reme.state !== 'connected') gaps.push(describeReme(status.reme))
770
+ if (!imCompatible(status.im)) gaps.push(describeIm(status.im))
771
+ if (gaps.length > 0) {
772
+ return { label: '降级可用', tone: 'warn', hint: `${gaps.join(';')}。补上后体验更完整,不影响现在使用。` }
773
+ }
774
+ return { label: '可用', tone: 'success', hint: '本地档案、ReMe 和 IM 都正常。' }
775
+ }
776
+
777
+ function buildPersonaFieldPreview(field, text, budget) {
778
+ const title = field === 'soul' ? '# 你是谁' : '# 关于Ta'
779
+ const content = String(text == null ? '' : text).trim()
780
+ if (!content) return `${title}\n(空:实际不会注入这一节)`
781
+ if (content.length > budget) {
782
+ return `${title}\n${content.slice(0, budget)}\n…(超出预算的 ${content.length - budget} 字在注入时被截断)`
783
+ }
784
+ return `${title}\n${content}`
785
+ }
786
+
787
+ const IM_REASON_LABELS = {
788
+ CWD_MISMATCH: '工作目录不是这个家',
789
+ CWD_NOT_HOME: '工作目录不是这个家',
790
+ PRESET_MISMATCH: '代理预设不是 ta',
791
+ AGENT_PRESET_MISMATCH: '代理预设不是 ta',
792
+ GROUP_ACCESS_ENABLED: '群聊没有关闭',
793
+ GROUP_ACCESS: '群聊没有关闭',
794
+ PRIVATE_ACCESS_DENIED: '私聊没有放行',
795
+ PRIVATE_ACCESS: '私聊没有放行',
796
+ DISABLED: '账号已停用',
797
+ NOT_BOUND: '会话还没有绑定',
798
+ }
799
+
800
+ function imReasonText(reason) {
801
+ if (typeof reason !== 'string' || !reason.trim()) return ''
802
+ const key = reason.trim()
803
+ if (IM_REASON_LABELS[key]) return IM_REASON_LABELS[key]
804
+ return /^[A-Z][A-Z0-9_]*$/.test(key) ? `未满足条件:${key}` : key
805
+ }
806
+
807
+ function imAccountReasons(account, home) {
808
+ if (!account || typeof account !== 'object') return []
809
+ // Host 已经返回中文原因时直接展示,避免和本地推断重复。
810
+ if (Array.isArray(account.reasons)) {
811
+ const hostReasons = account.reasons.map(imReasonText).filter(Boolean)
812
+ if (hostReasons.length > 0) return hostReasons
813
+ }
814
+ const reasons = []
815
+ if (home && account.cwd && account.cwd !== home) reasons.push('工作目录不是 TA 的家')
816
+ if (account.agentPreset !== undefined && account.agentPreset !== 'ta') reasons.push('没有使用 ta 预设')
817
+ if (account.groupAccess !== undefined && account.groupAccess !== 'disabled') reasons.push('群聊权限没有关闭')
818
+ if (account.privateAccess !== undefined && account.privateAccess !== 'approved') reasons.push('私聊权限不是仅批准用户')
819
+ if (account.enabled === false) reasons.push('账号已停用')
820
+ return reasons
821
+ }
822
+
823
+ function imGuidance(im) {
824
+ if (!im) return '尚未检测到 IM Connect。'
825
+ const accounts = Array.isArray(im.accounts) ? im.accounts : []
826
+ if (im.installed === false) {
827
+ return '还没有安装 IM Connect。安装后,在 IM Connect 新建一个工作目录为 TA 的家、预设为 ta、只开放私聊的账号,就能在 IM 里找到 TA。'
828
+ }
829
+ if (imCompatible(im)) return '已经有一个兼容的私聊账号,可以在 IM 里直接找 TA。'
830
+ if (accounts.length === 0) {
831
+ return '还没有 IM 会话。在 IM Connect 新建一个工作目录为 TA 的家、预设为 ta、只开放私聊的账号。'
832
+ }
833
+ return '检测到账号,但还没有全部满足条件。下面列出了每项原因;可以在 IM Connect 里调整,或新建一个兼容账号。'
834
+ }
835
+
836
+ /* ------------------------------------------------------------------ *
837
+ * 插件
838
+ * ------------------------------------------------------------------ */
839
+
55
840
  return {
56
- inject: ['slots', 'uiWorkspace', 'workspaces', 'configForms'],
841
+ inject: ['slots', 'conversation', 'uiWorkspace', 'workspaces', 'configForms'],
57
842
  apply(ctx) {
58
843
  const uiWorkspace = ctx.uiWorkspace || ctx.get('uiWorkspace')
59
844
  const workspaces = ctx.workspaces || ctx.get('workspaces')
@@ -62,463 +847,1687 @@ window.__ModuleLoader__.load({
62
847
  function configuredHome() {
63
848
  try {
64
849
  const value = configForms?.get('dsh-ta')?.getSnapshot?.().value
65
- return typeof value?.taHome === 'string' && value.taHome ? value.taHome : DEFAULTS.taHome
850
+ return typeof value?.taHome === 'string' && value.taHome ? value.taHome : DEFAULT_HOME_PATH
66
851
  } catch {
67
- return DEFAULTS.taHome
852
+ return DEFAULT_HOME_PATH
68
853
  }
69
854
  }
70
855
 
71
- function TaEntry({ wide }) {
72
- const [busy, setBusy] = React.useState(false)
73
- const [error, setError] = React.useState('')
856
+ function workspaceItems() {
857
+ try {
858
+ const items = workspaces?.list?.getSnapshot?.().items
859
+ return Array.isArray(items) ? items : []
860
+ } catch {
861
+ return []
862
+ }
863
+ }
74
864
 
75
- async function openTa() {
76
- if (busy) return
77
- if (!uiWorkspace || !workspaces) {
78
- setError('会话服务未就绪')
79
- return
80
- }
81
- setBusy(true)
82
- setError('')
83
- try {
84
- const home = configuredHome()
85
- const suffix = home.replace(/^~\/?/, '').replace(/\/+$/, '')
86
- const workspace = workspaces?.list?.getSnapshot?.().items
87
- ?.find(item => item.path === home
88
- || (suffix && item.path?.endsWith(`/${suffix}`)))
89
- if (!workspace) {
90
- setError(`没有找到 ${home} 工作区`)
91
- return
92
- }
93
- await uiWorkspace.openWorkspace(workspace.workspaceId, undefined, { agentPreset: 'ta' })
94
- } catch (cause) {
95
- setError(cause instanceof Error ? cause.message : String(cause))
96
- } finally {
97
- setBusy(false)
98
- }
865
+ function findWorkspace(home) {
866
+ const target = String(home == null ? '' : home)
867
+ const suffix = target.replace(/^~\/?/, '').replace(/\/+$/, '')
868
+ return workspaceItems().find(item => item && (
869
+ item.path === target
870
+ || (suffix && typeof item.path === 'string' && item.path.endsWith(`/${suffix}`))
871
+ ))
872
+ }
873
+
874
+ async function openTaWorkspace(home) {
875
+ if (!uiWorkspace || !workspaces) throw new Error('会话服务未就绪')
876
+ const value = typeof home === 'string' && home.trim() ? home.trim() : configuredHome()
877
+ let workspace = findWorkspace(value)
878
+ // 新家可能还没有注册为 DSH 工作区;注册的是已有路径,不创建文件。
879
+ if (!workspace && typeof workspaces.create === 'function') {
880
+ workspace = await workspaces.create({ path: value })
99
881
  }
882
+ if (!workspace) throw new Error(`没有找到 ${value} 工作区,请先把它注册为工作区`)
883
+ const workspaceId = workspace.workspaceId ?? workspace.id
884
+ if (!workspaceId) throw new Error(`工作区 ${value} 缺少 id`)
885
+ await uiWorkspace.openWorkspace(workspaceId, undefined, { agentPreset: 'ta' })
886
+ return workspace
887
+ }
888
+
889
+ /* -------------------------------------------------------------- *
890
+ * 基础组件
891
+ * -------------------------------------------------------------- */
100
892
 
893
+ function ActionButton({ variant = 'secondary', busy = false, disabled = false, className, children, ...rest }) {
894
+ const blocked = Boolean(disabled || busy)
895
+ const classes = `ta-btn ta-btn--${variant}${className ? ` ${className}` : ''}`
101
896
  return h('button', {
102
897
  type: 'button',
103
- title: error || '去找Ta',
104
- 'aria-label': '去找Ta',
105
- disabled: busy,
106
- onClick: openTa,
107
- style: {
108
- display: 'inline-flex',
109
- alignItems: 'center',
110
- justifyContent: 'center',
111
- gap: 6,
112
- height: 30,
113
- width: wide ? 'auto' : 30,
114
- padding: wide ? '0 9px' : 0,
115
- border: '1px solid var(--dsw-alias-border-l2, var(--dsw-alias-border-l1, rgba(127,127,127,.28)))',
116
- borderRadius: 8,
117
- background: 'transparent',
118
- color: 'inherit',
119
- font: 'inherit',
120
- fontSize: 12,
121
- cursor: busy ? 'default' : 'pointer',
122
- opacity: busy ? 0.6 : 1,
123
- },
898
+ ...rest,
899
+ disabled: blocked,
900
+ 'aria-busy': busy || undefined,
901
+ className: classes,
124
902
  },
125
- h('span', { 'aria-hidden': true, style: { fontSize: 14, lineHeight: 1 } }, '✦'),
126
- wide ? h('span', null, error || '去找Ta') : null)
903
+ busy ? h('span', { className: 'ta-spinner', 'aria-hidden': true }) : null,
904
+ children)
127
905
  }
128
906
 
129
- function Field({ label, hint, children }) {
130
- return h('label', {
131
- style: { display: 'grid', gap: 5, marginBottom: 15 },
907
+ function Badge({ tone = 'idle', children }) {
908
+ return h('span', { className: `ta-badge ta-badge--${tone}` },
909
+ h('span', { className: 'ta-badge-dot', 'aria-hidden': true }),
910
+ children)
911
+ }
912
+
913
+ function Notice({ tone = 'info', title, action, children }) {
914
+ return h('div', {
915
+ className: `ta-notice ta-notice--${tone}`,
916
+ role: tone === 'error' ? 'alert' : 'status',
917
+ 'aria-live': tone === 'error' ? 'assertive' : 'polite',
132
918
  },
133
- h('span', { style: { fontSize: 13, fontWeight: 600 } }, label),
134
- children,
135
- hint ? h('span', {
136
- style: { fontSize: 11, lineHeight: 1.45, opacity: 0.62 },
137
- }, hint) : null)
919
+ h('div', { className: 'ta-notice-main' },
920
+ title ? h('strong', { className: 'ta-notice-title' }, title) : null,
921
+ h('div', { className: 'ta-notice-text' }, children)),
922
+ action ? h('div', { className: 'ta-notice-action' }, action) : null)
923
+ }
924
+
925
+ function Card({ title, description, badge, children, className }) {
926
+ const hasHead = Boolean(title || description || badge)
927
+ return h('section', { className: `ta-card${className ? ` ${className}` : ''}` },
928
+ hasHead
929
+ ? h('header', { className: 'ta-card-head' },
930
+ h('div', { className: 'ta-card-head-main' },
931
+ title ? h('h3', { className: 'ta-card-title' }, title) : null,
932
+ description ? h('p', { className: 'ta-card-desc' }, description) : null),
933
+ h('div', { className: 'ta-card-head-side' }, badge || null))
934
+ : null,
935
+ h('div', { className: 'ta-card-body' }, children))
936
+ }
937
+
938
+ function Field({ label, hint, children }) {
939
+ return h('label', { className: 'ta-field' },
940
+ h('span', { className: 'ta-label' }, label),
941
+ children,
942
+ hint ? h('span', { className: 'ta-hint' }, hint) : null)
138
943
  }
139
944
 
140
945
  function Toggle({ label, hint, checked, disabled, onChange }) {
141
- return h('label', {
142
- style: {
143
- display: 'flex',
144
- alignItems: 'flex-start',
145
- gap: 9,
146
- marginBottom: 12,
147
- cursor: disabled ? 'default' : 'pointer',
148
- opacity: disabled ? 0.55 : 1,
946
+ return h('div', { className: 'ta-toggle-row' },
947
+ h('div', { className: 'ta-toggle-copy' },
948
+ h('span', { className: 'ta-toggle-label' }, label),
949
+ hint ? h('span', { className: 'ta-hint' }, hint) : null),
950
+ h('button', {
951
+ type: 'button',
952
+ role: 'switch',
953
+ 'aria-checked': Boolean(checked),
954
+ 'aria-label': label,
955
+ disabled,
956
+ className: `ta-toggle${checked ? ' is-on' : ''}`,
957
+ onClick: () => onChange(!checked),
958
+ }, h('span', { className: 'ta-toggle-knob', 'aria-hidden': true })))
959
+ }
960
+
961
+ function Fact({ label, value }) {
962
+ return h('div', { className: 'ta-fact' },
963
+ h('dt', { className: 'ta-fact-label' }, label),
964
+ h('dd', { className: 'ta-fact-value' }, value))
965
+ }
966
+
967
+ function PageHeader({ overline, title, description }) {
968
+ return h('header', { className: 'ta-page-head' },
969
+ overline ? h('span', { className: 'ta-overline' }, overline) : null,
970
+ h('h2', { className: 'ta-h1' }, title),
971
+ description ? h('p', { className: 'ta-desc' }, description) : null)
972
+ }
973
+
974
+ function SegmentedTabs({ items, value, onChange, label }) {
975
+ return h('div', { className: 'ta-tabs', role: 'tablist', 'aria-label': label },
976
+ items.map(item => h('button', {
977
+ key: item.value,
978
+ type: 'button',
979
+ role: 'tab',
980
+ id: item.id,
981
+ 'aria-selected': item.value === value,
982
+ 'aria-controls': item.panelId,
983
+ className: `ta-tab${item.value === value ? ' is-active' : ''}`,
984
+ onClick: () => onChange(item.value),
985
+ }, item.label)))
986
+ }
987
+
988
+ function Panel({ id, labelledBy, active, children }) {
989
+ return h('div', {
990
+ id,
991
+ role: 'tabpanel',
992
+ 'aria-labelledby': labelledBy,
993
+ className: 'ta-panel',
994
+ hidden: !active,
995
+ }, children)
996
+ }
997
+
998
+ function LoadPlaceholder({ overline, title, description, state, onRetry }) {
999
+ const unavailable = state && state.phase === 'unavailable'
1000
+ const loading = !state || state.phase === 'loading'
1001
+ return h('div', { className: 'ta-page' },
1002
+ h(PageHeader, { overline, title, description }),
1003
+ h(Card, null,
1004
+ loading
1005
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取 TA 的状态…')
1006
+ : h(Notice, {
1007
+ tone: unavailable ? 'warn' : 'error',
1008
+ title: unavailable ? '设置接口不可用' : '状态读取失败',
1009
+ action: h(ActionButton, { onClick: onRetry }, '重试'),
1010
+ }, unavailable
1011
+ ? 'Host 端可能还是旧版本,或 dsh-ta 没有挂载设置路由。升级并重启 DSH 后刷新页面。'
1012
+ : `${(state && state.error) || '网络异常'}。请检查网络或 Host 服务后重试。`)))
1013
+ }
1014
+
1015
+ /* -------------------------------------------------------------- *
1016
+ * 配置页 · 服务就绪条
1017
+ * -------------------------------------------------------------- */
1018
+
1019
+ function ReadyStrip({ status, reme, im }) {
1020
+ const hasHome = Boolean(status && (status.existing || status.initialized))
1021
+ const items = [
1022
+ {
1023
+ key: 'home',
1024
+ label: '本地档案',
1025
+ tone: hasHome ? 'success' : 'idle',
1026
+ value: hasHome ? '已创建' : '未创建',
1027
+ detail: (status && status.home) || DEFAULT_HOME_PATH,
1028
+ },
1029
+ {
1030
+ key: 'reme',
1031
+ label: '长期记忆 ReMe',
1032
+ tone: remeTone(reme),
1033
+ value: describeRemeShort(reme),
1034
+ detail: (reme && reme.endpoint) || '地址未配置',
1035
+ },
1036
+ {
1037
+ key: 'im',
1038
+ label: 'IM',
1039
+ tone: imTone(im),
1040
+ value: describeImShort(im),
1041
+ detail: describeImSummary(im),
1042
+ },
1043
+ ]
1044
+ return h('div', { className: 'ta-ready', role: 'list', 'aria-label': '服务就绪情况' },
1045
+ items.map(item => h('div', {
1046
+ key: item.key,
1047
+ role: 'listitem',
1048
+ className: `ta-ready-item is-${item.tone}`,
149
1049
  },
1050
+ h('span', { className: 'ta-dot', 'aria-hidden': true }),
1051
+ h('div', { className: 'ta-ready-text' },
1052
+ h('span', { className: 'ta-ready-label' }, item.label),
1053
+ h('span', { className: 'ta-ready-value' }, item.value),
1054
+ h('span', { className: 'ta-ready-detail', title: item.detail }, item.detail)))))
1055
+ }
1056
+
1057
+ /* -------------------------------------------------------------- *
1058
+ * 配置页 · 长期记忆(ReMe)
1059
+ * -------------------------------------------------------------- */
1060
+
1061
+ function RemeCard({ reme, config, refreshConnections, alive }) {
1062
+ const [testing, setTesting] = React.useState(false)
1063
+ const testingRef = React.useRef(false)
1064
+ const draft = config.draft
1065
+ const endpoint = draft ? String(draft.remeEndpoint == null ? '' : draft.remeEndpoint) : ''
1066
+ const baselineEndpoint = config.baseline ? String(config.baseline.remeEndpoint == null ? '' : config.baseline.remeEndpoint) : ''
1067
+ const dirty = Boolean(draft) && endpoint.trim() !== baselineEndpoint
1068
+ const ready = config.phase === 'ready' && Boolean(draft)
1069
+ const disabled = config.saving
1070
+
1071
+ async function testConnection() {
1072
+ if (testingRef.current) return
1073
+ testingRef.current = true
1074
+ setTesting(true)
1075
+ try {
1076
+ await refreshConnections()
1077
+ } finally {
1078
+ testingRef.current = false
1079
+ if (alive.current) setTesting(false)
1080
+ }
1081
+ }
1082
+
1083
+ async function saveEndpoint() {
1084
+ if (config.saving || !ready) return
1085
+ const value = endpoint.trim()
1086
+ if (!isHttpUrl(value)) {
1087
+ config.showError('ReMe 地址必须是 http(s) URL,例如 http://127.0.0.1:2333。')
1088
+ return
1089
+ }
1090
+ const target = { ...(config.draft || {}), remeEndpoint: value }
1091
+ const saved = await config.save({ fields: ['remeEndpoint'], target, successMessage: 'ReMe 地址已保存。' })
1092
+ if (saved) await refreshConnections()
1093
+ }
1094
+
1095
+ return h(Card, {
1096
+ title: '长期记忆 · ReMe',
1097
+ description: 'ReMe 是独立的长期记忆服务;TA 的家只保存本地文件。',
1098
+ badge: h(Badge, { tone: remeTone(reme) }, describeRemeShort(reme)),
150
1099
  },
151
- h('input', {
152
- type: 'checkbox',
153
- checked: Boolean(checked),
154
- disabled,
155
- onChange: event => onChange(event.target.checked),
156
- style: { marginTop: 2, accentColor: 'var(--dsw-alias-brand-primary, #4d6bfe)' },
157
- }),
158
- h('span', null,
159
- h('span', { style: { display: 'block', fontSize: 13, fontWeight: 600 } }, label),
160
- hint ? h('span', {
161
- style: { display: 'block', marginTop: 2, fontSize: 11, lineHeight: 1.45, opacity: 0.62 },
162
- }, hint) : null))
1100
+ h('p', { className: 'ta-text' },
1101
+ reme && reme.state === 'connected'
1102
+ ? 'ReMe 已连接:TA 会从现在开始把对话写入长期记忆。'
1103
+ : '不接 ReMe 也能正常聊天,但 TA 不会长期记住以前的事。接入后从接入时开始捕获,不会自动回填旧对话。'),
1104
+ config.phase === 'unavailable'
1105
+ ? h(Notice, {
1106
+ tone: 'warn',
1107
+ action: h(ActionButton, { onClick: config.reload }, '重新读取'),
1108
+ }, config.message || '配置服务不可用,暂时不能修改 ReMe 地址。')
1109
+ : null,
1110
+ config.phase === 'loading'
1111
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取 ReMe 地址…')
1112
+ : null,
1113
+ ready
1114
+ ? h(Field, { label: 'ReMe 地址', hint: '默认 http://127.0.0.1:2333;只建议本机回环地址。' },
1115
+ h('input', {
1116
+ className: 'ta-input',
1117
+ type: 'url',
1118
+ value: endpoint,
1119
+ placeholder: 'http://127.0.0.1:2333',
1120
+ disabled,
1121
+ onChange: event => config.update('remeEndpoint', event.target.value),
1122
+ onKeyDown: event => {
1123
+ if (event.key === 'Enter') {
1124
+ event.preventDefault()
1125
+ void saveEndpoint()
1126
+ }
1127
+ },
1128
+ }))
1129
+ : null,
1130
+ ready
1131
+ ? h('div', { className: 'ta-actions' },
1132
+ h(ActionButton, {
1133
+ variant: 'primary',
1134
+ disabled: !dirty || disabled,
1135
+ busy: disabled,
1136
+ onClick: saveEndpoint,
1137
+ }, disabled ? '保存中…' : '保存地址'),
1138
+ h(ActionButton, { disabled: testing || disabled, busy: testing, onClick: testConnection }, testing ? '检测中…' : '测试连接'),
1139
+ dirty ? h('span', { className: 'ta-muted' }, '地址有未保存修改') : null)
1140
+ : null,
1141
+ config.error ? h(Notice, { tone: 'error' }, config.error) : null,
1142
+ config.message
1143
+ ? h(Notice, { tone: config.message.indexOf('已保存') !== -1 ? 'success' : 'info' }, config.message)
1144
+ : null,
1145
+ h('dl', { className: 'ta-facts' },
1146
+ h(Fact, { label: '当前地址', value: (reme && reme.endpoint) || (ready && endpoint) || '未配置' }),
1147
+ h(Fact, { label: '检测结果', value: describeRemeDetail(reme) })),
1148
+ reme && reme.message ? h('p', { className: 'ta-hint' }, reme.message) : null,
1149
+ h('div', { className: 'ta-callout' },
1150
+ h('strong', null, '重置长期记忆'),
1151
+ h('p', { className: 'ta-hint' },
1152
+ '设置页不提供清空按钮,也不会删除 ReMe 数据。要重置记忆,请在你自己的 ReMe 部署里操作:停止 ReMe 服务 → 备份或删除 workspace → 重启 ReMe。远程部署请到对应服务器操作。')))
163
1153
  }
164
1154
 
165
- function Section({ title, children }) {
166
- return h('section', {
167
- style: {
168
- padding: '15px 16px 2px',
169
- marginBottom: 14,
170
- border: '1px solid var(--dsw-alias-border-l2, var(--dsw-alias-border-l1, rgba(127,127,127,.2)))',
171
- borderRadius: 10,
172
- background: 'var(--dsw-alias-bg-layer-1, rgba(127,127,127,.035))',
173
- },
1155
+ /* -------------------------------------------------------------- *
1156
+ * 配置页 · IM 连接
1157
+ * -------------------------------------------------------------- */
1158
+
1159
+ function ImCard({ status, im, integrationsState, refreshConnections, alive }) {
1160
+ const [testing, setTesting] = React.useState(false)
1161
+ const testingRef = React.useRef(false)
1162
+ const accounts = im && Array.isArray(im.accounts) ? im.accounts : []
1163
+ const home = status && status.home
1164
+
1165
+ async function testConnection() {
1166
+ if (testingRef.current) return
1167
+ testingRef.current = true
1168
+ setTesting(true)
1169
+ try {
1170
+ await refreshConnections()
1171
+ } finally {
1172
+ testingRef.current = false
1173
+ if (alive.current) setTesting(false)
1174
+ }
1175
+ }
1176
+
1177
+ return h(Card, {
1178
+ title: 'IM 连接',
1179
+ description: '在飞书等 IM 里找到 TA;设置页只做只读检测,不会修改 IM 配置。',
1180
+ badge: h(Badge, { tone: imTone(im) }, describeImShort(im)),
174
1181
  },
175
- h('h3', {
176
- style: { margin: '0 0 13px', fontSize: 13, letterSpacing: '.02em', opacity: 0.82 },
177
- }, title),
178
- children)
1182
+ h('p', { className: 'ta-text' }, imGuidance(im)),
1183
+ h('div', { className: 'ta-callout' },
1184
+ h('strong', null, '新建账号时这样填'),
1185
+ h('p', { className: 'ta-hint' },
1186
+ '在 IM Connect 新建一个会话:工作目录(cwd)= 这个 TA 的家,代理预设(agentPreset)= ta,只允许私聊。设置页不会修改 IM Connect 的配置,旧会话也不会被追溯成 TA。'),
1187
+ home ? h('p', { className: 'ta-hint' }, `当前 TA 的家:${home}`) : null),
1188
+ accounts.length > 0
1189
+ ? h('ul', { className: 'ta-accounts' },
1190
+ accounts.map((account, index) => h('li', {
1191
+ key: (account && account.id) || index,
1192
+ className: 'ta-account',
1193
+ },
1194
+ h('div', { className: 'ta-account-head' },
1195
+ h('strong', null, (account && account.name) || '未命名账号'),
1196
+ account && account.platform ? h('span', { className: 'ta-muted' }, account.platform) : null,
1197
+ h('span', { className: account && account.compatible ? 'ta-ok-text' : 'ta-warn-text' },
1198
+ account && account.compatible ? '兼容' : '不兼容')),
1199
+ account && !account.compatible
1200
+ ? h('ul', { className: 'ta-reasons' },
1201
+ imAccountReasons(account, home).map((reason, reasonIndex) => h('li', { key: reasonIndex }, reason)))
1202
+ : null,
1203
+ account && account.cwd ? h('p', { className: 'ta-hint' }, `工作目录:${account.cwd}`) : null)))
1204
+ : h('p', { className: 'ta-hint' },
1205
+ im && im.installed === false ? '没有安装 IM Connect。' : '还没有可用的 IM 会话。'),
1206
+ integrationsState && integrationsState.error
1207
+ ? h('p', { className: 'ta-hint' }, `上次检测失败:${integrationsState.error}`)
1208
+ : null,
1209
+ h('div', { className: 'ta-actions' },
1210
+ h(ActionButton, { disabled: testing, busy: testing, onClick: testConnection }, testing ? '检测中…' : '重新检测')))
179
1211
  }
180
1212
 
181
- function TaSettings() {
182
- const [form, setForm] = React.useState(null)
183
- const [draft, setDraft] = React.useState({ ...DEFAULTS })
184
- const [baseline, setBaseline] = React.useState({ ...DEFAULTS })
185
- const [jurisdictionText, setJurisdictionText] = React.useState(DEFAULTS.jurisdictions.join('\n'))
186
- const [state, setState] = React.useState('loading')
187
- const [message, setMessage] = React.useState('')
188
- const saving = React.useRef(false)
189
- const editing = React.useRef(false)
1213
+ /* -------------------------------------------------------------- *
1214
+ * 配置页 · TA 的家(折叠:初始化 / 转生)
1215
+ * -------------------------------------------------------------- */
190
1216
 
191
- React.useEffect(() => {
192
- if (!configForms) {
193
- setState('unavailable')
194
- setMessage('配置服务不可用')
195
- return undefined
1217
+ function HomeInitPanel({ call, alive, blocked, onBusyChange, onDone }) {
1218
+ const [homePath, setHomePath] = React.useState(DEFAULT_HOME_PATH)
1219
+ const [creating, setCreating] = React.useState(false)
1220
+ const [error, setError] = React.useState('')
1221
+ const [adoptPending, setAdoptPending] = React.useState('')
1222
+ const creatingRef = React.useRef(false)
1223
+
1224
+ async function createHome(confirmAdopt) {
1225
+ if (creatingRef.current || blocked) return
1226
+ const path = String(homePath || '').trim()
1227
+ if (!path) {
1228
+ setError('请填写 TA 家的路径')
1229
+ return
196
1230
  }
197
- let bound
198
- let ready = false
199
- const timeout = setTimeout(() => {
200
- if (!ready) {
201
- setState('unavailable')
202
- setMessage('读取配置超时,请刷新页面重试')
203
- }
204
- }, 10000)
1231
+ creatingRef.current = true
1232
+ setCreating(true)
1233
+ setError('')
1234
+ if (typeof onBusyChange === 'function') onBusyChange(true)
205
1235
  try {
206
- bound = configForms.get('dsh-ta')
207
- setForm(bound)
1236
+ const body = { path }
1237
+ if (confirmAdopt) body.confirmAdopt = true
1238
+ const result = await call('/home/init', { method: 'POST', body, timeoutMs: 30000 })
1239
+ if (!alive.current) return
1240
+ setAdoptPending('')
1241
+ if (typeof onDone === 'function') onDone(result)
208
1242
  } catch (cause) {
209
- ready = true
210
- setState('unavailable')
211
- setMessage(cause instanceof Error ? cause.message : String(cause))
212
- return undefined
213
- }
214
- const read = () => {
215
- const snapshot = bound.getSnapshot()
216
- if (snapshot.status === 'unavailable') {
217
- ready = true
218
- setState('unavailable')
219
- setMessage('当前 profile 没有提供 dsh-ta 配置')
220
- return
1243
+ if (alive.current && !(cause && cause.cancelled)) {
1244
+ if (cause && cause.code === 'ADOPT_CONFIRM_REQUIRED') {
1245
+ setAdoptPending(path)
1246
+ setError('')
1247
+ } else {
1248
+ setError(errorMessage(cause))
1249
+ }
221
1250
  }
222
- if (snapshot.status === 'loading' && !snapshot.value) return
223
- if (snapshot.value && !saving.current && !editing.current) {
224
- const next = { ...DEFAULTS, ...snapshot.value }
225
- setDraft(next)
226
- setBaseline(next)
227
- setJurisdictionText((next.jurisdictions ?? DEFAULTS.jurisdictions).join('\n'))
228
- ready = true
229
- setState('ready')
1251
+ } finally {
1252
+ creatingRef.current = false
1253
+ if (alive.current) setCreating(false)
1254
+ if (typeof onBusyChange === 'function') onBusyChange(false)
1255
+ }
1256
+ }
1257
+
1258
+ return h('div', { className: 'ta-lifecycle' },
1259
+ h('h4', { className: 'ta-subtitle' }, '创建 TA 的家'),
1260
+ h('p', { className: 'ta-text' },
1261
+ '第一次创建会写入初始模板和目录;已有文件不会被覆盖。创建后路径锁定,之后只能通过转生更换。'),
1262
+ h(Field, {
1263
+ label: '家的位置',
1264
+ hint: `默认 ${DEFAULT_HOME_PATH}。可以输入绝对路径或 ~ 开头的路径。`,
1265
+ },
1266
+ h('input', {
1267
+ className: 'ta-input',
1268
+ value: homePath,
1269
+ placeholder: DEFAULT_HOME_PATH,
1270
+ disabled: creating || blocked,
1271
+ onChange: event => {
1272
+ setHomePath(event.target.value)
1273
+ setError('')
1274
+ setAdoptPending('')
1275
+ },
1276
+ })),
1277
+ h('div', { className: 'ta-actions' },
1278
+ h(ActionButton, {
1279
+ variant: 'primary',
1280
+ busy: creating,
1281
+ disabled: blocked,
1282
+ onClick: () => createHome(false),
1283
+ }, creating ? '正在创建…' : '创建 TA 的家')),
1284
+ adoptPending
1285
+ ? h(Notice, {
1286
+ tone: 'warn',
1287
+ action: h(ActionButton, {
1288
+ variant: 'primary',
1289
+ busy: creating,
1290
+ onClick: () => createHome(true),
1291
+ }, creating ? '接管中…' : '确认接管'),
1292
+ }, '这个目录里已经有内容。继续只会补写 .ta-home、缺失的模板和目录,不会覆盖已有文件;确认后才创建。')
1293
+ : null,
1294
+ error ? h(Notice, { tone: 'error' }, error) : null)
1295
+ }
1296
+
1297
+ function ReincarnatePanel({ status, call, alive, blocked, personaDirty, onBusyChange, onDone }) {
1298
+ const [newHome, setNewHome] = React.useState('')
1299
+ const [reincarnateWord, setReincarnateWord] = React.useState('')
1300
+ const [deleteOldHome, setDeleteOldHome] = React.useState(false)
1301
+ const [deleteWord, setDeleteWord] = React.useState('')
1302
+ const [busy, setBusy] = React.useState(false)
1303
+ const [error, setError] = React.useState('')
1304
+ const busyRef = React.useRef(false)
1305
+
1306
+ const lifecycleBusy = Boolean(status && status.lifecycle === 'reincarnating')
1307
+ const disabled = busy || lifecycleBusy || blocked
1308
+ const deleteReady = !deleteOldHome || deleteWord.trim() === '删除旧家'
1309
+ const canSubmit = String(newHome).trim().length > 0
1310
+ && reincarnateWord.trim() === '转生'
1311
+ && deleteReady
1312
+ && !disabled
1313
+ && !personaDirty
1314
+
1315
+ async function run() {
1316
+ if (busyRef.current || disabled) return
1317
+ if (personaDirty) {
1318
+ setError('人设有未保存的修改:请先在「人设」页保存或撤销,再转生。')
1319
+ return
1320
+ }
1321
+ if (!String(newHome).trim()) {
1322
+ setError('请填写新家的路径')
1323
+ return
1324
+ }
1325
+ if (reincarnateWord.trim() !== '转生') {
1326
+ setError('请输入“转生”两个字确认')
1327
+ return
1328
+ }
1329
+ if (deleteOldHome && deleteWord.trim() !== '删除旧家') {
1330
+ setError('要删除旧家,请输入“删除旧家”确认')
1331
+ return
1332
+ }
1333
+ busyRef.current = true
1334
+ setBusy(true)
1335
+ setError('')
1336
+ if (typeof onBusyChange === 'function') onBusyChange(true)
1337
+ try {
1338
+ const body = { newHome: String(newHome).trim(), confirm: '转生', deleteOldHome }
1339
+ if (deleteOldHome) body.deleteConfirm = '删除旧家'
1340
+ const result = await call('/lifecycle/reincarnate', {
1341
+ method: 'POST',
1342
+ body,
1343
+ timeoutMs: 120000,
1344
+ })
1345
+ if (!alive.current) return
1346
+ busyRef.current = false
1347
+ setBusy(false)
1348
+ if (typeof onDone === 'function') onDone(result)
1349
+ } catch (cause) {
1350
+ if (alive.current) {
1351
+ if (!(cause && cause.cancelled)) setError(errorMessage(cause))
1352
+ busyRef.current = false
1353
+ setBusy(false)
230
1354
  }
1355
+ } finally {
1356
+ if (typeof onBusyChange === 'function') onBusyChange(false)
231
1357
  }
232
- read()
233
- const unsubscribe = bound.subscribe(read)
234
- return () => {
235
- clearTimeout(timeout)
236
- unsubscribe()
1358
+ }
1359
+
1360
+ return h('div', { className: 'ta-lifecycle' },
1361
+ h('h4', { className: 'ta-subtitle' }, '转生到新家'),
1362
+ h('p', { className: 'ta-text' },
1363
+ '转生会换一个全新的空家;ReMe 长期记忆保留,旧 DSH 会话和旧 IM 聊天记录不受影响。'),
1364
+ h('p', { className: 'ta-hint' },
1365
+ '旧家的人设、日记、笔记、表情包和待发送记忆默认保留;勾选后才会随转生一起删除。'),
1366
+ busy || lifecycleBusy
1367
+ ? h(Notice, { tone: 'info' },
1368
+ deleteOldHome
1369
+ ? '正在创建新家、切换运行期并删除旧家;请保持页面打开。'
1370
+ : '正在创建新家并切换运行期;旧家会保留。')
1371
+ : null,
1372
+ personaDirty
1373
+ ? h(Notice, { tone: 'warn' }, '人设有未保存的修改。请先在「人设」页保存或撤销,再转生。')
1374
+ : null,
1375
+ h(Field, {
1376
+ label: '新家的路径',
1377
+ hint: '必须是空目录或尚不存在的路径;不能是旧家,也不能在旧家内部。',
1378
+ },
1379
+ h('input', {
1380
+ className: 'ta-input',
1381
+ value: newHome,
1382
+ placeholder: '~/TATA/home-2',
1383
+ disabled,
1384
+ onChange: event => {
1385
+ setNewHome(event.target.value)
1386
+ setError('')
1387
+ },
1388
+ })),
1389
+ h('label', { className: 'ta-check' },
1390
+ h('input', {
1391
+ type: 'checkbox',
1392
+ checked: deleteOldHome,
1393
+ disabled,
1394
+ onChange: event => {
1395
+ setDeleteOldHome(event.target.checked)
1396
+ setDeleteWord('')
1397
+ setError('')
1398
+ },
1399
+ }),
1400
+ h('span', { className: 'ta-check-copy' },
1401
+ h('span', { className: 'ta-check-title' }, '同时删除旧家(本地档案)'),
1402
+ h('span', { className: 'ta-check-hint' },
1403
+ '会删除旧家的人设、日记、笔记、认识、出门记录、本地表情包、待发送记忆和插件状态。不可恢复,默认不勾选。'))),
1404
+ deleteOldHome
1405
+ ? h('div', { className: 'ta-danger-box' },
1406
+ h(Notice, { tone: 'warn' },
1407
+ `删除旧家:${(status && status.home) || '(未知路径)'}。ReMe 长期记忆、旧 DSH 会话和旧 IM 聊天记录不会删除。`),
1408
+ h(Field, { label: '输入“删除旧家”确认' },
1409
+ h('input', {
1410
+ className: 'ta-input',
1411
+ value: deleteWord,
1412
+ placeholder: '删除旧家',
1413
+ disabled,
1414
+ onChange: event => {
1415
+ setDeleteWord(event.target.value)
1416
+ setError('')
1417
+ },
1418
+ })))
1419
+ : null,
1420
+ h(Field, { label: '输入“转生”确认' },
1421
+ h('input', {
1422
+ className: 'ta-input',
1423
+ value: reincarnateWord,
1424
+ placeholder: '转生',
1425
+ disabled,
1426
+ onChange: event => {
1427
+ setReincarnateWord(event.target.value)
1428
+ setError('')
1429
+ },
1430
+ })),
1431
+ h('div', { className: 'ta-actions' },
1432
+ h(ActionButton, {
1433
+ variant: 'primary',
1434
+ disabled: !canSubmit,
1435
+ busy,
1436
+ onClick: run,
1437
+ }, busy ? '正在转生…' : '转生到新家')),
1438
+ error ? h(Notice, { tone: 'error' }, error) : null)
1439
+ }
1440
+
1441
+ function HomeCard({ status, call, alive, refreshAll, blocked, personaDirty, onBusyChange }) {
1442
+ const [open, setOpen] = React.useState(false)
1443
+ const [warnings, setWarnings] = React.useState([])
1444
+ const [notice, setNotice] = React.useState('')
1445
+ const initialized = Boolean(status && status.initialized)
1446
+ const hasHome = Boolean(status && (status.existing || status.initialized))
1447
+ const homePath = (status && status.home) || DEFAULT_HOME_PATH
1448
+
1449
+ function handleDone(kind, result) {
1450
+ setOpen(false)
1451
+ const nextWarnings = result && Array.isArray(result.warnings) ? result.warnings.slice() : []
1452
+ if (kind === 'init') {
1453
+ if (result && result.adopted) nextWarnings.push('接管了已有目录;已有文件没有被覆盖')
1454
+ if (result && result.repairedMarker) nextWarnings.push('修复了损坏的 .ta-home 标记,旧文件已改名保留')
237
1455
  }
238
- }, [])
1456
+ setWarnings(nextWarnings)
1457
+ setNotice(kind === 'init'
1458
+ ? 'TA 的家已创建,可以从侧栏「去找Ta」进入;人设可以稍后在「人设」页继续完善。'
1459
+ : result && result.oldHomeDeleted
1460
+ ? '转生完成。新家已就绪,旧家已删除;ReMe 长期记忆保留。'
1461
+ : '转生完成。新家已就绪,旧家保留;ReMe 长期记忆保留。')
1462
+ refreshAll()
1463
+ }
1464
+
1465
+ return h(Card, {
1466
+ title: 'TA 的家 · 本地档案',
1467
+ description: '人格、日记和文件都保存在这里。路径一旦创建就锁定,换家只能走转生;长期记忆在 ReMe,不在这里。',
1468
+ badge: h(Badge, { tone: initialized ? 'success' : 'idle' },
1469
+ initialized ? '已初始化' : hasHome ? '待填写人设' : '未初始化'),
1470
+ },
1471
+ h('button', {
1472
+ type: 'button',
1473
+ className: 'ta-fold-head',
1474
+ 'aria-expanded': open,
1475
+ onClick: () => setOpen(value => !value),
1476
+ },
1477
+ h('span', { className: 'ta-fold-icon', 'aria-hidden': true }, h(LockIcon, { size: 14 })),
1478
+ h('span', { className: 'ta-fold-path' }, homePath),
1479
+ h('span', { className: 'ta-muted' }, hasHome ? '已初始化' : '未初始化'),
1480
+ h('span', { className: 'ta-fold-action' }, open ? '收起' : '展开'),
1481
+ h('span', { className: 'ta-fold-chevron', 'aria-hidden': true }, open ? '▴' : '▾')),
1482
+ open
1483
+ ? h('div', { className: 'ta-fold-body' },
1484
+ !hasHome
1485
+ ? h(HomeInitPanel, {
1486
+ call,
1487
+ alive,
1488
+ blocked,
1489
+ onBusyChange,
1490
+ onDone: result => handleDone('init', result),
1491
+ })
1492
+ : null,
1493
+ hasHome && !initialized
1494
+ ? h(Notice, { tone: 'info' },
1495
+ 'TA 的家已经创建,可以去侧栏「去找Ta」;SOUL 或 USER 还是空的,可以稍后在「人设」页完善。')
1496
+ : null,
1497
+ initialized
1498
+ ? h(ReincarnatePanel, {
1499
+ status,
1500
+ call,
1501
+ alive,
1502
+ blocked,
1503
+ personaDirty,
1504
+ onBusyChange,
1505
+ onDone: result => handleDone('reincarnate', result),
1506
+ })
1507
+ : null)
1508
+ : null,
1509
+ warnings.length > 0
1510
+ ? h(Notice, { tone: 'warn' }, `请留意:${warnings.join(';')}`)
1511
+ : null,
1512
+ notice ? h(Notice, { tone: 'success' }, notice) : null)
1513
+ }
239
1514
 
240
- const update = (field, value) => {
241
- if (saving.current) return
242
- editing.current = true
243
- setDraft(previous => ({ ...previous, [field]: value }))
244
- setMessage('')
245
- setState(previous => previous === 'error' ? 'ready' : previous)
1515
+ /* -------------------------------------------------------------- *
1516
+ * 配置页
1517
+ * -------------------------------------------------------------- */
1518
+
1519
+ function ConfigPage({
1520
+ status, statusState, integrations, integrationsState,
1521
+ call, alive, refreshAll, refreshConnections,
1522
+ config, blocked, personaDirty, onBusyChange, onRetryStatus,
1523
+ }) {
1524
+ if (!status) {
1525
+ return h(LoadPlaceholder, {
1526
+ overline: 'CONFIG',
1527
+ title: '配置',
1528
+ description: 'TA 的本地档案、长期记忆和 IM 连接。',
1529
+ state: statusState,
1530
+ onRetry: onRetryStatus,
1531
+ })
246
1532
  }
1533
+ const reme = (integrations && integrations.reme) || status.reme || null
1534
+ const im = (integrations && integrations.im) || status.im || null
1535
+ return h('div', { className: 'ta-page' },
1536
+ h(PageHeader, {
1537
+ overline: 'CONFIG',
1538
+ title: '配置',
1539
+ description: '本地档案保存 TA 的人格和文件,长期记忆保存在 ReMe。ReMe 和 IM 都可以稍后再接,不影响聊天。',
1540
+ }),
1541
+ h(HomeCard, {
1542
+ status,
1543
+ call,
1544
+ alive,
1545
+ refreshAll,
1546
+ blocked,
1547
+ personaDirty,
1548
+ onBusyChange,
1549
+ }),
1550
+ h('div', { className: 'ta-grid ta-grid--2' },
1551
+ h(RemeCard, { reme, config, refreshConnections, alive }),
1552
+ h(ImCard, { status, im, integrationsState, refreshConnections, alive })),
1553
+ h(ReadyStrip, { status, reme, im }))
1554
+ }
247
1555
 
248
- const save = async () => {
249
- if (!form || saving.current) return
250
- const target = {
251
- ...draft,
252
- jurisdictions: parseJurisdictions(jurisdictionText),
253
- }
254
- target.taHome = String(target.taHome ?? '').trim()
255
- if (!target.taHome) {
256
- setState('error')
257
- setMessage('Ta 的家目录不能为空')
1556
+ /* -------------------------------------------------------------- *
1557
+ * 人设页
1558
+ * -------------------------------------------------------------- */
1559
+
1560
+ function PersonaFieldCard({
1561
+ field, title, description, budget, status, resource, reload, call, alive,
1562
+ blocked, hasHome, onDirtyChange, onSaved,
1563
+ }) {
1564
+ const data = resource.data
1565
+ const version = resource.version || 0
1566
+ const [draft, setDraft] = React.useState('')
1567
+ const [baseline, setBaseline] = React.useState({ content: '', revision: '' })
1568
+ const [hydrated, setHydrated] = React.useState(false)
1569
+ const [previewOpen, setPreviewOpen] = React.useState(false)
1570
+ const [saving, setSaving] = React.useState(false)
1571
+ const [saveError, setSaveError] = React.useState('')
1572
+ const [conflict, setConflict] = React.useState(false)
1573
+ const [notice, setNotice] = React.useState('')
1574
+ const [warnings, setWarnings] = React.useState([])
1575
+ const [budgetFromSave, setBudgetFromSave] = React.useState(null)
1576
+ const savingRef = React.useRef(false)
1577
+ const syncedRef = React.useRef(-1)
1578
+ const forceReloadRef = React.useRef(false)
1579
+ const draftRef = React.useRef('')
1580
+ const baselineRef = React.useRef({ content: '', revision: '' })
1581
+ draftRef.current = draft
1582
+ baselineRef.current = baseline
1583
+
1584
+ const fileName = field === 'soul' ? 'SOUL.md' : 'USER.md'
1585
+ const revisionKey = field === 'soul' ? 'soulRevision' : 'userRevision'
1586
+ const effectiveBudget = Number(budgetFromSave) || Number(budget) || DEFAULT_PERSONA_BUDGETS[field]
1587
+ const dirty = Boolean(data) && hydrated && draft !== baseline.content
1588
+ const loading = !data && resource.phase === 'loading'
1589
+ const failed = !data && (resource.phase === 'error' || resource.phase === 'unavailable')
1590
+ const disabled = !hasHome || !data || saving || !hydrated || blocked
1591
+ const overBudget = draft.length > effectiveBudget
1592
+ const overMax = draft.length > PERSONA_MAX_CHARS
1593
+
1594
+ React.useEffect(() => {
1595
+ if (typeof onDirtyChange === 'function') onDirtyChange(field, dirty)
1596
+ }, [dirty, field, onDirtyChange])
1597
+
1598
+ React.useEffect(() => {
1599
+ if (!data) return
1600
+ if (syncedRef.current === version) return
1601
+ const dirtyNow = hydrated && draftRef.current !== baselineRef.current.content
1602
+ if (dirtyNow && !forceReloadRef.current) {
1603
+ // 另一个编辑器或外部刷新:不要覆盖当前草稿。
1604
+ syncedRef.current = version
258
1605
  return
259
1606
  }
260
- if (target.taHome === '/' || target.taHome === '~') {
261
- setState('error')
262
- setMessage('Ta 的家目录不能是 / 或 ~')
1607
+ const content = typeof data[field] === 'string' ? data[field] : ''
1608
+ const revision = String(data[revisionKey] || '')
1609
+ setDraft(content)
1610
+ setBaseline({ content, revision })
1611
+ setHydrated(true)
1612
+ setPreviewOpen(false)
1613
+ setSaveError('')
1614
+ setConflict(false)
1615
+ setNotice('')
1616
+ setWarnings([])
1617
+ syncedRef.current = version
1618
+ forceReloadRef.current = false
1619
+ }, [data, version, field, revisionKey, hydrated])
1620
+
1621
+ function update(value) {
1622
+ if (savingRef.current) return
1623
+ setDraft(value)
1624
+ setPreviewOpen(false)
1625
+ setSaveError('')
1626
+ setConflict(false)
1627
+ setNotice('')
1628
+ setWarnings([])
1629
+ }
1630
+
1631
+ function reloadPersona() {
1632
+ if (savingRef.current) return
1633
+ forceReloadRef.current = true
1634
+ setSaveError('')
1635
+ setConflict(false)
1636
+ setPreviewOpen(false)
1637
+ setNotice('')
1638
+ setWarnings([])
1639
+ void reload()
1640
+ }
1641
+
1642
+ function resetDraft() {
1643
+ if (savingRef.current) return
1644
+ setDraft(baseline.content)
1645
+ setPreviewOpen(false)
1646
+ setSaveError('')
1647
+ setConflict(false)
1648
+ setNotice('')
1649
+ setWarnings([])
1650
+ }
1651
+
1652
+ async function save() {
1653
+ if (!hasHome || !data || savingRef.current || blocked) return
1654
+ if (overMax) {
1655
+ setSaveError(`${fileName} 最多 ${PERSONA_MAX_CHARS} 字(当前 ${draft.length} 字),保存会被拒绝。`)
263
1656
  return
264
1657
  }
1658
+ const submittedContent = draft
1659
+ const submittedRevision = baseline.revision
1660
+ savingRef.current = true
1661
+ setSaving(true)
1662
+ setSaveError('')
1663
+ setConflict(false)
1664
+ setNotice('')
1665
+ setWarnings([])
1666
+ try {
1667
+ const saved = await call('/persona', {
1668
+ method: 'PUT',
1669
+ body: { field, content: submittedContent, revision: submittedRevision },
1670
+ })
1671
+ if (!alive.current) return
1672
+ const nextRevision = saved && typeof saved.revision === 'string' && saved.revision
1673
+ ? saved.revision
1674
+ : submittedRevision
1675
+ setBaseline({ content: submittedContent, revision: nextRevision })
1676
+ if (saved && saved.budgets && saved.budgets[field] != null) {
1677
+ const nextBudget = Number(saved.budgets[field])
1678
+ if (nextBudget > 0) setBudgetFromSave(nextBudget)
1679
+ }
1680
+ const nextWarnings = saved && Array.isArray(saved.warnings) ? saved.warnings : []
1681
+ setWarnings(nextWarnings)
1682
+ setPreviewOpen(false)
1683
+ setNotice(nextWarnings.length > 0
1684
+ ? '已保存;请留意上方预算提示。'
1685
+ : '已保存。之后开始的会话会使用更新后的内容。')
1686
+ if (typeof onSaved === 'function') onSaved(field)
1687
+ } catch (cause) {
1688
+ if (!alive.current || (cause && cause.cancelled)) return
1689
+ if ((cause && cause.status === 409) || (cause && cause.code === 'PERSONA_CONFLICT')) {
1690
+ setConflict(true)
1691
+ } else {
1692
+ setSaveError(errorMessage(cause))
1693
+ }
1694
+ } finally {
1695
+ savingRef.current = false
1696
+ if (alive.current) setSaving(false)
1697
+ }
1698
+ }
1699
+
1700
+ const placeholder = !hasHome
1701
+ ? '先创建 TA 的家'
1702
+ : loading
1703
+ ? '正在读取人设…'
1704
+ : !hydrated
1705
+ ? '正在载入人设…'
1706
+ : failed
1707
+ ? '人设读取失败,重新加载后编辑'
1708
+ : ''
1709
+
1710
+ return h(Card, {
1711
+ title,
1712
+ description,
1713
+ badge: h('span', { className: 'ta-file-badge' }, fileName),
1714
+ },
1715
+ !hasHome ? h(Notice, { tone: 'info' }, '先创建 TA 的家,之后才能编辑人设。') : null,
1716
+ data && resource.error
1717
+ ? h(Notice, {
1718
+ tone: 'warn',
1719
+ action: h(ActionButton, { onClick: reloadPersona }, '重新加载'),
1720
+ }, `人设刷新失败:${resource.error}(显示的是上次读取的内容)`)
1721
+ : null,
1722
+ failed
1723
+ ? h(Notice, {
1724
+ tone: resource.phase === 'unavailable' ? 'warn' : 'error',
1725
+ action: h(ActionButton, { onClick: reloadPersona }, '重新加载'),
1726
+ }, `${resource.phase === 'unavailable' ? '人设接口不可用' : '人设读取失败'}:${resource.error || '请重试。'}`)
1727
+ : null,
1728
+ loading
1729
+ ? h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取…')
1730
+ : null,
1731
+ h('textarea', {
1732
+ className: 'ta-textarea ta-textarea--tall',
1733
+ rows: 10,
1734
+ value: draft,
1735
+ placeholder,
1736
+ disabled,
1737
+ 'aria-label': `${title}(${fileName})`,
1738
+ onChange: event => update(event.target.value),
1739
+ }),
1740
+ h('div', { className: 'ta-counter' },
1741
+ h('span', { className: overBudget ? 'ta-counter-warn' : 'ta-muted' }, `${draft.length} / ${effectiveBudget} 字`),
1742
+ overBudget
1743
+ ? h('span', { className: 'ta-counter-warn' },
1744
+ `超出预算 ${draft.length - effectiveBudget} 字,实际注入时只使用前 ${effectiveBudget} 字`)
1745
+ : null,
1746
+ !draft.length && data && hasHome
1747
+ ? h('span', { className: 'ta-muted' }, '尚未填写(可选)')
1748
+ : null,
1749
+ overMax
1750
+ ? h('span', { className: 'ta-counter-error' }, `超过 ${PERSONA_MAX_CHARS} 字上限,无法保存`)
1751
+ : null,
1752
+ dirty ? h('span', { className: 'ta-counter-warn' }, '有未保存修改') : null),
1753
+ h('div', { className: 'ta-actions' },
1754
+ h(ActionButton, {
1755
+ variant: 'primary',
1756
+ disabled: !dirty || disabled,
1757
+ busy: saving,
1758
+ onClick: save,
1759
+ }, saving ? '保存中…' : `保存 ${fileName}`),
1760
+ h(ActionButton, {
1761
+ disabled: !data || saving,
1762
+ onClick: () => setPreviewOpen(value => !value),
1763
+ }, previewOpen ? '收起预览' : '预览'),
1764
+ h(ActionButton, {
1765
+ variant: 'ghost',
1766
+ disabled: !dirty || saving,
1767
+ onClick: resetDraft,
1768
+ }, '撤销修改'),
1769
+ h('span', { className: 'ta-muted ta-actions-end' },
1770
+ saving ? '保存中…' : dirty ? '有未保存修改' : hydrated ? '已保存' : '')),
1771
+ blocked
1772
+ ? h(Notice, { tone: 'info' }, 'TA 正在转生中,人设暂时不能保存;操作完成后会自动恢复。')
1773
+ : null,
1774
+ previewOpen
1775
+ ? h('div', { className: 'ta-preview-box' },
1776
+ h('h4', { className: 'ta-subtitle' }, '保存后实际注入内容'),
1777
+ h('p', { className: 'ta-hint' }, `按注入顺序预览这一个字段。预算 ${effectiveBudget} 字;超出预算的部分不会注入。`),
1778
+ h('pre', { className: 'ta-preview' }, buildPersonaFieldPreview(field, draft, effectiveBudget)),
1779
+ h('div', { className: 'ta-actions' },
1780
+ h(ActionButton, {
1781
+ variant: 'primary',
1782
+ busy: saving,
1783
+ disabled,
1784
+ onClick: save,
1785
+ }, saving ? '保存中…' : `保存 ${fileName}`),
1786
+ h(ActionButton, { disabled: saving, onClick: () => setPreviewOpen(false) }, '返回修改')))
1787
+ : null,
1788
+ conflict
1789
+ ? h(Notice, {
1790
+ tone: 'error',
1791
+ action: h(ActionButton, { onClick: reloadPersona }, '重新加载'),
1792
+ }, '这个文件已被其他会话修改。请先重新加载,再保存;当前草稿已保留。')
1793
+ : null,
1794
+ saveError ? h(Notice, { tone: 'error' }, saveError) : null,
1795
+ warnings.length > 0
1796
+ ? h(Notice, { tone: 'warn' }, `预算提示:${warnings.join(';')}`)
1797
+ : null,
1798
+ notice ? h(Notice, { tone: 'success' }, notice) : null)
1799
+ }
1800
+
1801
+ function PersonaPage({
1802
+ status, statusState, resource, reload, call, alive, blocked, onDirtyChange, onSaved, onRetryStatus,
1803
+ }) {
1804
+ if (!status) {
1805
+ return h(LoadPlaceholder, {
1806
+ overline: 'PERSONA',
1807
+ title: '人设',
1808
+ description: 'TA 是谁和关于你,分开编辑、分别保存。',
1809
+ state: statusState,
1810
+ onRetry: onRetryStatus,
1811
+ })
1812
+ }
1813
+ const hasHome = Boolean(status.existing || status.initialized)
1814
+ const data = resource.data
1815
+ const personaStatus = status.persona || {}
1816
+ const budgets = {
1817
+ soul: Number(data && data.budgets && data.budgets.soul)
1818
+ || Number(personaStatus.soulBudget)
1819
+ || DEFAULT_PERSONA_BUDGETS.soul,
1820
+ user: Number(data && data.budgets && data.budgets.user)
1821
+ || Number(personaStatus.userBudget)
1822
+ || DEFAULT_PERSONA_BUDGETS.user,
1823
+ }
1824
+ return h('div', { className: 'ta-page' },
1825
+ h(PageHeader, {
1826
+ overline: 'PERSONA',
1827
+ title: '人设',
1828
+ description: 'TA 是谁(SOUL)和关于你(USER)分开编辑、分别保存;保存一个不会影响另一个。',
1829
+ }),
1830
+ h('div', { className: 'ta-grid ta-grid--2' },
1831
+ h(PersonaFieldCard, {
1832
+ field: 'soul',
1833
+ title: 'TA 是谁',
1834
+ description: 'SOUL.md:TA 的人格底色、在意的事和说话方式。',
1835
+ budget: budgets.soul,
1836
+ status,
1837
+ resource,
1838
+ reload,
1839
+ call,
1840
+ alive,
1841
+ blocked,
1842
+ hasHome,
1843
+ onDirtyChange,
1844
+ onSaved,
1845
+ }),
1846
+ h(PersonaFieldCard, {
1847
+ field: 'user',
1848
+ title: '关于你',
1849
+ description: 'USER.md:关于你的事,TA 会一直记得。',
1850
+ budget: budgets.user,
1851
+ status,
1852
+ resource,
1853
+ reload,
1854
+ call,
1855
+ alive,
1856
+ blocked,
1857
+ hasHome,
1858
+ onDirtyChange,
1859
+ onSaved,
1860
+ })))
1861
+ }
1862
+
1863
+ /* -------------------------------------------------------------- *
1864
+ * 状态页(只读统计 + 花销清零)
1865
+ * -------------------------------------------------------------- */
1866
+
1867
+ function UsageBar({ label, value, budget }) {
1868
+ const percent = budget > 0 ? Math.min(100, Math.round((value / budget) * 100)) : 0
1869
+ const over = value > budget
1870
+ return h('div', { className: 'ta-usage-bar' },
1871
+ h('div', { className: 'ta-usage-bar-head' },
1872
+ h('span', { className: 'ta-label' }, label),
1873
+ h('span', { className: over ? 'ta-counter-warn' : 'ta-muted' }, `${value} / ${budget} 字`)),
1874
+ h('div', {
1875
+ className: 'ta-bar',
1876
+ role: 'progressbar',
1877
+ 'aria-label': `${label} 字数`,
1878
+ 'aria-valuenow': value,
1879
+ 'aria-valuemin': 0,
1880
+ 'aria-valuemax': budget,
1881
+ }, h('div', {
1882
+ className: `ta-bar-fill${over ? ' is-over' : ''}`,
1883
+ style: { width: `${percent}%` },
1884
+ })),
1885
+ over ? h('span', { className: 'ta-counter-warn' }, '超出预算的部分不会注入') : null)
1886
+ }
1887
+
1888
+ function StatusPage({ status, statusState, integrations, onRetry }) {
1889
+ if (!status) {
1890
+ return h(LoadPlaceholder, {
1891
+ overline: 'STATUS',
1892
+ title: '状态',
1893
+ description: 'TA 的只读运行状态。',
1894
+ state: statusState,
1895
+ onRetry,
1896
+ })
1897
+ }
1898
+ const overall = overallStatus(status)
1899
+ const persona = status.persona || {}
1900
+ const generated = status.generated || {}
1901
+ const reme = (integrations && integrations.reme) || status.reme || null
1902
+ const im = (integrations && integrations.im) || status.im || null
1903
+ const soulChars = Number(persona.soulChars) || 0
1904
+ const userChars = Number(persona.userChars) || 0
1905
+ const soulBudget = Number(persona.soulBudget) || DEFAULT_PERSONA_BUDGETS.soul
1906
+ const userBudget = Number(persona.userBudget) || DEFAULT_PERSONA_BUDGETS.user
1907
+ const diaryCount = Number(generated.diaryCount) || 0
1908
+ const hasHome = Boolean(status.existing || status.initialized)
1909
+
1910
+ return h('div', { className: 'ta-page' },
1911
+ h(PageHeader, {
1912
+ overline: 'STATUS',
1913
+ title: '状态',
1914
+ description: '生命周期、本地档案、人设、生成物和连接情况;除花销清零外,这里不改动任何内容。',
1915
+ }),
1916
+ h(UsageCard, null),
1917
+ h('div', { className: 'ta-status-hero' },
1918
+ h(Badge, { tone: overall.tone }, overall.label),
1919
+ h('span', { className: 'ta-muted' }, overall.hint)),
1920
+ h('div', { className: 'ta-grid ta-grid--2' },
1921
+ h(Card, { title: '本地档案', description: 'TA 的人格、日记和本地文件。' },
1922
+ h('dl', { className: 'ta-facts' },
1923
+ h(Fact, {
1924
+ label: '路径',
1925
+ value: hasHome && status.home
1926
+ ? h('span', { className: 'ta-status-path' },
1927
+ h(LockIcon, { size: 12 }),
1928
+ h('span', null, status.home))
1929
+ : '尚未创建',
1930
+ }),
1931
+ h(Fact, { label: '生命周期', value: status.lifecycle === 'reincarnating' ? '转生中' : status.initialized ? '已初始化' : hasHome ? '待填写人设' : '未初始化' }),
1932
+ h(Fact, { label: '可写', value: status.writable === false ? '不可写' : status.writable === true ? '可写' : '未知' }),
1933
+ h(Fact, { label: '标记', value: status.homeMarked === false ? '缺少 .ta-home(会自动补写)' : '正常' }))),
1934
+ h(Card, { title: '人设', description: 'SOUL.md 与 USER.md 的字数与预算。' },
1935
+ h(UsageBar, { label: 'SOUL', value: soulChars, budget: soulBudget }),
1936
+ h(UsageBar, { label: 'USER', value: userChars, budget: userBudget })),
1937
+ h(Card, { title: '生成物', description: '由夜间回顾自动生成,只读展示。' },
1938
+ h('dl', { className: 'ta-facts' },
1939
+ h(Fact, { label: 'MEMORY.md', value: generated.memory ? '已生成' : '尚未生成' }),
1940
+ h(Fact, { label: 'self/', value: generated.self ? '已生成' : '尚未生成' }),
1941
+ h(Fact, { label: '日记', value: `${diaryCount} 篇${generated.latestDiary ? ` · 最新 ${generated.latestDiary}` : ''}` }))),
1942
+ h(Card, { title: '连接', description: 'ReMe 和 IM 都是可选的。' },
1943
+ h('div', { className: 'ta-status-line' },
1944
+ h(Badge, { tone: remeTone(reme) }, describeRemeShort(reme)),
1945
+ h('span', { className: 'ta-muted' }, (reme && reme.endpoint) || '地址未配置')),
1946
+ h('div', { className: 'ta-status-line' },
1947
+ h(Badge, { tone: imTone(im) }, describeImShort(im)),
1948
+ h('span', { className: 'ta-muted' }, describeImSummary(im))),
1949
+ h('p', { className: 'ta-hint' }, 'ReMe 和 IM 不阻塞聊天。'))))
1950
+ }
1951
+
1952
+ /* -------------------------------------------------------------- *
1953
+ * 高级页(configForms)
1954
+ * -------------------------------------------------------------- */
1955
+
1956
+ function AdvancedPage({ config }) {
1957
+ const draft = config.draft
1958
+ const ready = config.phase === 'ready' && Boolean(draft)
1959
+ const saving = config.saving
1960
+ const jurisdictionArray = parseJurisdictions(config.jurisdictionText)
1961
+ const dirty = Boolean(draft && config.baseline) && (
1962
+ ADVANCED_FIELDS.some(name => JSON.stringify(draft[name]) !== JSON.stringify(config.baseline[name]))
1963
+ || JSON.stringify(jurisdictionArray) !== JSON.stringify(config.baseline.jurisdictions))
1964
+
1965
+ async function saveAdvanced() {
1966
+ if (!ready || saving) return
1967
+ const target = { ...draft, jurisdictions: jurisdictionArray }
265
1968
  if (target.jurisdictions.length === 0) {
266
- setState('error')
267
- setMessage('至少保留一个只读辖区')
1969
+ config.showError('至少保留一个只读辖区。')
268
1970
  return
269
1971
  }
270
1972
  if (target.jurisdictions.some(root => root === '/' || root === '~')) {
271
- setState('error')
272
- setMessage('辖区不能是 / 或 ~')
1973
+ config.showError('辖区不能是 / 或 ~。')
273
1974
  return
274
1975
  }
275
1976
  if (!Number.isInteger(target.captureInterval) || target.captureInterval < 1 || target.captureInterval > 60) {
276
- setState('error')
277
- setMessage('捕获间隔必须是 1–60 的整数')
1977
+ config.showError('捕获间隔必须是 1–60 的整数。')
278
1978
  return
279
1979
  }
280
- try {
281
- const endpoint = new URL(target.remeEndpoint)
282
- if (endpoint.protocol !== 'http:' && endpoint.protocol !== 'https:') throw new Error('协议')
283
- } catch {
284
- setState('error')
285
- setMessage('ReMe 地址必须是 http(s) URL')
1980
+ if (!Number.isInteger(target.stickerMinGapMinutes) || target.stickerMinGapMinutes < 0 || target.stickerMinGapMinutes > 1440) {
1981
+ config.showError('表情最小间隔必须是 0–1440 的整数(分钟)。')
1982
+ return
1983
+ }
1984
+ if (!Number.isInteger(target.stickerMaxPerDay) || target.stickerMaxPerDay < 1 || target.stickerMaxPerDay > 100) {
1985
+ config.showError('每日表情上限必须是 1–100 的整数。')
286
1986
  return
287
1987
  }
288
1988
  for (const clock of [target.heartbeatActiveStart, target.heartbeatActiveEnd, target.jurisdictionOutingTime]) {
289
- if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(clock)) {
290
- setState('error')
291
- setMessage(`时间格式应为 HH:MM,当前是 ${clock}`)
1989
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(String(clock))) {
1990
+ config.showError(`时间格式应为 HH:MM,当前是 ${clock}。`)
292
1991
  return
293
1992
  }
294
1993
  }
295
1994
  try {
296
1995
  new Intl.DateTimeFormat('en-US', { timeZone: target.timezone })
297
1996
  } catch {
298
- setState('error')
299
- setMessage(`无效时区:${target.timezone}`)
1997
+ config.showError(`无效时区:${target.timezone}。`)
300
1998
  return
301
1999
  }
2000
+ await config.save({ fields: ADVANCED_FIELDS, target, successMessage: '已保存。配置已即时生效。' })
2001
+ }
302
2002
 
303
- const snapshot = form.getSnapshot()
304
- if (snapshot.writable === false) {
305
- setState('error')
306
- setMessage('当前 profile 不允许写入配置')
307
- return
2003
+ function restoreDefaults() {
2004
+ if (!draft || saving) return
2005
+ const next = { ...draft }
2006
+ for (const name of ADVANCED_FIELDS) {
2007
+ next[name] = Array.isArray(ADVANCED_DEFAULTS[name])
2008
+ ? ADVANCED_DEFAULTS[name].slice()
2009
+ : ADVANCED_DEFAULTS[name]
308
2010
  }
309
- const changed = FIELD_KEYS.filter(field => JSON.stringify(target[field]) !== JSON.stringify(baseline[field]))
310
- if (changed.length === 0) {
311
- setState('ready')
312
- setMessage('没有修改')
313
- return
2011
+ config.replaceDraft(next)
2012
+ config.setJurisdictionText(ADVANCED_DEFAULTS.jurisdictions.join('\n'))
2013
+ config.showMessage('已填入默认值;点击「保存配置」后生效。')
2014
+ }
2015
+
2016
+ function textInput(name, placeholder) {
2017
+ return h('input', {
2018
+ className: 'ta-input',
2019
+ value: draft[name] == null ? '' : draft[name],
2020
+ placeholder,
2021
+ disabled: saving,
2022
+ onChange: event => config.update(name, event.target.value),
2023
+ })
2024
+ }
2025
+
2026
+ function numberInput(name, min, max) {
2027
+ return h('input', {
2028
+ className: 'ta-input ta-input--number',
2029
+ type: 'number',
2030
+ min,
2031
+ max,
2032
+ value: draft[name] == null ? '' : draft[name],
2033
+ disabled: saving,
2034
+ onChange: event => config.update(name, Number(event.target.value)),
2035
+ })
2036
+ }
2037
+
2038
+ return h('div', { className: 'ta-page' },
2039
+ h(PageHeader, {
2040
+ overline: 'ADVANCED',
2041
+ title: '高级',
2042
+ description: '通常不需要修改。这里的设置写入当前 profile,保存后即时生效;家路径和 ReMe 数据目录不在普通设置里。',
2043
+ }),
2044
+ config.phase === 'unavailable'
2045
+ ? h(Notice, {
2046
+ tone: 'warn',
2047
+ action: h(ActionButton, { onClick: config.reload }, '重新读取'),
2048
+ }, config.message || '配置服务不可用。')
2049
+ : null,
2050
+ config.phase === 'loading'
2051
+ ? h(Card, null, h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取配置…'))
2052
+ : null,
2053
+ ready
2054
+ ? h(React.Fragment, null,
2055
+ h(Card, { title: '对话捕获', description: '控制日常对话送入 ReMe 长期记忆的节奏。' },
2056
+ h(Toggle, {
2057
+ label: '启用对话捕获',
2058
+ hint: '关闭后不把日常对话送入长期记忆。',
2059
+ checked: Boolean(draft.captureEnabled),
2060
+ disabled: saving,
2061
+ onChange: value => config.update('captureEnabled', value),
2062
+ }),
2063
+ h(Field, { label: '每几轮封一批', hint: '1–60 的整数。' },
2064
+ numberInput('captureInterval', 1, 60))),
2065
+ h(Card, { title: '夜间回顾' },
2066
+ h(Toggle, {
2067
+ label: '22:30 ReMe 整理',
2068
+ checked: Boolean(draft.dreamEnabled),
2069
+ disabled: saving,
2070
+ onChange: value => config.update('dreamEnabled', value),
2071
+ }),
2072
+ h(Toggle, {
2073
+ label: '02:00 清理旧出门记录',
2074
+ checked: Boolean(draft.outingCleanupEnabled),
2075
+ disabled: saving,
2076
+ onChange: value => config.update('outingCleanupEnabled', value),
2077
+ }),
2078
+ h(Toggle, {
2079
+ label: '22:45 辖区人格化查看',
2080
+ hint: '由 TA 自己读当天文件和对话,写一份辖区出门记录,供回顾使用。',
2081
+ checked: Boolean(draft.jurisdictionOutingEnabled),
2082
+ disabled: saving,
2083
+ onChange: value => config.update('jurisdictionOutingEnabled', value),
2084
+ }),
2085
+ h(Field, { label: '辖区查看时间', hint: '24 小时制,例如 22:45。' },
2086
+ textInput('jurisdictionOutingTime', '22:45'))),
2087
+ h(Card, { title: '主动消息' },
2088
+ h(Toggle, {
2089
+ label: '启用心跳',
2090
+ hint: '默认关闭。开启后只在活跃时段、inbox 非空时创建 life 会话。',
2091
+ checked: Boolean(draft.heartbeatEnabled),
2092
+ disabled: saving,
2093
+ onChange: value => config.update('heartbeatEnabled', value),
2094
+ }),
2095
+ h(Field, { label: '活跃开始' }, textInput('heartbeatActiveStart', '08:00')),
2096
+ h(Field, { label: '活跃结束' }, textInput('heartbeatActiveEnd', '23:00'))),
2097
+ h(Card, { title: '只读辖区', description: 'TA 可以只读访问的目录。' },
2098
+ h(Field, { label: '辖区列表', hint: '每行一个根目录;不能填 / 或 ~。' },
2099
+ h('textarea', {
2100
+ className: 'ta-textarea',
2101
+ rows: 4,
2102
+ value: config.jurisdictionText,
2103
+ disabled: saving,
2104
+ onChange: event => config.setJurisdictionText(event.target.value),
2105
+ }))),
2106
+ h(Card, { title: '时区' },
2107
+ h(Field, { label: 'IANA 时区', hint: '例如 Asia/Shanghai。' },
2108
+ textInput('timezone', 'Asia/Shanghai'))),
2109
+ h(Card, { title: '表情频率' },
2110
+ h(Field, { label: '两次表情的最小间隔(分钟)', hint: '0–1440。' },
2111
+ numberInput('stickerMinGapMinutes', 0, 1440)),
2112
+ h(Field, { label: '每个会话每天最多几个表情', hint: '1–100。' },
2113
+ numberInput('stickerMaxPerDay', 1, 100))),
2114
+ h('div', { className: 'ta-actions' },
2115
+ h(ActionButton, {
2116
+ variant: 'primary',
2117
+ disabled: saving || !dirty,
2118
+ busy: saving,
2119
+ onClick: saveAdvanced,
2120
+ }, saving ? '保存中…' : '保存配置'),
2121
+ h(ActionButton, { disabled: saving || !dirty, onClick: config.resetAll }, '还原修改'),
2122
+ h(ActionButton, { variant: 'ghost', disabled: saving, onClick: restoreDefaults }, '恢复默认值'),
2123
+ h('span', {
2124
+ className: 'ta-muted ta-actions-end',
2125
+ role: 'status',
2126
+ 'aria-live': 'polite',
2127
+ }, config.message || (dirty ? '有未保存修改' : '已保存'))),
2128
+ config.error ? h(Notice, { tone: 'error' }, config.error) : null)
2129
+ : null)
2130
+ }
2131
+
2132
+ /* -------------------------------------------------------------- *
2133
+ * 花销卡
2134
+ * -------------------------------------------------------------- */
2135
+
2136
+ function UsageCard() {
2137
+ const [report, setReport] = React.useState(null)
2138
+ const [error, setError] = React.useState('')
2139
+ const [reloadKey, setReloadKey] = React.useState(0)
2140
+ const [resetOpen, setResetOpen] = React.useState(false)
2141
+ const [resetting, setResetting] = React.useState(false)
2142
+ const [resetError, setResetError] = React.useState('')
2143
+ const [resetNotice, setResetNotice] = React.useState('')
2144
+ React.useEffect(() => {
2145
+ let alive = true
2146
+ const controller = new AbortController()
2147
+ const timeout = setTimeout(() => controller.abort(), 8000)
2148
+ setError('')
2149
+ fetch('/api/dsh-ta/usage', { cache: 'no-store', signal: controller.signal })
2150
+ .then(response => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`)))
2151
+ .then(value => { if (alive) setReport(value) })
2152
+ .catch(cause => { if (alive) setError(cause instanceof Error ? cause.message : String(cause)) })
2153
+ .finally(() => clearTimeout(timeout))
2154
+ return () => {
2155
+ alive = false
2156
+ clearTimeout(timeout)
2157
+ controller.abort()
314
2158
  }
2159
+ }, [reloadKey])
315
2160
 
316
- saving.current = true
317
- setState('saving')
318
- setMessage('')
2161
+ async function clearUsage() {
2162
+ if (resetting) return
2163
+ setResetting(true)
2164
+ setResetError('')
319
2165
  try {
320
- const ops = changed.map(field => ({ op: 'set', path: [field], value: target[field] }))
321
- const accepted = await form.mutate(ops, snapshot.revision)
322
- if (!accepted) throw new Error('宿主拒绝了这次配置写入')
323
- editing.current = false
324
- setDraft(target)
325
- setBaseline(target)
326
- setJurisdictionText(target.jurisdictions.join('\n'))
327
- setState('ready')
328
- setMessage('已保存。配置已即时生效。')
2166
+ const response = await fetch('/api/dsh-ta/usage/reset', {
2167
+ method: 'POST',
2168
+ headers: { 'content-type': 'application/json' },
2169
+ body: JSON.stringify({ confirm: '清零' }),
2170
+ })
2171
+ let payload = null
2172
+ try { payload = await response.json() } catch { /* 非 JSON 错误按 HTTP 状态处理 */ }
2173
+ if (!response.ok || !payload || payload.ok !== true) {
2174
+ throw new Error(payload?.error?.message || `清零失败(HTTP ${response.status})`)
2175
+ }
2176
+ const count = Number(payload.data && payload.data.records) || 0
2177
+ setResetOpen(false)
2178
+ setResetNotice(count > 0
2179
+ ? `已清零 ${count} 条记录。之后的对话会重新累计。`
2180
+ : '花销已经清零。之后的对话会重新累计。')
2181
+ setReport(null)
2182
+ setReloadKey(value => value + 1)
329
2183
  } catch (cause) {
330
- setState('error')
331
- setMessage(cause instanceof Error ? cause.message : String(cause))
2184
+ setResetError(cause instanceof Error ? cause.message : String(cause))
332
2185
  } finally {
333
- saving.current = false
2186
+ setResetting(false)
334
2187
  }
335
2188
  }
336
2189
 
337
- const reset = () => {
338
- editing.current = false
339
- setDraft({ ...baseline })
340
- setJurisdictionText((baseline.jurisdictions ?? DEFAULTS.jurisdictions).join('\n'))
341
- setState('ready')
342
- setMessage('')
2190
+ if (error) {
2191
+ return h(Card, { title: '花销', description: 'DSH agent 估算;ReMe 自己的调用不在范围内。' },
2192
+ h(Notice, { tone: 'warn' }, `花销接口暂不可用:${error}`))
343
2193
  }
2194
+ if (!report) {
2195
+ return h(Card, { title: '花销', description: 'DSH agent 估算;ReMe 自己的调用不在范围内。' },
2196
+ h('p', { className: 'ta-muted', role: 'status', 'aria-busy': 'true' }, '正在读取花销…'))
2197
+ }
2198
+ const total = report.total || { tokens: {}, costCny: null }
2199
+ const noTurns = Number(total.turns) === 0
2200
+ const currency = report.currency === 'CNY' || report.currency == null ? '¥' : `${report.currency} `
2201
+ // 零记录显示 0;有记录但完全未定价时才是未知(—)。
2202
+ const money = value => value == null
2203
+ ? (noTurns ? `${currency}0.000` : '—')
2204
+ : `${currency}${Number(value).toFixed(3)}`
2205
+ const tokens = value => Number(value || 0).toLocaleString('zh-CN')
2206
+ const allTokens = (total.tokens.uncachedInput || 0)
2207
+ + (total.tokens.cacheRead || 0)
2208
+ + (total.tokens.cacheWrite || 0)
2209
+ + (total.tokens.output || 0)
2210
+ return h(Card, {
2211
+ title: '花销',
2212
+ description: 'DSH agent 估算;ReMe 自己的 LLM 调用、余额和充值不在统计范围内。',
2213
+ },
2214
+ h('div', { className: 'ta-usage-top' },
2215
+ h('span', { className: 'ta-usage-money' }, money(total.costCny)),
2216
+ h('span', { className: 'ta-usage-meta' },
2217
+ `${tokens(allTokens)} tokens · ${total.turns || 0} 轮${total.unpricedTurns ? ` · ${total.unpricedTurns} 轮未定价` : ''}`)),
2218
+ h('div', { className: 'ta-usage-links' },
2219
+ h('a', { href: '/api/dsh-ta/usage/export.csv', className: 'ta-link' }, '导出 CSV'),
2220
+ h('a', { href: '/api/dsh-ta/usage/export.json', className: 'ta-link' }, '导出 JSON'),
2221
+ h('button', {
2222
+ type: 'button',
2223
+ className: 'ta-link ta-link--danger',
2224
+ 'aria-expanded': resetOpen,
2225
+ onClick: () => {
2226
+ setResetOpen(value => !value)
2227
+ setResetError('')
2228
+ },
2229
+ }, resetOpen ? '收起' : '清零')),
2230
+ resetOpen
2231
+ ? h('div', { className: 'ta-usage-reset' },
2232
+ h(Notice, { tone: 'warn' },
2233
+ '只删除本地花销记录(state/usage/*.jsonl),不会删除 ReMe 记忆、聊天记录或配置。清零后不可恢复。'),
2234
+ h('div', { className: 'ta-actions' },
2235
+ h(ActionButton, {
2236
+ variant: 'danger',
2237
+ busy: resetting,
2238
+ onClick: clearUsage,
2239
+ }, resetting ? '正在清零…' : '确认清零'),
2240
+ h(ActionButton, {
2241
+ disabled: resetting,
2242
+ onClick: () => { setResetOpen(false); setResetError('') },
2243
+ }, '取消')),
2244
+ resetError ? h(Notice, { tone: 'error' }, resetError) : null)
2245
+ : null,
2246
+ resetNotice ? h(Notice, { tone: 'success' }, resetNotice) : null,
2247
+ h('div', { className: 'ta-usage-rows' },
2248
+ ...Object.entries(report.byCategory || {}).map(([name, value]) => h('div', {
2249
+ key: name,
2250
+ className: 'ta-usage-row',
2251
+ },
2252
+ h('span', null, name),
2253
+ h('span', null,
2254
+ `${money(value.costCny)} · ${tokens(Object.values(value.tokens || {}).reduce((a, b) => a + Number(b || 0), 0))} tok`)))))
2255
+ }
2256
+
2257
+ /* -------------------------------------------------------------- *
2258
+ * 表情 toolview
2259
+ * -------------------------------------------------------------- */
344
2260
 
345
- if (state === 'loading') {
346
- return h('div', { style: { padding: 24, fontSize: 13, opacity: 0.68 } }, '正在读取 Ta 配置…')
2261
+ function TaStickerCard({ block, phase }) {
2262
+ const text = Array.isArray(block?.content)
2263
+ ? block.content.find(part => part?.type === 'text')?.text
2264
+ : undefined
2265
+ let value
2266
+ try {
2267
+ const marker = typeof text === 'string' ? text.indexOf('STICKER:') : -1
2268
+ value = marker >= 0 ? JSON.parse(text.slice(marker + 'STICKER:'.length)) : undefined
2269
+ } catch {
2270
+ value = undefined
347
2271
  }
348
- if (state === 'unavailable' || !form) {
349
- return h('div', { style: { maxWidth: 760, padding: '8px 4px' } },
350
- h('h2', { style: { margin: '0 0 8px', fontSize: 18 } }, 'TA 的家'),
351
- h('p', { style: { margin: 0, fontSize: 13, lineHeight: 1.6, opacity: 0.68 } },
352
- message || '当前 profile 没有提供 dsh-ta 配置,无法编辑。'),
353
- h('p', { style: { margin: '12px 0 0', fontSize: 12, lineHeight: 1.55, opacity: 0.56 } },
354
- '请先在 profile 中启用 dsh-ta 配置,然后刷新设置页。'))
2272
+ if (phase === 'preparing' || phase === 'start') {
2273
+ return h('span', { style: { fontSize: 12, opacity: 0.65 } }, '正在准备表情…')
355
2274
  }
2275
+ if (block?.isError) {
2276
+ return h('span', {
2277
+ role: 'alert',
2278
+ style: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, inherit)' },
2279
+ }, block?.error?.message || '表情发送失败')
2280
+ }
2281
+ return h('span', { style: { fontSize: 12, opacity: 0.7 } },
2282
+ value?.text ? `表情已发送 · ${value.text}` : '表情已发送')
2283
+ }
356
2284
 
357
- const disabled = state === 'saving'
358
- const dirty = FIELD_KEYS.some(field => JSON.stringify(draft[field]) !== JSON.stringify(baseline[field]))
359
- || JSON.stringify(parseJurisdictions(jurisdictionText)) !== JSON.stringify(baseline.jurisdictions)
360
- const text = (field, placeholder) => h('input', {
361
- style: inputStyle,
362
- value: draft[field] ?? '',
363
- placeholder,
364
- disabled,
365
- onChange: event => update(field, event.target.value),
366
- })
367
- const number = (field, min, max) => h('input', {
368
- type: 'number',
369
- min,
370
- max,
371
- style: inputStyle,
372
- value: draft[field] ?? '',
373
- disabled,
374
- onChange: event => update(field, Number(event.target.value)),
375
- })
2285
+ /* -------------------------------------------------------------- *
2286
+ * 侧栏入口
2287
+ * -------------------------------------------------------------- */
376
2288
 
377
- return h('div', {
378
- style: { maxWidth: 760, padding: '8px 4px 28px', color: 'inherit' },
379
- },
380
- h('div', { style: { marginBottom: 18 } },
381
- h('h2', { style: { margin: '0 0 5px', fontSize: 18 } }, 'TA 的家'),
382
- h('p', {
383
- style: { margin: 0, fontSize: 12, lineHeight: 1.55, opacity: 0.64 },
384
- }, '身份、记忆、辖区与夜间回顾。保存会写入当前 profile;配置字段即时生效。')),
385
-
386
- state === 'error' ? h('div', {
387
- role: 'alert',
388
- style: {
389
- marginBottom: 14,
390
- padding: '9px 11px',
391
- border: '1px solid var(--dsw-alias-state-error-primary, rgba(220,80,80,.35))',
392
- borderRadius: 8,
393
- color: 'var(--dsw-alias-state-error-primary, #c44)',
394
- fontSize: 12,
395
- lineHeight: 1.45,
396
- },
397
- }, message || '配置不可用') : null,
398
-
399
- h(Section, { title: '位置' },
400
- h(Field, { label: 'Ta 的家', hint: '必须与 ta / ta-review 会话的工作目录一致。' },
401
- text('taHome', '~/TATA/home')),
402
- h(Field, { label: 'ReMe 地址', hint: '建议只指向本机回环地址;capture 会把对话写入这里。' },
403
- text('remeEndpoint', 'http://127.0.0.1:2333'))),
404
-
405
- h(Section, { title: '记忆与辖区' },
406
- h(Field, { label: '只读辖区', hint: '每行一个根目录;不能填 / 或 ~。' },
407
- h('textarea', {
408
- style: { ...inputStyle, minHeight: 64, resize: 'vertical', lineHeight: 1.5 },
409
- value: jurisdictionText,
410
- disabled,
411
- onChange: event => {
412
- editing.current = true
413
- setJurisdictionText(event.target.value)
414
- setMessage('')
415
- setState(previous => previous === 'error' ? 'ready' : previous)
416
- },
417
- })),
418
- h(Toggle, {
419
- label: '捕获完成的聊天',
420
- hint: '关闭后不把日常对话送入长期记忆。',
421
- checked: draft.captureEnabled,
422
- disabled,
423
- onChange: value => update('captureEnabled', value),
424
- }),
425
- h(Field, { label: '每几轮封一批', hint: '1–60。' },
426
- number('captureInterval', 1, 60))),
2289
+ function TaEntry({ wide }) {
2290
+ const alive = useAlive()
2291
+ const [busy, setBusy] = React.useState(false)
2292
+ const [error, setError] = React.useState('')
2293
+ const busyRef = React.useRef(false)
427
2294
 
428
- h(Section, { title: '夜间回顾' },
429
- h(Toggle, {
430
- label: '22:30 ReMe 整理',
431
- checked: draft.dreamEnabled,
432
- disabled,
433
- onChange: value => update('dreamEnabled', value),
434
- }),
435
- h(Toggle, {
436
- label: '02:00 清理旧出门记录',
437
- checked: draft.outingCleanupEnabled,
438
- disabled,
439
- onChange: value => update('outingCleanupEnabled', value),
440
- }),
441
- h(Toggle, {
442
- label: '22:45 辖区人格化查看',
443
- hint: '由 Ta 自己读当天文件和对话,写一份辖区出门记录,供回顾使用。',
444
- checked: draft.jurisdictionOutingEnabled,
445
- disabled,
446
- onChange: value => update('jurisdictionOutingEnabled', value),
447
- }),
448
- h(Field, { label: '辖区查看时间', hint: '24 小时制,例如 22:45。' },
449
- text('jurisdictionOutingTime', '22:45')),
450
- h(Field, { label: '时区' },
451
- text('timezone', 'Asia/Shanghai'))),
452
-
453
- h(Section, { title: '主动消息' },
454
- h(Toggle, {
455
- label: '启用心跳',
456
- hint: '默认关闭。开启后只在活跃时段、inbox 非空时创建 life 会话。',
457
- checked: draft.heartbeatEnabled,
458
- disabled,
459
- onChange: value => update('heartbeatEnabled', value),
460
- }),
461
- h(Field, { label: '活跃开始' }, text('heartbeatActiveStart', '08:00')),
462
- h(Field, { label: '活跃结束' }, text('heartbeatActiveEnd', '23:00'))),
2295
+ async function openTa() {
2296
+ if (busyRef.current) return
2297
+ if (!uiWorkspace || !workspaces) {
2298
+ setError('会话服务未就绪')
2299
+ return
2300
+ }
2301
+ busyRef.current = true
2302
+ setBusy(true)
2303
+ setError('')
2304
+ try {
2305
+ let initialized
2306
+ try {
2307
+ const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(5000) : undefined
2308
+ const status = await requestJson('/status', { signal })
2309
+ initialized = status && status.initialized
2310
+ } catch {
2311
+ /* 旧 Host 没有设置接口时继续按工作区查找 */
2312
+ }
2313
+ if (initialized === false) {
2314
+ const message = 'TA 还没有家:请先打开 设置 → TA 的家 完成初始化'
2315
+ if (alive.current) setError(message)
2316
+ return
2317
+ }
2318
+ await openTaWorkspace(configuredHome())
2319
+ } catch (cause) {
2320
+ if (alive.current && !(cause && cause.cancelled)) setError(errorMessage(cause))
2321
+ } finally {
2322
+ busyRef.current = false
2323
+ if (alive.current) setBusy(false)
2324
+ }
2325
+ }
463
2326
 
464
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 9, marginTop: 18 } },
465
- h('button', {
466
- type: 'button',
467
- onClick: save,
468
- disabled: disabled,
469
- style: {
470
- padding: '7px 14px',
471
- border: 0,
472
- borderRadius: 7,
473
- background: 'var(--dsw-alias-button-primary-fill, var(--dsw-alias-brand-primary, #4d6bfe))',
474
- color: 'var(--dsw-alias-label-primary-foreground, #fff)',
475
- font: 'inherit',
476
- fontSize: 12,
477
- fontWeight: 600,
478
- cursor: disabled ? 'default' : 'pointer',
479
- opacity: disabled ? 0.55 : 1,
480
- },
481
- }, state === 'saving' ? '保存中…' : '保存'),
482
- h('button', {
2327
+ return h('button', {
483
2328
  type: 'button',
484
- onClick: reset,
485
- disabled,
2329
+ title: error || '去找Ta',
2330
+ 'aria-label': '去找Ta',
2331
+ disabled: busy,
2332
+ onClick: openTa,
486
2333
  style: {
487
- padding: '7px 12px',
488
- border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.28))',
489
- borderRadius: 7,
2334
+ display: 'inline-flex',
2335
+ alignItems: 'center',
2336
+ justifyContent: 'center',
2337
+ gap: 6,
2338
+ height: 30,
2339
+ width: wide ? 'auto' : 30,
2340
+ padding: wide ? '0 9px' : 0,
2341
+ border: '1px solid var(--dsw-alias-border-l2, var(--dsw-alias-border-l1, transparent))',
2342
+ borderRadius: 8,
490
2343
  background: 'transparent',
491
2344
  color: 'inherit',
492
2345
  font: 'inherit',
493
2346
  fontSize: 12,
494
- cursor: disabled ? 'default' : 'pointer',
2347
+ cursor: busy ? 'default' : 'pointer',
2348
+ opacity: busy ? 0.6 : 1,
495
2349
  },
496
- }, '还原修改'),
497
- (message || dirty) ? h('span', {
498
- role: 'status',
499
- 'aria-live': 'polite',
500
- style: { fontSize: 11, opacity: 0.65 },
501
- }, message || '有未保存修改') : null))
2350
+ },
2351
+ h('span', { 'aria-hidden': true, style: { fontSize: 14, lineHeight: 1 } }, '✦'),
2352
+ wide ? h('span', null, error || '去找Ta') : null)
502
2353
  }
503
2354
 
504
- function TaIcon({ size, active }) {
2355
+ function LockIcon({ size = 14 }) {
505
2356
  return h('svg', {
506
2357
  'aria-hidden': true,
507
- viewBox: '0 0 24 24',
2358
+ focusable: 'false',
2359
+ viewBox: '0 0 16 16',
508
2360
  width: size,
509
2361
  height: size,
510
2362
  fill: 'none',
511
2363
  stroke: 'currentColor',
512
- strokeWidth: 1.9,
513
- strokeLinecap: 'round',
514
- strokeLinejoin: 'round',
515
- style: { opacity: active ? 1 : 0.82, display: 'block' },
2364
+ strokeWidth: 1.3,
2365
+ style: { display: 'block', flex: 'none' },
516
2366
  },
517
- h('path', { d: 'M4.5 20.5h15' }),
518
- h('path', { d: 'M6 20.5V9.5L12 4.5l6 5v11' }),
519
- h('path', { d: 'M12 9.2l.65 1.8 1.8.65-1.8.65-.65 1.8-.65-1.8-1.8-.65 1.8-.65z', strokeWidth: 1.4 }))
2367
+ h('path', {
2368
+ d: 'M5.6 7.4V5.65a2.4 2.4 0 0 1 4.8 0V7.4',
2369
+ vectorEffect: 'non-scaling-stroke',
2370
+ }),
2371
+ h('rect', {
2372
+ x: 3.8,
2373
+ y: 7.4,
2374
+ width: 8.4,
2375
+ height: 6.3,
2376
+ rx: 1.6,
2377
+ vectorEffect: 'non-scaling-stroke',
2378
+ }),
2379
+ h('circle', { cx: 8, cy: 10.2, r: 0.85, fill: 'currentColor', stroke: 'none' }))
520
2380
  }
521
2381
 
2382
+ function TaIcon({ size = 16 }) {
2383
+ return h('svg', {
2384
+ 'aria-hidden': true,
2385
+ focusable: 'false',
2386
+ viewBox: '0 0 16 16',
2387
+ width: size,
2388
+ height: size,
2389
+ fill: 'none',
2390
+ stroke: 'currentColor',
2391
+ strokeWidth: 1.3,
2392
+ style: { display: 'block', flex: 'none' },
2393
+ },
2394
+ h('path', {
2395
+ // 房子只描边,视觉重量更接近其他导航图标。
2396
+ d: 'M2.1 7.15 8 2.2l5.9 4.95M3.45 6.65v7.15h9.1V6.65M6.7 13.8v-3.7h2.6v3.7',
2397
+ vectorEffect: 'non-scaling-stroke',
2398
+ }),
2399
+ h('path', {
2400
+ // 右上角实心曲线星,底端轻触屋顶;16px 下约 5.6px,参考设置里的技能图标。
2401
+ 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',
2402
+ fill: 'currentColor',
2403
+ stroke: 'none',
2404
+ }))
2405
+ }
2406
+
2407
+ /* -------------------------------------------------------------- *
2408
+ * 设置面板
2409
+ * -------------------------------------------------------------- */
2410
+
2411
+ function TaSettings(props) {
2412
+ const { call, alive } = useApi()
2413
+ const [statusState, reloadStatus] = useResource('/status', call, alive)
2414
+ const [personaState, reloadPersona] = useResource('/persona', call, alive)
2415
+ const [integrationsState, reloadIntegrations] = useResource('/integrations', call, alive)
2416
+ const [tab, setTab] = React.useState('config')
2417
+ const [operationBusy, setOperationBusy] = React.useState(false)
2418
+ const [dirtyMap, setDirtyMap] = React.useState({ soul: false, user: false })
2419
+ const remeConfig = useConfigForm(configForms)
2420
+ const advancedConfig = useConfigForm(configForms)
2421
+
2422
+ const refreshAll = React.useCallback(() => {
2423
+ void reloadStatus()
2424
+ void reloadPersona()
2425
+ void reloadIntegrations()
2426
+ }, [reloadStatus, reloadPersona, reloadIntegrations])
2427
+
2428
+ const refreshConnections = React.useCallback(async () => {
2429
+ await Promise.allSettled([reloadStatus(), reloadIntegrations()])
2430
+ }, [reloadStatus, reloadIntegrations])
2431
+
2432
+ const handlePersonaDirty = React.useCallback((field, dirty) => {
2433
+ setDirtyMap(previous => previous[field] === dirty ? previous : { ...previous, [field]: dirty })
2434
+ }, [])
2435
+
2436
+ const handlePersonaSaved = React.useCallback(() => {
2437
+ void reloadStatus()
2438
+ }, [reloadStatus])
2439
+
2440
+ // 已有 TA 缺 .ta-home 标记时自动补写一次;失败忽略,不阻塞页面。
2441
+ const markerFixRef = React.useRef('')
2442
+ React.useEffect(() => {
2443
+ const data = statusState.data
2444
+ if (statusState.phase !== 'ready' || !data || !data.initialized || data.homeMarked !== false) return
2445
+ const home = String(data.home || '')
2446
+ if (!home || markerFixRef.current === home) return
2447
+ markerFixRef.current = home
2448
+ call('/home/init', { method: 'POST', body: { path: home }, timeoutMs: 30000 })
2449
+ .then(() => {
2450
+ if (alive.current) refreshAll()
2451
+ })
2452
+ .catch(() => {
2453
+ /* 补标记失败不阻塞:下次打开设置会再试 */
2454
+ })
2455
+ }, [statusState.phase, statusState.data, call, alive, refreshAll])
2456
+
2457
+ const status = statusState.data
2458
+ const lifecycleBusy = Boolean(status && status.lifecycle === 'reincarnating')
2459
+ const blocked = operationBusy || lifecycleBusy
2460
+ const personaDirty = Boolean(dirtyMap.soul || dirtyMap.user)
2461
+
2462
+ function changeTab(next) {
2463
+ remeConfig.clearNotices()
2464
+ advancedConfig.clearNotices()
2465
+ setTab(next)
2466
+ }
2467
+
2468
+ return h('div', { className: 'ta-root' },
2469
+ h('style', { 'data-dsh-ta-ui': '' }, TA_CSS),
2470
+ h(SegmentedTabs, {
2471
+ items: TAB_ITEMS,
2472
+ value: tab,
2473
+ onChange: changeTab,
2474
+ label: 'TA 设置分区',
2475
+ }),
2476
+ statusState.error && status
2477
+ ? h(Notice, {
2478
+ tone: 'warn',
2479
+ action: h(ActionButton, { onClick: () => { void reloadStatus() } }, '刷新状态'),
2480
+ }, `状态刷新失败:${statusState.error}。页面显示的是上次读取的数据。`)
2481
+ : null,
2482
+ h(Panel, { id: 'ta-panel-config', labelledBy: 'ta-tab-config', active: tab === 'config' },
2483
+ h(ConfigPage, {
2484
+ status,
2485
+ statusState,
2486
+ integrations: integrationsState.data,
2487
+ integrationsState,
2488
+ call,
2489
+ alive,
2490
+ refreshAll,
2491
+ refreshConnections,
2492
+ config: remeConfig,
2493
+ blocked,
2494
+ personaDirty,
2495
+ onBusyChange: setOperationBusy,
2496
+ onRetryStatus: () => { void reloadStatus() },
2497
+ })),
2498
+ h(Panel, { id: 'ta-panel-persona', labelledBy: 'ta-tab-persona', active: tab === 'persona' },
2499
+ h(PersonaPage, {
2500
+ status,
2501
+ statusState,
2502
+ resource: personaState,
2503
+ reload: reloadPersona,
2504
+ call,
2505
+ alive,
2506
+ blocked,
2507
+ onDirtyChange: handlePersonaDirty,
2508
+ onSaved: handlePersonaSaved,
2509
+ onRetryStatus: () => { void reloadStatus() },
2510
+ })),
2511
+ h(Panel, { id: 'ta-panel-status', labelledBy: 'ta-tab-status', active: tab === 'status' },
2512
+ h(StatusPage, {
2513
+ status,
2514
+ statusState,
2515
+ integrations: integrationsState.data,
2516
+ onRetry: () => { void reloadStatus() },
2517
+ })),
2518
+ h(Panel, { id: 'ta-panel-advanced', labelledBy: 'ta-tab-advanced', active: tab === 'advanced' },
2519
+ h(AdvancedPage, { config: advancedConfig })))
2520
+ }
2521
+
2522
+ /* -------------------------------------------------------------- *
2523
+ * Slot 注册
2524
+ * -------------------------------------------------------------- */
2525
+
2526
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
2527
+ name: 'tool.call.toolview',
2528
+ key: 'ta_sticker',
2529
+ }, TaStickerCard))
2530
+
522
2531
  ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
523
2532
  name: 'sidebar.footer.action',
524
2533
  id: 'dsh-ta-entry',