{"version":3,"file":"entries.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/Conversation/entries.ts"],"sourcesContent":["import type { AIUIDocument } from '../GenerativeUI/AIUIDocument';\nimport type { AIMessageAttachmentData } from '../Message/AIMessageAttachment';\nimport type { AIMessage, AIPendingMessage } from './types';\n\n/** A row of the conversation: a message, or a message the person sent that is on its way. */\nexport type AIConversationEntry = {\n  /** The message's id, or, for the copy of a message that was on its way, that message's. */\n  id: string;\n  isFromUser: boolean;\n  /** Whether it is a reply that ends the conversation. */\n  isLatestReply: boolean;\n  /** The message, or `undefined` for one on its way. */\n  message?: AIMessage;\n  /** The message on its way, until its copy arrives. */\n  pending?: AIPendingMessage;\n  /** What the person sent with a message on its way, which its copy shows rather than load it again. */\n  sentAttachments: AIMessageAttachmentData[];\n};\n\n/** The person's message and the replies to it. */\nexport type AIConversationTurn = { entries: AIConversationEntry[]; id: string };\n\n/** Whether a reply's generated UI shows, such as `AIUIHost.canShow`. */\nexport type AIConversationCanShowUI = (document: AIUIDocument) => boolean;\n\nconst showsNoUI: AIConversationCanShowUI = () => false;\n\n// The id of the person's newest message, looked for from the end: the copy of one they just sent\n// is always it, and while a reply is written it is a step or two from the end.\nconst newestFromUserOf = (messages: AIMessage[]) => {\n  for (let index = messages.length - 1; index >= 0; index -= 1) {\n    if (messages[index].role === 'user') return messages[index].id;\n  }\n  return undefined;\n};\n\n// A reply the agent has started but that has nothing to show yet: no text, steps or attachments,\n// and no UI that `canShowUI` says shows.\nconst showsNothing = (message: AIMessage, canShowUI: AIConversationCanShowUI) =>\n  message.role !== 'user' &&\n  message.text === '' &&\n  !message.parts?.length &&\n  !message.attachments?.length &&\n  !(message.uiDocument && canShowUI(message.uiDocument));\n\n/**\n * Groups the rows into turns, each starting with one of the person's messages. A row that\n * started a turn, kept in `starts`, keeps starting one: a reply that opened the first page loaded\n * stays the start of its turn when older messages load above it, so the turn keeps its key.\n */\nexport const turnsOf = (entries: AIConversationEntry[], starts = new Set<string>()) =>\n  entries.reduce<AIConversationTurn[]>((turns, entry) => {\n    const last = turns[turns.length - 1];\n    if (!last || entry.isFromUser || starts.has(entry.id)) {\n      starts.add(entry.id);\n      turns.push({ entries: [entry], id: entry.id });\n    } else last.entries.push(entry);\n    return turns;\n  }, []);\n\n/**\n * Follows a message the person sent until its copy arrives in the messages, so the copy takes\n * over its row (and its key) without a flicker, and tells whether the agent is surely about to\n * answer. The counterpart of `AIPendingMessageTracker`.\n */\nexport class AIPendingMessageTracker {\n  // The person's messages each pending message's copy cannot be: those there were when it was\n  // first seen, and those that arrived since without being its copy, such as older ones.\n  private seen = new Map<string, Set<string>>();\n  // The pending message each copy took over, by the copy's id.\n  private copies = new Map<string, AIPendingMessage>();\n  // The pending message of the last update, whose copy can arrive in the update that stops\n  // passing it.\n  private lastPending?: AIPendingMessage;\n  // The person's newest message as of the last update, `null` before the first one. A message on\n  // its way first seen in an update that also brings its copy finds it as the person's newest\n  // message, when that one is new.\n  private lastNewestFromUser: string | null | undefined = null;\n\n  // The rows of a conversation: its messages, apart from replies with nothing to show yet, and\n  // a message on its way until its copy arrives. A reply's UI shows when `canShowUI` says.\n  entries(\n    messages: AIMessage[],\n    pending?: AIPendingMessage | null,\n    canShowUI: AIConversationCanShowUI = showsNoUI,\n  ): AIConversationEntry[] {\n    let showsPending = !!pending;\n    const newestFromUser = newestFromUserOf(messages);\n    // A copy that arrives in the update that stops passing its pending message still takes over\n    // its row. Only then: a message sent later is not the copy of one that failed.\n    const awaited = pending ?? this.lastPending;\n    if (awaited) {\n      const sent = messages.filter((message) => message.role === 'user');\n      const ids = new Set(sent.map((message) => message.id));\n      let known = this.seen.get(awaited.id);\n      if (!known) {\n        known = new Set(ids);\n        // The person's message that arrived with this update can be the copy.\n        const arrived =\n          this.lastNewestFromUser !== null && newestFromUser !== this.lastNewestFromUser;\n        if (arrived && newestFromUser !== undefined) known.delete(newestFromUser);\n      }\n      const matched = [...this.copies].find(\n        ([copyId, original]) => original.id === awaited.id && ids.has(copyId),\n      )?.[0];\n      const copy = matched ?? this.copyOf(awaited, sent, known);\n      if (copy !== undefined) {\n        if (!this.copies.has(copy)) this.copies.set(copy, awaited);\n        showsPending = false;\n      } else {\n        this.seen.set(awaited.id, new Set([...known, ...ids]));\n      }\n    }\n    this.lastPending = pending ?? undefined;\n    this.lastNewestFromUser = newestFromUser;\n\n    const entries: AIConversationEntry[] = messages\n      .filter((message) => !showsNothing(message, canShowUI))\n      .map((message) => {\n        const taken = this.copies.get(message.id);\n        return {\n          id: taken?.id ?? message.id,\n          isFromUser: message.role === 'user',\n          isLatestReply: false,\n          message,\n          sentAttachments: taken?.attachments ?? [],\n        };\n      });\n    if (showsPending && pending) {\n      entries.push({\n        id: pending.id,\n        isFromUser: true,\n        isLatestReply: false,\n        pending,\n        sentAttachments: [],\n      });\n    }\n    const last = entries[entries.length - 1];\n    if (last && !last.isFromUser) last.isLatestReply = true;\n    return entries;\n  }\n\n  // The copy of a message that was on its way: the person's message with its id, when the app\n  // knew it. Otherwise their first after those known, which older messages loading above cannot\n  // be. With none of theirs known, it is their latest, when that is the only new one or says the\n  // same.\n  private copyOf(pending: AIPendingMessage, sent: AIMessage[], known: Set<string>) {\n    const ids = sent.map((message) => message.id);\n    if (ids.includes(pending.id)) return pending.id;\n    let lastKnown = -1;\n    ids.forEach((id, index) => {\n      if (known.has(id)) lastKnown = index;\n    });\n    if (lastKnown >= 0) return ids[lastKnown + 1];\n    const fresh = sent.filter((message) => !known.has(message.id));\n    const latest = fresh[fresh.length - 1];\n    if (!latest || (fresh.length !== 1 && latest.text !== pending.text)) return undefined;\n    return latest.id;\n  }\n\n  // Whether the latest message is surely waiting for a reply that shows nothing yet: it is on its\n  // way, it is the copy of the one on its way, or its reply is being written but shows nothing.\n  // Call it after `entries`, which matches the copies.\n  isAwaitingReply(\n    messages: AIMessage[],\n    pending?: AIPendingMessage | null,\n    canShowUI: AIConversationCanShowUI = showsNoUI,\n  ) {\n    const last = messages[messages.length - 1];\n    if (\n      last &&\n      last.role !== 'user' &&\n      last.isGenerating &&\n      showsNothing(last, canShowUI)\n    )\n      return true;\n    if (!pending) return false;\n    const copy = [...this.copies].find(([, original]) => original.id === pending.id)?.[0];\n    if (copy === undefined) return true;\n    return last?.id === copy;\n  }\n}\n"],"mappings":";AAyBA,IAAM,kBAA2C;AAIjD,IAAM,oBAAoB,aAA0B;CAClD,KAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,SAAS,GAAG,SAAS,GACzD,IAAI,SAAS,MAAM,CAAC,SAAS,QAAQ,OAAO,SAAS,MAAM,CAAC;AAGhE;AAIA,IAAM,gBAAgB,SAAoB,cACxC,QAAQ,SAAS,UACjB,QAAQ,SAAS,MACjB,CAAC,QAAQ,OAAO,UAChB,CAAC,QAAQ,aAAa,UACtB,EAAE,QAAQ,cAAc,UAAU,QAAQ,UAAU;;;;;;AAOtD,IAAa,WAAW,SAAgC,yBAAS,IAAI,IAAY,MAC/E,QAAQ,QAA8B,OAAO,UAAU;CACrD,MAAM,OAAO,MAAM,MAAM,SAAS;CAClC,IAAI,CAAC,QAAQ,MAAM,cAAc,OAAO,IAAI,MAAM,EAAE,GAAG;EACrD,OAAO,IAAI,MAAM,EAAE;EACnB,MAAM,KAAK;GAAE,SAAS,CAAC,KAAK;GAAG,IAAI,MAAM;EAAG,CAAC;CAC/C,OAAO,KAAK,QAAQ,KAAK,KAAK;CAC9B,OAAO;AACT,GAAG,CAAC,CAAC;;;;;;AAOP,IAAa,0BAAb,MAAqC;CAGnC,uBAAe,IAAI,IAAyB;CAE5C,yBAAiB,IAAI,IAA8B;CAGnD;CAIA,qBAAwD;CAIxD,QACE,UACA,SACA,YAAqC,WACd;EACvB,IAAI,eAAe,CAAC,CAAC;EACrB,MAAM,iBAAiB,iBAAiB,QAAQ;EAGhD,MAAM,UAAU,WAAW,KAAK;EAChC,IAAI,SAAS;GACX,MAAM,OAAO,SAAS,QAAQ,YAAY,QAAQ,SAAS,MAAM;GACjE,MAAM,MAAM,IAAI,IAAI,KAAK,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