R-Kentaren commited on
Commit
57430a1
·
verified ·
1 Parent(s): 1a220a8

Upload static/app.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. static/app.js +553 -426
static/app.js CHANGED
@@ -1,9 +1,6 @@
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,
@@ -15,68 +12,15 @@ const STATE = {
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"),
@@ -84,51 +28,59 @@ const dom = {
84
  temperatureSlider: document.getElementById("temperature-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,299 +89,341 @@ marked.setOptions({
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");
423
  dom.temperatureSlider = document.getElementById("temperature-slider");
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,139 +440,138 @@ async function initializeApp() {
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,28 +580,20 @@ async function initializeApp() {
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,55 +604,82 @@ function toggleSettingsDrawer(open) {
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,6 +689,7 @@ function createPreviewThumb(file) {
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,81 +703,116 @@ function removeFile(id) {
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,
764
- STATE.maxTokens,
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,25 +820,27 @@ async function triggerPromptSubmission(inputElement) {
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,37 +856,55 @@ function setLoadingState(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">
827
  <div class="message-text">${escapeHtml(text)}</div>
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,31 +922,44 @@ function appendAssistantPlaceholderBubble() {
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,30 +967,44 @@ function updateAssistantBubble(id, content, reasoning, duration) {
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,24 +1019,40 @@ function addCopyButtons(container) {
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,15 +1069,33 @@ function appendSystemLog(message, isError = false) {
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,9 +1105,7 @@ function scrollToBottom() {
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 {
 
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,
 
12
  isThinking: false,
13
  rpMode: true,
14
  autoHideThinking: true,
15
+ // Auth state
16
+ username: "",
17
+ isLoggedIn: false,
18
+ // Chat history state
19
+ currentSessionId: null,
20
+ chatSessions: []
21
  };
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  // DOM Elements hooks
 
24
  const dom = {
25
  effortRadioButtons: document.querySelectorAll('input[name="reasoning-effort"]'),
26
  maxTokensSlider: document.getElementById("max-tokens-slider"),
 
28
  temperatureSlider: document.getElementById("temperature-slider"),
29
  temperatureVal: document.getElementById("temperature-val"),
30
  systemPromptInput: document.getElementById("system-prompt-input"),
31
+
32
+ // Left Sidebar
33
  sidebarLeft: document.getElementById("sidebar-left"),
34
+ sidebarOverlayLeft: document.getElementById("sidebar-overlay-left"),
35
+ btnToggleLeft: document.getElementById("btn-toggle-left"),
36
+ btnCloseLeft: document.getElementById("btn-close-left"),
37
+
38
+ // Right Sidebar Drawer
39
+ sidebarRight: document.getElementById("sidebar-right"),
40
  sidebarOverlay: document.getElementById("sidebar-overlay"),
41
  btnToggleRight: document.getElementById("btn-toggle-right"),
 
42
  btnCloseDrawer: document.getElementById("btn-close-drawer"),
43
+
44
+ // User profile
45
+ userProfileSection: document.getElementById("user-profile-section"),
46
+ userAvatar: document.getElementById("user-avatar"),
47
+ userDisplayName: document.getElementById("user-display-name"),
48
+ hfLoginBtn: document.getElementById("hf-login-btn"),
49
+
50
+ // Chat history
51
+ chatHistoryList: document.getElementById("chat-history-list"),
52
+
53
+ // Viewports
54
  studioDashboard: document.getElementById("studio-dashboard"),
55
  chatThreadContainer: document.getElementById("chat-thread-container"),
56
  chatMessagesFeed: document.getElementById("chat-messages-feed"),
57
+
58
+ // Main Console Box Elements (Dashboard view)
59
  studioPromptInput: document.getElementById("studio-prompt-input"),
60
  innerShelfPreview: document.getElementById("inner-shelf-preview"),
61
  studioUploadTrigger: document.getElementById("studio-upload-trigger"),
62
  studioSendBtn: document.getElementById("studio-send-button"),
63
  studioSpinner: document.getElementById("studio-spinner"),
64
+
65
+ // Mini Console Box Elements (Chat thread view)
66
  miniPromptInput: document.getElementById("mini-prompt-input"),
67
  miniShelfPreview: document.getElementById("mini-shelf-preview"),
68
  miniUploadTrigger: document.getElementById("mini-upload-trigger"),
69
  miniSendBtn: document.getElementById("mini-send-button"),
70
  miniSpinner: document.getElementById("mini-spinner"),
71
+
72
+ // Core file upload elements
73
  fileUploader: document.getElementById("file-uploader"),
74
  shelfList: document.getElementById("shelf-list"),
75
+
76
+ // Action Resets
77
  menuNewChat: document.getElementById("menu-new-chat"),
78
+
79
+ // Showcase recipe chips
80
+ recipeChips: document.querySelectorAll(".recipe-chip")
 
 
 
 
 
 
 
 
81
  };
82
 
 
83
  // Markdown configuration
 
84
  marked.setOptions({
85
  breaks: true,
86
  highlight: function(code, lang) {
 
89
  }
90
  });
91
 
 
92
  // RP (Roleplay) Markdown Processor
 
93
  function processRpMarkdown(text) {
94
  if (!text) return text;
95
+
96
+ // Protect code blocks from RP processing
97
  const codeBlocks = [];
98
  text = text.replace(/(```[\s\S]*?```|`[^`]+`)/g, (match) => {
99
  codeBlocks.push(match);
100
  return `%%CODEBLOCK_${codeBlocks.length - 1}%%`;
101
  });
102
+
103
+ // Protect existing HTML tags
104
  const htmlBlocks = [];
105
  text = text.replace(/(<[^>]+>)/g, (match) => {
106
  htmlBlocks.push(match);
107
  return `%%HTMLBLOCK_${htmlBlocks.length - 1}%%`;
108
  });
109
+
110
+ // Process strikethrough ~~text~~ -> OOC styling (done first to avoid conflicts)
111
  text = text.replace(/~~([^~]+)~~/g, '<span class="rp-ooc">$1</span>');
112
+
113
+ // Process bold **text** (must come before italic)
114
  text = text.replace(/\*\*([^*]+)\*\*/g, '<strong class="rp-bold">$1</strong>');
115
+
116
+ // Process italic *text* -> narration styling
117
  text = text.replace(/(?<!\*)\*(?!\*)([^*\n]+)\*(?!\*)/g, '<em class="rp-narration">$1</em>');
118
+
119
+ // Process dialogue: "text" with smart quotes or regular quotes
120
  text = text.replace(/[\u201C\u201E"]([^"\u201D\n]+)[\u201D"]([^"\u201C\u201E]|$)/g, (match, dialogue, after) => {
121
  return `<span class="rp-dialogue">\u201C${dialogue}\u201D</span>${after}`;
122
  });
123
+
124
+ // Process narrative dividers: --- or *** or ___ on their own line
125
  text = text.replace(/^(---|\*\*\*|___)$/gm, '<hr class="rp-divider">');
126
+
127
+ // Process OOC markers: ((text))
128
  text = text.replace(/\(\(([^)]+)\)\)/g, '<span class="rp-ooc">(($1))</span>');
129
+
130
+ // Restore HTML blocks
131
+ htmlBlocks.forEach((block, i) => {
132
+ text = text.replace(`%%HTMLBLOCK_${i}%%`, block);
133
+ });
134
+
135
+ // Restore code blocks
136
+ codeBlocks.forEach((block, i) => {
137
+ text = text.replace(`%%CODEBLOCK_${i}%%`, block);
138
+ });
139
+
140
  return text;
141
  }
142
 
143
+ // Combined markdown renderer that applies RP processing if enabled
144
  function renderMarkdown(content) {
145
+ let html = marked.parse(content);
146
  if (STATE.rpMode) {
147
+ const rpProcessed = processRpMarkdown(content);
148
+ html = marked.parse(rpProcessed);
149
  }
150
+ return html;
151
  }
152
 
153
+ // ── Auth Functions ──────────────────────────────────────────────────────
154
+ async function checkUserInfo() {
 
 
155
  try {
156
+ if (!STATE.gradioClient) return;
157
+ const result = await STATE.gradioClient.predict("/get_user_info", []);
158
+ const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
159
+ const data = JSON.parse(rawData);
160
+
161
+ if (data.logged_in) {
162
+ STATE.isLoggedIn = true;
163
+ STATE.username = data.username;
164
+ updateAuthUI();
165
+ await loadChatHistory();
166
+ } else {
167
+ STATE.isLoggedIn = false;
168
+ STATE.username = "";
169
+ updateAuthUI();
 
 
 
 
 
 
 
 
 
170
  }
171
  } catch (e) {
172
+ console.warn("Could not check user info:", e);
173
  }
174
  }
175
 
176
+ function updateAuthUI() {
177
+ if (STATE.isLoggedIn) {
178
+ if (dom.userAvatar) {
179
+ dom.userAvatar.textContent = STATE.username.charAt(0).toUpperCase();
180
+ dom.userAvatar.classList.add("logged-in");
181
+ }
182
+ if (dom.userDisplayName) {
183
+ dom.userDisplayName.textContent = STATE.username;
184
+ }
185
+ if (dom.hfLoginBtn) {
186
+ dom.hfLoginBtn.textContent = "Sign out";
187
+ dom.hfLoginBtn.classList.add("logged-in");
188
+ }
189
+ } else {
190
+ if (dom.userAvatar) {
191
+ dom.userAvatar.textContent = "?";
192
+ dom.userAvatar.classList.remove("logged-in");
193
+ }
194
+ if (dom.userDisplayName) {
195
+ dom.userDisplayName.textContent = "Not logged in";
196
+ }
197
+ if (dom.hfLoginBtn) {
198
+ dom.hfLoginBtn.textContent = "Sign in with HuggingFace";
199
+ dom.hfLoginBtn.classList.remove("logged-in");
200
+ }
201
+ }
202
  }
203
 
204
+ function handleLoginLogout() {
205
+ if (STATE.isLoggedIn) {
206
+ // Logout: redirect to Gradio's logout endpoint
207
+ window.location.href = "/logout";
 
 
 
 
208
  } else {
209
+ // Login: redirect to Gradio's OAuth login endpoint
210
+ window.location.href = "/login";
211
  }
212
  }
213
 
214
+ // ── Chat History Functions ──────────────────────────────────────────────
215
+ async function loadChatHistory() {
216
+ if (!STATE.isLoggedIn || !STATE.gradioClient) return;
217
+ try {
218
+ const result = await STATE.gradioClient.predict("/list_chat_sessions", []);
219
+ const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
220
+ const data = JSON.parse(rawData);
221
+
222
+ if (data.status === "success") {
223
+ STATE.chatSessions = data.sessions;
224
+ renderChatHistory();
225
+ }
226
+ } catch (e) {
227
+ console.warn("Could not load chat history:", e);
228
+ }
229
  }
230
 
231
+ function renderChatHistory() {
232
+ if (!dom.chatHistoryList) return;
233
+
234
+ if (STATE.chatSessions.length === 0) {
235
+ dom.chatHistoryList.innerHTML = '<div class="empty-history-text">No chat history yet.<br>Start a conversation!</div>';
236
+ return;
237
+ }
238
+
239
+ dom.chatHistoryList.innerHTML = "";
240
+ STATE.chatSessions.forEach(session => {
241
+ const item = document.createElement("div");
242
+ item.className = "chat-history-item" + (session.id === STATE.currentSessionId ? " active" : "");
243
+ item.dataset.sessionId = session.id;
244
+
245
+ const timeAgo = formatTimeAgo(session.updated_at);
246
+
247
+ item.innerHTML = `
248
+ <div class="history-item-content" data-session-id="${session.id}">
249
+ <div class="history-item-title">${escapeHtml(session.title)}</div>
250
+ <div class="history-item-meta">${session.message_count} msgs · ${timeAgo}</div>
251
+ </div>
252
+ <button class="history-item-delete" data-session-id="${session.id}" title="Delete">
253
+ <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" stroke-width="2" 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>
254
+ </button>
255
+ `;
256
+
257
+ // Click to load session
258
+ const contentEl = item.querySelector(".history-item-content");
259
+ contentEl.addEventListener("click", () => loadSession(session.id));
260
+
261
+ // Delete button
262
+ const deleteBtn = item.querySelector(".history-item-delete");
263
+ deleteBtn.addEventListener("click", (e) => {
264
+ e.stopPropagation();
265
+ deleteSession(session.id);
266
+ });
267
+
268
+ dom.chatHistoryList.appendChild(item);
269
+ });
270
+ }
271
+
272
+ function formatTimeAgo(timestamp) {
273
+ const now = Date.now() / 1000;
274
+ const diff = now - timestamp;
275
+ if (diff < 60) return "just now";
276
+ if (diff < 3600) return Math.floor(diff / 60) + "m ago";
277
+ if (diff < 86400) return Math.floor(diff / 3600) + "h ago";
278
+ return Math.floor(diff / 86400) + "d ago";
279
  }
280
 
281
+ async function loadSession(sessionId) {
282
+ if (!STATE.gradioClient) return;
283
+ try {
284
+ const result = await STATE.gradioClient.predict("/load_chat_session", [sessionId]);
285
+ const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
286
+ const data = JSON.parse(rawData);
287
+
288
+ if (data.status === "success") {
289
+ STATE.currentSessionId = data.session_id;
290
+ STATE.conversationHistory = data.messages;
291
+
292
+ // Rebuild the chat UI from the loaded messages
293
+ rebuildChatFromHistory(data.messages);
294
+
295
+ // Highlight active session in sidebar
296
+ renderChatHistory();
297
+ }
298
+ } catch (e) {
299
+ console.error("Failed to load session:", e);
300
  }
 
 
301
  }
302
 
303
+ function rebuildChatFromHistory(messages) {
304
+ // Clear current feed
 
 
 
 
 
 
 
305
  dom.chatMessagesFeed.innerHTML = "";
306
+
307
+ if (messages.length === 0) {
308
+ // Show dashboard
309
  dom.chatThreadContainer.style.display = "none";
310
+ dom.studioDashboard.style.display = "flex";
311
+ return;
 
 
 
 
 
 
 
 
 
312
  }
313
+
314
+ // Show chat thread
315
+ dom.studioDashboard.style.display = "none";
316
+ dom.chatThreadContainer.style.display = "flex";
317
+
318
+ // Rebuild message bubbles
319
+ messages.forEach(msg => {
320
+ if (msg.role === "user") {
321
+ const text = typeof msg.content === "string" ? msg.content : msg.content.map(c => c.text || "").join(" ");
322
+ appendUserBubble(text, []);
323
+ } else if (msg.role === "assistant") {
324
+ appendAssistantBubble(msg.content);
325
+ }
326
+ });
327
+
328
  scrollToBottom();
329
  }
330
 
331
+ function appendAssistantBubble(content) {
332
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
333
  const bubble = document.createElement("div");
334
  bubble.className = "message-bubble assistant";
335
  bubble.id = id;
336
 
337
+ const startCollapsed = STATE.autoHideThinking ? " collapsed" : "";
338
+ const toggleIcon = STATE.autoHideThinking ? "▶" : "▼";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
  bubble.innerHTML = `
341
  <div class="message-meta">DeepSeek V4 Flash</div>
342
  <div class="message-body">
343
+ <div class="message-text markdown-body" id="${id}-text-box" data-raw-content="${escapeAttr(content)}">
344
+ ${renderMarkdown(content)}
345
+ </div>
346
  </div>
347
  `;
348
 
349
  dom.chatMessagesFeed.appendChild(bubble);
350
 
351
+ // Highlight code blocks
352
  const textBox = document.getElementById(`${id}-text-box`);
353
  if (textBox) {
354
+ textBox.querySelectorAll("pre code").forEach((el) => {
355
+ hljs.highlightElement(el);
356
+ });
357
  addCopyButtons(textBox);
358
  }
359
+ }
360
 
361
+ async function saveCurrentSession() {
362
+ if (!STATE.isLoggedIn || !STATE.gradioClient) return;
363
+ if (STATE.conversationHistory.length === 0) return;
364
+
365
+ try {
366
+ const title = STATE.conversationHistory.find(m => m.role === "user")
367
+ ? (typeof STATE.conversationHistory[0].content === "string"
368
+ ? STATE.conversationHistory[0].content
369
+ : "New Chat")
370
+ : "New Chat";
371
+
372
+ const result = await STATE.gradioClient.predict("/save_chat_session", [
373
+ JSON.stringify(STATE.conversationHistory),
374
+ title,
375
+ STATE.currentSessionId || "new"
376
+ ]);
377
+ const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
378
+ const data = JSON.parse(rawData);
379
+
380
+ if (data.status === "success") {
381
+ STATE.currentSessionId = data.session_id;
382
+ await loadChatHistory();
383
  }
384
+ } catch (e) {
385
+ console.warn("Failed to save session:", e);
386
  }
387
  }
388
 
389
+ async function deleteSession(sessionId) {
390
+ if (!STATE.gradioClient) return;
391
+ try {
392
+ await STATE.gradioClient.predict("/delete_chat_session", [sessionId]);
 
 
 
 
 
 
 
393
 
394
+ // If we deleted the active session, go back to dashboard
395
+ if (sessionId === STATE.currentSessionId) {
396
+ resetSandbox();
397
+ }
398
+
399
+ await loadChatHistory();
400
+ } catch (e) {
401
+ console.error("Failed to delete session:", e);
402
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  }
404
 
405
+ // Setup Initial State & Event Handlers
 
 
406
  async function initializeApp() {
407
+ // Re-query all DOM elements to ensure they are fully resolved
 
 
 
408
  dom.effortRadioButtons = document.querySelectorAll('input[name="reasoning-effort"]');
409
  dom.maxTokensSlider = document.getElementById("max-tokens-slider");
410
  dom.maxTokensVal = document.getElementById("max-tokens-val");
411
  dom.temperatureSlider = document.getElementById("temperature-slider");
412
  dom.temperatureVal = document.getElementById("temperature-val");
413
  dom.systemPromptInput = document.getElementById("system-prompt-input");
 
414
  dom.sidebarLeft = document.getElementById("sidebar-left");
415
+ dom.sidebarOverlayLeft = document.getElementById("sidebar-overlay-left");
416
+ dom.btnToggleLeft = document.getElementById("btn-toggle-left");
417
+ dom.btnCloseLeft = document.getElementById("btn-close-left");
418
+ dom.sidebarRight = document.getElementById("sidebar-right");
419
  dom.sidebarOverlay = document.getElementById("sidebar-overlay");
420
  dom.btnToggleRight = document.getElementById("btn-toggle-right");
 
421
  dom.btnCloseDrawer = document.getElementById("btn-close-drawer");
422
+ dom.userProfileSection = document.getElementById("user-profile-section");
423
+ dom.userAvatar = document.getElementById("user-avatar");
424
+ dom.userDisplayName = document.getElementById("user-display-name");
425
+ dom.hfLoginBtn = document.getElementById("hf-login-btn");
426
+ dom.chatHistoryList = document.getElementById("chat-history-list");
427
  dom.studioDashboard = document.getElementById("studio-dashboard");
428
  dom.chatThreadContainer = document.getElementById("chat-thread-container");
429
  dom.chatMessagesFeed = document.getElementById("chat-messages-feed");
 
440
  dom.fileUploader = document.getElementById("file-uploader");
441
  dom.shelfList = document.getElementById("shelf-list");
442
  dom.menuNewChat = document.getElementById("menu-new-chat");
 
443
  dom.recipeChips = document.querySelectorAll(".recipe-chip");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
 
445
+ // 1. Connect Gradio Client in background (Non-blocking)
446
  Client.connect(window.location.origin)
447
  .then(app => {
448
  STATE.gradioClient = app;
449
+ console.log("Successfully connected to Gradio backend.");
450
+ // Check user auth status
451
+ checkUserInfo();
452
  })
453
+ .catch(e => {
454
+ console.error("Gradio Client Connection Failed:", e);
455
+ });
456
+
457
+ // 2. Register Left Sidebar (Chat History) Events
458
+ if (dom.btnToggleLeft) dom.btnToggleLeft.addEventListener("click", () => toggleLeftSidebar(true));
459
+ if (dom.btnCloseLeft) dom.btnCloseLeft.addEventListener("click", () => toggleLeftSidebar(false));
460
+ if (dom.sidebarOverlayLeft) dom.sidebarOverlayLeft.addEventListener("click", () => toggleLeftSidebar(false));
461
 
462
+ // 3. Register Right Sidebar Drawer Slide Events
463
  if (dom.btnToggleRight) dom.btnToggleRight.addEventListener("click", () => toggleSettingsDrawer(true));
464
  if (dom.btnCloseDrawer) dom.btnCloseDrawer.addEventListener("click", () => toggleSettingsDrawer(false));
465
+ if (dom.sidebarOverlay) dom.sidebarOverlay.addEventListener("click", () => toggleSettingsDrawer(false));
466
+
467
+ // 4. Login/Logout button
468
+ if (dom.hfLoginBtn) dom.hfLoginBtn.addEventListener("click", handleLoginLogout);
 
 
 
 
 
 
 
469
 
470
+ // 5. Register Settings Listeners
471
  if (dom.effortRadioButtons) {
472
  dom.effortRadioButtons.forEach(radio => {
473
  radio.addEventListener("change", (e) => {
474
  STATE.reasoningEffort = e.target.value;
 
475
  });
476
  });
477
  }
478
+
479
  if (dom.maxTokensSlider && dom.maxTokensVal) {
480
  dom.maxTokensSlider.addEventListener("input", (e) => {
481
  STATE.maxTokens = parseInt(e.target.value);
482
  dom.maxTokensVal.textContent = STATE.maxTokens;
 
483
  });
484
  }
485
+
486
  if (dom.temperatureSlider && dom.temperatureVal) {
487
  dom.temperatureSlider.addEventListener("input", (e) => {
488
  STATE.temperature = parseFloat(e.target.value);
489
  dom.temperatureVal.textContent = STATE.temperature.toFixed(1);
 
490
  });
491
  }
492
+
493
+ // System prompt listener
494
  if (dom.systemPromptInput) {
495
  dom.systemPromptInput.addEventListener("input", (e) => {
496
  STATE.systemPrompt = e.target.value;
 
497
  });
498
  }
499
 
500
+ // RP Mode toggle listener
501
  const rpModeToggle = document.getElementById("rp-mode-toggle");
502
  if (rpModeToggle) {
503
  rpModeToggle.checked = STATE.rpMode;
504
  rpModeToggle.addEventListener("change", (e) => {
505
  STATE.rpMode = e.target.checked;
 
506
  rerenderAllAssistantMessages();
507
  });
508
  }
509
 
510
+ // Auto-hide thinking toggle listener
511
  const autoHideToggle = document.getElementById("auto-hide-thinking-toggle");
512
  if (autoHideToggle) {
513
  autoHideToggle.checked = STATE.autoHideThinking;
514
  autoHideToggle.addEventListener("change", (e) => {
515
  STATE.autoHideThinking = e.target.checked;
 
516
  document.querySelectorAll(".thought-container").forEach(tc => {
517
+ if (STATE.autoHideThinking) {
518
+ tc.classList.add("collapsed");
519
+ } else {
520
+ tc.classList.remove("collapsed");
521
+ }
522
  const iconEl = tc.querySelector(".thought-toggle-icon");
523
+ if (iconEl) {
524
+ iconEl.textContent = tc.classList.contains("collapsed") ? "▶" : "▼";
525
+ }
526
  });
527
  });
528
  }
529
 
530
+ // 6. Register File Upload Actions
531
  if (dom.studioUploadTrigger) dom.studioUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
532
  if (dom.miniUploadTrigger) dom.miniUploadTrigger.addEventListener("click", () => dom.fileUploader.click());
533
  if (dom.fileUploader) dom.fileUploader.addEventListener("change", handleFileSelection);
534
 
535
+ // 7. Submit Triggers
536
+ if (dom.studioSendBtn) {
537
+ dom.studioSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.studioPromptInput));
538
+ }
539
+ if (dom.miniSendBtn) {
540
+ dom.miniSendBtn.addEventListener("click", () => triggerPromptSubmission(dom.miniPromptInput));
541
+ }
542
+
543
  if (dom.studioPromptInput) {
544
  dom.studioPromptInput.addEventListener("keydown", (e) => {
545
+ if (e.key === "Enter" && !e.shiftKey) {
546
+ e.preventDefault();
547
+ triggerPromptSubmission(dom.studioPromptInput);
548
+ }
549
  });
550
  }
551
+
552
  if (dom.miniPromptInput) {
553
  dom.miniPromptInput.addEventListener("keydown", (e) => {
554
+ if (e.key === "Enter" && !e.shiftKey) {
555
+ e.preventDefault();
556
+ triggerPromptSubmission(dom.miniPromptInput);
557
+ }
558
  });
559
  }
560
 
561
+ // 8. New Chat
562
  if (dom.menuNewChat) dom.menuNewChat.addEventListener("click", resetSandbox);
 
563
 
564
+ // 9. Recipe Chips Console Setup
565
  if (dom.recipeChips) {
566
  dom.recipeChips.forEach(chip => {
567
+ chip.addEventListener("click", () => {
568
+ const recipeType = chip.getAttribute("data-recipe");
569
+ loadRecipe(recipeType);
570
+ });
571
  });
572
  }
573
 
574
+ // Auto-expand input textareas
 
 
 
575
  [dom.studioPromptInput, dom.miniPromptInput].forEach(textarea => {
576
  if (textarea) {
577
  textarea.addEventListener("input", () => {
 
580
  });
581
  }
582
  });
 
 
583
  }
584
 
585
+ // Left Sidebar Toggler
586
+ function toggleLeftSidebar(open) {
587
+ if (open) {
588
+ if (dom.sidebarLeft) dom.sidebarLeft.classList.add("open");
589
+ if (dom.sidebarOverlayLeft) dom.sidebarOverlayLeft.classList.add("active");
590
+ } else {
591
+ if (dom.sidebarLeft) dom.sidebarLeft.classList.remove("open");
592
+ if (dom.sidebarOverlayLeft) dom.sidebarOverlayLeft.classList.remove("active");
593
+ }
 
 
 
 
594
  }
595
 
596
+ // Right Drawer Toggler Action
 
 
597
  function toggleSettingsDrawer(open) {
598
  if (open) {
599
  if (dom.sidebarRight) dom.sidebarRight.classList.remove("collapsed");
 
604
  }
605
  }
606
 
607
+ // Handle File Select & Base64 Encoder
608
+ function handleFileSelection(e) {
609
+ processFiles(e.target.files);
610
+ }
611
 
612
  function processFiles(files) {
613
  if (!files.length) return;
614
+
615
  Array.from(files).forEach(file => {
616
  const reader = new FileReader();
617
  reader.onload = (event) => {
618
+ const fileData = {
619
  id: Math.random().toString(36).substring(2, 9),
620
  name: file.name,
621
  type: file.type,
622
  size: (file.size / 1024 / 1024).toFixed(2) + " MB",
623
  base64: event.target.result
624
+ };
625
+
626
+ STATE.uploadedFiles.push(fileData);
627
  updateShelfUI();
628
  };
629
  reader.readAsDataURL(file);
630
  });
631
  }
632
 
633
+ // Update UI Attachment Previews
634
  function updateShelfUI() {
635
  if (dom.shelfList) dom.shelfList.innerHTML = "";
636
  if (dom.innerShelfPreview) dom.innerShelfPreview.innerHTML = "";
637
  if (dom.miniShelfPreview) dom.miniShelfPreview.innerHTML = "";
638
+
639
  if (STATE.uploadedFiles.length === 0) {
640
  if (dom.shelfList) dom.shelfList.innerHTML = `<div class="empty-shelf-text">No active attachments loaded. Upload images or video clips.</div>`;
641
  return;
642
  }
643
+
644
  STATE.uploadedFiles.forEach(file => {
645
+ // 1. Sidebar Chip
646
  const chip = document.createElement("div");
647
  chip.className = "media-chip";
648
+
649
+ let previewHtml = "";
650
+ if (file.type.startsWith("image/")) {
651
+ previewHtml = `<img src="${file.base64}" alt="${file.name}">`;
652
+ } else if (file.type.startsWith("video/")) {
653
+ previewHtml = "🎬";
654
+ } else {
655
+ previewHtml = "📎";
656
+ }
657
+
658
  chip.innerHTML = `
659
  <div class="media-chip-preview">${previewHtml}</div>
660
  <div class="media-chip-details">
661
  <div class="media-chip-name">${file.name}</div>
662
+ <div class="media-chip-meta">
663
+ <span>${file.type.split("/")[1].toUpperCase()}</span>
664
+ <span>${file.size}</span>
665
+ </div>
666
  </div>
667
  <button class="media-chip-remove" data-id="${file.id}">
668
  <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>
669
  </button>
670
  `;
671
+
672
+ chip.querySelector(".media-chip-remove").addEventListener("click", () => {
673
+ removeFile(file.id);
674
+ });
675
+
676
  if (dom.shelfList) dom.shelfList.appendChild(chip);
677
+
678
+ // 2. Dashboard Inner Console Preview
679
  const previewItemDash = createPreviewThumb(file);
680
  if (dom.innerShelfPreview) dom.innerShelfPreview.appendChild(previewItemDash);
681
+
682
+ // 3. Mini Input Preview
683
  const previewItemMini = createPreviewThumb(file);
684
  if (dom.miniShelfPreview) dom.miniShelfPreview.appendChild(previewItemMini);
685
  });
 
689
  const previewItem = document.createElement("div");
690
  previewItem.className = "quick-preview-item";
691
  previewItem.title = file.name;
692
+
693
  if (file.type.startsWith("image/")) {
694
  previewItem.innerHTML = `<img src="${file.base64}"><div class="quick-preview-badge"></div>`;
695
  } else {
 
703
  updateShelfUI();
704
  }
705
 
706
+ // Load Showcase Recipes
707
  function loadRecipe(recipeType) {
708
  let promptText = "";
709
+
710
+ if (recipeType === "coding") {
711
+ promptText = "Write a Python function that finds the longest palindromic substring in a given string. Include comments explaining the algorithm and its time complexity.";
712
+ } else if (recipeType === "reasoning") {
713
+ 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?";
714
+ } else if (recipeType === "creative") {
715
+ 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.";
716
+ }
717
+
718
+ // Set value in BOTH text areas
719
  dom.studioPromptInput.value = promptText;
720
  dom.miniPromptInput.value = promptText;
721
+
722
  dom.studioPromptInput.dispatchEvent(new Event("input"));
723
  dom.miniPromptInput.dispatchEvent(new Event("input"));
724
+
725
+ // Focus active textarea
726
+ if (dom.studioDashboard.style.display !== "none") {
727
+ dom.studioPromptInput.focus();
728
+ } else {
729
+ dom.miniPromptInput.focus();
730
+ }
731
  }
732
 
733
+ // Submit prompt values to Gradio Backend API
 
 
734
  async function triggerPromptSubmission(inputElement) {
735
  if (STATE.isThinking) return;
736
+
737
  const promptText = inputElement.value.trim();
738
  if (!promptText && STATE.uploadedFiles.length === 0) return;
739
+
740
  setLoadingState(true);
741
 
742
+ // 1. Format user message contents
743
+ const contentArray = [];
744
+ if (promptText) {
745
+ contentArray.push({
746
+ type: "text",
747
+ text: promptText
748
+ });
749
  }
750
 
751
+ // Attachments
 
752
  STATE.uploadedFiles.forEach(file => {
753
+ if (file.type.startsWith("image/")) {
754
+ contentArray.push({
755
+ type: "image_url",
756
+ image_url: {
757
+ url: file.base64
758
+ }
759
+ });
760
+ } else if (file.type.startsWith("video/")) {
761
+ contentArray.push({
762
+ type: "video_url",
763
+ video_url: {
764
+ url: file.base64
765
+ }
766
+ });
767
+ }
768
  });
769
 
770
  const userMessage = {
771
  role: "user",
772
+ content: contentArray.length === 1 && contentArray[0].type === "text"
773
+ ? promptText
774
+ : contentArray
775
  };
776
 
777
+ // 2. Transition dashboard to Chat Thread view
778
  if (dom.studioDashboard.style.display !== "none") {
779
  dom.studioDashboard.style.display = "none";
780
  dom.chatThreadContainer.style.display = "flex";
781
  }
782
 
783
+ // Append to UI thread list
784
  appendUserBubble(promptText, STATE.uploadedFiles);
 
785
 
786
+ // Append to backend log history
787
+ STATE.conversationHistory.push(userMessage);
 
 
 
 
 
 
788
 
789
+ // Clear active UI containers
790
  dom.studioPromptInput.value = "";
791
  dom.miniPromptInput.value = "";
792
  dom.studioPromptInput.style.height = "auto";
793
  dom.miniPromptInput.style.height = "auto";
794
+
795
  STATE.uploadedFiles = [];
796
  updateShelfUI();
797
 
798
+ // 3. Connect API Call
799
  try {
800
+ if (!STATE.gradioClient) {
801
+ throw new Error("Gradio server is initializing. Please wait a few seconds and try sending again.");
802
+ }
803
+
804
  const responseId = appendAssistantPlaceholderBubble();
805
  const startTime = Date.now();
806
+
807
+ // Call our gradio Server api endpoint
808
  const result = await STATE.gradioClient.predict("/chat_with_deepseek", [
809
  JSON.stringify(STATE.conversationHistory),
810
  STATE.reasoningEffort,
811
+ String(STATE.maxTokens),
812
+ String(STATE.temperature),
813
  STATE.systemPrompt
814
  ]);
815
+
816
  const duration = ((Date.now() - startTime) / 1000).toFixed(1);
817
  const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
818
  const data = JSON.parse(rawData);
 
820
  if (data.status === "error") {
821
  updateAssistantBubble(responseId, `⚠️ **API Error:** ${data.message}`, "", duration);
822
  STATE.conversationHistory.pop();
 
823
  } else {
824
  updateAssistantBubble(responseId, data.content, data.reasoning_content, duration);
825
+ STATE.conversationHistory.push({
826
+ role: "assistant",
827
+ content: data.content
828
+ });
829
+
830
+ // Auto-save session for logged-in users
831
+ saveCurrentSession();
832
  }
833
+
834
  } catch (e) {
835
  console.error(e);
836
  appendSystemLog(`Connection exception: ${e.message}`, true);
837
  setLoadingState(false);
838
  }
839
+
840
  setLoadingState(false);
841
  }
842
 
843
+ // UI spinner state toggles
 
 
844
  function setLoadingState(loading) {
845
  STATE.isThinking = loading;
846
  if (loading) {
 
856
  }
857
  }
858
 
859
+ // Render User Bubble
860
  function appendUserBubble(text, files) {
861
  const bubble = document.createElement("div");
862
  bubble.className = "message-bubble user";
863
+
864
  let attachmentsHtml = "";
865
  if (files.length > 0) {
866
  attachmentsHtml = `<div class="bubble-attachments">`;
867
  files.forEach(file => {
868
  if (file.type.startsWith("image/")) {
869
+ attachmentsHtml += `
870
+ <div class="bubble-attachment-card">
871
+ <img src="${file.base64}">
872
+ <div class="bubble-attachment-label">IMG</div>
873
+ </div>
874
+ `;
875
  } else {
876
+ attachmentsHtml += `
877
+ <div class="bubble-attachment-card">
878
+ <video src="${file.base64}" controls preload="metadata"></video>
879
+ <div class="bubble-attachment-label">VIDEO</div>
880
+ </div>
881
+ `;
882
  }
883
  });
884
  attachmentsHtml += `</div>`;
885
  }
886
+
887
+ const displayName = STATE.isLoggedIn ? STATE.username : "You";
888
+
889
  bubble.innerHTML = `
890
+ <div class="message-meta">${escapeHtml(displayName)}</div>
891
  <div class="message-body">
892
  <div class="message-text">${escapeHtml(text)}</div>
893
  ${attachmentsHtml}
894
  </div>
895
  `;
896
+
897
  dom.chatMessagesFeed.appendChild(bubble);
898
  scrollToBottom();
899
  }
900
 
901
+ // Render Assistant Placeholder
902
  function appendAssistantPlaceholderBubble() {
903
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
904
  const bubble = document.createElement("div");
905
  bubble.className = "message-bubble assistant";
906
  bubble.id = id;
907
+
908
  bubble.innerHTML = `
909
  <div class="message-meta">DeepSeek V4 Flash</div>
910
  <div class="message-body">
 
922
  </div>
923
  </div>
924
  `;
925
+
926
  dom.chatMessagesFeed.appendChild(bubble);
927
  scrollToBottom();
928
+
929
+ // Start Thought Timer
930
  let seconds = 0.0;
931
  const timerEl = document.getElementById(`${id}-timer`);
932
  const interval = setInterval(() => {
933
+ if (!STATE.isThinking || !document.getElementById(id)) {
934
+ clearInterval(interval);
935
+ return;
936
+ }
937
  seconds += 0.1;
938
  timerEl.textContent = seconds.toFixed(1) + "s";
939
  }, 100);
940
+
941
  return id;
942
  }
943
 
944
+ // Complete Assistant Bubble
945
  function updateAssistantBubble(id, content, reasoning, duration) {
946
  const bubble = document.getElementById(id);
947
  if (!bubble) return;
948
+
949
  const thoughtBox = document.getElementById(`${id}-thought-box`);
950
  const textBox = document.getElementById(`${id}-text-box`);
951
 
952
  if (reasoning) {
953
+ // Auto-hide thinking: start collapsed by default
954
+ const startCollapsed = STATE.autoHideThinking;
955
+ if (startCollapsed) thoughtBox.classList.add("collapsed");
956
+ const toggleIcon = startCollapsed ? "▶" : "▼";
957
+
958
  thoughtBox.innerHTML = `
959
  <div class="thought-header" id="${id}-thought-toggle">
960
+ <div class="thought-title-group">
961
+ <span>🧠 Thought Process</span>
962
+ </div>
963
  <div style="display:flex;align-items:center;gap:10px;">
964
  <span class="thought-timer">Thought for ${duration}s</span>
965
  <span class="thought-toggle-icon" id="${id}-toggle-icon">${toggleIcon}</span>
 
967
  </div>
968
  <div class="thought-content">${escapeHtml(reasoning)}</div>
969
  `;
970
+
971
  const toggleBtn = document.getElementById(`${id}-thought-toggle`);
972
  toggleBtn.addEventListener("click", () => {
973
  thoughtBox.classList.toggle("collapsed");
974
  const iconEl = document.getElementById(`${id}-toggle-icon`);
975
+ if (iconEl) {
976
+ iconEl.textContent = thoughtBox.classList.contains("collapsed") ? "▶" : "▼";
977
+ }
978
  });
979
  } else {
980
  thoughtBox.style.display = "none";
981
  }
982
 
983
+ // Store raw content for re-rendering when RP mode changes
984
  textBox.dataset.rawContent = content;
985
  textBox.innerHTML = renderMarkdown(content);
986
+
987
+ // Highlight code blocks and add copy buttons
988
+ textBox.querySelectorAll("pre code").forEach((el) => {
989
+ hljs.highlightElement(el);
990
+ });
991
+
992
  addCopyButtons(textBox);
993
+
994
  scrollToBottom();
995
  }
996
 
997
+ // Add copy buttons to code blocks
998
  function addCopyButtons(container) {
999
  container.querySelectorAll("pre").forEach(pre => {
1000
+ // Skip if already wrapped
1001
  if (pre.parentNode.classList.contains("code-block-wrapper")) return;
1002
+
1003
  const wrapper = document.createElement("div");
1004
  wrapper.className = "code-block-wrapper";
1005
  pre.parentNode.insertBefore(wrapper, pre);
1006
  wrapper.appendChild(pre);
1007
+
1008
  const copyBtn = document.createElement("button");
1009
  copyBtn.className = "copy-code-btn";
1010
  copyBtn.textContent = "Copy";
 
1019
  });
1020
  }
1021
 
1022
+ // Reset Sandbox Chat Context Logs
1023
  function resetSandbox() {
1024
+ // Save current session before resetting
1025
+ if (STATE.isLoggedIn && STATE.conversationHistory.length > 0) {
1026
+ saveCurrentSession();
1027
+ }
1028
+
1029
  STATE.conversationHistory = [];
1030
+ STATE.currentSessionId = null;
1031
  STATE.uploadedFiles = [];
 
1032
  updateShelfUI();
1033
+
1034
+ // Clear feed
1035
  dom.chatMessagesFeed.innerHTML = "";
1036
+
1037
+ // Show dashboard
1038
  dom.chatThreadContainer.style.display = "none";
1039
  dom.studioDashboard.style.display = "flex";
1040
+
1041
  dom.studioPromptInput.value = "";
1042
  dom.miniPromptInput.value = "";
1043
  dom.studioPromptInput.style.height = "auto";
1044
  dom.miniPromptInput.style.height = "auto";
1045
+
1046
+ // Deselect active chat in history
1047
  renderChatHistory();
1048
  }
1049
 
1050
  function appendSystemLog(message, isError = false) {
1051
+ if (dom.chatThreadContainer.style.display === "none") {
1052
+ console.warn(`System Log: ${message}`);
1053
+ return;
1054
+ }
1055
+
1056
  const log = document.createElement("div");
1057
  log.className = "message-bubble assistant";
1058
  log.innerHTML = `
 
1069
 
1070
  function escapeHtml(text) {
1071
  if (!text) return "";
1072
+ return text
1073
+ .replace(/&/g, "&amp;")
1074
+ .replace(/</g, "&lt;")
1075
+ .replace(/>/g, "&gt;")
1076
+ .replace(/"/g, "&quot;")
1077
+ .replace(/'/g, "&#039;");
1078
  }
1079
 
1080
+ function escapeAttr(text) {
1081
+ if (!text) return "";
1082
+ return text
1083
+ .replace(/&/g, "&amp;")
1084
+ .replace(/"/g, "&quot;")
1085
+ .replace(/'/g, "&#039;")
1086
+ .replace(/</g, "&lt;")
1087
+ .replace(/>/g, "&gt;");
1088
+ }
1089
+
1090
+ // Re-render all assistant messages with current RP mode setting
1091
  function rerenderAllAssistantMessages() {
1092
  document.querySelectorAll(".message-bubble.assistant").forEach(bubble => {
1093
  const textBox = bubble.querySelector(".message-text.markdown-body");
1094
  if (textBox && textBox.dataset.rawContent) {
1095
  textBox.innerHTML = renderMarkdown(textBox.dataset.rawContent);
1096
+ textBox.querySelectorAll("pre code").forEach((el) => {
1097
+ hljs.highlightElement(el);
1098
+ });
1099
  addCopyButtons(textBox);
1100
  }
1101
  });
 
1105
  dom.chatMessagesFeed.scrollTop = dom.chatMessagesFeed.scrollHeight;
1106
  }
1107
 
1108
+ // Initialise application when DOM is fully set up
 
 
1109
  if (document.readyState === "loading") {
1110
  window.addEventListener("DOMContentLoaded", initializeApp);
1111
  } else {