[Bug] `loadPreferences()` is uncached and runs on every render: about 140 synchronous file reads per streamed turn
Description
loadPreferences() does readFileSync + JSON.parse on every call, and App calls it on every render: once in useAppState and twice through getPrivacyPreference(). The UI renders dozens of times per streamed answer, so each turn does a burst of synchronous disk reads on the event loop. On slow disks or with antivirus scanning every read, this shows up as stalls.
Environment
- OS: Windows 11 (10.0.26300)
- Node version: 22.22.3
- Nanocoder version: 1.31.0 (main at 5c2e6935)
Steps to Reproduce
- Preload a wrapper that counts
fs.readFileSynccalls fornanocoder-preferences.json(andagents.config.json). - Start
nanocoder, send 3 prompts that stream an answer, quit. - Read the counts.
Evidence
- 41 reads of
nanocoder-preferences.jsonduring startup alone, 463 in a session of 3 streamed turns. By call stack:useAppState136,getPrivacyPreferencein theAppbody 136 + 136 (136 App renders in 3 turns, about 45 per turn). - Call sites:
source/hooks/useAppState.tsx:52,source/app/App.tsx:350and:817,source/config/preferences.ts:82(loadPreferences) and:410(getPrivacyPreference). The versioned cache helpercachedPreference(around line 129) exists, butloadPreferencesitself is uncached. - Startup also reads
agents.config.json18 times and callsexistsSyncon it 39 times (config resolution repeats). - In a streaming-turn CPU profile
loadPreferencesaccounted for 0.47 s of self time over 8 turns (loaded host).
Proposed Change
- Cache the parsed result in
loadPreferences, keyed on the resolved path andpreferencesVersion(already bumped by everysavePreferences). To still see edits from another process, comparestatSync().mtimeMsinstead of re-reading. - In
useAppState, read once withuseState(() => loadPreferences())or a ref. - Apply the same memoization to the repeated
agents.config.jsonresolution at startup.
Expected Behavior
- At most 3 preference reads during startup and 0 during a streamed turn.
- Changing a setting in
/settingsstill takes effect immediately.
Additional Context
- Effort: S. Start with
source/config/preferences.ts,source/hooks/useAppState.tsx,source/app/App.tsx. - Risk: stale-cache bugs if a write path bypasses
savePreferences. Specs:source/config/preferences.spec.ts,useAppState.spec.tsx.
Hey @addyCooks, I'd like to work on this issue.
My approach would be to cache the parsed preferences using the resolved file path and preferencesVersion, with cache invalidation on saves and mtimeMs checks for external changes. I'll also avoid repeated preference reads during React renders and look into memoizing the agents.config.json resolution.
I'll add regression tests to ensure settings updates are reflected immediately and unnecessary disk reads are eliminated.