@restregular/dsh-memory 0.3.1 → 0.4.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/lib/client.js ADDED
@@ -0,0 +1,859 @@
1
+ /**
2
+ * dsh-memory — 客户端半边(设置页「记忆」区块)。
3
+ *
4
+ * 合并后本 bundle 与 provider / 工具 / 注入同属一个 npm 包
5
+ * `@restregular/dsh-memory`:一个包名、一条 Loader entry、两侧都在。
6
+ * 拆成两个包时这里曾是 '@restregular/dsh-memory-panel'。
7
+ *
8
+ * 与 dsh-meme / dshmarket 客户端同款形态:
9
+ * - window.__ModuleLoader__.load({id, factory(require)}):**id 必须等于包名**
10
+ * (client-modules 按包名建图行;声明成别的名字会让宿主找不到该行、回退重拉
11
+ * 同一个 bundle → 二次注册 → "duplicate factory registration" 启动失败);
12
+ * 而且 client bundle 只为「有活 Loader entry 且该 entry 解析到包名」的包服务,
13
+ * 所以这个 id 与 patch 里那一行的 name 必须同时是本包名。
14
+ * - exports.inject = ['slots'](dsh-client-ui-slots 在 desktop 宿主 asar 里存在);
15
+ * - ctx.get('slots') 判空防御,缺 slots 就静默退出,绝不让 client boot 失败;
16
+ * - 数据走 /memory/api HTTP(服务端半边注册的 prefix 路由);
17
+ * - 颜色全走宿主 --dsw-alias-* 主题 token,深浅色自适应,零硬编码色值。
18
+ */
19
+ window.__ModuleLoader__.load({
20
+ id: '@restregular/dsh-memory',
21
+ factory: (require) => {
22
+ var module = { exports: {} }
23
+ var exports = module.exports
24
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
25
+
26
+ const React = require('react')
27
+ const h = React.createElement
28
+
29
+ const API = '/memory/api'
30
+
31
+ const CSS = [
32
+ '.memp{display:flex;flex-direction:column;gap:14px;padding:2px 0;font-size:13px;color:var(--dsw-alias-label-primary)}',
33
+ '.memp .row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}',
34
+ '.memp .toolbar input[type=text]{flex:1;min-width:170px;max-width:320px}',
35
+ '.memp .linkbtn{background:none;border:none;padding:2px 4px;color:var(--dsw-alias-label-secondary);font-size:12px}',
36
+ '.memp .linkbtn:hover{color:var(--dsw-alias-brand-primary);border:none}',
37
+ // 概览
38
+ '.memp .stats{display:flex;gap:10px;flex-wrap:wrap}',
39
+ '.memp .stat{min-width:104px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:8px 14px;background:var(--dsw-alias-bg-layer-1)}',
40
+ '.memp .stat b{display:block;font-size:17px;font-weight:600;line-height:1.35}',
41
+ '.memp .stat span{font-size:11px;color:var(--dsw-alias-label-secondary)}',
42
+ '.memp .muted{font-size:11.5px;color:var(--dsw-alias-label-secondary)}',
43
+ '.memp .mono{font-family:var(--ds-font-family-code, ui-monospace, monospace);font-size:11px;color:var(--dsw-alias-label-secondary)}',
44
+ // 向量服务
45
+ '.memp .server{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:10px 12px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:8px}',
46
+ '.memp .server-head{display:flex;gap:8px;align-items:center;flex-wrap:wrap}',
47
+ '.memp .server-spacer{flex:1}',
48
+ '.memp .dot{width:8px;height:8px;border-radius:50%;flex:none;background:var(--dsw-alias-border-l1)}',
49
+ '.memp .dot.on{background:var(--dsw-alias-brand-primary)}',
50
+ '.memp .dot.off{background:var(--dsw-alias-label-danger, #e05555)}',
51
+ '.memp .pill{font-size:11px;line-height:1.7;padding:0 8px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);flex:none}',
52
+ '.memp .hint{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.6}',
53
+ '.memp .hint code,.memp .mono code{background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);border-radius:5px;padding:0 4px}',
54
+ // 控件
55
+ '.memp input[type=text],.memp select,.memp input[type=number]{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;font-size:13px;outline:none}',
56
+ '.memp input[type=text]:focus,.memp select:focus,.memp textarea:focus{border-color:var(--dsw-alias-brand-primary)}',
57
+ '.memp textarea{width:100%;box-sizing:border-box;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:6px 10px;font-size:13px;outline:none;resize:vertical;font-family:inherit}',
58
+ '.memp button{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:5px 12px;font-size:13px;cursor:pointer;transition:border-color .12s ease,color .12s ease}',
59
+ // hover 只改边框与文字颜色。**不要**再叠 box-shadow:那会在边框外多出一圈线
60
+ // (看起来就是"双层边框"),鼠标移开时又容易被看成残留。
61
+ '.memp button:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}',
62
+ // 点击后浏览器给的 focus 环同理:鼠标操作不留痕,键盘操作仍可见。
63
+ '.memp button:focus{outline:none}',
64
+ '.memp button:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}',
65
+ '.memp button:disabled{opacity:.5;cursor:default;border-color:var(--dsw-alias-border-l1);color:var(--dsw-alias-label-primary)}',
66
+ // 服务器开关(switch 造型)
67
+ '.memp .toggle{display:inline-flex;align-items:center;gap:8px;padding:4px 12px 4px 5px}',
68
+ '.memp .toggle-track{width:34px;height:18px;border-radius:999px;background:var(--dsw-alias-border-l1);position:relative;transition:background .15s ease;flex:none;display:inline-block}',
69
+ '.memp .toggle.on .toggle-track{background:var(--dsw-alias-brand-primary)}',
70
+ '.memp .toggle-knob{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.25);transition:transform .15s ease}',
71
+ '.memp .toggle.on .toggle-knob{transform:translateX(16px)}',
72
+ // 记忆列表:一条一行时信息密度优先
73
+ '.memp .list{display:flex;flex-direction:column;gap:8px}',
74
+ '.memp .rec{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:9px 12px;background:var(--dsw-alias-bg-layer-1)}',
75
+ '.memp .rec:hover{border-color:var(--dsw-alias-brand-primary)}',
76
+ '.memp .rec-head{display:flex;gap:7px;align-items:center;font-size:11.5px;color:var(--dsw-alias-label-secondary);cursor:pointer;user-select:none}',
77
+ '.memp .rec-head:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px;border-radius:6px}',
78
+ '.memp .chev{font-size:9px;opacity:.6;width:9px;flex:none;transition:transform .12s ease}',
79
+ '.memp .chev.open{transform:rotate(90deg)}',
80
+ '.memp .badge{border:1px solid var(--dsw-alias-border-l1);border-radius:5px;padding:0 6px;line-height:1.7;color:var(--dsw-alias-label-secondary);flex:none}',
81
+ '.memp .badge.scope{color:var(--dsw-alias-brand-primary);max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
82
+ '.memp .pending{flex:none}',
83
+ '.memp .time{margin-left:auto;flex:none}',
84
+ '.memp .preview{margin-top:7px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary);line-height:1.5}',
85
+ '.memp .content{margin-top:7px;white-space:pre-wrap;word-break:break-word;line-height:1.55}',
86
+ '.memp .rec-body{margin-top:6px}',
87
+ '.memp .acts{display:flex;gap:6px;margin-top:8px}',
88
+ '.memp .acts button{padding:3px 10px;font-size:12px}',
89
+ '.memp .editrow{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin-bottom:6px}',
90
+ '.memp .editrow input[type=text]{padding:4px 8px}',
91
+ '.memp .editrow input[type=number]{width:64px;padding:4px 8px}',
92
+ '.memp .err{color:var(--dsw-alias-label-danger, #e05555);font-size:12px}',
93
+ '.memp .empty{color:var(--dsw-alias-label-secondary);font-size:12.5px;padding:16px 2px;text-align:center}',
94
+ // 维护区(卸载向量服务 / 清空记忆数据)
95
+ '.memp .maint{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:10px 12px;display:flex;flex-direction:column;gap:8px}',
96
+ '.memp .maint-row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12.5px}',
97
+ '.memp .maint-row .grow{flex:1;min-width:160px}',
98
+ '.memp .path{max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
99
+ '.memp .danger{color:var(--dsw-alias-label-danger, #e05555);border-color:var(--dsw-alias-label-danger, #e05555)}',
100
+ // 模型与硬件(折叠在向量服务卡片里:默认视图保持干净)
101
+ '.memp .adv{border-top:1px solid var(--dsw-alias-border-l1);padding-top:8px}',
102
+ // 原生三角标记藏掉:展开/收起由左边的 .advcaret 自己画
103
+ '.memp .adv summary{cursor:pointer;font-size:12px;color:var(--dsw-alias-label-secondary);outline:none;list-style:none}',
104
+ '.memp .adv summary::-webkit-details-marker{display:none}',
105
+ '.memp .adv summary:hover{color:var(--dsw-alias-brand-primary)}',
106
+ '.memp .advsum{display:flex;gap:6px;align-items:center;flex-wrap:wrap}',
107
+ '.memp .advcaret{font-size:9px;opacity:.7;flex:none}',
108
+ '.memp .advsum .spacer{flex:1}',
109
+ '.memp .spacer{flex:1}',
110
+ '.memp .advbody{display:flex;flex-direction:column;gap:8px;padding-top:8px}',
111
+ // 标签气泡(本机配置 / 当前模型 / 选项里的体积与推荐)
112
+ // 两行都一样:一条线排开,超出就横向滚动(不换行、不挤压)
113
+ // 但**不显示滚动条**(宽度太显眼):仍可用滚轮 / 触控板 / 拖拽滚动。
114
+ '.memp .vec{display:flex;flex-direction:column;gap:8px}',
115
+ '.memp .chipline{display:flex;gap:8px;align-items:center;min-width:0}',
116
+ '.memp .chiptitle{flex:none;font-size:11.5px;color:var(--dsw-alias-label-secondary)}',
117
+ '.memp .chips{display:flex;gap:6px;align-items:center;flex:1;min-width:0;flex-wrap:nowrap;overflow-x:auto;overflow-y:hidden;scrollbar-width:none;-ms-overflow-style:none}',
118
+ '.memp .chips .chip{flex:none}',
119
+ '.memp .chips::-webkit-scrollbar{display:none;width:0;height:0}',
120
+ '.memp .chip{font-size:11px;line-height:1.75;padding:0 8px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-2);white-space:nowrap}',
121
+ '.memp .chip.rec{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}',
122
+ '.memp .chip.on{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}',
123
+ // 自定义下拉(原生 select 画不出气泡)
124
+ '.memp .drop{position:relative;display:inline-flex;flex-direction:column;align-items:flex-start}',
125
+ '.memp .dropbtn{display:inline-flex;align-items:center;gap:6px;max-width:100%}',
126
+ '.memp .dropname{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
127
+ // 模型名可能很长:按钮与列表都给个上限,超出的省略
128
+ '.memp .drop.modeldrop .dropbtn{max-width:360px}',
129
+ '.memp .caret{margin-left:6px;opacity:.6;font-size:10px}',
130
+ '.memp .droplist{position:absolute;z-index:10;top:100%;left:0;margin-top:4px;max-height:264px;overflow:auto;max-width:min(90vw,460px);border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 8px 24px rgba(0,0,0,.20);padding:4px}',
131
+ '.memp .dropitem{display:flex;align-items:center;gap:6px;padding:5px 8px;border-radius:6px;cursor:pointer;white-space:nowrap;border:1px solid transparent;transition:border-color .12s ease,color .12s ease,background .12s ease}',
132
+ // hover 的边框只出现在指针下;移开即恢复透明边框,不留痕
133
+ '.memp .dropitem:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-bg-layer-2)}',
134
+ // 当前项不用边框做标记(容易被看成残留),改用品牌色 + 加粗的名字
135
+ '.memp .dropitem.on{background:var(--dsw-alias-bg-layer-2)}',
136
+ '.memp .dropitem.on .dropname{font-weight:600;color:var(--dsw-alias-brand-primary)}',
137
+ '.memp .warn{font-size:11.5px;color:var(--dsw-alias-label-secondary)}',
138
+ ].join('')
139
+
140
+ async function api(method, body) {
141
+ const res = await fetch(`${API}/${method}`, {
142
+ method: body === undefined ? 'GET' : 'POST',
143
+ headers: body === undefined ? undefined : { 'content-type': 'application/json' },
144
+ body: body === undefined ? undefined : JSON.stringify(body),
145
+ })
146
+ let wire
147
+ try { wire = await res.json() } catch { throw new Error(`memory api: bad response (${res.status})`) }
148
+ if (!wire || wire.ok !== true) throw new Error((wire && wire.error && wire.error.message) || `memory api: ${method} failed`)
149
+ return wire.value
150
+ }
151
+
152
+ function fmtTime(ts) {
153
+ if (!ts) return '—'
154
+ const d = new Date(ts)
155
+ const pad = (n) => String(n).padStart(2, '0')
156
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
157
+ }
158
+
159
+ function scopeLabel(scope) {
160
+ return scope === 'global' ? '全局' : scope.startsWith('project:') ? scope.slice(8) : scope
161
+ }
162
+
163
+ function RecordCard({ rec, vectorOn, onSaved, onDeleted }) {
164
+ // collapsed by default: the list stays scannable, full text on demand
165
+ const [expanded, setExpanded] = React.useState(false)
166
+ const [editing, setEditing] = React.useState(false)
167
+ const [content, setContent] = React.useState(rec.content)
168
+ const [kind, setKind] = React.useState(rec.kind)
169
+ const [tags, setTags] = React.useState(rec.tags.join(', '))
170
+ const [importance, setImportance] = React.useState(rec.importance)
171
+ const [busy, setBusy] = React.useState(false)
172
+ const [error, setError] = React.useState('')
173
+
174
+ // editing implies expanded: the editor replaces the body
175
+ const open = expanded || editing
176
+ const toggle = () => { if (!editing) setExpanded((v) => !v) }
177
+
178
+ const save = async () => {
179
+ setBusy(true); setError('')
180
+ try {
181
+ await api('update', {
182
+ id: rec.id,
183
+ content,
184
+ kind,
185
+ importance: Number(importance) || 0,
186
+ tags: tags.split(',').map((t) => t.trim()).filter(Boolean),
187
+ })
188
+ setEditing(false)
189
+ onSaved()
190
+ } catch (e) { setError(String(e.message || e)) } finally { setBusy(false) }
191
+ }
192
+
193
+ const del = async () => {
194
+ if (!window.confirm('删除这条记忆?')) return
195
+ setBusy(true); setError('')
196
+ try { await api('delete', { id: rec.id }); onDeleted() } catch (e) { setError(String(e.message || e)) } finally { setBusy(false) }
197
+ }
198
+
199
+ const cancelEdit = () => {
200
+ setEditing(false)
201
+ setContent(rec.content); setKind(rec.kind)
202
+ setTags(rec.tags.join(', ')); setImportance(rec.importance)
203
+ }
204
+
205
+ return h('div', { className: 'rec' },
206
+ h('div', {
207
+ className: 'rec-head',
208
+ role: 'button',
209
+ tabIndex: 0,
210
+ 'aria-expanded': open,
211
+ title: open ? '收起' : '展开查看完整内容',
212
+ onClick: toggle,
213
+ onKeyDown: (e) => {
214
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle() }
215
+ },
216
+ },
217
+ h('span', { className: open ? 'chev open' : 'chev' }, '▶'),
218
+ h('span', { className: 'badge scope', title: rec.scope }, scopeLabel(rec.scope)),
219
+ h('span', { className: 'badge' }, rec.kind),
220
+ rec.supersedes ? h('span', { className: 'badge', title: `修正 #${rec.supersedes}` }, '修正') : null,
221
+ // 只在"待嵌入"时提示:已嵌入是常态,向量没启用时这条也没有行动价值。
222
+ !rec.embedded && vectorOn ? h('span', { className: 'pending', title: '待嵌入:向量服务就绪后会自动补上' }, '待嵌入') : null,
223
+ h('span', { className: 'time', title: `更新于 ${fmtTime(rec.updatedAt)}` }, fmtTime(rec.updatedAt)),
224
+ ),
225
+ !open ? h('div', { className: 'preview' }, rec.content) : null,
226
+ open
227
+ ? h('div', { className: 'rec-body' },
228
+ editing
229
+ ? h('div', null,
230
+ h('textarea', { rows: 4, value: content, onChange: (e) => setContent(e.target.value) }),
231
+ h('div', { className: 'editrow' },
232
+ // 类型也用同一个自绘下拉(全站不再有原生 select)
233
+ h(Dropdown, {
234
+ items: ['fact', 'decision', 'preference', 'procedure', 'note'].map((k) => ({ value: k, label: k })),
235
+ value: kind,
236
+ disabled: busy,
237
+ onChange: (next) => setKind(next),
238
+ }),
239
+ h('input', { type: 'text', style: { width: 170 }, value: tags, placeholder: '标签, 逗号分隔', onChange: (e) => setTags(e.target.value) }),
240
+ h('label', null, '重要度 ',
241
+ h('input', { type: 'number', min: 0, max: 1, step: 0.1, value: importance, onChange: (e) => setImportance(e.target.value) })),
242
+ ),
243
+ h('div', { className: 'acts' },
244
+ h('button', { disabled: busy, onClick: save }, busy ? '保存中…' : '保存'),
245
+ h('button', { disabled: busy, onClick: cancelEdit }, '取消'),
246
+ ),
247
+ )
248
+ : h('div', { className: 'content' }, rec.content),
249
+ )
250
+ : null,
251
+ error ? h('div', { className: 'err' }, error) : null,
252
+ open && !editing
253
+ ? h('div', { className: 'acts' },
254
+ h('button', { onClick: () => setEditing(true) }, '编辑'),
255
+ h('button', { disabled: busy, onClick: del }, busy ? '…' : '删除'),
256
+ )
257
+ : null,
258
+ )
259
+ }
260
+
261
+ /** 磁盘文案:MB 就是 MB,不足 1GB 时别显示成 "0GB"(曾经多除了一次 1024)。 */
262
+ function diskText(freeDiskMb) {
263
+ return freeDiskMb >= 1024 ? `${(freeDiskMb / 1024).toFixed(0)}GB` : `${freeDiskMb.toFixed(0)}MB`
264
+ }
265
+
266
+ /** 体积文案:小于 1GB 用 MB,否则 GB。 */
267
+ function sizeText(bytes) {
268
+ const mb = bytes / 1048576
269
+ return mb >= 1024 ? `${(mb / 1024).toFixed(1)}GB` : `${Math.round(mb)}MB`
270
+ }
271
+
272
+ /** 标签气泡。 */
273
+ function Chip({ children, tone, title }) {
274
+ return h('span', { className: `chip${tone ? ` ${tone}` : ''}`, ...(title ? { title } : {}) }, children)
275
+ }
276
+
277
+ /** 运行时风味的中文名。 */
278
+ function flavorLabel(flavor) {
279
+ if (flavor === 'cuda') return 'CUDA(显卡)'
280
+ if (flavor === 'vulkan') return 'Vulkan(显卡)'
281
+ if (flavor === 'metal') return 'Metal(显卡)'
282
+ return 'CPU'
283
+ }
284
+
285
+ /**
286
+ * 统一的**自绘下拉**:模型 / 运行时 / 作用域都用它。
287
+ *
288
+ * 为什么不用原生 `<select>`:它画不出气泡(体积、推荐标记),也没法在按钮里放多段内容。
289
+ * 行为对齐原生:点按钮开合、点选项选中并关闭、点外面关、Esc 关。
290
+ * `items`: [{ value, label, chips?, recommended? }]
291
+ */
292
+ function Dropdown({ items, value, disabled, title, onChange, className }) {
293
+ const [open, setOpen] = React.useState(false)
294
+ const current = items.find((item) => item.value === value) || items[0] || null
295
+
296
+ // 点列表外面(或按 Esc)关掉 —— 原生 select 自带的行为,自绘的得自己补。
297
+ // document 不可用(单元测试的脚手架)时安静跳过。
298
+ React.useEffect(() => {
299
+ if (!open) return undefined
300
+ const doc = typeof document !== 'undefined' ? document : undefined
301
+ if (doc === undefined || typeof doc.addEventListener !== 'function') return undefined
302
+ const inside = (target) => Boolean(target && typeof target.closest === 'function' && target.closest('.drop'))
303
+ const onDown = (event) => { if (!inside(event && event.target)) setOpen(false) }
304
+ const onKey = (event) => { if (event && event.key === 'Escape') setOpen(false) }
305
+ doc.addEventListener('click', onDown)
306
+ doc.addEventListener('keydown', onKey)
307
+ return () => {
308
+ doc.removeEventListener('click', onDown)
309
+ doc.removeEventListener('keydown', onKey)
310
+ }
311
+ }, [open])
312
+
313
+ return h('div', { className: `drop${className ? ` ${className}` : ''}` },
314
+ h('button', {
315
+ className: 'dropbtn',
316
+ disabled,
317
+ ...(title ? { title } : {}),
318
+ 'aria-haspopup': 'listbox',
319
+ 'aria-expanded': open,
320
+ onClick: () => setOpen(!open),
321
+ },
322
+ h('span', { className: 'dropname' }, current === null ? '—' : current.label),
323
+ ...(current === null ? [] : (current.chips ?? []).map((text, i) => h(Chip, { key: `c${i}` }, text))),
324
+ current !== null && current.recommended ? h(Chip, { tone: 'rec' }, '推荐') : null,
325
+ h('span', { className: 'caret' }, '▾'),
326
+ ),
327
+ open
328
+ ? h('div', { className: 'droplist', role: 'listbox' },
329
+ items.map((item) => h('div', {
330
+ key: item.value,
331
+ role: 'option',
332
+ 'aria-selected': item.value === value,
333
+ className: `dropitem${item.value === value ? ' on' : ''}`,
334
+ onClick: () => { setOpen(false); onChange(item.value) },
335
+ },
336
+ h('span', { className: 'dropname' }, item.label),
337
+ ...(item.chips ?? []).map((text, i) => h(Chip, { key: `c${i}` }, text)),
338
+ item.recommended ? h(Chip, { tone: 'rec' }, '推荐') : null,
339
+ )),
340
+ )
341
+ : null,
342
+ )
343
+ }
344
+
345
+ /**
346
+ * 向量服务这一整块:本机配置行 + 当前模型行 + 折叠的「模型与硬件」。
347
+ *
348
+ * 三行放在一起,是因为它们必须**始终可见**(不展开也要看到本机配置、当前模型和安装按钮),
349
+ * 而展开体里只放"改选择"的东西。硬件探测在面板一出现时取一次(服务端有 10 分钟缓存),
350
+ * 所以这两行不用等展开。下拉是自绘的 —— 原生 select 画不出气泡。
351
+ */
352
+ function ModelPicker({ busy, installing, installedBackend, current, onInstall }) {
353
+ const [open, setOpen] = React.useState(false)
354
+ const [report, setReport] = React.useState(null)
355
+ const [err, setErr] = React.useState('')
356
+ const [preset, setPreset] = React.useState('')
357
+ const [variant, setVariant] = React.useState('')
358
+ const [flavor, setFlavor] = React.useState('')
359
+ const [customOpen, setCustomOpen] = React.useState(false)
360
+ const [url, setUrl] = React.useState('')
361
+ const [dims, setDims] = React.useState('')
362
+
363
+ const load = async (force) => {
364
+ setErr('')
365
+ try {
366
+ setReport(await api(force ? 'embed/model/refresh' : 'embed/model', force ? {} : undefined))
367
+ } catch (e) {
368
+ setErr(String(e.message || e))
369
+ }
370
+ }
371
+ // 面板一出现就取一次(不等到展开):未配置时要在「向量服务」下面**直接**显示
372
+ // 默认选中(推荐)的模型与配置,而不是点开「模型与硬件」才出现。
373
+ // 服务端对硬件探测有 10 分钟缓存,所以这次请求通常只是一次读缓存。
374
+ React.useEffect(() => { if (report === null && err === '') load(false) }, [])
375
+
376
+ const catalog = (report && report.catalog) || []
377
+ const rec = report && report.recommendation
378
+ const hw = report && report.hardware
379
+ const options = []
380
+ for (const m of catalog) {
381
+ for (const v of m.variants) {
382
+ options.push({
383
+ key: `${m.id}/${v.id}`,
384
+ name: m.label,
385
+ variantLabel: v.label,
386
+ modelId: m.id,
387
+ variantId: v.id,
388
+ bytes: v.bytes,
389
+ dims: m.dims,
390
+ pooling: m.pooling,
391
+ // 逐档的"装没装"(服务端按 exe + 该档模型文件是否存在判断)
392
+ installed: Boolean(v.installed),
393
+ recommended: Boolean(rec && rec.modelId === m.id && rec.variantId === v.id),
394
+ })
395
+ }
396
+ }
397
+ const configured = Boolean(current && current.presetId && current.presetId !== 'custom')
398
+ const fallbackKey = configured
399
+ ? `${current.presetId}/${current.variantId}`
400
+ : (rec ? `${rec.modelId}/${rec.variantId}` : (options[0] ? options[0].key : ''))
401
+ const selectedKey = preset !== '' && variant !== '' ? `${preset}/${variant}` : fallbackKey
402
+ const selected = options.find((o) => o.key === selectedKey) || options[0] || null
403
+ const flavors = (hw && hw.flavors) || ['cpu']
404
+ const flavorValue = flavor !== '' ? flavor : (configured ? (current.flavor || 'cpu') : (rec ? rec.flavor : 'cpu'))
405
+
406
+ // 本机配置的四个事实(气泡行)
407
+ const machine = hw === null || hw === undefined
408
+ ? []
409
+ : [
410
+ `${hw.cpuCount} 核`,
411
+ `${Math.round(hw.totalRamMb / 1024)}GB 内存`,
412
+ hw.gpu ? `显卡 ${hw.gpu.name}${hw.gpu.vramMb ? `(${Math.round(hw.gpu.vramMb / 1024)}GB)` : ''}` : '无独立显卡',
413
+ hw.freeDiskMb !== null ? `磁盘剩余 ${diskText(hw.freeDiskMb)}` : '磁盘剩余未知',
414
+ ]
415
+ // 「当前模型」:已配置就显示实际配置,未配置就跟着上面的选择实时变
416
+ const currentChips = []
417
+ if (configured) {
418
+ const [name, variantLabel] = String(current.modelLabel || current.model || '').split(' · ')
419
+ currentChips.push(name, variantLabel, current.dims ? `${current.dims} 维` : null, current.pooling, current.flavor)
420
+ } else if (selected !== null) {
421
+ currentChips.push(selected.name, selected.variantLabel, `${selected.dims} 维`, selected.pooling, flavorValue)
422
+ }
423
+ const chipList = currentChips.filter(Boolean)
424
+
425
+ // 选中的这一档装没装。两个来源:catalog 的逐档标记(准,但要等清单刷新),
426
+ // 以及后端快照 install.installed(= exe + **当前配置那份**模型文件都在)。
427
+ // 后者让"刚下完"的那一刻按钮就能立刻变「已安装」,不用等重新拉清单。
428
+ const alreadyInstalled = selected !== null && (selected.installed
429
+ || (Boolean(installedBackend) && configured && selectedKey === `${current.presetId}/${current.variantId}`))
430
+ // 已经装过东西(运行时 + 某个模型)就不许再装第二个:要换模型,先去「维护」里卸载。
431
+ // 允许并行安装会让 <root>/llamacpp 与 models 里堆着多份文件,而配置只能指向一份,
432
+ // 之后"当前到底在跑哪个"就说不清了。
433
+ const hasInstalled = Boolean(installedBackend) || options.some((o) => o.installed)
434
+ const needUninstall = selected !== null && !alreadyInstalled && hasInstalled
435
+
436
+ // 安装/卸载状态一变就重拉清单:否则清单里"装没装"的标记会一直是旧的,
437
+ // 卸载完按钮还卡在「需先卸载」。
438
+ const [seenState, setSeenState] = React.useState(null)
439
+ React.useEffect(() => {
440
+ const now = `${installing ? 'running' : 'idle'}:${installedBackend ? 'in' : 'out'}`
441
+ if (seenState === null) { setSeenState(now); return }
442
+ if (seenState === now) return
443
+ setSeenState(now)
444
+ load(false)
445
+ }, [installing, installedBackend, seenState])
446
+
447
+ const pickFlavor = (next) => setFlavor(next)
448
+ const doInstall = () => {
449
+ if (selected === null) return
450
+ onInstall({ preset: selected.modelId, variant: selected.variantId, flavor: flavorValue })
451
+ }
452
+ const doCustom = () => {
453
+ if (url.trim() === '' || !(Number(dims) > 0)) { setErr('自定义模型需要填 URL 与维度'); return }
454
+ onInstall({ custom: { url: url.trim(), dims: Number(dims) } })
455
+ }
456
+
457
+ return h('div', { className: 'vec' },
458
+ // 两行状态气泡都带标题、都横向滚动不换行;动作按钮各自挂在这一行的最右边。
459
+ h('div', { className: 'chipline' },
460
+ h('span', { className: 'chiptitle' }, '本机配置:'),
461
+ h('div', { className: 'chips' },
462
+ (machine.length > 0 ? machine : ['读取中…']).map((label, i) => h(Chip, { key: i }, label))),
463
+ h('button', { disabled: busy, onClick: () => load(true) }, '重新检测硬件'),
464
+ ),
465
+ h('div', { className: 'chipline' },
466
+ h('span', { className: 'chiptitle' }, '当前模型:'),
467
+ h('div', { className: 'chips' }, chipList.map((label, i) => h(Chip, { key: i }, label))),
468
+ h('button', {
469
+ className: 'install',
470
+ // 四态:请求中 / 下载中 / 已装好 / 已装过别的(要先卸载)。后三种都不可点。
471
+ disabled: busy || installing || selected === null || alreadyInstalled || needUninstall,
472
+ ...(installing ? { title: '正在下载,进度见上方向量服务那一行' }
473
+ : alreadyInstalled ? { title: '这一档已经装好了' }
474
+ : needUninstall ? { title: '已经装过一个模型了。要换模型,请先在下面的「维护」里卸载向量服务' } : {}),
475
+ onClick: doInstall,
476
+ }, busy ? '处理中…'
477
+ : installing ? '下载中…'
478
+ : alreadyInstalled ? '已安装'
479
+ : needUninstall ? '需先卸载'
480
+ : '下载并安装'),
481
+ ),
482
+ h('details', { className: 'adv', onToggle: (e) => setOpen(Boolean(e.target.open)) },
483
+ h('summary', { className: 'advsum' },
484
+ h('span', { className: 'advcaret' }, open ? '▾' : '▸'),
485
+ h('span', null, '模型与硬件'),
486
+ ),
487
+ h('div', { className: 'advbody' },
488
+ report === null && err === '' ? h('div', { className: 'muted' }, '正在读取…') : null,
489
+ err ? h('div', { className: 'err' }, err) : null,
490
+ h('div', { className: 'row' },
491
+ h('span', { className: 'hint' }, '向量检索为可选功能,可以自定义配置任意 OpenAI 兼容的服务'),
492
+ ),
493
+ selected !== null
494
+ ? h('div', { className: 'row' },
495
+ h(Dropdown, {
496
+ items: options.map((o) => ({
497
+ value: o.key,
498
+ label: o.name,
499
+ chips: [o.variantLabel, sizeText(o.bytes)],
500
+ recommended: o.recommended,
501
+ })),
502
+ value: selectedKey,
503
+ disabled: busy,
504
+ className: 'modeldrop',
505
+ onChange: (key) => {
506
+ const [pid, vid] = key.split('/')
507
+ setPreset(pid); setVariant(vid)
508
+ },
509
+ }),
510
+ h(Dropdown, {
511
+ items: flavors.map((f) => ({ value: f, label: flavorLabel(f) })),
512
+ value: flavorValue,
513
+ disabled: busy,
514
+ title: '运行时:CPU 最稳,GPU 更快',
515
+ onChange: (next) => pickFlavor(next),
516
+ }),
517
+ )
518
+ : null,
519
+ h('div', { className: 'row' },
520
+ h('button', { onClick: () => setCustomOpen(!customOpen) }, customOpen ? '收起自定义模型' : '自定义 GGUF…'),
521
+ ),
522
+ customOpen
523
+ ? h('div', { className: 'row' },
524
+ h('input', { type: 'text', placeholder: 'https://…/model.gguf', value: url, onChange: (e) => setUrl(e.target.value) }),
525
+ h('input', { type: 'number', placeholder: '维度', value: dims, style: { width: 80 }, onChange: (e) => setDims(e.target.value) }),
526
+ h('button', { disabled: busy, onClick: doCustom }, '安装'),
527
+ )
528
+ : null,
529
+ report && report.records > 0
530
+ ? h('div', { className: 'muted' }, `换模型会让这 ${report.records} 条记忆重新嵌入;期间检索暂时用词法匹配。`)
531
+ : null,
532
+ ),
533
+ ),
534
+ )
535
+ }
536
+
537
+ function MemoryPanel() {
538
+ const [records, setRecords] = React.useState([])
539
+ const [scopes, setScopes] = React.useState([])
540
+ const [embedServer, setEmbedServer] = React.useState(null)
541
+ const [embedBusy, setEmbedBusy] = React.useState(false)
542
+ const [embedNotice, setEmbedNotice] = React.useState('')
543
+ const [installRequested, setInstallRequested] = React.useState(false)
544
+ const [dangerAsk, setDangerAsk] = React.useState('')
545
+ const [scopeFilter, setScopeFilter] = React.useState('')
546
+ const [q, setQ] = React.useState('')
547
+ const [loading, setLoading] = React.useState(true)
548
+ const [error, setError] = React.useState('')
549
+
550
+ const load = async (query, scopeF) => {
551
+ setLoading(true); setError('')
552
+ try {
553
+ const params = new URLSearchParams()
554
+ const qq = query !== undefined ? query : q
555
+ const ss = scopeF !== undefined ? scopeF : scopeFilter
556
+ if (ss) params.set('scope', ss)
557
+ if (qq.trim()) params.set('q', qq.trim())
558
+ const suffix = params.toString() ? `?${params}` : ''
559
+ const [recVal, status] = await Promise.all([api(`records${suffix}`), api('status')])
560
+ setRecords(recVal.records)
561
+ setScopes(status.scopes)
562
+ setEmbedServer(status.embedServer ?? null)
563
+ } catch (e) {
564
+ setError(String(e.message || e))
565
+ }
566
+ setLoading(false)
567
+ }
568
+ React.useEffect(() => { load('', '') }, [])
569
+
570
+ const embedAction = async (action, body = {}) => {
571
+ setEmbedBusy(true); setEmbedNotice('')
572
+ try {
573
+ const value = await api(`embed/${action}`, body)
574
+ // 安装接口返回的是 { install, ...status }:先落状态,进度由轮询刷新
575
+ setEmbedServer(value.embedServer ? { ...value.embedServer } : value)
576
+ if (action === 'install') {
577
+ // 不弹任何"下载开始"提示:进度本身就是反馈,装好会自动变成运行中。
578
+ setInstallRequested(true)
579
+ } else if (action === 'install/cancel') {
580
+ setInstallRequested(false)
581
+ setEmbedNotice('已请求取消下载')
582
+ } else if (action === 'start') {
583
+ setEmbedNotice(value.state === 'disabled'
584
+ ? '未配置自启(spawn.enabled),无法启动'
585
+ : value.reachable ? `已启动(pid ${value.pid ?? '?'})` : '已请求启动,但健康检查未通过,请看 llama-server.log')
586
+ } else {
587
+ setEmbedNotice(value.stopped
588
+ ? '已停止'
589
+ : value.reason === 'EXTERNAL_INSTANCE'
590
+ ? '这是应用外部启动的实例,不受本应用管理,未关闭'
591
+ : '当前没有由本应用管理的进程')
592
+ }
593
+ } catch (e) {
594
+ setEmbedNotice(`操作失败: ${String(e.message || e)}`)
595
+ }
596
+ setEmbedBusy(false)
597
+ }
598
+
599
+ /**
600
+ * 维护动作:卸载向量服务 / 清空记忆数据。两者都不可撤销,所以都走两步确认
601
+ * (dangerAsk 记住当前等确认的那一项,第二次点击才真的发请求)。
602
+ */
603
+ const maintenanceAction = async (which) => {
604
+ if (dangerAsk !== which) { setDangerAsk(which); setEmbedNotice(''); return }
605
+ setDangerAsk('')
606
+ setEmbedBusy(true); setEmbedNotice('')
607
+ try {
608
+ const value = which === 'uninstall'
609
+ ? await api('embed/uninstall', {})
610
+ // 服务端要求显式 confirm:"delete",避免任何一次误触就清库
611
+ : await api('data/wipe', { confirm: 'delete' })
612
+ setEmbedServer(value.embedServer ? { ...value.embedServer } : value)
613
+ if (which === 'uninstall') {
614
+ setEmbedNotice(value.removed
615
+ ? `已卸载向量服务,释放约 ${((value.freedBytes ?? 0) / 1048576).toFixed(1)} MB。向量检索已关闭,词法检索照常。`
616
+ : value.reason === 'EXTERNAL_BACKEND'
617
+ ? '当前后端不在本插件管理的目录里(是你自己装的),没有删除任何东西。'
618
+ : '没有找到本插件安装的向量服务文件。')
619
+ } else {
620
+ setEmbedNotice(`已清空 ${value.removed ?? 0} 条记忆(${(value.scopes ?? []).length} 个作用域)。`)
621
+ }
622
+ await load('', '')
623
+ } catch (e) {
624
+ setEmbedNotice(`操作失败: ${String(e.message || e)}`)
625
+ }
626
+ setEmbedBusy(false)
627
+ }
628
+
629
+ // 安装状态要在 effect 之前算出来:依赖数组在渲染期取值,晚于它的 const 会踩 TDZ。
630
+ const install = (embedServer && embedServer.install) || null
631
+ const maintenance = (embedServer && embedServer.maintenance) || null
632
+ const usageMb = maintenance ? (maintenance.usageBytes / 1048576).toFixed(1) : '0.0'
633
+ const installPhase = install && install.phase ? install.phase : 'idle'
634
+ const installRunning = installPhase !== 'idle' && installPhase !== 'done' && installPhase !== 'error'
635
+ const installBusy = installRunning
636
+ const installed = Boolean(install && install.installed)
637
+ // 点了按钮就一定要轮询:provider 的 start() 是 fire-and-forget,紧接着返回的那次
638
+ // 状态可能还停在 idle,只看 phase 会让进度永远不刷新。
639
+ const shouldPoll = shouldPollInstall(installPhase, installRequested)
640
+ React.useEffect(() => {
641
+ if (!shouldPoll) return undefined
642
+ const timer = setInterval(() => { load('', '') }, 1500)
643
+ return () => clearInterval(timer)
644
+ }, [shouldPoll])
645
+ React.useEffect(() => {
646
+ if (installRequested && (installPhase === 'done' || installPhase === 'error')) setInstallRequested(false)
647
+ }, [installRequested, installPhase])
648
+
649
+ const total = scopes.reduce((n, s) => n + s.records, 0)
650
+ const pending = scopes.reduce((n, s) => n + s.pendingEmbeds, 0)
651
+
652
+ // 向量卡片的状态判定。provider 给的 mode 决定"该不该有启停开关":
653
+ // off 没配置任何后端 → 不给开关,模型与安装入口都在「模型与硬件」里
654
+ // external 只知道 endpoint(云端/用户自建)→ 开关无意义,我们不该假装拥有它
655
+ // managed 配置了 spawn(或刚自动装好)→ 我们托管子进程,给开关
656
+ // 另外 enabled=false(配置里显式关掉)时也不能给一个"开了也没用"的开关。
657
+ const mode = embedServer && embedServer.mode
658
+ ? embedServer.mode
659
+ : (embedServer && embedServer.baseUrl ? 'managed' : 'off')
660
+ const vectorEnabled = embedServer ? Boolean(embedServer.enabled) : false
661
+ const configured = Boolean(embedServer && (embedServer.configured !== undefined
662
+ ? embedServer.configured
663
+ : mode !== 'off'))
664
+ const serverOn = Boolean(embedServer && embedServer.reachable)
665
+ const managed = mode === 'managed'
666
+ const canToggle = Boolean(embedServer) && managed && vectorEnabled
667
+ const toggleTitle = !embedServer
668
+ ? '当前 provider 未提供向量服务管理'
669
+ : mode === 'external' ? '这是外部服务(云端或你自己跑的),不由本应用启停'
670
+ : !vectorEnabled ? '向量检索已在配置里关闭'
671
+ : serverOn ? '点击关闭向量服务' : '点击启动向量服务'
672
+
673
+ const mb = (n) => (n / 1048576).toFixed(1)
674
+ const installPercent = install && install.totalBytes ? Math.min(100, Math.round((install.receivedBytes / install.totalBytes) * 100)) : null
675
+
676
+ const dotClass = serverOn ? 'dot on' : 'dot off'
677
+ // 状态只说状态,归属由 pill 说 —— 之前两处各说一遍("运行中 · 由本应用管理" + "由本应用托管")。
678
+ let stateText
679
+ if (!embedServer) stateText = '不可用'
680
+ else if (mode === 'off') stateText = installBusy ? '正在安装' : installed ? '检测到本地文件' : '未配置'
681
+ else if (!vectorEnabled) stateText = '已在配置里关闭'
682
+ else if (serverOn) stateText = '运行中'
683
+ else stateText = managed ? '已停止' : '未连接'
684
+
685
+ // 端点/pid/模型是排障信息,折成一行 mono;完整信息放 title,不占版面。
686
+ const endpoint = embedServer ? String(embedServer.baseUrl || embedServer.endpoint || '') : ''
687
+ const endpointLabel = (() => {
688
+ if (!endpoint) return ''
689
+ try { return new URL(endpoint).host } catch { return endpoint.replace(/^https?:\/\//, '').split('/')[0] }
690
+ })()
691
+ const endpointTitle = [endpoint, embedServer && embedServer.pid ? `pid ${embedServer.pid}` : '', embedServer && embedServer.model ? `模型 ${embedServer.model}` : ''].filter(Boolean).join(' · ')
692
+
693
+ // 右侧动作区:安装进度 > 重试 > 启停开关。
694
+ // 原则:只在"开关真能改变什么"时才渲染它——未配置、外部服务、配置里显式
695
+ // 关闭,这三种情况给别的动作或干脆不给,避免一个永远灰着的开关。
696
+ // 安装入口不放这里:模型在下面的「模型与硬件」里选,安装按钮跟着选择走。
697
+ const actions = []
698
+ if (installBusy) {
699
+ actions.push(h('span', { className: 'muted', key: 'prog' },
700
+ `${install.message || install.phase}${installPercent === null ? '' : ` ${installPercent}%`}`
701
+ + (install.totalBytes ? `(${mb(install.receivedBytes)}/${mb(install.totalBytes)} MB)` : '')))
702
+ actions.push(h('button', { key: 'cancel', disabled: embedBusy, onClick: () => embedAction('install/cancel') }, '取消'))
703
+ } else if (install && install.phase === 'error') {
704
+ actions.push(h('button', { key: 'retry', disabled: embedBusy, onClick: () => embedAction('install') }, '重试下载'))
705
+ } else if (canToggle) {
706
+ actions.push(h('button', {
707
+ key: 'toggle',
708
+ className: serverOn ? 'toggle on' : 'toggle',
709
+ role: 'switch',
710
+ 'aria-checked': serverOn,
711
+ disabled: embedBusy,
712
+ title: toggleTitle,
713
+ onClick: () => embedAction(serverOn ? 'stop' : 'start'),
714
+ },
715
+ h('span', { className: 'toggle-track' }, h('span', { className: 'toggle-knob' })),
716
+ h('span', null, embedBusy ? '处理中…' : serverOn ? '已开启' : '已关闭'),
717
+ ))
718
+ }
719
+
720
+ // 错误说明只在这里出现一次(重试按钮在右上方);配置里关掉了向量检索时解释一句。
721
+ let notice = null
722
+ if (mode !== 'off' && !vectorEnabled) {
723
+ notice = h('div', { className: 'hint' }, '配置里关掉了向量检索(', h('code', null, 'retrieval.vector.enabled'), ' 改回 true 并重启即可)。')
724
+ } else if (install && install.phase === 'error') {
725
+ notice = h('div', { className: 'hint err' }, `安装失败:${install.error || install.message}`)
726
+ }
727
+
728
+ const filtering = q.trim() !== '' || scopeFilter !== ''
729
+
730
+ return h('div', { className: 'memp' },
731
+ h('div', { className: 'stats' },
732
+ h('div', { className: 'stat' }, h('b', null, String(total)), h('span', null, '条记忆')),
733
+ h('div', { className: 'stat' }, h('b', null, String(scopes.length)), h('span', null, '个作用域')),
734
+ configured && vectorEnabled
735
+ ? h('div', { className: 'stat' }, h('b', null, String(pending)), h('span', null, '待嵌入向量'))
736
+ : h('div', { className: 'stat' }, h('b', null, '—'), h('span', null, '向量未启用')),
737
+ ),
738
+ h('div', { className: 'server' },
739
+ h('div', { className: 'server-head' },
740
+ h('span', { className: dotClass }),
741
+ h('b', null, '向量服务'),
742
+ h('span', { className: 'muted' }, stateText),
743
+ // 地址紧跟在状态右边(排障要看的就是它),完整信息(pid/模型)进 title。
744
+ endpointLabel ? h('span', { className: 'mono', title: endpointTitle }, endpointLabel) : null,
745
+ configured && vectorEnabled ? h('span', { className: 'pill' }, managed ? '由本应用托管' : '外部服务') : null,
746
+ h('span', { className: 'server-spacer' }),
747
+ actions,
748
+ ),
749
+ notice,
750
+ embedNotice ? h('div', { className: 'muted' }, embedNotice) : null,
751
+ h(ModelPicker, {
752
+ busy: embedBusy,
753
+ // 下载是后台跑的,`busy`(一次请求)早就结束了;要单独把"正在下载"传给按钮,
754
+ // 否则下载中还能反复点「下载并安装」。
755
+ installing: installBusy || installRequested,
756
+ installedBackend: installed,
757
+ current: embedServer
758
+ ? { presetId: embedServer.presetId, variantId: embedServer.variantId, model: embedServer.model, modelLabel: embedServer.modelLabel, dims: embedServer.dims, pooling: embedServer.pooling, flavor: embedServer.flavor }
759
+ : null,
760
+ onInstall: (override) => embedAction('install', override),
761
+ }),
762
+ ),
763
+ // 维护区:DSH 卸载插件时不会给插件任何提问机会(就是 pnpm remove + 去掉
764
+ // bundles),所以"要不要留向量服务 / 要不要留记忆数据"只能在这里、卸载之前问。
765
+ maintenance
766
+ ? h('div', { className: 'maint' },
767
+ h('div', { className: 'maint-row' },
768
+ h('b', null, '维护'),
769
+ h('span', { className: 'muted' }, '卸载插件不会移除已配置的向量服务与记忆文件'),
770
+ ),
771
+ h('div', { className: 'maint-row' },
772
+ h('span', { className: 'grow' }, `向量服务:${usageMb} MB`),
773
+ maintenance.usageBytes > 0
774
+ ? (dangerAsk === 'uninstall'
775
+ ? [h('button', { key: 'ok', className: 'danger', disabled: embedBusy, onClick: () => maintenanceAction('uninstall') }, `确认卸载(释放 ${usageMb} MB)`),
776
+ h('button', { key: 'no', disabled: embedBusy, onClick: () => setDangerAsk('') }, '取消')]
777
+ : h('button', { key: 'ask', disabled: embedBusy, onClick: () => maintenanceAction('uninstall') }, '卸载向量服务'))
778
+ : h('span', { className: 'muted' }, '未安装'),
779
+ ),
780
+ h('div', { className: 'maint-row' },
781
+ h('span', { className: 'grow' }, `记忆数据:${maintenance.records} 条`),
782
+ maintenance.storeDir ? h('span', { className: 'muted path', title: maintenance.storeDir }, maintenance.storeDir) : null,
783
+ maintenance.records > 0
784
+ ? (dangerAsk === 'wipe'
785
+ ? [h('button', { key: 'ok', className: 'danger', disabled: embedBusy, onClick: () => maintenanceAction('wipe') }, `确认清空 ${maintenance.records} 条(不可恢复)`),
786
+ h('button', { key: 'no', disabled: embedBusy, onClick: () => setDangerAsk('') }, '取消')]
787
+ : h('button', { key: 'ask', disabled: embedBusy, onClick: () => maintenanceAction('wipe') }, '清空记忆数据'))
788
+ : h('span', { className: 'muted' }, '无'),
789
+ ),
790
+ )
791
+ : null,
792
+ h('div', { className: 'row toolbar' },
793
+ h('input', {
794
+ type: 'text', placeholder: '搜索内容、类型或标签', value: q,
795
+ onChange: (e) => setQ(e.target.value),
796
+ onKeyDown: (e) => { if (e.key === 'Enter') load(q, scopeFilter) },
797
+ }),
798
+ // 作用域也用同一个自绘下拉(与模型/运行时统一)
799
+ h(Dropdown, {
800
+ items: [
801
+ { value: '', label: '全部作用域' },
802
+ ...scopes.map((s) => ({ value: s.scope, label: scopeLabel(s.scope) })),
803
+ ],
804
+ value: scopeFilter,
805
+ disabled: loading,
806
+ onChange: (next) => { setScopeFilter(next); load(q, next) },
807
+ }),
808
+ h('button', { onClick: () => load(q, scopeFilter), disabled: loading }, loading ? '刷新中…' : '刷新'),
809
+ filtering ? h('button', { className: 'linkbtn', onClick: () => { setQ(''); setScopeFilter(''); load('', '') } }, '清空筛选') : null,
810
+ ),
811
+ error ? h('div', { className: 'err' }, error) : null,
812
+ !loading && !error && records.length === 0
813
+ ? h('div', { className: 'empty' }, filtering ? '没有匹配的记忆' : '还没有记忆')
814
+ : h('div', { className: 'list' },
815
+ records.map((rec) => h(RecordCard, { key: rec.id, rec, vectorOn: configured && vectorEnabled, onSaved: () => load(), onDeleted: () => load() }))),
816
+ )
817
+ }
818
+
819
+ const inject = ['slots']
820
+
821
+ function apply(ctx) {
822
+ try {
823
+ const styleEl = document.createElement('style')
824
+ styleEl.textContent = CSS
825
+ document.head.appendChild(styleEl)
826
+ ctx.effect(() => () => { styleEl.remove() }, 'dsh-memory: styles')
827
+
828
+ const slots = ctx.get('slots')
829
+ if (slots === undefined) return
830
+ slots.inject('settings.section', () => slots.register(
831
+ { name: 'settings.section', id: 'memory', order: 24, label: '记忆' },
832
+ () => React.createElement(MemoryPanel),
833
+ ))
834
+ } catch (error) {
835
+ console.error('[dsh-memory] client apply 失败(已吞掉):', error?.message)
836
+ }
837
+ }
838
+
839
+ exports.apply = apply
840
+ exports.inject = inject
841
+ // exported for the render smoke test only (host/bundler never reads it),
842
+ // same convention as the official dsh-meme client
843
+ /**
844
+ * Should the panel keep polling the status endpoint?
845
+ *
846
+ * Two cases, and the second one is the reason this is a named function: the
847
+ * provider's start() is fire-and-forget, so the status returned immediately
848
+ * after POST /embed/install can still say 'idle'. Polling only while a phase
849
+ * is in flight would then never show any progress at all.
850
+ */
851
+ function shouldPollInstall(phase, requested) {
852
+ const running = phase !== 'idle' && phase !== 'done' && phase !== 'error'
853
+ return running || (requested === true && phase === 'idle')
854
+ }
855
+
856
+ exports.__test = { RecordCard: RecordCard, MemoryPanel: MemoryPanel, CSS: CSS, shouldPollInstall: shouldPollInstall }
857
+ return module.exports
858
+ },
859
+ })