Spaces:
Paused

assistant / ui /web /src /components /ChatPane.svelte
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
43 kB
<script> import { onDestroy } from "svelte"; import { app, getGenSettingsOpen, setGenSettingsOpen, getChatCollapsed, setChatCollapsed, getHistory, setHistory, getRunLog, setRunLog, setBusy, PICKER_SOURCE, requestModelDownloadConfirm, trackModelDownload, t, } from "../lib/stores.svelte.js"; import { fetchDiskSpace, fetchModelCheck, fetchModelNotice, modelDownloadStatus, openChatSocket, openReports, resetAgent, saveReport, saveSetting, startModelDownload } from "../lib/api.js"; import { buildBasePayload, buildTabPayload } from "../lib/chatTabs.js"; import { RUN_TIMEOUT_OPTIONS } from "../lib/chatPresets.js"; import "./chat/ChatPane.css"; import PresetSelect from "./chat/PresetSelect.svelte"; import MessageList from "./chat/MessageList.svelte"; import Composer from "./chat/Composer.svelte"; import RagControls from "./chat/RagControls.svelte"; import DrControls from "./chat/DrControls.svelte"; import VisionControls from "./chat/VisionControls.svelte"; import DataControls from "./chat/DataControls.svelte"; import { ANALYSIS_PROMPTS } from "../lib/chatTabs.js"; import { scaledMaxSteps } from "../lib/autoDefaults.js"; import AgentControls from "./chat/AgentControls.svelte"; import MiniSelect from "./chat/MiniSelect.svelte"; import { bindClearShortcut, DEFAULT_CLEAR_CONFIRM_MIN } from "../lib/shortcuts.js"; /** 'general' | 'rag' | 'deep_research' | 'vision'. The pane is keyed by tab * in App.svelte, so each tab gets its own instance and its own history. */ let { tab, modelLabel, providerLabel } = $props(); // Keyed per tab, so these never change within an instance; derived keeps // the build warning-free and makes the intent explicit. const isRag = $derived(tab === "rag"); const isDr = $derived(tab === "deep_research"); const isVision = $derived(tab === "vision"); const isData = $derived(tab === "data"); // Report folder key (model_registry.REPORT_DIRS) for this pane's tab β€” // each chat tab's "Open Reports Folder" button opens ITS OWN folder. const reportTab = $derived( { general: "gen", rag: "rag", deep_research: "dr", vision: "vis", data: "data" }[tab] || tab || "" ); /** The concrete values this tab's "auto" controls resolve to β€” the * backend's base defaults (/api/meta autoDefaults) scaled to the CURRENT * picker model, so an empty field's placeholder shows the real number the * run will use instead of the opaque word "auto". Derived from the live * modelLabel so a mid-session model switch updates the placeholders too. * execTimeout: smolagents' 30s CodeAgent executor default (Data: 120s). */ const auto = $derived.by(() => { const d = app.meta?.autoDefaults ?? {}; const sb = d.stepBudgets ?? {}; return { maxSteps: scaledMaxSteps(modelLabel, sb.general ?? 8), searcherSteps: scaledMaxSteps(modelLabel, sb.rag_searcher ?? 5), workerSteps: scaledMaxSteps(modelLabel, sb.data_worker ?? 10), dataSteps: scaledMaxSteps(modelLabel, sb.data ?? 20), drManagerSteps: scaledMaxSteps(modelLabel, sb.deep_research ?? 12), drSearchSteps: scaledMaxSteps(modelLabel, sb.deep_research_search ?? 4), execTimeout: isData ? (d.execTimeout?.data ?? 120) : (d.execTimeout?.general ?? 30), }; }); /** Conversation history lives in the shared store (keyed by tab) so it * survives tab switches β€” the pane itself is keyed and recreated per tab. */ let history = $derived(getHistory(tab)); /** Real progress lines streamed from the backend run (llama-server * launch, model load, agent build, …) β€” shown live inside the status card * while the run is in flight. Store-backed so a tab switch mid-run keeps * them. */ const runLog = $derived(getRunLog(tab)); /** Optimistic echo of the user's message until the first server update. */ let pendingMsg = $state(""); /** Raw model tokens streamed LIVE from the run via `live` WS events * (backend.live_stream bus drained by _run_stream). While non-empty the * answer bubble shows this growing text INSTEAD of the status card β€” the * model is visibly "speaking". Cleared on update/final/stop. */ let liveText = $state(""); let input = $state(""); let agentic = $state(true); let memory = $state(true); let toolCalling = $state(true); // RAG-only retrieval-topic filters (bound into RagControls). Multi- // select: `themes` / `subthemes` are arrays of selected names (empty = // all), and `ragFiles` is the array of selected KB source filenames. let themes = $state([]); let subthemes = $state([]); let ragFiles = $state([]); // General/RAG agentic-mode step budgets (bound into AgentControls, shown // only while agentic mode is on). null = AUTO: the backend applies its // model-scaled default (full budget on small models, a fail-fast cap on // large/slow local GGUFs) β€” so the untouched control never overrides the // scaling. A typed number is the user's explicit budget; clearing the // field returns to auto (Svelte binds number inputs to null when empty). let maxSteps = $state(null); let searcherSteps = $state(null); // Data-tab-only: the data_worker SUB-AGENT's step budget (the Data // tab's "Sub-agent steps" control). Same AUTO semantics β€” null = the // backend's model-scaled default (DATA_WORKER_DEFAULT_MAX_STEPS). let workerSteps = $state(null); // General-only agentic per-step execution timeout (bound into // AgentControls, shown only while agentic mode is on). Same auto pattern: // null = the agent factory's default timeout; a number overrides it. let execTimeout = $state(null); // Per-tab whole-run generation timeout (seconds) β€” the Generation // Settings "Timeout" field. The server aborts a run that exceeds it. // null = no explicit deadline (the run finishes naturally). Deep Research // exposes the same setting through DrControls' own `drTimeout` state. let runTimeout = $state(null); // RAG-only: the visual path toggle (the page-image visual_retriever tool // + the VLM grounding pass). Default OFF β€” resource-intensive. Sent in // the RAG WS payload; the backend skips all visual work when false. let visualRetrieval = $state(false); // Deep-Research-only budgets (bound into DrControls). let usePlaywright = $state(false); let headless = $state(false); let managerSteps = $state(12); let searchSteps = $state(6); let drTimeout = $state(300); // Data-tab-only state (bound into DataControls): the uploaded files // (temp paths from /api/data/upload β€” the WS payload sends them, the // backend deletes them after the run) and the analysis-preset workflow // (becomes the message when the composer is empty, like the old tab's // "question || preset" flow). maxSteps/execTimeout above double as the // data tab's step budget / code-execution timeout (the EDA always runs a // CodeAgent, so the AUTO semantics apply just like General agentic). let dataFiles = $state([]); let analysisType = $state("exploratory"); // Per-tab context window (n_ctx) β€” the dropdown value is the option LABEL // (the backend maps the label to the token count). Restored from meta and // saved per tab β€” same key the old Settings card used to write. let ctxLabel = $state(""); /** Restore the persisted per-tab step budgets into the controls once * /api/meta arrives (meta is loaded before the panes mount, but the * effect makes the wiring robust either way). null = auto. DR's * defaults (12/6) are kept when nothing was ever saved. */ $effect(() => { const sb = app.meta?.savedStepBudgets; if (tab === "general") { maxSteps = sb?.general ?? null; execTimeout = app.meta?.savedExecutionTimeout?.general ?? null; } else if (isRag) { maxSteps = sb?.rag ?? null; searcherSteps = sb?.rag_searcher ?? null; execTimeout = app.meta?.savedExecutionTimeout?.rag ?? null; } else if (isDr) { managerSteps = sb?.deep_research ?? 12; searchSteps = sb?.deep_research_search ?? 6; drTimeout = sb?.deep_research_timeout ?? 300; execTimeout = app.meta?.savedExecutionTimeout?.deep_research ?? null; } else if (isData) { maxSteps = sb?.data ?? null; workerSteps = sb?.data_worker ?? null; execTimeout = app.meta?.savedExecutionTimeout?.data ?? null; } }); // Restore this tab's saved context-window label once meta arrives (the // pane may mount before /api/meta resolves, so the effect does the wiring). // NOTE: the effect must NOT read `ctxLabel` back β€” that would make the // user's own edits a reactive dependency and snap the dropdown back to // the saved value on every pick (the "can't change the Run Timeout" bug // class). Restore only when meta's saved value itself changes. $effect(() => { const saved = app.meta?.savedCtxWindow?.[tab]; if (saved) ctxLabel = saved; }); // Restore this tab's saved whole-run generation timeout (the Generation // Settings "Timeout" field) once meta arrives β€” Deep Research keeps its // own DrControls timeout, so only the other chat tabs read this. // NOTE: same rule as the ctx restore above β€” never read `runTimeout` // back in this effect, or every keystroke re-runs it and it clobbers // the user's edit with the persisted value (the reported "Run Timeout // can't be changed in the RAG tab" bug). $effect(() => { if (isDr) return; const saved = app.meta?.savedRunTimeout?.[tab]; if (saved) runTimeout = saved; }); // Restore this tab's saved RAG visual toggle once meta arrives. $effect(() => { if (!isRag) return; const saved = app.meta?.savedVisualRetrieval; if (typeof saved === "boolean") visualRetrieval = saved; }); /** Persist this tab's context window (n_ctx) choice β€” the label IS the * value the backend expects (it maps it to the token count). Mirrors the * old Settings card's save handler, per-tab. */ function onCtxChange() { saveSetting("ctx_window", ctxLabel, tab).catch(() => {}); if (app.meta?.savedCtxWindow) app.meta.savedCtxWindow[tab] = ctxLabel; } /** Persist this tab's whole-run generation timeout and keep meta fresh so * a remount of this pane (tab switch away/back) shows the saved value, * not a stale one. null = back to no explicit deadline. */ function onRunTimeoutChange() { saveSetting("run_timeout", runTimeout ?? null, tab).catch(() => {}); if (app.meta) { if (!app.meta.savedRunTimeout) app.meta.savedRunTimeout = {}; app.meta.savedRunTimeout[tab] = runTimeout ?? null; } } /** Persist the RAG tab's visual-retrieval toggle (default OFF). Saved * under the 'rag' tab key so a remount shows the same choice. */ function onVisualRetrievalChange() { saveSetting("visual_retrieval", visualRetrieval, "rag").catch(() => {}); if (app.meta) app.meta.savedVisualRetrieval = visualRetrieval; } /** Persist a budget and keep meta fresh so a remount of this pane * (tab switch away/back) shows the saved value, not the stale default. */ function persistSteps(settingKey, value, metaKey) { saveSetting(settingKey, value ?? null, tab).catch(() => {}); if (app.meta) { if (settingKey === "execution_timeout") { if (!app.meta.savedExecutionTimeout) app.meta.savedExecutionTimeout = {}; app.meta.savedExecutionTimeout[metaKey] = value ?? null; } else { if (!app.meta.savedStepBudgets) app.meta.savedStepBudgets = {}; app.meta.savedStepBudgets[metaKey] = value ?? null; } } } /** AgentControls (General/RAG) β€” map the setting key to the meta key. */ function onSteps(settingKey, value) { const metaKey = settingKey === "execution_timeout" ? (isRag ? "rag" : "general") : (isRag ? (settingKey === "searcher_max_steps" ? "rag_searcher" : "rag") : "general"); persistSteps(settingKey, value, metaKey); } /** DrControls β€” ALL three budgets persist (manager/search steps + the * whole-run timeout) so they survive a restart. The DrControls keys map * to the backend save keys (agent_max_steps / searcher_max_steps / * deep_research_timeout) and the meta keys this pane restores from. */ function onDrBudget(settingKey, value) { const map = { manager_max_steps: { saveKey: "agent_max_steps", metaKey: "deep_research" }, search_max_steps: { saveKey: "searcher_max_steps", metaKey: "deep_research_search" }, timeout: { saveKey: "deep_research_timeout", metaKey: "deep_research_timeout" }, execution_timeout: { saveKey: "execution_timeout", metaKey: "deep_research" }, }; const m = map[settingKey]; if (!m) return; persistSteps(m.saveKey, value, m.metaKey); } /** DataControls β€” the step budgets AND the per-step code-execution * timeout persist (manager "agent_max_steps" + the data_worker sub- * agent's "searcher_max_steps" backend slot, plus "execution_timeout" * for the Exec timeout preset) so they survive a restart, mirroring the * RAG/DR tabs. */ function onDataSteps(settingKey, value) { const map = { max_steps: { saveKey: "agent_max_steps", metaKey: "data" }, worker_max_steps: { saveKey: "searcher_max_steps", metaKey: "data_worker" }, execution_timeout: { saveKey: "execution_timeout", metaKey: "data" }, }; const m = map[settingKey]; if (!m) return; persistSteps(m.saveKey, value, m.metaKey); } // Vision-only: uploaded image (temp path from /api/upload) + preview URL // and the mmproj (vision projector) label β€” image state is bound into // VisionControls; mmprojLabel feeds the payload. The Vision tab is fully // standalone: no knowledge-base (text or visual-index) retrieval feeds it. let imagePath = $state(""); let imagePreview = $state(""); let mmprojLabel = $state(""); let flash = $state(""); let flashErr = $state(false); // Inline notice below the πŸ’Ύ Save Report button (the pane's flash stays // for everything else). let saveMsg = $state(""); let saveMsgErr = $state(false); let ws = null; // ── Model download status notice ────────────────────────────────── // Shows whether the selected model is downloaded, needs downloading, // or is a remote/cloud model. Fetches from /api/model-notice whenever // the tab's model/provider changes. let modelNotice = $state(""); let modelNoticeRaw = $state(""); // Detect download-in-progress from WS log lines (the GGUF download // prints "[llama.cpp] Downloading…" and HF models print progress). let modelDownloading = $state(false); let downloadProgress = $state(""); // ── Pre-download button state ─────────────────────────────────── let preDownloadBusy = $state(false); let preDownloadDone = $state(false); let preDownloadError = $state(""); let preDownloadProgress = $state(""); let preDownloadTimer = null; // ── Disk space check ───────────────────────────────────────────── let diskSpace = $state(null); // {available_gb, total_gb, path} let diskWarn = $state(false); let diskNeed = $state(0); // model size in GB let diskAvail = $state(0); let diskDrive = $state(""); const displayHistory = $derived( pendingMsg ? [...history, { role: "user", content: pendingMsg }] : history ); // Vision may send an image with no text; Data may send uploaded files // with an empty composer (the preset or the agent's default EDA prompt // then becomes the question); everyone else needs a message. const canSend = $derived(!!input.trim() || !!imagePath || dataFiles.length > 0); function onEvent(ev) { if (ev.type === "log") { // Terminal status lines captured from the backend run ([Model] load, // [llama-server] launch, [DataAgent]/[GeneralAgent] build, …) β€” // streamed into the answer area. Capped so a very long run can't grow // the DOM unboundedly. const lines = Array.isArray(ev.lines) ? ev.lines : []; if (lines.length) { setRunLog(tab, [...getRunLog(tab), ...lines].slice(-400)); detectDownloadProgress(lines); } } else if (ev.type === "update") { pendingMsg = ""; liveText = ""; setHistory(tab, ev.history); } else if (ev.type === "final") { pendingMsg = ""; liveText = ""; setHistory(tab, ev.history); app.exportText = ev.export || ""; endRun(); } else if (ev.type === "live") { // Real generated tokens from the model (backend.live_stream, drained // by _run_stream every 0.5s): `reset` starts a fresh answer (drop the // previous generation's tail), `text` appends the new delta. The // answer bubble grows from ACTUAL model output while the run is busy. if (ev.reset) liveText = ""; if (ev.text) liveText += ev.text; } else if (ev.type === "timeout") { // The run exceeded its Generation Settings "Timeout" β€” the server // aborted it mid-way. Surface the bilingual message as an assistant // bubble and clear the busy state. pendingMsg = ""; liveText = ""; setHistory(tab, [...history, { role: "assistant", content: ev.message }]); endRun(); } else if (ev.type === "error") { pendingMsg = ""; liveText = ""; setHistory(tab, [...history, { role: "assistant", content: "❌ " + ev.message }]); endRun(); } } function endRun() { liveText = ""; clearDownloadState(); setBusy(false); if (ws) { ws.close(); ws = null; } } function doSend(msg) { // A fresh turn starts with an empty terminal log. setRunLog(tab, []); clearDownloadState(); input = ""; // Once the user sends, collapse the Generation Settings section β€” the // composer stays clean for the next turn. setGenSettingsOpen(tab, false); pendingMsg = msg || (isData ? "πŸ“Š" : "πŸ–ΌοΈ"); setBusy(true); app.exportText = ""; ws = openChatSocket(onEvent); ws.send({ ...buildBasePayload(tab, { message: msg, history: getHistory(tab), modelLabel, lang: app.lang, memory, toolCalling, }), ...buildTabPayload(tab, { agentic, themes, subthemes, ragFiles, maxSteps, searcherSteps, workerSteps, execTimeout, runTimeout, usePlaywright, headless, managerSteps, searchSteps, drTimeout, imagePath, mmprojLabel, dataFiles, }), }); } async function send() { const msg = input.trim() || (isData ? ANALYSIS_PROMPTS[analysisType] || "" : ""); if ((!msg && !imagePath && !dataFiles.length) || app.busy) return; // Check if the current model is downloaded before sending const provider = providerLabel || app.pickers[tab]?.provider || ""; const model = modelLabel || app.pickers[tab]?.model || ""; const src = PICKER_SOURCE[tab]; if (src && model) { try { const chk = await fetchModelCheck(provider, model, src.type, app.lang); if (chk?.needs_download) { requestModelDownloadConfirm( { id: chk.model_id, label: model, size: chk.size_gb }, () => { doSend(msg); } ); return; } } catch {} } doSend(msg); } function stop() { endRun(); } function clearChat() { // If a run is streaming, stop it first β€” otherwise the WebSocket would // keep appending results into the just-cleared conversation. if (app.busy) endRun(); setHistory(tab, []); setRunLog(tab, []); pendingMsg = ""; liveText = ""; app.exportText = ""; removeImage(); dataFiles = []; // the Data tab's uploaded files are per-conversation // Gradio parity: clearing the chat also resets the cached agent so the // next run starts with empty memory. resetAgent({ tab }).catch(() => {}); } // Alt+Delete clears this tab's conversation (the πŸ—‘οΈ Clear button's twin // β€” same shortcut as the STT tab). The shared bindClearShortcut helper // owns the key combo and the listener's lifecycle (its returned cleanup // runs on unmount via $effect). For a LONG conversation (at/above the // user-tunable threshold β€” Settings β†’ "Confirm-clear threshold") the // shortcut asks for confirmation first: a fat-fingered Alt+Delete on a // big chat is irreversible, while a short exchange clears instantly. The // threshold is read LIVE from app.meta at keypress time, so a Settings // change applies immediately. The button click stays unconfirmed (an // explicit deliberate action). $effect(() => bindClearShortcut(clearChat, { confirm: () => { const min = app.meta?.clearConfirmMin ?? DEFAULT_CLEAR_CONFIRM_MIN; return history.length >= min ? { message: t("web_confirm_clear_chat").replace("{n}", String(history.length)), ok: t("btn_clear"), cancel: t("web_confirm_cancel"), } : null; }, }) ); function removeImage() { if (imagePreview) URL.revokeObjectURL(imagePreview); imagePreview = ""; imagePath = ""; } // ── Model notice fetch ──────────────────────────────────────────── const TAB_TYPE_MAP = { general: "llm", rag: "llm", deep_research: "llm", vision: "vlm", data: "llm" }; $effect(() => { const p = providerLabel; const m = modelLabel; if (!m) { modelNotice = ""; modelNoticeRaw = ""; return; } let stale = false; const type = TAB_TYPE_MAP[tab] || "llm"; fetchModelNotice(p || "", m, type, app.lang) .then((r) => { if (stale) return; modelNoticeRaw = r.notice || ""; modelNotice = r.notice || ""; // Also fetch disk space for not-downloaded models so we can warn // when the model won't fit on disk. const notice = r.notice || ""; if ((notice.includes("πŸ“₯") || notice.includes("🚨"))) { const sizeMatch = /~?([\d.]+)\s*GB/.exec(notice); const needGB = sizeMatch ? parseFloat(sizeMatch[1]) : 0; if (needGB > 0) { fetchDiskSpace().then((ds) => { if (stale || !ds.ok) return; diskSpace = ds; diskAvail = ds.available_gb || 0; diskDrive = ds.path || ""; diskNeed = needGB; diskWarn = diskAvail > 0 && diskAvail < needGB; }).catch(() => { diskWarn = false; }); } else { diskWarn = false; } } else { diskWarn = false; } }) .catch(() => { if (!stale) { modelNotice = ""; modelNoticeRaw = ""; diskWarn = false; } }); return () => { stale = true; }; }); /** Parse the raw /api/model-notice markdown into a structured object * for the template to render a nicer per-status notice. */ function parseModelNotice(raw) { if (!raw) return null; const isKh = app.lang === "kh"; // 🚨 Large model warning (β‰₯20GB) β€” check BEFORE πŸ“₯ since it replaces // the not-downloaded notice for heavy models. if (raw.includes("🚨")) { const sizeMatch = /~?([\d.]+)\s*GB/.exec(raw); const sizeStr = sizeMatch ? `~${sizeMatch[1]} GB` : ""; return { status: "large_warning", icon: "🚨", text: t("web_model_large_warning").replace("{size}", sizeStr), title: t("web_model_large_warning_title"), timeHint: t("web_model_large_warning_time"), }; } if (raw.includes("βœ…")) { // Downloaded/cached const sizeMatch = /\(([\d.]+) GB/.exec(raw); return { status: "downloaded", icon: "βœ…", text: sizeMatch ? t("web_model_downloaded") + ` (${sizeMatch[1]} GB)` : t("web_model_downloaded"), }; } if (raw.includes("πŸ“₯")) { // Not downloaded yet β€” show size const sizeMatch = /~?([\d.]+)\s*GB/.exec(raw); const sizeStr = sizeMatch ? `~${sizeMatch[1]} GB` : (isKh ? "αž˜αž·αž“αžŠαžΉαž„αž‘αŸ†αž αŸ†" : "unknown size"); return { status: "not_downloaded", icon: "πŸ“₯", text: t("web_model_not_downloaded").replace("{size}", sizeStr), }; } if (raw.includes("☁️")) { return { status: "cloud", icon: "☁️", text: t("web_model_cloud") }; } if (raw.includes("πŸ”—")) { return { status: "remote", icon: "πŸ”—", text: t("web_model_remote") }; } if (raw.includes("πŸ–₯️")) { return { status: "local", icon: "πŸ–₯️", text: t("web_model_local_file") }; } // Fallback: strip markdown, show raw const plain = raw.replace(/\*\*/g, "").replace(/`/g, "").replace(/\s+/g, " ").trim(); return { status: "info", icon: "ℹ️", text: plain }; } const parsedNotice = $derived(parseModelNotice(modelNoticeRaw)); /** Detect download-in-progress from WS log events. */ function detectDownloadProgress(lines) { for (const line of (lines || [])) { if (typeof line !== "string") continue; if (/Downloading.*\.gguf/i.test(line) || /Downloading GGUF/i.test(line) || /hf_hub_download/i.test(line) || /downloading model/i.test(line) || /Fetching.*files/i.test(line)) { modelDownloading = true; downloadProgress = line.replace(/\[.*?\]\s*/, ""); return; } } } /** Clear download state when run ends. */ function clearDownloadState() { modelDownloading = false; downloadProgress = ""; } // ── Pre-download button ────────────────────────────────────────── /** Extract the HF repo id from the model notice raw text. The model_id * is wrapped in backticks in the raw notice. */ function extractModelId(raw) { if (!raw) return ""; const m = /`([^`]+)`/.exec(raw); return m ? m[1] : ""; } /** Extract download size estimate from the raw notice text. */ function extractDownloadSize(raw) { if (!raw) return ""; const m = /~?([\d.]+)\s*GB/.exec(raw); return m ? `~${m[1]} GB` : ""; } /** Start a pre-download of the selected model in the background with confirmation. */ async function doPreDownload() { const modelId = extractModelId(modelNoticeRaw); if (!modelId || preDownloadBusy) return; // Skip non-HF models (local GGUF files, server backends, etc.) if (!modelId.includes("/") && !modelId.toLowerCase().endsWith(".gguf")) return; const size = extractDownloadSize(modelNoticeRaw); requestModelDownloadConfirm( { id: modelId, label: modelLabel || modelId, size }, async () => { preDownloadBusy = true; preDownloadDone = false; preDownloadError = ""; preDownloadProgress = ""; try { await startModelDownload(modelId); trackModelDownload(modelId, modelLabel || modelId); pollPreDownload(); } catch (err) { preDownloadBusy = false; preDownloadError = err.message || "Download failed"; } } ); } /** Poll the model download status until it finishes. */ function pollPreDownload() { if (preDownloadTimer) return; preDownloadTimer = setInterval(async () => { try { const r = await modelDownloadStatus(); preDownloadProgress = r.progress || ""; // cached alone never means complete while a download is running // (interrupted downloads leave config.json cached β€” see stores.js) if (r.done || (r.cached && !r.running)) { preDownloadDone = true; preDownloadBusy = false; preDownloadProgress = ""; clearInterval(preDownloadTimer); preDownloadTimer = null; // Refresh the model notice to show βœ… downloaded const modelId = extractModelId(modelNoticeRaw); const type = TAB_TYPE_MAP[tab] || "llm"; try { const nr = await fetchModelNotice(providerLabel || "", modelLabel || "", type, app.lang); modelNoticeRaw = nr.notice || ""; } catch { /* best-effort */ } } if (r.error) { preDownloadBusy = false; preDownloadError = r.error; clearInterval(preDownloadTimer); preDownloadTimer = null; } if (!r.running && !r.done && !r.error) { // Not running and not done = never started or finished before first poll preDownloadBusy = false; clearInterval(preDownloadTimer); preDownloadTimer = null; } } catch { /* transient network error β€” keep polling */ } }, 1500); } onDestroy(() => { if (preDownloadTimer) clearInterval(preDownloadTimer); }); /** Whether the current model notice qualifies for a Download Now button. */ const canPreDownload = $derived( parsedNotice && (parsedNotice.status === "not_downloaded" || parsedNotice.status === "large_warning") && !preDownloadDone && extractModelId(modelNoticeRaw).includes("/") ); let lastSavedReportFolder = $state(""); async function doSaveReport() { if (!app.exportText) return; flash = ""; flashErr = false; try { const r = await saveReport({ tab, markdown: app.exportText, filename: "", }); if (r.ok && r.folder) { lastSavedReportFolder = r.folder; } else if (r.ok && r.path) { lastSavedReportFolder = r.path; } // The confirmation appears inline, right below this button. saveMsg = r.ok ? (r.path ? t("web_saved_path").replace("{path}", r.path) : t("web_saved_ok")) : t("web_saved_fail"); saveMsgErr = !r.ok; } catch { saveMsg = t("web_saved_fail"); saveMsgErr = true; } } /** Open the reports folder in the OS file explorer (the saved .docx * reports live under user_data/reports/<tab>/). */ async function doOpenReports() { flash = ""; flashErr = false; try { // This pane's own tab folder (user_data/reports/<tab>/), or the exact report folder if saved. const r = await openReports(reportTab, lastSavedReportFolder); flash = r.ok ? (r.path ? t("web_opened_path").replace("{path}", r.path) : t("web_opened")) : t("web_open_failed"); flashErr = !r.ok; } catch (err) { flash = err.message; flashErr = true; } } /** Flash sink handed to VisionControls for upload errors. */ function notifyFlash(msg, isErr) { flash = msg; flashErr = !!isErr; } /** Copy all conversation messages to clipboard as formatted text. */ async function copyAllResults() { const lines = []; for (const msg of history) { const role = msg.role === "user" ? t("web_copy_user") : t("web_copy_assistant"); // Strip HTML tags from the answer for clean clipboard text const text = (msg.content || "") .replace(/<[^>]+>/g, "") .replace(/&nbsp;/g, " ") .replace(/&amp;/g, "&") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">") .trim(); if (text) lines.push(`${role}:\n${text}\n`); } if (!lines.length) return; try { await navigator.clipboard.writeText(lines.join("\n")); flashMsg(t("web_copied")); } catch { flashMsg(t("web_copy_fail"), true); } } onDestroy(() => { if (ws) ws.close(); if (imagePreview) URL.revokeObjectURL(imagePreview); }); </script> <div class="chat"> <MessageList {tab} messages={displayHistory} busy={app.busy} runLog={runLog} liveText={liveText} /> <!-- Model download status notice removed β€” the same info already shows as a chip near the model dropdown in the header (App.svelte). --> <!-- Input-area collapser β€” a slim always-visible strip between the messages and the input bar. It hides/shows the WHOLE lower part (the uploads, composer, Generation Settings and the tool row) so a long conversation can be read full-height. State lives in the shared store keyed by tab (the same reason as genSettingsOpen: the pane is destroyed on every tab switch) and reads reactively here, so the inputbar just disappears/reappears. --> <button type="button" class="chat-collapser" onclick={() => setChatCollapsed(tab, !getChatCollapsed(tab))} data-tooltip={t("web_tt_collapse_input")} > {getChatCollapsed(tab) ? t("web_show_input") : t("web_collapse_input")} </button> {#if !getChatCollapsed(tab)} <div class="inputbar"> <div class="inputbar-inner"> <!-- Vision's image upload stays visible β€” it's the INPUT for this tab, not a setting (the projector select below is the setting). --> {#if isVision} <VisionControls bind:imagePath bind:imagePreview notify={notifyFlash} imageOnly /> {/if} <!-- Data's file upload stays visible β€” it's the INPUT for this tab (the analysis preset + step budgets hide in Generation Settings). --> {#if isData} <DataControls bind:dataFiles bind:analysisType bind:maxSteps bind:workerSteps bind:execTimeout autoMaxSteps={auto.dataSteps} autoWorkerSteps={auto.workerSteps} autoExecTimeout={auto.execTimeout} notify={notifyFlash} onSteps={onDataSteps} fileOnly /> {/if} <!-- RAG's Knowledge Base notice + Theme/Subtheme retrieval filters live ABOVE the composer β€” they are per-message INPUT (which KB slice to search), not settings, so they stay visible instead of hiding inside the collapsed Generation Settings section. --> {#if isRag} <RagControls bind:themes bind:subthemes bind:files={ragFiles} /> {/if} <Composer bind:input busy={app.busy} canSend={canSend} onSend={send} onStop={stop} /> <!-- Generation Settings β€” everything that used to crowd the input area is collapsed below the composer: the mode chips, this tab's context-window dropdown, and the tab-specific controls (RAG filters, agentic budgets, Deep Research budgets, vision projector). Collapsed by default so the composer stays clean. --> <!-- Expanded/collapsed state lives in the shared store (keyed by tab): the pane is keyed per tab and destroyed on every switch, so a local <details> would reset to collapsed. `open` restores the remembered state on mount; `ontoggle` remembers the user's click (the browser fires it on summary toggle, before any re-render). --> <details class="gen-settings" open={getGenSettingsOpen(tab)} ontoggle={(e) => setGenSettingsOpen(tab, e.currentTarget.open)} > <summary> <span class="gen-settings-title">{t("web_generation_settings")}</span> </summary> <div class="gen-settings-body"> <div class="chip-row"> {#if isDr} <label class="chip" class:on={usePlaywright} data-tooltip={t("web_tt_playwright")}> <input type="checkbox" bind:checked={usePlaywright} /> {t("web_playwright")} </label> <label class="chip" class:on={headless} data-tooltip={t("web_tt_headless")}> <input type="checkbox" bind:checked={headless} /> {t("web_headless")} </label> {:else if !isData} <label class="chip" class:on={agentic} data-tooltip={t("web_tt_agentic")}> <input type="checkbox" bind:checked={agentic} /> {t("web_agentic")} </label> {/if} <label class="chip" class:on={memory} data-tooltip={t("info_memory")}> <input type="checkbox" bind:checked={memory} /> {t("web_memory")} </label> {#if !isVision && !isData} <label class="chip" class:on={toolCalling} data-tooltip={t("web_tt_tool_calling")}> <input type="checkbox" bind:checked={toolCalling} /> {t("web_tool_calling")} </label> {/if} {#if isRag} <!-- RAG-only: the resource-intensive visual path β€” the page-image `visual_retriever` tool (agentic mode) + the VLM grounding pass. Default OFF (pure text retrieval + the text LLM); the change persists immediately like the other chips. --> <label class="chip" class:on={visualRetrieval} data-tooltip={t("web_tt_rag_visual")}> <input type="checkbox" bind:checked={visualRetrieval} onchange={onVisualRetrievalChange} /> {t("web_rag_visual")} </label> {/if} </div> <div class="theme-row"> <label class="mini-field" data-tooltip={t("web_tt_ctx_window")}> <span>{t("label_ctx_window")}</span> <MiniSelect bind:value={ctxLabel} options={app.meta?.contextWindowOptions ?? []} tip={t("web_tt_ctx_window")} onchange={onCtxChange} /> </label> </div> <!-- Whole-run generation timeout β€” every chat tab's Generation Settings carries one. Deep Research renders its own inside DrControls below, so only General/RAG/Vision get it here. --> {#if !isDr} <div class="theme-row"> <label class="mini-field" data-tooltip={t("web_tt_run_timeout")}> <span>{t("web_timeout")}</span> <PresetSelect bind:value={runTimeout} options={RUN_TIMEOUT_OPTIONS} autoLabel={t("web_no_limit")} tip={t("web_tt_run_timeout")} onchange={onRunTimeoutChange} /> </label> </div> {/if} {#if isVision} <VisionControls {modelLabel} {providerLabel} bind:mmprojLabel projectorOnly /> {/if} {#if isData} <DataControls bind:dataFiles bind:analysisType bind:maxSteps bind:workerSteps bind:execTimeout autoMaxSteps={auto.dataSteps} autoWorkerSteps={auto.workerSteps} autoExecTimeout={auto.execTimeout} notify={notifyFlash} onSteps={onDataSteps} settingsOnly /> {/if} {#if (tab === "general" || isRag) && agentic} <!-- Agentic-mode step budgets β€” only visible while agentic is on, so direct mode stays clean (see AgentControls.svelte). --> <!-- The per-step execution timeout only bites on the CodeAgent path, so show it only while tool calling is OFF (the tool-calling chip above) β€” an inert field on ToolCallingAgent would be clutter. The saved value still persists either way. --> <AgentControls bind:maxSteps bind:searcherSteps bind:execTimeout autoMaxSteps={auto.maxSteps} autoSearcherSteps={auto.searcherSteps} autoExecTimeout={auto.execTimeout} showSearcher={isRag} showExecTimeout={(tab === "general" || isRag) && !toolCalling} onSteps={onSteps} /> {/if} {#if isDr} <DrControls bind:managerSteps bind:searchSteps bind:drTimeout bind:execTimeout autoManagerSteps={auto.drManagerSteps} autoSearchSteps={auto.drSearchSteps} autoExecTimeout={auto.execTimeout} showExecTimeout={!toolCalling} onBudget={onDrBudget} /> {/if} </div> </details> <div class="tool-row"> <button class="btn" onclick={clearChat} disabled={!history.length && !pendingMsg && !imagePath && !dataFiles.length} data-tooltip={t("web_tt_clear_chat")} > {t("btn_clear")} </button> <button class="btn" onclick={copyAllResults} disabled={!history.length} data-tooltip={t("web_tt_copy_all")} > {t("btn_copy_all")} </button> <div class="save-group"> <button class="tool-btn" onclick={doSaveReport} disabled={!app.exportText} data-tooltip={t("info_save_report")} > {t("web_save_report")} </button> {#if saveMsg} <div class="save-notice" class:err={saveMsgErr}>{saveMsg}</div> {/if} </div> <button class="tool-btn" onclick={doOpenReports} data-tooltip={t("info_open_reports")}> {t("web_reports_open")} </button> {#if flash} <span class="tool-flash" class:err={flashErr}>{flash}</span> {/if} </div> </div> </div> {/if} </div>
<script>
import { onDestroy } from "svelte";
import {
app,
getGenSettingsOpen,
setGenSettingsOpen,
getChatCollapsed,
setChatCollapsed,
getHistory,
setHistory,
getRunLog,
setRunLog,
setBusy,
PICKER_SOURCE,
requestModelDownloadConfirm,
trackModelDownload,
t,
} from "../lib/stores.svelte.js";
import { fetchDiskSpace, fetchModelCheck, fetchModelNotice, modelDownloadStatus, openChatSocket, openReports, resetAgent, saveReport, saveSetting, startModelDownload } from "../lib/api.js";
import { buildBasePayload, buildTabPayload } from "../lib/chatTabs.js";
import { RUN_TIMEOUT_OPTIONS } from "../lib/chatPresets.js";
import "./chat/ChatPane.css";
import PresetSelect from "./chat/PresetSelect.svelte";
import MessageList from "./chat/MessageList.svelte";
import Composer from "./chat/Composer.svelte";
import RagControls from "./chat/RagControls.svelte";
import DrControls from "./chat/DrControls.svelte";
import VisionControls from "./chat/VisionControls.svelte";
import DataControls from "./chat/DataControls.svelte";
import { ANALYSIS_PROMPTS } from "../lib/chatTabs.js";
import { scaledMaxSteps } from "../lib/autoDefaults.js";
import AgentControls from "./chat/AgentControls.svelte";
import MiniSelect from "./chat/MiniSelect.svelte";
import { bindClearShortcut, DEFAULT_CLEAR_CONFIRM_MIN } from "../lib/shortcuts.js";
/** 'general' | 'rag' | 'deep_research' | 'vision'. The pane is keyed by tab
* in App.svelte, so each tab gets its own instance and its own history. */
let { tab, modelLabel, providerLabel } = $props();
// Keyed per tab, so these never change within an instance; derived keeps
// the build warning-free and makes the intent explicit.
const isRag = $derived(tab === "rag");
const isDr = $derived(tab === "deep_research");
const isVision = $derived(tab === "vision");
const isData = $derived(tab === "data");
// Report folder key (model_registry.REPORT_DIRS) for this pane's tab β€”
// each chat tab's "Open Reports Folder" button opens ITS OWN folder.
const reportTab = $derived(
{ general: "gen", rag: "rag", deep_research: "dr", vision: "vis", data: "data" }[tab] || tab || ""
);
/** The concrete values this tab's "auto" controls resolve to β€” the
* backend's base defaults (/api/meta autoDefaults) scaled to the CURRENT
* picker model, so an empty field's placeholder shows the real number the
* run will use instead of the opaque word "auto". Derived from the live
* modelLabel so a mid-session model switch updates the placeholders too.
* execTimeout: smolagents' 30s CodeAgent executor default (Data: 120s). */
const auto = $derived.by(() => {
const d = app.meta?.autoDefaults ?? {};
const sb = d.stepBudgets ?? {};
return {
maxSteps: scaledMaxSteps(modelLabel, sb.general ?? 8),
searcherSteps: scaledMaxSteps(modelLabel, sb.rag_searcher ?? 5),
workerSteps: scaledMaxSteps(modelLabel, sb.data_worker ?? 10),
dataSteps: scaledMaxSteps(modelLabel, sb.data ?? 20),
drManagerSteps: scaledMaxSteps(modelLabel, sb.deep_research ?? 12),
drSearchSteps: scaledMaxSteps(modelLabel, sb.deep_research_search ?? 4),
execTimeout: isData ? (d.execTimeout?.data ?? 120) : (d.execTimeout?.general ?? 30),
};
});
/** Conversation history lives in the shared store (keyed by tab) so it
* survives tab switches β€” the pane itself is keyed and recreated per tab. */
let history = $derived(getHistory(tab));
/** Real progress lines streamed from the backend run (llama-server
* launch, model load, agent build, …) β€” shown live inside the status card
* while the run is in flight. Store-backed so a tab switch mid-run keeps
* them. */
const runLog = $derived(getRunLog(tab));
/** Optimistic echo of the user's message until the first server update. */
let pendingMsg = $state("");
/** Raw model tokens streamed LIVE from the run via `live` WS events
* (backend.live_stream bus drained by _run_stream). While non-empty the
* answer bubble shows this growing text INSTEAD of the status card β€” the
* model is visibly "speaking". Cleared on update/final/stop. */
let liveText = $state("");
let input = $state("");
let agentic = $state(true);
let memory = $state(true);
let toolCalling = $state(true);
// RAG-only retrieval-topic filters (bound into RagControls). Multi-
// select: `themes` / `subthemes` are arrays of selected names (empty =
// all), and `ragFiles` is the array of selected KB source filenames.
let themes = $state([]);
let subthemes = $state([]);
let ragFiles = $state([]);
// General/RAG agentic-mode step budgets (bound into AgentControls, shown
// only while agentic mode is on). null = AUTO: the backend applies its
// model-scaled default (full budget on small models, a fail-fast cap on