@sagepilot-ai/react-native-sdk 0.3.0 → 0.3.2

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.
package/README.md CHANGED
@@ -2,31 +2,25 @@
2
2
 
3
3
  Official React Native SDK for adding Sagepilot chat to iOS and Android apps.
4
4
 
5
- The SDK opens the Sagepilot-hosted chat experience inside a React Native WebView and provides APIs for setup, identity, unread count, and app-owned launchers.
5
+ The SDK opens the Sagepilot-hosted chat experience inside a React Native WebView and provides APIs for setup, identity, unread count, attachments, and app-owned launchers.
6
+
7
+ For full integration docs, see [React Native SDK docs](https://docs.sagepilot.ai/sdks/react-native/overview).
6
8
 
7
9
  ## Requirements
8
10
 
9
11
  - React 18+
10
12
  - React Native 0.72+
11
13
  - `react-native-webview` 13+
12
- - A Sagepilot workspace id and chat channel id
14
+ - A Sagepilot workspace ID and chat channel ID
13
15
  - Secure token storage for production apps
14
16
 
15
- ## Install And Configure
16
-
17
- ### 1. Install The Base Chat SDK
18
-
19
- Use this install when your app wants Sagepilot chat without Sagepilot's Android CameraX implementation:
17
+ ## Install
20
18
 
21
19
  ```bash
22
- npm install @sagepilot-ai/react-native-sdk react-native-webview
20
+ npm install @sagepilot-ai/react-native-sdk@latest react-native-webview
23
21
  ```
24
22
 
25
- This installs the base SDK only. It includes `SagepilotChat.configure`, hosted chat WebView, auth/session handling, the native bridge, attachment bridge protocol, `SagepilotFilePickerAdapter`, and custom picker support. It does not include CameraX or Android CameraX Gradle dependencies.
26
-
27
- ### 2. Add Secure Session Storage
28
-
29
- For production apps, install one secure storage library so Sagepilot customer sessions survive app restarts.
23
+ For secure persisted sessions, install one storage library:
30
24
 
31
25
  ```bash
32
26
  npm install react-native-keychain
@@ -38,383 +32,11 @@ Expo apps can use `expo-secure-store` instead:
38
32
  npx expo install expo-secure-store
39
33
  ```
40
34
 
41
- ### 3. Configure The SDK
42
-
43
- Configure Sagepilot once when your app starts. The minimum working setup is:
44
-
45
- ```ts
46
- import { SagepilotChat } from "@sagepilot-ai/react-native-sdk";
47
-
48
- await SagepilotChat.configure({
49
- key: "workspace_id:channel_id"
50
- });
51
- ```
52
-
53
- For production, pass secure token storage:
54
-
55
- ```ts
56
- import * as Keychain from "react-native-keychain";
57
- import {
58
- SagepilotChat,
59
- createKeychainTokenStorage
60
- } from "@sagepilot-ai/react-native-sdk";
61
-
62
- await SagepilotChat.configure({
63
- key: "workspace_id:channel_id",
64
- tokenStorage: createKeychainTokenStorage(Keychain)
65
- });
66
- ```
67
-
68
- Then mount `SagepilotChatProvider` once near the top of your app so the SDK can render the hosted chat WebView when you open it:
69
-
70
- ```tsx
71
- import { useEffect, type ReactNode } from "react";
72
- import * as Keychain from "react-native-keychain";
73
- import {
74
- SagepilotChat,
75
- SagepilotChatProvider,
76
- createKeychainTokenStorage
77
- } from "@sagepilot-ai/react-native-sdk";
78
-
79
- function SagepilotProvider({ children }: { children: ReactNode }) {
80
- useEffect(() => {
81
- void SagepilotChat.configure({
82
- key: "workspace_id:channel_id",
83
- tokenStorage: createKeychainTokenStorage(Keychain)
84
- });
85
-
86
- return () => {
87
- SagepilotChat.destroy();
88
- };
89
- }, []);
90
-
91
- return <SagepilotChatProvider>{children}</SagepilotChatProvider>;
92
- }
93
-
94
- export function App() {
95
- return (
96
- <SagepilotProvider>
97
- <RootNavigator />
98
- </SagepilotProvider>
99
- );
100
- }
101
- ```
102
-
103
- ### 4. Optional: Add Sagepilot Android CameraX
104
-
105
- Install this addon only when you want Sagepilot's Android in-app CameraX picker. Apps that skip this step keep the smaller base SDK install.
106
-
107
- ```bash
108
- npm install @sagepilot-ai/react-native-camera-addon
109
- ```
110
-
111
- After installing the addon, run a fresh native Android build. A Metro reload is not enough for React Native autolinking to register `NativeModules.SagepilotInAppCamera`.
112
-
113
- Then pass the addon picker into `SagepilotChat.configure`:
114
-
115
- ```ts
116
- import { SagepilotChat } from "@sagepilot-ai/react-native-sdk";
117
- import { createSagepilotCameraXFilePicker } from "@sagepilot-ai/react-native-camera-addon";
118
-
119
- await SagepilotChat.configure({
120
- key: "workspace_id:channel_id",
121
- filePicker: createSagepilotCameraXFilePicker()
122
- });
123
- ```
124
-
125
- With this setup, the base SDK still owns chat configuration, hosted WebView rendering, auth/session, and the bridge. The camera addon owns CameraX dependencies, native module registration, camera activity, overlay, and image processing.
126
-
127
- ## Configuration Values
128
-
129
- You configure the SDK with:
130
-
131
- - `key`: public routing config in the format `workspace_id:channel_id`
132
- - `tokenStorage`: secure storage adapter for SDK-created customer session tokens
133
- - optional request, presentation, and behavior settings
134
-
135
- For standard Sagepilot cloud usage, omit `host`. The SDK connects to Sagepilot's hosted endpoints automatically. Set `host` only when Sagepilot provides a dedicated endpoint for your workspace.
136
-
137
- ```ts
138
- await SagepilotChat.configure({
139
- key: "workspace_id:channel_id"
140
- });
141
- ```
142
-
143
- If Sagepilot provides a dedicated endpoint for your workspace, pass it as an optional override:
144
-
145
- ```ts
146
- await SagepilotChat.configure({
147
- key: "workspace_id:channel_id",
148
- host: "https://your-sagepilot-host.com"
149
- });
150
- ```
151
-
152
- The `key` is not a secret. It is safe to ship in a mobile app. Do not put server API keys, signing secrets, or private workspace secrets in a React Native app.
153
-
154
- ### Supported Configuration Options
155
-
156
- These options are part of the supported React Native SDK configuration contract.
157
-
158
- | Option | Purpose |
159
- |---|---|
160
- | `key` | Public routing key in the format `workspace_id:channel_id`. |
161
- | `host` | Optional Sagepilot host override. Most apps should omit this unless Sagepilot provides a dedicated endpoint. |
162
- | `widgetHost` | Optional hosted widget origin override. Use only when Sagepilot provides a separate widget endpoint. |
163
- | `headers` | Additional headers for SDK service requests. Do not pass server API keys or long-lived secrets from a mobile app. |
164
- | `fetch` | Custom fetch implementation for runtimes that need one. |
165
- | `tokenStorage` | Secure storage adapter for SDK-created customer session tokens. |
166
- | `anonymousId` | Optional stable anonymous identifier sent when the SDK creates a customer session. |
167
- | `metadata` | Optional app metadata merged into the session creation payload. |
168
- | `deviceInfo` | Optional adapter that returns device metadata to include during session creation. |
169
- | `presentation.style` | Modal presentation style: `"sheet"`, `"fullScreen"`, or `"push"`. |
170
- | `presentation.mobile` | Adds `mobile=1` to the hosted widget URL. Defaults to `true` for React Native. |
171
- | `presentation.showCloseButton` | Controls whether the provider renders a native close button around the WebView. Defaults to `false` so the hosted Sagepilot widget owns close behavior. |
172
- | `theme.accentColor` | Primary brand color used as the fallback launcher button color. |
173
- | `theme.logoUrl` | Optional brand logo URL exposed in SDK theme state. |
174
- | `theme.preferredColorScheme` | Optional hosted chat color scheme hint: `"light"`, `"dark"`, or `"system"`. |
175
- | `theme.launcher` | Optional chat launcher icon, label, and badge color configuration. |
176
- | `behavior.preloadWebView` | Preloads a hidden hosted chat WebView after configuration. |
177
- | `behavior.enableUnreadPolling` | Starts or disables automatic unread-count polling after configuration. |
178
- | `behavior.unreadPollIntervalMs` | Sets the unread polling interval in milliseconds. |
179
-
180
- `SagepilotChatProvider` renders the Sagepilot-hosted chat UI in a React Native WebView. Most apps do not need any host override.
181
-
182
- ### Chat Launcher Theme
183
-
184
- Use `theme.launcher` to configure the icon button and unread badge colors for your app-owned launcher. The SDK resolves omitted values to Sagepilot defaults, so customers only need to set the colors they want to control.
185
-
186
- ```ts
187
- const CHAT_LAUNCHER_CONFIG = {
188
- label: "Support",
189
- buttonColor: "#173c2d",
190
- pressedButtonColor: "#225340",
191
- disabledButtonColor: "#d8cdbb",
192
- borderColor: "#2a5e49",
193
- disabledBorderColor: "#cbbda9",
194
- iconColor: "#fff8ef",
195
- iconInsideColor: "#173c2d",
196
- labelColor: "#d4e9dc",
197
- disabledContentColor: "#8d8172",
198
- unreadBadgeColor: "#e76f51",
199
- unreadBadgeTextColor: "#ffffff",
200
- unreadBadgeBorderColor: "#efe4d4"
201
- };
202
-
203
- await SagepilotChat.configure({
204
- key: "workspace_id:channel_id",
205
- theme: {
206
- accentColor: CHAT_LAUNCHER_CONFIG.buttonColor,
207
- preferredColorScheme: "system",
208
- launcher: CHAT_LAUNCHER_CONFIG
209
- }
210
- });
211
- ```
212
-
213
- Use the resolved launcher theme from `useSagepilotChat()` when rendering your own button:
214
-
215
- ```tsx
216
- import { Pressable, Text, View } from "react-native";
217
- import { MessageCircle } from "lucide-react-native";
218
- import { useSagepilotChat } from "@sagepilot-ai/react-native-sdk";
219
-
220
- export function ChatLauncher() {
221
- const { configured, unreadCount, presentMessages, theme } = useSagepilotChat();
222
- const launcher = theme.launcher;
223
-
224
- return (
225
- <Pressable
226
- accessibilityRole="button"
227
- accessibilityLabel={launcher.label}
228
- disabled={!configured}
229
- onPress={presentMessages}
230
- style={({ pressed }) => ({
231
- alignItems: "center",
232
- backgroundColor: !configured
233
- ? launcher.disabledButtonColor
234
- : pressed
235
- ? launcher.pressedButtonColor
236
- : launcher.buttonColor,
237
- borderColor: !configured ? launcher.disabledBorderColor : launcher.borderColor,
238
- borderRadius: 28,
239
- borderWidth: 1,
240
- height: 56,
241
- justifyContent: "center",
242
- width: 56
243
- })}
244
- >
245
- <MessageCircle
246
- color={!configured ? launcher.disabledContentColor : launcher.iconColor}
247
- fill={!configured ? launcher.disabledContentColor : launcher.iconInsideColor}
248
- size={24}
249
- />
250
- {unreadCount > 0 ? (
251
- <View
252
- style={{
253
- alignItems: "center",
254
- backgroundColor: launcher.unreadBadgeColor,
255
- borderColor: launcher.unreadBadgeBorderColor,
256
- borderRadius: 9,
257
- borderWidth: 1,
258
- minWidth: 18,
259
- paddingHorizontal: 4,
260
- position: "absolute",
261
- right: -2,
262
- top: -2
263
- }}
264
- >
265
- <Text style={{ color: launcher.unreadBadgeTextColor, fontSize: 11 }}>
266
- {unreadCount}
267
- </Text>
268
- </View>
269
- ) : null}
270
- </Pressable>
271
- );
272
- }
273
- ```
274
-
275
- ## Native File Picker
276
-
277
- By default, the hosted chat widget's attach button uses the WebView's `<input type="file">`. On low-RAM Android devices this is unreliable: while the system camera is in the foreground, Android can kill the WebView render process, leaving a dead white screen and losing the captured photo.
278
-
279
- Configure `filePicker` so the attach button uses native pickers instead. Captured files are delivered to the widget over a hardened bridge (protocol v2): they are held in app memory **and** mirrored to `cacheStorage`, then **re-delivered until the widget acknowledges them** — surviving the WebView hydration race, renderer crashes, and (for small batches) full app-process death. Pending batches are pinned to the hosted chat route that requested them, so a recovered photo is re-delivered to the originating thread. On Android the SDK also runs a liveness watchdog on app-resume that repaints and, if the widget is confirmed dead, remounts the WebView.
280
-
281
- The base package does not include CameraX. Apps that want the smallest install can use only:
282
-
283
- ```bash
284
- npm install @sagepilot-ai/react-native-sdk react-native-webview
285
- ```
286
-
287
- ### Optional Android CameraX Addon
288
-
289
- Install the CameraX addon only when you want Sagepilot's Android in-app camera implementation:
290
-
291
- ```bash
292
- npm install @sagepilot-ai/react-native-camera-addon
293
- ```
294
-
295
- Run a clean native Android rebuild after installing the addon. If you only Metro-reload, the native module is not linked yet and `createSagepilotCameraXFilePicker()` returns `undefined`, so the hosted widget falls back to the WebView file input.
296
-
297
- Then configure the addon adapter:
298
-
299
- ```ts
300
- import { SagepilotChat } from "@sagepilot-ai/react-native-sdk";
301
- import { createSagepilotCameraXFilePicker } from "@sagepilot-ai/react-native-camera-addon";
302
-
303
- await SagepilotChat.configure({
304
- key: "workspace_id:channel_id",
305
- filePicker: createSagepilotCameraXFilePicker()
306
- });
307
- ```
308
-
309
- The addon owns the Android CameraX Gradle dependencies, `CAMERA` permission merge, native module, camera activity, overlay, and image processing. The base SDK continues to own the hosted chat WebView, auth/session, bridge, attachment protocol, and `SagepilotFilePickerAdapter` type.
310
-
311
- For the strongest resilience (a photo captured right before the OS kills the app survives the restart, at any size), pass BOTH `cacheStorage` (stores the tiny manifest) and `fileStore` (stores the bytes on disk). `cacheStorage` alone keeps only small (≤~2MB) batches durable, because Android's AsyncStorage caps a single row near 2MB; `fileStore` lifts that limit by writing bytes to an app-private file and persisting only file keys in the manifest:
312
-
313
- ```ts
314
- import AsyncStorage from "@react-native-async-storage/async-storage";
315
- import ReactNativeBlobUtil from "react-native-blob-util";
316
- import { createAsyncStorageCacheStorage, createSagepilotFileStore } from "@sagepilot-ai/react-native-sdk";
317
- import { createSagepilotCameraXFilePicker } from "@sagepilot-ai/react-native-camera-addon";
318
-
319
- await SagepilotChat.configure({
320
- key: "workspace_id:channel_id",
321
- cacheStorage: createAsyncStorageCacheStorage(AsyncStorage),
322
- fileStore: createSagepilotFileStore(ReactNativeBlobUtil),
323
- filePicker: createSagepilotCameraXFilePicker()
324
- });
325
- ```
326
-
327
- ### Host-Provided Pickers
328
-
329
- You can also provide your own picker modules to the base SDK. Modules are passed in rather than imported by the SDK, so Metro never resolves packages your app did not install.
330
-
331
- Install the optional dependencies your app needs:
332
-
333
- ```sh
334
- # Camera/gallery through react-native-image-picker
335
- npm install react-native-image-picker
336
-
337
- # Document/file picking (optional)
338
- npm install @react-native-documents/picker
339
-
340
- # Reliable document reads (optional, recommended with the documents picker)
341
- npm install react-native-blob-util
342
- ```
343
-
344
- Then pass the modules to `createSagepilotFilePicker`:
345
-
346
- ```ts
347
- import * as imagePicker from "react-native-image-picker";
348
- import * as documentsPicker from "@react-native-documents/picker";
349
- import ReactNativeBlobUtil from "react-native-blob-util";
350
- import {
351
- SagepilotChat,
352
- createSagepilotFilePicker
353
- } from "@sagepilot-ai/react-native-sdk";
354
-
355
- await SagepilotChat.configure({
356
- key: "workspace_id:channel_id",
357
- filePicker: createSagepilotFilePicker({
358
- imagePicker,
359
- documentsPicker,
360
- fileReader: ReactNativeBlobUtil
361
- })
362
- });
363
- ```
364
-
365
- Notes:
366
-
367
- - Android CameraX images are captured by `@sagepilot-ai/react-native-camera-addon` and downscaled natively (1920px longest edge, JPEG quality 0.8 by default; override with `imageMaxDimension` / `imageQuality`). This keeps memory and upload sizes low on constrained devices.
368
- - The CameraX addon can also expose Android Photo Picker and document sources from its native module. The base `createSagepilotFilePicker(...)` helper uses only the host-provided modules you pass into it.
369
- - Gallery multi-select is capped at 5 by default (`imageSelectionLimit`); documents are rejected above 20MB (`documentMaxFileSizeBytes`) and images above 15MB (`imageMaxFileSizeBytes`) **before** they are read into memory, preventing out-of-memory crashes on large files.
370
- - Failures are never silent: the picker distinguishes user-cancel from real errors and surfaces a typed `code` (`permission_denied`, `camera_unavailable`, `encode_failed`, `file_too_large`, `read_failed`) to the widget.
371
- - Android apps that install the CameraX addon must grant `CAMERA` at runtime; the addon requests it automatically before opening the camera and surfaces a clear message (with a Settings hint) when it is denied. iOS apps using `react-native-image-picker` need `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in `Info.plist`.
372
- - Apps that skip `filePicker` keep the WebView file input. The SDK still recovers from WebView renderer crashes by reloading the widget, but a photo captured at crash time cannot be restored in that mode.
373
-
374
- ## Secure Session Storage
375
-
376
- The SDK creates opaque customer session tokens at runtime. These tokens are not exposed through hooks or public session APIs.
377
-
378
- If `tokenStorage` is not provided, tokens are kept in memory only and the session will not persist after the app process restarts. Production apps should pass secure native storage.
379
-
380
- ### React Native Keychain
381
-
382
- `react-native-keychain` stores values in iOS Keychain and Android secure storage backed by Android Keystore.
383
-
384
- ```ts
385
- import * as Keychain from "react-native-keychain";
386
- import {
387
- SagepilotChat,
388
- createKeychainTokenStorage
389
- } from "@sagepilot-ai/react-native-sdk";
390
-
391
- await SagepilotChat.configure({
392
- key: "workspace_id:channel_id",
393
- tokenStorage: createKeychainTokenStorage(Keychain)
394
- });
395
- ```
396
-
397
- ### Expo SecureStore
398
-
399
- Expo SecureStore uses iOS Keychain and Android encrypted storage backed by Android Keystore.
400
-
401
- ```ts
402
- import * as SecureStore from "expo-secure-store";
403
- import { SagepilotChat } from "@sagepilot-ai/react-native-sdk";
404
-
405
- await SagepilotChat.configure({
406
- key: "workspace_id:channel_id",
407
- tokenStorage: {
408
- getItem: SecureStore.getItemAsync,
409
- setItem: SecureStore.setItemAsync,
410
- removeItem: SecureStore.deleteItemAsync
411
- }
412
- });
413
- ```
35
+ The SDK key is public routing config in the format `workspace_id:channel_id`. Do not ship server API keys, signing secrets, or private workspace secrets in a React Native app.
414
36
 
415
37
  ## Basic Setup
416
38
 
417
- Configure the SDK after your app knows the current workspace/channel and, if available, the current user.
39
+ Configure Sagepilot once when your app starts, then mount `SagepilotChatProvider` near the top of the app.
418
40
 
419
41
  ```tsx
420
42
  import * as Keychain from "react-native-keychain";
@@ -441,7 +63,8 @@ export function SagepilotProvider({ children }: { children: ReactNode }) {
441
63
  },
442
64
  behavior: {
443
65
  preloadWebView: true,
444
- enableUnreadPolling: true
66
+ enableUnreadPolling: true,
67
+ waitForIdentifyBeforeComposer: true
445
68
  }
446
69
  });
447
70
 
@@ -466,8 +89,6 @@ export function SagepilotProvider({ children }: { children: ReactNode }) {
466
89
  }
467
90
  ```
468
91
 
469
- Mount the provider once near the top of your app:
470
-
471
92
  ```tsx
472
93
  export function App() {
473
94
  return (
@@ -478,9 +99,11 @@ export function App() {
478
99
  }
479
100
  ```
480
101
 
102
+ More setup details: [Configuration](https://docs.sagepilot.ai/sdks/react-native/configuration).
103
+
481
104
  ## Opening Chat
482
105
 
483
- The SDK does not force a launcher UI. Use the hook to connect Sagepilot to your own button, tab, badge, or help screen.
106
+ Use the hook for app-owned launchers:
484
107
 
485
108
  ```tsx
486
109
  import { Pressable, Text } from "react-native";
@@ -499,145 +122,115 @@ export function SupportButton() {
499
122
  }
500
123
  ```
501
124
 
502
- Other open helpers:
125
+ You can also call the public methods directly:
503
126
 
504
127
  ```ts
128
+ import { SagepilotChat } from "@sagepilot-ai/react-native-sdk";
129
+
505
130
  SagepilotChat.present();
506
131
  SagepilotChat.presentMessages();
507
- SagepilotChat.presentMessageComposer("I need help with my order");
508
- SagepilotChat.presentMessageComposer("Start a new request", { mode: "new" });
509
- SagepilotChat.presentMessageComposer("I need help with this order", { chatId: savedChatId });
132
+ await SagepilotChat.presentMessageComposer("I need help with my order");
133
+ await SagepilotChat.presentMessageComposer("I need help with my order", { mode: "auto" });
134
+ await SagepilotChat.presentMessageComposer("Start a new request", { mode: "new" });
135
+ await SagepilotChat.presentMessageComposer("I need help with this order", { chatId: savedChatId });
510
136
  ```
511
137
 
512
- `presentMessageComposer(message)` pre-fills the composer and lets Sagepilot reuse an existing conversation when one is available. If there is no existing conversation, Sagepilot starts a new one when the customer sends the message.
513
-
514
- Use `{ mode: "new" }` only when the button or workflow should always start a fresh conversation.
515
-
516
- Pass `{ chatId }` when an app-owned surface should reopen a specific conversation, such as an order help button. The SDK sends this as the hosted widget `chat_id` and keeps the existing no-`chatId` behavior unchanged.
517
-
518
- To store the chat id when a customer creates a conversation from a screen-specific composer:
519
-
520
- ```ts
521
- SagepilotChat.presentMessageComposer("I need help with this order", {
522
- metadata: { orderId: "10212984" },
523
- onConversationCreated: ({ chat_id, metadata }) => {
524
- // Store metadata.orderId -> chat_id in your app.
525
- }
526
- });
527
- ```
138
+ `presentMessageComposer(message)` uses `{ mode: "auto" }` by default. It pre-fills the composer and lets Sagepilot reuse an existing conversation when one is available. Use `{ mode: "new" }` only when a workflow should always start a fresh conversation.
528
139
 
529
- You can also subscribe globally:
140
+ `presentMessageComposer()` returns `boolean` by default. If `behavior.waitForIdentifyBeforeComposer` is `true` and `identify()` is already in flight, it returns `Promise<boolean>` and waits up to 60 seconds for identity to finish before opening. You can `await` it in both cases.
530
141
 
531
- ```ts
532
- const unsubscribe = SagepilotChat.onConversationCreated(({ chat_id }) => {
533
- // Persist chat_id for later use.
534
- });
535
- ```
142
+ More examples: [Opening chat](https://docs.sagepilot.ai/sdks/react-native/opening-chat).
536
143
 
537
144
  ## Identity
538
145
 
539
- Call `identify()` when you know the signed-in app user.
146
+ Call `identify()` after `configure()` when you know the signed-in customer.
540
147
 
541
148
  ```ts
542
149
  await SagepilotChat.identify({
543
- userId: user.id,
544
- email: user.email,
545
- name: user.name,
546
- phone: user.phone,
547
- customProperties: {
548
- plan: "pro",
549
- storeId: "store_123"
550
- }
150
+ userId: "user_123",
151
+ email: "customer@example.com",
152
+ name: "Customer Name",
153
+ phone: "+15551234567"
551
154
  });
552
155
  ```
553
156
 
554
- If identity verification is enabled for your workspace, generate `userHash` on your server and pass only the generated hash to the app:
157
+ Use `waitForIdentifyBeforeComposer: true` for authenticated support flows where the composer should wait for an in-flight identity request before opening.
555
158
 
556
159
  ```ts
557
- await SagepilotChat.identify({
558
- userId: user.id,
559
- email: user.email,
560
- userHash: serverGeneratedUserHash
561
- });
160
+ const opened = await SagepilotChat.presentMessageComposer("I need help with my order");
562
161
  ```
563
162
 
564
- Never generate `userHash` in the mobile app with a signing secret.
565
-
566
- ## Logout
567
-
568
163
  When the app user signs out, clear Sagepilot identity/session state:
569
164
 
570
165
  ```ts
571
166
  await SagepilotChat.logout();
572
- await SagepilotChat.destroy();
167
+ SagepilotChat.destroy();
573
168
  ```
574
169
 
575
- `logout()` removes the known customer identity from the current SDK session. `destroy()` stops polling, clears in-memory state, and removes SDK listeners.
576
-
577
- ## Public API
578
-
579
- ### Setup
580
-
581
- - `SagepilotChat.configure(config)`: initializes the SDK, loads channel config, creates or resumes a customer session, and starts unread polling unless disabled.
582
- - `SagepilotChat.destroy()`: stops polling, clears in-memory SDK state, and removes listeners.
583
- - `SagepilotChat.getChannel()`: returns the loaded channel bootstrap data.
584
-
585
- ### Identity And Session
586
-
587
- - `SagepilotChat.identify(identity)`: links the active session to a known customer.
588
- - `SagepilotChat.logout()`: removes known-customer identity from the active session.
589
- - `SagepilotChat.getSession()`: fetches the current session and returns safe session metadata. It does not expose the session token.
590
- - `SagepilotChat.getSessionState()`: returns safe local session metadata. It does not expose the session token.
591
- - `SagepilotChat.getIdentityState()`: returns local identity state.
592
- - `SagepilotChat.onIdentify(callback)`: subscribes to successful identify events.
593
-
594
- ### Hosted Chat UI
170
+ More details: [Identity](https://docs.sagepilot.ai/sdks/react-native/identity).
595
171
 
596
- - `SagepilotChat.present()`: opens the hosted chat home screen.
597
- - `SagepilotChat.presentMessages()`: opens the hosted conversations/messages screen.
598
- - `SagepilotChat.presentMessageComposer(message?, options?)`: opens the message composer and optionally pre-fills the composer text. By default, Sagepilot reuses an existing conversation when one is available. Pass `{ mode: "new" }` to force a fresh conversation, or `{ chatId }` to open a specific conversation. It does not auto-send.
599
- - `SagepilotChat.dismiss()`: closes the hosted chat modal.
600
- - `SagepilotChat.hide()`: alias for `dismiss()`.
601
- - `SagepilotChat.toggle()`: opens the chat when closed and closes it when open.
602
- - `SagepilotChat.isPresented()`: returns whether the hosted chat modal is open.
603
- - `SagepilotChat.onConversationCreated(callback)`: subscribes to hosted conversations created from the React Native widget and returns `chat_id` plus any composer metadata.
604
- - `SagepilotChatProvider`: renders the hosted Sagepilot chat inside a React Native modal WebView.
172
+ ## Attachments
605
173
 
606
- When `SagepilotChatProvider` is mounted, the SDK preloads a hidden hosted WebView after `configure()` so the first visible open can reuse warmed network/cache state. Disable this with `behavior.preloadWebView: false`.
174
+ The base package supports custom native file-picker adapters. Apps that want Sagepilot's Android in-app CameraX picker can install the optional addon:
607
175
 
608
- ### Unread State
609
-
610
- - `SagepilotChat.getUnreadCount()`: fetches and returns the current unread count.
611
- - `SagepilotChat.onUnreadChange(callback)`: subscribes to unread count changes.
612
- - `SagepilotChat.startUnreadPolling(intervalMs?)`: starts unread polling.
613
- - `SagepilotChat.stopUnreadPolling()`: stops unread polling.
614
-
615
- ### Lifecycle Events
176
+ ```bash
177
+ npm install @sagepilot-ai/react-native-camera-addon@latest
178
+ ```
616
179
 
617
- - `SagepilotChat.onReady(callback)`: fires when SDK configuration completes.
618
- - `SagepilotChat.onPresent(callback)`: fires when chat opens.
619
- - `SagepilotChat.onDismiss(callback)`: fires when chat closes.
620
- - `SagepilotChat.onError(callback)`: subscribes to SDK errors.
621
- - `SagepilotChat.onStateChange(callback)`: subscribes to local SDK state changes.
180
+ The base chat SDK does not bundle CameraX. The optional addon adds these Android dependencies through its own Gradle file:
622
181
 
623
- ### React Hook
182
+ - `androidx.camera:camera-core`
183
+ - `androidx.camera:camera-camera2`
184
+ - `androidx.camera:camera-lifecycle`
185
+ - `androidx.camera:camera-view`
186
+ - `androidx.exifinterface:exifinterface`
187
+ - `androidx.activity:activity`
624
188
 
625
- - `useSagepilotChat()`: returns presentation helpers, unread count, identity state, and common actions for app-owned launchers and badges.
189
+ By default, the addon uses CameraX `1.5.3`, ExifInterface `1.4.2`, and AndroidX Activity `1.10.1`. Apps can override them from the root Gradle project with `sagepilotCameraXVersion`, `sagepilotExifInterfaceVersion`, and `sagepilotActivityVersion`.
626
190
 
627
- ### Storage Helpers
191
+ ```ts
192
+ import { SagepilotChat } from "@sagepilot-ai/react-native-sdk";
193
+ import { createSagepilotCameraXFilePicker } from "@sagepilot-ai/react-native-camera-addon";
628
194
 
629
- - `createKeychainTokenStorage(keychain, options?)`: adapts `react-native-keychain` for secure session token storage.
195
+ await SagepilotChat.configure({
196
+ key: "workspace_id:channel_id",
197
+ filePicker: createSagepilotCameraXFilePicker()
198
+ });
199
+ ```
630
200
 
631
- Do not use AsyncStorage for session tokens.
201
+ Run a fresh native Android build after installing the addon so React Native autolinking can register the native module.
632
202
 
633
- ## Runtime Notes
203
+ More details: [Native file picker](https://docs.sagepilot.ai/sdks/react-native/native-file-picker).
634
204
 
635
- The React Native UI uses `react-native-webview` to show the Sagepilot-owned hosted conversation. The SDK injects mobile WebView polish for viewport scaling, text selection, tap highlighting, native bridge message forwarding, and secure hosted-auth handoff.
205
+ ## Method Return Behavior
636
206
 
637
- Customers should depend on the public SDK methods and components, not WebView internals or hosted route implementation details.
207
+ | Method | Return behavior |
208
+ |---|---|
209
+ | `SagepilotChat.configure(config)` | `Promise<SagepilotMobileConfigureResult>` |
210
+ | `SagepilotChat.identify(identity)` | `Promise<SagepilotIdentifyResult>` |
211
+ | `SagepilotChat.logout()` | `Promise<SagepilotLogoutResponse>` |
212
+ | `SagepilotChat.getSession()` | `Promise<SagepilotSessionState>` |
213
+ | `SagepilotChat.getUnreadCount()` | `Promise<number>` |
214
+ | `SagepilotChat.presentMessageComposer(message?, options?)` | `boolean` or `Promise<boolean>` when `waitForIdentifyBeforeComposer` is enabled and identity is pending |
215
+ | `SagepilotChat.present()` | `boolean` |
216
+ | `SagepilotChat.presentMessages()` | `boolean` |
217
+ | `SagepilotChat.dismiss()` / `hide()` / `toggle()` | `boolean` |
218
+ | `SagepilotChat.isPresented()` | `boolean` |
219
+ | `SagepilotChat.getIdentityState()` / `getSessionState()` / `getChannel()` | synchronous state |
220
+ | `SagepilotChat.onIdentify(...)` / `onConversationCreated(...)` / lifecycle subscriptions | unsubscribe function |
221
+ | `SagepilotChat.destroy()` | `void` |
222
+
223
+ Full API reference: [SDK API reference](https://docs.sagepilot.ai/sdks/react-native/api-reference).
224
+
225
+ ## Useful Links
226
+
227
+ - [React Native SDK overview](https://docs.sagepilot.ai/sdks/react-native/overview)
228
+ - [Installation](https://docs.sagepilot.ai/sdks/react-native/installation)
229
+ - [Configuration](https://docs.sagepilot.ai/sdks/react-native/configuration)
230
+ - [Opening chat](https://docs.sagepilot.ai/sdks/react-native/opening-chat)
231
+ - [Native file picker](https://docs.sagepilot.ai/sdks/react-native/native-file-picker)
232
+ - [SDK API reference](https://docs.sagepilot.ai/sdks/react-native/api-reference)
638
233
 
639
234
  ## License
640
235
 
641
- MIT. See [LICENSE.md](./LICENSE.md).
642
-
643
- The MIT License applies only to this SDK code. It does not grant access to Sagepilot AI services, workspaces, API credentials, hosted infrastructure, models, data, or paid features. Use of Sagepilot AI hosted services, APIs, Workspace IDs, and runtime-generated license keys is governed separately by Sagepilot AI's Terms of Service or the applicable customer agreement.
236
+ MIT
package/dist/index.d.mts CHANGED
@@ -246,6 +246,7 @@ type SagepilotMobileBehaviorConfig = {
246
246
  enableUnreadPolling?: boolean;
247
247
  preloadWebView?: boolean;
248
248
  unreadPollIntervalMs?: number;
249
+ waitForIdentifyBeforeComposer?: boolean;
249
250
  };
250
251
  type SagepilotTokenStorage = {
251
252
  getItem: (key: string) => Promise<string | null>;
@@ -471,7 +472,7 @@ type SagepilotChatHookState = {
471
472
  theme: SagepilotMobileThemeState;
472
473
  present: () => boolean;
473
474
  presentMessages: () => boolean;
474
- presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean;
475
+ presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean | Promise<boolean>;
475
476
  dismiss: () => boolean;
476
477
  hide: () => boolean;
477
478
  toggle: () => boolean;
@@ -505,7 +506,7 @@ declare const SagepilotChat: {
505
506
  stopUnreadPolling: () => void;
506
507
  present: () => boolean;
507
508
  presentMessages: () => boolean;
508
- presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean;
509
+ presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean | Promise<boolean>;
509
510
  dismiss: () => boolean;
510
511
  hide: () => boolean;
511
512
  toggle: () => boolean;
package/dist/index.d.ts CHANGED
@@ -246,6 +246,7 @@ type SagepilotMobileBehaviorConfig = {
246
246
  enableUnreadPolling?: boolean;
247
247
  preloadWebView?: boolean;
248
248
  unreadPollIntervalMs?: number;
249
+ waitForIdentifyBeforeComposer?: boolean;
249
250
  };
250
251
  type SagepilotTokenStorage = {
251
252
  getItem: (key: string) => Promise<string | null>;
@@ -471,7 +472,7 @@ type SagepilotChatHookState = {
471
472
  theme: SagepilotMobileThemeState;
472
473
  present: () => boolean;
473
474
  presentMessages: () => boolean;
474
- presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean;
475
+ presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean | Promise<boolean>;
475
476
  dismiss: () => boolean;
476
477
  hide: () => boolean;
477
478
  toggle: () => boolean;
@@ -505,7 +506,7 @@ declare const SagepilotChat: {
505
506
  stopUnreadPolling: () => void;
506
507
  present: () => boolean;
507
508
  presentMessages: () => boolean;
508
- presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean;
509
+ presentMessageComposer: (message?: string, options?: SagepilotMessageComposerOptions) => boolean | Promise<boolean>;
509
510
  dismiss: () => boolean;
510
511
  hide: () => boolean;
511
512
  toggle: () => boolean;
package/dist/index.js CHANGED
@@ -67,7 +67,7 @@ var SagepilotChatError = class extends Error {
67
67
 
68
68
  // src/core/config/constants.ts
69
69
  var SDK_NAME = "@sagepilot-ai/react-native-sdk";
70
- var SDK_VERSION = "0.3.0";
70
+ var SDK_VERSION = "0.3.2";
71
71
  var DEFAULT_HOST = "https://app.sagepilot.ai";
72
72
  var DEFAULT_WIDGET_HOST = "https://app.sagepilot.ai";
73
73
  var CUSTOMER_API_PREFIX = "/customer-api/v1";
@@ -490,6 +490,7 @@ function fetchUnreadCount(http, host, channelId, sessionId, authorizationHeader)
490
490
  var PRESENTATION_CACHE_NAMESPACE = "sagepilot_rn_presentation";
491
491
  var PRESENTATION_CACHE_KEY = "state";
492
492
  var PRESENTATION_RESTORE_MAX_AGE_MS = 15 * 60 * 1e3;
493
+ var IDENTIFY_PENDING_COMPOSER_TIMEOUT_MS = 60 * 1e3;
493
494
  var DEFAULT_MOBILE_LAUNCHER_CONFIG = {
494
495
  label: "Chat",
495
496
  buttonColor: "#173c2d",
@@ -808,7 +809,16 @@ var SagepilotReactNativeChat = class {
808
809
  return this.showHostedChat();
809
810
  }
810
811
  presentMessageComposer(message, options) {
811
- this.requireConfigured();
812
+ const session = this.requireSession();
813
+ const shouldWaitForIdentify = this.runtimeOptions?.behavior?.waitForIdentifyBeforeComposer === true;
814
+ if (!shouldWaitForIdentify || !this.identifyPending) return this.openMessageComposer(message, options);
815
+ return this.waitForIdentifyOrTimeout().then(() => {
816
+ if (!this.session || this.session.session_id !== session.session_id) return false;
817
+ return this.openMessageComposer(message, options);
818
+ });
819
+ }
820
+ /** Opens the hosted composer with the latest session identity state. */
821
+ openMessageComposer(message, options) {
812
822
  const chatId = normalizeOptionalString(options?.chatId);
813
823
  this.hostedChatView = {
814
824
  screen: "composer",
@@ -820,6 +830,24 @@ var SagepilotReactNativeChat = class {
820
830
  };
821
831
  return this.showHostedChat();
822
832
  }
833
+ /** Waits for a successful identify response before falling back to the timeout. */
834
+ waitForIdentifyOrTimeout(timeoutMs = IDENTIFY_PENDING_COMPOSER_TIMEOUT_MS) {
835
+ if (!this.identifyPending) return Promise.resolve();
836
+ return new Promise((resolve) => {
837
+ let completed = false;
838
+ let timeout = null;
839
+ const finish = () => {
840
+ if (completed) return;
841
+ completed = true;
842
+ if (timeout) clearTimeout(timeout);
843
+ this.identifyCallbacks.delete(handleIdentify);
844
+ resolve();
845
+ };
846
+ const handleIdentify = () => finish();
847
+ timeout = setTimeout(finish, timeoutMs);
848
+ this.identifyCallbacks.add(handleIdentify);
849
+ });
850
+ }
823
851
  dismiss() {
824
852
  this.requireConfigured();
825
853
  if (!this.presented) return true;
@@ -1416,7 +1444,6 @@ var SAGEPILOT_DEFAULT_IMAGE_QUALITY = 0.8;
1416
1444
  var SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES = 15 * 1024 * 1024;
1417
1445
 
1418
1446
  // src/core/native/filePicker.ts
1419
- var DEBUG_PREFIX = "[SagepilotSDK][FilePicker]";
1420
1447
  var DEFAULT_IMAGE_MAX_DIMENSION = SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION;
1421
1448
  var DEFAULT_IMAGE_QUALITY = SAGEPILOT_DEFAULT_IMAGE_QUALITY;
1422
1449
  var DEFAULT_IMAGE_MIME_TYPE = "image/jpeg";
@@ -1433,9 +1460,6 @@ function estimateBase64ByteSize(dataBase64) {
1433
1460
  function stripFileScheme(uri) {
1434
1461
  return uri.startsWith("file://") ? uri.replace("file://", "") : uri;
1435
1462
  }
1436
- function debugFilePicker(message, details) {
1437
- console.log(`${DEBUG_PREFIX} ${message}`, details ?? "");
1438
- }
1439
1463
  async function promptOpenSagepilotCameraSettings() {
1440
1464
  if (import_react_native2.Platform.OS !== "android") return;
1441
1465
  await new Promise((resolve) => {
@@ -1462,13 +1486,10 @@ async function ensureSagepilotAndroidCameraPermission() {
1462
1486
  if (import_react_native2.Platform.OS !== "android") return;
1463
1487
  let result;
1464
1488
  try {
1465
- debugFilePicker("requesting Android camera permission");
1466
1489
  result = await import_react_native2.PermissionsAndroid.request(import_react_native2.PermissionsAndroid.PERMISSIONS.CAMERA);
1467
1490
  } catch {
1468
- debugFilePicker("camera permission request threw; continuing to native launch");
1469
1491
  return;
1470
1492
  }
1471
- debugFilePicker("Android camera permission result", { result });
1472
1493
  if (result === import_react_native2.PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
1473
1494
  await promptOpenSagepilotCameraSettings();
1474
1495
  throw new SagepilotFilePickerError(
@@ -1565,13 +1586,6 @@ function createSagepilotFilePicker(options) {
1565
1586
  if (canUseCameraSource(imagePicker)) sources.push("camera");
1566
1587
  if (imagePicker) sources.push("library");
1567
1588
  if (documentsPicker) sources.push("documents");
1568
- debugFilePicker("adapter created", {
1569
- platform: import_react_native2.Platform.OS,
1570
- hasImagePicker: Boolean(imagePicker),
1571
- hasDocumentsPicker: Boolean(documentsPicker),
1572
- hasFileReader: Boolean(fileReader),
1573
- sources
1574
- });
1575
1589
  if (sources.length === 0) return void 0;
1576
1590
  const imageOptions = {
1577
1591
  mediaType: "photo",
@@ -1582,22 +1596,14 @@ function createSagepilotFilePicker(options) {
1582
1596
  saveToPhotos: false
1583
1597
  };
1584
1598
  async function pickFromCamera() {
1585
- debugFilePicker("camera pick requested", {
1586
- platform: import_react_native2.Platform.OS,
1587
- imageMaxDimension,
1588
- imageQuality,
1589
- imageMaxFileSizeBytes
1590
- });
1591
1599
  await ensureSagepilotAndroidCameraPermission();
1592
1600
  if (!imagePicker) {
1593
1601
  throw new SagepilotFilePickerError("camera_unavailable", "The camera picker is not available in this build.");
1594
1602
  }
1595
- debugFilePicker("launching image-picker camera", { platform: import_react_native2.Platform.OS });
1596
1603
  return imageAssetsToPickedFiles(await imagePicker.launchCamera(imageOptions), imageMaxFileSizeBytes);
1597
1604
  }
1598
1605
  async function pickFromLibrary(multiple) {
1599
1606
  if (!imagePicker) return [];
1600
- debugFilePicker("library pick requested", { multiple, imageSelectionLimit });
1601
1607
  return imageAssetsToPickedFiles(await imagePicker.launchImageLibrary({
1602
1608
  ...imageOptions,
1603
1609
  // Bounded multi-select: 0 (unlimited) lets a huge batch OOM the bridge.
@@ -1606,7 +1612,6 @@ function createSagepilotFilePicker(options) {
1606
1612
  }
1607
1613
  async function pickDocuments(multiple) {
1608
1614
  if (!documentsPicker) return [];
1609
- debugFilePicker("document pick requested", { multiple, documentMaxFileSizeBytes });
1610
1615
  let picked;
1611
1616
  try {
1612
1617
  picked = await documentsPicker.pick({ allowMultiSelection: multiple });
@@ -1656,7 +1661,6 @@ function createSagepilotFilePicker(options) {
1656
1661
  return {
1657
1662
  sources,
1658
1663
  async pickFiles(request) {
1659
- debugFilePicker("pickFiles request", request);
1660
1664
  if (request.source === "camera") return pickFromCamera();
1661
1665
  if (request.source === "library") return pickFromLibrary(request.multiple);
1662
1666
  return pickDocuments(request.multiple);
@@ -1877,7 +1881,6 @@ var FILE_PICKER_SOURCE_ICON_COLORS = {
1877
1881
  library: "#16a34a",
1878
1882
  documents: "#7c3aed"
1879
1883
  };
1880
- var DEBUG_PREFIX2 = "[SagepilotSDK][Provider]";
1881
1884
  var DELIVERY_RETRY_MS = 1500;
1882
1885
  var DELIVERY_LEGACY_FALLBACK_ATTEMPTS = 2;
1883
1886
  var DELIVERY_MAX_ATTEMPTS = 8;
@@ -1961,16 +1964,6 @@ function readFilePickerError(error) {
1961
1964
  }
1962
1965
  return { message: "Could not attach the selected file." };
1963
1966
  }
1964
- function debugProvider(message, details) {
1965
- console.log(`${DEBUG_PREFIX2} ${message}`, details ?? "");
1966
- }
1967
- function describeAttachmentTarget(target) {
1968
- return {
1969
- targetChatId: target?.chatId,
1970
- targetRouteChatId: target?.routeChatId,
1971
- targetScreen: target?.hostedChatView.screen
1972
- };
1973
- }
1974
1967
  function getHostedIdentityDispatchScript() {
1975
1968
  const message = internalSagepilotChat.getHostedIdentityMessage();
1976
1969
  if (!message) return "";
@@ -2120,10 +2113,6 @@ function SagepilotChatProvider({
2120
2113
  const batch = pendingBatchesRef.current[0];
2121
2114
  if (!batch) return;
2122
2115
  if (internalSagepilotChat.restoreHostedAttachmentTarget(batch.target)) {
2123
- debugProvider("restored hosted attachment target", {
2124
- batchId: batch.batchId,
2125
- ...describeAttachmentTarget(batch.target)
2126
- });
2127
2116
  widgetReadyRef.current = false;
2128
2117
  deliveryTimerRef.current = setTimeout(() => pumpDelivery(), DELIVERY_RETRY_MS);
2129
2118
  return;
@@ -2133,13 +2122,6 @@ function SagepilotChatProvider({
2133
2122
  const ref = nativeWebViewRef.current;
2134
2123
  const shouldDeliver = ref && (widgetReadyRef.current || attempts >= DELIVERY_LEGACY_FALLBACK_ATTEMPTS);
2135
2124
  if (shouldDeliver && ref) {
2136
- debugProvider("delivering native picked files", {
2137
- batchId: batch.batchId,
2138
- attempt: attempts,
2139
- widgetReady: widgetReadyRef.current,
2140
- count: batch.files.length,
2141
- ...describeAttachmentTarget(batch.target)
2142
- });
2143
2125
  ref.injectJavaScript(buildFilesPickedScript(batch));
2144
2126
  }
2145
2127
  if (attempts < DELIVERY_MAX_ATTEMPTS) {
@@ -2177,21 +2159,12 @@ function SagepilotChatProvider({
2177
2159
  storageKeys,
2178
2160
  target: internalSagepilotChat.getHostedAttachmentTarget()
2179
2161
  };
2180
- debugProvider("queued native picked files", {
2181
- batchId,
2182
- count: files.length,
2183
- totalBase64Bytes: totalBase64Bytes(files),
2184
- persistedToFileStore: hasFileStore,
2185
- ...describeAttachmentTarget(batch.target)
2186
- });
2187
2162
  pendingBatchesRef.current = [...pendingBatchesRef.current, batch];
2188
2163
  ensureDelivery();
2189
2164
  writeManifest();
2190
2165
  void writeBatchBytes(batch);
2191
2166
  }, [ensureDelivery, writeManifest, writeBatchBytes]);
2192
- const recoverNativeWebView = (0, import_react.useCallback)((reasonOrEvent) => {
2193
- const reason = typeof reasonOrEvent === "string" ? reasonOrEvent : "webview_render_process";
2194
- debugProvider("recovering native WebView", { reason });
2167
+ const recoverNativeWebView = (0, import_react.useCallback)((_reasonOrEvent) => {
2195
2168
  widgetReadyRef.current = false;
2196
2169
  setNativeWebViewKey((key) => key + 1);
2197
2170
  }, []);
@@ -2205,31 +2178,14 @@ function SagepilotChatProvider({
2205
2178
  const runNativeFilePicker = (0, import_react.useCallback)((source, multiple) => {
2206
2179
  const filePicker = internalSagepilotChat.getConfig()?.filePicker;
2207
2180
  if (!filePicker) {
2208
- debugProvider("native file picker requested but no adapter is configured", { source, multiple });
2209
2181
  return;
2210
2182
  }
2211
2183
  if (pickerInFlightRef.current) {
2212
- debugProvider("native file picker ignored because another picker is in flight", { source, multiple });
2213
2184
  return;
2214
2185
  }
2215
- debugProvider("native file picker starting", {
2216
- source,
2217
- multiple,
2218
- configuredSources: filePicker.sources
2219
- });
2220
2186
  pauseLivenessAfterPicker(6e4);
2221
2187
  pickerInFlightRef.current = true;
2222
2188
  filePicker.pickFiles({ source, multiple }).then((files) => {
2223
- debugProvider("native file picker resolved", {
2224
- source,
2225
- count: files.length,
2226
- files: files.map((file) => ({
2227
- fileName: file.file_name,
2228
- mimeType: file.mime_type,
2229
- size: file.size,
2230
- base64Length: file.data_base64.length
2231
- }))
2232
- });
2233
2189
  if (files.length === 0) {
2234
2190
  nativeWebViewRef.current?.injectJavaScript(buildFilePickerCancelledScript());
2235
2191
  return;
@@ -2237,7 +2193,6 @@ function SagepilotChatProvider({
2237
2193
  queuePickedFiles(files);
2238
2194
  }).catch((error) => {
2239
2195
  const { message, code } = readFilePickerError(error);
2240
- debugProvider("native file picker failed", { source, code, message });
2241
2196
  nativeWebViewRef.current?.injectJavaScript(buildFilePickerErrorScript(message, code));
2242
2197
  }).finally(() => {
2243
2198
  pickerInFlightRef.current = false;
@@ -2247,14 +2202,8 @@ function SagepilotChatProvider({
2247
2202
  const openNativeFilePicker = (0, import_react.useCallback)((multiple) => {
2248
2203
  const filePicker = internalSagepilotChat.getConfig()?.filePicker;
2249
2204
  if (!filePicker || filePicker.sources.length === 0) {
2250
- debugProvider("open native file picker ignored", {
2251
- multiple,
2252
- hasAdapter: Boolean(filePicker),
2253
- sources: filePicker?.sources ?? []
2254
- });
2255
2205
  return;
2256
2206
  }
2257
- debugProvider("open native file picker", { multiple, sources: filePicker.sources });
2258
2207
  const [onlySource] = filePicker.sources;
2259
2208
  if (filePicker.sources.length === 1 && onlySource && onlySource !== "camera") {
2260
2209
  runNativeFilePicker(onlySource, multiple);
@@ -2364,10 +2313,6 @@ function SagepilotChatProvider({
2364
2313
  const pauseRemainingMs = livenessPausedUntilRef.current - Date.now();
2365
2314
  if (pickerInFlightRef.current || pauseRemainingMs > 0) {
2366
2315
  const retryDelayMs = pickerInFlightRef.current ? 500 : Math.max(0, pauseRemainingMs);
2367
- debugProvider("liveness probe deferred after picker", {
2368
- pickerInFlight: pickerInFlightRef.current,
2369
- retryDelayMs
2370
- });
2371
2316
  clearDeferredLivenessProbe();
2372
2317
  livenessResumeTimerRef.current = setTimeout(() => {
2373
2318
  livenessResumeTimerRef.current = null;
@@ -2452,11 +2397,6 @@ function SagepilotChatProvider({
2452
2397
  const ackBatchId = message.batch_id;
2453
2398
  const head = pendingBatchesRef.current[0];
2454
2399
  if (head && (!ackBatchId || ackBatchId === head.batchId)) {
2455
- debugProvider("native picked files acknowledged", {
2456
- batchId: head.batchId,
2457
- ackBatchId,
2458
- count: message.count
2459
- });
2460
2400
  acknowledgeHeadBatch();
2461
2401
  }
2462
2402
  return;
@@ -2466,10 +2406,6 @@ function SagepilotChatProvider({
2466
2406
  if (pending && (!message.nonce || message.nonce === pending.nonce)) {
2467
2407
  if (message.alive === false) {
2468
2408
  clearPing();
2469
- debugProvider("liveness probe reported dead widget", {
2470
- supportsHeartbeat: message.supportsHeartbeat,
2471
- remountCount: livenessRemountCountRef.current
2472
- });
2473
2409
  if (livenessRemountCountRef.current < LIVENESS_MAX_REMOUNTS) {
2474
2410
  livenessRemountCountRef.current += 1;
2475
2411
  recoverNativeWebView("liveness_dead_pong");
@@ -2499,7 +2435,6 @@ function SagepilotChatProvider({
2499
2435
  nativeWebViewRef.current.injectJavaScript(getInjectedWebViewScript());
2500
2436
  };
2501
2437
  const handleNativeWebViewLoadEnd = () => {
2502
- debugProvider("native WebView load end");
2503
2438
  injectNativeBridgeToNativeWebView();
2504
2439
  postIdentityToNativeWebView();
2505
2440
  widgetReadyRef.current = false;
package/dist/index.mjs CHANGED
@@ -18,7 +18,7 @@ var SagepilotChatError = class extends Error {
18
18
 
19
19
  // src/core/config/constants.ts
20
20
  var SDK_NAME = "@sagepilot-ai/react-native-sdk";
21
- var SDK_VERSION = "0.3.0";
21
+ var SDK_VERSION = "0.3.2";
22
22
  var DEFAULT_HOST = "https://app.sagepilot.ai";
23
23
  var DEFAULT_WIDGET_HOST = "https://app.sagepilot.ai";
24
24
  var CUSTOMER_API_PREFIX = "/customer-api/v1";
@@ -441,6 +441,7 @@ function fetchUnreadCount(http, host, channelId, sessionId, authorizationHeader)
441
441
  var PRESENTATION_CACHE_NAMESPACE = "sagepilot_rn_presentation";
442
442
  var PRESENTATION_CACHE_KEY = "state";
443
443
  var PRESENTATION_RESTORE_MAX_AGE_MS = 15 * 60 * 1e3;
444
+ var IDENTIFY_PENDING_COMPOSER_TIMEOUT_MS = 60 * 1e3;
444
445
  var DEFAULT_MOBILE_LAUNCHER_CONFIG = {
445
446
  label: "Chat",
446
447
  buttonColor: "#173c2d",
@@ -759,7 +760,16 @@ var SagepilotReactNativeChat = class {
759
760
  return this.showHostedChat();
760
761
  }
761
762
  presentMessageComposer(message, options) {
762
- this.requireConfigured();
763
+ const session = this.requireSession();
764
+ const shouldWaitForIdentify = this.runtimeOptions?.behavior?.waitForIdentifyBeforeComposer === true;
765
+ if (!shouldWaitForIdentify || !this.identifyPending) return this.openMessageComposer(message, options);
766
+ return this.waitForIdentifyOrTimeout().then(() => {
767
+ if (!this.session || this.session.session_id !== session.session_id) return false;
768
+ return this.openMessageComposer(message, options);
769
+ });
770
+ }
771
+ /** Opens the hosted composer with the latest session identity state. */
772
+ openMessageComposer(message, options) {
763
773
  const chatId = normalizeOptionalString(options?.chatId);
764
774
  this.hostedChatView = {
765
775
  screen: "composer",
@@ -771,6 +781,24 @@ var SagepilotReactNativeChat = class {
771
781
  };
772
782
  return this.showHostedChat();
773
783
  }
784
+ /** Waits for a successful identify response before falling back to the timeout. */
785
+ waitForIdentifyOrTimeout(timeoutMs = IDENTIFY_PENDING_COMPOSER_TIMEOUT_MS) {
786
+ if (!this.identifyPending) return Promise.resolve();
787
+ return new Promise((resolve) => {
788
+ let completed = false;
789
+ let timeout = null;
790
+ const finish = () => {
791
+ if (completed) return;
792
+ completed = true;
793
+ if (timeout) clearTimeout(timeout);
794
+ this.identifyCallbacks.delete(handleIdentify);
795
+ resolve();
796
+ };
797
+ const handleIdentify = () => finish();
798
+ timeout = setTimeout(finish, timeoutMs);
799
+ this.identifyCallbacks.add(handleIdentify);
800
+ });
801
+ }
774
802
  dismiss() {
775
803
  this.requireConfigured();
776
804
  if (!this.presented) return true;
@@ -1367,7 +1395,6 @@ var SAGEPILOT_DEFAULT_IMAGE_QUALITY = 0.8;
1367
1395
  var SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES = 15 * 1024 * 1024;
1368
1396
 
1369
1397
  // src/core/native/filePicker.ts
1370
- var DEBUG_PREFIX = "[SagepilotSDK][FilePicker]";
1371
1398
  var DEFAULT_IMAGE_MAX_DIMENSION = SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION;
1372
1399
  var DEFAULT_IMAGE_QUALITY = SAGEPILOT_DEFAULT_IMAGE_QUALITY;
1373
1400
  var DEFAULT_IMAGE_MIME_TYPE = "image/jpeg";
@@ -1384,9 +1411,6 @@ function estimateBase64ByteSize(dataBase64) {
1384
1411
  function stripFileScheme(uri) {
1385
1412
  return uri.startsWith("file://") ? uri.replace("file://", "") : uri;
1386
1413
  }
1387
- function debugFilePicker(message, details) {
1388
- console.log(`${DEBUG_PREFIX} ${message}`, details ?? "");
1389
- }
1390
1414
  async function promptOpenSagepilotCameraSettings() {
1391
1415
  if (Platform2.OS !== "android") return;
1392
1416
  await new Promise((resolve) => {
@@ -1413,13 +1437,10 @@ async function ensureSagepilotAndroidCameraPermission() {
1413
1437
  if (Platform2.OS !== "android") return;
1414
1438
  let result;
1415
1439
  try {
1416
- debugFilePicker("requesting Android camera permission");
1417
1440
  result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA);
1418
1441
  } catch {
1419
- debugFilePicker("camera permission request threw; continuing to native launch");
1420
1442
  return;
1421
1443
  }
1422
- debugFilePicker("Android camera permission result", { result });
1423
1444
  if (result === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
1424
1445
  await promptOpenSagepilotCameraSettings();
1425
1446
  throw new SagepilotFilePickerError(
@@ -1516,13 +1537,6 @@ function createSagepilotFilePicker(options) {
1516
1537
  if (canUseCameraSource(imagePicker)) sources.push("camera");
1517
1538
  if (imagePicker) sources.push("library");
1518
1539
  if (documentsPicker) sources.push("documents");
1519
- debugFilePicker("adapter created", {
1520
- platform: Platform2.OS,
1521
- hasImagePicker: Boolean(imagePicker),
1522
- hasDocumentsPicker: Boolean(documentsPicker),
1523
- hasFileReader: Boolean(fileReader),
1524
- sources
1525
- });
1526
1540
  if (sources.length === 0) return void 0;
1527
1541
  const imageOptions = {
1528
1542
  mediaType: "photo",
@@ -1533,22 +1547,14 @@ function createSagepilotFilePicker(options) {
1533
1547
  saveToPhotos: false
1534
1548
  };
1535
1549
  async function pickFromCamera() {
1536
- debugFilePicker("camera pick requested", {
1537
- platform: Platform2.OS,
1538
- imageMaxDimension,
1539
- imageQuality,
1540
- imageMaxFileSizeBytes
1541
- });
1542
1550
  await ensureSagepilotAndroidCameraPermission();
1543
1551
  if (!imagePicker) {
1544
1552
  throw new SagepilotFilePickerError("camera_unavailable", "The camera picker is not available in this build.");
1545
1553
  }
1546
- debugFilePicker("launching image-picker camera", { platform: Platform2.OS });
1547
1554
  return imageAssetsToPickedFiles(await imagePicker.launchCamera(imageOptions), imageMaxFileSizeBytes);
1548
1555
  }
1549
1556
  async function pickFromLibrary(multiple) {
1550
1557
  if (!imagePicker) return [];
1551
- debugFilePicker("library pick requested", { multiple, imageSelectionLimit });
1552
1558
  return imageAssetsToPickedFiles(await imagePicker.launchImageLibrary({
1553
1559
  ...imageOptions,
1554
1560
  // Bounded multi-select: 0 (unlimited) lets a huge batch OOM the bridge.
@@ -1557,7 +1563,6 @@ function createSagepilotFilePicker(options) {
1557
1563
  }
1558
1564
  async function pickDocuments(multiple) {
1559
1565
  if (!documentsPicker) return [];
1560
- debugFilePicker("document pick requested", { multiple, documentMaxFileSizeBytes });
1561
1566
  let picked;
1562
1567
  try {
1563
1568
  picked = await documentsPicker.pick({ allowMultiSelection: multiple });
@@ -1607,7 +1612,6 @@ function createSagepilotFilePicker(options) {
1607
1612
  return {
1608
1613
  sources,
1609
1614
  async pickFiles(request) {
1610
- debugFilePicker("pickFiles request", request);
1611
1615
  if (request.source === "camera") return pickFromCamera();
1612
1616
  if (request.source === "library") return pickFromLibrary(request.multiple);
1613
1617
  return pickDocuments(request.multiple);
@@ -1840,7 +1844,6 @@ var FILE_PICKER_SOURCE_ICON_COLORS = {
1840
1844
  library: "#16a34a",
1841
1845
  documents: "#7c3aed"
1842
1846
  };
1843
- var DEBUG_PREFIX2 = "[SagepilotSDK][Provider]";
1844
1847
  var DELIVERY_RETRY_MS = 1500;
1845
1848
  var DELIVERY_LEGACY_FALLBACK_ATTEMPTS = 2;
1846
1849
  var DELIVERY_MAX_ATTEMPTS = 8;
@@ -1924,16 +1927,6 @@ function readFilePickerError(error) {
1924
1927
  }
1925
1928
  return { message: "Could not attach the selected file." };
1926
1929
  }
1927
- function debugProvider(message, details) {
1928
- console.log(`${DEBUG_PREFIX2} ${message}`, details ?? "");
1929
- }
1930
- function describeAttachmentTarget(target) {
1931
- return {
1932
- targetChatId: target?.chatId,
1933
- targetRouteChatId: target?.routeChatId,
1934
- targetScreen: target?.hostedChatView.screen
1935
- };
1936
- }
1937
1930
  function getHostedIdentityDispatchScript() {
1938
1931
  const message = internalSagepilotChat.getHostedIdentityMessage();
1939
1932
  if (!message) return "";
@@ -2083,10 +2076,6 @@ function SagepilotChatProvider({
2083
2076
  const batch = pendingBatchesRef.current[0];
2084
2077
  if (!batch) return;
2085
2078
  if (internalSagepilotChat.restoreHostedAttachmentTarget(batch.target)) {
2086
- debugProvider("restored hosted attachment target", {
2087
- batchId: batch.batchId,
2088
- ...describeAttachmentTarget(batch.target)
2089
- });
2090
2079
  widgetReadyRef.current = false;
2091
2080
  deliveryTimerRef.current = setTimeout(() => pumpDelivery(), DELIVERY_RETRY_MS);
2092
2081
  return;
@@ -2096,13 +2085,6 @@ function SagepilotChatProvider({
2096
2085
  const ref = nativeWebViewRef.current;
2097
2086
  const shouldDeliver = ref && (widgetReadyRef.current || attempts >= DELIVERY_LEGACY_FALLBACK_ATTEMPTS);
2098
2087
  if (shouldDeliver && ref) {
2099
- debugProvider("delivering native picked files", {
2100
- batchId: batch.batchId,
2101
- attempt: attempts,
2102
- widgetReady: widgetReadyRef.current,
2103
- count: batch.files.length,
2104
- ...describeAttachmentTarget(batch.target)
2105
- });
2106
2088
  ref.injectJavaScript(buildFilesPickedScript(batch));
2107
2089
  }
2108
2090
  if (attempts < DELIVERY_MAX_ATTEMPTS) {
@@ -2140,21 +2122,12 @@ function SagepilotChatProvider({
2140
2122
  storageKeys,
2141
2123
  target: internalSagepilotChat.getHostedAttachmentTarget()
2142
2124
  };
2143
- debugProvider("queued native picked files", {
2144
- batchId,
2145
- count: files.length,
2146
- totalBase64Bytes: totalBase64Bytes(files),
2147
- persistedToFileStore: hasFileStore,
2148
- ...describeAttachmentTarget(batch.target)
2149
- });
2150
2125
  pendingBatchesRef.current = [...pendingBatchesRef.current, batch];
2151
2126
  ensureDelivery();
2152
2127
  writeManifest();
2153
2128
  void writeBatchBytes(batch);
2154
2129
  }, [ensureDelivery, writeManifest, writeBatchBytes]);
2155
- const recoverNativeWebView = useCallback((reasonOrEvent) => {
2156
- const reason = typeof reasonOrEvent === "string" ? reasonOrEvent : "webview_render_process";
2157
- debugProvider("recovering native WebView", { reason });
2130
+ const recoverNativeWebView = useCallback((_reasonOrEvent) => {
2158
2131
  widgetReadyRef.current = false;
2159
2132
  setNativeWebViewKey((key) => key + 1);
2160
2133
  }, []);
@@ -2168,31 +2141,14 @@ function SagepilotChatProvider({
2168
2141
  const runNativeFilePicker = useCallback((source, multiple) => {
2169
2142
  const filePicker = internalSagepilotChat.getConfig()?.filePicker;
2170
2143
  if (!filePicker) {
2171
- debugProvider("native file picker requested but no adapter is configured", { source, multiple });
2172
2144
  return;
2173
2145
  }
2174
2146
  if (pickerInFlightRef.current) {
2175
- debugProvider("native file picker ignored because another picker is in flight", { source, multiple });
2176
2147
  return;
2177
2148
  }
2178
- debugProvider("native file picker starting", {
2179
- source,
2180
- multiple,
2181
- configuredSources: filePicker.sources
2182
- });
2183
2149
  pauseLivenessAfterPicker(6e4);
2184
2150
  pickerInFlightRef.current = true;
2185
2151
  filePicker.pickFiles({ source, multiple }).then((files) => {
2186
- debugProvider("native file picker resolved", {
2187
- source,
2188
- count: files.length,
2189
- files: files.map((file) => ({
2190
- fileName: file.file_name,
2191
- mimeType: file.mime_type,
2192
- size: file.size,
2193
- base64Length: file.data_base64.length
2194
- }))
2195
- });
2196
2152
  if (files.length === 0) {
2197
2153
  nativeWebViewRef.current?.injectJavaScript(buildFilePickerCancelledScript());
2198
2154
  return;
@@ -2200,7 +2156,6 @@ function SagepilotChatProvider({
2200
2156
  queuePickedFiles(files);
2201
2157
  }).catch((error) => {
2202
2158
  const { message, code } = readFilePickerError(error);
2203
- debugProvider("native file picker failed", { source, code, message });
2204
2159
  nativeWebViewRef.current?.injectJavaScript(buildFilePickerErrorScript(message, code));
2205
2160
  }).finally(() => {
2206
2161
  pickerInFlightRef.current = false;
@@ -2210,14 +2165,8 @@ function SagepilotChatProvider({
2210
2165
  const openNativeFilePicker = useCallback((multiple) => {
2211
2166
  const filePicker = internalSagepilotChat.getConfig()?.filePicker;
2212
2167
  if (!filePicker || filePicker.sources.length === 0) {
2213
- debugProvider("open native file picker ignored", {
2214
- multiple,
2215
- hasAdapter: Boolean(filePicker),
2216
- sources: filePicker?.sources ?? []
2217
- });
2218
2168
  return;
2219
2169
  }
2220
- debugProvider("open native file picker", { multiple, sources: filePicker.sources });
2221
2170
  const [onlySource] = filePicker.sources;
2222
2171
  if (filePicker.sources.length === 1 && onlySource && onlySource !== "camera") {
2223
2172
  runNativeFilePicker(onlySource, multiple);
@@ -2327,10 +2276,6 @@ function SagepilotChatProvider({
2327
2276
  const pauseRemainingMs = livenessPausedUntilRef.current - Date.now();
2328
2277
  if (pickerInFlightRef.current || pauseRemainingMs > 0) {
2329
2278
  const retryDelayMs = pickerInFlightRef.current ? 500 : Math.max(0, pauseRemainingMs);
2330
- debugProvider("liveness probe deferred after picker", {
2331
- pickerInFlight: pickerInFlightRef.current,
2332
- retryDelayMs
2333
- });
2334
2279
  clearDeferredLivenessProbe();
2335
2280
  livenessResumeTimerRef.current = setTimeout(() => {
2336
2281
  livenessResumeTimerRef.current = null;
@@ -2415,11 +2360,6 @@ function SagepilotChatProvider({
2415
2360
  const ackBatchId = message.batch_id;
2416
2361
  const head = pendingBatchesRef.current[0];
2417
2362
  if (head && (!ackBatchId || ackBatchId === head.batchId)) {
2418
- debugProvider("native picked files acknowledged", {
2419
- batchId: head.batchId,
2420
- ackBatchId,
2421
- count: message.count
2422
- });
2423
2363
  acknowledgeHeadBatch();
2424
2364
  }
2425
2365
  return;
@@ -2429,10 +2369,6 @@ function SagepilotChatProvider({
2429
2369
  if (pending && (!message.nonce || message.nonce === pending.nonce)) {
2430
2370
  if (message.alive === false) {
2431
2371
  clearPing();
2432
- debugProvider("liveness probe reported dead widget", {
2433
- supportsHeartbeat: message.supportsHeartbeat,
2434
- remountCount: livenessRemountCountRef.current
2435
- });
2436
2372
  if (livenessRemountCountRef.current < LIVENESS_MAX_REMOUNTS) {
2437
2373
  livenessRemountCountRef.current += 1;
2438
2374
  recoverNativeWebView("liveness_dead_pong");
@@ -2462,7 +2398,6 @@ function SagepilotChatProvider({
2462
2398
  nativeWebViewRef.current.injectJavaScript(getInjectedWebViewScript());
2463
2399
  };
2464
2400
  const handleNativeWebViewLoadEnd = () => {
2465
- debugProvider("native WebView load end");
2466
2401
  injectNativeBridgeToNativeWebView();
2467
2402
  postIdentityToNativeWebView();
2468
2403
  widgetReadyRef.current = false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagepilot-ai/react-native-sdk",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Sagepilot AI React Native chat SDK",
5
5
  "keywords": [
6
6
  "sagepilot",