import { measureTextWrap } from '@evenrealities/pretext'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { Controller, type Snapshot } from '../../apps/even-client/src/core/controller.ts'; import { EvenDevice } from '../../apps/even-client/src/device/evenAdapter.ts'; import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts'; import { createHarness, type Harness } from './harness.ts'; /** * Leaving the glasses when idle, at the production seam: the REAL EvenDevice adapter driven by * a stand-in Even host. The bridge is real; Hermes is the test fake. No glasses are involved, * and nothing here shows what the real Even app does on `shutDownPageContainer(0)`. */ const ADAPTER_TIMEOUT_MS = 100; class FakeEvenHost { readonly durable = new Map(); /** Reads settle only when released, to hold start-up open. */ stallReads = false; private heldReads: Array<() => void> = []; /** What the next exit calls answer; 'hold' settles only on `releaseExit`. Then `true`. */ exitScript: Array = []; private heldExit: ((ok: boolean) => void) | null = null; private heldExitReject: ((err: Error) => void) | null = null; exitCalls: number[] = []; hudCreates = 0; inFlight = 0; maxInFlight = 0; private launch = new Set<(source: string) => void>(); private hub = new Set<(event: unknown) => void>(); private async track(call: () => Promise): Promise { this.inFlight += 1; this.maxInFlight = Math.max(this.maxInFlight, this.inFlight); try { return await call(); } finally { this.inFlight -= 1; } } readonly bridge = { createStartUpPageContainer: () => this.track(async () => { this.hudCreates += 1; return 0; }), textContainerUpgrade: () => this.track(async () => true), audioControl: () => this.track(async () => true), shutDownPageContainer: (mode: number) => this.track(() => { this.exitCalls.push(mode); const next = this.exitScript.shift() ?? true; if (next === 'throw') return Promise.reject(new Error('host error')); if (next === 'hold') return new Promise((resolve, reject) => { this.heldExit = resolve; this.heldExitReject = reject; }); return Promise.resolve(next); }), getLocalStorage: (key: string) => this.track( () => new Promise((resolve) => { const answer = () => resolve(this.durable.get(key) ?? ''); if (this.stallReads) this.heldReads.push(answer); else answer(); }), ), setLocalStorage: (key: string, value: string) => this.track(async () => { this.durable.set(key, value); return true; }), onEvenHubEvent: (cb: (event: unknown) => void) => { this.hub.add(cb); return () => this.hub.delete(cb); }, onDeviceStatusChanged: () => () => undefined, onLaunchSource: (cb: (source: string) => void) => { this.launch.add(cb); return () => this.launch.delete(cb); }, }; /** The host's one-shot launch-source push: delivered once, to whoever is subscribed NOW. */ pushLaunchSource(source: string): number { for (const cb of this.launch) cb(source); return this.launch.size; } releaseReads(): void { for (const answer of this.heldReads.splice(0)) answer(); } exitHeld(): boolean { return this.heldExit !== null; } releaseExit(ok: boolean): void { const resolve = this.heldExit; this.heldExit = null; resolve?.(ok); } systemExit(): void { for (const cb of this.hub) cb({ sysEvent: { eventType: 7 } }); } /** The held exit call fails with an error instead of answering. */ rejectExit(): void { const reject = this.heldExitReject; this.heldExit = null; this.heldExitReject = null; reject?.(new Error('host error')); } swipeDown(): void { for (const cb of this.hub) cb({ sysEvent: { eventType: 2 } }); } } let h: Harness; let host: FakeEvenHost; let controller: Controller; let snapshot: Snapshot; const unhandled: unknown[] = []; const onUnhandled = (reason: unknown) => unhandled.push(reason); function makeController(extra: Partial[0]> = {}): Controller { return new Controller({ device: new EvenDevice(host.bridge as never, ADAPTER_TIMEOUT_MS), measure: (text, width) => measureTextWrap(text, width).lineCount, locale: 'en-US', pollIntervalMs: 20, idleExit: { answer: 150, ready: 150, message: 100 }, exitRetryMs: 40, exitAttempts: 4, makeClient: (baseUrl, token) => new BridgeClient({ baseUrl, token, timeoutMs: 500 }), onChange: (s) => { snapshot = s; }, ...extra, }); } async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise { const deadline = Date.now() + timeoutMs; while (!predicate()) { if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase}`); await new Promise((r) => setTimeout(r, 10)); } } const quiet = (ms: number) => new Promise((r) => setTimeout(r, ms)); const logged = (text: string) => snapshot.log.filter((e) => e.detail.includes(text)).length; /** A host that already holds a pairing, as after an earlier session. Idle exit off while pairing. */ async function pairedHost(): Promise { host = new FakeEvenHost(); controller = makeController({ idleExit: null }); await controller.start(); await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'idle-exit'); await until('ready', () => snapshot.state.phase === 'ready'); await controller.stop(); // That was the earlier page, with its own adapter. Let its last host calls finish, then count // overlap from zero: the claim under test is about ONE adapter's calls. await until('earlier page is quiet', () => host.inFlight === 0); await quiet(30); host.maxInFlight = 0; } beforeEach(async () => { h = await createHarness(); unhandled.length = 0; process.on('unhandledRejection', onUnhandled); }); afterEach(async () => { vi.useRealTimers(); await controller?.stop(); await quiet(20); process.off('unhandledRejection', onUnhandled); expect(unhandled).toEqual([]); await h.close(); }); describe('the one-shot launch source is not lost during start-up', () => { it('pushed while storage is still being read and before the HUD exists: Ready is armed and the app leaves exactly once', async () => { await pairedHost(); host.stallReads = true; host.hudCreates = 0; controller = makeController(); const starting = controller.start(); await quiet(30); // Start-up is parked on the storage read; the HUD has not been created. expect(host.hudCreates).toBe(0); // The host pushes its one-shot event now. Someone must already be listening. expect(host.pushLaunchSource('glassesMenu')).toBeGreaterThan(0); await quiet(30); host.stallReads = false; host.releaseReads(); await starting; await until('ready', () => snapshot.state.phase === 'ready'); expect(snapshot.launchSource).toBe('glassesMenu'); expect(host.exitCalls).toEqual([]); await until('left the glasses', () => logged('left the glasses') === 1, 2000); await quiet(400); expect(host.exitCalls).toEqual([0]); // one call, immediate mode expect(host.maxInFlight).toBe(1); }); it('with no launch source and no gesture at all, the same start-up still leaves, once', async () => { await pairedHost(); controller = makeController(); await controller.start(); await until('ready', () => snapshot.state.phase === 'ready'); await until('left the glasses', () => logged('left the glasses') === 1, 2000); await quiet(400); expect(host.exitCalls).toEqual([0]); }); }); describe('an exit the host does not complete', () => { async function launchedFromGlasses(): Promise { await pairedHost(); controller = makeController(); host.pushLaunchSource('glassesMenu'); await controller.start(); await until('ready', () => snapshot.state.phase === 'ready'); } it('answered false, then true: a second call is made, and only then is it final', async () => { host = new FakeEvenHost(); await launchedFromGlasses(); host.exitScript = [false]; await until('left the glasses', () => logged('left the glasses') === 1, 2000); expect(host.exitCalls).toEqual([0, 0]); expect(logged('did not confirm leaving; will try again')).toBe(1); await quiet(400); expect(host.exitCalls).toEqual([0, 0]); expect(host.maxInFlight).toBe(1); }); it('a host call that throws is treated the same way, with no unhandled rejection', async () => { await launchedFromGlasses(); host.exitScript = ['throw']; await until('left the glasses', () => logged('left the glasses') === 1, 2000); expect(host.exitCalls).toEqual([0, 0]); expect(host.maxInFlight).toBe(1); }); it('no answer in time, then a late success: one host call ever, never two in flight, and it ends as left', async () => { await launchedFromGlasses(); host.exitScript = ['hold']; await until('the exit is with the host', () => host.exitHeld()); // Longer than the adapter's wait plus a retry: the controller has asked again by now. await until('a retry was scheduled', () => logged('will try again') >= 1, 2000); await quiet(ADAPTER_TIMEOUT_MS); expect(host.exitCalls).toEqual([0]); // the retry waited on the same call expect(host.inFlight).toBe(1); host.releaseExit(true); await until('left the glasses', () => logged('left the glasses') === 1, 2000); await quiet(400); expect(host.exitCalls).toEqual([0]); expect(host.maxInFlight).toBe(1); }); it('the host answers only after every attempt has run out: still one call, and no exit is sent afterwards', async () => { await launchedFromGlasses(); host.exitScript = ['hold']; await until('gave up for now', () => logged('staying until the next activity') === 1, 4000); expect(host.exitCalls).toEqual([0]); host.releaseExit(true); // the Even app finally acts on it await quiet(50); host.swipeDown(); // activity re-arms the countdown; the adapter knows it already left await until('recorded as left', () => logged('left the glasses') === 1, 2000); await quiet(300); expect(host.exitCalls).toEqual([0]); expect(host.maxInFlight).toBe(1); }); it('no answer, then a late refusal: a fresh call follows it, in order', async () => { await launchedFromGlasses(); host.exitScript = ['hold']; await until('the exit is with the host', () => host.exitHeld()); await quiet(ADAPTER_TIMEOUT_MS + 30); host.releaseExit(false); await until('left the glasses', () => logged('left the glasses') === 1, 2000); expect(host.exitCalls).toEqual([0, 0]); expect(host.maxInFlight).toBe(1); }); }); /** * The DEFAULT times, under fake time, with the production adapter. Only the clock and the timers * are faked; the bridge calls made during start-up are real and are awaited as promises. */ describe('default idle times with the production adapter (fake clock)', () => { const fakeClock = () => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] }); const defaults = () => makeController({ idleExit: {}, exitRetryMs: undefined as never, exitAttempts: undefined as never }); async function expectOneExitAtThirtySeconds(): Promise { await vi.advanceTimersByTimeAsync(29_900); expect(host.exitCalls).toEqual([]); await vi.advanceTimersByTimeAsync(200); expect(host.exitCalls).toEqual([0]); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([0]); // exactly once, however long it is left expect(logged('left the glasses')).toBe(1); expect(host.maxInFlight).toBe(1); } it('glassesMenu pushed BEFORE the controller starts: one exit, 30 s after Ready', async () => { await pairedHost(); fakeClock(); controller = defaults(); expect(host.pushLaunchSource('glassesMenu')).toBeGreaterThan(0); // the adapter is already listening await controller.start(); expect(snapshot.state.phase).toBe('ready'); await expectOneExitAtThirtySeconds(); }); it('glassesMenu pushed AFTER the controller subscribed: still one exit, 30 s after Ready', async () => { await pairedHost(); fakeClock(); controller = defaults(); await controller.start(); await vi.advanceTimersByTimeAsync(10_000); host.pushLaunchSource('glassesMenu'); // arrives late: it must not restart or double the countdown await vi.advanceTimersByTimeAsync(19_900); expect(host.exitCalls).toEqual([]); await vi.advanceTimersByTimeAsync(200); expect(host.exitCalls).toEqual([0]); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([0]); }); it('NO launch source is ever pushed (seen on a real G2 voice launch): one exit, 30 s after Ready', async () => { await pairedHost(); fakeClock(); controller = defaults(); await controller.start(); expect(snapshot.launchSource).toBe('unknown'); await expectOneExitAtThirtySeconds(); }); it('appMenu pushed early: opened from the phone app, it leaves the same way', async () => { await pairedHost(); fakeClock(); controller = defaults(); host.pushLaunchSource('appMenu'); await controller.start(); expect(snapshot.launchSource).toBe('appMenu'); await expectOneExitAtThirtySeconds(); }); it('opened and then the phone page is touched: the full two-minute grace, then 30 s', async () => { await pairedHost(); fakeClock(); controller = defaults(); await controller.start(); await vi.advanceTimersByTimeAsync(5_000); controller.notePhoneActivity(); await vi.advanceTimersByTimeAsync(149_500); expect(host.exitCalls).toEqual([]); await vi.advanceTimersByTimeAsync(1_000); expect(host.exitCalls).toEqual([0]); }); it('never paired: nothing leaves, however long it is left', async () => { host = new FakeEvenHost(); fakeClock(); controller = defaults(); host.pushLaunchSource('glassesMenu'); await controller.start(); expect(snapshot.state.phase).toBe('unpaired'); host.swipeDown(); await vi.advanceTimersByTimeAsync(30 * 60_000); expect(host.exitCalls).toEqual([]); }); it('unsubscribing is preserved: a stopped controller no longer hears the launch source', async () => { await pairedHost(); fakeClock(); controller = defaults(); await controller.start(); await controller.stop(); host.pushLaunchSource('glassesMenu'); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([]); }); it('a real exit event from the glasses is final: no idle exit follows it', async () => { await pairedHost(); fakeClock(); controller = defaults(); host.pushLaunchSource('glassesMenu'); await controller.start(); await vi.advanceTimersByTimeAsync(10_000); host.systemExit(); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([]); }); it('default retry: refused, then thrown, then no answer, then confirmed, one call at a time', async () => { await pairedHost(); fakeClock(); controller = defaults(); host.pushLaunchSource('glassesMenu'); host.exitScript = [false, 'throw', 'hold']; await controller.start(); await vi.advanceTimersByTimeAsync(30_100); expect(host.exitCalls).toEqual([0]); // refused await vi.advanceTimersByTimeAsync(3_100); expect(host.exitCalls).toEqual([0, 0]); // threw await vi.advanceTimersByTimeAsync(3_100); expect(host.exitCalls).toEqual([0, 0, 0]); // held by the host await vi.advanceTimersByTimeAsync(1_000); // The wait for an answer has run out and a retry is pending; no second call is in flight. expect(logged('will try again')).toBe(3); expect(host.exitCalls).toEqual([0, 0, 0]); expect(host.inFlight).toBe(1); host.releaseExit(true); // the host finally acts on the call it was holding await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([0, 0, 0]); expect(logged('left the glasses')).toBe(1); expect(host.maxInFlight).toBe(1); }); }); /** * CODY-019. Activity that arrives while an exit call is still with the host restarts the full * countdown (or the phone grace period). When that call then fails, its short retry must not * replace the restarted timer. Default times, fake clock, production adapter. */ describe('activity during a pending exit keeps its full countdown (CODY-019)', () => { const fakeClock = () => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] }); /** Launched from the glasses, idle for 30 s: the first exit call is now held by the host. */ async function firstExitHeld(): Promise { await pairedHost(); fakeClock(); controller = makeController({ idleExit: {}, exitRetryMs: undefined as never, exitAttempts: undefined as never }); host.pushLaunchSource('glassesMenu'); host.exitScript = ['hold']; await controller.start(); await vi.advanceTimersByTimeAsync(30_050); expect(host.exitCalls).toEqual([0]); expect(host.exitHeld()).toBe(true); } /** From the activity: nothing for the full 30 s, then one more call, which succeeds. */ async function fullCountdownThenLeaves(expectedCalls: number): Promise { const before = host.exitCalls.length; await vi.advanceTimersByTimeAsync(29_800); // 3 s retry would have fired long ago expect(host.exitCalls.length).toBe(before); expect(logged('left the glasses')).toBe(0); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls.length).toBe(expectedCalls); expect(logged('left the glasses')).toBe(1); expect(host.maxInFlight).toBe(1); } it('a swipe at Ready (no state change), then the host answers false', async () => { await firstExitHeld(); const generation = snapshot.state.generation; host.swipeDown(); expect(snapshot.state.generation).toBe(generation); // the gesture changed no state host.releaseExit(false); await fullCountdownThenLeaves(2); }); it('a swipe at Ready, then the host call fails with an error', async () => { await firstExitHeld(); host.swipeDown(); host.rejectExit(); await fullCountdownThenLeaves(2); }); it('a swipe at Ready, then the host never answers in time; its late success is still final', async () => { await firstExitHeld(); host.swipeDown(); await vi.advanceTimersByTimeAsync(ADAPTER_TIMEOUT_MS + 50); // the wait for an answer runs out expect(logged('will try again')).toBe(0); // no short retry was scheduled over the swipe's countdown await vi.advanceTimersByTimeAsync(29_700); expect(host.exitCalls).toEqual([0]); // The full countdown from the swipe ends; the retry waits on the SAME held call. await vi.advanceTimersByTimeAsync(400); expect(host.exitCalls).toEqual([0]); expect(host.inFlight).toBe(1); host.releaseExit(true); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([0]); // one host call ever expect(logged('left the glasses')).toBe(1); expect(host.maxInFlight).toBe(1); }); it('a touch on the phone page, then the host answers false: the whole grace period stands', async () => { await firstExitHeld(); controller.notePhoneActivity(); host.releaseExit(false); // Grace is 120 s, then the 30 s Ready wait: nothing before 150 s from the touch. await vi.advanceTimersByTimeAsync(149_500); expect(host.exitCalls).toEqual([0]); expect(logged('left the glasses')).toBe(0); await vi.advanceTimersByTimeAsync(1_000); expect(host.exitCalls).toEqual([0, 0]); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([0, 0]); expect(logged('left the glasses')).toBe(1); expect(host.maxInFlight).toBe(1); }); it('after such activity the attempts are still bounded: a host that keeps refusing gets four, then none', async () => { await firstExitHeld(); host.swipeDown(); host.exitScript = [false, false, false, false, false, false]; host.releaseExit(false); await vi.advanceTimersByTimeAsync(10 * 60_000); expect(host.exitCalls).toEqual([0, 0, 0, 0, 0]); // the one overtaken by the swipe, then four expect(logged('staying until the next activity')).toBe(1); expect(host.maxInFlight).toBe(1); }); it('control: with no activity, the same refusal IS retried after 3 s', async () => { await firstExitHeld(); host.releaseExit(false); await vi.advanceTimersByTimeAsync(3_100); expect(host.exitCalls).toEqual([0, 0]); expect(logged('left the glasses')).toBe(1); }); });