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.
This commit is contained in:
Junmo Kim
2026-11-05 16:36:36 +08:00
committed by GitHub
parent 6712e19dfa
commit 003f5237db
2 changed files with 67 additions and 2 deletions
+31
View File
@@ -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)
+36 -2
View File
@@ -15,11 +15,45 @@ let running = false
let retry: ReturnType<typeof setTimeout> | undefined
const tailFollowers = new Map<string, number>()
// 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