forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads-context.tsx
More file actions
69 lines (60 loc) · 1.75 KB
/
Copy paththreads-context.tsx
File metadata and controls
69 lines (60 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import React, {
createContext,
useCallback,
useContext,
useState,
ReactNode,
SetStateAction,
} from "react";
import { randomUUID } from "@copilotkit/shared";
export interface ThreadsContextValue {
threadId: string;
setThreadId: (value: SetStateAction<string>) => void;
// True when the current threadId was chosen by the caller — either via
// the `threadId` prop on <CopilotKit> / <ThreadsProvider>, or via a later
// setThreadId() call. False when the provider minted a UUID on first
// mount so downstream consumers don't have to treat that placeholder as
// a real backend thread.
isThreadIdExplicit: boolean;
}
const ThreadsContext = createContext<ThreadsContextValue | undefined>(
undefined,
);
export interface ThreadsProviderProps {
children: ReactNode;
threadId?: string;
}
export function ThreadsProvider({
children,
threadId: explicitThreadId,
}: ThreadsProviderProps) {
const [internalThreadId, setInternalThreadId] = useState<string>(() =>
randomUUID(),
);
const [internalIsExplicit, setInternalIsExplicit] = useState<boolean>(false);
const threadId = explicitThreadId ?? internalThreadId;
const isThreadIdExplicit = explicitThreadId != null || internalIsExplicit;
const setThreadId = useCallback((value: SetStateAction<string>) => {
setInternalThreadId(value);
setInternalIsExplicit(true);
}, []);
return (
<ThreadsContext.Provider
value={{
threadId,
setThreadId,
isThreadIdExplicit,
}}
>
{children}
</ThreadsContext.Provider>
);
}
export function useThreads() {
const context = useContext(ThreadsContext);
if (!context) {
throw new Error("useThreads must be used within ThreadsProvider");
}
return context;
}
export { ThreadsContext };