fix: persist autoRestoreRan on globalThis to survive Vite HMR (BUG-F7)

Module re-evaluation during HMR reset autoRestoreRan to false, causing
duplicate auth-restore API calls. Now persists flag on globalThis.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Dorian
2026-03-13 00:09:20 +00:00
co-authored by Claude Opus 4.6
parent 1c296c6f1c
commit c288b23c13
2 changed files with 36 additions and 4 deletions
@@ -128,4 +128,34 @@ describe('useNostr', () => {
expect(result).toBe(false)
vi.useRealTimers()
})
it('BUG-F7: autoRestoreRan survives module re-import (HMR)', async () => {
// Set up conditions that trigger auto-restore: pubkey stored, no bot, valid JWT
localStorage.setItem('bf_pubkey', JSON.stringify('a'.repeat(64)))
mockGetToken.mockReturnValue('valid-jwt')
mockIsTokenExpired.mockReturnValue(false)
mockAuthFetch.mockResolvedValue({ json: () => Promise.resolve({ exists: true, bot: { id: 'b1', name: 'Bot' } }) })
// Clear globalThis flag
delete (globalThis as any).__bf_autoRestoreRan
// First import triggers auto-restore
vi.resetModules()
await import('../useNostr')
await new Promise(r => setTimeout(r, 0)) // flush microtasks
expect(mockAuthFetch).toHaveBeenCalledTimes(1)
// globalThis flag should be set
expect((globalThis as any).__bf_autoRestoreRan).toBe(true)
// Second import (simulating HMR) should NOT trigger auto-restore again
vi.resetModules()
mockAuthFetch.mockClear()
await import('../useNostr')
await new Promise(r => setTimeout(r, 0))
expect(mockAuthFetch).not.toHaveBeenCalled()
// Clean up
delete (globalThis as any).__bf_autoRestoreRan
})
})