{"version":3,"file":"browser-decision-check.cjs","sources":["../../src/chat/browser-decision-check.ts"],"sourcesContent":["import {\n  type AgoraFetch,\n  type BrowserDecisionCheckOutcome,\n  type DecisionCheckClient,\n  type PendingBrowserDecisionCheck,\n  runBrowserDecisionCheck,\n  statewireAnswerDescriptors,\n} from '@athenaintel/agent-runtime';\nimport { useMutation } from '@tanstack/react-query';\nimport { useCallback, useContext, useMemo, useRef } from 'react';\nimport { useAthenaQueryClient } from '../lib/use-athena-rest-query';\nimport { useAthenaConfig } from '../provider/AthenaContext';\nimport { resolveStatewireAuthHeaders } from '../runtime/statewire-auth-headers';\nimport { AthenaStatewireThreadIdContext } from '../threads/thread-id-context';\nimport type { StatewireDecisionAnswer, StatewireDecisionConfirmer } from './StatewireApprovalCard';\n\n/** The browser check in flight, as the host shows it: the code, the link, a way to stop. */\nexport interface PendingBrowserDecisionConfirm extends PendingBrowserDecisionCheck {\n  /** Stop waiting: the answer goes without a check (report-only). */\n  readonly cancel: () => void;\n}\n\nexport interface BrowserDecisionConfirmerOptions {\n  /** The statewire thread the approval card answers; no confirmer without one. */\n  readonly threadId: string | null | undefined;\n  /** Which surface asks, as the check page shows it. */\n  readonly client: DecisionCheckClient;\n  /** An authenticated request to agora, as the person (or their device key). */\n  readonly agoraFetch: AgoraFetch;\n  /** Open the check page in a new tab or the system browser. */\n  readonly openUrl: (url: string) => void | Promise<void>;\n  /** An app link the page sends the person back to once they answered. */\n  readonly returnUrl?: string;\n  /** The check the person is finishing in the browser, and `null` once it settled. */\n  readonly onPending?: (pending: PendingBrowserDecisionConfirm | null) => void;\n  /** Every outcome: where a host nudges a person with no passkey to set one up. */\n  readonly onOutcome?: (outcome: BrowserDecisionCheckOutcome) => void;\n}\n\ninterface CheckVariables {\n  readonly threadId: string;\n  readonly answer: StatewireDecisionAnswer;\n}\n\n/**\n * \"Confirm with your passkey\" for a host whose page can't run the passkey\n * prompt itself (identity row 0b.9, PR C): the Chrome extension, the Office\n * add-ins, Midas and SDK apps on another origin. Hand the confirmer this\n * returns to `StatewireApprovalCard` (or `AthenaChat`) as `confirmDecision`.\n *\n * An approving answer asks agora for a check, opens the web app's check page\n * through `openUrl`, and resolves the token once the person confirmed there;\n * the card sends it as `decisionCheck`. A reject never reaches here. While\n * checks are report-only the answer goes ahead without a token whenever there\n * is none (no passkey yet, the check skipped, cancelled, expired or\n * unavailable). Runs through TanStack Query, on the host's client.\n */\nexport function useBrowserDecisionConfirmer(\n  options: BrowserDecisionConfirmerOptions,\n): StatewireDecisionConfirmer | undefined {\n  const latest = useRef(options);\n  latest.current = options;\n  const queryClient = useAthenaQueryClient();\n  const { mutateAsync } = useMutation(\n    {\n      mutationKey: ['athena', 'decision-check', 'browser'],\n      mutationFn: ({ threadId, answer }: CheckVariables) => {\n        const controller = new AbortController();\n        return runBrowserDecisionCheck({\n          decisions: statewireAnswerDescriptors({ threadId, answer }),\n          client: latest.current.client,\n          agoraFetch: (path, init) => latest.current.agoraFetch(path, init),\n          openUrl: (url) => latest.current.openUrl(url),\n          returnUrl: latest.current.returnUrl,\n          signal: controller.signal,\n          onPending: (pending) =>\n            latest.current.onPending?.(\n              pending === null ? null : { ...pending, cancel: () => controller.abort() },\n            ),\n        });\n      },\n      // A check is one person's act at one moment: never paused offline and\n      // replayed later, and never repeated.\n      networkMode: 'always',\n      retry: false,\n    },\n    queryClient,\n  );\n\n  const { threadId } = options;\n  return useMemo(() => {\n    if (!threadId) return undefined;\n    return async (answer: StatewireDecisionAnswer): Promise<string | undefined> => {\n      let outcome: BrowserDecisionCheckOutcome;\n      try {\n        outcome = await mutateAsync({ threadId, answer });\n      } catch (error) {\n        outcome = {\n          status: 'failed',\n          message: error instanceof Error ? error.message : String(error),\n        };\n      }\n      if (outcome.status !== 'confirmed') {\n        // Report-only: the answer still goes; agora counts it as made\n        // without a check.\n        console.info('[athena] decision sent without a passkey check:', outcome.status);\n      }\n      latest.current.onOutcome?.(outcome);\n      return outcome.status === 'confirmed' ? outcome.token : undefined;\n    };\n  }, [threadId, mutateAsync]);\n}\n\n/** agora's API root for `backendUrl` (which may name the assistant-ui endpoint). */\nexport function agoraApiRoot(backendUrl: string): string {\n  return backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '').replace(/\\/+$/, '');\n}\n\n/**\n * A tab opened at the click, while the browser still counts it as the\n * person's act, and pointed at the check page once agora answered: a tab\n * opened only after that round trip is one a pop-up blocker may refuse. Its\n * opener is cut at once. `null` when the browser refused even that.\n */\nfunction openPlaceholderTab(): Window | null {\n  if (typeof window === 'undefined') return null;\n  const tab = window.open('', '_blank');\n  if (tab) tab.opener = null;\n  return tab;\n}\n\nexport interface AthenaBrowserDecisionConfirmerOptions {\n  /** Which surface asks; defaults to an SDK app. */\n  readonly client?: DecisionCheckClient;\n  /** Defaults to a new browser tab. A host that can't open one passes its own. */\n  readonly openUrl?: (url: string) => void | Promise<void>;\n  readonly returnUrl?: string;\n  /**\n   * Show the code and a link to the check page while it is open. With the\n   * default opener and no `onPending`, a browser that refuses the new tab\n   * leaves the person no way to the page, so the answer goes at once without\n   * a check (report-only) instead of waiting out the request.\n   */\n  readonly onPending?: (pending: PendingBrowserDecisionConfirm | null) => void;\n  readonly onOutcome?: (outcome: BrowserDecisionCheckOutcome) => void;\n}\n\n/**\n * {@link useBrowserDecisionConfirmer} bound to the enclosing `<AthenaProvider>`:\n * its backend, its credential (renewed once after a 401) and the thread it\n * attached. For SDK apps on another origin and Midas: pass the result to\n * `<AthenaChat confirmDecision={…}>`.\n */\nexport function useAthenaBrowserDecisionConfirmer(\n  options: AthenaBrowserDecisionConfirmerOptions = {},\n): StatewireDecisionConfirmer | undefined {\n  const config = useAthenaConfig();\n  const threadId = useContext(AthenaStatewireThreadIdContext);\n  const configRef = useRef(config);\n  configRef.current = config;\n  const agoraFetch = useCallback<AgoraFetch>(async (path, init) => {\n    const current = configRef.current;\n    const source = { apiKey: current.apiKey, token: current.token, getToken: current.getToken };\n    const send = async (staleAuth: boolean) => {\n      const authHeaders = await resolveStatewireAuthHeaders(source, { staleAuth });\n      return fetch(`${agoraApiRoot(current.backendUrl)}${path}`, {\n        ...init,\n        // With neither a token nor a key, the host signs in with its session\n        // cookie, which a request to another origin carries only when asked.\n        ...(Object.keys(authHeaders).length === 0 ? { credentials: 'include' as const } : {}),\n        headers: { ...Object.fromEntries(new Headers(init.headers).entries()), ...authHeaders },\n      });\n    };\n    const first = await send(false);\n    return first.status === 401 && current.getToken ? send(true) : first;\n  }, []);\n\n  const optionsRef = useRef(options);\n  optionsRef.current = options;\n  // The default opener's tab, opened at the click (see `openPlaceholderTab`).\n  const placeholderRef = useRef<Window | null>(null);\n  const confirm = useBrowserDecisionConfirmer({\n    threadId,\n    client: options.client ?? { kind: 'sdk' },\n    agoraFetch,\n    openUrl: (url) => {\n      const custom = optionsRef.current.openUrl;\n      if (custom) return custom(url);\n      const tab = placeholderRef.current;\n      placeholderRef.current = null;\n      if (tab && !tab.closed) tab.location.href = url;\n    },\n    returnUrl: options.returnUrl,\n    onPending: options.onPending,\n    onOutcome: options.onOutcome,\n  });\n  return useMemo(() => {\n    if (confirm === undefined) return undefined;\n    return async (answer: StatewireDecisionAnswer): Promise<string | undefined> => {\n      if (optionsRef.current.openUrl) return confirm(answer);\n      const tab = openPlaceholderTab();\n      // No tab and nowhere to show a link: nothing could reach the check page.\n      if (tab === null && !optionsRef.current.onPending) return undefined;\n      placeholderRef.current = tab;\n      try {\n        return await confirm(answer);\n      } finally {\n        // A check that ended before opening the page leaves no blank tab behind.\n        if (placeholderRef.current === tab && tab && !tab.closed) tab.close();\n        placeholderRef.current = null;\n      }\n    };\n  }, [confirm]);\n}\n"],"names":["useRef","useAthenaQueryClient","useMutation","threadId","runBrowserDecisionCheck","statewireAnswerDescriptors","useMemo","useAthenaConfig","useContext","AthenaStatewireThreadIdContext","useCallback","resolveStatewireAuthHeaders"],"mappings":";;;;;;;;;AAyDO,SAAS,4BACd,SACwC;AACxC,QAAM,SAASA,WAAAA,OAAO,OAAO;AAC7B,SAAO,UAAU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