Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: surface and recover Quota Burn edits lost by a failed dismount flush save (#3933)

[._.]/ Adam Eivy7704d0abf206
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 649cfba838..55c0453c70 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -77,3 +77,4 @@
- Exporting a catalog slice no longer issues three database queries per ingredient. `exportSliceForRef` hydrated scraps, refs and media one ingredient at a time, so a universe holding 100 ingredients cost 300 round-trips and pinned the connection pool for the length of the export. The three lookups are now batched with `WHERE ingredient_id = ANY($1)` and grouped in memory (`listScrapsForIngredients` / `listRefsForIngredients` / `listMediaForIngredients`, sharing `groupRowsByIngredient`), so one slice costs four queries regardless of how many ingredients it holds. The per-ingredient helpers stay on the same names and shapes — they now delegate to the batched query — and the exported payload, its ordering (scraps oldest-first, portraits ahead of other media) and its empty-array handling are unchanged.
- A failed job-skill save in the Prompt Manager no longer looks like a successful one. `saveJobSkill` sent the PUT with `{ silent: true }` and an empty `.catch(() => {})`, so a network blip, an auth failure, or a 500 dropped the edit on the floor while the Save button simply re-enabled — the exact shape of a save that worked. The failure now raises a toast naming the cause, a successful save confirms itself ("Job skill saved"), and the Preview button on the same panel likewise reports a failed render instead of leaving the preview panel blank with no explanation.
- Saving a universe no longer issues one database read per canon entry. `projectToCatalog` — which runs synchronously inside `updateUniverse` to keep each catalog row in step with its embedded character/place/object entry — called `getIngredient` once per entry just to compare timestamps, so a universe with 50 canon items cost 50 single-row `SELECT`s before the first write, on the request the user is waiting on. The freshness lookup is now a single batched query (`getIngredientTimestamps`, `WHERE id = ANY($1)`, two columns rather than the whole jsonb row), with the loop-break guard applied before the batch so a guarded ingredient is never fetched at all. The LWW rule is unchanged (an entry at least as fresh as its row wins; an older one is skipped), missing rows still count as skipped instead of being confused with stale ones, and a per-entry write failure is still logged and skipped without aborting the rest of the pass.
+- Unsaved Quota Burn edits are no longer lost silently when you navigate away. The page has no Save button — edits persist on a 500ms trailing edge — and the dismount flush that catches everything typed inside that window swallowed its own failure with `.catch(() => {})`, so leaving the page while the header still read "Saving changes…" dropped a pasted work prompt or a changed interval for good, with no toast and nothing on screen having said so. A failed flush now raises an error toast naming what happened and keeps the patch in tab-scoped `sessionStorage`; the next visit that successfully reads a plan replays it through the normal save path, so the edits come back on screen AND get re-sent to the server instead of waiting for the user to retype the field. A visit whose own read failed leaves the stash alone for the visit after it, and a stash that is not a patch object is ignored rather than replayed into a 400.
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9a46ff6ce6..e50d1c1710 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -114,7 +114,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
-| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useCitySettings`, `useNavWorkingSet`, and the command palette. |
+| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useCitySettings`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
| `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). |
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
diff --git a/client/src/lib/safeStorage.js b/client/src/lib/safeStorage.js
index f68f77e442..23521a34bb 100644
--- a/client/src/lib/safeStorage.js
+++ b/client/src/lib/safeStorage.js
@@ -56,3 +56,36 @@ export const safeRemoveStorage = (key) => {
// Ignore — nothing persisted to remove when storage is unavailable.
}
};
+
+// `sessionStorage` variants, same guarantees. Session scope is for state that
+// should survive a navigation or a reload but must NOT outlive the tab —
+// crash-recovery buffers for edits the server has not accepted yet. Persisting
+// those to `localStorage` would resurrect them weeks later, on top of whatever
+// the record holds by then.
+export const safeReadJsonSession = (key, fallback = null) => {
+ try {
+ const raw = globalThis.sessionStorage?.getItem(key) ?? null;
+ if (raw === null) return fallback;
+ return JSON.parse(raw);
+ } catch {
+ return fallback;
+ }
+};
+
+// Best-effort JSON write. Serialization is inside the guard for the same reason
+// as `safeWriteJsonStorage` — `JSON.stringify` throws on circular/BigInt values.
+export const safeWriteJsonSession = (key, value) => {
+ try {
+ globalThis.sessionStorage?.setItem(key, JSON.stringify(value));
+ } catch {
+ // Ignore — the value stays in memory when persistence is unavailable.
+ }
+};
+
+export const safeRemoveSession = (key) => {
+ try {
+ globalThis.sessionStorage?.removeItem(key);
+ } catch {
+ // Ignore — nothing persisted to remove when storage is unavailable.
+ }
+};
diff --git a/client/src/lib/safeStorage.test.js b/client/src/lib/safeStorage.test.js
index e579eda7d3..0f944dfec5 100644
--- a/client/src/lib/safeStorage.test.js
+++ b/client/src/lib/safeStorage.test.js
@@ -1,9 +1,13 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
-import { safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeWriteJsonStorage, safeRemoveStorage } from './safeStorage.js';
+import {
+ safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeWriteJsonStorage, safeRemoveStorage,
+ safeReadJsonSession, safeWriteJsonSession, safeRemoveSession,
+} from './safeStorage.js';
afterEach(() => {
vi.restoreAllMocks();
window.localStorage.clear();
+ window.sessionStorage.clear();
});
describe('safeStorage', () => {
@@ -56,4 +60,32 @@ describe('safeStorage', () => {
expect(() => safeWriteStorage('k', 'v')).not.toThrow();
expect(() => safeRemoveStorage('k')).not.toThrow();
});
+
+ it('round-trips session JSON without touching localStorage', () => {
+ safeWriteJsonSession('draft', { a: 1 });
+ expect(safeReadJsonSession('draft')).toEqual({ a: 1 });
+ // Session scope is the point: the same key must not have been persisted
+ // where it would outlive the tab.
+ expect(safeReadStorage('draft')).toBeNull();
+ safeRemoveSession('draft');
+ expect(safeReadJsonSession('draft', 'fallback')).toBe('fallback');
+ });
+
+ it('falls back on corrupt session JSON', () => {
+ window.sessionStorage.setItem('corrupt', '{not-json');
+ expect(safeReadJsonSession('corrupt', 'fallback')).toBe('fallback');
+ expect(safeReadJsonSession('missing', 'fallback')).toBe('fallback');
+ });
+
+ it('swallows a session storage that throws on every access', () => {
+ // Blocked storage (Safari private mode, a sandboxed iframe) throws from the
+ // accessor itself, so the whole call has to be inside the guard.
+ const boom = () => { throw new DOMException('The operation is insecure.', 'SecurityError'); };
+ vi.stubGlobal('sessionStorage', { getItem: boom, setItem: boom, removeItem: boom });
+
+ expect(() => safeWriteJsonSession('k', { a: 1 })).not.toThrow();
+ expect(safeReadJsonSession('k', 'fallback')).toBe('fallback');
+ expect(() => safeRemoveSession('k')).not.toThrow();
+ vi.unstubAllGlobals();
+ });
});
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index 761fbab7ef..bf19ed6cec 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -24,6 +24,7 @@ import { NumberField } from '../components/quotaBurn/fields';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';
+import { safeReadJsonSession, safeRemoveSession, safeWriteJsonSession } from '../lib/safeStorage';
import { coalesce } from '../utils/coalesce';
import { timeAgo } from '../utils/formatters';
@@ -38,6 +39,20 @@ const PENDING_POLL_MS = 4000;
const EMPTY_CATALOG = { jobTypes: [], apps: [], universes: [], imageModes: [] };
+// Where a patch the server never accepted waits for the next visit. Session
+// scope, not local: this is a crash buffer for the current tab, and a patch
+// resurrected days later would be applied on top of a config it no longer
+// describes.
+const UNSAVED_PATCH_KEY = 'quotaBurn:unsavedPatch';
+
+// A stash written by an older build (or hand-edited) must not be replayed as a
+// patch — the PUT body is an object, and anything else would 400 the save the
+// restore is supposed to rescue.
+const readStashedPatch = () => {
+ const stored = safeReadJsonSession(UNSAVED_PATCH_KEY);
+ return stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : null;
+};
+
// Distinguishes a read that THREW from one that resolved with nothing — the
// two need opposite handling of the error state, and both are falsy.
const READ_FAILED = Symbol('quota-burn-read-failed');
@@ -109,6 +124,11 @@ export default function QuotaBurn() {
const retriedRef = useRef(false);
const persistRef = useRef(null);
const savingRef = useRef(false);
+ // `save` is re-created every render and the mount effect must not re-run when
+ // it changes, so the restore path reaches it through a ref — same shape as
+ // `persistRef` above.
+ const saveRef = useRef(null);
+ const hasConfigRef = useRef(false);
// Resolves to `null` when the read landed, or to the failure message when it
// didn't. The banner state alone can't tell a caller whether THIS read failed
@@ -139,6 +159,10 @@ export default function QuotaBurn() {
// `status` is derived server-side and never edited here, so it is always
// safe to adopt; `config` is the form's own state and must not be rewound.
setStatus(data.status);
+ // Whether the page ever got a plan to merge onto. A stashed patch replayed
+ // onto `null` would render a config with no `families` and crash the plan
+ // section, so the restore waits for a read that actually answered.
+ if (data.config) hasConfigRef.current = true;
// The counter alone only catches an edit that landed WHILE this GET was in
// flight. An edit made just BEFORE it was issued leaves the counter
// unmoved, so the response — which predates the still-debounced PUT —
@@ -173,7 +197,20 @@ export default function QuotaBurn() {
}, []);
useEffect(() => {
- Promise.all([load(), loadCatalog()]).finally(() => setLoading(false));
+ Promise.all([load(), loadCatalog()]).finally(() => {
+ setLoading(false);
+ // Edits the last visit could not persist. Replaying them through `save`
+ // — rather than only re-rendering them — puts them back on screen AND
+ // re-arms the debounce, so the recovery ends in the server holding them
+ // instead of the user having to retype the field to trigger a PUT.
+ // A failed read leaves the stash alone rather than dropping it — the next
+ // visit that does get a plan is where the recovery belongs.
+ const stashed = hasConfigRef.current ? readStashedPatch() : null;
+ if (!stashed) return;
+ safeRemoveSession(UNSAVED_PATCH_KEY);
+ saveRef.current?.(stashed);
+ toast('Restored Quota Burn edits that could not be saved last time.');
+ });
}, [load, loadCatalog]);
const retryCatalog = async () => {
@@ -250,7 +287,18 @@ export default function QuotaBurn() {
// Flush, don't drop. `cancel()` alone discards everything typed in the last
// debounce window — navigating away 200ms after pasting a work prompt would
// lose it silently, with nothing on screen having said it was unsaved.
- if (pendingRef.current) api.saveQuotaBurn(pendingRef.current, { silent: true }).catch(() => {});
+ const patch = pendingRef.current;
+ if (!patch) return;
+ pendingRef.current = null;
+ api.saveQuotaBurn(patch, { silent: true })
+ // The page is gone, so there is no header indicator left to tell the
+ // truth about persistence: swallowing this failure is what turned
+ // "Saving changes…" into permanently-lost edits. Say so, and keep the
+ // patch for the next visit — the toast is transient, the work isn't.
+ .catch(() => {
+ safeWriteJsonSession(UNSAVED_PATCH_KEY, mergeQuotaBurnPatch(readStashedPatch(), patch));
+ toast.error('Quota Burn changes could not be saved — they will be restored next time you open the page.');
+ });
}, [persist]);
const save = (patch) => {
@@ -264,6 +312,8 @@ export default function QuotaBurn() {
persist();
};
+ saveRef.current = save;
+
const patchFamily = (familyId, patch) => save({ families: { [familyId]: patch } });
// Re-arm spends nothing — it only makes a spent `run once` step eligible again
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index b3472553cd..1c1692aa07 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -86,8 +86,13 @@ const renderPage = (path = '/devtools/quota-burn') => render(
</MemoryRouter>,
);
+// Mirrors UNSAVED_PATCH_KEY in the page — the session-scoped stash holding a
+// patch the server never accepted.
+const STASH_KEY = 'quotaBurn:unsavedPatch';
+
beforeEach(() => {
vi.clearAllMocks();
+ globalThis.sessionStorage.clear();
api.getQuotaBurn.mockResolvedValue({ config, status });
api.getQuotaBurnCatalog.mockResolvedValue(catalog);
api.saveQuotaBurn.mockResolvedValue({ config });
@@ -535,6 +540,56 @@ describe('QuotaBurn save races', () => {
expect(api.saveQuotaBurn.mock.calls[0][0].families.grok.jobs[0].label).toContain('Q');
});
+ it('reports a failed unmount flush and stashes the patch for the next visit', async () => {
+ // The page is gone, so no header indicator is left to say the save failed:
+ // swallowing it turned "Saving changes…" into permanently lost edits.
+ api.saveQuotaBurn.mockRejectedValue(new Error('Network request failed'));
+ const user = userEvent.setup();
+ const { unmount } = renderPage('/devtools/quota-burn/grok');
+ await user.type(await screen.findByLabelText('Name for step 1'), 'Q');
+ unmount();
+
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith(expect.stringMatching(/could not be saved/i)));
+ const stashed = JSON.parse(globalThis.sessionStorage.getItem(STASH_KEY));
+ expect(stashed.families.grok.jobs[0].label).toContain('Q');
+ });
+
+ it('restores a stashed patch on the next visit and re-saves it', async () => {
+ globalThis.sessionStorage.setItem(STASH_KEY, JSON.stringify({ checkIntervalMinutes: 45 }));
+ renderPage();
+
+ // Back on screen AND re-armed for a PUT — a restore that only re-rendered
+ // the value would leave the server holding the pre-edit plan until the
+ // user retyped the field.
+ expect(await screen.findByDisplayValue('45')).toBeInTheDocument();
+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(1));
+ expect(api.saveQuotaBurn.mock.calls[0][0].checkIntervalMinutes).toBe(45);
+ expect(globalThis.sessionStorage.getItem(STASH_KEY)).toBeNull();
+ });
+
+ it('keeps a stashed patch when the visit could not read a plan', async () => {
+ // Replaying the patch onto a page with no config would render a plan with
+ // no families; the recovery belongs on the next visit that gets one.
+ api.getQuotaBurn.mockRejectedValue(new Error('Network request failed'));
+ globalThis.sessionStorage.setItem(STASH_KEY, JSON.stringify({ checkIntervalMinutes: 45 }));
+ renderPage();
+
+ expect(await screen.findByText('Quota burn is unavailable')).toBeInTheDocument();
+ expect(globalThis.sessionStorage.getItem(STASH_KEY)).not.toBeNull();
+ expect(api.saveQuotaBurn).not.toHaveBeenCalled();
+ });
+
+ it('ignores a stash that is not a patch object', async () => {
+ // A hand-edited or older-build entry must not be replayed — the PUT body is
+ // an object, and anything else 400s the save the restore should rescue.
+ globalThis.sessionStorage.setItem(STASH_KEY, '"not-a-patch"');
+ renderPage();
+
+ expect(await screen.findByText(/62% left/)).toBeInTheDocument();
+ await sleep(100);
+ expect(api.saveQuotaBurn).not.toHaveBeenCalled();
+ });
+
it('names why the first load failed and recovers from the Retry button', async () => {
// A failed first read used to leave a bare "the server did not return a
// plan" with the header — and its Refresh — unrendered, so the only way