{"version":3,"file":"AIToolApproval.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/MessageParts/AIToolApproval.tsx"],"sourcesContent":["import React, { type ReactNode, useEffect, useRef, useState } from 'react';\nimport clsx from 'clsx';\n\nimport { useTranslationContext } from '../../../context/TranslationContext';\nimport { useComponentContextIcons } from '../../../context/useComponentContextIcons';\nimport { type AIToolApprover, useAIToolApprover } from '../ToolCalls/AIToolApprover';\nimport { isAwaitingApproval } from './parseMessageParts';\nimport { formatToolArguments } from './toolArguments';\nimport type { AIToolApprovalData, AIToolCallPart } from './types';\nimport { ThemeScopeProvider, useAIThemeScopeClassName } from '../themeScope';\n\n/** Where the person's answer to a tool call's question is. */\nexport type AIToolApprovalState = {\n  /** The answer couldn't be sent, and the person can answer again. */\n  failed: boolean;\n  /** The answer is on its way, or arrived and the call's step hasn't changed yet. */\n  isSending: boolean;\n};\n\nconst idle: AIToolApprovalState = { failed: false, isSending: false };\n\n/** The agent's reason, as a sentence, then what allowing it shares. */\nexport const approvalLines = (approval: AIToolApprovalData) => {\n  const lines: string[] = [];\n  const reason = approval.reason?.trim();\n  if (reason) {\n    const sentence = reason[0].toUpperCase() + reason.slice(1);\n    lines.push(/[.!?…]$/.test(sentence) ? sentence : `${sentence}.`);\n  }\n  if (approval.message) lines.push(approval.message);\n  return lines;\n};\n\n// Arguments longer than this, in characters or lines, start collapsed.\nconst LONG_ARGUMENTS_CHARACTERS = 280;\nconst LONG_ARGUMENTS_LINES = 6;\n\n// Formatted arguments, in full when short, else collapsed under \"What it sends\".\n// Scoped on its own root, since `AIToolArguments` also renders it outside an approval card.\nconst ToolArgumentsText = ({ className, text }: { text: string; className?: string }) => {\n  const themeScopeClassName = useAIThemeScopeClassName();\n  const { t } = useTranslationContext();\n  const isLong =\n    text.length > LONG_ARGUMENTS_CHARACTERS ||\n    text.split('\\n').length > LONG_ARGUMENTS_LINES;\n  const code = <pre className='str-chat__ai-tool-arguments__code'>{text}</pre>;\n  return isLong ? (\n    <details\n      className={clsx(themeScopeClassName, 'str-chat__ai-tool-arguments', className)}\n    >\n      <summary className='str-chat__ai-tool-arguments__label'>\n        {t('aiComponents.toolApproval.arguments.label', 'What it sends')}\n      </summary>\n      {code}\n    </details>\n  ) : (\n    <div\n      aria-label={t('aiComponents.toolApproval.arguments.ariaLabel', 'What it sends')}\n      className={clsx(themeScopeClassName, 'str-chat__ai-tool-arguments', className)}\n      role='group'\n    >\n      {code}\n    </div>\n  );\n};\n\nexport type AIToolArgumentsProps = {\n  /** The call's arguments, as the agent sent them. */\n  args: unknown;\n  className?: string;\n};\n\n/**\n * What a tool call will send, as JSON: in full when short, else collapsed under \"What it sends\",\n * which the person opens to read it. Renders nothing for a call with no arguments. The default\n * of `AIToolApprover.argumentsPreview`.\n */\nexport const AIToolArguments = ({ args, className }: AIToolArgumentsProps) => {\n  const text = formatToolArguments(args);\n  return text === undefined ? null : (\n    <ToolArgumentsText className={className} text={text} />\n  );\n};\n\n// What an approval card shows of a call's arguments: the approver's `argumentsPreview`, else\n// the arguments as `AIToolArguments` shows them, formatted once. `null` when it shows nothing.\nconst toolArgumentsPreview = (\n  call: AIToolCallPart,\n  approver?: AIToolApprover,\n): ReactNode => {\n  const own = approver?.argumentsPreview?.(call);\n  if (own !== undefined) return own;\n  const text = formatToolArguments(call.arguments);\n  return text === undefined ? null : <ToolArgumentsText text={text} />;\n};\n\nexport type AIToolApprovalCardProps = {\n  approval: AIToolApprovalData;\n  /** Called with the person's answer. */\n  onDecide: (allowed: boolean) => void;\n  /**\n   * What the call will send, under the question, such as `<AIToolArguments args={…} />`.\n   * `AIToolApproval` passes the approver's `argumentsPreview`, else the call's arguments.\n   */\n  argumentsPreview?: ReactNode;\n  className?: string;\n  state?: AIToolApprovalState;\n};\n\n/**\n * Asks the person a tool call's question, such as \"Share your location?\", with the agent's\n * reason, what allowing it shares and what the call will send (`argumentsPreview`), and an\n * Allow and a Don't Allow button. Used inline under a step by `AIToolApproval`, and on its own,\n * such as on a voice call. The counterpart of `AIToolApprovalCard`.\n */\nexport const AIToolApprovalCard = ({\n  approval,\n  argumentsPreview,\n  className,\n  onDecide,\n  state = idle,\n}: AIToolApprovalCardProps) => {\n  const themeScopeClassName = useAIThemeScopeClassName();\n  const { t } = useTranslationContext();\n  const { IconLoading } = useComponentContextIcons();\n  return (\n    <ThemeScopeProvider>\n      <div\n        aria-busy={state.isSending}\n        className={clsx(\n          themeScopeClassName,\n          'str-chat__ai-tool-approval-card',\n          className,\n        )}\n        role='group'\n      >\n        <div className='str-chat__ai-tool-approval-card__text'>\n          <div className='str-chat__ai-tool-approval-card__title'>{approval.title}</div>\n          {approvalLines(approval).map((line) => (\n            <div className='str-chat__ai-tool-approval-card__message' key={line}>\n              {line}\n            </div>\n          ))}\n        </div>\n        {argumentsPreview !== undefined && argumentsPreview !== null && (\n          <div className='str-chat__ai-tool-approval-card__arguments'>\n            {argumentsPreview}\n          </div>\n        )}\n        <div className='str-chat__ai-tool-approval-card__actions'>\n          <button\n            className='str-chat__ai-button str-chat__ai-button--primary'\n            disabled={state.isSending}\n            onClick={() => onDecide(true)}\n            type='button'\n          >\n            {approval.allowTitle ?? t('aiComponents.toolApproval.allow.label', 'Allow')}\n          </button>\n          <button\n            className='str-chat__ai-button str-chat__ai-button--secondary'\n            disabled={state.isSending}\n            onClick={() => onDecide(false)}\n            type='button'\n          >\n            {approval.declineTitle ??\n              t('aiComponents.toolApproval.dontAllow.label', \"Don't Allow\")}\n          </button>\n          {state.isSending && (\n            <span className='str-chat__ai-spinner'>\n              <IconLoading />\n            </span>\n          )}\n        </div>\n        {state.failed && (\n          <div className='str-chat__ai-tool-approval-card__failure' role='alert'>\n            {t(\n              'aiComponents.toolApproval.answerNotSent.text',\n              \"Your answer couldn't be sent. Try again.\",\n            )}\n          </div>\n        )}\n      </div>\n    </ThemeScopeProvider>\n  );\n};\n\nexport type AIToolApprovalProps = {\n  part: AIToolCallPart;\n  /** Who answers on this device. Defaults to the one of the nearest `AIToolApproverProvider`. */\n  approver?: AIToolApprover;\n  /**\n   * Renders the question, instead of `AIToolApprovalCard`. `argumentsPreview` is what the card\n   * would show of the call's arguments (see `AIToolApprover.argumentsPreview`), or `null`.\n   */\n  children?: (\n    approval: AIToolApprovalData,\n    state: AIToolApprovalState,\n    decide: (allowed: boolean) => void,\n    argumentsPreview: ReactNode,\n  ) => ReactNode;\n};\n\n/**\n * Asks the question of a tool call that waits for this person on this device, and sends their\n * answer with `approver.decide`. Until the call's step changes the buttons wait; a failed send\n * lets them answer again. Renders nothing for a call that does not wait for them here. The\n * counterpart of `AIToolApprovalView`.\n */\nexport const AIToolApproval = ({\n  approver: approverProp,\n  children,\n  part,\n}: AIToolApprovalProps) => {\n  const approver = useAIToolApprover(approverProp);\n  const [state, setState] = useState<AIToolApprovalState>(idle);\n  const mounted = useRef(true);\n  useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n\n  if (\n    !approver ||\n    !part.approval ||\n    !isAwaitingApproval(part, approver.userId, approver.clientId)\n  ) {\n    return null;\n  }\n\n  const decide = (allowed: boolean) => {\n    if (state.isSending) return;\n    setState({ failed: false, isSending: true });\n    approver.decide(part, allowed).catch(() => {\n      if (mounted.current) setState({ failed: true, isSending: false });\n    });\n  };\n\n  const argumentsPreview = toolArgumentsPreview(part, approver);\n\n  return (\n    <>\n      {children ? (\n        children(part.approval, state, decide, argumentsPreview)\n      ) : (\n        <AIToolApprovalCard\n          approval={part.approval}\n          argumentsPreview={argumentsPreview}\n          onDecide={decide}\n          state={state}\n        />\n      )}\n    </>\n  );\n};\n"],"mappings":";;;;;;;;;;;AAmBA,IAAM,OAA4B;CAAE,QAAQ;CAAO,WAAW;AAAM;;AAGpE,IAAa,iBAAiB,aAAiC;CAC7D,MAAM,QAAkB,CAAC;CACzB,MAAM,SAAS,SAAS,QAAQ,KAAK;CACrC,IAAI,QAAQ;EACV,MAAM,WAAW,OAAO,EAAE,CAAC,YAAY,IAAI,OAAO,MAAM,CAAC;EACzD,MAA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