Skip to content

fix(dashboard): route remaining raw Web Storage writes through safeStorage - #11752

Merged
iamwhatever merged 2 commits into
kirodotdev:mainfrom
DeryFerd:fix/dashboard-safe-storage-adoption
Sep 18, 2026
Merged

iamwhatever merged 2 commits into
kirodotdev:mainfrom
DeryFerd:fix/dashboard-safe-storage-adoption

Conversation

@DeryFerd

@DeryFerd DeryFerd commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

website/src/utils/safeStorage.ts exists because the dashboard's per-origin localStorage quota fills up in normal use. Its own header names the offenders: the per-session virtualizer height caches (vc_heights_<sid>, up to 2000 entries each) pile up across every chat session ever opened and are never reclaimed, and the mc-paste-store-v1 sent-paste side table can reach several MB on its own. Once the origin is full, the next localStorage.setItem anywhere in the app throws QuotaExceededError.

The helper handles exactly that. On a quota error it drops one tier of disposable cache and retries, escalating a tier at a time until the write succeeds or there is nothing reclaimable left. A raw setItem in the same situation throws instead, and the throw lands wherever the write happened to be called from.

The visible half-migration was in dashboardSlice.ts. That file adopted safeSetItem for mc-unread-slots and left the adjacent mc-unread-shared record written raw, two lines apart in the same function:

localStorage.setItem('mc-unread-shared', JSON.stringify(stored))
// ...
safeSetItem('mc-unread-slots', JSON.stringify(Object.keys(stored)))

Five files were in that state, all of them already importing the helper: store/dashboardSlice.ts, pages/ChatPage.tsx, pages/SchedulePage.tsx, components/WebPreviewPanel.tsx, and components/MarkdownPanel.tsx.

Why it matters

Nothing looks broken when this happens, which is what makes it easy to miss. safeStorage.ts states the mechanism in its header: a quota error raised on the websocket onmessage → Redux dispatch → re-render path bubbles out of an event handler or a commit phase, which a React ErrorBoundary cannot catch, and it white-screens the whole app. That is why the module was written in the first place.

Even when the app survives, the data is lost for no reason. Every one of these sites writes inside a swallow-only try/catch, so a full quota silently drops the write while megabytes of re-derivable cache sit right next to it, reclaimable. dashboardSlice.ts is the clearest case: the unread record is what the sidebar badge and the cross-window read relay are built on, and it was the one key in the function not going through the helper that exists to protect it.

There is a slower cost too. A file that imports a hardening helper and then writes raw around it teaches the next reader that the helper is optional. The mc-unread-shared line sat one statement away from the safeSetItem call that would have fixed it, which is how a half-finished migration survives review.

What changed (motivation → approach → change)

The symptom is a quota error escaping on the dispatch path. The root cause is that the write does not go through the helper that already exists for it. The change routes those writes through safeSetItem / safeSetSessionItem so a full quota reclaims and retries instead of throwing.

I scoped this to files that already import safeStorage, on purpose. That makes the PR read as "finish the migration you started" rather than a repo-wide sweep, and it keeps the diff small enough to review in one pass. There are 47 more raw setItem calls elsewhere in src/, in files with no helper import; those are a separate conversation about whether each one wants the reclaim behavior or is a throwaway marker where it does not matter. Leaving them out is deliberate, not an oversight.

Three of the sites needed more than a mechanical swap, and all three are worth a reviewer's attention.

The git-panel auto-open guard in ChatPage.tsx used the throw as control flow:

try { localStorage.setItem(key, '1') } catch { return }

That guard exists because opening the panel changes tabsCtl, which re-runs the effect, and an absent marker would make it open again forever. The helper reports whether the write landed instead of throwing, so the guard became if (!safeSetItem(key, '1')) return. The failure path is preserved exactly: if the marker cannot be persisted, the open is still skipped. What changes is that a quota the helper can reclaim from no longer suppresses the open, which is the point of the fix.

WebPreviewPanel.tsx needed a different kind of care. Its saveAnnotateMirrors did both the write and the delete inside one try. The write moved to safeSetSessionItem; the delete stayed a plain removeItem with its own guard, because removing a key frees space rather than needing it, so it is not the quota failure mode this PR is about. Splitting them keeps the exemption visible rather than hiding it inside a shared catch.

The shared unread record in dashboardSlice.ts is the third, and it is the one a plain conversion gets wrong. Converting a throwing call is not a drop-in swap when work follows it in the same try: the raw setItem threw on a full quota, the surrounding catch swallowed it, and the projection write below never ran. safeSetItem reports the same failure by returning false instead, so execution continued, and mc-unread-slots is a projection of the record's keys and strictly smaller than it, so on a quota it can free space and succeed where the record just failed. That leaves two persisted records that disagree, and restoreUnreadSince trusts the record while older tabs and the hub relay read the projection. The fix bails out when the authoritative write fails, restoring what the throw used to guarantee.

The regression guard is the part that outlives this PR. safeStorage.adoptionChokepoint.test.ts scans the source and fails if a file that imports safeStorage also writes raw. Reads and removeItem are out of scope; this is about the write that throws. There is no exemption marker: every file in scope writes through the helper today, so an escape hatch would be a convention with no consumer. It follows the shape of the existing dashboardSlice.rowWriterChokepoint.test.ts, which pins the same kind of rule on the row-write chokepoint: the rule is enforced where it can be read, not left to a reviewer noticing an omission.

Backwards compatibility

Compatible. Nothing that main currently accepts stops working.

Two behavior notes, both widenings rather than tightenings. The ChatPage.tsx git-panel guard now proceeds with the auto-open when the marker write succeeds after reclaiming space, where the old code skipped it; it still skips when the write genuinely fails. The sessionStorage writes in MarkdownPanel.tsx and WebPreviewPanel.tsx now swallow a quota or SecurityError inside the helper instead of inside a local try, which is the same outcome for the caller.

No public API, config key, or persisted format changes. The storage keys and their JSON shapes are untouched.

Tests

  • website/src/test/dashboardSlice.test.ts gains a quota-reclaim case. It seeds a disposable vc_heights_* entry, makes Storage.prototype.setItem throw QuotaExceededError only while that entry is present, dispatches a markSlotUnread arrival, and asserts the shared record persisted and the disposable entry was the thing sacrificed. I wrote it first and watched it fail with expected {} to deeply equal { 'chat-1': '2026-01-01T00:00:00Z' } — the record silently empty — then made it pass. It fails again on any future revert to a raw write at that site.
  • A second case in the same file covers the projection split: it makes the record write fail while the projection write still succeeds, and asserts the projection is left untouched. It fails on the unguarded form with expected [ 'chat-1' ] to deeply equal [ 'chat-1', 'chat-2', 'chat-3' ].
  • website/src/test/safeStorage.adoptionChokepoint.test.ts is new. It pins the rule on the source, and it also asserts its own matchers still work, so it cannot pass vacuously if the regex stops matching.
  • On the touched surfaces (safeStorage, dashboardSlice, the new chokepoint guard, slotReadRelay, ChatPage.gitPanelGate): 116 tests pass across 5 files, three consecutive runs, no flakes.
  • npx jscpd . reports 0 clones, which matters here because the pretest hook runs the duplication gate before any test does.
  • npx eslint on all seven changed files is clean.
  • npx tsc -b reports 78 errors on this box, and 78 with the change applied — zero added. The remainder are pre-existing missing optional deps (html-to-image, lexical) that fail identically on a stashed baseline.

Manual verification

N/A — unit coverage is sufficient here. The behavior under test is "does the write survive a quota error," which is decided entirely in the helper and is directly observable in the test above; no rendering or integration path is involved.

One thing worth eyeballing if a reviewer wants to, since the tests cannot show it: with the dashboard open, fill the origin by opening enough chat sessions that the height caches accumulate, then mark a session unread. Before this change the badge would fail to persist across a reload once the quota was hit; after it, the disposable cache is dropped and the badge survives.

Related Issues

No dedicated issue for these call sites. #10678 is the same class of fix for treeExpansionMemory.ts and is still open, which is useful evidence that the pattern is wanted rather than an argument against this PR.

Screenshots / video

Why no screenshot: every site keeps its rendered output identical in the normal case; the only difference appears when the origin quota is already full, where a write now succeeds instead of being dropped, so there is no visual delta to capture. Every site in this PR keeps its rendered output identical in the normal case; the difference only shows up when the origin quota is already full, where the write now succeeds instead of being dropped. The manual steps above reproduce that state if a reviewer wants to see it, but a screenshot of a badge that persists is not distinguishable from a screenshot of a badge that was never at risk.

Pattern harvest

Rule candidate: review-prompt

Pattern: a file that imports a shared hardening helper still calls the raw primitive it wraps, for a neighbouring key in the same function.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable) — N/A: no doc describes these call sites, and safeStorage.ts's own header already states the contract this PR enforces
  • No secrets, credentials, or internal references in the diff

@DeryFerd
DeryFerd requested review from a team and bolichen97 September 18, 2026 09:14
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Sep 18, 2026
@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5, fork) — ✅ PASS

UX-level review of a6ee0b6b0858a20cb3baded4de9b47fb5220301d via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: PASS

Nothing to check.

[UX-REVIEWED] a6ee0b6

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — ✅ PASS

Design-level review of a6ee0b6b0858a20cb3baded4de9b47fb5220301d via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Nothing to check.

[DESIGN-REVIEWED] a6ee0b6

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings

Reviewed a6ee0b6b0858a20cb3baded4de9b47fb5220301d via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] a6ee0b6

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5, fork) — ✅ PASS

Premise-level review of a6ee0b6b0858a20cb3baded4de9b47fb5220301d via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

One behavior widening to eye: the git-panel auto-open now fires after a quota reclaim the old code suppressed — confirm that re-open loop stays closed (gitPanelAutoOpen.test.ts covers the marker path).

What this change ships

Inventory (10 items) — 10 justified

Intent: FIX — stop a full localStorage quota from white-screening the app or silently dropping the unread record, by finishing the half-done migration onto the existing safeStorage helper (whose base header documents exactly this failure and this migration plan). All five touched files already import the helper on base; the 47 raw writes in non-importing files are counted, declared, and deliberately deferred by the description.

  1. Sidebar unread record survives a full quota by reclaiming disposable cache and retrying — justified
  2. When the record write still fails, the projection is left untouched so the two persisted unread stores cannot disagree — justified
  3. Per-tab manual reminder write goes through the session helper (same swallow, one spelling) — justified
  4. Legacy unread-slots migration write reclaims on quota — justified
  5. Web-preview applied marker write reclaims on quota — justified
  6. Git-panel auto-open proceeds when the marker persists after reclaim; still skipped on genuine failure, preserving the old pin's re-open guard — justified
  7. Schedule template-update dismissal persists through reclaim — justified
  8. Annotate-mirror write routes through the helper; the delete keeps its own guard, exemption stated in place — justified
  9. Composer draft mirror write routes through the helper — justified
  10. New source-scan test pins "an importer never writes raw" — justified (fixes the named cause: the omission a reviewer cannot see; no duplicate — grepped AUTOSDE.yaml and eslint.config.js, no existing storage-write rule)

[FIRST-PRINCIPLES-REVIEWED] a6ee0b6

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

Reviewed a6ee0b6b0858a20cb3baded4de9b47fb5220301d via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] a6ee0b6

…orage

A QuotaExceededError from `localStorage.setItem` on the websocket
onmessage -> dispatch -> re-render path bubbles out of an event handler,
which a React ErrorBoundary cannot catch, and white-screens the app.
`src/utils/safeStorage.ts` exists for exactly this: on a quota error it
reclaims one tier of disposable cache and retries, escalating a tier at a
time, so the write survives instead of being dropped beside reclaimable
cache.

Seven files already imported the helper but still wrote raw, and
`dashboardSlice.ts` was the visible half-migration: it adopted
`safeSetItem` for `mc-unread-slots` while writing the adjacent
`mc-unread-shared` record raw inside a swallow-only catch. This finishes
the migration for every file that already imports the module.

- dashboardSlice: the shared unread record, the per-tab sentinel mirror,
  and the legacy-migration write now go through the helper.
- ChatPage: the webpreview marker, and the git-panel auto-open guard.
  The guard keeps its semantics — it still skips the open when the
  marker cannot persist, but now reads that from the helper's return
  value rather than a caught throw, so a reclaimable quota no longer
  suppresses the open.
- SchedulePage, WebPreviewPanel, MarkdownPanel: the dismiss marker and
  the two sessionStorage mirrors.

`safeStorage.adoptionChokepoint.test.ts` pins the rule on the source: a
file that imports the module may not write raw, with a
`// raw-storage-ok: <why>` marker for a deliberate exemption. Reads and
removeItem stay out of scope; this is about the write that throws.

Tests: a quota-reclaim case in `dashboardSlice.test.ts` fails on the old
code with the record silently empty and passes with it, plus the
chokepoint guard. `npx vitest run` on the touched surfaces is green;
`jscpd` reports 0 clones; eslint clean on all changed files. The
remaining suite failures on this box (missing optional deps
`html-to-image` / `lexical`, and the app-registry/nav-label files) are
pre-existing and reproduce identically on a stashed baseline.
…d write

Converting a throwing `localStorage.setItem` to `safeSetItem` is not a
drop-in swap when the call sits in a `try` body with work after it. The
raw call threw on a full quota, the surrounding catch swallowed it, and
the next statement never ran. The helper reports the same failure by
returning false instead, so execution continued into the projection write.

That matters here because `mc-unread-slots` is a projection of the shared
record's keys and is strictly smaller than it (keys only, no timestamps).
On a quota it can free space and succeed where the record just failed,
leaving two persisted records that disagree: `restoreUnreadSince` trusts
the record, while older tabs and the hub relay read the projection.

Bail out when the authoritative write fails, restoring the protection the
throw used to provide. The regression test fails on the unguarded form
with `expected [ 'chat-1' ] to deeply equal [ 'chat-1', 'chat-2',
'chat-3' ]`.

Also drops the `// raw-storage-ok:` exemption from the new guard. It had
zero consumers — every file in scope writes through the helper — so the
escape hatch was a convention supported only by symmetry with the
row-write guard's exercised marker. The first real exemption can add it
back alongside its reason.

Tests: dashboardSlice 51/51, the touched surfaces 116/116 across 5 files,
eslint clean, jscpd 0 clones, tsc unchanged at the 78 pre-existing
errors.
@DeryFerd
DeryFerd force-pushed the fix/dashboard-safe-storage-adoption branch from 837e186 to a6ee0b6 Compare September 18, 2026 10:29
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 18, 2026
@DeryFerd DeryFerd changed the title fix(dashboard): route remaining raw Web Storage writes through safeSt… fix(dashboard): route remaining raw Web Storage writes through safeStorage Sep 18, 2026
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Sep 18, 2026

@iamwhatever iamwhatever left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved after a full read of the diff on the current head: the change matches the body and linked issue, every load-bearing claim was spot-checked against main, the failure paths were traced and fail safe, tests pin the behaviour, and every review-lane item on this head is either PASS or disposed.

@iamwhatever
iamwhatever enabled auto-merge (squash) September 18, 2026 21:23
@iamwhatever
iamwhatever merged commit 40e660b into kirodotdev:main Sep 18, 2026
98 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 18, 2026
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…orage (kirodotdev#11752)

* fix(dashboard): route remaining raw Web Storage writes through safeStorage

A QuotaExceededError from `localStorage.setItem` on the websocket
onmessage -> dispatch -> re-render path bubbles out of an event handler,
which a React ErrorBoundary cannot catch, and white-screens the app.
`src/utils/safeStorage.ts` exists for exactly this: on a quota error it
reclaims one tier of disposable cache and retries, escalating a tier at a
time, so the write survives instead of being dropped beside reclaimable
cache.

Seven files already imported the helper but still wrote raw, and
`dashboardSlice.ts` was the visible half-migration: it adopted
`safeSetItem` for `mc-unread-slots` while writing the adjacent
`mc-unread-shared` record raw inside a swallow-only catch. This finishes
the migration for every file that already imports the module.

- dashboardSlice: the shared unread record, the per-tab sentinel mirror,
  and the legacy-migration write now go through the helper.
- ChatPage: the webpreview marker, and the git-panel auto-open guard.
  The guard keeps its semantics — it still skips the open when the
  marker cannot persist, but now reads that from the helper's return
  value rather than a caught throw, so a reclaimable quota no longer
  suppresses the open.
- SchedulePage, WebPreviewPanel, MarkdownPanel: the dismiss marker and
  the two sessionStorage mirrors.

`safeStorage.adoptionChokepoint.test.ts` pins the rule on the source: a
file that imports the module may not write raw, with a
`// raw-storage-ok: <why>` marker for a deliberate exemption. Reads and
removeItem stay out of scope; this is about the write that throws.

Tests: a quota-reclaim case in `dashboardSlice.test.ts` fails on the old
code with the record silently empty and passes with it, plus the
chokepoint guard. `npx vitest run` on the touched surfaces is green;
`jscpd` reports 0 clones; eslint clean on all changed files. The
remaining suite failures on this box (missing optional deps
`html-to-image` / `lexical`, and the app-registry/nav-label files) are
pre-existing and reproduce identically on a stashed baseline.

* fix(dashboard): stop the projection write after a failed shared-record write

Converting a throwing `localStorage.setItem` to `safeSetItem` is not a
drop-in swap when the call sits in a `try` body with work after it. The
raw call threw on a full quota, the surrounding catch swallowed it, and
the next statement never ran. The helper reports the same failure by
returning false instead, so execution continued into the projection write.

That matters here because `mc-unread-slots` is a projection of the shared
record's keys and is strictly smaller than it (keys only, no timestamps).
On a quota it can free space and succeed where the record just failed,
leaving two persisted records that disagree: `restoreUnreadSince` trusts
the record, while older tabs and the hub relay read the projection.

Bail out when the authoritative write fails, restoring the protection the
throw used to provide. The regression test fails on the unguarded form
with `expected [ 'chat-1' ] to deeply equal [ 'chat-1', 'chat-2',
'chat-3' ]`.

Also drops the `// raw-storage-ok:` exemption from the new guard. It had
zero consumers — every file in scope writes through the helper — so the
escape hatch was a convention supported only by symmetry with the
row-write guard's exercised marker. The first real exemption can add it
back alongside its reason.

Tests: dashboardSlice 51/51, the touched surfaces 116/116 across 5 files,
eslint clean, jscpd 0 clones, tsc unchanged at the 78 pre-existing
errors.

---------

Co-authored-by: DeryFerd <DeryFerd@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants