@ruoy/dsh-session-bus 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,473 @@
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
+