viewModels.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import type {
  2. ApprovalRequest,
  3. ChatMessage,
  4. ClarificationRequest,
  5. ConversationArtifact,
  6. FileLibraryItem,
  7. GroupAgent,
  8. GroupInteraction,
  9. GroupMessage,
  10. GroupRoomDetail,
  11. GroupRoomSummary,
  12. SessionSummary,
  13. ToolCall,
  14. } from '@shared/types'
  15. import type { SidebarItem } from '@/components/app/types'
  16. import type { UiAgent, UiRoom } from '@/components/groups/types'
  17. import type { UiLibraryItem } from '@/components/library/types'
  18. import type { UiInteraction, UiMessage, UiMessageAttachment, UiToolCall } from '@/components/messages/types'
  19. function record(value: unknown): Record<string, unknown> {
  20. return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
  21. }
  22. function string(value: unknown, fallback = ''): string {
  23. return typeof value === 'string' ? value : fallback
  24. }
  25. function formatRelative(value: number): string {
  26. const ms = value < 10_000_000_000 ? value * 1000 : value
  27. const diff = Date.now() - ms
  28. if (diff < 60_000) return '刚刚'
  29. if (diff < 3_600_000) return `${Math.max(1, Math.floor(diff / 60_000))} 分钟`
  30. if (diff < 86_400_000) return `${Math.max(1, Math.floor(diff / 3_600_000))} 小时`
  31. const date = new Date(ms)
  32. return `${date.getMonth() + 1}/${date.getDate()}`
  33. }
  34. function historySection(value: number, pinned = false): string | undefined {
  35. if (pinned) return '已置顶'
  36. const ms = value < 10_000_000_000 ? value * 1000 : value
  37. const today = new Date()
  38. today.setHours(0, 0, 0, 0)
  39. const yesterday = new Date(today)
  40. yesterday.setDate(yesterday.getDate() - 1)
  41. if (ms >= today.getTime()) return '今天'
  42. if (ms >= yesterday.getTime()) return '昨天'
  43. return '更早'
  44. }
  45. export function sessionSidebarItem(session: SessionSummary, unread = 0, agentName = ''): SidebarItem {
  46. return {
  47. id: session.id,
  48. title: session.title || '未命名会话',
  49. subtitle: session.preview || `${session.messageCount} 条消息`,
  50. meta: agentName || session.agent || formatRelative(session.updatedAt),
  51. section: historySection(session.updatedAt, session.pinned),
  52. icon: 'chat',
  53. pinned: session.pinned,
  54. unread,
  55. }
  56. }
  57. function toolToUi(tool: ToolCall): UiToolCall {
  58. const status: UiToolCall['status'] = tool.status === 'completed' ? 'success' : tool.status === 'failed' ? 'error' : tool.status
  59. return {
  60. id: tool.id,
  61. name: tool.name,
  62. status,
  63. input: tool.arguments,
  64. output: tool.error || tool.result || tool.preview,
  65. durationMs: tool.durationSeconds ? Math.round(tool.durationSeconds * 1000) : undefined,
  66. }
  67. }
  68. function toolResult(message: ChatMessage): unknown {
  69. const raw = record(message.raw)
  70. if (raw.result !== undefined) return raw.result
  71. if (raw.output !== undefined && typeof raw.output !== 'string') return raw.output
  72. try { return JSON.parse(message.content) } catch { return message.content || undefined }
  73. }
  74. function timelineMetadata(value: unknown): Record<string, unknown> | undefined {
  75. return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined
  76. }
  77. const CONTEXT_COMPACTION_PREFIX = '[context compaction'
  78. const BACKGROUND_PROCESS_NOTICE = /^\[IMPORTANT:\s*Background process\s+(\S+)\s+exited\s+\(exit code\s+(-?\d+)(?:,\s*([^)]+))?\)\.?\]?(?:\r?\n|$)/i
  79. function isContextCompactionMessage(message: ChatMessage): boolean {
  80. return message.content.trim().toLocaleLowerCase().startsWith(CONTEXT_COMPACTION_PREFIX)
  81. || message.displayKind?.toLocaleLowerCase().includes('compaction') === true
  82. }
  83. function backgroundProcessMetadata(content: string): Record<string, unknown> | undefined {
  84. const match = content.trim().match(BACKGROUND_PROCESS_NOTICE)
  85. if (!match) return undefined
  86. return {
  87. process_id: match[1],
  88. exit_code: Number(match[2]),
  89. ...(match[3]?.trim() ? { signal: match[3].trim() } : {}),
  90. }
  91. }
  92. function isSystemTimelineMessage(message: ChatMessage): boolean {
  93. return Boolean(message.displayKind)
  94. || /^\[system:/i.test(message.content.trim())
  95. || isContextCompactionMessage(message)
  96. || Boolean(backgroundProcessMetadata(message.content))
  97. }
  98. export function chatMessageToUi(message: ChatMessage, agentNameFor?: (profile?: string) => string | undefined): UiMessage {
  99. const attachments: UiMessageAttachment[] | undefined = message.attachments?.map(attachment => ({
  100. id: attachment.id,
  101. name: attachment.name,
  102. kind: attachment.kind === 'image' ? 'image' : 'file',
  103. url: attachment.url,
  104. size: attachment.size,
  105. }))
  106. return {
  107. id: message.id,
  108. role: message.role,
  109. author: message.role === 'assistant' ? agentNameFor?.(message.profile) || message.profile : undefined,
  110. content: message.content,
  111. reasoning: message.reasoning,
  112. createdAt: message.timestamp < 10_000_000_000 ? message.timestamp * 1000 : message.timestamp,
  113. status: message.isStreaming ? 'streaming' : message.stage,
  114. error: message.error,
  115. attachments,
  116. tools: message.toolCalls?.map(toolToUi),
  117. profile: message.profile,
  118. }
  119. }
  120. /** Render only user and agent prose; tool result rows belong under their call. */
  121. export function chatMessagesToUi(messages: ChatMessage[], agentNameFor?: (profile?: string) => string | undefined): UiMessage[] {
  122. const result: UiMessage[] = []
  123. const toolOwners = new Map<string, UiMessage>()
  124. let lastAssistant: UiMessage | undefined
  125. for (const message of messages) {
  126. if (message.role === 'tool') {
  127. const owner = (message.toolCallId && toolOwners.get(message.toolCallId)) || lastAssistant
  128. if (!owner) continue
  129. const id = message.toolCallId || message.id
  130. const tools = [...(owner.tools ?? [])]
  131. const index = tools.findIndex(tool => tool.id === id)
  132. const patch: UiToolCall = {
  133. id,
  134. name: message.toolName || tools[index]?.name || '工具',
  135. status: message.error ? 'error' : 'success',
  136. input: tools[index]?.input,
  137. output: message.error || toolResult(message),
  138. }
  139. if (index >= 0) tools[index] = { ...tools[index], ...patch }
  140. else tools.push(patch)
  141. owner.tools = tools
  142. if (message.toolCallId) toolOwners.set(message.toolCallId, owner)
  143. continue
  144. }
  145. // Gateway system rows are transport/protocol detail unless they carry an
  146. // explicit display marker or a human-readable [System: ...] notice.
  147. if (message.role === 'system' && !isSystemTimelineMessage(message)) continue
  148. const ui = chatMessageToUi(message, agentNameFor)
  149. if (isSystemTimelineMessage(message)) {
  150. const backgroundProcess = backgroundProcessMetadata(message.content)
  151. ui.role = 'system'
  152. ui.timelineKind = message.displayKind === 'async_delegation_complete'
  153. ? 'delegation-complete'
  154. : backgroundProcess
  155. ? 'background-process'
  156. : 'system'
  157. ui.timelineMetadata = {
  158. ...(timelineMetadata(message.displayMetadata) ?? {}),
  159. ...(backgroundProcess ?? {}),
  160. eventKind: isContextCompactionMessage(message) ? 'compaction' : message.displayKind,
  161. }
  162. }
  163. result.push(ui)
  164. if (message.role === 'assistant') {
  165. lastAssistant = ui
  166. for (const tool of ui.tools ?? []) toolOwners.set(tool.id, ui)
  167. }
  168. }
  169. return result
  170. }
  171. export function chatInteraction(approval?: ApprovalRequest, clarification?: ClarificationRequest): UiInteraction | null {
  172. if (approval) return {
  173. id: approval.id,
  174. kind: 'approval',
  175. title: approval.toolName ? `允许 ${approval.toolName}` : '允许这项操作',
  176. prompt: approval.message || 'Agent 请求执行一项需要确认的操作。',
  177. options: approval.choices,
  178. detail: JSON.stringify(approval.payload, null, 2),
  179. }
  180. if (clarification) return {
  181. id: clarification.id,
  182. kind: 'clarification',
  183. prompt: clarification.question,
  184. options: clarification.choices,
  185. detail: JSON.stringify(clarification.payload, null, 2),
  186. }
  187. return null
  188. }
  189. export function roomSidebarItem(
  190. room: GroupRoomSummary,
  191. avatars: Record<string, string> = {},
  192. avatarsByName: Record<string, string> = {},
  193. ): SidebarItem {
  194. return {
  195. id: room.id,
  196. title: room.name || '未命名团队',
  197. subtitle: room.lastMessage?.content || `${room.agentCount} 个 Agent`,
  198. meta: formatRelative(room.updatedAt),
  199. section: historySection(room.updatedAt),
  200. unread: room.unreadCount,
  201. avatar: room.avatar || '',
  202. avatarMembers: (room.avatarMembers || []).map(member => ({
  203. name: member.displayName || member.profile,
  204. avatar: member.nodeId === 'local' ? avatars[member.profile] || avatarsByName[member.displayName] : undefined,
  205. })),
  206. }
  207. }
  208. export function groupMessageToUi(message: GroupMessage, agents: GroupAgent[] = []): UiMessage {
  209. const tools = (message.toolState || []).map((entry, index) => {
  210. const value = record(entry)
  211. const rawStatus = string(value.status, 'success')
  212. const status: UiToolCall['status'] = rawStatus === 'completed' ? 'success' : rawStatus === 'failed' ? 'error' : ['running', 'pending', 'success', 'error'].includes(rawStatus) ? rawStatus as UiToolCall['status'] : 'success'
  213. 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 }
  214. })
  215. const execution = message.execution
  216. const model = execution?.actualModel || execution?.requestedModel
  217. const reasoning = execution?.actualReasoningEffort || execution?.requestedReasoningEffort
  218. const fast = execution?.actualFastMode ?? execution?.requestedFastMode
  219. const metadata = model ? `${fast ? '⚡ ' : ''}${model}${reasoning ? ` · ${reasoning}` : ''}` : undefined
  220. const sender = message.senderKind === 'agent'
  221. ? agents.find(agent => agent.id === message.senderId)
  222. : undefined
  223. return {
  224. id: message.id,
  225. role: message.senderKind === 'human' ? 'user' : message.senderKind === 'agent' ? 'assistant' : 'system',
  226. author: sender?.displayName || message.senderName,
  227. isRemoteAgent: message.senderKind === 'agent' && sender != null && sender.nodeId !== 'local',
  228. // Only local agents share this Web client's Desktop Bots identity map.
  229. // Remote nodes keep their own identity and intentionally do not collide by
  230. // profile slug with a local agent.
  231. profile: sender?.nodeId === 'local' ? sender.profile : undefined,
  232. content: message.content,
  233. reasoning: message.reasoning,
  234. createdAt: message.createdAt < 10_000_000_000 ? message.createdAt * 1000 : message.createdAt,
  235. status: message.status === 'completed' ? 'settled' : message.status === 'queued' ? 'pending' : message.status === 'streaming' ? 'streaming' : message.status === 'failed' ? 'failed' : message.status === 'unknown' ? 'unknown-receipt' : 'settled',
  236. error: message.error,
  237. tools,
  238. metadata,
  239. }
  240. }
  241. export function groupInteraction(interaction?: GroupInteraction): UiInteraction | null {
  242. if (!interaction || interaction.status !== 'pending') return null
  243. const payload = record(interaction.payload)
  244. const choices = Array.isArray(payload.choices) ? payload.choices.filter((choice): choice is string => typeof choice === 'string') : undefined
  245. return {
  246. id: interaction.id,
  247. kind: interaction.kind === 'clarification' ? 'clarification' : 'approval',
  248. title: string(payload.title || payload.tool_name),
  249. prompt: string(payload.question || payload.message || payload.prompt, interaction.kind === 'clarification' ? 'Agent 需要补充信息' : 'Agent 请求执行操作'),
  250. options: choices,
  251. detail: JSON.stringify(payload, null, 2),
  252. }
  253. }
  254. export function agentToUi(agent: GroupAgent): UiAgent {
  255. return {
  256. id: agent.id,
  257. name: agent.displayName || agent.profile,
  258. profile: agent.profile,
  259. nodeId: agent.nodeId,
  260. enabled: agent.enabled,
  261. autoReply: agent.replyWithoutMention,
  262. isHost: agent.isHost,
  263. status: agent.status === 'running' || agent.status === 'queued' ? 'working' : agent.status === 'unknown' ? 'offline' : 'idle',
  264. }
  265. }
  266. export function roomToUi(room: GroupRoomDetail): UiRoom {
  267. return {
  268. id: room.id,
  269. name: room.name,
  270. archived: room.archived,
  271. instructions: room.instructions,
  272. avatar: room.avatar,
  273. memberIds: room.agents.map(agent => agent.id),
  274. replyRounds: room.maxReplyRounds,
  275. orchestrationMode: room.orchestrationMode,
  276. }
  277. }
  278. export function fileToUi(item: FileLibraryItem): UiLibraryItem {
  279. const extension = (item.extension || item.name.split('.').at(-1) || '').replace(/^\./, '').toLocaleLowerCase()
  280. const isTextFile = ['md', 'markdown', 'txt', 'json', 'yaml', 'yml', 'csv', 'js', 'ts', 'py', 'sh', 'css', 'html', 'xml'].includes(extension)
  281. const kind: UiLibraryItem['kind'] = item.mimeType === 'application/pdf' || extension === 'pdf'
  282. ? 'pdf'
  283. : isTextFile || /text|json|xml|javascript|typescript|css|html/i.test(item.mimeType)
  284. ? 'text'
  285. : item.kind === 'document' ? 'document' : item.kind === 'other' ? 'file' : item.kind
  286. const origin = item.origins.at(-1)
  287. return {
  288. id: item.id,
  289. name: item.name,
  290. kind,
  291. mimeType: item.mimeType,
  292. size: item.size,
  293. updatedAt: item.modifiedAt < 10_000_000_000 ? item.modifiedAt * 1000 : item.modifiedAt,
  294. previewUrl: item.previewUrl,
  295. downloadUrl: item.downloadUrl,
  296. sourceLabel: origin?.sessionTitle || origin?.authorName || origin?.profile,
  297. sourceSessionId: origin?.sessionId,
  298. sourceMessageId: origin?.messageId,
  299. sourceProfile: origin?.profile,
  300. }
  301. }
  302. export function artifactToUi(item: ConversationArtifact): UiLibraryItem {
  303. const raw = item.attachment
  304. const kind: UiLibraryItem['kind'] = item.kind === 'link' ? 'link' : item.kind === 'image' ? 'image' : raw?.mimeType === 'application/pdf' ? 'pdf' : 'file'
  305. return {
  306. id: item.id,
  307. name: item.label || item.value.split('/').at(-1) || '产物',
  308. title: item.label,
  309. kind,
  310. mimeType: item.mimeType || raw?.mimeType,
  311. size: raw?.size,
  312. createdAt: item.timestamp < 10_000_000_000 ? item.timestamp * 1000 : item.timestamp,
  313. previewUrl: raw?.url || item.value,
  314. downloadUrl: raw?.url || (item.kind === 'file' ? item.value : undefined),
  315. sourceLabel: item.sessionTitle,
  316. sourceSessionId: item.sessionId,
  317. sourceMessageId: item.messageId,
  318. sourceProfile: item.profile,
  319. }
  320. }