@ruoy/dsh-session-bus 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/panel.js CHANGED
@@ -1,473 +1,923 @@
1
- // 会话互通 · 浏览器半边:右栏「会话互通」标签页 + 编辑器上方的一个入口按钮。
2
- // 纯 JS + React.createElement(模板不允许 JSX,也不允许 import 宿主组件)。
3
- window.__ModuleLoader__.load({
4
- id: 'dsh-session-bus',
5
- factory(require) {
6
- const React = require('react')
7
- const h = React.createElement
8
-
9
- const KIND = 'session-bus'
10
- const STATE_ROUTE = '/dsh-session-bus/api/state'
11
- const SEND_ROUTE = '/dsh-session-bus/api/send'
12
-
13
- const DICT = {
14
- zh: {
15
- open: '会话互通',
16
- sessions: '会话',
17
- messages: '消息',
18
- audit: '审计',
19
- empty: '还没有消息往来。',
20
- unread: '未读',
21
- live: '在线',
22
- offline: '离线',
23
- self: '本会话',
24
- loading: '加载中…',
25
- error: '读取失败',
26
- sendTo: '发给',
27
- send: '发送',
28
- sending: '发送中…',
29
- placeholder: '给这个会话发一条消息…',
30
- sent: '已发送',
31
- pick: '先点上面任一会话选为目标',
32
- pendingApproval: '待批授权',
33
- search: '搜索会话或消息…',
34
- unreadTotal: '未读',
35
- replyTo: '回复',
36
- },
37
- en: {
38
- open: 'Session bus',
39
- sessions: 'Sessions',
40
- messages: 'Messages',
41
- audit: 'Audit',
42
- empty: 'No traffic yet.',
43
- unread: 'unread',
44
- live: 'live',
45
- offline: 'offline',
46
- self: 'this session',
47
- loading: 'Loading…',
48
- error: 'Failed to load',
49
- sendTo: 'To',
50
- send: 'Send',
51
- sending: 'Sending…',
52
- placeholder: 'Send a message to this session…',
53
- sent: 'Sent',
54
- pick: 'Pick a session above first',
55
- pendingApproval: 'pending approval',
56
- search: 'Search sessions or messages…',
57
- unreadTotal: 'unread',
58
- replyTo: 'reply',
59
- },
60
- }
61
-
62
- let lang = 'zh'
63
- try {
64
- const html = String(document?.documentElement?.lang ?? '').toLowerCase()
65
- const nav = String(globalThis.navigator?.language ?? '').toLowerCase()
66
- const pick = html || nav
67
- lang = pick.startsWith('en') ? 'en' : 'zh'
68
- } catch {
69
- lang = 'zh'
70
- }
71
- const t = (key) => DICT[lang][key] ?? key
72
-
73
- const styles = {
74
- root: {
75
- display: 'flex',
76
- flexDirection: 'column',
77
- gap: '10px',
78
- padding: '10px 12px',
79
- height: '100%',
80
- overflow: 'auto',
81
- color: 'var(--dsw-alias-label-primary, #e6e6e6)',
82
- fontSize: '12px',
83
- lineHeight: 1.5,
84
- },
85
- sectionTitle: {
86
- fontSize: '11px',
87
- letterSpacing: '.04em',
88
- textTransform: 'uppercase',
89
- color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
90
- margin: '4px 0 2px',
91
- },
92
- row: {
93
- display: 'flex',
94
- alignItems: 'center',
95
- gap: '6px',
96
- padding: '5px 7px',
97
- borderRadius: '6px',
98
- background: 'var(--dsw-alias-bg-layer-1, #232323)',
99
- // 刻意不画边框:任何 border/outline 都可能被宿主的原生 button 外观覆盖成深色描边。
100
- // 行的可点击性靠底色 + hover 光标表达,选中靠更亮的底色与左侧细色条。
101
- border: '0 none',
102
- outline: '0 none',
103
- appearance: 'none',
104
- WebkitAppearance: 'none',
105
- boxShadow: 'none',
106
- cursor: 'pointer',
107
- textAlign: 'left',
108
- color: 'inherit',
109
- font: 'inherit',
110
- width: '100%',
111
- WebkitTapHighlightColor: 'transparent',
112
- },
113
- rowActive: {
114
- background: 'var(--dsw-alias-bg-layer-2, #2c2c2c)',
115
- boxShadow: 'inset 2px 0 0 var(--dsw-alias-brand-primary, #4c8dff)',
116
- },
117
- name: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
118
- dot: { width: '7px', height: '7px', borderRadius: '50%', flex: '0 0 auto' },
119
- badge: {
120
- flex: '0 0 auto',
121
- minWidth: '16px',
122
- textAlign: 'center',
123
- padding: '0 5px',
124
- borderRadius: '8px',
125
- background: 'var(--dsw-alias-brand-primary, #4c8dff)',
126
- color: 'var(--dsw-alias-bg-base, #1b1b1b)',
127
- fontSize: '10px',
128
- },
129
- warn: {
130
- flex: '0 0 auto',
131
- padding: '0 4px',
132
- borderRadius: '4px',
133
- background: 'var(--dsw-alias-state-warn-primary, #d9a521)',
134
- color: 'var(--dsw-alias-bg-base, #1b1b1b)',
135
- fontSize: '10px',
136
- },
137
- meta: { color: 'var(--dsw-alias-label-secondary, #a0a0a0)', fontSize: '11px' },
138
- summaryRow: {
139
- display: 'flex',
140
- alignItems: 'center',
141
- justifyContent: 'space-between',
142
- gap: '8px',
143
- },
144
- summaryButtons: { display: 'flex', gap: '6px', flex: '0 0 auto' },
145
- tinyButton: {
146
- cursor: 'pointer',
147
- fontSize: '11px',
148
- padding: '1px 6px',
149
- borderRadius: '4px',
150
- border: '0 none',
151
- background: 'var(--dsw-alias-bg-layer-2, #2c2c2c)',
152
- color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
153
- userSelect: 'none',
154
- },
155
- msg: {
156
- display: 'flex',
157
- flexDirection: 'column',
158
- gap: '2px',
159
- padding: '6px 8px',
160
- borderRadius: '6px',
161
- background: 'var(--dsw-alias-bg-layer-2, #2c2c2c)',
162
- border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
163
- },
164
- msgText: { whiteSpace: 'pre-wrap', wordBreak: 'break-word' },
165
- search: {
166
- width: '100%',
167
- boxSizing: 'border-box',
168
- height: '26px',
169
- padding: '0 8px',
170
- borderRadius: '6px',
171
- border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
172
- background: 'var(--dsw-alias-bg-layer-1, #232323)',
173
- color: 'var(--dsw-alias-label-primary, #e6e6e6)',
174
- font: 'inherit',
175
- },
176
- composer: { display: 'flex', flexDirection: 'column', gap: '6px' },
177
- input: {
178
- width: '100%',
179
- boxSizing: 'border-box',
180
- minHeight: '52px',
181
- resize: 'vertical',
182
- padding: '6px 8px',
183
- borderRadius: '6px',
184
- border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
185
- background: 'var(--dsw-alias-bg-layer-1, #232323)',
186
- color: 'var(--dsw-alias-label-primary, #e6e6e6)',
187
- font: 'inherit',
188
- },
189
- sendRow: { display: 'flex', alignItems: 'center', gap: '8px' },
190
- button: {
191
- height: '26px',
192
- padding: '0 12px',
193
- borderRadius: '6px',
194
- border: '1px solid var(--dsw-alias-brand-primary, #4c8dff)',
195
- background: 'var(--dsw-alias-brand-primary, #4c8dff)',
196
- color: 'var(--dsw-alias-bg-base, #1b1b1b)',
197
- font: 'inherit',
198
- cursor: 'pointer',
199
- },
200
- buttonDisabled: { opacity: '.5', cursor: 'not-allowed' },
201
- error: { color: 'var(--dsw-alias-state-error-primary, #e5484d)', fontSize: '11px' },
202
- trigger: {
203
- display: 'inline-flex',
204
- alignItems: 'center',
205
- gap: '6px',
206
- height: '26px',
207
- padding: '0 10px',
208
- borderRadius: '999px',
209
- border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
210
- background: 'var(--dsw-alias-bg-layer-1, #232323)',
211
- color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
212
- fontSize: '12px',
213
- cursor: 'pointer',
214
- },
215
- }
216
-
217
- function useBusState(sessionId, reloadToken) {
218
- const [state, setState] = React.useState({ loading: true, error: null, data: null })
219
- React.useEffect(() => {
220
- if (!sessionId) return undefined
221
- let alive = true
222
- const controller = new AbortController()
223
- const load = async () => {
224
- try {
225
- const response = await fetch(`${STATE_ROUTE}?session=${encodeURIComponent(sessionId)}`, {
226
- credentials: 'same-origin',
227
- signal: controller.signal,
228
- })
229
- const body = await response.json()
230
- if (!alive) return
231
- setState(body.ok ? { loading: false, error: null, data: body } : { loading: false, error: body.error ?? t('error'), data: null })
232
- } catch (error) {
233
- if (!alive || controller.signal.aborted) return
234
- setState((prev) => ({ ...prev, loading: false, error: String(error?.message ?? error) }))
235
- }
236
- }
237
- void load()
238
- const timer = setInterval(load, 3000)
239
- return () => {
240
- alive = false
241
- controller.abort()
242
- clearInterval(timer)
243
- }
244
- }, [sessionId, reloadToken])
245
- return state
246
- }
247
-
248
- function formatTime(ts) {
249
- if (!ts) return ''
250
- try {
251
- return new Date(ts).toLocaleTimeString(lang === 'zh' ? 'zh-CN' : 'en-US', { hour12: false })
252
- } catch {
253
- return ''
254
- }
255
- }
256
-
257
- function BusPanel(props) {
258
- const sessionId = props.sessionId
259
- const [reloadToken, setReloadToken] = React.useState(0)
260
- const { loading, error, data } = useBusState(sessionId, reloadToken)
261
- const [target, setTarget] = React.useState('')
262
- const [draft, setDraft] = React.useState('')
263
- const [sending, setSending] = React.useState(false)
264
- const [sendError, setSendError] = React.useState('')
265
- const [sentNote, setSentNote] = React.useState('')
266
- const [search, setSearch] = React.useState('')
267
-
268
- const sessions = data?.sessions ?? []
269
- const messages = (data?.messages ?? []).slice(-30).reverse()
270
- const audit = (data?.audit ?? []).slice(-8).reverse()
271
- const targetRow = sessions.find((row) => row.id === target)
272
-
273
- React.useEffect(() => {
274
- if (target) return
275
- const first = sessions.find((row) => !row.isSelf)
276
- if (first) setTarget(first.id)
277
- }, [sessions, target])
278
-
279
- const doSend = React.useCallback(async () => {
280
- if (!target) return
281
- const text = draft.trim()
282
- if (!text) {
283
- setSendError(t('send') + ':' + '内容不能为空')
284
- return
285
- }
286
- if (new TextEncoder().encode(text).length > 4096) {
287
- setSendError('消息过长(上限 4096 字节)')
288
- return
289
- }
290
- setSending(true)
291
- setSendError('')
292
- setSentNote('')
293
- try {
294
- const response = await fetch(SEND_ROUTE, {
295
- method: 'POST',
296
- credentials: 'same-origin',
297
- headers: { 'content-type': 'application/json' },
298
- body: JSON.stringify({ from: sessionId, to: target, text }),
299
- })
300
- const body = await response.json()
301
- if (body.ok) {
302
- setDraft('')
303
- setSentNote(`${t('sent')} · ${body.status ?? ''}`)
304
- setReloadToken((n) => n + 1)
305
- } else {
306
- setSendError(body.error ?? t('error'))
307
- }
308
- } catch (sendFailure) {
309
- setSendError(String(sendFailure?.message ?? sendFailure))
310
- } finally {
311
- setSending(false)
312
- }
313
- }, [draft, sessionId, target])
314
-
315
- const needle = search.trim().toLowerCase()
316
- const sessionsShown = needle
317
- ? sessions.filter((row) => `${row.title} ${row.id}`.toLowerCase().includes(needle))
318
- : sessions
319
- const messagesShown = needle
320
- ? messages.filter((m) => `${m.text} ${m.from} ${m.to}`.toLowerCase().includes(needle))
321
- : messages
322
-
323
- const children = []
324
- if (loading) children.push(h('div', { key: 'loading', style: styles.meta }, t('loading')))
325
- if (error) children.push(h('div', { key: 'err', style: styles.error }, `${t('error')}: ${error}`))
326
-
327
- // 汇总行 + 两个按钮:重新加载界面(等价 F5,本机 F5 常常打不到页面)、立即拉取最新状态
328
- children.push(h('div', { key: 'summary', style: styles.summaryRow },
329
- h('span', { style: styles.meta },
330
- `${t('unreadTotal')} ${data?.totalUnread ?? 0} · ${t('sessions')} ${sessions.length} · ${t('messages')} ${messages.length}`),
331
- // 只保留「刷新数据」:这个只是重新拉一次 /api/state,安全。
332
- // 绝对不要放 window.location.reload() —— 实测点了会让整个应用崩掉(21:00 那次),
333
- // 这也解释了为什么用户按 F5 感觉「没用」:F5 走的是同一条崩溃路径。
334
- h('span', { style: styles.summaryButtons },
335
- h('span', {
336
- style: styles.tinyButton,
337
- title: '重新拉取一次面板数据(不会重载页面,安全)',
338
- onClick: () => setReloadToken((n) => n + 1),
339
- }, '刷新'),
340
- ),
341
- ))
342
- children.push(h('input', {
343
- key: 'search',
344
- style: styles.search,
345
- value: search,
346
- placeholder: t('search'),
347
- onChange: (event) => setSearch(event.target.value),
348
- }))
349
-
350
- // 发送区(面板的核心能力:能发,而不只是看)
351
- children.push(h('div', { key: 'composer', style: styles.composer },
352
- h('div', { style: styles.meta },
353
- `${t('sendTo')}:` + (targetRow ? targetRow.title : t('pick')),
354
- targetRow && targetRow.pendingApprovals > 0
355
- ? h('span', { style: { ...styles.warn, marginLeft: '6px' } }, `${t('pendingApproval')} ${targetRow.pendingApprovals}`)
356
- : null),
357
- h('textarea', {
358
- style: styles.input,
359
- value: draft,
360
- placeholder: t('placeholder'),
361
- onChange: (event) => setDraft(event.target.value),
362
- }),
363
- h('div', { style: styles.sendRow },
364
- h('button', {
365
- type: 'button',
366
- style: { ...styles.button, ...(sending || !target || !draft.trim() ? styles.buttonDisabled : {}) },
367
- disabled: sending || !target || !draft.trim(),
368
- onClick: () => { void doSend() },
369
- }, sending ? t('sending') : t('send')),
370
- sentNote ? h('span', { style: styles.meta }, sentNote) : null,
371
- sendError ? h('span', { style: styles.error }, sendError) : null,
372
- ),
373
- ))
374
-
375
- children.push(h('div', { key: 'mt', style: styles.sectionTitle }, `${t('messages')} · ${messages.length}`))
376
- if (messages.length === 0) children.push(h('div', { key: 'empty', style: styles.meta }, t('empty')))
377
- for (const message of messagesShown) {
378
- children.push(h('div', { key: message.id, style: styles.msg },
379
- h('div', { style: styles.meta },
380
- `${String(message.from).replace(/^session-/, '').slice(0, 8)} → ${String(message.to).replace(/^session-/, '').slice(0, 8)} · ${formatTime(message.ts)} · ${message.status}`),
381
- message.replyTo ? h('div', { style: styles.meta }, `↩ ${t('replyTo')} ${String(message.replyTo).slice(0, 14)}`) : null,
382
- h('div', { style: styles.msgText }, message.text),
383
- ))
384
- }
385
-
386
- children.push(h('div', { key: 'st', style: styles.sectionTitle }, `${t('sessions')} · ${sessions.length}`))
387
- for (const row of sessionsShown.slice(0, 12)) {
388
- const active = row.id === target
389
- // 用 div 而不是 button:button 自带浏览器默认边框,一旦某个 CSS token 没解析出来
390
- // 就会退回深色描边,看起来像「全被选中」。div + role=button 没有这个问题。
391
- children.push(h('div', {
392
- key: `s-${row.id}`,
393
- role: 'button',
394
- tabIndex: -1,
395
- title: row.cwd,
396
- onClick: () => setTarget(row.id),
397
- style: { ...styles.row, ...(active ? styles.rowActive : {}) },
398
- },
399
- h('span', {
400
- style: { ...styles.dot, background: row.live ? 'var(--dsw-alias-state-success-primary, #35c46a)' : 'var(--dsw-alias-state-idle-primary, #8a8a8a)' },
401
- title: row.live ? t('live') : t('offline'),
402
- }),
403
- h('span', { style: styles.name }, row.title + (row.isSelf ? ` · ${t('self')}` : '')),
404
- row.pendingApprovals > 0 ? h('span', { style: styles.warn }, `⚠${row.pendingApprovals}`) : null,
405
- row.unread > 0 ? h('span', { style: styles.badge }, String(row.unread)) : null,
406
- ))
407
- }
408
- if (sessions.length > 12) {
409
- children.push(h('div', { key: 'more', style: styles.meta }, `…还有 ${sessions.length - 12} 个会话`))
410
- }
411
-
412
- if (audit.length > 0) {
413
- children.push(h('div', { key: 'at', style: styles.sectionTitle }, t('audit')))
414
- for (const row of audit) {
415
- children.push(h('div', { key: `a-${row.ts}-${row.action}`, style: styles.meta },
416
- `${formatTime(row.ts)} ${row.action} ${row.target ? String(row.target).replace(/^session-/, '').slice(0, 8) : ''}`))
417
- }
418
- }
419
-
420
- return h('div', { style: styles.root }, children)
421
- }
422
-
423
- function OpenButton() {
424
- const onClick = React.useCallback(() => {
425
- try {
426
- busCtx?.sidebarRight?.openTab(KIND)
427
- busCtx?.layout?.openRightbar(true, false)
428
- } catch (error) {
429
- console.warn('session-bus: 打开面板失败', error)
430
- }
431
- }, [])
432
- return h('button', { type: 'button', style: styles.trigger, onClick, title: t('open') },
433
- h('span', { 'aria-hidden': true }, '⇄'),
434
- h('span', null, t('open')),
435
- )
436
- }
437
-
438
- let busCtx = null
439
-
440
- return {
441
- inject: ['slots', 'layout', 'sidebarRight', 'sidebarRightTabs', 'locale'],
442
- apply(ctx) {
443
- busCtx = ctx
444
- // 以页面 <html lang> 为准:宿主界面是中文时它一定是 zh-CN;
445
- // ctx.locale 的 id 在桌面端可能是 'en' 而界面仍是中文,不能拿来判语言。
446
- try {
447
- const html = String(document?.documentElement?.lang ?? '').toLowerCase()
448
- if (html) lang = html.startsWith('en') ? 'en' : 'zh'
449
- } catch { /* 保持默认(中文) */ }
450
-
451
- ctx.effect(() => ctx.sidebarRightTabs.register({
452
- id: KIND,
453
- kind: KIND,
454
- title: () => t('open'),
455
- }), 'session-bus: tab type')
456
-
457
- ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
458
- name: 'sidebar.right.pane.tab',
459
- key: KIND,
460
- }, BusPanel)), 'session-bus: tab body')
461
-
462
- ctx.effect(() => ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
463
- name: 'conversation.composer.dock',
464
- id: 'session-bus-open',
465
- order: 90,
466
- }, OpenButton)), 'session-bus: open button')
467
- },
468
- }
469
- },
470
- })
471
-
472
-
473
-
1
+ // 会话互通 · 浏览器半边:右栏「会话互通」标签页 + 编辑器上方的一个入口按钮。
2
+ // 纯 JS + React.createElement(模板不允许 JSX,也不允许 import 宿主组件)。
3
+ window.__ModuleLoader__.load({
4
+ // ⚠️ 必须与 package.json 的 name 完全一致:改包名(例如为了发 npm 加 scope)时
5
+ // 这里不改,客户端半边会静默不挂载(2026-11-25 踩过:面板和按钮整晚消失)。
6
+ id: '@ruoy/dsh-session-bus',
7
+ factory(require) {
8
+ const React = require('react')
9
+ const h = React.createElement
10
+
11
+ const KIND = 'session-bus'
12
+ const STATE_ROUTE = '/dsh-session-bus/api/state'
13
+ const SEND_ROUTE = '/dsh-session-bus/api/send'
14
+ const APPROVALS_ROUTE = '/dsh-session-bus/api/approvals'
15
+ const APPROVE_ROUTE = '/dsh-session-bus/api/approve'
16
+ const REVOKE_ROUTE = '/dsh-session-bus/api/revoke-grant'
17
+ const SET_PRESET_ROUTE = '/dsh-session-bus/api/set-preset'
18
+ const PANEL_PING_ROUTE = '/dsh-session-bus/api/panel-ping'
19
+ // 改客户端代码时把这里一起改:宿主 /api/state 的 panelVersion 会回显它,
20
+ // 用来确认「Ctrl+R 之后到底加载的是不是新面板」。
21
+ const PANEL_VERSION = '0.3.9'
22
+
23
+ /** 往宿主上报一条诊断(用 panel-ping 的 notice 字段,宿主侧 /api/state.panelNotices 可见)。 */
24
+ function reportNotice(text) {
25
+ try {
26
+ return fetch(PANEL_PING_ROUTE, {
27
+ method: 'POST',
28
+ credentials: 'same-origin',
29
+ headers: { 'content-type': 'application/json' },
30
+ body: JSON.stringify({ version: PANEL_VERSION, notice: String(text ?? '').slice(0, 380) }),
31
+ }).catch(() => {})
32
+ } catch {
33
+ return Promise.resolve()
34
+ }
35
+ }
36
+
37
+ const DICT = {
38
+ zh: {
39
+ open: '会话互通',
40
+ sessions: '会话',
41
+ messages: '消息',
42
+ audit: '审计',
43
+ empty: '还没有消息往来。',
44
+ unread: '未读',
45
+ live: '在线',
46
+ offline: '离线',
47
+ self: '本会话',
48
+ loading: '加载中…',
49
+ error: '读取失败',
50
+ sendTo: '发给',
51
+ send: '发送',
52
+ sending: '发送中…',
53
+ placeholder: '给这个会话发一条消息…',
54
+ sent: '已发送',
55
+ pick: '先点上面任一会话选为目标',
56
+ pendingApproval: '待批授权',
57
+ search: '搜索会话或消息…',
58
+ unreadTotal: '未读',
59
+ replyTo: '回复',
60
+ approvals: '待批(需要你点)',
61
+ grants: '授权(到期自动撤销)',
62
+ allow: '允许',
63
+ deny: '拒绝',
64
+ revokeGrant: '撤销',
65
+ jump: '去那个会话',
66
+ bridgeOff: '面板没开时审批直接按默认处理(fail closed)',
67
+ approveFailed: '提交失败',
68
+ noApprovals: '现在没有待批的审批。',
69
+ noGrants: '现在没有生效的授权。',
70
+ },
71
+ en: {
72
+ open: 'Session bus',
73
+ sessions: 'Sessions',
74
+ messages: 'Messages',
75
+ audit: 'Audit',
76
+ empty: 'No traffic yet.',
77
+ unread: 'unread',
78
+ live: 'live',
79
+ offline: 'offline',
80
+ self: 'this session',
81
+ loading: 'Loading…',
82
+ error: 'Failed to load',
83
+ sendTo: 'To',
84
+ send: 'Send',
85
+ sending: 'Sending…',
86
+ placeholder: 'Send a message to this session…',
87
+ sent: 'Sent',
88
+ pick: 'Pick a session above first',
89
+ pendingApproval: 'pending approval',
90
+ search: 'Search sessions or messages…',
91
+ unreadTotal: 'unread',
92
+ replyTo: 'reply',
93
+ approvals: 'Pending approvals',
94
+ grants: 'Grants (auto-revoke on expiry)',
95
+ allow: 'Allow',
96
+ deny: 'Deny',
97
+ revokeGrant: 'Revoke',
98
+ jump: 'Open session',
99
+ bridgeOff: 'With the panel closed, approvals fall back to the default answerer',
100
+ approveFailed: 'Submit failed',
101
+ noApprovals: 'No pending approvals.',
102
+ noGrants: 'No active grants.',
103
+ },
104
+ }
105
+
106
+ let lang = 'zh'
107
+ try {
108
+ const html = String(document?.documentElement?.lang ?? '').toLowerCase()
109
+ const nav = String(globalThis.navigator?.language ?? '').toLowerCase()
110
+ const pick = html || nav
111
+ lang = pick.startsWith('en') ? 'en' : 'zh'
112
+ } catch {
113
+ lang = 'zh'
114
+ }
115
+ const t = (key) => DICT[lang][key] ?? key
116
+
117
+ const styles = {
118
+ root: {
119
+ display: 'flex',
120
+ flexDirection: 'column',
121
+ gap: '10px',
122
+ padding: '10px 12px',
123
+ height: '100%',
124
+ overflow: 'auto',
125
+ color: 'var(--dsw-alias-label-primary, #e6e6e6)',
126
+ fontSize: '12px',
127
+ lineHeight: 1.5,
128
+ },
129
+ sectionTitle: {
130
+ fontSize: '11px',
131
+ letterSpacing: '.04em',
132
+ textTransform: 'uppercase',
133
+ color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
134
+ margin: '4px 0 2px',
135
+ },
136
+ // —— 可折叠分区(长面板的核心:默认只展开真正需要的两块)——
137
+ section: {
138
+ border: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.18))',
139
+ borderRadius: '10px',
140
+ background: 'var(--dsw-alias-bg-layer-1, rgba(128,128,128,.04))',
141
+ overflow: 'hidden',
142
+ },
143
+ sectionHead: {
144
+ display: 'flex',
145
+ alignItems: 'center',
146
+ gap: '6px',
147
+ padding: '7px 10px',
148
+ cursor: 'pointer',
149
+ userSelect: 'none',
150
+ borderBottom: '1px solid transparent',
151
+ },
152
+ sectionHeadOpen: {
153
+ borderBottomColor: 'var(--dsw-alias-border-l1, rgba(128,128,128,.18))',
154
+ },
155
+ sectionTitleText: { flex: '1 1 auto', fontSize: '12px', fontWeight: 600 },
156
+ sectionCount: {
157
+ fontSize: '12px',
158
+ padding: '1px 6px',
159
+ borderRadius: '999px',
160
+ background: 'var(--dsw-alias-bg-layer-2, rgba(128,128,128,.16))',
161
+ color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
162
+ },
163
+ chevron: { fontSize: '10px', color: 'var(--dsw-alias-label-secondary, #a0a0a0)' },
164
+ sectionBody: { padding: '8px 10px', display: 'flex', flexDirection: 'column', gap: '8px' },
165
+ scrollBox: { maxHeight: '36vh', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '2px' },
166
+ chips: { display: 'flex', flexWrap: 'wrap', gap: '6px' },
167
+ chip: {
168
+ fontSize: '12px',
169
+ padding: '2px 8px',
170
+ borderRadius: '999px',
171
+ background: 'var(--dsw-alias-bg-layer-2, rgba(128,128,128,.16))',
172
+ color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
173
+ },
174
+ row: {
175
+ display: 'flex',
176
+ alignItems: 'center',
177
+ gap: '6px',
178
+ padding: '5px 7px',
179
+ borderRadius: '6px',
180
+ background: 'var(--dsw-alias-bg-layer-1, #232323)',
181
+ // 刻意不画边框:任何 border/outline 都可能被宿主的原生 button 外观覆盖成深色描边。
182
+ // 行的可点击性靠底色 + hover 光标表达,选中靠更亮的底色与左侧细色条。
183
+ border: '0 none',
184
+ outline: '0 none',
185
+ appearance: 'none',
186
+ WebkitAppearance: 'none',
187
+ boxShadow: 'none',
188
+ cursor: 'pointer',
189
+ textAlign: 'left',
190
+ color: 'inherit',
191
+ font: 'inherit',
192
+ width: '100%',
193
+ WebkitTapHighlightColor: 'transparent',
194
+ },
195
+ rowActive: {
196
+ background: 'var(--dsw-alias-bg-layer-2, #2c2c2c)',
197
+ boxShadow: 'inset 2px 0 0 var(--dsw-alias-brand-primary, #4c8dff)',
198
+ },
199
+ name: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
200
+ dot: { width: '7px', height: '7px', borderRadius: '50%', flex: '0 0 auto' },
201
+ badge: {
202
+ flex: '0 0 auto',
203
+ minWidth: '16px',
204
+ textAlign: 'center',
205
+ padding: '0 5px',
206
+ borderRadius: '8px',
207
+ background: 'var(--dsw-alias-brand-primary, #4c8dff)',
208
+ color: 'var(--dsw-alias-bg-base, #1b1b1b)',
209
+ fontSize: '11px',
210
+ },
211
+ warn: {
212
+ flex: '0 0 auto',
213
+ padding: '0 4px',
214
+ borderRadius: '4px',
215
+ background: 'var(--dsw-alias-state-warn-primary, #d9a521)',
216
+ color: 'var(--dsw-alias-bg-base, #1b1b1b)',
217
+ fontSize: '11px',
218
+ },
219
+ meta: { color: 'var(--dsw-alias-label-secondary, #a0a0a0)', fontSize: '11px' },
220
+ summaryRow: {
221
+ display: 'flex',
222
+ alignItems: 'center',
223
+ justifyContent: 'space-between',
224
+ gap: '8px',
225
+ },
226
+ summaryButtons: { display: 'flex', gap: '6px', flex: '0 0 auto' },
227
+ tinyButton: {
228
+ cursor: 'pointer',
229
+ fontSize: '11px',
230
+ padding: '1px 6px',
231
+ borderRadius: '4px',
232
+ border: '0 none',
233
+ background: 'var(--dsw-alias-bg-layer-2, #2c2c2c)',
234
+ color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
235
+ userSelect: 'none',
236
+ },
237
+ msg: {
238
+ display: 'flex',
239
+ flexDirection: 'column',
240
+ gap: '2px',
241
+ padding: '6px 8px',
242
+ borderRadius: '6px',
243
+ background: 'var(--dsw-alias-bg-layer-2, #2c2c2c)',
244
+ border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
245
+ },
246
+ msgText: { whiteSpace: 'pre-wrap', wordBreak: 'break-word' },
247
+ search: {
248
+ width: '100%',
249
+ boxSizing: 'border-box',
250
+ height: '26px',
251
+ padding: '0 8px',
252
+ borderRadius: '6px',
253
+ border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
254
+ background: 'var(--dsw-alias-bg-layer-1, #232323)',
255
+ color: 'var(--dsw-alias-label-primary, #e6e6e6)',
256
+ font: 'inherit',
257
+ },
258
+ composer: { display: 'flex', flexDirection: 'column', gap: '6px' },
259
+ input: {
260
+ width: '100%',
261
+ boxSizing: 'border-box',
262
+ minHeight: '52px',
263
+ resize: 'vertical',
264
+ padding: '6px 8px',
265
+ borderRadius: '6px',
266
+ border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
267
+ background: 'var(--dsw-alias-bg-layer-1, #232323)',
268
+ color: 'var(--dsw-alias-label-primary, #e6e6e6)',
269
+ font: 'inherit',
270
+ },
271
+ sendRow: { display: 'flex', alignItems: 'center', gap: '8px' },
272
+ button: {
273
+ height: '26px',
274
+ padding: '0 12px',
275
+ borderRadius: '6px',
276
+ border: '1px solid var(--dsw-alias-brand-primary, #4c8dff)',
277
+ background: 'var(--dsw-alias-brand-primary, #4c8dff)',
278
+ color: 'var(--dsw-alias-bg-base, #1b1b1b)',
279
+ font: 'inherit',
280
+ cursor: 'pointer',
281
+ },
282
+ buttonDisabled: { opacity: '.5', cursor: 'not-allowed' },
283
+ error: { color: 'var(--dsw-alias-state-error-primary, #e5484d)', fontSize: '11px' },
284
+ trigger: {
285
+ display: 'inline-flex',
286
+ alignItems: 'center',
287
+ gap: '6px',
288
+ height: '26px',
289
+ padding: '0 10px',
290
+ borderRadius: '999px',
291
+ border: '1px solid var(--dsw-alias-border-l1, #3a3a3a)',
292
+ background: 'var(--dsw-alias-bg-layer-1, #232323)',
293
+ color: 'var(--dsw-alias-label-secondary, #a0a0a0)',
294
+ fontSize: '12px',
295
+ cursor: 'pointer',
296
+ },
297
+ }
298
+
299
+ function useBusState(sessionId, reloadToken) {
300
+ const [state, setState] = React.useState({ loading: true, error: null, data: null })
301
+ React.useEffect(() => {
302
+ let alive = true
303
+ const controller = new AbortController()
304
+ const load = async () => {
305
+ try {
306
+ // 浮层槽(root scope)不会注入 sessionId,此时取全量即可——
307
+ // 路由本身允许不带 session 参数(返回全部会话 + 汇总)。
308
+ const url = sessionId
309
+ ? `${STATE_ROUTE}?session=${encodeURIComponent(sessionId)}`
310
+ : STATE_ROUTE
311
+ const response = await fetch(url, {
312
+ credentials: 'same-origin',
313
+ signal: controller.signal,
314
+ })
315
+ const body = await response.json()
316
+ if (!alive) return
317
+ setState(body.ok ? { loading: false, error: null, data: body } : { loading: false, error: body.error ?? t('error'), data: null })
318
+ } catch (error) {
319
+ if (!alive || controller.signal.aborted) return
320
+ setState((prev) => ({ ...prev, loading: false, error: String(error?.message ?? error) }))
321
+ }
322
+ }
323
+ void load()
324
+ const timer = setInterval(load, 3000)
325
+ return () => {
326
+ alive = false
327
+ controller.abort()
328
+ clearInterval(timer)
329
+ }
330
+ }, [sessionId, reloadToken])
331
+ return state
332
+ }
333
+
334
+ // 跨会话审批看板:轮询宿主侧的「挂起的审批」。这个请求同时是心跳——
335
+ // 面板关掉就不再轮询,宿主就不会为我们挂起任何审批(原有 fail-closed 行为不变)。
336
+ function useBusApprovals(reloadToken) {
337
+ const [state, setState] = React.useState({ pending: [], bridge: false, error: null })
338
+ React.useEffect(() => {
339
+ let alive = true
340
+ const controller = new AbortController()
341
+ const load = async () => {
342
+ try {
343
+ const response = await fetch(APPROVALS_ROUTE, { credentials: 'same-origin', signal: controller.signal })
344
+ const body = await response.json()
345
+ if (!alive) return
346
+ setState({ pending: Array.isArray(body.pending) ? body.pending : [], bridge: body.bridge === true, error: body.ok ? null : (body.error ?? t('error')) })
347
+ } catch (error) {
348
+ if (!alive || controller.signal.aborted) return
349
+ setState((prev) => ({ ...prev, error: String(error?.message ?? error) }))
350
+ }
351
+ }
352
+ void load()
353
+ const timer = setInterval(load, 3000)
354
+ return () => {
355
+ alive = false
356
+ controller.abort()
357
+ clearInterval(timer)
358
+ }
359
+ }, [reloadToken])
360
+ return state
361
+ }
362
+
363
+ function formatTime(ts) {
364
+ if (!ts) return ''
365
+ try {
366
+ return new Date(ts).toLocaleTimeString(lang === 'zh' ? 'zh-CN' : 'en-US', { hour12: false })
367
+ } catch {
368
+ return ''
369
+ }
370
+ }
371
+
372
+ function BusPanel(props) {
373
+ const sessionId = props.sessionId
374
+ const [reloadToken, setReloadToken] = React.useState(0)
375
+ const { loading, error, data } = useBusState(sessionId, reloadToken)
376
+ const approvals = useBusApprovals(reloadToken)
377
+ const [target, setTarget] = React.useState('')
378
+ const [draft, setDraft] = React.useState('')
379
+ const [sending, setSending] = React.useState(false)
380
+ const [sendError, setSendError] = React.useState('')
381
+ const [sentNote, setSentNote] = React.useState('')
382
+ const [search, setSearch] = React.useState('')
383
+
384
+ const sessions = data?.sessions ?? []
385
+ const messages = (data?.messages ?? []).slice(-30).reverse()
386
+ const audit = (data?.audit ?? []).slice(-8).reverse()
387
+ const targetRow = sessions.find((row) => row.id === target)
388
+
389
+ React.useEffect(() => {
390
+ if (target) return
391
+ const first = sessions.find((row) => !row.isSelf)
392
+ if (first) setTarget(first.id)
393
+ }, [sessions, target])
394
+
395
+ const doSend = React.useCallback(async () => {
396
+ if (!target) return
397
+ const text = draft.trim()
398
+ if (!text) {
399
+ setSendError(t('send') + ':' + '内容不能为空')
400
+ return
401
+ }
402
+ if (new TextEncoder().encode(text).length > 4096) {
403
+ setSendError('消息过长(上限 4096 字节)')
404
+ return
405
+ }
406
+ setSending(true)
407
+ setSendError('')
408
+ setSentNote('')
409
+ try {
410
+ const response = await fetch(SEND_ROUTE, {
411
+ method: 'POST',
412
+ credentials: 'same-origin',
413
+ headers: { 'content-type': 'application/json' },
414
+ body: JSON.stringify({ from: sessionId, to: target, text }),
415
+ })
416
+ const body = await response.json()
417
+ if (body.ok) {
418
+ setDraft('')
419
+ setSentNote(`${t('sent')} · ${body.status ?? ''}`)
420
+ setReloadToken((n) => n + 1)
421
+ } else {
422
+ setSendError(body.error ?? t('error'))
423
+ }
424
+ } catch (sendFailure) {
425
+ setSendError(String(sendFailure?.message ?? sendFailure))
426
+ } finally {
427
+ setSending(false)
428
+ }
429
+ }, [draft, sessionId, target])
430
+
431
+ // 审批:允许 / 拒绝 → 宿主侧的 waterfall 句柄(不是 $events/result,那个要浏览器自己的 clientId)
432
+ const doApprove = React.useCallback(async (id, decision) => {
433
+ setSendError('')
434
+ try {
435
+ const response = await fetch(APPROVE_ROUTE, {
436
+ method: 'POST',
437
+ credentials: 'same-origin',
438
+ headers: { 'content-type': 'application/json' },
439
+ body: JSON.stringify({ id, decision }),
440
+ })
441
+ const body = await response.json()
442
+ if (!body.ok) setSendError(`${t('approveFailed')}: ${body.error ?? ''}`)
443
+ setReloadToken((n) => n + 1)
444
+ } catch (failure) {
445
+ setSendError(`${t('approveFailed')}: ${String(failure?.message ?? failure)}`)
446
+ }
447
+ }, [])
448
+
449
+ const doRevoke = React.useCallback(async (id) => {
450
+ setSendError('')
451
+ try {
452
+ const response = await fetch(REVOKE_ROUTE, {
453
+ method: 'POST',
454
+ credentials: 'same-origin',
455
+ headers: { 'content-type': 'application/json' },
456
+ body: JSON.stringify({ id }),
457
+ })
458
+ const body = await response.json()
459
+ if (!body.ok) setSendError(body.error ?? t('error'))
460
+ setReloadToken((n) => n + 1)
461
+ } catch (failure) {
462
+ setSendError(String(failure?.message ?? failure))
463
+ }
464
+ }, [])
465
+
466
+ // 只看不动地跳到那个会话(宿主没把审批句柄交给面板时用这个)
467
+ const jumpTo = React.useCallback((id) => {
468
+ try {
469
+ const workspace = busCtx?.get?.('uiWorkspace')
470
+ if (workspace && typeof workspace.openSession === 'function') workspace.openSession(id)
471
+ } catch (failure) {
472
+ console.warn('session-bus: 打开会话失败', failure)
473
+ }
474
+ }, [])
475
+
476
+ const needle = search.trim().toLowerCase()
477
+ const sessionsShown = needle
478
+ ? sessions.filter((row) => `${row.title} ${row.id}`.toLowerCase().includes(needle))
479
+ : sessions
480
+ const messagesShown = needle
481
+ ? messages.filter((m) => `${m.text} ${m.from} ${m.to}`.toLowerCase().includes(needle))
482
+ : messages
483
+
484
+ const children = []
485
+ if (loading) children.push(h('div', { key: 'loading', style: styles.meta }, t('loading')))
486
+ if (error) children.push(h('div', { key: 'err', style: styles.error }, `${t('error')}: ${error}`))
487
+
488
+ // 顶部一行:几个关键计数做成 chip + 刷新按钮(不占高度)
489
+ const pendingTotal = sessions.filter((row) => (row.pendingApprovals ?? 0) > 0).length
490
+ const mode = data?.mode ?? null
491
+ const presetOptions = Array.isArray(data?.presetOptions) ? data.presetOptions : []
492
+ const doSetPreset = async (name) => {
493
+ if (!sessionId) return
494
+ setSendError('')
495
+ try {
496
+ const response = await fetch(SET_PRESET_ROUTE, {
497
+ method: 'POST',
498
+ credentials: 'same-origin',
499
+ headers: { 'content-type': 'application/json' },
500
+ body: JSON.stringify({ session: sessionId, name }),
501
+ })
502
+ const body = await response.json()
503
+ if (!body.ok) setSendError(body.error ?? t('error'))
504
+ setReloadToken((n) => n + 1)
505
+ } catch (failure) {
506
+ setSendError(String(failure?.message ?? failure))
507
+ }
508
+ }
509
+ const modeLabel = mode === null
510
+ ? ''
511
+ : `${mode.presetName ?? '自定义'}${mode.sandboxMode ? ` · ${mode.sandboxMode === 'danger-full-access' ? '全权限' : mode.sandboxMode === 'read-only' ? '只读' : '工作区'}` : ''}${mode.approvalPolicy === 'ask' ? ' · 会问' : mode.approvalPolicy === 'never' ? ' · 不问' : ''}`
512
+ children.push(h('div', { key: 'summary', style: styles.summaryRow },
513
+ h('span', { style: styles.chips },
514
+ modeLabel ? h('span', { key: 'mode', style: { ...styles.chip, color: 'var(--dsw-alias-brand-primary, #4c7dff)' }, title: '当前会话:沙箱 / 审批 / 命中的预设' }, modeLabel) : null,
515
+ h('span', { style: styles.chip }, `${t('unreadTotal')} ${data?.totalUnread ?? 0}`),
516
+ h('span', { style: styles.chip }, `${t('sessions')} ${sessions.length}`),
517
+ pendingTotal > 0 ? h('span', { style: { ...styles.chip, ...styles.warn } }, `⚠ ${pendingTotal}`) : null,
518
+ ),
519
+ // 只保留「刷新数据」:这个只是重新拉一次 /api/state,安全。
520
+ // 绝对不要放 window.location.reload() —— 实测点了会让整个应用崩掉(21:00 那次),
521
+ // 这也解释了为什么用户按 F5 感觉「没用」:F5 走的是同一条崩溃路径。
522
+ h('span', { style: styles.summaryButtons },
523
+ h('span', {
524
+ style: styles.tinyButton,
525
+ title: '重新拉取一次面板数据(不会重载页面,安全)',
526
+ onClick: () => setReloadToken((n) => n + 1),
527
+ }, '刷新'),
528
+ ),
529
+ ))
530
+ // 新建会话(原生创建,立刻是真会话,不是草稿)
531
+
532
+ // 一键切预设:不依赖那个只有三档的沙箱快关
533
+ if (sessionId && presetOptions.length > 0) {
534
+ children.push(h('div', { key: 'presets', style: styles.chips },
535
+
536
+ ...presetOptions.map((option) => h('button', {
537
+ key: `pp-${option.name}`,
538
+ type: 'button',
539
+ title: option.description || option.name,
540
+ onClick: () => { void doSetPreset(option.name) },
541
+ style: option.label === mode?.presetName
542
+ ? { ...styles.tinyButton, borderColor: 'var(--dsw-alias-brand-primary, #4c7dff)' }
543
+ : styles.tinyButton,
544
+ }, option.label || option.name)),
545
+ ))
546
+ }
547
+
548
+ // 发送区(面板的核心能力:能发,而不只是看)
549
+ children.push(h('div', { key: 'composer', style: styles.composer },
550
+ h('div', { style: styles.meta },
551
+ `${t('sendTo')}:` + (targetRow ? targetRow.title : t('pick')),
552
+ targetRow && targetRow.pendingApprovals > 0
553
+ ? h('span', { style: { ...styles.warn, marginLeft: '6px' } }, `${t('pendingApproval')} ${targetRow.pendingApprovals}`)
554
+ : null),
555
+ h('textarea', {
556
+ style: styles.input,
557
+ value: draft,
558
+ placeholder: t('placeholder'),
559
+ onChange: (event) => setDraft(event.target.value),
560
+ }),
561
+ h('div', { style: styles.sendRow },
562
+ h('button', {
563
+ type: 'button',
564
+ style: { ...styles.button, ...(sending || !target || !draft.trim() ? styles.buttonDisabled : {}) },
565
+ disabled: sending || !target || !draft.trim(),
566
+ onClick: () => { void doSend() },
567
+ }, sending ? t('sending') : t('send')),
568
+ sentNote ? h('span', { style: styles.meta }, sentNote) : null,
569
+ sendError ? h('span', { style: styles.error }, sendError) : null,
570
+ ),
571
+ ))
572
+
573
+ // 待批:① 宿主挂起、面板可直接拍的 → 允许/拒绝;② 别的会话里在等、我们没句柄的 → 去那个会话
574
+ const bridged = approvals.pending ?? []
575
+ const waiting = sessions.filter((row) => (row.pendingApprovals ?? 0) > 0 && !bridged.some((item) => item.sessionId === row.id))
576
+ const pendingCount = bridged.length + waiting.length
577
+ if (pendingCount > 0) {
578
+ const pendingRows = []
579
+ for (const item of bridged) {
580
+ pendingRows.push(h('div', { key: `ap-${item.id}`, style: styles.msg },
581
+ h('div', { style: styles.meta }, `${item.sessionTitle || String(item.sessionId).slice(0, 8)} · ${item.toolName} · ${item.waitingMinutes}m`),
582
+ h('div', { style: styles.msgText }, item.reason || item.en || ''),
583
+ h('div', { style: styles.sendRow },
584
+ h('button', { type: 'button', style: styles.tinyButton, onClick: () => { void doApprove(item.id, 'allow') } }, t('allow')),
585
+ h('button', { type: 'button', style: styles.tinyButton, onClick: () => { void doApprove(item.id, 'deny') } }, t('deny')),
586
+ ),
587
+ ))
588
+ }
589
+ for (const row of waiting) {
590
+ pendingRows.push(h('div', { key: `aw-${row.id}`, style: styles.msg },
591
+ h('div', { style: styles.meta }, `${row.title} · ${t('pendingApproval')} ${row.pendingApprovals}`),
592
+ h('div', { style: styles.sendRow },
593
+ h('button', { type: 'button', style: styles.tinyButton, onClick: () => jumpTo(row.id) }, t('jump')),
594
+ ),
595
+ ))
596
+ }
597
+ children.push(h(Section, { key: 'sec-approvals', id: 'approvals', title: t('approvals'), count: pendingCount }, pendingRows))
598
+ }
599
+
600
+ // 授权台账:目录授权带倒计时,可直接撤销
601
+ const grants = data?.grants ?? []
602
+ if (grants.length > 0) {
603
+ const grantRows = grants.map((grant) => {
604
+ const remain = grant.remainingMinutes === null || grant.remainingMinutes === undefined ? '—' : `${grant.remainingMinutes}m`
605
+ return h('div', { key: `g-${grant.id}`, style: styles.msg },
606
+ h('div', { style: styles.meta },
607
+ `${String(grant.sessionId).slice(0, 8)} · ${grant.kind} · ${remain}${grant.dir ? ` · ${grant.dir}` : ''}`),
608
+ h('div', { style: styles.sendRow },
609
+ h('button', { type: 'button', style: styles.tinyButton, onClick: () => { void doRevoke(grant.id) } }, t('revokeGrant')),
610
+ ),
611
+ )
612
+ })
613
+ children.push(h(Section, { key: 'sec-grants', id: 'grants', title: t('grants'), count: grants.length }, grantRows))
614
+ }
615
+
616
+ // 会话:面板最常用的一块,放在消息之前,自带滚动框
617
+ const sessionRows = []
618
+ for (const row of sessionsShown.slice(0, 40)) {
619
+ const active = row.id === target
620
+ // 用 div 而不是 button:button 自带浏览器默认边框,一旦某个 CSS token 没解析出来
621
+ // 就会退回深色描边,看起来像「全被选中」。div + role=button 没有这个问题。
622
+ sessionRows.push(h('div', {
623
+ key: `s-${row.id}`,
624
+ role: 'button',
625
+ tabIndex: -1,
626
+ title: row.cwd,
627
+ onClick: () => setTarget(row.id),
628
+ style: { ...styles.row, ...(active ? styles.rowActive : {}) },
629
+ },
630
+ h('span', {
631
+ style: { ...styles.dot, background: row.live ? 'var(--dsw-alias-state-success-primary, #35c46a)' : 'var(--dsw-alias-state-idle-primary, #8a8a8a)' },
632
+ title: row.live ? t('live') : t('offline'),
633
+ }),
634
+ h('span', { style: styles.name }, row.title + (row.isSelf ? ` · ${t('self')}` : '')),
635
+ row.pendingApprovals > 0 ? h('span', { style: styles.warn }, `⚠${row.pendingApprovals}`) : null,
636
+ row.unread > 0 ? h('span', { style: styles.badge }, String(row.unread)) : null,
637
+ ))
638
+ }
639
+ if (sessionsShown.length > 40) {
640
+ sessionRows.push(h('div', { key: 'more', style: styles.meta }, `…还有 ${sessionsShown.length - 40} 个(用搜索缩小)`))
641
+ }
642
+ children.push(h(Section, { key: 'sec-sessions', id: 'sessions', title: t('sessions'), count: sessionsShown.length },
643
+ h('input', {
644
+ key: 'search',
645
+ style: styles.search,
646
+ value: search,
647
+ placeholder: t('search'),
648
+ onChange: (event) => setSearch(event.target.value),
649
+ }),
650
+ h('div', { style: styles.scrollBox }, sessionRows)))
651
+
652
+ // 消息:默认收起(面板里最长的东西)
653
+ const messageRows = messages.length === 0
654
+ ? [h('div', { key: 'empty', style: styles.meta }, t('empty'))]
655
+ : messagesShown.map((message) => h('div', { key: message.id, style: styles.msg },
656
+ h('div', { style: styles.meta },
657
+ `${String(message.from).replace(/^session-/, '').slice(0, 8)} → ${String(message.to).replace(/^session-/, '').slice(0, 8)} · ${formatTime(message.ts)} · ${message.status}`),
658
+ message.replyTo ? h('div', { style: styles.meta }, `↩ ${t('replyTo')} ${String(message.replyTo).slice(0, 14)}`) : null,
659
+ h('div', { style: styles.msgText }, message.text),
660
+ ))
661
+ children.push(h(Section, { key: 'sec-messages', id: 'messages', title: t('messages'), count: messages.length },
662
+ h('div', { style: styles.scrollBox }, messageRows)))
663
+
664
+ // 审计:默认收起
665
+ if (audit.length > 0) {
666
+ const auditRows = audit.map((row) => h('div', { key: `a-${row.ts}-${row.action}`, style: styles.meta },
667
+ `${formatTime(row.ts)} ${row.action} ${row.target ? String(row.target).replace(/^session-/, '').slice(0, 8) : ''}`))
668
+ children.push(h(Section, { key: 'sec-audit', id: 'audit', title: t('audit'), count: audit.length }, auditRows))
669
+ }
670
+
671
+ return h('div', { style: styles.root }, children)
672
+ }
673
+
674
+ function OpenButton() {
675
+ const [open, setOpen] = useBusOpen()
676
+ const onClick = React.useCallback(() => {
677
+ // 右栏服务存在时优先用右栏(老宿主),否则切浮层(rc.5+)。
678
+ const right = busCtx?.get?.('sidebarRight')
679
+ if (right && busCtx?.get?.('sidebarRightTabs')) {
680
+ try {
681
+ right.openTab(KIND)
682
+ busCtx?.get?.('layout')?.openRightbar?.(true, false)
683
+ return
684
+ } catch (error) {
685
+ console.warn('session-bus: 右栏打开失败,退回浮层', error)
686
+ }
687
+ }
688
+ setOpen(!open)
689
+ }, [open])
690
+ return h('button', { type: 'button', style: styles.trigger, onClick, title: t('open') },
691
+ h('span', { 'aria-hidden': true }, '⇄'),
692
+ h('span', null, t('open')),
693
+ )
694
+ }
695
+
696
+ let busCtx = null
697
+
698
+ // ── 开合状态(模块级小 store)──────────────────────────────────────────
699
+ // 按钮和浮层是两个独立槽位,必须共享同一份状态;内置只有 React,
700
+ // 没有 ReactDOM,所以不自己 portal,直接注册到宿主的 shell.overlay 槽。
701
+ const busState = { open: false, listeners: new Set() }
702
+ function setBusOpen(next) {
703
+ if (busState.open === next) return
704
+ busState.open = next
705
+ for (const fn of busState.listeners) {
706
+ try { fn() } catch { /* 单个订阅者出错不影响其它 */ }
707
+ }
708
+ }
709
+ // ── 可折叠分区 ────────────────────────────────────────────────────────
710
+ // 面板曾经是"一长条",消息/审计把会话列表挤到很下面,要滚很久。现在:
711
+ // 会话常开(自带滚动),消息/审计默认收起,待批/授权只有真有内容才出现。
712
+ const sectionOpen = { sessions: true, approvals: true, grants: true, messages: false, audit: false }
713
+ const sectionListeners = new Set()
714
+ function toggleSection(id) {
715
+ sectionOpen[id] = !sectionOpen[id]
716
+ for (const fn of sectionListeners) {
717
+ try { fn() } catch { /* 单个订阅者出错不影响其它 */ }
718
+ }
719
+ }
720
+ function useSectionOpen(id) {
721
+ const [open, setOpen] = React.useState(sectionOpen[id] !== false)
722
+ React.useEffect(() => {
723
+ const fn = () => setOpen(sectionOpen[id] !== false)
724
+ sectionListeners.add(fn)
725
+ return () => { sectionListeners.delete(fn) }
726
+ }, [id])
727
+ return open
728
+ }
729
+
730
+ function Section({ id, title, count, children }) {
731
+ const open = useSectionOpen(id)
732
+ return h('div', { style: styles.section },
733
+ h('div', {
734
+ role: 'button',
735
+ tabIndex: -1,
736
+ onClick: () => toggleSection(id),
737
+ style: { ...styles.sectionHead, ...(open ? styles.sectionHeadOpen : {}) },
738
+ title: open ? '收起' : '展开',
739
+ },
740
+ h('span', { style: styles.chevron }, open ? '▾' : '▸'),
741
+ h('span', { style: styles.sectionTitleText }, title),
742
+ h('span', { style: styles.sectionCount }, String(count ?? '')),
743
+ ),
744
+ open ? h('div', { style: styles.sectionBody }, children) : null,
745
+ )
746
+ }
747
+
748
+ function useBusOpen() { const [open, setOpen] = React.useState(busState.open)
749
+ React.useEffect(() => {
750
+ const fn = () => setOpen(busState.open)
751
+ busState.listeners.add(fn)
752
+ fn()
753
+ return () => { busState.listeners.delete(fn) }
754
+ }, [])
755
+ return [open, setBusOpen]
756
+ }
757
+
758
+ // 浮层槽里的宿主:打开时渲染面板 + 遮罩,关闭时渲染 null。
759
+ function BusOverlay() {
760
+ const [open, setOpen] = useBusOpen()
761
+ if (!open) return null
762
+ return h('div', {
763
+ style: {
764
+ position: 'fixed',
765
+ // 顶部让出 44px:右上角是窗口的最小化/最大化/关闭,不能盖住。
766
+ top: '44px',
767
+ right: '0',
768
+ bottom: '0',
769
+ zIndex: 40,
770
+ display: 'flex',
771
+ justifyContent: 'flex-end',
772
+ background: 'rgba(0, 0, 0, 0.18)',
773
+ },
774
+ onClick: (event) => { if (event.target === event.currentTarget) setOpen(false) },
775
+ }, h('div', {
776
+ style: {
777
+ width: 'min(420px, 92vw)',
778
+ height: '100%',
779
+ display: 'flex',
780
+ flexDirection: 'column',
781
+ overflow: 'hidden',
782
+ // 用宿主真实主题变量(--dsw-alias-*)。之前写成 --dsh-surface 不存在,
783
+ // 于是落到深色兜底,浅色主题下就是一块黑的。
784
+ background: 'var(--dsw-alias-bg-overlay, var(--dsw-alias-bg-layer-1, #ffffff))',
785
+ color: 'var(--dsw-alias-label-primary, #1b1b1b)',
786
+ borderLeft: '1px solid var(--dsw-alias-border-l1, #d9d9d9)',
787
+ borderTopLeftRadius: '10px',
788
+ boxShadow: '-8px 0 24px rgba(0, 0, 0, 0.18)',
789
+ },
790
+ }, [
791
+ // 顶部操作条:标题 + 关闭
792
+ h('div', {
793
+ key: 'bar',
794
+ style: {
795
+ display: 'flex',
796
+ alignItems: 'center',
797
+ justifyContent: 'space-between',
798
+ gap: '8px',
799
+ padding: '8px 12px',
800
+ borderBottom: '1px solid var(--dsw-alias-border-l1, #d9d9d9)',
801
+ flex: '0 0 auto',
802
+ },
803
+ }, [
804
+ h('span', { key: 'title', style: { fontSize: '12px', fontWeight: 600 } }, t('open')),
805
+ h('button', {
806
+ key: 'close',
807
+ type: 'button',
808
+ onClick: () => setOpen(false),
809
+ title: '关闭',
810
+ style: {
811
+ border: '0 none',
812
+ background: 'transparent',
813
+ color: 'var(--dsw-alias-label-secondary, #666)',
814
+ cursor: 'pointer',
815
+ fontSize: '14px',
816
+ lineHeight: 1,
817
+ padding: '2px 6px',
818
+ borderRadius: '6px',
819
+ appearance: 'none',
820
+ },
821
+ }, '×'),
822
+ ]),
823
+ h('div', { key: 'body', style: { flex: '1 1 auto', minHeight: '0', overflowY: 'auto' } },
824
+ h(BusPanel)),
825
+ ]))
826
+ }
827
+
828
+ return {
829
+ // ⚠️ inject 是**硬依赖**:列了宿主没有的服务 → 整个客户端半边静默不加载。
830
+ // rc.5 实测客户端只有 layout / locale / sessions / slots / theme / timer /
831
+ // uiWorkspace / workspaces —— sidebarRight / sidebarRightTabs **不存在**
832
+ // (0.2.0 起所有人没面板的真因)。侧栏相关一律用 ctx.get 做可选。
833
+ inject: ['slots', 'layout', 'locale'],
834
+ apply(ctx) {
835
+ busCtx = ctx
836
+ // 以页面 <html lang> 为准:宿主界面是中文时它一定是 zh-CN;
837
+ // ctx.locale 的 id 在桌面端可能是 'en' 而界面仍是中文,不能拿来判语言。
838
+ try {
839
+ const html = String(document?.documentElement?.lang ?? '').toLowerCase()
840
+ if (html) lang = html.startsWith('en') ? 'en' : 'zh'
841
+ } catch { /* 保持默认(中文) */ }
842
+
843
+ // 老宿主兼容:有右栏服务就额外注册一个标签(新宿主没有,走浮层)。
844
+ const tabs = ctx.get('sidebarRightTabs')
845
+ if (tabs) {
846
+ ctx.effect(() => tabs.register({
847
+ id: KIND,
848
+ kind: KIND,
849
+ title: () => t('open'),
850
+ }), 'session-bus: tab type')
851
+
852
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
853
+ name: 'sidebar.right.pane.tab',
854
+ key: KIND,
855
+ }, BusPanel)), 'session-bus: tab body')
856
+ }
857
+
858
+ // 浮层宿主(rc.5 起的主形态)
859
+ ctx.effect(() => ctx.slots.inject('shell.overlay', () => ctx.slots.register({
860
+ name: 'shell.overlay',
861
+ id: 'session-bus-panel',
862
+ order: 90,
863
+ }, BusOverlay)), 'session-bus: overlay')
864
+
865
+ // 输入框下方的开合按钮
866
+ ctx.effect(() => ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
867
+ name: 'conversation.composer.dock',
868
+ id: 'session-bus-open',
869
+ order: 90,
870
+ }, OpenButton)), 'session-bus: open button')
871
+
872
+ // 实验(0.3.2):客户端到底能不能收到别的会话的 approval/request?
873
+ // 能收到 → 才有资格谈「面板一键批」;同时把 this 上的相关字段上报,看有没有 clientId/eventId。
874
+ // 无论结果如何都 return next(),不影响内置审批卡。
875
+ ctx.effect(() => {
876
+ const remote = ctx.get('remote')
877
+ if (remote === undefined || typeof remote.$on !== 'function') {
878
+ void reportNotice('client-remote-unavailable')
879
+ return () => {}
880
+ }
881
+ void reportNotice('client-remote-ok')
882
+ return remote.$on('approval/request', function approvalObserver(request, next) {
883
+ try {
884
+ const read = (pick) => {
885
+ try { return pick() } catch { return '?' }
886
+ }
887
+ const keys = read(() => Object.keys(this ?? {}).join('|'))
888
+ const eventId = read(() => String(this?.eventId ?? ''))
889
+ const clientId = read(() => String(this?.clientId ?? ''))
890
+ const sessionId = read(() => String(request?.agent?.session?.id ?? request?.agent?.id ?? ''))
891
+ void reportNotice(
892
+ `client-approval-seen tool=${String(request?.toolName ?? '?')} session=${sessionId.slice(0, 16)} `
893
+ + `eventId=${eventId.slice(0, 24)} clientId=${clientId.slice(0, 24)} thisKeys=${keys.slice(0, 120)}`,
894
+ )
895
+ } catch { /* 上报失败绝不影响审批 */ }
896
+ return next()
897
+ })
898
+ }, 'session-bus: approval observer (experiment)')
899
+
900
+ // 版本握手:面板一挂载就报版本,之后每分钟一次。
901
+ // 宿主侧 /api/state 的 panelVersion / panelPingMinutesAgo 就是「新面板到底上没上」的判据。
902
+ ctx.effect(() => {
903
+ const ping = () => {
904
+ try {
905
+ void fetch(PANEL_PING_ROUTE, {
906
+ method: 'POST',
907
+ credentials: 'same-origin',
908
+ headers: { 'content-type': 'application/json' },
909
+ body: JSON.stringify({ version: PANEL_VERSION }),
910
+ }).catch(() => {})
911
+ } catch { /* 上报失败不影响面板 */ }
912
+ }
913
+ ping()
914
+ const timer = setInterval(ping, 60000)
915
+ return () => clearInterval(timer)
916
+ }, 'session-bus: panel ping')
917
+ },
918
+ }
919
+ },
920
+ })
921
+
922
+
923
+