AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import type { Db } from './db'
import { DEFAULT_SETTINGS, type AppSettings } from '../../shared/types'
import {
normalizeBenchmarkHistory,
normalizeBenchmarkResult,
normalizeGpuProbe,
normalizeModelPlacements
} from '../../shared/benchmark-schema'
import { MAX_LOCAL_API_PORT, MIN_LOCAL_API_PORT } from '../../shared/local-api'
import { isUiLanguageSetting } from '../../shared/i18n'
/** Upper bound on any persisted string[] setting so a buggy/hostile renderer can't bloat the
* encrypted settings blob (`skillInfoSeen` is the shipping case; the element-wise validation
* below stays generic for future ones). */
const MAX_SETTINGS_ARRAY = 10_000
/** Bounds for the null-default settings keys (BE-1, full-audit 2026-07-10). Their defaults
* carry no type information (they are null), so the generic type gate in `updateSettings`
* cannot check them — each gets an explicit shape check, and the string ones a length cap in
* the SEC-1 bounding style so a buggy/hostile renderer can't bloat the encrypted settings
* blob. Generous on purpose: model ids are short slugs; `gpuLastError` is a one-line
* timestamped reason (`persistGpuFailure` truncates it to 2 000 chars before it gets here). */
const MAX_SETTINGS_ID_LENGTH = 512
const MAX_SETTINGS_ERROR_LENGTH = 4096
/** Serialized-JSON ceiling for the object-valued settings (`checksumCache` map, plus the
* `lastBenchmark`/`gpuProbe` result blobs). These are read on start/hot paths and persist into
* the encrypted settings blob; the shape gates in `updateSettings` check only the top-level type,
* so a buggy/hostile renderer could otherwise bloat the blob without bound (CODE-16,
* full-audit 2026-07-11). 256 KB dwarfs a real benchmark/probe blob and a large checksum map
* (~120 B/entry ⇒ ~2 000 weights) — an over-cap payload is dropped, SEC-1 bounding style. */
const MAX_SETTINGS_OBJECT_BYTES = 256 * 1024
/** Floor for `contextTokens` (HIGH_BUG vuln-scan-2026-06-21). The doc-task window budget is
* derived from this; below this floor the summary-tree builder's per-level node summaries can
* exceed a single budget window and the build cannot reduce. 2048 always fits >= 2 node
* summaries (each <= SUMMARY_OUTPUT_TOKENS) plus the prompt/output reserve in one reduce
* window. A renderer-supplied value below it is clamped UP, never dropped. */
const MIN_CONTEXT_TOKENS = 2048
/** Ceiling for the user's `contextTokensOverride` (AI Model screen context-size picker). The KV
* cache grows linearly with the window, so very large picks cost real memory — but a hard 32k
* cap dead-ended long-document workflows (deep index, whole-doc summaries) on models whose
* native window is far larger (issue #43: Qwen3.5 is 262k native). 128k covers every preset
* the UI offers; the picker pairs the big rungs with an honest memory warning instead of a
* silent cap, and a start that doesn't fit falls down the GPU ladder to CPU or fails with a
* friendly error rather than wedging the app. */
export const MAX_CONTEXT_TOKENS_OVERRIDE = 131_072
/** Bounds for the retrieval tuning keys (#868). No screen writes them, but they stay renderer-writable
* (a maintainer may tune them in the running app), so the gate bounds them instead of trusting
* `typeof`: a negative count or a huge budget was stored as given, and NaN / ±Infinity (they survive
* the IPC's structured clone) were stored as JSON `null` and read back by retrieval
* (`ragSettingsFrom`) and the reranker's request ceiling (`cpuRequestCeilingFor`). A finite value is
* floored (the counts and the token budget) and clamped into its range; a non-finite one is dropped
* and the previous value kept (the `localApiPort` convention). The ranges are generous: they keep
* every sane tuning and refuse only values no retrieval can use (`ragMinSimilarity` is a cosine
* floor, 0 keeps every non-negative hit; the budget ceiling is the largest context window the app
* launches). `contextTokens` keeps its own floor and gains the same ceiling, below. */
const RETRIEVAL_TUNING_BOUNDS = {
ragTopKInitial: { min: 1, max: 200, integer: true },
ragTopKFinal: { min: 1, max: 200, integer: true },
ragMaxContextTokens: { min: 256, max: MAX_CONTEXT_TOKENS_OVERRIDE, integer: true },
ragMinSimilarity: { min: 0, max: 1, integer: false }
} as const satisfies Partial<Record<keyof AppSettings, { min: number; max: number; integer: boolean }>>
// Settings persistence on top of the key/value `settings` table (spec §8).
// Each AppSettings field is stored as its own row so partial updates are clean.
// The table lives inside the workspace database, so on an encrypted workspace the
// settings are encrypted at rest and unreadable before unlock.
export function getSettings(db: Db): AppSettings {
const rows = db.prepare('SELECT key, value_json FROM settings').all() as Array<{
key: string
value_json: string
}>
const stored: Record<string, unknown> = {}
for (const r of rows) {
// Own settings keys only (#251): a `__proto__` row written by an older build would
// otherwise set `stored`'s prototype here and be parsed on every unlock.
if (!Object.hasOwn(DEFAULT_SETTINGS, r.key)) continue
try {
stored[r.key] = JSON.parse(r.value_json)
} catch {
/* ignore malformed rows */
}
}
// Validate the benchmark records BEFORE the merge (PR #303 audit H1/L8, owner decision G7).
// The rows above are parsed verbatim, so anything a `updateSettings` gate never saw — a row
// written by an older build, a hand-edited DB, a half-written blob — used to reach the
// startup fingerprinting, the first-benchmark decision, the #107 memo, Diagnostics and the
// Performance screen unchecked (a `{}` history entry crashed the screen in `fmt1`). The
// normalizers live in `shared/benchmark-schema.ts`, so main and renderer agree on what a
// trustworthy record is. This is an IN-MEMORY repair: a read never rewrites the DB (the
// stored row stays as it is until something legitimately writes that key), so `getSettings`
// keeps its no-side-effect contract on every hot path that calls it.
if ('lastBenchmark' in stored) stored.lastBenchmark = normalizeBenchmarkResult(stored.lastBenchmark)
if ('benchmarkHistory' in stored) stored.benchmarkHistory = normalizeBenchmarkHistory(stored.benchmarkHistory)
if ('modelPlacements' in stored) stored.modelPlacements = normalizeModelPlacements(stored.modelPlacements)
// The probe too (P5): the memory class, the VRAM budget and the graphics tile read it.
if ('gpuProbe' in stored) stored.gpuProbe = normalizeGpuProbe(stored.gpuProbe)
// Merge stored values over defaults so new fields always have a value.
return { ...DEFAULT_SETTINGS, ...(stored as Partial<AppSettings>) }
}
export function updateSettings(db: Db, patch: Partial<AppSettings>): AppSettings {
const now = new Date().toISOString()
const upsert = db.prepare(
`INSERT INTO settings (key, value_json, updated_at) VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at`
)
for (const [key, value] of Object.entries(patch)) {
if (value === undefined) continue
// The patch crosses the IPC boundary from the renderer: persist only KNOWN settings
// keys. `null` is accepted ONLY for keys whose default is null (that is how e.g. the
// active model is cleared) — anywhere else it would shadow a non-nullable default
// (`checksumCache: null` broke every checksum reader — BE-1, full-audit 2026-07-10).
// Non-null values must match the default's primitive type; the null-default keys carry
// no type information in DEFAULT_SETTINGS, so each gets an explicit shape check
// (bounded string / plain object; `contextTokensOverride` has its own clamp below, and the
// three benchmark-record keys are additionally VALIDATED field by field further down).
// Unknown/mistyped entries are dropped. OWN keys only (#251): `in` also matched
// inherited names, so a JSON.parse-built `{"__proto__": …}` patch persisted a junk row.
if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
const def = (DEFAULT_SETTINGS as unknown as Record<string, unknown>)[key]
if (value === null) {
if (def !== null) continue
} else if (def !== null) {
if (typeof value !== typeof def) continue
} else if (key === 'activeModelId' || key === 'activeEmbeddingModelId') {
if (typeof value !== 'string' || value.length > MAX_SETTINGS_ID_LENGTH) continue
} else if (key === 'gpuLastError') {
if (typeof value !== 'string' || value.length > MAX_SETTINGS_ERROR_LENGTH) continue
} else if (key === 'lastBenchmark' || key === 'gpuProbe') {
if (typeof value !== 'object' || Array.isArray(value)) continue
}
// Bound the object-valued settings (CODE-16, full-audit 2026-07-11). `checksumCache` has a
// non-null object default, so an ARRAY slips through the generic `typeof value !== typeof def`
// gate above (arrays report `object`) — reject it here; the null-default `lastBenchmark`/
// `gpuProbe` pair reject arrays above, so this re-check is harmless for them. The SERIALIZED
// size cap (SEC-1 bounding style, so a renderer can't bloat the encrypted blob these
// start-hot readers touch) is applied once, below, to every non-primitive write (#251).
// `value === null` (a legitimate clear of the null-default pair) is accepted upstream and
// never reaches here.
if (
(key === 'lastBenchmark' || key === 'gpuProbe' || key === 'checksumCache' || key === 'modelPlacements') &&
value !== null
) {
if (typeof value !== 'object' || Array.isArray(value)) continue
}
// Array-typed defaults (any future `string[]` setting) pass the
// `typeof === 'object'` check above, so validate them element-wise: require an actual
// array, keep only string elements, and cap the length (SEC-1) — mirroring the
// `safeIdArray`/`parseDocumentScope` pattern so a non-array/oversized renderer value is
// never persisted verbatim into the encrypted blob.
let toStore: unknown = value
// The three benchmark-record keys are VALIDATED, not just shape-checked (PR #303 audit
// H1/L8, owner decision G7): the old gate accepted any plain object, so `{}` was a valid
// history entry and `{ m: {} }` a valid placement map, and both reached readers that
// assume real figures. The normalizers (`shared/benchmark-schema.ts`) are the same ones
// `getSettings` applies on read, so a value that survives a write reads back unchanged.
// Garbage is IGNORED, never stored: a `lastBenchmark` that normalizes to nothing leaves
// the previous result in place (the convention every mistyped value here follows —
// `null` is still the explicit clear), while the two COLLECTIONS keep their existing
// element-wise semantics and store what survived, which for an all-junk payload is empty.
if (key === 'benchmarkHistory') {
// The one array-of-OBJECTS setting: valid results only (a junk element is dropped, never
// persisted), one per machine, newest first, capped at the per-machine history size. An
// UNKEYED entry is dropped too — the history is addressed by machine. The
// serialized-size cap below still applies to the whole list.
if (!Array.isArray(value)) continue
toStore = normalizeBenchmarkHistory(value)
} else if (key === 'modelPlacements') {
// Gated at the top level only until now (L8): `{ m: {} }` and `{ m: 'x' }` were stored
// and a `{}` record reached `placementVerdict`. Each record must validate AND be filed
// under its own model id.
toStore = normalizeModelPlacements(value)
} else if (key === 'lastBenchmark' && value !== null) {
const normalized = normalizeBenchmarkResult(value)
if (normalized == null) continue
toStore = normalized
} else if (key === 'gpuProbe' && value !== null) {
// P5: validated devices (junk items dropped), a parseable `probedAt`, and the machine
// stamp kept exactly as given — absent stays absent (an unstamped legacy probe is never
// re-stamped, G3). A value with no `devices` array is not a probe and is ignored.
const normalized = normalizeGpuProbe(value)
if (normalized == null) continue
toStore = normalized
} else if (Array.isArray(def)) {
if (!Array.isArray(value)) continue
toStore = (value as unknown[]).filter((x) => typeof x === 'string').slice(0, MAX_SETTINGS_ARRAY)
}
// The same serialized-size cap for EVERY non-primitive write (#251) — an array of long
// strings, or any future object-valued setting, must not bloat the blob either.
if (typeof toStore === 'object' && toStore !== null) {
if (JSON.stringify(toStore).length > MAX_SETTINGS_OBJECT_BYTES) continue
}
// Enum-valued keys get an exact-value check (a renderer bug must not persist junk
// like `gpuMode: 'banana'` — readers treat anything !== 'auto' as off, which fails
// safe, but junk must not be stored either).
// contextTokens floor: clamp UP a too-small value so the doc-task budget can never drop
// below a single summary's size (else the tree builder cannot reduce — HIGH_BUG). A
// non-finite value falls back to the floor rather than persisting NaN. #868: and clamp DOWN
// to the override's RAM-safety ceiling, which bounds the window this falls back to.
if (key === 'contextTokens') {
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : MIN_CONTEXT_TOKENS
toStore = Math.min(MAX_CONTEXT_TOKENS_OVERRIDE, Math.max(MIN_CONTEXT_TOKENS, n))
}
// #868: the four retrieval tuning keys (RETRIEVAL_TUNING_BOUNDS above).
if (Object.hasOwn(RETRIEVAL_TUNING_BOUNDS, key)) {
const bound = RETRIEVAL_TUNING_BOUNDS[key as keyof typeof RETRIEVAL_TUNING_BOUNDS]
if (typeof value !== 'number' || !Number.isFinite(value)) continue
toStore = Math.min(bound.max, Math.max(bound.min, bound.integer ? Math.floor(value) : value))
}
// contextTokensOverride: null = automatic (model default) and stores as-is. A number is
// clamped into [MIN_CONTEXT_TOKENS, MAX_CONTEXT_TOKENS_OVERRIDE] — the same tree-builder
// floor as contextTokens (the override becomes the doc-task window when it launches the
// runtime) plus a RAM-safety ceiling. The default is null, so the generic type check above
// passes ANY value for this key — reject non-numeric junk here instead of storing it.
if (key === 'contextTokensOverride' && value !== null) {
if (typeof value !== 'number' || !Number.isFinite(value)) continue
toStore = Math.min(MAX_CONTEXT_TOKENS_OVERRIDE, Math.max(MIN_CONTEXT_TOKENS, Math.floor(value)))
}
// localApiPort: clamp into the valid loopback-bind range (the booleans of the
// local-api trio validate for free via the generic type gate above). A non-finite
// number is DROPPED, not defaulted — clobbering a customized port back to 4980 would
// silently break every configured client (the contextTokensOverride convention).
if (key === 'localApiPort') {
if (typeof value !== 'number' || !Number.isFinite(value)) continue
toStore = Math.min(MAX_LOCAL_API_PORT, Math.max(MIN_LOCAL_API_PORT, Math.floor(value)))
}
if (key === 'gpuMode' && value !== 'auto' && value !== 'off') continue
// #858: the two modes a workspace can be in; anything else would make Settings misreport it.
if (key === 'workspaceMode' && value !== 'encrypted' && value !== 'plaintext_dev') continue
if (key === 'theme' && value !== 'system' && value !== 'light' && value !== 'dark') continue
// uiLanguage: 'system' or a language this build registers. The READ path stays tolerant on
// purpose: a value a newer build wrote (a shared drive) resolves like 'system' and its row
// is kept, so going back to that build still finds the choice (i18n record §3.2).
if (key === 'uiLanguage' && !isUiLanguageSetting(value)) continue
upsert.run(key, JSON.stringify(toStore), now)
}
return getSettings(db)
}
/** Seed defaults on first run (writes only when the table is empty; keys added in
* later versions are filled at read time by `getSettings`'s defaults merge). */
export function seedSettings(db: Db): AppSettings {
const existing = db.prepare('SELECT COUNT(*) AS n FROM settings').get() as { n: number }
if (existing.n === 0) {
return updateSettings(db, DEFAULT_SETTINGS)
}
return getSettings(db)
}