Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)*

---

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

---

Expand Down Expand Up @@ -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.*
5 changes: 4 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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)}}
Expand Down Expand Up @@ -324,7 +326,7 @@
<div style="margin-top:auto">
<a class="nav" data-view="settings">⚙️ Settings</a>
<div class="footer">
<div style="color:var(--text-3);font-size:11px">v1.9.2 · FinLens</div>
<div style="color:var(--text-3);font-size:11px">v1.9.3 · FinLens</div>
</div>
</div>
</aside>
Expand All @@ -351,6 +353,7 @@
<button class="btn ghost sm" id="themeToggle" title="Toggle theme">◐</button>
</div>

<div class="folder-banner-wrap" id="folderBanner" hidden></div>
<div class="content" id="content"></div>
</main>
</div>
Expand Down
41 changes: 39 additions & 2 deletions js/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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();
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
Expand Down
2 changes: 2 additions & 0 deletions js/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,7 @@
setRange('month');
buildAccountFilter();
showView('overview');
// Folder access lapsed (Chromium resets it on every load): offer Reconnect.
updateFolderBanner();

})();
2 changes: 2 additions & 0 deletions js/views-cleanup.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.' : ''));
}
Expand Down
Loading