// 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" ? `