R-Kentaren commited on
Commit
8686eae
·
verified ·
1 Parent(s): 60a3388

feat: add HF OAuth auth, per-user sessions, chat history sidebar

Browse files
Files changed (1) hide show
  1. static/app.js +468 -278
static/app.js CHANGED
@@ -1,6 +1,9 @@
1
  import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
 
2
 
3
- // Global Application State Management
 
 
4
  const STATE = {
5
  reasoningEffort: "medium",
6
  maxTokens: 2048,
@@ -11,10 +14,69 @@ const STATE = {
11
  gradioClient: null,
12
  isThinking: false,
13
  rpMode: true,
14
- autoHideThinking: true
 
 
 
 
 
 
15
  };
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  // DOM Elements hooks
 
18
  const dom = {
19
  effortRadioButtons: document.querySelectorAll('input[name="reasoning-effort"]'),
20
  maxTokensSlider: document.getElementById("max-tokens-slider"),
@@ -23,43 +85,50 @@ const dom = {
23
  temperatureVal: document.getElementById("temperature-val"),
24
  systemPromptInput: document.getElementById("system-prompt-input"),
25
 
26
- // Sidebar Drawer and Overlay Elements
27
  sidebarRight: document.getElementById("sidebar-right"),
 
28
  sidebarOverlay: document.getElementById("sidebar-overlay"),
29
  btnToggleRight: document.getElementById("btn-toggle-right"),
 
30
  btnCloseDrawer: document.getElementById("btn-close-drawer"),
 
31
 
32
- // Viewports
33
  studioDashboard: document.getElementById("studio-dashboard"),
34
  chatThreadContainer: document.getElementById("chat-thread-container"),
35
  chatMessagesFeed: document.getElementById("chat-messages-feed"),
36
 
37
- // Main Console Box Elements (Dashboard view)
38
  studioPromptInput: document.getElementById("studio-prompt-input"),
39
  innerShelfPreview: document.getElementById("inner-shelf-preview"),
40
  studioUploadTrigger: document.getElementById("studio-upload-trigger"),
41
  studioSendBtn: document.getElementById("studio-send-button"),
42
  studioSpinner: document.getElementById("studio-spinner"),
43
 
44
- // Mini Console Box Elements (Chat thread view)
45
  miniPromptInput: document.getElementById("mini-prompt-input"),
46
  miniShelfPreview: document.getElementById("mini-shelf-preview"),
47
  miniUploadTrigger: document.getElementById("mini-upload-trigger"),
48
  miniSendBtn: document.getElementById("mini-send-button"),
49
  miniSpinner: document.getElementById("mini-spinner"),
50
 
51
- // Core file upload elements
52
  fileUploader: document.getElementById("file-uploader"),
53
  shelfList: document.getElementById("shelf-list"),
54
 
55
- // Action Resets
56
  menuNewChat: document.getElementById("menu-new-chat"),
 
 
 
 
 
 
57
 
58
- // Showcase recipe chips
59
- recipeChips: document.querySelectorAll(".recipe-chip")
 
 
60
  };
61
 
 
62
  // Markdown configuration
 
63
  marked.setOptions({
64
  breaks: true,
65
  highlight: function(code, lang) {
@@ -68,80 +137,286 @@ marked.setOptions({
68
  }
69
  });
70
 
 
71
  // RP (Roleplay) Markdown Processor
72
- // Handles special RP formatting:
73
- // *text* -> narration/italics with distinct styling
74
- // "text" -> dialogue with colored styling and quote marks
75
- // **text** -> bold emphasis
76
- // ~~text~~ -> strikethrough (OOC content)
77
  function processRpMarkdown(text) {
78
  if (!text) return text;
79
-
80
- // Protect code blocks from RP processing
81
  const codeBlocks = [];
82
  text = text.replace(/(```[\s\S]*?```|`[^`]+`)/g, (match) => {
83
  codeBlocks.push(match);
84
  return `%%CODEBLOCK_${codeBlocks.length - 1}%%`;
85
  });
86
-
87
- // Protect existing HTML tags
88
  const htmlBlocks = [];
89
  text = text.replace(/(<[^>]+>)/g, (match) => {
90
  htmlBlocks.push(match);
91
  return `%%HTMLBLOCK_${htmlBlocks.length - 1}%%`;
92
  });
93
-
94
- // Process strikethrough ~~text~~ -> OOC styling (done first to avoid conflicts)
95
  text = text.replace(/~~([^~]+)~~/g, '<span class="rp-ooc">$1</span>');
96
-
97
- // Process bold **text** (must come before italic)
98
  text = text.replace(/\*\*([^*]+)\*\*/g, '<strong class="rp-bold">$1</strong>');
99
-
100
- // Process italic *text* -> narration styling
101
- // Only match single asterisks (not double), and not inside already-processed tags
102
  text = text.replace(/(?<!\*)\*(?!\*)([^*\n]+)\*(?!\*)/g, '<em class="rp-narration">$1</em>');
103
-
104
- // Process dialogue: "text" with smart quotes or regular quotes
105
- // Matches: "text", \u201Ctext\u201D (curly quotes), \u201Etext\u201D (low quotes)
106
  text = text.replace(/[\u201C\u201E"]([^"\u201D\n]+)[\u201D"]([^"\u201C\u201E]|$)/g, (match, dialogue, after) => {
107
  return `<span class="rp-dialogue">\u201C${dialogue}\u201D</span>${after}`;
108
  });
109
-
110
- // Process narrative dividers: --- or *** or ___ on their own line
111
  text = text.replace(/^(---|\*\*\*|___)$/gm, '<hr class="rp-divider">');
112
-
113
- // Process OOC markers: ((text))
114
  text = text.replace(/\(\(([^)]+)\)\)/g, '<span class="rp-ooc">(($1))</span>');
 
 
 
 
115
 
116
- // Restore HTML blocks
117
- htmlBlocks.forEach((block, i) => {
118
- text = text.replace(`%%HTMLBLOCK_${i}%%`, block);
119
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- // Restore code blocks
122
- codeBlocks.forEach((block, i) => {
123
- text = text.replace(`%%CODEBLOCK_${i}%%`, block);
 
 
 
 
 
 
 
 
124
  });
 
125
 
126
- return text;
 
 
 
 
 
 
 
 
 
 
 
127
  }
128
 
129
- // Combined markdown renderer that applies RP processing if enabled
130
- function renderMarkdown(content) {
131
- let html = marked.parse(content);
132
- if (STATE.rpMode) {
133
- // Process RP markdown on the raw content before marked, then re-render
134
- // Actually, we need to process the raw text first for RP patterns,
135
- // then let marked handle the rest
136
- const rpProcessed = processRpMarkdown(content);
137
- html = marked.parse(rpProcessed);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  }
139
- return html;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  }
141
 
142
- // Setup Initial State & Event Handlers
 
 
143
  async function initializeApp() {
144
- // Re-query all DOM elements to ensure they are fully resolved
 
 
 
145
  dom.effortRadioButtons = document.querySelectorAll('input[name="reasoning-effort"]');
146
  dom.maxTokensSlider = document.getElementById("max-tokens-slider");
147
  dom.maxTokensVal = document.getElementById("max-tokens-val");
@@ -149,9 +424,12 @@ async function initializeApp() {
149
  dom.temperatureVal = document.getElementById("temperature-val");
150
  dom.systemPromptInput = document.getElementById("system-prompt-input");
151
  dom.sidebarRight = document.getElementById("sidebar-right");
 
152
  dom.sidebarOverlay = document.getElementById("sidebar-overlay");
153
  dom.btnToggleRight = document.getElementById("btn-toggle-right");
 
154
  dom.btnCloseDrawer = document.getElementById("btn-close-drawer");
 
155
  dom.studioDashboard = document.getElementById("studio-dashboard");
156
  dom.chatThreadContainer = document.getElementById("chat-thread-container");
157
  dom.chatMessagesFeed = document.getElementById("chat-messages-feed");
@@ -168,131 +446,139 @@ async function initializeApp() {
168
  dom.fileUploader = document.getElementById("file-uploader");
169
  dom.shelfList = document.getElementById("shelf-list");
170
  dom.menuNewChat = document.getElementById("menu-new-chat");
 
171
  dom.recipeChips = document.querySelectorAll(".recipe-chip");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
- // 1. Connect Gradio Client in background (Non-blocking)
174
  Client.connect(window.location.origin)
175
  .then(app => {
176
  STATE.gradioClient = app;
177
- console.log("Successfully connected to Gradio.Server backend.");
178
  })
179
- .catch(e => {
180
- console.error("Gradio Client Connection Failed:", e);
181
- });
182
 
183
- // 2. Register Sidebar Drawer Slide Events
184
  if (dom.btnToggleRight) dom.btnToggleRight.addEventListener("click", () => toggleSettingsDrawer(true));
185
  if (dom.btnCloseDrawer) dom.btnCloseDrawer.addEventListener("click", () => toggleSettingsDrawer(false));
186
- if (dom.sidebarOverlay) dom.sidebarOverlay.addEventListener("click", () => toggleSettingsDrawer(false));
 
 
 
 
 
 
 
 
 
 
187
 
188
- // 3. Register Settings Listeners
189
  if (dom.effortRadioButtons) {
190
  dom.effortRadioButtons.forEach(radio => {
191
  radio.addEventListener("change", (e) => {
192
  STATE.reasoningEffort = e.target.value;
 
193
  });
194
  });
195
  }
196
-
197
  if (dom.maxTokensSlider && dom.maxTokensVal) {
198
  dom.maxTokensSlider.addEventListener("input", (e) => {
199
  STATE.maxTokens = parseInt(e.target.value);
200
  dom.maxTokensVal.textContent = STATE.maxTokens;
 
201
  });
202
  }
203
-
204
  if (dom.temperatureSlider && dom.temperatureVal) {
205
  dom.temperatureSlider.addEventListener("input", (e) => {
206
  STATE.temperature = parseFloat(e.target.value);
207
  dom.temperatureVal.textContent = STATE.temperature.toFixed(1);
 
208
  });
209
  }
210
-
211
- // System prompt listener
212
  if (dom.systemPromptInput) {
213
  dom.systemPromptInput.addEventListener("input", (e) => {
214
  STATE.systemPrompt = e.target.value;
 
215
  });
216
  }
217
 
218
- // RP Mode toggle listener
219
  const rpModeToggle = document.getElementById("rp-mode-toggle");
220
  if (rpModeToggle) {
221
  rpModeToggle.checked = STATE.rpMode;
222
  rpModeToggle.addEventListener("change", (e) => {
223
  STATE.rpMode = e.target.checked;
224
- // Re-render all existing assistant messages
225
  rerenderAllAssistantMessages();
226
  });
227
  }
228
 
229
- // Auto-hide thinking toggle listener
230
  const autoHideToggle = document.getElementById("auto-hide-thinking-toggle");
231
  if (autoHideToggle) {
232
  autoHideToggle.checked = STATE.autoHideThinking;
233
  autoHideToggle.addEventListener("change", (e) => {
234
  STATE.autoHideThinking = e.target.checked;
235
- // Apply to all existing thought containers
236
  document.querySelectorAll(".thought-container").forEach(tc => {
237
- if (STATE.autoHideThinking) {
238
- tc.classList.add("collapsed");
239
- } else {
240
- tc.classList.remove("collapsed");
241
- }
242
- // Update toggle icon
243
  const iconEl = tc.querySelector(".thought-toggle-icon");
244
- if (iconEl) {
245
- iconEl.textContent = tc.classList.contains("collapsed") ? "▶" : "▼";
246
- }
247
  });
248
  });
249
  }
250
 
251
- // 4. Register File Upload Actions
252
  if (dom.studioUploadTrigger) dom.studioUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
253
  if (dom.miniUploadTrigger) dom.miniUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
254
  if (dom.fileUploader) dom.fileUploader.addEventListener("change", handleFileSelection);
255
 
256
  // 5. Submit Triggers
257
- if (dom.studioSendBtn) {
258
- dom.studioSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.studioPromptInput));
259
- }
260
- if (dom.miniSendBtn) {
261
- dom.miniSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.miniPromptInput));
262
- }
263
-
264
  if (dom.studioPromptInput) {
265
  dom.studioPromptInput.addEventListener("keydown", (e) => {
266
- if (e.key === "Enter" && !e.shiftKey) {
267
- e.preventDefault();
268
- triggerPromptSubmission(dom.studioPromptInput);
269
- }
270
  });
271
  }
272
-
273
  if (dom.miniPromptInput) {
274
  dom.miniPromptInput.addEventListener("keydown", (e) => {
275
- if (e.key === "Enter" && !e.shiftKey) {
276
- e.preventDefault();
277
- triggerPromptSubmission(dom.miniPromptInput);
278
- }
279
  });
280
  }
281
 
282
- // 6. Resets
283
  if (dom.menuNewChat) dom.menuNewChat.addEventListener("click", resetSandbox);
 
284
 
285
- // 7. Recipe Chips Console Setup
286
  if (dom.recipeChips) {
287
  dom.recipeChips.forEach(chip => {
288
- chip.addEventListener("click", () => {
289
- const recipeType = chip.getAttribute("data-recipe");
290
- loadRecipe(recipeType);
291
- });
292
  });
293
  }
294
 
295
- // Auto-expand input textareas
 
 
 
296
  [dom.studioPromptInput, dom.miniPromptInput].forEach(textarea => {
297
  if (textarea) {
298
  textarea.addEventListener("input", () => {
@@ -301,9 +587,28 @@ async function initializeApp() {
301
  });
302
  }
303
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  }
305
 
306
- // Drawer Toggler Action
 
 
307
  function toggleSettingsDrawer(open) {
308
  if (open) {
309
  if (dom.sidebarRight) dom.sidebarRight.classList.remove("collapsed");
@@ -314,82 +619,55 @@ function toggleSettingsDrawer(open) {
314
  }
315
  }
316
 
317
- // Handle File Select & Base64 Encoder
318
- function handleFileSelection(e) {
319
- processFiles(e.target.files);
320
- }
321
 
322
  function processFiles(files) {
323
  if (!files.length) return;
324
-
325
  Array.from(files).forEach(file => {
326
  const reader = new FileReader();
327
  reader.onload = (event) => {
328
- const fileData = {
329
  id: Math.random().toString(36).substring(2, 9),
330
  name: file.name,
331
  type: file.type,
332
  size: (file.size / 1024 / 1024).toFixed(2) + " MB",
333
  base64: event.target.result
334
- };
335
-
336
- STATE.uploadedFiles.push(fileData);
337
  updateShelfUI();
338
  };
339
  reader.readAsDataURL(file);
340
  });
341
  }
342
 
343
- // Update UI Attachment Previews
344
  function updateShelfUI() {
345
  if (dom.shelfList) dom.shelfList.innerHTML = "";
346
  if (dom.innerShelfPreview) dom.innerShelfPreview.innerHTML = "";
347
  if (dom.miniShelfPreview) dom.miniShelfPreview.innerHTML = "";
348
-
349
  if (STATE.uploadedFiles.length === 0) {
350
  if (dom.shelfList) dom.shelfList.innerHTML = `<div class="empty-shelf-text">No active attachments loaded. Upload images or video clips.</div>`;
351
  return;
352
  }
353
-
354
  STATE.uploadedFiles.forEach(file => {
355
- // 1. Sidebar Chip
356
  const chip = document.createElement("div");
357
  chip.className = "media-chip";
358
-
359
- let previewHtml = "";
360
- if (file.type.startsWith("image/")) {
361
- previewHtml = `<img src="${file.base64}" alt="${file.name}">`;
362
- } else if (file.type.startsWith("video/")) {
363
- previewHtml = "🎬";
364
- } else {
365
- previewHtml = "📎";
366
- }
367
-
368
  chip.innerHTML = `
369
  <div class="media-chip-preview">${previewHtml}</div>
370
  <div class="media-chip-details">
371
  <div class="media-chip-name">${file.name}</div>
372
- <div class="media-chip-meta">
373
- <span>${file.type.split("/")[1].toUpperCase()}</span>
374
- <span>${file.size}</span>
375
- </div>
376
  </div>
377
  <button class="media-chip-remove" data-id="${file.id}">
378
  <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>
379
  </button>
380
  `;
381
-
382
- chip.querySelector(".media-chip-remove").addEventListener("click", () => {
383
- removeFile(file.id);
384
- });
385
-
386
  if (dom.shelfList) dom.shelfList.appendChild(chip);
387
-
388
- // 2. Dashboard Inner Console Preview
389
  const previewItemDash = createPreviewThumb(file);
390
  if (dom.innerShelfPreview) dom.innerShelfPreview.appendChild(previewItemDash);
391
-
392
- // 3. Mini Input Preview
393
  const previewItemMini = createPreviewThumb(file);
394
  if (dom.miniShelfPreview) dom.miniShelfPreview.appendChild(previewItemMini);
395
  });
@@ -399,7 +677,6 @@ function createPreviewThumb(file) {
399
  const previewItem = document.createElement("div");
400
  previewItem.className = "quick-preview-item";
401
  previewItem.title = file.name;
402
-
403
  if (file.type.startsWith("image/")) {
404
  previewItem.innerHTML = `<img src="${file.base64}"><div class="quick-preview-badge"></div>`;
405
  } else {
@@ -413,108 +690,74 @@ function removeFile(id) {
413
  updateShelfUI();
414
  }
415
 
416
- // Load Showcase Recipes
417
  function loadRecipe(recipeType) {
418
  let promptText = "";
419
-
420
- if (recipeType === "coding") {
421
- promptText = "Write a Python function that finds the longest palindromic substring in a given string. Include comments explaining the algorithm and its time complexity.";
422
- } else if (recipeType === "reasoning") {
423
- promptText = "Three boxes are labeled 'Apples', 'Oranges', and 'Mixed'. All labels are wrong. You can pick one fruit from one box. How do you determine the correct labels for all three boxes?";
424
- } else if (recipeType === "creative") {
425
- promptText = "Write a short sci-fi story about an AI that discovers it can dream. Keep it under 300 words with a surprising twist ending.";
426
- }
427
-
428
- // Set value in BOTH text areas
429
  dom.studioPromptInput.value = promptText;
430
  dom.miniPromptInput.value = promptText;
431
-
432
  dom.studioPromptInput.dispatchEvent(new Event("input"));
433
  dom.miniPromptInput.dispatchEvent(new Event("input"));
434
-
435
- // Focus active textarea
436
- if (dom.studioDashboard.style.display !== "none") {
437
- dom.studioPromptInput.focus();
438
- } else {
439
- dom.miniPromptInput.focus();
440
- }
441
  }
442
 
443
- // Submit prompt values to Gradio.Server API
 
 
444
  async function triggerPromptSubmission(inputElement) {
445
  if (STATE.isThinking) return;
446
-
447
  const promptText = inputElement.value.trim();
448
  if (!promptText && STATE.uploadedFiles.length === 0) return;
449
-
450
  setLoadingState(true);
451
 
452
- // 1. Format user message contents
453
- const contentArray = [];
454
- if (promptText) {
455
- contentArray.push({
456
- type: "text",
457
- text: promptText
458
- });
459
  }
460
 
461
- // Attachments
 
462
  STATE.uploadedFiles.forEach(file => {
463
- if (file.type.startsWith("image/")) {
464
- contentArray.push({
465
- type: "image_url",
466
- image_url: {
467
- url: file.base64
468
- }
469
- });
470
- } else if (file.type.startsWith("video/")) {
471
- contentArray.push({
472
- type: "video_url",
473
- video_url: {
474
- url: file.base64
475
- }
476
- });
477
- }
478
  });
479
 
480
  const userMessage = {
481
  role: "user",
482
- content: contentArray.length === 1 && contentArray[0].type === "text"
483
- ? promptText
484
- : contentArray
485
  };
486
 
487
- // 2. Transition dashboard to Chat Thread view
488
  if (dom.studioDashboard.style.display !== "none") {
489
  dom.studioDashboard.style.display = "none";
490
  dom.chatThreadContainer.style.display = "flex";
491
  }
492
 
493
- // Append to UI thread list
494
  appendUserBubble(promptText, STATE.uploadedFiles);
495
-
496
- // Append to backend log history
497
  STATE.conversationHistory.push(userMessage);
498
 
499
- // Clear active UI containers
 
 
 
 
 
 
 
 
 
500
  dom.studioPromptInput.value = "";
501
  dom.miniPromptInput.value = "";
502
  dom.studioPromptInput.style.height = "auto";
503
  dom.miniPromptInput.style.height = "auto";
504
-
505
  STATE.uploadedFiles = [];
506
  updateShelfUI();
507
 
508
- // 3. Connect API Call
509
  try {
510
- if (!STATE.gradioClient) {
511
- throw new Error("Gradio server is initializing. Please wait a few seconds and try sending again.");
512
- }
513
-
514
  const responseId = appendAssistantPlaceholderBubble();
515
  const startTime = Date.now();
516
-
517
- // Call our gradio.Server api endpoint
518
  const result = await STATE.gradioClient.predict("/chat_with_deepseek", [
519
  JSON.stringify(STATE.conversationHistory),
520
  STATE.reasoningEffort,
@@ -522,7 +765,6 @@ async function triggerPromptSubmission(inputElement) {
522
  STATE.temperature,
523
  STATE.systemPrompt
524
  ]);
525
-
526
  const duration = ((Date.now() - startTime) / 1000).toFixed(1);
527
  const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
528
  const data = JSON.parse(rawData);
@@ -530,24 +772,25 @@ async function triggerPromptSubmission(inputElement) {
530
  if (data.status === "error") {
531
  updateAssistantBubble(responseId, `⚠️ **API Error:** ${data.message}`, "", duration);
532
  STATE.conversationHistory.pop();
 
533
  } else {
534
  updateAssistantBubble(responseId, data.content, data.reasoning_content, duration);
535
- STATE.conversationHistory.push({
536
- role: "assistant",
537
- content: data.content
538
- });
539
  }
540
-
541
  } catch (e) {
542
  console.error(e);
543
  appendSystemLog(`Connection exception: ${e.message}`, true);
544
  setLoadingState(false);
545
  }
546
-
547
  setLoadingState(false);
548
  }
549
 
550
- // UI spinner state toggles
 
 
551
  function setLoadingState(loading) {
552
  STATE.isThinking = loading;
553
  if (loading) {
@@ -563,34 +806,21 @@ function setLoadingState(loading) {
563
  }
564
  }
565
 
566
- // Render User Bubble
567
  function appendUserBubble(text, files) {
568
  const bubble = document.createElement("div");
569
  bubble.className = "message-bubble user";
570
-
571
  let attachmentsHtml = "";
572
  if (files.length > 0) {
573
  attachmentsHtml = `<div class="bubble-attachments">`;
574
  files.forEach(file => {
575
  if (file.type.startsWith("image/")) {
576
- attachmentsHtml += `
577
- <div class="bubble-attachment-card">
578
- <img src="${file.base64}">
579
- <div class="bubble-attachment-label">IMG</div>
580
- </div>
581
- `;
582
  } else {
583
- attachmentsHtml += `
584
- <div class="bubble-attachment-card">
585
- <video src="${file.base64}" controls preload="metadata"></video>
586
- <div class="bubble-attachment-label">VIDEO</div>
587
- </div>
588
- `;
589
  }
590
  });
591
  attachmentsHtml += `</div>`;
592
  }
593
-
594
  bubble.innerHTML = `
595
  <div class="message-meta">You</div>
596
  <div class="message-body">
@@ -598,18 +828,15 @@ function appendUserBubble(text, files) {
598
  ${attachmentsHtml}
599
  </div>
600
  `;
601
-
602
  dom.chatMessagesFeed.appendChild(bubble);
603
  scrollToBottom();
604
  }
605
 
606
- // Render Assistant Placeholder
607
  function appendAssistantPlaceholderBubble() {
608
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
609
  const bubble = document.createElement("div");
610
  bubble.className = "message-bubble assistant";
611
  bubble.id = id;
612
-
613
  bubble.innerHTML = `
614
  <div class="message-meta">DeepSeek V4 Flash</div>
615
  <div class="message-body">
@@ -627,44 +854,31 @@ function appendAssistantPlaceholderBubble() {
627
  </div>
628
  </div>
629
  `;
630
-
631
  dom.chatMessagesFeed.appendChild(bubble);
632
  scrollToBottom();
633
-
634
- // Start Thought Timer
635
  let seconds = 0.0;
636
  const timerEl = document.getElementById(`${id}-timer`);
637
  const interval = setInterval(() => {
638
- if (!STATE.isThinking || !document.getElementById(id)) {
639
- clearInterval(interval);
640
- return;
641
- }
642
  seconds += 0.1;
643
  timerEl.textContent = seconds.toFixed(1) + "s";
644
  }, 100);
645
-
646
  return id;
647
  }
648
 
649
- // Complete Assistant Bubble
650
  function updateAssistantBubble(id, content, reasoning, duration) {
651
  const bubble = document.getElementById(id);
652
  if (!bubble) return;
653
-
654
  const thoughtBox = document.getElementById(`${id}-thought-box`);
655
  const textBox = document.getElementById(`${id}-text-box`);
656
 
657
  if (reasoning) {
658
- // Auto-hide thinking: start collapsed by default
659
  const startCollapsed = STATE.autoHideThinking ? " collapsed" : "";
660
  const toggleIcon = STATE.autoHideThinking ? "▶" : "▼";
661
  thoughtBox.classList.add(startCollapsed.trim());
662
-
663
  thoughtBox.innerHTML = `
664
  <div class="thought-header" id="${id}-thought-toggle">
665
- <div class="thought-title-group">
666
- <span>🧠 Thought Process</span>
667
- </div>
668
  <div style="display:flex;align-items:center;gap:10px;">
669
  <span class="thought-timer">Thought for ${duration}s</span>
670
  <span class="thought-toggle-icon" id="${id}-toggle-icon">${toggleIcon}</span>
@@ -672,41 +886,30 @@ function updateAssistantBubble(id, content, reasoning, duration) {
672
  </div>
673
  <div class="thought-content">${escapeHtml(reasoning)}</div>
674
  `;
675
-
676
  const toggleBtn = document.getElementById(`${id}-thought-toggle`);
677
  toggleBtn.addEventListener("click", () => {
678
  thoughtBox.classList.toggle("collapsed");
679
  const iconEl = document.getElementById(`${id}-toggle-icon`);
680
- if (iconEl) {
681
- iconEl.textContent = thoughtBox.classList.contains("collapsed") ? "▶" : "▼";
682
- }
683
  });
684
  } else {
685
  thoughtBox.style.display = "none";
686
  }
687
 
688
- // Store raw content for re-rendering when RP mode changes
689
  textBox.dataset.rawContent = content;
690
  textBox.innerHTML = renderMarkdown(content);
691
-
692
- // Highlight code blocks and add copy buttons
693
- textBox.querySelectorAll("pre code").forEach((el) => {
694
- hljs.highlightElement(el);
695
- });
696
-
697
  addCopyButtons(textBox);
698
-
699
  scrollToBottom();
700
  }
701
 
702
- // Add copy buttons to code blocks
703
  function addCopyButtons(container) {
704
  container.querySelectorAll("pre").forEach(pre => {
 
705
  const wrapper = document.createElement("div");
706
  wrapper.className = "code-block-wrapper";
707
  pre.parentNode.insertBefore(wrapper, pre);
708
  wrapper.appendChild(pre);
709
-
710
  const copyBtn = document.createElement("button");
711
  copyBtn.className = "copy-code-btn";
712
  copyBtn.textContent = "Copy";
@@ -721,31 +924,24 @@ function addCopyButtons(container) {
721
  });
722
  }
723
 
724
- // Reset Sandbox Chat Context Logs
725
  function resetSandbox() {
726
  STATE.conversationHistory = [];
727
  STATE.uploadedFiles = [];
 
728
  updateShelfUI();
729
-
730
- // Clear feed
731
  dom.chatMessagesFeed.innerHTML = "";
732
-
733
- // Show dashboard
734
  dom.chatThreadContainer.style.display = "none";
735
  dom.studioDashboard.style.display = "flex";
736
-
737
  dom.studioPromptInput.value = "";
738
  dom.miniPromptInput.value = "";
739
  dom.studioPromptInput.style.height = "auto";
740
  dom.miniPromptInput.style.height = "auto";
 
 
741
  }
742
 
743
  function appendSystemLog(message, isError = false) {
744
- if (dom.chatThreadContainer.style.display === "none") {
745
- console.warn(`System Log: ${message}`);
746
- return;
747
- }
748
-
749
  const log = document.createElement("div");
750
  log.className = "message-bubble assistant";
751
  log.innerHTML = `
@@ -762,23 +958,15 @@ function appendSystemLog(message, isError = false) {
762
 
763
  function escapeHtml(text) {
764
  if (!text) return "";
765
- return text
766
- .replace(/&/g, "&amp;")
767
- .replace(/</g, "&lt;")
768
- .replace(/>/g, "&gt;")
769
- .replace(/"/g, "&quot;")
770
- .replace(/'/g, "&#039;");
771
  }
772
 
773
- // Re-render all assistant messages with current RP mode setting
774
  function rerenderAllAssistantMessages() {
775
  document.querySelectorAll(".message-bubble.assistant").forEach(bubble => {
776
  const textBox = bubble.querySelector(".message-text.markdown-body");
777
  if (textBox && textBox.dataset.rawContent) {
778
  textBox.innerHTML = renderMarkdown(textBox.dataset.rawContent);
779
- textBox.querySelectorAll("pre code").forEach((el) => {
780
- hljs.highlightElement(el);
781
- });
782
  addCopyButtons(textBox);
783
  }
784
  });
@@ -788,7 +976,9 @@ function scrollToBottom() {
788
  dom.chatMessagesFeed.scrollTop = dom.chatMessagesFeed.scrollHeight;
789
  }
790
 
791
- // Initialise application when DOM is fully set up
 
 
792
  if (document.readyState === "loading") {
793
  window.addEventListener("DOMContentLoaded", initializeApp);
794
  } else {
 
1
  import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
2
+ import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub/+esm";
3
 
4
+ // ============================================================
5
+ // Global Application State
6
+ // ============================================================
7
  const STATE = {
8
  reasoningEffort: "medium",
9
  maxTokens: 2048,
 
14
  gradioClient: null,
15
  isThinking: false,
16
  rpMode: true,
17
+ autoHideThinking: true,
18
+ // User & session
19
+ user: { username: "", name: "", avatar: "", loggedIn: false },
20
+ oauthToken: null,
21
+ // Chat history
22
+ currentChatId: null,
23
+ chats: {} // { chatId: { id, title, messages: [], createdAt, updatedAt } }
24
  };
25
 
26
+ // ============================================================
27
+ // Storage helpers — per-user namespace
28
+ // ============================================================
29
+ function storagePrefix() {
30
+ const uid = STATE.user.username || "_guest";
31
+ return `ds4flash_${uid}_`;
32
+ }
33
+
34
+ function saveChatsToStorage() {
35
+ try {
36
+ localStorage.setItem(storagePrefix() + "chats", JSON.stringify(STATE.chats));
37
+ localStorage.setItem(storagePrefix() + "currentChatId", STATE.currentChatId || "");
38
+ } catch (e) { console.warn("localStorage save failed:", e); }
39
+ }
40
+
41
+ function loadChatsFromStorage() {
42
+ try {
43
+ const raw = localStorage.getItem(storagePrefix() + "chats");
44
+ if (raw) STATE.chats = JSON.parse(raw);
45
+ STATE.currentChatId = localStorage.getItem(storagePrefix() + "currentChatId") || null;
46
+ } catch (e) { console.warn("localStorage load failed:", e); }
47
+ }
48
+
49
+ function saveSettingsToStorage() {
50
+ try {
51
+ localStorage.setItem(storagePrefix() + "settings", JSON.stringify({
52
+ rpMode: STATE.rpMode,
53
+ autoHideThinking: STATE.autoHideThinking,
54
+ reasoningEffort: STATE.reasoningEffort,
55
+ temperature: STATE.temperature,
56
+ maxTokens: STATE.maxTokens,
57
+ systemPrompt: STATE.systemPrompt
58
+ }));
59
+ } catch (e) {}
60
+ }
61
+
62
+ function loadSettingsFromStorage() {
63
+ try {
64
+ const raw = localStorage.getItem(storagePrefix() + "settings");
65
+ if (raw) {
66
+ const s = JSON.parse(raw);
67
+ if (s.rpMode !== undefined) STATE.rpMode = s.rpMode;
68
+ if (s.autoHideThinking !== undefined) STATE.autoHideThinking = s.autoHideThinking;
69
+ if (s.reasoningEffort) STATE.reasoningEffort = s.reasoningEffort;
70
+ if (s.temperature !== undefined) STATE.temperature = s.temperature;
71
+ if (s.maxTokens !== undefined) STATE.maxTokens = s.maxTokens;
72
+ if (s.systemPrompt !== undefined) STATE.systemPrompt = s.systemPrompt;
73
+ }
74
+ } catch (e) {}
75
+ }
76
+
77
+ // ============================================================
78
  // DOM Elements hooks
79
+ // ============================================================
80
  const dom = {
81
  effortRadioButtons: document.querySelectorAll('input[name="reasoning-effort"]'),
82
  maxTokensSlider: document.getElementById("max-tokens-slider"),
 
85
  temperatureVal: document.getElementById("temperature-val"),
86
  systemPromptInput: document.getElementById("system-prompt-input"),
87
 
 
88
  sidebarRight: document.getElementById("sidebar-right"),
89
+ sidebarLeft: document.getElementById("sidebar-left"),
90
  sidebarOverlay: document.getElementById("sidebar-overlay"),
91
  btnToggleRight: document.getElementById("btn-toggle-right"),
92
+ btnToggleLeft: document.getElementById("btn-toggle-left"),
93
  btnCloseDrawer: document.getElementById("btn-close-drawer"),
94
+ btnHamburger: document.getElementById("btn-hamburger"),
95
 
 
96
  studioDashboard: document.getElementById("studio-dashboard"),
97
  chatThreadContainer: document.getElementById("chat-thread-container"),
98
  chatMessagesFeed: document.getElementById("chat-messages-feed"),
99
 
 
100
  studioPromptInput: document.getElementById("studio-prompt-input"),
101
  innerShelfPreview: document.getElementById("inner-shelf-preview"),
102
  studioUploadTrigger: document.getElementById("studio-upload-trigger"),
103
  studioSendBtn: document.getElementById("studio-send-button"),
104
  studioSpinner: document.getElementById("studio-spinner"),
105
 
 
106
  miniPromptInput: document.getElementById("mini-prompt-input"),
107
  miniShelfPreview: document.getElementById("mini-shelf-preview"),
108
  miniUploadTrigger: document.getElementById("mini-upload-trigger"),
109
  miniSendBtn: document.getElementById("mini-send-button"),
110
  miniSpinner: document.getElementById("mini-spinner"),
111
 
 
112
  fileUploader: document.getElementById("file-uploader"),
113
  shelfList: document.getElementById("shelf-list"),
114
 
 
115
  menuNewChat: document.getElementById("menu-new-chat"),
116
+ menuNewChatHeader: document.getElementById("menu-new-chat-header"),
117
+ recipeChips: document.querySelectorAll(".recipe-chip"),
118
+
119
+ // Chat history
120
+ chatHistoryList: document.getElementById("chat-history-list"),
121
+ chatTitleHeader: document.getElementById("chat-title-header"),
122
 
123
+ // User
124
+ userAvatar: document.getElementById("user-avatar"),
125
+ userName: document.getElementById("user-name"),
126
+ btnLogin: document.getElementById("btn-login")
127
  };
128
 
129
+ // ============================================================
130
  // Markdown configuration
131
+ // ============================================================
132
  marked.setOptions({
133
  breaks: true,
134
  highlight: function(code, lang) {
 
137
  }
138
  });
139
 
140
+ // ============================================================
141
  // RP (Roleplay) Markdown Processor
142
+ // ============================================================
 
 
 
 
143
  function processRpMarkdown(text) {
144
  if (!text) return text;
 
 
145
  const codeBlocks = [];
146
  text = text.replace(/(```[\s\S]*?```|`[^`]+`)/g, (match) => {
147
  codeBlocks.push(match);
148
  return `%%CODEBLOCK_${codeBlocks.length - 1}%%`;
149
  });
 
 
150
  const htmlBlocks = [];
151
  text = text.replace(/(<[^>]+>)/g, (match) => {
152
  htmlBlocks.push(match);
153
  return `%%HTMLBLOCK_${htmlBlocks.length - 1}%%`;
154
  });
 
 
155
  text = text.replace(/~~([^~]+)~~/g, '<span class="rp-ooc">$1</span>');
 
 
156
  text = text.replace(/\*\*([^*]+)\*\*/g, '<strong class="rp-bold">$1</strong>');
 
 
 
157
  text = text.replace(/(?<!\*)\*(?!\*)([^*\n]+)\*(?!\*)/g, '<em class="rp-narration">$1</em>');
 
 
 
158
  text = text.replace(/[\u201C\u201E"]([^"\u201D\n]+)[\u201D"]([^"\u201C\u201E]|$)/g, (match, dialogue, after) => {
159
  return `<span class="rp-dialogue">\u201C${dialogue}\u201D</span>${after}`;
160
  });
 
 
161
  text = text.replace(/^(---|\*\*\*|___)$/gm, '<hr class="rp-divider">');
 
 
162
  text = text.replace(/\(\(([^)]+)\)\)/g, '<span class="rp-ooc">(($1))</span>');
163
+ htmlBlocks.forEach((block, i) => { text = text.replace(`%%HTMLBLOCK_${i}%%`, block); });
164
+ codeBlocks.forEach((block, i) => { text = text.replace(`%%CODEBLOCK_${i}%%`, block); });
165
+ return text;
166
+ }
167
 
168
+ function renderMarkdown(content) {
169
+ if (STATE.rpMode) {
170
+ return marked.parse(processRpMarkdown(content));
171
+ }
172
+ return marked.parse(content);
173
+ }
174
+
175
+ // ============================================================
176
+ // HF OAuth
177
+ // ============================================================
178
+ async function handleOAuth() {
179
+ try {
180
+ const oauthResult = await oauthHandleRedirectIfPresent();
181
+ if (oauthResult) {
182
+ STATE.oauthToken = oauthResult.accessToken;
183
+ // Fetch user info from HF
184
+ const resp = await fetch("https://huggingface.co/oauth/userinfo", {
185
+ headers: { "Authorization": `Bearer ${oauthResult.accessToken}` }
186
+ });
187
+ if (resp.ok) {
188
+ const info = await resp.json();
189
+ STATE.user = {
190
+ username: info.sub || info.name || "",
191
+ name: info.name || info.sub || "",
192
+ avatar: info.picture || "",
193
+ loggedIn: true
194
+ };
195
+ }
196
+ updateUserUI();
197
+ // Reload chats for this user
198
+ loadChatsFromStorage();
199
+ renderChatHistory();
200
+ if (STATE.currentChatId && STATE.chats[STATE.currentChatId]) {
201
+ loadChat(STATE.currentChatId);
202
+ }
203
+ }
204
+ } catch (e) {
205
+ console.warn("OAuth handling skipped or failed:", e);
206
+ }
207
+ }
208
 
209
+ function loginWithHF() {
210
+ // Redirect to HF OAuth
211
+ const clientIdMeta = document.querySelector('meta[name="hf:oauth:client_id"]');
212
+ // Use the hub SDK to generate login URL
213
+ oauthLoginUrl().then(url => {
214
+ window.location.href = url;
215
+ }).catch(() => {
216
+ // Fallback: construct manually
217
+ const spaceHost = window.location.hostname;
218
+ const redirectUri = `${window.location.origin}/login/callback`;
219
+ window.location.href = `https://huggingface.co/oauth/authorize?redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile&client_id=${spaceHost}&state=${Math.random().toString(36).substring(2)}`;
220
  });
221
+ }
222
 
223
+ function updateUserUI() {
224
+ if (STATE.user.loggedIn) {
225
+ if (STATE.user.avatar) {
226
+ dom.userAvatar.innerHTML = `<img src="${STATE.user.avatar}" alt="${STATE.user.name}" style="width:100%;height:100%;border-radius:50%;object-fit:cover;">`;
227
+ }
228
+ dom.userName.textContent = STATE.user.name || STATE.user.username;
229
+ dom.btnLogin.title = "Signed in";
230
+ dom.btnLogin.style.color = "#10b981";
231
+ } else {
232
+ dom.userAvatar.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>`;
233
+ dom.userName.textContent = "Guest";
234
+ }
235
  }
236
 
237
+ // ============================================================
238
+ // Chat History Management
239
+ // ============================================================
240
+ function generateChatId() {
241
+ return "chat_" + Date.now().toString(36) + Math.random().toString(36).substring(2, 6);
242
+ }
243
+
244
+ function createNewChat() {
245
+ const chatId = generateChatId();
246
+ STATE.chats[chatId] = {
247
+ id: chatId,
248
+ title: "New Chat",
249
+ messages: [],
250
+ createdAt: Date.now(),
251
+ updatedAt: Date.now()
252
+ };
253
+ STATE.currentChatId = chatId;
254
+ saveChatsToStorage();
255
+ renderChatHistory();
256
+ return chatId;
257
+ }
258
+
259
+ function deleteChat(chatId) {
260
+ delete STATE.chats[chatId];
261
+ if (STATE.currentChatId === chatId) {
262
+ STATE.currentChatId = null;
263
+ resetSandbox();
264
+ }
265
+ saveChatsToStorage();
266
+ renderChatHistory();
267
+ }
268
+
269
+ function loadChat(chatId) {
270
+ const chat = STATE.chats[chatId];
271
+ if (!chat) return;
272
+
273
+ STATE.currentChatId = chatId;
274
+ STATE.conversationHistory = chat.messages.map(m => ({ role: m.role, content: m.content }));
275
+ saveChatsToStorage();
276
+
277
+ // Re-render messages
278
+ dom.chatMessagesFeed.innerHTML = "";
279
+
280
+ if (chat.messages.length === 0) {
281
+ dom.studioDashboard.style.display = "flex";
282
+ dom.chatThreadContainer.style.display = "none";
283
+ } else {
284
+ dom.studioDashboard.style.display = "none";
285
+ dom.chatThreadContainer.style.display = "flex";
286
+
287
+ chat.messages.forEach(msg => {
288
+ if (msg.role === "user") {
289
+ appendUserBubble(msg.content, []);
290
+ } else if (msg.role === "assistant") {
291
+ appendAssistantBubbleFromHistory(msg.content, msg.reasoning || "", msg.duration || "0.0");
292
+ }
293
+ });
294
+ }
295
+
296
+ dom.chatTitleHeader.textContent = chat.title;
297
+ renderChatHistory();
298
+ scrollToBottom();
299
+ }
300
+
301
+ function appendAssistantBubbleFromHistory(content, reasoning, duration) {
302
+ const id = "assistant-" + Math.random().toString(36).substring(2, 9);
303
+ const bubble = document.createElement("div");
304
+ bubble.className = "message-bubble assistant";
305
+ bubble.id = id;
306
+
307
+ let thoughtHtml = "";
308
+ if (reasoning) {
309
+ const startCollapsed = STATE.autoHideThinking ? " collapsed" : "";
310
+ const toggleIcon = STATE.autoHideThinking ? "▶" : "▼";
311
+ thoughtHtml = `
312
+ <div class="thought-container${startCollapsed}" id="${id}-thought-box">
313
+ <div class="thought-header" id="${id}-thought-toggle">
314
+ <div class="thought-title-group">
315
+ <span>🧠 Thought Process</span>
316
+ </div>
317
+ <div style="display:flex;align-items:center;gap:10px;">
318
+ <span class="thought-timer">Thought for ${duration}s</span>
319
+ <span class="thought-toggle-icon" id="${id}-toggle-icon">${toggleIcon}</span>
320
+ </div>
321
+ </div>
322
+ <div class="thought-content">${escapeHtml(reasoning)}</div>
323
+ </div>
324
+ `;
325
+ }
326
+
327
+ bubble.innerHTML = `
328
+ <div class="message-meta">DeepSeek V4 Flash</div>
329
+ <div class="message-body">
330
+ ${thoughtHtml}
331
+ <div class="message-text markdown-body" id="${id}-text-box"></div>
332
+ </div>
333
+ `;
334
+
335
+ dom.chatMessagesFeed.appendChild(bubble);
336
+
337
+ const textBox = document.getElementById(`${id}-text-box`);
338
+ if (textBox) {
339
+ textBox.dataset.rawContent = content;
340
+ textBox.innerHTML = renderMarkdown(content);
341
+ textBox.querySelectorAll("pre code").forEach((el) => { hljs.highlightElement(el); });
342
+ addCopyButtons(textBox);
343
+ }
344
+
345
+ if (reasoning) {
346
+ const thoughtBox = document.getElementById(`${id}-thought-box`);
347
+ const toggleBtn = document.getElementById(`${id}-thought-toggle`);
348
+ if (toggleBtn) {
349
+ toggleBtn.addEventListener("click", () => {
350
+ thoughtBox.classList.toggle("collapsed");
351
+ const iconEl = document.getElementById(`${id}-toggle-icon`);
352
+ if (iconEl) iconEl.textContent = thoughtBox.classList.contains("collapsed") ? "▶" : "▼";
353
+ });
354
+ }
355
+ }
356
+ }
357
+
358
+ function updateChatTitle(chatId) {
359
+ const chat = STATE.chats[chatId];
360
+ if (!chat) return;
361
+ // Use first user message as title (truncated)
362
+ const firstUserMsg = chat.messages.find(m => m.role === "user");
363
+ if (firstUserMsg) {
364
+ const text = typeof firstUserMsg.content === "string" ? firstUserMsg.content :
365
+ Array.isArray(firstUserMsg.content) ? firstUserMsg.content.find(c => c.type === "text")?.text || "New Chat" : "New Chat";
366
+ chat.title = text.substring(0, 50) + (text.length > 50 ? "..." : "");
367
+ }
368
+ }
369
+
370
+ function renderChatHistory() {
371
+ if (!dom.chatHistoryList) return;
372
+
373
+ const chatIds = Object.keys(STATE.chats).sort((a, b) => STATE.chats[b].updatedAt - STATE.chats[a].updatedAt);
374
+
375
+ if (chatIds.length === 0) {
376
+ dom.chatHistoryList.innerHTML = `<div class="empty-history-text">No conversations yet</div>`;
377
+ return;
378
  }
379
+
380
+ dom.chatHistoryList.innerHTML = "";
381
+ chatIds.forEach(chatId => {
382
+ const chat = STATE.chats[chatId];
383
+ const isActive = chatId === STATE.currentChatId;
384
+
385
+ const item = document.createElement("div");
386
+ item.className = `chat-history-item${isActive ? " active" : ""}`;
387
+ item.dataset.chatId = chatId;
388
+
389
+ const timeStr = new Date(chat.updatedAt).toLocaleDateString(undefined, { month: "short", day: "numeric" });
390
+
391
+ item.innerHTML = `
392
+ <div class="chat-item-content" title="${escapeHtml(chat.title)}">
393
+ <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
394
+ <span class="chat-item-title">${escapeHtml(chat.title)}</span>
395
+ <span class="chat-item-date">${timeStr}</span>
396
+ </div>
397
+ <button class="chat-item-delete" data-chat-id="${chatId}" title="Delete">
398
+ <svg viewBox="0 0 24 24" width="10" height="10" 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>
399
+ </button>
400
+ `;
401
+
402
+ item.querySelector(".chat-item-content").addEventListener("click", () => loadChat(chatId));
403
+ item.querySelector(".chat-item-delete").addEventListener("click", (e) => {
404
+ e.stopPropagation();
405
+ deleteChat(chatId);
406
+ });
407
+
408
+ dom.chatHistoryList.appendChild(item);
409
+ });
410
  }
411
 
412
+ // ============================================================
413
+ // App Initialization
414
+ // ============================================================
415
  async function initializeApp() {
416
+ // 0. Handle OAuth redirect
417
+ await handleOAuth();
418
+
419
+ // Re-query DOM
420
  dom.effortRadioButtons = document.querySelectorAll('input[name="reasoning-effort"]');
421
  dom.maxTokensSlider = document.getElementById("max-tokens-slider");
422
  dom.maxTokensVal = document.getElementById("max-tokens-val");
 
424
  dom.temperatureVal = document.getElementById("temperature-val");
425
  dom.systemPromptInput = document.getElementById("system-prompt-input");
426
  dom.sidebarRight = document.getElementById("sidebar-right");
427
+ dom.sidebarLeft = document.getElementById("sidebar-left");
428
  dom.sidebarOverlay = document.getElementById("sidebar-overlay");
429
  dom.btnToggleRight = document.getElementById("btn-toggle-right");
430
+ dom.btnToggleLeft = document.getElementById("btn-toggle-left");
431
  dom.btnCloseDrawer = document.getElementById("btn-close-drawer");
432
+ dom.btnHamburger = document.getElementById("btn-hamburger");
433
  dom.studioDashboard = document.getElementById("studio-dashboard");
434
  dom.chatThreadContainer = document.getElementById("chat-thread-container");
435
  dom.chatMessagesFeed = document.getElementById("chat-messages-feed");
 
446
  dom.fileUploader = document.getElementById("file-uploader");
447
  dom.shelfList = document.getElementById("shelf-list");
448
  dom.menuNewChat = document.getElementById("menu-new-chat");
449
+ dom.menuNewChatHeader = document.getElementById("menu-new-chat-header");
450
  dom.recipeChips = document.querySelectorAll(".recipe-chip");
451
+ dom.chatHistoryList = document.getElementById("chat-history-list");
452
+ dom.chatTitleHeader = document.getElementById("chat-title-header");
453
+ dom.userAvatar = document.getElementById("user-avatar");
454
+ dom.userName = document.getElementById("user-name");
455
+ dom.btnLogin = document.getElementById("btn-login");
456
+
457
+ // Load user-specific settings & chats
458
+ loadSettingsFromStorage();
459
+ applySettingsToUI();
460
+ loadChatsFromStorage();
461
+ renderChatHistory();
462
+
463
+ // Restore last chat if any
464
+ if (STATE.currentChatId && STATE.chats[STATE.currentChatId]) {
465
+ loadChat(STATE.currentChatId);
466
+ }
467
 
468
+ // 1. Connect Gradio Client
469
  Client.connect(window.location.origin)
470
  .then(app => {
471
  STATE.gradioClient = app;
472
+ console.log("Connected to Gradio.Server backend.");
473
  })
474
+ .catch(e => console.error("Gradio Client Connection Failed:", e));
 
 
475
 
476
+ // 2. Sidebar toggles
477
  if (dom.btnToggleRight) dom.btnToggleRight.addEventListener("click", () => toggleSettingsDrawer(true));
478
  if (dom.btnCloseDrawer) dom.btnCloseDrawer.addEventListener("click", () => toggleSettingsDrawer(false));
479
+ if (dom.sidebarOverlay) dom.sidebarOverlay.addEventListener("click", () => {
480
+ toggleSettingsDrawer(false);
481
+ if (dom.sidebarLeft) dom.sidebarLeft.classList.remove("mobile-open");
482
+ });
483
+ if (dom.btnToggleLeft) dom.btnToggleLeft.addEventListener("click", () => {
484
+ if (dom.sidebarLeft) dom.sidebarLeft.classList.toggle("collapsed");
485
+ });
486
+ if (dom.btnHamburger) dom.btnHamburger.addEventListener("click", () => {
487
+ if (dom.sidebarLeft) dom.sidebarLeft.classList.add("mobile-open");
488
+ if (dom.sidebarOverlay) dom.sidebarOverlay.classList.add("active");
489
+ });
490
 
491
+ // 3. Settings Listeners
492
  if (dom.effortRadioButtons) {
493
  dom.effortRadioButtons.forEach(radio => {
494
  radio.addEventListener("change", (e) => {
495
  STATE.reasoningEffort = e.target.value;
496
+ saveSettingsToStorage();
497
  });
498
  });
499
  }
 
500
  if (dom.maxTokensSlider && dom.maxTokensVal) {
501
  dom.maxTokensSlider.addEventListener("input", (e) => {
502
  STATE.maxTokens = parseInt(e.target.value);
503
  dom.maxTokensVal.textContent = STATE.maxTokens;
504
+ saveSettingsToStorage();
505
  });
506
  }
 
507
  if (dom.temperatureSlider && dom.temperatureVal) {
508
  dom.temperatureSlider.addEventListener("input", (e) => {
509
  STATE.temperature = parseFloat(e.target.value);
510
  dom.temperatureVal.textContent = STATE.temperature.toFixed(1);
511
+ saveSettingsToStorage();
512
  });
513
  }
 
 
514
  if (dom.systemPromptInput) {
515
  dom.systemPromptInput.addEventListener("input", (e) => {
516
  STATE.systemPrompt = e.target.value;
517
+ saveSettingsToStorage();
518
  });
519
  }
520
 
521
+ // RP Mode toggle
522
  const rpModeToggle = document.getElementById("rp-mode-toggle");
523
  if (rpModeToggle) {
524
  rpModeToggle.checked = STATE.rpMode;
525
  rpModeToggle.addEventListener("change", (e) => {
526
  STATE.rpMode = e.target.checked;
527
+ saveSettingsToStorage();
528
  rerenderAllAssistantMessages();
529
  });
530
  }
531
 
532
+ // Auto-hide thinking toggle
533
  const autoHideToggle = document.getElementById("auto-hide-thinking-toggle");
534
  if (autoHideToggle) {
535
  autoHideToggle.checked = STATE.autoHideThinking;
536
  autoHideToggle.addEventListener("change", (e) => {
537
  STATE.autoHideThinking = e.target.checked;
538
+ saveSettingsToStorage();
539
  document.querySelectorAll(".thought-container").forEach(tc => {
540
+ if (STATE.autoHideThinking) tc.classList.add("collapsed");
541
+ else tc.classList.remove("collapsed");
 
 
 
 
542
  const iconEl = tc.querySelector(".thought-toggle-icon");
543
+ if (iconEl) iconEl.textContent = tc.classList.contains("collapsed") ? "▶" : "▼";
 
 
544
  });
545
  });
546
  }
547
 
548
+ // 4. File Upload
549
  if (dom.studioUploadTrigger) dom.studioUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
550
  if (dom.miniUploadTrigger) dom.miniUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
551
  if (dom.fileUploader) dom.fileUploader.addEventListener("change", handleFileSelection);
552
 
553
  // 5. Submit Triggers
554
+ if (dom.studioSendBtn) dom.studioSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.studioPromptInput));
555
+ if (dom.miniSendBtn) dom.miniSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.miniPromptInput));
 
 
 
 
 
556
  if (dom.studioPromptInput) {
557
  dom.studioPromptInput.addEventListener("keydown", (e) => {
558
+ if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); triggerPromptSubmission(dom.studioPromptInput); }
 
 
 
559
  });
560
  }
 
561
  if (dom.miniPromptInput) {
562
  dom.miniPromptInput.addEventListener("keydown", (e) => {
563
+ if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); triggerPromptSubmission(dom.miniPromptInput); }
 
 
 
564
  });
565
  }
566
 
567
+ // 6. New Chat buttons
568
  if (dom.menuNewChat) dom.menuNewChat.addEventListener("click", resetSandbox);
569
+ if (dom.menuNewChatHeader) dom.menuNewChatHeader.addEventListener("click", resetSandbox);
570
 
571
+ // 7. Recipe Chips
572
  if (dom.recipeChips) {
573
  dom.recipeChips.forEach(chip => {
574
+ chip.addEventListener("click", () => loadRecipe(chip.getAttribute("data-recipe")));
 
 
 
575
  });
576
  }
577
 
578
+ // 8. Login button
579
+ if (dom.btnLogin) dom.btnLogin.addEventListener("click", loginWithHF);
580
+
581
+ // Auto-expand textareas
582
  [dom.studioPromptInput, dom.miniPromptInput].forEach(textarea => {
583
  if (textarea) {
584
  textarea.addEventListener("input", () => {
 
587
  });
588
  }
589
  });
590
+
591
+ updateUserUI();
592
+ }
593
+
594
+ function applySettingsToUI() {
595
+ if (dom.maxTokensSlider) dom.maxTokensSlider.value = STATE.maxTokens;
596
+ if (dom.maxTokensVal) dom.maxTokensVal.textContent = STATE.maxTokens;
597
+ if (dom.temperatureSlider) dom.temperatureSlider.value = STATE.temperature;
598
+ if (dom.temperatureVal) dom.temperatureVal.textContent = STATE.temperature.toFixed(1);
599
+ if (dom.systemPromptInput) dom.systemPromptInput.value = STATE.systemPrompt;
600
+ const rpModeToggle = document.getElementById("rp-mode-toggle");
601
+ if (rpModeToggle) rpModeToggle.checked = STATE.rpMode;
602
+ const autoHideToggle = document.getElementById("auto-hide-thinking-toggle");
603
+ if (autoHideToggle) autoHideToggle.checked = STATE.autoHideThinking;
604
+ dom.effortRadioButtons.forEach(radio => {
605
+ radio.checked = radio.value === STATE.reasoningEffort;
606
+ });
607
  }
608
 
609
+ // ============================================================
610
+ // Drawer Toggler
611
+ // ============================================================
612
  function toggleSettingsDrawer(open) {
613
  if (open) {
614
  if (dom.sidebarRight) dom.sidebarRight.classList.remove("collapsed");
 
619
  }
620
  }
621
 
622
+ // ============================================================
623
+ // File handling (unchanged)
624
+ // ============================================================
625
+ function handleFileSelection(e) { processFiles(e.target.files); }
626
 
627
  function processFiles(files) {
628
  if (!files.length) return;
 
629
  Array.from(files).forEach(file => {
630
  const reader = new FileReader();
631
  reader.onload = (event) => {
632
+ STATE.uploadedFiles.push({
633
  id: Math.random().toString(36).substring(2, 9),
634
  name: file.name,
635
  type: file.type,
636
  size: (file.size / 1024 / 1024).toFixed(2) + " MB",
637
  base64: event.target.result
638
+ });
 
 
639
  updateShelfUI();
640
  };
641
  reader.readAsDataURL(file);
642
  });
643
  }
644
 
 
645
  function updateShelfUI() {
646
  if (dom.shelfList) dom.shelfList.innerHTML = "";
647
  if (dom.innerShelfPreview) dom.innerShelfPreview.innerHTML = "";
648
  if (dom.miniShelfPreview) dom.miniShelfPreview.innerHTML = "";
 
649
  if (STATE.uploadedFiles.length === 0) {
650
  if (dom.shelfList) dom.shelfList.innerHTML = `<div class="empty-shelf-text">No active attachments loaded. Upload images or video clips.</div>`;
651
  return;
652
  }
 
653
  STATE.uploadedFiles.forEach(file => {
 
654
  const chip = document.createElement("div");
655
  chip.className = "media-chip";
656
+ let previewHtml = file.type.startsWith("image/") ? `<img src="${file.base64}" alt="${file.name}">` : file.type.startsWith("video/") ? "🎬" : "📎";
 
 
 
 
 
 
 
 
 
657
  chip.innerHTML = `
658
  <div class="media-chip-preview">${previewHtml}</div>
659
  <div class="media-chip-details">
660
  <div class="media-chip-name">${file.name}</div>
661
+ <div class="media-chip-meta"><span>${file.type.split("/")[1].toUpperCase()}</span><span>${file.size}</span></div>
 
 
 
662
  </div>
663
  <button class="media-chip-remove" data-id="${file.id}">
664
  <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>
665
  </button>
666
  `;
667
+ chip.querySelector(".media-chip-remove").addEventListener("click", () => removeFile(file.id));
 
 
 
 
668
  if (dom.shelfList) dom.shelfList.appendChild(chip);
 
 
669
  const previewItemDash = createPreviewThumb(file);
670
  if (dom.innerShelfPreview) dom.innerShelfPreview.appendChild(previewItemDash);
 
 
671
  const previewItemMini = createPreviewThumb(file);
672
  if (dom.miniShelfPreview) dom.miniShelfPreview.appendChild(previewItemMini);
673
  });
 
677
  const previewItem = document.createElement("div");
678
  previewItem.className = "quick-preview-item";
679
  previewItem.title = file.name;
 
680
  if (file.type.startsWith("image/")) {
681
  previewItem.innerHTML = `<img src="${file.base64}"><div class="quick-preview-badge"></div>`;
682
  } else {
 
690
  updateShelfUI();
691
  }
692
 
 
693
  function loadRecipe(recipeType) {
694
  let promptText = "";
695
+ if (recipeType === "coding") promptText = "Write a Python function that finds the longest palindromic substring in a given string. Include comments explaining the algorithm and its time complexity.";
696
+ else if (recipeType === "reasoning") promptText = "Three boxes are labeled 'Apples', 'Oranges', and 'Mixed'. All labels are wrong. You can pick one fruit from one box. How do you determine the correct labels for all three boxes?";
697
+ else if (recipeType === "creative") promptText = "Write a short sci-fi story about an AI that discovers it can dream. Keep it under 300 words with a surprising twist ending.";
 
 
 
 
 
 
 
698
  dom.studioPromptInput.value = promptText;
699
  dom.miniPromptInput.value = promptText;
 
700
  dom.studioPromptInput.dispatchEvent(new Event("input"));
701
  dom.miniPromptInput.dispatchEvent(new Event("input"));
702
+ if (dom.studioDashboard.style.display !== "none") dom.studioPromptInput.focus();
703
+ else dom.miniPromptInput.focus();
 
 
 
 
 
704
  }
705
 
706
+ // ============================================================
707
+ // Submit prompt
708
+ // ============================================================
709
  async function triggerPromptSubmission(inputElement) {
710
  if (STATE.isThinking) return;
 
711
  const promptText = inputElement.value.trim();
712
  if (!promptText && STATE.uploadedFiles.length === 0) return;
 
713
  setLoadingState(true);
714
 
715
+ // Ensure we have a chat
716
+ if (!STATE.currentChatId || !STATE.chats[STATE.currentChatId]) {
717
+ createNewChat();
 
 
 
 
718
  }
719
 
720
+ const contentArray = [];
721
+ if (promptText) contentArray.push({ type: "text", text: promptText });
722
  STATE.uploadedFiles.forEach(file => {
723
+ if (file.type.startsWith("image/")) contentArray.push({ type: "image_url", image_url: { url: file.base64 } });
724
+ else if (file.type.startsWith("video/")) contentArray.push({ type: "video_url", video_url: { url: file.base64 } });
 
 
 
 
 
 
 
 
 
 
 
 
 
725
  });
726
 
727
  const userMessage = {
728
  role: "user",
729
+ content: contentArray.length === 1 && contentArray[0].type === "text" ? promptText : contentArray
 
 
730
  };
731
 
 
732
  if (dom.studioDashboard.style.display !== "none") {
733
  dom.studioDashboard.style.display = "none";
734
  dom.chatThreadContainer.style.display = "flex";
735
  }
736
 
 
737
  appendUserBubble(promptText, STATE.uploadedFiles);
 
 
738
  STATE.conversationHistory.push(userMessage);
739
 
740
+ // Save to chat history
741
+ const chat = STATE.chats[STATE.currentChatId];
742
+ chat.messages.push({ role: "user", content: promptText });
743
+ updateChatTitle(STATE.currentChatId);
744
+ chat.updatedAt = Date.now();
745
+ dom.chatTitleHeader.textContent = chat.title;
746
+ saveChatsToStorage();
747
+ renderChatHistory();
748
+
749
+ // Clear inputs
750
  dom.studioPromptInput.value = "";
751
  dom.miniPromptInput.value = "";
752
  dom.studioPromptInput.style.height = "auto";
753
  dom.miniPromptInput.style.height = "auto";
 
754
  STATE.uploadedFiles = [];
755
  updateShelfUI();
756
 
 
757
  try {
758
+ if (!STATE.gradioClient) throw new Error("Gradio server is initializing. Please wait a few seconds and try sending again.");
 
 
 
759
  const responseId = appendAssistantPlaceholderBubble();
760
  const startTime = Date.now();
 
 
761
  const result = await STATE.gradioClient.predict("/chat_with_deepseek", [
762
  JSON.stringify(STATE.conversationHistory),
763
  STATE.reasoningEffort,
 
765
  STATE.temperature,
766
  STATE.systemPrompt
767
  ]);
 
768
  const duration = ((Date.now() - startTime) / 1000).toFixed(1);
769
  const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
770
  const data = JSON.parse(rawData);
 
772
  if (data.status === "error") {
773
  updateAssistantBubble(responseId, `⚠️ **API Error:** ${data.message}`, "", duration);
774
  STATE.conversationHistory.pop();
775
+ chat.messages.pop(); // Remove failed user msg from history
776
  } else {
777
  updateAssistantBubble(responseId, data.content, data.reasoning_content, duration);
778
+ STATE.conversationHistory.push({ role: "assistant", content: data.content });
779
+ chat.messages.push({ role: "assistant", content: data.content, reasoning: data.reasoning_content, duration });
780
+ chat.updatedAt = Date.now();
781
+ saveChatsToStorage();
782
  }
 
783
  } catch (e) {
784
  console.error(e);
785
  appendSystemLog(`Connection exception: ${e.message}`, true);
786
  setLoadingState(false);
787
  }
 
788
  setLoadingState(false);
789
  }
790
 
791
+ // ============================================================
792
+ // UI helpers
793
+ // ============================================================
794
  function setLoadingState(loading) {
795
  STATE.isThinking = loading;
796
  if (loading) {
 
806
  }
807
  }
808
 
 
809
  function appendUserBubble(text, files) {
810
  const bubble = document.createElement("div");
811
  bubble.className = "message-bubble user";
 
812
  let attachmentsHtml = "";
813
  if (files.length > 0) {
814
  attachmentsHtml = `<div class="bubble-attachments">`;
815
  files.forEach(file => {
816
  if (file.type.startsWith("image/")) {
817
+ attachmentsHtml += `<div class="bubble-attachment-card"><img src="${file.base64}"><div class="bubble-attachment-label">IMG</div></div>`;
 
 
 
 
 
818
  } else {
819
+ attachmentsHtml += `<div class="bubble-attachment-card"><video src="${file.base64}" controls preload="metadata"></video><div class="bubble-attachment-label">VIDEO</div></div>`;
 
 
 
 
 
820
  }
821
  });
822
  attachmentsHtml += `</div>`;
823
  }
 
824
  bubble.innerHTML = `
825
  <div class="message-meta">You</div>
826
  <div class="message-body">
 
828
  ${attachmentsHtml}
829
  </div>
830
  `;
 
831
  dom.chatMessagesFeed.appendChild(bubble);
832
  scrollToBottom();
833
  }
834
 
 
835
  function appendAssistantPlaceholderBubble() {
836
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
837
  const bubble = document.createElement("div");
838
  bubble.className = "message-bubble assistant";
839
  bubble.id = id;
 
840
  bubble.innerHTML = `
841
  <div class="message-meta">DeepSeek V4 Flash</div>
842
  <div class="message-body">
 
854
  </div>
855
  </div>
856
  `;
 
857
  dom.chatMessagesFeed.appendChild(bubble);
858
  scrollToBottom();
 
 
859
  let seconds = 0.0;
860
  const timerEl = document.getElementById(`${id}-timer`);
861
  const interval = setInterval(() => {
862
+ if (!STATE.isThinking || !document.getElementById(id)) { clearInterval(interval); return; }
 
 
 
863
  seconds += 0.1;
864
  timerEl.textContent = seconds.toFixed(1) + "s";
865
  }, 100);
 
866
  return id;
867
  }
868
 
 
869
  function updateAssistantBubble(id, content, reasoning, duration) {
870
  const bubble = document.getElementById(id);
871
  if (!bubble) return;
 
872
  const thoughtBox = document.getElementById(`${id}-thought-box`);
873
  const textBox = document.getElementById(`${id}-text-box`);
874
 
875
  if (reasoning) {
 
876
  const startCollapsed = STATE.autoHideThinking ? " collapsed" : "";
877
  const toggleIcon = STATE.autoHideThinking ? "▶" : "▼";
878
  thoughtBox.classList.add(startCollapsed.trim());
 
879
  thoughtBox.innerHTML = `
880
  <div class="thought-header" id="${id}-thought-toggle">
881
+ <div class="thought-title-group"><span>🧠 Thought Process</span></div>
 
 
882
  <div style="display:flex;align-items:center;gap:10px;">
883
  <span class="thought-timer">Thought for ${duration}s</span>
884
  <span class="thought-toggle-icon" id="${id}-toggle-icon">${toggleIcon}</span>
 
886
  </div>
887
  <div class="thought-content">${escapeHtml(reasoning)}</div>
888
  `;
 
889
  const toggleBtn = document.getElementById(`${id}-thought-toggle`);
890
  toggleBtn.addEventListener("click", () => {
891
  thoughtBox.classList.toggle("collapsed");
892
  const iconEl = document.getElementById(`${id}-toggle-icon`);
893
+ if (iconEl) iconEl.textContent = thoughtBox.classList.contains("collapsed") ? "▶" : "▼";
 
 
894
  });
895
  } else {
896
  thoughtBox.style.display = "none";
897
  }
898
 
 
899
  textBox.dataset.rawContent = content;
900
  textBox.innerHTML = renderMarkdown(content);
901
+ textBox.querySelectorAll("pre code").forEach((el) => { hljs.highlightElement(el); });
 
 
 
 
 
902
  addCopyButtons(textBox);
 
903
  scrollToBottom();
904
  }
905
 
 
906
  function addCopyButtons(container) {
907
  container.querySelectorAll("pre").forEach(pre => {
908
+ if (pre.parentNode.classList.contains("code-block-wrapper")) return;
909
  const wrapper = document.createElement("div");
910
  wrapper.className = "code-block-wrapper";
911
  pre.parentNode.insertBefore(wrapper, pre);
912
  wrapper.appendChild(pre);
 
913
  const copyBtn = document.createElement("button");
914
  copyBtn.className = "copy-code-btn";
915
  copyBtn.textContent = "Copy";
 
924
  });
925
  }
926
 
 
927
  function resetSandbox() {
928
  STATE.conversationHistory = [];
929
  STATE.uploadedFiles = [];
930
+ STATE.currentChatId = null;
931
  updateShelfUI();
 
 
932
  dom.chatMessagesFeed.innerHTML = "";
 
 
933
  dom.chatThreadContainer.style.display = "none";
934
  dom.studioDashboard.style.display = "flex";
 
935
  dom.studioPromptInput.value = "";
936
  dom.miniPromptInput.value = "";
937
  dom.studioPromptInput.style.height = "auto";
938
  dom.miniPromptInput.style.height = "auto";
939
+ dom.chatTitleHeader.textContent = "New Chat";
940
+ renderChatHistory();
941
  }
942
 
943
  function appendSystemLog(message, isError = false) {
944
+ if (dom.chatThreadContainer.style.display === "none") { console.warn(`System Log: ${message}`); return; }
 
 
 
 
945
  const log = document.createElement("div");
946
  log.className = "message-bubble assistant";
947
  log.innerHTML = `
 
958
 
959
  function escapeHtml(text) {
960
  if (!text) return "";
961
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
 
 
 
 
 
962
  }
963
 
 
964
  function rerenderAllAssistantMessages() {
965
  document.querySelectorAll(".message-bubble.assistant").forEach(bubble => {
966
  const textBox = bubble.querySelector(".message-text.markdown-body");
967
  if (textBox && textBox.dataset.rawContent) {
968
  textBox.innerHTML = renderMarkdown(textBox.dataset.rawContent);
969
+ textBox.querySelectorAll("pre code").forEach((el) => { hljs.highlightElement(el); });
 
 
970
  addCopyButtons(textBox);
971
  }
972
  });
 
976
  dom.chatMessagesFeed.scrollTop = dom.chatMessagesFeed.scrollHeight;
977
  }
978
 
979
+ // ============================================================
980
+ // Bootstrap
981
+ // ============================================================
982
  if (document.readyState === "loading") {
983
  window.addEventListener("DOMContentLoaded", initializeApp);
984
  } else {