File size: 6,546 Bytes
249a397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08ce316
 
 
249a397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08ce316
 
 
 
 
 
 
 
249a397
 
 
 
 
 
 
 
 
08ce316
 
 
 
 
 
 
 
 
249a397
 
 
 
 
 
08ce316
 
 
 
 
 
249a397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e89912
249a397
 
 
 
8da73c0
 
 
 
 
 
 
 
249a397
08ce316
 
 
249a397
 
08ce316
 
 
 
 
 
 
 
 
 
249a397
 
 
 
 
08ce316
249a397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08ce316
 
249a397
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// src/useChat.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import type { ThreadMeta } from "./threads";
import {
  loadThreads,
  newThreadMeta,
  upsertThread,
  removeThread,
} from "./threads";
import type { ChatMessage } from "./messages";
import { loadMessages, saveMessages, clearMessages } from "./messages";

export function useChat() {
  const [threads, setThreads] = useState<ThreadMeta[]>(() => loadThreads());
  const [active, setActive] = useState<ThreadMeta>(
    () => threads[0] ?? newThreadMeta()
  );
  const [messagesByThread, setMessagesByThread] = useState<
    Record<string, ChatMessage[]>
  >({});
  const [isStreaming, setIsStreaming] = useState(false);
  const [hasFirstToken, setHasFirstToken] = useState(false); // NEW
  const firstTokenSeenRef = useRef(false);
  const esRef = useRef<EventSource | null>(null);

  // Load messages whenever the active thread changes (covers initial mount too)
  useEffect(() => {
    if (!active?.id) return;
    setMessagesByThread((prev) => ({
      ...prev,
      [active.id]: loadMessages(active.id),
    }));
  }, [active?.id]);

  // Close SSE on unmount
  useEffect(() => {
    return () => {
      if (esRef.current) {
        esRef.current.close();
        esRef.current = null;
      }
    };
  }, []);

  const setActiveThread = useCallback((t: ThreadMeta) => {
    setActive(t);
    upsertThread({ ...t, lastAt: new Date().toISOString() });
    setThreads(loadThreads());
  }, []);

  const newChat = useCallback(() => {
    const t = newThreadMeta();
    setActive(t);
    upsertThread(t);
    setThreads(loadThreads());
  }, []);

  const clearChat = useCallback(() => {
    if (!active?.id) return;
    setMessagesByThread((prev) => ({ ...prev, [active.id]: [] }));
    clearMessages(active.id);
  }, [active?.id]);

  const deleteThread = useCallback(
    (tid: string) => {
      if (esRef.current) {
        esRef.current.close();
        esRef.current = null;
      }
      setMessagesByThread((prev) => {
        const copy = { ...prev };
        delete copy[tid];
        return copy;
      });
      removeThread(tid);
      setThreads(loadThreads());

      if (active?.id === tid) {
        const list = loadThreads();
        if (list.length) setActive(list[0]);
        else {
          const t = newThreadMeta();
          setActive(t);
          upsertThread(t);
          setThreads(loadThreads());
        }
      }
    },
    [active?.id]
  );

  const persist = useCallback((tid: string, msgs: ChatMessage[]) => {
    saveMessages(tid, msgs);
  }, []);

  const appendMsg = useCallback(
    (tid: string, msg: ChatMessage) => {
      setMessagesByThread((prev) => {
        const arr = prev[tid] ?? [];
        const next = [...arr, msg];
        persist(tid, next);
        return { ...prev, [tid]: next };
      });
    },
    [persist]
  );

  // βœ… keep mutateLastAssistant as a useCallback
  const mutateLastAssistant = useCallback(
    (tid: string, chunk: string) => {
      setMessagesByThread((prev) => {
        const arr = (prev[tid] ?? []) as ChatMessage[]; // keep strict type
        if (arr.length === 0) return prev;

        const last = arr[arr.length - 1];
        let next: ChatMessage[];

        if (last.role === "assistant") {
          const merged: ChatMessage = {
            ...last,
            content: (last.content ?? "") + (chunk ?? ""),
          };
          next = [...arr.slice(0, -1), merged];
        } else {
          // πŸ‘ˆ important: literal role type to avoid widening to string
          next = [
            ...arr,
            {
              id: crypto.randomUUID(),
              role: "assistant" as const,
              content: chunk,
            },
          ];
        }

        persist(tid, next); // ChatMessage[]
        return { ...prev, [tid]: next }; // Record<string, ChatMessage[]>
      });
    },
    [persist]
  );

  // const makeMsg = (
  //   role: "user" | "assistant",
  //   content: string
  // ): ChatMessage => ({
  //   id: crypto.randomUUID(),
  //   role,
  //   content,
  // });

  const send = useCallback(
    (text: string) => {
      if (!active?.id) return;
      const thread_id = active.id;

      // optimistic UI
      appendMsg(thread_id, {
        id: crypto.randomUUID(),
        role: "user",
        content: text,
      });
      // appendMsg(thread_id, makeMsg("assistant", ""));

      // bump thread meta (derive title from first user msg if needed)
      const title =
        active.title && active.title !== "New chat"
          ? active.title
          : text.slice(0, 40);
      const bumped = { ...active, lastAt: new Date().toISOString(), title };
      setActive(bumped);
      upsertThread(bumped);
      setThreads(loadThreads());

      // Close any prior stream
      if (esRef.current) {
        esRef.current.close();
        esRef.current = null;
      }

      if (typeof window === "undefined") return; // SSR guard

      // Start SSE
      const url = new URL("api/chat", window.location.origin);
      url.searchParams.set("message", text);
      url.searchParams.set("thread_id", thread_id);

      const es = new EventSource(url.toString());
      es.addEventListener("tool", (ev: MessageEvent) => {
        try {
          const data = JSON.parse((ev as MessageEvent<string>).data || "{}");
          console.log("[TOOL]", data.phase, data.name);
        } catch {
          console.log("[TOOL]", (ev as MessageEvent<string>).data);
        }
      });
      esRef.current = es;
      setIsStreaming(true);
      setHasFirstToken(false);
      firstTokenSeenRef.current = false;

      es.addEventListener("token", (ev: MessageEvent) => {
        const data = (ev as MessageEvent<string>).data ?? "";
        const hasVisibleChars = data.trim().length > 0; // πŸ‘ˆ NEW

        // flip the flag only when the first *visible* token arrives
        if (!firstTokenSeenRef.current && hasVisibleChars) {
          firstTokenSeenRef.current = true;
          setHasFirstToken(true);
        }

        mutateLastAssistant(thread_id, data);
      });

      const close = () => {
        es.close();
        esRef.current = null;
        setIsStreaming(false);
      };

      es.addEventListener("done", close);
      es.onerror = close;
    },
    [active, appendMsg, mutateLastAssistant]
  );

  return {
    threads,
    active,
    messages: messagesByThread[active?.id ?? ""] ?? [],
    setActiveThread,
    newChat,
    clearChat,
    deleteThread,
    send,
    isStreaming,
    hasFirstToken,
  };
}