@dashx/react 0.2.3 → 0.3.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 (58) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/cjs/hooks/index.d.ts +3 -0
  3. package/dist/cjs/hooks/index.js +1 -1
  4. package/dist/cjs/hooks/index.js.map +3 -3
  5. package/dist/cjs/hooks/use-in-app-chat-notifications.d.ts +27 -0
  6. package/dist/cjs/hooks/use-in-app-chat-notifications.js +2 -0
  7. package/dist/cjs/hooks/use-in-app-chat-notifications.js.map +7 -0
  8. package/dist/cjs/hooks/use-in-app-chat.d.ts +41 -0
  9. package/dist/cjs/hooks/use-in-app-chat.js +2 -0
  10. package/dist/cjs/hooks/use-in-app-chat.js.map +7 -0
  11. package/dist/cjs/providers/DashXProvider.d.ts +15 -1
  12. package/dist/cjs/providers/DashXProvider.js +1 -1
  13. package/dist/cjs/providers/DashXProvider.js.map +3 -3
  14. package/dist/cjs/widgets/InAppChat.d.ts +16 -0
  15. package/dist/cjs/widgets/InAppChat.js +2 -0
  16. package/dist/cjs/widgets/InAppChat.js.map +7 -0
  17. package/dist/cjs/widgets/InAppChatButton.d.ts +12 -0
  18. package/dist/cjs/widgets/InAppChatButton.js +2 -0
  19. package/dist/cjs/widgets/InAppChatButton.js.map +7 -0
  20. package/dist/cjs/widgets/index.d.ts +2 -0
  21. package/dist/cjs/widgets/index.js +1 -1
  22. package/dist/cjs/widgets/index.js.map +3 -3
  23. package/dist/esm/hooks/index.d.ts +3 -0
  24. package/dist/esm/hooks/index.js +1 -1
  25. package/dist/esm/hooks/index.js.map +2 -2
  26. package/dist/esm/hooks/use-in-app-chat-notifications.d.ts +27 -0
  27. package/dist/esm/hooks/use-in-app-chat-notifications.js +2 -0
  28. package/dist/esm/hooks/use-in-app-chat-notifications.js.map +7 -0
  29. package/dist/esm/hooks/use-in-app-chat.d.ts +41 -0
  30. package/dist/esm/hooks/use-in-app-chat.js +2 -0
  31. package/dist/esm/hooks/use-in-app-chat.js.map +7 -0
  32. package/dist/esm/providers/DashXProvider.d.ts +15 -1
  33. package/dist/esm/providers/DashXProvider.js +1 -1
  34. package/dist/esm/providers/DashXProvider.js.map +3 -3
  35. package/dist/esm/widgets/InAppChat.d.ts +16 -0
  36. package/dist/esm/widgets/InAppChat.js +2 -0
  37. package/dist/esm/widgets/InAppChat.js.map +7 -0
  38. package/dist/esm/widgets/InAppChatButton.d.ts +12 -0
  39. package/dist/esm/widgets/InAppChatButton.js +2 -0
  40. package/dist/esm/widgets/InAppChatButton.js.map +7 -0
  41. package/dist/esm/widgets/index.d.ts +2 -0
  42. package/dist/esm/widgets/index.js +1 -1
  43. package/dist/esm/widgets/index.js.map +2 -2
  44. package/package.json +2 -2
  45. package/src/hooks/index.ts +3 -0
  46. package/src/hooks/use-in-app-chat-notifications.ts +117 -0
  47. package/src/hooks/use-in-app-chat.ts +281 -0
  48. package/src/providers/DashXProvider.tsx +74 -7
  49. package/src/widgets/InAppChat.tsx +193 -0
  50. package/src/widgets/InAppChatButton.tsx +103 -0
  51. package/src/widgets/index.ts +2 -0
  52. package/styles.css +6 -0
  53. package/dist/cjs/widgets/NotificationBell.d.ts +0 -2
  54. package/dist/cjs/widgets/NotificationBell.js +0 -2
  55. package/dist/cjs/widgets/NotificationBell.js.map +0 -7
  56. package/dist/esm/widgets/NotificationBell.d.ts +0 -2
  57. package/dist/esm/widgets/NotificationBell.js +0 -2
  58. package/dist/esm/widgets/NotificationBell.js.map +0 -7
@@ -0,0 +1,281 @@
1
+ import uuid from 'uuid-random';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import type { InAppChatMessageData } from '@dashx/browser';
4
+
5
+ import useDashXProvider from './use-dashx-provider.js';
6
+ import { useWebSocket } from '../providers/DashXProvider.js';
7
+
8
+ type UseInAppChatHookProps = {
9
+ // The workspace's chat-identity id (the receiving surface), created when the
10
+ // chat integration is installed; pasted into config alongside the public key.
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.
23
+ enabled?: boolean;
24
+ // Invoked once per LIVE inbound message (not for history load / reconnect
25
+ // refetch). Drives browser notifications without having to diff backfilled
26
+ // history against live events.
27
+ onInboundMessage?: (message: InAppChatMessageData) => void;
28
+ };
29
+
30
+ // UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and
31
+ // drives alignment; it arrives lowercase ('user'/'assistant'), so the widget
32
+ // compares it case-insensitively (see `isOutgoing`).
33
+ type InAppChatMessage = {
34
+ id: string;
35
+ externalUid: string | null;
36
+ renderedContent: any;
37
+ aiRole: string | null;
38
+ createdAt: string;
39
+ turnSeq?: number;
40
+ isPending?: boolean;
41
+ };
42
+
43
+ type UseInAppChatHookResponse = {
44
+ conversationId: string | null;
45
+ messages: InAppChatMessage[];
46
+ isLoading: boolean;
47
+ isConnected: boolean;
48
+ error: string | null;
49
+ // 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`.
52
+ sendMessage: (text: string) => boolean;
53
+ };
54
+
55
+ const CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';
56
+
57
+ const toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({
58
+ id: message.id,
59
+ // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as
60
+ // optional; normalize the absent case to null for the UI message shape.
61
+ externalUid: message.externalUid ?? null,
62
+ renderedContent: message.renderedContent,
63
+ aiRole: message.aiRole ?? null,
64
+ createdAt: message.createdAt,
65
+ turnSeq: message.turnSeq,
66
+ });
67
+
68
+ // Dedup by externalUid (server message replaces the optimistic pending one)
69
+ // then id; order by createdAt as the authoritative key. `turnSeq` isn't in the
70
+ // fetched message fields, so it's absent from history (which already arrives
71
+ // ordered, preserved by the stable sort); it only breaks same-createdAt ties
72
+ // among realtime WS events, which carry it.
73
+ const mergeMessages = (
74
+ existing: InAppChatMessage[],
75
+ incoming: InAppChatMessage[],
76
+ ): InAppChatMessage[] => {
77
+ const byKey = new Map<string, InAppChatMessage>();
78
+ const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;
79
+
80
+ [...existing, ...incoming].forEach((message) => {
81
+ const existingForKey = byKey.get(keyOf(message));
82
+ if (!existingForKey || existingForKey.isPending) {
83
+ byKey.set(keyOf(message), message);
84
+ }
85
+ });
86
+
87
+ return [...byKey.values()].sort((a, b) => {
88
+ if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;
89
+ return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);
90
+ });
91
+ };
92
+
93
+ /**
94
+ * Two-way InApp Chat for a visitor.
95
+ *
96
+ * 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.
105
+ */
106
+ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
107
+ const dashX = useDashXProvider();
108
+ const { isConnected, initializeWebSocket } = useWebSocket();
109
+
110
+ const [conversationId, setConversationId] = useState<string | null>(null);
111
+ const [messages, setMessages] = useState<InAppChatMessage[]>([]);
112
+ const [isLoading, setIsLoading] = useState(true);
113
+ const [error, setError] = useState<string | null>(null);
114
+
115
+ // Bumped on every identity/key change and on unmount so stale start/fetch/send
116
+ // resolutions are ignored (the classic React async race).
117
+ const generationRef = useRef(0);
118
+ const conversationIdRef = useRef<string | null>(null);
119
+
120
+ // Latest live-message callback, kept in a ref so changing its identity doesn't
121
+ // tear down and re-create the channel subscription.
122
+ const onInboundMessageRef = useRef(onInboundMessage);
123
+ onInboundMessageRef.current = onInboundMessage;
124
+
125
+ const appendMessages = useCallback((incoming: InAppChatMessage[]) => {
126
+ setMessages((prev) => mergeMessages(prev, incoming));
127
+ }, []);
128
+
129
+ useEffect(() => {
130
+ const generation = (generationRef.current += 1);
131
+ const isStale = () => generation !== generationRef.current;
132
+
133
+ setConversationId(null);
134
+ setMessages([]);
135
+ setError(null);
136
+ conversationIdRef.current = null;
137
+
138
+ // Idle until enabled (e.g. before the launcher's first open): don't create a
139
+ // conversation, subscribe, or fetch.
140
+ if (!enabled) {
141
+ setIsLoading(false);
142
+ return () => { generationRef.current += 1; };
143
+ }
144
+
145
+ setIsLoading(true);
146
+
147
+ // Ensure the WS exists (idempotent — returns early if already created).
148
+ initializeWebSocket();
149
+
150
+ let unsubscribe: (() => void) | undefined;
151
+
152
+ (async () => {
153
+ try {
154
+ const conversation = await dashX.startInAppChatConversation({
155
+ identityId,
156
+ clientIdempotencyKey: idempotencyKey,
157
+ // Stable client message id → the automated message is inserted once,
158
+ // even if the conversation is reopened (the server dedups repeat sends).
159
+ // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is
160
+ // truncated so the suffixed id stays within the 1-128 char limit.
161
+ ...(initialMessage
162
+ ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }
163
+ : {}),
164
+ });
165
+ if (isStale()) return;
166
+
167
+ const convId = conversation.id;
168
+ setConversationId(convId);
169
+ conversationIdRef.current = convId;
170
+
171
+ const refetchHistory = async () => {
172
+ const history = await dashX.fetchInAppChatMessages({ conversationId: convId });
173
+ if (isStale()) return;
174
+ appendMessages(history.map(toUiMessage));
175
+ };
176
+
177
+ // Subscribe BEFORE fetching history so a reply landing in the gap is
178
+ // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and
179
+ // on a first ack that arrives after a `ready` timeout — both mean we are
180
+ // (now) subscribed, so clear any connection error and (re)load history.
181
+ const subscription = dashX.subscribeToChannel(
182
+ `${CHAT_CHANNEL_PREFIX}${convId}`,
183
+ (event) => {
184
+ if (isStale()) return;
185
+ appendMessages([toUiMessage(event)]);
186
+ // LIVE messages only — history load / reconnect refetch go through
187
+ // `refetchHistory`, so notification consumers never fire for
188
+ // backfilled messages.
189
+ onInboundMessageRef.current?.(event);
190
+ },
191
+ {
192
+ onReconnectAck: () => {
193
+ if (isStale()) return;
194
+ setError(null);
195
+ refetchHistory().catch(() => {});
196
+ },
197
+ },
198
+ );
199
+ unsubscribe = subscription.unsubscribe;
200
+
201
+ // Load history only once the subscription is acked — fetching before
202
+ // that would show history while silently never receiving realtime
203
+ // replies. On ack failure, surface an error and defer the fetch to
204
+ // `onReconnectAck` (fires if/when the channel finally acks).
205
+ try {
206
+ await subscription.ready;
207
+ } catch {
208
+ if (!isStale()) setError('Couldn’t connect to live chat. Retrying…');
209
+ return;
210
+ }
211
+ if (isStale()) return;
212
+ await refetchHistory();
213
+ } catch {
214
+ if (!isStale()) setError('Failed to start chat');
215
+ } finally {
216
+ if (!isStale()) setIsLoading(false);
217
+ }
218
+ })();
219
+
220
+ return () => {
221
+ // Invalidate in-flight async and drop the old channel before the next
222
+ // conversation binds.
223
+ generationRef.current += 1;
224
+ unsubscribe?.();
225
+ };
226
+ }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);
227
+
228
+ // Synchronous on purpose: it returns `true` the moment the message is optimistically
229
+ // queued and runs the network send in the background. The caller clears the composer
230
+ // on `true` immediately — if it instead awaited the round-trip, a fast second Enter
231
+ // would re-send the still-present text as a new message (fresh clientMessageId, so the
232
+ // backend won't dedupe it) and create a duplicate.
233
+ const sendMessage = useCallback(
234
+ (text: string): boolean => {
235
+ const convId = conversationIdRef.current;
236
+ // Not ready (conversation still starting, or start failed) — report back so
237
+ // the caller can keep the typed text instead of clearing it on a no-op send.
238
+ if (!text.trim() || !convId) return false;
239
+
240
+ // Pin the generation so a response that resolves after the identity/key
241
+ // changed (or unmount) can't contaminate the new conversation's state.
242
+ const generation = generationRef.current;
243
+ const clientMessageId = uuid();
244
+ const optimistic: InAppChatMessage = {
245
+ id: clientMessageId,
246
+ externalUid: `in_app_chat:${clientMessageId}`,
247
+ renderedContent: { text },
248
+ aiRole: 'USER',
249
+ createdAt: new Date().toISOString(),
250
+ isPending: true,
251
+ };
252
+ appendMessages([optimistic]);
253
+
254
+ void (async () => {
255
+ try {
256
+ const serverMessage = await dashX.sendInAppChatMessage({
257
+ conversationId: convId,
258
+ identityId,
259
+ content: { text },
260
+ clientMessageId,
261
+ });
262
+ if (generation !== generationRef.current) return;
263
+ // Reconcile by externalUid (the WS echo reconciles too — both idempotent).
264
+ appendMessages([toUiMessage(serverMessage)]);
265
+ } catch {
266
+ if (generation === generationRef.current) setError('Failed to send message');
267
+ }
268
+ })();
269
+
270
+ // Queued (optimistically appended) — the background send reconciles/errors later.
271
+ return true;
272
+ },
273
+ [dashX, identityId, appendMessages],
274
+ );
275
+
276
+ return { conversationId, messages, isLoading, isConnected, error, sendMessage };
277
+ };
278
+
279
+ export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
280
+
281
+ export default useInAppChat;
@@ -15,7 +15,21 @@ const WebSocketContext = createContext<WebSocketContextType | null>(null);
15
15
 
16
16
  type DashXProviderProps = ClientParams & {
17
17
  initializeWebSocketOnLoad?: boolean,
18
- webSocketQueryParams?: Record<string, any>
18
+ webSocketQueryParams?: Record<string, any>,
19
+ /**
20
+ * The visitor's account uid, addressed on both transports (GraphQL + WS).
21
+ * Pass `null` to explicitly clear it (e.g. on logout); omit (`undefined`) to
22
+ * leave it unchanged. Pair with `identityToken` for the same identity.
23
+ */
24
+ identityUid?: string | null,
25
+ /**
26
+ * Identity token (minted with your DashX server SDK's `generateIdentityToken`,
27
+ * or from an exchange endpoint you control). When set, the SDK uses it for both
28
+ * GraphQL (`X-Identity-Token` header) and the WebSocket handshake — the server
29
+ * identifies the visitor from it, which is the ownership key for InApp Chat.
30
+ * Pass `null` to clear it on logout; omit (`undefined`) to leave it unchanged.
31
+ */
32
+ identityToken?: string | null,
19
33
  }
20
34
 
21
35
  function DashXProvider({
@@ -28,20 +42,43 @@ function DashXProvider({
28
42
  targetVersion,
29
43
  initializeWebSocketOnLoad = false,
30
44
  webSocketQueryParams = {},
45
+ identityUid,
46
+ identityToken,
31
47
  }: React.PropsWithChildren<DashXProviderProps>) {
32
48
  const dashX = React.useMemo(
33
- () =>
34
- DashX.configure({
49
+ () => {
50
+ const client = DashX.configure({
35
51
  publicKey: publicKey,
36
52
  baseUri: baseUri,
37
53
  realtimeBaseUri: realtimeBaseUri,
38
54
  targetEnvironment: targetEnvironment,
39
55
  targetProduct,
40
56
  targetVersion,
41
- }),
57
+ });
58
+ // Apply identity synchronously at creation so a child that starts work in
59
+ // its own mount effect (child effects run before this provider's effects)
60
+ // sees the token already set. Later prop changes go through the effect
61
+ // below; identity is intentionally not a useMemo dep (we don't recreate
62
+ // the client when it changes).
63
+ if (identityUid !== undefined || identityToken !== undefined) {
64
+ client.setIdentity(identityUid, identityToken);
65
+ }
66
+ return client;
67
+ },
68
+ // eslint-disable-next-line react-hooks/exhaustive-deps
42
69
  [publicKey, baseUri, realtimeBaseUri, targetEnvironment, targetProduct, targetVersion],
43
70
  );
44
71
 
72
+ // `webSocketQueryParams` defaults to a fresh `{}` each render and is a dep of
73
+ // the effects below, so memoize on its content to keep the reference stable —
74
+ // otherwise those effects (setIdentity / WS init) re-run on every render.
75
+ const webSocketQueryParamsKey = JSON.stringify(webSocketQueryParams ?? {});
76
+ const stableWebSocketQueryParams = React.useMemo(
77
+ () => webSocketQueryParams ?? {},
78
+ // eslint-disable-next-line react-hooks/exhaustive-deps
79
+ [webSocketQueryParamsKey],
80
+ );
81
+
45
82
  // WebSocket state
46
83
  const [isConnected, setIsConnected] = useState(false);
47
84
  const wsManagerRef = useRef<WebSocketManager | null>(null);
@@ -74,6 +111,10 @@ function DashXProvider({
74
111
  const queryParams = {
75
112
  publicKey: dashX.publicKey,
76
113
  ...(dashX.targetEnvironment && { targetEnvironment: dashX.targetEnvironment }),
114
+ // Provider-level defaults apply to every provider-owned socket — including
115
+ // when the chat hook (or any consumer) opens the socket first by calling
116
+ // `initializeWebSocket()` with no args. Explicit call-site params override.
117
+ ...stableWebSocketQueryParams,
77
118
  ...customQueryParams,
78
119
  };
79
120
 
@@ -109,13 +150,39 @@ function DashXProvider({
109
150
 
110
151
  wsManagerRef.current = wsManager;
111
152
  wsManager.connect();
112
- }, [dashX]);
153
+ }, [dashX, stableWebSocketQueryParams]);
154
+
155
+ // Forward `identityUid` + `identityToken` into the dashX client so the same
156
+ // identity is used by GraphQL and the WS. Pass the props as-is: `setIdentity`
157
+ // treats `undefined` as "leave unchanged", so setting only `identityToken`
158
+ // won't clobber an existing account uid (and vice versa).
159
+ const previousIdentityTokenRef = useRef(identityToken);
160
+ useEffect(() => {
161
+ if (!dashX || (identityUid === undefined && identityToken === undefined)) {
162
+ return;
163
+ }
164
+
165
+ dashX.setIdentity(identityUid, identityToken);
166
+
167
+ // This provider owns the socket (created via `createWebSocketConnection`,
168
+ // not the client's internal manager that `setIdentity` reconnects), so on a
169
+ // token change we recreate it here to put the new identity_token in the WS
170
+ // URL. GraphQL picks up the new header on its own; tracked chat channels
171
+ // re-subscribe on the new socket's `onOpen`.
172
+ const tokenChanged = identityToken !== previousIdentityTokenRef.current;
173
+ previousIdentityTokenRef.current = identityToken;
174
+ if (tokenChanged && wsManagerRef.current) {
175
+ wsManagerRef.current.disconnect();
176
+ wsManagerRef.current = null;
177
+ initializeWebSocket(stableWebSocketQueryParams);
178
+ }
179
+ }, [ dashX, identityUid, identityToken, initializeWebSocket, stableWebSocketQueryParams ]);
113
180
 
114
181
  useEffect(() => {
115
182
  if (initializeWebSocketOnLoad) {
116
- initializeWebSocket(webSocketQueryParams);
183
+ initializeWebSocket(stableWebSocketQueryParams);
117
184
  }
118
- }, [ initializeWebSocketOnLoad, webSocketQueryParams ]);
185
+ }, [ initializeWebSocketOnLoad, initializeWebSocket, stableWebSocketQueryParams ]);
119
186
 
120
187
  return (
121
188
  <DashXContext.Provider value={dashX}>
@@ -0,0 +1,193 @@
1
+ import * as ScrollArea from '@radix-ui/react-scroll-area';
2
+ import React, { useEffect, useState } from 'react';
3
+ import { Send, X } from 'lucide-react';
4
+ import type { KeyboardEvent } from 'react';
5
+
6
+ import { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';
7
+ import { cn } from '../utils/cn.js';
8
+ import useAutoScroll from '../hooks/use-auto-scroll.js';
9
+ import useInAppChat, {
10
+ type InAppChatMessage,
11
+ type UseInAppChatHookProps,
12
+ type UseInAppChatHookResponse,
13
+ } from '../hooks/use-in-app-chat.js';
14
+ import useInAppChatNotifications, {
15
+ type InAppChatNotificationOptions,
16
+ } from '../hooks/use-in-app-chat-notifications.js';
17
+
18
+ type InAppChatProps = UseInAppChatHookResponse & {
19
+ withChatHeader?: boolean;
20
+ withPopoverClose?: boolean;
21
+ borderless?: boolean;
22
+ title?: string;
23
+ };
24
+
25
+ const messageText = (message: InAppChatMessage): string => {
26
+ const content = message.renderedContent;
27
+ if (typeof content === 'string') return content;
28
+ return content?.text ?? '';
29
+ };
30
+
31
+ const isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';
32
+
33
+ const InAppChat = ({
34
+ messages,
35
+ isLoading,
36
+ error,
37
+ sendMessage,
38
+ withChatHeader = false,
39
+ withPopoverClose = false,
40
+ borderless = false,
41
+ title = 'Chat',
42
+ }: InAppChatProps) => {
43
+ const [inputValue, setInputValue] = useState('');
44
+ const { scrollAreaRef, scrollToBottom } = useAutoScroll();
45
+
46
+ useEffect(() => {
47
+ setTimeout(() => scrollToBottom({ smooth: true }), 0);
48
+ }, [messages.length, scrollToBottom]);
49
+
50
+ const handleSubmit = () => {
51
+ if (!inputValue.trim()) return;
52
+ // `sendMessage` is synchronous: it returns true the instant the message is
53
+ // optimistically queued (network send runs in the background). Clear the
54
+ // composer right away on success so a fast second Enter can't re-send the same
55
+ // text as a duplicate; on false (chat not ready) keep the visitor's text.
56
+ if (sendMessage(inputValue)) setInputValue('');
57
+ };
58
+
59
+ const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
60
+ if (e.key === 'Enter' && !e.shiftKey) {
61
+ e.preventDefault();
62
+ handleSubmit();
63
+ }
64
+ };
65
+
66
+ return (
67
+ <Theme asChild>
68
+ <Flex direction="column" className={cn('h-full', !borderless && 'border border-gray-400/40')}>
69
+ {withChatHeader && (
70
+ <Flex align="center" justify="between" className="border-b border-b-gray-400/40 px-6 py-4">
71
+ <Heading size={3}>{title}</Heading>
72
+ {withPopoverClose && (
73
+ <Popover.Close>
74
+ <Button shape="square" roundness="full" variant="ghost" mode="subtle" inset="right">
75
+ <X />
76
+ </Button>
77
+ </Popover.Close>
78
+ )}
79
+ </Flex>
80
+ )}
81
+
82
+ <Flex direction="column" className="grow overflow-auto bg-gray-50">
83
+ <ScrollArea.Root ref={scrollAreaRef} className="h-full grow p-6">
84
+ <ScrollArea.Viewport className="h-full">
85
+ <Flex direction="column" gap={3}>
86
+ {messages.map((message) => (
87
+ <div
88
+ key={message.externalUid || message.id}
89
+ className={cn(
90
+ 'max-w-[80%] rounded-lg py-2 px-3',
91
+ isOutgoing(message)
92
+ ? 'bg-accent-600 ml-auto items-end text-white'
93
+ : 'bg-gray-200 mr-auto items-start text-gray-900',
94
+ )}
95
+ >
96
+ <Text as="p" size={2}>{messageText(message)}</Text>
97
+ </div>
98
+ ))}
99
+
100
+ {isLoading && (
101
+ <Text as="p" size={2} className="mr-auto text-gray-500">
102
+ Loading…
103
+ </Text>
104
+ )}
105
+
106
+ {error && (
107
+ <Text
108
+ as="p"
109
+ size={2}
110
+ className="bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3"
111
+ >
112
+ {error}
113
+ </Text>
114
+ )}
115
+ </Flex>
116
+ </ScrollArea.Viewport>
117
+ <ScrollArea.Scrollbar orientation="vertical" className="w-1 bg-gray-200 opacity-50">
118
+ <ScrollArea.Thumb className="flex-1 rounded-2xl bg-gray-400" />
119
+ </ScrollArea.Scrollbar>
120
+ <ScrollArea.Corner />
121
+ </ScrollArea.Root>
122
+ </Flex>
123
+
124
+ <div className="shrink-0 grow-0 border-t border-t-gray-400/40">
125
+ <Flex gap={2} align="end" className="w-full">
126
+ <div className="w-full [&_textarea]:border-none! [&_textarea]:outline-none!">
127
+ <TextArea
128
+ aria-label="message"
129
+ size="extralarge"
130
+ placeholder="Type a message…"
131
+ value={inputValue}
132
+ onKeyDown={handleKeyDown}
133
+ onChange={(text) => setInputValue(text)}
134
+ roundness="none"
135
+ autogrow
136
+ />
137
+ </div>
138
+ <div className="mr-[7px] mb-[7px]">
139
+ <Button
140
+ shape="square"
141
+ roundness="full"
142
+ variant="fill"
143
+ size="medium"
144
+ onPress={handleSubmit}
145
+ isDisabled={!inputValue.trim()}
146
+ >
147
+ <Send size={20} />
148
+ </Button>
149
+ </div>
150
+ </Flex>
151
+ </div>
152
+ </Flex>
153
+ </Theme>
154
+ );
155
+ };
156
+
157
+ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>
158
+ & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>
159
+ & {
160
+ // Foreground browser notifications for incoming agent/AI messages while the
161
+ // chat isn't focused. `false` disables; an object customizes title/icon/body.
162
+ // Default: enabled but silent until permission is granted (this always-visible
163
+ // surface never auto-prompts — call `Client.requestNotificationPermission()`
164
+ // from your own UI, or use `<InAppChatButton>` which prompts on first open).
165
+ notifications?: boolean | InAppChatNotificationOptions;
166
+ };
167
+
168
+ const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {
169
+ // Always-visible surface: treat as "open" and gate notifications on tab
170
+ // visibility/focus only. No launcher gesture exists here, so default to
171
+ // 'manual' permission (auto-requesting would prompt on mount).
172
+ const notifier = useInAppChatNotifications({
173
+ isOpen: true,
174
+ enabled: notifications !== false,
175
+ options: {
176
+ requestPermissionOn: 'manual',
177
+ ...(typeof notifications === 'object' ? notifications : undefined),
178
+ },
179
+ });
180
+ const chat = useInAppChat({
181
+ identityId,
182
+ idempotencyKey,
183
+ initialMessage,
184
+ onInboundMessage: notifier.handleInboundMessage,
185
+ });
186
+ return <InAppChat {...chat} {...props} />;
187
+ };
188
+
189
+ export type { InAppChatProps, InAppChatWrapperProps };
190
+
191
+ export { InAppChat };
192
+
193
+ export default InAppChatWrapper;