@copilotkit/react-native 2.0.0-rc.3 → 2.0.0-rc.31
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/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-BXpkAl1Y.mjs} +55 -42
- package/dist/CopilotKitProvider-BXpkAl1Y.mjs.map +1 -0
- package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-DDPbJkHS.cjs} +53 -40
- package/dist/CopilotKitProvider-DDPbJkHS.cjs.map +1 -0
- package/dist/CopilotKitProvider-F7Pn5kp4.d.cts +65 -0
- package/dist/CopilotKitProvider-Khgz5dQo.d.mts +65 -0
- package/dist/{Markdown-C_9Re36O.cjs → Markdown-CaYHlD4j.cjs} +8 -8
- package/dist/Markdown-CaYHlD4j.cjs.map +1 -0
- package/dist/{Markdown-1ips7myr.d.cts → Markdown-DzjnSuu5.d.cts} +3 -3
- package/dist/{Markdown-C6AsLHmd.mjs → Markdown-SE9MfY2U.mjs} +4 -4
- package/dist/Markdown-SE9MfY2U.mjs.map +1 -0
- package/dist/{Markdown-JsYh7oSA.d.mts → Markdown-a-rdG22_.d.mts} +3 -3
- package/dist/{MarkdownRendererContext-CAnuohIS.mjs → MarkdownRendererContext-B_AKdPAN.mjs} +1 -1
- package/dist/{MarkdownRendererContext-CAnuohIS.mjs.map → MarkdownRendererContext-B_AKdPAN.mjs.map} +1 -1
- package/dist/components/index.cjs +73 -172
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.d.cts +2 -2
- package/dist/components/index.d.mts +2 -2
- package/dist/components/index.mjs +75 -174
- package/dist/components/index.mjs.map +1 -1
- package/dist/headless.cjs +2 -1
- package/dist/headless.d.cts +2 -2
- package/dist/headless.d.mts +2 -2
- package/dist/headless.mjs +2 -1
- package/dist/index.cjs +126 -158
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -17
- package/dist/index.d.mts +36 -18
- package/dist/index.mjs +130 -161
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills/encoding.cjs +5 -5
- package/dist/polyfills/encoding.cjs.map +1 -1
- package/dist/polyfills/encoding.mjs +5 -4
- package/dist/polyfills/encoding.mjs.map +1 -1
- package/dist/polyfills.cjs +2 -1
- package/dist/polyfills.cjs.map +1 -1
- package/dist/polyfills.mjs +2 -1
- package/dist/polyfills.mjs.map +1 -1
- package/dist/{streaming-fetch-Dm1oN4f2.mjs → streaming-fetch-CLHG3Z1H.mjs} +1 -1
- package/dist/{streaming-fetch-Dm1oN4f2.mjs.map → streaming-fetch-CLHG3Z1H.mjs.map} +1 -1
- package/dist/{streaming-fetch-Bm91EsRc.cjs → streaming-fetch-DbDALGya.cjs} +1 -1
- package/dist/{streaming-fetch-Bm91EsRc.cjs.map → streaming-fetch-DbDALGya.cjs.map} +1 -1
- package/dist/utf8-BIN9t4Oy.mjs +113 -0
- package/dist/utf8-BIN9t4Oy.mjs.map +1 -0
- package/dist/utf8-Cf3Ssy33.cjs +125 -0
- package/dist/utf8-Cf3Ssy33.cjs.map +1 -0
- package/package.json +12 -21
- package/scripts/verify-polyfill-barrel.mjs +4 -6
- package/src/CopilotChat.tsx +114 -93
- package/src/CopilotKitProvider.tsx +87 -130
- package/src/CopilotPopup.tsx +2 -2
- package/src/CopilotSidebar.tsx +7 -5
- package/src/__mocks__/react-native.ts +31 -0
- package/src/__mocks__/test-copilotkit.tsx +9 -3
- package/src/__tests__/attachments-integration.test.tsx +15 -2
- package/src/__tests__/copilot-chat-agentid.test.tsx +15 -2
- package/src/__tests__/copilot-chat-attachments.test.tsx +15 -2
- package/src/__tests__/copilot-chat-configuration.test.tsx +82 -0
- package/src/__tests__/copilot-chat-threads.test.tsx +232 -0
- package/src/__tests__/copilot-popup.test.tsx +15 -2
- package/src/__tests__/copilot-sidebar.test.tsx +15 -2
- package/src/__tests__/copilotkit-provider.test.tsx +68 -73
- package/src/__tests__/headless-integration.test.tsx +11 -1
- package/src/__tests__/use-attachments.test.ts +27 -2
- package/src/components/CopilotChat.tsx +106 -233
- package/src/components/CopilotModal.tsx +1 -1
- package/src/components/Markdown.tsx +4 -4
- package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
- package/src/components/__tests__/CopilotChat.test.tsx +12 -4
- package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
- package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
- package/src/components/messages/AssistantMessage.tsx +3 -3
- package/src/components/messages/TypingIndicator.tsx +4 -4
- package/src/hooks/use-attachments.ts +95 -139
- package/src/polyfills/__tests__/utf8.test.ts +112 -0
- package/src/polyfills/encoding.ts +5 -4
- package/src/polyfills/utf8.ts +151 -0
- package/src/types.d.ts +0 -13
- package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
- package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
- package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
- package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
- package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
- package/dist/Markdown-C_9Re36O.cjs.map +0 -1
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import {
|
|
3
|
+
act,
|
|
4
|
+
fireEvent,
|
|
5
|
+
render,
|
|
6
|
+
screen,
|
|
7
|
+
waitFor,
|
|
8
|
+
} from "@testing-library/react";
|
|
9
|
+
import { describe, expect, it, vi } from "vitest";
|
|
10
|
+
import { EventType, HttpAgent } from "@ag-ui/client";
|
|
11
|
+
import type { RunAgentInput } from "@ag-ui/client";
|
|
12
|
+
import { useCopilotKit } from "@copilotkit/react-core/context";
|
|
13
|
+
import type { CopilotKitCoreReact } from "@copilotkit/react-core/context";
|
|
14
|
+
|
|
15
|
+
// The shared react-native stub passes FlatList props through unused. This one
|
|
16
|
+
// renders the rows and then the footer, which is where CopilotChat draws the
|
|
17
|
+
// interrupt element.
|
|
18
|
+
vi.mock("react-native", async () => {
|
|
19
|
+
const actual = await vi.importActual<any>("../../__mocks__/react-native");
|
|
20
|
+
return {
|
|
21
|
+
...actual,
|
|
22
|
+
FlatList: ({
|
|
23
|
+
data,
|
|
24
|
+
renderItem,
|
|
25
|
+
keyExtractor,
|
|
26
|
+
ListEmptyComponent,
|
|
27
|
+
ListFooterComponent,
|
|
28
|
+
}: any) =>
|
|
29
|
+
React.createElement(
|
|
30
|
+
"div",
|
|
31
|
+
{ "data-testid": "flatlist" },
|
|
32
|
+
data?.length
|
|
33
|
+
? data.map((item: any, index: number) =>
|
|
34
|
+
React.createElement(
|
|
35
|
+
"div",
|
|
36
|
+
{ key: keyExtractor?.(item) ?? index },
|
|
37
|
+
renderItem({ item, index, separators: {} }),
|
|
38
|
+
),
|
|
39
|
+
)
|
|
40
|
+
: ListEmptyComponent,
|
|
41
|
+
ListFooterComponent,
|
|
42
|
+
),
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
import { CopilotChat } from "../CopilotChat";
|
|
47
|
+
import { useInterrupt } from "../../headless";
|
|
48
|
+
import { TestCopilotKit } from "../../__mocks__/test-copilotkit";
|
|
49
|
+
|
|
50
|
+
function CoreProbe({
|
|
51
|
+
coreRef,
|
|
52
|
+
}: {
|
|
53
|
+
coreRef: { current: CopilotKitCoreReact | null };
|
|
54
|
+
}) {
|
|
55
|
+
coreRef.current = useCopilotKit().copilotkit;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* An agent whose first run stops on an approval interrupt and whose later runs
|
|
61
|
+
* finish normally. It streams real AG-UI events over SSE, so core and
|
|
62
|
+
* useInterrupt see the same run lifecycle as in an app.
|
|
63
|
+
*/
|
|
64
|
+
function createInterruptingAgent() {
|
|
65
|
+
const inputs: RunAgentInput[] = [];
|
|
66
|
+
const agent = new HttpAgent({
|
|
67
|
+
url: "http://localhost/agent",
|
|
68
|
+
fetch: async (_url, init) => {
|
|
69
|
+
const input = JSON.parse(String(init.body)) as RunAgentInput;
|
|
70
|
+
inputs.push(input);
|
|
71
|
+
const { threadId, runId } = input;
|
|
72
|
+
const events = [
|
|
73
|
+
{ type: EventType.RUN_STARTED, threadId, runId },
|
|
74
|
+
{
|
|
75
|
+
type: EventType.RUN_FINISHED,
|
|
76
|
+
threadId,
|
|
77
|
+
runId,
|
|
78
|
+
...(inputs.length === 1
|
|
79
|
+
? {
|
|
80
|
+
outcome: {
|
|
81
|
+
type: "interrupt",
|
|
82
|
+
interrupts: [
|
|
83
|
+
{ id: "approve", reason: "approval", message: "Deploy?" },
|
|
84
|
+
],
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
: {}),
|
|
88
|
+
},
|
|
89
|
+
];
|
|
90
|
+
return new Response(
|
|
91
|
+
events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""),
|
|
92
|
+
{ headers: { "Content-Type": "text/event-stream" } },
|
|
93
|
+
);
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
return { agent, inputs };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Uses useInterrupt with the default renderInChat: true. */
|
|
100
|
+
function Approval() {
|
|
101
|
+
useInterrupt({
|
|
102
|
+
render: ({ interrupt, resolve }) => (
|
|
103
|
+
<button
|
|
104
|
+
data-testid="interrupt-ui"
|
|
105
|
+
onClick={() => void resolve({ approved: true })}
|
|
106
|
+
>
|
|
107
|
+
{interrupt?.message}
|
|
108
|
+
</button>
|
|
109
|
+
),
|
|
110
|
+
});
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const messages = [
|
|
115
|
+
{ id: "u1", role: "user", content: "Deploy the app" },
|
|
116
|
+
{ id: "a1", role: "assistant", content: "I need your approval first." },
|
|
117
|
+
];
|
|
118
|
+
|
|
119
|
+
function Chat({
|
|
120
|
+
agent,
|
|
121
|
+
coreRef,
|
|
122
|
+
withApproval = true,
|
|
123
|
+
}: {
|
|
124
|
+
agent: HttpAgent;
|
|
125
|
+
coreRef: { current: CopilotKitCoreReact | null };
|
|
126
|
+
withApproval?: boolean;
|
|
127
|
+
}) {
|
|
128
|
+
return (
|
|
129
|
+
<TestCopilotKit messages={messages} agent={agent}>
|
|
130
|
+
<CoreProbe coreRef={coreRef} />
|
|
131
|
+
{withApproval && <Approval />}
|
|
132
|
+
<CopilotChat />
|
|
133
|
+
</TestCopilotKit>
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Mounts the chat and runs the agent until it stops on the interrupt. */
|
|
138
|
+
async function renderInterruptedChat() {
|
|
139
|
+
const { agent, inputs } = createInterruptingAgent();
|
|
140
|
+
const coreRef: { current: CopilotKitCoreReact | null } = { current: null };
|
|
141
|
+
const view = render(<Chat agent={agent} coreRef={coreRef} />);
|
|
142
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
143
|
+
|
|
144
|
+
await act(async () => {
|
|
145
|
+
await coreRef.current!.runAgent({ agent });
|
|
146
|
+
});
|
|
147
|
+
await waitFor(() => expect(screen.getByTestId("interrupt-ui")).toBeTruthy());
|
|
148
|
+
return { ...view, agent, inputs, coreRef };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
describe("CopilotChat interrupt rendering", () => {
|
|
152
|
+
it("draws the interrupt element that useInterrupt publishes to core", () => {
|
|
153
|
+
const coreRef: { current: CopilotKitCoreReact | null } = { current: null };
|
|
154
|
+
render(
|
|
155
|
+
<TestCopilotKit messages={[]}>
|
|
156
|
+
<CoreProbe coreRef={coreRef} />
|
|
157
|
+
<CopilotChat />
|
|
158
|
+
</TestCopilotKit>,
|
|
159
|
+
);
|
|
160
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
161
|
+
|
|
162
|
+
act(() => {
|
|
163
|
+
coreRef.current!.setInterruptElement(
|
|
164
|
+
<div data-testid="interrupt-ui">Approve?</div>,
|
|
165
|
+
);
|
|
166
|
+
});
|
|
167
|
+
expect(screen.getByTestId("interrupt-ui").textContent).toBe("Approve?");
|
|
168
|
+
|
|
169
|
+
act(() => {
|
|
170
|
+
coreRef.current!.setInterruptElement(null);
|
|
171
|
+
});
|
|
172
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it("draws a useInterrupt element after the last message and removes it once resolved", async () => {
|
|
176
|
+
const { inputs } = await renderInterruptedChat();
|
|
177
|
+
|
|
178
|
+
const interrupt = screen.getByTestId("interrupt-ui");
|
|
179
|
+
expect(interrupt.textContent).toBe("Deploy?");
|
|
180
|
+
const lastMessage = screen.getByText("I need your approval first.");
|
|
181
|
+
expect(
|
|
182
|
+
lastMessage.compareDocumentPosition(interrupt) &
|
|
183
|
+
Node.DOCUMENT_POSITION_FOLLOWING,
|
|
184
|
+
).toBeTruthy();
|
|
185
|
+
|
|
186
|
+
await act(async () => {
|
|
187
|
+
fireEvent.click(interrupt);
|
|
188
|
+
});
|
|
189
|
+
await waitFor(() => expect(inputs).toHaveLength(2));
|
|
190
|
+
expect(inputs[1]!.resume).toEqual([
|
|
191
|
+
{
|
|
192
|
+
interruptId: "approve",
|
|
193
|
+
status: "resolved",
|
|
194
|
+
payload: { approved: true },
|
|
195
|
+
},
|
|
196
|
+
]);
|
|
197
|
+
await waitFor(() =>
|
|
198
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull(),
|
|
199
|
+
);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it("removes the useInterrupt element when its component unmounts", async () => {
|
|
203
|
+
const { agent, coreRef, rerender } = await renderInterruptedChat();
|
|
204
|
+
|
|
205
|
+
rerender(<Chat agent={agent} coreRef={coreRef} withApproval={false} />);
|
|
206
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
207
|
+
});
|
|
208
|
+
});
|
|
@@ -14,7 +14,7 @@ vi.mock("react-native", () => ({
|
|
|
14
14
|
// Capture the props handed to the underlying streaming renderer so we can
|
|
15
15
|
// assert how CopilotMarkdown translates its public style map.
|
|
16
16
|
const capturedProps: any[] = [];
|
|
17
|
-
vi.mock("@copilotkit/markdown
|
|
17
|
+
vi.mock("@copilotkit/markdown/react-native", () => ({
|
|
18
18
|
StreamingMarkdownRenderer: (props: any) => {
|
|
19
19
|
capturedProps.push(props);
|
|
20
20
|
return null;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import { View, Text, StyleSheet
|
|
2
|
+
import { View, Text, StyleSheet } from "react-native";
|
|
3
|
+
import type { ViewStyle } from "react-native";
|
|
3
4
|
import { CopilotMarkdown } from "../Markdown";
|
|
4
5
|
import {
|
|
5
6
|
useMarkdownRenderer,
|
|
@@ -10,7 +11,6 @@ import { formatTimestamp } from "./utils";
|
|
|
10
11
|
|
|
11
12
|
// ─── Colors ──────────────────────────────────────────────────────────────────
|
|
12
13
|
const ASSISTANT_BUBBLE_BG = "#F0F0F0";
|
|
13
|
-
const ASSISTANT_TEXT_COLOR = "#1A1A1A";
|
|
14
14
|
const TIMESTAMP_COLOR = "#999999";
|
|
15
15
|
|
|
16
16
|
/**
|
|
@@ -19,7 +19,7 @@ const TIMESTAMP_COLOR = "#999999";
|
|
|
19
19
|
export interface AssistantMessageProps {
|
|
20
20
|
/** Markdown content to render inside the bubble */
|
|
21
21
|
content: string;
|
|
22
|
-
/** When true, shows a typing indicator
|
|
22
|
+
/** When true, shows a typing indicator below any content */
|
|
23
23
|
isLoading?: boolean;
|
|
24
24
|
/** Optional timestamp displayed below the bubble */
|
|
25
25
|
timestamp?: Date;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { useEffect,
|
|
1
|
+
import React, { useEffect, useState } from "react";
|
|
2
2
|
import { View, Animated, StyleSheet } from "react-native";
|
|
3
3
|
import type { ViewStyle } from "react-native";
|
|
4
4
|
|
|
@@ -21,9 +21,9 @@ const ANIMATION_DURATION = 400;
|
|
|
21
21
|
* Uses React Native's built-in `Animated` API (no Reanimated dependency).
|
|
22
22
|
*/
|
|
23
23
|
export function TypingIndicator({ style }: TypingIndicatorProps) {
|
|
24
|
-
const dot1 =
|
|
25
|
-
const dot2 =
|
|
26
|
-
const dot3 =
|
|
24
|
+
const [dot1] = useState(() => new Animated.Value(0));
|
|
25
|
+
const [dot2] = useState(() => new Animated.Value(0));
|
|
26
|
+
const [dot3] = useState(() => new Animated.Value(0));
|
|
27
27
|
|
|
28
28
|
useEffect(() => {
|
|
29
29
|
const createPulse = (dot: Animated.Value, delay: number) =>
|
|
@@ -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
|
-
//
|
|
76
|
+
// Queue adapter
|
|
80
77
|
// ---------------------------------------------------------------------------
|
|
81
78
|
|
|
82
|
-
|
|
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
|
|
154
|
+
* and lifecycle. All returned callbacks are referentially stable.
|
|
91
155
|
*
|
|
92
|
-
*
|
|
93
|
-
* `@copilotkit/
|
|
94
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
(
|
|
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
|
-
|
|
134
|
-
|
|
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
|
|
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
|
|
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(
|
|
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(
|
|
256
|
-
|
|
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,
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { Utf8TextDecoder, Utf8TextEncoder } from "../utf8";
|
|
3
|
+
|
|
4
|
+
// Node's built-in classes are the reference: the polyfill must give the same
|
|
5
|
+
// output on the runtimes that lack them.
|
|
6
|
+
const NativeEncoder = globalThis.TextEncoder;
|
|
7
|
+
const NativeDecoder = globalThis.TextDecoder;
|
|
8
|
+
|
|
9
|
+
const strings = [
|
|
10
|
+
"",
|
|
11
|
+
"hello",
|
|
12
|
+
"Grüße, 東京, emoji 🚀🧪",
|
|
13
|
+
"\u0000\u007f\u0080߿ࠀ",
|
|
14
|
+
"🚀 pair, \ud800 lone high, \udc00 lone low",
|
|
15
|
+
"starts with a BOM",
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
const byteSequences: number[][] = [
|
|
19
|
+
[0xe2, 0x82, 0xac],
|
|
20
|
+
[0xc3],
|
|
21
|
+
[0xc0, 0x80],
|
|
22
|
+
[0xed, 0xa0, 0x80],
|
|
23
|
+
[0xf4, 0x90, 0x80, 0x80],
|
|
24
|
+
[0xf0, 0x9f, 0x9a],
|
|
25
|
+
[0xe0, 0x80, 0x41],
|
|
26
|
+
[0x80, 0xbf, 0x41],
|
|
27
|
+
[0xff, 0xfe, 0x41],
|
|
28
|
+
[0xef, 0xbb, 0xbf, 0x41],
|
|
29
|
+
[0xf0, 0x9f, 0x98, 0x80, 0xe2, 0x82],
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
function splits(bytes: Uint8Array): Uint8Array[][] {
|
|
33
|
+
const out: Uint8Array[][] = [[bytes]];
|
|
34
|
+
for (let at = 0; at <= bytes.length; at++) {
|
|
35
|
+
out.push([bytes.subarray(0, at), bytes.subarray(at)]);
|
|
36
|
+
}
|
|
37
|
+
out.push([...bytes].map((byte) => new Uint8Array([byte])));
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function streamDecode(
|
|
42
|
+
decoder: {
|
|
43
|
+
decode: (input?: Uint8Array, options?: { stream?: boolean }) => string;
|
|
44
|
+
},
|
|
45
|
+
chunks: Uint8Array[],
|
|
46
|
+
): string {
|
|
47
|
+
return (
|
|
48
|
+
chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join("") +
|
|
49
|
+
decoder.decode()
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe("Utf8TextEncoder", () => {
|
|
54
|
+
it.each(strings)("encodes %j like the built-in encoder", (input) => {
|
|
55
|
+
expect([...new Utf8TextEncoder().encode(input)]).toEqual([
|
|
56
|
+
...new NativeEncoder().encode(input),
|
|
57
|
+
]);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("Utf8TextDecoder", () => {
|
|
62
|
+
const inputs = [
|
|
63
|
+
...strings.map((input) => new NativeEncoder().encode(input)),
|
|
64
|
+
...byteSequences.map((bytes) => new Uint8Array(bytes)),
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
it.each(inputs.map((bytes) => [[...bytes].join(","), bytes] as const))(
|
|
68
|
+
"decodes [%s] like the built-in decoder, in every chunk split",
|
|
69
|
+
(_, bytes) => {
|
|
70
|
+
for (const chunks of splits(bytes)) {
|
|
71
|
+
for (const ignoreBOM of [false, true]) {
|
|
72
|
+
expect(
|
|
73
|
+
streamDecode(new Utf8TextDecoder("utf-8", { ignoreBOM }), chunks),
|
|
74
|
+
).toBe(
|
|
75
|
+
streamDecode(new NativeDecoder("utf-8", { ignoreBOM }), chunks),
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
it("throws on invalid bytes when fatal is set", () => {
|
|
83
|
+
for (const bytes of byteSequences.map((b) => new Uint8Array(b))) {
|
|
84
|
+
const native = () =>
|
|
85
|
+
new NativeDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
86
|
+
const polyfill = () =>
|
|
87
|
+
new Utf8TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
88
|
+
let nativeThrew = false;
|
|
89
|
+
try {
|
|
90
|
+
native();
|
|
91
|
+
} catch {
|
|
92
|
+
nativeThrew = true;
|
|
93
|
+
}
|
|
94
|
+
if (nativeThrew) expect(polyfill).toThrow(TypeError);
|
|
95
|
+
else expect(polyfill()).toBe(native());
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("decodes an ArrayBuffer and a view into a larger buffer", () => {
|
|
100
|
+
const buffer = new NativeEncoder().encode("xx東京xx").buffer;
|
|
101
|
+
expect(new Utf8TextDecoder().decode(buffer)).toBe("xx東京xx");
|
|
102
|
+
expect(new Utf8TextDecoder().decode(new Uint8Array(buffer, 2, 6))).toBe(
|
|
103
|
+
"東京",
|
|
104
|
+
);
|
|
105
|
+
expect(new Utf8TextDecoder().decode()).toBe("");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("supports only UTF-8", () => {
|
|
109
|
+
expect(new Utf8TextDecoder("UTF8").encoding).toBe("utf-8");
|
|
110
|
+
expect(() => new Utf8TextDecoder("latin1")).toThrow(RangeError);
|
|
111
|
+
});
|
|
112
|
+
});
|
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Polyfill: TextEncoder, TextDecoder
|
|
3
3
|
*
|
|
4
|
-
* Required for stream chunk processing in CopilotKit.
|
|
4
|
+
* Required for stream chunk processing in CopilotKit. The polyfill supports
|
|
5
|
+
* UTF-8, the only encoding that CopilotKit uses.
|
|
5
6
|
* Skipped if the globals are already defined.
|
|
6
7
|
*
|
|
7
8
|
* Usage:
|
|
8
9
|
* import "@copilotkit/react-native/polyfills/encoding";
|
|
9
10
|
*/
|
|
10
11
|
|
|
11
|
-
import {
|
|
12
|
+
import { Utf8TextDecoder, Utf8TextEncoder } from "./utf8";
|
|
12
13
|
|
|
13
14
|
const g = globalThis as Record<string, unknown>;
|
|
14
15
|
|
|
15
16
|
if (typeof g.TextEncoder === "undefined") {
|
|
16
|
-
g.TextEncoder =
|
|
17
|
+
g.TextEncoder = Utf8TextEncoder;
|
|
17
18
|
}
|
|
18
19
|
if (typeof g.TextDecoder === "undefined") {
|
|
19
|
-
g.TextDecoder =
|
|
20
|
+
g.TextDecoder = Utf8TextDecoder;
|
|
20
21
|
}
|