@@ -24,6 +24,7 @@ interface UsePipeOptions {
24
24
}
25
25
26
26
const uuidSchema = z . string ( ) . uuid ( ) ;
27
+ const externalThreadIdSchema = uuidSchema . optional ( ) ;
27
28
28
29
export function usePipe ( {
29
30
apiRoute = '/langbase/pipes/run-stream' ,
@@ -41,7 +42,9 @@ export function usePipe({
41
42
const [ error , setError ] = useState < Error | null > ( null ) ;
42
43
43
44
const abortControllerRef = useRef < AbortController | null > ( null ) ;
44
- const threadIdRef = useRef < string | null > ( initialThreadId || null ) ;
45
+ const threadIdRef = useRef < string | undefined > (
46
+ initialThreadId || undefined ,
47
+ ) ;
45
48
const messagesRef = useRef < Message [ ] > ( initialMessages ) ;
46
49
const isFirstRequestRef = useRef < boolean > ( true ) ;
47
50
@@ -87,6 +90,17 @@ export function usePipe({
87
90
[ updateMessages , onResponse , onFinish ] ,
88
91
) ;
89
92
93
+ const setThreadId = useCallback ( ( newThreadId : string | undefined ) => {
94
+ const isValidThreadId =
95
+ externalThreadIdSchema . safeParse ( newThreadId ) . success ;
96
+
97
+ if ( isValidThreadId ) {
98
+ threadIdRef . current = newThreadId ;
99
+ } else {
100
+ throw new Error ( 'Invalid thread ID' ) ;
101
+ }
102
+ } , [ ] ) ;
103
+
90
104
const getMessagesToSend = useCallback (
91
105
( updatedMessages : Message [ ] ) : [ Message [ ] , boolean ] => {
92
106
const isInitialRequest = isFirstRequestRef . current ;
@@ -264,6 +278,7 @@ export function usePipe({
264
278
threadId : threadIdRef . current ,
265
279
sendMessage,
266
280
setInput,
281
+ setThreadId,
267
282
} ) ,
268
283
[
269
284
messages ,
0 commit comments