File size: 7,713 Bytes
a706099
 
63428e7
a706099
 
 
f444dc0
8066d07
63428e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a706099
 
 
 
98d2bd7
a706099
 
 
 
 
 
98d2bd7
a706099
 
 
f444dc0
 
 
63428e7
f444dc0
63428e7
f444dc0
 
 
 
 
 
63428e7
f444dc0
 
 
63428e7
 
 
 
 
 
 
f444dc0
63428e7
f444dc0
 
 
 
a706099
 
 
f444dc0
a706099
 
 
 
 
 
 
 
 
 
8d0b379
f444dc0
8d0b379
 
f444dc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63428e7
 
8d0b379
 
a706099
 
 
 
8d0b379
a706099
 
 
 
 
8d0b379
 
 
f444dc0
 
 
 
 
63428e7
 
a706099
 
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
import { useState } from 'react';

export const useChunkNavigation = (documentData) => {
    const [chunkStates, setChunkStates] = useState({});
    const [currentChunkIndex, setCurrentChunkIndex] = useState(0);
    const [chunkExpanded, setChunkExpanded] = useState(true);
    const [globalChatHistory, setGlobalChatHistory] = useState([]);
    const [showChat, setShowChat] = useState(true);
    const [loadingChunkIndex, setLoadingChunkIndex] = useState(null);

    const streamResponse = async (requestBody, isAutomated, nextChunkIndex) => {
        const targetChunkIndex = nextChunkIndex || currentChunkIndex;
        setLoadingChunkIndex(targetChunkIndex);

        try {
            const response = await fetch('/api/chat/stream', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: requestBody
            });
            
            const reader = await response.body.getReader()

            let shouldStop = false;
            const parsedBody = JSON.parse(requestBody);
            let localMessages = [...parsedBody.messages];
            
            const createTempId = () => `assistant_${Date.now()}_${Math.random().toString(36).slice(2)}`;
            let assistantId = null;

            // SSE read buffer
            let sseBuffer = '';

            // Streaming smoothness buffer
            let textBuffer = '';
            let frameScheduled = false;

            const flushBuffer = (isFinal = false) => {
                if (!assistantId) return;

                const lastMsg = localMessages[localMessages.length - 1];
                if (lastMsg.id === assistantId) {
                    // Append buffered text
                    lastMsg.content += textBuffer;
                    textBuffer = '';
                }
                updateGlobalChatHistory([...localMessages]);
            };

            const scheduleFlush = () => {
                if (!frameScheduled) {
                    frameScheduled = true;
                    requestAnimationFrame(() => {
                        flushBuffer();
                        frameScheduled = false;
                    });
                }
            };
            while (!shouldStop) {
                const { done, value } = await reader.read();
                if (done) break;

                sseBuffer += new TextDecoder().decode(value);
                const parts = sseBuffer.split('\n\n');
                sseBuffer = parts.pop(); // keep last partial

                for (const part of parts) {
                    if (!part.startsWith('data:')) continue;
                    const jsonStr = part.slice(5).trim();
                    if (!jsonStr) continue;

                    let parsed;
                    try {
                        parsed = JSON.parse(jsonStr);
                    } catch (err) {
                        console.warn('Could not JSON.parse stream chunk', jsonStr);
                        continue;
                    }

                    if (parsed.error) { 
                        console.error('streaming error', parsed.error); 
                        shouldStop = true; 
                        break; 
                    }
                    if (parsed.done) { 
                        shouldStop = true; 
                        flushBuffer(true); // final flush, remove cursor
                        break; 
                    }

                    const delta = typeof parsed === 'string' ? parsed : parsed?.content ?? '';

                    if (!assistantId) {
                        assistantId = createTempId();
                        localMessages.push({
                            id: assistantId,
                            role: 'assistant',
                            content: delta,
                            chunkIndex: nextChunkIndex ? nextChunkIndex : currentChunkIndex
                        });
                    } else {
                        textBuffer += delta;
                    }

                    // Schedule smooth UI update
                    scheduleFlush();
                }
            }
        } catch (error) {
            console.error(error);
            addMessageToChunk(
                { role: 'assistant', content: 'Sorry, something went wrong. Please try again.' },
                currentChunkIndex
            );
        } finally {
            setLoadingChunkIndex(null);
        }
    };

    const goToNextChunk = () => {
        if (documentData && currentChunkIndex < documentData.chunks.length - 1) {
            setCurrentChunkIndex(currentChunkIndex + 1);
            setChunkExpanded(true);
        }
    };

    const goToPrevChunk = () => {
        if (currentChunkIndex > 0) {
            setCurrentChunkIndex(currentChunkIndex - 1);
            setChunkExpanded(true);
        }
    };

    const sendAutomatedMessage = async (action) => {
        if (!documentData || currentChunkIndex >= documentData.chunks.length - 1) return;
        const nextChunkIndex = currentChunkIndex + 1;
        setLoadingChunkIndex(nextChunkIndex);
        const nextChunk = documentData.chunks[nextChunkIndex];
                
        // Update chunk index immediately for UI feedback
        setCurrentChunkIndex(nextChunkIndex);

        // Check if we already have messages for this chunk
        if (hasChunkMessages(nextChunkIndex)) {
            // Don't generate new response, just navigate
            setLoadingChunkIndex(null);
            return;
        }

        const requestBody = JSON.stringify({
            messages: globalChatHistory,
            currentChunk: documentData.chunks[currentChunkIndex]?.text || '',
            nextChunk: nextChunk.text,
            action: action,
            document: documentData ? JSON.stringify(documentData) : ''
        })

        streamResponse(requestBody, true, nextChunkIndex);
    };

    const skipChunk = () => {
        return sendAutomatedMessage('skip');
    };

    const markChunkUnderstood = () => {
        return sendAutomatedMessage('understood');
    };

    const startInteractiveLesson = (startChunkLessonFn) => {
        setChunkStates(prev => ({
            ...prev,
            [currentChunkIndex]: 'interactive'
        }));
        startChunkLessonFn(currentChunkIndex);
    };

    const setChunkAsInteractive = () => {
        // No longer tracking status - this is just for compatibility
    };

    const updateGlobalChatHistory = (messages) => {
        setGlobalChatHistory(messages);
    };

    const getGlobalChatHistory = () => {
        return globalChatHistory;
    };

    const addMessageToChunk = (message, chunkIndex) => {
        const messageWithChunk = { ...message, chunkIndex };
        setGlobalChatHistory(prev => [...prev, messageWithChunk]);
    };

    const getCurrentChunkMessages = () => {
        return globalChatHistory.filter(msg => msg.chunkIndex === currentChunkIndex);
    };

    const hasChunkMessages = (chunkIndex) => {
        return globalChatHistory.some(msg => msg.chunkIndex === chunkIndex);
    };

    const isChunkLoading = (chunkIndex) => {
        return loadingChunkIndex === chunkIndex;
    };

    return {
        chunkStates,
        currentChunkIndex,
        chunkExpanded,
        showChat,
        goToNextChunk,
        goToPrevChunk,
        skipChunk,
        markChunkUnderstood,
        startInteractiveLesson,
        setChunkExpanded,
        setShowChat,
        setChunkAsInteractive,
        updateGlobalChatHistory,
        getGlobalChatHistory,
        addMessageToChunk,
        getCurrentChunkMessages,
        hasChunkMessages,
        isChunkLoading,
        streamResponse
    };
};