@copilotkit/react-native 1.57.1 → 1.57.3
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 +11 -1
- package/dist/index.cjs +752 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +394 -6
- package/dist/index.d.mts +394 -6
- package/dist/index.mjs +725 -14
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills.cjs +86 -73
- package/dist/polyfills.cjs.map +1 -1
- package/dist/polyfills.mjs +86 -73
- package/dist/polyfills.mjs.map +1 -1
- package/package.json +21 -5
- package/src/CopilotChat.tsx +293 -0
- package/src/CopilotKitProvider.tsx +55 -13
- package/src/CopilotModal.tsx +32 -0
- package/src/CopilotPopup.tsx +359 -0
- package/src/CopilotSidebar.tsx +357 -0
- package/src/__tests__/__mocks__/expo-document-picker.ts +13 -0
- package/src/__tests__/__mocks__/expo-file-system.ts +12 -0
- package/src/__tests__/attachments-integration.test.tsx +336 -0
- package/src/__tests__/copilot-chat-agentid.test.tsx +305 -0
- package/src/__tests__/copilot-chat-attachments.test.tsx +259 -0
- package/src/__tests__/copilot-popup.test.tsx +558 -0
- package/src/__tests__/copilot-sidebar.test.tsx +500 -0
- package/src/__tests__/copilotkit-provider.test.tsx +3 -0
- package/src/__tests__/headless-integration.test.tsx +55 -1
- package/src/__tests__/streaming-fetch.test.ts +84 -44
- package/src/__tests__/use-attachments.test.ts +410 -0
- package/src/hooks/use-attachments.ts +274 -0
- package/src/index.ts +77 -3
- package/src/polyfills.ts +3 -2
- package/src/streaming-fetch.ts +135 -104
- package/tsdown.config.ts +1 -0
- package/vitest.config.mjs +19 -0
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// packages/react-native/src/__tests__/use-attachments.test.ts
|
|
2
|
+
import { renderHook, act } from "@testing-library/react";
|
|
3
|
+
import { describe, it, expect, beforeEach, vi } from "vitest";
|
|
4
|
+
|
|
5
|
+
// ─── Mocks ────────────────────────────────────────────────────────────────────
|
|
6
|
+
|
|
7
|
+
// Mock expo-document-picker
|
|
8
|
+
const mockGetDocumentAsync = vi.fn();
|
|
9
|
+
vi.mock("expo-document-picker", () => ({
|
|
10
|
+
getDocumentAsync: (...args: any[]) => mockGetDocumentAsync(...args),
|
|
11
|
+
}));
|
|
12
|
+
|
|
13
|
+
// Mock expo-file-system
|
|
14
|
+
const mockReadAsStringAsync = vi.fn();
|
|
15
|
+
vi.mock("expo-file-system", () => ({
|
|
16
|
+
readAsStringAsync: (...args: any[]) => mockReadAsStringAsync(...args),
|
|
17
|
+
EncodingType: { Base64: "base64" },
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
// Mock @copilotkit/shared -- only the utils we use
|
|
21
|
+
vi.mock("@copilotkit/shared", () => ({
|
|
22
|
+
getModalityFromMimeType: (mimeType: string) => {
|
|
23
|
+
if (mimeType.startsWith("image/")) return "image";
|
|
24
|
+
if (mimeType.startsWith("audio/")) return "audio";
|
|
25
|
+
if (mimeType.startsWith("video/")) return "video";
|
|
26
|
+
return "document";
|
|
27
|
+
},
|
|
28
|
+
formatFileSize: (bytes: number) => {
|
|
29
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
30
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
31
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
32
|
+
},
|
|
33
|
+
randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
// Import AFTER mocks
|
|
37
|
+
import { useAttachments } from "../hooks/use-attachments";
|
|
38
|
+
import type { NativeFileInput } from "../hooks/use-attachments";
|
|
39
|
+
|
|
40
|
+
// ─── Tests ────────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
describe("useAttachments (React Native)", () => {
|
|
43
|
+
beforeEach(() => {
|
|
44
|
+
vi.clearAllMocks();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
// ── Initial state ──────────────────────────────────────────────────────
|
|
48
|
+
|
|
49
|
+
describe("initial state", () => {
|
|
50
|
+
it("returns empty attachments when no config provided", () => {
|
|
51
|
+
const { result } = renderHook(() => useAttachments({}));
|
|
52
|
+
|
|
53
|
+
expect(result.current.attachments).toEqual([]);
|
|
54
|
+
expect(result.current.enabled).toBe(false);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("returns enabled=true when config.enabled is true", () => {
|
|
58
|
+
const { result } = renderHook(() =>
|
|
59
|
+
useAttachments({ config: { enabled: true } }),
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
expect(result.current.enabled).toBe(true);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("returns enabled=false when config.enabled is false", () => {
|
|
66
|
+
const { result } = renderHook(() =>
|
|
67
|
+
useAttachments({ config: { enabled: false } }),
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
expect(result.current.enabled).toBe(false);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// ── processFiles ──────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
describe("processFiles", () => {
|
|
77
|
+
it("adds attachment with correct modality for an image", async () => {
|
|
78
|
+
mockReadAsStringAsync.mockResolvedValue("base64ImageData");
|
|
79
|
+
|
|
80
|
+
const { result } = renderHook(() =>
|
|
81
|
+
useAttachments({ config: { enabled: true } }),
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
const file: NativeFileInput = {
|
|
85
|
+
uri: "file:///tmp/photo.jpg",
|
|
86
|
+
name: "photo.jpg",
|
|
87
|
+
size: 1024,
|
|
88
|
+
mimeType: "image/jpeg",
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
await act(async () => {
|
|
92
|
+
await result.current.processFiles([file]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
expect(result.current.attachments).toHaveLength(1);
|
|
96
|
+
expect(result.current.attachments[0]).toMatchObject({
|
|
97
|
+
type: "image",
|
|
98
|
+
filename: "photo.jpg",
|
|
99
|
+
size: 1024,
|
|
100
|
+
status: "ready",
|
|
101
|
+
source: {
|
|
102
|
+
type: "data",
|
|
103
|
+
value: "base64ImageData",
|
|
104
|
+
mimeType: "image/jpeg",
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
expect(result.current.attachments[0].id).toBeDefined();
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("adds attachment with 'document' modality for a PDF", async () => {
|
|
111
|
+
mockReadAsStringAsync.mockResolvedValue("base64PdfData");
|
|
112
|
+
|
|
113
|
+
const { result } = renderHook(() =>
|
|
114
|
+
useAttachments({ config: { enabled: true } }),
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
const file: NativeFileInput = {
|
|
118
|
+
uri: "file:///tmp/doc.pdf",
|
|
119
|
+
name: "doc.pdf",
|
|
120
|
+
size: 2048,
|
|
121
|
+
mimeType: "application/pdf",
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
await act(async () => {
|
|
125
|
+
await result.current.processFiles([file]);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
expect(result.current.attachments).toHaveLength(1);
|
|
129
|
+
expect(result.current.attachments[0].type).toBe("document");
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("rejects files that exceed maxSize", async () => {
|
|
133
|
+
const onUploadFailed = vi.fn();
|
|
134
|
+
|
|
135
|
+
const { result } = renderHook(() =>
|
|
136
|
+
useAttachments({
|
|
137
|
+
config: {
|
|
138
|
+
enabled: true,
|
|
139
|
+
maxSize: 500,
|
|
140
|
+
onUploadFailed,
|
|
141
|
+
},
|
|
142
|
+
}),
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
const file: NativeFileInput = {
|
|
146
|
+
uri: "file:///tmp/big.jpg",
|
|
147
|
+
name: "big.jpg",
|
|
148
|
+
size: 1000,
|
|
149
|
+
mimeType: "image/jpeg",
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
await act(async () => {
|
|
153
|
+
await result.current.processFiles([file]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
expect(result.current.attachments).toHaveLength(0);
|
|
157
|
+
expect(onUploadFailed).toHaveBeenCalledWith(
|
|
158
|
+
expect.objectContaining({
|
|
159
|
+
reason: "file-too-large",
|
|
160
|
+
}),
|
|
161
|
+
);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("rejects files that do not match accept filter", async () => {
|
|
165
|
+
const onUploadFailed = vi.fn();
|
|
166
|
+
|
|
167
|
+
const { result } = renderHook(() =>
|
|
168
|
+
useAttachments({
|
|
169
|
+
config: {
|
|
170
|
+
enabled: true,
|
|
171
|
+
accept: "image/*",
|
|
172
|
+
onUploadFailed,
|
|
173
|
+
},
|
|
174
|
+
}),
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
const file: NativeFileInput = {
|
|
178
|
+
uri: "file:///tmp/doc.pdf",
|
|
179
|
+
name: "doc.pdf",
|
|
180
|
+
size: 1024,
|
|
181
|
+
mimeType: "application/pdf",
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
await act(async () => {
|
|
185
|
+
await result.current.processFiles([file]);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
expect(result.current.attachments).toHaveLength(0);
|
|
189
|
+
expect(onUploadFailed).toHaveBeenCalledWith(
|
|
190
|
+
expect.objectContaining({
|
|
191
|
+
reason: "invalid-type",
|
|
192
|
+
}),
|
|
193
|
+
);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it("handles file read errors gracefully", async () => {
|
|
197
|
+
mockReadAsStringAsync.mockRejectedValue(new Error("Read failed"));
|
|
198
|
+
const onUploadFailed = vi.fn();
|
|
199
|
+
|
|
200
|
+
const { result } = renderHook(() =>
|
|
201
|
+
useAttachments({
|
|
202
|
+
config: { enabled: true, onUploadFailed },
|
|
203
|
+
}),
|
|
204
|
+
);
|
|
205
|
+
|
|
206
|
+
const file: NativeFileInput = {
|
|
207
|
+
uri: "file:///tmp/bad.jpg",
|
|
208
|
+
name: "bad.jpg",
|
|
209
|
+
size: 100,
|
|
210
|
+
mimeType: "image/jpeg",
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
await act(async () => {
|
|
214
|
+
await result.current.processFiles([file]);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// Placeholder should have been removed after error
|
|
218
|
+
expect(result.current.attachments).toHaveLength(0);
|
|
219
|
+
expect(onUploadFailed).toHaveBeenCalledWith(
|
|
220
|
+
expect.objectContaining({
|
|
221
|
+
reason: "upload-failed",
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("calls custom onUpload instead of reading file directly", async () => {
|
|
227
|
+
const customUpload = vi.fn().mockResolvedValue({
|
|
228
|
+
type: "url",
|
|
229
|
+
value: "https://cdn.example.com/photo.jpg",
|
|
230
|
+
mimeType: "image/jpeg",
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
const { result } = renderHook(() =>
|
|
234
|
+
useAttachments({
|
|
235
|
+
config: { enabled: true, onUpload: customUpload },
|
|
236
|
+
}),
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
const file: NativeFileInput = {
|
|
240
|
+
uri: "file:///tmp/photo.jpg",
|
|
241
|
+
name: "photo.jpg",
|
|
242
|
+
size: 1024,
|
|
243
|
+
mimeType: "image/jpeg",
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
await act(async () => {
|
|
247
|
+
await result.current.processFiles([file]);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
expect(customUpload).toHaveBeenCalledWith(file);
|
|
251
|
+
expect(mockReadAsStringAsync).not.toHaveBeenCalled();
|
|
252
|
+
expect(result.current.attachments[0].source).toEqual({
|
|
253
|
+
type: "url",
|
|
254
|
+
value: "https://cdn.example.com/photo.jpg",
|
|
255
|
+
mimeType: "image/jpeg",
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
// ── removeAttachment ──────────────────────────────────────────────────
|
|
261
|
+
|
|
262
|
+
describe("removeAttachment", () => {
|
|
263
|
+
it("removes an attachment by id", async () => {
|
|
264
|
+
mockReadAsStringAsync.mockResolvedValue("base64Data");
|
|
265
|
+
|
|
266
|
+
const { result } = renderHook(() =>
|
|
267
|
+
useAttachments({ config: { enabled: true } }),
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
const file: NativeFileInput = {
|
|
271
|
+
uri: "file:///tmp/a.jpg",
|
|
272
|
+
name: "a.jpg",
|
|
273
|
+
size: 100,
|
|
274
|
+
mimeType: "image/jpeg",
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
await act(async () => {
|
|
278
|
+
await result.current.processFiles([file]);
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
const id = result.current.attachments[0].id;
|
|
282
|
+
|
|
283
|
+
act(() => {
|
|
284
|
+
result.current.removeAttachment(id);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
expect(result.current.attachments).toHaveLength(0);
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
// ── consumeAttachments ────────────────────────────────────────────────
|
|
292
|
+
|
|
293
|
+
describe("consumeAttachments", () => {
|
|
294
|
+
it("returns ready attachments and clears the queue", async () => {
|
|
295
|
+
mockReadAsStringAsync.mockResolvedValue("base64Data");
|
|
296
|
+
|
|
297
|
+
const { result } = renderHook(() =>
|
|
298
|
+
useAttachments({ config: { enabled: true } }),
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
const file: NativeFileInput = {
|
|
302
|
+
uri: "file:///tmp/a.jpg",
|
|
303
|
+
name: "a.jpg",
|
|
304
|
+
size: 100,
|
|
305
|
+
mimeType: "image/jpeg",
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
await act(async () => {
|
|
309
|
+
await result.current.processFiles([file]);
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
expect(result.current.attachments).toHaveLength(1);
|
|
313
|
+
|
|
314
|
+
let consumed: any[];
|
|
315
|
+
act(() => {
|
|
316
|
+
consumed = result.current.consumeAttachments();
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
expect(consumed!).toHaveLength(1);
|
|
320
|
+
expect(consumed![0].status).toBe("ready");
|
|
321
|
+
expect(result.current.attachments).toHaveLength(0);
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
it("returns empty array when no attachments", () => {
|
|
325
|
+
const { result } = renderHook(() =>
|
|
326
|
+
useAttachments({ config: { enabled: true } }),
|
|
327
|
+
);
|
|
328
|
+
|
|
329
|
+
let consumed: any[];
|
|
330
|
+
act(() => {
|
|
331
|
+
consumed = result.current.consumeAttachments();
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
expect(consumed!).toHaveLength(0);
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
// ── openPicker ────────────────────────────────────────────────────────
|
|
339
|
+
|
|
340
|
+
describe("openPicker", () => {
|
|
341
|
+
it("calls DocumentPicker.getDocumentAsync and processes the result", async () => {
|
|
342
|
+
mockGetDocumentAsync.mockResolvedValue({
|
|
343
|
+
canceled: false,
|
|
344
|
+
assets: [
|
|
345
|
+
{
|
|
346
|
+
uri: "file:///cache/picked.jpg",
|
|
347
|
+
name: "picked.jpg",
|
|
348
|
+
size: 2048,
|
|
349
|
+
mimeType: "image/jpeg",
|
|
350
|
+
},
|
|
351
|
+
],
|
|
352
|
+
});
|
|
353
|
+
mockReadAsStringAsync.mockResolvedValue("pickedBase64");
|
|
354
|
+
|
|
355
|
+
const { result } = renderHook(() =>
|
|
356
|
+
useAttachments({ config: { enabled: true } }),
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
await act(async () => {
|
|
360
|
+
await result.current.openPicker();
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
expect(mockGetDocumentAsync).toHaveBeenCalledWith({
|
|
364
|
+
type: ["*/*"],
|
|
365
|
+
copyToCacheDirectory: true,
|
|
366
|
+
multiple: true,
|
|
367
|
+
});
|
|
368
|
+
expect(result.current.attachments).toHaveLength(1);
|
|
369
|
+
expect(result.current.attachments[0].filename).toBe("picked.jpg");
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
it("does nothing when picker is canceled", async () => {
|
|
373
|
+
mockGetDocumentAsync.mockResolvedValue({
|
|
374
|
+
canceled: true,
|
|
375
|
+
assets: [],
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
const { result } = renderHook(() =>
|
|
379
|
+
useAttachments({ config: { enabled: true } }),
|
|
380
|
+
);
|
|
381
|
+
|
|
382
|
+
await act(async () => {
|
|
383
|
+
await result.current.openPicker();
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
expect(result.current.attachments).toHaveLength(0);
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it("passes accept filter to DocumentPicker", async () => {
|
|
390
|
+
mockGetDocumentAsync.mockResolvedValue({
|
|
391
|
+
canceled: true,
|
|
392
|
+
assets: [],
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
const { result } = renderHook(() =>
|
|
396
|
+
useAttachments({ config: { enabled: true, accept: "image/*" } }),
|
|
397
|
+
);
|
|
398
|
+
|
|
399
|
+
await act(async () => {
|
|
400
|
+
await result.current.openPicker();
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
expect(mockGetDocumentAsync).toHaveBeenCalledWith(
|
|
404
|
+
expect.objectContaining({
|
|
405
|
+
type: ["image/*"],
|
|
406
|
+
}),
|
|
407
|
+
);
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
});
|
|
@@ -0,0 +1,274 @@
|
|
|
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";
|
|
8
|
+
import type {
|
|
9
|
+
Attachment,
|
|
10
|
+
AttachmentUploadResult,
|
|
11
|
+
AttachmentUploadErrorReason,
|
|
12
|
+
} from "@copilotkit/shared";
|
|
13
|
+
import * as DocumentPicker from "expo-document-picker";
|
|
14
|
+
import * as FileSystem from "expo-file-system";
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Types
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Platform-neutral file descriptor for React Native.
|
|
22
|
+
* Replaces the web `File` object in all attachment APIs.
|
|
23
|
+
*/
|
|
24
|
+
export interface NativeFileInput {
|
|
25
|
+
/** Local file URI (e.g. `file:///path/to/file`). */
|
|
26
|
+
uri: string;
|
|
27
|
+
/** Filename with extension. */
|
|
28
|
+
name: string;
|
|
29
|
+
/** File size in bytes. */
|
|
30
|
+
size: number;
|
|
31
|
+
/** MIME type (e.g. `"image/jpeg"`). */
|
|
32
|
+
mimeType: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* React Native variant of AttachmentsConfig.
|
|
37
|
+
* Identical to the shared AttachmentsConfig except `onUpload` receives
|
|
38
|
+
* a `NativeFileInput` instead of a web `File`.
|
|
39
|
+
*/
|
|
40
|
+
export interface NativeAttachmentsConfig {
|
|
41
|
+
/** Enable file attachments in the chat input. */
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
/** MIME type filter for the file picker, default all files. */
|
|
44
|
+
accept?: string;
|
|
45
|
+
/** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */
|
|
46
|
+
maxSize?: number;
|
|
47
|
+
/** Custom upload handler. Receives the native file descriptor. */
|
|
48
|
+
onUpload?: (
|
|
49
|
+
file: NativeFileInput,
|
|
50
|
+
) => AttachmentUploadResult | Promise<AttachmentUploadResult>;
|
|
51
|
+
/** Called when an attachment fails validation or upload. */
|
|
52
|
+
onUploadFailed?: (error: {
|
|
53
|
+
reason: AttachmentUploadErrorReason;
|
|
54
|
+
file: NativeFileInput;
|
|
55
|
+
message: string;
|
|
56
|
+
}) => void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface UseNativeAttachmentsProps {
|
|
60
|
+
config?: NativeAttachmentsConfig;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface UseNativeAttachmentsReturn {
|
|
64
|
+
/** Currently selected attachments (uploading + ready). */
|
|
65
|
+
attachments: Attachment[];
|
|
66
|
+
/** Whether attachments are enabled. */
|
|
67
|
+
enabled: boolean;
|
|
68
|
+
/** Open the native document picker. */
|
|
69
|
+
openPicker: () => Promise<void>;
|
|
70
|
+
/** Process an array of NativeFileInput objects (validate, read, add to state). */
|
|
71
|
+
processFiles: (files: NativeFileInput[]) => Promise<void>;
|
|
72
|
+
/** Remove an attachment by ID. */
|
|
73
|
+
removeAttachment: (id: string) => void;
|
|
74
|
+
/** Consume ready attachments and clear the queue. Returns the consumed attachments. */
|
|
75
|
+
consumeAttachments: () => Attachment[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
// Constants
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
const DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB
|
|
83
|
+
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
// Hook
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* React Native hook that manages file attachment state -- picking, uploading,
|
|
90
|
+
* and lifecycle. All returned callbacks are referentially stable via useCallback.
|
|
91
|
+
*
|
|
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).
|
|
95
|
+
*/
|
|
96
|
+
export function useAttachments({
|
|
97
|
+
config,
|
|
98
|
+
}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {
|
|
99
|
+
const enabled = config?.enabled ?? false;
|
|
100
|
+
|
|
101
|
+
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
|
102
|
+
|
|
103
|
+
// Refs for stable callbacks to read latest values
|
|
104
|
+
const configRef = useRef(config);
|
|
105
|
+
configRef.current = config;
|
|
106
|
+
const attachmentsRef = useRef<Attachment[]>([]);
|
|
107
|
+
attachmentsRef.current = attachments;
|
|
108
|
+
|
|
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
|
+
[],
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
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],
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
const openPicker = useCallback(async () => {
|
|
224
|
+
const cfg = configRef.current;
|
|
225
|
+
const accept = cfg?.accept ?? "*/*";
|
|
226
|
+
|
|
227
|
+
// Convert accept string to array for DocumentPicker
|
|
228
|
+
const typeArray = accept
|
|
229
|
+
.split(",")
|
|
230
|
+
.map((t) => t.trim())
|
|
231
|
+
.filter(Boolean);
|
|
232
|
+
|
|
233
|
+
try {
|
|
234
|
+
const result = await DocumentPicker.getDocumentAsync({
|
|
235
|
+
type: typeArray.length > 0 ? typeArray : ["*/*"],
|
|
236
|
+
copyToCacheDirectory: true,
|
|
237
|
+
multiple: true,
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
if (result.canceled || !result.assets?.length) return;
|
|
241
|
+
|
|
242
|
+
const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({
|
|
243
|
+
uri: asset.uri,
|
|
244
|
+
name: asset.name ?? "unknown",
|
|
245
|
+
size: asset.size ?? 0,
|
|
246
|
+
mimeType: asset.mimeType ?? "application/octet-stream",
|
|
247
|
+
}));
|
|
248
|
+
|
|
249
|
+
await processFiles(nativeFiles);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
console.error("[CopilotKit] Document picker error:", error);
|
|
252
|
+
}
|
|
253
|
+
}, [processFiles]);
|
|
254
|
+
|
|
255
|
+
const removeAttachment = useCallback((id: string) => {
|
|
256
|
+
setAttachments((prev) => prev.filter((a) => a.id !== id));
|
|
257
|
+
}, []);
|
|
258
|
+
|
|
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
|
+
}, []);
|
|
265
|
+
|
|
266
|
+
return {
|
|
267
|
+
attachments,
|
|
268
|
+
enabled,
|
|
269
|
+
openPicker,
|
|
270
|
+
processFiles,
|
|
271
|
+
removeAttachment,
|
|
272
|
+
consumeAttachments,
|
|
273
|
+
};
|
|
274
|
+
}
|