xonecas.io
53129
Pa

PAT / files

PAT / src / hooks / api / useNewThreadMessage.ts

1.7 KB
1"use client";
2
3import { useMutation, useQueryClient } from "@tanstack/react-query";
4
5type StreamedMessage = {
6  role: string;
7  content: string;
8  thinking?: string;
9};
10
11export function useNewThreadMessage(
12  threadId: number | null,
13  message: string,
14  onMessageChunk?: (msg: StreamedMessage) => void,
15  onSuccess?: () => void
16) {
17  const queryClient = useQueryClient();
18
19  return useMutation<void, Error>({
20    mutationFn: async () => {
21      if (!threadId) {
22        throw new Error("Thread ID is required");
23      }
24
25      const response = await fetch(`/api/threads/${threadId}/messages`, {
26        method: "POST",
27        body: JSON.stringify({ message }),
28      });
29
30      if (!response.ok || !response.body) {
31        throw new Error(`Failed to create message: ${response.statusText}`);
32      }
33
34      const reader = response.body.getReader();
35      const decoder = new TextDecoder("utf-8");
36      let accumulated = "";
37
38      while (true) {
39        const { done, value } = await reader.read();
40        if (done) {
41          break;
42        }
43        accumulated += decoder.decode(value, { stream: true });
44
45        // Split stream into lines
46        const lines = accumulated.split("\n\n");
47        accumulated = lines.pop() || "";
48
49        for (const line of lines) {
50          if (line.startsWith("data: ")) {
51            try {
52              const json = JSON.parse(line.replace(/^data: /, ""));
53              onMessageChunk?.(json as StreamedMessage);
54            } catch {
55              // ignore JSON parse errors for invalid chunks
56            }
57          }
58        }
59      }
60    },
61    onSuccess: () => {
62      if (!threadId) {
63        return;
64      }
65      queryClient.invalidateQueries({ queryKey: ["threadMessages", threadId] });
66      onSuccess?.();
67    },
68  });
69}