import { describe, expect, it, vi } from 'vitest' import { withBootstrapAwareTimeout, withTimeout } from './with-timeout' describe('withTimeout', () => { it('allows a full cold start when installation finishes near a deadline', async () => { vi.useFakeTimers() try { let active = true let finish!: (value: string) => void const connection = new Promise(resolve => { finish = resolve }) const result = withBootstrapAwareTimeout(connection, 45_000, 'timeout', async () => ({ active })) await vi.advanceTimersByTimeAsync(75_000) active = false await vi.advanceTimersByTimeAsync(25_000) finish('connected') await expect(result).resolves.toBe('connected') } finally { vi.useRealTimers() } }) it.each([{ active: true }, { setupChoice: { active: true } }])( 'waits beyond cold boot during setup: %j', async state => { vi.useFakeTimers() try { let finish!: (value: string) => void const connection = new Promise(resolve => { finish = resolve }) const probe = vi.fn(async () => state) const result = withBootstrapAwareTimeout(connection, 45_000, 'timeout', probe) await vi.advanceTimersByTimeAsync(180_000) expect(probe).toHaveBeenCalledTimes(4) finish('connected') await expect(result).resolves.toBe('connected') } finally { vi.useRealTimers() } } ) it('keeps an ordinary stalled backend bounded', async () => { vi.useFakeTimers() try { const result = withBootstrapAwareTimeout(new Promise(() => {}), 45_000, 'timeout', async () => ({ active: false })) const rejection = expect(result).rejects.toThrow('timeout') await vi.advanceTimersByTimeAsync(45_000) await rejection } finally { vi.useRealTimers() } }) it('bounds a stalled bootstrap IPC probe', async () => { vi.useFakeTimers() try { const result = withBootstrapAwareTimeout( new Promise(() => {}), 45_000, 'timeout', () => new Promise(() => {}) ) const rejection = expect(result).rejects.toThrow('timeout') await vi.advanceTimersByTimeAsync(50_000) await rejection } finally { vi.useRealTimers() } }) it('propagates a real backend failure during setup', async () => { const failure = new Error('runtime install failed') await expect( withBootstrapAwareTimeout(Promise.reject(failure), 45_000, 'timeout', async () => ({ active: true })) ).rejects.toBe(failure) }) it('rejects with an onTimeout exception instead of letting it escape the timer callback', async () => { vi.useFakeTimers() try { const callbackFailure = new Error('abort callback failed') const result = withTimeout(new Promise(() => undefined), 10, 'work timed out', () => { throw callbackFailure }) const rejection = expect(result).rejects.toBe(callbackFailure) await vi.advanceTimersByTimeAsync(10) await rejection } finally { vi.useRealTimers() } }) })