Spaces:
Running
Running
File size: 18,474 Bytes
9a5c4c1 b7a0abe c68d274 b7a0abe c68d274 b7a0abe dcc108f 1cad839 a0409b4 1cad839 214af7d 1cad839 214af7d 1cad839 c68d274 1cad839 cda5bcd b33a738 cda5bcd 1cad839 b10a301 7750bd0 d61ee9c b10a301 d61ee9c b10a301 7750bd0 d61ee9c b10a301 14f8fbe d61ee9c 7750bd0 1cad839 a0409b4 1cad839 b7a0abe 8574870 b7a0abe 8574870 99051d0 8574870 c4bd131 8574870 c62ad6f 06fa89e 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c 9a5c4c1 b99a374 9a5c4c1 b99a374 9a5c4c1 8574870 5078dae 9a5c4c1 c62ad6f 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c b99a374 58ab20c 06fa89e b99a374 cffbc30 b99a374 cffbc30 091efc4 8574870 99051d0 8574870 b99a374 58ab20c 9a5c4c1 b99a374 58ab20c b99a374 58ab20c 99051d0 58ab20c b7a0abe 58ab20c b99a374 58ab20c 9a5c4c1 58ab20c 9a5c4c1 b99a374 58ab20c b99a374 58ab20c 1cad839 58ab20c 9a5c4c1 58ab20c 8574870 99051d0 9a5c4c1 8574870 9a5c4c1 99051d0 8574870 99051d0 863efcd 9a5c4c1 8574870 214af7d 8574870 58ab20c 8574870 863efcd 8574870 9a5c4c1 8574870 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | // Plain Vanilla Chat Frontend with Copy Button, SSE Streaming, Export, and Clear
// Global mode management
window.setMode = function(mode) {
window.currentMode = mode;
document.getElementById("btn-assistant").className = "mode-btn" + (mode === "assistant" ? " active" : "");
document.getElementById("btn-trainer").className = "mode-btn" + (mode === "trainer" ? " trainer-active" : "");
const label = document.getElementById("mode-label");
if(label) label.textContent = mode === "trainer" ? "β Trainer Mode π" : "";
const output = document.getElementById("chat-output");
if(output) output.innerHTML = "";
fetch("/chat/clear", { method: "POST" });
};
window.currentMode = "assistant";
window.toggleTheme = function() {
const root = document.documentElement;
const btn = document.getElementById("theme-btn");
const isLight = root.classList.toggle("light");
btn.textContent = isLight ? "π" : "βοΈ";
btn.title = isLight ? "Switch to dark theme" : "Switch to light theme";
localStorage.setItem("deepshell-theme", isLight ? "light" : "dark");
// Swap Prism theme
const darkTheme = document.getElementById("prism-theme");
const lightTheme = document.getElementById("prism-light-theme");
if (darkTheme && lightTheme) {
darkTheme.disabled = isLight;
lightTheme.disabled = !isLight;
}
};
// Apply saved Prism theme on load
document.addEventListener("DOMContentLoaded", function() {
const saved = localStorage.getItem("deepshell-theme");
if (saved === "light") {
const darkTheme = document.getElementById("prism-theme");
const lightTheme = document.getElementById("prism-light-theme");
if (darkTheme && lightTheme) {
darkTheme.disabled = true;
lightTheme.disabled = false;
}
const btn = document.getElementById("theme-btn");
if (btn) btn.textContent = "π";
}
});
// Apply saved theme on load
(function() {
const saved = localStorage.getItem("deepshell-theme");
if (saved === "light") {
document.documentElement.classList.add("light");
document.addEventListener("DOMContentLoaded", function() {
const btn = document.getElementById("theme-btn");
if (btn) { btn.textContent = "π"; }
});
}
})();
window.ttsEnabled = false;
window.lastSpokenText = "";
window.ttsLang = 'en-US';
window.setLang = function(lang) {
window.ttsLang = lang;
window.speechSynthesis.cancel();
};
window.toggleTTS = function() {
window.ttsEnabled = !window.ttsEnabled;
const btn = document.getElementById("tts-btn");
if (window.ttsEnabled) {
btn.classList.add("tts-active");
btn.title = "Voice ON β click to disable";
btn.innerHTML = "π Voice ON";
} else {
btn.classList.remove("tts-active");
btn.title = "Voice OFF β click to enable";
btn.innerHTML = "π Voice OFF";
window.speechSynthesis.cancel();
}
};
window.replayLast = function() {
if (window.lastSpokenText) {
window.speakText(window.lastSpokenText);
}
};
window.speakText = function(text) {
if (!window.ttsEnabled || window.currentMode !== "trainer") return;
window.lastSpokenText = text;
window.speechSynthesis.cancel();
// Strip markdown symbols for cleaner speech
const clean = text
.replace(/#{1,6}\s/g, "")
.replace(/\*\*/g, "")
.replace(/\*/g, "")
.replace(/```[\s\S]*?```/g, "")
.replace(/`([^`]+)`/g, "$1")
.replace(/π―|π»|π|β οΈ|π|π‘/g, "")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.trim();
// Non-English: translate via backend then speak via Piper TTS
if (window.ttsLang !== 'en-US' && window.ttsLang !== 'en-GB') {
const langCode = window.ttsLang.split('-')[0];
const sentences = clean.match(/[^.!?]+[.!?]+/g) || [clean];
let i = 0;
function translateAndSpeakNext() {
if (i >= sentences.length || !window.ttsEnabled) return;
const sentence = sentences[i].trim();
fetch('/translate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({text: sentence, target: langCode})
})
.then(r => r.json())
.then(data => {
const translated = data.translatedText || sentence;
return fetch('/tts', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({text: translated, lang: langCode})
});
})
.then(r => r.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
audio.onended = () => { URL.revokeObjectURL(url); i++; translateAndSpeakNext(); };
// Small delay on first sentence to avoid audio startup cutoff
const delay = i === 0 ? 300 : 0;
setTimeout(() => audio.play(), delay);
})
.catch(() => {
const utt = new SpeechSynthesisUtterance(sentence);
utt.lang = window.ttsLang;
utt.onend = () => { i++; translateAndSpeakNext(); };
window.speechSynthesis.speak(utt);
});
}
translateAndSpeakNext();
return;
}
window._speakDirect(clean);
};
window._speakDirect = function(clean) {
const chunks = clean.match(/[^.!?]+[.!?]+/g) || [clean];
let i = 0;
function speakNext() {
if (i >= chunks.length || !window.ttsEnabled) return;
const utt = new SpeechSynthesisUtterance(chunks[i].trim());
utt.lang = window.ttsLang;
const voices = window.speechSynthesis.getVoices();
const match = voices.find(v => v.lang === window.ttsLang);
if (match) utt.voice = match;
utt.rate = 0.95;
utt.pitch = 1.0;
utt.volume = 1.0;
utt.onend = () => { i++; speakNext(); };
window.speechSynthesis.speak(utt);
}
speakNext();
};
(function () {
"use strict";
// ---------- Utilities ----------
function escapeHtml(text) {
return String(text).replace(/[&<>"']/g, (m) => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
})[m]);
}
function renderMarkdown(md) {
if (window.marked) {
const renderer = new marked.Renderer();
renderer.code = function(code, lang) {
const language = lang || 'bash';
const validLang = Prism.languages[language] ? language : 'bash';
return `<pre><code class="language-${validLang}">${escapeHtml(code)}</code></pre>`;
};
return marked.parse(md, { renderer });
}
return `<pre>${escapeHtml(md)}</pre>`;
}
function createCopyButton(code) {
const btn = document.createElement("button");
btn.className = "copy-btn";
btn.textContent = "Copy";
btn.onclick = async () => {
try {
await navigator.clipboard.writeText(code);
btn.textContent = "Copied!";
setTimeout(() => { btn.textContent = "Copy"; }, 2000);
} catch (err) {
const textarea = document.createElement("textarea");
textarea.value = code;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand("copy");
btn.textContent = "Copied!";
setTimeout(() => { btn.textContent = "Copy"; }, 2000);
} catch (e) {
btn.textContent = "Failed";
setTimeout(() => { btn.textContent = "Copy"; }, 2000);
}
document.body.removeChild(textarea);
}
};
return btn;
}
function createExecuteButton(command, output) {
const btn = document.createElement("button");
btn.className = "execute-btn";
btn.textContent = "Execute";
btn.onclick = async () => {
btn.disabled = true;
btn.textContent = "Executing...";
try {
const response = await fetch("/chat/execute", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ command }),
});
const result = await response.json();
if (result.success) {
const outputText = result.stdout || result.stderr || "(no output)";
appendMessage(output, "Command Output", `Exit Code: ${result.exit_code}\n\n${outputText}`, false);
btn.textContent = "β Executed";
btn.style.background = "#22c55e";
} else {
appendMessage(output, "Execution Error", result.error || "Unknown error", false);
btn.textContent = "β Failed";
btn.style.background = "#ef4444";
}
} catch (err) {
appendMessage(output, "Error", `Failed to execute: ${err.message}`, false);
btn.textContent = "β Error";
btn.style.background = "#ef4444";
}
setTimeout(() => {
btn.disabled = false;
btn.textContent = "Execute";
btn.style.background = "";
}, 3000);
};
return btn;
}
function extractExecuteTags(text) {
const regex = /<execute>(.*?)<\/execute>/gs;
const commands = [];
let match;
while ((match = regex.exec(text)) !== null) {
commands.push(match[1].trim());
}
return commands;
}
// Add copy buttons to all code blocks in a container
function addCopyButtonsToCodeBlocks(container) {
container.querySelectorAll("pre").forEach((pre) => {
if (pre.parentElement && pre.parentElement.classList.contains("code-wrapper")) {
return;
}
const codeEl = pre.querySelector("code");
const code = codeEl ? codeEl.textContent : pre.textContent;
if (!code || !code.trim()) return;
const wrapper = document.createElement("div");
wrapper.className = "code-wrapper";
const copyBtn = createCopyButton(code);
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(copyBtn);
wrapper.appendChild(pre);
});
}
function appendMessage(container, sender, message, useMarkdown = false, isError = false) {
const msgDiv = document.createElement("div");
msgDiv.classList.add("message");
if (sender === "You") msgDiv.classList.add("user-msg");
if (isError) msgDiv.classList.add("error");
const commands = extractExecuteTags(message);
if (commands.length > 0) {
let displayText = message.replace(/<execute>.*?<\/execute>/gs, "");
msgDiv.innerHTML = `<strong>${sender}:</strong>${useMarkdown ? renderMarkdown(displayText) : `<pre>${escapeHtml(displayText)}</pre>`}`;
commands.forEach(cmd => {
const cmdWrapper = document.createElement("div");
cmdWrapper.className = "command-wrapper";
const cmdPre = document.createElement("pre");
cmdPre.className = "command-block";
cmdPre.textContent = cmd;
const btnContainer = document.createElement("div");
btnContainer.className = "command-buttons";
const executeBtn = createExecuteButton(cmd, container);
const copyBtn = createCopyButton(cmd);
btnContainer.appendChild(executeBtn);
btnContainer.appendChild(copyBtn);
cmdWrapper.appendChild(cmdPre);
cmdWrapper.appendChild(btnContainer);
msgDiv.appendChild(cmdWrapper);
});
} else if (useMarkdown) {
msgDiv.innerHTML = `<strong>${sender}:</strong><div class="markdown-content">${renderMarkdown(String(message))}</div>`;
addCopyButtonsToCodeBlocks(msgDiv);
} else {
msgDiv.innerHTML = `<strong>${sender}:</strong> <pre>${escapeHtml(String(message))}</pre>`;
}
container.appendChild(msgDiv);
container.scrollTop = container.scrollHeight;
if (window.Prism) {
try {
Prism.highlightAllUnder(msgDiv);
} catch (_) {}
}
return msgDiv;
}
// ---------- Streaming UI ----------
function createStreamingMessage(container, sender) {
const msgDiv = document.createElement("div");
msgDiv.classList.add("message", "loading");
msgDiv.innerHTML = `<strong>${sender}:</strong> <span class="streaming-content"></span><span class="spinner"></span>`;
const contentSpan = msgDiv.querySelector(".streaming-content");
container.appendChild(msgDiv);
container.scrollTop = container.scrollHeight;
return {
msgDiv,
contentSpan,
updateContent: (text) => {
contentSpan.textContent = text;
container.scrollTop = container.scrollHeight;
},
finalize: (text) => {
msgDiv.remove();
appendMessage(container, sender, text, true);
}
};
}
// ---------- SSE Streaming ----------
async function sendPromptStreaming(prompt, output, sendBtn, input) {
const streamUI = createStreamingMessage(output, "DeepShell");
let fullText = "";
try {
const response = await fetch("/chat/run-agent-stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt, mode: window.currentMode || "assistant" }),
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n\n");
buffer = lines.pop();
for (const line of lines) {
if (!line.trim() || !line.startsWith("data: ")) continue;
const jsonStr = line.substring(6);
try {
const data = JSON.parse(jsonStr);
if (data.type === "token") {
fullText += data.text;
streamUI.updateContent(fullText);
} else if (data.type === "done") {
streamUI.finalize(fullText);
window.speakText(fullText);
return;
} else if (data.type === "error") {
throw new Error(data.message);
}
} catch (e) {
console.warn("Failed to parse SSE data:", jsonStr, e);
}
}
}
if (fullText) {
streamUI.finalize(fullText);
}
} catch (err) {
streamUI.msgDiv.remove();
appendMessage(output, "Error", `${err.message}`, false, true);
console.error("Streaming error:", err);
} finally {
if (sendBtn) sendBtn.disabled = false;
input.focus();
}
}
// ---------- Clear Chat ----------
async function clearChat(output) {
if (!confirm("Clear conversation history? This cannot be undone.")) {
return;
}
try {
const response = await fetch("/chat/clear", {
method: "POST",
});
if (response.ok) {
output.innerHTML = "";
appendMessage(output, "System", "Chat cleared. Session history reset.", false);
} else {
throw new Error("Failed to clear chat");
}
} catch (err) {
appendMessage(output, "Error", `Failed to clear chat: ${err.message}`, false, true);
}
}
// ---------- Export Chat ----------
function exportChat(output) {
const messages = output.querySelectorAll(".message");
if (messages.length === 0) {
alert("No messages to export!");
return;
}
let markdown = "# DeepShell Chat Export\n\n";
markdown += `**Exported:** ${new Date().toLocaleString()}\n\n---\n\n`;
messages.forEach((msg) => {
const sender = msg.querySelector("strong")?.textContent.replace(":", "") || "Unknown";
// Get text content, excluding buttons
const clone = msg.cloneNode(true);
clone.querySelectorAll("button").forEach(btn => btn.remove());
const content = clone.textContent
.replace(sender + ":", "")
.trim();
markdown += `## ${sender}\n\n${content}\n\n---\n\n`;
});
// Create download
const blob = new Blob([markdown], { type: "text/markdown" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `deepshell-chat-${Date.now()}.md`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// ---------- Chat wiring ----------
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("chat-form");
const input = document.getElementById("chat-input");
const output = document.getElementById("chat-output");
const sendBtn = document.getElementById("chat-send");
const clearBtn = document.getElementById("clear-btn");
const exportBtn = document.getElementById("export-btn");
if (!form || !input || !output) {
console.warn("Chat elements not found (chat-form/chat-input/chat-output).");
return;
}
// Send message
form.addEventListener("submit", (e) => {
e.preventDefault();
const prompt = input.value.trim();
if (!prompt) return;
// Hide welcome message on first user input
const welcome = document.getElementById("welcome-msg");
if (welcome) welcome.style.display = "none";
appendMessage(output, "You", prompt);
input.value = "";
if (sendBtn) sendBtn.disabled = true;
sendPromptStreaming(prompt, output, sendBtn, input);
});
if (sendBtn) {
sendBtn.addEventListener("click", (e) => {
e.preventDefault();
form.requestSubmit();
});
}
// Clear chat button
if (clearBtn) {
clearBtn.addEventListener("click", () => {
clearChat(output);
});
}
// Export chat button
if (exportBtn) {
exportBtn.addEventListener("click", () => {
exportChat(output);
});
}
// Enter to send, Shift+Enter for newline
input.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
form.requestSubmit();
}
});
});
})();
|