{"version":3,"sources":["../../../src/hooks/useWebChat.ts"],"sourcesContent":["import type {\n  AgentConversationPublicationMeta,\n  AgentConversationRunSnapshot,\n  AgentConversationRuntime,\n  AgentConversationSnapshot,\n  AgentConversationStatus,\n  AgentEventEnvelope,\n  AgentHashFields,\n  AgentMessage,\n  AgentPendingAction,\n  AgentToolApprovalDecision,\n  LoadConversationResult,\n  RespondToActionResult,\n  SendActionResult,\n  SendMessageInput,\n  SendMessageResult,\n  StopResult,\n  WebChatPagination,\n  WebChatPlanLimitError,\n} from '@novu/js';\nimport { NovuError } from '@novu/js';\nimport { type MutableRefObject, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { useDataRef } from './internal/useDataRef';\nimport { useNovu } from './NovuProvider';\n\ntype UseWebChatCallbacks = {\n  onSuccess?: (data: LoadConversationResult) => void;\n  onError?: (error: NovuError | WebChatPlanLimitError) => void;\n  /**\n   * Fires once when a message id first appears. History pages do not fire.\n   * The first event of a turn can create an empty assistant message before text arrives.\n   * A send that never reaches the server does not fire. The message status becomes `failed` instead.\n   */\n  onMessage?: (message: AgentMessage) => void;\n  /**\n   * Fires once per pending action, including actions still pending on mount.\n   * Paging backwards does not fire.\n   */\n  onActionRequested?: (action: AgentPendingAction) => void;\n  /**\n   * Live event envelopes for this conversation.\n   * Duplicates that the client drops do not fire.\n   * Envelopes that arrive before the conversation id exists do not fire.\n   * The message list in this render does not include this envelope yet.\n   */\n  onEvent?: (envelope: AgentEventEnvelope) => void;\n};\n\n/** Arguments for {@link useWebChat}. Pass `agentId`, or pass `conversation`. Do not mix the two. */\nexport type UseWebChatProps = UseWebChatCallbacks &\n  AgentHashFields &\n  (\n    | {\n        agentId: string;\n        /**\n         * Resume this conversation. The hook loads history on mount.\n         * Omit this prop to start a new chat. The first send creates a conversation.\n         */\n        conversationId?: string;\n        conversation?: never;\n      }\n    | {\n        /** Share an existing conversation runtime across multiple hook instances. */\n        conversation: AgentConversationRuntime;\n        agentId?: never;\n        conversationId?: never;\n        agentHash?: never;\n      }\n  );\n\n/**\n * State and actions returned by {@link useWebChat}.\n * `sendMessage`, `respondToAction`, `sendAction`, and `retryMessage` resolve `{ data, error }` and never reject.\n * Inspect `error` on the result, or show hook `error`.\n */\nexport type UseWebChatResult = {\n  /** Conversation timeline. */\n  messages: AgentMessage[];\n  /** Tool approvals and MCP connect items that are still pending. */\n  pendingActions: AgentPendingAction[];\n  /** Server conversation id after create or resume. */\n  conversationId?: string;\n  /** Last error from load, send, retry, or action. Mutations also return `{ error }` for that call. */\n  error?: NovuError | WebChatPlanLimitError;\n  /** True while Web Chat loads and, for an existing conversation, until the first history fetch completes. */\n  isLoading: boolean;\n  /** True while the agent turn is in progress. Same as `run.isRunning`. */\n  isRunning: boolean;\n  /** True from `stop()` until the run ends. Same as `run.isStopping`. */\n  isStopping: boolean;\n  /** Typing indicator. Same as `run.typing`. Absent when the agent is not typing. */\n  typing?: AgentConversationRunSnapshot['typing'];\n  /** `'active'` or `'resolved'`. The agent sets `resolved` with `ctx.resolve()`. Not a loading flag. */\n  conversationStatus: AgentConversationStatus;\n  /** Current agent-run snapshot. */\n  run: AgentConversationRunSnapshot;\n  /** Older-history control. Not a top-level `hasMore` or `fetchMore`. */\n  pagination: WebChatPagination & {\n    fetchMore: () => Promise<{\n      data?: { messages: AgentMessage[]; hasMore: boolean };\n      error?: NovuError;\n    }>;\n  };\n  /** True while reconnect recovery is in progress. */\n  isRecovering: boolean;\n  /** Set when reconnect recovery fails. Separate from send and fetch `error`. */\n  catchUpError?: NovuError;\n  /** Reload the newest history page. No-op when there is no conversation id. */\n  refetch: () => Promise<void>;\n  /**\n   * Send a user message. `input` is a string, or `{ text, metadata }`. Creates a conversation when `conversationId` is omitted.\n   * Does not throw. Resolves `{ data, error }`. Inspect `error` on the result, or show hook `error`.\n   */\n  sendMessage: (input: SendMessageInput) => Promise<{\n    data?: SendMessageResult;\n    error?: NovuError | WebChatPlanLimitError;\n  }>;\n  /**\n   * Resolve a pending `approval`. Pass `approvalId` from `pendingActions` or message parts.\n   * Does not throw. Resolves `{ data, error }`. Inspect `error` on the result, or show hook `error`.\n   */\n  respondToAction: (args: { approvalId: string; decision: AgentToolApprovalDecision }) => Promise<{\n    data?: RespondToActionResult;\n    error?: NovuError | WebChatPlanLimitError;\n  }>;\n  /**\n   * Click a Card button. Do not use this for tool approval.\n   * Does not throw. Resolves `{ data, error }`. Inspect `error` on the result, or show hook `error`.\n   */\n  sendAction: (args: { actionId: string; sourceMessageId: string; value?: string }) => Promise<{\n    data?: SendActionResult;\n    error?: NovuError | WebChatPlanLimitError;\n  }>;\n  /**\n   * Resend a message whose `status` is `failed`. Reuses the original idempotency key.\n   * Does not throw. Resolves `{ data, error }`. Inspect `error` on the result, or show hook `error`.\n   */\n  retryMessage: (messageId: string) => Promise<{\n    data?: SendMessageResult;\n    error?: NovuError | WebChatPlanLimitError;\n  }>;\n  /**\n   * Stop the agent turn that is running. Does nothing when no turn runs. Resolves an `error` when no message was\n   * sent yet. `isStopping` is true until the run ends, and the last assistant message then has `stopped: true`.\n   * Does not throw. Resolves `{ data, error }`. Inspect `error` on the result, or show hook `error`.\n   *\n   * @experimental Not every agent runtime can stop a turn mid-step yet. The agent finishes its current step first.\n   */\n  stop: () => Promise<{\n    data?: StopResult;\n    error?: NovuError | WebChatPlanLimitError;\n  }>;\n  /**\n   * Start a new empty chat for the current `agentId`. The next `sendMessage` creates the server conversation.\n   * No-op when `conversationId` or `conversation` is provided.\n   */\n  startNewConversation: () => void;\n};\n\nconst EMPTY_SERVER_SNAPSHOT = {\n  key: 'ssr',\n  status: 'loading',\n  run: { isRunning: false, isStopping: false },\n  conversationStatus: 'active',\n  pagination: { hasMore: false, status: 'idle' },\n  messages: [],\n  pendingActions: [],\n  isRecovering: false,\n} as AgentConversationSnapshot;\n\ntype RuntimeActionResult<T> = {\n  data?: T;\n  error?: NovuError | WebChatPlanLimitError;\n};\n\nfunction notifyErrors(args: {\n  snapshot: AgentConversationSnapshot;\n  propsRef: ReturnType<typeof useDataRef<UseWebChatProps>>;\n  notifiedCatchUpErrorRef: MutableRefObject<NovuError | undefined>;\n  lastReportedErrorKeyRef: MutableRefObject<string | undefined>;\n}): void {\n  const { snapshot, propsRef, notifiedCatchUpErrorRef, lastReportedErrorKeyRef } = args;\n\n  if (snapshot.catchUpError && snapshot.catchUpError !== notifiedCatchUpErrorRef.current) {\n    notifiedCatchUpErrorRef.current = snapshot.catchUpError;\n    propsRef.current.onError?.(snapshot.catchUpError);\n  } else if (!snapshot.catchUpError) {\n    notifiedCatchUpErrorRef.current = undefined;\n  }\n\n  if (snapshot.error) {\n    const originalMessage = 'originalError' in snapshot.error ? (snapshot.error.originalError?.message ?? '') : '';\n    const errorKey = `${snapshot.error.message}:${originalMessage}`;\n    if (lastReportedErrorKeyRef.current !== errorKey) {\n      lastReportedErrorKeyRef.current = errorKey;\n      propsRef.current.onError?.(snapshot.error as NovuError | WebChatPlanLimitError);\n    }\n  } else {\n    lastReportedErrorKeyRef.current = undefined;\n  }\n}\n\nfunction handlePublicationCallbacks(args: {\n  snapshot: AgentConversationSnapshot;\n  meta: AgentConversationPublicationMeta | undefined;\n  conversationIdProp: string | undefined;\n  propsRef: ReturnType<typeof useDataRef<UseWebChatProps>>;\n  loadNotifiedRef: MutableRefObject<boolean>;\n  notifiedCatchUpErrorRef: MutableRefObject<NovuError | undefined>;\n  lastReportedErrorKeyRef: MutableRefObject<string | undefined>;\n}): void {\n  const {\n    snapshot,\n    meta,\n    conversationIdProp,\n    propsRef,\n    loadNotifiedRef,\n    notifiedCatchUpErrorRef,\n    lastReportedErrorKeyRef,\n  } = args;\n\n  if ((meta?.historyLoaded || meta?.change?.kind === 'history') && !loadNotifiedRef.current && conversationIdProp) {\n    if (snapshot.conversationId) {\n      loadNotifiedRef.current = true;\n      propsRef.current.onSuccess?.({\n        conversationId: snapshot.conversationId,\n        messages: [...snapshot.messages],\n        hasMore: snapshot.pagination.hasMore,\n      });\n    }\n  }\n\n  notifyErrors({ snapshot, propsRef, notifiedCatchUpErrorRef, lastReportedErrorKeyRef });\n\n  const change = meta?.change;\n  if (change?.kind === 'live') {\n    propsRef.current.onEvent?.(change.envelope);\n  }\n\n  if (change && change.kind !== 'history') {\n    for (const message of change.addedMessages) {\n      propsRef.current.onMessage?.(message);\n    }\n  }\n\n  if (change) {\n    for (const action of change.newActions) {\n      propsRef.current.onActionRequested?.(action);\n    }\n  }\n}\n\ntype OwnedRuntimeEntry = {\n  key: string;\n  novu: ReturnType<typeof useNovu>;\n  runtime: AgentConversationRuntime;\n};\n\nfunction getCreateFlowKey(agentId: string, agentHash?: string): string {\n  return `${agentId}\\0${agentHash ?? ''}`;\n}\n\nfunction getManagedRuntimeKey(\n  agentId: string,\n  agentHash: string | undefined,\n  conversationIdProp: string | undefined,\n  createEpoch: number\n): string {\n  if (conversationIdProp) {\n    return `resume:${agentId}\\0${agentHash ?? ''}\\0${conversationIdProp}`;\n  }\n\n  return `${getCreateFlowKey(agentId, agentHash)}\\0${createEpoch}`;\n}\n\ntype ManagedRuntimeEntry = {\n  key: string;\n  runtime: AgentConversationRuntime;\n};\n\ntype WebChatLoadState =\n  | { novu: ReturnType<typeof useNovu>; status: 'loading' }\n  | { novu: ReturnType<typeof useNovu>; status: 'ready' }\n  | { novu: ReturnType<typeof useNovu>; status: 'error'; error: NovuError };\n\nfunction toNovuError(error: unknown): NovuError {\n  if (error instanceof NovuError) {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return new NovuError('Failed to load Web Chat', error);\n  }\n\n  return new NovuError('Failed to load Web Chat', new Error(String(error)));\n}\n\n/**\n * Headless Web Chat client. Use it inside `NovuProvider`.\n *\n * @example\n * ```tsx\n * const { messages, sendMessage, isRunning, isLoading, error } = useWebChat({\n *   agentId: 'YOUR_AGENT_IDENTIFIER',\n * });\n * ```\n */\nexport const useWebChat = (props: UseWebChatProps): UseWebChatResult => {\n  const novu = useNovu();\n  const propsRef = useDataRef(props);\n  const [loadState, setLoadState] = useState<WebChatLoadState>(() => ({\n    novu,\n    status: 'loading',\n  }));\n\n  useEffect(() => {\n    let cancelled = false;\n\n    if (!novu.isWebChatLoaded) {\n      setLoadState({ novu, status: 'loading' });\n    }\n\n    void novu\n      .loadWebChat()\n      .then(() => {\n        if (!cancelled) {\n          setLoadState({ novu, status: 'ready' });\n        }\n      })\n      .catch((error: unknown) => {\n        if (cancelled) {\n          return;\n        }\n\n        const novuError = toNovuError(error);\n        propsRef.current.onError?.(novuError);\n        setLoadState({ novu, status: 'error', error: novuError });\n      });\n\n    return () => {\n      cancelled = true;\n    };\n  }, [novu, propsRef]);\n\n  const webChatReady = loadState.novu === novu && loadState.status === 'ready';\n  const webChatLoadError = loadState.novu === novu && loadState.status === 'error' ? loadState.error : undefined;\n  const isWebChatLoading = loadState.novu !== novu || loadState.status === 'loading';\n\n  const sharedRuntime = 'conversation' in props ? props.conversation : undefined;\n  const agentId = props.conversation ? props.conversation.agentId : props.agentId;\n  const conversationIdProp = sharedRuntime ? undefined : props.conversationId;\n  const agentHash = sharedRuntime ? undefined : props.agentHash;\n\n  const ownedRuntimeRef = useRef<OwnedRuntimeEntry | null>(null);\n  // The conversation a new chat created, so a rebuilt runtime (e.g. a new `novu` instance) resumes it instead of starting empty.\n  const createdConversationRef = useRef<{ key: string; identity: string; conversationId: string } | null>(null);\n  const [managedRuntime, setManagedRuntime] = useState<ManagedRuntimeEntry | null>(null);\n  const [createEpoch, setCreateEpoch] = useState(0);\n  const managedRuntimeKey = sharedRuntime\n    ? null\n    : getManagedRuntimeKey(agentId, agentHash, conversationIdProp, createEpoch);\n\n  useEffect(() => {\n    if (sharedRuntime) {\n      ownedRuntimeRef.current?.runtime.dispose();\n      ownedRuntimeRef.current = null;\n      setManagedRuntime(null);\n\n      return;\n    }\n\n    if (!webChatReady || !managedRuntimeKey) {\n      setManagedRuntime(null);\n\n      return;\n    }\n\n    const key = managedRuntimeKey;\n    // Only a client for the same app, subscriber and context may resume the saved conversation.\n    const identity = `${novu.applicationIdentifier}\\0${novu.subscriberId}\\0${novu.contextKey}`;\n    const current = ownedRuntimeRef.current;\n\n    let runtime: AgentConversationRuntime;\n    if (current?.novu === novu && current.key === key) {\n      runtime = current.runtime;\n    } else {\n      current?.runtime.dispose();\n      const resumeConversationId =\n        conversationIdProp ??\n        (createdConversationRef.current?.key === key && createdConversationRef.current.identity === identity\n          ? createdConversationRef.current.conversationId\n          : undefined);\n      runtime = resumeConversationId\n        ? novu.webChat.conversation({ agentId, conversationId: resumeConversationId, agentHash })\n        : novu.webChat.conversation({ agentId, agentHash });\n      ownedRuntimeRef.current = { key, novu, runtime };\n    }\n\n    setManagedRuntime({ key, runtime });\n\n    return () => {\n      const conversationId = ownedRuntimeRef.current?.runtime.getSnapshot().conversationId;\n      if (conversationId) createdConversationRef.current = { key, identity, conversationId };\n      ownedRuntimeRef.current?.runtime.dispose();\n      ownedRuntimeRef.current = null;\n      setManagedRuntime(null);\n    };\n  }, [webChatReady, sharedRuntime, novu, agentId, conversationIdProp, agentHash, createEpoch, managedRuntimeKey]);\n\n  const runtime = sharedRuntime ?? (managedRuntime?.key === managedRuntimeKey ? managedRuntime.runtime : null);\n\n  const loadNotifiedRef = useRef(false);\n  const replayedActionsRef = useRef(false);\n  const notifiedCatchUpErrorRef = useRef<NovuError | undefined>();\n  const lastReportedErrorKeyRef = useRef<string>();\n\n  useEffect(() => {\n    loadNotifiedRef.current = false;\n    replayedActionsRef.current = false;\n    notifiedCatchUpErrorRef.current = undefined;\n    lastReportedErrorKeyRef.current = undefined;\n  }, [runtime]);\n\n  const subscribe = useCallback(\n    (onStoreChange: () => void) => {\n      if (!runtime) {\n        return () => {};\n      }\n\n      if (!replayedActionsRef.current) {\n        replayedActionsRef.current = true;\n        for (const action of runtime.getSnapshot().pendingActions) {\n          propsRef.current.onActionRequested?.(action);\n        }\n      }\n\n      return runtime.subscribe((snapshot, meta) => {\n        onStoreChange();\n        handlePublicationCallbacks({\n          snapshot,\n          meta,\n          conversationIdProp,\n          propsRef,\n          loadNotifiedRef,\n          notifiedCatchUpErrorRef,\n          lastReportedErrorKeyRef,\n        });\n      });\n    },\n    [runtime, conversationIdProp, propsRef]\n  );\n\n  const getSnapshot = useCallback(() => {\n    return runtime?.getSnapshot() ?? EMPTY_SERVER_SNAPSHOT;\n  }, [runtime]);\n\n  const getServerSnapshot = useCallback(() => {\n    return runtime?.getServerSnapshot() ?? EMPTY_SERVER_SNAPSHOT;\n  }, [runtime]);\n\n  const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n  const callRuntime = useCallback(\n    async <T>(action: (target: AgentConversationRuntime) => Promise<RuntimeActionResult<T>>) => {\n      if (!runtime) {\n        const error =\n          webChatLoadError ??\n          new NovuError(\n            isWebChatLoading ? 'Web Chat is still loading' : 'Web Chat runtime is unavailable',\n            new Error('Web Chat runtime is not ready')\n          );\n        propsRef.current.onError?.(error);\n\n        return { error };\n      }\n\n      const response = await action(runtime);\n      if (response.error) {\n        propsRef.current.onError?.(response.error);\n      }\n\n      return response;\n    },\n    [runtime, webChatLoadError, isWebChatLoading, propsRef]\n  );\n\n  const refetch = useCallback(async () => {\n    if (!runtime) {\n      return;\n    }\n\n    const response = await runtime.load();\n    if (response.data) {\n      propsRef.current.onSuccess?.({\n        conversationId: response.data.conversationId,\n        messages: [...response.data.messages],\n        hasMore: response.data.hasMore,\n      });\n    }\n  }, [runtime, propsRef]);\n\n  const fetchMore = useCallback(async () => {\n    const response = await callRuntime((target) => target.fetchMore());\n\n    return {\n      ...response,\n      error: response.error as NovuError | undefined,\n      data: response.data\n        ? {\n            messages: [...response.data.messages],\n            hasMore: response.data.hasMore,\n          }\n        : undefined,\n    };\n  }, [callRuntime]);\n\n  const paginationWithFetch = useMemo(\n    () => ({\n      status: snapshot.pagination.status,\n      hasMore: snapshot.pagination.hasMore,\n      fetchMore,\n    }),\n    [snapshot.pagination.status, snapshot.pagination.hasMore, fetchMore]\n  );\n\n  const sendMessage = useCallback(\n    (input: SendMessageInput) => callRuntime((target) => target.sendMessage(input)),\n    [callRuntime]\n  );\n  const respondToAction = useCallback(\n    (args: { approvalId: string; decision: AgentToolApprovalDecision }) =>\n      callRuntime((target) => target.respondToAction(args)),\n    [callRuntime]\n  );\n  const sendAction = useCallback(\n    (args: { actionId: string; sourceMessageId: string; value?: string }) =>\n      callRuntime((target) => target.sendAction(args)),\n    [callRuntime]\n  );\n  const retryMessage = useCallback(\n    (messageId: string) => callRuntime((target) => target.retryMessage(messageId)),\n    [callRuntime]\n  );\n  const stop = useCallback(() => callRuntime((target) => target.stop()), [callRuntime]);\n  const startNewConversation = useCallback(() => {\n    if (sharedRuntime || conversationIdProp) {\n      return;\n    }\n\n    setCreateEpoch((epoch) => epoch + 1);\n  }, [sharedRuntime, conversationIdProp]);\n\n  return {\n    messages: [...snapshot.messages],\n    pendingActions: [...snapshot.pendingActions],\n    conversationId: snapshot.conversationId,\n    error: webChatLoadError ?? (snapshot.error as UseWebChatResult['error']),\n    isLoading: !webChatLoadError && (isWebChatLoading || snapshot.status === 'loading'),\n    isRunning: snapshot.run.isRunning,\n    isStopping: snapshot.run.isStopping,\n    typing: snapshot.run.typing,\n    conversationStatus: snapshot.conversationStatus,\n    run: snapshot.run,\n    pagination: paginationWithFetch,\n    isRecovering: snapshot.isRecovering,\n    catchUpError: snapshot.catchUpError,\n    refetch,\n    sendMessage,\n    respondToAction,\n    sendAction,\n    retryMessage,\n    stop,\n    startNewConversation,\n  };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,gBAA0B;AAC1B,mBAA+G;AAC/G,wBAA2B;AAC3B,0BAAwB;AAwIxB,IAAM,wBAAwB;AAAA,EAC5B,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,KAAK,EAAE,WAAW,OAAO,YAAY,MAAM;AAAA,EAC3C,oBAAoB;AAAA,EACpB,YAAY,EAAE,SAAS,OAAO,QAAQ,OAAO;AAAA,EAC7C,UAAU,CAAC;AAAA,EACX,gBAA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