{"version":3,"file":"AIToolAuthorization.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/MessageParts/AIToolAuthorization.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 {\n  type AIToolApprover,\n  type AIToolAuthorizer,\n  useAIToolApprover,\n} from '../ToolCalls/AIToolApprover';\nimport { AIConnectorSignInError } from '../ToolCalls/popupAuthorizer';\nimport { useNow } from '../utils';\nimport { isAuthorizationExpired, isAwaitingAuthorization } from './parseMessageParts';\nimport type { AIToolAuthorizationData, AIToolCallPart } from './types';\nimport { ThemeScopeProvider, useAIThemeScopeClassName } from '../themeScope';\n\n/** Where the person's answer to a sign-in is. */\nexport type AIToolAuthorizationState = {\n  /** The sign-in couldn't be opened, and the person can try again. */\n  connectFailed: boolean;\n  /** Their \"not now\" couldn't be sent, and the person can answer again. */\n  declineFailed: boolean;\n  /** The sign-in is open, or done and the call's step hasn't changed yet. */\n  isConnecting: boolean;\n  /** Their \"not now\" is on its way, or arrived and the call's step hasn't changed yet. */\n  isDeclining: boolean;\n  /** The browser blocked the sign-in's popup. */\n  popupBlocked?: boolean;\n};\n\nconst idle: AIToolAuthorizationState = {\n  connectFailed: false,\n  declineFailed: false,\n  isConnecting: false,\n  isDeclining: false,\n};\n\nexport type AIToolAuthorizationCardProps = {\n  authorization: AIToolAuthorizationData;\n  onConnect: () => void;\n  onDecline: () => void;\n  className?: string;\n  state?: AIToolAuthorizationState;\n};\n\n/**\n * Asks the person to sign in at a provider a tool call needs, such as \"Connect Linear\", with a\n * Connect and a Not now button. Once the sign-in is over it says how it ended (connected,\n * declined, expired or failed), and a sign-in past its expiry can no longer be opened. The\n * counterpart of `AIToolAuthorizationCard`.\n */\nexport const AIToolAuthorizationCard = ({\n  authorization,\n  className,\n  onConnect,\n  onDecline,\n  state = idle,\n}: AIToolAuthorizationCardProps) => {\n  const themeScopeClassName = useAIThemeScopeClassName();\n  const { t } = useTranslationContext();\n  const { IconLoading } = useComponentContextIcons();\n  const open = authorization.status === undefined;\n  // Re-checked every few seconds while it is open, so it turns expired on its own.\n  const now = useNow(open && authorization.expiresAt !== undefined, 5000);\n  const expired = isAuthorizationExpired(authorization, now);\n  const provider = authorization.providerName ?? authorization.provider;\n  const busy = state.isConnecting || state.isDeclining;\n\n  const outcome = (() => {\n    if (expired)\n      return t(\n        'aiComponents.toolAuthorization.signInExpired.text',\n        'This sign-in has expired.',\n      );\n    switch (authorization.status) {\n      case undefined:\n        return undefined;\n      case 'connected':\n        return t(\n          'aiComponents.toolAuthorization.connectedTo.text',\n          'Connected to {{ provider }}',\n          { provider },\n        );\n      case 'declined':\n        return t('aiComponents.toolAuthorization.notConnected.text', 'Not connected');\n      default:\n        return t(\n          'aiComponents.toolAuthorization.signInDidntComplete.text',\n          \"The sign-in didn't complete.\",\n        );\n    }\n  })();\n\n  const failure = (() => {\n    if (state.popupBlocked)\n      return t(\n        'aiComponents.toolAuthorization.popupBlocked.text',\n        'Your browser blocked the sign-in window. Allow pop-ups and try again.',\n      );\n    if (state.connectFailed)\n      return t(\n        'aiComponents.toolAuthorization.signInCouldntOpen.text',\n        \"The sign-in couldn't be opened. Try again.\",\n      );\n    if (state.declineFailed)\n      return t(\n        'aiComponents.toolAuthorization.answerNotSent.text',\n        \"Your answer couldn't be sent. Try again.\",\n      );\n    return undefined;\n  })();\n\n  return (\n    <ThemeScopeProvider>\n      <div\n        aria-busy={busy}\n        className={clsx(\n          themeScopeClassName,\n          'str-chat__ai-tool-authorization-card',\n          authorization.status &&\n            `str-chat__ai-tool-authorization-card--${authorization.status}`,\n          expired && 'str-chat__ai-tool-authorization-card--expired',\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'>\n            {authorization.title}\n          </div>\n          {authorization.message && (\n            <div className='str-chat__ai-tool-approval-card__message'>\n              {authorization.message}\n            </div>\n          )}\n        </div>\n        {outcome && (\n          <div className='str-chat__ai-tool-authorization-card__outcome' role='status'>\n            {outcome}\n          </div>\n        )}\n        {open && (\n          <div className='str-chat__ai-tool-approval-card__actions'>\n            {!expired && (\n              <button\n                className='str-chat__ai-button str-chat__ai-button--primary'\n                disabled={busy}\n                onClick={onConnect}\n                type='button'\n              >\n                {state.isConnecting\n                  ? t('aiComponents.toolAuthorization.connecting.label', 'Connecting…')\n                  : t('aiComponents.toolAuthorization.connect.label', 'Connect')}\n              </button>\n            )}\n            {/* Left enabled while the sign-in is open, so one that never comes back leaves a way out. */}\n            <button\n              className='str-chat__ai-button str-chat__ai-button--secondary'\n              disabled={state.isDeclining}\n              onClick={onDecline}\n              type='button'\n            >\n              {t('aiComponents.toolAuthorization.notNow.label', 'Not now')}\n            </button>\n            {busy && (\n              <span className='str-chat__ai-spinner'>\n                <IconLoading />\n              </span>\n            )}\n          </div>\n        )}\n        {failure && (\n          <div className='str-chat__ai-tool-approval-card__failure' role='alert'>\n            {failure}\n          </div>\n        )}\n      </div>\n    </ThemeScopeProvider>\n  );\n};\n\n/**\n * The sign-in this person is asked for on `call` here: one the call waits for them to finish,\n * of a kind this device opens, and only when they can sign in on it.\n */\nexport const signInFor = (call: AIToolCallPart, approver: AIToolApprover | undefined) => {\n  if (!approver?.authorizer || !isAwaitingAuthorization(call, approver.userId)) return;\n  return call.authorization?.type === 'oauth' ? call.authorization : undefined;\n};\n\nexport type AIToolAuthorizationProps = {\n  part: AIToolCallPart;\n  /** Who answers on this device, with the `authorizer` the sign-in needs. Defaults to the one of the nearest `AIToolApproverProvider`. */\n  approver?: AIToolApprover;\n  /** Renders the sign-in, instead of `AIToolAuthorizationCard`. */\n  children?: (\n    authorization: AIToolAuthorizationData,\n    state: AIToolAuthorizationState,\n    actions: { connect: () => void; decline: () => void },\n  ) => ReactNode;\n};\n\n/**\n * Asks for the sign-in of a tool call that waits for this person, and runs it with\n * `approver.authorizer`. Renders nothing for a call that does not wait for them, or without an\n * authorizer. The counterpart of `AIToolAuthorizationView`.\n */\nexport const AIToolAuthorization = ({\n  approver: approverProp,\n  children,\n  part,\n}: AIToolAuthorizationProps) => {\n  const approver = useAIToolApprover(approverProp);\n  const [state, setState] = useState<AIToolAuthorizationState>(idle);\n  const mounted = useRef(true);\n  useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n\n  const authorization = signInFor(part, approver);\n  const authorizer = approver?.authorizer;\n  if (!authorization || !authorizer) return null;\n\n  const update = (next: AIToolAuthorizationState) => {\n    if (mounted.current) setState(next);\n  };\n\n  const connect = (signIn: AIToolAuthorizer) => {\n    if (state.isConnecting || state.isDeclining) return;\n    setState({ ...idle, isConnecting: true });\n    // Called in the click itself: a popup opened before anything is awaited is not blocked.\n    signIn.connect(part).then(\n      // Your backend has the provider's answer before the popup comes back, and its change to\n      // the step hides this. Until then it says it is connecting, unless the person closed the\n      // popup or the provider did not connect them.\n      (connected) => {\n        if (!connected) update(idle);\n      },\n      (error: unknown) =>\n        update({\n          ...idle,\n          connectFailed: true,\n          popupBlocked:\n            error instanceof AIConnectorSignInError && error.reason === 'blocked',\n        }),\n    );\n  };\n\n  const decline = (signIn: AIToolAuthorizer) => {\n    if (state.isDeclining) return;\n    setState({ ...idle, isDeclining: true });\n    signIn.decline(part).catch(() => update({ ...idle, declineFailed: true }));\n  };\n\n  const actions = {\n    connect: () => connect(authorizer),\n    decline: () => decline(authorizer),\n  };\n\n  return (\n    <>\n      {children ? (\n        children(authorization, state, actions)\n      ) : (\n        <AIToolAuthorizationCard\n          authorization={authorization}\n          onConnect={actions.connect}\n          onDecline={actions.decline}\n          state={state}\n        />\n      )}\n    </>\n  );\n};\n"],"mappings":";;;;;;;;;;;;AA8BA,IAAM,OAAiC;CACrC,eAAe;CACf,eAAe;CACf,cAAc;CACd,aAAa;AACf;;;;;;;AAgBA,IAAa,2BAA2B,EACtC,eACA,WACA,WACA,W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