dsh-rig 0.0.0 → 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/lib/client.js ADDED
@@ -0,0 +1,618 @@
1
+ /**
2
+ * dsh-rig · client half — 右栏「插件实验室」面板
3
+ *
4
+ * ⚠️ 这个文件是**一个 ModuleLoader bundle**:协议上没法拆成多文件(factory 只能 require
5
+ * 宿主导出的模块,不能 require 本包自己的文件)。所以「组件化」靠文件内的分区保证,
6
+ * 分区顺序固定:常量 → 样式 → 通信 → hook → 原子组件 → 容器 → 注册。
7
+ * 结构守卫(test/structure.test.mjs)盯着它的行长上限与 API 前缀对拍。
8
+ *
9
+ * 承载面走 DSH 官方右栏注册表:`sidebarRightTabs.register` 定义 tab 类型 + guide 卡片,
10
+ * 正文/标题注册进键控槽,另在会话头部加一个入口按钮。
11
+ *
12
+ * 数据面走宿主 webServer 的 `/dsh-rig/api`:事件流用 fetch 手工解 SSE(EventSource 发不了
13
+ * 自定义头),命令走 POST。iframe 是跨源的,所以「锁定」只能挡输入,不能碰它内部状态。
14
+ */
15
+ window.__ModuleLoader__.load({
16
+ id: 'dsh-rig',
17
+ factory(require) {
18
+ const React = require('react')
19
+ const h = React.createElement
20
+ const { useState, useEffect, useRef, useCallback } = React
21
+
22
+ // ── 1. 常量(一个名字只在这里出现一次) ────────────────────────────
23
+ const TAB_ID = 'dsh-rig'
24
+ const TAB_KIND = 'dsh-rig:lab'
25
+ const GUIDE_ORDER = 45
26
+ const HEADER_ACTION_ORDER = 32
27
+ /** 与 host 半 `lib/lab/constants.js` 的 API_PREFIX 必须一致,由结构守卫对拍。 */
28
+ const API = '/dsh-rig/api'
29
+ const HEADERS = { 'x-dsh-rig': '1' }
30
+ const LOG_TAIL = 80
31
+ const LOG_KEEP = 400
32
+
33
+ const T = {
34
+ tab: '实验室',
35
+ panelTitle: '插件实验室',
36
+ guideTitle: '插件实验室',
37
+ guideDescription: '开一个真实、隔离的 DSH,看它跑起来',
38
+ headerAction: '插件实验室',
39
+ emptyTitle: '还没有实验室',
40
+ emptyDesc: '建一个之后,这里会嵌进来一个真实的 DSH 进程。',
41
+ create: '创建实验室',
42
+ creating: '创建中…',
43
+ actions: { start: '启动', restart: '重启', refresh: '刷新', stop: '停止', destroy: '销毁', popout: '弹出' },
44
+ mode: { lock: '锁定', unlock: '可介入' },
45
+ modeHint: { lock: '仅智能体可操作', unlock: '你可以直接上手' },
46
+ agent: {
47
+ label: '智能体操作界面',
48
+ on: '已授权',
49
+ off: '未授权',
50
+ hintOff: '授权后智能体才能点按钮、打字、截图(工具只在授权期间存在)',
51
+ hintOn: '智能体现在可以操作这个实验室的界面',
52
+ noBackend: '本机没有可用浏览器后端(装 playwright 后可用)',
53
+ },
54
+ lockBadge: '已锁定 · 点「可介入」解锁',
55
+ viewport: { idle: '实验室未运行', hint: '点「启动」后在这里看它', starting: '启动中…' },
56
+ logs: { title: '日志', empty: '(暂无日志)' },
57
+ conn: { on: '已连接', off: '未连接' },
58
+ status: { created: '未启动', starting: '启动中', running: '运行中', stopped: '已停止', crashed: '已崩溃' },
59
+ hint: '实验室是独立进程:它崩了这边不会崩。锁定只挡输入,不是安全边界。',
60
+ hostVersion: '跟随宿主',
61
+ }
62
+
63
+ const COLOR = {
64
+ created: 'var(--dsw-alias-state-idle-primary)',
65
+ stopped: 'var(--dsw-alias-state-idle-primary)',
66
+ starting: 'var(--dsw-alias-state-warn-primary)',
67
+ running: 'var(--dsw-alias-state-success-primary)',
68
+ crashed: 'var(--dsw-alias-state-error-primary)',
69
+ }
70
+
71
+ // ── 2. 样式(全部走主题令牌,浅色/深色都跟宿主) ──────────────────
72
+ const S = {
73
+ panel: {
74
+ display: 'flex', flexDirection: 'column', gap: 10, padding: '12px 12px 14px',
75
+ height: '100%', minHeight: 0, boxSizing: 'border-box',
76
+ color: 'var(--dsw-alias-label-primary)', fontSize: 13, lineHeight: 1.5,
77
+ },
78
+ row: { display: 'flex', alignItems: 'center', gap: 8, flex: 'none', minWidth: 0 },
79
+ title: { fontSize: 13, fontWeight: 600, letterSpacing: 0.2, whiteSpace: 'nowrap' },
80
+ pill: {
81
+ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '2px 8px', borderRadius: 999,
82
+ border: '1px solid var(--dsw-alias-border-l1)', background: 'var(--dsw-alias-bg-layer-1)',
83
+ fontSize: 11, color: 'var(--dsw-alias-label-secondary)', whiteSpace: 'nowrap',
84
+ },
85
+ dot: (color) => ({ width: 7, height: 7, borderRadius: '50%', background: color, flex: 'none' }),
86
+ spacer: { flex: 1 },
87
+ meta: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
88
+ controls: { display: 'flex', flexWrap: 'wrap', gap: 6, flex: 'none' },
89
+ btn: {
90
+ appearance: 'none', border: '1px solid var(--dsw-alias-border-l1)', background: 'var(--dsw-alias-bg-layer-1)',
91
+ color: 'var(--dsw-alias-label-primary)', borderRadius: 8, padding: '5px 10px', fontSize: 12, cursor: 'pointer', font: 'inherit',
92
+ },
93
+ btnPrimary: { borderColor: 'var(--dsw-alias-brand-primary)', color: 'var(--dsw-alias-brand-primary)' },
94
+ btnDanger: { color: 'var(--dsw-alias-state-error-primary)' },
95
+ btnOff: { cursor: 'not-allowed', color: 'var(--dsw-alias-state-idle-primary)' },
96
+ seg: { display: 'flex', border: '1px solid var(--dsw-alias-border-l1)', borderRadius: 8, overflow: 'hidden', flex: 'none' },
97
+ segItem: (active) => ({
98
+ padding: '4px 10px', fontSize: 12, cursor: 'pointer', font: 'inherit', appearance: 'none', border: 'none',
99
+ background: active ? 'var(--dsw-alias-bg-layer-2)' : 'transparent',
100
+ color: active ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-secondary)',
101
+ }),
102
+ viewportWrap: {
103
+ position: 'relative', flex: 1, minHeight: 160, border: '1px solid var(--dsw-alias-border-l2)',
104
+ borderRadius: 10, overflow: 'hidden', background: 'var(--dsw-alias-bg-base)',
105
+ },
106
+ viewportIdle: {
107
+ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center',
108
+ justifyContent: 'center', gap: 6, textAlign: 'center', padding: 16,
109
+ color: 'var(--dsw-alias-label-secondary)', fontSize: 12,
110
+ },
111
+ frame: { width: '100%', height: '100%', border: 'none', display: 'block', background: 'transparent' },
112
+ lockShield: {
113
+ position: 'absolute', inset: 0, zIndex: 2, cursor: 'not-allowed',
114
+ background: 'color-mix(in srgb, var(--dsw-alias-bg-base) 8%, transparent)',
115
+ display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: 8,
116
+ },
117
+ lockBadge: {
118
+ fontSize: 11, padding: '2px 8px', borderRadius: 999, border: '1px solid var(--dsw-alias-border-l2)',
119
+ background: 'var(--dsw-alias-bg-overlay)', color: 'var(--dsw-alias-label-secondary)',
120
+ },
121
+ logBox: {
122
+ flex: 'none', maxHeight: 150, overflow: 'auto', border: '1px solid var(--dsw-alias-border-l1)',
123
+ borderRadius: 8, background: 'var(--dsw-alias-bg-layer-1)', padding: '6px 8px',
124
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: 11, lineHeight: 1.45,
125
+ },
126
+ logLine: { whiteSpace: 'pre-wrap', wordBreak: 'break-all', color: 'var(--dsw-alias-label-secondary)' },
127
+ logErr: { color: 'var(--dsw-alias-state-error-primary)' },
128
+ errorBar: {
129
+ flex: 'none', fontSize: 12, padding: '6px 8px', borderRadius: 8,
130
+ border: '1px solid var(--dsw-alias-state-error-primary)', color: 'var(--dsw-alias-state-error-primary)',
131
+ },
132
+ hint: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)', flex: 'none' },
133
+ headerButton: {
134
+ appearance: 'none', display: 'inline-flex', alignItems: 'center', gap: 6, border: '1px solid var(--dsw-alias-border-l1)',
135
+ background: 'var(--dsw-alias-bg-layer-1)', color: 'var(--dsw-alias-label-secondary)', borderRadius: 999,
136
+ padding: '3px 10px', fontSize: 12, cursor: 'pointer', font: 'inherit', flex: 'none',
137
+ },
138
+ }
139
+
140
+ // ── 3. 通信(唯一的 HTTP 出入口) ────────────────────────────────
141
+ async function request(path, init) {
142
+ const res = await fetch(API + path, { ...init, headers: { ...HEADERS, ...((init && init.headers) || {}) } })
143
+ if (!res.ok) {
144
+ let detail = ''
145
+ try {
146
+ detail = (await res.json()).error || ''
147
+ } catch {
148
+ /* 非 JSON */
149
+ }
150
+ throw new Error(detail || `HTTP ${res.status}`)
151
+ }
152
+ return res.json()
153
+ }
154
+
155
+ /** 手工解 SSE。返回时说明流结束了(不是错误)。 */
156
+ async function consumeEvents(onEvent, signal) {
157
+ const res = await fetch(`${API}/events`, { headers: { ...HEADERS, accept: 'text/event-stream' }, signal })
158
+ if (!res.ok || !res.body) throw new Error(`事件流 HTTP ${res.status}`)
159
+ const reader = res.body.getReader()
160
+ const decoder = new TextDecoder()
161
+ let buffer = ''
162
+ for (;;) {
163
+ const { done, value } = await reader.read()
164
+ if (done) return
165
+ buffer += decoder.decode(value, { stream: true })
166
+ let cut
167
+ while ((cut = buffer.indexOf('\n\n')) >= 0) {
168
+ const chunk = buffer.slice(0, cut)
169
+ buffer = buffer.slice(cut + 2)
170
+ for (const line of chunk.split('\n')) {
171
+ if (!line.startsWith('data: ')) continue
172
+ try {
173
+ onEvent(JSON.parse(line.slice(6)))
174
+ } catch {
175
+ /* 坏帧忽略 */
176
+ }
177
+ }
178
+ }
179
+ }
180
+ }
181
+
182
+ // ── 4. hook:把事件流收敛成一份视图状态 ──────────────────────────
183
+ function useLabState() {
184
+ const [labs, setLabs] = useState([])
185
+ const [diagnostics, setDiagnostics] = useState(null)
186
+ const [logs, setLogs] = useState({})
187
+ const [connected, setConnected] = useState(false)
188
+ const [error, setError] = useState('')
189
+ const [uiMode, setUiMode] = useState(false)
190
+ const [ui, setUi] = useState(null)
191
+ const [frameSig, setFrameSig] = useState('')
192
+ const [frameGen, setFrameGen] = useState(0)
193
+
194
+ useEffect(() => {
195
+ const controller = new AbortController()
196
+ let retry = null
197
+
198
+ const pushLog = (id, entry) =>
199
+ setLogs((prev) => {
200
+ const list = (prev[id] || []).concat(entry)
201
+ return { ...prev, [id]: list.length > LOG_KEEP ? list.slice(list.length - LOG_KEEP) : list }
202
+ })
203
+
204
+ const applyState = (data) => {
205
+ setLabs(data.labs || [])
206
+ if (data.diagnostics) setDiagnostics(data.diagnostics)
207
+ if (typeof data.uiMode === 'boolean') setUiMode(data.uiMode)
208
+ if (data.ui) setUi(data.ui)
209
+ if (typeof data.frameSig === 'string') setFrameSig(data.frameSig)
210
+ }
211
+
212
+ const refresh = () => request('/state').then(applyState).catch(() => {})
213
+
214
+ let lastEventAt = Date.now()
215
+
216
+ const applyEvent = (event) => {
217
+ lastEventAt = Date.now()
218
+ if (event.type === 'snapshot') {
219
+ setLabs(event.labs || [])
220
+ if (event.diagnostics) setDiagnostics(event.diagnostics)
221
+ if (typeof event.uiMode === 'boolean') setUiMode(event.uiMode)
222
+ if (event.ui) setUi(event.ui)
223
+ if (typeof event.frameSig === 'string') setFrameSig(event.frameSig)
224
+ } else if (event.type === 'ui-mode') {
225
+ setUiMode(Boolean(event.enabled))
226
+ } else if (event.type === 'url') {
227
+ // 实验室换了地址(启动/重启):让 iframe 重新走一次稳定入口,拿新 token。
228
+ // 只把 key 绑在入口地址上不够 —— 入口地址本身不变,必须由这次自增触发导航。
229
+ setFrameGen((n) => n + 1)
230
+ refresh()
231
+ } else if (event.type === 'log') {
232
+ pushLog(event.id, event.entry)
233
+ } else if (event.type === 'status' || event.type === 'labs') {
234
+ refresh()
235
+ }
236
+ }
237
+
238
+ const loop = () => {
239
+ if (controller.signal.aborted) return
240
+ setConnected(true)
241
+ consumeEvents(applyEvent, controller.signal)
242
+ .then(() => {
243
+ setConnected(false)
244
+ if (!controller.signal.aborted) retry = setTimeout(loop, 2_000)
245
+ })
246
+ .catch((err) => {
247
+ setConnected(false)
248
+ if (controller.signal.aborted) return
249
+ setError(`事件流断开:${err && err.message ? err.message : err}`)
250
+ retry = setTimeout(loop, 3_000)
251
+ })
252
+ }
253
+
254
+ request('/state')
255
+ .then((data) => {
256
+ applyState(data)
257
+ setError('')
258
+ loop()
259
+ })
260
+ .catch((err) => setError(`拿不到实验室状态:${err && err.message ? err.message : err}(宿主可能没有 HTTP 面)`))
261
+
262
+ /**
263
+ * 看门狗:事件流可能**安静地挂住**(不报错、也不再送数据),面板就停在旧状态。
264
+ * 25 秒无事件则主动拉一次状态:不解决根因,但保证「旧一拍」自愈。
265
+ */
266
+ const watchdog = setInterval(() => {
267
+ if (controller.signal.aborted) return
268
+ if (Date.now() - lastEventAt > 25_000) refresh()
269
+ }, 10_000)
270
+
271
+ return () => {
272
+ controller.abort()
273
+ if (retry) clearTimeout(retry)
274
+ clearInterval(watchdog)
275
+ }
276
+ }, [])
277
+
278
+ return { labs, diagnostics, logs, connected, error, setError, uiMode, setUiMode, ui, frameSig, frameGen }
279
+ }
280
+
281
+ // ── 5. 原子组件(只吃 props,不认识 ctx / 网络) ──────────────────
282
+ function StatusPill({ label, color }) {
283
+ return h('span', { style: S.pill }, h('span', { style: S.dot(color) }), label)
284
+ }
285
+
286
+ function Btn({ children, onClick, disabled, tone, title }) {
287
+ const off = Boolean(disabled)
288
+ const style = { ...S.btn, ...(tone === 'primary' ? S.btnPrimary : {}), ...(tone === 'danger' ? S.btnDanger : {}), ...(off ? S.btnOff : {}) }
289
+ return h('button', { type: 'button', disabled: off, title: title || children, style, onClick: off ? undefined : onClick }, children)
290
+ }
291
+
292
+ function MetaRow({ left, right }) {
293
+ return h('div', { style: S.row }, h('span', { style: S.meta }, left), h('span', { style: S.spacer }), right ? h('span', { style: S.meta }, right) : null)
294
+ }
295
+
296
+ // ── 6. 业务组件(每个只负责一件事) ──────────────────────────────
297
+ function LabModeSwitch({ locked, onChange }) {
298
+ return h(
299
+ 'div',
300
+ { style: S.row },
301
+ h(
302
+ 'div',
303
+ { style: S.seg },
304
+ h('button', { type: 'button', style: S.segItem(locked), onClick: () => onChange(true) }, T.mode.lock),
305
+ h('button', { type: 'button', style: S.segItem(!locked), onClick: () => onChange(false) }, T.mode.unlock),
306
+ ),
307
+ h('span', { style: S.meta }, locked ? T.modeHint.lock : T.modeHint.unlock),
308
+ )
309
+ }
310
+
311
+ /**
312
+ * 「允许智能体操作界面」开关。
313
+ * 它不是一个纯 UI 状态:打开/关闭会让宿主**注册/注销** `lab_ui` 工具。
314
+ * 所以文案要说清代价 —— 授权期间智能体才有点击与打字的工具。
315
+ */
316
+ function LabAgentSwitch({ enabled, backend, available, onChange }) {
317
+ const usable = available !== false
318
+ return h(
319
+ 'div',
320
+ { style: S.row },
321
+ h(
322
+ 'button',
323
+ {
324
+ type: 'button',
325
+ disabled: !usable,
326
+ style: { ...S.btn, ...(enabled ? S.btnPrimary : {}), ...(usable ? {} : S.btnOff) },
327
+ title: usable ? '' : T.agent.noBackend,
328
+ onClick: () => usable && onChange(!enabled),
329
+ },
330
+ `${T.agent.label}:${enabled ? T.agent.on : T.agent.off}`,
331
+ ),
332
+ h(
333
+ 'span',
334
+ { style: S.meta },
335
+ usable ? (enabled ? T.agent.hintOn : T.agent.hintOff) : T.agent.noBackend,
336
+ ),
337
+ )
338
+ }
339
+
340
+ function LabControls({ lab, busy, live, onAction, onRefresh, onPopout }) {
341
+ const any = busy !== ''
342
+ return h(
343
+ 'div',
344
+ { style: S.controls },
345
+ h(Btn, { tone: 'primary', disabled: any || !lab || live, onClick: () => onAction('start') }, T.actions.start),
346
+ h(Btn, { disabled: any || !live, onClick: () => onAction('restart') }, T.actions.restart),
347
+ h(Btn, { disabled: !lab || !lab.url, onClick: onRefresh }, T.actions.refresh),
348
+ h(Btn, { disabled: !lab || !lab.url, onClick: onPopout }, T.actions.popout),
349
+ h(Btn, { disabled: any || !live, onClick: () => onAction('stop') }, T.actions.stop),
350
+ h(Btn, { tone: 'danger', disabled: any || live, onClick: () => onAction('destroy') }, T.actions.destroy),
351
+ )
352
+ }
353
+
354
+ function LabViewport({ lab, locked, frameUrl }) {
355
+ const status = lab ? lab.status : 'created'
356
+ return h(
357
+ 'div',
358
+ { style: S.viewportWrap },
359
+ frameUrl
360
+ ? h('iframe', {
361
+ // key 绑在地址上:地址一变就强制重建 iframe,避免沿用旧文档。
362
+ key: frameUrl,
363
+ src: frameUrl,
364
+ style: { ...S.frame, pointerEvents: locked ? 'none' : 'auto' },
365
+ title: T.panelTitle,
366
+ allow: 'clipboard-write',
367
+ })
368
+ : h(
369
+ 'div',
370
+ { style: S.viewportIdle },
371
+ h('div', null, status === 'starting' ? T.viewport.starting : T.viewport.idle),
372
+ h('div', null, T.viewport.hint),
373
+ ),
374
+ locked && frameUrl ? h('div', { style: S.lockShield }, h('span', { style: S.lockBadge }, T.lockBadge)) : null,
375
+ )
376
+ }
377
+
378
+ function LabLogPanel({ entries }) {
379
+ const ref = useRef(null)
380
+ useEffect(() => {
381
+ const el = ref.current
382
+ if (el) el.scrollTop = el.scrollHeight
383
+ }, [entries.length])
384
+ if (!entries.length) return h('div', { style: { ...S.logBox, color: 'var(--dsw-alias-label-secondary)' } }, T.logs.empty)
385
+ return h(
386
+ 'div',
387
+ { style: S.logBox, ref },
388
+ ...entries.slice(-LOG_TAIL).map((entry) =>
389
+ h('div', { key: entry.seq, style: { ...S.logLine, ...(entry.stream === 'err' ? S.logErr : {}) } }, entry.text),
390
+ ),
391
+ )
392
+ }
393
+
394
+ function LabEmpty({ busy, onCreate }) {
395
+ return h(
396
+ 'div',
397
+ { style: { ...S.viewportWrap, display: 'flex', alignItems: 'center', justifyContent: 'center' } },
398
+ h(
399
+ 'div',
400
+ { style: S.viewportIdle },
401
+ h('div', { style: { fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, T.emptyTitle),
402
+ h('div', null, T.emptyDesc),
403
+ h(Btn, { tone: 'primary', onClick: onCreate, disabled: busy !== '' }, busy === 'create' ? T.creating : T.create),
404
+ ),
405
+ )
406
+ }
407
+
408
+ // ── 7. 容器:只做接线(状态 → 组件),不写样式细节 ─────────────
409
+ function LabPanel() {
410
+ const { labs, logs, connected, error, setError, uiMode, setUiMode, ui, frameSig, frameGen } = useLabState()
411
+ const [locked, setLocked] = useState(true)
412
+ const [busy, setBusy] = useState('')
413
+ const [nonce, setNonce] = useState(0)
414
+
415
+ const lab = labs.length > 0 ? labs[0] : null
416
+ const entries = lab ? logs[lab.id] || [] : []
417
+ const status = lab ? lab.status : 'created'
418
+ const live = status === 'running' || status === 'starting'
419
+ // iframe 指向**宿主**的稳定入口而不是实验室裸地址:实验室每次重启都换端口与 token,
420
+ // 直连它时一次重启就让面板卡在 `dsh web authentication required`(2026-11-21 撞上)。
421
+ // 走入口后宿主每次 302 到当前真地址,面板即使旧一拍也不会拿过期 token 去撞 401。
422
+ const frameUrl = lab && frameSig ? `${API}/frame?id=${encodeURIComponent(lab.id)}&sig=${frameSig}&n=${nonce + frameGen}` : null
423
+
424
+ const run = useCallback(
425
+ async (label, fn) => {
426
+ setBusy(label)
427
+ setError('')
428
+ try {
429
+ await fn()
430
+ } catch (err) {
431
+ setError(`${label}失败:${err && err.message ? err.message : err}`)
432
+ } finally {
433
+ setBusy('')
434
+ }
435
+ },
436
+ [setError],
437
+ )
438
+
439
+ const createLab = () => run('create', () => request('/labs', { method: 'POST', body: JSON.stringify({}) }))
440
+ const toggleAgent = (next) =>
441
+ run('授权', async () => {
442
+ setUiMode(next)
443
+ await request('/ui-mode', { method: 'POST', body: JSON.stringify({ enabled: next }) })
444
+ })
445
+ const onAction = (action) => run(action, () => request(`/labs/${lab.id}`, { method: 'POST', body: JSON.stringify({ action }) }))
446
+
447
+ return h(
448
+ 'div',
449
+ { style: S.panel },
450
+ h(
451
+ 'div',
452
+ { style: S.row },
453
+ h('span', { style: S.title }, T.panelTitle),
454
+ lab ? h(StatusPill, { label: T.status[status] || status, color: COLOR[status] || COLOR.created }) : null,
455
+ h('span', { style: S.spacer }),
456
+ h('span', { style: S.meta }, connected ? T.conn.on : T.conn.off),
457
+ ),
458
+ lab ? h(MetaRow, { left: `${lab.version === 'host' ? T.hostVersion : lab.version} · ${lab.id}`, right: lab.port ? `:${lab.port}` : null }) : null,
459
+ error ? h('div', { style: S.errorBar }, error) : null,
460
+ !lab
461
+ ? h(LabEmpty, { busy, onCreate: createLab })
462
+ : h(
463
+ React.Fragment,
464
+ null,
465
+ h(LabControls, {
466
+ lab,
467
+ busy,
468
+ live,
469
+ onAction,
470
+ onRefresh: () => setNonce((n) => n + 1),
471
+ onPopout: () => lab.url && window.open(lab.url, '_blank', 'noopener'),
472
+ }),
473
+ h(LabModeSwitch, { locked, onChange: setLocked }),
474
+ h(LabAgentSwitch, {
475
+ enabled: uiMode,
476
+ backend: ui && ui.backend,
477
+ available: ui ? ui.available : null,
478
+ onChange: toggleAgent,
479
+ }),
480
+ h(LabViewport, { lab, locked, frameUrl }),
481
+ h(MetaRow, { left: `${T.logs.title}(${entries.length})` }),
482
+ h(LabLogPanel, { entries }),
483
+ ),
484
+ h('div', { style: S.hint }, T.hint),
485
+ )
486
+ }
487
+
488
+ /** tab 标题:文字 + 状态点。 */
489
+ function LabTabTitle() {
490
+ return h(
491
+ 'span',
492
+ { style: { display: 'inline-flex', alignItems: 'center', gap: 6 } },
493
+ h('span', { style: S.dot('var(--dsw-alias-state-idle-primary)') }),
494
+ T.tab,
495
+ )
496
+ }
497
+
498
+ // ── 8. 注册(只接线:拿服务、注册槽位) ─────────────────────────
499
+ function service(ctx, key) {
500
+ try {
501
+ return typeof ctx?.get === 'function' ? ctx.get(key) : null
502
+ } catch {
503
+ return null
504
+ }
505
+ }
506
+
507
+ function openLab(ctx) {
508
+ const nav = service(ctx, 'sidebarRight')
509
+ try {
510
+ if (nav && typeof nav.openTab === 'function') {
511
+ nav.openTab(TAB_KIND)
512
+ return
513
+ }
514
+ } catch {
515
+ /* 兜底 */
516
+ }
517
+ const layout = service(ctx, 'layout')
518
+ try {
519
+ if (layout && typeof layout.openRightbar === 'function') layout.openRightbar(true, false)
520
+ } catch {
521
+ /* 打不开不是错 */
522
+ }
523
+ }
524
+
525
+ function collector() {
526
+ const list = []
527
+ return {
528
+ add(dispose) {
529
+ if (typeof dispose === 'function') list.push(dispose)
530
+ },
531
+ disposeAll() {
532
+ while (list.length > 0) {
533
+ try {
534
+ list.pop()()
535
+ } catch {
536
+ /* 已注销 */
537
+ }
538
+ }
539
+ },
540
+ }
541
+ }
542
+
543
+ function registerInto(ctx) {
544
+ const disposers = collector()
545
+ try {
546
+ const disposeInject = ctx.inject(['sidebarRightTabs'], (ictx) => {
547
+ const inner = collector()
548
+ try {
549
+ const tabs = ictx.sidebarRightTabs
550
+ if (!tabs || typeof tabs.register !== 'function') return inner.disposeAll
551
+ inner.add(
552
+ tabs.register({
553
+ id: TAB_ID,
554
+ kind: TAB_KIND,
555
+ priority: 'extension',
556
+ title: () => T.tab,
557
+ guide: [{ id: TAB_ID, order: GUIDE_ORDER, title: () => T.guideTitle, description: () => T.guideDescription }],
558
+ }),
559
+ )
560
+ inner.add(
561
+ ictx.slots.inject('sidebar.right.pane.tab', () =>
562
+ ictx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID }, LabPanel),
563
+ ),
564
+ )
565
+ inner.add(
566
+ ictx.slots.inject('sidebar.right.pane.tab.title', () =>
567
+ ictx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID }, LabTabTitle),
568
+ ),
569
+ )
570
+ } catch (e) {
571
+ console.warn('[dsh-rig] 右栏注册失败', e)
572
+ }
573
+ return inner.disposeAll
574
+ })
575
+ if (typeof disposeInject === 'function') disposers.add(disposeInject)
576
+ } catch (e) {
577
+ console.warn('[dsh-rig] inject(sidebarRightTabs) 不可用', e)
578
+ }
579
+
580
+ try {
581
+ const slots = service(ctx, 'slots')
582
+ if (slots && typeof slots.inject === 'function') {
583
+ disposers.add(
584
+ slots.inject('conversation.session.header.actions', () =>
585
+ slots.register(
586
+ { name: 'conversation.session.header.actions', id: TAB_ID, order: HEADER_ACTION_ORDER, label: T.headerAction },
587
+ function HeaderButton() {
588
+ return h(
589
+ 'button',
590
+ { type: 'button', style: S.headerButton, title: T.headerAction, onClick: () => openLab(ctx) },
591
+ h('span', { 'aria-hidden': true }, '🧪'),
592
+ h('span', null, T.headerAction),
593
+ )
594
+ },
595
+ ),
596
+ ),
597
+ )
598
+ }
599
+ } catch (e) {
600
+ console.warn('[dsh-rig] 头部入口注册失败', e)
601
+ }
602
+
603
+ return () => disposers.disposeAll()
604
+ }
605
+
606
+ return {
607
+ inject: ['slots'],
608
+ apply(ctx) {
609
+ try {
610
+ const dispose = registerInto(ctx)
611
+ if (typeof ctx.effect === 'function') ctx.effect(() => dispose, 'dsh-rig registration')
612
+ } catch (e) {
613
+ console.warn('[dsh-rig] apply 失败', e)
614
+ }
615
+ },
616
+ }
617
+ },
618
+ })