viewModels.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import { visibleMessageText, messageReasoningText } from '@shared/messageFiles'
  2. import { workspaceConversationTimestamp, workspaceHasUnread } from '@shared/workspace'
  3. import { toolResultFailed, toolStatus } from '@shared/chatTools'
  4. import { serverFilePath, serverFileUrl } from '@shared/serverFiles'
  5. import type {
  6. ApprovalRequest,
  7. ChatMessage,
  8. ClarificationRequest,
  9. ConversationArtifact,
  10. FileLibraryItem,
  11. GroupAgent,
  12. GroupInteraction,
  13. GroupMessage,
  14. GroupRoomDetail,
  15. GroupRoomSummary,
  16. SessionSummary,
  17. ToolCall,
  18. } from '@shared/types'
  19. import type { SidebarItem } from '@/components/app/types'
  20. import type { UiAgent, UiRoom } from '@/components/groups/types'
  21. import type { UiLibraryItem } from '@/components/library/types'
  22. import type { UiInteraction, UiMessage, UiMessageAttachment, UiToolCall } from '@/components/messages/types'
  23. import { normalizeAssistantMediaMarkdown } from '@/utils/mediaMarkdown'
  24. import { formatMessageTime, formatConversationTime } from '@/utils/messageTime'
  25. function record(value: unknown): Record<string, unknown> {
  26. return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
  27. }
  28. function string(value: unknown, fallback = ''): string {
  29. return typeof value === 'string' ? value : fallback
  30. }
  31. function formatRelative(value: number): string {
  32. const ms = value < 10_000_000_000 ? value * 1000 : value
  33. const diff = Date.now() - ms
  34. if (diff < 60_000) return '刚刚'
  35. if (diff < 3_600_000) return `${Math.max(1, Math.floor(diff / 60_000))} 分钟`
  36. if (diff < 86_400_000) return `${Math.max(1, Math.floor(diff / 3_600_000))} 小时`
  37. const date = new Date(ms)
  38. return `${date.getMonth() + 1}/${date.getDate()}`
  39. }
  40. function historySection(value: number, pinned = false): string | undefined {
  41. if (pinned) return '已置顶'
  42. const ms = value < 10_000_000_000 ? value * 1000 : value
  43. const today = new Date()
  44. today.setHours(0, 0, 0, 0)
  45. const yesterday = new Date(today)
  46. yesterday.setDate(yesterday.getDate() - 1)
  47. if (ms >= today.getTime()) return '今天'
  48. if (ms >= yesterday.getTime()) return '昨天'
  49. return '更早'
  50. }
  51. export function sessionSidebarItem(session: SessionSummary, unread = 0, agentName = ''): SidebarItem {
  52. return {
  53. id: session.id,
  54. title: session.title || '未命名会话',
  55. subtitle: session.preview || `${session.messageCount} 条消息`,
  56. meta: agentName || session.agent || formatRelative(session.updatedAt),
  57. section: historySection(session.updatedAt, session.pinned),
  58. icon: 'chat',
  59. pinned: session.pinned,
  60. unread,
  61. }
  62. }
  63. function toolToUi(tool: ToolCall): UiToolCall {
  64. const status: UiToolCall['status'] = tool.status === 'completed' ? 'success' : tool.status === 'failed' ? 'error' : tool.status
  65. return {
  66. id: tool.id,
  67. name: tool.name,
  68. status,
  69. input: tool.arguments,
  70. output: tool.error || tool.result || tool.preview,
  71. durationMs: tool.durationSeconds ? Math.round(tool.durationSeconds * 1000) : undefined,
  72. }
  73. }
  74. function toolResult(message: ChatMessage): unknown {
  75. const raw = record(message.raw)
  76. if (raw.result !== undefined) return raw.result
  77. if (raw.output !== undefined && typeof raw.output !== 'string') return raw.output
  78. try { return JSON.parse(message.content) } catch { return message.content || undefined }
  79. }
  80. function timelineMetadata(value: unknown): Record<string, unknown> | undefined {
  81. return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined
  82. }
  83. const CONTEXT_COMPACTION_PREFIX = '[context compaction'
  84. const BACKGROUND_PROCESS_NOTICE = /^\[IMPORTANT:\s*Background process\s+(\S+)\s+exited\s+\(exit code\s+(-?\d+)(?:,\s*([^)]+))?\)\.?\]?(?:\r?\n|$)/i
  85. function isContextCompactionMessage(message: ChatMessage): boolean {
  86. return message.content.trim().toLocaleLowerCase().startsWith(CONTEXT_COMPACTION_PREFIX)
  87. || message.displayKind?.toLocaleLowerCase().includes('compaction') === true
  88. }
  89. function backgroundProcessMetadata(content: string): Record<string, unknown> | undefined {
  90. const match = content.trim().match(BACKGROUND_PROCESS_NOTICE)
  91. if (!match) return undefined
  92. return {
  93. process_id: match[1],
  94. exit_code: Number(match[2]),
  95. ...(match[3]?.trim() ? { signal: match[3].trim() } : {}),
  96. }
  97. }
  98. function isSystemTimelineMessage(message: ChatMessage): boolean {
  99. return Boolean(message.displayKind)
  100. || /^\[system:/i.test(message.content.trim())
  101. || isContextCompactionMessage(message)
  102. || Boolean(backgroundProcessMetadata(message.content))
  103. }
  104. export function chatMessageToUi(message: ChatMessage, agentNameFor?: (profile?: string) => string | undefined): UiMessage {
  105. const attachments: UiMessageAttachment[] | undefined = message.attachments?.map(attachment => ({
  106. id: attachment.id,
  107. name: attachment.name,
  108. kind: attachment.kind === 'image' ? 'image' : 'file',
  109. url: serverFileUrl(attachment.url || attachment.path || '', message.profile) || attachment.url || attachment.path,
  110. size: attachment.size,
  111. }))
  112. return {
  113. id: message.id,
  114. role: message.role,
  115. author: message.role === 'assistant' ? agentNameFor?.(message.profile) || message.profile : undefined,
  116. content: message.role === 'assistant' ? visibleMessageText(message.content) : message.content,
  117. reasoning: message.role === 'assistant' ? messageReasoningText(message.content, message.reasoning) : message.reasoning,
  118. createdAt: message.timestamp < 10_000_000_000 ? message.timestamp * 1000 : message.timestamp,
  119. status: message.isStreaming ? 'streaming' : message.stage,
  120. error: message.error,
  121. attachments,
  122. // A later streaming string may replace an older structured body.
  123. contentParts: message.contentParts?.filter(part => 'text' in part).map(part => (part as { text: string }).text).filter(Boolean).join('\n\n') === message.content
  124. ? message.contentParts?.map(part => 'text' in part && message.role === 'assistant' ? { text: visibleMessageText(part.text) } : part)
  125. : undefined,
  126. tools: message.toolCalls?.filter(tool => tool.id).map(tool => toolToUi(!message.isStreaming && ['pending', 'running'].includes(tool.status)
  127. ? { ...tool, status: 'interrupted' } : tool)),
  128. profile: message.profile,
  129. }
  130. }
  131. /** Render only user and agent prose; tool result rows belong under their call. */
  132. export function chatMessagesToUi(messages: ChatMessage[], agentNameFor?: (profile?: string) => string | undefined): UiMessage[] {
  133. const result: UiMessage[] = []
  134. const toolOwners = new Map<string, UiMessage>()
  135. let lastAssistant: UiMessage | undefined
  136. for (const message of messages) {
  137. if (message.role === 'tool') {
  138. const owner = (message.toolCallId && toolOwners.get(message.toolCallId)) || lastAssistant
  139. if (!owner) continue
  140. const id = message.toolCallId || message.id
  141. const tools = [...(owner.tools ?? [])]
  142. const index = tools.findIndex(tool => tool.id === id)
  143. const patch: UiToolCall = {
  144. id,
  145. name: message.toolName || tools[index]?.name || '工具',
  146. status: toolResultFailed(toolResult(message), message.error) ? 'error' : 'success',
  147. input: tools[index]?.input,
  148. output: message.error || toolResult(message),
  149. }
  150. if (index >= 0) tools[index] = { ...tools[index], ...patch }
  151. else tools.push(patch)
  152. owner.tools = tools
  153. if (message.toolCallId) toolOwners.set(message.toolCallId, owner)
  154. continue
  155. }
  156. // Gateway system rows are transport/protocol detail unless they carry an
  157. // explicit display marker or a human-readable [System: ...] notice.
  158. if (message.role === 'system' && !isSystemTimelineMessage(message)) continue
  159. const ui = chatMessageToUi(message, agentNameFor)
  160. if (isSystemTimelineMessage(message)) {
  161. const backgroundProcess = backgroundProcessMetadata(message.content)
  162. ui.role = 'system'
  163. ui.timelineKind = message.displayKind === 'async_delegation_complete'
  164. ? 'delegation-complete'
  165. : backgroundProcess
  166. ? 'background-process'
  167. : 'system'
  168. ui.timelineMetadata = {
  169. ...(timelineMetadata(message.displayMetadata) ?? {}),
  170. ...(backgroundProcess ?? {}),
  171. eventKind: isContextCompactionMessage(message) ? 'compaction' : message.displayKind,
  172. }
  173. }
  174. result.push(ui)
  175. if (message.role === 'assistant') {
  176. lastAssistant = ui
  177. ui.tools = ui.tools?.map(tool => {
  178. const previous = toolOwners.get(tool.id)
  179. const known = previous?.tools?.find(candidate => candidate.id === tool.id)
  180. if (previous && known && !/^tool-\d+$/.test(tool.id)) {
  181. previous.tools = previous.tools?.filter(candidate => candidate.id !== tool.id)
  182. tool = { ...known, ...tool, input: tool.input ?? known.input, output: tool.output ?? known.output,
  183. status: ['success', 'error'].includes(known.status) && !['success', 'error'].includes(tool.status) ? known.status : tool.status }
  184. }
  185. toolOwners.set(tool.id, ui)
  186. return tool
  187. })
  188. }
  189. }
  190. return result
  191. }
  192. export function chatInteraction(approval?: ApprovalRequest, clarification?: ClarificationRequest): UiInteraction | null {
  193. if (approval) return {
  194. id: approval.id,
  195. kind: 'approval',
  196. title: approval.toolName ? `允许 ${approval.toolName}` : '允许这项操作',
  197. prompt: approval.message || '机器人请求执行一项需要确认的操作。',
  198. options: approval.choices,
  199. detail: JSON.stringify(approval.payload, null, 2),
  200. }
  201. if (clarification) return {
  202. id: clarification.id,
  203. kind: 'clarification',
  204. prompt: clarification.question,
  205. options: clarification.choices,
  206. detail: JSON.stringify(clarification.payload, null, 2),
  207. }
  208. return null
  209. }
  210. export function roomSidebarItem(
  211. room: GroupRoomSummary,
  212. avatars: Record<string, string> = {},
  213. avatarsByName: Record<string, string> = {},
  214. ): SidebarItem {
  215. return {
  216. id: room.id,
  217. title: room.name || '未命名团队',
  218. subtitle: room.lastMessage?.content || `${room.agentCount} 个机器人`,
  219. meta: formatRelative(room.updatedAt),
  220. section: historySection(room.updatedAt),
  221. unread: room.unreadCount,
  222. avatar: room.avatar || '',
  223. avatarFallbackKey: room.id,
  224. avatarMembers: (room.avatarMembers || []).map(member => ({
  225. name: member.displayName || member.profile,
  226. avatar: member.nodeId === 'local' ? avatars[member.profile] || avatarsByName[member.displayName] : undefined,
  227. })),
  228. }
  229. }
  230. export function groupMessageToUi(message: GroupMessage, agents: GroupAgent[] = []): UiMessage {
  231. const tools = (message.toolState || []).map((entry, index) => {
  232. const value = record(entry)
  233. const rawStatus = string(value.status, 'success')
  234. const status: UiToolCall['status'] = rawStatus === 'completed' ? 'success' : rawStatus === 'failed' ? 'error' : ['running', 'pending', 'success', 'error'].includes(rawStatus) ? rawStatus as UiToolCall['status'] : 'success'
  235. return { id: string(value.id, `${message.id}:tool:${index}`), name: string(value.name ?? value.tool, '工具调用'), status, input: value.input ?? value.arguments, output: value.output ?? value.result }
  236. })
  237. const execution = message.execution
  238. const model = execution?.actualModel || execution?.requestedModel
  239. const reasoning = execution?.actualReasoningEffort || execution?.requestedReasoningEffort
  240. const fast = execution?.actualFastMode ?? execution?.requestedFastMode
  241. const metadata = model ? `${fast ? '⚡ ' : ''}${model}${reasoning ? ` · ${reasoning}` : ''}` : undefined
  242. const sender = message.senderKind === 'agent'
  243. ? agents.find(agent => agent.id === message.senderId)
  244. : undefined
  245. const content = sender && sender.nodeId !== 'local'
  246. ? rewriteRemoteNodeFiles(message.content, sender.nodeId, message.status === 'streaming')
  247. : message.content
  248. return {
  249. id: message.id,
  250. role: message.senderKind === 'human' ? 'user' : message.senderKind === 'agent' ? 'assistant' : 'system',
  251. author: sender?.displayName || message.senderName,
  252. isRemoteAgent: message.senderKind === 'agent' && sender != null && sender.nodeId !== 'local',
  253. // Only local agents share this Web client's Desktop Bots identity map.
  254. // Remote nodes keep their own identity and intentionally do not collide by
  255. // profile slug with a local agent.
  256. profile: sender
  257. ? sender.nodeId === 'local'
  258. ? sender.profile
  259. : `node:${sender.nodeId}:${sender.profile}`
  260. : undefined,
  261. content,
  262. reasoning: message.senderKind === 'agent' ? messageReasoningText(message.content, message.reasoning) : message.reasoning,
  263. createdAt: message.createdAt < 10_000_000_000 ? message.createdAt * 1000 : message.createdAt,
  264. status: message.status === 'completed' ? 'settled' : message.status === 'queued' ? 'pending' : message.status === 'streaming' ? 'streaming' : message.status === 'failed' ? 'failed' : message.status === 'unknown' ? 'unknown-receipt' : 'settled',
  265. error: message.error,
  266. tools,
  267. metadata,
  268. }
  269. }
  270. export function rewriteRemoteNodeFiles(content: string, nodeId: string, streaming = false): string {
  271. if (!/^[0-9a-f-]{36}$/i.test(nodeId)) return content
  272. return normalizeAssistantMediaMarkdown(content, streaming).replace(
  273. /(!?\[[^\]]*\]\()<?(?:file:\/\/|sandbox:)?(\/[^)>\n]+)>?(\))/g,
  274. (match, prefix: string, raw: string, suffix: string) => {
  275. const path = serverFilePath(raw)
  276. return path && serverFileUrl(raw) ? `${prefix}/api/app/groups/nodes/${encodeURIComponent(nodeId)}/files?path=${encodeURIComponent(path)}${suffix}` : match
  277. },
  278. )
  279. }
  280. export function groupInteraction(interaction?: GroupInteraction): UiInteraction | null {
  281. if (!interaction || interaction.status !== 'pending') return null
  282. const payload = record(interaction.payload)
  283. const choices = Array.isArray(payload.choices) ? payload.choices.filter((choice): choice is string => typeof choice === 'string') : undefined
  284. return {
  285. id: interaction.id,
  286. kind: interaction.kind === 'clarification' ? 'clarification' : 'approval',
  287. title: string(payload.title || payload.tool_name),
  288. prompt: string(payload.question || payload.message || payload.prompt, interaction.kind === 'clarification' ? '机器人需要补充信息' : '机器人请求执行操作'),
  289. options: choices,
  290. detail: JSON.stringify(payload, null, 2),
  291. }
  292. }
  293. export function agentToUi(agent: GroupAgent): UiAgent {
  294. return {
  295. id: agent.id,
  296. name: agent.displayName || agent.profile,
  297. profile: agent.profile,
  298. nodeId: agent.nodeId,
  299. enabled: agent.enabled,
  300. autoReply: agent.replyWithoutMention,
  301. isHost: agent.isHost,
  302. status: agent.status === 'running' || agent.status === 'queued' ? 'working' : agent.status === 'unknown' ? 'offline' : 'idle',
  303. }
  304. }
  305. export function roomToUi(room: GroupRoomDetail): UiRoom {
  306. return {
  307. id: room.id,
  308. name: room.name,
  309. archived: room.archived,
  310. instructions: room.instructions,
  311. avatar: room.avatar,
  312. memberIds: room.agents.map(agent => agent.id),
  313. replyRounds: room.maxReplyRounds,
  314. orchestrationMode: room.orchestrationMode,
  315. }
  316. }
  317. export function fileToUi(item: FileLibraryItem): UiLibraryItem {
  318. const extension = (item.extension || item.name.split('.').at(-1) || '').replace(/^\./, '').toLocaleLowerCase()
  319. const isTextFile = ['md', 'markdown', 'txt', 'json', 'yaml', 'yml', 'csv', 'js', 'ts', 'py', 'sh', 'css', 'html', 'xml'].includes(extension)
  320. const kind: UiLibraryItem['kind'] = item.mimeType === 'application/pdf' || extension === 'pdf'
  321. ? 'pdf'
  322. : isTextFile || /text|json|xml|javascript|typescript|css|html/i.test(item.mimeType)
  323. ? 'text'
  324. : item.kind === 'document' ? 'document' : item.kind === 'other' ? 'file' : item.kind
  325. const origin = item.origins.at(-1)
  326. return {
  327. id: item.id,
  328. name: item.name,
  329. kind,
  330. mimeType: item.mimeType,
  331. size: item.size,
  332. updatedAt: item.modifiedAt < 10_000_000_000 ? item.modifiedAt * 1000 : item.modifiedAt,
  333. previewUrl: item.previewUrl,
  334. downloadUrl: item.downloadUrl,
  335. sourceLabel: origin?.sessionTitle || origin?.authorName || origin?.profile,
  336. sourceSessionId: origin?.sessionId,
  337. sourceWorkspaceConversationId: origin?.workspaceConversationId,
  338. sourceMessageId: origin?.messageId,
  339. sourceProfile: origin?.profile,
  340. }
  341. }
  342. export function artifactToUi(item: ConversationArtifact): UiLibraryItem {
  343. const raw = item.attachment
  344. const kind: UiLibraryItem['kind'] = item.kind === 'link' ? 'link' : item.kind === 'image' ? 'image' : raw?.mimeType === 'application/pdf' ? 'pdf' : 'file'
  345. return {
  346. id: item.id,
  347. name: item.label || item.value.split('/').at(-1) || '产物',
  348. title: item.label,
  349. kind,
  350. mimeType: item.mimeType || raw?.mimeType,
  351. size: raw?.size,
  352. createdAt: item.timestamp < 10_000_000_000 ? item.timestamp * 1000 : item.timestamp,
  353. previewUrl: raw?.url || item.value,
  354. downloadUrl: raw?.url || (item.kind === 'file' ? item.value : undefined),
  355. sourceLabel: item.sessionTitle,
  356. sourceSessionId: item.sessionId,
  357. sourceMessageId: item.messageId,
  358. sourceProfile: item.profile,
  359. }
  360. }
  361. /** Adapt the Web-owned transcript to the existing chat presentation. */
  362. export function workspaceMessagesToUi(messages: import('@shared/workspace').WorkspaceMessage[]): UiMessage[] {
  363. return messages.filter(message => message.visible !== false).map(message => ({
  364. id: message.id, role: message.role, author: message.agentName,
  365. communication: message.communication,
  366. browserCard: message.browserCard,
  367. serviceWarnings: message.serviceWarnings,
  368. taskReference: message.taskReference,
  369. error: message.error, runId: message.runId,
  370. profile: message.agentId, createdAt: message.createdAt,
  371. // Resolve legacy MEDIA references before mapping paths to archived file URLs,
  372. // so the renderer can identify body media and trailing attachments as one file.
  373. content: (message.communication?.content ?? (message.role === 'assistant'
  374. ? normalizeAssistantMediaMarkdown(visibleMessageText(message.content), message.status === 'streaming')
  375. : message.content)).replace(/(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g, (whole, label: string, path: string) => {
  376. const sourcePath = serverFilePath(path)
  377. const file = message.attachments.find(file => file.sourcePath === path
  378. || (sourcePath && file.sourcePath && serverFilePath(file.sourcePath, false) === sourcePath))
  379. return file ? `${label}(/api/app/files/${file.id}/${label.startsWith('!') ? 'preview' : 'download'})` : whole
  380. }),
  381. reasoning: message.role === 'assistant' ? messageReasoningText(message.content, message.reasoning) : message.reasoning,
  382. status: message.status === 'complete' || message.status === 'interrupted' ? 'settled'
  383. : message.status === 'uncertain' ? 'unknown-receipt'
  384. : message.status === 'queued' ? 'pending' : message.status,
  385. attachments: message.attachments.map(file => ({
  386. id: file.id, name: file.name, size: file.size,
  387. kind: file.mimeType.startsWith('image/') ? 'image' : file.mimeType.startsWith('video/') ? 'video' : file.mimeType.startsWith('audio/') ? 'audio' : 'file',
  388. url: `/api/app/files/${file.id}/${file.mimeType.startsWith('image/') ? 'preview' : 'download'}`,
  389. })),
  390. tools: message.tools.map((tool, index) => {
  391. let status = toolStatus(tool.status, tool.result ?? tool.output, tool.error)
  392. // Match runtime finalization for older messages whose tools were not settled.
  393. if (status === 'running' && ['complete', 'failed', 'interrupted'].includes(message.status)) {
  394. status = message.status === 'complete' ? 'completed' : message.status === 'failed' ? 'failed' : 'interrupted'
  395. }
  396. return {
  397. id: String(tool.id || index), name: String(tool.name || tool.tool_name || '工具'),
  398. status: status === 'completed' ? 'success' : status === 'failed' ? 'error' : status,
  399. input: tool.arguments ?? tool.args ?? tool.input, output: tool.error ?? tool.result ?? tool.output,
  400. detailsUrl: typeof tool.detailsUrl === 'string' ? tool.detailsUrl : undefined,
  401. }
  402. }),
  403. }))
  404. }
  405. export function workspaceAvatarMembers(memberIds: string[], agents: import('@shared/workspace').WorkspaceAgent[], conversation?: import('@shared/workspace').WorkspaceConversation) {
  406. const byId = new Map(agents.map(agent => [agent.id, agent]))
  407. return memberIds.flatMap(id => {
  408. const agent = byId.get(id)
  409. return agent ? [{ name: agent.name, avatar: agent.avatar, state: workspaceAvatarState(conversation, agent.id), activityKey: conversation?.lastSeq }] : []
  410. })
  411. }
  412. export function workspaceAvatarState(conversation: import('@shared/workspace').WorkspaceConversation | undefined, agentId: string): 'idle' | 'working' | 'waiting' | 'loading' | 'success' | 'failure' | 'notifying' {
  413. const state = conversation?.activeAgentStates?.[agentId]
  414. if (state) return state === 'running' ? 'working' : state === 'queued' ? 'loading' : 'waiting'
  415. const signal = conversation?.avatarSignals?.[agentId]
  416. if (signal && Date.now() - signal.at < 2000) return signal.state
  417. if (conversation?.activeRunStatus === 'queued' && conversation.memberIds[0] === agentId) return 'loading'
  418. if (!conversation?.activeRunId || conversation.activeAgentId !== agentId) return conversation?.previewAgentId === agentId && workspaceHasUnread(conversation) ? 'notifying' : 'idle'
  419. return conversation.activeRunStatus === 'waiting' || conversation.activeRunStatus === 'uncertain' ? 'waiting' : 'working'
  420. }
  421. type WorkspaceAgentActivity = 'working' | 'waiting' | 'loading'
  422. /** A Bot can be busy in several chats; one finished run must not hide another. */
  423. export function workspaceAgentActivity(conversations: import('@shared/workspace').WorkspaceConversation[]): Map<string, WorkspaceAgentActivity> {
  424. const activity = new Map<string, WorkspaceAgentActivity>()
  425. const priority = { working: 3, waiting: 2, loading: 1 }
  426. for (const conversation of conversations) {
  427. for (const id of conversation.memberIds) {
  428. const state = workspaceAvatarState(conversation, id)
  429. if (state !== 'working' && state !== 'waiting' && state !== 'loading') continue
  430. const previous = activity.get(id)
  431. if (!previous || priority[state] > priority[previous]) activity.set(id, state)
  432. }
  433. }
  434. return activity
  435. }
  436. export function workspaceConversationItem(c: import('@shared/workspace').WorkspaceConversation, agents: import('@shared/workspace').WorkspaceAgent[], agentActivity?: ReadonlyMap<string, WorkspaceAgentActivity>): SidebarItem {
  437. const activity = c.kind === 'direct' ? agentActivity?.get(c.memberIds[0] || '') : undefined
  438. return {
  439. id: c.id, title: c.name, subtitle: c.preview || (c.kind === 'direct' ? agents.find(agent => agent.id === c.memberIds[0])?.job || '' : '') || '开始聊天', pinned: c.pinned,
  440. section: c.pinned ? '已置顶' : '聊天', avatar: c.kind === 'group' ? '' : c.avatar,
  441. avatarMembers: c.kind === 'group' ? workspaceAvatarMembers(c.memberIds, agents, c) : [],
  442. meta: formatConversationTime(workspaceConversationTimestamp(c)),
  443. avatarKind: c.kind === 'direct' ? 'agent' : 'team',
  444. avatarState: activity ?? workspaceAvatarState(c, c.memberIds[0] || ''), avatarActivityKey: c.lastSeq,
  445. unreadDot: workspaceHasUnread(c), status: activity || c.activeRunId ? 'working' : undefined,
  446. }
  447. }