CODY-016, 017, 018: launch source cannot be missed; a failed idle exit is retried

CODY-016. The SDK pushes the launch source once, early. The Even adapter now
subscribes in its constructor, remembers the value and replays it to a
listener that subscribes later. appMenu still does not arm idle exit.

CODY-018. exitNow() returns whether the host confirmed. The adapter keeps at
most one shutdown call in flight (through the same queue as every other host
call), lets a repeat request wait on that call, and never calls the host
again after a confirmed exit, including one confirmed late. The controller
marks itself as gone only on confirmation or on a system_exit/abnormal_exit
event; otherwise it retries after 3 s, at most 4 attempts in a row, under the
same resting-screen and phone-grace guards, and starts again after activity.

CODY-017. README: one owner-reported locked-phone success; pocketed,
five-minute and ten-cycle runs unverified.

Tests: production-adapter tests with a stand-in host, including the default
30 s under a fake clock; a simulator scenario that performs the real exit
(development-only ?idleExit=fast). Not reviewed. 0.1.1 is not uploaded.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-21 14:38:29 -08:00
co-authored by Claude Fable 5.2
parent 1ae105ed18
commit bbde3c86a8
12 changed files with 679 additions and 42 deletions
+67
View File
@@ -707,6 +707,73 @@ describe('leaving the glasses when idle (the app blocks notifications while it i
expect(snapshot.log.some((e) => e.detail.includes('leaving the glasses: idle on answer'))).toBe(true);
});
it('an exit the host does not confirm is tried again, and a confirmed one is final', async () => {
controllerExtras = { idleExit: FAST, exitRetryMs: 60, exitAttempts: 4 };
await pairedController();
device.exitResults = [false, false];
device.launchedFrom('glassesMenu');
await until('left on the third attempt', () => device.exits === 1, 2000);
expect(device.exitAttempts).toBe(3);
await quiet(400);
expect(device.exitAttempts).toBe(3);
expect(snapshot.log.some((e) => e.detail === 'left the glasses')).toBe(true);
});
it('a host that keeps refusing is asked a bounded number of times, then again only after activity', async () => {
controllerExtras = { idleExit: FAST, exitRetryMs: 40, exitAttempts: 3 };
await pairedController();
device.exitResults = Array.from({ length: 10 }, () => false);
device.launchedFrom('glassesMenu');
await until('three attempts', () => device.exitAttempts === 3, 2000);
await quiet(500);
expect(device.exitAttempts).toBe(3);
expect(device.exits).toBe(0);
// A gesture is activity: the countdown and the attempts start again, and the app still works.
device.exitResults = [];
device.swipeDown();
await until('left after the next idle period', () => device.exits === 1, 2000);
expect(device.exitAttempts).toBe(4);
});
it('never leaves while a request is outstanding and the bridge cannot be reached', async () => {
controllerExtras = { idleExit: FAST };
await pairedController();
device.launchedFrom('glassesMenu');
h.hermes.next({ kind: 'complete', afterMs: 300, output: 'worth the wait' });
controller.askText('q');
await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1);
network.down = true;
await until('disconnected', () => phase() === 'disconnected');
await quiet(600); // four timeouts' worth
expect(phase()).toBe('disconnected');
expect(device.exitAttempts).toBe(0);
network.down = false;
await until('answer', () => phase() === 'answer');
await until('left once the answer had been shown and left alone', () => device.exits === 1, 2000);
});
it('once the glasses report the app closed, no idle exit is sent, and a failed one is not retried', async () => {
controllerExtras = { idleExit: FAST, exitRetryMs: 60, exitAttempts: 4 };
await pairedController();
device.launchedFrom('glassesMenu');
device.emit({ type: 'system_exit' });
await quiet(600);
expect(device.exitAttempts).toBe(0);
await controller.stop();
const stored = device.storage;
device = new FakeDevice();
for (const [k, v] of stored) device.storage.set(k, v);
controller = makeController(device);
await controller.start();
device.exitResults = Array.from({ length: 10 }, () => false);
device.launchedFrom('glassesMenu');
await until('first attempt refused', () => device.exitAttempts === 1, 2000);
device.emit({ type: 'abnormal_exit' });
await quiet(600);
expect(device.exitAttempts).toBe(1);
});
it('paging, or any gesture, restarts the countdown', async () => {
controllerExtras = { idleExit: FAST };
await pairedController();
+28
View File
@@ -126,6 +126,7 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends
shutDownPageContainer: (...a: unknown[]) => call('exit', a),
getLocalStorage: (...a: unknown[]) => call('get', a),
setLocalStorage: (...a: unknown[]) => call('set', a),
onLaunchSource: () => () => undefined,
};
return { bridge, calls, micOpen: () => micOpen, maxInFlight: () => maxInFlight, pending: () => calls.filter((c) => !c.settled) };
}
@@ -165,6 +166,33 @@ describe('CODY-002: host calls stay serialised and a late microphone start ends
expect(host.pending()).toEqual([]);
});
it('an idle exit waits its turn behind a host call that is still in flight, and is asked only once', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
const writing = device.storageSet('k', 'v');
await tick();
const leaving = device.exitNow();
const leavingAgain = device.exitNow();
await tick();
// The write has not settled: the exit has not been sent.
expect(host.calls.map((c) => c.name)).toEqual(['set']);
host.pending()[0]!.resolve(true);
await tick();
expect(await writing).toBe(true);
expect(host.calls.map((c) => c.name)).toEqual(['set', 'exit']);
expect(host.calls[1]!.args).toEqual([0]); // immediate mode, no dialog
host.pending()[0]!.resolve(true);
await tick();
expect(await leaving).toBe(true);
expect(await leavingAgain).toBe(true);
// Confirmed: nothing further is ever sent for an exit.
expect(await device.exitNow()).toBe(true);
expect(host.calls.map((c) => c.name)).toEqual(['set', 'exit']);
expect(host.maxInFlight()).toBe(1);
});
it('a stop requested while the start is still pending waits its turn and still leaves the microphone closed', async () => {
const host = fakeHost();
const device = new EvenDevice(host.bridge as never);
+375
View File
@@ -0,0 +1,375 @@
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<string, string>();
/** 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<boolean | 'hold' | 'throw'> = [];
private heldExit: ((ok: boolean) => 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<T>(call: () => Promise<T>): Promise<T> {
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<boolean>((resolve) => (this.heldExit = resolve));
return Promise.resolve(next);
}),
getLocalStorage: (key: string) =>
this.track(
() =>
new Promise<string>((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 } });
}
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<ConstructorParameters<typeof Controller>[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<void> {
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<void> {
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('control: with no launch source and no gesture, the same start-up does not leave', async () => {
await pairedHost();
controller = makeController();
await controller.start();
await until('ready', () => snapshot.state.phase === 'ready');
await quiet(500);
expect(host.exitCalls).toEqual([]);
});
});
describe('an exit the host does not complete', () => {
async function launchedFromGlasses(): Promise<void> {
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<void> {
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: one exit, 30 s later', async () => {
await pairedHost();
fakeClock();
controller = defaults();
await controller.start();
await vi.advanceTimersByTimeAsync(5 * 60_000);
expect(host.exitCalls).toEqual([]); // nothing has said the glasses are in use
host.pushLaunchSource('glassesMenu');
await expectOneExitAtThirtySeconds();
});
it('appMenu pushed early does not arm it; the first glasses gesture does', async () => {
await pairedHost();
fakeClock();
controller = defaults();
host.pushLaunchSource('appMenu');
await controller.start();
expect(snapshot.launchSource).toBe('appMenu');
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(host.exitCalls).toEqual([]);
host.swipeDown();
await expectOneExitAtThirtySeconds();
});
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);
});
});