perf(stores): defer safeStorage writes off the interaction path (#1941)

* perf(stores): defer safeStorage writes off the interaction path

Session switches funnel every persisted store slice through safeStorage.setItem,
and doing those large JSON.stringify writes synchronously blocked the main
thread for over a second. Add a write-behind buffer that:

- Defers each setItem/removeItem to a later task via setTimeout(0) so the
  click-to-paint path is not blocked.
- Coalesces repeated writes to the same key into a single backing flush.
- Serves pending values from memory so read-after-write stays consistent
  within the deferral window.
- Flushes synchronously on pagehide/beforeunload/visibilitychange/freeze so
  deferred state survives tab close, reload, and the mobile freeze lifecycle.

Adds a test covering write deferral, coalescing, and pending read serving.

* fix(stores): defer persisted JSON serialization

* fix(stores): defer direct safeStorage writes

---------

Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
This commit is contained in:
Tom Rochette
2026-06-30 11:47:52 +03:00
committed by GitHub
co-authored by Bohdan Triapitsyn
parent 088a70fe5a
commit 1505274f94
32 changed files with 406 additions and 83 deletions
+3 -3
View File
@@ -7,7 +7,7 @@ import type {
GitLogResponse,
GitIdentitySummary,
} from '@/lib/api/types';
import { getSafeStorage } from '@/stores/utils/safeStorage';
import { getDeferredSafeStorage } from '@/stores/utils/safeStorage';
const LOG_STALE_THRESHOLD = 10000;
const REPO_CHECK_STALE_THRESHOLD = 60_000;
@@ -155,7 +155,7 @@ const GIT_BRANCH_CACHE_KEY = 'oc.gitBranchCache';
const readBranchCache = (): Record<string, GitBranch> => {
try {
const raw = getSafeStorage().getItem(GIT_BRANCH_CACHE_KEY);
const raw = getDeferredSafeStorage().getItem(GIT_BRANCH_CACHE_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw) as Record<string, GitBranch>;
return parsed && typeof parsed === 'object' ? parsed : {};
@@ -169,7 +169,7 @@ const writeCachedBranches = (directory: string, branches: GitBranch): void => {
try {
const cache = readBranchCache();
cache[directory] = branches;
getSafeStorage().setItem(GIT_BRANCH_CACHE_KEY, JSON.stringify(cache));
getDeferredSafeStorage().setItem(GIT_BRANCH_CACHE_KEY, JSON.stringify(cache));
} catch {
// quota / serialization — ignore; live fetch still refreshes the store
}