@restregular/dsh-team-hub 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/client.js ADDED
@@ -0,0 +1,934 @@
1
+ /**
2
+ * @restregular/dsh-team-hub — Client half: canvas-style team board.
3
+ * 整文件包在 IIFE 里,避免与其它插件的顶层 const/let 共享全局词法作用域。
4
+ */
5
+ (() => {
6
+ const MODULE_ID = '@restregular/dsh-team-hub'
7
+ const loader = window.__ModuleLoader__
8
+ if (!loader || typeof loader.load !== 'function') return
9
+ if (loader.factories?.has?.(MODULE_ID)) return
10
+
11
+ loader.load({
12
+ id: MODULE_ID,
13
+ factory(require) {
14
+ const React = require('react')
15
+ const { useState, useEffect, useRef, useCallback, useMemo } = React
16
+ const h = React.createElement
17
+ const PANEL_ID = 'team-hub'
18
+ const NS = 'teamHub'
19
+ const API = '/team-hub/api'
20
+ const TAB_KIND = 'team-hub-canvas'
21
+ const TAB_ID = '@restregular/dsh-team-hub/canvas'
22
+ let boundWorkspace = null
23
+ let boundWorkspaceTitle = ''
24
+ let sidebarRightSvc = null
25
+
26
+ /* ------------------------------------------------------------- 数据 */
27
+ async function api(path, options = {}) {
28
+ const opts = { ...options }
29
+ if (opts.body && typeof opts.body !== 'string') {
30
+ opts.body = JSON.stringify(opts.body)
31
+ opts.headers = { 'content-type': 'application/json', ...(opts.headers || {}) }
32
+ }
33
+ const res = await fetch(API + path, opts)
34
+ let data
35
+ try { data = await res.json() } catch { throw new Error(`HTTP ${res.status}`) }
36
+ if (!data?.ok) throw new Error(data?.error?.message || `HTTP ${res.status}`)
37
+ return data.value
38
+ }
39
+
40
+ const STATUS_LABEL = {
41
+ uninstantiated: '还未实例化', idle: '空闲', working: '工作中',
42
+ done: '已完成', failed: '失败', archived: '已归档',
43
+ }
44
+ function statusOf(agent) { return agent?.sessionId ? (agent.status || 'idle') : 'uninstantiated' }
45
+ function initText(agent) {
46
+ const p = [`你现在是团队中的「${agent.name}」。`]
47
+ if (agent.identity) p.push(`身份:${agent.identity}`)
48
+ if (agent.duties) p.push(`职责边界:${agent.duties}`)
49
+ const perm = agent.permissions || {}
50
+ if (perm.denyTools?.length) p.push(`禁止使用的工具:${perm.denyTools.join('、')}(硬约束,由系统强制执行)。`)
51
+ if (perm.writeFiles?.length) p.push(`允许写入的文件范围:${perm.writeFiles.join('、')}。`)
52
+ if (perm.readFiles?.length) p.push(`可读文件范围:${perm.readFiles.join('、')}。`)
53
+ p.push('请确认已了解上述设定,等待团队协作消息。')
54
+ return p.join('\n')
55
+ }
56
+
57
+ /* -------------------------------------------------------- 事件解析 */
58
+ function contentText(content) {
59
+ if (!Array.isArray(content)) return ''
60
+ return content.filter((b) => b && typeof b.text === 'string').map((b) => b.text).join('')
61
+ }
62
+ function cleanUserText(text) {
63
+ return String(text || '')
64
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
65
+ .replace(/^\s*以下是(?:本项目|与)[\s\S]*?(?:记忆摘要|相关的记忆)/gm, '')
66
+ .trim()
67
+ }
68
+ function parseEvent(ev) {
69
+ if (!ev) return null
70
+ const d = ev.data || {}
71
+ const seq = typeof ev.seq === 'number' ? ev.seq : Date.now()
72
+ switch (ev.type) {
73
+ case 'assistant/message': {
74
+ const text = contentText(d.message?.content)
75
+ return text ? { kind: 'assistant', text, seq } : null
76
+ }
77
+ case 'user/message': {
78
+ const text = cleanUserText(contentText(d.content))
79
+ return text ? { kind: 'user', text, seq } : null
80
+ }
81
+ case 'tool/call': return { kind: 'tool', text: `调用工具 ${d.name || ''}`, seq }
82
+ case 'tool/result': {
83
+ const text = contentText(d.message?.content) || '工具结果'
84
+ return { kind: d.error ? 'error' : 'tool', text, seq }
85
+ }
86
+ case 'turn/end': {
87
+ const reason = d.reason && typeof d.reason === 'object' ? (d.reason.kind || d.reason.reason || 'complete') : d.reason
88
+ return { kind: 'turn', text: `本轮结束${reason ? `(${reason})` : ''}`, seq }
89
+ }
90
+ default: return null
91
+ }
92
+ }
93
+
94
+ function useAgentFeed(ctx, sessionId) {
95
+ const [feed, setFeed] = useState([])
96
+ useEffect(() => {
97
+ setFeed([])
98
+ if (!sessionId || !ctx?.sessions?.retain) return
99
+ let ref, off, disposed = false
100
+ const read = () => {
101
+ if (disposed || !ref) return
102
+ const entries = ref.binding?.eventSource?.getSnapshot()?.entries || []
103
+ const items = []
104
+ for (const e of entries) {
105
+ const parsed = parseEvent(e?.event)
106
+ if (parsed) items.push(parsed)
107
+ }
108
+ setFeed(items.slice(-20))
109
+ }
110
+ try {
111
+ ref = ctx.sessions.retain(sessionId, { source: 'teamHub' })
112
+ Promise.resolve(ref?.ready).then(() => {
113
+ if (disposed) { ref?.release?.(); return }
114
+ read()
115
+ off = ref.binding?.eventSource?.subscribe(read)
116
+ }).catch((err) => console.warn('[team-hub] feed ready failed:', err?.message))
117
+ } catch (err) { console.warn('[team-hub] retain failed:', err?.message) }
118
+ return () => { disposed = true; off?.(); ref?.release?.() }
119
+ }, [ctx, sessionId])
120
+ return feed
121
+ }
122
+
123
+ function useRemoteNotices(ctx) {
124
+ const [notices, setNotices] = useState({})
125
+ useEffect(() => {
126
+ if (!ctx?.remote?.$on) return
127
+ const push = (kind, payload) => {
128
+ const sid = payload?.agent?.session?.id
129
+ if (!sid) return
130
+ const text = kind === 'approval'
131
+ ? `审批请求:${payload.toolName || ''}${payload.reason ? ` — ${payload.reason}` : ''}`
132
+ : `提问:${(payload.questions || []).map((q) => q.question || q.title || '').join(' / ')}`
133
+ setNotices((m) => ({ ...m, [sid]: [...(m[sid] || []), { kind, text, ts: Date.now() }].slice(-8) }))
134
+ }
135
+ try {
136
+ const offA = ctx.remote.$on('approval/request', (p) => push('approval', p))
137
+ const offQ = ctx.remote.$on('user-questions/request', (p) => push('question', p))
138
+ return () => { offA?.(); offQ?.() }
139
+ } catch (err) { console.warn('[team-hub] remote notices:', err?.message) }
140
+ }, [ctx])
141
+ return notices
142
+ }
143
+
144
+ /* ----------------------------------------------------------- 图标 */
145
+ function HubIcon({ size = 16, active }) {
146
+ return h('svg', {
147
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
148
+ stroke: 'currentColor', 'stroke-width': active ? 2.2 : 1.8,
149
+ 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': true,
150
+ },
151
+ h('rect', { x: 3, y: 3, width: 7, height: 7, rx: 2 }),
152
+ h('rect', { x: 14, y: 14, width: 7, height: 7, rx: 2 }),
153
+ h('path', { d: 'M10 6.5h4a3 3 0 0 1 3 3V14' }),
154
+ h('path', { d: 'M6.5 10v4a3 3 0 0 0 3 3H14' }),
155
+ )
156
+ }
157
+
158
+ /** 按缩放生成鼠标指针:白底+深色描边在深浅背景都清晰,尺寸随 zoom 变化。 */
159
+ function makeCursor(scale, grabbing) {
160
+ const s = Math.max(0.6, Math.min(2.2, scale || 1))
161
+ const size = Math.round(28 * s)
162
+ const sw = (1.6 * s).toFixed(2)
163
+ const path = grabbing
164
+ ? `M9 12 V7 a2 2 0 0 1 4 0 v4 a2 2 0 0 1 4 0 v1 a2 2 0 0 1 4 0 v5 c0 4-3 7-7 7 h-2 c-3 0-5-2-6-4 l-3-5 a2 2 0 0 1 3-2 l3 3 z`
165
+ : `M5 2 L5 22 L10 17 L14 25 L18 23 L14 15 L21 15 Z`
166
+ const raw = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 28 28"><path d="${path}" fill="#ffffff" stroke="#111827" stroke-width="${sw}" stroke-linejoin="round"/></svg>`
167
+ const hx = Math.round((grabbing ? 12 : 5) * s)
168
+ const hy = Math.round((grabbing ? 8 : 2) * s)
169
+ return `url("data:image/svg+xml,${encodeURIComponent(raw)}") ${hx} ${hy}, ${grabbing ? 'grabbing' : 'grab'}`
170
+ }
171
+
172
+ /* ------------------------------------------------------------- 样式 */
173
+ const CSS = `
174
+ .th-root { position:relative; display:flex; flex-direction:column; width:100%; height:100%; min-height:0; overflow:hidden; background:var(--dsw-alias-bg-base); color:var(--dsw-alias-label-primary); font-family:inherit; }
175
+ .th-compact .th-bar { padding:8px 10px; gap:6px; }
176
+ .th-compact .th-title, .th-compact .th-sub { font-size:11px; }
177
+ .th-compact .th-ws-chip { max-width:120px; font-size:10px; }
178
+ .th-compact .th-btn { padding:4px 8px; font-size:11px; }
179
+ .th-compact .th-zoom button { width:20px; height:20px; }
180
+ .th-compact .th-zoom span { min-width:38px; font-size:10px; }
181
+ .th-compact .th-activity { display:none; }
182
+ .th-bar { display:flex; align-items:center; gap:10px; padding:10px 16px; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-1); flex:0 0 auto; z-index:5; flex-wrap:wrap; }
183
+ .th-title { font-size:15px; font-weight:650; letter-spacing:.2px; display:flex; align-items:center; gap:8px; }
184
+ .th-title svg { color:var(--dsw-alias-brand-primary); }
185
+ .th-sub { font-size:12px; color:var(--dsw-alias-label-secondary); }
186
+ .th-ws-chip { display:inline-flex; align-items:center; gap:5px; padding:3px 9px; border-radius:999px; font-size:11.5px; border:1px solid var(--dsw-alias-border-l2); color:var(--dsw-alias-label-secondary); background:var(--dsw-alias-bg-layer-2); max-width:240px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
187
+ .th-ws-chip.bound { color:var(--dsw-alias-brand-primary); border-color:var(--dsw-alias-brand-primary); }
188
+ .th-spacer { flex:1 1 auto; }
189
+ .th-btn { appearance:none; border:1px solid var(--dsw-alias-border-l2); background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); border-radius:8px; padding:6px 12px; font-size:12px; cursor:pointer; transition:background .16s ease, transform .16s ease, border-color .16s ease; }
190
+ .th-btn:hover { background:var(--dsw-alias-interactive-bg-hover); }
191
+ .th-btn:active { transform:scale(.96); }
192
+ .th-btn.primary { background:var(--dsw-alias-button-primary-fill); border-color:transparent; color:var(--dsw-alias-bg-base); }
193
+ .th-btn.danger { color:var(--dsw-alias-state-error-primary); }
194
+ .th-btn:disabled { opacity:.45; cursor:not-allowed; }
195
+ .th-zoom { display:inline-flex; align-items:center; gap:2px; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; overflow:hidden; }
196
+ .th-zoom button { appearance:none; border:0; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); width:26px; height:26px; font-size:14px; cursor:pointer; transition:background .16s ease; }
197
+ .th-zoom button:hover { background:var(--dsw-alias-interactive-bg-hover); }
198
+ .th-zoom span { min-width:46px; text-align:center; font-size:11px; color:var(--dsw-alias-label-secondary); font-variant-numeric:tabular-nums; }
199
+ .th-canvas { position:relative; flex:1 1 auto; min-height:0; overflow:hidden; background-color:var(--dsw-alias-bg-layer-1); background-image:linear-gradient(to right, var(--dsw-alias-border-l1) 1px, transparent 1px), linear-gradient(to bottom, var(--dsw-alias-border-l1) 1px, transparent 1px); background-size:24px 24px; cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Cpath d='M5 2 L5 22 L10 17 L14 25 L18 23 L14 15 L21 15 Z' fill='%23ffffff' stroke='%23111827' stroke-width='1.6' stroke-linejoin='round'/%3E%3C/svg%3E") 5 2, grab; }
200
+ .th-canvas.th-panning { cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Cpath d='M9 12 V7 a2 2 0 0 1 4 0 v4 a2 2 0 0 1 4 0 v1 a2 2 0 0 1 4 0 v5 c0 4-3 7-7 7 h-2 c-3 0-5-2-6-4 l-3-5 a2 2 0 0 1 3-2 l3 3 z' fill='%23ffffff' stroke='%23111827' stroke-width='1.6' stroke-linejoin='round'/%3E%3C/svg%3E") 12 8, grabbing; }
201
+ .th-node, .th-node * { cursor:auto; }
202
+ .th-head, .th-head * { cursor:grab !important; }
203
+ .th-head:active, .th-head:active * { cursor:grabbing !important; }
204
+ .th-stage { position:absolute; inset:0; pointer-events:none; }
205
+ .th-world { position:absolute; left:0; top:0; transform-origin:0 0; pointer-events:none; }
206
+ .th-world > * { pointer-events:auto; }
207
+ .th-links { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; overflow:visible; }
208
+ .th-link { stroke:var(--dsw-alias-brand-primary); stroke-width:1.8; opacity:.38; fill:none; }
209
+ .th-packet { fill:var(--dsw-alias-brand-primary); }
210
+ .th-node { position:absolute; width:236px; will-change:transform; transition:transform .18s cubic-bezier(.2,.8,.2,1); }
211
+ .th-node.dragging-node { transition:none; z-index:20; }
212
+ .th-card { position:relative; width:236px; border:1px solid var(--dsw-alias-border-l2); border-radius:14px; background:var(--dsw-alias-bg-layer-1); box-shadow:0 6px 22px rgba(0,0,0,.14); overflow:hidden; transition:box-shadow .18s ease, border-color .18s ease; }
213
+ .th-card:hover { box-shadow:0 10px 32px rgba(0,0,0,.22); border-color:var(--dsw-alias-brand-primary); }
214
+ .th-enter { animation:th-pop .28s ease both; }
215
+ @keyframes th-pop { from { opacity:0; } to { opacity:1; } }
216
+ /* 卡片上方外部的气泡:约两行高,实时内容向上滚屏 */
217
+ .th-bubble-out { position:absolute; left:0; right:0; bottom:100%; margin-bottom:8px; height:46px; border:1px solid var(--dsw-alias-border-l2); border-radius:12px; background:var(--dsw-alias-bg-overlay); box-shadow:0 6px 18px rgba(0,0,0,.16); overflow:hidden; cursor:pointer; transition:border-color .16s ease, opacity .16s ease; }
218
+ .th-bubble-out:hover { border-color:var(--dsw-alias-brand-primary); }
219
+ .th-bubble-out::after { content:''; position:absolute; left:24px; bottom:-6px; width:10px; height:10px; background:var(--dsw-alias-bg-overlay); border-right:1px solid var(--dsw-alias-border-l2); border-bottom:1px solid var(--dsw-alias-border-l2); transform:rotate(45deg); }
220
+ .th-bubble-track { display:flex; flex-direction:column; animation:th-bubble-roll .5s cubic-bezier(.2,.8,.2,1) both; }
221
+ @keyframes th-bubble-roll { from { transform:translateY(100%); opacity:0; } to { transform:translateY(0); opacity:1; } }
222
+ .th-bline { display:flex; align-items:center; gap:6px; height:23px; padding:0 10px; font-size:11px; white-space:nowrap; color:var(--dsw-alias-label-secondary); }
223
+ .th-bline .th-btag { flex:0 0 auto; font-size:9px; padding:1px 5px; border-radius:5px; background:var(--dsw-alias-bg-layer-2); }
224
+ .th-bline.assistant .th-btag { color:var(--dsw-alias-brand-primary); }
225
+ .th-bline.tool .th-btag { color:var(--dsw-alias-state-warn-primary); }
226
+ .th-bline.error .th-btag, .th-bline.approval .th-btag, .th-bline.question .th-btag { color:var(--dsw-alias-state-error-primary); }
227
+ .th-bline .th-btext { overflow:hidden; text-overflow:ellipsis; }
228
+ .th-head { display:flex; align-items:center; gap:9px; padding:11px 12px; cursor:grab; user-select:none; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-2); }
229
+ .th-head:active { cursor:grabbing; }
230
+ .th-emoji { font-size:22px; line-height:1; width:28px; text-align:center; }
231
+ .th-name { font-size:13px; font-weight:650; flex:1 1 auto; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
232
+ .th-dot { width:8px; height:8px; border-radius:50%; background:var(--dsw-alias-state-idle-primary); transition:background .3s ease, box-shadow .3s ease; }
233
+ .th-dot.uninstantiated { background:transparent; border:1px dashed var(--dsw-alias-state-idle-primary); opacity:.7; }
234
+ .th-dot.working { background:var(--dsw-alias-state-warn-primary); box-shadow:0 0 0 4px color-mix(in srgb, var(--dsw-alias-state-warn-primary) 18%, transparent); animation:th-pulse 1.4s ease-in-out infinite; }
235
+ .th-dot.done { background:var(--dsw-alias-state-success-primary); }
236
+ .th-dot.failed, .th-dot.archived { background:var(--dsw-alias-state-error-primary); }
237
+ @keyframes th-pulse { 0%,100%{opacity:1} 50%{opacity:.45} }
238
+ .th-body { padding:10px 12px; font-size:11.5px; color:var(--dsw-alias-label-secondary); line-height:1.55; }
239
+ .th-role { display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; min-height:34px; }
240
+ .th-last { margin-top:8px; padding-top:8px; border-top:1px dashed var(--dsw-alias-border-l1); color:var(--dsw-alias-label-primary); max-height:54px; overflow:hidden; }
241
+ .th-foot { display:flex; gap:6px; padding:9px 12px; border-top:1px solid var(--dsw-alias-border-l1); }
242
+ .th-foot .th-btn { flex:1 1 auto; padding:5px 6px; font-size:11px; text-align:center; }
243
+ .th-toast { position:absolute; left:50%; bottom:22px; transform:translateX(-50%) translateY(12px); background:var(--dsw-alias-bg-overlay); border:1px solid var(--dsw-alias-border-l2); color:var(--dsw-alias-label-primary); padding:9px 16px; border-radius:10px; font-size:12px; opacity:0; pointer-events:none; transition:opacity .24s ease, transform .24s ease; z-index:50; box-shadow:0 8px 28px rgba(0,0,0,.2); }
244
+ .th-toast.show { opacity:1; transform:translateX(-50%) translateY(0); }
245
+ .th-overlay { position:fixed; inset:0; background:rgba(0,0,0,.42); display:flex; align-items:center; justify-content:center; z-index:100; animation:th-fade .18s ease both; }
246
+ @keyframes th-fade { from{opacity:0} to{opacity:1} }
247
+ .th-modal { width:460px; max-width:92vw; max-height:86vh; overflow:auto; background:var(--dsw-alias-bg-layer-1); border:1px solid var(--dsw-alias-border-l2); border-radius:16px; padding:20px; box-shadow:0 24px 70px rgba(0,0,0,.4); animation:th-rise .24s cubic-bezier(.2,.8,.2,1) both; }
248
+ @keyframes th-rise { from{opacity:0; transform:translateY(18px) scale(.97)} to{opacity:1; transform:none} }
249
+ .th-modal h3 { margin:0 0 14px; font-size:16px; }
250
+ .th-field { display:flex; flex-direction:column; gap:5px; margin-bottom:12px; }
251
+ .th-field label { font-size:11px; color:var(--dsw-alias-label-secondary); }
252
+ .th-bind { background:var(--dsw-alias-bg-layer-2); border:1px solid var(--dsw-alias-border-l1); border-radius:8px; padding:8px 10px; font-size:11.5px; color:var(--dsw-alias-label-secondary); margin-bottom:14px; }
253
+ .th-input, .th-textarea { width:100%; box-sizing:border-box; background:var(--dsw-alias-bg-base); color:var(--dsw-alias-label-primary); border:1px solid var(--dsw-alias-border-l2); border-radius:8px; padding:8px 10px; font-size:12.5px; font-family:inherit; transition:border-color .16s ease; }
254
+ .th-input:focus, .th-textarea:focus { outline:none; border-color:var(--dsw-alias-brand-primary); }
255
+ .th-textarea { min-height:72px; resize:vertical; }
256
+ .th-modal-foot { display:flex; justify-content:flex-end; gap:8px; margin-top:8px; }
257
+ .th-composer { display:flex; align-items:flex-end; gap:8px; padding:12px 18px; border-top:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-1); }
258
+ .th-composer .th-cinput { flex:1 1 auto; resize:none; min-height:42px; max-height:130px; border-radius:18px; padding:10px 14px; background:var(--dsw-alias-bg-layer-2); border:1px solid var(--dsw-alias-border-l2); color:var(--dsw-alias-label-primary); font-size:12.5px; font-family:inherit; outline:none; transition:border-color .16s ease; }
259
+ .th-composer .th-cinput:focus { border-color:var(--dsw-alias-brand-primary); }
260
+ .th-composer .th-send { width:38px; height:38px; border-radius:50%; border:0; background:var(--dsw-alias-button-primary-fill); color:var(--dsw-alias-bg-base); cursor:pointer; font-size:15px; flex:0 0 auto; transition:transform .16s ease, opacity .16s ease; }
261
+ .th-composer .th-send:hover { transform:scale(1.06); }
262
+ .th-composer .th-send:disabled { opacity:.4; cursor:not-allowed; }
263
+ .th-activity { position:absolute; right:14px; top:14px; width:260px; max-height:calc(100% - 28px); overflow:auto; background:var(--dsw-alias-bg-layer-1); border:1px solid var(--dsw-alias-border-l1); border-radius:12px; padding:10px 12px; font-size:11px; z-index:4; box-shadow:0 6px 20px rgba(0,0,0,.12); }
264
+ .th-log { padding:6px 0; border-bottom:1px dashed var(--dsw-alias-border-l1); color:var(--dsw-alias-label-secondary); animation:th-slide .3s ease both; }
265
+ @keyframes th-slide { from{opacity:0; transform:translateX(10px)} to{opacity:1; transform:none} }
266
+ .th-log b { color:var(--dsw-alias-label-primary); font-weight:600; }
267
+ .th-empty { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; color:var(--dsw-alias-label-secondary); font-size:13px; }
268
+ /* 右侧栏里的紧凑画布 */
269
+ .th-side { display:flex; flex-direction:column; height:100%; min-height:0; font-family:inherit; color:var(--dsw-alias-label-primary); background:var(--dsw-alias-bg-base); }
270
+ .th-side-bar { display:flex; align-items:center; gap:8px; padding:10px 12px; border-bottom:1px solid var(--dsw-alias-border-l1); font-size:12px; flex:0 0 auto; }
271
+ .th-side-list { flex:1 1 auto; min-height:0; overflow:auto; padding:10px 12px; display:flex; flex-direction:column; gap:8px; }
272
+ .th-side-card { border:1px solid var(--dsw-alias-border-l2); border-radius:10px; padding:9px 10px; background:var(--dsw-alias-bg-layer-1); cursor:pointer; transition:border-color .16s ease; }
273
+ .th-side-card:hover { border-color:var(--dsw-alias-brand-primary); }
274
+ .th-side-row { display:flex; align-items:center; gap:8px; }
275
+ .th-side-row .th-name { font-size:12px; }
276
+ .th-side-msg { margin-top:6px; font-size:10.5px; color:var(--dsw-alias-label-secondary); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
277
+ `
278
+
279
+ function useStyles() {
280
+ useEffect(() => {
281
+ if (document.querySelector('[data-team-hub-style]')) return
282
+ const el = document.createElement('style')
283
+ el.setAttribute('data-team-hub-style', MODULE_ID)
284
+ el.textContent = CSS
285
+ document.head.appendChild(el)
286
+ return () => el.remove()
287
+ }, [])
288
+ }
289
+
290
+ /* ----------------------------------------------------------- 组件 */
291
+ const BUBBLE_KIND = {
292
+ assistant: '回复', user: '用户', tool: '工具', error: '错误',
293
+ turn: '完成', approval: '审批', question: '提问',
294
+ }
295
+ const CARD_W = 236
296
+ const CARD_H = 168
297
+
298
+ /** 两卡片最近边中点连线:按中心差选主轴,取对应边的中点。 */
299
+ function edgePoints(a, b) {
300
+ const ac = { x: a.x + CARD_W / 2, y: a.y + CARD_H / 2 }
301
+ const bc = { x: b.x + CARD_W / 2, y: b.y + CARD_H / 2 }
302
+ const dx = bc.x - ac.x, dy = bc.y - ac.y
303
+ if (Math.abs(dx) >= Math.abs(dy)) {
304
+ return dx >= 0
305
+ ? { x1: a.x + CARD_W, y1: ac.y, x2: b.x, y2: bc.y }
306
+ : { x1: a.x, y1: ac.y, x2: b.x + CARD_W, y2: bc.y }
307
+ }
308
+ return dy >= 0
309
+ ? { x1: ac.x, y1: a.y + CARD_H, x2: bc.x, y2: b.y }
310
+ : { x1: ac.x, y1: a.y, x2: bc.x, y2: b.y + CARD_H }
311
+ }
312
+
313
+ function BubbleOut({ items, status, onClick }) {
314
+ const tail = items.slice(-2)
315
+ return h('div', { className: 'th-bubble-out', title: '点击查看原生会话', onClick },
316
+ h('div', { className: 'th-bubble-track', key: tail.map((i) => i.kind + i.seq).join('-') },
317
+ tail.length
318
+ ? tail.map((it, i) => h('div', { className: `th-bline ${it.kind}`, key: i },
319
+ h('span', { className: 'th-btag' }, BUBBLE_KIND[it.kind] || it.kind),
320
+ h('span', { className: 'th-btext' }, it.text.slice(0, 46)),
321
+ ))
322
+ : h('div', { className: 'th-bline' },
323
+ h('span', { className: 'th-btag' }, STATUS_LABEL[status] || status),
324
+ h('span', { className: 'th-btext' }, status === 'working' ? '正在工作…' : '暂无实时内容'),
325
+ ),
326
+ ),
327
+ )
328
+ }
329
+
330
+ function AgentCard({ agent, feed, notices, onDragStart, onMessage, onOpen, onEdit, onRemove, onStatus, onInstantiate, onRefresh }) {
331
+ const status = statusOf(agent)
332
+ const sid = agent.sessionId
333
+ const extra = sid ? (notices[sid] || []) : []
334
+ const all = [...feed, ...extra.map((n) => ({ kind: n.kind, text: n.text, seq: n.ts }))]
335
+ return h('div', {
336
+ className: 'th-node th-enter',
337
+ style: { transform: `translate(${agent.x}px, ${agent.y}px)` },
338
+ 'data-agent': agent.id,
339
+ },
340
+ sid ? h(BubbleOut, { items: all, status, onClick: () => onOpen(agent) })
341
+ : h('div', { className: 'th-bubble-out', style: { opacity: .65 }, title: '实例化后显示实时内容' },
342
+ h('div', { className: 'th-bline' },
343
+ h('span', { className: 'th-btag' }, '未实例化'),
344
+ h('span', { className: 'th-btext' }, '点击「实例化」创建会话'),
345
+ ),
346
+ ),
347
+ h('div', { className: 'th-card' },
348
+ h('div', { className: 'th-head', onPointerDown: (e) => onDragStart(e, agent) },
349
+ h('span', { className: 'th-emoji' }, agent.icon || '🤖'),
350
+ h('span', { className: 'th-name', title: agent.name }, agent.name),
351
+ h('span', { className: `th-dot ${status}`, title: STATUS_LABEL[status] || status }),
352
+ ),
353
+ h('div', { className: 'th-body' },
354
+ h('div', { className: 'th-role' }, agent.duties || agent.identity || '暂无职责说明'),
355
+ agent.lastMessage ? h('div', { className: 'th-last', title: agent.lastMessage }, agent.lastMessage) : null,
356
+ ),
357
+ !sid
358
+ ? h('div', { className: 'th-foot' },
359
+ h('button', { className: 'th-btn primary', onClick: () => onInstantiate(agent) }, '实例化'),
360
+ h('button', { className: 'th-btn', onClick: () => onEdit(agent) }, '编辑'),
361
+ h('button', { className: 'th-btn danger', onClick: () => onRemove(agent) }, '移除'),
362
+ )
363
+ : h('div', null,
364
+ h('div', { className: 'th-foot' },
365
+ h('button', { className: 'th-btn primary', onClick: () => onMessage(agent) }, '发消息'),
366
+ h('button', { className: 'th-btn', onClick: () => onOpen(agent) }, '打开会话'),
367
+ ),
368
+ h('div', { className: 'th-foot' },
369
+ h('button', { className: 'th-btn', onClick: () => onStatus(agent) }, '状态'),
370
+ h('button', { className: 'th-btn', onClick: () => onRefresh(agent) }, '刷新实例'),
371
+ h('button', { className: 'th-btn', onClick: () => onEdit(agent) }, '编辑'),
372
+ h('button', { className: 'th-btn danger', onClick: () => onRemove(agent) }, '移除'),
373
+ ),
374
+ ),
375
+ ),
376
+ )
377
+ }
378
+
379
+ function AgentForm({ agent, t, workspaceTitle, onClose, onSave }) {
380
+ const [form, setForm] = useState(agent || { icon: '🤖', name: '', identity: '', duties: '', permissions: { denyTools: '', writeFiles: '', readFiles: '' } })
381
+ const set = (k, v) => setForm((f) => ({ ...f, [k]: v }))
382
+ const setPerm = (k, v) => setForm((f) => ({ ...f, permissions: { ...f.permissions, [k]: v } }))
383
+ const split = (v) => String(v || '').split(/[,,\n]/).map((s) => s.trim()).filter(Boolean)
384
+ return h('div', { className: 'th-overlay', onPointerDown: (e) => { if (e.target === e.currentTarget) onClose() } },
385
+ h('div', { className: 'th-modal' },
386
+ h('h3', null, agent ? t('editAgent') : t('newAgent')),
387
+ !agent && h('div', { className: 'th-bind' }, '🔗 ', t('newAgentHint'), ':', workspaceTitle || t('noWorkspace')),
388
+ h('div', { className: 'th-field' }, h('label', null, t('icon')), h('input', { className: 'th-input', value: form.icon, onChange: (e) => set('icon', e.target.value) })),
389
+ h('div', { className: 'th-field' }, h('label', null, t('name')), h('input', { className: 'th-input', value: form.name, onChange: (e) => set('name', e.target.value), placeholder: '例如:研究员' })),
390
+ h('div', { className: 'th-field' }, h('label', null, t('identity')), h('textarea', { className: 'th-textarea', value: form.identity, onChange: (e) => set('identity', e.target.value) })),
391
+ h('div', { className: 'th-field' }, h('label', null, t('duties')), h('textarea', { className: 'th-textarea', value: form.duties, onChange: (e) => set('duties', e.target.value) })),
392
+ h('div', { className: 'th-field' }, h('label', null, t('denyTools')), h('input', { className: 'th-input', value: form.permissions.denyTools || '', onChange: (e) => setPerm('denyTools', e.target.value), placeholder: 'bash, pwsh(硬约束)' })),
393
+ h('div', { className: 'th-field' }, h('label', null, t('writeFiles')), h('input', { className: 'th-input', value: form.permissions.writeFiles || '', onChange: (e) => setPerm('writeFiles', e.target.value), placeholder: '仅提示词约束' })),
394
+ h('div', { className: 'th-field' }, h('label', null, t('readFiles')), h('input', { className: 'th-input', value: form.permissions.readFiles || '', onChange: (e) => setPerm('readFiles', e.target.value), placeholder: '仅提示词约束' })),
395
+ h('div', { className: 'th-modal-foot' },
396
+ h('button', { className: 'th-btn', onClick: onClose }, t('cancel')),
397
+ h('button', {
398
+ className: 'th-btn primary', disabled: !form.name?.trim(),
399
+ onClick: () => onSave({
400
+ ...form,
401
+ permissions: {
402
+ denyTools: split(form.permissions.denyTools),
403
+ writeFiles: split(form.permissions.writeFiles),
404
+ readFiles: split(form.permissions.readFiles),
405
+ },
406
+ }),
407
+ }, t('save')),
408
+ ),
409
+ ),
410
+ )
411
+ }
412
+
413
+ /** 发消息弹窗:单个入口(派任务/消息合并),宿主原版 composer 无公开复用 API,做等价输入框。 */
414
+ function Composer({ agent, t, onClose, onSend }) {
415
+ const [text, setText] = useState('')
416
+ return h('div', { className: 'th-overlay', onPointerDown: (e) => { if (e.target === e.currentTarget) onClose() } },
417
+ h('div', { className: 'th-modal' },
418
+ h('h3', null, `${t('sendMessage')} · ${agent.name}`),
419
+ h('div', { className: 'th-composer', style: { border: 0, padding: 0 } },
420
+ h('textarea', {
421
+ className: 'th-cinput', autoFocus: true, value: text,
422
+ onChange: (e) => setText(e.target.value),
423
+ onKeyDown: (e) => { if (e.key === 'Enter' && !e.shiftKey && text.trim()) { e.preventDefault(); onSend(text.trim()) } },
424
+ placeholder: '写一条消息或任务…',
425
+ }),
426
+ h('button', { className: 'th-send', disabled: !text.trim(), onClick: () => onSend(text.trim()) }, '➤'),
427
+ ),
428
+ h('div', { className: 'th-modal-foot' }, h('button', { className: 'th-btn', onClick: onClose }, t('cancel'))),
429
+ ),
430
+ )
431
+ }
432
+
433
+ /** 刷新实例弹窗:设置保存/恢复进度提示词,把 Agent 换绑到新会话。 */
434
+ function RefreshModal({ agent, t, busy, onClose, onRun }) {
435
+ const [saveText, setSaveText] = useState(t('defaultSavePrompt'))
436
+ const [restoreText, setRestoreText] = useState(t('defaultRestorePrompt'))
437
+ return h('div', { className: 'th-overlay', onPointerDown: (e) => { if (e.target === e.currentTarget && !busy) onClose() } },
438
+ h('div', { className: 'th-modal' },
439
+ h('h3', null, `${t('refreshInstance')} · ${agent.name}`),
440
+ h('div', { className: 'th-bind' }, t('refreshHint')),
441
+ h('div', { className: 'th-field' },
442
+ h('label', null, t('savePrompt')),
443
+ h('textarea', { className: 'th-textarea', value: saveText, onChange: (e) => setSaveText(e.target.value), disabled: busy }),
444
+ ),
445
+ h('div', { className: 'th-field' },
446
+ h('label', null, t('restorePrompt')),
447
+ h('textarea', { className: 'th-textarea', value: restoreText, onChange: (e) => setRestoreText(e.target.value), disabled: busy }),
448
+ ),
449
+ h('div', { className: 'th-modal-foot' },
450
+ h('button', { className: 'th-btn', onClick: onClose, disabled: busy }, t('cancel')),
451
+ h('button', {
452
+ className: 'th-btn primary', disabled: busy,
453
+ onClick: () => onRun({ saveText, restoreText }),
454
+ }, busy ? t('refreshing') : t('startRefresh')),
455
+ ),
456
+ ),
457
+ )
458
+ }
459
+
460
+ /** 右侧栏紧凑画布:与中央画布共享同一份看板数据,点击卡片打开对应原生会话。 */
461
+ /** 右侧栏里渲染的是同一个完整画布(拖拽/缩放/气泡/连线俱全),不是列表。 */
462
+ function SidebarCanvas(props) {
463
+ return h(TeamHubPage, { ...props, compact: true })
464
+ }
465
+
466
+ /* --------------------------------------------------------- 主面板 */
467
+ function pickRecentWorkspace(items, sessionsById) {
468
+ let selected, selectedTime = Number.NEGATIVE_INFINITY
469
+ for (const ws of items || []) {
470
+ let latest = Number.NEGATIVE_INFINITY
471
+ for (const id of ws.sessionIds || []) {
472
+ const s = sessionsById?.[id]
473
+ if (s && typeof s.updatedAt === 'number') latest = Math.max(latest, s.updatedAt)
474
+ }
475
+ if (latest === Number.NEGATIVE_INFINITY) latest = Date.parse(ws.createdAt) || 0
476
+ if (!selected || latest > selectedTime) { selected = ws; selectedTime = latest }
477
+ }
478
+ return selected
479
+ }
480
+
481
+ function AgentNode({ agent, ctx, notices, ...handlers }) {
482
+ const feed = useAgentFeed(ctx, agent.sessionId)
483
+ return h(AgentCard, { agent, feed, notices, ...handlers })
484
+ }
485
+
486
+ function TeamHubPage(props) {
487
+ useStyles()
488
+ const ctx = props.ctx
489
+ const t = props.t || ((k) => k)
490
+ const openSession = props.openSession
491
+ const useWorkspaces = props.useWorkspaces
492
+ const useSessions = props.useSessions
493
+ const recentWs = useWorkspaces ? useWorkspaces((s) => pickRecentWorkspace(s.items, null)) : null
494
+ const sessionByIds = useSessions ? useSessions((s) => s.byId) : null
495
+ const workspace = boundWorkspace
496
+ ? (useWorkspaces ? useWorkspaces((s) => s.items.find((w) => w.workspaceId === boundWorkspace)) : null) || { workspaceId: boundWorkspace, title: boundWorkspaceTitle }
497
+ : (recentWs && sessionByIds ? pickRecentWorkspace([recentWs], sessionByIds) : recentWs)
498
+ const workspaceId = workspace?.workspaceId
499
+ const workspaceTitle = workspace?.title
500
+ const notices = useRemoteNotices(ctx)
501
+
502
+ const [board, setBoard] = useState(null)
503
+ const [removedAgents, setRemovedAgents] = useState([])
504
+ const [archivedIds, setArchivedIds] = useState([])
505
+ const [archiveReady, setArchiveReady] = useState(false)
506
+ const [error, setError] = useState('')
507
+ const [toast, setToast] = useState('')
508
+ const [form, setForm] = useState(null)
509
+ const [composer, setComposer] = useState(null)
510
+ const [refreshing, setRefreshing] = useState(null)
511
+ const [refreshBusy, setRefreshBusy] = useState(false)
512
+ const [activity, setActivity] = useState([])
513
+ const [pulses, setPulses] = useState([])
514
+ const [zoom, setZoom] = useState(props.compact ? 0.6 : 1)
515
+ const [pan, setPan] = useState({ x: 60, y: 60 })
516
+ const [panning, setPanning] = useState(false)
517
+ const dragRef = useRef(null)
518
+ const worldRef = useRef(null)
519
+ const canvasRef = useRef(null)
520
+ const zoomRef = useRef(zoom)
521
+ const panRef = useRef(pan)
522
+ useEffect(() => { zoomRef.current = zoom }, [zoom])
523
+ useEffect(() => { panRef.current = pan }, [pan])
524
+
525
+ const refresh = useCallback(async () => {
526
+ try {
527
+ const q = workspaceId ? `?workspaceId=${encodeURIComponent(workspaceId)}` : ''
528
+ setBoard(await api('/state' + q)); setError('')
529
+ } catch (e) { setError(e.message) }
530
+ }, [workspaceId])
531
+ const refreshRemoved = useCallback(async () => {
532
+ try { setRemovedAgents(workspaceId ? await api('/removed?workspaceId=' + encodeURIComponent(workspaceId)) : []) } catch {}
533
+ }, [workspaceId])
534
+ useEffect(() => { refresh(); refreshRemoved() }, [refresh, refreshRemoved])
535
+ useEffect(() => { if (workspaceId) { refresh(); refreshRemoved() } }, [workspaceId, refresh, refreshRemoved])
536
+
537
+ useEffect(() => {
538
+ const src = ctx?.workspaces?.list
539
+ if (!src) return
540
+ const read = () => {
541
+ const snap = src.getSnapshot()
542
+ if (snap?.phase === 'ready') { setArchivedIds(snap.archivedSessionIds || []); setArchiveReady(true) }
543
+ }
544
+ read()
545
+ const off = src.subscribe(read)
546
+ return () => off?.()
547
+ }, [ctx])
548
+ useEffect(() => {
549
+ if (!archiveReady) return
550
+ for (const a of removedAgents) {
551
+ if (a.sessionId && !archivedIds.includes(a.sessionId)) {
552
+ api('/restore', { method: 'POST', body: { id: a.id } })
553
+ .then(() => { notify(`会话已恢复,Agent「${a.name}」已回到画布`); refresh(); refreshRemoved() })
554
+ .catch(() => {})
555
+ }
556
+ }
557
+ }, [archivedIds, archiveReady, removedAgents])
558
+
559
+ const setZoomClamped = useCallback((next) => setZoom(Math.min(2, Math.max(0.4, Math.round(next * 10) / 10))), [])
560
+ // Ctrl+滚轮:以鼠标位置为锚点缩放(无限画布,不受固定边界限制)。
561
+ useEffect(() => {
562
+ const el = canvasRef.current
563
+ if (!el) return
564
+ const onWheel = (ev) => {
565
+ ev.preventDefault()
566
+ const rect = el.getBoundingClientRect()
567
+ const mx = ev.clientX - rect.left, my = ev.clientY - rect.top
568
+ if (ev.ctrlKey || ev.metaKey) {
569
+ const old = zoomRef.current
570
+ const next = Math.min(2, Math.max(0.4, Math.round((old + (ev.deltaY < 0 ? 0.1 : -0.1)) * 10) / 10))
571
+ if (next === old) return
572
+ const p = panRef.current
573
+ // 保持鼠标下的世界坐标不变:world = (mouse - pan)/zoom
574
+ const wx = (mx - p.x) / old, wy = (my - p.y) / old
575
+ setPan({ x: mx - wx * next, y: my - wy * next })
576
+ setZoom(next)
577
+ } else {
578
+ // 普通滚轮也可平移画布
579
+ setPan((cur) => ({ x: cur.x - ev.deltaX, y: cur.y - ev.deltaY }))
580
+ }
581
+ }
582
+ el.addEventListener('wheel', onWheel, { passive: false })
583
+ return () => el.removeEventListener('wheel', onWheel)
584
+ }, [])
585
+
586
+ // 拖拽空白处平移画布(改 pan transform);点在卡片上不触发。
587
+ useEffect(() => {
588
+ const el = canvasRef.current
589
+ if (!el) return
590
+ let drag = null
591
+ const down = (ev) => {
592
+ if (ev.button !== 0) return
593
+ if (ev.target.closest('.th-node')) return // 卡片拖拽交给 onDragStart
594
+ drag = { x: ev.clientX, y: ev.clientY, pan: { ...panRef.current } }
595
+ el.classList.add('th-panning')
596
+ setPanning(true)
597
+ }
598
+ const move = (ev) => {
599
+ if (!drag) return
600
+ const dx = ev.clientX - drag.x, dy = ev.clientY - drag.y
601
+ setPan({ x: drag.pan.x + dx, y: drag.pan.y + dy })
602
+ }
603
+ const up = () => { drag = null; el.classList.remove('th-panning'); setPanning(false) }
604
+ el.addEventListener('pointerdown', down)
605
+ window.addEventListener('pointermove', move)
606
+ window.addEventListener('pointerup', up)
607
+ return () => {
608
+ el.removeEventListener('pointerdown', down)
609
+ window.removeEventListener('pointermove', move)
610
+ window.removeEventListener('pointerup', up)
611
+ }
612
+ }, [])
613
+
614
+ // 鼠标指针始终自定义,尺寸随 zoom 变化;inline 覆盖 CSS。
615
+ useEffect(() => {
616
+ const el = canvasRef.current
617
+ if (el) el.style.cursor = makeCursor(zoom, panning)
618
+ }, [zoom, panning])
619
+
620
+ const notify = useCallback((msg) => {
621
+ setToast(msg)
622
+ setTimeout(() => setToast((cur) => (cur === msg ? '' : cur)), 2600)
623
+ }, [])
624
+ const log = useCallback((text) => {
625
+ setActivity((a) => [{ id: Math.random().toString(36).slice(2), text, at: new Date().toLocaleTimeString() }, ...a].slice(0, 40))
626
+ }, [])
627
+
628
+ const onDragStart = useCallback((e, agent) => {
629
+ if (e.button !== 0) return
630
+ if (!worldRef.current) return
631
+ const head = e.currentTarget
632
+ const node = head.closest('.th-node') || head
633
+ const pointerId = e.pointerId
634
+ const scale = zoomRef.current
635
+ dragRef.current = {
636
+ id: agent.id, startX: e.clientX, startY: e.clientY,
637
+ originX: agent.x, originY: agent.y, x: agent.x, y: agent.y, moved: false, scale,
638
+ }
639
+ try { head.setPointerCapture(pointerId) } catch {}
640
+ try { node.classList.add('dragging-node') } catch {}
641
+ const move = (ev) => {
642
+ const d = dragRef.current
643
+ if (!d) return
644
+ const dx = (ev.clientX - d.startX) / d.scale
645
+ const dy = (ev.clientY - d.startY) / d.scale
646
+ if (Math.abs(dx) + Math.abs(dy) > 3) d.moved = true
647
+ d.x = Math.max(0, d.originX + dx)
648
+ d.y = Math.max(0, d.originY + dy)
649
+ setBoard((b) => b ? { ...b, agents: b.agents.map((a) => a.id === d.id ? { ...a, x: d.x, y: d.y } : a) } : b)
650
+ }
651
+ const up = async () => {
652
+ const d = dragRef.current
653
+ try { head.releasePointerCapture?.(pointerId) } catch {}
654
+ try { node.classList.remove('dragging-node') } catch {}
655
+ window.removeEventListener('pointermove', move)
656
+ window.removeEventListener('pointerup', up)
657
+ dragRef.current = null
658
+ if (!d?.moved) return
659
+ try { await api('/move', { method: 'POST', body: { id: d.id, x: d.x, y: d.y } }) }
660
+ catch (err) { notify(`保存位置失败: ${err.message}`) }
661
+ }
662
+ window.addEventListener('pointermove', move)
663
+ window.addEventListener('pointerup', up)
664
+ }, [notify])
665
+
666
+ const saveAgent = async (data) => {
667
+ try {
668
+ await api('/agent', { method: 'POST', body: { ...data, workspaceId: data.workspaceId || workspaceId } })
669
+ setForm(null)
670
+ notify(data.id ? '已保存 Agent 卡片' : '已创建 Agent 卡片,点「实例化」建会话')
671
+ log(`保存卡片 <b>${data.name}</b>`)
672
+ await refresh()
673
+ } catch (e) { notify(`失败: ${e.message}`) }
674
+ }
675
+
676
+ const instantiate = async (agent) => {
677
+ const ws = agent.workspaceId || workspaceId
678
+ if (!ws) { notify('未绑定工作区,无法实例化'); return }
679
+ try {
680
+ notify('正在创建会话并发送初始化设定…')
681
+ const sessionId = await ctx.sessions.create({ workspaceId: ws })
682
+ await ctx.sessions.using(sessionId, { source: 'teamHub' }, async (ref) => {
683
+ await ref.ready
684
+ return ref.binding.session.prompt([{ type: 'text', text: initText(agent) }], 'queue', undefined, crypto.randomUUID())
685
+ })
686
+ await api('/agent', { method: 'POST', body: { ...agent, sessionId } })
687
+ log(`<b>${agent.name}</b> 已实例化并绑定会话`)
688
+ notify('已实例化,初始化设定已发送至新会话')
689
+ await refresh()
690
+ } catch (e) { notify(`实例化失败: ${e.message}`) }
691
+ }
692
+
693
+ /** 刷新实例:旧会话发保存进度→等其跑完→归档→建新会话→发恢复进度→重绑。 */
694
+ const runRefresh = async (agent, { saveText, restoreText }) => {
695
+ if (!agent?.sessionId) { notify('该 Agent 还未实例化'); setRefreshing(null); return }
696
+ setRefreshBusy(true)
697
+ const oldSid = agent.sessionId
698
+ const ws = agent.workspaceId || workspaceId
699
+ try {
700
+ // 1) 旧会话发送保存进度提示词
701
+ notify('正在让旧会话保存进度…')
702
+ if (saveText.trim()) {
703
+ await ctx.sessions.using(oldSid, { source: 'teamHub' }, async (ref) => {
704
+ await ref.ready
705
+ return ref.binding.session.prompt([{ type: 'text', text: saveText.trim() }], 'queue', undefined, crypto.randomUUID())
706
+ })
707
+ // 2) 等旧会话这一轮跑完(wait 在 idle / input-required / timeout 时返回)
708
+ const waitRes = await ctx.remote.session.wait({ sessionId: oldSid, timeoutMs: 60000, maxMessages: 6 })
709
+ if (waitRes && waitRes.ok === false) notify(`等待保存完成超时/失败:${waitRes.error?.message || ''}`)
710
+ }
711
+ // 3) 归档旧会话
712
+ await ctx.uiWorkspace?.archiveSession(oldSid, { stopActivity: true })
713
+ log(`<b>${agent.name}</b> 旧会话已归档`)
714
+ // 4) 建新会话
715
+ if (!ws) throw new Error('未绑定工作区')
716
+ const newSid = await ctx.sessions.create({ workspaceId: ws })
717
+ notify('新会话已创建,正在恢复进度…')
718
+ // 5) 新会话发恢复进度提示词
719
+ await ctx.sessions.using(newSid, { source: 'teamHub' }, async (ref) => {
720
+ await ref.ready
721
+ const msgs = [{ type: 'text', text: restoreText?.trim() || t('defaultRestorePrompt') }]
722
+ return ref.binding.session.prompt(msgs, 'queue', undefined, crypto.randomUUID())
723
+ })
724
+ // 6) 重绑卡片
725
+ await api('/agent', { method: 'POST', body: { ...agent, sessionId: newSid } })
726
+ log(`<b>${agent.name}</b> 已刷新实例并恢复进度`)
727
+ notify('刷新实例完成')
728
+ setRefreshing(null)
729
+ await refresh()
730
+ } catch (e) {
731
+ notify(`刷新失败: ${e.message}`)
732
+ } finally { setRefreshBusy(false) }
733
+ }
734
+
735
+ const removeAgent = async (agent) => {
736
+ if (!window.confirm(`移除 Agent「${agent.name}」?\n其会话将被归档;之后在侧边栏恢复该会话,Agent 会自动回到画布。`)) return
737
+ try {
738
+ if (agent.sessionId) await ctx.uiWorkspace?.archiveSession(agent.sessionId, { stopActivity: true })
739
+ await api(`/agent?id=${encodeURIComponent(agent.id)}`, { method: 'DELETE' })
740
+ log(`移除 <b>${agent.name}</b> 并归档会话`)
741
+ notify('已移除并归档会话')
742
+ await refresh(); await refreshRemoved()
743
+ } catch (e) { notify(`移除失败: ${e.message}`) }
744
+ }
745
+
746
+ const sendMessage = async (agent, text) => {
747
+ setComposer(null)
748
+ try {
749
+ await api('/message', { method: 'POST', body: { from: '团队面板', to: agent.id, text } })
750
+ setPulses((p) => [...p, { id: Math.random().toString(36).slice(2), from: null, to: agent.id }])
751
+ setTimeout(() => setPulses((p) => p.slice(1)), 1200)
752
+ log(`发消息 → <b>${agent.name}</b>`)
753
+ notify('消息已送达')
754
+ await refresh()
755
+ } catch (e) { notify(`失败: ${e.message}`) }
756
+ }
757
+
758
+ const showStatus = async (agent) => {
759
+ try {
760
+ const state = await api(`/status?id=${encodeURIComponent(agent.id)}`)
761
+ notify(state ? `状态:${state.active ? '活跃' : '空闲'} · ${state.running ? '运行中' : '未运行'}` : '状态暂不可用')
762
+ } catch (e) { notify(`失败: ${e.message}`) }
763
+ }
764
+
765
+ /** 卡片点击:中央切回原生会话 + 画布缩到右侧栏(彻底复用原生 UI)。 */
766
+ const openInSplit = useCallback((agent) => {
767
+ if (!agent?.sessionId) { notify('请先实例化该 Agent'); return }
768
+ ctx.uiWorkspace?.openSession(agent.sessionId)
769
+ try { sidebarRightSvc?.openTab(TAB_KIND, { params: { sessionId: agent.sessionId } }) }
770
+ catch (err) { console.warn('[team-hub] openTab failed:', err?.message) }
771
+ }, [ctx, notify])
772
+
773
+ const agents = board?.agents || []
774
+ const byId = useMemo(() => Object.fromEntries(agents.map((a) => [a.id, a])), [agents])
775
+ // 连线只来自真实沟通记录(每个 from→to 对只取最近一条),不再全连接。
776
+ const links = useMemo(() => {
777
+ const seen = new Map()
778
+ for (const m of [...(board?.messages || [])].reverse()) {
779
+ const key = `${m.from}->${m.to}`
780
+ if (!seen.has(key) && byId[m.from] && byId[m.to]) seen.set(key, { from: byId[m.from], to: byId[m.to] })
781
+ }
782
+ return [...seen.values()]
783
+ }, [board, byId])
784
+
785
+ return h('div', { className: `th-root ${props.compact ? 'th-compact' : ''}` },
786
+ h('div', { className: 'th-bar' },
787
+ h('span', { className: 'th-title' }, h(HubIcon, { size: 18, active: true }), t('title')),
788
+ h('span', { className: `th-ws-chip ${boundWorkspace ? 'bound' : ''}`, title: workspaceId || '' },
789
+ h('svg', { width: 13, height: 13, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'aria-hidden': true },
790
+ h('path', { d: 'M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z' }),
791
+ ),
792
+ boundWorkspace ? (workspaceTitle || t('boundWorkspace')) : t('globalWorkspace'),
793
+ ),
794
+ h('span', { className: 'th-sub' }, `${agents.length} 个 Agent · Ctrl+滚轮缩放`),
795
+ h('span', { className: 'th-spacer' }),
796
+ h('div', { className: 'th-zoom' },
797
+ h('button', { title: '缩小', onClick: () => setZoomClamped(zoom - 0.1) }, '−'),
798
+ h('span', { title: 'Ctrl+滚轮缩放' }, `${Math.round(zoom * 100)}%`),
799
+ h('button', { title: '放大', onClick: () => setZoomClamped(zoom + 0.1) }, '+'),
800
+ h('button', { title: '重置', onClick: () => setZoomClamped(1) }, '⟳'),
801
+ ),
802
+ h('button', { className: 'th-btn', onClick: () => { refresh(); refreshRemoved() } }, t('refresh')),
803
+ h('button', { className: 'th-btn primary', onClick: () => setForm({}) }, t('newAgent')),
804
+ ),
805
+ h('div', { className: 'th-canvas', ref: canvasRef },
806
+ h('div', { className: 'th-stage' },
807
+ h('div', { className: 'th-world', ref: worldRef, style: { transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})` } },
808
+ h('svg', { className: 'th-links' },
809
+ links.map(({ from, to }) => {
810
+ const p = edgePoints(from, to)
811
+ return h('path', { key: `${from.id}-${to.id}`, className: 'th-link',
812
+ d: `M ${p.x1} ${p.y1} L ${p.x2} ${p.y2}` })
813
+ }),
814
+ pulses.map((pl) => {
815
+ const to = byId[pl.to]
816
+ if (!to) return null
817
+ const x2 = to.x + CARD_W / 2, y2 = to.y - 22
818
+ return h('circle', { key: pl.id, className: 'th-packet', r: 5 },
819
+ h('animateMotion', { dur: '.9s', fill: 'freeze', path: `M 1200 30 Q ${(1200 + x2) / 2} ${Math.min(30, y2) - 80} ${x2} ${y2}` }),
820
+ )
821
+ }),
822
+ ),
823
+ agents.length === 0
824
+ ? h('div', { className: 'th-empty' }, h('div', { style: { fontSize: 30 } }, '🗂️'), h('div', null, t('empty')), h('button', { className: 'th-btn primary', onClick: () => setForm({}) }, t('newAgent')))
825
+ : agents.map((a) => h(AgentNode, {
826
+ key: a.id, agent: a, ctx, notices,
827
+ onDragStart,
828
+ onMessage: (ag) => setComposer({ agent: ag }),
829
+ onOpen: openInSplit,
830
+ onEdit: (ag) => setForm(ag),
831
+ onRemove: removeAgent,
832
+ onStatus: showStatus,
833
+ onInstantiate: instantiate,
834
+ onRefresh: (ag) => setRefreshing(ag),
835
+ })),
836
+ activity.length > 0 && h('div', { className: 'th-activity' },
837
+ h('div', { style: { fontWeight: 650, marginBottom: 6 } }, t('activity')),
838
+ activity.map((l) => h('div', { className: 'th-log', key: l.id, dangerouslySetInnerHTML: { __html: `${l.text}<br><span style="opacity:.6">${l.at}</span>` } })),
839
+ ),
840
+ ),
841
+ ),
842
+ ),
843
+ h('div', { className: `th-toast ${toast ? 'show' : ''}` }, toast),
844
+ error ? h('div', { className: 'th-toast show', style: { color: 'var(--dsw-alias-state-error-primary)' } }, error) : null,
845
+ form !== null ? h(AgentForm, { agent: form.id ? form : null, t, workspaceTitle, onClose: () => setForm(null), onSave: saveAgent }) : null,
846
+ composer ? h(Composer, { agent: composer.agent, t, onClose: () => setComposer(null), onSend: (text) => sendMessage(composer.agent, text) }) : null,
847
+ refreshing ? h(RefreshModal, { agent: refreshing, t, busy: refreshBusy, onClose: () => setRefreshing(null), onRun: (p) => runRefresh(refreshing, p) }) : null,
848
+ )
849
+ }
850
+
851
+ /* --------------------------------------------------------- 注册 */
852
+ const DICT = {
853
+ zh: {
854
+ title: '团队中枢', panel: '团队画布', workspaceAction: '在团队中枢打开', refresh: '刷新', newAgent: '新建 Agent',
855
+ boundWorkspace: '已绑定工作区', globalWorkspace: '全局视图(未绑定工作区)',
856
+ editAgent: '编辑 Agent', icon: '图标', name: '名称', identity: '身份设定',
857
+ duties: '职责边界', newAgentHint: '将在此工作区创建卡片,再点「实例化」建会话', noWorkspace: '未检测到工作区',
858
+ denyTools: '禁用工具(硬约束)', writeFiles: '可写文件(提示约束)', readFiles: '可读文件(提示约束)',
859
+ cancel: '取消', save: '保存', sendMessage: '发消息 / 派任务',
860
+ refreshInstance: '刷新实例', refreshHint: '旧会话先按「保存进度提示词」收尾,等运行结束后自动归档,再在新会话发送「恢复进度提示词」。',
861
+ savePrompt: '保存进度提示词', restorePrompt: '恢复进度提示词',
862
+ defaultSavePrompt: '请总结当前进度与待办,写入你的记忆,方便在新会话中恢复。完成后回复“已保存”。',
863
+ defaultRestorePrompt: '请从记忆中恢复之前的进度与待办,继续工作。',
864
+ startRefresh: '开始刷新', refreshing: '正在刷新…',
865
+ activity: '协作动态', empty: '还没有 Agent,点「新建 Agent」开始搭建你的团队画布',
866
+ },
867
+ en: {
868
+ title: 'Team Hub', panel: 'Team canvas', workspaceAction: 'Open in Team Hub', refresh: 'Refresh', newAgent: 'New agent',
869
+ boundWorkspace: 'Bound workspace', globalWorkspace: 'Global view (no workspace)',
870
+ editAgent: 'Edit agent', icon: 'Icon', name: 'Name', identity: 'Identity',
871
+ duties: 'Responsibilities', newAgentHint: 'Card will be created here; click Instantiate to bind a session',
872
+ noWorkspace: 'No workspace detected', denyTools: 'Denied tools (hard)', writeFiles: 'Writable files (prompt)', readFiles: 'Readable files (prompt)',
873
+ cancel: 'Cancel', save: 'Save', sendMessage: 'Send message / task',
874
+ refreshInstance: 'Refresh instance', refreshHint: 'The old session wraps up with the save-progress prompt, then is archived; a new session receives the restore-progress prompt.',
875
+ savePrompt: 'Save-progress prompt', restorePrompt: 'Restore-progress prompt',
876
+ defaultSavePrompt: 'Summarize your current progress and TODOs into memory so a new session can resume. Reply "saved" when done.',
877
+ defaultRestorePrompt: 'Resume your previous progress and TODOs from memory, then continue working.',
878
+ startRefresh: 'Start refresh', refreshing: 'Refreshing…',
879
+ activity: 'Activity', empty: 'No agents yet — create one to start your board',
880
+ },
881
+ }
882
+
883
+ function apply(ctx) {
884
+ ctx.effect(() => ctx.locale.register(NS, DICT), 'team-hub: dict')
885
+ const t = ctx.locale.bind(NS)
886
+ const openSession = (id) => { if (id) ctx.uiWorkspace?.openSession(id) }
887
+
888
+ // 侧边栏右栏画布:点击卡片后中央切回原生会话、画布缩到右栏。
889
+ ctx.inject(['sidebarRight'], (svc) => { sidebarRightSvc = svc.get('sidebarRight') })
890
+ ctx.inject(['sidebarRightTabs'], (svc) => {
891
+ try {
892
+ const tabs = svc.get('sidebarRightTabs')
893
+ if (!tabs?.register) return
894
+ svc.effect(() => tabs.register({
895
+ id: TAB_ID, kind: TAB_KIND, priority: 'extension',
896
+ title: () => t('panel'),
897
+ guide: [{ id: 'team-hub', order: 45, title: () => t('panel'), description: () => t('workspaceAction') }],
898
+ }))
899
+ } catch (err) { console.warn('[team-hub] sidebar tab register failed:', err?.message) }
900
+ })
901
+ const Side = (props) => h(SidebarCanvas, { ...props, ctx, t, onOpen: (a) => openSession(a.sessionId) })
902
+ ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID }, Side))
903
+ ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID }, () => h('span', null, t('panel'))))
904
+
905
+ const Page = (props) => h(TeamHubPage, { ...props, ctx, t, openSession })
906
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID, locale: NS }, Page))
907
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
908
+ name: 'sidebar.panellist', id: PANEL_ID, order: 6, label: () => t('panel'), locale: NS,
909
+ }, HubIcon))
910
+ ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({ name: 'contextMenu.icon', key: 'team-hub.icon' }, () => h(HubIcon, { size: 16 })))
911
+
912
+ ctx.inject(['contextMenus'], (svc) => {
913
+ try {
914
+ const menus = svc.get('contextMenus')
915
+ if (!menus?.register) return
916
+ svc.effect(() => menus.register({
917
+ id: 'team-hub.open', target: 'workspace', order: 50,
918
+ resolve: ({ workspaceId, displayTitle }) => [{
919
+ id: 'open-team-hub', label: t('workspaceAction'), icon: { key: 'team-hub.icon' },
920
+ run: () => {
921
+ boundWorkspace = workspaceId
922
+ boundWorkspaceTitle = displayTitle
923
+ ctx.layout?.selectPanel(PANEL_ID)
924
+ },
925
+ }],
926
+ }))
927
+ } catch (err) { console.warn('[team-hub] 工作区菜单注册失败:', err?.message) }
928
+ })
929
+ }
930
+
931
+ return { apply, inject: ['slots', 'locale', 'layout', 'uiWorkspace', 'sessions', 'workspaces', 'contextMenus', 'remote', 'sidebarRight', 'sidebarRightTabs'] }
932
+ },
933
+ })
934
+ })()