{"version":3,"file":"AIConversation.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/Conversation/AIConversation.tsx"],"sourcesContent":["import React, {\n  type ComponentType,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\nimport clsx from 'clsx';\n\nimport { useTranslationContext } from '../../../context/TranslationContext';\nimport { useComponentContextIcons } from '../../../context/useComponentContextIcons';\nimport type { AIUIHost } from '../GenerativeUI/AIUIHost';\nimport { AIUIGenerated, useAIUIHostRefresh } from '../GenerativeUI/AIUIView';\nimport { AIAssistantMessage } from '../Message/AIAssistantMessage';\nimport type { AIMessageAttachmentData } from '../Message/AIMessageAttachment';\nimport { AIReplyActions, type AIReplyActionsProps } from '../Message/AIReplyActions';\nimport { AIUserMessage } from '../Message/AIUserMessage';\nimport type { AIMessagePartData } from '../MessageParts/types';\nimport { AIThinking } from '../Reasoning/AIReasoning';\nimport { AIThinkingClock, AIThinkingTurnContext } from '../Reasoning/thinkingClock';\nimport { type AIToolApprover, AIToolApproverProvider } from '../ToolCalls/AIToolApprover';\nimport { prefersReducedMotion, useIsomorphicLayoutEffect } from '../utils';\nimport {\n  type AIConversationEntry,\n  type AIConversationTurn,\n  AIPendingMessageTracker,\n  turnsOf,\n} from './entries';\nimport type { AIMessage, AIPendingMessage } from './types';\nimport { ThemeScopeProvider, useAIThemeScopeClassName } from '../themeScope';\nimport type {\n  AIConversationController,\n  AIConversationControllerState,\n} from './controller/AIConversationController';\nimport { editActionOf, latestUserMessageIdOf, replyActionsOf } from './controller/offers';\nimport { useAIConversationState } from './controller/useAIConversationState';\n\n// How far from the end still counts as at the end, in pixels.\nconst END_SLACK = 32;\n// How long the spinner above the turns stays in view before older messages load, so a list\n// that opens at its end does not load for the frame its start shows.\nconst LOAD_OLDER_DELAY_MS = 300;\n// How long to wait before asking again after loading older messages failed.\nconst LOAD_OLDER_RETRY_MS = 3000;\n\nexport type AIConversationUserMessageProps = {\n  /** What the person sent with it, such as images and files. */\n  attachments: AIMessageAttachmentData[];\n  /** What the person wrote. */\n  text: string;\n  /** The message, or `undefined` for one on its way. */\n  message?: AIMessage;\n  /** Edits the message: a `conversation` offers it on the person's latest message. */\n  onEdit?: () => void;\n};\n\nexport type AIConversationAssistantMessageProps = {\n  attachments: AIMessageAttachmentData[];\n  isGenerating: boolean;\n  message: AIMessage;\n  parts: AIMessagePartData[];\n  /**\n   * Whether the UI the agent wrote for the reply shows, in place of its words, which `text` then\n   * leaves out. `false` for a reply with no UI, one the conversation's `ui` host has no renderer\n   * for, one whose renderer shows nothing of it, and one whose UI failed (`uiFailed`). A reply\n   * that is neither generating nor showing UI, with no `text`, finished without a text reply,\n   * for which a message can show a status of its own.\n   */\n  showsUI: boolean;\n  /** What the reply says, or `''` while its UI shows in place of its words (`showsUI`). */\n  text: string;\n  /**\n   * Whether the reply has UI that failed to show (`AIUIHost.fail`), so its words, if any, show\n   * instead. The message renders again when it fails, whether or not it is memoised.\n   */\n  uiFailed: boolean;\n  approver?: AIToolApprover;\n  reasoningText?: (stepId: string) => string | undefined;\n};\n\nexport type AIConversationReplyActionsProps = {\n  /** Whether it is the reply that ends the conversation, which can be asked for again. */\n  isLatestReply: boolean;\n  message: AIMessage;\n  text: string;\n};\n\nexport type AIConversationProps = {\n  /**\n   * The conversation's state and what the person does in it, such as an\n   * `AIConversationController`. The conversation shows its messages, the message on its way and\n   * whether the agent thinks, loads its older messages, and offers rating and regenerating\n   * replies and editing the person's latest message. It takes the place of `messages`,\n   * `pendingMessage`, `isThinking` and `loadOlderMessages`, its reply actions are used unless\n   * `replyActions` is passed, and its `approver` unless one is passed.\n   */\n  conversation?: AIConversationController;\n  /** The conversation, oldest message first. Required without `conversation`. */\n  messages?: AIMessage[];\n  /** Who answers tool calls' questions and sign-ins on this device, to ask them. */\n  approver?: AIToolApprover;\n  /** The view of the agent's replies. Defaults to `AIAssistantMessage`. */\n  AssistantMessage?: ComponentType<AIConversationAssistantMessageProps>;\n  /**\n   * Room left under the latest turn, in pixels, for a composer floating over the bottom of the\n   * conversation. The question of a new turn pins to the top of what is visible above it.\n   */\n  bottomInset?: number;\n  className?: string;\n  /** What the conversation shows while there are no messages, centered in it. */\n  emptyContent?: ReactNode;\n  /** A view under the latest turn's messages, such as what the agent is doing, or an error with a way to retry. */\n  footer?: ReactNode;\n  /**\n   * Whether the agent is answering the latest message and its reply shows nothing yet.\n   * Meanwhile the latest turn ends with `AIThinking`, and the reply's first reasoning step takes\n   * over its seconds. The conversation also knows it is while `pendingMessage` waits, and while\n   * the latest reply is being written but shows nothing.\n   */\n  isThinking?: boolean;\n  /**\n   * Loads the messages before the first one, which the conversation asks for as the person\n   * scrolls to its start. It shows a spinner meanwhile, and what is on screen stays in place as\n   * they arrive. Pass `undefined` once there are none left.\n   */\n  loadOlderMessages?: () => Promise<unknown> | void;\n  /**\n   * A message the person sent that is not in `messages` yet. Keep passing it until its reply\n   * starts: the conversation stops showing it once its copy arrives.\n   */\n  pendingMessage?: AIPendingMessage | null;\n  /** The actions under each finished reply. Defaults to `AIReplyActions`; `null` shows none. */\n  ReplyActions?: ComponentType<AIConversationReplyActionsProps> | null;\n  /**\n   * What the default `AIReplyActions` offers for a reply besides copy and share, such as its\n   * rating and how to rate or regenerate it.\n   */\n  replyActions?: (\n    message: AIMessage,\n    context: { isLatestReply: boolean },\n  ) => Omit<AIReplyActionsProps, 'text'> | undefined;\n  /**\n   * Shows the UI the agent writes for its replies (`AIMessage.uiDocument`) in place of their\n   * text, with the renderers of the formats it writes, such as A2UI. A reply whose UI none of\n   * them shows shows its text. Keep one host per conversation, for as long as it shows.\n   */\n  ui?: AIUIHost;\n  /** The view of the person's messages. Defaults to `AIUserMessage`. */\n  UserMessage?: ComponentType<AIConversationUserMessageProps>;\n};\n\nconst DefaultUserMessage = ({\n  attachments,\n  onEdit,\n  text,\n}: AIConversationUserMessageProps) => (\n  <AIUserMessage attachments={attachments} onEdit={onEdit} text={text} />\n);\n\nconst NO_MESSAGES: AIMessage[] = [];\n\ntype EditAction = (message: AIMessage) => (() => void) | undefined;\n\nconst DefaultAssistantMessage = ({\n  approver,\n  attachments,\n  isGenerating,\n  parts,\n  reasoningText,\n  text,\n}: AIConversationAssistantMessageProps) => (\n  <AIAssistantMessage\n    approver={approver}\n    attachments={attachments}\n    isGenerating={isGenerating}\n    parts={parts}\n    reasoningText={reasoningText}\n    text={text}\n  />\n);\n\ntype EntryViewProps = {\n  AssistantMessage: ComponentType<AIConversationAssistantMessageProps>;\n  editAction?: EditAction;\n  entry: AIConversationEntry;\n  ReplyActions: ComponentType<AIConversationReplyActionsProps> | null;\n  UserMessage: ComponentType<AIConversationUserMessageProps>;\n  approver?: AIToolApprover;\n  ui?: AIUIHost;\n};\n\n// Not memoised: an app's messages are new objects on every update while a reply streams, and a\n// rating given through `replyActions` must reach the reply's actions whether or not they are.\nconst EntryView = ({\n  approver,\n  AssistantMessage,\n  editAction,\n  entry,\n  ReplyActions,\n  ui,\n  UserMessage,\n}: EntryViewProps) => {\n  const { message, pending } = entry;\n  if (!message) {\n    return pending ? (\n      <UserMessage attachments={pending.attachments ?? []} text={pending.text} />\n    ) : null;\n  }\n  if (message.role === 'user') {\n    return (\n      <UserMessage\n        attachments={\n          entry.sentAttachments.length\n            ? entry.sentAttachments\n            : (message.attachments ?? [])\n        }\n        message={message}\n        onEdit={editAction?.(message)}\n        text={message.text}\n      />\n    );\n  }\n  // The UI the agent generated for the reply, when one of the host's renderers shows it. It\n  // shows in place of the reply's text, after the reply's steps.\n  const { uiDocument } = message;\n  const generated = ui && uiDocument ? ui.content(uiDocument, message.id) : null;\n  const showsUI = !!uiDocument && generated !== null && generated !== undefined;\n  const uiFailed = !!uiDocument && !!ui?.hasFailed(message.id);\n  // A finished reply has its actions under it whether it answers in text or in UI, once the\n  // UI is written.\n  const hasAnswer = message.text !== '' || showsUI;\n  const isWritingUI = showsUI && uiDocument.isStreaming;\n  return (\n    <div className='str-chat__ai-conversation__reply'>\n      <AssistantMessage\n        approver={approver}\n        attachments={message.attachments ?? []}\n        isGenerating={!!message.isGenerating}\n        message={message}\n        parts={message.parts ?? []}\n        reasoningText={message.reasoningText}\n        showsUI={showsUI}\n        text={showsUI ? '' : message.text}\n        uiFailed={uiFailed}\n      />\n      {showsUI && (\n        <AIUIGenerated\n          isStreaming={uiDocument.isStreaming}\n          onError={(error) => ui?.fail(message.id, error)}\n        >\n          {generated}\n        </AIUIGenerated>\n      )}\n      {ReplyActions && !message.isGenerating && hasAnswer && !isWritingUI && (\n        <ReplyActions\n          isLatestReply={entry.isLatestReply}\n          message={message}\n          text={message.text}\n        />\n      )}\n    </div>\n  );\n};\n\ntype HeldTurn = { id: string; top: number };\n\n// The turn's first reasoning step, which takes over the seconds the turn was seen thinking.\nconst firstStepOf = (turn: AIConversationTurn | undefined) => {\n  for (const { message } of turn?.entries ?? []) {\n    if (!message || message.role === 'user') continue;\n    const step = message.parts?.find((part) => part.reasoning);\n    if (step) return step.id;\n  }\n  return undefined;\n};\n\nconst scrollScroller = (scroller: HTMLElement, top: number, smooth: boolean) => {\n  if (typeof scroller.scrollTo !== 'function') {\n    scroller.scrollTop = top;\n    return;\n  }\n  scroller.scrollTo({\n    behavior: smooth && !prefersReducedMotion() ? 'smooth' : 'auto',\n    top,\n  });\n};\n\n/**\n * The conversation with an AI agent, laid out by turn: each of the person's questions starts\n * a turn, with the agent's reply under it. The counterpart of `AIConversationView`.\n *\n * - A new question pins to the top of what is visible, and the reply writes out below it,\n *   without moving what is on screen. The latest turn is at least as tall as the conversation.\n * - It opens at the end; older messages load as the person scrolls to the start, and what is\n *   on screen stays in place as they arrive.\n * - A button scrolls back to the latest message when the end is out of view.\n * - A message the person sent shows at once (`pendingMessage`) and the agent thinks under it\n *   (`AIThinking`) until its reply shows something.\n *\n * With a `conversation`, such as an `AIConversationController`, it shows the conversation's\n * state and offers what the person can do in it. Without one, pass its `messages` and the rest.\n */\nexport const AIConversation = (props: AIConversationProps) =>\n  props.conversation ? (\n    <ControlledConversation {...props} conversation={props.conversation} />\n  ) : (\n    <ConversationView {...props} />\n  );\n\nconst controlledSelector = ({\n  hasOlderMessages,\n  messages,\n  pendingMessage,\n  ratings,\n  status,\n}: AIConversationControllerState) => ({\n  hasOlderMessages,\n  messages,\n  pendingMessage,\n  ratings,\n  status,\n});\n\n// The conversation as its controller has it. The controller knows when its agent is thinking,\n// including after a stop or a failure that leaves the person's message on its way.\nconst ControlledConversation = ({\n  conversation,\n  ...props\n}: AIConversationProps & { conversation: AIConversationController }) => {\n  const { hasOlderMessages, messages, pendingMessage, ratings, status } =\n    useAIConversationState(conversation, controlledSelector);\n  const replyActions = useMemo(\n    () =>\n      (message: AIMessage, { isLatestReply }: { isLatestReply: boolean }) =>\n        replyActionsOf(conversation, { ratings, status }, message, isLatestReply),\n    [conversation, ratings, status],\n  );\n  const latestUserMessageId = latestUserMessageIdOf(messages);\n  const editAction = useMemo<EditAction>(\n    () => (message) =>\n      editActionOf(conversation, { latestUserMessageId, status }, message),\n    [conversation, latestUserMessageId, status],\n  );\n  const { ui } = props;\n  // A reply that shows only its UI has started, which the controller can't tell without the\n  // host that reads it.\n  const last = messages[messages.length - 1];\n  const showsReply =\n    !!last && last.role !== 'user' && !!last.uiDocument && !!ui?.canShow(last.uiDocument);\n  return (\n    <ConversationView\n      {...props}\n      approver={props.approver ?? conversation.approver}\n      editAction={editAction}\n      isThinking={status === 'submitted' && !showsReply}\n      isThinkingKnown\n      loadOlderMessages={hasOlderMessages ? conversation.loadOlderMessages : undefined}\n      messages={messages as AIMessage[]}\n      pendingMessage={pendingMessage}\n      replyActions={props.replyActions ?? replyActions}\n    />\n  );\n};\n\ntype ConversationViewProps = Omit<AIConversationProps, 'conversation'> & {\n  editAction?: EditAction;\n  // Whether `isThinking` alone says whether the agent is thinking.\n  isThinkingKnown?: boolean;\n};\n\nconst ConversationView = ({\n  approver,\n  AssistantMessage = DefaultAssistantMessage,\n  bottomInset = 0,\n  className,\n  editAction,\n  emptyContent,\n  footer,\n  isThinking = false,\n  isThinkingKnown = false,\n  loadOlderMessages,\n  messages = NO_MESSAGES,\n  pendingMessage,\n  ReplyActions: ReplyActionsProp,\n  replyActions,\n  ui,\n  UserMessage = DefaultUserMessage,\n}: ConversationViewProps) => {\n  const themeScopeClassName = useAIThemeScopeClassName();\n  const { t } = useTranslationContext();\n  const { IconArrowDown, IconLoading } = useComponentContextIcons();\n\n  const [tracker] = useState(() => new AIPendingMessageTracker());\n  const [clock] = useState(() => new AIThinkingClock());\n\n  // Every reply's UI reaches its renderer before any row asks for its view, oldest first,\n  // whether or not the row is on screen. Only what arrived or changed is passed on. The rows\n  // show again when the host says what one of them shows changed.\n  useAIUIHostRefresh(ui);\n  ui?.receive(messages);\n  const canShowUI = useMemo(() => (ui ? ui.canShow.bind(ui) : undefined), [ui]);\n  const entries = useMemo(\n    () => tracker.entries(messages, pendingMessage, canShowUI),\n    [canShowUI, messages, pendingMessage, tracker],\n  );\n  // after `entries`, which matched the copies\n  const thinking = isThinkingKnown\n    ? isThinking\n    : isThinking || tracker.isAwaitingReply(messages, pendingMessage, canShowUI);\n  // The rows that started a turn keep starting one, so a turn keeps its key as older messages\n  // load above it.\n  const turnStarts = useRef(new Set<string>());\n  const turns = useMemo(() => turnsOf(entries, turnStarts.current), [entries]);\n  const latest = turns[turns.length - 1];\n  const latestHasReplies = (latest?.entries.length ?? 0) > 1;\n  const latestHasFirstStep = firstStepOf(latest) !== undefined;\n  // Before the views below read it in their effects and next renders: a turn's thinking starts\n  // and ends once.\n  useIsomorphicLayoutEffect(() => {\n    clock.update(latest?.id, thinking, latestHasReplies, latestHasFirstStep);\n  }, [clock, latest?.id, latestHasFirstStep, latestHasReplies, thinking]);\n\n  const replyActionsRef = useRef(replyActions);\n  replyActionsRef.current = replyActions;\n  const DefaultReplyActions = useMemo(() => {\n    const ConversationReplyActions = ({\n      isLatestReply,\n      message,\n      text,\n    }: AIConversationReplyActionsProps) => (\n      <AIReplyActions\n        {...replyActionsRef.current?.(message, { isLatestReply })}\n        text={text}\n      />\n    );\n    return ConversationReplyActions;\n  }, []);\n  const ReplyActions =\n    ReplyActionsProp === undefined ? DefaultReplyActions : ReplyActionsProp;\n\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  const turnElements = useRef(new Map<string, HTMLDivElement>());\n  const [height, setHeight] = useState(0);\n  const [isEndInView, setIsEndInView] = useState(true);\n  const lastTurnIdRef = useRef<string | undefined>(undefined);\n  lastTurnIdRef.current = latest?.id;\n  const bottomInsetRef = useRef(bottomInset);\n  bottomInsetRef.current = bottomInset;\n\n  // The end is where the latest turn's content ends, above the floating composer: not the\n  // room the latest turn's minimum height leaves under a short reply.\n  const checkEnd = useCallback(() => {\n    const scroller = scrollerRef.current;\n    if (!scroller) return;\n    const turn =\n      lastTurnIdRef.current === undefined\n        ? undefined\n        : turnElements.current.get(lastTurnIdRef.current);\n    const last = turn?.lastElementChild as HTMLElement | null | undefined;\n    const end = last\n      ? last.offsetTop + last.offsetHeight\n      : scroller.scrollHeight - bottomInsetRef.current;\n    const visibleEnd =\n      scroller.scrollTop + scroller.clientHeight - bottomInsetRef.current;\n    setIsEndInView(end <= visibleEnd + END_SLACK);\n  }, []);\n\n  useIsomorphicLayoutEffect(() => {\n    const scroller = scrollerRef.current;\n    if (!scroller) return;\n    setHeight(scroller.clientHeight);\n    if (typeof ResizeObserver === 'undefined') return;\n    const observer = new ResizeObserver(() => {\n      setHeight(scroller.clientHeight);\n      checkEnd();\n    });\n    observer.observe(scroller);\n    return () => observer.disconnect();\n  }, [checkEnd]);\n\n  // Content that grows without this component rendering, such as an answer typing out or an\n  // image loading, moves the end too.\n  const hasTurns = turns.length > 0;\n  useEffect(() => {\n    const content = contentRef.current;\n    if (!content || typeof ResizeObserver === 'undefined') return;\n    const observer = new ResizeObserver(() => checkEnd());\n    observer.observe(content);\n    return () => observer.disconnect();\n  }, [checkEnd, hasTurns]);\n\n  // Where the turns in view were, the one at the top first, so older messages arriving above\n  // them leave them in place.\n  const held = useRef<HeldTurn[]>([]);\n  const noteHeld = useCallback(() => {\n    const scroller = scrollerRef.current;\n    if (!scroller) return;\n    const top = scroller.scrollTop;\n    const bottom = top + scroller.clientHeight;\n    held.current = [...turnElements.current]\n      .map(([id, element]) => ({ element, id }))\n      .filter(\n        ({ element }) =>\n          element.offsetTop + element.offsetHeight > top && element.offsetTop < bottom,\n      )\n      .sort((a, b) => a.element.offsetTop - b.element.offsetTop)\n      .map(({ element, id }) => ({ id, top: element.offsetTop - top }));\n  }, []);\n\n  // Noting where the turns are reads the layout of each, so scrolling does it once a frame.\n  const scrollFrame = useRef<number | undefined>(undefined);\n  const onScroll = () => {\n    if (scrollFrame.current !== undefined) return;\n    scrollFrame.current = requestAnimationFrame(() => {\n      scrollFrame.current = undefined;\n      noteHeld();\n      checkEnd();\n    });\n  };\n  useEffect(() => () => cancelAnimationFrame(scrollFrame.current ?? 0), []);\n\n  const scrollToEnd = useCallback((smooth: boolean) => {\n    const scroller = scrollerRef.current;\n    if (scroller) scrollScroller(scroller, scroller.scrollHeight, smooth);\n  }, []);\n\n  const firstTurnId = turns[0]?.id;\n  const lastTurnId = latest?.id;\n  const loadsOlder = !!loadOlderMessages && turns.length > 0;\n  const shown = useRef<{\n    firstTurnId?: string;\n    height: number;\n    lastTurnId?: string;\n    loadsOlder: boolean;\n    mounted: boolean;\n  }>({ height: 0, loadsOlder, mounted: false });\n\n  // Runs when the turns around what is in view change, not on every render: a reply streaming in\n  // grows only the latest turn, which the observers above follow.\n  useIsomorphicLayoutEffect(() => {\n    const previous = shown.current;\n    shown.current = { firstTurnId, height, lastTurnId, loadsOlder, mounted: true };\n    const scroller = scrollerRef.current;\n    if (!scroller) return;\n\n    // Opens at its end, and again once its height is known, which sets the latest turn's\n    // minimum height and so where the end is.\n    if (!previous.mounted || (previous.height === 0 && height > 0)) {\n      scroller.scrollTop = scroller.scrollHeight;\n    } else if (\n      previous.firstTurnId !== undefined &&\n      (previous.firstTurnId !== firstTurnId || previous.loadsOlder !== loadsOlder) &&\n      previous.lastTurnId === lastTurnId\n    ) {\n      // Older messages arrived above what is in view, or the spinner came or went: the turn at\n      // the top goes back to where it was, rather than being pushed. The top one can be gone: a\n      // turn that starts with a reply joins the turn of its question when older messages bring it.\n      const anchor = held.current.find(({ id }) => turnElements.current.has(id));\n      const element = anchor && turnElements.current.get(anchor.id);\n      if (anchor && element) scroller.scrollTop = element.offsetTop - anchor.top;\n    } else if (lastTurnId !== previous.lastTurnId && lastTurnId !== undefined) {\n      // A new question pins to the top, once laid out at least as tall as the conversation. A\n      // conversation replaced as a whole opens at its end.\n      const continues =\n        previous.lastTurnId !== undefined &&\n        turnElements.current.has(previous.lastTurnId);\n      const element = turnElements.current.get(lastTurnId);\n      if (continues && element) scrollScroller(scroller, element.offsetTop, true);\n      else scroller.scrollTop = scroller.scrollHeight;\n    }\n    noteHeld();\n    checkEnd();\n  }, [checkEnd, firstTurnId, height, lastTurnId, loadsOlder, noteHeld]);\n\n  // Loads older messages once the spinner above the turns has been in view a moment, and again\n  // whenever the first turn changes while it is in view.\n  const loadOlderRef = useRef(loadOlderMessages);\n  loadOlderRef.current = loadOlderMessages;\n  const spinnerRef = useRef<HTMLDivElement>(null);\n  useEffect(() => {\n    const spinner = spinnerRef.current;\n    const scroller = scrollerRef.current;\n    if (\n      !loadsOlder ||\n      !spinner ||\n      !scroller ||\n      typeof IntersectionObserver === 'undefined'\n    ) {\n      return;\n    }\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    let loading = false;\n    let disposed = false;\n    const observer = new IntersectionObserver(\n      ([visible]) => {\n        clearTimeout(timer);\n        if (!visible?.isIntersecting || loading) return;\n        timer = setTimeout(() => {\n          loading = true;\n          let failed = false;\n          Promise.resolve(loadOlderRef.current?.())\n            .catch(() => {\n              failed = true;\n            })\n            .finally(() => {\n              loading = false;\n              if (disposed) return;\n              // Watching the spinner afresh reports whether it is still in view, so a load that\n              // failed, or brought nothing while there is more, asks again: after a pause when\n              // it failed. A load that brought older messages re-runs this effect instead.\n              observer.unobserve(spinner);\n              timer = setTimeout(\n                () => observer.observe(spinner),\n                failed ? LOAD_OLDER_RETRY_MS : 0,\n              );\n            });\n        }, LOAD_OLDER_DELAY_MS);\n      },\n      { root: scroller },\n    );\n    observer.observe(spinner);\n    return () => {\n      disposed = true;\n      clearTimeout(timer);\n      observer.disconnect();\n    };\n  }, [firstTurnId, loadsOlder]);\n\n  const renderTurn = (turn: AIConversationTurn) => {\n    const isLatest = turn.id === lastTurnId;\n    return (\n      <div\n        className={clsx(\n          'str-chat__ai-conversation__turn',\n          isLatest && 'str-chat__ai-conversation__turn--latest',\n        )}\n        data-turn-id={turn.id}\n        key={turn.id}\n        ref={(element) => {\n          if (element) turnElements.current.set(turn.id, element);\n          else turnElements.current.delete(turn.id);\n        }}\n        style={\n          isLatest && height\n            ? { minHeight: Math.max(0, height - bottomInset) }\n            : undefined\n        }\n      >\n        <AIThinkingTurnContext.Provider\n          value={{ clock, firstStepId: firstStepOf(turn), key: turn.id }}\n        >\n          {turn.entries.map((entry) => (\n            <EntryView\n              approver={approver}\n              AssistantMessage={AssistantMessage}\n              editAction={editAction}\n              entry={entry}\n              key={entry.id}\n              ReplyActions={ReplyActions}\n              ui={ui}\n              UserMessage={UserMessage}\n            />\n          ))}\n          {isLatest && thinking && <AIThinking />}\n          {isLatest && footer}\n        </AIThinkingTurnContext.Provider>\n      </div>\n    );\n  };\n\n  return (\n    <ThemeScopeProvider>\n      <AIToolApproverProvider approver={approver}>\n        <div\n          className={clsx(themeScopeClassName, 'str-chat__ai-conversation', className)}\n        >\n          <div\n            className='str-chat__ai-conversation__scroller'\n            onScroll={onScroll}\n            ref={scrollerRef}\n          >\n            {turns.length === 0 ? (\n              <div\n                className='str-chat__ai-conversation__empty'\n                ref={contentRef}\n                style={{ paddingBottom: bottomInset }}\n              >\n                {emptyContent}\n              </div>\n            ) : (\n              <div\n                className='str-chat__ai-conversation__turns'\n                ref={contentRef}\n                style={{ paddingBottom: bottomInset }}\n              >\n                {loadsOlder && (\n                  <div\n                    aria-label={t(\n                      'aiComponents.conversation.loadingOlderMessages.ariaLabel',\n                      'Loading older messages',\n                    )}\n                    className='str-chat__ai-conversation__loading-older'\n                    ref={spinnerRef}\n                    role='progressbar'\n                  >\n                    <IconLoading />\n                  </div>\n                )}\n                {turns.map(renderTurn)}\n              </div>\n            )}\n          </div>\n          {!isEndInView && turns.length > 0 && (\n            <button\n              aria-label={t(\n                'aiComponents.conversation.scrollToLatest.ariaLabel',\n                'Scroll to latest',\n              )}\n              className='str-chat__ai-conversation__scroll-to-latest'\n              onClick={() => scrollToEnd(true)}\n              style={{ bottom: bottomInset }}\n              title={t(\n                'aiComponents.conversation.scrollToLatest.ariaLabel',\n                'Scroll to latest',\n              )}\n              type='button'\n            >\n              <IconArrowDown />\n            </button>\n          )}\n        </div>\n      </AIToolApproverProvider>\n    </ThemeScopeProvider>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,IAAM,YAAY;AAGlB,IAAM,sBAAsB;AAE5B,IAAM,sBAAsB;AA4G5B,IAAM,sBAAsB,EAC1B,aACA,QACA,WAEA,oBAAC,eAAD;CAA4B;CAAqB;CAAc;AAAO,CAAA;AAGxE,IAAM,cAA2B,CAAC;AAIlC,IAAM,2BAA2B,EAC/B,UACA,aACA,cACA,OACA,eACA,WAEA,oBAAC,oBAAD;CACY;CACG;CACC;CACP;CACQ;CACT;AACP,CAAA;AAeH,IAAM,aAAa,EACjB,UACA,kBACA,YACA,OACA,cACA,IACA,kBACoB;CACpB,MAAM,EAAE,SAAS,YAAY;CAC7B,IAAI,CAAC,SACH,OAAO,UACL,oBAAC,aAAD;EAAa,aAAa,QAAQ,eAAe,CAAC;EAAG,MAAM,QAAQ;CAAO,CAAA,IACxE;CAEN,IAAI,QAAQ,SAAS,QACnB,OACE,oBAAC,aAAD;EACE,aACE,MAAM,gBAAgB,SAClB,MAAM,kBACL,QAAQ,eAAe,CAAC;EAEtB;EACT,QAAQ,aAAa,OAA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