Spaces:
Paused

assistant / ui /web /src /components /KbTab.svelte
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
25.2 kB
<script>
import { app, t } from "../lib/stores.svelte.js";
import { fetchModelNotice, getSessionToken, kbClear, kbDelete, kbDocs, kbIndex, kbThemes, kbVisualClear, kbVisualDelete, kbVisualDocs, openReports } from "../lib/api.js";
import { showConfirmDialog } from "../lib/shortcuts.js";
import "./chat/Controls.css";
import MiniSelect from "./chat/MiniSelect.svelte";
// The embedding provider/model live in the shared header pickers
// (app.pickers.kb) β€” this tab only configures the visual retriever and
// the indexing upload itself.
let visualRetriever = $state("");
let files = $state([]);
/** Multi-select tags for the uploaded files β€” each selected theme/
* subtheme tags the upload (the backend indexes one copy per combination,
* so every picked tag is retrievable). Same controls as the RAG tab. */
let theme = $state([]);
let subtheme = $state([]);
/** Existing theme/subtheme choices β€” the multi-select dropdown options.
* The subtheme list is the UNION of the selected themes' subthemes (or
* all subthemes when no theme is picked). */
let themeList = $state([]);
let subthemeList = $state([]);
let busyIndex = $state(false);
let message = $state("");
/** Live terminal progress captured while indexing (embedding load, model
* warnings …) β€” shown in the result box and included in Copy All. */
let indexLog = $state("");
let actionMsg = $state("");
let flash = $state("");
let flashErr = $state(false);
let rows = $state([]);
let selected = $state([]); // row indexes
/** Visual index table β€” every visual document (source, doc id, pages). */
let visRows = $state([]);
let visSelected = $state([]);
let visActionMsg = $state("");
/** Visual retriever model notice β€” fetched from /api/model-notice. */
let visRetNotice = $state("");
let visRetNoticeRaw = $state("");
// Theme/subtheme filters for BOTH tables (multi-select, OR semantics β€”
// mirroring the RAG tab's filters). The option lists derive from the
// rows' own tag columns, so only tags actually present are offered.
let docThemeFilter = $state([]);
let docSubthemeFilter = $state([]);
let visThemeFilter = $state([]);
let visSubthemeFilter = $state([]);
function tagOptions(tableRows, idx) {
const set = new Set();
for (const r of tableRows || []) {
for (const t of String(r[idx] || "").split(",")) {
const v = t.trim();
if (v) set.add(v);
}
}
return [...set].sort();
}
function matchesTag(cell, filter) {
if (!filter || !filter.length) return true;
const tags = String(cell || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
return filter.some((f) => tags.includes(f));
}
// docs table: [Source, Type, Pages, Chunks, Theme, Subtheme]
const docThemeOptions = $derived(tagOptions(rows, 4));
const docSubthemeOptions = $derived(tagOptions(rows, 5));
const docFiltered = $derived(rows.filter(
(r) => matchesTag(r[4], docThemeFilter) && matchesTag(r[5], docSubthemeFilter)
));
// visual table: [Source, Doc ID, Pages/Images, Theme, Subtheme]
const visThemeOptions = $derived(tagOptions(visRows, 3));
const visSubthemeOptions = $derived(tagOptions(visRows, 4));
const visFiltered = $derived(visRows.filter(
(r) => matchesTag(r[3], visThemeFilter) && matchesTag(r[4], visSubthemeFilter)
));
// Thumbnail of a visual document's page, served from the persisted
// collection (no model load). Every /api/* route is session-token guarded
// and an <img> can't send a header β€” the token must ride ?token= (the
// same contract as the Data tab's chart images).
function thumbSrc(docId, page = 1) {
return `/api/kb/visual-thumb?doc_id=${encodeURIComponent(docId)}&page=${page}&token=${encodeURIComponent(getSessionToken())}`;
}
/** The page count of a visual row (row[2] = "pages/images"); never less
* than one, so every row always renders at least its first page. */
function visPageCount(row) {
const n = parseInt(String(row?.[2] || ""), 10);
return Number.isFinite(n) && n > 0 ? n : 1;
}
/** Full-size lightbox preview of a visual document's page (clicking the
* thumbnail) β€” same overlay pattern as the Data tab's chart zoom. */
let visLightbox = $state(null); // { src, name, docId, page }
function openVisPreview(row, page = 1) {
visLightbox = { src: thumbSrc(row[1], page), name: row[0], docId: row[1], page };
}
function closeVisPreview() {
visLightbox = null;
}
// Escape closes the preview; the listener lives only while it is open.
$effect(() => {
if (!visLightbox) return;
const onKey = (e) => {
if (e.key === "Escape") visLightbox = null;
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
});
async function loadThemeChoices(selectedThemes = []) {
try {
const res = await kbThemes("");
if (res?.ok) {
themeList = res.themes || [];
const sel = (selectedThemes || []).filter(Boolean);
if (sel.length === 0) {
subthemeList = res.subthemes || [];
} else {
const results = await Promise.all(sel.map((th) => kbThemes(th)));
const merged = new Set();
for (const r of results) {
if (r?.ok) for (const s of r.subthemes || []) merged.add(s);
}
subthemeList = [...merged].sort();
}
}
} catch {
// Degrade gracefully β€” the dropdowns just lose their suggestions.
}
}
// Refresh the subtheme list whenever the theme selection changes (the
// union of the picked themes' subthemes). Also seed from /api/meta.
$effect(() => {
const m = app.meta;
if (!m) return;
if (!visualRetriever) visualRetriever = m.visualRetrievers?.[0] || "";
if (m.themes?.length) themeList = m.themes;
loadThemeChoices(theme);
});
// Fetch the visual retriever model download notice when the selection changes.
$effect(() => {
const vr = visualRetriever;
if (!vr) { visRetNotice = ""; visRetNoticeRaw = ""; return; }
let stale = false;
// Extract the model id from the label (e.g. "vidore/colpali-v1.3-hf (~2 GB | recommended)" β†’ "vidore/colpali-v1.3-hf")
const modelId = vr.split(/\s/)[0];
fetchModelNotice("", modelId, "embed", app.lang)
.then((r) => {
if (!stale) { visRetNoticeRaw = r.notice || ""; visRetNotice = r.notice || ""; }
})
.catch(() => { if (!stale) { visRetNotice = ""; visRetNoticeRaw = ""; } });
return () => { stale = true; };
});
let inited = false;
$effect(() => {
if (!app.meta || inited) return;
inited = true;
refresh(true);
});
const headers = $derived(t("doc_table_headers"));
function pickFiles(e) {
files = [...e.currentTarget.files];
e.currentTarget.value = "";
message = "";
}
function removeFile(i) {
files = files.filter((_, idx) => idx !== i);
}
async function index() {
if (busyIndex) return;
if (!files.length) {
message = t("web_no_files");
return;
}
busyIndex = true;
indexLog = "";
message = t("web_kb_indexing");
try {
const r = await kbIndex({
files, theme, subtheme, visualRetriever, lang: app.lang,
embedProvider: app.pickers?.kb?.provider || "",
embedModel: app.pickers?.kb?.model || "",
onLog: (line) => {
indexLog = indexLog ? indexLog + "\n" + line : line;
// keep the result line live too, so the box updates as it streams
message = indexLog.split("\n").slice(-1)[0] || t("web_kb_indexing");
},
});
message = r.message || t("web_saved_ok");
await refresh(true);
} catch (err) {
message = err.message;
} finally {
busyIndex = false;
}
}
async function refresh(force = false) {
try {
const r = await kbDocs(force);
rows = r.rows || [];
selected = [];
} catch { /* keep last rows */ }
try {
const v = await kbVisualDocs();
visRows = v.rows || [];
visSelected = [];
} catch { /* keep last visual rows */ }
}
function toggleVisRow(i) {
visSelected = visSelected.includes(i)
? visSelected.filter((x) => x !== i)
: [...visSelected, i];
}
async function doVisDelete() {
if (!visSelected.length) {
visActionMsg = t("web_no_files");
return;
}
// Destructive and irreversible β€” confirm first (same themed dialog).
const ok = await showConfirmDialog({
message: t("kb_confirm_visual_delete").replace("{n}", String(visSelected.length)),
ok: t("btn_delete"),
cancel: t("web_confirm_cancel"),
});
if (!ok) return;
try {
const r = await kbVisualDelete(visSelected, visFiltered, app.lang);
visActionMsg = r.message || "";
visRows = r.rows || [];
visSelected = [];
} catch (err) {
visActionMsg = err.message;
}
}
async function doVisClear() {
// Wipes the whole visual index β€” always ask first.
const ok = await showConfirmDialog({
message: t("kb_confirm_visual_clear"),
ok: t("btn_clear_all"),
cancel: t("web_confirm_cancel"),
});
if (!ok) return;
try {
const r = await kbVisualClear(app.lang);
visActionMsg = r.message || "";
visRows = r.rows || [];
visSelected = [];
} catch (err) {
visActionMsg = err.message;
}
}
function toggleRow(i) {
selected = selected.includes(i) ? selected.filter((x) => x !== i) : [...selected, i];
}
async function doDelete() {
if (!selected.length) {
actionMsg = t("web_no_files");
return;
}
// Destructive and irreversible β€” ask for confirmation first (the same
// themed in-app dialog the chat clear uses). The count is the number of
// selected rows (each a source file and its indexed chunks).
const ok = await showConfirmDialog({
message: t("kb_confirm_delete").replace("{n}", String(selected.length)),
ok: t("btn_delete"),
cancel: t("web_confirm_cancel"),
});
if (!ok) return;
try {
const r = await kbDelete(selected, docFiltered, app.lang);
actionMsg = r.message || "";
rows = r.rows || [];
selected = [];
} catch (err) {
actionMsg = err.message;
}
}
async function doClear() {
// Clearing the WHOLE knowledge base (documents + images + chunks) is
// irreversible β€” always ask for confirmation first.
const ok = await showConfirmDialog({
message: t("kb_confirm_clear_all"),
ok: t("btn_clear_all"),
cancel: t("web_confirm_cancel"),
});
if (!ok) return;
try {
const r = await kbClear(app.lang);
actionMsg = r.message || "";
rows = r.rows || [];
selected = [];
} catch (err) {
actionMsg = err.message;
}
}
async function doOpenReports() {
try {
// KB has no per-tab report folder β€” open the reports base dir.
const r = await openReports();
actionMsg = r.ok ? (r.path ? t("web_opened_path").replace("{path}", r.path) : t("web_opened")) : t("web_open_failed");
} catch (err) {
actionMsg = err.message;
}
}
/** Transient "Copied" / "Failed to copy" status line next to the button. */
function flashMsg(msg, err = false) {
flash = msg;
flashErr = err;
}
const activeEmbedProvider = $derived(app.pickers?.kb?.provider || app.meta?.savedEmbed?.provider || "β€”");
const activeEmbedModel = $derived(app.pickers?.kb?.model || app.meta?.savedEmbed?.model || "β€”");
/** Copy EVERY KB result to the clipboard as plain text: the active
* embedding model, the visual-retriever model notice (the FULL raw
* markdown β€” the chip on screen truncates it), every app/message status
* line, and both tables (docs + visual index) as tab-separated rows. */
async function copyAllResults() {
const parts = [];
parts.push(
`${t("label_embed_active")}: ${activeEmbedProvider} / ${activeEmbedModel}`
);
if (visualRetriever) parts.push(`${t("label_vis_ret")}: ${visualRetriever}`);
if (visRetNoticeRaw) parts.push(`${t("label_vis_ret")}: ${visRetNoticeRaw.replace(/\*\*/g, "").replace(/`/g, "").replace(/\s+/g, " ").trim()}`);
if (message) parts.push(message);
if (indexLog) parts.push(`${t("web_tt_kb_log")}\n${indexLog}`);
if (actionMsg) parts.push(actionMsg);
if (visActionMsg) parts.push(visActionMsg);
if (docFiltered.length) {
const lines = [t("doc_table_headers").join("\t")];
for (const row of docFiltered) {
lines.push(row.map((c) => String(c ?? "")).join("\t"));
}
parts.push(`${t("label_kb_docs")}\n${lines.join("\n")}`);
}
if (visFiltered.length) {
const lines = [t("visual_table_headers").join("\t")];
for (const row of visFiltered) {
lines.push(row.map((c) => String(c ?? "")).join("\t"));
}
parts.push(`${t("label_visual_docs")}\n${lines.join("\n")}`);
}
try {
await navigator.clipboard.writeText(parts.join("\n\n"));
flashMsg(t("web_copied"));
} catch {
flashMsg(t("web_copy_fail"), true);
}
}
</script>
<div class="tab-scroll">
<div class="card">
<div class="card-title">{t("tab_kb_desc")}</div>
<div class="field-row">
<label class="field" data-tooltip={t("web_tt_vis_ret")}>
<span class="field-label">{t("label_vis_ret")}</span>
<select bind:value={visualRetriever}>
{#each app.meta?.visualRetrievers ?? [] as v (v)}
<option value={v}>{v}</option>
{/each}
</select>
</label>
{#if visRetNotice}
<span class="model-status-chip" data-tooltip={visRetNoticeRaw.replace(/\*\*/g, "").replace(/`/g, "").replace(/\s+/g, " ").trim()}>
{#if visRetNotice.includes("βœ…")}
βœ… {(visRetNotice.match(/\*\*(.*?)\*\*/) || ["", visRetNotice])[1].trim() || visRetNotice.replace(/\*\*/g, "").replace(/`/g, "").slice(0, 40)}
{:else if visRetNotice.includes("πŸ“₯")}
πŸ“₯ {(visRetNotice.match(/\*\*(.*?)\*\*/) || ["", visRetNotice])[1].trim() || visRetNotice.replace(/\*\*/g, "").replace(/`/g, "").slice(0, 40)}
{:else}
{visRetNotice.replace(/\*\*/g, "").replace(/`/g, "").replace(/\s+/g, " ").trim().slice(0, 50)}
{/if}
</span>
{/if}
</div>
<div class="field-row">
<span class="embed-active-info">
{t("label_embed_active")}:
<strong>{activeEmbedProvider}</strong>
/ <strong>{activeEmbedModel}</strong>
</span>
</div>
<label class="upload-area" data-tooltip={t("web_tt_upload_files")}>
<input type="file" accept=".pdf,.txt,.md,.docx,.png,.jpg,.jpeg,.webp,.bmp,.gif" multiple onchange={pickFiles} hidden />
<span>
{t("web_upload_files")}
{#if files.length}
<span class="upload-name">({files.length})</span>
{/if}
</span>
</label>
{#if files.length > 0}
<div class="rag-files">
{#each files as f, i (f.name)}
<span class="chip file-chip" data-tooltip={f.name}>
<span class="file-chip-name">{f.name}</span>
<button
type="button"
class="chip-x"
aria-label={t("web_tt_remove_file")}
data-tooltip={t("web_tt_remove_file")}
onclick={() => removeFile(i)}
>βœ•</button>
</span>
{/each}
</div>
{/if}
<div class="field-row">
<label class="field" data-tooltip={t("web_tt_theme_field")}>
<span class="field-label">{t("theme_label")}</span>
<MiniSelect
multiple
creatable
createLabel={t("web_create_tag")}
bind:value={theme}
options={themeList}
noneLabel={t("web_filter_none")}
tip={t("web_tt_theme_field")}
onopen={() => loadThemeChoices(theme)}
/>
</label>
<label class="field" data-tooltip={t("web_tt_subtheme_field")}>
<span class="field-label">{t("subtheme_label")}</span>
<MiniSelect
multiple
creatable
createLabel={t("web_create_tag")}
bind:value={subtheme}
options={subthemeList}
noneLabel={t("web_filter_none")}
tip={t("web_tt_subtheme_field")}
onopen={() => loadThemeChoices(theme)}
/>
</label>
</div>
<button class="btn btn-primary" onclick={index} disabled={busyIndex} data-tooltip={t("web_tt_index")}>
{t("btn_index")}
</button>
{#if message}
<div class="status-line" class:err={message.startsWith("⚠️") || message.startsWith("❌")}>
{message}
</div>
{/if}
{#if indexLog}
<div class="kb-log" data-tooltip={t("web_tt_kb_log")}>
{#each indexLog.split("\n") as line}
<div class="kb-log-line">{line}</div>
{/each}
</div>
{/if}
</div>
<div class="card">
<div class="card-title">{t("label_kb_docs")}</div>
{#if rows.length}
<div class="theme-row">
<label class="mini-field" data-tooltip={t("web_tt_theme_filter")}>
<span>{t("web_theme")}</span>
<MiniSelect
multiple
bind:value={docThemeFilter}
options={docThemeOptions}
emptyLabel={t("web_filter_all")}
noneLabel={t("web_filter_none")}
tip={t("web_tt_theme_filter")}
/>
</label>
<label class="mini-field" data-tooltip={t("web_tt_subtheme_filter")}>
<span>{t("web_subtheme")}</span>
<MiniSelect
multiple
bind:value={docSubthemeFilter}
options={docSubthemeOptions}
emptyLabel={t("web_filter_all")}
noneLabel={t("web_filter_none")}
tip={t("web_tt_subtheme_filter")}
/>
</label>
</div>
{#if docFiltered.length}
<div class="table-wrap">
<table class="doc-table">
<thead>
<tr>
{#each headers as h (h)}
<th>{h}</th>
{/each}
</tr>
</thead>
<tbody>
{#each docFiltered as row, i (i)}
<tr class:sel={selected.includes(i)} onclick={() => toggleRow(i)} data-tooltip={t("web_tt_doc_row")}>
{#each row as cell, j (j)}
{#if j === 6 && row[6]}
<td>
<img
class="vis-thumb"
src={thumbSrc(row[6], 1)}
alt=""
loading="lazy"
data-tooltip={t("web_tt_doc_thumb").replace("{name}", row[0])}
onclick={(e) => {
e.stopPropagation(); // don't toggle row selection
openVisPreview([row[0], row[6]], 1);
}}
onerror={(e) => (e.currentTarget.style.display = "none")}
/>
</td>
{:else}
<td>{cell}</td>
{/if}
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
<div class="tool-row">
<button class="btn btn-sm" onclick={() => refresh(true)} data-tooltip={t("web_tt_refresh_docs")}>{t("btn_refresh")}</button>
<button class="btn btn-danger btn-sm" onclick={doDelete} data-tooltip={t("web_tt_delete_docs")}>{t("btn_delete")}</button>
<button class="btn btn-danger btn-sm" onclick={doClear} data-tooltip={t("web_tt_clear_all_docs")}>{t("btn_clear_all")}</button>
<button class="btn btn-sm" onclick={copyAllResults} disabled={!rows.length && !visRows.length} data-tooltip={t("web_tt_copy_all")}>{t("btn_copy_all")}</button>
<button class="btn btn-sm" 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>
{:else}
<div class="empty-hint">{t("web_no_rows_match")}</div>
{/if}
{:else}
<div class="empty-hint">{t("web_empty_hint")}</div>
{/if}
{#if actionMsg}
<div class="status-line">{actionMsg}</div>
{/if}
</div>
<div class="card">
<div class="card-title">{t("label_visual_docs")}</div>
{#if visRows.length}
<div class="theme-row">
<label class="mini-field" data-tooltip={t("web_tt_theme_filter")}>
<span>{t("web_theme")}</span>
<MiniSelect
multiple
bind:value={visThemeFilter}
options={visThemeOptions}
emptyLabel={t("web_filter_all")}
noneLabel={t("web_filter_none")}
tip={t("web_tt_theme_filter")}
/>
</label>
<label class="mini-field" data-tooltip={t("web_tt_subtheme_filter")}>
<span>{t("web_subtheme")}</span>
<MiniSelect
multiple
bind:value={visSubthemeFilter}
options={visSubthemeOptions}
emptyLabel={t("web_filter_all")}
noneLabel={t("web_filter_none")}
tip={t("web_tt_subtheme_filter")}
/>
</label>
</div>
{#if visFiltered.length}
<div class="table-wrap">
<table class="doc-table">
<thead>
<tr>
{#each t("visual_table_headers") as h (h)}
<th>{h}</th>
{/each}
</tr>
</thead>
<tbody>
{#each visFiltered as row, i (i)}
<tr class:sel={visSelected.includes(i)} onclick={() => toggleVisRow(i)} data-tooltip={t("web_tt_doc_row")}>
{#each row as cell, j (j)}
{#if j === 0}
<td>
<span class="vis-cell">
<span class="vis-strip">
{#each Array(visPageCount(row)) as _, p (p)}
<img
class="vis-thumb"
src={thumbSrc(row[1], p + 1)}
alt=""
loading="lazy"
data-tooltip={t("web_tt_visual_thumb").replace("{page}", String(p + 1))}
onclick={(e) => {
e.stopPropagation(); // don't toggle row selection
openVisPreview(row, p + 1);
}}
onerror={(e) => (e.currentTarget.style.display = "none")}
/>
{/each}
</span>
<span>{cell}</span>
</span>
</td>
{:else}
<td>{cell}</td>
{/if}
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
<div class="tool-row">
<button class="btn btn-sm" onclick={() => refresh(true)} data-tooltip={t("web_tt_refresh_docs")}>{t("btn_refresh")}</button>
<button class="btn btn-danger btn-sm" onclick={doVisDelete} data-tooltip={t("web_tt_visual_delete")}>{t("btn_delete")}</button>
<button class="btn btn-danger btn-sm" onclick={doVisClear} data-tooltip={t("web_tt_visual_clear")}>{t("btn_clear_all")}</button>
<button class="btn btn-sm" onclick={copyAllResults} disabled={!rows.length && !visRows.length} data-tooltip={t("web_tt_copy_all")}>{t("btn_copy_all")}</button>
{#if flash}
<span class="tool-flash" class:err={flashErr}>{flash}</span>
{/if}
</div>
{:else}
<div class="empty-hint vis-empty">{t("web_no_rows_match")}</div>
{/if}
{:else}
<div class="empty-hint vis-empty">{t("web_empty_visual")}</div>
{/if}
{#if visActionMsg}
<div class="status-line">{visActionMsg}</div>
{/if}
</div>
{#if visLightbox}
<!-- Full-size preview of the visual page: the whole overlay closes on
a background click; the image itself stays put for inspection. -->
<div
class="chart-lightbox"
role="dialog"
aria-modal="true"
onclick={(e) => {
if (e.target === e.currentTarget) closeVisPreview();
}}
>
<button
type="button"
class="lightbox-close"
aria-label={t("web_tt_close_preview")}
data-tooltip={t("web_tt_close_preview")}
onclick={closeVisPreview}
>
Γ—
</button>
<img src={visLightbox.src} alt={visLightbox.name} />
<span class="lightbox-caption">
{t("web_visual_page_of").replace("{page}", String(visLightbox.page)).replace("{name}", visLightbox.name)}
</span>
</div>
{/if}
</div>