Spaces:
Paused

assistant / ui /web /src /App.svelte
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
22.2 kB
<script>
import { onMount } from "svelte";
import {
app,
computePickers,
initPickers,
loadMeta,
loadLanguage,
PICKER_SOURCE,
requestModelDownloadConfirm,
setActiveTab,
t,
} from "./lib/stores.svelte.js";
import { fetchMemory, fetchModelCheck, fetchModelNotice, freeVram, restartApp, saveSetting, saveSettings } from "./lib/api.js";
import { CHAT_TABS, isChatTab } from "./lib/chatTabs.js";
import ChatPane from "./components/ChatPane.svelte";
import SttTab from "./components/SttTab.svelte";
import KbTab from "./components/KbTab.svelte";
import SettingsTab from "./components/SettingsTab.svelte";
import AboutTab from "./components/AboutTab.svelte";
import FeedbackTab from "./components/FeedbackTab.svelte";
import DownloadProgressPopup from "./components/DownloadProgressPopup.svelte";
import Tooltip from "./components/Tooltip.svelte";
import FirstRunDialog from "./components/FirstRunDialog.svelte";
import DownloadConfirmDialog from "./components/DownloadConfirmDialog.svelte";
// PICKER_SOURCE now lives in stores.svelte.js β€” shared with SettingsTab's
// after-save meta refresh so the provider/model dropdowns have ONE
// definition (see lib/stores.svelte.js).
let theme = $state("light");
/** Read the persisted collapsed-sidebar preference synchronously so the
* rail renders in the right state from the very first paint (no flash). */
function initSidebar() {
try {
return localStorage.getItem("lal-sidebar") === "1";
} catch {
return false;
}
}
/** True = the sidebar is collapsed to an icon-only rail. */
let sidebarCollapsed = $state(initSidebar());
/** True while the first-run onboarding popup (Settings landing) is open
* β€” shown exactly once on the very first launch, then persisted as seen. */
let firstRunOpen = $state(false);
/** The /api/model-notice text for the active tab's picker (empty = none). */
let modelNotice = $state("");
let vramBusy = $state(false);
/** Transient confirmation after freeing VRAM from the header chip. */
let vramFlash = $state("");
let vramFlashErr = $state(false);
let vramFlashTimer = null;
/** Live RAM/VRAM usage ({ram:{...}, vram:{...}}) for the compact header
* readout next to the Free-VRAM button. */
let mem = $state(null);
/** "12.3/31.9 GB Β· 39%" compact sidebar form β€” 'unknown' when not probeable. */
function memCompact(part) {
if (!part || part.used_gb == null || part.total_gb == null) return t("web_mem_unknown");
const pct = part.pct != null ? ` Β· ${Math.round(part.pct)}%` : "";
return `${part.used_gb}/${part.total_gb} GB${pct}`;
}
/** "34%" CPU readout β€” 'unknown' when not probeable. */
function cpuText(part) {
if (!part || part.pct == null) return t("web_mem_unknown");
return `${Math.round(part.pct)}%`;
}
async function refreshMem() {
try {
mem = (await fetchMemory()).usage || null;
} catch {
/* transient β€” keep the last good snapshot */
}
}
function applyTheme(mode) {
theme = mode;
document.documentElement.classList.toggle("dark", mode === "dark");
try {
localStorage.setItem("lal-theme", mode);
} catch {
/* private mode */
}
}
function toggleTheme() {
applyTheme(theme === "dark" ? "light" : "dark");
}
function toggleSidebar() {
sidebarCollapsed = !sidebarCollapsed;
try {
localStorage.setItem("lal-sidebar", sidebarCollapsed ? "1" : "0");
} catch {
/* private mode */
}
}
/** The provider option list (label/value objects) for a tab. */
function pickerProviders(tab) {
const src = PICKER_SOURCE[tab];
if (!src) return [];
return app.meta?.[src.providers] ?? [];
}
/** The model choices for a tab + provider (STT is flat; others keyed). */
function choicesFor(tab, provider) {
const src = PICKER_SOURCE[tab];
if (!src) return [];
if (src.flatModels) return app.meta?.[src.models] ?? [];
return app.meta?.[src.models]?.[provider] ?? [];
}
async function onProviderChange(e) {
const label = e.currentTarget.value;
const tab = app.activeTab;
const cur = app.pickers[tab];
if (!label || !cur || label === cur.provider) return;
const src = PICKER_SOURCE[tab];
const choices = choicesFor(tab, label);
const firstModel = choices[0] ?? "";
app.pickers = {
...app.pickers,
[tab]: { ...cur, provider: label, model: firstModel, choices },
};
try {
if (tab === "stt") await saveSetting("stt_provider", label);
else if (tab === "kb") {
await saveSetting("embed_provider", label);
if (app.meta) app.meta = { ...app.meta, savedEmbed: { provider: label, model: firstModel } };
}
else await saveSettings({ tab, provider_label: label });
// The provider switch reset the model to the provider's first choice
// β€” persist it too, so /api/meta's savedModel reopens the picker on
// exactly the state the user left (not a stale label from the old
// provider that happens to still be a valid choice).
await saveSettings({ tab, model_label: firstModel });
} catch {
/* non-fatal β€” saved provider is read on next run */
}
if (src && firstModel) {
try {
const chk = await fetchModelCheck(label, firstModel, src.type, app.lang);
if (chk?.needs_download) {
requestModelDownloadConfirm(
{ id: chk.model_id, label: firstModel, size: chk.size_gb },
async () => {},
() => {}
);
}
} catch {}
}
}
/** Free all VRAM right where the model-status chip sits β€” the web port of
* the Settings tab's Free All VRAM button (POST /api/settings/free-vram).
* Shows the bilingual unload confirmation as a transient toast. */
async function doFreeVram() {
if (vramBusy) return;
vramBusy = true;
try {
const r = await freeVram(app.lang);
vramFlash = r.notice || t("web_saved_ok");
vramFlashErr = false;
refreshMem(); // show how much freeing VRAM actually recovered
} catch (err) {
vramFlash = err.message;
vramFlashErr = true;
} finally {
vramBusy = false;
if (vramFlashTimer) clearTimeout(vramFlashTimer);
vramFlashTimer = setTimeout(() => {
vramFlash = "";
}, 5000);
}
}
/** Full app restart (POST /api/restart): the backend resets every loaded
* model / cached agent / managed server and rebuilds the model registry,
* then the SPA re-boots from fresh /api/meta β€” like a cold app start
* without killing the process (see the endpoint's docstring). Shows the
* bilingual confirmation as the same centered toast as Free-All-VRAM. */
let restartBusy = $state(false);
let restartFlash = $state("");
let restartFlashErr = $state(false);
let restartFlashTimer = null;
async function doRestartApp() {
if (restartBusy) return;
restartBusy = true;
try {
const r = await restartApp(app.lang);
restartFlash = r.message || r.notice || t("web_saved_ok");
restartFlashErr = false;
// Give the toast a beat to be read, then re-boot the SPA from the
// fresh backend state (mirrors the refresh button's final reload).
restartFlashTimer = setTimeout(() => {
window.location.reload();
}, 900);
} catch (err) {
restartFlash = err.message;
restartFlashErr = true;
// Errors auto-hide like the VRAM toast; success reloads above.
restartFlashTimer = setTimeout(() => {
restartFlash = "";
}, 5000);
} finally {
restartBusy = false;
}
}
async function onModelChange(e) {
const model = e.currentTarget.value;
const tab = app.activeTab;
if (!app.pickers[tab]) return;
const prevModel = app.pickers[tab].model;
const provider = app.pickers[tab].provider;
const src = PICKER_SOURCE[tab];
app.pickers = {
...app.pickers,
[tab]: { ...app.pickers[tab], model },
};
if (src) {
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 },
async () => {
try {
await saveSettings({ tab, model_label: model });
if (tab === "kb" && app.meta) {
app.meta = { ...app.meta, savedEmbed: { ...app.meta?.savedEmbed, model } };
}
} catch {}
},
() => {
if (prevModel && app.pickers[tab]) {
app.pickers = {
...app.pickers,
[tab]: { ...app.pickers[tab], model: prevModel },
};
}
}
);
return;
}
} catch {}
}
try {
// Every tab's model persists (STT/KB included β€” their slots are
// model_stt / model_embed on the backend) so each tab reopens on the
// user's last model pick.
await saveSettings({ tab, model_label: model });
if (tab === "kb" && app.meta) {
app.meta = { ...app.meta, savedEmbed: { ...app.meta?.savedEmbed, model } };
}
} catch {
/* non-fatal */
}
}
function selectTab(key) {
setActiveTab(key);
}
onMount(async () => {
let savedTheme = "light";
try {
savedTheme =
localStorage.getItem("lal-theme") ||
(matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
} catch {
/* ignore */
}
applyTheme(savedTheme);
const meta = await loadMeta();
initPickers(computePickers(meta, null));
await loadLanguage(meta.app?.lang || "kh");
// The VERY FIRST launch lands on the Settings tab and shows the setup
// popup (install GPU PyTorch, llama-server / llama-cpp-python, set the
// Hugging Face token) β€” exactly once, until the user dismisses it. The
// backend persists the dismissal, so later launches never re-trigger
// it: they restore the LAST-OPEN tab (General by default) instead.
if (meta.firstRun) {
// Forced first-run landing β€” persist=false so this is never
// remembered as the user's last tab (the next launch restores the
// last tab the USER opened, i.e. General by default).
setActiveTab("settings", false);
firstRunOpen = true;
} else {
let savedTab = "general";
try {
savedTab = localStorage.getItem("lal-active-tab") || "general";
} catch {
/* private mode */
}
// Only restore a tab that actually exists (a stale localStorage value
// must never break boot); falls back to General chat.
const valid = (meta.tabs || []).some((tb) => tb.key === savedTab);
if (valid && savedTab !== app.activeTab) setActiveTab(savedTab);
}
refreshMem();
// Keep the sidebar CPU/RAM/VRAM readouts live β€” same 5s cadence as the
// Settings tab's usage poll, so the numbers stay current without a reload.
const memTimer = setInterval(refreshMem, 5000);
return () => clearInterval(memTimer);
});
/** Strip a leading emoji from a tab label β€” the sidebar already renders the
* icon separately (tab.icon), so a label that starts with the same emoji
* would render it twice; the header title uses the same plain text so the
* two stay in sync. Handles VS16 (πŸŽ™οΈ) and the ZWSP some Khmer labels carry. */
function labelText(label) {
if (!label) return label || "";
const plain = label
.replace(/^\p{Extended_Pictographic}\uFE0F?\s*/u, "")
.replace(/^[\s\u200B\u2060\uFEFF]+/, "");
return plain || label;
}
/** Strip markdown (** and backticks) from a notice for tooltip display. */
function plainNotice(md) {
return (md || "")
.replace(/\*\*/g, "")
.replace(/`/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** Compact chip label: the leading emoji + the **bold** title. */
function chipLabel(md) {
const m = /^(\S+)\s*\*\*(.*?)\*\*/.exec(md || "");
if (m) return `${m[1]} ${m[2].trim()}`;
const plain = plainNotice(md);
return plain.length > 60 ? `${plain.slice(0, 59)}…` : plain;
}
// Fetch the downloaded-notice whenever the active tab's picker (or
// language) changes β€” reruns when app.pickers[tab] is replaced.
$effect(() => {
const tab = app.activeTab;
const p = app.pickers[tab];
if (!p || !p.model) {
modelNotice = "";
return;
}
const src = PICKER_SOURCE[tab];
let stale = false;
fetchModelNotice(p.provider, p.model, src.type, app.lang)
.then((r) => {
if (!stale) modelNotice = r.notice || "";
})
.catch(() => {
if (!stale) modelNotice = "";
});
return () => {
stale = true;
};
});
/** The sidebar / header-title tab label β€” derived from the client i18n
* table (`t("tab_" + key)`) so it reacts INSTANTLY to the header language
* toggle. The backend /api/meta tab labels are boot-time snapshots of the
* persisted user_config language (default Khmer), so relying on them makes
* the sidebar stay Khmer even after the user switches to English. */
function tabLabel(key) {
return labelText(t("tab_" + key));
}
</script>
<div class="shell" class:collapsed={sidebarCollapsed}>
<aside class="sidebar" id="app-sidebar">
<div class="brand">
<div class="brand-mark">
<img
class="brand-logo"
src="./logo.png"
alt="LocalAiLab"
draggable="false"
/>
</div>
<div>
<div class="brand-title-row">
<div class="brand-name">LocalAiLab</div>
<span class="brand-ver">v{app.meta?.app?.version ?? ""}</span>
</div>
</div>
</div>
<nav class="tabs">
{#each app.meta?.tabs ?? [] as tab (tab.key)}
<button
class="tab-btn"
class:active={app.activeTab === tab.key}
data-tooltip={tabLabel(tab.key)}
onclick={() => selectTab(tab.key)}
>
<span class="tab-ic">{tab.icon}</span>
<span class="tab-lb">{tabLabel(tab.key)}</span>
</button>
{/each}
</nav>
<!-- System usage readouts + Free All VRAM β€” always visible on EVERY tab
(the web port of the Gradio header's free-vram button). Deliberately
NOT gated behind the model notice (empty for cached/local GGUF
models) or the per-tab pickers (Settings/About have none), so the
user can always find and click it. Order: CPU, RAM, GPU (VRAM). -->
<div class="sidebar-stats">
{#if mem}
<span class="mem-chip" data-tooltip={t("info_mem_usage")}>
<span class="mem-chip-label">{t("web_mem_cpu")}</span>
<span class="mem-chip-val">{cpuText(mem?.cpu)}</span>
</span>
<span class="mem-chip" data-tooltip={t("info_mem_usage")}>
<span class="mem-chip-label">{t("web_mem_ram")}</span>
<span class="mem-chip-val">{memCompact(mem?.ram)}</span>
</span>
<span class="mem-chip" data-tooltip={t("info_mem_usage")}>
<span class="mem-chip-label">{t("web_mem_vram")}</span>
<span class="mem-chip-val">{memCompact(mem?.vram)}</span>
</span>
{/if}
<button
class="vram-btn"
data-tooltip={t("info_free_vram")}
onclick={doFreeVram}
disabled={vramBusy}
>
<span class="vram-btn-ic">πŸ’₯</span>
<span class="vram-btn-label">{t("web_free_vram")}</span>
</button>
{#if vramFlash}
<!-- The Free-All-VRAM confirmation renders as the SAME centered
popup toast as the llama-server / GGUF activation messages in
Settings (consistent confirmation style across the app). -->
<div class="settings-toast" class:err={vramFlashErr} role="status">
{vramFlash}
</div>
{/if}
</div>
<div class="sidebar-foot">
<span class="offline-dot"></span>
<a
class="yt-link"
href="https://youtube.com/@localailabkh"
target="_blank"
rel="noopener"
data-tooltip={t("web_youtube_tip")}
>
<span class="yt-ic">▢️</span>
<span class="yt-txt">{t("web_youtube")}</span>
</a>
</div>
</aside>
<div class="main">
<header class="header">
<button
class="icon-btn sidebar-toggle"
data-tooltip={sidebarCollapsed ? t("web_sidebar_expand") : t("web_sidebar_collapse")}
aria-label={sidebarCollapsed ? t("web_sidebar_expand") : t("web_sidebar_collapse")}
aria-expanded={!sidebarCollapsed}
aria-controls="app-sidebar"
onclick={toggleSidebar}
>
☰
</button>
<div class="header-title">{tabLabel(app.activeTab)}</div>
<div class="header-actions">
{#if app.busy}
<span class="busy-dot" data-tooltip={t("web_thinking")}></span>
{/if}
<button
class="icon-btn theme-toggle"
onclick={toggleTheme}
data-tooltip={t("info_theme_switch")}
aria-label={t("info_theme_switch")}
>
{theme === "dark" ? "β˜€οΈ" : "πŸŒ™"}
</button>
<div class="seg" data-tooltip={t("info_lang_switch")}>
<button
class:active={app.lang === "kh"}
onclick={() => loadLanguage("kh")}
data-tooltip={t("info_lang_switch")}
aria-label={t("info_lang_switch")}
>αžαŸ’αž˜αŸ‚αžš</button>
<button
class:active={app.lang === "en"}
onclick={() => loadLanguage("en")}
data-tooltip={t("info_lang_switch")}
aria-label={t("info_lang_switch")}
>EN</button>
</div>
{#if app.pickers[app.activeTab]}
<select
class="pill-select"
data-tooltip={t("info_provider")}
value={app.pickers[app.activeTab].provider}
onchange={onProviderChange}
>
{#each pickerProviders(app.activeTab) as p (p.value)}
<option value={p.label}>{p.label}</option>
{/each}
</select>
<select
class="pill-select"
data-tooltip={t("info_model")}
value={app.pickers[app.activeTab].model}
onchange={onModelChange}
disabled={!app.pickers[app.activeTab].choices.length}
>
{#each app.pickers[app.activeTab].choices as m (m)}
<option value={m}>{m}</option>
{/each}
</select>
{#if modelNotice}
<span class="model-status-chip" data-tooltip={plainNotice(modelNotice)}>
{chipLabel(modelNotice)}
</span>
{/if}
{/if}
<!-- Hard app refresh: re-boots the SPA (re-fetches /api/meta,
model lists, hardware status) without touching the backend β€”
picks up newly downloaded components / changed settings. -->
<button
class="icon-btn refresh-btn"
data-tooltip={t("web_tt_refresh_app")}
aria-label={t("web_tt_refresh_app")}
onclick={() => window.location.reload()}
>
πŸ”„
</button>
<!-- Full app restart: the backend resets every loaded model / cached
agent / managed server and rebuilds the model registry, then the
SPA re-boots from fresh /api/meta β€” use after installing new
components (GPU torch, llama-server, a new GGUF) or if the app
freezes. -->
<button
class="icon-btn restart-btn"
id="header-restart-btn"
data-tooltip={t("info_restart_app")}
aria-label={t("info_restart_app")}
onclick={doRestartApp}
disabled={restartBusy}
>
⏻
</button>
{#if restartFlash}
<!-- Restart confirmation β€” the same centered popup toast as the
Free-All-VRAM / path-activation messages. -->
<div class="settings-toast" class:err={restartFlashErr} role="status">
{restartFlash}
</div>
{/if}
</div>
</header>
<section class="content">
{#key app.activeTab}
{#if isChatTab(app.activeTab)}
<ChatPane
tab={app.activeTab}
modelLabel={app.pickers[app.activeTab]?.model ?? ""}
providerLabel={app.pickers[app.activeTab]?.provider ?? ""}
/>
{:else if app.activeTab === "stt"}
<SttTab />
{:else if app.activeTab === "kb"}
<KbTab />
{:else if app.activeTab === "settings"}
<SettingsTab />
{:else if app.activeTab === "about"}
<AboutTab />
{:else if app.activeTab === "feedback"}
<FeedbackTab />
{/if}
{/key}
</section>
</div>
</div>
<!-- First-run onboarding popup (shown once on the very first launch). -->
{#if firstRunOpen}
<FirstRunDialog onclose={() => { firstRunOpen = false; }} />
{/if}
<!-- Model download confirmation popup for any tab -->
{#if app.confirmModal}
<DownloadConfirmDialog
model={app.confirmModal.model}
onconfirm={app.confirmModal.onConfirm}
onclose={app.confirmModal.onCancel}
/>
{/if}
<!-- Global model download progress popup -->
<DownloadProgressPopup />
<!-- The app-wide styled tooltip singleton (delegated [data-tooltip] listeners). -->
<Tooltip />