@zxlll/dsh-integration-env 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1233 @@
1
+ /**
2
+ * Client 半:Web GUI 右栏「集成环境」面板(@zxlll/dsh-integration-env)。
3
+ *
4
+ * 职责:把 Host 半管理的实例(MySQL / Nacos / Redis / MongoDB / MQTT)
5
+ * 渲染成可筛选、可勾选、可编辑、可试连的面板;勾选结果按会话保存在 Host,
6
+ * 「插入上下文」把 Host 生成的【集成环境】提示块写进当前会话输入框。
7
+ *
8
+ * 只通过 POST /integration-env/api 与 Host 通信,不依赖任何 Host 文件;
9
+ * 只用 require('react'),不 import 任何 @deepseek-ai/* 包(profile 里解析不到,会白屏)。
10
+ */
11
+ window.__ModuleLoader__.load({
12
+ id: '@zxlll/dsh-integration-env',
13
+ factory(require) {
14
+ const React = require('react')
15
+ const h = React.createElement
16
+
17
+ /** 右栏标签类型,sidebarRight.openTab 用它打开页面。 */
18
+ const KIND = 'integration-env'
19
+ /** 标签实现 id,也是 sidebar.right.pane.tab 槽的 key,必须全局唯一。 */
20
+ const IMPL_ID = '@zxlll/dsh-integration-env'
21
+ const API_URL = '/integration-env/api'
22
+ /** 只记住筛选条件;实例选择一律以 Host 为准,不写 localStorage。 */
23
+ const STORAGE_KEY = 'dsh.integration-env.v1'
24
+
25
+ // ───────────────────────── 数据访问 ─────────────────────────
26
+
27
+ /** 调用 Host 半的接口;失败时抛出可直接展示的错误。 */
28
+ async function callApi(method, payload, signal) {
29
+ let response
30
+ try {
31
+ response = await fetch(API_URL, {
32
+ method: 'POST',
33
+ headers: { 'content-type': 'application/json' },
34
+ credentials: 'same-origin',
35
+ body: JSON.stringify({ method, payload: payload ?? {} }),
36
+ signal,
37
+ })
38
+ } catch (error) {
39
+ if (error && error.name === 'AbortError') throw error
40
+ throw new Error(`无法连接插件 Host 半:${error && error.message ? error.message : String(error)}`)
41
+ }
42
+ let envelope
43
+ try {
44
+ envelope = await response.json()
45
+ } catch {
46
+ throw new Error(`Host 返回了非 JSON 响应(HTTP ${response.status})`)
47
+ }
48
+ if (!envelope || envelope.ok !== true) {
49
+ const message = envelope && envelope.error && envelope.error.message ? envelope.error.message : `HTTP ${response.status}`
50
+ throw new Error(message)
51
+ }
52
+ return envelope.value
53
+ }
54
+
55
+ /** 读取上次的筛选条件。 */
56
+ function loadPrefs() {
57
+ try {
58
+ const raw = window.localStorage.getItem(STORAGE_KEY)
59
+ if (!raw) return {}
60
+ const parsed = JSON.parse(raw)
61
+ return parsed && typeof parsed === 'object' ? parsed : {}
62
+ } catch {
63
+ return {}
64
+ }
65
+ }
66
+
67
+ /** 记住筛选条件(只有 kindFilter,实例选择不落盘)。 */
68
+ function savePrefs(next) {
69
+ try {
70
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
71
+ } catch {
72
+ /* 隐私模式等场景下忽略 */
73
+ }
74
+ }
75
+
76
+ function isAbort(error) {
77
+ return Boolean(error && error.name === 'AbortError')
78
+ }
79
+
80
+ function errorMessage(error) {
81
+ if (!error) return '未知错误'
82
+ if (typeof error === 'string') return error
83
+ if (error.message) return error.message
84
+ return String(error)
85
+ }
86
+
87
+ /** busy 状态码 → 底部提示文案。 */
88
+ function busyText(key) {
89
+ if (!key) return ''
90
+ if (key.indexOf('test:') === 0) return '正在测试连接…'
91
+ if (key.indexOf('toggle:') === 0) return '正在保存本会话的启用选择…'
92
+ const map = {
93
+ save: '正在保存…',
94
+ delete: '正在删除…',
95
+ 'test-form': '正在测试连接…',
96
+ insert: '正在生成并插入上下文…',
97
+ clear: '正在清空本会话启用…',
98
+ }
99
+ return map[key] || '处理中…'
100
+ }
101
+
102
+ /** 一条测试结果的展示文案(状态点 title / 行内提示共用)。 */
103
+ function testSummary(result) {
104
+ if (!result) return ''
105
+ if (result.ok) {
106
+ const latency = typeof result.latencyMs === 'number' ? ` · ${result.latencyMs}ms` : ''
107
+ const detail = result.detail ? ` · ${result.detail}` : ''
108
+ return `连接成功${latency}${detail}`
109
+ }
110
+ const latency = typeof result.latencyMs === 'number' ? `(${result.latencyMs}ms)` : ''
111
+ return `连接失败${latency}:${result.error || '未知错误'}`
112
+ }
113
+
114
+ // ───────────── 表单纯函数(也导出到 internals 供自检) ─────────────
115
+
116
+ /** 按 kind.fields 生成一份默认 config;Client 永远不硬编码字段。 */
117
+ function defaultConfigForKind(kind) {
118
+ const config = {}
119
+ if (!kind || !Array.isArray(kind.fields)) return config
120
+ for (const field of kind.fields) {
121
+ if (!field || typeof field.key !== 'string') continue
122
+ const hasDefault = field.default !== undefined && field.default !== null
123
+ if (field.type === 'boolean') {
124
+ config[field.key] = field.default === true
125
+ } else if (field.type === 'select') {
126
+ const options = Array.isArray(field.options) ? field.options : []
127
+ config[field.key] = hasDefault ? field.default : options.length ? options[0].value : ''
128
+ } else if (field.type === 'number') {
129
+ config[field.key] = hasDefault ? field.default : ''
130
+ } else {
131
+ config[field.key] = hasDefault ? field.default : ''
132
+ }
133
+ }
134
+ return config
135
+ }
136
+
137
+ /** 编辑态:公开 config 里有的字段用存的值,secret 一律留空(留空 = 保持)。 */
138
+ function configForInstance(kind, instance) {
139
+ const config = defaultConfigForKind(kind)
140
+ const fields = kind && Array.isArray(kind.fields) ? kind.fields : []
141
+ const stored = instance && instance.config && typeof instance.config === 'object' ? instance.config : {}
142
+ for (const field of fields) {
143
+ if (!field || field.type === 'secret') continue
144
+ if (Object.prototype.hasOwnProperty.call(stored, field.key)) config[field.key] = stored[field.key]
145
+ }
146
+ return config
147
+ }
148
+
149
+ /** 表单草稿 → InstanceDraft(契约 §4.2)。 */
150
+ function buildDraftFromForm(form, kind) {
151
+ if (!form) return null
152
+ const fields = kind && Array.isArray(kind.fields) ? kind.fields : []
153
+ const source = form.config && typeof form.config === 'object' ? form.config : {}
154
+ const clearSecrets = Array.isArray(form.clearSecrets) ? form.clearSecrets.slice() : []
155
+ const config = {}
156
+ for (const field of fields) {
157
+ if (!field || typeof field.key !== 'string') continue
158
+ const raw = source[field.key]
159
+ if (field.type === 'boolean') {
160
+ config[field.key] = raw === true
161
+ continue
162
+ }
163
+ if (field.type === 'number') {
164
+ // 空值不传,交给 Host 用默认值;其余转 number。
165
+ if (raw === '' || raw === undefined || raw === null || Number.isNaN(Number(raw))) continue
166
+ config[field.key] = Number(raw)
167
+ continue
168
+ }
169
+ const text = raw === undefined || raw === null ? '' : String(raw)
170
+ if (field.type === 'secret') {
171
+ // 空字符串 = 保留原值;显式清除时传空串 + clearSecrets。
172
+ if (clearSecrets.indexOf(field.key) !== -1) {
173
+ config[field.key] = ''
174
+ } else if (text !== '') {
175
+ config[field.key] = text
176
+ }
177
+ continue
178
+ }
179
+ config[field.key] = text
180
+ }
181
+ const draft = {
182
+ kind: String(form.kind || (kind && kind.id) || ''),
183
+ name: String(form.name || '').trim(),
184
+ note: String(form.note || '').trim(),
185
+ enabled: form.enabled !== false,
186
+ config,
187
+ }
188
+ if (form.mode === 'edit' && form.id) draft.id = form.id
189
+ // 只有用户显式点「清除密码」的 secret 才进 clearSecrets。
190
+ const cleared = clearSecrets.filter((key) => fields.some((field) => field && field.key === key && field.type === 'secret'))
191
+ if (cleared.length) draft.clearSecrets = cleared
192
+ return draft
193
+ }
194
+
195
+ // ───────────────────────── 样式(只用 --dsw-alias-* token) ─────────────────────────
196
+
197
+ const STYLE_TEXT = `
198
+ .ie-root { display:flex; flex-direction:column; height:100%; min-height:0; color:var(--dsw-alias-label-primary); font-size:13px; }
199
+ .ie-head { display:flex; align-items:center; gap:8px; padding:10px 12px 8px; border-bottom:1px solid var(--dsw-alias-border-l1); }
200
+ .ie-head-title { font-size:13px; font-weight:600; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
201
+ .ie-dot { width:7px; height:7px; border-radius:50%; flex:none; }
202
+ .ie-body { flex:1; min-height:0; overflow:auto; padding:8px 12px 12px; display:flex; flex-direction:column; gap:10px; }
203
+ .ie-group { display:flex; flex-direction:column; gap:6px; }
204
+ .ie-label-row { display:flex; align-items:center; gap:6px; }
205
+ .ie-label-row .ie-label { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
206
+ .ie-label { font-size:11px; font-weight:600; letter-spacing:.04em; color:var(--dsw-alias-label-secondary); text-transform:uppercase; }
207
+ .ie-hint { font-size:11px; color:var(--dsw-alias-label-secondary); line-height:1.5; }
208
+ .ie-icon-btn { display:inline-flex; align-items:center; justify-content:center; height:24px; min-width:24px; padding:0 6px; border-radius:6px; border:1px solid transparent; background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; cursor:pointer; flex:none; }
209
+ .ie-icon-btn:hover { background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); }
210
+ .ie-icon-btn:disabled { opacity:.45; cursor:default; }
211
+ .ie-btn { flex:1; padding:6px 10px; border-radius:7px; border:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); font-size:12px; font-weight:500; cursor:pointer; }
212
+ .ie-btn:hover { border-color:var(--dsw-alias-border-l2); }
213
+ .ie-btn[data-primary='true'] { background:var(--dsw-alias-brand-primary); border-color:var(--dsw-alias-brand-primary); color:#fff; }
214
+ .ie-btn[data-danger='true'] { color:var(--dsw-alias-state-error-primary); border-color:var(--dsw-alias-state-error-primary); }
215
+ .ie-btn:disabled { opacity:.5; cursor:default; }
216
+ .ie-body .ie-btn { flex:none; padding:5px 10px; }
217
+ .ie-actions { display:flex; gap:6px; }
218
+ .ie-chips { display:flex; flex-wrap:wrap; gap:5px; }
219
+ .ie-chip { display:inline-flex; align-items:center; gap:5px; padding:3px 9px; border-radius:999px; border:1px solid var(--dsw-alias-border-l1); background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; cursor:pointer; line-height:18px; }
220
+ .ie-chip:hover { background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); }
221
+ .ie-chip[data-active='true'] { border-color:var(--dsw-alias-brand-primary); color:var(--dsw-alias-brand-primary); background:var(--dsw-alias-bg-layer-2); }
222
+ .ie-chip-count { font-size:10.5px; opacity:.75; }
223
+ .ie-session { border:1px solid var(--dsw-alias-border-l1); border-radius:8px; padding:8px; background:var(--dsw-alias-bg-layer-1); display:flex; flex-direction:column; gap:6px; }
224
+ .ie-session-chips { display:flex; flex-wrap:wrap; gap:5px; }
225
+ .ie-session-chip { display:inline-flex; align-items:center; gap:2px; padding:2px 4px 2px 8px; border-radius:999px; border:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); font-size:11.5px; max-width:100%; }
226
+ .ie-session-chip-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
227
+ .ie-session-chip-x { display:inline-flex; align-items:center; justify-content:center; width:16px; height:16px; padding:0; border:none; border-radius:999px; background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; line-height:1; cursor:pointer; }
228
+ .ie-session-chip-x:hover { background:var(--dsw-alias-bg-layer-1); color:var(--dsw-alias-label-primary); }
229
+ .ie-session-chip-x:disabled { opacity:.45; cursor:default; }
230
+ .ie-list { display:flex; flex-direction:column; gap:4px; }
231
+ .ie-row { display:flex; align-items:center; gap:8px; padding:7px 8px; border-radius:8px; border:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-1); }
232
+ .ie-row:hover { background:var(--dsw-alias-bg-layer-2); }
233
+ .ie-row[data-disabled='true'] { opacity:.55; }
234
+ .ie-check { width:14px; height:14px; flex:none; accent-color:var(--dsw-alias-brand-primary); cursor:pointer; }
235
+ .ie-row-main { flex:1; min-width:0; display:flex; flex-direction:column; gap:2px; }
236
+ .ie-row-line { display:flex; align-items:center; gap:6px; min-width:0; }
237
+ .ie-row-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:12.5px; font-weight:500; }
238
+ .ie-kind { flex:none; padding:1px 5px; border-radius:4px; border:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-secondary); font-size:10.5px; }
239
+ .ie-row-sub { display:flex; align-items:center; gap:2px; min-width:0; color:var(--dsw-alias-label-secondary); font-size:11px; }
240
+ .ie-row-sub > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
241
+ .ie-empty { padding:12px 10px; text-align:center; color:var(--dsw-alias-label-secondary); font-size:12px; }
242
+ .ie-form { border:1px solid var(--dsw-alias-border-l2); border-radius:8px; padding:10px; background:var(--dsw-alias-bg-layer-1); display:flex; flex-direction:column; gap:8px; }
243
+ .ie-form-head { font-size:12.5px; font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
244
+ .ie-form-grid { display:flex; flex-direction:column; gap:8px; }
245
+ .ie-field { display:flex; flex-direction:column; gap:3px; min-width:0; }
246
+ .ie-field-label { display:flex; align-items:center; gap:4px; color:var(--dsw-alias-label-secondary); font-size:11.5px; }
247
+ .ie-req { color:var(--dsw-alias-state-error-primary); }
248
+ .ie-two-col { display:flex; align-items:center; gap:8px; min-width:0; }
249
+ .ie-two-col > .ie-field { flex:1; min-width:0; }
250
+ .ie-two-col > .ie-field-label { flex:1; min-width:0; }
251
+ .ie-input { width:100%; box-sizing:border-box; height:26px; padding:0 8px; border-radius:6px; border:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); font-size:12px; outline:none; }
252
+ .ie-input:focus { border-color:var(--dsw-alias-brand-primary); }
253
+ .ie-switch { position:relative; width:34px; height:20px; flex:none; padding:0; border-radius:999px; border:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-2); cursor:pointer; transition:background .15s; }
254
+ .ie-switch[data-on='true'] { background:var(--dsw-alias-brand-primary); border-color:var(--dsw-alias-brand-primary); }
255
+ .ie-switch-thumb { position:absolute; top:2px; left:2px; width:14px; height:14px; border-radius:50%; background:#fff; transition:transform .15s; }
256
+ .ie-switch[data-on='true'] .ie-switch-thumb { transform:translateX(14px); }
257
+ .ie-form-error { color:var(--dsw-alias-state-error-primary); font-size:11.5px; line-height:1.5; }
258
+ .ie-test-ok { color:var(--dsw-alias-state-success-primary); font-size:11.5px; line-height:1.5; }
259
+ .ie-test-fail { color:var(--dsw-alias-state-error-primary); font-size:11.5px; line-height:1.5; }
260
+ .ie-notice { font-size:11.5px; color:var(--dsw-alias-label-secondary); min-height:16px; line-height:1.5; }
261
+ .ie-error { border:1px solid var(--dsw-alias-state-error-primary); border-radius:8px; padding:10px; font-size:12px; color:var(--dsw-alias-state-error-primary); display:flex; flex-direction:column; gap:8px; }
262
+ .ie-open-btn { display:inline-flex; align-items:center; gap:5px; height:26px; padding:0 9px; border-radius:6px; border:1px solid var(--dsw-alias-border-l1); background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; cursor:pointer; }
263
+ .ie-open-btn:hover { background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); }
264
+ `
265
+
266
+ // ───────────────────────── 面板主体 ─────────────────────────
267
+
268
+ /** 右栏标签页主体。所有 props 都按可选处理,拿不到不能崩。 */
269
+ function IntegrationEnvTab(props) {
270
+ const safeProps = props && typeof props === 'object' ? props : {}
271
+ const sessionId = typeof safeProps.sessionId === 'string' ? safeProps.sessionId : ''
272
+ const useInput = safeProps.useInput
273
+ const inputActions = safeProps.inputActions
274
+ const useTabInfo = safeProps.useTabInfo
275
+
276
+ // 框架提供的 tab 信息钩子;缺失时当作可见,保证不会因为它而崩。
277
+ const tabInfo = typeof useTabInfo === 'function' ? useTabInfo() : null
278
+ const visible = tabInfo && tabInfo.tab ? tabInfo.tab.visible !== false : true
279
+
280
+ // 输入框草稿:编辑器拒绝插入时回退为整段替换。
281
+ const draft = typeof useInput === 'function' ? useInput((state) => (state ? state.draft : '')) : ''
282
+
283
+ const prefs = React.useRef(loadPrefs())
284
+ const mountedAbort = React.useRef(null)
285
+ const lastVisible = React.useRef(visible)
286
+
287
+ const [catalog, setCatalog] = React.useState(null)
288
+ const [loading, setLoading] = React.useState(true)
289
+ const [error, setError] = React.useState(null)
290
+ const [refreshTick, setRefreshTick] = React.useState(0)
291
+ const [kindFilter, setKindFilter] = React.useState(
292
+ prefs.current && typeof prefs.current.kindFilter === 'string' ? prefs.current.kindFilter : 'all',
293
+ )
294
+ const [form, setForm] = React.useState(null)
295
+ const [formError, setFormError] = React.useState('')
296
+ const [formTest, setFormTest] = React.useState(null)
297
+ const [deleteArmed, setDeleteArmed] = React.useState(false)
298
+ const [busy, setBusy] = React.useState('')
299
+ const [notice, setNotice] = React.useState('')
300
+ const [testResults, setTestResults] = React.useState({})
301
+
302
+ // 组件级 AbortController:卸载时中断所有进行中的请求。
303
+ React.useEffect(() => {
304
+ const controller = new AbortController()
305
+ mountedAbort.current = controller
306
+ return () => {
307
+ mountedAbort.current = null
308
+ controller.abort()
309
+ }
310
+ }, [])
311
+
312
+ // 挂载 + 每次刷新 tick 拉一次 catalog。
313
+ React.useEffect(() => {
314
+ const controller = new AbortController()
315
+ let alive = true
316
+ setLoading(true)
317
+ setError(null)
318
+ callApi('catalog', sessionId ? { sessionId } : {}, controller.signal)
319
+ .then((value) => {
320
+ if (!alive) return
321
+ setCatalog(value)
322
+ setLoading(false)
323
+ })
324
+ .catch((failure) => {
325
+ if (!alive || isAbort(failure)) return
326
+ setError(errorMessage(failure))
327
+ setLoading(false)
328
+ })
329
+ return () => {
330
+ alive = false
331
+ controller.abort()
332
+ }
333
+ }, [refreshTick, sessionId])
334
+
335
+ // 切到本标签(不可见 → 可见)时刷新一次。
336
+ React.useEffect(() => {
337
+ const wasVisible = lastVisible.current
338
+ lastVisible.current = visible
339
+ if (visible && !wasVisible) setRefreshTick((tick) => tick + 1)
340
+ }, [visible])
341
+
342
+ // 只持久化筛选条件。
343
+ React.useEffect(() => {
344
+ savePrefs({ kindFilter })
345
+ }, [kindFilter])
346
+
347
+ // 上次筛选的 kind 被删掉后回到「全部」。
348
+ React.useEffect(() => {
349
+ if (!catalog) return
350
+ const list = Array.isArray(catalog.kinds) ? catalog.kinds : []
351
+ if (kindFilter !== 'all' && !list.some((item) => item && item.id === kindFilter)) setKindFilter('all')
352
+ }, [catalog, kindFilter])
353
+
354
+ const kinds = catalog && Array.isArray(catalog.kinds) ? catalog.kinds : []
355
+ const instances = catalog && Array.isArray(catalog.instances) ? catalog.instances : []
356
+ const storage = (catalog && catalog.storage) || {}
357
+ const session = (catalog && catalog.session) || {}
358
+ const stats = (catalog && catalog.stats) || {}
359
+ const byKind = stats && stats.byKind && typeof stats.byKind === 'object' ? stats.byKind : {}
360
+ const activeIds = Array.isArray(session.activeIds) ? session.activeIds : []
361
+ const storageWritable = storage.writable !== false
362
+ const sessionIdValue = sessionId || (typeof session.id === 'string' ? session.id : '')
363
+
364
+ function kindById(id) {
365
+ return kinds.find((item) => item && item.id === id) || null
366
+ }
367
+
368
+ function instanceById(id) {
369
+ return instances.find((item) => item && item.id === id) || null
370
+ }
371
+
372
+ const activeInstances = activeIds.map((id) => instanceById(id)).filter(Boolean)
373
+ const visibleInstances = kindFilter === 'all' ? instances : instances.filter((item) => item && item.kind === kindFilter)
374
+
375
+ const filterChips = [{ id: 'all', label: '全部', count: instances.length }].concat(
376
+ kinds.map((item) => {
377
+ const counted = typeof byKind[item.id] === 'number' ? byKind[item.id] : instances.filter((one) => one.kind === item.id).length
378
+ return { id: item.id, label: item.label || item.id, count: counted }
379
+ }),
380
+ )
381
+
382
+ /** 统一取请求信号;卸载后为 undefined,交给 fetch 自己处理。 */
383
+ function actionSignal() {
384
+ return mountedAbort.current ? mountedAbort.current.signal : undefined
385
+ }
386
+
387
+ /** 把 session.setActive / session.toggle 的结果合并回 catalog。 */
388
+ function applySession(sessionValue) {
389
+ if (!sessionValue || typeof sessionValue !== 'object') return
390
+ const ids = Array.isArray(sessionValue.activeIds) ? sessionValue.activeIds : []
391
+ setCatalog((prev) => {
392
+ if (!prev) return prev
393
+ return {
394
+ ...prev,
395
+ session: { ...(prev.session || {}), ...sessionValue },
396
+ instances: (prev.instances || []).map((item) => ({ ...item, activeForSession: ids.indexOf(item.id) !== -1 })),
397
+ }
398
+ })
399
+ }
400
+
401
+ function handleRefresh() {
402
+ if (busy) return
403
+ setRefreshTick((tick) => tick + 1)
404
+ }
405
+
406
+ /** 勾选框 = 本会话启用;调 session.toggle。 */
407
+ async function handleToggle(instance) {
408
+ if (!instance || busy) return
409
+ if (!sessionIdValue) {
410
+ setNotice('当前拿不到会话 id,无法保存本会话的启用选择(请在实际会话里打开这个面板)')
411
+ return
412
+ }
413
+ const target = activeIds.indexOf(instance.id) === -1
414
+ setBusy(`toggle:${instance.id}`)
415
+ try {
416
+ const value = await callApi(
417
+ 'session.toggle',
418
+ { sessionId: sessionIdValue, id: instance.id, active: target },
419
+ actionSignal(),
420
+ )
421
+ applySession(value && value.session)
422
+ setNotice(`${target ? '已启用' : '已停用'}「${instance.name}」`)
423
+ } catch (failure) {
424
+ if (!isAbort(failure)) setNotice(`切换失败:${errorMessage(failure)}`)
425
+ } finally {
426
+ setBusy('')
427
+ }
428
+ }
429
+
430
+ /** 清空本会话启用(不影响 Host 的默认启用)。 */
431
+ async function handleClear() {
432
+ if (busy) return
433
+ if (!sessionIdValue) {
434
+ setNotice('当前拿不到会话 id,无法修改本会话启用')
435
+ return
436
+ }
437
+ setBusy('clear')
438
+ try {
439
+ const value = await callApi('session.setActive', { sessionId: sessionIdValue, ids: [] }, actionSignal())
440
+ applySession(value && value.session)
441
+ setNotice('已清空本会话启用')
442
+ } catch (failure) {
443
+ if (!isAbort(failure)) setNotice(`清空失败:${errorMessage(failure)}`)
444
+ } finally {
445
+ setBusy('')
446
+ }
447
+ }
448
+
449
+ /** 插入上下文:prompt.preview 的文本写进输入框,失败按 log-context 的方式回退 setDraft。 */
450
+ async function handleInsert() {
451
+ if (busy) return
452
+ if (!inputActions) {
453
+ setNotice('当前没有可写入的输入框')
454
+ return
455
+ }
456
+ setBusy('insert')
457
+ try {
458
+ let text = ''
459
+ if (sessionIdValue) {
460
+ const value = await callApi('prompt.preview', { sessionId: sessionIdValue }, actionSignal())
461
+ if (value && typeof value.text === 'string') text = value.text
462
+ }
463
+ if (!text && session && typeof session.promptText === 'string') text = session.promptText
464
+ if (!text) throw new Error('Host 没有返回可插入的上下文内容')
465
+ try {
466
+ const span = inputActions.captureInsertion()
467
+ if (inputActions.insertText(text, span)) {
468
+ setNotice('已插入到输入框,补一句问题即可发送')
469
+ return
470
+ }
471
+ } catch {
472
+ /* 落到下面的回退路径 */
473
+ }
474
+ inputActions.setDraft((draft ? draft + '\n' : '') + text)
475
+ setNotice('已写入输入框')
476
+ } catch (failure) {
477
+ if (isAbort(failure)) return
478
+ // 接口失败时至少用 catalog 里已有的提示块,不让用户白点一次。
479
+ const fallbackText = session && typeof session.promptText === 'string' ? session.promptText : ''
480
+ if (fallbackText) {
481
+ try {
482
+ inputActions.setDraft((draft ? draft + '\n' : '') + fallbackText)
483
+ setNotice(`prompt.preview 调用失败(${errorMessage(failure)}),已用面板里的上下文写入输入框`)
484
+ return
485
+ } catch (writeFailure) {
486
+ setNotice(`写入失败:${errorMessage(writeFailure)}`)
487
+ return
488
+ }
489
+ }
490
+ setNotice(`插入失败:${errorMessage(failure)}`)
491
+ } finally {
492
+ setBusy('')
493
+ }
494
+ }
495
+
496
+ /** 打开新增表单。 */
497
+ function openCreate() {
498
+ const fallback = kindFilter !== 'all' ? kindById(kindFilter) : kinds[0]
499
+ if (!fallback) {
500
+ setNotice('Host 没有返回可用的实例类型(kinds),先刷新试试')
501
+ return
502
+ }
503
+ setForm({
504
+ mode: 'create',
505
+ id: '',
506
+ kind: fallback.id,
507
+ name: '',
508
+ note: '',
509
+ enabled: true,
510
+ config: defaultConfigForKind(fallback),
511
+ secrets: {},
512
+ clearSecrets: [],
513
+ })
514
+ setFormError('')
515
+ setFormTest(null)
516
+ setDeleteArmed(false)
517
+ setNotice('')
518
+ }
519
+
520
+ /** 打开编辑表单。 */
521
+ function openEdit(instance) {
522
+ const kind = kindById(instance.kind)
523
+ setForm({
524
+ mode: 'edit',
525
+ id: instance.id,
526
+ kind: instance.kind,
527
+ name: instance.name || '',
528
+ note: instance.note || '',
529
+ enabled: instance.enabled !== false,
530
+ config: configForInstance(kind, instance),
531
+ secrets: instance.secrets && typeof instance.secrets === 'object' ? { ...instance.secrets } : {},
532
+ clearSecrets: [],
533
+ })
534
+ setFormError('')
535
+ setFormTest(null)
536
+ setDeleteArmed(false)
537
+ setNotice('')
538
+ }
539
+
540
+ function closeForm() {
541
+ setForm(null)
542
+ setFormError('')
543
+ setFormTest(null)
544
+ setDeleteArmed(false)
545
+ }
546
+
547
+ /** 表单顶层字段(名称 / 备注 / 启用)。 */
548
+ function updateForm(patch) {
549
+ setForm((prev) => (prev ? { ...prev, ...patch } : prev))
550
+ setFormError('')
551
+ setFormTest(null)
552
+ setDeleteArmed(false)
553
+ }
554
+
555
+ /** 动态字段值变化:保留原始输入(number 在提交时再转)。 */
556
+ function setFieldValue(key, value) {
557
+ setForm((prev) => (prev ? { ...prev, config: { ...(prev.config || {}), [key]: value } } : prev))
558
+ setFormError('')
559
+ setFormTest(null)
560
+ }
561
+
562
+ /** 显式标记清除某个 secret(再点一次取消)。 */
563
+ function toggleClearSecret(key) {
564
+ setForm((prev) => {
565
+ if (!prev) return prev
566
+ const list = Array.isArray(prev.clearSecrets) ? prev.clearSecrets.slice() : []
567
+ const index = list.indexOf(key)
568
+ if (index >= 0) list.splice(index, 1)
569
+ else list.push(key)
570
+ return { ...prev, clearSecrets: list, config: { ...(prev.config || {}), [key]: '' } }
571
+ })
572
+ setFormError('')
573
+ setFormTest(null)
574
+ }
575
+
576
+ /** 新增时切换 kind:整份 config 换成新 kind 的默认值。 */
577
+ function handleKindChange(kindIdValue) {
578
+ const kind = kindById(kindIdValue)
579
+ setForm((prev) =>
580
+ prev ? { ...prev, kind: kindIdValue, config: defaultConfigForKind(kind), secrets: {}, clearSecrets: [] } : prev,
581
+ )
582
+ setFormError('')
583
+ setFormTest(null)
584
+ }
585
+
586
+ /** 保存:新增 / 整体替换。 */
587
+ async function handleSave() {
588
+ if (!form || busy) return
589
+ const kind = kindById(form.kind)
590
+ if (!kind) {
591
+ setFormError('请选择实例类型')
592
+ return
593
+ }
594
+ const instanceDraft = buildDraftFromForm(form, kind)
595
+ if (!instanceDraft.name) {
596
+ setFormError('请填写名称:模型和其它工具都用它来引用这个实例')
597
+ return
598
+ }
599
+ setBusy('save')
600
+ setFormError('')
601
+ try {
602
+ const payload = Object.assign({}, sessionIdValue ? { sessionId: sessionIdValue } : {}, { instance: instanceDraft })
603
+ const value = await callApi('instance.save', payload, actionSignal())
604
+ const saved = value && value.instance ? value.instance : null
605
+ closeForm()
606
+ setNotice(saved ? `已保存「${saved.name}」` : '已保存')
607
+ setRefreshTick((tick) => tick + 1)
608
+ } catch (failure) {
609
+ if (!isAbort(failure)) setFormError(errorMessage(failure))
610
+ } finally {
611
+ setBusy('')
612
+ }
613
+ }
614
+
615
+ /** 表单内试连:未保存用 draft(编辑态带上 id,Host 可复用已存 secret)。 */
616
+ async function handleTestForm() {
617
+ if (!form || busy) return
618
+ const kind = kindById(form.kind)
619
+ if (!kind) {
620
+ setFormError('请选择实例类型')
621
+ return
622
+ }
623
+ setBusy('test-form')
624
+ setFormTest(null)
625
+ setFormError('')
626
+ try {
627
+ const value = await callApi('instance.test', { draft: buildDraftFromForm(form, kind) }, actionSignal())
628
+ if (value && value.ok) {
629
+ const latency = typeof value.latencyMs === 'number' ? ` · ${value.latencyMs}ms` : ''
630
+ const detail = value.detail ? ` · ${value.detail}` : ''
631
+ setFormTest({ ok: true, text: `连接成功${latency}${detail}` })
632
+ } else {
633
+ setFormTest({ ok: false, text: value && value.error ? value.error : '连接失败(Host 没有给出原因)' })
634
+ }
635
+ } catch (failure) {
636
+ if (!isAbort(failure)) setFormTest({ ok: false, text: errorMessage(failure) })
637
+ } finally {
638
+ setBusy('')
639
+ }
640
+ }
641
+
642
+ /** 删除:第一次点击只进入确认态,第二次才真的删。 */
643
+ async function handleDelete() {
644
+ if (!form || busy) return
645
+ if (form.mode !== 'edit' || !form.id) return
646
+ if (!deleteArmed) {
647
+ setDeleteArmed(true)
648
+ setFormError('删除不可恢复:再点一次「确认删除」才会真正删除')
649
+ return
650
+ }
651
+ setBusy('delete')
652
+ setFormError('')
653
+ try {
654
+ const name = form.name || form.id
655
+ await callApi('instance.delete', { id: form.id }, actionSignal())
656
+ closeForm()
657
+ setNotice(`已删除「${name}」`)
658
+ setRefreshTick((tick) => tick + 1)
659
+ } catch (failure) {
660
+ if (!isAbort(failure)) setFormError(errorMessage(failure))
661
+ } finally {
662
+ setBusy('')
663
+ }
664
+ }
665
+
666
+ /** 实例行上的连通测试。 */
667
+ async function handleTest(instance) {
668
+ if (!instance || busy) return
669
+ setBusy(`test:${instance.id}`)
670
+ try {
671
+ const value = await callApi('instance.test', { id: instance.id }, actionSignal())
672
+ if (value && typeof value === 'object') {
673
+ setTestResults((prev) => ({ ...prev, [instance.id]: value }))
674
+ setNotice(`「${instance.name}」${testSummary(value)}`)
675
+ } else {
676
+ setTestResults((prev) => ({ ...prev, [instance.id]: { ok: false, error: 'Host 返回了空结果' } }))
677
+ setNotice(`「${instance.name}」测试失败:Host 返回了空结果`)
678
+ }
679
+ } catch (failure) {
680
+ if (!isAbort(failure)) {
681
+ setTestResults((prev) => ({ ...prev, [instance.id]: { ok: false, error: errorMessage(failure) } }))
682
+ setNotice(`「${instance.name}」测试失败:${errorMessage(failure)}`)
683
+ }
684
+ } finally {
685
+ setBusy('')
686
+ }
687
+ }
688
+
689
+ /** 一个实例行:勾选框 + 名称/类型/摘要/备注 + 测试/编辑。 */
690
+ function renderInstanceRow(instance) {
691
+ const active = activeIds.indexOf(instance.id) !== -1
692
+ const result = testResults[instance.id] || null
693
+ const testing = busy === `test:${instance.id}`
694
+ return h(
695
+ 'div',
696
+ { key: instance.id, className: 'ie-row', 'data-disabled': instance.enabled === false ? 'true' : 'false' },
697
+ h('input', {
698
+ type: 'checkbox',
699
+ className: 'ie-check',
700
+ checked: active,
701
+ disabled: busy !== '',
702
+ 'aria-label': `本会话启用「${instance.name}」`,
703
+ title: active ? '本会话已启用,取消勾选可移除' : '勾选后本会话启用该实例',
704
+ onChange: () => handleToggle(instance),
705
+ }),
706
+ h(
707
+ 'div',
708
+ { className: 'ie-row-main' },
709
+ h(
710
+ 'div',
711
+ { className: 'ie-row-line' },
712
+ h('span', { className: 'ie-row-name', title: instance.name }, instance.name),
713
+ h('span', { className: 'ie-kind' }, instance.kindLabel || instance.kind),
714
+ instance.enabled === false ? h('span', { className: 'ie-kind' }, '已停用') : null,
715
+ ),
716
+ h(
717
+ 'div',
718
+ { className: 'ie-row-sub' },
719
+ h('span', { title: instance.summary || '' }, instance.summary || '(无摘要)'),
720
+ instance.note ? h('span', { title: instance.note }, ` · ${instance.note}`) : null,
721
+ ),
722
+ ),
723
+ result
724
+ ? h('span', {
725
+ className: 'ie-dot',
726
+ style: {
727
+ background: result.ok
728
+ ? 'var(--dsw-alias-state-success-primary)'
729
+ : 'var(--dsw-alias-state-error-primary)',
730
+ },
731
+ title: testSummary(result),
732
+ })
733
+ : null,
734
+ h(
735
+ 'button',
736
+ {
737
+ type: 'button',
738
+ className: 'ie-icon-btn',
739
+ disabled: busy !== '',
740
+ title: '测试这个实例的连通性',
741
+ onClick: () => handleTest(instance),
742
+ },
743
+ testing ? '测试中…' : '测试',
744
+ ),
745
+ h(
746
+ 'button',
747
+ {
748
+ type: 'button',
749
+ className: 'ie-icon-btn',
750
+ disabled: busy !== '',
751
+ title: `编辑「${instance.name}」`,
752
+ onClick: () => openEdit(instance),
753
+ },
754
+ '编辑',
755
+ ),
756
+ )
757
+ }
758
+
759
+ /** 按 kind.fields 动态渲染一个字段。 */
760
+ function renderField(field) {
761
+ if (!field || typeof field.key !== 'string') return null
762
+ const value = form.config ? form.config[field.key] : undefined
763
+ const labelNode = h(
764
+ 'span',
765
+ { className: 'ie-field-label' },
766
+ field.label || field.key,
767
+ field.required ? h('span', { className: 'ie-req' }, '*') : null,
768
+ )
769
+ if (field.type === 'boolean') {
770
+ const on = value === true
771
+ return h(
772
+ 'div',
773
+ { className: 'ie-field', key: field.key },
774
+ h(
775
+ 'div',
776
+ { className: 'ie-two-col' },
777
+ labelNode,
778
+ h(
779
+ 'button',
780
+ {
781
+ type: 'button',
782
+ className: 'ie-switch',
783
+ role: 'switch',
784
+ 'aria-checked': on,
785
+ 'aria-label': field.label || field.key,
786
+ 'data-on': on ? 'true' : 'false',
787
+ title: field.help || '',
788
+ onClick: () => setFieldValue(field.key, !on),
789
+ },
790
+ h('span', { className: 'ie-switch-thumb' }),
791
+ ),
792
+ ),
793
+ field.help ? h('span', { className: 'ie-hint' }, field.help) : null,
794
+ )
795
+ }
796
+ const isSecret = field.type === 'secret'
797
+ const secretSet = Boolean(form.secrets && form.secrets[field.key])
798
+ const clearArmed = Array.isArray(form.clearSecrets) && form.clearSecrets.indexOf(field.key) !== -1
799
+ let control
800
+ if (field.type === 'select') {
801
+ const options = Array.isArray(field.options) ? field.options : []
802
+ control = h(
803
+ 'select',
804
+ {
805
+ className: 'ie-input',
806
+ value: value === undefined || value === null ? '' : String(value),
807
+ onChange: (event) => setFieldValue(field.key, event.target.value),
808
+ },
809
+ options.map((option) =>
810
+ h('option', { key: String(option.value), value: String(option.value) }, String(option.label === undefined ? option.value : option.label)),
811
+ ),
812
+ )
813
+ } else if (field.type === 'number') {
814
+ control = h('input', {
815
+ className: 'ie-input',
816
+ type: 'number',
817
+ value: value === undefined || value === null ? '' : String(value),
818
+ min: field.min === undefined ? undefined : field.min,
819
+ max: field.max === undefined ? undefined : field.max,
820
+ placeholder: field.placeholder || '',
821
+ onChange: (event) => setFieldValue(field.key, event.target.value),
822
+ })
823
+ } else {
824
+ control = h('input', {
825
+ className: 'ie-input',
826
+ type: isSecret ? 'password' : 'text',
827
+ autoComplete: isSecret ? 'new-password' : undefined,
828
+ value: value === undefined || value === null ? '' : String(value),
829
+ placeholder: isSecret
830
+ ? clearArmed
831
+ ? '标记清除,保存后生效'
832
+ : secretSet
833
+ ? '已设置(留空保持不变)'
834
+ : field.placeholder || ''
835
+ : field.placeholder || '',
836
+ onChange: (event) => setFieldValue(field.key, event.target.value),
837
+ })
838
+ }
839
+ return h(
840
+ 'div',
841
+ { className: 'ie-field', key: field.key },
842
+ h(
843
+ 'div',
844
+ { className: 'ie-two-col' },
845
+ labelNode,
846
+ isSecret
847
+ ? h(
848
+ 'button',
849
+ {
850
+ type: 'button',
851
+ className: 'ie-icon-btn',
852
+ title: secretSet ? '保存时清除已保存的值' : '当前没有已保存的值',
853
+ disabled: busy !== '',
854
+ onClick: () => toggleClearSecret(field.key),
855
+ },
856
+ clearArmed ? '取消清除' : '清除密码',
857
+ )
858
+ : null,
859
+ ),
860
+ control,
861
+ field.help ? h('span', { className: 'ie-hint' }, field.help) : null,
862
+ )
863
+ }
864
+
865
+ /** 内联新增 / 编辑表单。 */
866
+ function renderForm() {
867
+ if (!form) return null
868
+ const kind = kindById(form.kind)
869
+ const fields = kind && Array.isArray(kind.fields) ? kind.fields : []
870
+ return h(
871
+ 'div',
872
+ { className: 'ie-form', key: 'form' },
873
+ h('div', { className: 'ie-form-head' }, form.mode === 'edit' ? `编辑「${form.name || form.id}」` : '新增实例'),
874
+ h(
875
+ 'div',
876
+ { className: 'ie-field' },
877
+ h('span', { className: 'ie-field-label' }, '名称', h('span', { className: 'ie-req' }, '*')),
878
+ h('input', {
879
+ className: 'ie-input',
880
+ value: form.name,
881
+ placeholder: '例如:示例库',
882
+ onChange: (event) => updateForm({ name: event.target.value }),
883
+ }),
884
+ ),
885
+ h(
886
+ 'div',
887
+ { className: 'ie-field' },
888
+ h('span', { className: 'ie-field-label' }, '备注'),
889
+ h('input', {
890
+ className: 'ie-input',
891
+ value: form.note,
892
+ placeholder: '可选,例如:demo_db',
893
+ onChange: (event) => updateForm({ note: event.target.value }),
894
+ }),
895
+ ),
896
+ h(
897
+ 'div',
898
+ { className: 'ie-two-col' },
899
+ h(
900
+ 'div',
901
+ { className: 'ie-field' },
902
+ h('span', { className: 'ie-field-label' }, '类型'),
903
+ form.mode === 'edit'
904
+ ? h('span', { className: 'ie-kind', style: { alignSelf: 'flex-start' } }, kind ? kind.label || kind.id : form.kind)
905
+ : h(
906
+ 'select',
907
+ {
908
+ className: 'ie-input',
909
+ value: form.kind,
910
+ onChange: (event) => handleKindChange(event.target.value),
911
+ },
912
+ kinds.map((item) => h('option', { key: item.id, value: item.id }, item.label || item.id)),
913
+ ),
914
+ kind && kind.connectable === false ? h('span', { className: 'ie-hint' }, '该类型 v1 只做配置与端口连通测试') : null,
915
+ ),
916
+ h(
917
+ 'div',
918
+ { className: 'ie-field' },
919
+ h('span', { className: 'ie-field-label' }, '启用'),
920
+ h(
921
+ 'button',
922
+ {
923
+ type: 'button',
924
+ className: 'ie-switch',
925
+ role: 'switch',
926
+ 'aria-checked': form.enabled !== false,
927
+ 'aria-label': '实例启用',
928
+ 'data-on': form.enabled !== false ? 'true' : 'false',
929
+ title: '停用后不会出现在工具和提示块里',
930
+ onClick: () => updateForm({ enabled: form.enabled === false }),
931
+ },
932
+ h('span', { className: 'ie-switch-thumb' }),
933
+ ),
934
+ ),
935
+ ),
936
+ fields.length === 0
937
+ ? h('div', { className: 'ie-hint' }, '该类型没有可配置字段')
938
+ : h('div', { className: 'ie-form-grid' }, fields.map((field) => renderField(field))),
939
+ formError ? h('span', { className: 'ie-form-error' }, formError) : null,
940
+ formTest ? h('span', { className: formTest.ok ? 'ie-test-ok' : 'ie-test-fail' }, formTest.text) : null,
941
+ h(
942
+ 'div',
943
+ { className: 'ie-actions' },
944
+ h(
945
+ 'button',
946
+ { type: 'button', className: 'ie-btn', 'data-primary': 'true', disabled: busy !== '', onClick: handleSave },
947
+ busy === 'save' ? '保存中…' : '保存',
948
+ ),
949
+ h('button', { type: 'button', className: 'ie-btn', disabled: busy !== '', onClick: closeForm }, '取消'),
950
+ ),
951
+ h(
952
+ 'div',
953
+ { className: 'ie-actions' },
954
+ h(
955
+ 'button',
956
+ { type: 'button', className: 'ie-btn', disabled: busy !== '', onClick: handleTestForm },
957
+ busy === 'test-form' ? '测试中…' : '测试连接',
958
+ ),
959
+ form.mode === 'edit'
960
+ ? h(
961
+ 'button',
962
+ {
963
+ type: 'button',
964
+ className: 'ie-btn',
965
+ 'data-danger': 'true',
966
+ disabled: busy !== '',
967
+ onClick: handleDelete,
968
+ },
969
+ busy === 'delete' ? '删除中…' : deleteArmed ? '确认删除' : '删除',
970
+ )
971
+ : null,
972
+ ),
973
+ )
974
+ }
975
+
976
+ return h(
977
+ 'div',
978
+ { className: 'ie-root' },
979
+ h('style', null, STYLE_TEXT),
980
+ h(
981
+ 'div',
982
+ { className: 'ie-head' },
983
+ h('span', {
984
+ className: 'ie-dot',
985
+ style: {
986
+ background: !catalog
987
+ ? 'var(--dsw-alias-state-idle-primary)'
988
+ : storageWritable
989
+ ? 'var(--dsw-alias-state-success-primary)'
990
+ : 'var(--dsw-alias-state-error-primary)',
991
+ },
992
+ title: !catalog
993
+ ? '正在读取存储状态'
994
+ : storageWritable
995
+ ? `数据文件可写${storage.file ? `:${storage.file}` : ''}`
996
+ : `数据文件不可写${storage.error ? `:${storage.error}` : storage.file ? `:${storage.file}` : ''}`,
997
+ }),
998
+ h('span', { className: 'ie-head-title' }, '集成环境'),
999
+ h(
1000
+ 'button',
1001
+ {
1002
+ type: 'button',
1003
+ className: 'ie-icon-btn',
1004
+ title: '刷新实例列表与存储状态',
1005
+ disabled: loading || busy !== '',
1006
+ onClick: handleRefresh,
1007
+ },
1008
+ loading ? '刷新中' : '刷新',
1009
+ ),
1010
+ ),
1011
+ h(
1012
+ 'div',
1013
+ { className: 'ie-body' },
1014
+ error
1015
+ ? h(
1016
+ 'div',
1017
+ { className: 'ie-error' },
1018
+ h('span', null, error),
1019
+ h('span', { className: 'ie-hint' }, '请确认 Host 半已随插件启用;改完配置后再重试一次。'),
1020
+ h('button', { type: 'button', className: 'ie-btn', onClick: handleRefresh }, '重试'),
1021
+ )
1022
+ : null,
1023
+ !catalog && loading ? h('div', { className: 'ie-empty' }, '正在读取集成环境配置…') : null,
1024
+ catalog
1025
+ ? [
1026
+ // 本会话启用
1027
+ h(
1028
+ 'div',
1029
+ { className: 'ie-group', key: 'session' },
1030
+ h(
1031
+ 'div',
1032
+ { className: 'ie-label-row' },
1033
+ h('span', { className: 'ie-label' }, `本会话启用(${activeIds.length})`),
1034
+ h(
1035
+ 'button',
1036
+ {
1037
+ type: 'button',
1038
+ className: 'ie-icon-btn',
1039
+ disabled: busy !== '',
1040
+ title: '把 Host 生成的【集成环境】提示块插入输入框',
1041
+ onClick: handleInsert,
1042
+ },
1043
+ busy === 'insert' ? '插入中…' : '插入上下文',
1044
+ ),
1045
+ h(
1046
+ 'button',
1047
+ {
1048
+ type: 'button',
1049
+ className: 'ie-icon-btn',
1050
+ disabled: busy !== '' || activeIds.length === 0,
1051
+ title: '清空本会话的启用选择(不影响默认启用)',
1052
+ onClick: handleClear,
1053
+ },
1054
+ '清空',
1055
+ ),
1056
+ ),
1057
+ h(
1058
+ 'div',
1059
+ { className: 'ie-session' },
1060
+ activeInstances.length === 0
1061
+ ? h('div', { className: 'ie-empty' }, '本会话还没有启用实例')
1062
+ : h(
1063
+ 'div',
1064
+ { className: 'ie-session-chips' },
1065
+ activeInstances.map((item) =>
1066
+ h(
1067
+ 'span',
1068
+ {
1069
+ key: item.id,
1070
+ className: 'ie-session-chip',
1071
+ title: `${item.kindLabel || item.kind} · ${item.summary || ''}`,
1072
+ },
1073
+ h('span', { className: 'ie-session-chip-name' }, item.name),
1074
+ h(
1075
+ 'button',
1076
+ {
1077
+ type: 'button',
1078
+ className: 'ie-session-chip-x',
1079
+ title: `从本会话移除「${item.name}」`,
1080
+ disabled: busy !== '',
1081
+ onClick: () => handleToggle(item),
1082
+ },
1083
+ '×',
1084
+ ),
1085
+ ),
1086
+ ),
1087
+ ),
1088
+ ),
1089
+ h(
1090
+ 'span',
1091
+ { className: 'ie-hint' },
1092
+ '勾选下面的实例,本会话就会用它们;模型通过 integration_env_list 读取同一份选择。',
1093
+ ),
1094
+ ),
1095
+ // 筛选 + 实例列表
1096
+ h(
1097
+ 'div',
1098
+ { className: 'ie-group', key: 'instances' },
1099
+ h(
1100
+ 'div',
1101
+ { className: 'ie-label-row' },
1102
+ h('span', { className: 'ie-label' }, `实例(${visibleInstances.length})`),
1103
+ h(
1104
+ 'button',
1105
+ {
1106
+ type: 'button',
1107
+ className: 'ie-icon-btn',
1108
+ disabled: busy !== '' || kinds.length === 0,
1109
+ title: '新增一个实例',
1110
+ onClick: openCreate,
1111
+ },
1112
+ '新增实例',
1113
+ ),
1114
+ ),
1115
+ h(
1116
+ 'div',
1117
+ { className: 'ie-chips' },
1118
+ filterChips.map((chip) =>
1119
+ h(
1120
+ 'button',
1121
+ {
1122
+ key: chip.id,
1123
+ type: 'button',
1124
+ className: 'ie-chip',
1125
+ 'data-active': kindFilter === chip.id ? 'true' : 'false',
1126
+ onClick: () => setKindFilter(chip.id),
1127
+ },
1128
+ h('span', null, chip.label),
1129
+ h('span', { className: 'ie-chip-count' }, String(chip.count)),
1130
+ ),
1131
+ ),
1132
+ ),
1133
+ visibleInstances.length === 0
1134
+ ? h(
1135
+ 'div',
1136
+ { className: 'ie-empty' },
1137
+ instances.length === 0 ? '还没有配置实例,点「新增实例」开始' : '这个类型下还没有实例',
1138
+ )
1139
+ : h('div', { className: 'ie-list' }, visibleInstances.map((item) => renderInstanceRow(item))),
1140
+ ),
1141
+ // 内联表单放在列表下方
1142
+ renderForm(),
1143
+ ]
1144
+ : null,
1145
+ h('div', { className: 'ie-notice' }, busyText(busy) || notice),
1146
+ ),
1147
+ )
1148
+ }
1149
+
1150
+ // ───────────────────────── 输入框入口按钮 ─────────────────────────
1151
+
1152
+ /** 输入框左侧的入口按钮:打开右栏标签。 */
1153
+ function makeOpenButton(sidebarRight) {
1154
+ return function OpenIntegrationEnvButton() {
1155
+ return h(
1156
+ React.Fragment,
1157
+ null,
1158
+ h('style', null, STYLE_TEXT),
1159
+ h(
1160
+ 'button',
1161
+ {
1162
+ type: 'button',
1163
+ className: 'ie-open-btn',
1164
+ title: '打开集成环境面板(配置 Nacos / MySQL / Redis 实例并按会话勾选)',
1165
+ onClick: () => {
1166
+ try {
1167
+ sidebarRight.openTab(KIND)
1168
+ } catch (failure) {
1169
+ console.error('[integration-env] 打开右栏标签失败:', failure)
1170
+ }
1171
+ },
1172
+ },
1173
+ '集成环境',
1174
+ ),
1175
+ )
1176
+ }
1177
+ }
1178
+
1179
+ return {
1180
+ inject: ['slots'],
1181
+ // 自检用的纯函数出口;Loader 只读取 inject / apply,忽略其余字段。
1182
+ internals: { KIND, IMPL_ID, API_URL, defaultConfigForKind, configForInstance, buildDraftFromForm, testSummary },
1183
+ apply(ctx) {
1184
+ ctx.inject(['sidebarRightTabs', 'sidebarRight'], (injected) => {
1185
+ const tabs = injected.get('sidebarRightTabs')
1186
+ const sidebarRight = injected.get('sidebarRight')
1187
+ if (!tabs || !sidebarRight) return undefined
1188
+
1189
+ const disposers = []
1190
+ disposers.push(
1191
+ tabs.register({
1192
+ id: IMPL_ID,
1193
+ kind: KIND,
1194
+ keepMounted: true,
1195
+ priority: 'extension',
1196
+ title: () => '集成环境',
1197
+ guide: [
1198
+ {
1199
+ id: 'integration-env',
1200
+ order: 21,
1201
+ title: () => '集成环境',
1202
+ description: () => '在这里管理 Nacos / MySQL / Redis 等实例,并按会话勾选要用的实例',
1203
+ },
1204
+ ],
1205
+ }),
1206
+ )
1207
+ disposers.push(
1208
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
1209
+ ctx.slots.register({ name: 'sidebar.right.pane.tab', key: IMPL_ID }, IntegrationEnvTab),
1210
+ ),
1211
+ )
1212
+ disposers.push(
1213
+ ctx.slots.inject('conversation.input.left', () =>
1214
+ ctx.slots.register(
1215
+ { name: 'conversation.input.left', id: 'integration-env', order: 21 },
1216
+ makeOpenButton(sidebarRight),
1217
+ ),
1218
+ ),
1219
+ )
1220
+ return () => {
1221
+ for (const dispose of disposers.reverse()) {
1222
+ try {
1223
+ dispose()
1224
+ } catch (failure) {
1225
+ console.error('[integration-env] 释放注册失败:', failure)
1226
+ }
1227
+ }
1228
+ }
1229
+ })
1230
+ },
1231
+ }
1232
+ },
1233
+ })