Test / frontend /ui.html
Hfzune's picture
Update frontend/ui.html
7076ebb verified
Raw History Blame Contribute Delete
22.7 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Abliterated Chat</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<!-- Markdown & Syntax Highlighting -->
<script src="https://cdn.jsdelivr.net/npm/marked@9.0.3/marked.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<style>
:root {
--bg: #0b0b0d;
--panel: #141418;
--panel2: #1c1c22;
--border: #2a2a33;
--text: #e8e8ed;
--muted: #8a8a94;
--accent: #6366f1;
--user-bg: #1e1b4b;
--assist-bg: #1a1a20;
--danger: #ef4444;
--ok: #22c55e;
--warn: #f59e0b;
}
* { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }
html, body { height: 100%; overflow: hidden; width: 100%; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--bg); color: var(--text);
display: flex; font-size: 14px;
}
/* ── Sidebar ── */
#sidebar {
width: 240px; flex-shrink: 0;
background: var(--panel);
border-right: 1px solid var(--border);
display: flex; flex-direction: column;
padding: 12px; gap: 10px;
transition: transform 0.2s;
}
#sidebar.hidden { transform: translateX(-100%); position: absolute; height: 100%; z-index: 10; }
#sidebar h1 { font-size: 12px; color: var(--muted); font-weight: 600; letter-spacing: 0.5px; padding: 4px; }
.btn {
padding: 10px 12px; border-radius: 8px; border: 1px solid var(--border);
background: var(--panel2); color: var(--text); cursor: pointer;
font-size: 13px; display: flex; align-items: center; gap: 8px;
transition: background 0.15s, border-color 0.15s;
}
.btn:hover { background: #24242c; border-color: #3a3a45; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 500; }
.btn.primary:hover { background: #4f46e5; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
#chat-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 4px; }
.chat-item {
padding: 8px 10px; border-radius: 6px; cursor: pointer;
font-size: 13px; color: var(--text); display: flex;
justify-content: space-between; align-items: center; gap: 6px;
}
.chat-item:hover { background: var(--panel2); }
.chat-item.active { background: #1e1b4b; }
.chat-item .title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chat-item .del { color: var(--muted); opacity: 0; font-size: 15px; }
.chat-item:hover .del { opacity: 1; }
.chat-item .del:hover { color: var(--danger); }
/* ── Main ── */
#main { flex: 1; display: flex; flex-direction: column; min-width: 0; /* CRITICAL FIX */ }
#header {
padding: 10px 16px; border-bottom: 1px solid var(--border);
display: flex; align-items: center; gap: 10px; flex-shrink: 0;
}
#menu-btn { background: none; border: none; color: var(--text); font-size: 20px; cursor: pointer; padding: 4px; }
#header .title { font-weight: 600; font-size: 14px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#header .model { font-size: 11px; color: var(--muted); background: var(--panel2); padding: 3px 8px; border-radius: 999px; }
/* ── Messages ── */
#messages {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0; /* CRITICAL FIX */
}
.msg {
padding: 10px 14px;
border-radius: 12px;
line-height: 1.55;
word-wrap: break-word;
overflow-wrap: break-word;
min-width: 0; /* CRITICAL FIX: Allows flex child to shrink */
max-width: 100%;
}
.msg.user {
align-self: flex-end;
background: var(--user-bg);
border: 1px solid #3730a3;
white-space: pre-wrap;
width: fit-content;
max-width: 85%;
}
.msg.assistant {
align-self: flex-start;
background: var(--assist-bg);
border: 1px solid var(--border);
width: 100%;
overflow: hidden; /* CRITICAL FIX: Prevents child from pushing parent out */
}
.msg.error { align-self: center; background: #2a1414; border: 1px solid #7f1d1d; color: #fca5a5; font-size: 12px; }
/* Markdown styles */
.msg.assistant p { margin-bottom: 8px; }
.msg.assistant p:last-child { margin-bottom: 0; }
.msg.assistant h1, .msg.assistant h2, .msg.assistant h3 { margin: 12px 0 6px; font-size: 1.1em; }
.msg.assistant ul, .msg.assistant ol { margin-left: 20px; margin-bottom: 8px; }
/* Code block layout */
.code-block-wrapper {
margin: 10px 0;
border-radius: 8px;
border: 1px solid var(--border);
overflow: hidden;
max-width: 100%; /* CRITICAL FIX */
}
.code-block-header {
display: flex; justify-content: space-between; align-items: center;
background: #1e1e24; padding: 6px 12px;
font-size: 11px; color: var(--muted);
border-bottom: 1px solid var(--border);
}
.copy-btn {
background: #2a2a33; border: 1px solid #3a3a45; color: var(--text);
border-radius: 4px; padding: 2px 8px; cursor: pointer; font-size: 11px;
transition: background 0.2s;
}
.copy-btn:hover { background: #3a3a45; }
.copy-btn.copied { background: var(--ok); border-color: var(--ok); color: #000; }
/* Code scrolling */
.msg.assistant pre {
margin: 0;
padding: 12px;
background: #111115;
overflow-x: auto;
max-width: 100%;
-webkit-overflow-scrolling: touch;
}
.msg.assistant code {
font-family: "SF Mono", "Fira Code", monospace;
font-size: 13px;
white-space: pre;
word-break: normal;
}
.msg .cursor {
display: inline-block; width: 7px; height: 14px;
background: var(--accent); margin-left: 2px; vertical-align: text-bottom;
animation: blink 1s steps(2) infinite; border-radius: 1px;
}
@keyframes blink { 50% { opacity: 0; } }
/* ── Composer ── */
#composer { padding: 10px 16px 14px; border-top: 1px solid var(--border); flex-shrink: 0; }
#composer-inner { display: flex; gap: 8px; align-items: flex-end; max-width: 820px; margin: 0 auto; }
#prompt {
flex: 1; resize: none; border: 1px solid var(--border); border-radius: 10px;
padding: 10px 12px; font-family: inherit; font-size: 14px; line-height: 1.4;
background: var(--panel2); color: var(--text);
min-height: 44px; max-height: 160px; outline: none;
transition: border-color 0.15s;
}
#prompt:focus { border-color: var(--accent); }
#send-btn, #stop-btn {
height: 44px; padding: 0 16px; border-radius: 10px; border: none;
cursor: pointer; font-size: 14px; font-weight: 500; transition: opacity 0.15s;
}
#send-btn { background: var(--accent); color: #fff; }
#stop-btn { background: var(--danger); color: #fff; display: none; }
#send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
/* ── Token meter ── */
#token-meter { max-width: 820px; margin: 8px auto 0; font-size: 11px; color: var(--muted); }
#token-bar-bg { height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; margin-top: 4px; }
#token-bar { height: 100%; width: 0%; background: var(--ok); transition: width 0.3s, background 0.3s; }
/* ── Mobile ── */
@media (max-width: 640px) {
#sidebar { position: absolute; height: 100%; z-index: 20; box-shadow: 4px 0 24px rgba(0,0,0,0.5); }
#sidebar.hidden { transform: translateX(-100%); }
#menu-btn { display: block; }
}
@media (min-width: 641px) {
#menu-btn { display: none; }
}
</style>
</head>
<body>
<aside id="sidebar">
<h1>YOUR CHATS</h1>
<button class="btn primary" id="new-chat-btn">➕ New chat</button>
<div id="chat-list"></div>
</aside>
<main id="main">
<header id="header">
<button id="menu-btn" title="Menu">☰</button>
<span class="title" id="header-title">New chat</span>
<span class="model" id="model-tag">…</span>
</header>
<div id="messages"></div>
<div id="composer">
<div id="composer-inner">
<textarea id="prompt" rows="1" placeholder="Message the model…"></textarea>
<button id="send-btn">Send</button>
<button id="stop-btn">Stop</button>
</div>
<div id="token-meter">
<div style="display:flex;justify-content:space-between;">
<span>📊 Context</span>
<span id="token-text">0 / 0</span>
</div>
<div id="token-bar-bg"><div id="token-bar"></div></div>
</div>
</div>
</main>
<script>
const tg = window.Telegram?.WebApp;
if (tg) { try { tg.ready(); tg.expand(); } catch (e) {} }
function haptic(kind = "light") {
try { tg?.HapticFeedback?.impactOccurred(kind); } catch (e) {}
}
// ── Markdown Setup ────────────────────────────────────────────────────
const markedLib = window.marked;
const hljsLib = window.hljs;
if (markedLib && hljsLib) {
const renderer = new markedLib.Renderer();
renderer.code = function (code, language) {
const validLang = language && hljsLib.getLanguage(language) ? language : 'plaintext';
let highlighted = code;
try {
highlighted = hljsLib.highlight(code, { language: validLang }).value;
} catch (e) {
highlighted = code.replace(/[&<>]/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[m]));
}
return `
<div class="code-block-wrapper">
<div class="code-block-header">
<span>${validLang}</span>
<button class="copy-btn">Copy</button>
</div>
<pre><code class="hljs language-${validLang}">${highlighted}</code></pre>
</div>`;
};
markedLib.use({ renderer });
markedLib.setOptions({ breaks: true, gfm: true });
}
// Copy logic using DOM traversal
document.addEventListener('click', async (e) => {
if (e.target.classList.contains('copy-btn')) {
const btn = e.target;
const codeBlock = btn.closest('.code-block-wrapper').querySelector('code');
const code = codeBlock.innerText;
try {
await navigator.clipboard.writeText(code);
btn.textContent = 'Copied!';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = 'Copy';
btn.classList.remove('copied');
}, 2000);
} catch (err) {
btn.textContent = 'Failed';
setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
}
}
});
// ── State & Constants ─────────────────────────────────────────────────
const STORAGE_KEY = "ablt_v1";
const ACTIVE_KEY = "ablt_active_v1";
const MAX_TOKENS = 6144;
const state = {
sessions: [],
activeId: null,
streaming: false,
abortController: null,
};
const $ = (id) => document.getElementById(id);
const messagesEl = $("messages");
const chatListEl = $("chat-list");
const promptEl = $("prompt");
const sendBtn = $("send-btn");
const stopBtn = $("stop-btn");
const tokenBar = $("token-bar");
const tokenText = $("token-text");
// ── Persistence ───────────────────────────────────────────────────────
function save() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state.sessions));
localStorage.setItem(ACTIVE_KEY, state.activeId || "");
}
function load() {
try { state.sessions = JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"); }
catch { state.sessions = []; }
state.activeId = localStorage.getItem(ACTIVE_KEY) || null;
if (!state.sessions.length) createSession();
else if (!state.sessions.some(s => s.id === state.activeId))
state.activeId = state.sessions[0].id;
}
// ── Sessions ──────────────────────────────────────────────────────────
const active = () => state.sessions.find(s => s.id === state.activeId) || null;
function createSession() {
const id = crypto.randomUUID();
state.sessions.unshift({ id, title: "New chat", messages: [] });
state.activeId = id;
save(); renderSidebar(); renderMessages(); updateMeter();
if (window.innerWidth > 640) promptEl.focus();
}
function switchSession(id) {
if (state.streaming) return;
state.activeId = id;
save(); renderSidebar(); renderMessages(); updateMeter();
$("sidebar").classList.add("hidden");
}
function deleteSession(id) {
if (state.streaming) return;
state.sessions = state.sessions.filter(s => s.id !== id);
if (!state.sessions.length) return createSession();
if (state.activeId === id) state.activeId = state.sessions[0].id;
save(); renderSidebar(); renderMessages(); updateMeter();
}
function deriveTitle(t) {
const x = (t || "").trim().replace(/\s+/g, " ");
return x.length > 36 ? x.slice(0, 36) + "…" : (x || "New chat");
}
// ── Rendering ─────────────────────────────────────────────────────────
function renderSidebar() {
chatListEl.innerHTML = "";
state.sessions.forEach(s => {
const el = document.createElement("div");
el.className = "chat-item" + (s.id === state.activeId ? " active" : "");
const title = document.createElement("span");
title.className = "title";
title.textContent = s.title;
const del = document.createElement("span");
del.className = "del";
del.textContent = "✕";
title.onclick = () => switchSession(s.id);
del.onclick = (e) => { e.stopPropagation(); deleteSession(s.id); };
el.appendChild(title); el.appendChild(del);
chatListEl.appendChild(el);
});
}
function renderMessages() {
messagesEl.innerHTML = "";
const s = active();
if (!s) return;
$("header-title").textContent = s.title;
s.messages.forEach(m => appendBubble(m.role, m.content));
messagesEl.scrollTop = messagesEl.scrollHeight;
}
function appendBubble(role, content, streaming = false) {
const el = document.createElement("div");
el.className = `msg ${role}`;
el.dataset.streaming = streaming ? "1" : "0";
if (role === "assistant") {
el.innerHTML = parseMarkdownSafe(content);
if (streaming) {
const c = document.createElement("span");
c.className = "cursor";
el.appendChild(c);
}
} else {
el.textContent = content;
}
messagesEl.appendChild(el);
messagesEl.scrollTop = messagesEl.scrollHeight;
return el;
}
// Helper to safely parse markdown during streaming
function parseMarkdownSafe(text) {
if (!markedLib) return text;
let safeText = text;
// Count triple backticks. If odd, it means a block is currently open.
const backtickMatches = safeText.match(/```/g);
const backtickCount = backtickMatches ? backtickMatches.length : 0;
if (backtickCount % 2 !== 0) {
safeText += "\n```";
}
try {
return markedLib.parse(safeText);
} catch (e) {
return text;
}
}
function updateMeter() {
const s = active();
if (!s) return;
fetch("/api/count_tokens", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ history: s.messages, system_prompt: "" }),
})
.then(r => r.json())
.then(d => {
const n = d.tokens || 0;
const max = d.max || MAX_TOKENS;
const pct = Math.min((n / max) * 100, 100);
tokenText.textContent = `${n.toLocaleString()} / ${max.toLocaleString()}`;
tokenBar.style.width = pct + "%";
tokenBar.style.background = pct < 50 ? "var(--ok)" : pct < 80 ? "var(--warn)" : "var(--danger)";
})
.catch(() => {});
}
// ── Streaming ─────────────────────────────────────────────────────────
async function sendMessage() {
if (state.streaming) return;
const text = promptEl.value.trim();
if (!text) return;
const s = active();
if (!s) return;
haptic("light");
if (s.title === "New chat") {
s.title = deriveTitle(text);
$("header-title").textContent = s.title;
renderSidebar();
}
s.messages.push({ role: "user", content: text });
appendBubble("user", text);
promptEl.value = "";
autoResize();
const bubble = appendBubble("assistant", "", true);
const priorHistory = s.messages.slice(0, -1);
state.streaming = true;
state.abortController = new AbortController();
sendBtn.disabled = true;
sendBtn.style.display = "none";
stopBtn.style.display = "block";
let finalText = "";
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: text,
history: priorHistory,
system_prompt: "",
max_new_tokens: 256,
temperature: 0.7,
top_p: 0.9,
}),
signal: state.abortController.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop();
for (const part of parts) {
if (!part.startsWith("data: ")) continue;
let data;
try { data = JSON.parse(part.slice(6)); } catch { continue; }
if (data.type === "token") {
finalText = data.content;
bubble.innerHTML = parseMarkdownSafe(finalText);
const c = document.createElement("span");
c.className = "cursor";
bubble.appendChild(c);
messagesEl.scrollTop = messagesEl.scrollHeight;
} else if (data.type === "done") {
finalText = data.content;
bubble.innerHTML = markedLib ? markedLib.parse(finalText) : finalText;
bubble.dataset.streaming = "0";
s.messages.push({ role: "assistant", content: finalText });
} else if (data.type === "error") {
bubble.dataset.streaming = "0";
bubble.className = "msg error";
bubble.textContent = `⚠️ ${data.content}`;
}
}
}
if (finalText && !s.messages.some(m => m.role === "assistant" && m.content === finalText)) {
s.messages.push({ role: "assistant", content: finalText });
}
} catch (err) {
if (err.name === "AbortError") {
if (finalText) {
bubble.innerHTML = markedLib ? markedLib.parse(finalText) : finalText;
bubble.dataset.streaming = "0";
s.messages.push({ role: "assistant", content: finalText });
} else {
bubble.remove();
}
} else {
bubble.dataset.streaming = "0";
bubble.className = "msg error";
bubble.textContent = `⚠️ ${err.message}`;
}
} finally {
state.streaming = false;
state.abortController = null;
sendBtn.disabled = false;
sendBtn.style.display = "block";
stopBtn.style.display = "none";
save();
updateMeter();
promptEl.focus();
}
}
function stopGeneration() {
haptic("medium");
state.abortController?.abort();
}
// ── UI wiring ─────────────────────────────────────────────────────────
$("new-chat-btn").onclick = () => {
haptic("light");
if (!state.streaming) createSession();
};
$("menu-btn").onclick = () => $("sidebar").classList.toggle("hidden");
sendBtn.onclick = sendMessage;
stopBtn.onclick = stopGeneration;
promptEl.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 640) {
e.preventDefault();
sendMessage();
}
});
promptEl.addEventListener("input", autoResize);
function autoResize() {
promptEl.style.height = "auto";
promptEl.style.height = Math.min(promptEl.scrollHeight, 160) + "px";
}
// ── Boot ──────────────────────────────────────────────────────────────
(async function init() {
load();
renderSidebar();
renderMessages();
updateMeter();
if (window.innerWidth <= 640) $("sidebar").classList.add("hidden");
try {
const h = await (await fetch("/health")).json();
$("model-tag").textContent = h.model?.split("/").pop() || "model";
} catch { $("model-tag").textContent = "online"; }
})();
</script>
</body>
</html>