{"version":3,"file":"AIConversationExchange.mjs","names":[],"sources":["../../../../../../src/plugins/AIComponents/Conversation/controller/AIConversationExchange.ts"],"sourcesContent":["import isEqual from 'react-fast-compare';\n\nimport type { AIMessageAttachmentData } from '../../Message/AIMessageAttachment';\nimport type { AIMessage, AIPendingMessage } from '../types';\nimport type { AIConversationRequest } from './types';\n\n// Where the request is: waiting for its reply, stopped by the person before it started, not\n// sent because the transport failed, or not answered by the agent.\nexport type AIConversationExchangeState = 'waiting' | 'stopped' | 'failed' | 'unanswered';\n\n/** Where a file the person picked shows from while it is on its way, such as an object URL. */\nexport type AIFileURLOf = (file: File) => string | undefined;\n\n// A reply the agent has started with no text, steps or attachments yet. Its generated UI can\n// still show, when the conversation's host reads it.\nexport const hasEmptyContent = (message: AIMessage) =>\n  message.role !== 'user' &&\n  message.text === '' &&\n  !message.parts?.length &&\n  !message.attachments?.length;\n\n// Whether a reply is written again since it was `original`: it started anew, or it shows\n// something else.\nconst isRewritten = (message: AIMessage, original: AIMessage) =>\n  (!!message.isGenerating && !original.isGenerating) ||\n  message.text !== original.text ||\n  !isEqual(message.parts ?? [], original.parts ?? []) ||\n  !isEqual(message.attachments ?? [], original.attachments ?? []) ||\n  !isEqual(message.uiDocument, original.uiDocument);\n\nexport const attachmentOfFile = (\n  file: File,\n  urlOf?: AIFileURLOf,\n): AIMessageAttachmentData => ({\n  kind: !file.type || file.type.startsWith('image') ? 'image' : 'file',\n  mimeType: file.type?.includes('/') ? file.type : undefined,\n  name: file.name,\n  size: file.size,\n  url: urlOf?.(file),\n});\n\n/** A unique id, such as for the person's message. */\nexport const generateId = () =>\n  typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n    ? crypto.randomUUID()\n    : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n\n// The latest request, until its reply starts or another request takes its place.\nexport class AIConversationExchange<Message extends AIMessage> {\n  state: AIConversationExchangeState = 'waiting';\n  // The messages there were when it was made, none of which is its reply.\n  readonly known: Set<string>;\n  // The messages it replaces, as they were, which the conversation leaves out while it waits:\n  // the reply written again, or the message edited, and those after it.\n  readonly replaced: Map<string, Message>;\n  // The person's message on its way.\n  readonly pending: AIPendingMessage | undefined;\n\n  constructor(\n    // Tells it apart from the requests before and after it.\n    readonly id: number,\n    readonly request: AIConversationRequest<Message>,\n    conversation: readonly Message[],\n    // Where the files the person picked show from while their message is on its way.\n    urlOf?: AIFileURLOf,\n  ) {\n    this.known = new Set(conversation.map((message) => message.id));\n    const target = request.message\n      ? conversation.findIndex((message) => message.id === request.message?.id)\n      : -1;\n    this.replaced = new Map(\n      target >= 0 && (request.kind === 'regenerate' || request.kind === 'edit')\n        ? conversation.slice(target).map((message) => [message.id, message])\n        : [],\n    );\n    if (request.kind === 'regenerate') {\n      this.pending = undefined;\n    } else {\n      const edited = request.kind === 'edit' ? (request.message?.attachments ?? []) : [];\n      this.pending = {\n        attachments: [\n          ...edited,\n          ...request.attachments.map((file) => attachmentOfFile(file, urlOf)),\n        ],\n        id: request.messageId,\n        text: request.text,\n      };\n    }\n  }\n\n  get hasFailed() {\n    return this.state === 'failed' || this.state === 'unanswered';\n  }\n\n  // The person's message while the conversation shows it: until its reply starts, and for a\n  // new message also once it is stopped or failed, since the agent may have it, or `retry()`\n  // sends it again. The messages an edit replaces come back instead.\n  get shownPending() {\n    return this.state === 'waiting' || this.request.kind === 'message'\n      ? this.pending\n      : undefined;\n  }\n\n  // The latest message when it is the request's reply: a reply that wasn't there, or one the\n  // request replaces, once it is written again.\n  reply(conversation: readonly Message[]) {\n    const last = conversation[conversation.length - 1];\n    if (!last || last.role === 'user') return undefined;\n    const original = this.replaced.get(last.id);\n    const rewritten = original ? isRewritten(last, original) : false;\n    return !this.known.has(last.id) || rewritten ? last : undefined;\n  }\n\n  // Whether its reply has started: it shows something, or it is already finished.\n  hasReplyStarted(conversation: readonly Message[]) {\n    const reply = this.reply(conversation);\n    return !!reply && (!hasEmptyContent(reply) || !reply.isGenerating);\n  }\n\n  // Whether the person's message is in the conversation: one with its id, or one of theirs\n  // after the messages there were.\n  hasMessageArrived(conversation: readonly Message[]) {\n    if (conversation.some((message) => message.id === this.request.messageId))\n      return true;\n    let lastKnown = -1;\n    conversation.forEach((message, index) => {\n      if (this.known.has(message.id)) lastKnown = index;\n    });\n    return conversation.slice(lastKnown + 1).some((message) => message.role === 'user');\n  }\n\n  // What `retry()` sends: the request again, or, when the agent had the person's message but\n  // couldn't answer it, a request for its reply, since sending it again would add it twice.\n  retryRequest(conversation: readonly Message[]): AIConversationRequest<Message> {\n    if (\n      this.state !== 'unanswered' ||\n      this.request.kind !== 'message' ||\n      !this.hasMessageArrived(conversation)\n    ) {\n      return this.request;\n    }\n    return {\n      attachments: [],\n      kind: 'regenerate',\n      messageId: generateId(),\n      text: this.request.text,\n    };\n  }\n}\n"],"mappings":";;AAeA,IAAa,mBAAmB,YAC9B,QAAQ,SAAS,UACjB,QAAQ,SAAS,MACjB,CAAC,QAAQ,OAAO,UAChB,CAAC,QAAQ,aAAa;AAIxB,IAAM,eAAe,SAAoB,aACtC,CAAC,CAAC,QAAQ,gBAAgB,CAAC,SAAS,gBACrC,QAAQ,SAAS,SAAS,QAC1B,CAAC,UAAQ,QAAQ,SAAS,CAAC,GAAG,SAAS,SAAS,CAAC,CAAC,KAClD,CAAC,UAAQ,QAAQ,eAAe,CAAC,GAAG,SAAS,eAAe,CAAC,CAAC,KAC9D,CAAC,UAAQ,QAAQ,YAAY,SAAS,UAAU;AAElD,IAAa,oBACX,MACA,WAC6B;CAC7B,MAAM,CAAC,KAAK,QAAQ,KAAK,KAAK,WAAW,OAAO,IAAI,UAAU;CAC9D,UAAU,KAAK,MAAM,SAAS,GAAG,IAAI,KAAK,OAAO,KAAA;CACjD,MAAM,KAAK;CACX,MAAM,KAAK;CACX,KAAK,QAAQ,IAAI;AACnB;;AAGA,IAAa,mBACX,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,aAC1D,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,C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