File size: 22,803 Bytes
ed9c135
6e7902e
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
dc3d28d
f12802a
dc3d28d
f12802a
dc3d28d
f12802a
dc3d28d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f12802a
6e7902e
dc3d28d
 
 
f12802a
dc3d28d
f12802a
dc3d28d
f12802a
 
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
62beaf6
ed9c135
4d7b624
 
b85818d
 
 
 
 
6e7902e
62beaf6
2e50f11
 
 
dc3d28d
62beaf6
6e7902e
2e50f11
 
 
 
 
6e7902e
2e50f11
6e7902e
2e50f11
 
 
 
 
 
6e7902e
2e50f11
 
 
 
 
 
6e7902e
f12802a
2e50f11
 
 
 
6e7902e
 
2e50f11
 
 
 
 
 
 
6e7902e
2e50f11
 
 
 
 
 
6e7902e
2e50f11
 
 
 
 
 
6e7902e
dc3d28d
2e50f11
 
 
 
 
 
dc3d28d
2e50f11
 
 
 
 
 
 
 
dc3d28d
2e50f11
 
 
 
 
 
 
 
6e7902e
dc3d28d
2e50f11
 
6e7902e
f12802a
2e50f11
 
 
 
 
 
6e7902e
2e50f11
6e7902e
dc3d28d
 
2e50f11
 
 
 
 
 
6e7902e
 
 
f12802a
 
 
2e50f11
 
f12802a
2e50f11
 
f12802a
 
 
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
2e50f11
 
 
6e7902e
 
2e50f11
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
2e50f11
6e7902e
dc3d28d
 
2e50f11
6e7902e
dc3d28d
 
2e50f11
6e7902e
 
 
dc3d28d
 
 
 
 
 
 
 
 
 
 
 
 
6e7902e
 
 
 
 
dc3d28d
6e7902e
 
 
 
dc3d28d
 
6e7902e
dc3d28d
6e7902e
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
 
dc3d28d
6e7902e
 
 
f12802a
dc3d28d
 
 
6e7902e
dc3d28d
 
 
 
 
 
 
 
 
6e7902e
 
dc3d28d
 
6e7902e
 
dc3d28d
6e7902e
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
 
 
 
 
 
 
6e7902e
 
dc3d28d
6e7902e
 
dc3d28d
 
 
 
 
 
6e7902e
 
 
dc3d28d
6e7902e
 
b85818d
6e7902e
 
 
 
 
ed9c135
 
 
 
 
 
 
6e7902e
 
4d7b624
 
6e7902e
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
dc3d28d
 
 
 
6e7902e
dc3d28d
 
 
 
6e7902e
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
 
 
dc3d28d
 
 
 
 
 
 
 
 
 
 
 
 
 
6e7902e
 
 
dc3d28d
 
 
 
 
6e7902e
 
 
 
dc3d28d
 
6e7902e
 
 
 
dc3d28d
6e7902e
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3d28d
6e7902e
 
dc3d28d
6e7902e
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";

// Global Application State Management
const STATE = {
    reasoningEffort: "medium",
    maxTokens: 2048,
    temperature: 0.7,
    uploadedFiles: [], // Current prompt attachments
    conversationHistory: [], // Sent to StepFun API
    gradioClient: null,
    isThinking: false
};

// DOM Elements hooks
const dom = {
    effortRadioButtons: document.querySelectorAll('input[name="reasoning-effort"]'),
    maxTokensSlider: document.getElementById("max-tokens-slider"),
    maxTokensVal: document.getElementById("max-tokens-val"),
    temperatureSlider: document.getElementById("temperature-slider"),
    temperatureVal: document.getElementById("temperature-val"),
    
    // Sidebar Drawer and Overlay Elements (Mobile & Minimalist)
    sidebarRight: document.getElementById("sidebar-right"),
    sidebarOverlay: document.getElementById("sidebar-overlay"),
    btnToggleRight: document.getElementById("btn-toggle-right"),
    btnCloseDrawer: document.getElementById("btn-close-drawer"),
    
    // Viewports
    studioDashboard: document.getElementById("studio-dashboard"),
    chatThreadContainer: document.getElementById("chat-thread-container"),
    chatMessagesFeed: document.getElementById("chat-messages-feed"),
    
    // Main Console Box Elements (Dashboard view)
    studioPromptInput: document.getElementById("studio-prompt-input"),
    innerShelfPreview: document.getElementById("inner-shelf-preview"),
    studioUploadTrigger: document.getElementById("studio-upload-trigger"),
    studioSendBtn: document.getElementById("studio-send-button"),
    studioSpinner: document.getElementById("studio-spinner"),
    
    // Mini Console Box Elements (Chat thread view)
    miniPromptInput: document.getElementById("mini-prompt-input"),
    miniShelfPreview: document.getElementById("mini-shelf-preview"),
    miniUploadTrigger: document.getElementById("mini-upload-trigger"),
    miniSendBtn: document.getElementById("mini-send-button"),
    miniSpinner: document.getElementById("mini-spinner"),
    
    // Core file upload elements
    fileUploader: document.getElementById("file-uploader"),
    shelfList: document.getElementById("shelf-list"),
    dropZone: document.getElementById("drop-zone"),
    
    // Action Resets
    menuNewChat: document.getElementById("menu-new-chat"),
    clearChatBtn: document.getElementById("clear-chat-button"),
    
    // Showcase recipe chips
    recipeChips: document.querySelectorAll(".recipe-chip")
};

// Markdown configuration
marked.setOptions({
    breaks: true,
    highlight: function(code, lang) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
    }
});

// Setup Initial State & Event Handlers
async function initializeApp() {
    // 1. Connect Gradio Client in background (Non-blocking)
    Client.connect(window.location.origin)
        .then(app => {
            STATE.gradioClient = app;
            console.log("Successfully connected to Gradio.Server backend.");
        })
        .catch(e => {
            console.error("Gradio Client Connection Failed:", e);
        });

    // 2. Register Sidebar Drawer Slide Events (Drawer + Overlay)
    if (dom.btnToggleRight) dom.btnToggleRight.addEventListener("click", () => toggleSettingsDrawer(true));
    if (dom.btnCloseDrawer) dom.btnCloseDrawer.addEventListener("click", () => toggleSettingsDrawer(false));
    if (dom.sidebarOverlay) dom.sidebarOverlay.addEventListener("click", () => toggleSettingsDrawer(false));

    // 3. Register Settings Listeners

    if (dom.effortRadioButtons) {
        dom.effortRadioButtons.forEach(radio => {
            radio.addEventListener("change", (e) => {
                STATE.reasoningEffort = e.target.value;
            });
        });
    }

    if (dom.maxTokensSlider && dom.maxTokensVal) {
        dom.maxTokensSlider.addEventListener("input", (e) => {
            STATE.maxTokens = parseInt(e.target.value);
            dom.maxTokensVal.textContent = STATE.maxTokens;
        });
    }

    if (dom.temperatureSlider && dom.temperatureVal) {
        dom.temperatureSlider.addEventListener("input", (e) => {
            STATE.temperature = parseFloat(e.target.value);
            dom.temperatureVal.textContent = STATE.temperature.toFixed(1);
        });
    }

    // 5. Register File Upload Actions
    if (dom.studioUploadTrigger) dom.studioUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
    if (dom.miniUploadTrigger) dom.miniUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
    if (dom.dropZone) dom.dropZone.addEventListener("click", () => dom.fileUploader.click());
    if (dom.fileUploader) dom.fileUploader.addEventListener("change", handleFileSelection);

    // Dropzone Drag-and-Drop animations
    if (dom.dropZone) {
        ["dragenter", "dragover"].forEach(eventName => {
            dom.dropZone.addEventListener(eventName, (e) => {
                e.preventDefault();
                dom.dropZone.classList.add("drag-active");
            }, false);
        });

        ["dragleave", "drop"].forEach(eventName => {
            dom.dropZone.addEventListener(eventName, (e) => {
                e.preventDefault();
                dom.dropZone.classList.remove("drag-active");
            }, false);
        });

        dom.dropZone.addEventListener("drop", (e) => {
            const dt = e.dataTransfer;
            const files = dt.files;
            processFiles(files);
        });
    }

    // 6. Submit Triggers
    if (dom.studioSendBtn) {
        dom.studioSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.studioPromptInput));
    }
    if (dom.miniSendBtn) {
        dom.miniSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.miniPromptInput));
    }

    if (dom.studioPromptInput) {
        dom.studioPromptInput.addEventListener("keydown", (e) => {
            if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                triggerPromptSubmission(dom.studioPromptInput);
            }
        });
    }

    if (dom.miniPromptInput) {
        dom.miniPromptInput.addEventListener("keydown", (e) => {
            if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                triggerPromptSubmission(dom.miniPromptInput);
            }
        });
    }

    // 7. Resets
    if (dom.menuNewChat) dom.menuNewChat.addEventListener("click", resetSandbox);
    if (dom.clearChatBtn) dom.clearChatBtn.addEventListener("click", resetSandbox);

    // 8. Recipe Chips Console Setup
    if (dom.recipeChips) {
        dom.recipeChips.forEach(chip => {
            chip.addEventListener("click", () => {
                const recipeType = chip.getAttribute("data-recipe");
                loadRecipe(recipeType);
            });
        });
    }

    // Auto-expand input textareas
    [dom.studioPromptInput, dom.miniPromptInput].forEach(textarea => {
        if (textarea) {
            textarea.addEventListener("input", () => {
                textarea.style.height = "auto";
                textarea.style.height = (textarea.scrollHeight) + "px";
            });
        }
    });
}

// Drawer Toggler Action
function toggleSettingsDrawer(open) {
    if (open) {
        if (dom.sidebarRight) dom.sidebarRight.classList.remove("collapsed");
        if (dom.sidebarOverlay) dom.sidebarOverlay.classList.add("active");
    } else {
        if (dom.sidebarRight) dom.sidebarRight.classList.add("collapsed");
        if (dom.sidebarOverlay) dom.sidebarOverlay.classList.remove("active");
    }
}

// Handle File Select & Base64 Encoder
function handleFileSelection(e) {
    processFiles(e.target.files);
}

function processFiles(files) {
    if (!files.length) return;

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = (event) => {
            const fileData = {
                id: Math.random().toString(36).substring(2, 9),
                name: file.name,
                type: file.type,
                size: (file.size / 1024 / 1024).toFixed(2) + " MB",
                base64: event.target.result
            };
            
            STATE.uploadedFiles.push(fileData);
            updateShelfUI();
        };
        reader.readAsDataURL(file);
    });
}

// Update UI Attachment Previews
function updateShelfUI() {
    if (dom.shelfList) dom.shelfList.innerHTML = "";
    if (dom.innerShelfPreview) dom.innerShelfPreview.innerHTML = "";
    if (dom.miniShelfPreview) dom.miniShelfPreview.innerHTML = "";

    if (STATE.uploadedFiles.length === 0) {
        if (dom.shelfList) dom.shelfList.innerHTML = `<div class="empty-shelf-text">No active attachments loaded. Upload images or video clips.</div>`;
        return;
    }

    STATE.uploadedFiles.forEach(file => {
        // 1. Sidebar Chip
        const chip = document.createElement("div");
        chip.className = "media-chip";
        
        let previewHtml = "";
        if (file.type.startsWith("image/")) {
            previewHtml = `<img src="${file.base64}" alt="${file.name}">`;
        } else if (file.type.startsWith("video/")) {
            previewHtml = `🎬`;
        } else {
            previewHtml = `📎`;
        }

        chip.innerHTML = `
            <div class="media-chip-preview">${previewHtml}</div>
            <div class="media-chip-details">
                <div class="media-chip-name">${file.name}</div>
                <div class="media-chip-meta">
                    <span>${file.type.split("/")[1].toUpperCase()}</span>
                    <span>${file.size}</span>
                </div>
            </div>
            <button class="media-chip-remove" data-id="${file.id}">
                <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        `;

        chip.querySelector(".media-chip-remove").addEventListener("click", () => {
            removeFile(file.id);
        });

        if (dom.shelfList) dom.shelfList.appendChild(chip);

        // 2. Dashboard Inner Console Preview
        const previewItemDash = createPreviewThumb(file);
        if (dom.innerShelfPreview) dom.innerShelfPreview.appendChild(previewItemDash);

        // 3. Mini Input Preview
        const previewItemMini = createPreviewThumb(file);
        if (dom.miniShelfPreview) dom.miniShelfPreview.appendChild(previewItemMini);
    });
}

function createPreviewThumb(file) {
    const previewItem = document.createElement("div");
    previewItem.className = "quick-preview-item";
    previewItem.title = file.name;
    
    if (file.type.startsWith("image/")) {
        previewItem.innerHTML = `<img src="${file.base64}"><div class="quick-preview-badge"></div>`;
    } else {
        previewItem.innerHTML = `<div class="media-chip-preview" style="width:100%;height:100%;">🎬</div><div class="quick-preview-badge"></div>`;
    }
    return previewItem;
}

function removeFile(id) {
    STATE.uploadedFiles = STATE.uploadedFiles.filter(f => f.id !== id);
    updateShelfUI();
}

// Load Cookbook Showcase Recipes
function loadRecipe(recipeType) {
    const mockImageBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
    STATE.uploadedFiles = [];

    let promptText = "";

    if (recipeType === "whiteboard") {
        promptText = "Here is a snapshot of our whiteboard project plan sketch. Translate this visual sequence of tasks and boxes into a clean, itemized roadmap plan with a structured markdown table.";
        STATE.uploadedFiles.push({
            id: "recipe-whiteboard",
            name: "whiteboard_gantt.png",
            type: "image/png",
            size: "0.02 MB",
            base64: mockImageBase64
        });
    } else if (recipeType === "diagnostic") {
        promptText = "This is a recorded visual sequence of steps leading to a runtime exception crash. Provide a detailed reconstruction of the event timeline, summarize the diagnostic signals, and suggest an engineering hotfix.";
        STATE.uploadedFiles.push({
            id: "recipe-diagnostics",
            name: "console_bug.mp4",
            type: "video/mp4",
            size: "1.45 MB",
            base64: mockImageBase64
        });
    }

    // Set value in BOTH text areas
    dom.studioPromptInput.value = promptText;
    dom.miniPromptInput.value = promptText;

    updateShelfUI();
    dom.studioPromptInput.dispatchEvent(new Event("input"));
    dom.miniPromptInput.dispatchEvent(new Event("input"));
    
    // Focus active textarea
    if (dom.studioDashboard.style.display !== "none") {
        dom.studioPromptInput.focus();
    } else {
        dom.miniPromptInput.focus();
    }
}

// Submit prompt values to Gradio.Server API
async function triggerPromptSubmission(inputElement) {
    if (STATE.isThinking) return;

    const promptText = inputElement.value.trim();
    if (!promptText && STATE.uploadedFiles.length === 0) return;

    setLoadingState(true);

    // 1. Format user message contents
    const contentArray = [];
    if (promptText) {
        contentArray.push({
            type: "text",
            text: promptText
        });
    }

    // Attachments
    STATE.uploadedFiles.forEach(file => {
        if (file.type.startsWith("image/")) {
            contentArray.push({
                type: "image_url",
                image_url: {
                    url: file.base64
                }
            });
        } else if (file.type.startsWith("video/")) {
            contentArray.push({
                type: "video_url",
                video_url: {
                    url: file.base64
                }
            });
        }
    });

    const userMessage = {
        role: "user",
        content: contentArray
    };

    // 2. Transition dashboard to Chat Thread view
    if (dom.studioDashboard.style.display !== "none") {
        dom.studioDashboard.style.display = "none";
        dom.chatThreadContainer.style.display = "flex";
    }

    // Append to UI thread list
    appendUserBubble(promptText, STATE.uploadedFiles);

    // Append to backend log history
    STATE.conversationHistory.push(userMessage);

    // Clear active UI containers
    dom.studioPromptInput.value = "";
    dom.miniPromptInput.value = "";
    dom.studioPromptInput.style.height = "auto";
    dom.miniPromptInput.style.height = "auto";
    
    STATE.uploadedFiles = [];
    updateShelfUI();

    // 3. Connect API Call
    try {
        if (!STATE.gradioClient) {
            throw new Error("Gradio server is initializing. Please wait a few seconds and try sending again.");
        }

        const responseId = appendAssistantPlaceholderBubble();
        const startTime = Date.now();

        // Call our gradio.Server api endpoint using standard positional array arguments
        const result = await STATE.gradioClient.predict("/chat_with_step", [
            JSON.stringify(STATE.conversationHistory),
            STATE.reasoningEffort,
            STATE.maxTokens,
            STATE.temperature
        ]);

        const duration = ((Date.now() - startTime) / 1000).toFixed(1);
        const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
        const data = JSON.parse(rawData);

        if (data.status === "error") {
            updateAssistantBubble(responseId, `⚠️ **API Error:** ${data.message}`, "", duration);
            STATE.conversationHistory.pop(); // Remove failed prompt
        } else {
            updateAssistantBubble(responseId, data.content, data.reasoning_content, duration);
            STATE.conversationHistory.push({
                role: "assistant",
                content: data.content
            });
        }

    } catch (e) {
        console.error(e);
        appendSystemLog(`Connection exception: ${e.message}`, true);
        setLoadingState(false);
    }

    setLoadingState(false);
}

// UI spinner state toggles
function setLoadingState(loading) {
    STATE.isThinking = loading;
    if (loading) {
        dom.studioSpinner.style.display = "block";
        dom.miniSpinner.style.display = "block";
        dom.studioSendBtn.disabled = true;
        dom.miniSendBtn.disabled = true;
    } else {
        dom.studioSpinner.style.display = "none";
        dom.miniSpinner.style.display = "none";
        dom.studioSendBtn.disabled = false;
        dom.miniSendBtn.disabled = false;
    }
}

// Render User Bubble
function appendUserBubble(text, files) {
    const bubble = document.createElement("div");
    bubble.className = "message-bubble user";
    
    let attachmentsHtml = "";
    if (files.length > 0) {
        attachmentsHtml = `<div class="bubble-attachments">`;
        files.forEach(file => {
            if (file.type.startsWith("image/")) {
                attachmentsHtml += `
                    <div class="bubble-attachment-card">
                        <img src="${file.base64}">
                        <div class="bubble-attachment-label">IMG</div>
                    </div>
                `;
            } else {
                attachmentsHtml += `
                    <div class="bubble-attachment-card">
                        <div class="media-chip-preview" style="width:100%;height:100%;">🎬</div>
                        <div class="bubble-attachment-label">VIDEO</div>
                    </div>
                `;
            }
        });
        attachmentsHtml += `</div>`;
    }

    bubble.innerHTML = `
        <div class="message-meta">User</div>
        <div class="message-body">
            <div class="message-text">${escapeHtml(text)}</div>
            ${attachmentsHtml}
        </div>
    `;

    dom.chatMessagesFeed.appendChild(bubble);
    scrollToBottom();
}

// Render Assistant Placeholder
function appendAssistantPlaceholderBubble() {
    const id = "assistant-" + Math.random().toString(36).substring(2, 9);
    const bubble = document.createElement("div");
    bubble.className = "message-bubble assistant";
    bubble.id = id;

    bubble.innerHTML = `
        <div class="message-meta">Step 3.7 Flash</div>
        <div class="message-body">
            <div class="thought-container" id="${id}-thought-box">
                <div class="thought-header">
                    <div class="thought-title-group">
                        <div class="spinner-light" style="width:12px;height:12px;border-width:1.5px; border-top-color:#111827; border-left-color:#e5e7eb;"></div>
                        <span>Reasoning...</span>
                    </div>
                    <span class="thought-timer" id="${id}-timer">0.0s</span>
                </div>
            </div>
            <div class="message-text markdown-body" id="${id}-text-box">
                <span class="text-muted">Analyzing context and constructing reasoning chain...</span>
            </div>
        </div>
    `;

    dom.chatMessagesFeed.appendChild(bubble);
    scrollToBottom();

    // Start Thought Timer
    let seconds = 0.0;
    const timerEl = document.getElementById(`${id}-timer`);
    const interval = setInterval(() => {
        if (!STATE.isThinking || !document.getElementById(id)) {
            clearInterval(interval);
            return;
        }
        seconds += 0.1;
        timerEl.textContent = seconds.toFixed(1) + "s";
    }, 100);

    return id;
}

// Complete Assistant Bubble
function updateAssistantBubble(id, content, reasoning, duration) {
    const bubble = document.getElementById(id);
    if (!bubble) return;

    const thoughtBox = document.getElementById(`${id}-thought-box`);
    const textBox = document.getElementById(`${id}-text-box`);

    if (reasoning) {
        thoughtBox.innerHTML = `
            <div class="thought-header" id="${id}-thought-toggle">
                <div class="thought-title-group">
                    <span>🧠 Thought Process</span>
                </div>
                <div style="display:flex;align-items:center;gap:10px;">
                    <span class="thought-timer">Thought for ${duration}s</span>
                    <span class="thought-toggle-icon">▼</span>
                </div>
            </div>
            <div class="thought-content">${escapeHtml(reasoning)}</div>
        `;
        
        const toggleBtn = document.getElementById(`${id}-thought-toggle`);
        toggleBtn.addEventListener("click", () => {
            thoughtBox.classList.toggle("collapsed");
        });
    } else {
        thoughtBox.style.display = "none";
    }

    textBox.innerHTML = marked.parse(content);
    
    textBox.querySelectorAll("pre code").forEach((el) => {
        hljs.highlightElement(el);
    });

    scrollToBottom();
}

// Reset Sandbox Chat Context Logs
function resetSandbox() {
    STATE.conversationHistory = [];
    STATE.uploadedFiles = [];
    updateShelfUI();

    // Clear feed
    dom.chatMessagesFeed.innerHTML = "";

    // Show dashboard
    dom.chatThreadContainer.style.display = "none";
    dom.studioDashboard.style.display = "flex";

    dom.studioPromptInput.value = "";
    dom.miniPromptInput.value = "";
    dom.studioPromptInput.style.height = "auto";
    dom.miniPromptInput.style.height = "auto";

    appendSystemLog("Workspace sandbox reset successful.");
}

function appendSystemLog(message, isError = false) {
    if (dom.chatThreadContainer.style.display === "none") {
        console.warn(`System Log: ${message}`);
        return;
    }

    const log = document.createElement("div");
    log.className = "message-bubble assistant";
    log.innerHTML = `
        <div class="message-meta">System</div>
        <div class="message-body" style="background-color: ${isError ? '#fef2f2' : '#f0fdf4'}; border-color: ${isError ? '#fee2e2' : '#bbf7d0'};">
            <div class="message-text" style="color: ${isError ? '#ef4444' : '#16a34a'}; font-size: 11.5px; font-weight: 500;">
                ${isError ? '🛑' : 'ℹ️'} ${message}
            </div>
        </div>
    `;
    dom.chatMessagesFeed.appendChild(log);
    scrollToBottom();
}

function escapeHtml(text) {
    if (!text) return "";
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function scrollToBottom() {
    dom.chatMessagesFeed.scrollTop = dom.chatMessagesFeed.scrollHeight;
}

// Initialise application when DOM is fully set up
window.addEventListener("DOMContentLoaded", initializeApp);