diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b962a5..9849570 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,33 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.9.3] — 2026-10-25 + +### Fixed +- **`finlens-state.json` stopped loading and saving after a page reload in Edge and Chrome.** + - **Symptoms:** at startup the console showed `[FinLens] File load error: … The request is not allowed by the user agent or the platform in the current context.`, and Settings → Import → **Save Now** showed no message, success or failure. + - **Cause:** + - Chromium browsers reset a stored folder's permission to "prompt" on every page load. + - `loadStateFromFile()` and `saveStateToFile()` never checked or re-requested it, so both threw `NotAllowedError`. + - The folder was only ever granted `read` access (folder picker, `reloadDataFiles()`), and writing the state file needs `readwrite`. + - **Save Now** ignored the result of `saveStateToFile()`, so a failure only reached `console.warn`. + - **Effect:** the app booted from IndexedDB (data was safe in the browser), but every automatic save failed silently, so `finlens-state.json` went stale. The bug was already on `master`. + - **Fix:** + - **Startup:** `loadStateFromFile()` checks access first with the new `folderPermission()` helper (never prompts). When access has lapsed it skips the file without an error and a **Backups paused** banner appears above every view with a **Reconnect folder** button. + - **Reconnect:** asks for `readwrite` (the click allows the prompt) and then writes this browser's data to `finlens-state.json`. The browser copy wins; the file is not loaded over it. If access is refused, the banner says so and keeps the button. + - **Save Now:** asks for `readwrite` when clicked, saves through `saveStateNow()`, and shows "Saved to finlens-state.json …" or why it failed (no folder, permission refused, or the write error). + - **Autosave:** `saveStateToFile()` skips quietly while access is missing, instead of throwing every 5 seconds, and shows the banner. The next successful save clears it. + - **Read-write everywhere:** the folder picker, **Reload** and **Reconnect Folder** in Settings → Import now ask for `readwrite` instead of `read`. + - **Status card:** Settings → Import → Auto-Backup says **Backup paused** while access is missing, instead of "Backup enabled". +- **An empty browser could overwrite the only backup.** Once saving works, picking or reconnecting a folder from a browser with no data (new browser, cleared site data) would have replaced a good `finlens-state.json` with an empty state. In that case FinLens now restores from the file, the same way boot does (`_restoreStateIfBrowserEmpty()`). +- **Data & Reset** now reports a failed state-file write as a failure, with the reason; `saveStateNow()` returns `'error'` for it instead of `'denied'`. +- **Reconnect respects a deliberate clear.** After *Clear transactions & accounts* (v1.9.0's `csvAutoImportPaused`), reconnecting neither re-imports the folder's CSVs nor restores `finlens-state.json` over the empty browser; it only turns backups back on. + +### Docs +- **CLAUDE.md §14** documents the folder-permission rules. + +--- + ## [1.9.2] — 2026-10-23 ### Docs diff --git a/CLAUDE.md b/CLAUDE.md index dc98f28..d6e2fb9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ Until then, this section is the rule. FinLens is a **single-origin, zero-build, vanilla JavaScript personal finance dashboard** that runs entirely in the browser. There is no server, no npm, no bundler, no framework, and no TypeScript. The entry point is `index.html`; everything else is a plain `.js` file in the `js/` folder. -**Current version:** v1.9.2 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.9.3 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). **What it does:** Imports CSV exports from Ally Bank (Checking + Savings) and Chase credit cards, parses and normalizes them into a unified transaction model, and renders a multi-tab financial dashboard with budgeting, debt tracking, savings forecasting, investment planning, and Claude-powered AI analysis. @@ -676,6 +676,14 @@ The old `FileStorage` object and `finlens-data.json` were removed in v1.4.1. The handle lives in a separate `finlens_fs` database (distinct from `finlens_db`), accessed through the lightweight `_idbOpen`/`idbGet`/`idbSet`/`idbDel` helpers in `core.js`. `finlens-state.json` is git-ignored by name, wherever the folder is. +### Folder permission (v1.9.3) + +- **It lapses on every page load in Chromium** (Edge, Chrome): a stored handle's permission goes back to `prompt`. Only a click can ask again — `requestPermission()` throws without user activation. +- **Check before touching files.** `loadStateFromFile()` and `saveStateToFile()` call `folderPermission(dir, mode)` (wraps `queryPermission`, never prompts) and skip quietly instead of throwing `NotAllowedError`. When access is missing they set `State._folderNeedsAccess`, which shows the **Reconnect folder** banner (`#folderBanner`, `updateFolderBanner()` in `views-data.js`). A successful save clears it. +- **Always ask for `readwrite`**, not `read`: the folder picker, Reload and Reconnect all do, because the same folder holds `finlens-state.json`. +- **Prompting code runs only in click handlers:** `saveNowClick()`, `reconnectFolderClick()`, `reloadDataFiles()`, and the Data & Reset actions via `folderWithWriteAccess()` / `saveStateNow()`. +- **After reconnecting, the browser copy wins** (Luis's decision, 2026-10-24): `reconnectDataFolder()` writes the browser's state to the file and does not load the file over it. **Exception:** a browser with no transactions (new browser, cleared site data) restores from the file instead (`_restoreStateIfBrowserEmpty()`), so an empty state never overwrites the only backup. Picking a folder follows the same rule. + --- ## 15. What NOT to Do @@ -777,7 +785,7 @@ Multiple Chase card files can be loaded simultaneously. Each gets a unique `acco --- -*Last updated: v1.9.2 — 2026-10-23 (§0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §20 Data & Reset added; v1.8.1: §10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* +*Last updated: v1.9.3 — 2026-10-25 (§14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §20 Data & Reset added; v1.8.1: §10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* --- diff --git a/README.md b/README.md index 999607b..9cf89d5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > A zero-install, browser-native finance dashboard. Drop in your bank CSVs, get instant clarity on your money. -**Version:** v1.9.2  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.9.3  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -235,4 +235,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.9.2 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.9.3 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index a0d4e02..eed0766 100644 --- a/index.html +++ b/index.html @@ -116,6 +116,8 @@ .acct-filter,.range-custom{border:1px solid var(--border);background:var(--surface);border-radius:9px;padding:6px 10px;font-size:12.5px;color:var(--text);} .content{padding:22px;display:flex;flex-direction:column;gap:18px} +.folder-banner-wrap{padding:16px 22px 0} +.folder-banner{display:flex;align-items:center;gap:12px;flex-wrap:wrap} section.view{display:none;flex-direction:column;gap:18px;animation:fade .25s ease} section.view.active{display:flex} @keyframes fade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}} @@ -324,7 +326,7 @@
⚙️ Settings
@@ -351,6 +353,7 @@ +
diff --git a/js/core.js b/js/core.js index 4251cde..b1a3daa 100644 --- a/js/core.js +++ b/js/core.js @@ -92,6 +92,15 @@ const downloadFile = (name, content, mime) => { }; /* ---------- Filesystem state persistence (source of truth) ---------- */ +// Chromium browsers (Edge, Chrome) reset a stored folder's permission to "prompt" on +// every page load, and only a click can ask for it again. So the file functions check +// first (queryPermission never prompts) instead of letting getFileHandle() throw +// NotAllowedError. When access has lapsed they set State._folderNeedsAccess, which +// shows the "Reconnect folder" banner (updateFolderBanner() in views-data.js). +async function folderPermission(dir, mode) { + try { return await dir.queryPermission({ mode }); } catch(e) { return 'denied'; } +} + // Load state from finlens-state.json in the backup folder async function loadStateFromFile() { try { @@ -100,6 +109,12 @@ async function loadStateFromFile() { console.log('[FinLens] No backup folder selected; skipping file load'); return null; } + // Saving needs read-write; without it backups are paused even if reading works. + if ((await folderPermission(dirHandle, 'readwrite')) !== 'granted') State._folderNeedsAccess = true; + if ((await folderPermission(dirHandle, 'read')) !== 'granted') { + console.log('[FinLens] Folder access needs to be renewed this session; loading from browser storage instead of finlens-state.json'); + return null; + } const fileHandle = await dirHandle.getFileHandle('finlens-state.json'); const file = await fileHandle.getFile(); const text = await file.text(); @@ -138,12 +153,24 @@ async function saveStateToFile(state) { // "Start over" sets this so a pending debounced save can't re-create the file // between the reset and the page reload. if (State._resetInProgress) return false; + State._lastSaveError = ''; try { const dirHandle = await idbGet('csvDirHandle'); if (!dirHandle) { console.log('[FinLens] No backup folder selected; state not saved to file'); return false; } + // No write access (lapsed on reload, or only read was ever granted): skip quietly + // and show the banner, rather than throwing on every debounced save. + if ((await folderPermission(dirHandle, 'readwrite')) !== 'granted') { + State._lastSaveError = 'no write access to the folder'; + if (!State._folderNeedsAccess) { + State._folderNeedsAccess = true; + console.log('[FinLens] Backups paused: no write access to the folder'); + if (typeof updateFolderBanner === 'function') updateFolderBanner(); + } + return false; + } const fileHandle = await dirHandle.getFileHandle('finlens-state.json', { create: true }); const writable = await fileHandle.createWritable(); // Serialize State, being careful with non-serializable properties. @@ -176,8 +203,13 @@ async function saveStateToFile(state) { await writable.close(); State.lastFsyncTime = new Date(); console.log('[FinLens] Auto-saved state to finlens-state.json'); + if (State._folderNeedsAccess) { + State._folderNeedsAccess = false; + if (typeof updateFolderBanner === 'function') updateFolderBanner(); + } return true; } catch(e) { + State._lastSaveError = e.message; console.warn('[FinLens] Failed to save state to file:', e.message); return false; } @@ -206,11 +238,14 @@ async function folderWithWriteAccess() { // Writes finlens-state.json right away, e.g. after clearing data, so the next page // load can't restore what was just cleared from an older file. -// Returns 'saved', 'no-folder' or 'denied'. +// Also used by Settings → Import → Save Now. Must be called from a click handler, +// since it may need to ask for read-write access. +// Returns 'saved', 'no-folder', 'denied' (access refused) or 'error' (the write +// itself failed; the reason is in State._lastSaveError). async function saveStateNow() { if (!(await idbGet('csvDirHandle'))) return 'no-folder'; if (!(await folderWithWriteAccess())) return 'denied'; - return (await saveStateToFile(State)) ? 'saved' : 'denied'; + return (await saveStateToFile(State)) ? 'saved' : 'error'; } // Used by "Start over": retires finlens-state.json so reconnecting the same folder @@ -255,7 +290,9 @@ async function forgetDataFolder() { await idbDel('csvDirHandle'); State.lastFolderName = ''; State._csvNeedsReconnect = false; + State._folderNeedsAccess = false; State.csvAutoImportPaused = false; + if (typeof updateFolderBanner === 'function') updateFolderBanner(); lsSet('lastFolderName', ''); lsSet('csvAutoImportPaused', false); } diff --git a/js/init.js b/js/init.js index c5e5ac1..7fd2fe9 100644 --- a/js/init.js +++ b/js/init.js @@ -132,5 +132,7 @@ setRange('month'); buildAccountFilter(); showView('overview'); + // Folder access lapsed (Chromium resets it on every load): offer Reconnect. + updateFolderBanner(); })(); diff --git a/js/views-cleanup.js b/js/views-cleanup.js index da2ef96..f5d2a26 100644 --- a/js/views-cleanup.js +++ b/js/views-cleanup.js @@ -140,6 +140,8 @@ const DataCleanup = { const file = await saveStateNow(); if (file === 'denied') { this._done('warn', `${text} But FinLens couldn't update finlens-state.json in “${State.lastFolderName}” (no write access), so reloading may bring the cleared data back. Allow access when asked, or disconnect the folder.`); + } else if (file === 'error') { + this._done('warn', `${text} But writing finlens-state.json in “${State.lastFolderName}” failed (${State._lastSaveError || 'unknown error'}), so reloading may bring the cleared data back.`); } else { this._done('good', text + (file === 'saved' ? ' Backup file updated.' : '')); } diff --git a/js/views-data.js b/js/views-data.js index 879d446..4163d05 100644 --- a/js/views-data.js +++ b/js/views-data.js @@ -11,6 +11,8 @@ let pendingFileObjects=[]; let _lastImportResults = []; // [{ filename, account, importResult }] let _importLogCache = []; // cached import log (refreshed on view render) let _coverageCache = {}; // cached coverage (refreshed on view render) +let _saveNowMsg = null; // { kind, text } — result of the last Save Now click +let _folderBannerMsg = null; // { kind, text } — result of the last Reconnect click registerView('import','Import',(root)=>{ @@ -24,10 +26,10 @@ registerView('import','Import',(root)=>{ ? `
📁 ${escapeHtml(State.lastFolderName)}
-
${State.transactions.length?'✓ '+State.transactions.length+' transactions loaded':(State.csvAutoImportPaused?'Transactions cleared — automatic import is paused. Click Reload to import again.':(needsReconnect?'⚠ Permission needed — click Reconnect':'No data loaded yet'))}
+
${State.transactions.length?'✓ '+State.transactions.length+' transactions loaded':(State.csvAutoImportPaused?(needsReconnect||State._folderNeedsAccess?'Transactions cleared — automatic import is paused. Reconnect turns backups back on without re-importing.':'Transactions cleared — automatic import is paused. Click Reload to import again.'):(needsReconnect?'⚠ Permission needed — click Reconnect':'No data loaded yet'))}
- ${needsReconnect - ? `` + ${needsReconnect||State._folderNeedsAccess + ? `` : ``}
` @@ -46,24 +48,29 @@ registerView('import','Import',(root)=>{ const backupCard=document.createElement('div'); backupCard.className='card'; const hasBackupFolder=!!State.lastFolderName; // Uses same folder as CSV files const lastSync=State.lastFsyncTime?dayjs(State.lastFsyncTime).format('MMM D, YYYY h:mm A'):'Never'; + const paused=!!State._folderNeedsAccess; + const saveMsg=_saveNowMsg; _saveNowMsg=null; // shown once, after the click that produced it backupCard.innerHTML=`

📦 Auto-Backup to Disk

Your dashboard state is automatically saved to finlens-state.json in your folder every 5 seconds (when you make changes). This survives browser cache clearing.

${hasBackupFolder - ? `
-
✓ Backup enabled
+ ? `
+
${paused?'⚠ Backup paused — FinLens needs permission to write to this folder again':'✓ Backup enabled'}
Folder: ${escapeHtml(State.lastFolderName)}
Last saved: ${lastSync}
- -
` + +
+ ${saveMsg?`
${escapeHtml(saveMsg.text)}
`:''}` : `
⚠ Backup disabled
Pick a folder above (under "Data Source") to enable automatic backups.
`} `; root.appendChild(backupCard); + const saveNowBtn=backupCard.querySelector('#saveNowBtn'); + if (saveNowBtn) saveNowBtn.onclick=saveNowClick; /* ---- Pending file assignment ---- */ if (pendingFileObjects.length) { @@ -350,11 +357,18 @@ async function importAssignedFiles() { async function pickDataFolder() { if ('showDirectoryPicker' in window) { try { - const handle = await window.showDirectoryPicker({ mode:'read', startIn:'documents' }); + // readwrite: the same folder holds finlens-state.json, which FinLens writes to. + const handle = await window.showDirectoryPicker({ mode:'readwrite', startIn:'documents' }); await idbSet('csvDirHandle', handle); State.lastFolderName = handle.name; + State._folderNeedsAccess = false; + State._csvNeedsReconnect = false; lsSet('lastFolderName', handle.name); - await reloadFromDirHandle(handle); + // A browser with no data of its own (new browser, cleared site data) must not + // overwrite the folder's backup: restore it instead, as boot does. + const restored = await _restoreStateIfBrowserEmpty(); + if (!restored || !State.transactions.length) await reloadFromDirHandle(handle); + updateFolderBanner(); return; } catch(e) { if (e.name !== 'AbortError') { console.error('pickDataFolder:', e); } @@ -395,15 +409,121 @@ async function reloadDataFiles() { const handle = await idbGet('csvDirHandle'); if (handle) { try { - let perm = await handle.queryPermission({ mode:'read' }); - if (perm !== 'granted') perm = await handle.requestPermission({ mode:'read' }); - if (perm === 'granted') { await reloadFromDirHandle(handle); return; } + // Ask for readwrite (not just read) so the reload also resumes backups. + if (await folderWithWriteAccess()) { + State._csvNeedsReconnect = false; + updateFolderBanner(); + await reloadFromDirHandle(handle); + return; + } + // Write refused but reading still allowed: reload anyway; backups stay paused. + if ((await folderPermission(handle, 'read')) === 'granted') { await reloadFromDirHandle(handle); return; } } catch(e) { /* permission revoked — fall through */ } } // No stored handle or permission denied — open picker await pickDataFolder(); } +/* ---- Folder access: Reconnect banner, Reconnect + Save Now click handlers ---- */ + +// When this browser has no data of its own (no transactions: a new browser, or site +// data cleared), the folder's finlens-state.json is the only copy. Load it, exactly as +// boot does, rather than letting the next save overwrite it with an empty state. +// Needs read access already granted. Returns true if state was restored. +async function _restoreStateIfBrowserEmpty() { + // After "Clear transactions & accounts" the browser is empty on purpose: keep it. + if (State.transactions.length || State.csvAutoImportPaused) return false; + const fsState = await loadStateFromFile(); + if (!fsState) return false; + Object.assign(State, fsState); + buildAccountFilter(); + renderActive(); + console.log('[FinLens] Browser had no data; restored', State.transactions.length, 'transactions from finlens-state.json'); + return true; +} + +// Click handler (banner + Import tab). Asks for read-write access to the stored folder. +// Decision (Luis, 2026-10-24): after reconnecting, the browser copy wins. It overwrites +// finlens-state.json; the file is not loaded over the browser data. The one exception +// is a browser with no data at all (see _restoreStateIfBrowserEmpty). +// Returns 'saved' | 'restored' | 'no-folder' | 'denied' | 'error'. +async function reconnectDataFolder() { + const dir = await idbGet('csvDirHandle'); + if (!dir) return 'no-folder'; + if (!(await folderWithWriteAccess())) return 'denied'; + State._folderNeedsAccess = false; + let restored = false; + if (!State.transactions.length) { + restored = await _restoreStateIfBrowserEmpty(); + // Boot skipped the CSV auto-import for lack of access; do it now, unless the user + // cleared their transactions on purpose (Data & Reset) and import is paused. + if (!State.transactions.length && !State.csvAutoImportPaused) await reloadFromDirHandle(dir); + } + State._csvNeedsReconnect = false; + if (restored) return 'restored'; + return (await saveStateToFile(State)) ? 'saved' : 'error'; +} + +async function reconnectFolderClick() { + $$('[data-reconnect-btn]').forEach(b => { b.disabled = true; }); + const r = await reconnectDataFolder(); + const name = State.lastFolderName || 'your folder'; + _folderBannerMsg = { + saved: { kind:'good', text:`Reconnected to “${name}”. This browser's data was saved to finlens-state.json, and backups are back on.` }, + restored: { kind:'good', text:`Reconnected to “${name}”. This browser had no data, so it was restored from finlens-state.json.` }, + 'no-folder':{ kind:'warn', text:'No folder is connected. Pick one in Settings → Import.' }, + denied: { kind:'bad', text:`Access to “${name}” wasn't granted, so backups are still paused. Click Reconnect folder and choose Allow. If no prompt appears, file access for this site is blocked in your browser's site settings.` }, + error: { kind:'bad', text:`Reconnected, but saving finlens-state.json failed: ${State._lastSaveError || 'unknown error'}.` }, + }[r]; + updateFolderBanner(); + renderActive(); + if (_folderBannerMsg && _folderBannerMsg.kind === 'good') { + const shown = _folderBannerMsg; + setTimeout(() => { if (_folderBannerMsg === shown) { _folderBannerMsg = null; updateFolderBanner(); } }, 8000); + } +} + +// Settings → Import → Save Now. Asks for read-write access if needed (the click +// allows the prompt), saves right away, and reports the outcome either way. +async function saveNowClick() { + const btn = $('#saveNowBtn'); + if (btn) btn.disabled = true; + const r = await saveStateNow(); + const name = State.lastFolderName || 'your folder'; + _saveNowMsg = { + saved: { kind:'good', text:`Saved to finlens-state.json in “${name}” at ${dayjs().format('h:mm A')}.` }, + 'no-folder':{ kind:'warn', text:'Not saved: no folder is connected. Pick one under Data Source first.' }, + denied: { kind:'bad', text:`Not saved: FinLens doesn't have permission to write to “${name}”. Click Save Now again and choose Allow. If no prompt appears, file access for this site is blocked in your browser's site settings.` }, + error: { kind:'bad', text:`Not saved: ${State._lastSaveError || 'unknown error'}.` }, + }[r]; + renderActive(); +} + +// The banner above every view (#folderBanner in index.html). Shown while access to +// the stored folder has lapsed, and briefly after a Reconnect click with its result. +function updateFolderBanner() { + const el = $('#folderBanner'); + if (!el) return; + const msg = _folderBannerMsg; + const needs = !!State._folderNeedsAccess; + if (!needs && !msg) { el.hidden = true; el.innerHTML = ''; return; } + const name = escapeHtml(State.lastFolderName || 'your folder'); + const body = needs + ? `Backups paused. FinLens needs your permission again to use “${name}”, so changes aren't being saved to finlens-state.json. Your data is safe in this browser.` + : ''; + const kind = msg ? msg.kind : 'warn'; + el.hidden = false; + el.innerHTML = `
+
${msg ? escapeHtml(msg.text) : body}
+ ${needs ? `` : ''} + ${!needs ? `` : ''} +
`; + const rb = el.querySelector('[data-reconnect-btn]'); + if (rb) rb.onclick = reconnectFolderClick; + const cb = el.querySelector('[data-banner-close]'); + if (cb) cb.onclick = () => { _folderBannerMsg = null; updateFolderBanner(); }; +} + function addManualAccount() { const name=$('#newAcctName').value.trim(); const kind=$('#newAcctKind').value; diff --git a/js/views-settings.js b/js/views-settings.js index 8fa7575..fe5e875 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -49,7 +49,7 @@ function _renderGeneralSettings(root) { -
FinLens v1.9.2 ·${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
`; +
FinLens v1.9.3 ·${State.transactions.length} transactions loaded${State.lastRefresh?' · Refreshed '+dayjs(State.lastRefresh).format('MMM D, YYYY h:mm A'):''}
`; root.appendChild(displayCard); /* ---- Anthropic API Key ---- */