flicker-ai's picture
Deploy Flicker Flash 2 chat
0d37787 verified
Raw History Blame Contribute Delete
24.3 kB
// Flicker Flash 2 — on-device chat (Qwen3.5-2B + Flicker LoRA, GGUF via wllama / llama.cpp WASM)
import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.13.0/esm/index.js';
const WASM = { default: 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.13.0/esm/wasm/wllama.wasm' };
const MODEL_URL = 'https://huggingface.co/flicker-ai/flicker-flash2-gguf/resolve/main/flicker-flash2-Q4_K_M-00001-of-00003.gguf';
const MODEL_MB = 1300;
const N_CTX = 8192;
const SYSP = (eff) => `You are Flicker Flash 2, a helpful AI made by Flicker Lab. Effort: ${eff}. Answer in the format the user asks for: HTML/CSS when they ask for HTML, a web page or CSS, Roblox Luau only when they ask about Roblox, Python for Python. Low effort = short and fast; higher effort = think more carefully.`;
let SYSTEM = SYSP(localStorage.getItem('ff_effort') || 'medium');
const CHIPS = [
'Make a 3D wobbly jelly in HTML for iPhone using three.js',
'Make an SVG of a smiling face',
'Write a Python FizzBuzz',
'What is 17 × 23?',
'Make a glassmorphism CSS card in HTML',
];
const $ = (id) => document.getElementById(id);
const el = {
scroller: $('scroller'), messages: $('messages'), empty: $('empty'), chips: $('chips'),
loader: $('loader'), bar: $('barFill'), loaderTitle: $('loaderTitle'), loaderSub: $('loaderSub'), retry: $('retryBtn'),
input: $('input'), send: $('sendBtn'), stop: $('stopBtn'), newChat: $('newChat'), think: $('thinkToggle'),
status: $('status'), statusText: $('statusText'),
sheet: $('sheet'), frame: $('previewFrame'), sheetClose: $('sheetClose'), sheetReload: $('sheetReload'), toast: $('toast'),
};
const state = {
wllama: null, ready: false, busy: false, thinking: localStorage.getItem('ff_think') !== '0',
history: [], // {role, content}
abort: null, lastPreview: '', lastSpeed: null,
};
window.ffState = state; // handy for debugging/tests
/* ---------------- status / toast ---------------- */
function setStatus(text, kind = '') {
el.statusText.textContent = text;
el.status.className = 'status ' + kind;
}
let toastT;
function toast(msg) {
el.toast.textContent = msg; el.toast.classList.add('show');
clearTimeout(toastT); toastT = setTimeout(() => el.toast.classList.remove('show'), 1400);
}
async function copyText(text) {
try { await navigator.clipboard.writeText(text); }
catch {
const ta = document.createElement('textarea'); ta.value = text; ta.setAttribute('readonly', '');
ta.style.cssText = 'position:fixed;opacity:0;top:0'; document.body.appendChild(ta);
ta.select(); ta.setSelectionRange(0, text.length); try { document.execCommand('copy'); } catch {} ta.remove();
}
toast('Copied ✓');
}
/* ---------------- model loading ---------------- */
async function loadModel(opts = {}) {
el.retry.classList.add('hidden');
el.loaderTitle.textContent = 'Getting Flicker Flash ready';
setStatus('Loading model…');
try { navigator.storage && navigator.storage.persist && navigator.storage.persist(); } catch {}
const quiet = { debug() {}, log() {}, warn: console.warn.bind(console), error: console.error.bind(console) };
const w = new Wllama(WASM, { parallelDownloads: 3, allowOffline: true, logger: quiet });
let lastPct = -1;
const params = {
n_ctx: N_CTX,
cache_type_k: opts.plainKV ? undefined : 'q8_0',
cache_type_v: opts.plainKV ? undefined : 'q8_0',
flash_attn: opts.plainKV ? undefined : true,
...(opts.cpuOnly ? { n_gpu_layers: 0 } : {}),
progressCallback: ({ loaded, total }) => {
const pct = total ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
if (pct === lastPct) return; lastPct = pct;
el.bar.style.width = pct + '%';
el.loaderSub.textContent = pct >= 100
? 'Warming up the model…'
: `Downloading ${(loaded / 1048576).toFixed(0)} / ${(total / 1048576).toFixed(0)} MB · cached after the first time`;
setStatus(pct >= 100 ? 'Warming up…' : `Downloading ${pct}%`);
},
};
Object.keys(params).forEach((k) => params[k] === undefined && delete params[k]);
await w.loadModelFromUrl(MODEL_URL, params);
return w;
}
async function boot() {
const attempts = [{}, { plainKV: true, cpuOnly: true }];
let lastErr;
for (const opts of attempts) {
try {
state.wllama = await loadModel(opts);
state.ready = true;
el.bar.style.width = '100%';
el.loader.classList.add('hidden');
showEmptyIfNeeded();
const mt = state.wllama.isMultithread?.() ? `${state.wllama.getNumThreads()} threads` : 'on-device';
setStatus('Ready · ' + mt, 'ready');
updateSend();
return;
} catch (e) {
console.error('load failed', opts, e);
lastErr = e;
try { await state.wllama?.exit(); } catch {}
state.wllama = null;
}
}
el.loaderTitle.textContent = 'Couldn’t load the model';
el.loaderSub.textContent = (lastErr && lastErr.message ? lastErr.message : String(lastErr)).slice(0, 220) +
' — check your connection and free memory, then try again.';
el.retry.classList.remove('hidden');
setStatus('Load failed', 'err');
}
el.retry.onclick = () => boot();
/* ---------------- markdown ---------------- */
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
function inline(s) {
const codes = [];
s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
s = esc(s);
s = s.replace(/\\boxed\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g, '<span class="boxed">$1</span>');
s = s.replace(/\\\(|\\\)|\\\[|\\\]/g, '');
s = s.replace(/\$\$([^$]+)\$\$/g, '$1').replace(/\$([^$\n]*[=+\-*\/^×÷\\][^$\n]*)\$/g, '$1');
s = s.replace(/\\times/g, '×').replace(/\\cdot/g, '·').replace(/\\div/g, '÷').replace(/\\le(?![a-z])/g, '≤').replace(/\\ge(?![a-z])/g, '≥');
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/__([^_]+)__/g, '<strong>$1</strong>');
s = s.replace(/(^|[^*\w])\*([^*\n]+)\*(?!\w)/g, '$1<em>$2</em>');
s = s.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
s = s.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code class="inl">${esc(codes[+i])}</code>`);
return s;
}
const KW = /\b(function|return|const|let|var|if|else|for|while|in|of|def|class|import|from|as|new|this|true|false|null|None|True|False|print|elif|and|or|not|async|await|export|default|try|catch|except|with|lambda|yield|break|continue|switch|case|public|private|static|void|int|float|string|bool|struct|fn|pub|use|self)\b/;
function highlight(code, lang) {
lang = (lang || '').toLowerCase();
if (/^(html|svg|xml|htm)$/.test(lang)) {
return esc(code)
.replace(/(&lt;!--[\s\S]*?--&gt;)/g, '<span class="tk-c">$1</span>')
.replace(/(&lt;\/?)([a-zA-Z][\w:-]*)/g, '$1<span class="tk-t">$2</span>')
.replace(/([\w:-]+)=(&quot;[^&]*?&quot;)/g, '<span class="tk-k">$1</span>=<span class="tk-s">$2</span>');
}
const re = /(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`|\b\d+(?:\.\d+)?\b|\b[A-Za-z_]\w*\b)/g;
const hashComments = /^(python|py|bash|sh|shell|ruby|rb|yaml|yml|r|perl)$/.test(lang);
let out = '', last = 0, m;
while ((m = re.exec(code))) {
out += esc(code.slice(last, m.index)); last = re.lastIndex;
const t = m[0];
if (t.startsWith('//') || t.startsWith('/*') || (t.startsWith('#') && hashComments)) out += `<span class="tk-c">${esc(t)}</span>`;
else if (t.startsWith('#')) { out += esc(t[0]); re.lastIndex = m.index + 1; last = re.lastIndex; }
else if (/^["'`]/.test(t)) out += `<span class="tk-s">${esc(t)}</span>`;
else if (/^\d/.test(t)) out += `<span class="tk-n">${t}</span>`;
else if (KW.test(t) && t.match(KW)[0] === t) out += `<span class="tk-k">${t}</span>`;
else out += esc(t);
}
return out + esc(code.slice(last));
}
function isPreviewable(lang, code) {
lang = (lang || '').toLowerCase();
if (/^(html|htm|svg)$/.test(lang)) return true;
if (/^(xml|)$/.test(lang) && /<svg[\s>]/i.test(code)) return true;
if (!lang && /<!DOCTYPE html|<html[\s>]/i.test(code)) return true;
return false;
}
function codeBlockHTML(lang, code, open) {
const pv = isPreviewable(lang, code);
return `<div class="code-block" data-lang="${esc(lang || '')}">
<div class="code-head"><span class="lang">${esc(/^(lua|luau|roblox)$/i.test(lang||'') ? 'Roblox script (Luau)' : (lang || 'code'))}</span>${pv ? '<button class="cbtn pv" data-act="preview">▶ Preview</button>' : ''}<button class="cbtn" data-act="copy">Copy</button></div>
<pre><code>${highlight(code, lang)}${open ? '' : ''}</code></pre></div>`;
}
// wrap raw (unfenced) HTML / SVG output in a fence so it gets Copy + Preview
function fenceRaw(text) {
if (text.includes('```')) return text;
let m = text.search(/<!DOCTYPE html|<html[\s>]/i);
if (m >= 0) {
const endIdx = text.search(/<\/html>/i);
const end = endIdx >= 0 ? endIdx + 7 : text.length;
return text.slice(0, m) + '\n```html\n' + text.slice(m, end) + '\n```\n' + text.slice(end);
}
m = text.search(/<svg[\s>]/i);
if (m >= 0) {
const endIdx = text.lastIndexOf('</svg>');
const end = endIdx >= 0 ? endIdx + 6 : text.length;
return text.slice(0, m) + '\n```svg\n' + text.slice(m, end) + '\n```\n' + text.slice(end);
}
return text;
}
function md(src) {
src = fenceRaw(src.replace(/\r/g, ''));
const lines = src.split('\n');
let html = '', i = 0, para = [];
const flush = () => { if (para.length) { html += `<p>${inline(para.join('\n')).replace(/\n/g, '<br>')}</p>`; para = []; } };
while (i < lines.length) {
const line = lines[i];
const fence = line.match(/^\s*```\s*([\w+#.-]*)/);
if (fence) {
flush();
const lang = fence[1] || '';
const buf = []; i++;
while (i < lines.length && !/^\s*```\s*$/.test(lines[i])) buf.push(lines[i++]);
const closed = i < lines.length; i++;
html += codeBlockHTML(lang, buf.join('\n'), !closed);
continue;
}
if (/^\s*$/.test(line)) { flush(); i++; continue; }
let h = line.match(/^(#{1,6})\s+(.*)$/);
if (h) { flush(); const n = Math.min(4, h[1].length); html += `<h${n}>${inline(h[2])}</h${n}>`; i++; continue; }
if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) { flush(); html += '<hr>'; i++; continue; }
if (/^\s*>/.test(line)) {
flush(); const buf = [];
while (i < lines.length && /^\s*>/.test(lines[i])) buf.push(lines[i++].replace(/^\s*>\s?/, ''));
html += `<blockquote>${inline(buf.join('\n')).replace(/\n/g, '<br>')}</blockquote>`; continue;
}
if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1])) {
flush(); const row = (l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
const head = row(line); i += 2; let t = '<table><thead><tr>' + head.map((c) => `<th>${inline(c)}</th>`).join('') + '</tr></thead><tbody>';
while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) t += '<tr>' + row(lines[i++]).map((c) => `<td>${inline(c)}</td>`).join('') + '</tr>';
html += t + '</tbody></table>'; continue;
}
const li = line.match(/^\s*([-*+]|\d+[.)])\s+(.*)$/);
if (li) {
flush(); const ordered = /\d/.test(li[1]); const tag = ordered ? 'ol' : 'ul'; let items = '';
while (i < lines.length) {
const m2 = lines[i].match(/^\s*([-*+]|\d+[.)])\s+(.*)$/);
if (!m2 || /\d/.test(m2[1]) !== ordered) break;
items += `<li>${inline(m2[2])}</li>`; i++;
}
html += `<${tag}>${items}</${tag}>`; continue;
}
para.push(line); i++;
}
flush();
return html;
}
/* ---------------- preview ---------------- */
function buildDoc(code, lang) {
lang = (lang || '').toLowerCase();
const vp = '<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">';
const isFullHtml = /<!DOCTYPE html|<html[\s>]/i.test(code);
if (isFullHtml) {
if (!/name=["']?viewport/i.test(code)) code = code.replace(/<head[^>]*>/i, (m) => m + vp);
return code;
}
if (lang === 'svg' || lang === 'xml' || (/^\s*(<\?xml[^>]*>\s*)?<svg[\s>]/i.test(code))) {
code = code.replace(/<svg\b[^>]*>/i, (tag) => {
if (/viewBox=/i.test(tag)) return tag;
const w = tag.match(/\swidth=["']?(\d+(?:\.\d+)?)/i), h = tag.match(/\sheight=["']?(\d+(?:\.\d+)?)/i);
return w && h ? tag.replace(/<svg/i, `<svg viewBox="0 0 ${w[1]} ${h[1]}"`) : tag;
});
return `<!DOCTYPE html><html><head>${vp}<style>html,body{margin:0;height:100%;background:#fff}body{display:grid;place-items:center}body>svg{width:min(88vw,80vh);height:auto;max-height:88vh}</style></head><body>${code}</body></html>`;
}
return `<!DOCTYPE html><html><head><meta charset="utf-8">${vp}<style>body{margin:0;font-family:-apple-system,system-ui,sans-serif}</style></head><body>${code}</body></html>`;
}
function openPreview(code, lang) {
state.lastPreview = buildDoc(code, lang);
el.frame.srcdoc = state.lastPreview;
el.sheet.classList.remove('hidden');
document.body.style.overflow = 'hidden';
}
function closePreview() {
el.sheet.classList.add('hidden');
el.frame.srcdoc = '<!DOCTYPE html><html><body></body></html>';
document.body.style.overflow = '';
}
el.sheetClose.onclick = closePreview;
el.sheetReload.onclick = () => { el.frame.srcdoc = ''; requestAnimationFrame(() => (el.frame.srcdoc = state.lastPreview)); };
el.sheet.addEventListener('click', (e) => { if (e.target === el.sheet) closePreview(); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !el.sheet.classList.contains('hidden')) closePreview(); });
// event delegation for code buttons
el.messages.addEventListener('click', (e) => {
const b = e.target.closest('[data-act]'); if (!b) return;
const act = b.dataset.act;
if (act === 'copy' || act === 'preview') {
const block = b.closest('.code-block');
const code = block.querySelector('pre code').textContent;
if (act === 'copy') { copyText(code); b.textContent = 'Copied ✓'; b.classList.add('ok'); setTimeout(() => { b.textContent = 'Copy'; b.classList.remove('ok'); }, 1500); } else openPreview(code, block.dataset.lang);
} else if (act === 'copyall') {
const msg = b.closest('.msg'); copyText(msg._answer || ''); const t0 = b.textContent; b.textContent = 'Copied ✓'; b.classList.add('ok'); setTimeout(() => { b.textContent = t0; b.classList.remove('ok'); }, 1500);
} else if (act === 'previewlast') {
const msg = b.closest('.msg'); const blocks = [...msg.querySelectorAll('.code-block')].filter((x) => x.querySelector('[data-act="preview"]'));
const blk = blocks[blocks.length - 1]; if (blk) openPreview(blk.querySelector('pre code').textContent, blk.dataset.lang);
}
});
/* ---------------- chat UI ---------------- */
function showEmptyIfNeeded() {
el.empty.classList.toggle('hidden', !state.ready || el.messages.children.length > 0);
}
CHIPS.forEach((c) => {
const b = document.createElement('button'); b.className = 'chip'; b.textContent = c;
b.onclick = () => { if (!state.ready || state.busy) return; el.input.value = c; autosize(); send(); };
el.chips.appendChild(b);
});
function nearBottom() { const s = el.scroller; return s.scrollHeight - s.scrollTop - s.clientHeight < 140; }
function toBottom(force) { if (force || stick) el.scroller.scrollTop = el.scroller.scrollHeight; }
let stick = true;
el.scroller.addEventListener('scroll', () => { stick = nearBottom(); }, { passive: true });
function addUser(text) {
const m = document.createElement('div'); m.className = 'msg user';
const b = document.createElement('div'); b.className = 'bubble'; b.textContent = text;
m.appendChild(b); el.messages.appendChild(m); showEmptyIfNeeded();
}
function addBot() {
const m = document.createElement('div'); m.className = 'msg bot';
m.innerHTML = `<div class="bubble"><details class="thought hidden"><summary><span>Thinking…</span></summary><div class="tbody"></div></details><div class="answer"><span class="typing"><i></i><i></i><i></i></span></div></div><div class="meta hidden"></div>`;
el.messages.appendChild(m);
return { root: m, thought: m.querySelector('.thought'), tsum: m.querySelector('.thought summary span'), tbody: m.querySelector('.tbody'), answer: m.querySelector('.answer'), meta: m.querySelector('.meta') };
}
function splitThink(reasoning, content) {
let thought = reasoning || '', answer = content || '', thinkingOpen = false;
const o = answer.indexOf('<think>');
if (o >= 0) {
const c = answer.indexOf('</think>', o);
if (c >= 0) { thought += answer.slice(o + 7, c); answer = answer.slice(0, o) + answer.slice(c + 8); }
else { thought += answer.slice(o + 7); answer = answer.slice(0, o); thinkingOpen = true; }
} else if (answer.includes('</think>')) { // template opened <think> in the prompt
const c = answer.indexOf('</think>'); thought += answer.slice(0, c); answer = answer.slice(c + 8);
}
return { thought: thought.trim(), answer: answer.replace(/^\s+/, ''), thinkingOpen };
}
function addCaret(root) {
let node = root.lastElementChild;
while (node) {
if (node.classList.contains('code-block')) { node = node.querySelector('pre code'); break; }
if (/^(UL|OL|BLOCKQUOTE|TABLE|TBODY|TR)$/.test(node.tagName) && node.lastElementChild) { node = node.lastElementChild; continue; }
break;
}
const c = document.createElement('span'); c.className = 'caret';
(node || root).appendChild(c);
}
/* ---------------- history trimming (~4k ctx) ---------------- */
const estTok = (s) => Math.ceil(s.length / 3.2) + 6;
function buildMessages(maxNew) {
const budget = N_CTX - maxNew - estTok(SYSTEM) - 48;
const out = []; let used = 0;
for (let i = state.history.length - 1; i >= 0; i--) {
const h = state.history[i]; let c = h.content; let t = estTok(c);
if (used + t > budget) {
if (out.length === 0) { c = c.slice(-Math.floor((budget - 10) * 3.2)); t = estTok(c); } else break;
}
out.unshift({ role: h.role, content: c }); used += t;
}
while (out.length && out[0].role !== 'user') out.shift();
return [{ role: 'system', content: SYSTEM }, ...out];
}
/* ---------------- send / stream ---------------- */
function updateSend() {
el.send.disabled = !state.ready || state.busy || !el.input.value.trim();
el.send.classList.toggle('hidden', state.busy);
el.stop.classList.toggle('hidden', !state.busy);
}
function autosize() { el.input.style.height = 'auto'; el.input.style.height = Math.min(160, el.input.scrollHeight) + 'px'; updateSend(); }
el.input.addEventListener('input', autosize);
el.input.addEventListener('keydown', (e) => {
const touch = matchMedia('(pointer:coarse)').matches;
if (e.key === 'Enter' && !e.shiftKey && !touch && !e.isComposing) { e.preventDefault(); send(); }
});
el.send.onclick = () => send();
el.stop.onclick = () => { state.abort?.abort(); };
el.think.onclick = () => {
state.thinking = !state.thinking; localStorage.setItem('ff_think', state.thinking ? '1' : '0');
el.think.setAttribute('aria-pressed', String(state.thinking));
const effBtns = document.querySelectorAll('#effort button');
function setEffort(e, quiet) {
localStorage.setItem('ff_effort', e); SYSTEM = SYSP(e);
effBtns.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.eff === e)));
if (!quiet) toast('Effort: ' + e[0].toUpperCase() + e.slice(1));
}
effBtns.forEach((b) => (b.onclick = () => setEffort(b.dataset.eff)));
setEffort(localStorage.getItem('ff_effort') || 'medium', true);
toast(state.thinking ? '🧠 Thinking on' : 'Thinking off');
};
el.think.setAttribute('aria-pressed', String(state.thinking));
el.newChat.onclick = () => {
if (state.busy) state.abort?.abort();
state.history = []; el.messages.innerHTML = ''; showEmptyIfNeeded(); el.input.focus();
};
async function send() {
const text = el.input.value.trim();
if (!text || !state.ready || state.busy) return;
el.input.value = ''; autosize();
if (matchMedia('(pointer:coarse)').matches) el.input.blur();
state.busy = true; updateSend(); stick = true;
addUser(text);
state.history.push({ role: 'user', content: text });
const ui = addBot(); toBottom(true);
const thinking = state.thinking;
const eff = localStorage.getItem('ff_effort') || 'medium';
const maxNew = thinking ? 3072 : (eff === 'low' ? 768 : eff === 'high' ? 3072 : 2048);
const messages = buildMessages(maxNew);
const ac = new AbortController(); state.abort = ac;
let reasoning = '', content = '', nTok = 0, t0 = performance.now(), tFirst = 0, stopped = false, error = null, finish = null;
let pending = false;
const tThinkStart = performance.now(); let tThinkEnd = 0;
let done = false;
const render = (final) => {
pending = false;
if (done && !final) return;
if (final) done = true;
const { thought, answer, thinkingOpen } = splitThink(reasoning, content);
const stillThinking = !final && (thinkingOpen || (thought && !answer));
if (thought) {
ui.thought.classList.remove('hidden');
ui.thought.classList.toggle('thinking-live', stillThinking);
if (!stillThinking && !tThinkEnd) tThinkEnd = performance.now();
ui.tsum.textContent = stillThinking ? 'Thinking…' : `Thought for ${Math.max(1, Math.round(((tThinkEnd || performance.now()) - tThinkStart) / 1000))}s`;
ui.tbody.textContent = thought;
if (stillThinking && ui.thought.open) ui.tbody.scrollTop = ui.tbody.scrollHeight;
}
if (answer) {
ui.answer.innerHTML = md(answer);
if (!final) addCaret(ui.answer);
} else if (final) {
ui.answer.innerHTML = stopped ? '<em style="color:var(--mute)">Stopped.</em>' : (error ? '' : '<em style="color:var(--mute)">(no answer)</em>');
} else if (!stillThinking || !thought) {
// keep typing dots
} else {
ui.answer.innerHTML = '';
}
ui.root._answer = answer;
toBottom();
};
const schedule = () => { if (!pending) { pending = true; requestAnimationFrame(() => render(false)); } };
try {
setStatus(thinking ? 'Thinking…' : 'Generating…', 'busy');
const stream = await state.wllama.createChatCompletion({
messages, stream: true, max_tokens: maxNew,
temperature: 0.7, top_p: 0.95, top_k: 20,
chat_template_kwargs: { enable_thinking: thinking },
abortSignal: ac.signal,
});
for await (const chunk of stream) {
const ch = chunk && chunk.choices && chunk.choices[0];
if (!ch) continue;
const d = ch.delta || {};
if (d.reasoning_content) { reasoning += d.reasoning_content; nTok++; }
if (d.content) { content += d.content; nTok++; }
if (nTok === 1 && !tFirst) tFirst = performance.now();
if (ch.finish_reason) finish = ch.finish_reason;
schedule();
if (ac.signal.aborted) { stopped = true; break; }
}
} catch (e) {
if (ac.signal.aborted || (e && /abort/i.test(e.name + ' ' + e.message))) stopped = true;
else { error = e; console.error(e); }
}
render(true);
const { answer } = splitThink(reasoning, content);
if (answer.trim()) state.history.push({ role: 'assistant', content: answer.trim() });
else state.history.pop(); // drop the unanswered user turn from context
const secs = (performance.now() - (tFirst || t0)) / 1000;
const speed = nTok > 1 && secs > 0 ? (nTok - 1) / secs : null;
state.lastSpeed = speed;
const hasPreview = !!ui.answer.querySelector('[data-act="preview"]');
let meta = '';
if (answer.trim()) meta += '<button class="mbtn" data-act="copyall">Copy all</button>';
if (hasPreview) meta += '<button class="mbtn pv" data-act="previewlast">▶ Preview</button>';
if (speed) meta += `<span>${speed.toFixed(1)} tok/s</span>`;
if (stopped) meta += '<span>· stopped</span>';
if (finish === 'length') meta += '<span>· hit length limit</span>';
if (error) meta += `<span class="err-text">Error: ${esc(String(error.message || error)).slice(0, 160)}</span>`;
ui.meta.innerHTML = meta; ui.meta.classList.toggle('hidden', !meta);
state.busy = false; state.abort = null; updateSend();
setStatus(speed ? `Ready · ${speed.toFixed(1)} tok/s` : 'Ready · on-device', 'ready');
toBottom();
}
/* ---------------- go ---------------- */
updateSend();
boot();