@copilotkit/react-native 2.0.0-rc.25 → 2.0.0-rc.27

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.
@@ -1,12 +1,9 @@
1
1
  // packages/react-native/src/hooks/use-attachments.ts
2
- import { useCallback, useRef, useState } from "react";
3
- import {
4
- randomUUID,
5
- getModalityFromMimeType,
6
- formatFileSize,
7
- } from "@copilotkit/shared";
2
+ import { useCallback, useRef, useState, useSyncExternalStore } from "react";
3
+ import { ɵAttachmentQueue } from "@copilotkit/core";
8
4
  import type {
9
5
  Attachment,
6
+ AttachmentsConfig,
10
7
  AttachmentUploadResult,
11
8
  AttachmentUploadErrorReason,
12
9
  } from "@copilotkit/shared";
@@ -76,10 +73,77 @@ export interface UseNativeAttachmentsReturn {
76
73
  }
77
74
 
78
75
  // ---------------------------------------------------------------------------
79
- // Constants
76
+ // Queue adapter
80
77
  // ---------------------------------------------------------------------------
81
78
 
82
- const DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB
79
+ /**
80
+ * The queue's view of a picked file: the `name`, `size` and `type` it reads to
81
+ * validate the file and to draw its placeholder.
82
+ */
83
+ interface QueuedNativeFile {
84
+ name: string;
85
+ size: number;
86
+ type: string;
87
+ }
88
+
89
+ // The native descriptor behind each file the queue holds, so the app's
90
+ // callbacks get the `NativeFileInput` they were typed for.
91
+ const nativeFiles = new WeakMap<object, NativeFileInput>();
92
+
93
+ /**
94
+ * Wraps a native file for core's `ɵAttachmentQueue`, which is typed for the
95
+ * web `File`. The queue reads only `name`, `size` and `type`, because the
96
+ * config from {@link toQueueConfig} always uploads through `onUpload` and the
97
+ * queue never reads the bytes itself.
98
+ */
99
+ function toQueueFile(file: NativeFileInput) {
100
+ const queued: QueuedNativeFile = {
101
+ name: file.name,
102
+ size: file.size,
103
+ type: file.mimeType,
104
+ };
105
+ nativeFiles.set(queued, file);
106
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the queue is typed for the web File; it only reads name, size and type, and uploads go through onUpload with the native file
107
+ return queued as unknown as File;
108
+ }
109
+
110
+ function toNativeFile(file: File) {
111
+ const native = nativeFiles.get(file);
112
+ if (!native) {
113
+ throw new Error(`[CopilotKit] "${file.name}" was not picked natively`);
114
+ }
115
+ return native;
116
+ }
117
+
118
+ /** Reads a picked file as base64 with expo-file-system. */
119
+ async function readNativeFile(file: NativeFileInput) {
120
+ const value = await FileSystem.readAsStringAsync(file.uri, {
121
+ encoding: FileSystem.EncodingType.Base64,
122
+ });
123
+ return { type: "data" as const, value, mimeType: file.mimeType };
124
+ }
125
+
126
+ /**
127
+ * The RN config as core's queue takes it. Uploads go through the app's
128
+ * `onUpload`, or through expo-file-system when there is none.
129
+ */
130
+ function toQueueConfig(
131
+ config: NativeAttachmentsConfig | undefined,
132
+ ): AttachmentsConfig | undefined {
133
+ if (!config) return undefined;
134
+ const { onUpload, onUploadFailed, ...rest } = config;
135
+ return {
136
+ ...rest,
137
+ onUpload: (file) => {
138
+ const native = toNativeFile(file);
139
+ return onUpload ? onUpload(native) : readNativeFile(native);
140
+ },
141
+ onUploadFailed: onUploadFailed
142
+ ? ({ file, ...error }) =>
143
+ onUploadFailed({ ...error, file: toNativeFile(file) })
144
+ : undefined,
145
+ };
146
+ }
83
147
 
84
148
  // ---------------------------------------------------------------------------
85
149
  // Hook
@@ -87,142 +151,38 @@ const DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB
87
151
 
88
152
  /**
89
153
  * React Native hook that manages file attachment state -- picking, uploading,
90
- * and lifecycle. All returned callbacks are referentially stable via useCallback.
154
+ * and lifecycle. All returned callbacks are referentially stable.
91
155
  *
92
- * This is the RN counterpart of the web `useAttachments` hook from
93
- * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,
94
- * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).
156
+ * The queue itself (accept filter, size check, uploads, ready state) is
157
+ * `@copilotkit/core`'s `ɵAttachmentQueue`, shared with the web chats. This
158
+ * hook adds the native glue: expo-document-picker to pick files and
159
+ * expo-file-system to read them.
95
160
  */
96
161
  export function useAttachments({
97
162
  config,
98
163
  }: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {
99
164
  const enabled = config?.enabled ?? false;
100
165
 
101
- const [attachments, setAttachments] = useState<Attachment[]>([]);
102
-
103
- // Refs for stable callbacks to read latest values
166
+ // The queue reads the latest config on every action.
104
167
  const configRef = useRef(config);
105
168
  configRef.current = config;
106
- const attachmentsRef = useRef<Attachment[]>([]);
107
- attachmentsRef.current = attachments;
108
169
 
109
- /**
110
- * Simple MIME accept filter for NativeFileInput.
111
- * Handles wildcards like "image/*" and exact types like "application/pdf".
112
- * Comma-separated lists are supported.
113
- */
114
- const matchesAccept = useCallback(
115
- (file: NativeFileInput, accept: string): boolean => {
116
- if (!accept || accept === "*/*") return true;
117
- const filters = accept.split(",").map((f) => f.trim());
118
- return filters.some((filter) => {
119
- if (filter.startsWith(".")) {
120
- return file.name.toLowerCase().endsWith(filter.toLowerCase());
121
- }
122
- if (filter.endsWith("/*")) {
123
- const prefix = filter.slice(0, -2);
124
- return file.mimeType.startsWith(prefix + "/");
125
- }
126
- return file.mimeType === filter;
127
- });
128
- },
129
- [],
170
+ const [queue] = useState(
171
+ () => new ɵAttachmentQueue(() => toQueueConfig(configRef.current)),
172
+ );
173
+ const attachments = useSyncExternalStore(
174
+ useCallback((onChange) => queue.subscribe(onChange), [queue]),
175
+ () => queue.getSnapshot(),
176
+ () => queue.getSnapshot(),
130
177
  );
131
178
 
132
179
  const processFiles = useCallback(
133
- async (files: NativeFileInput[]) => {
134
- const cfg = configRef.current;
135
- const accept = cfg?.accept ?? "*/*";
136
- const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;
137
-
138
- // Filter by accept type
139
- const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));
140
- for (const file of rejectedFiles) {
141
- cfg?.onUploadFailed?.({
142
- reason: "invalid-type",
143
- file,
144
- message: `File "${file.name}" is not accepted. Supported types: ${accept}`,
145
- });
146
- }
147
-
148
- const validFiles = files.filter((f) => matchesAccept(f, accept));
149
-
150
- for (const file of validFiles) {
151
- // Size check
152
- if (file.size > maxSize) {
153
- cfg?.onUploadFailed?.({
154
- reason: "file-too-large",
155
- file,
156
- message: `File "${file.name}" exceeds the maximum size of ${formatFileSize(maxSize)}`,
157
- });
158
- continue;
159
- }
160
-
161
- const modality = getModalityFromMimeType(file.mimeType);
162
- const placeholderId = randomUUID();
163
- const placeholder: Attachment = {
164
- id: placeholderId,
165
- type: modality,
166
- source: { type: "data", value: "", mimeType: file.mimeType },
167
- filename: file.name,
168
- size: file.size,
169
- status: "uploading",
170
- };
171
-
172
- setAttachments((prev) => [...prev, placeholder]);
173
-
174
- try {
175
- let source: Attachment["source"];
176
- let uploadMetadata: Record<string, unknown> | undefined;
177
-
178
- if (cfg?.onUpload) {
179
- const { metadata: meta, ...uploadSource } =
180
- await cfg.onUpload(file);
181
- source = uploadSource;
182
- uploadMetadata = meta;
183
- } else {
184
- // Default: read file as base64 via expo-file-system
185
- const base64 = await FileSystem.readAsStringAsync(file.uri, {
186
- encoding: FileSystem.EncodingType.Base64,
187
- });
188
- source = { type: "data", value: base64, mimeType: file.mimeType };
189
- }
190
-
191
- setAttachments((prev) =>
192
- prev.map((att) =>
193
- att.id === placeholderId
194
- ? {
195
- ...att,
196
- source,
197
- status: "ready" as const,
198
- metadata: uploadMetadata,
199
- }
200
- : att,
201
- ),
202
- );
203
- } catch (error) {
204
- // Remove placeholder on failure
205
- setAttachments((prev) =>
206
- prev.filter((att) => att.id !== placeholderId),
207
- );
208
- console.error(`[CopilotKit] Failed to upload "${file.name}":`, error);
209
- cfg?.onUploadFailed?.({
210
- reason: "upload-failed",
211
- file,
212
- message:
213
- error instanceof Error
214
- ? error.message
215
- : `Failed to upload "${file.name}"`,
216
- });
217
- }
218
- }
219
- },
220
- [matchesAccept],
180
+ (files: NativeFileInput[]) => queue.processFiles(files.map(toQueueFile)),
181
+ [queue],
221
182
  );
222
183
 
223
184
  const openPicker = useCallback(async () => {
224
- const cfg = configRef.current;
225
- const accept = cfg?.accept ?? "*/*";
185
+ const accept = configRef.current?.accept ?? "*/*";
226
186
 
227
187
  // Convert accept string to array for DocumentPicker
228
188
  const typeArray = accept
@@ -239,29 +199,25 @@ export function useAttachments({
239
199
 
240
200
  if (result.canceled || !result.assets?.length) return;
241
201
 
242
- const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({
202
+ const pickedFiles: NativeFileInput[] = result.assets.map((asset) => ({
243
203
  uri: asset.uri,
244
204
  name: asset.name ?? "unknown",
245
205
  size: asset.size ?? 0,
246
206
  mimeType: asset.mimeType ?? "application/octet-stream",
247
207
  }));
248
208
 
249
- await processFiles(nativeFiles);
209
+ await processFiles(pickedFiles);
250
210
  } catch (error) {
251
211
  console.error("[CopilotKit] Document picker error:", error);
252
212
  }
253
213
  }, [processFiles]);
254
214
 
255
- const removeAttachment = useCallback((id: string) => {
256
- setAttachments((prev) => prev.filter((a) => a.id !== id));
257
- }, []);
215
+ const removeAttachment = useCallback(
216
+ (id: string) => queue.remove(id),
217
+ [queue],
218
+ );
258
219
 
259
- const consumeAttachments = useCallback(() => {
260
- const ready = attachmentsRef.current.filter((a) => a.status === "ready");
261
- if (ready.length === 0) return ready;
262
- setAttachments((prev) => prev.filter((a) => a.status !== "ready"));
263
- return ready;
264
- }, []);
220
+ const consumeAttachments = useCallback(() => queue.consumeReady(), [queue]);
265
221
 
266
222
  return {
267
223
  attachments,