import type { Snapshot } from "../shared/ipc"; function escape(text: string): string { return text.replace(/[&<>"]/g, (char) => { if (char === "&") return "&"; if (char === "<") return "<"; if (char === ">") return ">"; return """; }); } function time(at: number): string { return new Date(at).toLocaleTimeString("zh-CN", { hour12: false }); } function bytes(value: number): string { if (value < 1024) return `${value} B`; if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`; return `${(value / 1024 / 1024).toFixed(2)} MB`; } function snippet(text: string): string { const parts = text.split(/[\u0001\u0002]/); return parts .map((part, index) => index % 2 === 1 ? `${escape(part)}` : escape(part), ) .join(""); } export function mountApp(root: HTMLElement): void { root.innerHTML = `

本地知识库

导入 → 分块 → SQLite FTS5 → utilityProcess 索引
未索引 索引器未启动

索引

userData/knowledge/kb.sqlite
文档0
分块0
数据库0
索引耗时—
等待导入

    后台索引器

    utilityProcess

      索引在独立 utility 进程里做,主进程只读数据库;写入集中在 一个写者,WAL 让查询不被写入阻塞。进度通过 parentPort 消息回传。

      活动

      索引 / 搜索 / 错误

        全文检索

        —

          检索设计

          • 按段落/句子切块,块间保留 overlap,避免答案被切断。
          • FTS5 用 unicode61 分词;查询加前缀星号覆盖部分中文输入。
          • bm25 排序,snippet 高亮命中词;结果保留文档与块序号。
          • 索引器清空重建在一个事务里,失败不会留下半套数据。
          `; const status = root.querySelector('[data-testid="status"]'); const workerPill = root.querySelector( '[data-testid="worker-pill"]', ); const docCount = root.querySelector('[data-testid="doc-count"]'); const chunkCount = root.querySelector( '[data-testid="chunk-count"]', ); const dbSize = root.querySelector('[data-testid="db-size"]'); const indexTime = root.querySelector( '[data-testid="index-time"]', ); const progressBar = root.querySelector( '[data-testid="progress-bar"]', ); const progressText = root.querySelector( '[data-testid="progress-text"]', ); const errorEl = root.querySelector('[data-testid="error"]'); const docsEl = root.querySelector('[data-testid="docs"]'); const workerEl = root.querySelector('[data-testid="worker"]'); const eventsEl = root.querySelector('[data-testid="events"]'); const searchInput = root.querySelector( '[data-testid="search-input"]', ); const searchMeta = root.querySelector( '[data-testid="search-meta"]', ); const hitsEl = root.querySelector('[data-testid="hits"]'); const searchError = root.querySelector( '[data-testid="search-error"]', ); let state: Snapshot | null = null; function renderIndex(): void { if (!state) return; const info = state.index; if (status) { status.textContent = info.status === "ready" ? "已索引" : info.status === "indexing" ? "索引中" : info.status === "error" ? "失败" : "未索引"; status.className = `pill ${ info.status === "ready" ? "ok-pill" : info.status === "error" ? "bad-pill" : "" }`; } if (workerPill) { workerPill.textContent = state.worker.running ? `索引器运行中 · pid ${state.worker.pid}` : state.worker.pid ? `索引器已退出 · pid ${state.worker.pid}` : "索引器未启动"; } if (docCount) docCount.textContent = String(info.docs); if (chunkCount) chunkCount.textContent = String(info.chunks); if (dbSize) dbSize.textContent = bytes(info.dbBytes); if (indexTime) indexTime.textContent = info.indexedAt ? time(info.indexedAt) : "—"; if (progressBar) progressBar.style.width = `${info.progress}%`; if (progressText) { progressText.textContent = info.status === "indexing" ? `正在索引 ${info.current}/${info.total}(${info.progress}%)` : info.status === "ready" ? `索引完成 · ${info.docs} 篇 / ${info.chunks} 块` : "等待导入"; } if (errorEl) errorEl.textContent = info.lastError; if (docsEl) { docsEl.innerHTML = state.docs.length === 0 ? `
        • 尚未索引文档
        • ` : state.docs .map( (doc) => `
        • ${escape(doc.title)} ${escape(doc.path.split("/").pop() ?? doc.path)}
          ${doc.chunks} 块 · ${bytes(doc.bytes)}
        • `, ) .join(""); } if (workerEl) { workerEl.innerHTML = `
        • 状态${state.worker.running ? "运行中" : "空闲"}
        • PID${state.worker.pid || "—"}
        • 文档 / 块${info.docs} / ${info.chunks}
        • 数据库${bytes(info.dbBytes)}
        • `; } } function renderHits(): void { if (!state) return; if (searchMeta) { searchMeta.textContent = state.lastQuery ? `${state.hits.length} 条 · ${state.searchMs}ms` : "—"; } if (searchError) searchError.textContent = state.searchError; if (!hitsEl) return; hitsEl.innerHTML = state.hits.length === 0 ? `
        • ${ state.lastQuery ? "没有匹配结果" : "输入关键词后搜索" }
        • ` : state.hits .map( (hit) => `
        • ${escape(hit.title)} 第 ${hit.seq + 1} 块 · score ${hit.score}
          ${snippet(hit.snippet)}
        • `, ) .join(""); } function renderEvents(): void { if (!eventsEl || !state) return; eventsEl.innerHTML = state.events.length === 0 ? `
        • 暂无活动
        • ` : state.events .slice(0, 8) .map( (row) => `
        • ${time(row.at)} ${escape(row.kind)} ${escape(row.detail)}
        • `, ) .join(""); } function render(next: Snapshot): void { state = next; renderIndex(); renderHits(); renderEvents(); } void window.api.knowledge.snapshot().then(render); const unsubscribe = window.api.knowledge.onEvent(() => { void window.api.knowledge.snapshot().then(render); }); const run = async (promise: Promise): Promise => { try { render(await promise); } catch (caught) { if (errorEl) errorEl.textContent = String(caught); } }; root .querySelector('[data-testid="reindex"]') ?.addEventListener("click", () => void run(window.api.knowledge.reindex())); root .querySelector('[data-testid="start"]') ?.addEventListener( "click", () => void run(window.api.knowledge.startSamples()), ); root .querySelector('[data-testid="pick"]') ?.addEventListener("click", () => void run(window.api.knowledge.pick())); root .querySelector('[data-testid="refresh"]') ?.addEventListener("click", () => void run(window.api.knowledge.refresh())); const doSearch = (): void => { const query = searchInput?.value.trim() ?? ""; if (query) void run(window.api.knowledge.search(query)); }; root .querySelector('[data-testid="search"]') ?.addEventListener("click", doSearch); searchInput?.addEventListener("keydown", (event) => { if (event.key === "Enter") doSearch(); }); root .querySelectorAll("[data-sample]") .forEach((button) => { button.addEventListener("click", () => { if (searchInput) searchInput.value = button.dataset.sample ?? ""; doSearch(); }); }); const sleep = (value: number): Promise => new Promise((resolve) => setTimeout(resolve, value)); const waitIndexed = async (): Promise => { let snapshot = await window.api.knowledge.snapshot(); for (let attempt = 0; attempt < 80; attempt += 1) { if (snapshot.index.status === "ready") break; await sleep(100); snapshot = await window.api.knowledge.snapshot(); } render(snapshot); }; window.__prepareShots = async (stage) => { document.body.dataset.shot = stage; if (stage === "index") { await waitIndexed(); return; } if (stage === "search") { await waitIndexed(); if (searchInput) searchInput.value = "隔离区"; render(await window.api.knowledge.search("隔离区")); return; } render(await window.api.knowledge.refresh()); }; window.__smoke = async () => { const api = window.api.knowledge; const indexed = await api.reindex(); const one = await api.search("隔离区"); const two = await api.search("虚拟列表"); const prefix = await api.search("闭包"); const none = await api.search("zzzz-not-found"); const second = await api.reindex(); const final = await api.refresh(); unsubscribe(); return { docs: indexed.index.docs, chunks: indexed.index.chunks, dbBytes: indexed.index.dbBytes, workerPid: indexed.worker.pid, status: indexed.index.status, progress: indexed.index.progress, hits1: one.hits.length, hits2: two.hits.length, prefixHits: prefix.hits.length, noHits: none.hits.length, secondDocs: second.index.docs, sampleCount: indexed.samples.length, searchError: one.searchError, events: final.events.length, }; }; }