@ai-sdk/react 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +4 -0
- package/.turbo/turbo-build.log +21 -0
- package/.turbo/turbo-clean.log +4 -0
- package/CHANGELOG.md +9 -0
- package/LICENSE +13 -0
- package/README.md +7 -0
- package/dist/index.d.mts +189 -0
- package/dist/index.d.ts +189 -0
- package/dist/index.js +684 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +653 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +74 -0
- package/src/index.ts +3 -0
- package/src/use-assistant.ts +279 -0
- package/src/use-assistant.ui.test.tsx +132 -0
- package/src/use-chat.ts +572 -0
- package/src/use-chat.ui.test.tsx +209 -0
- package/src/use-completion.ts +203 -0
- package/src/use-completion.ui.test.tsx +142 -0
- package/tsconfig.json +9 -0
- package/tsup.config.ts +13 -0
- package/turbo.json +8 -0
- package/vitest.config.js +12 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mockFetchDataStream,
|
|
3
|
+
mockFetchDataStreamWithGenerator,
|
|
4
|
+
mockFetchError,
|
|
5
|
+
} from '@ai-sdk/ui-utils/test';
|
|
6
|
+
import '@testing-library/jest-dom/vitest';
|
|
7
|
+
import { cleanup, findByText, render, screen } from '@testing-library/react';
|
|
8
|
+
import userEvent from '@testing-library/user-event';
|
|
9
|
+
import React from 'react';
|
|
10
|
+
import { useChat } from './use-chat';
|
|
11
|
+
|
|
12
|
+
describe('stream data stream', () => {
|
|
13
|
+
const TestComponent = () => {
|
|
14
|
+
const [id, setId] = React.useState<string>('first-id');
|
|
15
|
+
const { messages, append, error, data, isLoading } = useChat({ id });
|
|
16
|
+
|
|
17
|
+
return (
|
|
18
|
+
<div>
|
|
19
|
+
<div data-testid="loading">{isLoading.toString()}</div>
|
|
20
|
+
{error && <div data-testid="error">{error.toString()}</div>}
|
|
21
|
+
{data && <div data-testid="data">{JSON.stringify(data)}</div>}
|
|
22
|
+
{messages.map((m, idx) => (
|
|
23
|
+
<div data-testid={`message-${idx}`} key={m.id}>
|
|
24
|
+
{m.role === 'user' ? 'User: ' : 'AI: '}
|
|
25
|
+
{m.content}
|
|
26
|
+
</div>
|
|
27
|
+
))}
|
|
28
|
+
|
|
29
|
+
<button
|
|
30
|
+
data-testid="do-append"
|
|
31
|
+
onClick={() => {
|
|
32
|
+
append({ role: 'user', content: 'hi' });
|
|
33
|
+
}}
|
|
34
|
+
/>
|
|
35
|
+
<button
|
|
36
|
+
data-testid="do-change-id"
|
|
37
|
+
onClick={() => {
|
|
38
|
+
setId('second-id');
|
|
39
|
+
}}
|
|
40
|
+
/>
|
|
41
|
+
</div>
|
|
42
|
+
);
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
beforeEach(() => {
|
|
46
|
+
render(<TestComponent />);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
afterEach(() => {
|
|
50
|
+
vi.restoreAllMocks();
|
|
51
|
+
cleanup();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('should show streamed response', async () => {
|
|
55
|
+
mockFetchDataStream({
|
|
56
|
+
url: 'https://example.com/api/chat',
|
|
57
|
+
chunks: ['0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n'],
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
await userEvent.click(screen.getByTestId('do-append'));
|
|
61
|
+
|
|
62
|
+
await screen.findByTestId('message-0');
|
|
63
|
+
expect(screen.getByTestId('message-0')).toHaveTextContent('User: hi');
|
|
64
|
+
|
|
65
|
+
await screen.findByTestId('message-1');
|
|
66
|
+
expect(screen.getByTestId('message-1')).toHaveTextContent(
|
|
67
|
+
'AI: Hello, world.',
|
|
68
|
+
);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('should show streamed response with data', async () => {
|
|
72
|
+
mockFetchDataStream({
|
|
73
|
+
url: 'https://example.com/api/chat',
|
|
74
|
+
chunks: ['2:[{"t1":"v1"}]\n', '0:"Hello"\n'],
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
await userEvent.click(screen.getByTestId('do-append'));
|
|
78
|
+
|
|
79
|
+
await screen.findByTestId('data');
|
|
80
|
+
expect(screen.getByTestId('data')).toHaveTextContent('[{"t1":"v1"}]');
|
|
81
|
+
|
|
82
|
+
await screen.findByTestId('message-1');
|
|
83
|
+
expect(screen.getByTestId('message-1')).toHaveTextContent('AI: Hello');
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should show error response', async () => {
|
|
87
|
+
mockFetchError({ statusCode: 404, errorMessage: 'Not found' });
|
|
88
|
+
|
|
89
|
+
await userEvent.click(screen.getByTestId('do-append'));
|
|
90
|
+
|
|
91
|
+
// TODO bug? the user message does not show up
|
|
92
|
+
// await screen.findByTestId('message-0');
|
|
93
|
+
// expect(screen.getByTestId('message-0')).toHaveTextContent('User: hi');
|
|
94
|
+
|
|
95
|
+
await screen.findByTestId('error');
|
|
96
|
+
expect(screen.getByTestId('error')).toHaveTextContent('Error: Not found');
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
describe('loading state', () => {
|
|
100
|
+
it('should show loading state', async () => {
|
|
101
|
+
let finishGeneration: ((value?: unknown) => void) | undefined;
|
|
102
|
+
const finishGenerationPromise = new Promise(resolve => {
|
|
103
|
+
finishGeneration = resolve;
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
mockFetchDataStreamWithGenerator({
|
|
107
|
+
url: 'https://example.com/api/chat',
|
|
108
|
+
chunkGenerator: (async function* generate() {
|
|
109
|
+
const encoder = new TextEncoder();
|
|
110
|
+
yield encoder.encode('0:"Hello"\n');
|
|
111
|
+
await finishGenerationPromise;
|
|
112
|
+
})(),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
await userEvent.click(screen.getByTestId('do-append'));
|
|
116
|
+
|
|
117
|
+
await screen.findByTestId('loading');
|
|
118
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('true');
|
|
119
|
+
|
|
120
|
+
finishGeneration?.();
|
|
121
|
+
|
|
122
|
+
await findByText(await screen.findByTestId('loading'), 'false');
|
|
123
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('should reset loading state on error', async () => {
|
|
127
|
+
mockFetchError({ statusCode: 404, errorMessage: 'Not found' });
|
|
128
|
+
|
|
129
|
+
await userEvent.click(screen.getByTestId('do-append'));
|
|
130
|
+
|
|
131
|
+
await screen.findByTestId('loading');
|
|
132
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
describe('id', () => {
|
|
137
|
+
it('should clear out messages when the id changes', async () => {
|
|
138
|
+
mockFetchDataStream({
|
|
139
|
+
url: 'https://example.com/api/chat',
|
|
140
|
+
chunks: ['0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n'],
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
await userEvent.click(screen.getByTestId('do-append'));
|
|
144
|
+
|
|
145
|
+
await screen.findByTestId('message-1');
|
|
146
|
+
expect(screen.getByTestId('message-1')).toHaveTextContent(
|
|
147
|
+
'AI: Hello, world.',
|
|
148
|
+
);
|
|
149
|
+
|
|
150
|
+
await userEvent.click(screen.getByTestId('do-change-id'));
|
|
151
|
+
|
|
152
|
+
expect(screen.queryByTestId('message-0')).not.toBeInTheDocument();
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
describe('text stream', () => {
|
|
158
|
+
const TestComponent = () => {
|
|
159
|
+
const { messages, append } = useChat({
|
|
160
|
+
streamMode: 'text',
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
return (
|
|
164
|
+
<div>
|
|
165
|
+
{messages.map((m, idx) => (
|
|
166
|
+
<div data-testid={`message-${idx}-text-stream`} key={m.id}>
|
|
167
|
+
{m.role === 'user' ? 'User: ' : 'AI: '}
|
|
168
|
+
{m.content}
|
|
169
|
+
</div>
|
|
170
|
+
))}
|
|
171
|
+
|
|
172
|
+
<button
|
|
173
|
+
data-testid="do-append-text-stream"
|
|
174
|
+
onClick={() => {
|
|
175
|
+
append({ role: 'user', content: 'hi' });
|
|
176
|
+
}}
|
|
177
|
+
/>
|
|
178
|
+
</div>
|
|
179
|
+
);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
beforeEach(() => {
|
|
183
|
+
render(<TestComponent />);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
afterEach(() => {
|
|
187
|
+
vi.restoreAllMocks();
|
|
188
|
+
cleanup();
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it('should show streamed response', async () => {
|
|
192
|
+
mockFetchDataStream({
|
|
193
|
+
url: 'https://example.com/api/chat',
|
|
194
|
+
chunks: ['Hello', ',', ' world', '.'],
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
await userEvent.click(screen.getByTestId('do-append-text-stream'));
|
|
198
|
+
|
|
199
|
+
await screen.findByTestId('message-0-text-stream');
|
|
200
|
+
expect(screen.getByTestId('message-0-text-stream')).toHaveTextContent(
|
|
201
|
+
'User: hi',
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
await screen.findByTestId('message-1-text-stream');
|
|
205
|
+
expect(screen.getByTestId('message-1-text-stream')).toHaveTextContent(
|
|
206
|
+
'AI: Hello, world.',
|
|
207
|
+
);
|
|
208
|
+
});
|
|
209
|
+
});
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import {
|
|
2
|
+
JSONValue,
|
|
3
|
+
RequestOptions,
|
|
4
|
+
UseCompletionOptions,
|
|
5
|
+
callCompletionApi,
|
|
6
|
+
} from '@ai-sdk/ui-utils';
|
|
7
|
+
import { useCallback, useEffect, useId, useRef, useState } from 'react';
|
|
8
|
+
import useSWR from 'swr';
|
|
9
|
+
|
|
10
|
+
export type { UseCompletionOptions };
|
|
11
|
+
|
|
12
|
+
export type UseCompletionHelpers = {
|
|
13
|
+
/** The current completion result */
|
|
14
|
+
completion: string;
|
|
15
|
+
/**
|
|
16
|
+
* Send a new prompt to the API endpoint and update the completion state.
|
|
17
|
+
*/
|
|
18
|
+
complete: (
|
|
19
|
+
prompt: string,
|
|
20
|
+
options?: RequestOptions,
|
|
21
|
+
) => Promise<string | null | undefined>;
|
|
22
|
+
/** The error object of the API request */
|
|
23
|
+
error: undefined | Error;
|
|
24
|
+
/**
|
|
25
|
+
* Abort the current API request but keep the generated tokens.
|
|
26
|
+
*/
|
|
27
|
+
stop: () => void;
|
|
28
|
+
/**
|
|
29
|
+
* Update the `completion` state locally.
|
|
30
|
+
*/
|
|
31
|
+
setCompletion: (completion: string) => void;
|
|
32
|
+
/** The current value of the input */
|
|
33
|
+
input: string;
|
|
34
|
+
/** setState-powered method to update the input value */
|
|
35
|
+
setInput: React.Dispatch<React.SetStateAction<string>>;
|
|
36
|
+
/**
|
|
37
|
+
* An input/textarea-ready onChange handler to control the value of the input
|
|
38
|
+
* @example
|
|
39
|
+
* ```jsx
|
|
40
|
+
* <input onChange={handleInputChange} value={input} />
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
handleInputChange: (
|
|
44
|
+
e:
|
|
45
|
+
| React.ChangeEvent<HTMLInputElement>
|
|
46
|
+
| React.ChangeEvent<HTMLTextAreaElement>,
|
|
47
|
+
) => void;
|
|
48
|
+
/**
|
|
49
|
+
* Form submission handler to automatically reset input and append a user message
|
|
50
|
+
* @example
|
|
51
|
+
* ```jsx
|
|
52
|
+
* <form onSubmit={handleSubmit}>
|
|
53
|
+
* <input onChange={handleInputChange} value={input} />
|
|
54
|
+
* </form>
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
|
|
58
|
+
/** Whether the API request is in progress */
|
|
59
|
+
isLoading: boolean;
|
|
60
|
+
/** Additional data added on the server via StreamData */
|
|
61
|
+
data?: JSONValue[];
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export function useCompletion({
|
|
65
|
+
api = '/api/completion',
|
|
66
|
+
id,
|
|
67
|
+
initialCompletion = '',
|
|
68
|
+
initialInput = '',
|
|
69
|
+
credentials,
|
|
70
|
+
headers,
|
|
71
|
+
body,
|
|
72
|
+
streamMode,
|
|
73
|
+
onResponse,
|
|
74
|
+
onFinish,
|
|
75
|
+
onError,
|
|
76
|
+
}: UseCompletionOptions = {}): UseCompletionHelpers {
|
|
77
|
+
// Generate an unique id for the completion if not provided.
|
|
78
|
+
const hookId = useId();
|
|
79
|
+
const completionId = id || hookId;
|
|
80
|
+
|
|
81
|
+
// Store the completion state in SWR, using the completionId as the key to share states.
|
|
82
|
+
const { data, mutate } = useSWR<string>([api, completionId], null, {
|
|
83
|
+
fallbackData: initialCompletion,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(
|
|
87
|
+
[completionId, 'loading'],
|
|
88
|
+
null,
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
const { data: streamData, mutate: mutateStreamData } = useSWR<
|
|
92
|
+
JSONValue[] | undefined
|
|
93
|
+
>([completionId, 'streamData'], null);
|
|
94
|
+
|
|
95
|
+
const [error, setError] = useState<undefined | Error>(undefined);
|
|
96
|
+
const completion = data!;
|
|
97
|
+
|
|
98
|
+
// Abort controller to cancel the current API call.
|
|
99
|
+
const [abortController, setAbortController] =
|
|
100
|
+
useState<AbortController | null>(null);
|
|
101
|
+
|
|
102
|
+
const extraMetadataRef = useRef({
|
|
103
|
+
credentials,
|
|
104
|
+
headers,
|
|
105
|
+
body,
|
|
106
|
+
});
|
|
107
|
+
useEffect(() => {
|
|
108
|
+
extraMetadataRef.current = {
|
|
109
|
+
credentials,
|
|
110
|
+
headers,
|
|
111
|
+
body,
|
|
112
|
+
};
|
|
113
|
+
}, [credentials, headers, body]);
|
|
114
|
+
|
|
115
|
+
const triggerRequest = useCallback(
|
|
116
|
+
async (prompt: string, options?: RequestOptions) =>
|
|
117
|
+
callCompletionApi({
|
|
118
|
+
api,
|
|
119
|
+
prompt,
|
|
120
|
+
credentials: extraMetadataRef.current.credentials,
|
|
121
|
+
headers: { ...extraMetadataRef.current.headers, ...options?.headers },
|
|
122
|
+
body: {
|
|
123
|
+
...extraMetadataRef.current.body,
|
|
124
|
+
...options?.body,
|
|
125
|
+
},
|
|
126
|
+
streamMode,
|
|
127
|
+
setCompletion: completion => mutate(completion, false),
|
|
128
|
+
setLoading: mutateLoading,
|
|
129
|
+
setError,
|
|
130
|
+
setAbortController,
|
|
131
|
+
onResponse,
|
|
132
|
+
onFinish,
|
|
133
|
+
onError,
|
|
134
|
+
onData: data => {
|
|
135
|
+
mutateStreamData([...(streamData || []), ...(data || [])], false);
|
|
136
|
+
},
|
|
137
|
+
}),
|
|
138
|
+
[
|
|
139
|
+
mutate,
|
|
140
|
+
mutateLoading,
|
|
141
|
+
api,
|
|
142
|
+
extraMetadataRef,
|
|
143
|
+
setAbortController,
|
|
144
|
+
onResponse,
|
|
145
|
+
onFinish,
|
|
146
|
+
onError,
|
|
147
|
+
setError,
|
|
148
|
+
streamData,
|
|
149
|
+
streamMode,
|
|
150
|
+
mutateStreamData,
|
|
151
|
+
],
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
const stop = useCallback(() => {
|
|
155
|
+
if (abortController) {
|
|
156
|
+
abortController.abort();
|
|
157
|
+
setAbortController(null);
|
|
158
|
+
}
|
|
159
|
+
}, [abortController]);
|
|
160
|
+
|
|
161
|
+
const setCompletion = useCallback(
|
|
162
|
+
(completion: string) => {
|
|
163
|
+
mutate(completion, false);
|
|
164
|
+
},
|
|
165
|
+
[mutate],
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
const complete = useCallback<UseCompletionHelpers['complete']>(
|
|
169
|
+
async (prompt, options) => {
|
|
170
|
+
return triggerRequest(prompt, options);
|
|
171
|
+
},
|
|
172
|
+
[triggerRequest],
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
const [input, setInput] = useState(initialInput);
|
|
176
|
+
|
|
177
|
+
const handleSubmit = useCallback(
|
|
178
|
+
(e: React.FormEvent<HTMLFormElement>) => {
|
|
179
|
+
e.preventDefault();
|
|
180
|
+
if (!input) return;
|
|
181
|
+
return complete(input);
|
|
182
|
+
},
|
|
183
|
+
[input, complete],
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
const handleInputChange = (e: any) => {
|
|
187
|
+
setInput(e.target.value);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
completion,
|
|
192
|
+
complete,
|
|
193
|
+
error,
|
|
194
|
+
setCompletion,
|
|
195
|
+
stop,
|
|
196
|
+
input,
|
|
197
|
+
setInput,
|
|
198
|
+
handleInputChange,
|
|
199
|
+
handleSubmit,
|
|
200
|
+
isLoading,
|
|
201
|
+
data: streamData,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mockFetchDataStream,
|
|
3
|
+
mockFetchDataStreamWithGenerator,
|
|
4
|
+
mockFetchError,
|
|
5
|
+
} from '@ai-sdk/ui-utils/test';
|
|
6
|
+
import '@testing-library/jest-dom/vitest';
|
|
7
|
+
import { cleanup, findByText, render, screen } from '@testing-library/react';
|
|
8
|
+
import userEvent from '@testing-library/user-event';
|
|
9
|
+
import { useCompletion } from './use-completion';
|
|
10
|
+
|
|
11
|
+
describe('stream data stream', () => {
|
|
12
|
+
const TestComponent = () => {
|
|
13
|
+
const {
|
|
14
|
+
completion,
|
|
15
|
+
handleSubmit,
|
|
16
|
+
error,
|
|
17
|
+
handleInputChange,
|
|
18
|
+
input,
|
|
19
|
+
isLoading,
|
|
20
|
+
} = useCompletion();
|
|
21
|
+
|
|
22
|
+
return (
|
|
23
|
+
<div>
|
|
24
|
+
<div data-testid="loading">{isLoading.toString()}</div>
|
|
25
|
+
<div data-testid="error">{error?.toString()}</div>
|
|
26
|
+
<div data-testid="completion">{completion}</div>
|
|
27
|
+
<form onSubmit={handleSubmit}>
|
|
28
|
+
<input
|
|
29
|
+
data-testid="input"
|
|
30
|
+
value={input}
|
|
31
|
+
placeholder="Say something..."
|
|
32
|
+
onChange={handleInputChange}
|
|
33
|
+
/>
|
|
34
|
+
</form>
|
|
35
|
+
</div>
|
|
36
|
+
);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
render(<TestComponent />);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
vi.restoreAllMocks();
|
|
45
|
+
cleanup();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('should render stream', async () => {
|
|
49
|
+
mockFetchDataStream({
|
|
50
|
+
url: 'https://example.com/api/completion',
|
|
51
|
+
chunks: ['0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n'],
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
|
|
55
|
+
|
|
56
|
+
await screen.findByTestId('completion');
|
|
57
|
+
expect(screen.getByTestId('completion')).toHaveTextContent('Hello, world.');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe('loading state', () => {
|
|
61
|
+
it('should show loading state', async () => {
|
|
62
|
+
let finishGeneration: ((value?: unknown) => void) | undefined;
|
|
63
|
+
const finishGenerationPromise = new Promise(resolve => {
|
|
64
|
+
finishGeneration = resolve;
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
mockFetchDataStreamWithGenerator({
|
|
68
|
+
url: 'https://example.com/api/chat',
|
|
69
|
+
chunkGenerator: (async function* generate() {
|
|
70
|
+
const encoder = new TextEncoder();
|
|
71
|
+
yield encoder.encode('0:"Hello"\n');
|
|
72
|
+
await finishGenerationPromise;
|
|
73
|
+
})(),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
|
|
77
|
+
|
|
78
|
+
await screen.findByTestId('loading');
|
|
79
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('true');
|
|
80
|
+
|
|
81
|
+
finishGeneration?.();
|
|
82
|
+
|
|
83
|
+
await findByText(await screen.findByTestId('loading'), 'false');
|
|
84
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('should reset loading state on error', async () => {
|
|
88
|
+
mockFetchError({ statusCode: 404, errorMessage: 'Not found' });
|
|
89
|
+
|
|
90
|
+
await userEvent.type(screen.getByTestId('input'), 'hi{enter}');
|
|
91
|
+
|
|
92
|
+
await screen.findByTestId('loading');
|
|
93
|
+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe('text stream', () => {
|
|
99
|
+
const TestComponent = () => {
|
|
100
|
+
const { completion, handleSubmit, handleInputChange, input } =
|
|
101
|
+
useCompletion({
|
|
102
|
+
streamMode: 'text',
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
return (
|
|
106
|
+
<div>
|
|
107
|
+
<div data-testid="completion-text-stream">{completion}</div>
|
|
108
|
+
<form onSubmit={handleSubmit}>
|
|
109
|
+
<input
|
|
110
|
+
data-testid="input-text-stream"
|
|
111
|
+
value={input}
|
|
112
|
+
placeholder="Say something..."
|
|
113
|
+
onChange={handleInputChange}
|
|
114
|
+
/>
|
|
115
|
+
</form>
|
|
116
|
+
</div>
|
|
117
|
+
);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
beforeEach(() => {
|
|
121
|
+
render(<TestComponent />);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
afterEach(() => {
|
|
125
|
+
vi.restoreAllMocks();
|
|
126
|
+
cleanup();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('should render stream', async () => {
|
|
130
|
+
mockFetchDataStream({
|
|
131
|
+
url: 'https://example.com/api/completion',
|
|
132
|
+
chunks: ['Hello', ',', ' world', '.'],
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
await userEvent.type(screen.getByTestId('input-text-stream'), 'hi{enter}');
|
|
136
|
+
|
|
137
|
+
await screen.findByTestId('completion-text-stream');
|
|
138
|
+
expect(screen.getByTestId('completion-text-stream')).toHaveTextContent(
|
|
139
|
+
'Hello, world.',
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
});
|
package/tsconfig.json
ADDED
package/tsup.config.ts
ADDED
package/turbo.json
ADDED
package/vitest.config.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import react from '@vitejs/plugin-react';
|
|
2
|
+
import { defineConfig } from 'vite';
|
|
3
|
+
|
|
4
|
+
// https://vitejs.dev/config/
|
|
5
|
+
export default defineConfig({
|
|
6
|
+
plugins: [react()],
|
|
7
|
+
test: {
|
|
8
|
+
environment: 'jsdom',
|
|
9
|
+
globals: true,
|
|
10
|
+
include: ['src/**/*.ui.test.ts', 'src/**/*.ui.test.tsx'],
|
|
11
|
+
},
|
|
12
|
+
});
|