LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: context budget — proportional page cap + LLM response reserve
nash_su06555f5ed8eb
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsxindex ea5bd97d..078f42c9 100644--- a/src/components/chat/chat-panel.tsx+++ b/src/components/chat/chat-panel.tsx@@ -13,6 +13,7 @@ import { buildRetrievalGraph, getRelatedNodes } from "@/lib/graph-relevance"import { normalizePath, getFileName, getRelativePath } from "@/lib/path-utils"import { getOutputLanguage, buildLanguageReminder } from "@/lib/output-language"import { isGreeting } from "@/lib/greeting-detector"+import { computeContextBudget } from "@/lib/context-budget"// Store the page mapping from the last query so SourceFilesBar can show which pages were citedexport let lastQueryPages: { title: string; path: string }[] = []@@ -189,12 +190,16 @@ export function ChatPanel() {} else if (project) {const pp = normalizePath(project.path)const dataVersion = useWikiStore.getState().dataVersion- const maxCtx = llmConfig.maxContextSize || 204800- // ── Budget allocation ──────────────────────────────────- const INDEX_BUDGET = Math.floor(maxCtx * 0.05)- const PAGE_BUDGET = Math.floor(maxCtx * 0.6)- const MAX_PAGE_SIZE = Math.min(Math.floor(PAGE_BUDGET * 0.3), 30_000)+ // ── Budget allocation (see context-budget.ts) ─────────+ // Page budget scales with the LLM's context window; we now+ // also reserve ~15% as headroom for the response so the+ // model isn't truncated mid-sentence on a packed prompt.+ const {+ indexBudget: INDEX_BUDGET,+ pageBudget: PAGE_BUDGET,+ maxPageSize: MAX_PAGE_SIZE,+ } = computeContextBudget(llmConfig.maxContextSize)const [rawIndex, purpose] = await Promise.all([readFile(`${pp}/wiki/index.md`).catch(() => ""),diff --git a/src/lib/context-budget.test.ts b/src/lib/context-budget.test.tsnew file mode 100644index 00000000..6f5eb0c6--- /dev/null+++ b/src/lib/context-budget.test.ts@@ -0,0 +1,101 @@+/**+ * Unit tests for computeContextBudget.+ *+ * The function is pure, so tests can pin exact integer outputs. The+ * scenarios below are picked deliberately to exercise the boundaries+ * we care about:+ * - tiny configs (8K-class models)+ * - mid configs (32K, 128K)+ * - large configs (200K — the previous default + cap boundary)+ * - huge configs (1M — the case the old 30K cap actively wasted)+ * - degenerate inputs (0, undefined, NaN)+ */+import { describe, it, expect } from "vitest"+import { computeContextBudget } from "./context-budget"++describe("computeContextBudget", () => {+ it("falls back to 204,800 chars when input is undefined / 0 / NaN", () => {+ expect(computeContextBudget(undefined).maxCtx).toBe(204_800)+ expect(computeContextBudget(0).maxCtx).toBe(204_800)+ expect(computeContextBudget(NaN).maxCtx).toBe(204_800)+ })++ it("8K-class small model: per-page cap clamps to pageBudget so one page can fully use the budget", () => {+ const b = computeContextBudget(8_192)+ // pageBudget = 4,096 (50%); per-page floor of 5,000 would exceed+ // that, so per-page MUST clamp down to pageBudget itself.+ // Otherwise tryAddPage would slice to 5K, then reject the slice+ // for being > 4K total budget — net result: page never makes it.+ expect(b.pageBudget).toBe(4_096)+ expect(b.maxPageSize).toBe(4_096)+ expect(b.responseReserve).toBe(1_228)+ expect(b.indexBudget).toBe(409)+ })++ it("32K mid-tier: floor of 5,000 chars/page is the binding cap, not the 30% rule", () => {+ const b = computeContextBudget(32_000)+ // pageBudget = 16,000; 30% = 4,800 < 5,000 floor → maxPageSize = 5,000.+ // Pin this so a regression that drops the floor would surface as+ // a tiny per-page truncation on small-context configs.+ expect(b.pageBudget).toBe(16_000)+ expect(b.maxPageSize).toBe(5_000)+ })++ it("128K config: 30% rule kicks in, per-page = 19,200", () => {+ const b = computeContextBudget(131_072)+ expect(b.pageBudget).toBe(65_536)+ // 65,536 * 0.3 = 19,660.8 → floor = 19,660. Well above the 5K floor.+ expect(b.maxPageSize).toBe(19_660)+ })++ it("200K config (legacy default): per-page is 30,720 — NOT the old 30,000 cap", () => {+ const b = computeContextBudget(204_800)+ expect(b.pageBudget).toBe(102_400)+ expect(b.maxPageSize).toBe(30_720) // proportional, not capped at 30K+ expect(b.responseReserve).toBe(30_720)+ expect(b.indexBudget).toBe(10_240)+ })++ it("1M config: per-page is 150,000 — used to be capped at 30K, wasting 5x the budget", () => {+ const b = computeContextBudget(1_000_000)+ expect(b.pageBudget).toBe(500_000)+ // 500_000 * 0.3 = 150_000. Old code would have returned min(150K, 30K) = 30K+ // and never allowed a long page through.+ expect(b.maxPageSize).toBe(150_000)+ expect(b.responseReserve).toBe(150_000)+ expect(b.indexBudget).toBe(50_000)+ })++ it("budgets always sum to ≤ maxCtx (never over-provision)", () => {+ // Index + pages + response reserve must leave room for system+ // prompt + conversation history + user query. Anything over 100%+ // would overflow context immediately.+ for (const maxCtx of [4_000, 32_000, 128_000, 204_800, 1_000_000]) {+ const b = computeContextBudget(maxCtx)+ const sum = b.indexBudget + b.pageBudget + b.responseReserve+ expect(sum, `maxCtx=${maxCtx}: index+pages+response=${sum} > ${maxCtx}`).toBeLessThanOrEqual(maxCtx)+ // And we should leave a meaningful chunk (≥20%) for history ++ // system prompt. 100% - 5% - 50% - 15% = 30% remaining.+ expect(maxCtx - sum, `maxCtx=${maxCtx}: only ${maxCtx - sum} left for history/prompt`).toBeGreaterThanOrEqual(+ Math.floor(maxCtx * 0.2),+ )+ }+ })++ it("response reserve is exactly 15% (regression guard for the new behavior)", () => {+ // If someone bumps RESPONSE_RESERVE_FRAC, EVERY ratio elsewhere+ // shifts. Pin it at the boundary.+ expect(computeContextBudget(100_000).responseReserve).toBe(15_000)+ expect(computeContextBudget(1_000_000).responseReserve).toBe(150_000)+ })++ it("maxPageSize never exceeds pageBudget (a single page can't outgrow the entire page budget)", () => {+ for (const maxCtx of [1_000, 2_000, 5_000, 8_192, 16_000, 32_000, 100_000, 1_000_000]) {+ const b = computeContextBudget(maxCtx)+ expect(+ b.maxPageSize,+ `maxCtx=${maxCtx}: maxPageSize=${b.maxPageSize} > pageBudget=${b.pageBudget}`,+ ).toBeLessThanOrEqual(b.pageBudget)+ }+ })+})diff --git a/src/lib/context-budget.ts b/src/lib/context-budget.tsnew file mode 100644index 00000000..cd24fd5e--- /dev/null+++ b/src/lib/context-budget.ts@@ -0,0 +1,99 @@+/**+ * Pure budget allocator for chat context assembly.+ *+ * Given an LLM's `maxContextSize` (in characters — see wiki-store.ts;+ * yes, that's a quirky unit, but tokens-vs-chars conversion lives+ * elsewhere), compute the per-section character budgets used by+ * chat-panel when packing the prompt.+ *+ * Why this is its own module:+ * - The math has corner cases that deserve their own tests+ * (tiny configs, huge configs, the legacy 30K cap removal).+ * - Inlining it in chat-panel.tsx made it untestable in isolation.+ *+ * The shape of the budget:+ *+ * ┌─────────────────────────────────────────────────────┐+ * │ maxCtx (100%) │+ * ├──────┬───────────────┬──────────────────┬───────────┤+ * │ idx │ pages │ history + sys │ resp │+ * │ 5% │ 50% │ ~30% │ 15% │+ * └──────┴───────────────┴──────────────────┴───────────┘+ *+ * `historyAndSystem` isn't returned because it's not enforced as a+ * single budget — system prompt is roughly fixed-size, and history+ * is gated by `maxHistoryMessages` (count, not bytes). The leftover+ * just provides headroom.+ *+ * The response reserve is a "passive" reservation: we don't pass+ * `max_tokens: responseReserve / 3` to the LLM (yet — that's a+ * follow-up). We just refuse to fill above (maxCtx - responseReserve)+ * so the LLM has room to actually answer.+ */++/** Result of `computeContextBudget`. All values are character counts. */+export interface ContextBudget {+ /** The model's full context window (always populated; falls back+ * to a sensible default when caller passes 0/undefined). */+ maxCtx: number+ /** Characters NOT to be filled with prompt content — left empty so+ * the LLM has room to write its response. */+ responseReserve: number+ /** Wiki index summary budget. ~5% — enough to list every page's+ * title without occupying serious budget. */+ indexBudget: number+ /** Total characters available for retrieved wiki page content. */+ pageBudget: number+ /** Per-page truncation cap. A single page won't be embedded longer+ * than this even if `pageBudget` would allow it. Scales with+ * pageBudget (used to be hard-capped at 30,000 chars regardless+ * of context size — that wasted budget on long-context models). */+ maxPageSize: number+}++const DEFAULT_MAX_CTX = 204_800+const RESPONSE_RESERVE_FRAC = 0.15+const INDEX_BUDGET_FRAC = 0.05+const PAGE_BUDGET_FRAC = 0.5+const PER_PAGE_FRAC = 0.3+const PER_PAGE_FLOOR = 5_000++/**+ * Compute character budgets from the LLM's max context window.+ *+ * Falsy `maxContextSize` (0 / NaN / undefined) falls back to the+ * pre-Phase-1 default of 200K chars so existing configs don't break.+ */+export function computeContextBudget(+ maxContextSize: number | undefined,+): ContextBudget {+ const maxCtx =+ typeof maxContextSize === "number" && maxContextSize > 0+ ? maxContextSize+ : DEFAULT_MAX_CTX++ const responseReserve = Math.floor(maxCtx * RESPONSE_RESERVE_FRAC)+ const indexBudget = Math.floor(maxCtx * INDEX_BUDGET_FRAC)+ const pageBudget = Math.floor(maxCtx * PAGE_BUDGET_FRAC)++ // Per-page cap rules:+ // - At minimum, allow PER_PAGE_FLOOR (5K) so a small config still+ // fits one short page.+ // - At maximum, never exceed pageBudget itself — for tiny configs+ // where pageBudget < 5K, the floor would otherwise allow a+ // single page bigger than the entire page budget, which then+ // gets entirely rejected by tryAddPage in chat-panel.+ // - Otherwise scale linearly with pageBudget at PER_PAGE_FRAC (30%).+ const maxPageSize = Math.min(+ pageBudget,+ Math.max(PER_PAGE_FLOOR, Math.floor(pageBudget * PER_PAGE_FRAC)),+ )++ return {+ maxCtx,+ responseReserve,+ indexBudget,+ pageBudget,+ maxPageSize,+ }+}