transcriptStore.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { WorkspaceMessageReconciler } from '@shared/workspaceMessagePatch'
  2. import type { AgentAssignment, AgentGoal } from '@shared/agentTasks'
  3. import { compareWorkspaceConversations } from '@shared/workspace'
  4. import type { WorkspaceAgent, WorkspaceConversation, WorkspaceEvent, WorkspaceInteraction, WorkspaceMessage, WorkspaceRun, WorkspaceTask, WorkspaceSendReceipt } from '@shared/workspace'
  5. export interface WorkspaceDetail {
  6. conversation: WorkspaceConversation
  7. messages: WorkspaceMessage[]
  8. task?: WorkspaceTask | null
  9. tasks?: WorkspaceTask[]
  10. assignments?: AgentAssignment[]
  11. run: WorkspaceRun | null
  12. interactions: WorkspaceInteraction[]
  13. context: Record<string, unknown> | null
  14. hiddenMessageIds?: string[]
  15. hasOlder?: boolean
  16. cursor?: number
  17. }
  18. export interface WorkspaceSnapshot {
  19. agents: WorkspaceAgent[]
  20. conversations: WorkspaceConversation[]
  21. details: WorkspaceDetail[]
  22. cursor: number
  23. }
  24. export const transcriptKey = (id: string, taskId?: string | null) => `${id}:${taskId ?? ''}`
  25. function upsert<T extends { id: string }>(rows: T[], value: T): T[] {
  26. const index = rows.findIndex(row => row.id === value.id)
  27. if (index < 0) return [...rows, value]
  28. const next = rows.slice(); next[index] = value; return next
  29. }
  30. /** Apply only the entity named by an event; settled message objects keep their identity. */
  31. export function foldDetail(detail: WorkspaceDetail, event: WorkspaceEvent): WorkspaceDetail {
  32. if (event.conversationId !== detail.conversation.id) return detail
  33. const data = event.data as Record<string, unknown>
  34. const inTask = (task: unknown) => (task ?? null) === (detail.task?.id ?? null)
  35. switch (event.type) {
  36. case 'conversation.changed': return { ...detail, conversation: event.data as WorkspaceConversation }
  37. case 'message.changed': {
  38. const message = event.data as WorkspaceMessage
  39. if (!inTask(message.conversationTaskId)) return detail
  40. const messages = message.visible === false ? detail.messages.filter(m => m.id !== message.id)
  41. : upsert(detail.messages, message).sort((a, b) => a.seq - b.seq)
  42. return { ...detail, messages }
  43. }
  44. case 'task.changed': {
  45. const task = event.data as WorkspaceTask
  46. return { ...detail, tasks: upsert(detail.tasks ?? [], task), task: detail.task?.id === task.id ? task : detail.task }
  47. }
  48. case 'task.deleted': return { ...detail, tasks: (detail.tasks ?? []).filter(t => t.id !== data.id) }
  49. case 'run.changed': return inTask(data.conversationTaskId) ? { ...detail, run: event.data as WorkspaceRun } : detail
  50. case 'context.changed': return inTask(data.conversationTaskId) ? { ...detail, context: data } : detail
  51. case 'interaction.changed': return inTask(data.conversationTaskId) ? { ...detail, interactions: data.resolved
  52. ? detail.interactions.filter(i => i.id !== data.id) : upsert(detail.interactions, event.data as WorkspaceInteraction) } : detail
  53. case 'assignment.changed': return data.goalId === detail.task?.id
  54. ? { ...detail, assignments: upsert(detail.assignments ?? [], event.data as AgentAssignment) } : detail
  55. case 'goal.changed': return data.id === detail.task?.id
  56. ? { ...detail, task: { ...detail.task!, goal: event.data as AgentGoal } } : detail
  57. default: return detail
  58. }
  59. }
  60. export class WorkspaceTranscriptStore {
  61. agents: WorkspaceAgent[] = []
  62. private conversationRows: WorkspaceConversation[] = []
  63. get conversations(): WorkspaceConversation[] { return this.conversationRows }
  64. set conversations(rows: WorkspaceConversation[]) {
  65. this.conversationRows = [...rows].sort(compareWorkspaceConversations)
  66. }
  67. readonly details = new Map<string, WorkspaceDetail>()
  68. cursor = 0
  69. readonly selectedTasks = new Map<string, string>()
  70. private reads = new Map<symbol, WorkspaceEvent[]>()
  71. private entityVersions = new Map<string, number>()
  72. private snapshotFloor = 0
  73. private messageReconciler = new WorkspaceMessageReconciler()
  74. readonly staleDetails = new Set<string>()
  75. acceptReceipt(receipt: WorkspaceSendReceipt): void {
  76. if (receipt.cursor === undefined) return
  77. for (const [type, data] of [['message.changed', receipt.message], ['run.changed', receipt.run],
  78. ['conversation.changed', receipt.conversation], ['task.changed', receipt.task]] as const) {
  79. if (data) this.accept({ seq: receipt.cursor, type, conversationId: receipt.run.conversationId, data })
  80. }
  81. }
  82. beginRead(): symbol { const token = Symbol(); this.reads.set(token, []); return token }
  83. cancelRead(token: symbol): void { this.reads.delete(token) }
  84. finishRead(token: symbol, incoming: WorkspaceDetail, preserveHistory = true): WorkspaceDetail {
  85. const key = transcriptKey(incoming.conversation.id, incoming.task?.id)
  86. const previous = this.details.get(key)
  87. if (previous && incoming.cursor !== undefined && incoming.cursor < this.snapshotFloor) {
  88. incoming = { ...previous, cursor: incoming.cursor, messages: incoming.messages,
  89. hiddenMessageIds: previous.hiddenMessageIds, hasOlder: previous.hasOlder }
  90. }
  91. let detail = incoming
  92. if (previous && preserveHistory) {
  93. const messages = new Map(previous.messages.map(message => [message.id, message]))
  94. for (const message of incoming.messages) {
  95. const current = messages.get(message.id)
  96. if (!current || (this.entityVersions.get(`message:${message.id}`) ?? this.snapshotFloor) <= (incoming.cursor ?? Number.MAX_SAFE_INTEGER)) messages.set(message.id, message)
  97. }
  98. detail = { ...incoming, hasOlder: previous.hasOlder,
  99. messages: [...messages.values()].filter(m => m.visible !== false && !incoming.hiddenMessageIds?.includes(m.id)).sort((a, b) => a.seq - b.seq) }
  100. }
  101. // A response that started before a live event must never overwrite that event.
  102. for (const event of this.reads.get(token) ?? []) {
  103. if (event.seq <= (incoming.cursor ?? 0)) continue
  104. const id = (event.data as { id?: string }).id
  105. if ((event.type === 'conversation.deleted' && id === incoming.conversation.id)
  106. || (event.type === 'task.deleted' && id === incoming.task?.id)) {
  107. this.reads.delete(token)
  108. throw new Error('会话或任务已被删除')
  109. }
  110. detail = foldDetail(detail, event)
  111. }
  112. this.reads.delete(token)
  113. this.details.set(key, detail); this.staleDetails.delete(key)
  114. for (const message of detail.messages) this.messageReconciler.remember(message)
  115. return detail
  116. }
  117. hydrate(snapshot: WorkspaceSnapshot): void {
  118. if (!snapshot || !Number.isSafeInteger(snapshot.cursor) || snapshot.cursor < 0
  119. || !Array.isArray(snapshot.agents) || !Array.isArray(snapshot.conversations) || !Array.isArray(snapshot.details)) {
  120. throw new Error('Bot 会话数据尚未就绪,正在重新同步')
  121. }
  122. const reset = snapshot.cursor === 0 && snapshot.conversations.length === 0
  123. const previous = new Map(reset ? [] : this.details)
  124. if (reset) this.reads.clear()
  125. const concurrent = [...this.reads.values()].flat().filter(event => event.seq > snapshot.cursor).sort((a, b) => a.seq - b.seq)
  126. this.entityVersions.clear(); this.snapshotFloor = snapshot.cursor; this.messageReconciler.clear()
  127. this.agents = snapshot.agents; this.conversations = snapshot.conversations; this.cursor = snapshot.cursor
  128. this.details.clear(); this.staleDetails.clear()
  129. for (const incoming of snapshot.details) {
  130. const key = transcriptKey(incoming.conversation.id, incoming.task?.id), old = previous.get(key)
  131. const messages = new Map(old?.messages.map(m => [m.id, m]))
  132. for (const message of incoming.messages) messages.set(message.id, message)
  133. const detail = old ? { ...incoming, hasOlder: old?.hasOlder ?? incoming.hasOlder,
  134. messages: [...messages.values()].filter(m => m.visible !== false && !incoming.hiddenMessageIds?.includes(m.id)).sort((a, b) => a.seq - b.seq) } : incoming
  135. this.details.set(key, detail)
  136. for (const message of detail.messages) this.messageReconciler.remember(message)
  137. }
  138. for (const [key, detail] of previous) {
  139. const conversation = snapshot.conversations.find(c => c.id === detail.conversation.id)
  140. const current = snapshot.details.find(d => d.conversation.id === detail.conversation.id)
  141. if (!this.details.has(key) && conversation && (conversation.archived || current?.tasks?.some(t => t.id === detail.task?.id))) {
  142. this.details.set(key, { ...detail, conversation }); this.staleDetails.add(key)
  143. }
  144. }
  145. for (const event of concurrent) this.accept(event)
  146. }
  147. get(id: string, taskId?: string | null): WorkspaceDetail | undefined {
  148. if (taskId) return this.details.get(transcriptKey(id, taskId))
  149. const remembered = this.selectedTasks.get(id)
  150. return (remembered ? this.details.get(transcriptKey(id, remembered)) : undefined)
  151. ?? [...this.details.values()].find(detail => detail.conversation.id === id)
  152. }
  153. apply(event: WorkspaceEvent): void {
  154. if (event.seq <= this.cursor) return
  155. this.accept(event)
  156. this.cursor = event.seq
  157. }
  158. private accept(event: WorkspaceEvent): void {
  159. event = this.messageReconciler.normalize(event)
  160. const data = event.data as { id: string }
  161. const key = `${event.type.split('.')[0]}:${data.id ?? event.conversationId}`
  162. if (event.seq < (this.entityVersions.get(key) ?? this.snapshotFloor)) return
  163. this.entityVersions.set(key, event.seq)
  164. for (const events of this.reads.values()) events.push(event)
  165. if (event.type === 'agent.changed') this.agents = upsert(this.agents, event.data as WorkspaceAgent)
  166. if (event.type === 'agent.deleted') this.agents = this.agents.filter(a => a.id !== data.id)
  167. if (event.type === 'conversation.changed') this.conversations = upsert(this.conversations, event.data as WorkspaceConversation)
  168. if (event.type === 'conversation.deleted') this.conversations = this.conversations.filter(c => c.id !== data.id)
  169. for (const [key, detail] of this.details) {
  170. if ((event.type === 'conversation.deleted' && detail.conversation.id === data.id)
  171. || (event.type === 'task.deleted' && detail.task?.id === data.id)) this.details.delete(key)
  172. else if (event.conversationId === detail.conversation.id) this.details.set(key, foldDetail(detail, event))
  173. }
  174. }
  175. }