-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodingHelper.tsx
More file actions
422 lines (388 loc) · 19.3 KB
/
Copy pathCodingHelper.tsx
File metadata and controls
422 lines (388 loc) · 19.3 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { LiveServerMessage, Modality } from '@google/genai';
// Fix: Import runCodeSimulation directly instead of non-existent GeminiService
import { runCodeSimulation, getGenAIInstance } from './geminiService';
import { Button } from './Button';
import { Input } from './Input';
import { LoadingSpinner } from './LoadingSpinner';
import { decodeAudioData, createBlob } from './audioUtils';
import { decode } from './utils/base64Utils';
import { GEMINI_LIVE_MODEL, CODING_HELPER_SYSTEM_INSTRUCTION } from './constants';
export const CodingHelper: React.FC = () => {
const [goal, setGoal] = useState('');
const [language, setLanguage] = useState('Python');
const [code, setCode] = useState('');
const [messages, setMessages] = useState<{ role: 'ai' | 'user'; text: string }[]>([]);
const [currentAiResponse, setCurrentAiResponse] = useState('');
const [isStarted, setIsStarted] = useState(false);
const [output, setOutput] = useState('');
const [isRunning, setIsRunning] = useState(false);
const [isSuspended, setIsSuspended] = useState(false);
const [connectionStatus, setConnectionStatus] = useState('Disconnected');
const [error, setError] = useState<string | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const outputAudioContextRef = useRef<AudioContext | null>(null);
const scriptProcessorRef = useRef<ScriptProcessorNode | null>(null);
const mediaStreamRef = useRef<MediaStream | null>(null);
const sessionPromiseRef = useRef<Promise<any> | null>(null);
const nextStartTimeRef = useRef(0);
const sourcesRef = useRef<Set<AudioBufferSourceNode>>(new Set());
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const lastSentCodeRef = useRef<string>('');
const backgroundTimerRef = useRef<NodeJS.Timeout | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [messages, currentAiResponse]);
const resetAudioState = useCallback(() => {
for (const source of sourcesRef.current.values()) {
source.stop();
sourcesRef.current.delete(source);
}
nextStartTimeRef.current = 0;
if (scriptProcessorRef.current) {
scriptProcessorRef.current.disconnect();
scriptProcessorRef.current = null;
}
if (mediaStreamRef.current) {
mediaStreamRef.current.getTracks().forEach((track) => track.stop());
mediaStreamRef.current = null;
}
if (audioContextRef.current) {
audioContextRef.current.close();
audioContextRef.current = null;
}
if (outputAudioContextRef.current) {
outputAudioContextRef.current.close();
outputAudioContextRef.current = null;
}
}, []);
const handleLiveOnMessage = useCallback(async (message: LiveServerMessage) => {
const base64EncodedAudioString = message.serverContent?.modelTurn?.parts[0]?.inlineData?.data;
if (base64EncodedAudioString) {
if (!outputAudioContextRef.current) {
outputAudioContextRef.current = new AudioContext({ sampleRate: 24000 });
}
nextStartTimeRef.current = Math.max(
nextStartTimeRef.current,
outputAudioContextRef.current.currentTime,
);
try {
const audioBuffer = await decodeAudioData(
decode(base64EncodedAudioString),
outputAudioContextRef.current,
24000,
1,
);
const source = outputAudioContextRef.current.createBufferSource();
source.buffer = audioBuffer;
source.connect(outputAudioContextRef.current.destination);
source.addEventListener('ended', () => {
sourcesRef.current.delete(source);
});
source.start(nextStartTimeRef.current);
nextStartTimeRef.current = nextStartTimeRef.current + audioBuffer.duration;
sourcesRef.current.add(source);
} catch (audioDecodeError) {
console.error('Error decoding audio data:', audioDecodeError);
}
}
const transcription = message.serverContent?.outputTranscription?.text;
if (transcription) {
setCurrentAiResponse(prev => prev + transcription);
}
if (message.serverContent?.turnComplete) {
setCurrentAiResponse(prev => {
if (prev.trim()) {
setMessages(curr => [...curr, { role: 'ai', text: prev.trim() }]);
}
return '';
});
}
}, []);
const startLiveSession = useCallback(async () => {
setConnectionStatus('Connecting...');
setError(null);
try {
mediaStreamRef.current = await navigator.mediaDevices.getUserMedia({ audio: true });
audioContextRef.current = new AudioContext({ sampleRate: 16000 });
outputAudioContextRef.current = new AudioContext({ sampleRate: 24000 });
// Fix: Await getGenAIInstance() because it returns a Promise<GoogleGenAI>
const ai = await getGenAIInstance();
const goalContext = `User Goal: Create a program in ${language} that: ${goal}.`;
const fullSystemInstruction = `${CODING_HELPER_SYSTEM_INSTRUCTION}\n${goalContext}`;
sessionPromiseRef.current = ai.live.connect({
model: GEMINI_LIVE_MODEL,
callbacks: {
onopen: () => {
setConnectionStatus('Synced');
sessionPromiseRef.current?.then((session) => {
session.sendRealtimeInput({ text: "Logic session initiated. I am monitoring your execution context." });
});
const source = audioContextRef.current!.createMediaStreamSource(mediaStreamRef.current!);
scriptProcessorRef.current = audioContextRef.current!.createScriptProcessor(4096, 1, 1);
scriptProcessorRef.current.onaudioprocess = (audioProcessingEvent) => {
const inputData = audioProcessingEvent.inputBuffer.getChannelData(0);
const pcmBlob = createBlob(inputData);
sessionPromiseRef.current?.then((session) => {
session.sendRealtimeInput({ media: pcmBlob });
});
};
source.connect(scriptProcessorRef.current);
scriptProcessorRef.current.connect(audioContextRef.current!.destination);
},
onmessage: handleLiveOnMessage,
onerror: (e: any) => {
console.error(e);
setConnectionStatus('Fault');
setError('Neural link interrupted.');
},
onclose: () => {
setConnectionStatus('Disconnected');
},
},
config: {
responseModalities: [Modality.AUDIO],
inputAudioTranscription: {},
outputAudioTranscription: {},
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Zephyr' } },
},
systemInstruction: fullSystemInstruction,
},
});
await sessionPromiseRef.current;
} catch (e) {
console.error(e);
setConnectionStatus('Failed');
setError('Check input peripherals.');
stopLiveSession();
}
}, [goal, language, handleLiveOnMessage, resetAudioState]);
const stopLiveSession = useCallback((isAutoSuspend = false) => {
resetAudioState();
sessionPromiseRef.current?.then(s => { try { s.close(); } catch(e) {} }).catch(e => console.error(e));
sessionPromiseRef.current = null;
if (isAutoSuspend) {
setIsSuspended(true);
setConnectionStatus('Suspended');
} else {
setIsSuspended(false);
setConnectionStatus('Disconnected');
}
}, [resetAudioState]);
useEffect(() => {
const handleVisibility = async () => {
if (!document.hidden) {
if (backgroundTimerRef.current) {
clearTimeout(backgroundTimerRef.current);
backgroundTimerRef.current = null;
}
if (isSuspended) return;
if (connectionStatus === 'Synced') {
try {
if (audioContextRef.current?.state === 'suspended') await audioContextRef.current.resume();
if (outputAudioContextRef.current?.state === 'suspended') await outputAudioContextRef.current.resume();
} catch (e) {
console.warn("Audio resume failed in IDE", e);
stopLiveSession();
}
}
} else {
if (connectionStatus === 'Synced') {
backgroundTimerRef.current = setTimeout(() => {
stopLiveSession(true);
}, 60000);
}
}
};
document.addEventListener("visibilitychange", handleVisibility);
return () => {
if (backgroundTimerRef.current) clearTimeout(backgroundTimerRef.current);
document.removeEventListener("visibilitychange", handleVisibility);
};
}, [connectionStatus, isSuspended, stopLiveSession]);
useEffect(() => {
if (!isStarted || connectionStatus !== 'Synced') return;
if (timerRef.current) clearInterval(timerRef.current);
timerRef.current = setInterval(() => {
if (code !== lastSentCodeRef.current && code.trim().length > 0) {
sessionPromiseRef.current?.then(session => {
session.sendRealtimeInput({ text: `[SYSTEM] User paused. Current Code Snippet:\n${code}` });
});
lastSentCodeRef.current = code;
}
}, 10000);
return () => {
if (timerRef.current) clearInterval(timerRef.current);
};
}, [code, isStarted, connectionStatus]);
const handleRunCode = async () => {
setIsRunning(true);
setOutput('> Compiling binary stream...');
try {
// Fix: Call runCodeSimulation directly as an imported function
const result = await runCodeSimulation(code, language);
setOutput(result);
sessionPromiseRef.current?.then(session => {
session.sendRealtimeInput({ text: `[SYSTEM] Code executed successfully. Output:\n${result}` });
});
} catch (e) {
const errText = `Error: ${e instanceof Error ? e.message : String(e)}`;
setOutput(errText);
sessionPromiseRef.current?.then(session => {
session.sendRealtimeInput({ text: `[SYSTEM] Code execution failed. Error logs:\n${errText}` });
});
} finally {
setIsRunning(false);
}
};
useEffect(() => {
return () => {
stopLiveSession();
}
}, [stopLiveSession]);
if (!isStarted) {
return (
<div className="flex flex-col items-center justify-center h-full bg-[#080a0f] p-8">
<div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-cyan-500 via-blue-500 to-purple-500"></div>
<div className="w-20 h-20 bg-cyan-500/10 rounded-3xl flex items-center justify-center text-cyan-400 text-4xl mb-8 border border-cyan-500/20 shadow-2xl shadow-cyan-500/10">
<i className="fas fa-code"></i>
</div>
<h2 className="text-4xl font-black text-white mb-4 tracking-tight uppercase">Cognitive IDE</h2>
<p className="text-gray-500 mb-12 max-w-sm text-center font-medium">Link your objective with our real-time logical monitoring engine.</p>
<div className="w-full max-w-lg bg-gray-900/40 p-10 rounded-[2.5rem] border border-gray-800 shadow-2xl backdrop-blur-md space-y-8">
<div>
<label className="block text-[10px] font-black text-gray-500 uppercase tracking-widest mb-3 ml-2">Execution Environment</label>
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
className="w-full bg-black border border-gray-800 text-white p-5 rounded-2xl focus:ring-2 focus:ring-cyan-600 appearance-none outline-none transition-all cursor-pointer"
>
<option value="Python">Python Runtime</option>
<option value="JavaScript">Node.js Environment</option>
<option value="TypeScript">TypeScript Compiler</option>
<option value="C++">C++ (GCC)</option>
<option value="C">C (Clang)</option>
<option value="SQL">PostgreSQL Engine</option>
</select>
</div>
<div>
<label className="block text-[10px] font-black text-gray-500 uppercase tracking-widest mb-3 ml-2">Project Objective</label>
<Input
value={goal}
onChange={(e) => setGoal(e.target.value)}
placeholder="e.g. Asynchronous data fetcher, Sorting algorithm..."
className="w-full bg-black border border-gray-800 text-white py-5 px-6 rounded-2xl focus:ring-2 focus:ring-cyan-600 shadow-inner"
/>
</div>
<Button onClick={() => { setIsStarted(true); setIsSuspended(false); startLiveSession(); }} className="w-full py-6 bg-cyan-600 hover:bg-cyan-500 text-white font-black rounded-2xl shadow-xl shadow-cyan-900/40 uppercase tracking-widest transition-all transform active:scale-95">
Initialize Link (Mic ON)
</Button>
<div className="flex items-center gap-3 bg-cyan-950/20 p-4 rounded-2xl border border-cyan-800/20">
<i className="fas fa-info-circle text-cyan-400"></i>
<p className="text-[10px] text-cyan-300 font-bold uppercase tracking-wider leading-relaxed">
Voice monitoring active. AI provides intervention only upon logical failure or explicit request.
</p>
</div>
</div>
</div>
);
}
return (
<div className="flex flex-col h-[calc(100vh-1rem)] bg-[#050608] rounded-3xl shadow-2xl overflow-hidden border border-gray-900 m-2">
<div className="bg-[#0a0c10] border-b border-gray-900 p-5 flex justify-between items-center shrink-0">
<div className="flex items-center gap-6">
<div className="w-10 h-10 rounded-xl bg-cyan-500/10 flex items-center justify-center text-cyan-400 border border-cyan-500/20">
<i className="fas fa-terminal text-xs"></i>
</div>
<div>
<h2 className="text-sm font-black text-white uppercase tracking-widest">Compiler_{language.toUpperCase()}</h2>
<div className="flex items-center gap-2">
<span className={`inline-block w-2 h-2 rounded-full ${connectionStatus === 'Synced' ? 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] animate-pulse' : 'bg-red-500'}`}></span>
<p className="text-[9px] font-black text-gray-600 uppercase tracking-widest">{connectionStatus}</p>
</div>
</div>
</div>
<div className="flex items-center gap-4">
{isSuspended && (
<Button onClick={() => { setIsSuspended(false); startLiveSession(); }} className="bg-cyan-600 hover:bg-cyan-500 text-white text-[10px] font-black uppercase tracking-widest py-2 px-4 rounded-xl shadow-lg transition-all">
Resume Sync
</Button>
)}
<div className="bg-black border border-gray-800 px-4 py-2 rounded-xl">
<p className="text-[9px] font-black text-cyan-500 uppercase tracking-[0.2em]">{goal || "SANDBOX"}</p>
</div>
<Button onClick={() => { setIsStarted(false); stopLiveSession(); }} className="bg-gray-900 hover:bg-red-900/20 text-gray-500 hover:text-red-400 text-[10px] font-black uppercase tracking-widest py-2 px-4 rounded-xl border border-gray-800 transition-all">
Terminate
</Button>
</div>
</div>
<div className="flex flex-1 overflow-hidden">
{/* Assistant Panel */}
<div className="w-[320px] bg-[#080a0f] border-r border-gray-900 flex flex-col">
<div className="p-6 border-b border-gray-900 bg-black/20">
<h3 className="text-[10px] font-black text-gray-600 uppercase tracking-[0.3em]">Neural Logs</h3>
</div>
<div className="flex-1 overflow-y-auto custom-scrollbar p-6 space-y-6">
<div className="bg-cyan-900/10 border border-cyan-500/10 p-4 rounded-2xl text-[11px] text-cyan-300 font-medium leading-relaxed shadow-inner">
<strong>[SYSTEM]:</strong> Passive monitoring active. State your questions or continue execution.
</div>
{messages.map((msg, idx) => (
<div key={idx} className={`p-4 rounded-2xl text-xs shadow-lg animate-fade-in ${msg.role === 'ai' ? 'bg-gray-800/40 text-gray-200 border border-gray-800' : 'bg-cyan-600/10 text-cyan-100 border border-cyan-500/20'}`}>
<div className="flex items-center justify-between mb-2">
<span className="text-[9px] font-black uppercase tracking-widest opacity-40">{msg.role === 'ai' ? 'Assist' : 'User'}</span>
<i className={`fas ${msg.role === 'ai' ? 'fa-robot' : 'fa-user'} text-[8px] opacity-20`}></i>
</div>
{msg.text}
</div>
))}
{currentAiResponse && (
<div className="p-4 rounded-2xl text-xs bg-cyan-600/20 text-white border border-cyan-500/30 animate-pulse">
<span className="text-[9px] font-black uppercase tracking-widest opacity-40 block mb-2">Streaming...</span>
{currentAiResponse}
</div>
)}
<div ref={messagesEndRef} />
</div>
{error && <div className="mx-6 mb-6 text-[9px] font-black text-red-400 bg-red-900/20 p-3 rounded-xl border border-red-500/20 uppercase tracking-widest text-center">{error}</div>}
</div>
{/* Editor Area */}
<div className="flex-1 flex flex-col bg-black">
<div className="flex-1 relative group">
<div className="absolute top-4 left-4 z-10 opacity-20 group-hover:opacity-100 transition-opacity">
<span className="text-[10px] font-mono text-gray-600 px-2 py-1 bg-gray-900 rounded select-none">ln 1</span>
</div>
<textarea
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder={`// Enter ${language} sequence...`}
className="w-full h-full bg-[#050608] text-cyan-400 font-mono p-8 focus:outline-none resize-none text-sm md:text-base leading-relaxed tracking-wide custom-scrollbar"
spellCheck="false"
/>
</div>
{/* Console Area */}
<div className="h-[280px] border-t border-gray-900 flex flex-col bg-[#0a0c10]">
<div className="bg-black/40 px-6 py-3 flex justify-between items-center border-b border-gray-900">
<div className="flex items-center gap-3">
<i className="fas fa-terminal text-[10px] text-gray-600"></i>
<span className="text-[9px] font-black text-gray-400 uppercase tracking-widest">IO Terminal</span>
</div>
<Button onClick={handleRunCode} disabled={isRunning} className="bg-cyan-600 hover:bg-cyan-500 text-white py-1.5 px-6 text-[10px] font-black uppercase tracking-widest rounded-lg shadow-lg shadow-cyan-900/20 transition-all">
{isRunning ? <><LoadingSpinner size="sm" /> RUNNING</> : 'RUN EXECUTION'}
</Button>
</div>
<div className="flex-1 bg-black p-6 font-mono text-xs overflow-y-auto custom-scrollbar">
<pre className="whitespace-pre-wrap text-gray-400 leading-relaxed">
{output || <span className="opacity-20 italic">Waiting for input stream...</span>}
</pre>
</div>
</div>
</div>
</div>
</div>
);
};