viewModels.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import { visibleMessageText, messageReasoningText } from '@shared/messageFiles'
  2. import { workspaceHasUnread } from '@shared/workspace'
  3. import { toolResultFailed } 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. tools: message.toolCalls?.filter(tool => tool.id).map(tool => toolToUi(!message.isStreaming && ['pending', 'running'].includes(tool.status)
  123. ? { ...tool, status: 'interrupted' } : tool)),
  124. profile: message.profile,
  125. }
  126. }
  127. /** Render only user and agent prose; tool result rows belong under their call. */
  128. export function chatMessagesToUi(messages: ChatMessage[], agentNameFor?: (profile?: string) => string | undefined): UiMessage[] {
  129. const result: UiMessage[] = []
  130. const toolOwners = new Map<string, UiMessage>()
  131. let lastAssistant: UiMessage | undefined
  132. for (const message of messages) {
  133. if (message.role === 'tool') {
  134. const owner = (message.toolCallId && toolOwners.get(message.toolCallId)) || lastAssistant
  135. if (!owner) continue
  136. const id = message.toolCallId || message.id
  137. const tools = [...(owner.tools ?? [])]
  138. const index = tools.findIndex(tool => tool.id === id)
  139. const patch: UiToolCall = {
  140. id,
  141. name: message.toolName || tools[index]?.name || '工具',
  142. status: toolResultFailed(toolResult(message), message.error) ? 'error' : 'success',
  143. input: tools[index]?.input,
  144. output: message.error || toolResult(message),
  145. }
  146. if (index >= 0) tools[index] = { ...tools[index], ...patch }
  147. else tools.push(patch)
  148. owner.tools = tools
  149. if (message.toolCallId) toolOwners.set(message.toolCallId, owner)
  150. continue
  151. }
  152. // Gateway system rows are transport/protocol detail unless they carry an
  153. // explicit display marker or a human-readable [System: ...] notice.
  154. if (message.role === 'system' && !isSystemTimelineMessage(message)) continue
  155. const ui = chatMessageToUi(message, agentNameFor)
  156. if (isSystemTimelineMessage(message)) {
  157. const backgroundProcess = backgroundProcessMetadata(message.content)
  158. ui.role = 'system'
  159. ui.timelineKind = message.displayKind === 'async_delegation_complete'
  160. ? 'delegation-complete'
  161. : backgroundProcess
  162. ? 'background-process'
  163. : 'system'
  164. ui.timelineMetadata = {
  165. ...(timelineMetadata(message.displayMetadata) ?? {}),
  166. ...(backgroundProcess ?? {}),
  167. eventKind: isContextCompactionMessage(message) ? 'compaction' : message.displayKind,
  168. }
  169. }
  170. result.push(ui)
  171. if (message.role === 'assistant') {
  172. lastAssistant = ui
  173. ui.tools = ui.tools?.map(tool => {
  174. const previous = toolOwners.get(tool.id)
  175. const known = previous?.tools?.find(candidate => candidate.id === tool.id)
  176. if (previous && known && !/^tool-\d+$/.test(tool.id)) {
  177. previous.tools = previous.tools?.filter(candidate => candidate.id !== tool.id)
  178. tool = { ...known, ...tool, input: tool.input ?? known.input, output: tool.output ?? known.output,
  179. status: ['success', 'error'].includes(known.status) && !['success', 'error'].includes(tool.status) ? known.status : tool.status }
  180. }
  181. toolOwners.set(tool.id, ui)
  182. return tool
  183. })
  184. }
  185. }
  186. return result
  187. }
  188. export function chatInteraction(approval?: ApprovalRequest, clarification?: ClarificationRequest): UiInteraction | null {
  189. if (approval) return {
  190. id: approval.id,
  191. kind: 'approval',
  192. title: approval.toolName ? `允许 ${approval.toolName}` : '允许这项操作',
  193. prompt: approval.message || '机器人请求执行一项需要确认的操作。',
  194. options: approval.choices,
  195. detail: JSON.stringify(approval.payload, null, 2),
  196. }
  197. if (clarification) return {
  198. id: clarification.id,
  199. kind: 'clarification',
  200. prompt: clarification.question,
  201. options: clarification.choices,
  202. detail: JSON.stringify(clarification.payload, null, 2),
  203. }
  204. return null
  205. }
  206. export function roomSidebarItem(
  207. room: GroupRoomSummary,
  208. avatars: Record<string, string> = {},
  209. avatarsByName: Record<string, string> = {},
  210. ): SidebarItem {
  211. return {
  212. id: room.id,
  213. title: room.name || '未命名团队',
  214. subtitle: room.lastMessage?.content || `${room.agentCount} 个机器人`,
  215. meta: formatRelative(room.updatedAt),
  216. section: historySection(room.updatedAt),
  217. unread: room.unreadCount,
  218. avatar: room.avatar || '',
  219. avatarFallbackKey: room.id,
  220. avatarMembers: (room.avatarMembers || []).map(member => ({
  221. name: member.displayName || member.profile,
  222. avatar: member.nodeId === 'local' ? avatars[member.profile] || avatarsByName[member.displayName] : undefined,
  223. })),
  224. }
  225. }
  226. export function groupMessageToUi(message: GroupMessage, agents: GroupAgent[] = []): UiMessage {
  227. const tools = (message.toolState || []).map((entry, index) => {
  228. const value = record(entry)
  229. const rawStatus = string(value.status, 'success')
  230. const status: UiToolCall['status'] = rawStatus === 'completed' ? 'success' : rawStatus === 'failed' ? 'error' : ['running', 'pending', 'success', 'error'].includes(rawStatus) ? rawStatus as UiToolCall['status'] : 'success'
  231. 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 }
  232. })
  233. const execution = message.execution
  234. const model = execution?.actualModel || execution?.requestedModel
  235. const reasoning = execution?.actualReasoningEffort || execution?.requestedReasoningEffort
  236. const fast = execution?.actualFastMode ?? execution?.requestedFastMode
  237. const metadata = model ? `${fast ? '⚡ ' : ''}${model}${reasoning ? ` · ${reasoning}` : ''}` : undefined
  238. const sender = message.senderKind === 'agent'
  239. ? agents.find(agent => agent.id === message.senderId)
  240. : undefined
  241. const content = sender && sender.nodeId !== 'local'
  242. ? rewriteRemoteNodeFiles(message.content, sender.nodeId, message.status === 'streaming')
  243. : message.content
  244. return {
  245. id: message.id,
  246. role: message.senderKind === 'human' ? 'user' : message.senderKind === 'agent' ? 'assistant' : 'system',
  247. author: sender?.displayName || message.senderName,
  248. isRemoteAgent: message.senderKind === 'agent' && sender != null && sender.nodeId !== 'local',
  249. // Only local agents share this Web client's Desktop Bots identity map.
  250. // Remote nodes keep their own identity and intentionally do not collide by
  251. // profile slug with a local agent.
  252. profile: sender
  253. ? sender.nodeId === 'local'
  254. ? sender.profile
  255. : `node:${sender.nodeId}:${sender.profile}`
  256. : undefined,
  257. content,
  258. reasoning: message.senderKind === 'agent' ? messageReasoningText(message.content, message.reasoning) : message.reasoning,
  259. createdAt: message.createdAt < 10_000_000_000 ? message.createdAt * 1000 : message.createdAt,
  260. status: message.status === 'completed' ? 'settled' : message.status === 'queued' ? 'pending' : message.status === 'streaming' ? 'streaming' : message.status === 'failed' ? 'failed' : message.status === 'unknown' ? 'unknown-receipt' : 'settled',
  261. error: message.error,
  262. tools,
  263. metadata,
  264. }
  265. }
  266. export function rewriteRemoteNodeFiles(content: string, nodeId: string, streaming = false): string {
  267. if (!/^[0-9a-f-]{36}$/i.test(nodeId)) return content
  268. return normalizeAssistantMediaMarkdown(content, streaming).replace(
  269. /(!?\[[^\]]*\]\()<?(?:file:\/\/|sandbox:)?(\/[^)>\n]+)>?(\))/g,
  270. (match, prefix: string, raw: string, suffix: string) => {
  271. const path = serverFilePath(raw)
  272. return path && serverFileUrl(raw) ? `${prefix}/api/app/groups/nodes/${encodeURIComponent(nodeId)}/files?path=${encodeURIComponent(path)}${suffix}` : match
  273. },
  274. )
  275. }
  276. export function groupInteraction(interaction?: GroupInteraction): UiInteraction | null {
  277. if (!interaction || interaction.status !== 'pending') return null
  278. const payload = record(interaction.payload)
  279. const choices = Array.isArray(payload.choices) ? payload.choices.filter((choice): choice is string => typeof choice === 'string') : undefined
  280. return {
  281. id: interaction.id,
  282. kind: interaction.kind === 'clarification' ? 'clarification' : 'approval',
  283. title: string(payload.title || payload.tool_name),
  284. prompt: string(payload.question || payload.message || payload.prompt, interaction.kind === 'clarification' ? '机器人需要补充信息' : '机器人请求执行操作'),
  285. options: choices,
  286. detail: JSON.stringify(payload, null, 2),
  287. }
  288. }
  289. export function agentToUi(agent: GroupAgent): UiAgent {
  290. return {
  291. id: agent.id,
  292. name: agent.displayName || agent.profile,
  293. profile: agent.profile,
  294. nodeId: agent.nodeId,
  295. enabled: agent.enabled,
  296. autoReply: agent.replyWithoutMention,
  297. isHost: agent.isHost,
  298. status: agent.status === 'running' || agent.status === 'queued' ? 'working' : agent.status === 'unknown' ? 'offline' : 'idle',
  299. }
  300. }
  301. export function roomToUi(room: GroupRoomDetail): UiRoom {
  302. return {
  303. id: room.id,
  304. name: room.name,
  305. archived: room.archived,
  306. instructions: room.instructions,
  307. avatar: room.avatar,
  308. memberIds: room.agents.map(agent => agent.id),
  309. replyRounds: room.maxReplyRounds,
  310. orchestrationMode: room.orchestrationMode,
  311. }
  312. }
  313. export function fileToUi(item: FileLibraryItem): UiLibraryItem {
  314. const extension = (item.extension || item.name.split('.').at(-1) || '').replace(/^\./, '').toLocaleLowerCase()
  315. const isTextFile = ['md', 'markdown', 'txt', 'json', 'yaml', 'yml', 'csv', 'js', 'ts', 'py', 'sh', 'css', 'html', 'xml'].includes(extension)
  316. const kind: UiLibraryItem['kind'] = item.mimeType === 'application/pdf' || extension === 'pdf'
  317. ? 'pdf'
  318. : isTextFile || /text|json|xml|javascript|typescript|css|html/i.test(item.mimeType)
  319. ? 'text'
  320. : item.kind === 'document' ? 'document' : item.kind === 'other' ? 'file' : item.kind
  321. const origin = item.origins.at(-1)
  322. return {
  323. id: item.id,
  324. name: item.name,
  325. kind,
  326. mimeType: item.mimeType,
  327. size: item.size,
  328. updatedAt: item.modifiedAt < 10_000_000_000 ? item.modifiedAt * 1000 : item.modifiedAt,
  329. previewUrl: item.previewUrl,
  330. downloadUrl: item.downloadUrl,
  331. sourceLabel: origin?.sessionTitle || origin?.authorName || origin?.profile,
  332. sourceSessionId: origin?.sessionId,
  333. sourceWorkspaceConversationId: origin?.workspaceConversationId,
  334. sourceMessageId: origin?.messageId,
  335. sourceProfile: origin?.profile,
  336. }
  337. }
  338. export function artifactToUi(item: ConversationArtifact): UiLibraryItem {
  339. const raw = item.attachment
  340. const kind: UiLibraryItem['kind'] = item.kind === 'link' ? 'link' : item.kind === 'image' ? 'image' : raw?.mimeType === 'application/pdf' ? 'pdf' : 'file'
  341. return {
  342. id: item.id,
  343. name: item.label || item.value.split('/').at(-1) || '产物',
  344. title: item.label,
  345. kind,
  346. mimeType: item.mimeType || raw?.mimeType,
  347. size: raw?.size,
  348. createdAt: item.timestamp < 10_000_000_000 ? item.timestamp * 1000 : item.timestamp,
  349. previewUrl: raw?.url || item.value,
  350. downloadUrl: raw?.url || (item.kind === 'file' ? item.value : undefined),
  351. sourceLabel: item.sessionTitle,
  352. sourceSessionId: item.sessionId,
  353. sourceMessageId: item.messageId,
  354. sourceProfile: item.profile,
  355. }
  356. }
  357. /** Adapt the Web-owned transcript to the existing chat presentation. */
  358. export function workspaceMessagesToUi(messages: import('@shared/workspace').WorkspaceMessage[]): UiMessage[] {
  359. return messages.filter(message => message.visible !== false).map(message => ({
  360. id: message.id, role: message.role, author: message.agentName,
  361. profile: message.agentId, createdAt: message.createdAt,
  362. content: (message.role === 'assistant' ? visibleMessageText(message.content) : message.content).replace(/(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g, (whole, label: string, path: string) => {
  363. const file = message.attachments.find(file => file.sourcePath === path)
  364. return file ? `${label}(/api/app/files/${file.id}/${label.startsWith('!') ? 'preview' : 'download'})` : whole
  365. }),
  366. reasoning: message.role === 'assistant' ? messageReasoningText(message.content, message.reasoning) : message.reasoning,
  367. status: message.status === 'complete' || message.status === 'interrupted' ? 'settled'
  368. : message.status === 'uncertain' ? 'unknown-receipt'
  369. : message.status === 'queued' ? 'pending' : message.status,
  370. attachments: message.attachments.map(file => ({
  371. id: file.id, name: file.name, size: file.size,
  372. kind: file.mimeType.startsWith('image/') ? 'image' : file.mimeType.startsWith('video/') ? 'video' : file.mimeType.startsWith('audio/') ? 'audio' : 'file',
  373. url: `/api/app/files/${file.id}/${file.mimeType.startsWith('image/') ? 'preview' : 'download'}`,
  374. })),
  375. tools: message.tools.map((tool, index) => ({
  376. id: String(tool.id || index), name: String(tool.name || tool.tool_name || '工具'),
  377. status: String(tool.status).includes('error') ? 'error' : String(tool.status).includes('complete') ? 'success' : 'running',
  378. input: tool.arguments ?? tool.input, output: tool.result ?? tool.output,
  379. })),
  380. }))
  381. }
  382. export function workspaceAvatarMembers(memberIds: string[], agents: import('@shared/workspace').WorkspaceAgent[], conversation?: import('@shared/workspace').WorkspaceConversation) {
  383. const byId = new Map(agents.map(agent => [agent.id, agent]))
  384. return memberIds.flatMap(id => {
  385. const agent = byId.get(id)
  386. return agent ? [{ name: agent.name, avatar: agent.avatar, state: workspaceAvatarState(conversation, agent.id), activityKey: conversation?.lastSeq }] : []
  387. })
  388. }
  389. export function workspaceAvatarState(conversation: import('@shared/workspace').WorkspaceConversation | undefined, agentId: string): 'idle' | 'working' | 'waiting' | 'loading' | 'success' | 'failure' | 'notifying' {
  390. const state = conversation?.activeAgentStates?.[agentId]
  391. if (state) return state === 'running' ? 'working' : state === 'queued' ? 'loading' : 'waiting'
  392. const signal = conversation?.avatarSignals?.[agentId]
  393. if (signal && Date.now() - signal.at < 2000) return signal.state
  394. if (conversation?.activeRunStatus === 'queued' && conversation.memberIds[0] === agentId) return 'loading'
  395. if (!conversation?.activeRunId || conversation.activeAgentId !== agentId) return conversation?.previewAgentId === agentId && workspaceHasUnread(conversation) ? 'notifying' : 'idle'
  396. return conversation.activeRunStatus === 'waiting' || conversation.activeRunStatus === 'uncertain' ? 'waiting' : 'working'
  397. }
  398. type WorkspaceAgentActivity = 'working' | 'waiting' | 'loading'
  399. /** A Bot can be busy in several chats; one finished run must not hide another. */
  400. export function workspaceAgentActivity(conversations: import('@shared/workspace').WorkspaceConversation[]): Map<string, WorkspaceAgentActivity> {
  401. const activity = new Map<string, WorkspaceAgentActivity>()
  402. const priority = { working: 3, waiting: 2, loading: 1 }
  403. for (const conversation of conversations) {
  404. for (const id of conversation.memberIds) {
  405. const state = workspaceAvatarState(conversation, id)
  406. if (state !== 'working' && state !== 'waiting' && state !== 'loading') continue
  407. const previous = activity.get(id)
  408. if (!previous || priority[state] > priority[previous]) activity.set(id, state)
  409. }
  410. }
  411. return activity
  412. }
  413. export function workspaceConversationItem(c: import('@shared/workspace').WorkspaceConversation, agents: import('@shared/workspace').WorkspaceAgent[], agentActivity?: ReadonlyMap<string, WorkspaceAgentActivity>): SidebarItem {
  414. const activity = c.kind === 'direct' ? agentActivity?.get(c.memberIds[0] || '') : undefined
  415. return {
  416. id: c.id, title: c.name, subtitle: c.preview || '开始聊天', pinned: c.pinned,
  417. section: c.pinned ? '已置顶' : '聊天', avatar: c.kind === 'group' ? '' : c.avatar,
  418. avatarMembers: c.kind === 'group' ? workspaceAvatarMembers(c.memberIds, agents, c) : [],
  419. meta: formatConversationTime(c.lastMessageAt ?? c.createdAt),
  420. avatarKind: c.kind === 'direct' ? 'agent' : 'team',
  421. avatarState: activity ?? workspaceAvatarState(c, c.memberIds[0] || ''), avatarActivityKey: c.lastSeq,
  422. unreadDot: workspaceHasUnread(c), status: activity || c.activeRunId ? 'working' : undefined,
  423. }
  424. }