File size: 14,131 Bytes
973d6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9cb5b
973d6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9cb5b
973d6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9cb5b
973d6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9cb5b
973d6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { useCallback, useEffect, useRef, useState, ReactNode } from 'react';
import { Send, Wifi, WifiOff, Loader2, Trash2 } from 'lucide-react';
import ThemeToggle from './ThemeToggle';
import ModelSelector from './ModelSelector';
import { useWebSocket, WSEvent } from '../hooks/useWebSocket';
import MessageBubble, { ChatMessage, MediaItem } from './MessageBubble';
import ApiKeysPanel from './ApiKeysPanel';
import './ChatPanel.css';

interface ChatPanelProps {
    cacheToggle?: ReactNode;
}

let msgCounter = 0;
const uid = () => `msg-${++msgCounter}-${Date.now()}`;

export default function ChatPanel({ cacheToggle }: ChatPanelProps) {
    const [messages, setMessages] = useState<ChatMessage[]>([]);
    const [input, setInput] = useState('');
    const [isThinking, setIsThinking] = useState(false);
    const [statusMsg, setStatusMsg] = useState('');
    const [needKeys, setNeedKeys] = useState<boolean | null>(null); // null = don't know yet
    const [keysConfigured, setKeysConfigured] = useState(false);
    const bottomRef = useRef<HTMLDivElement>(null);
    const streamBuf = useRef('');
    const streamMedia = useRef<MediaItem[]>([]);
    const streamSnippets = useRef<string[]>([]);
    const streamId = useRef<string | null>(null);
    const textareaRef = useRef<HTMLTextAreaElement>(null);


    /* ── event handler ── */
    const handleEvent = useCallback((ev: WSEvent) => {
        switch (ev.type) {
            case 'thinking':
                setIsThinking(true);
                setStatusMsg('');
                streamBuf.current = '';
                streamMedia.current = [];
                streamSnippets.current = [];
                streamId.current = uid();
                break;

            case 'status':
                setStatusMsg(ev.content ?? '');
                break;

            case 'tool_start':
                setMessages(prev => {
                    const id = streamId.current ?? uid();
                    streamId.current = id;
                    const exists = prev.find(m => m.id === id);
                    if (exists) {
                        return prev.map(m =>
                            m.id === id ? { ...m, toolLabel: ev.content ?? '' } : m
                        );
                    }
                    return [...prev, { id, role: 'assistant', content: '', toolLabel: ev.content ?? '', isStreaming: true }];
                });
                break;

            case 'stream': {
                setIsThinking(false);
                setStatusMsg('');
                const chunk = ev.content ?? '';
                streamBuf.current += chunk;
                const id = streamId.current ?? uid();
                streamId.current = id;
                setMessages(prev => {
                    const exists = prev.find(m => m.id === id);
                    if (exists) {
                        return prev.map(m =>
                            m.id === id ? { ...m, content: streamBuf.current, isStreaming: true } : m
                        );
                    }
                    return [...prev, { id, role: 'assistant', content: streamBuf.current, isStreaming: true }];
                });
                break;
            }

            case 'plot': {
                const id = streamId.current ?? uid();
                streamId.current = id;
                if (ev.data) {
                    streamMedia.current.push({
                        type: 'plot',
                        base64: ev.data as string,
                        path: ev.path as string | undefined,
                        code: ev.code as string | undefined,
                    });
                }
                setMessages(prev => {
                    const exists = prev.find(m => m.id === id);
                    if (exists) {
                        return prev.map(m =>
                            m.id === id ? { ...m, media: [...streamMedia.current] } : m
                        );
                    }
                    return [...prev, { id, role: 'assistant', content: streamBuf.current, media: [...streamMedia.current], isStreaming: true }];
                });
                break;
            }

            case 'video': {
                const id = streamId.current ?? uid();
                streamId.current = id;
                if (ev.data) {
                    streamMedia.current.push({
                        type: 'video',
                        base64: ev.data as string,
                        path: ev.path as string | undefined,
                        mimetype: ev.mimetype as string | undefined,
                    });
                }
                setMessages(prev => {
                    const exists = prev.find(m => m.id === id);
                    if (exists) {
                        return prev.map(m =>
                            m.id === id ? { ...m, media: [...streamMedia.current] } : m
                        );
                    }
                    return [...prev, { id, role: 'assistant', content: streamBuf.current, media: [...streamMedia.current], isStreaming: true }];
                });
                break;
            }

            case 'arraylake_snippet': {
                const id = streamId.current;
                if (ev.content && id) {
                    streamSnippets.current.push(ev.content);
                    setMessages(prev =>
                        prev.map(m =>
                            m.id === id ? { ...m, arraylakeSnippets: [...streamSnippets.current] } : m
                        )
                    );
                }
                break;
            }

            case 'complete':
                setIsThinking(false);
                setStatusMsg('');
                // Only finalize the existing streaming message β€” never create a new one.
                // Snapshot refs into locals BEFORE the state setter runs.
                if (streamId.current) {
                    const capturedId = streamId.current;
                    const capturedContent = ev.content ?? streamBuf.current;
                    const capturedMedia = [...streamMedia.current];
                    const capturedSnippets = [...streamSnippets.current];
                    setMessages(prev =>
                        prev.map(m => {
                            if (m.id !== capturedId) return m;
                            return {
                                ...m,
                                content: capturedContent || m.content,
                                // Preserve media/snippets already on the message if our refs are empty
                                media: capturedMedia.length > 0 ? capturedMedia : (m.media || []),
                                arraylakeSnippets: capturedSnippets.length > 0 ? capturedSnippets : (m.arraylakeSnippets || []),
                                isStreaming: false,
                                toolLabel: undefined,
                                statusText: undefined,
                            };
                        })
                    );
                }
                streamBuf.current = '';
                streamMedia.current = [];
                streamSnippets.current = [];
                streamId.current = null;
                break;

            case 'error':
                setIsThinking(false);
                setStatusMsg('');
                setMessages(prev => [...prev, { id: uid(), role: 'system', content: `⚠ ${ev.content ?? 'Unknown error'}` }]);
                streamId.current = null;
                break;

            case 'keys_configured':
                if (ev.ready) {
                    setNeedKeys(false);
                    setKeysConfigured(true);
                }
                break;

            case 'request_keys':
                // Server lost keys β€” resend from sessionStorage
                setNeedKeys(true);
                break;

            case 'clear':
                setMessages([]);
                streamBuf.current = '';
                streamMedia.current = [];
                streamSnippets.current = [];
                streamId.current = null;
                break;

            default:
                break;
        }
    }, []);

    const { status, send, sendMessage, configureKeys } = useWebSocket(handleEvent);

    /* ── check if server has keys ── */
    useEffect(() => {
        if (status !== 'connected') return; // only check when connected
        fetch('/api/keys-status')
            .then(r => r.json())
            .then(data => {
                setNeedKeys(!data.openai);
            })
            .catch(() => setNeedKeys(true)); // no server keys β€” show panel
    }, [status]);

    /* ── auto-scroll ── */
    useEffect(() => {
        bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages, isThinking, statusMsg]);

    /* ── send ── */
    const handleSend = () => {
        const text = input.trim();
        if (!text || status !== 'connected') return;
        setMessages(prev => [...prev, { id: uid(), role: 'user', content: text }]);
        sendMessage(text);
        setInput('');
        if (textareaRef.current) {
            textareaRef.current.style.height = 'auto';
        }
    };

    /* ── clear conversation ── */
    const handleClear = async () => {
        if (!confirm('Clear conversation history?')) return;
        try {
            await fetch('/api/conversation', { method: 'DELETE' });
            setMessages([]);
        } catch { /* ignore */ }
    };

    /* ── auto-resize textarea ── */
    const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setInput(e.target.value);
        const ta = e.target;
        ta.style.height = 'auto';
        ta.style.height = Math.min(ta.scrollHeight, 160) + 'px';
    };

    /* ── keys handler ── */
    const handleSaveKeys = (keys: { openai_api_key: string; arraylake_api_key: string }) => {
        configureKeys(keys);
    };

    const statusColor = status === 'connected' ? '#34d399' : status === 'connecting' ? '#fbbf24' : '#f87171';
    const StatusIcon = status === 'connected' ? Wifi : WifiOff;
    const statusClass = `status-badge ${status === 'disconnected' ? 'disconnected' : ''}`;

    const canSend = status === 'connected' && needKeys !== true;

    return (
        <div className="chat-panel">
            {/* header */}
            <header className="chat-header">
                <div className="chat-title">
                    <div className="chat-logo">🌊</div>
                    <h1>Eurus Climate Agent</h1>
                </div>
                <div className="chat-header-actions">
                    <div className={statusClass} style={{ color: statusColor }}>
                        <StatusIcon size={12} />
                        <span>{status}</span>
                    </div>
                    {cacheToggle}
                    <ModelSelector send={send} />
                    <ThemeToggle />
                    <button className="icon-btn danger-btn" onClick={handleClear} title="Clear conversation">
                        <Trash2 size={16} />
                    </button>
                </div>
            </header>

            {/* API keys panel */}
            <ApiKeysPanel visible={needKeys === true} onSave={handleSaveKeys} configured={keysConfigured} />

            {/* messages */}
            <div className="messages-container">
                {messages.length === 0 && (
                    <div className="empty-state">
                        <div className="empty-icon">🌍</div>
                        <h2>Welcome to Eurus</h2>
                        <p>Ask about ERA5 climate data β€” SST, wind, precipitation, temperature and more.</p>
                        <p className="empty-warning">
                            ⚠️ <strong>Experimental</strong> β€” research prototype. Avoid very large datasets. Use πŸ“¦ Arraylake Code for heavy workloads.
                        </p>
                        <div className="example-queries">
                            <button onClick={() => { setInput('Show SST map for the North Atlantic, Jan 2024'); }}>
                                🌑 SST β€” North Atlantic
                            </button>
                            <button onClick={() => { setInput('Compare 2m temperature Berlin vs Tokyo, March 2023'); }}>
                                πŸ’¨ Temperature β€” Berlin vs Tokyo
                            </button>
                            <button onClick={() => { setInput('Precipitation anomalies over Amazon, 2023'); }}>
                                🌧 Rain β€” Amazon basin
                            </button>
                        </div>
                    </div>
                )}
                {messages.map((m) => <MessageBubble key={m.id} msg={m} />)}
                {(isThinking || statusMsg) && (
                    <div className="thinking-indicator">
                        <Loader2 className="spin" size={16} />
                        <span>{statusMsg || 'Analyzing...'}</span>
                    </div>
                )}
                <div ref={bottomRef} />
            </div>

            {/* input */}
            <div className="input-bar">
                <textarea
                    ref={textareaRef}
                    value={input}
                    onChange={handleInputChange}
                    onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
                    placeholder={canSend ? 'Ask about climate data…' : needKeys ? 'Enter API keys above…' : 'Connecting…'}
                    disabled={!canSend}
                    rows={1}
                />
                <button
                    className="send-btn"
                    onClick={handleSend}
                    disabled={!input.trim() || !canSend}
                >
                    <Send size={18} />
                </button>
            </div>
        </div>
    );
}