import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { get } from 'svelte/store'; import type { FleetOperation } from '../../src/lib/fleet-overview.js'; vi.mock('$app/environment', () => ({ browser: true })); let documentStub: EventTarget & { visibilityState: string }; let stop: (() => void) | undefined; const changed = () => window.dispatchEvent(new Event('ec:fleet-changed')); const visibility = (state: string) => { documentStub.visibilityState = state; documentStub.dispatchEvent(new Event('visibilitychange')); }; const response = (url: string) => Response.json( url === '/api/servers' ? { serverNow: Date.now(), servers: [], integrations: {} } : { operations: [] } ); beforeEach(() => { vi.resetModules(); vi.useFakeTimers(); vi.setSystemTime(new Date('2026-10-05T12:00:00Z')); documentStub = Object.assign(new EventTarget(), { visibilityState: 'visible' }); vi.stubGlobal('document', documentStub); vi.stubGlobal('window', new EventTarget()); vi.stubGlobal( 'fetch', vi.fn(async (url: string) => response(url)) ); }); afterEach(() => { stop?.(); stop = undefined; vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); async function setup() { const store = await import('../../src/lib/ui/stores/fleet.js'); store.fleet.set({ servers: [], operations: [], receivedAt: Date.now() }); stop = store.startFleetMonitor(); return store; } describe('fleet event refreshes', () => { it('hydrates and refreshes the all-host attention count without an additional request', async () => { const store = await import('../../src/lib/ui/stores/fleet.js'); const integrations = { rcon: true, rconTimeoutMs: 2000, defaultRconHost: '' }; store.hydrateFleet({ servers: [], operations: [], integrations, serverNow: Date.now(), hostAttention: 2 }); expect(get(store.fleet).hostAttention).toBe(2); vi.mocked(fetch).mockImplementation(async (url) => Response.json( String(url) === '/api/servers' ? { serverNow: Date.now(), servers: [], integrations, hostAttention: 0 } : { operations: [] } ) ); await store.refreshFleet(); expect(get(store.fleet).hostAttention).toBe(0); expect(fetch).toHaveBeenCalledTimes(2); expect( vi .mocked(fetch) .mock.calls.map(([url]) => url) .sort() ).toEqual(['/api/fleet', '/api/servers']); }); it('refreshes server history through one scoped request without replacing the fleet snapshot', async () => { const store = await import('../../src/lib/ui/stores/fleet.js'); const integrations = { rcon: true, rconTimeoutMs: 2000, defaultRconHost: '' }; const snapshot = { servers: [], operations: [], integrations, serverNow: Date.now() }; store.hydrateFleet(snapshot); const originalFleet = get(store.fleet); const detail = store.createFleetStore('one / two'); detail.hydrateFleet(snapshot); stop = detail.startFleetMonitor(); const history: FleetOperation[] = [ { key: 'deployment:done', group: 'deployment:done', kind: 'deployment', server: 'one / two', state: 'done', label: 'Complete', detail: 'Complete', href: '/provisioning/done', startedAt: new Date().toISOString() } ]; vi.mocked(fetch).mockResolvedValue(Response.json({ ...snapshot, operations: history })); changed(); await vi.advanceTimersByTimeAsync(250); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith('/api/servers/one%20%2F%20two', expect.anything()); expect(get(detail.fleet).operations).toEqual(history); expect(get(store.fleet)).toBe(originalFleet); expect(get(store.fleet).operations).toEqual([]); }); it('isolates late responses when navigating between server detail stores', async () => { const { createFleetStore, fleet } = await import('../../src/lib/ui/stores/fleet.js'); const first = createFleetStore('first'); const second = createFleetStore('second'); let finish!: (response: Response) => void; vi.mocked(fetch).mockImplementationOnce( () => new Promise((resolve) => { finish = resolve; }) ); const oldRequest = first.refreshFleet(); const newSnapshot = { serverNow: Date.now(), servers: [], integrations: {}, operations: [] }; vi.mocked(fetch).mockResolvedValue(Response.json(newSnapshot)); await second.refreshFleet(); const current = get(second.fleet); finish(Response.json(newSnapshot)); await oldRequest; expect(get(second.fleet)).toBe(current); expect(get(fleet).receivedAt).toBe(0); expect(fetch).toHaveBeenCalledTimes(2); }); it('coalesces bursts and refreshes at most once every two seconds with a trailing refresh', async () => { await setup(); changed(); changed(); changed(); await vi.advanceTimersByTimeAsync(249); expect(fetch).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(1); expect(fetch).toHaveBeenCalledTimes(2); for (let i = 0; i < 7; i++) { changed(); await vi.advanceTimersByTimeAsync(250); expect(fetch).toHaveBeenCalledTimes(2); } await vi.advanceTimersByTimeAsync(250); expect(fetch).toHaveBeenCalledTimes(4); changed(); await vi.advanceTimersByTimeAsync(2000); expect(fetch).toHaveBeenCalledTimes(6); await vi.advanceTimersByTimeAsync(5000); expect(fetch).toHaveBeenCalledTimes(6); }); it('keeps events during a request without an immediate follow-up when it finishes', async () => { await setup(); let finish!: () => void; const gate = new Promise((resolve) => { finish = resolve; }); vi.mocked(fetch).mockImplementation(async (url) => { await gate; return response(String(url)); }); changed(); await vi.advanceTimersByTimeAsync(250); expect(fetch).toHaveBeenCalledTimes(2); changed(); changed(); await vi.advanceTimersByTimeAsync(500); finish(); await vi.advanceTimersByTimeAsync(1499); expect(fetch).toHaveBeenCalledTimes(2); await vi.advanceTimersByTimeAsync(1); expect(fetch).toHaveBeenCalledTimes(4); }); it('waits for a slow manual refresh and coalesces events arriving during it', async () => { const { refreshFleet } = await setup(); let finish!: () => void; const gate = new Promise((resolve) => { finish = resolve; }); vi.mocked(fetch).mockImplementation(async (url) => { await gate; return response(String(url)); }); const manual = refreshFleet(); changed(); await vi.advanceTimersByTimeAsync(3000); changed(); changed(); expect(fetch).toHaveBeenCalledTimes(2); finish(); await manual; await vi.advanceTimersByTimeAsync(0); expect(fetch).toHaveBeenCalledTimes(4); await vi.advanceTimersByTimeAsync(3000); expect(fetch).toHaveBeenCalledTimes(4); }); it('skips queued refreshes while hidden, refreshes on return, and cancels on stop', async () => { await setup(); changed(); visibility('hidden'); await vi.advanceTimersByTimeAsync(250); changed(); await vi.advanceTimersByTimeAsync(3000); expect(fetch).not.toHaveBeenCalled(); visibility('visible'); await vi.advanceTimersByTimeAsync(0); expect(fetch).toHaveBeenCalledTimes(2); changed(); stop!(); await vi.advanceTimersByTimeAsync(3000); expect(fetch).toHaveBeenCalledTimes(2); }); it('cancels a follow-up waiting for an active request when stopped', async () => { const { refreshFleet } = await setup(); let finish!: () => void; const gate = new Promise((resolve) => { finish = resolve; }); vi.mocked(fetch).mockImplementation(async (url) => { await gate; return response(String(url)); }); const manual = refreshFleet(); changed(); await vi.advanceTimersByTimeAsync(250); stop!(); finish(); await manual; await vi.advanceTimersByTimeAsync(3000); expect(fetch).toHaveBeenCalledTimes(2); }); });