From 003f5237db8cfa8226ade7eb68fa9601a6eba345 Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Thu, 5 Nov 2026 17:36:36 +0900 Subject: [PATCH] fix(web): avoid re-parsing session read state for every sidebar row (#2290) The session list asks for read state once per row on each render, and each call re-read and re-parsed the whole persisted store. With about 1.7k sessions that kept the main thread busy for tens of seconds when loading the list or opening a session. Keep the parsed store and compare it with the raw stored value on the first read after a microtask checkpoint, then trust it for the rest of that synchronous pass. localStorage stays the source of truth, so writes from other tabs or code are picked up by the next read after the checkpoint. If a save fails the cached copy is dropped so unsaved changes are not kept. --- web/src/lib/sessionLastSeen.test.ts | 31 +++++++++++++++++++++++ web/src/lib/sessionLastSeen.ts | 38 +++++++++++++++++++++++++++-- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/web/src/lib/sessionLastSeen.test.ts b/web/src/lib/sessionLastSeen.test.ts index c1f0aa3f..8c6b2d51 100644 --- a/web/src/lib/sessionLastSeen.test.ts +++ b/web/src/lib/sessionLastSeen.test.ts @@ -19,6 +19,37 @@ beforeEach(() => { afterEach(async () => { cleanup(); await vi.advanceTimersByTimeAsync(0); vi.useRealTimers(); vi.restoreAllMocks() }) describe('durable session read state', () => { + it('reads persisted state once per synchronous pass instead of once per row', async () => { + markSessionSeen('s', 2) + await Promise.resolve() + const parse = vi.spyOn(JSON, 'parse') + const getItem = vi.spyOn(Storage.prototype, 'getItem') + for (let i = 0; i < 500; i += 1) { + getSessionLastSeenAt('s') + getSessionManualUnreadAt('s') + } + expect(parse).not.toHaveBeenCalled() + expect(getItem).toHaveBeenCalledTimes(1) + expect(getSessionLastSeenAt('s')).toBe(2) + }) + + it('observes writes from other tabs or code after the next microtask checkpoint', async () => { + markSessionSeen('s', 2) + localStorage.setItem('hapi.sessionReadState.v1:hub-a:alice', JSON.stringify({ s: { server: server(7) } })) + await Promise.resolve() + expect(getSessionLastSeenAt('s')).toBe(7) + localStorage.clear() + await Promise.resolve() + expect(getSessionLastSeenAt('s')).toBe(0) + }) + + it('does not keep an unsaved mutation when persistence fails', () => { + markSessionSeen('s', 2) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + markSessionSeen('s', 9) + expect(getSessionLastSeenAt('s')).toBe(2) + }) + it('ignores legacy timestamps and metadata-only changes', () => { localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({ s: Date.now() })) expect(getSessionLastSeenAt('s')).toBe(0) diff --git a/web/src/lib/sessionLastSeen.ts b/web/src/lib/sessionLastSeen.ts index f5ad733e..a80e50b2 100644 --- a/web/src/lib/sessionLastSeen.ts +++ b/web/src/lib/sessionLastSeen.ts @@ -15,11 +15,45 @@ let running = false let retry: ReturnType | undefined const tailFollowers = new Map() +// The sidebar reads per-session state for every row on every render, and reading +// (let alone parsing) the whole persisted store per row is O(rows x store size). +// localStorage stays the source of truth: the parsed copy is compared with the raw +// stored value on the first read after a microtask checkpoint and trusted for the +// rest of that synchronous pass, so writes from other tabs or other code are +// observed by the next read after the checkpoint. +let cache: { key: string; raw: string | null; store: Store } | null = null +let trusted = false +function trustUntilNextCheckpoint(): void { + if (trusted) return + trusted = true + queueMicrotask(() => { trusted = false }) +} function readStore(key = scope): Store { - try { return JSON.parse(localStorage.getItem(PREFIX + key) ?? '{}') as Store } catch { return {} } + if (trusted && cache?.key === key) return cache.store + let raw: string | null + try { raw = localStorage.getItem(PREFIX + key) } catch { return {} } + if (cache?.key !== key || cache.raw !== raw) { + let store: Store + try { store = JSON.parse(raw ?? '{}') as Store } catch { store = {} } + cache = { key, raw, store } + } + trustUntilNextCheckpoint() + return cache.store } function save(store: Store, key = scope): boolean { - try { localStorage.setItem(PREFIX + key, JSON.stringify(store)); return true } catch { return false } + try { + const raw = JSON.stringify(store) + localStorage.setItem(PREFIX + key, raw) + cache = { key, raw, store } + trustUntilNextCheckpoint() + return true + } catch { + // Callers mutate the cached store before saving; drop it so the next + // read reflects what is actually persisted. + cache = null + trusted = false + return false + } } function notify(): void { changeVersion += 1