@ququ-jiaxk/dsh-groupchat 0.0.0-stage → 0.1.3

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,3436 @@
1
+ /**
2
+ * dsh-groupchat · Client half (MVP)
3
+ *
4
+ * 入口:左侧栏「群聊」图标(全局,任何会话都可见)。点击后主界面显示群聊面板。
5
+ * 数据通过 fetch('/groupchat/api/...') 从 Host 拉取(对齐 ops-board 的已验证通道)。
6
+ *
7
+ * 面板三层:
8
+ * - 群列表:群名 + 成员 + 任务状态徽章,顶部「+ 新建群聊」
9
+ * - 群详情:消息流 + 发消息 + 让项目经理汇报 + 解散群
10
+ * - 新建群对话框:群名/描述/初始任务/项目经理会话(留空=自动创建)/成员会话列表
11
+ */
12
+ window.__ModuleLoader__.load({
13
+ id: '@local/dsh-groupchat',
14
+ factory(require) {
15
+ const React = require('react')
16
+ const { useState, useEffect, useCallback, useRef } = React
17
+ const h = React.createElement
18
+
19
+ const PANEL_ID = 'groupchat'
20
+ const API = '/groupchat/api'
21
+ const NS = 'groupchat'
22
+
23
+ // ---- 主题 token(设计系统) ----
24
+ const T = {
25
+ text: 'var(--dsw-alias-text-primary, #16233A)',
26
+ textMuted: 'var(--dsw-alias-text-secondary, #5B6470)',
27
+ textOnInverse: 'var(--dsw-alias-text-on-inverse, #ffffff)',
28
+ surface: 'var(--dsw-alias-surface, #ffffff)',
29
+ surfaceHover: 'var(--dsw-alias-surface-hover, #F2F5FA)',
30
+ border: 'var(--dsw-alias-border, #E4E9F2)',
31
+ primary: 'var(--dsw-alias-accent, #2E6BE6)',
32
+ danger: '#C0392B',
33
+ warn: '#8A5A12',
34
+ warnBg: '#FFF4E5',
35
+ ok: '#1E7D46',
36
+ okBg: '#EAF6EE',
37
+ // 设计系统扩展
38
+ bg: 'var(--dsw-alias-bg, #F7F8FA)',
39
+ card: 'var(--dsw-alias-surface, #ffffff)',
40
+ cardHover: 'var(--dsw-alias-surface-hover, #FAFBFC)',
41
+ accent: 'var(--dsw-alias-accent, #2E6BE6)',
42
+ accentSoft: 'rgba(46,107,230,0.08)',
43
+ accentText: 'var(--dsw-alias-accent, #2E6BE6)',
44
+ shadow: '0 1px 3px rgba(16,41,66,0.06), 0 1px 2px rgba(16,41,66,0.04)',
45
+ shadowHover: '0 4px 12px rgba(16,41,66,0.1), 0 2px 4px rgba(16,41,66,0.06)',
46
+ radius: 14,
47
+ radiusSm: 10,
48
+ radiusLg: 18,
49
+ shadowMd: '0 8px 24px rgba(16,41,66,0.16), 0 2px 8px rgba(16,41,66,0.1)',
50
+ gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
51
+ gradientPrimary: 'linear-gradient(135deg, var(--dsw-alias-accent, #2E6BE6) 0%, #764ba2 100%)',
52
+ }
53
+
54
+ /**
55
+ * Agent 运行时状态机(与 Host 的 AGENT_STATES 一一对应)。
56
+ * 每种状态有自己的颜色、标签、以及是否需要呼吸动画。
57
+ */
58
+ const AGENT_STATE_META = {
59
+ idle: { label: '空闲', color: '#8A94A6', bg: 'rgba(138,148,166,0.12)', dot: '#8A94A6', ring: '#C9D0DA', pulse: false, busy: false },
60
+ received: { label: '已接收', color: '#B7791F', bg: 'rgba(183,121,31,0.14)', dot: '#D69E2E', ring: '#E8B44A', pulse: true, busy: true },
61
+ thinking: { label: '思考中', color: '#8A5A12', bg: 'rgba(214,158,46,0.14)', dot: '#D69E2E', ring: '#D69E2E', pulse: true, busy: true },
62
+ streaming: { label: '写回复', color: '#2E6BE6', bg: 'rgba(46,107,230,0.12)', dot: '#2E6BE6', ring: '#2E6BE6', pulse: true, busy: true },
63
+ tool: { label: '执行工具', color: '#764ba2', bg: 'rgba(118,75,162,0.12)', dot: '#764ba2', ring: '#764ba2', pulse: true, busy: true },
64
+ waiting: { label: '等待响应', color: '#C0392B', bg: 'rgba(192,57,43,0.12)', dot: '#C0392B', ring: '#C0392B', pulse: true, busy: true },
65
+ offline: { label: '失联', color: '#8A94A6', bg: 'rgba(138,148,166,0.1)', dot: '#B8C0CC', ring: '#D8DEE6', pulse: false, busy: false },
66
+ }
67
+
68
+ function agentStateMeta(state) {
69
+ return AGENT_STATE_META[state] || AGENT_STATE_META.idle
70
+ }
71
+
72
+ function normalizeAgentState(agentState) {
73
+ if (!agentState) return null
74
+ const state = typeof agentState === 'string' ? agentState : agentState.state
75
+ if (!state) return null
76
+ return {
77
+ state,
78
+ detail: (typeof agentState === 'object' && agentState.detail) || '',
79
+ since: (typeof agentState === 'object' && agentState.since) || 0,
80
+ }
81
+ }
82
+
83
+ function isBusyState(agentState) {
84
+ const s = normalizeAgentState(agentState)
85
+ return !!s && !!agentStateMeta(s.state).busy
86
+ }
87
+
88
+ const zh = {
89
+ panel: '群聊',
90
+ empty: '还没有群聊。点「新建群聊」创建一个项目群。',
91
+ newGroup: '新建群聊',
92
+ groupName: '群名',
93
+ groupDesc: '描述(可选)',
94
+ groupTask: '初始任务(可选)',
95
+ sagentId: '项目经理会话 id(留空自动创建)',
96
+ membersHint: '成员会话 id(逗号分隔,可选)',
97
+ create: '创建',
98
+ cancel: '取消',
99
+ back: '返回',
100
+ send: '发送',
101
+ placeholder: '输入消息…',
102
+ refresh: '让项目经理汇报',
103
+ disband: '解散群',
104
+ disbandConfirm: '确定解散该群?群数据将被删除。',
105
+ loading: '加载中…',
106
+ failed: '加载失败',
107
+ taskIdle: '未开始',
108
+ taskDoing: '进行中',
109
+ taskBlocked: '已阻塞',
110
+ taskDone: '已完成',
111
+ members: '成员',
112
+ sagent: '项目经理',
113
+ you: '我',
114
+ system: '系统',
115
+ notify: '汇报',
116
+ autoSagentHint: '将自动创建一个项目经理(sAgent)会话',
117
+ roster: '花名册',
118
+ newProfile: '创建智能体',
119
+ profileName: '名字',
120
+ profileRole: '角色',
121
+ profileBio: '一句话介绍(可选)',
122
+ profileAvatar: '头像',
123
+ profileSession: '绑定会话 id(留空自动新建)',
124
+ profileCreate: '加入花名册',
125
+ profileSave: '保存修改',
126
+ profileHint: '点击头像可编辑该智能体的名字、角色和简介;修改会同步到花名册。',
127
+ // ---- Agent 编辑器 Tab / Activity ----
128
+ tabBasic: '基本信息',
129
+ tabActivity: 'Activity',
130
+ activityEmpty: '还没有工作记录。等这个智能体开始干活后再来看。',
131
+ activityLoading: '加载中…',
132
+ activityRefresh: '刷新',
133
+ activityHint: '记录该智能体最近的运行动作:收到消息、开始处理、调用工具、产出回复。',
134
+ activityKindReceived: '收到消息',
135
+ activityKindThinking: '思考',
136
+ activityKindStreaming: '写回复',
137
+ activityKindTool: '工具',
138
+ activityKindToolResult: '工具返回',
139
+ activityKindWaiting: '等待',
140
+ activityKindMessage: '回复',
141
+ activityKindIdle: '结束',
142
+ activityKindInfo: '信息',
143
+ secState: '运行状态',
144
+ secSession: '工作区 / 会话',
145
+ secProfile: '资料(可编辑)',
146
+ secModel: '模型',
147
+ secHistory: '项目经验',
148
+ workspaceLabel: '工作区',
149
+ sessionLabel: '会话',
150
+ sessionIdLabel: '会话 ID',
151
+ modelCurrent: '当前模型',
152
+ modelInherit: '(默认模型,尚未单独设置)',
153
+ modelSwitch: '切换模型',
154
+ modelProvider: '服务商',
155
+ modelName: '模型',
156
+ modelApply: '应用',
157
+ modelSaved: '模型已切换',
158
+ modelUnavailable: '该会话不在运行中,无法切换模型',
159
+ readonlyNote: '工作区与会话由会话本身决定,只能查看、不能修改。',
160
+ noProfileBound: '该智能体没有绑定花名册资料,只能查看运行信息。',
161
+ profileRemove: '移除',
162
+ profileRemoveConfirm: '确定从花名册移除该智能体?(不删除其会话)',
163
+ profileEmpty: '花名册还没有智能体。点「创建智能体」招一个进来。',
164
+ profileAvailable: '待命',
165
+ profileOnProject: '在群',
166
+ roleLabel: '角色',
167
+ selectSagent: '项目经理(从花名册选,或留空自动创建)',
168
+ selectMembers: '成员(从花名册勾选)',
169
+ noProfile: '花名册里还没有可用智能体,先到「花名册」页创建。',
170
+ manageMembers: '成员管理',
171
+ addMembers: '添加成员',
172
+ addMembersConfirm: '添加所选成员',
173
+ removeMember: '移除',
174
+ noMembersToAdd: '花名册里没有可添加的成员(都在群里了)。',
175
+ taskBoard: '任务看板',
176
+ subtaskPlaceholder: '新增子任务…',
177
+ addSubtask: '添加',
178
+ noSubtasks: '还没有子任务。让项目经理拆解任务,或自己添加一个。',
179
+ assignTo: '派给',
180
+ unassigned: '未派',
181
+ expHistory: '项目经验',
182
+ expEmpty: '暂无项目经验',
183
+ }
184
+
185
+ const en = {
186
+ panel: 'Group chat',
187
+ empty: 'No groups yet. Create a project group.',
188
+ newGroup: 'New group',
189
+ groupName: 'Group name',
190
+ groupDesc: 'Description (optional)',
191
+ groupTask: 'Initial task (optional)',
192
+ sagentId: 'Manager session id (empty = auto-create)',
193
+ membersHint: 'Member session ids (comma-separated, optional)',
194
+ create: 'Create',
195
+ cancel: 'Cancel',
196
+ back: 'Back',
197
+ send: 'Send',
198
+ placeholder: 'Type a message…',
199
+ refresh: 'Ask manager to report',
200
+ disband: 'Disband',
201
+ disbandConfirm: 'Disband this group? Its data will be deleted.',
202
+ loading: 'Loading…',
203
+ failed: 'Failed to load',
204
+ taskIdle: 'Idle',
205
+ taskDoing: 'In progress',
206
+ taskBlocked: 'Blocked',
207
+ taskDone: 'Done',
208
+ members: 'Members',
209
+ sagent: 'Manager',
210
+ you: 'Me',
211
+ system: 'System',
212
+ notify: 'Report',
213
+ autoSagentHint: 'A manager (sAgent) session will be created automatically',
214
+ roster: 'Roster',
215
+ newProfile: 'New agent',
216
+ profileName: 'Name',
217
+ profileRole: 'Role',
218
+ profileBio: 'One-line intro (optional)',
219
+ profileAvatar: 'Avatar',
220
+ profileSession: 'Session id (empty = auto-create)',
221
+ profileCreate: 'Add to roster',
222
+ profileSave: 'Save changes',
223
+ profileHint: 'Click an avatar to edit the agent\'s name, role, and intro; changes sync to the roster.',
224
+ // ---- Agent editor tabs / Activity ----
225
+ tabBasic: 'Basic info',
226
+ tabActivity: 'Activity',
227
+ activityEmpty: 'No activity yet. Check back once this agent starts working.',
228
+ activityLoading: 'Loading…',
229
+ activityRefresh: 'Refresh',
230
+ activityHint: 'Recent runtime actions: messages received, processing started, tool calls, replies produced.',
231
+ activityKindReceived: 'Received',
232
+ activityKindThinking: 'Thinking',
233
+ activityKindStreaming: 'Writing',
234
+ activityKindTool: 'Tool',
235
+ activityKindToolResult: 'Tool result',
236
+ activityKindWaiting: 'Waiting',
237
+ activityKindMessage: 'Reply',
238
+ activityKindIdle: 'Finished',
239
+ activityKindInfo: 'Info',
240
+ secState: 'Runtime state',
241
+ secSession: 'Workspace / Session',
242
+ secProfile: 'Profile (editable)',
243
+ secModel: 'Model',
244
+ secHistory: 'Project experience',
245
+ workspaceLabel: 'Workspace',
246
+ sessionLabel: 'Session',
247
+ sessionIdLabel: 'Session ID',
248
+ modelCurrent: 'Current model',
249
+ modelInherit: '(default model, not set for this session)',
250
+ modelSwitch: 'Switch model',
251
+ modelProvider: 'Provider',
252
+ modelName: 'Model',
253
+ modelApply: 'Apply',
254
+ modelSaved: 'Model switched',
255
+ modelUnavailable: 'This session is not running, so its model cannot be switched',
256
+ readonlyNote: 'Workspace and Session come from the session itself — view only.',
257
+ noProfileBound: 'This agent has no bound roster profile; only runtime info is shown.',
258
+ profileRemove: 'Remove',
259
+ profileRemoveConfirm: 'Remove this agent from the roster? (Its session is not deleted)',
260
+ profileEmpty: 'No agents yet. Create one.',
261
+ profileAvailable: 'Available',
262
+ profileOnProject: 'In group',
263
+ roleLabel: 'Role',
264
+ selectSagent: 'Manager (pick from roster, or leave empty to auto-create)',
265
+ selectMembers: 'Members (pick from roster)',
266
+ noProfile: 'No available agents in the roster. Create one in the Roster tab first.',
267
+ manageMembers: 'Members',
268
+ addMembers: 'Add members',
269
+ addMembersConfirm: 'Add selected',
270
+ removeMember: 'Remove',
271
+ noMembersToAdd: 'No roster agents left to add.',
272
+ taskBoard: 'Task board',
273
+ subtaskPlaceholder: 'New subtask…',
274
+ addSubtask: 'Add',
275
+ noSubtasks: 'No subtasks yet.',
276
+ assignTo: 'Assign to',
277
+ unassigned: 'Unassigned',
278
+ expHistory: 'Experience',
279
+ expEmpty: 'No project experience yet',
280
+ }
281
+
282
+ // ---- 当前会话 id(建群时记录创建者) ----
283
+ const sessionsRef = { current: null }
284
+ // ---- layout 服务(全局 toast 跳转到群聊面板用) ----
285
+ const layoutRef = { current: null }
286
+ function getCurrentSessionId() {
287
+ const sessions = sessionsRef.current
288
+ if (!sessions || !sessions.list) return null
289
+ const byId = sessions.list.getSnapshot().byId
290
+ for (const id of Object.keys(byId)) {
291
+ const row = byId[id]
292
+ if (row && row.retainedBy && (row.retainedBy.mainView ?? 0) > 0) return id
293
+ }
294
+ return null
295
+ }
296
+
297
+ // ---- 全局状态 store:唯一的数据源,面板与 toast 都从这里读 ----
298
+ // 之前面板和全局轮询各拉一次,状态更新滞后且重复请求;现在只有 globalPoll 拉数据。
299
+ const stateStore = (() => {
300
+ let value = null
301
+ const listeners = new Set()
302
+ const emit = () => { for (const l of listeners) l() }
303
+ return {
304
+ get: () => value,
305
+ // delta === true 表示这是增量响应,需要与现有状态合并
306
+ set: (incoming, isDelta) => {
307
+ if (!incoming) return
308
+ if (isDelta && value) {
309
+ const current = value
310
+ const newMessages = [...(current.messages || []), ...(incoming.messages || [])]
311
+ const newSignals = [...(current.signals || []), ...(incoming.signals || [])]
312
+ const seenM = new Set()
313
+ const seenS = new Set()
314
+ value = {
315
+ ...incoming,
316
+ messages: newMessages
317
+ .filter(x => { if (!x || seenM.has(x.id)) return false; seenM.add(x.id); return true })
318
+ .sort((a, b) => a.ts - b.ts),
319
+ signals: newSignals
320
+ .filter(x => { if (!x || seenS.has(x.id)) return false; seenS.add(x.id); return true })
321
+ .sort((a, b) => a.ts - b.ts),
322
+ }
323
+ } else {
324
+ value = incoming
325
+ }
326
+ emit()
327
+ },
328
+ subscribe: (listener) => {
329
+ listeners.add(listener)
330
+ return () => listeners.delete(listener)
331
+ },
332
+ }
333
+ })()
334
+
335
+ // ---- 全局未读计数 store(侧栏图标角标用) ----
336
+ const unreadStore = (() => {
337
+ let value = 0
338
+ const listeners = new Set()
339
+ return {
340
+ get: () => value,
341
+ set: (next) => {
342
+ if (next === value) return
343
+ value = next
344
+ for (const l of listeners) l()
345
+ },
346
+ subscribe: (listener) => {
347
+ listeners.add(listener)
348
+ return () => listeners.delete(listener)
349
+ },
350
+ }
351
+ })()
352
+
353
+ // ---- 面板记忆(跨卸载保留 UI 状态) ----
354
+ // 用户切到别的界面/会话时 GroupchatPanel 会卸载,React state 全部丢失,
355
+ // 再回来就"重新加载"(回到列表、草稿没了、滚动回顶部)。
356
+ // 这里用一个模块级 store 记住这些,重新挂载时原样恢复,且不触发重新拉数据。
357
+ const panelMemo = {
358
+ view: 'list', // 'list' | 'create' | 'roster' | 'createProfile' | groupId
359
+ drafts: {}, // groupId -> 输入框草稿
360
+ scroll: {}, // groupId -> 消息区 scrollTop
361
+ displayCount: {}, // groupId -> 已加载条数
362
+ statusMenuFor: null,
363
+ }
364
+
365
+ // ---- 当前正在查看的群(用于抑制该群的 toast 通知) ----
366
+ // 用户在群里看消息时,新消息已经在眼前了,再弹「XX 说…」纯属噪音。
367
+ const viewingGroupStore = (() => {
368
+ let value = null // 群 id;null 表示不在任何群详情页
369
+ const listeners = new Set()
370
+ return {
371
+ get: () => value,
372
+ set: (next) => {
373
+ if (next === value) return
374
+ value = next
375
+ for (const l of listeners) l()
376
+ },
377
+ subscribe: (listener) => {
378
+ listeners.add(listener)
379
+ return () => listeners.delete(listener)
380
+ },
381
+ }
382
+ })()
383
+
384
+ // ---- 面板导航 store(全局 toast「查看群聊 →」跳转用) ----
385
+ const panelNavStore = (() => {
386
+ let openGroupHandler = null
387
+ let pendingGroup = null
388
+ return {
389
+ // 由 GroupchatPanel 注册:负责把 view 切到某个群
390
+ registerOpener: (fn) => { openGroupHandler = fn },
391
+ // 跳转到某个群:先切到群聊主面板,再让面板打开对应群
392
+ request: (groupId) => {
393
+ pendingGroup = groupId
394
+ // 面板还没挂载时,选中群聊主面板会让它挂载,挂载后消费 pendingGroup
395
+ if (typeof openGroupHandler === 'function') {
396
+ openGroupHandler(groupId)
397
+ pendingGroup = null
398
+ return
399
+ }
400
+ try {
401
+ if (layoutRef.current && typeof layoutRef.current.selectPanel === 'function') {
402
+ layoutRef.current.selectPanel(PANEL_ID)
403
+ }
404
+ } catch (_e) { /* 主面板未注册时忽略 */ }
405
+ },
406
+ // GroupchatPanel 挂载时调用:消费挂起的目标群
407
+ consume: () => {
408
+ const g = pendingGroup
409
+ pendingGroup = null
410
+ return g
411
+ },
412
+ }
413
+ })()
414
+
415
+ // ---- 全局 toast 通知(任何界面可见,多条合并显示) ----
416
+ const toastStore = (() => {
417
+ let value = null // { id, text, groupId, ts }
418
+ const listeners = new Set()
419
+ let timer = null
420
+ return {
421
+ get: () => value,
422
+ show: (toast) => {
423
+ clearTimeout(timer)
424
+ value = { ...toast, ts: Date.now() }
425
+ for (const l of listeners) l(value)
426
+ // 5 秒后自动消失(卡片信息更多,留足阅读时间;进度条同步 5s)
427
+ timer = setTimeout(() => {
428
+ value = null
429
+ for (const l of listeners) l(null)
430
+ }, 5000)
431
+ },
432
+ hide: () => {
433
+ clearTimeout(timer)
434
+ value = null
435
+ for (const l of listeners) l(null)
436
+ },
437
+ subscribe: (listener) => {
438
+ listeners.add(listener)
439
+ return () => listeners.delete(listener)
440
+ },
441
+ }
442
+ })()
443
+
444
+ // ---- 数据访问 ----
445
+ async function api(path, options) {
446
+ const res = await fetch(API + path, options)
447
+ const json = await res.json().catch(() => ({}))
448
+ if (!res.ok) throw new Error(json.error || ('HTTP ' + res.status))
449
+ return json
450
+ }
451
+
452
+ // ---- 全局轮询:无论是否打开群聊面板,都拉增量并弹 toast / 更新角标 ----
453
+ const globalLastTsRef = { current: 0 }
454
+
455
+ // 按群聚合新消息并弹全局 toast(供全局轮询复用)
456
+ function fireToastForNewMessages(newMsgs, groups) {
457
+ if (!newMsgs || newMsgs.length === 0) return
458
+ // 正在查看的群不弹通知:消息已经在眼前,再弹就是打扰
459
+ const viewing = viewingGroupStore.get()
460
+ const groupStats = {}
461
+ for (const m of newMsgs) {
462
+ if (viewing && m.groupId === viewing) continue
463
+ const g = (groups || []).find(x => x.id === m.groupId)
464
+ if (!g) continue
465
+ if (!groupStats[m.groupId]) groupStats[m.groupId] = { name: g.name, count: 0, latest: m }
466
+ groupStats[m.groupId].count++
467
+ groupStats[m.groupId].latest = m
468
+ }
469
+ const gs = Object.values(groupStats)
470
+ if (gs.length === 1) {
471
+ const g = gs[0]
472
+ const m = g.latest
473
+ // 从群成员里解析作者的头像/角色,让通知卡片能显示头像
474
+ const mem = (g.members || []).find(x => x.name === m.authorName)
475
+ const isSagent = m.authorName === g.sAgentName
476
+ toastStore.show({
477
+ kind: 'message',
478
+ groupId: m.groupId,
479
+ groupName: g.name,
480
+ authorName: m.authorName,
481
+ authorRole: mem ? mem.roleId : (isSagent ? 'manager' : ''),
482
+ avatarData: (mem && mem.avatar) || null,
483
+ content: String(m.content || ''),
484
+ count: g.count,
485
+ })
486
+ } else if (gs.length > 1) {
487
+ const total = gs.reduce((sum, g) => sum + g.count, 0)
488
+ toastStore.show({
489
+ kind: 'digest',
490
+ groupId: gs[0].latest.groupId,
491
+ groupName: gs[0].name,
492
+ groups: gs.map(g => ({ name: g.name, count: g.count, latest: g.latest.authorName })),
493
+ count: total,
494
+ })
495
+ }
496
+ }
497
+
498
+ async function globalPoll() {
499
+ try {
500
+ const since = globalLastTsRef.current
501
+ const r = await api('/state' + (since > 0 ? `?since=${since}` : ''))
502
+ const st = r.state || {}
503
+ const msgTs = (st.messages || []).map(m => m.ts)
504
+ const sigTs = (st.signals || []).map(s => s.ts)
505
+ const allTs = msgTs.concat(sigTs)
506
+ const maxTs = allTs.length > 0 ? Math.max(...allTs) : since
507
+ // 首次全量加载(since=0)不弹 toast,避免打开页面就刷历史
508
+ if (since > 0) fireToastForNewMessages(st.messages || [], st.groups)
509
+ globalLastTsRef.current = maxTs
510
+ // 同步侧栏未读角标(delta 响应里 groups 也是全量)
511
+ const totalUnread = (st.groups || []).reduce((sum, g) => sum + (g.unreadToUser || 0), 0)
512
+ unreadStore.set(totalUnread)
513
+ // 把整个 state 推给面板,让 agent 状态实时更新(不依赖面板自己的轮询)
514
+ if (st.groups) stateStore.set(st, r.delta === true)
515
+ } catch (_e) { /* 静默 */ }
516
+ }
517
+
518
+ // ---- 小工具 ----
519
+ /**
520
+ * 轻量 Markdown 渲染器(零依赖,纯 React 元素输出)。
521
+ *
522
+ * 之前消息正文直接当文本子节点渲染,浏览器会折叠换行与连续空格,
523
+ * 导致 ## 标题、**加粗**、列表、空行分段全部糊成一整段。
524
+ * 这里支持群消息里实际出现的子集:
525
+ * #/##/### 标题、**粗体**、`代码`、有序/无序列表、> 引用、--- 分隔线、空行分段、单换行
526
+ */
527
+ function renderRichText(text, opts) {
528
+ const raw = String(text == null ? '' : text)
529
+ if (!raw) return null
530
+ const o = opts || {}
531
+ const bulletColor = o.muted ? 'rgba(255,255,255,0.7)' : T.textMuted
532
+
533
+ // 行内解析:**粗体**、`代码`、[文字](链接)
534
+ const inline = (str, keyPrefix) => {
535
+ const out = []
536
+ const re = /(\*\*([^*]+)\*\*)|(`([^`]+)`)|(\[([^\]]+)\]\(([^)]+)\))/g
537
+ let last = 0
538
+ let m
539
+ let i = 0
540
+ while ((m = re.exec(str)) !== null) {
541
+ if (m.index > last) out.push(str.slice(last, m.index))
542
+ const k = keyPrefix + 'i' + (i++)
543
+ if (m[2] !== undefined) {
544
+ out.push(h('strong', { key: k, style: { fontWeight: 700 } }, m[2]))
545
+ } else if (m[4] !== undefined) {
546
+ out.push(h('code', {
547
+ key: k,
548
+ style: {
549
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
550
+ fontSize: '0.92em', padding: '1px 5px', borderRadius: 4,
551
+ background: o.muted ? 'rgba(255,255,255,0.18)' : 'rgba(16,41,66,0.07)',
552
+ },
553
+ }, m[4]))
554
+ } else if (m[6] !== undefined) {
555
+ out.push(h('a', {
556
+ key: k, href: m[7], target: '_blank', rel: 'noreferrer',
557
+ style: { color: o.muted ? '#fff' : T.accent, textDecoration: 'underline' },
558
+ }, m[6]))
559
+ }
560
+ last = re.lastIndex
561
+ }
562
+ if (last < str.length) out.push(str.slice(last))
563
+ return out.length === 1 && typeof out[0] === 'string' ? out[0] : out
564
+ }
565
+
566
+ const lines = raw.replace(/\r\n?/g, '\n').split('\n')
567
+ const blocks = []
568
+ let i = 0
569
+ let keyN = 0
570
+ const nextKey = () => 'b' + (keyN++)
571
+
572
+ while (i < lines.length) {
573
+ const line = lines[i]
574
+ const trimmed = line.trim()
575
+
576
+ // 空行:跳过(块间距由各块 margin 控制)
577
+ if (!trimmed) { i++; continue }
578
+
579
+ // 分隔线
580
+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
581
+ blocks.push(h('hr', {
582
+ key: nextKey(),
583
+ style: { border: 'none', borderTop: `1px solid ${o.muted ? 'rgba(255,255,255,0.3)' : T.border}`, margin: '10px 0' },
584
+ }))
585
+ i++
586
+ continue
587
+ }
588
+
589
+ // 标题 # ~ ####
590
+ const hm = trimmed.match(/^(#{1,4})\s+(.*)$/)
591
+ if (hm) {
592
+ const level = hm[1].length
593
+ const size = level === 1 ? 17 : level === 2 ? 15.5 : level === 3 ? 14.5 : 14
594
+ blocks.push(h('div', {
595
+ key: nextKey(),
596
+ style: {
597
+ fontSize: size, fontWeight: 700, lineHeight: 1.45,
598
+ margin: blocks.length === 0 ? '0 0 6px' : '12px 0 6px',
599
+ color: o.muted ? '#fff' : T.text,
600
+ },
601
+ }, inline(hm[2], nextKey())))
602
+ i++
603
+ continue
604
+ }
605
+
606
+ // 引用 >
607
+ if (/^>\s?/.test(trimmed)) {
608
+ const quoteLines = []
609
+ while (i < lines.length && /^>\s?/.test(lines[i].trim())) {
610
+ quoteLines.push(lines[i].trim().replace(/^>\s?/, ''))
611
+ i++
612
+ }
613
+ blocks.push(h('div', {
614
+ key: nextKey(),
615
+ style: {
616
+ borderLeft: `3px solid ${o.muted ? 'rgba(255,255,255,0.5)' : T.accent}`,
617
+ paddingLeft: 10, margin: '6px 0', opacity: 0.92,
618
+ fontSize: 13.5, lineHeight: 1.6,
619
+ },
620
+ }, inline(quoteLines.join('\n'), nextKey())))
621
+ continue
622
+ }
623
+
624
+ // Markdown 表格:表头 + 分隔行(|---|---|)+ 数据行
625
+ // 之前没有这个分支,表格被当成普通段落渲染,竖线原样显示、列也挤在一起。
626
+ if (trimmed.includes('|') && i + 1 < lines.length
627
+ && /^\|?[\s:|-]+\|[\s:|-]*$/.test(lines[i + 1].trim())
628
+ && /-{2,}/.test(lines[i + 1])) {
629
+ const splitRow = (ln) => {
630
+ let t = ln.trim()
631
+ if (t.startsWith('|')) t = t.slice(1)
632
+ if (t.endsWith('|')) t = t.slice(0, -1)
633
+ return t.split('|').map(c => c.trim())
634
+ }
635
+ const header = splitRow(line)
636
+ // 解析对齐方式
637
+ const alignCells = splitRow(lines[i + 1])
638
+ const aligns = alignCells.map(c => {
639
+ const l = c.startsWith(':')
640
+ const r = c.endsWith(':')
641
+ if (l && r) return 'center'
642
+ if (r) return 'right'
643
+ if (l) return 'left'
644
+ return 'left'
645
+ })
646
+ i += 2
647
+ const rows = []
648
+ while (i < lines.length && lines[i].trim().includes('|')) {
649
+ const t = lines[i].trim()
650
+ if (!t) break
651
+ rows.push(splitRow(t))
652
+ i++
653
+ }
654
+ const borderColor = o.muted ? 'rgba(255,255,255,0.25)' : T.border
655
+ const headBg = o.muted ? 'rgba(255,255,255,0.12)' : 'rgba(16,41,66,0.04)'
656
+ const cellStyle = (idx) => ({
657
+ padding: '6px 10px', fontSize: 12.8, lineHeight: 1.55,
658
+ textAlign: aligns[idx] || 'left',
659
+ borderBottom: `1px solid ${borderColor}`,
660
+ verticalAlign: 'top', wordBreak: 'break-word', minWidth: 0,
661
+ })
662
+ blocks.push(h('div', {
663
+ key: nextKey(),
664
+ style: { margin: '8px 0', overflowX: 'auto' },
665
+ },
666
+ h('table', {
667
+ style: {
668
+ borderCollapse: 'collapse', width: '100%',
669
+ border: `1px solid ${borderColor}`, borderRadius: 8,
670
+ fontSize: 12.8, tableLayout: 'auto',
671
+ },
672
+ },
673
+ h('thead', null,
674
+ h('tr', null,
675
+ header.map((cell, ci) => h('th', {
676
+ key: 'th' + ci,
677
+ style: {
678
+ ...cellStyle(ci),
679
+ fontWeight: 700,
680
+ background: headBg,
681
+ borderBottom: `1.5px solid ${borderColor}`,
682
+ whiteSpace: 'nowrap',
683
+ },
684
+ }, inline(cell, nextKey() + 'th' + ci))),
685
+ ),
686
+ ),
687
+ h('tbody', null,
688
+ rows.map((row, ri) => h('tr', { key: 'tr' + ri },
689
+ header.map((_h, ci) => h('td', {
690
+ key: 'td' + ri + '_' + ci,
691
+ style: {
692
+ ...cellStyle(ci),
693
+ background: ri % 2 === 1
694
+ ? (o.muted ? 'rgba(255,255,255,0.05)' : 'rgba(16,41,66,0.015)')
695
+ : 'transparent',
696
+ },
697
+ }, inline(row[ci] === undefined ? '' : row[ci], nextKey() + 'td' + ri + '_' + ci))),
698
+ )),
699
+ ),
700
+ ),
701
+ ))
702
+ continue
703
+ }
704
+
705
+ // 有序列表 1. 2.
706
+ if (/^\d+[.)]\s+/.test(trimmed)) {
707
+ const items = []
708
+ while (i < lines.length && /^\d+[.)]\s+/.test(lines[i].trim())) {
709
+ items.push(lines[i].trim().replace(/^\d+[.)]\s+/, ''))
710
+ i++
711
+ }
712
+ blocks.push(h('div', { key: nextKey(), style: { margin: '6px 0' } },
713
+ items.map((t, idx) => h('div', {
714
+ key: 'li' + idx,
715
+ style: { display: 'flex', gap: 6, marginBottom: 4, fontSize: 13.8, lineHeight: 1.6 },
716
+ },
717
+ h('span', { style: { color: bulletColor, flexShrink: 0, minWidth: 14, textAlign: 'right' } }, (idx + 1) + '.'),
718
+ h('span', { style: { flex: 1, minWidth: 0 } }, inline(t, nextKey() + 'li' + idx)),
719
+ )),
720
+ ))
721
+ continue
722
+ }
723
+
724
+ // 无序列表 - * +(支持一级缩进的子项)
725
+ if (/^[-*+]\s+/.test(trimmed)) {
726
+ const items = []
727
+ while (i < lines.length) {
728
+ const cur = lines[i]
729
+ const curTrim = cur.trim()
730
+ if (!/^[-*+]\s+/.test(curTrim)) break
731
+ const indent = cur.length - cur.trimStart().length
732
+ items.push({ text: curTrim.replace(/^[-*+]\s+/, ''), indent })
733
+ i++
734
+ }
735
+ const baseIndent = Math.min(...items.map(x => x.indent))
736
+ blocks.push(h('div', { key: nextKey(), style: { margin: '6px 0' } },
737
+ items.map((it, idx) => h('div', {
738
+ key: 'li' + idx,
739
+ style: {
740
+ display: 'flex', gap: 6, marginBottom: 3,
741
+ fontSize: 13.8, lineHeight: 1.6,
742
+ paddingLeft: Math.max(0, (it.indent - baseIndent) * 6),
743
+ },
744
+ },
745
+ h('span', { style: { color: bulletColor, flexShrink: 0, minWidth: 10 } }, it.indent > baseIndent ? '◦' : '•'),
746
+ h('span', { style: { flex: 1, minWidth: 0 } }, inline(it.text, nextKey() + 'li' + idx)),
747
+ )),
748
+ ))
749
+ continue
750
+ }
751
+
752
+ // 普通段落:连续非空行合并为一个段落,段内保留换行
753
+ const para = []
754
+ while (i < lines.length) {
755
+ const cur = lines[i]
756
+ const t = cur.trim()
757
+ if (!t) break
758
+ if (/^(#{1,4}\s|>|\d+[.)]\s|[-*+]\s)/.test(t)) break
759
+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(t)) break
760
+ // 表格起始(当前行含 | 且下一行是分隔行)也要断开段落
761
+ if (t.includes('|') && i + 1 < lines.length
762
+ && /^\|?[\s:|-]+\|[\s:|-]*$/.test(lines[i + 1].trim())
763
+ && /-{2,}/.test(lines[i + 1])) break
764
+ para.push(t)
765
+ i++
766
+ }
767
+ if (para.length > 0) {
768
+ const parts = []
769
+ para.forEach((p, idx) => {
770
+ parts.push(h('span', { key: 'p' + idx }, inline(p, nextKey() + 'p' + idx)))
771
+ if (idx < para.length - 1) parts.push(h('br', { key: 'br' + idx }))
772
+ })
773
+ blocks.push(h('div', {
774
+ key: nextKey(),
775
+ style: {
776
+ fontSize: 14, lineHeight: 1.7, margin: blocks.length === 0 ? 0 : '8px 0 0',
777
+ wordBreak: 'break-word',
778
+ },
779
+ }, parts))
780
+ }
781
+ }
782
+
783
+ if (blocks.length === 0) return null
784
+ // 展开 blocks:h('div', props, blocks) 会把整个数组当成一个子节点
785
+ return h('div', { style: { display: 'flex', flexDirection: 'column' } }, ...blocks)
786
+ }
787
+
788
+ function fmtTime(ts) {
789
+ const d = new Date(ts)
790
+ const p = (n) => String(n).padStart(2, '0')
791
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
792
+ }
793
+
794
+ function Icon(props) {
795
+ const d = 'M2 13.5V2.5M2 13.5h12M4.5 13.5V9m3 4.5V6m3 7.5V8m3 5.5V4.5'
796
+ return h('svg', { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', ...props },
797
+ h('path', { d }))
798
+ }
799
+
800
+ // ---- 全局 UI 组件(供所有子组件使用) ----
801
+ const wrap = (style, ...children) => h('div', {
802
+ style: {
803
+ // 主面板容器是 flex 列(flex:1; min-height:0),这里用 flex 填充而非
804
+ // 硬编码 height/minHeight,否则面板比可视区还高,消息区不溢出就无法滚动。
805
+ display: 'flex', flexDirection: 'column', flex: '1 1 auto', minHeight: 0, minWidth: 0,
806
+ color: T.text, font: "14px/1.6 -apple-system, PingFang SC, 'Segoe UI', sans-serif",
807
+ background: T.bg, ...style,
808
+ },
809
+ }, children)
810
+
811
+ const btn = (text, onClick, kind, size) => h('button', {
812
+ onClick,
813
+ style: {
814
+ padding: size === 'sm' ? '6px 12px' : '9px 16px',
815
+ borderRadius: T.radiusSm,
816
+ border: kind === 'danger' ? `1px solid ${T.danger}` : 'none',
817
+ background: kind === 'danger' ? 'transparent' : kind === 'ghost' ? T.accentSoft : T.gradientPrimary,
818
+ color: kind === 'danger' ? T.danger : kind === 'ghost' ? T.accentText : T.textOnInverse,
819
+ fontSize: size === 'sm' ? 12 : 13, fontWeight: 500, cursor: 'pointer',
820
+ boxShadow: kind === 'ghost' || kind === 'danger' ? 'none' : T.shadow,
821
+ transition: 'all .15s ease',
822
+ },
823
+ }, text)
824
+
825
+ // compact=true 用于抽屉内的紧凑表单;默认保持群聊输入框的大尺寸
826
+ const input = (value, onChange, placeholder, rows, onKeyDown, compact, extra) => h(rows ? 'textarea' : 'input', {
827
+ value, onChange: (e) => onChange(e.target.value), placeholder,
828
+ ...(rows ? { rows } : {}),
829
+ ...(onKeyDown ? { onKeyDown } : {}),
830
+ ...(extra || {}),
831
+ style: compact
832
+ ? {
833
+ width: '100%', boxSizing: 'border-box', padding: '6px 10px',
834
+ border: `1px solid ${T.border}`, borderRadius: 8, fontSize: 12.5,
835
+ color: T.text, background: T.card, fontFamily: 'inherit', resize: 'vertical',
836
+ transition: 'all .15s ease', lineHeight: 1.5,
837
+ }
838
+ : {
839
+ width: '100%', boxSizing: 'border-box', padding: '11px 16px',
840
+ border: `1.5px solid ${T.border}`, borderRadius: 12, fontSize: 14,
841
+ color: T.text, background: T.bg, fontFamily: 'inherit', resize: 'vertical',
842
+ transition: 'all .15s ease',
843
+ },
844
+ })
845
+
846
+ const card = (children, opts) => h('div', {
847
+ style: {
848
+ background: T.card, borderRadius: T.radius, boxShadow: T.shadow,
849
+ padding: '16px 18px', marginBottom: 12,
850
+ transition: 'all .2s ease',
851
+ border: '1px solid transparent',
852
+ ...(opts || {}),
853
+ },
854
+ ...(opts && opts.onClick ? { onClick: opts.onClick } : {}),
855
+ }, children)
856
+
857
+ // 抽屉(右侧滑出)
858
+ const drawer = (title, children, footer, onClose) => h('div', { style: { position: 'fixed', inset: 0, zIndex: 200 } },
859
+ h('div', {
860
+ style: { position: 'absolute', inset: 0, background: 'rgba(16,41,66,0.3)' },
861
+ onClick: onClose,
862
+ }),
863
+ h('div', {
864
+ style: {
865
+ position: 'absolute', top: 0, right: 0, bottom: 0, width: 420,
866
+ background: T.card, boxShadow: '-4px 0 24px rgba(16,41,66,0.12)',
867
+ display: 'flex', flexDirection: 'column',
868
+ animation: 'slideIn .3s cubic-bezier(0.32, 0.72, 0, 1)',
869
+ },
870
+ },
871
+ h('div', { style: { padding: '12px 16px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 } },
872
+ h('div', { style: { fontSize: 15, fontWeight: 600 } }, title),
873
+ h('button', {
874
+ onClick: onClose,
875
+ style: { width: 32, height: 32, borderRadius: 8, border: 'none', background: T.bg, color: T.textMuted, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14 },
876
+ }, '✕'),
877
+ ),
878
+ h('div', { style: { flex: 1, overflow: 'auto', padding: '16px' } }, children),
879
+ footer ? h('div', { style: { padding: '16px 20px', borderTop: `1px solid ${T.border}`, display: 'flex', justifyContent: 'flex-end', gap: 10 } }, footer) : null,
880
+ ),
881
+ )
882
+
883
+ // 徽章(状态)
884
+ const badge = (text, status) => {
885
+ const map = {
886
+ doing: { bg: T.accentSoft, color: T.accent },
887
+ done: { bg: T.okBg, color: T.ok },
888
+ blocked: { bg: T.warnBg, color: T.warn },
889
+ idle: { bg: T.bg, color: T.textMuted, border: `1px solid ${T.border}` },
890
+ }
891
+ const s = map[status] || map.idle
892
+ return h('span', {
893
+ style: {
894
+ fontSize: 11, padding: '2px 8px', borderRadius: 6, fontWeight: 500,
895
+ background: s.bg, color: s.color, whiteSpace: 'nowrap', letterSpacing: '0.2px',
896
+ ...(s.border ? { border: s.border } : {}),
897
+ },
898
+ }, text)
899
+ }
900
+
901
+ // 头像(角色色块)+ 右下角运行时状态点
902
+ /**
903
+ * 回车是不是"输入法在用"的那次回车?
904
+ *
905
+ * 中文/日文输入法拼写英文或汉字时,按回车是"确认候选词",同时会派发 keydown。
906
+ * 不拦住的话,会把还没上屏的半截拼音直接发出去(组词中被提前提交)。
907
+ * 三种情况都要拦:
908
+ * 1. 事件本身处于组合中(isComposing / nativeEvent.isComposing)
909
+ * 2. 老浏览器的 keyCode 229(组合中的固定码)
910
+ * 3. 某些输入法在 compositionend 之后紧接着补发一次 keydown,需要时间窗兜底
911
+ */
912
+ const isImeComposing = (e, endedAt) => {
913
+ if (!e) return false
914
+ if (e.isComposing || (e.nativeEvent && e.nativeEvent.isComposing)) return true
915
+ if (e.keyCode === 229) return true
916
+ if (endedAt && Date.now() - endedAt < 150) return true
917
+ return false
918
+ }
919
+
920
+ // 垂直轮播(群卡片上的"当前任务"):文字超出可视高度时,按行走上下滚动。
921
+ // 之前用横向 marquee,中文长句左右摆读起来费劲,改成上下步进。
922
+ function VerticalTicker({ text, lineHeight, visibleLines, color }) {
923
+ const lh = lineHeight || 18
924
+ const boxH = lh * (visibleLines || 1)
925
+ const boxRef = useRef(null)
926
+ const innerRef = useRef(null)
927
+ const [offset, setOffset] = useState(0)
928
+
929
+ useEffect(() => {
930
+ setOffset(0)
931
+ const box = boxRef.current
932
+ const inner = innerRef.current
933
+ if (!box || !inner) return undefined
934
+ let pos = 0
935
+ let dir = 1
936
+ const timer = setInterval(() => {
937
+ const max = inner.scrollHeight - box.clientHeight
938
+ if (max <= 1) { setOffset(0); return }
939
+ pos += dir * lh
940
+ if (pos >= max) { pos = max; dir = -1 }
941
+ else if (pos <= 0) { pos = 0; dir = 1 }
942
+ setOffset(pos)
943
+ }, 2200)
944
+ return () => clearInterval(timer)
945
+ }, [text, lh])
946
+
947
+ return h('div', {
948
+ ref: boxRef,
949
+ style: { flex: 1, minWidth: 0, height: boxH, overflow: 'hidden', position: 'relative' },
950
+ },
951
+ h('div', {
952
+ ref: innerRef,
953
+ style: {
954
+ transform: `translateY(-${offset}px)`,
955
+ transition: 'transform .5s ease',
956
+ fontSize: 11.5, lineHeight: lh + 'px',
957
+ color: color || T.textMuted,
958
+ whiteSpace: 'normal', wordBreak: 'break-word',
959
+ },
960
+ }, text),
961
+ )
962
+ }
963
+
964
+ // 头像(角色色块 + 状态环;支持自定义 emoji / 图片头像,缺省回落名字前两字)
965
+ // avatarData 形态:{ kind: 'emoji', value } | { kind: 'image', dataUrl } | null
966
+ const avatar = (name, role, size, agentState, avatarData) => {
967
+ const colors = { manager: '#764ba2', dev: '#2E6BE6', product: '#1E7D46', test: '#8A5A12' }
968
+ const bg = colors[role] || T.gradient
969
+ const sz = size || 22
970
+ const st = normalizeAgentState(agentState)
971
+ const meta = st ? agentStateMeta(st.state) : null
972
+ const busy = !!meta && meta.busy
973
+ const isOffline = !!meta && st.state === 'offline'
974
+ const ringWidth = busy ? 2.5 : (isOffline ? 1.5 : 0)
975
+ const ringGap = busy ? 2 : (isOffline ? 2 : 0)
976
+ const dotSize = Math.max(9, Math.round(sz * 0.34))
977
+
978
+ // 内容:图片 > emoji > 名字前两字
979
+ let content
980
+ let contentBg = bg
981
+ if (avatarData && avatarData.kind === 'image' && avatarData.dataUrl) {
982
+ content = h('img', {
983
+ src: avatarData.dataUrl, alt: name || '',
984
+ style: { width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%', display: 'block' },
985
+ })
986
+ contentBg = 'transparent'
987
+ } else if (avatarData && avatarData.kind === 'emoji' && avatarData.value) {
988
+ content = h('span', { style: { fontSize: sz * 0.58, lineHeight: 1 } }, avatarData.value)
989
+ } else {
990
+ content = (name || '?').slice(0, 2)
991
+ }
992
+
993
+ return h('div', {
994
+ title: meta ? (st.detail ? `${meta.label}:${st.detail}` : meta.label) : undefined,
995
+ style: {
996
+ width: sz, height: sz, borderRadius: '50%', background: contentBg, color: '#fff',
997
+ fontSize: sz * 0.4, display: 'flex', alignItems: 'center', justifyContent: 'center',
998
+ fontWeight: 600, flexShrink: 0, position: 'relative', overflow: 'hidden',
999
+ boxShadow: ringWidth > 0
1000
+ ? `0 0 0 ${ringGap}px #fff, 0 0 0 ${ringGap + ringWidth}px ${meta.ring}`
1001
+ : '0 1px 3px rgba(0,0,0,0.12)',
1002
+ ...(busy ? { animation: 'groupchatRing 1.5s ease-in-out infinite' } : {}),
1003
+ ...(isOffline ? { border: '1.5px dashed ' + meta.ring } : {}),
1004
+ },
1005
+ },
1006
+ content,
1007
+ busy ? h('span', {
1008
+ style: {
1009
+ position: 'absolute', right: -2, bottom: -2, width: dotSize, height: dotSize,
1010
+ borderRadius: '50%', background: meta.dot,
1011
+ border: `${Math.max(1.5, Math.round(dotSize * 0.22))}px solid #fff`,
1012
+ boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
1013
+ animation: 'groupchatPulse 1.2s ease-in-out infinite',
1014
+ },
1015
+ }) : null,
1016
+ )
1017
+ }
1018
+
1019
+ // 状态徽章(带呼吸点,用于成员条 / 详情)
1020
+ const statePill = (agentState) => {
1021
+ const st = normalizeAgentState(agentState)
1022
+ if (!st) return null
1023
+ const meta = agentStateMeta(st.state)
1024
+ const detail = st.detail || ''
1025
+ // idle 不占视觉注意力:只在成员条这种地方给一个极淡的灰标
1026
+ const dim = st.state === 'idle'
1027
+ return h('span', {
1028
+ title: detail ? `${meta.label}:${detail}` : meta.label,
1029
+ style: {
1030
+ display: 'inline-flex', alignItems: 'center', gap: 5,
1031
+ fontSize: 11, padding: '2px 8px', borderRadius: 999, fontWeight: dim ? 400 : 600,
1032
+ background: dim ? 'transparent' : meta.bg,
1033
+ color: dim ? T.textMuted : meta.color,
1034
+ whiteSpace: 'nowrap',
1035
+ ...(dim ? { border: `1px solid ${T.border}` } : {}),
1036
+ },
1037
+ },
1038
+ dim ? null : h('span', {
1039
+ style: {
1040
+ width: 6, height: 6, borderRadius: '50%', background: meta.dot, flexShrink: 0,
1041
+ animation: meta.pulse ? 'groupchatPulse 1.2s ease-in-out infinite' : 'none',
1042
+ },
1043
+ }),
1044
+ meta.label + (detail && st.state === 'tool' ? `:${detail}` : ''),
1045
+ )
1046
+ }
1047
+
1048
+ // 头像堆叠
1049
+ const avatarStack = (members, size) => h('div', { style: { display: 'flex', marginRight: 6 } },
1050
+ members.slice(0, 5).map((m, i) => h('div', {
1051
+ key: i, style: { marginLeft: i === 0 ? 0 : -8, zIndex: 5 - i },
1052
+ }, avatar(m.name, m.role, size, m.agentState, m.avatar || null)))
1053
+ )
1054
+
1055
+ // ---- 主面板 ----
1056
+ function GroupchatPanel() {
1057
+ // 数据来自全局 stateStore(由 globalPoll 驱动),面板不再自己轮询
1058
+ const [state, setState] = useState(() => stateStore.get())
1059
+ // 视图从模块级记忆恢复:切走再切回仍停留在原来的群/标签页
1060
+ const [view, setViewRaw] = useState(() => panelMemo.view || 'list') // 'list' | 'create' | 'roster' | 'createProfile' | groupId
1061
+ const setView = useCallback((next) => {
1062
+ panelMemo.view = next
1063
+ setViewRaw(next)
1064
+ }, [])
1065
+ const [error, setError] = useState(null)
1066
+ const [busy, setBusy] = useState(false)
1067
+ const [lang] = useState(zh) // MVP 先固定中文(locale 服务注入可选,后续再接)
1068
+
1069
+ // 订阅全局状态
1070
+ useEffect(() => {
1071
+ const unsub = stateStore.subscribe(() => setState(stateStore.get()))
1072
+ setState(stateStore.get())
1073
+ return unsub
1074
+ }, [])
1075
+
1076
+ // 主动刷新一次(操作后用,比如发消息、改资料后立刻看到结果)
1077
+ const reload = useCallback(async () => {
1078
+ try {
1079
+ await globalPoll()
1080
+ setError(null)
1081
+ } catch (e) {
1082
+ setError(e.message || '加载失败')
1083
+ }
1084
+ }, [])
1085
+
1086
+ // 注册「打开某个群」的处理器(全局 toast 跳转用),并消费挂起的目标群
1087
+ useEffect(() => {
1088
+ panelNavStore.registerOpener((groupId) => setView(groupId))
1089
+ const pending = panelNavStore.consume()
1090
+ if (pending) setView(pending)
1091
+ return () => panelNavStore.registerOpener(null)
1092
+ }, [])
1093
+
1094
+ const act = useCallback(async (fn) => {
1095
+ if (busy) return
1096
+ setBusy(true)
1097
+ try { await fn() } catch (e) { setError(e.message || '操作失败') } finally { setBusy(false) }
1098
+ }, [busy])
1099
+
1100
+ // ---- 空态 ----
1101
+ if (error && !state) {
1102
+ return wrap({ alignItems: 'center', justifyContent: 'center', padding: 40 },
1103
+ h('div', { style: { color: T.danger, marginBottom: 12 } }, lang.failed + ':' + error),
1104
+ btn('重试', () => reload()),
1105
+ )
1106
+ }
1107
+
1108
+ // ---- 花名册 ----
1109
+ if (view === 'roster' || view === 'createProfile') {
1110
+ return h(RosterPanel, { lang, input, btn, act, api, wrap, drawer, setView, state, onChanged: () => reload(), showCreateProfile: view === 'createProfile' })
1111
+ }
1112
+
1113
+ // ---- 群详情 ----
1114
+ if (view !== 'list' && view !== 'create' && state) {
1115
+ const g = (state.groups || []).find(x => x.id === view)
1116
+ if (g) return h(GroupDetail, { lang, input, btn, act, api, wrap, drawer, state, group: g, setView, onChanged: () => reload() })
1117
+ }
1118
+
1119
+ // ---- 群列表 ----
1120
+ const groups = (state && state.groups) || []
1121
+ return wrap({ overflow: 'hidden' },
1122
+ // 头部:tab + 新建按钮
1123
+ h('div', {
1124
+ style: {
1125
+ padding: '16px 20px', borderBottom: `1px solid ${T.border}`, background: T.card,
1126
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0,
1127
+ },
1128
+ },
1129
+ h('div', { style: { display: 'flex', gap: 20, alignItems: 'center' } },
1130
+ tabLink(lang.panel, view === 'list', () => setView('list')),
1131
+ tabLink(lang.roster, view === 'roster', () => setView('roster')),
1132
+ ),
1133
+ btn(lang.newGroup, () => setView('create')),
1134
+ ),
1135
+ // 群卡片列表
1136
+ h('div', { className: 'gc-fade', style: { flex: 1, overflow: 'auto', padding: '16px 20px' } },
1137
+ groups.length === 0
1138
+ ? h('div', { style: { color: T.textMuted, padding: '40px 0', textAlign: 'center' } }, lang.empty)
1139
+ : groups.map((g, gi) => {
1140
+ // sAgent 的状态挂在 sAgentState,成员的挂在各自 agentState 上
1141
+ const members = [
1142
+ { name: g.sAgentName, role: 'manager', agentState: g.sAgentState },
1143
+ ...(g.members || []),
1144
+ ]
1145
+ const status = g.task ? g.task.status : 'idle'
1146
+ const unread = g.unreadToUser || 0
1147
+ // 有 agent 正在干活(思考/写回复/跑工具/等响应)就亮出状态
1148
+ const busyMembers = members.filter(m => {
1149
+ const st = m.agentState && (m.agentState.state || m.agentState)
1150
+ return st && st !== 'idle' && st !== 'offline'
1151
+ })
1152
+ return h('div', {
1153
+ key: keyOf(g.id),
1154
+ onClick: () => setView(g.id),
1155
+ className: 'gc-card gc-in',
1156
+ style: {
1157
+ background: T.card, borderRadius: T.radius, boxShadow: T.shadow,
1158
+ padding: '16px 18px', marginBottom: 12, cursor: 'pointer',
1159
+ border: '1px solid transparent',
1160
+ position: 'relative',
1161
+ // 错峰入场:每张卡延后 45ms
1162
+ animationDelay: (Math.min(gi, 8) * 45) + 'ms',
1163
+ },
1164
+ onMouseEnter: (e) => { e.currentTarget.style.boxShadow = T.shadowHover },
1165
+ onMouseLeave: (e) => { e.currentTarget.style.boxShadow = T.shadow },
1166
+ },
1167
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 } },
1168
+ h('div', { style: { fontSize: 15, fontWeight: 600, letterSpacing: '-0.2px' } }, g.name),
1169
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
1170
+ unread > 0 ? h('span', {
1171
+ // key 跟着数字走:未读数一变就重挂载,触发 pop 动画
1172
+ key: 'unread-' + unread,
1173
+ className: 'gc-pop',
1174
+ style: {
1175
+ minWidth: 20, height: 20, borderRadius: '50%', background: T.danger, color: '#fff',
1176
+ fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
1177
+ padding: '0 5px',
1178
+ },
1179
+ }, unread > 99 ? '99+' : unread) : null,
1180
+ badge(({
1181
+ idle: lang.taskIdle, doing: lang.taskDoing, blocked: lang.taskBlocked, done: lang.taskDone,
1182
+ })[status] || status, status),
1183
+ ),
1184
+ ),
1185
+ g.description ? h('div', { style: { fontSize: 12.5, color: T.textMuted, marginBottom: 8 } }, g.description) : null,
1186
+ // 最近一条消息预览(随 2 秒轮询实时更新)
1187
+ (() => {
1188
+ const all = (state && state.messages) || []
1189
+ let last = null
1190
+ for (const mm of all) {
1191
+ if (mm.groupId !== g.id) continue
1192
+ if (!last || mm.ts > last.ts) last = mm
1193
+ }
1194
+ if (!last) return null
1195
+ const body = String(last.content || '').replace(/\s+/g, ' ').trim()
1196
+ const isMine = last.authorRole === 'user'
1197
+ return h('div', {
1198
+ // key 跟消息 id 走:来了新消息就重挂载,闪一次背景提示更新
1199
+ key: 'preview-' + last.id,
1200
+ className: 'gc-flash',
1201
+ style: {
1202
+ fontSize: 12, marginBottom: 8, display: 'flex', gap: 4,
1203
+ overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis',
1204
+ color: T.textMuted, alignItems: 'baseline',
1205
+ borderRadius: 4, padding: '1px 3px', marginLeft: -3,
1206
+ },
1207
+ title: `${last.authorName}:${body}`,
1208
+ },
1209
+ h('span', { style: { color: isMine ? T.accent : T.text, fontWeight: 500, flexShrink: 0 } },
1210
+ `${last.authorName}:`),
1211
+ h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis' } }, body.slice(0, 80)),
1212
+ )
1213
+ })(),
1214
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' } },
1215
+ avatarStack(members, 22),
1216
+ h('span', { style: { fontSize: 12, color: T.textMuted } }, members.map(m => m.name).join('、')),
1217
+ // 正在干活的成员状态(思考中 / 写回复 / 执行工具 / 等待响应)
1218
+ busyMembers.length > 0
1219
+ ? h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 'auto' } },
1220
+ busyMembers.slice(0, 2).map((m, i) =>
1221
+ h('span', { key: i, style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
1222
+ h('span', { style: { fontSize: 11, color: T.textMuted } }, m.name),
1223
+ statePill(m.agentState),
1224
+ ),
1225
+ ),
1226
+ )
1227
+ : null,
1228
+ ),
1229
+ // 当前进行中任务的轮播条(随任务状态实时更新,数据来自 2s 全局轮询)
1230
+ (() => {
1231
+ const subs = (g.task && g.task.subtasks) || []
1232
+ const doing = subs.find(x => x.status === 'doing')
1233
+ const blocked = subs.find(x => x.status === 'blocked')
1234
+ const current = blocked || doing
1235
+ if (!current) return null
1236
+ const isBlocked = current.status === 'blocked'
1237
+ const label = (isBlocked ? lang.taskBlocked : lang.taskDoing) + ' · ' + current.title
1238
+ return h('div', {
1239
+ style: {
1240
+ marginTop: 8, paddingTop: 8, borderTop: `1px dashed ${T.border}`,
1241
+ display: 'flex', alignItems: 'center', gap: 6, overflow: 'hidden',
1242
+ },
1243
+ title: label,
1244
+ },
1245
+ h('span', {
1246
+ style: {
1247
+ width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
1248
+ background: isBlocked ? T.warn : T.primary,
1249
+ animation: 'groupchatPulse 1.2s ease-in-out infinite',
1250
+ },
1251
+ }),
1252
+ // 超长标题上下轮播(不再左右摆)
1253
+ h(VerticalTicker, { text: label, lineHeight: 18, visibleLines: 1, color: isBlocked ? T.warn : T.textMuted }),
1254
+ current.ownerName
1255
+ ? h('span', { style: { fontSize: 11, color: T.accent, flexShrink: 0 } }, current.ownerName)
1256
+ : null,
1257
+ )
1258
+ })(),
1259
+ )
1260
+ }),
1261
+ ),
1262
+ // 新建群抽屉
1263
+ view === 'create' ? h(CreateGroup, { lang, input, btn, act, api, wrap, drawer, setView, state, onDone: (id) => { reload(); setView(id) } }) : null,
1264
+ )
1265
+ }
1266
+
1267
+ // ---- 全局 toast 通知组件 ----
1268
+ function ToastNotification() {
1269
+ const [toast, setToast] = useState(null)
1270
+ useEffect(() => {
1271
+ const unsubscribe = toastStore.subscribe((next) => setToast(next))
1272
+ return unsubscribe
1273
+ }, [])
1274
+ if (!toast) return null
1275
+
1276
+ const isDigest = toast.kind === 'digest'
1277
+ const preview = isDigest ? '' : String(toast.content || '').replace(/\s+/g, ' ').trim()
1278
+
1279
+ return h('div', {
1280
+ // 每次新通知换 key,保证重新播放入场动画
1281
+ key: toast.ts,
1282
+ className: 'gc-toast',
1283
+ style: {
1284
+ position: 'fixed', top: 18, right: 18, zIndex: 1000,
1285
+ width: 344, maxWidth: 'calc(100vw - 36px)',
1286
+ background: T.card, borderRadius: 14,
1287
+ border: `1px solid ${T.border}`,
1288
+ boxShadow: '0 12px 32px rgba(16,41,66,0.18), 0 2px 8px rgba(16,41,66,0.08)',
1289
+ pointerEvents: 'auto', overflow: 'hidden',
1290
+ },
1291
+ },
1292
+ // 顶部强调条
1293
+ h('div', {
1294
+ style: {
1295
+ height: 3,
1296
+ background: `linear-gradient(90deg, ${T.accent}, ${T.accent}88)`,
1297
+ },
1298
+ }),
1299
+
1300
+ h('div', { style: { padding: '12px 14px 10px' } },
1301
+ // 第一行:头像 + 群名/时间 + 关闭
1302
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
1303
+ isDigest
1304
+ ? h('div', {
1305
+ style: {
1306
+ width: 32, height: 32, borderRadius: 10, flexShrink: 0,
1307
+ background: T.accentSoft, color: T.accent,
1308
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
1309
+ fontSize: 15, fontWeight: 700,
1310
+ },
1311
+ }, String(toast.count))
1312
+ : avatar(toast.authorName, toast.authorRole, 32, null, toast.avatarData),
1313
+
1314
+ h('div', { style: { flex: 1, minWidth: 0 } },
1315
+ h('div', {
1316
+ title: isDigest ? `${(toast.groups || []).length} 个群有新消息` : toast.groupName,
1317
+ style: {
1318
+ fontSize: 12.5, fontWeight: 600, color: T.text, lineHeight: 1.35,
1319
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
1320
+ },
1321
+ }, isDigest
1322
+ ? `${(toast.groups || []).length} 个群有新消息`
1323
+ : (toast.groupName || '群聊')),
1324
+ h('div', { style: { fontSize: 11, color: T.textMuted, marginTop: 1 } },
1325
+ isDigest
1326
+ ? `共 ${toast.count} 条`
1327
+ : `${toast.authorName}${toast.count > 1 ? ` · 另有 ${toast.count - 1} 条` : ''}`),
1328
+ ),
1329
+
1330
+ h('button', {
1331
+ onClick: () => toastStore.hide(),
1332
+ title: '关闭',
1333
+ style: {
1334
+ border: 'none', background: 'transparent', color: T.textMuted, cursor: 'pointer',
1335
+ fontSize: 13, padding: 2, lineHeight: 1, flexShrink: 0, borderRadius: 6,
1336
+ },
1337
+ onMouseEnter: (e) => { e.currentTarget.style.background = T.bg; e.currentTarget.style.color = T.text },
1338
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = T.textMuted },
1339
+ }, '✕'),
1340
+ ),
1341
+
1342
+ // 正文:摘要模式列群名;单群模式显示消息内容(两行截断)
1343
+ isDigest
1344
+ ? h('div', { style: { marginTop: 8, display: 'flex', flexDirection: 'column', gap: 3 } },
1345
+ (toast.groups || []).slice(0, 3).map((g2, i) =>
1346
+ h('div', {
1347
+ key: i,
1348
+ style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: 11.5, color: T.textMuted },
1349
+ },
1350
+ h('span', {
1351
+ style: { color: T.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 },
1352
+ }, g2.name),
1353
+ h('span', { style: { flexShrink: 0 } }, `${g2.count} 条`),
1354
+ ),
1355
+ ),
1356
+ (toast.groups || []).length > 3
1357
+ ? h('div', { style: { fontSize: 11, color: T.textMuted } }, `…等 ${toast.groups.length} 个群`)
1358
+ : null,
1359
+ )
1360
+ : h('div', {
1361
+ title: preview,
1362
+ style: {
1363
+ marginTop: 8, fontSize: 12.5, color: T.text, lineHeight: 1.55,
1364
+ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
1365
+ overflow: 'hidden', wordBreak: 'break-word',
1366
+ },
1367
+ }, preview),
1368
+ ),
1369
+
1370
+ // 底部操作条
1371
+ h('div', {
1372
+ style: {
1373
+ display: 'flex', alignItems: 'center', gap: 8,
1374
+ padding: '8px 14px 10px',
1375
+ borderTop: `1px solid ${T.border}`, background: T.bg,
1376
+ },
1377
+ },
1378
+ h('button', {
1379
+ onClick: () => { panelNavStore.request(toast.groupId); toastStore.hide() },
1380
+ style: {
1381
+ border: 'none', cursor: 'pointer', padding: '5px 12px', borderRadius: 8,
1382
+ background: T.accent, color: '#fff', fontSize: 12, fontWeight: 500,
1383
+ transition: 'opacity .15s',
1384
+ },
1385
+ onMouseEnter: (e) => { e.currentTarget.style.opacity = '0.88' },
1386
+ onMouseLeave: (e) => { e.currentTarget.style.opacity = '1' },
1387
+ }, '查看群聊'),
1388
+ h('button', {
1389
+ onClick: () => toastStore.hide(),
1390
+ style: {
1391
+ border: `1px solid ${T.border}`, cursor: 'pointer', padding: '5px 12px', borderRadius: 8,
1392
+ background: 'transparent', color: T.textMuted, fontSize: 12,
1393
+ },
1394
+ onMouseEnter: (e) => { e.currentTarget.style.color = T.text },
1395
+ onMouseLeave: (e) => { e.currentTarget.style.color = T.textMuted },
1396
+ }, '忽略'),
1397
+ h('span', { style: { flex: 1 } }),
1398
+ // 自动消失倒计时进度条
1399
+ h('div', {
1400
+ style: {
1401
+ width: 54, height: 3, borderRadius: 999, background: T.border, overflow: 'hidden',
1402
+ },
1403
+ },
1404
+ h('div', {
1405
+ className: 'gc-toast-bar',
1406
+ style: { height: '100%', background: T.accent, borderRadius: 999 },
1407
+ }),
1408
+ ),
1409
+ ),
1410
+ )
1411
+ }
1412
+
1413
+ // ---- 新建群对话框 ----
1414
+ function CreateGroup({ lang, input, btn, act, api, wrap, drawer, setView, state, onDone }) {
1415
+ const [name, setName] = useState('')
1416
+ const [desc, setDesc] = useState('')
1417
+ const [task, setTask] = useState('')
1418
+ const [sagentProfileId, setSagentProfileId] = useState('')
1419
+ const [memberProfileIds, setMemberProfileIds] = useState([])
1420
+
1421
+ const profiles = (state && state.profiles) || []
1422
+
1423
+ const toggleMember = (pid) => {
1424
+ setMemberProfileIds(prev => prev.includes(pid) ? prev.filter(x => x !== pid) : [...prev, pid])
1425
+ }
1426
+
1427
+ const submit = () => act(async () => {
1428
+ const r = await api('/groups', {
1429
+ method: 'POST',
1430
+ headers: { 'content-type': 'application/json' },
1431
+ body: JSON.stringify({
1432
+ name, description: desc, task,
1433
+ autoSagent: !sagentProfileId,
1434
+ sAgentProfileId: sagentProfileId || undefined,
1435
+ memberProfileIds,
1436
+ creatorSessionId: getCurrentSessionId(),
1437
+ }),
1438
+ })
1439
+ onDone(r.groupId)
1440
+ })
1441
+
1442
+ // 可选的项目经理:优先 manager 角色的,否则所有花名册智能体(克隆模型下都可重复用)
1443
+ const managerCandidates = profiles.filter(p => p.roleId === 'role-manager')
1444
+ const managerPool = managerCandidates.length > 0 ? managerCandidates : profiles
1445
+ const memberPool = profiles.filter(p => p.id !== sagentProfileId)
1446
+
1447
+ return drawer(lang.newGroup,
1448
+ h('div', null,
1449
+ field(lang.groupName, input(name, setName, lang.groupName)),
1450
+ field(lang.groupDesc, input(desc, setDesc, lang.groupDesc, 2)),
1451
+ field(lang.groupTask, input(task, setTask, lang.groupTask, 2)),
1452
+
1453
+ // 项目经理选择
1454
+ h('div', { style: { marginBottom: 16 } },
1455
+ h('div', { style: { fontSize: 13, color: T.textMuted, marginBottom: 6, fontWeight: 500 } }, lang.selectSagent),
1456
+ h('select', {
1457
+ value: sagentProfileId,
1458
+ onChange: (e) => { setSagentProfileId(e.target.value); setMemberProfileIds(prev => prev.filter(x => x !== e.target.value)) },
1459
+ style: {
1460
+ width: '100%', boxSizing: 'border-box', padding: '11px 16px',
1461
+ border: `1.5px solid ${T.border}`, borderRadius: 12, fontSize: 14,
1462
+ color: T.text, background: T.bg, fontFamily: 'inherit',
1463
+ transition: 'all .15s ease',
1464
+ },
1465
+ },
1466
+ h('option', { value: '' }, '(自动创建项目经理)'),
1467
+ managerPool.map(p => h('option', { key: p.id, value: p.id }, `${p.name}(${p.roleName})`)),
1468
+ ),
1469
+ ),
1470
+
1471
+ // 成员勾选
1472
+ h('div', { style: { marginBottom: 16 } },
1473
+ h('div', { style: { fontSize: 13, color: T.textMuted, marginBottom: 6, fontWeight: 500 } }, lang.selectMembers),
1474
+ h('div', { style: { maxHeight: 200, overflow: 'auto' } },
1475
+ memberPool.length === 0
1476
+ ? h('div', { style: { color: T.textMuted, fontSize: 12.5 } }, lang.noProfile)
1477
+ : memberPool.map(p => {
1478
+ const checked = memberProfileIds.includes(p.id)
1479
+ return h('label', {
1480
+ key: keyOf(p.id),
1481
+ style: {
1482
+ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
1483
+ border: `1.5px solid ${checked ? T.accent : T.border}`, borderRadius: T.radiusSm,
1484
+ marginBottom: 6, cursor: 'pointer', transition: 'all .15s ease',
1485
+ background: checked ? T.accentSoft : T.card,
1486
+ },
1487
+ },
1488
+ h('input', { type: 'checkbox', checked, onChange: () => toggleMember(p.id), style: { cursor: 'pointer', accentColor: T.accent } }),
1489
+ h('span', { style: { fontWeight: 500, fontSize: 13 } }, p.name),
1490
+ h('span', { style: { fontSize: 11, color: T.accent, marginLeft: 'auto' } }, p.roleName),
1491
+ )
1492
+ }),
1493
+ ),
1494
+ ),
1495
+ ),
1496
+ h('div', null,
1497
+ btn(lang.cancel, () => setView('list'), 'ghost'),
1498
+ btn(lang.create, submit),
1499
+ ),
1500
+ () => setView('list'),
1501
+ )
1502
+ }
1503
+
1504
+ function tabLink(text, active, onClick, key, size) {
1505
+ const sm = size === 'sm'
1506
+ return h('button', {
1507
+ key: keyOf(key === undefined ? text : key),
1508
+ onClick,
1509
+ style: {
1510
+ border: 'none', background: 'transparent', cursor: 'pointer',
1511
+ fontSize: sm ? 13 : 15,
1512
+ fontWeight: active ? 600 : 400, color: active ? T.accent : T.textMuted,
1513
+ padding: sm ? '9px 0' : 0,
1514
+ marginBottom: sm ? -1 : 0,
1515
+ borderBottom: active ? `2px solid ${T.accent}` : '2px solid transparent',
1516
+ transition: 'all .15s ease',
1517
+ },
1518
+ }, text)
1519
+ }
1520
+
1521
+ function field(label, control) {
1522
+ return h('div', { style: { marginBottom: 16 } },
1523
+ h('div', { style: { fontSize: 13, color: T.textMuted, marginBottom: 6, fontWeight: 500 } }, label),
1524
+ control,
1525
+ )
1526
+ }
1527
+
1528
+ // ---- 任务看板抽屉(右侧滑出) ----
1529
+ // 列表在正文滚动区,新增任务表单固定在抽屉底部(footer 位)。
1530
+ function TaskBoardDrawer({ lang, input, btn, drawer, group, subtaskTitle, setSubtaskTitle, addSubtask, updateSubtask, removeSubtask, onClose }) {
1531
+ const subtasks = (group.task && group.task.subtasks) || []
1532
+ // 输入法组合状态(任务描述可能用中文输入法输入)
1533
+ const imeRef = useRef({ composing: false, endedAt: 0 })
1534
+ // 状态切换:先展开列表选择,再二次确认,避免误点直接改状态
1535
+ const [statusMenuFor, setStatusMenuFor] = useState(null) // 展开菜单的子任务 id
1536
+ // { kind: 'status', id, title, status } 或 { kind: 'owner', id, title, ownerSessionId, ownerName }
1537
+ const [confirmTarget, setConfirmTarget] = useState(null)
1538
+ const STATUS_ORDER = ['idle', 'doing', 'blocked', 'done']
1539
+ const statusLabel = (v) => ({
1540
+ idle: lang.taskIdle, doing: lang.taskDoing, done: lang.taskDone, blocked: lang.taskBlocked,
1541
+ })[v] || v
1542
+ const statusColor = (v) => ({
1543
+ idle: T.textMuted, doing: T.primary, done: T.ok, blocked: T.warn,
1544
+ })[v] || T.textMuted
1545
+ const statusBorder = (v) => ({
1546
+ idle: T.border, doing: T.primary, done: T.ok, blocked: T.warn,
1547
+ })[v] || T.border
1548
+ const owners = [group.sAgentName, ...(group.members || []).map(m => m.name)]
1549
+ const ownerSids = [group.sAgentSessionId, ...(group.members || []).map(m => m.sessionId)]
1550
+
1551
+ const body = h('div', null,
1552
+ // 整群状态 + 备注
1553
+ group.task
1554
+ ? h('div', {
1555
+ style: {
1556
+ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
1557
+ padding: '8px 10px', borderRadius: 8, background: T.bg,
1558
+ border: `1px solid ${T.border}`, marginBottom: 12, fontSize: 12,
1559
+ },
1560
+ },
1561
+ badge(({
1562
+ idle: lang.taskIdle, doing: lang.taskDoing, blocked: lang.taskBlocked, done: lang.taskDone,
1563
+ })[group.task.status || 'idle'] || 'idle', group.task.status || 'idle'),
1564
+ group.task.note
1565
+ ? h('span', {
1566
+ title: group.task.note,
1567
+ style: {
1568
+ color: T.textMuted, fontSize: 11.5, flex: 1, minWidth: 0,
1569
+ // 备注最多两行,超出省略;完整内容悬停可见
1570
+ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
1571
+ overflow: 'hidden', lineHeight: 1.5,
1572
+ },
1573
+ }, group.task.note)
1574
+ : null,
1575
+ )
1576
+ : null,
1577
+
1578
+ subtasks.length === 0
1579
+ ? h('div', { style: { fontSize: 12.5, color: T.textMuted, padding: '20px 0', textAlign: 'center' } }, lang.noSubtasks)
1580
+ : subtasks.map(st =>
1581
+ h('div', {
1582
+ key: keyOf(st.id),
1583
+ style: { padding: '10px 0', borderBottom: `1px dashed ${T.border}` },
1584
+ },
1585
+ // 第一行:状态徽标 + 标题(标题独占剩余宽度,自由换行)
1586
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'flex-start' } },
1587
+ h('div', { style: { position: 'relative', flexShrink: 0 } },
1588
+ h('button', {
1589
+ onClick: () => setStatusMenuFor(statusMenuFor === st.id ? null : st.id),
1590
+ title: '点击选择状态',
1591
+ style: {
1592
+ fontSize: 11, padding: '3px 10px', borderRadius: 999, cursor: 'pointer',
1593
+ border: '1.5px solid', background: 'transparent', minWidth: 54, textAlign: 'center',
1594
+ transition: 'all .15s', fontWeight: 500, flexShrink: 0, marginTop: 1,
1595
+ color: ({ idle: T.textMuted, doing: T.primary, done: T.ok, blocked: T.warn })[st.status] || T.textMuted,
1596
+ borderColor: ({ idle: T.border, doing: T.primary, done: T.ok, blocked: T.warn })[st.status] || T.border,
1597
+ },
1598
+ }, statusLabel(st.status)),
1599
+ // ---- 状态下拉:列出四个状态,点选后进入二次确认 ----
1600
+ statusMenuFor === st.id
1601
+ ? h('div', {
1602
+ style: {
1603
+ position: 'absolute', top: '100%', left: 0, marginTop: 4, zIndex: 30,
1604
+ background: T.card, border: `1px solid ${T.border}`, borderRadius: 9,
1605
+ boxShadow: '0 8px 24px rgba(16,41,66,0.16)', padding: 4, minWidth: 116,
1606
+ animation: 'gcFadeIn .16s ease both',
1607
+ },
1608
+ onMouseLeave: () => setStatusMenuFor(null),
1609
+ },
1610
+ STATUS_ORDER.map(sv =>
1611
+ h('button', {
1612
+ key: sv,
1613
+ onClick: () => {
1614
+ setStatusMenuFor(null)
1615
+ if (sv === st.status) return // 选中的就是当前状态,不用确认
1616
+ setConfirmTarget({ kind: 'status', id: st.id, title: st.title, status: sv })
1617
+ },
1618
+ style: {
1619
+ display: 'flex', alignItems: 'center', gap: 6, width: '100%',
1620
+ padding: '6px 9px', borderRadius: 6, border: 'none', cursor: 'pointer',
1621
+ background: sv === st.status ? T.accentSoft : 'transparent',
1622
+ color: statusColor(sv), fontSize: 12, textAlign: 'left',
1623
+ fontWeight: sv === st.status ? 600 : 400,
1624
+ },
1625
+ onMouseEnter: (e) => { if (sv !== st.status) e.currentTarget.style.background = T.bg },
1626
+ onMouseLeave: (e) => { if (sv !== st.status) e.currentTarget.style.background = 'transparent' },
1627
+ },
1628
+ h('span', {
1629
+ style: {
1630
+ width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
1631
+ background: statusColor(sv),
1632
+ },
1633
+ }),
1634
+ statusLabel(sv),
1635
+ sv === st.status ? h('span', { style: { marginLeft: 'auto', fontSize: 11 } }, '✓') : null,
1636
+ ),
1637
+ ),
1638
+ )
1639
+ : null,
1640
+ ),
1641
+ h('div', {
1642
+ style: {
1643
+ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 500, lineHeight: 1.5,
1644
+ wordBreak: 'break-word',
1645
+ textDecoration: st.status === 'done' ? 'line-through' : 'none',
1646
+ color: st.status === 'done' ? T.textMuted : T.text,
1647
+ },
1648
+ }, st.title),
1649
+ ),
1650
+ // 第二行:负责人选择 + 删除,与标题左对齐(缩进 = 徽标宽 + gap)
1651
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 6, paddingLeft: 62 } },
1652
+ h('span', { style: { fontSize: 11, color: T.textMuted, flexShrink: 0 } }, '负责人'),
1653
+ h('select', {
1654
+ value: st.ownerSessionId || '',
1655
+ onChange: (e) => {
1656
+ const val = e.target.value || null
1657
+ if (val === (st.ownerSessionId || null)) return
1658
+ const idx = ownerSids.indexOf(val)
1659
+ setConfirmTarget({
1660
+ kind: 'owner',
1661
+ id: st.id,
1662
+ title: st.title,
1663
+ ownerSessionId: val,
1664
+ ownerName: val ? (owners[idx] || '') : '',
1665
+ })
1666
+ // 让下拉回到原值,等确认后再真正生效
1667
+ e.target.value = st.ownerSessionId || ''
1668
+ },
1669
+ title: lang.assignTo,
1670
+ style: {
1671
+ fontSize: 11.5, padding: '4px 8px', borderRadius: 7,
1672
+ border: `1px solid ${T.border}`, color: T.textMuted,
1673
+ background: T.card, maxWidth: 210, flexShrink: 0,
1674
+ },
1675
+ },
1676
+ h('option', { value: '' }, lang.unassigned),
1677
+ ownerSids.map((sid, i) => h('option', { key: sid, value: sid }, owners[i])),
1678
+ ),
1679
+ h('span', { style: { flex: 1 } }),
1680
+ h('button', {
1681
+ onClick: () => setConfirmTarget({ kind: 'delete', id: st.id, title: st.title }),
1682
+ title: '删除子任务',
1683
+ style: { border: 'none', background: 'transparent', color: T.danger, cursor: 'pointer', fontSize: 12, flexShrink: 0, padding: 4 },
1684
+ }, '✕'),
1685
+ ),
1686
+ ),
1687
+ ),
1688
+
1689
+ // ---- 二次确认条:选中状态后必须先确认才真正提交 ----
1690
+ confirmTarget
1691
+ ? h('div', {
1692
+ style: {
1693
+ position: 'sticky', bottom: 0, marginTop: 12,
1694
+ background: T.card, border: `1px solid ${T.border}`, borderRadius: 10,
1695
+ boxShadow: '0 -4px 16px rgba(16,41,66,0.10)',
1696
+ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 8,
1697
+ animation: 'gcFadeIn .18s ease both',
1698
+ // sticky 元素默认按内容宽度撑开,会被抽屉右边界裁掉;
1699
+ // 显式占满可用宽度 + 允许换行
1700
+ width: '100%', maxWidth: '100%', boxSizing: 'border-box',
1701
+ overflow: 'hidden', wordBreak: 'break-word',
1702
+ },
1703
+ },
1704
+ // 文案按类型区分:改状态 vs 改负责人
1705
+ h('div', { style: { fontSize: 12.5, color: T.text, lineHeight: 1.5 } },
1706
+ confirmTarget.kind === 'delete'
1707
+ ? h('span', null,
1708
+ '确认删除',
1709
+ h('span', { style: { fontWeight: 600 } }, `「${confirmTarget.title}」`),
1710
+ '?删除后不可恢复。')
1711
+ : confirmTarget.kind === 'owner'
1712
+ ? h('span', null,
1713
+ '确认把',
1714
+ h('span', { style: { fontWeight: 600 } }, `「${confirmTarget.title}」`),
1715
+ '的负责人改为',
1716
+ h('span', {
1717
+ style: { fontWeight: 600, color: T.accent, whiteSpace: 'nowrap' },
1718
+ }, `「${confirmTarget.ownerName || (lang.unassigned || '未指派')}」`),
1719
+ '?')
1720
+ : h('span', null,
1721
+ '确认把',
1722
+ h('span', { style: { fontWeight: 600 } }, `「${confirmTarget.title}」`),
1723
+ '改为',
1724
+ h('span', {
1725
+ style: { fontWeight: 600, color: statusColor(confirmTarget.status), whiteSpace: 'nowrap' },
1726
+ }, `「${statusLabel(confirmTarget.status)}」`),
1727
+ '状态?'),
1728
+ ),
1729
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end', flexShrink: 0 } },
1730
+ btn(lang.cancel, () => setConfirmTarget(null), 'ghost', 'sm'),
1731
+ btn(confirmTarget.kind === 'delete' ? '确认删除' : '确认更改', () => {
1732
+ const t = confirmTarget
1733
+ setConfirmTarget(null)
1734
+ if (t.kind === 'delete') {
1735
+ removeSubtask(t.id)
1736
+ return
1737
+ }
1738
+ if (t.kind === 'owner') {
1739
+ // 负责人变更:保持当前状态不变,只改 owner
1740
+ const cur = subtasks.find(x => x.id === t.id)
1741
+ updateSubtask(t.id, (cur && cur.status) || 'idle', t.ownerSessionId)
1742
+ } else {
1743
+ updateSubtask(t.id, t.status)
1744
+ }
1745
+ }, confirmTarget.kind === 'delete' ? 'danger' : 'primary', 'sm'),
1746
+ ),
1747
+ )
1748
+ : null,
1749
+ )
1750
+
1751
+ // 底部固定的新增任务表单:多行输入(任务描述往往很长,单行输入框不够用)
1752
+ // Enter 换行;⌘/Ctrl+Enter 提交。
1753
+ // width:100% —— drawer 的 footer 容器是 justifyContent:flex-end,
1754
+ // 不撑满的话多行输入框会被挤成一小条
1755
+ const footer = h('div', { style: { display: 'flex', gap: 8, alignItems: 'flex-end', width: '100%' } },
1756
+ h('div', { style: { flex: 1, minWidth: 0 } },
1757
+ h('textarea', {
1758
+ value: subtaskTitle,
1759
+ placeholder: lang.subtaskPlaceholder,
1760
+ onKeyDown: (e) => {
1761
+ // 组合输入中的回车/组合刚结束的回车都不算快捷键
1762
+ if (isImeComposing(e, imeRef.current.endedAt)) return
1763
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && subtaskTitle.trim()) {
1764
+ e.preventDefault()
1765
+ addSubtask()
1766
+ }
1767
+ },
1768
+ onCompositionStart: () => { imeRef.current.composing = true },
1769
+ onCompositionEnd: () => { imeRef.current.composing = false; imeRef.current.endedAt = Date.now() },
1770
+ onChange: (e) => {
1771
+ setSubtaskTitle(e.target.value)
1772
+ // 自动增高:1~5 行后内部滚动
1773
+ const el = e.currentTarget
1774
+ el.style.height = 'auto'
1775
+ el.style.height = Math.min(el.scrollHeight, 132) + 'px'
1776
+ },
1777
+ style: {
1778
+ width: '100%', boxSizing: 'border-box', padding: '8px 10px',
1779
+ border: `1px solid ${T.border}`, borderRadius: 8, fontSize: 13,
1780
+ color: T.text, background: T.card, fontFamily: 'inherit', lineHeight: 1.55,
1781
+ minHeight: 58, maxHeight: 132, resize: 'vertical', outline: 'none',
1782
+ },
1783
+ }),
1784
+ ),
1785
+ btn(lang.addSubtask, addSubtask, undefined, 'sm'),
1786
+ )
1787
+
1788
+ return drawer(lang.taskBoard, body, footer, onClose)
1789
+ }
1790
+
1791
+ // ---- 群详情 ----
1792
+ function GroupDetail({ lang, input, btn, act, api, wrap, drawer, state, group, setView, onChanged }) {
1793
+ // 进入群详情时登记"正在看的群",离开时清除 —— 期间该群不弹 toast 通知
1794
+ React.useEffect(() => {
1795
+ viewingGroupStore.set(group.id)
1796
+ // 只在"当前仍是本群"时才清空:切到另一个群时,
1797
+ // 旧组件的 cleanup 会先执行,不能把新群的状态擦掉。
1798
+ return () => {
1799
+ if (viewingGroupStore.get() === group.id) viewingGroupStore.set(null)
1800
+ }
1801
+ }, [group.id])
1802
+
1803
+ // 草稿从记忆恢复:切走再回来,没发出去的字还在
1804
+ const [draft, setDraft] = useState(() => panelMemo.drafts[group.id] || '')
1805
+ const [showMembers, setShowMembers] = useState(false)
1806
+ const [showBoard, setShowBoard] = useState(false)
1807
+ const [addIds, setAddIds] = useState([])
1808
+ const [subtaskTitle, setSubtaskTitle] = useState('')
1809
+ // @ 成员快捷选择
1810
+ const [showMention, setShowMention] = useState(false)
1811
+ const [mentionIndex, setMentionIndex] = useState(0)
1812
+ // 消息分批加载:默认显示最近 50 条
1813
+ // 已加载条数从记忆恢复:回来时不至于又只剩最近 50 条
1814
+ const [displayCount, setDisplayCount] = useState(() => panelMemo.displayCount[group.id] || 50)
1815
+ // 滚动容器 ref(打开/新消息时滚动到底部)
1816
+ const messagesRef = useRef(null)
1817
+ // 是否用户手动向上翻了(不自动滚动)
1818
+ const userScrolledUp = useRef(false)
1819
+
1820
+ const messages = (state.messages || []).filter(m => m.groupId === group.id).sort((a, b) => a.ts - b.ts)
1821
+ const displayMessages = messages.slice(-displayCount)
1822
+ const hasMore = messages.length > displayCount
1823
+
1824
+ // 根据 authorName 找到群成员的「成员记录」(含 sAgent)。
1825
+ // 注意:sAgent 不在 group.members 里,之前只查 members 会导致点项目经理头像什么都不发生。
1826
+ const memberOf = (authorName) => {
1827
+ if (!authorName) return null
1828
+ const profiles = (state && state.profiles) || []
1829
+ if (authorName === group.sAgentName) {
1830
+ const prof = group.sAgentProfileId ? profiles.find(p => p.id === group.sAgentProfileId) : null
1831
+ return {
1832
+ name: group.sAgentName,
1833
+ roleId: 'manager',
1834
+ role: 'manager',
1835
+ sessionId: group.sAgentSessionId,
1836
+ profileId: group.sAgentProfileId || null,
1837
+ agentState: group.sAgentState || null,
1838
+ sessionInfo: group.sAgentSession || null,
1839
+ isSagent: true,
1840
+ avatarData: prof && prof.avatar ? prof.avatar : null,
1841
+ }
1842
+ }
1843
+ const m = (group.members || []).find(x => x.name === authorName)
1844
+ if (!m) return null
1845
+ const prof = m.profileId ? profiles.find(p => p.id === m.profileId) : null
1846
+ // Host 已把 sessionInfo 字段(cwd/workspace/title/sessionId)平铺到成员上
1847
+ return {
1848
+ ...m,
1849
+ avatarData: (prof && prof.avatar) || null,
1850
+ sessionInfo: {
1851
+ sessionId: m.sessionId,
1852
+ cwd: m.cwd || '',
1853
+ workspace: m.workspace || '',
1854
+ title: m.title || '',
1855
+ },
1856
+ }
1857
+ }
1858
+
1859
+ // 某个作者的运行时状态(给消息头像/名字旁的状态点用)
1860
+ const agentStateForAuthor = (authorName) => {
1861
+ const m = memberOf(authorName)
1862
+ return m && m.agentState ? m.agentState : null
1863
+ }
1864
+
1865
+ // 头像点击打开设置:把 profile(花名册)与成员(会话)合并成一个可展示对象。
1866
+ // 成员可能没有绑定花名册 profile(如自动创建的 sAgent),这时也要能打开面板。
1867
+ const openAgentPanel = (authorName) => {
1868
+ const m = memberOf(authorName)
1869
+ if (!m) return
1870
+ const prof = m.profileId ? ((state && state.profiles) || []).find(p => p.id === m.profileId) : null
1871
+ setAgentProfileView({
1872
+ // 花名册字段(有 profile 才可编辑)
1873
+ id: prof ? prof.id : null,
1874
+ profileId: m.profileId || null,
1875
+ name: prof ? prof.name : m.name,
1876
+ roleId: prof ? prof.roleId : (m.roleId || ''),
1877
+ roleName: prof ? prof.roleName : (m.role || ''),
1878
+ bio: prof ? prof.bio : '',
1879
+ history: prof ? (prof.history || []) : [],
1880
+ groups: prof ? (prof.groups || []) : [],
1881
+ avatarData: (prof && prof.avatar) || m.avatarData || null,
1882
+ // 成员/会话字段(只读展示)
1883
+ sessionId: m.sessionId || '',
1884
+ sessionInfo: m.sessionInfo || null,
1885
+ agentState: m.agentState || null,
1886
+ isSagent: !!m.isSagent,
1887
+ editable: !!prof,
1888
+ })
1889
+ }
1890
+
1891
+ // 头像 hover 状态(显示简介卡片)
1892
+ const [hoveredAuthor, setHoveredAuthor] = useState(null)
1893
+ // 头像位置 ref(用于定位简介卡片)
1894
+ const avatarRefs = useRef({})
1895
+ // 头像点击的 agent 设置界面(可编辑)
1896
+ const [agentProfileView, setAgentProfileView] = useState(null)
1897
+ // agent 编辑状态
1898
+ const [editName, setEditName] = useState('')
1899
+ const [editRoleId, setEditRoleId] = useState('')
1900
+ const [editBio, setEditBio] = useState('')
1901
+
1902
+ // 打开 agent 设置界面时初始化编辑字段
1903
+ useEffect(() => {
1904
+ if (agentProfileView) {
1905
+ setEditName(agentProfileView.name || '')
1906
+ setEditRoleId(agentProfileView.roleId || '')
1907
+ setEditBio(agentProfileView.bio || '')
1908
+ }
1909
+ }, [agentProfileView])
1910
+
1911
+ // @ 成员列表(群成员 + 项目经理)
1912
+ const mentionMembers = [{ name: group.sAgentName, roleId: 'manager', role: group.sAgentName }, ...(group.members || [])]
1913
+
1914
+ // 打开群时标记给用户的未读消息为已读(角标清零)
1915
+ useEffect(() => {
1916
+ api(`/groups/${group.id}/read`, { method: 'POST' }).catch(() => {})
1917
+ }, [group.id, api])
1918
+
1919
+ // 恢复滚动位置期间置位,避免"自动滚到底"把它覆盖掉
1920
+ const restoringScroll = useRef(false)
1921
+
1922
+ // 打开群时滚动到最新消息(底部)——除非本次是从记忆恢复位置
1923
+ useEffect(() => {
1924
+ if (restoringScroll.current) return
1925
+ if (messagesRef.current) {
1926
+ messagesRef.current.scrollTop = messagesRef.current.scrollHeight
1927
+ }
1928
+ }, [group.id])
1929
+
1930
+ // 新消息到达时自动滚动到底部(除非用户向上翻了)。
1931
+ //
1932
+ // 依赖必须是「最后一条消息的身份 + 总条数」,不能只用 displayMessages.length:
1933
+ // displayMessages 是 messages.slice(-displayCount) 的窗口,超过 displayCount(默认 50)
1934
+ // 之后 length 恒等于 displayCount,effect 再也不会触发 —— 这就是「新消息不自动滚动」的根因。
1935
+ const lastMessageKey = displayMessages.length > 0
1936
+ ? displayMessages[displayMessages.length - 1].id
1937
+ : ''
1938
+ const messageCount = messages.length
1939
+ React.useLayoutEffect(() => {
1940
+ const el = messagesRef.current
1941
+ if (!el) return
1942
+ if (userScrolledUp.current) return
1943
+ // 刚挂载且在恢复上次滚动位置时,不要抢着滚到底
1944
+ if (restoringScroll.current) return
1945
+ const scrollToBottom = () => {
1946
+ // 恢复滚动位置期间、或用户已向上翻,都不要抢着滚到底。
1947
+ // 之前只拦了第一帧,嵌套 rAF 在后面又滚了一次,把恢复的位置覆盖掉了。
1948
+ if (restoringScroll.current) return
1949
+ if (userScrolledUp.current) return
1950
+ const node = messagesRef.current
1951
+ if (node) node.scrollTop = node.scrollHeight
1952
+ }
1953
+ // 当前帧渲染完先滚一次;下一帧再滚一次,兜住图片/字体等异步撑高
1954
+ scrollToBottom()
1955
+ const raf = requestAnimationFrame(() => {
1956
+ scrollToBottom()
1957
+ requestAnimationFrame(scrollToBottom)
1958
+ })
1959
+ return () => cancelAnimationFrame(raf)
1960
+ }, [lastMessageKey, messageCount, group.id])
1961
+
1962
+ // 监听滚动:用户向上翻时不自动滚动;同时记住位置,切走再回来看原处
1963
+ const handleScroll = (e) => {
1964
+ const el = e.target
1965
+ const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40
1966
+ userScrolledUp.current = !atBottom
1967
+ panelMemo.scroll[group.id] = el.scrollTop
1968
+ }
1969
+
1970
+ // 重新挂载时恢复上次的滚动位置(若之前停在底部,则保持"自动滚到底"的行为)
1971
+ useEffect(() => {
1972
+ const saved = panelMemo.scroll[group.id]
1973
+ if (typeof saved !== 'number' || !messagesRef.current) return
1974
+ restoringScroll.current = true
1975
+ // 重挂载后消息是一帧帧渲染出来的,scrollHeight 会持续增长;
1976
+ // 过早设置 scrollTop 会被夹到当前最大底部。这里多帧重试直到位置真的落下。
1977
+ let tries = 0
1978
+ let rafId = 0
1979
+ const applyRestore = () => {
1980
+ const el = messagesRef.current
1981
+ if (!el) { restoringScroll.current = false; return }
1982
+ el.scrollTop = saved
1983
+ const maxNow = el.scrollHeight - el.clientHeight
1984
+ const settled = maxNow >= saved - 1
1985
+ if (!settled && tries++ < 20) {
1986
+ rafId = requestAnimationFrame(applyRestore)
1987
+ return
1988
+ }
1989
+ const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40
1990
+ userScrolledUp.current = !atBottom
1991
+ // 保护再保留一小段时间,等所有嵌套 rAF 跑完再解除
1992
+ setTimeout(() => { restoringScroll.current = false }, 200)
1993
+ }
1994
+ rafId = requestAnimationFrame(applyRestore)
1995
+ return () => { restoringScroll.current = false; cancelAnimationFrame(rafId) }
1996
+ // 只在群变化时恢复一次
1997
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1998
+ }, [group.id])
1999
+
2000
+ // 加载更早的消息
2001
+ const loadOlder = () => setDisplayCount((c) => {
2002
+ const next = c + 50
2003
+ panelMemo.displayCount[group.id] = next
2004
+ return next
2005
+ })
2006
+
2007
+ // 检测 @ 输入(input 的 onChange 传的是 value)
2008
+ const handleDraftChange = (value) => {
2009
+ setDraft(value)
2010
+ panelMemo.drafts[group.id] = value
2011
+ // 检测最后一个 @ 字符
2012
+ const lastAt = value.lastIndexOf('@')
2013
+ if (lastAt >= 0 && value.length === lastAt + 1) {
2014
+ setShowMention(true)
2015
+ setMentionIndex(0)
2016
+ } else {
2017
+ setShowMention(false)
2018
+ }
2019
+ }
2020
+
2021
+ // 选择 @ 成员
2022
+ const selectMention = (member) => {
2023
+ setDraft(draft + member.name + ' ')
2024
+ setShowMention(false)
2025
+ }
2026
+
2027
+ // 输入法组合状态:拼写英文/汉字时按回车是"确认候选",不能当发送
2028
+ const imeRef = useRef({ composing: false, endedAt: 0 })
2029
+ const composerCompositionProps = {
2030
+ onCompositionStart: () => { imeRef.current.composing = true },
2031
+ onCompositionEnd: () => {
2032
+ imeRef.current.composing = false
2033
+ imeRef.current.endedAt = Date.now()
2034
+ },
2035
+ }
2036
+
2037
+ // 键盘上下选择 + Enter 发送
2038
+ const handleKeyDown = (e) => {
2039
+ // ── 最关键的一行 ──
2040
+ // 输入法组合中的回车(含刚结束组合瞬间补发的回车)一律放行给输入法,
2041
+ // 既不 preventDefault 也不发送,否则会把没上屏的半截文字发出去。
2042
+ if (isImeComposing(e, imeRef.current.endedAt)) return
2043
+
2044
+ // @ 成员选择弹层打开时,Enter 选择成员
2045
+ if (showMention) {
2046
+ if (e.key === 'ArrowDown') {
2047
+ e.preventDefault()
2048
+ setMentionIndex(Math.min(mentionIndex + 1, mentionMembers.length - 1))
2049
+ } else if (e.key === 'ArrowUp') {
2050
+ e.preventDefault()
2051
+ setMentionIndex(Math.max(mentionIndex - 1, 0))
2052
+ } else if (e.key === 'Enter') {
2053
+ e.preventDefault()
2054
+ selectMention(mentionMembers[mentionIndex])
2055
+ } else if (e.key === 'Escape') {
2056
+ setShowMention(false)
2057
+ }
2058
+ return
2059
+ }
2060
+ // Enter 发送消息(非 Shift+Enter 换行)
2061
+ if (e.key === 'Enter' && !e.shiftKey) {
2062
+ e.preventDefault()
2063
+ send()
2064
+ }
2065
+ }
2066
+
2067
+ const send = () => act(async () => {
2068
+ if (!draft.trim()) return
2069
+ await api(`/groups/${group.id}/post`, {
2070
+ method: 'POST',
2071
+ headers: { 'content-type': 'application/json' },
2072
+ body: JSON.stringify({ content: draft.trim(), sessionId: getCurrentSessionId() }),
2073
+ })
2074
+ setDraft('')
2075
+ panelMemo.drafts[group.id] = ''
2076
+ // 自己发的消息要滚到底部:清掉「向上翻」标记,让新消息到达时自动滚动
2077
+ userScrolledUp.current = false
2078
+ onChanged()
2079
+ })
2080
+
2081
+ // 「让项目经理汇报」的反馈状态:idle | sending | ok | fail
2082
+ const [refreshState, setRefreshState] = useState('idle')
2083
+ const refresh = () => act(async () => {
2084
+ setRefreshState('sending')
2085
+ try {
2086
+ const r = await api(`/groups/${group.id}/refresh`, { method: 'POST' })
2087
+ // r.woken:经理是否被唤醒(false = 会话失联/无法唤醒)
2088
+ setRefreshState(r && r.woken === false ? 'fail' : 'ok')
2089
+ } catch (e) {
2090
+ setRefreshState('fail')
2091
+ throw e
2092
+ } finally {
2093
+ onChanged()
2094
+ // 2.5 秒后复位按钮文字
2095
+ setTimeout(() => setRefreshState('idle'), 2500)
2096
+ }
2097
+ })
2098
+
2099
+ const disband = () => act(async () => {
2100
+ if (!window.confirm(lang.disbandConfirm)) return
2101
+ await api(`/groups/${group.id}`, { method: 'DELETE' })
2102
+ onChanged()
2103
+ setView('list')
2104
+ })
2105
+
2106
+ const addMembers = () => act(async () => {
2107
+ if (addIds.length === 0) return
2108
+ await api(`/groups/${group.id}/members`, {
2109
+ method: 'POST',
2110
+ headers: { 'content-type': 'application/json' },
2111
+ body: JSON.stringify({ profileIds: addIds }),
2112
+ })
2113
+ setAddIds([])
2114
+ onChanged()
2115
+ })
2116
+
2117
+ const removeMember = (sessionId) => act(async () => {
2118
+ await api(`/groups/${group.id}/members/${encodeURIComponent(sessionId)}`, { method: 'DELETE' })
2119
+ onChanged()
2120
+ })
2121
+
2122
+ // 任务看板操作:通过 group_task_update 工具对应的 HTTP 无工具路径?不,直接调用后端端点。
2123
+ // 这里复用 HTTP:新增一个轻量端点 /tasks 或复用现有?MVP 用直接操作 state 的 HTTP 端点更简单。
2124
+ // 但为了一致,我在 Host 端加 /groups/:id/tasks 端点,这里调用它。
2125
+ const addSubtask = () => act(async () => {
2126
+ if (!subtaskTitle.trim()) return
2127
+ await api(`/groups/${group.id}/tasks`, {
2128
+ method: 'POST',
2129
+ headers: { 'content-type': 'application/json' },
2130
+ body: JSON.stringify({ action: 'add', title: subtaskTitle.trim() }),
2131
+ })
2132
+ setSubtaskTitle('')
2133
+ onChanged()
2134
+ })
2135
+
2136
+ const updateSubtask = (subtaskId, status, ownerSessionId) => act(async () => {
2137
+ await api(`/groups/${group.id}/tasks`, {
2138
+ method: 'POST',
2139
+ headers: { 'content-type': 'application/json' },
2140
+ body: JSON.stringify({ action: 'update', subtaskId, status, ...(ownerSessionId !== undefined ? { ownerSessionId } : {}) }),
2141
+ })
2142
+ onChanged()
2143
+ })
2144
+
2145
+ const removeSubtask = (subtaskId) => act(async () => {
2146
+ await api(`/groups/${group.id}/tasks`, {
2147
+ method: 'POST',
2148
+ headers: { 'content-type': 'application/json' },
2149
+ body: JSON.stringify({ action: 'remove', subtaskId }),
2150
+ })
2151
+ onChanged()
2152
+ })
2153
+
2154
+ const memberNames = [group.sAgentName, ...(group.members || []).map(m => m.name)]
2155
+ // 可添加的花名册智能体:排除已在群里的 profile
2156
+ const inGroupProfileIds = new Set([
2157
+ group.sAgentProfileId,
2158
+ ...(group.members || []).map(m => m.profileId).filter(Boolean),
2159
+ ])
2160
+ const addableProfiles = ((state && state.profiles) || []).filter(p => !inGroupProfileIds.has(p.id))
2161
+
2162
+ return wrap({},
2163
+ // 头部
2164
+ h('div', { style: { padding: '14px 20px', borderBottom: `1px solid ${T.border}`, background: T.card, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 } },
2165
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
2166
+ h('button', { onClick: () => setView('list'), style: { width: 32, height: 32, borderRadius: 10, border: 'none', background: T.bg, color: T.accent, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14 } }, '←'),
2167
+ h('div', { style: { fontSize: 16, fontWeight: 600, letterSpacing: '-0.2px' } }, group.name),
2168
+ badge(({
2169
+ idle: lang.taskIdle, doing: lang.taskDoing, blocked: lang.taskBlocked, done: lang.taskDone,
2170
+ })[group.task?.status || 'idle'] || 'idle', group.task?.status || 'idle'),
2171
+ ),
2172
+ h('div', { style: { display: 'flex', gap: 6 } },
2173
+ btn(
2174
+ refreshState === 'sending' ? '发送中…'
2175
+ : refreshState === 'ok' ? '已通知经理 ✓'
2176
+ : refreshState === 'fail' ? '未唤醒,经理可能失联'
2177
+ : lang.refresh,
2178
+ refresh, 'ghost', 'sm',
2179
+ ),
2180
+ btn(lang.taskBoard, () => setShowBoard(v => !v), 'ghost', 'sm'),
2181
+ btn(lang.manageMembers, () => setShowMembers(v => !v), 'ghost', 'sm'),
2182
+ btn(lang.disband, disband, 'danger', 'sm'),
2183
+ ),
2184
+ ),
2185
+ // 任务 + 成员条:头像化(去掉「成员:」标签,点头像 = 点聊天区头像)
2186
+ h('div', { style: { padding: '10px 20px', borderBottom: `1px solid ${T.border}`, background: T.card, fontSize: 12.5, color: T.textMuted, display: 'flex', gap: 14, flexShrink: 0, alignItems: 'center', flexWrap: 'wrap' } },
2187
+ h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' } },
2188
+ // 项目经理
2189
+ (() => {
2190
+ const open = () => openAgentPanel(group.sAgentName)
2191
+ return h('span', {
2192
+ onClick: open,
2193
+ title: `${group.sAgentName}(点击查看)`,
2194
+ style: { display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer', padding: '2px 6px 2px 2px', borderRadius: 999, transition: 'background .15s' },
2195
+ onMouseEnter: (e) => { e.currentTarget.style.background = T.accentSoft },
2196
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent' },
2197
+ },
2198
+ avatar(group.sAgentName, 'manager', 26, group.sAgentState, (memberOf(group.sAgentName) || {}).avatarData),
2199
+ h('span', { style: { fontSize: 12.5, color: T.text } }, group.sAgentName),
2200
+ )
2201
+ })(),
2202
+ // 成员
2203
+ (group.members || []).map(m =>
2204
+ h('span', {
2205
+ key: m.sessionId,
2206
+ onClick: () => openAgentPanel(m.name),
2207
+ title: `${m.name}(点击查看)`,
2208
+ style: { display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer', padding: '2px 6px 2px 2px', borderRadius: 999, transition: 'background .15s' },
2209
+ onMouseEnter: (e) => { e.currentTarget.style.background = T.accentSoft },
2210
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent' },
2211
+ },
2212
+ avatar(m.name, m.roleId, 26, m.agentState, (memberOf(m.name) || {}).avatarData),
2213
+ h('span', { style: { fontSize: 12.5, color: T.text } }, m.name),
2214
+ ),
2215
+ ),
2216
+ ),
2217
+ group.task && group.task.stage ? h('span', null, `任务:${group.task.stage}`) : null,
2218
+ group.task && group.task.note ? h('span', { style: { color: T.warn } }, `状态:${group.task.note}`) : null,
2219
+ ),
2220
+ // 任务看板改为右侧抽屉:列表在正文滚动区,新增表单固定在抽屉底部
2221
+ showBoard ? h(TaskBoardDrawer, {
2222
+ lang, input, btn, drawer, group,
2223
+ subtaskTitle, setSubtaskTitle,
2224
+ addSubtask, updateSubtask, removeSubtask,
2225
+ onClose: () => setShowBoard(false),
2226
+ }) : null,
2227
+ // 消息流(气泡式,分批加载)
2228
+ // minHeight:0 + 子项 flexShrink:0:flex 列容器里子项默认会被压扁,
2229
+ // 内容一多就不溢出、不产生滚动条,scrollTop=scrollHeight 也就成了空操作。
2230
+ h('div', {
2231
+ ref: messagesRef,
2232
+ onScroll: handleScroll,
2233
+ style: { flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '20px', display: 'flex', flexDirection: 'column' },
2234
+ },
2235
+ // 加载更早的消息按钮
2236
+ hasMore ? h('div', { style: { textAlign: 'center', marginBottom: 16 } },
2237
+ h('button', {
2238
+ onClick: loadOlder,
2239
+ style: { padding: '6px 16px', borderRadius: T.radiusSm, border: `1px solid ${T.border}`, background: T.card, color: T.accent, cursor: 'pointer', fontSize: 12.5, transition: 'all .15s' },
2240
+ onMouseEnter: (e) => e.currentTarget.style.background = T.accentSoft,
2241
+ onMouseLeave: (e) => e.currentTarget.style.background = T.card,
2242
+ }, `加载更早的消息(还有 ${messages.length - displayCount} 条)`),
2243
+ ) : null,
2244
+ displayMessages.length === 0
2245
+ ? h('div', { style: { color: T.textMuted, textAlign: 'center', padding: 40 } }, '—')
2246
+ : displayMessages.map(m => {
2247
+ const isMe = m.authorRole === 'user'
2248
+ const isNotify = m.kind === 'notify'
2249
+ const isSystem = m.kind === 'system'
2250
+ const roleColor = { manager: '#764ba2', dev: '#2E6BE6', product: '#1E7D46', test: '#8A5A12' }[m.authorRole] || T.accent
2251
+ return h('div', {
2252
+ key: keyOf(m.id),
2253
+ style: {
2254
+ display: 'flex', marginBottom: 14, gap: 10, flexShrink: 0,
2255
+ justifyContent: isSystem ? 'center' : isMe ? 'flex-end' : 'flex-start',
2256
+ },
2257
+ },
2258
+ // 用户消息不显示头像和标记(用户自己知道是自己发的)
2259
+ !isSystem && !isMe ? (() => {
2260
+ const st = agentStateForAuthor(m.authorName)
2261
+ const meta = st ? agentStateMeta(st.state) : null
2262
+ const showDot = !!meta && st.state !== 'idle' && st.state !== 'offline'
2263
+ return h('div', {
2264
+ ref: (el) => { if (el) avatarRefs.current[m.authorName] = el },
2265
+ style: {
2266
+ width: 34, height: 34, borderRadius: '50%', flexShrink: 0,
2267
+ background: roleColor, color: '#fff',
2268
+ fontSize: 11, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center',
2269
+ boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
2270
+ cursor: 'pointer', position: 'relative',
2271
+ ...(showDot ? { boxShadow: `0 0 0 2px ${meta.bg}` } : {}),
2272
+ },
2273
+ onClick: () => openAgentPanel(m.authorName),
2274
+ onMouseEnter: () => setHoveredAuthor(m.authorName),
2275
+ onMouseLeave: () => setHoveredAuthor(null),
2276
+ },
2277
+ (m.authorName || '?').slice(0, 2),
2278
+ showDot ? h('span', {
2279
+ title: meta.label,
2280
+ style: {
2281
+ position: 'absolute', right: -2, bottom: -2, width: 10, height: 10,
2282
+ borderRadius: '50%', background: meta.dot, border: '2px solid #fff',
2283
+ animation: meta.pulse ? 'groupchatPulse 1.4s ease-in-out infinite' : 'none',
2284
+ },
2285
+ }) : null,
2286
+ )
2287
+ })() : null,
2288
+ h('div', { style: { maxWidth: isSystem ? '100%' : '70%' } },
2289
+ // 用户消息不显示 authorName 和 role 标记
2290
+ !isSystem && !isMe ? h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, justifyContent: isMe ? 'flex-end' : 'flex-start' } },
2291
+ h('span', { style: { fontSize: 12.5, fontWeight: 600 } }, m.authorName),
2292
+ h('span', { style: { fontSize: 10, padding: '1px 6px', borderRadius: 999, border: `1px solid ${roleColor}`, color: roleColor } }, m.authorRole),
2293
+ statePill(agentStateForAuthor(m.authorName)),
2294
+ h('span', { style: { fontSize: 11, color: T.textMuted } }, fmtTime(m.ts)),
2295
+ ) : null,
2296
+ h('div', {
2297
+ style: {
2298
+ padding: isSystem ? '2px 0' : '10px 16px',
2299
+ borderRadius: T.radiusLg, fontSize: 14, lineHeight: 1.65,
2300
+ background: isSystem ? 'transparent' : isNotify ? T.warnBg : isMe ? T.gradientPrimary : T.card,
2301
+ color: isMe ? '#fff' : T.text,
2302
+ boxShadow: isSystem ? 'none' : T.shadow,
2303
+ border: isNotify ? `1px solid #F3D9B4` : 'none',
2304
+ ...(isNotify ? { borderLeft: `3px solid ${T.warn}` } : {}),
2305
+ ...(isSystem ? { textAlign: 'center', fontSize: 11.5, color: T.textMuted } : {}),
2306
+ },
2307
+ // 正文走轻量 Markdown 渲染:保留段落、换行、标题、列表、粗体
2308
+ }, renderRichText(m.content, { muted: isMe }) || m.content),
2309
+ ),
2310
+ )
2311
+ }),
2312
+ ),
2313
+ // 输入区(带 @ 成员快捷选择)
2314
+ h('div', { style: { padding: '16px 20px', borderTop: `1px solid ${T.border}`, background: T.card, display: 'flex', gap: 12, flexShrink: 0, position: 'relative' } },
2315
+ h('div', { style: { flex: 1, position: 'relative' } },
2316
+ input(draft, handleDraftChange, lang.placeholder, undefined, handleKeyDown, undefined, composerCompositionProps),
2317
+ // @ 成员快捷选择弹层
2318
+ showMention && mentionMembers.length > 0 ? h('div', {
2319
+ style: {
2320
+ position: 'absolute', bottom: '100%', left: 0, right: 0, marginBottom: 4,
2321
+ background: T.card, borderRadius: T.radiusSm, boxShadow: T.shadowMd,
2322
+ border: `1px solid ${T.border}`, maxHeight: 200, overflow: 'auto', zIndex: 100,
2323
+ },
2324
+ },
2325
+ mentionMembers.map((m, i) => h('div', {
2326
+ key: keyOf(m.sessionId),
2327
+ onClick: () => selectMention(m),
2328
+ style: {
2329
+ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px',
2330
+ cursor: 'pointer', background: i === mentionIndex ? T.accentSoft : 'transparent',
2331
+ transition: 'background .1s',
2332
+ },
2333
+ onMouseEnter: (e) => e.currentTarget.style.background = T.accentSoft,
2334
+ onMouseLeave: (e) => e.currentTarget.style.background = i === mentionIndex ? T.accentSoft : 'transparent',
2335
+ },
2336
+ avatar(m.name, m.roleId, 24, null, (memberOf(m.name) || {}).avatarData),
2337
+ h('span', { style: { fontSize: 13, fontWeight: 500 } }, m.name),
2338
+ h('span', { style: { fontSize: 11, color: T.accent, marginLeft: 'auto' } }, m.role),
2339
+ )),
2340
+ ) : null,
2341
+ ),
2342
+ btn(lang.send, send),
2343
+ ),
2344
+ // 成员管理抽屉
2345
+ showMembers ? drawer(lang.manageMembers,
2346
+ h('div', null,
2347
+ h('div', { style: { fontSize: 13, fontWeight: 600, color: T.textMuted, marginBottom: 12 } }, lang.members),
2348
+ (group.members || []).map(m => h('div', {
2349
+ key: keyOf(m.sessionId),
2350
+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: `1px dashed ${T.border}` },
2351
+ },
2352
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
2353
+ avatar(m.name, m.roleId, 32, null, (memberOf(m.name) || {}).avatarData),
2354
+ h('div', null,
2355
+ h('div', { style: { fontWeight: 500, fontSize: 13 } }, m.name),
2356
+ h('div', { style: { fontSize: 11, color: T.accent } }, m.role),
2357
+ ),
2358
+ ),
2359
+ h('button', {
2360
+ onClick: () => removeMember(m.sessionId),
2361
+ style: { border: 'none', background: 'transparent', color: T.danger, cursor: 'pointer', fontSize: 12 },
2362
+ }, lang.removeMember),
2363
+ )),
2364
+ h('div', { style: { fontSize: 13, fontWeight: 600, color: T.textMuted, margin: '20px 0 12px' } }, lang.addMembers),
2365
+ h('div', { style: { maxHeight: 200, overflow: 'auto' } },
2366
+ addableProfiles.length === 0
2367
+ ? h('div', { style: { fontSize: 12.5, color: T.textMuted } }, lang.noMembersToAdd)
2368
+ : addableProfiles.map(p => {
2369
+ const checked = addIds.includes(p.id)
2370
+ return h('label', {
2371
+ key: keyOf(p.id),
2372
+ style: {
2373
+ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
2374
+ border: `1.5px solid ${checked ? T.accent : T.border}`, borderRadius: T.radiusSm,
2375
+ marginBottom: 6, cursor: 'pointer', transition: 'all .15s',
2376
+ background: checked ? T.accentSoft : T.card,
2377
+ },
2378
+ },
2379
+ h('input', { type: 'checkbox', checked, onChange: () => setAddIds(prev => prev.includes(p.id) ? prev.filter(x => x !== p.id) : [...prev, p.id]), style: { cursor: 'pointer', accentColor: T.accent } }),
2380
+ h('span', { style: { fontWeight: 500, fontSize: 13 } }, p.name),
2381
+ h('span', { style: { fontSize: 11, color: T.accent, marginLeft: 'auto' } }, p.roleName),
2382
+ )
2383
+ }),
2384
+ ),
2385
+ ),
2386
+ h('div', null,
2387
+ btn(lang.addMembersConfirm, addMembers),
2388
+ ),
2389
+ () => setShowMembers(false)
2390
+ ) : null,
2391
+ // 头像 hover 简介卡片(从头像位置附近弹出,贴边自动翻转避免超出视口)
2392
+ hoveredAuthor && memberOf(hoveredAuthor) ? (() => {
2393
+ const info = memberOf(hoveredAuthor)
2394
+ const prof = info.profileId ? ((state && state.profiles) || []).find(p => p.id === info.profileId) : null
2395
+ const avatarEl = avatarRefs.current[hoveredAuthor]
2396
+ const rect = avatarEl ? avatarEl.getBoundingClientRect() : null
2397
+ const CARD_W = 320
2398
+ const GAP = 12
2399
+ let left, top, transform = 'none'
2400
+ if (rect) {
2401
+ const vw = window.innerWidth
2402
+ const vh = window.innerHeight
2403
+ // 优先放头像右侧;放不下就放左侧;再不行就固定到视口内
2404
+ if (rect.right + GAP + CARD_W <= vw) left = rect.right + GAP
2405
+ else if (rect.left - GAP - CARD_W >= 0) left = rect.left - GAP - CARD_W
2406
+ else left = Math.max(8, vw - CARD_W - 8)
2407
+ // 垂直以头像顶边为基准,向下溢出视口时向上收
2408
+ top = rect.top
2409
+ if (top + 260 > vh) top = Math.max(8, vh - 260 - 8)
2410
+ } else {
2411
+ left = '50%'
2412
+ top = '50%'
2413
+ transform = 'translate(-50%, -50%)'
2414
+ }
2415
+ return h('div', {
2416
+ style: {
2417
+ position: 'fixed', left, top, transform,
2418
+ background: T.card, borderRadius: T.radius, boxShadow: T.shadowMd,
2419
+ padding: '20px', maxWidth: CARD_W, width: CARD_W, boxSizing: 'border-box',
2420
+ zIndex: 300, border: `1px solid ${T.border}`,
2421
+ pointerEvents: 'none',
2422
+ },
2423
+ },
2424
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 } },
2425
+ avatar(info.name, info.roleId, 40, info.agentState, info.avatarData),
2426
+ h('div', null,
2427
+ h('div', { style: { fontSize: 15, fontWeight: 600 } }, info.name),
2428
+ h('div', { style: { fontSize: 12, color: T.accent } }, info.role || info.roleId),
2429
+ ),
2430
+ ),
2431
+ // 实时状态
2432
+ info.agentState ? h('div', { style: { marginBottom: 8 } }, statePill(info.agentState)) : null,
2433
+ prof && prof.bio ? h('div', { style: { fontSize: 12.5, color: T.textMuted, marginBottom: 8 } }, prof.bio) : null,
2434
+ // 工作区 / 会话(只读)
2435
+ info.sessionInfo ? h('div', { style: { fontSize: 11.5, color: T.textMuted, borderTop: `1px dashed ${T.border}`, paddingTop: 8, marginTop: 4 } },
2436
+ info.sessionInfo.workspace ? h('div', null, `工作区:${info.sessionInfo.workspace}`) : null,
2437
+ info.sessionInfo.cwd ? h('div', { style: { wordBreak: 'break-all', opacity: 0.75 } }, info.sessionInfo.cwd) : null,
2438
+ info.sessionInfo.sessionId ? h('div', { style: { fontFamily: 'ui-monospace, monospace', opacity: 0.6 } }, info.sessionInfo.sessionId.slice(0, 8)) : null,
2439
+ ) : null,
2440
+ prof && (prof.history || []).length > 0
2441
+ ? h('div', { style: { fontSize: 11.5, color: T.textMuted, borderTop: `1px dashed ${T.border}`, paddingTop: 8 } },
2442
+ h('div', { style: { fontSize: 11, fontWeight: 600, marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.5px' } }, lang.expHistory),
2443
+ prof.history.slice(-3).map((h2, i) => h('div', { key: i, style: { marginBottom: 2 } },
2444
+ `· ${h2.groupName}:${h2.title}${h2.summary ? '(' + h2.summary + ')' : ''}`)),
2445
+ )
2446
+ : null,
2447
+ )
2448
+ })() : null,
2449
+ // 头像点击的 agent 设置界面:运行时状态 + 工作区/会话(只读)+ 可编辑资料 + 模型切换
2450
+ agentProfileView ? h(AgentEditorDrawer, {
2451
+ key: keyOf(agentProfileView.sessionId || agentProfileView.id || 'agent-editor'),
2452
+ view: agentProfileView,
2453
+ state,
2454
+ lang,
2455
+ input,
2456
+ btn,
2457
+ api,
2458
+ act,
2459
+ drawer,
2460
+ setView,
2461
+ editName, setEditName,
2462
+ editRoleId, setEditRoleId,
2463
+ editBio, setEditBio,
2464
+ onClose: () => setAgentProfileView(null),
2465
+ onSaved: () => { setAgentProfileView(null); onChanged() },
2466
+ onModelChanged: () => onChanged(),
2467
+ onAvatarChanged: () => onChanged(),
2468
+ }) : null,
2469
+ )
2470
+ }
2471
+
2472
+ // ---- 区块标题(设置抽屉内复用) ----
2473
+ function sectionTitle(text, extra) {
2474
+ return h('div', {
2475
+ style: {
2476
+ fontSize: 11, fontWeight: 700, color: T.textMuted, textTransform: 'uppercase',
2477
+ letterSpacing: '0.6px', marginBottom: 8, marginTop: extra ? 20 : 0,
2478
+ },
2479
+ }, text)
2480
+ }
2481
+
2482
+ // 只读信息行(label + value)
2483
+ function infoRow(label, value, mono) {
2484
+ if (!value) return null
2485
+ return h('div', { style: { display: 'flex', gap: 10, fontSize: 12.5, lineHeight: 1.7, alignItems: 'baseline' } },
2486
+ h('span', { style: { color: T.textMuted, minWidth: 56, flexShrink: 0 } }, label),
2487
+ h('span', {
2488
+ style: {
2489
+ color: T.text, wordBreak: 'break-all',
2490
+ ...(mono ? { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 11.5, opacity: 0.85 } : {}),
2491
+ },
2492
+ }, value),
2493
+ )
2494
+ }
2495
+
2496
+ // ---- 花名册 ----
2497
+ function RosterPanel({ lang, input, btn, act, api, wrap, drawer, setView, state, onChanged, showCreateProfile }) {
2498
+ const profiles = (state && state.profiles) || []
2499
+ const [editProfile, setEditProfile] = useState(null)
2500
+ // 花名册编辑表单状态:必须在本组件内声明。
2501
+ // 此前误用了 GroupDetail 里的 editName/editRoleId/editBio,
2502
+ // 它们不在本作用域 → 点「编辑」直接 ReferenceError,整个面板崩掉。
2503
+ const [editName, setEditName] = useState('')
2504
+ const [editRoleId, setEditRoleId] = useState('')
2505
+ const [editBio, setEditBio] = useState('')
2506
+ useEffect(() => {
2507
+ if (editProfile) {
2508
+ setEditName(editProfile.name || '')
2509
+ setEditRoleId(editProfile.roleId || '')
2510
+ setEditBio(editProfile.bio || '')
2511
+ }
2512
+ }, [editProfile])
2513
+ const remove = (p) => act(async () => {
2514
+ if (!window.confirm(lang.profileRemoveConfirm)) return
2515
+ await api(`/profiles/${p.id}`, { method: 'DELETE' })
2516
+ onChanged()
2517
+ })
2518
+
2519
+ return wrap({ overflow: 'hidden' },
2520
+ // 头部:tab + 新建按钮
2521
+ h('div', {
2522
+ style: {
2523
+ padding: '16px 20px', borderBottom: `1px solid ${T.border}`, background: T.card,
2524
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0,
2525
+ },
2526
+ },
2527
+ h('div', { style: { display: 'flex', gap: 20, alignItems: 'center' } },
2528
+ tabLink(lang.panel, false, () => setView('list')),
2529
+ tabLink(lang.roster, true, () => setView('roster')),
2530
+ ),
2531
+ btn(lang.newProfile, () => setView('createProfile')),
2532
+ ),
2533
+ // 卡片网格
2534
+ h('div', { className: 'gc-fade', style: { flex: 1, overflow: 'auto', padding: '24px' } },
2535
+ profiles.length === 0
2536
+ ? h('div', { style: { color: T.textMuted, padding: '40px 0', textAlign: 'center' } }, lang.profileEmpty)
2537
+ : h('div', {
2538
+ style: {
2539
+ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
2540
+ gap: 16,
2541
+ // 同一行的卡片等高:gridAutoRows + 卡片 height:100%
2542
+ gridAutoRows: '1fr',
2543
+ alignItems: 'stretch',
2544
+ },
2545
+ },
2546
+ profiles.map((p, pi) => {
2547
+ const groups = p.groups || []
2548
+ const isBusy = groups.length > 0
2549
+ const roleColor = { 'role-manager': '#764ba2', 'role-dev': '#2E6BE6', 'role-product': '#1E7D46', 'role-test': '#8A5A12' }[p.roleId] || T.accent
2550
+ // 两行截断的通用样式(保证卡片内每块高度可预期,不因内容长短参差)
2551
+ const clamp = (lines) => ({
2552
+ display: '-webkit-box', WebkitLineClamp: lines, WebkitBoxOrient: 'vertical',
2553
+ overflow: 'hidden', wordBreak: 'break-word',
2554
+ })
2555
+ return h('div', {
2556
+ key: keyOf(p.id),
2557
+ className: 'gc-card gc-in',
2558
+ style: {
2559
+ background: T.card, borderRadius: T.radius, boxShadow: T.shadow,
2560
+ padding: '18px 18px 14px', border: '1px solid transparent',
2561
+ display: 'flex', flexDirection: 'column', height: '100%', boxSizing: 'border-box',
2562
+ minHeight: 148,
2563
+ animationDelay: (Math.min(pi, 8) * 45) + 'ms',
2564
+ },
2565
+ onMouseEnter: (e) => { e.currentTarget.style.boxShadow = T.shadowHover },
2566
+ onMouseLeave: (e) => { e.currentTarget.style.boxShadow = T.shadow },
2567
+ },
2568
+ // ---- 头部:头像 + 名字/角色(名字最多两行,固定块高)----
2569
+ h('div', { style: { display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 10 } },
2570
+ p.avatar
2571
+ ? avatar(p.name, p.roleId, 44, null, p.avatar)
2572
+ : h('div', {
2573
+ style: {
2574
+ width: 44, height: 44, borderRadius: 14, background: roleColor, color: '#fff',
2575
+ fontSize: 17, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
2576
+ boxShadow: '0 2px 6px rgba(0,0,0,0.12)', flexShrink: 0,
2577
+ },
2578
+ }, (p.name || '?').slice(0, 2)),
2579
+ h('div', { style: { minWidth: 0, flex: 1 } },
2580
+ h('div', {
2581
+ title: p.name,
2582
+ style: { fontSize: 14.5, fontWeight: 600, lineHeight: 1.35, ...clamp(2) },
2583
+ }, p.name),
2584
+ h('div', { style: { fontSize: 11, color: roleColor, marginTop: 2 } }, p.roleName),
2585
+ ),
2586
+ ),
2587
+ // ---- 状态条 ----
2588
+ h('div', {
2589
+ title: isBusy ? groups.map(g => g.groupName).join('、') : '',
2590
+ style: {
2591
+ fontSize: 11.5, padding: '3px 9px', borderRadius: 6, display: 'inline-block',
2592
+ alignSelf: 'flex-start', maxWidth: '100%',
2593
+ background: isBusy ? T.warnBg : T.okBg, color: isBusy ? T.warn : T.ok,
2594
+ ...clamp(1),
2595
+ },
2596
+ }, isBusy ? `${lang.profileOnProject}:${groups.map(g => g.groupName).join('、')}` : lang.profileAvailable),
2597
+ // ---- 简介(最多两行)----
2598
+ p.bio ? h('div', { title: p.bio, style: { fontSize: 12, color: T.textMuted, marginTop: 6, lineHeight: 1.5, ...clamp(2) } }, p.bio) : null,
2599
+ // ---- 项目经验(最多两条,超出省略)----
2600
+ (p.history && p.history.length > 0)
2601
+ ? h('div', { style: { marginTop: 10, paddingTop: 10, borderTop: `1px dashed ${T.border}`, fontSize: 11.5, color: T.textMuted, lineHeight: 1.5 } },
2602
+ h('div', { style: { fontSize: 10.5, fontWeight: 600, marginBottom: 4, letterSpacing: '0.4px' } }, lang.expHistory),
2603
+ p.history.slice(-1).map((h2, i) => h('div', { key: i, style: { ...clamp(2) } },
2604
+ `· ${h2.groupName}:${h2.title}`)),
2605
+ )
2606
+ : null,
2607
+ // ---- 操作行:始终贴底对齐(marginTop:auto 吃掉剩余空间)----
2608
+ h('div', {
2609
+ style: {
2610
+ display: 'flex', gap: 14, marginTop: 'auto', paddingTop: 10,
2611
+ },
2612
+ },
2613
+ h('button', {
2614
+ onClick: () => setEditProfile(p),
2615
+ style: { border: 'none', background: 'transparent', color: T.accent, cursor: 'pointer', fontSize: 12.5, padding: 0 },
2616
+ }, '编辑'),
2617
+ h('button', {
2618
+ onClick: () => remove(p),
2619
+ style: { border: 'none', background: 'transparent', color: T.danger, cursor: 'pointer', fontSize: 12.5, padding: 0 },
2620
+ }, lang.profileRemove),
2621
+ ),
2622
+ )
2623
+ }),
2624
+ ),
2625
+ ),
2626
+ // 新建智能体抽屉
2627
+ showCreateProfile ? h(CreateProfile, { lang, input, btn, act, api, wrap, drawer, setView, state, onDone: () => { onChanged(); setView('roster') } }) : null,
2628
+ // 编辑智能体抽屉
2629
+ // 编辑智能体抽屉(与群内头像入口同一个组件,带 基本信息 / Activity)
2630
+ editProfile ? h(AgentEditorDrawer, {
2631
+ key: keyOf(editProfile.id),
2632
+ view: {
2633
+ id: editProfile.id,
2634
+ profileId: editProfile.id,
2635
+ name: editProfile.name,
2636
+ roleId: editProfile.roleId,
2637
+ roleName: editProfile.roleName,
2638
+ bio: editProfile.bio,
2639
+ // 带上当前头像,编辑抽屉才能显示「现在用的是哪个」
2640
+ avatarData: editProfile.avatar || null,
2641
+ history: editProfile.history || [],
2642
+ groups: editProfile.groups || [],
2643
+ sessionId: editProfile.sessionId || '',
2644
+ sessionInfo: editProfile.sessionId ? {
2645
+ sessionId: editProfile.sessionId,
2646
+ cwd: editProfile.cwd || '',
2647
+ workspace: editProfile.workspace || '',
2648
+ title: editProfile.title || '',
2649
+ } : null,
2650
+ agentState: null,
2651
+ editable: true,
2652
+ },
2653
+ state, lang, input, btn, api, act, drawer,
2654
+ editName, setEditName,
2655
+ editRoleId, setEditRoleId,
2656
+ editBio, setEditBio,
2657
+ onClose: () => setEditProfile(null),
2658
+ onSaved: () => { onChanged(); setEditProfile(null) },
2659
+ onModelChanged: () => onChanged(),
2660
+ onAvatarChanged: () => onChanged(),
2661
+ }) : null,
2662
+ )
2663
+ }
2664
+
2665
+ // ---- 创建智能体(花名册,右侧抽屉) ----
2666
+ function CreateProfile({ lang, input, btn, act, api, wrap, drawer, setView, state, onDone }) {
2667
+ const [name, setName] = useState('')
2668
+ const [roleId, setRoleId] = useState('')
2669
+ const [bio, setBio] = useState('')
2670
+ const [sessionId, setSessionId] = useState('')
2671
+ const [workspace, setWorkspace] = useState('')
2672
+ const roles = (state && state.roles) || []
2673
+
2674
+ // 工作区列表(从 sessions 拿所有 cwd 去重)
2675
+ const sessions = sessionsRef.current
2676
+ const workspaces = []
2677
+ if (sessions && sessions.list) {
2678
+ const byId = sessions.list.getSnapshot().byId
2679
+ const seen = new Set()
2680
+ for (const id of Object.keys(byId)) {
2681
+ const row = byId[id]
2682
+ if (row && row.cwd && !seen.has(row.cwd)) {
2683
+ seen.add(row.cwd)
2684
+ workspaces.push({ id: row.cwd, name: row.cwd.split('/').pop() || row.cwd })
2685
+ }
2686
+ }
2687
+ }
2688
+ // 会话列表(当前工作区下的会话)
2689
+ const sessionList = []
2690
+ if (sessions && sessions.list && workspace) {
2691
+ const byId = sessions.list.getSnapshot().byId
2692
+ for (const id of Object.keys(byId)) {
2693
+ const row = byId[id]
2694
+ if (row && row.cwd === workspace) {
2695
+ sessionList.push({ id, title: row.displayTitle || id })
2696
+ }
2697
+ }
2698
+ }
2699
+
2700
+ const submit = () => act(async () => {
2701
+ const r = await api('/profiles', {
2702
+ method: 'POST',
2703
+ headers: { 'content-type': 'application/json' },
2704
+ body: JSON.stringify({
2705
+ name, roleId, bio,
2706
+ sessionId: sessionId || undefined,
2707
+ // 用户选的工作区要一起提交:后端建会话时按它设 cwd,
2708
+ // 否则会落到插件进程目录,用户看到的就是「没按我选的来」
2709
+ workspace: workspace || undefined,
2710
+ }),
2711
+ })
2712
+ onDone(r.profileId)
2713
+ })
2714
+
2715
+ return drawer(lang.newProfile,
2716
+ h('div', null,
2717
+ h('div', null,
2718
+ field(lang.profileName, input(name, setName, lang.profileName)),
2719
+ h('div', { style: { marginBottom: 16 } },
2720
+ h('div', { style: { fontSize: 13, color: T.textMuted, marginBottom: 6, fontWeight: 500 } }, lang.profileRole),
2721
+ h('select', {
2722
+ value: roleId,
2723
+ onChange: (e) => setRoleId(e.target.value),
2724
+ style: {
2725
+ width: '100%', boxSizing: 'border-box', padding: '11px 16px',
2726
+ border: `1.5px solid ${T.border}`, borderRadius: 12, fontSize: 14,
2727
+ color: T.text, background: T.bg, fontFamily: 'inherit',
2728
+ transition: 'all .15s ease',
2729
+ },
2730
+ },
2731
+ h('option', { value: '' }, '(选择角色)'),
2732
+ roles.map(r => h('option', { key: r.id, value: r.id }, r.name)),
2733
+ ),
2734
+ ),
2735
+ // 角色说明
2736
+ (roleId && (state.roles || []).find(r => r.id === roleId))
2737
+ ? h('div', {
2738
+ style: { padding: '10px 12px', borderRadius: 10, background: T.bg, fontSize: 12.5, color: T.textMuted, marginBottom: 16, border: `1px solid ${T.border}` },
2739
+ },
2740
+ (state.roles.find(r => r.id === roleId).persona || '').slice(0, 140))
2741
+ : null,
2742
+ field(lang.profileBio, input(bio, setBio, lang.profileBio, 2)),
2743
+ // 工作区选择
2744
+ h('div', { style: { marginBottom: 16 } },
2745
+ h('div', { style: { fontSize: 13, color: T.textMuted, marginBottom: 6, fontWeight: 500 } }, '工作区'),
2746
+ h('select', {
2747
+ value: workspace,
2748
+ onChange: (e) => { setWorkspace(e.target.value); setSessionId('') },
2749
+ style: {
2750
+ width: '100%', boxSizing: 'border-box', padding: '11px 16px',
2751
+ border: `1.5px solid ${T.border}`, borderRadius: 12, fontSize: 14,
2752
+ color: T.text, background: T.bg, fontFamily: 'inherit',
2753
+ },
2754
+ },
2755
+ h('option', { value: '' }, '(选择工作区)'),
2756
+ workspaces.map(w => h('option', { key: w.id, value: w.id }, w.name)),
2757
+ ),
2758
+ ),
2759
+ // 会话选择(联动)
2760
+ workspace ? h('div', { style: { marginBottom: 16 } },
2761
+ h('div', { style: { fontSize: 13, color: T.textMuted, marginBottom: 6, fontWeight: 500 } }, '会话'),
2762
+ h('select', {
2763
+ value: sessionId,
2764
+ onChange: (e) => setSessionId(e.target.value),
2765
+ style: {
2766
+ width: '100%', boxSizing: 'border-box', padding: '11px 16px',
2767
+ border: `1.5px solid ${T.border}`, borderRadius: 12, fontSize: 14,
2768
+ color: T.text, background: T.bg, fontFamily: 'inherit',
2769
+ },
2770
+ },
2771
+ h('option', { value: '' }, '(自动新建会话)'),
2772
+ sessionList.map(s => h('option', { key: s.id, value: s.id }, s.title)),
2773
+ ),
2774
+ h('div', { style: { fontSize: 12, color: T.textMuted, marginTop: 4 } }, '选择工作区后,下方列出该工作区的会话;留空则自动创建新会话'),
2775
+ ) : null,
2776
+ ),
2777
+ h('div', null,
2778
+ btn(lang.cancel, () => setView('roster'), 'ghost'),
2779
+ btn(lang.profileCreate, submit),
2780
+ ),
2781
+ () => setView('roster'),
2782
+ ),
2783
+ )
2784
+ }
2785
+
2786
+ // 安全 key:React 会对 key 做字符串化,传 Symbol/对象会抛
2787
+ // "Cannot convert a Symbol value to a string"。所有 key 都经过这里。
2788
+ function keyOf(v, fallback) {
2789
+ if (v === null || v === undefined || v === '') return fallback === undefined ? 'k' : String(fallback)
2790
+ const t = typeof v
2791
+ if (t === 'string' || t === 'number') return String(v)
2792
+ if (t === 'symbol' || t === 'object' || t === 'function') return fallback === undefined ? 'k' : String(fallback)
2793
+ return String(v)
2794
+ }
2795
+
2796
+ // 分组卡片:把一组字段收进一张带边框的卡里
2797
+ // 接受任意个子元素(不是 style!)。旧签名 (children, style) 在调用方传多个子元素时,
2798
+ // 第二个元素会被当成 style 展开,把 React 元素的 $$typeof(Symbol) 混进 style,
2799
+ // 触发 "Cannot convert a Symbol value to a string" 让整个抽屉白屏。
2800
+ function groupCard(...children) {
2801
+ return h('div', {
2802
+ style: {
2803
+ background: T.card, border: `1px solid ${T.border}`, borderRadius: 10,
2804
+ padding: '10px 12px',
2805
+ },
2806
+ }, children)
2807
+ }
2808
+
2809
+ // 紧凑字段:label 左、控件右的单行布局
2810
+ function inlineField(label, control) {
2811
+ return h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, minHeight: 30 } },
2812
+ h('span', { style: { fontSize: 12, color: T.textMuted, minWidth: 48, flexShrink: 0 } }, label),
2813
+ h('div', { style: { flex: 1, minWidth: 0 } }, control),
2814
+ )
2815
+ }
2816
+
2817
+ // ---- 统一的 Agent 编辑器(带 Tab) ----
2818
+ // 群内头像点击 与 花名册编辑 共用此组件,Tab:基本信息 / Activity
2819
+ function AgentEditorDrawer({
2820
+ view, state, lang, input, btn, api, drawer, act,
2821
+ editName, setEditName, editRoleId, setEditRoleId, editBio, setEditBio,
2822
+ onClose, onSaved, onModelChanged, onAvatarChanged,
2823
+ }) {
2824
+ // 注意:不能在 useState 之前做条件 return(会违反 Hooks 规则导致崩溃)。
2825
+ // 这里先把可能缺失的 view 归一成一个安全对象,渲染阶段再判断。
2826
+ const v = view || { name: '', roleId: '', roleName: '', bio: '', history: [], groups: [], sessionId: '', sessionInfo: null, agentState: null, editable: false }
2827
+ const [tab, setTab] = useState('basic') // 'basic' | 'activity'
2828
+
2829
+ // ---- 模型(仅会话可用时才显示) ----
2830
+ const [catalog, setCatalog] = useState(null)
2831
+ const [catalogError, setCatalogError] = useState(null)
2832
+ const [current, setCurrent] = useState(null)
2833
+ const [selProvider, setSelProvider] = useState('')
2834
+ const [selModel, setSelModel] = useState('')
2835
+ const [switching, setSwitching] = useState(false)
2836
+ const [switchMsg, setSwitchMsg] = useState(null)
2837
+
2838
+ // ---- Activity ----
2839
+ const [activity, setActivity] = useState(null)
2840
+ const [activityError, setActivityError] = useState(null)
2841
+ const [activityLoading, setActivityLoading] = useState(false)
2842
+ const [liveState, setLiveState] = useState(null)
2843
+
2844
+ // ---- 头像编辑:emoji 内置选择 或 上传图片(64x64 压平为 data-url) ----
2845
+ // null = 用默认(名字首字);{ kind:'emoji'|'image' } = 自定义
2846
+ const [editAvatar, setEditAvatar] = useState(view && view.avatarData ? view.avatarData : null)
2847
+ const BUILTIN_AVATARS = ['🤖', '🧑‍💻', '🧪', '📋', '🎨', '🧭', '🦉', '🦊', '🐼', '🐯', '🦁', '🐸', '🐙', '🦄', '🛠️', '🚀']
2848
+ const fileInputRef = useRef(null)
2849
+ // 头像选中即保存(不用等「保存」按钮):预览先变,随后落库
2850
+ const [avatarSaved, setAvatarSaved] = useState('')
2851
+ const persistAvatar = (av) => {
2852
+ setEditAvatar(av)
2853
+ if (!(view && view.editable && view.id)) return
2854
+ ;(async () => {
2855
+ try {
2856
+ await api(`/profiles/${view.id}`, {
2857
+ method: 'PUT',
2858
+ headers: { 'content-type': 'application/json' },
2859
+ body: JSON.stringify({ avatar: av }),
2860
+ })
2861
+ setAvatarSaved('已保存')
2862
+ if (typeof onAvatarChanged === 'function') onAvatarChanged()
2863
+ } catch (e) {
2864
+ setAvatarSaved('保存失败:' + (e && e.message ? e.message : '未知错误'))
2865
+ } finally {
2866
+ setTimeout(() => setAvatarSaved(''), 2000)
2867
+ }
2868
+ })()
2869
+ }
2870
+ const [uploadErr, setUploadErr] = useState('')
2871
+ const handleUpload = (file) => {
2872
+ setUploadErr('')
2873
+ if (!file) return
2874
+ if (!file.type.startsWith('image/')) { setUploadErr('只支持图片文件'); return }
2875
+ const reader = new FileReader()
2876
+ reader.onload = () => {
2877
+ const img = new Image()
2878
+ img.onload = () => {
2879
+ const S = 64
2880
+ const cvs = document.createElement('canvas')
2881
+ cvs.width = S; cvs.height = S
2882
+ const ctx2 = cvs.getContext('2d')
2883
+ // 居中裁方形
2884
+ const side = Math.min(img.width, img.height)
2885
+ ctx2.drawImage(img, (img.width - side) / 2, (img.height - side) / 2, side, side, 0, 0, S, S)
2886
+ persistAvatar({ kind: 'image', dataUrl: cvs.toDataURL('image/png') })
2887
+ }
2888
+ img.onerror = () => setUploadErr('图片无法解析')
2889
+ img.src = reader.result
2890
+ }
2891
+ reader.readAsDataURL(file)
2892
+ }
2893
+
2894
+ const sessionId = view.sessionId || ''
2895
+ const info = view.sessionInfo || null
2896
+
2897
+ // 拉 Activity(切到该 Tab 或点刷新时)
2898
+ const loadActivity = useCallback(async () => {
2899
+ if (!sessionId) return
2900
+ setActivityLoading(true)
2901
+ setActivityError(null)
2902
+ try {
2903
+ const r = await api(`/activity?sessionId=${encodeURIComponent(sessionId)}`)
2904
+ setActivity(r.activity || [])
2905
+ setLiveState(r.state || null)
2906
+ } catch (e) {
2907
+ setActivityError(e.message || '读取工作日志失败')
2908
+ } finally {
2909
+ setActivityLoading(false)
2910
+ }
2911
+ }, [sessionId, api])
2912
+
2913
+ // 切到 Activity Tab 时自动加载,并且每 2 秒刷新(agent 正在干活时能实时看到)
2914
+ useEffect(() => {
2915
+ if (tab !== 'activity' || !sessionId) return
2916
+ let cancelled = false
2917
+ loadActivity()
2918
+ const timer = setInterval(() => { if (!cancelled) loadActivity() }, 2000)
2919
+ return () => { cancelled = true; clearInterval(timer) }
2920
+ }, [tab, sessionId, loadActivity])
2921
+
2922
+ // 拉模型目录 + 当前模型
2923
+ useEffect(() => {
2924
+ if (tab !== 'basic' || !sessionId) return
2925
+ let cancelled = false
2926
+ ;(async () => {
2927
+ try {
2928
+ const r = await api(`/models?sessionId=${encodeURIComponent(sessionId)}`)
2929
+ if (cancelled) return
2930
+ setCatalog(r.catalog || [])
2931
+ const cur = r.current || null
2932
+ setCurrent(cur)
2933
+ if (cur) {
2934
+ setSelProvider(cur.provider || '')
2935
+ setSelModel(cur.model || '')
2936
+ } else if ((r.catalog || []).length > 0) {
2937
+ const first = r.catalog[0]
2938
+ setSelProvider(first.id)
2939
+ setSelModel(first.models && first.models[0] ? first.models[0].id : '')
2940
+ }
2941
+ } catch (e) {
2942
+ if (!cancelled) setCatalogError(e.message || '读取模型目录失败')
2943
+ }
2944
+ })()
2945
+ return () => { cancelled = true }
2946
+ }, [tab, sessionId, api])
2947
+
2948
+ const providerEntry = (catalog || []).find(p => p.id === selProvider)
2949
+ const modelOptions = providerEntry ? providerEntry.models : []
2950
+
2951
+ const applyModel = () => {
2952
+ if (!sessionId || !selProvider || !selModel) return
2953
+ setSwitching(true)
2954
+ setSwitchMsg(null)
2955
+ ;(async () => {
2956
+ try {
2957
+ const r = await api(`/sessions/${encodeURIComponent(sessionId)}/model`, {
2958
+ method: 'POST',
2959
+ headers: { 'content-type': 'application/json' },
2960
+ body: JSON.stringify({ provider: selProvider, model: selModel }),
2961
+ })
2962
+ setCurrent(r.current || { provider: selProvider, model: selModel })
2963
+ setSwitchMsg({ ok: true, text: lang.modelSaved })
2964
+ if (onModelChanged) onModelChanged()
2965
+ } catch (e) {
2966
+ setSwitchMsg({ ok: false, text: e.message || '切换失败' })
2967
+ } finally {
2968
+ setSwitching(false)
2969
+ }
2970
+ })()
2971
+ }
2972
+
2973
+ // ---- Tab 头 ----
2974
+ const tabHeader = h('div', {
2975
+ style: {
2976
+ display: 'flex', gap: 18, borderBottom: `1px solid ${T.border}`,
2977
+ padding: '0 16px', background: T.card, flexShrink: 0,
2978
+ },
2979
+ },
2980
+ tabLink(lang.tabBasic, tab === 'basic', () => setTab('basic'), 'basic', 'sm'),
2981
+ tabLink(lang.tabActivity, tab === 'activity', () => setTab('activity'), 'activity', 'sm'),
2982
+ )
2983
+
2984
+ // ---- 基本信息 Tab ----
2985
+ const basicBody = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } },
2986
+
2987
+ // ===== 顶部身份条:头像 + 名字角色 + 实时状态(一行内聚)=====
2988
+ groupCard(
2989
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
2990
+ avatar(view.name, view.roleId, 40, view.agentState, view.avatarData),
2991
+ h('div', { style: { minWidth: 0, flex: 1 } },
2992
+ h('div', { style: { fontSize: 14, fontWeight: 600, lineHeight: 1.3 } }, view.name),
2993
+ h('div', { style: { fontSize: 11.5, color: T.accent, lineHeight: 1.4 } }, view.roleName || view.roleId || '—'),
2994
+ ),
2995
+ // 状态靠右,和身份信息同一行
2996
+ view.agentState
2997
+ ? h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2, flexShrink: 0 } },
2998
+ statePill(view.agentState),
2999
+ view.agentState.since
3000
+ ? h('span', { style: { fontSize: 10, color: T.textMuted } }, fmtTime(view.agentState.since))
3001
+ : null,
3002
+ )
3003
+ : null,
3004
+ ),
3005
+ ),
3006
+
3007
+ // ===== 可编辑资料 =====
3008
+ // 不再单独加标题:Tab 名已经叫「基本信息」,重复一遍是冗余。
3009
+ h('div', null,
3010
+ groupCard(
3011
+ view.editable
3012
+ ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
3013
+ inlineField(lang.profileName, input(editName, setEditName, lang.profileName, undefined, undefined, true)),
3014
+ inlineField(lang.profileRole,
3015
+ h('select', {
3016
+ value: editRoleId,
3017
+ onChange: (e) => setEditRoleId(e.target.value),
3018
+ style: {
3019
+ width: '100%', boxSizing: 'border-box', padding: '6px 10px',
3020
+ border: `1px solid ${T.border}`, borderRadius: 8, fontSize: 12.5,
3021
+ color: T.text, background: T.card, fontFamily: 'inherit',
3022
+ },
3023
+ },
3024
+ h('option', { value: '' }, '(选择角色)'),
3025
+ (state.roles || []).map(r => h('option', { key: r.id, value: r.id }, r.name)),
3026
+ ),
3027
+ ),
3028
+ // 角色说明:和角色选择紧贴,不再单独占一段
3029
+ (editRoleId && (state.roles || []).find(r => r.id === editRoleId))
3030
+ ? h('div', {
3031
+ style: {
3032
+ padding: '6px 10px', borderRadius: 8, background: T.bg,
3033
+ fontSize: 11.5, color: T.textMuted, lineHeight: 1.5,
3034
+ border: `1px solid ${T.border}`,
3035
+ },
3036
+ },
3037
+ (state.roles.find(r => r.id === editRoleId).persona || '').slice(0, 120))
3038
+ : null,
3039
+ // 简介:label 在上,textarea 紧凑
3040
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
3041
+ h('span', { style: { fontSize: 12, color: T.textMuted } }, lang.profileBio),
3042
+ input(editBio, setEditBio, lang.profileBio, 2, undefined, true),
3043
+ ),
3044
+ // ===== 头像:内置 emoji 选择 + 上传自定义图片 =====
3045
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
3046
+ h('span', { style: { fontSize: 12, color: T.textMuted } }, lang.profileAvatar || '头像'),
3047
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
3048
+ // 当前预览
3049
+ avatar(view.name, view.roleId, 44, null, editAvatar),
3050
+ h('div', { style: { display: 'flex', gap: 6 } },
3051
+ btn('上传图片', () => fileInputRef.current && fileInputRef.current.click(), 'ghost', 'sm'),
3052
+ editAvatar
3053
+ ? btn('恢复默认', () => persistAvatar(null), 'ghost', 'sm')
3054
+ : null,
3055
+ avatarSaved
3056
+ ? h('span', { style: { fontSize: 11, color: avatarSaved.startsWith('保存失败') ? T.danger : T.ok } }, avatarSaved)
3057
+ : null,
3058
+ ),
3059
+ ),
3060
+ h('input', {
3061
+ ref: fileInputRef, type: 'file', accept: 'image/*',
3062
+ style: { display: 'none' },
3063
+ onChange: (e) => { handleUpload(e.target.files && e.target.files[0]); e.target.value = '' },
3064
+ }),
3065
+ uploadErr ? h('div', { style: { fontSize: 11, color: T.danger } }, uploadErr) : null,
3066
+ // 内置 emoji 网格
3067
+ h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 2 } },
3068
+ BUILTIN_AVATARS.map(emo =>
3069
+ h('button', {
3070
+ key: emo,
3071
+ onClick: () => persistAvatar({ kind: 'emoji', value: emo }),
3072
+ title: emo,
3073
+ style: {
3074
+ width: 32, height: 32, borderRadius: 8, cursor: 'pointer', fontSize: 17,
3075
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
3076
+ background: T.bg, transition: 'all .12s',
3077
+ border: editAvatar && editAvatar.kind === 'emoji' && editAvatar.value === emo
3078
+ ? `2px solid ${T.accent}` : `1px solid ${T.border}`,
3079
+ },
3080
+ }, emo),
3081
+ ),
3082
+ ),
3083
+ ),
3084
+ )
3085
+ : h('div', { style: { fontSize: 12, color: T.textMuted } }, lang.noProfileBound),
3086
+ ),
3087
+ ),
3088
+
3089
+ // ===== 工作区 / 会话 / 模型:三组只读信息合并为一张卡片,用分隔线区隔 =====
3090
+ h('div', null,
3091
+ sectionTitle(lang.secSession),
3092
+ groupCard(
3093
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
3094
+ // 工作区 + 路径合成两行,紧凑
3095
+ infoRow(lang.workspaceLabel, info ? info.workspace : '') ||
3096
+ h('div', { style: { fontSize: 12, color: T.textMuted } }, '—'),
3097
+ infoRow('', info ? info.cwd : '', true),
3098
+ infoRow(lang.sessionLabel, info ? (info.title || '') : ''),
3099
+ infoRow(lang.sessionIdLabel, sessionId, true),
3100
+ ),
3101
+
3102
+ // 模型区:用分隔线接在同一张卡里,删掉独立大标题
3103
+ sessionId ? h('div', {
3104
+ style: { marginTop: 8, paddingTop: 8, borderTop: `1px dashed ${T.border}`, display: 'flex', flexDirection: 'column', gap: 6 },
3105
+ },
3106
+ // 当前模型一行展示
3107
+ h('div', { style: { display: 'flex', alignItems: 'baseline', gap: 8, fontSize: 12, minWidth: 0 } },
3108
+ h('span', { style: { color: T.textMuted, minWidth: 48, flexShrink: 0 } }, lang.modelCurrent),
3109
+ current
3110
+ ? h('span', { style: { fontWeight: 600, minWidth: 0, wordBreak: 'break-all' } },
3111
+ `${current.provider} / ${current.model}`,
3112
+ current.inherited
3113
+ ? h('span', { style: { fontWeight: 400, fontSize: 10, color: T.textMuted, marginLeft: 4 } }, lang.modelInherit)
3114
+ : null,
3115
+ )
3116
+ : h('span', { style: { color: T.textMuted } }, '—'),
3117
+ ),
3118
+ // 切换器:两列并排 + 按钮,省掉三行
3119
+ catalogError
3120
+ ? h('div', { style: { fontSize: 11.5, color: T.danger } }, catalogError)
3121
+ : !catalog
3122
+ ? h('div', { style: { fontSize: 11.5, color: T.textMuted } }, lang.loading)
3123
+ : catalog.length === 0
3124
+ ? h('div', { style: { fontSize: 11.5, color: T.textMuted } }, '没有可用的模型')
3125
+ : h('div', { style: { display: 'flex', gap: 6, alignItems: 'center' } },
3126
+ h('select', {
3127
+ value: selProvider,
3128
+ onChange: (e) => {
3129
+ const pid = e.target.value
3130
+ setSelProvider(pid)
3131
+ const entry = (catalog || []).find(p => p.id === pid)
3132
+ setSelModel(entry && entry.models[0] ? entry.models[0].id : '')
3133
+ setSwitchMsg(null)
3134
+ },
3135
+ title: lang.modelProvider,
3136
+ style: {
3137
+ flex: '0 0 38%', minWidth: 0, boxSizing: 'border-box', padding: '6px 8px',
3138
+ border: `1px solid ${T.border}`, borderRadius: 8, fontSize: 12,
3139
+ color: T.text, background: T.card, fontFamily: 'inherit',
3140
+ },
3141
+ }, (catalog || []).map(p => h('option', { key: p.id, value: p.id }, p.name))),
3142
+ h('select', {
3143
+ value: selModel,
3144
+ onChange: (e) => { setSelModel(e.target.value); setSwitchMsg(null) },
3145
+ title: lang.modelName,
3146
+ style: {
3147
+ flex: '1 1 auto', minWidth: 0, boxSizing: 'border-box', padding: '6px 8px',
3148
+ border: `1px solid ${T.border}`, borderRadius: 8, fontSize: 12,
3149
+ color: T.text, background: T.card, fontFamily: 'inherit',
3150
+ },
3151
+ },
3152
+ modelOptions.length === 0
3153
+ ? h('option', { value: '' }, '(无可选模型)')
3154
+ : modelOptions.map(m => h('option', { key: m.id, value: m.id }, m.name || m.id)),
3155
+ ),
3156
+ h('button', {
3157
+ onClick: applyModel,
3158
+ disabled: switching || !selProvider || !selModel,
3159
+ style: {
3160
+ flexShrink: 0, padding: '6px 12px', borderRadius: 8, border: 'none',
3161
+ background: (switching || !selProvider || !selModel) ? T.border : T.accent,
3162
+ color: '#fff', fontSize: 12, fontWeight: 500,
3163
+ cursor: (switching || !selProvider || !selModel) ? 'not-allowed' : 'pointer',
3164
+ },
3165
+ }, switching ? '…' : lang.modelApply),
3166
+ ),
3167
+ switchMsg
3168
+ ? h('div', { style: { fontSize: 11.5, color: switchMsg.ok ? T.ok : T.danger } }, switchMsg.text)
3169
+ : null,
3170
+ ) : null,
3171
+
3172
+ // 只读说明并进卡片底部,不再单独一行占位
3173
+ h('div', { style: { marginTop: 8, fontSize: 10.5, color: T.textMuted, lineHeight: 1.45 } }, lang.readonlyNote),
3174
+ ),
3175
+ ),
3176
+
3177
+ // ===== 项目经验:无内容时不渲染整块,避免空白 =====
3178
+ (view.history || []).length > 0
3179
+ ? h('div', null,
3180
+ sectionTitle(lang.expHistory),
3181
+ groupCard(
3182
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
3183
+ view.history.map((h2, i) => h('div', { key: i, style: { fontSize: 11.5, color: T.textMuted, lineHeight: 1.5 } },
3184
+ h('span', { style: { fontWeight: 600, color: T.text } }, h2.groupName),
3185
+ h('span', null, ' · ' + h2.title + (h2.summary ? '(' + h2.summary + ')' : '')),
3186
+ )),
3187
+ ),
3188
+ ),
3189
+ )
3190
+ : null,
3191
+ )
3192
+
3193
+
3194
+ // ---- Activity Tab ----
3195
+ const activityKindMeta = {
3196
+ received: { label: lang.activityKindReceived, color: '#B7791F', bg: 'rgba(183,121,31,0.12)' },
3197
+ thinking: { label: lang.activityKindThinking, color: '#8A5A12', bg: 'rgba(214,158,46,0.12)' },
3198
+ streaming: { label: lang.activityKindStreaming, color: '#2E6BE6', bg: 'rgba(46,107,230,0.1)' },
3199
+ tool: { label: lang.activityKindTool, color: '#764ba2', bg: 'rgba(118,75,162,0.1)' },
3200
+ 'tool-result': { label: lang.activityKindToolResult, color: '#5B6470', bg: 'rgba(91,100,112,0.09)' },
3201
+ waiting: { label: lang.activityKindWaiting, color: '#C0392B', bg: 'rgba(192,57,43,0.1)' },
3202
+ message: { label: lang.activityKindMessage, color: '#1E7D46', bg: 'rgba(30,125,70,0.1)' },
3203
+ idle: { label: lang.activityKindIdle, color: '#8A94A6', bg: 'rgba(138,148,166,0.1)' },
3204
+ info: { label: lang.activityKindInfo, color: '#5B6470', bg: 'rgba(91,100,112,0.08)' },
3205
+ }
3206
+
3207
+ const activityBody = (() => {
3208
+ if (!sessionId) {
3209
+ return h('div', { style: { fontSize: 12.5, color: T.textMuted, padding: '20px 0' } }, lang.noProfileBound)
3210
+ }
3211
+ return h('div', null,
3212
+ // 顶部:当前状态 + 刷新
3213
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8, gap: 8 } },
3214
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, minWidth: 0, flexWrap: 'wrap' } },
3215
+ h('span', { style: { fontSize: 11, color: T.textMuted } }, lang.secState),
3216
+ statePill(liveState || view.agentState),
3217
+ ),
3218
+ h('button', {
3219
+ onClick: loadActivity,
3220
+ disabled: activityLoading,
3221
+ style: {
3222
+ border: `1px solid ${T.border}`, background: T.card, color: T.accent,
3223
+ borderRadius: 8, padding: '4px 10px', fontSize: 11.5,
3224
+ cursor: activityLoading ? 'default' : 'pointer', flexShrink: 0,
3225
+ opacity: activityLoading ? 0.6 : 1,
3226
+ },
3227
+ }, activityLoading ? '…' : lang.activityRefresh),
3228
+ ),
3229
+ h('div', { style: { fontSize: 10.5, color: T.textMuted, lineHeight: 1.45, marginBottom: 10 } }, lang.activityHint),
3230
+
3231
+ activityError
3232
+ ? h('div', { style: { fontSize: 12, color: T.danger } }, activityError)
3233
+ : activity === null
3234
+ ? h('div', { style: { fontSize: 12, color: T.textMuted } }, lang.activityLoading)
3235
+ : activity.length === 0
3236
+ ? h('div', { style: { fontSize: 12, color: T.textMuted, padding: '16px 0', textAlign: 'center' } }, lang.activityEmpty)
3237
+ : h('div', { style: { position: 'relative', paddingLeft: 16 } },
3238
+ // 时间轴竖线
3239
+ h('div', {
3240
+ style: {
3241
+ position: 'absolute', left: 3, top: 4, bottom: 4, width: 1.5,
3242
+ background: T.border, borderRadius: 1,
3243
+ },
3244
+ }),
3245
+ // 最新的排在最上面
3246
+ activity.slice().reverse().map((a, i) => {
3247
+ const meta = activityKindMeta[a.kind] || activityKindMeta.info
3248
+ return h('div', { key: a.id || i, style: { position: 'relative', marginBottom: 10 } },
3249
+ // 时间轴圆点
3250
+ h('span', {
3251
+ style: {
3252
+ position: 'absolute', left: -16, top: 5, width: 7, height: 7,
3253
+ borderRadius: '50%', background: meta.color,
3254
+ boxShadow: `0 0 0 2px ${T.card}`, border: `1.5px solid ${T.card}`,
3255
+ },
3256
+ }),
3257
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2, flexWrap: 'wrap' } },
3258
+ h('span', {
3259
+ style: {
3260
+ fontSize: 10, padding: '1px 7px', borderRadius: 999,
3261
+ background: meta.bg, color: meta.color, fontWeight: 600, whiteSpace: 'nowrap',
3262
+ },
3263
+ }, meta.label),
3264
+ h('span', { style: { fontSize: 12, fontWeight: 500, color: T.text } }, a.title),
3265
+ h('span', { style: { fontSize: 10.5, color: T.textMuted, marginLeft: 'auto', flexShrink: 0 } }, fmtTime(a.ts)),
3266
+ ),
3267
+ a.detail
3268
+ ? h('div', {
3269
+ style: {
3270
+ fontSize: 11, color: T.textMuted, lineHeight: 1.5, marginTop: 2,
3271
+ fontFamily: a.kind === 'tool' || a.kind === 'tool-result' ? 'ui-monospace, SFMono-Regular, Menlo, monospace' : 'inherit',
3272
+ whiteSpace: 'pre-wrap', wordBreak: 'break-word',
3273
+ background: T.bg, borderRadius: 6, padding: '5px 7px',
3274
+ // 工具返回可能很长,限制高度避免撑爆面板
3275
+ maxHeight: 160, overflowY: 'auto',
3276
+ },
3277
+ }, a.detail)
3278
+ : null,
3279
+ )
3280
+ }),
3281
+ ),
3282
+ )
3283
+ })()
3284
+
3285
+ // 注意:drawer 的内容容器是普通块级(flex:1 + overflow:auto),没有确定高度,
3286
+ // 所以这里不能用 height:100% —— 那会让整个抽屉高度塌成 0,表现为点开一片空白。
3287
+ // 改用负 margin 贴边 + 自身 flex 布局(不依赖父级高度)。
3288
+ return drawer(view.name,
3289
+ h('div', { style: { display: 'flex', flexDirection: 'column', minHeight: '100%', margin: '-16px' } },
3290
+ tabHeader,
3291
+ h('div', { style: { flex: '1 0 auto', padding: '14px' } },
3292
+ tab === 'basic' ? basicBody : activityBody,
3293
+ ),
3294
+ ),
3295
+ h('div', null,
3296
+ btn(lang.cancel, onClose, 'ghost'),
3297
+ view.editable
3298
+ ? btn(lang.profileSave, () => {
3299
+ act(async () => {
3300
+ await api(`/profiles/${view.id}`, {
3301
+ method: 'PUT',
3302
+ headers: { 'content-type': 'application/json' },
3303
+ body: JSON.stringify({ name: editName, roleId: editRoleId, bio: editBio, avatar: editAvatar }),
3304
+ })
3305
+ onSaved()
3306
+ })()
3307
+ })
3308
+ : null,
3309
+ ),
3310
+ onClose,
3311
+ )
3312
+ }
3313
+
3314
+ // ---- 侧栏图标(带未读角标) ----
3315
+ function GroupchatIcon() {
3316
+ const [unread, setUnread] = useState(0)
3317
+ useEffect(() => {
3318
+ const unsubscribe = unreadStore.subscribe(() => setUnread(unreadStore.get()))
3319
+ setUnread(unreadStore.get())
3320
+ return unsubscribe
3321
+ }, [])
3322
+ return h('div', { style: { position: 'relative', width: 18, height: 18 } },
3323
+ h('svg', { width: 18, height: 18, viewBox: '0 0 18 18', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' },
3324
+ h('circle', { cx: 6, cy: 8, r: 2.4 }),
3325
+ h('circle', { cx: 12, cy: 8, r: 2.4 }),
3326
+ h('path', { d: 'M2.5 15c0-2 1.4-3.4 3.5-3.4h1.6M15.5 15c0-2-1.4-3.4-3.5-3.4h-1.6' }),
3327
+ ),
3328
+ unread > 0 ? h('span', {
3329
+ style: {
3330
+ position: 'absolute', top: -2, right: -2, minWidth: 14, height: 14,
3331
+ borderRadius: '50%', background: '#C0392B', color: '#fff',
3332
+ fontSize: 8, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
3333
+ padding: '0 3px', border: '2px solid #fff',
3334
+ },
3335
+ }, unread > 99 ? '99+' : unread) : null,
3336
+ )
3337
+ }
3338
+
3339
+ function apply(ctx) {
3340
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'groupchat: dictionaries')
3341
+ sessionsRef.current = ctx.sessions
3342
+ layoutRef.current = ctx.layout || null
3343
+
3344
+ // 状态点的呼吸动画(agent 正在工作时)
3345
+ ctx.effect(() => {
3346
+ const style = document.createElement('style')
3347
+ style.dataset.groupchat = 'animations'
3348
+ style.textContent = `
3349
+ @keyframes groupchatPulse {
3350
+ 0%, 100% { opacity: 1; transform: scale(1); }
3351
+ 50% { opacity: .45; transform: scale(.82); }
3352
+ }
3353
+ @keyframes groupchatRing {
3354
+ 0%, 100% { filter: brightness(1); }
3355
+ 50% { filter: brightness(1.3); }
3356
+ }
3357
+ @keyframes groupchatSpin {
3358
+ from { transform: rotate(0deg); }
3359
+ to { transform: rotate(360deg); }
3360
+ }
3361
+ @keyframes slideIn {
3362
+ from { transform: translateX(100%); }
3363
+ to { transform: translateX(0); }
3364
+ }
3365
+ /* 卡片入场:轻微上浮 + 淡入(配合 animationDelay 做错峰) */
3366
+ @keyframes gcCardIn {
3367
+ from { opacity: 0; transform: translateY(10px) scale(.985); }
3368
+ to { opacity: 1; transform: translateY(0) scale(1); }
3369
+ }
3370
+ /* 视图切换:整块淡入 */
3371
+ @keyframes gcFadeIn {
3372
+ from { opacity: 0; transform: translateY(4px); }
3373
+ to { opacity: 1; transform: translateY(0); }
3374
+ }
3375
+ /* 未读数变化:弹一下 */
3376
+ @keyframes gcPop {
3377
+ 0% { transform: scale(.6); }
3378
+ 60% { transform: scale(1.18); }
3379
+ 100% { transform: scale(1); }
3380
+ }
3381
+ /* 新消息预览:闪一次背景,提示"刚更新" */
3382
+ @keyframes gcFlash {
3383
+ 0% { background: var(--dsw-alias-accent-soft, rgba(46,107,230,.12)); }
3384
+ 100% { background: transparent; }
3385
+ }
3386
+ .gc-card {
3387
+ transition: transform .2s cubic-bezier(0.22,1,0.36,1), box-shadow .2s ease, border-color .2s ease;
3388
+ will-change: transform;
3389
+ }
3390
+ .gc-card:hover { transform: translateY(-3px); }
3391
+ .gc-card:active { transform: translateY(-1px) scale(.996); }
3392
+ .gc-in { animation: gcCardIn .38s cubic-bezier(0.22,1,0.36,1) both; }
3393
+ .gc-fade { animation: gcFadeIn .26s ease both; }
3394
+ .gc-pop { animation: gcPop .32s cubic-bezier(0.22,1,0.36,1); }
3395
+ .gc-flash { animation: gcFlash .9s ease-out; }
3396
+ /* 通知卡片入场 + 倒计时进度 */
3397
+ @keyframes gcToastIn {
3398
+ from { opacity: 0; transform: translateX(26px) scale(.98); }
3399
+ to { opacity: 1; transform: translateX(0) scale(1); }
3400
+ }
3401
+ @keyframes gcToastBar {
3402
+ from { width: 100%; }
3403
+ to { width: 0%; }
3404
+ }
3405
+ .gc-toast { animation: gcToastIn .28s cubic-bezier(0.22,1,0.36,1) both; }
3406
+ .gc-toast-bar { animation: gcToastBar 5s linear forwards; }
3407
+ @media (prefers-reduced-motion: reduce) {
3408
+ .gc-card, .gc-in, .gc-fade, .gc-pop, .gc-flash, .gc-toast, .gc-toast-bar { animation: none !important; transition: none !important; }
3409
+ }
3410
+ `
3411
+ document.head.appendChild(style)
3412
+ return () => { try { style.remove() } catch (_e) { /* ignore */ } }
3413
+ }, 'groupchat: animations')
3414
+
3415
+ // 全局轮询:页面加载即开始,不依赖群聊面板是否打开
3416
+ ctx.effect(() => {
3417
+ globalPoll()
3418
+ globalPollTimer = setInterval(globalPoll, 2000)
3419
+ return () => { clearInterval(globalPollTimer); globalPollTimer = null }
3420
+ }, 'groupchat: global poll')
3421
+
3422
+ ctx.slots.inject('sidebar.panellist', () =>
3423
+ ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 30, label: () => '群聊', locale: NS }, GroupchatIcon),
3424
+ )
3425
+ ctx.slots.inject('main', function* () {
3426
+ yield ctx.slots.register({ name: 'main', key: PANEL_ID }, GroupchatPanel)
3427
+ })
3428
+ // 全局 toast:挂到 shell.overlay(根层,任何界面可见,不依赖群聊面板是否打开)
3429
+ ctx.slots.inject('shell.overlay', () =>
3430
+ ctx.slots.register({ name: 'shell.overlay', id: 'groupchat.toast', order: 50 }, ToastNotification),
3431
+ )
3432
+ }
3433
+
3434
+ return { inject: ['slots', 'locale', 'sessions', 'layout'], apply }
3435
+ },
3436
+ })