viewModels.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. function isContextCompactionMessage(message: ChatMessage): boolean {
  79. return message.content.trim().toLocaleLowerCase().startsWith(CONTEXT_COMPACTION_PREFIX)
  80. || message.displayKind?.toLocaleLowerCase().includes('compaction') === true
  81. }
  82. function isSystemTimelineMessage(message: ChatMessage): boolean {
  83. return Boolean(message.displayKind) || /^\[system:/i.test(message.content.trim()) || isContextCompactionMessage(message)
  84. }
  85. export function chatMessageToUi(message: ChatMessage, agentNameFor?: (profile?: string) => string | undefined): UiMessage {
  86. const attachments: UiMessageAttachment[] | undefined = message.attachments?.map(attachment => ({
  87. id: attachment.id,
  88. name: attachment.name,
  89. kind: attachment.kind === 'image' ? 'image' : 'file',
  90. url: attachment.url,
  91. size: attachment.size,
  92. }))
  93. return {
  94. id: message.id,
  95. role: message.role,
  96. author: message.role === 'assistant' ? agentNameFor?.(message.profile) || message.profile : undefined,
  97. content: message.content,
  98. reasoning: message.reasoning,
  99. createdAt: message.timestamp < 10_000_000_000 ? message.timestamp * 1000 : message.timestamp,
  100. status: message.isStreaming ? 'streaming' : message.stage,
  101. error: message.error,
  102. attachments,
  103. tools: message.toolCalls?.map(toolToUi),
  104. profile: message.profile,
  105. }
  106. }
  107. /** Render only user and agent prose; tool result rows belong under their call. */
  108. export function chatMessagesToUi(messages: ChatMessage[], agentNameFor?: (profile?: string) => string | undefined): UiMessage[] {
  109. const result: UiMessage[] = []
  110. const toolOwners = new Map<string, UiMessage>()
  111. let lastAssistant: UiMessage | undefined
  112. for (const message of messages) {
  113. if (message.role === 'tool') {
  114. const owner = (message.toolCallId && toolOwners.get(message.toolCallId)) || lastAssistant
  115. if (!owner) continue
  116. const id = message.toolCallId || message.id
  117. const tools = [...(owner.tools ?? [])]
  118. const index = tools.findIndex(tool => tool.id === id)
  119. const patch: UiToolCall = {
  120. id,
  121. name: message.toolName || tools[index]?.name || '工具',
  122. status: message.error ? 'error' : 'success',
  123. input: tools[index]?.input,
  124. output: message.error || toolResult(message),
  125. }
  126. if (index >= 0) tools[index] = { ...tools[index], ...patch }
  127. else tools.push(patch)
  128. owner.tools = tools
  129. if (message.toolCallId) toolOwners.set(message.toolCallId, owner)
  130. continue
  131. }
  132. // Gateway system rows are transport/protocol detail unless they carry an
  133. // explicit display marker or a human-readable [System: ...] notice.
  134. if (message.role === 'system' && !isSystemTimelineMessage(message)) continue
  135. const ui = chatMessageToUi(message, agentNameFor)
  136. if (isSystemTimelineMessage(message)) {
  137. ui.role = 'system'
  138. ui.timelineKind = message.displayKind === 'async_delegation_complete' ? 'delegation-complete' : 'system'
  139. ui.timelineMetadata = {
  140. ...(timelineMetadata(message.displayMetadata) ?? {}),
  141. eventKind: isContextCompactionMessage(message) ? 'compaction' : message.displayKind,
  142. }
  143. }
  144. result.push(ui)
  145. if (message.role === 'assistant') {
  146. lastAssistant = ui
  147. for (const tool of ui.tools ?? []) toolOwners.set(tool.id, ui)
  148. }
  149. }
  150. return result
  151. }
  152. export function chatInteraction(approval?: ApprovalRequest, clarification?: ClarificationRequest): UiInteraction | null {
  153. if (approval) return {
  154. id: approval.id,
  155. kind: 'approval',
  156. title: approval.toolName ? `允许 ${approval.toolName}` : '允许这项操作',
  157. prompt: approval.message || 'Agent 请求执行一项需要确认的操作。',
  158. options: approval.choices,
  159. detail: JSON.stringify(approval.payload, null, 2),
  160. }
  161. if (clarification) return {
  162. id: clarification.id,
  163. kind: 'clarification',
  164. prompt: clarification.question,
  165. options: clarification.choices,
  166. detail: JSON.stringify(clarification.payload, null, 2),
  167. }
  168. return null
  169. }
  170. export function roomSidebarItem(room: GroupRoomSummary): SidebarItem {
  171. return {
  172. id: room.id,
  173. title: room.name || '未命名群聊',
  174. subtitle: room.lastMessage?.content || `${room.agentCount} 个 Agent`,
  175. meta: formatRelative(room.updatedAt),
  176. section: historySection(room.updatedAt),
  177. unread: room.unreadCount,
  178. icon: 'groups',
  179. }
  180. }
  181. export function groupMessageToUi(message: GroupMessage, agents: GroupAgent[] = []): UiMessage {
  182. const tools = (message.toolState || []).map((entry, index) => {
  183. const value = record(entry)
  184. const rawStatus = string(value.status, 'success')
  185. const status: UiToolCall['status'] = rawStatus === 'completed' ? 'success' : rawStatus === 'failed' ? 'error' : ['running', 'pending', 'success', 'error'].includes(rawStatus) ? rawStatus as UiToolCall['status'] : 'success'
  186. 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 }
  187. })
  188. const execution = message.execution
  189. const model = execution?.actualModel || execution?.requestedModel
  190. const reasoning = execution?.actualReasoningEffort || execution?.requestedReasoningEffort
  191. const fast = execution?.actualFastMode ?? execution?.requestedFastMode
  192. const metadata = model ? `${fast ? '⚡ ' : ''}${model}${reasoning ? ` · ${reasoning}` : ''}` : undefined
  193. const sender = message.senderKind === 'agent'
  194. ? agents.find(agent => agent.id === message.senderId)
  195. : undefined
  196. return {
  197. id: message.id,
  198. role: message.senderKind === 'human' ? 'user' : message.senderKind === 'agent' ? 'assistant' : 'system',
  199. author: sender?.displayName || message.senderName,
  200. isRemoteAgent: message.senderKind === 'agent' && sender != null && sender.nodeId !== 'local',
  201. content: message.content,
  202. reasoning: message.reasoning,
  203. createdAt: message.createdAt < 10_000_000_000 ? message.createdAt * 1000 : message.createdAt,
  204. status: message.status === 'completed' ? 'settled' : message.status === 'queued' ? 'pending' : message.status === 'streaming' ? 'streaming' : message.status === 'failed' ? 'failed' : message.status === 'unknown' ? 'unknown-receipt' : 'settled',
  205. error: message.error,
  206. tools,
  207. metadata,
  208. }
  209. }
  210. export function groupInteraction(interaction?: GroupInteraction): UiInteraction | null {
  211. if (!interaction || interaction.status !== 'pending') return null
  212. const payload = record(interaction.payload)
  213. const choices = Array.isArray(payload.choices) ? payload.choices.filter((choice): choice is string => typeof choice === 'string') : undefined
  214. return {
  215. id: interaction.id,
  216. kind: interaction.kind === 'clarification' ? 'clarification' : 'approval',
  217. title: string(payload.title || payload.tool_name),
  218. prompt: string(payload.question || payload.message || payload.prompt, interaction.kind === 'clarification' ? 'Agent 需要补充信息' : 'Agent 请求执行操作'),
  219. options: choices,
  220. detail: JSON.stringify(payload, null, 2),
  221. }
  222. }
  223. export function agentToUi(agent: GroupAgent): UiAgent {
  224. return {
  225. id: agent.id,
  226. name: agent.displayName || agent.profile,
  227. profile: agent.profile,
  228. enabled: agent.enabled,
  229. autoReply: agent.replyWithoutMention,
  230. isHost: agent.isHost,
  231. status: agent.status === 'running' || agent.status === 'queued' ? 'working' : agent.status === 'unknown' ? 'offline' : 'idle',
  232. }
  233. }
  234. export function roomToUi(room: GroupRoomDetail): UiRoom {
  235. return {
  236. id: room.id,
  237. name: room.name,
  238. archived: room.archived,
  239. instructions: room.instructions,
  240. memberIds: room.agents.map(agent => agent.id),
  241. replyRounds: room.maxReplyRounds,
  242. orchestrationMode: room.orchestrationMode,
  243. }
  244. }
  245. export function fileToUi(item: FileLibraryItem): UiLibraryItem {
  246. const extension = (item.extension || item.name.split('.').at(-1) || '').replace(/^\./, '').toLocaleLowerCase()
  247. const isTextFile = ['md', 'markdown', 'txt', 'json', 'yaml', 'yml', 'csv', 'js', 'ts', 'py', 'sh', 'css', 'html', 'xml'].includes(extension)
  248. const kind: UiLibraryItem['kind'] = item.mimeType === 'application/pdf' || extension === 'pdf'
  249. ? 'pdf'
  250. : isTextFile || /text|json|xml|javascript|typescript|css|html/i.test(item.mimeType)
  251. ? 'text'
  252. : item.kind === 'document' ? 'document' : item.kind === 'other' ? 'file' : item.kind
  253. const origin = item.origins.at(-1)
  254. return {
  255. id: item.id,
  256. name: item.name,
  257. kind,
  258. mimeType: item.mimeType,
  259. size: item.size,
  260. updatedAt: item.modifiedAt < 10_000_000_000 ? item.modifiedAt * 1000 : item.modifiedAt,
  261. previewUrl: item.previewUrl,
  262. downloadUrl: item.downloadUrl,
  263. sourceLabel: origin?.sessionTitle || origin?.authorName || origin?.profile,
  264. sourceSessionId: origin?.sessionId,
  265. sourceMessageId: origin?.messageId,
  266. sourceProfile: origin?.profile,
  267. }
  268. }
  269. export function artifactToUi(item: ConversationArtifact): UiLibraryItem {
  270. const raw = item.attachment
  271. const kind: UiLibraryItem['kind'] = item.kind === 'link' ? 'link' : item.kind === 'image' ? 'image' : raw?.mimeType === 'application/pdf' ? 'pdf' : 'file'
  272. return {
  273. id: item.id,
  274. name: item.label || item.value.split('/').at(-1) || '产物',
  275. title: item.label,
  276. kind,
  277. mimeType: item.mimeType || raw?.mimeType,
  278. size: raw?.size,
  279. createdAt: item.timestamp < 10_000_000_000 ? item.timestamp * 1000 : item.timestamp,
  280. previewUrl: raw?.url || item.value,
  281. downloadUrl: raw?.url || (item.kind === 'file' ? item.value : undefined),
  282. sourceLabel: item.sessionTitle,
  283. sourceSessionId: item.sessionId,
  284. sourceMessageId: item.messageId,
  285. sourceProfile: item.profile,
  286. }
  287. }