Spaces:
Paused

assistant / ui /web /src /components /SettingsTab.svelte
localailb's picture
Deploy full LocalAiLab application (Backend + Svelte UI + Agents)
dab4ea2 verified
Raw History Blame Contribute Delete
45 kB
<script> import { onDestroy } from "svelte"; import { app, refreshMetaAndSyncPickers, t, trackModelDownload } from "../lib/stores.svelte.js"; import MiniSelect from "./chat/MiniSelect.svelte"; import LlamaCppInstallDialog from "./LlamaCppInstallDialog.svelte"; import LlamaServerInstallDialog from "./LlamaServerInstallDialog.svelte"; import WhisperServerInstallDialog from "./WhisperServerInstallDialog.svelte"; import PyTorchInstallDialog from "./PyTorchInstallDialog.svelte"; import DownloadConfirmDialog from "./DownloadConfirmDialog.svelte"; import { clearReports, deleteModel, deleteReport, downloadStatus, fetchModelCheck, fetchSettings, llmCppInstall, llamaServerInstall, whisperServerInstall, pytorchInstall, openReports, refreshReports, saveSetting, saveSettings, startDownload, startModelDownload, } from "../lib/api.js"; let s = $state(null); let days = $state(30); let reportFiles = $state([]); let selectedReport = $state(""); let flash = $state(""); let flashErr = $state(false); let dl = $state({ running: false, log: "", component: "", progress: null, label: "", dlMb: "", totalMb: "" }); let timer = null; // ── Model Management State ────────────────────────────────────────── // Model type filter: user picks LLM / Vision / STT / Embedding first, // then only providers of that type appear in the provider dropdown. let modelTypeFilter = $state("stt"); const MODEL_TYPE_OPTIONS = $derived([ { value: "llm", label: t("tab_general") }, { value: "vlm", label: t("tab_vision") }, { value: "stt", label: t("tab_stt") }, { value: "embed", label: t("tab_kb") }, ]); // Provider list filtered to the selected model type. const MODEL_PROVIDER_OPTIONS = $derived.by(() => { if (!app.meta) return []; const tf = modelTypeFilter; const list = []; if (tf === "llm") { for (const p of (app.meta.providers || [])) list.push({ value: p.label, label: p.label, type: "llm" }); } else if (tf === "vlm") { for (const p of (app.meta.vlmProviders || [])) list.push({ value: p.label, label: p.label, type: "vlm" }); } else if (tf === "stt") { for (const p of (app.meta.sttProviders || [])) list.push({ value: p.label, label: p.label, type: "stt" }); } else if (tf === "embed") { for (const p of (app.meta.embedProviders || [])) list.push({ value: p.label, label: p.label, type: "embed" }); } return list; }); let selectedModelProvider = $state(""); let modelCheckCache = $state({}); // Auto-select first provider when type filter or provider list changes. let _prevType = ""; $effect(() => { const opts = MODEL_PROVIDER_OPTIONS; const tf = modelTypeFilter; if (tf !== _prevType || !selectedModelProvider || !opts.some((o) => o.value === selectedModelProvider)) { selectedModelProvider = opts[0]?.value || ""; _prevType = tf; } }); const currentProviderObj = $derived( MODEL_PROVIDER_OPTIONS.find((p) => p.value === selectedModelProvider) || MODEL_PROVIDER_OPTIONS[0] || { value: "", label: "", type: "llm" } ); // Fetch the list of models for the currently selected provider. // app.meta.models / vlmModels / sttModels / embedModels are all keyed // by provider label (the same string the chat tabs store as savedProvider). const currentProvModelsList = $derived.by(() => { if (!app.meta) return []; const label = currentProviderObj.value; if (!label) return []; const type = currentProviderObj.type; if (type === "vlm") return app.meta.vlmModels?.[label] || []; if (type === "stt") return app.meta.sttModels?.[label] || []; if (type === "embed") return app.meta.embedModels?.[label] || []; return app.meta.models?.[label] || []; }); // Fetch model check (download status / size) for every model of the // currently selected provider. The backend /api/model-check resolves // the provider label back to its sentinel via the same provider_map the // chat tabs use. $effect(() => { const p = currentProviderObj; const models = currentProvModelsList; if (p?.value && models.length) { for (const m of models) { const mLabel = typeof m === "string" ? m : (m.label || m.id); const cacheKey = `${p.value}::${mLabel}::${p.type}`; if (!modelCheckCache[cacheKey]) { fetchModelCheck(p.value, mLabel, p.type, app.lang).then((res) => { if (res) { modelCheckCache = { ...modelCheckCache, [cacheKey]: res }; } }).catch(() => {}); } } } }); async function handleDownloadModelItem(m) { const p = currentProviderObj; const mLabel = typeof m === "string" ? m : (m.label || m.id); const cacheKey = `${p.value}::${mLabel}::${p.type}`; const check = modelCheckCache[cacheKey]; const modelId = check?.model_id || (typeof m === "object" ? m.id : mLabel); try { await startModelDownload(modelId, mLabel); trackModelDownload(modelId, mLabel); flash = t("web_download_started"); flashErr = false; } catch (err) { flash = err.message || "Failed to start download"; flashErr = true; } } async function handleDeleteModelItem(m) { const p = currentProviderObj; const mLabel = typeof m === "string" ? m : (m.label || m.id); const cacheKey = `${p.value}::${mLabel}::${p.type}`; const check = modelCheckCache[cacheKey]; const modelId = check?.model_id || (typeof m === "object" ? m.id : mLabel); if (!confirm(t("confirm_delete_model") || "Are you sure you want to delete this model from disk?")) { return; } try { await deleteModel(modelId); flash = t("status_model_deleted"); flashErr = false; // Re-check model status β€” must use immutable update for Svelte reactivity fetchModelCheck(p.value, mLabel, p.type, app.lang).then((res) => { if (res) { modelCheckCache = { ...modelCheckCache, [cacheKey]: res }; } }); refreshMetaAndSyncPickers().catch(() => {}); } catch (err) { flash = err.message || "Failed to delete model"; flashErr = true; } } // After a model download completes, re-fetch settings (to reflect the auto-selected // GGUF model path) and re-fetch the model-check for every model in the current provider // list so the table row flips from "Not Downloaded" to "Downloaded" immediately. let _lastDlDone = false; $effect(() => { const done = app.modelDl.done; if (done && !_lastDlDone) { load().then(() => { autoSelectFolderModels(); }).catch(() => {}); const p = currentProviderObj; const models = currentProvModelsList; if (p?.value && models.length) { for (const m of models) { const mLabel = typeof m === "string" ? m : (m.label || m.id); const cacheKey = `${p.value}::${mLabel}::${p.type}`; fetchModelCheck(p.value, mLabel, p.type, app.lang).then((res) => { if (res) { modelCheckCache = { ...modelCheckCache, [cacheKey]: res }; } }).catch(() => {}); } } } _lastDlDone = !!done; }); /** llama-cpp-python install popup β€” open while the detection report * dialog is visible (the user picks which build to install). */ let llmCppPopup = $state(false); /** llama-server download popup β€” open while the detection report dialog * is visible (the user picks which build to download). */ let llamaServerPopup = $state(false); /** whisper-server download popup β€” open while the detection report dialog * is visible (the user picks which build to download). */ let whisperServerPopup = $state(false); /** PyTorch install popup β€” open while the detection report dialog is * visible (the user picks which build to install). */ let pytorchPopup = $state(false); /** Direct-download confirmation popup β€” shown before poppler/playwright * downloads that don't have a multi-choice install dialog. */ let dlConfirmPopup = $state(false); let dlConfirmComponent = $state(""); /** Activation-confirmation popup (llama-server / GGUF model path saved * via Enter or clicking outside the field) β€” a toast that pops over the * tab and auto-hides after a few seconds. */ let activation = $state(""); let activationTimer = null; /** Inline hint shown under the GGUF folder field after a successful save * ("model list refreshed β€” new GGUF models are selectable now"), auto- * cleared after a few seconds. */ let ggufHint = $state(""); let ggufHintTimer = null; /** The KV-cache data-type MiniSelect options ('' = Auto β€” llama.cpp * default, no flag): the persisted label is the value. */ const kvCacheOptions = $derived([ { value: "", label: t("web_accel_auto") }, { value: "f16", label: "f16" }, { value: "q8_0", label: "q8_0" }, { value: "q4_0", label: "q4_0" }, { value: "bf16", label: "bf16" }, ]); let kvCache = $state(""); $effect(() => { const saved = s?.fields?.llama_kv_cache_quant; if (saved !== undefined) kvCache = saved || ""; }); /** Persist a KV-cache data-type pick ('' = Auto β†’ persisted ""). */ function onKvCacheChange() { saveSetting("llama_kv_cache_quant", kvCache).catch(() => {}); } /** The torch.compile-mode MiniSelect options ('' = default mode β€” the * behaviour before the toggle existed). */ const compileModeOptions = $derived([ { value: "", label: t("web_compile_mode_default") }, { value: "reduce-overhead", label: "reduce-overhead" }, { value: "max-autotune", label: "max-autotune" }, { value: "max-autotune-no-cudagraphs", label: "max-autotune-no-cudagraphs" }, ]); let compileMode = $state(""); $effect(() => { const saved = s?.fields?.torch_compile_mode; if (saved !== undefined) compileMode = saved || ""; }); /** Persist the chosen torch.compile mode ('' = default mode). */ function onCompileModeChange() { saveSetting("torch_compile_mode", compileMode).catch(() => {}); } // Provider-grouped layout: each provider is its own block holding the // per-tab settings fields set (label key + kind + placeholder). One // provider per row, with every provider's block laid out side by side. // Each field: [key, label key, input kind, placeholder, tooltip key] const PROVIDERS = [ { titleKey: "label_provider_hf", fields: [ ["hf_token", "label_hf_token", "password", "hf_...", "web_tt_hf_token"], // The HF API model is chosen ONLY in each tab's header model picker // (the curated hf_api_models.csv list) β€” the Settings 'πŸ€— HF Model // ID' field was removed so no custom/free-text model id is used. ["hf_provider", "label_hf_provider", "text", "", "web_tt_hf_provider"], ], }, { titleKey: "label_provider_litellm", fields: [ ["litellm_model_id", "label_litellm_model_id", "text", "anthropic/claude-4-sonnet-20250514", "web_tt_litellm_model_id"], ["litellm_api_key", "label_litellm_api_key", "password", "sk-...", "web_tt_litellm_api_key"], ["litellm_api_base", "label_litellm_api_base", "text", "", "web_tt_litellm_api_base"], ], }, { titleKey: "label_provider_llama", fields: [ ["llama_server_path", "label_llama_server_path", "text", "D:\\llama.cpp\\llama-server.exe", "web_tt_llama_path"], ["llama_server_args", "label_llama_server_args", "text", "", "web_tt_llama_args"], ], }, { titleKey: "label_provider_whisper", fields: [ ["whisper_server_path", "label_whisper_server_path", "text", "D:\\whisper.cpp\\whisper-server.exe", "web_tt_whisper_path"], ["whisper_server_args", "label_whisper_server_args", "text", "", "web_tt_whisper_args"], ], }, { titleKey: "label_provider_gguf", fields: [ ["gguf_dir", "label_gguf_dir", "text", "", "web_tt_gguf_dir"], ], }, ]; async function load() { try { s = await fetchSettings(app.lang); reportFiles = s.reportFiles || []; if (!selectedReport && reportFiles.length) selectedReport = reportFiles[0]; } catch (err) { flash = err.message; flashErr = true; } } /** Copy all hardware/env/component status to clipboard. */ async function copyAllStatus() { if (!s) return; const parts = []; if (s.hw) parts.push(`${t("label_hw_status")}:\n${s.hw}`); if (s.cuda) parts.push(`${t("label_cuda_status")}:\n${s.cuda}`); if (s.env) parts.push(`${t("label_env_status")}:\n${s.env}`); if (s.components) parts.push(`${t("acc_tools_downloader")}:\n${s.components}`); if (!parts.length) return; try { await navigator.clipboard.writeText(parts.join("\n\n")); flash = t("web_copied"); flashErr = false; } catch { flash = t("web_copy_fail"); flashErr = true; } } // Load on mount, and reload the bilingual status lines on a language switch. let loadedLang = ""; $effect(() => { if (app.lang !== loadedLang) { loadedLang = app.lang; load(); } }); // Fields whose saved value changes the per-tab provider/model dropdowns or // the server backends: after saving one of these the backend applies it // immediately (module globals + persist), so refresh /api/meta + the // picker choices to make the new llama-server path / GGUF model folder // usable RIGHT NOW β€” no app restart. const META_SYNC_KEYS = new Set([ "llama_server_path", "llama_server_args", "gguf_dir", "whisper_server_path", "whisper_server_args", ]); // Tabs whose provider is a GGUF-backed one (the two llama providers) β€” // after a GGUF-folder change these get their model AUTO-SWITCHED to the // first model discovered in the new folder (unless the user already // picked a folder model), so the models from the new path are usable // immediately without restarting or re-picking by hand. const GGUF_PROVIDER_MARKERS = ["llama.cpp server", "llama-cpp-python (in-process)"]; function autoSelectFolderModels() { const next = { ...app.pickers }; const changed = []; for (const tab of Object.keys(next)) { const cur = next[tab]; if (!cur || !cur.provider || !cur.choices?.length) continue; const isGguf = GGUF_PROVIDER_MARKERS.some((m) => cur.provider.includes(m)); if (!isGguf) continue; // Folder-discovered models carry the 'llama.cpp |' mode tag in their // label; presets carry 'HF Hub'. Keep the user's pick when it's // already a folder model. if (cur.choices.includes(cur.model) && cur.model.includes("llama.cpp |")) continue; const folderModel = cur.choices.find((c) => c.includes("llama.cpp |")) ?? cur.choices[0]; if (!folderModel || folderModel === cur.model) continue; next[tab] = { ...cur, model: folderModel }; changed.push([tab, folderModel]); } if (changed.length) { app.pickers = next; // Persist each switch exactly like picking it in the header, so the // auto-selected model survives a restart. for (const [tab, model] of changed) { saveSettings({ tab, model_label: model }).catch(() => { /* non-fatal */ }); } } } /** The llama-server timeout presets (label + seconds) as MiniSelect * options β€” value is the seconds string, label the human preset. The * saved value may sit OUTSIDE the presets (a previously typed number * from the old number input); MiniSelect shows it as-is, exactly like * the former per-tab dropdown. */ const llamaTimeoutOptions = $derived( (s?.llama_server_timeout_options || []).map((o) => ({ value: String(o.seconds), label: o.label, })) ); let llamaTimeout = $state(""); // Sync the dropdown from the loaded settings (a pick writes llamaTimeout // and saves; this effect never reads llamaTimeout back, so a user choice // is never snapped back to the persisted value). $effect(() => { const saved = s?.fields?.llama_server_timeout; if (saved) llamaTimeout = String(saved); }); /** Persist the chosen llama-server request timeout (the GLOBAL setting β€” * one shared llama-server subprocess). The server hot-updates the live * model's timeout on save. */ function onLlamaTimeoutChange() { const seconds = parseInt(llamaTimeout, 10); if (Number.isFinite(seconds) && seconds > 0) { saveSetting("llama_server_timeout", seconds).catch(() => {}); } } /** Pop the activation-confirmation toast (a llama-server / GGUF model * path was saved and is now the ACTIVE backend) β€” auto-hides after a * few seconds so it never blocks the tab. */ function showActivation(msg) { activation = msg; if (activationTimer) clearTimeout(activationTimer); activationTimer = setTimeout(() => { activation = ""; }, 5000); } function setField(key) { return async (e) => { const value = e.currentTarget.value; try { await saveSetting(key, value); if (s) s.fields[key] = value; // keep the rendered field in sync if (META_SYNC_KEYS.has(key)) { await refreshMetaAndSyncPickers(); if (key === "gguf_dir") { // GGUF-folder change: auto-select the new folder's models on // every GGUF-backed tab and show the inline refresh hint. autoSelectFolderModels(); ggufHint = t("web_gguf_refreshed"); if (ggufHintTimer) clearTimeout(ggufHintTimer); ggufHintTimer = setTimeout(() => { ggufHint = ""; }, 8000); flash = ""; // The folder is now the ACTIVE GGUF model source β€” confirm it // with a popup showing the exact path (only when a path was // actually entered; clearing the field just saves the empty // value). if (value.trim()) showActivation(t("web_path_gguf_activated").replace("{path}", value.trim())); } else if (key === "llama_server_path") { // The entered binary is now the ACTIVE llama-server backend β€” // pop up a confirmation showing the exact path (same Enter / // click-outside commit). if (value.trim()) showActivation(t("web_path_llama_activated").replace("{path}", value.trim())); else { flash = t("web_settings_applied"); flashErr = false; } } else if (key === "whisper_server_path") { // The entered binary is now the ACTIVE whisper-server backend // (STT) β€” pop up a confirmation showing the exact path, same // Enter / click-outside commit as the llama-server path. if (value.trim()) showActivation(t("web_path_whisper_activated").replace("{path}", value.trim())); else { flash = t("web_settings_applied"); flashErr = false; } } else { flash = t("web_settings_applied"); flashErr = false; } } } catch { /* non-fatal */ } }; } async function toggleFlash(key) { try { await saveSetting(key, s.fields[key]); } catch { /* non-fatal */ } } async function doClearReports() { try { const r = await clearReports(days); const msg = r.deleted ? t("web_reports_deleted").replace("{n}", r.deleted) : t("web_reports_nothing"); flash = msg; flashErr = false; reportFiles = (await refreshReports()).files || []; selectedReport = reportFiles[0] || ""; } catch (err) { flash = err.message; flashErr = true; } } async function doOpenReports() { try { const r = await openReports(); 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; } } async function doRefreshReports() { try { reportFiles = (await refreshReports()).files || []; selectedReport = reportFiles[0] || ""; } catch (err) { flash = err.message; flashErr = true; } } async function doDeleteReport() { if (!selectedReport) return; try { const r = await deleteReport(selectedReport); flash = r.ok ? t("web_deleted") : t("web_delete_failed"); flashErr = !r.ok; reportFiles = r.files || []; selectedReport = reportFiles[0] || ""; } catch (err) { flash = err.message; flashErr = true; } } async function doDownload(component) { if (component === "llama_server") { // llama-server ships multiple builds (CPU / NVIDIA CUDA 12.4 / CUDA // 13.3) β€” open the detection popup so the USER chooses which build to // download, never a silent auto-pick (the old behaviour). llamaServerPopup = true; return; } if (component === "whisper_server") { // whisper-server ships multiple builds (CPU / NVIDIA cuBLAS 11.8 / // cuBLAS 12.4) β€” open the detection popup so the USER chooses which // build to download, never a silent CPU-only auto-pick. whisperServerPopup = true; return; } if (component === "llama_cpp") { // llama-cpp-python has multiple builds (CPU / NVIDIA CUDA / Vulkan) β€” // open the detection popup so the USER chooses, never silently install // the CPU wheel (the old behaviour). llmCppPopup = true; return; } if (component === "fix_env") { // PyTorch has multiple builds (CPU / NVIDIA CUDA / Intel XPU / // AMD ROCm) β€” open the detection popup so the USER chooses which build // to install, never a silent auto-pick (the old behaviour). pytorchPopup = true; return; } // Direct downloads (poppler, playwright) β€” show confirmation first dlConfirmComponent = component; dlConfirmPopup = true; } /** Kick off a confirmed direct download after the user clicks Confirm * in the DownloadConfirmDialog. */ async function doConfirmDownload(component) { dlConfirmPopup = false; try { await startDownload(component); dl.component = component; flash = t("web_download_started"); flashErr = false; poll(); } catch (err) { flash = err.message; flashErr = true; } } /** Kick off the user-chosen llama-cpp-python build from the popup β€” same * shared download job/poll as the other components. */ async function doLlamaCppInstall(choice) { try { await llmCppInstall(choice); dl.component = "llm_cpp_install"; flash = t("web_download_started"); flashErr = false; poll(); } catch (err) { flash = err.message; flashErr = true; } } /** Kick off the user-chosen llama-server build from the popup β€” same * shared download job/poll as the other components. */ async function doLlamaServerInstall(choice) { try { await llamaServerInstall(choice); dl.component = "llama_server_install"; flash = t("web_download_started"); flashErr = false; poll(); } catch (err) { flash = err.message; flashErr = true; } } /** Kick off the user-chosen PyTorch build from the popup β€” same shared * download job/poll as the other components. */ async function doPytorchInstall(choice) { try { await pytorchInstall(choice); dl.component = "fix_env"; flash = t("web_download_started"); flashErr = false; poll(); } catch (err) { flash = err.message; flashErr = true; } } /** Kick off the user-chosen whisper-server build from the popup β€” same * shared download job/poll as the other components. */ async function doWhisperServerInstall(choice) { try { await whisperServerInstall(choice); dl.component = "whisper_server_install"; flash = t("web_download_started"); flashErr = false; poll(); } catch (err) { flash = err.message; flashErr = true; } } async function poll() { if (timer) return; dl.running = true; timer = setInterval(async () => { try { const r = await downloadStatus(); dl.log = r.log || ""; dl.component = r.component || dl.component; dl.progress = r.progress ?? null; dl.label = r.label || ""; dl.dlMb = r.dl_mb || ""; dl.totalMb = r.total_mb || ""; if (!r.running) { dl.running = false; dl.progress = null; dl.label = ""; dl.dlMb = ""; dl.totalMb = ""; if (timer) { clearInterval(timer); timer = null; } flash = t("web_download_done"); s = await fetchSettings(app.lang); } } catch { /* transient */ } }, 1000); } onDestroy(() => { if (timer) clearInterval(timer); if (ggufHintTimer) clearTimeout(ggufHintTimer); if (activationTimer) clearTimeout(activationTimer); }); // [component, label key, tooltip key] const components = [ ["llama_server", "btn_dl_llama_server", "info_dl_llama_server"], ["whisper_server", "btn_dl_whisper_server", "info_dl_whisper_server"], ["poppler", "btn_dl_poppler", "info_dl_poppler"], ["playwright", "btn_dl_playwright", "info_dl_playwright"], ["llama_cpp", "btn_install_llama_cpp", "info_install_llama_cpp"], ]; </script> {#if s} <div class="tab-scroll"> <div class="card"> <div class="card-title">{t("label_hw_status")}</div> <button class="btn btn-sm" onclick={copyAllStatus} disabled={!s} data-tooltip={t("web_tt_copy_all")}>{t("btn_copy_all")}</button> <pre class="console">{s.hw}</pre> <div class="card-subtitle">{t("label_cuda_status")}</div> <pre class="console">{s.cuda}</pre> <div class="tool-row wrap"> <button class="btn btn-sm" onclick={() => doDownload("fix_env")} disabled={dl.running} data-tooltip={t("info_install_cuda")}> {t("btn_install_cuda")} </button> </div> {#if dl.running && dl.component === "fix_env"} <div class="status-line">{t("web_download_running")}</div> {/if} {#if dl.component === "fix_env" && dl.log} <pre class="console log">{dl.log}</pre> {/if} </div> <!-- App environment & packages β€” the 'does the app recognize its packages?' check (runtime mode: frozen standalone vs .venv, the interpreter, and a live import check of every core package). --> <div class="card"> <div class="card-title">{t("label_env_status")}</div> <pre class="console">{s.env}</pre> </div> <div class="card"> <div class="card-title">{t("acc_tools_downloader")}</div> <pre class="console">{s.components}</pre> <div class="tool-row wrap"> {#each components as [comp, key, tip] (comp)} <button class="btn btn-sm" onclick={() => doDownload(comp)} disabled={dl.running} data-tooltip={t(tip)}> {t(key)} </button> {/each} </div> {#if dl.running && dl.component !== "fix_env"} <div class="status-line">{t("web_download_running")}</div> {#if dl.progress !== null} <div class="dl-progress"> <div class="dl-progress-header"> <span class="dl-progress-label">{dl.label || t("web_download_running")}</span> <span class="dl-progress-pct">{dl.progress}%</span> </div> <div class="dl-progress-track"> <div class="dl-progress-bar" style="width: {dl.progress}%"></div> </div> {#if dl.dlMb} <div class="dl-progress-size">{dl.dlMb} / {dl.totalMb} MB</div> {/if} </div> {/if} {/if} {#if dl.component !== "fix_env" && dl.log} <pre class="console log">{dl.log}</pre> {/if} </div> <div class="card"> <div class="card-title">{t("acc_settings_global")}</div> <div class="provider-grid"> {#each PROVIDERS as prov, pi (prov.titleKey)} <div class="provider-block"> <div class="provider-title">{t(prov.titleKey)}</div> <div class="provider-fields"> {#each prov.fields as [key, labelKey, type, placeholder, tip] (key)} <label class="field" data-tooltip={tip ? t(tip) : undefined}> <span class="field-label">{t(labelKey)}</span> <input type={type} value={s.fields[key] ?? ""} placeholder={placeholder} data-tooltip={tip ? t(tip) : undefined} onchange={setField(key)} onkeydown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} /> </label> {/each} {#if prov.titleKey === "label_provider_gguf" && ggufHint} <div class="status-line">{ggufHint}</div> {/if} {#if prov.titleKey === "label_provider_llama"} <label class="field" data-tooltip={t("info_llama_timeout")}> <span class="field-label">{t("label_llama_server_timeout")}</span> <MiniSelect bind:value={llamaTimeout} options={llamaTimeoutOptions} tip={t("info_llama_timeout")} onchange={onLlamaTimeoutChange} /> </label> {/if} </div> </div> {/each} </div> </div> <!-- Model Management β€” Provider dropdown + Model table with status and download/remove buttons --> <div class="card"> <div class="card-title">{t("acc_model_management")}</div> <div class="card-subtitle">{t("label_model_mgmt_desc")}</div> <!-- Model type + Provider side by side --> <div class="tool-row" style="gap: 14px; margin-bottom: 14px;"> <label class="field" data-tooltip={t("info_model_type")}> <span class="field-label">{t("label_model_type")}</span> <MiniSelect bind:value={modelTypeFilter} options={MODEL_TYPE_OPTIONS} tip={t("info_model_type")} /> </label> <label class="field" data-tooltip={t("info_provider")}> <span class="field-label">{t("label_provider_select")}</span> <MiniSelect bind:value={selectedModelProvider} options={MODEL_PROVIDER_OPTIONS} tip={t("info_provider")} /> </label> </div> <!-- Models Table --> <div class="table-wrap"> <table class="model-table"> <thead> <tr> <th>{t("model_table_col_name")}</th> <th>{t("model_table_col_size")}</th> <th>{t("model_table_col_status")}</th> <th>{t("model_table_col_action")}</th> </tr> </thead> <tbody> {#if currentProvModelsList.length === 0} <tr data-tooltip={t("label_model_details")}> <td colspan="4" class="empty-hint" style="text-align: center;"> {t("web_loading", "No models available for this provider")} </td> </tr> {:else} {#each currentProvModelsList as m (typeof m === "string" ? m : (m.id || m.label))} {@const mLabel = typeof m === "string" ? m : (m.label || m.id)} {@const cacheKey = `${currentProviderObj.value}::${mLabel}::${currentProviderObj.type}`} {@const check = modelCheckCache[cacheKey]} {@const isDownloading = app.modelDl.running && (app.modelDl.modelLabel === mLabel || app.modelDl.modelId === check?.model_id)} <tr data-tooltip={t("label_model_details")}> <td> <div class="model-name-cell"> <span class="model-name-title">{mLabel}</span> {#if check?.model_id && check.model_id !== mLabel} <span class="model-name-id">{check.model_id}</span> {/if} </div> </td> <td> {#if check?.size_gb} {check.size_gb} GB {:else if typeof m === "object" && m.size_gb} {m.size_gb} GB {:else} β€” {/if} </td> <td> {#if isDownloading} <span class="model-status-chip download"> ⏳ {t("web_model_downloading_btn")} ({app.modelDl.progress ?? 0}%) </span> {:else if check?.cached} <span class="model-status-chip ready"> {t("status_model_downloaded")} </span> {:else if check?.needs_download} <span class="model-status-chip download"> {t("status_model_not_downloaded")} </span> {:else} <span class="model-status-chip cloud"> {t("status_model_online")} </span> {/if} </td> <td> <div class="action-btn-group"> {#if check?.needs_download} <button type="button" class="btn btn-primary btn-sm" onclick={() => handleDownloadModelItem(m)} disabled={app.modelDl.running} data-tooltip={t("web_tt_download_model")} > {t("btn_download_model")} </button> {:else if check?.cached} <button type="button" class="btn btn-danger btn-sm" onclick={() => handleDeleteModelItem(m)} disabled={app.modelDl.running} data-tooltip={t("web_tt_delete_model")} > {t("btn_delete_model")} </button> <button type="button" class="btn btn-sm" onclick={() => handleDownloadModelItem(m)} disabled={app.modelDl.running} data-tooltip={t("web_tt_download_model")} > πŸ”„ </button> {:else} <span class="text-dim">β€”</span> {/if} </div> </td> </tr> {/each} {/if} </tbody> </table> </div> </div> <div class="card"> <div class="card-title">{t("acc_settings_accel")}</div> <div class="provider-grid"> <div class="provider-block"> <div class="provider-title">{t("label_provider_llama")}</div> <div class="provider-fields"> <label class="field" data-tooltip={t("info_kv_cache_quant")}> <span class="field-label">{t("label_kv_cache_quant")}</span> <MiniSelect bind:value={kvCache} options={kvCacheOptions} tip={t("info_kv_cache_quant")} onchange={onKvCacheChange} /> </label> <label class="field" data-tooltip={t("info_llama_threads")}> <span class="field-label">{t("label_llama_threads")}</span> <input type="number" min="0" value={s.fields.llama_threads || ""} placeholder={t("web_accel_auto")} data-tooltip={t("info_llama_threads")} onchange={setField("llama_threads")} onkeydown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} /> </label> <label class="field" data-tooltip={t("info_llama_tensor_split")}> <span class="field-label">{t("label_llama_tensor_split")}</span> <input type="text" value={s.fields.llama_tensor_split || ""} placeholder="3,1" data-tooltip={t("info_llama_tensor_split")} onchange={setField("llama_tensor_split")} onkeydown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} /> </label> <label class="field" data-tooltip={t("info_llama_draft_model")}> <span class="field-label">{t("label_llama_draft_model")}</span> <input type="text" value={s.fields.llama_draft_model || ""} placeholder="D:\\draft-0.5b.gguf" data-tooltip={t("info_llama_draft_model")} onchange={setField("llama_draft_model")} onkeydown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} /> </label> <label class="field" data-tooltip={t("info_llama_draft_max")}> <span class="field-label">{t("label_llama_draft_max")}</span> <input type="number" min="1" value={s.fields.llama_draft_max || 3} placeholder="3" data-tooltip={t("info_llama_draft_max")} onchange={setField("llama_draft_max")} onkeydown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} /> </label> </div> <div class="chip-row"> <label class="chip" class:on={s.fields.flash_attn_llama} data-tooltip={t("info_flash_attn_llama")}> <input type="checkbox" checked={s.fields.flash_attn_llama} onchange={(e) => { s.fields.flash_attn_llama = e.currentTarget.checked; toggleFlash("flash_attn_llama"); }} /> {t("label_flash_attn_llama")} </label> <label class="chip" class:on={s.fields.llama_mlock} data-tooltip={t("info_llama_mlock")}> <input type="checkbox" checked={s.fields.llama_mlock} onchange={(e) => { s.fields.llama_mlock = e.currentTarget.checked; toggleFlash("llama_mlock"); }} /> {t("label_llama_mlock")} </label> <label class="chip" class:on={s.fields.llama_mmap} data-tooltip={t("info_llama_mmap")}> <input type="checkbox" checked={s.fields.llama_mmap} onchange={(e) => { s.fields.llama_mmap = e.currentTarget.checked; toggleFlash("llama_mmap"); }} /> {t("label_llama_mmap")} </label> </div> </div> <div class="provider-block"> <div class="provider-title">{t("label_provider_pytorch")}</div> <div class="provider-fields"> <label class="field" data-tooltip={t("info_torch_compile_mode")}> <span class="field-label">{t("label_torch_compile_mode")}</span> <MiniSelect bind:value={compileMode} options={compileModeOptions} tip={t("info_torch_compile_mode")} onchange={onCompileModeChange} /> </label> </div> <div class="chip-row"> <label class="chip" class:on={s.fields.flash_attn_pytorch} data-tooltip={t("info_flash_attn_pytorch")}> <input type="checkbox" checked={s.fields.flash_attn_pytorch} onchange={(e) => { s.fields.flash_attn_pytorch = e.currentTarget.checked; toggleFlash("flash_attn_pytorch"); }} /> {t("label_flash_attn_pytorch")} </label> <label class="chip" class:on={s.fields.torch_compile} data-tooltip={t("info_torch_compile")}> <input type="checkbox" checked={s.fields.torch_compile} onchange={(e) => { s.fields.torch_compile = e.currentTarget.checked; toggleFlash("torch_compile"); }} /> {t("label_torch_compile")} </label> <label class="chip" class:on={s.fields.torch_bf16} data-tooltip={t("info_torch_bf16")}> <input type="checkbox" checked={s.fields.torch_bf16} onchange={(e) => { s.fields.torch_bf16 = e.currentTarget.checked; toggleFlash("torch_bf16"); }} /> {t("label_torch_bf16")} </label> </div> </div> </div> </div> <div class="card"> <div class="card-title">{t("label_report_files")}</div> <div class="field-row"> <label class="field" data-tooltip={t("web_tt_days")}> <span class="field-label">{t("label_clear_reports_days")}</span> <input type="number" min="1" bind:value={days} /> </label> <select bind:value={selectedReport} class="field select-wide" data-tooltip={t("web_tt_report_select")}> {#each reportFiles as f (f)} <option value={f}>{f}</option> {/each} </select> </div> <div class="tool-row wrap"> <button class="btn btn-sm" onclick={doClearReports} data-tooltip={t("info_clear_reports")}>{t("btn_clear_reports")}</button> <button class="btn btn-sm" onclick={doOpenReports} data-tooltip={t("info_open_reports")}>{t("btn_open_reports")}</button> <button class="btn btn-sm" onclick={doRefreshReports} data-tooltip={t("info_refresh_reports")}>{t("btn_refresh_reports")}</button> <button class="btn btn-danger btn-sm" onclick={doDeleteReport} data-tooltip={t("info_delete_report")}>{t("btn_delete_report")}</button> </div> <div class="reports-path" data-tooltip={s.reportBaseDir}>πŸ“‚ {s.reportBaseDir}</div> </div> </div> {:else} <div class="status-line">{t("web_loading", "…")}</div> {/if} {#if flash} <div class="tool-flash" class:err={flashErr}>{flash}</div> {/if} {#if activation} <div class="settings-toast" role="status">{activation}</div> {/if} {#if llmCppPopup} <LlamaCppInstallDialog onclose={() => { llmCppPopup = false; }} oninstall={(choice) => doLlamaCppInstall(choice)} /> {/if} {#if llamaServerPopup} <LlamaServerInstallDialog onclose={() => { llamaServerPopup = false; }} oninstall={(choice) => doLlamaServerInstall(choice)} /> {/if} {#if whisperServerPopup} <WhisperServerInstallDialog onclose={() => { whisperServerPopup = false; }} oninstall={(choice) => doWhisperServerInstall(choice)} /> {/if} {#if pytorchPopup} <PyTorchInstallDialog onclose={() => { pytorchPopup = false; }} oninstall={(choice) => doPytorchInstall(choice)} /> {/if} {#if dlConfirmPopup} <DownloadConfirmDialog component={dlConfirmComponent} onclose={() => { dlConfirmPopup = false; }} onconfirm={(comp) => doConfirmDownload(comp)} /> {/if}
<script>
import { onDestroy } from "svelte";
import { app, refreshMetaAndSyncPickers, t, trackModelDownload } from "../lib/stores.svelte.js";
import MiniSelect from "./chat/MiniSelect.svelte";
import LlamaCppInstallDialog from "./LlamaCppInstallDialog.svelte";
import LlamaServerInstallDialog from "./LlamaServerInstallDialog.svelte";
import WhisperServerInstallDialog from "./WhisperServerInstallDialog.svelte";
import PyTorchInstallDialog from "./PyTorchInstallDialog.svelte";
import DownloadConfirmDialog from "./DownloadConfirmDialog.svelte";
import {
clearReports,
deleteModel,
deleteReport,
downloadStatus,
fetchModelCheck,
fetchSettings,
llmCppInstall,
llamaServerInstall,
whisperServerInstall,
pytorchInstall,
openReports,
refreshReports,
saveSetting,
saveSettings,
startDownload,
startModelDownload,
} from "../lib/api.js";
let s = $state(null);
let days = $state(30);
let reportFiles = $state([]);
let selectedReport = $state("");
let flash = $state("");
let flashErr = $state(false);
let dl = $state({ running: false, log: "", component: "", progress: null, label: "", dlMb: "", totalMb: "" });
let timer = null;
// ── Model Management State ──────────────────────────────────────────
// Model type filter: user picks LLM / Vision / STT / Embedding first,
// then only providers of that type appear in the provider dropdown.
let modelTypeFilter = $state("stt");
const MODEL_TYPE_OPTIONS = $derived([
{ value: "llm", label: t("tab_general") },
{ value: "vlm", label: t("tab_vision") },
{ value: "stt", label: t("tab_stt") },
{ value: "embed", label: t("tab_kb") },
]);
// Provider list filtered to the selected model type.
const MODEL_PROVIDER_OPTIONS = $derived.by(() => {
if (!app.meta) return [];
const tf = modelTypeFilter;
const list = [];
if (tf === "llm") {
for (const p of (app.meta.providers || [])) list.push({ value: p.label, label: p.label, type: "llm" });
} else if (tf === "vlm") {
for (const p of (app.meta.vlmProviders || [])) list.push({ value: p.label, label: p.label, type: "vlm" });
} else if (tf === "stt") {
for (const p of (app.meta.sttProviders || [])) list.push({ value: p.label, label: p.label, type: "stt" });
} else if (tf === "embed") {
for (const p of (app.meta.embedProviders || [])) list.push({ value: p.label, label: p.label, type: "embed" });
}
return list;
});
let selectedModelProvider = $state("");
let modelCheckCache = $state({});
// Auto-select first provider when type filter or provider list changes.
let _prevType = "";
$effect(() => {
const opts = MODEL_PROVIDER_OPTIONS;
const tf = modelTypeFilter;
if (tf !== _prevType || !selectedModelProvider || !opts.some((o) => o.value === selectedModelProvider)) {
selectedModelProvider = opts[0]?.value || "";
_prevType = tf;
}
});
const currentProviderObj = $derived(
MODEL_PROVIDER_OPTIONS.find((p) => p.value === selectedModelProvider) ||
MODEL_PROVIDER_OPTIONS[0] ||
{ value: "", label: "", type: "llm" }
);
// Fetch the list of models for the currently selected provider.
// app.meta.models / vlmModels / sttModels / embedModels are all keyed
// by provider label (the same string the chat tabs store as savedProvider).
const currentProvModelsList = $derived.by(() => {
if (!app.meta) return [];
const label = currentProviderObj.value;
if (!label) return [];
const type = currentProviderObj.type;
if (type === "vlm") return app.meta.vlmModels?.[label] || [];
if (type === "stt") return app.meta.sttModels?.[label] || [];
if (type === "embed") return app.meta.embedModels?.[label] || [];
return app.meta.models?.[label] || [];
});
// Fetch model check (download status / size) for every model of the