// The Fin AI chat front end for Gradio-backed demo Spaces. // The Space's Gradio app exposes `/chat` (gr.api, streaming); this page talks to it with @gradio/client. // window.FA_CHAT = { client, endpoint, image: bool, examples: [{text, label, image?}], params: [{key,label,min,max,step,value}], greeting, avatar } import { marked } from "https://cdn.jsdelivr.net/npm/marked@12.0.2/lib/marked.esm.js"; import DOMPurify from "https://cdn.jsdelivr.net/npm/dompurify@3.1.6/dist/purify.es.mjs"; const C = window.FA_CHAT; const $ = s => document.querySelector(s); // Gradio may run head scripts twice and renders our HTML after hydration: // run once, and only after #fa-log exists and is the same node on two checks in a row. if (window.__faChat) await new Promise(() => {}); // second copy: park forever window.__faChat = true; await new Promise(r => { let last = null; const ok = () => { const n = document.querySelector("#fa-log"); if (n && n === last) r(); else { last = n; setTimeout(ok, 120); } }; ok(); }); // @gradio/client must match the Space's Gradio major version (1.x for Gradio 5, 2.x for Gradio 6) const { Client, handle_file } = await import(`https://cdn.jsdelivr.net/npm/@gradio/client@${C.client}/dist/index.min.js`); const esc = s => String(s).replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const md = s => DOMPurify.sanitize(marked.parse(s || "", { breaks: true })); const log = $("#fa-log"), input = $("#fa-input"), send = $("#fa-send"), stop = $("#fa-stop"), clear = $("#fa-clear"), status = $("#fa-status"); const history = []; // [{role, content}] text-only turns sent to the model let stopNow = null, job = null, client = null, image = null, imageURL = null, lastImage = null, lastImageURL = null; // lastImage: reused for follow-ups // ---------- connection ---------- async function connect() { if (client) return client; status.dataset.state = "connecting"; status.querySelector("span").textContent = "Connecting…"; // ask for status events too: @gradio/client 1.x only streams "data" by default, so "complete" would never arrive client = await Client.connect(location.origin + location.pathname.replace(/\/$/, ""), { events: ["data", "status"] }); status.dataset.state = "ready"; status.querySelector("span").textContent = C.readyText || "Ready"; return client; } connect().catch(() => { status.dataset.state = "error"; status.querySelector("span").textContent = "Could not reach the model server"; }); // ---------- messages ---------- function bubble(role, html, extra = "") { log.querySelector(".fa-empty")?.remove(); const el = document.createElement("div"); el.className = `msg ${role}${extra}`; el.innerHTML = role === "assistant" ? `
${html}
` : `
${html}
`; log.appendChild(el); log.scrollTo({ top: log.scrollHeight, behavior: "smooth" }); return el.querySelector(".body"); } function empty() { log.innerHTML = `

${esc(C.greeting.title)}

${esc(C.greeting.text)}

`; } empty(); // ---------- examples ---------- $("#fa-examples").innerHTML = C.examples.map((x, i) => ``).join(""); $("#fa-examples").addEventListener("click", async e => { const b = e.target.closest(".ex"); if (!b || job) return; const x = C.examples[+b.dataset.i]; if (x.image) { const blob = await (await fetch(x.image)).blob(); setImage(new File([blob], x.image.split("/").pop(), { type: blob.type })); } input.value = x.text; autosize(); submit(); }); // ---------- image (multimodal demos) ---------- const drop = $("#fa-image"), preview = $("#fa-preview"); function setImage(f) { image = f; if (imageURL && imageURL !== lastImageURL) URL.revokeObjectURL(imageURL); imageURL = f ? URL.createObjectURL(f) : null; if (preview) { preview.hidden = !f; preview.querySelector("img").src = imageURL || ""; } } if (C.image && drop) { drop.addEventListener("change", () => drop.files[0] && setImage(drop.files[0])); preview.querySelector("button").addEventListener("click", () => setImage(null)); const composer = $(".composer"); ["dragenter", "dragover"].forEach(t => composer.addEventListener(t, e => { e.preventDefault(); composer.classList.add("drag"); })); ["dragleave", "drop"].forEach(t => composer.addEventListener(t, e => { e.preventDefault(); composer.classList.remove("drag"); })); composer.addEventListener("drop", e => { const f = [...e.dataTransfer.files].find(f => f.type.startsWith("image/")); if (f) setImage(f); }); input.addEventListener("paste", e => { const f = [...(e.clipboardData?.files || [])].find(f => f.type.startsWith("image/")); if (f) setImage(f); }); } // ---------- params ---------- const params = Object.fromEntries(C.params.map(p => [p.key, p.value])); $("#fa-params").innerHTML = C.params.map(p => ``).join(""); $("#fa-params").addEventListener("input", e => { const k = e.target.dataset.k; if (!k) return; params[k] = +e.target.value; $(`#pv-${k}`).textContent = e.target.value; }); // ---------- composer ---------- function autosize() { input.style.height = "auto"; input.style.height = Math.min(input.scrollHeight, 200) + "px"; send.disabled = !input.value.trim() || !!job; } input.addEventListener("input", autosize); input.addEventListener("keydown", e => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); submit(); } }); send.addEventListener("click", submit); stop.addEventListener("click", () => { job?.cancel(); stopNow?.(); }); clear.addEventListener("click", () => { if (job) return; history.length = 0; setImage(null); lastImage = null; empty(); }); autosize(); async function submit() { const text = input.value.trim(); if (!text || job) return; const img = image || lastImage, imgURL = image ? imageURL : lastImageURL; if (C.image && !img) { flash("Add an image first: upload, drop or paste a chart or table."); return; } input.value = ""; autosize(); bubble("user", (image ? `` : img ? `same image` : "") + esc(text).replace(/\n/g, "
")); const out = bubble("assistant", ``, " pending"); const msgEl = out.parentElement; document.body.classList.add("busy"); stop.hidden = false; send.hidden = true; let reply = "", t0 = performance.now(); try { const c = await connect(); const args = { message: text, history: history.slice(), ...params }; if (C.image) args.image = handle_file(img); job = c.submit(C.endpoint, args); // Don't `break` out of the iterator: with @gradio/client 1.x its return() never settles. Settle on our own instead, // on "complete", on "error", or when Stop is pressed. await new Promise((resolve, reject) => { stopNow = resolve; (async () => { try { for await (const ev of job) { if (ev.type === "data") { reply = ev.data[0] ?? ""; msgEl.classList.remove("pending"); out.innerHTML = md(reply) + ``; log.scrollTo({ top: log.scrollHeight }); } else if (ev.type === "status") { if (ev.stage === "pending" && ev.queue && ev.position > 0) out.innerHTML = `In queue · position ${ev.position + 1}`; if (ev.stage === "error") return reject(new Error(ev.message || "The model returned an error.")); if (ev.stage === "complete") return resolve(); } } resolve(); } catch (err) { reject(err); } })(); }); out.innerHTML = md(reply) || `No answer.`; msgEl.insertAdjacentHTML("beforeend", `
${((performance.now() - t0) / 1000).toFixed(1)} s ·
`); msgEl.querySelector(".copy").addEventListener("click", e => navigator.clipboard.writeText(reply).then(() => (e.target.textContent = "Copied ✓"))); history.push({ role: "user", content: text }, { role: "assistant", content: reply }); if (C.image && image) { lastImage = image; lastImageURL = imageURL; imageURL = null; } } catch (err) { msgEl.classList.remove("pending"); msgEl.classList.add("error"); out.innerHTML = reply ? md(reply) : `Something went wrong. ${esc(err.message || err)}`; } finally { job = null; stopNow = null; document.body.classList.remove("busy"); stop.hidden = true; send.hidden = false; autosize(); if (C.image) { image = null; if (preview) preview.hidden = true; } } } function flash(t) { const n = $("#fa-note"); n.textContent = t; n.classList.add("on"); clearTimeout(flash._t); flash._t = setTimeout(() => n.classList.remove("on"), 3200); } // ---------- page chrome ---------- document.querySelectorAll("[data-count]").forEach(el => { const to = +el.dataset.count, dec = +(el.dataset.dec || 0), t0 = performance.now(); if (matchMedia("(prefers-reduced-motion: reduce)").matches || document.hidden) { el.textContent = to.toFixed(dec); return; } const step = t => { const p = Math.min(1, (t - t0) / 1000); el.textContent = (to * (1 - Math.pow(1 - p, 3))).toFixed(dec); if (p < 1) requestAnimationFrame(step); }; requestAnimationFrame(step); setTimeout(() => (el.textContent = to.toFixed(dec)), 1300); }); const io = new IntersectionObserver(es => es.forEach(en => { if (en.isIntersecting) { en.target.classList.add("in"); io.unobserve(en.target); } }), { threshold: .1 }); document.querySelectorAll(".reveal").forEach(el => io.observe(el));