@dashx/react 0.3.7 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/cjs/hooks/use-in-app-chat-notifications.d.ts +1 -1
  3. package/dist/cjs/hooks/use-in-app-chat-notifications.js +1 -1
  4. package/dist/cjs/hooks/use-in-app-chat-notifications.js.map +2 -2
  5. package/dist/cjs/hooks/use-in-app-chat.d.ts +15 -13
  6. package/dist/cjs/hooks/use-in-app-chat.js +1 -1
  7. package/dist/cjs/hooks/use-in-app-chat.js.map +3 -3
  8. package/dist/cjs/widgets/InAppChat.d.ts +1 -1
  9. package/dist/cjs/widgets/InAppChat.js +1 -1
  10. package/dist/cjs/widgets/InAppChat.js.map +3 -3
  11. package/dist/cjs/widgets/InAppChatButton.d.ts +1 -1
  12. package/dist/cjs/widgets/InAppChatButton.js +1 -1
  13. package/dist/cjs/widgets/InAppChatButton.js.map +3 -3
  14. package/dist/esm/hooks/use-in-app-chat-notifications.d.ts +1 -1
  15. package/dist/esm/hooks/use-in-app-chat-notifications.js +1 -1
  16. package/dist/esm/hooks/use-in-app-chat-notifications.js.map +2 -2
  17. package/dist/esm/hooks/use-in-app-chat.d.ts +15 -13
  18. package/dist/esm/hooks/use-in-app-chat.js +1 -1
  19. package/dist/esm/hooks/use-in-app-chat.js.map +3 -3
  20. package/dist/esm/widgets/InAppChat.d.ts +1 -1
  21. package/dist/esm/widgets/InAppChat.js +1 -1
  22. package/dist/esm/widgets/InAppChat.js.map +3 -3
  23. package/dist/esm/widgets/InAppChatButton.d.ts +1 -1
  24. package/dist/esm/widgets/InAppChatButton.js +1 -1
  25. package/dist/esm/widgets/InAppChatButton.js.map +3 -3
  26. package/package.json +2 -2
  27. package/src/hooks/use-in-app-chat-notifications.ts +5 -3
  28. package/src/hooks/use-in-app-chat.ts +42 -70
  29. package/src/widgets/InAppChat.tsx +6 -3
  30. package/src/widgets/InAppChatButton.tsx +7 -7
@@ -1,2 +1,2 @@
1
- import q from"uuid-random";import{useCallback as m,useEffect as D,useRef as M,useState as C}from"react";import F from"./use-dashx-provider.js";import{useWebSocket as L}from"../providers/DashXProvider.js";const $="in_app_chat:conversation:",b=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),X=(e,i)=>{const r=new Map,u=t=>t.externalUid||t.id;return[...e,...i].forEach(t=>{const n=r.get(u(t));(!n||n.isPending)&&r.set(u(t),t)}),[...r.values()].sort((t,n)=>t.createdAt!==n.createdAt?t.createdAt<n.createdAt?-1:1:(t.turnSeq??0)-(n.turnSeq??0))},K=({identityId:e,idempotencyKey:i,initialMessage:r,enabled:u=!0,onInboundMessage:t})=>{const n=F(),{isConnected:x,initializeWebSocket:y}=L(),[H,v]=C(null),[w,R]=C([]),[P,I]=C(!0),[E,l]=C(null),o=M(0),A=M(null),U=M(t);U.current=t;const c=m(a=>{R(s=>X(s,a))},[]);D(()=>{const a=o.current+=1,s=()=>a!==o.current;if(v(null),R([]),l(null),A.current=null,!u)return I(!1),()=>{o.current+=1};I(!0),y();let d;return(async()=>{try{const g=r?{identityId:e,clientIdempotencyKey:i,content:{text:r},clientMessageId:`${i.slice(0,122)}-intro`}:{identityId:e,clientIdempotencyKey:i},f=await n.startInAppChatConversation(g);if(s())return;const p=f.id;v(p),A.current=p;const S=async()=>{const h=await n.fetchInAppChatMessages({conversationId:p});s()||c(h.map(b))},k=n.subscribeToChannel(`${$}${p}`,h=>{s()||(c([b(h)]),U.current?.(h))},{onReconnectAck:()=>{s()||(l(null),S().catch(()=>{}))}});d=k.unsubscribe;try{await k.ready}catch{s()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(s())return;await S()}catch{s()||l("Failed to start chat")}finally{s()||I(!1)}})(),()=>{o.current+=1,d?.()}},[n,e,i,r,u,y,c]);const _=m(a=>{const s=A.current;if(!a.trim()||!s)return!1;const d=o.current,g=q(),f={id:g,externalUid:`in_app_chat:${g}`,renderedContent:{text:a},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return c([f]),(async()=>{try{const p=await n.sendInAppChatMessage({conversationId:s,identityId:e,content:{text:a},clientMessageId:g});if(d!==o.current)return;c([b(p)])}catch{d===o.current&&l("Failed to send message")}})(),!0},[n,e,c]);return{conversationId:H,messages:w,isLoading:P,isConnected:x,error:E,sendMessage:_}};var z=K;export{z as default};
1
+ import H from"uuid-random";import{useCallback as b,useEffect as x,useRef as R,useState as C}from"react";import P from"./use-dashx-provider.js";import{useWebSocket as w}from"../providers/DashXProvider.js";const E="in_app_chat:conversation:",f=t=>({id:t.id,externalUid:t.externalUid??null,renderedContent:t.renderedContent,aiRole:t.aiRole??null,createdAt:t.createdAt,turnSeq:t.turnSeq}),_=(t,s)=>{const r=new Map,u=e=>e.externalUid||e.id;return[...t,...s].forEach(e=>{const a=r.get(u(e));(!a||a.isPending)&&r.set(u(e),e)}),[...r.values()].sort((e,a)=>e.createdAt!==a.createdAt?e.createdAt<a.createdAt?-1:1:(e.turnSeq??0)-(a.turnSeq??0))},q=({identityId:t,conversationId:s,enabled:r=!0,onInboundMessage:u})=>{const e=P(),{isConnected:a,initializeWebSocket:M}=w(),[U,I]=C([]),[S,A]=C(!0),[k,l]=C(null),o=R(0),y=R(u);y.current=u;const p=b(i=>{I(n=>_(n,i))},[]);x(()=>{const i=o.current+=1,n=()=>i!==o.current;if(I([]),l(null),!r||!s)return A(!1),()=>{o.current+=1};A(!0),M();let c;return(async()=>{try{const d=async()=>{const h=await e.fetchInAppChatMessages({conversationId:s});n()||p(h.map(f))},g=e.subscribeToChannel(`${E}${s}`,h=>{n()||(p([f(h)]),y.current?.(h))},{onReconnectAck:()=>{n()||(l(null),d().catch(()=>{}))}});c=g.unsubscribe;try{await g.ready}catch{n()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(n())return;await d()}catch{n()||l("Failed to load chat")}finally{n()||A(!1)}})(),()=>{o.current+=1,c?.()}},[e,t,s,r,M,p]);const m=b(i=>{if(!i.trim()||!s||!r)return!1;const n=o.current,c=H(),d={id:c,externalUid:`in_app_chat:${c}`,renderedContent:{text:i},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return p([d]),(async()=>{try{const g=await e.sendInAppChatMessage({conversationId:s,identityId:t,content:{text:i},clientMessageId:c});if(n!==o.current)return;p([f(g)])}catch{n===o.current&&l("Failed to send message")}})(),!0},[e,t,s,r,p]);return{messages:U,isLoading:S,isConnected:a,error:k,sendMessage:m}};var $=q;export{$ as default};
2
2
  //# sourceMappingURL=use-in-app-chat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/hooks/use-in-app-chat.ts"],
4
- "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // Caller-supplied conversation key; the server uses it so repeat opens with\n // the same key resolve to the same conversation thread.\n idempotencyKey: string;\n // Optional automated first message sent when the conversation is first\n // created (e.g. \"Help with order #123\"). Sent via `startInAppChatConversation`\n // with a stable client message id, so it lands exactly once across reopens.\n initialMessage?: string;\n // When false, the hook is idle: no conversation is started, subscribed, or\n // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor\n // first opens the launcher, while keeping the hook mounted afterwards so its\n // subscription (and thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n conversationId: string | null;\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no conversation yet). Synchronous so the caller can clear the\n // composer immediately on `true`; callers keep the input populated on `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat for a visitor.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). The chat mutations require\n * identity-token auth \u2014 if the chat starts before an identity is resolved, they\n * are rejected and the hook surfaces an auth error. It does NOT auto-retry when\n * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014\n * e.g. `{identityToken && <InAppChat \u2026 />}`. `<InAppChatButton>` largely sidesteps\n * this by starting lazily when the visitor opens it, by which point the provider\n * has applied the token.\n */\nconst useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [conversationId, setConversationId] = useState<string | null>(null);\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/key change and on unmount so stale start/fetch/send\n // resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n const conversationIdRef = useRef<string | null>(null);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setConversationId(null);\n setMessages([]);\n setError(null);\n conversationIdRef.current = null;\n\n // Idle until enabled (e.g. before the launcher's first open): don't create a\n // conversation, subscribe, or fetch.\n if (!enabled) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n // `content` + `clientMessageId` travel together: `StartInAppChatConversationArgs`\n // is a union of \"empty start\" and \"start with a first message\", because the\n // backend rejects metadata with no message to attach it to. The branch must\n // therefore stay OUTSIDE the object literal \u2014 a conditional spread collapses to\n // `content?: \u2026 | undefined` and loses the correlation, matching neither arm.\n //\n // Stable client message id \u2192 the automated message is inserted once, even if the\n // conversation is reopened (the server dedups repeat sends). `-` separator\n // (client ids allow only `[A-Za-z0-9._-]`); the key is truncated so the suffixed\n // id stays within the 1-128 char limit.\n const startArgs = initialMessage\n ? {\n identityId,\n clientIdempotencyKey: idempotencyKey,\n content: { text: initialMessage },\n clientMessageId: `${idempotencyKey.slice(0, 122)}-intro`,\n }\n : { identityId, clientIdempotencyKey: idempotencyKey };\n\n const conversation = await dashX.startInAppChatConversation(startArgs);\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
- "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAA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,EAIA,IAAOK,EAAQrC",
6
- "names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "startArgs", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
4
+ "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // The conversation to participate in. This hook does NOT create conversations:\n // creating one is server-only (DashX rejects identity-token callers), so your\n // backend creates it and hands you the id. Pass `null` while you don't have one\n // yet \u2014 the hook stays idle rather than guessing.\n conversationId: string | null;\n // When false, the hook is idle: nothing is subscribed or fetched. Lets\n // `<InAppChatButton>` defer the subscription until the visitor first opens the\n // launcher, while keeping the hook mounted afterwards so its subscription (and\n // thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no `conversationId`, or disabled). Synchronous so the caller can\n // clear the composer immediately on `true`; callers keep the input populated on\n // `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat within an EXISTING conversation.\n *\n * This hook participates; it never creates. Creating a conversation is a\n * server-only operation \u2014 DashX rejects identity-token callers and requires an\n * `accountUid` the browser has no authority to assert, and the conversation's\n * metadata must be derived server-side. So the flow is: your backend creates the\n * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). Fetching history, sending, and\n * subscribing all require identity-token auth \u2014 if they run before an identity is\n * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry\n * when a token arrives later (its inputs are `identityId`/`conversationId`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014 e.g.\n * `{identityToken && <InAppChat \u2026 />}`.\n */\nconst useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/conversation change and on unmount so stale\n // fetch/send resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setMessages([]);\n setError(null);\n\n // Idle until enabled (e.g. before the launcher's first open) and until the\n // caller has a conversation to join: don't subscribe or fetch.\n if (!enabled || !conversationId) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${conversationId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to load chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, conversationId, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n // Not ready (no conversation supplied yet, or the hook is disabled) \u2014 report\n // back so the caller can keep the typed text instead of clearing it on a\n // no-op send.\n if (!text.trim() || !conversationId || !enabled) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, conversationId, enabled, appendMessages],\n );\n\n return { messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
+ "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCA+C7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,CACpBC,EACAC,IACuB,CACvB,MAAMC,EAAQ,IAAI,IACZC,EAASL,GAA8BA,EAAQ,aAAeA,EAAQ,GAE5E,OAAC,GAAGE,EAAU,GAAGC,CAAQ,EAAE,QAASH,GAAY,CAC9C,MAAMM,EAAiBF,EAAM,IAAIC,EAAML,CAAO,CAAC,GAC3C,CAACM,GAAkBA,EAAe,YACpCF,EAAM,IAAIC,EAAML,CAAO,EAAGA,CAAO,CAErC,CAAC,EAEM,CAAC,GAAGI,EAAM,OAAO,CAAC,EAAE,KAAK,CA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,EAAYC,EAAgBC,EAASa,CAAc,CAC7D,EAEA,MAAO,CAAE,SAAAR,EAAU,UAAAE,EAAW,YAAAJ,EAAa,MAAAM,EAAO,YAAAa,CAAY,CAChE,EAIA,IAAOK,EAAQ9B",
6
+ "names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "conversationId", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
7
7
  }
@@ -10,7 +10,7 @@ declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHea
10
10
  type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'> & {
11
11
  notifications?: boolean | InAppChatNotificationOptions;
12
12
  };
13
- declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
13
+ declare const InAppChatWrapper: ({ identityId, conversationId, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
14
14
  export type { InAppChatProps, InAppChatWrapperProps };
15
15
  export { InAppChat };
16
16
  export default InAppChatWrapper;
@@ -1,2 +1,2 @@
1
- import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as b,Flex as s,Heading as T,Popover as S,Text as c,TextArea as k,Theme as H}from"../components";import{cn as x}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",y=({messages:o,isLoading:a,error:l,sendMessage:r,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:d=!1,title:C="Chat"})=>{const[i,h]=w(""),{scrollAreaRef:A,scrollToBottom:g}=R();v(()=>{setTimeout(()=>g({smooth:!0}),0)},[o.length,g]);const f=()=>{i.trim()&&r(i)&&h("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),f())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:x("h-full",!d&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(b,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:x("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(c,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(c,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),l&&e(c,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:l})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:I,onChange:t=>h(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(b,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:f,isDisabled:!i.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,idempotencyKey:a,initialMessage:l,notifications:r=!0,...u})=>{const m=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),d=U({identityId:o,idempotencyKey:a,initialMessage:l,onInboundMessage:m.handleInboundMessage});return e(y,{...d,...u})};var _=E;export{y as InAppChat,_ as default};
1
+ import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as f,Flex as s,Heading as T,Popover as S,Text as d,TextArea as k,Theme as H}from"../components";import{cn as b}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",x=({messages:o,isLoading:a,error:r,sendMessage:i,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:y=!1,title:C="Chat"})=>{const[l,c]=w(""),{scrollAreaRef:A,scrollToBottom:h}=R();v(()=>{setTimeout(()=>h({smooth:!0}),0)},[o.length,h]);const g=()=>{l.trim()&&i(l)&&c("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),g())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:b("h-full",!y&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(f,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:b("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(d,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(d,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&e(d,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:l,onKeyDown:I,onChange:t=>c(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(f,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:g,isDisabled:!l.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,conversationId:a,notifications:r=!0,...i})=>{const u=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),m=U({identityId:o,conversationId:a,onInboundMessage:u.handleInboundMessage});return e(x,{...m,...i})};var _=E;export{x as InAppChat,_ as default};
2
2
  //# sourceMappingURL=InAppChat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChat.tsx"],
4
- "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
- "mappings": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BACP,OAAOC,MAEA,4CASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAU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C,CAAM,IAA6B,CAIlI,MAAMC,EAAW5B,EAA0B,CACzC,OAAQ,GACR,QAAS0B,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKG,EAAO9B,EAAa,CACxB,WAAAwB,EACA,eAAAC,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,OAAO7C,EAACsB,EAAA,CAAW,GAAGwB,EAAO,GAAGF,EAAO,CACzC,EAMA,IAAOG,EAAQR",
6
- "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "notifications", "props", "notifier", "chat", "InAppChat_default"]
4
+ "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\n// `conversationId` is required (inherited from the hook's props): this widget\n// participates in a conversation your BACKEND created \u2014 it cannot create one, because\n// creating a chat is server-only in DashX. Pass `null` while you're still fetching the\n// id and the widget renders its empty/loading state instead of guessing.\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, conversationId, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n conversationId,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
+ "mappings": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BACP,OAAOC,MAEA,4CASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFG,EAAY,CAAC,CACjB,SAAAC,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa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AAQP",
6
+ "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "conversationId", "notifications", "props", "notifier", "chat", "InAppChat_default"]
7
7
  }
@@ -7,6 +7,6 @@ type InAppChatButtonProps = InAppChatWrapperProps & {
7
7
  /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
8
8
  theme?: ThemeProps;
9
9
  };
10
- declare const InAppChatButton: ({ identityId, idempotencyKey, initialMessage, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
10
+ declare const InAppChatButton: ({ identityId, conversationId, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
11
11
  export type { InAppChatButtonProps };
12
12
  export default InAppChatButton;
@@ -1,2 +1,2 @@
1
- import{jsx as t,jsxs as w}from"react/jsx-runtime";import{useCallback as i,useRef as I,useState as A}from"react";import{MessageCircle as O}from"lucide-react";import{Button as v,Flex as T,Popover as p,Theme as y}from"../components";import{InAppChat as B}from"./InAppChat.js";import R from"../hooks/use-in-app-chat.js";import x from"../hooks/use-in-app-chat-notifications.js";const L={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},S=({identityId:h,idempotencyKey:l,initialMessage:u,notifications:e=!0,position:m="bottom-right",theme:f,...c})=>{const[o,n]=A(!1),r=I(!1);o&&(r.current=!0);const g=r.current,C=i(()=>n(!0),[]),{handleInboundMessage:P,requestPermissionOnOpen:s}=x({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:C}),d=i(a=>{a&&s(),n(a)},[s]),b=R({identityId:h,idempotencyKey:l,initialMessage:u,enabled:g,onInboundMessage:P});return t(y,{...f,children:t(T,{className:`fixed z-50 ${L[m]}`,children:w(p.Root,{open:o,onOpenChange:d,children:[t(p.Trigger,{children:t(v,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(O,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(B,{...b,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...c})})]})})})};var H=S;export{H as default};
1
+ import{jsx as t,jsxs as S}from"react/jsx-runtime";import{useCallback as i,useRef as b,useState as I}from"react";import{MessageCircle as A}from"lucide-react";import{Button as O,Flex as v,Popover as p,Theme as T}from"../components";import{InAppChat as y}from"./InAppChat.js";import B from"../hooks/use-in-app-chat.js";import R from"../hooks/use-in-app-chat-notifications.js";const x={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},L=({identityId:h,conversationId:l,notifications:e=!0,position:u="bottom-right",theme:m,...f})=>{const[o,n]=I(!1),r=b(!1);o&&(r.current=!0);const c=r.current,g=i(()=>n(!0),[]),{handleInboundMessage:C,requestPermissionOnOpen:s}=R({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:g}),P=i(a=>{a&&s(),n(a)},[s]),d=B({identityId:h,conversationId:l,enabled:c,onInboundMessage:C});return t(T,{...m,children:t(v,{className:`fixed z-50 ${x[u]}`,children:S(p.Root,{open:o,onOpenChange:P,children:[t(p.Trigger,{children:t(O,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(A,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(y,{...d,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...f})})]})})})};var k=L;export{k as default};
2
2
  //# sourceMappingURL=InAppChatButton.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChatButton.tsx"],
4
- "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n initialMessage,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first\n // open the hook is idle, so no conversation is created on page load.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
- "mappings": "AA2EQ,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBA3ER,OAAgB,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QACrD,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAS,aAAAC,MAA6C,iBACtD,OAAOC,MAAkB,8BACzB,OAAOC,MAA+B,4CAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,EAAInB,EAAS,EAAK,EAMpCoB,EAAerB,EAAO,EAAK,EAC7BmB,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,EAAOxB,EAAY,IAAMqB,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,EAAIhB,EAA0B,CAClF,OAAAU,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKG,EAAmB3B,EACtB4B,GAAsB,CACjBA,GAAUF,EAAwB,EACtCL,EAAUO,CAAQ,CACpB,EACA,CAACF,CAAuB,CAC1B,EAEMG,EAAOpB,EAAa,CACxB,WAAAI,EACA,eAAAC,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,OACE3B,EAACS,EAAA,CAAO,GAAGW,EACT,SAAApB,EAACO,EAAA,CAAK,UAAW,cAAcM,EAAeM,CAAQ,CAAC,GACrD,SAAAlB,EAACO,EAAQ,KAAR,CAAa,KAAMc,EAAQ,aAAcO,EACxC,UAAA7B,EAACQ,EAAQ,QAAR,CACC,SAAAR,EAACM,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGqB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQlB",
6
- "names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "initialMessage", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
4
+ "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n conversationId,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first open\n // the hook is idle, so a page that never opens the launcher does no chat work\n // (no subscription, no history fetch). It never created a conversation either \u2014\n // the conversation is created by your backend and passed in as `conversationId`.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n conversationId,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so a launcher the visitor never opens costs nothing. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
+ "mappings": "AA2EQ,OAGM,OAAAA,EAHN,QAAAC,MAAA,oBA3ER,OAAgB,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QACrD,OAAS,iBAAAC,MAAqB,eAE9B,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,SAAAC,MAA8B,gBAC9D,OAAS,aAAAC,MAA6C,iBACtD,OAAOC,MAAkB,8BACzB,OAAOC,MAA+B,4CAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,EAAIlB,EAAS,EAAK,EAQpCmB,EAAepB,EAAO,EAAK,EAC7BkB,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,EAAOvB,EAAY,IAAMoB,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,EAAIf,EAA0B,CAClF,OAAAS,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKG,EAAmB1B,EACtB2B,GAAsB,CACjBA,GAAUF,EAAwB,EACtCL,EAAUO,CAAQ,CACpB,EACA,CAACF,CAAuB,CAC1B,EAEMG,EAAOnB,EAAa,CACxB,WAAAI,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,OACE1B,EAACS,EAAA,CAAO,GAAGU,EACT,SAAAnB,EAACO,EAAA,CAAK,UAAW,cAAcM,EAAeK,CAAQ,CAAC,GACrD,SAAAjB,EAACO,EAAQ,KAAR,CAAa,KAAMa,EAAQ,aAAcO,EACxC,UAAA5B,EAACQ,EAAQ,QAAR,CACC,SAAAR,EAACM,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGoB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQjB",
6
+ "names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "conversationId", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dashx/react",
3
- "version": "0.3.7",
3
+ "version": "0.4.1",
4
4
  "license": "UNLICENSED",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/cjs/index.js",
@@ -75,7 +75,7 @@
75
75
  "clean": "rm -rf .turbo node_modules dist tokens layout *.css"
76
76
  },
77
77
  "dependencies": {
78
- "@dashx/browser": "^0.9.0",
78
+ "@dashx/browser": "^0.10.0",
79
79
  "@radix-ui/colors": "^3.0.0",
80
80
  "@radix-ui/primitive": "^1.1.3",
81
81
  "@radix-ui/react-accessible-icon": "^1.1.8",
@@ -27,8 +27,10 @@ type UseInAppChatNotificationsProps = {
27
27
  enabled?: boolean;
28
28
  options?: InAppChatNotificationOptions;
29
29
  // Invoked when the visitor clicks a notification — focus is handled by the
30
- // SDK; this opens the chat panel.
31
- onActivate?: () => void;
30
+ // SDK; this opens the chat panel. Receives the message that raised THAT
31
+ // notification, so a surface watching several conversations can open the right
32
+ // one: without it, every notification resolves to whichever arrived last.
33
+ onActivate?: (message: InAppChatMessageData) => void;
32
34
  };
33
35
 
34
36
  const textFromContent = (content: any): string => {
@@ -86,7 +88,7 @@ const useInAppChatNotifications = ({
86
88
  body,
87
89
  icon: optionsRef.current?.icon,
88
90
  tag: message.conversationId ? `in_app_chat:${message.conversationId}` : undefined,
89
- onClick: () => onActivateRef.current?.(),
91
+ onClick: () => onActivateRef.current?.(message),
90
92
  });
91
93
  },
92
94
  [dashX],
@@ -9,17 +9,15 @@ type UseInAppChatHookProps = {
9
9
  // The workspace's chat-identity id (the receiving surface), created when the
10
10
  // chat integration is installed; pasted into config alongside the public key.
11
11
  identityId: string;
12
- // Caller-supplied conversation key; the server uses it so repeat opens with
13
- // the same key resolve to the same conversation thread.
14
- idempotencyKey: string;
15
- // Optional automated first message sent when the conversation is first
16
- // created (e.g. "Help with order #123"). Sent via `startInAppChatConversation`
17
- // with a stable client message id, so it lands exactly once across reopens.
18
- initialMessage?: string;
19
- // When false, the hook is idle: no conversation is started, subscribed, or
20
- // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor
21
- // first opens the launcher, while keeping the hook mounted afterwards so its
22
- // subscription (and thus notifications) survive the panel being closed.
12
+ // The conversation to participate in. This hook does NOT create conversations:
13
+ // creating one is server-only (DashX rejects identity-token callers), so your
14
+ // backend creates it and hands you the id. Pass `null` while you don't have one
15
+ // yet — the hook stays idle rather than guessing.
16
+ conversationId: string | null;
17
+ // When false, the hook is idle: nothing is subscribed or fetched. Lets
18
+ // `<InAppChatButton>` defer the subscription until the visitor first opens the
19
+ // launcher, while keeping the hook mounted afterwards so its subscription (and
20
+ // thus notifications) survive the panel being closed.
23
21
  enabled?: boolean;
24
22
  // Invoked once per LIVE inbound message (not for history load / reconnect
25
23
  // refetch). Drives browser notifications without having to diff backfilled
@@ -41,14 +39,14 @@ type InAppChatMessage = {
41
39
  };
42
40
 
43
41
  type UseInAppChatHookResponse = {
44
- conversationId: string | null;
45
42
  messages: InAppChatMessage[];
46
43
  isLoading: boolean;
47
44
  isConnected: boolean;
48
45
  error: string | null;
49
46
  // Returns `true` if the message was optimistically queued, `false` if the chat
50
- // wasn't ready (no conversation yet). Synchronous so the caller can clear the
51
- // composer immediately on `true`; callers keep the input populated on `false`.
47
+ // wasn't ready (no `conversationId`, or disabled). Synchronous so the caller can
48
+ // clear the composer immediately on `true`; callers keep the input populated on
49
+ // `false`.
52
50
  sendMessage: (text: string) => boolean;
53
51
  };
54
52
 
@@ -91,31 +89,33 @@ const mergeMessages = (
91
89
  };
92
90
 
93
91
  /**
94
- * Two-way InApp Chat for a visitor.
92
+ * Two-way InApp Chat within an EXISTING conversation.
93
+ *
94
+ * This hook participates; it never creates. Creating a conversation is a
95
+ * server-only operation — DashX rejects identity-token callers and requires an
96
+ * `accountUid` the browser has no authority to assert, and the conversation's
97
+ * metadata must be derived server-side. So the flow is: your backend creates the
98
+ * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
95
99
  *
96
100
  * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
97
- * `identityToken` (and matching `identityUid`). The chat mutations require
98
- * identity-token auth — if the chat starts before an identity is resolved, they
99
- * are rejected and the hook surfaces an auth error. It does NOT auto-retry when
100
- * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
101
- * visitor token), so only render the chat once `identityToken` is available —
102
- * e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
103
- * this by starting lazily when the visitor opens it, by which point the provider
104
- * has applied the token.
101
+ * `identityToken` (and matching `identityUid`). Fetching history, sending, and
102
+ * subscribing all require identity-token auth — if they run before an identity is
103
+ * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
104
+ * when a token arrives later (its inputs are `identityId`/`conversationId`, not the
105
+ * visitor token), so only render the chat once `identityToken` is available — e.g.
106
+ * `{identityToken && <InAppChat … />}`.
105
107
  */
106
- const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
108
+ const useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
107
109
  const dashX = useDashXProvider();
108
110
  const { isConnected, initializeWebSocket } = useWebSocket();
109
111
 
110
- const [conversationId, setConversationId] = useState<string | null>(null);
111
112
  const [messages, setMessages] = useState<InAppChatMessage[]>([]);
112
113
  const [isLoading, setIsLoading] = useState(true);
113
114
  const [error, setError] = useState<string | null>(null);
114
115
 
115
- // Bumped on every identity/key change and on unmount so stale start/fetch/send
116
- // resolutions are ignored (the classic React async race).
116
+ // Bumped on every identity/conversation change and on unmount so stale
117
+ // fetch/send resolutions are ignored (the classic React async race).
117
118
  const generationRef = useRef(0);
118
- const conversationIdRef = useRef<string | null>(null);
119
119
 
120
120
  // Latest live-message callback, kept in a ref so changing its identity doesn't
121
121
  // tear down and re-create the channel subscription.
@@ -130,14 +130,12 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
130
130
  const generation = (generationRef.current += 1);
131
131
  const isStale = () => generation !== generationRef.current;
132
132
 
133
- setConversationId(null);
134
133
  setMessages([]);
135
134
  setError(null);
136
- conversationIdRef.current = null;
137
135
 
138
- // Idle until enabled (e.g. before the launcher's first open): don't create a
139
- // conversation, subscribe, or fetch.
140
- if (!enabled) {
136
+ // Idle until enabled (e.g. before the launcher's first open) and until the
137
+ // caller has a conversation to join: don't subscribe or fetch.
138
+ if (!enabled || !conversationId) {
141
139
  setIsLoading(false);
142
140
  return () => { generationRef.current += 1; };
143
141
  }
@@ -151,34 +149,8 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
151
149
 
152
150
  (async () => {
153
151
  try {
154
- // `content` + `clientMessageId` travel together: `StartInAppChatConversationArgs`
155
- // is a union of "empty start" and "start with a first message", because the
156
- // backend rejects metadata with no message to attach it to. The branch must
157
- // therefore stay OUTSIDE the object literal — a conditional spread collapses to
158
- // `content?: … | undefined` and loses the correlation, matching neither arm.
159
- //
160
- // Stable client message id → the automated message is inserted once, even if the
161
- // conversation is reopened (the server dedups repeat sends). `-` separator
162
- // (client ids allow only `[A-Za-z0-9._-]`); the key is truncated so the suffixed
163
- // id stays within the 1-128 char limit.
164
- const startArgs = initialMessage
165
- ? {
166
- identityId,
167
- clientIdempotencyKey: idempotencyKey,
168
- content: { text: initialMessage },
169
- clientMessageId: `${idempotencyKey.slice(0, 122)}-intro`,
170
- }
171
- : { identityId, clientIdempotencyKey: idempotencyKey };
172
-
173
- const conversation = await dashX.startInAppChatConversation(startArgs);
174
- if (isStale()) return;
175
-
176
- const convId = conversation.id;
177
- setConversationId(convId);
178
- conversationIdRef.current = convId;
179
-
180
152
  const refetchHistory = async () => {
181
- const history = await dashX.fetchInAppChatMessages({ conversationId: convId });
153
+ const history = await dashX.fetchInAppChatMessages({ conversationId });
182
154
  if (isStale()) return;
183
155
  appendMessages(history.map(toUiMessage));
184
156
  };
@@ -188,7 +160,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
188
160
  // on a first ack that arrives after a `ready` timeout — both mean we are
189
161
  // (now) subscribed, so clear any connection error and (re)load history.
190
162
  const subscription = dashX.subscribeToChannel(
191
- `${CHAT_CHANNEL_PREFIX}${convId}`,
163
+ `${CHAT_CHANNEL_PREFIX}${conversationId}`,
192
164
  (event) => {
193
165
  if (isStale()) return;
194
166
  appendMessages([toUiMessage(event)]);
@@ -220,7 +192,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
220
192
  if (isStale()) return;
221
193
  await refetchHistory();
222
194
  } catch {
223
- if (!isStale()) setError('Failed to start chat');
195
+ if (!isStale()) setError('Failed to load chat');
224
196
  } finally {
225
197
  if (!isStale()) setIsLoading(false);
226
198
  }
@@ -232,7 +204,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
232
204
  generationRef.current += 1;
233
205
  unsubscribe?.();
234
206
  };
235
- }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);
207
+ }, [dashX, identityId, conversationId, enabled, initializeWebSocket, appendMessages]);
236
208
 
237
209
  // Synchronous on purpose: it returns `true` the moment the message is optimistically
238
210
  // queued and runs the network send in the background. The caller clears the composer
@@ -241,10 +213,10 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
241
213
  // backend won't dedupe it) and create a duplicate.
242
214
  const sendMessage = useCallback(
243
215
  (text: string): boolean => {
244
- const convId = conversationIdRef.current;
245
- // Not ready (conversation still starting, or start failed) — report back so
246
- // the caller can keep the typed text instead of clearing it on a no-op send.
247
- if (!text.trim() || !convId) return false;
216
+ // Not ready (no conversation supplied yet, or the hook is disabled) — report
217
+ // back so the caller can keep the typed text instead of clearing it on a
218
+ // no-op send.
219
+ if (!text.trim() || !conversationId || !enabled) return false;
248
220
 
249
221
  // Pin the generation so a response that resolves after the identity/key
250
222
  // changed (or unmount) can't contaminate the new conversation's state.
@@ -263,7 +235,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
263
235
  void (async () => {
264
236
  try {
265
237
  const serverMessage = await dashX.sendInAppChatMessage({
266
- conversationId: convId,
238
+ conversationId,
267
239
  identityId,
268
240
  content: { text },
269
241
  clientMessageId,
@@ -279,10 +251,10 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
279
251
  // Queued (optimistically appended) — the background send reconciles/errors later.
280
252
  return true;
281
253
  },
282
- [dashX, identityId, appendMessages],
254
+ [dashX, identityId, conversationId, enabled, appendMessages],
283
255
  );
284
256
 
285
- return { conversationId, messages, isLoading, isConnected, error, sendMessage };
257
+ return { messages, isLoading, isConnected, error, sendMessage };
286
258
  };
287
259
 
288
260
  export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
@@ -154,6 +154,10 @@ const InAppChat = ({
154
154
  );
155
155
  };
156
156
 
157
+ // `conversationId` is required (inherited from the hook's props): this widget
158
+ // participates in a conversation your BACKEND created — it cannot create one, because
159
+ // creating a chat is server-only in DashX. Pass `null` while you're still fetching the
160
+ // id and the widget renders its empty/loading state instead of guessing.
157
161
  type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>
158
162
  & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>
159
163
  & {
@@ -165,7 +169,7 @@ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse
165
169
  notifications?: boolean | InAppChatNotificationOptions;
166
170
  };
167
171
 
168
- const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {
172
+ const InAppChatWrapper = ({ identityId, conversationId, notifications = true, ...props }: InAppChatWrapperProps) => {
169
173
  // Always-visible surface: treat as "open" and gate notifications on tab
170
174
  // visibility/focus only. No launcher gesture exists here, so default to
171
175
  // 'manual' permission (auto-requesting would prompt on mount).
@@ -179,8 +183,7 @@ const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifica
179
183
  });
180
184
  const chat = useInAppChat({
181
185
  identityId,
182
- idempotencyKey,
183
- initialMessage,
186
+ conversationId,
184
187
  onInboundMessage: notifier.handleInboundMessage,
185
188
  });
186
189
  return <InAppChat {...chat} {...props} />;
@@ -25,8 +25,7 @@ const POSITION_CLASS: Record<LauncherPosition, string> = {
25
25
 
26
26
  const InAppChatButton = ({
27
27
  identityId,
28
- idempotencyKey,
29
- initialMessage,
28
+ conversationId,
30
29
  notifications = true,
31
30
  position = 'bottom-right',
32
31
  theme,
@@ -36,8 +35,10 @@ const InAppChatButton = ({
36
35
 
37
36
  // Latch: once the launcher has been opened, keep the chat hook active so its
38
37
  // channel subscription persists while the panel is closed — that's what lets
39
- // us notify on replies that land while the panel is shut. Before the first
40
- // open the hook is idle, so no conversation is created on page load.
38
+ // us notify on replies that land while the panel is shut. Before the first open
39
+ // the hook is idle, so a page that never opens the launcher does no chat work
40
+ // (no subscription, no history fetch). It never created a conversation either —
41
+ // the conversation is created by your backend and passed in as `conversationId`.
41
42
  const hasOpenedRef = useRef(false);
42
43
  if (isOpen) hasOpenedRef.current = true;
43
44
  const enabled = hasOpenedRef.current;
@@ -64,8 +65,7 @@ const InAppChatButton = ({
64
65
 
65
66
  const chat = useInAppChat({
66
67
  identityId,
67
- idempotencyKey,
68
- initialMessage,
68
+ conversationId,
69
69
  enabled,
70
70
  onInboundMessage: handleInboundMessage,
71
71
  });
@@ -82,7 +82,7 @@ const InAppChatButton = ({
82
82
  {/* The chat hook lives at the launcher level (above the popover) so its
83
83
  subscription survives the panel closing — required to notify on
84
84
  replies that arrive while the panel is shut. It activates lazily on
85
- first open, so no empty conversation is created on page load. */}
85
+ first open, so a launcher the visitor never opens costs nothing. */}
86
86
  <Popover.Content spacing="large" width="350px" height="450px">
87
87
  <InAppChat
88
88
  {...chat}